kinescope 0.0.1__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.
- kinescope/__init__.py +76 -0
- kinescope/adapters/__init__.py +3 -0
- kinescope/adapters/anthropic.py +25 -0
- kinescope/adapters/base.py +47 -0
- kinescope/adapters/gemini.py +37 -0
- kinescope/adapters/ollama.py +20 -0
- kinescope/adapters/openai.py +27 -0
- kinescope/branch.py +98 -0
- kinescope/cli.py +243 -0
- kinescope/diff.py +65 -0
- kinescope/engine.py +142 -0
- kinescope/export/__init__.py +4 -0
- kinescope/export/bundle.py +70 -0
- kinescope/export/otel.py +74 -0
- kinescope/intercept/__init__.py +12 -0
- kinescope/intercept/http.py +160 -0
- kinescope/intercept/stdlib.py +111 -0
- kinescope/intercept/tools.py +100 -0
- kinescope/model.py +84 -0
- kinescope/runner.py +48 -0
- kinescope/session.py +167 -0
- kinescope/store/__init__.py +4 -0
- kinescope/store/base.py +31 -0
- kinescope/store/local.py +194 -0
- kinescope/store/mongo.py +169 -0
- kinescope/tui/__init__.py +3 -0
- kinescope/tui/app.py +261 -0
- kinescope-0.0.1.dist-info/METADATA +206 -0
- kinescope-0.0.1.dist-info/RECORD +32 -0
- kinescope-0.0.1.dist-info/WHEEL +4 -0
- kinescope-0.0.1.dist-info/entry_points.txt +2 -0
- kinescope-0.0.1.dist-info/licenses/LICENSE +21 -0
kinescope/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Kinescope — deterministic record-replay and counterfactual branching for AI agents.
|
|
2
|
+
|
|
3
|
+
Quickstart::
|
|
4
|
+
|
|
5
|
+
import anthropic, kinescope
|
|
6
|
+
|
|
7
|
+
def run_agent():
|
|
8
|
+
client = anthropic.Anthropic(http_client=kinescope.http_client())
|
|
9
|
+
return client.messages.create(model="claude-opus-4-8", max_tokens=64,
|
|
10
|
+
messages=[{"role": "user", "content": "hi"}])
|
|
11
|
+
|
|
12
|
+
with kinescope.record("demo") as rec:
|
|
13
|
+
run_agent()
|
|
14
|
+
|
|
15
|
+
with kinescope.replay(rec.run_id) as rep:
|
|
16
|
+
run_agent() # returns the recorded completion; no network call
|
|
17
|
+
assert not rep.divergences
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from collections.abc import Callable
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from .branch import fork
|
|
26
|
+
from .diff import diff_snapshots, json_diff
|
|
27
|
+
from .engine import async_http_client, http_client, record, replay, snapshot
|
|
28
|
+
from .export import export_bundle, export_otel, import_bundle # otel imported lazily, when called
|
|
29
|
+
from .intercept import instrument_tools, tool
|
|
30
|
+
from .model import Event, Run, Snapshot
|
|
31
|
+
from .session import DivergenceError, Session, active_session
|
|
32
|
+
from .store import LocalStore, TraceStore
|
|
33
|
+
|
|
34
|
+
__version__ = "0.0.1"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def ui(
|
|
38
|
+
run_id: str,
|
|
39
|
+
store: TraceStore | None = None,
|
|
40
|
+
agent: Callable[[], Any] | None = None,
|
|
41
|
+
default_override: dict[str, Any] | None = None,
|
|
42
|
+
) -> None:
|
|
43
|
+
"""Launch the timeline TUI (lazily imports the optional `textual` extra).
|
|
44
|
+
|
|
45
|
+
Pass `agent` (a zero-arg callable that re-runs your agent) to enable fork-and-run.
|
|
46
|
+
"""
|
|
47
|
+
from .tui.app import run_tui
|
|
48
|
+
|
|
49
|
+
run_tui(run_id, store=store, agent=agent, default_override=default_override)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"record",
|
|
54
|
+
"replay",
|
|
55
|
+
"fork",
|
|
56
|
+
"http_client",
|
|
57
|
+
"async_http_client",
|
|
58
|
+
"tool",
|
|
59
|
+
"instrument_tools",
|
|
60
|
+
"snapshot",
|
|
61
|
+
"ui",
|
|
62
|
+
"export_otel",
|
|
63
|
+
"export_bundle",
|
|
64
|
+
"import_bundle",
|
|
65
|
+
"json_diff",
|
|
66
|
+
"diff_snapshots",
|
|
67
|
+
"LocalStore",
|
|
68
|
+
"TraceStore",
|
|
69
|
+
"Session",
|
|
70
|
+
"Event",
|
|
71
|
+
"Run",
|
|
72
|
+
"Snapshot",
|
|
73
|
+
"DivergenceError",
|
|
74
|
+
"active_session",
|
|
75
|
+
"__version__",
|
|
76
|
+
]
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Anthropic Messages API → `gen_ai.*` meta."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .base import safe_json
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def normalize(req_body: Any, resp_bytes: bytes) -> dict[str, Any]:
|
|
11
|
+
meta: dict[str, Any] = {"gen_ai.system": "anthropic"}
|
|
12
|
+
if isinstance(req_body, dict) and req_body.get("model"):
|
|
13
|
+
meta["gen_ai.request.model"] = req_body["model"]
|
|
14
|
+
resp = safe_json(resp_bytes) # None for SSE/streaming bodies — model still set from request
|
|
15
|
+
if isinstance(resp, dict):
|
|
16
|
+
usage = resp.get("usage") or {}
|
|
17
|
+
if "input_tokens" in usage:
|
|
18
|
+
meta["gen_ai.usage.input_tokens"] = usage["input_tokens"]
|
|
19
|
+
if "output_tokens" in usage:
|
|
20
|
+
meta["gen_ai.usage.output_tokens"] = usage["output_tokens"]
|
|
21
|
+
if resp.get("stop_reason"):
|
|
22
|
+
meta["gen_ai.response.finish_reasons"] = [resp["stop_reason"]]
|
|
23
|
+
if resp.get("model"):
|
|
24
|
+
meta["gen_ai.response.model"] = resp["model"]
|
|
25
|
+
return meta
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Provider normalizers: turn a recorded HTTP exchange into OTel-GenAI `gen_ai.*` meta
|
|
2
|
+
(DESIGN.md §4.3). The engine stays provider-agnostic — only these adapters know a
|
|
3
|
+
provider's wire shape, dispatched by request host. Normalization parses JSON only, so it
|
|
4
|
+
needs no provider SDK installed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from typing import Any
|
|
11
|
+
from urllib.parse import urlsplit
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def safe_json(data: bytes) -> Any:
|
|
15
|
+
try:
|
|
16
|
+
return json.loads(data)
|
|
17
|
+
except (ValueError, TypeError):
|
|
18
|
+
return None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
OLLAMA_PORT = 11434 # Ollama's well-known local port
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def normalize_meta(url: str, req_body: Any, resp_bytes: bytes) -> dict[str, Any]:
|
|
25
|
+
"""Best-effort `gen_ai.*` metadata for the timeline (never raises)."""
|
|
26
|
+
split = urlsplit(url)
|
|
27
|
+
host = (split.hostname or "").lower()
|
|
28
|
+
if "ollama" in host or split.port == OLLAMA_PORT:
|
|
29
|
+
from .ollama import normalize as ollama_normalize
|
|
30
|
+
|
|
31
|
+
return ollama_normalize(req_body, resp_bytes) # local, OpenAI-compatible wire
|
|
32
|
+
if "anthropic" in host:
|
|
33
|
+
from .anthropic import normalize
|
|
34
|
+
|
|
35
|
+
return normalize(req_body, resp_bytes)
|
|
36
|
+
if "openai" in host or "azure" in host:
|
|
37
|
+
from .openai import normalize
|
|
38
|
+
|
|
39
|
+
return normalize(req_body, resp_bytes)
|
|
40
|
+
if "generativelanguage" in host or "gemini" in host:
|
|
41
|
+
from .gemini import normalize as gemini_normalize
|
|
42
|
+
|
|
43
|
+
return gemini_normalize(url, req_body, resp_bytes) # needs the URL: model lives there
|
|
44
|
+
meta: dict[str, Any] = {"gen_ai.system": host or "unknown"}
|
|
45
|
+
if isinstance(req_body, dict) and req_body.get("model"):
|
|
46
|
+
meta["gen_ai.request.model"] = req_body["model"]
|
|
47
|
+
return meta
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Google Gemini `generateContent` API → `gen_ai.*` meta.
|
|
2
|
+
|
|
3
|
+
A deliberately *different* wire shape from Anthropic/OpenAI — the stronger test that the
|
|
4
|
+
event schema is genuinely provider-agnostic: the model is in the **URL path** (not the body),
|
|
5
|
+
token counts are `promptTokenCount`/`candidatesTokenCount`, and `finishReason` is uppercase.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .base import safe_json
|
|
14
|
+
|
|
15
|
+
# .../v1beta/models/<model>:generateContent → capture <model>
|
|
16
|
+
_MODEL_IN_URL = re.compile(r"/models/([^:/?]+)")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def normalize(url: str, req_body: Any, resp_bytes: bytes) -> dict[str, Any]:
|
|
20
|
+
meta: dict[str, Any] = {"gen_ai.system": "gcp.gemini"}
|
|
21
|
+
match = _MODEL_IN_URL.search(url or "")
|
|
22
|
+
if match:
|
|
23
|
+
meta["gen_ai.request.model"] = match.group(1) # Gemini puts the model in the URL
|
|
24
|
+
resp = safe_json(resp_bytes)
|
|
25
|
+
if isinstance(resp, dict):
|
|
26
|
+
usage = resp.get("usageMetadata") or {}
|
|
27
|
+
if "promptTokenCount" in usage:
|
|
28
|
+
meta["gen_ai.usage.input_tokens"] = usage["promptTokenCount"]
|
|
29
|
+
if "candidatesTokenCount" in usage:
|
|
30
|
+
meta["gen_ai.usage.output_tokens"] = usage["candidatesTokenCount"]
|
|
31
|
+
candidates = resp.get("candidates") or []
|
|
32
|
+
reasons = [c.get("finishReason") for c in candidates if c.get("finishReason")]
|
|
33
|
+
if reasons:
|
|
34
|
+
meta["gen_ai.response.finish_reasons"] = reasons
|
|
35
|
+
if resp.get("modelVersion"):
|
|
36
|
+
meta["gen_ai.response.model"] = resp["modelVersion"]
|
|
37
|
+
return meta
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Ollama (locally-served models) → `gen_ai.*` meta.
|
|
2
|
+
|
|
3
|
+
Ollama exposes an OpenAI-compatible `/v1/chat/completions`, so the response parsing is shared
|
|
4
|
+
with the OpenAI adapter — only `gen_ai.system` differs. That sharing is itself the point: the
|
|
5
|
+
schema absorbs a new *runtime* without new parsing code, while Gemini (a different wire shape)
|
|
6
|
+
proves it absorbs new *shapes*. Recording a local model is also the cheapest real-provider
|
|
7
|
+
evidence available: no key, no quota, no network.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from .openai import normalize as _openai_normalize
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def normalize(req_body: Any, resp_bytes: bytes) -> dict[str, Any]:
|
|
18
|
+
meta = _openai_normalize(req_body, resp_bytes)
|
|
19
|
+
meta["gen_ai.system"] = "ollama" # OpenAI-compatible wire, local runtime
|
|
20
|
+
return meta
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""OpenAI Chat Completions API → `gen_ai.*` meta (the second-provider proof, H1)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .base import safe_json
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def normalize(req_body: Any, resp_bytes: bytes) -> dict[str, Any]:
|
|
11
|
+
meta: dict[str, Any] = {"gen_ai.system": "openai"}
|
|
12
|
+
if isinstance(req_body, dict) and req_body.get("model"):
|
|
13
|
+
meta["gen_ai.request.model"] = req_body["model"]
|
|
14
|
+
resp = safe_json(resp_bytes)
|
|
15
|
+
if isinstance(resp, dict):
|
|
16
|
+
usage = resp.get("usage") or {}
|
|
17
|
+
if "prompt_tokens" in usage: # OpenAI names differ from Anthropic's
|
|
18
|
+
meta["gen_ai.usage.input_tokens"] = usage["prompt_tokens"]
|
|
19
|
+
if "completion_tokens" in usage:
|
|
20
|
+
meta["gen_ai.usage.output_tokens"] = usage["completion_tokens"]
|
|
21
|
+
choices = resp.get("choices") or []
|
|
22
|
+
reasons = [c.get("finish_reason") for c in choices if c.get("finish_reason")]
|
|
23
|
+
if reasons:
|
|
24
|
+
meta["gen_ai.response.finish_reasons"] = reasons
|
|
25
|
+
if resp.get("model"):
|
|
26
|
+
meta["gen_ai.response.model"] = resp["model"]
|
|
27
|
+
return meta
|
kinescope/branch.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Branching — the counterfactual hook (DESIGN.md §6.3).
|
|
2
|
+
|
|
3
|
+
`fork(parent, at=k, override=...)` builds a new child run whose log is the parent's
|
|
4
|
+
events `0..k-1` copied verbatim, plus event `k` with its **output swapped** for the
|
|
5
|
+
override. Re-running the agent inside the `fork()` context then replays that prefix
|
|
6
|
+
(so it reaches step `k` and receives the overridden output) and switches to **live**
|
|
7
|
+
execution for every boundary after `k` — exploring "what if this one step had gone
|
|
8
|
+
differently?". The child is a normal recorded run: itself replayable and forkable.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import contextlib
|
|
14
|
+
from collections.abc import Iterator
|
|
15
|
+
from dataclasses import replace
|
|
16
|
+
from time import time as _wall
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from .engine import _versions
|
|
20
|
+
from .intercept.stdlib import StdlibPatcher
|
|
21
|
+
from .model import Event, Run, new_run_id
|
|
22
|
+
from .session import Policy, Session
|
|
23
|
+
from .store.base import TraceStore
|
|
24
|
+
from .store.local import LocalStore
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _apply_override(store: TraceStore, parent_k: Event, output: Any, child_id: str) -> Event:
|
|
28
|
+
"""Clone the parent's fork-point event into the child with its output replaced."""
|
|
29
|
+
meta = {**parent_k.meta, "overridden": True}
|
|
30
|
+
if parent_k.kind in ("clock", "rng"): # scalar output lives inline in meta
|
|
31
|
+
meta["value"] = output
|
|
32
|
+
return replace(parent_k, run_id=child_id, output_ref=None, meta=meta)
|
|
33
|
+
return replace(parent_k, run_id=child_id, output_ref=store.put_blob(output), meta=meta)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@contextlib.contextmanager
|
|
37
|
+
def fork(
|
|
38
|
+
parent_id: str,
|
|
39
|
+
at: int,
|
|
40
|
+
override: dict[str, Any],
|
|
41
|
+
store: TraceStore | None = None,
|
|
42
|
+
*,
|
|
43
|
+
policy: Policy = "warn",
|
|
44
|
+
) -> Iterator[Session]:
|
|
45
|
+
"""Fork `parent_id` at step `at`, substituting `override["output"]` for that step's
|
|
46
|
+
output, then re-run the agent inside this context to explore the branch live.
|
|
47
|
+
|
|
48
|
+
The new child run's id is `session.run_id`; it records `parent_run_id`, `forked_at_seq`,
|
|
49
|
+
and the override.
|
|
50
|
+
"""
|
|
51
|
+
store = store or LocalStore()
|
|
52
|
+
parent = store.get_run(parent_id)
|
|
53
|
+
events = store.events(parent_id)
|
|
54
|
+
if not 0 <= at < len(events):
|
|
55
|
+
raise ValueError(f"fork point {at} out of range (run has {len(events)} events)")
|
|
56
|
+
if "output" not in override:
|
|
57
|
+
raise ValueError("override must include an 'output' value")
|
|
58
|
+
|
|
59
|
+
child = Run(
|
|
60
|
+
run_id=new_run_id(),
|
|
61
|
+
label=f"{parent.label}#fork@{at}",
|
|
62
|
+
created_at=_wall(),
|
|
63
|
+
status="recording",
|
|
64
|
+
parent_run_id=parent_id,
|
|
65
|
+
forked_at_seq=at,
|
|
66
|
+
overrides=[override],
|
|
67
|
+
sdk_versions=_versions(),
|
|
68
|
+
capture=parent.capture,
|
|
69
|
+
)
|
|
70
|
+
store.create_run(child)
|
|
71
|
+
for ev in events[:at]: # copy the deterministic prefix 0..at-1 verbatim
|
|
72
|
+
store.append_event(replace(ev, run_id=child.run_id))
|
|
73
|
+
store.append_event(_apply_override(store, events[at], override["output"], child.run_id))
|
|
74
|
+
|
|
75
|
+
ses = Session(
|
|
76
|
+
store=store,
|
|
77
|
+
run=child,
|
|
78
|
+
mode="branch",
|
|
79
|
+
policy=policy,
|
|
80
|
+
recorded=store.events(child.run_id), # the pre-built prefix 0..at
|
|
81
|
+
)
|
|
82
|
+
ses.fork_at = at
|
|
83
|
+
patcher = StdlibPatcher(ses, child.capture)
|
|
84
|
+
token = ses.activate()
|
|
85
|
+
patcher.install()
|
|
86
|
+
try:
|
|
87
|
+
yield ses
|
|
88
|
+
if child.status == "recording":
|
|
89
|
+
child.status = "complete"
|
|
90
|
+
ses.finalize_replay()
|
|
91
|
+
except BaseException:
|
|
92
|
+
child.status = "error"
|
|
93
|
+
raise
|
|
94
|
+
finally:
|
|
95
|
+
patcher.uninstall()
|
|
96
|
+
store.update_run(child)
|
|
97
|
+
store.commit() # flush buffered events durably
|
|
98
|
+
ses.deactivate(token)
|
kinescope/cli.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""The `kinescope` CLI (DESIGN.md §6.7): `record`/`replay`/`fork` (run an agent script via
|
|
2
|
+
`-- python your_agent.py`), plus `ls`, `show`, `diff`, `ui`, `export`/`import`, and
|
|
3
|
+
`export-otel`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
from rich.console import Console
|
|
13
|
+
from rich.table import Table
|
|
14
|
+
|
|
15
|
+
from .branch import fork as _fork
|
|
16
|
+
from .diff import diff_snapshots
|
|
17
|
+
from .engine import record as _record
|
|
18
|
+
from .engine import replay as _replay
|
|
19
|
+
from .runner import run_script, split_command
|
|
20
|
+
from .store.local import LocalStore
|
|
21
|
+
|
|
22
|
+
app = typer.Typer(
|
|
23
|
+
help="Kinescope — deterministic record-replay for AI agents.",
|
|
24
|
+
no_args_is_help=True,
|
|
25
|
+
add_completion=False,
|
|
26
|
+
)
|
|
27
|
+
console = Console()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
_PASSTHROUGH = {"allow_extra_args": True, "ignore_unknown_options": True}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _parse_capture(capture: str) -> Any:
|
|
34
|
+
if not capture:
|
|
35
|
+
return ()
|
|
36
|
+
if capture == "all":
|
|
37
|
+
return "all"
|
|
38
|
+
return [c.strip() for c in capture.split(",") if c.strip()]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@app.command(context_settings=_PASSTHROUGH)
|
|
42
|
+
def record(
|
|
43
|
+
ctx: typer.Context,
|
|
44
|
+
label: str = typer.Option("run", help="Run label."),
|
|
45
|
+
store: str = typer.Option(".kinescope", help="Trace store directory."),
|
|
46
|
+
capture: str = typer.Option("", help="Stdlib capture: any of clock,rng,uuid or 'all'."),
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Record an agent script: `kinescope record -- python your_agent.py [args]`.
|
|
49
|
+
|
|
50
|
+
The script must build its client with `kinescope.http_client()` and must NOT call
|
|
51
|
+
`kinescope.record()` itself (this command provides the session).
|
|
52
|
+
"""
|
|
53
|
+
script, argv = split_command(ctx.args)
|
|
54
|
+
with _record(label, LocalStore(store), capture=_parse_capture(capture)) as ses:
|
|
55
|
+
run_script(script, argv)
|
|
56
|
+
console.print(f"recorded run [bold]{ses.run_id}[/bold] ({len(ses.events)} events)")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@app.command(context_settings=_PASSTHROUGH)
|
|
60
|
+
def replay(
|
|
61
|
+
ctx: typer.Context,
|
|
62
|
+
run_id: str = typer.Argument(..., help="Run id to replay."),
|
|
63
|
+
store: str = typer.Option(".kinescope", help="Trace store directory."),
|
|
64
|
+
policy: str = typer.Option("warn", help="Divergence policy: strict | warn | off."),
|
|
65
|
+
) -> None:
|
|
66
|
+
"""Replay an agent script deterministically: `kinescope replay <id> -- python your_agent.py`."""
|
|
67
|
+
script, argv = split_command(ctx.args)
|
|
68
|
+
with _replay(run_id, LocalStore(store), policy=policy) as ses: # type: ignore[arg-type]
|
|
69
|
+
run_script(script, argv)
|
|
70
|
+
if ses.divergences:
|
|
71
|
+
console.print(f"[yellow](!) {len(ses.divergences)} divergence(s):[/yellow]")
|
|
72
|
+
for d in ses.divergences:
|
|
73
|
+
console.print(f" seq {d['seq']}: {d['reason']}")
|
|
74
|
+
else:
|
|
75
|
+
console.print("[green]replayed with 0 divergences[/green]")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@app.command(context_settings=_PASSTHROUGH)
|
|
79
|
+
def fork(
|
|
80
|
+
ctx: typer.Context,
|
|
81
|
+
run_id: str = typer.Argument(..., help="Parent run id."),
|
|
82
|
+
at: int = typer.Option(..., "--at", help="Step (seq) to fork at."),
|
|
83
|
+
override: str = typer.Option(..., "--override", help='Override JSON, e.g. \'{"output": 72}\'.'),
|
|
84
|
+
store: str = typer.Option(".kinescope", help="Trace store directory."),
|
|
85
|
+
) -> None:
|
|
86
|
+
"""Fork a run at a step, override that step's output, and run the tail live:
|
|
87
|
+
`kinescope fork <id> --at 3 --override '{"output": 72}' -- python your_agent.py`."""
|
|
88
|
+
try:
|
|
89
|
+
override_obj = json.loads(override)
|
|
90
|
+
except json.JSONDecodeError as exc:
|
|
91
|
+
console.print(f"[red]--override must be valid JSON: {exc}[/red]")
|
|
92
|
+
raise typer.Exit(1) from exc
|
|
93
|
+
script, argv = split_command(ctx.args)
|
|
94
|
+
with _fork(run_id, at, override_obj, LocalStore(store)) as ses:
|
|
95
|
+
run_script(script, argv)
|
|
96
|
+
console.print(f"forked run [bold]{ses.run_id}[/bold] (from {run_id} @ step {at})")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@app.command("ls")
|
|
100
|
+
def ls(store: str = typer.Option(".kinescope", help="Trace store directory.")) -> None:
|
|
101
|
+
"""List recorded runs."""
|
|
102
|
+
s = LocalStore(store)
|
|
103
|
+
runs = s.list_runs()
|
|
104
|
+
if not runs:
|
|
105
|
+
console.print(f"[dim]no runs in {store}/[/dim]")
|
|
106
|
+
raise typer.Exit()
|
|
107
|
+
table = Table(title=f"runs in {store}/")
|
|
108
|
+
for col in ("run id", "label", "status", "events", "diverge", "forked from"):
|
|
109
|
+
table.add_column(col)
|
|
110
|
+
for r in runs:
|
|
111
|
+
n_events = len(s.events(r.run_id))
|
|
112
|
+
status_style = {"complete": "green", "diverged": "yellow", "error": "red"}.get(r.status, "")
|
|
113
|
+
lineage = f"{r.parent_run_id}@{r.forked_at_seq}" if r.parent_run_id else "-"
|
|
114
|
+
table.add_row(
|
|
115
|
+
r.run_id,
|
|
116
|
+
r.label,
|
|
117
|
+
f"[{status_style}]{r.status}[/{status_style}]" if status_style else r.status,
|
|
118
|
+
str(n_events),
|
|
119
|
+
str(len(r.divergences)),
|
|
120
|
+
lineage,
|
|
121
|
+
)
|
|
122
|
+
console.print(table)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@app.command("show")
|
|
126
|
+
def show(
|
|
127
|
+
run_id: str,
|
|
128
|
+
step: int | None = typer.Option(None, "--step", help="Show only this step (seq)."),
|
|
129
|
+
store: str = typer.Option(".kinescope", help="Trace store directory."),
|
|
130
|
+
) -> None:
|
|
131
|
+
"""Show a run's events (and a preview of each call's I/O)."""
|
|
132
|
+
s = LocalStore(store)
|
|
133
|
+
run = s.get_run(run_id)
|
|
134
|
+
events = s.events(run_id)
|
|
135
|
+
console.print(f"[bold]{run.label}[/bold] {run.run_id} ({run.status})")
|
|
136
|
+
if run.divergences:
|
|
137
|
+
console.print(f"[yellow](!) {len(run.divergences)} divergence(s)[/yellow]")
|
|
138
|
+
selected = [e for e in events if step is None or e.seq == step]
|
|
139
|
+
for ev in selected:
|
|
140
|
+
console.print(
|
|
141
|
+
f"\n[cyan]#{ev.seq}[/cyan] {ev.kind} [bold]{ev.name}[/bold] ({ev.dur_ms:.0f}ms)"
|
|
142
|
+
)
|
|
143
|
+
if ev.input_ref:
|
|
144
|
+
console.print(" in :", _preview(s.get_blob(ev.input_ref)))
|
|
145
|
+
if ev.output_ref:
|
|
146
|
+
console.print(" out:", _preview(s.get_blob(ev.output_ref)))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@app.command("diff")
|
|
150
|
+
def diff(
|
|
151
|
+
run_id: str,
|
|
152
|
+
a: int = typer.Argument(..., help="From step (seq)."),
|
|
153
|
+
b: int = typer.Argument(..., help="To step (seq)."),
|
|
154
|
+
store: str = typer.Option(".kinescope", help="Trace store directory."),
|
|
155
|
+
) -> None:
|
|
156
|
+
"""Show the state diff between two steps (uses the nearest preceding snapshots)."""
|
|
157
|
+
s = LocalStore(store)
|
|
158
|
+
try:
|
|
159
|
+
ops = diff_snapshots(s, run_id, a, b)
|
|
160
|
+
except ValueError as exc:
|
|
161
|
+
console.print(f"[red]{exc}[/red]")
|
|
162
|
+
raise typer.Exit(1) from exc
|
|
163
|
+
if not ops:
|
|
164
|
+
console.print(f"[dim]no state change between step {a} and {b}[/dim]")
|
|
165
|
+
return
|
|
166
|
+
glyph = {"add": ("[green]", "+"), "remove": ("[red]", "-"), "replace": ("[yellow]", "~")}
|
|
167
|
+
console.print(f"state diff step {a} -> {b}")
|
|
168
|
+
for op in ops:
|
|
169
|
+
style, sign = glyph[op["op"]]
|
|
170
|
+
val = "" if op["op"] == "remove" else f" {json.dumps(op['value'])}"
|
|
171
|
+
console.print(f" {style}{sign} {op['path']}{val}[/]")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@app.command("export")
|
|
175
|
+
def export_cmd(
|
|
176
|
+
run_id: str,
|
|
177
|
+
path: str = typer.Argument(..., help="Output bundle path (.zip)."),
|
|
178
|
+
store: str = typer.Option(".kinescope", help="Trace store directory."),
|
|
179
|
+
) -> None:
|
|
180
|
+
"""Export a run to a portable, shareable bundle (events + snapshots + blobs)."""
|
|
181
|
+
from .export.bundle import export_bundle
|
|
182
|
+
|
|
183
|
+
out = export_bundle(run_id, path, LocalStore(store))
|
|
184
|
+
console.print(f"wrote {out} ({out.stat().st_size:,} bytes)")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@app.command("import")
|
|
188
|
+
def import_cmd(
|
|
189
|
+
path: str = typer.Argument(..., help="Bundle path to import."),
|
|
190
|
+
store: str = typer.Option(".kinescope", help="Trace store directory."),
|
|
191
|
+
) -> None:
|
|
192
|
+
"""Import a trace bundle into the local store (replayable/forkable afterward)."""
|
|
193
|
+
from .export.bundle import import_bundle
|
|
194
|
+
|
|
195
|
+
run_id = import_bundle(path, LocalStore(store))
|
|
196
|
+
console.print(f"imported run {run_id}")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@app.command("export-otel")
|
|
200
|
+
def export_otel_cmd(
|
|
201
|
+
run_id: str,
|
|
202
|
+
store: str = typer.Option(".kinescope", help="Trace store directory."),
|
|
203
|
+
) -> None:
|
|
204
|
+
"""Export a run as OpenTelemetry GenAI spans to the console (needs the 'otel' extra)."""
|
|
205
|
+
try:
|
|
206
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
207
|
+
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
|
|
208
|
+
|
|
209
|
+
from .export.otel import export_otel
|
|
210
|
+
except ModuleNotFoundError as exc:
|
|
211
|
+
console.print("[red]Export needs the 'otel' extra: pip install kinescope[otel][/red]")
|
|
212
|
+
raise typer.Exit(1) from exc
|
|
213
|
+
provider = TracerProvider()
|
|
214
|
+
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
|
|
215
|
+
n = export_otel(run_id, LocalStore(store), tracer_provider=provider)
|
|
216
|
+
provider.force_flush()
|
|
217
|
+
console.print(f"exported {n} gen_ai span(s) + 1 run span")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@app.command("ui")
|
|
221
|
+
def ui(
|
|
222
|
+
run_id: str,
|
|
223
|
+
store: str = typer.Option(".kinescope", help="Trace store directory."),
|
|
224
|
+
) -> None:
|
|
225
|
+
"""Open the timeline TUI to scrub a run (view-only; fork via kinescope.ui(..., agent=...))."""
|
|
226
|
+
try:
|
|
227
|
+
from .tui.app import run_tui
|
|
228
|
+
except ModuleNotFoundError as exc:
|
|
229
|
+
console.print("[red]The TUI needs the 'tui' extra: pip install kinescope[tui][/red]")
|
|
230
|
+
raise typer.Exit(1) from exc
|
|
231
|
+
run_tui(run_id, LocalStore(store))
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _preview(blob: bytes, limit: int = 240) -> str:
|
|
235
|
+
try:
|
|
236
|
+
text = json.dumps(json.loads(blob), separators=(",", ":"))
|
|
237
|
+
except ValueError:
|
|
238
|
+
text = blob.decode("utf-8", "replace")
|
|
239
|
+
return text[:limit] + ("..." if len(text) > limit else "")
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
if __name__ == "__main__":
|
|
243
|
+
app()
|
kinescope/diff.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Structural JSON diffing for state snapshots (DESIGN.md §6.5).
|
|
2
|
+
|
|
3
|
+
Emits RFC 6902-shaped ops (add / remove / replace over JSON Pointer paths). Computed
|
|
4
|
+
lazily — only when a step is inspected — so scrubbing a long run stays O(1). Lists are
|
|
5
|
+
diffed positionally (an append shows up as an `add` at the tail), which is exactly what
|
|
6
|
+
a growing message history wants.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from .model import Snapshot
|
|
15
|
+
from .store.base import TraceStore
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _esc(token: Any) -> str:
|
|
19
|
+
"""JSON Pointer escaping: ~ -> ~0, / -> ~1."""
|
|
20
|
+
return str(token).replace("~", "~0").replace("/", "~1")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def json_diff(a: Any, b: Any, path: str = "") -> list[dict[str, Any]]:
|
|
24
|
+
"""Return the ops that transform `a` into `b`."""
|
|
25
|
+
ops: list[dict[str, Any]] = []
|
|
26
|
+
if isinstance(a, dict) and isinstance(b, dict):
|
|
27
|
+
for key in a:
|
|
28
|
+
if key not in b:
|
|
29
|
+
ops.append({"op": "remove", "path": f"{path}/{_esc(key)}"})
|
|
30
|
+
for key, bv in b.items():
|
|
31
|
+
child = f"{path}/{_esc(key)}"
|
|
32
|
+
if key not in a:
|
|
33
|
+
ops.append({"op": "add", "path": child, "value": bv})
|
|
34
|
+
elif a[key] != bv:
|
|
35
|
+
ops.extend(json_diff(a[key], bv, child))
|
|
36
|
+
elif isinstance(a, list) and isinstance(b, list):
|
|
37
|
+
common = min(len(a), len(b))
|
|
38
|
+
for i in range(common):
|
|
39
|
+
if a[i] != b[i]:
|
|
40
|
+
ops.extend(json_diff(a[i], b[i], f"{path}/{i}"))
|
|
41
|
+
for i in range(common, len(b)):
|
|
42
|
+
ops.append({"op": "add", "path": f"{path}/{i}", "value": b[i]})
|
|
43
|
+
for i in range(len(a) - 1, common - 1, -1): # remove tail high→low
|
|
44
|
+
ops.append({"op": "remove", "path": f"{path}/{i}"})
|
|
45
|
+
elif a != b:
|
|
46
|
+
ops.append({"op": "replace", "path": path or "/", "value": b})
|
|
47
|
+
return ops
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _at_or_before(snaps: list[Snapshot], seq: int) -> Snapshot:
|
|
51
|
+
candidates = [s for s in snaps if s.after_seq <= seq]
|
|
52
|
+
return candidates[-1] if candidates else snaps[0]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def diff_snapshots(store: TraceStore, run_id: str, a: int, b: int) -> list[dict[str, Any]]:
|
|
56
|
+
"""Diff the snapshots nearest at-or-before steps `a` and `b`."""
|
|
57
|
+
snaps = store.snapshots(run_id)
|
|
58
|
+
if not snaps:
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f"run {run_id} has no snapshots — call kinescope.snapshot(state) in the agent"
|
|
61
|
+
)
|
|
62
|
+
sa, sb = _at_or_before(snaps, a), _at_or_before(snaps, b)
|
|
63
|
+
state_a = json.loads(store.get_blob(sa.state_ref))
|
|
64
|
+
state_b = json.loads(store.get_blob(sb.state_ref))
|
|
65
|
+
return json_diff(state_a, state_b)
|