codexed 0.1.2__tar.gz → 0.1.3__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 (35) hide show
  1. {codexed-0.1.2 → codexed-0.1.3}/PKG-INFO +3 -1
  2. {codexed-0.1.2 → codexed-0.1.3}/pyproject.toml +4 -1
  3. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/__init__.py +7 -4
  4. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/client.py +71 -69
  5. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/__init__.py +18 -0
  6. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/codex_types.py +3 -0
  7. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/event_data.py +7 -0
  8. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/events.py +10 -0
  9. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/request_params.py +19 -0
  10. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/responses.py +15 -0
  11. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/thread_item.py +2 -0
  12. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/session.py +4 -0
  13. codexed-0.1.3/src/codexed/transport.py +201 -0
  14. {codexed-0.1.2 → codexed-0.1.3}/LICENSE +0 -0
  15. {codexed-0.1.2 → codexed-0.1.3}/README.md +0 -0
  16. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/README.md +0 -0
  17. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/exceptions.py +0 -0
  18. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/helpers.py +0 -0
  19. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/log.py +0 -0
  20. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/base.py +0 -0
  21. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/command_action.py +0 -0
  22. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/fuzzy_search.py +0 -0
  23. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/hooks.py +0 -0
  24. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/mcp_server.py +0 -0
  25. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/misc.py +0 -0
  26. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/realtime.py +0 -0
  27. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/response_item.py +0 -0
  28. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/terminal.py +0 -0
  29. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/thread_status.py +0 -0
  30. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/token_usage.py +0 -0
  31. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/tool_config.py +0 -0
  32. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/user_input.py +0 -0
  33. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/models/web_search.py +0 -0
  34. {codexed-0.1.2 → codexed-0.1.3}/src/codexed/py.typed +0 -0
  35. {codexed-0.1.2 → codexed-0.1.3}/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.3
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.3"
6
6
  description = "Alternative codex app-server client"
7
7
  readme = "README.md"
8
8
  requires-python = ">=3.13"
@@ -35,6 +35,9 @@ dependencies = [
35
35
  # Only add below (Copier)
36
36
  ]
37
37
 
38
+ [project.optional-dependencies]
39
+ websocket = ["websockets>=13.0"]
40
+
38
41
  [project.urls]
39
42
  "Code coverage" = "https://app.codecov.io/gh/phil65/codexed"
40
43
  Discussions = "https://github.com/phil65/codexed/discussions"
@@ -16,10 +16,6 @@ __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
20
  from codexed.client import CodexClient
25
21
  from codexed.session import Session
@@ -86,6 +82,7 @@ from codexed.models.codex_types import (
86
82
  CollabAgentTool,
87
83
  CollaborationMode,
88
84
  CollaborationModeSettings,
85
+ CommandExecutionSource,
89
86
  CommandExecutionStatus,
90
87
  DangerFullAccessSandboxPolicy,
91
88
  ExternalSandboxPolicy,
@@ -127,6 +124,7 @@ from codexed.models.events import (
127
124
  ConfigWarningEvent,
128
125
  EventType,
129
126
  FileChangeOutputDeltaEvent,
127
+ FsChangedEvent,
130
128
  ItemCompletedEvent,
131
129
  ItemStartedEvent,
132
130
  ModelReroutedEvent,
@@ -144,6 +142,7 @@ from codexed.models.events import (
144
142
  TurnStartedEvent,
145
143
  )
146
144
  from codexed.models.mcp_server import HttpMcpServer, McpServerConfig, StdioMcpServer
145
+ from codexed.transport import StdioTransport, WebSocketTransport
147
146
  from codexed.models.tool_config import BuiltinToolsConfig, ToolConfig, tools_to_config_dict
148
147
  from codexed.request_handlers import (
149
148
  ApprovalHandler,
@@ -180,6 +179,7 @@ __all__ = [
180
179
  "CommandExecResponse",
181
180
  "CommandExecutionOutputDeltaData",
182
181
  "CommandExecutionOutputDeltaEvent",
182
+ "CommandExecutionSource",
183
183
  "CommandExecutionStatus",
184
184
  "ConfigWarningData",
185
185
  "ConfigWarningEvent",
@@ -190,6 +190,7 @@ __all__ = [
190
190
  "ExperimentalFeature",
191
191
  "ExternalSandboxPolicy",
192
192
  "FileChangeOutputDeltaEvent",
193
+ "FsChangedEvent",
193
194
  "HttpMcpServer",
194
195
  "InputModality",
195
196
  "InternalRpcError",
@@ -235,6 +236,7 @@ __all__ = [
235
236
  "SkillData",
236
237
  "SkillScope",
237
238
  "StdioMcpServer",
239
+ "StdioTransport",
238
240
  "Thread",
239
241
  "ThreadActiveFlag",
240
242
  "ThreadArchivedData",
@@ -278,6 +280,7 @@ __all__ = [
278
280
  "UserInputMention",
279
281
  "UserInputSkill",
280
282
  "UserInputText",
283
+ "WebSocketTransport",
281
284
  "WorkspaceWriteSandboxPolicy",
282
285
  "is_retryable_error",
283
286
  "map_jsonrpc_error",
@@ -5,12 +5,9 @@ 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
 
16
13
  from codexed.exceptions import (
@@ -51,6 +48,9 @@ from codexed.models import (
51
48
  FsReadFileParams,
52
49
  FsReadFileResponse,
53
50
  FsRemoveParams,
51
+ FsUnwatchParams,
52
+ FsWatchParams,
53
+ FsWatchResponse,
54
54
  FsWriteFileParams,
55
55
  GetAccountParams,
56
56
  GetAccountRateLimitsResponse,
@@ -88,6 +88,7 @@ from codexed.models import (
88
88
  ThreadRollbackParams,
89
89
  ThreadRollbackResponse,
90
90
  ThreadSetNameParams,
91
+ ThreadShellCommandParams,
91
92
  ThreadStartParams,
92
93
  ThreadUnarchiveParams,
93
94
  ThreadUnarchiveResponse,
@@ -116,6 +117,7 @@ from codexed.request_handlers import (
116
117
  SERVER_REQUEST_USER_INPUT,
117
118
  create_auto_approve_dict,
118
119
  )
120
+ from codexed.transport import StdioTransport
119
121
 
120
122
 
121
123
  if TYPE_CHECKING:
@@ -158,6 +160,7 @@ if TYPE_CHECKING:
158
160
  UserInputHandler,
159
161
  )
160
162
  from codexed.session import Session
163
+ from codexed.transport import Transport
161
164
 
162
165
  logger = logging.getLogger(__name__)
163
166
 
@@ -182,6 +185,7 @@ class CodexClient:
182
185
  on_dynamic_tool_call: DynamicToolCallHandler | None = None,
183
186
  on_mcp_elicitation: McpElicitationHandler | None = None,
184
187
  mcp_elicitation_for_approvals: bool = False,
188
+ transport: Transport | None = None,
185
189
  ) -> None:
186
190
  """Initialize the Codex app-server client.
187
191
 
@@ -203,18 +207,26 @@ class CodexClient:
203
207
  to handle approvals (the schema is empty; context is in ``_meta``).
204
208
  Default is False because the default elicitation handler auto-declines,
205
209
  which would break MCP tool approvals.
210
+ transport: Pre-configured transport instance. If provided,
211
+ ``codex_command``, ``profile``, ``env_vars``, and ``mcp_servers``
212
+ are ignored (they are only used to build the default
213
+ ``StdioTransport``). Pass a ``WebSocketTransport`` here to
214
+ connect to a remote app-server.
206
215
  """
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
216
+ if transport is not None:
217
+ self._transport = transport
218
+ else:
219
+ self._transport = StdioTransport(
220
+ codex_command=codex_command,
221
+ profile=profile,
222
+ env_vars=env_vars,
223
+ mcp_servers=mcp_servers,
224
+ )
211
225
  self._request_id = 0
212
- self._env_vars = env_vars or {}
213
226
  self._pending_requests: dict[int, asyncio.Future[Any]] = {}
214
227
  self._event_queue: asyncio.Queue[CodexEvent | None] = asyncio.Queue()
215
228
  self._turn_queues: dict[str, asyncio.Queue[CodexEvent | None]] = {}
216
229
  self._reader_task: asyncio.Task[None] | None = None
217
- self._writer_lock = asyncio.Lock()
218
230
  self._active_threads: set[str] = set()
219
231
  self._mcp_elicitation_enabled = on_mcp_elicitation is not None
220
232
  self._mcp_elicitation_for_approvals = mcp_elicitation_for_approvals
@@ -240,47 +252,27 @@ class CodexClient:
240
252
  await self.stop()
241
253
 
242
254
  async def start(self) -> None:
243
- """Start the Codex app-server subprocess and initialize connection.
255
+ """Start the transport and initialize the JSON-RPC connection.
244
256
 
245
257
  Raises:
246
- CodexProcessError: If failed to start the process
258
+ CodexProcessError: If failed to start the transport
247
259
  """
248
260
  import codexed
249
261
 
250
- if self._process is not None:
262
+ if self._transport.is_connected:
251
263
  return
252
264
 
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
265
+ await self._transport.start()
274
266
  # Start reader task
275
267
  self._reader_task = asyncio.create_task(self._read_loop())
276
268
  # Initialize connection
277
269
  version = codexed.__version__
278
- init_params = InitializeParams.create(name="agentpool-codex-adapter", version=version)
270
+ init_params = InitializeParams.create(name="codexed", version=version)
279
271
  await self._send_request("initialize", init_params)
280
272
 
281
273
  async def stop(self) -> None:
282
- """Stop the Codex app-server subprocess."""
283
- if self._process is None:
274
+ """Stop the transport and clean up resources."""
275
+ if not self._transport.is_connected:
284
276
  return
285
277
 
286
278
  # Cancel reader task
@@ -289,16 +281,7 @@ class CodexClient:
289
281
  with contextlib.suppress(asyncio.CancelledError):
290
282
  await self._reader_task
291
283
 
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
284
+ await self._transport.stop()
302
285
  # Reject pending requests
303
286
  for future in self._pending_requests.values():
304
287
  if not future.done():
@@ -672,6 +655,19 @@ class CodexClient:
672
655
  raise ValueError(f"Turn {turn_id!r} is already the last turn in thread {thread_id!r}")
673
656
  return await self.thread_rollback(thread_id, num_turns_to_drop)
674
657
 
658
+ async def thread_shell_command(self, thread_id: str, command: str) -> None:
659
+ """Run a user-initiated shell command against a thread.
660
+
661
+ Executes the command unsandboxed, as if the user typed `!command`
662
+ in the Codex CLI.
663
+
664
+ Args:
665
+ thread_id: The thread ID.
666
+ command: Shell command to execute.
667
+ """
668
+ params = ThreadShellCommandParams(thread_id=thread_id, command=command)
669
+ await self._send_request("thread/shellCommand", params)
670
+
675
671
  # ========================================================================
676
672
  # Turn methods
677
673
  # ========================================================================
@@ -1137,6 +1133,28 @@ class CodexClient:
1137
1133
  params = FsCopyParams(source_path=source, destination_path=destination, recursive=recursive)
1138
1134
  await self._send_request("fs/copy", params)
1139
1135
 
1136
+ async def fs_watch(self, path: str) -> FsWatchResponse:
1137
+ """Start filesystem watch notifications for an absolute path.
1138
+
1139
+ Args:
1140
+ path: Absolute file or directory path to watch.
1141
+
1142
+ Returns:
1143
+ FsWatchResponse with watch_id and canonicalized path.
1144
+ """
1145
+ params = FsWatchParams(path=path)
1146
+ result = await self._send_request("fs/watch", params)
1147
+ return FsWatchResponse.model_validate(result)
1148
+
1149
+ async def fs_unwatch(self, watch_id: str) -> None:
1150
+ """Stop filesystem watch notifications for a prior watch.
1151
+
1152
+ Args:
1153
+ watch_id: Watch identifier returned by fs_watch.
1154
+ """
1155
+ params = FsUnwatchParams(watch_id=watch_id)
1156
+ await self._send_request("fs/unwatch", params)
1157
+
1140
1158
  # ========================================================================
1141
1159
  # MCP server methods
1142
1160
  # ========================================================================
@@ -1474,7 +1492,7 @@ class CodexClient:
1474
1492
  Returns:
1475
1493
  Response result (not yet validated - caller should validate)
1476
1494
  """
1477
- if self._process is None or self._process.stdin is None:
1495
+ if not self._transport.is_connected:
1478
1496
  raise TransportClosedError("Not connected to Codex app-server")
1479
1497
 
1480
1498
  request_id = self._request_id
@@ -1486,7 +1504,7 @@ class CodexClient:
1486
1504
  request = JsonRpcRequest(id=request_id, method=method, params=params_dict)
1487
1505
  try:
1488
1506
  message = request.model_dump(mode="json", by_alias=True, exclude_none=True)
1489
- await self._write_message(message)
1507
+ await self._transport.send(message)
1490
1508
  except Exception as exc:
1491
1509
  del self._pending_requests[request_id]
1492
1510
  raise CodexProcessError(f"Failed to send request: {exc}") from exc
@@ -1494,25 +1512,14 @@ class CodexClient:
1494
1512
  return await future
1495
1513
 
1496
1514
  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
-
1515
+ """Read messages from the transport."""
1501
1516
  try:
1502
1517
  while True:
1503
- line_bytes = await self._process.stdout.readline()
1504
- if not line_bytes:
1518
+ message = await self._transport.receive()
1519
+ if message is None:
1505
1520
  break
1506
-
1507
- line = line_bytes.decode().strip()
1508
- if not line or line == "null":
1509
- continue
1510
-
1511
1521
  try:
1512
- message = anyenv.load_json(line, return_type=dict)
1513
1522
  await self._process_message(message)
1514
- except json.JSONDecodeError:
1515
- logger.warning("Failed to parse JSON: %s", line)
1516
1523
  except Exception:
1517
1524
  logger.exception("Error processing message")
1518
1525
 
@@ -1639,13 +1646,8 @@ class CodexClient:
1639
1646
  await self._write_message(response)
1640
1647
 
1641
1648
  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()
1649
+ """Write a JSON message via the transport."""
1650
+ await self._transport.send(message)
1649
1651
 
1650
1652
  # ========================================================================
1651
1653
  # Server request handler registration
@@ -16,6 +16,7 @@ from codexed.models.codex_types import (
16
16
  CollabAgentTool,
17
17
  CollaborationMode,
18
18
  CollaborationModeSettings,
19
+ CommandExecutionSource,
19
20
  CommandExecutionStatus,
20
21
  DangerFullAccessSandboxPolicy,
21
22
  ElicitationAction,
@@ -78,6 +79,7 @@ from codexed.models.event_data import (
78
79
  CommandExecutionTerminalInteractionData,
79
80
  ConfigWarningData,
80
81
  ContextCompactedData,
82
+ FsChangedData,
81
83
  DeprecationNoticeData,
82
84
  ErrorEventData,
83
85
  EventData,
@@ -176,6 +178,7 @@ from codexed.models.events import (
176
178
  CommandExecutionTerminalInteractionEvent,
177
179
  ConfigWarningEvent,
178
180
  ContextCompactedEvent,
181
+ FsChangedEvent,
179
182
  DeltaEvent,
180
183
  HookCompletedEvent,
181
184
  HookStartedEvent,
@@ -297,6 +300,8 @@ from codexed.models.request_params import (
297
300
  FsReadDirectoryParams,
298
301
  FsReadFileParams,
299
302
  FsRemoveParams,
303
+ FsUnwatchParams,
304
+ FsWatchParams,
300
305
  FsWriteFileParams,
301
306
  GetAccountParams,
302
307
  InitializeParams,
@@ -325,6 +330,7 @@ from codexed.models.request_params import (
325
330
  ThreadResumeParams,
326
331
  ThreadRollbackParams,
327
332
  ThreadSetNameParams,
333
+ ThreadShellCommandParams,
328
334
  ThreadStartParams,
329
335
  ThreadUnarchiveParams,
330
336
  ThreadUnsubscribeParams,
@@ -374,6 +380,8 @@ from codexed.models.responses import (
374
380
  FsReadDirectoryResponse,
375
381
  FsReadFileResponse,
376
382
  FsRemoveResponse,
383
+ FsUnwatchResponse,
384
+ FsWatchResponse,
377
385
  FsWriteFileResponse,
378
386
  GetAccountRateLimitsResponse,
379
387
  GetAccountResponse,
@@ -394,6 +402,7 @@ from codexed.models.responses import (
394
402
  ThreadReadResponse,
395
403
  ThreadResponse,
396
404
  ThreadRollbackResponse,
405
+ ThreadShellCommandResponse,
397
406
  ThreadUnarchiveResponse,
398
407
  ThreadUnsubscribeResponse,
399
408
  ToolRequestUserInputResponse,
@@ -538,6 +547,7 @@ __all__ = [
538
547
  "CommandExecutionOutputDeltaEvent",
539
548
  "CommandExecutionRequestApprovalParams",
540
549
  "CommandExecutionRequestApprovalResponse",
550
+ "CommandExecutionSource",
541
551
  "CommandExecutionStatus",
542
552
  "CommandExecutionTerminalInteractionData",
543
553
  "CommandExecutionTerminalInteractionEvent",
@@ -592,6 +602,8 @@ __all__ = [
592
602
  "FileChangeRequestApprovalParams",
593
603
  "FileChangeRequestApprovalResponse",
594
604
  "FileUpdateChange",
605
+ "FsChangedData",
606
+ "FsChangedEvent",
595
607
  "FsCopyParams",
596
608
  "FsCopyResponse",
597
609
  "FsCreateDirectoryParams",
@@ -605,6 +617,10 @@ __all__ = [
605
617
  "FsReadFileResponse",
606
618
  "FsRemoveParams",
607
619
  "FsRemoveResponse",
620
+ "FsUnwatchParams",
621
+ "FsUnwatchResponse",
622
+ "FsWatchParams",
623
+ "FsWatchResponse",
608
624
  "FsWriteFileParams",
609
625
  "FsWriteFileResponse",
610
626
  "FullAccessReadOnlyAccess",
@@ -836,6 +852,8 @@ __all__ = [
836
852
  "ThreadRollbackParams",
837
853
  "ThreadRollbackResponse",
838
854
  "ThreadSetNameParams",
855
+ "ThreadShellCommandParams",
856
+ "ThreadShellCommandResponse",
839
857
  "ThreadSortKey",
840
858
  "ThreadSourceKind",
841
859
  "ThreadStartParams",
@@ -48,6 +48,9 @@ ThreadSourceKind = Literal[
48
48
  MessagePhase = Literal["commentary", "final_answer"]
49
49
  PatchApplyStatus = Literal["inProgress", "completed", "failed", "declined"]
50
50
  CommandExecutionStatus = Literal["inProgress", "completed", "failed", "declined"]
51
+ CommandExecutionSource = Literal[
52
+ "agent", "userShell", "unifiedExecStartup", "unifiedExecInteraction"
53
+ ]
51
54
  ToolCallStatus = Literal["inProgress", "completed", "failed"]
52
55
  CollabAgentTool = Literal["spawnAgent", "sendInput", "resumeAgent", "wait", "closeAgent"]
53
56
  CollabAgentStatus = Literal[
@@ -299,6 +299,13 @@ class AppListUpdatedData(CodexBaseModel):
299
299
  data: list[AppInfo]
300
300
 
301
301
 
302
+ class FsChangedData(CodexBaseModel):
303
+ """Payload for fs/changed notification."""
304
+
305
+ watch_id: str
306
+ changed_paths: list[str]
307
+
308
+
302
309
  class ContextCompactedData(CodexBaseModel):
303
310
  """Payload for thread/compacted/v2 notification."""
304
311
 
@@ -25,6 +25,7 @@ from codexed.models.event_data import ( # noqa: TC001
25
25
  DeprecationNoticeData,
26
26
  ErrorEventData,
27
27
  FileChangeOutputDeltaData,
28
+ FsChangedData,
28
29
  ItemCompletedData,
29
30
  ItemStartedData,
30
31
  LoginChatGptCompleteData,
@@ -510,6 +511,13 @@ class AppListUpdatedEvent(CodexBaseModel):
510
511
  data: AppListUpdatedData
511
512
 
512
513
 
514
+ class FsChangedEvent(CodexBaseModel):
515
+ """Filesystem changed event."""
516
+
517
+ event_type: Literal["fs/changed"] = "fs/changed"
518
+ data: FsChangedData
519
+
520
+
513
521
  class ContextCompactedEvent(CodexBaseModel):
514
522
  """Context compacted event (alias for ThreadCompactedEvent with turnId)."""
515
523
 
@@ -596,6 +604,7 @@ CodexEvent = Annotated[
596
604
  | ModelReroutedEvent
597
605
  | ConfigWarningEvent
598
606
  | AppListUpdatedEvent
607
+ | FsChangedEvent
599
608
  | ContextCompactedEvent
600
609
  | ServerRequestResolvedEvent,
601
610
  Field(discriminator="event_type"),
@@ -678,6 +687,7 @@ EventType = Literal[
678
687
  "model/rerouted",
679
688
  "configWarning",
680
689
  "app/list/updated",
690
+ "fs/changed",
681
691
  "thread/compacted/v2",
682
692
  "serverRequest/resolved",
683
693
  ]
@@ -460,6 +460,25 @@ class FsCopyParams(CodexBaseModel):
460
460
  recursive: bool = False
461
461
 
462
462
 
463
+ class ThreadShellCommandParams(CodexBaseModel):
464
+ """Parameters for thread/shellCommand request."""
465
+
466
+ thread_id: str
467
+ command: str
468
+
469
+
470
+ class FsWatchParams(CodexBaseModel):
471
+ """Parameters for fs/watch request."""
472
+
473
+ path: str
474
+
475
+
476
+ class FsUnwatchParams(CodexBaseModel):
477
+ """Parameters for fs/unwatch request."""
478
+
479
+ watch_id: str
480
+
481
+
463
482
  class CommandExecutionRequestApprovalParams(CodexBaseModel):
464
483
  """Parameters for item/commandExecution/requestApproval server request."""
465
484
 
@@ -364,3 +364,18 @@ class FsRemoveResponse(CodexBaseModel):
364
364
 
365
365
  class FsCopyResponse(CodexBaseModel):
366
366
  """Response for fs/copy request."""
367
+
368
+
369
+ class ThreadShellCommandResponse(CodexBaseModel):
370
+ """Response for thread/shellCommand request."""
371
+
372
+
373
+ class FsWatchResponse(CodexBaseModel):
374
+ """Response for fs/watch request."""
375
+
376
+ watch_id: str
377
+ path: str
378
+
379
+
380
+ class FsUnwatchResponse(CodexBaseModel):
381
+ """Response for fs/unwatch request."""
@@ -9,6 +9,7 @@ from codexed.models.base import CodexBaseModel
9
9
  from codexed.models.codex_types import ( # noqa: TC001
10
10
  CollabAgentStatus,
11
11
  CollabAgentTool,
12
+ CommandExecutionSource,
12
13
  CommandExecutionStatus,
13
14
  MessagePhase,
14
15
  PatchApplyStatus,
@@ -121,6 +122,7 @@ class ThreadItemCommandExecution(BaseThreadItem):
121
122
  cwd: str
122
123
  process_id: str | None = None
123
124
  status: CommandExecutionStatus
125
+ source: CommandExecutionSource = "agent"
124
126
  command_actions: list[CommandAction] = Field(default_factory=list)
125
127
  aggregated_output: str | None = None
126
128
  exit_code: int | None = None
@@ -182,6 +182,10 @@ class Session:
182
182
  """Rollback to a specific turn. See :meth:`CodexClient.thread_rollback_to_turn`."""
183
183
  return await self._client.thread_rollback_to_turn(self.thread_id, turn_id)
184
184
 
185
+ async def shell_command(self, command: str) -> None:
186
+ """Run a user-initiated shell command. See :meth:`CodexClient.thread_shell_command`."""
187
+ await self._client.thread_shell_command(self.thread_id, command)
188
+
185
189
  # -- Review --------------------------------------------------------------
186
190
 
187
191
  async def review_start(
@@ -0,0 +1,201 @@
1
+ """Transport abstractions for the Codex app-server protocol.
2
+
3
+ Provides a Protocol-based transport interface and concrete implementations:
4
+ - StdioTransport: Communicates via subprocess stdin/stdout (default)
5
+ - WebSocketTransport: Connects to a remote app-server via WebSocket
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import contextlib
12
+ import json
13
+ import logging
14
+ import os
15
+ from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
16
+
17
+ import anyenv
18
+
19
+ from codexed.exceptions import CodexProcessError, TransportClosedError
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from collections.abc import Mapping
24
+
25
+ from codexed.models import McpServerConfig
26
+
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ @runtime_checkable
32
+ class Transport(Protocol):
33
+ """Abstract transport for bidirectional JSON message exchange."""
34
+
35
+ async def start(self) -> None:
36
+ """Open the transport connection."""
37
+ ...
38
+
39
+ async def stop(self) -> None:
40
+ """Close the transport connection and release resources."""
41
+ ...
42
+
43
+ async def send(self, message: dict[str, Any]) -> None:
44
+ """Send a JSON message over the transport."""
45
+ ...
46
+
47
+ async def receive(self) -> dict[str, Any] | None:
48
+ """Receive the next JSON message, or None if the transport is closed."""
49
+ ...
50
+
51
+ @property
52
+ def is_connected(self) -> bool:
53
+ """Whether the transport is currently connected."""
54
+ ...
55
+
56
+
57
+ class StdioTransport:
58
+ """Transport that communicates with a Codex app-server subprocess via stdin/stdout."""
59
+
60
+ def __init__(
61
+ self,
62
+ codex_command: str = "codex",
63
+ profile: str | None = None,
64
+ env_vars: dict[str, str] | None = None,
65
+ mcp_servers: Mapping[str, McpServerConfig] | None = None,
66
+ ) -> None:
67
+ self._codex_command = codex_command
68
+ self._profile = profile
69
+ self._mcp_servers = dict(mcp_servers) if mcp_servers else {}
70
+ self._env_vars = env_vars or {}
71
+ self._process: asyncio.subprocess.Process | None = None
72
+ self._writer_lock = asyncio.Lock()
73
+
74
+ async def start(self) -> None:
75
+ if self._process is not None:
76
+ return
77
+
78
+ cmd = [self._codex_command, "app-server"]
79
+ if self._profile:
80
+ cmd.extend(["--profile", self._profile])
81
+ for server_name, server_config in self._mcp_servers.items():
82
+ config_str = server_config.to_config_toml(server_name)
83
+ cmd.extend(["--config", config_str])
84
+
85
+ logger.info("Starting Codex app-server: %s", " ".join(cmd))
86
+ try:
87
+ self._process = await anyenv.create_process(
88
+ *cmd,
89
+ stdin="pipe",
90
+ stdout="pipe",
91
+ stderr="pipe",
92
+ env={**os.environ, **self._env_vars},
93
+ )
94
+ except FileNotFoundError as exc:
95
+ raise CodexProcessError(f"Codex binary not found: {self._codex_command}") from exc
96
+ except Exception as exc:
97
+ raise CodexProcessError(f"Failed to start Codex app-server: {exc}") from exc
98
+
99
+ async def stop(self) -> None:
100
+ if self._process is None:
101
+ return
102
+ if self._process.returncode is None:
103
+ self._process.terminate()
104
+ try:
105
+ await asyncio.wait_for(self._process.wait(), timeout=5.0)
106
+ except TimeoutError:
107
+ self._process.kill()
108
+ await self._process.wait()
109
+ self._process = None
110
+
111
+ async def send(self, message: dict[str, Any]) -> None:
112
+ if self._process is None or self._process.stdin is None:
113
+ raise TransportClosedError("Not connected to Codex app-server")
114
+ async with self._writer_lock:
115
+ line = json.dumps(message) + "\n"
116
+ self._process.stdin.write(line.encode())
117
+ await self._process.stdin.drain()
118
+
119
+ async def receive(self) -> dict[str, Any] | None:
120
+ if self._process is None or self._process.stdout is None:
121
+ return None
122
+ line_bytes = await self._process.stdout.readline()
123
+ if not line_bytes:
124
+ return None
125
+ line = line_bytes.decode().strip()
126
+ if not line or line == "null":
127
+ return await self.receive()
128
+ return anyenv.load_json(line, return_type=dict)
129
+
130
+ @property
131
+ def is_connected(self) -> bool:
132
+ return self._process is not None
133
+
134
+
135
+ class WebSocketTransport:
136
+ """Transport that connects to a remote Codex app-server via WebSocket.
137
+
138
+ Requires the ``websockets`` package (``pip install codexed[websocket]``).
139
+ """
140
+
141
+ def __init__(
142
+ self,
143
+ url: str,
144
+ *,
145
+ auth_token: str | None = None,
146
+ extra_headers: dict[str, str] | None = None,
147
+ ) -> None:
148
+ self._url = url
149
+ self._auth_token = auth_token
150
+ self._extra_headers = extra_headers or {}
151
+ self._ws: Any = None
152
+ self._writer_lock = asyncio.Lock()
153
+
154
+ async def start(self) -> None:
155
+ if self._ws is not None:
156
+ return
157
+ try:
158
+ import websockets
159
+ except ImportError as exc:
160
+ msg = (
161
+ "WebSocketTransport requires the 'websockets' package. "
162
+ "Install it with: pip install codexed[websocket]"
163
+ )
164
+ raise ImportError(msg) from exc
165
+
166
+ headers = dict(self._extra_headers)
167
+ if self._auth_token:
168
+ headers["Authorization"] = f"Bearer {self._auth_token}"
169
+
170
+ self._ws = await websockets.connect(self._url, additional_headers=headers)
171
+
172
+ async def stop(self) -> None:
173
+ if self._ws is None:
174
+ return
175
+ with contextlib.suppress(Exception):
176
+ await self._ws.close()
177
+ self._ws = None
178
+
179
+ async def send(self, message: dict[str, Any]) -> None:
180
+ if self._ws is None:
181
+ raise TransportClosedError("WebSocket not connected")
182
+ async with self._writer_lock:
183
+ await self._ws.send(json.dumps(message))
184
+
185
+ async def receive(self) -> dict[str, Any] | None:
186
+ if self._ws is None:
187
+ return None
188
+ try:
189
+ raw = await self._ws.recv()
190
+ except Exception: # noqa: BLE001
191
+ return None
192
+ if isinstance(raw, bytes):
193
+ raw = raw.decode()
194
+ raw = raw.strip()
195
+ if not raw or raw == "null":
196
+ return await self.receive()
197
+ return json.loads(raw)
198
+
199
+ @property
200
+ def is_connected(self) -> bool:
201
+ return self._ws is not None
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes