feat(webui): inspect file context in a live graph sidebar (#6562)

* feat(webui): inspect file context in a live graph sidebar

* refactor(webui): place preview controls in the shared sidebar header

* fix(webui): synchronize npm lockfile for graph dependencies

* fix(webui): preserve compacted context and refine graph inspection

* fix(context): harden provenance, request usage, and drawer lifecycle

* fix(webui): align source skeleton and browser fixtures

* perf(context): reuse source analysis and capture request graphs once

* perf(webui): compact graph history and render graph motion on canvas

* fix(webui): remove redundant context sidebar header

* style(webui): clarify context replay icon

* perf(webui): pace context replay on an adaptive timeline

* feat(webui): briefly reveal labels for new context nodes

* fix(webui): reveal new labels only for loaded context files

* fix(webui): restart graph animation clock after idle

* fix(webui): reveal labels when replay reverses node exit

* refactor(context): project file-use facts without retention tracking

* refactor(context): observe file reads outside agent execution

* fix(webui): animate context sidebar closing

* refactor(context): remove unused graph and usage panel code

* refactor(context): isolate prompt observation from execution metadata

* fix(webui): clarify cache rate and show context token usage

* fix(webui): abbreviate context token counts in thousands

* fix(webui): omit token unit from context usage details

* fix(webui): restore large source preview highlighting and panel elevation

* fix(webui): distinguish modifier scrolling from keyboard focus

* fix(webui): align preview tab and panel corner radii

* fix(webui): attach file tabs to the header divider

* fix(webui): use one action to toggle file preview mode

* fix(webui): use hover hint for context replay

* fix(webui): share composer layout between graph and file sidebars

* fix(webui): align sidebar bottom with composer surface

* fix(webui): restore mobile graph drawing and touch file details

* test(webui): align legacy cache assertions with current label

* perf(context): retain source analysis and bound graph animation work

* style(webui): add light elevation to user messages

* test(webui): await lazy graph scene before replay assertions

* fix(webui): align preview skeleton and browser contracts
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-05 17:09:20 +08:00
1 parent 2b44088413
commit 519ed81132
132 files changed
+4673 -1159

No files matched your search

+10 -2
View File
@@ -10,6 +10,7 @@ from nanobot.agent.skills import SkillsLoader
from nanobot.agent.tools import mcp as mcp_tools
from nanobot.agent.tools import sessions as session_tools
from nanobot.apps.cli import utils as cli_app_utils
from nanobot.context_sources import record_source
from nanobot.runtime_context import (
RUNTIME_CONTEXT_MESSAGE_META,
RuntimeContextBlock,
@@ -98,7 +99,7 @@ class ContextBuilder:
if bootstrap:
parts.append(bootstrap)
parts.append(render_template("agent/tool_contract.md"))
parts.append(render_template("agent/tool_contract.md", track_source=True))
project_path = root.expanduser().resolve()
if project_path != self.workspace.expanduser().resolve():
@@ -112,6 +113,9 @@ class ContextBuilder:
memory = self.memory.read_memory()
if memory and not self._is_template_content(memory, "memory/MEMORY.md"):
parts.append(memory)
record_source(self.memory.memory_file, memory)
elif self.memory.memory_file.is_file():
record_source(self.memory.memory_file, "", loaded=False)
with self.skills.snapshot():
active_skills = self.skills.get_always_skills()
@@ -125,7 +129,7 @@ class ContextBuilder:
workspace=root,
)
if skills_summary:
parts.append(render_template("agent/skills_section.md", skills_summary=skills_summary))
parts.append(render_template("agent/skills_section.md", skills_summary=skills_summary, track_source=True))
if session_summary and session_summary["text"] != "(nothing)":
parts.append(
@@ -145,6 +149,7 @@ class ContextBuilder:
return render_template(
"agent/identity.md",
track_source=True,
workspace_path=workspace_path,
agent_workspace_path=agent_workspace_path,
runtime=runtime,
@@ -194,12 +199,15 @@ class ContextBuilder:
):
content = load_bundled_template("SOUL.md") or content
if not content.strip():
record_source(file_path, "", loaded=False)
continue
if filename in self._SKIPPABLE_DEFAULTS and self._is_template_content(
content, filename
):
record_source(file_path, "", loaded=False)
continue
parts.append(f"## {filename}\n\n{content}")
record_source(file_path, content)
return "\n\n".join(parts) if parts else ""
+7
View File
@@ -92,6 +92,10 @@ class AgentHook:
async def on_finally(self, context: AgentRunHookContext) -> None:
pass
async def before_model_request(self) -> None:
"""Observe a prepared logical request, including recovery requests."""
pass
async def before_iteration(self, context: AgentHookContext) -> None:
pass
@@ -207,6 +211,9 @@ class CompositeHook(AgentHook):
"AgentHook.{} error in {}", method_name, type(h).__name__,
)
async def before_model_request(self) -> None:
await self._for_each_hook_safe("before_model_request")
async def before_iteration(self, context: AgentHookContext) -> None:
await self._for_each_hook_safe("before_iteration", context)
+14
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from loguru import logger
@@ -8,6 +9,7 @@ from loguru import logger
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.bus.outbound_events import ProgressEvent, StreamDeltaEvent, StreamEndEvent
from nanobot.events import NO_EVENTS, EventSink
from nanobot.security.workspace_access import current_tool_workspace
from nanobot.utils.helpers import IncrementalThinkExtractor, strip_think
from nanobot.utils.progress_events import (
build_tool_event_finish_payloads,
@@ -25,12 +27,15 @@ class AgentProgressHook(AgentHook):
streaming: bool = False,
session_key: str | None = None,
log_content: bool = True,
workspace: Path | None = None,
) -> None:
super().__init__(reraise=True)
self._publish = events.publish
self._streaming = streaming
self._session_key = session_key
self._log_content = log_content
self._workspace = workspace
self._tool_workspaces: dict[str, str] = {}
self._stream_buf = ""
self._think_extractor = IncrementalThinkExtractor()
self._reasoning_open = False
@@ -150,10 +155,19 @@ class AgentProgressHook(AgentHook):
async def on_tool_execution_event(self, context: AgentHookContext) -> None:
if self._publish:
finished = bool(context.tool_events)
if not finished:
directory = str(current_tool_workspace(self._workspace).project_path or Path.cwd())
for call in context.tool_calls:
self._tool_workspaces[call.id] = directory
payloads = (
build_tool_event_finish_payloads(context) if finished
else [build_tool_event_start_payload(tc) for tc in context.tool_calls]
)
for payload in payloads:
call_id = payload["call_id"]
directory = self._tool_workspaces.pop(call_id, None) if finished else self._tool_workspaces.get(call_id)
if directory is not None:
payload["working_directory"] = directory
await self._publish(ProgressEvent(tool_hint=not finished, tool_events=payloads))
async def after_iteration(self, context: AgentHookContext) -> None:
+5
View File
@@ -929,6 +929,7 @@ class AgentRunner:
Callers reserve a live round slot; recovery invocations update it.
"""
request_id = uuid4().hex
request_usage: LLMUsage | None = None
async def emit(phase: Literal["started", "completed", "failed", "cancelled"]) -> None:
state.request_sequence += 1
@@ -940,9 +941,12 @@ class AgentRunner:
usage=state.request_usage,
round_usages=tuple(usage for usage in state.recent_round_usages if usage is not None),
context_window_tokens=spec.runtime.context_window_tokens,
request_usage=request_usage,
))
try:
if spec.hook is not None:
await spec.hook.before_model_request()
await emit("started")
_raise_if_cancelling()
response = await spec.runtime.provider.chat_stream_with_retry(**kwargs)
@@ -962,6 +966,7 @@ class AgentRunner:
reported_usage = response.usage.with_timing(
generation_ms=response.generation_ms, ttft_ms=response.ttft_ms,
)
request_usage = reported_usage
state.request_usage = self._merge_usage(state.request_usage, reported_usage)
state.recent_round_usages[-1] = self._merge_usage(
state.recent_round_usages[-1], reported_usage,
+17 -10
View File
@@ -21,6 +21,7 @@ from nanobot.agent.skill_metadata import (
from nanobot.agent.skill_metadata import (
valid_skill_metadata as valid_skill_metadata,
)
from nanobot.context_sources import record_source
from nanobot.runtime_context import RuntimeContextBlock
_SKILL_REFERENCE = re.compile(r"(?<![\w$])\$([A-Za-z0-9_-]+)")
@@ -166,7 +167,7 @@ class SkillsLoader:
with self.snapshot():
return self._load_skill(name)
def _load_skill(self, name: str) -> str | None:
def _load_skill(self, name: str, *, for_context: bool = False) -> str | None:
skills = self.list_skills(filter_unavailable=False)
available = {skill["name"] for skill in skills}
resolved = name if name in available else self._skill_aliases().get(name, name)
@@ -175,10 +176,14 @@ class SkillsLoader:
return None
snapshot = self._snapshot.get()
if snapshot is not None and resolved in snapshot.documents:
return snapshot.documents[resolved]
content = Path(entry["path"]).read_text(encoding="utf-8")
if snapshot is not None:
snapshot.documents[resolved] = content
content = snapshot.documents[resolved]
else:
content = Path(entry["path"]).read_text(encoding="utf-8")
if snapshot is not None:
snapshot.documents[resolved] = content
if for_context:
content = self._strip_frontmatter(content)
record_source(Path(entry["path"]), content)
return content
def load_skills_for_context(self, skill_names: list[str]) -> str:
@@ -191,11 +196,12 @@ class SkillsLoader:
Returns:
Formatted skills content.
"""
parts = [
f"### Skill: {name}\n\n{self._strip_frontmatter(markdown)}"
for name in skill_names
if (markdown := self.load_skill(name))
]
with self.snapshot():
parts = [
f"### Skill: {name}\n\n{content}"
for name in skill_names
if (content := self._load_skill(name, for_context=True))
]
return "\n\n---\n\n".join(parts)
def get_explicitly_invoked_skills(self, text: str) -> list[str]:
@@ -297,6 +303,7 @@ class SkillsLoader:
lines = [f"### {label} (`{display_root}`)"]
for entry in entries:
skill_name = entry["name"]
record_source(Path(entry["path"]), "", loaded=False)
desc = self.get_skill_description(skill_name)
relative_path = Path(entry["path"]).relative_to(root).as_posix()
lines.append(f"- **{skill_name}** — {desc} `{relative_path}`")
+1
View File
@@ -46,6 +46,7 @@ def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:
streaming=spec.streaming,
session_key=spec.session_key,
log_content=log_content,
workspace=spec.workspace,
)
if spec.ephemeral and not spec.run_extra_hooks_for_ephemeral:
return progress_hook
+2
View File
@@ -7,6 +7,7 @@ from nanobot.bus.outbound_events import (
StreamDeltaEvent,
StreamEndEvent,
)
from nanobot.context_sources import PromptSourcesEvent
from nanobot.events import (
AgentEvent,
ContextCompactionEvent,
@@ -29,6 +30,7 @@ NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = {
RetryStatusEvent: "interactive",
ResponseSourceEvent: "interactive",
ModelRequestEvent: "interactive",
PromptSourcesEvent: "interactive",
}
@@ -3700,10 +3700,10 @@ async def test_durable_incomplete_marker_stays_pending_without_safe_session_reco
original_append = history.sessions.state.append_history
async def fail_answer(session_key, facts, *, expected_generation):
async def fail_answer(session_key, facts, *, expected_generation, skip_invalid=False):
if any(fact.kind is HistoryKind.ANSWER for fact in facts):
raise OSError("transient disk failure")
await original_append(session_key, facts, expected_generation=expected_generation)
return await original_append(session_key, facts, expected_generation=expected_generation, skip_invalid=skip_invalid)
monkeypatch.setattr(history.sessions.state, "append_history", fail_answer)
@@ -3807,10 +3807,10 @@ async def test_http_replay_recovers_marked_answer_from_session_after_gateway_res
original_append = history.sessions.state.append_history
async def fail_answer(session_key, facts, *, expected_generation):
async def fail_answer(session_key, facts, *, expected_generation, skip_invalid=False):
if any(fact.kind is HistoryKind.ANSWER for fact in facts):
raise OSError("transient disk failure")
await original_append(session_key, facts, expected_generation=expected_generation)
return await original_append(session_key, facts, expected_generation=expected_generation, skip_invalid=skip_invalid)
monkeypatch.setattr(history.sessions.state, "append_history", fail_answer)
await channel.send(await history.message(
@@ -7004,3 +7004,99 @@ async def test_history_model_request_opt_in_preserves_old_clients_cursors_and_et
assert old_page["events"] == [event for event in modern_page["events"] if event["event"] != "model_request"]
assert old_page["page"]["loaded_event_count"] == len(old_page["events"])
assert modern_page["page"]["loaded_event_count"] == len(modern_page["events"])
@pytest.mark.asyncio
@pytest.mark.parametrize("state", ["missing", "present", "new_request"])
async def test_thread_replays_durable_compaction_boundaries(history, tmp_path, monkeypatch, state):
from urllib.parse import quote
from websockets.http11 import Request
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:legacy-context"
snapshot = {"graph": {"nodes": [], "edges": []}, "estimated_tokens": 100, "context_window_tokens": 1000}
history.append(key, {"event": "user", "chat_id": "legacy-context", "text": "hello"})
compact = {"event": "context_compaction", "compaction_id": "compact", "phase": "succeeded"}
if state == "present":
compact["context_snapshot"] = snapshot
history.append(key, compact)
if state == "new_request":
history.append(key, {"event": "model_request", "request_id": "request", "run_id": "run", "sequence": 1, "phase": "started"})
gateway = _basic_handler(MagicMock(), workspace_path=tmp_path, session_manager=history.sessions)
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
encoded = quote(key, safe="")
path = f"/api/sessions/{encoded}/webui-thread?include_model_requests=1"
request = Request(path, Headers([("Authorization", "Bearer tok")]))
response = await gateway.http._handle_webui_thread_get_async(request, encoded)
assert response.status_code == 200
body = json.loads(response.body)
event = next(event for event in body["events"] if event["event"] == "context_compaction")
assert event["phase"] == "succeeded"
assert event["compaction_id"] == "compact"
if state == "present":
assert event["context_snapshot"] == snapshot
else:
# Historical reads must not invent a snapshot from today's disk files.
assert "context_snapshot" not in event
cached_request = Request(path, Headers([("Authorization", "Bearer tok"), ("If-None-Match", response.headers["ETag"])]))
cached = await gateway.http._handle_webui_thread_get_async(cached_request, encoded)
assert cached.status_code == 304
@pytest.mark.asyncio
async def test_context_graph_dictionary_pages_are_self_contained_and_opt_in(history):
from urllib.parse import quote
from websockets.http11 import Request
key = "websocket:graph-pages"
graph = {"nodes": [{"path": "/guide.md", "name": "guide.md", "tokens": 10, "state": "loaded"}], "edges": []}
for number in range(3):
history.append(key, {"event": "user", "text": f"question {number}"})
history.append(key, {"event": "model_request", "request_id": str(number), "run_id": str(number), "sequence": 2, "phase": "completed", "context_graph": graph, "request_usage": {"context_tokens": number + 10}})
history.append(key, {"event": "context_compaction", "compaction_id": str(number), "phase": "succeeded", "context_snapshot": {"graph": graph, "estimated_tokens": 5, "context_window_tokens": 100}})
history.append(key, {"event": "turn_end"})
channel = _ch(MagicMock(), session_manager=history.sessions)
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
encoded = quote(key, safe="")
async def fetch(before=None, compact=False, etag=None):
query = "include_model_requests=1&limit=1"
if before:
query += "&before=" + quote(before, safe="")
if compact:
query += "&context_graph_encoding=references-v1"
headers = [("Authorization", "Bearer tok")]
if etag:
headers.append(("If-None-Match", etag))
return await channel.gateway.http._handle_webui_thread_get_async(Request(f"/api/sessions/{encoded}/webui-thread?{query}", Headers(headers)), encoded)
before = None
seen = []
for _ in range(3):
old_response = await fetch(before)
compact_response = await fetch(before, compact=True, etag=old_response.headers["ETag"])
assert compact_response.status_code == 200
old = json.loads(old_response.body)
compact = json.loads(compact_response.body)
assert "context_graphs" not in old
assert len(compact["context_graphs"]) == 1
assert compact["context_graph_nodes"] == graph["nodes"]
assert compact["context_graph_edges"] == graph["edges"]
decoded_graphs = {key: {
"nodes": [compact["context_graph_nodes"][index] for index in descriptor["nodes"]],
"edges": [compact["context_graph_edges"][index] for index in descriptor["edges"]],
} for key, descriptor in compact["context_graphs"].items()}
for event in compact["events"]:
if "context_graph_ref" in event:
event["context_graph"] = decoded_graphs[event.pop("context_graph_ref")]
seen.append(event["request_id"])
if "context_snapshot" in event:
snapshot = event["context_snapshot"]
snapshot["graph"] = decoded_graphs[snapshot.pop("graph_ref")]
assert compact["events"] == old["events"]
assert compact["page"]["before_cursor"] == old["page"]["before_cursor"]
before = compact["page"]["before_cursor"]
assert seen == ["2", "1", "0"]
@@ -574,10 +574,18 @@ async def test_ready_activity_group_commits_before_ordered_fanout(history, monke
if index < 2:
entered[index].set()
await release[index].wait()
await append(key, facts, **kwargs)
return await append(key, facts, **kwargs)
monkeypatch.setattr(history.sessions.state, "append_history", gated_append)
usage = LLMUsage.reported(input_tokens=100, output_tokens=20)
from nanobot.context_graph import graph_from_sources
from nanobot.context_sources import PromptSource, PromptSourcesEvent
from nanobot.file_references import source_receipt
source = PromptSource(tmp_path / "guide.md", "Guide content")
graph = graph_from_sources([source_receipt(source.path, source.content)])
await channel.send(OutboundMessage(
"websocket", chat, "", metadata=metadata, event=PromptSourcesEvent((source,)),
))
events = [
ModelRequestEvent("request", "run", 1, "started"),
RetryStatusEvent(state="cleared", attempt=1, max_attempts=None, error_kind="unknown"),
@@ -612,12 +620,14 @@ async def test_ready_activity_group_commits_before_ordered_fanout(history, monke
"model_request", "retry_status", "model_request", "message", "message", "message", "turn_end", "session_updated",
]
assert frames[2]["usage"] == usage.to_turn_dict()
assert frames[0]["context_graph"] == frames[2]["context_graph"] == graph
assert frames[4]["tool_events"][0]["result"] == "complete"
assert [len(facts) for facts in writes] == [1, 4, 1, 1]
durable = history.read(f"websocket:{chat}")
assert [row["turn_seq"] for row in durable] == list(range(1, 8))
assert durable[4]["tool_events"][0]["result"] == "complete"
assert durable[-1]["event"] == "turn_end"
assert all(row["context_graph"] == graph for row in durable if row["event"] == "model_request")
late_frames = [json.loads(late.sent.get_nowait()) for _ in range(late.sent.qsize())]
assert [frame["event"] for frame in late_frames] == ["message", "turn_end", "session_updated"]
assert late_frames[0]["text"] == "answer"
@@ -768,3 +778,51 @@ async def test_unencodable_tool_argument_does_not_discard_neighboring_activity(h
assert [row["text"] for row in history.read(f"websocket:{chat}")] == ["first", "last"]
finally:
await channel.stop()
@pytest.mark.parametrize("batched", [False, True])
async def test_context_observer_orders_reads_requests_and_compaction(history, tmp_path, batched):
from nanobot.agent.tools.filesystem import ReadFileTool
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, TurnEndEvent
from nanobot.events import ModelRequestEvent
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
(tmp_path / "guide.md").write_text("[Reference](reference.md)")
result = await ReadFileTool(workspace=tmp_path).execute(path="guide.md")
tool = {"name": "read_file", "call_id": "read", "phase": "end",
"arguments": {"path": "guide.md"}, "result": result}
channel = _channel(history.sessions)
chat = "observed-context"
async def message(event):
return await history.message(channel="websocket", chat_id=chat, content="", event=event,
metadata={WEBUI_TURN_METADATA_KEY: "turn"})
events = [
ModelRequestEvent("before", "run", 1, "started"),
ProgressEvent(tool_events=[{**tool, "working_directory": str(tmp_path)}]),
ModelRequestEvent("after", "run", 2, "started"),
]
messages = [await message(event) for event in events]
if batched:
await channel.send_batch(messages)
else:
for msg in messages:
await channel.send(msg)
requests = [row for row in history.read(f"websocket:{chat}") if row["event"] == "model_request"]
assert requests[0]["context_graph"] == {"nodes": [], "edges": []}
graph = requests[-1]["context_graph"]
assert [(node["name"], node["state"]) for node in graph["nodes"]] == [
("guide.md", "loaded"), ("reference.md", "discovered"),
]
# End-of-turn cleanup and a fresh delivery service must recover display state.
await channel.send(await message(TurnEndEvent()))
channel = _channel(history.sessions)
await channel.send(await message(ContextCompactionEvent("failed", "failed")))
await channel.send(await message(ModelRequestEvent("restored", "run", 3, "started")))
requests = [row for row in history.read(f"websocket:{chat}") if row["event"] == "model_request"]
assert requests[-1]["context_graph"] == graph
await channel.send(await message(ContextCompactionEvent("done", "succeeded")))
await channel.send(await message(ModelRequestEvent("reset", "run", 4, "started")))
requests = [row for row in history.read(f"websocket:{chat}") if row["event"] == "model_request"]
assert requests[-1]["context_graph"] == {"nodes": [], "edges": []}
+2 -1
View File
@@ -65,6 +65,7 @@ from nanobot.utils.helpers import sanitize_surrogates as _sanitize_surrogates #
from nanobot.utils.helpers import ( # noqa: E402
sync_workspace_templates,
)
from nanobot.webui.context_source_hook import create_context_source_hook # noqa: E402
# Backward-compatible import for callers that used the former module location.
SafeFileHistory = cli_terminal.SafeFileHistory
@@ -388,7 +389,7 @@ def serve(
runtime_config, bus,
provider=unconfigured_provider,
session_manager=session_manager,
hook_factories=[create_file_edit_activity_hook],
hook_factories=[create_file_edit_activity_hook, create_context_source_hook],
tool_registry=tools,
builtin_assembly=install_goal,
)
+2 -1
View File
@@ -55,6 +55,7 @@ from nanobot.utils.evaluator import evaluate_response, resolve_evaluator_prompt
from nanobot.utils.helpers import sync_workspace_templates
from nanobot.utils.token_encoding import warmup_token_encoding
from nanobot.webui.build import BuildMode
from nanobot.webui.context_source_hook import create_context_source_hook
from nanobot.webui.dev import WebUIDevError, WebUIDevServer
from nanobot.webui.sidebar_state import ensure_webui_session_archives
@@ -608,7 +609,7 @@ def _run_claimed_gateway(
provider_signature=provider_snapshot.signature,
local_trigger_store=trigger_store,
hooks=[_MCPReadinessHook(mcp_provider)],
hook_factories=[create_file_edit_activity_hook],
hook_factories=[create_file_edit_activity_hook, create_context_source_hook],
tool_registry=tools,
recovery_admission=recovery,
builtin_assembly=install_goal,
+85
View File
@@ -0,0 +1,85 @@
"""Client graph projection of file-use facts and persisted snapshot validation."""
from __future__ import annotations
from collections.abc import Sequence
from pathlib import Path
from typing import Literal, TypedDict, cast
from nanobot.context_sources import SourceReceipt
class ContextNode(TypedDict):
path: str
name: str
state: Literal["loaded", "discovered"]
tokens: int
class ContextEdge(TypedDict):
source: str
target: str
class ContextGraph(TypedDict):
nodes: list[ContextNode]
edges: list[ContextEdge]
def parse_context_graph(value: object) -> ContextGraph | None:
"""Validate persisted graph data at the transcript boundary."""
if not isinstance(value, dict):
return None
value = cast(dict[str, object], value)
raw_nodes, raw_edges = value.get("nodes"), value.get("edges")
if not isinstance(raw_nodes, list) or not isinstance(raw_edges, list):
return None
nodes: list[ContextNode] = []
for raw_node in cast(list[object], raw_nodes):
if not isinstance(raw_node, dict):
return None
node = cast(dict[str, object], raw_node)
path, name = node.get("path"), node.get("name")
if not isinstance(path, str) or not isinstance(name, str):
return None
tokens, state = node.get("tokens"), node.get("state")
if not isinstance(tokens, int) or isinstance(tokens, bool) or tokens < 0 or state not in ("loaded", "discovered"):
return None
nodes.append({"path": path, "name": name, "tokens": tokens,
"state": "loaded" if state == "loaded" else "discovered"})
paths = {node["path"] for node in nodes}
edges: list[ContextEdge] = []
for raw_edge in cast(list[object], raw_edges):
if not isinstance(raw_edge, dict):
return None
edge = cast(dict[str, object], raw_edge)
source, target = edge.get("source"), edge.get("target")
if not isinstance(source, str) or not isinstance(target, str):
return None
if source not in paths or target not in paths:
return None
edges.append({"source": source, "target": target})
return {"nodes": nodes, "edges": edges}
def graph_from_sources(sources: Sequence[SourceReceipt]) -> ContextGraph:
"""Project files used in this epoch, regardless of subsequent text edits."""
nodes: dict[str, ContextNode] = {}
edges: dict[tuple[str, str], ContextEdge] = {}
for source in sources:
path = source["path"]
node = nodes.setdefault(path, {"path": path, "name": source["name"], "state": "discovered", "tokens": 0})
if source["loaded"]:
node["state"] = "loaded"
node["tokens"] = max(node["tokens"], source["tokens"])
for target in source["links"]:
if target not in nodes:
nodes[target] = {"path": target, "name": Path(target).name, "state": "discovered", "tokens": 0}
edges[path, target] = {"source": path, "target": target}
return {"nodes": list(nodes.values()), "edges": list(edges.values())}
class ContextSnapshot(TypedDict):
graph: ContextGraph
estimated_tokens: int
context_window_tokens: int
+70
View File
@@ -0,0 +1,70 @@
"""Compact file-use facts captured at source boundaries, not prompt-retention claims."""
from __future__ import annotations
from collections.abc import Generator
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from pathlib import Path
from typing import TypedDict, cast
from nanobot.events import AgentEvent
class SourceReceipt(TypedDict):
path: str
name: str
tokens: int
links: list[str]
loaded: bool
@dataclass(frozen=True)
class PromptSource:
path: Path
content: str
loaded: bool = True
@dataclass(frozen=True)
class PromptSourcesEvent(AgentEvent):
sources: tuple[PromptSource, ...]
_sources: ContextVar[list[PromptSource] | None] = ContextVar("context_sources", default=None)
@contextmanager
def capture_sources() -> Generator[list[PromptSource]]:
"""Observe builder reads in one run, including its prompt worker tasks."""
sources: list[PromptSource] = []
token = _sources.set(sources)
try:
yield sources
finally:
_sources.reset(token)
def record_source(path: Path, content: str, *, loaded: bool = True) -> None:
if (sources := _sources.get()) is not None:
# Keep parsing and token estimation out of prompt construction.
sources.append(PromptSource(path, content, loaded))
def parse_source_receipt(value: object) -> SourceReceipt | None:
"""Validate one persisted file-read fact at the display history boundary."""
if not isinstance(value, dict):
return None
source = cast(dict[str, object], value)
path, name, tokens = source.get("path"), source.get("name"), source.get("tokens")
links, loaded = source.get("links"), source.get("loaded")
if not isinstance(path, str) or not isinstance(name, str):
return None
if not isinstance(tokens, int) or isinstance(tokens, bool) or tokens < 0:
return None
if not isinstance(loaded, bool) or not isinstance(links, list):
return None
if not all(isinstance(link, str) for link in cast(list[object], links)):
return None
return {"path": path, "name": name, "tokens": tokens, "links": cast(list[str], links), "loaded": loaded}
+1
View File
@@ -24,6 +24,7 @@ class ModelRequestEvent(AgentEvent):
usage: LLMUsage | None = None
round_usages: tuple[LLMUsage, ...] = ()
context_window_tokens: int | None = None
request_usage: LLMUsage | None = None
@dataclass(frozen=True)
+112
View File
@@ -0,0 +1,112 @@
"""Analyze bounded file reads; syntax support is registered by suffix."""
from __future__ import annotations
from collections import OrderedDict
from collections.abc import Iterator
from pathlib import Path
from threading import Lock
from typing import TYPE_CHECKING, Protocol
from urllib.parse import unquote, urlsplit
from markdown_it import MarkdownIt
from nanobot.context_sources import SourceReceipt
from nanobot.utils.token_encoding import get_token_encoding
if TYPE_CHECKING:
from tiktoken import Encoding
class ReferenceParser(Protocol):
def references(self, content: str) -> Iterator[str]: ...
class MarkdownReferences:
def references(self, content: str) -> Iterator[str]:
for block in MarkdownIt("commonmark").parse(content):
for token in block.children or ():
if token.type == "link_open" and (href := token.attrGet("href")):
if isinstance(href, str):
yield href
# Bound retained source text, rather than evicting a normal prompt's working set
# after sixteen files. Results contain unresolved links so directory/symlink
# changes still take effect on every observation.
_ANALYSIS_SOURCE_BYTES = 4 * 1024 * 1024
_ANALYSIS_ENTRIES = 256
_analysis_cache: OrderedDict[
tuple[str, ReferenceParser | None, Encoding | None],
tuple[int, tuple[str, ...], int],
] = OrderedDict()
_analysis_bytes = 0
_analysis_lock = Lock()
def _analyze_source(content: str, parser: ReferenceParser | None) -> tuple[int, tuple[str, ...]]:
global _analysis_bytes
encoding = get_token_encoding()
key = (content, parser, encoding)
with _analysis_lock:
if (cached := _analysis_cache.get(key)) is not None:
_analysis_cache.move_to_end(key)
return cached[0], cached[1]
source_bytes = len(content.encode("utf-8"))
links = tuple(dict.fromkeys(parser.references(content))) if parser else ()
tokens = source_bytes
if encoding is not None:
try:
tokens = len(encoding.encode_ordinary(content))
except Exception:
# Do not cache a transient encoding failure as a successful estimate.
return tokens, links
if source_bytes <= _ANALYSIS_SOURCE_BYTES:
with _analysis_lock:
# Concurrent observers may have analyzed the same content meanwhile.
if key not in _analysis_cache:
while _analysis_cache and (
_analysis_bytes + source_bytes > _ANALYSIS_SOURCE_BYTES
or len(_analysis_cache) >= _ANALYSIS_ENTRIES
):
_analysis_bytes -= _analysis_cache.popitem(last=False)[1][2]
_analysis_cache[key] = (tokens, links, source_bytes)
_analysis_bytes += source_bytes
return tokens, links
REFERENCE_PARSERS: dict[str, ReferenceParser] = {
".md": MarkdownReferences(),
".markdown": MarkdownReferences(),
}
def source_receipt(path: Path, content: str, *, loaded: bool = True) -> SourceReceipt:
"""Discover links without opening, checking, or fetching their targets."""
path = path.resolve()
links: list[str] = []
parser = REFERENCE_PARSERS.get(path.suffix.lower()) if loaded else None
tokens, references = _analyze_source(content, parser) if loaded else (0, ())
if parser:
seen: set[str] = set()
for href in references:
if href in seen:
continue
seen.add(href)
try:
parsed = urlsplit(href)
if parsed.scheme or parsed.netloc or not parsed.path:
continue
decoded_path = unquote(parsed.path)
if "\x00" in decoded_path:
continue
target = str((path.parent / decoded_path).resolve())
except (ValueError, OSError, RuntimeError):
# Link text is untrusted; invalid paths must not break prompt assembly.
continue
if target != str(path) and target not in links:
links.append(target)
if len(links) >= 128:
break
return {"path": str(path), "name": path.parent.name if path.name == "SKILL.md" else path.name, "tokens": tokens,
"links": links, "loaded": loaded}
+18 -6
View File
@@ -8,6 +8,8 @@ from enum import StrEnum
from pathlib import Path
from typing import Any, cast
from nanobot.session.history_graph import encode_graph_fields, graph_size_adjustment
MAX_HISTORY_FACT_BYTES = 8 * 1024 * 1024
HISTORY_GENERATION_METADATA_KEY = "_history_generation"
@@ -40,13 +42,23 @@ class HistoryFact:
created_at_ms: int = 0
def encode(self) -> str:
record = json.dumps({
"kind": self.kind.value, "content": dict(self.content),
content = encode_graph_fields(self.content)
payload = {
"kind": self.kind.value, "content": content,
"turn_id": self.turn_id, "phase": self.phase,
"sequence": self.sequence, "created_at_ms": self.created_at_ms,
}, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
if len(record.encode("utf-8")) > MAX_HISTORY_FACT_BYTES:
}
record = json.dumps(payload, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
stored_bytes = len(record.encode("utf-8"))
adjustment = graph_size_adjustment(content)
logical_bytes = stored_bytes + adjustment
if max(stored_bytes, logical_bytes) > MAX_HISTORY_FACT_BYTES:
raise ValueError("history fact exceeds the 8 MiB storage limit")
if adjustment:
payload["uncompressed_bytes"] = logical_bytes
record = json.dumps(payload, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
if len(record.encode("utf-8")) > MAX_HISTORY_FACT_BYTES:
raise ValueError("history fact exceeds the 8 MiB storage limit")
return record
@classmethod
@@ -116,14 +128,14 @@ class HistoryReader:
((HistoryKind.COMPLETION,), "DESC"),
((HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT, HistoryKind.ANSWER_FRAGMENT), "DESC")):
row = self._db.execute(
f"SELECT position, length(CAST(record AS BLOB)) FROM history_entries WHERE {clause} "
f"SELECT position, coalesce(json_extract(record, '$.uncompressed_bytes'), length(CAST(record AS BLOB))) FROM history_entries WHERE {clause} "
f"AND kind IN ({','.join('?' for _ in kinds)}) ORDER BY position {order} LIMIT 1",
(*params, *kinds),
).fetchone()
if row is not None:
priorities.append((row[0], row[1]))
candidates = self._db.execute(
f"SELECT position, length(CAST(record AS BLOB)) FROM history_entries WHERE {clause} ORDER BY position DESC LIMIT ?",
f"SELECT position, coalesce(json_extract(record, '$.uncompressed_bytes'), length(CAST(record AS BLOB))) FROM history_entries WHERE {clause} ORDER BY position DESC LIMIT ?",
(*params, max_records),
)
positions: set[int] = set()
+250
View File
@@ -0,0 +1,250 @@
"""Self-contained graph values for history facts; encoding runs in the storage worker."""
from __future__ import annotations
import base64
import json
import zlib
from collections.abc import Generator, Mapping
from contextlib import contextmanager
from contextvars import ContextVar
from functools import lru_cache
from typing import Any, cast
from nanobot.context_graph import (
ContextEdge,
ContextGraph,
ContextNode,
ContextSnapshot,
parse_context_graph,
)
_PREFIX = "graph-columns-v1:"
_MAX_BYTES = 8 * 1024 * 1024
_CACHEABLE_BYTES = 128 * 1024
@lru_cache(maxsize=16)
def _compress_small(serialized: str) -> str | None:
return _compress(serialized)
def _compress(serialized: str) -> str | None:
graph = parse_context_graph(json.loads(serialized))
if graph is None:
return None
paths = {node["path"]: index for index, node in enumerate(graph["nodes"])}
columns = [
[[node["path"], node["name"], node["tokens"], node["state"]] for node in graph["nodes"]],
[index for edge in graph["edges"] for index in (paths[edge["source"]], paths[edge["target"]])],
]
raw = json.dumps(columns, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
return f"{_PREFIX}{len(serialized.encode('utf-8'))}:{len(raw)}:" + base64.b64encode(zlib.compress(raw, level=1)).decode("ascii")
def encode_graph(value: object) -> object:
if not isinstance(value, dict):
return value
value = cast(dict[str, object], value)
serialized = json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
size = len(serialized.encode("utf-8"))
if size > _MAX_BYTES:
raise ValueError("history graph exceeds the 8 MiB storage limit")
encoded = _compress_small(serialized) if size <= _CACHEABLE_BYTES else _compress(serialized)
return encoded if encoded is not None else value
def encode_graph_fields(content: Mapping[str, Any]) -> dict[str, Any]:
result = dict(content)
if "context_graph" in result:
result["context_graph"] = encode_graph(result["context_graph"])
snapshot = result.get("context_snapshot")
if isinstance(snapshot, dict) and "graph" in snapshot:
snapshot = cast(dict[str, Any], snapshot)
result["context_snapshot"] = {**snapshot, "graph": encode_graph(snapshot["graph"])}
return result
class GraphDecoder:
"""One projection owns validated shared entities, including changing snapshots."""
def __init__(self) -> None:
self.graphs: dict[str, ContextGraph | None] = {}
self.nodes: dict[tuple[object, ...], ContextNode] = {}
self.edges: dict[tuple[object, object], ContextEdge] = {}
self.sizes: dict[int, int] = {}
def node(self, path: object, name: object, tokens: object, state: object) -> ContextNode | None:
key = (path, name, type(tokens), tokens, state)
try:
cached = self.nodes.get(key)
except TypeError:
return None
if cached is not None:
return cached
if not isinstance(path, str) or not isinstance(name, str) or type(tokens) is not int or tokens < 0 or state not in ("loaded", "discovered"):
return None
node: ContextNode = {"path": path, "name": name, "tokens": tokens,
"state": "loaded" if state == "loaded" else "discovered"}
self.nodes[key] = node
self.sizes[id(node)] = len(json.dumps(node, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
return node
def edge(self, source: str, target: str) -> ContextEdge:
key = (source, target)
if key not in self.edges:
edge: ContextEdge = {"source": source, "target": target}
self.edges[key] = edge
self.sizes[id(edge)] = len(json.dumps(edge, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
return self.edges[key]
def inline(self, value: object) -> ContextGraph | None:
if not isinstance(value, dict):
return None
value = cast(dict[str, object], value)
raw_nodes, raw_edges = value.get("nodes"), value.get("edges")
if not isinstance(raw_nodes, list) or not isinstance(raw_edges, list):
return None
nodes: list[ContextNode] = []
for raw in cast(list[object], raw_nodes):
if not isinstance(raw, dict):
return None
row = cast(dict[str, object], raw)
node = self.node(row.get("path"), row.get("name"), row.get("tokens"), row.get("state"))
if node is None:
return None
nodes.append(node)
paths = {node["path"] for node in nodes}
edges: list[ContextEdge] = []
for raw in cast(list[object], raw_edges):
if not isinstance(raw, dict):
return None
row = cast(dict[str, object], raw)
source, target = row.get("source"), row.get("target")
if not isinstance(source, str) or not isinstance(target, str) or source not in paths or target not in paths:
return None
edges.append(self.edge(source, target))
return {"nodes": nodes, "edges": edges}
def columns(self, value: object, logical_bytes: int) -> ContextGraph | None:
if not isinstance(value, list) or len(cast(list[object], value)) != 2:
return None
rows, indices = cast(list[object], value)
if not isinstance(rows, list) or not isinstance(indices, list) or len(cast(list[object], indices)) % 2:
return None
nodes: list[ContextNode] = []
for row in cast(list[object], rows):
if not isinstance(row, list) or len(cast(list[object], row)) != 4:
return None
path, name, tokens, state = cast(list[object], row)
node = self.node(path, name, tokens, state)
if node is None:
return None
nodes.append(node)
indices = cast(list[object], indices)
if any(type(index) is not int or not 0 <= index < len(nodes) for index in indices):
return None
positions = cast(list[int], indices)
edges = [self.edge(nodes[positions[i]]["path"], nodes[positions[i + 1]]["path"])
for i in range(0, len(positions), 2)]
# Do not trust a small declared logical size to bypass the replay byte budget.
size = 23 + max(0, len(nodes) - 1) + max(0, len(edges) - 1)
size += sum(self.sizes[id(node)] for node in nodes) + sum(self.sizes[id(edge)] for edge in edges)
return {"nodes": nodes, "edges": edges} if size <= logical_bytes else None
def graph(self, value: object) -> ContextGraph | None:
if isinstance(value, str):
key = value
elif isinstance(value, dict):
try:
key = json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
except (ValueError, TypeError):
return None
else:
return None
if key in self.graphs:
return self.graphs[key]
self.graphs[key] = None
if isinstance(value, str):
if not value.startswith(_PREFIX) or len(value) > _MAX_BYTES * 2:
return None
try:
logical_text, size_text, encoded = value[len(_PREFIX):].split(":", 2)
logical_size, size = int(logical_text), int(size_text)
if not 0 <= logical_size <= _MAX_BYTES or not 0 <= size <= _MAX_BYTES:
return None
raw = base64.b64decode(encoded, validate=True)
inflater = zlib.decompressobj()
expanded = inflater.decompress(raw, _MAX_BYTES + 1)
if len(expanded) != size or not inflater.eof or inflater.unused_data:
return None
graph = self.columns(json.loads(expanded), logical_size)
except (ValueError, zlib.error, UnicodeDecodeError):
return None
else:
graph = self.inline(cast(object, value))
self.graphs[key] = graph
return graph
_decoder: ContextVar[GraphDecoder | None] = ContextVar("history_graph_decoder", default=None)
@contextmanager
def graph_decoding() -> Generator[None]:
token = _decoder.set(GraphDecoder())
try:
yield
finally:
_decoder.reset(token)
def decode_graph(value: object) -> ContextGraph | None:
return (_decoder.get() or GraphDecoder()).graph(value)
def decode_snapshot(value: object) -> ContextSnapshot | None:
if not isinstance(value, dict):
return None
snapshot = cast(dict[str, object], value)
tokens, window = snapshot.get("estimated_tokens"), snapshot.get("context_window_tokens")
if type(tokens) is not int or tokens < 0 or type(window) is not int or window <= 0:
return None
graph = decode_graph(snapshot.get("graph"))
return {"graph": graph, "estimated_tokens": tokens, "context_window_tokens": window} if graph is not None else None
def expand_graph_fields(content: Mapping[str, Any]) -> dict[str, Any]:
result = dict(content)
for field, decode in (("context_graph", decode_graph), ("context_snapshot", decode_snapshot)):
if field in result:
decoded = decode(result[field])
if decoded is None:
result.pop(field)
else:
result[field] = decoded
return result
def graph_size_adjustment(content: Mapping[str, Any]) -> int:
"""Retain the original replay byte budget despite storage compression."""
values = [content.get("context_graph")]
snapshot = content.get("context_snapshot")
if isinstance(snapshot, dict):
values.append(cast(dict[str, object], snapshot).get("graph"))
adjustment = 0
for value in values:
if isinstance(value, str) and value.startswith(_PREFIX):
try:
size = int(value[len(_PREFIX):].split(":", 1)[0])
except ValueError:
continue
if 0 <= size <= _MAX_BYTES:
adjustment += size - len(value) - 2 # ASCII encoding plus JSON quotes.
return adjustment
def history_record_size(record: str) -> int:
stored = len(record.encode("utf-8"))
if '"uncompressed_bytes":' not in record:
return stored
value = json.loads(record).get("uncompressed_bytes")
return value if type(value) is int and 0 <= value <= _MAX_BYTES else stored
+29 -12
View File
@@ -12,6 +12,7 @@ from typing import Any, TypeVar, cast
from nanobot.providers.base import ProviderConversationState
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.session.history_graph import history_record_size
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import (
Session,
@@ -428,8 +429,25 @@ class SqliteSessionStore:
def append_history(
self, key: str, facts: list[HistoryFact], *, expected_generation: str | None,
) -> None:
encoded = [(fact, fact.encode()) for fact in facts]
skip_invalid: bool = False,
) -> list[str]:
encoded: list[tuple[HistoryKind, int, str, str]] = []
errors: list[str] = []
for fact in facts:
try:
record = fact.encode()
# Freeze all transaction inputs from the encoded snapshot; never
# revisit mutable content after serialization has completed.
preview = ""
if fact.kind in {HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT}:
preview = message_preview_text({"content": json.loads(record)["content"].get("text", "")})
encoded.append((fact.kind, fact.created_at_ms, record, preview))
except (ValueError, TypeError) as exc:
if not skip_invalid:
raise
errors.append(str(exc))
if not encoded and errors:
return errors
with self.transaction() as db:
row = db.execute("SELECT generation FROM sessions WHERE key=?", (key,)).fetchone()
if row is None or (expected_generation is not None and row[0] != expected_generation):
@@ -441,7 +459,7 @@ class SqliteSessionStore:
).fetchone()
ordinal, position = (int(tail[0]), int(tail[1])) if tail is not None else (0, 0)
completed = tail is not None and bool(tail[2])
for fact, record in encoded:
for kind, created_at_ms, record, preview in encoded:
if completed:
ordinal, position = ordinal + 1, 0
if position == 0:
@@ -449,25 +467,24 @@ class SqliteSessionStore:
"INSERT INTO history_turns VALUES (?, ?, 0, 0, 0, 0)", (key, ordinal),
)
db.execute("INSERT INTO history_entries VALUES (?, ?, ?, ?, ?)", (
key, ordinal, position, fact.kind.value, record,
key, ordinal, position, kind.value, record,
))
completed = fact.kind is HistoryKind.COMPLETION
completed = kind is HistoryKind.COMPLETION
db.execute(
"""UPDATE history_turns SET record_count=record_count+1, byte_count=byte_count+?,
user_count=user_count+?, completed=? WHERE session_key=? AND ordinal=?""",
(len(record.encode("utf-8")), int(fact.kind is HistoryKind.INPUT),
(history_record_size(record), int(kind is HistoryKind.INPUT),
int(completed), key, ordinal),
)
position += 1
if fact.kind in {HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT}:
preview = message_preview_text({"content": fact.content.get("text", "")})
if preview:
field = "user_preview" if fact.kind is HistoryKind.INPUT else "preview"
db.execute(f"UPDATE history_heads SET {field}=? WHERE session_key=? AND {field}=''", (preview, key))
if preview:
field = "user_preview" if kind is HistoryKind.INPUT else "preview"
db.execute(f"UPDATE history_heads SET {field}=? WHERE session_key=? AND {field}=''", (preview, key))
db.execute("UPDATE history_heads SET updated_at_ms=max(updated_at_ms, ?) WHERE session_key=?",
(fact.created_at_ms, key))
(created_at_ms, key))
if encoded:
db.execute("UPDATE history_heads SET revision=revision+1 WHERE session_key=?", (key,))
return errors
def copy_history_prefix(self, source_key: str, target: Session, before_input: int) -> bool:
"""Copy a display prefix alongside its canonical fork, in the caller's transaction."""
+6 -4
View File
@@ -725,12 +725,14 @@ class SessionState:
async def append_history(
self, key: str, facts: Sequence[HistoryFact], *, expected_generation: str | None,
) -> None:
"""Append to an existing session; None selects its current generation."""
skip_invalid: bool = False,
) -> list[str]:
"""Serialize owned facts in the worker; None selects the current generation."""
records = list(facts)
await self._execute(
return await self._execute(
key,
lambda: self._store.append_history(key, deepcopy(records), expected_generation=expected_generation),
lambda: self._store.append_history(key, records, expected_generation=expected_generation,
skip_invalid=skip_invalid),
operation_name="append_history",
)
+7 -2
View File
@@ -11,6 +11,8 @@ from typing import Any
from jinja2 import Environment, FileSystemLoader
from nanobot.context_sources import record_source
_TEMPLATES_ROOT = Path(__file__).resolve().parent.parent / "templates"
@@ -25,11 +27,14 @@ def _environment() -> Environment:
)
def render_template(name: str, *, strip: bool = False, **kwargs: Any) -> str:
def render_template(name: str, *, strip: bool = False, track_source: bool = False, **kwargs: Any) -> str:
"""Render ``name`` (e.g. ``agent/identity.md``, ``agent/platform_policy.md``) under ``templates/``.
Use ``strip=True`` for single-line user-facing strings when the file ends
with a trailing newline you do not want preserved.
"""
text = _environment().get_template(name).render(**kwargs)
return text.rstrip() if strip else text
text = text.rstrip() if strip else text
if track_source:
record_source(_TEMPLATES_ROOT / name, text)
return text
+2 -1
View File
@@ -26,6 +26,7 @@ UPDATE_RETRY_CAPABILITY = "webui.update-jobs.retry-handoff.v1"
UPDATE_SETTLE_HANDOFF_CAPABILITY = "webui.update-jobs.settle-handoff.v1"
UPDATE_FLOW_CAPABILITY = "webui.update-flow.v1"
UPDATE_CHANNEL_CAPABILITY = "webui.update-channels.v1"
CONTEXT_GRAPH_REFERENCES_CAPABILITY = "webui.context-graph.references.v1"
PROMPT_NAVIGATION_CAPABILITY = "webui.prompt-navigation.v1"
@@ -46,7 +47,7 @@ def webui_contract() -> dict[str, object]:
BINARY_ATTACHMENTS_CAPABILITY, UPDATE_PLAN_CAPABILITY,
UPDATE_JOB_CAPABILITY, UPDATE_PREPARATION_CAPABILITY, UPDATE_EXECUTION_CAPABILITY,
UPDATE_RETRY_CAPABILITY, UPDATE_SETTLE_HANDOFF_CAPABILITY, UPDATE_FLOW_CAPABILITY, UPDATE_CHANNEL_CAPABILITY,
PROMPT_NAVIGATION_CAPABILITY,
PROMPT_NAVIGATION_CAPABILITY, CONTEXT_GRAPH_REFERENCES_CAPABILITY,
],
}
+179
View File
@@ -0,0 +1,179 @@
"""Observe completed reads on the ordered display stream, outside agent execution."""
from __future__ import annotations
import asyncio
import re
from collections.abc import Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, cast
from loguru import logger
from nanobot.context_graph import ContextGraph, ContextNode, graph_from_sources
from nanobot.context_sources import PromptSource, SourceReceipt, parse_source_receipt
from nanobot.file_references import source_receipt
from nanobot.session.display_history import (
HISTORY_GENERATION_METADATA_KEY,
HistoryKind,
HistoryReader,
)
from nanobot.session.history_graph import decode_graph
from nanobot.session.manager import SessionManager
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
from nanobot.webui.session_identity import webui_session_key
def merge_graph(target: ContextGraph, incoming: ContextGraph, *, accumulate: bool = False) -> ContextGraph:
nodes: dict[str, ContextNode] = {node["path"]: node.copy() for node in target["nodes"]}
for node in incoming["nodes"]:
previous = nodes.get(node["path"])
if previous is None:
nodes[node["path"]] = node.copy()
elif node["state"] == "loaded":
previous["name"] = node["name"]
previous["state"] = "loaded"
previous["tokens"] = (previous["tokens"] + node["tokens"] if accumulate
else max(previous["tokens"], node["tokens"]))
edges = {(edge["source"], edge["target"]): edge for edge in target["edges"]}
edges.update({(edge["source"], edge["target"]): edge for edge in incoming["edges"]})
return {"nodes": list(nodes.values()), "edges": list(edges.values())}
def read_source(event: Mapping[str, Any]) -> SourceReceipt | None:
"""Use only the returned numbered text, never reread a source or link target."""
if event.get("name") != "read_file" or event.get("phase") != "end":
return None
arguments, result = event.get("arguments"), event.get("result")
if not isinstance(arguments, dict) or not isinstance(result, str):
return None
path = cast(dict[str, object], arguments).get("path")
if not isinstance(path, str) or not path:
return None
file = Path(path).expanduser()
if not file.is_absolute():
directory = event.get("working_directory")
if not isinstance(directory, str) or not Path(directory).is_absolute():
return None
file = Path(directory) / file
# ReadFileTool uses numbered lines even for a clipped first line. Its notices
# and unchanged-file response have no such prefix and must not count twice.
lines: list[str] = []
for line in result.splitlines():
match = re.match(r"^\d+\| ?(.*)$", line)
if match is None:
break
lines.append(match.group(1))
if not lines:
return None
return source_receipt(file, "\n".join(lines))
@dataclass
class _State:
graph: ContextGraph = field(default_factory=lambda: {"nodes": [], "edges": []})
calls: set[tuple[str | None, str]] = field(default_factory=set)
def apply(self, event: Mapping[str, Any], turn_id: str | None = None) -> None:
call_id = event.get("call_id")
source = parse_source_receipt(event.get("context_source"))
if not isinstance(call_id, str) or (turn_id, call_id) in self.calls or source is None:
return
self.graph = merge_graph(self.graph, graph_from_sources([source]), accumulate=True)
self.calls.add((turn_id, call_id))
def _restore(history: HistoryReader, generation: str | None) -> _State:
state = _State()
revision = history.revision
if revision is None or generation != revision[0]:
return state
pending: list[tuple[Mapping[str, Any], str | None]] = []
for turn in history.turns(reverse=True):
for _, fact in reversed(history.read_entries(turn.ordinal)):
boundary = fact.kind is HistoryKind.COMPACTION and fact.content.get("phase") == "succeeded"
graph = decode_graph(fact.content.get("context_graph")) if fact.kind is HistoryKind.MODEL_REQUEST else None
if boundary or graph is not None:
if graph is not None:
state.graph = graph
for event, turn_id in reversed(pending):
state.apply(event, turn_id)
return state
events = fact.content.get("tool_events")
if not isinstance(events, list):
continue
for event in reversed(cast(list[object], events)):
if isinstance(event, dict) and "context_source" in event:
pending.append((cast(dict[str, Any], event), fact.turn_id))
for event, turn_id in reversed(pending):
state.apply(event, turn_id)
return state
class ContextGraphObserver:
"""Display delivery serializes each chat; other chats have independent state."""
def __init__(self, sessions: SessionManager | None) -> None:
self._sessions = sessions
self._states: dict[tuple[str, str | None], _State] = {}
def discard(self, chat_id: str) -> None:
for key in tuple(self._states):
if key[0] == chat_id:
del self._states[key]
async def _state(self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool) -> _State:
raw_generation = metadata.get(HISTORY_GENERATION_METADATA_KEY)
generation = raw_generation if isinstance(raw_generation, str) else None
key = (chat_id, generation)
if key not in self._states:
self.discard(chat_id)
state = await self._sessions.state.project_history(
webui_session_key(chat_id), lambda history: _restore(history, generation),
) if persistent and self._sessions is not None else _State()
self._states[key] = state
return self._states[key]
async def observe_tools(
self, chat_id: str, events: list[dict[str, Any]], metadata: Mapping[str, Any], *, persistent: bool,
) -> None:
for event in events:
if event.get("name") != "read_file" or event.get("phase") != "end":
continue
try:
source = await asyncio.to_thread(read_source, event)
if source is not None:
state = await self._state(chat_id, metadata, persistent=persistent)
event["context_source"] = source
turn_id = metadata.get(WEBUI_TURN_METADATA_KEY)
state.apply(event, turn_id if isinstance(turn_id, str) else None)
except Exception:
# A presentation parser failure must not lose the tool result.
logger.exception("Unable to observe file read for context graph")
async def observe_prompt(
self, chat_id: str, sources: tuple[PromptSource, ...], metadata: Mapping[str, Any], *, persistent: bool,
) -> None:
if not sources:
return
def project() -> ContextGraph:
receipts = [source_receipt(source.path, source.content, loaded=source.loaded) for source in sources]
return graph_from_sources(receipts)
try:
graph = await asyncio.to_thread(project)
state = await self._state(chat_id, metadata, persistent=persistent)
state.graph = merge_graph(state.graph, graph)
except Exception:
logger.exception("Unable to observe prompt sources for context graph")
async def snapshot(
self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool,
) -> ContextGraph:
state = await self._state(chat_id, metadata, persistent=persistent)
return state.graph
async def reset(self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool) -> None:
state = await self._state(chat_id, metadata, persistent=persistent)
state.graph = {"nodes": [], "edges": []}
state.calls.clear()
+32
View File
@@ -0,0 +1,32 @@
"""Turn-scoped prompt observation installed by WebUI runtime composition."""
from __future__ import annotations
from nanobot.agent.hook import AgentHook, AgentRunHookContext, AgentTurnHookContext
from nanobot.context_sources import PromptSourcesEvent, capture_sources
from nanobot.events import EventSink
class ContextSourceHook(AgentHook):
def __init__(self, events: EventSink) -> None:
super().__init__()
self._events = events
self._capture = capture_sources()
self._sources = self._capture.__enter__()
def has_run_hooks(self) -> bool:
# Cleanup owns no transcript; avoid copying all messages for this observer.
return False
async def before_model_request(self) -> None:
sources = tuple(self._sources)
self._sources.clear()
if sources:
await self._events.emit(PromptSourcesEvent(sources))
async def on_finally(self, context: AgentRunHookContext) -> None:
self._sources.clear()
self._capture.__exit__(None, None, None)
def create_context_source_hook(context: AgentTurnHookContext) -> AgentHook | None:
return ContextSourceHook(context.events) if context.events.accepts(PromptSourcesEvent) else None
+5 -4
View File
@@ -5,6 +5,7 @@ from typing import Any
from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.session.history_graph import expand_graph_fields
from nanobot.webui.session_identity import webui_chat_id
_EVENTS = {
@@ -31,7 +32,7 @@ _CONTENT_FIELDS = frozenset({
"merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state",
"outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message",
"transcript_incomplete", "stream_id", "compaction_id", "phase", "reason", "render_as",
"request_id", "run_id", "sequence",
"request_usage", "request_id", "run_id", "sequence", "context_graph", "context_snapshot",
})
@@ -63,14 +64,14 @@ def fact_from_record(record: Mapping[str, Any]) -> HistoryFact:
return fact
def record_from_fact(fact: HistoryFact, key: str) -> dict[str, Any]:
def record_from_fact(fact: HistoryFact, key: str, *, expand_graphs: bool = True) -> dict[str, Any]:
if fact.kind in _MESSAGE_KINDS.values():
event = "message"
message_kind = next(name for name, kind in _MESSAGE_KINDS.items() if kind is fact.kind)
else:
event = next(name for name, kind in _EVENTS.items() if kind is fact.kind)
message_kind = None
record = {"event": event, "chat_id": webui_chat_id(key), **fact.content,
record = {"event": event, "chat_id": webui_chat_id(key), **(expand_graph_fields(fact.content) if expand_graphs else fact.content),
"created_at_ms": fact.created_at_ms}
if message_kind:
record["kind"] = message_kind
@@ -86,6 +87,6 @@ def record_from_fact(fact: HistoryFact, key: str) -> dict[str, Any]:
def turn_records(
history: HistoryReader, ordinal: int, *, max_records: int | None = None, max_bytes: int | None = None,
) -> list[dict[str, Any]]:
return [{**record_from_fact(fact, history.key),
return [{**record_from_fact(fact, history.key, expand_graphs=False),
"_webui_replay_identity": f"turn:{ordinal}:record:{position}"}
for position, fact in history.read_entries(ordinal, max_records=max_records, max_bytes=max_bytes)]
+54 -9
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import asyncio
import json
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
@@ -24,6 +25,8 @@ from nanobot.bus.outbound_events import (
)
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import SubagentTaskChanged
from nanobot.context_graph import ContextGraph
from nanobot.context_sources import PromptSourcesEvent
from nanobot.events import ModelRequestEvent
from nanobot.pairing.events import PairingChanged
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
@@ -32,6 +35,7 @@ from nanobot.session.webui_turns import (
mark_websocket_turn_transcript_persistence_failed,
websocket_turn_transcript_persistence_failed,
)
from nanobot.webui.context_observer import ContextGraphObserver
from nanobot.webui.media_gateway import WebUIMediaGateway
from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
@@ -44,6 +48,7 @@ from nanobot.webui.outbound_wire import (
GoalStateWirePayload,
GoalStatusWirePayload,
MessageWirePayload,
NotificationProjection,
RuntimeModelWirePayload,
SessionUpdatedWirePayload,
StreamWirePayload,
@@ -73,6 +78,12 @@ WebUIAudience: TypeAlias = ChatAudience | Literal["all_connections", "authentica
_ACTIVITY_BATCH_BYTES = 128 * 1024
async def _encode_payload(payload: Mapping[str, object]) -> str:
if "context_graph" in payload or "context_snapshot" in payload:
return await asyncio.to_thread(json.dumps, payload, ensure_ascii=False)
return json.dumps(payload, ensure_ascii=False)
class WebUIOutboundTransport(Protocol):
"""Snapshot recipients and enqueue already projected public JSON frames."""
@@ -100,17 +111,39 @@ class WebUIOutboundDelivery:
self._transcripts = transcripts
self._temporary_chats = temporary_chats
self._session_projection = session_projection
self._context_graph = ContextGraphObserver(transcripts.sessions)
self._stream_text_buffers: dict[tuple[str, str], list[str]] = {}
self._reasoning_text_buffers: dict[tuple[str, str], list[str]] = {}
async def _project_notification(self, msg: OutboundMessage) -> NotificationProjection | None:
event = msg.event
if not isinstance(event, ModelRequestEvent | ContextCompactionEvent):
return project_notification(msg.chat_id, event, msg.metadata)
persistent = self._temporary_chats.should_persist_transcript(msg.chat_id)
if isinstance(event, ModelRequestEvent):
graph: ContextGraph = {"nodes": [], "edges": []}
try:
graph = await self._context_graph.snapshot(msg.chat_id, msg.metadata, persistent=persistent)
except Exception:
logger.exception("Unable to restore context graph")
return project_notification(msg.chat_id, event, msg.metadata, context_graph=graph)
if event.phase == "succeeded":
try:
await self._context_graph.reset(msg.chat_id, msg.metadata, persistent=persistent)
except Exception:
logger.exception("Unable to reset context graph")
return project_notification(msg.chat_id, event, msg.metadata)
def bind_pairing(self, bus: MessageBus, *, channel: str) -> Callable[[], None]:
async def queue_changed(event: PairingChanged) -> None:
await bus.publish_event(event, channel=channel, chat_id="*")
return bus.subscribe(queue_changed, PairingChanged)
def discard(self, chat_id: str) -> None:
def discard(self, chat_id: str, *, complete: bool = False) -> None:
"""Forget unclosed streams when a turn ends or its chat is discarded."""
if not complete or self._temporary_chats.should_persist_transcript(chat_id):
self._context_graph.discard(chat_id)
for buffers in (self._stream_text_buffers, self._reasoning_text_buffers):
for key in tuple(buffers):
if key[0] == chat_id:
@@ -134,7 +167,9 @@ class WebUIOutboundDelivery:
*,
label: str,
) -> None:
raw = json.dumps(payload, ensure_ascii=False)
if not recipients:
return
raw = await _encode_payload(payload)
for connection in recipients:
await self._transport.webui_send_raw(connection, raw, label=label)
@@ -182,10 +217,10 @@ class WebUIOutboundDelivery:
for msg in messages:
progress = msg.event if isinstance(msg.event, ProgressEvent) else None
if progress is not None:
body = self._message_payload(msg, progress)
body = await self._message_payload(msg, progress)
persistent, label = True, " "
else:
notification = project_notification(msg.chat_id, msg.event, msg.metadata)
notification = await self._project_notification(msg)
assert notification is not None
body = dict(notification.payload)
persistent = notification.persistence == "turn_activity"
@@ -195,7 +230,7 @@ class WebUIOutboundDelivery:
msg.chat_id, body, metadata=msg.metadata, phase="activity", include_source=progress is not None,
)
try:
raw = json.dumps(body, ensure_ascii=False)
raw = await _encode_payload(body)
size = len(raw.encode("utf-8"))
except (TypeError, ValueError, RecursionError) as exc:
logger.warning("WebUI activity encoding failed for {}: {}", msg.chat_id, exc)
@@ -212,6 +247,12 @@ class WebUIOutboundDelivery:
async def send(self, msg: OutboundMessage) -> None:
event = msg.event
if isinstance(event, PromptSourcesEvent):
await self._context_graph.observe_prompt(
msg.chat_id, event.sources, msg.metadata,
persistent=self._temporary_chats.should_persist_transcript(msg.chat_id),
)
return
if isinstance(event, PairingChanged):
await self._fanout(
self._transport.webui_recipients("authenticated_webui"),
@@ -248,7 +289,7 @@ class WebUIOutboundDelivery:
body["provenance"] = event.provenance
await self._fanout(recipients, body, label=" user_message ")
return
notification = project_notification(msg.chat_id, event, msg.metadata)
notification = await self._project_notification(msg)
if notification is not None:
if recipients or notification.deliver_offline:
await self._send_payload(
@@ -373,7 +414,7 @@ class WebUIOutboundDelivery:
chat_id, persisted=persisted, metadata=metadata, phase=phase,
)
def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]:
async def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]:
text = msg.content
user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True
payload: MessageWirePayload = {
@@ -401,6 +442,10 @@ class WebUIOutboundDelivery:
payload["latency_ms"] = int(latency)
if progress and progress.tool_events:
payload["tool_events"] = project_tool_events(progress.tool_events)
await self._context_graph.observe_tools(
msg.chat_id, payload["tool_events"], msg.metadata,
persistent=self._temporary_chats.should_persist_transcript(msg.chat_id),
)
agent_ui = msg.metadata.get(OUTBOUND_META_AGENT_UI)
if agent_ui is not None:
payload["agent_ui"] = agent_ui
@@ -410,7 +455,7 @@ class WebUIOutboundDelivery:
async def _send_message(self, msg: OutboundMessage, progress: ProgressEvent | None) -> None:
recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id))
body = self._message_payload(msg, progress)
body = await self._message_payload(msg, progress)
await self._persist_turn_transcript_event(
msg.chat_id, body, metadata=msg.metadata,
phase="activity" if progress else "answer", include_source=True,
@@ -528,7 +573,7 @@ class WebUIOutboundDelivery:
if persisted:
# A durable incomplete marker allows HTTP recovery after restart.
clear_websocket_turn_if_current(chat_id, turn_owner)
self.discard(chat_id)
self.discard(chat_id, complete=True)
await self._fanout(recipients, body, label=f" {body['event']} ")
async def _send_goal_state(self, chat_id: str, blob: dict[str, Any]) -> None:
+8
View File
@@ -11,6 +11,7 @@ from nanobot.bus.outbound_events import (
RetryStatusEvent,
TurnEndEvent,
)
from nanobot.context_graph import ContextGraph, ContextSnapshot
from nanobot.events import AgentEvent, CompactionReason, ModelRequestEvent
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
@@ -97,6 +98,8 @@ class TurnEndWirePayload(_ChatWirePayload):
class ModelRequestWirePayload(_ChatWirePayload):
request_usage: dict[str, int] | None
context_graph: NotRequired[ContextGraph]
event: Literal["model_request"]
request_id: str
run_id: str
@@ -108,6 +111,7 @@ class ModelRequestWirePayload(_ChatWirePayload):
class ContextCompactionWirePayload(_ChatWirePayload):
context_snapshot: NotRequired[ContextSnapshot]
event: Literal["context_compaction"]
compaction_id: str
phase: Literal["started", "succeeded", "failed", "cancelled"]
@@ -253,6 +257,7 @@ class NotificationProjection:
def project_notification(
chat_id: str, event: AgentEvent | None, metadata: Mapping[str, object] | None = None,
*, context_graph: ContextGraph | None = None,
) -> NotificationProjection | None:
"""Keep notification serialization and persistence decisions at one boundary."""
if isinstance(event, ModelRequestEvent):
@@ -260,7 +265,10 @@ def project_notification(
"event": "model_request", "chat_id": chat_id,
"request_id": event.request_id, "run_id": event.run_id,
"sequence": event.sequence, "phase": event.phase,
"request_usage": event.request_usage.to_turn_dict() if event.request_usage is not None else None,
}
if context_graph is not None:
payload["context_graph"] = context_graph
if event.usage is not None:
payload["usage"] = event.usage.to_turn_dict()
payload["round_usages"] = [usage.to_turn_dict() for usage in event.round_usages[-8:]]
+20 -6
View File
@@ -28,6 +28,12 @@ from nanobot.session.display_history import (
HistoryFact,
HistoryReader,
)
from nanobot.session.history_graph import (
decode_graph,
decode_snapshot,
graph_decoding,
graph_size_adjustment,
)
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
from nanobot.session.sqlite_store import SessionConflictError
@@ -233,7 +239,7 @@ def _record_json_line(record: dict[str, Any]) -> str:
def _records_bytes(records: list[dict[str, Any]]) -> int:
total = 0
for record in records:
total += len(_record_json_line(record).encode("utf-8")) + 1
total += len(_record_json_line(record).encode("utf-8")) + graph_size_adjustment(record) + 1
return total
@@ -581,9 +587,6 @@ class WebUITranscriptRecorder:
for event in events:
try:
fact = fact_from_record(_record_for_append(event))
if len(events) > 1:
# An invalid member must not roll back otherwise valid activity.
fact.encode()
facts.append(fact)
except (ValueError, TypeError) as exc:
self._log.warning("history append failed for {}: {}", chat_id, exc)
@@ -591,8 +594,12 @@ class WebUITranscriptRecorder:
if not facts:
return False
try:
await self.sessions.state.append_history(webui_session_key(chat_id), facts,
expected_generation=generation)
errors = await self.sessions.state.append_history(webui_session_key(chat_id), facts,
expected_generation=generation,
skip_invalid=len(events) > 1)
for error in errors:
self._log.warning("history append failed for {}: {}", chat_id, error)
valid = valid and not errors
except (OSError, ValueError, TypeError, sqlite3.Error, SessionConflictError, SessionOperationQueueFullError) as exc:
self._log.warning("history append failed for {}: {}", chat_id, exc)
return False
@@ -1510,6 +1517,8 @@ def _client_projection_event(
"compaction_id": compaction_id,
"phase": phase,
}
if (snapshot := decode_snapshot(record.get("context_snapshot"))) is not None:
projected["context_snapshot"] = snapshot
reason = record.get("reason")
if isinstance(reason, str) and reason in {"idle", "context_pressure", "manual", "provider_native"}:
projected["reason"] = reason
@@ -1528,6 +1537,10 @@ def _client_projection_event(
):
return None
projected.update(request_id=request_id, run_id=run_id, sequence=sequence, phase=phase)
if "request_usage" in record:
projected["request_usage"] = _sanitize_turn_usage(record["request_usage"]) or None
if (graph := decode_graph(record.get("context_graph"))) is not None:
projected["context_graph"] = graph
latency_ms = record.get("latency_ms")
if isinstance(latency_ms, int | float) and latency_ms >= 0:
projected["latency_ms"] = int(latency_ms)
@@ -1757,6 +1770,7 @@ def build_session_thread_response(
"active_turn_id": turn_id if active else None}
@graph_decoding()
def build_webui_thread_response(
session_key: str,
*,
+71 -13
View File
@@ -18,7 +18,7 @@ import time
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any, Protocol, cast
from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast
from urllib.parse import quote, unquote, urlsplit, urlunsplit
from loguru import logger
@@ -29,6 +29,7 @@ from websockets.http11 import Response
from nanobot.agent.subagent import SubagentControlError
from nanobot.agent.subagent_status import SubagentSessionError
from nanobot.command.application import builtin_command_palette
from nanobot.context_graph import ContextGraph
from nanobot.cron.binding import CronBindingError, binding_revision
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob, CronSchedule
@@ -348,8 +349,58 @@ def _resolve_bootstrap_model_name(
return _default_model_name_from_config(config_path) or ""
class _HistoryProjection(Protocol):
def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: ...
_ProjectionResult = TypeVar("_ProjectionResult", covariant=True)
class _HistoryProjection(Protocol[_ProjectionResult]):
def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> _ProjectionResult: ...
@dataclass
class _PreparedThreadResponse:
data: dict[str, Any]
headers: list[tuple[str, str]]
def _encode_thread_response(data: dict[str, Any], *, graph_references: bool, **kwargs: Any) -> Response:
if graph_references:
graphs: dict[str, object] = {}
references: dict[int, tuple[str, ContextGraph]] = {}
nodes: list[object] = []
edges: list[object] = []
node_ids: dict[int, int] = {}
edge_ids: dict[int, int] = {}
def index(value: object, values: list[object], ids: dict[int, int]) -> int:
identity = id(value)
if identity not in ids:
ids[identity] = len(values)
values.append(value)
return ids[identity]
def reference(graph: ContextGraph) -> str:
identity = id(graph)
if identity not in references:
key = str(len(graphs))
references[identity] = (key, graph)
graphs[key] = {
"nodes": [index(node, nodes, node_ids) for node in graph["nodes"]],
"edges": [index(edge, edges, edge_ids) for edge in graph["edges"]],
}
return references[identity][0]
for event in data.get("events", []):
if "context_graph" in event:
event["context_graph_ref"] = reference(event.pop("context_graph"))
snapshot = event.get("context_snapshot")
if isinstance(snapshot, dict) and "graph" in snapshot:
snapshot = cast(dict[str, Any], snapshot)
event["context_snapshot"] = {**snapshot, "graph_ref": reference(snapshot["graph"])}
event["context_snapshot"].pop("graph")
data["context_graphs"] = graphs
data["context_graph_nodes"] = nodes
data["context_graph_edges"] = edges
return _http_json_response(data, **kwargs)
class GatewayHTTPHandler:
@@ -1048,8 +1099,8 @@ class GatewayHTTPHandler:
return self.session_manager.read_session_version(key) if self.session_manager is not None else None
async def _project_session_history(
self, request: WsRequest, key: str, project: _HistoryProjection,
) -> Response:
self, request: WsRequest, key: str, project: _HistoryProjection[_ProjectionResult],
) -> _ProjectionResult | Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
decoded = _decode_api_key(key)
@@ -1111,11 +1162,20 @@ class GatewayHTTPHandler:
timer = loop.call_later(0.05, sample_event_loop_lag)
started = time.perf_counter()
def project(request: WsRequest, key: str, *, history: HistoryReader) -> Response:
def project(request: WsRequest, key: str, *, history: HistoryReader) -> Response | _PreparedThreadResponse:
return self._handle_webui_thread_get(request, key, history=history, diagnostics=diagnostics)
try:
response = await self._project_session_history(request, key, project)
prepared = await self._project_session_history(request, key, project)
if isinstance(prepared, _PreparedThreadResponse):
response = await asyncio.to_thread(
_encode_thread_response, prepared.data,
graph_references=_query_first(_parse_query(request.path), "context_graph_encoding") == "references-v1",
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),
extra_headers=prepared.headers, metrics=diagnostics.response,
)
else:
response = prepared
finally:
active = False
timer.cancel()
@@ -1170,7 +1230,7 @@ class GatewayHTTPHandler:
*,
history: HistoryReader,
diagnostics: _WebUIThreadDiagnostics | None = None,
) -> Response:
) -> Response | _PreparedThreadResponse:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
decoded_key = _decode_api_key(key)
@@ -1215,6 +1275,7 @@ class GatewayHTTPHandler:
include_model_requests = _query_first(query, "include_model_requests") == "1"
revision_variant = {
"include_model_requests": include_model_requests,
"context_graph_encoding": _query_first(query, "context_graph_encoding"),
"active_turn_id": active_turn_id,
"active_turn_started_at": active_turn_started_at,
"active_turn_transcript_persistence_failed": (
@@ -1267,11 +1328,8 @@ class GatewayHTTPHandler:
if final_revision is not None and final_revision == initial_revision:
response_headers.append(("ETag", _quoted_etag(final_revision)))
data["revision"] = final_revision
return _http_json_response(
data,
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),
extra_headers=response_headers,
metrics=diagnostics.response if diagnostics is not None else None,
return _PreparedThreadResponse(
data=data, headers=response_headers,
)
def _handle_webui_trace_detail_get(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: