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.
@@ -1,9 +1,10 @@
1
1
  import asyncio
2
2
  import typing
3
+ from contextlib import contextmanager
3
4
  from dataclasses import dataclass
4
5
  from typing import Awaitable, Callable
5
6
 
6
- from ..events import CompactStartedEvent, TerminalEvent, TurnStartedEvent
7
+ from ..events import ModelRequestInterrupted, TurnInterrupted
7
8
  from ..utils.compat import Literal
8
9
  from .clock_manager import ClockManager
9
10
  from .goal_manager import GoalManager
@@ -100,17 +101,17 @@ class AgentRuntimeEnvironment:
100
101
  self._resources = {}
101
102
  self._restart_handlers = []
102
103
  self._close_handlers = []
103
- self._event_handlers = []
104
104
  self._bindings = None
105
105
 
106
- def register_resource(self, name, manager, restart=None, close=None, observer=None):
106
+ def register_resource(self, name, manager, restart=None, close=None):
107
107
  """Register one shared manager, independently of its callable tools."""
108
108
  if name in self._resources or manager in self._resources.values():
109
109
  raise ValueError("resource already registered: " + name)
110
110
  self._resources[name] = manager
111
+ if name == "clock":
112
+ self.clock_manager = manager
111
113
  for handler, handlers in (
112
114
  (restart, self._restart_handlers), (close, self._close_handlers),
113
- (observer, self._event_handlers),
114
115
  ):
115
116
  if handler is not None:
116
117
  handlers.append(handler)
@@ -144,11 +145,6 @@ class AgentRuntimeEnvironment:
144
145
  for item in manager.background_work_snapshot()
145
146
  ]
146
147
 
147
- def event_observers(self, event):
148
- return self._event_handlers if isinstance(
149
- event, (TerminalEvent, TurnStartedEvent, CompactStartedEvent),
150
- ) else []
151
-
152
148
  def dump_state(self):
153
149
  managers = {"clock": self.clock_manager.dump_state()}
154
150
  goal = self.goal_manager.dump_state()
@@ -179,8 +175,22 @@ class AgentRuntimeEnvironment:
179
175
  self.clock_manager.arm_after_reply()
180
176
  self.goal_manager.start()
181
177
 
182
- def handle_agent_event(self, event):
183
- self.goal_manager.handle_agent_event(event)
178
+ @contextmanager
179
+ def execution(self, save_state, manual=False):
180
+ self.goal_manager.begin_turn()
181
+ self.clock_manager.turn_started()
182
+ interrupted = False
183
+ try:
184
+ yield
185
+ except (TurnInterrupted, ModelRequestInterrupted):
186
+ interrupted = not manual
187
+ raise
188
+ finally:
189
+ self.goal_manager.finish_turn(interrupted)
190
+ save_state()
191
+ if not manual:
192
+ self.goal_manager.schedule_continuation()
193
+ self.clock_manager.arm_after_reply()
184
194
 
185
195
  def tool_completed(self):
186
196
  self.goal_manager.account()
@@ -34,6 +34,7 @@ DEFAULT_EXEC_YIELD_TIME_MS = 10_000
34
34
  DEFAULT_WRITE_STDIN_YIELD_TIME_MS = 250
35
35
  DEFAULT_LOGIN = True
36
36
  DEFAULT_TTY = False
37
+ DEFAULT_WAKE_ME_UP_WHEN_DONE = False
37
38
  DEFAULT_SESSION_ID_START = 1000
38
39
  UNIFIED_EXEC_OUTPUT_MAX_BYTES = 1024 * 1024
39
40
  # Match upstream unified exec's short post-exit output close wait.
@@ -175,6 +176,7 @@ class UnifiedExecManager:
175
176
  tty: "bool" = DEFAULT_TTY,
176
177
  yield_time_ms: "int" = DEFAULT_EXEC_YIELD_TIME_MS,
177
178
  max_output_tokens: "typing.Union[int, None]" = None,
179
+ wake_me_up_when_done: "bool" = DEFAULT_WAKE_ME_UP_WHEN_DONE,
178
180
  ) -> "JSONValue":
179
181
  session_id = await self._allocate_session_id()
180
182
  command = self._build_shell_command(cmd, shell, login)
@@ -215,7 +217,11 @@ class UnifiedExecManager:
215
217
  )
216
218
  session = await self._get_session(session_id)
217
219
  if session is not None:
218
- asyncio.create_task(self._notify_when_session_completes(session_id))
220
+ asyncio.create_task(
221
+ self._notify_when_session_completes(
222
+ session_id, wake_me_up_when_done=wake_me_up_when_done
223
+ )
224
+ )
219
225
  return output
220
226
 
221
227
  async def write_stdin(
@@ -360,16 +366,22 @@ class UnifiedExecManager:
360
366
  session.output_event.set()
361
367
  session.output_event.set()
362
368
 
363
- async def _notify_when_session_completes(self, session_id: "int") -> "None":
369
+ async def _notify_when_session_completes(
370
+ self,
371
+ session_id: "int",
372
+ wake_me_up_when_done: "bool" = True,
373
+ ) -> "None":
364
374
  from ..runtime import SubmissionInterrupted
365
375
 
366
- if self._notify_hook is None:
376
+ if self._notify_hook is None and self._state_listener is None:
367
377
  return
368
378
  session = await self._get_session(session_id)
369
379
  if session is None:
370
380
  return
371
381
  await session.process.wait()
372
382
  self._state_changed()
383
+ if not wake_me_up_when_done:
384
+ return
373
385
  with self._lock:
374
386
  if self._sessions.get(session_id) is not session:
375
387
  return
@@ -1,22 +1,15 @@
1
1
  import typing
2
+ from collections import defaultdict, deque
2
3
  from dataclasses import dataclass
4
+ from pathlib import Path
3
5
 
4
6
  from ..protocol import (
5
7
  AssistantMessage,
6
8
  ContextMessage,
7
9
  ConversationItem,
8
- ModelResponse,
9
10
  ToolCall,
10
11
  ToolResult,
11
- ToolSpec,
12
- UserMessage,
13
12
  )
14
- from .random_ids import uuid7_string
15
-
16
- if typing.TYPE_CHECKING:
17
- from ..context import ContextManager
18
- from ..events import ModelEvent
19
- from ..model import ModelClient
20
13
 
21
14
  DEFAULT_COMPACT_PROMPT = """You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.
22
15
 
@@ -50,10 +43,17 @@ class CompactResult:
50
43
  def retained_item_count(self) -> "int":
51
44
  return max(len(self.history) - 1, 0)
52
45
 
46
+ @classmethod
47
+ def from_response(cls, response, session_file, original_item_count, pruned_tool_results):
48
+ summary = _last_assistant_message(response.items)
49
+ if summary is None or not summary.strip():
50
+ raise ValueError("compact response contains no assistant summary")
51
+ return cls(compact(response.items, session_file), original_item_count, pruned_tool_results)
52
+
53
53
 
54
54
  def compact(
55
55
  history: "typing.Sequence[ConversationItem]",
56
- session_file: "typing.Union[str, None]" = None,
56
+ session_file: "typing.Union[str, Path, None]" = None,
57
57
  ) -> "typing.Tuple[ConversationItem, ...]":
58
58
  summary_text = _build_summary_message(_last_assistant_message(history))
59
59
  if session_file:
@@ -67,98 +67,25 @@ def compact(
67
67
  return build_compacted_history(summary_text)
68
68
 
69
69
 
70
- async def compact_history(
71
- history: "typing.Sequence[ConversationItem]",
72
- model_client: "ModelClient",
73
- context_manager: "ContextManager",
74
- tools: "typing.List[ToolSpec]",
75
- parallel_tool_calls: "bool",
76
- stream_event_handler: "typing.Union[typing.Callable[[ModelEvent], None], None]" = None,
77
- prune_tool_results_on_context_error: "bool" = False,
78
- session_file: "typing.Union[str, None]" = None,
79
- turn_id: "typing.Union[str, None]" = None,
80
- session_id: "typing.Union[str, None]" = None,
81
- ) -> "typing.Union[CompactResult, None]":
82
- from ..model import ContextLengthExceeded, ResponsesIncompleteError
83
-
84
- if not history:
85
- return None
86
- original_item_count = len(history)
87
- pruned_tool_results = 0
88
- turn_id = turn_id or uuid7_string()
89
-
90
- noop_stream_event_handler = lambda _event: None
91
- while True:
92
- compact_prompt = UserMessage(text=DEFAULT_COMPACT_PROMPT)
93
- prompt = context_manager.build_prompt(
94
- list(history) + [compact_prompt],
95
- tools,
96
- parallel_tool_calls,
97
- turn_id=turn_id,
98
- reasoning_effort=model_client.reasoning_effort,
99
- capture_context=False,
100
- session_id=session_id,
101
- )
102
- try:
103
- response = await model_client.complete(
104
- prompt,
105
- stream_event_handler or noop_stream_event_handler,
106
- )
107
- break
108
- except ResponsesIncompleteError as exc:
109
- if (
110
- exc.reason != "max_output_tokens"
111
- or _last_assistant_message(exc.partial_items) is None
112
- ):
113
- raise
114
- response = ModelResponse(items=list(exc.partial_items))
115
- break
116
- except ContextLengthExceeded:
117
- if not prune_tool_results_on_context_error:
118
- raise
119
- pruned_history = prune_oldest_tool_response(history)
120
- if pruned_history is None:
121
- raise
122
- history = pruned_history
123
- pruned_tool_results += 1
124
-
125
- summary = _last_assistant_message(response.items)
126
- if summary is None or not summary.strip():
127
- raise ValueError("compact response contains no assistant summary")
128
- compacted_history = compact(
129
- response.items,
130
- session_file,
131
- )
132
- return CompactResult(
133
- history=compacted_history,
134
- original_item_count=original_item_count,
135
- pruned_tool_results=pruned_tool_results,
136
- )
137
-
138
-
139
70
  def prune_oldest_tool_response(
140
- history: "typing.Sequence[ConversationItem]",
141
- ) -> "typing.Union[typing.Tuple[ConversationItem, ...], None]":
142
- items = list(history)
143
- tool_result_index = None
144
- call_id = None
145
- for index, item in enumerate(items):
146
- if isinstance(item, ToolResult):
147
- tool_result_index = index
148
- call_id = item.call_id
149
- break
150
- if tool_result_index is None:
151
- return None
152
-
153
- indexes_to_remove = {tool_result_index}
154
- for index, item in enumerate(items[:tool_result_index]):
155
- if isinstance(item, ToolCall) and item.call_id == call_id:
156
- indexes_to_remove.add(index)
157
- break
158
-
159
- return tuple(
160
- item for index, item in enumerate(items) if index not in indexes_to_remove
161
- )
71
+ history: "typing.Sequence[ConversationItem]", count: "int" = 1,
72
+ ) -> "typing.Optional[typing.Sequence[ConversationItem]]":
73
+ """Drop the oldest count results together with their matching calls."""
74
+ if count == 0:
75
+ return history
76
+ calls = defaultdict(deque)
77
+ removed = set()
78
+ for index, item in enumerate(history):
79
+ if isinstance(item, ToolCall):
80
+ calls[item.call_id].append(index)
81
+ elif isinstance(item, ToolResult):
82
+ removed.add(index)
83
+ if calls[item.call_id]:
84
+ removed.add(calls[item.call_id].popleft())
85
+ count -= 1
86
+ if count == 0:
87
+ return tuple(item for i, item in enumerate(history) if i not in removed)
88
+ return None
162
89
 
163
90
 
164
91
  def build_compacted_history(
pycodex/utils/compat.py CHANGED
@@ -5,8 +5,14 @@ import asyncio
5
5
  import functools
6
6
  import io
7
7
  import shlex
8
+ import sys
8
9
  import tokenize
9
10
 
11
+ if sys.version_info >= (3, 7):
12
+ from contextvars import ContextVar, copy_context
13
+ else: # pragma: no cover - Python 3.6 task-local context
14
+ from aiocontextvars import ContextVar, copy_context
15
+
10
16
  try:
11
17
  from http.server import ThreadingHTTPServer
12
18
  except ImportError: # pragma: no cover - Python 3.6 path
@@ -6,6 +6,8 @@ import shlex
6
6
  import typing
7
7
  from dataclasses import asdict
8
8
 
9
+ from ..protocol import AgentMessage, UserMessage
10
+
9
11
  PROMPT_CONTEXT_BASELINE_TOKENS = 12_000
10
12
 
11
13
 
@@ -92,6 +94,13 @@ def shorten_title(text: "str", limit: "int" = 48) -> "str":
92
94
  return truncate_text(text, limit)
93
95
 
94
96
 
97
+ def visible_input_text(messages):
98
+ return "\n".join(
99
+ message.text for message in messages
100
+ if isinstance(message, (UserMessage, AgentMessage)) and message.visible
101
+ )
102
+
103
+
95
104
  def percent_of_context_window_remaining(total_tokens, context_window_tokens):
96
105
  if context_window_tokens <= PROMPT_CONTEXT_BASELINE_TOKENS:
97
106
  return 0
@@ -3,7 +3,6 @@
3
3
  import json
4
4
  import re
5
5
  import typing
6
- from functools import lru_cache
7
6
  from pathlib import Path
8
7
 
9
8
  from ..protocol import JSONDict
@@ -11,7 +10,6 @@ from ..protocol import JSONDict
11
10
  DEFAULT_MODELS_PATH = Path(__file__).resolve().parents[1] / "prompts" / "models.json"
12
11
 
13
12
 
14
- @lru_cache(maxsize=1)
15
13
  def load_models_by_slug() -> "typing.Dict[str, JSONDict]":
16
14
  payload = json.loads(DEFAULT_MODELS_PATH.read_text(encoding="utf-8"))
17
15
  models = payload.get("models", [])
@@ -25,10 +23,13 @@ def load_models_by_slug() -> "typing.Dict[str, JSONDict]":
25
23
  return by_slug
26
24
 
27
25
 
28
- def model_metadata(slug: "typing.Union[str, None]") -> "typing.Union[JSONDict, None]":
26
+ def model_metadata(
27
+ slug: "typing.Union[str, None]",
28
+ catalog: "typing.Union[typing.Dict[str, JSONDict], None]" = None,
29
+ ) -> "typing.Union[JSONDict, None]":
29
30
  if slug is None:
30
31
  return None
31
- models = load_models_by_slug()
32
+ models = load_models_by_slug() if catalog is None else catalog
32
33
  candidates = [name for name in models if slug.startswith(name)]
33
34
  if not candidates:
34
35
  namespace, separator, suffix = slug.partition("/")
@@ -1,9 +1,10 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-codex
3
- Version: 0.6.3
3
+ Version: 0.7.0
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
7
+ Requires-Dist: aiocontextvars>=0.2.2; python_version < '3.7'
7
8
  Requires-Dist: dataclasses>=0.8; python_version < '3.7'
8
9
  Requires-Dist: importlib-metadata>=4.8.3; python_version < '3.8'
9
10
  Requires-Dist: loguru>=0.7.3
@@ -20,7 +21,7 @@ Description-Content-Type: text/markdown
20
21
 
21
22
  # pycodex
22
23
 
23
- [中文](README_ZH.md)
24
+ [中文](README_ZH.md) · [0.7.0 release notes](https://github.com/Randomizez/pycodex/blob/v0.7.0/docs/RELEASE_0.7.0.md)
24
25
 
25
26
  pycodex is a Python implementation of the [Codex](https://github.com/openai/codex)
26
27
  coding agent. Use it in a terminal, in a browser, or from your own Python code.
@@ -85,7 +86,7 @@ The browser workspace picks up profile changes for new sessions without a restar
85
86
 
86
87
  See [configuration](docs/CONTEXT.md#配置读取与-profile) and the
87
88
  [Gemini setup example](docs/responses_server/README.md#gemini-api).
88
- Gemini 4 Argon includes a prompt adapted from Antigravity.
89
+ Gemini 4 Argon and Carbon include prompts adapted from Antigravity's coding guidance.
89
90
  Gemini tool arguments stream as they are generated; tools run after the complete call is received.
90
91
  Gemini tool results use `response.output`; returned images stay in the matching
91
92
  `functionResponse.parts`.
@@ -114,9 +115,19 @@ The agent can edit files and run commands with your user account's permissions.
114
115
  | `/cd <directory>` | Change directory while idle |
115
116
  | `/title`, `/history` | Manage the title and inspect conversation history |
116
117
  | `/resume` | List or resume saved sessions |
118
+ | `/retry` | Retry the last failed model request |
117
119
  | `/compact` | Summarize history to free context |
118
120
  | `/queue <message>` | Submit a task after the current one finishes |
119
121
 
122
+ Use `/retry 429|502` to retry either error code indefinitely, or `/retry *` to
123
+ retry every model request error, including disconnects. `/retry off` disables infinite retries.
124
+
125
+ Manual and automatic compaction preserve the tool declarations, instruction
126
+ prefix and ordinary tool choice. The Agent can use its live tools while
127
+ preparing the summary in memory. Success writes one summary checkpoint.
128
+ On failure, completed tool exchanges are saved so the Agent can use their
129
+ results on retry.
130
+
120
131
  Send a message while the agent is working to redirect it, or use `/queue` to
121
132
  wait. Sessions are saved under `~/.codex/sessions` by default.
122
133
  Ctrl+C or Ctrl+D closes the session after issued operations finish.
@@ -149,17 +160,24 @@ pycodex-ws --listen 127.0.0.1:6007 --workspace-config workspaces.json
149
160
  Open `http://127.0.0.1:6007`. The workspace uses the same model configuration as
150
161
  the CLI and provides conversations, a live HTML Canvas, and file/diff viewers.
151
162
  Chat updates arrive through two-second polling; completed replies render as Markdown.
163
+ When opening or switching conversations, a loading indicator above the input
164
+ stays visible until the latest session snapshot arrives, including when cached
165
+ messages are shown immediately.
166
+ Click the × beside a session and confirm to remove it from the workspace.
167
+ Each entry shows the time since the session's last activity.
152
168
  Click file links to inspect code, then select text and use **Insert into chat**
153
169
  to include it in your next message.
170
+ Local HTML links such as `report.html#results` open the preview at the named section.
154
171
  Each input displays its author and creation time, including separate messages
155
172
  in a steer batch. Recorded messages keep that metadata when the session resumes.
156
173
  Restoring a tab reads the rollout tail needed for its latest 80 display rows;
157
174
  Agent resume still restores the complete active context after the last checkpoint.
158
175
 
159
- The settings menu provides interface customization, password-protected
160
- workspace sharing, and [One-line Agent](packages/pycodex-ws/README.md#one-line-agent):
161
- an Agent that runs directly in most shells without installation, for bootstrapping
162
- an Agent environment or simple debugging. See the [workspace guide](packages/pycodex-ws/README.md) for
176
+ **Settings → Customize Agent** opens the optional feature catalog. Browse the
177
+ descriptions and send a feature name, ID or custom request in chat to start the Agent.
178
+ Settings also provides password-protected sharing
179
+ and [External Call](packages/pycodex-ws/README.md#external-call)
180
+ sessions that connect an external client to a Web conversation. See the [workspace guide](packages/pycodex-ws/README.md) for
163
181
  session controls, storage and Feishu setup. A separate
164
182
  [VS Code extension](packages/pycodex-ws/extensions/vscode/README.md) connects to
165
183
  the same backend, including over Remote SSH.
@@ -195,7 +213,12 @@ run_async(main())
195
213
  ```
196
214
 
197
215
  `AgentsManager` creates the runtime; `submit_input` submits work.
198
- Await `receipt.future` for the result. The example closes the runtime and any
216
+ Await `receipt.future` for the result. Models and tools import `EventScope` from
217
+ `pycodex.events` and call `EventScope.emit(event)` to notify the session’s observers.
218
+ Each observer receives its own copy. During a turn the event loop reports
219
+ observer errors and the Agent continues.
220
+ Custom model clients return token counts in `ModelResponse.usage` for goal accounting
221
+ and automatic compaction. The example closes the runtime and any
199
222
  local compatibility server when finished. See [runtime contracts](docs/RUNTIME.md#ownership) for
200
223
  custom models, tools and integrations.
201
224
 
@@ -1,22 +1,22 @@
1
1
  pycodex/__init__.py,sha256=2rP9Qd5ClJlSI3bPNB0Jmn9lJUpeeo7gcbRPUvH81eI,2904
2
2
  pycodex/__main__.py,sha256=MHKZ_ae3fSLGTLUUMOx15fWdeOnJSHhq-zslRP5F5Lc,79
3
- pycodex/agent.py,sha256=EanBfEvRLnGSfvWv_P447mUw5CezVk680h2vP4pc_YI,23848
3
+ pycodex/agent.py,sha256=uwhdz4YpJonSvGvc0FOmS1rBu-f0-jDKczNsMm-6IaU,25867
4
4
  pycodex/bootstrap.py,sha256=4bn2MhNzAHk1fFVFO1V8p2hFKcOMbe4-y2PA5qhPY98,5429
5
5
  pycodex/cli.py,sha256=HkX_fFNUyPnNo25FeSa9ZMaQG79rqk3b0oV4ZH0h68c,12576
6
- pycodex/config.py,sha256=mGM7oLaciBwGXHMQjKVifWFTd7gZTfzqlQeJSFzcQic,1218
7
- pycodex/context.py,sha256=OKIm-bs8ZosKn_tqy3CEU7XUu6rMFLbNZ_eyuIkzMaQ,42016
8
- pycodex/events.py,sha256=8gPVe_wb5r5s2hVQhywFMnz1YVvBmDLhyq43e9Y71wk,23090
9
- pycodex/model.py,sha256=SaAMysy0MaeFNbRgJS4zP_QcAerBYa5_Jilwvgtv34s,59992
10
- pycodex/multi_agents.py,sha256=3KN_Ai3UremtsQppvxd0pE7pFam_v0zBastCNi-NNx8,16150
11
- pycodex/protocol.py,sha256=qYUS9371F-DadlsYgctCpQbm3JCqyfpcWcxkANRAZWQ,15586
12
- pycodex/runtime.py,sha256=92hVNdBzugUYQb01-bbkAOYpNpjIB1IWVEU6_U6SERA,37120
6
+ pycodex/config.py,sha256=WDelsGpLgqZF38sgEEjGRwMqzpXCG4GaOueIMuOdt8A,1348
7
+ pycodex/context.py,sha256=yMG7JzsDo8OP7-SUmF-YKkIc9_GT2dgViUgiKnJfQEg,42632
8
+ pycodex/events.py,sha256=vj890PCw5QJ5IlQmCgXFI6LRUTjnrOLzM9XHALdiPBc,26305
9
+ pycodex/model.py,sha256=bnI605p10gN2LLDrHKw72bcnjd7N-GnlG-J-z24fOCU,64908
10
+ pycodex/multi_agents.py,sha256=RBBXHTyJkhHaTXfmy-eDDhz9lWoDTKdeiNYp6W5A2aY,15203
11
+ pycodex/protocol.py,sha256=sIgnfBYo9zvRBGnJWk89YDyD5Qjqq_-DcQUzwRldqnU,15635
12
+ pycodex/runtime.py,sha256=MAGSw72Y7Y-3YFoDRhfw2bOyeCwY-3W_u2zshpChUeU,39103
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
16
16
  pycodex/portable/server.py,sha256=UCQAqcO0OTNkEv4MQgR-fIt1y5bzdqMndFJtMm16Lqk,7503
17
17
  pycodex/prompts/default_base_instructions.md,sha256=D65mcj6bo4CDvVom-D9cbJRJVNquo0NghKt164_fRsg,20923
18
18
  pycodex/prompts/developer_messages.json,sha256=E-CAWMOL2KoImJ1U_1aA-OYbuVtJF0-GtZkn983B-TI,4007
19
- pycodex/prompts/models.json,sha256=m2edzANgpiRutpuw3nGJFiJQX4Y7751_omr4E4zN_uU,747802
19
+ pycodex/prompts/models.json,sha256=55xs5IxAY04P4XqC7BdfyEoXoI8uT8Fhz9SnaEwDSYA,743063
20
20
  pycodex/prompts/goals/budget_limit.md,sha256=RbvI03fMD3tTy-ytnzylqAsIr9b2O_Cb81CQejR1J-k,775
21
21
  pycodex/prompts/goals/continuation.md,sha256=K7OtQKQNoCKcgne-e-SQBGJjEpnCVcVCtML7T-82bWI,6153
22
22
  pycodex/prompts/permissions/approval_policy/never.md,sha256=QceTG6wjkaJARjYr0HYV1aPnPcpGcrkRUW-smWRr6MQ,120
@@ -27,18 +27,18 @@ pycodex/prompts/permissions/approval_policy/unless_trusted.md,sha256=XHpi1Lfx1iI
27
27
  pycodex/prompts/permissions/sandbox_mode/danger_full_access.md,sha256=nZ7YHacBd3cAHKRZc9XClOOOnXJPXPh0WFBueh5C2D0,197
28
28
  pycodex/prompts/permissions/sandbox_mode/read_only.md,sha256=2rAPEXsBYCcuttI5j3euS-3uv_v97catIsnhxlSQSIM,173
29
29
  pycodex/prompts/permissions/sandbox_mode/workspace_write.md,sha256=lVN-LwrBbHqlv5yVjcd_mU8tzZW8jfKpTatJKIZu9HI,277
30
- pycodex/tools/__init__.py,sha256=yE_9gmbNrbUKXMfZO79Y8chfHMmOe9NBozy4i0vn0bY,5175
30
+ pycodex/tools/__init__.py,sha256=RJ0Ejcqwt41jFwEhTtvKjYu7wmJzI3Kd--3oGAQdZ8U,5101
31
31
  pycodex/tools/agent_tool_schemas.py,sha256=juw4b2pp2tDhDPVTVY4rytm8IyVr2h686Qfk_5e9S0E,780
32
32
  pycodex/tools/apply_patch_tool.py,sha256=LcyJuGtndmLLbFL1sIUQ2Y6KLCef95KBfi0adGA1bN8,13183
33
33
  pycodex/tools/base_tool.py,sha256=dD_makVyjbnJN_cAhRAj_sJJHYh8VUDoXFiRoWDh6Ko,8644
34
- pycodex/tools/clock_manager.py,sha256=Xn1i4aasN_ZZdL9WsA_cS-RAVLV-SQXmOecMc1nGCa4,5884
34
+ pycodex/tools/clock_manager.py,sha256=mOlTjqHqWTCH3MVKj9nw9UPWmuABIsVjqKalFLh4oCQ,5525
35
35
  pycodex/tools/clock_tool.py,sha256=14Y1uLagSuEO8eaACQcQQbPZP1R6cSAYaReZIyZen4c,3790
36
36
  pycodex/tools/code_mode_manager.py,sha256=_bZ7RlKzAEqb2m6PBfR7Or1GJYajeuSz1xCmuJcGsV8,15975
37
- pycodex/tools/exec_command_tool.py,sha256=Mf2FRsx6o5pWq68PCXNCSOce4wzwqyX6VrXNOvym_So,4076
38
- pycodex/tools/exec_runtime.py,sha256=vR4HfTxknxbKDhO7QFlBDgltKegFy5KJE1eAODWVYqY,12061
37
+ pycodex/tools/exec_command_tool.py,sha256=1LXoHkK-1ueACABk-qE5qXOVpp8vhFqtakn9M1q8pqU,4583
38
+ pycodex/tools/exec_runtime.py,sha256=9e5dMdOJGF-kv7r9v8PZIDprVVvVSI_4wUa2_wNK40Y,12243
39
39
  pycodex/tools/exec_tool.py,sha256=7HQ8sazJBr4WQklJsCJS30kfVaQOsg5gBgIutC6QyRY,5209
40
40
  pycodex/tools/followup_task_tool.py,sha256=D3nRu6csiriwe1WVig_HNLRzJQfDNMmk2R75vMfSI4Y,1609
41
- pycodex/tools/goal_manager.py,sha256=8zicCSjqJgYyONL6EaOIyaGjTA6EBECi1NYQgEwLFms,8480
41
+ pycodex/tools/goal_manager.py,sha256=wDTSsHX1dCp46xi_aSyged76Ggnw7ES4NBzMKxYfk4g,8058
42
42
  pycodex/tools/goal_tool.py,sha256=TShHf6dh6YCdMPoc6zuIgj0W2D_O95ewmh6OZKFXAX0,5225
43
43
  pycodex/tools/grep_files_tool.py,sha256=KCBVNaSTU45ND-iAhh14YawMyjQnMRZnGI1NGKL3zgg,4809
44
44
  pycodex/tools/interrupt_agent_tool.py,sha256=q4TBTam6sFLwAQwDsoz1WNL_b9y1Esne7awgc77gerw,1589
@@ -47,12 +47,12 @@ pycodex/tools/list_dir_tool.py,sha256=_U6ouRcVbGHT5mChVyUsiMgDGrFK7EFMFaspPLAHtH
47
47
  pycodex/tools/python_tool_schema.py,sha256=yoJHP7GJGSu6oyT_0nxbGJWy_TaTobFwDoFQMl65464,5781
48
48
  pycodex/tools/read_file_tool.py,sha256=YK__uhIVldBjAQega5S_ZuZU5jgP_kLOwr-YhjAmRo4,9735
49
49
  pycodex/tools/request_permissions_tool.py,sha256=t-Y-iEhvUyE9IJAeiwnzfUdbQ73Gw7uxFcWLwS0no4o,4000
50
- pycodex/tools/runtime_services.py,sha256=oEqUyR7-oHQdTsEWXoiP7VKP_JDiG5dc8AjlSGQFjYI,7542
50
+ pycodex/tools/runtime_services.py,sha256=59Vg22uQ6F0VPokAVf8x5AXdSdmj8_FffBzheD6RLFo,7810
51
51
  pycodex/tools/send_message_tool.py,sha256=mH51ufxTCcsHuLFI1tDKyX14AHPMij2cMJLJdlFFjZQ,1414
52
52
  pycodex/tools/shell_command_tool.py,sha256=bJKlTdIs2i28vH5f4GZfpunezr6JNicRzsL_6Vc3HvU,3675
53
53
  pycodex/tools/shell_tool.py,sha256=I6lYLABSmLddRrNmpk0Li83AV55MI8x0bckWaRkFGI0,3527
54
54
  pycodex/tools/spawn_agent_tool.py,sha256=yjkjHsUxGdSHOn9_kZTs8Bd-0ZnWznZxOfcy3E-WKcA,3596
55
- pycodex/tools/unified_exec_manager.py,sha256=O1o2dGkLsOLFf1XZ0_HeQQT_NIlDT6NOC1y2_OaYchw,14479
55
+ pycodex/tools/unified_exec_manager.py,sha256=jFI6y8jsJ-9uv0S_8m81FVFJYbIxIg4uUeHPG8NdCpM,14853
56
56
  pycodex/tools/update_plan_tool.py,sha256=xwrSrerw5qfkbFc9Ltx1OZEmD__CWtryOy3UhL0-Jp4,3198
57
57
  pycodex/tools/view_image_tool.py,sha256=H7OP-QZEU5Gf-E4YnQbXfu2hDkL5-dJ3Apla2YYjErQ,3754
58
58
  pycodex/tools/wait_agent_tool.py,sha256=uo4KcFZBm8BAmw7i_wVjg2i3f_T9PrGL4ZnxbGt3-38,2516
@@ -62,18 +62,18 @@ pycodex/tools/write_stdin_tool.py,sha256=jvBDchLLmoDITd7g-ZVeEVXHRhWKkmnjM5laL-5
62
62
  pycodex/utils/__init__.py,sha256=ih_KyZ2_bajR5YlZ1QMTWOHnuEBda-S3gQ7PwnBtLZQ,453
63
63
  pycodex/utils/async_bridge.py,sha256=BXsKTUTUvUtPJnItQlulFRdV7opdKKDlsKLdtVTYshs,1732
64
64
  pycodex/utils/codex_config.py,sha256=oCisEGUJcJxcZL1wIqXkon1xTShymOlz96E3VgDVTlY,3748
65
- pycodex/utils/compactor.py,sha256=qSHZpTP_hWuxuqeVt6JijbtgkXiW2act1CdTQ5wovBM,6399
66
- pycodex/utils/compat.py,sha256=16FyHHlDES57mOHCasN4FWveEkGYd2aZex9-Eojlkg8,5277
65
+ pycodex/utils/compactor.py,sha256=Nzh_W2YxU-c-HBjsPiUmAYxlXfBwRM75uvnDeIkT6u0,4172
66
+ pycodex/utils/compat.py,sha256=eVI53Jb3TxXQuiNeDwtlI0q2KW7KFGSQlT6mCES9E70,5487
67
67
  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=ULvTSktxMd--VEL2UJA6CbuWHLsrctAcAuEk91wGLL8,12021
71
+ pycodex/utils/event_helpers.py,sha256=99f94sdQOdFVMzGKBzeNzhs67ccM3HZPj7faqb1G2AI,12260
72
72
  pycodex/utils/get_env.py,sha256=L4S8h84tkgxZKvrxY7ezTgePbXepG-yIigUTKeY6uuE,6094
73
73
  pycodex/utils/history.py,sha256=qgt5IxxkfCYjjpr08VJFhasICSSlqxQM7d-DjRJVjHA,3845
74
74
  pycodex/utils/http_headers.py,sha256=4Jlnmun6QFSQ6L7javlDQfom1p2AZZQFXvcHzD3_cQk,877
75
75
  pycodex/utils/image_utils.py,sha256=OUzUs0Cow4L8Z2np0EBeEUotAqqsCmRmhrV8AxZUXRw,2460
76
- pycodex/utils/model_metadata.py,sha256=uK3iI4yC7Ge7yN4I1_gQYalQ4MYKddz2qMwsmQb-P80,1337
76
+ pycodex/utils/model_metadata.py,sha256=kCfe3jof1wrXJX9f2nDB9XN11v6JFSATNW4ewXb9gBI,1392
77
77
  pycodex/utils/random_ids.py,sha256=jLTxZZ0MBbRdQOFDFWGVRjWzIo6FKSQ5ADXbQSLPp1s,379
78
78
  pycodex/utils/session_persist.py,sha256=7JXXInvKaeO-9zz-n4LrnqrNn4BvFPEoVgZ88c9yZrM,31333
79
79
  pycodex/utils/skill_catalog.py,sha256=3W-r6pn_fzEGyd89aKD2shGNhrUK2hLgrlwOlqYOpgU,618
@@ -86,9 +86,9 @@ pycodex/utils/_aes_gcm/gcm.py,sha256=Z8fYHpnLpqJyTPmjDOZtryqe0xmT_93vscNuJe5ZY-w
86
86
  pycodex/utils/_aes_gcm/source-sha256.json,sha256=g9uPWXuA0D9Wq9EGnduyiVanTgi8QWRFW-9T69FG-fc,215
87
87
  responses_server/__init__.py,sha256=SOMO5Q-Z0dpaRih8yWuKUTclPl28tpy_XIPTOO_BPq0,447
88
88
  responses_server/__main__.py,sha256=876xZTqhPeDBD2GKKr8pKX33Af8PhFTosAI8bYQsFgQ,61
89
- responses_server/app.py,sha256=6D23sAyftNUwGwmWT7WGM6aau78i7KCkhZfc16Sul3o,8600
89
+ responses_server/app.py,sha256=9DwnX7DlvaGFpqy4FwVOxcIjIFE_nWLPVUJt1ivWh5s,8773
90
90
  responses_server/config.py,sha256=XxBRXrLEeCnaqKXGV-f_3iTtur0hPn4yqM7wLngcTFM,2931
91
- responses_server/gemini_api.py,sha256=d5ChR4_fOnx2tPVSQQWWYIgXuIEcHdJUScaOptoGii4,16163
91
+ responses_server/gemini_api.py,sha256=cVc9UMN6Mjv9MRaIXFxLFfU0WpThDCBrebvSkd0osxU,16745
92
92
  responses_server/messages_api.py,sha256=dDZ2z2AfE5Mfayuy0yt3tmgYp7fj11QtOBQ51gtdVCE,19613
93
93
  responses_server/payload_processors.py,sha256=-lcw5DJ-uGiK4ZDsw373gjxpqVTapC-kWGVBXFGmr1A,3585
94
94
  responses_server/request_translation.py,sha256=qG5rxW0bf6NS83L24YmMOuVNpPZGWnl2NVjNtQ-_GeQ,20508
@@ -97,12 +97,12 @@ responses_server/session_store.py,sha256=nwGxQL6nUVKnDVeDHz8IzqNQ7dWk8Ybf0URekOH
97
97
  responses_server/stream_events.py,sha256=nWi5VcssytFD3SDHW5hQik5LR-US-Clk-5EEWAi3t-k,4984
98
98
  responses_server/stream_router.py,sha256=7-_KoXtaDtEISeSxGL-tJ-l6gmypbIgQ_Mxx9dtyklA,15474
99
99
  responses_server/trajectory_dump.py,sha256=5_Wy6tslszrqx3j1JeP_boyTbzIicKy8No84PzMnmHk,5111
100
- responses_server/transport.py,sha256=PmflqUUZ-p7dO4vTFPNM4SzbQITXT0lntMqwiTrw2rw,16810
100
+ responses_server/transport.py,sha256=-pR-8zMxarSOH8H62i6IaG9nxi-IcWibRQarXs3Nk-s,17150
101
101
  responses_server/tools/__init__.py,sha256=ivsBSEy0SBUhY-Uea5v1XMLXShkwHdCVl0id-1FwdZg,150
102
102
  responses_server/tools/custom_adapter.py,sha256=leYNJKp4Ute0JWNfGpe-ntSyFqRgYCdWF4dMYQFINlk,8615
103
103
  responses_server/tools/web_search.py,sha256=JyF6NHCS0SqoBrO18jX8cgBsiV4OYQBPz0Ky4u3juSQ,9059
104
- python_codex-0.6.3.dist-info/METADATA,sha256=shh4KMFZrpoJD0vfiDk2WFzZ-5tbAni_J4nn8bevZ-g,8187
105
- python_codex-0.6.3.dist-info/WHEEL,sha256=KGYbc1zXlYddvwxnNty23BeaKzh7YuoSIvIMO4jEhvw,87
106
- python_codex-0.6.3.dist-info/entry_points.txt,sha256=sNUVakoVuTrzJH505ZgRTQxmtRRPUHV_EH0i6EbYTyM,45
107
- python_codex-0.6.3.dist-info/licenses/LICENSE,sha256=0X8ifk312hYAORM4hlzg8wVSEXYKNmiPgWlB1YIy2Nw,10926
108
- python_codex-0.6.3.dist-info/RECORD,,
104
+ python_codex-0.7.0.dist-info/METADATA,sha256=9IpkJ6m_iJqpXm2UV0_9JjUkrWhZWrp5JNrF467pIZo,9743
105
+ python_codex-0.7.0.dist-info/WHEEL,sha256=KGYbc1zXlYddvwxnNty23BeaKzh7YuoSIvIMO4jEhvw,87
106
+ python_codex-0.7.0.dist-info/entry_points.txt,sha256=sNUVakoVuTrzJH505ZgRTQxmtRRPUHV_EH0i6EbYTyM,45
107
+ python_codex-0.7.0.dist-info/licenses/LICENSE,sha256=0X8ifk312hYAORM4hlzg8wVSEXYKNmiPgWlB1YIy2Nw,10926
108
+ python_codex-0.7.0.dist-info/RECORD,,
responses_server/app.py CHANGED
@@ -59,6 +59,10 @@ def _stream_events(
59
59
  error_type = getattr(exc, "error_type", None)
60
60
  if error_type:
61
61
  error["type"] = error_type
62
+ if exc.error_code is not None:
63
+ error["code"] = exc.error_code
64
+ if exc.http_status is not None:
65
+ error["http_status"] = exc.http_status
62
66
  yield _format_sse_event(
63
67
  "response.failed",
64
68
  {
@@ -1,5 +1,6 @@
1
1
  """Gemini generateContent request and streaming response adapter."""
2
2
 
3
+ import base64
3
4
  import json
4
5
  import re
5
6
  import uuid
@@ -7,6 +8,10 @@ from copy import deepcopy
7
8
 
8
9
  from .request_translation import inline_history_instructions
9
10
 
11
+ SKIP_THOUGHT_SIGNATURE_VALIDATOR = base64.b64encode(
12
+ b"skip_thought_signature_validator"
13
+ ).decode("ascii")
14
+
10
15
 
11
16
  class GeminiAPIAdapterError(ValueError):
12
17
  pass
@@ -36,16 +41,17 @@ def build_gemini_request(request):
36
41
  # Unsigned empty text can end a stream, but is not input data.
37
42
  parts = [part for part in parts
38
43
  if part.get("text") != "" or "thoughtSignature" in part]
44
+ native_call_ids = {
45
+ entry["call_id"] for entry in native
46
+ if "call_id" in entry and "functionCall" in entry["part"]
47
+ }
48
+ for call in message.get("tool_calls", []):
49
+ if call["id"] not in native_call_ids:
50
+ parts.append(_unsigned_function_call_part(call))
39
51
  else:
40
52
  parts = _content_parts(message.get("content"))
41
53
  for call in message.get("tool_calls", []):
42
- function = call["function"]
43
- arguments = json.loads(function["arguments"])
44
- if not isinstance(arguments, dict):
45
- raise GeminiAPIAdapterError("Gemini function arguments must be objects")
46
- parts.append({"functionCall": {
47
- "name": function["name"], "args": arguments, "id": call["id"],
48
- }})
54
+ parts.append(_unsigned_function_call_part(call))
49
55
  role = "model"
50
56
  elif role == "tool":
51
57
  call_id = message["tool_call_id"]
@@ -116,6 +122,19 @@ def build_gemini_request(request):
116
122
  return payload
117
123
 
118
124
 
125
+ def _unsigned_function_call_part(call):
126
+ function = call["function"]
127
+ arguments = json.loads(function["arguments"])
128
+ if not isinstance(arguments, dict):
129
+ raise GeminiAPIAdapterError("Gemini function arguments must be objects")
130
+ return {
131
+ "functionCall": {
132
+ "name": function["name"], "args": arguments, "id": call["id"],
133
+ },
134
+ "thoughtSignature": SKIP_THOUGHT_SIGNATURE_VALIDATOR,
135
+ }
136
+
137
+
119
138
  def _content_parts(content):
120
139
  if not content:
121
140
  return []