fix(webui): retain system context graph after compaction (#6608)
This commit is contained in:
1 parent
d789e1bfc7
commit
4212ad726d
25 files changed
+748
-102
No files matched your search
@@ -10,7 +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.context_sources import record_source, system_source_scope
|
||||
from nanobot.runtime_context import (
|
||||
RUNTIME_CONTEXT_MESSAGE_META,
|
||||
RuntimeContextBlock,
|
||||
@@ -275,16 +275,15 @@ class ContextBuilder:
|
||||
"""Build a model transcript while preserving the fresh-turn boundary."""
|
||||
root = workspace or self.workspace
|
||||
with self.skills.snapshot():
|
||||
with system_source_scope():
|
||||
system_prompt = self.build_system_prompt(
|
||||
channel=channel,
|
||||
session_summary=transcript.session_summary,
|
||||
workspace=root,
|
||||
include_memory=include_memory,
|
||||
)
|
||||
messages: list[dict[str, Any]] = [
|
||||
{
|
||||
"role": "system",
|
||||
"content": self.build_system_prompt(
|
||||
channel=channel,
|
||||
session_summary=transcript.session_summary,
|
||||
workspace=root,
|
||||
include_memory=include_memory,
|
||||
),
|
||||
},
|
||||
{"role": "system", "content": system_prompt},
|
||||
*transcript.history,
|
||||
]
|
||||
if transcript.current_message is None:
|
||||
|
||||
@@ -21,6 +21,7 @@ from uuid import uuid4
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.context_sources import drain_system_sources
|
||||
from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink
|
||||
from nanobot.providers.base import (
|
||||
CONTEXT_SAFETY_BUFFER,
|
||||
@@ -706,13 +707,18 @@ class ContextGovernor:
|
||||
),
|
||||
)
|
||||
raise
|
||||
await state.events.emit(
|
||||
ContextCompactionEvent(
|
||||
compaction_id=compaction_id,
|
||||
phase="succeeded",
|
||||
reason="context_pressure",
|
||||
),
|
||||
)
|
||||
async def publish_success() -> None:
|
||||
if (sources := drain_system_sources()) is not None:
|
||||
await state.events.emit(sources)
|
||||
await state.events.emit(
|
||||
ContextCompactionEvent(
|
||||
compaction_id=compaction_id,
|
||||
phase="succeeded",
|
||||
reason="context_pressure",
|
||||
),
|
||||
)
|
||||
|
||||
await shield_and_drain(publish_success())
|
||||
return prepared
|
||||
|
||||
async def prepare_request(
|
||||
|
||||
@@ -38,6 +38,7 @@ from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import RuntimeEventContext, SubagentTaskChanged
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import AgentDefaults, ToolsConfig
|
||||
from nanobot.context_sources import without_source_capture
|
||||
from nanobot.events import AgentEvent, EventSink
|
||||
from nanobot.llm_usage.context import LLMUsageSource, current_llm_usage_source
|
||||
from nanobot.providers.base import LLMProvider, ToolCallRequest
|
||||
@@ -597,7 +598,8 @@ class SubagentManager:
|
||||
)
|
||||
self._tasks[task_id] = record
|
||||
self._publish_status(status)
|
||||
execution = asyncio.create_task(self._run_subagent(record))
|
||||
with without_source_capture():
|
||||
execution = asyncio.create_task(self._run_subagent(record))
|
||||
self._running_tasks[task_id] = execution
|
||||
execution.add_done_callback(partial(self._task_done, record))
|
||||
logger.info("Started subagent [{}]: {}", task_id,
|
||||
|
||||
@@ -826,3 +826,277 @@ async def test_context_observer_orders_reads_requests_and_compaction(history, tm
|
||||
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": []}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("mode", ["local", "native", "response"])
|
||||
async def test_compaction_keeps_system_sources_in_new_graph(history, tmp_path, mode) -> None:
|
||||
from functools import partial
|
||||
|
||||
from nanobot.agent.context import ContextBuilder, TranscriptInput
|
||||
from nanobot.agent.runner import AgentRunner, AgentRunSpec
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.events import EventSink, ModelRequestEvent
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse
|
||||
from nanobot.providers.compaction import NativeCompaction, ProviderCompactionEvents
|
||||
from nanobot.providers.openai_responses.state import (
|
||||
attach_responses_state,
|
||||
build_responses_compaction_state,
|
||||
)
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
from nanobot.webui.context_observer import ContextGraphObserver
|
||||
from nanobot.webui.context_source_hook import ContextSourceHook
|
||||
|
||||
workspace = tmp_path / "prompt-workspace"
|
||||
workspace.mkdir()
|
||||
soul = workspace / "SOUL.md"
|
||||
soul.write_text("Be precise. [Old](old.md)" if mode == "local" else "Be precise. [Guide](guide.md)", encoding="utf-8")
|
||||
skill = workspace / "skills" / "review" / "SKILL.md"
|
||||
if mode == "local":
|
||||
skill.parent.mkdir(parents=True)
|
||||
skill.write_text("---\nname: review\ndescription: Review changes.\n---\n\n# Review workflow", encoding="utf-8")
|
||||
channel = _channel(history.sessions)
|
||||
chat = "compacted-graph"
|
||||
metadata = await history.metadata(chat, {"webui_turn_id": "turn"})
|
||||
connection = _RecordingConnection()
|
||||
channel._attach(cast(Any, connection), chat)
|
||||
|
||||
async def send(event):
|
||||
await channel.send(OutboundMessage("websocket", chat, "", metadata=metadata, event=event))
|
||||
|
||||
def read_event(name, call_id):
|
||||
return ProgressEvent(tool_events=[{
|
||||
"name": "read_file", "phase": "end", "call_id": call_id,
|
||||
"arguments": {"path": str(workspace / name)}, "result": "1| content",
|
||||
}])
|
||||
|
||||
async def provider_call(**kwargs):
|
||||
assert "Be precise" in kwargs["messages"][0]["content"]
|
||||
response = LLMResponse(content="done")
|
||||
if mode == "native":
|
||||
compaction = ProviderCompactionEvents(kwargs["provider_context"].events)
|
||||
event_id = await compaction.start("provider_native")
|
||||
state = build_responses_compaction_state(provider="codex", model="test", output_items=[
|
||||
{"type": "compaction", "encrypted_content": "synthetic"},
|
||||
])
|
||||
assert state is not None
|
||||
await compaction.accept(NativeCompaction(state, state, event_id), commit=None)
|
||||
response.provider_compaction_applied = True
|
||||
response.provider_compaction_state = state
|
||||
response.provider_compaction_scope = "prior_context"
|
||||
response.provider_compaction_event_id = event_id
|
||||
async with asyncio.timeout(2):
|
||||
while True:
|
||||
frame = json.loads(await connection.sent.get())
|
||||
if frame.get("event") == "context_compaction" and frame.get("phase") == "succeeded":
|
||||
break
|
||||
graph = frame["context_graph"]
|
||||
assert {"SOUL.md", "guide.md"} <= {node["name"] for node in graph["nodes"]}
|
||||
assert "before.py" not in {node["name"] for node in graph["nodes"]}
|
||||
replay = history.build(f"websocket:{chat}", include_model_requests=True)
|
||||
boundary = next(row for row in replay["events"] if row.get("event") == "context_compaction")
|
||||
assert boundary["context_graph"] == graph
|
||||
observer = ContextGraphObserver(history.sessions)
|
||||
assert await observer.snapshot(chat, metadata, persistent=True) == graph
|
||||
elif mode == "local":
|
||||
assert "Summary of earlier work" in kwargs["messages"][0]["content"]
|
||||
else:
|
||||
attach_responses_state(response, provider="codex", model="test", input_items=[], output_items=[
|
||||
{"type": "compaction", "encrypted_content": "synthetic"},
|
||||
])
|
||||
return response
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = provider_call
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
events = EventSink(send)
|
||||
|
||||
async def consolidate_history(_messages, _summary):
|
||||
soul.write_text("Be precise. [Guide](guide.md)", encoding="utf-8")
|
||||
return "Summary of earlier work"
|
||||
|
||||
try:
|
||||
await send(read_event("before.py", "before"))
|
||||
result = await AgentRunner().run(AgentRunSpec(
|
||||
initial_messages=None, tools=tools,
|
||||
runtime=LLMRuntime(provider=provider, model="test", generation=GenerationSettings(max_tokens=1000),
|
||||
context_window_tokens=8192 if mode == "local" else 128000),
|
||||
max_iterations=2, max_tool_result_chars=10000, workspace=workspace,
|
||||
transcript_input=TranscriptInput(
|
||||
history=[{"role": "user", "content": "previous work " * 12000}] if mode == "local" else [],
|
||||
current_message="hello $review" if mode == "local" else "hello",
|
||||
),
|
||||
transcript_builder=partial(ContextBuilder(workspace).build_transcript, channel="websocket"),
|
||||
consolidate_history=consolidate_history, hook=ContextSourceHook(events), events=events,
|
||||
))
|
||||
assert result.final_content == "done"
|
||||
records = history.read(f"websocket:{chat}")
|
||||
boundary = next(row for row in records if row.get("event") == "context_compaction" and row.get("phase") == "succeeded")
|
||||
if mode != "local":
|
||||
started = next(row for row in records if row.get("event") == "model_request" and row.get("phase") == "started")
|
||||
assert "before.py" in {node["name"] for node in started["context_graph"]["nodes"]}
|
||||
boundary_names = {node["name"] for node in boundary["context_graph"]["nodes"]}
|
||||
assert {"SOUL.md", "guide.md"} <= boundary_names
|
||||
assert "before.py" not in boundary_names
|
||||
assert "old.md" not in boundary_names
|
||||
completed = next(row for row in records if row.get("event") == "model_request" and row.get("phase") == "completed")
|
||||
names = {node["name"] for node in completed["context_graph"]["nodes"]}
|
||||
assert {"SOUL.md", "guide.md"} <= names
|
||||
if mode == "local":
|
||||
boundary_skill = next(node for node in boundary["context_graph"]["nodes"] if node["path"] == str(skill))
|
||||
request_skill = next(node for node in completed["context_graph"]["nodes"] if node["path"] == str(skill))
|
||||
assert boundary_skill["state"] == "discovered"
|
||||
assert request_skill["state"] == "loaded"
|
||||
assert {"source": str(soul), "target": str(workspace / "guide.md")} in completed["context_graph"]["edges"]
|
||||
if mode == "response":
|
||||
assert records.index(completed) < records.index(boundary)
|
||||
else:
|
||||
assert records.index(boundary) < records.index(completed)
|
||||
assert "before.py" not in names
|
||||
assert "old.md" not in names
|
||||
|
||||
await send(read_event("after.py", "after"))
|
||||
request = ModelRequestEvent("next", "run-next", 1, "started")
|
||||
restored_channel = _channel(history.sessions)
|
||||
await restored_channel.send(OutboundMessage("websocket", chat, "", metadata=metadata, event=request))
|
||||
records = history.read(f"websocket:{chat}")
|
||||
latest = next(row for row in reversed(records) if row.get("event") == "model_request")
|
||||
names = {node["name"] for node in latest["context_graph"]["nodes"]}
|
||||
assert {"SOUL.md", "guide.md", "after.py"} <= names
|
||||
assert "before.py" not in names
|
||||
finally:
|
||||
await channel._cleanup_connection(cast(Any, connection))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_local_compaction_publishes_rebuilt_system_graph_before_next_request(history, tmp_path, monkeypatch) -> None:
|
||||
from functools import partial
|
||||
|
||||
from nanobot.agent.context import ContextBuilder, TranscriptInput
|
||||
from nanobot.agent.runner import AgentRunner, AgentRunSpec
|
||||
from nanobot.events import EventSink
|
||||
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
from nanobot.webui.context_source_hook import ContextSourceHook
|
||||
|
||||
workspace = tmp_path / "prompt-workspace"
|
||||
workspace.mkdir()
|
||||
soul = workspace / "SOUL.md"
|
||||
soul.write_text("[Old](old.md)", encoding="utf-8")
|
||||
channel = _channel(history.sessions)
|
||||
chat = "rebuilt-prompt"
|
||||
metadata = await history.metadata(chat, {"webui_turn_id": "turn"})
|
||||
|
||||
async def send(event):
|
||||
await channel.send(OutboundMessage("websocket", chat, "", metadata=metadata, event=event))
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.can_resume_conversation_state.return_value = False
|
||||
provider.supports_pre_request_compaction.return_value = False
|
||||
prompts = []
|
||||
|
||||
async def provider_call(**kwargs):
|
||||
prompts.append(kwargs["messages"][0]["content"])
|
||||
if len(prompts) == 1:
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(id="edit", name="edit_file", arguments={})])
|
||||
return LLMResponse(content="done")
|
||||
|
||||
provider.chat_stream_with_retry = provider_call
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
|
||||
async def edit_file(*_args, **_kwargs):
|
||||
soul.write_text("[New](new.md)", encoding="utf-8")
|
||||
return "updated"
|
||||
|
||||
tools.execute = AsyncMock(side_effect=edit_file)
|
||||
|
||||
def estimate(_provider, _model, messages, _tools):
|
||||
has_tool_result = any(message.get("role") == "tool" and message.get("content") == "updated" for message in messages)
|
||||
has_summary = any(message.get("role") == "system" and "Summary after compaction" in message.get("content", "") for message in messages)
|
||||
return (600 if has_tool_result and not has_summary else 100, "test-counter")
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", estimate)
|
||||
events = EventSink(send)
|
||||
result = await AgentRunner().run(AgentRunSpec(
|
||||
initial_messages=None, tools=tools,
|
||||
runtime=LLMRuntime(provider=provider, model="test", generation=GenerationSettings(max_tokens=100),
|
||||
context_window_tokens=1624),
|
||||
max_iterations=2, max_tool_result_chars=10000, workspace=workspace,
|
||||
transcript_input=TranscriptInput(history=[], current_message="update the prompt"),
|
||||
transcript_builder=partial(ContextBuilder(workspace).build_transcript, channel="websocket"),
|
||||
consolidate_history=AsyncMock(return_value="Summary after compaction"),
|
||||
hook=ContextSourceHook(events), events=events,
|
||||
))
|
||||
assert result.final_content == "done"
|
||||
assert "[Old](old.md)" in prompts[0]
|
||||
assert "[New](new.md)" in prompts[1]
|
||||
records = history.read(f"websocket:{chat}")
|
||||
boundary = next(row for row in records if row.get("event") == "context_compaction" and row.get("phase") == "succeeded")
|
||||
request = next(row for row in reversed(records) if row.get("event") == "model_request" and row.get("phase") == "started")
|
||||
assert boundary["context_graph"] == request["context_graph"]
|
||||
names = {node["name"] for node in boundary["context_graph"]["nodes"]}
|
||||
assert "new.md" in names and "old.md" not in names
|
||||
replay = history.build(f"websocket:{chat}", include_model_requests=True)
|
||||
replay_boundary = next(row for row in replay["events"] if row.get("event") == "context_compaction")
|
||||
assert replay_boundary["context_graph"] == boundary["context_graph"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("batched", [False, True])
|
||||
@pytest.mark.parametrize("request_after_read", [False, True])
|
||||
async def test_next_turn_replaces_restored_system_sources_without_losing_reads(history, tmp_path, request_after_read, batched) -> None:
|
||||
from nanobot.bus.outbound_events import ProgressEvent, TurnEndEvent
|
||||
from nanobot.context_sources import PromptSource, PromptSourcesEvent
|
||||
from nanobot.events import AgentEvent, ContextCompactionEvent, ModelRequestEvent
|
||||
from nanobot.file_references import source_receipt
|
||||
|
||||
channel = _channel(history.sessions)
|
||||
chat = "restored-prompt"
|
||||
first = await history.metadata(chat, {"webui_turn_id": "first"})
|
||||
second = await history.metadata(chat, {"webui_turn_id": "second"})
|
||||
soul = tmp_path / "SOUL.md"
|
||||
old_prompt, new_prompt, read_content = "[Old](old.md)", "[New](new.md)", "[Post](post.md)"
|
||||
|
||||
async def send(event, metadata):
|
||||
await channel.send(OutboundMessage("websocket", chat, "", metadata=metadata, event=event))
|
||||
|
||||
def read(path, content, call_id):
|
||||
return ProgressEvent(tool_events=[{
|
||||
"name": "read_file", "phase": "end", "call_id": call_id,
|
||||
"arguments": {"path": str(path)}, "result": f"1| {content}",
|
||||
}])
|
||||
|
||||
async def send_events(events, metadata):
|
||||
messages = [OutboundMessage("websocket", chat, "", metadata=metadata, event=event) for event in events]
|
||||
if batched:
|
||||
await channel.send_batch(messages)
|
||||
else:
|
||||
for message in messages:
|
||||
await channel.send(message)
|
||||
|
||||
await send(PromptSourcesEvent((), (PromptSource(soul, old_prompt),)), first)
|
||||
await send_events([
|
||||
ModelRequestEvent("first", "run-first", 1, "started"),
|
||||
read(tmp_path / "before.py", "old read", "before"),
|
||||
], first)
|
||||
await send(ContextCompactionEvent("compact", "succeeded"), first)
|
||||
events: list[AgentEvent] = [read(soul, read_content, "after")]
|
||||
if request_after_read:
|
||||
events.append(ModelRequestEvent("after", "run-first", 2, "started"))
|
||||
await send_events(events, first)
|
||||
await send(TurnEndEvent(), first)
|
||||
|
||||
await send(PromptSourcesEvent((), (PromptSource(soul, new_prompt),)), second)
|
||||
await send(ModelRequestEvent("second", "run-second", 1, "started"), second)
|
||||
records = history.read(f"websocket:{chat}")
|
||||
graph = next(row["context_graph"] for row in reversed(records) if row.get("event") == "model_request")
|
||||
nodes = {node["name"]: node for node in graph["nodes"]}
|
||||
assert {"SOUL.md", "new.md", "post.md"} <= nodes.keys()
|
||||
assert "old.md" not in nodes and "before.py" not in nodes
|
||||
assert nodes["SOUL.md"]["tokens"] == (
|
||||
source_receipt(soul, new_prompt)["tokens"] + source_receipt(soul, read_content)["tokens"]
|
||||
)
|
||||
assert {"source": str(soul), "target": str(tmp_path / "new.md")} in graph["edges"]
|
||||
assert {"source": str(soul), "target": str(tmp_path / "post.md")} in graph["edges"]
|
||||
@@ -26,6 +26,33 @@ class ContextGraph(TypedDict):
|
||||
edges: list[ContextEdge]
|
||||
|
||||
|
||||
class ContextGraphParts(TypedDict):
|
||||
kind: Literal["context_graph_parts"]
|
||||
stage: ContextGraph
|
||||
system: ContextGraph
|
||||
reads: ContextGraph
|
||||
|
||||
|
||||
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 graph_from_parts(parts: ContextGraphParts) -> ContextGraph:
|
||||
return merge_graph(merge_graph(parts["stage"], parts["system"]), parts["reads"], accumulate=True)
|
||||
|
||||
|
||||
def parse_context_graph(value: object) -> ContextGraph | None:
|
||||
"""Validate persisted graph data at the transcript boundary."""
|
||||
if not isinstance(value, dict):
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
from collections.abc import Generator
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import TypedDict, cast
|
||||
|
||||
@@ -30,26 +30,79 @@ class PromptSource:
|
||||
@dataclass(frozen=True)
|
||||
class PromptSourcesEvent(AgentEvent):
|
||||
sources: tuple[PromptSource, ...]
|
||||
# None means no rebuild; an empty tuple is a rebuilt prompt with no sources.
|
||||
system_sources: tuple[PromptSource, ...] | None = None
|
||||
|
||||
|
||||
_sources: ContextVar[list[PromptSource] | None] = ContextVar("context_sources", default=None)
|
||||
@dataclass
|
||||
class SourceCapture:
|
||||
sources: list[PromptSource] = field(default_factory=list)
|
||||
system_sources: list[PromptSource] | None = None
|
||||
|
||||
def drain(self) -> PromptSourcesEvent:
|
||||
event = PromptSourcesEvent(tuple(self.sources), None if self.system_sources is None else tuple(self.system_sources))
|
||||
self.sources.clear()
|
||||
self.system_sources = None
|
||||
return event
|
||||
|
||||
def drain_system(self) -> PromptSourcesEvent | None:
|
||||
if self.system_sources is None:
|
||||
return None
|
||||
event = PromptSourcesEvent((), tuple(self.system_sources))
|
||||
self.system_sources = None
|
||||
return event
|
||||
|
||||
|
||||
_sources: ContextVar[SourceCapture | None] = ContextVar("context_sources", default=None)
|
||||
_system_source: ContextVar[bool] = ContextVar("context_system_source", default=False)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def capture_sources() -> Generator[list[PromptSource]]:
|
||||
def capture_sources() -> Generator[SourceCapture]:
|
||||
"""Observe builder reads in one run, including its prompt worker tasks."""
|
||||
sources: list[PromptSource] = []
|
||||
token = _sources.set(sources)
|
||||
capture = SourceCapture()
|
||||
token = _sources.set(capture)
|
||||
try:
|
||||
yield sources
|
||||
yield capture
|
||||
finally:
|
||||
_sources.reset(token)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def without_source_capture() -> Generator[None]:
|
||||
"""Keep independently scheduled runs from inheriting their parent's capture."""
|
||||
token = _sources.set(None)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_sources.reset(token)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def system_source_scope() -> Generator[None]:
|
||||
"""Capture a replacement snapshot of the system prompt's file sources."""
|
||||
if (capture := _sources.get()) is not None:
|
||||
# Compaction can rebuild the prompt before a request; keep the latest build.
|
||||
capture.system_sources = []
|
||||
token = _system_source.set(True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_system_source.reset(token)
|
||||
|
||||
|
||||
def drain_system_sources() -> PromptSourcesEvent | None:
|
||||
"""Take a committed prompt rebuild without consuming pending turn sources."""
|
||||
capture = _sources.get()
|
||||
return capture.drain_system() if capture is not None else None
|
||||
|
||||
|
||||
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))
|
||||
if (capture := _sources.get()) is not None:
|
||||
sources = capture.system_sources if _system_source.get() else capture.sources
|
||||
if sources 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:
|
||||
|
||||
@@ -13,8 +13,10 @@ from typing import Any, cast
|
||||
from nanobot.context_graph import (
|
||||
ContextEdge,
|
||||
ContextGraph,
|
||||
ContextGraphParts,
|
||||
ContextNode,
|
||||
ContextSnapshot,
|
||||
graph_from_parts,
|
||||
parse_context_graph,
|
||||
)
|
||||
|
||||
@@ -53,10 +55,25 @@ def encode_graph(value: object) -> object:
|
||||
return encoded if encoded is not None else value
|
||||
|
||||
|
||||
def _parts_mapping(value: object) -> dict[str, object] | None:
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
parts = cast(dict[str, object], value)
|
||||
return parts if parts.get("kind") == "context_graph_parts" else None
|
||||
|
||||
|
||||
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"])
|
||||
graph: object = result["context_graph"]
|
||||
parts = _parts_mapping(graph)
|
||||
if parts is not None:
|
||||
result["context_graph"] = {
|
||||
"kind": "context_graph_parts",
|
||||
**{key: encode_graph(parts.get(key)) for key in ("stage", "system", "reads")},
|
||||
}
|
||||
else:
|
||||
result["context_graph"] = encode_graph(graph)
|
||||
snapshot = result.get("context_snapshot")
|
||||
if isinstance(snapshot, dict) and "graph" in snapshot:
|
||||
snapshot = cast(dict[str, Any], snapshot)
|
||||
@@ -150,6 +167,15 @@ class GraphDecoder:
|
||||
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 parts(self, value: object) -> ContextGraphParts | None:
|
||||
parts = _parts_mapping(value)
|
||||
if parts is None:
|
||||
return None
|
||||
stage, system, reads = (self.graph(parts.get(key)) for key in ("stage", "system", "reads"))
|
||||
if stage is None or system is None or reads is None:
|
||||
return None
|
||||
return {"kind": "context_graph_parts", "stage": stage, "system": system, "reads": reads}
|
||||
|
||||
def graph(self, value: object) -> ContextGraph | None:
|
||||
if isinstance(value, str):
|
||||
key = value
|
||||
@@ -179,6 +205,9 @@ class GraphDecoder:
|
||||
graph = self.columns(json.loads(expanded), logical_size)
|
||||
except (ValueError, zlib.error, UnicodeDecodeError):
|
||||
return None
|
||||
elif (raw_parts := _parts_mapping(cast(object, value))) is not None:
|
||||
parts = self.parts(raw_parts)
|
||||
graph = self.inline(graph_from_parts(parts)) if parts is not None else None
|
||||
else:
|
||||
graph = self.inline(cast(object, value))
|
||||
self.graphs[key] = graph
|
||||
@@ -201,6 +230,10 @@ def decode_graph(value: object) -> ContextGraph | None:
|
||||
return (_decoder.get() or GraphDecoder()).graph(value)
|
||||
|
||||
|
||||
def decode_graph_parts(value: object) -> ContextGraphParts | None:
|
||||
return (_decoder.get() or GraphDecoder()).parts(value)
|
||||
|
||||
|
||||
def decode_snapshot(value: object) -> ContextSnapshot | None:
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
@@ -226,7 +259,9 @@ def expand_graph_fields(content: Mapping[str, Any]) -> dict[str, Any]:
|
||||
|
||||
def graph_size_adjustment(content: Mapping[str, Any]) -> int:
|
||||
"""Retain the original replay byte budget despite storage compression."""
|
||||
values = [content.get("context_graph")]
|
||||
graph: object = content.get("context_graph")
|
||||
parts = _parts_mapping(graph)
|
||||
values: list[object] = [parts.get(key) for key in ("stage", "system", "reads")] if parts is not None else [graph]
|
||||
snapshot = content.get("context_snapshot")
|
||||
if isinstance(snapshot, dict):
|
||||
values.append(cast(dict[str, object], snapshot).get("graph"))
|
||||
|
||||
@@ -11,7 +11,13 @@ from typing import Any, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.context_graph import ContextGraph, ContextNode, graph_from_sources
|
||||
from nanobot.context_graph import (
|
||||
ContextGraph,
|
||||
ContextGraphParts,
|
||||
graph_from_parts,
|
||||
graph_from_sources,
|
||||
merge_graph,
|
||||
)
|
||||
from nanobot.context_sources import PromptSource, SourceReceipt, parse_source_receipt
|
||||
from nanobot.file_references import source_receipt
|
||||
from nanobot.session.display_history import (
|
||||
@@ -19,28 +25,12 @@ from nanobot.session.display_history import (
|
||||
HistoryKind,
|
||||
HistoryReader,
|
||||
)
|
||||
from nanobot.session.history_graph import decode_graph
|
||||
from nanobot.session.history_graph import decode_graph, decode_graph_parts
|
||||
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":
|
||||
@@ -72,15 +62,27 @@ def read_source(event: Mapping[str, Any]) -> SourceReceipt | None:
|
||||
|
||||
@dataclass
|
||||
class _State:
|
||||
# Prompt sources and reads belong to the compaction stage; system sources
|
||||
# belong to the current turn's prompt and are replaced on each rebuild.
|
||||
graph: ContextGraph = field(default_factory=lambda: {"nodes": [], "edges": []})
|
||||
reads: ContextGraph = field(default_factory=lambda: {"nodes": [], "edges": []})
|
||||
system_graph: ContextGraph = field(default_factory=lambda: {"nodes": [], "edges": []})
|
||||
system_turn_id: str | None = None
|
||||
calls: set[tuple[str | None, str]] = field(default_factory=set)
|
||||
|
||||
def request_parts(self, turn_id: object) -> ContextGraphParts:
|
||||
system: ContextGraph = (
|
||||
self.system_graph if isinstance(turn_id, str) and turn_id and turn_id == self.system_turn_id
|
||||
else {"nodes": [], "edges": []}
|
||||
)
|
||||
return {"kind": "context_graph_parts", "stage": self.graph, "system": system, "reads": self.reads}
|
||||
|
||||
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.reads = merge_graph(self.reads, graph_from_sources([source]), accumulate=True)
|
||||
self.calls.add((turn_id, call_id))
|
||||
|
||||
|
||||
@@ -93,9 +95,16 @@ def _restore(history: HistoryReader, generation: str | None) -> _State:
|
||||
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:
|
||||
value = fact.content.get("context_graph")
|
||||
parts = decode_graph_parts(value) if fact.kind is HistoryKind.MODEL_REQUEST or boundary else None
|
||||
graph = decode_graph(value) if parts is None and (fact.kind is HistoryKind.MODEL_REQUEST or boundary) else None
|
||||
if boundary or parts is not None or graph is not None:
|
||||
if parts is not None:
|
||||
state.graph = parts["stage"]
|
||||
state.system_graph = parts["system"]
|
||||
state.system_turn_id = fact.turn_id
|
||||
state.reads = parts["reads"]
|
||||
elif graph is not None:
|
||||
state.graph = graph
|
||||
for event, turn_id in reversed(pending):
|
||||
state.apply(event, turn_id)
|
||||
@@ -154,26 +163,46 @@ class ContextGraphObserver:
|
||||
|
||||
async def observe_prompt(
|
||||
self, chat_id: str, sources: tuple[PromptSource, ...], metadata: Mapping[str, Any], *, persistent: bool,
|
||||
system_sources: tuple[PromptSource, ...] | None = None,
|
||||
) -> None:
|
||||
if not sources:
|
||||
if not sources and system_sources is None:
|
||||
return
|
||||
def project() -> ContextGraph:
|
||||
receipts = [source_receipt(source.path, source.content, loaded=source.loaded) for source in sources]
|
||||
return graph_from_sources(receipts)
|
||||
def project() -> tuple[ContextGraph, ContextGraph | None]:
|
||||
def graph_for(items: tuple[PromptSource, ...]) -> ContextGraph:
|
||||
return graph_from_sources([
|
||||
source_receipt(source.path, source.content, loaded=source.loaded) for source in items
|
||||
])
|
||||
return graph_for(sources), graph_for(system_sources) if system_sources is not None else None
|
||||
try:
|
||||
graph = await asyncio.to_thread(project)
|
||||
graph, system_graph = await asyncio.to_thread(project)
|
||||
state = await self._state(chat_id, metadata, persistent=persistent)
|
||||
if system_graph is not None:
|
||||
turn_id = metadata.get(WEBUI_TURN_METADATA_KEY)
|
||||
state.system_graph = system_graph
|
||||
state.system_turn_id = turn_id if isinstance(turn_id, str) else None
|
||||
state.graph = merge_graph(state.graph, graph)
|
||||
except Exception:
|
||||
logger.exception("Unable to observe prompt sources for context graph")
|
||||
|
||||
async def snapshot_parts(
|
||||
self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool,
|
||||
) -> ContextGraphParts:
|
||||
state = await self._state(chat_id, metadata, persistent=persistent)
|
||||
return state.request_parts(metadata.get(WEBUI_TURN_METADATA_KEY))
|
||||
|
||||
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
|
||||
return graph_from_parts(await self.snapshot_parts(chat_id, metadata, persistent=persistent))
|
||||
|
||||
async def reset(self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool) -> None:
|
||||
async def reset(
|
||||
self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool,
|
||||
) -> ContextGraphParts | None:
|
||||
state = await self._state(chat_id, metadata, persistent=persistent)
|
||||
state.graph = {"nodes": [], "edges": []}
|
||||
state.reads = {"nodes": [], "edges": []}
|
||||
state.calls.clear()
|
||||
turn_id = metadata.get(WEBUI_TURN_METADATA_KEY)
|
||||
if isinstance(turn_id, str) and turn_id and state.system_turn_id == turn_id:
|
||||
return state.request_parts(turn_id)
|
||||
return None
|
||||
@@ -18,13 +18,12 @@ class ContextSourceHook(AgentHook):
|
||||
return False
|
||||
|
||||
async def before_model_request(self) -> None:
|
||||
sources = tuple(self._sources)
|
||||
self._sources.clear()
|
||||
if sources:
|
||||
await self._events.emit(PromptSourcesEvent(sources))
|
||||
event = self._sources.drain()
|
||||
if event.sources or event.system_sources is not None:
|
||||
await self._events.emit(event)
|
||||
|
||||
async def on_finally(self, context: AgentRunHookContext) -> None:
|
||||
self._sources.clear()
|
||||
self._sources.drain()
|
||||
self._capture.__exit__(None, None, None)
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
from collections.abc import Callable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, replace
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias
|
||||
|
||||
@@ -25,7 +25,7 @@ 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_graph import ContextGraph, ContextGraphParts, graph_from_parts
|
||||
from nanobot.context_sources import PromptSourcesEvent
|
||||
from nanobot.events import ModelRequestEvent
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
@@ -120,19 +120,22 @@ class WebUIOutboundDelivery:
|
||||
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)
|
||||
parts: ContextGraphParts | None = None
|
||||
graph: ContextGraph | None = None
|
||||
try:
|
||||
if isinstance(event, ModelRequestEvent):
|
||||
parts = await self._context_graph.snapshot_parts(msg.chat_id, msg.metadata, persistent=persistent)
|
||||
elif event.phase == "succeeded":
|
||||
parts = await self._context_graph.reset(msg.chat_id, msg.metadata, persistent=persistent)
|
||||
if parts is not None:
|
||||
graph = graph_from_parts(parts)
|
||||
except Exception:
|
||||
logger.exception("Unable to observe context graph")
|
||||
if graph is None and isinstance(event, ModelRequestEvent):
|
||||
graph = {"nodes": [], "edges": []}
|
||||
notification = project_notification(msg.chat_id, event, msg.metadata, context_graph=graph)
|
||||
assert notification is not None
|
||||
return replace(notification, context_graph_parts=parts)
|
||||
|
||||
async def initialize(self) -> None:
|
||||
await self._transcripts.initialize()
|
||||
@@ -219,6 +222,7 @@ class WebUIOutboundDelivery:
|
||||
|
||||
for msg in messages:
|
||||
progress = msg.event if isinstance(msg.event, ProgressEvent) else None
|
||||
parts: ContextGraphParts | None = None
|
||||
if progress is not None:
|
||||
body = await self._message_payload(msg, progress)
|
||||
persistent, label = True, " "
|
||||
@@ -226,6 +230,7 @@ class WebUIOutboundDelivery:
|
||||
notification = await self._project_notification(msg)
|
||||
assert notification is not None
|
||||
body = dict(notification.payload)
|
||||
parts = notification.context_graph_parts
|
||||
persistent = notification.persistence == "turn_activity"
|
||||
label = f" {body['event']} "
|
||||
if persistent:
|
||||
@@ -244,7 +249,10 @@ class WebUIOutboundDelivery:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id))
|
||||
frames.append((recipients, raw, label))
|
||||
if persistent:
|
||||
records.append({**body, "text": msg.content} if progress is not None else body)
|
||||
record = {**body, "text": msg.content} if progress is not None else dict(body)
|
||||
if parts is not None:
|
||||
record["context_graph"] = parts
|
||||
records.append(record)
|
||||
byte_count += size
|
||||
await flush()
|
||||
|
||||
@@ -252,7 +260,7 @@ class WebUIOutboundDelivery:
|
||||
event = msg.event
|
||||
if isinstance(event, PromptSourcesEvent):
|
||||
await self._context_graph.observe_prompt(
|
||||
msg.chat_id, event.sources, msg.metadata,
|
||||
msg.chat_id, event.sources, msg.metadata, system_sources=event.system_sources,
|
||||
persistent=self._temporary_chats.should_persist_transcript(msg.chat_id),
|
||||
)
|
||||
return
|
||||
@@ -298,6 +306,7 @@ class WebUIOutboundDelivery:
|
||||
await self._send_payload(
|
||||
msg.chat_id, notification.payload, persistence=notification.persistence,
|
||||
metadata=msg.metadata if notification.attach_turn_metadata else None,
|
||||
context_graph_parts=notification.context_graph_parts,
|
||||
)
|
||||
return
|
||||
if isinstance(event, GoalStateSyncEvent):
|
||||
@@ -559,11 +568,15 @@ class WebUIOutboundDelivery:
|
||||
persistence: WebUIWirePersistence,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
turn_owner: str | None = None,
|
||||
context_graph_parts: ContextGraphParts | None = None,
|
||||
) -> None:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(chat_id))
|
||||
body: dict[str, Any] = dict(payload)
|
||||
if persistence == "turn_activity":
|
||||
await self._persist_turn_transcript_event(chat_id, body, metadata=metadata, phase="activity")
|
||||
await self._persist_turn_transcript_event(
|
||||
chat_id, body, metadata=metadata, phase="activity",
|
||||
transcript_overrides={"context_graph": context_graph_parts} if context_graph_parts is not None else None,
|
||||
)
|
||||
elif persistence == "turn_complete":
|
||||
prior_failure = (
|
||||
(metadata or {}).get("webui") is True
|
||||
|
||||
@@ -11,7 +11,7 @@ from nanobot.bus.outbound_events import (
|
||||
RetryStatusEvent,
|
||||
TurnEndEvent,
|
||||
)
|
||||
from nanobot.context_graph import ContextGraph, ContextSnapshot
|
||||
from nanobot.context_graph import ContextGraph, ContextGraphParts, ContextSnapshot
|
||||
from nanobot.events import AgentEvent, CompactionReason, ModelRequestEvent
|
||||
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
|
||||
|
||||
@@ -111,6 +111,7 @@ class ModelRequestWirePayload(_ChatWirePayload):
|
||||
|
||||
|
||||
class ContextCompactionWirePayload(_ChatWirePayload):
|
||||
context_graph: NotRequired[ContextGraph]
|
||||
context_snapshot: NotRequired[ContextSnapshot]
|
||||
event: Literal["context_compaction"]
|
||||
compaction_id: str
|
||||
@@ -253,6 +254,7 @@ class NotificationProjection:
|
||||
persistence: WebUIWirePersistence = "transient"
|
||||
deliver_offline: bool = False
|
||||
attach_turn_metadata: bool = False
|
||||
context_graph_parts: ContextGraphParts | None = None
|
||||
|
||||
|
||||
def project_notification(
|
||||
@@ -278,8 +280,11 @@ def project_notification(
|
||||
payload, persistence="turn_activity", deliver_offline=True, attach_turn_metadata=True,
|
||||
)
|
||||
if isinstance(event, ContextCompactionEvent):
|
||||
compaction_payload = encode_context_compaction(chat_id, event)
|
||||
if context_graph is not None:
|
||||
compaction_payload["context_graph"] = context_graph
|
||||
return NotificationProjection(
|
||||
encode_context_compaction(chat_id, event),
|
||||
compaction_payload,
|
||||
persistence="transient" if event.phase == "started" else "turn_activity",
|
||||
deliver_offline=True,
|
||||
attach_turn_metadata=True,
|
||||
|
||||
@@ -1542,6 +1542,8 @@ def _client_projection_event(
|
||||
"compaction_id": compaction_id,
|
||||
"phase": phase,
|
||||
}
|
||||
if (graph := decode_graph(record.get("context_graph"))) is not None:
|
||||
projected["context_graph"] = graph
|
||||
if (snapshot := decode_snapshot(record.get("context_snapshot"))) is not None:
|
||||
projected["context_snapshot"] = snapshot
|
||||
reason = record.get("reason")
|
||||
|
||||
Reference in new issue
Block a user