Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Small in-process supervisor for durable local Deep Research."""
from __future__ import annotations
import weakref
from core.training.account_jobs import account_is_retired, account_key, job_accounts
from utils.account_context import arun_as, current_account, run_as
import asyncio
import json
import os
import re
import sqlite3
import threading
import time
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
from typing import Any, AsyncIterator, Callable, NamedTuple
import httpx
from auth import storage as auth_storage
from core.inference.external_provider import _SERVED_WINDOW_PROVIDERS, ExternalProviderClient
from core.inference.llama_admission import llama_admission_config_from_env
from core.inference.message_content import message_text_with_pastes
from core.inference.providers import validate_provider_base_url
from core.inference.stream_errors import stream_error_from_chunk
from core.inference.tool_loop_controller import is_tool_error, strip_result_for_model
from core.inference.tools import (
EMPTY_SEARCH_RESULTS,
RAG_SOURCES_SENTINEL,
execute_mcp_tool,
execute_tool,
is_high_risk_tool_call,
mcp_search_tools,
)
from core.inference.web_access_policy import check_url_access, website_policy_prompt
from core.research.parsing import (
_MAX_PREVIEW_LABELS,
_next_unused_seed_action,
_normalize_research_state,
_normalize_synthesis_audit,
_parse_and_validate_action,
_parse_and_validate_plan,
_parse_json_object,
_recover_report_from_reasoning,
_report_after_boundary,
_streamed_titles,
)
from core.research.citations import (
_allowed_document_citations,
_citation_title,
_document_source_citation,
_mcp_source_label,
_validate_report,
)
from core.research.redaction import _sanitize_public_query, _shield_untrusted
from core.research.prompts import (
_AGENT_SYSTEM_PROMPT,
_REPORT_BOUNDARY_MARKER,
_REPORT_SYSTEM_PROMPT,
_SYNTHESIS_AUDIT_SYSTEM_PROMPT,
_planner_system_prompt,
_system_prompt_with_instructions,
)
from loggers import get_logger
from state.tool_policy import get_tool_policy
from storage import credential_secrets, providers_db
from storage import research_runs_db as db
from storage.studio_db import (
get_chat_message,
is_sqlite_busy_error,
list_chat_messages,
upsert_chat_message,
)
from utils.host_policy import (
LOOPBACK_FALLBACK_HOST,
dial_host,
prefer_loopback,
scope_request_host,
)
logger = get_logger(__name__)
_served_context_lengths: dict[tuple[Any, Any], int] = {}
_URL_BLOCK = re.compile(
r"Title:\s*(?P<title>[^\n]*)\nURL:\s*(?P<url>https?://[^\s]+)\nSnippet:\s*(?P<snippet>.*?)(?=\n\n---|\Z)",
re.DOTALL,
)
_OPENAI_RESPONSES_FIXED_SAMPLING_MODEL = re.compile(
r"^(?:gpt-6-astra(?:[-.]|$)|gpt-5(?:[-.]|$)|gpt-4\.5(?:[-.]|$)|"
r"o\d+(?:[-.]|$)|codex-mini(?:[-.]|$))"
)
_OPENAI_NON_REASONING_CHAT_ALIAS = re.compile(r"-chat(?:-latest)?$")
_WALL_CLOCK_TIMEOUT_CANCEL_MESSAGE = "research-wall-clock-timeout"
_MAX_ERROR_CHARS = 500
_MAX_CONTEXT_CHARS = 12_000
_MAX_CONTEXT_MESSAGE_CHARS = 4_000
_MAX_SYNTHESIS_EVIDENCE_CHARS = 32_000
# The synthesis prompt must fit context or it is silently truncated.
_MIN_SYNTHESIS_EVIDENCE_CHARS = 1_500
# Each section keeps a floor: overflow on a tiny context is recoverable, an empty prompt is not.
_MIN_QUESTION_CHARS = 800
_SYNTHESIS_EVIDENCE_CHARS_PER_TOKEN = 3.0
_SYNTHESIS_CONTEXT_RESERVE_TOKENS = 4_096
_SYNTHESIS_MAX_TOKENS = 16_384
# Nothing between here and the provider bounds what is sent, and published caps reach 384_000.
_SYNTHESIS_MAX_TOKENS_CEILING = 65_536
# Deliberately pessimistic: overshooting the wall clock loses the run, undershooting shortens it.
_SYNTHESIS_TOKENS_PER_SECOND = 50
_CAP_UNREADABLE = object()
_CAP_LOOKUP_ATTEMPTS = 3
_CAP_LOOKUP_RETRY_SECONDS = 0.2
_PROGRESS_FLUSH_CHARS = 512
_PROGRESS_FLUSH_SECONDS = 0.25
# _PROGRESS_FLUSH_CHARS / _PROGRESS_FLUSH_SECONDS * 64; both arms scale from the same length.
_PROGRESS_FLUSH_CHARS_PER_SECOND = 131_072
# Mirrors EXTERNAL_MIN_OUTPUT_TOKENS_BY_PROVIDER in the client module.
_EXTERNAL_MIN_OUTPUT_TOKENS_BY_PROVIDER = {"kimi": 16_000}
_EXTERNAL_MIN_OUTPUT_TOKENS = 64
# Below this loaded context the prompt scaffolding alone fills the window, so grounding is skipped.
_AUTO_SCRAPE_MIN_CONTEXT_TOKENS = 8_192
# Off by default; enable with UNSLOTH_RESEARCH_AUTO_SCRAPE=1; safe only with the context gate.
_AUTO_SCRAPE_TOP_K = 3
_AUTO_SCRAPE_TOTAL_CHARS = 6_000
_WEB_RAG_TOP_N = 6
_WEB_RAG_MIN_SCORE = 0.30
# routes.inference's 400 when nothing is loaded is transient, not a bad request.
_MODEL_WAIT_POLL_SECONDS = 2.0
# A model that keeps disappearing would re-send forever, so cap how many times one call may wait.
_MAX_MODEL_WAITS = 3
_NO_MODEL_LOADED_DETAIL = "No model loaded"
# Every "no grammar engine here" refusal says this (routes, grammar_constraint); a re-send fixes those only.
_NO_GRAMMAR_ENGINE_DETAIL = "needs a grammar engine"
# routes.inference reports the same unloaded state this way when auto-switch finds no local match.
_MODEL_NOT_FOUND_CODE = "model_not_found"
# routes.inference 503s with this while an auto-switch to the run's model is still loading.
_MODEL_SWITCH_FAILED_CODE = "model_switch_failed"
# Used when the 503 carries no usable Retry-After, and as the step between switch retries.
_MODEL_SWITCH_RETRY_SECONDS = 5.0
# Long enough for a load already in flight; past that the refusal is the honest answer.
_NAMED_MODEL_WAIT_SECONDS = 60.0
# Transport keepalives prevent HTTP read timeouts without proving that a model is progressing.
_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS = 120.0
_MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS = 120.0
# Cancellation is cooperative, so bound the unwind; a stuck iterator keeps a timed-out call open.
_STREAM_CLEANUP_TIMEOUT_SECONDS = 5.0
# The SSE comment routes/inference.py sends while queued, not while the backend is silent.
_ADMISSION_WAIT_COMMENT = ": admission-wait"
_ADMISSION_DONE_COMMENT = ": admission-done"
# Queue notices arrive on the configured heartbeat, so allow for a few missed ones.
_ADMISSION_HEARTBEAT_MISSES = 3
# Also the ceiling for any budget, so the poll loop stays bounded however long generation itself runs.
_DEFAULT_MODEL_TIMEOUT_SECONDS = 900.0
_MAX_MODEL_WAIT_BUDGET_SECONDS = 3600.0
# Past the hourly windows providers reset on, short of parking a run and its lease on one mistaken header.
_MAX_RATE_LIMIT_WAIT_SECONDS = 3600.0
# Retry waits measure against this: a key that expires mid-backoff fails auth without reaching the provider.
_MODEL_CALL_KEY_LIFETIME_SECONDS = 2 * 60 * 60
# Headroom so the named stall guards expire before HTTPX's own read timeout does.
_STREAM_READ_TIMEOUT_MARGIN_SECONDS = 30.0
def _model_wait_budget(run: dict) -> float:
"""One model wait's share of the request budget, clamped so the poll loop stays bounded."""
timeout = float(run["config"]["budgets"]["modelTimeoutSeconds"])
capped = min(timeout or _DEFAULT_MODEL_TIMEOUT_SECONDS, _MAX_MODEL_WAIT_BUDGET_SECONDS)
return capped / (_MAX_MODEL_WAITS + 1)
def _select_synthesis_report(content: str, reasoning: str) -> str:
content_report = _report_after_boundary(content, _REPORT_BOUNDARY_MARKER)
if content_report:
return content_report
reasoning_report = _report_after_boundary(reasoning, _REPORT_BOUNDARY_MARKER)
if content_report == "":
return reasoning_report or ""
if content.strip():
return content.strip()
return reasoning_report or ""
def _synthesis_needs_recovery(report: str, finish_reason: str | None) -> bool:
return finish_reason == "length" or not report
# Missing/unknown finish reasons may be a bare EOF, so only 'stop' counts as natural.
_NATURAL_FINISH_REASONS = frozenset({"stop"})
def _auto_scrape_default() -> int:
"""Default maxAutoScrape is 0 unless UNSLOTH_RESEARCH_AUTO_SCRAPE is 1/true (top-K) or an
explicit count clamped to [0, _AUTO_SCRAPE_TOP_K]."""
raw = os.environ.get("UNSLOTH_RESEARCH_AUTO_SCRAPE", "").strip().lower()
if not raw:
return 0
if raw in ("0", "false", "no", "off"):
return 0
if raw in ("1", "true", "yes", "on"):
return _AUTO_SCRAPE_TOP_K
try:
return max(0, min(int(raw), _AUTO_SCRAPE_TOP_K))
except ValueError:
return 0
# Nav menus, language sidebars and percent-encoded link lists are not evidence and derail retrieval.
_MD_LINK = re.compile(r"\[([^\]]*)\]\([^)]*\)")
_PERCENT_ESCAPE = re.compile(r"%[0-9A-Fa-f]{2}")
_LIST_PREFIX = re.compile(r"^(?:[\*\-\+•]|\d+[.)])\s")
_BLANK_RUN = re.compile(r"\n\n\n+")
# Tracking URLs are single 80+ char tokens that small models echo.
_LONG_TOKEN = re.compile(r"\S{80,}")
def _clean_scraped_text(text: str) -> str:
kept: list[str] = []
for line in text.splitlines():
stripped = line.strip()
if not stripped:
kept.append("")
continue
if len(_PERCENT_ESCAPE.findall(stripped)) >= 4:
continue
if _LONG_TOKEN.search(stripped):
continue
prose = _MD_LINK.sub(r"\1", stripped).strip()
if "](" in stripped and (
_LIST_PREFIX.match(stripped) or len(prose) <= max(30, len(stripped) // 3)
):
continue
kept.append(line)
return _BLANK_RUN.sub("\n\n", "\n".join(kept)).strip()
class RunCancelled(Exception):
pass
class LeaseLost(Exception):
pass
class ModelOutputIdleTimeout(httpx.ReadTimeout):
# Default message: the stream reader raises the class the deadline names.
def __init__(self, message: str = "Local model stopped producing output"):
super().__init__(message)
class ModelFirstOutputTimeout(httpx.ReadTimeout):
def __init__(self, message: str = "Local model never produced output"):
super().__init__(message)
class ModelWallClockTimeout(httpx.ReadTimeout):
pass
# Every separator, not just "\n": one survivor lets provider text open a block of its own.
_LINE_SEPARATOR = re.compile(r"[\r\n\v\f\x1c-\x1e\x85\u2028\u2029]+")
def _safe_error(exc: BaseException) -> str:
if isinstance(exc, ModelFirstOutputTimeout):
return "Local model never started producing output"
if isinstance(exc, ModelOutputIdleTimeout):
return "Local model stopped producing output before completion"
if isinstance(exc, ModelWallClockTimeout):
return "Local model request exhausted its total time budget"
if isinstance(exc, httpx.TimeoutException):
return "Local model request timed out"
if isinstance(exc, httpx.HTTPStatusError):
return f"Local model request failed with HTTP {exc.response.status_code}"
# str() must stay the server text: routes/inference.py's token-count regex matches it.
friendly = getattr(exc, "friendly", None)
text = friendly if isinstance(friendly, str) and friendly else str(exc)
text = _LINE_SEPARATOR.sub(" ", text).strip()
return (text or exc.__class__.__name__)[:_MAX_ERROR_CHARS]
def _extract_text(message: dict) -> str:
return message_text_with_pastes(message).strip()
def _research_question_context(
thread_id: str,
user_message_id: str,
override: str = "",
) -> tuple[str, str]:
"""The handoff override folds in the conversation and wins; the raw user message is the fallback."""
messages = list_chat_messages(thread_id)
by_id = {str(message["id"]): message for message in messages}
user = by_id.get(user_message_id)
question = override.strip() or _extract_text(user or {})
if not user:
return question, "[]"
ancestors: list[dict] = []
seen = {user_message_id}
parent_id = user.get("parentId")
while isinstance(parent_id, str) and parent_id and parent_id not in seen:
seen.add(parent_id)
parent = by_id.get(parent_id)
if parent is None:
break
ancestors.append(parent)
parent_id = parent.get("parentId")
ancestors.reverse()
remaining = _MAX_CONTEXT_CHARS
turns: list[dict[str, str]] = []
for message in reversed(ancestors):
text = _extract_text(message).strip()
role = str(message.get("role") or "").strip()
if not text or role not in {"user", "assistant"}:
continue
text = text[:_MAX_CONTEXT_MESSAGE_CHARS]
if len(text) > remaining:
text = text[:remaining]
if not text:
break
turns.append({"role": role, "content": text})
remaining -= len(text)
if remaining <= 0:
break
turns.reverse()
return question, json.dumps(turns, ensure_ascii = False)
def _positive_int_or_none(value: object) -> int | None:
return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None
def _peek_inference_backend() -> Any:
"""Returns the existing orchestrator or None; building one would block the loop on a torch import."""
from core.inference import get_inference_backend
# Native / transformers: the orchestrator the API layer reads (not the subprocess singleton).
try:
from core.inference.orchestrator import get_inference_backend as _real
from core.inference.orchestrator import peek_inference_backend
except Exception:
return get_inference_backend()
return (
get_inference_backend() if get_inference_backend is not _real else peek_inference_backend()
)
def _external_provider_run(inference: dict[str, Any] | None) -> bool:
return bool((inference or {}).get("providerType"))
def _run_inference_request(run: dict) -> dict[str, Any]:
return (run.get("config") or {}).get("inferenceRequest") or {}
def _served_window_key(inference: dict[str, Any]) -> tuple[Any, Any]:
return inference.get("providerId"), inference.get("externalModel")
def _saved_connection_client(run: dict) -> ExternalProviderClient | None:
inference = _run_inference_request(run)
provider_id = inference["providerId"]
provider = providers_db.get_provider(provider_id)
if provider is None or not provider["is_enabled"]:
return None
headers = provider.get("extra_headers")
client = ExternalProviderClient(
provider_type = provider["provider_type"],
base_url = validate_provider_base_url(provider["base_url"]),
api_key = credential_secrets.get_provider_api_key(provider_id) or "",
api_type = provider.get("api_type", "chat_completions"),
**({"extra_headers": headers} if headers else {}),
)
client.set_header_context(f"research:{run['id']}", inference["externalModel"])
return client
async def _guarded_connection_client(run: dict) -> ExternalProviderClient | None:
from routes.provider_credentials import provider_config_guard
provider_id = _run_inference_request(run)["providerId"]
provider = await asyncio.to_thread(providers_db.get_provider, provider_id)
if provider is None:
return None
# A concurrent edit must not pair the old endpoint with the new key.
async with provider_config_guard(
provider_id, shared_by_owner = bool(provider.get("shared_by_owner"))
):
return await asyncio.to_thread(_saved_connection_client, run)
async def _refresh_served_context_length(run: dict) -> None:
inference = _run_inference_request(run)
window = None
if inference.get("providerType") in _SERVED_WINDOW_PROVIDERS:
try:
client = await _guarded_connection_client(run)
if client is not None:
window = await client.served_context_window(inference["externalModel"])
except Exception:
logger.debug("research.served_window_probe_failed", exc_info = True)
if window:
_served_context_lengths[_served_window_key(inference)] = window
else:
_served_context_lengths.pop(_served_window_key(inference), None)
def _loaded_context_length(inference: dict[str, Any] | None = None) -> int | None:
"""Active model's context window, or None; reads the orchestrator the routes use, not the ML worker."""
if _external_provider_run(inference):
return _served_context_lengths.get(_served_window_key(inference))
try:
from routes.inference import get_llama_cpp_backend
llama = get_llama_cpp_backend()
if getattr(llama, "is_loaded", False):
ctx = _positive_int_or_none(getattr(llama, "context_length", None))
if ctx is not None:
return ctx
except Exception:
logger.debug("research.context_probe_llama_failed", exc_info = True)
try:
backend = _peek_inference_backend()
name = getattr(backend, "active_model_name", None)
models = getattr(backend, "models", {}) or {}
info = models.get(name) if (name and isinstance(models, dict)) else None
for candidate in (
(info or {}).get("context_length"),
getattr(backend, "context_length", None),
getattr(backend, "max_seq_length", None),
):
ctx = _positive_int_or_none(candidate)
if ctx is not None:
return ctx
except Exception:
logger.debug("research.context_probe_failed", exc_info = True)
return None
def _estimate_prompt_tokens(messages: list[dict]) -> int:
"""Conservative token estimate for clamping max_tokens; same chars-per-token heuristic as synthesis."""
chars = 0
for message in messages:
content = message.get("content")
if isinstance(content, str):
chars += len(content)
continue
if isinstance(content, list):
for part in content:
if isinstance(part, dict):
text = part.get("text")
if isinstance(text, str):
chars += len(text)
return max(1, int(chars / _SYNTHESIS_EVIDENCE_CHARS_PER_TOKEN) + len(messages) * 4)
def _clamp_max_tokens_for_context(
requested: int,
messages: list[dict],
*,
context_length: int | None = None,
inference: dict[str, Any] | None = None,
) -> int:
ctx = context_length if context_length is not None else _loaded_context_length(inference)
if not ctx:
return requested
available = max(1, ctx - _estimate_prompt_tokens(messages))
return max(1, min(requested, available))
def _resolve_max_tokens(
max_tokens: int | None, inference: dict[str, Any], messages: list[dict]
) -> int:
if max_tokens is None:
requested = min(int(inference.get("maxTokens") or 4096), 8192)
else:
# Re-capping a budget the caller already resolved is what truncated the report.
requested = max(1, int(max_tokens))
# Defers, not short-circuits: a provider run has no window unless its server reports one.
return _clamp_max_tokens_for_context(requested, messages, inference = inference)
def _synthesis_max_tokens(inference: dict[str, Any], model_timeout_seconds: Any = None) -> int:
"""Output budget between _report_floor and the ceiling; the published cap is stated, not proven."""
if not inference.get("providerType"):
return _SYNTHESIS_MAX_TOKENS
floor = _provider_output_floor(inference.get("providerType"))
saved = _saved_connection_cap(inference.get("providerId"))
if saved is _CAP_UNREADABLE:
# Neither cap is confirmable: take the smaller, since losing a run to a transient lock costs more.
unconfirmed = _positive_int_or_none(inference.get("maxOutputTokens"))
return max(min(unconfirmed or _SYNTHESIS_MAX_TOKENS, _SYNTHESIS_MAX_TOKENS), floor)
resolved = _positive_int_or_none(inference.get("maxOutputTokens"))
if resolved and not saved and inference.get("maxOutputTokensFromSavedCap") is True:
# Only the saved cap supports this number; on undocumented models, clearing it is the field's point.
resolved = None
if resolved:
# The run is durable, so the cap can have been lowered since the client resolved this.
budget = min(resolved, saved) if saved else resolved
else:
# Legacy run: the saved cap is connection-wide, so raising on it would be a guess.
budget = _SYNTHESIS_MAX_TOKENS
# Below its provider floor a thinking answer is cut off before the report starts.
return max(
min(budget, _synthesis_budget_ceiling(model_timeout_seconds)),
_report_floor(inference),
floor,
)
def _report_floor(inference: dict[str, Any]) -> int:
"""Pre-ceiling default: only a model's own published limit may lower it, never a chat override."""
published = _positive_int_or_none(inference.get("maxOutputTokensPublished"))
if published:
return min(_SYNTHESIS_MAX_TOKENS, published)
return _SYNTHESIS_MAX_TOKENS
def _synthesis_budget_ceiling(model_timeout_seconds: Any = None) -> int:
"""Most this run can ask for, never below the previous default; a timeout aborts without the report."""
ceiling = _SYNTHESIS_MAX_TOKENS_CEILING
timeout = model_timeout_seconds
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
timeout = None
# 0 is "unlimited" in the budgets schema.
if timeout and timeout > 0:
ceiling = min(ceiling, int(timeout * _SYNTHESIS_TOKENS_PER_SECOND))
return max(ceiling, _SYNTHESIS_MAX_TOKENS)
def _provider_output_floor(provider_type: object) -> int:
if not isinstance(provider_type, str):
return _EXTERNAL_MIN_OUTPUT_TOKENS
return _EXTERNAL_MIN_OUTPUT_TOKENS_BY_PROVIDER.get(provider_type, _EXTERNAL_MIN_OUTPUT_TOKENS)
def _saved_connection_cap(provider_id: object) -> int | None | object:
"""An unreadable cap is not uncapped: it may have been lowered since the durable run was created."""
if not isinstance(provider_id, str):
return None
for attempt in range(_CAP_LOOKUP_ATTEMPTS):
try:
provider = providers_db.get_provider(provider_id) or {}
except Exception:
logger.debug("research.provider_cap_probe_failed", exc_info = True)
# A read that lost the writer lock is transient, and this runs off the loop.
if attempt + 1 < _CAP_LOOKUP_ATTEMPTS:
time.sleep(_CAP_LOOKUP_RETRY_SECONDS)
continue
return _CAP_UNREADABLE
return _positive_int_or_none(provider.get("max_output_tokens"))
return _CAP_UNREADABLE
def _custom_responses_rejects_sampling(inference: dict[str, Any]) -> bool:
"""Whether this research hop targets fixed-sampling OpenAI Responses semantics."""
if inference.get("providerType") != "custom":
return False
provider_id = inference.get("providerId")
if not isinstance(provider_id, str) or not provider_id:
return False
try:
provider = providers_db.get_provider(provider_id) or {}
except Exception:
logger.debug("research.provider_api_type_probe_failed", exc_info = True)
return False
if provider.get("provider_type") != "custom" or provider.get("api_type") != "responses":
return False
model = str(inference.get("externalModel") or inference.get("model") or "").strip().lower()
if _OPENAI_NON_REASONING_CHAT_ALIAS.search(model):
return False
# Upstream contract: codex-mini and gpt-4.5 reject sampling fields regardless of UI flags.
return _OPENAI_RESPONSES_FIXED_SAMPLING_MODEL.match(model) is not None
def _normalize_completion_usage(raw: Any) -> dict[str, int] | None:
if not isinstance(raw, dict):
return None
usage: dict[str, int] = {}
for key in ("prompt_tokens", "completion_tokens", "total_tokens"):
value = raw.get(key)
if isinstance(value, (int, float)):
usage[key] = int(value)
return usage or None
def _completion_hit_context_wall(
usage: dict[str, int] | None,
*,
requested_max_tokens: int,
context_length: int | None = None,
inference: dict[str, Any] | None = None,
) -> bool:
if not usage:
return False
prompt_tokens = int(usage.get("prompt_tokens") or 0)
completion_tokens = int(usage.get("completion_tokens") or 0)
total_tokens = int(usage.get("total_tokens") or prompt_tokens + completion_tokens)
ctx = context_length if context_length is not None else _loaded_context_length(inference)
if ctx is not None and total_tokens >= ctx:
return True
return completion_tokens < requested_max_tokens
def _synthesis_length_limit_error(
usage: dict[str, int] | None,
*,
requested_max_tokens: int,
inference: dict[str, Any] | None = None,
) -> str:
# Saved connections skip loaded context; their cap is the provider's output limit, not Context Length.
if _external_provider_run(inference):
return "Connected model report reached its output limit before completion"
if _completion_hit_context_wall(
usage, requested_max_tokens = requested_max_tokens, inference = inference
):
return (
"Local model report hit the loaded context window before completion. "
"Increase Context Length in chat settings or reduce the research evidence size."
)
return "Local model report reached its output limit before completion"
async def _response_format_unsupported(response: httpx.Response) -> bool:
"""Only the API's explicit guided-decoding refusal permits a prompt-only retry."""
if response.status_code != 400:
return False
try:
await response.aread()
body = response.json()
except Exception:
return False
error = body.get("error") if isinstance(body, dict) else None
return (
isinstance(error, dict)
and error.get("code") == "unsupported_parameter"
and error.get("param") == "response_format"
# Code and param alone also match the audio and tool-loop refusals, which no re-send fixes.
and _NO_GRAMMAR_ENGINE_DETAIL in str(error.get("message") or "")
)
async def _model_unloaded(response: httpx.Response) -> str | None:
"""Names the transient refusal (empty, named, switching) a durable run waits out; None for others."""
if response.status_code not in (400, 404, 503):
return None
try:
body = await response.aread()
except Exception:
return None
text = body.decode("utf-8", "replace")
if response.status_code == 400:
return "empty" if _NO_MODEL_LOADED_DETAIL in text else None
if response.status_code == 503:
return "switching" if _MODEL_SWITCH_FAILED_CODE in text else None
return "named" if _MODEL_NOT_FOUND_CODE in text else None
def _retry_after_delay(raw: object) -> float | None:
"""Parses Retry-After as seconds or an HTTP-date, since CDNs send dates; None when absent or past."""
if raw is None:
return None
text = str(raw).strip()
if not text:
return None
try:
delay = float(text)
except ValueError:
try:
at = parsedate_to_datetime(text)
except (IndexError, TypeError, ValueError):
return None
if at is None:
return None
if at.tzinfo is None:
# RFC 9110 dates are GMT; a form that omits the zone is not a local time.
at = at.replace(tzinfo = timezone.utc)
delay = (at - datetime.now(timezone.utc)).total_seconds()
return delay if delay > 0 else None
def _retry_after_seconds(response: httpx.Response) -> float | None:
"""The response's Retry-After delay in seconds, or None when it is absent or already past."""
return _retry_after_delay(response.headers.get("Retry-After"))
async def _peek_stream_head(lines: AsyncIterator[str]) -> str | None:
"""Returns only the first line: queue notices belong to another loop; a refusal is always first."""
async for line in lines:
return line
return None
def _stream_rate_limit_delay(head: str | None) -> float | None:
"""Retry delay from a proxied 429 line: None if the stream has no such line, 0.0 if no delay."""
if head is None or not head.startswith("data:"):
return None
try:
chunk = json.loads(head[5:].strip())
except (TypeError, ValueError):
return None
error = chunk.get("error") if isinstance(chunk, dict) else None
if not isinstance(error, dict):
return None
if str(error.get("code")) != "429" and error.get("type") != "rate_limit_error":
return None
metadata = error.get("metadata")
if isinstance(metadata, dict) and metadata.get("terminal"):
# Quota exhausted rather than throttled: no wait clears it, so surface it now.
return None
requested = error.get("retry_after")
if requested is None and isinstance(metadata, dict):
requested = metadata.get("retry_after")
return _retry_after_delay(requested) or 0.0
async def _with_head(head: str | None, rest: AsyncIterator[str]) -> AsyncIterator[str]:
"""Yields ``head`` (if not None) then ``rest``; a blank SSE separator line is still a line."""
if head is not None:
yield head
async for line in rest:
yield line
def _rate_limit_wait(requested: float, remaining: float, headroom: float) -> float:
"""Never reserve all of what is left for re-send room, or every wait collapses to zero."""
headroom = min(headroom, remaining / 2)
return max(0.0, min(requested, _MAX_RATE_LIMIT_WAIT_SECONDS, remaining - headroom))
def _local_model_ready() -> bool:
"""Whether the local chat-completions path has a model to serve, using the same two checks
routes.inference.openai_chat_completions makes before it 400s. Fails open when neither
backend can be probed, so a probe failure can only run a request, never withhold one."""
probed = False
try:
from routes.inference import get_llama_cpp_backend
if getattr(get_llama_cpp_backend(), "is_loaded", False):
return True
probed = True
except Exception:
logger.debug("research.model_probe_llama_failed", exc_info = True)
try:
# No orchestrator yet is a real answer (nothing is loaded), not a failed probe.
if getattr(_peek_inference_backend(), "active_model_name", None):
return True
probed = True
except Exception:
logger.debug("research.model_probe_failed", exc_info = True)
return not probed
def _fit_source_catalog(catalog: str, max_chars: int) -> str:
"""Drops whole catalog entries from the tail, never mid-entry, so every kept URL stays citable."""
if max_chars <= 0 or len(catalog) <= max_chars:
return catalog if max_chars > 0 else ""
kept: list[str] = []
used = 0
for entry in catalog.split("\n\n") if "\n\n" in catalog else catalog.splitlines(True):
used += len(entry)
if used > max_chars:
break
kept.append(entry)
return ("".join(kept) if not kept or kept[0].endswith("\n") else "\n\n".join(kept)).rstrip()
def _fit_synthesis_catalogs(
web_entries: list[str], document_entries: list[str], max_chars: int
) -> tuple[str, str]:
limits = _water_fill([len("\n".join(web_entries)), len("\n".join(document_entries))], max_chars)
fitted = []
for entries, limit in zip((web_entries, document_entries), limits):
kept, used = [], -1
for entry in entries:
used += len(entry) + 1
if used > limit:
break
kept.append(entry)
fitted.append("\n".join(kept))
return fitted[0], fitted[1]
def _fit_decision_inputs(
question: str, plan: dict, system_chars: int, total_budget: int | None
) -> tuple[str, str]:
"""Fit the decision question and plan while keeping the plan valid JSON."""
full_plan = json.dumps(plan, ensure_ascii = False)
if total_budget is None:
minimum_question_chars = min(len(question), _MIN_QUESTION_CHARS)
research_reserve = 0
plan_budget = len(full_plan)
else:
input_budget = max(0, total_budget - system_chars)
if input_budget < len("{}"):
raise ValueError("Loaded model context is too small for a research decision")
minimum_question_chars = min(
len(question),
_MIN_QUESTION_CHARS,
max(0, input_budget - len("{}")),
)
research_reserve = min(
_MIN_SYNTHESIS_EVIDENCE_CHARS,
max(0, input_budget - minimum_question_chars - len("{}")),
)
plan_budget = max(0, input_budget - minimum_question_chars - research_reserve)
if len(full_plan) <= plan_budget:
fitted_plan = full_plan
else:
fitted_plan = "{}"
steps = plan.get("steps") if isinstance(plan.get("steps"), list) else []
for count in range(len(steps) + 1):
candidate = json.dumps(
{"title": plan.get("title") or "Research plan", "steps": steps[:count]},
ensure_ascii = False,
)
if len(candidate) > plan_budget:
break
fitted_plan = candidate
question_budget = _trimmable_budget(
total_budget,
system_chars + len(fitted_plan) + research_reserve,
_MAX_SYNTHESIS_EVIDENCE_CHARS,
)
return question[:question_budget], fitted_plan
@asynccontextmanager
async def _wall_clock_timeout(seconds: float | None) -> AsyncIterator[None]:
"""Use asyncio.timeout when available, with the same behavior on Python 3.9/3.10."""
if seconds is None:
yield
return
timeout = getattr(asyncio, "timeout", None)
if timeout is not None:
async with timeout(seconds):
yield
return
task = asyncio.current_task()
if task is None:
yield
return
expired = False
def cancel() -> None:
nonlocal expired
expired = True
task.cancel(_WALL_CLOCK_TIMEOUT_CANCEL_MESSAGE)
handle = asyncio.get_running_loop().call_later(seconds, cancel)
try:
yield
except asyncio.CancelledError as exc:
if expired and exc.args == (_WALL_CLOCK_TIMEOUT_CANCEL_MESSAGE,):
raise asyncio.TimeoutError from exc
raise
finally:
handle.cancel()
def _prompt_char_budget(reserve_tokens: int, inference: dict[str, Any] | None = None) -> int | None:
"""Prompt char budget; the output reserve is capped at half the window so a reserve cannot empty it."""
ctx = _loaded_context_length(inference)
if not ctx:
return None
reserve = min(reserve_tokens, max(1, ctx // 2))
return int(max(0, ctx - reserve) * _SYNTHESIS_EVIDENCE_CHARS_PER_TOKEN)
def _trimmable_budget(total: int | None, fixed_chars: int, hard_cap: int) -> int:
"""Chars left for a trimmable section; 0 rather than a floor, since a short report beats a failure."""
if total is None:
return hard_cap
return max(0, min(hard_cap, total - fixed_chars))
def _synthesis_evidence_budget(
fixed_chars: int = 0, inference: dict[str, Any] | None = None
) -> int:
"""Char budget for synthesis evidence (full cap when the context is unknown)."""
return _trimmable_budget(
_prompt_char_budget(_SYNTHESIS_CONTEXT_RESERVE_TOKENS, inference),
fixed_chars,
_MAX_SYNTHESIS_EVIDENCE_CHARS,
)
def _water_fill(lengths: list[int], available: int) -> list[int]:
limits = [0] * len(lengths)
for position, index in enumerate(sorted(range(len(lengths)), key = lambda i: lengths[i])):
limits[index] = min(lengths[index], available // (len(lengths) - position))
available -= limits[index]
return limits
def _truncate_evidence(text: str, limit: int) -> str:
suffix = "\n[Evidence truncated]"
if len(text) <= limit:
return text
if limit <= len(suffix):
return text[:limit]
return text[: limit - len(suffix)].rstrip() + suffix
def _bounded_synthesis_evidence(
notes: list[str | tuple[str, ...]], max_chars: int = _MAX_SYNTHESIS_EVIDENCE_CHARS
) -> str:
if not notes:
return "(none)"
if max_chars <= 0:
return ""
# Split evenly: a per-note floor lets early notes eat the budget and drop later steps entirely.
separator = "\n\n"
available = max(0, max_chars - len(separator) * (len(notes) - 1))
# A (heading, *parts) note pays its heading once and splits the rest of its share across parts.
texts = [
note if isinstance(note, str) else f"{note[0]}\n" + separator.join(note[1:])
for note in notes
]
limits = _water_fill([len(text) for text in texts], available)
bounded = []
for note, text, limit in zip(notes, texts, limits):
parts = [] if isinstance(note, str) else list(note[1:])
room = limit - len(text) + sum(map(len, parts))
if len(text) <= limit or not parts or room <= 0:
bounded.append(_truncate_evidence(text, limit))
continue
part_limits = _water_fill([len(part) for part in parts], room)
bounded.append(
f"{note[0]}\n"
+ separator.join(
_truncate_evidence(part, part_limit) for part, part_limit in zip(parts, part_limits)
)
)
return separator.join(bounded)[:max_chars]
def _fit_synthesis_context(
notes: list[str | tuple[str, ...]],
prioritized_payloads: list[dict[str, Any]],
fixed_chars: int = 0,
inference: dict[str, Any] | None = None,
) -> tuple[str, list[str]]:
"""Shares the budget across JSON blocks by priority; an oversized one becomes {}, keeping JSON valid."""
total_budget = _synthesis_evidence_budget(fixed_chars, inference)
placeholder = "{}"
minimum_evidence = min(_MIN_SYNTHESIS_EVIDENCE_CHARS, total_budget)
remaining_payload_budget = max(
0,
total_budget - minimum_evidence - len(placeholder) * len(prioritized_payloads),
)
serialized_payloads = []
for payload in prioritized_payloads:
candidate = json.dumps(payload, ensure_ascii = False) if payload else placeholder
extra_chars = max(0, len(candidate) - len(placeholder))
if extra_chars <= remaining_payload_budget:
serialized_payloads.append(candidate)
remaining_payload_budget -= extra_chars
else:
serialized_payloads.append(placeholder)
evidence_budget = max(0, total_budget - sum(map(len, serialized_payloads)))
return _bounded_synthesis_evidence(notes, evidence_budget), serialized_payloads
def _merge_scraped_evidence(raw_result: str, scraped_section: str) -> str:
"""Appends grounded excerpts after the snippets; replacing snippets lost answers to distractors."""
raw = (raw_result or "").strip()
scraped = (scraped_section or "").strip()
if not scraped:
return raw_result
if not raw:
return scraped_section
return f"{raw}\n\nAdditional detail retrieved from the pages above:\n{scraped}"
def _split_rag_result(result: str) -> tuple[str, list[dict[str, Any]]]:
if RAG_SOURCES_SENTINEL not in result:
return result, []
text, raw_sources = result.split(RAG_SOURCES_SENTINEL, 1)
try:
candidates = json.loads(raw_sources)
except (TypeError, ValueError, json.JSONDecodeError):
return text.rstrip(), []
if not isinstance(candidates, list):
return text.rstrip(), []
sources = []
for candidate in candidates:
if not isinstance(candidate, dict):
continue
sources.append(
{
"kind": "knowledge_base",
"chunkId": candidate.get("chunkId"),
"documentId": candidate.get("documentId"),
"filename": str(candidate.get("filename") or "Document")[:500],
"page": candidate.get("page"),
"score": candidate.get("score"),
"snippet": str(candidate.get("text") or "")[:2000],
}
)
return text.rstrip(), sources
def _mcp_evidence(sources: list[dict]) -> str:
if not sources:
return ""
share = 6000 // len(sources)
text = "\n\n".join(
f"{_document_source_citation(source)}\n{(source.get('snippet') or '')[:share]}"
for source in sources
)
return f"\n\nMCP tools:\n{text}"
def _research_step_failed(web_result: str, rag_sources: list[dict]) -> bool:
"""empty searches must report missing evidence even when the tool succeeds."""
if rag_sources:
return False
return is_tool_error(web_result) or web_result.strip() in EMPTY_SEARCH_RESULTS
def _preferred_step_error(current: str, candidate: str) -> str:
"""engine errors need retries; empty searches need new queries, so preserve engine errors."""
if not candidate:
return current
if is_tool_error(current) and not is_tool_error(candidate):
return current
return candidate
def _run_moved_on(fresh: dict | None, attempt: int) -> bool:
"""True once the user has re-pointed the run; a stale terminal reply would stamp the new question."""
if not fresh:
return True
return int(fresh.get("retryCount") or 0) != attempt
def _cited_sources(run: dict) -> list[dict]:
"""Sources trimmed to the budget: past it, the model never saw them to cite."""
max_sources = int(((run.get("config") or {}).get("budgets") or {}).get("maxSources") or 0)
return list(run.get("sources") or [])[:max_sources]
# A WAL commit on a busy disk has held the writer lock for 37s; under the 120-second lease.
_TERMINAL_WRITE_DEADLINE_SECONDS = 60.0
_TERMINAL_WRITE_RETRY_SECONDS = 1.0
def _as_literal_markdown(text: str) -> str:
"""Provider text for a Markdown surface, as the one inline context nothing reparses."""
longest = max((len(run) for run in re.findall(r"`+", text)), default = 0)
fence = "`" * (longest + 1)
# A span whose content touches a backtick needs padding, which the renderer then strips.
pad = " " if text.startswith("`") or text.endswith("`") else ""
return f"{fence}{pad}{text}{pad}{fence}"
def _report_under_notice(report: str, lead: str, notice: str) -> str:
"""A report under a notice; above it, since a cut report can end in an unterminated fence."""
return f"> **{lead}** {notice}\n\n{report.lstrip()}"
class _ReportDraft(NamedTuple):
"""``whole`` is whether the provider said the model stopped of its own accord, which an
interrupted stream can still have done; ``reason`` is why it stops short, when known."""
text: str
whole: bool
reason: str = ""
def _update_assistant(
run: dict,
text: str,
status: str,
sources: list[dict] | None = None,
reasoning: str = "",
completion_worker_id: str | None = None,
) -> None:
if account_is_retired():
return
message_id = db.discover_and_bind_assistant_message(run["id"])
if not message_id:
if status not in db.TERMINAL_STATUSES:
return
message_id, _created = db.create_and_bind_terminal_fallback(
run["id"],
text = text,
status = status,
sources = sources,
completion_worker_id = completion_worker_id,
expected_attempt = int(run.get("retryCount") or 0),
)
if not message_id:
return
existing = get_chat_message(run["threadId"], message_id) or {}
content = existing.get("content") if isinstance(existing.get("content"), list) else []
# Only replace this worker's text/source parts; retain artifacts, reasoning, and other extensions.
replaced_types = {"text", "source"}
if reasoning:
replaced_types.add("reasoning")
retained = [
part
for part in content
if not isinstance(part, dict)
or part.get("type") not in replaced_types
or part.get("researchRunId") not in (None, run["id"])
]
if reasoning:
retained.append({"type": "reasoning", "text": reasoning, "researchRunId": run["id"]})
retained.append({"type": "text", "text": text, "researchRunId": run["id"]})
for source in sources or []:
retained.append(
{
"type": "source",
"sourceType": "url",
"id": source["url"],
"url": source["url"],
"title": source.get("title") or source["url"],
"metadata": {"description": source.get("snippet") or ""},
"researchRunId": run["id"],
}
)
metadata = dict(existing.get("metadata") or {})
metadata.update(
{
"researchRunId": run["id"],
"researchStatus": status,
"researchPlanRevision": run.get("planRevision", 0),
"serverManaged": True,
}
)
upsert_chat_message(
{
"id": message_id,
"threadId": run["threadId"],
"parentId": existing.get("parentId") or run["userMessageId"],
"role": "assistant",
"content": retained,
"attachments": existing.get("attachments"),
"metadata": metadata,
"createdAt": existing.get("createdAt") or db.now_ms(),
},
allow_research_update = True,
expected_research_run_id = run["id"],
expected_research_attempt = int(run.get("retryCount") or 0),
)
_supervisors = weakref.WeakSet()
class ResearchSupervisor:
def __init__(
self,
app: Any,
poll_seconds: float = 0.5,
) -> None:
_supervisors.add(self)
self.job_account = None
self.app = app
self.poll_seconds = poll_seconds
self.worker_id = uuid.uuid4().hex
self._stopping = asyncio.Event()
self._task: asyncio.Task | None = None
self._cancel_events: dict[str, threading.Event] = {}
self._lost_leases: set[str] = set()
# In memory, not read back on failure: every write that would store a draft can itself fail.
self._report_drafts: dict[str, _ReportDraft] = {}
self._last_claim_account: str | None = None
def start(self) -> None:
for account in job_accounts():
run_as(account, db.recover_expired)
if self._task is None:
self._task = asyncio.create_task(self._loop(), name = "research-supervisor")
async def stop(self) -> None:
self._stopping.set()
try:
if self._task is not None:
for cancel_event in self._cancel_events.values():
cancel_event.set()
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
# Polling is intentionally sufficient for one local process; requests never own tasks.
pass
finally:
for account in job_accounts():
await asyncio.to_thread(run_as, account, db.release_worker_leases, self.worker_id)
def wake(self) -> None:
pass
def cancel(self, run_id: str) -> None:
self._cancel_events.setdefault(account_key(run_id), threading.Event()).set()
def _cancel_event(self, run_id: str) -> threading.Event:
return self._cancel_events.setdefault(account_key(run_id), threading.Event())
async def _check_active(self, run_id: str) -> None:
if account_is_retired():
raise RunCancelled()
if account_key(run_id) in self._lost_leases:
raise LeaseLost()
cancelled, owns_lease = await asyncio.gather(
asyncio.to_thread(db.is_cancel_requested, run_id),
asyncio.to_thread(db.owns_lease, run_id, self.worker_id),
)
if cancelled:
self.cancel(run_id)
raise RunCancelled()
if not owns_lease:
raise LeaseLost()
if self._cancel_event(run_id).is_set():
raise RunCancelled()
async def _auto_scrape_sources(
self,
run: dict,
question: str,
step_sources: list[dict],
fetched_urls: set[str],
*,
limit: int,
tool_timeout: int,
website_policy: dict | None,
) -> tuple[str, list[str]]:
"""Reads up to limit URLs concurrently, dropping failures; the caller enforces cancellation."""
cap = max(0, min(limit, _AUTO_SCRAPE_TOP_K))
if cap <= 0:
return "", []
targets = []
for source in step_sources:
url = str(source.get("url") or "")
if url and url not in fetched_urls:
targets.append(source)
if len(targets) >= cap:
break
if not targets:
return "", []
cancel_event = self._cancel_event(run["id"])
results = await asyncio.gather(
*(
asyncio.to_thread(
execute_tool,
"web_search",
{"url": source["url"]},
cancel_event = cancel_event,
timeout = tool_timeout,
website_policy = website_policy,
)
for source in targets
),
return_exceptions = True,
)
pages = []
fetched = []
for source, result in zip(targets, results):
if isinstance(result, BaseException) or not isinstance(result, str):
continue
body = strip_result_for_model(result, "web_search")
if is_tool_error(body):
continue
body = _clean_scraped_text(body)
if not body:
continue
fetched.append(source["url"])
pages.append(
{
"text": body,
"title": source.get("title") or source["url"],
"url": source["url"],
}
)
if not pages:
return "", []
# Runs off the event loop, since embedding and the sqlite/vec index work are CPU/GPU bound.
from core.rag import web_rank
section, _sources = await asyncio.to_thread(
web_rank.retrieve_web_chunks,
pages,
question,
top_n = _WEB_RAG_TOP_N,
min_score = _WEB_RAG_MIN_SCORE,
char_budget = _AUTO_SCRAPE_TOTAL_CHARS,
)
if not section:
return "", []
return (
"Relevant passages retrieved from the top results (already read):\n\n" + section,
fetched,
)
async def _search_mcp_tools(
self, run: dict, tools: list[dict], query: str, position: int, tool_timeout: int
) -> list[dict]:
labels = {
tool["name"]: _mcp_source_label({"filename": f"{tool['serverName']} · {tool['tool']}"})
for tool in tools
}
label_values = list(labels.values())
labels = {
name: f"{label} ({name})" if label_values.count(label) > 1 else label
for name, label in labels.items()
}
cancel_event = self._cancel_event(run["id"])
calls = [
(tool, {tool["argument"]: query})
for tool in tools
if not is_high_risk_tool_call(tool["name"], {tool["argument"]: query})
]
results = await asyncio.gather(
*(
asyncio.to_thread(
execute_mcp_tool,
tool["name"],
arguments,
cancel_event = cancel_event,
timeout = tool_timeout,
)
for tool, arguments in calls
),
return_exceptions = True,
)
found = []
for (tool, _arguments), result in zip(calls, results):
text = (
strip_result_for_model(result, tool["name"]).strip()
if isinstance(result, str)
else ""
)
if not text or is_tool_error(text):
logger.warning(
"research.mcp_search_failed run_id=%s tool=%s error=%s",
run["id"],
tool["name"],
(text or str(result))[:200],
)
continue
found.append(
{
"kind": "mcp",
"chunkId": f"{tool['name']}:{position}",
"documentId": tool["name"],
"filename": labels[tool["name"]],
"page": None,
"score": None,
"snippet": text[:4000],
}
)
return found
async def _check_worker_write(self, run_id: str, written: bool) -> None:
if written:
return
await self._check_active(run_id)
raise LeaseLost()
def _salvage_report(self, run_id: str, notice: str) -> str:
draft = self._report_drafts.get(account_key(run_id))
if draft is None or not draft.text:
return ""
if draft.whole:
return _report_under_notice(draft.text, "Report complete.", notice)
reason = f"{draft.reason}. {notice}" if draft.reason else notice
return _report_under_notice(draft.text, "Incomplete report.", reason)
async def _finish_terminal(
self, run_id: str, status: str, error: str | None, report: str
) -> str | None:
"""Commits terminal status with a bounded lock wait; raises rather than overwrite an expired
lease."""
deadline = time.monotonic() + _TERMINAL_WRITE_DEADLINE_SECONDS
while True:
try:
return await asyncio.to_thread(
db.finish,
run_id,
self.worker_id,
status,
error,
{"report": report} if report else None,
)
except sqlite3.OperationalError as exc:
if not is_sqlite_busy_error(exc) or time.monotonic() >= deadline:
raise
logger.warning("research.terminal_write_busy run_id=%s: %s", run_id, exc)
await asyncio.sleep(_TERMINAL_WRITE_RETRY_SECONDS)
async def _finish_after_lease_loss(self, run_id: str) -> str | None:
while True:
try:
return await asyncio.to_thread(
db.finish,
run_id,
self.worker_id,
"failed",
"Worker lease expired",
None,
True,
)
except sqlite3.OperationalError:
logger.warning(
"research.lease_loss_finish_retry run_id=%s",
run_id,
exc_info = True,
)
await asyncio.sleep(1)
def note_server_address(self, server: Any) -> None:
state = self.app.state
published = getattr(state, "server_request_host", None)
if not (isinstance(published, str) and published):
host = scope_request_host(server)
if host is not None:
state.research_request_host = prefer_loopback(
getattr(state, "research_request_host", None),
host,
)
if isinstance(getattr(state, "server_port", None), int):
return
if (
isinstance(server, tuple)
and len(server) >= 2
and isinstance(server[1], int)
and server[1] > 0
):
state.research_request_port = server[1]
def note_request_address(self, request: Any) -> None:
self.note_server_address(getattr(request, "scope", {}).get("server"))
async def _loop(self) -> None:
while not self._stopping.is_set():
try:
if self._server_port() is None:
await asyncio.sleep(self.poll_seconds)
continue
account, run = await asyncio.to_thread(self._claim_account_run)
if run is None:
await asyncio.sleep(self.poll_seconds)
continue
self.job_account = account
try:
await arun_as(account, self._process(run))
finally:
self.job_account = None
except asyncio.CancelledError:
raise
except sqlite3.OperationalError as exc:
# Never re-raise: it would stop the supervisor for the life of the process.
if is_sqlite_busy_error(exc):
logger.warning("research.supervisor_db_busy: %s", exc)
else:
logger.exception("research.supervisor_iteration_failed")
await asyncio.sleep(1)
except Exception:
logger.exception("research.supervisor_iteration_failed")
await asyncio.sleep(1)
def _claim_account_run(self):
# Round robin from the account after the last claim: runs are processed one at a time.
accounts = job_accounts()
start = 0
for index, account in enumerate(accounts):
if account.account_id == self._last_claim_account:
start = index + 1
break
for offset in range(len(accounts)):
account = accounts[(start + offset) % len(accounts)]
try:
run = run_as(account, db.claim_next, self.worker_id)
except Exception:
# The order is stable, so one corrupt database would shadow the accounts behind it.
logger.exception("research.claim_failed_for_account")
continue
if run is not None:
self._last_claim_account = account.account_id
return account, run
return None, None
def _server_port(self) -> int | None:
port = getattr(self.app.state, "server_port", None)
if not isinstance(port, int) or port <= 0:
port = getattr(self.app.state, "research_request_port", None)
if not isinstance(port, int) or port <= 0:
return None
return port
def _server_host(self) -> str:
host = getattr(self.app.state, "server_request_host", None)
if not isinstance(host, str) or not host:
host = getattr(self.app.state, "research_request_host", None)
if not isinstance(host, str) or not host:
return LOOPBACK_FALLBACK_HOST
return host
def _endpoint(self) -> str:
from utils.studio_tls import loopback_http_port
loopback_port = loopback_http_port(self.app.state)
if loopback_port is not None:
return f"http://127.0.0.1:{loopback_port}/v1/chat/completions"
port = self._server_port()
if port is None:
raise RuntimeError("Research is waiting for the Unsloth server port")
return f"http://{dial_host(self._server_host())}:{port}/v1/chat/completions"
async def _wait_for_local_model(
self,
run: dict,
max_seconds: float | None = None,
) -> bool:
"""Waits up to the model timeout for a reload, so a resumed run survives its model being gone."""
loop = asyncio.get_running_loop()
# Split the model budget across waits, or the outer wall clock fires first and buries the refusal.
budget = _model_wait_budget(run)
if max_seconds is not None:
budget = min(budget, max_seconds)
deadline = loop.time() + budget
logger.info("research.waiting_for_local_model run_id=%s", run["id"])
while loop.time() < deadline:
await self._check_active(run["id"])
await asyncio.sleep(_MODEL_WAIT_POLL_SECONDS)
if _local_model_ready():
return True
return False
async def _wait_for_model_switch(self, run: dict, response: httpx.Response, waits: int) -> None:
"""Waits out an in-flight model switch before re-sending, since a loaded model looks like
success."""
run_id = run["id"]
step = _retry_after_seconds(response) or _MODEL_SWITCH_RETRY_SECONDS
# Same split as _wait_for_local_model, leaving room for the refusal, not a wall-clock timeout.
remaining = min(step * waits, _NAMED_MODEL_WAIT_SECONDS, _model_wait_budget(run))
logger.info("research.waiting_for_model_switch run_id=%s seconds=%.0f", run_id, remaining)
while remaining > 0:
await self._check_active(run_id)
await asyncio.sleep(min(_MODEL_WAIT_POLL_SECONDS, remaining))
remaining -= _MODEL_WAIT_POLL_SECONDS
await self._check_active(run_id)
async def _wait_out_rate_limit(
self, run: dict, requested: float, deadline: float, headroom: float
) -> None:
"""Wait out a provider's retry delay, whatever carried it, against the same budget."""
remaining = deadline - asyncio.get_running_loop().time()
await self._wait_out_retry_after(
run["id"], _rate_limit_wait(requested, remaining, headroom)
)
async def _wait_out_retry_after(self, run_id: str, delay: float) -> None:
"""Wait out a provider-set retry delay in the same poll-sized slices as the model waits
above, so a cancel or a lost lease ends the run during the wait rather than after it."""
remaining = delay
while remaining > 0:
await self._check_active(run_id)
await asyncio.sleep(min(_MODEL_WAIT_POLL_SECONDS, remaining))
remaining -= _MODEL_WAIT_POLL_SECONDS
@staticmethod
def _absorb_late_task(run_id: str, what: str, task: asyncio.Task) -> None:
"""Retrieve the outcome of a task that outlived the cleanup bound."""
if task.cancelled():
return
error = task.exception()
if error is not None:
logger.warning(
"research.%s_late_cleanup_failed run_id=%s", what, run_id, exc_info = error
)
def _absorb_when_done(self, run_id: str, task: asyncio.Task, what: str) -> None:
"""Arrange for a task still running past cleanup to have its outcome retrieved."""
if task.done():
self._absorb_late_task(run_id, what, task)
return
task.add_done_callback(lambda finished: self._absorb_late_task(run_id, what, finished))
async def _discard_task(self, run_id: str, task: asyncio.Task, what: str) -> None:
"""Cancels a task, absorbing only its own outcome; the wait is bounded, so a stuck task
cannot hang."""
task.cancel()
try:
await asyncio.wait({task}, timeout = _STREAM_CLEANUP_TIMEOUT_SECONDS)
except asyncio.CancelledError:
# Re-raise cancellation, but hand the task off first: it outlives this frame and is absorbed later.
self._absorb_when_done(run_id, task, what)
raise
if not task.done():
logger.warning("research.%s_cleanup_timed_out run_id=%s", what, run_id)
self._absorb_when_done(run_id, task, what)
return
try:
task.result()
except (asyncio.CancelledError, StopAsyncIteration):
pass
except Exception:
logger.warning("research.%s_cleanup_failed run_id=%s", what, run_id, exc_info = True)
async def _iter_stream_lines(
self,
run_id: str,
response: httpx.Response,
semantic_deadline: Callable[[], tuple[float, type[BaseException]] | None] | None = None,
) -> AsyncIterator[str]:
iterator = response.aiter_lines().__aiter__()
def wait_timeout() -> float:
if semantic_deadline is None:
return 0.2
deadline = semantic_deadline()
if deadline is None:
return 0.2
at, expired = deadline
remaining = at - asyncio.get_running_loop().time()
if remaining > 0:
return min(0.2, remaining)
# Named by the caller, so a first-output deadline is never reported as a stall.
raise expired()
while True:
if self._cancel_event(run_id).is_set():
await self._check_active(run_id)
timeout = wait_timeout()
line_task = asyncio.create_task(anext(iterator))
discarded = False
try:
while not line_task.done():
await asyncio.wait({line_task}, timeout = timeout)
if self._cancel_event(run_id).is_set():
# Set first: the finally must not spend the bound on it again.
discarded = True
await self._discard_task(run_id, line_task, "stream_iterator")
await self._check_active(run_id)
# Lines arriving during the wait count; recomputing the deadline first would let expiry drop them.
if line_task.done():
break
timeout = wait_timeout()
try:
line = line_task.result()
except StopAsyncIteration:
return
finally:
if not discarded and not line_task.done():
await self._discard_task(run_id, line_task, "stream_iterator")
yield line
async def _stream_completion(
self,
run: dict,
messages: list[dict],
*,
json_mode: bool = False,
report_progress: bool = True,
phase: str = "unknown",
step_position: int | None = None,
max_tokens: int | None = None,
enable_thinking: bool | None = None,
preview_labels: bool = False,
on_partial: Callable[[str, str, str | None], None] | None = None,
) -> tuple[str, str, str | None, dict[str, int] | None]:
call_id = uuid.uuid4().hex
expires = (
datetime.now(timezone.utc) + timedelta(seconds = _MODEL_CALL_KEY_LIFETIME_SECONDS)
).isoformat()
key_minted = asyncio.get_running_loop().time()
account = current_account()
token, key = await asyncio.to_thread(
auth_storage.create_api_key,
username = run["ownerSubject"],
# Load-bearing: the external-provider route scopes its credential exception to this name.
name = auth_storage.DEEP_RESEARCH_WORKFLOW_KEY_NAME,
expires_at = expires,
internal = True,
# Pinned to the claiming account: the username could name a recreated namesake.
account_id = None if account.is_owner else account.account_id,
)
config = run["config"]
inference = config.get("inferenceRequest") or {}
omit_sampling = inference.get("providerType") == "custom" and await asyncio.to_thread(
_custom_responses_rejects_sampling, inference
)
payload: dict[str, Any] = {
"model": inference.get("model") or config.get("model") or "",
"messages": messages,
"stream": True,
"stream_options": {"include_usage": True},
# Each hop gets its own Codex prompt-cache thread_id, not the shared transport fallback.
"thread_id": f"research:{run['id']}",
# Both opt-outs needed: --enable-tools overrides enable_tools; omitted enabled_tools = all built-ins.
"tool_choice": "none",
"enabled_tools": [],
}
if not omit_sampling:
payload["temperature"] = inference.get("temperature", 0.2)
# _sanitize_config already admits only enabled saved studio-tools-capable connections.
if inference.get("providerType"):
payload.update(
{
"provider_id": inference["providerId"],
"provider_type": inference["providerType"],
"external_model": inference["externalModel"],
}
)
if not omit_sampling and inference.get("topP") is not None:
payload["top_p"] = inference["topP"]
if inference.get("providerType") in (
"deepseek",
"huggingface",
"qwen",
"qwencloud",
"mistral",
):
# These providers forward reasoning fields verbatim, and a strict upstream rejects one the model lacks.
# Mistral documents reasoning_effort for mistral-small-latest and mistral-medium-3-5 only, so the
# planner opt-out must not reach mistral-large and the other non-reasoning models.
# `is not True`, not `is False`: a run from before these flags carries neither, and a
# thinking planner call on a resumed run beats a request the model rejects.
if inference.get("supportsReasoning") is not True:
enable_thinking = None
inference = {
key: value
for key, value in inference.items()
if key not in ("enableThinking", "reasoningEffort")
}
elif enable_thinking is False and inference.get("supportsReasoningOff") is False:
enable_thinking = None
if enable_thinking is not None:
payload["enable_thinking"] = enable_thinking
elif inference.get("enableThinking") is not None:
payload["enable_thinking"] = inference["enableThinking"]
if enable_thinking is False:
payload["reasoning_effort"] = "none"
elif inference.get("reasoningEffort") is not None:
payload["reasoning_effort"] = inference["reasoningEffort"]
if json_mode:
payload["response_format"] = {"type": "json_object"}
report = ""
reasoning = ""
pending_report = ""
pending_reasoning = ""
pending_reasoning_offset = 0
last_progress_flush = asyncio.get_running_loop().time()
finish_reason: str | None = None
usage: dict[str, int] | None = None
semantic_output_at: float | None = None
first_output_deadline: float | None = None
emitted_labels = 0
async def flush_progress() -> None:
nonlocal pending_report, pending_reasoning, pending_reasoning_offset
nonlocal last_progress_flush
if pending_reasoning:
try:
seq = await asyncio.to_thread(
db.append_worker_event,
run["id"],
self.worker_id,
"reasoning.updated",
{
"reasoningDelta": pending_reasoning,
"reasoningOffset": pending_reasoning_offset,
"phase": phase,
"callId": call_id,
**(
{"stepPosition": step_position} if step_position is not None else {}
),
},
)
if seq is None:
await self._check_active(run["id"])
raise LeaseLost()
pending_reasoning = ""
except (LeaseLost, RunCancelled):
raise
except Exception:
logger.warning(
"research.reasoning_flush_failed run_id=%s",
run["id"],
exc_info = True,
)
last_progress_flush = asyncio.get_running_loop().time()
return
if report_progress and pending_report:
try:
written = await asyncio.to_thread(
db.set_report_progress,
run["id"],
report,
pending_report,
self.worker_id,
)
if not written:
await self._check_active(run["id"])
raise LeaseLost()
pending_report = ""
except (LeaseLost, RunCancelled):
raise
except Exception:
logger.warning(
"research.report_flush_failed run_id=%s",
run["id"],
exc_info = True,
)
last_progress_flush = asyncio.get_running_loop().time()
try:
await self._note_phase(run["id"], "phase.started", phase, call_id, step_position)
model_timeout = float(config["budgets"]["modelTimeoutSeconds"])
# Configurable, capped by a finite run wall clock; legacy runs use the default.
first_output_budget = float(
config["budgets"].get(
"firstOutputTimeoutSeconds", _MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS
)
)
if model_timeout > 0:
first_output_budget = min(first_output_budget, model_timeout)
# Unlimited drops only the wall clock; the gap bound must still clear the queue-notice heartbeat.
admission_gap_budget = max(
first_output_budget,
_MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS,
llama_admission_config_from_env().keepalive_interval_s
* _ADMISSION_HEARTBEAT_MISSES,
)
timeout = (
httpx.Timeout(model_timeout)
if model_timeout
else httpx.Timeout(
first_output_budget,
# Looser than the guards above so a stall is named, not a bare HTTPX ReadTimeout.
read = admission_gap_budget + _STREAM_READ_TIMEOUT_MARGIN_SECONDS,
)
)
loop = asyncio.get_running_loop()
def semantic_deadline() -> tuple[float, type[BaseException]] | None:
if semantic_output_at is None:
if first_output_deadline is None:
return None
return first_output_deadline, ModelFirstOutputTimeout
return (
semantic_output_at + _MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS,
ModelOutputIdleTimeout,
)
call_started = loop.time()
# No backoff below may outlast this call's wall clock or the key the re-send authenticates with.
retry_deadline = key_minted + _MODEL_CALL_KEY_LIFETIME_SECONDS
if model_timeout:
retry_deadline = min(retry_deadline, call_started + model_timeout)
async with (
_wall_clock_timeout(model_timeout or None),
httpx.AsyncClient(timeout = timeout, trust_env = False) as client,
):
response: httpx.Response | None = None
send_task: asyncio.Task | None = None
# A retry builds a fresh task, so the guard starts over with it.
send_discarded = False
model_waits = 0
attempt = 0
try:
while True:
if (
max_tokens is not None
and inference.get("providerType")
and phase in ("synthesis", "synthesis_recovery")
):
# Each re-send after a queue or rate-limit wait is bounded by the cap in force when it goes out.
max_tokens = min(
max_tokens,
await asyncio.to_thread(
_synthesis_max_tokens, inference, model_timeout
),
)
payload["max_tokens"] = _resolve_max_tokens(
max_tokens,
inference,
messages,
)
request = client.build_request(
"POST",
self._endpoint(),
json = payload,
headers = {
"Authorization": f"Bearer {token}",
# Keep text-only intent across retries and model switches.
"X-Unsloth-Require-Text": "1",
},
)
try:
send_task = asyncio.create_task(client.send(request, stream = True))
send_discarded = False
while not send_task.done():
await asyncio.wait({send_task}, timeout = 0.2)
if self._cancel_event(run["id"]).is_set():
# Set first: a send outlasting the bound is not waited on twice.
send_discarded = True
await self._discard_task(run["id"], send_task, "send")
await self._check_active(run["id"])
response = await send_task
response.raise_for_status()
first_output_deadline = loop.time() + first_output_budget
except (httpx.TransportError, httpx.HTTPStatusError) as exc:
# Only reachable before a body byte is touched, so a re-send cannot duplicate report text.
if (
not _external_provider_run(inference)
and payload.get("response_format") == {"type": "json_object"}
and isinstance(exc, httpx.HTTPStatusError)
and await _response_format_unsupported(exc.response)
):
# No grammar engine; output is validated anyway, so retry once without response_format.
del payload["response_format"]
await exc.response.aclose()
response = None
await self._check_active(run["id"])
continue
unloaded = (
await _model_unloaded(exc.response)
if isinstance(exc, httpx.HTTPStatusError)
else None
)
rate_limited = (
isinstance(exc, httpx.HTTPStatusError)
and exc.response.status_code == 429
)
retryable = (
not isinstance(exc, httpx.HTTPStatusError)
or exc.response.status_code >= 500
or rate_limited
)
if unloaded:
model_waits += 1
if model_waits > _MAX_MODEL_WAITS:
raise
elif not retryable or attempt == 2:
raise
if response is not None:
# Manual stream mode owns the connection; release it to re-send.
await response.aclose()
response = None
if unloaded == "switching":
await self._wait_for_model_switch(run, exc.response, model_waits)
elif unloaded:
# Nothing loaded (restart or eject): wait for a model, without spending a transport attempt.
if not await self._wait_for_local_model(
run,
_NAMED_MODEL_WAIT_SECONDS if unloaded == "named" else None,
):
raise
else:
delay = 2**attempt
if rate_limited:
# This runs to minutes, so re-read the run while it waits.
await self._wait_out_rate_limit(
run,
_retry_after_seconds(exc.response) or delay,
retry_deadline,
first_output_budget,
)
else:
await asyncio.sleep(delay)
attempt += 1
await self._check_active(run["id"])
continue
# A proxied provider 429 can arrive as a 200 whose first line is the refusal.
stream = self._iter_stream_lines(run["id"], response, semantic_deadline)
head = await _peek_stream_head(stream)
throttled = _stream_rate_limit_delay(head)
if throttled is None or attempt == 2:
# Out of attempts: let the stream raise the provider's own error.
break
await stream.aclose()
await response.aclose()
response = None
await self._wait_out_rate_limit(
run, throttled or 2**attempt, retry_deadline, first_output_budget
)
attempt += 1
await self._check_active(run["id"])
async for line in _with_head(head, stream):
if self._cancel_event(run["id"]).is_set():
await self._check_active(run["id"])
if not line.startswith("data:"):
# Queueing has no timeout by design; start the model budget only when the slot is granted.
if line.startswith(_ADMISSION_WAIT_COMMENT):
# Unlimited has no wall clock, so bound the gap between queue notices; each notice refreshes it.
first_output_deadline = (
None if model_timeout else loop.time() + admission_gap_budget
)
elif line.startswith(_ADMISSION_DONE_COMMENT):
first_output_deadline = loop.time() + first_output_budget
continue
data = line[5:].strip()
if data == "[DONE]":
break
if not data:
continue
# Arming research is the approval: queue the plan as stored, not parked for a second confirm.
try:
chunk = json.loads(data)
_stream_error = stream_error_from_chunk(chunk)
if _stream_error is not None:
error = chunk.get("error")
if (
json_mode
and phase in ("decision", "synthesis_audit")
and isinstance(error, dict)
and error.get("code") == "structured_output_failed"
):
# Provider-rejected JSON takes the malformed-reply fallback.
await self._check_active(run["id"])
logger.warning(
"research.structured_output_failed run_id=%s phase=%s",
run["id"],
phase,
)
return "", "", None, usage
# Keep the server's error text: it names the cause and both token counts a user can act on.
raise _stream_error
normalized_usage = _normalize_completion_usage(
chunk.get("usage") if isinstance(chunk, dict) else None
)
if normalized_usage is not None:
usage = normalized_usage
choice = chunk.get("choices", [{}])[0]
delta = choice.get("delta", {})
if isinstance(choice.get("finish_reason"), str):
finish_reason = choice["finish_reason"]
text = delta.get("content")
except (AttributeError, IndexError, json.JSONDecodeError, TypeError):
continue
thought = delta.get("reasoning_content")
if isinstance(thought, str) and thought:
semantic_output_at = loop.time()
if not pending_reasoning:
pending_reasoning_offset = len(reasoning)
reasoning += thought
pending_reasoning += thought
if isinstance(text, str) and text:
semantic_output_at = loop.time()
report += text
pending_report += text
# only a closing quote completes a title; per-token rescans cost ~170ms.
if preview_labels and '"' in text:
emitted_labels = await self._emit_preview_labels(
run["id"], phase, call_id, report, emitted_labels
)
pending_chars = len(pending_reasoning) + len(pending_report)
# Every flush rewrites the whole row: quadratic in report length.
written = len(report) + len(reasoning)
flush_chars = max(_PROGRESS_FLUSH_CHARS, written // 64)
flush_seconds = max(
_PROGRESS_FLUSH_SECONDS, written / _PROGRESS_FLUSH_CHARS_PER_SECOND
)
if (
pending_chars >= flush_chars
or pending_chars > 0
and asyncio.get_running_loop().time() - last_progress_flush
>= flush_seconds
):
await flush_progress()
if semantic_output_at is None:
raise ModelFirstOutputTimeout("Local model never produced output")
finally:
if send_task is not None and not send_discarded and not send_task.done():
await self._discard_task(run["id"], send_task, "send")
if (
response is None
and send_task is not None
and send_task.done()
and not send_task.cancelled()
):
try:
response = send_task.result()
except Exception:
pass
if response is not None:
try:
await response.aclose()
except Exception:
# Closing a broken stream is best-effort and must not mask the result or the teardown error.
logger.warning(
"research.stream_cleanup_failed run_id=%s",
run["id"],
exc_info = True,
)
await flush_progress()
return report, reasoning, finish_reason, usage
# Not errors: the flush below would fail without writing.
except (RunCancelled, LeaseLost):
raise
except Exception as exc:
# Before the flush, which only displays it; with the finish reason, which text cannot carry.
if on_partial is not None:
on_partial(report, reasoning, finish_reason)
if report_progress:
try:
# Best effort: a progress update must not replace the error that stopped the run.
await flush_progress()
except Exception:
logger.warning(
"research.error_flush_failed run_id=%s", run["id"], exc_info = True
)
if isinstance(
exc, (ModelFirstOutputTimeout, ModelOutputIdleTimeout, ModelWallClockTimeout)
):
raise
# Transport backstop: HTTPX raises this with no message, so name the stall instead.
if isinstance(exc, httpx.ReadTimeout):
if semantic_output_at is None:
raise ModelFirstOutputTimeout("Local model never produced output") from exc
raise ModelOutputIdleTimeout("Local model stopped producing output") from exc
if isinstance(exc, (TimeoutError, asyncio.TimeoutError)):
raise ModelWallClockTimeout(
"Local model request exceeded its wall-clock timeout"
) from exc
raise
finally:
# revoked before the phase event, so a cancel there cannot leak a live key.
try:
await asyncio.to_thread(auth_storage.revoke_internal_api_key, int(key["id"]))
except Exception:
logger.warning(
"research.api_key_cleanup_failed run_id=%s",
run["id"],
exc_info = True,
)
await self._note_phase(run["id"], "phase.ended", phase, call_id, step_position)
async def _emit_preview_labels(
self, run_id: str, phase: str, call_id: str, streamed: str, already_emitted: int
) -> int:
"""Publish each plan step title as the planner finishes writing it, and return the
running total. Turns a multi-minute silent JSON generation into visible progress."""
titles = _streamed_titles(streamed)
emitted = already_emitted
for label in titles[already_emitted:_MAX_PREVIEW_LABELS]:
try:
await asyncio.to_thread(
db.append_worker_event,
run_id,
self.worker_id,
"phase.progress",
{"phase": phase, "callId": call_id, "label": label},
)
except Exception:
logger.debug("research.phase_preview_failed run_id=%s", run_id, exc_info = True)
return emitted
emitted += 1
return emitted
async def _note_phase(
self, run_id: str, event_type: str, phase: str, call_id: str, step_position: int | None
) -> None:
"""Brackets a silent model call with a timeline event so a long phase does not look like a stall."""
try:
await asyncio.to_thread(
db.append_worker_event,
run_id,
self.worker_id,
event_type,
{
"phase": phase,
"callId": call_id,
**({"stepPosition": step_position} if step_position is not None else {}),
},
)
except Exception:
# Best effort: a progress marker must never fail the run it is reporting on.
logger.debug("research.phase_event_failed run_id=%s", run_id, exc_info = True)
async def _process(self, run: dict) -> None:
# After a terminal status, this worker may write only while the run is still on its attempt.
attempt = int(run.get("retryCount") or 0)
cancel_event = self._cancel_event(run["id"])
if await asyncio.to_thread(db.is_cancel_requested, run["id"]):
cancel_event.set()
heartbeat = asyncio.create_task(self._heartbeat(run["id"]))
try:
await self._check_active(run["id"])
if run["status"] == "planning":
await self._plan(run)
else:
await self._research(run)
except RunCancelled:
actual_status = await asyncio.to_thread(
db.finish, run["id"], self.worker_id, "cancelled"
)
fresh = await asyncio.to_thread(db.get_run, run["id"])
if actual_status == "cancelled" and not _run_moved_on(fresh, attempt):
await asyncio.to_thread(
_update_assistant, fresh, "Research cancelled.", "cancelled"
)
except LeaseLost:
logger.warning("research.lease_lost run_id=%s", run["id"])
actual_status = await self._finish_after_lease_loss(run["id"])
fresh = await asyncio.to_thread(db.get_run, run["id"])
if actual_status == "cancelled" and not _run_moved_on(fresh, attempt):
await asyncio.to_thread(
_update_assistant,
fresh,
"Research cancelled.",
"cancelled",
)
elif actual_status == "failed" and not _run_moved_on(fresh, attempt):
await asyncio.to_thread(
_update_assistant,
fresh,
"Research paused because its worker lease expired. Retry to continue.",
"failed",
)
except Exception as exc:
error = _safe_error(exc)
logger.warning("research.run_failed run_id=%s error=%s", run["id"], error)
reported = f"Research failed: {_as_literal_markdown(error)}"
partial_report = self._salvage_report(run["id"], reported)
actual_status = await self._finish_terminal(run["id"], "failed", error, partial_report)
if actual_status is None:
actual_status = await self._finish_after_lease_loss(run["id"])
fresh = await asyncio.to_thread(db.get_run, run["id"])
if actual_status == "cancelled" and not _run_moved_on(fresh, attempt):
await asyncio.to_thread(
_update_assistant, fresh, "Research cancelled.", "cancelled"
)
elif actual_status == "failed" and not _run_moved_on(fresh, attempt):
saved = fresh.get("report")
await asyncio.to_thread(
_update_assistant,
fresh,
saved or reported,
"failed",
_cited_sources(fresh) if saved else None,
)
finally:
heartbeat.cancel()
try:
await heartbeat
except asyncio.CancelledError:
pass
# Stops side lookups that outlive a failed step.
self._cancel_events.pop(account_key(run["id"]), None)
cancel_event.set()
self._lost_leases.discard(account_key(run["id"]))
self._report_drafts.pop(account_key(run["id"]), None)
async def _heartbeat(self, run_id: str) -> None:
delay = 30.0
consecutive_errors = 0
while True:
await asyncio.sleep(delay)
delay = 30.0
try:
renewed = await asyncio.to_thread(db.heartbeat, run_id, self.worker_id)
except Exception:
logger.warning("research.heartbeat_failed run_id=%s", run_id, exc_info = True)
# Retry busy SQLite briefly, but stop well before the 120-second lease expires.
consecutive_errors += 1
if consecutive_errors >= 10:
self._lost_leases.add(account_key(run_id))
self.cancel(run_id)
return
delay = 1.0
continue
consecutive_errors = 0
if not renewed:
self._lost_leases.add(account_key(run_id))
self.cancel(run_id)
return
async def _plan(self, run: dict) -> None:
question, conversation_context = await asyncio.to_thread(
_research_question_context,
run["threadId"],
run["userMessageId"],
str(run["config"].get("question") or ""),
)
if not question:
raise ValueError("User message has no text to research")
max_steps = int(run["config"]["budgets"]["maxSteps"])
planner_system = _system_prompt_with_instructions(
_planner_system_prompt(max_steps, run["config"].get("websitePolicy")),
run["config"],
)
await _refresh_served_context_length(run)
# The question needs its own budget: a pasted document arrives verbatim and would overflow planning.
planning_total = _prompt_char_budget(
_SYNTHESIS_CONTEXT_RESERVE_TOKENS, _run_inference_request(run)
)
planning_question = question[
: max(
_MIN_QUESTION_CHARS,
_trimmable_budget(
planning_total, len(planner_system), _MAX_SYNTHESIS_EVIDENCE_CHARS
),
)
]
planning_context = conversation_context[
: _trimmable_budget(
planning_total, len(planner_system) + len(planning_question), _MAX_CONTEXT_CHARS
)
]
response, planning_reasoning, _finish_reason, _usage = await self._stream_completion(
run,
[
{
"role": "system",
"content": planner_system,
},
{
"role": "user",
"content": (
"Prior conversation context as JSON (oldest to newest; use it only to "
"resolve references in the latest request):\n"
f"{_shield_untrusted(planning_context)}\n\n"
f"Latest research request:\n{_shield_untrusted(planning_question)}"
),
},
],
json_mode = True,
report_progress = False,
phase = "planning",
max_tokens = 4096,
enable_thinking = False,
preview_labels = True,
)
plan = _parse_and_validate_plan(response, planning_reasoning, max_steps)
try:
result = await asyncio.to_thread(
db.set_plan,
run["id"],
plan,
None,
self.worker_id,
)
except db.ResearchConflictError:
if await asyncio.to_thread(db.is_cancel_requested, run["id"]):
raise RunCancelled()
await self._check_active(run["id"])
raise
run.update(result)
# The structured inline card renders the plan; no second markdown copy below it.
async def _research(self, run: dict) -> None:
# The routes refuse to start a run while tools are off; a durable run approved before a
# restart under `--disable-tools` is still claimed here.
if get_tool_policy() is False:
raise RuntimeError("Tools are disabled on this server")
# Completed steps on a queued run are ones a Retry kept (a fresh plan's steps are all pending).
resuming = run.get("claimedFromStatus") == "running" or any(
step.get("status") == "completed" for step in run.get("steps") or ()
)
fresh = await asyncio.to_thread(db.get_run, run["id"])
if not fresh or not fresh.get("plan"):
raise ValueError("Approved plan is missing")
run = fresh
# The attempt this pass belongs to, kept because ``run`` is re-read below.
research_attempt = int(run.get("retryCount") or 0)
budgets = run["config"]["budgets"]
max_steps = int(budgets["maxSteps"])
max_sources = int(budgets["maxSources"])
tool_timeout = int(budgets["toolTimeoutSeconds"])
# default 0 preserves behavior for runs created before auto-scrape.
max_auto_scrape = int(budgets.get("maxAutoScrape", 0))
await _refresh_served_context_length(run)
# prompt overhead fills tiny context windows, so use snippets alone.
if max_auto_scrape > 0:
loaded_ctx = _loaded_context_length(_run_inference_request(run))
if loaded_ctx is not None and loaded_ctx < _AUTO_SCRAPE_MIN_CONTEXT_TOKENS:
logger.info(
"research.auto_scrape_disabled_small_context run_id=%s context=%s",
run["id"],
loaded_ctx,
)
max_auto_scrape = 0
website_policy = run["config"].get("websitePolicy")
policy_prompt = website_policy_prompt(website_policy)
selected_mcp = {
(item["serverId"], item["tool"]) for item in run["config"].get("mcpSources") or ()
}
mcp_tools = (
[
tool
for tool in await mcp_search_tools(
server_ids = {server_id for server_id, _tool in selected_mcp}
)
if (tool["serverId"], tool["tool"]) in selected_mcp
]
if selected_mcp
else []
)
notes: list[str | tuple[str, ...]] = []
decision_notes: list[str] = []
research_state: dict[str, Any] = {}
sources: list[dict] = []
document_sources: list[dict] = []
used_queries: set[str] = set()
fetched_urls: set[str] = set()
completed_steps = 0
step_error = ""
question, conversation_context = await asyncio.to_thread(
_research_question_context,
run["threadId"],
run["userMessageId"],
str(run["config"].get("question") or ""),
)
reset = db.prepare_execution_resume if resuming else db.reset_execution_steps
written = await asyncio.to_thread(reset, run["id"], self.worker_id)
await self._check_worker_write(run["id"], written)
run = await asyncio.to_thread(db.get_run, run["id"])
if not run:
raise LeaseLost()
if resuming:
sources = list(run.get("sources") or [])[:max_sources]
document_sources = list(run.get("documentSources") or [])[:max_sources]
for step in run.get("steps") or []:
result = step.get("result") if isinstance(step.get("result"), dict) else {}
action = str(result.get("action") or "search")
argument = str(result.get("input") or step.get("query") or "")
if action == "fetch":
fetched_urls.add(argument)
elif argument:
used_queries.add(argument)
if step.get("status") != "completed":
step_error = _preferred_step_error(step_error, str(result.get("error") or ""))
continue
restored_state = _normalize_research_state(result.get("researchState"))
if restored_state:
research_state = restored_state
step_sources = [
source for source in sources if source.get("stepPosition") == step.get("position")
]
web_evidence = str(result.get("excerpt") or "")
if not web_evidence and step_sources:
web_evidence = "\n\n---\n\n".join(
f"Title: {source.get('title') or source['url']}\n"
f"URL: {source['url']}\n"
f"Snippet: {source.get('snippet') or ''}"
for source in step_sources
)
restored_rag_sources = [
item for item in result.get("evidenceSources") or [] if isinstance(item, dict)
]
document_source_keys = {
str(
source.get("chunkId")
or f"{source.get('documentId') or source.get('filename')}:{source.get('page') or ''}"
)
for source in document_sources
}
# Only cataloged chunks may be evidence, or synthesis builds claims on text the validator strips.
accepted_rag_sources = []
for source in restored_rag_sources:
source_key = str(
source.get("chunkId")
or f"{source.get('documentId') or source.get('filename')}:{source.get('page') or ''}"
)
if source_key not in document_source_keys:
if len(document_sources) >= max_sources:
continue
written = await asyncio.to_thread(
db.upsert_document_source,
run["id"],
int(step["position"]),
source,
self.worker_id,
)
await self._check_worker_write(run["id"], written)
document_source_keys.add(source_key)
document_sources.append({**source, "stepPosition": step["position"]})
accepted_rag_sources.append(source)
rag_evidence = "\n".join(
f"{item.get('filename') or 'Document'}: "
f"{item.get('text') or item.get('snippet') or ''}"
for item in accepted_rag_sources
if item.get("kind") != "mcp"
)
mcp_evidence = _mcp_evidence(
[item for item in accepted_rag_sources if item.get("kind") == "mcp"]
)
# unscraped searches save no excerpt, so completed steps may resume without evidence.
if web_evidence or rag_evidence or mcp_evidence:
completed_steps += 1
title = str(step.get("title") or "Recovered research step")
heading = f"### {title} ({action})\nInput: {argument}"
notes.append(
(
heading,
f"Result:\n{web_evidence}",
f"Knowledge base:\n{rag_evidence}{mcp_evidence}",
)
if rag_evidence or mcp_evidence
else f"{heading}\nResult:\n{web_evidence}"
)
decision_notes.append(f"{heading}\nResult:\n{web_evidence}")
start_position = (
max(
(int(step["position"]) for step in run.get("steps") or []),
default = -1,
)
+ 1
)
for position in range(start_position, max_steps):
await self._check_active(run["id"])
source_catalog = "\n".join(
f"- {_citation_title(source, source['url'])} | {source['url']} | "
f"{source.get('snippet') or ''}"
for source in sources
)
evidence = "\n\n".join(decision_notes)
decision_system = _system_prompt_with_instructions(
_AGENT_SYSTEM_PROMPT + (f"\n\n{policy_prompt}" if policy_prompt else ""),
run["config"],
)
await _refresh_served_context_length(run)
# A fixed 60k tail dwarfs small contexts and runs every step; overflow kills the run pre-synthesis.
decision_total = _prompt_char_budget(
_SYNTHESIS_CONTEXT_RESERVE_TOKENS, _run_inference_request(run)
)
decision_question, decision_plan_json = _fit_decision_inputs(
question,
run["plan"],
len(decision_system),
decision_total,
)
# Catalog is unbounded too (maxSources, 4000-char snippets); fit it before dependent sections.
decision_catalog = _fit_source_catalog(
source_catalog,
_trimmable_budget(
decision_total,
len(decision_system)
+ len(decision_question)
+ len(decision_plan_json)
+ _MIN_SYNTHESIS_EVIDENCE_CHARS,
len(source_catalog),
),
)
decision_query_history_json = json.dumps(
sorted(used_queries),
ensure_ascii = False,
)
decision_state_json = json.dumps(research_state, ensure_ascii = False)
decision_scaffold = (
len(decision_system)
+ len(decision_question)
+ len(decision_plan_json)
+ len(decision_catalog)
+ len(decision_query_history_json)
+ len(decision_state_json)
)
evidence_chars = _trimmable_budget(
decision_total, decision_scaffold, _MAX_SYNTHESIS_EVIDENCE_CHARS
)
decision_context = conversation_context[
: _trimmable_budget(
decision_total, decision_scaffold + evidence_chars, _MAX_CONTEXT_CHARS
)
]
decision, decision_reasoning, _finish_reason, _usage = await self._stream_completion(
run,
[
{
"role": "system",
"content": decision_system,
},
{
"role": "user",
"content": (
f"Conversation context JSON:\n{_shield_untrusted(decision_context)}\n\n"
f"Question:\n{_shield_untrusted(decision_question)}\n\n"
f"Approved plan (guidance only):\n"
f"{_shield_untrusted(decision_plan_json)}\n\n"
f"Actions remaining after this one: {max_steps - position - 1}\n"
f"<untrusted_query_history_json>\n"
f"{_shield_untrusted(decision_query_history_json)}\n"
f"</untrusted_query_history_json>\n\n"
f"<untrusted_research_state_json>\n"
f"{_shield_untrusted(decision_state_json) or '{}'}\n"
f"</untrusted_research_state_json>\n\n"
f"<untrusted_web_evidence>\n"
f"Gathered sources:\n{_shield_untrusted(decision_catalog) or '(none)'}\n\n"
f"{_shield_untrusted(evidence[-evidence_chars:] if evidence_chars else '') or '(none)'}\n"
f"</untrusted_web_evidence>"
),
},
],
json_mode = True,
report_progress = False,
phase = "decision",
step_position = position,
max_tokens = 2048,
enable_thinking = False,
)
try:
action = _parse_and_validate_action(
decision,
decision_reasoning,
{source["url"] for source in sources},
website_policy,
)
except (ValueError, json.JSONDecodeError):
action = _next_unused_seed_action(run["plan"], used_queries)
if action is None:
break
if action["action"] == "finish":
if notes:
next_state = _normalize_research_state(action.get("researchState"))
if next_state:
research_state = next_state
break
action = _next_unused_seed_action(run["plan"], used_queries)
if action is None:
break
argument = action.get("query") or action.get("url") or ""
if action["action"] == "search":
try:
argument = _sanitize_public_query(argument)
action["query"] = argument
except ValueError:
replacement = _next_unused_seed_action(run["plan"], used_queries)
if replacement is None:
break
action = replacement
argument = action["query"]
duplicate = (action["action"] == "search" and argument in used_queries) or (
action["action"] == "fetch" and argument in fetched_urls
)
if duplicate:
action = _next_unused_seed_action(run["plan"], used_queries)
if action is None:
break
argument = action["query"]
# Only after the action is final, so rejected decisions cannot leak stale state.
next_state = _normalize_research_state(action.get("researchState"))
if next_state:
research_state = next_state
written = await asyncio.to_thread(
db.upsert_execution_step,
run["id"],
position,
action["title"],
argument,
"running",
None,
self.worker_id,
)
await self._check_worker_write(run["id"], written)
seq = await asyncio.to_thread(
db.append_worker_event,
run["id"],
self.worker_id,
"step.started",
{
"position": position,
"stepPosition": position,
"title": action["title"],
"action": action["action"],
"input": argument,
},
)
await self._check_worker_write(run["id"], seq is not None)
mcp_sources = []
if action["action"] == "fetch":
fetched_urls.add(argument)
result = await asyncio.to_thread(
execute_tool,
"web_search",
{"url": argument},
cancel_event = self._cancel_event(run["id"]),
timeout = tool_timeout,
website_policy = website_policy,
)
rag_result = ""
else:
used_queries.add(argument)
# Side lookups overlap the web search; awaited after it so a web error still wins.
rag_task = (
asyncio.ensure_future(
asyncio.to_thread(
execute_tool,
"search_knowledge_base",
{"query": argument},
cancel_event = self._cancel_event(run["id"]),
timeout = tool_timeout,
rag_scope = run["config"]["ragScope"],
)
)
if run["config"].get("ragScope")
else None
)
mcp_task = (
asyncio.ensure_future(
self._search_mcp_tools(run, mcp_tools, argument, position, tool_timeout)
)
if mcp_tools
else None
)
side_tasks = [task for task in (rag_task, mcp_task) if task is not None]
try:
result = await asyncio.to_thread(
execute_tool,
"web_search",
{"query": argument},
cancel_event = self._cancel_event(run["id"]),
timeout = tool_timeout,
website_policy = website_policy,
)
rag_result = await rag_task if rag_task is not None else ""
if mcp_task is not None:
mcp_sources = await mcp_task
except BaseException:
for task in side_tasks:
task.cancel()
await asyncio.gather(*side_tasks, return_exceptions = True)
raise
rag_result, rag_sources = _split_rag_result(rag_result)
await self._check_active(run["id"])
document_source_keys = {
str(
source.get("chunkId")
or f"{source.get('documentId') or source.get('filename')}:{source.get('page') or ''}"
)
for source in document_sources
}
accepted_rag_sources = []
for source in rag_sources:
source_key = str(
source.get("chunkId")
or f"{source.get('documentId') or source.get('filename')}:{source.get('page') or ''}"
)
if source_key not in document_source_keys:
if len(document_sources) >= max_sources:
continue
written = await asyncio.to_thread(
db.upsert_document_source,
run["id"],
position,
source,
self.worker_id,
)
await self._check_worker_write(run["id"], written)
document_source_keys.add(source_key)
document_sources.append({**source, "stepPosition": position})
accepted_rag_sources.append(source)
if accepted_rag_sources:
rag_result = "\n\n".join(
f"Document: {source.get('filename') or 'Document'}"
f"{', page ' + str(source.get('page')) if source.get('page') is not None else ''}\n"
f"{source.get('text') or source.get('snippet') or ''}"
for source in accepted_rag_sources
)
elif rag_sources:
# uncataloged chunks lose citations; keep text-only replies when no chunks exist.
rag_result = ""
rag_sources = accepted_rag_sources
for source in mcp_sources:
if len(document_sources) >= max_sources:
break
written = await asyncio.to_thread(
db.upsert_document_source,
run["id"],
position,
source,
self.worker_id,
)
await self._check_worker_write(run["id"], written)
document_sources.append({**source, "stepPosition": position})
rag_sources.append(source)
step_sources = []
for match in _URL_BLOCK.finditer(result if action["action"] == "search" else ""):
if len(sources) >= max_sources:
break
source = {k: match.group(k).strip() for k in ("title", "url", "snippet")}
allowed, _reason, _hostname = check_url_access(
source["url"],
website_policy,
)
if not allowed:
continue
if source["url"] in {s["url"] for s in sources}:
continue
sources.append(source)
step_sources.append(source)
await self._check_active(run["id"])
written = await asyncio.to_thread(
db.upsert_source,
run["id"],
position,
source["url"],
source["title"],
source["snippet"],
self.worker_id,
)
await self._check_worker_write(run["id"], written)
tool_failed = is_tool_error(result)
step_failed = _research_step_failed(result, rag_sources)
scraped_section = ""
if (
action["action"] == "search"
and step_sources
and not tool_failed
and max_auto_scrape > 0
):
scraped_section, scraped_urls = await self._auto_scrape_sources(
run,
question,
step_sources,
fetched_urls,
limit = max_auto_scrape,
tool_timeout = tool_timeout,
website_policy = website_policy,
)
fetched_urls.update(scraped_urls)
await self._check_active(run["id"])
if scraped_section:
# replacing snippets with scraped chunks reduced accuracy.
result = _merge_scraped_evidence(result, scraped_section)
mcp_evidence = _mcp_evidence(
[source for source in rag_sources if source.get("kind") == "mcp"]
)
heading = f"### {action['title']} ({action['action']})\nInput: {argument}"
web_part = f"Result:\n{result[:12000]}"
rag_part = f"Knowledge base:\n{rag_result[:6000]}{mcp_evidence}"
# Text-only replies such as "No matching chunks" stay behind the web results, cut first.
notes.append(
(heading, web_part, rag_part)
if rag_sources
else f"{heading}\n{web_part}\n\n{rag_part}"
if rag_result
else f"{heading}\n{web_part}"
)
decision_notes.append(f"{heading}\nResult:\n{result[:12000]}")
clean_result = strip_result_for_model(result, "web_search")
if step_failed:
step_error = _preferred_step_error(step_error, clean_result[:500])
else:
completed_steps += 1
step_result = {
"action": action["action"],
"input": argument,
"sourceCount": len(step_sources) + len(rag_sources),
"sourceUrls": [source["url"] for source in step_sources],
"evidenceSources": rag_sources,
**(
{"excerpt": clean_result[:12000]}
if action["action"] == "fetch" or scraped_section
else {}
),
**({"researchState": research_state} if research_state else {}),
# tool_failed as well as step_failed: a tool error RAG rescued still records why.
**({"error": clean_result[:500]} if tool_failed or step_failed else {}),
}
await self._check_active(run["id"])
written = await asyncio.to_thread(
db.upsert_execution_step,
run["id"],
position,
action["title"],
argument,
"failed" if step_failed else "completed",
step_result,
self.worker_id,
)
await self._check_worker_write(run["id"], written)
seq = await asyncio.to_thread(
db.append_worker_event,
run["id"],
self.worker_id,
"step.failed" if step_failed else "step.completed",
{
"position": position,
"stepPosition": position,
"title": action["title"],
"action": action["action"],
"input": argument,
"sourceCount": len(step_sources) + len(rag_sources),
**({"error": clean_result[:500]} if step_failed else {}),
},
)
await self._check_worker_write(run["id"], seq is not None)
await self._check_active(run["id"])
if not completed_steps and not sources and not document_sources:
raise ValueError(f"No research step gathered any evidence. {step_error}".rstrip())
web_entries = [
f"{index}. Title: {_citation_title(source, source['url'])}\n URL: {source['url']}"
for index, source in enumerate(sources, 1)
]
document_entries = [
f"{index}. Filename: {source.get('filename') or 'Document'}\n"
f" Page: {source.get('page') if source.get('page') is not None else '(unknown)'}\n"
f" Citation: {_document_source_citation(source)}\n"
f" Document ID: {source.get('documentId') or '(unknown)'}\n"
f" Chunk ID: {source.get('chunkId') or '(unknown)'}"
for index, source in enumerate(document_sources, 1)
]
await _refresh_served_context_length(run)
# Model-derived JSON shares the evidence budget; history gets only what the fixed scaffold leaves.
total_budget = _prompt_char_budget(
_SYNTHESIS_CONTEXT_RESERVE_TOKENS, _run_inference_request(run)
)
plan_json = json.dumps(run["plan"], ensure_ascii = False)
audit_system = _system_prompt_with_instructions(
_SYNTHESIS_AUDIT_SYSTEM_PROMPT,
run["config"],
)
report_system = _system_prompt_with_instructions(_REPORT_SYSTEM_PROMPT, run["config"])
catalog_chars = len("\n".join(web_entries)) + len("\n".join(document_entries))
source_catalog, document_source_catalog = _fit_synthesis_catalogs(
web_entries,
document_entries,
catalog_chars
if total_budget is None or not document_entries
else max(
0,
total_budget
- max(len(audit_system), len(report_system))
- len(question)
- len(plan_json),
)
// 2,
)
audit_scaffold_chars = (
len(audit_system)
+ len(question)
+ len(plan_json)
+ len(source_catalog)
+ len(document_source_catalog)
)
audit_evidence_text, [audit_state_json] = _fit_synthesis_context(
notes,
[research_state],
audit_scaffold_chars,
_run_inference_request(run),
)
audit_conversation_context = conversation_context[
: _trimmable_budget(
total_budget,
audit_scaffold_chars + len(audit_evidence_text) + len(audit_state_json),
_MAX_CONTEXT_CHARS,
)
]
(
audit_response,
audit_reasoning,
_audit_finish_reason,
_audit_usage,
) = await self._stream_completion(
run,
[
{
"role": "system",
"content": audit_system,
},
{
"role": "user",
"content": (
f"<conversation_context_json>\n"
f"{_shield_untrusted(audit_conversation_context)}\n"
f"</conversation_context_json>\n\n"
f"<research_question>\n{_shield_untrusted(question)}\n"
f"</research_question>\n\n"
f"<approved_plan>\n"
f"{_shield_untrusted(plan_json)}\n"
f"</approved_plan>\n\n"
f"<source_catalog>\n"
f"{_shield_untrusted(source_catalog) or '(no web sources gathered)'}\n"
f"</source_catalog>\n\n"
f"<document_source_catalog>\n"
f"{_shield_untrusted(document_source_catalog) or '(no document sources gathered)'}\n"
f"</document_source_catalog>\n\n"
f"<untrusted_research_state_json>\n"
f"{_shield_untrusted(audit_state_json)}\n"
f"</untrusted_research_state_json>\n\n"
f"<untrusted_evidence>\n{_shield_untrusted(audit_evidence_text)}\n"
f"</untrusted_evidence>"
),
},
],
json_mode = True,
report_progress = False,
phase = "synthesis_audit",
max_tokens = 2048,
enable_thinking = False,
)
synthesis_audit: dict[str, Any] = {}
for candidate in (audit_response, audit_reasoning):
if not candidate.strip():
continue
try:
synthesis_audit = _normalize_synthesis_audit(
_parse_json_object(candidate),
{source["url"] for source in sources},
_allowed_document_citations(document_sources),
)
if synthesis_audit:
break
except (ValueError, json.JSONDecodeError):
continue
report_scaffold_chars = (
len(report_system)
+ len(question)
+ len(plan_json)
+ len(source_catalog)
+ len(document_source_catalog)
)
evidence_text, [synthesis_audit_json, synthesis_state_json] = _fit_synthesis_context(
notes,
[synthesis_audit, research_state],
report_scaffold_chars,
_run_inference_request(run),
)
synthesis_conversation_context = conversation_context[
: _trimmable_budget(
total_budget,
report_scaffold_chars
+ len(evidence_text)
+ len(synthesis_audit_json)
+ len(synthesis_state_json),
_MAX_CONTEXT_CHARS,
)
]
synthesis_messages = [
{
"role": "system",
"content": report_system,
},
{
"role": "user",
"content": (
f"<conversation_context_json>\n"
f"{_shield_untrusted(synthesis_conversation_context)}\n"
f"</conversation_context_json>\n\n"
f"<research_question>\n{_shield_untrusted(question)}\n"
f"</research_question>\n\n"
f"<approved_plan>\n{_shield_untrusted(plan_json)}\n"
f"</approved_plan>\n\n"
f"<source_catalog>\n{_shield_untrusted(source_catalog) or '(no web sources gathered)'}\n"
f"</source_catalog>\n\n"
f"<document_source_catalog>\n"
f"{_shield_untrusted(document_source_catalog) or '(no document sources gathered)'}\n"
f"</document_source_catalog>\n\n"
f"<untrusted_research_state_json>\n"
f"{_shield_untrusted(synthesis_state_json)}\n"
f"</untrusted_research_state_json>\n\n"
f"<untrusted_synthesis_audit_json>\n"
f"{_shield_untrusted(synthesis_audit_json)}\n"
f"</untrusted_synthesis_audit_json>\n\n"
f"<untrusted_evidence>\n{_shield_untrusted(evidence_text)}\n"
f"</untrusted_evidence>"
),
},
]
def _delivered(draft: str) -> str:
"""What the reader would get: a model out of budget pads with citations validation drops."""
return _validate_report(draft, sources, document_sources)
def _keep_draft(
report: str,
finish_reason: str | None,
reason: str = "",
) -> None:
"""Keep the best report reached, so a later failure can still publish it. Ranked as
the success path ranks its drafts: finished over cut off, then longer, then newest."""
if not reason and finish_reason == "length":
# Without the token count, which only a call reaching its own end reports.
reason = _synthesis_length_limit_error(
None, requested_max_tokens = 0, inference = _run_inference_request(run)
).rstrip(".")
text = _delivered(report).strip()
draft = _ReportDraft(
text, finish_reason in _NATURAL_FINISH_REASONS and bool(text), reason
)
kept = self._report_drafts.get(account_key(run["id"]))
if kept is None or (draft.whole, len(draft.text)) >= (kept.whole, len(kept.text)):
self._report_drafts[account_key(run["id"])] = draft
def _keep_partial(content: str, reasoning: str, finish_reason: str | None) -> None:
"""Keep a cut-off stream's text past the final-report boundary; above it is analysis."""
draft = (
_report_after_boundary(content, _REPORT_BOUNDARY_MARKER)
or _report_after_boundary(reasoning, _REPORT_BOUNDARY_MARKER)
or ""
)
_keep_draft(draft, finish_reason)
synthesis_max_tokens = await asyncio.to_thread(
_synthesis_max_tokens,
run["config"].get("inferenceRequest") or {},
(run["config"].get("budgets") or {}).get("modelTimeoutSeconds"),
)
try:
(
report,
synthesis_reasoning,
synthesis_finish_reason,
synthesis_usage,
) = await self._stream_completion(
run,
synthesis_messages,
phase = "synthesis",
max_tokens = synthesis_max_tokens,
on_partial = _keep_partial,
)
except (RunCancelled, LeaseLost, httpx.ReadTimeout):
raise
except Exception:
if synthesis_max_tokens <= _SYNTHESIS_MAX_TOKENS:
raise
# Connection refusals of a raised budget can't be enumerated; failing would discard a finished run.
logger.warning(
"research.synthesis_budget_refused run_id=%s budget=%s",
run["id"],
synthesis_max_tokens,
exc_info = True,
)
await self._check_active(run["id"])
synthesis_max_tokens = _SYNTHESIS_MAX_TOKENS
(
report,
synthesis_reasoning,
synthesis_finish_reason,
synthesis_usage,
) = await self._stream_completion(
run,
synthesis_messages,
phase = "synthesis",
max_tokens = synthesis_max_tokens,
on_partial = _keep_partial,
)
report = _select_synthesis_report(report, synthesis_reasoning)
# Before the checks below, which can fail once the report already exists.
_keep_draft(report, synthesis_finish_reason)
await self._check_active(run["id"])
truncation_notice = ""
if _synthesis_needs_recovery(report, synthesis_finish_reason):
recovery_reason = (
"exhausted its output budget"
if synthesis_finish_reason == "length"
else "did not return a safely identifiable final report"
)
recovery_messages = [
{
**synthesis_messages[0],
"content": (
synthesis_messages[0]["content"]
+ f"\nThe previous synthesis {recovery_reason}. Write the report "
"directly without exposing analysis or reconstructing source URLs. Copy "
"citation titles and URLs only from the supplied catalogs. Begin with the "
"required final-report boundary on its own line."
),
},
synthesis_messages[1],
]
recovery_max_tokens = _resolve_max_tokens(
synthesis_max_tokens,
_run_inference_request(run),
recovery_messages,
)
try:
(
recovered_report,
recovery_reasoning,
recovery_finish_reason,
recovery_usage,
) = await self._stream_completion(
run,
recovery_messages,
phase = "synthesis_recovery",
max_tokens = synthesis_max_tokens,
enable_thinking = False,
on_partial = _keep_partial,
)
except (RunCancelled, LeaseLost):
raise
except Exception:
# Failing discards the draft being rescued; its larger prompt may be refused where the first fit.
logger.warning(
"research.synthesis_recovery_failed run_id=%s budget=%s",
run["id"],
synthesis_max_tokens,
exc_info = True,
)
await self._check_active(run["id"])
recovered_report, recovery_reasoning = "", ""
recovery_finish_reason, recovery_usage = None, None
synthesis_reasoning += recovery_reasoning
recovered = _select_synthesis_report(recovered_report, recovery_reasoning)
# A recovery reaching a natural stop wins; else the longer draft, measured post-validation.
comparable_recovered = _delivered(recovered)
comparable_report = _delivered(report)
recovered_whole = (
bool(comparable_recovered) and recovery_finish_reason in _NATURAL_FINISH_REASONS
)
take_recovery = recovered_whole or len(comparable_recovered) >= len(comparable_report)
requested_max_tokens = recovery_max_tokens
if take_recovery:
report = recovered
synthesis_finish_reason = recovery_finish_reason
synthesis_usage = recovery_usage
else:
requested_max_tokens = _resolve_max_tokens(
synthesis_max_tokens,
_run_inference_request(run),
synthesis_messages,
)
_keep_draft(report, synthesis_finish_reason)
await self._check_active(run["id"])
if report and synthesis_finish_reason == "length":
truncation_notice = _synthesis_length_limit_error(
synthesis_usage,
requested_max_tokens = requested_max_tokens,
inference = _run_inference_request(run),
).rstrip(".")
report = _validate_report(report, sources, document_sources)
if not report:
raise ValueError(
"Local model returned no safely identifiable final report. Disable thinking or "
"use a compatible chat template and retry."
)
# Notice goes above, after the validators, which must only ever see what the model wrote.
_keep_draft(report, synthesis_finish_reason, truncation_notice)
if truncation_notice:
report = _report_under_notice(report, "Incomplete report.", f"{truncation_notice}.")
reasoning = await asyncio.to_thread(db.get_reasoning_text, run["id"])
if synthesis_reasoning and synthesis_reasoning not in reasoning:
reasoning += synthesis_reasoning
# Renew ownership before syncing the discoverable chat message; a restarted worker can safely overwrite it.
renewed = await asyncio.to_thread(db.heartbeat, run["id"], self.worker_id)
if not renewed:
await self._check_active(run["id"])
raise LeaseLost()
await asyncio.to_thread(
_update_assistant,
run,
report,
"completed",
sources,
reasoning,
self.worker_id,
)
actual_status = await self._finish_terminal(run["id"], "completed", None, report)
if actual_status is None:
raise LeaseLost()
run = await asyncio.to_thread(db.get_run, run["id"])
if actual_status == "cancelled" and not _run_moved_on(run, research_attempt):
await asyncio.to_thread(_update_assistant, run, "Research cancelled.", "cancelled")
def retire_account_research(account) -> None:
"""Cancel this account's in-flight generation without stopping the supervisor."""
for supervisor in tuple(_supervisors):
for key, event in list(supervisor._cancel_events.items()):
if (isinstance(key, str) and account.is_owner) or (
isinstance(key, tuple) and key[0] == account.account_id
):
event.set()