python-codex 0.6.3__py3-none-any.whl → 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pycodex/config.py CHANGED
@@ -8,6 +8,7 @@ from .context import ContextConfig
8
8
  from .model import ResponsesProviderConfig
9
9
  from .utils.codex_config import DEFAULT_CODEX_CONFIG_PATH, read_codex_config
10
10
  from .utils.dotenv import load_codex_dotenv
11
+ from .utils.model_metadata import load_models_by_slug
11
12
 
12
13
 
13
14
  @dataclass(frozen=True)
@@ -28,9 +29,10 @@ class CodexConfig:
28
29
  path = Path(config_path)
29
30
  load_codex_dotenv(path)
30
31
  selected = read_codex_config(path, profile, use_default_profile)
32
+ model_catalog = load_models_by_slug()
31
33
  return cls(
32
34
  path=path,
33
35
  profile=selected["profile"],
34
- provider=ResponsesProviderConfig.from_mapping(selected),
35
- context=ContextConfig.from_mapping(selected, path),
36
+ provider=ResponsesProviderConfig.from_mapping(selected, model_catalog),
37
+ context=ContextConfig.from_mapping(selected, path, model_catalog),
36
38
  )
pycodex/context.py CHANGED
@@ -1,7 +1,7 @@
1
1
  import json
2
2
  import typing
3
3
  from copy import deepcopy
4
- from dataclasses import dataclass, replace
4
+ from dataclasses import dataclass, field, replace
5
5
  from datetime import datetime
6
6
  from pathlib import Path
7
7
  from uuid import UUID, uuid5
@@ -89,10 +89,13 @@ class ContextConfig:
89
89
  code_mode_only: "typing.Union[bool, None]" = None
90
90
  include_environment_context: "bool" = True
91
91
  model_slug: "typing.Union[str, None]" = None
92
+ model_catalog: "typing.Dict[str, JSONDict]" = field(
93
+ default_factory=load_models_by_slug, repr=False, compare=False,
94
+ )
92
95
 
93
96
  def __post_init__(self):
94
97
  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()
98
+ not isinstance(self.model_slug, str) or self.model_slug not in self.model_catalog
96
99
  ):
97
100
  raise ValueError("model_slug must name an entry in models.json")
98
101
  if self.code_mode_only is not None and not isinstance(self.code_mode_only, bool):
@@ -126,6 +129,7 @@ class ContextConfig:
126
129
  cls,
127
130
  selected: "typing.Mapping[str, typing.Any]",
128
131
  config_path: "typing.Union[str, Path]",
132
+ model_catalog: "typing.Union[typing.Dict[str, JSONDict], None]" = None,
129
133
  ) -> "ContextConfig":
130
134
  path = Path(config_path)
131
135
  model_instructions_file = selected.get("model_instructions_file")
@@ -152,6 +156,7 @@ class ContextConfig:
152
156
 
153
157
  return cls(
154
158
  base_instructions=_normalize_text(selected.get("base_instructions")),
159
+ model_catalog=load_models_by_slug() if model_catalog is None else model_catalog,
155
160
  developer_instructions=_normalize_text(
156
161
  selected.get("developer_instructions")
157
162
  ),
@@ -399,11 +404,15 @@ class ContextManager:
399
404
  def resolve_code_mode_only(self) -> "bool":
400
405
  if self.config.code_mode_only is not None:
401
406
  return self.config.code_mode_only
402
- metadata = model_metadata(self.config.model_slug or self.config.model)
407
+ metadata = model_metadata(
408
+ self.config.model_slug or self.config.model, self.config.model_catalog,
409
+ )
403
410
  return metadata is not None and metadata.get("tool_mode") == "code_mode_only"
404
411
 
405
412
  def resolve_model_max_context_window(self) -> "typing.Union[int, None]":
406
- metadata = model_metadata(self.config.model_slug or self.config.model)
413
+ metadata = model_metadata(
414
+ self.config.model_slug or self.config.model, self.config.model_catalog,
415
+ )
407
416
  context_window = self.config.model_context_window
408
417
  if context_window is None and metadata is not None:
409
418
  context_window = _normalize_int(metadata.get("context_window"))
@@ -413,7 +422,9 @@ class ContextManager:
413
422
  context_window = self.resolve_model_max_context_window()
414
423
  if context_window is None:
415
424
  return None
416
- metadata = model_metadata(self.config.model_slug or self.config.model)
425
+ metadata = model_metadata(
426
+ self.config.model_slug or self.config.model, self.config.model_catalog,
427
+ )
417
428
  effective_percent = None
418
429
  if metadata is not None:
419
430
  effective_percent = _normalize_int(
@@ -443,7 +454,7 @@ class ContextManager:
443
454
  model_slug = self.config.model_slug or self.config.model
444
455
  if model_slug is None:
445
456
  return None
446
- metadata = model_metadata(model_slug)
457
+ metadata = model_metadata(model_slug, self.config.model_catalog)
447
458
  if metadata is None:
448
459
  return None
449
460
  return _normalize_int(metadata.get("auto_compact_token_limit"))
@@ -452,7 +463,7 @@ class ContextManager:
452
463
  model_slug = self.config.model_slug or self.config.model
453
464
  if model_slug is None:
454
465
  return None
455
- metadata = model_metadata(model_slug)
466
+ metadata = model_metadata(model_slug, self.config.model_catalog)
456
467
  if metadata is None:
457
468
  return None
458
469
 
@@ -499,7 +510,9 @@ class ContextManager:
499
510
  )
500
511
 
501
512
  def _model_message(self, *keys):
502
- metadata = model_metadata(self.config.model_slug or self.config.model)
513
+ metadata = model_metadata(
514
+ self.config.model_slug or self.config.model, self.config.model_catalog,
515
+ )
503
516
  value = metadata.get("model_messages") if metadata is not None else None
504
517
  for key in keys:
505
518
  if value is None:
@@ -636,7 +649,9 @@ class ContextManager:
636
649
  skill.path_to_skill_md.relative_to(skill.root).as_posix(),
637
650
  )
638
651
  lines.append(f"- {skill.name}: {skill.description} (file: {path_str})")
639
- metadata = model_metadata(self.config.model_slug or self.config.model)
652
+ metadata = model_metadata(
653
+ self.config.model_slug or self.config.model, self.config.model_catalog,
654
+ )
640
655
  if metadata is None or metadata.get("include_skills_usage_instructions", True):
641
656
  lines.append("### How to use skills")
642
657
  lines.extend(SKILLS_GUIDANCE.splitlines())
pycodex/events.py CHANGED
@@ -1,11 +1,19 @@
1
- """Typed events, plain-text views and stateful presentation without frontend I/O."""
1
+ """Task-scoped notifications, typed events and frontend presentation."""
2
2
 
3
+ import asyncio
3
4
  import json
5
+ import logging
6
+ import threading
4
7
  import typing
8
+ from contextlib import contextmanager
9
+ from copy import deepcopy
5
10
  from dataclasses import dataclass
6
11
  from typing import ClassVar
7
12
 
8
- from .protocol import AgentMessage, ConversationItem, JSONDict, ToolCall, ToolResult, UserMessage
13
+ from .protocol import (
14
+ AgentMessage, ConversationItem, JSONDict, ToolCall, ToolResult, UserMessage,
15
+ )
16
+ from .utils.compat import ContextVar, copy_context
9
17
  from .utils.event_helpers import (
10
18
  colorize_cli_message,
11
19
  colorize_tool_message,
@@ -15,6 +23,7 @@ from .utils.event_helpers import (
15
23
  percent_of_context_window_remaining,
16
24
  shorten_title,
17
25
  summarize_tool_result,
26
+ visible_input_text,
18
27
  )
19
28
 
20
29
  DEFAULT_MAIN_PROMPT = "pycodex> "
@@ -128,6 +137,10 @@ class Event:
128
137
  pass
129
138
 
130
139
 
140
+ EventHandler = typing.Callable[[Event], None]
141
+ BASE_EVENT_HANDLER: "EventHandler" = lambda _event: None
142
+
143
+
131
144
  class TurnEvent(Event):
132
145
  turn_id: "str"
133
146
  submission_id: "typing.Union[str, None]"
@@ -152,10 +165,7 @@ class TurnStartedEvent(TurnEvent):
152
165
  kind: ClassVar[str] = "turn_started"
153
166
 
154
167
  def visualize(self) -> "str":
155
- return "\n".join(
156
- message.text for message in self.messages
157
- if isinstance(message, (UserMessage, AgentMessage)) and message.visible
158
- )
168
+ return visible_input_text(self.messages)
159
169
 
160
170
  def render(self, display: "EventDisplay") -> "None":
161
171
  display.begin_turn(self)
@@ -163,7 +173,7 @@ class TurnStartedEvent(TurnEvent):
163
173
 
164
174
  @dataclass(frozen=True)
165
175
  class TurnInputReadyEvent(TurnEvent):
166
- """Synchronous input coordination; delivery failures must fail the turn."""
176
+ """Pending input has been delivered for the next sample."""
167
177
 
168
178
  turn_id: "str"
169
179
  submission_id: "typing.Union[str, None]" = None
@@ -725,3 +735,102 @@ class InputResolvedEvent(Event):
725
735
 
726
736
  def render(self, display: "EventDisplay") -> "None":
727
737
  display.set_prompt(display.main_prompt())
738
+
739
+
740
+ class TurnInterrupted(RuntimeError):
741
+ def __init__(self):
742
+ super().__init__("turn interrupted")
743
+
744
+
745
+ class ModelRequestInterrupted(RuntimeError):
746
+ """A cooperative stop ended retries after an issued request finished."""
747
+
748
+
749
+ class EventScope:
750
+ """Task-scoped observer binding, isolation and worker-thread forwarding."""
751
+
752
+ _current_observer = ContextVar("pycodex_event_observer", default=BASE_EVENT_HANDLER)
753
+
754
+ @staticmethod
755
+ def router(fn):
756
+ """Mark an internal forwarder that delegates leaf isolation to notify."""
757
+ fn._event_router = True
758
+ return fn
759
+
760
+ @classmethod
761
+ def wrap(cls, observer):
762
+ if observer is BASE_EVENT_HANDLER or getattr(observer, "_event_router", False) is True:
763
+ return observer
764
+ return lambda event: cls.notify(event, observer)
765
+
766
+ @classmethod
767
+ @contextmanager
768
+ def _bind(cls, dispatch):
769
+ token = cls._current_observer.set(dispatch)
770
+ try:
771
+ yield
772
+ finally:
773
+ cls._current_observer.reset(token)
774
+
775
+ @classmethod
776
+ @contextmanager
777
+ def observe(cls, observer):
778
+ """Bind a notification recipient for this execution and its child tasks."""
779
+ with cls._bind(cls.wrap(observer)):
780
+ yield
781
+
782
+ @classmethod
783
+ def current(cls):
784
+ return cls._current_observer.get()
785
+
786
+ @classmethod
787
+ def emit(cls, event):
788
+ """Publish an event to the observer bound in the current task scope."""
789
+ cls._current_observer.get()(event)
790
+
791
+ @classmethod
792
+ def notify(cls, event, *observers):
793
+ for observer in observers:
794
+ if observer is BASE_EVENT_HANDLER:
795
+ continue
796
+ try:
797
+ observer(deepcopy(event))
798
+ except (Exception, asyncio.CancelledError) as exc:
799
+ cls.report_observer_error("Agent event observer failed: " + event.kind, exc)
800
+
801
+ @staticmethod
802
+ def report_observer_error(message, exc):
803
+ try:
804
+ loop = asyncio.get_running_loop()
805
+ except RuntimeError:
806
+ logging.getLogger(__name__).error(message, exc_info=(type(exc), exc, exc.__traceback__))
807
+ else:
808
+ loop.call_exception_handler({"message": message, "exception": exc})
809
+
810
+ @classmethod
811
+ @contextmanager
812
+ def worker_events(cls, observer=None):
813
+ """Forward worker events to the caller's loop until the request exits."""
814
+ loop = asyncio.get_running_loop()
815
+ lock = threading.Lock()
816
+ active = True
817
+
818
+ def deliver(event):
819
+ if active:
820
+ owner.run(cls.emit, event)
821
+
822
+ def post(event):
823
+ with lock:
824
+ if active:
825
+ loop.call_soon_threadsafe(deliver, event)
826
+
827
+ scope = cls._bind(cls.current()) if observer is None else cls.observe(observer)
828
+ with scope:
829
+ owner = copy_context()
830
+ with cls._bind(post):
831
+ worker = copy_context()
832
+ try:
833
+ yield worker
834
+ finally:
835
+ with lock:
836
+ active = False