Repository navigation
Expand file tree
/
Copy pathsessions.py
More file actions
2265 lines (1892 loc) · 82.4 KB
/
Copy pathsessions.py
File metadata and controls
2265 lines (1892 loc) · 82.4 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
"""Thread management using LangGraph's built-in checkpoint persistence."""
from __future__ import annotations
import asyncio
import contextlib
import json
import logging
import sqlite3
import time
from contextlib import asynccontextmanager
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, NamedTuple, NotRequired, TypedDict, cast
from deepagents_code._constants import DEFAULT_THREAD_LIMIT
from deepagents_code._paths import harden_state_dir
from deepagents_code.goal_state_notice import is_internal_message
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Mapping
import aiosqlite
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from deepagents_code.output import OutputFormat
logger = logging.getLogger(__name__)
_aiosqlite_patched = False
_jsonplus_serializer: JsonPlusSerializer | None = None
_message_count_cache: dict[str, tuple[str | None, int]] = {}
_MAX_MESSAGE_COUNT_CACHE = 4096
_initial_prompt_cache: dict[str, tuple[str | None, str | None]] = {}
_MAX_INITIAL_PROMPT_CACHE = 4096
_recent_threads_cache: dict[tuple[str | None, int], list[ThreadInfo]] = {}
_MAX_RECENT_THREADS_CACHE_KEYS = 16
MAX_THREAD_NAME_LENGTH = 50
_DEFAULT_SQLITE_TIMEOUT = 5.0
"""Seconds to wait out a locked database; matches the `sqlite3` default."""
def _patch_aiosqlite() -> None:
"""Patch aiosqlite.Connection with `is_alive()` if missing.
Required by langgraph-checkpoint>=2.1.0.
See: https://github.com/langchain-ai/langgraph/issues/6583
"""
global _aiosqlite_patched # noqa: PLW0603 # Module-level flag requires global statement
if _aiosqlite_patched:
return
import aiosqlite as _aiosqlite
if not hasattr(_aiosqlite.Connection, "is_alive"):
def _is_alive(self: _aiosqlite.Connection) -> bool:
"""Check if the connection is still alive.
Returns:
True if connection is alive, False otherwise.
"""
return bool(self._running and self._connection is not None)
# Dynamically adding a method to aiosqlite.Connection at runtime.
# Type checkers can't understand this monkey-patch, so we suppress the
# "attr-defined" error that would otherwise be raised.
_aiosqlite.Connection.is_alive = _is_alive # ty: ignore[unresolved-attribute]
_aiosqlite_patched = True
async def _drain_aiosqlite_worker(conn: aiosqlite.Connection) -> None:
"""Join the aiosqlite worker thread after its connection is closed.
`aiosqlite.Connection` wraps a daemon `Thread` (`conn._thread`) that
drains its tx queue independently of the caller's event loop. The
library's `close()` puts a stop sentinel on the queue and awaits the
sentinel's future, but does not explicitly join the worker thread.
If the connection is leaked (no explicit close) and the surrounding
event loop has already shut down, the worker can still pop a queued
item (typically from `Connection.__del__` calling `stop()`) and call
`future.get_loop().call_soon_threadsafe(...)` on the closed loop. That
raises `RuntimeError: Event loop is closed`, which pytest surfaces as
`PytestUnhandledThreadExceptionWarning` (and GitHub Actions then
surfaces as a workflow annotation).
Explicitly joining the worker thread after close guarantees it has
exited before this coroutine returns, eliminating the race for any
connection routed through `_connect` / `get_checkpointer`.
"""
worker = getattr(conn, "_thread", None)
if worker is None or not worker.is_alive():
return
# `RuntimeError` covers the "thread was never started" case; treat as
# already drained.
with contextlib.suppress(RuntimeError):
await asyncio.to_thread(worker.join, 5.0)
def _guard_sqlite_handle(conn: aiosqlite.Connection) -> None:
"""Keep the sqlite handle closable when the opening task is cancelled.
`aiosqlite` opens the database on its worker thread and delivers the raw
`sqlite3.Connection` back through a future, recording it on the
`Connection` only once the awaiting coroutine resumes. Background workers
are routinely cancelled at app exit, and a cancel landing anywhere in that
window leaves the handle unreachable from the cleanup that follows:
- Cancelled while the worker is still opening, the library has no handle
recorded yet, so the cleanup it queues closes nothing.
- Cancelled after the handle is delivered but before the coroutine resumes,
the library clears its own record before that queued cleanup can run, so
again it closes nothing.
Either way the garbage collector is left to report `ResourceWarning:
unclosed database`. Recording the handle from the worker thread covers the
first case; queueing an explicit close ahead of the library's own cleanup
covers the second. Both run on the thread that opened the handle, and
closing twice is a no-op, so neither disturbs a normal shutdown.
Args:
conn: A connection that has not been opened yet.
"""
# No public hooks for any of this, so tolerate it moving: the leak avoided
# here is a warning at teardown, not something worth failing a query for.
connector = getattr(conn, "_connector", None)
queue = getattr(conn, "_tx", None)
stop = getattr(conn, "stop", None)
if connector is None or queue is None or stop is None:
logger.debug("aiosqlite internals moved; cannot guard the sqlite handle")
return
def open_and_record() -> sqlite3.Connection:
handle = connector()
# The assignment aiosqlite makes once the awaiting coroutine resumes,
# made early enough that a cancel cannot get in front of it.
conn._connection = handle
return handle
def stop_and_close() -> asyncio.Future[Any] | None:
# Runs before aiosqlite drops its own reference, so the handle is still
# here to queue a close for -- ahead of the stop sentinel, which ends
# the worker loop. A `None` future keeps the worker from reaching for an
# event loop that may already be gone.
handle = conn._connection
if handle is not None:
queue.put_nowait((None, handle.close))
return stop()
conn._connector = open_and_record
# Shadows the bound method on this one instance; the declared type is the
# unbound `stop(self)`, which a zero-argument replacement cannot match.
conn.stop = stop_and_close # ty: ignore[invalid-assignment]
def _new_connection(timeout: float = _DEFAULT_SQLITE_TIMEOUT) -> aiosqlite.Connection:
"""Build an unopened connection to the sessions database.
Args:
timeout: Seconds to wait out a locked database before giving up.
Returns:
A connection that closes its sqlite handle even when interrupted.
"""
import aiosqlite as _aiosqlite
_patch_aiosqlite()
conn = _aiosqlite.connect(str(get_db_path()), timeout=timeout)
_guard_sqlite_handle(conn)
return conn
@asynccontextmanager
async def _connect() -> AsyncIterator[aiosqlite.Connection]:
"""Import aiosqlite, apply the compatibility patch, and connect.
Centralizes the deferred import + patch + connect sequence used by every
database function in this module.
Yields:
An open aiosqlite connection to the sessions database.
"""
conn = _new_connection(timeout=30.0)
try:
async with conn as opened:
yield opened
finally:
await _drain_aiosqlite_worker(conn)
class ThreadInfo(TypedDict):
"""Thread metadata returned by `list_threads`."""
thread_id: str
"""Unique identifier for the thread."""
agent_name: str | None
"""Name of the agent that owns the thread."""
updated_at: str | None
"""ISO timestamp of the last update."""
created_at: NotRequired[str | None]
"""ISO timestamp of thread creation (earliest checkpoint)."""
git_branch: NotRequired[str | None]
"""Git branch active when the thread was created."""
initial_prompt: NotRequired[str | None]
"""First human message in the thread."""
thread_name: NotRequired[str | None]
"""User-assigned or generated thread name."""
message_count: NotRequired[int]
"""Number of messages in the thread."""
latest_checkpoint_id: NotRequired[str | None]
"""Most recent checkpoint ID for cache invalidation."""
cwd: NotRequired[str | None]
"""Working directory where the thread was last used."""
class _CheckpointSummary(NamedTuple):
"""Structured data extracted from a thread's latest checkpoint."""
message_count: int | None
"""Number of messages inlined in the latest checkpoint, or `None`.
`None` means the latest checkpoint did not inline the `messages` channel
value, so the count is unknown and must be reconstructed from the `writes`
table. This happens when `messages` uses a `DeltaChannel` (a LangGraph
channel the deepagents SDK applies to `messages` as of v0.6) and the latest
checkpoint falls between periodic snapshots. An `int` (including `0`) is a
trustworthy count.
"""
initial_prompt: str | None
"""First human prompt recovered from the latest checkpoint."""
def format_timestamp(iso_timestamp: str | None) -> str:
"""Format ISO timestamp for display (e.g., 'dec 05, 6:10pm').
Args:
iso_timestamp: ISO 8601 timestamp string, or `None`.
Returns:
Formatted timestamp string or empty string if invalid.
"""
if not iso_timestamp:
return ""
try:
dt = datetime.fromisoformat(iso_timestamp).astimezone()
except (ValueError, TypeError):
logger.debug(
"Failed to parse timestamp %r; displaying as blank",
iso_timestamp,
exc_info=True,
)
return ""
# `%-I` (12-hour clock, no zero padding) is a glibc/BSD extension. MSVC's
# CRT rejects it as an invalid formatting code, which CPython surfaces as
# `ValueError`, so the hour is derived by hand to keep every platform on
# the same rendering.
hour_12 = dt.hour % 12 or 12
return f"{dt:%b %d}, {hour_12}:{dt:%M}{dt:%p}".lower()
def format_relative_timestamp(iso_timestamp: str | None) -> str:
"""Format ISO timestamp as relative time (e.g., '5m ago', '2h ago').
Args:
iso_timestamp: ISO 8601 timestamp string, or `None`.
Returns:
Relative time string or empty string if invalid.
"""
if not iso_timestamp:
return ""
try:
dt = datetime.fromisoformat(iso_timestamp).astimezone()
except (ValueError, TypeError):
logger.debug(
"Failed to parse timestamp %r; displaying as blank",
iso_timestamp,
exc_info=True,
)
return ""
delta = datetime.now(tz=dt.tzinfo) - dt
seconds = int(delta.total_seconds())
if seconds < 0:
return "just now"
if seconds < 60: # noqa: PLR2004
return f"{seconds}s ago"
minutes = seconds // 60
if minutes < 60: # noqa: PLR2004
return f"{minutes}m ago"
hours = minutes // 60
if hours < 24: # noqa: PLR2004
return f"{hours}h ago"
days = hours // 24
if days < 30: # noqa: PLR2004
return f"{days}d ago"
if days < 365: # noqa: PLR2004
months = days // 30
return f"{months}mo ago"
years = days // 365
return f"{years}y ago"
def format_path(path: str | None) -> str:
"""Format a filesystem path for display.
Paths under the user's home directory are shown relative to `~`.
All other paths are returned as-is.
Args:
path: Absolute filesystem path, or `None`.
Returns:
Formatted path string, or empty string if path is falsy.
"""
if not path:
return ""
try:
home = str(Path.home())
if path == home:
return "~"
prefix = home + "/"
if path.startswith(prefix):
return "~/" + path[len(prefix) :]
except (RuntimeError, KeyError, OSError):
logger.debug(
"Could not resolve home directory for path formatting", exc_info=True
)
return path
else:
return path
_db_path: Path | None = None
def get_db_path() -> Path:
"""Get path to global database.
The result is cached after the first successful call to avoid repeated
filesystem operations.
Returns:
Path to the SQLite database file.
"""
global _db_path # noqa: PLW0603 # Module-level cache requires global statement
if _db_path is not None:
return _db_path
from deepagents_code.model_config import DEFAULT_STATE_DIR
# Pass the directory rather than letting it default to
# `PATHS.profile.state_dir`: the database has always been located from
# `DEFAULT_STATE_DIR`, and tests patch that name on its own.
harden_state_dir(DEFAULT_STATE_DIR)
_db_path = DEFAULT_STATE_DIR / "sessions.db"
return _db_path
def generate_thread_id() -> str:
"""Generate a new thread ID as a full UUID7 string.
Returns:
UUID7 string (time-ordered for natural sort by creation time).
"""
from uuid_utils import uuid7
return str(uuid7())
async def _table_exists(conn: aiosqlite.Connection, table: str) -> bool:
"""Check if a table exists in the database.
Returns:
True if table exists, False otherwise.
"""
query = "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?"
async with conn.execute(query, (table,)) as cursor:
return await cursor.fetchone() is not None
_THREADS_LIST_INDEX = "idx_dcode_threads_list_v2"
"""Covering index that makes the `list_threads` GROUP BY an index-only scan.
LangGraph's `SqliteSaver` stores each checkpoint's full state blob inline in the
`checkpoints` row alongside the small `metadata` field. The thread-list query
only needs `metadata` (per-thread latest `updated_at`, `agent_name`, etc.), but
without a covering index SQLite scans the whole table — dragging every state
blob through I/O. On a large profile (e.g. ~12 GB of blobs) that scan takes
tens of seconds. This index carries exactly the expressions the query reads, so
the planner satisfies the GROUP BY from the index alone and never touches the
blob-bearing rows, turning a ~60 s scan into a sub-second lookup.
The column order (leading `thread_id`) also lets the GROUP BY consume the index
in order. Keep the indexed expressions in sync with the `list_threads` query.
"""
async def _ensure_threads_list_index(conn: aiosqlite.Connection) -> None:
"""Create the `list_threads` covering index if it does not already exist.
Reuse either v2 or its v3 superset from early thread-naming builds. Rebuilding
it to include names can hold the write lock past workspace binding's timeout.
Names are loaded separately for the displayed threads instead.
The one-time build on a pre-existing large database costs a
single full table scan (seconds to tens of seconds), after which every
`list_threads` call is a sub-second index-only scan. Runs in the aiosqlite
worker thread, so it does not block the event loop.
A failure here is non-fatal: the list query still returns correct results via
the slower table scan, so we log and continue rather than break `threads
list` (e.g. on a read-only database or under write-lock contention).
"""
try:
async with conn.execute(
"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name IN (?, ?)",
(_THREADS_LIST_INDEX, "idx_dcode_threads_list_v3"),
) as cursor:
if await cursor.fetchone():
return
await conn.execute(
f"CREATE INDEX IF NOT EXISTS {_THREADS_LIST_INDEX} ON checkpoints("
"thread_id, "
"json_extract(metadata, '$.updated_at'), "
"COALESCE(json_extract(metadata, '$.created_at'), "
"json_extract(metadata, '$.updated_at')), "
"checkpoint_id, "
"json_extract(metadata, '$.agent_name'), "
"json_extract(metadata, '$.git_branch'), "
"json_extract(metadata, '$.cwd'))"
)
# Replace the older index, which did not cover the creation timestamp.
await conn.execute("DROP INDEX IF EXISTS idx_dcode_threads_list")
await conn.commit()
except Exception:
logger.warning(
"Failed to create the %s index; `threads list` will fall back to a "
"full table scan and may be slow on large databases",
_THREADS_LIST_INDEX,
exc_info=True,
)
async def _populate_thread_names(
conn: aiosqlite.Connection, threads: list[ThreadInfo]
) -> None:
"""Load names after limiting the list, keeping its covering index unchanged."""
names: dict[str, str | None] = {}
if await _table_exists(conn, "dcode_thread_names"):
async with conn.execute(
"SELECT thread_id, name FROM dcode_thread_names "
"WHERE thread_id IN (SELECT value FROM json_each(?))",
(json.dumps([thread["thread_id"] for thread in threads]),),
) as cursor:
names = {row[0]: row[1] for row in await cursor.fetchall()}
missing = [
thread["thread_id"] for thread in threads if thread["thread_id"] not in names
]
if missing:
names.update(await _checkpoint_thread_names(conn, missing))
for thread in threads:
thread["thread_name"] = names.get(thread["thread_id"])
async def _checkpoint_thread_names(
conn: aiosqlite.Connection, thread_ids: list[str]
) -> dict[str, str | None]:
"""Read names from the latest root checkpoints of the requested threads.
Saved names come from `dcode_thread_names`; this fallback is for checkpoint
metadata only. Seek via the primary key instead of scanning an unnamed
thread's entire history looking for a non-null name.
Returns:
Names found in the latest checkpoints, keyed by thread ID.
"""
async with conn.execute(
"SELECT value, (SELECT json_extract(metadata, '$.thread_name') "
"FROM checkpoints WHERE thread_id = requested.value "
"AND checkpoint_ns = '' "
"ORDER BY checkpoint_id DESC LIMIT 1) FROM json_each(?) AS requested",
(json.dumps(thread_ids),),
) as cursor:
return {row[0]: row[1] for row in await cursor.fetchall()}
async def list_threads(
agent_name: str | None = None,
limit: int = DEFAULT_THREAD_LIMIT,
include_message_count: bool = False,
sort_by: str = "updated",
branch: str | None = None,
cwd: str | None = None,
) -> list[ThreadInfo]:
"""List threads from checkpoints table.
Args:
agent_name: Optional filter by agent name.
limit: Maximum number of threads to return.
include_message_count: Whether to include message counts.
sort_by: Sort field — `"updated"` or `"created"`.
branch: Optional filter by git branch name.
cwd: Optional filter by working directory. Only threads whose stored
`cwd` metadata equals this path are returned. Matching is an
exact string comparison — no path normalization, symlink
resolution, or prefix matching. Threads without a stored `cwd`
(older rows) are excluded.
Returns:
List of `ThreadInfo` dicts with `thread_id`, `agent_name`,
`updated_at`, `created_at`, `latest_checkpoint_id`, `git_branch`,
`cwd`, and optionally `message_count`.
Raises:
ValueError: If `sort_by` is not `"updated"` or `"created"`.
"""
started_at = time.perf_counter()
async with _connect() as conn:
if not await _table_exists(conn, "checkpoints"):
logger.debug(
"Thread metadata listing completed in %.1f ms: rows=0",
(time.perf_counter() - started_at) * 1000,
)
return []
# Ensure the covering index exists before the GROUP BY below, so the
# query is an index-only scan instead of a full scan over the (large,
# blob-bearing) checkpoints table.
await _ensure_threads_list_index(conn)
if sort_by not in {"updated", "created"}:
msg = f"Invalid sort_by {sort_by!r}; expected 'updated' or 'created'"
raise ValueError(msg)
order_col = "created_at" if sort_by == "created" else "updated_at"
where_clauses: list[str] = []
params_list: list[str | int] = []
if agent_name:
where_clauses.append("json_extract(metadata, '$.agent_name') = ?")
params_list.append(agent_name)
if branch:
where_clauses.append("json_extract(metadata, '$.git_branch') = ?")
params_list.append(branch)
if cwd:
where_clauses.append("json_extract(metadata, '$.cwd') = ?")
params_list.append(cwd)
where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
query = f"""
SELECT thread_id,
json_extract(metadata, '$.agent_name') as agent_name,
MAX(json_extract(metadata, '$.updated_at')) as updated_at,
MAX(checkpoint_id) as latest_checkpoint_id,
MIN(COALESCE(json_extract(metadata, '$.created_at'),
json_extract(metadata, '$.updated_at'))) as created_at,
MAX(json_extract(metadata, '$.git_branch')) as git_branch,
MAX(json_extract(metadata, '$.cwd')) as cwd
FROM checkpoints
{where_sql}
GROUP BY thread_id
ORDER BY {order_col} DESC
LIMIT ?
""" # noqa: S608 # where_sql/order_col derived from controlled internal values; user values use ? placeholders
params: tuple = (*params_list, limit)
async with conn.execute(query, params) as cursor:
rows = await cursor.fetchall()
threads: list[ThreadInfo] = [
ThreadInfo(
thread_id=r[0],
agent_name=r[1],
updated_at=r[2],
latest_checkpoint_id=r[3],
created_at=r[4],
git_branch=r[5],
cwd=r[6],
)
for r in rows
]
if threads:
await _populate_thread_names(conn, threads)
# Fetch message counts if requested
if include_message_count and threads:
await _populate_message_counts(conn, threads)
# Only cache unfiltered results so the thread selector modal
# doesn't receive branch-/cwd-filtered or differently-sorted data.
if sort_by == "updated" and branch is None and cwd is None:
_cache_recent_threads(agent_name, limit, threads)
logger.debug(
"Thread metadata listing completed in %.1f ms: rows=%d sort=%s",
(time.perf_counter() - started_at) * 1000,
len(threads),
sort_by,
)
return threads
async def populate_thread_checkpoint_details(
threads: list[ThreadInfo],
*,
include_message_count: bool = True,
include_initial_prompt: bool = True,
) -> list[ThreadInfo]:
"""Populate checkpoint-derived fields for an existing thread list.
This is used by the `/threads` modal to enrich rows in one background pass,
so the latest checkpoint is fetched and deserialized at most once per row.
Args:
threads: Thread rows to enrich in place.
include_message_count: Whether to populate `message_count`.
include_initial_prompt: Whether to populate `initial_prompt`.
Returns:
The same list object with missing checkpoint-derived fields populated.
"""
if not threads or (not include_message_count and not include_initial_prompt):
return threads
return await _enrich_thread_checkpoint_details(
threads,
include_message_count=include_message_count,
include_initial_prompt=include_initial_prompt,
source="picker",
)
async def _enrich_thread_checkpoint_details(
threads: list[ThreadInfo],
*,
include_message_count: bool,
include_initial_prompt: bool,
source: str,
) -> list[ThreadInfo]:
"""Enrich threads and record the caller context for diagnostics.
Returns:
The enriched thread list.
"""
started_at = time.perf_counter()
async with _connect() as conn:
await _populate_checkpoint_fields(
conn,
threads,
include_message_count=include_message_count,
include_initial_prompt=include_initial_prompt,
)
logger.debug(
"Thread enrichment completed in %.1f ms: source=%s rows=%d "
"counts=%s prompts=%s",
(time.perf_counter() - started_at) * 1000,
source,
len(threads),
include_message_count,
include_initial_prompt,
)
return threads
async def prewarm_thread_message_counts(limit: int | None = None) -> None:
"""Prewarm thread selector cache for faster `/threads` open.
Fetches a bounded list of recent threads and populates checkpoint-derived
fields for currently visible columns into the in-memory cache. Intended to
run in a background worker during app startup and again whenever the
session database has changed (e.g. after a turn writes new checkpoints), so
the selector's first paint is never missing a thread the user just created.
Re-running this is cheap: the per-thread message-count and initial-prompt
caches are keyed on checkpoint freshness, so only threads whose latest
checkpoint changed are read back from disk.
Args:
limit: Maximum threads to prewarm. Uses `get_thread_limit()` when `None`.
"""
thread_limit = limit if limit is not None else get_thread_limit()
if thread_limit < 1:
return
try:
from deepagents_code.model_config import load_thread_config
cfg = load_thread_config()
threads = await list_threads(limit=thread_limit, include_message_count=False)
if threads:
await _enrich_thread_checkpoint_details(
threads,
include_message_count=cfg.columns.get("messages", False),
include_initial_prompt=cfg.columns.get("initial_prompt", False),
source="startup-prewarm",
)
_cache_recent_threads(None, thread_limit, threads)
except (OSError, sqlite3.Error):
logger.debug("Could not prewarm thread selector cache", exc_info=True)
except Exception:
logger.warning(
"Unexpected error while prewarming thread selector cache",
exc_info=True,
)
def get_cached_threads(
agent_name: str | None = None,
limit: int | None = None,
) -> list[ThreadInfo] | None:
"""Get cached recent threads, if available.
Args:
agent_name: Optional agent-name filter key.
limit: Maximum rows requested. Uses `get_thread_limit()` when `None`.
Returns:
Copy of cached rows when available, otherwise `None`.
"""
def _copy_with_cached_counts(rows: list[ThreadInfo]) -> list[ThreadInfo]:
copied_rows = _copy_threads(rows)
apply_cached_thread_message_counts(copied_rows)
apply_cached_thread_initial_prompts(copied_rows)
return copied_rows
thread_limit = limit if limit is not None else get_thread_limit()
if thread_limit < 1:
return None
exact = _recent_threads_cache.get((agent_name, thread_limit))
if exact is not None:
return _copy_with_cached_counts(exact)
best_key: tuple[str | None, int] | None = None
for key in _recent_threads_cache:
cache_agent, cache_limit = key
if cache_agent != agent_name or cache_limit < thread_limit:
continue
if best_key is None or cache_limit < best_key[1]:
best_key = key
if best_key is None:
return None
return _copy_with_cached_counts(_recent_threads_cache[best_key][:thread_limit])
def apply_cached_thread_message_counts(threads: list[ThreadInfo]) -> int:
"""Apply cached message counts onto thread rows when freshness matches.
Args:
threads: Thread rows to mutate in place.
Returns:
Number of rows that were populated from cache.
"""
populated = 0
for thread in threads:
if "message_count" in thread:
continue
thread_id = thread["thread_id"]
freshness = _thread_freshness(thread)
cached = _message_count_cache.get(thread_id)
if cached is None or cached[0] != freshness:
continue
thread["message_count"] = cached[1]
populated += 1
return populated
def apply_cached_thread_initial_prompts(threads: list[ThreadInfo]) -> int:
"""Apply cached initial prompts onto thread rows when freshness matches.
Args:
threads: Thread rows to mutate in place.
Returns:
Number of rows that were populated from cache.
"""
populated = 0
for thread in threads:
if "initial_prompt" in thread:
continue
thread_id = thread["thread_id"]
freshness = _thread_freshness(thread)
cached = _initial_prompt_cache.get(thread_id)
if cached is None or cached[0] != freshness:
continue
thread["initial_prompt"] = cached[1]
populated += 1
return populated
async def _populate_message_counts(
conn: aiosqlite.Connection,
threads: list[ThreadInfo],
) -> None:
"""Fill `message_count` on thread rows with cache-aware lookup."""
await _populate_checkpoint_fields(
conn,
threads,
include_message_count=True,
include_initial_prompt=False,
)
async def _get_jsonplus_serializer() -> JsonPlusSerializer:
"""Return a cached JsonPlus serializer, loading it off the UI loop."""
global _jsonplus_serializer # noqa: PLW0603 # Module-level cache requires global statement
if _jsonplus_serializer is not None:
return _jsonplus_serializer
started_at = time.perf_counter()
loop = asyncio.get_running_loop()
_jsonplus_serializer = await loop.run_in_executor(None, _create_jsonplus_serializer)
logger.debug(
"Thread serializer initialization completed in %.1f ms",
(time.perf_counter() - started_at) * 1000,
)
return _jsonplus_serializer
def _create_jsonplus_serializer() -> JsonPlusSerializer:
"""Import and create a JsonPlus serializer.
Returns:
A ready `JsonPlusSerializer` instance.
"""
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
return JsonPlusSerializer()
def _cache_message_count(thread_id: str, freshness: str | None, count: int) -> None:
"""Cache a thread's message count with a freshness token."""
if len(_message_count_cache) >= _MAX_MESSAGE_COUNT_CACHE and (
thread_id not in _message_count_cache
):
oldest = next(iter(_message_count_cache))
_message_count_cache.pop(oldest, None)
_message_count_cache[thread_id] = (freshness, count)
def _cache_initial_prompt(
thread_id: str,
freshness: str | None,
initial_prompt: str | None,
) -> None:
"""Cache a thread's initial prompt with a freshness token."""
if len(_initial_prompt_cache) >= _MAX_INITIAL_PROMPT_CACHE and (
thread_id not in _initial_prompt_cache
):
oldest = next(iter(_initial_prompt_cache))
_initial_prompt_cache.pop(oldest, None)
_initial_prompt_cache[thread_id] = (freshness, initial_prompt)
def _thread_freshness(thread: ThreadInfo) -> str | None:
"""Return a cache freshness token for a thread row.
The token is checkpoint-granular (`latest_checkpoint_id`). The
writes-reconstructed `message_count` includes pending writes on the latest
checkpoint, which in principle can change without a new checkpoint ID — so
this token does not capture intra-checkpoint write churn. In practice that
is benign: dcode only mutates `messages` through the agent graph, and every
batch of message writes culminates in a new checkpoint (each superstep,
`aupdate_state`, interrupt, and cancellation all advance
`latest_checkpoint_id`). The only window where a cached count can lag is
opening the `/threads` selector mid-superstep against an actively streaming
thread; the selector does not live-refresh, so that count stays put until
the modal is reopened (by then a new checkpoint exists and the cache
refreshes). Making the key write-sensitive would require probing the
`writes` table for every row on every `list_threads`, which is not worth it
for a cosmetic count.
"""
return thread.get("latest_checkpoint_id") or thread.get("updated_at")
def _cache_recent_threads(
agent_name: str | None,
limit: int,
threads: list[ThreadInfo],
) -> None:
"""Store a copy of recent thread rows for fast selector startup."""
key = (agent_name, max(1, limit))
if len(_recent_threads_cache) >= _MAX_RECENT_THREADS_CACHE_KEYS and (
key not in _recent_threads_cache
):
_recent_threads_cache.clear()
_recent_threads_cache[key] = _copy_threads(threads)
def _copy_threads(threads: list[ThreadInfo]) -> list[ThreadInfo]:
"""Return shallow-copied thread rows."""
return [ThreadInfo(**thread) for thread in threads]
async def _populate_checkpoint_fields(
conn: aiosqlite.Connection,
threads: list[ThreadInfo],
*,
include_message_count: bool,
include_initial_prompt: bool,
) -> None:
"""Populate checkpoint-derived thread fields with a batched latest-row pass."""
serde = await _get_jsonplus_serializer()
# Phase 1: apply cache hits, collect threads that need DB fetch.
uncached: list[ThreadInfo] = []
for thread in threads:
thread_id = thread["thread_id"]
freshness = _thread_freshness(thread)
needs_count = False
needs_prompt = False
if include_message_count:
cached = _message_count_cache.get(thread_id)
if cached is not None and cached[0] == freshness:
thread["message_count"] = cached[1]
else:
needs_count = True
if include_initial_prompt and "initial_prompt" not in thread:
cached_prompt = _initial_prompt_cache.get(thread_id)
if cached_prompt is not None and cached_prompt[0] == freshness:
thread["initial_prompt"] = cached_prompt[1]
else:
needs_prompt = True
if needs_count or needs_prompt:
uncached.append(thread)
logger.debug(
"Thread enrichment cache lookup: rows=%d hits=%d misses=%d",
len(threads),
len(threads) - len(uncached),
len(uncached),
)
if not uncached:
return
# Phase 2: batch-fetch all uncached threads.
uncached_ids = [t["thread_id"] for t in uncached]
batch_results: dict[str, _CheckpointSummary] = {}
if include_message_count or include_initial_prompt:
phase_started_at = time.perf_counter()
batch_results = await _load_latest_checkpoint_summaries_batch(
conn, uncached_ids, serde
)
logger.debug(
"Latest checkpoint loading and decoding completed in %.1f ms: "
"requested=%d loaded=%d",
(time.perf_counter() - phase_started_at) * 1000,
len(uncached_ids),
len(batch_results),
)
# `initial_prompt` cannot be recovered from the latest checkpoint alone:
# `after_model` middleware (e.g., `ResumeStateMiddleware`) writes partial
# checkpoints whose `channel_values` omit `messages`. Read the very first
# write to the `messages` channel from the `writes` table instead — that
# row holds the user's original input.
prompt_results: dict[str, str | None] = {}
if include_initial_prompt:
phase_started_at = time.perf_counter()
prompt_results = await _load_initial_prompts_from_writes_batch(
conn, uncached_ids, serde
)
logger.debug(
"Initial prompt loading completed in %.1f ms: requested=%d loaded=%d",
(time.perf_counter() - phase_started_at) * 1000,
len(uncached_ids),
len(prompt_results),
)
# Phase 3: apply inline results, deferring threads whose latest checkpoint
# does not inline the `messages` channel value. When `messages` uses a
# `DeltaChannel` (LangGraph channel applied by the deepagents SDK as of
# v0.6) the full list is only snapshotted into `channel_values` periodically,
# so the latest checkpoint usually omits it; the count must then be
# reconstructed from the `writes` table.
needs_writes_count: list[str] = []
for thread in uncached:
thread_id = thread["thread_id"]
freshness = _thread_freshness(thread)