Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
feat: agentic Inquire (opt-in beta) - ReAct tool loop with scoped search/list/read tools, per-user summaries/notes availability toggles, live activity timeline with citations, history compaction with memory divider, native tool calling with prompted-JSON fallback and legacy pipeline fallback
Murtaza Nasircdb37f7a097f
diff --git a/config/env.asr.example b/config/env.asr.exampleindex 6b36d0ff..2004e98c 100644--- a/config/env.asr.example+++ b/config/env.asr.example@@ -205,6 +205,27 @@ ADMIN_PASSWORD=changeme# Requires additional dependencies (already included in Docker image)ENABLE_INQUIRE_MODE=false+# Agentic Inquire (opt-in beta). Replaces the single-shot Inquire pipeline+# with a tool-using agent that can search, list and read your recordings+# iteratively before answering, with live activity shown in the UI.+# Requires ENABLE_INQUIRE_MODE=true. Falls back to the classic pipeline on+# any agent failure.+# ENABLE_INQUIRE_AGENT=false+# Tool-calling mode: auto (probe native, fall back to prompted JSON),+# native, or prompt. Default: auto.+# INQUIRE_AGENT_TOOL_MODE=auto+# Loop limits (defaults shown): max tool steps per answer, per-tool-result+# token cap, wall-clock cap, and the conversation context budget that+# triggers history compaction.+# INQUIRE_AGENT_MAX_STEPS=8+# INQUIRE_AGENT_TOOL_RESULT_TOKENS=4000+# INQUIRE_AGENT_TIMEOUT_SECONDS=120+# INQUIRE_CONTEXT_BUDGET_TOKENS=24000+# Defaults for the per-user content availability toggles (users override in+# Account settings; transcripts are always available):+# INQUIRE_DEFAULT_ALLOW_SUMMARIES=true+# INQUIRE_DEFAULT_ALLOW_NOTES=false+# Embedding model for Inquire-mode semantic search.# Default is a local sentence-transformers model (no API needed).# EMBEDDING_MODEL=all-MiniLM-L6-v2diff --git a/config/env.transcription.example b/config/env.transcription.exampleindex d8e3a31c..f55c767b 100644--- a/config/env.transcription.example+++ b/config/env.transcription.example@@ -374,6 +374,27 @@ AUDIO_BITRATE=128k# --- Inquire Mode (AI search across all recordings) ---ENABLE_INQUIRE_MODE=false+# Agentic Inquire (opt-in beta). Replaces the single-shot Inquire pipeline+# with a tool-using agent that can search, list and read your recordings+# iteratively before answering, with live activity shown in the UI.+# Requires ENABLE_INQUIRE_MODE=true. Falls back to the classic pipeline on+# any agent failure.+# ENABLE_INQUIRE_AGENT=false+# Tool-calling mode: auto (probe native, fall back to prompted JSON),+# native, or prompt. Default: auto.+# INQUIRE_AGENT_TOOL_MODE=auto+# Loop limits (defaults shown): max tool steps per answer, per-tool-result+# token cap, wall-clock cap, and the conversation context budget that+# triggers history compaction.+# INQUIRE_AGENT_MAX_STEPS=8+# INQUIRE_AGENT_TOOL_RESULT_TOKENS=4000+# INQUIRE_AGENT_TIMEOUT_SECONDS=120+# INQUIRE_CONTEXT_BUDGET_TOKENS=24000+# Defaults for the per-user content availability toggles (users override in+# Account settings; transcripts are always available):+# INQUIRE_DEFAULT_ALLOW_SUMMARIES=true+# INQUIRE_DEFAULT_ALLOW_NOTES=false+# Embedding model for Inquire-mode semantic search.# Default is a local sentence-transformers model (no API needed).# EMBEDDING_MODEL=all-MiniLM-L6-v2diff --git a/config/env.whisper.example b/config/env.whisper.exampleindex 19733981..379cb30c 100644--- a/config/env.whisper.example+++ b/config/env.whisper.example@@ -201,6 +201,27 @@ ADMIN_PASSWORD=changeme# Requires additional dependencies (already included in Docker image)ENABLE_INQUIRE_MODE=false+# Agentic Inquire (opt-in beta). Replaces the single-shot Inquire pipeline+# with a tool-using agent that can search, list and read your recordings+# iteratively before answering, with live activity shown in the UI.+# Requires ENABLE_INQUIRE_MODE=true. Falls back to the classic pipeline on+# any agent failure.+# ENABLE_INQUIRE_AGENT=false+# Tool-calling mode: auto (probe native, fall back to prompted JSON),+# native, or prompt. Default: auto.+# INQUIRE_AGENT_TOOL_MODE=auto+# Loop limits (defaults shown): max tool steps per answer, per-tool-result+# token cap, wall-clock cap, and the conversation context budget that+# triggers history compaction.+# INQUIRE_AGENT_MAX_STEPS=8+# INQUIRE_AGENT_TOOL_RESULT_TOKENS=4000+# INQUIRE_AGENT_TIMEOUT_SECONDS=120+# INQUIRE_CONTEXT_BUDGET_TOKENS=24000+# Defaults for the per-user content availability toggles (users override in+# Account settings; transcripts are always available):+# INQUIRE_DEFAULT_ALLOW_SUMMARIES=true+# INQUIRE_DEFAULT_ALLOW_NOTES=false+# Embedding model for Inquire-mode semantic search.# Default is a local sentence-transformers model (no API needed).# EMBEDDING_MODEL=all-MiniLM-L6-v2diff --git a/config/env.whisperx.example b/config/env.whisperx.exampleindex 560a536e..ba16794b 100644--- a/config/env.whisperx.example+++ b/config/env.whisperx.example@@ -146,6 +146,27 @@ ADMIN_PASSWORD=changeme# Requires additional dependencies (already included in Docker image)ENABLE_INQUIRE_MODE=false+# Agentic Inquire (opt-in beta). Replaces the single-shot Inquire pipeline+# with a tool-using agent that can search, list and read your recordings+# iteratively before answering, with live activity shown in the UI.+# Requires ENABLE_INQUIRE_MODE=true. Falls back to the classic pipeline on+# any agent failure.+# ENABLE_INQUIRE_AGENT=false+# Tool-calling mode: auto (probe native, fall back to prompted JSON),+# native, or prompt. Default: auto.+# INQUIRE_AGENT_TOOL_MODE=auto+# Loop limits (defaults shown): max tool steps per answer, per-tool-result+# token cap, wall-clock cap, and the conversation context budget that+# triggers history compaction.+# INQUIRE_AGENT_MAX_STEPS=8+# INQUIRE_AGENT_TOOL_RESULT_TOKENS=4000+# INQUIRE_AGENT_TIMEOUT_SECONDS=120+# INQUIRE_CONTEXT_BUDGET_TOKENS=24000+# Defaults for the per-user content availability toggles (users override in+# Account settings; transcripts are always available):+# INQUIRE_DEFAULT_ALLOW_SUMMARIES=true+# INQUIRE_DEFAULT_ALLOW_NOTES=false+# --- Automated File Processing (Black Hole Directory) ---# Set to "true" to enable automated file processingENABLE_AUTO_PROCESSING=falsediff --git a/docs/user-guide/inquire-mode.md b/docs/user-guide/inquire-mode.mdindex c4c09394..b287800c 100644--- a/docs/user-guide/inquire-mode.md+++ b/docs/user-guide/inquire-mode.md@@ -80,6 +80,16 @@ The system processes recordings in chunks, allowing it to search through even vePerformance scales well with proper setup. The initial indexing of recordings happens automatically after transcription, and subsequent searches leverage this pre-computed index. Response times typically range from a few seconds for focused searches to slightly longer for complex queries across large libraries.+## Agentic Inquire (Beta)++Administrators can enable an agentic mode with `ENABLE_INQUIRE_AGENT=true` (requires Inquire Mode to be enabled). Instead of a single retrieval pass, an AI agent works iteratively: it searches your transcripts, lists recordings, and reads transcripts, summaries, or notes as needed, thinking between steps until it can answer. The interface shows each step live (what was searched, what was read, how many matches), a Stop button to interrupt, and a collapsed activity line on every answer so you can always see how a conclusion was reached. Answers cite their sources as links back to the recordings they came from.++The agent respects your privacy settings. Under Account, the Inquire Privacy section controls what the agent may read: transcripts are always available (they are the minimum for Inquire to function), summaries are optional and on by default, and your notes are optional and off by default. A disabled content type is removed from the agent's toolbox entirely. Only your own notes are ever used, never notes on recordings shared with you. The active filter selection is a hard boundary: the agent can narrow its search within your filters but can never reach recordings outside them.++Long conversations are handled automatically. When the conversation grows past the context budget, older turns are folded into a summary the assistant keeps; a divider appears in the chat where this happened, and clicking it shows exactly what the assistant still remembers. A small meter next to the input shows how full the context is once it passes the halfway point.++Agentic answers involve several model calls per question, so they take longer (typically ten to thirty seconds for multi-step questions) and consume more tokens than the classic pipeline. Usage is tracked separately in the admin dashboard under the `inquire_agent` operation type. The agent works with any OpenAI-compatible endpoint: it uses native tool calling when the endpoint supports it and falls back to a prompted protocol when it does not. If the agent fails for any reason, the classic single-shot pipeline answers instead. See `config/env.transcription.example` for the tuning variables (step limits, timeouts, context budget, and availability defaults).+## Making the Most of Inquire ModeTo maximize the value of Inquire Mode, maintain good recording hygiene. Ensure your recordings have clear audio quality for accurate transcription, use speaker identification to track who said what, and apply consistent tags to organize your content. The better your input data, the more powerful your searches become.diff --git a/src/api/auth.py b/src/api/auth.pyindex 36abe585..5216bc87 100644--- a/src/api/auth.py+++ b/src/api/auth.py@@ -657,6 +657,12 @@ def account():current_user.summary_prompt = summary_prompt_text if summary_prompt_text else None# Handle event extraction settingcurrent_user.extract_events = 'extract_events' in request.form+ # Inquire content availability (agentic inquire). Gated on the+ # marker field so form submissions without this section cannot+ # clobber the settings (same reasoning as audio_player_position).+ if 'inquire_privacy_section' in request.form:+ current_user.inquire_allow_summaries = 'inquire_allow_summaries' in request.form+ current_user.inquire_allow_notes = 'inquire_allow_notes' in request.form# Handle transcription hintshotwords = request.form.get('transcription_hotwords')current_user.transcription_hotwords = hotwords if hotwords else None@@ -796,6 +802,9 @@ def account():# Get user's UI language preferenceuser_language = current_user.ui_language if current_user.ui_language else 'en'+ from src.services.inquire_agent import get_availability as _get_inquire_availability+ _inquire_availability = _get_inquire_availability(current_user)+return render_template('account.html',title='Account',default_summary_prompt_text=default_summary_prompt_text,@@ -821,6 +830,8 @@ def account():auto_speaker_labelling_threshold=current_user.auto_speaker_labelling_threshold or 'medium',admin_disabled_auto_summarization=admin_disabled_auto_summarization,auto_summarization=current_user.auto_summarization if current_user.auto_summarization is not None else True,+ inquire_allow_summaries=_inquire_availability['summaries'],+ inquire_allow_notes=_inquire_availability['notes'],user_language=user_language,enable_auto_export=ENABLE_AUTO_EXPORT,enable_auto_processing=os.environ.get('ENABLE_AUTO_PROCESSING', 'false').lower() == 'true')diff --git a/src/api/inquire.py b/src/api/inquire.pyindex a9a00f36..1b298288 100644--- a/src/api/inquire.py+++ b/src/api/inquire.py@@ -811,8 +811,26 @@ Order your response with notes from the most recent meetings first. Always use pfinally:ctx.pop()+ # Agentic mode (opt-in beta, ENABLE_INQUIRE_AGENT): a ReAct-style tool+ # loop replaces the single-shot pipeline. The legacy generator is+ # passed as fallback so a failing agent never breaks Inquire.+ from src.services.inquire_agent import agent_enabled, run_inquire_agent+ if agent_enabled():+ user_ctx = {+ 'name': user_name,+ 'title': user_title,+ 'company': user_company,+ 'output_language': user_output_language,+ }+ agent_gen = run_inquire_agent(+ app, user_id, user_ctx, user_message, message_history,+ data.get('conversation_memory'), filters,+ legacy_fallback=generate_enhanced_chat,+ )+ return Response(agent_gen, mimetype='text/event-stream')+return Response(generate_enhanced_chat(), mimetype='text/event-stream')-+except Exception as e:current_app.logger.error(f"Error in inquire chat endpoint: {str(e)}")return jsonify({'error': str(e)}), 500diff --git a/src/init_db.py b/src/init_db.pyindex 1b37d4a5..44c72588 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -404,6 +404,13 @@ def initialize_database(app):# Configurable auto-export filenames (#348)if add_column_if_not_exists(engine, 'user', 'export_filename_template', 'VARCHAR(500)'):app.logger.info("Added export_filename_template column to user table")++ # Inquire content availability toggles (agentic inquire). Nullable on+ # purpose: NULL means "use the admin env default".+ if add_column_if_not_exists(engine, 'user', 'inquire_allow_summaries', 'BOOLEAN'):+ app.logger.info("Added inquire_allow_summaries column to user table")+ if add_column_if_not_exists(engine, 'user', 'inquire_allow_notes', 'BOOLEAN'):+ app.logger.info("Added inquire_allow_notes column to user table")if add_column_if_not_exists(engine, 'recording', 'export_filename', 'VARCHAR(500)'):app.logger.info("Added export_filename column to recording table")diff --git a/src/models/user.py b/src/models/user.pyindex 47b2e210..f181e5c6 100644--- a/src/models/user.py+++ b/src/models/user.py@@ -28,6 +28,11 @@ class User(db.Model, UserMixin):ui_language = db.Column(db.String(10), nullable=True, default='en') # For UI language preference (en, es, fr, zh)summary_prompt = db.Column(db.Text, nullable=True)extract_events = db.Column(db.Boolean, default=False) # Enable event extraction from transcripts+ # Inquire content availability (agentic inquire). Transcripts are always+ # available; summaries/notes are optional. NULL = use the admin env+ # default (INQUIRE_DEFAULT_ALLOW_SUMMARIES=true / INQUIRE_DEFAULT_ALLOW_NOTES=false).+ inquire_allow_summaries = db.Column(db.Boolean, nullable=True)+ inquire_allow_notes = db.Column(db.Boolean, nullable=True)name = db.Column(db.String(100), nullable=True)job_title = db.Column(db.String(100), nullable=True)company = db.Column(db.String(100), nullable=True)diff --git a/src/services/inquire_agent.py b/src/services/inquire_agent.pynew file mode 100644index 00000000..26a209e4--- /dev/null+++ b/src/services/inquire_agent.py@@ -0,0 +1,1022 @@+"""Agentic Inquire: a ReAct-style tool loop over the user's recordings.++Replaces the single-shot RAG pipeline (router -> enrich -> one retrieval ->+answer) with an iterative agent that can search transcripts, browse recording+metadata, and read transcripts/summaries/notes until it can answer, then+streams the answer. See temp/design_inquire_agent.md for the full design.++Key properties:+- Every tool is scoped to the requesting user's ACLs AND the UI filter set+ (the agent can narrow within the filters, never escape them).+- Content availability is structural: a disabled content type's tool is not+ in the schema at all. Notes are only ever the user's OWN notes.+- Two tool-invocation modes: native OpenAI function calling, and a+ prompted-JSON fallback for endpoints without tool support. `auto` probes+ native once per (base_url, model) and remembers.+- Hard budgets: max steps, per-tool-result token cap, wall-clock cap, and the+ existing per-user token budget (checked by call_chat_completion each step).+- On failure before any answer content, falls back to the caller-provided+ legacy pipeline so Inquire never regresses.+"""++import json+import os+import re+import time as time_mod+from datetime import datetime, time as dtime++from src.database import db+from src.models import Recording, RecordingTag, Tag, User+from src.services.embeddings import get_accessible_recording_ids, semantic_search_chunks+from src.services.llm import call_chat_completion, TokenBudgetExceeded, get_chat_config++# ---------------------------------------------------------------------------+# Configuration (read live so tests and admins can tweak without restart)+# ---------------------------------------------------------------------------++def _env_int(name, default):+ try:+ return int(os.environ.get(name, default))+ except (TypeError, ValueError):+ return default+++def _env_bool(name, default):+ raw = os.environ.get(name)+ if raw is None:+ return default+ return str(raw).strip().lower() in ('true', '1', 'yes')+++def agent_enabled():+ return _env_bool('ENABLE_INQUIRE_AGENT', False)+++def _max_steps():+ return max(1, _env_int('INQUIRE_AGENT_MAX_STEPS', 8))+++def _tool_result_token_cap():+ return max(500, _env_int('INQUIRE_AGENT_TOOL_RESULT_TOKENS', 4000))+++def _timeout_seconds():+ return max(15, _env_int('INQUIRE_AGENT_TIMEOUT_SECONDS', 120))+++def _context_budget_tokens():+ return max(4000, _env_int('INQUIRE_CONTEXT_BUDGET_TOKENS', 24000))+++def _tool_mode():+ mode = os.environ.get('INQUIRE_AGENT_TOOL_MODE', 'auto').strip().lower()+ return mode if mode in ('auto', 'native', 'prompt') else 'auto'+++# Remembers, per (base_url, model), whether native tool calling works, so+# `auto` mode only pays the probe once per process lifetime.+_NATIVE_TOOLS_SUPPORTED = {}+++def _estimate_tokens(text):+ """Cheap char/4 heuristic; no tokenizer dependency."""+ return len(text) // 4 if text else 0+++# ---------------------------------------------------------------------------+# Availability (decision: transcripts always on; summaries/notes optional)+# ---------------------------------------------------------------------------++def get_availability(user):+ """Effective content availability for a user.++ A NULL column means "use the admin default" so changing the env default+ later affects users who never made an explicit choice.+ """+ allow_summaries = getattr(user, 'inquire_allow_summaries', None)+ if allow_summaries is None:+ allow_summaries = _env_bool('INQUIRE_DEFAULT_ALLOW_SUMMARIES', True)+ allow_notes = getattr(user, 'inquire_allow_notes', None)+ if allow_notes is None:+ allow_notes = _env_bool('INQUIRE_DEFAULT_ALLOW_NOTES', False)+ return {'summaries': bool(allow_summaries), 'notes': bool(allow_notes)}+++# ---------------------------------------------------------------------------+# Scope: the set of recording ids the agent may touch this request+# ---------------------------------------------------------------------------++def resolve_allowed_recording_ids(user_id, filters):+ """Accessible recordings intersected with the UI filter set.++ Mirrors the filter semantics of semantic_search_chunks so search results+ and direct reads can never disagree about what is in scope.+ """+ accessible = set(get_accessible_recording_ids(user_id))+ if not accessible:+ return set()++ q = db.session.query(Recording.id).filter(Recording.id.in_(accessible))+ filters = filters or {}++ if filters.get('recording_ids'):+ q = q.filter(Recording.id.in_(filters['recording_ids']))+ if filters.get('tag_ids'):+ q = q.join(RecordingTag, Recording.id == RecordingTag.recording_id) \+ .filter(RecordingTag.tag_id.in_(filters['tag_ids']))+ if filters.get('speaker_names'):+ q = q.filter(db.or_(*[+ Recording.participants.ilike(f'%{name}%')+ for name in filters['speaker_names']+ ]))+ if filters.get('date_from'):+ q = q.filter(Recording.meeting_date >= datetime.combine(filters['date_from'], dtime.min))+ if filters.get('date_to'):+ q = q.filter(Recording.meeting_date <= datetime.combine(filters['date_to'], dtime.max))++ return {row[0] for row in q.all()}+++# ---------------------------------------------------------------------------+# Tools+# ---------------------------------------------------------------------------++def _truncate_to_tokens(text, cap_tokens, pagination_hint=None):+ """Cap tool output; tell the model what was cut and how to get more."""+ cap_chars = cap_tokens * 4+ if len(text) <= cap_chars:+ return text+ marker = f"\n\n[TRUNCATED: output exceeded {cap_tokens} tokens."+ if pagination_hint:+ marker += f" {pagination_hint}"+ marker += "]"+ return text[:cap_chars] + marker+++def _recording_brief(rec):+ d = {+ 'recording_id': rec.id,+ 'title': rec.title or 'Untitled Recording',+ 'has_transcript': bool(rec.transcription),+ 'has_summary': bool(rec.summary),+ 'has_notes': bool(rec.notes),+ }+ if rec.meeting_date:+ d['meeting_date'] = rec.meeting_date.strftime('%Y-%m-%d %H:%M')+ if rec.participants:+ d['participants'] = rec.participants+ if rec.audio_duration_seconds:+ d['duration_seconds'] = int(rec.audio_duration_seconds)+ return d+++def _parse_transcript_segments(transcription):+ """Return (segments, is_json). Segment: {speaker, text, start_time}."""+ if not transcription:+ return [], False+ try:+ data = json.loads(transcription)+ if isinstance(data, list):+ segments = []+ for seg in data:+ if isinstance(seg, dict):+ segments.append({+ 'speaker': seg.get('speaker'),+ 'text': seg.get('sentence') or seg.get('text') or '',+ 'start_time': seg.get('start_time'),+ })+ return segments, True+ except (ValueError, TypeError):+ pass+ return [], False+++def _fmt_time(seconds):+ if seconds is None:+ return None+ seconds = int(seconds)+ return f"{seconds // 60}:{seconds % 60:02d}"+++class ToolContext:+ """Everything a tool needs, resolved once per request."""++ def __init__(self, user_id, filters, allowed_ids, availability):+ self.user_id = user_id+ self.filters = filters or {}+ self.allowed_ids = allowed_ids+ self.availability = availability++ def check_scope(self, recording_id):+ try:+ recording_id = int(recording_id)+ except (TypeError, ValueError):+ return None, "recording_id must be an integer"+ if recording_id not in self.allowed_ids:+ return None, (f"Recording {recording_id} is not available "+ "(it does not exist, you lack access, or it is outside the active filters)")+ rec = db.session.get(Recording, recording_id)+ if not rec:+ return None, f"Recording {recording_id} not found"+ return rec, None+++def tool_search_transcripts(ctx, args):+ query = (args.get('query') or '').strip()+ if not query:+ return {'error': "query is required"}+ top_k = min(max(int(args.get('top_k', 8) or 8), 1), 20)++ # Narrow within the UI filters: tool args can only tighten, never widen.+ filters = dict(ctx.filters)+ filters['recording_ids'] = list(ctx.allowed_ids)+ if args.get('speakers'):+ filters['speaker_names'] = [str(s) for s in args['speakers']][:10]+ for key, arg in (('date_from', 'date_from'), ('date_to', 'date_to')):+ if args.get(arg):+ try:+ parsed = datetime.fromisoformat(str(args[arg])).date()+ base = filters.get(key)+ # intersect with the UI date range+ if key == 'date_from':+ filters[key] = max(base, parsed) if base else parsed+ else:+ filters[key] = min(base, parsed) if base else parsed+ except ValueError:+ return {'error': f"{arg} must be an ISO date (YYYY-MM-DD)"}++ results = semantic_search_chunks(ctx.user_id, query, filters, top_k)+ hits = []+ for chunk, similarity in results:+ if not chunk or not chunk.recording or chunk.recording_id not in ctx.allowed_ids:+ continue+ hits.append({+ 'recording_id': chunk.recording_id,+ 'title': chunk.recording.title or 'Untitled Recording',+ 'meeting_date': chunk.recording.meeting_date.strftime('%Y-%m-%d') if chunk.recording.meeting_date else None,+ 'speaker': chunk.speaker_name,+ 'time': _fmt_time(chunk.start_time),+ 'chunk_index': chunk.chunk_index,+ 'snippet': chunk.content,+ 'similarity': round(float(similarity), 3),+ })+ return {'query': query, 'result_count': len(hits), 'results': hits}+++def tool_list_recordings(ctx, args):+ q = Recording.query.filter(Recording.id.in_(ctx.allowed_ids))+ if args.get('participant'):+ q = q.filter(Recording.participants.ilike(f"%{args['participant']}%"))+ for arg, op in (('date_from', 'ge'), ('date_to', 'le')):+ if args.get(arg):+ try:+ parsed = datetime.fromisoformat(str(args[arg]))+ except ValueError:+ return {'error': f"{arg} must be an ISO date (YYYY-MM-DD)"}+ if op == 'ge':+ q = q.filter(Recording.meeting_date >= parsed)+ else:+ q = q.filter(Recording.meeting_date <= datetime.combine(parsed.date(), dtime.max))+ sort = args.get('sort', 'newest')+ q = q.order_by(Recording.meeting_date.asc() if sort == 'oldest' else Recording.meeting_date.desc())+ limit = min(max(int(args.get('limit', 25) or 25), 1), 100)+ total = q.count()+ recs = q.limit(limit).all()+ return {+ 'total_in_scope': total,+ 'returned': len(recs),+ 'recordings': [_recording_brief(r) for r in recs],+ }+++DEFAULT_TRANSCRIPT_PAGE = 150+++def tool_get_transcript(ctx, args):+ rec, err = ctx.check_scope(args.get('recording_id'))+ if err:+ return {'error': err}+ if not rec.transcription:+ return {'error': f"Recording {rec.id} has no transcript"}++ offset = max(int(args.get('offset', 0) or 0), 0)+ limit = min(max(int(args.get('limit', DEFAULT_TRANSCRIPT_PAGE) or DEFAULT_TRANSCRIPT_PAGE), 1), 400)++ segments, is_json = _parse_transcript_segments(rec.transcription)+ if is_json:+ window = segments[offset:offset + limit]+ lines = []+ for seg in window:+ prefix = f"{seg['speaker']}: " if seg.get('speaker') else ''+ t = _fmt_time(seg.get('start_time'))+ suffix = f" [{t}]" if t else ''+ lines.append(f"{prefix}{seg['text']}{suffix}")+ return {+ 'recording_id': rec.id,+ 'title': rec.title,+ 'total_segments': len(segments),+ 'offset': offset,+ 'returned_segments': len(window),+ 'next_offset': offset + limit if offset + limit < len(segments) else None,+ 'transcript': "\n".join(lines),+ }++ # Plain-text transcript: character-window pagination.+ page_chars = limit * 200+ text = rec.transcription+ window = text[offset:offset + page_chars]+ return {+ 'recording_id': rec.id,+ 'title': rec.title,+ 'total_chars': len(text),+ 'offset': offset,+ 'next_offset': offset + page_chars if offset + page_chars < len(text) else None,+ 'transcript': window,+ 'note': 'Plain-text transcript; offset/limit are character-based here (limit unit = 200 chars).',+ }+++def tool_get_summary(ctx, args):+ rec, err = ctx.check_scope(args.get('recording_id'))+ if err:+ return {'error': err}+ if not rec.summary:+ return {'error': f"Recording {rec.id} has no summary"}+ return {'recording_id': rec.id, 'title': rec.title, 'summary': rec.summary}+++def tool_get_notes(ctx, args):+ rec, err = ctx.check_scope(args.get('recording_id'))+ if err:+ return {'error': err}+ # Decision (2026-08-28): only the user's OWN notes, never notes on+ # recordings shared with them, regardless of toggles.+ if rec.user_id != ctx.user_id:+ return {'error': "Notes are only available on your own recordings"}+ if not rec.notes:+ return {'error': f"Recording {rec.id} has no notes"}+ return {'recording_id': rec.id, 'title': rec.title, 'notes': rec.notes}+++def tool_get_recording_metadata(ctx, args):+ rec, err = ctx.check_scope(args.get('recording_id'))+ if err:+ return {'error': err}+ info = _recording_brief(rec)+ try:+ info['tags'] = [t.name for t in rec.tags]+ except Exception:+ pass+ return info+++_DATE_PROPS = {+ 'date_from': {'type': 'string', 'description': 'ISO date YYYY-MM-DD (inclusive)'},+ 'date_to': {'type': 'string', 'description': 'ISO date YYYY-MM-DD (inclusive)'},+}+++def build_toolbox(availability):+ """(schemas, executors) for the enabled tools only.++ Disabled content types are omitted from the schema entirely — the model+ never sees a tool it is not allowed to use.+ """+ tools = [+ ('search_transcripts', tool_search_transcripts,+ 'Semantic search across the transcripts of the recordings in scope. '+ 'Returns matching snippets with recording ids, titles, speakers and timestamps. '+ 'Use short, content-bearing queries; call multiple times with different phrasings if needed.',+ {'type': 'object',+ 'properties': {+ 'query': {'type': 'string', 'description': 'Search phrase'},+ 'top_k': {'type': 'integer', 'description': 'Max results, 1-20 (default 8)'},+ 'speakers': {'type': 'array', 'items': {'type': 'string'},+ 'description': 'Restrict to recordings whose participants include these names'},+ **_DATE_PROPS,+ },+ 'required': ['query']}),+ ('list_recordings', tool_list_recordings,+ 'List the recordings in scope with their metadata (title, date, participants, duration, '+ 'which artifacts exist). Use this to survey what is available or find a recording by date/participant.',+ {'type': 'object',+ 'properties': {+ 'sort': {'type': 'string', 'enum': ['newest', 'oldest']},+ 'limit': {'type': 'integer', 'description': 'Max rows, 1-100 (default 25)'},+ 'participant': {'type': 'string', 'description': 'Only recordings whose participants include this name'},+ **_DATE_PROPS,+ }}),+ ('get_transcript', tool_get_transcript,+ 'Read a window of a recording\'s full transcript, in order. Paginated: the result reports '+ 'total_segments and next_offset; call again with offset=next_offset to continue.',+ {'type': 'object',+ 'properties': {+ 'recording_id': {'type': 'integer'},+ 'offset': {'type': 'integer', 'description': 'Segment offset to start from (default 0)'},+ 'limit': {'type': 'integer', 'description': f'Segments to return (default {DEFAULT_TRANSCRIPT_PAGE}, max 400)'},+ },+ 'required': ['recording_id']}),+ ('get_recording_metadata', tool_get_recording_metadata,+ 'Get one recording\'s metadata: title, date, participants, duration, tags, which artifacts exist.',+ {'type': 'object',+ 'properties': {'recording_id': {'type': 'integer'}},+ 'required': ['recording_id']}),+ ]+ if availability.get('summaries'):+ tools.append((+ 'get_summary', tool_get_summary,+ 'Read the stored AI summary of one recording. Cheap way to survey a long recording before '+ 'deciding whether to read its transcript.',+ {'type': 'object',+ 'properties': {'recording_id': {'type': 'integer'}},+ 'required': ['recording_id']}))+ if availability.get('notes'):+ tools.append((+ 'get_notes', tool_get_notes,+ 'Read the user\'s own notes on one recording (only available on recordings they own).',+ {'type': 'object',+ 'properties': {'recording_id': {'type': 'integer'}},+ 'required': ['recording_id']}))++ schemas = [{'type': 'function',+ 'function': {'name': name, 'description': desc, 'parameters': params}}+ for name, _fn, desc, params in tools]+ executors = {name: fn for name, fn, _d, _p in tools}+ return schemas, executors+++# Human-readable activity lines for the UI. (label, detail) builders.+_TOOL_ICONS = {+ 'search_transcripts': 'fa-magnifying-glass',+ 'list_recordings': 'fa-list',+ 'get_transcript': 'fa-file-lines',+ 'get_summary': 'fa-file-alt',+ 'get_notes': 'fa-note-sticky',+ 'get_recording_metadata': 'fa-circle-info',+}+++def _activity_label(tool, args):+ if tool == 'search_transcripts':+ return f"Searching: “{str(args.get('query', ''))[:80]}”"+ if tool == 'list_recordings':+ return "Scanning recordings"+ if tool == 'get_transcript':+ off = args.get('offset') or 0+ return f"Reading transcript of recording {args.get('recording_id')}" + (f" (from segment {off})" if off else "")+ if tool == 'get_summary':+ return f"Reading summary of recording {args.get('recording_id')}"+ if tool == 'get_notes':+ return f"Reading notes on recording {args.get('recording_id')}"+ if tool == 'get_recording_metadata':+ return f"Checking recording {args.get('recording_id')}"+ return f"Running {tool}"+++def _activity_result(tool, result):+ """(status, detail) once a tool has run."""+ if isinstance(result, dict) and result.get('error'):+ return 'error', str(result['error'])[:160]+ if tool == 'search_transcripts':+ n = result.get('result_count', 0)+ if not n:+ return 'empty', 'no matches'+ recs = {r['recording_id'] for r in result.get('results', [])}+ return 'done', f"{n} match{'es' if n != 1 else ''} in {len(recs)} recording{'s' if len(recs) != 1 else ''}"+ if tool == 'list_recordings':+ return 'done', f"{result.get('returned', 0)} of {result.get('total_in_scope', 0)} recordings"+ if tool == 'get_transcript':+ if 'total_segments' in result:+ got = result.get('returned_segments', 0)+ return 'done', f"{got} segments (of {result.get('total_segments', '?')}) — {result.get('title', '')}"+ return 'done', str(result.get('title', ''))+ if tool in ('get_summary', 'get_notes', 'get_recording_metadata'):+ return 'done', str(result.get('title', ''))[:120]+ return 'done', ''+++def _summary_line(tool_counts):+ names = {+ 'search_transcripts': ('search', 'searches'),+ 'list_recordings': ('listing', 'listings'),+ 'get_transcript': ('transcript read', 'transcript reads'),+ 'get_summary': ('summary read', 'summary reads'),+ 'get_notes': ('notes read', 'notes reads'),+ 'get_recording_metadata': ('metadata check', 'metadata checks'),+ }+ parts = []+ for tool, count in tool_counts.items():+ singular, plural = names.get(tool, (tool, tool))+ parts.append(f"{count} {singular if count == 1 else plural}")+ return ' · '.join(parts)+++# ---------------------------------------------------------------------------+# Prompts+# ---------------------------------------------------------------------------++def _system_prompt(user_ctx, filters_text, availability, tool_mode_prompt_block):+ language_instruction = (+ f"Respond in {user_ctx['output_language']}. " if user_ctx.get('output_language') else '')+ notes_line = "the user's own notes, " if availability.get('notes') else ''+ summaries_line = "stored summaries, " if availability.get('summaries') else ''+ return f"""You are a research assistant analyzing {user_ctx['name']}'s audio recording library \+(meetings, calls, voice notes). {user_ctx['name']} is a(n) {user_ctx['title']} at {user_ctx['company']}. \+{language_instruction}Today's date is {datetime.utcnow().strftime('%Y-%m-%d')}.++You have tools to search transcripts, list recordings, and read transcripts, {summaries_line}{notes_line}\+and metadata{filters_text}. Work iteratively: search or browse first, read more where needed, and only \+answer once you have enough evidence. Prefer summaries to survey long recordings, transcripts for exact \+quotes and details. If a search finds nothing, try different phrasings or list_recordings before giving up. \+Never invent content that is not in the tool results; say clearly when something cannot be found.++{tool_mode_prompt_block}When you give your final answer:+- Use clear markdown (headings per recording where it helps, bullets, **bold** speaker names).+- Cite sources inline as markdown links: [Recording Title](/recordings/<recording_id>) — cite the \+recording you drew each substantive point from, at most one citation per bullet or paragraph.+- Order information from the most recent recordings first unless the question implies otherwise."""+++_PROMPT_MODE_BLOCK = """TOOL CALLING PROTOCOL (this endpoint has no native tool support):+To use a tool, reply with ONLY a single JSON object, nothing else:+{"tool": "<tool_name>", "arguments": { ... }}+Available tools and their arguments are listed below. One tool call per reply.+To give your final answer, reply with the answer text directly (never start a final answer with "{").++TOOLS:+%TOOLS%++"""+++# ---------------------------------------------------------------------------+# Context assembly + compaction+# ---------------------------------------------------------------------------++KEEP_VERBATIM_MESSAGES = 8 # last 4 turns+++def sanitize_history(message_history):+ """Client history -> [{role, content}] with activity provenance folded in."""+ out = []+ for msg in message_history or []:+ if not isinstance(msg, dict):+ continue+ role = msg.get('role')+ content = msg.get('content')+ if role not in ('user', 'assistant') or not isinstance(content, str) or not content.strip():+ continue+ if role == 'assistant' and msg.get('activity'):+ content = f"{content}\n\n[research performed for this answer: {str(msg['activity'])[:300]}]"+ out.append({'role': role, 'content': content})+ return out+++def estimate_context_tokens(system_prompt, memory, history, toolbox_schemas):+ total = _estimate_tokens(system_prompt) + _estimate_tokens(memory or '')+ total += sum(_estimate_tokens(m['content']) for m in history)+ total += _estimate_tokens(json.dumps(toolbox_schemas))+ return total+++def compact_history(user_id, memory, history, keep_last=KEEP_VERBATIM_MESSAGES):+ """Fold all but the last `keep_last` messages into a rolling memory block.++ Returns (new_memory, kept_history, folded_count). Raises nothing: on any+ LLM failure it hard-truncates instead (the caller keeps going).+ """+ if len(history) <= keep_last:+ return memory, history, 0+ to_fold = history[:-keep_last]+ kept = history[-keep_last:]+ transcript = "\n\n".join(f"{m['role'].upper()}: {m['content']}" for m in to_fold)+ prompt = f"""Summarize this conversation-so-far into a compact memory block that lets an assistant \+continue the conversation seamlessly. Capture: topics discussed, questions asked and their answers (with \+any recording titles/ids referenced), decisions or conclusions, and open threads. Be dense and factual; \+under 400 words.++{"Existing memory from even earlier turns:" + chr(10) + memory + chr(10) + chr(10) if memory else ""}Conversation to fold in:+{transcript[:24000]}"""+ try:+ resp = call_chat_completion(+ messages=[{'role': 'system', 'content': 'You compress conversations into dense, factual memory blocks.'},+ {'role': 'user', 'content': prompt}],+ temperature=0.2, max_tokens=700,+ user_id=user_id, operation_type='inquire_compaction')+ new_memory = (resp.choices[0].message.content or '').strip()+ if not new_memory:+ raise ValueError('empty compaction result')+ return new_memory, kept, len(to_fold)+ except Exception:+ # Degrade to hard truncation — never block the user's question.+ marker = '[Earlier conversation truncated]'+ combined = (memory + '\n' if memory else '') + marker+ return combined, kept, len(to_fold)+++# ---------------------------------------------------------------------------+# The loop+# ---------------------------------------------------------------------------++def _sse(payload):+ return f"data: {json.dumps(payload)}\n\n"+++class _ThinkingFilter:+ """Splits streamed content into visible/thinking parts (<think> tags)."""++ _OPEN = re.compile(r'<think(?:ing)?>', re.IGNORECASE)+ _CLOSE = re.compile(r'</think(?:ing)?>', re.IGNORECASE)++ def __init__(self):+ self.buffer = ''+ self.in_thinking = False+ self.thinking = ''++ def feed(self, fragment):+ """Returns (visible_text, thinking_completed_or_None)."""+ self.buffer += fragment+ visible = ''+ thinking_out = None+ while True:+ if not self.in_thinking:+ m = self._OPEN.search(self.buffer)+ if m:+ visible += self.buffer[:m.start()]+ self.buffer = self.buffer[m.end():]+ self.in_thinking = True+ self.thinking = ''+ else:+ # Hold back a partial "<think" prefix at the tail.+ safe_len = len(self.buffer)+ tail = self.buffer[-9:]+ lt = tail.rfind('<')+ if lt != -1 and self._OPEN.match(tail[lt:]) is None and '<think'.startswith(tail[lt:lt + 6].lower()):+ safe_len = len(self.buffer) - (len(tail) - lt)+ visible += self.buffer[:safe_len]+ self.buffer = self.buffer[safe_len:]+ break+ else:+ m = self._CLOSE.search(self.buffer)+ if m:+ self.thinking += self.buffer[:m.start()]+ self.buffer = self.buffer[m.end():]+ self.in_thinking = False+ if self.thinking.strip():+ thinking_out = self.thinking.strip()+ self.thinking = ''+ else:+ hold = 10+ self.thinking += self.buffer[:-hold] if len(self.buffer) > hold else ''+ self.buffer = self.buffer[-hold:] if len(self.buffer) > hold else self.buffer+ break+ return visible, thinking_out++ def flush(self):+ if self.in_thinking:+ leftover = (self.thinking + self.buffer).strip()+ self.buffer = ''+ self.thinking = ''+ return '', (leftover or None)+ visible = self.buffer+ self.buffer = ''+ return visible, None+++def _native_tools_known_unsupported(err_text):+ err = (err_text or '').lower()+ return any(k in err for k in ('tool', 'function', 'unsupported', 'not support'))+++def run_inquire_agent(app, user_id, user_ctx, user_message, message_history,+ conversation_memory, filters, legacy_fallback=None,+ llm_call=call_chat_completion):+ """SSE generator implementing the agent loop.++ `legacy_fallback`: zero-arg generator function; invoked (yield from) if the+ agent fails before producing any answer content.+ `llm_call`: injectable for tests.+ """+ ctx = app.app_context()+ ctx.push()+ produced_answer = False+ try:+ try:+ user = db.session.get(User, user_id)+ availability = get_availability(user)+ allowed_ids = resolve_allowed_recording_ids(user_id, filters)+ schemas, executors = build_toolbox(availability)+ except Exception as e:+ app.logger.error(f"Inquire agent setup failed: {e}", exc_info=True)+ if legacy_fallback is not None:+ yield from legacy_fallback()+ return+ yield _sse({'error': str(e)})+ return++ # Filter description for the prompt+ filter_bits = []+ f = filters or {}+ if f.get('tag_ids'):+ names = [t.name for t in Tag.query.filter(Tag.id.in_(f['tag_ids'])).all()]+ filter_bits.append(f"tags: {', '.join(names)}")+ if f.get('speaker_names'):+ filter_bits.append(f"speakers: {', '.join(f['speaker_names'])}")+ if f.get('date_from') or f.get('date_to'):+ filter_bits.append(f"dates {f.get('date_from', '...')} to {f.get('date_to', '...')}")+ if f.get('recording_ids'):+ filter_bits.append(f"{len(f['recording_ids'])} selected recordings")+ filters_text = (f". The user has limited this conversation to {len(allowed_ids)} recordings "+ f"({'; '.join(filter_bits)})" if filter_bits+ else f". {len(allowed_ids)} recordings are in scope")++ # Tool mode resolution+ cfg = get_chat_config()+ mode_key = (cfg.get('base_url'), cfg.get('model_name'))+ mode = _tool_mode()+ if mode == 'auto':+ known = _NATIVE_TOOLS_SUPPORTED.get(mode_key)+ mode = 'prompt' if known is False else 'native'++ def build_messages(current_mode, memory, history):+ block = ''+ if current_mode == 'prompt':+ tool_lines = "\n".join(+ f"- {s['function']['name']}: {s['function']['description']} "+ f"Arguments schema: {json.dumps(s['function']['parameters'])}"+ for s in schemas)+ block = _PROMPT_MODE_BLOCK.replace('%TOOLS%', tool_lines)+ sys_prompt = _system_prompt(user_ctx, filters_text, availability, block)+ msgs = [{'role': 'system', 'content': sys_prompt}]+ if memory:+ msgs.append({'role': 'system',+ 'content': f"Conversation memory (earlier turns, summarized):\n{memory}"})+ msgs.extend(history)+ msgs.append({'role': 'user', 'content': user_message})+ return msgs++ history = sanitize_history(message_history)+ memory = (conversation_memory or '').strip() or None++ # Context accounting + compaction before the first call+ budget = _context_budget_tokens()+ est = estimate_context_tokens(_system_prompt(user_ctx, filters_text, availability, ''),+ memory, history, schemas)+ usage_pct = min(int(est * 100 / budget), 100)+ yield _sse({'context_usage': usage_pct})+ if est > budget * 0.6 and len(history) > KEEP_VERBATIM_MESSAGES:+ yield _sse({'status': 'compacting', 'message': 'Summarizing earlier conversation...'})+ memory, history, folded = compact_history(user_id, memory, history)+ if folded:+ yield _sse({'context_compacted': {'memory': memory, 'keep_last': KEEP_VERBATIM_MESSAGES}})++ messages = build_messages(mode, memory, history)++ tool_ctx = ToolContext(user_id, filters, allowed_ids, availability)+ started = time_mod.monotonic()+ step_id = 0+ tool_counts = {}+ call_cache = {}+ consecutive_empty_searches = 0+ answer_filter = _ThinkingFilter()++ def finish(summary_needed=True):+ events = []+ if summary_needed and tool_counts:+ events.append(_sse({'agent_summary': {+ 'steps': sum(tool_counts.values()),+ 'line': _summary_line(tool_counts)}}))+ if memory:+ events.append(_sse({'conversation_memory': memory}))+ events.append(_sse({'end_of_stream': True}))+ return events++ def execute_tool(name, raw_args):+ nonlocal step_id, consecutive_empty_searches+ step_id += 1+ this_step = step_id+ try:+ args = raw_args if isinstance(raw_args, dict) else json.loads(raw_args or '{}')+ if not isinstance(args, dict):+ args = {}+ except (ValueError, TypeError):+ args = None+ label = _activity_label(name, args or {})+ events = [_sse({'agent_step': {'id': this_step, 'tool': name,+ 'icon': _TOOL_ICONS.get(name, 'fa-gear'),+ 'label': label, 'status': 'running'}})]+ if args is None:+ result = {'error': 'arguments were not valid JSON'}+ elif name not in executors:+ result = {'error': f"Unknown tool: {name}"}+ else:+ cache_key = (name, json.dumps(args, sort_keys=True))+ if cache_key in call_cache:+ result = {'note': 'duplicate call — cached result returned; try a DIFFERENT '+ 'query or tool instead of repeating this one',+ **call_cache[cache_key]}+ else:+ try:+ result = executors[name](tool_ctx, args)+ except Exception as e:+ app.logger.warning(f"Inquire agent tool {name} failed: {e}", exc_info=True)+ result = {'error': f"tool failed: {e}"}+ call_cache[cache_key] = result+ tool_counts[name] = tool_counts.get(name, 0) + 1+ status, detail = _activity_result(name, result)+ if name == 'search_transcripts':+ consecutive_empty_searches = consecutive_empty_searches + 1 if status == 'empty' else 0+ events.append(_sse({'agent_step': {'id': this_step, 'tool': name,+ 'icon': _TOOL_ICONS.get(name, 'fa-gear'),+ 'label': label, 'status': status,+ 'detail': detail}}))+ hint = ''+ if 'transcript' in (result or {}) and result.get('next_offset') is not None:+ hint = 'Call again with offset=next_offset for more.'+ result_text = _truncate_to_tokens(json.dumps(result, ensure_ascii=False),+ _tool_result_token_cap(), hint)+ return events, result_text++ max_steps = _max_steps()+ for iteration in range(max_steps + 1):+ timed_out = (time_mod.monotonic() - started) > _timeout_seconds()+ forcing_final = iteration >= max_steps or timed_out+ if forcing_final:+ messages.append({'role': 'system',+ 'content': 'Step budget exhausted. Answer NOW with the evidence you '+ 'already gathered; state clearly what could not be verified.'})+ if consecutive_empty_searches >= 2:+ consecutive_empty_searches = 0+ messages.append({'role': 'system',+ 'content': 'Your last searches found nothing. Try substantially different '+ 'terms, or use list_recordings to see what exists, or answer '+ 'that the information does not appear in the recordings.'})++ use_tools = (mode == 'native') and not forcing_final+ try:+ if mode == 'native':+ stream = llm_call(messages=messages,+ tools=schemas if use_tools else None,+ temperature=0.4, stream=True,+ max_tokens=int(os.environ.get('CHAT_MAX_TOKENS', '2000')),+ user_id=user_id, operation_type='inquire_agent')+ else:+ response = llm_call(messages=messages, temperature=0.4,+ max_tokens=int(os.environ.get('CHAT_MAX_TOKENS', '2000')),+ user_id=user_id, operation_type='inquire_agent')+ except TokenBudgetExceeded:+ raise+ except Exception as e:+ if mode == 'native' and _tool_mode() == 'auto' and _native_tools_known_unsupported(str(e)):+ app.logger.info(f"Native tool calling unsupported by endpoint; switching to prompt mode: {e}")+ _NATIVE_TOOLS_SUPPORTED[mode_key] = False+ mode = 'prompt'+ messages = build_messages(mode, memory, history)+ continue+ raise++ if mode == 'native':+ # Consume the stream: accumulate tool calls; live-stream+ # content once it is clearly an answer (no tool deltas yet+ # and enough text), otherwise treat pre-tool content as+ # thinking.+ calls = {}+ content_buffer = ''+ streaming_live = False+ for chunk in stream:+ if not getattr(chunk, 'choices', None):+ continue+ delta = chunk.choices[0].delta+ if delta is None:+ continue+ for tc in (getattr(delta, 'tool_calls', None) or []):+ entry = calls.setdefault(tc.index, {'id': tc.id, 'name': '', 'args': ''})+ if tc.id:+ entry['id'] = tc.id+ if tc.function:+ if tc.function.name:+ entry['name'] = (entry['name'] or '') + tc.function.name+ if tc.function.arguments:+ entry['args'] += tc.function.arguments+ text = getattr(delta, 'content', None)+ if text:+ if streaming_live:+ visible, thinking = answer_filter.feed(text)+ if visible:+ produced_answer = True+ yield _sse({'delta': visible})+ if thinking:+ yield _sse({'thinking': thinking})+ else:+ content_buffer += text+ if not calls and len(content_buffer) > 200:+ streaming_live = True+ produced_answer = True+ visible, thinking = answer_filter.feed(content_buffer)+ content_buffer = ''+ if visible:+ yield _sse({'delta': visible})+ if thinking:+ yield _sse({'thinking': thinking})++ if calls:+ if content_buffer.strip():+ yield _sse({'thinking': content_buffer.strip()})+ assistant_msg = {'role': 'assistant', 'content': None, 'tool_calls': [+ {'id': entry['id'] or f'call_{i}', 'type': 'function',+ 'function': {'name': entry['name'], 'arguments': entry['args'] or '{}'}}+ for i, entry in sorted(calls.items())]}+ messages.append(assistant_msg)+ for i, entry in sorted(calls.items()):+ events, result_text = execute_tool(entry['name'], entry['args'])+ for ev in events:+ yield ev+ messages.append({'role': 'tool',+ 'tool_call_id': entry['id'] or f'call_{i}',+ 'content': result_text})+ continue++ # No tool calls: this was the final answer.+ if not streaming_live and content_buffer:+ visible, thinking = answer_filter.feed(content_buffer)+ if visible:+ produced_answer = True+ yield _sse({'delta': visible})+ if thinking:+ yield _sse({'thinking': thinking})+ visible, thinking = answer_filter.flush()+ if visible:+ produced_answer = True+ yield _sse({'delta': visible})+ if thinking:+ yield _sse({'thinking': thinking})+ if not produced_answer:+ yield _sse({'delta': "I could not produce an answer. Please try rephrasing your question."})+ produced_answer = True+ for ev in finish():+ yield ev+ return++ else: # prompt mode+ raw = (response.choices[0].message.content or '').strip()+ # strip a wrapping code fence, then decide: tool call or answer+ fenced = re.match(r'^```(?:json)?\s*(.*?)\s*```$', raw, re.DOTALL)+ candidate = fenced.group(1).strip() if fenced else raw+ parsed = None+ if candidate.startswith('{') and not forcing_final:+ try:+ parsed = json.loads(candidate)+ except ValueError:+ m = re.search(r'\{.*\}', candidate, re.DOTALL)+ if m:+ try:+ parsed = json.loads(m.group())+ except ValueError:+ parsed = None+ if parsed is None:+ # one retry with the parse error fed back+ messages.append({'role': 'assistant', 'content': raw})+ messages.append({'role': 'system',+ 'content': 'Your tool call was not valid JSON. Reply with ONLY '+ 'a valid JSON object {"tool": ..., "arguments": {...}} '+ 'or with your final answer as plain text.'})+ continue+ if parsed is not None and isinstance(parsed, dict) and parsed.get('tool'):+ messages.append({'role': 'assistant', 'content': candidate})+ events, result_text = execute_tool(str(parsed.get('tool')),+ parsed.get('arguments') or {})+ for ev in events:+ yield ev+ messages.append({'role': 'user',+ 'content': f"TOOL RESULT:\n{result_text}"})+ continue++ # Final answer (single delta in prompt mode).+ cleaned = re.sub(r'<think(?:ing)?>.*?</think(?:ing)?>', '', raw,+ flags=re.IGNORECASE | re.DOTALL).strip()+ produced_answer = True+ yield _sse({'delta': cleaned or raw})+ for ev in finish():+ yield ev+ return++ # Loop exhausted without a final answer (shouldn't normally happen —+ # the forcing_final pass answers). Close out defensively.+ yield _sse({'delta': "I ran out of steps before finishing. Please try a more specific question."})+ for ev in finish():+ yield ev++ except TokenBudgetExceeded as e:+ yield _sse({'error': str(e), 'budget_exceeded': True})+ except Exception as e:+ app.logger.error(f"Inquire agent failed: {e}", exc_info=True)+ if not produced_answer and legacy_fallback is not None:+ app.logger.info("Falling back to the single-shot Inquire pipeline")+ try:+ yield from legacy_fallback()+ return+ except Exception as fe:+ app.logger.error(f"Legacy fallback also failed: {fe}")+ yield _sse({'error': str(e)})+ finally:+ ctx.pop()diff --git a/src/services/llm.py b/src/services/llm.pyindex 31274e3b..793cd265 100644--- a/src/services/llm.py+++ b/src/services/llm.py@@ -365,7 +365,7 @@ def call_llm_completion(messages, temperature=0.7, response_format=None, stream=def call_chat_completion(messages, temperature=0.7, response_format=None, stream=False, max_tokens=None,- user_id=None, operation_type=None):+ user_id=None, operation_type=None, tools=None, tool_choice=None):"""Chat-specific LLM completion function. Uses dedicated chat model if configured,otherwise falls back to standard TEXT_MODEL configuration.@@ -378,6 +378,9 @@ def call_chat_completion(messages, temperature=0.7, response_format=None, streammax_tokens: Optional maximum tokens to generateuser_id: Optional user ID for token tracking and budget enforcementoperation_type: Optional operation type for token tracking (e.g., 'chat')+ tools: Optional list of tool schemas (OpenAI function-calling format).+ Only sent when provided, so non-agent call sites are unaffected.+ tool_choice: Optional tool_choice value, passed through when tools are set.Returns:OpenAI completion object or generator (if streaming)@@ -441,6 +444,11 @@ def call_chat_completion(messages, temperature=0.7, response_format=None, streamif response_format:completion_args["response_format"] = response_format+ if tools:+ completion_args["tools"] = tools+ if tool_choice:+ completion_args["tool_choice"] = tool_choice+# Visibility: surface the resolved budget per call so admins can# confirm CHAT_MAX_TOKENS or per-call overrides took effect.budget_key = 'max_completion_tokens' if using_gpt5 else 'max_tokens'diff --git a/static/locales/de.json b/static/locales/de.jsonindex e3811e03..4871317b 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -1086,6 +1086,14 @@"title": "Nachfragen","to": "Bis"},+ "inquirePrivacy": {+ "title": "Inquire-Datenschutz",+ "description": "Wählen Sie, was die Inquire-KI beim Beantworten Ihrer Fragen lesen darf. Transkripte sind immer verfügbar; alles andere entscheiden Sie.",+ "summariesLabel": "Zugriff auf Zusammenfassungen erlauben",+ "summariesHelp": "Erlaubt Inquire, die KI-Zusammenfassungen Ihrer Aufnahmen zu lesen, um lange Aufnahmen schnell zu überblicken.",+ "notesLabel": "Zugriff auf Ihre Notizen erlauben",+ "notesHelp": "Ihre privaten Notizen bleiben unzugänglich, solange Sie dies nicht aktivieren. Es werden nur Ihre eigenen Notizen verwendet, niemals Notizen zu mit Ihnen geteilten Aufnahmen."+ },"languages": {"ar": "Arabisch","de": "Deutsch",diff --git a/static/locales/en.json b/static/locales/en.jsonindex 11ad85f4..fe209c5f 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -1086,6 +1086,14 @@"title": "Inquire","to": "To"},+ "inquirePrivacy": {+ "title": "Inquire Privacy",+ "description": "Choose what the Inquire AI may read when answering your questions. Transcripts are always available; everything else is up to you.",+ "summariesLabel": "Allow access to summaries",+ "summariesHelp": "Lets Inquire read your recordings' AI summaries to survey long recordings quickly.",+ "notesLabel": "Allow access to your notes",+ "notesHelp": "Your private notes stay unavailable unless you enable this. Only your own notes are ever used, never notes on recordings shared with you."+ },"languages": {"ar": "Arabic","de": "German",diff --git a/static/locales/es.json b/static/locales/es.jsonindex 96d6359c..903b705d 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -1086,6 +1086,14 @@"title": "Consultar","to": "Hasta"},+ "inquirePrivacy": {+ "title": "Privacidad de Inquire",+ "description": "Elija qué puede leer la IA de Inquire al responder sus preguntas. Las transcripciones siempre están disponibles; todo lo demás depende de usted.",+ "summariesLabel": "Permitir acceso a los resúmenes",+ "summariesHelp": "Permite a Inquire leer los resúmenes de IA de sus grabaciones para revisar rápidamente grabaciones largas.",+ "notesLabel": "Permitir acceso a sus notas",+ "notesHelp": "Sus notas privadas permanecen inaccesibles a menos que active esta opción. Solo se usan sus propias notas, nunca las notas de grabaciones compartidas con usted."+ },"languages": {"ar": "Árabe","de": "Alemán",diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex c57c5220..4af4527d 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -1086,6 +1086,14 @@"title": "Enquêter","to": "À"},+ "inquirePrivacy": {+ "title": "Confidentialité Inquire",+ "description": "Choisissez ce que l'IA Inquire peut lire pour répondre à vos questions. Les transcriptions sont toujours disponibles ; tout le reste dépend de vous.",+ "summariesLabel": "Autoriser l’accès aux résumés",+ "summariesHelp": "Permet à Inquire de lire les résumés IA de vos enregistrements pour parcourir rapidement les enregistrements longs.",+ "notesLabel": "Autoriser l’accès à vos notes",+ "notesHelp": "Vos notes privées restent inaccessibles tant que vous n’activez pas cette option. Seules vos propres notes sont utilisées, jamais les notes des enregistrements partagés avec vous."+ },"languages": {"ar": "Arabe","de": "Allemand",diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.jsonindex 4feb8e27..91123a49 100644--- a/static/locales/pt-BR.json+++ b/static/locales/pt-BR.json@@ -1086,6 +1086,14 @@"title": "Consulta","to": "Para"},+ "inquirePrivacy": {+ "title": "Privacidade do Inquire",+ "description": "Escolha o que a IA do Inquire pode ler ao responder suas perguntas. As transcrições estão sempre disponíveis; todo o resto é você quem decide.",+ "summariesLabel": "Permitir acesso aos resumos",+ "summariesHelp": "Permite que o Inquire leia os resumos de IA das suas gravações para examinar rapidamente gravações longas.",+ "notesLabel": "Permitir acesso às suas notas",+ "notesHelp": "Suas notas privadas permanecem indisponíveis a menos que você ative esta opção. Somente as suas próprias notas são usadas, nunca notas de gravações compartilhadas com você."+ },"languages": {"ar": "Árabe","de": "Alemão",diff --git a/static/locales/ru.json b/static/locales/ru.jsonindex 0ad4e44f..f74885b1 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -1086,6 +1086,14 @@"title": "Inquire","to": "По"},+ "inquirePrivacy": {+ "title": "Конфиденциальность Inquire",+ "description": "Выберите, что ИИ Inquire может читать при ответе на ваши вопросы. Транскрипции доступны всегда; всё остальное решаете вы.",+ "summariesLabel": "Разрешить доступ к резюме",+ "summariesHelp": "Позволяет Inquire читать ИИ-резюме ваших записей, чтобы быстро просматривать длинные записи.",+ "notesLabel": "Разрешить доступ к вашим заметкам",+ "notesHelp": "Ваши личные заметки остаются недоступными, пока вы не включите эту опцию. Используются только ваши собственные заметки, но никогда заметки к записям, которыми с вами поделились."+ },"languages": {"ar": "Арабский","de": "Немецкий",diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 25f886cd..efa96e6d 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -1086,6 +1086,14 @@"title": "查询","to": "结束日期"},+ "inquirePrivacy": {+ "title": "Inquire 隐私",+ "description": "选择 Inquire AI 在回答问题时可以读取的内容。转录文本始终可用;其余内容由您决定。",+ "summariesLabel": "允许访问摘要",+ "summariesHelp": "允许 Inquire 读取录音的 AI 摘要,以便快速浏览较长的录音。",+ "notesLabel": "允许访问您的笔记",+ "notesHelp": "除非您启用此选项,否则您的私人笔记不可访问。仅会使用您自己的笔记,绝不会使用他人共享给您的录音中的笔记。"+ },"languages": {"ar": "阿拉伯语","de": "德语",diff --git a/templates/account.html b/templates/account.htmlindex 381228d0..26d5b105 100644--- a/templates/account.html+++ b/templates/account.html@@ -782,6 +782,52 @@</div></div>+ <!-- Inquire Privacy Section: what the Inquire AI may read.+ Transcripts are always available (the minimum for+ Inquire to work); summaries and notes are optional.+ Enforcement is structural: a disabled type's tool is+ removed from the agent's toolbox entirely. -->+ <div class="bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-4">+ <i class="fas fa-user-shield mr-2"></i>+ <span data-i18n="inquirePrivacy.title">Inquire Privacy</span>+ </h3>+ <input type="hidden" name="inquire_privacy_section" value="1">+ <p class="text-xs text-[var(--text-muted)] mb-4" data-i18n="inquirePrivacy.description">+ Choose what the Inquire AI may read when answering your questions. Transcripts are always available; everything else is up to you.+ </p>+ <div class="mb-3">+ <label class="flex items-start space-x-3">+ <input type="checkbox" name="inquire_allow_summaries" id="inquire_allow_summaries"+ {% if inquire_allow_summaries %}checked{% endif %}+ class="mt-1 h-4 w-4 text-[var(--border-accent)] focus:ring-[var(--border-focus)] border-[var(--border-secondary)] rounded">+ <div>+ <span class="block text-sm font-medium text-[var(--text-primary)]" data-i18n="inquirePrivacy.summariesLabel">+ Allow access to summaries+ </span>+ <span class="block text-xs text-[var(--text-muted)] mt-1" data-i18n="inquirePrivacy.summariesHelp">+ Lets Inquire read your recordings' AI summaries to survey long recordings quickly.+ </span>+ </div>+ </label>+ </div>+ <div>+ <label class="flex items-start space-x-3">+ <input type="checkbox" name="inquire_allow_notes" id="inquire_allow_notes"+ {% if inquire_allow_notes %}checked{% endif %}+ class="mt-1 h-4 w-4 text-[var(--border-accent)] focus:ring-[var(--border-focus)] border-[var(--border-secondary)] rounded">+ <div>+ <span class="block text-sm font-medium text-[var(--text-primary)]" data-i18n="inquirePrivacy.notesLabel">+ Allow access to your notes+ </span>+ <span class="block text-xs text-[var(--text-muted)] mt-1" data-i18n="inquirePrivacy.notesHelp">+ Your private notes stay unavailable unless you enable this. Only your own notes are ever used, never notes on recordings shared with you.+ </span>+ </div>+ </label>+ </div>+ </div>+<!-- Custom Prompts Section --><div class="bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]"><h3 class="text-lg font-medium text-[var(--text-secondary)] mb-4" data-i18n="customPrompts.summaryGeneration">Summary Generation Prompt</h3>diff --git a/templates/inquire.html b/templates/inquire.htmlindex a2de43b7..2082152c 100644--- a/templates/inquire.html+++ b/templates/inquire.html@@ -140,6 +140,29 @@border-radius: 3px;font-size: 0.9em;}++ /* Citation chips: the agent cites sources as markdown links to+ /recordings/<id>; style them like small tag chips so they read+ as references rather than inline hyperlinks. */+ .chat-message .prose a[href^="/recordings/"] {+ display: inline-block;+ background-color: var(--bg-tertiary);+ color: var(--text-accent);+ border: 1px solid var(--border-secondary);+ border-radius: 9999px;+ padding: 0 0.55em;+ font-size: 0.78em;+ line-height: 1.6;+ text-decoration: none;+ vertical-align: baseline;+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .chat-message .prose a[href^="/recordings/"]:hover {+ border-color: var(--border-focus);+ }</style></head><body class="h-full bg-[var(--bg-primary)] text-[var(--text-primary)] transition-colors duration-300">@@ -465,29 +488,93 @@markdown renders consistently. Both bubblesuse rounded-lg (instead of rounded-xl) so theshape matches the rest of the design system. -->- <div v-for="(message, index) in inquireChatMessages" :key="index"- :class="['flex', message.role === 'user' ? 'justify-end' : 'justify-start']">- <div class="max-w-3xl chat-message"- :class="message.role === 'user' ? 'message user-message' : 'message ai-message'">- <div v-if="message.html || message.content"- class="prose prose-sm max-w-none"- :class="message.role === 'user' ? 'prose-invert' : ''"- v-html="message.html || message.content">+ <template v-for="(message, index) in inquireChatMessages" :key="index">+ <!-- Compaction divider: older turns above this point were+ folded into a memory summary the assistant still sees.+ Click to inspect exactly what it remembers. -->+ <div v-if="index === memoryState.dividerIndex && memoryState.memory" class="my-2">+ <button @click="memoryState.showMemory = !memoryState.showMemory"+ class="w-full flex items-center gap-3 text-xs"+ style="color: var(--text-muted);">+ <span class="flex-1 border-t" style="border-color: var(--border-primary);"></span>+ <span class="flex items-center gap-1.5 whitespace-nowrap">+ <i class="fas fa-layer-group"></i>+ <span>Earlier conversation summarized</span>+ <i :class="['fas text-[10px]', memoryState.showMemory ? 'fa-chevron-up' : 'fa-chevron-down']"></i>+ </span>+ <span class="flex-1 border-t" style="border-color: var(--border-primary);"></span>+ </button>+ <div v-if="memoryState.showMemory"+ class="surface-raised mt-2 text-xs whitespace-pre-wrap"+ style="padding: var(--sp-3); color: var(--text-secondary);"+ v-text="memoryState.memory"></div></div>- </div>++ <div :class="['flex', message.role === 'user' ? 'justify-end' : 'justify-start']">+ <div class="max-w-3xl chat-message"+ :class="message.role === 'user' ? 'message user-message' : 'message ai-message'">+ <!-- Persistent provenance: the agent's collapsed+ activity line, expandable to the full timeline. -->+ <div v-if="message.role === 'assistant' && message.activitySummary"+ class="mb-2 pb-2 border-b" style="border-color: var(--border-primary);">+ <button @click="message.showSteps = !message.showSteps"+ class="flex items-center gap-2 text-xs" style="color: var(--text-muted);">+ <i class="fas fa-list-check"></i>+ <span v-text="message.agentStepCount + (message.agentStepCount === 1 ? ' step · ' : ' steps · ') + message.activitySummary"></span>+ <i :class="['fas text-[10px]', message.showSteps ? 'fa-chevron-up' : 'fa-chevron-down']"></i>+ </button>+ <div v-if="message.showSteps && message.steps && message.steps.length" class="mt-2 space-y-1">+ <div v-for="step in message.steps" :key="step.id"+ class="flex items-start gap-2 text-xs" style="color: var(--text-secondary);">+ <i :class="['fas mt-0.5 w-4 text-center', step.icon]" style="color: var(--text-muted);"></i>+ <span class="min-w-0">+ <span v-text="step.label"></span>+ <span v-if="step.detail" style="color: var(--text-muted);" v-text="' — ' + step.detail"></span>+ </span>+ </div>+ </div>+ </div>+ <div v-if="message.html || message.content"+ class="prose prose-sm max-w-none"+ :class="message.role === 'user' ? 'prose-invert' : ''"+ v-html="message.html || message.content">+ </div>+ </div>+ </div>+ </template><!-- Loading indicator — uses the .ai-messageprimitive for visual consistency with normalassistant messages, plus a clear step indicatorrow so the user sees progress through theanalysis pipeline. -->- <div v-if="isInquireChatLoading" class="flex justify-start">- <div class="ai-message message max-w-md">+ <div v-if="isInquireChatLoading && !answerStarted" class="flex justify-start">+ <div class="ai-message message max-w-md" style="min-width: 260px;"><div class="flex items-center gap-2"><div class="spinner flex-shrink-0"></div>- <span class="t-meta" v-if="showProcessingStatus">${ chatProcessingStatus }</span>- <span class="t-meta" v-else>Analyzing transcriptions...</span>+ <span class="t-meta flex-1" v-if="showProcessingStatus">${ chatProcessingStatus }</span>+ <span class="t-meta flex-1" v-else-if="agentSteps.length">Working on it...</span>+ <span class="t-meta flex-1" v-else>Analyzing transcriptions...</span>+ <button @click="stopInquireChat" class="btn btn--ghost btn--sm flex-shrink-0" title="Stop">+ <i class="fas fa-stop text-xs"></i>+ </button>+ </div>+ <!-- Agent activity timeline: one row per tool step,+ spinner while running, muted check when done.+ Empty results and tool errors render calmly+ (they are a normal part of searching). -->+ <div v-if="agentSteps.length" class="mt-2 space-y-1.5">+ <div v-for="step in agentSteps" :key="step.id"+ class="flex items-start gap-2 text-xs" style="color: var(--text-secondary);">+ <i v-if="step.status === 'running'" class="fas fa-circle-notch fa-spin mt-0.5 w-4 text-center" style="color: var(--text-accent);"></i>+ <i v-else-if="step.status === 'done'" class="fas fa-check mt-0.5 w-4 text-center" style="color: var(--text-muted);"></i>+ <i v-else :class="['fas mt-0.5 w-4 text-center', step.status === 'error' ? 'fa-circle-exclamation' : 'fa-minus']" style="color: var(--text-muted);"></i>+ <span class="min-w-0">+ <span v-text="step.label"></span>+ <span v-if="step.detail" style="color: var(--text-muted);" v-text="' — ' + step.detail"></span>+ </span>+ </div></div><div v-if="showProcessingStatus" class="mt-2 flex gap-1"><div class="h-1 w-4 rounded transition-colors"@@ -528,8 +615,22 @@</div><div class="t-meta mt-2 flex items-center justify-between"><span>${t('inquire.sendHint')}</span>- <span v-if="hasActiveFilters" style="color: var(--text-accent);">- <i class="fas fa-filter mr-1"></i>${t('inquire.filtersActive')}+ <span class="flex items-center gap-3">+ <!-- Context meter: invisible below 50% to avoid+ clutter; past that it shows how full the+ conversation context is, so compaction never+ feels like silent memory loss. -->+ <span v-if="contextUsage >= 50" class="flex items-center gap-1.5"+ :title="'Conversation context: ' + contextUsage + '% — older messages are summarized when it fills up'">+ <span class="inline-block w-16 h-1 rounded-full overflow-hidden" style="background: var(--bg-tertiary);">+ <span class="block h-full rounded-full"+ :style="{ width: contextUsage + '%', background: 'var(--bg-accent)' }"></span>+ </span>+ <span v-text="contextUsage + '%'"></span>+ </span>+ <span v-if="hasActiveFilters" style="color: var(--text-accent);">+ <i class="fas fa-filter mr-1"></i>${t('inquire.filtersActive')}+ </span></span></div></div>@@ -720,6 +821,19 @@const isInquireChatLoading = ref(false);const chatProcessingStatus = ref('');const showProcessingStatus = ref(false);+ // --- Agentic Inquire state (ENABLE_INQUIRE_AGENT beta) ---+ // Live tool activity for the in-flight turn; moved onto the+ // finished message so provenance persists in the history.+ const agentSteps = ref([]);+ const answerStarted = ref(false);+ // Context accounting: 0-100 estimate from the server, and+ // the compaction state. `memory` is the server-produced+ // summary of folded turns; `fromIndex` is where verbatim+ // history starts in inquireChatMessages; `dividerIndex`+ // marks where the "summarized" divider renders.+ const contextUsage = ref(0);+ const memoryState = reactive({ memory: '', fromIndex: 0, dividerIndex: -1, showMemory: false });+ const inquireAbort = ref(null);const inquireMessagesRef = ref(null);const globalError = ref(null);const shouldAutoScroll = ref(true); // Track if we should auto-scroll@@ -786,21 +900,41 @@}};+ const stopInquireChat = () => {+ // Aborting the fetch closes the SSE stream; the server+ // agent loop stops between steps when the client goes away.+ if (inquireAbort.value) inquireAbort.value.abort();+ };+const sendInquireChatMessage = async () => {if (!inquireChatInput.value.trim() || isInquireChatLoading.value) return;-+const userMessage = inquireChatInput.value.trim();inquireChatMessages.value.push({ role: 'user', content: userMessage, html: userMessage });inquireChatInput.value = '';isInquireChatLoading.value = true;showProcessingStatus.value = true;chatProcessingStatus.value = 'Initializing...';-+ agentSteps.value = [];+ answerStarted.value = false;+// Always scroll to bottom when user sends a messageshouldAutoScroll.value = true;await nextTick();scrollToBottom();-++ // Verbatim history starts at fromIndex (earlier turns+ // live in memoryState.memory after compaction). The+ // sent length is needed to map the server's keep_last+ // back to an index in the full message list.+ const sentHistory = inquireChatMessages.value+ .slice(memoryState.fromIndex, -1)+ .filter(m => m.role === 'user' || m.role === 'assistant')+ .map(m => ({ role: m.role, content: m.content, activity: m.activitySummary || undefined }));+ const sentFromIndex = memoryState.fromIndex;+ const controller = new AbortController();+ inquireAbort.value = controller;+try {const response = await fetch('/api/inquire/chat', {method: 'POST',@@ -808,9 +942,11 @@'Content-Type': 'application/json','X-CSRFToken': csrfToken.value},+ signal: controller.signal,body: JSON.stringify({message: userMessage,- message_history: inquireChatMessages.value.slice(0, -1),+ message_history: sentHistory,+ conversation_memory: memoryState.memory || undefined,filter_tags: inquireFilters.selectedTags,filter_speakers: inquireFilters.selectedSpeakers,filter_recording_ids: inquireFilters.selectedRecordings,@@ -819,24 +955,24 @@context_chunks: 8})});-+if (!response.ok) {throw new Error('Chat request failed');}-+// Handle streaming responseconst reader = response.body.getReader();const decoder = new TextDecoder();- let assistantMessage = reactive({ role: 'assistant', content: '', html: '' });+ let assistantMessage = reactive({ role: 'assistant', content: '', html: '', steps: [], activitySummary: '', showSteps: false });let messageAdded = false;-+while (true) {const { done, value } = await reader.read();if (done) break;-+const chunk = decoder.decode(value, { stream: true });const lines = chunk.split('\n');-+for (const line of lines) {if (line.startsWith('data: ')) {try {@@ -844,12 +980,46 @@if (data.status && data.message) {// Update processing statuschatProcessingStatus.value = data.message;+ } else if (data.agent_step) {+ // Upsert by id: 'running' first, then the+ // completion state with the result detail.+ const step = data.agent_step;+ const existing = agentSteps.value.find(s => s.id === step.id);+ if (existing) Object.assign(existing, step);+ else agentSteps.value.push(step);+ showProcessingStatus.value = false;+ await nextTick();+ scrollToBottom();+ } else if (data.context_usage !== undefined) {+ contextUsage.value = data.context_usage;+ } else if (data.context_compacted) {+ // Older turns were folded into a memory block.+ // Verbatim history now starts keep_last messages+ // from the end of what we sent.+ const kept = data.context_compacted.keep_last || 0;+ memoryState.memory = data.context_compacted.memory || '';+ const newFrom = Math.max(sentFromIndex, inquireChatMessages.value.length - 1 - kept);+ memoryState.fromIndex = newFrom;+ memoryState.dividerIndex = newFrom;+ } else if (data.conversation_memory) {+ memoryState.memory = data.conversation_memory;+ } else if (data.agent_summary) {+ assistantMessage.activitySummary = data.agent_summary.line || '';+ assistantMessage.agentStepCount = data.agent_summary.steps || 0;+ } else if (data.thinking) {+ // Surfaced reasoning: keep the latest status text+ // visible but do not render into the answer.+ chatProcessingStatus.value = 'Thinking...';} else if (data.delta) {// Hide status and start showing responseif (!messageAdded) {inquireChatMessages.value.push(assistantMessage);messageAdded = true;showProcessingStatus.value = false;+ answerStarted.value = true;+ // Attach the activity timeline to the message+ // so provenance persists after the turn.+ assistantMessage.steps = agentSteps.value;}assistantMessage.content += data.delta;assistantMessage.html = window.renderMarkdownSafe(assistantMessage.content);@@ -871,17 +1041,28 @@throw new Error(data.error);}} catch (parseError) {- console.warn('Failed to parse SSE data:', line);+ if (parseError instanceof SyntaxError) {+ console.warn('Failed to parse SSE data:', line);+ } else {+ throw parseError;+ }}}}}} catch (error) {- console.error('Error in inquire chat:', error);- setGlobalError(error.message || 'Chat failed. Please try again.', 10000);+ if (error && error.name === 'AbortError') {+ // User pressed Stop: keep whatever streamed so far.+ console.info('Inquire chat stopped by user');+ } else {+ console.error('Error in inquire chat:', error);+ setGlobalError(error.message || 'Chat failed. Please try again.', 10000);+ }} finally {isInquireChatLoading.value = false;showProcessingStatus.value = false;+ inquireAbort.value = null;+ agentSteps.value = [];loadTokenBudget(); // Refresh token usage after chatawait nextTick();scrollToBottom(); // Use smart scrolling@@ -906,6 +1087,12 @@inquireFilters.dateFrom = null;inquireFilters.dateTo = null;inquireChatMessages.value = [];+ // New conversation: drop the agent's memory/compaction state.+ memoryState.memory = '';+ memoryState.fromIndex = 0;+ memoryState.dividerIndex = -1;+ memoryState.showMemory = false;+ contextUsage.value = 0;};const formatDate = (dateString) => {@@ -1035,6 +1222,11 @@inquireChatMessages,inquireChatInput,isInquireChatLoading,+ agentSteps,+ answerStarted,+ contextUsage,+ memoryState,+ stopInquireChat,inquireMessagesRef,globalError,tokenBudget,diff --git a/tests/test_inquire_agent.py b/tests/test_inquire_agent.pynew file mode 100644index 00000000..555d39a4--- /dev/null+++ b/tests/test_inquire_agent.py@@ -0,0 +1,493 @@+#!/usr/bin/env python3+"""Tests for src/services/inquire_agent.py — the agentic Inquire tool loop.++Covers: toolbox availability gating, filter scoping, notes ownership,+transcript pagination, result truncation, history sanitization/compaction,+and the agent loop itself (native tool-calling and prompted-JSON modes,+duplicate-call guard, forced finals, budget errors, legacy fallback) using a+scripted fake LLM. No network, no real LLM.++Run: docker exec speakr-dev python -m pytest tests/test_inquire_agent.py -q+"""++import json+import os+import sys+import uuid+import contextlib++import pytest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app, db # noqa: E402+from src.models import User, Recording, Tag, RecordingTag # noqa: E402+from src.services import inquire_agent as ia # noqa: E402+from src.services.llm import TokenBudgetExceeded # noqa: E402+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++class NS:+ def __init__(self, **kw):+ self.__dict__.update(kw)+++def text_chunk(s):+ return NS(choices=[NS(delta=NS(content=s, tool_calls=None))])+++def tool_chunk(idx, call_id=None, name=None, args=None):+ fn = NS(name=name, arguments=args)+ return NS(choices=[NS(delta=NS(content=None, tool_calls=[NS(index=idx, id=call_id, function=fn)]))])+++def nonstream_response(text):+ return NS(choices=[NS(message=NS(content=text))])+++class FakeLLM:+ """Scripted stand-in for call_chat_completion.++ Each entry in `script` is either a list of stream chunks (returned as an+ iterator when stream=True), a nonstream response object, or an Exception+ to raise.+ """++ def __init__(self, script):+ self.script = list(script)+ self.calls = []++ def __call__(self, messages=None, tools=None, tool_choice=None, temperature=None,+ stream=False, max_tokens=None, user_id=None, operation_type=None,+ response_format=None):+ self.calls.append({'messages': messages, 'tools': tools, 'stream': stream,+ 'operation_type': operation_type})+ if not self.script:+ raise AssertionError('FakeLLM script exhausted')+ item = self.script.pop(0)+ if isinstance(item, Exception):+ raise item+ if isinstance(item, list):+ return iter(item)+ return item+++def parse_events(sse_strings):+ out = []+ for s in sse_strings:+ assert s.startswith('data: ')+ out.append(json.loads(s[len('data: '):].strip()))+ return out+++def event_types(events):+ types = []+ for e in events:+ types.append(next(iter(+ k for k in ('agent_step', 'delta', 'thinking', 'agent_summary', 'end_of_stream',+ 'context_usage', 'context_compacted', 'conversation_memory',+ 'status', 'error') if k in e), 'other'))+ return types+++USER_CTX = {'name': 'Testy', 'title': 'analyst', 'company': 'ACME', 'output_language': None}++SEGMENTS = [{'speaker': f'S{i % 2}', 'sentence': f'sentence number {i}', 'start_time': i * 2.0}+ for i in range(300)]+++def env_agent():+ saved = {}+ keys = ['ENABLE_INQUIRE_AGENT', 'INQUIRE_AGENT_MAX_STEPS', 'INQUIRE_AGENT_TOOL_MODE',+ 'INQUIRE_AGENT_TOOL_RESULT_TOKENS', 'INQUIRE_AGENT_TIMEOUT_SECONDS',+ 'INQUIRE_CONTEXT_BUDGET_TOKENS', 'INQUIRE_DEFAULT_ALLOW_SUMMARIES',+ 'INQUIRE_DEFAULT_ALLOW_NOTES']+ for k in keys:+ saved[k] = os.environ.pop(k, None)+ yield+ for k, v in saved.items():+ if v is None:+ os.environ.pop(k, None)+ else:+ os.environ[k] = v+++def data(env_agent):+ """Two users; owner has three recordings (one tagged, one older, one from+ the other user injected only for ownership tests)."""+ with app.app_context():+ suffix = uuid.uuid4().hex[:8]+ owner = User(username=f'agent_o_{suffix}', email=f'ao_{suffix}@example.com', password='x')+ other = User(username=f'agent_x_{suffix}', email=f'ax_{suffix}@example.com', password='x')+ db.session.add_all([owner, other])+ db.session.flush()++ tag = Tag(name=f'agtag_{suffix}', user_id=owner.id)+ db.session.add(tag)+ db.session.flush()++ from datetime import datetime+ r1 = Recording(user_id=owner.id, title='Weekly Sync', status='COMPLETED',+ transcription=json.dumps(SEGMENTS), summary='sum of weekly sync',+ notes='owner notes r1', participants='Alice, Bob',+ meeting_date=datetime(2026, 8, 20, 10, 0))+ r2 = Recording(user_id=owner.id, title='Old Planning', status='COMPLETED',+ transcription='plain text transcript ' * 50,+ meeting_date=datetime(2026, 1, 5, 9, 0))+ r3 = Recording(user_id=other.id, title='Foreign Rec', status='COMPLETED',+ transcription=json.dumps(SEGMENTS[:5]), notes='not yours',+ meeting_date=datetime(2026, 8, 21, 9, 0))+ db.session.add_all([r1, r2, r3])+ db.session.flush()+ db.session.add(RecordingTag(recording_id=r1.id, tag_id=tag.id))+ db.session.commit()++ ids = {'owner': owner.id, 'other': other.id, 'tag': tag.id,+ 'r1': r1.id, 'r2': r2.id, 'r3': r3.id}+ yield ids++ RecordingTag.query.filter_by(recording_id=ids['r1']).delete()+ Recording.query.filter(Recording.id.in_([ids['r1'], ids['r2'], ids['r3']])).delete(synchronize_session=False)+ Tag.query.filter_by(id=ids['tag']).delete()+ User.query.filter(User.id.in_([ids['owner'], ids['other']])).delete(synchronize_session=False)+ db.session.commit()+++# ---------------------------------------------------------------------------+# Toolbox availability+# ---------------------------------------------------------------------------++def test_toolbox_gates_notes_and_summaries():+ schemas, execs = ia.build_toolbox({'summaries': True, 'notes': True})+ assert {'get_summary', 'get_notes'} <= set(execs)+ schemas, execs = ia.build_toolbox({'summaries': False, 'notes': False})+ assert 'get_summary' not in execs and 'get_notes' not in execs+ names = [s['function']['name'] for s in schemas]+ assert 'get_notes' not in names and 'get_summary' not in names+ assert {'search_transcripts', 'list_recordings', 'get_transcript', 'get_recording_metadata'} <= set(execs)+++def test_availability_env_defaults_and_user_override(env_agent, data):+ with app.app_context():+ user = db.session.get(User, data['owner'])+ # NULL columns -> env defaults (summaries on, notes off)+ assert ia.get_availability(user) == {'summaries': True, 'notes': False}+ os.environ['INQUIRE_DEFAULT_ALLOW_SUMMARIES'] = 'false'+ assert ia.get_availability(user)['summaries'] is False+ user.inquire_allow_summaries = True+ user.inquire_allow_notes = True+ assert ia.get_availability(user) == {'summaries': True, 'notes': True}+++# ---------------------------------------------------------------------------+# Scope+# ---------------------------------------------------------------------------++def test_scope_respects_filters(data):+ with app.app_context():+ uid = data['owner']+ all_ids = ia.resolve_allowed_recording_ids(uid, {})+ assert {data['r1'], data['r2']} <= all_ids+ assert data['r3'] not in all_ids # other user's recording++ tag_ids = ia.resolve_allowed_recording_ids(uid, {'tag_ids': [data['tag']]})+ assert tag_ids & {data['r1'], data['r2']} == {data['r1']}++ from datetime import date+ recent = ia.resolve_allowed_recording_ids(uid, {'date_from': date(2026, 6, 1)})+ assert data['r1'] in recent and data['r2'] not in recent++ subset = ia.resolve_allowed_recording_ids(uid, {'recording_ids': [data['r2']]})+ assert subset & {data['r1'], data['r2']} == {data['r2']}+++def test_tools_refuse_out_of_scope(data):+ with app.app_context():+ ctx = ia.ToolContext(data['owner'], {}, {data['r1']}, {'summaries': True, 'notes': True})+ res = ia.tool_get_transcript(ctx, {'recording_id': data['r2']})+ assert 'error' in res and 'not available' in res['error']+++def test_notes_never_on_foreign_recordings(data):+ with app.app_context():+ # Even if a foreign recording somehow lands in scope (e.g. shared),+ # notes remain owner-only.+ ctx = ia.ToolContext(data['owner'], {}, {data['r3']}, {'summaries': True, 'notes': True})+ res = ia.tool_get_notes(ctx, {'recording_id': data['r3']})+ assert 'error' in res and 'own recordings' in res['error']+++# ---------------------------------------------------------------------------+# Tools+# ---------------------------------------------------------------------------++def test_get_transcript_pagination(data):+ with app.app_context():+ ctx = ia.ToolContext(data['owner'], {}, {data['r1']}, {'summaries': True, 'notes': False})+ page1 = ia.tool_get_transcript(ctx, {'recording_id': data['r1'], 'limit': 100})+ assert page1['total_segments'] == 300+ assert page1['returned_segments'] == 100+ assert page1['next_offset'] == 100+ assert 'sentence number 0' in page1['transcript']+ page3 = ia.tool_get_transcript(ctx, {'recording_id': data['r1'], 'offset': 200, 'limit': 100})+ assert page3['next_offset'] is None+ assert 'sentence number 299' in page3['transcript']+++def test_get_transcript_plain_text(data):+ with app.app_context():+ ctx = ia.ToolContext(data['owner'], {}, {data['r2']}, {'summaries': True, 'notes': False})+ res = ia.tool_get_transcript(ctx, {'recording_id': data['r2']})+ assert 'total_chars' in res and res['transcript'].startswith('plain text')+++def test_list_recordings_and_metadata(data):+ with app.app_context():+ allowed = {data['r1'], data['r2']}+ ctx = ia.ToolContext(data['owner'], {}, allowed, {'summaries': True, 'notes': False})+ res = ia.tool_list_recordings(ctx, {})+ assert res['total_in_scope'] == 2+ titles = [r['title'] for r in res['recordings']]+ assert titles == ['Weekly Sync', 'Old Planning'] # newest first+ res = ia.tool_list_recordings(ctx, {'participant': 'Alice'})+ assert res['total_in_scope'] == 1+ meta = ia.tool_get_recording_metadata(ctx, {'recording_id': data['r1']})+ assert meta['has_summary'] is True and meta['has_notes'] is True+++def test_search_tool_scopes_and_shapes(data, monkeypatch):+ with app.app_context():+ r1 = db.session.get(Recording, data['r1'])+ chunk = NS(recording_id=r1.id, recording=r1, speaker_name='Alice',+ start_time=63.0, chunk_index=4, content='budget talk')+ foreign = db.session.get(Recording, data['r3'])+ stray = NS(recording_id=foreign.id, recording=foreign, speaker_name=None,+ start_time=None, chunk_index=0, content='should not appear')+ monkeypatch.setattr(ia, 'semantic_search_chunks',+ lambda uid, q, f, k: [(chunk, 0.9), (stray, 0.8)])+ ctx = ia.ToolContext(data['owner'], {}, {data['r1'], data['r2']},+ {'summaries': True, 'notes': False})+ res = ia.tool_search_transcripts(ctx, {'query': 'budget'})+ assert res['result_count'] == 1+ hit = res['results'][0]+ assert hit['recording_id'] == data['r1'] and hit['time'] == '1:03'+++def test_truncation_marker():+ text = 'x' * 100000+ out = ia._truncate_to_tokens(text, 100, 'More available.')+ assert len(out) < 1000+ assert 'TRUNCATED' in out and 'More available.' in out+++# ---------------------------------------------------------------------------+# History and compaction+# ---------------------------------------------------------------------------++def test_sanitize_history_folds_activity_and_drops_junk():+ history = [+ {'role': 'user', 'content': 'q1'},+ {'role': 'assistant', 'content': 'a1', 'html': '<p>a1</p>', 'activity': '2 searches'},+ {'role': 'system', 'content': 'nope'},+ {'role': 'assistant', 'content': ''},+ 'garbage',+ ]+ out = ia.sanitize_history(history)+ assert len(out) == 2+ assert out[1]['content'].startswith('a1')+ assert 'research performed' in out[1]['content']+ assert all(set(m) == {'role', 'content'} for m in out)+++def test_compact_history_uses_llm_and_keeps_tail(data, monkeypatch):+ with app.app_context():+ history = [{'role': 'user' if i % 2 == 0 else 'assistant', 'content': f'm{i}'}+ for i in range(12)]+ monkeypatch.setattr(ia, 'call_chat_completion',+ lambda **kw: nonstream_response('MEMORY BLOCK'))+ memory, kept, folded = ia.compact_history(data['owner'], None, history, keep_last=8)+ assert memory == 'MEMORY BLOCK'+ assert folded == 4 and len(kept) == 8+ assert kept[0]['content'] == 'm4'+++def test_compact_history_degrades_to_truncation(data, monkeypatch):+ with app.app_context():+ history = [{'role': 'user', 'content': f'm{i}'} for i in range(12)]+ def boom(**kw):+ raise RuntimeError('llm down')+ monkeypatch.setattr(ia, 'call_chat_completion', boom)+ memory, kept, folded = ia.compact_history(data['owner'], 'old mem', history, keep_last=8)+ assert 'truncated' in memory.lower() and 'old mem' in memory+ assert len(kept) == 8 and folded == 4+++# ---------------------------------------------------------------------------+# The loop (native mode)+# ---------------------------------------------------------------------------++def _run(data, fake, history=None, memory=None, filters=None, fallback=None):+ gen = ia.run_inquire_agent(app, data['owner'], USER_CTX, 'what happened?',+ history or [], memory, filters or {},+ legacy_fallback=fallback, llm_call=fake)+ return parse_events(list(gen))+++def test_loop_tool_call_then_answer(data):+ os.environ['INQUIRE_AGENT_TOOL_MODE'] = 'native'+ args = json.dumps({'recording_id': data['r1'], 'limit': 5})+ fake = FakeLLM([+ [tool_chunk(0, 'c1', 'get_transcript', args)],+ [text_chunk('The answer is ' * 30)], # >200 chars so it live-streams+ ])+ events = _run(data, fake)+ types = event_types(events)+ steps = [e['agent_step'] for e in events if 'agent_step' in e]+ assert steps[0]['status'] == 'running' and steps[1]['status'] == 'done'+ assert 'delta' in types and types[-1] == 'end_of_stream'+ summary = next(e['agent_summary'] for e in events if 'agent_summary' in e)+ assert summary['steps'] == 1 and 'transcript read' in summary['line']+ # The tool result was appended as a tool message on the second call+ second_call = fake.calls[1]['messages']+ assert any(m.get('role') == 'tool' for m in second_call)+++def test_loop_duplicate_call_served_from_cache(data):+ os.environ['INQUIRE_AGENT_TOOL_MODE'] = 'native'+ args = json.dumps({'recording_id': data['r1'], 'limit': 5})+ fake = FakeLLM([+ [tool_chunk(0, 'c1', 'get_transcript', args)],+ [tool_chunk(0, 'c2', 'get_transcript', args)],+ [text_chunk('done ' * 50)],+ ])+ events = _run(data, fake)+ third_call = fake.calls[2]['messages']+ tool_msgs = [m for m in third_call if m.get('role') == 'tool']+ assert len(tool_msgs) == 2+ assert 'duplicate call' in tool_msgs[1]['content']+ summary = next(e['agent_summary'] for e in events if 'agent_summary' in e)+ assert summary['steps'] == 1 # cached call doesn't count as a new step+++def test_loop_unknown_tool_and_bad_args_recover(data):+ os.environ['INQUIRE_AGENT_TOOL_MODE'] = 'native'+ fake = FakeLLM([+ [tool_chunk(0, 'c1', 'no_such_tool', '{}')],+ [tool_chunk(0, 'c2', 'get_transcript', 'NOT JSON')],+ [text_chunk('recovered fine, here is the answer. ' * 10)],+ ])+ events = _run(data, fake)+ steps = [e['agent_step'] for e in events if 'agent_step' in e and e['agent_step'].get('status') not in ('running',)]+ assert all(s['status'] == 'error' for s in steps)+ assert event_types(events)[-1] == 'end_of_stream'+ assert any('delta' in e for e in events)+++def test_loop_forced_final_at_max_steps(data):+ os.environ['INQUIRE_AGENT_TOOL_MODE'] = 'native'+ os.environ['INQUIRE_AGENT_MAX_STEPS'] = '1'+ args = json.dumps({'recording_id': data['r1'], 'limit': 5})+ fake = FakeLLM([+ [tool_chunk(0, 'c1', 'get_transcript', args)],+ [text_chunk('forced final answer with evidence so far. ' * 10)],+ ])+ events = _run(data, fake)+ # The forcing call must NOT offer tools+ assert fake.calls[0]['tools'] is not None+ assert fake.calls[1]['tools'] is None+ forcing_msgs = [m for m in fake.calls[1]['messages'] if m.get('role') == 'system']+ assert any('Step budget exhausted' in m['content'] for m in forcing_msgs)+ assert event_types(events)[-1] == 'end_of_stream'+++def test_loop_budget_exceeded_event(data):+ os.environ['INQUIRE_AGENT_TOOL_MODE'] = 'native'+ fake = FakeLLM([TokenBudgetExceeded('over budget', 101)])+ events = _run(data, fake)+ assert events[-1].get('budget_exceeded') is True+++def test_loop_fallback_to_legacy(data):+ os.environ['INQUIRE_AGENT_TOOL_MODE'] = 'native'+ fake = FakeLLM([RuntimeError('connection refused')])+ def legacy():+ yield 'data: {"delta": "legacy says hi"}\n\n'+ yield 'data: {"end_of_stream": true}\n\n'+ events = _run(data, fake, fallback=legacy)+ assert any(e.get('delta') == 'legacy says hi' for e in events)+++def test_loop_auto_switches_to_prompt_mode(data):+ os.environ['INQUIRE_AGENT_TOOL_MODE'] = 'auto'+ ia._NATIVE_TOOLS_SUPPORTED.clear()+ tool_call = json.dumps({'tool': 'get_transcript',+ 'arguments': {'recording_id': data['r1'], 'limit': 5}})+ fake = FakeLLM([+ RuntimeError("400: 'tools' is not supported by this endpoint"),+ nonstream_response(tool_call),+ nonstream_response('final answer from prompt mode'),+ ])+ events = _run(data, fake)+ assert any(e.get('delta') == 'final answer from prompt mode' for e in events)+ steps = [e['agent_step'] for e in events if 'agent_step' in e]+ assert steps and steps[-1]['status'] == 'done'+ # remembered for the session+ assert False in ia._NATIVE_TOOLS_SUPPORTED.values()+ ia._NATIVE_TOOLS_SUPPORTED.clear()+++def test_prompt_mode_fenced_json_and_retry(data):+ os.environ['INQUIRE_AGENT_TOOL_MODE'] = 'prompt'+ good = '```json\n' + json.dumps({'tool': 'list_recordings', 'arguments': {}}) + '\n```'+ fake = FakeLLM([+ nonstream_response('{ this is not valid json'),+ nonstream_response(good),+ nonstream_response('the final answer'),+ ])+ events = _run(data, fake)+ # retry instruction was injected after the parse failure+ retry_msgs = [m for m in fake.calls[1]['messages'] if m.get('role') == 'system']+ assert any('not valid JSON' in m['content'] for m in retry_msgs)+ assert any(e.get('delta') == 'the final answer' for e in events)+++def test_prompt_mode_strips_think_tags(data):+ os.environ['INQUIRE_AGENT_TOOL_MODE'] = 'prompt'+ fake = FakeLLM([nonstream_response('<think>secret reasoning</think>clean answer')])+ events = _run(data, fake)+ delta = next(e['delta'] for e in events if 'delta' in e)+ assert delta == 'clean answer'+++def test_loop_compaction_triggers_and_reports(data, monkeypatch):+ os.environ['INQUIRE_AGENT_TOOL_MODE'] = 'prompt'+ os.environ['INQUIRE_CONTEXT_BUDGET_TOKENS'] = '4000' # floor value, easy to exceed+ history = [{'role': 'user' if i % 2 == 0 else 'assistant', 'content': 'long ' * 400}+ for i in range(12)]+ monkeypatch.setattr(ia, 'compact_history',+ lambda uid, mem, hist, keep_last=8: ('COMPACTED', hist[-8:], len(hist) - 8))+ fake = FakeLLM([nonstream_response('answer after compaction')])+ events = _run(data, fake, history=history)+ compacted = next(e['context_compacted'] for e in events if 'context_compacted' in e)+ assert compacted['memory'] == 'COMPACTED' and compacted['keep_last'] == 8+ assert any(e.get('conversation_memory') == 'COMPACTED' for e in events)+ usage = next(e['context_usage'] for e in events if 'context_usage' in e)+ assert usage > 50+++def test_thinking_filter_streaming():+ f = ia._ThinkingFilter()+ vis1, th1 = f.feed('Hello <thi')+ vis2, th2 = f.feed('nk>hidden</think> world')+ vis3, th3 = f.flush()+ assert (vis1 + vis2 + vis3) == 'Hello world'+ assert th2 == 'hidden' or th1 == 'hidden' or th3 == 'hidden'+++if __name__ == '__main__':+ sys.exit(pytest.main([__file__, '-q']))