acquill 0.1.0__py3-none-any.whl
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.
- acquill/__init__.py +8 -0
- acquill/config/__init__.py +7 -0
- acquill/config/auth.py +91 -0
- acquill/core/__init__.py +23 -0
- acquill/core/dsa_map.py +146 -0
- acquill/core/models.py +90 -0
- acquill/graphs/__init__.py +23 -0
- acquill/graphs/checkpoint.py +275 -0
- acquill/graphs/workflows.py +100 -0
- acquill/interface/__init__.py +3 -0
- acquill/interface/cli.py +390 -0
- acquill/models/__init__.py +16 -0
- acquill/models/schemas.py +27 -0
- acquill/models/states.py +51 -0
- acquill/nodes/__init__.py +57 -0
- acquill/nodes/chat_nodes.py +348 -0
- acquill/nodes/digest_nodes.py +93 -0
- acquill/nodes/pattern_nodes.py +74 -0
- acquill/nodes/reminder_nodes.py +126 -0
- acquill/prompts/__init__.py +23 -0
- acquill/prompts/system_prompts.py +77 -0
- acquill/utils/__init__.py +19 -0
- acquill/utils/api.py +131 -0
- acquill-0.1.0.dist-info/METADATA +97 -0
- acquill-0.1.0.dist-info/RECORD +29 -0
- acquill-0.1.0.dist-info/WHEEL +5 -0
- acquill-0.1.0.dist-info/entry_points.txt +2 -0
- acquill-0.1.0.dist-info/licenses/LICENSE +21 -0
- acquill-0.1.0.dist-info/top_level.txt +1 -0
acquill/__init__.py
ADDED
acquill/config/auth.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import typer
|
|
5
|
+
from dotenv import load_dotenv
|
|
6
|
+
from supabase import create_client, Client
|
|
7
|
+
|
|
8
|
+
load_dotenv()
|
|
9
|
+
|
|
10
|
+
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
|
11
|
+
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
|
12
|
+
|
|
13
|
+
if not SUPABASE_URL or not SUPABASE_KEY:
|
|
14
|
+
raise ValueError(
|
|
15
|
+
"SUPABASE_URL and SUPABASE_KEY required in .env file.\n"
|
|
16
|
+
"Get them from: https://supabase.com/dashboard/project/_/settings"
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
SESSION_FILE = Path(typer.get_app_dir("acquill")) / "session.json"
|
|
20
|
+
|
|
21
|
+
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def save_session(session):
|
|
25
|
+
"""Save access + refresh tokens to the OS config folder for persistence"""
|
|
26
|
+
try:
|
|
27
|
+
SESSION_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
with open(SESSION_FILE, 'w') as f:
|
|
29
|
+
json.dump({
|
|
30
|
+
'access_token': session.access_token,
|
|
31
|
+
'refresh_token': session.refresh_token,
|
|
32
|
+
}, f)
|
|
33
|
+
except Exception as e:
|
|
34
|
+
print(f"Warning: Could not save session: {e}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def restore_session() -> bool:
|
|
38
|
+
"""Restore the saved session into the in-memory supabase client.
|
|
39
|
+
|
|
40
|
+
Returns False if no session file exists or restoring fails
|
|
41
|
+
(corrupted file, expired/invalid refresh token) — never raises.
|
|
42
|
+
"""
|
|
43
|
+
try:
|
|
44
|
+
if not SESSION_FILE.exists():
|
|
45
|
+
return False
|
|
46
|
+
with open(SESSION_FILE, 'r') as f:
|
|
47
|
+
data = json.load(f)
|
|
48
|
+
result = supabase.auth.set_session(
|
|
49
|
+
data['access_token'], data['refresh_token']
|
|
50
|
+
)
|
|
51
|
+
if result.session:
|
|
52
|
+
# Re-save: set_session may have refreshed the access token
|
|
53
|
+
save_session(result.session)
|
|
54
|
+
return True
|
|
55
|
+
return False
|
|
56
|
+
except Exception:
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def clear_session():
|
|
61
|
+
"""Delete saved session file"""
|
|
62
|
+
try:
|
|
63
|
+
if SESSION_FILE.exists():
|
|
64
|
+
SESSION_FILE.unlink()
|
|
65
|
+
except Exception:
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def signup(email: str, password: str):
|
|
70
|
+
result = supabase.auth.sign_up({"email": email, "password": password})
|
|
71
|
+
if result.session:
|
|
72
|
+
save_session(result.session)
|
|
73
|
+
return result
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def signin(email: str, password: str):
|
|
77
|
+
result = supabase.auth.sign_in_with_password({"email": email, "password": password})
|
|
78
|
+
if result.session:
|
|
79
|
+
save_session(result.session)
|
|
80
|
+
return result
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def signout():
|
|
84
|
+
result = supabase.auth.sign_out()
|
|
85
|
+
clear_session()
|
|
86
|
+
return result
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def get_current_user():
|
|
90
|
+
user = supabase.auth.get_user()
|
|
91
|
+
return user
|
acquill/core/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core package - LLM setup and configuration
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from .models import (
|
|
6
|
+
embeddings,
|
|
7
|
+
extract_llm,
|
|
8
|
+
diff_analysis_llm,
|
|
9
|
+
reply_llm,
|
|
10
|
+
quiz_llm,
|
|
11
|
+
digest_llm,
|
|
12
|
+
pattern_llm
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
'embeddings',
|
|
17
|
+
'extract_llm',
|
|
18
|
+
'diff_analysis_llm',
|
|
19
|
+
'reply_llm',
|
|
20
|
+
'quiz_llm',
|
|
21
|
+
'digest_llm',
|
|
22
|
+
'pattern_llm'
|
|
23
|
+
]
|
acquill/core/dsa_map.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Placement-focused DSA topic graph: topic -> its direct prerequisites.
|
|
2
|
+
|
|
3
|
+
Order follows college-placement preparation:
|
|
4
|
+
Tier 1 (must know) -> Tier 2 (important) -> Tier 3 (top product companies).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import difflib
|
|
8
|
+
import re
|
|
9
|
+
|
|
10
|
+
DSA_PREREQUISITES = {
|
|
11
|
+
# Tier 1 - foundations
|
|
12
|
+
"programming basics": (),
|
|
13
|
+
"time and space complexity": ("programming basics",),
|
|
14
|
+
"recursion": ("programming basics",),
|
|
15
|
+
# Tier 1 - arrays and strings
|
|
16
|
+
"arrays": ("programming basics",),
|
|
17
|
+
"strings": ("arrays",),
|
|
18
|
+
"two pointers": ("arrays",),
|
|
19
|
+
"sliding window": ("two pointers",),
|
|
20
|
+
"prefix sum": ("arrays",),
|
|
21
|
+
"sorting": ("arrays", "time and space complexity", "recursion"),
|
|
22
|
+
"binary search": ("arrays", "sorting"),
|
|
23
|
+
# Tier 1 - hashing
|
|
24
|
+
"hash maps and sets": ("arrays", "time and space complexity"),
|
|
25
|
+
# Tier 1 - linked list, stack, queue
|
|
26
|
+
"linked list": ("arrays", "programming basics"),
|
|
27
|
+
"fast and slow pointers": ("linked list", "two pointers"),
|
|
28
|
+
"stack": ("arrays",),
|
|
29
|
+
"queue": ("arrays",),
|
|
30
|
+
# Tier 1 - trees
|
|
31
|
+
"binary tree": ("recursion", "stack", "linked list"),
|
|
32
|
+
"level-order traversal": ("binary tree", "queue"),
|
|
33
|
+
"binary search tree": ("binary tree", "binary search"),
|
|
34
|
+
# Tier 2
|
|
35
|
+
"backtracking": ("recursion", "arrays"),
|
|
36
|
+
"heap": ("binary tree", "arrays"),
|
|
37
|
+
"top-k problems": ("heap",),
|
|
38
|
+
"greedy basics": ("sorting", "arrays"),
|
|
39
|
+
"graph basics": ("arrays", "linked list", "binary tree"),
|
|
40
|
+
"graph bfs and dfs": ("graph basics", "queue", "recursion"),
|
|
41
|
+
"cycle detection and connected components": ("graph bfs and dfs",),
|
|
42
|
+
"topological sort": ("graph bfs and dfs",),
|
|
43
|
+
"dynamic programming basics": ("recursion", "hash maps and sets"),
|
|
44
|
+
"1d dp": ("dynamic programming basics",),
|
|
45
|
+
"2d dp": ("1d dp",),
|
|
46
|
+
# Tier 3
|
|
47
|
+
"trie": ("binary tree", "strings", "hash maps and sets"),
|
|
48
|
+
"monotonic stack": ("stack", "arrays"),
|
|
49
|
+
"union-find": ("arrays", "binary tree"),
|
|
50
|
+
"dijkstra": ("graph basics", "heap"),
|
|
51
|
+
"longest increasing subsequence": ("1d dp", "binary search"),
|
|
52
|
+
"bit manipulation": ("programming basics",),
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
TOPIC_ALIASES = {
|
|
56
|
+
"big o": "time and space complexity",
|
|
57
|
+
"big-o": "time and space complexity",
|
|
58
|
+
"big o notation": "time and space complexity",
|
|
59
|
+
"complexity": "time and space complexity",
|
|
60
|
+
"time complexity": "time and space complexity",
|
|
61
|
+
"space complexity": "time and space complexity",
|
|
62
|
+
"sorting algorithms": "sorting",
|
|
63
|
+
"hash map": "hash maps and sets",
|
|
64
|
+
"hash maps": "hash maps and sets",
|
|
65
|
+
"hash set": "hash maps and sets",
|
|
66
|
+
"hashmap": "hash maps and sets",
|
|
67
|
+
"hashing": "hash maps and sets",
|
|
68
|
+
"linked lists": "linked list",
|
|
69
|
+
"two-pointer": "two pointers",
|
|
70
|
+
"two pointers technique": "two pointers",
|
|
71
|
+
"sliding window technique": "sliding window",
|
|
72
|
+
"prefix sums": "prefix sum",
|
|
73
|
+
"tree": "binary tree",
|
|
74
|
+
"trees": "binary tree",
|
|
75
|
+
"binary trees": "binary tree",
|
|
76
|
+
"binary tree and traversals": "binary tree",
|
|
77
|
+
"dfs": "binary tree",
|
|
78
|
+
"bfs": "level-order traversal",
|
|
79
|
+
"level order traversal": "level-order traversal",
|
|
80
|
+
"bst": "binary search tree",
|
|
81
|
+
"priority queue": "heap",
|
|
82
|
+
"heap / priority queue": "heap",
|
|
83
|
+
"top k problems": "top-k problems",
|
|
84
|
+
"top-k": "top-k problems",
|
|
85
|
+
"greedy": "greedy basics",
|
|
86
|
+
"greedy algorithms": "greedy basics",
|
|
87
|
+
"graph": "graph basics",
|
|
88
|
+
"graphs": "graph basics",
|
|
89
|
+
"graph representation": "graph basics",
|
|
90
|
+
"bfs and dfs": "graph bfs and dfs",
|
|
91
|
+
"graph traversal": "graph bfs and dfs",
|
|
92
|
+
"cycle detection": "cycle detection and connected components",
|
|
93
|
+
"connected components": "cycle detection and connected components",
|
|
94
|
+
"topo sort": "topological sort",
|
|
95
|
+
"dp": "dynamic programming basics",
|
|
96
|
+
"dynamic programming": "dynamic programming basics",
|
|
97
|
+
"memoization": "dynamic programming basics",
|
|
98
|
+
"1-d dp": "1d dp",
|
|
99
|
+
"2-d dp": "2d dp",
|
|
100
|
+
"union find": "union-find",
|
|
101
|
+
"disjoint set": "union-find",
|
|
102
|
+
"disjoint set union": "union-find",
|
|
103
|
+
"dijkstra's algorithm": "dijkstra",
|
|
104
|
+
"shortest path": "dijkstra",
|
|
105
|
+
"lis": "longest increasing subsequence",
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _normalize(name):
|
|
110
|
+
"""Lowercase, collapse whitespace, drop parentheticals."""
|
|
111
|
+
key = " ".join((name or "").lower().split())
|
|
112
|
+
key = re.sub(r"\(.*?\)", " ", key)
|
|
113
|
+
return " ".join(key.split())
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def canonical(name):
|
|
117
|
+
"""Map free text to a topic in the graph, or None if it is not DSA."""
|
|
118
|
+
key = _normalize(name)
|
|
119
|
+
if not key:
|
|
120
|
+
return None
|
|
121
|
+
key = TOPIC_ALIASES.get(key, key)
|
|
122
|
+
if key in DSA_PREREQUISITES:
|
|
123
|
+
return key
|
|
124
|
+
close = difflib.get_close_matches(key, DSA_PREREQUISITES, n=1, cutoff=0.85)
|
|
125
|
+
return close[0] if close else None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def prerequisites(name, depth=1):
|
|
129
|
+
"""Direct prerequisites (depth=1) or the full chain (depth=None)."""
|
|
130
|
+
root = canonical(name)
|
|
131
|
+
if not root:
|
|
132
|
+
return []
|
|
133
|
+
|
|
134
|
+
seen = set()
|
|
135
|
+
frontier = [root]
|
|
136
|
+
for _ in range(depth or len(DSA_PREREQUISITES)):
|
|
137
|
+
nxt = []
|
|
138
|
+
for topic in frontier:
|
|
139
|
+
for dep in DSA_PREREQUISITES.get(topic, ()):
|
|
140
|
+
if dep not in seen and dep != root:
|
|
141
|
+
seen.add(dep)
|
|
142
|
+
nxt.append(dep)
|
|
143
|
+
frontier = nxt
|
|
144
|
+
if not frontier:
|
|
145
|
+
break
|
|
146
|
+
return list(seen)
|
acquill/core/models.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Groq Model Configuration for LLM nodes
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from langchain_groq import ChatGroq
|
|
7
|
+
from langchain_community.embeddings import JinaEmbeddings
|
|
8
|
+
|
|
9
|
+
# Load configuration lazily to avoid import-time failures
|
|
10
|
+
_config_loaded = False
|
|
11
|
+
GROQ_API_KEY = None
|
|
12
|
+
JINA_API_KEY = None
|
|
13
|
+
EXTRACT_MODEL = "openai/gpt-oss-20b"
|
|
14
|
+
JINA_MODEL = "jina-embeddings-v2-base-en"
|
|
15
|
+
|
|
16
|
+
def _load_config():
|
|
17
|
+
"""Load configuration once, lazily"""
|
|
18
|
+
global _config_loaded, GROQ_API_KEY, JINA_API_KEY, EXTRACT_MODEL, JINA_MODEL
|
|
19
|
+
|
|
20
|
+
if _config_loaded:
|
|
21
|
+
return
|
|
22
|
+
|
|
23
|
+
# Try to load config from settings, fall back to .env
|
|
24
|
+
try:
|
|
25
|
+
from acquill.config.settings import get_config
|
|
26
|
+
config = get_config()
|
|
27
|
+
GROQ_API_KEY = config["providers"]["groq"]["api_key"]
|
|
28
|
+
JINA_API_KEY = config["providers"]["jina"]["api_key"]
|
|
29
|
+
EXTRACT_MODEL = config["providers"]["groq"].get("model", "openai/gpt-oss-20b")
|
|
30
|
+
JINA_MODEL = config["providers"]["jina"].get("model", "jina-embeddings-v2-base-en")
|
|
31
|
+
except Exception:
|
|
32
|
+
# Fall back to .env
|
|
33
|
+
from dotenv import load_dotenv
|
|
34
|
+
load_dotenv()
|
|
35
|
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
|
36
|
+
JINA_API_KEY = os.getenv("JINA_API_KEY")
|
|
37
|
+
EXTRACT_MODEL = "openai/gpt-oss-20b"
|
|
38
|
+
JINA_MODEL = "jina-embeddings-v2-base-en"
|
|
39
|
+
|
|
40
|
+
_config_loaded = True
|
|
41
|
+
|
|
42
|
+
# Load config immediately so module-level code works
|
|
43
|
+
_load_config()
|
|
44
|
+
|
|
45
|
+
DIFF_ANALYSIS_MODEL = EXTRACT_MODEL
|
|
46
|
+
REPLY_MODEL = EXTRACT_MODEL
|
|
47
|
+
QUIZ_MODEL = EXTRACT_MODEL
|
|
48
|
+
DIGEST_MODEL = EXTRACT_MODEL
|
|
49
|
+
PATTERN_MODEL = EXTRACT_MODEL
|
|
50
|
+
|
|
51
|
+
embeddings = JinaEmbeddings(
|
|
52
|
+
jina_api_key=JINA_API_KEY,
|
|
53
|
+
model_name=JINA_MODEL
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
extract_llm = ChatGroq(
|
|
57
|
+
model=EXTRACT_MODEL,
|
|
58
|
+
temperature=0.7,
|
|
59
|
+
groq_api_key=GROQ_API_KEY
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
diff_analysis_llm = ChatGroq(
|
|
63
|
+
model=DIFF_ANALYSIS_MODEL,
|
|
64
|
+
temperature=0.7,
|
|
65
|
+
groq_api_key=GROQ_API_KEY
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
reply_llm = ChatGroq(
|
|
69
|
+
model=REPLY_MODEL,
|
|
70
|
+
temperature=0.7,
|
|
71
|
+
groq_api_key=GROQ_API_KEY
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
quiz_llm = ChatGroq(
|
|
75
|
+
model=QUIZ_MODEL,
|
|
76
|
+
temperature=0.7,
|
|
77
|
+
groq_api_key=GROQ_API_KEY
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
digest_llm = ChatGroq(
|
|
81
|
+
model=DIGEST_MODEL,
|
|
82
|
+
temperature=0.7,
|
|
83
|
+
groq_api_key=GROQ_API_KEY
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
pattern_llm = ChatGroq(
|
|
87
|
+
model=PATTERN_MODEL,
|
|
88
|
+
temperature=0.7,
|
|
89
|
+
groq_api_key=GROQ_API_KEY
|
|
90
|
+
)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""
|
|
2
|
+
LangGraph workflow definitions
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from .checkpoint import get_checkpointer, get_thread_config, get_thread_id
|
|
6
|
+
from .workflows import (
|
|
7
|
+
build_chat_graph,
|
|
8
|
+
build_diff_graph,
|
|
9
|
+
build_reminder_graph,
|
|
10
|
+
build_digest_graph,
|
|
11
|
+
build_pattern_graph,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
'get_checkpointer',
|
|
16
|
+
'get_thread_config',
|
|
17
|
+
'get_thread_id',
|
|
18
|
+
'build_chat_graph',
|
|
19
|
+
'build_diff_graph',
|
|
20
|
+
'build_reminder_graph',
|
|
21
|
+
'build_digest_graph',
|
|
22
|
+
'build_pattern_graph'
|
|
23
|
+
]
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Postgres checkpointer (Supabase) + per-session thread config.
|
|
3
|
+
|
|
4
|
+
Checkpoints are SHORT-TERM memory only, scoped to ONE CLI session:
|
|
5
|
+
|
|
6
|
+
- One thread per run: '<user_id>:<run-uuid>' (uuid4 generated once per
|
|
7
|
+
process). A new run always starts with a fresh, empty conversation;
|
|
8
|
+
two runs never share a thread.
|
|
9
|
+
- When the run exits normally, that thread is deleted from the
|
|
10
|
+
checkpoint tables via the checkpointer's own delete_thread(), so the
|
|
11
|
+
database never fills up. Long-term data lives in our own tables
|
|
12
|
+
(topics, topic_history, documents), never in checkpoints.
|
|
13
|
+
- At session init, leftover threads from earlier runs of the SAME user
|
|
14
|
+
are deleted (crash/kill leaves them behind). A thread owned by a live
|
|
15
|
+
run is protected by a Postgres advisory lock and is never deleted.
|
|
16
|
+
Other users' threads are never touched, and the current thread is
|
|
17
|
+
never deleted.
|
|
18
|
+
|
|
19
|
+
NOTE: PostgresSaver.from_conn_string() is a context manager holding the
|
|
20
|
+
DB connection pool, so the saver must stay open for the whole CLI run.
|
|
21
|
+
We enter it once here and close it via atexit on process exit. atexit
|
|
22
|
+
runs LIFO, so the thread-deletion hook runs BEFORE the connection is
|
|
23
|
+
closed, and the advisory-lock connection closes after that.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import atexit
|
|
27
|
+
import hashlib
|
|
28
|
+
import logging
|
|
29
|
+
import os
|
|
30
|
+
import threading
|
|
31
|
+
import uuid
|
|
32
|
+
|
|
33
|
+
from dotenv import load_dotenv
|
|
34
|
+
|
|
35
|
+
load_dotenv()
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class SessionLostError(RuntimeError):
|
|
41
|
+
"""This run's thread lock is gone; the session cannot continue."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_SESSION_LOST_MSG = "Session lost, please restart Acquill."
|
|
45
|
+
|
|
46
|
+
_cm = None
|
|
47
|
+
_CHECKPOINTER = None
|
|
48
|
+
_THREAD_ID = None
|
|
49
|
+
_LOCK_CONN = None
|
|
50
|
+
_INITIALIZED = False
|
|
51
|
+
_EXIT_HOOK_REGISTERED = False
|
|
52
|
+
_SESSION_LOST = False
|
|
53
|
+
_SESSION_GUARD = threading.RLock()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get_checkpointer():
|
|
57
|
+
"""Return the shared PostgresSaver, creating + setting it up once."""
|
|
58
|
+
global _cm, _CHECKPOINTER
|
|
59
|
+
if _CHECKPOINTER is None:
|
|
60
|
+
from langgraph.checkpoint.postgres import PostgresSaver
|
|
61
|
+
|
|
62
|
+
db_url = os.getenv("CHECKPOINT_DB_URL")
|
|
63
|
+
if not db_url:
|
|
64
|
+
raise RuntimeError(
|
|
65
|
+
"CHECKPOINT_DB_URL is not set. Add your Supabase Postgres "
|
|
66
|
+
"connection string to .env (see .env.example)."
|
|
67
|
+
)
|
|
68
|
+
_cm = PostgresSaver.from_conn_string(db_url)
|
|
69
|
+
_CHECKPOINTER = _cm.__enter__()
|
|
70
|
+
_CHECKPOINTER.setup()
|
|
71
|
+
atexit.register(_cm.__exit__, None, None, None)
|
|
72
|
+
return _CHECKPOINTER
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _user_id() -> str:
|
|
76
|
+
"""Resolve the logged-in user's id. Raises if not logged in."""
|
|
77
|
+
from acquill.config.auth import get_current_user
|
|
78
|
+
|
|
79
|
+
result = get_current_user()
|
|
80
|
+
user = getattr(result, "user", None)
|
|
81
|
+
if isinstance(result, dict):
|
|
82
|
+
user = result.get("user", user)
|
|
83
|
+
user_id = getattr(user, "id", None)
|
|
84
|
+
if isinstance(user, dict):
|
|
85
|
+
user_id = user.get("id", user_id)
|
|
86
|
+
if not user_id:
|
|
87
|
+
raise RuntimeError(
|
|
88
|
+
"Not logged in: cannot resolve thread_id. "
|
|
89
|
+
"Run login first so checkpoints stay tied to your user."
|
|
90
|
+
)
|
|
91
|
+
return user_id
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def get_thread_id() -> str:
|
|
95
|
+
"""One thread per CLI run: '<user_id>:<run-uuid>' (fresh each run)."""
|
|
96
|
+
global _THREAD_ID
|
|
97
|
+
if _THREAD_ID is None:
|
|
98
|
+
_THREAD_ID = f"{_user_id()}:{uuid.uuid4()}"
|
|
99
|
+
return _THREAD_ID
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _lock_key(thread_id: str) -> int:
|
|
103
|
+
"""Stable signed 64-bit advisory-lock key for a thread id."""
|
|
104
|
+
digest = hashlib.blake2b(thread_id.encode("utf-8"), digest_size=8).digest()
|
|
105
|
+
return int.from_bytes(digest, "big", signed=True)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _acquire_own_lock() -> None:
|
|
109
|
+
"""Take this run's advisory lock on a dedicated connection.
|
|
110
|
+
|
|
111
|
+
Postgres releases the lock automatically if the process dies, so it
|
|
112
|
+
is a reliable "this run is still alive" signal for cleanup.
|
|
113
|
+
"""
|
|
114
|
+
global _LOCK_CONN
|
|
115
|
+
from psycopg import connect
|
|
116
|
+
from psycopg.rows import dict_row
|
|
117
|
+
|
|
118
|
+
conn = connect(
|
|
119
|
+
os.getenv("CHECKPOINT_DB_URL"), autocommit=True, row_factory=dict_row
|
|
120
|
+
)
|
|
121
|
+
try:
|
|
122
|
+
conn.execute("SET statement_timeout = 5000")
|
|
123
|
+
conn.execute(
|
|
124
|
+
"SELECT pg_advisory_lock(%s::bigint)",
|
|
125
|
+
(_lock_key(get_thread_id()),),
|
|
126
|
+
)
|
|
127
|
+
except Exception:
|
|
128
|
+
try:
|
|
129
|
+
conn.close()
|
|
130
|
+
except Exception:
|
|
131
|
+
logger.warning(
|
|
132
|
+
"checkpoint lock connection close failed", exc_info=True
|
|
133
|
+
)
|
|
134
|
+
raise
|
|
135
|
+
_LOCK_CONN = conn
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _close_lock_connection() -> None:
|
|
139
|
+
"""Close the lock connection (releases the lock). Never raises."""
|
|
140
|
+
global _LOCK_CONN
|
|
141
|
+
if _LOCK_CONN is not None:
|
|
142
|
+
try:
|
|
143
|
+
_LOCK_CONN.close()
|
|
144
|
+
except Exception:
|
|
145
|
+
logger.warning(
|
|
146
|
+
"checkpoint lock connection close failed", exc_info=True
|
|
147
|
+
)
|
|
148
|
+
finally:
|
|
149
|
+
_LOCK_CONN = None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _mark_session_lost(reason: str, *, exc_info: bool = False) -> None:
|
|
153
|
+
"""Set the permanent session-lost flag, log it, and fail closed."""
|
|
154
|
+
global _SESSION_LOST
|
|
155
|
+
_SESSION_LOST = True
|
|
156
|
+
logger.warning("checkpoint session lost: %s", reason, exc_info=exc_info)
|
|
157
|
+
raise SessionLostError(_SESSION_LOST_MSG)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def ensure_session_alive() -> None:
|
|
161
|
+
"""Probe this run's thread lock before a graph call; fail closed.
|
|
162
|
+
|
|
163
|
+
A dropped lock connection releases the advisory lock, so another
|
|
164
|
+
run's cleanup could delete this session's thread. Re-acquiring would
|
|
165
|
+
not prove the thread survived, so there is no recovery path: once
|
|
166
|
+
the lock is lost the session is over.
|
|
167
|
+
"""
|
|
168
|
+
with _SESSION_GUARD:
|
|
169
|
+
if _SESSION_LOST:
|
|
170
|
+
raise SessionLostError(_SESSION_LOST_MSG)
|
|
171
|
+
if not _INITIALIZED:
|
|
172
|
+
init_session()
|
|
173
|
+
return
|
|
174
|
+
if _LOCK_CONN is None:
|
|
175
|
+
_mark_session_lost("lock connection is gone")
|
|
176
|
+
try:
|
|
177
|
+
_LOCK_CONN.execute("SELECT 1")
|
|
178
|
+
except Exception:
|
|
179
|
+
_mark_session_lost("lock connection probe failed", exc_info=True)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _delete_leftover_threads(checkpointer) -> None:
|
|
183
|
+
"""Delete this user's leftover threads from earlier crashed runs.
|
|
184
|
+
|
|
185
|
+
Reads ONLY thread ids from the checkpoints table; deletes strictly
|
|
186
|
+
by thread_id. Other users' threads and the current thread are never
|
|
187
|
+
touched, and a thread whose advisory lock is held by a live run is
|
|
188
|
+
skipped.
|
|
189
|
+
"""
|
|
190
|
+
current = get_thread_id()
|
|
191
|
+
user_id = _user_id()
|
|
192
|
+
prefix = f"{user_id}:%"
|
|
193
|
+
try:
|
|
194
|
+
rows = checkpointer.conn.execute(
|
|
195
|
+
"SELECT DISTINCT thread_id FROM checkpoints "
|
|
196
|
+
"WHERE thread_id LIKE %s",
|
|
197
|
+
(prefix,),
|
|
198
|
+
).fetchall()
|
|
199
|
+
except Exception:
|
|
200
|
+
logger.warning(
|
|
201
|
+
"checkpoint cleanup: could not list threads", exc_info=True
|
|
202
|
+
)
|
|
203
|
+
return
|
|
204
|
+
for row in rows:
|
|
205
|
+
thread_id = row["thread_id"]
|
|
206
|
+
if (
|
|
207
|
+
not thread_id
|
|
208
|
+
or not thread_id.startswith(user_id + ":")
|
|
209
|
+
or thread_id == current
|
|
210
|
+
):
|
|
211
|
+
continue
|
|
212
|
+
key = _lock_key(thread_id)
|
|
213
|
+
try:
|
|
214
|
+
locked = _LOCK_CONN.execute(
|
|
215
|
+
"SELECT pg_try_advisory_lock(%s::bigint) AS locked", (key,)
|
|
216
|
+
).fetchone()["locked"]
|
|
217
|
+
if not locked:
|
|
218
|
+
continue
|
|
219
|
+
try:
|
|
220
|
+
checkpointer.delete_thread(thread_id)
|
|
221
|
+
finally:
|
|
222
|
+
_LOCK_CONN.execute(
|
|
223
|
+
"SELECT pg_advisory_unlock(%s::bigint) AS unlocked",
|
|
224
|
+
(key,),
|
|
225
|
+
)
|
|
226
|
+
except Exception:
|
|
227
|
+
logger.warning(
|
|
228
|
+
"checkpoint cleanup: could not delete thread %s",
|
|
229
|
+
thread_id,
|
|
230
|
+
exc_info=True,
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _delete_current_on_exit() -> None:
|
|
235
|
+
"""Delete this run's thread on normal exit. Never raises."""
|
|
236
|
+
if _THREAD_ID is not None and _CHECKPOINTER is not None:
|
|
237
|
+
try:
|
|
238
|
+
_CHECKPOINTER.delete_thread(_THREAD_ID)
|
|
239
|
+
except Exception:
|
|
240
|
+
logger.warning(
|
|
241
|
+
"checkpoint cleanup: could not delete session thread %s",
|
|
242
|
+
_THREAD_ID,
|
|
243
|
+
exc_info=True,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def init_session() -> str:
|
|
248
|
+
"""Once per run: resolve thread id, clear leftovers, arm exit cleanup.
|
|
249
|
+
|
|
250
|
+
Must be called after login (the thread id embeds the user's id).
|
|
251
|
+
Safe to call repeatedly; does the work only on the first successful
|
|
252
|
+
call. A failed attempt keeps the same thread id and can be retried.
|
|
253
|
+
"""
|
|
254
|
+
global _INITIALIZED, _EXIT_HOOK_REGISTERED
|
|
255
|
+
with _SESSION_GUARD:
|
|
256
|
+
if _INITIALIZED:
|
|
257
|
+
return _THREAD_ID
|
|
258
|
+
if _SESSION_LOST:
|
|
259
|
+
raise SessionLostError(_SESSION_LOST_MSG)
|
|
260
|
+
get_thread_id()
|
|
261
|
+
checkpointer = get_checkpointer()
|
|
262
|
+
if _LOCK_CONN is None:
|
|
263
|
+
_acquire_own_lock()
|
|
264
|
+
atexit.register(_close_lock_connection)
|
|
265
|
+
_delete_leftover_threads(checkpointer)
|
|
266
|
+
if not _EXIT_HOOK_REGISTERED:
|
|
267
|
+
atexit.register(_delete_current_on_exit)
|
|
268
|
+
_EXIT_HOOK_REGISTERED = True
|
|
269
|
+
_INITIALIZED = True
|
|
270
|
+
return _THREAD_ID
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def get_thread_config() -> dict:
|
|
274
|
+
"""LangGraph invoke config pinning this run's calls to its thread."""
|
|
275
|
+
return {"configurable": {"thread_id": init_session()}}
|