krouter-memory 2.2.1__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.
- krouter/__init__.py +184 -0
- krouter/cli.py +102 -0
- krouter/demo.py +110 -0
- krouter/doctor.py +331 -0
- krouter/integrations/__init__.py +1 -0
- krouter/integrations/langgraph.py +883 -0
- krouter/integrations/langgraph_demo.py +82 -0
- krouter/integrations/llamaindex.py +44 -0
- krouter/sample.py +257 -0
- krouter/view.py +230 -0
- krouter/view_ui/app.css +123 -0
- krouter/view_ui/app.js +349 -0
- krouter/view_ui/index.html +31 -0
- krouter/viewdata.py +572 -0
- krouter/why.py +824 -0
- krouter_memory-2.2.1.dist-info/METADATA +378 -0
- krouter_memory-2.2.1.dist-info/RECORD +98 -0
- krouter_memory-2.2.1.dist-info/WHEEL +5 -0
- krouter_memory-2.2.1.dist-info/entry_points.txt +2 -0
- krouter_memory-2.2.1.dist-info/licenses/LICENSE +21 -0
- krouter_memory-2.2.1.dist-info/top_level.txt +4 -0
- krouter_router/answer_cards.py +297 -0
- krouter_router/ask_product.py +400 -0
- krouter_router/ask_reader.py +189 -0
- krouter_router/associate.py +506 -0
- krouter_router/backup.py +418 -0
- krouter_router/canonical_lookup.py +392 -0
- krouter_router/canonical_sources.psv +11 -0
- krouter_router/capture_ledger.py +168 -0
- krouter_router/checkup.py +223 -0
- krouter_router/cocite.py +91 -0
- krouter_router/compile_subconscious.py +513 -0
- krouter_router/consolidate_topics.py +242 -0
- krouter_router/corrections.py +455 -0
- krouter_router/evidence.py +601 -0
- krouter_router/experience.py +759 -0
- krouter_router/hot.py +246 -0
- krouter_router/import_claude_mem.py +419 -0
- krouter_router/import_sessions.py +1015 -0
- krouter_router/kb.py +955 -0
- krouter_router/krouter_home.py +85 -0
- krouter_router/krouter_redact.py +131 -0
- krouter_router/learn_mentions.py +273 -0
- krouter_router/lexicon_zh2.txt +23631 -0
- krouter_router/llm.py +871 -0
- krouter_router/mcp_server.py +1153 -0
- krouter_router/nightly.py +333 -0
- krouter_router/notify.py +70 -0
- krouter_router/propose_aliases.py +232 -0
- krouter_router/pyfind.sh +36 -0
- krouter_router/recall_index.py +1560 -0
- krouter_router/recollect.py +1142 -0
- krouter_router/reconsolidate.py +188 -0
- krouter_router/route_knowledge.py +684 -0
- krouter_router/route_knowledge.sh +336 -0
- krouter_router/route_worker.py +83 -0
- krouter_router/session_hook.py +676 -0
- krouter_router/skills.py +853 -0
- krouter_router/team.py +335 -0
- krouter_router/zones.py +199 -0
- krouter_router/zones_en.psv +40 -0
- krouter_template/01 /351/241/271/347/233/256//347/244/272/344/276/213/351/241/271/347/233/256//347/244/272/344/276/213/351/241/271/347/233/256.md" +8 -0
- krouter_template/01 /351/241/271/347/233/256//351/241/271/347/233/256.md" +10 -0
- krouter_template/02 /347/273/217/351/252/214/344/270/216/346/226/271/346/263/225/Agent//347/224/250/346/210/267/345/201/217/345/245/275/344/270/216/345/267/245/344/275/234/347/272/246/346/235/237.md" +10 -0
- krouter_template/02 /347/273/217/351/252/214/344/270/216/346/226/271/346/263/225/Automation/Seal the day from the log file.md" +28 -0
- krouter_template/02 /347/273/217/351/252/214/344/270/216/346/226/271/346/263/225//345/207/206/347/273/217/351/252/214/A timer that fired is not a product.md" +36 -0
- krouter_template/02 /347/273/217/351/252/214/344/270/216/346/226/271/346/263/225//345/207/206/347/273/217/351/252/214//345/207/206/347/273/217/351/252/214/345/205/245/345/217/243.md" +19 -0
- krouter_template/02 /347/273/217/351/252/214/344/270/216/346/226/271/346/263/225//347/273/217/351/252/214/344/270/216/346/226/271/346/263/225.md" +31 -0
- krouter_template/03 /350/265/204/346/226/231/344/270/216/350/257/201/346/215/256//350/265/204/346/226/231/344/270/216/350/257/201/346/215/256.md" +8 -0
- krouter_template/04 /345/267/262/345/256/214/346/210/220/344/270/216/345/244/215/347/233/230//345/267/262/345/256/214/346/210/220/344/270/216/345/244/215/347/233/230.md" +8 -0
- krouter_template/05 /346/227/266/351/227/264/346/227/245/345/277/227/2026-01/01/357/275/234/347/244/272/344/276/213/346/227/245.md" +9 -0
- krouter_template/05 /346/227/266/351/227/264/346/227/245/345/277/227//346/227/266/351/227/264/346/227/245/345/277/227/345/205/245/345/217/243.md" +8 -0
- krouter_template/90 /347/263/273/347/273/237/346/226/207/344/273/266/Agent/350/256/260/345/277/206//345/217/257/351/235/240/350/256/260/345/277/206/347/264/242/345/274/225.md" +8 -0
- krouter_template/90 /347/263/273/347/273/237/346/226/207/344/273/266/Agent/350/256/260/345/277/206//347/272/240/351/224/231/344/270/216/345/217/226/344/273/243/350/256/260/345/275/225.md" +8 -0
- krouter_template/90 /347/263/273/347/273/237/346/226/207/344/273/266/Clippings /346/225/264/347/220/206/350/256/260/345/275/225.json" +3 -0
- krouter_template/90 /347/263/273/347/273/237/346/226/207/344/273/266//347/212/266/346/200/201.md" +10 -0
- krouter_template/90 /347/263/273/347/273/237/346/226/207/344/273/266//350/207/252/345/212/250/345/214/226//346/227/245/346/233/264/345/201/245/345/272/267.md" +15 -0
- krouter_template/90 /347/263/273/347/273/237/346/226/207/344/273/266//350/207/252/345/212/250/345/214/226//350/207/252/350/277/233/345/214/226/351/222/245/345/214/231.md" +38 -0
- krouter_template/Agent/347/254/254/344/272/214/345/244/247/350/204/221.md +29 -0
- krouter_template_zh/01 /351/241/271/347/233/256//347/244/272/344/276/213/351/241/271/347/233/256//347/244/272/344/276/213/351/241/271/347/233/256.md" +8 -0
- krouter_template_zh/01 /351/241/271/347/233/256//351/241/271/347/233/256.md" +10 -0
- krouter_template_zh/02 /347/273/217/351/252/214/344/270/216/346/226/271/346/263/225/Agent//347/224/250/346/210/267/345/201/217/345/245/275/344/270/216/345/267/245/344/275/234/347/272/246/346/235/237.md" +10 -0
- krouter_template_zh/02 /347/273/217/351/252/214/344/270/216/346/226/271/346/263/225//345/207/206/347/273/217/351/252/214//345/207/206/347/273/217/351/252/214/345/205/245/345/217/243.md" +19 -0
- krouter_template_zh/02 /347/273/217/351/252/214/344/270/216/346/226/271/346/263/225//345/207/206/347/273/217/351/252/214//345/256/232/346/227/266/345/231/250/345/223/215/344/272/206/344/270/215/347/255/211/344/272/216/346/264/273/345/271/262/345/256/214/344/272/206.md" +36 -0
- krouter_template_zh/02 /347/273/217/351/252/214/344/270/216/346/226/271/346/263/225//347/273/217/351/252/214/344/270/216/346/226/271/346/263/225.md" +31 -0
- krouter_template_zh/02 /347/273/217/351/252/214/344/270/216/346/226/271/346/263/225//350/207/252/345/212/250/345/214/226//346/214/211/346/227/245/345/277/227/346/226/207/344/273/266/345/210/244/346/226/255/345/260/201/350/264/246.md" +28 -0
- krouter_template_zh/03 /350/265/204/346/226/231/344/270/216/350/257/201/346/215/256//350/265/204/346/226/231/344/270/216/350/257/201/346/215/256.md" +8 -0
- krouter_template_zh/04 /345/267/262/345/256/214/346/210/220/344/270/216/345/244/215/347/233/230//345/267/262/345/256/214/346/210/220/344/270/216/345/244/215/347/233/230.md" +8 -0
- krouter_template_zh/05 /346/227/266/351/227/264/346/227/245/345/277/227/2026-01/01/357/275/234/347/244/272/344/276/213/346/227/245.md" +9 -0
- krouter_template_zh/05 /346/227/266/351/227/264/346/227/245/345/277/227//346/227/266/351/227/264/346/227/245/345/277/227/345/205/245/345/217/243.md" +8 -0
- krouter_template_zh/90 /347/263/273/347/273/237/346/226/207/344/273/266/Agent/350/256/260/345/277/206//345/217/257/351/235/240/350/256/260/345/277/206/347/264/242/345/274/225.md" +8 -0
- krouter_template_zh/90 /347/263/273/347/273/237/346/226/207/344/273/266/Agent/350/256/260/345/277/206//347/272/240/351/224/231/344/270/216/345/217/226/344/273/243/350/256/260/345/275/225.md" +8 -0
- krouter_template_zh/90 /347/263/273/347/273/237/346/226/207/344/273/266/Clippings /346/225/264/347/220/206/350/256/260/345/275/225.json" +3 -0
- krouter_template_zh/90 /347/263/273/347/273/237/346/226/207/344/273/266/canonical_sources.psv" +11 -0
- krouter_template_zh/90 /347/263/273/347/273/237/346/226/207/344/273/266//347/212/266/346/200/201.md" +10 -0
- krouter_template_zh/90 /347/263/273/347/273/237/346/226/207/344/273/266//350/207/252/345/212/250/345/214/226//346/227/245/346/233/264/345/201/245/345/272/267.md" +15 -0
- krouter_template_zh/90 /347/263/273/347/273/237/346/226/207/344/273/266//350/207/252/345/212/250/345/214/226//350/207/252/350/277/233/345/214/226/351/222/245/345/214/231.md" +38 -0
- krouter_template_zh/Agent/347/254/254/344/272/214/345/244/247/350/204/221.md +29 -0
krouter/__init__.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""KRouter from Python: ask your memory a question, check its health, write a note.
|
|
2
|
+
|
|
3
|
+
import krouter
|
|
4
|
+
a = krouter.ask("how do we ship a release?")
|
|
5
|
+
a.page, a.how, a.refused # the page it came from, the one-line answer, True when the memory does not know
|
|
6
|
+
a.references # knowledge-base pages (reference material), listed apart from the answer
|
|
7
|
+
krouter.note("Releases are tagged from main only.", kind="decision")
|
|
8
|
+
|
|
9
|
+
The memory is `vault=`, else `KROUTER_VAULT` (`OBSIDIAN_VAULT`, the older name, also works), else the folder the
|
|
10
|
+
one-line install recorded (`~/.config/krouter/vault`).
|
|
11
|
+
Lookups run on this machine; nothing is sent anywhere.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
__version__ = "2.2.1"
|
|
23
|
+
ROUTES = ("search", "preference", "correction", "memory", "project", "suggest")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def router_dir() -> Path:
|
|
27
|
+
"""The router's scripts: the copy installed with this package, else the repository this file sits in."""
|
|
28
|
+
try:
|
|
29
|
+
import krouter_router # 打包时随包装进来的那份路由器
|
|
30
|
+
|
|
31
|
+
return Path(list(krouter_router.__path__)[0]).resolve() # 没有 __init__.py 的命名空间包,只有 __path__
|
|
32
|
+
except ImportError:
|
|
33
|
+
here = Path(__file__).resolve().parents[2] / "skill" / "krouter" / "scripts"
|
|
34
|
+
if (here / "route_knowledge.py").exists():
|
|
35
|
+
return here
|
|
36
|
+
raise RuntimeError("KRouter's router scripts were not found; reinstall the package") from None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Answer:
|
|
41
|
+
"""One receipt. `fields` holds every `key: value` line; the properties name the ones most callers need."""
|
|
42
|
+
|
|
43
|
+
text: str
|
|
44
|
+
fields: dict = field(default_factory=dict)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def hits(self) -> list[dict]:
|
|
48
|
+
"""The pages recall listed, best first: `{"page", "tier", "status", "how"}`. A replaced page can be listed
|
|
49
|
+
(tier `dead`, status `superseded`) so you see it was replaced; it is never the answer."""
|
|
50
|
+
out: list[dict] = []
|
|
51
|
+
inside = False
|
|
52
|
+
for line in self.text.splitlines():
|
|
53
|
+
if line.startswith("recall:"):
|
|
54
|
+
inside = line.strip() == "recall:"
|
|
55
|
+
continue
|
|
56
|
+
if not inside:
|
|
57
|
+
continue
|
|
58
|
+
if line.startswith("- "):
|
|
59
|
+
head, _, rest = line[2:].partition(" tier=")
|
|
60
|
+
meta = dict(kv.split("=", 1) for kv in ("tier=" + rest).split() if "=" in kv) if rest else {}
|
|
61
|
+
out.append({"page": head.strip(), "tier": meta.get("tier", ""), "status": meta.get("status", ""), "how": ""})
|
|
62
|
+
elif line.startswith(" how: ") and out:
|
|
63
|
+
out[-1]["how"] = line[len(" how: "):].strip()
|
|
64
|
+
elif not line.startswith(" "):
|
|
65
|
+
inside = False
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def references(self) -> list[dict]:
|
|
70
|
+
"""Pages of the knowledge base the receipt listed apart (`knowledge_base:`): reference material someone else
|
|
71
|
+
wrote, never the answer to what you decided. `{"page", "kb", "title", "source"}`, best first."""
|
|
72
|
+
out: list[dict] = []
|
|
73
|
+
inside = False
|
|
74
|
+
for line in self.text.splitlines():
|
|
75
|
+
if line.startswith("knowledge_base:"):
|
|
76
|
+
inside = True
|
|
77
|
+
continue
|
|
78
|
+
if not inside:
|
|
79
|
+
continue
|
|
80
|
+
if line.startswith("- "):
|
|
81
|
+
head, _, rest = line[2:].partition(" kb=")
|
|
82
|
+
out.append({"page": head.strip(), "kb": rest.split()[0] if rest else "", "title": "", "source": ""})
|
|
83
|
+
elif line.startswith(" title: ") and out:
|
|
84
|
+
out[-1]["title"] = line[len(" title: "):].strip()
|
|
85
|
+
elif line.startswith(" source: ") and out:
|
|
86
|
+
out[-1]["source"] = line[len(" source: "):].strip()
|
|
87
|
+
elif not line.startswith(" "):
|
|
88
|
+
inside = False
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def state(self) -> str:
|
|
93
|
+
"""The receipt's first line, as one word: `direct` (an alias lock or `high`: answer from the page), `related`
|
|
94
|
+
(only related pages: answer only if one of them states it outright), `none` (the memory does not have it;
|
|
95
|
+
also `related` under strict mode)."""
|
|
96
|
+
import re
|
|
97
|
+
|
|
98
|
+
m = re.match(r"[a-z]+", self.fields.get("memory", ""))
|
|
99
|
+
return m.group(0) if m else ""
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def memory_none(self) -> bool:
|
|
103
|
+
"""True when your memory has nothing on the question and only the knowledge base matched."""
|
|
104
|
+
return self.fields.get("memory", "").startswith("none")
|
|
105
|
+
|
|
106
|
+
def _top(self) -> dict:
|
|
107
|
+
return next((h for h in self.hits if h["tier"] != "dead" and h["status"] != "superseded"), {})
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def page(self) -> str:
|
|
111
|
+
"""The page the answer comes from: the locked page on an exact match, else recall's best live page."""
|
|
112
|
+
if self.fields.get("canonical_match") == "true":
|
|
113
|
+
return self.fields.get("source", "")
|
|
114
|
+
return "" if self.refused else self._top().get("page", "")
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def how(self) -> str:
|
|
118
|
+
"""The one line that answers it (recall's `how:`), empty when the memory does not know."""
|
|
119
|
+
return "" if self.refused else (self._top().get("how") or self.fields.get("how", ""))
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def refused(self) -> bool:
|
|
123
|
+
return self.fields.get("recall", "").startswith("none")
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def confidence(self) -> str:
|
|
127
|
+
return self.fields.get("recall_confidence", "")
|
|
128
|
+
|
|
129
|
+
def __str__(self) -> str:
|
|
130
|
+
return self.text
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _parse(text: str) -> dict:
|
|
134
|
+
out: dict = {}
|
|
135
|
+
for line in text.splitlines():
|
|
136
|
+
if ": " in line and not line.startswith((" ", "-", "|")):
|
|
137
|
+
k, v = line.split(": ", 1)
|
|
138
|
+
out.setdefault(k.strip(), v.strip())
|
|
139
|
+
return out
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _env(vault: str | os.PathLike | None) -> dict:
|
|
143
|
+
env = dict(os.environ)
|
|
144
|
+
if vault: # 点名的文件夹优先:子进程里 KROUTER_VAULT 会盖过 OBSIDIAN_VAULT,所以两个都设成它
|
|
145
|
+
env["KROUTER_VAULT"] = env["OBSIDIAN_VAULT"] = str(Path(vault).expanduser())
|
|
146
|
+
return env
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def ask(question: str, route: str = "search", vault: str | os.PathLike | None = None, timeout: float = 120) -> Answer:
|
|
150
|
+
"""Look the question up in the memory. `route` narrows where it looks (see ROUTES)."""
|
|
151
|
+
if route not in ROUTES:
|
|
152
|
+
raise ValueError(f"route must be one of {', '.join(ROUTES)}")
|
|
153
|
+
proc = subprocess.run([sys.executable, str(router_dir() / "route_knowledge.py"), route, question],
|
|
154
|
+
env=_env(vault), capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL)
|
|
155
|
+
if proc.returncode != 0:
|
|
156
|
+
raise RuntimeError((proc.stderr or proc.stdout or f"router exited {proc.returncode}").strip()[-2000:])
|
|
157
|
+
return Answer(proc.stdout.strip(), _parse(proc.stdout))
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def status(vault: str | os.PathLike | None = None) -> Answer:
|
|
161
|
+
"""Health of the memory and of the nightly job, with what to do when something is off."""
|
|
162
|
+
proc = subprocess.run([sys.executable, str(router_dir() / "route_knowledge.py"), "status", ""], env=_env(vault),
|
|
163
|
+
capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
|
|
164
|
+
return Answer(proc.stdout.strip(), _parse(proc.stdout))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def note(text: str, kind: str = "note", vault: str | os.PathLike | None = None) -> str:
|
|
168
|
+
"""Write one line to today's notes page (a clue, not a rule), listed in the change ledger and one git commit."""
|
|
169
|
+
sys.path.insert(0, str(router_dir()))
|
|
170
|
+
import mcp_server
|
|
171
|
+
|
|
172
|
+
saved = os.environ.get("OBSIDIAN_VAULT")
|
|
173
|
+
if vault:
|
|
174
|
+
os.environ["OBSIDIAN_VAULT"] = str(Path(vault).expanduser())
|
|
175
|
+
try:
|
|
176
|
+
msg, err = mcp_server.note({"text": text, "kind": kind})
|
|
177
|
+
finally: # 不改调用方进程的环境
|
|
178
|
+
if saved is None:
|
|
179
|
+
os.environ.pop("OBSIDIAN_VAULT", None)
|
|
180
|
+
else:
|
|
181
|
+
os.environ["OBSIDIAN_VAULT"] = saved
|
|
182
|
+
if err:
|
|
183
|
+
raise ValueError(msg)
|
|
184
|
+
return msg
|
krouter/cli.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""`krouter ask|why|view|status|doctor|note|kb|demo|mcp`: the same lookups from a terminal, an explanation of one, a read-only page about the memory, a one-verdict check, the knowledge base, and the MCP server."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import ROUTES, __version__, ask, note, router_dir, status
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def env_lang() -> str:
|
|
13
|
+
"""en or zh from LC_ALL / LC_MESSAGES / LANG (the first one set; C and POSIX say nothing); en when none does."""
|
|
14
|
+
for var in ("LC_ALL", "LC_MESSAGES", "LANG"):
|
|
15
|
+
val = os.environ.get(var, "").strip().lower()
|
|
16
|
+
if val and val.split(".")[0] not in ("c", "posix"):
|
|
17
|
+
return "zh" if val.startswith("zh") else "en"
|
|
18
|
+
return "en"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
22
|
+
ap = argparse.ArgumentParser(prog="krouter", description="Ask your KRouter memory from a terminal.")
|
|
23
|
+
ap.add_argument("--version", action="version", version=f"krouter {__version__}")
|
|
24
|
+
ap.add_argument("--vault", default=None, help="the memory folder (default: the installed one)")
|
|
25
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
26
|
+
a = sub.add_parser("ask", help="look a question up")
|
|
27
|
+
a.add_argument("question")
|
|
28
|
+
a.add_argument("--route", default="search", choices=ROUTES)
|
|
29
|
+
w = sub.add_parser("why", help="explain how a lookup came out: the alias or words that matched, why each page sits where it does, "
|
|
30
|
+
"why the confidence is that, what came along a connection, what replaced what (read only)")
|
|
31
|
+
w.add_argument("question")
|
|
32
|
+
w.add_argument("--lang", choices=("en", "zh"), default=None, help="language of the explanation (default: the memory's)")
|
|
33
|
+
w.add_argument("--json", action="store_true", help="the structured explanation instead of text")
|
|
34
|
+
v = sub.add_parser("view", help="a read-only page about the memory on this machine: pages, connections, experience cards, "
|
|
35
|
+
"what last night did, and a box that runs `why` (prints the address; add --open to open it)")
|
|
36
|
+
v.add_argument("--port", type=int, default=0, help="port on 127.0.0.1 (default: a free one)")
|
|
37
|
+
v.add_argument("--open", action="store_true", help="also open the address in the default browser (nothing opens without this)")
|
|
38
|
+
v.add_argument("--demo", action="store_true", help="show a throwaway sample memory instead of yours")
|
|
39
|
+
v.add_argument("--lang", choices=("en", "zh"), default=None, help="language of the --demo memory")
|
|
40
|
+
v.add_argument("--verbose", action="store_true", help="log each request to stderr")
|
|
41
|
+
sub.add_parser("status", help="health of the memory and the nightly job (the raw receipt)")
|
|
42
|
+
sub.add_parser("doctor", help="one verdict: OK, or what is missing and the command that fixes it")
|
|
43
|
+
n = sub.add_parser("note", help="write one line into the memory")
|
|
44
|
+
n.add_argument("text")
|
|
45
|
+
n.add_argument("--kind", default="note", choices=("decision", "correction", "note"))
|
|
46
|
+
d = sub.add_parser("demo", help="decide, change your mind, ask: on a throwaway memory, no install, no key")
|
|
47
|
+
d.add_argument("--lang", choices=("en", "zh"), default=env_lang())
|
|
48
|
+
d.add_argument("--keep", action="store_true", help="keep the demo memory to look at")
|
|
49
|
+
k = sub.add_parser("kb", help="the knowledge base: declare reference folders (add / remove / list), see folders that "
|
|
50
|
+
"look like reference material (suggest), import a PDF, Word or HTML file (import)")
|
|
51
|
+
k.add_argument("rest", nargs=argparse.REMAINDER)
|
|
52
|
+
m = sub.add_parser("mcp", help="run the MCP server (stdio; --http for a team server)")
|
|
53
|
+
m.add_argument("rest", nargs=argparse.REMAINDER)
|
|
54
|
+
return ap
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def main(argv: list[str] | None = None) -> int:
|
|
58
|
+
args = build_parser().parse_args(argv)
|
|
59
|
+
if args.cmd == "ask":
|
|
60
|
+
print(ask(args.question, args.route, args.vault))
|
|
61
|
+
elif args.cmd == "status":
|
|
62
|
+
print(status(args.vault))
|
|
63
|
+
elif args.cmd in ("why", "view"):
|
|
64
|
+
sys.path.insert(0, str(router_dir()))
|
|
65
|
+
from krouter_home import vault_path
|
|
66
|
+
|
|
67
|
+
vault = args.vault or vault_path()
|
|
68
|
+
if args.cmd == "why":
|
|
69
|
+
if not vault:
|
|
70
|
+
print("set KROUTER_VAULT to your memory folder, or pass --vault", file=sys.stderr)
|
|
71
|
+
return 2
|
|
72
|
+
from .why import run as why_run
|
|
73
|
+
|
|
74
|
+
return why_run(vault, args.question, args.lang, args.json)
|
|
75
|
+
from .view import run as view_run
|
|
76
|
+
|
|
77
|
+
return view_run(vault, args.port, args.open, args.demo, args.verbose, args.lang or env_lang())
|
|
78
|
+
elif args.cmd == "doctor":
|
|
79
|
+
from .doctor import run as doctor
|
|
80
|
+
|
|
81
|
+
return doctor(args.vault)
|
|
82
|
+
elif args.cmd == "demo":
|
|
83
|
+
from .demo import run
|
|
84
|
+
|
|
85
|
+
return run(args.lang, args.keep)
|
|
86
|
+
elif args.cmd == "note":
|
|
87
|
+
print(note(args.text, args.kind, args.vault))
|
|
88
|
+
elif args.cmd == "kb":
|
|
89
|
+
sys.path.insert(0, str(router_dir()))
|
|
90
|
+
import kb
|
|
91
|
+
|
|
92
|
+
return kb.main((["--vault", args.vault] if args.vault else []) + args.rest)
|
|
93
|
+
else:
|
|
94
|
+
sys.path.insert(0, str(router_dir()))
|
|
95
|
+
import mcp_server
|
|
96
|
+
|
|
97
|
+
return mcp_server.main((["--vault", args.vault] if args.vault else []) + args.rest)
|
|
98
|
+
return 0
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
if __name__ == "__main__":
|
|
102
|
+
raise SystemExit(main())
|
krouter/demo.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""`krouter demo`: decide, change your mind, ask — on a throwaway memory, with no install, no key and no network.
|
|
2
|
+
|
|
3
|
+
Copies the bundled template to a temporary folder, writes two pages (Monday's decision, Wednesday's correction that
|
|
4
|
+
replaces it), asks three questions and prints what came back: the corrected answer with its page, the old page shown
|
|
5
|
+
as replaced rather than given as the answer, and a refusal for something the memory never heard of. The folder is
|
|
6
|
+
deleted afterwards unless `--keep`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import tempfile
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from . import ask, router_dir
|
|
17
|
+
|
|
18
|
+
PAGES = {
|
|
19
|
+
"en": {
|
|
20
|
+
"Release day.md": ("superseded", "2026-11-02", "", "Monday 2026-11-02: we ship a release every Friday afternoon."),
|
|
21
|
+
"Release day, changed.md": ("active", "2026-11-04", "Release day",
|
|
22
|
+
"Wednesday 2026-11-04: releases now ship every Tuesday morning, not Friday, "
|
|
23
|
+
"because QA runs on Mondays."),
|
|
24
|
+
},
|
|
25
|
+
"zh": {
|
|
26
|
+
"发版日.md": ("superseded", "2026-11-02", "", "周一 2026-11-02:每周五下午发版。"),
|
|
27
|
+
"发版日(改).md": ("active", "2026-11-04", "发版日", "周三 2026-11-04:发版改到每周二上午,不再周五,因为测试周一才跑完。"),
|
|
28
|
+
},
|
|
29
|
+
}
|
|
30
|
+
QUESTIONS = {
|
|
31
|
+
"en": ["when do we ship releases", "do we still ship releases on friday", "what is our on-call rotation"],
|
|
32
|
+
"zh": ["我们哪天发版", "还是周五发版吗", "值班表是怎么排的"],
|
|
33
|
+
}
|
|
34
|
+
SAY = {
|
|
35
|
+
"en": {"head": "KRouter demo: a throwaway memory in {v}",
|
|
36
|
+
"q": "? {q}", "a": " → {how}\n from: {page}", "old": " replaced, shown but not the answer: {page}",
|
|
37
|
+
"no": " → recall: none. The memory says it does not know instead of guessing.",
|
|
38
|
+
"keep": "Kept: {v} (a plain Markdown folder: open it in any editor, or in Obsidian).", "gone": "Deleted the demo memory. Next: the one-line install in the README."},
|
|
39
|
+
"zh": {"head": "KRouter 演示:临时记忆库在 {v}", "q": "?{q}",
|
|
40
|
+
"a": " → {how}\n 出处:{page}", "old": " 已被取代,只列出来、不当答案:{page}",
|
|
41
|
+
"no": " → recall: none。记忆里没有,直说不知道,不拿差不多的凑数。",
|
|
42
|
+
"keep": "保留在:{v}(纯 Markdown 文件夹,用任何编辑器或 Obsidian 打开看)。", "gone": "演示用的库已删除。下一步:README 里的一行安装。"},
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def template_dir(lang: str) -> Path:
|
|
47
|
+
"""The template packaged with KRouter, else the repository's own copy."""
|
|
48
|
+
name = "krouter_template_zh" if lang == "zh" else "krouter_template"
|
|
49
|
+
try:
|
|
50
|
+
mod = __import__(name)
|
|
51
|
+
return Path(list(mod.__path__)[0])
|
|
52
|
+
except ImportError:
|
|
53
|
+
return Path(__file__).resolve().parents[2] / ("template-zh" if lang == "zh" else "template")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def build(root: Path, lang: str) -> Path:
|
|
57
|
+
"""The template in a throwaway folder; in English with English folder and file names, as the install lays it."""
|
|
58
|
+
import sys
|
|
59
|
+
|
|
60
|
+
vault = root / "vault"
|
|
61
|
+
sys.path.insert(0, str(router_dir()))
|
|
62
|
+
import zones
|
|
63
|
+
|
|
64
|
+
if lang == "en":
|
|
65
|
+
zones.lay_out(template_dir(lang), vault, alias_sample=router_dir() / "canonical_sources.psv")
|
|
66
|
+
else:
|
|
67
|
+
shutil.copytree(template_dir(lang), vault)
|
|
68
|
+
rules = zones.path(vault, "02 经验与方法")
|
|
69
|
+
for name, (status, day, replaces, body) in PAGES[lang].items():
|
|
70
|
+
title = name[:-3]
|
|
71
|
+
fm = f"---\ntitle: {title}\nstatus: {status}\ndate: {day}\n"
|
|
72
|
+
fm += f"supersedes:\n - \"[[{replaces}]]\"\n" if replaces else ""
|
|
73
|
+
(rules / name).write_text(fm + f"---\n\n# {title}\n\n{body}\n", encoding="utf-8")
|
|
74
|
+
return vault
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def run(lang: str = "en", keep: bool = False) -> int:
|
|
78
|
+
lang = "zh" if lang == "zh" else "en"
|
|
79
|
+
say = SAY[lang]
|
|
80
|
+
root = Path(tempfile.mkdtemp(prefix="krouter-demo-"))
|
|
81
|
+
saved = {k: os.environ.get(k) for k in ("KROUTER_NO_QUERY_LOG", "KROUTER_CACHE_DIR", "KROUTER_STATE_DIR")}
|
|
82
|
+
os.environ.update({"KROUTER_NO_QUERY_LOG": "1", "KROUTER_CACHE_DIR": str(root / "cache"),
|
|
83
|
+
"KROUTER_STATE_DIR": str(root / "state")}) # 演示不碰真的查询日志和缓存
|
|
84
|
+
try:
|
|
85
|
+
vault = build(root, lang)
|
|
86
|
+
print(say["head"].format(v=vault) + "\n")
|
|
87
|
+
bodies = [v[3] for v in PAGES[lang].values()]
|
|
88
|
+
print(" " + bodies[0])
|
|
89
|
+
print(" " + bodies[1] + "\n")
|
|
90
|
+
for q in QUESTIONS[lang]:
|
|
91
|
+
a = ask(q, vault=vault)
|
|
92
|
+
print(say["q"].format(q=q))
|
|
93
|
+
if a.refused or not a.page:
|
|
94
|
+
print(say["no"])
|
|
95
|
+
else:
|
|
96
|
+
print(say["a"].format(how=a.how, page=a.page))
|
|
97
|
+
for h in a.hits:
|
|
98
|
+
if h["status"] == "superseded":
|
|
99
|
+
print(say["old"].format(page=h["page"]))
|
|
100
|
+
print()
|
|
101
|
+
print(say["keep"].format(v=vault) if keep else say["gone"])
|
|
102
|
+
return 0
|
|
103
|
+
finally:
|
|
104
|
+
for k, v in saved.items():
|
|
105
|
+
if v is None:
|
|
106
|
+
os.environ.pop(k, None)
|
|
107
|
+
else:
|
|
108
|
+
os.environ[k] = v
|
|
109
|
+
if not keep:
|
|
110
|
+
shutil.rmtree(root, ignore_errors=True)
|