@agentsdock/server 1.0.11 → 1.0.12-beta.10

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.
@@ -27,10 +27,11 @@ from fastapi import APIRouter, HTTPException, Request
27
27
  from fastapi.responses import JSONResponse
28
28
 
29
29
 
30
- MAX_QUESTION_CHARS = 8000
31
30
  MAX_HISTORY_ITEMS = 32
32
31
  MAX_HISTORY_CHARS = 60000
33
32
  MAX_REQUEST_BYTES = 512 * 1024
33
+ # The streamed body limit bounds input; avoid a second, smaller model-text cap.
34
+ MAX_QUESTION_CHARS = MAX_REQUEST_BYTES
34
35
  MAX_CONTEXT_CHARS = 60000
35
36
  MAX_LOG_BYTES = 4 * 1024 * 1024
36
37
  MAX_OUTPUT_BYTES = 1024 * 1024
@@ -57,7 +58,7 @@ class SideQuestionError(Exception):
57
58
 
58
59
  def capability():
59
60
  return {"available": True, "version": 2, "native_context": True, "backends": ["codex", "claude"],
60
- "max_question_chars": MAX_QUESTION_CHARS, "sync": True, "runtime_settings": True}
61
+ "max_question_chars": MAX_QUESTION_CHARS, "sync": True, "runtime_settings": True, "multiple": True}
61
62
 
62
63
 
63
64
  def validate_runtime_settings(value):
@@ -369,11 +370,6 @@ class _NativeConversation:
369
370
  closed: bool = False
370
371
  timer: object = None
371
372
  close_task: asyncio.Task | None = None
372
-
373
-
374
- NATIVE_IDLE_SECONDS = 30 * 60
375
-
376
-
377
373
  class SideQuestions:
378
374
  def __init__(self, answer=None, *, native_factory=None, storage_path=None, notify=None, admission_check=None, runtime_settings_for_session=None):
379
375
  self.answer = answer
@@ -396,6 +392,43 @@ class SideQuestions:
396
392
  def active_work_labels(self):
397
393
  return [f"Side chat in {session_id}" for session_id in sorted(self.active_session_ids())]
398
394
 
395
+ def background_work_scopes(self):
396
+ handles = [(key[1], conversation.handle) for key, conversation in self.conversations.items()
397
+ if not conversation.closed and conversation.handle is not None]
398
+ if self.synced is not None:
399
+ handles.extend((key[1], handle) for key, handle in self.synced.handles.items())
400
+ scopes = []
401
+ for session_id, handle in handles:
402
+ inspect = getattr(handle, "background_work_scope", None)
403
+ scope = inspect() if callable(inspect) else None
404
+ if scope is not None:
405
+ scopes.append((session_id, handle, scope))
406
+ return tuple(scopes)
407
+
408
+ async def prepare_background_work_snapshot(self, *, timeout_seconds=5.0):
409
+ scopes = self.background_work_scopes()
410
+
411
+ async def inspect(session_id, handle, _scope):
412
+ try:
413
+ active = await handle.has_background_work()
414
+ except Exception:
415
+ return f"Side chat provider state unknown in {session_id}"
416
+ return f"Side chat background work in {session_id}" if active else None
417
+
418
+ try:
419
+ values = await asyncio.wait_for(asyncio.gather(*(inspect(*scope) for scope in scopes)),
420
+ timeout=timeout_seconds)
421
+ labels = tuple(sorted(set(value for value in values if value)))
422
+ except asyncio.TimeoutError:
423
+ labels = tuple(f"Side chat provider state unknown in {session_id}" for session_id, _, _ in scopes)
424
+ return {"scopes": scopes, "labels": labels}
425
+
426
+ def background_work_labels_from_snapshot(self, snapshot):
427
+ scopes = self.background_work_scopes()
428
+ if snapshot.get("scopes", ()) != scopes:
429
+ return ["Side chat provider state changed during inspection"]
430
+ return list(snapshot.get("labels", ()))
431
+
399
432
  async def _close_conversation(self, conversation):
400
433
  conversation.closed = True
401
434
  if conversation.timer is not None:
@@ -415,7 +448,7 @@ class SideQuestions:
415
448
  await asyncio.shield(conversation.close_task)
416
449
 
417
450
  def _expire_conversation(self, key, conversation):
418
- if self.conversations.get(key) is not conversation or conversation.busy:
451
+ if self.conversations.get(key) is not conversation or conversation.busy or not conversation.closed:
419
452
  return
420
453
  self.conversations.pop(key, None)
421
454
  task = asyncio.create_task(self._close_conversation(conversation), name="side-chat-expiry")
@@ -461,8 +494,9 @@ class SideQuestions:
461
494
  raise
462
495
  finally:
463
496
  conversation.busy = False
464
- conversation.timer = asyncio.get_running_loop().call_later(
465
- NATIVE_IDLE_SECONDS, self._expire_conversation, key, conversation)
497
+ if conversation.closed:
498
+ conversation.timer = asyncio.get_running_loop().call_later(
499
+ RECEIPT_TTL_SECONDS, self._expire_conversation, key, conversation)
466
500
 
467
501
  async def close_conversation(self, owner, session_id, side_chat_id):
468
502
  key = (owner, session_id, side_chat_id)
@@ -473,7 +507,7 @@ class SideQuestions:
473
507
  await self.cancel(*receipt_key)
474
508
  await self._close_conversation(conversation)
475
509
  conversation.timer = asyncio.get_running_loop().call_later(
476
- NATIVE_IDLE_SECONDS, self._expire_conversation, key, conversation)
510
+ RECEIPT_TTL_SECONDS, self._expire_conversation, key, conversation)
477
511
 
478
512
  def _prune(self):
479
513
  now = time.monotonic()
@@ -595,6 +629,8 @@ class SideChatStore:
595
629
  os.close(descriptor)
596
630
  database = sqlite3.connect(self.path)
597
631
  database.execute("CREATE TABLE IF NOT EXISTS chats (owner TEXT, session TEXT, document TEXT NOT NULL, PRIMARY KEY(owner, session))")
632
+ database.execute("CREATE TABLE IF NOT EXISTS side_chat_conversations (owner TEXT, session TEXT, chat_key TEXT, side_chat TEXT NOT NULL, document TEXT NOT NULL, PRIMARY KEY(owner, session, chat_key), UNIQUE(owner, session, side_chat))")
633
+ database.execute("CREATE TABLE IF NOT EXISTS side_chat_aliases (owner TEXT, session TEXT, side_chat TEXT, chat_key TEXT NOT NULL, PRIMARY KEY(owner, session, side_chat))")
598
634
  database.execute("CREATE TABLE IF NOT EXISTS receipts (owner TEXT, session TEXT, request TEXT, side_chat TEXT NOT NULL, question TEXT NOT NULL, PRIMARY KEY(owner, session, request))")
599
635
  database.execute("CREATE TABLE IF NOT EXISTS provider_threads (thread TEXT PRIMARY KEY)")
600
636
  with database:
@@ -605,8 +641,13 @@ class SideChatStore:
605
641
  database.execute("UPDATE receipts SET question=? WHERE owner=? AND session=? AND request=?",
606
642
  (hashlib.sha256(question.encode()).hexdigest(), owner, session, request))
607
643
  database.execute("PRAGMA user_version=1")
608
- for owner, session, raw in database.execute("SELECT owner, session, document FROM chats").fetchall():
644
+ stored = [(owner, session, "", raw) for owner, session, raw in
645
+ database.execute("SELECT owner, session, document FROM chats").fetchall()]
646
+ stored.extend(database.execute("SELECT owner, session, chat_key, document FROM side_chat_conversations").fetchall())
647
+ for owner, session, chat_key, raw in stored:
609
648
  document = json.loads(raw)
649
+ database.execute("INSERT OR IGNORE INTO side_chat_aliases VALUES(?,?,?,?)",
650
+ (owner, session, document["side_chat_id"], chat_key))
610
651
  thread = ((document.get("_provider_state") or {}).get("codex") or {}).get("thread_id")
611
652
  if isinstance(thread, str) and thread:
612
653
  database.execute("INSERT OR IGNORE INTO provider_threads VALUES(?)", (thread,))
@@ -618,21 +659,34 @@ class SideChatStore:
618
659
  changed = True
619
660
  if changed:
620
661
  document["revision"] += 1
621
- database.execute("UPDATE chats SET document=? WHERE owner=? AND session=?",
622
- (json.dumps(document), owner, session))
662
+ if chat_key:
663
+ database.execute("UPDATE side_chat_conversations SET document=? WHERE owner=? AND session=? AND chat_key=?",
664
+ (json.dumps(document), owner, session, chat_key))
665
+ else:
666
+ database.execute("UPDATE chats SET document=? WHERE owner=? AND session=?",
667
+ (json.dumps(document), owner, session))
623
668
  self.database = database
624
669
  return self.database
625
670
 
626
- def load(self, owner, session):
627
- row = self._db().execute("SELECT document FROM chats WHERE owner=? AND session=?", (owner, session)).fetchone()
671
+ def load(self, owner, session, chat_key=None):
672
+ if chat_key is not None:
673
+ row = self._db().execute("SELECT document FROM side_chat_conversations WHERE owner=? AND session=? AND chat_key=?",
674
+ (owner, session, chat_key)).fetchone()
675
+ if row is None:
676
+ raise SideQuestionError(404, "Side chat not found")
677
+ else:
678
+ row = self._db().execute("SELECT document FROM chats WHERE owner=? AND session=?", (owner, session)).fetchone()
628
679
  if row:
629
- return json.loads(row[0])
680
+ document = json.loads(row[0])
681
+ document["conversation_id"] = "side_" + chat_key if chat_key is not None else "default"
682
+ return document
630
683
  document = {"session_id": session, "side_chat_id": uuid.uuid4().hex, "revision": 0,
631
- "exchanges": [], "last_request_id": None, "_provider_state": None}
684
+ "exchanges": [], "last_request_id": None, "_provider_state": None,
685
+ "created_at": side_chat_timestamp(), "conversation_id": "default"}
632
686
  self.save(owner, session, document)
633
687
  return document
634
688
 
635
- def save(self, owner, session, document, *, receipt=None):
689
+ def save(self, owner, session, document, *, receipt=None, chat_key=None):
636
690
  database = self._db()
637
691
  with database:
638
692
  if receipt is not None:
@@ -643,8 +697,44 @@ class SideChatStore:
643
697
  thread_id = (provider_state.get("codex") or {}).get("thread_id")
644
698
  if isinstance(thread_id, str) and thread_id:
645
699
  database.execute("INSERT OR IGNORE INTO provider_threads VALUES(?)", (thread_id,))
646
- database.execute("INSERT OR REPLACE INTO chats VALUES(?,?,?)",
647
- (owner, session, json.dumps(document, ensure_ascii=False)))
700
+ if chat_key is not None:
701
+ database.execute("INSERT INTO side_chat_conversations VALUES(?,?,?,?,?) ON CONFLICT(owner, session, chat_key) DO UPDATE SET side_chat=excluded.side_chat, document=excluded.document",
702
+ (owner, session, chat_key, document["side_chat_id"], json.dumps(document, ensure_ascii=False)))
703
+ else:
704
+ database.execute("INSERT OR REPLACE INTO chats VALUES(?,?,?)",
705
+ (owner, session, json.dumps(document, ensure_ascii=False)))
706
+ # Keep previous generations so delayed Clear/Stop targets only
707
+ # its original conversation after that conversation was cleared.
708
+ database.execute("INSERT OR IGNORE INTO side_chat_aliases VALUES(?,?,?,?)",
709
+ (owner, session, document["side_chat_id"], chat_key or ""))
710
+
711
+ def key_for_id(self, owner, session, side_chat_id):
712
+ row = self._db().execute("SELECT chat_key FROM side_chat_aliases WHERE owner=? AND session=? AND side_chat=?",
713
+ (owner, session, side_chat_id)).fetchone()
714
+ if row is None:
715
+ raise SideQuestionError(404, "Side chat not found")
716
+ return (owner, session, row[0]) if row[0] else (owner, session)
717
+
718
+ def keys(self, owner, session):
719
+ self.load(owner, session)
720
+ return [(owner, session), *((owner, session, row[0]) for row in self._db().execute(
721
+ "SELECT chat_key FROM side_chat_conversations WHERE owner=? AND session=? ORDER BY rowid", (owner, session)))]
722
+
723
+ def create(self, owner, session, side_chat_id):
724
+ try:
725
+ key = self.key_for_id(owner, session, side_chat_id)
726
+ except SideQuestionError:
727
+ key = (owner, session, side_chat_id)
728
+ else:
729
+ document = self.load(*key)
730
+ if document["side_chat_id"] != side_chat_id:
731
+ raise SideQuestionError(409, "Side chat was cleared; use a new side chat ID")
732
+ return document
733
+ document = {"session_id": session, "side_chat_id": side_chat_id, "revision": 0,
734
+ "exchanges": [], "last_request_id": None, "_provider_state": None,
735
+ "created_at": side_chat_timestamp(), "conversation_id": "side_" + key[2]}
736
+ self.save(owner, session, document, chat_key=key[2])
737
+ return document
648
738
 
649
739
  def receipt(self, owner, session, request_id):
650
740
  return self._db().execute("SELECT side_chat, question FROM receipts WHERE owner=? AND session=? AND request=?",
@@ -661,6 +751,8 @@ class SideChatStore:
661
751
  database = self._db()
662
752
  with database:
663
753
  database.execute("DELETE FROM chats WHERE session=?", (session,))
754
+ database.execute("DELETE FROM side_chat_conversations WHERE session=?", (session,))
755
+ database.execute("DELETE FROM side_chat_aliases WHERE session=?", (session,))
664
756
  database.execute("DELETE FROM receipts WHERE session=?", (session,))
665
757
 
666
758
  def provider_thread_ids(self):
@@ -710,13 +802,17 @@ class SyncedSideChats:
710
802
  def _lock(self, key):
711
803
  return self.locks.setdefault(key, asyncio.Lock())
712
804
 
805
+ def _save(self, key, document, *, receipt=None):
806
+ return self.store.save(key[0], key[1], document, receipt=receipt,
807
+ **({"chat_key": key[2]} if len(key) == 3 else {}))
808
+
713
809
  def _load(self, key):
714
810
  pending = self.pending_writes.get(key)
715
811
  if pending is not None:
716
812
  # A disk failure after an answer must not strand a permanently
717
813
  # running receipt. The next client read retries only this write,
718
814
  # never the provider request or its tools.
719
- self.store.save(*key, pending)
815
+ self._save(key, pending)
720
816
  self.pending_writes.pop(key, None)
721
817
  return self.store.load(*key)
722
818
 
@@ -731,34 +827,63 @@ class SyncedSideChats:
731
827
  with suppress(Exception):
732
828
  await self.notify(document["session_id"], {
733
829
  "type": "side_chat_updated", "session_id": document["session_id"],
830
+ "side_chat_id": document["side_chat_id"], "conversation_id": document["conversation_id"],
734
831
  "revision": document["revision"],
735
832
  })
736
833
 
737
- async def snapshot(self, owner, session):
738
- async with self._lock((owner, session)):
739
- document = self._load((owner, session))
834
+ async def snapshot(self, owner, session, side_chat_id=None):
835
+ key = self.store.key_for_id(owner, session, side_chat_id) if side_chat_id is not None else (owner, session)
836
+ return await self._snapshot_key(key, side_chat_id)
837
+
838
+ async def _snapshot_key(self, key, side_chat_id=None):
839
+ async with self._lock(key):
840
+ document = self._load(key)
841
+ if side_chat_id is not None and document["side_chat_id"] != side_chat_id:
842
+ raise SideQuestionError(409, "Side chat was cleared; refresh the side chat list")
740
843
  if "model" not in document and self.runtime_settings_for_session is not None:
741
844
  # Retained history stays readable when provider credentials,
742
845
  # endpoint configuration or model discovery are unavailable.
743
846
  settings = {}
744
847
  with suppress(Exception):
745
- settings = self.runtime_settings_for_session(session)
848
+ settings = self.runtime_settings_for_session(key[1])
746
849
  if settings:
747
850
  document.update(settings)
748
851
  document["revision"] += 1
749
- self.store.save(owner, session, document)
852
+ self._save(key, document)
750
853
  return self.public(document)
751
854
 
855
+ async def list_chats(self, owner, session):
856
+ chats = []
857
+ for key in self.store.keys(owner, session):
858
+ async with self._lock(key):
859
+ chats.append(self.public(self._load(key)))
860
+ return {"session_id": session, "side_chats": chats}
861
+
862
+ async def create(self, owner, session, side_chat_id=None):
863
+ if self.stopping:
864
+ raise SideQuestionError(503, "Server is shutting down")
865
+ if self.admission_check is not None:
866
+ self.admission_check()
867
+ side_chat_id = side_chat_id or uuid.uuid4().hex
868
+ # Creation has no await before its atomic write. It neither opens a
869
+ # provider nor changes the default conversation used by older apps.
870
+ document = self.store.create(owner, session, side_chat_id)
871
+ await self._changed(document)
872
+ return await self.snapshot(owner, session, side_chat_id)
873
+
752
874
  async def submit(self, owner, session, request_id, question, side_chat_id, after_request_id=None, runtime_settings=None):
753
875
  runtime_settings = validate_runtime_settings(runtime_settings or {})
754
- key = (owner, session)
876
+ try:
877
+ key = self.store.key_for_id(owner, session, side_chat_id)
878
+ except SideQuestionError:
879
+ raise SideQuestionError(409, "Side chat was cleared; refresh before sending") from None
755
880
  async with self._lock(key):
756
881
  if self.stopping:
757
882
  raise SideQuestionError(503, "Server is shutting down")
758
883
  if self.admission_check is not None:
759
884
  self.admission_check()
760
885
  document = self._load(key)
761
- previous = self.store.receipt(*key, request_id)
886
+ previous = self.store.receipt(owner, session, request_id)
762
887
  if previous is not None:
763
888
  if previous != (side_chat_id, request_digest(question, runtime_settings)) or document["side_chat_id"] != side_chat_id:
764
889
  raise SideQuestionError(409, "Request ID belongs to a different or cleared side chat")
@@ -777,7 +902,7 @@ class SyncedSideChats:
777
902
  **({"runtime_settings": runtime_settings} if runtime_settings else {})}
778
903
  document["exchanges"].append(exchange)
779
904
  document["revision"] += 1
780
- self.store.save(*key, document, receipt=exchange)
905
+ self._save(key, document, receipt=exchange)
781
906
  timer = self.timers.pop(key, None)
782
907
  if timer is not None:
783
908
  timer.cancel()
@@ -804,7 +929,7 @@ class SyncedSideChats:
804
929
  document.update(settings)
805
930
  if changed:
806
931
  document["revision"] += 1
807
- self.store.save(*key, document)
932
+ self._save(key, document)
808
933
  if changed:
809
934
  await self._changed(document)
810
935
 
@@ -819,7 +944,7 @@ class SyncedSideChats:
819
944
  exchange.update(activity=activity, updated_at=side_chat_timestamp())
820
945
  document["revision"] += 1
821
946
  try:
822
- self.store.save(*key, document)
947
+ self._save(key, document)
823
948
  self.pending_writes.pop(key, None)
824
949
  except (OSError, sqlite3.Error):
825
950
  self.pending_writes[key] = document
@@ -874,8 +999,6 @@ class SyncedSideChats:
874
999
  self.cleanup_tasks.discard(cleanup)
875
1000
  if self.tasks.get(key) is asyncio.current_task():
876
1001
  self.tasks.pop(key, None)
877
- if not self.stopping:
878
- self.timers[key] = asyncio.get_running_loop().call_later(NATIVE_IDLE_SECONDS, self._expire, key)
879
1002
 
880
1003
  async def _finish(self, key, side_chat_id, request_id, status, **result):
881
1004
  async with self._lock(key):
@@ -890,7 +1013,7 @@ class SyncedSideChats:
890
1013
  document["last_request_id"] = request_id
891
1014
  document["revision"] += 1
892
1015
  try:
893
- self.store.save(*key, document)
1016
+ self._save(key, document)
894
1017
  self.pending_writes.pop(key, None)
895
1018
  except (OSError, sqlite3.Error):
896
1019
  self.pending_writes[key] = document
@@ -906,8 +1029,12 @@ class SyncedSideChats:
906
1029
  self.cleanup_tasks.add(task)
907
1030
  task.add_done_callback(lambda done: (self.cleanup_tasks.discard(done), None if done.cancelled() else done.exception()))
908
1031
 
909
- async def cancel(self, owner, session, request_id):
910
- key = (owner, session)
1032
+ async def cancel(self, owner, session, request_id, side_chat_id=None):
1033
+ receipt = self.store.receipt(owner, session, request_id)
1034
+ if side_chat_id is not None and receipt is not None and receipt[0] != side_chat_id:
1035
+ raise SideQuestionError(409, "Request belongs to a different side chat")
1036
+ target_id = side_chat_id or (receipt[0] if receipt is not None else None)
1037
+ key = self.store.key_for_id(owner, session, target_id) if target_id is not None else (owner, session)
911
1038
  async with self._lock(key):
912
1039
  # Pending progress may be unsaved while provider work is active.
913
1040
  # Storage recovery must not gate the operator's Stop intent.
@@ -916,8 +1043,8 @@ class SyncedSideChats:
916
1043
  if exchange is None:
917
1044
  # Stop can overtake submission in transit. Preserve an opaque
918
1045
  # receipt so the late POST cannot start provider/tool work.
919
- if self.store.receipt(*key, request_id) is None:
920
- self.store.save(*key, document, receipt={"request_id": request_id, "question": ""})
1046
+ if self.store.receipt(owner, session, request_id) is None:
1047
+ self._save(key, document, receipt={"request_id": request_id, "question": ""})
921
1048
  return self.public(document)
922
1049
  if exchange["status"] != "running":
923
1050
  return self.public(self._load(key))
@@ -934,7 +1061,7 @@ class SyncedSideChats:
934
1061
  document["last_request_id"] = request_id
935
1062
  document["revision"] += 1
936
1063
  try:
937
- self.store.save(*key, document)
1064
+ self._save(key, document)
938
1065
  self.pending_writes.pop(key, None)
939
1066
  except (OSError, sqlite3.Error):
940
1067
  self.pending_writes[key] = document
@@ -943,10 +1070,14 @@ class SyncedSideChats:
943
1070
  if task is not None:
944
1071
  await asyncio.shield(asyncio.gather(task, return_exceptions=True))
945
1072
  await self._changed(document)
946
- return await self.snapshot(*key)
1073
+ return await self._snapshot_key(key)
947
1074
 
948
1075
  async def clear(self, owner, session, side_chat_id):
949
- key = (owner, session)
1076
+ try:
1077
+ key = self.store.key_for_id(owner, session, side_chat_id)
1078
+ except SideQuestionError:
1079
+ # Preserve the original singleton API's harmless stale Clear.
1080
+ return await self.snapshot(owner, session)
950
1081
  async with self._lock(key):
951
1082
  # Preserve the new conversation fence even if progress storage
952
1083
  # is unavailable; still retire the old provider immediately.
@@ -960,7 +1091,7 @@ class SyncedSideChats:
960
1091
  document.pop("effort", None)
961
1092
  document["revision"] += 1
962
1093
  try:
963
- self.store.save(*key, document)
1094
+ self._save(key, document)
964
1095
  self.pending_writes.pop(key, None)
965
1096
  except (OSError, sqlite3.Error):
966
1097
  self.pending_writes[key] = document
@@ -973,7 +1104,7 @@ class SyncedSideChats:
973
1104
  if handle is not None:
974
1105
  await handle.close()
975
1106
  await self._changed(document)
976
- return await self.snapshot(*key)
1107
+ return await self._snapshot_key(key)
977
1108
 
978
1109
  async def close(self):
979
1110
  self.stopping = True
@@ -1053,7 +1184,7 @@ def create_side_question_router(*, authorize, session_exists, runtime: SideQuest
1053
1184
  if not isinstance(request_id, str) or not IDENTIFIER.fullmatch(request_id):
1054
1185
  raise HTTPException(400, "Invalid side question request ID")
1055
1186
  if not isinstance(question, str) or not question.strip() or len(question) > MAX_QUESTION_CHARS:
1056
- raise HTTPException(400, "Question must contain 1 to 8000 characters")
1187
+ raise HTTPException(400, f"Question must contain 1 to {MAX_QUESTION_CHARS} characters")
1057
1188
  try:
1058
1189
  question.encode("utf-8")
1059
1190
  except UnicodeEncodeError:
@@ -1126,6 +1257,39 @@ def create_side_question_router(*, authorize, session_exists, runtime: SideQuest
1126
1257
  owner = guard(request, session_id)
1127
1258
  return await synced_response(synced_runtime().snapshot(owner, session_id))
1128
1259
 
1260
+ @router.get("/api/sessions/{session_id}/side-chats")
1261
+ async def list_synced(session_id: str, request: Request):
1262
+ owner = guard(request, session_id)
1263
+ return await synced_response(synced_runtime().list_chats(owner, session_id))
1264
+
1265
+ @router.post("/api/sessions/{session_id}/side-chats")
1266
+ async def create_synced(session_id: str, request: Request):
1267
+ owner = guard(request, session_id)
1268
+ async def body():
1269
+ data = bytearray()
1270
+ async for chunk in request.stream():
1271
+ if len(data) + len(chunk) > 2048:
1272
+ raise HTTPException(413, "Side chat request is too large")
1273
+ data.extend(chunk)
1274
+ return json.loads(data or b"{}")
1275
+ try:
1276
+ value = await asyncio.wait_for(body(), 10)
1277
+ except (ValueError, UnicodeError, RecursionError):
1278
+ raise HTTPException(400, "Invalid side chat request") from None
1279
+ except asyncio.TimeoutError:
1280
+ raise HTTPException(408, "Side chat request was not received") from None
1281
+ if not isinstance(value, dict) or set(value) - {"side_chat_id"}:
1282
+ raise HTTPException(400, "Invalid side chat fields")
1283
+ side_chat_id = value.get("side_chat_id")
1284
+ if "side_chat_id" in value and (not isinstance(side_chat_id, str) or not IDENTIFIER.fullmatch(side_chat_id)):
1285
+ raise HTTPException(400, "Invalid side conversation ID")
1286
+ return await synced_response(synced_runtime().create(owner, session_id, side_chat_id), status_code=201)
1287
+
1288
+ @router.get("/api/sessions/{session_id}/side-chats/{side_chat_id}")
1289
+ async def get_selected_synced(session_id: str, side_chat_id: str, request: Request):
1290
+ owner = guard(request, session_id, side_chat_id)
1291
+ return await synced_response(synced_runtime().snapshot(owner, session_id, side_chat_id))
1292
+
1129
1293
  @router.post("/api/sessions/{session_id}/side-chat")
1130
1294
  async def post_synced(session_id: str, request: Request):
1131
1295
  owner = guard(request, session_id)
@@ -1152,7 +1316,7 @@ def create_side_question_router(*, authorize, session_exists, runtime: SideQuest
1152
1316
  raise HTTPException(400, "Invalid side conversation ID")
1153
1317
  question = value["question"]
1154
1318
  if not isinstance(question, str) or not question.strip() or len(question) > MAX_QUESTION_CHARS:
1155
- raise HTTPException(400, "Question must contain 1 to 8000 characters")
1319
+ raise HTTPException(400, f"Question must contain 1 to {MAX_QUESTION_CHARS} characters")
1156
1320
  try:
1157
1321
  question.encode("utf-8")
1158
1322
  except UnicodeEncodeError:
@@ -1164,7 +1328,10 @@ def create_side_question_router(*, authorize, session_exists, runtime: SideQuest
1164
1328
  @router.delete("/api/sessions/{session_id}/side-chat/requests/{request_id}")
1165
1329
  async def cancel_synced(session_id: str, request_id: str, request: Request):
1166
1330
  owner = guard(request, session_id, request_id)
1167
- return await synced_response(synced_runtime().cancel(owner, session_id, request_id))
1331
+ side_chat_id = request.query_params.get("side_chat_id")
1332
+ if side_chat_id is not None and not IDENTIFIER.fullmatch(side_chat_id):
1333
+ raise HTTPException(400, "Invalid side conversation ID")
1334
+ return await synced_response(synced_runtime().cancel(owner, session_id, request_id, side_chat_id))
1168
1335
 
1169
1336
  @router.delete("/api/sessions/{session_id}/side-chat/{side_chat_id}")
1170
1337
  async def clear_synced(session_id: str, side_chat_id: str, request: Request):
@@ -281,7 +281,7 @@ class _RecordParser:
281
281
  def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
282
282
  require_newline=True, max_records=250_000, deadline=None,
283
283
  cancelled=None, max_retained_bytes=MAX_RETAINED_BYTES, retained_fields=None,
284
- max_nodes=-1, max_depth=None):
284
+ max_nodes=-1, max_depth=None, allow_nul_padding=False):
285
285
  """Yield (projected object or None, ending offset, RawRecord).
286
286
 
287
287
  Malformed provider lines may be represented by None, as before. Resource
@@ -289,6 +289,8 @@ def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
289
289
  A fixed end excludes concurrent appends; callers own file identity checks.
290
290
  Native-import work budgets remain the default. Durable metadata-only scans
291
291
  can supply separate structural limits without imposing import caps on logs.
292
+ Native Claude recovery can explicitly accept NUL-only padding lines. They
293
+ provide no event or ownership evidence, but retain their exact raw receipt.
292
294
  """
293
295
  # Externally supplied deadlines can belong to a larger operation. Do not
294
296
  # invent a duration for them; the caller can provide its own timeout detail.
@@ -306,14 +308,23 @@ def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
306
308
  parser = _RecordParser(stream, end, deadline, cancelled, project, max_retained_bytes, budget_seconds, retained_fields, max_nodes, max_depth)
307
309
  blank = False
308
310
  malformed = False
311
+ nul_padding = False
309
312
  try:
310
313
  try:
311
- parser.space()
312
- blank = parser.peek() is None
313
- value = None if blank else parser.value()
314
- parser.space()
315
- if parser.peek() is not None:
316
- raise InvalidRecord('trailing JSON content')
314
+ if allow_nul_padding and parser.peek() == 0:
315
+ while parser.peek() == 0:
316
+ parser.index += 1
317
+ if parser.take() != 10 or parser.peek() is not None:
318
+ raise InvalidRecord('invalid NUL padding record')
319
+ nul_padding = malformed = True
320
+ value = None
321
+ else:
322
+ parser.space()
323
+ blank = parser.peek() is None
324
+ value = None if blank else parser.value()
325
+ parser.space()
326
+ if parser.peek() is not None:
327
+ raise InvalidRecord('trailing JSON content')
317
328
  except (InvalidRecord, UnicodeDecodeError, json.JSONDecodeError) as error:
318
329
  if strict:
319
330
  raise ValueError('malformed transcript record') from error
@@ -329,6 +340,6 @@ def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
329
340
  raise ValueError('transcript cursor does not end on a complete line')
330
341
  raw = RawRecord(stream, start, stop, parser.complete, blank, malformed or blank,
331
342
  deadline, cancelled, count, budget_seconds)
332
- if strict and not isinstance(value, dict):
343
+ if strict and not isinstance(value, dict) and not nul_padding:
333
344
  raise ValueError('transcript object expected')
334
345
  yield value if isinstance(value, dict) else None, stop, raw