bibliotheque 0.1.27__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.
@@ -0,0 +1,132 @@
1
+ """Bibliothèque plugin entry — agent-plugins 1.0, loaded as hermes_plugins.<slug>.
2
+
3
+ register(ctx) is the real loader contract: ctx.register_tool(name, toolset,
4
+ schema={"type":"object","parameters":…}, handler, description). Handlers
5
+ absorb dispatch kwargs themselves (**_x — Hermes passes task_id + extras).
6
+
7
+ Env contract: register() checks that onnxruntime, numpy, and transformers
8
+ import, and refuses to register tools when they do not. Install them with
9
+ `pip install -r requirements.txt`. The model snapshot is loaded from the
10
+ Hugging Face cache and is not downloaded on startup.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import sys
16
+
17
+ _PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__))
18
+
19
+ from .core import config_root as _cr # noqa: E402
20
+
21
+
22
+ def _config_root() -> str:
23
+ """Root from the plugin dir's bibliotheque-config.yaml (delegated to the shared seam)."""
24
+ return _cr.config_root(_PLUGIN_DIR)
25
+
26
+
27
+ TOOL_ROOT = _cr.default_root(_PLUGIN_DIR)
28
+
29
+ PYVER = f"python{sys.version_info.major}.{sys.version_info.minor}"
30
+
31
+ BOOTSTRAP_HINT = (
32
+ "Bibliothèque engine deps missing — pip install -r requirements.txt "
33
+ "from the plugin directory"
34
+ )
35
+
36
+
37
+ def _engine_importable() -> bool:
38
+ try:
39
+ import onnxruntime # noqa: F401
40
+ import numpy # noqa: F401
41
+ import transformers # noqa: F401
42
+ # The processor chain constructs a video processor needing BOTH torch and
43
+ # torchvision; without them every embed raises ImportError at call time
44
+ # while the plugin still advertises five working tools.
45
+ import torch # noqa: F401
46
+ import torchvision # noqa: F401
47
+ return True
48
+ except Exception:
49
+ return False
50
+
51
+
52
+ def register(ctx) -> None:
53
+ """Bibliothèque native tool registration (Hermes loader contract)."""
54
+ # Deps arrive with the plugin install (python_dependencies / requirements.txt).
55
+ # Nothing here edits sys.path or the process environment: this runs inside the
56
+ # Hermes gateway, where either would leak into every other plugin.
57
+ if not _engine_importable():
58
+ print(f"[bibliotheque] {BOOTSTRAP_HINT}")
59
+ return
60
+
61
+ import json as _json
62
+
63
+ from .core import tools as _tools
64
+
65
+ def _json_result(handler):
66
+ """Registry dispatch contract: handler receives ONE positional arg (the
67
+ args dict, task_id-style extras included) and returns a str (dict
68
+ results are rejected — the workspace plugin's lifetime bug)."""
69
+ def wrapped(args=None, **kwargs):
70
+ a = dict(args or {})
71
+ a.update(kwargs)
72
+ return _json.dumps(handler(**a))
73
+ return wrapped
74
+
75
+ def reg(name, desc, handler, params, required):
76
+ ctx.register_tool(
77
+ name=name,
78
+ toolset="bibliotheque",
79
+ schema={"type": "object", "parameters": {
80
+ "type": "object", "properties": params, "required": required}},
81
+ handler=_json_result(handler),
82
+ check_fn=lambda: True,
83
+ description=desc,
84
+ )
85
+
86
+ reg(
87
+ "bibliotheque_search",
88
+ "Search documents and media (hybrid: semantic + keyword/BM25): text, images, "
89
+ "audio. Ranked hits with snippets, scores, spans, and image thumbnails.",
90
+ _tools.tool_search,
91
+ {
92
+ "query": {"type": "string", "description": "natural-language query (or keyword terms)"},
93
+ "k": {"type": "integer", "default": 5},
94
+ "kind": {"type": "string", "enum": ["text", "image", "audio", "video"]},
95
+ "include_thumbnails": {"type": "boolean", "default": True},
96
+ },
97
+ ["query"],
98
+ )
99
+ reg(
100
+ "bibliotheque_add_note",
101
+ "Store a text note into the Bibliothèque corpus (searchable afterwards).",
102
+ _tools.tool_add_note,
103
+ {"text": {"type": "string", "description": "note text"},
104
+ },
105
+ ["text"],
106
+ )
107
+ reg(
108
+ "bibliotheque_ingest_dir",
109
+ "Bulk-index a directory of documents and media (pdf, office, notes, "
110
+ "subtitles, images, audio). Per-file errors are collected, never fatal.",
111
+ _tools.tool_ingest_dir,
112
+ {"path": {"type": "string"},
113
+ },
114
+ ["path"],
115
+ )
116
+ reg(
117
+ "bibliotheque_add_source",
118
+ "Add one source: local file/dir, http(s) URL, or adapter scheme URI "
119
+ "(raindrop://, pcloud://, obsidian://, rclone://backend:path).",
120
+ _tools.tool_add_source,
121
+ {"source": {"type": "string"},
122
+ },
123
+ ["source"],
124
+ )
125
+ reg(
126
+ "bibliotheque_status",
127
+ "Bibliothèque corpus status: row counts by kind, corpus root, adapters.",
128
+ _tools.tool_status,
129
+ {},
130
+ [],
131
+ )
132
+ print(f"[bibliotheque] 5 tools registered (corpus root: {TOOL_ROOT})")
File without changes
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env python3
2
+ """Bibliothèque source adapter: dropbox://<path-in-dropbox> — Dropbox assets via the
3
+ desktop client's local folder (or any local mirror).
4
+
5
+ Env: DROPBOX_DIR (default: "~/Dropbox"). Item shape: {"uri", "path"} — the
6
+ indexer decodes/embeds real files itself, so this adapter deliberately does not
7
+ carry its own extension list: `ing.index_file` knows which formats it can read
8
+ (pdf/epub/docx via pandoc, pdf via pdftotext, images, audio) and returns an
9
+ `unsupported_ext` skip for the rest. Duplicating that list here is how Dropbox
10
+ PDFs would go missing without a word.
11
+ """
12
+ import json
13
+ import os
14
+ import sys
15
+
16
+ # Dropbox's own bookkeeping, plus the usual VCS/mount debris. Anything else is
17
+ # the indexer's call.
18
+ SKIP_DIRS = {".dropbox", ".dropbox.cache", ".git", ".obsidian", ".trash"}
19
+
20
+
21
+ def main():
22
+ if len(sys.argv) != 3 or sys.argv[1] != "fetch":
23
+ print("usage: dropbox fetch <path-in-dropbox> (e.g. dropbox://Papers)", file=sys.stderr)
24
+ return 2
25
+ base = os.path.expanduser(os.environ.get("DROPBOX_DIR", "~/Dropbox"))
26
+ sub = sys.argv[2].lstrip("/")
27
+ root = os.path.join(base, sub)
28
+ if not os.path.isdir(root):
29
+ print(f"not a directory: {root} (set DROPBOX_DIR if your Dropbox lives elsewhere)",
30
+ file=sys.stderr)
31
+ return 1
32
+ total = 0
33
+ for dirpath, dirnames, filenames in os.walk(root):
34
+ dirnames[:] = [d for d in dirnames if not d.startswith(".") and d not in SKIP_DIRS]
35
+ for fn in sorted(filenames):
36
+ if fn.startswith(".") or fn.endswith(".dropbox.attr"):
37
+ continue
38
+ p = os.path.join(dirpath, fn)
39
+ print(json.dumps({"uri": f"dropbox://{os.path.relpath(p, base).replace(os.sep, "/")}", "path": p},
40
+ ensure_ascii=False))
41
+ total += 1
42
+ print(f"emitted {total} files under {sub or '/'} (indexer decides what it can read)",
43
+ file=sys.stderr)
44
+ return 0
45
+
46
+
47
+ if __name__ == "__main__":
48
+ sys.exit(main())
@@ -0,0 +1,203 @@
1
+ #!/usr/bin/env python3
2
+ """Bibliothèque source adapter: notion://<page-or-database-id> — Notion pages as text.
3
+
4
+ Env: NOTION_TOKEN (integration secret). Stdout = one JSON line per page:
5
+ {"uri": "notion://<page-id>", "title": <page title>, "text": <markdown-ish body>}.
6
+ Stdlib only; no dependencies. Community adapters follow this shape.
7
+
8
+ Text only, deliberately: Notion-hosted files/images carry signed URLs that
9
+ expire within an hour, so they are not stable corpus assets.
10
+ Sub-pages: child_page/child_database blocks contribute their TITLE only —
11
+ there is no workspace-wide crawl; index a sub-page's body via its own
12
+ notion://<id>.
13
+ """
14
+ import json
15
+ import os
16
+ import sys
17
+ import time
18
+ import urllib.error
19
+ import urllib.parse
20
+ import urllib.request
21
+
22
+ API = "https://api.notion.com/v1"
23
+ VERSION = "2022-06-28"
24
+ RATE_DELAY = 0.34 # Notion allows 3 requests/second
25
+ MAX_DEPTH = 8 # toggles nest; deeper than this is noise
26
+ SKIP_BLOCK_TYPES = { # never text; never try to decode them
27
+ "image", "video", "file", "pdf", "audio", "bookmark", "embed",
28
+ "breadcrumb", "table_of_contents", "unsupported", "synced_block",
29
+ }
30
+
31
+
32
+ def get(path, token, params=None, payload=None):
33
+ url = API + path + (("?" + urllib.parse.urlencode(params)) if params else "")
34
+ data = json.dumps(payload).encode() if payload is not None else None
35
+ for attempt in range(3): # transient 429 bursts get a Retry-After pass, not a dead source
36
+ time.sleep(RATE_DELAY)
37
+ req = urllib.request.Request(url, data=data, headers={
38
+ "Authorization": "Bearer " + token,
39
+ "Notion-Version": VERSION,
40
+ "Content-Type": "application/json",
41
+ }, method="POST" if data else "GET")
42
+ try:
43
+ return json.load(urllib.request.urlopen(req, timeout=45))
44
+ except urllib.error.HTTPError as e:
45
+ if e.code != 429 or attempt == 2:
46
+ raise
47
+ try:
48
+ e.read() # drain the socket before sleeping
49
+ except Exception:
50
+ pass
51
+ hdrs = getattr(e, "hdrs", None) or getattr(e, "headers", None) or {}
52
+ time.sleep(max(float(hdrs.get("Retry-After") or 1), RATE_DELAY))
53
+ raise RuntimeError("unreachable")
54
+
55
+
56
+ def rich_text(block_type_obj):
57
+ return "".join(t.get("plain_text", "") for t in block_type_obj.get("rich_text", []))
58
+
59
+
60
+ def block_lines(b, depth, token):
61
+ """One block -> (markdown lines, child block id to recurse into or None)."""
62
+ typ = b.get("type", "")
63
+ if typ in SKIP_BLOCK_TYPES:
64
+ return [], None
65
+ body = b.get(typ) or {}
66
+ text = rich_text(body)
67
+ prefix = {
68
+ "paragraph": "", "heading_1": "# ", "heading_2": "## ", "heading_3": "### ",
69
+ "bulleted_list_item": "- ", "numbered_list_item": "1. ",
70
+ "quote": "> ", "toggle": "",
71
+ }.get(typ)
72
+ if typ == "to_do":
73
+ return [("- [x] " if body.get("checked") else "- [ ] ") + text], b["id"] if b.get("has_children") else None
74
+ if typ == "code":
75
+ return ["```" + (body.get("language") or ""), text, "```"], None
76
+ if typ == "divider":
77
+ return ["---"], None
78
+ if typ == "table_row":
79
+ return [" | ".join("".join(t.get("plain_text", "") for t in cell) for cell in body.get("cells", []))], None
80
+ if typ in ("child_page", "child_database"):
81
+ return ["# " + (body.get("title") or "(untitled)")], None
82
+ if typ == "callout":
83
+ return ["> " + text], b["id"] if b.get("has_children") else None
84
+ if typ in ("table", "column_list", "column"):
85
+ # Containers: no text of their own, but their children are the content.
86
+ return [], b["id"] if b.get("has_children") else None
87
+ if prefix is not None:
88
+ return [prefix + text] if text else [], b["id"] if b.get("has_children") else None
89
+ return [], None # unknown type: ignore rather than fail the whole page
90
+
91
+
92
+ def page_text(page_id, token, depth=0):
93
+ """All blocks under a page/block, flattened to markdown lines."""
94
+ if depth > MAX_DEPTH:
95
+ return []
96
+ lines, cursor = [], None
97
+ while True:
98
+ params = {"page_size": 100}
99
+ if cursor:
100
+ params["start_cursor"] = cursor
101
+ resp = get(f"/blocks/{page_id}/children", token, params)
102
+ for b in resp.get("results", []):
103
+ sub, child = block_lines(b, depth, token)
104
+ lines.extend(sub)
105
+ if child:
106
+ lines.extend(page_text(child, token, depth + 1))
107
+ if not resp.get("has_more"):
108
+ break
109
+ cursor = resp.get("next_cursor")
110
+ return lines
111
+
112
+
113
+ def page_title(page):
114
+ for prop in (page.get("properties") or {}).values():
115
+ if prop.get("type") == "title":
116
+ # Title properties key the array "title", not "rich_text".
117
+ return "".join(t.get("plain_text", "") for t in prop.get("title", [])).strip() or "(untitled)"
118
+ return "(untitled)"
119
+
120
+
121
+ def page_properties(page):
122
+ """Non-title database properties as text lines — status/owner/dates are
123
+ content a user searches for, not metadata to discard."""
124
+ out = []
125
+ for key, prop in (page.get("properties") or {}).items():
126
+ typ = prop.get("type")
127
+ if typ == "title":
128
+ continue
129
+ value = None
130
+ if typ == "rich_text":
131
+ value = rich_text(prop)
132
+ elif typ in ("select", "status"):
133
+ value = (prop.get(typ) or {}).get("name")
134
+ elif typ == "multi_select":
135
+ value = ", ".join(o.get("name", "") for o in prop.get("multi_select", []))
136
+ elif typ == "date":
137
+ d = prop.get("date") or {}
138
+ value = d.get("start") + (" → " + d["end"] if d.get("end") else "") if d.get("start") else None
139
+ elif typ in ("url", "email", "phone_number"):
140
+ value = prop.get(typ)
141
+ elif typ == "number":
142
+ value = prop.get("number")
143
+ elif typ == "checkbox":
144
+ value = "yes" if prop.get("checkbox") else "no"
145
+ elif typ == "people":
146
+ value = ", ".join(p.get("name", "") for p in prop.get("people", []))
147
+ if value not in (None, "", []):
148
+ out.append(f"{key}: {value}")
149
+ return out
150
+
151
+
152
+ def emit_page(page, token):
153
+ title = page_title(page)
154
+ lines = page_properties(page) + page_text(page["id"], token)
155
+ text = "# " + title + "\n\n" + "\n".join(lines).strip()
156
+ if text.strip():
157
+ print(json.dumps({"uri": "notion://" + page["id"], "title": title, "text": text},
158
+ ensure_ascii=False))
159
+ return 1
160
+ return 0
161
+
162
+
163
+ def main():
164
+ if len(sys.argv) != 3 or sys.argv[1] != "fetch":
165
+ print("usage: notion fetch <page-or-database-id> (e.g. notion://0123abcd...)", file=sys.stderr)
166
+ return 2
167
+ token = os.environ.get("NOTION_TOKEN", "").strip()
168
+ if not token:
169
+ print("set NOTION_TOKEN in the server environment (a Notion integration secret)",
170
+ file=sys.stderr)
171
+ return 1
172
+ target = sys.argv[2].strip().replace("-", "")
173
+ try:
174
+ total = 0
175
+ cursor = None
176
+ try:
177
+ # A database query 404s for a plain page id — that is the disambiguation.
178
+ while True:
179
+ payload = {"page_size": 100}
180
+ if cursor:
181
+ payload["start_cursor"] = cursor
182
+ resp = get(f"/databases/{target}/query", token, payload=payload)
183
+ for page in resp.get("results", []):
184
+ total += emit_page(page, token)
185
+ if not resp.get("has_more"):
186
+ break
187
+ cursor = resp.get("next_cursor")
188
+ except urllib.error.HTTPError as e:
189
+ if e.code != 404:
190
+ raise
191
+ total += emit_page(get(f"/pages/{target}", token), token)
192
+ except urllib.error.HTTPError as e:
193
+ print(f"notion API HTTP {e.code}: {e.read()[:200].decode(errors='replace')}", file=sys.stderr)
194
+ return 1
195
+ except Exception as e: # URLError, timeout, json decode — one clear error, not a traceback
196
+ print(f"notion fetch failed: {e}", file=sys.stderr)
197
+ return 1
198
+ print(f"emitted {total} pages", file=sys.stderr)
199
+ return 0
200
+
201
+
202
+ if __name__ == "__main__":
203
+ sys.exit(main())
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env python3
2
+ """Bibliothèque source adapter: obsidian://<vault-path> — an Obsidian vault.
3
+
4
+ Emits {"uri", "path"} items for indexable files under the vault, skipping
5
+ Obsidian's own config/noise (.obsidian, .trash, .DS_Store, hidden dirs, .tmp).
6
+ Vault resolution order for the arg (the part after obsidian://):
7
+ 1. absolute or ~-expanded path as given
8
+ 2. $OBSIDIAN_VAULT + arg
9
+ Env: OBSIDIAN_VAULT (optional default vault). Indexable extensions = the server's.
10
+ """
11
+ import json
12
+ import os
13
+ import sys
14
+
15
+ SKIP_DIRS = {".obsidian", ".trash", ".git", ".smart-env", ".DS_Store"}
16
+ SKIP_EXT = {".tmp", ".bak", ".partial"}
17
+
18
+
19
+ def main():
20
+ if len(sys.argv) != 3 or sys.argv[1] != "fetch":
21
+ print("usage: obsidian fetch <vault-path> (e.g. obsidian://~/notes/vault)", file=sys.stderr)
22
+ return 2
23
+ sub = sys.argv[2]
24
+ candidates = []
25
+ if sub.startswith("/"):
26
+ candidates.append(sub)
27
+ if sub.startswith("~"):
28
+ candidates.append(os.path.expanduser(sub))
29
+ default = os.environ.get("OBSIDIAN_VAULT", "")
30
+ if default:
31
+ candidates.append(os.path.join(os.path.expanduser(default), sub.lstrip("/")))
32
+ root = next((c for c in candidates if os.path.isdir(c)), None)
33
+ if root is None:
34
+ print(f"vault not found: tried {candidates} (set OBSIDIAN_VAULT or pass an absolute path)",
35
+ file=sys.stderr)
36
+ return 1
37
+ total = 0
38
+ for dirpath, dirnames, filenames in os.walk(root):
39
+ dirnames[:] = [d for d in dirnames if not d.startswith(".") and d not in SKIP_DIRS]
40
+ for fn in sorted(filenames):
41
+ base, ext = os.path.splitext(fn)
42
+ if fn.startswith(".") or fn.endswith(".tmp") or ext.lower() in SKIP_EXT:
43
+ continue
44
+ p = os.path.join(dirpath, fn)
45
+ rel = os.path.relpath(p, root).replace(os.sep, "/")
46
+ print(json.dumps({"uri": f"obsidian://{rel}", "path": p}, ensure_ascii=False))
47
+ total += 1
48
+ print(f"emitted {total} indexable files from vault {root}", file=sys.stderr)
49
+ return 0
50
+
51
+
52
+ if __name__ == "__main__":
53
+ sys.exit(main())
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env python3
2
+ """Bibliothèque source adapter: pcloud://<path-in-drive> — pCloud assets via the
3
+ rclone FUSE mount (or any local mount point).
4
+
5
+ Env: PCLOUD_MOUNT (default: "~/pCloud Drive"). Item shape: {"uri", "path"} —
6
+ the indexer decodes/embeds real files itself. Every file is emitted; the indexer
7
+ classifies extensions itself and reports unsupported ones as skips.
8
+ """
9
+ import json
10
+ import os
11
+ import sys
12
+
13
+
14
+ def main():
15
+ if len(sys.argv) != 3 or sys.argv[1] != "fetch":
16
+ print("usage: pcloud fetch <path-inside-drive> (e.g. pcloud://Shared/wiki)", file=sys.stderr)
17
+ return 2
18
+ mount = os.environ.get("PCLOUD_MOUNT", "~/pCloud Drive")
19
+ mount = os.path.expanduser(mount)
20
+ sub = sys.argv[2]
21
+ if sub.startswith("/"): # accept both "Shard/x" and "/Shared/x"
22
+ sub = sub.lstrip("/")
23
+ root = os.path.join(mount, sub)
24
+ if not os.path.isdir(root):
25
+ print(f"not a directory: {root} (set PCLOUD_MOUNT if your mount differs)", file=sys.stderr)
26
+ return 1
27
+ total = 0
28
+ for dirpath, dirnames, filenames in os.walk(root):
29
+ dirnames[:] = [d for d in dirnames if not d.startswith(".") and d != ".corpus"]
30
+ for fn in sorted(filenames):
31
+ if fn.startswith("."):
32
+ continue
33
+ p = os.path.join(dirpath, fn)
34
+ print(json.dumps({"uri": f"pcloud://{os.path.relpath(p, mount).replace(os.sep, "/")}", "path": p},
35
+ ensure_ascii=False))
36
+ total += 1
37
+ print(f"emitted {total} indexable files under {sub}", file=sys.stderr)
38
+ return 0
39
+
40
+
41
+ if __name__ == "__main__":
42
+ sys.exit(main())
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env python3
2
+ """Bibliothèque source adapter: raindrop://bookmarks — Raindrop.io bookmarks as text items.
3
+
4
+ Env: RAINDROP_API_TOKEN (required). Stdout = one JSON line per bookmark.
5
+ Stdlib only; no dependencies. Community adapters follow this shape.
6
+ """
7
+ import json
8
+ import os
9
+ import sys
10
+ import urllib.request
11
+
12
+
13
+ def resolve_token():
14
+ return os.environ.get("RAINDROP_API_TOKEN", "").strip()
15
+
16
+
17
+ def main():
18
+ if len(sys.argv) != 3 or sys.argv[1] != "fetch":
19
+ print("usage: raindrop fetch <what> (e.g. raindrop://bookmarks)", file=sys.stderr)
20
+ return 2
21
+ token = resolve_token()
22
+ if not token:
23
+ print("set RAINDROP_API_TOKEN in the server environment", file=sys.stderr)
24
+ return 1
25
+ total = 0
26
+ page = -1 # raindrop pagination is 0-indexed; loop pre-increments
27
+ while True:
28
+ page += 1
29
+ url = f"https://api.raindrop.io/rest/v1/raindrops/0?perpage=50&page={page}"
30
+ req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"})
31
+ try:
32
+ resp = json.load(urllib.request.urlopen(req, timeout=30))
33
+ except Exception as e:
34
+ print(f"raindrop API page {page} failed: {e}", file=sys.stderr)
35
+ return 1
36
+ if resp.get("result") not in (0, True):
37
+ print(f"raindrop API error on page {page}: {resp.get('error')}", file=sys.stderr)
38
+ return 1
39
+ items = resp.get("items") or []
40
+ for d in items:
41
+ title = (d.get("title") or "").strip() or "(untitled)"
42
+ parts = [f"# {title}"]
43
+ if d.get("excerpt"):
44
+ parts.append(f"Excerpt: {d['excerpt']}")
45
+ if d.get("tags"):
46
+ parts.append("Tags: " + ", ".join(d["tags"]))
47
+ if d.get("note"):
48
+ parts.append(f"Note: {d['note']}")
49
+ if d.get("link"):
50
+ parts.append(f"URL: {d['link']}")
51
+ text = "\n\n".join(parts).strip()
52
+ if not text:
53
+ continue
54
+ item = {"uri": f"raindrop://{d['_id']}", "title": title, "text": text}
55
+ print(json.dumps(item, ensure_ascii=False))
56
+ total += 1
57
+ if len(items) < 50:
58
+ break
59
+ print(f"emitted {total} bookmarks", file=sys.stderr)
60
+ return 0
61
+
62
+
63
+ if __name__ == "__main__":
64
+ sys.exit(main())
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env python3
2
+ """Bibliothèque source adapter: rclone://<remote>:<path> — ANY rclone-configured
3
+ backend (Google Drive, OneDrive, S3, WebDAV, Dropbox, SFTP, …) in one adapter.
4
+
5
+ Mechanism: `rclone copy` the subtree into a persistent local cache, then emit
6
+ {"uri", "path"} items for indexable files (the server's native indexer decodes
7
+ and embeds them itself). The cache is persistent (default ~/.cache/bibliotheque/
8
+ rclone/<remote>/<path>) so thumbnails and re-indexing keep working afterwards.
9
+
10
+ Env: RCLONE_ADAPTER_CACHE (default ~/.cache/bibliotheque/rclone). rclone credentials
11
+ come from the server's rclone environment (config file / env), same as any
12
+ rclone invocation.
13
+ """
14
+ import json
15
+ import os
16
+ import subprocess
17
+ import sys
18
+
19
+ SKIP_DIRS = {".obsidian", ".trash", ".git"}
20
+
21
+
22
+ def main():
23
+ if len(sys.argv) != 3 or sys.argv[1] != "fetch":
24
+ print("usage: rclone fetch \"<remote>:<path>\" (e.g. rclone://gdrive:/notes)", file=sys.stderr)
25
+ return 2
26
+ target = sys.argv[2]
27
+ if ":" not in target:
28
+ print('target must be "<remote>:<path>", e.g. "gdrive:/notes"', file=sys.stderr)
29
+ return 1
30
+ remote, _, remote_path = target.partition(":")
31
+ # remote is joined into the cache path below, so it must be a bare remote
32
+ # name: "x/../../etc:y" would otherwise escape the cache directory.
33
+ if not remote or remote.startswith(".") or any(c in remote for c in ("/", "\\")):
34
+ print(f"invalid remote name {remote!r}: expected a bare rclone remote", file=sys.stderr)
35
+ return 1
36
+ remote_path = "/" + remote_path.lstrip("/")
37
+ cache = os.environ.get("RCLONE_ADAPTER_CACHE",
38
+ os.path.expanduser("~/.cache/bibliotheque/rclone"))
39
+ # Containment, not just the remote name: "../" segments (and Windows
40
+ # backslashes) must not let remote_path escape the per-remote cache dir.
41
+ base = os.path.realpath(os.path.join(cache, remote))
42
+ dest = os.path.realpath(os.path.join(base, remote_path.replace("\\", "/").lstrip("/")))
43
+ if dest != base and os.path.commonpath([base, dest]) != base:
44
+ print(f"invalid remote path {remote_path!r}: escapes the cache directory", file=sys.stderr)
45
+ return 1
46
+ os.makedirs(dest, exist_ok=True)
47
+ # rclone copy: parallel, respects remotes' own config/env; exits non-zero on
48
+ # partial failure with a summary on stderr.
49
+ cp = subprocess.run(["rclone", "copy", f"{remote}:{remote_path}", dest,
50
+ "--transfers", "8", "--checkers", "8"],
51
+ capture_output=True, text=True)
52
+ for line in cp.stderr.strip().splitlines()[-3:]:
53
+ print(f"rclone: {line}", file=sys.stderr)
54
+ if cp.returncode != 0:
55
+ print(f"rclone copy failed (exit {cp.returncode})", file=sys.stderr)
56
+ return 1
57
+ total = 0
58
+ for dirpath, dirnames, filenames in os.walk(dest):
59
+ dirnames[:] = [d for d in dirnames if not d.startswith(".") and d not in SKIP_DIRS]
60
+ for fn in sorted(filenames):
61
+ if fn.startswith("."):
62
+ continue
63
+ p = os.path.join(dirpath, fn)
64
+ rel = os.path.relpath(p, os.path.join(cache, remote)).replace(os.sep, "/")
65
+ print(json.dumps({"uri": f"rclone://{remote}/{rel}", "path": p},
66
+ ensure_ascii=False))
67
+ total += 1
68
+ print(f"emitted {total} indexable files from {remote}:{remote_path} (cache {dest})",
69
+ file=sys.stderr)
70
+ return 0
71
+
72
+
73
+ if __name__ == "__main__":
74
+ sys.exit(main())
@@ -0,0 +1,4 @@
1
+ # Bibliothèque corpus configuration.
2
+ # Copy to bibliotheque-config.yaml next to the plugin __init__.py.
3
+ # Precedence: bibliotheque-config.yaml `root:` > BIBLIOTHEQUE_ROOT env > default ~/.bibliotheque
4
+ root: ~/.bibliotheque
@@ -0,0 +1,44 @@
1
+ """Corpus root resolution, shared by the plugin entry and the tool layer.
2
+
3
+ Kept dependency-free on purpose: the plugin __init__ must be able to compute a
4
+ root without importing numpy/onnxruntime/transformers, and the stdio MCP lane
5
+ must resolve the same root as the native lane.
6
+
7
+ Precedence: $BIBLIOTHEQUE_CONFIG file > plugin/package config file > $PLUGIN_ROOT
8
+ config file > $BIBLIOTHEQUE_ROOT > ~/.bibliotheque. The last two are only consulted when
9
+ no config file yields a root.
10
+ """
11
+ import os
12
+
13
+ _PKG_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
+
15
+
16
+ def config_root(base_dir: str | None = None) -> str:
17
+ """The `root:` value from bibliotheque-config.yaml, or "" when there is none.
18
+
19
+ # ponytail: flat `root:` line parse — no yaml dep on the stdio spawn path;
20
+ # switch to yaml.safe_load if the config ever grows beyond one key.
21
+ """
22
+ candidates = []
23
+ explicit = os.environ.get("BIBLIOTHEQUE_CONFIG")
24
+ if explicit:
25
+ candidates.append(explicit)
26
+ candidates.append(os.path.join(base_dir or _PKG_DIR, "bibliotheque-config.yaml"))
27
+ candidates.append(os.path.join(base_dir or _PKG_DIR, "mediarag-config.yaml")) # legacy name, pre-rename installs
28
+ plugin_root = os.environ.get("PLUGIN_ROOT")
29
+ if plugin_root:
30
+ candidates.append(os.path.join(plugin_root, "bibliotheque-config.yaml"))
31
+ candidates.append(os.path.join(plugin_root, "mediarag-config.yaml")) # legacy name, pre-rename installs
32
+ for path in candidates:
33
+ try:
34
+ with open(path, encoding="utf-8") as fh:
35
+ for line in fh:
36
+ if line.strip().startswith("root:"):
37
+ return line.split(":", 1)[1].strip().strip("'\"")
38
+ except OSError:
39
+ continue
40
+ return ""
41
+
42
+
43
+ def default_root(base_dir: str | None = None) -> str:
44
+ return config_root(base_dir) or os.environ.get("BIBLIOTHEQUE_ROOT") or os.path.expanduser("~/.bibliotheque")