python-codex 0.2.7__py3-none-any.whl → 0.3.1__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.
Files changed (85) hide show
  1. pycodex/__init__.py +14 -14
  2. pycodex/agent.py +465 -499
  3. pycodex/bootstrap.py +417 -0
  4. pycodex/cli.py +236 -510
  5. pycodex/compat.py +19 -5
  6. pycodex/context.py +222 -212
  7. pycodex/doctor.py +52 -48
  8. pycodex/events.py +857 -0
  9. pycodex/feishu_card.py +217 -163
  10. pycodex/feishu_link.py +43 -83
  11. pycodex/model.py +324 -253
  12. pycodex/model_metadata.py +19 -7
  13. pycodex/portable.py +76 -45
  14. pycodex/portable_server.py +32 -24
  15. pycodex/prompts/models.json +321 -883
  16. pycodex/protocol.py +177 -137
  17. pycodex/runtime.py +579 -176
  18. pycodex/runtime_services.py +204 -157
  19. pycodex/tools/__init__.py +1 -1
  20. pycodex/tools/apply_patch_tool.py +69 -48
  21. pycodex/tools/base_tool.py +89 -42
  22. pycodex/tools/clock_tool.py +58 -25
  23. pycodex/tools/close_agent_tool.py +2 -2
  24. pycodex/tools/code_mode_manager.py +77 -64
  25. pycodex/tools/exec_command_tool.py +26 -11
  26. pycodex/tools/exec_tool.py +4 -4
  27. pycodex/tools/grep_files_tool.py +12 -10
  28. pycodex/tools/ipython_tool.py +10 -13
  29. pycodex/tools/list_dir_tool.py +13 -9
  30. pycodex/tools/read_file_tool.py +29 -17
  31. pycodex/tools/request_permissions_tool.py +15 -5
  32. pycodex/tools/request_user_input_tool.py +13 -104
  33. pycodex/tools/resume_agent_tool.py +2 -2
  34. pycodex/tools/send_input_tool.py +11 -8
  35. pycodex/tools/shell_command_tool.py +7 -5
  36. pycodex/tools/shell_tool.py +7 -5
  37. pycodex/tools/spawn_agent_tool.py +7 -4
  38. pycodex/tools/unified_exec_manager.py +102 -69
  39. pycodex/tools/update_plan_tool.py +8 -5
  40. pycodex/tools/view_image_tool.py +7 -5
  41. pycodex/tools/wait_agent_tool.py +27 -4
  42. pycodex/tools/wait_tool.py +5 -4
  43. pycodex/tools/web_search_tool.py +4 -2
  44. pycodex/tools/write_stdin_tool.py +12 -11
  45. pycodex/utils/__init__.py +2 -17
  46. pycodex/utils/compactor.py +41 -72
  47. pycodex/utils/debug.py +2 -2
  48. pycodex/utils/dotenv.py +6 -7
  49. pycodex/utils/event_helpers.py +190 -0
  50. pycodex/utils/get_env.py +27 -70
  51. pycodex/{image_utils.py → utils/image_utils.py} +8 -11
  52. pycodex/utils/random_ids.py +1 -2
  53. pycodex/utils/session_persist.py +217 -163
  54. pycodex/utils/truncation.py +21 -45
  55. python_codex-0.3.1.dist-info/METADATA +743 -0
  56. python_codex-0.3.1.dist-info/RECORD +91 -0
  57. responses_server/__init__.py +1 -5
  58. responses_server/__main__.py +0 -1
  59. responses_server/app.py +34 -33
  60. responses_server/config.py +23 -23
  61. responses_server/messages_api.py +51 -53
  62. responses_server/payload_processors.py +25 -20
  63. responses_server/server.py +11 -11
  64. responses_server/session_store.py +14 -11
  65. responses_server/stream_router.py +209 -98
  66. responses_server/tools/custom_adapter.py +17 -16
  67. responses_server/tools/web_search.py +39 -36
  68. responses_server/trajectory_dump.py +36 -14
  69. workspace_server/__main__.py +0 -1
  70. workspace_server/app.py +465 -377
  71. workspace_server/owned_process.py +27 -0
  72. workspace_server/workspace.html +854 -228
  73. workspace_server/workspaces.html +94 -95
  74. workspace_server/workspaces.py +141 -84
  75. pycodex/collaboration.py +0 -20
  76. pycodex/interactive_session.py +0 -415
  77. pycodex/prompts/collaboration_default.md +0 -11
  78. pycodex/prompts/collaboration_plan.md +0 -128
  79. pycodex/utils/toolcall_visualize.py +0 -713
  80. pycodex/utils/visualize.py +0 -560
  81. python_codex-0.2.7.dist-info/METADATA +0 -455
  82. python_codex-0.2.7.dist-info/RECORD +0 -93
  83. {python_codex-0.2.7.dist-info → python_codex-0.3.1.dist-info}/WHEEL +0 -0
  84. {python_codex-0.2.7.dist-info → python_codex-0.3.1.dist-info}/entry_points.txt +0 -0
  85. {python_codex-0.2.7.dist-info → python_codex-0.3.1.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,743 @@
1
+ Metadata-Version: 2.1
2
+ Name: python-codex
3
+ Version: 0.3.1
4
+ Summary: A minimal Python extraction of Codex's main agent loop
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.6.2
7
+ Requires-Dist: dataclasses>=0.8; python_version < '3.7'
8
+ Requires-Dist: fastapi<0.84,>=0.83.0; python_version < '3.7'
9
+ Requires-Dist: fastapi>=0.83.0; python_version >= '3.7'
10
+ Requires-Dist: importlib-metadata>=4.8.3; python_version < '3.8'
11
+ Requires-Dist: loguru>=0.7.3
12
+ Requires-Dist: pillow>=8.4.0; python_version < '3.7'
13
+ Requires-Dist: pillow>=9.0.0; python_version >= '3.7'
14
+ Requires-Dist: prompt-toolkit>=3.0.36
15
+ Requires-Dist: pycryptodomex>=3.20
16
+ Requires-Dist: pyyaml>=6.0
17
+ Requires-Dist: requests>=2.27.1
18
+ Requires-Dist: tomli<2,>=1.2.3; python_version < '3.11'
19
+ Requires-Dist: typing-extensions>=4.1.1; python_version < '3.8'
20
+ Requires-Dist: uvicorn<0.17,>=0.16.0; python_version < '3.7'
21
+ Requires-Dist: uvicorn>=0.16.0; python_version >= '3.7'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # pycodex
25
+
26
+ English README. Chinese version: `README_ZH.md`
27
+
28
+ 0.3.0 release preparation and Python API migration: `docs/RELEASE_0.3.0.md`.
29
+
30
+ PyPI distributions:
31
+
32
+ - Primary package: `python-codex`
33
+ - Workspace install alias: `pycodex-ws`
34
+
35
+ The import path remains `pycodex`; the CLI commands are `pycodex` and
36
+ `pycodex-ws`.
37
+
38
+ `pycodex-ws` is a thin metapackage that depends on the exact matching
39
+ `python-codex` version. The implementation and console script remain owned by
40
+ `python-codex`, so the two distributions never install duplicate modules.
41
+
42
+ This repository extracts the core Codex agent loop from upstream Codex
43
+ (`https://github.com/openai/codex`) into a deliberately small Python version,
44
+ while preserving the two most important layers:
45
+
46
+ - `submission_loop`: sequentially consumes submitted operations.
47
+ - `run_turn`: keeps executing `model sample -> tool call -> feed tool result
48
+ back into the model` inside a single turn until a final answer is reached.
49
+
50
+ Relevant Rust reference points:
51
+
52
+ - `codex-rs/core/src/codex.rs` -> `submission_loop`
53
+ - `codex-rs/core/src/codex.rs` -> `run_turn`
54
+ - `codex-rs/core/src/codex.rs` -> `run_sampling_request`
55
+ - `codex-rs/core/src/tools/router.rs` -> `ToolRouter`
56
+ - `codex-rs/core/src/stream_events_utils.rs` -> `handle_output_item_done`
57
+
58
+ ## Quick Start
59
+
60
+ Install the full package or the workspace-oriented alias:
61
+
62
+ ```bash
63
+ pip install python-codex
64
+ pip install pycodex-ws
65
+ ```
66
+
67
+ Install dependencies first:
68
+
69
+ ```bash
70
+ uv sync
71
+ ```
72
+
73
+ Try the real entry points:
74
+
75
+ ```bash
76
+ uv run pycodex "Reply with exactly OK."
77
+ uv run pycodex
78
+ ```
79
+
80
+ A VS Code frontend is available in [`extensions/vscode`](extensions/vscode/README.md).
81
+ It reuses an existing `python-codex>=0.3.1` installation. On first use, missing
82
+ or older backends are installed/upgraded with pip in the selected Python
83
+ environment on the workspace host; compatible versions need no network check.
84
+ It starts a dedicated `pycodex-ws` workspace on the project's host and opens a
85
+ chat in the left sidebar using VS Code's stable WebviewView API. Each chat
86
+ creates a workspace session with no code context attached. You can insert code
87
+ from editors, diffs or file-tree selections as editable tokens among your words.
88
+ Each token expands at its position when you send the message.
89
+ Previous chats fold into live status entries; each can be
90
+ reopened or closed, and models can be changed with `/model`.
91
+ Remote workspaces run Python on the remote host. A stdin pipe ties each backend
92
+ to its extension host; normal closure or host failure triggers draining and exit.
93
+ `pycodex-ws` always shuts down on stdin EOF, after accepted work finishes.
94
+ Keep stdin open while running the server; redirecting it from `/dev/null`
95
+ causes the server to shut down.
96
+ Workspace configuration uses a temporary JSON file passed to `--workspace-config`;
97
+ normal backend exit removes the temporary directory.
98
+ The extension uses that host's `~/.codex/config.toml` by default.
99
+ The chat settings menu selects a project venv or another Python interpreter
100
+ and edits the Codex profile. Changes offer a window reload when a backend is
101
+ already running.
102
+ Its context ring shows the same remaining budget and usage details as the
103
+ workspace web frontend.
104
+ See the extension README for building a VSIX, server setup and Remote SSH usage.
105
+
106
+ ## Design Tradeoffs
107
+
108
+ This is not a 1:1 port of the Rust implementation. The current goal is a
109
+ minimal reusable kernel that converges on the upstream behavior over time:
110
+
111
+ 1. Use a thin `ModelClient` protocol to abstract the model side.
112
+ 2. Use `ToolRegistry` to manage tool specs and executors.
113
+ 3. Use `AgentLoop` to implement the core closed loop.
114
+ 4. Use `AgentRuntime` to preserve the outer submission queue so it can keep
115
+ converging toward Rust's `submission_loop` later.
116
+
117
+ Intentionally not included yet:
118
+
119
+ - TUI / streaming incremental rendering
120
+ - MCP / connectors / sandbox / approvals
121
+ - memory / compact / review mode
122
+ - a full production OpenAI adapter surface
123
+
124
+ All of those can be layered on later. For now, the project is focused on
125
+ nailing the core tool-augmented reasoning loop first.
126
+
127
+ ## Layout
128
+
129
+ - `pycodex/protocol.py`: minimal conversation item / prompt protocol
130
+ - `pycodex/events.py`: typed events, plain-text views and stateful presentation
131
+ - `pycodex/utils/event_helpers.py`: stateless text, color, summary and result-formatting helpers
132
+ - `pycodex/utils/image_utils.py`: image loading, resizing and data-URL preparation
133
+ - `pycodex/model.py`: model client protocol and Responses API adapter
134
+ - `pycodex/cli.py`: single-turn/interactive entry points, terminal I/O executor and input loop
135
+ - `pycodex/bootstrap.py`: frontend-independent model, tools, Agent and session assembly
136
+ - `pycodex/tools/base_tool.py`: `BaseTool`, `ToolRegistry`, `ToolContext`
137
+ - `pycodex/tools/`: concrete tool implementations
138
+ - `pycodex/agent.py`: inner turn loop
139
+ - `pycodex/runtime.py`: session commands, submission queues and frontend event subscriptions
140
+ - `extensions/vscode/`: VS Code chat frontend using the workspace HTTP API
141
+ - `tests/test_agent.py`: core behavior tests
142
+
143
+ ## Current Alignment Status
144
+
145
+ Current progress is easiest to read in layers:
146
+
147
+ - prompt/context alignment:
148
+ - the 2026-09-23 audit uses Codex CLI 0.153.4: shared context matches for
149
+ `gpt-5.4` first/resume/tool-follow-up requests and suffixed Astra first/resume
150
+ requests, with explicit exclusions recorded in `docs/CONTEXT.md`;
151
+ - this layer is now mainly handled by `pycodex/context.py` plus vendored
152
+ prompt data; model lookup uses the longest matching slug prefix without
153
+ rewriting the requested model name.
154
+ - turn-loop semantic alignment:
155
+ - `AgentLoop` no longer uses a fixed 12-iteration cap by default;
156
+ - like upstream, it now converges naturally based on whether there is still
157
+ follow-up work or tool handoff to do;
158
+ - the local iteration-limit parameter is gone.
159
+ - request-level alignment:
160
+ - full raw request parity is **not** claimed: client-generated message/result
161
+ IDs, the tool catalog, new upstream telemetry, and some permission profiles
162
+ still differ;
163
+ - the default CLI keeps the `codex-tui` client identity, but intentionally
164
+ omits collaboration-mode developer instructions;
165
+ - `User-Agent` and rollout `cli_version` use the fixed upstream alignment
166
+ version `0.153.4`; session creation does not run `codex --version`;
167
+ - `tests/compare_context_requests.py` keeps raw differences separate from
168
+ shared-context exclusions; older interactive captures are not a fresh
169
+ certification of 0.153.4 interactive behavior.
170
+ - structured user input:
171
+ - `request_user_input` remains declared, but calls return
172
+ `request_user_input is unavailable in Default mode` without opening a question;
173
+ - attaching a frontend or input handler does not enable it. The generic runtime
174
+ input and permission services remain available;
175
+ - local tool-result `success` metadata is omitted from API requests, including
176
+ when replaying answers from older rollouts.
177
+
178
+ See `docs/ALIGNMENT.md` for more detailed notes.
179
+
180
+ `PYCODEX_DUMP` records downstream `stream_completed` and `stream_error_type`
181
+ alongside usage, finish reason, and exact token IDs. Failed attempts remain
182
+ in the dump, including failures before the first chunk. Chat SSE `error`
183
+ payloads propagate as `response.failed`, never as an empty completed response.
184
+ Chained failures also retain `stream_error_cause_type` and, for HTTP errors,
185
+ `stream_error_http_status`; exception messages, headers and URLs are not
186
+ copied into these diagnostic fields.
187
+
188
+ Downstream errors include elapsed time, timeout, failure stage, response-header
189
+ and first-chunk timing, and received chunk count directly in the error message.
190
+
191
+ ## Live Model Integration
192
+
193
+ If this machine already has a Codex CLI configuration, `pycodex` can reuse the
194
+ `model`, `model_provider`, `base_url`, and `env_key` from
195
+ `~/.codex/config.toml` directly:
196
+
197
+ ```python
198
+ from pycodex import ResponsesModelClient
199
+
200
+ client = ResponsesModelClient.from_codex_config()
201
+ ```
202
+
203
+ The current implementation uses the streaming OpenAI-compatible `/responses`
204
+ endpoint. This path has already been validated against the local
205
+ `~/.codex/config.toml` setup.
206
+
207
+ When launched through the CLI, `pycodex` also loads `.env` from the same
208
+ configuration directory before reading config (typically `~/.codex/.env`), so
209
+ provider keys and similar environment variables can live there. To match
210
+ upstream Codex, variables starting with `CODEX_` are not imported from `.env`.
211
+
212
+ ## pycodex CLI
213
+
214
+ `pycodex` now defaults to a minimal interactive entry point. Internally it uses
215
+ `AgentRuntime` to drive the turn submission loop and reuses
216
+ `~/.codex/config.toml` by default:
217
+
218
+ ```bash
219
+ pycodex
220
+ pycodex "Summarize this repo in one sentence."
221
+ printf 'Reply with exactly OK.' | pycodex
222
+ pycodex --json "Reply with exactly OK."
223
+ pycodex --profile model_proxy "Reply with exactly OK."
224
+ pycodex --profile opus --use-messages "Reply with exactly OK."
225
+ pycodex --vllm-endpoint http://127.0.0.1:18000 "Reply with exactly OK."
226
+ pycodex --put @127.0.0.1:5577
227
+ pycodex --put /data/.codex/@127.0.0.1:5577
228
+ pycodex --call SECRET-CALLID@127.0.0.1:5577 "Reply with exactly OK."
229
+ pycodex doctor
230
+ pycodex-ws --listen 0.0.0.0:6007 --workspace-config ./workspaces.json
231
+ pycodex-ws --listen 0.0.0.0:6007 --workspace-config ./workspaces.json --password 12345
232
+ ```
233
+
234
+ Current behavior:
235
+
236
+ - with no argv prompt and a TTY stdin, enter interactive mode
237
+ - with an argv prompt or piped stdin, run a single turn
238
+ - `pycodex-ws` starts the standalone browser workspace manager and serves each
239
+ workspace with a board pane and a pycodex session pane
240
+ - interactive mode exits through `/exit`, `/quit`, Ctrl+D on an empty prompt,
241
+ or a single Ctrl+C; accepted work finishes before cleanup and normal exit.
242
+ A `[closing]` message explains the wait. Press Ctrl+C again while closing
243
+ to immediately exit the CLI with status 130. This skips remaining cleanup;
244
+ external tool processes may keep running.
245
+ - interactive mode shows a compact event stream for user-visible phases such as
246
+ tool execution and model follow-up after tool results
247
+ - assistant text is printed from streaming deltas directly
248
+ - interactive mode supports `/history`, `/title`, `/model`, `/resume`, `/compact`,
249
+ and `/fork`
250
+ - `/model <name>` switches the model used by later turns in the current
251
+ interactive session; `/model` shows the current model and available choices
252
+ - `/resume` with no argument lists the currently resumable sessions by their
253
+ first user-message preview; `/resume 1` resumes the first listed session
254
+ - `/resume <number>` replaces the in-memory history with the selected recorded
255
+ Codex rollout from `CODEX_HOME/sessions`. Tool calls without recorded results
256
+ are omitted during restore; later saved messages and completed tools remain
257
+ available, and the source file is left intact.
258
+ - `/compact` synthesizes a local handoff summary, replaces the in-memory
259
+ conversation history with the compacted view, and appends a compacted-history
260
+ entry to the rollout so later `/resume` sees the same state. The handoff remains
261
+ model context, but is omitted from frontend conversation blocks and `/history`;
262
+ real replies after compaction remain visible, including after resume or fork.
263
+ - `/fork` allocates a new Agent/provider session id and lazy rollout while
264
+ preserving current history and the workspace tab; the original rollout stays intact
265
+ - workspace tabs follow the fork's rollout once it is written. Before that,
266
+ restart restores the source recording and creates a fresh fork, preserving
267
+ history and title without appending to the source file.
268
+ - `model_auto_compact_token_limit = <tokens>` in `config.toml` enables the same
269
+ compaction path automatically when the latest reported usage reaches that
270
+ threshold before a follow-up sampling request or the next user turn
271
+ - `service_tier = "fast"` enables Fast mode for models whose vendored metadata
272
+ advertises the `priority` service tier; pycodex follows upstream Codex by
273
+ sending `service_tier = "priority"` on the Responses request, while
274
+ `service_tier = "default"` or unsupported tiers are omitted
275
+ - if a model request fails with `context_length_exceeded`, pycodex now treats
276
+ the provider-reported requested token count as a failed-request usage sample,
277
+ triggers the same compact path immediately, and retries the request once; if
278
+ the compact request is also over the limit, it repeatedly drops the oldest
279
+ tool response plus its matching tool call before retrying compact
280
+ - new sessions are now recorded under `CODEX_HOME/sessions/.../rollout-*.jsonl`
281
+ with a stable session/thread id and per-item append+flush semantics so
282
+ `/resume` reads back the same rollout format
283
+ - if `TURN_HOOK.md` exists in the workspace root and is non-empty, each
284
+ completed turn also forks the just-finished history into a temporary,
285
+ non-persisted follow-up session and submits the file contents as the next
286
+ user instruction; this is intended for side-effect follow-ups such as
287
+ Feishu notifications
288
+ - `/link <feishu-email|open_id|chat_id>` attaches the current interactive
289
+ session to a Feishu card; multiple sessions in the same pycodex process share
290
+ one Feishu long-connection listener and route card actions by message id
291
+ - Feishu user OAuth stores its refresh token only in
292
+ `~/.codex/.feishu_refresh_token` (mode `0600`). Run
293
+ `env -u VIRTUAL_ENV uv run python tools/feishu_oauth.py` from this repository
294
+ to authorize; app credentials can stay in `~/.codex/.env`. Each refresh reads
295
+ the latest token from the dedicated file and saves its replacement there.
296
+ `FEISHU_REFRESH_TOKEN` in `.env` or the environment is no longer used and
297
+ can be removed. Refresh is triggered by API calls, with no idle keepalive.
298
+ - `pycodex-ws --workspace-config workspaces.json` serves workspace boards from
299
+ one process. The JSON file can be either a list or
300
+ `{"workspaces": [...]}`; each entry uses `board` and `work_dir`, with optional
301
+ display/URL `id`, and is exposed at `/w/<id>/`. Internally the resolved
302
+ `board` path is the workspace identity, so adding the same board path twice is
303
+ rejected even with a different name. Relative `board` and `work_dir` paths
304
+ resolve from the config file directory. The root path `/` shows a workspaces
305
+ management page with `add_workspace(name=None, dir="./", board=None)` and
306
+ `delete(name)` controls; omitted names become `workspace-1`, `workspace-2`,
307
+ etc. If `board` is omitted when adding a workspace, pycodex assigns a random
308
+ writable `/tmp/pcws-*.html` board path. Add/delete actions and later
309
+ session-state saves refresh the JSON file. Board HTML can reference local
310
+ images beside the board (including nested paths) with relative URLs; only
311
+ `image/*` files contained by the board directory are served.
312
+ Assistant Markdown supports KaTeX formulas with `$...$`, `$$...$$`,
313
+ `\(...\)`, and `\[...\]` delimiters.
314
+ `--password <value>` enables a password-only login page for workspace pages,
315
+ APIs, and websocket connections. After login, the browser returns to the
316
+ requested workspace path with its query parameters.
317
+ Questions and permission requests appear below the conversation only while
318
+ waiting for input; they disappear when answered, cancelled, or timed out,
319
+ leaving the continuing assistant output at the bottom.
320
+ Queued enqueue/steer messages become user conversation blocks when their
321
+ turns start, in execution order. Small capsules to the left of the status
322
+ pill preview pending Steer (`↑`) and Queue (`◷`) text. Long text is truncated;
323
+ hover shows the full pending content. Each disappears when that type has
324
+ no waiting input.
325
+ - steer is enabled by default in interactive mode: normal input goes into the
326
+ runtime steer path, the current request stops at the next safe boundary, and
327
+ later steer text is appended to the next model request's `input` in order;
328
+ for explicit queueing, use `/queue <message>`, which prints
329
+ `[steer] queued: ...` and later `[steer] inserted: ...`
330
+ - the default local tool set includes the upstream-aligned subset plus the
331
+ pycodex `clock` extension: `shell`, `shell_command`, `exec_command`,
332
+ `write_stdin`, `clock`, `exec`, `wait`, `web_search`, `update_plan`,
333
+ `request_user_input`, `request_permissions`, `spawn_agent`, `send_input`,
334
+ `resume_agent`, `wait_agent`, `close_agent`, `apply_patch`, `grep_files`,
335
+ `read_file`, `list_dir`, `view_image`
336
+ - `clock(period_m)` sets one periodic clock for the current Agent session;
337
+ `null` cancels it. The countdown restarts after each reply and wakes the
338
+ Agent with a `<clock_tick>` message containing the current timezone-aware
339
+ time when it expires.
340
+ - while a background command or clock is pending, the idle status is
341
+ `idle: sleeping`
342
+ - only the active workspace tab shows its close button; closing it restores
343
+ the selected tab's conversation, draft, and scroll position immediately
344
+ after its snapshot loads
345
+ - `--vllm-endpoint http://host:port` automatically launches a local
346
+ `responses_server` compatibility layer; when the URL path is empty it is
347
+ normalized to `/v1`, and `/responses` requests are still forwarded to the
348
+ downstream `/v1/chat/completions` endpoint. This local compat path always
349
+ uses the canonical Responses request shape, even when the selected model's
350
+ metadata enables `responses_lite`. With `--vllm-endpoint`, startup also reads
351
+ `/v1/models` and uses the last returned model id for the downstream request.
352
+ For `model_provider = "vllm"`, reasoning is preserved across this path:
353
+ chat chunks with `reasoning` or `reasoning_content` are translated back into
354
+ Responses `reasoning` items, and
355
+ historical `reasoning` items are replayed into downstream assistant messages
356
+ via the `reasoning` field. Streaming token usage is also requested from vLLM
357
+ and forwarded to the final `response.completed.response.usage`. If a
358
+ downstream chat stream terminates after emitting only reasoning, with no
359
+ assistant content and no tool call, the compat layer discards that partial
360
+ reasoning, retries the same downstream request once, and only then emits
361
+ `response.failed` with `type = "model_output_invalid"` if the retry is still
362
+ reasoning-only
363
+ - malformed JSON in ordinary downstream function-call arguments is detected by
364
+ `responses_server` and returned as `response.failed` with `type = "server_error"`;
365
+ the client's existing `stream_max_retries` policy retries the current request
366
+ before its local tools execute
367
+ - downstream connection failures before HTTP response headers or during SSE
368
+ reading are converted to `response.failed` for provider retries. Downstream
369
+ requests honor environment proxies; see the
370
+ [connection troubleshooting notes](docs/responses_server/README.md#连接排查)
371
+ for `RemoteDisconnected` and proxy bypass configuration
372
+ - standalone `responses_server` now also supports downstream `/v1/messages`
373
+ backends via `--outcomming-api messages`, while keeping the internal
374
+ canonical request/route logic in chat-completions shape
375
+ - `pycodex doctor` checks config, `.env`, API keys, DNS, TCP/TLS, and an
376
+ optional live Responses API request
377
+
378
+ Current primary uses:
379
+
380
+ - verify provider / model / auth configuration
381
+ - debug `ResponsesModelClient`
382
+ - run minimal single-turn and multi-turn smoke tests
383
+
384
+ `doctor` examples:
385
+
386
+ ```bash
387
+ pycodex doctor
388
+ pycodex doctor --skip-live
389
+ pycodex doctor --json
390
+ ```
391
+
392
+ ## Portable Mode
393
+
394
+ `Portable Mode` is the quickest way to bring your usual `pycodex` setup into a
395
+ fresh machine, container, or debug image.
396
+
397
+ Use it like this:
398
+
399
+ ```bash
400
+ pycodex --put @127.0.0.1:5577
401
+ pycodex --put /data/.codex/@127.0.0.1:5577
402
+ ```
403
+
404
+ - `--put` prints a reusable `SECRET-CALLID@host:port` plus a final one-line
405
+ `pycodex --call ...` command
406
+ - on the new environment or image, run that printed `--call` command directly
407
+ - quickly restoring your usual `config.toml`, `.env`, `AGENTS.md`, and
408
+ `skills/` into a clean debug environment
409
+ - keeping a new image focused on the bug you are debugging instead of spending
410
+ time rebuilding local Codex setup by hand
411
+ - bootstrapping `pycodex` even when the target environment does not already
412
+ have a populated `~/.codex`
413
+ - bare `--put` uses the current user's `~/.codex`
414
+ - `--put /path/.codex/@host:port` lets you publish a different Codex home
415
+
416
+ ## Example
417
+
418
+ ```python
419
+ import asyncio
420
+ from pathlib import Path
421
+
422
+ from pycodex import (
423
+ Agent,
424
+ BaseTool,
425
+ ContextConfig,
426
+ ResponsesModelClient,
427
+ ToolRegistry,
428
+ )
429
+
430
+
431
+ class EchoTool(BaseTool):
432
+ name = "echo"
433
+ description = "Echo the provided text."
434
+ input_schema = {
435
+ "type": "object",
436
+ "properties": {"text": {"type": "string"}},
437
+ "required": ["text"],
438
+ }
439
+
440
+ async def run(self, context, args):
441
+ del context
442
+ return args["text"]
443
+
444
+
445
+ async def main() -> None:
446
+ config_path = Path.home() / ".codex" / "config.toml"
447
+ model = ResponsesModelClient.from_codex_config(config_path)
448
+ context_config = ContextConfig.from_codex_config(config_path)
449
+
450
+ tools = ToolRegistry()
451
+ tools.register(EchoTool())
452
+
453
+ agent = Agent(model, tools, context_config)
454
+ result = await agent.run_turn(
455
+ ["Call the echo tool with text=hello, then tell me what it returned."]
456
+ )
457
+ print(result.output_text)
458
+
459
+
460
+ asyncio.run(main())
461
+ ```
462
+
463
+ ### Turn lifecycle
464
+
465
+ `Agent` requires a model client, tool registry, and `ContextConfig`. It creates
466
+ its own `ContextManager`; cwd, instruction overrides and
467
+ extra contextual messages belong in that config. The client's model identifier
468
+ is authoritative for the Agent's context. Standalone context construction uses
469
+ `ContextManager(config)`; load files through `ContextConfig.from_codex_config`.
470
+
471
+ Collaboration modes and their prompt templates are removed. There is no mode
472
+ switch in `ContextConfig`, `ToolContext` or `build_agent`; normal interaction,
473
+ `update_plan`, structured user input and sub-agents remain independent features.
474
+
475
+ Dependencies are ordinary attributes: `model_client`, `tool_registry`,
476
+ `context_manager` and `event_handler`. The Agent has no Runtime/Queue reference;
477
+ `AgentRuntime` calls its public methods and subscribes to its events.
478
+ Pure getter/setter wrappers are removed. `history` remains a tuple snapshot,
479
+ and `model_name` and lifecycle properties remain derived values.
480
+
481
+ `session_file_path=None`, the default, means **keep history in memory without
482
+ recording**. Passing a file path creates an internal rollout recorder. Every
483
+ Agent still receives a stable UUIDv7 session id unless an explicit id is supplied.
484
+ CLI, Web and Feishu use `build_agent`, which assigns an id and a matching path
485
+ under the configured Codex home's `sessions/` directory. Sub-agents leave the path
486
+ as `None`, so their turns, compaction, forks and reopening stay in memory.
487
+
488
+ When a path is supplied, construction does not create the file or its parent
489
+ directories. The first history append or successful compaction creates it,
490
+ writing metadata and the current initial history before the new records.
491
+ An existing destination raises `FileExistsError`; exclusive creation also
492
+ prevents overwriting a file that appears before the first write.
493
+ `agent.session_id` and the read-only `agent.session_file_path` expose the identity
494
+ and optional recording path without exposing the recorder.
495
+
496
+ ```python
497
+ agent = Agent(model, tools, context_config) # In-memory session.
498
+ agent.resume("~/.codex/sessions/2026/09/22/rollout-example.jsonl")
499
+ ```
500
+
501
+ `resume(path)` reads an existing file, restores history and session identity, and
502
+ continues appending to that same file. Paths accept `~`; the existing
503
+ concatenated-JSON and compact-checkpoint loader is reused. Constructing an Agent
504
+ and immediately resuming another file leaves no unused rollout behind. Initial
505
+ history is recorded only when the new recorded session first writes. `history`
506
+ is read-only; there is no public `replace_history()` interface.
507
+
508
+ An `Agent` executes one turn or manual compaction at a time.
509
+ There are two public turn interfaces:
510
+
511
+ - `agent.ask(text)` blocks and returns the turn result.
512
+ - `await agent.run_turn(texts, turn_id=None)` executes the ordinary coroutine
513
+ and returns the turn result.
514
+
515
+ The Agent does not create, hold or return a per-turn Task. Creating a coroutine
516
+ does not start it or mark the Agent busy. A host that needs concurrent UI/input
517
+ handling can schedule the coroutine with `asyncio.create_task`; synchronous code
518
+ can use `ask` or `asyncio.run(agent.run_turn([...]))`. `start_turn` is removed.
519
+
520
+ `agent.is_running` reflects actual execution. One idle event backs both that
521
+ state and `await agent.wait_until_idle()`; `finally` releases it on exit.
522
+ Starting an overlapping operation raises `RuntimeError`; use `AgentRuntime`
523
+ for queued or steer submissions. `maybe_invoke` skips a busy or closed Agent;
524
+ when idle, it directly awaits the same `run_turn` path and propagates errors.
525
+ It returns `True` after that turn finishes, not immediately after scheduling.
526
+
527
+ `runtime.is_busy` includes active Agent work and pending submissions, including
528
+ direct/background turns that bypass the queue. CLI, web, and Feishu use this
529
+ state instead of tracking another busy flag. There is no Agent cancellation API:
530
+ `agent.cancel()`, `runtime.cancel_current()` and Task listeners are removed.
531
+
532
+ Steer asks `agent.stop_asap()` to end the current execution at a safe boundary.
533
+ The in-flight request and all issued tools finish first; the Agent records their
534
+ results, emits `turn_interrupted` and raises `TurnInterrupted`, without knowing
535
+ why the stop was requested. Runtime alone settles submission futures and starts
536
+ the next batch. Runtime-owned steer retains its logical turn id, but starts a new
537
+ `run_turn` execution with a fresh iteration count. `/queue` does not request a stop.
538
+ Checks after compaction prevent an extra sample when steer arrives during it.
539
+ Direct Agent calls never consume Runtime queues; their caller observes
540
+ `TurnInterrupted`, and pending input waits for the Runtime worker.
541
+
542
+ The core loop has one threshold-compaction entry, then samples, commits output
543
+ and executes tools or finishes. Before the first sample, compaction precedes new
544
+ user input; later it includes completed tool results. Context-overflow recovery
545
+ stays inside sampling: compact and retry once without counting another iteration
546
+ or replaying tools. Stops are checked before each request attempt and after the
547
+ issued tool batch, without a separate preparation wrapper. Network retries remain
548
+ inside the provider.
549
+
550
+ `await agent.compact()` computes a summary and commits the replacement history
551
+ only after the summary and rollout checkpoint succeed. Failed compaction leaves
552
+ the active history unchanged, including tool results pruned from retry prompts.
553
+ History persistence failures are surfaced rather than silently ignored.
554
+ Manual and automatic compaction share the same execution/observation path.
555
+
556
+ Sub-agent status comes from Agent lifecycle events and current busy/queue state,
557
+ including direct and background invocations. Bare `Agent.shutdown()` rejects new
558
+ calls and disables background hooks, but lets the current turn finish. `runtime.close()`,
559
+ `close_agent`, and workspace close wait for accepted work and child workers to
560
+ finish naturally; a stuck request can therefore keep close waiting.
561
+ `resume_agent` explicitly reopens the child. No turn-abort or synthetic
562
+ interruption-result recovery is performed.
563
+
564
+ Queue lifecycle uses only `start()` and `close()`. Closing switches off admission;
565
+ the worker exits when the queues are empty, without a special shutdown request.
566
+ Background invocations obey the same admission switch. Tool shutdown hooks run
567
+ once, after draining accepted work. Concurrent or repeated close calls share the
568
+ worker's completion and errors; cancelling a caller does not cancel its Agent turn.
569
+
570
+ CLI, web and Feishu restore through the backend's `runtime.resume(session_file_path)`,
571
+ which delegates to `agent.resume(session_file_path)`. It rejects
572
+ active or queued work, loads history, restores supported provider session
573
+ identity, switches its internal recorder, and clears stale usage in one
574
+ synchronous operation. Load failures leave the existing session unchanged.
575
+ The backend broadcasts restored history/title/identity to all attached views.
576
+ `agent.resume()` without a path reopens the same in-memory Agent and rebinds its
577
+ tool callbacks, without reading or writing a file or changing history, identity,
578
+ recorder or usage. It returns `None` and also rejects active or queued work.
579
+ Sub-agent services use this form to reopen the child's in-memory history.
580
+ There is no separate `reopen()` method.
581
+ Model switching and history replacement remain explicit operations because they
582
+ enforce state consistency, not merely assign a field.
583
+
584
+ ### Shared session backend
585
+
586
+ CLI, Web and Feishu all use `AgentRuntime.submit_input`: not just `/model`
587
+ and `/resume`, but every session command, steer/queue admission, interactive
588
+ questions and permissions, state notifications and shutdown. Frontends only
589
+ adapt input and render events. Web no longer imports or runs the CLI shell.
590
+ IPython is the deliberate exception: `ipython_agent()` still returns a bare Agent.
591
+
592
+ ```python
593
+ from pycodex.bootstrap import build_agent, build_model, build_runtime
594
+
595
+ async def run_session():
596
+ runtime = build_runtime(build_agent(build_model()))
597
+ await runtime.start()
598
+ observer = runtime.attach(lambda event: print(event.kind))
599
+ try:
600
+ receipt = await runtime.submit_input("/model", sender="application")
601
+ result = await receipt.future
602
+ return result
603
+ finally:
604
+ await runtime.close()
605
+ runtime.detach(observer)
606
+ ```
607
+
608
+ Attach immediately supplies a state snapshot; subsequent events synchronize
609
+ all views. Detach does not close the backend. Plain input steers at the next
610
+ sampling boundary, `/queue` waits for its own turn, and busy Feishu cards still
611
+ accept steer or question answers. Unknown slash commands report errors instead
612
+ of silently entering model history. See [runtime contracts](docs/RUNTIME.md)
613
+ for command receipts, structured answers and session ownership.
614
+
615
+ Python observers receive typed `Event` dataclasses from `pycodex.events`, such
616
+ as `TurnStartedEvent` and `ToolCompletedEvent`, not generic payload dictionaries.
617
+ Custom model clients emit `ModelEvent` variants such as `AssistantDeltaEvent`.
618
+ Events provide reusable plain text through `event.visualize()`, or render through
619
+ `event.render(display)`. Each CLI view and Feishu card owns an `EventDisplay` with
620
+ independent stream/queue state and log/status/prompt callbacks. Events own colors,
621
+ flushing, status transitions and prompt text; frontends execute I/O or update their
622
+ display fields. Feishu disables colors and shows a bounded recent transcript plus
623
+ the live stream, rather than a separate last-answer/last-turn projection.
624
+ There is no display-handler mapping. Web retains its own projection and unchanged
625
+ event JSON format.
626
+
627
+ ### Internal contracts
628
+
629
+ - Tools implement async `BaseTool.run`; synchronous implementations are not
630
+ implicitly accepted. Tool-specific follow-up messages come from
631
+ `BaseTool.follow_up_messages`, not tool-name checks in the Agent loop.
632
+ - Completed tool results are committed individually. Explicitly parallel tool
633
+ batches wait for all their operations before propagating a commit failure;
634
+ they do not cancel remaining operations or invent interruption results.
635
+ - Background tools bind their own callbacks through `BaseTool.bind_agent`.
636
+ The Agent does not reach into specific tools' private managers.
637
+ - Event observers report failures to the asyncio exception handler without
638
+ changing the execution result. Provider stream callbacks run on the owning
639
+ event loop and stop delivering when their request is finished or cancelled.
640
+ - `ModelClient.model` is a required read-only model identifier, also supplied by
641
+ test clients. `Agent.model_name` reads it directly, without `getattr` fallback.
642
+ `ModelClient.complete` returns a `ModelResponse` containing only supported
643
+ output item types. Context overflow is reported as `ContextLengthExceeded`;
644
+ provider-specific text classification stays inside the Responses client.
645
+ - A terminal `response.incomplete` is not a disconnected stream and is not
646
+ retried. For `max_output_tokens`, done assistant/reasoning items are retained
647
+ for the next turn, but uncommitted text deltas and unresolved tool calls are not.
648
+ - Interactive clients expose the `ModelControl` interface in `pycodex.model`.
649
+ Use `agent.set_model(name)` to update provider metadata, context instructions,
650
+ context limits, and usage state together.
651
+ - Runtime services belong to the tool registry. Pass an explicit environment to
652
+ `ToolRegistry(environment)` or `get_tools(environment)` when needed; the Agent
653
+ uses `agent.tool_registry.runtime_environment`, not a forwarding Agent property.
654
+ The global `get_agent_runtime_environment()` and
655
+ separate `Agent(..., runtime_environment=...)` entry points are removed.
656
+ - Each sub-agent gets its own context manager and runtime services. The sub-agent
657
+ service retains terminal event status, rather than inspecting Task results.
658
+ - Every Agent records its session, including direct and child Agents; external
659
+ callers no longer construct or inject `SessionRolloutRecorder`. The outer queue
660
+ remains optional and no worker starts implicitly. Empty initial history and a
661
+ no-op event callback remain valid defaults.
662
+
663
+ See `docs/RUNTIME.md` for state ownership and failure semantics.
664
+
665
+ ## Alignment Checklist
666
+
667
+ See `docs/ALIGNMENT.md` for more detail. This section keeps a high-level
668
+ checklist for quick status scanning.
669
+
670
+ ### Tool Alignment
671
+
672
+ Official upstream tools:
673
+
674
+ - [x] `shell` - run shell commands in argv form.
675
+ - [x] `shell_command` - run shell scripts in string form.
676
+ - [x] `exec_command` - start long-running commands with a session.
677
+ - [x] `write_stdin` - write stdin to an existing execution session or poll
678
+ output.
679
+ - [x] `web_search` - expose provider-native web search capability.
680
+ - [x] `update_plan` - update the task plan and maintain step status.
681
+ - [x] `request_user_input` - retain the declaration and return the upstream
682
+ Default-mode unavailable response.
683
+ - [x] `request_permissions` - request extra permissions before continuing.
684
+ - [x] `spawn_agent` - create and start a sub-agent.
685
+ - [x] `send_input` - continue feeding input to an existing sub-agent.
686
+ - [x] `resume_agent` - reopen a closed sub-agent.
687
+ - [x] `wait_agent` - wait for a sub-agent to reach a terminal state.
688
+ - [x] `close_agent` - close a sub-agent that is no longer needed.
689
+ - [x] `apply_patch` - edit files precisely with a freeform patch.
690
+ - [x] `grep_files` - search file contents by pattern.
691
+ - [x] `read_file` - read file slices while preserving line-number semantics.
692
+ - [x] `list_dir` - list directory tree slices.
693
+ - [x] `view_image` - turn a local image into model-visible input.
694
+
695
+ Upstream low-frequency / special-mode tools not yet modeled separately:
696
+
697
+ - [ ] `wait_infinite` - long blocking wait for external events or later input.
698
+ - [ ] `spawn_agents_on_csv` - create sub-agent jobs in bulk from CSV.
699
+ - [ ] `report_agent_job_result` - report batch agent job results.
700
+ - [ ] `js_repl` - JavaScript REPL / code-mode primary entry point.
701
+ - [ ] `js_repl_reset` - reset `js_repl` state.
702
+ - [ ] `artifacts` - generate or manage structured artifact outputs.
703
+ - [ ] `list_mcp_resources` - list MCP resources.
704
+ - [ ] `list_mcp_resource_templates` - list MCP resource templates.
705
+ - [ ] `read_mcp_resource` - read MCP resource contents.
706
+ - [ ] `multi_tool_use.parallel` - parallel wrapper around multiple developer
707
+ tool calls.
708
+
709
+ Repository-specific compatibility / transition tools:
710
+
711
+ - [x] `clock` - pycodex periodic Agent wake-up extension.
712
+ - [x] `exec` - current local approximation of code mode.
713
+ - [x] `wait` - current local approximation of code-mode waiting behavior.
714
+
715
+ ### Behavior Alignment
716
+
717
+ - [x] `AgentLoop` / `AgentRuntime` main loop skeleton - turn loop and submission
718
+ queue are in place.
719
+ - [x] non-interactive `exec` `instructions` alignment - base instructions match
720
+ upstream.
721
+ - [x] shared `exec` context content - the audited first/resume/tool-follow-up
722
+ scenarios match after documented exclusions; raw item identity is not equal.
723
+ - [x] developer/contextual-user message shape alignment - message/content shape
724
+ matches upstream.
725
+ - [x] `AGENTS.md` + `<environment_context>` injection alignment - context
726
+ assembly order matches upstream.
727
+ - [ ] complete 0.153.4 tool catalog alignment - local `clock`, legacy sub-agent
728
+ tools, and upstream goal/deferred/code-mode-v2 surfaces still differ.
729
+ - [x] `include = ["reasoning.encrypted_content"]` - reasoning include field is
730
+ aligned.
731
+ - [x] `prompt_cache_key` - request-level prompt cache key is implemented.
732
+ - [x] `x-client-request-id` - request id header is implemented.
733
+ - [x] `x-codex-turn-metadata` - turn id / sandbox header is implemented.
734
+ - [x] `originator` - mode-aware originator header is implemented.
735
+ - [ ] current identity/telemetry header parity - local identity remains
736
+ unchanged; the audit records upstream's newer headers and `client_metadata`.
737
+ - [x] field-by-field upstream exec-mode tool schema alignment - aligned tools
738
+ use class-level specs; `clock` is documented separately as an extension.
739
+ - [ ] full interactive-mode and non-`exec` behavior alignment - the non-exec
740
+ first-turn context is now on the `codex-tui` path, but continuous REPL
741
+ multi-turn behavior is not fully verified yet.
742
+ - [ ] sandbox / approvals / compact / memory and other outer behavior alignment
743
+ - these systems are still in later scope.