codexed 0.1.4__tar.gz → 0.1.5__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.
- {codexed-0.1.4 → codexed-0.1.5}/PKG-INFO +1 -1
- {codexed-0.1.4 → codexed-0.1.5}/pyproject.toml +1 -1
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/__init__.py +0 -2
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/client/client.py +89 -247
- codexed-0.1.5/src/codexed/client/dispatch.py +151 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/client/fs.py +9 -9
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/__init__.py +4 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/codex_types.py +1 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/event_data.py +11 -1
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/events.py +12 -0
- {codexed-0.1.4 → codexed-0.1.5}/LICENSE +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/README.md +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/README.md +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/client/__init__.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/client/session.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/exceptions.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/helpers.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/log.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/base.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/command_action.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/fuzzy_search.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/hooks.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/mcp_server.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/misc.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/realtime.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/request_params.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/response_item.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/responses.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/terminal.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/thread_item.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/thread_status.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/token_usage.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/tool_config.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/user_input.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/models/web_search.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/py.typed +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/request_handlers.py +0 -0
- {codexed-0.1.4 → codexed-0.1.5}/src/codexed/transport.py +0 -0
|
@@ -32,7 +32,6 @@ from codexed.exceptions import (
|
|
|
32
32
|
TransportClosedError,
|
|
33
33
|
TurnFailedError,
|
|
34
34
|
is_retryable_error,
|
|
35
|
-
map_jsonrpc_error,
|
|
36
35
|
)
|
|
37
36
|
from codexed.models import (
|
|
38
37
|
AgentMessageDeltaData,
|
|
@@ -282,6 +281,5 @@ __all__ = [
|
|
|
282
281
|
"WebSocketTransport",
|
|
283
282
|
"WorkspaceWriteSandboxPolicy",
|
|
284
283
|
"is_retryable_error",
|
|
285
|
-
"map_jsonrpc_error",
|
|
286
284
|
"tools_to_config_dict",
|
|
287
285
|
]
|
|
@@ -4,20 +4,14 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
6
|
from collections.abc import AsyncIterator, Mapping # noqa: TC003
|
|
7
|
-
import contextlib
|
|
8
7
|
import logging
|
|
9
8
|
from typing import TYPE_CHECKING, Any, assert_never
|
|
10
9
|
|
|
11
10
|
from pydantic import BaseModel, TypeAdapter
|
|
12
11
|
|
|
12
|
+
from codexed.client.dispatch import Dispatch
|
|
13
13
|
from codexed.client.fs import CodexFS
|
|
14
|
-
from codexed.exceptions import
|
|
15
|
-
CodexProcessError,
|
|
16
|
-
CodexRequestError,
|
|
17
|
-
TransportClosedError,
|
|
18
|
-
TurnFailedError,
|
|
19
|
-
map_jsonrpc_error,
|
|
20
|
-
)
|
|
14
|
+
from codexed.exceptions import CodexRequestError, TurnFailedError
|
|
21
15
|
from codexed.helpers import kebab_to_camel, merge_config
|
|
22
16
|
from codexed.models import (
|
|
23
17
|
AppsListParams,
|
|
@@ -43,9 +37,6 @@ from codexed.models import (
|
|
|
43
37
|
GetAccountParams,
|
|
44
38
|
GetAccountRateLimitsResponse,
|
|
45
39
|
GetAccountResponse,
|
|
46
|
-
InitializeParams,
|
|
47
|
-
JsonRpcRequest,
|
|
48
|
-
JsonRpcResponse,
|
|
49
40
|
ListMcpServerStatusParams,
|
|
50
41
|
ListMcpServerStatusResponse,
|
|
51
42
|
LoginAccountParams,
|
|
@@ -199,20 +190,19 @@ class CodexClient:
|
|
|
199
190
|
``StdioTransport``). Pass a ``WebSocketTransport`` here to
|
|
200
191
|
connect to a remote app-server.
|
|
201
192
|
"""
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
self._event_queue: asyncio.Queue[CodexEvent | None] = asyncio.Queue()
|
|
193
|
+
tp = transport or StdioTransport(
|
|
194
|
+
command=codex_command,
|
|
195
|
+
profile=profile,
|
|
196
|
+
env_vars=env_vars,
|
|
197
|
+
mcp_servers=mcp_servers,
|
|
198
|
+
)
|
|
199
|
+
self.dispatch = Dispatch(
|
|
200
|
+
tp,
|
|
201
|
+
on_notification=self._handle_notification,
|
|
202
|
+
on_server_request=self._handle_server_request,
|
|
203
|
+
)
|
|
214
204
|
self._turn_queues: dict[str, asyncio.Queue[CodexEvent | None]] = {}
|
|
215
|
-
self.
|
|
205
|
+
self._event_queue: asyncio.Queue[CodexEvent | None] = asyncio.Queue()
|
|
216
206
|
self._active_threads: set[str] = set()
|
|
217
207
|
self._mcp_elicitation_enabled = on_mcp_elicitation is not None
|
|
218
208
|
self._mcp_elicitation_for_approvals = mcp_elicitation_for_approvals
|
|
@@ -231,49 +221,18 @@ class CodexClient:
|
|
|
231
221
|
|
|
232
222
|
async def __aenter__(self) -> Self:
|
|
233
223
|
"""Async context manager entry - starts the app-server."""
|
|
234
|
-
await self.start()
|
|
235
|
-
return self
|
|
236
|
-
|
|
237
|
-
async def __aexit__(self, *_args: object) -> None:
|
|
238
|
-
"""Async context manager exit - stops the app-server."""
|
|
239
|
-
await self.stop()
|
|
240
|
-
|
|
241
|
-
async def start(self) -> None:
|
|
242
|
-
"""Start the transport and initialize the JSON-RPC connection.
|
|
243
|
-
|
|
244
|
-
Raises:
|
|
245
|
-
CodexProcessError: If failed to start the transport
|
|
246
|
-
"""
|
|
247
224
|
import codexed
|
|
225
|
+
from codexed.models import InitializeParams
|
|
248
226
|
|
|
249
|
-
|
|
250
|
-
return
|
|
251
|
-
|
|
252
|
-
await self._transport.start()
|
|
253
|
-
# Start reader task
|
|
254
|
-
self._reader_task = asyncio.create_task(self._read_loop())
|
|
255
|
-
# Initialize connection
|
|
227
|
+
await self.dispatch.start()
|
|
256
228
|
version = codexed.__version__
|
|
257
229
|
init_params = InitializeParams.create(name="codexed", version=version)
|
|
258
|
-
await self.
|
|
259
|
-
|
|
260
|
-
async def stop(self) -> None:
|
|
261
|
-
"""Stop the transport and clean up resources."""
|
|
262
|
-
if not self._transport.is_connected:
|
|
263
|
-
return
|
|
264
|
-
|
|
265
|
-
# Cancel reader task
|
|
266
|
-
if self._reader_task:
|
|
267
|
-
self._reader_task.cancel()
|
|
268
|
-
with contextlib.suppress(asyncio.CancelledError):
|
|
269
|
-
await self._reader_task
|
|
230
|
+
await self.dispatch.send_request("initialize", init_params)
|
|
231
|
+
return self
|
|
270
232
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
if not future.done():
|
|
275
|
-
future.set_exception(TransportClosedError("Connection closed"))
|
|
276
|
-
self._pending_requests.clear()
|
|
233
|
+
async def __aexit__(self, *_args: object) -> None:
|
|
234
|
+
"""Async context manager exit - stops the app-server."""
|
|
235
|
+
await self.dispatch.stop()
|
|
277
236
|
|
|
278
237
|
# ========================================================================
|
|
279
238
|
# Thread lifecycle methods
|
|
@@ -323,6 +282,13 @@ class CodexClient:
|
|
|
323
282
|
"""
|
|
324
283
|
from codexed.client.session import Session
|
|
325
284
|
|
|
285
|
+
cfg = merge_config(
|
|
286
|
+
config,
|
|
287
|
+
tools,
|
|
288
|
+
code_mode,
|
|
289
|
+
mcp_servers,
|
|
290
|
+
mcp_elicitation_for_approvals=self._mcp_elicitation_for_approvals,
|
|
291
|
+
)
|
|
326
292
|
params = ThreadStartParams(
|
|
327
293
|
cwd=cwd,
|
|
328
294
|
model=model,
|
|
@@ -331,18 +297,12 @@ class CodexClient:
|
|
|
331
297
|
developer_instructions=developer_instructions,
|
|
332
298
|
approval_policy=approval_policy,
|
|
333
299
|
sandbox=sandbox,
|
|
334
|
-
config=
|
|
335
|
-
config,
|
|
336
|
-
tools,
|
|
337
|
-
code_mode,
|
|
338
|
-
mcp_servers,
|
|
339
|
-
mcp_elicitation_for_approvals=self._mcp_elicitation_for_approvals,
|
|
340
|
-
),
|
|
300
|
+
config=cfg,
|
|
341
301
|
service_name=service_name,
|
|
342
302
|
personality=personality,
|
|
343
303
|
ephemeral=ephemeral,
|
|
344
304
|
)
|
|
345
|
-
result = await self.
|
|
305
|
+
result = await self.dispatch.send_request("thread/start", params)
|
|
346
306
|
response = ThreadResponse.model_validate(result)
|
|
347
307
|
self._active_threads.add(response.thread.id)
|
|
348
308
|
return Session(self, response)
|
|
@@ -408,7 +368,7 @@ class CodexClient:
|
|
|
408
368
|
config=cfg,
|
|
409
369
|
personality=personality,
|
|
410
370
|
)
|
|
411
|
-
result = await self.
|
|
371
|
+
result = await self.dispatch.send_request("thread/resume", params)
|
|
412
372
|
response = ThreadResponse.model_validate(result)
|
|
413
373
|
self._active_threads.add(response.thread.id)
|
|
414
374
|
return Session(self, response)
|
|
@@ -476,7 +436,7 @@ class CodexClient:
|
|
|
476
436
|
config=cfg,
|
|
477
437
|
personality=personality,
|
|
478
438
|
)
|
|
479
|
-
result = await self.
|
|
439
|
+
result = await self.dispatch.send_request("thread/fork", params)
|
|
480
440
|
response = ThreadResponse.model_validate(result)
|
|
481
441
|
self._active_threads.add(response.thread.id)
|
|
482
442
|
session = Session(self, response)
|
|
@@ -521,7 +481,7 @@ class CodexClient:
|
|
|
521
481
|
cwd=cwd,
|
|
522
482
|
search_term=search_term,
|
|
523
483
|
)
|
|
524
|
-
result = await self.
|
|
484
|
+
result = await self.dispatch.send_request("thread/list", params)
|
|
525
485
|
return ThreadListResponse.model_validate(result)
|
|
526
486
|
|
|
527
487
|
async def thread_read(
|
|
@@ -529,12 +489,12 @@ class CodexClient:
|
|
|
529
489
|
) -> ThreadReadResponse:
|
|
530
490
|
"""Read a thread's data."""
|
|
531
491
|
params = ThreadReadParams(thread_id=thread_id, include_turns=include_turns)
|
|
532
|
-
result = await self.
|
|
492
|
+
result = await self.dispatch.send_request("thread/read", params)
|
|
533
493
|
return ThreadReadResponse.model_validate(result)
|
|
534
494
|
|
|
535
495
|
async def thread_loaded_list(self) -> list[str]:
|
|
536
496
|
"""List thread IDs currently loaded in memory."""
|
|
537
|
-
result = await self.
|
|
497
|
+
result = await self.dispatch.send_request("thread/loaded/list")
|
|
538
498
|
response = ThreadLoadedListResponse.model_validate(result)
|
|
539
499
|
return response.data
|
|
540
500
|
|
|
@@ -548,30 +508,30 @@ class CodexClient:
|
|
|
548
508
|
ThreadUnsubscribeResponse with status (notLoaded/notSubscribed/unsubscribed)
|
|
549
509
|
"""
|
|
550
510
|
params = ThreadUnsubscribeParams(thread_id=thread_id)
|
|
551
|
-
result = await self.
|
|
511
|
+
result = await self.dispatch.send_request("thread/unsubscribe", params)
|
|
552
512
|
return ThreadUnsubscribeResponse.model_validate(result)
|
|
553
513
|
|
|
554
514
|
async def thread_archive(self, thread_id: str) -> None:
|
|
555
515
|
"""Archive a thread (move to archived directory)."""
|
|
556
516
|
params = ThreadArchiveParams(thread_id=thread_id)
|
|
557
|
-
await self.
|
|
517
|
+
await self.dispatch.send_request("thread/archive", params)
|
|
558
518
|
self._active_threads.discard(thread_id)
|
|
559
519
|
|
|
560
520
|
async def thread_unarchive(self, thread_id: str) -> ThreadUnarchiveResponse:
|
|
561
521
|
"""Unarchive a previously archived thread. Returns unarchived thread data."""
|
|
562
522
|
params = ThreadUnarchiveParams(thread_id=thread_id)
|
|
563
|
-
result = await self.
|
|
523
|
+
result = await self.dispatch.send_request("thread/unarchive", params)
|
|
564
524
|
return ThreadUnarchiveResponse.model_validate(result)
|
|
565
525
|
|
|
566
526
|
async def thread_set_name(self, thread_id: str, name: str) -> None:
|
|
567
527
|
"""Set a user-facing name for a thread."""
|
|
568
528
|
params = ThreadSetNameParams(thread_id=thread_id, name=name)
|
|
569
|
-
await self.
|
|
529
|
+
await self.dispatch.send_request("thread/name/set", params)
|
|
570
530
|
|
|
571
531
|
async def thread_compact_start(self, thread_id: str) -> None:
|
|
572
532
|
"""Trigger context compaction for a thread."""
|
|
573
533
|
params = ThreadCompactStartParams(thread_id=thread_id)
|
|
574
|
-
await self.
|
|
534
|
+
await self.dispatch.send_request("thread/compact/start", params)
|
|
575
535
|
|
|
576
536
|
async def thread_rollback(self, thread_id: str, turns: int) -> ThreadRollbackResponse:
|
|
577
537
|
"""Rollback the last N turns from a thread.
|
|
@@ -584,7 +544,7 @@ class CodexClient:
|
|
|
584
544
|
Updated thread object with turns populated
|
|
585
545
|
"""
|
|
586
546
|
params = ThreadRollbackParams(thread_id=thread_id, turns=turns)
|
|
587
|
-
result = await self.
|
|
547
|
+
result = await self.dispatch.send_request("thread/rollback", params)
|
|
588
548
|
return ThreadRollbackResponse.model_validate(result)
|
|
589
549
|
|
|
590
550
|
async def thread_rollback_to_turn(self, thread_id: str, turn_id: str) -> ThreadRollbackResponse:
|
|
@@ -624,7 +584,7 @@ class CodexClient:
|
|
|
624
584
|
command: Shell command to execute.
|
|
625
585
|
"""
|
|
626
586
|
params = ThreadShellCommandParams(thread_id=thread_id, command=command)
|
|
627
|
-
await self.
|
|
587
|
+
await self.dispatch.send_request("thread/shellCommand", params)
|
|
628
588
|
|
|
629
589
|
# ========================================================================
|
|
630
590
|
# Turn methods
|
|
@@ -699,7 +659,7 @@ class CodexClient:
|
|
|
699
659
|
collaboration_mode=collaboration_mode,
|
|
700
660
|
)
|
|
701
661
|
# Start turn (non-blocking request)
|
|
702
|
-
turn_result = await self.
|
|
662
|
+
turn_result = await self.dispatch.send_request("turn/start", params)
|
|
703
663
|
response = TurnStartResponse.model_validate(turn_result)
|
|
704
664
|
turn_id = response.turn.id
|
|
705
665
|
# Create per-turn event queue for proper routing
|
|
@@ -746,13 +706,13 @@ class CodexClient:
|
|
|
746
706
|
input=[UserInputText(text=user_input)] if isinstance(user_input, str) else user_input,
|
|
747
707
|
expected_turn_id=expected_turn_id,
|
|
748
708
|
)
|
|
749
|
-
result = await self.
|
|
709
|
+
result = await self.dispatch.send_request("turn/steer", params)
|
|
750
710
|
return TurnSteerResponse.model_validate(result)
|
|
751
711
|
|
|
752
712
|
async def turn_interrupt(self, thread_id: str, turn_id: str) -> None:
|
|
753
713
|
"""Interrupt a running turn."""
|
|
754
714
|
params = TurnInterruptParams(thread_id=thread_id, turn_id=turn_id)
|
|
755
|
-
await self.
|
|
715
|
+
await self.dispatch.send_request("turn/interrupt", params)
|
|
756
716
|
|
|
757
717
|
async def turn_stream_structured[ResultType: BaseModel](
|
|
758
718
|
self,
|
|
@@ -846,7 +806,7 @@ class CodexClient:
|
|
|
846
806
|
ReviewStartResponse with turn and review thread ID
|
|
847
807
|
"""
|
|
848
808
|
params = ReviewStartParams(thread_id=thread_id, target=target, delivery=delivery)
|
|
849
|
-
result = await self.
|
|
809
|
+
result = await self.dispatch.send_request("review/start", params)
|
|
850
810
|
return ReviewStartResponse.model_validate(result)
|
|
851
811
|
|
|
852
812
|
# ========================================================================
|
|
@@ -869,7 +829,7 @@ class CodexClient:
|
|
|
869
829
|
List of skills with metadata
|
|
870
830
|
"""
|
|
871
831
|
params = SkillsListParams(cwds=cwds, force_reload=force_reload)
|
|
872
|
-
result = await self.
|
|
832
|
+
result = await self.dispatch.send_request("skills/list", params)
|
|
873
833
|
response = SkillsListResponse.model_validate(result)
|
|
874
834
|
# Return skills from first container (usually only one)
|
|
875
835
|
if response.data:
|
|
@@ -884,7 +844,7 @@ class CodexClient:
|
|
|
884
844
|
enabled: Whether the skill is enabled
|
|
885
845
|
"""
|
|
886
846
|
params = SkillsConfigWriteParams(path=path, enabled=enabled)
|
|
887
|
-
await self.
|
|
847
|
+
await self.dispatch.send_request("skills/config/write", params)
|
|
888
848
|
|
|
889
849
|
async def skills_remote_list(
|
|
890
850
|
self,
|
|
@@ -908,7 +868,7 @@ class CodexClient:
|
|
|
908
868
|
product_surface=product_surface,
|
|
909
869
|
enabled=enabled,
|
|
910
870
|
)
|
|
911
|
-
result = await self.
|
|
871
|
+
result = await self.dispatch.send_request("skills/remote/list", params)
|
|
912
872
|
response = SkillsRemoteListResponse.model_validate(result)
|
|
913
873
|
return response.data
|
|
914
874
|
|
|
@@ -922,7 +882,7 @@ class CodexClient:
|
|
|
922
882
|
SkillsRemoteExportResponse with id and local path
|
|
923
883
|
"""
|
|
924
884
|
params = SkillsRemoteExportParams(hazelnut_id=hazelnut_id)
|
|
925
|
-
result = await self.
|
|
885
|
+
result = await self.dispatch.send_request("skills/remote/export", params)
|
|
926
886
|
return SkillsRemoteExportResponse.model_validate(result)
|
|
927
887
|
|
|
928
888
|
# ========================================================================
|
|
@@ -939,7 +899,7 @@ class CodexClient:
|
|
|
939
899
|
List of available models
|
|
940
900
|
"""
|
|
941
901
|
params = ModelListParams(include_hidden=include_hidden)
|
|
942
|
-
result = await self.
|
|
902
|
+
result = await self.dispatch.send_request("model/list", params)
|
|
943
903
|
response = ModelListResponse.model_validate(result)
|
|
944
904
|
return response.data
|
|
945
905
|
|
|
@@ -949,7 +909,7 @@ class CodexClient:
|
|
|
949
909
|
Returns:
|
|
950
910
|
List of collaboration mode presets with name, mode, model, and effort
|
|
951
911
|
"""
|
|
952
|
-
result = await self.
|
|
912
|
+
result = await self.dispatch.send_request("collaborationMode/list")
|
|
953
913
|
response = CollaborationModeListResponse.model_validate(result)
|
|
954
914
|
return response.data
|
|
955
915
|
|
|
@@ -982,7 +942,7 @@ class CodexClient:
|
|
|
982
942
|
sandbox_policy=sandbox_policy,
|
|
983
943
|
timeout_ms=timeout_ms,
|
|
984
944
|
)
|
|
985
|
-
result = await self.
|
|
945
|
+
result = await self.dispatch.send_request("command/exec", params)
|
|
986
946
|
return CommandExecResponse.model_validate(result)
|
|
987
947
|
|
|
988
948
|
# ========================================================================
|
|
@@ -995,7 +955,7 @@ class CodexClient:
|
|
|
995
955
|
Triggers all threads to rebuild their MCP connections on the next turn
|
|
996
956
|
using the latest config file.
|
|
997
957
|
"""
|
|
998
|
-
await self.
|
|
958
|
+
await self.dispatch.send_request("config/mcpServer/reload")
|
|
999
959
|
|
|
1000
960
|
async def mcp_server_status_list(
|
|
1001
961
|
self,
|
|
@@ -1013,7 +973,7 @@ class CodexClient:
|
|
|
1013
973
|
Response with server status entries and optional next_cursor
|
|
1014
974
|
"""
|
|
1015
975
|
params = ListMcpServerStatusParams(cursor=cursor, limit=limit)
|
|
1016
|
-
result = await self.
|
|
976
|
+
result = await self.dispatch.send_request("mcpServerStatus/list", params)
|
|
1017
977
|
return ListMcpServerStatusResponse.model_validate(result)
|
|
1018
978
|
|
|
1019
979
|
async def mcp_server_oauth_login(
|
|
@@ -1034,7 +994,7 @@ class CodexClient:
|
|
|
1034
994
|
Response with authorization URL
|
|
1035
995
|
"""
|
|
1036
996
|
params = McpServerOauthLoginParams(name=name, scopes=scopes, timeout_secs=timeout_secs)
|
|
1037
|
-
result = await self.
|
|
997
|
+
result = await self.dispatch.send_request("mcpServer/oauth/login", params)
|
|
1038
998
|
return McpServerOauthLoginResponse.model_validate(result)
|
|
1039
999
|
|
|
1040
1000
|
# ========================================================================
|
|
@@ -1051,7 +1011,7 @@ class CodexClient:
|
|
|
1051
1011
|
GetAccountResponse with account info
|
|
1052
1012
|
"""
|
|
1053
1013
|
params = GetAccountParams(refresh_token=refresh_token)
|
|
1054
|
-
result = await self.
|
|
1014
|
+
result = await self.dispatch.send_request("account/read", params)
|
|
1055
1015
|
return GetAccountResponse.model_validate(result)
|
|
1056
1016
|
|
|
1057
1017
|
async def account_login_start(
|
|
@@ -1079,22 +1039,22 @@ class CodexClient:
|
|
|
1079
1039
|
access_token=access_token,
|
|
1080
1040
|
chatgpt_account_id=chatgpt_account_id,
|
|
1081
1041
|
)
|
|
1082
|
-
result = await self.
|
|
1042
|
+
result = await self.dispatch.send_request("account/login/start", params)
|
|
1083
1043
|
return LoginAccountResponse.model_validate(result)
|
|
1084
1044
|
|
|
1085
1045
|
async def account_login_cancel(self, login_id: str) -> CancelLoginAccountResponse:
|
|
1086
1046
|
"""Cancel an in-progress account login."""
|
|
1087
1047
|
params = CancelLoginAccountParams(login_id=login_id)
|
|
1088
|
-
result = await self.
|
|
1048
|
+
result = await self.dispatch.send_request("account/login/cancel", params)
|
|
1089
1049
|
return CancelLoginAccountResponse.model_validate(result)
|
|
1090
1050
|
|
|
1091
1051
|
async def account_logout(self) -> None:
|
|
1092
1052
|
"""Logout from the current account."""
|
|
1093
|
-
await self.
|
|
1053
|
+
await self.dispatch.send_request("account/logout")
|
|
1094
1054
|
|
|
1095
1055
|
async def account_rate_limits_read(self) -> GetAccountRateLimitsResponse:
|
|
1096
1056
|
"""Read account rate limits."""
|
|
1097
|
-
result = await self.
|
|
1057
|
+
result = await self.dispatch.send_request("account/rateLimits/read")
|
|
1098
1058
|
return GetAccountRateLimitsResponse.model_validate(result)
|
|
1099
1059
|
|
|
1100
1060
|
# ========================================================================
|
|
@@ -1117,7 +1077,7 @@ class CodexClient:
|
|
|
1117
1077
|
ConfigReadResponse with config data
|
|
1118
1078
|
"""
|
|
1119
1079
|
params = ConfigReadParams(include_layers=include_layers, cwd=cwd)
|
|
1120
|
-
result = await self.
|
|
1080
|
+
result = await self.dispatch.send_request("config/read", params)
|
|
1121
1081
|
return ConfigReadResponse.model_validate(result)
|
|
1122
1082
|
|
|
1123
1083
|
async def config_value_write(
|
|
@@ -1148,7 +1108,7 @@ class CodexClient:
|
|
|
1148
1108
|
file_path=file_path,
|
|
1149
1109
|
expected_version=expected_version,
|
|
1150
1110
|
)
|
|
1151
|
-
result = await self.
|
|
1111
|
+
result = await self.dispatch.send_request("config/value/write", params)
|
|
1152
1112
|
return ConfigWriteResponse.model_validate(result)
|
|
1153
1113
|
|
|
1154
1114
|
async def config_batch_write(
|
|
@@ -1173,12 +1133,12 @@ class CodexClient:
|
|
|
1173
1133
|
file_path=file_path,
|
|
1174
1134
|
expected_version=expected_version,
|
|
1175
1135
|
)
|
|
1176
|
-
result = await self.
|
|
1136
|
+
result = await self.dispatch.send_request("config/batchWrite", params)
|
|
1177
1137
|
return ConfigWriteResponse.model_validate(result)
|
|
1178
1138
|
|
|
1179
1139
|
async def config_requirements_read(self) -> ConfigRequirementsReadResponse:
|
|
1180
1140
|
"""Read config requirements."""
|
|
1181
|
-
result = await self.
|
|
1141
|
+
result = await self.dispatch.send_request("configRequirements/read")
|
|
1182
1142
|
return ConfigRequirementsReadResponse.model_validate(result)
|
|
1183
1143
|
|
|
1184
1144
|
# ========================================================================
|
|
@@ -1210,7 +1170,7 @@ class CodexClient:
|
|
|
1210
1170
|
thread_id=thread_id,
|
|
1211
1171
|
force_refetch=force_refetch,
|
|
1212
1172
|
)
|
|
1213
|
-
result = await self.
|
|
1173
|
+
result = await self.dispatch.send_request("app/list", params)
|
|
1214
1174
|
response = AppsListResponse.model_validate(result)
|
|
1215
1175
|
return response.data
|
|
1216
1176
|
|
|
@@ -1234,7 +1194,7 @@ class CodexClient:
|
|
|
1234
1194
|
List of ExperimentalFeature objects
|
|
1235
1195
|
"""
|
|
1236
1196
|
params = ExperimentalFeatureListParams(cursor=cursor, limit=limit)
|
|
1237
|
-
result = await self.
|
|
1197
|
+
result = await self.dispatch.send_request("experimentalFeature/list", params)
|
|
1238
1198
|
response = ExperimentalFeatureListResponse.model_validate(result)
|
|
1239
1199
|
return response.data
|
|
1240
1200
|
|
|
@@ -1270,7 +1230,7 @@ class CodexClient:
|
|
|
1270
1230
|
include_logs=include_logs,
|
|
1271
1231
|
extra_log_files=extra_log_files,
|
|
1272
1232
|
)
|
|
1273
|
-
result = await self.
|
|
1233
|
+
result = await self.dispatch.send_request("feedback/upload", params)
|
|
1274
1234
|
return FeedbackUploadResponse.model_validate(result)
|
|
1275
1235
|
|
|
1276
1236
|
# ========================================================================
|
|
@@ -1293,7 +1253,7 @@ class CodexClient:
|
|
|
1293
1253
|
ExternalAgentConfigDetectResponse with migration items
|
|
1294
1254
|
"""
|
|
1295
1255
|
params = ExternalAgentConfigDetectParams(include_home=include_home, cwds=cwds)
|
|
1296
|
-
result = await self.
|
|
1256
|
+
result = await self.dispatch.send_request("externalAgentConfig/detect", params)
|
|
1297
1257
|
return ExternalAgentConfigDetectResponse.model_validate(result)
|
|
1298
1258
|
|
|
1299
1259
|
async def external_agent_config_import(
|
|
@@ -1306,178 +1266,60 @@ class CodexClient:
|
|
|
1306
1266
|
migration_items: List of migration items to import
|
|
1307
1267
|
"""
|
|
1308
1268
|
params = ExternalAgentConfigImportParams(migration_items=migration_items)
|
|
1309
|
-
await self.
|
|
1269
|
+
await self.dispatch.send_request("externalAgentConfig/import", params)
|
|
1310
1270
|
|
|
1311
1271
|
# ========================================================================
|
|
1312
|
-
# Internal
|
|
1272
|
+
# Internal: JSON-RPC dispatch callbacks
|
|
1313
1273
|
# ========================================================================
|
|
1314
1274
|
|
|
1315
|
-
async def
|
|
1316
|
-
"""
|
|
1317
|
-
|
|
1318
|
-
Args:
|
|
1319
|
-
method: JSON-RPC method name
|
|
1320
|
-
params: Pydantic model with request parameters (will be serialized)
|
|
1321
|
-
|
|
1322
|
-
Returns:
|
|
1323
|
-
Response result (not yet validated - caller should validate)
|
|
1324
|
-
"""
|
|
1325
|
-
if not self._transport.is_connected:
|
|
1326
|
-
raise TransportClosedError("Not connected to Codex app-server")
|
|
1327
|
-
|
|
1328
|
-
request_id = self._request_id
|
|
1329
|
-
self._request_id += 1
|
|
1330
|
-
future: asyncio.Future[Any] = asyncio.Future()
|
|
1331
|
-
self._pending_requests[request_id] = future
|
|
1332
|
-
# Serialize params to dict if provided
|
|
1333
|
-
params_dict = params.model_dump(by_alias=True, exclude_none=True) if params else {}
|
|
1334
|
-
request = JsonRpcRequest(id=request_id, method=method, params=params_dict)
|
|
1335
|
-
try:
|
|
1336
|
-
message = request.model_dump(mode="json", by_alias=True, exclude_none=True)
|
|
1337
|
-
await self._transport.send(message)
|
|
1338
|
-
except Exception as exc:
|
|
1339
|
-
del self._pending_requests[request_id]
|
|
1340
|
-
raise CodexProcessError(f"Failed to send request: {exc}") from exc
|
|
1341
|
-
|
|
1342
|
-
return await future
|
|
1343
|
-
|
|
1344
|
-
async def _read_loop(self) -> None:
|
|
1345
|
-
"""Read messages from the transport."""
|
|
1346
|
-
try:
|
|
1347
|
-
while True:
|
|
1348
|
-
message = await self._transport.receive()
|
|
1349
|
-
if message is None:
|
|
1350
|
-
break
|
|
1351
|
-
try:
|
|
1352
|
-
await self._process_message(message)
|
|
1353
|
-
except Exception:
|
|
1354
|
-
logger.exception("Error processing message")
|
|
1355
|
-
|
|
1356
|
-
except asyncio.CancelledError:
|
|
1357
|
-
pass
|
|
1358
|
-
except Exception:
|
|
1359
|
-
logger.exception("Reader loop failed")
|
|
1360
|
-
finally:
|
|
1361
|
-
await self._event_queue.put(None)
|
|
1362
|
-
|
|
1363
|
-
async def _process_message(self, message: dict[str, Any]) -> None:
|
|
1364
|
-
"""Process a message from the app-server.
|
|
1365
|
-
|
|
1366
|
-
Messages are one of:
|
|
1367
|
-
- Server request: has both "method" and "id" -> needs a response
|
|
1368
|
-
- Response to our request: has "id" but no "method" -> resolves pending future
|
|
1369
|
-
- Notification: has "method" but no "id" -> routed as event
|
|
1370
|
-
|
|
1371
|
-
Args:
|
|
1372
|
-
message: Raw JSON-RPC message
|
|
1373
|
-
"""
|
|
1374
|
-
match message:
|
|
1375
|
-
case {"method": _, "id": _}: # Server request - the server is asking us to do something
|
|
1376
|
-
await self._handle_server_request(message)
|
|
1377
|
-
case {"id": _}: # Response to one of our requests
|
|
1378
|
-
self._handle_response(message)
|
|
1379
|
-
case {"method": _}: # Notification - one-way event
|
|
1380
|
-
await self._handle_notification(message)
|
|
1381
|
-
case _:
|
|
1382
|
-
raise TypeError(f"Unknown message shape {message}")
|
|
1383
|
-
|
|
1384
|
-
def _handle_response(self, message: dict[str, Any]) -> None:
|
|
1385
|
-
"""Handle a JSON-RPC response to one of our pending requests."""
|
|
1386
|
-
msg_id = message["id"]
|
|
1387
|
-
try:
|
|
1388
|
-
response = JsonRpcResponse.model_validate(message)
|
|
1389
|
-
future = self._pending_requests.pop(response.id, None)
|
|
1390
|
-
if future and not future.done():
|
|
1391
|
-
if err := response.error:
|
|
1392
|
-
future.set_exception(map_jsonrpc_error(err.code, err.message, err.data))
|
|
1393
|
-
else:
|
|
1394
|
-
future.set_result(response.result)
|
|
1395
|
-
except Exception as exc: # noqa: BLE001
|
|
1396
|
-
logger.warning("Failed to parse response: %s", exc)
|
|
1397
|
-
if isinstance(msg_id, int):
|
|
1398
|
-
future = self._pending_requests.pop(msg_id, None)
|
|
1399
|
-
if future and not future.done():
|
|
1400
|
-
future.set_result(message.get("result"))
|
|
1401
|
-
|
|
1402
|
-
async def _handle_notification(self, message: dict[str, Any]) -> None:
|
|
1403
|
-
"""Handle a JSON-RPC notification (one-way event)."""
|
|
1404
|
-
method = message["method"]
|
|
1405
|
-
params = message.get("params") or {}
|
|
1406
|
-
|
|
1275
|
+
async def _handle_notification(self, method: str, params: dict[str, Any]) -> None:
|
|
1276
|
+
"""Route a JSON-RPC notification to the appropriate event queue."""
|
|
1407
1277
|
if method.startswith("codex/event/"):
|
|
1408
1278
|
return
|
|
1409
1279
|
|
|
1410
|
-
event_data = {"event_type": method, "data": params
|
|
1411
|
-
event = codex_event_adapter.validate_python(event_data)
|
|
1412
|
-
|
|
1280
|
+
event_data = {"event_type": method, "data": params}
|
|
1281
|
+
event: CodexEvent = codex_event_adapter.validate_python(event_data)
|
|
1282
|
+
|
|
1413
1283
|
thread_id = params.get("threadId")
|
|
1414
1284
|
turn_id = params.get("turnId")
|
|
1415
|
-
# Also check nested turn object (some events have it there)
|
|
1416
1285
|
if not turn_id and "turn" in params:
|
|
1417
|
-
|
|
1418
|
-
turn_id = turn_data.get("id")
|
|
1286
|
+
turn_id = params.get("turn", {}).get("id")
|
|
1419
1287
|
|
|
1420
1288
|
if thread_id and turn_id:
|
|
1421
|
-
# Turn-specific event - route to turn queue
|
|
1422
1289
|
turn_key = f"{thread_id}:{turn_id}"
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
else:
|
|
1426
|
-
# Turn queue not found (might be old event) - put in global queue
|
|
1427
|
-
await self._event_queue.put(event)
|
|
1290
|
+
queue = self._turn_queues.get(turn_key)
|
|
1291
|
+
await (queue or self._event_queue).put(event)
|
|
1428
1292
|
else:
|
|
1429
|
-
# Global event (account, MCP, etc.) - put in global queue
|
|
1430
1293
|
await self._event_queue.put(event)
|
|
1431
1294
|
|
|
1432
|
-
async def _handle_server_request(
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
params = message.get("params") or {}
|
|
1437
|
-
|
|
1295
|
+
async def _handle_server_request(
|
|
1296
|
+
self, method: str, request_id: int | str, params: dict[str, Any]
|
|
1297
|
+
) -> None:
|
|
1298
|
+
"""Handle a server-initiated JSON-RPC request."""
|
|
1438
1299
|
type_entry = SERVER_REQUEST_TYPES.get(method)
|
|
1439
1300
|
if type_entry is None:
|
|
1440
1301
|
logger.warning("Unhandled server request method: %s (id=%s)", method, request_id)
|
|
1441
|
-
await self.
|
|
1302
|
+
await self.dispatch.send_error(request_id, -32601, f"Method not found: {method}")
|
|
1442
1303
|
return
|
|
1443
1304
|
|
|
1444
|
-
params_type, _ = type_entry
|
|
1445
1305
|
handler = self._server_request_handlers.get(method)
|
|
1446
1306
|
if handler is None:
|
|
1447
1307
|
logger.warning("No handler registered for request: %s (id=%s)", method, request_id)
|
|
1448
|
-
await self.
|
|
1308
|
+
await self.dispatch.send_error(request_id, -32603, f"No handler for: {method}")
|
|
1449
1309
|
return
|
|
1450
1310
|
|
|
1311
|
+
params_type, _ = type_entry
|
|
1451
1312
|
try:
|
|
1452
1313
|
if isinstance(params_type, TypeAdapter):
|
|
1453
1314
|
parsed_params = params_type.validate_python(params)
|
|
1454
1315
|
else:
|
|
1455
1316
|
parsed_params = params_type.model_validate(params)
|
|
1456
1317
|
response_model = await handler(parsed_params)
|
|
1457
|
-
|
|
1318
|
+
result = response_model.model_dump(by_alias=True, exclude_none=True)
|
|
1319
|
+
await self.dispatch.send_response(request_id, result)
|
|
1458
1320
|
except Exception:
|
|
1459
1321
|
logger.exception("Error handling server request %s (id=%s)", method, request_id)
|
|
1460
|
-
await self.
|
|
1461
|
-
request_id, -32603, f"Internal error handling {method}"
|
|
1462
|
-
)
|
|
1463
|
-
|
|
1464
|
-
async def _send_server_request_response(self, request_id: int | str, result: BaseModel) -> None:
|
|
1465
|
-
"""Send a JSON-RPC response to a server request."""
|
|
1466
|
-
dct = result.model_dump(by_alias=True, exclude_none=True)
|
|
1467
|
-
response = {"jsonrpc": "2.0", "id": request_id, "result": dct}
|
|
1468
|
-
await self._write_message(response)
|
|
1469
|
-
|
|
1470
|
-
async def _send_server_request_error(
|
|
1471
|
-
self, request_id: int | str, code: int, message: str
|
|
1472
|
-
) -> None:
|
|
1473
|
-
"""Send a JSON-RPC error response to a server request."""
|
|
1474
|
-
error = {"code": code, "message": message}
|
|
1475
|
-
response = {"jsonrpc": "2.0", "id": request_id, "error": error}
|
|
1476
|
-
await self._write_message(response)
|
|
1477
|
-
|
|
1478
|
-
async def _write_message(self, message: dict[str, Any]) -> None:
|
|
1479
|
-
"""Write a JSON message via the transport."""
|
|
1480
|
-
await self._transport.send(message)
|
|
1322
|
+
await self.dispatch.send_error(request_id, -32603, f"Internal error handling {method}")
|
|
1481
1323
|
|
|
1482
1324
|
# ========================================================================
|
|
1483
1325
|
# Server request handler registration
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Pure JSON-RPC dispatch layer — no Codex domain knowledge."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections.abc import Awaitable, Callable
|
|
7
|
+
import contextlib
|
|
8
|
+
import logging
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
10
|
+
|
|
11
|
+
from codexed.exceptions import CodexProcessError, TransportClosedError, map_jsonrpc_error
|
|
12
|
+
from codexed.models import JsonRpcRequest, JsonRpcResponse
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from pydantic import BaseModel
|
|
17
|
+
|
|
18
|
+
from codexed.transport import Transport
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
NotificationHandler = Callable[[str, dict[str, Any]], Awaitable[None]]
|
|
23
|
+
"""``(method, params) -> None`` — called for every JSON-RPC notification."""
|
|
24
|
+
|
|
25
|
+
ServerRequestHandler = Callable[[str, int | str, dict[str, Any]], Awaitable[None]]
|
|
26
|
+
"""``(method, request_id, params) -> None`` — called for every server request."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Dispatch:
|
|
30
|
+
"""Thin JSON-RPC transport wrapper.
|
|
31
|
+
|
|
32
|
+
Owns the read loop, request/response correlation, and transport lifecycle.
|
|
33
|
+
Notifications and server-initiated requests are forwarded to callbacks
|
|
34
|
+
supplied by the caller.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
transport: Transport,
|
|
40
|
+
*,
|
|
41
|
+
on_notification: NotificationHandler,
|
|
42
|
+
on_server_request: ServerRequestHandler,
|
|
43
|
+
) -> None:
|
|
44
|
+
self._transport = transport
|
|
45
|
+
self._on_notification = on_notification
|
|
46
|
+
self._on_server_request = on_server_request
|
|
47
|
+
self._request_id = 0
|
|
48
|
+
self._pending_requests: dict[int | str, asyncio.Future[Any]] = {}
|
|
49
|
+
self._reader_task: asyncio.Task[None] | None = None
|
|
50
|
+
|
|
51
|
+
async def start(self) -> None:
|
|
52
|
+
"""Start the transport and begin the read loop."""
|
|
53
|
+
if self._transport.is_connected:
|
|
54
|
+
return
|
|
55
|
+
|
|
56
|
+
await self._transport.start()
|
|
57
|
+
self._reader_task = asyncio.create_task(self._read_loop())
|
|
58
|
+
|
|
59
|
+
async def stop(self) -> None:
|
|
60
|
+
"""Stop the transport and clean up resources."""
|
|
61
|
+
if not self._transport.is_connected:
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
if self._reader_task:
|
|
65
|
+
self._reader_task.cancel()
|
|
66
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
67
|
+
await self._reader_task
|
|
68
|
+
|
|
69
|
+
await self._transport.stop()
|
|
70
|
+
for future in self._pending_requests.values():
|
|
71
|
+
if not future.done():
|
|
72
|
+
future.set_exception(TransportClosedError("Connection closed"))
|
|
73
|
+
self._pending_requests.clear()
|
|
74
|
+
|
|
75
|
+
async def send_request(self, method: str, params: BaseModel | None = None) -> Any:
|
|
76
|
+
"""Send a JSON-RPC request and wait for the response."""
|
|
77
|
+
if not self._transport.is_connected:
|
|
78
|
+
raise TransportClosedError("Not connected to Codex app-server")
|
|
79
|
+
|
|
80
|
+
request_id = self._request_id
|
|
81
|
+
self._request_id += 1
|
|
82
|
+
future: asyncio.Future[Any] = asyncio.Future()
|
|
83
|
+
self._pending_requests[request_id] = future
|
|
84
|
+
params_dict = params.model_dump(by_alias=True, exclude_none=True) if params else {}
|
|
85
|
+
request = JsonRpcRequest(id=request_id, method=method, params=params_dict)
|
|
86
|
+
try:
|
|
87
|
+
message = request.model_dump(mode="json", by_alias=True, exclude_none=True)
|
|
88
|
+
await self._transport.send(message)
|
|
89
|
+
except Exception as exc:
|
|
90
|
+
del self._pending_requests[request_id]
|
|
91
|
+
raise CodexProcessError(f"Failed to send request: {exc}") from exc
|
|
92
|
+
|
|
93
|
+
return await future
|
|
94
|
+
|
|
95
|
+
async def send_response(self, request_id: int | str, result: dict[str, Any]) -> None:
|
|
96
|
+
"""Send a JSON-RPC success response to a server request."""
|
|
97
|
+
await self._transport.send({"jsonrpc": "2.0", "id": request_id, "result": result})
|
|
98
|
+
|
|
99
|
+
async def send_error(self, request_id: int | str, code: int, message: str) -> None:
|
|
100
|
+
"""Send a JSON-RPC error response to a server request."""
|
|
101
|
+
error = {"code": code, "message": message}
|
|
102
|
+
await self._transport.send({"jsonrpc": "2.0", "id": request_id, "error": error})
|
|
103
|
+
|
|
104
|
+
# ------------------------------------------------------------------
|
|
105
|
+
# Internal
|
|
106
|
+
# ------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
async def _read_loop(self) -> None:
|
|
109
|
+
try:
|
|
110
|
+
while True:
|
|
111
|
+
message = await self._transport.receive()
|
|
112
|
+
if message is None:
|
|
113
|
+
break
|
|
114
|
+
try:
|
|
115
|
+
await self._process_message(message)
|
|
116
|
+
except Exception:
|
|
117
|
+
logger.exception("Error processing message")
|
|
118
|
+
except asyncio.CancelledError:
|
|
119
|
+
pass
|
|
120
|
+
except Exception:
|
|
121
|
+
logger.exception("Reader loop failed")
|
|
122
|
+
|
|
123
|
+
async def _process_message(self, message: dict[str, Any]) -> None:
|
|
124
|
+
match message:
|
|
125
|
+
case {"method": _, "id": _}:
|
|
126
|
+
await self._on_server_request(
|
|
127
|
+
message["method"], message["id"], message.get("params") or {}
|
|
128
|
+
)
|
|
129
|
+
case {"id": _}:
|
|
130
|
+
self._handle_response(message)
|
|
131
|
+
case {"method": _}:
|
|
132
|
+
await self._on_notification(message["method"], message.get("params") or {})
|
|
133
|
+
case _:
|
|
134
|
+
raise TypeError(f"Unknown message shape {message}")
|
|
135
|
+
|
|
136
|
+
def _handle_response(self, message: dict[str, Any]) -> None:
|
|
137
|
+
msg_id = message["id"]
|
|
138
|
+
try:
|
|
139
|
+
response = JsonRpcResponse.model_validate(message)
|
|
140
|
+
future = self._pending_requests.pop(response.id, None)
|
|
141
|
+
if future and not future.done():
|
|
142
|
+
if err := response.error:
|
|
143
|
+
future.set_exception(map_jsonrpc_error(err.code, err.message, err.data))
|
|
144
|
+
else:
|
|
145
|
+
future.set_result(response.result)
|
|
146
|
+
except Exception as exc: # noqa: BLE001
|
|
147
|
+
logger.warning("Failed to parse response: %s", exc)
|
|
148
|
+
if isinstance(msg_id, int):
|
|
149
|
+
future = self._pending_requests.pop(msg_id, None)
|
|
150
|
+
if future and not future.done():
|
|
151
|
+
future.set_result(message.get("result"))
|
|
@@ -43,7 +43,7 @@ class CodexFS:
|
|
|
43
43
|
FsReadFileResponse with base64-encoded file contents.
|
|
44
44
|
"""
|
|
45
45
|
params = FsReadFileParams(path=path)
|
|
46
|
-
result = await self._client.
|
|
46
|
+
result = await self._client.dispatch.send_request("fs/readFile", params)
|
|
47
47
|
return FsReadFileResponse.model_validate(result)
|
|
48
48
|
|
|
49
49
|
async def write_file(self, path: str, data_base64: str) -> None:
|
|
@@ -54,7 +54,7 @@ class CodexFS:
|
|
|
54
54
|
data_base64: File contents encoded as base64.
|
|
55
55
|
"""
|
|
56
56
|
params = FsWriteFileParams(path=path, data_base64=data_base64)
|
|
57
|
-
await self._client.
|
|
57
|
+
await self._client.dispatch.send_request("fs/writeFile", params)
|
|
58
58
|
|
|
59
59
|
async def create_directory(self, path: str, *, recursive: bool | None = None) -> None:
|
|
60
60
|
"""Create a directory on the host filesystem.
|
|
@@ -64,7 +64,7 @@ class CodexFS:
|
|
|
64
64
|
recursive: Whether to create parent directories. Defaults to True server-side.
|
|
65
65
|
"""
|
|
66
66
|
params = FsCreateDirectoryParams(path=path, recursive=recursive)
|
|
67
|
-
await self._client.
|
|
67
|
+
await self._client.dispatch.send_request("fs/createDirectory", params)
|
|
68
68
|
|
|
69
69
|
async def get_metadata(self, path: str) -> FsGetMetadataResponse:
|
|
70
70
|
"""Get metadata for an absolute path.
|
|
@@ -76,7 +76,7 @@ class CodexFS:
|
|
|
76
76
|
FsGetMetadataResponse with isDirectory, isFile, and timestamps.
|
|
77
77
|
"""
|
|
78
78
|
params = FsGetMetadataParams(path=path)
|
|
79
|
-
result = await self._client.
|
|
79
|
+
result = await self._client.dispatch.send_request("fs/getMetadata", params)
|
|
80
80
|
return FsGetMetadataResponse.model_validate(result)
|
|
81
81
|
|
|
82
82
|
async def read_directory(
|
|
@@ -95,7 +95,7 @@ class CodexFS:
|
|
|
95
95
|
List of directory entries with fileName, isDirectory, isFile.
|
|
96
96
|
"""
|
|
97
97
|
params = FsReadDirectoryParams(path=path)
|
|
98
|
-
result = await self._client.
|
|
98
|
+
result = await self._client.dispatch.send_request("fs/readDirectory", params)
|
|
99
99
|
entries = FsReadDirectoryResponse.model_validate(result).entries
|
|
100
100
|
if not recursive:
|
|
101
101
|
return entries
|
|
@@ -122,7 +122,7 @@ class CodexFS:
|
|
|
122
122
|
force: Whether to ignore missing paths. Defaults to True server-side.
|
|
123
123
|
"""
|
|
124
124
|
params = FsRemoveParams(path=path, recursive=recursive, force=force)
|
|
125
|
-
await self._client.
|
|
125
|
+
await self._client.dispatch.send_request("fs/remove", params)
|
|
126
126
|
|
|
127
127
|
async def copy(self, source: str, destination: str, *, recursive: bool = False) -> None:
|
|
128
128
|
"""Copy a file or directory tree on the host filesystem.
|
|
@@ -133,7 +133,7 @@ class CodexFS:
|
|
|
133
133
|
recursive: Required for directory copies; ignored for file copies.
|
|
134
134
|
"""
|
|
135
135
|
params = FsCopyParams(source_path=source, destination_path=destination, recursive=recursive)
|
|
136
|
-
await self._client.
|
|
136
|
+
await self._client.dispatch.send_request("fs/copy", params)
|
|
137
137
|
|
|
138
138
|
async def watch(self, path: str) -> FsWatchResponse:
|
|
139
139
|
"""Start filesystem watch notifications for an absolute path.
|
|
@@ -145,7 +145,7 @@ class CodexFS:
|
|
|
145
145
|
FsWatchResponse with watch_id and canonicalized path.
|
|
146
146
|
"""
|
|
147
147
|
params = FsWatchParams(path=path)
|
|
148
|
-
result = await self._client.
|
|
148
|
+
result = await self._client.dispatch.send_request("fs/watch", params)
|
|
149
149
|
return FsWatchResponse.model_validate(result)
|
|
150
150
|
|
|
151
151
|
async def unwatch(self, watch_id: str) -> None:
|
|
@@ -155,4 +155,4 @@ class CodexFS:
|
|
|
155
155
|
watch_id: Watch identifier returned by fs_watch.
|
|
156
156
|
"""
|
|
157
157
|
params = FsUnwatchParams(watch_id=watch_id)
|
|
158
|
-
await self._client.
|
|
158
|
+
await self._client.dispatch.send_request("fs/unwatch", params)
|
|
@@ -88,6 +88,7 @@ from codexed.models.event_data import (
|
|
|
88
88
|
ItemStartedData,
|
|
89
89
|
LoginChatGptCompleteData,
|
|
90
90
|
McpServerOAuthLoginCompletedData,
|
|
91
|
+
McpServerStartupStatusUpdatedData,
|
|
91
92
|
McpToolCallProgressData,
|
|
92
93
|
ModelReroutedData,
|
|
93
94
|
PlanDeltaData,
|
|
@@ -199,6 +200,7 @@ from codexed.models.events import (
|
|
|
199
200
|
ItemStartedEvent,
|
|
200
201
|
LoginChatGptCompleteEvent,
|
|
201
202
|
McpServerOAuthLoginCompletedEvent,
|
|
203
|
+
McpServerStartupStatusUpdatedEvent,
|
|
202
204
|
McpToolCallProgressEvent,
|
|
203
205
|
ModelReroutedEvent,
|
|
204
206
|
PlanDeltaEvent,
|
|
@@ -699,6 +701,8 @@ __all__ = [
|
|
|
699
701
|
"McpServerOauthLoginParams",
|
|
700
702
|
"McpServerOauthLoginResponse",
|
|
701
703
|
"McpServerRefreshResponse",
|
|
704
|
+
"McpServerStartupStatusUpdatedData",
|
|
705
|
+
"McpServerStartupStatusUpdatedEvent",
|
|
702
706
|
"McpServerStatusEntry",
|
|
703
707
|
"McpTool",
|
|
704
708
|
"McpToolCallError",
|
|
@@ -28,6 +28,7 @@ ItemType = Literal[
|
|
|
28
28
|
]
|
|
29
29
|
ItemStatus = Literal["pending", "running", "completed", "error"]
|
|
30
30
|
McpElicitationAction = Literal["accept", "decline", "cancel"]
|
|
31
|
+
McpServerStartupState = Literal["starting", "ready", "failed", "cancelled"]
|
|
31
32
|
"""Action taken by the user on an elicitation request."""
|
|
32
33
|
|
|
33
34
|
# New type aliases
|
|
@@ -3,7 +3,7 @@ from __future__ import annotations
|
|
|
3
3
|
from typing import Any
|
|
4
4
|
|
|
5
5
|
from codexed.models.base import CodexBaseModel
|
|
6
|
-
from codexed.models.codex_types import ModelRerouteReason
|
|
6
|
+
from codexed.models.codex_types import McpServerStartupState, ModelRerouteReason
|
|
7
7
|
from codexed.models.misc import (
|
|
8
8
|
AppInfo,
|
|
9
9
|
RateLimitSnapshot,
|
|
@@ -125,6 +125,14 @@ class McpToolCallProgressData(CodexBaseModel):
|
|
|
125
125
|
# MCP/Account/System notifications
|
|
126
126
|
|
|
127
127
|
|
|
128
|
+
class McpServerStartupStatusUpdatedData(CodexBaseModel):
|
|
129
|
+
"""Payload for mcpServer/startupStatus/updated notification."""
|
|
130
|
+
|
|
131
|
+
name: str
|
|
132
|
+
status: McpServerStartupState
|
|
133
|
+
error: str | None = None
|
|
134
|
+
|
|
135
|
+
|
|
128
136
|
class McpServerOAuthLoginCompletedData(CodexBaseModel):
|
|
129
137
|
"""Payload for mcpServer/oauthLogin/completed notification."""
|
|
130
138
|
|
|
@@ -361,6 +369,8 @@ EventData = (
|
|
|
361
369
|
| FileChangeOutputDeltaData
|
|
362
370
|
# Item deltas - MCP tool calls
|
|
363
371
|
| McpToolCallProgressData
|
|
372
|
+
# MCP server status
|
|
373
|
+
| McpServerStartupStatusUpdatedData
|
|
364
374
|
# MCP OAuth
|
|
365
375
|
| McpServerOAuthLoginCompletedData
|
|
366
376
|
# Account/Auth events
|
|
@@ -30,6 +30,7 @@ from codexed.models.event_data import (
|
|
|
30
30
|
ItemStartedData,
|
|
31
31
|
LoginChatGptCompleteData,
|
|
32
32
|
McpServerOAuthLoginCompletedData,
|
|
33
|
+
McpServerStartupStatusUpdatedData,
|
|
33
34
|
McpToolCallProgressData,
|
|
34
35
|
ModelReroutedData,
|
|
35
36
|
PlanDeltaData,
|
|
@@ -412,6 +413,13 @@ class McpToolCallProgressEvent(CodexBaseModel):
|
|
|
412
413
|
# ============================================================================
|
|
413
414
|
|
|
414
415
|
|
|
416
|
+
class McpServerStartupStatusUpdatedEvent(CodexBaseModel):
|
|
417
|
+
"""MCP server startup status updated event."""
|
|
418
|
+
|
|
419
|
+
event_type: Literal["mcpServer/startupStatus/updated"] = "mcpServer/startupStatus/updated"
|
|
420
|
+
data: McpServerStartupStatusUpdatedData
|
|
421
|
+
|
|
422
|
+
|
|
415
423
|
class McpServerOAuthLoginCompletedEvent(CodexBaseModel):
|
|
416
424
|
"""MCP server OAuth login completed event."""
|
|
417
425
|
|
|
@@ -588,6 +596,8 @@ CodexEvent = Annotated[
|
|
|
588
596
|
| FileChangeOutputDeltaEvent
|
|
589
597
|
# Item deltas - MCP tool calls
|
|
590
598
|
| McpToolCallProgressEvent
|
|
599
|
+
# MCP server status
|
|
600
|
+
| McpServerStartupStatusUpdatedEvent
|
|
591
601
|
# MCP OAuth
|
|
592
602
|
| McpServerOAuthLoginCompletedEvent
|
|
593
603
|
# Account/Auth events
|
|
@@ -671,6 +681,8 @@ EventType = Literal[
|
|
|
671
681
|
"item/fileChange/outputDelta",
|
|
672
682
|
# Item deltas - MCP tool calls
|
|
673
683
|
"item/mcpToolCall/progress",
|
|
684
|
+
# MCP server status
|
|
685
|
+
"mcpServer/startupStatus/updated",
|
|
674
686
|
# MCP OAuth
|
|
675
687
|
"mcpServer/oauthLogin/completed",
|
|
676
688
|
# Account/Auth events
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|