Files
DeepTutor/deeptutor/core/stream.py
Bingxi Zhao (Frank) e3a351a488 refactor(guided-learning): post-merge hardening of #500
Security/correctness:
- Stop leaking diagnostic answers: persist a _sanitize_diagnostic() snapshot
  (drops top-level answers + inline answer keys) into progress.diagnostic,
  which is returned verbatim by the /progress endpoints. Grading is unaffected
  (authoritative answers live in LearningStore).
- _safe_json_parse + generate_from_notebook now use the shared fence-stripping
  parse_json_response instead of bare json.loads, so the common fenced/lightly
  -malformed LLM output is recovered instead of silently dropped / 500'd.

Decoupling:
- unified_ws change_module: move module lookup + PRETEST reset into
  LearningService.switch_module(); router keeps only the WS ordering
  (module_changed before cancel) and no longer imports learning.models.
- unified_ws check_active_turn: use new public TurnRuntimeManager
  .has_live_execution() instead of reaching into _lock/_executions.
- redo endpoint: LearningStore.clear_questions() instead of poking _questions_path.
- remove unused StreamEventType.USER_INPUT enum; document the WS message types.

Stability:
- LearningStore: question read-modify-write (save_question_answers/_meta),
  delete(), and clear_questions() now hold _cas_lock — consistent concurrency
  model; _atomic_write_text cleans up its temp file on failure.

Cleanliness/clarity:
- router: shared _validate_book_id() (9 endpoints) + _parse_modules()
  (init/replace); _classify_error drops unused expected_answer param.
- guided_learning: hoist logging/RAGService imports + module logger; move tuning
  constants to class top; ContextVar declared after imports.
- storage: hoist json import (7 inline copies removed).
- pocketbase_store: move _VALID_ID/_validate_id below the import block.
- rename misleading mastered_pct -> avg_mastery_pct (service + web consumers).

Frontend:
- learning [bookId] page uses lib fetchProgress (apiFetch -> auth redirect)
  instead of a raw credentials fetch; track/clear the retry + auto-advance
  timers on unmount; drop dead currentStage state + ModuleTree prop.
- learning-api: remove orphaned submitAnswer + AnswerRequest.
- CreateModuleDialog: use the static bookApi import; reset manualBookId to ''
  to match initial state; learning list page: stop shadowing the t() translator.

Conflict-resolution carryover: dropped the PR's incidental 300s factory timeout
(kept dev's stream runner).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-29 14:28:32 +08:00

73 lines
2.0 KiB
Python

"""
Stream Event Protocol
=====================
Defines the unified streaming event format used by all tools, capabilities,
and plugins to communicate progress and results to consumers (CLI, WebSocket, SDK).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
import time
from typing import Any
class StreamEventType(str, Enum):
"""All possible event types in a streaming session."""
STAGE_START = "stage_start"
STAGE_END = "stage_end"
THINKING = "thinking"
OBSERVATION = "observation"
CONTENT = "content"
TOOL_CALL = "tool_call"
TOOL_RESULT = "tool_result"
PROGRESS = "progress"
SOURCES = "sources"
RESULT = "result"
ERROR = "error"
SESSION = "session"
SESSION_META = "session_meta"
DONE = "done"
WAIT_FOR_INPUT = "wait_for_input"
@dataclass
class StreamEvent:
"""
A single streaming event emitted during a chat turn.
Attributes:
type: The semantic kind of this event.
source: Which tool / capability / plugin produced it (e.g. "deep_solve").
stage: Current stage within the source (e.g. "planning").
content: Human-readable text payload.
metadata: Arbitrary structured data (tool args, sources, metrics, …).
timestamp: Unix epoch seconds when the event was created.
"""
type: StreamEventType
source: str = ""
stage: str = ""
content: str = ""
metadata: dict[str, Any] = field(default_factory=dict)
session_id: str = ""
turn_id: str = ""
seq: int = 0
timestamp: float = field(default_factory=time.time)
def to_dict(self) -> dict[str, Any]:
return {
"type": self.type.value,
"source": self.source,
"stage": self.stage,
"content": self.content,
"metadata": self.metadata,
"session_id": self.session_id,
"turn_id": self.turn_id,
"seq": self.seq,
"timestamp": self.timestamp,
}