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
k0ntrol/events.py
ADDED
|
@@ -0,0 +1,838 @@
|
|
|
1
|
+
"""The always-on, content-free event log.
|
|
2
|
+
|
|
3
|
+
One append-only file, `.k0-mem/events.jsonl`, one JSON line per event. The
|
|
4
|
+
schema is the contract in spec #33 ("Events and Langfuse"): every line has
|
|
5
|
+
`ts` (ISO UTC, ms), `kind`, and `run` — or `chat` for `/ask`. Fields that do
|
|
6
|
+
not apply are omitted, never `null`. No prompts, completions, file contents
|
|
7
|
+
or tool arguments other than `path` (file tools) and `host` (the hostname of
|
|
8
|
+
a tool call's `url` argument, for the network tools) are ever written.
|
|
9
|
+
|
|
10
|
+
Rotation: when an `EventWriter` is created and `events.jsonl` is over
|
|
11
|
+
`EVENTS_MAX_BYTES`, the file is renamed to `events.1.jsonl`, the previous
|
|
12
|
+
`events.1.jsonl` becomes `events.2.jsonl`, and so on up to `EVENTS_KEEP`
|
|
13
|
+
(3); the oldest is deleted. So `events.1.jsonl` is the newest rotated file
|
|
14
|
+
and `events.<EVENTS_KEEP>.jsonl` the oldest; all match `events.*.jsonl`.
|
|
15
|
+
Rotation never happens on an append, and any error during it is ignored:
|
|
16
|
+
the writer then keeps appending to the existing file. The first rotation in
|
|
17
|
+
a repo also adds `events*.jsonl` to `.k0-mem/.gitignore` when that file
|
|
18
|
+
exists and does not already cover it.
|
|
19
|
+
|
|
20
|
+
`run_start` may also carry `session`: the id of the REPL sitting that started
|
|
21
|
+
or resumed the run (the stem of its `.k0-mem/sessions/<id>.txt` file, also the
|
|
22
|
+
Langfuse session of task runs and `/ask` chats), so the log can group runs
|
|
23
|
+
by sitting. Omitted when no sitting is known.
|
|
24
|
+
|
|
25
|
+
`EventWriter` appends lines for harness events (`run_start`, `agent`,
|
|
26
|
+
`gate`, `run_end`). `K0EventHandler` — the one callback attached to every
|
|
27
|
+
graph and helper model call — emits the `model` and `tool` events through
|
|
28
|
+
the same writer.
|
|
29
|
+
|
|
30
|
+
Shared contract for tool refusals (the `denied` field): a tool refuses a
|
|
31
|
+
call by raising an exception that carries a `denied` attribute with value
|
|
32
|
+
`"allowlist"`, `"path_guard"`, `"slice_guard"` or `"network_guard"`. The
|
|
33
|
+
canonical class is
|
|
34
|
+
`k0ntrol.tools.errors.ToolError` (raised with `denied="path_guard"` /
|
|
35
|
+
`denied="allowlist"` / `denied="slice_guard"` / `denied="network_guard"`);
|
|
36
|
+
the handler accepts any
|
|
37
|
+
exception with a truthy `denied` attribute, so tool code never depends on
|
|
38
|
+
this module.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
import json
|
|
42
|
+
import os
|
|
43
|
+
import threading
|
|
44
|
+
import time
|
|
45
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
46
|
+
from datetime import UTC, datetime
|
|
47
|
+
from pathlib import Path
|
|
48
|
+
from typing import Any, Literal
|
|
49
|
+
from urllib.parse import urlsplit
|
|
50
|
+
from uuid import uuid4
|
|
51
|
+
|
|
52
|
+
from langgraph.callbacks import GraphCallbackHandler, GraphInterruptEvent
|
|
53
|
+
|
|
54
|
+
from k0ntrol.memory.layout import EVENTS_IGNORE
|
|
55
|
+
from k0ntrol.providers import REGISTRY
|
|
56
|
+
|
|
57
|
+
ERR_MAX_CHARS = 500
|
|
58
|
+
EVENTS_MAX_BYTES = 10 * 1024 * 1024
|
|
59
|
+
EVENTS_KEEP = 3
|
|
60
|
+
MASKED = "***"
|
|
61
|
+
# Values shorter than this are not masked: a short env value would mangle
|
|
62
|
+
# ordinary words inside error text. Real credentials are much longer.
|
|
63
|
+
MASK_MIN_LENGTH = 8
|
|
64
|
+
|
|
65
|
+
# Env-var name suffixes whose *values* are treated as secrets for masking.
|
|
66
|
+
# Same rule the command runner uses to scrub its environment.
|
|
67
|
+
_SECRET_NAME_SUFFIXES = ("_KEY", "_TOKEN", "_SECRET")
|
|
68
|
+
|
|
69
|
+
# Metadata keys the run module / agent builder put in config["metadata"] so
|
|
70
|
+
# the handler can fill the event fields. `k0_agent` xor `k0_helper` decides
|
|
71
|
+
# the `agent`/`helper` field; `langgraph_node` is the fallback for agents.
|
|
72
|
+
META_AGENT = "k0_agent"
|
|
73
|
+
META_HELPER = "k0_helper"
|
|
74
|
+
META_ATTEMPT = "k0_attempt"
|
|
75
|
+
META_EFFORT = "k0_effort"
|
|
76
|
+
|
|
77
|
+
# The custom-event name middleware dispatches to emit a `warning` event
|
|
78
|
+
# from inside a model call (#182).
|
|
79
|
+
WARNING_EVENT = "warning"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def events_path(root: Path) -> Path:
|
|
83
|
+
"""The event log for the project rooted at `root`."""
|
|
84
|
+
return root / ".k0-mem" / "events.jsonl"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
_rotate_lock = threading.Lock()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _rotated(path: Path, generation: int) -> Path:
|
|
91
|
+
return path.with_name(f"{path.stem}.{generation}{path.suffix}")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _ignore_rotated_files(mem_dir: Path) -> None:
|
|
95
|
+
gitignore = mem_dir / ".gitignore"
|
|
96
|
+
text = gitignore.read_text(encoding="utf-8")
|
|
97
|
+
if EVENTS_IGNORE in text.splitlines() or "events.*.jsonl" in text.splitlines():
|
|
98
|
+
return
|
|
99
|
+
prefix = "" if text.endswith("\n") or not text else "\n"
|
|
100
|
+
with open(gitignore, "a", encoding="utf-8") as fh:
|
|
101
|
+
fh.write(f"{prefix}{EVENTS_IGNORE}\n")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _shift_rotated(path: Path, keep: int) -> None:
|
|
105
|
+
_rotated(path, keep).unlink(missing_ok=True)
|
|
106
|
+
for generation in range(keep - 1, 0, -1):
|
|
107
|
+
source = _rotated(path, generation)
|
|
108
|
+
if source.exists():
|
|
109
|
+
os.replace(source, _rotated(path, generation + 1))
|
|
110
|
+
os.replace(path, _rotated(path, 1))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def rotate_events(
|
|
114
|
+
path: Path, *, max_bytes: int = EVENTS_MAX_BYTES, keep: int = EVENTS_KEEP
|
|
115
|
+
) -> bool:
|
|
116
|
+
"""Rotate `path` when it is over `max_bytes`; True when it rotated.
|
|
117
|
+
|
|
118
|
+
Never raises: a failure leaves the log as it is and writing carries on.
|
|
119
|
+
"""
|
|
120
|
+
with _rotate_lock:
|
|
121
|
+
try:
|
|
122
|
+
if path.stat().st_size <= max_bytes:
|
|
123
|
+
return False
|
|
124
|
+
_shift_rotated(path, keep)
|
|
125
|
+
except OSError:
|
|
126
|
+
return False
|
|
127
|
+
try:
|
|
128
|
+
_ignore_rotated_files(path.parent)
|
|
129
|
+
except OSError:
|
|
130
|
+
pass
|
|
131
|
+
return True
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def new_run_id() -> str:
|
|
135
|
+
"""A fresh run id: 32 lowercase hex, also the Langfuse trace id."""
|
|
136
|
+
return uuid4().hex
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def new_chat_id() -> str:
|
|
140
|
+
"""A fresh `chat` id for a `/ask` exchange. Same format as a run id."""
|
|
141
|
+
return new_run_id()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def secret_env_values(env: Mapping[str, str] | None = None) -> list[str]:
|
|
145
|
+
"""Exact values of known secret env vars, used for `err` masking."""
|
|
146
|
+
source = os.environ if env is None else env
|
|
147
|
+
known_names = set().union(*(spec.credentials for spec in REGISTRY.values()))
|
|
148
|
+
values = [
|
|
149
|
+
value
|
|
150
|
+
for name, value in source.items()
|
|
151
|
+
if (name in known_names or name.endswith(_SECRET_NAME_SUFFIXES))
|
|
152
|
+
and len(value) >= MASK_MIN_LENGTH
|
|
153
|
+
]
|
|
154
|
+
return values
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class EventWriteError(Exception):
|
|
158
|
+
"""A JSONL write failed. The run treats this as `stuck`."""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _now_iso() -> str:
|
|
162
|
+
return datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _mask(text: str, secrets: Iterable[str]) -> str:
|
|
166
|
+
for secret in secrets:
|
|
167
|
+
text = text.replace(secret, MASKED)
|
|
168
|
+
return text[:ERR_MAX_CHARS]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class EventWriter:
|
|
172
|
+
"""Appends one JSON line per event to `path`.
|
|
173
|
+
|
|
174
|
+
Bound to exactly one scope: a `run` id, or a `chat` id for `/ask`.
|
|
175
|
+
`progress`, when given, is called with each written event (for the
|
|
176
|
+
REPL's progress lines); it may never break a write.
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
def __init__(
|
|
180
|
+
self,
|
|
181
|
+
path: Path,
|
|
182
|
+
*,
|
|
183
|
+
run: str | None = None,
|
|
184
|
+
chat: str | None = None,
|
|
185
|
+
mask: Iterable[str] | None = None,
|
|
186
|
+
progress: Callable[[dict], None] | None = None,
|
|
187
|
+
max_bytes: int = EVENTS_MAX_BYTES,
|
|
188
|
+
) -> None:
|
|
189
|
+
if (run is None) == (chat is None):
|
|
190
|
+
raise ValueError("EventWriter needs exactly one of run= or chat=")
|
|
191
|
+
rotate_events(path, max_bytes=max_bytes)
|
|
192
|
+
self._path = path
|
|
193
|
+
self._run = run
|
|
194
|
+
self._chat = chat
|
|
195
|
+
self._mask = list(mask) if mask is not None else secret_env_values()
|
|
196
|
+
self._progress = progress
|
|
197
|
+
self._lock = threading.Lock()
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
def run(self) -> str | None:
|
|
201
|
+
"""The run id this writer is bound to (`None` for a chat writer)."""
|
|
202
|
+
return self._run
|
|
203
|
+
|
|
204
|
+
def emit(self, kind: str, **fields: Any) -> dict:
|
|
205
|
+
"""Append one event. `None` fields are omitted; `err` is masked."""
|
|
206
|
+
event: dict[str, Any] = {"ts": _now_iso(), "kind": kind}
|
|
207
|
+
event["run" if self._run else "chat"] = self._run or self._chat
|
|
208
|
+
err = fields.pop("err", None)
|
|
209
|
+
for key, value in fields.items():
|
|
210
|
+
if value is not None:
|
|
211
|
+
event[key] = value
|
|
212
|
+
if err:
|
|
213
|
+
event["err"] = _mask(str(err), self._mask)
|
|
214
|
+
line = json.dumps(event, separators=(",", ":"))
|
|
215
|
+
with self._lock:
|
|
216
|
+
try:
|
|
217
|
+
with open(self._path, "a", encoding="utf-8") as fh:
|
|
218
|
+
fh.write(line + "\n")
|
|
219
|
+
except OSError as exc:
|
|
220
|
+
raise EventWriteError(f"events.jsonl write failed: {exc}") from exc
|
|
221
|
+
self._notify(event)
|
|
222
|
+
return event
|
|
223
|
+
|
|
224
|
+
def working(self, **fields: Any) -> None:
|
|
225
|
+
"""Tell the progress display a model or tool call just started.
|
|
226
|
+
|
|
227
|
+
Display only: nothing is written to `events.jsonl`, so the log keeps
|
|
228
|
+
exactly one line per finished model call.
|
|
229
|
+
"""
|
|
230
|
+
event = {"kind": "working", **{k: v for k, v in fields.items() if v is not None}}
|
|
231
|
+
self._notify(event)
|
|
232
|
+
|
|
233
|
+
def _notify(self, event: dict) -> None:
|
|
234
|
+
if self._progress is None:
|
|
235
|
+
return
|
|
236
|
+
try:
|
|
237
|
+
self._progress(event)
|
|
238
|
+
except Exception:
|
|
239
|
+
pass
|
|
240
|
+
|
|
241
|
+
def run_start(
|
|
242
|
+
self,
|
|
243
|
+
run_kind: Literal[
|
|
244
|
+
"implement", "plan", "research", "triage"
|
|
245
|
+
],
|
|
246
|
+
*,
|
|
247
|
+
work_item: str | None = None,
|
|
248
|
+
branch: str | None = None,
|
|
249
|
+
version: str | None = None,
|
|
250
|
+
resumed: bool | None = None,
|
|
251
|
+
session: str | None = None,
|
|
252
|
+
question: str | None = None,
|
|
253
|
+
) -> dict:
|
|
254
|
+
"""Emit `run_start`. `work_item`, `resumed` and `session` (the REPL
|
|
255
|
+
sitting's id) only when they apply."""
|
|
256
|
+
return self.emit(
|
|
257
|
+
"run_start",
|
|
258
|
+
run_kind=run_kind,
|
|
259
|
+
work_item=work_item,
|
|
260
|
+
branch=branch,
|
|
261
|
+
version=version,
|
|
262
|
+
resumed=resumed,
|
|
263
|
+
session=session,
|
|
264
|
+
question=question,
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
def gate(
|
|
268
|
+
self,
|
|
269
|
+
gate: str,
|
|
270
|
+
result: str,
|
|
271
|
+
*,
|
|
272
|
+
redo: list[str] | None = None,
|
|
273
|
+
) -> dict:
|
|
274
|
+
"""Emit `gate`: `pass`/`fail` for code gates, `waiting` then a
|
|
275
|
+
decision (`approve`/`reject`/`retry`/`stop`) for human gates."""
|
|
276
|
+
return self.emit("gate", gate=gate, result=result, redo=redo)
|
|
277
|
+
|
|
278
|
+
def run_end(
|
|
279
|
+
self,
|
|
280
|
+
outcome: Literal["done", "stuck", "rejected"],
|
|
281
|
+
ms: int,
|
|
282
|
+
*,
|
|
283
|
+
reason: str | None = None,
|
|
284
|
+
node: str | None = None,
|
|
285
|
+
agent_runs: dict[str, int] | None = None,
|
|
286
|
+
validator_reds: int | None = None,
|
|
287
|
+
model_calls: int | None = None,
|
|
288
|
+
) -> dict:
|
|
289
|
+
"""Emit `run_end`. `reason`/`node` only for `stuck` from a limit;
|
|
290
|
+
the rest is the run's cost: agent runs per node, VALIDATOR reds
|
|
291
|
+
and model calls (#150)."""
|
|
292
|
+
return self.emit(
|
|
293
|
+
"run_end",
|
|
294
|
+
outcome=outcome,
|
|
295
|
+
ms=ms,
|
|
296
|
+
reason=reason,
|
|
297
|
+
node=node,
|
|
298
|
+
agent_runs=agent_runs,
|
|
299
|
+
validator_reds=validator_reds,
|
|
300
|
+
model_calls=model_calls,
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class K0EventHandler(GraphCallbackHandler):
|
|
305
|
+
"""The one callback handler attached to every graph and helper call.
|
|
306
|
+
|
|
307
|
+
Emits `model` events on chat-model end/error and `tool` events on tool
|
|
308
|
+
end/error through the bound `EventWriter` (which carries the `run` or
|
|
309
|
+
`chat` scope). Per-call context comes from `config["metadata"]`:
|
|
310
|
+
`k0_agent` xor `k0_helper`, `k0_attempt`, `k0_effort`; `langgraph_node`
|
|
311
|
+
is the fallback for `agent`.
|
|
312
|
+
|
|
313
|
+
`raise_error` is on so a failed JSONL write propagates and the run can
|
|
314
|
+
end `stuck`; `run_inline` keeps line order under async dispatch.
|
|
315
|
+
|
|
316
|
+
`on_interrupt` emits `gate`/`waiting` when a gate node's `interrupt()`
|
|
317
|
+
value is a mapping carrying a `"gate"` name — the convention gate
|
|
318
|
+
payloads follow. Decisions (`approve`/`reject`/`retry`/`stop`) are
|
|
319
|
+
harness events emitted through `EventWriter.gate`.
|
|
320
|
+
"""
|
|
321
|
+
|
|
322
|
+
run_inline = True
|
|
323
|
+
raise_error = True
|
|
324
|
+
|
|
325
|
+
def __init__(self, writer: EventWriter) -> None:
|
|
326
|
+
self._writer = writer
|
|
327
|
+
self._llm_starts: dict[Any, dict] = {}
|
|
328
|
+
self._tool_starts: dict[Any, dict] = {}
|
|
329
|
+
|
|
330
|
+
# -- model events ------------------------------------------------------
|
|
331
|
+
|
|
332
|
+
def on_chat_model_start(
|
|
333
|
+
self,
|
|
334
|
+
serialized: dict,
|
|
335
|
+
messages: list,
|
|
336
|
+
*,
|
|
337
|
+
run_id: Any,
|
|
338
|
+
parent_run_id: Any = None,
|
|
339
|
+
tags: list | None = None,
|
|
340
|
+
metadata: dict | None = None,
|
|
341
|
+
**kwargs: Any,
|
|
342
|
+
) -> None:
|
|
343
|
+
self._llm_starts[run_id] = self._started(metadata)
|
|
344
|
+
|
|
345
|
+
def on_llm_start(
|
|
346
|
+
self,
|
|
347
|
+
serialized: dict,
|
|
348
|
+
prompts: list,
|
|
349
|
+
*,
|
|
350
|
+
run_id: Any,
|
|
351
|
+
parent_run_id: Any = None,
|
|
352
|
+
tags: list | None = None,
|
|
353
|
+
metadata: dict | None = None,
|
|
354
|
+
**kwargs: Any,
|
|
355
|
+
) -> None:
|
|
356
|
+
# k0 uses chat models, but a plain LLM call still gets its event.
|
|
357
|
+
self._llm_starts[run_id] = self._started(metadata)
|
|
358
|
+
|
|
359
|
+
def _started(self, metadata: Mapping | None) -> dict:
|
|
360
|
+
start = _call_start(metadata)
|
|
361
|
+
who = {"helper": start["helper"]} if start["helper"] else {"agent": start["agent"]}
|
|
362
|
+
self._writer.working(**who)
|
|
363
|
+
return start
|
|
364
|
+
|
|
365
|
+
def on_llm_end(
|
|
366
|
+
self,
|
|
367
|
+
response: Any,
|
|
368
|
+
*,
|
|
369
|
+
run_id: Any,
|
|
370
|
+
parent_run_id: Any = None,
|
|
371
|
+
tags: list | None = None,
|
|
372
|
+
**kwargs: Any,
|
|
373
|
+
) -> None:
|
|
374
|
+
start = self._llm_starts.pop(run_id, {})
|
|
375
|
+
message = _llm_message(response)
|
|
376
|
+
usage = getattr(message, "usage_metadata", None) or {}
|
|
377
|
+
self._writer.emit(
|
|
378
|
+
"model",
|
|
379
|
+
agent=start.get("agent"),
|
|
380
|
+
helper=start.get("helper"),
|
|
381
|
+
provider=start.get("provider"),
|
|
382
|
+
model=start.get("model") or _response_model(response, message),
|
|
383
|
+
effort=start.get("effort"),
|
|
384
|
+
attempt=start.get("attempt"),
|
|
385
|
+
ms=_elapsed_ms(start),
|
|
386
|
+
tokens_in=usage.get("input_tokens"),
|
|
387
|
+
tokens_out=usage.get("output_tokens"),
|
|
388
|
+
cost_usd=_response_cost(message),
|
|
389
|
+
web_searches=_web_searches(message),
|
|
390
|
+
ok=True,
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
def on_llm_error(
|
|
394
|
+
self,
|
|
395
|
+
error: BaseException,
|
|
396
|
+
*,
|
|
397
|
+
run_id: Any,
|
|
398
|
+
parent_run_id: Any = None,
|
|
399
|
+
tags: list | None = None,
|
|
400
|
+
**kwargs: Any,
|
|
401
|
+
) -> None:
|
|
402
|
+
start = self._llm_starts.pop(run_id, {})
|
|
403
|
+
self._writer.emit(
|
|
404
|
+
"model",
|
|
405
|
+
agent=start.get("agent"),
|
|
406
|
+
helper=start.get("helper"),
|
|
407
|
+
provider=start.get("provider"),
|
|
408
|
+
model=start.get("model"),
|
|
409
|
+
effort=start.get("effort"),
|
|
410
|
+
attempt=start.get("attempt"),
|
|
411
|
+
ms=_elapsed_ms(start),
|
|
412
|
+
ok=False,
|
|
413
|
+
**_failure(error),
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
# -- tool events --------------------------------------------------------
|
|
417
|
+
|
|
418
|
+
def on_tool_start(
|
|
419
|
+
self,
|
|
420
|
+
serialized: dict,
|
|
421
|
+
input_str: str,
|
|
422
|
+
*,
|
|
423
|
+
run_id: Any,
|
|
424
|
+
parent_run_id: Any = None,
|
|
425
|
+
tags: list | None = None,
|
|
426
|
+
metadata: dict | None = None,
|
|
427
|
+
inputs: dict | None = None,
|
|
428
|
+
**kwargs: Any,
|
|
429
|
+
) -> None:
|
|
430
|
+
metadata = metadata or {}
|
|
431
|
+
path = inputs.get("path") if isinstance(inputs, dict) else None
|
|
432
|
+
self._tool_starts[run_id] = {
|
|
433
|
+
"t0": time.monotonic(),
|
|
434
|
+
"agent": _agent_name(metadata),
|
|
435
|
+
"tool": (serialized or {}).get("name"),
|
|
436
|
+
"path": str(path) if path else None,
|
|
437
|
+
"host": _input_host(inputs),
|
|
438
|
+
}
|
|
439
|
+
start = self._tool_starts[run_id]
|
|
440
|
+
self._writer.working(
|
|
441
|
+
agent=start["agent"],
|
|
442
|
+
tool=start["tool"],
|
|
443
|
+
path=start["path"],
|
|
444
|
+
host=start["host"],
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
def on_tool_end(
|
|
448
|
+
self,
|
|
449
|
+
output: Any,
|
|
450
|
+
*,
|
|
451
|
+
run_id: Any,
|
|
452
|
+
parent_run_id: Any = None,
|
|
453
|
+
**kwargs: Any,
|
|
454
|
+
) -> None:
|
|
455
|
+
start = self._tool_starts.pop(run_id, {})
|
|
456
|
+
self._writer.emit(
|
|
457
|
+
"tool",
|
|
458
|
+
agent=start.get("agent"),
|
|
459
|
+
tool=start.get("tool"),
|
|
460
|
+
path=start.get("path"),
|
|
461
|
+
host=start.get("host"),
|
|
462
|
+
ms=_elapsed_ms(start),
|
|
463
|
+
ok=True,
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
def on_tool_error(
|
|
467
|
+
self,
|
|
468
|
+
error: BaseException,
|
|
469
|
+
*,
|
|
470
|
+
run_id: Any,
|
|
471
|
+
parent_run_id: Any = None,
|
|
472
|
+
**kwargs: Any,
|
|
473
|
+
) -> None:
|
|
474
|
+
start = self._tool_starts.pop(run_id, {})
|
|
475
|
+
self._writer.emit(
|
|
476
|
+
"tool",
|
|
477
|
+
agent=start.get("agent"),
|
|
478
|
+
tool=start.get("tool"),
|
|
479
|
+
path=start.get("path"),
|
|
480
|
+
host=start.get("host"),
|
|
481
|
+
ms=_elapsed_ms(start),
|
|
482
|
+
ok=False,
|
|
483
|
+
err=str(error),
|
|
484
|
+
denied=getattr(error, "denied", None),
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
# -- custom events --------------------------------------------------------
|
|
488
|
+
|
|
489
|
+
def on_custom_event(
|
|
490
|
+
self,
|
|
491
|
+
name: str,
|
|
492
|
+
data: Any,
|
|
493
|
+
*,
|
|
494
|
+
run_id: Any = None,
|
|
495
|
+
tags: list | None = None,
|
|
496
|
+
metadata: dict | None = None,
|
|
497
|
+
**kwargs: Any,
|
|
498
|
+
) -> None:
|
|
499
|
+
"""A middleware's adhoc ``warning`` becomes one JSONL event."""
|
|
500
|
+
if name == WARNING_EVENT and isinstance(data, Mapping):
|
|
501
|
+
self._writer.emit(
|
|
502
|
+
WARNING_EVENT,
|
|
503
|
+
agent=data.get("agent"),
|
|
504
|
+
model=data.get("model"),
|
|
505
|
+
reason=data.get("reason"),
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
# -- gate events ---------------------------------------------------------
|
|
509
|
+
|
|
510
|
+
def on_interrupt(self, event: GraphInterruptEvent) -> None:
|
|
511
|
+
for interrupt in event.interrupts:
|
|
512
|
+
value = interrupt.value
|
|
513
|
+
if isinstance(value, Mapping) and value.get("gate"):
|
|
514
|
+
self._writer.gate(str(value["gate"]), "waiting")
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
_HOST_MAX = 253
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _input_host(inputs: Any) -> str | None:
|
|
521
|
+
"""The hostname of a tool call's ``url`` argument — never the rest."""
|
|
522
|
+
if not isinstance(inputs, dict):
|
|
523
|
+
return None
|
|
524
|
+
url = inputs.get("url")
|
|
525
|
+
if not isinstance(url, str):
|
|
526
|
+
return None
|
|
527
|
+
try:
|
|
528
|
+
host = urlsplit(url).hostname
|
|
529
|
+
except ValueError:
|
|
530
|
+
return None
|
|
531
|
+
return host[:_HOST_MAX] if host else None
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _call_start(metadata: Mapping | None) -> dict:
|
|
535
|
+
metadata = metadata or {}
|
|
536
|
+
return {
|
|
537
|
+
"t0": time.monotonic(),
|
|
538
|
+
"helper": metadata.get(META_HELPER),
|
|
539
|
+
"agent": _agent_name(metadata),
|
|
540
|
+
"provider": metadata.get("ls_provider"),
|
|
541
|
+
"model": metadata.get("ls_model_name"),
|
|
542
|
+
"effort": metadata.get(META_EFFORT),
|
|
543
|
+
"attempt": metadata.get(META_ATTEMPT),
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _agent_name(metadata: Mapping) -> Any:
|
|
548
|
+
if metadata.get(META_HELPER):
|
|
549
|
+
return None
|
|
550
|
+
return metadata.get(META_AGENT) or metadata.get("langgraph_node")
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _elapsed_ms(start: Mapping) -> int:
|
|
554
|
+
t0 = start.get("t0")
|
|
555
|
+
if t0 is None:
|
|
556
|
+
return 0
|
|
557
|
+
return round((time.monotonic() - t0) * 1000)
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _llm_message(response: Any) -> Any | None:
|
|
561
|
+
try:
|
|
562
|
+
generation = response.generations[0][0]
|
|
563
|
+
except (IndexError, TypeError, AttributeError):
|
|
564
|
+
return None
|
|
565
|
+
return getattr(generation, "message", None)
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _response_model(response: Any, message: Any | None) -> Any | None:
|
|
569
|
+
llm_output = getattr(response, "llm_output", None) or {}
|
|
570
|
+
if llm_output.get("model_name"):
|
|
571
|
+
return llm_output["model_name"]
|
|
572
|
+
meta = getattr(message, "response_metadata", None) or {}
|
|
573
|
+
return meta.get("model_name")
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _response_cost(message: Any | None) -> Any | None:
|
|
577
|
+
meta = getattr(message, "response_metadata", None) or {}
|
|
578
|
+
return meta.get("cost")
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _web_searches(message: Any | None) -> int | None:
|
|
582
|
+
"""The provider searches the call ran, or ``None`` — the field is
|
|
583
|
+
left out of the ``model`` event when the call ran none (#182).
|
|
584
|
+
OpenAI's ``web_search_call`` items land in the content blocks; a
|
|
585
|
+
v0-formatted response keeps them in ``additional_kwargs.tool_outputs``.
|
|
586
|
+
Anthropic's are the billed ``usage.server_tool_use.web_search_requests``
|
|
587
|
+
(#209): a ``server_tool_use`` block can name a search that runs on a
|
|
588
|
+
later call, so its blocks are not counted. Streaming drops that usage,
|
|
589
|
+
so then each executed search counts by its ``web_search_tool_result``
|
|
590
|
+
block (#210 review)."""
|
|
591
|
+
if message is None:
|
|
592
|
+
return None
|
|
593
|
+
count = _search_calls(getattr(message, "content", None))
|
|
594
|
+
tool_outputs = (getattr(message, "additional_kwargs", None) or {}).get(
|
|
595
|
+
"tool_outputs"
|
|
596
|
+
)
|
|
597
|
+
count += _search_calls(tool_outputs)
|
|
598
|
+
count += _anthropic_searches(message)
|
|
599
|
+
return count or None
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def _search_calls(blocks: Any) -> int:
|
|
603
|
+
if not isinstance(blocks, list):
|
|
604
|
+
return 0
|
|
605
|
+
return sum(
|
|
606
|
+
1
|
|
607
|
+
for block in blocks
|
|
608
|
+
if isinstance(block, dict) and block.get("type") == "web_search_call"
|
|
609
|
+
)
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def _anthropic_searches(message: Any) -> int:
|
|
613
|
+
billed = _billed_searches(getattr(message, "response_metadata", None))
|
|
614
|
+
if billed is not None:
|
|
615
|
+
return billed
|
|
616
|
+
content = getattr(message, "content", None)
|
|
617
|
+
if not isinstance(content, list):
|
|
618
|
+
return 0
|
|
619
|
+
return sum(
|
|
620
|
+
1
|
|
621
|
+
for block in content
|
|
622
|
+
if isinstance(block, dict) and block.get("type") == "web_search_tool_result"
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _billed_searches(metadata: Any) -> int | None:
|
|
627
|
+
usage = (metadata or {}).get("usage") if isinstance(metadata, dict) else None
|
|
628
|
+
server = usage.get("server_tool_use") if isinstance(usage, dict) else None
|
|
629
|
+
count = server.get("web_search_requests") if isinstance(server, dict) else None
|
|
630
|
+
return count if isinstance(count, int) else None
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
# --- Progress renderer ----------------------------------------------------
|
|
634
|
+
|
|
635
|
+
_ERR_SNIP = 80
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def render_event(event: dict) -> str | None:
|
|
639
|
+
"""One progress line for an event, or `None` when there is nothing to
|
|
640
|
+
say (unknown or absent `kind`, e.g. old 0.0.x lines)."""
|
|
641
|
+
renderer = _RENDERERS.get(event.get("kind", ""))
|
|
642
|
+
if renderer is None:
|
|
643
|
+
return None
|
|
644
|
+
return renderer(event)
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
class ProgressRenderer:
|
|
648
|
+
"""Turns each event into at most one progress line via `write`.
|
|
649
|
+
|
|
650
|
+
A `write` with an `event` method is a rich output (the terminal UI):
|
|
651
|
+
it gets the event itself and renders it its own way.
|
|
652
|
+
"""
|
|
653
|
+
|
|
654
|
+
def __init__(self, write: Callable[[str], None]) -> None:
|
|
655
|
+
self._write = write
|
|
656
|
+
|
|
657
|
+
def __call__(self, event: dict) -> None:
|
|
658
|
+
rich_output = getattr(self._write, "event", None)
|
|
659
|
+
if rich_output is not None:
|
|
660
|
+
rich_output(event)
|
|
661
|
+
return
|
|
662
|
+
line = render_event(event)
|
|
663
|
+
if line is not None:
|
|
664
|
+
self._write(line)
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def _snip(text: str) -> str:
|
|
668
|
+
return text[:_ERR_SNIP]
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _render_run_start(e: dict) -> str:
|
|
672
|
+
parts = ["run", e.get("run_kind", "?")]
|
|
673
|
+
if e.get("work_item"):
|
|
674
|
+
parts.append(e["work_item"])
|
|
675
|
+
parts.append("started")
|
|
676
|
+
if e.get("branch"):
|
|
677
|
+
parts.append("on " + e["branch"])
|
|
678
|
+
if e.get("resumed"):
|
|
679
|
+
parts.append("(resumed)")
|
|
680
|
+
return " ".join(parts)
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _render_model(e: dict) -> str:
|
|
684
|
+
who = e.get("agent") or e.get("helper") or "?"
|
|
685
|
+
desc = _model_desc(e)
|
|
686
|
+
if e.get("ok"):
|
|
687
|
+
return _render_model_ok(e, who, desc)
|
|
688
|
+
return f"model {who} {desc} failed: {_snip(e.get('err', ''))} ({e.get('ms', 0)}ms)"
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def _model_desc(e: dict) -> str:
|
|
692
|
+
desc = e.get("model") or "?"
|
|
693
|
+
if e.get("provider"):
|
|
694
|
+
return f"{e['provider']}/{desc}"
|
|
695
|
+
return desc
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _render_model_ok(e: dict, who: str, desc: str) -> str:
|
|
699
|
+
usage = ""
|
|
700
|
+
if "tokens_in" in e or "tokens_out" in e:
|
|
701
|
+
usage = f" ({e.get('tokens_in', 0)} in, {e.get('tokens_out', 0)} out)"
|
|
702
|
+
return f"model {who} {desc} ok {e.get('ms', 0)}ms{usage}"
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def _render_tool(e: dict) -> str:
|
|
706
|
+
head = f"tool {e.get('agent', '?')} {e.get('tool', '?')}"
|
|
707
|
+
if e.get("path"):
|
|
708
|
+
head += f" {e['path']}"
|
|
709
|
+
if e.get("host"):
|
|
710
|
+
head += f" {e['host']}"
|
|
711
|
+
if e.get("denied"):
|
|
712
|
+
return f"{head} denied {e['denied']} ({e.get('ms', 0)}ms)"
|
|
713
|
+
if e.get("ok"):
|
|
714
|
+
return f"{head} ok {e.get('ms', 0)}ms"
|
|
715
|
+
return f"{head} failed: {_snip(e.get('err', ''))} ({e.get('ms', 0)}ms)"
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def _render_warning(e: dict) -> str:
|
|
719
|
+
return (
|
|
720
|
+
f"warning {e.get('agent', '?')} {e.get('model', '?')}: "
|
|
721
|
+
f"{e.get('reason', '?')}"
|
|
722
|
+
)
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def _render_gate(e: dict) -> str:
|
|
726
|
+
line = f"gate {e.get('gate', '?')} {e.get('result', '?')}"
|
|
727
|
+
if e.get("redo"):
|
|
728
|
+
line += " redo: " + ", ".join(e["redo"])
|
|
729
|
+
return line
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def cost_parts(
|
|
733
|
+
agent_runs: Mapping[str, int] | None,
|
|
734
|
+
validator_reds: int | None,
|
|
735
|
+
model_calls: int | None,
|
|
736
|
+
) -> list[str]:
|
|
737
|
+
"""The run's cost as summary parts — ``implementer ×2``,
|
|
738
|
+
``validator red ×1``, ``37 model calls`` — for the one line a
|
|
739
|
+
finished run shows (#150)."""
|
|
740
|
+
parts = [
|
|
741
|
+
f"{name} ×{count}" for name, count in (agent_runs or {}).items()
|
|
742
|
+
]
|
|
743
|
+
if validator_reds:
|
|
744
|
+
parts.append(f"validator red ×{validator_reds}")
|
|
745
|
+
if model_calls:
|
|
746
|
+
parts.append(f"{model_calls} model calls")
|
|
747
|
+
return parts
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def run_cost(path: Path, run: str) -> dict[str, Any]:
|
|
751
|
+
"""The run's work counts off its event log (#150): agent runs per
|
|
752
|
+
label (the ``agent`` events — crashed runs count too), VALIDATOR
|
|
753
|
+
reds (its ``fail`` gate results) and model calls — helpers and
|
|
754
|
+
failed calls included."""
|
|
755
|
+
events = [e for e in _log_events(path) if e.get("run") == run]
|
|
756
|
+
return {
|
|
757
|
+
"agent_runs": _agent_runs(events),
|
|
758
|
+
"validator_reds": _validator_reds(events),
|
|
759
|
+
"model_calls": sum(1 for e in events if e.get("kind") == "model"),
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def _agent_runs(events: list[dict]) -> dict[str, int]:
|
|
764
|
+
runs: dict[str, int] = {}
|
|
765
|
+
for event in events:
|
|
766
|
+
if event.get("kind") == "agent" and event.get("agent"):
|
|
767
|
+
label = str(event["agent"])
|
|
768
|
+
runs[label] = runs.get(label, 0) + 1
|
|
769
|
+
return runs
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def _validator_reds(events: list[dict]) -> int:
|
|
773
|
+
"""One red per VALIDATOR round: a configured gate itself named
|
|
774
|
+
``validator`` logs its own ``fail`` right before the aggregate's —
|
|
775
|
+
adjacent duplicates collapse into the one red they came from."""
|
|
776
|
+
reds = 0
|
|
777
|
+
for index, event in enumerate(events):
|
|
778
|
+
if _is_red(event) and not (index and _is_red(events[index - 1])):
|
|
779
|
+
reds += 1
|
|
780
|
+
return reds
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def _is_red(event: dict) -> bool:
|
|
784
|
+
return (
|
|
785
|
+
event.get("kind") == "gate"
|
|
786
|
+
and event.get("gate") == "validator"
|
|
787
|
+
and event.get("result") == "fail"
|
|
788
|
+
)
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def _log_events(path: Path) -> Iterable[dict]:
|
|
792
|
+
for log in sorted(path.parent.glob(f"{path.stem}*.jsonl")):
|
|
793
|
+
yield from _log_lines(log)
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def _log_lines(log: Path) -> Iterable[dict]:
|
|
797
|
+
try:
|
|
798
|
+
lines = log.read_text(encoding="utf-8").splitlines()
|
|
799
|
+
except OSError:
|
|
800
|
+
return
|
|
801
|
+
for line in lines:
|
|
802
|
+
try:
|
|
803
|
+
event = json.loads(line)
|
|
804
|
+
except json.JSONDecodeError:
|
|
805
|
+
continue
|
|
806
|
+
if isinstance(event, dict):
|
|
807
|
+
yield event
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def _render_run_end(e: dict) -> str:
|
|
811
|
+
line = f"run ended {e.get('outcome', '?')} ({e.get('ms', 0)}ms)"
|
|
812
|
+
if e.get("reason"):
|
|
813
|
+
line += f" {e['reason']}"
|
|
814
|
+
if e.get("node"):
|
|
815
|
+
line += f" at {e['node']}"
|
|
816
|
+
cost = cost_parts(
|
|
817
|
+
e.get("agent_runs"), e.get("validator_reds"), e.get("model_calls")
|
|
818
|
+
)
|
|
819
|
+
if cost:
|
|
820
|
+
line += " · " + " · ".join(cost)
|
|
821
|
+
return line
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
_RENDERERS: dict[str, Callable[[dict], str]] = {
|
|
825
|
+
"run_start": _render_run_start,
|
|
826
|
+
"model": _render_model,
|
|
827
|
+
"tool": _render_tool,
|
|
828
|
+
"warning": _render_warning,
|
|
829
|
+
"gate": _render_gate,
|
|
830
|
+
"run_end": _render_run_end,
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
def _failure(error: BaseException) -> dict:
|
|
835
|
+
"""A failed call's outcome: Ctrl-C is the user pausing the run (#204)."""
|
|
836
|
+
if isinstance(error, KeyboardInterrupt):
|
|
837
|
+
return {"paused": True}
|
|
838
|
+
return {"err": str(error)}
|