-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodex_service.py
More file actions
2064 lines (1963 loc) · 79.7 KB
/
Copy pathcodex_service.py
File metadata and controls
2064 lines (1963 loc) · 79.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Codex application service with project authorization and Turn orchestration."""
from __future__ import annotations
import asyncio
import json
import time
import uuid
from collections.abc import Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from typing import Any
from openai_codex import ApprovalMode, AsyncThread, LocalImageInput, Sandbox, TextInput
from openai_codex.errors import InvalidParamsError, InvalidRequestError
from openai_codex.generated.v2_all import ThreadDeleteParams, ThreadDeleteResponse, SkillsListParams, SkillsListResponse
from starlette.concurrency import run_in_threadpool
from codex_goal_adapter import CodexGoalAdapter
from codex_serializers import field, notification_view, thread_view, to_primitive
from conversation_attachments import REFERENCE_MARKER, ConversationAttachmentStore
from event_hub import EventEnvelope, EventHub, Subscription
from projects import Project, ProjectRegistry, UnknownProjectError
from stream_journal import (
StreamJournal,
complete_stream_turn_ids,
history_watermark,
materialize_timeline,
normalize_event,
)
from turn_manager import (
TurnConflictError,
TurnManager,
TurnNotActiveError,
TurnsUnavailableError,
)
from utility.log import LOGD, LOGW
SESSION_TITLE_MODEL = "gpt-5.6-luna"
SESSION_TITLE_REASONING_EFFORT = "low"
_SESSION_TITLE_DEVELOPER_INSTRUCTIONS = """
Create a concise session title that summarizes the user's first message.
Use the same language as the user. Return only the requested structured output.
The title must be specific, contain no quotation marks or terminal punctuation,
and be no longer than 80 characters.
""".strip()
_SESSION_TITLE_OUTPUT_SCHEMA = {
"type": "object",
"properties": {
"title": {"type": "string", "minLength": 1, "maxLength": 80},
},
"required": ["title"],
"additionalProperties": False,
}
def _is_unmaterialized_thread_error(exc: BaseException) -> bool:
"""Return whether Codex rejected turns for a new, empty thread."""
if not isinstance(exc, InvalidRequestError) or exc.code != -32600:
return False
message = exc.message.lower()
return "not materialized yet" in message and "includeturns" in message
def _is_thread_not_loaded_error(exc: BaseException) -> bool:
"""Return whether Codex can no longer read a deleted thread handle."""
if not isinstance(exc, InvalidRequestError) or exc.code != -32600:
return False
return "thread not loaded" in exc.message.lower()
def _is_stale_turn_interrupt_error(exc: BaseException | None) -> bool:
"""Return whether Codex rejected an interrupt for an obsolete handle."""
if not isinstance(exc, InvalidRequestError) or exc.code != -32600:
return False
message = exc.message.lower()
return (
"expected active turn id" in message
or "no active turn to interrupt" in message
)
class ConsoleServiceError(RuntimeError):
status_code = 500
code = "console_error"
safe_message = "The console could not complete the request."
class ConsoleBadRequest(ConsoleServiceError):
status_code = 400
code = "invalid_request"
safe_message = "The request is not valid."
class ConsoleNotFound(ConsoleServiceError):
status_code = 404
code = "not_found"
safe_message = "The requested project or session was not found."
class ConsoleConflict(ConsoleServiceError):
status_code = 409
code = "active_turn_conflict"
safe_message = "The session state does not allow this operation."
class ConsoleProjectExists(ConsoleServiceError):
status_code = 409
code = "project_exists"
safe_message = "A project with this directory name already exists."
class ConsoleProjectUnavailable(ConsoleServiceError):
status_code = 503
code = "project_root_unavailable"
safe_message = "The configured project root is not available."
class ConsoleUnavailable(ConsoleServiceError):
status_code = 503
code = "codex_unavailable"
safe_message = "Codex is temporarily unavailable."
class ConsoleTimeout(ConsoleServiceError):
status_code = 504
code = "codex_timeout"
safe_message = "Codex did not respond before the operation timed out."
class ConsoleSubmissionUncertain(ConsoleServiceError):
status_code = 503
code = "attachment_submission_uncertain"
safe_message = "Codex may have accepted this message. Reopen the session to check its history before sending again."
@dataclass(slots=True)
class _PendingThread:
"""Server-created thread not yet discoverable through Codex thread/list."""
project: Project
handle: Any
view: dict[str, Any]
archived: bool = False
class CodexService:
def __init__(
self,
codex: Any,
*,
registry: ProjectRegistry,
event_hub: EventHub,
turn_manager: TurnManager,
approval_mode: ApprovalMode,
sandbox: Sandbox,
stream_journal: StreamJournal | None = None,
goal_adapter: Any | None = None,
operation_timeout: float = 30,
turn_idle_reconcile_seconds: float = 2,
lookup_page_limit: int = 50,
tenant_id: str | None = None,
on_thread_authorized: Callable[[str], None] | None = None,
) -> None:
self.codex = codex
self.registry = registry
self.event_hub = event_hub
self.turn_manager = turn_manager
self.approval_mode = approval_mode
self.sandbox = sandbox
self.stream_journal = stream_journal or StreamJournal()
self.goal_adapter = goal_adapter or CodexGoalAdapter(codex)
self.operation_timeout = operation_timeout
self.turn_idle_reconcile_seconds = max(0.01, turn_idle_reconcile_seconds)
self.lookup_page_limit = lookup_page_limit
self.tenant_id = tenant_id
self._on_thread_authorized = on_thread_authorized
self._pending_threads: dict[str, _PendingThread] = {}
self._thread_projects: dict[str, Project] = {}
self._mutating_projects: set[str] = set()
self._publish_lock = asyncio.Lock()
self._recent_stream_fingerprints: dict[str, tuple[str, float]] = {}
self._ignored_notification_threads: set[str] = set()
self._uncertain_attachment_threads: set[str] = set()
self._turn_idle_reconciliation_tasks: dict[
tuple[str, str], asyncio.Task[None]
] = {}
async def _fan_out_record(self, record: dict[str, Any]) -> EventEnvelope | None:
thread_id = str(record["thread_id"])
sequence = int(record["seq"])
if sequence <= await self.event_hub.current_sequence(
thread_id,
owner_id=self.tenant_id,
):
return None
data = dict(record.get("data") or {})
project = self._thread_projects.get(thread_id)
if project is not None and data.get("attachments"):
data = await self._attachment_event_data(project, thread_id, data)
return await self.event_hub.publish(
thread_id,
event_type=str(record.get("event_type") or "codex.notification"),
method=str(record.get("method") or record.get("type") or "unknown"),
data=data,
turn_id=(str(record["turn_id"]) if record.get("turn_id") else None),
sequence=sequence,
owner_id=self.tenant_id,
)
@staticmethod
async def _attachment_event_data(project: Project, thread_id: str, data: dict[str, Any]) -> dict[str, Any]:
decorated = {**data, "attachments": [dict(item) for item in data["attachments"]]}
await run_in_threadpool(ConversationAttachmentStore(project).decorate_timeline, thread_id, [{"items": [decorated]}])
return decorated
def _register_thread_project(self, thread_id: str, project: Project) -> None:
self._thread_projects[thread_id] = project
if self._on_thread_authorized is not None:
self._on_thread_authorized(thread_id)
async def _publish(
self,
thread_id: str,
*,
event_type: str,
method: str,
data: dict[str, Any] | None = None,
turn_id: str | None = None,
dedup_key: str | None = None,
channel: str = "console",
) -> EventEnvelope | None:
"""Persist one normalized event before exposing its sequence to SSE."""
async with self._publish_lock:
project = self._thread_projects.get(thread_id)
if project is None:
project, _thread = await self._find_thread(thread_id)
self._register_thread_project(thread_id, project)
opened = await self.stream_journal.ensure_opened(project.path, thread_id)
if not opened.duplicate:
await self._fan_out_record(opened.record)
normalized = normalize_event(
thread_id=thread_id,
event_type=event_type,
method=method,
data=data,
turn_id=turn_id,
dedup_key=dedup_key,
)
if normalized is None:
return None
fingerprint = normalized.get("notification_fingerprint")
if isinstance(fingerprint, str) and fingerprint:
now = time.monotonic()
previous = self._recent_stream_fingerprints.get(fingerprint)
if previous is not None and previous[0] != channel and now - previous[1] <= 5:
return None
self._recent_stream_fingerprints[fingerprint] = (channel, now)
if len(self._recent_stream_fingerprints) > 2_000:
cutoff = now - 10
self._recent_stream_fingerprints = {
key: value for key, value in self._recent_stream_fingerprints.items() if value[1] >= cutoff
}
appended = await self.stream_journal.append(
project.path,
thread_id,
normalized,
)
if appended.duplicate:
return None
return await self._fan_out_record(appended.record)
async def publish_notification(
self,
thread_id: str,
*,
method: str,
data: dict[str, Any],
turn_id: str | None = None,
channel: str = "global",
) -> EventEnvelope | None:
if thread_id in self._ignored_notification_threads:
return None
if turn_id is None:
turn_id = str(data.get("turn_id") or data.get("turnId") or "") or None
if turn_id is None:
active = await self.turn_manager.current(
thread_id,
owner_id=self.tenant_id,
)
turn_id = active.turn_id if active is not None else None
published = await self._publish(
thread_id,
event_type="codex.notification",
method=method,
data=data,
turn_id=turn_id,
channel=channel,
)
if method == "thread/status/changed" and self._thread_status(data) == "idle":
self._schedule_idle_turn_reconciliation(thread_id, turn_id=turn_id)
return published
@staticmethod
def _thread_status(data: dict[str, Any]) -> str | None:
status: Any = data.get("status")
if isinstance(status, dict):
root = status.get("root")
if isinstance(root, dict):
status = root
if isinstance(status, dict):
status = status.get("type")
if isinstance(status, str) and status:
return status.lower()
return None
def _schedule_idle_turn_reconciliation(
self,
thread_id: str,
*,
turn_id: str | None,
) -> None:
"""Release a physical turn if Codex becomes idle without completing it."""
if turn_id is None:
return
key = (thread_id, turn_id)
existing = self._turn_idle_reconciliation_tasks.get(key)
if existing is not None and not existing.done():
return
task = asyncio.create_task(
self._reconcile_idle_turn(thread_id, turn_id),
name=f"codex-turn-idle-reconcile:{thread_id}:{turn_id}",
)
self._turn_idle_reconciliation_tasks[key] = task
def finished(completed: asyncio.Task[None]) -> None:
if self._turn_idle_reconciliation_tasks.get(key) is completed:
self._turn_idle_reconciliation_tasks.pop(key, None)
if completed.cancelled():
return
error = completed.exception()
if error is not None:
LOGW(
"Codex idle turn reconciliation failed: "
f"{type(error).__name__}"
)
task.add_done_callback(finished)
async def _reconcile_idle_turn(self, thread_id: str, turn_id: str) -> None:
await asyncio.sleep(self.turn_idle_reconcile_seconds)
await self._release_stale_turn(
thread_id,
turn_id,
error_code="missing_turn_completion",
)
async def _release_stale_turn(
self,
thread_id: str,
turn_id: str,
*,
error_code: str,
) -> bool:
current = await self.turn_manager.current(
thread_id,
owner_id=self.tenant_id,
)
if (
current is None
or current.kind != "turn"
or current.turn_id != turn_id
):
return False
LOGW(
"Reconciling stale Codex turn: "
f"thread_id={thread_id} turn_id={turn_id} reason={error_code}"
)
try:
await self._publish(
thread_id,
event_type="console.turn.error",
method="turn/error",
data={"error_code": error_code},
turn_id=turn_id,
)
finally:
pump = current.task
if pump is not None and pump is not asyncio.current_task() and not pump.done():
pump.cancel()
await asyncio.gather(pump, return_exceptions=True)
latest = await self.turn_manager.current(
thread_id,
owner_id=self.tenant_id,
)
if latest is not None and latest.turn_id == turn_id:
await self._publish(
thread_id,
event_type="console.turn.idle",
method="console.turn.idle",
turn_id=turn_id,
)
await self.turn_manager.finish(
thread_id,
turn_id=turn_id,
owner_id=self.tenant_id,
)
return True
def _remember_pending_thread(
self,
*,
project: Project,
handle: Any,
view: dict[str, Any],
) -> None:
thread_id = str(view.get("id", ""))
handle_id = str(field(handle, "id", ""))
if not thread_id or handle_id != thread_id:
LOGD(f"codex_pending_thread_rejected view_thread_id={thread_id or 'missing'} handle_matches={handle_id == thread_id}")
raise ConsoleUnavailable
self._pending_threads[thread_id] = _PendingThread(
project=project,
handle=handle,
view=view,
archived=bool(view.get("archived", False)),
)
self._register_thread_project(thread_id, project)
LOGD(f"codex_pending_thread_registered thread_id={thread_id} project_key={project.key}")
def _refresh_pending_thread(
self,
thread_id: str,
*,
handle: Any,
view: dict[str, Any],
) -> None:
pending = self._pending_threads.get(thread_id)
if pending is None:
return
pending.handle = handle
pending.view = view
pending.archived = bool(view.get("archived", pending.archived))
async def _call(
self,
awaitable,
*,
operation: str,
invalid_is_bad_request: bool = False,
allow_unmaterialized_thread: bool = False,
allow_unloaded_thread: bool = False,
):
started_at = time.perf_counter()
LOGD(f"codex_rpc_start operation={operation}")
try:
result = await asyncio.wait_for(
awaitable,
timeout=self.operation_timeout,
)
except asyncio.CancelledError:
elapsed_ms = (time.perf_counter() - started_at) * 1000
LOGD(f"codex_rpc_cancelled operation={operation} elapsed_ms={elapsed_ms:.1f}")
raise
except TimeoutError as exc:
elapsed_ms = (time.perf_counter() - started_at) * 1000
LOGD(f"codex_rpc_timeout operation={operation} elapsed_ms={elapsed_ms:.1f}")
raise ConsoleTimeout from exc
except ConsoleServiceError as exc:
LOGD(f"codex_rpc_console_error operation={operation} exception={type(exc).__name__}")
raise
except (
TurnConflictError,
TurnNotActiveError,
TurnsUnavailableError,
) as exc:
LOGD(f"codex_rpc_turn_state_error operation={operation} exception={type(exc).__name__}")
raise
except (InvalidParamsError, InvalidRequestError) as exc:
if (
allow_unmaterialized_thread
and _is_unmaterialized_thread_error(exc)
):
LOGD(
f"codex_rpc_unmaterialized operation={operation} "
f"exception={type(exc).__name__}"
)
raise
if allow_unloaded_thread and _is_thread_not_loaded_error(exc):
LOGD(
f"codex_rpc_thread_not_loaded operation={operation} "
f"exception={type(exc).__name__}"
)
raise
LOGD(
f"codex_rpc_invalid operation={operation} exception={type(exc).__name__} invalid_is_bad_request={invalid_is_bad_request}",
exc_info=True,
)
LOGW(f"Codex operation rejected invalid parameters: {type(exc).__name__}")
if invalid_is_bad_request:
raise ConsoleBadRequest from exc
raise ConsoleUnavailable from exc
except Exception as exc:
LOGD(
f"codex_rpc_failed operation={operation} exception={type(exc).__name__}",
exc_info=True,
)
LOGW(f"Codex operation failed: {type(exc).__name__}")
raise ConsoleUnavailable from exc
elapsed_ms = (time.perf_counter() - started_at) * 1000
LOGD(f"codex_rpc_complete operation={operation} elapsed_ms={elapsed_ms:.1f}")
return result
async def _read_thread_handle(
self,
thread: Any,
*,
include_turns: bool,
operation: str,
) -> Any:
"""Read a thread, treating a pre-first-message thread as empty."""
try:
return await self._call(
thread.read(include_turns=include_turns),
operation=operation,
allow_unmaterialized_thread=include_turns,
)
except InvalidRequestError as exc:
if not _is_unmaterialized_thread_error(exc):
raise
LOGD(f"codex_thread_read_without_turns operation={operation}")
return await self._call(
thread.read(include_turns=False),
operation=f"{operation}_without_turns",
)
def _project(self, project_key: str) -> Project:
if project_key in self._mutating_projects:
raise ConsoleConflict
try:
return self.registry.get(project_key)
except UnknownProjectError as exc:
raise ConsoleNotFound from exc
async def account(self) -> dict[str, Any]:
response = await self._call(
self.codex.account(),
operation="account",
)
data = to_primitive(response)
return data if isinstance(data, dict) else {"account": data}
async def list_models(self, *, include_hidden: bool = False) -> dict[str, Any]:
response = await self._call(
self.codex.models(include_hidden=include_hidden),
operation="models",
)
data = to_primitive(response)
return data if isinstance(data, dict) else {"data": data}
@asynccontextmanager
async def _project_mutation(self, project_key: str):
project = self._project(project_key)
self._mutating_projects.add(project_key)
reserved: list[str] = []
threads: dict[str, dict[str, Any]] = {}
try:
for archived in (False, True):
cursor = None
while True:
response = await self._call(
self.codex.thread_list(cwd=str(project.path), archived=archived, cursor=cursor, limit=100),
operation="project_threads",
)
for thread in field(response, "data", ()):
if self.registry.project_for_path(field(thread, "cwd", "")) == project:
view = thread_view(thread, project_key=project.key)
threads[str(view["id"])] = {**view, "archived": archived}
cursor = field(response, "next_cursor")
if not cursor:
break
for thread_id, pending in self._pending_threads.items():
if pending.project == project:
threads.setdefault(thread_id, {**pending.view, "archived": pending.archived})
for thread_id, thread in threads.items():
if self._thread_status(thread) in {"active", "running", "inprogress", "in_progress"}:
raise ConsoleConflict
await self.turn_manager.reserve_mutation(thread_id, owner_id=self.tenant_id)
reserved.append(thread_id)
self._ignored_notification_threads.update(reserved)
yield project, threads
except TurnConflictError as exc:
raise ConsoleConflict from exc
finally:
self._ignored_notification_threads.difference_update(reserved)
for thread_id in reserved:
await self.turn_manager.finish_mutation(thread_id, owner_id=self.tenant_id)
self._mutating_projects.discard(project_key)
async def _move_thread_cwd(self, thread: dict[str, Any], project: Project) -> None:
thread_id = str(thread["id"])
archived = thread["archived"]
if archived:
await self._call(self.codex.thread_unarchive(thread_id), operation="project_thread_unarchive")
try:
handle = await self._call(
self.codex.thread_resume(
thread_id, cwd=str(project.path), approval_mode=self.approval_mode, sandbox=self.sandbox,
),
operation="project_thread_relocate",
)
response = await self._read_thread_handle(handle, include_turns=False, operation="project_thread_verify")
actual = field(response, "thread")
if str(field(actual, "id", "")) != thread_id or self.registry.project_for_path(field(actual, "cwd", "")) != project:
raise ConsoleUnavailable
self._register_thread_project(thread_id, project)
pending = self._pending_threads.get(thread_id)
if pending is not None:
pending.project = project
pending.handle = handle
pending.view = {**self._read_view(response, project), "archived": archived}
finally:
if archived:
await self._call(self.codex.thread_archive(thread_id), operation="project_thread_archive")
async def rename_project(self, project_key: str, name: str) -> Project:
async with self._project_mutation(project_key) as (original, threads):
renamed = await asyncio.to_thread(self.registry.rename, project_key, name)
if renamed == original:
return renamed
self._mutating_projects.add(renamed.key)
attempted: list[dict[str, Any]] = []
try:
for thread in threads.values():
attempted.append(thread)
await self._move_thread_cwd(thread, renamed)
except BaseException:
restored = await asyncio.to_thread(self.registry.rename, renamed.key, original.path.name)
for thread in attempted:
await self._move_thread_cwd(thread, restored)
raise
finally:
self._mutating_projects.discard(renamed.key)
return renamed
async def delete_project(self, project_key: str) -> None:
async with self._project_mutation(project_key) as (_project, threads):
await asyncio.to_thread(self.registry.delete, project_key)
for thread_id in threads:
self._pending_threads.pop(thread_id, None)
self._thread_projects.pop(thread_id, None)
async def list_threads(
self,
*,
project_key: str,
archived: bool = False,
cursor: str | None = None,
limit: int = 30,
) -> dict[str, Any]:
project = self._project(project_key)
LOGD(f"codex_thread_list_start project_key={project.key} archived={archived} cursor_present={cursor is not None} limit={limit}")
response = await self._call(
self.codex.thread_list(
archived=archived,
cursor=cursor,
cwd=str(project.path),
limit=limit,
),
operation="thread_list",
invalid_is_bad_request=True,
)
threads = [
thread_view(thread, project_key=project.key)
for thread in field(response, "data", ())
if self.registry.project_for_path(field(thread, "cwd", "")) == project
]
listed_ids = {str(thread["id"]) for thread in threads}
discovered_pending_ids = listed_ids.intersection(self._pending_threads)
for thread_id in discovered_pending_ids:
self._pending_threads.pop(thread_id, None)
LOGD(f"codex_pending_thread_discovered thread_id={thread_id} project_key={project.key}")
pending_views: list[dict[str, Any]] = []
if cursor is None:
pending_views = [
dict(pending.view)
for pending in reversed(tuple(self._pending_threads.values()))
if pending.project == project and pending.archived is archived and str(pending.view["id"]) not in listed_ids
]
if pending_views:
LOGD(f"codex_thread_list_pending_merged project_key={project.key} archived={archived} pending_count={len(pending_views)}")
threads = [*pending_views, *threads]
payload = {
"data": threads,
"next_cursor": field(response, "next_cursor"),
"backwards_cursor": field(response, "backwards_cursor"),
}
LOGD(
f"codex_thread_list_complete project_key={project.key} "
f"archived={archived} result_count={len(threads)} "
f"next_cursor_present={payload['next_cursor'] is not None}"
)
return payload
async def _find_thread(self, thread_id: str) -> tuple[Project, Any]:
pending = self._pending_threads.get(thread_id)
if pending is not None:
if pending.project.key in self._mutating_projects:
raise ConsoleConflict
LOGD(f"codex_thread_lookup_pending thread_id={thread_id} project_key={pending.project.key}")
self._register_thread_project(thread_id, pending.project)
return pending.project, pending.handle
scanned_pages = 0
LOGD(f"codex_thread_lookup_start thread_id={thread_id} project_count={len(self.registry)}")
for project in self.registry:
for archived in (False, True):
cursor: str | None = None
for page_number in range(self.lookup_page_limit):
response = await self._call(
self.codex.thread_list(
archived=archived,
cursor=cursor,
cwd=str(project.path),
limit=100,
),
operation="thread_list_lookup",
)
scanned_pages += 1
listed_threads = tuple(field(response, "data", ()))
LOGD(
f"codex_thread_lookup_page thread_id={thread_id} "
f"project_key={project.key} archived={archived} "
f"page={page_number + 1} result_count={len(listed_threads)}"
)
for listed_thread in listed_threads:
if (
str(field(listed_thread, "id", "")) == thread_id
and self.registry.project_for_path(field(listed_thread, "cwd", "")) == project
):
if project.key in self._mutating_projects:
raise ConsoleConflict
LOGD(
f"codex_thread_lookup_found thread_id={thread_id} "
f"project_key={project.key} archived={archived} "
f"page={page_number + 1} scanned_pages={scanned_pages}"
)
self._register_thread_project(thread_id, project)
return project, listed_thread
cursor = field(response, "next_cursor")
if not cursor:
break
LOGD(f"codex_thread_lookup_miss thread_id={thread_id} scanned_pages={scanned_pages}")
raise ConsoleNotFound
async def _authorized_thread(
self,
thread_id: str,
*,
include_turns: bool,
resume: bool = True,
model: str | None = None,
reasoning_effort: str | None = None,
) -> tuple[Project, Any, Any]:
LOGD(f"codex_thread_authorize_start thread_id={thread_id} include_turns={include_turns}")
pending = self._pending_threads.get(thread_id)
if pending is not None and pending.project.key in self._mutating_projects:
raise ConsoleConflict
if pending is not None and model is None and reasoning_effort is None:
project = pending.project
thread = pending.handle
LOGD(f"codex_thread_authorize_fresh thread_id={thread_id} project_key={project.key}")
else:
if pending is not None:
project = pending.project
else:
project, _listed = await self._find_thread(thread_id)
if resume:
thread = await self._call(
self.codex.thread_resume(
thread_id,
approval_mode=self.approval_mode,
sandbox=self.sandbox,
model=model,
config=({"model_reasoning_effort": reasoning_effort} if reasoning_effort is not None else None),
),
operation="thread_resume",
)
else:
# Reading saved history does not require taking over its writer.
# Another Codex process may already be running this session.
thread = AsyncThread(self.codex, thread_id)
response = await self._read_thread_handle(
thread,
include_turns=include_turns,
operation="thread_read",
)
actual_thread = field(response, "thread")
if str(field(actual_thread, "id", "")) != thread_id or self.registry.project_for_path(field(actual_thread, "cwd", "")) != project:
LOGD(f"codex_thread_authorize_mismatch thread_id={thread_id} project_key={project.key}")
self._pending_threads.pop(thread_id, None)
raise ConsoleNotFound
self._refresh_pending_thread(
thread_id,
handle=thread,
view=self._read_view(response, project),
)
self._register_thread_project(thread_id, project)
LOGD(f"codex_thread_authorize_complete thread_id={thread_id} project_key={project.key} include_turns={include_turns}")
return project, thread, response
def _read_view(self, response: Any, project: Project) -> dict[str, Any]:
return thread_view(field(response, "thread"), project_key=project.key)
async def create_thread(
self,
*,
project_key: str,
name: str | None,
model: str | None,
) -> dict[str, Any]:
project = self._project(project_key)
LOGD(f"codex_thread_create_start project_key={project.key} has_name={name is not None} model_selected={model is not None}")
thread = await self._call(
self.codex.thread_start(
cwd=str(project.path),
model=model,
approval_mode=self.approval_mode,
sandbox=self.sandbox,
),
operation="thread_start",
)
created_thread_id = str(field(thread, "id", ""))
LOGD(f"codex_thread_create_started project_key={project.key} thread_id={created_thread_id or 'missing'}")
if name:
await self._call(
thread.set_name(name),
operation="thread_set_name",
)
response = await self._read_thread_handle(
thread,
include_turns=True,
operation="thread_read_created",
)
actual = field(response, "thread")
if self.registry.project_for_path(field(actual, "cwd", "")) != project:
LOGD(f"codex_thread_create_project_mismatch project_key={project.key} thread_id={created_thread_id or 'missing'}")
raise ConsoleNotFound
view = self._read_view(response, project)
self._remember_pending_thread(
project=project,
handle=thread,
view=view,
)
LOGD(f"codex_thread_create_complete project_key={project.key} thread_id={view['id']}")
return view
async def _generate_session_title(self, project: Project, prompt: str) -> str:
LOGD(
"codex_session_title_start "
f"project_key={project.key} model={SESSION_TITLE_MODEL} "
f"reasoning_effort={SESSION_TITLE_REASONING_EFFORT}"
)
naming_thread = await self._call(
self.codex.thread_start(
cwd=str(project.path),
model=SESSION_TITLE_MODEL,
ephemeral=True,
developer_instructions=_SESSION_TITLE_DEVELOPER_INSTRUCTIONS,
approval_mode=ApprovalMode.deny_all,
sandbox=Sandbox.read_only,
),
operation="session_title_thread_start",
)
naming_thread_id = str(field(naming_thread, "id", ""))
if naming_thread_id:
if len(self._ignored_notification_threads) >= 2_000:
self._ignored_notification_threads.pop()
self._ignored_notification_threads.add(naming_thread_id)
result = await self._call(
naming_thread.run(
prompt,
model=SESSION_TITLE_MODEL,
effort=SESSION_TITLE_REASONING_EFFORT,
output_schema=_SESSION_TITLE_OUTPUT_SCHEMA,
approval_mode=ApprovalMode.deny_all,
sandbox=Sandbox.read_only,
),
operation="session_title_generate",
)
raw_response = field(result, "final_response")
if not isinstance(raw_response, str):
raise ConsoleUnavailable
try:
payload = json.loads(raw_response)
except (json.JSONDecodeError, TypeError) as exc:
raise ConsoleUnavailable from exc
title = payload.get("title") if isinstance(payload, dict) else None
if not isinstance(title, str):
raise ConsoleUnavailable
normalized = " ".join(title.split()).strip(" \t\r\n\"'")
if not normalized:
raise ConsoleUnavailable
normalized = normalized[:200].rstrip()
LOGD(
"codex_session_title_complete "
f"project_key={project.key} title_length={len(normalized)}"
)
return normalized
async def create_thread_from_prompt(
self,
*,
project_key: str,
prompt: str,
model: str | None,
reasoning_effort: str | None,
attachment_ids: list[str] | None = None,
) -> dict[str, Any]:
project = self._project(project_key)
if attachment_ids:
self._validate_attachment_prompt(prompt)
await run_in_threadpool(ConversationAttachmentStore(project).validate_pending, attachment_ids)
title = await self._generate_session_title(project, prompt)
thread = await self.create_thread(
project_key=project_key,
name=title,
model=model,
)
try:
turn = await self.start_turn(
str(thread["id"]),
prompt=prompt,
model=model,
reasoning_effort=reasoning_effort,
attachment_ids=attachment_ids,
)
except ConsoleSubmissionUncertain:
raise
except (asyncio.CancelledError, Exception):
if str(thread["id"]) in self._uncertain_attachment_threads:
raise
try:
await self.delete_thread(str(thread["id"]))
except ConsoleServiceError as cleanup_error:
LOGW(
"Failed to remove a session after its initial turn failed: "
f"thread_id={thread['id']} exception={type(cleanup_error).__name__}"
)
raise
return {**thread, **turn}
async def create_thread_from_goal(
self,
*,
project_key: str,
objective: str,
model: str | None,
reasoning_effort: str | None,
) -> dict[str, Any]:
project = self._project(project_key)
title = await self._generate_session_title(project, objective)
thread = await self.create_thread(
project_key=project_key,
name=title,
model=model,
)
try:
goal = await self.start_goal(
str(thread["id"]),
objective=objective,
token_budget=None,
model=model,
reasoning_effort=reasoning_effort,
)
except (asyncio.CancelledError, Exception):
try:
await self.delete_thread(str(thread["id"]))
except ConsoleServiceError as cleanup_error:
LOGW(
"Failed to remove a session after its initial goal failed: "
f"thread_id={thread['id']} exception={type(cleanup_error).__name__}"
)
raise
return {**thread, **goal}
@staticmethod
def _journal_envelope(record: dict[str, Any]) -> EventEnvelope:
return EventEnvelope(
sequence=int(record["seq"]),
thread_id=str(record["thread_id"]),
turn_id=(str(record["turn_id"]) if record.get("turn_id") else None),
type=str(record.get("event_type") or "codex.notification"),
method=str(record.get("method") or record.get("type") or "unknown"),
data=dict(record.get("data") or {}),
)
async def _materialized_view(