"""Agentic tool loop for the Dracull chat endpoint.
Instead of a single completion, /api/chat now lets the model call real-time
web and browser-control tools (see chat_tools) and weave the results into a
final answer. Providers that cannot accept the `tools` parameter degrade to
a plain completion, so nothing that worked before breaks.
"""
import json
import re
from collections.abc import Awaitable, Callable, Iterator
from typing import Any
from .chat_tools import (
ChatBrowserSession,
build_tool_schemas,
)
from .config import settings
from .runtime.caps import MAX_ATTEMPTS, is_retryable, run_bounded
from .runtime.ledger import LedgerEntry, honest_mixed_result_sentence, summarize
from .runtime.untrusted import (
UNTRUSTED_SYSTEM_RULE,
detect_handoff,
wrap_untrusted,
)
from .tools.constants import RESULT_TEXT_CAP
from .tools.executor import execute_tool_calls
PER_CALL_TIMEOUT = 60
# Error classification shared by the tool loop and the /api/chat handler.
# Classification keys on exception class names in the MRO (covers litellm.Timeout,
# litellm.NotFoundError, openai's APITimeoutError, ...), the APIStatusError
# status_code and the message text — so wrapped/proxied provider errors still
# classify even when the concrete class differs.
CHAT_ERROR_HINTS = {
"timeout": "Pick another model or retry later.",
"model_not_found": "Check the model id — this provider does not offer it.",
"auth": "Check the API key for this provider in Settings.",
"rate_limit": "You are rate limited — wait a moment and retry.",
"other": "Check the provider status or try another model.",
}
def classify_chat_error(exc: BaseException) -> str:
"""Map a provider failure to one of the errorKinds in CHAT_ERROR_HINTS."""
class_names = {cls.__name__ for cls in type(exc).__mro__}
text = str(exc).lower()
status = getattr(exc, "status_code", None)
try:
status = int(status) if status is not None else None # APIStatusError carries an int
except (TypeError, ValueError):
status = None
if "Timeout" in class_names or "APITimeoutError" in class_names or "timed out" in text:
return "timeout"
# Auth must be tested BEFORE model_not_found: providers phrase 401s as
# "API key not found", and the message-text branch below would otherwise
# send the user to check the model id instead of their key.
if "AuthenticationError" in class_names or status == 401 or "api key" in text:
return "auth"
if (
"NotFoundError" in class_names
or status == 404
or "does not exist" in text
or "not found" in text
):
return "model_not_found"
if "RateLimitError" in class_names or status == 429:
return "rate_limit"
return "other"
# Tool results are JSON envelopes, but several values inside them come from
# the active page (title, URL, visible text, search-result fields, and the
# page-derived text embedded in verification descriptions). Keep the envelope
# and control-plane fields trusted, and wrap every page-controlled STRING at
# the value boundary. A name-based tool allowlist is intentionally not used:
# adding a new tool must not silently create a new prompt-injection path.
_PAGE_CONTROLLED_KEYS = frozenset({
"accessible_name",
"description",
"snippet",
"state",
"text",
"title",
"url",
})
_UNTRUSTED_BLOCK_RE = re.compile(
r"\A]*>.*\Z",
re.DOTALL | re.IGNORECASE,
)
# Preserve the five tools' source labels for their broad page payloads. Their
# values are still marked at the field boundary, so the structural envelope
# stays trusted and machine-readable for every tool.
_LEGACY_TOOL_SOURCES = {
"observe": "page",
"extract_text": "page",
"navigate": "page",
"http_fetch": "http",
"web_search": "search",
}
def _is_wrapped_untrusted(value: str) -> bool:
"""True when a value already is one complete untrusted-data block."""
return bool(_UNTRUSTED_BLOCK_RE.fullmatch(value))
def _contains_untrusted_block(value: str) -> bool:
"""True when a string contains an untrusted-data block."""
return " Any:
"""Wrap one page-controlled string, leaving an existing block unchanged."""
if not isinstance(value, str) or not value or _is_wrapped_untrusted(value):
return value
return wrap_untrusted(value, source=source)
def _wrap_page_controlled_values(value: Any, *, source: str) -> Any:
"""Recursively wrap page-controlled strings in a tool result.
The structural envelope and ordinary control-plane values stay intact.
Only fields whose contents originate in the page are wrapped; the trusted
``error`` payload is deliberately excluded.
"""
if isinstance(value, dict):
wrapped: dict[str, Any] = {}
for key, item in value.items():
if key == "error":
wrapped[key] = item
elif key in _PAGE_CONTROLLED_KEYS and isinstance(item, str):
wrapped[key] = _wrap_untrusted_value(item, source=source)
elif isinstance(item, str) and _contains_untrusted_block(item):
# A pre-wrapped value may live under any structural key. Keep it
# exactly once instead of nesting another boundary around it.
wrapped[key] = item
else:
wrapped[key] = _wrap_page_controlled_values(item, source=source)
return wrapped
if isinstance(value, list):
return [_wrap_page_controlled_values(item, source=source) for item in value]
if isinstance(value, tuple):
return tuple(_wrap_page_controlled_values(item, source=source) for item in value)
return value
def _model_visible_tool_content(
result: dict[str, Any],
*,
source: str,
tool_name: str | None = None,
) -> str:
"""Build one tool message with page-derived values marked untrusted.
The structural envelope stays JSON and trusted. Only page-controlled
strings inside it are wrapped, so the model can still read ``ok``, ``tool``
and action metadata while treating titles, URLs and page text as data.
"""
envelope = result["envelope"]
if envelope.get("ok") is not True:
# Structured executor failures are trusted control-plane data, not page
# text. Keep their JSON envelope machine-readable and unwrapped.
return str(result["content"])
safe_envelope = _wrap_page_controlled_values(envelope, source=source)
return json.dumps(safe_envelope, default=str)[:RESULT_TEXT_CAP]
CAPABILITY_SUFFIX = """
## Real-time web & browser control (always available)
You run inside Dracull Browser V2 with LIVE internet access and full control of a real
configured automation browser. You are NOT limited to training data.
- When the user asks which browser you use, call browser_capabilities and report the
REAL name/version it returns — never assume Chrome. A Firefox/Mozilla request is
refused (UNSUPPORTED_BROWSER, needs_consent) until the user approves a substitution.
- Tabs: tab_open (no url → about:blank), tab_list (source of truth for tab ids),
tab_select(tab_id), tab_close(tab_id).
- Page cycle: navigate → observe → act. observe returns a snapshot_id plus numbered
elements; click/type/select_option need BOTH the element index and the CURRENT
snapshot_id. A stale snapshot returns STALE_ELEMENT — observe again.
- Also available: scroll(pixels), press_key, extract_text, screenshot, wait_for
(timeout_ms is hard-capped at 15000).
- http_fetch reads a public page OUTSIDE the browser (source=http) — its results are
never tab results. Use it for plain reads; use the browser tools when a real tab is
needed.
- After acting, verify with observe/extract_text before claiming success; navigate
already reads back the final URL and title into verification.
- localhost, intranet and private-IP addresses are blocked by policy, as are
javascript:, file:, data: and chrome: URLs.
- type with submit=true sends data: it is refused pending user approval (Phase 3).
- Keep it efficient: usually 1-5 tool calls total, then answer in full prose.
""" + UNTRUSTED_SYSTEM_RULE
def _shorten_detail(payload: dict, limit: int = 90) -> str:
if "error" in payload:
error = payload["error"]
if isinstance(error, dict):
# Structured classified error (plan Table 4): show the one-step
# user message, never a traceback.
return str(error.get("message") or error.get("code") or "error")[:limit]
return str(error)[:limit]
# Phase 2 envelope: the interesting values live under "data".
data = payload.get("data")
if isinstance(data, dict):
return _shorten_detail(data, limit)
for key in ("url", "query", "clicked", "filled", "pressed", "path", "result", "scrolled"):
if key in payload:
value = str(payload[key])
return value[:limit]
if "closed" in payload:
return f"closed tab {payload['closed']} — {payload.get('open_tabs', '?')} open"
if "results" in payload:
return f"{len(payload['results'])} results"
if "tabs" in payload:
return f"{len(payload['tabs'])} tabs"
return "ok"
def _assistant_tool_message(message: Any) -> dict:
"""Convert a LiteLLM response message carrying tool_calls into a plain dict."""
data = message.model_dump(exclude_none=True) if hasattr(message, "model_dump") else dict(message)
tool_calls = []
for tc in data.get("tool_calls") or []:
fn = tc.get("function") or {}
tool_calls.append({
"id": tc.get("id"),
"type": "function",
"function": {"name": fn.get("name"), "arguments": fn.get("arguments") or "{}"},
})
return {"role": "assistant", "content": data.get("content") or "", "tool_calls": tool_calls}
def _usage_of(response: Any) -> tuple[int, int]:
usage = getattr(response, "usage", None)
return (getattr(usage, "prompt_tokens", 0) or 0, getattr(usage, "completion_tokens", 0) or 0)
def _detect_handoff(envelope: dict[str, Any]) -> Any:
"""Does this tool result show a step only a human may complete?
The detector accepts the structured observe payload (elements with
DOM-like attributes) and raw HTML, so both shapes of page content are
checked.
"""
data = envelope.get("data")
if isinstance(data, dict):
found = detect_handoff(data)
if found is not None:
return found
html = data.get("html")
if isinstance(html, str) and "<" in html and ">" in html:
return detect_handoff(html)
return None
if isinstance(data, str) and "<" in data and ">" in data:
return detect_handoff(data)
return None
def usable_chat_messages(raw_messages: list[dict]) -> list[dict]:
"""The conversation turns the loop accepts: user/assistant with non-empty content.
Single source of this rule — the handler validates and counts with it, and
run_chat builds its prompt from it, so the two can never drift apart.
"""
usable: list[dict] = []
for m in raw_messages[-24:]:
role = m.get("role")
content = (m.get("content") or "").strip()
if role in ("user", "assistant") and content:
usable.append({"role": role, "content": content})
return usable
async def run_chat(
*,
provider: str,
full_model: str,
api_key: str | None,
base_url: str | None,
system: str,
raw_messages: list[dict],
temperature: float,
browser: ChatBrowserSession,
max_tokens: int | None = None,
) -> dict:
"""Run the tool loop; returns {content, usage, tool_trace, degraded?}."""
import litellm # local import keeps startup light when chat is unused
messages: list[dict] = [{"role": "system", "content": (system or "").rstrip() + CAPABILITY_SUFFIX}]
messages.extend(usable_chat_messages(raw_messages))
tool_schemas = build_tool_schemas()
tool_trace: list[dict] = []
prompt_total = completion_total = 0
def completion_kwargs(**extra: Any) -> dict:
kwargs: dict = {
"model": full_model,
"messages": messages,
"temperature": temperature,
"timeout": PER_CALL_TIMEOUT,
# The underlying client retries by default, which stretched a
# single provider failure to minutes. Fail fast; the UI retries.
"num_retries": 0,
}
if max_tokens:
kwargs["max_tokens"] = max_tokens
if api_key:
kwargs["api_key"] = api_key
if base_url:
kwargs["base_url"] = base_url
if provider != "anthropic":
kwargs["custom_llm_provider"] = "openai"
kwargs.update(extra)
return kwargs
async def call_llm(**extra: Any) -> Any:
return await litellm.acompletion(**completion_kwargs(**extra))
# ── the bounded provider/tool loop ──────────────────────────────────────
# The four caps live in runtime/caps.py and are the SAME policy the
# workflow runner uses: max steps, a per-round timeout, at most two
# attempts and only for a retryable envelope, and one total wall clock.
# The live loop used to run its own 8-iteration `for` loop, so none of
# those caps governed a real conversation.
#
# The rounds are produced DYNAMICALLY (each round depends on the model's
# previous answer), which run_bounded supports because it consumes its
# step source lazily.
ledger: list[LedgerEntry] = []
final_content: str | None = None
degraded = False
round_index = 0
async def _execute_with_retry_budget(
tool_calls: list[Any],
) -> list[dict[str, Any]]:
"""Execute one provider batch, retrying ONLY retryable envelopes.
The retry unit is the TOOL CALL, not the provider round: retrying a
round would pay for another LLM call to re-run a tool that already
failed. A consequential action is never retried - its envelope says
retryable=false.
"""
results = await execute_tool_calls(browser, tool_calls)
final: list[dict[str, Any]] = []
for call, result in zip(tool_calls, results):
attempts = 1
envelope = result["envelope"]
while (
envelope.get("ok") is False
and is_retryable(envelope)
and attempts < MAX_ATTEMPTS
):
retry_results = await execute_tool_calls(browser, [call])
if not retry_results:
break
result = retry_results[0]
envelope = result["envelope"]
attempts += 1
final.append(result)
return final
async def _run_round() -> dict[str, Any]:
"""One provider round: ask the model, run its tools, record the truth."""
nonlocal prompt_total, completion_total, final_content, degraded, round_index
iteration = round_index
round_index += 1
try:
response = await call_llm(tools=tool_schemas)
except Exception as exc:
# Only a provider that "supports none of this" gets the tool-less retry:
# an unclassified failure may be a rejected `tools` parameter. A
# timeout/auth/rate-limit/model-not-found failure would fail the
# plain call the same way, so re-raise instead of paying a second
# PER_CALL_TIMEOUT to learn that.
if iteration == 0 and classify_chat_error(exc) == "other":
# Provider likely rejects function calling — degrade to a plain completion.
response = await call_llm()
prompt, completion = _usage_of(response)
prompt_total += prompt
completion_total += completion
content = (response.choices[0].message.content or "").strip()
if not content:
choice = response.choices[0]
content = (getattr(choice.message, "reasoning", None) or "").strip() \
or "(empty response from model)"
final_content = content
degraded = True
return {"ok": True, "data": {"final": True}}
raise
prompt, completion = _usage_of(response)
prompt_total += prompt
completion_total += completion
message = response.choices[0].message
tool_calls = getattr(message, "tool_calls", None)
if not tool_calls:
content = (message.content or "").strip()
if not content:
content = (getattr(message, "reasoning", None) or "").strip() \
or "(empty response from model)"
final_content = content
return {"ok": True, "data": {"final": True}}
messages.append(_assistant_tool_message(message))
# The executor owns argument parsing: the RAW provider arguments go
# in, so malformed JSON becomes a structured INVALID_ARGUMENTS error
# instead of being silently swallowed into empty arguments. One
# ordered role:"tool" message comes back per tool_call_id — including
# when the provider asked for several calls at once.
results = await _execute_with_retry_budget(tool_calls)
for tc, result in zip(tool_calls, results):
name = tc.function.name or ""
envelope = result["envelope"]
# The truth ledger is built from the ACTUAL envelopes, so the
# answer can be checked against what actually happened.
ledger.append(LedgerEntry.from_envelope(envelope))
tool_trace.append({
"tool": name,
"ok": bool(envelope.get("ok")),
"detail": _shorten_detail(envelope),
})
source = _LEGACY_TOOL_SOURCES.get(name, "page")
content = _model_visible_tool_content(
result, source=source, tool_name=name
)
messages.append({
"role": "tool",
"tool_call_id": result["tool_call_id"],
"content": content,
})
# A page that demands a human - a login, a one-time code, a
# payment, a CAPTCHA - is handed to the user. The agent never
# attempts it and never claims it did.
handoff = _detect_handoff(envelope)
if handoff is not None and handoff.required:
final_content = (
f"Human handoff required ({handoff.kind}). {handoff.reason} "
"The agent did not attempt it."
)
return {"ok": True, "data": {"final": True}}
return {"ok": True, "data": {"final": False}}
def _rounds() -> Iterator[Callable[[], Awaitable[dict[str, Any]]]]:
"""Produce one round-step at a time, until the model gives an answer."""
while final_content is None:
yield _run_round
loop_result = await run_bounded(
_rounds(),
max_steps=int(settings.agent_max_steps),
wall_clock_seconds=float(settings.agent_wall_clock_seconds),
# Each round is already bounded internally: the provider call has
# PER_CALL_TIMEOUT and every tool call has the executor's own
# per-tool timeout. The step timeout is the wall clock, so the wall
# clock - not a second, differently-valued deadline - is what ends a
# run, and the stop reason stays truthful.
step_timeout_seconds=float(settings.agent_wall_clock_seconds),
)
stop_reason: str | None = None
if final_content is None:
# A cap stopped the loop: force one final answer WITHOUT tools, and
# say plainly that the run was cut short.
stop_reason = loop_result.stop_reason
response = await call_llm()
prompt, completion = _usage_of(response)
prompt_total += prompt
completion_total += completion
content = (response.choices[0].message.content or "").strip() \
or "(empty response from model)"
final_content = content
final_content += (
f"\n\n[Stopped early: the {stop_reason} cap was reached after "
f"{loop_result.completed_steps} tool round(s). This is a partial "
"result, not a completed task.]"
)
# The answer is checked against the ledger. A MIXED result - some steps
# succeeded and some failed - must not be reported as a single success:
# that is the case where the model can say "the browser saw the page"
# after the browser step actually failed. An all-failed run is not
# rewritten: the model may be reporting the failure accurately, and every
# failure is already visible in the tool trace the UI renders.
if ledger:
facts = summarize(ledger)
mixed = bool(facts["tools_succeeded"]) and bool(facts["tools_failed"])
if mixed:
correction = honest_mixed_result_sentence(ledger)
failed = facts["failed_error_codes"]
if failed:
correction += " Failed steps: " + ", ".join(
f"{tool} ({code})" for tool, code in sorted(failed.items())
) + "."
final_content += "\n\n" + correction
return {"content": final_content, "usage": {
"prompt_tokens": prompt_total, "completion_tokens": completion_total,
}, "tool_trace": tool_trace, "degraded": degraded,
"stop_reason": stop_reason,
"ledger": [entry.__dict__ for entry in ledger]}