python-codex 0.6.1__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/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,
@@ -118,6 +119,7 @@ class Agent:
118
119
  self._configure_recording(session_id, session_file_path)
119
120
  self._last_total_usage_tokens: "typing.Union[int, None]" = None
120
121
  self._idle: "typing.Union[asyncio.Event, None]" = None
122
+ self._active_turn_id: "typing.Union[str, None]" = None
121
123
  self.is_shutdown = False
122
124
  self.accepts_input = True
123
125
  self._stop_requested = False
@@ -209,7 +211,7 @@ class Agent:
209
211
  def ask(self, text: "str") -> "TurnResult":
210
212
  from .utils.async_bridge import run_async
211
213
 
212
- return run_async(self.run_turn([text]))
214
+ return run_async(self.run_turn([UserMessage(text)]))
213
215
 
214
216
  def _configure_recording(
215
217
  self,
@@ -260,8 +262,8 @@ class Agent:
260
262
  self._idle = None
261
263
 
262
264
  async def run_turn(
263
- self, texts: "typing.List[str]", turn_id: "typing.Union[str, None]" = None,
264
- name: "str" = "user",
265
+ self, messages: "typing.Iterable[typing.Union[UserMessage, AgentMessage, ToolResult]]",
266
+ turn_id: "typing.Union[str, None]" = None,
265
267
  ) -> "TurnResult":
266
268
  if self.is_shutdown:
267
269
  raise RuntimeError("agent is shutdown")
@@ -271,18 +273,18 @@ class Agent:
271
273
  self._follow_up_requested = False
272
274
  self._idle = asyncio.Event()
273
275
  turn = _TurnState(turn_id or uuid7_string())
276
+ self._active_turn_id = turn.turn_id
274
277
  try:
275
- self._emit(TurnStartedEvent(turn.turn_id, tuple(texts)))
278
+ messages = self._bind_turn(messages)
279
+ self._emit(TurnStartedEvent(turn.turn_id, messages))
276
280
  while True:
277
281
  phase = "pre_turn" if turn.iteration == 0 else "mid_turn"
278
282
  await self._maybe_auto_compact(turn.turn_id, phase)
283
+ if turn.iteration == 0:
284
+ self._append_history(messages)
279
285
  self._follow_up_requested = False
280
286
  # Input delivery commits history; its failures must fail the turn.
281
287
  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
288
  response = await self._sample(turn)
287
289
  self._emit(
288
290
  ModelCompletedEvent(
@@ -347,6 +349,7 @@ class Agent:
347
349
  finally:
348
350
  self._stop_requested = False
349
351
  self._follow_up_requested = False
352
+ self._active_turn_id = None
350
353
  self._idle.set()
351
354
  self._idle = None
352
355
 
@@ -479,14 +482,30 @@ class Agent:
479
482
  )
480
483
  return None
481
484
 
485
+ def _bind_turn(
486
+ self, items: "typing.Iterable[ConversationItem]"
487
+ ) -> "typing.Tuple[ConversationItem, ...]":
488
+ turn_id = self._active_turn_id
489
+ return tuple(
490
+ item if isinstance(item, (ToolCall, ToolResult, ReasoningItem))
491
+ else replace(item, turn_id=turn_id) if turn_id is not None
492
+ else item
493
+ for item in items
494
+ )
495
+
482
496
  def _append_history(
483
497
  self,
484
498
  items: "typing.Iterable[ConversationItem]",
485
499
  ) -> "None":
486
- items = tuple(items)
500
+ items = self._bind_turn(items)
487
501
  if self._rollout_recorder is not None:
488
502
  self._rollout_recorder.append_history_items(items, self._history)
489
503
  self._history.extend(items)
504
+ messages = tuple(
505
+ item for item in items if isinstance(item, (UserMessage, AgentMessage, AssistantMessage))
506
+ )
507
+ if messages:
508
+ self._emit(MessagesAddedEvent(messages[0].turn_id or "", messages))
490
509
 
491
510
  def _handle_model_stream_event(self, turn_id: "str", event: "ModelEvent") -> "None":
492
511
  if isinstance(event, TokenCountEvent):
pycodex/context.py CHANGED
@@ -87,6 +87,7 @@ 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
90
91
 
91
92
  def __post_init__(self):
92
93
  if self.code_mode_only is not None and not isinstance(self.code_mode_only, bool):
@@ -228,6 +229,8 @@ class ContextManager:
228
229
 
229
230
  def get_turn_metadata(self, turn_id: "str") -> "JSONDict":
230
231
  metadata: "JSONDict" = {"turn_id": turn_id}
232
+ if not self.config.include_environment_context:
233
+ return metadata
231
234
  if self._workspace_metadata_turn_id is None:
232
235
  self._workspace_metadata_turn_id = turn_id
233
236
  self._workspace_metadata_cache = get_workspace_turn_metadata(self.cwd)
@@ -635,44 +638,24 @@ class ContextManager:
635
638
  return f"{SKILLS_OPEN_TAG}\n{body}\n{SKILLS_CLOSE_TAG}"
636
639
 
637
640
  def _discover_skills(self) -> "typing.List[SkillDescriptor]":
638
- codex_home = self.config.codex_home
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
641
+ return discover_skills(self.config.codex_home)
664
642
 
665
643
  def _build_contextual_user_messages(self) -> "typing.List[ContextMessage]":
666
644
  sections: "typing.List[str]" = []
667
645
  user_instructions = self._merged_user_instructions()
668
646
  if user_instructions is not None:
647
+ heading = (
648
+ f"{USER_INSTRUCTIONS_PREFIX}{self.cwd}"
649
+ if self.config.include_environment_context else "# User instructions"
650
+ )
669
651
  sections.append(
670
652
  (
671
- f"{USER_INSTRUCTIONS_PREFIX}{self.cwd}\n\n"
653
+ f"{heading}\n\n"
672
654
  f"<INSTRUCTIONS>\n{user_instructions}\n</INSTRUCTIONS>"
673
655
  )
674
656
  )
675
- sections.append(self._serialize_environment_context())
657
+ if self.config.include_environment_context:
658
+ sections.append(self._serialize_environment_context())
676
659
  sections.extend(self._extra_contextual_user_messages)
677
660
  if not sections:
678
661
  return []
@@ -960,3 +943,32 @@ def build_goal_message(goal, budget_limited=False):
960
943
  token_budget="none" if budget is None else budget,
961
944
  remaining_tokens="unbounded" if budget is None else max(0, budget - goal["tokensUsed"]),
962
945
  ))
946
+
947
+
948
+ def discover_skills(codex_home):
949
+ """Discover the same skill descriptors used in model context and input menus."""
950
+ if codex_home is None:
951
+ return []
952
+
953
+ user_root = codex_home / "skills"
954
+ system_root = user_root / ".system"
955
+ discovered: "typing.List[SkillDescriptor]" = []
956
+ seen: "typing.Set[Path]" = set()
957
+
958
+ user_paths = _discover_skill_files(user_root, excluded_root=system_root)
959
+ system_paths = _discover_skill_files(system_root)
960
+
961
+ for scope_rank, root, paths in (
962
+ (3, user_root, user_paths),
963
+ (0, system_root, system_paths),
964
+ ):
965
+ for path in paths:
966
+ resolved = path.resolve()
967
+ if resolved in seen:
968
+ continue
969
+ seen.add(resolved)
970
+ descriptor = _parse_skill_descriptor(path, scope_rank, root)
971
+ if descriptor is not None:
972
+ discovered.append(descriptor)
973
+
974
+ 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
- user_texts: "typing.Tuple[str, ...]"
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(self.user_texts)
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
- TurnStartedEvent(
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
- prompt: "str"
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.prompt, 72)
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/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, texts: "typing.List[str]", name: "str" = "user") -> "None":
55
+ def __init__(self, messages) -> "None":
56
56
  self.submission_id = uuid7_string()
57
57
  self.turn_id = self.submission_id
58
- self.texts = texts
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._snapshot_fields(execution),
236
- "session_id": execution.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
- "prompts": list(item.texts),
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(text, name=name)
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(UserMessage(text, name=name))
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, text, queue, sender, queue == "enqueue", busy)
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, text: "str", name: "str" = "user") -> "typing.Tuple[str, asyncio.Future[TurnResult]]":
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([text], name=name)
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 display text and turn identity.
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
- self._steer_queue.append(UserMessage(text) if isinstance(text, str) else text)
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.agent.receive_messages(tuple(self._steer_queue))
733
- self._steer_queue.clear()
734
- if self._input_activity is not None and not self._wait_interrupted:
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, texts = pending
763
+ queued = pending
764
764
  self._current_submission = queued
765
765
  try:
766
- result = await self.agent.run_turn(texts, turn_id=queued.turn_id, name=queued.name)
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[typing.Tuple[_QueuedSubmission, typing.List[str]], None]":
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
- return queued, list(queued.texts)
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
- self.message(continuation)
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
- "user_text": "\n".join(event.user_texts),
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 = "\n".join(event.user_texts)
886
+ prompt = event.visualize()
892
887
  if prompt:
893
888
  self.title = shorten_title(prompt)
894
889
  self.publish_state("auto_title")
@@ -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
- if not state["history"]:
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, (prompt, response) in enumerate(state["history"], 1):
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
- """Pure conversation-history projections, independent of rollout storage."""
1
+ """Message storage metadata and pure display conversion."""
2
2
 
3
- import typing
3
+ import json
4
4
  from dataclasses import replace
5
+ from hashlib import sha256
5
6
 
6
- from ..protocol import AgentMessage, AssistantMessage, ConversationItem, UserMessage
7
+ from ..protocol import AgentMessage, AssistantMessage, UserMessage
7
8
 
8
9
 
9
- def serialize_history_item(item: "ConversationItem") -> "typing.Dict[str, object]":
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["visible"] = item.visible
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 restore_visibility(item, payload):
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
- return replace(item, visible=visible)
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 iter_display_turns(history):
28
- """Project message visibility and grouping; None marks a compaction."""
29
- prompt = None
30
- response = ""
31
- phase = None
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
- if item is None:
34
- if prompt is not None or response:
35
- yield (prompt or "", response)
36
- yield None
37
- prompt, response, phase = None, "", None
38
- elif isinstance(item, (UserMessage, AgentMessage)):
39
- # Hidden mail must not split commentary from its final answer.
40
- # Keep an existing unphased reply when the next input arrives.
41
- if item.visible or (response and phase != "commentary"):
42
- if prompt is not None or response:
43
- yield (prompt or "", response)
44
- prompt, response, phase = None, "", None
45
- if item.visible:
46
- prompt = item.text
47
- elif isinstance(item, AssistantMessage) and item.visible:
48
- response, phase = item.text, item.phase
49
- if phase == "final":
50
- yield (prompt or "", response)
51
- prompt, response, phase = None, "", None
52
- if prompt is not None or response:
53
- yield (prompt or "", response)
54
-
55
-
56
- def conversation_history_to_turns(
57
- history: "typing.Iterable[ConversationItem]",
58
- ) -> "typing.Tuple[typing.Tuple[str, str], ...]":
59
- return tuple(entry for entry in iter_display_turns(history) if entry is not None)
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)
@@ -24,8 +24,7 @@ from ..protocol import (
24
24
  from .compactor import SUMMARY_PREFIX
25
25
  from .event_helpers import shorten_title
26
26
  from .history import (
27
- conversation_history_to_turns, iter_display_turns,
28
- restore_visibility, serialize_history_item,
27
+ conversation_history_to_turns, restore_message_metadata, serialize_history_item,
29
28
  )
30
29
  from .get_env import get_package_version
31
30
 
@@ -163,6 +162,9 @@ class SessionRolloutRecorder:
163
162
  "message": item.text,
164
163
  "name": item.name,
165
164
  "visible": item.visible,
165
+ "message_id": item.message_id,
166
+ "created_at": item.created_at,
167
+ "turn_id": item.turn_id,
166
168
  "images": [],
167
169
  "local_images": [],
168
170
  "text_elements": [],
@@ -310,7 +312,7 @@ def load_resumed_session_path(
310
312
  replacement_history = payload.get("replacement_history")
311
313
  if isinstance(replacement_history, list):
312
314
  history = _deserialize_compacted_history(
313
- replacement_history, payload.get("message")
315
+ replacement_history, payload.get("message"), entry["_record_offset"],
314
316
  )
315
317
  saw_input = any(
316
318
  isinstance(item, (UserMessage, AgentMessage, ContextMessage))
@@ -325,7 +327,7 @@ def load_resumed_session_path(
325
327
 
326
328
  if item_type == "event_msg" and isinstance(payload, dict):
327
329
  if payload.get("type") == "user_message":
328
- history.append(_user_message_from_event(payload))
330
+ history.append(_user_message_from_event(payload, entry))
329
331
  saw_input = True
330
332
  continue
331
333
 
@@ -341,6 +343,7 @@ def load_resumed_session_path(
341
343
  payload,
342
344
  tool_names_by_call_id,
343
345
  include_user_messages=False,
346
+ record_id=entry["_record_offset"], timestamp=entry.get("timestamp"),
344
347
  )
345
348
 
346
349
  if not history:
@@ -351,7 +354,8 @@ def load_resumed_session_path(
351
354
  raise ValueError(f"No resumable history found in {rollout_path}")
352
355
 
353
356
  turns = conversation_history_to_turns(history)
354
- first_prompt = next((prompt for prompt, _ in turns if prompt), "")
357
+ first_prompt = next(("\n".join(message.text for message in turn["messages"])
358
+ for turn in turns if turn["messages"]), "")
355
359
  title = thread_name or shorten_title(first_prompt) or thread_id
356
360
  return {
357
361
  "session_id": session_id,
@@ -398,39 +402,75 @@ def read_rollout_history_page(rollout_path, before=None, limit=100):
398
402
 
399
403
  def load_display_history(
400
404
  rollout_path: "typing.Union[str, Path]",
401
- limit: "int" = 80,
402
- ) -> "typing.Tuple[typing.Union[typing.Tuple[str, str], None], ...]":
403
- """Read visible turns across checkpoints; None marks a compaction."""
404
- return tuple(deque(iter_display_turns(_iter_display_items(rollout_path)), maxlen=limit))
405
-
406
-
407
- def _user_message_from_event(payload):
408
- return restore_visibility(UserMessage(
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(
409
441
  text=str(payload.get("message", "")), name=payload.get("name", "user"),
410
- ), payload)
442
+ ), payload, entry["_record_offset"], entry.get("timestamp"))
411
443
 
412
444
 
413
- def _iter_display_items(rollout_path):
445
+ def _iter_display_items(rollout_path, reverse=False):
414
446
  path = Path(rollout_path).expanduser().resolve()
415
- for entry in _iter_rollout_entries(path):
416
- item_type = entry.get("type")
417
- payload = entry.get("payload")
418
- if not isinstance(payload, dict):
419
- continue
420
- if item_type == "compacted":
421
- yield None
422
- elif item_type == "event_msg" and payload.get("type") == "user_message":
423
- yield _user_message_from_event(payload)
424
- elif (
425
- item_type == "response_item"
426
- and (
427
- payload.get("type") == "agent_message"
428
- or (payload.get("type") == "message" and payload.get("role") == "assistant")
429
- )
430
- ):
431
- items = []
432
- _append_deserialized_response_item(items, payload, {}, False)
433
- yield from items
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
434
474
 
435
475
 
436
476
  def _drop_unmatched_tool_calls(
@@ -534,6 +574,7 @@ def _iter_rollout_entries(
534
574
  ) -> "typing.Iterable[typing.Dict[str, object]]":
535
575
  decoder = json.JSONDecoder()
536
576
  buffer = ""
577
+ byte_offset = start_offset
537
578
  start = 0
538
579
  parsed_entries = 0
539
580
 
@@ -547,14 +588,16 @@ def _iter_rollout_entries(
547
588
  buffer += chunk
548
589
 
549
590
  while True:
591
+ whitespace_start = start
550
592
  while start < len(buffer) and buffer[start].isspace():
551
593
  start += 1
594
+ byte_offset += len(buffer[whitespace_start:start].encode("utf-8"))
552
595
  if start >= len(buffer):
553
596
  buffer = ""
554
597
  start = 0
555
598
  break
556
599
  try:
557
- entry, start = decoder.raw_decode(buffer, start)
600
+ entry, end = decoder.raw_decode(buffer, start)
558
601
  except json.JSONDecodeError as exc:
559
602
  if eof:
560
603
  if parsed_entries > 0:
@@ -566,8 +609,12 @@ def _iter_rollout_entries(
566
609
  buffer = buffer[start:]
567
610
  start = 0
568
611
  break
612
+ record_offset = byte_offset
613
+ byte_offset += len(buffer[start:end].encode("utf-8"))
614
+ start = end
569
615
  if isinstance(entry, dict):
570
616
  parsed_entries += 1
617
+ entry["_record_offset"] = record_offset
571
618
  yield entry
572
619
  if start > ROLLOUT_READ_CHUNK_SIZE:
573
620
  buffer = buffer[start:]
@@ -580,6 +627,38 @@ def _iter_rollout_entries(
580
627
  raise ValueError(f"no rollout entries found in {rollout_path}")
581
628
 
582
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
+
583
662
  def _extract_response_message_text(payload: "typing.Dict[str, object]") -> "str":
584
663
  text_parts: "typing.List[str]" = []
585
664
  for item in payload.get("content") or []:
@@ -604,10 +683,11 @@ def _compacted_payload(
604
683
  def _deserialize_compacted_history(
605
684
  replacement_history: "typing.Iterable[object]",
606
685
  summary_message: "typing.Union[str, None]" = None,
686
+ record_id: "object" = "checkpoint",
607
687
  ) -> "typing.List[ConversationItem]":
608
688
  history: "typing.List[ConversationItem]" = []
609
689
  tool_names_by_call_id: "typing.Dict[str, str]" = {}
610
- for payload in replacement_history:
690
+ for index, payload in enumerate(replacement_history):
611
691
  if not isinstance(payload, dict):
612
692
  continue
613
693
  _append_deserialized_response_item(
@@ -615,6 +695,7 @@ def _deserialize_compacted_history(
615
695
  payload,
616
696
  tool_names_by_call_id,
617
697
  include_user_messages=True,
698
+ record_id="{0}:{1}".format(record_id, index),
618
699
  )
619
700
  for index in range(len(history) - 1, -1, -1):
620
701
  item = history[index]
@@ -632,26 +713,28 @@ def _append_deserialized_response_item(
632
713
  payload: "typing.Dict[str, object]",
633
714
  tool_names_by_call_id: "typing.Dict[str, str]",
634
715
  include_user_messages: "bool",
716
+ record_id: "object" = "",
717
+ timestamp: "typing.Union[str, None]" = None,
635
718
  ) -> "None":
636
719
  response_item_type = str(payload.get("type", "")).strip()
637
720
  if response_item_type == "agent_message":
638
- history.append(restore_visibility(
639
- AgentMessage.from_response_item(payload), payload,
721
+ history.append(restore_message_metadata(
722
+ AgentMessage.from_response_item(payload), payload, record_id, timestamp,
640
723
  ))
641
724
  return
642
725
  if response_item_type == "message":
643
726
  role = str(payload.get("role", "")).strip()
644
727
  if role == "assistant":
645
- history.append(restore_visibility(
646
- AssistantMessage.from_response_item(payload), payload,
728
+ history.append(restore_message_metadata(
729
+ AssistantMessage.from_response_item(payload), payload, record_id, timestamp,
647
730
  ))
648
731
  return
649
732
  if include_user_messages and role == "user":
650
733
  history.append(
651
- restore_visibility(UserMessage(
734
+ restore_message_metadata(UserMessage(
652
735
  text=_extract_response_message_text(payload), id=payload.get("id"),
653
736
  name=payload.get("name", "user"),
654
- ), payload)
737
+ ), payload, record_id, timestamp)
655
738
  )
656
739
  return
657
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())
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-codex
3
- Version: 0.6.1
3
+ Version: 0.6.2
4
4
  Summary: A minimal Python extraction of Codex's main agent loop
5
5
  License-File: LICENSE
6
6
  Requires-Python: >=3.6.2
@@ -48,6 +48,11 @@ python3 -m pip install --upgrade pycodex-ws
48
48
 
49
49
  ## Configure a model
50
50
 
51
+ Start with [config_examples/](config_examples/README.md) for Responses, StepFun,
52
+ Chat Completions, Claude Messages or Gemini. Give an agent your endpoint and key
53
+ (StepFun Coding Plan includes its endpoint) and ask it to follow that guide to
54
+ install and verify a config or profile.
55
+
51
56
  Create `~/.codex/config.toml`. For example, with OpenAI:
52
57
 
53
58
  ```toml
@@ -82,6 +87,8 @@ See [configuration](docs/CONTEXT.md#配置读取与-profile) and the
82
87
  [Gemini setup example](docs/responses_server/README.md#gemini-api).
83
88
  Gemini 4 Argon includes a prompt adapted from Antigravity.
84
89
  Gemini tool arguments stream as they are generated; tools run after the complete call is received.
90
+ Gemini continuation omits unsigned empty text parts while preserving thought signatures,
91
+ including when resuming recorded sessions.
85
92
 
86
93
  ## Use the CLI
87
94
 
@@ -95,6 +102,8 @@ pycodex --json "Summarize this repository."
95
102
  ```
96
103
 
97
104
  The first command starts an interactive session; the others run a single task.
105
+ Web skill completion is an [optional frontend feature](packages/pycodex-ws/workspace_server/optional_features/skill-completion/README.md).
106
+ Apply `skill-completion` through Customize to enable @/$ prefix suggestions.
98
107
  The agent can edit files and run commands with your user account's permissions.
99
108
 
100
109
  | Command | Purpose |
@@ -139,9 +148,15 @@ Open `http://127.0.0.1:6007`. The workspace uses the same model configuration as
139
148
  the CLI and provides conversations, a live HTML Canvas, and file/diff viewers.
140
149
  Click file links to inspect code, then select text and use **Insert into chat**
141
150
  to include it in your next message.
142
-
143
- The settings menu provides interface customization and password-protected
144
- workspace sharing. See the [workspace guide](packages/pycodex-ws/README.md) for
151
+ Each input displays its author and creation time, including separate messages
152
+ in a steer batch. Recorded messages keep that metadata when the session resumes.
153
+ Restoring a tab reads the rollout tail needed for its latest 80 display rows;
154
+ Agent resume still restores the complete active context after the last checkpoint.
155
+
156
+ The settings menu provides interface customization, password-protected
157
+ workspace sharing, and [One-line Agent](packages/pycodex-ws/README.md#one-line-agent):
158
+ an Agent that runs directly in most shells without installation, for bootstrapping
159
+ an Agent environment or simple debugging. See the [workspace guide](packages/pycodex-ws/README.md) for
145
160
  session controls, storage and Feishu setup. A separate
146
161
  [VS Code extension](packages/pycodex-ws/extensions/vscode/README.md) connects to
147
162
  the same backend, including over Remote SSH.
@@ -1,15 +1,15 @@
1
1
  pycodex/__init__.py,sha256=2rP9Qd5ClJlSI3bPNB0Jmn9lJUpeeo7gcbRPUvH81eI,2904
2
2
  pycodex/__main__.py,sha256=MHKZ_ae3fSLGTLUUMOx15fWdeOnJSHhq-zslRP5F5Lc,79
3
- pycodex/agent.py,sha256=yZ75cpCBM2acDBayKo9ekqHZRvODXsKtJFjyhm78v9M,22704
3
+ pycodex/agent.py,sha256=DfT4zYsCWiTsfQaBdVvFi5KQ5ke2nJ7DXdUUW4B8YFo,23514
4
4
  pycodex/bootstrap.py,sha256=MR0msG5SEAAbdT8i_wCn1ueLdNx9sETsqIVWQPhPxus,4990
5
5
  pycodex/cli.py,sha256=HkX_fFNUyPnNo25FeSa9ZMaQG79rqk3b0oV4ZH0h68c,12576
6
6
  pycodex/config.py,sha256=mGM7oLaciBwGXHMQjKVifWFTd7gZTfzqlQeJSFzcQic,1218
7
- pycodex/context.py,sha256=Quc8VBNr7XVoan6-l1rzVJ1njH7Hj7lbdux_mJLXESQ,41096
8
- pycodex/events.py,sha256=dvEzq6jH5esN4Y99M-66feD19oVfmrOBvm4LG5xEhSs,22736
7
+ pycodex/context.py,sha256=i2Gpm2rXqd0PMZHYzZYefwdSPOP0eA62fxS3WeJNFw0,41483
8
+ pycodex/events.py,sha256=8gPVe_wb5r5s2hVQhywFMnz1YVvBmDLhyq43e9Y71wk,23090
9
9
  pycodex/model.py,sha256=omwYru3BZ2ejZTCvUTFsIltjtH1LQWG3zWrzZ3hyNhI,58672
10
10
  pycodex/multi_agents.py,sha256=3KN_Ai3UremtsQppvxd0pE7pFam_v0zBastCNi-NNx8,16150
11
- pycodex/protocol.py,sha256=-rqxpXiYkbSTzzzsAOGXwIXWREAb4uOd3sh0V0GHLW8,14650
12
- pycodex/runtime.py,sha256=Szeufq_cAPSw_r7HCmpin1nm_Ugsj3FCcn-pgCCkrrI,37525
11
+ pycodex/protocol.py,sha256=qYUS9371F-DadlsYgctCpQbm3JCqyfpcWcxkANRAZWQ,15586
12
+ pycodex/runtime.py,sha256=92hVNdBzugUYQb01-bbkAOYpNpjIB1IWVEU6_U6SERA,37120
13
13
  pycodex/portable/__init__.py,sha256=NgACNTFK5hbRK6fqbL89qjPuh44N950pr4eoDWLfKD4,1110
14
14
  pycodex/portable/client.py,sha256=ZvXjKCB557ZZ-ELmec9DIxymWbG8QBZsaU6e0axu0T0,15508
15
15
  pycodex/portable/protocol.py,sha256=jtyPHI3aVY4UldlSIzeZRQX3MCFzPYfG-0iDC6JSWYo,931
@@ -68,13 +68,14 @@ pycodex/utils/crypto.py,sha256=HRCXF26Ft3S8CG2X0YpZwa8GMU9YJ0Loo8Q9PMPMcNw,1249
68
68
  pycodex/utils/debug.py,sha256=5XMpWpwFSm6woyx6RGXvN2qL0afRtTQbwlOAv-LotTw,913
69
69
  pycodex/utils/doctor.py,sha256=xhPflFEYFfmtQ4-LjnIyz-cNts0GjNtAK0inVTYfKiI,10764
70
70
  pycodex/utils/dotenv.py,sha256=rLHBfz5zPZMbrJqyRyYPy3j4oiDwuzfrH4mDH3XRrow,1647
71
- pycodex/utils/event_helpers.py,sha256=VH8MMmpAO98EFb-PeEKjqAw8LCiGGaWegENP9Jnc6kA,12021
71
+ pycodex/utils/event_helpers.py,sha256=ULvTSktxMd--VEL2UJA6CbuWHLsrctAcAuEk91wGLL8,12021
72
72
  pycodex/utils/get_env.py,sha256=L4S8h84tkgxZKvrxY7ezTgePbXepG-yIigUTKeY6uuE,6094
73
- pycodex/utils/history.py,sha256=r9Fw9HmImzgvRAcnd92zw3E2tAOgerZCp4kyJOwA1AM,2362
73
+ pycodex/utils/history.py,sha256=qgt5IxxkfCYjjpr08VJFhasICSSlqxQM7d-DjRJVjHA,3845
74
74
  pycodex/utils/image_utils.py,sha256=OUzUs0Cow4L8Z2np0EBeEUotAqqsCmRmhrV8AxZUXRw,2460
75
75
  pycodex/utils/model_metadata.py,sha256=uK3iI4yC7Ge7yN4I1_gQYalQ4MYKddz2qMwsmQb-P80,1337
76
76
  pycodex/utils/random_ids.py,sha256=jLTxZZ0MBbRdQOFDFWGVRjWzIo6FKSQ5ADXbQSLPp1s,379
77
- pycodex/utils/session_persist.py,sha256=pKAJZqQ4gnxUc1pzGC3PjBJUZD8eeclqvxk5IWXJ3cs,27289
77
+ pycodex/utils/session_persist.py,sha256=7JXXInvKaeO-9zz-n4LrnqrNn4BvFPEoVgZ88c9yZrM,31333
78
+ pycodex/utils/skill_catalog.py,sha256=3W-r6pn_fzEGyd89aKD2shGNhrUK2hLgrlwOlqYOpgU,618
78
79
  pycodex/utils/truncation.py,sha256=5D6vAorT8EgXgjd7ASwtraAyIZdlCR-w5jKZqJxDzho,5446
79
80
  pycodex/utils/_aes_gcm/LICENSE,sha256=KvdHagY3sYIK34GldJaRi34sNnGwMVJIIoDhbC9MRu8,2805
80
81
  pycodex/utils/_aes_gcm/README.md,sha256=D9XGeewCgU2PVqJCO6WusUs0Mw2FbMnABCqaVktqCnE,3045
@@ -86,7 +87,7 @@ responses_server/__init__.py,sha256=SOMO5Q-Z0dpaRih8yWuKUTclPl28tpy_XIPTOO_BPq0,
86
87
  responses_server/__main__.py,sha256=876xZTqhPeDBD2GKKr8pKX33Af8PhFTosAI8bYQsFgQ,61
87
88
  responses_server/app.py,sha256=658hV1uR51RZzTe8B5xPvaasWZdjJo5rxg2GJFnxOLk,8495
88
89
  responses_server/config.py,sha256=HxoZYNkpDwZgbIxgVgoR_8BYTRV8V2e1dCddUTo1FyQ,2663
89
- responses_server/gemini_api.py,sha256=XUG05JhCPqxpDYSQ1m7-KCCturqIIow8ZMgDRZYMk14,15589
90
+ responses_server/gemini_api.py,sha256=dnKKzB7A60QDDHU-uDYShCyNo02Hsv-HJwZnW4t7UJ4,15798
90
91
  responses_server/messages_api.py,sha256=3Mr0v0ieN18PpEgmR48DnP6PrCDk980cAckZG-2HKrM,19274
91
92
  responses_server/payload_processors.py,sha256=jIiGCHGFootnkwPpZiM1-Zv1WKziHlklSWGo050hBgU,3567
92
93
  responses_server/request_translation.py,sha256=9TYgGv4GV2M7m6TGXV-pqIpIFTn8v_ZBKULUq3nvaB8,18754
@@ -99,8 +100,8 @@ responses_server/transport.py,sha256=363GeSws0VS-yL7pPjtMvjEp7rZ60FdMJ5oD0vPPIWU
99
100
  responses_server/tools/__init__.py,sha256=ivsBSEy0SBUhY-Uea5v1XMLXShkwHdCVl0id-1FwdZg,150
100
101
  responses_server/tools/custom_adapter.py,sha256=leYNJKp4Ute0JWNfGpe-ntSyFqRgYCdWF4dMYQFINlk,8615
101
102
  responses_server/tools/web_search.py,sha256=JyF6NHCS0SqoBrO18jX8cgBsiV4OYQBPz0Ky4u3juSQ,9059
102
- python_codex-0.6.1.dist-info/METADATA,sha256=c6tqvH3gR_x8Cax-kzRRds6sZ4FRSSUC8rfv28Cm1f0,6855
103
- python_codex-0.6.1.dist-info/WHEEL,sha256=KGYbc1zXlYddvwxnNty23BeaKzh7YuoSIvIMO4jEhvw,87
104
- python_codex-0.6.1.dist-info/entry_points.txt,sha256=sNUVakoVuTrzJH505ZgRTQxmtRRPUHV_EH0i6EbYTyM,45
105
- python_codex-0.6.1.dist-info/licenses/LICENSE,sha256=0X8ifk312hYAORM4hlzg8wVSEXYKNmiPgWlB1YIy2Nw,10926
106
- python_codex-0.6.1.dist-info/RECORD,,
103
+ python_codex-0.6.2.dist-info/METADATA,sha256=D6WM3UCjYbbicU8pXwNrZaMZH-Z1ZrHPXYbqlF7-hvk,7995
104
+ python_codex-0.6.2.dist-info/WHEEL,sha256=KGYbc1zXlYddvwxnNty23BeaKzh7YuoSIvIMO4jEhvw,87
105
+ python_codex-0.6.2.dist-info/entry_points.txt,sha256=sNUVakoVuTrzJH505ZgRTQxmtRRPUHV_EH0i6EbYTyM,45
106
+ python_codex-0.6.2.dist-info/licenses/LICENSE,sha256=0X8ifk312hYAORM4hlzg8wVSEXYKNmiPgWlB1YIy2Nw,10926
107
+ python_codex-0.6.2.dist-info/RECORD,,
@@ -31,6 +31,9 @@ def build_gemini_request(request):
31
31
  # opaque reasoning item. Never replay a removed function call.
32
32
  parts = [deepcopy(entry["part"]) for entry in native
33
33
  if "call_id" not in entry or entry["call_id"] in active_call_ids]
34
+ # Unsigned empty text can end a stream, but is not input data.
35
+ parts = [part for part in parts
36
+ if part.get("text") != "" or "thoughtSignature" in part]
34
37
  else:
35
38
  parts = _content_parts(message.get("content"))
36
39
  for call in message.get("tool_calls", []):