fix(sessions): preserve cross-session input ownership and history (#6613)
* fix(webui): reconcile cross-session history by message ID * fix(sessions): preserve target authority and input ownership Resolve cross-session follow-ups through the target route, carry stable input IDs through admission and recovery, and associate live and replayed answers with the inputs actually consumed. Keep ordinary input scope isolation and omit historical anomaly repair. Resolves NAN-430. * fix(sessions): complete input identity integration across boundaries Carry input identity explicitly in projected input events, keep runner annotations out of public history, and reuse the canonical WebUI session parser during recovery. Type validated recovery metadata and align existing channel and subagent regressions with explicit response ownership. All nine failed compatibility cases and adjacent recovery coverage pass in a focused 58-test run. * fix(sessions): unify input recording and block remote commands * fix(webui): keep input ownership checks page-bounded Look up referenced inputs through the existing identity index before invoking transcript backfill. Complete pages no longer scan the full prompt history, including answers whose inputs live on earlier pages. Cover cold-cache pagination and cross-turn ownership in existing regressions. Focused pagination, replay and follow-up recovery checks: 88 passed. * fix(webui): preserve response ownership during history replay * fix: resolve strict typing in response replay * fix: preserve continuation ownership during recovery * test: diagnose stuck gateway asyncio shutdown * test: retain gateway thread stack diagnostics * test(webui): stabilize native autoscroll browser setup
This commit is contained in:
1 parent
0ce335bf12
commit
394a78e82d
51 files changed
+1412
-334
No files matched your search
@@ -64,6 +64,7 @@ class TranscriptInput:
|
||||
current_role: str = "user"
|
||||
session_summary: SessionSummary | None = None
|
||||
runtime_context_blocks: Sequence[RuntimeContextBlock] | None = None
|
||||
input_metadata: Mapping[str, Any] | None = None
|
||||
|
||||
@property
|
||||
def message_count(self) -> int:
|
||||
@@ -295,6 +296,8 @@ class ContextBuilder:
|
||||
current_role=transcript.current_role,
|
||||
runtime_context_blocks=transcript.runtime_context_blocks,
|
||||
)
|
||||
if transcript.input_metadata:
|
||||
current["_meta"] = {**current.get("_meta", {}), **transcript.input_metadata}
|
||||
messages.append(current)
|
||||
return messages
|
||||
|
||||
|
||||
+24
-35
@@ -41,9 +41,7 @@ from nanobot.agent.turn_delivery import (
|
||||
from nanobot.agent.turn_delivery import TurnRoute as TurnRoute
|
||||
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
|
||||
from nanobot.bus.events import (
|
||||
INBOUND_META_LOCAL_MEDIA,
|
||||
INBOUND_META_RUNTIME_CONTROL,
|
||||
INBOUND_META_TURN_ID,
|
||||
INBOUND_META_USER_SHELL,
|
||||
RUNTIME_CONTROL_SESSION_DISCARD,
|
||||
InboundMessage,
|
||||
@@ -85,6 +83,7 @@ from nanobot.session.automation_turns import automation_history_overrides
|
||||
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
|
||||
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager, SessionPolicy
|
||||
from nanobot.session.message_metadata import input_history_metadata, persisted_message
|
||||
from nanobot.session.model_selection import (
|
||||
SESSION_MODEL_PRESET_METADATA_KEY,
|
||||
model_preset_from_metadata,
|
||||
@@ -646,7 +645,9 @@ class AgentLoop:
|
||||
) -> None:
|
||||
from nanobot.agent.tools.context import ToolContext
|
||||
from nanobot.agent.tools.loader import ToolLoader
|
||||
from nanobot.agent.tools.session_messages import session_message_runtime_context
|
||||
|
||||
self.register_runtime_context_provider(session_message_runtime_context)
|
||||
runtime_control = AgentRuntimeControl(self)
|
||||
self.register_runtime_context_provider(runtime_control.workspace_context)
|
||||
self.register_runtime_context_provider(
|
||||
@@ -698,18 +699,6 @@ class AgentLoop:
|
||||
def pending_local_trigger_ids_for_session(self, session_key: str) -> set[str]:
|
||||
return self._local_trigger_turns.pending_trigger_ids_for_session(session_key)
|
||||
|
||||
@staticmethod
|
||||
def _input_history_extra(msg: InboundMessage) -> dict[str, Any]:
|
||||
"""Keep input admission separate from the run that eventually consumes it."""
|
||||
extra: dict[str, Any] = {"timestamp": msg.timestamp.isoformat()}
|
||||
turn_id = msg.metadata.get(INBOUND_META_TURN_ID)
|
||||
if isinstance(turn_id, str) and turn_id:
|
||||
extra[INBOUND_META_TURN_ID] = turn_id
|
||||
local_media = msg.metadata.get(INBOUND_META_LOCAL_MEDIA)
|
||||
if isinstance(local_media, list) and local_media:
|
||||
extra[INBOUND_META_LOCAL_MEDIA] = [path for path in cast(list[object], local_media) if isinstance(path, str)]
|
||||
return extra
|
||||
|
||||
async def _persist_user_message_early(
|
||||
self,
|
||||
msg: InboundMessage,
|
||||
@@ -727,7 +716,7 @@ class AgentLoop:
|
||||
content_value = cast(object, msg.content)
|
||||
has_text = isinstance(content_value, str) and content_value.strip()
|
||||
if has_text or media_paths or runtime_context_blocks:
|
||||
extra = self._input_history_extra(msg) | ({"media": list(media_paths)} if media_paths else {}) | agent_context.session_extra(msg.metadata)
|
||||
extra = input_history_metadata(msg) | ({"media": list(media_paths)} if media_paths else {}) | agent_context.session_extra(msg.metadata)
|
||||
extra.update(kwargs)
|
||||
if HIDDEN_HISTORY_META in msg.metadata:
|
||||
extra[HIDDEN_HISTORY_META] = msg.metadata[HIDDEN_HISTORY_META]
|
||||
@@ -759,6 +748,11 @@ class AgentLoop:
|
||||
media=ctx.msg.media if ctx.kind is TurnKind.USER and ctx.msg.media else None,
|
||||
session_summary=ctx.pending_summary,
|
||||
runtime_context_blocks=ctx.runtime_context_blocks,
|
||||
input_metadata=(
|
||||
None
|
||||
if turn_continuation.internal_continuation_inbound(ctx.msg.metadata)
|
||||
else input_history_metadata(ctx.msg)
|
||||
),
|
||||
)
|
||||
|
||||
async def _request_context_for_turn(self, ctx: TurnContext) -> RequestContext:
|
||||
@@ -1103,7 +1097,7 @@ class AgentLoop:
|
||||
)
|
||||
row: dict[str, Any] = {
|
||||
"role": "user", "content": user_content,
|
||||
"_meta": self._input_history_extra(pending_msg),
|
||||
"_meta": input_history_metadata(pending_msg),
|
||||
}
|
||||
if HIDDEN_HISTORY_META in pending_msg.metadata:
|
||||
row[HIDDEN_HISTORY_META] = pending_msg.metadata[HIDDEN_HISTORY_META]
|
||||
@@ -1114,9 +1108,10 @@ class AgentLoop:
|
||||
else {}
|
||||
)
|
||||
if pending_msg.is_user_input:
|
||||
route = self.turn_delivery_factory.input_route(pending_msg, active_session_key or pending_msg.session_key)
|
||||
scope = await self.runner.prepare_prompt(
|
||||
self.workspace_scopes.for_turn,
|
||||
channel=pending_msg.channel,
|
||||
channel=route.channel,
|
||||
message_metadata=_prompt_scope_metadata(metadata),
|
||||
session_metadata=_prompt_scope_metadata(session.metadata) if session is not None else None,
|
||||
)
|
||||
@@ -1125,8 +1120,8 @@ class AgentLoop:
|
||||
if scope != effective_scope:
|
||||
return None
|
||||
pending_request = RequestContext(
|
||||
channel=pending_msg.channel,
|
||||
chat_id=pending_msg.chat_id,
|
||||
channel=route.channel,
|
||||
chat_id=route.chat_id,
|
||||
message_id=metadata.get("message_id"),
|
||||
session_key=active_session_key,
|
||||
session_generation=session.generation if session is not None else None,
|
||||
@@ -1251,6 +1246,15 @@ class AgentLoop:
|
||||
workspace=effective_scope.project_path,
|
||||
include_memory=session.policy.persist if session is not None else True,
|
||||
)
|
||||
if initial_message is not None and turn_continuation.internal_continuation_inbound(initial_message.metadata):
|
||||
build_transcript = transcript_builder
|
||||
|
||||
def transcript_builder(transcript: TranscriptInput) -> list[dict[str, Any]]:
|
||||
messages = build_transcript(transcript)
|
||||
if transcript.current_message is not None:
|
||||
messages[-1][HIDDEN_HISTORY_META] = {"kind": "internal_continuation"}
|
||||
return messages
|
||||
|
||||
if request_context is None:
|
||||
request_ctx = dataclasses.replace(
|
||||
request_ctx,
|
||||
@@ -2505,16 +2509,8 @@ class AgentLoop:
|
||||
if summary_checkpoint is not None and checkpoint_boundary == message_index:
|
||||
session.commit_summary_checkpoint(summary_checkpoint.summary)
|
||||
|
||||
entry = dict(message)
|
||||
entry = persisted_message(message)
|
||||
followup_id = entry.pop(PENDING_FOLLOWUP_ID_KEY, None)
|
||||
internal_meta = cast(object, entry.pop("_meta", None))
|
||||
runtime_context_meta = (
|
||||
cast(dict[str, Any], internal_meta).get(
|
||||
RUNTIME_CONTEXT_MESSAGE_META
|
||||
)
|
||||
if isinstance(internal_meta, dict)
|
||||
else None
|
||||
)
|
||||
role, content = entry.get("role"), entry.get("content")
|
||||
if role == "assistant" and not content and not entry.get("tool_calls"):
|
||||
continue # skip empty assistant messages — they poison session context
|
||||
@@ -2553,13 +2549,6 @@ class AgentLoop:
|
||||
if not filtered:
|
||||
continue
|
||||
entry["content"] = filtered
|
||||
if isinstance(runtime_context_meta, dict):
|
||||
entry[RUNTIME_CONTEXT_HISTORY_META] = runtime_context_meta
|
||||
if isinstance(internal_meta, dict):
|
||||
for key in ("timestamp", INBOUND_META_TURN_ID):
|
||||
value = cast(dict[str, Any], internal_meta).get(key)
|
||||
if isinstance(value, str) and value:
|
||||
entry[key] = value
|
||||
entry.setdefault("timestamp", datetime.now().isoformat())
|
||||
session.messages.append(entry)
|
||||
if role == "user" and isinstance(followup_id, str) and followup_id:
|
||||
|
||||
+47
-11
@@ -26,7 +26,7 @@ from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
|
||||
from nanobot.agent.tools.context import tool_log_content_allowed
|
||||
from nanobot.agent.tools.execution import ToolCallResult, execute_tool_calls
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.events import NO_EVENTS, EventSink, ModelRequestEvent
|
||||
from nanobot.events import NO_EVENTS, EventSink, ModelRequestEvent, ResponseInputsEvent
|
||||
from nanobot.llm_usage.context import (
|
||||
LLMUsageSource,
|
||||
bind_llm_usage_source,
|
||||
@@ -177,6 +177,31 @@ class AgentRunner:
|
||||
"""Append injected messages without rewriting the raw transcript."""
|
||||
messages.extend(injections)
|
||||
|
||||
@staticmethod
|
||||
def _response_input_ids(messages: list[dict[str, Any]]) -> tuple[str, ...]:
|
||||
"""Consecutive inputs share an answer; tool rounds keep their input owner."""
|
||||
identifiers: list[str] = []
|
||||
for message in reversed(messages):
|
||||
if message.get("role") != "user":
|
||||
if identifiers:
|
||||
break
|
||||
continue
|
||||
marker = message.get(HIDDEN_HISTORY_META)
|
||||
if isinstance(marker, dict) and cast(dict[str, Any], marker).get("kind") == "internal_continuation":
|
||||
if identifiers:
|
||||
break
|
||||
continue
|
||||
metadata: dict[str, Any] = message.get("_meta") or {}
|
||||
input_id = metadata.get("input_id")
|
||||
if not isinstance(input_id, str) or not input_id:
|
||||
break
|
||||
identifiers.append(input_id)
|
||||
return tuple(reversed(identifiers))
|
||||
|
||||
@staticmethod
|
||||
def _with_response_inputs(input_ids: tuple[str, ...], response: dict[str, Any]) -> dict[str, Any]:
|
||||
return {**response, "_meta": {**response.get("_meta", {}), "response_input_ids": list(input_ids)}}
|
||||
|
||||
async def _try_drain_injections(
|
||||
self,
|
||||
spec: AgentRunSpec,
|
||||
@@ -426,11 +451,15 @@ class AgentRunner:
|
||||
if interrupted:
|
||||
length_recovery_parts.clear()
|
||||
else:
|
||||
messages.append(build_length_recovery_message(segment_content))
|
||||
messages.append({
|
||||
**build_length_recovery_message(segment_content),
|
||||
HIDDEN_HISTORY_META: {"kind": "internal_continuation"},
|
||||
})
|
||||
if hook.wants_streaming():
|
||||
segment_context.stream_continues_current_message = not interrupted
|
||||
await hook.on_stream_end(segment_context, resuming=True)
|
||||
|
||||
response_input_ids: tuple[str, ...] = ()
|
||||
iteration = -1
|
||||
followup_requested = False
|
||||
while (
|
||||
@@ -454,6 +483,9 @@ class AgentRunner:
|
||||
if drained_before_request:
|
||||
had_injections = True
|
||||
await end_length_segment(interrupted=drained_before_request)
|
||||
response_input_ids = self._response_input_ids(messages)
|
||||
if spec.events.accepts(ResponseInputsEvent):
|
||||
await spec.events.emit(ResponseInputsEvent(response_input_ids))
|
||||
context = AgentHookContext(
|
||||
iteration=iteration,
|
||||
messages=messages,
|
||||
@@ -513,6 +545,7 @@ class AgentRunner:
|
||||
assistant_message,
|
||||
response,
|
||||
)
|
||||
assistant_message = self._with_response_inputs(response_input_ids, assistant_message)
|
||||
messages.append(assistant_message)
|
||||
await self._emit_checkpoint(
|
||||
spec,
|
||||
@@ -669,14 +702,14 @@ class AgentRunner:
|
||||
len(length_recovery_parts),
|
||||
_MAX_LENGTH_RECOVERIES,
|
||||
)
|
||||
messages.append(conversation_state.project_response_message(
|
||||
messages.append(self._with_response_inputs(response_input_ids, conversation_state.project_response_message(
|
||||
build_assistant_message(
|
||||
clean,
|
||||
reasoning_content=response.reasoning_content,
|
||||
thinking_blocks=response.thinking_blocks,
|
||||
),
|
||||
response,
|
||||
))
|
||||
)))
|
||||
# The next input snapshot decides whether to continue this
|
||||
# answer or close its stream before answering a new question.
|
||||
pending_length_segment = (context, clean or "")
|
||||
@@ -711,6 +744,7 @@ class AgentRunner:
|
||||
assistant_message,
|
||||
response,
|
||||
)
|
||||
assistant_message = self._with_response_inputs(response_input_ids, assistant_message)
|
||||
messages.append(assistant_message)
|
||||
await self._emit_checkpoint(
|
||||
spec,
|
||||
@@ -738,10 +772,10 @@ class AgentRunner:
|
||||
if not is_blank_text(interrupted_content):
|
||||
# This is unsynchronized output, not a completed response or
|
||||
# provider-owned projection. Keep it in the next native delta.
|
||||
messages.append({
|
||||
messages.append(self._with_response_inputs(response_input_ids, {
|
||||
**build_assistant_message(interrupted_content),
|
||||
"_interrupted": True,
|
||||
})
|
||||
}))
|
||||
|
||||
# Check for mid-turn injections BEFORE signaling stream end.
|
||||
# If injections are found we keep the stream alive (resuming=True)
|
||||
@@ -808,7 +842,7 @@ class AgentRunner:
|
||||
final_content = EMPTY_FINAL_RESPONSE_MESSAGE
|
||||
stop_reason = "empty_final_response"
|
||||
error = final_content
|
||||
self._append_final_message(messages, final_content)
|
||||
self._append_final_message(messages, final_content, response_input_ids)
|
||||
context.final_content = final_content
|
||||
context.error = error
|
||||
context.stop_reason = stop_reason
|
||||
@@ -868,7 +902,7 @@ class AgentRunner:
|
||||
pending_stream_content = terminal_tail
|
||||
else:
|
||||
final_content = terminal_content
|
||||
self._append_final_message(messages, terminal_content)
|
||||
self._append_final_message(messages, terminal_content, response_input_ids)
|
||||
|
||||
return AgentRunResult(
|
||||
final_content=final_content,
|
||||
@@ -1496,7 +1530,9 @@ class AgentRunner:
|
||||
})
|
||||
|
||||
@staticmethod
|
||||
def _append_final_message(messages: list[dict[str, Any]], content: str | None) -> None:
|
||||
def _append_final_message(
|
||||
messages: list[dict[str, Any]], content: str | None, input_ids: tuple[str, ...],
|
||||
) -> None:
|
||||
if not content:
|
||||
return
|
||||
if (
|
||||
@@ -1506,9 +1542,9 @@ class AgentRunner:
|
||||
):
|
||||
if messages[-1].get("content") == content:
|
||||
return
|
||||
messages[-1] = build_assistant_message(content)
|
||||
messages[-1] = AgentRunner._with_response_inputs(input_ids, build_assistant_message(content))
|
||||
return
|
||||
messages.append(build_assistant_message(content))
|
||||
messages.append(AgentRunner._with_response_inputs(input_ids, build_assistant_message(content)))
|
||||
|
||||
@staticmethod
|
||||
def _append_model_error_placeholder(messages: list[dict[str, Any]]) -> None:
|
||||
|
||||
@@ -40,6 +40,22 @@ MIN_REPLY_TIMEOUT_SECONDS = 5
|
||||
MAX_REPLY_TIMEOUT_SECONDS = 60
|
||||
|
||||
|
||||
async def session_message_runtime_context(
|
||||
request: RequestContext,
|
||||
) -> RuntimeContextBlock | None:
|
||||
envelope = session_message_envelope(request.metadata)
|
||||
if envelope is None:
|
||||
return None
|
||||
source = session_handle_for_name(
|
||||
envelope["source_session_key"],
|
||||
envelope["source_handle"],
|
||||
)
|
||||
content = f"Message from @{source.name}."
|
||||
if envelope["expect_reply"]:
|
||||
content += " Reply with send_session_message."
|
||||
return RuntimeContextBlock(source="session_message", content=content)
|
||||
|
||||
|
||||
class SessionMessageError(ValueError):
|
||||
pass
|
||||
|
||||
@@ -113,25 +129,6 @@ class SendSessionMessageTool(Tool):
|
||||
def description(self) -> str:
|
||||
return "Send a message to a persisted session by @handle."
|
||||
|
||||
def runtime_context_provider(self):
|
||||
return self._provide_runtime_context
|
||||
|
||||
async def _provide_runtime_context(
|
||||
self,
|
||||
request: RequestContext,
|
||||
) -> RuntimeContextBlock | None:
|
||||
envelope = session_message_envelope(request.metadata)
|
||||
if envelope is None:
|
||||
return None
|
||||
source = session_handle_for_name(
|
||||
envelope["source_session_key"],
|
||||
envelope["source_handle"],
|
||||
)
|
||||
content = f"Message from @{source.name}."
|
||||
if envelope["expect_reply"]:
|
||||
content += " Reply with send_session_message."
|
||||
return RuntimeContextBlock(source="session_message", content=content)
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
to: str,
|
||||
@@ -171,6 +168,8 @@ class SendSessionMessageTool(Tool):
|
||||
expect_reply: bool,
|
||||
reply_timeout_seconds: int | None = None,
|
||||
) -> str:
|
||||
if content.lstrip().startswith("/"):
|
||||
raise SessionMessageError("slash commands cannot be sent between sessions")
|
||||
timeout_seconds = self._validate_reply_timeout(expect_reply, reply_timeout_seconds)
|
||||
try:
|
||||
target_name = normalize_session_handle(target_handle)
|
||||
@@ -215,6 +214,7 @@ class SendSessionMessageTool(Tool):
|
||||
content=content,
|
||||
metadata={SESSION_MESSAGE_METADATA_KEY: envelope},
|
||||
session_key_override=target.session_key,
|
||||
require_existing_session=True,
|
||||
input_role="user",
|
||||
))
|
||||
sent_at.append(now)
|
||||
|
||||
@@ -24,6 +24,7 @@ from nanobot.events import (
|
||||
AgentEvent,
|
||||
ContextCompactionEvent,
|
||||
EventSink,
|
||||
ResponseInputsEvent,
|
||||
ResponseSource,
|
||||
ResponseSourceEvent,
|
||||
)
|
||||
@@ -34,6 +35,7 @@ from nanobot.session.keys import (
|
||||
is_internal_session,
|
||||
last_channel_from_metadata,
|
||||
)
|
||||
from nanobot.session.message_metadata import input_history_metadata
|
||||
from nanobot.utils.cancellation import shield_and_drain
|
||||
from nanobot.utils.helpers import strip_think
|
||||
|
||||
@@ -110,7 +112,7 @@ class TurnDeliveryFactory:
|
||||
*,
|
||||
enable_stream: bool = False,
|
||||
) -> TurnDelivery:
|
||||
route = self._default_route(msg, session_key)
|
||||
route = self.input_route(msg, session_key)
|
||||
if self.route_policy is not None:
|
||||
route = self.route_policy(msg, session_key, route)
|
||||
if not isinstance(cast(object, route), TurnRoute):
|
||||
@@ -178,7 +180,8 @@ class TurnDeliveryFactory:
|
||||
return _bind_events(self.bus, TurnRoute(channel, chat_id, metadata), session_key)
|
||||
|
||||
@staticmethod
|
||||
def _default_route(msg: InboundMessage, session_key: str) -> TurnRoute:
|
||||
def input_route(msg: InboundMessage, session_key: str) -> TurnRoute:
|
||||
"""Resolve the input's destination without acquiring a turn lifecycle owner."""
|
||||
if msg.channel != "system":
|
||||
return TurnRoute(
|
||||
channel=msg.channel,
|
||||
@@ -219,6 +222,7 @@ class TurnDelivery:
|
||||
_stop_reason: str | None = field(init=False, default=None)
|
||||
_failure_error_kind: str | None = field(init=False, default=None)
|
||||
_retry_status: RetryStatusEvent | None = field(init=False, default=None)
|
||||
_response_input_ids: tuple[str, ...] | None = field(init=False, default=None)
|
||||
_response_source: ResponseSource | None = field(init=False, default=None)
|
||||
_response_source_seen: bool = field(init=False, default=False)
|
||||
_response_content: str | None = field(init=False, default=None)
|
||||
@@ -227,8 +231,13 @@ class TurnDelivery:
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self.run_id = uuid4().hex
|
||||
input_id = input_history_metadata(self.input_message)["input_id"]
|
||||
self._response_input_ids = (input_id,) if input_id else None
|
||||
self._routed_events = _bind_events(self.bus, self.route, self.session_key)
|
||||
self.events = EventSink(self._publish_event, self._routed_events.accepts)
|
||||
self.events = EventSink(
|
||||
self._publish_event,
|
||||
lambda event_type: event_type is ResponseInputsEvent or self._routed_events.accepts(event_type),
|
||||
)
|
||||
self.delivery_message = dataclasses.replace(
|
||||
self.input_message,
|
||||
channel=self.route.channel,
|
||||
@@ -376,6 +385,10 @@ class TurnDelivery:
|
||||
**response.metadata,
|
||||
"response_sources": [dataclasses.asdict(self._response_source)],
|
||||
})
|
||||
if self._response_input_ids is not None and (response.channel, response.chat_id) == (self.route.channel, self.route.chat_id):
|
||||
response = dataclasses.replace(response, metadata={
|
||||
**response.metadata, "response_input_ids": list(self._response_input_ids),
|
||||
})
|
||||
if response.channel != "websocket" or stop_reason != "error":
|
||||
delivery = DeliveryRequest.from_context(
|
||||
self.input_message.metadata, self.session_key,
|
||||
@@ -460,6 +473,9 @@ class TurnDelivery:
|
||||
return f"{self._stream_base_id}:{self._stream_segment}"
|
||||
|
||||
async def _publish_event(self, event: AgentEvent) -> None:
|
||||
if isinstance(event, ResponseInputsEvent):
|
||||
self._response_input_ids = event.input_ids
|
||||
return
|
||||
if isinstance(event, ResponseSourceEvent):
|
||||
self._response_source_seen = True
|
||||
self._response_source = event.source
|
||||
@@ -484,6 +500,8 @@ class TurnDelivery:
|
||||
self._stream_sources.append(source)
|
||||
if self._routed_events.accepts(type(event)):
|
||||
metadata = deepcopy(self.route.metadata)
|
||||
if self._response_input_ids is not None:
|
||||
metadata["response_input_ids"] = list(self._response_input_ids)
|
||||
if self._response_source_seen and self._routed_events.accepts(ResponseSourceEvent):
|
||||
metadata["response_sources"] = (
|
||||
[] if self._stream_source_unknown else
|
||||
|
||||
@@ -92,6 +92,7 @@ class UserInputEvent(AgentEvent):
|
||||
|
||||
content: str
|
||||
created_at_ms: int
|
||||
input_id: str
|
||||
provenance: dict[str, Any]
|
||||
|
||||
|
||||
|
||||
@@ -2498,6 +2498,7 @@ async def test_send_projects_external_user_input_to_existing_wire_event() -> Non
|
||||
event=UserInputEvent(
|
||||
content="hello from another session",
|
||||
created_at_ms=1234,
|
||||
input_id="session-message:external-input",
|
||||
provenance={"name": "luma"},
|
||||
),
|
||||
)
|
||||
@@ -2510,6 +2511,7 @@ async def test_send_projects_external_user_input_to_existing_wire_event() -> Non
|
||||
"text": "hello from another session",
|
||||
"created_at_ms": 1234,
|
||||
"starts_turn": False,
|
||||
"input_id": "session-message:external-input",
|
||||
"provenance": {"name": "luma"},
|
||||
}
|
||||
|
||||
@@ -5424,6 +5426,7 @@ async def test_user_messages_fan_out_to_other_clients_on_the_same_chat(
|
||||
"text": "hello from A",
|
||||
"starts_turn": True,
|
||||
"turn_id": "turn-a",
|
||||
"input_id": "user:turn-a",
|
||||
"active_turn_id": "turn-a",
|
||||
"started_at": pytest.approx(wth.websocket_turn_wall_started_at("shared-chat")),
|
||||
}
|
||||
@@ -5433,6 +5436,7 @@ async def test_user_messages_fan_out_to_other_clients_on_the_same_chat(
|
||||
"text": "one more detail",
|
||||
"starts_turn": False,
|
||||
"turn_id": "steer-a",
|
||||
"input_id": "user:steer-a",
|
||||
"active_turn_id": "turn-a",
|
||||
"started_at": pytest.approx(wth.websocket_turn_wall_started_at("shared-chat")),
|
||||
}
|
||||
|
||||
@@ -364,6 +364,7 @@ async def test_same_session_projects_one_turn_to_both_clients(bus: MagicMock) ->
|
||||
"text": "hello from terminal A",
|
||||
"starts_turn": True,
|
||||
"turn_id": "turn-a",
|
||||
"input_id": "user:turn-a",
|
||||
"active_turn_id": "turn-a",
|
||||
"started_at": projected.raw["started_at"],
|
||||
}
|
||||
|
||||
@@ -27,6 +27,13 @@ class ModelRequestEvent(AgentEvent):
|
||||
request_usage: LLMUsage | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResponseInputsEvent(AgentEvent):
|
||||
"""Identify the inputs being answered by the next model request."""
|
||||
|
||||
input_ids: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResponseSource:
|
||||
"""Display-safe identity captured at the actual provider invocation."""
|
||||
|
||||
@@ -167,6 +167,13 @@ class HistoryReader:
|
||||
(self.key, ordinal),
|
||||
).fetchone()[0])
|
||||
|
||||
def has_input(self, input_id: str) -> bool:
|
||||
return self._db.execute(
|
||||
"""SELECT 1 FROM history_entries WHERE session_key=? AND kind='input'
|
||||
AND json_extract(record, '$.content.input_id')=?""",
|
||||
(self.key, input_id),
|
||||
).fetchone() is not None
|
||||
|
||||
def navigation(self) -> Iterator[tuple[int, int, HistoryFact]]:
|
||||
"""Read input/answer records only, never file diffs or tool result bodies."""
|
||||
kinds = (HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT,
|
||||
|
||||
@@ -303,6 +303,12 @@ class Session:
|
||||
if not any(key in message for key in ("tool_calls", "reasoning_content", "thinking_blocks")):
|
||||
continue
|
||||
entry: dict[str, Any] = {"role": message["role"], "content": content}
|
||||
if include_runtime_context and "input_id" in message and not is_hidden_history_message(message):
|
||||
entry["_meta"] = {"input_id": message["input_id"]}
|
||||
marker = message.get(HIDDEN_HISTORY_META)
|
||||
if include_runtime_context and isinstance(marker, dict) and cast(dict[str, Any], marker).get("kind") == "internal_continuation":
|
||||
# Attribution must distinguish persisted continuations from no-ID automation inputs.
|
||||
entry[HIDDEN_HISTORY_META] = {"kind": "internal_continuation"}
|
||||
for key in ("tool_calls", "tool_call_id", "name", "reasoning_content", "thinking_blocks"):
|
||||
if key in message:
|
||||
entry[key] = message[key]
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Admission identity and metadata shared by normal commits and checkpoint recovery."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, cast
|
||||
|
||||
from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA, INBOUND_META_TURN_ID, InboundMessage
|
||||
from nanobot.runtime_context import RUNTIME_CONTEXT_HISTORY_META, RUNTIME_CONTEXT_MESSAGE_META
|
||||
from nanobot.session.session_messages import session_message_input, session_message_public_metadata
|
||||
|
||||
|
||||
def input_history_metadata(message: InboundMessage) -> dict[str, Any]:
|
||||
# None marks an input without a public ID; synthetic continuations omit the key.
|
||||
extra: dict[str, Any] = {"timestamp": message.timestamp.isoformat(), "input_id": None}
|
||||
envelope = session_message_input(message)
|
||||
if envelope is not None:
|
||||
extra["session_message"] = session_message_public_metadata(envelope)
|
||||
extra["input_id"] = f"session-message:{envelope['message_id']}"
|
||||
turn_id = message.metadata.get(INBOUND_META_TURN_ID)
|
||||
if isinstance(turn_id, str) and turn_id:
|
||||
extra[INBOUND_META_TURN_ID] = turn_id
|
||||
if message.is_user_input and envelope is None:
|
||||
extra["input_id"] = f"user:{turn_id}"
|
||||
local_media = message.metadata.get(INBOUND_META_LOCAL_MEDIA)
|
||||
if isinstance(local_media, list) and local_media:
|
||||
extra[INBOUND_META_LOCAL_MEDIA] = [path for path in cast(list[object], local_media) if isinstance(path, str)]
|
||||
return extra
|
||||
|
||||
|
||||
def persisted_message(message: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Move internal transcript annotations to their durable history fields."""
|
||||
entry = dict(message)
|
||||
metadata = entry.pop("_meta", None)
|
||||
if not isinstance(metadata, dict):
|
||||
return entry
|
||||
metadata = cast(dict[str, Any], metadata)
|
||||
if entry.get("role") == "user":
|
||||
if "input_id" in metadata:
|
||||
entry["input_id"] = metadata["input_id"]
|
||||
for key in ("timestamp", INBOUND_META_TURN_ID):
|
||||
if isinstance(value := metadata.get(key), str) and value:
|
||||
entry[key] = value
|
||||
if isinstance(source := metadata.get("session_message"), dict):
|
||||
entry["session_message"] = source
|
||||
if isinstance(context := metadata.get(RUNTIME_CONTEXT_MESSAGE_META), dict):
|
||||
entry[RUNTIME_CONTEXT_HISTORY_META] = context
|
||||
elif entry.get("role") == "assistant" and "response_input_ids" in metadata:
|
||||
entry["response_input_ids"] = metadata["response_input_ids"]
|
||||
return entry
|
||||
@@ -11,6 +11,8 @@ from loguru import logger
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.session.message_metadata import persisted_message
|
||||
from nanobot.session.session_messages import session_message_envelope, session_message_input
|
||||
|
||||
RUNTIME_CHECKPOINT_KEY = "runtime_checkpoint"
|
||||
PENDING_USER_TURN_KEY = "pending_user_turn"
|
||||
@@ -66,7 +68,7 @@ class RecoveryAdmission(Protocol):
|
||||
|
||||
def record_pending_followup(session: Session, message: InboundMessage) -> str | None:
|
||||
"""Durably journal a WebUI follow-up before injecting it into a live turn."""
|
||||
if message.channel != "websocket":
|
||||
if message.channel != "websocket" and session_message_input(message) is None:
|
||||
return None
|
||||
try:
|
||||
metadata_value: object = json.loads(json.dumps(message.metadata))
|
||||
@@ -115,7 +117,7 @@ def pending_followups(session: Session) -> list[InboundMessage]:
|
||||
sender_id = cast(object, record.get("sender_id"))
|
||||
chat_id = cast(object, record.get("chat_id"))
|
||||
content = cast(object, record.get("content"))
|
||||
metadata = cast(object, record.get("metadata"))
|
||||
metadata_value = cast(object, record.get("metadata"))
|
||||
if (
|
||||
not isinstance(followup_id, str)
|
||||
or not followup_id
|
||||
@@ -125,8 +127,9 @@ def pending_followups(session: Session) -> list[InboundMessage]:
|
||||
or not chat_id
|
||||
):
|
||||
continue
|
||||
if not isinstance(content, str) or not isinstance(metadata, dict):
|
||||
if not isinstance(content, str) or not isinstance(metadata_value, dict):
|
||||
continue
|
||||
metadata = cast(dict[str, Any], metadata_value)
|
||||
media_value = cast(object, record.get("media"))
|
||||
media = (
|
||||
[item for item in cast(list[object], media_value) if isinstance(item, str)]
|
||||
@@ -136,15 +139,18 @@ def pending_followups(session: Session) -> list[InboundMessage]:
|
||||
timestamp = record.get("timestamp")
|
||||
# Older journals did not retain admission time; retain their existing recovery policy.
|
||||
received_at = datetime.fromisoformat(timestamp) if isinstance(timestamp, str) else datetime.now()
|
||||
envelope = session_message_envelope(metadata)
|
||||
is_session_input = envelope is not None and envelope["target_session_key"] == session.key
|
||||
messages.append(
|
||||
InboundMessage(
|
||||
channel="websocket",
|
||||
channel="system" if is_session_input else "websocket",
|
||||
input_role="user" if is_session_input else None,
|
||||
sender_id=sender_id,
|
||||
chat_id=chat_id,
|
||||
content=content,
|
||||
timestamp=received_at,
|
||||
media=media,
|
||||
metadata={**cast(dict[str, Any], metadata), PENDING_FOLLOWUP_ID_KEY: followup_id},
|
||||
metadata={**metadata, PENDING_FOLLOWUP_ID_KEY: followup_id},
|
||||
session_key_override=session.key,
|
||||
require_existing_session=True,
|
||||
)
|
||||
@@ -378,6 +384,7 @@ def restore_runtime_checkpoint(session: Session) -> bool:
|
||||
}
|
||||
)
|
||||
|
||||
restored = [persisted_message(message) for message in restored]
|
||||
overlap = 0
|
||||
# Cumulative checkpoints contain only the delta after accepted input. The
|
||||
# owner commits it and clears the checkpoint in one transaction, so none of
|
||||
|
||||
@@ -2,9 +2,12 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, TypedDict, cast
|
||||
from typing import TYPE_CHECKING, Any, TypedDict, cast
|
||||
|
||||
from nanobot.session.session_handles import normalize_session_handle
|
||||
from nanobot.session.session_handles import normalize_session_handle, session_handle_for_name
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.bus.events import InboundMessage
|
||||
|
||||
SESSION_MESSAGE_METADATA_KEY = "_session_message"
|
||||
|
||||
@@ -67,6 +70,22 @@ def session_message_envelope(
|
||||
}
|
||||
|
||||
|
||||
def session_message_input(message: InboundMessage) -> SessionMessageEnvelope | None:
|
||||
envelope = session_message_envelope(message.metadata)
|
||||
if (
|
||||
message.channel == "system" and message.is_user_input and envelope is not None
|
||||
and envelope["target_session_key"] == message.session_key
|
||||
):
|
||||
return envelope
|
||||
return None
|
||||
|
||||
|
||||
def session_message_public_metadata(envelope: SessionMessageEnvelope) -> dict[str, Any]:
|
||||
"""Return stable provenance without private routing identifiers."""
|
||||
source = session_handle_for_name(envelope["source_session_key"], envelope["source_handle"])
|
||||
return {"message_id": envelope["message_id"], "session": source.public_payload()}
|
||||
|
||||
|
||||
def _session_key(value: object) -> str | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
|
||||
@@ -117,9 +117,15 @@ def _create_schema_v4(db: sqlite3.Connection) -> None:
|
||||
db.execute("ALTER TABLE session_archives_v4 RENAME TO session_archives")
|
||||
|
||||
|
||||
def _create_schema_v5(db: sqlite3.Connection) -> None:
|
||||
db.execute("""CREATE UNIQUE INDEX history_input_identity ON history_entries (
|
||||
session_key, json_extract(record, '$.content.input_id')
|
||||
) WHERE kind='input'""")
|
||||
|
||||
|
||||
# Entries upgrade version N to N+1. Preserve released entries and append upgrades.
|
||||
_SCHEMA_MIGRATIONS: tuple[Callable[[sqlite3.Connection], None], ...] = (
|
||||
_create_schema_v1, _create_schema_v2, _create_schema_v3, _create_schema_v4,
|
||||
_create_schema_v1, _create_schema_v2, _create_schema_v3, _create_schema_v4, _create_schema_v5,
|
||||
)
|
||||
|
||||
|
||||
@@ -589,7 +595,15 @@ 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])
|
||||
appended = False
|
||||
for kind, created_at_ms, record, preview in encoded:
|
||||
if kind is HistoryKind.INPUT and db.execute(
|
||||
"""SELECT 1 FROM history_entries WHERE session_key=? AND kind='input'
|
||||
AND json_extract(record, '$.content.input_id')=json_extract(?, '$.content.input_id')""",
|
||||
(key, record),
|
||||
).fetchone() is not None:
|
||||
continue
|
||||
appended = True
|
||||
if completed:
|
||||
ordinal, position = ordinal + 1, 0
|
||||
if position == 0:
|
||||
@@ -612,7 +626,7 @@ class SqliteSessionStore:
|
||||
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=?",
|
||||
(created_at_ms, key))
|
||||
if encoded:
|
||||
if appended:
|
||||
db.execute("UPDATE history_heads SET revision=revision+1 WHERE session_key=?", (key,))
|
||||
return errors
|
||||
|
||||
|
||||
@@ -769,10 +769,11 @@ class SessionState:
|
||||
)
|
||||
|
||||
async def queue_followup(self, key: str, message: InboundMessage) -> str | None:
|
||||
if message.channel != "websocket":
|
||||
return None
|
||||
|
||||
from nanobot.session.recovery import record_pending_followup
|
||||
from nanobot.session.session_messages import session_message_input
|
||||
|
||||
if message.channel != "websocket" and session_message_input(message) is None:
|
||||
return None
|
||||
|
||||
payload = deepcopy(message)
|
||||
|
||||
|
||||
@@ -42,10 +42,10 @@ from nanobot.runtime_context import public_history_message
|
||||
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.session_handles import session_handle_for_name
|
||||
from nanobot.session.session_messages import (
|
||||
SessionMessageEnvelope,
|
||||
SESSION_MESSAGE_METADATA_KEY,
|
||||
session_message_envelope,
|
||||
session_message_public_metadata,
|
||||
)
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
from nanobot.utils.helpers import strip_think, truncate_text
|
||||
@@ -58,7 +58,7 @@ from nanobot.webui.metadata import (
|
||||
from nanobot.webui.recovery import RecoveryCoordinator
|
||||
from nanobot.webui.session_identity import is_webui_session_key, webui_session_key
|
||||
from nanobot.webui.star_prompt import update_star_prompt
|
||||
from nanobot.webui.transcript import append_session_message_input
|
||||
from nanobot.webui.transcript import WebUITranscriptRecorder
|
||||
|
||||
WEBUI_SESSION_METADATA_KEY = "webui"
|
||||
WEBUI_TITLE_METADATA_KEY = "title"
|
||||
@@ -85,19 +85,6 @@ class _WebsocketTurn:
|
||||
_WEBSOCKET_ACTIVE_TURNS: dict[str, dict[str, _WebsocketTurn]] = {}
|
||||
|
||||
|
||||
def _session_message_public_metadata(
|
||||
envelope: SessionMessageEnvelope,
|
||||
) -> dict[str, Any]:
|
||||
source = session_handle_for_name(
|
||||
envelope["source_session_key"],
|
||||
envelope["source_handle"],
|
||||
)
|
||||
return {
|
||||
"message_id": envelope["message_id"],
|
||||
"session": source.public_payload(),
|
||||
}
|
||||
|
||||
|
||||
def _validated_llm_runtime(value: object) -> LLMRuntime | None:
|
||||
return value if isinstance(value, LLMRuntime) else None
|
||||
|
||||
@@ -672,20 +659,16 @@ class WebuiTurnCoordinator:
|
||||
)
|
||||
if metadata is None or metadata.get(WEBUI_SESSION_METADATA_KEY) is not True:
|
||||
return
|
||||
public_metadata = _session_message_public_metadata(envelope)
|
||||
try:
|
||||
await append_session_message_input(
|
||||
session_key,
|
||||
sessions=self.sessions,
|
||||
content=event.content,
|
||||
created_at_ms=envelope["created_at_ms"],
|
||||
session_message=public_metadata,
|
||||
)
|
||||
except (OSError, TypeError, ValueError, SessionConflictError):
|
||||
logger.opt(exception=True).warning(
|
||||
"Failed to persist session input {}",
|
||||
envelope["message_id"],
|
||||
)
|
||||
public_metadata = session_message_public_metadata(envelope)
|
||||
revision = await self.sessions.state.project_history(session_key, lambda history: history.revision)
|
||||
if revision is None:
|
||||
return
|
||||
generation = event.context.session_generation or revision[0]
|
||||
metadata = {SESSION_MESSAGE_METADATA_KEY: envelope, HISTORY_GENERATION_METADATA_KEY: generation}
|
||||
if not await WebUITranscriptRecorder(self.sessions).append_user_message(
|
||||
session_key.split(":", 1)[1], event.content, metadata=metadata,
|
||||
):
|
||||
logger.warning("Failed to persist session input {}", envelope["message_id"])
|
||||
return
|
||||
await self.bus.publish_outbound(outbound_message_for_event(
|
||||
channel="websocket",
|
||||
@@ -693,6 +676,7 @@ class WebuiTurnCoordinator:
|
||||
event=UserInputEvent(
|
||||
content=event.content,
|
||||
created_at_ms=envelope["created_at_ms"],
|
||||
input_id=f"session-message:{envelope['message_id']}",
|
||||
provenance={"session_message": public_metadata},
|
||||
),
|
||||
))
|
||||
|
||||
@@ -37,7 +37,7 @@ _MESSAGE_KINDS = {
|
||||
}
|
||||
_CONTENT_FIELDS = frozenset({
|
||||
"text", "media_paths", "media", "media_urls", "reply_to", "agent_ui", "cli_apps", "mcp_presets", "session_mentions",
|
||||
"session_message", INBOUND_META_LOCAL_MEDIA, "tool_events", "edits", "source", "response_sources", "resuming",
|
||||
"session_message", "input_id", "response_input_ids", INBOUND_META_LOCAL_MEDIA, "tool_events", "edits", "source", "response_sources", "resuming",
|
||||
"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",
|
||||
|
||||
@@ -246,6 +246,7 @@ class WebUICommandRouter:
|
||||
}
|
||||
if turn_id is not None:
|
||||
body["turn_id"] = turn_id
|
||||
body["input_id"] = f"user:{turn_id}"
|
||||
if media:
|
||||
body["media_urls"] = media
|
||||
if cli_apps:
|
||||
|
||||
@@ -295,6 +295,7 @@ class WebUIOutboundDelivery:
|
||||
body: UserInputWirePayload = {
|
||||
"event": "user_message", "chat_id": msg.chat_id, "text": event.content,
|
||||
"created_at_ms": event.created_at_ms, "starts_turn": False,
|
||||
"input_id": event.input_id,
|
||||
}
|
||||
if event.provenance:
|
||||
body["provenance"] = event.provenance
|
||||
|
||||
@@ -172,6 +172,7 @@ class UserInputWirePayload(_ChatWirePayload):
|
||||
created_at_ms: int
|
||||
starts_turn: bool
|
||||
provenance: NotRequired[dict[str, Any]]
|
||||
input_id: NotRequired[str]
|
||||
|
||||
|
||||
class PairingChangedWirePayload(TypedDict):
|
||||
|
||||
@@ -140,7 +140,12 @@ class RecoveryCoordinator:
|
||||
and state["status"] == "resuming"
|
||||
and state["recovery_id"] == recovery_id
|
||||
)
|
||||
if message.channel != "websocket":
|
||||
from nanobot.session.session_messages import session_message_input
|
||||
|
||||
chat_id = message.chat_id if message.channel == "websocket" else None
|
||||
if session_message_input(message) is not None:
|
||||
chat_id = webui_chat_id(message.session_key)
|
||||
if chat_id is None:
|
||||
return True
|
||||
session = await self.sessions.state.get(message.session_key)
|
||||
state = recovery_state_from_metadata(session.metadata)
|
||||
@@ -164,7 +169,7 @@ class RecoveryCoordinator:
|
||||
reason="superseded",
|
||||
)
|
||||
await self.sessions.state.restore_interruption(session)
|
||||
await self._publish(message.chat_id, recovered)
|
||||
await self._publish(chat_id, recovered)
|
||||
return True
|
||||
|
||||
async def turn_completed(
|
||||
|
||||
+155
-53
@@ -36,6 +36,10 @@ from nanobot.session.history_graph import (
|
||||
)
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.session_messages import (
|
||||
session_message_envelope,
|
||||
session_message_public_metadata,
|
||||
)
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
from nanobot.session.state import SessionOperationQueueFullError
|
||||
from nanobot.webui.history import (
|
||||
@@ -46,7 +50,7 @@ from nanobot.webui.history import (
|
||||
)
|
||||
from nanobot.webui.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY
|
||||
from nanobot.webui.outbound_wire import project_tool_events
|
||||
from nanobot.webui.session_identity import webui_chat_id, webui_session_key
|
||||
from nanobot.webui.session_identity import webui_session_key
|
||||
|
||||
WEBUI_TRANSCRIPT_SCHEMA_VERSION = 3
|
||||
WEBUI_FORK_MARKER_EVENT = "fork_marker"
|
||||
@@ -487,21 +491,6 @@ def append_transcript_object(
|
||||
sessions.append_history(session_key, [fact_from_record(_record_for_append(obj))])
|
||||
|
||||
|
||||
async def append_session_message_input(
|
||||
session_key: str, *, sessions: SessionManager, content: str, created_at_ms: int,
|
||||
session_message: Mapping[str, Any],
|
||||
) -> None:
|
||||
chat_id = _chat_id_from_session_key(session_key)
|
||||
if chat_id is None:
|
||||
return
|
||||
event = build_user_transcript_event(chat_id, content)
|
||||
if event is None:
|
||||
return
|
||||
event.update(created_at_ms=created_at_ms, session_message=dict(session_message))
|
||||
await sessions.state.append_history(session_key, [fact_from_record(event)],
|
||||
expected_generation=None)
|
||||
|
||||
|
||||
def normalize_webui_turn_id(value: Any) -> str:
|
||||
if isinstance(value, str):
|
||||
candidate = value.strip()
|
||||
@@ -549,6 +538,10 @@ class WebUITranscriptRecorder:
|
||||
event["source"] = source
|
||||
if include_source and metadata is not None and "response_sources" in metadata:
|
||||
event["response_sources"] = _response_sources(metadata["response_sources"])
|
||||
if event.get("event") == "user" and (turn_id := (metadata or {}).get(WEBUI_TURN_METADATA_KEY)):
|
||||
event["input_id"] = f"user:{turn_id}"
|
||||
if include_source and metadata is not None and "response_input_ids" in metadata:
|
||||
event["response_input_ids"] = list(metadata["response_input_ids"])
|
||||
self._annotate_turn(chat_id, event, metadata, phase)
|
||||
|
||||
async def prepare_and_append(
|
||||
@@ -578,7 +571,10 @@ class WebUITranscriptRecorder:
|
||||
mcp_presets: list[dict[str, Any]] | None = None,
|
||||
session_mentions: Sequence[Mapping[str, Any]] | None = None,
|
||||
) -> bool:
|
||||
if text.strip() == "/stop" and not media_paths:
|
||||
envelope = session_message_envelope(metadata)
|
||||
if envelope is not None and envelope["target_session_key"] != webui_session_key(chat_id):
|
||||
envelope = None
|
||||
if text.strip() == "/stop" and not media_paths and envelope is None:
|
||||
return False
|
||||
event = build_user_transcript_event(
|
||||
chat_id,
|
||||
@@ -591,6 +587,12 @@ class WebUITranscriptRecorder:
|
||||
)
|
||||
if event is None:
|
||||
return False
|
||||
if envelope is not None:
|
||||
event.update(
|
||||
created_at_ms=envelope["created_at_ms"],
|
||||
session_message=session_message_public_metadata(envelope),
|
||||
input_id=f"session-message:{envelope['message_id']}",
|
||||
)
|
||||
return await self.prepare_and_append(chat_id, event, metadata=metadata, phase="user")
|
||||
|
||||
async def append(
|
||||
@@ -648,13 +650,6 @@ class WebUITranscriptRecorder:
|
||||
self._turn_sequences.pop((chat_id, turn_id), None)
|
||||
|
||||
|
||||
def _chat_id_from_session_key(session_key: str) -> str | None:
|
||||
chat_id = webui_chat_id(session_key)
|
||||
if chat_id is None:
|
||||
return None
|
||||
return chat_id.strip() or None
|
||||
|
||||
|
||||
def normalize_session_mentions_metadata(raw: object) -> list[dict[str, str]]:
|
||||
"""Validate session-reference metadata crossing a persistence seam."""
|
||||
if not isinstance(raw, Sequence) or isinstance(raw, (str, bytes, bytearray)):
|
||||
@@ -832,6 +827,8 @@ def _session_user_event(
|
||||
provenance = normalize_session_message_ui_metadata(message.get("session_message"))
|
||||
if provenance:
|
||||
event["session_message"] = provenance
|
||||
if isinstance(message_id := message.get("input_id"), str) and message_id:
|
||||
event["input_id"] = message_id
|
||||
input_id = message.get(INBOUND_META_TURN_ID)
|
||||
if isinstance(input_id, str) and _WEBUI_TURN_ID_RE.fullmatch(input_id):
|
||||
event["turn_id"] = input_id
|
||||
@@ -868,6 +865,8 @@ def _session_assistant_event(
|
||||
}
|
||||
if media_paths:
|
||||
event["media"] = media_paths
|
||||
if "response_input_ids" in message:
|
||||
event["response_input_ids"] = message["response_input_ids"]
|
||||
latency_ms = message.get("latency_ms")
|
||||
if isinstance(latency_ms, int | float) and latency_ms >= 0:
|
||||
event["latency_ms"] = int(latency_ms)
|
||||
@@ -890,7 +889,7 @@ def _session_backfill_turns(
|
||||
assistant_records: list[dict[str, Any]] = []
|
||||
|
||||
def flush() -> None:
|
||||
if current_user is None or not assistant_records:
|
||||
if current_user is None:
|
||||
return
|
||||
signature = tuple(
|
||||
text
|
||||
@@ -1120,9 +1119,16 @@ def _recover_incomplete_turns(
|
||||
return recovered
|
||||
|
||||
|
||||
def _needs_user_event_backfill(lines: list[dict[str, Any]]) -> bool:
|
||||
return any(
|
||||
not any(record.get("event") == "user" for record in turn)
|
||||
def _needs_user_event_backfill(lines: list[dict[str, Any]], history: HistoryReader) -> bool:
|
||||
referenced_inputs = {
|
||||
input_id
|
||||
for record in lines
|
||||
if isinstance(references := record.get("response_input_ids"), list)
|
||||
for input_id in cast(list[object], references)
|
||||
if isinstance(input_id, str) and input_id
|
||||
}
|
||||
return any(not history.has_input(input_id) for input_id in referenced_inputs) or any(
|
||||
not any(record.get("event") == "user" or isinstance(record.get("response_input_ids"), list) for record in turn)
|
||||
and _transcript_turn_signature(turn)
|
||||
for turn in _split_transcript_turns(lines)
|
||||
)
|
||||
@@ -1132,8 +1138,21 @@ def _with_backfilled_user(
|
||||
records: list[dict[str, Any]],
|
||||
user_event: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
input_id = user_event.get("input_id")
|
||||
legacy = not any("response_input_ids" in record for record in records)
|
||||
for index, rec in enumerate(records):
|
||||
if rec.get("event") in _TURN_DISPLAY_EVENTS:
|
||||
if (
|
||||
input_id and input_id in rec.get("response_input_ids", [])
|
||||
or (not input_id or legacy) and rec.get("event") in _TURN_DISPLAY_EVENTS
|
||||
):
|
||||
if input_id:
|
||||
references = rec.get("response_input_ids")
|
||||
if isinstance(references, list):
|
||||
references = cast(list[object], references)
|
||||
following = {value for value in references[references.index(input_id) + 1:]
|
||||
if isinstance(value, str)}
|
||||
index = next((i for i, prior in enumerate(records[:index])
|
||||
if prior.get("event") == "user" and prior.get("input_id") in following), index)
|
||||
return [*records[:index], dict(user_event), *records[index:]]
|
||||
return records
|
||||
|
||||
@@ -1358,6 +1377,8 @@ def build_webui_trace_detail_response(
|
||||
|
||||
def _client_projection_event_id(record: Mapping[str, Any]) -> str:
|
||||
identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY)
|
||||
if record.get("event") == "user" and isinstance(input_id := record.get("input_id"), str) and input_id:
|
||||
identity = f"input:{record.get('chat_id')}:{input_id}"
|
||||
if not isinstance(identity, str) or not identity:
|
||||
identity = _stable_record_digest(dict(record))
|
||||
digest = hashlib.sha256(f"event\0{identity}".encode("utf-8")).hexdigest()[:20]
|
||||
@@ -1389,6 +1410,8 @@ def _client_projection_common_fields(record: dict[str, Any]) -> dict[str, Any]:
|
||||
created_at_ms = _valid_created_at_ms(record.get("created_at_ms"))
|
||||
if created_at_ms is not None:
|
||||
fields["created_at_ms"] = created_at_ms
|
||||
if isinstance(input_id := record.get("input_id"), str):
|
||||
fields["input_id"] = input_id
|
||||
receipts = record.get(_WEBUI_PROJECTION_RECEIPTS_KEY)
|
||||
if receipts:
|
||||
fields["projection_receipts"] = receipts
|
||||
@@ -1419,8 +1442,11 @@ def _client_projection_event(
|
||||
) -> dict[str, Any] | None:
|
||||
event = record.get("event")
|
||||
common = _client_projection_common_fields(record)
|
||||
if event in {"delta", "stream_end", "message"} and "response_sources" in record:
|
||||
common["response_sources"] = _response_sources(record["response_sources"])
|
||||
if event in {"delta", "stream_end", "message"}:
|
||||
if "response_sources" in record:
|
||||
common["response_sources"] = _response_sources(record["response_sources"])
|
||||
if "response_input_ids" in record:
|
||||
common["response_input_ids"] = record["response_input_ids"]
|
||||
if event == "user":
|
||||
projected: dict[str, Any] = {
|
||||
"event": "user_message",
|
||||
@@ -1839,7 +1865,9 @@ def build_webui_thread_response(
|
||||
session_turns = _session_backfill_turns(session_key, session_messages or [])
|
||||
return session_turns
|
||||
|
||||
if _needs_user_event_backfill(lines):
|
||||
# Truncation can discard every reference that proves an input is missing.
|
||||
# Complete pages keep the ordinary missing-input fast-path decision.
|
||||
if replay_stats.truncated_oversized_turn or _needs_user_event_backfill(lines, history):
|
||||
view, _ = _prompt_view_snapshot(
|
||||
session_key, history=history, session_turns_loader=load_session_turns,
|
||||
session_version_loader=session_version_loader,
|
||||
@@ -1849,8 +1877,14 @@ def build_webui_thread_response(
|
||||
for turn in selected_turns:
|
||||
# Page selection assigns this absolute identity before any recovery.
|
||||
ordinal = int(turn[0][_WEBUI_REPLAY_IDENTITY_KEY].split(":")[1])
|
||||
user = view.backfilled_users.get(ordinal)
|
||||
recovered_lines.extend(_with_backfilled_user(turn, user) if user is not None else turn)
|
||||
for anchor, user in view.backfill_plan.get(ordinal, []):
|
||||
# Positions are stable even when the record at the anchor was
|
||||
# removed by oversized-turn selection or delta compaction.
|
||||
index = next((i for i, record in enumerate(turn)
|
||||
if (identity := record.get(_WEBUI_REPLAY_IDENTITY_KEY, "")).startswith(f"turn:{ordinal}:record:")
|
||||
and int(identity.rsplit(":", 1)[1]) >= anchor), len(turn))
|
||||
turn.insert(index, dict(user))
|
||||
recovered_lines.extend(turn)
|
||||
lines = recovered_lines
|
||||
if _needs_incomplete_turn_recovery(lines):
|
||||
lines = _recover_incomplete_turns(lines, load_session_turns())
|
||||
@@ -1920,6 +1954,7 @@ def build_webui_thread_response(
|
||||
|
||||
|
||||
class PromptSummary(TypedDict):
|
||||
inputId: str
|
||||
id: str
|
||||
preview: str
|
||||
answerPreview: str
|
||||
@@ -1933,16 +1968,20 @@ class _BackfillCandidate(NamedTuple):
|
||||
signature: str
|
||||
answer_preview: str
|
||||
has_user: bool
|
||||
input_ids: tuple[str, ...] | None
|
||||
|
||||
|
||||
class _ChunkPromptView(NamedTuple):
|
||||
prompts: tuple[PromptSummary, ...]
|
||||
candidates: tuple[_BackfillCandidate, ...]
|
||||
input_ids: frozenset[str]
|
||||
answers: dict[str, str]
|
||||
turns: dict[int, list[dict[str, Any]]]
|
||||
|
||||
|
||||
class _PromptView(NamedTuple):
|
||||
prompts: tuple[PromptSummary, ...]
|
||||
backfilled_users: dict[int, dict[str, Any]]
|
||||
backfill_plan: dict[int, list[tuple[int, dict[str, Any]]]]
|
||||
needs_canonical: bool
|
||||
|
||||
|
||||
@@ -1960,6 +1999,7 @@ def prompt_index_revision(session_key: str, session_version: tuple[str, int] | N
|
||||
def _prompt_summary(record: dict[str, Any], ordinal: int, answer: str) -> PromptSummary:
|
||||
return {
|
||||
"id": _client_projection_event_id(record),
|
||||
"inputId": str(record.get("input_id") or ""),
|
||||
"preview": str(record.get("text") or "").strip()[:320],
|
||||
"answerPreview": answer,
|
||||
"createdAt": _valid_created_at_ms(record.get("created_at_ms")) or 0,
|
||||
@@ -1971,29 +2011,41 @@ def _prompt_summary(record: dict[str, Any], ordinal: int, answer: str) -> Prompt
|
||||
def _history_prompt_summaries(history: HistoryReader) -> _ChunkPromptView:
|
||||
result: list[PromptSummary] = []
|
||||
candidates: list[_BackfillCandidate] = []
|
||||
input_ids: set[str] = set()
|
||||
answers: dict[str, str] = {}
|
||||
response_inputs: dict[int, list[str]] = {}
|
||||
turns: dict[int, list[dict[str, Any]]] = {}
|
||||
for ordinal, position, fact in history.navigation():
|
||||
record = record_from_fact(fact, history.key)
|
||||
record[_WEBUI_REPLAY_IDENTITY_KEY] = f"turn:{ordinal}:record:{position}"
|
||||
turns.setdefault(ordinal, []).append(record)
|
||||
if record.get("event") in {"message", "stream_end"} and not record.get("kind"):
|
||||
if isinstance(references := record.get("response_input_ids"), list):
|
||||
identifiers = [value for value in cast(list[object], references) if isinstance(value, str) and value]
|
||||
response_inputs.setdefault(ordinal, []).extend(identifiers)
|
||||
answer = str(record.get("text") or "").strip()[:240]
|
||||
if answer:
|
||||
for input_id in identifiers:
|
||||
answers.setdefault(input_id, answer)
|
||||
for ordinal, records in turns.items():
|
||||
has_user = any(record.get("event") == "user" for record in records)
|
||||
signature = _transcript_turn_signature(records)
|
||||
candidates.append(_BackfillCandidate(ordinal, _assistant_signature_identity(signature),
|
||||
signature[0][:240] if signature else "", has_user))
|
||||
candidates.append(_BackfillCandidate(
|
||||
ordinal, _assistant_signature_identity(signature),
|
||||
signature[0][:240] if signature else "", has_user,
|
||||
tuple(dict.fromkeys(response_inputs[ordinal])) if ordinal in response_inputs else None,
|
||||
))
|
||||
seen_turns: set[str] = set()
|
||||
seen_messages: set[str] = set()
|
||||
for index, record in enumerate(records):
|
||||
if record.get("event") != "user":
|
||||
continue
|
||||
turn_id = str(record.get("turn_id") or "")
|
||||
provenance = normalize_session_message_ui_metadata(record.get("session_message"))
|
||||
if provenance:
|
||||
message_id = str(provenance["message_id"])
|
||||
if message_id in seen_messages:
|
||||
continue
|
||||
seen_messages.add(message_id)
|
||||
elif turn_id and turn_id in seen_turns:
|
||||
input_id = record.get("input_id")
|
||||
if isinstance(input_id, str) and input_id:
|
||||
input_ids.add(input_id)
|
||||
result.append(_prompt_summary(record, ordinal, answers.get(input_id, "")))
|
||||
continue
|
||||
if turn_id and turn_id in seen_turns:
|
||||
continue
|
||||
if turn_id:
|
||||
seen_turns.add(turn_id)
|
||||
@@ -2006,7 +2058,7 @@ def _history_prompt_summaries(history: HistoryReader) -> _ChunkPromptView:
|
||||
if answer:
|
||||
break
|
||||
result.append(_prompt_summary(record, ordinal, answer))
|
||||
return _ChunkPromptView(tuple(result), tuple(candidates))
|
||||
return _ChunkPromptView(tuple(result), tuple(candidates), frozenset(input_ids), answers, turns)
|
||||
|
||||
|
||||
def _build_prompt_view(
|
||||
@@ -2018,7 +2070,11 @@ def _build_prompt_view(
|
||||
raw_prompts = list(chunk.prompts)
|
||||
candidates = list(chunk.candidates)
|
||||
session_turns = None
|
||||
needs_canonical = any(not candidate.has_user and candidate.signature for candidate in candidates)
|
||||
needs_canonical = any(
|
||||
not set(candidate.input_ids).issubset(chunk.input_ids)
|
||||
if candidate.input_ids is not None else not candidate.has_user and bool(candidate.signature)
|
||||
for candidate in candidates
|
||||
)
|
||||
if needs_canonical and session_turns_loader is not None:
|
||||
session_turns = session_turns_loader()
|
||||
entries: list[tuple[int, PromptSummary, dict[str, Any] | None]] = [
|
||||
@@ -2028,9 +2084,30 @@ def _build_prompt_view(
|
||||
signature_positions: dict[str, list[int]] = {}
|
||||
for position, turn in enumerate(session_turns or []):
|
||||
signature_positions.setdefault(_assistant_signature_identity(turn.assistant_signature), []).append(position)
|
||||
canonical_inputs = {
|
||||
user["input_id"]: user
|
||||
for turn in session_turns or []
|
||||
for user in (turn.user_event,)
|
||||
if isinstance(user.get("input_id"), str)
|
||||
}
|
||||
represented = set(chunk.input_ids)
|
||||
# Identity references take precedence over legacy answer matching, even when
|
||||
# the matching legacy answer occurs earlier in the display history.
|
||||
reserved = {input_id for candidate in candidates for input_id in candidate.input_ids or ()
|
||||
if input_id in canonical_inputs}
|
||||
used_positions: set[int] = set()
|
||||
for candidate in candidates:
|
||||
if not session_turns:
|
||||
break
|
||||
if candidate.input_ids is not None:
|
||||
for input_id in candidate.input_ids:
|
||||
if input_id in represented or input_id not in canonical_inputs:
|
||||
continue
|
||||
user = dict(canonical_inputs[input_id])
|
||||
summary = _prompt_summary(user, candidate.ordinal, chunk.answers.get(input_id, ""))
|
||||
entries.append((candidate.ordinal, summary, user))
|
||||
represented.add(input_id)
|
||||
continue
|
||||
positions = signature_positions.get(candidate.signature)
|
||||
if not candidate.signature or not positions:
|
||||
continue
|
||||
@@ -2044,15 +2121,40 @@ def _build_prompt_view(
|
||||
if candidate.has_user:
|
||||
continue
|
||||
user = dict(session_turns[match].user_event)
|
||||
if match in used_positions or user.get("input_id") in represented or user.get("input_id") in reserved:
|
||||
continue
|
||||
used_positions.add(match)
|
||||
if isinstance(input_id := user.get("input_id"), str) and input_id:
|
||||
represented.add(input_id)
|
||||
summary = _prompt_summary(user, candidate.ordinal, candidate.answer_preview)
|
||||
entries.append((candidate.ordinal, summary, user))
|
||||
prompts: list[PromptSummary] = []
|
||||
backfilled_users: dict[int, dict[str, Any]] = {}
|
||||
for ordinal, prompt, user in sorted(entries, key=lambda entry: entry[0]):
|
||||
prompts.append(prompt)
|
||||
backfilled_users: dict[int, list[dict[str, Any]]] = {}
|
||||
for ordinal, _, user in entries:
|
||||
if user is not None:
|
||||
backfilled_users[ordinal] = user
|
||||
return _PromptView(tuple(prompts), backfilled_users, needs_canonical)
|
||||
backfilled_users.setdefault(ordinal, []).append(user)
|
||||
order: dict[tuple[int, str], int] = {}
|
||||
plan: dict[int, list[tuple[int, dict[str, Any]]]] = {}
|
||||
for ordinal, records in chunk.turns.items():
|
||||
users = backfilled_users.get(ordinal, [])
|
||||
recovered_ids = {_client_projection_event_id(user) for user in users}
|
||||
for user in users:
|
||||
records = _with_backfilled_user(records, user)
|
||||
next_anchor = 2**63 - 1
|
||||
reverse_plan: list[tuple[int, dict[str, Any]]] = []
|
||||
for position in range(len(records) - 1, -1, -1):
|
||||
record = records[position]
|
||||
identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY, "")
|
||||
if identity.startswith(f"turn:{ordinal}:record:"):
|
||||
next_anchor = int(identity.rsplit(":", 1)[1])
|
||||
if record.get("event") == "user":
|
||||
event_id = _client_projection_event_id(record)
|
||||
order[(ordinal, event_id)] = position
|
||||
if event_id in recovered_ids:
|
||||
reverse_plan.append((next_anchor, record))
|
||||
if reverse_plan:
|
||||
plan[ordinal] = list(reversed(reverse_plan))
|
||||
entries.sort(key=lambda entry: (entry[0], order.get((entry[0], entry[1]["id"]), 0)))
|
||||
return _PromptView(tuple(prompt for _, prompt, _ in entries), plan, needs_canonical)
|
||||
|
||||
|
||||
def build_prompt_index(
|
||||
|
||||
Reference in new issue
Block a user