-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathweb_server.py
More file actions
8679 lines (7672 loc) · 352 KB
/
web_server.py
File metadata and controls
8679 lines (7672 loc) · 352 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
from __future__ import annotations
import base64
import json
import mimetypes
import os
import re
import threading
import time
import uuid
from collections.abc import Callable
from dataclasses import dataclass, replace
from datetime import datetime, timezone
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib import error as urllib_error
from urllib import request as urllib_request
from urllib.parse import parse_qs, quote, urlparse, urlunparse
from codex_context import is_conversation_record
from dotenv import load_dotenv
try:
import tiktoken
except ImportError: # pragma: no cover - dependency fallback for partially installed environments
tiktoken = None
from simple_agent.agent import BridgedFunctionCall, SimpleAgent, ToolEvent, sanitize_text, sanitize_value
from simple_agent.config import (
CODEX_PROXY_BASE_URL,
CODEX_PROXY_PROVIDER_ID,
Settings,
_UNSET,
load_settings,
save_settings,
)
from simple_agent.tools import ToolExecution
REPO_ROOT = Path(__file__).resolve().parent
DEFAULT_PAGE = REPO_ROOT / "hash.html"
REACT_DIST_DIR = REPO_ROOT / "react_app" / "dist"
RAW_STATE_DIR = Path(os.getenv("HASH_DATA_DIR", str(REPO_ROOT / "data"))).expanduser()
STATE_DIR = RAW_STATE_DIR if RAW_STATE_DIR.is_absolute() else (REPO_ROOT / RAW_STATE_DIR).resolve()
STATE_FILE = STATE_DIR / "hash_web_state.json"
PROXY_STATE_FILE = STATE_DIR / "proxy_state.json"
CODEX_LOCAL_SESSIONS_DIR = Path.home() / ".codex" / "sessions"
CONTEXT_REQUEST_DEBUG_FILE = STATE_DIR / "context_request_debug.ndjson"
CONTEXT_EDIT_MARKERS_FILE = STATE_DIR / "context_edit_markers.json"
ATTACHMENTS_DIR = STATE_DIR / "uploads"
ATTACHMENTS_ROUTE = "uploads"
DEFAULT_PROJECT_ID = "project_root"
NEW_PROJECT_PREFIX = "新项目"
NEW_SESSION_TITLE = "新对话"
HIDDEN_WORKSPACE_ENTRIES = {
".git",
".venv",
"__pycache__",
"node_modules",
"tmp_cherry_extract",
}
_TOKEN_ENCODING: Any | None = None
_TOKEN_ENCODING_LOAD_FAILED = False
CONTEXT_INPUT_MESSAGE_ROLES = {"system", "developer", "user", "assistant"}
CONTEXT_INPUT_RECORD_ROLES = {*CONTEXT_INPUT_MESSAGE_ROLES, "compaction", "context"}
CODEX_PAIRED_TOOL_CALL_ITEM_TYPES = {
"function_call",
"local_shell_call",
"custom_tool_call",
"tool_search_call",
}
CODEX_STANDALONE_TOOL_CALL_ITEM_TYPES = {
"web_search_call",
"image_generation_call",
}
CODEX_TOOL_CALL_ITEM_TYPES = {
*CODEX_PAIRED_TOOL_CALL_ITEM_TYPES,
*CODEX_STANDALONE_TOOL_CALL_ITEM_TYPES,
}
CODEX_TOOL_OUTPUT_ITEM_TYPES = {
"function_call_output",
"custom_tool_call_output",
"mcp_tool_call_output",
"tool_search_output",
"local_shell_call_output",
}
CODEX_TOOL_OUTPUT_TYPES_BY_CALL_TYPE = {
"function_call": {"function_call_output", "mcp_tool_call_output"},
"local_shell_call": {"function_call_output", "local_shell_call_output"},
"custom_tool_call": {"custom_tool_call_output"},
"tool_search_call": {"tool_search_output"},
}
CODEX_TOOL_CALL_TYPES_BY_OUTPUT_TYPE: dict[str, set[str]] = {}
for _call_type, _output_types in CODEX_TOOL_OUTPUT_TYPES_BY_CALL_TYPE.items():
for _output_type in _output_types:
CODEX_TOOL_CALL_TYPES_BY_OUTPUT_TYPE.setdefault(_output_type, set()).add(_call_type)
CONTEXT_EDITABLE_PROVIDER_ITEM_TYPES = {
"message",
"reasoning",
"compaction",
"compaction_summary",
*CODEX_TOOL_CALL_ITEM_TYPES,
*CODEX_TOOL_OUTPUT_ITEM_TYPES,
}
def is_relative_to_path(candidate: Path, root: Path) -> bool:
return candidate == root or root in candidate.parents
def attachment_url_path(stored_name: str) -> str:
return f"{ATTACHMENTS_ROUTE}/{stored_name}"
def resolve_attachment_file_path(relative_path: str) -> Path | None:
safe_relative_path = sanitize_text(relative_path or "").replace("\\", "/").lstrip("/")
if not safe_relative_path:
return None
route_prefix = f"{ATTACHMENTS_ROUTE}/"
if safe_relative_path.startswith(route_prefix):
attachment_name = safe_relative_path.removeprefix(route_prefix).strip("/")
if not attachment_name or "/" in attachment_name:
return None
attachments_root = ATTACHMENTS_DIR.resolve()
candidate = (ATTACHMENTS_DIR / attachment_name).resolve()
return candidate if is_relative_to_path(candidate, attachments_root) else None
repo_root = REPO_ROOT.resolve()
candidate = (REPO_ROOT / safe_relative_path).resolve()
return candidate if is_relative_to_path(candidate, repo_root) else None
DEFAULT_REASONING_OPTIONS = [
{"value": "default", "label": "自动"},
{"value": "none", "label": "关闭"},
{"value": "low", "label": "低"},
{"value": "medium", "label": "中"},
{"value": "high", "label": "高"},
]
MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024
MAX_TOTAL_ATTACHMENT_BYTES = 50 * 1024 * 1024
DATA_URL_PATTERN = re.compile(r"^data:(?P<mime>[^;,]+);base64,(?P<data>.+)$")
TITLE_GENERATION_INSTRUCTIONS = "\n".join(
[
"你只负责给一段新对话起标题。",
"标题要短、具体、自然,优先使用用户的语言。",
"不要解释,不要加引号,不要使用 Markdown。",
"最多 18 个中文字符或 8 个英文单词。",
]
)
class ClientDisconnectedError(BrokenPipeError):
"""Raised when the front-end intentionally closes a stream early."""
class RequestCancelledError(RuntimeError):
"""Raised when the user explicitly stops the active request."""
@dataclass(slots=True)
class SessionState:
session_id: str
title: str
scope: str
project_id: str | None
agent: SimpleAgent | None
transcript: list[dict[str, object]]
context_workbench_history: list[dict[str, str]]
context_revisions: list[dict[str, object]]
pending_context_restore: dict[str, object] | None
active_request_mode: str | None = None
active_request_id: str | None = None
active_cancel_event: threading.Event | None = None
agent_hydrated: bool = True
@dataclass(slots=True)
class ProjectState:
project_id: str
title: str
session_ids: list[str]
root_path: str | None = None
archived_session_ids: list[str] | None = None
@dataclass(slots=True)
class ContextWorkbenchToolDefinition:
name: str
label: str
description: str
parameters: dict[str, Any]
status: str
handler: Callable[[dict[str, Any]], ToolExecution]
def to_schema(self) -> dict[str, Any]:
return {
"type": "function",
"name": self.name,
"description": self.description,
"parameters": self.parameters,
}
def to_catalog_item(self) -> dict[str, str]:
return {
"id": self.name,
"label": self.label,
"description": self.description,
"status": self.status,
}
class AppState:
def __init__(self, settings: Settings) -> None:
self.settings = settings
self.lock = threading.Lock()
self.projects: list[ProjectState] = []
self.chat_session_ids: list[str] = []
self.sessions: dict[str, SessionState] = {}
self._load_state()
def refresh_settings(self, settings: Settings) -> None:
with self.lock:
self.settings = settings
for session in self.sessions.values():
session.agent = SimpleAgent(self._settings_for_session_locked(session))
self._hydrate_agent_locked(session)
self._save_state_locked()
def create_project(self, title: str | None = None, root_path: str | None = None) -> ProjectState:
with self.lock:
normalized_root_path = self._coerce_project_root_path(root_path)
project = ProjectState(
project_id=uuid.uuid4().hex,
title=self._coerce_project_title(title, normalized_root_path),
session_ids=[],
root_path=normalized_root_path,
archived_session_ids=[],
)
self.projects.insert(0, project)
self._save_state_locked()
return project
def pin_project(self, project_id: str | None) -> ProjectState:
safe_project_id = sanitize_text(project_id or "").strip()
if not safe_project_id:
raise ValueError("project_id is required")
with self.lock:
project = self._find_project_locked(safe_project_id)
if project is None:
raise ValueError("project not found")
self.projects = [item for item in self.projects if item.project_id != safe_project_id]
self.projects.insert(0, project)
self._save_state_locked()
return project
def rename_project(self, project_id: str | None, title: str | None) -> ProjectState:
safe_project_id = sanitize_text(project_id or "").strip()
safe_title = sanitize_text(title or "").strip()
if not safe_project_id:
raise ValueError("project_id is required")
if not safe_title:
raise ValueError("project title is required")
with self.lock:
project = self._find_project_locked(safe_project_id)
if project is None:
raise ValueError("project not found")
project.title = safe_title
self._save_state_locked()
return project
def archive_project_sessions(self, project_id: str | None) -> tuple[ProjectState, list[str]]:
safe_project_id = sanitize_text(project_id or "").strip()
if not safe_project_id:
raise ValueError("project_id is required")
with self.lock:
project = self._find_project_locked(safe_project_id)
if project is None:
raise ValueError("project not found")
archived_session_ids = list(project.session_ids)
existing_archived_ids = list(project.archived_session_ids or [])
for session_id in archived_session_ids:
if session_id not in existing_archived_ids:
existing_archived_ids.insert(0, session_id)
project.session_ids = []
project.archived_session_ids = existing_archived_ids
self._save_state_locked()
return project, archived_session_ids
def create_session(
self,
*,
scope: str = "chat",
project_id: str | None = None,
) -> SessionState:
normalized_scope = self._normalize_scope(scope)
with self.lock:
target_project_id: str | None = None
if normalized_scope == "project":
project = self._find_project_locked(project_id) or self._ensure_default_project_locked()
target_project_id = project.project_id
session = SessionState(
session_id=uuid.uuid4().hex,
title=NEW_SESSION_TITLE,
scope=normalized_scope,
project_id=target_project_id,
agent=SimpleAgent(self._settings_for_project_locked(target_project_id)),
transcript=[],
context_workbench_history=[],
context_revisions=[],
pending_context_restore=None,
)
ensure_initial_context_revision(session)
self.sessions[session.session_id] = session
self._insert_session_locked(session)
self._save_state_locked()
return session
def get_session(self, session_id: str | None) -> SessionState:
safe_session_id = sanitize_text(session_id or "").strip()
if not safe_session_id:
raise ValueError("session_id is required")
with self.lock:
session = self.sessions.get(safe_session_id)
if session is None:
raise ValueError("session not found")
return session
def acquire_session_request(self, session: SessionState, mode: str) -> str:
safe_mode = sanitize_text(mode).strip()
if safe_mode not in {"main", "context"}:
raise ValueError("invalid session request mode")
with self.lock:
active_mode = sanitize_text(session.active_request_mode or "").strip()
active_cancelled = bool(session.active_cancel_event and session.active_cancel_event.is_set())
if active_mode and active_mode != safe_mode:
raise ValueError("当前主聊天和上下文工作区不能并行,请等这一轮先结束。")
if active_mode == safe_mode:
if active_cancelled:
request_id = uuid.uuid4().hex
session.active_request_id = request_id
session.active_cancel_event = threading.Event()
return request_id
if safe_mode == "main":
raise ValueError("当前这条主对话还没结束。")
raise ValueError("当前上下文工作区还在处理中。")
request_id = uuid.uuid4().hex
session.active_request_mode = safe_mode
session.active_request_id = request_id
session.active_cancel_event = threading.Event()
return request_id
def release_session_request(self, session: SessionState, mode: str, request_id: str | None = None) -> None:
safe_mode = sanitize_text(mode).strip()
if safe_mode not in {"main", "context"}:
return
with self.lock:
if request_id is not None and session.active_request_id != request_id:
return
if session.active_request_mode == safe_mode:
session.active_request_mode = None
session.active_request_id = None
session.active_cancel_event = None
def cancel_session_request(self, session: SessionState, mode: str) -> bool:
safe_mode = sanitize_text(mode).strip()
if safe_mode not in {"main", "context"}:
raise ValueError("invalid session request mode")
with self.lock:
if session.active_request_mode != safe_mode or session.active_cancel_event is None:
return False
session.active_cancel_event.set()
return True
def is_session_request_cancelled(self, session: SessionState, request_id: str) -> bool:
with self.lock:
if session.active_request_id != request_id:
return True
return bool(session.active_cancel_event and session.active_cancel_event.is_set())
def touch_session(self, session_id: str) -> None:
with self.lock:
session = self.sessions.get(session_id)
if session is None:
return
self._remove_session_from_lists_locked(session_id)
self._insert_session_locked(session)
self._save_state_locked()
def upsert_proxy_session(
self,
*,
session_id: str,
title: str,
transcript: list[dict[str, object]],
is_running: bool = False,
) -> SessionState:
safe_session_id = sanitize_text(session_id or "").strip()
if not safe_session_id:
raise ValueError("session_id is required")
with self.lock:
session = self.sessions.get(safe_session_id)
created_session = False
if session is None:
session = SessionState(
session_id=safe_session_id,
title=sanitize_text(title or "").strip() or "Codex Context",
scope="chat",
project_id=None,
agent=SimpleAgent(self._settings_for_project_locked(None)),
transcript=[],
context_workbench_history=[],
context_revisions=[],
pending_context_restore=None,
)
self.sessions[safe_session_id] = session
self._insert_session_locked(session)
created_session = True
active_mode = sanitize_text(session.active_request_mode or "").strip()
active_request_id = sanitize_text(session.active_request_id or "").strip()
next_transcript = normalize_transcript(transcript)
next_title = sanitize_text(title or "").strip() or session.title or "Codex Context"
should_persist = created_session
if session.title != next_title:
session.title = next_title
should_persist = True
if session.scope != "chat":
session.scope = "chat"
should_persist = True
if session.project_id is not None:
session.project_id = None
should_persist = True
if active_mode != "context":
transcript_changed = next_transcript != normalize_transcript(session.transcript)
if transcript_changed:
session.transcript = next_transcript
session.pending_context_restore = None
should_persist = True
if active_mode != "context":
if is_running:
if active_mode != "main" or active_request_id != "proxy-running":
session.active_request_mode = "main"
session.active_request_id = "proxy-running"
session.active_cancel_event = threading.Event()
should_persist = True
elif active_mode == "main" and active_request_id == "proxy-running":
session.active_request_mode = None
session.active_request_id = None
session.active_cancel_event = None
should_persist = True
if should_persist:
ensure_initial_context_revision(session)
sync_active_context_revision_snapshot(session)
self._hydrate_agent_locked(session)
self._remove_session_from_lists_locked(session.session_id)
self._insert_session_locked(session)
self._save_state_locked()
return session
def reset_session(self, session_id: str) -> SessionState:
session = self.get_session(session_id)
with self.lock:
if session.agent is not None:
session.agent.reset()
session.agent_hydrated = True
session.title = NEW_SESSION_TITLE
session.transcript = []
session.context_workbench_history = []
session.context_revisions = []
session.pending_context_restore = None
ensure_initial_context_revision(session)
self._save_state_locked()
return session
def truncate_session(self, session_id: str, from_index: int) -> SessionState:
session = self.get_session(session_id)
with self.lock:
safe_index = max(0, min(from_index, len(session.transcript)))
session.transcript = session.transcript[:safe_index]
session.context_workbench_history = []
session.context_revisions = []
session.pending_context_restore = None
ensure_initial_context_revision(session)
self._hydrate_agent_locked(session)
if not session.transcript:
session.title = NEW_SESSION_TITLE
self._save_state_locked()
return session
def delete_transcript_message(
self,
session_id: str,
message_index: int,
) -> SessionState:
session = self.get_session(session_id)
with self.lock:
normalized_transcript = normalize_transcript(session.transcript)
if not normalized_transcript:
raise ValueError("当前没有可删除的消息")
safe_index = int(message_index)
if safe_index < 0 or safe_index >= len(normalized_transcript):
raise ValueError("message_index is out of range")
session.transcript = [
record
for index, record in enumerate(normalized_transcript)
if index != safe_index
]
ensure_initial_context_revision(session)
sync_active_context_revision_snapshot(session)
self._hydrate_agent_locked(session)
if not session.transcript:
session.title = NEW_SESSION_TITLE
self._save_state_locked()
return session
def delete_session(self, session_id: str) -> SessionState:
session = self.get_session(session_id)
with self.lock:
self.sessions.pop(session.session_id, None)
self._remove_session_from_lists_locked(session.session_id)
self._save_state_locked()
return session
def delete_project(self, project_id: str | None) -> tuple[ProjectState, list[str]]:
safe_project_id = sanitize_text(project_id or "").strip()
if not safe_project_id:
raise ValueError("project_id is required")
with self.lock:
project_index = next(
(index for index, project in enumerate(self.projects) if project.project_id == safe_project_id),
None,
)
if project_index is None:
raise ValueError("project not found")
project = self.projects.pop(project_index)
deleted_session_ids = list(project.session_ids)
for session_id in deleted_session_ids:
self.sessions.pop(session_id, None)
self._save_state_locked()
return project, deleted_session_ids
def rename_session_from_message(self, session: SessionState, message: str) -> None:
compact = summarize_title(message)
with self.lock:
if session.title == NEW_SESSION_TITLE and compact:
session.title = compact
self._save_state_locked()
def should_name_session_from_first_message(self, session: SessionState) -> bool:
with self.lock:
return session.title == NEW_SESSION_TITLE and not normalize_transcript(session.transcript)
def name_session_from_first_message(
self,
session: SessionState,
message: str,
*,
model: str | None = None,
) -> None:
safe_message = sanitize_text(message).strip()
if not safe_message:
return
with self.lock:
if session.title != NEW_SESSION_TITLE or normalize_transcript(session.transcript):
return
title = generate_session_title(
self.settings,
safe_message,
model=model,
)
if not title:
return
with self.lock:
if session.title == NEW_SESSION_TITLE and not normalize_transcript(session.transcript):
session.title = title
self._save_state_locked()
def name_session_from_first_message_async(
self,
session: SessionState,
message: str,
*,
model: str | None = None,
) -> None:
safe_message = sanitize_text(message).strip()
if not safe_message:
return
fallback_title = summarize_title(safe_message)
if not fallback_title:
return
with self.lock:
if session.title != NEW_SESSION_TITLE or normalize_transcript(session.transcript):
return
session.title = fallback_title
session_id = session.session_id
self._save_state_locked()
def worker() -> None:
title = generate_session_title(
self.settings,
safe_message,
model=model,
)
if not title or title == fallback_title:
return
with self.lock:
target_session = self.sessions.get(session_id)
if target_session is None or target_session.title != fallback_title:
return
target_session.title = title
self._save_state_locked()
threading.Thread(
target=worker,
name=f"hash-title-{session_id}",
daemon=True,
).start()
def append_context_workbench_turn(
self,
session: SessionState,
*,
user_message: str,
answer: str,
) -> list[dict[str, str]]:
with self.lock:
session.pending_context_restore = None
session.context_workbench_history = normalize_context_chat_history(
[
*session.context_workbench_history,
{"role": "user", "content": sanitize_text(user_message)},
{"role": "assistant", "content": sanitize_text(answer)},
]
)
ensure_initial_context_revision(session)
sync_active_context_revision_snapshot(session)
self._save_state_locked()
return sanitize_value(session.context_workbench_history)
def delete_context_workbench_history_message(
self,
session: SessionState,
*,
message_index: int,
) -> tuple[list[dict[str, object]], list[dict[str, str]], list[dict[str, object]], dict[str, object] | None]:
with self.lock:
normalized_history = normalize_context_chat_history(session.context_workbench_history)
if not normalized_history:
raise ValueError("当前没有可删除的手动消息")
safe_index = int(message_index)
if safe_index < 0 or safe_index >= len(normalized_history):
raise ValueError("message_index is out of range")
session.context_workbench_history = [
item
for index, item in enumerate(normalized_history)
if index != safe_index
]
session.pending_context_restore = None
sync_active_context_revision_snapshot(session)
self._save_state_locked()
return (
sanitize_value(session.transcript),
sanitize_value(session.context_workbench_history),
context_revision_summaries(session.context_revisions),
None,
)
def clear_context_workbench_history(
self,
session: SessionState,
) -> tuple[list[dict[str, object]], list[dict[str, str]], list[dict[str, object]], dict[str, object] | None]:
with self.lock:
session.context_workbench_history = []
session.pending_context_restore = None
sync_active_context_revision_snapshot(session)
self._save_state_locked()
return (
sanitize_value(session.transcript),
[],
context_revision_summaries(session.context_revisions),
None,
)
def apply_context_workbench_mutation(
self,
session: SessionState,
*,
transcript: list[dict[str, object]],
revision_label: str,
revision_summary: str,
operations: list[dict[str, object]],
) -> tuple[list[dict[str, object]], list[dict[str, object]], dict[str, object] | None]:
with self.lock:
ensure_initial_context_revision(session)
next_revision_number = next_context_revision_number(session.context_revisions)
session.transcript = normalize_transcript(transcript)
session.pending_context_restore = None
mark_active_context_revision(session.context_revisions, None)
session.context_revisions.append(
build_context_revision_entry(
transcript=session.transcript,
context_workbench_history=session.context_workbench_history,
revision_label=revision_label,
revision_summary=revision_summary,
operations=operations,
revision_number=next_revision_number,
)
)
self._hydrate_agent_locked(session)
self._save_state_locked()
return (
sanitize_value(session.transcript),
context_revision_summaries(session.context_revisions),
None,
)
def restore_context_revision(
self,
session: SessionState,
revision_id: str,
) -> tuple[list[dict[str, object]], list[dict[str, str]], list[dict[str, object]], dict[str, object]]:
with self.lock:
safe_revision_id = sanitize_text(revision_id).strip()
target = next(
(
revision
for revision in reversed(session.context_revisions)
if sanitize_text(revision.get("id") or "").strip() == safe_revision_id
),
None,
)
if target is None:
raise ValueError("revision not found")
raw_snapshot = target.get("snapshot")
snapshot = normalize_transcript(raw_snapshot)
if not snapshot and session.transcript and "snapshot" not in target:
raise ValueError("target revision snapshot is unavailable")
workbench_history_snapshot = normalize_context_chat_history(
target.get("context_workbench_history_snapshot")
)
undo_active_revision_id = find_active_context_revision_id(session.context_revisions)
session.pending_context_restore = {
"undo_transcript": sanitize_value(session.transcript),
"undo_context_workbench_history": sanitize_value(session.context_workbench_history),
"target_revision_id": safe_revision_id,
"target_label": sanitize_text(target.get("label") or "").strip() or "Revision",
"created_at": utc_timestamp(),
"undo_active_revision_id": undo_active_revision_id or "",
}
session.transcript = snapshot
session.context_workbench_history = workbench_history_snapshot
mark_active_context_revision(session.context_revisions, safe_revision_id)
sync_active_context_revision_snapshot(session)
self._hydrate_agent_locked(session)
self._save_state_locked()
return (
sanitize_value(session.transcript),
sanitize_value(session.context_workbench_history),
context_revision_summaries(session.context_revisions),
context_pending_restore_payload(session.pending_context_restore),
)
def undo_context_restore(
self,
session: SessionState,
) -> tuple[list[dict[str, object]], list[dict[str, str]], list[dict[str, object]], dict[str, object] | None]:
with self.lock:
pending_restore = session.pending_context_restore
if not isinstance(pending_restore, dict):
raise ValueError("there is no context restore to undo")
undo_transcript = normalize_transcript(pending_restore.get("undo_transcript"))
undo_context_workbench_history = normalize_context_chat_history(
pending_restore.get("undo_context_workbench_history")
)
undo_active_revision_id = sanitize_text(pending_restore.get("undo_active_revision_id") or "").strip()
session.transcript = undo_transcript
session.context_workbench_history = undo_context_workbench_history
session.pending_context_restore = None
mark_active_context_revision(session.context_revisions, undo_active_revision_id or None)
sync_active_context_revision_snapshot(session)
self._hydrate_agent_locked(session)
self._save_state_locked()
return (
sanitize_value(session.transcript),
sanitize_value(session.context_workbench_history),
context_revision_summaries(session.context_revisions),
None,
)
def append_turn(
self,
session: SessionState,
*,
user_message: str,
answer: str,
tool_events: list[ToolEvent],
assistant_blocks: list[dict[str, object]] | None = None,
user_attachments: list[dict[str, object]] | None = None,
) -> None:
with self.lock:
session.pending_context_restore = None
safe_user_message = sanitize_text(user_message)
safe_user_attachments = normalize_attachment_records(user_attachments)
user_record_index = len(session.transcript)
user_blocks = (
[{"kind": "text", "text": safe_user_message}]
if safe_user_message
else []
)
safe_assistant_blocks = sanitize_value(assistant_blocks or [])
assistant_text = message_blocks_to_text(safe_assistant_blocks) or sanitize_text(answer)
assistant_record_index = user_record_index + 1
assistant_tool_events = [serialize_tool_event(event) for event in tool_events]
session.transcript.append(
{
"role": "user",
"text": safe_user_message,
"attachments": safe_user_attachments,
"toolEvents": [],
"blocks": user_blocks,
"providerItems": build_provider_items_for_record(
role="user",
text=safe_user_message,
attachments=safe_user_attachments,
tool_events=[],
blocks=user_blocks,
record_index=user_record_index,
),
}
)
session.transcript.append(
{
"role": "assistant",
"text": assistant_text,
"attachments": [],
"toolEvents": assistant_tool_events,
"blocks": safe_assistant_blocks,
"providerItems": build_provider_items_for_record(
role="assistant",
text=assistant_text,
attachments=[],
tool_events=assistant_tool_events,
blocks=safe_assistant_blocks,
record_index=assistant_record_index,
),
}
)
ensure_initial_context_revision(session)
sync_active_context_revision_snapshot(session)
self._hydrate_agent_locked(session)
self._remove_session_from_lists_locked(session.session_id)
self._insert_session_locked(session)
self._save_state_locked()
def bootstrap_payload(self, session_id: str = "", include_conversation: bool = True) -> dict[str, object]:
with self.lock:
self._ensure_default_project_locked()
safe_session_id = sanitize_text(session_id or "").strip()
if not include_conversation:
conversations = {}
elif safe_session_id:
conversations = (
{safe_session_id: sanitize_value(self.sessions[safe_session_id].transcript)}
if safe_session_id in self.sessions
else {}
)
else:
conversations = self._conversation_map_locked()
context_workbench_histories = (
{safe_session_id: sanitize_value(self.sessions[safe_session_id].context_workbench_history)}
if safe_session_id
and safe_session_id in self.sessions
and self.sessions[safe_session_id].context_workbench_history
else ({} if safe_session_id else self._context_workbench_history_map_locked())
)
context_revision_histories = (
{safe_session_id: context_revision_summaries(self.sessions[safe_session_id].context_revisions)}
if safe_session_id
and safe_session_id in self.sessions
and self.sessions[safe_session_id].context_revisions
else ({} if safe_session_id else self._context_revision_map_locked())
)
pending_context_restores = (
{safe_session_id: context_pending_restore_payload(self.sessions[safe_session_id].pending_context_restore)}
if safe_session_id
and safe_session_id in self.sessions
and self.sessions[safe_session_id].pending_context_restore
else ({} if safe_session_id else self._pending_context_restore_map_locked())
)
return {
"project_name": self.settings.project_root.name or str(self.settings.project_root),
"project_root": str(self.settings.project_root),
"default_model": self.settings.model,
"models": model_options(self.settings.model, active_provider_models(self.settings)),
"reasoning_options": DEFAULT_REASONING_OPTIONS,
"settings": settings_payload(self.settings),
"projects": self._projects_payload_locked(),
"chat_sessions": self._chat_sessions_payload_locked(),
"conversations": conversations,
"context_workbench_histories": context_workbench_histories,
"context_revision_histories": context_revision_histories,
"pending_context_restores": pending_context_restores,
}
def sidebar_payload(self) -> dict[str, object]:
with self.lock:
return {
"projects": self._projects_payload_locked(),
"chat_sessions": self._chat_sessions_payload_locked(),
}
def session_payload(self, session: SessionState) -> dict[str, object]:
return {
"id": session.session_id,
"title": session.title,
"scope": session.scope,
"project_id": session.project_id,
}
def _load_state(self) -> None:
raw_state: dict[str, Any] = {}
if STATE_FILE.exists():
try:
raw_state = json.loads(STATE_FILE.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
raw_state = {}
projects_data = raw_state.get("projects")
if isinstance(projects_data, list):
for item in projects_data:
if not isinstance(item, dict):
continue
project_id = sanitize_text(item.get("id") or uuid.uuid4().hex).strip()
title = sanitize_text(item.get("title") or "").strip()
session_ids = [
sanitize_text(session_id).strip()
for session_id in item.get("session_ids", [])
if sanitize_text(session_id).strip()
]
if not title:
continue
archived_session_ids = [
sanitize_text(session_id).strip()
for session_id in item.get("archived_session_ids", [])
if sanitize_text(session_id).strip()
]
root_path = self._coerce_project_root_path(item.get("root_path"))
self.projects.append(
ProjectState(
project_id=project_id,
title=title,
session_ids=session_ids,
root_path=root_path,
archived_session_ids=archived_session_ids,
)
)
sessions_data = raw_state.get("sessions")
if isinstance(sessions_data, dict):
for session_id, item in sessions_data.items():
if not isinstance(item, dict):
continue
safe_session_id = sanitize_text(session_id).strip()
if not safe_session_id:
continue
scope = self._normalize_scope(item.get("scope"))
project_id = sanitize_text(item.get("project_id") or "").strip() or None
raw_transcript = item.get("transcript")
transcript = raw_transcript if isinstance(raw_transcript, list) else []