deadkey 0.9.5__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.
- deadkey/__init__.py +2 -0
- deadkey/a2a.py +207 -0
- deadkey/cognition.py +132 -0
- deadkey/config.py +55 -0
- deadkey/doctor.py +150 -0
- deadkey/embedder.py +138 -0
- deadkey/epistemic_gate.py +363 -0
- deadkey/epistemic_proxy.py +206 -0
- deadkey/live_client.py +507 -0
- deadkey/mcp_server.py +333 -0
- deadkey/memory_store.py +585 -0
- deadkey/prefetch.py +105 -0
- deadkey/providers.py +160 -0
- deadkey/rd_scout.py +148 -0
- deadkey/semantic_critic.py +308 -0
- deadkey/server.py +1414 -0
- deadkey/sessions.py +182 -0
- deadkey/sleep_cycle.py +149 -0
- deadkey/supervisor.py +278 -0
- deadkey/tool_router.py +356 -0
- deadkey/tools_runtime.py +386 -0
- deadkey/train_epistemic_dpo_gguf.py +206 -0
- deadkey/train_epistemic_rlvr_grpo.py +374 -0
- deadkey/turn_machine.py +263 -0
- deadkey/vgr_local.py +101 -0
- deadkey/voice_supervisor.py +339 -0
- deadkey-0.9.5.dist-info/METADATA +124 -0
- deadkey-0.9.5.dist-info/RECORD +33 -0
- deadkey-0.9.5.dist-info/WHEEL +5 -0
- deadkey-0.9.5.dist-info/entry_points.txt +5 -0
- deadkey-0.9.5.dist-info/licenses/LICENSE +202 -0
- deadkey-0.9.5.dist-info/licenses/NOTICE +20 -0
- deadkey-0.9.5.dist-info/top_level.txt +1 -0
deadkey/__init__.py
ADDED
deadkey/a2a.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Zero-dependency A2A (Agent-to-Agent Protocol) Peer Adapter for Deadkey / Deadkey.
|
|
2
|
+
|
|
3
|
+
Exposes:
|
|
4
|
+
- GET /.well-known/agent.json — Standard A2A Agent Card for peer discovery (Hermes, OpenClaw, LangGraph, Tailscale peers)
|
|
5
|
+
- POST /a2a — JSON-RPC 2.0 task execution (`agent/capabilities`, `tasks/send`)
|
|
6
|
+
|
|
7
|
+
Privacy Wall Guarantee:
|
|
8
|
+
- `epistemic_audit` (auditing caller-provided drafts + receipts via Tier 1 & optional Tier 2 Semantic Critic)
|
|
9
|
+
is stateless and safe on ANY cartridge.
|
|
10
|
+
- `memory_recall` / `memory_record` over A2A are STRICTLY BLOCKED whenever the active cartridge
|
|
11
|
+
enforces `cloud_privacy_wall=True` (private personal memories NEVER cross peer boundaries!).
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import time
|
|
16
|
+
import uuid
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from .epistemic_gate import EvidenceReceipt
|
|
20
|
+
from .semantic_critic import SemanticEpistemicCritic, evaluate_hybrid
|
|
21
|
+
from .tool_router import TurnLane
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def build_agent_card(rt: Any, base_url: str = "http://127.0.0.1:8765") -> dict[str, Any]:
|
|
25
|
+
is_private = bool(rt.cartridge.extra.get("cloud_privacy_wall", True))
|
|
26
|
+
sup = rt.supervisor.get_status(refresh_vram=False) if getattr(rt, "supervisor", None) else {}
|
|
27
|
+
skills = [
|
|
28
|
+
{
|
|
29
|
+
"id": "epistemic_audit",
|
|
30
|
+
"name": "Two-Tier Epistemic Audit",
|
|
31
|
+
"description": (
|
|
32
|
+
"Audits a candidate model draft against verified EvidenceReceipts and optional active "
|
|
33
|
+
"memory policies using the 0.01 ms deterministic Tier 1 Disk-Equals-Truth gate and "
|
|
34
|
+
"optional local Tier 2 Semantic Epistemic Critic."
|
|
35
|
+
),
|
|
36
|
+
"input_schema": {
|
|
37
|
+
"user_text": "string",
|
|
38
|
+
"draft_reply": "string",
|
|
39
|
+
"receipts": "list[dict] (optional)",
|
|
40
|
+
"active_memories": "list[str] (optional)",
|
|
41
|
+
"semantic": "bool (default false)",
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
"id": "health_telemetry",
|
|
46
|
+
"name": "Local Hardware & Runtime Telemetry",
|
|
47
|
+
"description": "Reports active model, engine, VRAM availability, and zero-VRAM memory DB stats.",
|
|
48
|
+
},
|
|
49
|
+
]
|
|
50
|
+
if not is_private:
|
|
51
|
+
skills.append({
|
|
52
|
+
"id": "memory_recall",
|
|
53
|
+
"name": "Zero-VRAM Bi-Temporal Memory Recall",
|
|
54
|
+
"description": "Valid-time SQLite FTS5 + hybrid CPU vector recall (zero stale superseded leaks).",
|
|
55
|
+
"input_schema": {"query": "string", "k": "int (default 5)"},
|
|
56
|
+
})
|
|
57
|
+
return {
|
|
58
|
+
"protocol": "a2a/1.0",
|
|
59
|
+
"name": f"Deadkey Peer ({rt.cartridge.display_name})",
|
|
60
|
+
"description": "Local-first sovereign AI runtime with 0-VRAM bi-temporal memory and 2-tier epistemic verification.",
|
|
61
|
+
"url": base_url.rstrip("/") + "/a2a",
|
|
62
|
+
"version": "1.0.0",
|
|
63
|
+
"capabilities": {
|
|
64
|
+
"streaming": False,
|
|
65
|
+
"pushNotifications": False,
|
|
66
|
+
"stateTransitionHistory": True,
|
|
67
|
+
},
|
|
68
|
+
"privacy": {
|
|
69
|
+
"cartridge_id": rt.cartridge.agent_id,
|
|
70
|
+
"privacy_wall": is_private,
|
|
71
|
+
"memory_exposed_over_a2a": (not is_private),
|
|
72
|
+
},
|
|
73
|
+
"runtime": {
|
|
74
|
+
"active_model": sup.get("active_model") or "offline",
|
|
75
|
+
"backend_url": rt.client.base_url,
|
|
76
|
+
},
|
|
77
|
+
"skills": skills,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _rpc_ok(req_id: Any, result: dict[str, Any]) -> dict[str, Any]:
|
|
82
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": result}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _rpc_err(req_id: Any, code: int, message: str, data: Any = None) -> dict[str, Any]:
|
|
86
|
+
err: dict[str, Any] = {"code": code, "message": message}
|
|
87
|
+
if data is not None:
|
|
88
|
+
err["data"] = data
|
|
89
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": err}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def handle_a2a_rpc(rt: Any, payload: dict[str, Any], base_url: str = "http://127.0.0.1:8765") -> dict[str, Any]:
|
|
93
|
+
req_id = payload.get("id")
|
|
94
|
+
method = str(payload.get("method") or "").strip()
|
|
95
|
+
params = payload.get("params") or {}
|
|
96
|
+
if not isinstance(params, dict):
|
|
97
|
+
return _rpc_err(req_id, -32602, "params must be a JSON object")
|
|
98
|
+
|
|
99
|
+
if method == "agent/capabilities":
|
|
100
|
+
return _rpc_ok(req_id, build_agent_card(rt, base_url=base_url))
|
|
101
|
+
|
|
102
|
+
if method != "tasks/send":
|
|
103
|
+
return _rpc_err(req_id, -32601, f"Unsupported A2A method: {method}")
|
|
104
|
+
|
|
105
|
+
task_id = str(params.get("id") or f"a2a-{uuid.uuid4().hex[:10]}")
|
|
106
|
+
skill = str(params.get("skill") or "epistemic_audit").strip()
|
|
107
|
+
inp = params.get("input") or {}
|
|
108
|
+
if not isinstance(inp, dict):
|
|
109
|
+
return _rpc_err(req_id, -32602, "params.input must be a JSON object")
|
|
110
|
+
|
|
111
|
+
t0 = time.perf_counter()
|
|
112
|
+
is_private = bool(rt.cartridge.extra.get("cloud_privacy_wall", True))
|
|
113
|
+
|
|
114
|
+
if skill == "health_telemetry":
|
|
115
|
+
sup = rt.supervisor.get_status(refresh_vram=False) if getattr(rt, "supervisor", None) else {}
|
|
116
|
+
stats = rt.memory.stats() if getattr(rt, "memory", None) else {}
|
|
117
|
+
return _rpc_ok(req_id, {
|
|
118
|
+
"id": task_id,
|
|
119
|
+
"status": {"state": "completed"},
|
|
120
|
+
"skill": skill,
|
|
121
|
+
"elapsed_ms": round((time.perf_counter() - t0) * 1000, 2),
|
|
122
|
+
"output": {
|
|
123
|
+
"cartridge_id": rt.cartridge.agent_id,
|
|
124
|
+
"privacy_wall": is_private,
|
|
125
|
+
"active_model": sup.get("active_model") or "offline",
|
|
126
|
+
"memory_stats": stats,
|
|
127
|
+
},
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
if skill == "memory_recall":
|
|
131
|
+
if is_private:
|
|
132
|
+
return _rpc_err(
|
|
133
|
+
req_id,
|
|
134
|
+
-32003,
|
|
135
|
+
"Privacy Wall active: private cartridge memory cannot be queried over A2A.",
|
|
136
|
+
{"cartridge_id": rt.cartridge.agent_id, "privacy_wall": True},
|
|
137
|
+
)
|
|
138
|
+
q = str(inp.get("query") or "").strip()
|
|
139
|
+
k = max(1, min(20, int(inp.get("k") or 5)))
|
|
140
|
+
qvec = rt.embedder.embed_query(q) if (getattr(rt, "embedder", None) and rt.embedder.ready) else None
|
|
141
|
+
hits = rt.memory.recall(q, k=k, query_vec=qvec) if getattr(rt, "memory", None) else []
|
|
142
|
+
return _rpc_ok(req_id, {
|
|
143
|
+
"id": task_id,
|
|
144
|
+
"status": {"state": "completed"},
|
|
145
|
+
"skill": skill,
|
|
146
|
+
"elapsed_ms": round((time.perf_counter() - t0) * 1000, 2),
|
|
147
|
+
"output": {"query": q, "hits": [h.__dict__ for h in hits]},
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
if skill == "epistemic_audit":
|
|
151
|
+
user_text = str(inp.get("user_text") or "")
|
|
152
|
+
draft_reply = str(inp.get("draft_reply") or "")
|
|
153
|
+
if not draft_reply:
|
|
154
|
+
return _rpc_err(req_id, -32602, "input.draft_reply is required for epistemic_audit")
|
|
155
|
+
raw_rcpts = inp.get("receipts") or []
|
|
156
|
+
receipts: list[EvidenceReceipt] = []
|
|
157
|
+
for r in raw_rcpts:
|
|
158
|
+
if isinstance(r, dict):
|
|
159
|
+
bc = r.get("byte_count") if r.get("byte_count") is not None else r.get("byte_size")
|
|
160
|
+
lc = r.get("line_count")
|
|
161
|
+
sha = r.get("sha256_short") or r.get("sha256_prefix")
|
|
162
|
+
vnums = {str(x) for x in (bc, lc) if x is not None}
|
|
163
|
+
receipts.append(EvidenceReceipt(
|
|
164
|
+
tool=str(r.get("tool") or r.get("tool_name") or "peer_tool"),
|
|
165
|
+
args=dict(r.get("args") or {}),
|
|
166
|
+
ok=bool(r.get("ok", True)),
|
|
167
|
+
result_text=str(r.get("result_text") or ""),
|
|
168
|
+
duration_ms=int(r.get("duration_ms") or 1),
|
|
169
|
+
resolved_path=r.get("resolved_path"),
|
|
170
|
+
byte_count=bc,
|
|
171
|
+
line_count=lc,
|
|
172
|
+
sha256_short=sha,
|
|
173
|
+
verified_numbers=vnums,
|
|
174
|
+
))
|
|
175
|
+
active_mems = [str(x) for x in (inp.get("active_memories") or []) if str(x).strip()]
|
|
176
|
+
use_semantic = bool(inp.get("semantic", False))
|
|
177
|
+
critic = SemanticEpistemicCritic(base_url=rt.client.base_url) if use_semantic else None
|
|
178
|
+
lane = TurnLane.EVIDENCE_GATED if str(inp.get("lane") or "evidence_gated") != "fast" else TurnLane.FAST_CONVERSATIONAL
|
|
179
|
+
verdict, c_verdict = evaluate_hybrid(
|
|
180
|
+
rt.gate,
|
|
181
|
+
critic,
|
|
182
|
+
user_text=user_text,
|
|
183
|
+
draft_reply=draft_reply,
|
|
184
|
+
lane=lane,
|
|
185
|
+
receipts=receipts,
|
|
186
|
+
active_memories=active_mems,
|
|
187
|
+
attempt=int(inp.get("attempt") or 1),
|
|
188
|
+
max_attempts=int(inp.get("max_attempts") or 2),
|
|
189
|
+
)
|
|
190
|
+
return _rpc_ok(req_id, {
|
|
191
|
+
"id": task_id,
|
|
192
|
+
"status": {"state": "completed"},
|
|
193
|
+
"skill": skill,
|
|
194
|
+
"elapsed_ms": round((time.perf_counter() - t0) * 1000, 2),
|
|
195
|
+
"output": {
|
|
196
|
+
"action": verdict.action,
|
|
197
|
+
"violations": verdict.violations,
|
|
198
|
+
"cleaned_text": verdict.cleaned_text,
|
|
199
|
+
"reprompt_instruction": verdict.reprompt_instruction,
|
|
200
|
+
"tier2_invoked": c_verdict.invoked,
|
|
201
|
+
"tier2_elapsed_ms": c_verdict.elapsed_ms,
|
|
202
|
+
"tier2_type": c_verdict.violation_type,
|
|
203
|
+
"tier2_reason": c_verdict.reason,
|
|
204
|
+
},
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
return _rpc_err(req_id, -32602, f"Unknown A2A skill: {skill}")
|
deadkey/cognition.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Slot-1 Background Cognition Engine (Zero KV Eviction Against Live Chat!).
|
|
2
|
+
|
|
3
|
+
Because Colossus runs `-np 2` multi-slot KV isolation (proven `kv_hit 0.95-0.995` across
|
|
4
|
+
all 8 benchmarked models!), background reflection runs on `id_slot=1` while live voice/text
|
|
5
|
+
chat stays warm on `id_slot=0`.
|
|
6
|
+
|
|
7
|
+
What Slot-1 Cognition does automatically (safe, bounded, truth-first):
|
|
8
|
+
1. Distills recent conversation turns into crisp, non-redundant semantic fact candidates.
|
|
9
|
+
2. Flags open threads or unresolved commitments so deadkey naturally remembers continuity.
|
|
10
|
+
3. Detects self-corrections or epistemic near-misses and feeds them into the Sleep-Time
|
|
11
|
+
DPO consolidation pipeline (human-approved before any weight update).
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import re
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
from dataclasses import asdict, dataclass
|
|
20
|
+
from typing import Any, Optional
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class CognitionPassReport:
|
|
25
|
+
ts: float
|
|
26
|
+
ran_on_slot: int
|
|
27
|
+
turns_analyzed: int
|
|
28
|
+
facts_added: int
|
|
29
|
+
threads_updated: int
|
|
30
|
+
summary: str
|
|
31
|
+
elapsed_ms: float
|
|
32
|
+
ok: bool
|
|
33
|
+
error: str = ""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_JSON_OBJ_RX = re.compile(r"\{[\s\S]*\}")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class SlotOneCognition:
|
|
40
|
+
def __init__(self, runtime: Any):
|
|
41
|
+
self.rt = runtime
|
|
42
|
+
self._lock = threading.Lock()
|
|
43
|
+
self._running = False
|
|
44
|
+
self.history: list[dict[str, Any]] = []
|
|
45
|
+
|
|
46
|
+
def is_running(self) -> bool:
|
|
47
|
+
return self._running
|
|
48
|
+
|
|
49
|
+
def trigger_async(self, session_id: Optional[str] = None) -> bool:
|
|
50
|
+
with self._lock:
|
|
51
|
+
if self._running:
|
|
52
|
+
return False
|
|
53
|
+
self._running = True
|
|
54
|
+
t = threading.Thread(target=self._run_worker, args=(session_id,), daemon=True)
|
|
55
|
+
t.start()
|
|
56
|
+
return True
|
|
57
|
+
|
|
58
|
+
def _run_worker(self, session_id: Optional[str]) -> None:
|
|
59
|
+
try:
|
|
60
|
+
self.run_once(session_id=session_id)
|
|
61
|
+
finally:
|
|
62
|
+
with self._lock:
|
|
63
|
+
self._running = False
|
|
64
|
+
|
|
65
|
+
def run_once(self, session_id: Optional[str] = None) -> CognitionPassReport:
|
|
66
|
+
t0 = time.perf_counter()
|
|
67
|
+
rt = self.rt
|
|
68
|
+
sid = session_id or rt.active_session_id
|
|
69
|
+
msgs = rt.sessions.get_messages(sid)[-8:] if rt.sessions else []
|
|
70
|
+
user_assistant = [m for m in msgs if m.get("role") in ("user", "assistant")]
|
|
71
|
+
if not user_assistant:
|
|
72
|
+
rep = CognitionPassReport(time.time(), 1, 0, 0, 0, "No recent turns to reflect on.", 0.0, True)
|
|
73
|
+
self.history.insert(0, asdict(rep))
|
|
74
|
+
return rep
|
|
75
|
+
|
|
76
|
+
convo = "\n".join(f"{m['role'].upper()}: {(m.get('content') or '')[:350]}" for m in user_assistant)
|
|
77
|
+
backend = rt.client.discover(timeout=0.5)
|
|
78
|
+
if not backend.reachable:
|
|
79
|
+
# Deterministic offline reflection fallback
|
|
80
|
+
rep = CognitionPassReport(
|
|
81
|
+
time.time(), 1, len(user_assistant), 0, 0,
|
|
82
|
+
f"Offline reflection indexed {len(user_assistant)} turns (LLM idle).",
|
|
83
|
+
round((time.perf_counter() - t0) * 1000, 1), True,
|
|
84
|
+
)
|
|
85
|
+
self.history.insert(0, asdict(rep))
|
|
86
|
+
return rep
|
|
87
|
+
|
|
88
|
+
sys_prompt = (
|
|
89
|
+
"You are Deadkey's quiet Slot-1 background memory reflection daemon. "
|
|
90
|
+
"Extract ONLY durable, factual, explicitly stated facts or open project threads from the conversation below. "
|
|
91
|
+
"Never invent details. Output strict JSON ONLY with keys:\n"
|
|
92
|
+
'{"summary": "1 concise sentence", "facts": [{"category": "project|preference|machine", "text": "..."}], '
|
|
93
|
+
'"threads": [{"title": "...", "notes": "..."}]}'
|
|
94
|
+
)
|
|
95
|
+
try:
|
|
96
|
+
turn, _tel = rt.client.chat_once(
|
|
97
|
+
system_prompt=sys_prompt,
|
|
98
|
+
messages=[{"role": "user", "content": convo}],
|
|
99
|
+
tools=None,
|
|
100
|
+
slot_id=1, # STRICT Slot-1 isolation -> 0% KV eviction on live Slot-0!
|
|
101
|
+
max_tokens=320,
|
|
102
|
+
temperature=0.2,
|
|
103
|
+
request_logprobs=False,
|
|
104
|
+
)
|
|
105
|
+
m = _JSON_OBJ_RX.search(turn.text or "")
|
|
106
|
+
parsed = json.loads(m.group(0)) if m else {}
|
|
107
|
+
facts_added = 0
|
|
108
|
+
threads_updated = 0
|
|
109
|
+
if rt.memory is not None:
|
|
110
|
+
for f in (parsed.get("facts") or [])[:3]:
|
|
111
|
+
txt = str(f.get("text") or "").strip()
|
|
112
|
+
if len(txt) >= 12:
|
|
113
|
+
rt.memory.add_semantic_fact(txt, category=str(f.get("category") or "reflection"), source="slot1_cognition")
|
|
114
|
+
facts_added += 1
|
|
115
|
+
for th in (parsed.get("threads") or [])[:2]:
|
|
116
|
+
title = str(th.get("title") or "").strip()
|
|
117
|
+
if title:
|
|
118
|
+
rt.memory.upsert_thread(title=title, notes=str(th.get("notes") or "")[:300], status="open")
|
|
119
|
+
threads_updated += 1
|
|
120
|
+
rep = CognitionPassReport(
|
|
121
|
+
time.time(), 1, len(user_assistant), facts_added, threads_updated,
|
|
122
|
+
str(parsed.get("summary") or "Reflection pass completed.")[:240],
|
|
123
|
+
round((time.perf_counter() - t0) * 1000, 1), True,
|
|
124
|
+
)
|
|
125
|
+
except Exception as exc:
|
|
126
|
+
rep = CognitionPassReport(
|
|
127
|
+
time.time(), 1, len(user_assistant), 0, 0,
|
|
128
|
+
"Reflection skipped due to error.", round((time.perf_counter() - t0) * 1000, 1), False, str(exc),
|
|
129
|
+
)
|
|
130
|
+
self.history.insert(0, asdict(rep))
|
|
131
|
+
self.history = self.history[:20]
|
|
132
|
+
return rep
|
deadkey/config.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Cartridge-aware configuration with zero hardcoded C:\\legacy-readonly paths.
|
|
2
|
+
|
|
3
|
+
Every runtime path resolves from AGENT_HOME (or an explicit cartridge directory),
|
|
4
|
+
so the exact same engine can run deadkey or the operator's AI Media Studio Director with
|
|
5
|
+
complete isolation of memory, identity, voice, and tool packs.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class CartridgeConfig:
|
|
18
|
+
agent_id: str
|
|
19
|
+
display_name: str
|
|
20
|
+
home_dir: Path
|
|
21
|
+
memory_dir: Path
|
|
22
|
+
db_path: Path
|
|
23
|
+
ledger_path: Path
|
|
24
|
+
audit_dir: Path
|
|
25
|
+
workspace_roots: tuple[Path, ...]
|
|
26
|
+
enabled_packs: tuple[str, ...]
|
|
27
|
+
voice_profile: str = "tara"
|
|
28
|
+
architecture: str = "arch_a" # "arch_a" (Streaming Orpheus GPU) | "arch_b" (CPU Pocket TTS + Max-Brain GPU)
|
|
29
|
+
provider_profile: str = "qwen36-a3b"
|
|
30
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def from_manifest(cls, manifest_path: str | Path) -> "CartridgeConfig":
|
|
34
|
+
p = Path(manifest_path).resolve()
|
|
35
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
36
|
+
home = p.parent
|
|
37
|
+
mem = (home / data.get("memory_dir", "data/memory")).resolve()
|
|
38
|
+
audit = (home / data.get("audit_dir", "data/audit")).resolve()
|
|
39
|
+
roots = tuple((home / r).resolve() if not Path(r).is_absolute() else Path(r)
|
|
40
|
+
for r in data.get("workspace_roots", ["workspace"]))
|
|
41
|
+
return cls(
|
|
42
|
+
agent_id=data["agent_id"],
|
|
43
|
+
display_name=data["display_name"],
|
|
44
|
+
home_dir=home,
|
|
45
|
+
memory_dir=mem,
|
|
46
|
+
db_path=(home / data.get("db_path", "data/memory.db")).resolve(),
|
|
47
|
+
ledger_path=(mem / data.get("ledger_file", "ledger.jsonl")).resolve(),
|
|
48
|
+
audit_dir=audit,
|
|
49
|
+
workspace_roots=roots,
|
|
50
|
+
enabled_packs=tuple(data.get("enabled_packs", ["core", "memory"])),
|
|
51
|
+
voice_profile=data.get("voice_profile", "tara"),
|
|
52
|
+
architecture=os.environ.get("AGENT_ARCH", data.get("architecture", "arch_a")),
|
|
53
|
+
provider_profile=os.environ.get("AGENT_MODEL_PROFILE", data.get("provider_profile", "qwen36-a3b")),
|
|
54
|
+
extra=data.get("extra", {}),
|
|
55
|
+
)
|
deadkey/doctor.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Deadkey / Deadkey Environment Doctor — 1-command readiness check for any GPU or CPU machine.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
python -m deadkey.doctor
|
|
5
|
+
python -m deadkey.doctor --json
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import platform
|
|
13
|
+
import shutil
|
|
14
|
+
import sqlite3
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
ROOT = Path(__file__).resolve().parent.parent
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _check_gpu() -> dict[str, Any]:
|
|
24
|
+
if not shutil.which("nvidia-smi"):
|
|
25
|
+
return {"ok": False, "detail": "nvidia-smi not found (CPU-only or non-NVIDIA host)"}
|
|
26
|
+
try:
|
|
27
|
+
out = subprocess.check_output(
|
|
28
|
+
["nvidia-smi", "--query-gpu=name,memory.total,memory.free,driver_version", "--format=csv,noheader"],
|
|
29
|
+
text=True,
|
|
30
|
+
timeout=5,
|
|
31
|
+
).strip()
|
|
32
|
+
line = out.splitlines()[0]
|
|
33
|
+
parts = [p.strip() for p in line.split(",")]
|
|
34
|
+
return {
|
|
35
|
+
"ok": True,
|
|
36
|
+
"name": parts[0],
|
|
37
|
+
"vram_total": parts[1] if len(parts) > 1 else "",
|
|
38
|
+
"vram_free": parts[2] if len(parts) > 2 else "",
|
|
39
|
+
"driver": parts[3] if len(parts) > 3 else "",
|
|
40
|
+
"detail": f"{parts[0]} ({parts[1]} total, {parts[2]} free, driver {parts[3]})",
|
|
41
|
+
}
|
|
42
|
+
except Exception as exc:
|
|
43
|
+
return {"ok": False, "detail": f"nvidia-smi error: {exc}"}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _check_sqlite_fts5() -> dict[str, Any]:
|
|
47
|
+
try:
|
|
48
|
+
conn = sqlite3.connect(":memory:")
|
|
49
|
+
conn.execute("CREATE VIRTUAL TABLE _fts_test USING fts5(body)")
|
|
50
|
+
conn.close()
|
|
51
|
+
return {"ok": True, "detail": f"SQLite {sqlite3.sqlite_version} + FTS5 enabled (0 MiB GPU VRAM)"}
|
|
52
|
+
except Exception as exc:
|
|
53
|
+
return {"ok": False, "detail": f"SQLite FTS5 unavailable: {exc}"}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _find_llama_server() -> dict[str, Any]:
|
|
57
|
+
candidates = [
|
|
58
|
+
ROOT / "engines" / "llama-b12780-cu135" / "llama-server.exe",
|
|
59
|
+
ROOT / "engines" / "llama-server.exe",
|
|
60
|
+
ROOT / "engines" / "llama-server",
|
|
61
|
+
]
|
|
62
|
+
which_hit = shutil.which("llama-server")
|
|
63
|
+
if which_hit:
|
|
64
|
+
candidates.append(Path(which_hit))
|
|
65
|
+
for c in candidates:
|
|
66
|
+
if c.is_file():
|
|
67
|
+
return {"ok": True, "path": str(c), "detail": f"Found {c}"}
|
|
68
|
+
return {"ok": False, "detail": "No local llama-server binary found (install llama.cpp or point DEADKEY_MODELS_PROFILE)"}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _check_cartridges() -> dict[str, Any]:
|
|
72
|
+
cdir = ROOT / "cartridges"
|
|
73
|
+
found = sorted(p.parent.name for p in cdir.glob("*/manifest.json")) if cdir.exists() else []
|
|
74
|
+
has_blank = "blank-lab" in found
|
|
75
|
+
return {
|
|
76
|
+
"ok": bool(found),
|
|
77
|
+
"cartridges": found,
|
|
78
|
+
"zero_pii_blank_ready": has_blank,
|
|
79
|
+
"detail": f"Cartridges: {', '.join(found) or 'none'} (blank-lab={'ready' if has_blank else 'missing'})",
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _check_profile() -> dict[str, Any]:
|
|
84
|
+
env_p = os.environ.get("DEADKEY_MODELS_PROFILE", "").strip()
|
|
85
|
+
candidates = [
|
|
86
|
+
Path(env_p) if env_p else None,
|
|
87
|
+
ROOT / "profiles" / "models.json",
|
|
88
|
+
ROOT / "profiles" / "laptop_4080_12gb.json",
|
|
89
|
+
ROOT / "profiles" / "laptop_4080_12gb.json",
|
|
90
|
+
ROOT / "profiles" / "models.example.json",
|
|
91
|
+
]
|
|
92
|
+
for p in candidates:
|
|
93
|
+
if p and p.is_file():
|
|
94
|
+
try:
|
|
95
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
96
|
+
on_disk = sum(1 for m in data if Path(str(m.get("file", ""))).is_file())
|
|
97
|
+
return {
|
|
98
|
+
"ok": True,
|
|
99
|
+
"profile": str(p),
|
|
100
|
+
"total": len(data),
|
|
101
|
+
"on_disk": on_disk,
|
|
102
|
+
"detail": f"{p.name}: {on_disk}/{len(data)} GGUF models present on disk",
|
|
103
|
+
}
|
|
104
|
+
except Exception as exc:
|
|
105
|
+
return {"ok": False, "detail": f"Invalid JSON in {p}: {exc}"}
|
|
106
|
+
return {"ok": False, "detail": "No model profile JSON found in profiles/"}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def run_doctor() -> dict[str, Any]:
|
|
110
|
+
checks = {
|
|
111
|
+
"python": {
|
|
112
|
+
"ok": sys.version_info >= (3, 10),
|
|
113
|
+
"detail": f"Python {platform.python_version()} ({platform.system()} {platform.machine()})",
|
|
114
|
+
},
|
|
115
|
+
"sqlite_fts5": _check_sqlite_fts5(),
|
|
116
|
+
"gpu": _check_gpu(),
|
|
117
|
+
"llama_server": _find_llama_server(),
|
|
118
|
+
"cartridges": _check_cartridges(),
|
|
119
|
+
"models_profile": _check_profile(),
|
|
120
|
+
}
|
|
121
|
+
core_ok = checks["python"]["ok"] and checks["sqlite_fts5"]["ok"] and checks["cartridges"]["ok"]
|
|
122
|
+
return {"ok": core_ok, "root": str(ROOT), "checks": checks}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def main() -> int:
|
|
126
|
+
ap = argparse.ArgumentParser(description="Deadkey / Deadkey Environment Doctor")
|
|
127
|
+
ap.add_argument("--json", action="store_true", help="Output raw JSON")
|
|
128
|
+
args = ap.parse_args()
|
|
129
|
+
res = run_doctor()
|
|
130
|
+
if args.json:
|
|
131
|
+
print(json.dumps(res, indent=2))
|
|
132
|
+
return 0 if res["ok"] else 1
|
|
133
|
+
|
|
134
|
+
print("=" * 68)
|
|
135
|
+
print(" DEADKEY — ENVIRONMENT DOCTOR (0-VRAM Memory + 2-Tier Gate)")
|
|
136
|
+
print("=" * 68)
|
|
137
|
+
for name, info in res["checks"].items():
|
|
138
|
+
tag = "PASS" if info.get("ok") else "WARN"
|
|
139
|
+
print(f" [{tag}] {name:16s}: {info.get('detail')}")
|
|
140
|
+
print("-" * 68)
|
|
141
|
+
print(" Quickstart:")
|
|
142
|
+
print(" 1. Verify kernel : python -m bench.reproduce_all --quick")
|
|
143
|
+
print(" 2. Launch UI : python -m deadkey.server --cartridge cartridges/blank-lab/manifest.json --port 8765")
|
|
144
|
+
print(" 3. MCP server : python -m deadkey.mcp_server --db ./memory.db")
|
|
145
|
+
print("=" * 68)
|
|
146
|
+
return 0 if res["ok"] else 1
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
if __name__ == "__main__":
|
|
150
|
+
raise SystemExit(main())
|