python-codex 0.6.3__py3-none-any.whl → 0.7.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.
- pycodex/agent.py +325 -321
- pycodex/config.py +19 -2
- pycodex/context.py +24 -9
- pycodex/events.py +127 -7
- pycodex/model.py +269 -95
- pycodex/multi_agents.py +13 -42
- pycodex/prompts/models.json +8 -8
- pycodex/protocol.py +4 -2
- pycodex/runtime.py +227 -131
- pycodex/tools/__init__.py +3 -3
- pycodex/tools/clock_manager.py +0 -7
- pycodex/tools/exec_command_tool.py +16 -5
- pycodex/tools/exec_runtime.py +5 -1
- pycodex/tools/goal_manager.py +25 -32
- pycodex/tools/runtime_services.py +21 -11
- pycodex/tools/unified_exec_manager.py +46 -3
- pycodex/utils/compactor.py +28 -101
- pycodex/utils/compat.py +6 -0
- pycodex/utils/event_helpers.py +47 -0
- pycodex/utils/history.py +22 -7
- pycodex/utils/model_metadata.py +5 -4
- pycodex/utils/session_persist.py +6 -2
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/METADATA +40 -13
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/RECORD +30 -30
- responses_server/app.py +4 -0
- responses_server/gemini_api.py +26 -7
- responses_server/transport.py +12 -5
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/WHEEL +0 -0
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/licenses/LICENSE +0 -0
pycodex/tools/goal_manager.py
CHANGED
|
@@ -3,14 +3,6 @@
|
|
|
3
3
|
import time
|
|
4
4
|
|
|
5
5
|
from ..context import build_goal_message
|
|
6
|
-
from ..events import (
|
|
7
|
-
CompactStartedEvent,
|
|
8
|
-
TerminalEvent,
|
|
9
|
-
TokenCountEvent,
|
|
10
|
-
TurnCompletedEvent,
|
|
11
|
-
TurnInterruptedEvent,
|
|
12
|
-
TurnStartedEvent,
|
|
13
|
-
)
|
|
14
6
|
|
|
15
7
|
|
|
16
8
|
class GoalManager:
|
|
@@ -126,30 +118,31 @@ class GoalManager:
|
|
|
126
118
|
if steer:
|
|
127
119
|
self._budget_message = build_goal_message(goal, budget_limited=True)
|
|
128
120
|
|
|
129
|
-
def
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
self.
|
|
151
|
-
|
|
152
|
-
|
|
121
|
+
def begin_turn(self):
|
|
122
|
+
self.start()
|
|
123
|
+
self._continuation_ready = False
|
|
124
|
+
self._count_tokens = self._goal is not None and self._goal["status"] == "active"
|
|
125
|
+
|
|
126
|
+
def record_usage(self, usage):
|
|
127
|
+
if self._count_tokens:
|
|
128
|
+
cached = usage.get("input_tokens_details", {}).get("cached_tokens", 0)
|
|
129
|
+
self._pending_tokens += (
|
|
130
|
+
max(0, usage.get("input_tokens", 0) - cached)
|
|
131
|
+
+ max(0, usage.get("output_tokens", 0))
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def finish_turn(self, interrupted):
|
|
135
|
+
self.account(steer=False)
|
|
136
|
+
self._count_tokens = False
|
|
137
|
+
if self._goal is not None:
|
|
138
|
+
if interrupted and self._goal["status"] == "active":
|
|
139
|
+
self._goal["status"] = "paused"
|
|
140
|
+
self._goal["updatedAt"] = int(time.time())
|
|
141
|
+
if self._goal["status"] != "active":
|
|
142
|
+
self._last_accounted_at = None
|
|
143
|
+
|
|
144
|
+
def schedule_continuation(self):
|
|
145
|
+
self._continuation_ready = self._goal is not None and self._goal["status"] == "active"
|
|
153
146
|
|
|
154
147
|
def follow_up_messages(self):
|
|
155
148
|
message, self._budget_message = self._budget_message, None
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import asyncio
|
|
2
2
|
import typing
|
|
3
|
+
from contextlib import contextmanager
|
|
3
4
|
from dataclasses import dataclass
|
|
4
5
|
from typing import Awaitable, Callable
|
|
5
6
|
|
|
6
|
-
from ..events import
|
|
7
|
+
from ..events import ModelRequestInterrupted, TurnInterrupted
|
|
7
8
|
from ..utils.compat import Literal
|
|
8
9
|
from .clock_manager import ClockManager
|
|
9
10
|
from .goal_manager import GoalManager
|
|
@@ -100,17 +101,17 @@ class AgentRuntimeEnvironment:
|
|
|
100
101
|
self._resources = {}
|
|
101
102
|
self._restart_handlers = []
|
|
102
103
|
self._close_handlers = []
|
|
103
|
-
self._event_handlers = []
|
|
104
104
|
self._bindings = None
|
|
105
105
|
|
|
106
|
-
def register_resource(self, name, manager, restart=None, close=None
|
|
106
|
+
def register_resource(self, name, manager, restart=None, close=None):
|
|
107
107
|
"""Register one shared manager, independently of its callable tools."""
|
|
108
108
|
if name in self._resources or manager in self._resources.values():
|
|
109
109
|
raise ValueError("resource already registered: " + name)
|
|
110
110
|
self._resources[name] = manager
|
|
111
|
+
if name == "clock":
|
|
112
|
+
self.clock_manager = manager
|
|
111
113
|
for handler, handlers in (
|
|
112
114
|
(restart, self._restart_handlers), (close, self._close_handlers),
|
|
113
|
-
(observer, self._event_handlers),
|
|
114
115
|
):
|
|
115
116
|
if handler is not None:
|
|
116
117
|
handlers.append(handler)
|
|
@@ -144,11 +145,6 @@ class AgentRuntimeEnvironment:
|
|
|
144
145
|
for item in manager.background_work_snapshot()
|
|
145
146
|
]
|
|
146
147
|
|
|
147
|
-
def event_observers(self, event):
|
|
148
|
-
return self._event_handlers if isinstance(
|
|
149
|
-
event, (TerminalEvent, TurnStartedEvent, CompactStartedEvent),
|
|
150
|
-
) else []
|
|
151
|
-
|
|
152
148
|
def dump_state(self):
|
|
153
149
|
managers = {"clock": self.clock_manager.dump_state()}
|
|
154
150
|
goal = self.goal_manager.dump_state()
|
|
@@ -179,8 +175,22 @@ class AgentRuntimeEnvironment:
|
|
|
179
175
|
self.clock_manager.arm_after_reply()
|
|
180
176
|
self.goal_manager.start()
|
|
181
177
|
|
|
182
|
-
|
|
183
|
-
|
|
178
|
+
@contextmanager
|
|
179
|
+
def execution(self, save_state, manual=False):
|
|
180
|
+
self.goal_manager.begin_turn()
|
|
181
|
+
self.clock_manager.turn_started()
|
|
182
|
+
interrupted = False
|
|
183
|
+
try:
|
|
184
|
+
yield
|
|
185
|
+
except (TurnInterrupted, ModelRequestInterrupted):
|
|
186
|
+
interrupted = not manual
|
|
187
|
+
raise
|
|
188
|
+
finally:
|
|
189
|
+
self.goal_manager.finish_turn(interrupted)
|
|
190
|
+
save_state()
|
|
191
|
+
if not manual:
|
|
192
|
+
self.goal_manager.schedule_continuation()
|
|
193
|
+
self.clock_manager.arm_after_reply()
|
|
184
194
|
|
|
185
195
|
def tool_completed(self):
|
|
186
196
|
self.goal_manager.account()
|
|
@@ -14,6 +14,8 @@ Expected behavior:
|
|
|
14
14
|
import asyncio
|
|
15
15
|
import os
|
|
16
16
|
import shlex
|
|
17
|
+
import signal
|
|
18
|
+
import subprocess
|
|
17
19
|
import threading
|
|
18
20
|
import typing
|
|
19
21
|
import uuid
|
|
@@ -34,6 +36,7 @@ DEFAULT_EXEC_YIELD_TIME_MS = 10_000
|
|
|
34
36
|
DEFAULT_WRITE_STDIN_YIELD_TIME_MS = 250
|
|
35
37
|
DEFAULT_LOGIN = True
|
|
36
38
|
DEFAULT_TTY = False
|
|
39
|
+
DEFAULT_WAKE_ME_UP_WHEN_DONE = False
|
|
37
40
|
DEFAULT_SESSION_ID_START = 1000
|
|
38
41
|
UNIFIED_EXEC_OUTPUT_MAX_BYTES = 1024 * 1024
|
|
39
42
|
# Match upstream unified exec's short post-exit output close wait.
|
|
@@ -136,6 +139,21 @@ class UnifiedExecManager:
|
|
|
136
139
|
def shutdown(self):
|
|
137
140
|
self._notify_hook = None
|
|
138
141
|
|
|
142
|
+
async def close(self):
|
|
143
|
+
"""Terminate command process trees left running when the session closes."""
|
|
144
|
+
with self._lock:
|
|
145
|
+
sessions = list(self._sessions.values())
|
|
146
|
+
self._sessions.clear()
|
|
147
|
+
for session in sessions:
|
|
148
|
+
if session.process.returncode is None:
|
|
149
|
+
_kill_process_tree(session.process.pid)
|
|
150
|
+
for session in sessions:
|
|
151
|
+
await session.process.wait()
|
|
152
|
+
if session.reader_task is not None:
|
|
153
|
+
await asyncio.gather(session.reader_task, return_exceptions=True)
|
|
154
|
+
if sessions:
|
|
155
|
+
self._state_changed()
|
|
156
|
+
|
|
139
157
|
def background_work_count(self, after_reply) -> "int":
|
|
140
158
|
return sum(
|
|
141
159
|
1
|
|
@@ -175,6 +193,7 @@ class UnifiedExecManager:
|
|
|
175
193
|
tty: "bool" = DEFAULT_TTY,
|
|
176
194
|
yield_time_ms: "int" = DEFAULT_EXEC_YIELD_TIME_MS,
|
|
177
195
|
max_output_tokens: "typing.Union[int, None]" = None,
|
|
196
|
+
wake_me_up_when_done: "bool" = DEFAULT_WAKE_ME_UP_WHEN_DONE,
|
|
178
197
|
) -> "JSONValue":
|
|
179
198
|
session_id = await self._allocate_session_id()
|
|
180
199
|
command = self._build_shell_command(cmd, shell, login)
|
|
@@ -215,7 +234,11 @@ class UnifiedExecManager:
|
|
|
215
234
|
)
|
|
216
235
|
session = await self._get_session(session_id)
|
|
217
236
|
if session is not None:
|
|
218
|
-
asyncio.create_task(
|
|
237
|
+
asyncio.create_task(
|
|
238
|
+
self._notify_when_session_completes(
|
|
239
|
+
session_id, wake_me_up_when_done=wake_me_up_when_done
|
|
240
|
+
)
|
|
241
|
+
)
|
|
219
242
|
return output
|
|
220
243
|
|
|
221
244
|
async def write_stdin(
|
|
@@ -360,16 +383,22 @@ class UnifiedExecManager:
|
|
|
360
383
|
session.output_event.set()
|
|
361
384
|
session.output_event.set()
|
|
362
385
|
|
|
363
|
-
async def _notify_when_session_completes(
|
|
386
|
+
async def _notify_when_session_completes(
|
|
387
|
+
self,
|
|
388
|
+
session_id: "int",
|
|
389
|
+
wake_me_up_when_done: "bool" = True,
|
|
390
|
+
) -> "None":
|
|
364
391
|
from ..runtime import SubmissionInterrupted
|
|
365
392
|
|
|
366
|
-
if self._notify_hook is None:
|
|
393
|
+
if self._notify_hook is None and self._state_listener is None:
|
|
367
394
|
return
|
|
368
395
|
session = await self._get_session(session_id)
|
|
369
396
|
if session is None:
|
|
370
397
|
return
|
|
371
398
|
await session.process.wait()
|
|
372
399
|
self._state_changed()
|
|
400
|
+
if not wake_me_up_when_done:
|
|
401
|
+
return
|
|
373
402
|
with self._lock:
|
|
374
403
|
if self._sessions.get(session_id) is not session:
|
|
375
404
|
return
|
|
@@ -425,3 +454,17 @@ class UnifiedExecManager:
|
|
|
425
454
|
def _tty_echo(self, chars: "str") -> "bytes":
|
|
426
455
|
normalized = chars.replace("\n", "\r\n")
|
|
427
456
|
return normalized.encode("utf-8")
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _kill_process_tree(pid: "int") -> "None":
|
|
460
|
+
if os.name == "nt":
|
|
461
|
+
subprocess.run(
|
|
462
|
+
["taskkill", "/F", "/T", "/PID", str(pid)],
|
|
463
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
464
|
+
)
|
|
465
|
+
return
|
|
466
|
+
try:
|
|
467
|
+
# Commands start in their own session, so the group holds their children.
|
|
468
|
+
os.killpg(pid, signal.SIGKILL)
|
|
469
|
+
except ProcessLookupError:
|
|
470
|
+
pass
|
pycodex/utils/compactor.py
CHANGED
|
@@ -1,22 +1,15 @@
|
|
|
1
1
|
import typing
|
|
2
|
+
from collections import defaultdict, deque
|
|
2
3
|
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
3
5
|
|
|
4
6
|
from ..protocol import (
|
|
5
7
|
AssistantMessage,
|
|
6
8
|
ContextMessage,
|
|
7
9
|
ConversationItem,
|
|
8
|
-
ModelResponse,
|
|
9
10
|
ToolCall,
|
|
10
11
|
ToolResult,
|
|
11
|
-
ToolSpec,
|
|
12
|
-
UserMessage,
|
|
13
12
|
)
|
|
14
|
-
from .random_ids import uuid7_string
|
|
15
|
-
|
|
16
|
-
if typing.TYPE_CHECKING:
|
|
17
|
-
from ..context import ContextManager
|
|
18
|
-
from ..events import ModelEvent
|
|
19
|
-
from ..model import ModelClient
|
|
20
13
|
|
|
21
14
|
DEFAULT_COMPACT_PROMPT = """You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.
|
|
22
15
|
|
|
@@ -50,10 +43,17 @@ class CompactResult:
|
|
|
50
43
|
def retained_item_count(self) -> "int":
|
|
51
44
|
return max(len(self.history) - 1, 0)
|
|
52
45
|
|
|
46
|
+
@classmethod
|
|
47
|
+
def from_response(cls, response, session_file, original_item_count, pruned_tool_results):
|
|
48
|
+
summary = _last_assistant_message(response.items)
|
|
49
|
+
if summary is None or not summary.strip():
|
|
50
|
+
raise ValueError("compact response contains no assistant summary")
|
|
51
|
+
return cls(compact(response.items, session_file), original_item_count, pruned_tool_results)
|
|
52
|
+
|
|
53
53
|
|
|
54
54
|
def compact(
|
|
55
55
|
history: "typing.Sequence[ConversationItem]",
|
|
56
|
-
session_file: "typing.Union[str, None]" = None,
|
|
56
|
+
session_file: "typing.Union[str, Path, None]" = None,
|
|
57
57
|
) -> "typing.Tuple[ConversationItem, ...]":
|
|
58
58
|
summary_text = _build_summary_message(_last_assistant_message(history))
|
|
59
59
|
if session_file:
|
|
@@ -67,98 +67,25 @@ def compact(
|
|
|
67
67
|
return build_compacted_history(summary_text)
|
|
68
68
|
|
|
69
69
|
|
|
70
|
-
async def compact_history(
|
|
71
|
-
history: "typing.Sequence[ConversationItem]",
|
|
72
|
-
model_client: "ModelClient",
|
|
73
|
-
context_manager: "ContextManager",
|
|
74
|
-
tools: "typing.List[ToolSpec]",
|
|
75
|
-
parallel_tool_calls: "bool",
|
|
76
|
-
stream_event_handler: "typing.Union[typing.Callable[[ModelEvent], None], None]" = None,
|
|
77
|
-
prune_tool_results_on_context_error: "bool" = False,
|
|
78
|
-
session_file: "typing.Union[str, None]" = None,
|
|
79
|
-
turn_id: "typing.Union[str, None]" = None,
|
|
80
|
-
session_id: "typing.Union[str, None]" = None,
|
|
81
|
-
) -> "typing.Union[CompactResult, None]":
|
|
82
|
-
from ..model import ContextLengthExceeded, ResponsesIncompleteError
|
|
83
|
-
|
|
84
|
-
if not history:
|
|
85
|
-
return None
|
|
86
|
-
original_item_count = len(history)
|
|
87
|
-
pruned_tool_results = 0
|
|
88
|
-
turn_id = turn_id or uuid7_string()
|
|
89
|
-
|
|
90
|
-
noop_stream_event_handler = lambda _event: None
|
|
91
|
-
while True:
|
|
92
|
-
compact_prompt = UserMessage(text=DEFAULT_COMPACT_PROMPT)
|
|
93
|
-
prompt = context_manager.build_prompt(
|
|
94
|
-
list(history) + [compact_prompt],
|
|
95
|
-
tools,
|
|
96
|
-
parallel_tool_calls,
|
|
97
|
-
turn_id=turn_id,
|
|
98
|
-
reasoning_effort=model_client.reasoning_effort,
|
|
99
|
-
capture_context=False,
|
|
100
|
-
session_id=session_id,
|
|
101
|
-
)
|
|
102
|
-
try:
|
|
103
|
-
response = await model_client.complete(
|
|
104
|
-
prompt,
|
|
105
|
-
stream_event_handler or noop_stream_event_handler,
|
|
106
|
-
)
|
|
107
|
-
break
|
|
108
|
-
except ResponsesIncompleteError as exc:
|
|
109
|
-
if (
|
|
110
|
-
exc.reason != "max_output_tokens"
|
|
111
|
-
or _last_assistant_message(exc.partial_items) is None
|
|
112
|
-
):
|
|
113
|
-
raise
|
|
114
|
-
response = ModelResponse(items=list(exc.partial_items))
|
|
115
|
-
break
|
|
116
|
-
except ContextLengthExceeded:
|
|
117
|
-
if not prune_tool_results_on_context_error:
|
|
118
|
-
raise
|
|
119
|
-
pruned_history = prune_oldest_tool_response(history)
|
|
120
|
-
if pruned_history is None:
|
|
121
|
-
raise
|
|
122
|
-
history = pruned_history
|
|
123
|
-
pruned_tool_results += 1
|
|
124
|
-
|
|
125
|
-
summary = _last_assistant_message(response.items)
|
|
126
|
-
if summary is None or not summary.strip():
|
|
127
|
-
raise ValueError("compact response contains no assistant summary")
|
|
128
|
-
compacted_history = compact(
|
|
129
|
-
response.items,
|
|
130
|
-
session_file,
|
|
131
|
-
)
|
|
132
|
-
return CompactResult(
|
|
133
|
-
history=compacted_history,
|
|
134
|
-
original_item_count=original_item_count,
|
|
135
|
-
pruned_tool_results=pruned_tool_results,
|
|
136
|
-
)
|
|
137
|
-
|
|
138
|
-
|
|
139
70
|
def prune_oldest_tool_response(
|
|
140
|
-
history: "typing.Sequence[ConversationItem]",
|
|
141
|
-
) -> "typing.
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
return tuple(
|
|
160
|
-
item for index, item in enumerate(items) if index not in indexes_to_remove
|
|
161
|
-
)
|
|
71
|
+
history: "typing.Sequence[ConversationItem]", count: "int" = 1,
|
|
72
|
+
) -> "typing.Optional[typing.Sequence[ConversationItem]]":
|
|
73
|
+
"""Drop the oldest count results together with their matching calls."""
|
|
74
|
+
if count == 0:
|
|
75
|
+
return history
|
|
76
|
+
calls = defaultdict(deque)
|
|
77
|
+
removed = set()
|
|
78
|
+
for index, item in enumerate(history):
|
|
79
|
+
if isinstance(item, ToolCall):
|
|
80
|
+
calls[item.call_id].append(index)
|
|
81
|
+
elif isinstance(item, ToolResult):
|
|
82
|
+
removed.add(index)
|
|
83
|
+
if calls[item.call_id]:
|
|
84
|
+
removed.add(calls[item.call_id].popleft())
|
|
85
|
+
count -= 1
|
|
86
|
+
if count == 0:
|
|
87
|
+
return tuple(item for i, item in enumerate(history) if i not in removed)
|
|
88
|
+
return None
|
|
162
89
|
|
|
163
90
|
|
|
164
91
|
def build_compacted_history(
|
pycodex/utils/compat.py
CHANGED
|
@@ -5,8 +5,14 @@ import asyncio
|
|
|
5
5
|
import functools
|
|
6
6
|
import io
|
|
7
7
|
import shlex
|
|
8
|
+
import sys
|
|
8
9
|
import tokenize
|
|
9
10
|
|
|
11
|
+
if sys.version_info >= (3, 7):
|
|
12
|
+
from contextvars import ContextVar, copy_context
|
|
13
|
+
else: # pragma: no cover - Python 3.6 task-local context
|
|
14
|
+
from aiocontextvars import ContextVar, copy_context
|
|
15
|
+
|
|
10
16
|
try:
|
|
11
17
|
from http.server import ThreadingHTTPServer
|
|
12
18
|
except ImportError: # pragma: no cover - Python 3.6 path
|
pycodex/utils/event_helpers.py
CHANGED
|
@@ -6,6 +6,8 @@ import shlex
|
|
|
6
6
|
import typing
|
|
7
7
|
from dataclasses import asdict
|
|
8
8
|
|
|
9
|
+
from ..protocol import AgentMessage, AssistantMessage, ReasoningItem, UserMessage
|
|
10
|
+
|
|
9
11
|
PROMPT_CONTEXT_BASELINE_TOKENS = 12_000
|
|
10
12
|
|
|
11
13
|
|
|
@@ -92,6 +94,51 @@ def shorten_title(text: "str", limit: "int" = 48) -> "str":
|
|
|
92
94
|
return truncate_text(text, limit)
|
|
93
95
|
|
|
94
96
|
|
|
97
|
+
def visible_input_text(messages):
|
|
98
|
+
return "\n".join(
|
|
99
|
+
"[{0}]".format(message.visible) if isinstance(message.visible, str) else message.text
|
|
100
|
+
for message in messages
|
|
101
|
+
if isinstance(message, (UserMessage, AgentMessage)) and message.visible
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def reasoning_item_text(item: "ReasoningItem", streamed_raw: "str" = "") -> "str":
|
|
106
|
+
content = item.payload.get("content")
|
|
107
|
+
if isinstance(content, list):
|
|
108
|
+
raw_text = "".join(
|
|
109
|
+
str(part.get("text", ""))
|
|
110
|
+
for part in content
|
|
111
|
+
if isinstance(part, dict) and part.get("type") == "reasoning_text"
|
|
112
|
+
)
|
|
113
|
+
if raw_text.strip():
|
|
114
|
+
return raw_text
|
|
115
|
+
if streamed_raw.strip():
|
|
116
|
+
return streamed_raw
|
|
117
|
+
summary = item.payload.get("summary")
|
|
118
|
+
if isinstance(summary, list):
|
|
119
|
+
for part in reversed(summary):
|
|
120
|
+
if isinstance(part, dict) and part.get("type") == "summary_text":
|
|
121
|
+
text = str(part.get("text", ""))
|
|
122
|
+
if text.strip():
|
|
123
|
+
return text
|
|
124
|
+
return ""
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def last_reasoning_text(history: "typing.Sequence[object]") -> "str":
|
|
128
|
+
for item in reversed(history):
|
|
129
|
+
if item is None or (isinstance(item, dict) and item.get("type") == "compacted"):
|
|
130
|
+
return ""
|
|
131
|
+
if isinstance(item, AssistantMessage) and item.visible and item.text.strip():
|
|
132
|
+
return ""
|
|
133
|
+
if isinstance(item, ReasoningItem):
|
|
134
|
+
text = reasoning_item_text(item)
|
|
135
|
+
if text:
|
|
136
|
+
return text
|
|
137
|
+
if isinstance(item, (UserMessage, AgentMessage)) and item.visible:
|
|
138
|
+
return ""
|
|
139
|
+
return ""
|
|
140
|
+
|
|
141
|
+
|
|
95
142
|
def percent_of_context_window_remaining(total_tokens, context_window_tokens):
|
|
96
143
|
if context_window_tokens <= PROMPT_CONTEXT_BASELINE_TOKENS:
|
|
97
144
|
return 0
|
pycodex/utils/history.py
CHANGED
|
@@ -19,8 +19,10 @@ def serialize_history_item(item):
|
|
|
19
19
|
|
|
20
20
|
def restore_message_metadata(item, payload, record_id, timestamp=None):
|
|
21
21
|
visible = payload.get("visible", item.visible)
|
|
22
|
-
if not isinstance(visible, bool)
|
|
23
|
-
|
|
22
|
+
if not isinstance(visible, bool) and (
|
|
23
|
+
not isinstance(visible, str) or not visible.strip()
|
|
24
|
+
):
|
|
25
|
+
raise ValueError("history item visible must be a boolean or non-empty string")
|
|
24
26
|
legacy_id = sha256(json.dumps(
|
|
25
27
|
[record_id, timestamp, payload], ensure_ascii=False, sort_keys=True,
|
|
26
28
|
).encode("utf-8")).hexdigest()[:32]
|
|
@@ -30,11 +32,16 @@ def restore_message_metadata(item, payload, record_id, timestamp=None):
|
|
|
30
32
|
)
|
|
31
33
|
|
|
32
34
|
|
|
35
|
+
def compaction_prefix_id(turn):
|
|
36
|
+
first = turn["messages"][0].message_id if turn["messages"] else turn["response_id"]
|
|
37
|
+
return "part-" + first
|
|
38
|
+
|
|
39
|
+
|
|
33
40
|
def conversation_history_to_turns(history, previous=()):
|
|
34
41
|
"""Convert a transcript or append committed items to existing display values.
|
|
35
42
|
|
|
36
43
|
The caller owns the result; neither the previous values nor messages change.
|
|
37
|
-
Explicit turn IDs group
|
|
44
|
+
Explicit turn IDs group messages between compactions. Old records retain phase boundaries.
|
|
38
45
|
"""
|
|
39
46
|
turns = [
|
|
40
47
|
{key: turn[key] for key in (
|
|
@@ -43,7 +50,9 @@ def conversation_history_to_turns(history, previous=()):
|
|
|
43
50
|
)}
|
|
44
51
|
for turn in previous
|
|
45
52
|
]
|
|
46
|
-
by_id = {turn["turn_id"]:
|
|
53
|
+
by_id = {turn["turn_id"]: index for index, turn in enumerate(turns)}
|
|
54
|
+
boundary = next((i + 1 for i in reversed(range(len(turns)))
|
|
55
|
+
if turns[i]["kind"] == "compaction"), 0)
|
|
47
56
|
current = turns[-1] if turns else None
|
|
48
57
|
if current is not None and (
|
|
49
58
|
current["kind"] == "compaction" or current["response_phase"] == "final"
|
|
@@ -55,6 +64,7 @@ def conversation_history_to_turns(history, previous=()):
|
|
|
55
64
|
)
|
|
56
65
|
if is_compaction:
|
|
57
66
|
turn_id = item["id"] if item is not None else "compaction-{0}".format(len(turns))
|
|
67
|
+
boundary = len(turns)
|
|
58
68
|
current = None
|
|
59
69
|
elif isinstance(item, (UserMessage, AgentMessage, AssistantMessage)):
|
|
60
70
|
is_input = isinstance(item, (UserMessage, AgentMessage))
|
|
@@ -68,15 +78,20 @@ def conversation_history_to_turns(history, previous=()):
|
|
|
68
78
|
turn_id = item.turn_id or (current["turn_id"] if current is not None else item.message_id)
|
|
69
79
|
else:
|
|
70
80
|
continue
|
|
71
|
-
|
|
72
|
-
if
|
|
81
|
+
index = by_id.get(turn_id)
|
|
82
|
+
if index is None or index < boundary:
|
|
83
|
+
if index is not None:
|
|
84
|
+
earlier = turns[index]
|
|
85
|
+
earlier["turn_id"] = compaction_prefix_id(earlier)
|
|
73
86
|
turn = {
|
|
74
87
|
"turn_id": turn_id, "messages": (), "response": "",
|
|
75
88
|
"response_id": None, "response_at": None, "response_phase": None,
|
|
76
89
|
"kind": "compaction" if is_compaction else "assistant",
|
|
77
90
|
}
|
|
91
|
+
by_id[turn_id] = len(turns)
|
|
78
92
|
turns.append(turn)
|
|
79
|
-
|
|
93
|
+
else:
|
|
94
|
+
turn = turns[index]
|
|
80
95
|
if is_compaction:
|
|
81
96
|
continue
|
|
82
97
|
if is_input:
|
pycodex/utils/model_metadata.py
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
import json
|
|
4
4
|
import re
|
|
5
5
|
import typing
|
|
6
|
-
from functools import lru_cache
|
|
7
6
|
from pathlib import Path
|
|
8
7
|
|
|
9
8
|
from ..protocol import JSONDict
|
|
@@ -11,7 +10,6 @@ from ..protocol import JSONDict
|
|
|
11
10
|
DEFAULT_MODELS_PATH = Path(__file__).resolve().parents[1] / "prompts" / "models.json"
|
|
12
11
|
|
|
13
12
|
|
|
14
|
-
@lru_cache(maxsize=1)
|
|
15
13
|
def load_models_by_slug() -> "typing.Dict[str, JSONDict]":
|
|
16
14
|
payload = json.loads(DEFAULT_MODELS_PATH.read_text(encoding="utf-8"))
|
|
17
15
|
models = payload.get("models", [])
|
|
@@ -25,10 +23,13 @@ def load_models_by_slug() -> "typing.Dict[str, JSONDict]":
|
|
|
25
23
|
return by_slug
|
|
26
24
|
|
|
27
25
|
|
|
28
|
-
def model_metadata(
|
|
26
|
+
def model_metadata(
|
|
27
|
+
slug: "typing.Union[str, None]",
|
|
28
|
+
catalog: "typing.Union[typing.Dict[str, JSONDict], None]" = None,
|
|
29
|
+
) -> "typing.Union[JSONDict, None]":
|
|
29
30
|
if slug is None:
|
|
30
31
|
return None
|
|
31
|
-
models = load_models_by_slug()
|
|
32
|
+
models = load_models_by_slug() if catalog is None else catalog
|
|
32
33
|
candidates = [name for name in models if slug.startswith(name)]
|
|
33
34
|
if not candidates:
|
|
34
35
|
namespace, separator, suffix = slug.partition("/")
|
pycodex/utils/session_persist.py
CHANGED
|
@@ -420,8 +420,7 @@ def load_display_history(
|
|
|
420
420
|
items.append(item)
|
|
421
421
|
if isinstance(item, dict):
|
|
422
422
|
remaining -= 1
|
|
423
|
-
|
|
424
|
-
continue
|
|
423
|
+
oldest_turn_id = None
|
|
425
424
|
elif not item.visible:
|
|
426
425
|
continue
|
|
427
426
|
else:
|
|
@@ -568,6 +567,11 @@ def _find_last_compacted_offset(
|
|
|
568
567
|
return None
|
|
569
568
|
|
|
570
569
|
|
|
570
|
+
def last_compaction_id(path):
|
|
571
|
+
offset = _find_last_compacted_offset(Path(path))
|
|
572
|
+
return "compaction-{0}".format(offset) if offset is not None else None
|
|
573
|
+
|
|
574
|
+
|
|
571
575
|
def _iter_rollout_entries(
|
|
572
576
|
rollout_path: "Path",
|
|
573
577
|
start_offset: "int" = 0,
|