python-codex 0.2.4__tar.gz → 0.4.2__tar.gz

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