k0ntrol-cli 0.1.0__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.
- k0ntrol/__init__.py +1 -0
- k0ntrol/agents.py +998 -0
- k0ntrol/cli.py +190 -0
- k0ntrol/config.py +330 -0
- k0ntrol/credentials.py +78 -0
- k0ntrol/defaults/config.yaml +23 -0
- k0ntrol/events.py +838 -0
- k0ntrol/frontends/__init__.py +1 -0
- k0ntrol/frontends/ask.py +218 -0
- k0ntrol/frontends/badges.py +228 -0
- k0ntrol/frontends/banner.py +128 -0
- k0ntrol/frontends/diffview.py +174 -0
- k0ntrol/frontends/editor.py +701 -0
- k0ntrol/frontends/klog.html +740 -0
- k0ntrol/frontends/klog.py +403 -0
- k0ntrol/frontends/logo.py +12 -0
- k0ntrol/frontends/mentions.py +29 -0
- k0ntrol/frontends/prompt.py +340 -0
- k0ntrol/frontends/render.py +485 -0
- k0ntrol/frontends/session.py +717 -0
- k0ntrol/frontends/setup.py +442 -0
- k0ntrol/frontends/terminal.py +396 -0
- k0ntrol/frontends/theme.py +24 -0
- k0ntrol/helpers.py +108 -0
- k0ntrol/init_flow.py +362 -0
- k0ntrol/langfuse.py +173 -0
- k0ntrol/memory/__init__.py +0 -0
- k0ntrol/memory/index.py +235 -0
- k0ntrol/memory/layout.py +66 -0
- k0ntrol/memory/python_extract.py +189 -0
- k0ntrol/memory/reflect.py +366 -0
- k0ntrol/memory/refresh.py +21 -0
- k0ntrol/memory/scan.py +538 -0
- k0ntrol/memory/session.py +145 -0
- k0ntrol/otel.py +429 -0
- k0ntrol/pricing.py +29 -0
- k0ntrol/prompts/chatty.md +17 -0
- k0ntrol/prompts/implementer.md +14 -0
- k0ntrol/prompts/planner.md +42 -0
- k0ntrol/prompts/researcher.md +20 -0
- k0ntrol/prompts/reviewer.md +34 -0
- k0ntrol/providers.py +718 -0
- k0ntrol/search.py +133 -0
- k0ntrol/tools/__init__.py +0 -0
- k0ntrol/tools/bulk_read.py +93 -0
- k0ntrol/tools/errors.py +50 -0
- k0ntrol/tools/fetch_url.py +212 -0
- k0ntrol/tools/net.py +317 -0
- k0ntrol/tools/path_guard.py +45 -0
- k0ntrol/tools/read.py +174 -0
- k0ntrol/tools/run_tests.py +66 -0
- k0ntrol/tools/runner.py +177 -0
- k0ntrol/tools/search_memory.py +32 -0
- k0ntrol/tools/slice_guard.py +166 -0
- k0ntrol/tools/slice_journal.py +481 -0
- k0ntrol/tools/tracker.py +115 -0
- k0ntrol/tools/web_search.py +199 -0
- k0ntrol/tools/write.py +123 -0
- k0ntrol/tracker/__init__.py +31 -0
- k0ntrol/tracker/github.py +371 -0
- k0ntrol/tracker/local_files.py +241 -0
- k0ntrol/tracker/protocol.py +210 -0
- k0ntrol/workflow/__init__.py +29 -0
- k0ntrol/workflow/change.py +605 -0
- k0ntrol/workflow/ci_gate.py +96 -0
- k0ntrol/workflow/context.py +137 -0
- k0ntrol/workflow/implement.py +1150 -0
- k0ntrol/workflow/nodes.py +331 -0
- k0ntrol/workflow/plan.py +675 -0
- k0ntrol/workflow/qa.py +98 -0
- k0ntrol/workflow/research.py +533 -0
- k0ntrol/workflow/routers.py +273 -0
- k0ntrol/workflow/run.py +1165 -0
- k0ntrol/workflow/state.py +146 -0
- k0ntrol/workflow/triage.py +269 -0
- k0ntrol_cli-0.1.0.dist-info/METADATA +154 -0
- k0ntrol_cli-0.1.0.dist-info/RECORD +80 -0
- k0ntrol_cli-0.1.0.dist-info/WHEEL +4 -0
- k0ntrol_cli-0.1.0.dist-info/entry_points.txt +2 -0
- k0ntrol_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""`/klog`: a local web page over k0's event log.
|
|
2
|
+
|
|
3
|
+
`read_events` loads `.k0-mem/events.jsonl` and any rotated
|
|
4
|
+
`events.*.jsonl` siblings. `build_data` adds the aggregation (runs,
|
|
5
|
+
totals, charts) so the page's JS only renders and filters. `write_page`
|
|
6
|
+
embeds the data in one self-contained HTML file at
|
|
7
|
+
`.k0-mem/klog/index.html`, and `Klog` serves that single file on
|
|
8
|
+
127.0.0.1 and opens it in the browser.
|
|
9
|
+
|
|
10
|
+
Cost is the logged `cost_usd`; when a call has none it is estimated from
|
|
11
|
+
`k0ntrol.pricing` and flagged `estimated`.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import math
|
|
16
|
+
import threading
|
|
17
|
+
import webbrowser
|
|
18
|
+
from collections import Counter, defaultdict
|
|
19
|
+
from collections.abc import Callable, Iterable
|
|
20
|
+
from datetime import UTC, datetime
|
|
21
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from k0ntrol.pricing import estimate_cost
|
|
26
|
+
|
|
27
|
+
HOST = "127.0.0.1"
|
|
28
|
+
PORT = 6767
|
|
29
|
+
TEMPLATE = Path(__file__).with_name("klog.html")
|
|
30
|
+
PLACEHOLDER = "__K0_DATA__"
|
|
31
|
+
LOCAL_HOSTS = frozenset({HOST, "localhost"})
|
|
32
|
+
PAGE_PATHS = frozenset({"/", "/index.html"})
|
|
33
|
+
|
|
34
|
+
APPROVED = frozenset({"approve", "pass"})
|
|
35
|
+
SENT_BACK = frozenset({"reject", "retry", "stop", "fail"})
|
|
36
|
+
|
|
37
|
+
# What the browser may do with the page: run its own inline code, nothing else.
|
|
38
|
+
CONTENT_SECURITY_POLICY = (
|
|
39
|
+
"default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; base-uri 'none'"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# -- reading ---------------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def read_events(root: Path) -> list[dict]:
|
|
47
|
+
"""Every event of the project, oldest first. Malformed lines are skipped."""
|
|
48
|
+
mem = root / ".k0-mem"
|
|
49
|
+
files = [mem / "events.jsonl", *sorted(mem.glob("events.*.jsonl"))]
|
|
50
|
+
events = [event for path in files for event in _read_file(path)]
|
|
51
|
+
return sorted(events, key=lambda event: str(event.get("ts", "")))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _read_file(path: Path) -> list[dict]:
|
|
55
|
+
try:
|
|
56
|
+
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
57
|
+
except OSError:
|
|
58
|
+
return []
|
|
59
|
+
return [event for event in map(_parse_line, lines) if event is not None]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _parse_line(line: str) -> dict | None:
|
|
63
|
+
try:
|
|
64
|
+
event = json.loads(line)
|
|
65
|
+
except ValueError:
|
|
66
|
+
return None
|
|
67
|
+
return event if isinstance(event, dict) else None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# -- aggregation -----------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def build_data(events: list[dict]) -> dict:
|
|
74
|
+
"""The page's data: annotated events, one row per run or chat, analytics."""
|
|
75
|
+
annotated = [_annotate(event) for event in events]
|
|
76
|
+
runs = _runs(annotated)
|
|
77
|
+
return {
|
|
78
|
+
"generated": datetime.now(UTC).isoformat(timespec="seconds"),
|
|
79
|
+
"events": annotated,
|
|
80
|
+
"runs": runs,
|
|
81
|
+
"analytics": _analytics(annotated, runs),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _number(value: Any) -> float:
|
|
86
|
+
ok = isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
87
|
+
return float(value) if ok else 0.0
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _annotate(event: dict) -> dict:
|
|
91
|
+
"""The event plus `cost`/`estimated` (model calls) and `flag` (failures)."""
|
|
92
|
+
out = dict(event)
|
|
93
|
+
if event.get("kind") == "model":
|
|
94
|
+
cost, estimated = _model_cost(event)
|
|
95
|
+
if cost is not None:
|
|
96
|
+
out["cost"], out["estimated"] = cost, estimated
|
|
97
|
+
flag = _flag(event)
|
|
98
|
+
if flag:
|
|
99
|
+
out["flag"] = flag
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _model_cost(event: dict) -> tuple[float | None, bool]:
|
|
104
|
+
logged = event.get("cost_usd")
|
|
105
|
+
if isinstance(logged, (int, float)) and not isinstance(logged, bool):
|
|
106
|
+
return float(logged), False
|
|
107
|
+
tokens_in, tokens_out = int(_number(event.get("tokens_in"))), int(_number(event.get("tokens_out")))
|
|
108
|
+
estimate = estimate_cost(event.get("provider"), event.get("model"), tokens_in, tokens_out)
|
|
109
|
+
return estimate, estimate is not None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
#: The run_end outcomes that make a run's row red (#205).
|
|
113
|
+
RED_OUTCOMES: frozenset[str] = frozenset({"failed", "paused"})
|
|
114
|
+
|
|
115
|
+
_ALSO_BAD: dict[str, Callable[[dict], bool]] = {
|
|
116
|
+
"gate": lambda event: event.get("result") == "fail",
|
|
117
|
+
"run_end": lambda event: event.get("outcome") in RED_OUTCOMES,
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _flag(event: dict) -> str | None:
|
|
122
|
+
if event.get("denied"):
|
|
123
|
+
return "denied"
|
|
124
|
+
also_bad = _ALSO_BAD.get(str(event.get("kind")), lambda _event: False)
|
|
125
|
+
return "fail" if event.get("ok") is False or also_bad(event) else None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _parse_ts(ts: Any) -> datetime | None:
|
|
129
|
+
try:
|
|
130
|
+
return datetime.fromisoformat(str(ts))
|
|
131
|
+
except ValueError:
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _runs(events: list[dict]) -> list[dict]:
|
|
136
|
+
groups: dict[str, list[dict]] = defaultdict(list)
|
|
137
|
+
for event in events:
|
|
138
|
+
key = event.get("run") or event.get("chat")
|
|
139
|
+
if key:
|
|
140
|
+
groups[str(key)].append(event)
|
|
141
|
+
rows = [_run_row(key, group) for key, group in groups.items()]
|
|
142
|
+
return sorted(rows, key=lambda row: row["start"] or "", reverse=True)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _first(events: Iterable[dict], kind: str) -> dict:
|
|
146
|
+
return next((event for event in events if event.get("kind") == kind), {})
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _usage(models: list[dict]) -> dict:
|
|
150
|
+
"""Model calls, tokens and cost over `models` (`cost` is None when no call is priced)."""
|
|
151
|
+
costs = [model["cost"] for model in models if "cost" in model]
|
|
152
|
+
return {
|
|
153
|
+
"model_calls": len(models),
|
|
154
|
+
"tokens_in": int(sum(_number(model.get("tokens_in")) for model in models)),
|
|
155
|
+
"tokens_out": int(sum(_number(model.get("tokens_out")) for model in models)),
|
|
156
|
+
"cost": sum(costs) if costs else None,
|
|
157
|
+
"cost_estimated": any(model.get("estimated") for model in models),
|
|
158
|
+
"unpriced_calls": len(models) - len(costs),
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _failures(events: list[dict]) -> int:
|
|
163
|
+
return sum(1 for event in events if event.get("flag") == "fail")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _denials(events: list[dict]) -> int:
|
|
167
|
+
"""Guard refusals (``path_guard``, an unset search provider): expected,
|
|
168
|
+
so counted apart from failures (#205)."""
|
|
169
|
+
return sum(1 for event in events if event.get("flag") == "denied")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _run_row(key: str, events: list[dict]) -> dict:
|
|
173
|
+
start, end = _first(events, "run_start"), _first(events, "run_end")
|
|
174
|
+
is_chat = not events[0].get("run")
|
|
175
|
+
models = [event for event in events if event.get("kind") == "model"]
|
|
176
|
+
row = {
|
|
177
|
+
"id": key,
|
|
178
|
+
"kind": start.get("run_kind") or ("chat" if is_chat else "unknown"),
|
|
179
|
+
"work_item": start.get("work_item"),
|
|
180
|
+
"branch": start.get("branch"),
|
|
181
|
+
"session": start.get("session"),
|
|
182
|
+
"start": events[0].get("ts"),
|
|
183
|
+
"duration_ms": _duration_ms(events, end),
|
|
184
|
+
"outcome": end.get("outcome") or (None if is_chat else "running"),
|
|
185
|
+
"failures": _failures(events),
|
|
186
|
+
"denials": _denials(events),
|
|
187
|
+
"flagged": end.get("outcome") in RED_OUTCOMES,
|
|
188
|
+
"events": len(events),
|
|
189
|
+
}
|
|
190
|
+
return row | _usage(models)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _duration_ms(events: list[dict], end: dict) -> int | None:
|
|
194
|
+
if isinstance(end.get("ms"), (int, float)):
|
|
195
|
+
return int(end["ms"])
|
|
196
|
+
first, last = _parse_ts(events[0].get("ts")), _parse_ts(events[-1].get("ts"))
|
|
197
|
+
if first is None or last is None:
|
|
198
|
+
return None
|
|
199
|
+
return int((last - first).total_seconds() * 1000)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _analytics(events: list[dict], runs: list[dict]) -> dict:
|
|
203
|
+
models = [event for event in events if event.get("kind") == "model"]
|
|
204
|
+
return {
|
|
205
|
+
"totals": _totals(events, models, runs),
|
|
206
|
+
"by_agent": _by_agent(models),
|
|
207
|
+
"by_day": _by_day(models),
|
|
208
|
+
"latency": _latency(models),
|
|
209
|
+
"tools": _tools(events),
|
|
210
|
+
"gates": _gates(events),
|
|
211
|
+
"outcomes": dict(Counter(row["outcome"] for row in runs if row["kind"] != "chat")),
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _totals(events: list[dict], models: list[dict], runs: list[dict]) -> dict:
|
|
216
|
+
usage = _usage(models)
|
|
217
|
+
usage["cost"] = usage["cost"] or 0.0
|
|
218
|
+
return usage | {
|
|
219
|
+
"runs": sum(1 for row in runs if row["kind"] != "chat"),
|
|
220
|
+
"chats": sum(1 for row in runs if row["kind"] == "chat"),
|
|
221
|
+
"failures": _failures(events),
|
|
222
|
+
"denials": _denials(events),
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _by_agent(models: list[dict]) -> list[dict]:
|
|
227
|
+
rows: dict[str, dict] = {}
|
|
228
|
+
for model in models:
|
|
229
|
+
name = str(model.get("agent") or model.get("helper") or "unknown")
|
|
230
|
+
row = rows.setdefault(
|
|
231
|
+
name,
|
|
232
|
+
{"name": name, "helper": not model.get("agent"), "calls": 0, "cost": 0.0, "tokens_in": 0, "tokens_out": 0},
|
|
233
|
+
)
|
|
234
|
+
row["calls"] += 1
|
|
235
|
+
row["cost"] += model.get("cost", 0.0)
|
|
236
|
+
row["tokens_in"] += int(_number(model.get("tokens_in")))
|
|
237
|
+
row["tokens_out"] += int(_number(model.get("tokens_out")))
|
|
238
|
+
return sorted(rows.values(), key=lambda row: (-row["cost"], row["name"]))
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _by_day(models: list[dict]) -> list[dict]:
|
|
242
|
+
"""Spend per UTC day, split by agent and by model for the spend board."""
|
|
243
|
+
days: dict[str, dict] = {}
|
|
244
|
+
for model in models:
|
|
245
|
+
day = str(model.get("ts", ""))[:10]
|
|
246
|
+
if len(day) == 10:
|
|
247
|
+
_add_to_day(days.setdefault(day, _empty_day(day)), model)
|
|
248
|
+
return [days[day] for day in sorted(days)]
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _empty_day(day: str) -> dict:
|
|
252
|
+
return {"day": day, "cost": 0.0, "calls": 0, "agents": defaultdict(float), "models": defaultdict(float)}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _add_to_day(row: dict, model: dict) -> None:
|
|
256
|
+
cost = model.get("cost", 0.0)
|
|
257
|
+
row["cost"] += cost
|
|
258
|
+
row["calls"] += 1
|
|
259
|
+
row["agents"][str(model.get("agent") or model.get("helper") or "unknown")] += cost
|
|
260
|
+
row["models"][str(model.get("model") or "unknown")] += cost
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _percentile(sorted_values: list[float], percent: int) -> float:
|
|
264
|
+
"""Nearest-rank percentile of an ascending, non-empty list."""
|
|
265
|
+
return sorted_values[max(math.ceil(percent / 100 * len(sorted_values)), 1) - 1]
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _latency(models: list[dict]) -> list[dict]:
|
|
269
|
+
by_model: dict[str, list[float]] = defaultdict(list)
|
|
270
|
+
for model in models:
|
|
271
|
+
if model.get("ok") is not False and isinstance(model.get("ms"), (int, float)):
|
|
272
|
+
by_model[str(model.get("model") or "unknown")].append(model["ms"])
|
|
273
|
+
return [
|
|
274
|
+
{"model": name, "calls": len(ms), "p50": _percentile(sorted(ms), 50), "p95": _percentile(sorted(ms), 95)}
|
|
275
|
+
for name, ms in sorted(by_model.items())
|
|
276
|
+
]
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _tools(events: list[dict]) -> list[dict]:
|
|
280
|
+
rows: dict[str, dict] = {}
|
|
281
|
+
for event in events:
|
|
282
|
+
if event.get("kind") != "tool":
|
|
283
|
+
continue
|
|
284
|
+
name = str(event.get("tool") or "unknown")
|
|
285
|
+
row = rows.setdefault(name, {"tool": name, "calls": 0, "failed": 0, "denied": 0})
|
|
286
|
+
row["calls"] += 1
|
|
287
|
+
flag = event.get("flag")
|
|
288
|
+
if flag:
|
|
289
|
+
row["denied" if flag == "denied" else "failed"] += 1
|
|
290
|
+
return sorted(rows.values(), key=lambda row: (-row["calls"], row["tool"]))
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _gates(events: list[dict]) -> list[dict]:
|
|
294
|
+
rows: dict[str, dict] = {}
|
|
295
|
+
for event in events:
|
|
296
|
+
result = event.get("result")
|
|
297
|
+
if event.get("kind") != "gate" or result not in APPROVED | SENT_BACK:
|
|
298
|
+
continue
|
|
299
|
+
row = rows.setdefault(str(event.get("gate")), {"gate": str(event.get("gate")), "approved": 0, "sent_back": 0})
|
|
300
|
+
row["approved" if result in APPROVED else "sent_back"] += 1
|
|
301
|
+
return sorted(rows.values(), key=lambda row: row["gate"])
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
# -- the page --------------------------------------------------------------
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def render_page(data: dict) -> str:
|
|
308
|
+
"""The HTML with `data` embedded; `<` is escaped so no content can end the script block."""
|
|
309
|
+
payload = json.dumps(data, separators=(",", ":")).replace("<", "\\u003c")
|
|
310
|
+
return TEMPLATE.read_text(encoding="utf-8").replace(PLACEHOLDER, payload, 1)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def write_page(root: Path) -> Path:
|
|
314
|
+
"""Create or overwrite `.k0-mem/klog/index.html` from the current log."""
|
|
315
|
+
page = root / ".k0-mem" / "klog" / "index.html"
|
|
316
|
+
page.parent.mkdir(parents=True, exist_ok=True)
|
|
317
|
+
page.write_text(render_page(build_data(read_events(root))), encoding="utf-8")
|
|
318
|
+
return page
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
# -- the server ------------------------------------------------------------
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _is_local_host(host_header: str) -> bool:
|
|
325
|
+
name = host_header.rpartition(":")[0] or host_header
|
|
326
|
+
return name in LOCAL_HOSTS
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
class _PageHandler(BaseHTTPRequestHandler):
|
|
330
|
+
"""Serves one file, at `/` and `/index.html`. Nothing else."""
|
|
331
|
+
|
|
332
|
+
page: Path
|
|
333
|
+
|
|
334
|
+
def do_GET(self) -> None: # noqa: N802 (http.server's name)
|
|
335
|
+
if not _is_local_host(self.headers.get("Host", "")):
|
|
336
|
+
return self._reply(403, b"")
|
|
337
|
+
if self.path.partition("?")[0] not in PAGE_PATHS:
|
|
338
|
+
return self._reply(404, b"")
|
|
339
|
+
try:
|
|
340
|
+
body = self.page.read_bytes()
|
|
341
|
+
except OSError:
|
|
342
|
+
return self._reply(404, b"")
|
|
343
|
+
self._reply(200, body, "text/html; charset=utf-8")
|
|
344
|
+
|
|
345
|
+
def _reply(self, status: int, body: bytes, content_type: str = "text/plain") -> None:
|
|
346
|
+
self.send_response(status)
|
|
347
|
+
for name, value in (
|
|
348
|
+
("Content-Type", content_type),
|
|
349
|
+
("Content-Length", str(len(body))),
|
|
350
|
+
("Cache-Control", "no-store"),
|
|
351
|
+
("X-Content-Type-Options", "nosniff"),
|
|
352
|
+
("Referrer-Policy", "no-referrer"),
|
|
353
|
+
("Content-Security-Policy", CONTENT_SECURITY_POLICY),
|
|
354
|
+
):
|
|
355
|
+
self.send_header(name, value)
|
|
356
|
+
self.end_headers()
|
|
357
|
+
self.wfile.write(body)
|
|
358
|
+
|
|
359
|
+
def log_message(self, format: str, *args: Any) -> None: # noqa: A002
|
|
360
|
+
"""Stay quiet: the REPL owns the terminal."""
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _bind(page: Path, port: int) -> ThreadingHTTPServer:
|
|
364
|
+
handler = type("PageHandler", (_PageHandler,), {"page": page})
|
|
365
|
+
try:
|
|
366
|
+
return ThreadingHTTPServer((HOST, port), handler)
|
|
367
|
+
except OSError:
|
|
368
|
+
return ThreadingHTTPServer((HOST, 0), handler)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
class Klog:
|
|
372
|
+
"""Writes the page and serves it: one server per instance, started on
|
|
373
|
+
the first `open` and reused after. `opener` and `port` are injectable
|
|
374
|
+
so tests never open a browser or hold a fixed port."""
|
|
375
|
+
|
|
376
|
+
def __init__(self, *, opener: Callable[[str], Any] = webbrowser.open, port: int = PORT) -> None:
|
|
377
|
+
self._opener = opener
|
|
378
|
+
self._port = port
|
|
379
|
+
self._server: ThreadingHTTPServer | None = None
|
|
380
|
+
|
|
381
|
+
@property
|
|
382
|
+
def address(self) -> tuple[str, int]:
|
|
383
|
+
"""Host and port the running server listens on."""
|
|
384
|
+
assert self._server is not None
|
|
385
|
+
host, port = self._server.server_address[:2]
|
|
386
|
+
return str(host), port
|
|
387
|
+
|
|
388
|
+
def open(self, root: Path) -> str:
|
|
389
|
+
"""Regenerate the page, make sure it is served, open it; return its URL."""
|
|
390
|
+
page = write_page(root)
|
|
391
|
+
if self._server is None:
|
|
392
|
+
self._server = _bind(page, self._port)
|
|
393
|
+
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
|
394
|
+
url = f"http://{HOST}:{self.address[1]}/"
|
|
395
|
+
self._opener(url)
|
|
396
|
+
return url
|
|
397
|
+
|
|
398
|
+
def close(self) -> None:
|
|
399
|
+
"""Stop the server (tests; the daemon thread dies with k0 otherwise)."""
|
|
400
|
+
if self._server is not None:
|
|
401
|
+
self._server.shutdown()
|
|
402
|
+
self._server.server_close()
|
|
403
|
+
self._server = None
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class MentionError(Exception):
|
|
6
|
+
"""Raised when an @file mention cannot be resolved."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def mention_paths(text: str, root: Path) -> list[Path]:
|
|
10
|
+
root_path = root.resolve()
|
|
11
|
+
paths = []
|
|
12
|
+
for match in re.finditer(r"@[^\s]+", text):
|
|
13
|
+
token = match.group()[1:]
|
|
14
|
+
paths.append(_resolve_mention(token, root_path))
|
|
15
|
+
return paths
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _resolve_mention(token: str, root: Path) -> Path:
|
|
19
|
+
candidate = Path(token)
|
|
20
|
+
if candidate.is_absolute():
|
|
21
|
+
raise MentionError(f"absolute mention path: {token}")
|
|
22
|
+
resolved = (root / candidate).resolve()
|
|
23
|
+
try:
|
|
24
|
+
resolved.relative_to(root)
|
|
25
|
+
except ValueError as error:
|
|
26
|
+
raise MentionError(f"mention path outside root: {token}") from error
|
|
27
|
+
if not resolved.is_file():
|
|
28
|
+
raise MentionError(f"mention is not an existing file: {token}")
|
|
29
|
+
return resolved
|