codexed 0.1.2__tar.gz → 0.1.4__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 (38) hide show
  1. {codexed-0.1.2 → codexed-0.1.4}/PKG-INFO +3 -1
  2. {codexed-0.1.2 → codexed-0.1.4}/pyproject.toml +5 -1
  3. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/__init__.py +8 -6
  4. codexed-0.1.4/src/codexed/client/__init__.py +7 -0
  5. {codexed-0.1.2/src/codexed → codexed-0.1.4/src/codexed/client}/client.py +56 -224
  6. codexed-0.1.4/src/codexed/client/fs.py +158 -0
  7. {codexed-0.1.2/src/codexed → codexed-0.1.4/src/codexed/client}/session.py +4 -0
  8. codexed-0.1.4/src/codexed/helpers.py +46 -0
  9. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/__init__.py +18 -0
  10. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/codex_types.py +3 -0
  11. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/event_data.py +12 -5
  12. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/events.py +15 -5
  13. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/misc.py +5 -4
  14. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/request_params.py +71 -38
  15. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/responses.py +18 -3
  16. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/thread_item.py +7 -5
  17. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/thread_status.py +1 -1
  18. codexed-0.1.4/src/codexed/transport.py +193 -0
  19. codexed-0.1.2/src/codexed/helpers.py +0 -7
  20. {codexed-0.1.2 → codexed-0.1.4}/LICENSE +0 -0
  21. {codexed-0.1.2 → codexed-0.1.4}/README.md +0 -0
  22. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/README.md +0 -0
  23. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/exceptions.py +0 -0
  24. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/log.py +0 -0
  25. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/base.py +0 -0
  26. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/command_action.py +0 -0
  27. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/fuzzy_search.py +0 -0
  28. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/hooks.py +0 -0
  29. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/mcp_server.py +0 -0
  30. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/realtime.py +0 -0
  31. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/response_item.py +0 -0
  32. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/terminal.py +0 -0
  33. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/token_usage.py +0 -0
  34. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/tool_config.py +0 -0
  35. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/user_input.py +0 -0
  36. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/models/web_search.py +0 -0
  37. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/py.typed +0 -0
  38. {codexed-0.1.2 → codexed-0.1.4}/src/codexed/request_handlers.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codexed
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: Alternative codex app-server client
5
5
  Keywords:
6
6
  Author: Philipp Temminghoff
@@ -24,12 +24,14 @@ Classifier: Typing :: Typed
24
24
  Requires-Dist: anyenv>=2.0.15
25
25
  Requires-Dist: pydantic
26
26
  Requires-Dist: schemez
27
+ Requires-Dist: websockets>=13.0 ; extra == 'websocket'
27
28
  Requires-Python: >=3.13
28
29
  Project-URL: Code coverage, https://app.codecov.io/gh/phil65/codexed
29
30
  Project-URL: Discussions, https://github.com/phil65/codexed/discussions
30
31
  Project-URL: Documentation, https://phil65.github.io/codexed/
31
32
  Project-URL: Issues, https://github.com/phil65/codexed/issues
32
33
  Project-URL: Source, https://github.com/phil65/codexed
34
+ Provides-Extra: websocket
33
35
  Description-Content-Type: text/markdown
34
36
 
35
37
  # Codexed
@@ -2,7 +2,7 @@
2
2
 
3
3
  [project]
4
4
  name = "codexed"
5
- version = "0.1.2"
5
+ version = "0.1.4"
6
6
  description = "Alternative codex app-server client"
7
7
  readme = "README.md"
8
8
  requires-python = ">=3.13"
@@ -42,6 +42,9 @@ Documentation = "https://phil65.github.io/codexed/"
42
42
  Issues = "https://github.com/phil65/codexed/issues"
43
43
  Source = "https://github.com/phil65/codexed"
44
44
 
45
+ [project.optional-dependencies]
46
+ websocket = ["websockets>=13.0"]
47
+
45
48
  [dependency-groups]
46
49
  dev = [
47
50
  "devtools",
@@ -239,6 +242,7 @@ runtime-evaluated-base-classes = [
239
242
  "sqlalchemy.orm.DeclarativeBase",
240
243
  "schemez.Schema",
241
244
  "sqlmodel.SQLModel",
245
+ "codexed.models.base.CodexBaseModel"
242
246
  ]
243
247
  runtime-evaluated-decorators = [
244
248
  "pydantic.validate_call",
@@ -16,13 +16,8 @@ __copyright__ = "Copyright (c) 2026 Philipp Temminghoff"
16
16
  __license__ = "MIT"
17
17
  __url__ = "https://github.com/phil65/codexed"
18
18
 
19
- __all__ = [
20
- "__version__",
21
- ]
22
-
23
19
 
24
- from codexed.client import CodexClient
25
- from codexed.session import Session
20
+ from codexed.client import CodexClient, Session
26
21
  from codexed.exceptions import (
27
22
  CodexError,
28
23
  CodexProcessError,
@@ -86,6 +81,7 @@ from codexed.models.codex_types import (
86
81
  CollabAgentTool,
87
82
  CollaborationMode,
88
83
  CollaborationModeSettings,
84
+ CommandExecutionSource,
89
85
  CommandExecutionStatus,
90
86
  DangerFullAccessSandboxPolicy,
91
87
  ExternalSandboxPolicy,
@@ -127,6 +123,7 @@ from codexed.models.events import (
127
123
  ConfigWarningEvent,
128
124
  EventType,
129
125
  FileChangeOutputDeltaEvent,
126
+ FsChangedEvent,
130
127
  ItemCompletedEvent,
131
128
  ItemStartedEvent,
132
129
  ModelReroutedEvent,
@@ -144,6 +141,7 @@ from codexed.models.events import (
144
141
  TurnStartedEvent,
145
142
  )
146
143
  from codexed.models.mcp_server import HttpMcpServer, McpServerConfig, StdioMcpServer
144
+ from codexed.transport import StdioTransport, WebSocketTransport
147
145
  from codexed.models.tool_config import BuiltinToolsConfig, ToolConfig, tools_to_config_dict
148
146
  from codexed.request_handlers import (
149
147
  ApprovalHandler,
@@ -180,6 +178,7 @@ __all__ = [
180
178
  "CommandExecResponse",
181
179
  "CommandExecutionOutputDeltaData",
182
180
  "CommandExecutionOutputDeltaEvent",
181
+ "CommandExecutionSource",
183
182
  "CommandExecutionStatus",
184
183
  "ConfigWarningData",
185
184
  "ConfigWarningEvent",
@@ -190,6 +189,7 @@ __all__ = [
190
189
  "ExperimentalFeature",
191
190
  "ExternalSandboxPolicy",
192
191
  "FileChangeOutputDeltaEvent",
192
+ "FsChangedEvent",
193
193
  "HttpMcpServer",
194
194
  "InputModality",
195
195
  "InternalRpcError",
@@ -235,6 +235,7 @@ __all__ = [
235
235
  "SkillData",
236
236
  "SkillScope",
237
237
  "StdioMcpServer",
238
+ "StdioTransport",
238
239
  "Thread",
239
240
  "ThreadActiveFlag",
240
241
  "ThreadArchivedData",
@@ -278,6 +279,7 @@ __all__ = [
278
279
  "UserInputMention",
279
280
  "UserInputSkill",
280
281
  "UserInputText",
282
+ "WebSocketTransport",
281
283
  "WorkspaceWriteSandboxPolicy",
282
284
  "is_retryable_error",
283
285
  "map_jsonrpc_error",
@@ -0,0 +1,7 @@
1
+ """Codex client."""
2
+
3
+ from .client import CodexClient
4
+ from .fs import CodexFS
5
+ from .session import Session
6
+
7
+ __all__ = ["CodexClient", "CodexFS", "Session"]
@@ -5,14 +5,12 @@ from __future__ import annotations
5
5
  import asyncio
6
6
  from collections.abc import AsyncIterator, Mapping # noqa: TC003
7
7
  import contextlib
8
- import json
9
8
  import logging
10
- import os
11
9
  from typing import TYPE_CHECKING, Any, assert_never
12
10
 
13
- import anyenv
14
11
  from pydantic import BaseModel, TypeAdapter
15
12
 
13
+ from codexed.client.fs import CodexFS
16
14
  from codexed.exceptions import (
17
15
  CodexProcessError,
18
16
  CodexRequestError,
@@ -20,7 +18,7 @@ from codexed.exceptions import (
20
18
  TurnFailedError,
21
19
  map_jsonrpc_error,
22
20
  )
23
- from codexed.helpers import kebab_to_camel
21
+ from codexed.helpers import kebab_to_camel, merge_config
24
22
  from codexed.models import (
25
23
  AppsListParams,
26
24
  AppsListResponse,
@@ -42,16 +40,6 @@ from codexed.models import (
42
40
  ExternalAgentConfigImportParams,
43
41
  FeedbackUploadParams,
44
42
  FeedbackUploadResponse,
45
- FsCopyParams,
46
- FsCreateDirectoryParams,
47
- FsGetMetadataParams,
48
- FsGetMetadataResponse,
49
- FsReadDirectoryParams,
50
- FsReadDirectoryResponse,
51
- FsReadFileParams,
52
- FsReadFileResponse,
53
- FsRemoveParams,
54
- FsWriteFileParams,
55
43
  GetAccountParams,
56
44
  GetAccountRateLimitsResponse,
57
45
  GetAccountResponse,
@@ -88,6 +76,7 @@ from codexed.models import (
88
76
  ThreadRollbackParams,
89
77
  ThreadRollbackResponse,
90
78
  ThreadSetNameParams,
79
+ ThreadShellCommandParams,
91
80
  ThreadStartParams,
92
81
  ThreadUnarchiveParams,
93
82
  ThreadUnarchiveResponse,
@@ -105,7 +94,6 @@ from codexed.models import (
105
94
  UserInputText,
106
95
  codex_event_adapter,
107
96
  )
108
- from codexed.models.tool_config import tools_to_config_dict
109
97
  from codexed.request_handlers import (
110
98
  SERVER_REQUEST_COMMAND_APPROVAL,
111
99
  SERVER_REQUEST_DYNAMIC_TOOL_CALL,
@@ -116,11 +104,13 @@ from codexed.request_handlers import (
116
104
  SERVER_REQUEST_USER_INPUT,
117
105
  create_auto_approve_dict,
118
106
  )
107
+ from codexed.transport import StdioTransport
119
108
 
120
109
 
121
110
  if TYPE_CHECKING:
122
111
  from typing import Self
123
112
 
113
+ from codexed.client.session import Session
124
114
  from codexed.models import (
125
115
  AppInfo,
126
116
  ApprovalPolicy,
@@ -130,7 +120,6 @@ if TYPE_CHECKING:
130
120
  ConfigEdit,
131
121
  ExperimentalFeature,
132
122
  ExternalAgentConfigMigrationItem,
133
- FsReadDirectoryEntry,
134
123
  McpServerConfig,
135
124
  MergeStrategy,
136
125
  ModelData,
@@ -157,7 +146,7 @@ if TYPE_CHECKING:
157
146
  ServerRequestHandler,
158
147
  UserInputHandler,
159
148
  )
160
- from codexed.session import Session
149
+ from codexed.transport import Transport
161
150
 
162
151
  logger = logging.getLogger(__name__)
163
152
 
@@ -182,6 +171,7 @@ class CodexClient:
182
171
  on_dynamic_tool_call: DynamicToolCallHandler | None = None,
183
172
  on_mcp_elicitation: McpElicitationHandler | None = None,
184
173
  mcp_elicitation_for_approvals: bool = False,
174
+ transport: Transport | None = None,
185
175
  ) -> None:
186
176
  """Initialize the Codex app-server client.
187
177
 
@@ -203,22 +193,31 @@ class CodexClient:
203
193
  to handle approvals (the schema is empty; context is in ``_meta``).
204
194
  Default is False because the default elicitation handler auto-declines,
205
195
  which would break MCP tool approvals.
196
+ transport: Pre-configured transport instance. If provided,
197
+ ``codex_command``, ``profile``, ``env_vars``, and ``mcp_servers``
198
+ are ignored (they are only used to build the default
199
+ ``StdioTransport``). Pass a ``WebSocketTransport`` here to
200
+ connect to a remote app-server.
206
201
  """
207
- self._codex_command = codex_command
208
- self._profile = profile
209
- self._mcp_servers = dict(mcp_servers) if mcp_servers else {}
210
- self._process: asyncio.subprocess.Process | None = None
202
+ if transport is not None:
203
+ self._transport = transport
204
+ else:
205
+ self._transport = StdioTransport(
206
+ command=codex_command,
207
+ profile=profile,
208
+ env_vars=env_vars,
209
+ mcp_servers=mcp_servers,
210
+ )
211
211
  self._request_id = 0
212
- self._env_vars = env_vars or {}
213
212
  self._pending_requests: dict[int, asyncio.Future[Any]] = {}
214
213
  self._event_queue: asyncio.Queue[CodexEvent | None] = asyncio.Queue()
215
214
  self._turn_queues: dict[str, asyncio.Queue[CodexEvent | None]] = {}
216
215
  self._reader_task: asyncio.Task[None] | None = None
217
- self._writer_lock = asyncio.Lock()
218
216
  self._active_threads: set[str] = set()
219
217
  self._mcp_elicitation_enabled = on_mcp_elicitation is not None
220
218
  self._mcp_elicitation_for_approvals = mcp_elicitation_for_approvals
221
219
  self._server_request_handlers: dict[str, ServerRequestHandler] = {}
220
+ self.fs = CodexFS(self)
222
221
  if on_approval:
223
222
  self.register_handler(SERVER_REQUEST_COMMAND_APPROVAL, on_approval) # type: ignore[arg-type]
224
223
  self.register_handler(SERVER_REQUEST_FILE_CHANGE_APPROVAL, on_approval) # type: ignore[arg-type]
@@ -240,47 +239,27 @@ class CodexClient:
240
239
  await self.stop()
241
240
 
242
241
  async def start(self) -> None:
243
- """Start the Codex app-server subprocess and initialize connection.
242
+ """Start the transport and initialize the JSON-RPC connection.
244
243
 
245
244
  Raises:
246
- CodexProcessError: If failed to start the process
245
+ CodexProcessError: If failed to start the transport
247
246
  """
248
247
  import codexed
249
248
 
250
- if self._process is not None:
249
+ if self._transport.is_connected:
251
250
  return
252
251
 
253
- cmd = [self._codex_command, "app-server"]
254
- if self._profile:
255
- cmd.extend(["--profile", self._profile])
256
- # Add MCP server configurations via --config flags
257
- for server_name, server_config in self._mcp_servers.items():
258
- config_str = server_config.to_config_toml(server_name)
259
- cmd.extend(["--config", config_str])
260
-
261
- logger.info("Starting Codex app-server: %s", " ".join(cmd))
262
- try:
263
- self._process = await anyenv.create_process(
264
- *cmd,
265
- stdin="pipe",
266
- stdout="pipe",
267
- stderr="pipe",
268
- env={**os.environ, **self._env_vars},
269
- )
270
- except FileNotFoundError as exc:
271
- raise CodexProcessError(f"Codex binary not found: {self._codex_command}") from exc
272
- except Exception as exc:
273
- raise CodexProcessError(f"Failed to start Codex app-server: {exc}") from exc
252
+ await self._transport.start()
274
253
  # Start reader task
275
254
  self._reader_task = asyncio.create_task(self._read_loop())
276
255
  # Initialize connection
277
256
  version = codexed.__version__
278
- init_params = InitializeParams.create(name="agentpool-codex-adapter", version=version)
257
+ init_params = InitializeParams.create(name="codexed", version=version)
279
258
  await self._send_request("initialize", init_params)
280
259
 
281
260
  async def stop(self) -> None:
282
- """Stop the Codex app-server subprocess."""
283
- if self._process is None:
261
+ """Stop the transport and clean up resources."""
262
+ if not self._transport.is_connected:
284
263
  return
285
264
 
286
265
  # Cancel reader task
@@ -289,16 +268,7 @@ class CodexClient:
289
268
  with contextlib.suppress(asyncio.CancelledError):
290
269
  await self._reader_task
291
270
 
292
- # Terminate process
293
- if self._process.returncode is None:
294
- self._process.terminate()
295
- try:
296
- await asyncio.wait_for(self._process.wait(), timeout=5.0)
297
- except TimeoutError:
298
- self._process.kill()
299
- await self._process.wait()
300
-
301
- self._process = None
271
+ await self._transport.stop()
302
272
  # Reject pending requests
303
273
  for future in self._pending_requests.values():
304
274
  if not future.done():
@@ -309,35 +279,6 @@ class CodexClient:
309
279
  # Thread lifecycle methods
310
280
  # ========================================================================
311
281
 
312
- @staticmethod
313
- def _merge_config(
314
- config: dict[str, Any] | None,
315
- tools: list[ToolConfig] | None,
316
- code_mode: bool | None,
317
- mcp_servers: Mapping[str, McpServerConfig] | None = None,
318
- mcp_elicitation_for_approvals: bool = False,
319
- ) -> dict[str, Any] | None:
320
- """Merge tools, code_mode, and mcp_servers into a config dict."""
321
- merged = dict(config) if config else {}
322
- if code_mode is not None:
323
- merged.setdefault("features", {})["code_mode"] = code_mode
324
- merged.setdefault("features", {})["codex_hooks"] = True
325
- merged.setdefault("features", {})["realtime_conversation"] = True
326
- if mcp_elicitation_for_approvals:
327
- merged.setdefault("features", {})["tool_call_mcp_elicitation"] = True
328
- if tools is not None:
329
- tool_config = tools_to_config_dict(tools)
330
- for key, value in tool_config.items():
331
- if key not in merged:
332
- merged[key] = value
333
- elif isinstance(value, dict) and isinstance(merged[key], dict):
334
- merged[key] = {**value, **merged[key]}
335
- if mcp_servers:
336
- servers = merged.setdefault("mcp_servers", {})
337
- for name, srv in mcp_servers.items():
338
- servers.setdefault(name, srv.model_dump(exclude_none=True))
339
- return merged or None
340
-
341
282
  async def thread_start(
342
283
  self,
343
284
  *,
@@ -380,7 +321,7 @@ class CodexClient:
380
321
  Returns:
381
322
  Session wrapping the new thread
382
323
  """
383
- from codexed.session import Session
324
+ from codexed.client.session import Session
384
325
 
385
326
  params = ThreadStartParams(
386
327
  cwd=cwd,
@@ -390,7 +331,7 @@ class CodexClient:
390
331
  developer_instructions=developer_instructions,
391
332
  approval_policy=approval_policy,
392
333
  sandbox=sandbox,
393
- config=self._merge_config(
334
+ config=merge_config(
394
335
  config,
395
336
  tools,
396
337
  code_mode,
@@ -445,9 +386,9 @@ class CodexClient:
445
386
  Returns:
446
387
  Session wrapping the resumed thread
447
388
  """
448
- from codexed.session import Session
389
+ from codexed.client.session import Session
449
390
 
450
- cfg = self._merge_config(
391
+ cfg = merge_config(
451
392
  config,
452
393
  tools,
453
394
  code_mode,
@@ -513,9 +454,9 @@ class CodexClient:
513
454
  Returns:
514
455
  Session wrapping the new forked thread
515
456
  """
516
- from codexed.session import Session
457
+ from codexed.client.session import Session
517
458
 
518
- cfg = self._merge_config(
459
+ cfg = merge_config(
519
460
  config,
520
461
  tools,
521
462
  code_mode,
@@ -672,6 +613,19 @@ class CodexClient:
672
613
  raise ValueError(f"Turn {turn_id!r} is already the last turn in thread {thread_id!r}")
673
614
  return await self.thread_rollback(thread_id, num_turns_to_drop)
674
615
 
616
+ async def thread_shell_command(self, thread_id: str, command: str) -> None:
617
+ """Run a user-initiated shell command against a thread.
618
+
619
+ Executes the command unsandboxed, as if the user typed `!command`
620
+ in the Codex CLI.
621
+
622
+ Args:
623
+ thread_id: The thread ID.
624
+ command: Shell command to execute.
625
+ """
626
+ params = ThreadShellCommandParams(thread_id=thread_id, command=command)
627
+ await self._send_request("thread/shellCommand", params)
628
+
675
629
  # ========================================================================
676
630
  # Turn methods
677
631
  # ========================================================================
@@ -1031,112 +985,6 @@ class CodexClient:
1031
985
  result = await self._send_request("command/exec", params)
1032
986
  return CommandExecResponse.model_validate(result)
1033
987
 
1034
- # ========================================================================
1035
- # Filesystem methods
1036
- # ========================================================================
1037
-
1038
- async def fs_read_file(self, path: str) -> FsReadFileResponse:
1039
- """Read a file from the host filesystem.
1040
-
1041
- Args:
1042
- path: Absolute path to read.
1043
-
1044
- Returns:
1045
- FsReadFileResponse with base64-encoded file contents.
1046
- """
1047
- params = FsReadFileParams(path=path)
1048
- result = await self._send_request("fs/readFile", params)
1049
- return FsReadFileResponse.model_validate(result)
1050
-
1051
- async def fs_write_file(self, path: str, data_base64: str) -> None:
1052
- """Write a file on the host filesystem.
1053
-
1054
- Args:
1055
- path: Absolute path to write.
1056
- data_base64: File contents encoded as base64.
1057
- """
1058
- params = FsWriteFileParams(path=path, data_base64=data_base64)
1059
- await self._send_request("fs/writeFile", params)
1060
-
1061
- async def fs_create_directory(self, path: str, *, recursive: bool | None = None) -> None:
1062
- """Create a directory on the host filesystem.
1063
-
1064
- Args:
1065
- path: Absolute directory path to create.
1066
- recursive: Whether to create parent directories. Defaults to True server-side.
1067
- """
1068
- params = FsCreateDirectoryParams(path=path, recursive=recursive)
1069
- await self._send_request("fs/createDirectory", params)
1070
-
1071
- async def fs_get_metadata(self, path: str) -> FsGetMetadataResponse:
1072
- """Get metadata for an absolute path.
1073
-
1074
- Args:
1075
- path: Absolute path to inspect.
1076
-
1077
- Returns:
1078
- FsGetMetadataResponse with isDirectory, isFile, and timestamps.
1079
- """
1080
- params = FsGetMetadataParams(path=path)
1081
- result = await self._send_request("fs/getMetadata", params)
1082
- return FsGetMetadataResponse.model_validate(result)
1083
-
1084
- async def fs_read_directory(
1085
- self,
1086
- path: str,
1087
- *,
1088
- recursive: bool = False,
1089
- ) -> list[FsReadDirectoryEntry]:
1090
- """List child entries for a directory.
1091
-
1092
- Args:
1093
- path: Absolute directory path to read.
1094
- recursive: If True, recursively list all descendant entries.
1095
-
1096
- Returns:
1097
- List of directory entries with fileName, isDirectory, isFile.
1098
- """
1099
- params = FsReadDirectoryParams(path=path)
1100
- result = await self._send_request("fs/readDirectory", params)
1101
- entries = FsReadDirectoryResponse.model_validate(result).entries
1102
- if not recursive:
1103
- return entries
1104
- all_entries = list(entries)
1105
- for entry in entries:
1106
- if entry.is_directory:
1107
- sub_path = f"{path.rstrip('/')}/{entry.file_name}"
1108
- sub_entries = await self.fs_read_directory(sub_path, recursive=True)
1109
- all_entries.extend(sub_entries)
1110
- return all_entries
1111
-
1112
- async def fs_remove(
1113
- self,
1114
- path: str,
1115
- *,
1116
- recursive: bool | None = None,
1117
- force: bool | None = None,
1118
- ) -> None:
1119
- """Remove a file or directory from the host filesystem.
1120
-
1121
- Args:
1122
- path: Absolute path to remove.
1123
- recursive: Whether to recurse into directories. Defaults to True server-side.
1124
- force: Whether to ignore missing paths. Defaults to True server-side.
1125
- """
1126
- params = FsRemoveParams(path=path, recursive=recursive, force=force)
1127
- await self._send_request("fs/remove", params)
1128
-
1129
- async def fs_copy(self, source: str, destination: str, *, recursive: bool = False) -> None:
1130
- """Copy a file or directory tree on the host filesystem.
1131
-
1132
- Args:
1133
- source: Absolute source path.
1134
- destination: Absolute destination path.
1135
- recursive: Required for directory copies; ignored for file copies.
1136
- """
1137
- params = FsCopyParams(source_path=source, destination_path=destination, recursive=recursive)
1138
- await self._send_request("fs/copy", params)
1139
-
1140
988
  # ========================================================================
1141
989
  # MCP server methods
1142
990
  # ========================================================================
@@ -1474,7 +1322,7 @@ class CodexClient:
1474
1322
  Returns:
1475
1323
  Response result (not yet validated - caller should validate)
1476
1324
  """
1477
- if self._process is None or self._process.stdin is None:
1325
+ if not self._transport.is_connected:
1478
1326
  raise TransportClosedError("Not connected to Codex app-server")
1479
1327
 
1480
1328
  request_id = self._request_id
@@ -1486,7 +1334,7 @@ class CodexClient:
1486
1334
  request = JsonRpcRequest(id=request_id, method=method, params=params_dict)
1487
1335
  try:
1488
1336
  message = request.model_dump(mode="json", by_alias=True, exclude_none=True)
1489
- await self._write_message(message)
1337
+ await self._transport.send(message)
1490
1338
  except Exception as exc:
1491
1339
  del self._pending_requests[request_id]
1492
1340
  raise CodexProcessError(f"Failed to send request: {exc}") from exc
@@ -1494,25 +1342,14 @@ class CodexClient:
1494
1342
  return await future
1495
1343
 
1496
1344
  async def _read_loop(self) -> None:
1497
- """Read messages from app-server stdout."""
1498
- if self._process is None or self._process.stdout is None:
1499
- return
1500
-
1345
+ """Read messages from the transport."""
1501
1346
  try:
1502
1347
  while True:
1503
- line_bytes = await self._process.stdout.readline()
1504
- if not line_bytes:
1348
+ message = await self._transport.receive()
1349
+ if message is None:
1505
1350
  break
1506
-
1507
- line = line_bytes.decode().strip()
1508
- if not line or line == "null":
1509
- continue
1510
-
1511
1351
  try:
1512
- message = anyenv.load_json(line, return_type=dict)
1513
1352
  await self._process_message(message)
1514
- except json.JSONDecodeError:
1515
- logger.warning("Failed to parse JSON: %s", line)
1516
1353
  except Exception:
1517
1354
  logger.exception("Error processing message")
1518
1355
 
@@ -1639,13 +1476,8 @@ class CodexClient:
1639
1476
  await self._write_message(response)
1640
1477
 
1641
1478
  async def _write_message(self, message: dict[str, Any]) -> None:
1642
- """Write a JSON message to the app-server stdin."""
1643
- if self._process is None or self._process.stdin is None:
1644
- raise TransportClosedError("Not connected to Codex app-server")
1645
- async with self._writer_lock:
1646
- line = json.dumps(message) + "\n"
1647
- self._process.stdin.write(line.encode())
1648
- await self._process.stdin.drain()
1479
+ """Write a JSON message via the transport."""
1480
+ await self._transport.send(message)
1649
1481
 
1650
1482
  # ========================================================================
1651
1483
  # Server request handler registration