keepfold 0.6.4__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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/app/server.py
ADDED
|
@@ -0,0 +1,3142 @@
|
|
|
1
|
+
"""`keepfold app`: a stdlib HTTP server on 127.0.0.1 and one page (docs/design/keepfold-app.md).
|
|
2
|
+
|
|
3
|
+
Security, because the app changes other apps' config files:
|
|
4
|
+
- a per-launch random token on every request: the page, its CSS and JS take it as `?t=` (the
|
|
5
|
+
page then cleans the URL); every API call sends it as the `X-Keepfold-Token` header;
|
|
6
|
+
- the Host must be the app's own loopback address (DNS rebinding), and any Origin its own;
|
|
7
|
+
- GET never changes anything; changes are POST with `Content-Type: application/json`;
|
|
8
|
+
- CSP `default-src 'self'`, no inline script; the page builds its DOM without innerHTML;
|
|
9
|
+
- in the browser it stops after 30 minutes idle, or on Quit; the desktop app (desktop.py: its
|
|
10
|
+
own window and a tray icon) runs until Quit.
|
|
11
|
+
Long actions run as background jobs, one at a time, with a progress line (`Jobs`).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hmac
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import secrets
|
|
21
|
+
import socket
|
|
22
|
+
import sys
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
import traceback
|
|
26
|
+
import unicodedata
|
|
27
|
+
import webbrowser
|
|
28
|
+
from contextlib import contextmanager
|
|
29
|
+
from functools import partial
|
|
30
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
31
|
+
from pathlib import Path, PurePosixPath
|
|
32
|
+
from urllib.parse import parse_qs, quote, unquote, urlsplit
|
|
33
|
+
|
|
34
|
+
from keepfold import update
|
|
35
|
+
from keepfold.app import actions, exports, news, status, targets, wizard
|
|
36
|
+
|
|
37
|
+
HOST = "127.0.0.1"
|
|
38
|
+
IDLE_S = 30 * 60
|
|
39
|
+
PRIVATE_S = 10 * 60 # the Private switch relocks by itself after 10 minutes
|
|
40
|
+
UPDATE_FIRST_S, UPDATE_EVERY_S = 60, 6 * 3600 # the quiet update check: a minute in, then 6 h
|
|
41
|
+
WATCH_S = 5 # seconds between idle checks
|
|
42
|
+
DRY_IDLE_S = 600 # X-ray's shared dry-run index goes after 10 unused minutes, as a model does
|
|
43
|
+
WARM_STATUS = True # `start` asks Status's slow probes at once (tests turn it off: conftest)
|
|
44
|
+
PIGGYBACK = True # C8: a fact-harvest pass after each Chat turn (tests turn it off: conftest)
|
|
45
|
+
MAX_BODY = 64 * 1024
|
|
46
|
+
PICTURE = "/api/brain/picture" # Save picture: a PNG in base64, so it has its own body cap
|
|
47
|
+
PICTURE_MAX = 8 * 1024 * 1024 # decoded bytes
|
|
48
|
+
MAX_UPLOAD = 4 * 2**30
|
|
49
|
+
UPLOAD = "/api/import/upload" # the one raw (not JSON) POST: an export file, streamed to disk
|
|
50
|
+
UPLOAD_EXT = (".zip", ".json", ".html", ".md", ".txt", ".ics", ".mbox",
|
|
51
|
+
".pdf", ".docx", # these two: a document, or a file attached in Chat (C1)
|
|
52
|
+
".apkg", ".colpkg") # Anki exports (R22)
|
|
53
|
+
CLOUD_FIELDS = ("cloud_processing", "provider", "model", "base_url", "api_key_env")
|
|
54
|
+
IMPORTS = ("claude", "chatgpt", "gemini", "perplexity", "google-activity", "notes", "calendar",
|
|
55
|
+
"docs", "repos", "highlights", "mail", "selfchat", "location",
|
|
56
|
+
"photos", "spotify", "voice-memos", "anki")
|
|
57
|
+
ASSETS = Path(__file__).resolve().parents[1] / "assets" / "app"
|
|
58
|
+
_JS, _CSS = "text/javascript; charset=utf-8", "text/css; charset=utf-8"
|
|
59
|
+
# path -> (its file, type); "/" is the live home, filled by dashboard.render_live
|
|
60
|
+
STATIC = {"/": (None, "text/html; charset=utf-8"),
|
|
61
|
+
"/manage": (ASSETS / "index.html", "text/html; charset=utf-8"),
|
|
62
|
+
"/app.css": (ASSETS / "app.css", _CSS), "/app.js": (ASSETS / "app.js", _JS),
|
|
63
|
+
# quick capture's box (the desktop app's hotkey): its own small page
|
|
64
|
+
"/capture": (ASSETS / "capture.html", "text/html; charset=utf-8"),
|
|
65
|
+
"/capture.js": (ASSETS / "capture.js", _JS),
|
|
66
|
+
"/dashboard.css": (ASSETS.parent / "dashboard.css", _CSS),
|
|
67
|
+
"/favicon.ico": (ASSETS.parent / "keepfold.ico", "image/x-icon"), # browsers ask unasked
|
|
68
|
+
**{"/" + n: (ASSETS.parent / n, _JS) for n in ("d3.v7.min.js", "brain3d.js",
|
|
69
|
+
"dashboard.js")}}
|
|
70
|
+
CAPTURE_MAX = 1000 # quick capture: a line's characters
|
|
71
|
+
URL_ONLY = re.compile(r"https?://\S+", re.I) # a quick-capture line that is one link
|
|
72
|
+
PAGE_ROWS = 20 # the private chats list, a page at a time
|
|
73
|
+
PORT = 47615 # tried first: one origin across launches keeps the page's theme and brain style
|
|
74
|
+
QUERY_GETS = {"/api/chat/get", "/api/chat/passage", "/api/home", # GETs that read the query
|
|
75
|
+
"/api/home/delta", "/api/home/site", "/api/status", "/api/browse/private-chats",
|
|
76
|
+
"/api/chat/pages"}
|
|
77
|
+
CSP = ("default-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; "
|
|
78
|
+
"frame-ancestors 'none'")
|
|
79
|
+
EXPIRED = (b"<!doctype html><meta charset=utf-8><title>Keepfold</title><p>This link has no valid "
|
|
80
|
+
b"key. Open the link that <code>keepfold app</code> printed, or run it again.</p>")
|
|
81
|
+
EXPIRED_INSTALLED = (b"<!doctype html><meta charset=utf-8><title>Keepfold</title><p>This link "
|
|
82
|
+
b"has no valid key. Open Keepfold from the Start menu again.</p>")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def snapshot_name() -> str:
|
|
86
|
+
return f"keepfold-snapshot-{time.strftime('%Y-%m-%d')}.html"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def reopen() -> str:
|
|
90
|
+
"""How this user reopens the app (A12): the Start menu for an installer install."""
|
|
91
|
+
return ("Open Keepfold from the Start menu to reopen it." if update.mode() == "installer"
|
|
92
|
+
else "Run keepfold app again to reopen it.")
|
|
93
|
+
_open = webbrowser.open # tests replace this
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _checkout() -> Path:
|
|
97
|
+
from keepfold import cli
|
|
98
|
+
return cli.CHECKOUT
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def skill_url() -> str:
|
|
102
|
+
"""The Chat skill attached to the latest release (installer/build.py makes it)."""
|
|
103
|
+
from keepfold import cli
|
|
104
|
+
return f"{cli.RELEASES}/latest/download/keepfold-skill.zip"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _open_path(p: Path) -> None:
|
|
108
|
+
if sys.platform == "win32" and _open is webbrowser.open:
|
|
109
|
+
os.startfile(p) # noqa: S606 (a folder or file Keepfold chose, never the page's)
|
|
110
|
+
else:
|
|
111
|
+
_open(p.as_uri())
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _obsidian() -> bool: # tests replace this
|
|
115
|
+
"""An obsidian:// handler is registered: the Windows registry, Obsidian.app on macOS, or
|
|
116
|
+
xdg-mime's default handler elsewhere."""
|
|
117
|
+
if sys.platform == "darwin":
|
|
118
|
+
try:
|
|
119
|
+
return any((d / "Applications" / "Obsidian.app").exists()
|
|
120
|
+
for d in (Path("/"), Path.home()))
|
|
121
|
+
except (OSError, RuntimeError): # no home, or a folder it may not read
|
|
122
|
+
return False
|
|
123
|
+
if sys.platform != "win32":
|
|
124
|
+
ok, out = targets._run(["xdg-mime", "query", "default", "x-scheme-handler/obsidian"],
|
|
125
|
+
timeout=5)
|
|
126
|
+
return ok and bool(out)
|
|
127
|
+
import winreg
|
|
128
|
+
for hive, key in ((winreg.HKEY_CURRENT_USER, r"Software\Classes\obsidian"),
|
|
129
|
+
(winreg.HKEY_CLASSES_ROOT, "obsidian")):
|
|
130
|
+
try:
|
|
131
|
+
winreg.CloseKey(winreg.OpenKey(hive, key))
|
|
132
|
+
return True
|
|
133
|
+
except OSError:
|
|
134
|
+
pass
|
|
135
|
+
return False
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _open_note(p: Path) -> dict:
|
|
139
|
+
"""A vault page or folder in Obsidian; without Obsidian, with this computer's default app
|
|
140
|
+
(Explorer for a folder)."""
|
|
141
|
+
if _obsidian():
|
|
142
|
+
_open("obsidian://open?path=" + quote(str(p), safe=""))
|
|
143
|
+
return {"ok": True, "obsidian": True}
|
|
144
|
+
_open_path(p)
|
|
145
|
+
return {"ok": True, "obsidian": False}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ---- jobs -------------------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
KEEPALIVE_S = 3 # seconds between {"t": "wait"} lines while a chat answer is quiet
|
|
152
|
+
|
|
153
|
+
class Busy(Exception):
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class NotFound(Exception): # a 404: the item does not exist, or may not be shown now
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class Job:
|
|
162
|
+
def __init__(self, name: str, section: str, cancellable: bool):
|
|
163
|
+
self.name, self.section, self.cancellable = name, section, cancellable
|
|
164
|
+
self.lines: list[str] = []
|
|
165
|
+
self.result = self.error = None
|
|
166
|
+
# monotonic: durations only, so a clock change mid-import never shows negative seconds
|
|
167
|
+
self.running, self.started, self.ended = True, time.monotonic(), None
|
|
168
|
+
self.cancelled = threading.Event()
|
|
169
|
+
self.proc = None
|
|
170
|
+
self.steps: dict | None = None # a stepped job's place (`progress`)
|
|
171
|
+
|
|
172
|
+
def progress(self, step: int, steps: int, done: int, total: int, label: str) -> None:
|
|
173
|
+
"""Where a stepped job is: step `step` of `steps`, named `label`, `done` of `total` in
|
|
174
|
+
it. The overall share never goes back."""
|
|
175
|
+
frac = min(max(done / total, 0.0), 1.0) if total else 0.0
|
|
176
|
+
overall = ((step - 1) + frac) / steps if steps else 0.0
|
|
177
|
+
if self.steps is not None:
|
|
178
|
+
overall = max(overall, self.steps["overall"])
|
|
179
|
+
self.steps = {"step": step, "steps": steps, "label": label, "done": done,
|
|
180
|
+
"total": total, "pct": round(frac * 100), "overall": overall,
|
|
181
|
+
"at": time.monotonic()}
|
|
182
|
+
|
|
183
|
+
def say(self, line) -> None:
|
|
184
|
+
self.lines.append(str(line)[:400])
|
|
185
|
+
del self.lines[:-300]
|
|
186
|
+
|
|
187
|
+
def cancel(self) -> None:
|
|
188
|
+
self.cancelled.set()
|
|
189
|
+
if self.proc is not None:
|
|
190
|
+
try:
|
|
191
|
+
self.proc.terminate()
|
|
192
|
+
except OSError:
|
|
193
|
+
pass
|
|
194
|
+
|
|
195
|
+
def view(self) -> dict:
|
|
196
|
+
out = {"name": self.name, "section": self.section, "running": self.running,
|
|
197
|
+
"cancellable": self.cancellable, "line": self.lines[-1] if self.lines else "",
|
|
198
|
+
"seconds": round((self.ended or time.monotonic()) - self.started, 1),
|
|
199
|
+
"result": self.result, "error": self.error}
|
|
200
|
+
if (s := self.steps) is not None:
|
|
201
|
+
took, overall = s["at"] - self.started, s["overall"]
|
|
202
|
+
# time left from the pace so far, once there is a pace to go by
|
|
203
|
+
eta = took * (1 - overall) / overall if overall >= 0.02 and took >= 2 else None
|
|
204
|
+
out["progress"] = {**{k: s[k] for k in ("step", "steps", "label", "done", "total",
|
|
205
|
+
"pct")},
|
|
206
|
+
"overall": round(overall * 100),
|
|
207
|
+
"eta_s": None if eta is None else round(eta)}
|
|
208
|
+
return out
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class Jobs:
|
|
212
|
+
def __init__(self):
|
|
213
|
+
self.lock = threading.Lock()
|
|
214
|
+
self.cur: Job | None = None
|
|
215
|
+
self.seq = 0
|
|
216
|
+
self.on_end = None # called with each job once it ends (the desktop app's notifier)
|
|
217
|
+
|
|
218
|
+
def start(self, name: str, section: str, fn, *, cancellable: bool = False,
|
|
219
|
+
quiet_errors: bool = False) -> dict:
|
|
220
|
+
"""Run `fn(job)` on a thread; Busy while another job runs. `quiet_errors` reports an
|
|
221
|
+
unexpected error by type only (browse jobs: a message could quote a page)."""
|
|
222
|
+
with self.lock:
|
|
223
|
+
if self.cur is not None and self.cur.running:
|
|
224
|
+
raise Busy(f"Wait: {self.cur.name} is still running.")
|
|
225
|
+
job = self.cur = Job(name, section, cancellable)
|
|
226
|
+
self.seq += 1
|
|
227
|
+
|
|
228
|
+
def body():
|
|
229
|
+
try:
|
|
230
|
+
job.result = fn(job)
|
|
231
|
+
except Exception as e: # noqa: BLE001 (reported on the page, never a traceback)
|
|
232
|
+
from keepfold.vault import VaultError # its messages are written for users
|
|
233
|
+
job.error = (type(e).__name__ if quiet_errors
|
|
234
|
+
and not isinstance(e, ValueError | VaultError)
|
|
235
|
+
else str(e)[:500] or type(e).__name__)
|
|
236
|
+
if not quiet_errors and not isinstance(e, ValueError | VaultError): # refusals
|
|
237
|
+
traceback.print_exc(limit=3)
|
|
238
|
+
finally:
|
|
239
|
+
job.running, job.ended = False, time.monotonic()
|
|
240
|
+
status.forget() # a job may have changed what Status shows
|
|
241
|
+
if self.on_end is not None:
|
|
242
|
+
try:
|
|
243
|
+
self.on_end(job)
|
|
244
|
+
except Exception: # noqa: BLE001 (a notification never fails the job)
|
|
245
|
+
traceback.print_exc(limit=3)
|
|
246
|
+
|
|
247
|
+
threading.Thread(target=body, daemon=True, name=f"keepfold-app-{name}").start()
|
|
248
|
+
return {"job": name, "seq": self.seq}
|
|
249
|
+
|
|
250
|
+
def view(self) -> dict:
|
|
251
|
+
return {"job": self.cur.view() if self.cur else None, "seq": self.seq}
|
|
252
|
+
|
|
253
|
+
def running(self) -> bool:
|
|
254
|
+
return self.cur is not None and self.cur.running
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# ---- the app ---------------------------------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _connect_skipped() -> bool:
|
|
261
|
+
app = status.config().get("app")
|
|
262
|
+
return isinstance(app, dict) and app.get("connect_skipped") is True
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _bool(body: dict, key: str) -> bool:
|
|
266
|
+
v = body.get(key)
|
|
267
|
+
if not isinstance(v, bool):
|
|
268
|
+
raise ValueError(f"{key} must be true or false")
|
|
269
|
+
return v
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _disk(body: dict, where: Path, need: int) -> dict | None:
|
|
273
|
+
"""{"disk": message} when a download of `need` bytes would leave less than 1 GB free in
|
|
274
|
+
`where` and the owner has not chosen to continue anyway (`override`), else None."""
|
|
275
|
+
ok, msg = wizard.free_space_ok(where, need)
|
|
276
|
+
return None if ok or body.get("override") is True else {"disk": msg}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _domains(v, key: str) -> list[str]:
|
|
280
|
+
if isinstance(v, str):
|
|
281
|
+
v = v.replace(",", "\n").split()
|
|
282
|
+
if not isinstance(v, list) or len(v) > 1000:
|
|
283
|
+
raise ValueError(f"{key} must be a list of domains")
|
|
284
|
+
out = []
|
|
285
|
+
for d in v:
|
|
286
|
+
d = str(d).strip().lower().lstrip(".")
|
|
287
|
+
if d and not (len(d) <= 253 and all(c.isalnum() or c in ".-" for c in d)):
|
|
288
|
+
raise ValueError(f"{d!r} is not a domain such as example.com")
|
|
289
|
+
if d:
|
|
290
|
+
out.append(d)
|
|
291
|
+
return sorted(set(out))
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
class App:
|
|
295
|
+
def __init__(self, root: Path | None):
|
|
296
|
+
self.root = Path(root).resolve() if root else None
|
|
297
|
+
self.token = secrets.token_urlsafe(32)
|
|
298
|
+
self.port = 0
|
|
299
|
+
self.jobs = Jobs()
|
|
300
|
+
self.scanned: dict = {} # source key -> the last scan's counts
|
|
301
|
+
self.uploads: dict[str, Path] = {} # upload id -> its file under ~/.keepfold/tmp
|
|
302
|
+
self.chatting = threading.Lock() # one chat answer at a time, beside any job
|
|
303
|
+
self.piggy = threading.Lock() # C8: one fact-harvest piggyback after a Chat turn at once
|
|
304
|
+
self.echo = print # `start` sets its own: the background passes' log lines
|
|
305
|
+
from keepfold import askfile
|
|
306
|
+
self.files = askfile.Store() # C1: files attached in Chat, in memory only
|
|
307
|
+
self.last = time.monotonic()
|
|
308
|
+
self.stop = threading.Event()
|
|
309
|
+
self.desktop = None # desktop.Desktop (window and tray) in the desktop app, else None
|
|
310
|
+
self.private_until = 0.0 # the Private switch: ?private=1 applies until this monotonic
|
|
311
|
+
self.update_ready: dict | None = None # a newer release, prepared by the quiet check
|
|
312
|
+
self.homes = (threading.Lock(), {}) # vault root -> its HomeCache
|
|
313
|
+
# X-ray's dry runs and compares: one read-only Index, one request at a time (_dry_index)
|
|
314
|
+
self.dry, self.dry_index, self.dry_used = threading.Lock(), None, 0.0
|
|
315
|
+
self.warming: threading.Thread | None = None # `warm_status`'s thread
|
|
316
|
+
self.core = None # (vault root, mcp_server.Keepfold) for the Review's clicks
|
|
317
|
+
self.reviewing = threading.Lock() # one Review click at a time
|
|
318
|
+
self.get = {"/api/status": self.status, "/api/status/report": self.status_report,
|
|
319
|
+
"/api/connect": self.connect,
|
|
320
|
+
"/api/app/autostart": self.autostart, "/api/app/notify": self.notify,
|
|
321
|
+
"/api/app/hotkey": self.hotkey, "/api/app/welcome": self.welcome,
|
|
322
|
+
"/api/home": self.home, "/api/home/version": self.home_version,
|
|
323
|
+
"/api/home/delta": self.home_delta, "/api/home/site": self.home_site,
|
|
324
|
+
"/api/home/check": self.cold_check, "/api/import/pickup": self.pickup,
|
|
325
|
+
"/api/vault/snapshot": None,
|
|
326
|
+
"/api/llm": self.llm, "/api/browse": self.browse, "/api/vault": self.vault,
|
|
327
|
+
"/api/setup": self.setup, "/api/chat": self.chat_state,
|
|
328
|
+
"/api/chat/list": self.chat_list, "/api/chat/get": self.chat_get,
|
|
329
|
+
"/api/chat/passage": self.chat_passage, "/api/chat/pages": self.chat_pages,
|
|
330
|
+
"/api/chat/settings": self.chat_settings_get,
|
|
331
|
+
"/api/update": self.update_state, "/api/job": self.jobs.view,
|
|
332
|
+
"/api/review": self.review, "/api/xray": self.xray,
|
|
333
|
+
"/api/tonight": self.tonight,
|
|
334
|
+
"/api/browse/private-chats": self.private_chats}
|
|
335
|
+
self.post = {
|
|
336
|
+
"/api/connect/plan": self.connect_plan, "/api/connect/apply": self.connect_apply,
|
|
337
|
+
"/api/connect/path": self.connect_path,
|
|
338
|
+
"/api/connect/copied": self.pack_copied,
|
|
339
|
+
"/api/profiles": self.profiles_set,
|
|
340
|
+
"/api/llm/settings": self.llm_settings, "/api/llm/load": self.llm_load,
|
|
341
|
+
"/api/llm/test": self.llm_test, "/api/llm/pull": self.llm_pull,
|
|
342
|
+
"/api/llm/size": self.llm_size,
|
|
343
|
+
"/api/browse/settings": self.browse_settings, "/api/browse/cloud": self.cloud,
|
|
344
|
+
"/api/browse/auto": self.auto_settings,
|
|
345
|
+
"/api/chat": None, # do_POST streams it
|
|
346
|
+
"/api/chat/delete": self.chat_delete, "/api/chat/settings": self.chat_settings,
|
|
347
|
+
"/api/chat/eval": self.chat_eval,
|
|
348
|
+
"/api/chat/attach": self.chat_attach, "/api/chat/file/remove": self.chat_file_remove,
|
|
349
|
+
"/api/chat/file/save": self.chat_file_save,
|
|
350
|
+
"/api/browse/login": self.login,
|
|
351
|
+
"/api/browse/process": self.process, "/api/browse/selftest": self.selftest,
|
|
352
|
+
"/api/browse/scan": self.scan, "/api/browse/import": self.history_import,
|
|
353
|
+
"/api/vault/export": self.export, "/api/vault/backup": self.backup,
|
|
354
|
+
PICTURE: self.brain_picture,
|
|
355
|
+
"/api/home/unlock": self.unlock, "/api/home/lock": self.lock,
|
|
356
|
+
"/api/home/check/answer": self.cold_answer, "/api/home/date": self.home_date,
|
|
357
|
+
"/api/home/layout": self.home_layout, "/api/home/fact": self.home_fact,
|
|
358
|
+
"/api/vault/doctor": self.doctor, "/api/vault/git": self.git_settings,
|
|
359
|
+
"/api/open": self.open,
|
|
360
|
+
"/api/setup/vault": self.setup_vault, "/api/setup/embed": self.setup_embed,
|
|
361
|
+
"/api/setup/voice": self.setup_voice,
|
|
362
|
+
"/api/setup/index": self.setup_index, "/api/setup/install": self.setup_install,
|
|
363
|
+
"/api/setup/git": self.setup_git,
|
|
364
|
+
"/api/setup/pull": self.setup_pull, "/api/setup/test": self.setup_test,
|
|
365
|
+
"/api/setup/start": self.setup_start, "/api/setup/model": self.setup_model,
|
|
366
|
+
UPLOAD: None, # do_POST streams it
|
|
367
|
+
"/api/import/preview": self.import_preview, "/api/import/run": self.import_run,
|
|
368
|
+
"/api/import/pickup/add": self.pickup_add,
|
|
369
|
+
"/api/import/pickup/dismiss": self.pickup_dismiss,
|
|
370
|
+
"/api/import/pickup/later": self.pickup_later,
|
|
371
|
+
"/api/import/watch/add": self.watch_add,
|
|
372
|
+
"/api/import/watch/remove": self.watch_remove,
|
|
373
|
+
"/api/job/cancel": self.cancel, "/api/quit": self.quit,
|
|
374
|
+
"/api/setup/skip": self.setup_skip, "/api/update/check": self.update_check,
|
|
375
|
+
"/api/update/apply": self.update_apply, "/api/whats_new/seen": self.news_seen,
|
|
376
|
+
"/api/window/show": self.window_show, "/api/app/autostart": self.autostart_set,
|
|
377
|
+
"/api/app/notify": self.notify_set, "/api/app/chat-import": self.chat_import_set,
|
|
378
|
+
"/api/app/welcome": self.welcome_set, "/api/app/hotkey": self.hotkey_set,
|
|
379
|
+
"/api/app/update-check": self.update_check_set,
|
|
380
|
+
"/api/capture/hide": self.capture_hide,
|
|
381
|
+
"/api/review/approve": self.review_approve, "/api/review/dismiss": self.review_dismiss,
|
|
382
|
+
"/api/review/still": self.review_still, "/api/review/retire": self.review_retire,
|
|
383
|
+
"/api/review/conflict": self.review_conflict,
|
|
384
|
+
"/api/review/rule/approve": self.review_rule_approve,
|
|
385
|
+
"/api/review/rule/approve-all": self.review_rule_approve_all,
|
|
386
|
+
"/api/review/resume": self.review_resume,
|
|
387
|
+
"/api/review/rule/dismiss": self.review_rule_dismiss,
|
|
388
|
+
"/api/review/decision/approve": self.review_decision_approve,
|
|
389
|
+
"/api/review/decision/dismiss": self.review_decision_dismiss,
|
|
390
|
+
"/api/review/forget/dismiss": self.review_forget_dismiss,
|
|
391
|
+
"/api/review/import/dismiss": self.review_import_dismiss,
|
|
392
|
+
"/api/review/unsafe/keep": self.review_unsafe_keep,
|
|
393
|
+
"/api/review/outside/keep": self.review_outside_keep,
|
|
394
|
+
"/api/review/outside/remove": self.review_outside_remove,
|
|
395
|
+
"/api/review/crowded/keep": self.review_crowded_keep,
|
|
396
|
+
"/api/review/playbook/keep": self.review_playbook_keep,
|
|
397
|
+
"/api/review/promote/pin": self.review_promote_pin,
|
|
398
|
+
"/api/review/promote/later": self.review_promote_later,
|
|
399
|
+
"/api/xray/pin": self.xray_pin, "/api/xray/mute": self.xray_mute,
|
|
400
|
+
"/api/xray/dryrun": self.xray_dryrun, "/api/xray/trace": self.xray_trace,
|
|
401
|
+
"/api/xray/compare": self.xray_compare, "/api/xray/ack": self.xray_ack,
|
|
402
|
+
"/api/tonight/undo": self.tonight_undo, "/api/capture": self.capture}
|
|
403
|
+
|
|
404
|
+
def touch(self) -> None:
|
|
405
|
+
self.last = time.monotonic()
|
|
406
|
+
|
|
407
|
+
def need_root(self) -> Path:
|
|
408
|
+
if self.root is None or not (self.root / ".keepfold").is_dir():
|
|
409
|
+
raise ValueError("Set up a vault first (Setup, step 1).")
|
|
410
|
+
return self.root
|
|
411
|
+
|
|
412
|
+
def entry(self) -> dict | None:
|
|
413
|
+
if self.root is None or not (self.root / ".keepfold").is_dir():
|
|
414
|
+
return None
|
|
415
|
+
from keepfold import clients
|
|
416
|
+
return clients.server_entry(clients.mcp_command(), self.root)
|
|
417
|
+
|
|
418
|
+
# ---- GET (never changes anything) ----
|
|
419
|
+
def status(self, q: dict | None = None) -> dict:
|
|
420
|
+
"""The Status board; its slow probes are `status.kept` (`?fresh=1`: asked again)."""
|
|
421
|
+
from keepfold import chat_import, egress, taint
|
|
422
|
+
if self.warming not in (None, threading.current_thread()):
|
|
423
|
+
self.warming.join() # its probes are already under way: wait for them, not ask twice
|
|
424
|
+
if (q or {}).get("fresh") == ["1"]:
|
|
425
|
+
status.forget()
|
|
426
|
+
v = status.vault(self.root)
|
|
427
|
+
entry = self.entry() if v["ok"] else None
|
|
428
|
+
ready = v["ok"] and (_connect_skipped() or any(
|
|
429
|
+
t["connected"] for t in status.kept(("targets", json.dumps(entry, sort_keys=True)),
|
|
430
|
+
lambda: targets.describe(entry))))
|
|
431
|
+
bad = taint.config_error() # privacy choices fail closed until it is fixed
|
|
432
|
+
return {"rows": ([{"id": "config", "label": "Settings file", "state": "warn",
|
|
433
|
+
"value": bad, "detail": taint.CONFIG_FIX}] if bad else [])
|
|
434
|
+
+ status.rows(self.root) + (self._paused_rows() if v["ok"] else []),
|
|
435
|
+
"first_run": not v["ok"], "vault": v["path"], "update": self.update_state(),
|
|
436
|
+
"whats_new": news.card(), "chat_import": chat_import.enabled(),
|
|
437
|
+
"issue_url": f"https://github.com/{update.REPO}/issues/new?template=bug_report.yml",
|
|
438
|
+
"connects": egress.summary(), # keepfold.egress: where Keepfold connects
|
|
439
|
+
"land": "status" if ready else "setup"} # Setup until its key steps are done
|
|
440
|
+
|
|
441
|
+
def status_report(self) -> dict:
|
|
442
|
+
"""Copy details: the same block as `keepfold doctor --report` (no paths, notes, values)."""
|
|
443
|
+
return {"text": status.report(self.root)}
|
|
444
|
+
|
|
445
|
+
def _paused_rows(self) -> list[dict]:
|
|
446
|
+
"""RR-10: one Status row per paused Review producer, with its Resume; "imports" also
|
|
447
|
+
when the owner undid most of the lines fact_harvest saved (fact_harvest.ledger)."""
|
|
448
|
+
from keepfold import fact_harvest, review
|
|
449
|
+
from keepfold.events import EventLog
|
|
450
|
+
try:
|
|
451
|
+
v = self._vault()
|
|
452
|
+
events = list(EventLog(v).iter_events())
|
|
453
|
+
led = review.ledger(events)
|
|
454
|
+
undone = fact_harvest.ledger(v, events)
|
|
455
|
+
except Exception: # noqa: BLE001 (a Status row must never cost the board)
|
|
456
|
+
return []
|
|
457
|
+
rows = [{"id": f"review-{p}", "label": "Review", "state": "warn",
|
|
458
|
+
"value": f"{review.PRODUCERS[p]} paused",
|
|
459
|
+
"detail": f"You dismissed {x['reject']} of the last {x['accept'] + x['reject']} "
|
|
460
|
+
"of these cards, so Review stopped offering them.", "resume": p}
|
|
461
|
+
for p, x in led.items() if x["paused"]]
|
|
462
|
+
if undone["paused"] and not led[fact_harvest.PRODUCER]["paused"]:
|
|
463
|
+
n = undone["accept"] + undone["reject"]
|
|
464
|
+
rows.append({"id": f"review-{fact_harvest.PRODUCER}", "label": "Review",
|
|
465
|
+
"state": "warn",
|
|
466
|
+
"value": f"{review.PRODUCERS[fact_harvest.PRODUCER]} paused",
|
|
467
|
+
"detail": f"You undid {undone['reject']} of the last {n} lines Keepfold "
|
|
468
|
+
"saved from your chats, so it stopped saving them.",
|
|
469
|
+
"resume": fact_harvest.PRODUCER})
|
|
470
|
+
return rows
|
|
471
|
+
|
|
472
|
+
def warm_status(self) -> None:
|
|
473
|
+
"""Status and Setup read once in the background at start: a first read waits ~3-4 s
|
|
474
|
+
on the LLM probes (LM Studio's `lms`, refused loopback connects) and first imports;
|
|
475
|
+
Status, Setup and Local model then answer from `status.kept` (refreshed after KEEP_S)."""
|
|
476
|
+
def warm():
|
|
477
|
+
self.status()
|
|
478
|
+
self.setup() # Settings opens on Setup until it is done: its probes too
|
|
479
|
+
self.warming = threading.Thread(target=warm, daemon=True, name="keepfold-app-warm-status")
|
|
480
|
+
self.warming.start()
|
|
481
|
+
|
|
482
|
+
def connect(self) -> dict:
|
|
483
|
+
"""Connect: the AI apps, plus (with a vault) the context packs for web chats and the
|
|
484
|
+
per-agent profiles (plan v9 item 8)."""
|
|
485
|
+
from keepfold import access, packs, profiles
|
|
486
|
+
from keepfold.events import EventLog
|
|
487
|
+
extra = {}
|
|
488
|
+
if self.entry() is not None:
|
|
489
|
+
v = self._vault()
|
|
490
|
+
events = list(EventLog(v).iter_events()) # read once for every pack
|
|
491
|
+
last = packs.copied(events)
|
|
492
|
+
|
|
493
|
+
def size(n, s, text): # R32a: changed only when copied before and now different
|
|
494
|
+
h = packs.digest(text)
|
|
495
|
+
return {"chars": s, "text": text, "hash": h,
|
|
496
|
+
"changed": (n, s) in last and last[(n, s)] != h}
|
|
497
|
+
extra = {"packs": [{"id": n, "sizes": [size(n, s, t) for s, t in
|
|
498
|
+
packs.sized(v, n, events=events).items()]}
|
|
499
|
+
for n in packs.PACKS],
|
|
500
|
+
"profiles": profiles.load(v), "scopes": list(access.SCOPES)}
|
|
501
|
+
return {"targets": targets.describe(self.entry()), "vault": self.entry() is not None,
|
|
502
|
+
"instructions": packs.USE_TEXT, # Copy instructions on rows with a `paste`
|
|
503
|
+
"skill_zip": str(_checkout() / "dist" / "keepfold-skill.zip"),
|
|
504
|
+
"skill_zip_found": (_checkout() / "dist" / "keepfold-skill.zip").is_file(),
|
|
505
|
+
"skill_url": skill_url(), **extra}
|
|
506
|
+
|
|
507
|
+
def pack_copied(self, body: dict) -> dict:
|
|
508
|
+
"""R32a: the owner pressed Copy on a context pack; one log event, so Connect can say
|
|
509
|
+
when the pack changed since. Only pack, chars and hash come from the app."""
|
|
510
|
+
from keepfold import packs
|
|
511
|
+
from keepfold.events import EventLog
|
|
512
|
+
if not isinstance(body, dict) or set(body) != {"pack", "chars", "hash"}:
|
|
513
|
+
raise ValueError("send pack, chars and hash only.")
|
|
514
|
+
name, chars, h = body["pack"], body["chars"], body["hash"]
|
|
515
|
+
if not isinstance(name, str) or name not in packs.PACKS:
|
|
516
|
+
raise ValueError(f"pack must be one of {', '.join(packs.PACKS)}.")
|
|
517
|
+
if type(chars) is not int or chars not in packs.SIZES:
|
|
518
|
+
raise ValueError("chars must be 1500 or 5000.")
|
|
519
|
+
if not isinstance(h, str) or not re.fullmatch(r"[0-9a-f]{16}", h):
|
|
520
|
+
raise ValueError("hash must be 16 hex characters.")
|
|
521
|
+
EventLog(self._vault()).append(session="cli", kind="log", source="self", fields={
|
|
522
|
+
"payload": {"kind": "pack_copied", "pack": name, "chars": chars, "hash": h}})
|
|
523
|
+
return {"ok": True}
|
|
524
|
+
|
|
525
|
+
def profiles_set(self, body: dict) -> dict:
|
|
526
|
+
"""The owner's per-agent profiles, saved from the app only (never from MCP input)."""
|
|
527
|
+
from keepfold import profiles
|
|
528
|
+
return {"profiles": profiles.save(self._vault(), body)} # body: {profiles, unknown}
|
|
529
|
+
|
|
530
|
+
def llm(self) -> dict:
|
|
531
|
+
"""The Local model page: both runners' chat models (embedding models left out by the
|
|
532
|
+
chat's own name rule) and the model sized to this computer."""
|
|
533
|
+
from keepfold import localllm
|
|
534
|
+
if self.warming not in (None, threading.current_thread()):
|
|
535
|
+
self.warming.join() # the warm-up is asking the same probes: wait, not ask twice
|
|
536
|
+
d, hw = status.llm(quick=True), wizard.hardware() # kept like Status's (~3 s fresh)
|
|
537
|
+
|
|
538
|
+
def chats(names):
|
|
539
|
+
return [n for n in names if not localllm._NOT_CHAT.search(n)]
|
|
540
|
+
return {**d, "ollama": None if d["ollama"] is None else chats(d["ollama"]),
|
|
541
|
+
"ollama_state": wizard._ollama_state(d["ollama"]), # the words Setup uses
|
|
542
|
+
"models": [m for m in status.kept(("lms_models", None), status.lms_models)
|
|
543
|
+
if chats([m["key"]])],
|
|
544
|
+
"hardware": hw, "recommend": wizard.model(wizard.recommend(hw["gb"], hw["kind"]))}
|
|
545
|
+
|
|
546
|
+
def browse(self) -> dict:
|
|
547
|
+
b = status.browse(self.root if self.entry() else None)
|
|
548
|
+
return {**b, "history": status.history(self.root if self.entry() else None, self.scanned),
|
|
549
|
+
"cloud": status.cloud(self.root if self.entry() else None)}
|
|
550
|
+
|
|
551
|
+
def private_chats(self, query: dict) -> dict:
|
|
552
|
+
"""Imported chats made private for a sensitive category (chat_import.made_private),
|
|
553
|
+
newest first, PAGE_ROWS from `offset`: titles, apps, dates and categories only, never
|
|
554
|
+
chat text or browsing. The app's own page only: no MCP tool reads it. While the Private
|
|
555
|
+
switch is locked: counts by category only (`locked`), no row."""
|
|
556
|
+
from keepfold import chat_import
|
|
557
|
+
from keepfold.events import EventLog
|
|
558
|
+
try:
|
|
559
|
+
at = max(0, int((query.get("offset") or ["0"])[0]))
|
|
560
|
+
except ValueError:
|
|
561
|
+
at = 0
|
|
562
|
+
v = self._vault()
|
|
563
|
+
rows = chat_import.made_private(v, EventLog(v).iter_events())
|
|
564
|
+
cats: dict[str, int] = {}
|
|
565
|
+
for r in rows:
|
|
566
|
+
cats[r["category"]] = cats.get(r["category"], 0) + 1
|
|
567
|
+
if not self.private_unlocked: # titles only while the Private switch is open
|
|
568
|
+
return {"rows": [], "total": len(rows), "offset": 0, "locked": True,
|
|
569
|
+
"by_category": cats}
|
|
570
|
+
return {"rows": rows[at:at + PAGE_ROWS], "total": len(rows), "offset": at,
|
|
571
|
+
"locked": False, "by_category": cats}
|
|
572
|
+
|
|
573
|
+
def vault(self) -> dict:
|
|
574
|
+
from keepfold.session import git_choice
|
|
575
|
+
g = status.config().get("git")
|
|
576
|
+
# the saved private choice, shown (greyed out) even while git is off
|
|
577
|
+
private = isinstance(g, dict) and g.get("private_browsing") is True
|
|
578
|
+
return {**status.vault(self.root), "embed": status.embedding(),
|
|
579
|
+
"git": {"enabled": git_choice()[0], "private_browsing": private}}
|
|
580
|
+
|
|
581
|
+
def chat_state(self) -> dict:
|
|
582
|
+
"""What the Chat page needs to open: the missing pieces (search model, local model),
|
|
583
|
+
the model's name, the settings and the past chats."""
|
|
584
|
+
from keepfold import chat, localllm
|
|
585
|
+
if self.entry() is None:
|
|
586
|
+
return {"vault": False}
|
|
587
|
+
st = localllm.status() # read-only: a GET never starts LM Studio or loads a model
|
|
588
|
+
runner, why = st["runner"], st["error"]
|
|
589
|
+
missing = [k for k, gone in (("embed", not status.embedding()["downloaded"]),
|
|
590
|
+
("llm", runner is None)) if gone]
|
|
591
|
+
return {"vault": True, "missing": missing, "llm_error": why,
|
|
592
|
+
"model": runner.model if runner else None, "settings": chat.get_settings(),
|
|
593
|
+
"chats": chat.list(self._vault()), "files": self.files.list()}
|
|
594
|
+
|
|
595
|
+
def _vault(self):
|
|
596
|
+
from keepfold.vault import Vault
|
|
597
|
+
return Vault(self.need_root())
|
|
598
|
+
|
|
599
|
+
def chat_list(self) -> dict:
|
|
600
|
+
from keepfold import chat
|
|
601
|
+
return {"chats": chat.list(self._vault())}
|
|
602
|
+
|
|
603
|
+
def chat_get(self, query: dict) -> dict:
|
|
604
|
+
from keepfold import chat
|
|
605
|
+
cid = (query.get("id") or [None])[0]
|
|
606
|
+
if cid is None:
|
|
607
|
+
return {"id": None, "messages": [], "remembers": 0}
|
|
608
|
+
msgs = chat.load(self._vault(), cid) # load checks the id
|
|
609
|
+
return {"id": cid, "messages": msgs, # where the model's memory starts, for its line
|
|
610
|
+
"remembers": chat.remembers(msgs, chat.get_settings()["sources"])}
|
|
611
|
+
|
|
612
|
+
def chat_passage(self, query: dict) -> dict:
|
|
613
|
+
"""The passage an answer cited (?path=&at=&len=), under Chat's source switches of now
|
|
614
|
+
(`chat.passage`): a page under a switch that is off is refused, never shown."""
|
|
615
|
+
from keepfold import chat
|
|
616
|
+
q = {k: (query.get(k) or [""])[0] for k in ("path", "at", "len")}
|
|
617
|
+
if not q["path"]: # no page named: not found, as /api/home/site
|
|
618
|
+
raise NotFound
|
|
619
|
+
try:
|
|
620
|
+
return chat.passage(self._vault(), q["path"], q["at"] or 0, q["len"] or 0,
|
|
621
|
+
chat.get_settings()["sources"])
|
|
622
|
+
except PermissionError as e:
|
|
623
|
+
raise ValueError(str(e)) from None
|
|
624
|
+
|
|
625
|
+
def _home(self):
|
|
626
|
+
from keepfold.home import HomeCache
|
|
627
|
+
from keepfold.vault import Vault
|
|
628
|
+
root = self.need_root()
|
|
629
|
+
lock, homes = self.homes
|
|
630
|
+
with lock:
|
|
631
|
+
if root not in homes:
|
|
632
|
+
homes.clear() # one vault at a time
|
|
633
|
+
homes[root] = HomeCache(Vault(root))
|
|
634
|
+
return homes[root]
|
|
635
|
+
|
|
636
|
+
# ---- the Private switch: private items only after Windows Hello, for 10 minutes ----
|
|
637
|
+
@property
|
|
638
|
+
def private_unlocked(self) -> bool:
|
|
639
|
+
return time.monotonic() < self.private_until
|
|
640
|
+
|
|
641
|
+
def _private(self, query: dict) -> bool | None:
|
|
642
|
+
"""True: the page asks for private items and may have them. None: it asks while the
|
|
643
|
+
switch is locked (it expired, or the window was minimised), so it relocks."""
|
|
644
|
+
if (query.get("private") or [""])[0] != "1":
|
|
645
|
+
return False
|
|
646
|
+
return True if self.private_unlocked else None
|
|
647
|
+
|
|
648
|
+
def warm_home(self) -> None:
|
|
649
|
+
try:
|
|
650
|
+
self._home().get(False)
|
|
651
|
+
except Exception as e: # noqa: BLE001 (the page's own read reports a real problem)
|
|
652
|
+
print(f"keepfold app: the home warm-up failed ({type(e).__name__})", file=sys.stderr)
|
|
653
|
+
|
|
654
|
+
def home(self, query: dict) -> dict:
|
|
655
|
+
"""The live home (keepfold.home): the dashboard's data plus feed, next_up and exams.
|
|
656
|
+
Builds and keeps the brain layout (`.keepfold/brain-layout.json`, a view cache). A page
|
|
657
|
+
that must relock gets the public home with `relock`."""
|
|
658
|
+
private = self._private(query)
|
|
659
|
+
home = self._home().get(private is True)
|
|
660
|
+
home = {**home, **self._home_prefs(home)}
|
|
661
|
+
return home if private is not None else {**home, "relock": True}
|
|
662
|
+
|
|
663
|
+
# ---- UX-E: Home's pinned layout and its Get started board (config.yaml `app:`) ----
|
|
664
|
+
def _home_prefs(self, home: dict) -> dict:
|
|
665
|
+
"""`home_layout` and `first_run_hidden` from config.yaml; while Get started shows,
|
|
666
|
+
`connected`: an AI app is connected, as Setup's Connect step reads it."""
|
|
667
|
+
from keepfold import dashboard
|
|
668
|
+
from keepfold.app import desktop
|
|
669
|
+
a = desktop._app_cfg()
|
|
670
|
+
out = {"home_layout": dashboard.home_layout({"app": a}),
|
|
671
|
+
"first_run_hidden": a.get("first_run_hidden") is True}
|
|
672
|
+
if home.get("get_started") and not out["first_run_hidden"]:
|
|
673
|
+
entry = self.entry()
|
|
674
|
+
out["connected"] = any(t["connected"] for t in status.kept(
|
|
675
|
+
("targets", json.dumps(entry, sort_keys=True)), lambda: targets.describe(entry)))
|
|
676
|
+
return out
|
|
677
|
+
|
|
678
|
+
def home_layout(self, body: dict) -> dict:
|
|
679
|
+
"""Pin layout (`order`: Home's groups in order, null to unpin) and Get started's Hide
|
|
680
|
+
(`first_run_hidden`: true), kept in config.yaml's `app:` as app.notify is."""
|
|
681
|
+
from keepfold import dashboard
|
|
682
|
+
from keepfold.app import desktop
|
|
683
|
+
if not body or set(body) - {"order", "first_run_hidden"}:
|
|
684
|
+
raise ValueError("send order or first_run_hidden")
|
|
685
|
+
order = body.get("order")
|
|
686
|
+
if "order" in body and order is not None and dashboard.home_layout(
|
|
687
|
+
{"app": {"home_layout": order}}) is None:
|
|
688
|
+
raise ValueError(f"order must list {', '.join(dashboard.HOME_GROUPS)}, each once")
|
|
689
|
+
if "first_run_hidden" in body and body["first_run_hidden"] is not True:
|
|
690
|
+
raise ValueError("first_run_hidden can only be true")
|
|
691
|
+
|
|
692
|
+
def merge(a: dict) -> dict:
|
|
693
|
+
a = {**a, **({"first_run_hidden": True} if "first_run_hidden" in body else {})}
|
|
694
|
+
if "order" in body:
|
|
695
|
+
a = {k: v for k, v in a.items() if k != "home_layout"}
|
|
696
|
+
if order is not None:
|
|
697
|
+
a["home_layout"] = list(order)
|
|
698
|
+
return a
|
|
699
|
+
desktop._merge_app(merge)
|
|
700
|
+
return self._home_prefs({})
|
|
701
|
+
|
|
702
|
+
def home_fact(self, body: dict) -> dict:
|
|
703
|
+
"""Get started's one line about you, saved as a `//fact:` typed in a chat is (tags:
|
|
704
|
+
me/profile under Background, the owner's own words)."""
|
|
705
|
+
from keepfold import tags
|
|
706
|
+
from keepfold.vault import Vault
|
|
707
|
+
text = body.get("text")
|
|
708
|
+
text = " ".join(text.split()) if isinstance(text, str) else ""
|
|
709
|
+
if not text:
|
|
710
|
+
raise ValueError("Write one line about you first.")
|
|
711
|
+
if len(text) > tags.MAX_CHARS:
|
|
712
|
+
raise ValueError(f"Keep it to {tags.MAX_CHARS} characters.")
|
|
713
|
+
root, refused = self.need_root(), []
|
|
714
|
+
with self.reviewing:
|
|
715
|
+
saved = tags.apply_in(Vault(root), [("fact", text, self._today())], refused=refused)
|
|
716
|
+
if refused:
|
|
717
|
+
raise ValueError(refused[0])
|
|
718
|
+
return {"saved": saved}
|
|
719
|
+
|
|
720
|
+
def home_version(self) -> dict:
|
|
721
|
+
"""The home's version, the Private switch and a prepared update (the page's 3 s poll)."""
|
|
722
|
+
r = self.update_ready
|
|
723
|
+
return {"v": self._home().version(), "private": self.private_unlocked,
|
|
724
|
+
"update": r and {"version": r["version"], "mode": r["mode"]}}
|
|
725
|
+
|
|
726
|
+
def home_delta(self, query: dict) -> dict:
|
|
727
|
+
"""Changes since `since`; a page that must relock gets the public home whole, so no
|
|
728
|
+
private item stays on it."""
|
|
729
|
+
private = self._private(query)
|
|
730
|
+
if private is None:
|
|
731
|
+
return {**self._home().get(False), "full": True, "relock": True}
|
|
732
|
+
return self._home().delta((query.get("since") or [None])[0], private)
|
|
733
|
+
|
|
734
|
+
def home_site(self, query: dict) -> dict:
|
|
735
|
+
"""One website of the brain's stem, read from the browsing store (never the vault's
|
|
736
|
+
Markdown). A private site while the switch is locked is a 404, as if it did not exist."""
|
|
737
|
+
got = self._home().site((query.get("site") or [""])[0], self._private(query) is True)
|
|
738
|
+
if got is None:
|
|
739
|
+
raise NotFound
|
|
740
|
+
return got
|
|
741
|
+
|
|
742
|
+
# ---- the 90-second check on Home: self-graded, recorded through keepfold_grade ----
|
|
743
|
+
COLD_ANSWERS = {"forgot": ("wrong", None, "Forgot"), "shaky": ("correct", 2, "Shaky"),
|
|
744
|
+
"knew": ("correct", 4, "Knew it")}
|
|
745
|
+
|
|
746
|
+
def cold_check(self) -> dict:
|
|
747
|
+
"""Up to 3 cloud-visible concepts due today or tomorrow, most overdue first, with each
|
|
748
|
+
page's one-line summary (home.cold_check). Never a private concept."""
|
|
749
|
+
from datetime import UTC, datetime
|
|
750
|
+
|
|
751
|
+
from keepfold import home
|
|
752
|
+
return {"items": home.cold_check(self._vault(), datetime.now(UTC))}
|
|
753
|
+
|
|
754
|
+
def cold_answer(self, body: dict) -> dict:
|
|
755
|
+
"""One answer: a closed-book recall item graded by the user (wrong; right at confidence
|
|
756
|
+
2; right at confidence 4), written by keepfold_grade's own code path as the Review's clicks
|
|
757
|
+
are (`_click`: an `app_clicks` Keepfold, a session closed at once so it is committed and
|
|
758
|
+
`keepfold undo` takes it back), with the app as client and model "self". A concept the
|
|
759
|
+
check would not offer now (unknown, private, not due) is a 404."""
|
|
760
|
+
from datetime import UTC, datetime
|
|
761
|
+
|
|
762
|
+
from keepfold import home, planner
|
|
763
|
+
from keepfold.catalog import Catalog
|
|
764
|
+
from keepfold.events import local_day
|
|
765
|
+
from keepfold.mcp_server import Keepfold
|
|
766
|
+
from keepfold.vault import Vault
|
|
767
|
+
cid, answer = body.get("id"), body.get("answer")
|
|
768
|
+
if answer not in self.COLD_ANSWERS:
|
|
769
|
+
raise ValueError("answer must be forgot, shaky or knew.")
|
|
770
|
+
v = self._vault()
|
|
771
|
+
day = local_day(datetime.now(UTC))
|
|
772
|
+
catalog = Catalog.load(v)
|
|
773
|
+
if not isinstance(cid, str) or cid not in home.cold_due(
|
|
774
|
+
planner.current_states(v, day, catalog)[0], catalog,
|
|
775
|
+
planner.hidden(v, catalog), day):
|
|
776
|
+
raise NotFound
|
|
777
|
+
verdict, confidence, said = self.COLD_ANSWERS[answer]
|
|
778
|
+
kwargs = {"concept": cid, "question": "90-second check: recall what you know, then "
|
|
779
|
+
"reveal.", "item_type": "recall", "learner_answer": said, "verdict": verdict,
|
|
780
|
+
**({"confidence": confidence} if confidence else {})}
|
|
781
|
+
root = self.need_root()
|
|
782
|
+
with self.reviewing:
|
|
783
|
+
if self.core is None or self.core[0] != root:
|
|
784
|
+
core = Keepfold(Vault(root))
|
|
785
|
+
core.app_clicks = True # every write here is the user's own click
|
|
786
|
+
self.core = (root, core)
|
|
787
|
+
core = self.core[1]
|
|
788
|
+
client = core.sessions.client
|
|
789
|
+
core.sessions.client = "keepfold-app" # server-set, as grader.client always is
|
|
790
|
+
try:
|
|
791
|
+
core.session = core.sessions.start("ambient", None, "self")
|
|
792
|
+
core._reset()
|
|
793
|
+
out = core._call("keepfold_grade", core.keepfold_grade, kwargs)
|
|
794
|
+
finally:
|
|
795
|
+
core.sessions.client = client
|
|
796
|
+
if core.sessions.current is not None:
|
|
797
|
+
core.sessions.close(summary="90-second check in the Keepfold app")
|
|
798
|
+
if "error" in out:
|
|
799
|
+
raise ValueError(out.get("message") or out["error"])
|
|
800
|
+
return {"recorded": True}
|
|
801
|
+
|
|
802
|
+
DATE_KINDS = ("exam", "deadline")
|
|
803
|
+
|
|
804
|
+
def home_date(self, body: dict) -> dict:
|
|
805
|
+
"""Home's Add a date (R31): an exam or deadline as an assessment page {title, date,
|
|
806
|
+
kind, outcome: pending}, written by keepfold_add's own code path as an AI app's add is (an
|
|
807
|
+
`app_clicks` Keepfold, the app as client, a session closed at once so `keepfold undo` takes
|
|
808
|
+
it back), so the planner, Next up, Chat and the snapshot see it. Refused: a name empty
|
|
809
|
+
or over 120 characters, a date that is not real or before today, another kind, and the
|
|
810
|
+
same name on the same day (an assessment page already has it)."""
|
|
811
|
+
from datetime import date
|
|
812
|
+
|
|
813
|
+
from keepfold.mcp_server import Keepfold
|
|
814
|
+
from keepfold.vault import Vault
|
|
815
|
+
what, when, kind = body.get("what"), body.get("when"), body.get("kind", "exam")
|
|
816
|
+
what = what.strip() if isinstance(what, str) else ""
|
|
817
|
+
if not what:
|
|
818
|
+
raise ValueError("Give it a name, such as DSA exam.")
|
|
819
|
+
if len(what) > 120:
|
|
820
|
+
raise ValueError("Keep the name to 120 characters.")
|
|
821
|
+
try:
|
|
822
|
+
day = date.fromisoformat(when) if isinstance(when, str) else None
|
|
823
|
+
except ValueError:
|
|
824
|
+
day = None
|
|
825
|
+
if day is None:
|
|
826
|
+
raise ValueError("Pick a date.")
|
|
827
|
+
if day.isoformat() < self._today():
|
|
828
|
+
raise ValueError("That date has passed. Pick today or a later day.")
|
|
829
|
+
if kind not in self.DATE_KINDS:
|
|
830
|
+
raise ValueError("kind must be exam or deadline.")
|
|
831
|
+
root = self.need_root()
|
|
832
|
+
with self.reviewing:
|
|
833
|
+
v = Vault(root)
|
|
834
|
+
if any(str(n.fields.get("date") or "")[:10] == day.isoformat()
|
|
835
|
+
and str(n.fields.get("title") or "").casefold() == what.casefold()
|
|
836
|
+
for n in v.iter_notes("assessment")):
|
|
837
|
+
raise ValueError("That is on your board already.")
|
|
838
|
+
if self.core is None or self.core[0] != root:
|
|
839
|
+
core = Keepfold(v)
|
|
840
|
+
core.app_clicks = True # every write here is the user's own click
|
|
841
|
+
self.core = (root, core)
|
|
842
|
+
core = self.core[1]
|
|
843
|
+
client = core.sessions.client
|
|
844
|
+
core.sessions.client = "keepfold-app" # server-set, as grader.client always is
|
|
845
|
+
try:
|
|
846
|
+
core.session = core.sessions.start("ambient", None, "self")
|
|
847
|
+
core._reset()
|
|
848
|
+
# force: another day's page of the same name (last term's DSA exam) is no copy
|
|
849
|
+
out = core._call("keepfold_add", core.keepfold_add, {
|
|
850
|
+
"kind": "assessment", "title": what, "force": True, "fields": {
|
|
851
|
+
"date": day.isoformat(), "kind": kind, "outcome": "pending"}})
|
|
852
|
+
finally:
|
|
853
|
+
core.sessions.client = client
|
|
854
|
+
if core.sessions.current is not None:
|
|
855
|
+
core.sessions.close(summary="Added a date in the Keepfold app")
|
|
856
|
+
if "error" in out:
|
|
857
|
+
raise ValueError(out.get("message") or out["error"])
|
|
858
|
+
return {"id": out["id"], "title": what, "date": day.isoformat(), "kind": kind}
|
|
859
|
+
|
|
860
|
+
def capture(self, body: dict) -> dict:
|
|
861
|
+
"""Quick capture (the desktop app's hotkey box): one typed line, written through the
|
|
862
|
+
shared core (`_with_core`) as the owner's own words. //pref, //fact and //forget lines
|
|
863
|
+
take the chat's own tag path (tags.find, tags.apply); a line that is only an http(s)
|
|
864
|
+
URL becomes a resource titled with its host and path (no fetch), unless a resource in
|
|
865
|
+
the index has that URL already; anything else is a journal line. {kind, said}: `said`
|
|
866
|
+
is the hint line's text. A refusal (a secret, an unsafe line) is a ValueError with the
|
|
867
|
+
core's own message, and nothing is written."""
|
|
868
|
+
from datetime import date
|
|
869
|
+
|
|
870
|
+
from keepfold import chats, dates, tags
|
|
871
|
+
from keepfold.events import local_day
|
|
872
|
+
text = body.get("text")
|
|
873
|
+
if not isinstance(text, str) or not text.strip():
|
|
874
|
+
raise ValueError("Type something first.")
|
|
875
|
+
if len(text) > CAPTURE_MAX:
|
|
876
|
+
raise ValueError(f"Keep it to {CAPTURE_MAX:,} characters.")
|
|
877
|
+
clean = chats.drop_private(text).strip()
|
|
878
|
+
if not clean.replace(chats.PRIVATE, "").strip():
|
|
879
|
+
raise ValueError("Nothing to save: a <private> part is never saved.")
|
|
880
|
+
if found := tags.find(text):
|
|
881
|
+
def tag(core) -> tuple[list[str], list[str]]:
|
|
882
|
+
refused: list[str] = []
|
|
883
|
+
day = local_day(core._now())
|
|
884
|
+
return tags.apply(core, [(t, x, day) for t, x in found],
|
|
885
|
+
refused=refused), refused
|
|
886
|
+
lines, refused = self._with_core(tag, "Quick capture in the Keepfold app")
|
|
887
|
+
if refused:
|
|
888
|
+
raise ValueError("; ".join(lines + refused))
|
|
889
|
+
return {"kind": "tag", "said": "; ".join(lines) or "Already saved today."}
|
|
890
|
+
parts = urlsplit(clean) if URL_ONLY.fullmatch(clean) else None
|
|
891
|
+
if parts is not None and parts.hostname:
|
|
892
|
+
want = clean.removesuffix("/")
|
|
893
|
+
title = (parts.hostname + parts.path.removesuffix("/"))[:200]
|
|
894
|
+
|
|
895
|
+
def link(core) -> dict:
|
|
896
|
+
core.index.refresh()
|
|
897
|
+
for n in core.index._notes.values(): # the index's parsed frontmatter
|
|
898
|
+
u = n["fields"].get("url")
|
|
899
|
+
if n["kind"] == "resource" and isinstance(u, str) \
|
|
900
|
+
and u.strip().removesuffix("/") == want:
|
|
901
|
+
return {"already": n["title"]}
|
|
902
|
+
return core._call("keepfold_add", core.keepfold_add, {
|
|
903
|
+
"kind": "resource", "title": title, "force": True, "fields": {"url": clean}})
|
|
904
|
+
out = self._with_core(link, "Quick capture in the Keepfold app")
|
|
905
|
+
if "error" in out:
|
|
906
|
+
raise ValueError(out.get("message") or out["error"])
|
|
907
|
+
if "already" in out:
|
|
908
|
+
return {"kind": "link", "said": f"Already saved: {out['already']}"}
|
|
909
|
+
return {"kind": "link", "said": "Link saved"}
|
|
910
|
+
|
|
911
|
+
def journal(core) -> dict:
|
|
912
|
+
now = core._now()
|
|
913
|
+
# typed just now, so its relative dates get today's day (L1); _log_journal pins
|
|
914
|
+
# nothing itself under app_clicks (mcp_server._pin_day), so this is the one pin
|
|
915
|
+
line = dates.pin(clean, date.fromisoformat(local_day(now)))
|
|
916
|
+
out = core._call("keepfold_log", core.keepfold_log,
|
|
917
|
+
{"kind": "journal", "payload": {"text": line}})
|
|
918
|
+
return {**out, "hhmm": f"{now.astimezone():%H:%M}"}
|
|
919
|
+
out = self._with_core(journal, "Quick capture in the Keepfold app")
|
|
920
|
+
if "error" in out:
|
|
921
|
+
raise ValueError(out.get("message") or out["error"])
|
|
922
|
+
return {"kind": "journal", "said": f"Added to today's journal {out['hhmm']}"}
|
|
923
|
+
|
|
924
|
+
def unlock(self, body: dict) -> dict:
|
|
925
|
+
"""The Private switch: Windows asks the user to verify (Windows Hello); private items
|
|
926
|
+
then show for PRIVATE_S, until the switch is pressed again or the window minimised."""
|
|
927
|
+
from keepfold.app import hello
|
|
928
|
+
ok, why = hello.verify()
|
|
929
|
+
if ok:
|
|
930
|
+
self.private_until = time.monotonic() + PRIVATE_S
|
|
931
|
+
return {"unlocked": ok, "message": why}
|
|
932
|
+
|
|
933
|
+
def lock(self, body: dict | None = None) -> dict:
|
|
934
|
+
self.private_until = 0.0
|
|
935
|
+
return {"ok": True}
|
|
936
|
+
|
|
937
|
+
# ---- Review (plan 5a): what waits for the user's own click ----
|
|
938
|
+
@staticmethod
|
|
939
|
+
def _today() -> str:
|
|
940
|
+
from datetime import UTC, datetime
|
|
941
|
+
|
|
942
|
+
from keepfold.events import local_day
|
|
943
|
+
return local_day(datetime.now(UTC))
|
|
944
|
+
|
|
945
|
+
def tidy_about_me(self) -> dict:
|
|
946
|
+
"""D1-D3: Keepfold's own sweep of the about-me lines (mcp_server.Keepfold.tidy), at start
|
|
947
|
+
and with each chat-import pass: waiting about-me lines move to their pages, near-copies
|
|
948
|
+
and settled pairs are retired, in one session `keepfold undo` can take back. Not an app
|
|
949
|
+
click, so nothing is stamped `clicked`."""
|
|
950
|
+
from keepfold.mcp_server import Keepfold
|
|
951
|
+
from keepfold.vault import Vault
|
|
952
|
+
root = self.root
|
|
953
|
+
if root is None or not (root / ".keepfold").is_dir():
|
|
954
|
+
return {"moved": 0, "retired": 0}
|
|
955
|
+
from keepfold import review
|
|
956
|
+
with self.reviewing: # never beside a Review click
|
|
957
|
+
review.record_baseline(Vault(root)) # R5a, first run: the guard's baseline
|
|
958
|
+
return Keepfold(Vault(root), build=False).tidy() # tidy reads me/ pages only
|
|
959
|
+
|
|
960
|
+
def review(self) -> dict:
|
|
961
|
+
"""The Review view and its badge count (keepfold.review); shown text only. UX-B: each
|
|
962
|
+
card about a page carries `related` (`_related`)."""
|
|
963
|
+
from keepfold import review
|
|
964
|
+
from keepfold.events import EventLog
|
|
965
|
+
v = self._vault()
|
|
966
|
+
evs = list(EventLog(v).iter_events())
|
|
967
|
+
return self._related(v, review.view(v, evs, self._today()), evs)
|
|
968
|
+
|
|
969
|
+
# ---- UX-B: "#" pages in Chat, related pages beside Review cards ----
|
|
970
|
+
RELATED = 3
|
|
971
|
+
CARDS = ("pending", "expired", "stale", "rules", "imports", "unsafe", "outside", "crowded",
|
|
972
|
+
"promote") # the Review boards whose cards name their `page`
|
|
973
|
+
|
|
974
|
+
def chat_pages(self, query: dict) -> dict:
|
|
975
|
+
"""The "#" list (?q=): pages Chat may read now whose title holds the words
|
|
976
|
+
(`chat.pick_list`); {pages: [{id, title, kind}]}."""
|
|
977
|
+
from keepfold import chat
|
|
978
|
+
q = (query.get("q") or [""])[0][:200]
|
|
979
|
+
return {"pages": chat.pick_list(self._vault(), q, chat.get_settings()["sources"])}
|
|
980
|
+
|
|
981
|
+
def _related(self, v, view: dict, evs: list) -> dict:
|
|
982
|
+
"""Each card with a `page` gets `related`: [{title, path}] of up to RELATED pages linked
|
|
983
|
+
with it (its [[links]] either way: the edges arm of `semantic.linked`, the cheap one;
|
|
984
|
+
the name arms cost ~180 ms a page at 5k), most links first, then by id; never the
|
|
985
|
+
card's own, a rollup, a hub or a quieted page. Chat's kept index holds no private
|
|
986
|
+
page, so none is listed (a card on a private page has none)."""
|
|
987
|
+
from keepfold import chat, chat_study, harvest, semantic
|
|
988
|
+
from keepfold.topics import is_hub
|
|
989
|
+
cards = [x for k in self.CARDS for x in view.get(k) or []
|
|
990
|
+
if isinstance(x.get("page"), str)]
|
|
991
|
+
# never build Chat's index (~3 s at 5k) just for Review: before Chat's first use, no line
|
|
992
|
+
if not cards or chat._INDEX.get(v.root) is None:
|
|
993
|
+
return view
|
|
994
|
+
quiet, got = harvest.quiet(evs), {}
|
|
995
|
+
with chat._INDEX_LOCK:
|
|
996
|
+
idx = chat._index(v, chat.FRESH)
|
|
997
|
+
paths = {i: p for p, i in idx._ids.items()}
|
|
998
|
+
for page in {x["page"] for x in cards}:
|
|
999
|
+
n: dict = {}
|
|
1000
|
+
for i, _ in semantic._neighbours(idx, page):
|
|
1001
|
+
note = idx._notes.get(i)
|
|
1002
|
+
if i != page and i in paths and note and note["kind"] != "rollup" \
|
|
1003
|
+
and not is_hub(note) and quiet.get(i) != 0:
|
|
1004
|
+
n[i] = n.get(i, 0) + 1
|
|
1005
|
+
got[page] = [{"title": chat_study._title(idx._notes[i]["title"]) or i,
|
|
1006
|
+
"path": idx._rel(paths[i])}
|
|
1007
|
+
for i in sorted(n, key=lambda i: (-n[i], i))[:self.RELATED]]
|
|
1008
|
+
for x in cards:
|
|
1009
|
+
x["related"] = got[x["page"]]
|
|
1010
|
+
return view
|
|
1011
|
+
|
|
1012
|
+
def _click(self, tool: str, method: str, kwargs: dict, card: str | None = None,
|
|
1013
|
+
producer: str | None = None) -> dict:
|
|
1014
|
+
"""One Review click, written by an mcp_server.Keepfold with `app_clicks` set through the
|
|
1015
|
+
tool's own code path (keepfold_patch, keepfold_log), in a session closed at once so it is
|
|
1016
|
+
committed and `keepfold undo` can take it back. Returns the fresh Review view. `card`
|
|
1017
|
+
(R3-4) and `producer` (RR-10, review.ledger): stamped on each change the click
|
|
1018
|
+
writes."""
|
|
1019
|
+
return self._clicks([(tool, method, kwargs, card, producer)])
|
|
1020
|
+
|
|
1021
|
+
def _with_core(self, fn, summary: str):
|
|
1022
|
+
"""fn(core) with the app's shared mcp_server.Keepfold (`app_clicks` set: every write is
|
|
1023
|
+
the owner's own) under the Review lock, in a session closed at once so it is committed
|
|
1024
|
+
and `keepfold undo` can take it back; fn's own result."""
|
|
1025
|
+
from keepfold.mcp_server import Keepfold
|
|
1026
|
+
from keepfold.vault import Vault
|
|
1027
|
+
root = self.need_root()
|
|
1028
|
+
with self.reviewing:
|
|
1029
|
+
if self.core is None or self.core[0] != root:
|
|
1030
|
+
core = Keepfold(Vault(root))
|
|
1031
|
+
core.app_clicks = True # every write here is the user's own click
|
|
1032
|
+
self.core = (root, core)
|
|
1033
|
+
core = self.core[1]
|
|
1034
|
+
try:
|
|
1035
|
+
return fn(core)
|
|
1036
|
+
finally:
|
|
1037
|
+
if core.sessions.current is not None:
|
|
1038
|
+
core.sessions.close(summary=summary)
|
|
1039
|
+
|
|
1040
|
+
def _clicks(self, calls: list[tuple]) -> dict:
|
|
1041
|
+
"""One answer's writes, each a `_click` (tool, method, kwargs, card, producer), all in
|
|
1042
|
+
one session, so one `keepfold undo` takes the whole answer back (D5: an answer that
|
|
1043
|
+
covers near-copies). Stops at the first error; what was written before it is kept."""
|
|
1044
|
+
def run(core) -> dict:
|
|
1045
|
+
out: dict = {}
|
|
1046
|
+
try:
|
|
1047
|
+
for tool, method, kwargs, card, producer in calls:
|
|
1048
|
+
core.sessions.stamp = {k: v for k, v in (("card", card),
|
|
1049
|
+
("producer", producer)) if v}
|
|
1050
|
+
out = core._call(tool, getattr(core, method), kwargs)
|
|
1051
|
+
if "error" in out:
|
|
1052
|
+
break
|
|
1053
|
+
finally:
|
|
1054
|
+
core.sessions.stamp = {}
|
|
1055
|
+
return out
|
|
1056
|
+
out = self._with_core(run, "Review in the Keepfold app")
|
|
1057
|
+
if "error" in out:
|
|
1058
|
+
raise ValueError(out.get("message") or out["error"])
|
|
1059
|
+
# R3-7: the rules-file block; R5a: a Keep or Remove on a line changed outside Keepfold
|
|
1060
|
+
if any(c[2].get("id") == "me/core" or c[2].get("page") in ("outside", "core")
|
|
1061
|
+
for c in calls):
|
|
1062
|
+
try: # follows the core at once
|
|
1063
|
+
targets.refresh_rules(self.entry())
|
|
1064
|
+
except Exception as e: # noqa: BLE001 (the periodic pass tries again)
|
|
1065
|
+
print(f"keepfold app: rules block refresh failed ({type(e).__name__})",
|
|
1066
|
+
file=sys.stderr)
|
|
1067
|
+
return self.review()
|
|
1068
|
+
|
|
1069
|
+
def _waiting(self, body: dict) -> dict:
|
|
1070
|
+
from keepfold import review
|
|
1071
|
+
key = body.get("key")
|
|
1072
|
+
item = next((p for p in review.pending(self._vault(), self._today())
|
|
1073
|
+
if isinstance(key, str) and p["key"] == key), None)
|
|
1074
|
+
if item is None:
|
|
1075
|
+
raise NotFound
|
|
1076
|
+
return item
|
|
1077
|
+
|
|
1078
|
+
def _live(self, body: dict) -> dict:
|
|
1079
|
+
from keepfold import claims
|
|
1080
|
+
cid = body.get("id")
|
|
1081
|
+
row = next((r for r in claims.rows(self._vault()) if isinstance(cid, str)
|
|
1082
|
+
and r["id"] == cid and r["status"] == "live"), None)
|
|
1083
|
+
if row is None:
|
|
1084
|
+
raise NotFound
|
|
1085
|
+
return row
|
|
1086
|
+
|
|
1087
|
+
def _waiting_group(self, p: dict) -> list[dict]:
|
|
1088
|
+
"""D5: the waiting lines of `p`'s page that say nearly what `p` says, `p` first."""
|
|
1089
|
+
from keepfold import review
|
|
1090
|
+
same = {x["key"]: x for x in review.pending(self._vault(), self._today())
|
|
1091
|
+
if x["page"] == p["page"]}
|
|
1092
|
+
return [same[k] for k in review.group(list(same.values()), p["key"]) if k in same]
|
|
1093
|
+
|
|
1094
|
+
def review_approve(self, body: dict) -> dict:
|
|
1095
|
+
"""Approve: the waiting line written as keepfold_patch writes a confirmed one, stamped
|
|
1096
|
+
`confirm: clicked`; a teaching-contract rule applies only this way (E2). D5: its
|
|
1097
|
+
near-copies go with it: on a claim page each is approved too (keepfold_patch keeps one of
|
|
1098
|
+
near-duplicates, D1), elsewhere they are dismissed. Only the first click is the card."""
|
|
1099
|
+
from keepfold import claims
|
|
1100
|
+
p = self._waiting(body)
|
|
1101
|
+
calls = []
|
|
1102
|
+
for n, x in enumerate(self._waiting_group(p)):
|
|
1103
|
+
card = "pending" if n == 0 else None
|
|
1104
|
+
if n and x["page"] not in claims.PAGES:
|
|
1105
|
+
calls.append(("keepfold_patch", "_dismiss", {
|
|
1106
|
+
"page": x["page"], "section": x["section"], "text": x["text"]}, card,
|
|
1107
|
+
self._producer(x)))
|
|
1108
|
+
continue
|
|
1109
|
+
rule = x["page"] == "teaching-contract" # stored bare; a rule is a list line
|
|
1110
|
+
calls.append(("keepfold_patch", "keepfold_patch", {
|
|
1111
|
+
"id": f"me/{x['page']}", "op": "append_to_section", "target": x["section"],
|
|
1112
|
+
"text": "- " * rule + x["text"], "user_confirmed": True}, card,
|
|
1113
|
+
self._producer(x)))
|
|
1114
|
+
return self._clicks(calls)
|
|
1115
|
+
|
|
1116
|
+
def review_dismiss(self, body: dict) -> dict:
|
|
1117
|
+
"""Dismiss: a claim page's line goes to its `## Not me` (keepfold_patch reject); another
|
|
1118
|
+
page's (the contract, the portrait) leaves a `dismiss` change. Never proposed again.
|
|
1119
|
+
D5: it covers the line's near-copies too."""
|
|
1120
|
+
from keepfold import claims
|
|
1121
|
+
calls = []
|
|
1122
|
+
for n, p in enumerate(self._waiting_group(self._waiting(body))):
|
|
1123
|
+
card = "pending" if n == 0 else None
|
|
1124
|
+
if p["page"] in claims.PAGES:
|
|
1125
|
+
calls.append(("keepfold_patch", "keepfold_patch", {
|
|
1126
|
+
"id": f"me/{p['page']}", "op": "reject",
|
|
1127
|
+
"target": f"{p['section']}: {p['text']}"}, card, self._producer(p)))
|
|
1128
|
+
else:
|
|
1129
|
+
calls.append(("keepfold_patch", "_dismiss", {
|
|
1130
|
+
"page": p["page"], "section": p["section"], "text": p["text"]}, card,
|
|
1131
|
+
self._producer(p)))
|
|
1132
|
+
return self._clicks(calls)
|
|
1133
|
+
|
|
1134
|
+
def _line_group(self, cid: str) -> list[str]:
|
|
1135
|
+
"""D5: the live line `cid` and, when it is on the Still true? or the unsafe board, the
|
|
1136
|
+
near-copies that card stands for (review.stale's `ids`, review.collapse)."""
|
|
1137
|
+
from keepfold import review
|
|
1138
|
+
from keepfold.events import EventLog
|
|
1139
|
+
v = self._vault()
|
|
1140
|
+
events = list(EventLog(v).iter_events())
|
|
1141
|
+
for x in review.stale(review.live_rows(v, events, self._today()), events,
|
|
1142
|
+
self._today(), review.known_texts(v)):
|
|
1143
|
+
if cid in x["ids"]:
|
|
1144
|
+
return [cid, *(i for i in x["ids"] if i != cid)]
|
|
1145
|
+
hidden = review._private(v)
|
|
1146
|
+
return review.group([x for x in review.unsafe_lines(v, events)
|
|
1147
|
+
if x["page"] not in hidden], cid, "id")
|
|
1148
|
+
|
|
1149
|
+
def review_still(self, body: dict) -> dict:
|
|
1150
|
+
"""Still true: a reconfirm stamped `confirm: clicked` (claims.tiers: confirmed), for
|
|
1151
|
+
the line and the near-copies its card stands for (D5)."""
|
|
1152
|
+
return self._clicks([("keepfold_log", "keepfold_log", {
|
|
1153
|
+
"kind": "reconfirm", "payload": {"claim": cid, "verdict": "yes"}}, None, None)
|
|
1154
|
+
for cid in self._line_group(self._live(body)["id"])])
|
|
1155
|
+
|
|
1156
|
+
def review_retire(self, body: dict) -> dict:
|
|
1157
|
+
"""Retire: keepfold_patch's retire op moves the line to `## Past`. A //forget card's
|
|
1158
|
+
candidate is the forget producer's accept (RR-10); a crowded line's (G7) is stamped
|
|
1159
|
+
`crowded`, so it counts in that card's monthly cap. D5: on a Still true? or unsafe card
|
|
1160
|
+
the near-copies it stands for are retired too."""
|
|
1161
|
+
from keepfold import claims, review, tags
|
|
1162
|
+
from keepfold.events import EventLog
|
|
1163
|
+
r = self._live(body)
|
|
1164
|
+
v = self._vault()
|
|
1165
|
+
events = list(EventLog(v).iter_events())
|
|
1166
|
+
cards = [x["text"] for x in tags.forget_cards(v, events, self._today())
|
|
1167
|
+
if any(c["id"] == r["id"] for c in x["candidates"])]
|
|
1168
|
+
forget = "forget" if cards else None
|
|
1169
|
+
card = forget or ("crowded" if any(x["id"] == r["id"] for x in review.crowded(
|
|
1170
|
+
v, review.live_rows(v, events, self._today()))[0]) else None)
|
|
1171
|
+
live = {x["id"]: x for x in claims.rows(v) if x["status"] == "live"}
|
|
1172
|
+
view = self._clicks([("keepfold_patch", "keepfold_patch", {
|
|
1173
|
+
"id": f"me/{live[cid]['page']}", "op": "retire", "target": cid,
|
|
1174
|
+
"user_confirmed": True}, card if n == 0 else None, forget)
|
|
1175
|
+
for n, cid in enumerate(self._line_group(r["id"]) if card is None else [r["id"]])
|
|
1176
|
+
if cid in live])
|
|
1177
|
+
if not forget or r["id"] not in live:
|
|
1178
|
+
return view
|
|
1179
|
+
# R10: a //forget card's line then goes from every store; the answer carries the receipt
|
|
1180
|
+
from keepfold import forget as forget_
|
|
1181
|
+
from keepfold import session
|
|
1182
|
+
mark = v.writes
|
|
1183
|
+
receipt = forget_.claim(v, live[r["id"]]["page"], r["id"], also=tuple(cards))
|
|
1184
|
+
session._commit(v, "keepfold: forget a line", v.wrote_since(mark))
|
|
1185
|
+
return {**self.review(), "receipt": receipt, "receipt_lines": forget_.lines(receipt)}
|
|
1186
|
+
|
|
1187
|
+
def review_crowded_keep(self, body: dict) -> dict:
|
|
1188
|
+
"""G7: Keep, on a line the X-ray shows cut for space in most primes: the X-ray's Pin
|
|
1189
|
+
(prime serves it first, within the Preferences cap) and a `dismiss` change on id
|
|
1190
|
+
`crowded` holding its id's hash, stamped `crowded` for the monthly cap."""
|
|
1191
|
+
from keepfold import review, xray
|
|
1192
|
+
from keepfold.events import EventLog
|
|
1193
|
+
v, cid = self._vault(), body.get("id")
|
|
1194
|
+
if not any(x["id"] == cid for x in review.crowded(
|
|
1195
|
+
v, review.live_rows(v, EventLog(v).iter_events(), self._today()))[0]):
|
|
1196
|
+
raise NotFound
|
|
1197
|
+
with self.reviewing:
|
|
1198
|
+
xray.set_flag(v, "pin", xray.claim(cid), True)
|
|
1199
|
+
return self._click("keepfold_patch", "_dismiss", {
|
|
1200
|
+
"page": "crowded", "section": "Crowded", "text": cid, "waiting": False}, "crowded")
|
|
1201
|
+
|
|
1202
|
+
def review_playbook_keep(self, body: dict) -> dict:
|
|
1203
|
+
"""G7: Keep, on a playbook no AI app was served lately: a `dismiss` change on id
|
|
1204
|
+
`playbooks` holding its id's hash, so it is not asked about for review.UNUSED_DAYS;
|
|
1205
|
+
stamped `unused` for the monthly cap. The page stays as it is."""
|
|
1206
|
+
from keepfold import review
|
|
1207
|
+
from keepfold.events import EventLog
|
|
1208
|
+
v, pid = self._vault(), body.get("id")
|
|
1209
|
+
if not any(x["id"] == pid for x in review.unused(
|
|
1210
|
+
v, list(EventLog(v).iter_events()), self._today())[0]):
|
|
1211
|
+
raise NotFound
|
|
1212
|
+
return self._click("keepfold_patch", "_dismiss", {
|
|
1213
|
+
"page": "playbooks", "section": "Playbooks", "text": pid, "waiting": False},
|
|
1214
|
+
"unused")
|
|
1215
|
+
|
|
1216
|
+
def _promoted(self, body: dict) -> dict:
|
|
1217
|
+
"""R28a: the offered "Pin it to Core?" line (review.promote) whose id `body` names."""
|
|
1218
|
+
from keepfold import review
|
|
1219
|
+
from keepfold.events import EventLog
|
|
1220
|
+
v, cid = self._vault(), body.get("id")
|
|
1221
|
+
events = list(EventLog(v).iter_events())
|
|
1222
|
+
x = next((x for x in review.promote(v, review.live_rows(v, events, self._today()),
|
|
1223
|
+
events, self._today()) if x["id"] == cid), None)
|
|
1224
|
+
if x is None:
|
|
1225
|
+
raise NotFound
|
|
1226
|
+
return x
|
|
1227
|
+
|
|
1228
|
+
def review_promote_pin(self, body: dict) -> dict:
|
|
1229
|
+
"""R28a: Pin to Core: the line written to me/core's `## Core` as Approve writes a
|
|
1230
|
+
repeated correction there (`confirm: clicked`), stamped `promote_core` for the card's
|
|
1231
|
+
monthly cap."""
|
|
1232
|
+
from keepfold import claims, review
|
|
1233
|
+
x = self._promoted(body)
|
|
1234
|
+
return self._click("keepfold_patch", "keepfold_patch", {
|
|
1235
|
+
"id": "me/core", "op": "append_to_section", "target": "Core",
|
|
1236
|
+
"text": " ".join(claims._MARK.sub("", x["text"]).split()),
|
|
1237
|
+
"user_confirmed": True}, review.PROMOTE)
|
|
1238
|
+
|
|
1239
|
+
def review_promote_later(self, body: dict) -> dict:
|
|
1240
|
+
"""R28a: Not now: a `dismiss` change on id `promote_core` holding the line id's hash,
|
|
1241
|
+
so it is not offered for review.PROMOTE_QUIET days; stamped for the monthly cap."""
|
|
1242
|
+
from keepfold import review
|
|
1243
|
+
x = self._promoted(body)
|
|
1244
|
+
return self._click("keepfold_patch", "_dismiss", {
|
|
1245
|
+
"page": review.PROMOTE, "section": "Core", "text": x["id"], "waiting": False},
|
|
1246
|
+
review.PROMOTE)
|
|
1247
|
+
|
|
1248
|
+
def _producer(self, p: dict) -> str:
|
|
1249
|
+
"""RR-10: the producer of a waiting line (review.producer_of)."""
|
|
1250
|
+
from keepfold import review
|
|
1251
|
+
from keepfold.events import EventLog
|
|
1252
|
+
v = self._vault()
|
|
1253
|
+
return review.producer_of(review._proposals(EventLog(v).iter_events()), p["page"],
|
|
1254
|
+
p["text"])
|
|
1255
|
+
|
|
1256
|
+
def review_resume(self, body: dict) -> dict:
|
|
1257
|
+
"""RR-10: Resume a paused Review producer (a `resume` change; Status names it)."""
|
|
1258
|
+
from keepfold import fact_harvest, review
|
|
1259
|
+
from keepfold.events import EventLog
|
|
1260
|
+
p, v = body.get("producer"), self._vault()
|
|
1261
|
+
if not review.ledger(EventLog(v).iter_events()).get(p, {}).get("paused") and not (
|
|
1262
|
+
p == fact_harvest.PRODUCER and fact_harvest.ledger(v)["paused"]):
|
|
1263
|
+
raise NotFound
|
|
1264
|
+
return self._click("keepfold_patch", "_resume", {"producer": p})
|
|
1265
|
+
|
|
1266
|
+
def review_conflict(self, body: dict) -> dict:
|
|
1267
|
+
"""A conflict pair (plan 5b, D2: two of the owner's lines or two inferred ones that
|
|
1268
|
+
clash): `keep` both (a `keep_both` change, which also covers later near-copies of the
|
|
1269
|
+
pair, review.kept_cover), or `left` or `right`, which retires the other line and its
|
|
1270
|
+
near-copies (review.copies) through keepfold_patch's retire op."""
|
|
1271
|
+
from keepfold import review
|
|
1272
|
+
from keepfold.events import EventLog
|
|
1273
|
+
v, key, keep = self._vault(), body.get("key"), body.get("keep")
|
|
1274
|
+
if keep not in ("both", "left", "right"):
|
|
1275
|
+
raise ValueError("keep must be both, left or right.")
|
|
1276
|
+
events = list(EventLog(v).iter_events())
|
|
1277
|
+
rows = review.live_rows(v, events, self._today())
|
|
1278
|
+
pair = next((c for c in review.conflicts(rows, events, review.known_texts(v))
|
|
1279
|
+
if c["key"] == key), None)
|
|
1280
|
+
if pair is None:
|
|
1281
|
+
raise NotFound
|
|
1282
|
+
card = "conflict"
|
|
1283
|
+
if keep == "both":
|
|
1284
|
+
return self._click("keepfold_patch", "_keep_both", {"page": pair["left"]["page"],
|
|
1285
|
+
"pair": pair["key"]}, card)
|
|
1286
|
+
# D5: the other line's near-copies go too, so the card does not come back
|
|
1287
|
+
return self._clicks([("keepfold_patch", "keepfold_patch", {
|
|
1288
|
+
"id": f"me/{r['page']}", "op": "retire", "target": r["id"],
|
|
1289
|
+
"user_confirmed": True}, card if n == 0 else None, None)
|
|
1290
|
+
for n, r in enumerate(review.copies(rows, pair["right" if keep == "left"
|
|
1291
|
+
else "left"]))])
|
|
1292
|
+
|
|
1293
|
+
def _rule(self, body: dict) -> dict:
|
|
1294
|
+
from keepfold import corrections, review
|
|
1295
|
+
from keepfold.events import EventLog
|
|
1296
|
+
v, key = self._vault(), body.get("key")
|
|
1297
|
+
events = list(EventLog(v).iter_events())
|
|
1298
|
+
rows = review.live_rows(v, events, self._today())
|
|
1299
|
+
item = next((x for x in corrections.proposals(v, events, rows) if x["key"] == key), None)
|
|
1300
|
+
if item is None:
|
|
1301
|
+
raise NotFound
|
|
1302
|
+
return item
|
|
1303
|
+
|
|
1304
|
+
def review_rule_approve(self, body: dict) -> dict:
|
|
1305
|
+
"""A repeated correction (plan 5b) approved: me/core's `## Core` (a standing rule) or
|
|
1306
|
+
me/preferences' `## Personal` gets it as the user's own line (`corrections.bound`),
|
|
1307
|
+
written as Approve writes a waiting one (`confirm: clicked`)."""
|
|
1308
|
+
x = self._rule(body)
|
|
1309
|
+
return self._click("keepfold_patch", "keepfold_patch", {
|
|
1310
|
+
"id": f"me/{x['page']}", "op": "append_to_section", "target": x["section"],
|
|
1311
|
+
"text": x["text"],
|
|
1312
|
+
"user_confirmed": True}, "rule", "corrections")
|
|
1313
|
+
|
|
1314
|
+
def review_rule_approve_all(self, body: dict) -> dict:
|
|
1315
|
+
"""R3-4: Approve all, only on repeated corrections (mined patterns, each seen in 2+
|
|
1316
|
+
chats): every offered one of the shown `keys`, each written as its own Approve."""
|
|
1317
|
+
keys = body.get("keys")
|
|
1318
|
+
if not isinstance(keys, list):
|
|
1319
|
+
raise ValueError("keys must be the shown corrections' keys.")
|
|
1320
|
+
items = [x for k in dict.fromkeys(keys) if isinstance(k, str)
|
|
1321
|
+
for x in [self._rule({"key": k})]] # an unknown key is 404 before any write
|
|
1322
|
+
out = self.review()
|
|
1323
|
+
for x in items:
|
|
1324
|
+
out = self._click("keepfold_patch", "keepfold_patch", {
|
|
1325
|
+
"id": f"me/{x['page']}", "op": "append_to_section",
|
|
1326
|
+
"target": x["section"], "text": x["text"],
|
|
1327
|
+
"user_confirmed": True}, "rule", "corrections")
|
|
1328
|
+
return out
|
|
1329
|
+
|
|
1330
|
+
def review_rule_dismiss(self, body: dict) -> dict:
|
|
1331
|
+
"""A repeated correction dismissed: a `dismiss` change on page `corrections` holds its
|
|
1332
|
+
text's hash, so it is not offered again."""
|
|
1333
|
+
x = self._rule(body)
|
|
1334
|
+
return self._click("keepfold_patch", "_dismiss", {
|
|
1335
|
+
"page": "corrections", "section": "Core", "text": x["text"], "waiting": False}, "rule",
|
|
1336
|
+
"corrections")
|
|
1337
|
+
|
|
1338
|
+
def _decision(self, body: dict) -> dict:
|
|
1339
|
+
from keepfold import more_sources
|
|
1340
|
+
from keepfold.events import EventLog
|
|
1341
|
+
v, key = self._vault(), body.get("key")
|
|
1342
|
+
item = next((x for x in more_sources.decision_proposals(v, EventLog(v).iter_events())
|
|
1343
|
+
if x["key"] == key), None)
|
|
1344
|
+
if item is None:
|
|
1345
|
+
raise NotFound
|
|
1346
|
+
return item
|
|
1347
|
+
|
|
1348
|
+
def review_decision_approve(self, body: dict) -> dict:
|
|
1349
|
+
"""RR-9: a decision-like commit subject approved becomes a decision page (status
|
|
1350
|
+
accepted, the commit's day, linked to the repo page; private when that page is)."""
|
|
1351
|
+
x = self._decision(body)
|
|
1352
|
+
from datetime import date, timedelta
|
|
1353
|
+
|
|
1354
|
+
from keepfold import loops # follow up REVIEW_DAYS from the approve day, not the commit's
|
|
1355
|
+
due = date.fromisoformat(self._today()) + timedelta(days=loops.REVIEW_DAYS)
|
|
1356
|
+
fields = {"date": x["date"], "status": "accepted", "related": [x["page"]],
|
|
1357
|
+
"review_on": due.isoformat(),
|
|
1358
|
+
"summary": f"From my commit {x['hash'][:7]} in {x['project']} "
|
|
1359
|
+
f"(\"{x['word']}\")."}
|
|
1360
|
+
if x["private"]:
|
|
1361
|
+
fields["private"] = True
|
|
1362
|
+
return self._click("keepfold_add", "_decide", {"title": x["subject"], "fields": fields,
|
|
1363
|
+
"hash": x["key"]}, "decision",
|
|
1364
|
+
"decisions")
|
|
1365
|
+
|
|
1366
|
+
def review_decision_dismiss(self, body: dict) -> dict:
|
|
1367
|
+
"""RR-9: a dismissed commit decision leaves a `dismiss` change on id `decisions` with its
|
|
1368
|
+
key, so it is not offered again."""
|
|
1369
|
+
x = self._decision(body)
|
|
1370
|
+
return self._click("keepfold_patch", "_dismiss", {
|
|
1371
|
+
"page": "decisions", "section": x["project"], "text": f"{x['page']} {x['hash']}",
|
|
1372
|
+
"waiting": False}, "decision", "decisions")
|
|
1373
|
+
|
|
1374
|
+
def review_forget_dismiss(self, body: dict) -> dict:
|
|
1375
|
+
"""A //forget card (keepfold.tags) dismissed: a `dismiss` change on page `forget` holds
|
|
1376
|
+
the hash of its event id, so the card closes; no line changes."""
|
|
1377
|
+
from keepfold import review, tags
|
|
1378
|
+
from keepfold.events import EventLog
|
|
1379
|
+
v, key = self._vault(), body.get("key")
|
|
1380
|
+
cards = tags.forget_cards(v, EventLog(v).iter_events(), self._today())
|
|
1381
|
+
if not any(x["key"] == key for x in cards):
|
|
1382
|
+
raise NotFound
|
|
1383
|
+
return self._clicks([("keepfold_patch", "_dismiss", { # D5: the card's near-copies too
|
|
1384
|
+
"page": "forget", "section": "Forget", "text": k, "waiting": False},
|
|
1385
|
+
"forget" if n == 0 else None, "forget")
|
|
1386
|
+
for n, k in enumerate(review.group(cards, key))])
|
|
1387
|
+
|
|
1388
|
+
def review_import_dismiss(self, body: dict) -> dict:
|
|
1389
|
+
"""RR-18: a card for a hand-edited imported page dismissed: a `dismiss` change on id
|
|
1390
|
+
`imports` holding its key; both pages stay as they are."""
|
|
1391
|
+
from keepfold import sources
|
|
1392
|
+
from keepfold.events import EventLog
|
|
1393
|
+
v, key = self._vault(), body.get("key")
|
|
1394
|
+
if not any(x["key"] == key for x in sources.edited_pages(v, EventLog(v).iter_events())):
|
|
1395
|
+
raise NotFound
|
|
1396
|
+
return self._click("keepfold_patch", "_dismiss", {
|
|
1397
|
+
"page": "imports", "section": "Imports", "text": key, "waiting": False})
|
|
1398
|
+
|
|
1399
|
+
def review_unsafe_keep(self, body: dict) -> dict:
|
|
1400
|
+
"""G6: Keep it, on a line that reads as an instruction to an AI or holds invisible
|
|
1401
|
+
characters: a `dismiss` change on id `unsafe` holding its key, so it is served again
|
|
1402
|
+
(review.unsafe_lines); the line stays as it is. Keep it out is Retire."""
|
|
1403
|
+
from keepfold import review
|
|
1404
|
+
from keepfold.events import EventLog
|
|
1405
|
+
v, key = self._vault(), body.get("key")
|
|
1406
|
+
lines = review.unsafe_lines(v, EventLog(v).iter_events())
|
|
1407
|
+
if not any(x["key"] == key for x in lines):
|
|
1408
|
+
raise NotFound
|
|
1409
|
+
hidden = review._private(v)
|
|
1410
|
+
return self._clicks([("keepfold_patch", "_dismiss", {
|
|
1411
|
+
"page": "unsafe", "section": "Unsafe", "text": k, "waiting": False}, None, None)
|
|
1412
|
+
for k in review.group([x for x in lines if x["page"] not in hidden], key)]) # D5
|
|
1413
|
+
|
|
1414
|
+
def _outside(self, body: dict) -> dict:
|
|
1415
|
+
"""R5a: the card's line changed outside Keepfold (review.outside_lines), by its key."""
|
|
1416
|
+
from keepfold import review
|
|
1417
|
+
from keepfold.events import EventLog
|
|
1418
|
+
v, key = self._vault(), body.get("key")
|
|
1419
|
+
hidden = review._private(v)
|
|
1420
|
+
x = next((x for x in review.outside_lines(v, EventLog(v).iter_events())
|
|
1421
|
+
if isinstance(key, str) and x["key"] == key and x["page"] not in hidden), None)
|
|
1422
|
+
if x is None:
|
|
1423
|
+
raise NotFound
|
|
1424
|
+
return x
|
|
1425
|
+
|
|
1426
|
+
def review_outside_keep(self, body: dict) -> dict:
|
|
1427
|
+
"""R5a: Keep, on a line changed outside Keepfold: a `dismiss` change on id `outside`
|
|
1428
|
+
holding its key, so AI apps are served it from now on; the line stays as it is."""
|
|
1429
|
+
x = self._outside(body)
|
|
1430
|
+
return self._click("keepfold_patch", "_dismiss", {
|
|
1431
|
+
"page": "outside", "section": "Outside", "text": x["key"], "waiting": False})
|
|
1432
|
+
|
|
1433
|
+
def review_outside_remove(self, body: dict) -> dict:
|
|
1434
|
+
"""R5a: Remove, on a line changed outside Keepfold: a claim line is retired to `## Past`
|
|
1435
|
+
(keepfold_patch retire), any other line deleted (Keepfold._remove_outside); undoable."""
|
|
1436
|
+
x = self._outside(body)
|
|
1437
|
+
if x["id"] and x["page"] != "teaching-contract":
|
|
1438
|
+
return self._click("keepfold_patch", "keepfold_patch", {
|
|
1439
|
+
"id": f"me/{x['page']}", "op": "retire", "target": x["id"],
|
|
1440
|
+
"user_confirmed": True})
|
|
1441
|
+
return self._click("keepfold_patch", "_remove_outside", {"page": x["page"],
|
|
1442
|
+
"key": x["key"]})
|
|
1443
|
+
|
|
1444
|
+
# ---- Tonight (Gemini round 3 "Nightly Closeout"): close the day ----
|
|
1445
|
+
def tonight(self) -> dict:
|
|
1446
|
+
"""The Tonight tab (keepfold.tonight) for the current Keepfold day, plus the Review view
|
|
1447
|
+
its Today's 5 board shows; read-only, shown text only."""
|
|
1448
|
+
from datetime import UTC, datetime
|
|
1449
|
+
|
|
1450
|
+
from keepfold import tonight
|
|
1451
|
+
from keepfold.events import EventLog
|
|
1452
|
+
v = self._vault()
|
|
1453
|
+
return {**tonight.view(v, list(EventLog(v).iter_events()), datetime.now(UTC)),
|
|
1454
|
+
"review": self.review()}
|
|
1455
|
+
|
|
1456
|
+
def tonight_undo(self, body: dict) -> dict:
|
|
1457
|
+
"""Undo one AI app's session shown under "What AI apps learned today", as `keepfold
|
|
1458
|
+
undo <session>` does (the CLI's own code, as a job). A session not shown there
|
|
1459
|
+
(unknown, or already undone: its events went with it) is 404. A session still open
|
|
1460
|
+
has no commit yet, so it is refused rather than "undone" with nothing reverted."""
|
|
1461
|
+
from keepfold import cli
|
|
1462
|
+
from keepfold.events import EventLog
|
|
1463
|
+
sid, root = body.get("session"), self.need_root()
|
|
1464
|
+
if not isinstance(sid, str) or sid not in {
|
|
1465
|
+
g["session"] for g in self.tonight()["learned"]}:
|
|
1466
|
+
raise NotFound
|
|
1467
|
+
if not any(e.get("session") == sid and e.get("kind") == "close"
|
|
1468
|
+
for e in EventLog(self._vault()).iter_events()):
|
|
1469
|
+
raise ValueError("This AI app's session is still open, so nothing is saved to undo "
|
|
1470
|
+
"yet. Undo works once the session closes.")
|
|
1471
|
+
|
|
1472
|
+
def run(job):
|
|
1473
|
+
try:
|
|
1474
|
+
return actions.capture(job, cli.undo, sid, vault=root)
|
|
1475
|
+
finally:
|
|
1476
|
+
with self.reviewing: # never mid-click: the Review clicks' Keepfold reloads
|
|
1477
|
+
self.core = None # the reverted catalog
|
|
1478
|
+
|
|
1479
|
+
return self.jobs.start("Undoing an AI app's changes", "tonight", run)
|
|
1480
|
+
|
|
1481
|
+
# ---- Agent X-ray (v9 item 6): what prime and context served each AI app ----
|
|
1482
|
+
def xray(self) -> dict:
|
|
1483
|
+
from keepfold import xray
|
|
1484
|
+
return xray.view(self._vault())
|
|
1485
|
+
|
|
1486
|
+
def _xray_set(self, which: str, body: dict) -> dict:
|
|
1487
|
+
"""Pin or Mute (`on`, default true) one id, or a private one by its view `token`. The
|
|
1488
|
+
app's click is the only way in: no MCP tool sets these (keepfold.xray)."""
|
|
1489
|
+
from keepfold import xray
|
|
1490
|
+
v, on = self._vault(), body.get("on", True)
|
|
1491
|
+
id = xray.resolve_token(v, body["token"]) if isinstance(body.get("token"), str) \
|
|
1492
|
+
else body.get("id")
|
|
1493
|
+
if not isinstance(on, bool) or id is None:
|
|
1494
|
+
raise ValueError("Pin or mute takes one page or claim id.")
|
|
1495
|
+
with self.reviewing:
|
|
1496
|
+
xray.set_flag(v, which, id, on)
|
|
1497
|
+
return self.xray()
|
|
1498
|
+
|
|
1499
|
+
def xray_pin(self, body: dict) -> dict:
|
|
1500
|
+
return self._xray_set("pin", body)
|
|
1501
|
+
|
|
1502
|
+
def xray_mute(self, body: dict) -> dict:
|
|
1503
|
+
return self._xray_set("mute", body)
|
|
1504
|
+
|
|
1505
|
+
def xray_dryrun(self, body: dict) -> dict:
|
|
1506
|
+
"""What keepfold_prime would serve one AI app for a prompt (mcp_server.dry_prime), shown
|
|
1507
|
+
as an X-ray call: titles only. Nothing is written or logged, the prompt included."""
|
|
1508
|
+
from keepfold import xray
|
|
1509
|
+
from keepfold.mcp_server import dry_prime
|
|
1510
|
+
client, prompt = body.get("client"), body.get("prompt")
|
|
1511
|
+
if not isinstance(client, str) or len(client) > 100:
|
|
1512
|
+
raise ValueError("client must be an AI app's name, at most 100 characters.")
|
|
1513
|
+
if not isinstance(prompt, str) or not prompt.strip() or len(prompt) > 2000:
|
|
1514
|
+
raise ValueError("Type a prompt of at most 2,000 characters.")
|
|
1515
|
+
with self._dry_index() as (v, index):
|
|
1516
|
+
got = dry_prime(v, client, prompt, index=index)
|
|
1517
|
+
return xray.present(v, got["served"], got["trimmed"], got["chars"])
|
|
1518
|
+
|
|
1519
|
+
@contextmanager
|
|
1520
|
+
def _dry_index(self):
|
|
1521
|
+
"""(the vault, X-ray's one read-only Index for it), held by this request alone: built
|
|
1522
|
+
by the first dry run or compare, kept for the next (dry_prime sets each run's withhold
|
|
1523
|
+
and refreshes it by stat), replaced for another vault and let go by `drop_dry`. A run
|
|
1524
|
+
that fails drops it, so a half-done refresh is never reused."""
|
|
1525
|
+
from keepfold.catalog import Catalog
|
|
1526
|
+
from keepfold.index import Index
|
|
1527
|
+
v = self._vault()
|
|
1528
|
+
with self.dry:
|
|
1529
|
+
if self.dry_index is None or self.dry_index[0] != v.root:
|
|
1530
|
+
self._close_dry()
|
|
1531
|
+
self.dry_index = (v.root, Index(v, Catalog.load(v), save=False))
|
|
1532
|
+
try:
|
|
1533
|
+
yield v, self.dry_index[1]
|
|
1534
|
+
except BaseException:
|
|
1535
|
+
self._close_dry()
|
|
1536
|
+
raise
|
|
1537
|
+
finally:
|
|
1538
|
+
self.dry_used = time.monotonic()
|
|
1539
|
+
|
|
1540
|
+
def _close_dry(self) -> None: # under self.dry
|
|
1541
|
+
if self.dry_index is not None:
|
|
1542
|
+
self.dry_index[1].db.close()
|
|
1543
|
+
self.dry_index = None
|
|
1544
|
+
|
|
1545
|
+
def drop_dry(self, now: float | None = None) -> bool:
|
|
1546
|
+
"""Let X-ray's shared index go once unused for DRY_IDLE_S or once another vault is open
|
|
1547
|
+
(`start`'s watch checks); never while a request holds it. True when it went."""
|
|
1548
|
+
if not self.dry.acquire(blocking=False): # in use: not idle
|
|
1549
|
+
return False
|
|
1550
|
+
try:
|
|
1551
|
+
now = time.monotonic() if now is None else now
|
|
1552
|
+
if self.dry_index is None or (now - self.dry_used < DRY_IDLE_S
|
|
1553
|
+
and self.dry_index[0] == self.root):
|
|
1554
|
+
return False
|
|
1555
|
+
self._close_dry()
|
|
1556
|
+
return True
|
|
1557
|
+
finally:
|
|
1558
|
+
self.dry.release()
|
|
1559
|
+
|
|
1560
|
+
@staticmethod
|
|
1561
|
+
def _xray_client(body: dict, key: str = "client") -> str:
|
|
1562
|
+
c = body.get(key)
|
|
1563
|
+
if not isinstance(c, str) or len(c) > 100:
|
|
1564
|
+
raise ValueError("client must be an AI app's name, at most 100 characters.")
|
|
1565
|
+
return c
|
|
1566
|
+
|
|
1567
|
+
def xray_trace(self, body: dict) -> dict:
|
|
1568
|
+
"""R27b: which of what Keepfold gave one AI app lately a pasted reply echoes
|
|
1569
|
+
(xray.trace, local words only). The reply is never written or logged: not here, not in
|
|
1570
|
+
an X-ray row or event, and an error answers with its type or our own message only."""
|
|
1571
|
+
from keepfold import xray
|
|
1572
|
+
client, text = self._xray_client(body), body.get("text")
|
|
1573
|
+
if not isinstance(text, str) or not text.strip() or len(text) > xray.TRACE_MAX:
|
|
1574
|
+
raise ValueError(f"Paste a reply of at most {xray.TRACE_MAX:,} characters.")
|
|
1575
|
+
return xray.trace(self._vault(), client, text)
|
|
1576
|
+
|
|
1577
|
+
def xray_compare(self, body: dict) -> dict:
|
|
1578
|
+
"""R27b: two AI apps' dry runs for one prompt and what each one's profile withholds
|
|
1579
|
+
(xray.compare). Nothing is written or logged, the prompt included."""
|
|
1580
|
+
from keepfold import xray
|
|
1581
|
+
a, b, prompt = self._xray_client(body, "a"), self._xray_client(body, "b"), \
|
|
1582
|
+
body.get("prompt")
|
|
1583
|
+
if not isinstance(prompt, str) or not prompt.strip() or len(prompt) > 2000:
|
|
1584
|
+
raise ValueError("Type a prompt of at most 2,000 characters.")
|
|
1585
|
+
if (a or "unknown") == (b or "unknown"):
|
|
1586
|
+
raise ValueError("Pick two different apps.")
|
|
1587
|
+
with self._dry_index() as (v, index):
|
|
1588
|
+
return xray.compare(v, prompt, a, b, index=index)
|
|
1589
|
+
|
|
1590
|
+
def xray_ack(self, body: dict) -> dict:
|
|
1591
|
+
"""R27b: Got it on an app's broad-read warning; like Pin and Mute, only this click sets
|
|
1592
|
+
it (xray.ack)."""
|
|
1593
|
+
from keepfold import xray
|
|
1594
|
+
client, end = self._xray_client(body), body.get("end")
|
|
1595
|
+
if not isinstance(end, str) or len(end) > 40:
|
|
1596
|
+
raise ValueError("end must be the warning's time.")
|
|
1597
|
+
v = self._vault()
|
|
1598
|
+
with self.reviewing:
|
|
1599
|
+
xray.ack(v, client, end)
|
|
1600
|
+
return self.xray()
|
|
1601
|
+
|
|
1602
|
+
def chat_settings_get(self) -> dict:
|
|
1603
|
+
from keepfold import chat
|
|
1604
|
+
return chat.get_settings()
|
|
1605
|
+
|
|
1606
|
+
def setup(self) -> dict:
|
|
1607
|
+
from keepfold import chats, cli, importers
|
|
1608
|
+
from keepfold.app import desktop
|
|
1609
|
+
if self.warming not in (None, threading.current_thread()):
|
|
1610
|
+
self.warming.join() # the warm-up is asking the same probes: wait, not ask twice
|
|
1611
|
+
return {**wizard.state(self.root, self.scanned),
|
|
1612
|
+
"connect": [{k: t[k] for k in ("id", "label", "detected", "connected")}
|
|
1613
|
+
for t in targets.describe(self.entry())],
|
|
1614
|
+
"first_prompts": list(cli.FIRST_PROMPTS), "connect_skipped": _connect_skipped(),
|
|
1615
|
+
"welcome_done": desktop._app_cfg().get("welcome_done") is True,
|
|
1616
|
+
"guides": {**chats.GUIDES, **importers.GUIDES},
|
|
1617
|
+
"imports": status.imports(self.root if self.entry() else None),
|
|
1618
|
+
"watched": self._watched()}
|
|
1619
|
+
|
|
1620
|
+
# ---- POST ----
|
|
1621
|
+
def _want(self, body: dict) -> dict:
|
|
1622
|
+
want = body.get("want")
|
|
1623
|
+
if not isinstance(want, dict) or not all(
|
|
1624
|
+
isinstance(v, bool) or (k == "lmstudio" and v == "private")
|
|
1625
|
+
for k, v in want.items()):
|
|
1626
|
+
raise ValueError("want must map app ids to true or false")
|
|
1627
|
+
return want
|
|
1628
|
+
|
|
1629
|
+
def connect_plan(self, body: dict) -> dict:
|
|
1630
|
+
return {"rows": targets.plan_all(self._want(body), self.entry())}
|
|
1631
|
+
|
|
1632
|
+
def connect_apply(self, body: dict) -> dict:
|
|
1633
|
+
want, base = self._want(body), self.entry()
|
|
1634
|
+
return self.jobs.start("Connecting AI apps", "connect",
|
|
1635
|
+
lambda job: {"ok": True,
|
|
1636
|
+
"rows": targets.apply_all(want, base, job.say)})
|
|
1637
|
+
|
|
1638
|
+
def connect_path(self, body: dict) -> dict:
|
|
1639
|
+
"""Status's Claude Code Fix (status.claude_code_row): the installed Keepfold's bin folder
|
|
1640
|
+
first on the user PATH, so the `keepfold` Claude Code starts is the app's."""
|
|
1641
|
+
from keepfold import clients
|
|
1642
|
+
from keepfold.app import winpath
|
|
1643
|
+
exe = clients.installed_keepfold()
|
|
1644
|
+
if exe is None:
|
|
1645
|
+
raise ValueError("This copy of Keepfold was not installed with KeepfoldSetup.exe.")
|
|
1646
|
+
winpath.put_first(str(exe.parent))
|
|
1647
|
+
# this app's own PATH too, so Status and what it starts see the change at once
|
|
1648
|
+
os.environ["PATH"] = winpath.first(os.environ.get("PATH", ""), str(exe.parent))
|
|
1649
|
+
print("PATH: Keepfold moved first") # never the PATH itself: it may name private folders
|
|
1650
|
+
return {"ok": True, "say": "Done. Quit Claude completely and open it again, so its "
|
|
1651
|
+
f"Keepfold tools use {update.current()}."}
|
|
1652
|
+
|
|
1653
|
+
def llm_settings(self, body: dict) -> dict:
|
|
1654
|
+
from keepfold import taint
|
|
1655
|
+
|
|
1656
|
+
def merge(cfg: dict) -> dict: # under the config lock
|
|
1657
|
+
old = cfg.get("localllm")
|
|
1658
|
+
new = dict(old) if isinstance(old, dict) else {}
|
|
1659
|
+
if "enabled" in body:
|
|
1660
|
+
new["enabled"] = _bool(body, "enabled")
|
|
1661
|
+
if "model" in body:
|
|
1662
|
+
m = body["model"]
|
|
1663
|
+
if not isinstance(m, str) or not m: # never write `model: null`
|
|
1664
|
+
raise ValueError("Choose a model first.")
|
|
1665
|
+
if len(m) > 200 or not all(c.isalnum() or c in "._:@/-" for c in m):
|
|
1666
|
+
raise ValueError("not a model name")
|
|
1667
|
+
r = body.get("runner", "lmstudio") # no runner: an LM Studio choice, as before
|
|
1668
|
+
if r not in wizard.RUNNERS:
|
|
1669
|
+
raise ValueError("runner must be ollama or lmstudio")
|
|
1670
|
+
new["model"], new["runner"] = m, r
|
|
1671
|
+
if "background_model" in body: # "" or null: the main model does background work too
|
|
1672
|
+
b = body["background_model"] or ""
|
|
1673
|
+
if not isinstance(b, str) or len(b) > 200 or not all(
|
|
1674
|
+
c.isalnum() or c in "._:@/-" for c in b):
|
|
1675
|
+
raise ValueError("not a model name")
|
|
1676
|
+
if b:
|
|
1677
|
+
new["background_model"] = b
|
|
1678
|
+
else:
|
|
1679
|
+
new.pop("background_model", None)
|
|
1680
|
+
return {"localllm": new}
|
|
1681
|
+
taint.write_config(merge)
|
|
1682
|
+
return {"ok": True}
|
|
1683
|
+
|
|
1684
|
+
def llm_load(self, body: dict) -> dict:
|
|
1685
|
+
m = body.get("model")
|
|
1686
|
+
if not isinstance(m, str) or not m:
|
|
1687
|
+
raise ValueError("choose a model first")
|
|
1688
|
+
return self.jobs.start(f"Loading {m}", "llm", lambda job: actions.llm_load(job, m))
|
|
1689
|
+
|
|
1690
|
+
def llm_size(self, body: dict) -> dict:
|
|
1691
|
+
"""A model's download size, asked before the page offers to download it (one request
|
|
1692
|
+
to ollama.com for a name Setup does not list)."""
|
|
1693
|
+
n = wizard.ollama_size(body.get("name"))
|
|
1694
|
+
return {"name": body["name"], "bytes": n, "size": wizard.size_text(n),
|
|
1695
|
+
"source": "ollama.com"}
|
|
1696
|
+
|
|
1697
|
+
def llm_pull(self, body: dict) -> dict:
|
|
1698
|
+
from keepfold import localllm
|
|
1699
|
+
name = wizard.ollama_name(body.get("name"))
|
|
1700
|
+
if not localllm._local_name(status.ollama_models() or [], name) and (
|
|
1701
|
+
stop := _disk(body, wizard.models_dir("ollama"), wizard.ollama_size(name))):
|
|
1702
|
+
return stop
|
|
1703
|
+
return self.jobs.start(f"Downloading {name}", "llm",
|
|
1704
|
+
lambda job: wizard.pull_ollama(job, name), cancellable=True)
|
|
1705
|
+
|
|
1706
|
+
def llm_test(self, body: dict) -> dict:
|
|
1707
|
+
# a test may start LM Studio and load the chosen model, as `enabled: true` would
|
|
1708
|
+
return self.jobs.start("Testing the local model", "llm",
|
|
1709
|
+
lambda job: actions.llm_test(job, actions.llm_config(enabled=True)))
|
|
1710
|
+
|
|
1711
|
+
def browse_settings(self, body: dict) -> dict:
|
|
1712
|
+
"""Save `browse:`, keeping its other keys and the rest of the config. The page sends
|
|
1713
|
+
per-category lists; the legacy adult/sensitive pair is then written to match them."""
|
|
1714
|
+
from keepfold import taint
|
|
1715
|
+
from keepfold.browse import lists
|
|
1716
|
+
for key, ok in (("adult", ("skip", "private")), ("sensitive", ("private", "skip"))):
|
|
1717
|
+
if key in body and body[key] not in ok:
|
|
1718
|
+
raise ValueError(f"{key} must be {' or '.join(ok)}")
|
|
1719
|
+
if "audience" in body: # one three-way choice per category, as the two lists
|
|
1720
|
+
aud = body["audience"]
|
|
1721
|
+
if not isinstance(aud, dict) or set(aud) != set(lists.CATEGORIES) or not all(
|
|
1722
|
+
v in ("skip", "local", "cloud") for v in aud.values()):
|
|
1723
|
+
raise ValueError("audience must give every category skip, local or cloud")
|
|
1724
|
+
body = {**body, "skip_categories": [c for c, v in aud.items() if v == "skip"],
|
|
1725
|
+
"hidden_from_claude": [c for c, v in aud.items() if v == "local"]}
|
|
1726
|
+
|
|
1727
|
+
def merge(cfg: dict) -> dict: # under the config lock
|
|
1728
|
+
old = cfg.get("browse")
|
|
1729
|
+
new = {**(old if isinstance(old, dict) else {}),
|
|
1730
|
+
**{k: body[k] for k in ("adult", "sensitive") if k in body},
|
|
1731
|
+
"visible_to_claude": _bool(body, "visible_to_claude"),
|
|
1732
|
+
"deny_domains": _domains(body.get("deny", []), "deny"),
|
|
1733
|
+
"allow_domains": _domains(body.get("allow", []), "allow"),
|
|
1734
|
+
"private_domains": _domains(body.get("private", []), "private")}
|
|
1735
|
+
for key in ("hidden_from_claude", "skip_categories"):
|
|
1736
|
+
if key in body:
|
|
1737
|
+
v = body[key]
|
|
1738
|
+
if not isinstance(v, list) or not all(c in lists.CATEGORIES for c in v):
|
|
1739
|
+
raise ValueError(f"{key} must list categories from "
|
|
1740
|
+
f"{', '.join(lists.CATEGORIES)}")
|
|
1741
|
+
new[key] = [c for c in lists.CATEGORIES if c in v]
|
|
1742
|
+
if "skip_categories" in body:
|
|
1743
|
+
skip = new["skip_categories"]
|
|
1744
|
+
new["adult"] = "skip" if "adult" in skip else "private"
|
|
1745
|
+
new["sensitive"] = "skip" if all(c in skip for c in lists.CATEGORIES
|
|
1746
|
+
if c != "adult") else "private"
|
|
1747
|
+
if "private_mcp" in body:
|
|
1748
|
+
new["private_mcp"] = _bool(body, "private_mcp")
|
|
1749
|
+
if "hidden_from_claude" in body: # C9: stored as the cloud allowlist; new stay local
|
|
1750
|
+
hidden = new.pop("hidden_from_claude")
|
|
1751
|
+
new["cloud_categories"] = [c for c in lists.CATEGORIES if c not in hidden]
|
|
1752
|
+
return {"browse": new}
|
|
1753
|
+
taint.write_config(merge)
|
|
1754
|
+
return {"ok": True}
|
|
1755
|
+
|
|
1756
|
+
def cloud(self, body: dict) -> dict:
|
|
1757
|
+
"""Save the cloud model: `browse.cloud_processing` and `cloudllm` (other keys kept).
|
|
1758
|
+
Never a key: only the name of the variable that holds it. Empty fields are removed."""
|
|
1759
|
+
from keepfold import cloudllm, taint
|
|
1760
|
+
from keepfold.vault import secret_pattern
|
|
1761
|
+
if extra := set(body) - set(CLOUD_FIELDS):
|
|
1762
|
+
raise ValueError(f"unknown field {sorted(extra)[0]!r}: the key itself is never "
|
|
1763
|
+
"sent here, only the name of the variable that holds it")
|
|
1764
|
+
on = _bool(body, "cloud_processing")
|
|
1765
|
+
got = {k: body.get(k) or None for k in CLOUD_FIELDS[1:]}
|
|
1766
|
+
if not all(v is None or (isinstance(v, str) and len(v) <= 300) for v in got.values()):
|
|
1767
|
+
raise ValueError("provider, model, base_url and api_key_env must be text")
|
|
1768
|
+
if got["provider"] is not None and got["provider"] not in (*cloudllm.PRESETS, "custom"):
|
|
1769
|
+
raise ValueError(f"provider must be one of {', '.join(cloudllm.PRESETS)} or custom")
|
|
1770
|
+
m = got["model"]
|
|
1771
|
+
if m is not None and not all(c.isalnum() or c in "._:@/-" for c in m):
|
|
1772
|
+
raise ValueError("not a model name")
|
|
1773
|
+
if got["provider"] != "custom":
|
|
1774
|
+
got["base_url"] = None # a preset's base is its own
|
|
1775
|
+
elif got["base_url"] is not None:
|
|
1776
|
+
cloudllm._check(got["base_url"]) # https with a host, or ValueError
|
|
1777
|
+
env = got["api_key_env"]
|
|
1778
|
+
if env is not None:
|
|
1779
|
+
cloudllm.check_env_name(env)
|
|
1780
|
+
if secret_pattern(env):
|
|
1781
|
+
raise ValueError("api_key_env is the NAME of an environment variable, such as "
|
|
1782
|
+
"OPENAI_API_KEY; never paste the key here")
|
|
1783
|
+
need = {"provider": "a provider", "model": "a model", "api_key_env": "the variable name"}
|
|
1784
|
+
if got["provider"] == "custom":
|
|
1785
|
+
need["base_url"] = "the Base URL"
|
|
1786
|
+
if on and (gap := [w for k, w in need.items() if got[k] is None]):
|
|
1787
|
+
raise ValueError(f"To turn the cloud model on, fill in {' and '.join(gap)} first.")
|
|
1788
|
+
|
|
1789
|
+
def merge(old: dict) -> dict: # under the config lock
|
|
1790
|
+
c = old.get("cloudllm") if isinstance(old.get("cloudllm"), dict) else {}
|
|
1791
|
+
c = {k: v for k, v in c.items() if k not in CLOUD_FIELDS}
|
|
1792
|
+
b = old.get("browse") if isinstance(old.get("browse"), dict) else {}
|
|
1793
|
+
return {"cloudllm": {**c, **{k: v for k, v in got.items() if v is not None}},
|
|
1794
|
+
"browse": {**b, "cloud_processing": on}}
|
|
1795
|
+
taint.write_config(merge)
|
|
1796
|
+
return {"ok": True}
|
|
1797
|
+
|
|
1798
|
+
def auto_settings(self, body: dict) -> dict:
|
|
1799
|
+
"""Save `browse.auto_import_hours` (0-168; 0 = off), the other browse keys kept."""
|
|
1800
|
+
from keepfold import taint
|
|
1801
|
+
h = body.get("hours")
|
|
1802
|
+
if not (isinstance(h, (int, float)) and not isinstance(h, bool) and 0 <= h <= 168):
|
|
1803
|
+
raise ValueError("hours must be a number from 0 (off) to 168")
|
|
1804
|
+
taint.write_config(lambda cfg: {"browse": {
|
|
1805
|
+
**(cfg["browse"] if isinstance(cfg.get("browse"), dict) else {}),
|
|
1806
|
+
"auto_import_hours": int(h) if h == int(h) else h}})
|
|
1807
|
+
return {"ok": True}
|
|
1808
|
+
|
|
1809
|
+
def auto_import(self) -> dict | None:
|
|
1810
|
+
"""The live import, every AUTO_EVERY_S (browse.auto_import_hours 0 turns it off): only
|
|
1811
|
+
the new visits of the browsers and profiles imported before, quietly (no job: it takes
|
|
1812
|
+
seconds), when no job runs and the browse-wide lock is free; never before the user's
|
|
1813
|
+
first import. The site pages first move into the store (`store.migrate`), as a job
|
|
1814
|
+
with its steps when there are pages to move. {"live": counts}, {"job": ...}, or None
|
|
1815
|
+
when it did not run."""
|
|
1816
|
+
from keepfold import browse_serve
|
|
1817
|
+
from keepfold.browse import load_settings, store
|
|
1818
|
+
from keepfold.vault import Vault
|
|
1819
|
+
if not self.entry() or self.jobs.running():
|
|
1820
|
+
return None
|
|
1821
|
+
if not status.embedding()["downloaded"]: # every page would land under Other: wait
|
|
1822
|
+
return None # for the search model
|
|
1823
|
+
root = self.root
|
|
1824
|
+
v = Vault(root)
|
|
1825
|
+
if not browse_serve.auto_import_due(v, live=True):
|
|
1826
|
+
return None
|
|
1827
|
+
srcs = browse_serve.auto_sources(v) # never an unticked one
|
|
1828
|
+
if not srcs:
|
|
1829
|
+
return None
|
|
1830
|
+
if not store.migrated(v):
|
|
1831
|
+
if store._site_page_files(v):
|
|
1832
|
+
try:
|
|
1833
|
+
return self.jobs.start("Moving site pages into Keepfold", "browse",
|
|
1834
|
+
lambda job: actions.browse_migrate(job, root),
|
|
1835
|
+
quiet_errors=True)
|
|
1836
|
+
except Busy:
|
|
1837
|
+
return None
|
|
1838
|
+
store.migrate(v, settings=load_settings()) # no page to move: only marks it done
|
|
1839
|
+
return {"live": status.safe(browse_serve.run_import(v, srcs=srcs,
|
|
1840
|
+
say=lambda s: None))}
|
|
1841
|
+
|
|
1842
|
+
def chat_import_auto(self) -> dict | None:
|
|
1843
|
+
"""Start a chat import job (chat_import.run) when the setting is on, a vault is set up,
|
|
1844
|
+
no job runs and a transcript is new or changed (stats only); None when it did not."""
|
|
1845
|
+
from keepfold import chat_import, taint
|
|
1846
|
+
from keepfold.vault import Vault
|
|
1847
|
+
if self.entry() and (err := taint.config_error()): # fail closed: it may turn it off
|
|
1848
|
+
self.echo(f"keepfold app: chat import skipped: {err}")
|
|
1849
|
+
return None
|
|
1850
|
+
if not chat_import.enabled() or not self.entry() or self.jobs.running():
|
|
1851
|
+
return None
|
|
1852
|
+
root = self.root
|
|
1853
|
+
if not chat_import.pending(Vault(root)):
|
|
1854
|
+
return None
|
|
1855
|
+
try:
|
|
1856
|
+
return self.jobs.start("Chat import", "status",
|
|
1857
|
+
lambda job: actions.chat_import(job, root),
|
|
1858
|
+
cancellable=True, quiet_errors=True)
|
|
1859
|
+
except Busy: # a job started meanwhile: the next pass tries again
|
|
1860
|
+
return None
|
|
1861
|
+
|
|
1862
|
+
def safety_net_auto(self) -> dict | None:
|
|
1863
|
+
"""One safety_net pass over the chat pages earlier imports wrote, in this thread, when
|
|
1864
|
+
the chat import is on, a vault is set up and no job runs; committed like an import.
|
|
1865
|
+
Its counts, or None when it did not run."""
|
|
1866
|
+
from keepfold import chat_import, safety_net
|
|
1867
|
+
from keepfold.vault import Vault
|
|
1868
|
+
if not chat_import.enabled() or not self.entry() or self.jobs.running():
|
|
1869
|
+
return None
|
|
1870
|
+
v = Vault(self.root)
|
|
1871
|
+
if not safety_net.pending(v): # stats only: no model probe when nothing changed
|
|
1872
|
+
return None
|
|
1873
|
+
runner, embed = safety_net.background_tools()
|
|
1874
|
+
try:
|
|
1875
|
+
return safety_net.run(v, runner, embed)
|
|
1876
|
+
finally:
|
|
1877
|
+
actions._commit(v, "safety net")
|
|
1878
|
+
|
|
1879
|
+
def chat_import_set(self, body: dict) -> dict:
|
|
1880
|
+
"""Turn the automatic chat import on or off (`app.chat_import`)."""
|
|
1881
|
+
from keepfold import chat_import
|
|
1882
|
+
from keepfold.app import desktop
|
|
1883
|
+
on = _bool(body, "enabled")
|
|
1884
|
+
desktop._merge_app(lambda a: {**a, "chat_import": on})
|
|
1885
|
+
return {"enabled": chat_import.enabled()}
|
|
1886
|
+
|
|
1887
|
+
def update_check_set(self, body: dict) -> dict:
|
|
1888
|
+
"""Turn the quiet update check on or off (`app.update_check`)."""
|
|
1889
|
+
from keepfold.app import desktop
|
|
1890
|
+
if set(body) != {"enabled"}:
|
|
1891
|
+
raise ValueError("send {\"enabled\": true or false}")
|
|
1892
|
+
on = _bool(body, "enabled")
|
|
1893
|
+
desktop._merge_app(lambda a: {**a, "update_check": on})
|
|
1894
|
+
return {"enabled": desktop.update_check()}
|
|
1895
|
+
|
|
1896
|
+
def welcome(self) -> dict:
|
|
1897
|
+
"""The welcome guide's quick look as the page opens, without Setup's slower probes:
|
|
1898
|
+
finished or skipped before, and whether a vault is set up."""
|
|
1899
|
+
from keepfold.app import desktop
|
|
1900
|
+
return {"welcome_done": desktop._app_cfg().get("welcome_done") is True,
|
|
1901
|
+
"vault": self.root is not None and (self.root / ".keepfold").is_dir()}
|
|
1902
|
+
|
|
1903
|
+
def welcome_set(self, body: dict) -> dict:
|
|
1904
|
+
"""The welcome guide was finished or skipped (`app.welcome_done`); it never opens by
|
|
1905
|
+
itself again. Like first_run_hidden, only true is accepted."""
|
|
1906
|
+
from keepfold.app import desktop
|
|
1907
|
+
if body != {"welcome_done": True}:
|
|
1908
|
+
raise ValueError("welcome_done can only be true")
|
|
1909
|
+
desktop._merge_app(lambda a: {**a, "welcome_done": True})
|
|
1910
|
+
return {"welcome_done": True}
|
|
1911
|
+
|
|
1912
|
+
def chat_begin(self, body: dict) -> tuple:
|
|
1913
|
+
"""Check a chat turn and take the one chat slot: (vault, id or None, text). Busy while
|
|
1914
|
+
another answer streams; ValueError on a bad body."""
|
|
1915
|
+
from keepfold import chat
|
|
1916
|
+
cid, text = body.get("id"), body.get("text")
|
|
1917
|
+
if not isinstance(text, str) or not text.strip() or len(text) > chat.MAX_TEXT:
|
|
1918
|
+
raise ValueError(f"Type a message (up to {chat.MAX_TEXT:,} characters).")
|
|
1919
|
+
vault = self._vault()
|
|
1920
|
+
if cid is not None:
|
|
1921
|
+
chat._path(vault, cid) # a ULID or ValueError: never a path
|
|
1922
|
+
if not self.chatting.acquire(blocking=False):
|
|
1923
|
+
raise Busy("An answer is still being written; wait for it or press Stop.")
|
|
1924
|
+
return vault, cid, text
|
|
1925
|
+
|
|
1926
|
+
def piggyback(self) -> threading.Thread | None:
|
|
1927
|
+
"""C8: after a Chat turn ends, a daemon thread waits fact_harvest.PIGGY_WAIT_S and then
|
|
1928
|
+
runs fact_harvest.after_chat, unless the app is quitting or a new Chat turn started
|
|
1929
|
+
meanwhile. At most one at a time (`piggy`); it never holds `chatting`. The thread, or
|
|
1930
|
+
None when one already runs."""
|
|
1931
|
+
if not PIGGYBACK or not self.piggy.acquire(blocking=False):
|
|
1932
|
+
return None
|
|
1933
|
+
|
|
1934
|
+
def go():
|
|
1935
|
+
from keepfold import fact_harvest
|
|
1936
|
+
try:
|
|
1937
|
+
if self.stop.wait(fact_harvest.PIGGY_WAIT_S) or self.chatting.locked():
|
|
1938
|
+
return # quitting, or the owner asked again: that turn's end tries again
|
|
1939
|
+
c = fact_harvest.after_chat(self)
|
|
1940
|
+
if c: # counts only: never a page's text
|
|
1941
|
+
self.echo("keepfold app: facts from chats after a Chat turn: " + ", ".join(
|
|
1942
|
+
f"{k} {n}" for k, n in sorted(c.items()) if k != "session"))
|
|
1943
|
+
except Exception as e: # noqa: BLE001 (the next turn or chats pass tries again)
|
|
1944
|
+
self.echo(f"keepfold app: saving facts after a Chat turn failed "
|
|
1945
|
+
f"({type(e).__name__})")
|
|
1946
|
+
finally:
|
|
1947
|
+
self.piggy.release()
|
|
1948
|
+
|
|
1949
|
+
t = threading.Thread(target=go, daemon=True, name="fact-piggyback")
|
|
1950
|
+
try:
|
|
1951
|
+
t.start()
|
|
1952
|
+
except RuntimeError: # no thread to spare: never keep `piggy` held
|
|
1953
|
+
self.piggy.release()
|
|
1954
|
+
return None
|
|
1955
|
+
return t
|
|
1956
|
+
|
|
1957
|
+
def chat_delete(self, body: dict) -> dict:
|
|
1958
|
+
from keepfold import chat
|
|
1959
|
+
if self.chatting.locked(): # the answer's final save would bring the chat back
|
|
1960
|
+
raise Busy("An answer is still being written; press Stop first, then delete.")
|
|
1961
|
+
if body.get("all") is True:
|
|
1962
|
+
self.files.clear() # the chats are cleared: their attached files go too
|
|
1963
|
+
return {"deleted": chat.delete_all(self._vault())}
|
|
1964
|
+
return {"deleted": int(chat.delete(self._vault(), body.get("id")))}
|
|
1965
|
+
|
|
1966
|
+
def chat_settings(self, body: dict) -> dict:
|
|
1967
|
+
from keepfold import chat
|
|
1968
|
+
return chat.save_settings(body)
|
|
1969
|
+
|
|
1970
|
+
# ---- C1: a file attached in Chat, kept in memory only (keepfold.askfile) ----
|
|
1971
|
+
def chat_attach(self, body: dict) -> dict:
|
|
1972
|
+
"""Read the file an upload brought (`body.upload`, named `body.name` by the page) into
|
|
1973
|
+
the attached files: parsed in the child, chunked and embedded in memory. The uploaded
|
|
1974
|
+
copy is deleted at once, read or not."""
|
|
1975
|
+
from keepfold import askfile
|
|
1976
|
+
uid = body.get("upload")
|
|
1977
|
+
p = self.uploads.pop(uid, None) if isinstance(uid, str) else None
|
|
1978
|
+
if p is None:
|
|
1979
|
+
raise ValueError("That file is gone; attach it again.")
|
|
1980
|
+
try:
|
|
1981
|
+
name = askfile.safe_name(body.get("name"))
|
|
1982
|
+
if not name.lower().endswith(p.suffix.lower()): # the upload's checked extension
|
|
1983
|
+
name += p.suffix
|
|
1984
|
+
f = askfile.read(p, name)
|
|
1985
|
+
finally:
|
|
1986
|
+
p.unlink(missing_ok=True)
|
|
1987
|
+
return self.files.add(f).info()
|
|
1988
|
+
|
|
1989
|
+
def chat_file_remove(self, body: dict) -> dict:
|
|
1990
|
+
if body.get("all") is True:
|
|
1991
|
+
self.files.clear()
|
|
1992
|
+
else:
|
|
1993
|
+
self.files.remove(body.get("id"))
|
|
1994
|
+
return {"files": self.files.list()}
|
|
1995
|
+
|
|
1996
|
+
def chat_file_save(self, body: dict) -> dict:
|
|
1997
|
+
"""Save to your brain: the attached file through the documents import (askfile.save),
|
|
1998
|
+
committed as other imports are; {saved: {title, path}, files}."""
|
|
1999
|
+
from keepfold import askfile
|
|
2000
|
+
from keepfold.vault import Vault
|
|
2001
|
+
got = self.files.get([body.get("id")])
|
|
2002
|
+
if not got:
|
|
2003
|
+
raise ValueError("That file is no longer attached; attach it again.")
|
|
2004
|
+
v = Vault(self.need_root())
|
|
2005
|
+
saved = askfile.save(v, got[0])
|
|
2006
|
+
actions._commit(v, "docs")
|
|
2007
|
+
return {"saved": saved, "files": self.files.list()}
|
|
2008
|
+
|
|
2009
|
+
def chat_eval(self, body: dict) -> dict:
|
|
2010
|
+
"""Run Chat's offline test (keepfold.chat_eval) as a job: a made-up vault in a temp
|
|
2011
|
+
folder, never the owner's; the result is the score, blockers and failures."""
|
|
2012
|
+
from keepfold import chat_eval
|
|
2013
|
+
|
|
2014
|
+
def run(job):
|
|
2015
|
+
r = chat_eval.run(cancel=job.cancelled, progress=lambda d, n, qid: job.progress(
|
|
2016
|
+
1, 1, d, n, f"Question {qid}"))
|
|
2017
|
+
return {"kind": "chat_eval", "passed": r["passed"], "ran": r["ran"],
|
|
2018
|
+
"result": r["result"], "manifest": r["manifest"][:12],
|
|
2019
|
+
"queries": {k: v["rate"] for k, v in r["queries"].items()},
|
|
2020
|
+
"misses": {k: len(v) for k, v in r["misses"].items()},
|
|
2021
|
+
"blocked": r["blocked"], "total": r["total"], "bar": r["pass_bar"],
|
|
2022
|
+
"model": r["model"], "model_note": r["model_note"], "stopped": r["stopped"],
|
|
2023
|
+
"blockers": [{k: b[k] for k in ("name", "state")} for b in r["blockers"]],
|
|
2024
|
+
"failures": [{"id": q["id"], "question": q["question"],
|
|
2025
|
+
"why": "; ".join(q["why"]), "answer": q["answer"][:300]}
|
|
2026
|
+
for q in r["questions"] if q["status"] == "fail"],
|
|
2027
|
+
"recall": r["retrieval"]["recall"], "median_s": r["latency"]["median"]}
|
|
2028
|
+
return self.jobs.start("Running the Chat test", "chat", run, cancellable=True)
|
|
2029
|
+
|
|
2030
|
+
def login(self, body: dict) -> dict:
|
|
2031
|
+
on, root = _bool(body, "on"), self.need_root()
|
|
2032
|
+
return self.jobs.start("Start at login" if on else "Removing start at login", "browse",
|
|
2033
|
+
lambda job: actions.login(job, root, on))
|
|
2034
|
+
|
|
2035
|
+
def process(self, body: dict) -> dict:
|
|
2036
|
+
root = self.need_root()
|
|
2037
|
+
return self.jobs.start("Processing browsing", "browse",
|
|
2038
|
+
lambda job: actions.browse_process(job, root), quiet_errors=True)
|
|
2039
|
+
|
|
2040
|
+
def selftest(self, body: dict) -> dict:
|
|
2041
|
+
return self.jobs.start("Browse self-test", "browse", actions.browse_selftest,
|
|
2042
|
+
quiet_errors=True)
|
|
2043
|
+
|
|
2044
|
+
def _section(self, body: dict) -> str:
|
|
2045
|
+
return "setup" if body.get("from") == "setup" else "browse"
|
|
2046
|
+
|
|
2047
|
+
def scan(self, body: dict) -> dict:
|
|
2048
|
+
def run(job):
|
|
2049
|
+
out = actions.browse_scan(job)
|
|
2050
|
+
self.scanned = {r["source"]: r for r in out["rows"]}
|
|
2051
|
+
return out
|
|
2052
|
+
return self.jobs.start("Counting browser history", self._section(body), run,
|
|
2053
|
+
quiet_errors=True)
|
|
2054
|
+
|
|
2055
|
+
def history_import(self, body: dict) -> dict:
|
|
2056
|
+
root, keys = self.need_root(), body.get("sources")
|
|
2057
|
+
if not isinstance(keys, list) or not keys or not all(isinstance(k, str) for k in keys):
|
|
2058
|
+
raise ValueError("Tick at least one browser.")
|
|
2059
|
+
if "skip" in body: # only the tick list sends it; Status's button must not clear it
|
|
2060
|
+
skip = body["skip"]
|
|
2061
|
+
if not isinstance(skip, list) or not all(isinstance(k, str) for k in skip):
|
|
2062
|
+
raise ValueError("skip must list profile keys")
|
|
2063
|
+
self._skip_profiles(skip, keys)
|
|
2064
|
+
return self.jobs.start("Importing past history", self._section(body),
|
|
2065
|
+
lambda job: actions.history_import(job, root, set(keys)),
|
|
2066
|
+
cancellable=True, quiet_errors=True)
|
|
2067
|
+
|
|
2068
|
+
@staticmethod
|
|
2069
|
+
def _skip_profiles(skip: list, ticked: list) -> None:
|
|
2070
|
+
"""Keep `browse.skip_profiles` as the user's last ticks: the unticked keys added, the
|
|
2071
|
+
ticked ones removed; the automatic imports (`sources.chosen`) leave those out."""
|
|
2072
|
+
from keepfold import taint
|
|
2073
|
+
|
|
2074
|
+
def merge(cfg: dict) -> dict: # under the config lock; unchanged: no write
|
|
2075
|
+
old = cfg.get("browse")
|
|
2076
|
+
old = old if isinstance(old, dict) else {}
|
|
2077
|
+
had = old.get("skip_profiles")
|
|
2078
|
+
had = [k for k in had if isinstance(k, str)] if isinstance(had, list) else []
|
|
2079
|
+
new = sorted((set(had) | set(skip)) - set(ticked))
|
|
2080
|
+
return {"browse": {**old, "skip_profiles": new}} if new != sorted(had) else {}
|
|
2081
|
+
taint.write_config(merge)
|
|
2082
|
+
|
|
2083
|
+
def snapshot(self) -> bytes:
|
|
2084
|
+
"""The self-contained snapshot page (dashboard.snapshot: CSP default-src 'none', no
|
|
2085
|
+
private item)."""
|
|
2086
|
+
from datetime import UTC, datetime
|
|
2087
|
+
|
|
2088
|
+
from keepfold import dashboard
|
|
2089
|
+
return dashboard.snapshot(self._vault(), now=datetime.now(UTC)).encode()
|
|
2090
|
+
|
|
2091
|
+
def export(self, body: dict) -> dict:
|
|
2092
|
+
"""Export snapshot. The desktop app asks where to save it (a save dialog) and writes it
|
|
2093
|
+
as a job; the browser downloads it from GET /api/vault/snapshot."""
|
|
2094
|
+
self.need_root()
|
|
2095
|
+
win = self.desktop.win if self.desktop is not None else None
|
|
2096
|
+
if win is None:
|
|
2097
|
+
return {"download": "/api/vault/snapshot"}
|
|
2098
|
+
import webview
|
|
2099
|
+
got = win.create_file_dialog(webview.FileDialog.SAVE, save_filename=snapshot_name(),
|
|
2100
|
+
file_types=("Web page (*.html)",))
|
|
2101
|
+
if not got:
|
|
2102
|
+
return {"cancelled": True}
|
|
2103
|
+
dest = Path(got if isinstance(got, str) else got[0])
|
|
2104
|
+
|
|
2105
|
+
def run(job):
|
|
2106
|
+
job.say("building the snapshot")
|
|
2107
|
+
dest.write_bytes(self.snapshot()) # the owner's chosen file, outside the vault
|
|
2108
|
+
return {"ok": True, "path": str(dest)}
|
|
2109
|
+
return self.jobs.start("Exporting a snapshot", "vault", run)
|
|
2110
|
+
|
|
2111
|
+
def brain_picture(self, body: dict) -> dict:
|
|
2112
|
+
"""Save picture: the brain page's PNG (`png`, base64; `day`, the page's day, names it).
|
|
2113
|
+
The desktop app asks where to save it (Downloads first) and writes it there; the browser
|
|
2114
|
+
app answers `download` and the page saves it itself. Never written anywhere else."""
|
|
2115
|
+
import base64
|
|
2116
|
+
import binascii
|
|
2117
|
+
bad = ValueError("That picture could not be saved.")
|
|
2118
|
+
b64 = body.get("png")
|
|
2119
|
+
if not isinstance(b64, str) or len(b64) > (PICTURE_MAX + 2) // 3 * 4:
|
|
2120
|
+
raise bad
|
|
2121
|
+
try:
|
|
2122
|
+
png = base64.b64decode(b64, validate=True)
|
|
2123
|
+
except (binascii.Error, ValueError):
|
|
2124
|
+
raise bad from None
|
|
2125
|
+
if not png.startswith(b"\x89PNG\r\n\x1a\n") or len(png) > PICTURE_MAX:
|
|
2126
|
+
raise bad
|
|
2127
|
+
win = self.desktop.win if self.desktop is not None else None
|
|
2128
|
+
if win is None:
|
|
2129
|
+
return {"download": True}
|
|
2130
|
+
day = body.get("day")
|
|
2131
|
+
if not (isinstance(day, str) and re.fullmatch(r"\d{4}-\d{2}-\d{2}", day)):
|
|
2132
|
+
day = time.strftime("%Y-%m-%d")
|
|
2133
|
+
import webview
|
|
2134
|
+
got = win.create_file_dialog(webview.FileDialog.SAVE, directory=str(exports.downloads()),
|
|
2135
|
+
save_filename=f"keepfold-brain-{day}.png",
|
|
2136
|
+
file_types=("PNG picture (*.png)",))
|
|
2137
|
+
if not got:
|
|
2138
|
+
return {"cancelled": True}
|
|
2139
|
+
dest = Path(got if isinstance(got, str) else got[0])
|
|
2140
|
+
try:
|
|
2141
|
+
dest.write_bytes(png) # the owner's chosen file, outside the vault
|
|
2142
|
+
except OSError: # a read-only folder, a full disk
|
|
2143
|
+
raise bad from None
|
|
2144
|
+
return {"saved": dest.name}
|
|
2145
|
+
|
|
2146
|
+
def backup(self, body: dict) -> dict:
|
|
2147
|
+
root = self.need_root()
|
|
2148
|
+
return self.jobs.start("Backing up the vault", "vault",
|
|
2149
|
+
lambda job: actions.backup(job, root))
|
|
2150
|
+
|
|
2151
|
+
def git_settings(self, body: dict) -> dict:
|
|
2152
|
+
"""Save `git:` (enabled, private_browsing), keeping its other keys, then apply the
|
|
2153
|
+
private-browsing choice to the vault's .gitignore (and index) now, not at the next
|
|
2154
|
+
browse import."""
|
|
2155
|
+
from keepfold import taint
|
|
2156
|
+
from keepfold.browse import forget
|
|
2157
|
+
new = {"enabled": _bool(body, "enabled"),
|
|
2158
|
+
"private_browsing": _bool(body, "private_browsing")}
|
|
2159
|
+
taint.write_config(lambda cfg: {"git": {
|
|
2160
|
+
**(cfg["git"] if isinstance(cfg.get("git"), dict) else {}), **new}})
|
|
2161
|
+
if self.entry() is not None:
|
|
2162
|
+
forget.sync_private(self._vault())
|
|
2163
|
+
return {"ok": True}
|
|
2164
|
+
|
|
2165
|
+
def doctor(self, body: dict) -> dict:
|
|
2166
|
+
root = self.root
|
|
2167
|
+
return self.jobs.start("Running the doctor", "vault",
|
|
2168
|
+
lambda job: actions.doctor(job, root))
|
|
2169
|
+
|
|
2170
|
+
def open(self, body: dict) -> dict:
|
|
2171
|
+
what = body.get("what")
|
|
2172
|
+
if what == "page": # a source of an answer: a Markdown page inside the vault
|
|
2173
|
+
root, rel = self.need_root(), body.get("path")
|
|
2174
|
+
p = (root / rel).resolve() if isinstance(rel, str) and rel else None
|
|
2175
|
+
if p is None or Path(rel).is_absolute() or not p.is_relative_to(root) \
|
|
2176
|
+
or p.suffix != ".md" or not p.is_file() \
|
|
2177
|
+
or p.relative_to(root).parts[0].startswith("."):
|
|
2178
|
+
raise ValueError("not a page in this vault")
|
|
2179
|
+
return _open_note(p)
|
|
2180
|
+
if what == "skill_zip":
|
|
2181
|
+
p = _checkout() / "dist"
|
|
2182
|
+
if not p.is_dir():
|
|
2183
|
+
raise ValueError(f"{p} is not there; build it first.")
|
|
2184
|
+
_open_path(p)
|
|
2185
|
+
return {"ok": True}
|
|
2186
|
+
root = self.need_root()
|
|
2187
|
+
if what in ("vault", "private"):
|
|
2188
|
+
from keepfold.vault import PRIVATE_BROWSE_DIR
|
|
2189
|
+
p = root / PRIVATE_BROWSE_DIR / "browse-private-index.md" if what == "private" \
|
|
2190
|
+
else root
|
|
2191
|
+
if what == "private" and not p.is_file():
|
|
2192
|
+
p = p.parent
|
|
2193
|
+
if not p.is_dir():
|
|
2194
|
+
raise ValueError("There are no private browse pages yet.")
|
|
2195
|
+
return _open_note(p)
|
|
2196
|
+
elif what == "folder": # the plain folder, in Explorer or Finder
|
|
2197
|
+
_open_path(root)
|
|
2198
|
+
else:
|
|
2199
|
+
raise ValueError("unknown thing to open")
|
|
2200
|
+
return {"ok": True}
|
|
2201
|
+
|
|
2202
|
+
def setup_skip(self, body: dict) -> dict:
|
|
2203
|
+
"""Skip the Connect step (Status becomes the landing page), or un-skip it."""
|
|
2204
|
+
from keepfold import taint
|
|
2205
|
+
skip = _bool(body, "skipped")
|
|
2206
|
+
|
|
2207
|
+
def merge(cfg: dict) -> dict: # under the config lock
|
|
2208
|
+
app = cfg.get("app")
|
|
2209
|
+
app = {k: v for k, v in app.items() if k != "connect_skipped"} \
|
|
2210
|
+
if isinstance(app, dict) else {}
|
|
2211
|
+
return {"app": {**app, "connect_skipped": True} if skip else app}
|
|
2212
|
+
taint.write_config(merge)
|
|
2213
|
+
return {"ok": True}
|
|
2214
|
+
|
|
2215
|
+
def setup_vault(self, body: dict) -> dict:
|
|
2216
|
+
path = body.get("path")
|
|
2217
|
+
wizard.vault_path(path) # a refused folder: one plain message (400), no failed job
|
|
2218
|
+
|
|
2219
|
+
def run(job):
|
|
2220
|
+
old = self.root
|
|
2221
|
+
root, out = wizard.make_vault(job, path)
|
|
2222
|
+
self.root = root
|
|
2223
|
+
if old is None or Path(old).resolve() == root:
|
|
2224
|
+
return out
|
|
2225
|
+
# FX1 6: the vault moved. Start at login is Keepfold's own: it follows at once, but
|
|
2226
|
+
# only the entry this Keepfold made for the old folder (never another install's).
|
|
2227
|
+
# AI apps' configs are the owner's: Connect re-points them after a confirm.
|
|
2228
|
+
if status.login_is_for(Path(old)):
|
|
2229
|
+
try:
|
|
2230
|
+
actions.login(job, root, True)
|
|
2231
|
+
out["lines"].append("Start at login now uses the new folder.")
|
|
2232
|
+
except Exception as e: # noqa: BLE001 (the vault itself is set up)
|
|
2233
|
+
out["lines"].append(f"Start at login still uses the old folder: {e}")
|
|
2234
|
+
if any(t.get("stale") for t in targets.describe(self.entry())):
|
|
2235
|
+
out["reconnect"] = True
|
|
2236
|
+
return out
|
|
2237
|
+
return self.jobs.start("Setting up the vault", "setup", run)
|
|
2238
|
+
|
|
2239
|
+
def setup_embed(self, body: dict) -> dict:
|
|
2240
|
+
root = self.entry() and self.root
|
|
2241
|
+
|
|
2242
|
+
def run(job): # a successful download goes straight on to indexing the notes
|
|
2243
|
+
out = wizard.embed(job, root)
|
|
2244
|
+
if not out["ok"] or not root or job.cancelled.is_set():
|
|
2245
|
+
return out
|
|
2246
|
+
job.say("downloaded; now indexing your notes")
|
|
2247
|
+
idx = wizard.index(job, root)
|
|
2248
|
+
return {**idx, "lines": [*out["lines"][-5:], *idx["lines"]]}
|
|
2249
|
+
return self.jobs.start("Downloading the search model", "setup", run, cancellable=True)
|
|
2250
|
+
|
|
2251
|
+
def setup_voice(self, body: dict) -> dict:
|
|
2252
|
+
return self.jobs.start("Installing the speech model", "setup", wizard.voice,
|
|
2253
|
+
cancellable=True)
|
|
2254
|
+
|
|
2255
|
+
def setup_index(self, body: dict) -> dict:
|
|
2256
|
+
root = self.need_root()
|
|
2257
|
+
return self.jobs.start("Indexing your notes", "setup",
|
|
2258
|
+
lambda job: wizard.index(job, root), cancellable=True)
|
|
2259
|
+
|
|
2260
|
+
def setup_install(self, body: dict) -> dict:
|
|
2261
|
+
if stop := _disk(body, wizard.install_dir(), wizard.OLLAMA_BYTES):
|
|
2262
|
+
return stop
|
|
2263
|
+
return self.jobs.start("Installing Ollama", "setup", wizard.install_ollama,
|
|
2264
|
+
cancellable=True)
|
|
2265
|
+
|
|
2266
|
+
def setup_git(self, body: dict) -> dict:
|
|
2267
|
+
"""winget's Git for this Windows account; scope "machine" only when the owner chose
|
|
2268
|
+
it after that failed. `from` "status": the result shows on Status."""
|
|
2269
|
+
scope = "machine" if body.get("scope") == "machine" else "user"
|
|
2270
|
+
if stop := _disk(body, wizard.install_dir(), wizard.GIT_BYTES):
|
|
2271
|
+
return stop
|
|
2272
|
+
root = self.root
|
|
2273
|
+
return self.jobs.start("Installing Git", "status" if body.get("from") == "status"
|
|
2274
|
+
else "setup", lambda job: wizard.install_git(job, scope, root),
|
|
2275
|
+
cancellable=True)
|
|
2276
|
+
|
|
2277
|
+
def _model_runner(self, body: dict) -> tuple[str, str]:
|
|
2278
|
+
m, r = body.get("model"), body.get("runner")
|
|
2279
|
+
wizard.model(m if isinstance(m, str) else "")
|
|
2280
|
+
if r not in ("ollama", "lmstudio"):
|
|
2281
|
+
raise ValueError("runner must be ollama or lmstudio")
|
|
2282
|
+
return m, r
|
|
2283
|
+
|
|
2284
|
+
@staticmethod
|
|
2285
|
+
def _model_disk(body: dict, m: str, r: str) -> dict | None:
|
|
2286
|
+
"""The free-space refusal for a Setup model this runner does not hold yet."""
|
|
2287
|
+
have = wizard._have(wizard.model(m), status.ollama_models(),
|
|
2288
|
+
status.lms_models() if r == "lmstudio" else [])[r]
|
|
2289
|
+
return None if have else _disk(body, wizard.models_dir(r), wizard.model(m)["bytes"])
|
|
2290
|
+
|
|
2291
|
+
def setup_pull(self, body: dict) -> dict:
|
|
2292
|
+
m, r = self._model_runner(body)
|
|
2293
|
+
if stop := self._model_disk(body, m, r):
|
|
2294
|
+
return stop
|
|
2295
|
+
return self.jobs.start(f"Downloading {wizard.model(m)['label']}", "setup",
|
|
2296
|
+
lambda job: wizard.pull(job, m, r), cancellable=True)
|
|
2297
|
+
|
|
2298
|
+
def setup_test(self, body: dict) -> dict:
|
|
2299
|
+
m, r = self._model_runner(body)
|
|
2300
|
+
return self.jobs.start(f"Testing {wizard.model(m)['label']}", "setup",
|
|
2301
|
+
lambda job: wizard.test_and_save(job, m, r))
|
|
2302
|
+
|
|
2303
|
+
def setup_start(self, body: dict) -> dict:
|
|
2304
|
+
r = body.get("runner")
|
|
2305
|
+
if r not in ("ollama", "lmstudio"):
|
|
2306
|
+
raise ValueError("runner must be ollama or lmstudio")
|
|
2307
|
+
name = "Ollama" if r == "ollama" else "LM Studio"
|
|
2308
|
+
return self.jobs.start(f"Starting {name}", "setup", lambda job: wizard.start(r))
|
|
2309
|
+
|
|
2310
|
+
def setup_model(self, body: dict) -> dict:
|
|
2311
|
+
"""One click: download the model, then test it and turn it on."""
|
|
2312
|
+
m, r = self._model_runner(body)
|
|
2313
|
+
if stop := self._model_disk(body, m, r):
|
|
2314
|
+
return stop
|
|
2315
|
+
|
|
2316
|
+
def run(job):
|
|
2317
|
+
out = wizard.pull(job, m, r)
|
|
2318
|
+
return wizard.test_and_save(job, m, r) if out["ok"] else out
|
|
2319
|
+
return self.jobs.start(f"Setting up {wizard.model(m)['label']}", "setup", run,
|
|
2320
|
+
cancellable=True)
|
|
2321
|
+
|
|
2322
|
+
# ---- guided imports: an upload (or a pasted path), a dry-run preview, then the import ----
|
|
2323
|
+
def _drop(self, uid: str | None) -> None:
|
|
2324
|
+
if uid and (p := self.uploads.pop(uid, None)) is not None:
|
|
2325
|
+
p.unlink(missing_ok=True)
|
|
2326
|
+
|
|
2327
|
+
def _import(self, body: dict, title: str, fn, keep: bool) -> dict:
|
|
2328
|
+
"""Start `fn(job, source, path, root)` as a job on a checked source and file. The
|
|
2329
|
+
upload is deleted when the job fails, and after it unless `keep` (a preview)."""
|
|
2330
|
+
source, uid, raw = body.get("source"), body.get("upload"), body.get("path")
|
|
2331
|
+
if source not in IMPORTS:
|
|
2332
|
+
raise ValueError(f"source must be one of {', '.join(IMPORTS)}")
|
|
2333
|
+
if uid is not None:
|
|
2334
|
+
p = self.uploads.get(uid) if isinstance(uid, str) else None
|
|
2335
|
+
if p is None or not p.is_file():
|
|
2336
|
+
raise ValueError("That file is gone; add it again.")
|
|
2337
|
+
else:
|
|
2338
|
+
if not isinstance(raw, str) or not raw.strip():
|
|
2339
|
+
raise ValueError("Add the file, or paste its full path.")
|
|
2340
|
+
p = Path(raw.strip().strip("\"'")).expanduser()
|
|
2341
|
+
if not p.is_absolute():
|
|
2342
|
+
raise ValueError("Paste the full path, such as "
|
|
2343
|
+
"C:\\Users\\you\\Downloads\\export.zip.")
|
|
2344
|
+
p = p.resolve()
|
|
2345
|
+
if not p.exists(): # a folder is fine: Perplexity .md files, an unzipped Takeout
|
|
2346
|
+
raise ValueError(f"Nothing is at {p}.")
|
|
2347
|
+
# notes, calendars and Google activity go into the vault; chats go beside it
|
|
2348
|
+
root = self.need_root() if source in actions.TIERED or (
|
|
2349
|
+
source == "google-activity" and not keep) else self.root
|
|
2350
|
+
|
|
2351
|
+
def run(job):
|
|
2352
|
+
out = None
|
|
2353
|
+
try:
|
|
2354
|
+
out = fn(job, source, p, root)
|
|
2355
|
+
return out
|
|
2356
|
+
finally: # kept after a preview, or to retry once the search model is in
|
|
2357
|
+
if out is None or not (keep or out.get("need")):
|
|
2358
|
+
self._drop(uid)
|
|
2359
|
+
return self.jobs.start(title, "setup", run,
|
|
2360
|
+
cancellable=source in ("google-activity", "voice-memos"),
|
|
2361
|
+
quiet_errors=source == "google-activity")
|
|
2362
|
+
|
|
2363
|
+
def import_preview(self, body: dict) -> dict:
|
|
2364
|
+
return self._import(body, "Checking the file", actions.import_preview, keep=True)
|
|
2365
|
+
|
|
2366
|
+
def import_run(self, body: dict) -> dict:
|
|
2367
|
+
# C2: the tier the page's choice sent; only the notes and calendar cards send one
|
|
2368
|
+
if body.get("tier") not in (None, "skip", "local", "cloud"): # before the job: the
|
|
2369
|
+
raise ValueError("tier must be one of skip, local, cloud") # upload is kept
|
|
2370
|
+
fn = actions.import_run if body.get("tier") is None else \
|
|
2371
|
+
partial(actions.import_run, tier=body["tier"])
|
|
2372
|
+
return self._import(body, "Importing", fn, keep=False)
|
|
2373
|
+
|
|
2374
|
+
# B2-b: an export in Downloads, offered on Home (keepfold.app.exports)
|
|
2375
|
+
def pickup(self) -> dict:
|
|
2376
|
+
return exports.offer()
|
|
2377
|
+
|
|
2378
|
+
def pickup_add(self, body: dict) -> dict:
|
|
2379
|
+
"""Add chats: the Import page's import of the offered zip, without its preview."""
|
|
2380
|
+
c = exports.pick(body.get("path"))
|
|
2381
|
+
out = self._import({"source": c["source"], "path": c["path"]}, "Importing",
|
|
2382
|
+
actions.import_run, keep=False)
|
|
2383
|
+
exports.mark(c, "added")
|
|
2384
|
+
return out
|
|
2385
|
+
|
|
2386
|
+
def pickup_dismiss(self, body: dict) -> dict:
|
|
2387
|
+
exports.mark(exports.pick(body.get("path")), "dismissed")
|
|
2388
|
+
return {"ok": True}
|
|
2389
|
+
|
|
2390
|
+
def pickup_later(self, body: dict) -> dict:
|
|
2391
|
+
exports.later()
|
|
2392
|
+
return {"ok": True}
|
|
2393
|
+
|
|
2394
|
+
# R18: watched folders (keepfold.watch), re-imported by the periodic pass (`watch_auto`)
|
|
2395
|
+
def _watched(self) -> dict | None:
|
|
2396
|
+
from keepfold import watch
|
|
2397
|
+
if self.root is None or not (self.root / ".keepfold").is_dir():
|
|
2398
|
+
return None
|
|
2399
|
+
return watch.listing(self._vault())
|
|
2400
|
+
|
|
2401
|
+
def watch_add(self, body: dict) -> dict:
|
|
2402
|
+
from keepfold import watch
|
|
2403
|
+
from keepfold.vault import VaultError
|
|
2404
|
+
path, source, tier = body.get("path"), body.get("source"), body.get("tier")
|
|
2405
|
+
if source not in watch.SOURCES:
|
|
2406
|
+
raise ValueError(f"source must be one of {', '.join(watch.SOURCES)}")
|
|
2407
|
+
if tier not in (None, "skip", "local", "cloud"):
|
|
2408
|
+
raise ValueError("tier must be one of skip, local, cloud")
|
|
2409
|
+
if not isinstance(path, str | None) or (not (path or "").strip() and source != "zotero"):
|
|
2410
|
+
raise ValueError("Paste the folder's full path.")
|
|
2411
|
+
try: # an empty path: Zotero finds its own library
|
|
2412
|
+
watch.add(self._vault(), (path or "").strip() or None, source, tier)
|
|
2413
|
+
except VaultError as e:
|
|
2414
|
+
raise ValueError(str(e)) from None
|
|
2415
|
+
return {"ok": True, "watched": self._watched()}
|
|
2416
|
+
|
|
2417
|
+
def watch_remove(self, body: dict) -> dict:
|
|
2418
|
+
from keepfold import watch
|
|
2419
|
+
if not isinstance(body.get("path"), str) or not watch.remove(self._vault(), body["path"]):
|
|
2420
|
+
raise ValueError("That folder is not watched.")
|
|
2421
|
+
return {"ok": True, "watched": self._watched()}
|
|
2422
|
+
|
|
2423
|
+
def watch_auto(self) -> list | None:
|
|
2424
|
+
"""One pass over the watched folders (keepfold.watch.run), in the periodic pass's thread,
|
|
2425
|
+
when a vault is set up and no job runs; committed like an import. Its results, or None
|
|
2426
|
+
when it did not run."""
|
|
2427
|
+
from keepfold import watch
|
|
2428
|
+
from keepfold.vault import Vault
|
|
2429
|
+
if not self.entry() or self.jobs.running():
|
|
2430
|
+
return None
|
|
2431
|
+
v = Vault(self.root)
|
|
2432
|
+
try:
|
|
2433
|
+
return watch.run(v)
|
|
2434
|
+
finally:
|
|
2435
|
+
actions._commit(v, "watched folders")
|
|
2436
|
+
|
|
2437
|
+
def forget_due(self) -> list | None:
|
|
2438
|
+
"""R10: the //forget lines a prompt hook or keepfold_prime retired and queued, swept from
|
|
2439
|
+
every store (keepfold.forget.run_due), in the periodic pass's thread when a vault is set
|
|
2440
|
+
up and no job runs; committed. The receipts, or None when it did not run."""
|
|
2441
|
+
from keepfold import forget, session
|
|
2442
|
+
from keepfold.vault import Vault
|
|
2443
|
+
if not self.entry() or self.jobs.running():
|
|
2444
|
+
return None
|
|
2445
|
+
v = Vault(self.root)
|
|
2446
|
+
try:
|
|
2447
|
+
return forget.run_due(v)
|
|
2448
|
+
finally:
|
|
2449
|
+
if v.writes:
|
|
2450
|
+
session._commit(v, "keepfold: forget a line", v.wrote_since(0))
|
|
2451
|
+
|
|
2452
|
+
def cancel(self, body: dict) -> dict:
|
|
2453
|
+
if self.jobs.cur is not None and self.jobs.cur.running and self.jobs.cur.cancellable:
|
|
2454
|
+
self.jobs.cur.cancel()
|
|
2455
|
+
return {"ok": True}
|
|
2456
|
+
|
|
2457
|
+
# ---- updates: checked and prepared quietly, applied only on a click ----
|
|
2458
|
+
def update_state(self) -> dict:
|
|
2459
|
+
from keepfold.app import desktop
|
|
2460
|
+
return {"current": update.current(), "mode": update.mode(), "ready": self.update_ready,
|
|
2461
|
+
"auto": desktop.update_check()}
|
|
2462
|
+
|
|
2463
|
+
def update_quietly(self) -> None:
|
|
2464
|
+
"""The background check (UPDATE_FIRST_S after start, then every UPDATE_EVERY_S): a
|
|
2465
|
+
newer release is downloaded and checked (installer), or its command noted (dev), then
|
|
2466
|
+
shown as Restart to update and notified once per version. Never applied here. Skipped
|
|
2467
|
+
while `app.update_check` is off (read each pass); the buttons work either way."""
|
|
2468
|
+
from keepfold.app import desktop
|
|
2469
|
+
if not desktop.update_check():
|
|
2470
|
+
return
|
|
2471
|
+
info, cur = update.latest(), update.current()
|
|
2472
|
+
if not update.newer(info["version"], update.parse_version(cur)):
|
|
2473
|
+
return
|
|
2474
|
+
version = ".".join(map(str, info["version"]))
|
|
2475
|
+
if self.update_ready and self.update_ready["version"] == version:
|
|
2476
|
+
return
|
|
2477
|
+
ready = {"version": version, "mode": update.mode(), "notes_url": info["notes_url"]}
|
|
2478
|
+
if ready["mode"] == "installer":
|
|
2479
|
+
dest = update.dest_dir(info)
|
|
2480
|
+
actions.sweep_updates(dest)
|
|
2481
|
+
if update.download(info, dest, None, self.stop) is None: # the app is stopping
|
|
2482
|
+
return
|
|
2483
|
+
else:
|
|
2484
|
+
ready["command"] = update.command(info["tag"])
|
|
2485
|
+
self.update_ready = ready
|
|
2486
|
+
if self.desktop is not None and desktop.notify_settings()["updates"] \
|
|
2487
|
+
and desktop.load_state().get("update_notified") != version:
|
|
2488
|
+
self.desktop.notify(f"Keepfold {version} is ready: restart to update")
|
|
2489
|
+
desktop.save_state("update_notified", version)
|
|
2490
|
+
|
|
2491
|
+
def _check(self, job) -> tuple[dict, dict]:
|
|
2492
|
+
job.say("asking GitHub for the latest release")
|
|
2493
|
+
info, cur = update.latest(), update.current()
|
|
2494
|
+
out = {"current": cur, "latest": ".".join(map(str, info["version"])),
|
|
2495
|
+
"newer": update.newer(info["version"], update.parse_version(cur)),
|
|
2496
|
+
"notes_url": info["notes_url"], "mode": update.mode(),
|
|
2497
|
+
"size": info["exe_size"]}
|
|
2498
|
+
if out["mode"] == "dev":
|
|
2499
|
+
out["command"] = update.command(info["tag"])
|
|
2500
|
+
actions.sweep_updates(update.dest_dir(info) if out["newer"] else None)
|
|
2501
|
+
return info, out
|
|
2502
|
+
|
|
2503
|
+
def news_seen(self, body: dict) -> dict:
|
|
2504
|
+
"""Got it on the What's new card: this version's news is not shown again."""
|
|
2505
|
+
news.record()
|
|
2506
|
+
return {"ok": True}
|
|
2507
|
+
|
|
2508
|
+
def update_check(self, body: dict) -> dict:
|
|
2509
|
+
return self.jobs.start("Checking for updates", "update", lambda job: self._check(job)[1])
|
|
2510
|
+
|
|
2511
|
+
def update_apply(self, body: dict) -> dict:
|
|
2512
|
+
"""Download the new installer (unless the quiet check already did), check it, start it
|
|
2513
|
+
and quit; it reopens the app. Restart to update and Update now both come here."""
|
|
2514
|
+
if update.mode() != "installer":
|
|
2515
|
+
info = update.latest()
|
|
2516
|
+
raise ValueError("This copy of Keepfold was not installed with KeepfoldSetup.exe. "
|
|
2517
|
+
f"Update it with: {update.command(info['tag'])}")
|
|
2518
|
+
|
|
2519
|
+
def run(job):
|
|
2520
|
+
info, out = self._check(job)
|
|
2521
|
+
if not out["newer"]:
|
|
2522
|
+
return {**out, "launched": False}
|
|
2523
|
+
|
|
2524
|
+
def said(got, total):
|
|
2525
|
+
job.say(f"downloaded {got >> 20} of {total >> 20} MB")
|
|
2526
|
+
ready = self.update_ready
|
|
2527
|
+
exe = update.dest_dir(info) / update.EXE # checked when the quiet check fetched it
|
|
2528
|
+
if not (ready and ready["version"] == out["latest"] and exe.is_file()):
|
|
2529
|
+
exe = update.download(info, update.dest_dir(info), said, job.cancelled)
|
|
2530
|
+
if exe is None:
|
|
2531
|
+
return {"cancelled": True}
|
|
2532
|
+
job.say("checked; starting the installer")
|
|
2533
|
+
update.launch(exe, os.getpid(), update.install_dir())
|
|
2534
|
+
threading.Timer(2, self.stop.set).start() # the page reads the result first
|
|
2535
|
+
return {**out, "launched": True}
|
|
2536
|
+
return self.jobs.start("Updating Keepfold", "update", run, cancellable=True)
|
|
2537
|
+
|
|
2538
|
+
def quit(self, body: dict) -> dict:
|
|
2539
|
+
if self.jobs.running(): # "Running jobs are cancelled": a download's process too
|
|
2540
|
+
self.jobs.cur.cancel()
|
|
2541
|
+
self.stop.set()
|
|
2542
|
+
return {"ok": True}
|
|
2543
|
+
|
|
2544
|
+
# ---- the desktop app: window, Start with Windows, notifications ----
|
|
2545
|
+
def window_show(self, body: dict) -> dict:
|
|
2546
|
+
"""A second `keepfold-app` launch brings this app's window up (False: the browser app)."""
|
|
2547
|
+
return {"shown": self.desktop is not None and self.desktop.show()}
|
|
2548
|
+
|
|
2549
|
+
def autostart(self) -> dict:
|
|
2550
|
+
from keepfold.app import desktop
|
|
2551
|
+
return desktop.autostart_state()
|
|
2552
|
+
|
|
2553
|
+
def autostart_set(self, body: dict) -> dict:
|
|
2554
|
+
from keepfold.app import desktop
|
|
2555
|
+
out = desktop.set_autostart(_bool(body, "enabled"))
|
|
2556
|
+
if self.desktop is not None:
|
|
2557
|
+
self.desktop.refresh_tray() # its Start with Windows tick
|
|
2558
|
+
return out
|
|
2559
|
+
|
|
2560
|
+
def notify(self) -> dict:
|
|
2561
|
+
from keepfold.app import desktop
|
|
2562
|
+
return desktop.notify_settings()
|
|
2563
|
+
|
|
2564
|
+
def notify_set(self, body: dict) -> dict:
|
|
2565
|
+
from keepfold.app import desktop
|
|
2566
|
+
return desktop.save_notify(body)
|
|
2567
|
+
|
|
2568
|
+
def hotkey(self) -> dict:
|
|
2569
|
+
"""Quick capture's key: the choice, the choices, and whether another app holds it
|
|
2570
|
+
(`taken`). `desktop`: false in the browser app, which has no hotkey."""
|
|
2571
|
+
from keepfold.app import desktop
|
|
2572
|
+
h = self.desktop.hotkey if self.desktop is not None else None
|
|
2573
|
+
return {"desktop": h is not None, "key": desktop.hotkey_setting(),
|
|
2574
|
+
"choices": [{"key": k, "label": v[2] if v else "Off"}
|
|
2575
|
+
for k, v in desktop.HOTKEYS.items()],
|
|
2576
|
+
"taken": bool(h and h.taken)}
|
|
2577
|
+
|
|
2578
|
+
def hotkey_set(self, body: dict) -> dict:
|
|
2579
|
+
from keepfold.app import desktop
|
|
2580
|
+
desktop.save_hotkey(body)
|
|
2581
|
+
if self.desktop is not None:
|
|
2582
|
+
self.desktop.change_hotkey() # registered again now, no restart
|
|
2583
|
+
return self.hotkey()
|
|
2584
|
+
|
|
2585
|
+
def capture_hide(self, body: dict) -> dict:
|
|
2586
|
+
"""The capture box's Esc, a saved line, or the box losing focus."""
|
|
2587
|
+
return {"hidden": self.desktop is not None and self.desktop.hide_box()}
|
|
2588
|
+
|
|
2589
|
+
|
|
2590
|
+
# ---- HTTP -----------------------------------------------------------------------------------
|
|
2591
|
+
|
|
2592
|
+
|
|
2593
|
+
def _handler(app: App):
|
|
2594
|
+
class H(BaseHTTPRequestHandler):
|
|
2595
|
+
server_version = "keepfold-app"
|
|
2596
|
+
sys_version = ""
|
|
2597
|
+
timeout = 30
|
|
2598
|
+
|
|
2599
|
+
def log_message(self, *a): # nothing from requests is logged
|
|
2600
|
+
pass
|
|
2601
|
+
|
|
2602
|
+
def _send(self, code: int, body, ctype: str = "application/json", extra=None):
|
|
2603
|
+
if self.command not in ("GET", "HEAD") and not getattr(self, "_drained", False):
|
|
2604
|
+
self._drained = True # Windows resets a socket closed with unread data
|
|
2605
|
+
try:
|
|
2606
|
+
n = int(self.headers.get("Content-Length", "0"))
|
|
2607
|
+
if 0 < n <= MAX_BODY:
|
|
2608
|
+
self.rfile.read(n)
|
|
2609
|
+
except (ValueError, OSError):
|
|
2610
|
+
pass
|
|
2611
|
+
data = body if isinstance(body, bytes) else json.dumps(body).encode()
|
|
2612
|
+
try:
|
|
2613
|
+
self._head(code, ctype, len(data), extra)
|
|
2614
|
+
self.wfile.write(data)
|
|
2615
|
+
except (ConnectionAbortedError, ConnectionResetError, BrokenPipeError):
|
|
2616
|
+
self.close_connection = True # the browser left mid-answer: nothing to tell it
|
|
2617
|
+
|
|
2618
|
+
def _head(self, code: int, ctype: str, length: int | None, extra=None):
|
|
2619
|
+
self.send_response(code)
|
|
2620
|
+
self.send_header("Content-Type", ctype)
|
|
2621
|
+
if length is not None:
|
|
2622
|
+
self.send_header("Content-Length", str(length))
|
|
2623
|
+
for k, v in (extra or {}).items():
|
|
2624
|
+
self.send_header(k, v)
|
|
2625
|
+
self.send_header("Cache-Control", "no-store")
|
|
2626
|
+
self.send_header("Content-Security-Policy", CSP)
|
|
2627
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
2628
|
+
self.send_header("Referrer-Policy", "no-referrer")
|
|
2629
|
+
self.send_header("X-Frame-Options", "DENY")
|
|
2630
|
+
self.send_header("Cross-Origin-Resource-Policy", "same-origin")
|
|
2631
|
+
self.end_headers()
|
|
2632
|
+
|
|
2633
|
+
def _redirect(self, where: str):
|
|
2634
|
+
self.send_response(302)
|
|
2635
|
+
self.send_header("Location", where)
|
|
2636
|
+
self.send_header("Content-Length", "0")
|
|
2637
|
+
self.send_header("Cache-Control", "no-store")
|
|
2638
|
+
self.send_header("Referrer-Policy", "no-referrer")
|
|
2639
|
+
self.end_headers()
|
|
2640
|
+
|
|
2641
|
+
def _gate(self, query_token: str | None = None, need_token: bool = True) -> bool:
|
|
2642
|
+
hosts = {f"{HOST}:{app.port}", f"localhost:{app.port}"}
|
|
2643
|
+
if self.headers.get("Host") not in hosts: # DNS rebinding
|
|
2644
|
+
self._send(403, {"error": "host"})
|
|
2645
|
+
return False
|
|
2646
|
+
origin = self.headers.get("Origin")
|
|
2647
|
+
if origin is not None and origin not in {f"http://{h}" for h in hosts}:
|
|
2648
|
+
self._send(403, {"error": "origin"})
|
|
2649
|
+
return False
|
|
2650
|
+
if not need_token: # the static page shell holds no data; the API needs the key
|
|
2651
|
+
return True
|
|
2652
|
+
given = self.headers.get("X-Keepfold-Token") or query_token or ""
|
|
2653
|
+
if not hmac.compare_digest(given.encode(), app.token.encode()):
|
|
2654
|
+
if self.command == "GET" and urlsplit(self.path).path == "/":
|
|
2655
|
+
self._send(401, EXPIRED_INSTALLED if update.mode() == "installer"
|
|
2656
|
+
else EXPIRED, "text/html; charset=utf-8")
|
|
2657
|
+
else:
|
|
2658
|
+
self._send(401, {"error": "token"})
|
|
2659
|
+
return False
|
|
2660
|
+
app.touch()
|
|
2661
|
+
return True
|
|
2662
|
+
|
|
2663
|
+
def do_GET(self):
|
|
2664
|
+
url = urlsplit(self.path)
|
|
2665
|
+
static = STATIC.get(url.path)
|
|
2666
|
+
qt = (parse_qs(url.query).get("t") or [None])[0] if static else None
|
|
2667
|
+
if not self._gate(qt, need_token=not static):
|
|
2668
|
+
return
|
|
2669
|
+
if static:
|
|
2670
|
+
path, ctype = static
|
|
2671
|
+
# the key goes only into a page opened with it
|
|
2672
|
+
ok = bool(qt) and hmac.compare_digest(qt.encode(), app.token.encode())
|
|
2673
|
+
key = app.token if ok else ""
|
|
2674
|
+
if path is None:
|
|
2675
|
+
try:
|
|
2676
|
+
app.need_root()
|
|
2677
|
+
except ValueError: # first run: no vault yet, so Setup
|
|
2678
|
+
self._redirect("/manage" + (f"?t={key}" if key else "") + "#setup")
|
|
2679
|
+
return
|
|
2680
|
+
from keepfold import dashboard
|
|
2681
|
+
data = dashboard.render_live(key).encode()
|
|
2682
|
+
else:
|
|
2683
|
+
data = path.read_bytes()
|
|
2684
|
+
if url.path in ("/manage", "/capture"):
|
|
2685
|
+
data = data.replace(b"{{T}}", key.encode()) \
|
|
2686
|
+
.replace(b"{{REOPEN}}", reopen().encode())
|
|
2687
|
+
self._send(200, data, ctype)
|
|
2688
|
+
elif url.path == "/api/vault/snapshot": # Export snapshot in the browser: a download
|
|
2689
|
+
self._run(app.snapshot, ctype="text/html; charset=utf-8", extra={
|
|
2690
|
+
"Content-Disposition": f'attachment; filename="{snapshot_name()}"'})
|
|
2691
|
+
elif url.path in app.get:
|
|
2692
|
+
self._run(app.get[url.path],
|
|
2693
|
+
*([parse_qs(url.query)] if url.path in QUERY_GETS else []))
|
|
2694
|
+
elif url.path in app.post:
|
|
2695
|
+
self._send(405, {"error": "use POST"})
|
|
2696
|
+
else:
|
|
2697
|
+
self._send(404, {"error": "not found"})
|
|
2698
|
+
|
|
2699
|
+
def do_POST(self):
|
|
2700
|
+
path = urlsplit(self.path).path
|
|
2701
|
+
if not self._gate():
|
|
2702
|
+
return
|
|
2703
|
+
if path not in app.post:
|
|
2704
|
+
self._send(405 if path in app.get or path in STATIC else 404,
|
|
2705
|
+
{"error": "not found"})
|
|
2706
|
+
return
|
|
2707
|
+
ctype = self.headers.get("Content-Type", "").split(";")[0].strip().lower()
|
|
2708
|
+
if path == UPLOAD:
|
|
2709
|
+
self._upload(ctype)
|
|
2710
|
+
return
|
|
2711
|
+
if ctype != "application/json":
|
|
2712
|
+
self._send(415, {"error": "Content-Type must be application/json"})
|
|
2713
|
+
return
|
|
2714
|
+
try:
|
|
2715
|
+
n = int(self.headers.get("Content-Length", ""))
|
|
2716
|
+
except ValueError:
|
|
2717
|
+
self._send(411, {"error": "length"})
|
|
2718
|
+
return
|
|
2719
|
+
if not 0 <= n <= (PICTURE_MAX * 3 // 2 if path == PICTURE else MAX_BODY):
|
|
2720
|
+
self.close_connection = True
|
|
2721
|
+
self._send(413, {"error": "too large"})
|
|
2722
|
+
return
|
|
2723
|
+
self._drained = True
|
|
2724
|
+
try:
|
|
2725
|
+
body = json.loads(self.rfile.read(n) or b"{}")
|
|
2726
|
+
except (ValueError, UnicodeDecodeError, RecursionError):
|
|
2727
|
+
body = None
|
|
2728
|
+
if not isinstance(body, dict):
|
|
2729
|
+
self._send(400, {"error": "the body must be a JSON object"})
|
|
2730
|
+
return
|
|
2731
|
+
if path == "/api/chat":
|
|
2732
|
+
self._chat(body)
|
|
2733
|
+
return
|
|
2734
|
+
status.forget() # an action: Status asks its slow probes again
|
|
2735
|
+
self._run(app.post[path], body)
|
|
2736
|
+
|
|
2737
|
+
def _chat(self, body: dict):
|
|
2738
|
+
"""Stream one chat turn as NDJSON on this thread (not a job: chat works while an
|
|
2739
|
+
import runs). The client going away sets cancel; the partial answer is kept."""
|
|
2740
|
+
from keepfold import chat, localllm
|
|
2741
|
+
try:
|
|
2742
|
+
vault, cid, text = app.chat_begin(body)
|
|
2743
|
+
except Busy as e:
|
|
2744
|
+
self._send(409, {"error": str(e)})
|
|
2745
|
+
return
|
|
2746
|
+
except ValueError as e:
|
|
2747
|
+
self._send(400, {"error": str(e)[:500]})
|
|
2748
|
+
return
|
|
2749
|
+
cancel, ended, wlock = threading.Event(), threading.Event(), threading.Lock()
|
|
2750
|
+
|
|
2751
|
+
def emit(ev: dict):
|
|
2752
|
+
if cancel.is_set():
|
|
2753
|
+
return
|
|
2754
|
+
app.touch()
|
|
2755
|
+
with wlock: # the keepalive thread writes too
|
|
2756
|
+
if ended.is_set():
|
|
2757
|
+
return
|
|
2758
|
+
try:
|
|
2759
|
+
self.wfile.write(json.dumps(ev).encode() + b"\n")
|
|
2760
|
+
self.wfile.flush()
|
|
2761
|
+
except OSError: # BrokenPipe, ConnectionReset/Aborted: the page stopped
|
|
2762
|
+
cancel.set()
|
|
2763
|
+
if ev.get("t") in ("done", "err"):
|
|
2764
|
+
ended.set()
|
|
2765
|
+
|
|
2766
|
+
def keepalive():
|
|
2767
|
+
# a closed page shows only on a write: while the model reads or reasons quietly,
|
|
2768
|
+
# write now and then, so Stop ends the turn (and frees the slot) early
|
|
2769
|
+
while not ended.wait(KEEPALIVE_S):
|
|
2770
|
+
emit({"t": "wait"})
|
|
2771
|
+
try:
|
|
2772
|
+
self.close_connection = True # no length: the end of the answer ends the body
|
|
2773
|
+
self._head(200, "application/x-ndjson", None)
|
|
2774
|
+
threading.Thread(target=keepalive, daemon=True, name="chat-keepalive").start()
|
|
2775
|
+
# local only, never cloudllm; looked up only when the turn needs the model. An
|
|
2776
|
+
# attached file (C1) is asked like any question: the person asked, so the
|
|
2777
|
+
# configured local model may start, as for every Chat turn
|
|
2778
|
+
files = app.files.get(body.get("files"))
|
|
2779
|
+
chat.reply(vault, cid, text, localllm.find, emit, cancel, files=files,
|
|
2780
|
+
pages=body.get("pages")) # UX-B: ids picked with "#"
|
|
2781
|
+
except Exception as e: # noqa: BLE001 (the type only: a message could quote a page)
|
|
2782
|
+
emit({"t": "err", "code": "internal",
|
|
2783
|
+
"message": f"internal error ({type(e).__name__})"})
|
|
2784
|
+
finally:
|
|
2785
|
+
ended.set()
|
|
2786
|
+
app.chatting.release()
|
|
2787
|
+
app.piggyback() # C8: the model is warm; a short fact-harvest pass
|
|
2788
|
+
|
|
2789
|
+
def _upload(self, ctype: str):
|
|
2790
|
+
"""Stream an export to ~/.keepfold/tmp/upload-<id>-<stem><ext>, owner-only (0600).
|
|
2791
|
+
Of the client's name (X-Keepfold-Name) only the extension and up to 40 letters,
|
|
2792
|
+
digits, combining marks, _ and - of its stem are kept: `importers.detect` reads
|
|
2793
|
+
names such as MyActivity.json. The size is capped at MAX_UPLOAD."""
|
|
2794
|
+
self.close_connection = True # a refused body is left unread
|
|
2795
|
+
if ctype != "application/octet-stream":
|
|
2796
|
+
self._send(415, {"error": "Content-Type must be application/octet-stream"})
|
|
2797
|
+
return
|
|
2798
|
+
raw = unquote(self.headers.get("X-Keepfold-Name", ""))
|
|
2799
|
+
name = PurePosixPath(raw.replace("\\", "/"))
|
|
2800
|
+
ext = name.suffix.lower()
|
|
2801
|
+
if ext not in UPLOAD_EXT:
|
|
2802
|
+
self._send(400, {"error": "Add the export as it came: a .zip, .json, .html, .md, "
|
|
2803
|
+
".txt, .ics, .mbox, .pdf, .docx, .apkg or .colpkg "
|
|
2804
|
+
"file."})
|
|
2805
|
+
return
|
|
2806
|
+
# letters, digits and combining marks of any script (Devanagari vowel signs are
|
|
2807
|
+
# marks), so takeout.activity_file still knows MeineAktivitäten or मेरीगतिविधि
|
|
2808
|
+
stem = "".join(c for c in unicodedata.normalize("NFC", name.stem)
|
|
2809
|
+
if c.isalnum() or c in "_-"
|
|
2810
|
+
or unicodedata.category(c)[0] == "M")[:40]
|
|
2811
|
+
try:
|
|
2812
|
+
n = int(self.headers.get("Content-Length", ""))
|
|
2813
|
+
except ValueError:
|
|
2814
|
+
self._send(411, {"error": "length"})
|
|
2815
|
+
return
|
|
2816
|
+
if not 0 < n <= MAX_UPLOAD:
|
|
2817
|
+
self._send(413, {"error": "The file is larger than 4 GB; unzip it and paste "
|
|
2818
|
+
"the path of the file inside instead."})
|
|
2819
|
+
return
|
|
2820
|
+
self._drained = True
|
|
2821
|
+
d = actions.tmp_dir()
|
|
2822
|
+
d.mkdir(mode=0o700, parents=True, exist_ok=True) # Windows: the profile's own ACL
|
|
2823
|
+
uid = secrets.token_hex(8)
|
|
2824
|
+
p, left = d / f"upload-{uid}{'-' * bool(stem)}{stem}{ext}", n
|
|
2825
|
+
try:
|
|
2826
|
+
fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0),
|
|
2827
|
+
0o600)
|
|
2828
|
+
with os.fdopen(fd, "wb") as f:
|
|
2829
|
+
while left:
|
|
2830
|
+
chunk = self.rfile.read(min(left, 1 << 20))
|
|
2831
|
+
if not chunk:
|
|
2832
|
+
raise OSError("short body")
|
|
2833
|
+
f.write(chunk)
|
|
2834
|
+
left -= len(chunk)
|
|
2835
|
+
except OSError:
|
|
2836
|
+
p.unlink(missing_ok=True)
|
|
2837
|
+
self._send(400, {"error": "The upload stopped before the end; try again."})
|
|
2838
|
+
return
|
|
2839
|
+
app.uploads[uid] = p
|
|
2840
|
+
self._send(200, {"upload": uid, "size": n})
|
|
2841
|
+
|
|
2842
|
+
def _run(self, fn, *args, ctype: str = "application/json", extra=None):
|
|
2843
|
+
try:
|
|
2844
|
+
self._send(200, fn(*args), ctype, extra)
|
|
2845
|
+
except Busy as e:
|
|
2846
|
+
self._send(409, {"error": str(e)})
|
|
2847
|
+
except NotFound:
|
|
2848
|
+
self._send(404, {"error": "not found"})
|
|
2849
|
+
except ValueError as e:
|
|
2850
|
+
self._send(400, {"error": str(e)[:500]})
|
|
2851
|
+
except Exception as e: # noqa: BLE001 (the type only: a message could quote a page)
|
|
2852
|
+
self._send(500, {"error": f"internal error ({type(e).__name__})"})
|
|
2853
|
+
|
|
2854
|
+
def _refuse(self):
|
|
2855
|
+
self._send(405, {"error": "method"})
|
|
2856
|
+
|
|
2857
|
+
do_PUT = do_DELETE = do_PATCH = do_OPTIONS = _refuse # noqa: N815
|
|
2858
|
+
|
|
2859
|
+
return H
|
|
2860
|
+
|
|
2861
|
+
|
|
2862
|
+
MAX_CONNECTIONS = 32 # open connections at once: one thread each
|
|
2863
|
+
|
|
2864
|
+
|
|
2865
|
+
class _Server(ThreadingHTTPServer):
|
|
2866
|
+
"""No port sharing: Windows binds a used port without SO_EXCLUSIVEADDRUSE, and the token
|
|
2867
|
+
would go to its owner. At most MAX_CONNECTIONS connections at once: a local program opening
|
|
2868
|
+
thousands of idle ones would otherwise start a thread for each; one over the cap is closed
|
|
2869
|
+
at once. Each handler's `timeout` bounds how long an idle one keeps its slot."""
|
|
2870
|
+
# POSIX SO_REUSEADDR only skips TIME_WAIT (a quick reopen keeps port 47615); on Windows
|
|
2871
|
+
# it would let a second listener take the live port
|
|
2872
|
+
allow_reuse_address = os.name != "nt"
|
|
2873
|
+
|
|
2874
|
+
def __init__(self, *a, **kw):
|
|
2875
|
+
self._slots = threading.BoundedSemaphore(MAX_CONNECTIONS)
|
|
2876
|
+
super().__init__(*a, **kw)
|
|
2877
|
+
|
|
2878
|
+
def server_bind(self):
|
|
2879
|
+
if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
|
|
2880
|
+
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
|
|
2881
|
+
super().server_bind()
|
|
2882
|
+
|
|
2883
|
+
def process_request(self, request, client_address):
|
|
2884
|
+
if not self._slots.acquire(blocking=False):
|
|
2885
|
+
self.shutdown_request(request)
|
|
2886
|
+
return
|
|
2887
|
+
try:
|
|
2888
|
+
super().process_request(request, client_address)
|
|
2889
|
+
except BaseException: # no thread started, so none will release the slot
|
|
2890
|
+
self._slots.release()
|
|
2891
|
+
raise
|
|
2892
|
+
|
|
2893
|
+
def process_request_thread(self, request, client_address):
|
|
2894
|
+
try:
|
|
2895
|
+
super().process_request_thread(request, client_address)
|
|
2896
|
+
finally:
|
|
2897
|
+
self._slots.release()
|
|
2898
|
+
|
|
2899
|
+
|
|
2900
|
+
def make_server(root: Path | None, port: int = 0) -> tuple[ThreadingHTTPServer, App]:
|
|
2901
|
+
"""The app's server on 127.0.0.1 only (port 0 picks a free one)."""
|
|
2902
|
+
app = App(root)
|
|
2903
|
+
actions.sweep_uploads() # left by an app that was killed before its `finally` ran
|
|
2904
|
+
actions.sweep_updates(update.prepared()) # installers an update already ran; a newer one
|
|
2905
|
+
# downloaded and still matching its checksum stays for Restart to update
|
|
2906
|
+
srv = _Server((HOST, port), _handler(app))
|
|
2907
|
+
srv.daemon_threads = True
|
|
2908
|
+
app.port = srv.server_address[1]
|
|
2909
|
+
return srv, app
|
|
2910
|
+
|
|
2911
|
+
|
|
2912
|
+
def state_file() -> Path:
|
|
2913
|
+
return Path.home() / ".keepfold" / "app.json"
|
|
2914
|
+
|
|
2915
|
+
|
|
2916
|
+
def _save_state(app: App) -> None:
|
|
2917
|
+
"""~/.keepfold/app.json {port, token, pid}, owner-only: a second launch opens this app."""
|
|
2918
|
+
p = state_file()
|
|
2919
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
2920
|
+
tmp = p.with_name(f".app-{os.getpid()}.tmp")
|
|
2921
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
2922
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
2923
|
+
json.dump({"port": app.port, "token": app.token, "pid": os.getpid()}, f)
|
|
2924
|
+
os.replace(tmp, p)
|
|
2925
|
+
|
|
2926
|
+
|
|
2927
|
+
def _drop_state(app: App) -> None:
|
|
2928
|
+
try:
|
|
2929
|
+
if json.loads(state_file().read_text(encoding="utf-8")).get("token") == app.token:
|
|
2930
|
+
state_file().unlink()
|
|
2931
|
+
except (OSError, ValueError, AttributeError):
|
|
2932
|
+
pass
|
|
2933
|
+
|
|
2934
|
+
|
|
2935
|
+
def running_url() -> str | None:
|
|
2936
|
+
"""The link of a Keepfold app that runs now (app.json names it and it answers with that
|
|
2937
|
+
key), else None: a stale or unreadable file is ignored."""
|
|
2938
|
+
import http.client
|
|
2939
|
+
try:
|
|
2940
|
+
s = json.loads(state_file().read_text(encoding="utf-8"))
|
|
2941
|
+
port, token = int(s["port"]), str(s["token"])
|
|
2942
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
2943
|
+
return None
|
|
2944
|
+
c = http.client.HTTPConnection(HOST, port, timeout=2)
|
|
2945
|
+
try:
|
|
2946
|
+
c.request("GET", "/api/job", headers={"Host": f"{HOST}:{port}", "X-Keepfold-Token": token})
|
|
2947
|
+
ok = c.getresponse().status == 200
|
|
2948
|
+
except OSError:
|
|
2949
|
+
return None
|
|
2950
|
+
finally:
|
|
2951
|
+
c.close()
|
|
2952
|
+
return f"http://{HOST}:{port}/?t={token}" if ok else None
|
|
2953
|
+
|
|
2954
|
+
|
|
2955
|
+
def show_window(url: str) -> bool:
|
|
2956
|
+
"""Ask the app at `url` (from running_url) to bring its window up; False when it has no
|
|
2957
|
+
window (the browser app) or does not answer."""
|
|
2958
|
+
import http.client
|
|
2959
|
+
u = urlsplit(url)
|
|
2960
|
+
token = (parse_qs(u.query).get("t") or [""])[0]
|
|
2961
|
+
c = http.client.HTTPConnection(HOST, u.port, timeout=10)
|
|
2962
|
+
try:
|
|
2963
|
+
c.request("POST", "/api/window/show", body=b"{}", headers={
|
|
2964
|
+
"Host": u.netloc, "X-Keepfold-Token": token, "Content-Type": "application/json"})
|
|
2965
|
+
r = c.getresponse()
|
|
2966
|
+
return r.status == 200 and json.loads(r.read()).get("shown") is True
|
|
2967
|
+
except (OSError, ValueError):
|
|
2968
|
+
return False
|
|
2969
|
+
finally:
|
|
2970
|
+
c.close()
|
|
2971
|
+
|
|
2972
|
+
|
|
2973
|
+
def start_url(app: App, now=None) -> str:
|
|
2974
|
+
"""The page the app opens on when it starts: Home, or Tonight from 20:00 until the Keepfold
|
|
2975
|
+
day rolls over at 04:00 local time (the owner's choice), once a vault exists. `now`: a
|
|
2976
|
+
naive local datetime (tests); later navigation is never moved."""
|
|
2977
|
+
from datetime import datetime
|
|
2978
|
+
|
|
2979
|
+
from keepfold.events import DAY_ROLLOVER
|
|
2980
|
+
h = (now or datetime.now()).hour
|
|
2981
|
+
night = (h >= 20 or h < DAY_ROLLOVER.seconds // 3600) and app.root is not None \
|
|
2982
|
+
and (app.root / ".keepfold").is_dir()
|
|
2983
|
+
return f"http://{HOST}:{app.port}/" + (f"manage?t={app.token}#tonight" if night
|
|
2984
|
+
else f"?t={app.token}")
|
|
2985
|
+
|
|
2986
|
+
|
|
2987
|
+
def start(root: Path | None, *, port: int = 0, echo=print, idle: bool = True,
|
|
2988
|
+
) -> tuple[ThreadingHTTPServer, App, str]:
|
|
2989
|
+
"""The app's server, app.json and its watch and auto-import threads, not yet serving: the
|
|
2990
|
+
caller runs `srv.serve_forever` and then `finish`. `idle`: stop after 30 minutes with no
|
|
2991
|
+
request and no job (the browser app; the desktop app runs until Quit). No `port`: PORT if
|
|
2992
|
+
it is free, else any free one."""
|
|
2993
|
+
try:
|
|
2994
|
+
srv, app = make_server(root, port or PORT)
|
|
2995
|
+
except OSError as e:
|
|
2996
|
+
if port:
|
|
2997
|
+
raise SystemExit(f"Port {port} is in use or not allowed ({e.strerror or e}). Pick "
|
|
2998
|
+
"another, or leave --port out for a free one.") from None
|
|
2999
|
+
srv, app = make_server(root, 0) # PORT is taken (a second Keepfold, another program)
|
|
3000
|
+
app.echo = echo
|
|
3001
|
+
url = start_url(app)
|
|
3002
|
+
try:
|
|
3003
|
+
_save_state(app)
|
|
3004
|
+
except OSError: # no single-instance file: a second launch starts its own app
|
|
3005
|
+
traceback.print_exc(limit=1)
|
|
3006
|
+
try:
|
|
3007
|
+
news.start() # a fresh install remembers this version, so it shows no What's new
|
|
3008
|
+
except Exception: # noqa: BLE001 (an unwritable config only means no card; the app opens)
|
|
3009
|
+
traceback.print_exc(limit=3)
|
|
3010
|
+
try:
|
|
3011
|
+
actions.migrate_login(app.root if app.entry() else None)
|
|
3012
|
+
except Exception: # noqa: BLE001 (Start at login stays as it was; the app still opens)
|
|
3013
|
+
traceback.print_exc(limit=3)
|
|
3014
|
+
if app.entry() is not None:
|
|
3015
|
+
try:
|
|
3016
|
+
from keepfold import dashboard
|
|
3017
|
+
dashboard.retire_old(app._vault()) # the old .keepfold/dashboard.html, once
|
|
3018
|
+
except Exception: # noqa: BLE001 (it is moved at the next start; the app still opens)
|
|
3019
|
+
traceback.print_exc(limit=3)
|
|
3020
|
+
try:
|
|
3021
|
+
from keepfold.browse import legacy
|
|
3022
|
+
legacy.migrate(app._vault()) # the browse files from before the store, once
|
|
3023
|
+
except Exception: # noqa: BLE001 (tried again at the next start or import)
|
|
3024
|
+
traceback.print_exc(limit=3)
|
|
3025
|
+
|
|
3026
|
+
def watch():
|
|
3027
|
+
while not app.stop.wait(WATCH_S):
|
|
3028
|
+
if idle and time.monotonic() - app.last > IDLE_S and not app.jobs.running():
|
|
3029
|
+
echo("keepfold app: 30 minutes idle; stopping.")
|
|
3030
|
+
break
|
|
3031
|
+
app.drop_dry()
|
|
3032
|
+
app.stop.set()
|
|
3033
|
+
srv.shutdown()
|
|
3034
|
+
|
|
3035
|
+
def forget_due(): # R10: a //forget's sweep, queued by a hook or keepfold_prime
|
|
3036
|
+
try:
|
|
3037
|
+
app.forget_due()
|
|
3038
|
+
except Exception as e: # noqa: BLE001 (the next pass tries again)
|
|
3039
|
+
echo(f"keepfold app: forgetting a //forget line failed ({type(e).__name__})")
|
|
3040
|
+
|
|
3041
|
+
def auto(): # the live import: first after a minute, then every 10
|
|
3042
|
+
from keepfold import browse_serve
|
|
3043
|
+
wait = browse_serve.AUTO_FIRST_S
|
|
3044
|
+
forget_due() # once at start, then with each pass
|
|
3045
|
+
while not app.stop.wait(wait):
|
|
3046
|
+
wait = browse_serve.AUTO_EVERY_S
|
|
3047
|
+
try:
|
|
3048
|
+
app.auto_import()
|
|
3049
|
+
except Exception as e: # noqa: BLE001 (the next check tries again)
|
|
3050
|
+
echo(f"keepfold app: live import failed ({type(e).__name__}); retried in "
|
|
3051
|
+
f"{browse_serve.AUTO_EVERY_S // 60} minutes")
|
|
3052
|
+
try: # R18: the watched folders' new and changed files; stats only when none
|
|
3053
|
+
app.watch_auto()
|
|
3054
|
+
except Exception as e: # noqa: BLE001 (the next pass tries again)
|
|
3055
|
+
echo(f"keepfold app: watched folders failed ({type(e).__name__})")
|
|
3056
|
+
forget_due()
|
|
3057
|
+
try: # the rollup pages after the import; a stamp check when nothing changed
|
|
3058
|
+
if app.root is not None and (app.root / ".keepfold").is_dir() \
|
|
3059
|
+
and not app.jobs.running():
|
|
3060
|
+
from keepfold import rollups
|
|
3061
|
+
rollups.run(app._vault())
|
|
3062
|
+
except Exception as e: # noqa: BLE001 (the next pass tries again)
|
|
3063
|
+
echo(f"keepfold app: rollup pages failed ({type(e).__name__})")
|
|
3064
|
+
|
|
3065
|
+
def tidy(): # D1-D3: the about-me sweep, at start and with each chat-import pass
|
|
3066
|
+
try:
|
|
3067
|
+
app.tidy_about_me()
|
|
3068
|
+
except Exception as e: # noqa: BLE001 (the next pass tries again)
|
|
3069
|
+
echo(f"keepfold app: tidying the about-me lines failed ({type(e).__name__})")
|
|
3070
|
+
|
|
3071
|
+
def chats(): # app.chat_import: the first pass a minute after start, then every 5 minutes
|
|
3072
|
+
from keepfold import chat_import
|
|
3073
|
+
wait = chat_import.FIRST_S
|
|
3074
|
+
tidy()
|
|
3075
|
+
while not app.stop.wait(wait):
|
|
3076
|
+
wait = chat_import.EVERY_S
|
|
3077
|
+
tidy()
|
|
3078
|
+
# the safety net reads the pages the last import wrote; first, since the import
|
|
3079
|
+
# below starts a job and the net waits while any job runs
|
|
3080
|
+
try:
|
|
3081
|
+
app.safety_net_auto()
|
|
3082
|
+
except Exception as e: # noqa: BLE001 (the next pass tries again)
|
|
3083
|
+
echo(f"keepfold app: the chat safety net failed ({type(e).__name__}); retried in "
|
|
3084
|
+
f"{chat_import.EVERY_S // 60} minutes")
|
|
3085
|
+
try: # facts the owner stated in those chats, saved as about-me guesses
|
|
3086
|
+
from keepfold import fact_harvest
|
|
3087
|
+
fact_harvest.auto(app)
|
|
3088
|
+
except Exception as e: # noqa: BLE001 (the next pass tries again)
|
|
3089
|
+
echo(f"keepfold app: saving facts from chats failed ({type(e).__name__})")
|
|
3090
|
+
try:
|
|
3091
|
+
app.chat_import_auto()
|
|
3092
|
+
except Exception as e: # noqa: BLE001 (the next pass tries again)
|
|
3093
|
+
echo(f"keepfold app: automatic chat import check failed ({type(e).__name__})")
|
|
3094
|
+
try: # plan v9 item 8: the Keepfold block in agents' rules files follows the core
|
|
3095
|
+
targets.refresh_rules(app.entry())
|
|
3096
|
+
except Exception as e: # noqa: BLE001 (the next pass tries again)
|
|
3097
|
+
echo(f"keepfold app: rules block refresh failed ({type(e).__name__})")
|
|
3098
|
+
|
|
3099
|
+
def updates(): # the quiet update check: a minute after start, then every 6 hours
|
|
3100
|
+
wait = UPDATE_FIRST_S
|
|
3101
|
+
while not app.stop.wait(wait):
|
|
3102
|
+
wait = UPDATE_EVERY_S
|
|
3103
|
+
try:
|
|
3104
|
+
app.update_quietly()
|
|
3105
|
+
except Exception as e: # noqa: BLE001 (offline, GitHub busy: the next check tries)
|
|
3106
|
+
echo(f"keepfold app: the update check failed ({type(e).__name__})")
|
|
3107
|
+
|
|
3108
|
+
threading.Thread(target=watch, daemon=True).start()
|
|
3109
|
+
threading.Thread(target=auto, daemon=True, name="keepfold-app-auto-import").start()
|
|
3110
|
+
threading.Thread(target=chats, daemon=True, name="keepfold-app-chat-import").start()
|
|
3111
|
+
threading.Thread(target=updates, daemon=True, name="keepfold-app-updates").start()
|
|
3112
|
+
if WARM_STATUS:
|
|
3113
|
+
app.warm_status()
|
|
3114
|
+
if app.entry() is not None: # the first page: its brain built before the window asks
|
|
3115
|
+
threading.Thread(target=app.warm_home, daemon=True,
|
|
3116
|
+
name="keepfold-app-warm-home").start()
|
|
3117
|
+
return srv, app, url
|
|
3118
|
+
|
|
3119
|
+
|
|
3120
|
+
def finish(srv: ThreadingHTTPServer, app: App) -> None:
|
|
3121
|
+
"""After serving: app.json and unused uploads go; the port closes."""
|
|
3122
|
+
app.stop.set()
|
|
3123
|
+
_drop_state(app)
|
|
3124
|
+
for uid in list(app.uploads): # exports added but never imported
|
|
3125
|
+
app._drop(uid)
|
|
3126
|
+
srv.server_close()
|
|
3127
|
+
|
|
3128
|
+
|
|
3129
|
+
def run(root: Path | None, *, open_browser: bool = True, port: int = 0, echo=print) -> None:
|
|
3130
|
+
"""Serve until Quit, Ctrl+C or 30 minutes with no request and no job."""
|
|
3131
|
+
srv, app, url = start(root, port=port, echo=echo)
|
|
3132
|
+
# the key (?t=) only when the link is the output (--no-open): logs get shared
|
|
3133
|
+
echo(f"Keepfold app: {url if not open_browser else url.split('?')[0]}")
|
|
3134
|
+
echo("It runs on this computer only. Close it with Quit on the page or Ctrl+C here.")
|
|
3135
|
+
if open_browser:
|
|
3136
|
+
_open(url)
|
|
3137
|
+
try:
|
|
3138
|
+
srv.serve_forever(poll_interval=0.5)
|
|
3139
|
+
except KeyboardInterrupt:
|
|
3140
|
+
pass
|
|
3141
|
+
finally:
|
|
3142
|
+
finish(srv, app)
|