cribsheet 0.23.0.dev2__py3-none-any.whl → 0.23.0.dev3__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.
- crib/cli.py +44 -0
- crib/gensetup.py +478 -0
- {cribsheet-0.23.0.dev2.dist-info → cribsheet-0.23.0.dev3.dist-info}/METADATA +25 -2
- {cribsheet-0.23.0.dev2.dist-info → cribsheet-0.23.0.dev3.dist-info}/RECORD +6 -5
- {cribsheet-0.23.0.dev2.dist-info → cribsheet-0.23.0.dev3.dist-info}/WHEEL +0 -0
- {cribsheet-0.23.0.dev2.dist-info → cribsheet-0.23.0.dev3.dist-info}/entry_points.txt +0 -0
crib/cli.py
CHANGED
|
@@ -2258,6 +2258,22 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
2258
2258
|
|
|
2259
2259
|
# internal: invoked by git as the cribnote merge driver (DESIGN §14). No
|
|
2260
2260
|
# help= → kept out of the listed commands (still a valid hidden subcommand).
|
|
2261
|
+
n_gen = sub.add_parser(
|
|
2262
|
+
"generate", help="set up and check LLM generation (descriptions, summaries)"
|
|
2263
|
+
)
|
|
2264
|
+
gensub = n_gen.add_subparsers(dest="generate_cmd", required=True)
|
|
2265
|
+
_gs = gensub.add_parser(
|
|
2266
|
+
"setup",
|
|
2267
|
+
help="detect the providers this machine has, pick one, write the config",
|
|
2268
|
+
)
|
|
2269
|
+
_gs.add_argument("--provider", help="use this detected provider (skips the prompt)")
|
|
2270
|
+
_gs.add_argument("--model", help="the model to use (skips the prompt)")
|
|
2271
|
+
_gs.add_argument("--mode", choices=("on", "explicit", "off"),
|
|
2272
|
+
help="when crib may generate (see [generate] mode)")
|
|
2273
|
+
_gs.add_argument("--yes", action="store_true",
|
|
2274
|
+
help="write without asking (defaults for anything not given)")
|
|
2275
|
+
gensub.add_parser("test", help="one small call per purpose, to check the setup")
|
|
2276
|
+
|
|
2261
2277
|
n_store = sub.add_parser("store", help="the vector store (DuckDB)")
|
|
2262
2278
|
storesub = n_store.add_subparsers(dest="store_cmd", required=True)
|
|
2263
2279
|
storesub.add_parser(
|
|
@@ -4001,6 +4017,30 @@ def _user_errors() -> tuple[type[BaseException], ...]:
|
|
|
4001
4017
|
return (*out, ToolError)
|
|
4002
4018
|
|
|
4003
4019
|
|
|
4020
|
+
def _generate_cmd(args: Any) -> int:
|
|
4021
|
+
from . import gensetup
|
|
4022
|
+
from .config import Config
|
|
4023
|
+
from .paths import Paths
|
|
4024
|
+
|
|
4025
|
+
paths = Paths.resolve()
|
|
4026
|
+
if args.generate_cmd == "setup":
|
|
4027
|
+
return gensetup.run_setup(
|
|
4028
|
+
paths, gensetup.detect(), ask=input, say=print, assume_yes=args.yes,
|
|
4029
|
+
pick=args.provider, model=args.model, mode=args.mode)
|
|
4030
|
+
cfg = Config.load(paths.config_file).generate
|
|
4031
|
+
print(f"generation mode: {cfg.resolved_mode()}"
|
|
4032
|
+
+ (f" · providers: {cfg.config} (profile {cfg.profile})" if cfg.config
|
|
4033
|
+
else " · no models config: the inline [generate] provider"))
|
|
4034
|
+
rows = gensetup.test_purposes(cfg)
|
|
4035
|
+
for r in rows:
|
|
4036
|
+
mark = "ok " if r["ok"] else "FAIL"
|
|
4037
|
+
print(f" {mark} {r['purpose']:<10} {r['seconds']:>5.1f}s"
|
|
4038
|
+
+ (f" {r['error']}" if r.get("error") else ""))
|
|
4039
|
+
if args.json:
|
|
4040
|
+
print(json.dumps(rows, indent=2))
|
|
4041
|
+
return 0 if all(r["ok"] for r in rows) else 1
|
|
4042
|
+
|
|
4043
|
+
|
|
4004
4044
|
def main(argv: list[str] | None = None) -> int:
|
|
4005
4045
|
import sys as _sys
|
|
4006
4046
|
|
|
@@ -4020,6 +4060,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
4020
4060
|
if args.cmd == "info":
|
|
4021
4061
|
cmd_info(args.json)
|
|
4022
4062
|
return 0
|
|
4063
|
+
if args.cmd == "generate":
|
|
4064
|
+
# Local and interactive: it reads and writes this machine's config files
|
|
4065
|
+
# and talks to the providers directly, never through the daemon.
|
|
4066
|
+
return _generate_cmd(args)
|
|
4023
4067
|
if args.cmd == "store" and args.store_cmd == "install-extensions":
|
|
4024
4068
|
# Runs locally (no daemon, no store file): it only fills crib's own
|
|
4025
4069
|
# extension directory, which every crib DuckDB connection reads.
|
crib/gensetup.py
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
"""`crib generate setup` / `crib generate test`: get LLM generation configured.
|
|
2
|
+
|
|
3
|
+
crib generates code-symbol descriptions and keywords (`elaborate`), note
|
|
4
|
+
summaries (`summarize`) and note rewrites (`distill`) through an llmkit
|
|
5
|
+
providers file, `~/.config/crib/models.toml`. Writing that file by hand needs
|
|
6
|
+
knowledge a new user doesn't have (adapters, key variables, profile keys,
|
|
7
|
+
provider quirks), so `setup`:
|
|
8
|
+
|
|
9
|
+
1. detects what this machine has (API keys in the environment, a local
|
|
10
|
+
OpenAI-compatible server, the `claude` CLI, providers already defined in
|
|
11
|
+
zsh-ai's models.toml);
|
|
12
|
+
2. lets you pick one, and a model;
|
|
13
|
+
3. shows the changes to models.toml and config.toml as a diff, backs both up,
|
|
14
|
+
and writes them on confirmation (known quirks built in);
|
|
15
|
+
4. offers `test`: one small call per purpose, so a bad key or a provider that
|
|
16
|
+
ignores structured output shows at setup, not as blank descriptions.
|
|
17
|
+
|
|
18
|
+
CLI only. Nothing here runs unless a person asks for it.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import difflib
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import shutil
|
|
28
|
+
import time
|
|
29
|
+
import urllib.request
|
|
30
|
+
from collections.abc import Callable
|
|
31
|
+
from dataclasses import dataclass, field
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
# What crib asks its providers for (`[profiles.<name>].<purpose>`).
|
|
36
|
+
PURPOSES = ("elaborate", "summarize", "distill")
|
|
37
|
+
PROFILE = "crib"
|
|
38
|
+
|
|
39
|
+
# A local OpenAI-compatible server on the usual ports.
|
|
40
|
+
LOCAL_SERVERS = (
|
|
41
|
+
("local-ollama", "http://localhost:11434/v1", "Ollama on this machine"),
|
|
42
|
+
("local-llama-swap", "http://localhost:11435/v1", "llama-swap on this machine"),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Candidate:
|
|
48
|
+
"""A provider setup can write: its name in models.toml, how it is shown,
|
|
49
|
+
its `[providers.<name>]` fields, and the models to offer (empty: ask)."""
|
|
50
|
+
|
|
51
|
+
name: str
|
|
52
|
+
label: str
|
|
53
|
+
fields: dict[str, Any]
|
|
54
|
+
models: list[str] = field(default_factory=list)
|
|
55
|
+
default_model: str = ""
|
|
56
|
+
source: str = "detected"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _openai_models(
|
|
60
|
+
endpoint: str, key: str | None, timeout: float = 4.0
|
|
61
|
+
) -> list[str] | None:
|
|
62
|
+
"""The model ids an OpenAI-compatible endpoint lists, or None when it
|
|
63
|
+
doesn't answer."""
|
|
64
|
+
req = urllib.request.Request(endpoint.rstrip("/") + "/models")
|
|
65
|
+
if key:
|
|
66
|
+
req.add_header("Authorization", f"Bearer {key}")
|
|
67
|
+
try:
|
|
68
|
+
with urllib.request.urlopen(req, timeout=timeout) as r: # noqa: S310 — fixed hosts
|
|
69
|
+
data = json.loads(r.read().decode("utf-8", "replace"))
|
|
70
|
+
except Exception: # noqa: BLE001 — not there, or not that kind of server
|
|
71
|
+
return None
|
|
72
|
+
return sorted(str(m.get("id")) for m in data.get("data", []) if m.get("id"))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def detect(
|
|
76
|
+
env: dict[str, str] | None = None,
|
|
77
|
+
list_models: Callable[[str, str | None], list[str] | None] = _openai_models,
|
|
78
|
+
which: Callable[[str], str | None] = shutil.which,
|
|
79
|
+
zsh_ai: Path | None = None,
|
|
80
|
+
) -> list[Candidate]:
|
|
81
|
+
"""Every provider this machine could use, best first; the Claude CLI last
|
|
82
|
+
(it runs on your Claude subscription)."""
|
|
83
|
+
env = dict(os.environ if env is None else env)
|
|
84
|
+
out: list[Candidate] = []
|
|
85
|
+
if env.get("OLLAMA_API_KEY"):
|
|
86
|
+
models = list_models("https://ollama.com/v1", env["OLLAMA_API_KEY"]) or []
|
|
87
|
+
out.append(
|
|
88
|
+
Candidate(
|
|
89
|
+
"ollama-cloud",
|
|
90
|
+
"Ollama Cloud (OLLAMA_API_KEY is set)",
|
|
91
|
+
{
|
|
92
|
+
"adapter": "openai-compatible",
|
|
93
|
+
"endpoint": "https://ollama.com/v1",
|
|
94
|
+
"api_key_env": "OLLAMA_API_KEY",
|
|
95
|
+
"max_tokens": 8192,
|
|
96
|
+
# Ollama Cloud ignores response_format: structured output rides
|
|
97
|
+
# a forced tool call (llmkit >= 0.2.2)
|
|
98
|
+
"structured": "tool",
|
|
99
|
+
},
|
|
100
|
+
models,
|
|
101
|
+
"glm-5.3-flash",
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
if env.get("OPENCODE_API_KEY"):
|
|
105
|
+
models = (
|
|
106
|
+
list_models("https://opencode.ai/zen/v1/", env["OPENCODE_API_KEY"]) or []
|
|
107
|
+
)
|
|
108
|
+
out.append(
|
|
109
|
+
Candidate(
|
|
110
|
+
"opencode-zen",
|
|
111
|
+
"opencode zen (OPENCODE_API_KEY is set)",
|
|
112
|
+
{
|
|
113
|
+
"adapter": "openai-compatible",
|
|
114
|
+
"endpoint": "https://opencode.ai/zen/v1/",
|
|
115
|
+
"api_key_env": "OPENCODE_API_KEY",
|
|
116
|
+
"max_tokens": 8192,
|
|
117
|
+
},
|
|
118
|
+
models,
|
|
119
|
+
"qwen3.5-plus",
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
if env.get("ANTHROPIC_API_KEY"):
|
|
123
|
+
out.append(
|
|
124
|
+
Candidate(
|
|
125
|
+
"anthropic",
|
|
126
|
+
"Anthropic API (ANTHROPIC_API_KEY is set)",
|
|
127
|
+
{
|
|
128
|
+
"adapter": "anthropic",
|
|
129
|
+
"api_key_env": "ANTHROPIC_API_KEY",
|
|
130
|
+
"max_tokens": 8192,
|
|
131
|
+
},
|
|
132
|
+
[],
|
|
133
|
+
"claude-haiku-5-5",
|
|
134
|
+
)
|
|
135
|
+
)
|
|
136
|
+
for var in ("GEMINI_API_KEY", "GOOGLE_API_KEY"):
|
|
137
|
+
if env.get(var):
|
|
138
|
+
out.append(
|
|
139
|
+
Candidate(
|
|
140
|
+
"google",
|
|
141
|
+
f"Google Gemini ({var} is set)",
|
|
142
|
+
{"adapter": "google", "api_key_env": var, "max_tokens": 8192},
|
|
143
|
+
[],
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
break
|
|
147
|
+
for name, endpoint, label in LOCAL_SERVERS:
|
|
148
|
+
models = list_models(endpoint, None)
|
|
149
|
+
if models is not None:
|
|
150
|
+
out.append(
|
|
151
|
+
Candidate(
|
|
152
|
+
name,
|
|
153
|
+
f"{label} ({endpoint})",
|
|
154
|
+
{
|
|
155
|
+
"adapter": "openai-compatible",
|
|
156
|
+
"endpoint": endpoint,
|
|
157
|
+
"api_key": "local",
|
|
158
|
+
"max_tokens": 8192,
|
|
159
|
+
},
|
|
160
|
+
models,
|
|
161
|
+
)
|
|
162
|
+
)
|
|
163
|
+
claude = (
|
|
164
|
+
Candidate(
|
|
165
|
+
"claude",
|
|
166
|
+
"Claude CLI via the Agent SDK (uses your Claude subscription; "
|
|
167
|
+
"needs llmkit's claude extra)",
|
|
168
|
+
{"adapter": "claude_code"},
|
|
169
|
+
[],
|
|
170
|
+
"claude-haiku-5-5",
|
|
171
|
+
)
|
|
172
|
+
if which("claude")
|
|
173
|
+
else None
|
|
174
|
+
)
|
|
175
|
+
taken = {c.name for c in out} | ({claude.name} if claude else set())
|
|
176
|
+
out += _from_zsh_ai(
|
|
177
|
+
zsh_ai
|
|
178
|
+
if zsh_ai is not None
|
|
179
|
+
else Path.home() / ".config" / "zsh-ai" / "models.toml",
|
|
180
|
+
taken,
|
|
181
|
+
)
|
|
182
|
+
if claude:
|
|
183
|
+
out.append(claude) # last: it spends your subscription
|
|
184
|
+
return out
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _with_quirks(fields: dict[str, Any]) -> dict[str, Any]:
|
|
188
|
+
"""What a provider needs to serve crib's bulk structured generation, added
|
|
189
|
+
to fields written elsewhere: Ollama Cloud ignores response_format (so the
|
|
190
|
+
structured channel is a forced tool call), and a cap under 8192 tokens
|
|
191
|
+
truncates a batch of descriptions mid-JSON."""
|
|
192
|
+
out = dict(fields)
|
|
193
|
+
if "ollama.com" in str(out.get("endpoint", "")):
|
|
194
|
+
out.setdefault("structured", "tool")
|
|
195
|
+
if isinstance(out.get("max_tokens"), int) and out["max_tokens"] < 8192:
|
|
196
|
+
out["max_tokens"] = 8192
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _from_zsh_ai(path: Path, taken: set[str]) -> list[Candidate]:
|
|
201
|
+
"""zsh-ai's own providers, offered for import as they are written there."""
|
|
202
|
+
import tomllib
|
|
203
|
+
|
|
204
|
+
try:
|
|
205
|
+
data = tomllib.loads(path.read_text())
|
|
206
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
207
|
+
return []
|
|
208
|
+
out = []
|
|
209
|
+
for name, fields in sorted((data.get("providers") or {}).items()):
|
|
210
|
+
if not isinstance(fields, dict) or name in taken or "fim" in name:
|
|
211
|
+
continue # taken, or fill-in-the-middle only (not a chat model)
|
|
212
|
+
model = str(fields.get("model") or "")
|
|
213
|
+
out.append(
|
|
214
|
+
Candidate(
|
|
215
|
+
name,
|
|
216
|
+
f"{name} from zsh-ai's models.toml ({fields.get('adapter', '?')}"
|
|
217
|
+
+ (f", {model}" if model else "")
|
|
218
|
+
+ ")",
|
|
219
|
+
_with_quirks({k: v for k, v in fields.items() if k != "model"}),
|
|
220
|
+
[],
|
|
221
|
+
model,
|
|
222
|
+
"zsh-ai",
|
|
223
|
+
)
|
|
224
|
+
)
|
|
225
|
+
return out
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# ── writing the files ──────────────────────────────────────────────────────
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _toml_value(v: Any) -> str:
|
|
232
|
+
if isinstance(v, bool):
|
|
233
|
+
return "true" if v else "false"
|
|
234
|
+
if isinstance(v, (int, float)):
|
|
235
|
+
return repr(v)
|
|
236
|
+
if isinstance(v, dict):
|
|
237
|
+
return (
|
|
238
|
+
"{ "
|
|
239
|
+
+ ", ".join(f"{json.dumps(k)} = {_toml_value(x)}" for k, x in v.items())
|
|
240
|
+
+ " }"
|
|
241
|
+
)
|
|
242
|
+
if isinstance(v, (list, tuple)):
|
|
243
|
+
return "[" + ", ".join(_toml_value(x) for x in v) + "]"
|
|
244
|
+
return json.dumps(str(v)) # a TOML basic string is JSON-escaped
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def set_keys(text: str, section: str, values: dict[str, Any], comment: str = "") -> str:
|
|
248
|
+
"""`text` with `values` set inside `[section]`: an existing `key = …` line is
|
|
249
|
+
replaced in place, a missing key added after the header, and a missing
|
|
250
|
+
section appended. Everything else (comments, other keys) is left as is."""
|
|
251
|
+
lines = text.splitlines()
|
|
252
|
+
header = re.compile(r"^\s*\[" + re.escape(section) + r"\]\s*(#.*)?$")
|
|
253
|
+
start = next((i for i, ln in enumerate(lines) if header.match(ln)), None)
|
|
254
|
+
if start is None:
|
|
255
|
+
block = (
|
|
256
|
+
([""] if text.strip() else [])
|
|
257
|
+
+ ([f"# {comment}"] if comment else [])
|
|
258
|
+
+ [f"[{section}]"]
|
|
259
|
+
+ [f"{k} = {_toml_value(v)}" for k, v in values.items()]
|
|
260
|
+
)
|
|
261
|
+
return "\n".join(lines + block) + "\n"
|
|
262
|
+
end = next(
|
|
263
|
+
(i for i in range(start + 1, len(lines)) if re.match(r"^\s*\[", lines[i])),
|
|
264
|
+
len(lines),
|
|
265
|
+
)
|
|
266
|
+
pending = dict(values)
|
|
267
|
+
for i in range(start + 1, end):
|
|
268
|
+
m = re.match(r"^\s*([A-Za-z0-9_-]+)\s*=", lines[i])
|
|
269
|
+
if m and m.group(1) in pending:
|
|
270
|
+
lines[i] = f"{m.group(1)} = {_toml_value(pending.pop(m.group(1)))}"
|
|
271
|
+
lines[start + 1 : start + 1] = [
|
|
272
|
+
f"{k} = {_toml_value(v)}" for k, v in pending.items()
|
|
273
|
+
]
|
|
274
|
+
return "\n".join(lines) + "\n"
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@dataclass
|
|
278
|
+
class Change:
|
|
279
|
+
path: Path
|
|
280
|
+
before: str
|
|
281
|
+
after: str
|
|
282
|
+
|
|
283
|
+
def diff(self) -> str:
|
|
284
|
+
return "".join(
|
|
285
|
+
difflib.unified_diff(
|
|
286
|
+
self.before.splitlines(keepends=True),
|
|
287
|
+
self.after.splitlines(keepends=True),
|
|
288
|
+
fromfile=f"{self.path} (now)",
|
|
289
|
+
tofile=f"{self.path} (after setup)",
|
|
290
|
+
)
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def plan(
|
|
295
|
+
config_file: Path, models_file: Path, cand: Candidate, model: str, mode: str | None
|
|
296
|
+
) -> list[Change]:
|
|
297
|
+
"""The edits that make `cand` crib's provider for every purpose."""
|
|
298
|
+
before_models = models_file.read_text() if models_file.exists() else ""
|
|
299
|
+
models = before_models or (
|
|
300
|
+
"# crib's LLM providers (llmkit format), written by `crib generate setup`.\n"
|
|
301
|
+
"# crib asks for three purposes: elaborate (code descriptions and\n"
|
|
302
|
+
"# keywords), summarize (note summaries) and distill (note rewrites).\n"
|
|
303
|
+
)
|
|
304
|
+
fields = {**cand.fields, **({"model": model} if model else {})}
|
|
305
|
+
models = set_keys(models, f"providers.{cand.name}", fields, comment=cand.label)
|
|
306
|
+
models = set_keys(
|
|
307
|
+
models,
|
|
308
|
+
f"profiles.{PROFILE}",
|
|
309
|
+
{p: cand.name for p in PURPOSES},
|
|
310
|
+
comment="which provider crib uses for each purpose",
|
|
311
|
+
)
|
|
312
|
+
before_cfg = config_file.read_text() if config_file.exists() else ""
|
|
313
|
+
gen: dict[str, Any] = {"config": _home_relative(models_file), "profile": PROFILE}
|
|
314
|
+
if mode:
|
|
315
|
+
gen["mode"] = mode
|
|
316
|
+
cfg = set_keys(before_cfg, "generate", gen)
|
|
317
|
+
return [
|
|
318
|
+
c
|
|
319
|
+
for c in (
|
|
320
|
+
Change(models_file, before_models, models),
|
|
321
|
+
Change(config_file, before_cfg, cfg),
|
|
322
|
+
)
|
|
323
|
+
if c.before != c.after
|
|
324
|
+
]
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _home_relative(p: Path) -> str:
|
|
328
|
+
home = str(Path.home())
|
|
329
|
+
s = str(p)
|
|
330
|
+
return "~" + s[len(home) :] if s.startswith(home + os.sep) else s
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def apply(changes: list[Change], backup_dir: Path) -> list[Path]:
|
|
334
|
+
"""Write `changes`, each existing file backed up first under `backup_dir`
|
|
335
|
+
(not beside it: the config may live in a dotfiles repo). Symlinks are
|
|
336
|
+
written through, so a linked config is edited where it lives."""
|
|
337
|
+
stamp = time.strftime("%Y%m%d-%H%M%S")
|
|
338
|
+
backups = []
|
|
339
|
+
for c in changes:
|
|
340
|
+
if c.before:
|
|
341
|
+
backup_dir.mkdir(parents=True, exist_ok=True)
|
|
342
|
+
b = backup_dir / f"{c.path.name}.{stamp}"
|
|
343
|
+
b.write_text(c.before)
|
|
344
|
+
backups.append(b)
|
|
345
|
+
target = c.path.resolve() if c.path.is_symlink() else c.path
|
|
346
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
347
|
+
target.write_text(c.after)
|
|
348
|
+
return backups
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
# ── test ───────────────────────────────────────────────────────────────────
|
|
352
|
+
|
|
353
|
+
_SCHEMA = {
|
|
354
|
+
"type": "object",
|
|
355
|
+
"properties": {"ok": {"type": "boolean"}},
|
|
356
|
+
"required": ["ok"],
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def test_purposes(gen_cfg: Any) -> list[dict[str, Any]]:
|
|
361
|
+
"""One small call per purpose: structured for elaborate/summarize (what
|
|
362
|
+
crib's bulk generation uses), plain for distill."""
|
|
363
|
+
from .generate import generate, generate_structured
|
|
364
|
+
|
|
365
|
+
rows = []
|
|
366
|
+
for purpose in PURPOSES:
|
|
367
|
+
row: dict[str, Any] = {"purpose": purpose}
|
|
368
|
+
t0 = time.monotonic()
|
|
369
|
+
try:
|
|
370
|
+
if purpose == "distill":
|
|
371
|
+
text = generate(gen_cfg, "Answer in one word.", "Say ok.", purpose)
|
|
372
|
+
row["ok"] = bool(text.strip())
|
|
373
|
+
else:
|
|
374
|
+
data = generate_structured(
|
|
375
|
+
gen_cfg,
|
|
376
|
+
"Reply with JSON matching the schema.",
|
|
377
|
+
'Return {"ok": true}.',
|
|
378
|
+
_SCHEMA,
|
|
379
|
+
purpose=purpose,
|
|
380
|
+
schema_name="check",
|
|
381
|
+
)
|
|
382
|
+
row["ok"] = isinstance(data, dict) and data.get("ok") is True
|
|
383
|
+
if not row["ok"]:
|
|
384
|
+
row["error"] = f"structured reply did not match: {data!r}"[:200]
|
|
385
|
+
except Exception as e: # noqa: BLE001 — reported, per purpose
|
|
386
|
+
row["ok"] = False
|
|
387
|
+
row["error"] = str(e)[:300]
|
|
388
|
+
row["seconds"] = round(time.monotonic() - t0, 1)
|
|
389
|
+
rows.append(row)
|
|
390
|
+
return rows
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
# ── the interactive flow ───────────────────────────────────────────────────
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def run_setup(
|
|
397
|
+
paths: Any,
|
|
398
|
+
candidates: list[Candidate],
|
|
399
|
+
ask: Callable[[str], str],
|
|
400
|
+
say: Callable[[str], None],
|
|
401
|
+
assume_yes: bool = False,
|
|
402
|
+
pick: str | None = None,
|
|
403
|
+
model: str | None = None,
|
|
404
|
+
mode: str | None = None,
|
|
405
|
+
) -> int:
|
|
406
|
+
"""Pick a candidate (and model), show the diff, write on confirmation."""
|
|
407
|
+
if not candidates:
|
|
408
|
+
say(
|
|
409
|
+
"No provider found on this machine: set an API key (OLLAMA_API_KEY, "
|
|
410
|
+
"OPENCODE_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY), run a local "
|
|
411
|
+
"OpenAI-compatible server, or install the claude CLI, then run this again."
|
|
412
|
+
)
|
|
413
|
+
return 1
|
|
414
|
+
if pick:
|
|
415
|
+
chosen = next((c for c in candidates if c.name == pick), None)
|
|
416
|
+
if chosen is None:
|
|
417
|
+
say(f"no candidate {pick!r}: found {[c.name for c in candidates]}")
|
|
418
|
+
return 1
|
|
419
|
+
else:
|
|
420
|
+
say("Generation providers found on this machine:")
|
|
421
|
+
for i, c in enumerate(candidates, 1):
|
|
422
|
+
say(f" {i}. {c.label}")
|
|
423
|
+
n = ask(f"Use which? [1-{len(candidates)}] ").strip() or "1"
|
|
424
|
+
if not n.isdigit() or not 1 <= int(n) <= len(candidates):
|
|
425
|
+
say("nothing chosen; no changes")
|
|
426
|
+
return 1
|
|
427
|
+
chosen = candidates[int(n) - 1]
|
|
428
|
+
if model is None:
|
|
429
|
+
if chosen.models:
|
|
430
|
+
say(f"Models at {chosen.name}:")
|
|
431
|
+
for i, m in enumerate(chosen.models[:30], 1):
|
|
432
|
+
say(f" {i}. {m}")
|
|
433
|
+
default = chosen.default_model or (chosen.models[0] if chosen.models else "")
|
|
434
|
+
got = (
|
|
435
|
+
""
|
|
436
|
+
if assume_yes
|
|
437
|
+
else ask(f"Model{f' [{default}]' if default else ''}: ").strip()
|
|
438
|
+
)
|
|
439
|
+
if got.isdigit() and chosen.models and 1 <= int(got) <= len(chosen.models[:30]):
|
|
440
|
+
got = chosen.models[int(got) - 1]
|
|
441
|
+
model = got or default
|
|
442
|
+
if not model and chosen.fields.get("adapter") != "claude_code":
|
|
443
|
+
say("a model is needed; no changes")
|
|
444
|
+
return 1
|
|
445
|
+
if mode is None and not assume_yes:
|
|
446
|
+
got = (
|
|
447
|
+
ask(
|
|
448
|
+
"Generate in the background as code and notes change (on), or only "
|
|
449
|
+
"when you run a verb that asks (explicit)? [on] "
|
|
450
|
+
)
|
|
451
|
+
.strip()
|
|
452
|
+
.lower()
|
|
453
|
+
)
|
|
454
|
+
mode = got or "on"
|
|
455
|
+
if mode not in (None, "on", "explicit", "off"):
|
|
456
|
+
say(f"unknown mode {mode!r}: on, explicit or off")
|
|
457
|
+
return 1
|
|
458
|
+
models_file = paths.config_dir / "models.toml"
|
|
459
|
+
changes = plan(paths.config_file, models_file, chosen, model, mode)
|
|
460
|
+
if not changes:
|
|
461
|
+
say("Already set up this way; nothing to change.")
|
|
462
|
+
return 0
|
|
463
|
+
for c in changes:
|
|
464
|
+
say(c.diff())
|
|
465
|
+
if not assume_yes and ask("Write these changes? [y/N] ").strip().lower() not in (
|
|
466
|
+
"y",
|
|
467
|
+
"yes",
|
|
468
|
+
):
|
|
469
|
+
say("no changes written")
|
|
470
|
+
return 1
|
|
471
|
+
backups = apply(changes, paths.index_dir / "config-backups")
|
|
472
|
+
for b in backups:
|
|
473
|
+
say(f"backed up to {b}")
|
|
474
|
+
say(
|
|
475
|
+
"Done. Check it with `crib generate test`; a running daemon picks the "
|
|
476
|
+
"new provider up on its next restart."
|
|
477
|
+
)
|
|
478
|
+
return 0
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: cribsheet
|
|
3
|
-
Version: 0.23.0-
|
|
3
|
+
Version: 0.23.0-dev3
|
|
4
4
|
Summary: Local MCP server: markdown memory with a DuckDB embedding index
|
|
5
5
|
Requires-Python: >=3.13
|
|
6
6
|
Requires-Dist: duckdb<3,>=2.0
|
|
@@ -160,7 +160,30 @@ Prefer to wire it by hand? Copy [`CLAUDE.md.example`](CLAUDE.md.example) into yo
|
|
|
160
160
|
global `$CLAUDE_CONFIG_DIR/CLAUDE.md` — that one-line directive is what keeps the
|
|
161
161
|
habit in context (tool descriptions alone load too late to form it).
|
|
162
162
|
|
|
163
|
-
**3 —
|
|
163
|
+
**3 — Set up generation (recommended).** crib uses an LLM to write a one-line
|
|
164
|
+
description and search keywords for every code symbol, and optional summaries of
|
|
165
|
+
your notes. They are what let `code lookup` find a function by what it does rather
|
|
166
|
+
than what it's called. Point crib at a provider once:
|
|
167
|
+
|
|
168
|
+
```bash
|
|
169
|
+
crib generate setup # finds the providers this machine has, asks which, writes the config
|
|
170
|
+
crib generate test # one small call per purpose: is the key good, does it reply?
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`setup` looks for API keys in your environment (`OLLAMA_API_KEY`,
|
|
174
|
+
`OPENCODE_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`), a local
|
|
175
|
+
OpenAI-compatible server (Ollama, llama-swap), the `claude` CLI, and providers
|
|
176
|
+
you already defined for zsh-ai. It shows the change to
|
|
177
|
+
`~/.config/crib/models.toml` and `~/.config/crib/config.toml` as a diff, backs both
|
|
178
|
+
up, and writes them only when you say yes.
|
|
179
|
+
|
|
180
|
+
Without a provider, crib still indexes code structure (names, signatures, calls),
|
|
181
|
+
but generates nothing in the background (`[generate] mode = "explicit"`): symbols
|
|
182
|
+
wait for a description until you configure one and run `crib project index`.
|
|
183
|
+
`crib status` counts what is waiting. Details:
|
|
184
|
+
[docs/generate.toml.example](docs/generate.toml.example).
|
|
185
|
+
|
|
186
|
+
**4 — Use it.** The CLI verbs mirror the MCP tools, so anything Claude does you can
|
|
164
187
|
do too:
|
|
165
188
|
|
|
166
189
|
```bash
|
|
@@ -3,7 +3,7 @@ crib/__main__.py,sha256=umIc03A2oA7s2oiL80Ts_QnS-0zj9fjV3IQ103AmNXg,232
|
|
|
3
3
|
crib/app.py,sha256=lLVvuUsRhJHrCuYSTO_HvT9OVZGlpJcIDv6iKJHYWRo,286180
|
|
4
4
|
crib/chunk.py,sha256=ICh4fmpxViXAIKDVNTbbO9-5bT6wWNPTsPUUNs8uwtg,15129
|
|
5
5
|
crib/claudemem.py,sha256=Xf4mVgTFbXHdhhqteTIRz2zirc4irf0wim8AeMybudI,4804
|
|
6
|
-
crib/cli.py,sha256=
|
|
6
|
+
crib/cli.py,sha256=2D1OOsHntfg5FLDWoYVgAt0OFCxjGhViiG3Jc6N3aaI,148924
|
|
7
7
|
crib/client.py,sha256=-PRVFFLjbI-D-libZ_wMdDFdcXkyHmc9AYikzxd9PmI,6605
|
|
8
8
|
crib/codeindex.py,sha256=HYavhLOEieD62iNQasC__kAaMEN6ld1uP2oHmoJjyEI,89916
|
|
9
9
|
crib/codeindexer.py,sha256=-eocU6ThZdNJar-cGaNJUgB5b6fd21QsjIRx56UFy-I,36737
|
|
@@ -21,6 +21,7 @@ crib/errors.py,sha256=OBCUWM1vH1zbZUPB7DhAkOydBQFYYfSWsCC83XRbDeo,1363
|
|
|
21
21
|
crib/filesync.py,sha256=H8n2gf3HqSBf5ezW7oQWG7RrwchqLmL0kWzomVw91MY,3739
|
|
22
22
|
crib/generate.py,sha256=Vgmtym-Yp8cwGfVCiys5ZLWAYHYI4wpbv5SqWxxvoNA,12630
|
|
23
23
|
crib/genledger.py,sha256=cgHo3ucf1gFU8b42PApfEI2Rhh5oo-66AciTr0zuI6U,7450
|
|
24
|
+
crib/gensetup.py,sha256=rXOVBMrvr-TlHsjOXRhXKHH0Xd5DaPzAeAQGJT23mbY,17572
|
|
24
25
|
crib/gitbacking.py,sha256=soVFzumWDQ7QMhn_qBZeP5wtzdofTLrNdmz8Zh4tQMU,25249
|
|
25
26
|
crib/inbound_auth.py,sha256=B2SbiKIMWP5o4pPQribkvtzbDTc_WVYV3MaDoOZ4uTE,4770
|
|
26
27
|
crib/indexer.py,sha256=kRK5r2jzgubMLYAvS4cALtqq46xJZ6NE20lIFWqNBoI,18640
|
|
@@ -50,7 +51,7 @@ crib/tomlrec.py,sha256=ptDbYNhTLmXQeN1BrQGcy2E4wNv0hpKM7aayQ7WvkxE,3796
|
|
|
50
51
|
crib/util.py,sha256=EmDszxT0SIjIkgcppD6pDJxbkp3eU-7blYRwri5b_m4,3282
|
|
51
52
|
crib/versions.py,sha256=P517DveKCh2jKb3o5IOxkzki8ddwmc-QeuiYMvsBb88,3646
|
|
52
53
|
crib/watch.py,sha256=29Vt-QxheleVT8RuQHsz-ptILHZKurc9zz7fqV99htw,33826
|
|
53
|
-
cribsheet-0.23.0.
|
|
54
|
-
cribsheet-0.23.0.
|
|
55
|
-
cribsheet-0.23.0.
|
|
56
|
-
cribsheet-0.23.0.
|
|
54
|
+
cribsheet-0.23.0.dev3.dist-info/METADATA,sha256=4Ee87SroimbyJg6CNdpYxXloRYB8ISmhn-1yQ-gAgSM,20614
|
|
55
|
+
cribsheet-0.23.0.dev3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
56
|
+
cribsheet-0.23.0.dev3.dist-info/entry_points.txt,sha256=CjLxgcZdPGI6U4VRZmrwQ2kL1gUkNykYNkLzT8EQkfQ,39
|
|
57
|
+
cribsheet-0.23.0.dev3.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|