python-codex 0.6.1__py3-none-any.whl → 0.6.3__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 +35 -9
- pycodex/bootstrap.py +8 -0
- pycodex/context.py +54 -36
- pycodex/events.py +19 -10
- pycodex/model.py +32 -7
- pycodex/prompts/models.json +345 -0
- pycodex/protocol.py +15 -0
- pycodex/runtime.py +49 -54
- pycodex/utils/compactor.py +5 -2
- pycodex/utils/event_helpers.py +5 -9
- pycodex/utils/history.py +74 -41
- pycodex/utils/http_headers.py +25 -0
- pycodex/utils/session_persist.py +125 -42
- pycodex/utils/skill_catalog.py +18 -0
- {python_codex-0.6.1.dist-info → python_codex-0.6.3.dist-info}/METADATA +22 -4
- {python_codex-0.6.1.dist-info → python_codex-0.6.3.dist-info}/RECORD +27 -25
- responses_server/app.py +2 -0
- responses_server/config.py +4 -1
- responses_server/gemini_api.py +17 -6
- responses_server/messages_api.py +12 -6
- responses_server/payload_processors.py +1 -1
- responses_server/request_translation.py +55 -13
- responses_server/stream_router.py +9 -0
- responses_server/transport.py +12 -6
- {python_codex-0.6.1.dist-info → python_codex-0.6.3.dist-info}/WHEEL +0 -0
- {python_codex-0.6.1.dist-info → python_codex-0.6.3.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.1.dist-info → python_codex-0.6.3.dist-info}/licenses/LICENSE +0 -0
pycodex/protocol.py
CHANGED
|
@@ -17,14 +17,20 @@ import json
|
|
|
17
17
|
import typing
|
|
18
18
|
from copy import deepcopy
|
|
19
19
|
from dataclasses import dataclass, field
|
|
20
|
+
from datetime import datetime, timezone
|
|
20
21
|
from typing import Any
|
|
21
22
|
|
|
22
23
|
from .utils.compat import Literal, TypeAlias
|
|
24
|
+
from .utils.random_ids import uuid7_string
|
|
23
25
|
|
|
24
26
|
JSONValue: "TypeAlias" = Any
|
|
25
27
|
JSONDict: "TypeAlias" = typing.Dict[str, Any]
|
|
26
28
|
|
|
27
29
|
|
|
30
|
+
def message_timestamp():
|
|
31
|
+
return datetime.now(timezone.utc).isoformat(timespec="milliseconds")
|
|
32
|
+
|
|
33
|
+
|
|
28
34
|
def qualified_tool_name(name, namespace):
|
|
29
35
|
return name if namespace in (None, "", "functions") else f"{namespace}.{name}"
|
|
30
36
|
|
|
@@ -94,6 +100,9 @@ class UserMessage:
|
|
|
94
100
|
# Local history metadata; serialize() is the model-facing representation.
|
|
95
101
|
name: "str" = "user"
|
|
96
102
|
visible: "bool" = True
|
|
103
|
+
message_id: "str" = field(default_factory=uuid7_string, compare=False)
|
|
104
|
+
created_at: "typing.Union[str, None]" = field(default_factory=message_timestamp, compare=False)
|
|
105
|
+
turn_id: "typing.Union[str, None]" = field(default=None, compare=False)
|
|
97
106
|
|
|
98
107
|
def serialize(self) -> "JSONDict":
|
|
99
108
|
payload = {
|
|
@@ -116,6 +125,9 @@ class AgentMessage:
|
|
|
116
125
|
id: "typing.Union[str, None]" = None
|
|
117
126
|
internal_chat_message_metadata_passthrough: "typing.Union[JSONDict, None]" = None
|
|
118
127
|
visible: "bool" = False
|
|
128
|
+
message_id: "str" = field(default_factory=uuid7_string, compare=False)
|
|
129
|
+
created_at: "typing.Union[str, None]" = field(default_factory=message_timestamp, compare=False)
|
|
130
|
+
turn_id: "typing.Union[str, None]" = field(default=None, compare=False)
|
|
119
131
|
|
|
120
132
|
@property
|
|
121
133
|
def text(self) -> "str":
|
|
@@ -167,6 +179,9 @@ class AssistantMessage:
|
|
|
167
179
|
phase: "typing.Union[str, None]" = None
|
|
168
180
|
content_items: "typing.Union[typing.Tuple[JSONDict, ...], None]" = None
|
|
169
181
|
visible: "bool" = True
|
|
182
|
+
message_id: "str" = field(default_factory=uuid7_string, compare=False)
|
|
183
|
+
created_at: "typing.Union[str, None]" = field(default_factory=message_timestamp, compare=False)
|
|
184
|
+
turn_id: "typing.Union[str, None]" = field(default=None, compare=False)
|
|
170
185
|
|
|
171
186
|
@classmethod
|
|
172
187
|
def from_response_item(cls, payload: "JSONDict") -> "AssistantMessage":
|
pycodex/runtime.py
CHANGED
|
@@ -8,7 +8,6 @@ from time import monotonic
|
|
|
8
8
|
from .agent import BASE_EVENT_HANDLER, Agent, TurnInterrupted
|
|
9
9
|
from .events import (
|
|
10
10
|
AssistantDeltaEvent,
|
|
11
|
-
AutoCompactCompletedEvent,
|
|
12
11
|
CommandCompletedEvent,
|
|
13
12
|
CommandFailedEvent,
|
|
14
13
|
CommandStartedEvent,
|
|
@@ -17,6 +16,7 @@ from .events import (
|
|
|
17
16
|
InputQueuedEvent,
|
|
18
17
|
InputRequestedEvent,
|
|
19
18
|
InputResolvedEvent,
|
|
19
|
+
MessagesAddedEvent,
|
|
20
20
|
RuntimeUpdatedEvent,
|
|
21
21
|
SessionClosedEvent,
|
|
22
22
|
SessionStateEvent,
|
|
@@ -30,7 +30,7 @@ from .events import (
|
|
|
30
30
|
TurnStartedEvent,
|
|
31
31
|
)
|
|
32
32
|
from .model import ModelControl
|
|
33
|
-
from .protocol import AgentMessage, ToolResult, TurnResult, UserMessage
|
|
33
|
+
from .protocol import AgentMessage, AssistantMessage, ToolResult, TurnResult, UserMessage
|
|
34
34
|
from .tools.runtime_services import close_resources
|
|
35
35
|
from .utils import uuid7_string
|
|
36
36
|
from .utils.event_helpers import shorten_title
|
|
@@ -52,11 +52,10 @@ class SubmissionInterrupted(RuntimeError):
|
|
|
52
52
|
|
|
53
53
|
|
|
54
54
|
class _QueuedSubmission:
|
|
55
|
-
def __init__(self,
|
|
55
|
+
def __init__(self, messages) -> "None":
|
|
56
56
|
self.submission_id = uuid7_string()
|
|
57
57
|
self.turn_id = self.submission_id
|
|
58
|
-
self.
|
|
59
|
-
self.name = name
|
|
58
|
+
self.messages = list(messages)
|
|
60
59
|
self.futures: "typing.List[asyncio.Future[TurnResult]]" = []
|
|
61
60
|
|
|
62
61
|
|
|
@@ -228,12 +227,11 @@ class AgentRuntime:
|
|
|
228
227
|
}
|
|
229
228
|
|
|
230
229
|
def snapshot(self):
|
|
231
|
-
execution = self.agent.execution_snapshot()
|
|
232
230
|
rollout_path = self.agent.session_file_path
|
|
233
231
|
recorded_path = self.agent.recorded_session_file_path
|
|
234
232
|
return {
|
|
235
|
-
**self.
|
|
236
|
-
"session_id":
|
|
233
|
+
**self.state_snapshot(),
|
|
234
|
+
"session_id": self.agent.session_id,
|
|
237
235
|
"rollout_path": str(rollout_path) if rollout_path is not None else None,
|
|
238
236
|
"recorded_rollout_path": str(recorded_path) if recorded_path is not None else None,
|
|
239
237
|
"model": "{0}:{1}".format(
|
|
@@ -241,9 +239,6 @@ class AgentRuntime:
|
|
|
241
239
|
self.agent.model_client.reasoning_effort or "default",
|
|
242
240
|
),
|
|
243
241
|
"history": conversation_history_to_turns(self.agent.history),
|
|
244
|
-
"active_turn": (
|
|
245
|
-
dict(self._active_turn) if self._active_turn is not None else None
|
|
246
|
-
),
|
|
247
242
|
}
|
|
248
243
|
|
|
249
244
|
def state_snapshot(self):
|
|
@@ -266,21 +261,14 @@ class AgentRuntime:
|
|
|
266
261
|
"reasoning_effort": client.reasoning_effort,
|
|
267
262
|
},
|
|
268
263
|
"running": execution.running,
|
|
269
|
-
"active_turn": (
|
|
270
|
-
{
|
|
271
|
-
key: active[key]
|
|
272
|
-
for key in (
|
|
273
|
-
"turn_id", "submission_id", "user_texts", "assistant_text",
|
|
274
|
-
"model_errors",
|
|
275
|
-
)
|
|
276
|
-
} if active is not None else None
|
|
277
|
-
),
|
|
264
|
+
"active_turn": dict(active) if active is not None else None,
|
|
278
265
|
"queued_inputs": [
|
|
279
266
|
{
|
|
280
267
|
"submission_id": item.submission_id,
|
|
281
268
|
"turn_id": item.turn_id,
|
|
282
269
|
"queue": name,
|
|
283
|
-
"
|
|
270
|
+
"messages": tuple(message for message in item.messages
|
|
271
|
+
if isinstance(message, (UserMessage, AgentMessage)) and message.visible),
|
|
284
272
|
}
|
|
285
273
|
for name, item in pending
|
|
286
274
|
],
|
|
@@ -515,18 +503,18 @@ class AgentRuntime:
|
|
|
515
503
|
|
|
516
504
|
def _submit_turn(self, text, queue, sender, name):
|
|
517
505
|
busy = self.is_busy
|
|
506
|
+
message = UserMessage(text, name=name)
|
|
518
507
|
if queue == "enqueue":
|
|
519
|
-
submission_id, future = self.enqueue(
|
|
508
|
+
submission_id, future = self.enqueue(message)
|
|
520
509
|
else:
|
|
521
510
|
current = self._current_submission if self.agent.is_running else None
|
|
522
511
|
self.stop_asap()
|
|
523
|
-
self.message(
|
|
512
|
+
self.message(message)
|
|
524
513
|
submission_id, future = self.trigger()
|
|
525
|
-
self._triggered_submission.texts.append(text)
|
|
526
514
|
if current is not None:
|
|
527
515
|
self._triggered_submission.turn_id = current.turn_id
|
|
528
516
|
self._publish(
|
|
529
|
-
InputQueuedEvent(submission_id,
|
|
517
|
+
InputQueuedEvent(submission_id, message, queue, sender, queue == "enqueue", busy)
|
|
530
518
|
)
|
|
531
519
|
return SubmittedInput(submission_id, "turn", future)
|
|
532
520
|
|
|
@@ -643,7 +631,7 @@ class AgentRuntime:
|
|
|
643
631
|
|
|
644
632
|
async def submit_user_turn(self, text: "str") -> "TurnResult":
|
|
645
633
|
"""Enqueue one independent turn and wait for its receipt."""
|
|
646
|
-
_submission_id, future = self.enqueue(text)
|
|
634
|
+
_submission_id, future = self.enqueue(UserMessage(text))
|
|
647
635
|
return await future
|
|
648
636
|
|
|
649
637
|
async def maybe_invoke(self, event: "typing.Dict[str, object]") -> "bool":
|
|
@@ -662,7 +650,6 @@ class AgentRuntime:
|
|
|
662
650
|
await self.start()
|
|
663
651
|
self.message(text)
|
|
664
652
|
_submission_id, future = self.trigger()
|
|
665
|
-
self._triggered_submission.texts.append(text)
|
|
666
653
|
await future
|
|
667
654
|
return True
|
|
668
655
|
|
|
@@ -682,11 +669,11 @@ class AgentRuntime:
|
|
|
682
669
|
self._last_agent_status = "interrupted"
|
|
683
670
|
self.publish_update("interrupt")
|
|
684
671
|
|
|
685
|
-
def enqueue(self,
|
|
672
|
+
def enqueue(self, message: "UserMessage") -> "typing.Tuple[str, asyncio.Future[TurnResult]]":
|
|
686
673
|
"""Schedule an independent user turn without affecting active execution."""
|
|
687
674
|
if not self.accepts_input:
|
|
688
675
|
raise RuntimeError("agent is shutting down")
|
|
689
|
-
queued = _QueuedSubmission([
|
|
676
|
+
queued = _QueuedSubmission([message])
|
|
690
677
|
self._enqueue_queue.append(queued)
|
|
691
678
|
return self._submission_receipt(queued)
|
|
692
679
|
|
|
@@ -697,7 +684,7 @@ class AgentRuntime:
|
|
|
697
684
|
if self._active_turn is not None and not self.agent.execution_snapshot().stop_requested:
|
|
698
685
|
return None
|
|
699
686
|
if self._triggered_submission is None:
|
|
700
|
-
self._triggered_submission = _QueuedSubmission(
|
|
687
|
+
self._triggered_submission = _QueuedSubmission(self._take_messages())
|
|
701
688
|
return self._submission_receipt(self._triggered_submission)
|
|
702
689
|
|
|
703
690
|
def _submission_receipt(self, queued):
|
|
@@ -705,7 +692,7 @@ class AgentRuntime:
|
|
|
705
692
|
future = loop.create_future()
|
|
706
693
|
future.add_done_callback(self._observe_completion)
|
|
707
694
|
queued.futures.append(future)
|
|
708
|
-
# Publish after the input layer attaches
|
|
695
|
+
# Publish after the input layer attaches the execution identity.
|
|
709
696
|
loop.call_soon(self._notify_queue_change)
|
|
710
697
|
return queued.submission_id, future
|
|
711
698
|
|
|
@@ -716,22 +703,35 @@ class AgentRuntime:
|
|
|
716
703
|
self.publish_update("queue")
|
|
717
704
|
self._wake_worker()
|
|
718
705
|
|
|
719
|
-
def message(self, text: "typing.Union[str, AgentMessage, ToolResult]") -> "None":
|
|
706
|
+
def message(self, text: "typing.Union[str, UserMessage, AgentMessage, ToolResult]") -> "None":
|
|
720
707
|
"""Deliver input to an open runtime's mailbox."""
|
|
721
708
|
if not self.accepts_input:
|
|
722
709
|
raise RuntimeError("agent is shutting down")
|
|
723
|
-
|
|
710
|
+
item = UserMessage(text) if isinstance(text, str) else text
|
|
711
|
+
if self._triggered_submission is not None:
|
|
712
|
+
self._triggered_submission.messages.append(item)
|
|
713
|
+
else:
|
|
714
|
+
self._steer_queue.append(item)
|
|
724
715
|
if self._active_turn is not None:
|
|
725
716
|
self.agent.request_follow_up()
|
|
726
717
|
if self._input_activity is not None:
|
|
727
718
|
self._input_activity.set()
|
|
728
719
|
|
|
720
|
+
def _take_messages(self):
|
|
721
|
+
messages = tuple(self._steer_queue)
|
|
722
|
+
self._steer_queue.clear()
|
|
723
|
+
return messages
|
|
724
|
+
|
|
729
725
|
def _deliver_messages(self):
|
|
730
726
|
if not self._steer_queue or self.agent.execution_snapshot().stop_requested:
|
|
731
727
|
return
|
|
732
|
-
self.
|
|
733
|
-
|
|
734
|
-
|
|
728
|
+
messages = self._take_messages()
|
|
729
|
+
try:
|
|
730
|
+
self.agent.receive_messages(messages)
|
|
731
|
+
except BaseException:
|
|
732
|
+
self._steer_queue.extendleft(reversed(messages))
|
|
733
|
+
raise
|
|
734
|
+
if self._input_activity is not None and not self._steer_queue and not self._wait_interrupted:
|
|
735
735
|
self._input_activity.clear()
|
|
736
736
|
|
|
737
737
|
async def wait_for_activity(self, timeout_ms):
|
|
@@ -760,10 +760,10 @@ class AgentRuntime:
|
|
|
760
760
|
pending = await self._next_submission()
|
|
761
761
|
if pending is None:
|
|
762
762
|
break
|
|
763
|
-
queued
|
|
763
|
+
queued = pending
|
|
764
764
|
self._current_submission = queued
|
|
765
765
|
try:
|
|
766
|
-
result = await self.agent.run_turn(
|
|
766
|
+
result = await self.agent.run_turn(queued.messages, turn_id=queued.turn_id)
|
|
767
767
|
except TurnInterrupted:
|
|
768
768
|
self._finish_submission_exception(queued, SubmissionInterrupted())
|
|
769
769
|
except Exception as exc:
|
|
@@ -788,17 +788,18 @@ class AgentRuntime:
|
|
|
788
788
|
self._publish(SessionClosedEvent())
|
|
789
789
|
self.agents_manager.unregister_runtime(self.agent.agent_id)
|
|
790
790
|
|
|
791
|
-
async def _next_submission(self) -> "typing.Union[
|
|
791
|
+
async def _next_submission(self) -> "typing.Union[_QueuedSubmission, None]":
|
|
792
792
|
while True:
|
|
793
793
|
await self.agent.wait_until_idle()
|
|
794
794
|
if not self.accepts_input:
|
|
795
795
|
return None
|
|
796
796
|
if self._triggered_submission is not None:
|
|
797
797
|
queued, self._triggered_submission = self._triggered_submission, None
|
|
798
|
-
return queued
|
|
798
|
+
return queued
|
|
799
799
|
if self._enqueue_queue:
|
|
800
800
|
queued = self._enqueue_queue.popleft()
|
|
801
|
-
|
|
801
|
+
queued.messages[:0] = self._take_messages()
|
|
802
|
+
return queued
|
|
802
803
|
if not self._steer_queue:
|
|
803
804
|
continuation = self.agent.tool_registry.runtime_environment.take_continuation()
|
|
804
805
|
if continuation is not None:
|
|
@@ -809,8 +810,7 @@ class AgentRuntime:
|
|
|
809
810
|
or self._enqueue_queue or self._steer_queue
|
|
810
811
|
):
|
|
811
812
|
continue
|
|
812
|
-
|
|
813
|
-
return _QueuedSubmission([]), []
|
|
813
|
+
return _QueuedSubmission([continuation])
|
|
814
814
|
self._queue_event.clear()
|
|
815
815
|
await self._queue_event.wait()
|
|
816
816
|
|
|
@@ -843,9 +843,6 @@ class AgentRuntime:
|
|
|
843
843
|
event = replace(
|
|
844
844
|
event, submission_id=event.submission_id or queued.submission_id
|
|
845
845
|
)
|
|
846
|
-
if isinstance(event, TurnStartedEvent):
|
|
847
|
-
# Triggered input is delivered through steer, not run_turn's texts.
|
|
848
|
-
event = replace(event, user_texts=tuple(queued.texts))
|
|
849
846
|
if isinstance(event, (TurnStartedEvent, CompactStartedEvent)):
|
|
850
847
|
self._wait_interrupted = False
|
|
851
848
|
if self._input_activity is not None and not self._steer_queue:
|
|
@@ -865,30 +862,28 @@ class AgentRuntime:
|
|
|
865
862
|
self._active_turn = {
|
|
866
863
|
"turn_id": event.turn_id,
|
|
867
864
|
"submission_id": event.submission_id or event.turn_id,
|
|
868
|
-
"
|
|
869
|
-
"user_texts": list(event.user_texts),
|
|
865
|
+
"messages": event.messages,
|
|
870
866
|
"assistant_text": "",
|
|
871
|
-
"completed_history": conversation_history_to_turns(self.agent.history),
|
|
872
867
|
"model_errors": [],
|
|
873
868
|
}
|
|
874
869
|
elif self._active_turn is not None:
|
|
875
870
|
if isinstance(event, AssistantDeltaEvent):
|
|
876
871
|
self._active_turn["assistant_text"] += event.delta
|
|
872
|
+
elif isinstance(event, MessagesAddedEvent) and any(
|
|
873
|
+
isinstance(message, AssistantMessage) for message in event.messages
|
|
874
|
+
):
|
|
875
|
+
self._active_turn["assistant_text"] = ""
|
|
877
876
|
elif isinstance(event, StreamErrorEvent):
|
|
878
877
|
self._active_turn["assistant_text"] = ""
|
|
879
878
|
self._active_turn["model_errors"].append(event.detail())
|
|
880
879
|
elif isinstance(event, ToolCompletedEvent):
|
|
881
880
|
self._active_turn["assistant_text"] = ""
|
|
882
|
-
elif isinstance(event, AutoCompactCompletedEvent):
|
|
883
|
-
self._active_turn["completed_history"] = conversation_history_to_turns(
|
|
884
|
-
self.agent.history
|
|
885
|
-
)
|
|
886
881
|
elif isinstance(
|
|
887
882
|
event, (TurnCompletedEvent, TurnFailedEvent, TurnInterruptedEvent)
|
|
888
883
|
):
|
|
889
884
|
self._active_turn = None
|
|
890
885
|
if isinstance(event, TurnStartedEvent) and not self.title:
|
|
891
|
-
prompt =
|
|
886
|
+
prompt = event.visualize()
|
|
892
887
|
if prompt:
|
|
893
888
|
self.title = shorten_title(prompt)
|
|
894
889
|
self.publish_state("auto_title")
|
pycodex/utils/compactor.py
CHANGED
|
@@ -8,6 +8,7 @@ from ..protocol import (
|
|
|
8
8
|
ModelResponse,
|
|
9
9
|
ToolCall,
|
|
10
10
|
ToolResult,
|
|
11
|
+
ToolSpec,
|
|
11
12
|
UserMessage,
|
|
12
13
|
)
|
|
13
14
|
from .random_ids import uuid7_string
|
|
@@ -70,6 +71,8 @@ async def compact_history(
|
|
|
70
71
|
history: "typing.Sequence[ConversationItem]",
|
|
71
72
|
model_client: "ModelClient",
|
|
72
73
|
context_manager: "ContextManager",
|
|
74
|
+
tools: "typing.List[ToolSpec]",
|
|
75
|
+
parallel_tool_calls: "bool",
|
|
73
76
|
stream_event_handler: "typing.Union[typing.Callable[[ModelEvent], None], None]" = None,
|
|
74
77
|
prune_tool_results_on_context_error: "bool" = False,
|
|
75
78
|
session_file: "typing.Union[str, None]" = None,
|
|
@@ -89,8 +92,8 @@ async def compact_history(
|
|
|
89
92
|
compact_prompt = UserMessage(text=DEFAULT_COMPACT_PROMPT)
|
|
90
93
|
prompt = context_manager.build_prompt(
|
|
91
94
|
list(history) + [compact_prompt],
|
|
92
|
-
|
|
93
|
-
|
|
95
|
+
tools,
|
|
96
|
+
parallel_tool_calls,
|
|
94
97
|
turn_id=turn_id,
|
|
95
98
|
reasoning_effort=model_client.reasoning_effort,
|
|
96
99
|
capture_context=False,
|
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,59 +1,92 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Message storage metadata and pure display conversion."""
|
|
2
2
|
|
|
3
|
-
import
|
|
3
|
+
import json
|
|
4
4
|
from dataclasses import replace
|
|
5
|
+
from hashlib import sha256
|
|
5
6
|
|
|
6
|
-
from ..protocol import AgentMessage, AssistantMessage,
|
|
7
|
+
from ..protocol import AgentMessage, AssistantMessage, UserMessage
|
|
7
8
|
|
|
8
9
|
|
|
9
|
-
def serialize_history_item(item
|
|
10
|
-
"""Include local message metadata without changing model serialization."""
|
|
10
|
+
def serialize_history_item(item):
|
|
11
11
|
payload = item.serialize()
|
|
12
12
|
if isinstance(item, UserMessage):
|
|
13
13
|
payload["name"] = item.name
|
|
14
14
|
if isinstance(item, (UserMessage, AgentMessage, AssistantMessage)):
|
|
15
|
-
payload
|
|
15
|
+
payload.update(message_id=item.message_id, created_at=item.created_at,
|
|
16
|
+
turn_id=item.turn_id, visible=item.visible)
|
|
16
17
|
return payload
|
|
17
18
|
|
|
18
19
|
|
|
19
|
-
def
|
|
20
|
-
"""Older rollouts use the message type's visibility default."""
|
|
20
|
+
def restore_message_metadata(item, payload, record_id, timestamp=None):
|
|
21
21
|
visible = payload.get("visible", item.visible)
|
|
22
22
|
if not isinstance(visible, bool):
|
|
23
23
|
raise ValueError("history item visible must be a boolean")
|
|
24
|
-
|
|
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
|
+
)
|
|
25
31
|
|
|
26
32
|
|
|
27
|
-
def
|
|
28
|
-
"""
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
phase
|
|
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
|
|
32
52
|
for item in history:
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
if item.
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
)
|
|
59
|
-
|
|
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:
|
|
81
|
+
continue
|
|
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
|
|
92
|
+
return tuple(turns)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Resolve provider headers using Codex's static-then-environment precedence."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import typing
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def build_http_headers(
|
|
9
|
+
http_headers: "typing.Mapping[str, str]",
|
|
10
|
+
env_http_headers: "typing.Mapping[str, str]",
|
|
11
|
+
) -> "typing.Dict[str, str]":
|
|
12
|
+
headers = {}
|
|
13
|
+
values = list(http_headers.items())
|
|
14
|
+
for name, env_var in env_http_headers.items():
|
|
15
|
+
value = os.environ.get(env_var)
|
|
16
|
+
if value is not None and value.strip():
|
|
17
|
+
values.append((name, value))
|
|
18
|
+
for name, value in values:
|
|
19
|
+
if not re.fullmatch(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+", name):
|
|
20
|
+
continue
|
|
21
|
+
if re.search(r"[\x00-\x08\x0a-\x1f\x7f]", value):
|
|
22
|
+
continue
|
|
23
|
+
# Rust HeaderValue stores UTF-8 bytes; Python HTTP clients encode Latin-1.
|
|
24
|
+
headers[name.lower()] = value.encode("utf-8").decode("latin-1")
|
|
25
|
+
return headers
|