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
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
"""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<untrusted-data\b[^>]*>.*</untrusted-data>\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 "<untrusted-data" in value.lower()


def _wrap_untrusted_value(value: Any, *, source: str) -> 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]}