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/agent.py
CHANGED
|
@@ -13,6 +13,7 @@ from .events import (
|
|
|
13
13
|
CompactFailedEvent,
|
|
14
14
|
CompactStartedEvent,
|
|
15
15
|
Event,
|
|
16
|
+
MessagesAddedEvent,
|
|
16
17
|
ModelCalledEvent,
|
|
17
18
|
ModelCompletedEvent,
|
|
18
19
|
ModelEvent,
|
|
@@ -112,12 +113,14 @@ class Agent:
|
|
|
112
113
|
self._parallel_tool_calls = parallel_tool_calls
|
|
113
114
|
self.event_handler = event_handler
|
|
114
115
|
self._history: "typing.List[ConversationItem]" = list(initial_history)
|
|
116
|
+
self.history_revision = uuid7_string()
|
|
115
117
|
# Agent identity stays fixed when resume changes the rollout session.
|
|
116
118
|
self.agent_id = session_id
|
|
117
119
|
self.agent_path = agent_path
|
|
118
120
|
self._configure_recording(session_id, session_file_path)
|
|
119
121
|
self._last_total_usage_tokens: "typing.Union[int, None]" = None
|
|
120
122
|
self._idle: "typing.Union[asyncio.Event, None]" = None
|
|
123
|
+
self._active_turn_id: "typing.Union[str, None]" = None
|
|
121
124
|
self.is_shutdown = False
|
|
122
125
|
self.accepts_input = True
|
|
123
126
|
self._stop_requested = False
|
|
@@ -200,6 +203,7 @@ class Agent:
|
|
|
200
203
|
restored_history = list(resumed["history"])
|
|
201
204
|
self._configure_recording(session_id, resumed["rollout_path"], resume=True)
|
|
202
205
|
self._history = restored_history
|
|
206
|
+
self.history_revision = uuid7_string()
|
|
203
207
|
self.context_manager.reset_history_context()
|
|
204
208
|
self._last_total_usage_tokens = None
|
|
205
209
|
self.is_shutdown = False
|
|
@@ -209,7 +213,7 @@ class Agent:
|
|
|
209
213
|
def ask(self, text: "str") -> "TurnResult":
|
|
210
214
|
from .utils.async_bridge import run_async
|
|
211
215
|
|
|
212
|
-
return run_async(self.run_turn([text]))
|
|
216
|
+
return run_async(self.run_turn([UserMessage(text)]))
|
|
213
217
|
|
|
214
218
|
def _configure_recording(
|
|
215
219
|
self,
|
|
@@ -260,8 +264,8 @@ class Agent:
|
|
|
260
264
|
self._idle = None
|
|
261
265
|
|
|
262
266
|
async def run_turn(
|
|
263
|
-
self,
|
|
264
|
-
|
|
267
|
+
self, messages: "typing.Iterable[typing.Union[UserMessage, AgentMessage, ToolResult]]",
|
|
268
|
+
turn_id: "typing.Union[str, None]" = None,
|
|
265
269
|
) -> "TurnResult":
|
|
266
270
|
if self.is_shutdown:
|
|
267
271
|
raise RuntimeError("agent is shutdown")
|
|
@@ -271,18 +275,18 @@ class Agent:
|
|
|
271
275
|
self._follow_up_requested = False
|
|
272
276
|
self._idle = asyncio.Event()
|
|
273
277
|
turn = _TurnState(turn_id or uuid7_string())
|
|
278
|
+
self._active_turn_id = turn.turn_id
|
|
274
279
|
try:
|
|
275
|
-
self.
|
|
280
|
+
messages = self._bind_turn(messages)
|
|
281
|
+
self._emit(TurnStartedEvent(turn.turn_id, messages))
|
|
276
282
|
while True:
|
|
277
283
|
phase = "pre_turn" if turn.iteration == 0 else "mid_turn"
|
|
278
284
|
await self._maybe_auto_compact(turn.turn_id, phase)
|
|
285
|
+
if turn.iteration == 0:
|
|
286
|
+
self._append_history(messages)
|
|
279
287
|
self._follow_up_requested = False
|
|
280
288
|
# Input delivery commits history; its failures must fail the turn.
|
|
281
289
|
self.event_handler(TurnInputReadyEvent(turn.turn_id))
|
|
282
|
-
if turn.iteration == 0:
|
|
283
|
-
self.receive_messages(
|
|
284
|
-
tuple(UserMessage(text=text, name=name) for text in texts)
|
|
285
|
-
)
|
|
286
290
|
response = await self._sample(turn)
|
|
287
291
|
self._emit(
|
|
288
292
|
ModelCompletedEvent(
|
|
@@ -347,6 +351,7 @@ class Agent:
|
|
|
347
351
|
finally:
|
|
348
352
|
self._stop_requested = False
|
|
349
353
|
self._follow_up_requested = False
|
|
354
|
+
self._active_turn_id = None
|
|
350
355
|
self._idle.set()
|
|
351
356
|
self._idle = None
|
|
352
357
|
|
|
@@ -479,14 +484,30 @@ class Agent:
|
|
|
479
484
|
)
|
|
480
485
|
return None
|
|
481
486
|
|
|
487
|
+
def _bind_turn(
|
|
488
|
+
self, items: "typing.Iterable[ConversationItem]"
|
|
489
|
+
) -> "typing.Tuple[ConversationItem, ...]":
|
|
490
|
+
turn_id = self._active_turn_id
|
|
491
|
+
return tuple(
|
|
492
|
+
item if isinstance(item, (ToolCall, ToolResult, ReasoningItem))
|
|
493
|
+
else replace(item, turn_id=turn_id) if turn_id is not None
|
|
494
|
+
else item
|
|
495
|
+
for item in items
|
|
496
|
+
)
|
|
497
|
+
|
|
482
498
|
def _append_history(
|
|
483
499
|
self,
|
|
484
500
|
items: "typing.Iterable[ConversationItem]",
|
|
485
501
|
) -> "None":
|
|
486
|
-
items =
|
|
502
|
+
items = self._bind_turn(items)
|
|
487
503
|
if self._rollout_recorder is not None:
|
|
488
504
|
self._rollout_recorder.append_history_items(items, self._history)
|
|
489
505
|
self._history.extend(items)
|
|
506
|
+
messages = tuple(
|
|
507
|
+
item for item in items if isinstance(item, (UserMessage, AgentMessage, AssistantMessage))
|
|
508
|
+
)
|
|
509
|
+
if messages:
|
|
510
|
+
self._emit(MessagesAddedEvent(messages[0].turn_id or "", messages))
|
|
490
511
|
|
|
491
512
|
def _handle_model_stream_event(self, turn_id: "str", event: "ModelEvent") -> "None":
|
|
492
513
|
if isinstance(event, TokenCountEvent):
|
|
@@ -583,6 +604,10 @@ class Agent:
|
|
|
583
604
|
self.history,
|
|
584
605
|
self.model_client,
|
|
585
606
|
self.context_manager,
|
|
607
|
+
self.tool_registry.model_visible_specs(
|
|
608
|
+
self.context_manager.resolve_code_mode_only(),
|
|
609
|
+
),
|
|
610
|
+
self._parallel_tool_calls,
|
|
586
611
|
handle_compact_stream_event,
|
|
587
612
|
prune_tool_results_on_context_error,
|
|
588
613
|
str(recorder.rollout_path) if recorder is not None else None,
|
|
@@ -592,6 +617,7 @@ class Agent:
|
|
|
592
617
|
if recorder is not None:
|
|
593
618
|
recorder.append_compacted_history(compact_result.history, self._history)
|
|
594
619
|
self._history = list(compact_result.history)
|
|
620
|
+
self.history_revision = uuid7_string()
|
|
595
621
|
self.context_manager.reset_history_context()
|
|
596
622
|
self._last_total_usage_tokens = None
|
|
597
623
|
except Exception as exc:
|
pycodex/bootstrap.py
CHANGED
|
@@ -8,6 +8,7 @@ from .model import (
|
|
|
8
8
|
ResponsesProviderConfig,
|
|
9
9
|
)
|
|
10
10
|
from .utils import get_debug_dir
|
|
11
|
+
from .utils.http_headers import build_http_headers
|
|
11
12
|
|
|
12
13
|
if typing.TYPE_CHECKING:
|
|
13
14
|
from responses_server import ManagedResponseServer
|
|
@@ -121,10 +122,14 @@ def build_model(
|
|
|
121
122
|
)
|
|
122
123
|
os.environ.setdefault(LOCAL_RESPONSES_SERVER_API_KEY_ENV, "dummy")
|
|
123
124
|
elif vllm_endpoint is not None or compat_api != "none":
|
|
125
|
+
headers = build_http_headers(
|
|
126
|
+
provider_config.http_headers, provider_config.env_http_headers,
|
|
127
|
+
)
|
|
124
128
|
if vllm_endpoint:
|
|
125
129
|
managed_server = launch_chat_completion_compat_server(
|
|
126
130
|
vllm_endpoint,
|
|
127
131
|
model_provider="vllm",
|
|
132
|
+
http_headers=headers,
|
|
128
133
|
)
|
|
129
134
|
else:
|
|
130
135
|
managed_server = launch_chat_completion_compat_server(
|
|
@@ -132,6 +137,7 @@ def build_model(
|
|
|
132
137
|
provider_config.api_key_env,
|
|
133
138
|
model_provider=provider_config.provider_name,
|
|
134
139
|
outcomming_api=compat_api,
|
|
140
|
+
http_headers=headers,
|
|
135
141
|
)
|
|
136
142
|
url, key_env = (
|
|
137
143
|
managed_server.base_url,
|
|
@@ -143,6 +149,8 @@ def build_model(
|
|
|
143
149
|
provider_config,
|
|
144
150
|
base_url=url,
|
|
145
151
|
api_key_env=key_env,
|
|
152
|
+
http_headers={} if uses_local_responses_compat else provider_config.http_headers,
|
|
153
|
+
env_http_headers={} if uses_local_responses_compat else provider_config.env_http_headers,
|
|
146
154
|
responses_lite_override=(
|
|
147
155
|
False
|
|
148
156
|
if uses_local_responses_compat
|
pycodex/context.py
CHANGED
|
@@ -10,7 +10,7 @@ from xml.sax.saxutils import escape
|
|
|
10
10
|
import yaml
|
|
11
11
|
|
|
12
12
|
from .utils.codex_config import read_codex_config
|
|
13
|
-
from .utils.model_metadata import model_metadata
|
|
13
|
+
from .utils.model_metadata import load_models_by_slug, model_metadata
|
|
14
14
|
from .protocol import (
|
|
15
15
|
ContextMessage, ConversationItem, JSONDict, Prompt, ToolCall, ToolResult, ToolSpec, UserMessage,
|
|
16
16
|
)
|
|
@@ -87,8 +87,14 @@ class ContextConfig:
|
|
|
87
87
|
multi_agent_subagent_instructions: "typing.Union[str, None]" = None
|
|
88
88
|
multi_agent_hint: "typing.Union[str, None]" = None
|
|
89
89
|
code_mode_only: "typing.Union[bool, None]" = None
|
|
90
|
+
include_environment_context: "bool" = True
|
|
91
|
+
model_slug: "typing.Union[str, None]" = None
|
|
90
92
|
|
|
91
93
|
def __post_init__(self):
|
|
94
|
+
if self.model_slug is not None and (
|
|
95
|
+
not isinstance(self.model_slug, str) or self.model_slug not in load_models_by_slug()
|
|
96
|
+
):
|
|
97
|
+
raise ValueError("model_slug must name an entry in models.json")
|
|
92
98
|
if self.code_mode_only is not None and not isinstance(self.code_mode_only, bool):
|
|
93
99
|
raise ValueError("code_mode_only must be a boolean")
|
|
94
100
|
if (
|
|
@@ -155,6 +161,7 @@ class ContextConfig:
|
|
|
155
161
|
codex_home=codex_home,
|
|
156
162
|
project_doc_max_bytes=_normalize_int(selected.get("project_doc_max_bytes")),
|
|
157
163
|
model=_normalize_text(selected.get("model")),
|
|
164
|
+
model_slug=selected.get("model_slug"),
|
|
158
165
|
model_context_window=_normalize_int(selected.get("model_context_window")),
|
|
159
166
|
model_auto_compact_token_limit=_normalize_int(
|
|
160
167
|
selected.get("model_auto_compact_token_limit")
|
|
@@ -228,6 +235,8 @@ class ContextManager:
|
|
|
228
235
|
|
|
229
236
|
def get_turn_metadata(self, turn_id: "str") -> "JSONDict":
|
|
230
237
|
metadata: "JSONDict" = {"turn_id": turn_id}
|
|
238
|
+
if not self.config.include_environment_context:
|
|
239
|
+
return metadata
|
|
231
240
|
if self._workspace_metadata_turn_id is None:
|
|
232
241
|
self._workspace_metadata_turn_id = turn_id
|
|
233
242
|
self._workspace_metadata_cache = get_workspace_turn_metadata(self.cwd)
|
|
@@ -390,11 +399,11 @@ class ContextManager:
|
|
|
390
399
|
def resolve_code_mode_only(self) -> "bool":
|
|
391
400
|
if self.config.code_mode_only is not None:
|
|
392
401
|
return self.config.code_mode_only
|
|
393
|
-
metadata = model_metadata(self.config.model)
|
|
402
|
+
metadata = model_metadata(self.config.model_slug or self.config.model)
|
|
394
403
|
return metadata is not None and metadata.get("tool_mode") == "code_mode_only"
|
|
395
404
|
|
|
396
405
|
def resolve_model_max_context_window(self) -> "typing.Union[int, None]":
|
|
397
|
-
metadata = model_metadata(self.config.model)
|
|
406
|
+
metadata = model_metadata(self.config.model_slug or self.config.model)
|
|
398
407
|
context_window = self.config.model_context_window
|
|
399
408
|
if context_window is None and metadata is not None:
|
|
400
409
|
context_window = _normalize_int(metadata.get("context_window"))
|
|
@@ -404,7 +413,7 @@ class ContextManager:
|
|
|
404
413
|
context_window = self.resolve_model_max_context_window()
|
|
405
414
|
if context_window is None:
|
|
406
415
|
return None
|
|
407
|
-
metadata = model_metadata(self.config.model)
|
|
416
|
+
metadata = model_metadata(self.config.model_slug or self.config.model)
|
|
408
417
|
effective_percent = None
|
|
409
418
|
if metadata is not None:
|
|
410
419
|
effective_percent = _normalize_int(
|
|
@@ -431,7 +440,7 @@ class ContextManager:
|
|
|
431
440
|
if self.config.model_auto_compact_token_limit is not None:
|
|
432
441
|
return self.config.model_auto_compact_token_limit
|
|
433
442
|
|
|
434
|
-
model_slug = self.config.model
|
|
443
|
+
model_slug = self.config.model_slug or self.config.model
|
|
435
444
|
if model_slug is None:
|
|
436
445
|
return None
|
|
437
446
|
metadata = model_metadata(model_slug)
|
|
@@ -440,7 +449,7 @@ class ContextManager:
|
|
|
440
449
|
return _normalize_int(metadata.get("auto_compact_token_limit"))
|
|
441
450
|
|
|
442
451
|
def _resolve_model_instructions(self) -> "typing.Union[str, None]":
|
|
443
|
-
model_slug = self.config.model
|
|
452
|
+
model_slug = self.config.model_slug or self.config.model
|
|
444
453
|
if model_slug is None:
|
|
445
454
|
return None
|
|
446
455
|
metadata = model_metadata(model_slug)
|
|
@@ -490,7 +499,7 @@ class ContextManager:
|
|
|
490
499
|
)
|
|
491
500
|
|
|
492
501
|
def _model_message(self, *keys):
|
|
493
|
-
metadata = model_metadata(self.config.model)
|
|
502
|
+
metadata = model_metadata(self.config.model_slug or self.config.model)
|
|
494
503
|
value = metadata.get("model_messages") if metadata is not None else None
|
|
495
504
|
for key in keys:
|
|
496
505
|
if value is None:
|
|
@@ -627,7 +636,7 @@ class ContextManager:
|
|
|
627
636
|
skill.path_to_skill_md.relative_to(skill.root).as_posix(),
|
|
628
637
|
)
|
|
629
638
|
lines.append(f"- {skill.name}: {skill.description} (file: {path_str})")
|
|
630
|
-
metadata = model_metadata(self.config.model)
|
|
639
|
+
metadata = model_metadata(self.config.model_slug or self.config.model)
|
|
631
640
|
if metadata is None or metadata.get("include_skills_usage_instructions", True):
|
|
632
641
|
lines.append("### How to use skills")
|
|
633
642
|
lines.extend(SKILLS_GUIDANCE.splitlines())
|
|
@@ -635,44 +644,24 @@ class ContextManager:
|
|
|
635
644
|
return f"{SKILLS_OPEN_TAG}\n{body}\n{SKILLS_CLOSE_TAG}"
|
|
636
645
|
|
|
637
646
|
def _discover_skills(self) -> "typing.List[SkillDescriptor]":
|
|
638
|
-
|
|
639
|
-
if codex_home is None:
|
|
640
|
-
return []
|
|
641
|
-
|
|
642
|
-
user_root = codex_home / "skills"
|
|
643
|
-
system_root = user_root / ".system"
|
|
644
|
-
discovered: "typing.List[SkillDescriptor]" = []
|
|
645
|
-
seen: "typing.Set[Path]" = set()
|
|
646
|
-
|
|
647
|
-
user_paths = _discover_skill_files(user_root, excluded_root=system_root)
|
|
648
|
-
system_paths = _discover_skill_files(system_root)
|
|
649
|
-
|
|
650
|
-
for scope_rank, root, paths in (
|
|
651
|
-
(3, user_root, user_paths),
|
|
652
|
-
(0, system_root, system_paths),
|
|
653
|
-
):
|
|
654
|
-
for path in paths:
|
|
655
|
-
resolved = path.resolve()
|
|
656
|
-
if resolved in seen:
|
|
657
|
-
continue
|
|
658
|
-
seen.add(resolved)
|
|
659
|
-
descriptor = _parse_skill_descriptor(path, scope_rank, root)
|
|
660
|
-
if descriptor is not None:
|
|
661
|
-
discovered.append(descriptor)
|
|
662
|
-
|
|
663
|
-
return discovered
|
|
647
|
+
return discover_skills(self.config.codex_home)
|
|
664
648
|
|
|
665
649
|
def _build_contextual_user_messages(self) -> "typing.List[ContextMessage]":
|
|
666
650
|
sections: "typing.List[str]" = []
|
|
667
651
|
user_instructions = self._merged_user_instructions()
|
|
668
652
|
if user_instructions is not None:
|
|
653
|
+
heading = (
|
|
654
|
+
f"{USER_INSTRUCTIONS_PREFIX}{self.cwd}"
|
|
655
|
+
if self.config.include_environment_context else "# User instructions"
|
|
656
|
+
)
|
|
669
657
|
sections.append(
|
|
670
658
|
(
|
|
671
|
-
f"{
|
|
659
|
+
f"{heading}\n\n"
|
|
672
660
|
f"<INSTRUCTIONS>\n{user_instructions}\n</INSTRUCTIONS>"
|
|
673
661
|
)
|
|
674
662
|
)
|
|
675
|
-
|
|
663
|
+
if self.config.include_environment_context:
|
|
664
|
+
sections.append(self._serialize_environment_context())
|
|
676
665
|
sections.extend(self._extra_contextual_user_messages)
|
|
677
666
|
if not sections:
|
|
678
667
|
return []
|
|
@@ -960,3 +949,32 @@ def build_goal_message(goal, budget_limited=False):
|
|
|
960
949
|
token_budget="none" if budget is None else budget,
|
|
961
950
|
remaining_tokens="unbounded" if budget is None else max(0, budget - goal["tokensUsed"]),
|
|
962
951
|
))
|
|
952
|
+
|
|
953
|
+
|
|
954
|
+
def discover_skills(codex_home):
|
|
955
|
+
"""Discover the same skill descriptors used in model context and input menus."""
|
|
956
|
+
if codex_home is None:
|
|
957
|
+
return []
|
|
958
|
+
|
|
959
|
+
user_root = codex_home / "skills"
|
|
960
|
+
system_root = user_root / ".system"
|
|
961
|
+
discovered: "typing.List[SkillDescriptor]" = []
|
|
962
|
+
seen: "typing.Set[Path]" = set()
|
|
963
|
+
|
|
964
|
+
user_paths = _discover_skill_files(user_root, excluded_root=system_root)
|
|
965
|
+
system_paths = _discover_skill_files(system_root)
|
|
966
|
+
|
|
967
|
+
for scope_rank, root, paths in (
|
|
968
|
+
(3, user_root, user_paths),
|
|
969
|
+
(0, system_root, system_paths),
|
|
970
|
+
):
|
|
971
|
+
for path in paths:
|
|
972
|
+
resolved = path.resolve()
|
|
973
|
+
if resolved in seen:
|
|
974
|
+
continue
|
|
975
|
+
seen.add(resolved)
|
|
976
|
+
descriptor = _parse_skill_descriptor(path, scope_rank, root)
|
|
977
|
+
if descriptor is not None:
|
|
978
|
+
discovered.append(descriptor)
|
|
979
|
+
|
|
980
|
+
return discovered
|
pycodex/events.py
CHANGED
|
@@ -5,7 +5,7 @@ import typing
|
|
|
5
5
|
from dataclasses import dataclass
|
|
6
6
|
from typing import ClassVar
|
|
7
7
|
|
|
8
|
-
from .protocol import JSONDict, ToolCall, ToolResult
|
|
8
|
+
from .protocol import AgentMessage, ConversationItem, JSONDict, ToolCall, ToolResult, UserMessage
|
|
9
9
|
from .utils.event_helpers import (
|
|
10
10
|
colorize_cli_message,
|
|
11
11
|
colorize_tool_message,
|
|
@@ -147,12 +147,15 @@ class TerminalEvent(TurnEvent):
|
|
|
147
147
|
@dataclass(frozen=True)
|
|
148
148
|
class TurnStartedEvent(TurnEvent):
|
|
149
149
|
turn_id: "str"
|
|
150
|
-
|
|
150
|
+
messages: "typing.Tuple[ConversationItem, ...]"
|
|
151
151
|
submission_id: "typing.Union[str, None]" = None
|
|
152
152
|
kind: ClassVar[str] = "turn_started"
|
|
153
153
|
|
|
154
154
|
def visualize(self) -> "str":
|
|
155
|
-
return "\n".join(
|
|
155
|
+
return "\n".join(
|
|
156
|
+
message.text for message in self.messages
|
|
157
|
+
if isinstance(message, (UserMessage, AgentMessage)) and message.visible
|
|
158
|
+
)
|
|
156
159
|
|
|
157
160
|
def render(self, display: "EventDisplay") -> "None":
|
|
158
161
|
display.begin_turn(self)
|
|
@@ -167,6 +170,16 @@ class TurnInputReadyEvent(TurnEvent):
|
|
|
167
170
|
kind: ClassVar[str] = "turn_input_ready"
|
|
168
171
|
|
|
169
172
|
|
|
173
|
+
@dataclass(frozen=True)
|
|
174
|
+
class MessagesAddedEvent(TurnEvent):
|
|
175
|
+
"""Conversation items committed to history, in their original order."""
|
|
176
|
+
|
|
177
|
+
turn_id: "str"
|
|
178
|
+
messages: "typing.Tuple[ConversationItem, ...]"
|
|
179
|
+
submission_id: "typing.Union[str, None]" = None
|
|
180
|
+
kind: ClassVar[str] = "messages_added"
|
|
181
|
+
|
|
182
|
+
|
|
170
183
|
@dataclass(frozen=True)
|
|
171
184
|
class TurnCompletedEvent(TerminalEvent):
|
|
172
185
|
turn_id: "str"
|
|
@@ -564,11 +577,7 @@ class SessionStateEvent(Event):
|
|
|
564
577
|
display.inserted_steer_prompts.clear()
|
|
565
578
|
active = state["active_turn"]
|
|
566
579
|
if active is not None:
|
|
567
|
-
|
|
568
|
-
active["turn_id"],
|
|
569
|
-
tuple(active["user_texts"]),
|
|
570
|
-
active["submission_id"],
|
|
571
|
-
).render(display)
|
|
580
|
+
display.set_status("working")
|
|
572
581
|
display.stream_buffer = active["assistant_text"]
|
|
573
582
|
elif not state["busy"]:
|
|
574
583
|
display.set_idle_status(state["background_work_count"])
|
|
@@ -636,7 +645,7 @@ class CommandFailedEvent(Event):
|
|
|
636
645
|
@dataclass(frozen=True)
|
|
637
646
|
class InputQueuedEvent(Event):
|
|
638
647
|
submission_id: "str"
|
|
639
|
-
|
|
648
|
+
message: "UserMessage"
|
|
640
649
|
queue: "str"
|
|
641
650
|
sender: "str"
|
|
642
651
|
explicit_queue: "bool"
|
|
@@ -644,7 +653,7 @@ class InputQueuedEvent(Event):
|
|
|
644
653
|
kind: ClassVar[str] = "input_queued"
|
|
645
654
|
|
|
646
655
|
def render(self, display: "EventDisplay") -> "None":
|
|
647
|
-
preview = shorten_title(self.
|
|
656
|
+
preview = shorten_title(self.message.text, 72)
|
|
648
657
|
if self.explicit_queue:
|
|
649
658
|
display.queued_steer_prompts.setdefault(self.submission_id, []).append(
|
|
650
659
|
preview
|
pycodex/model.py
CHANGED
|
@@ -17,6 +17,7 @@ from urllib3.exceptions import ReadTimeoutError
|
|
|
17
17
|
|
|
18
18
|
from .utils.compat import Protocol
|
|
19
19
|
from .utils.codex_config import DEFAULT_CODEX_CONFIG_PATH, read_codex_config
|
|
20
|
+
from .utils.http_headers import build_http_headers
|
|
20
21
|
|
|
21
22
|
from .events import (
|
|
22
23
|
AssistantDeltaEvent,
|
|
@@ -26,7 +27,7 @@ from .events import (
|
|
|
26
27
|
TokenCountEvent,
|
|
27
28
|
ToolCalledEvent,
|
|
28
29
|
)
|
|
29
|
-
from .utils.model_metadata import model_metadata
|
|
30
|
+
from .utils.model_metadata import load_models_by_slug, model_metadata
|
|
30
31
|
from .protocol import (
|
|
31
32
|
AssistantMessage,
|
|
32
33
|
JSONDict,
|
|
@@ -113,8 +114,22 @@ class ResponsesProviderConfig:
|
|
|
113
114
|
fallback_cooldown_seconds: "int" = 900
|
|
114
115
|
stream_first_data_timeout_ms: "typing.Union[int, None]" = None
|
|
115
116
|
compat_api: "str" = "none"
|
|
117
|
+
model_slug: "typing.Union[str, None]" = None
|
|
118
|
+
http_headers: "typing.Dict[str, str]" = field(default_factory=dict, repr=False)
|
|
119
|
+
env_http_headers: "typing.Dict[str, str]" = field(default_factory=dict)
|
|
116
120
|
|
|
117
121
|
def __post_init__(self):
|
|
122
|
+
for name in ("http_headers", "env_http_headers"):
|
|
123
|
+
headers = getattr(self, name)
|
|
124
|
+
if not isinstance(headers, dict) or any(
|
|
125
|
+
not isinstance(key, str) or not isinstance(value, str)
|
|
126
|
+
for key, value in headers.items()
|
|
127
|
+
):
|
|
128
|
+
raise ValueError(name + " must be a table of strings")
|
|
129
|
+
if self.model_slug is not None and (
|
|
130
|
+
not isinstance(self.model_slug, str) or self.model_slug not in load_models_by_slug()
|
|
131
|
+
):
|
|
132
|
+
raise ValueError("model_slug must name an entry in models.json")
|
|
118
133
|
if self.compat_api not in ("none", "chat_completions", "messages", "gemini"):
|
|
119
134
|
raise ValueError("compat_api must be none, chat_completions, messages or gemini")
|
|
120
135
|
cooldown = self.fallback_cooldown_seconds
|
|
@@ -186,9 +201,12 @@ class ResponsesProviderConfig:
|
|
|
186
201
|
raise ValueError("fallback_models must be an array of non-empty model IDs")
|
|
187
202
|
return cls(
|
|
188
203
|
model=selected["model"],
|
|
204
|
+
model_slug=selected.get("model_slug"),
|
|
189
205
|
provider_name=provider_name,
|
|
190
206
|
base_url=provider["base_url"],
|
|
191
207
|
api_key_env=api_key_env,
|
|
208
|
+
http_headers=provider.get("http_headers", {}),
|
|
209
|
+
env_http_headers=provider.get("env_http_headers", {}),
|
|
192
210
|
compat_api=compat_api,
|
|
193
211
|
wire_api=wire_api,
|
|
194
212
|
query_params=query_params,
|
|
@@ -228,7 +246,7 @@ class ResponsesProviderConfig:
|
|
|
228
246
|
return max(int(self.stream_idle_timeout_ms), 1) / 1000.0
|
|
229
247
|
|
|
230
248
|
def metadata(self) -> "typing.Union[JSONDict, None]":
|
|
231
|
-
return model_metadata(self.model)
|
|
249
|
+
return model_metadata(self.model_slug or self.model)
|
|
232
250
|
|
|
233
251
|
def use_responses_lite(self) -> "bool":
|
|
234
252
|
if self.responses_lite_override is not None:
|
|
@@ -447,6 +465,9 @@ class ResponsesModelClient:
|
|
|
447
465
|
openai_subagent: "typing.Union[str, None]" = None,
|
|
448
466
|
) -> "None":
|
|
449
467
|
self._config = config
|
|
468
|
+
self._provider_headers = build_http_headers(
|
|
469
|
+
config.http_headers, config.env_http_headers,
|
|
470
|
+
)
|
|
450
471
|
self._timeout_seconds = timeout_seconds
|
|
451
472
|
self._session_id = session_id or uuid7_string()
|
|
452
473
|
self.recording_metadata = ModelRecordingMetadata(originator, config.provider_name)
|
|
@@ -804,7 +825,7 @@ class ResponsesModelClient:
|
|
|
804
825
|
session_id = self._session_id if prompt.session_id is None else prompt.session_id
|
|
805
826
|
use_responses_lite = self._config.use_responses_lite()
|
|
806
827
|
input_items = [item.serialize() for item in prompt.input]
|
|
807
|
-
_filter_audio_inputs(input_items,
|
|
828
|
+
_filter_audio_inputs(input_items, self._config.metadata())
|
|
808
829
|
if use_responses_lite:
|
|
809
830
|
_strip_image_details(input_items)
|
|
810
831
|
|
|
@@ -936,12 +957,15 @@ class ResponsesModelClient:
|
|
|
936
957
|
session_id = self._session_id if prompt.session_id is None else prompt.session_id
|
|
937
958
|
headers = {
|
|
938
959
|
"content-type": "application/json",
|
|
939
|
-
"accept": "text/event-stream",
|
|
940
|
-
"x-client-request-id": session_id,
|
|
941
|
-
"session_id": session_id,
|
|
942
960
|
"originator": self.recording_metadata.originator,
|
|
943
961
|
"user-agent": self._user_agent,
|
|
944
962
|
}
|
|
963
|
+
headers.update(self._provider_headers)
|
|
964
|
+
headers.update({
|
|
965
|
+
"accept": "text/event-stream",
|
|
966
|
+
"x-client-request-id": session_id,
|
|
967
|
+
"session_id": session_id,
|
|
968
|
+
})
|
|
945
969
|
api_key = self._config.api_key()
|
|
946
970
|
if api_key is not None:
|
|
947
971
|
headers["authorization"] = f"Bearer {api_key}"
|
|
@@ -960,10 +984,11 @@ class ResponsesModelClient:
|
|
|
960
984
|
|
|
961
985
|
def _build_model_list_headers(self) -> "typing.Dict[str, str]":
|
|
962
986
|
headers = {
|
|
963
|
-
"accept": "application/json",
|
|
964
987
|
"originator": self.recording_metadata.originator,
|
|
965
988
|
"user-agent": self._user_agent,
|
|
966
989
|
}
|
|
990
|
+
headers.update(self._provider_headers)
|
|
991
|
+
headers["accept"] = "application/json"
|
|
967
992
|
api_key = self._config.api_key()
|
|
968
993
|
if api_key is not None:
|
|
969
994
|
headers["authorization"] = f"Bearer {api_key}"
|