python-codex 0.5.1__tar.gz → 0.5.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 (91) hide show
  1. {python_codex-0.5.1 → python_codex-0.5.2}/PKG-INFO +30 -3
  2. {python_codex-0.5.1 → python_codex-0.5.2}/README.md +29 -2
  3. {python_codex-0.5.1 → python_codex-0.5.2}/README_ZH.md +13 -2
  4. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/events.py +15 -0
  5. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/runtime.py +128 -14
  6. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/base_tool.py +6 -0
  7. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/clock_tool.py +44 -2
  8. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/exec_command_tool.py +6 -0
  9. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/runtime_services.py +44 -0
  10. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/unified_exec_manager.py +27 -0
  11. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/session_persist.py +31 -0
  12. {python_codex-0.5.1 → python_codex-0.5.2}/pyproject.toml +2 -2
  13. {python_codex-0.5.1 → python_codex-0.5.2}/.gitignore +0 -0
  14. {python_codex-0.5.1 → python_codex-0.5.2}/LICENSE +0 -0
  15. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/__init__.py +0 -0
  16. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/__main__.py +0 -0
  17. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/agent.py +0 -0
  18. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/bootstrap.py +0 -0
  19. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/cli.py +0 -0
  20. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/context.py +0 -0
  21. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/model.py +0 -0
  22. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/portable/__init__.py +0 -0
  23. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/portable/client.py +0 -0
  24. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/portable/server.py +0 -0
  25. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/prompts/default_base_instructions.md +0 -0
  26. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/prompts/models.json +0 -0
  27. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/prompts/permissions/approval_policy/never.md +0 -0
  28. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/prompts/permissions/approval_policy/on_failure.md +0 -0
  29. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/prompts/permissions/approval_policy/on_request.md +0 -0
  30. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/prompts/permissions/approval_policy/on_request_rule_request_permission.md +0 -0
  31. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/prompts/permissions/approval_policy/unless_trusted.md +0 -0
  32. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/prompts/permissions/sandbox_mode/danger_full_access.md +0 -0
  33. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/prompts/permissions/sandbox_mode/read_only.md +0 -0
  34. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/prompts/permissions/sandbox_mode/workspace_write.md +0 -0
  35. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/protocol.py +0 -0
  36. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/__init__.py +0 -0
  37. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/agent_tool_schemas.py +0 -0
  38. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/apply_patch_tool.py +0 -0
  39. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/close_agent_tool.py +0 -0
  40. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/code_mode_manager.py +0 -0
  41. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/exec_runtime.js +0 -0
  42. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/exec_tool.py +0 -0
  43. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/grep_files_tool.py +0 -0
  44. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/list_dir_tool.py +0 -0
  45. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/read_file_tool.py +0 -0
  46. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/request_permissions_tool.py +0 -0
  47. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/request_user_input_tool.py +0 -0
  48. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/resume_agent_tool.py +0 -0
  49. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/send_input_tool.py +0 -0
  50. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/shell_command_tool.py +0 -0
  51. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/shell_tool.py +0 -0
  52. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/spawn_agent_tool.py +0 -0
  53. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/update_plan_tool.py +0 -0
  54. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/view_image_tool.py +0 -0
  55. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/wait_agent_tool.py +0 -0
  56. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/wait_tool.py +0 -0
  57. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/web_search_tool.py +0 -0
  58. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/tools/write_stdin_tool.py +0 -0
  59. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/__init__.py +0 -0
  60. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/_aes_gcm/LICENSE +0 -0
  61. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/_aes_gcm/README.md +0 -0
  62. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/_aes_gcm/__init__.py +0 -0
  63. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/_aes_gcm/aes.py +0 -0
  64. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/_aes_gcm/gcm.py +0 -0
  65. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/_aes_gcm/source-sha256.json +0 -0
  66. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/async_bridge.py +0 -0
  67. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/compactor.py +0 -0
  68. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/compat.py +0 -0
  69. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/crypto.py +0 -0
  70. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/debug.py +0 -0
  71. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/doctor.py +0 -0
  72. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/dotenv.py +0 -0
  73. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/event_helpers.py +0 -0
  74. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/get_env.py +0 -0
  75. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/image_utils.py +0 -0
  76. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/model_metadata.py +0 -0
  77. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/random_ids.py +0 -0
  78. {python_codex-0.5.1 → python_codex-0.5.2}/pycodex/utils/truncation.py +0 -0
  79. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/__init__.py +0 -0
  80. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/__main__.py +0 -0
  81. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/app.py +0 -0
  82. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/config.py +0 -0
  83. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/messages_api.py +0 -0
  84. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/payload_processors.py +0 -0
  85. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/server.py +0 -0
  86. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/session_store.py +0 -0
  87. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/stream_router.py +0 -0
  88. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/tools/__init__.py +0 -0
  89. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/tools/custom_adapter.py +0 -0
  90. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/tools/web_search.py +0 -0
  91. {python_codex-0.5.1 → python_codex-0.5.2}/responses_server/trajectory_dump.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-codex
3
- Version: 0.5.1
3
+ Version: 0.5.2
4
4
  Summary: A minimal Python extraction of Codex's main agent loop
5
5
  License-File: LICENSE
6
6
  Requires-Python: >=3.6.2
@@ -132,9 +132,34 @@ pycodex-ws --listen 127.0.0.1:6007 --workspace-config workspaces.json
132
132
  Open `http://127.0.0.1:6007`. The workspace combines conversations with a live
133
133
  HTML Canvas and read-only file/diff viewers. Click file links in replies to open
134
134
  them, and use **Insert into chat** to add selected code to an editable draft.
135
+ Local PDF links open in the browser's built-in reader, with **Open in new tab**
136
+ and **Download** links. PDF files are streamed separately from text snapshots.
135
137
  Keep the server's stdin open: EOF initiates shutdown.
136
- The gear button starts an Agent conversation for customizing the interface
137
- through files in `~/.pycodex/frontend/`.
138
+ **New session** directly creates a session using the launch `--profile`, or the
139
+ base config when unset. The **+** button on its right (**Custom profile**) lets
140
+ you choose a named profile from the server's Codex config; **Default** uses the
141
+ launch setting. Each session saves its profile name and uses it again on restart; existing sessions
142
+ keep their configuration. Restart the server after adding or removing profiles.
143
+ While the selected Agent is working, the empty composer cycles through usage
144
+ hints about commands, frontend customization, workspace sharing, session collaboration and optional
145
+ features about every six seconds, starting at a random hint. Edit the short
146
+ strings in the `hints` list in `workspace.html`'s `updatePromptPlaceholder` to change the tips.
147
+ The gear button opens **Customize Agent** and **Share**, with a short description of each.
148
+ Customize Agent starts an Agent conversation for editing files in
149
+ `~/.pycodex/frontend/`. Its setup context includes an API quick
150
+ reference and the path to the full API documentation shipped with the package.
151
+ Browse the [feature catalog](packages/pycodex-ws/workspace_server/optional_features/README.md)
152
+ in the view area and tell the Agent which features to adapt. You can also ask it
153
+ to publish a local customization as a GitHub feature PR using the
154
+ [contribution format](packages/pycodex-ws/workspace_server/optional_features/CONTRIBUTING.md).
155
+ The [custom frontend API](docs/WORKSPACE_API.md) provides structured state,
156
+ command results, history pagination, event replay and Agent/background-task
157
+ inventories. Optional `custom.js` extensions can export `mount(host)` to use
158
+ the built-in page's session, draft and viewer controls.
159
+ With a workspace server administrator password configured, **Share** sets a
160
+ separate password for this workspace using the existing login page. Sharing
161
+ passwords and visitor logins live only in memory; changing the password, stopping
162
+ sharing or restarting the process invalidates them. Router login is unchanged.
138
163
 
139
164
  See the [workspace guide](packages/pycodex-ws/README.md) for session controls,
140
165
  storage and Feishu setup. The separately distributed
@@ -190,10 +215,12 @@ uv run --dev pytest
190
215
  ```
191
216
 
192
217
  - [Test environments and coverage](tests/TESTS.md)
218
+ - [Repository development rules and reading guide](AGENTS.md)
193
219
  - [Architecture, package layout and runtime contracts](docs/RUNTIME.md)
194
220
  - [Prompts, configuration and context](docs/CONTEXT.md)
195
221
  - [Upstream alignment](docs/ALIGNMENT.md)
196
222
  - [Responses compatibility server](docs/responses_server/README.md)
223
+ - [Portable configuration contracts](docs/PORTABLE.md)
197
224
 
198
225
  Release notes and implementation details live in `docs/`.
199
226
 
@@ -112,9 +112,34 @@ pycodex-ws --listen 127.0.0.1:6007 --workspace-config workspaces.json
112
112
  Open `http://127.0.0.1:6007`. The workspace combines conversations with a live
113
113
  HTML Canvas and read-only file/diff viewers. Click file links in replies to open
114
114
  them, and use **Insert into chat** to add selected code to an editable draft.
115
+ Local PDF links open in the browser's built-in reader, with **Open in new tab**
116
+ and **Download** links. PDF files are streamed separately from text snapshots.
115
117
  Keep the server's stdin open: EOF initiates shutdown.
116
- The gear button starts an Agent conversation for customizing the interface
117
- through files in `~/.pycodex/frontend/`.
118
+ **New session** directly creates a session using the launch `--profile`, or the
119
+ base config when unset. The **+** button on its right (**Custom profile**) lets
120
+ you choose a named profile from the server's Codex config; **Default** uses the
121
+ launch setting. Each session saves its profile name and uses it again on restart; existing sessions
122
+ keep their configuration. Restart the server after adding or removing profiles.
123
+ While the selected Agent is working, the empty composer cycles through usage
124
+ hints about commands, frontend customization, workspace sharing, session collaboration and optional
125
+ features about every six seconds, starting at a random hint. Edit the short
126
+ strings in the `hints` list in `workspace.html`'s `updatePromptPlaceholder` to change the tips.
127
+ The gear button opens **Customize Agent** and **Share**, with a short description of each.
128
+ Customize Agent starts an Agent conversation for editing files in
129
+ `~/.pycodex/frontend/`. Its setup context includes an API quick
130
+ reference and the path to the full API documentation shipped with the package.
131
+ Browse the [feature catalog](packages/pycodex-ws/workspace_server/optional_features/README.md)
132
+ in the view area and tell the Agent which features to adapt. You can also ask it
133
+ to publish a local customization as a GitHub feature PR using the
134
+ [contribution format](packages/pycodex-ws/workspace_server/optional_features/CONTRIBUTING.md).
135
+ The [custom frontend API](docs/WORKSPACE_API.md) provides structured state,
136
+ command results, history pagination, event replay and Agent/background-task
137
+ inventories. Optional `custom.js` extensions can export `mount(host)` to use
138
+ the built-in page's session, draft and viewer controls.
139
+ With a workspace server administrator password configured, **Share** sets a
140
+ separate password for this workspace using the existing login page. Sharing
141
+ passwords and visitor logins live only in memory; changing the password, stopping
142
+ sharing or restarting the process invalidates them. Router login is unchanged.
118
143
 
119
144
  See the [workspace guide](packages/pycodex-ws/README.md) for session controls,
120
145
  storage and Feishu setup. The separately distributed
@@ -170,10 +195,12 @@ uv run --dev pytest
170
195
  ```
171
196
 
172
197
  - [Test environments and coverage](tests/TESTS.md)
198
+ - [Repository development rules and reading guide](AGENTS.md)
173
199
  - [Architecture, package layout and runtime contracts](docs/RUNTIME.md)
174
200
  - [Prompts, configuration and context](docs/CONTEXT.md)
175
201
  - [Upstream alignment](docs/ALIGNMENT.md)
176
202
  - [Responses compatibility server](docs/responses_server/README.md)
203
+ - [Portable configuration contracts](docs/PORTABLE.md)
177
204
 
178
205
  Release notes and implementation details live in `docs/`.
179
206
 
@@ -106,8 +106,17 @@ pycodex-ws --listen 127.0.0.1:6007 --workspace-config workspaces.json
106
106
 
107
107
  访问 `http://127.0.0.1:6007`。工作区同时提供对话、实时 HTML Canvas 和只读
108
108
  文件/diff 查看器。点击回复中的文件链接打开视图,通过 **Insert into chat**
109
- 把选中的代码插入可编辑草稿。运行期间保持服务器 stdin 打开,EOF 会触发关闭。
110
- 点击齿轮按钮可开启界面定制会话,让 Agent 修改 `~/.pycodex/frontend/` 中的文件。
109
+ 把选中的代码插入可编辑草稿。本地 PDF 链接使用浏览器内置阅读器预览,
110
+ 并提供新标签页打开和下载入口。运行期间保持服务器 stdin 打开,EOF 会触发关闭。
111
+ 点击 **New session** 直接按启动时的 `--profile` 创建会话,未指定时使用基础配置。
112
+ 右侧 **+** 按钮(Custom profile)可从服务器的 Codex 配置中选择 profile;
113
+ 选择框中的 **Default** 沿用启动配置。会话保存 profile 名称,
114
+ 重启后按同一名称恢复;已有会话的配置保持不变。增删 profile 后需重启服务器。
115
+ 当前 Agent 工作时,空输入框从随机位置开始,每约 6 秒顺序轮换一条简短提示,
116
+ 涵盖命令、界面定制、工作区分享、会话间协作和可选功能。可在 `workspace.html` 的 `updatePromptPlaceholder`
117
+ 中编辑 `hints` 字符串列表。已有草稿不受影响。
118
+ 点击齿轮按钮,在 **Customize Agent** 中开启界面定制会话,让 Agent 修改
119
+ `~/.pycodex/frontend/` 中的文件;**Share** 可通过链接和密码共享当前工作区。
111
120
 
112
121
  会话操作、存储和飞书配置见[工作区说明](packages/pycodex-ws/README.md)。
113
122
  独立分发的 [VS Code 扩展](packages/pycodex-ws/extensions/vscode/README.md)
@@ -160,9 +169,11 @@ uv run --dev pytest
160
169
  ```
161
170
 
162
171
  - [测试环境与覆盖范围](tests/TESTS.md)
172
+ - [仓库开发约定与阅读导航](AGENTS.md)
163
173
  - [架构、包布局与运行时契约](docs/RUNTIME.md)
164
174
  - [提示、配置与上下文](docs/CONTEXT.md)
165
175
  - [上游对齐](docs/ALIGNMENT.md)
166
176
  - [Responses 兼容服务](docs/responses_server/README.md)
177
+ - [Portable 配置契约](docs/PORTABLE.md)
167
178
 
168
179
  发布记录和实现细节放在 `docs/`。
@@ -751,6 +751,12 @@ class SessionStateEvent(Event):
751
751
  state["input_request"].render(display)
752
752
 
753
753
 
754
+ @dataclass(frozen=True)
755
+ class RuntimeUpdatedEvent(Event):
756
+ reason: "str"
757
+ kind: ClassVar[str] = "runtime_updated"
758
+
759
+
754
760
  @dataclass(frozen=True)
755
761
  class SessionClosedEvent(Event):
756
762
  kind: ClassVar[str] = "session_closed"
@@ -760,6 +766,14 @@ class SessionClosedEvent(Event):
760
766
  display.finish_stream()
761
767
 
762
768
 
769
+ @dataclass(frozen=True)
770
+ class CommandStartedEvent(Event):
771
+ submission_id: "str"
772
+ command: "str"
773
+ sender: "str" = "user"
774
+ kind: ClassVar[str] = "command_started"
775
+
776
+
763
777
  @dataclass(frozen=True)
764
778
  class CommandCompletedEvent(Event):
765
779
  submission_id: "str"
@@ -782,6 +796,7 @@ class CommandFailedEvent(Event):
782
796
  command: "str"
783
797
  error: "str"
784
798
  sender: "str"
799
+ error_type: "str" = "CommandError"
785
800
  kind: ClassVar[str] = "command_failed"
786
801
 
787
802
  def visualize(self) -> "str":
@@ -10,10 +10,12 @@ from .events import (
10
10
  AutoCompactCompletedEvent,
11
11
  CommandCompletedEvent,
12
12
  CommandFailedEvent,
13
+ CommandStartedEvent,
13
14
  Event,
14
15
  InputQueuedEvent,
15
16
  InputRequestedEvent,
16
17
  InputResolvedEvent,
18
+ RuntimeUpdatedEvent,
17
19
  SessionClosedEvent,
18
20
  SessionStateEvent,
19
21
  StreamErrorEvent,
@@ -86,6 +88,9 @@ class AgentRuntime:
86
88
  self.title = ""
87
89
  self.command_handlers = {}
88
90
  self._frontends = {}
91
+ self._interactive_frontends = set()
92
+ self._command_tasks = set()
93
+ self._active_commands = {}
89
94
  self._close_handlers = []
90
95
  self._worker = None
91
96
  self._command_lock = None
@@ -96,10 +101,18 @@ class AgentRuntime:
96
101
  environment = agent.tool_registry.runtime_environment
97
102
  environment.request_user_input_manager.set_handler(self._request_user_input)
98
103
  environment.request_permissions_manager.set_handler(self._request_permissions)
104
+ environment.plan_store.set_listener(lambda _plan: self._publish_update("plan"))
105
+ environment.subagent_manager.set_state_listener(
106
+ lambda: self._publish_update("agents")
107
+ )
108
+ for tool in self.agent.tool_registry.tools():
109
+ tool.set_state_listener(lambda: self._publish_update("background_work"))
99
110
 
100
- def attach(self, event_handler):
111
+ def attach(self, event_handler, interactive=True):
101
112
  frontend_id = uuid7_string()
102
113
  self._frontends[frontend_id] = event_handler
114
+ if interactive:
115
+ self._interactive_frontends.add(frontend_id)
103
116
  self._notify_handler(
104
117
  event_handler, SessionStateEvent("attach", self.snapshot())
105
118
  )
@@ -107,7 +120,8 @@ class AgentRuntime:
107
120
 
108
121
  def detach(self, frontend_id):
109
122
  del self._frontends[frontend_id]
110
- if not self._frontends and self._input_request is not None:
123
+ self._interactive_frontends.discard(frontend_id)
124
+ if not self._interactive_frontends and self._input_request is not None:
111
125
  self._finish_input_request(None)
112
126
 
113
127
  def register_command(self, name, handler):
@@ -170,6 +184,70 @@ class AgentRuntime:
170
184
  "plan": self.agent.tool_registry.runtime_environment.plan_store.snapshot(),
171
185
  }
172
186
 
187
+ def state_snapshot(self):
188
+ """Current frontend state, without completed conversation history."""
189
+ agent = self.agent
190
+ client = typing.cast(ModelControl, agent.model_client)
191
+ active = self._active_turn
192
+ return {
193
+ "agent_session_id": agent.session_id,
194
+ "title": self.title,
195
+ "cwd": str(agent.context_manager.cwd),
196
+ "model": {
197
+ "name": agent.model_name,
198
+ "reasoning_effort": client.reasoning_effort,
199
+ },
200
+ "busy": self.is_busy,
201
+ "running": agent.is_running,
202
+ "closed": agent.is_shutdown,
203
+ "accepts_input": self.accepts_input,
204
+ "active_turn": (
205
+ {
206
+ key: active[key]
207
+ for key in (
208
+ "turn_id", "submission_id", "user_texts", "assistant_text",
209
+ "model_errors",
210
+ )
211
+ } if active is not None else None
212
+ ),
213
+ "queued_inputs": [
214
+ {
215
+ "submission_id": item.submission_id,
216
+ "turn_id": item.turn_id,
217
+ "queue": name,
218
+ "prompts": list(item.texts),
219
+ }
220
+ for name, queue in (
221
+ ("steer", self._steer_queue), ("enqueue", self._enqueue_queue)
222
+ )
223
+ for item in queue
224
+ ],
225
+ "input_request": self._input_request_event(),
226
+ "plan": agent.tool_registry.runtime_environment.plan_store.snapshot(),
227
+ "commands": [dict(command) for command in self._active_commands.values()],
228
+ "background_work_count": sum(
229
+ tool.background_work_count(False)
230
+ for tool in agent.tool_registry.tools()
231
+ ),
232
+ "context_window": agent.context_manager.resolve_model_context_window(),
233
+ "max_context_window": agent.context_manager.resolve_model_max_context_window(),
234
+ "auto_compact_token_limit": agent.context_manager.resolve_auto_compact_token_limit(),
235
+ "usage_tokens": agent._last_total_usage_tokens,
236
+ }
237
+
238
+ def background_work_snapshot(self):
239
+ return [
240
+ dict(item, tool=tool.name)
241
+ for tool in self.agent.tool_registry.tools()
242
+ for item in tool.background_work_snapshot()
243
+ ]
244
+
245
+ async def list_models(self):
246
+ return await self.agent.model_client.list_models()
247
+
248
+ def _publish_update(self, reason):
249
+ self._publish(RuntimeUpdatedEvent(reason))
250
+
173
251
  def publish_state(self, reason):
174
252
  self._recorded_rollout_path = self.agent.recorded_session_file_path
175
253
  self._publish(SessionStateEvent(reason, self.snapshot()))
@@ -237,7 +315,7 @@ class AgentRuntime:
237
315
  self._wake_worker()
238
316
  await asyncio.shield(self._worker)
239
317
 
240
- async def submit_input(self, text, sender="user"):
318
+ async def submit_input(self, text, sender="user", wait_for_command=True):
241
319
  if not self.agent.accepts_input:
242
320
  raise RuntimeError("agent is shutting down")
243
321
  input_starts_with_space = text.startswith(" ")
@@ -270,19 +348,50 @@ class AgentRuntime:
270
348
  return await self._submit_message(argument.strip(), "enqueue", sender, True)
271
349
  submission_id = uuid7_string()
272
350
  future = asyncio.get_running_loop().create_future()
351
+ future.add_done_callback(self._observe_completion)
352
+ receipt = SubmittedInput(submission_id, "command", future)
353
+ self._active_commands[submission_id] = {
354
+ "submission_id": submission_id, "command": command,
355
+ "sender": sender, "status": "queued",
356
+ }
357
+ self._publish_update("commands")
358
+ operation = self._run_command(receipt, command, argument.strip(), sender)
359
+ if wait_for_command:
360
+ await operation
361
+ else:
362
+ task = asyncio.create_task(operation)
363
+ self._command_tasks.add(task)
364
+ task.add_done_callback(self._command_tasks.discard)
365
+ return receipt
366
+
367
+ async def _run_command(self, receipt, command, argument, sender):
273
368
  try:
274
369
  async with self._get_command_lock():
275
- if not self.agent.accepts_input:
276
- raise RuntimeError("agent is shutting down")
277
- result = await self._execute_command(command[1:], argument.strip())
370
+ self._active_commands[receipt.submission_id]["status"] = "running"
371
+ self._publish(
372
+ CommandStartedEvent(receipt.submission_id, command, sender)
373
+ )
374
+ result = await self._execute_command(command[1:], argument)
375
+ except asyncio.CancelledError:
376
+ del self._active_commands[receipt.submission_id]
377
+ receipt.future.cancel()
378
+ self._publish(CommandFailedEvent(
379
+ receipt.submission_id, command, "command caller cancelled",
380
+ sender, "CancelledError",
381
+ ))
382
+ raise
278
383
  except Exception as exc:
279
- future.set_exception(exc)
280
- self._publish(CommandFailedEvent(submission_id, command, str(exc), sender))
384
+ del self._active_commands[receipt.submission_id]
385
+ receipt.future.set_exception(exc)
386
+ self._publish(CommandFailedEvent(
387
+ receipt.submission_id, command, str(exc), sender, type(exc).__name__,
388
+ ))
281
389
  else:
282
- future.set_result(result)
283
- self._publish(CommandCompletedEvent(submission_id, command, result, sender))
284
- future.add_done_callback(self._observe_completion)
285
- return SubmittedInput(submission_id, "command", future)
390
+ del self._active_commands[receipt.submission_id]
391
+ receipt.future.set_result(result)
392
+ self._publish(
393
+ CommandCompletedEvent(receipt.submission_id, command, result, sender)
394
+ )
286
395
 
287
396
  async def _execute_command(self, command, argument):
288
397
  if command in {"help", "history", "compact", "fork"} and argument:
@@ -309,7 +418,7 @@ class AgentRuntime:
309
418
  return {
310
419
  "kind": "models",
311
420
  "model": self.agent.model_name,
312
- "models": await self.agent.model_client.list_models(),
421
+ "models": await self.list_models(),
313
422
  }
314
423
  if command == "effort":
315
424
  client = typing.cast(ModelControl, self.agent.model_client)
@@ -373,7 +482,7 @@ class AgentRuntime:
373
482
  return await self._request_input("permissions", payload)
374
483
 
375
484
  async def _request_input(self, kind, payload):
376
- if not self._frontends or not self.agent.accepts_input:
485
+ if not self._interactive_frontends or not self.agent.accepts_input:
377
486
  return None
378
487
  if self._input_request is not None:
379
488
  raise RuntimeError("a user input request is already pending")
@@ -506,6 +615,7 @@ class AgentRuntime:
506
615
  queued = self._steer_queue[-1]
507
616
  queued.texts.append(text)
508
617
  queued.futures.append(future)
618
+ self._publish_update("queue")
509
619
  return queued.submission_id, future
510
620
 
511
621
  submission_id = uuid7_string()
@@ -522,6 +632,7 @@ class AgentRuntime:
522
632
  )
523
633
  target = self._steer_queue if queue == "steer" else self._enqueue_queue
524
634
  target.append(queued)
635
+ self._publish_update("queue")
525
636
  asyncio.get_running_loop().call_soon(self._wake_worker)
526
637
  return submission_id, future
527
638
 
@@ -544,7 +655,10 @@ class AgentRuntime:
544
655
  self._finish_submission_result(queued, result)
545
656
  finally:
546
657
  self._current_submission = None
658
+ self._publish_update("idle")
547
659
  try:
660
+ if self._command_tasks:
661
+ await asyncio.gather(*tuple(self._command_tasks))
548
662
  async with self._get_command_lock():
549
663
  await self._close_resources()
550
664
  finally:
@@ -107,6 +107,12 @@ class BaseTool(ABC):
107
107
  def background_work_count(self, after_reply: "bool") -> "int":
108
108
  return 0
109
109
 
110
+ def background_work_snapshot(self) -> "typing.List[JSONDict]":
111
+ return []
112
+
113
+ def set_state_listener(self, listener) -> "None":
114
+ pass
115
+
110
116
 
111
117
  class ToolRegistry:
112
118
  def __init__(
@@ -8,7 +8,7 @@ cancels the pending countdown, and every successful reply starts a fresh one.
8
8
  import asyncio
9
9
  import math
10
10
  import typing
11
- from datetime import datetime
11
+ from datetime import datetime, timedelta
12
12
 
13
13
  from ..events import (
14
14
  CompactCompletedEvent,
@@ -50,6 +50,8 @@ class ClockManager:
50
50
  self._period_m: "typing.Union[float, None]" = None
51
51
  self._timer_task: "typing.Union[asyncio.Task, None]" = None
52
52
  self._generation = 0
53
+ self._next_fire_at = None
54
+ self._state_listener = None
53
55
  self._notify_hook: "typing.Union[typing.Callable[[typing.Dict[str, object]], typing.Awaitable[typing.Any]], None]" = (None)
54
56
 
55
57
  def set_notify_hook(
@@ -58,10 +60,29 @@ class ClockManager:
58
60
  ) -> "None":
59
61
  self._notify_hook = callback
60
62
 
63
+ def set_state_listener(self, listener):
64
+ self._state_listener = listener
65
+
66
+ def _state_changed(self):
67
+ if self._state_listener is not None:
68
+ self._state_listener()
69
+
70
+ def background_snapshot(self):
71
+ return dict(
72
+ self.snapshot(),
73
+ kind="clock",
74
+ next_fire_at=self._next_fire_at,
75
+ status=(
76
+ "armed" if self._next_fire_at is not None
77
+ else "paused" if self.enabled else "disabled"
78
+ ),
79
+ )
80
+
61
81
  def set_period(self, value: "object") -> "JSONDict":
62
82
  self._cancel_pending()
63
83
  if value is None:
64
84
  self._period_m = None
85
+ self._state_changed()
65
86
  return self.snapshot()
66
87
  if isinstance(value, bool) or not isinstance(value, (int, float)):
67
88
  raise ValueError("period_m must be a positive finite number or null")
@@ -69,6 +90,7 @@ class ClockManager:
69
90
  if not math.isfinite(period_m) or period_m <= 0:
70
91
  raise ValueError("period_m must be a positive finite number or null")
71
92
  self._period_m = period_m
93
+ self._state_changed()
72
94
  return self.snapshot()
73
95
 
74
96
  def snapshot(self) -> "JSONDict":
@@ -81,21 +103,32 @@ class ClockManager:
81
103
  def enabled(self) -> "bool":
82
104
  return self._period_m is not None
83
105
 
106
+ @property
107
+ def armed(self) -> "bool":
108
+ return self._next_fire_at is not None
109
+
84
110
  def turn_started(self) -> "None":
85
111
  self._cancel_pending()
112
+ self._state_changed()
86
113
 
87
114
  def arm_after_reply(self) -> "None":
88
115
  self._cancel_pending()
89
116
  period_m = self._period_m
90
117
  if period_m is None or self._notify_hook is None:
118
+ self._state_changed()
91
119
  return
92
120
  generation = self._generation
121
+ self._next_fire_at = (
122
+ datetime.now().astimezone()
123
+ + timedelta(seconds=period_m * self._seconds_per_minute)
124
+ ).isoformat()
93
125
  self._timer_task = asyncio.create_task(
94
126
  self._wait_and_notify(generation, period_m)
95
127
  )
96
128
  self._timer_task.add_done_callback(
97
129
  lambda task: None if task.cancelled() else task.exception()
98
130
  )
131
+ self._state_changed()
99
132
 
100
133
  def cancel(self) -> "None":
101
134
  self.set_period(None)
@@ -104,6 +137,7 @@ class ClockManager:
104
137
  self._generation += 1
105
138
  task = self._timer_task
106
139
  self._timer_task = None
140
+ self._next_fire_at = None
107
141
  if task is not None and not task.done():
108
142
  task.cancel()
109
143
 
@@ -118,6 +152,8 @@ class ClockManager:
118
152
  return
119
153
 
120
154
  self._timer_task = None
155
+ self._next_fire_at = None
156
+ self._state_changed()
121
157
  callback = self._notify_hook
122
158
  if callback is None:
123
159
  return
@@ -192,7 +228,13 @@ class ClockTool(BaseTool):
192
228
  self._manager.set_notify_hook(None)
193
229
 
194
230
  def background_work_count(self, after_reply: "bool") -> "int":
195
- return int(after_reply and self._manager.enabled)
231
+ return int(self._manager.enabled if after_reply else self._manager.armed)
232
+
233
+ def background_work_snapshot(self):
234
+ return [self._manager.background_snapshot()]
235
+
236
+ def set_state_listener(self, listener):
237
+ self._manager.set_state_listener(listener)
196
238
 
197
239
  async def run(self, context: "ToolContext", args: "JSONDict") -> "JSONValue":
198
240
  del context
@@ -86,6 +86,12 @@ class ExecCommandTool(BaseTool):
86
86
  def background_work_count(self, after_reply: "bool") -> "int":
87
87
  return self._manager.running_session_count()
88
88
 
89
+ def background_work_snapshot(self):
90
+ return self._manager.snapshot()
91
+
92
+ def set_state_listener(self, listener):
93
+ self._manager.set_state_listener(listener)
94
+
89
95
  async def run(self, context: "ToolContext", args: "JSONDict") -> "JSONValue":
90
96
  cmd = str(args.get("cmd", "")).strip()
91
97
  if not cmd:
@@ -10,6 +10,8 @@ from ..events import (
10
10
  CompactFailedEvent,
11
11
  CompactStartedEvent,
12
12
  Event,
13
+ RuntimeUpdatedEvent,
14
+ SessionClosedEvent,
13
15
  TurnCompletedEvent,
14
16
  TurnFailedEvent,
15
17
  TurnInterruptedEvent,
@@ -225,6 +227,40 @@ class SubAgentManager:
225
227
  self._condition = None
226
228
  self._available_nicknames: "typing.List[str]" = []
227
229
  self._nickname_random = random.Random()
230
+ self._state_listener = None
231
+
232
+ def set_state_listener(self, listener):
233
+ self._state_listener = listener
234
+
235
+ def _state_changed(self):
236
+ if self._state_listener is not None:
237
+ self._state_listener()
238
+
239
+ def list_agents(self, parent_agent_id):
240
+ agents = []
241
+ for managed in self._agents.values():
242
+ agents.append({
243
+ "agent_id": managed.agent_id,
244
+ "parent_agent_id": parent_agent_id,
245
+ "nickname": managed.nickname,
246
+ "status": self._status_payload(managed),
247
+ })
248
+ agents.extend(
249
+ managed.runtime.agent.tool_registry.runtime_environment
250
+ .subagent_manager.list_agents(managed.agent_id)
251
+ )
252
+ return agents
253
+
254
+ def get_runtime(self, agent_id):
255
+ if agent_id in self._agents:
256
+ return self._agents[agent_id].runtime
257
+ for managed in self._agents.values():
258
+ manager = managed.runtime.agent.tool_registry.runtime_environment.subagent_manager
259
+ try:
260
+ return manager.get_runtime(agent_id)
261
+ except KeyError:
262
+ continue
263
+ raise KeyError(agent_id)
228
264
 
229
265
  def _get_condition(self):
230
266
  if self._condition is None:
@@ -271,6 +307,7 @@ class SubAgentManager:
271
307
  async with self._get_condition():
272
308
  self._agents[agent_id] = managed
273
309
  self._condition.notify_all()
310
+ self._state_changed()
274
311
 
275
312
  initial_prompt = self._compose_prompt(message, items)
276
313
  if initial_prompt:
@@ -300,6 +337,7 @@ class SubAgentManager:
300
337
  future.add_done_callback(self._submission_finished)
301
338
  async with self._get_condition():
302
339
  self._condition.notify_all()
340
+ self._state_changed()
303
341
  return {"submission_id": submission_id}
304
342
 
305
343
  async def resume_agent(self, agent_id: "str") -> "typing.Dict[str, object]":
@@ -312,6 +350,7 @@ class SubAgentManager:
312
350
  await managed.runtime.start()
313
351
  async with self._get_condition():
314
352
  self._condition.notify_all()
353
+ self._state_changed()
315
354
  return {"status": self._status_payload(managed)}
316
355
 
317
356
  async def close_agent(self, agent_id: "str") -> "typing.Dict[str, object]":
@@ -322,6 +361,7 @@ class SubAgentManager:
322
361
  await managed.runtime.close()
323
362
  async with self._get_condition():
324
363
  self._condition.notify_all()
364
+ self._state_changed()
325
365
  return {"previous_status": previous_status}
326
366
 
327
367
  async def shutdown(self) -> "None":
@@ -389,6 +429,9 @@ class SubAgentManager:
389
429
  asyncio.create_task(self._notify_waiters())
390
430
 
391
431
  def _handle_agent_event(self, managed: "ManagedAgent", event: "Event") -> "None":
432
+ if isinstance(event, (RuntimeUpdatedEvent, SessionClosedEvent)):
433
+ self._state_changed()
434
+ return
392
435
  if isinstance(event, TurnCompletedEvent):
393
436
  managed.last_status = {"completed": event.output_text}
394
437
  elif isinstance(event, CompactCompletedEvent):
@@ -426,6 +469,7 @@ class SubAgentManager:
426
469
  asyncio.create_task(self._notify_waiters())
427
470
 
428
471
  async def _notify_waiters(self) -> "None":
472
+ self._state_changed()
429
473
  async with self._get_condition():
430
474
  self._condition.notify_all()
431
475
 
@@ -125,6 +125,7 @@ class UnifiedExecManager:
125
125
  self._next_session_id = DEFAULT_SESSION_ID_START
126
126
  self._sessions: "typing.Dict[int, UnifiedExecSession]" = {}
127
127
  self._lock = threading.Lock()
128
+ self._state_listener = None
128
129
  self._notify_hook: "typing.Union[typing.Callable[[typing.Dict[str, object]], typing.Awaitable[typing.Any]], None]" = (None)
129
130
 
130
131
  def set_notify_hook(
@@ -140,6 +141,29 @@ class UnifiedExecManager:
140
141
  if session.process.returncode is None
141
142
  )
142
143
 
144
+ def set_state_listener(self, listener):
145
+ self._state_listener = listener
146
+
147
+ def _state_changed(self):
148
+ if self._state_listener is not None:
149
+ self._state_listener()
150
+
151
+ def snapshot(self):
152
+ with self._lock:
153
+ return [
154
+ {
155
+ "kind": "exec",
156
+ "session_id": session.session_id,
157
+ "pid": session.process.pid,
158
+ "tty": session.tty,
159
+ "status": (
160
+ "running" if session.process.returncode is None else "exited"
161
+ ),
162
+ "exit_code": session.process.returncode,
163
+ }
164
+ for session in self._sessions.values()
165
+ ]
166
+
143
167
  async def exec_command(
144
168
  self,
145
169
  cmd: "str",
@@ -180,6 +204,7 @@ class UnifiedExecManager:
180
204
 
181
205
  with self._lock:
182
206
  self._sessions[session_id] = session
207
+ self._state_changed()
183
208
 
184
209
  output = await self._wait_and_snapshot(
185
210
  session_id,
@@ -299,6 +324,7 @@ class UnifiedExecManager:
299
324
  session = self._sessions.pop(session_id, None)
300
325
  if session is None:
301
326
  return
327
+ self._state_changed()
302
328
  if session.process.stdin is not None and not stream_writer_is_closing(
303
329
  session.process.stdin
304
330
  ):
@@ -349,6 +375,7 @@ class UnifiedExecManager:
349
375
  if session is None:
350
376
  return
351
377
  await session.process.wait()
378
+ self._state_changed()
352
379
  with self._lock:
353
380
  if self._sessions.get(session_id) is not session:
354
381
  return
@@ -332,6 +332,37 @@ def conversation_history_to_turns(
332
332
  return tuple(turns)
333
333
 
334
334
 
335
+ def read_rollout_history_page(rollout_path, before=None, limit=100):
336
+ """Read a bounded page of conversation records in chronological order."""
337
+ if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 200:
338
+ raise ValueError("limit must be between 1 and 200")
339
+ if before is not None and (
340
+ isinstance(before, bool) or not isinstance(before, int) or before < 0
341
+ ):
342
+ raise ValueError("before must be a non-negative record index")
343
+ entries = deque(maxlen=limit + 1)
344
+ index = 0
345
+ for entry in _iter_rollout_entries(Path(rollout_path)):
346
+ kind = entry.get("type")
347
+ if kind not in {"response_item", "compacted"}:
348
+ continue
349
+ if before is not None and index >= before:
350
+ break
351
+ payload = entry["payload"]
352
+ if kind == "compacted":
353
+ payload = {"message": payload.get("message", "")}
354
+ entries.append({"index": index, "type": kind, "payload": payload})
355
+ index += 1
356
+ if before is not None and before > index:
357
+ raise ValueError("history cursor is beyond the current history")
358
+ more = len(entries) > limit
359
+ items = list(entries)[-limit:]
360
+ return {
361
+ "items": items,
362
+ "next_before": items[0]["index"] if more else None,
363
+ }
364
+
365
+
335
366
  def load_display_history(
336
367
  rollout_path: "typing.Union[str, Path]",
337
368
  limit: "int" = 80,
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "python-codex"
7
- version = "0.5.1"
7
+ version = "0.5.2"
8
8
  description = "A minimal Python extraction of Codex's main agent loop"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.6.2"
@@ -40,7 +40,7 @@ test = [
40
40
  ]
41
41
  dev = [
42
42
  { include-group = "test" },
43
- "pycodex-ws==0.5.1",
43
+ "pycodex-ws==0.5.2",
44
44
  "black>=22.8.0",
45
45
  "debugpy>=1.8.20; python_version >= '3.8'",
46
46
  "isort>=5.10.1",
File without changes
File without changes