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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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
"""The deterministic tool executor β€” plan Chapter 7, steps 1-7.



One pipeline per tool call, always in this order:



1. validate the tool name against the registry   -> structured error

2. parse the arguments JSON (string or dict)     -> structured error

3. validate arguments against the registry model -> structured error

4. apply the permission/risk gate                -> APPROVAL_REQUIRED, no run

5. enforce the URL policy                        -> POLICY_BLOCKED

6. check the browser is connected                -> BROWSER_DISCONNECTED

   (a session with a rebuild path recovers in step 7 instead)

7. run under a timeout (asyncio.wait_for)        -> structured error on timeout



Every outcome returns the result envelope: ``{"ok": bool, "tool": name,

"data": ...}`` plus, on failure, ``{"error": {code, message, retryable,

diagnostic_id}}``; optional ``tab_id`` and ``verification`` are lifted to

envelope level when the handler reports them. ``execute_tool_calls`` turns a

multi-call provider response into exactly one ordered result per

``tool_call_id``.

"""

from __future__ import annotations

import asyncio
import contextlib
import inspect
import json
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any, Protocol

from pydantic import ValidationError

from ..browser.errors import (
    APPROVAL_REQUIRED,
    BROWSER_DISCONNECTED,
    INVALID_ARGUMENTS,
    POLICY_BLOCKED,
    UNKNOWN,
    ClassifiedError,
    classify_exception,
    write_diagnostic_log,
)
from ..config import settings
from ..protocol import HITLActionType
from .constants import RESULT_TEXT_CAP
from .registry import REGISTRY, ToolSpec
from .url_policy import PolicyViolation, enforce_url_policy


@dataclass(frozen=True)
class GateDecision:
    allowed: bool
    risk: str
    reason: str | None = None


class ApprovalResult(Protocol):
    """The minimal response shape needed from the live HITL broker."""

    request_id: str
    approved: bool
    data: dict[str, Any] | None


@dataclass(frozen=True)
class ApprovalRequest:
    """Secret-free description of the consequential action awaiting approval."""

    tool: str
    message: str
    details: dict[str, Any]


ApprovalRequester = Callable[[ApprovalRequest], Awaitable[ApprovalResult]]


async def _request_approval(

    tool: str,

    args: Any,

    requester: ApprovalRequester,

) -> ApprovalResult:
    """Ask a human to approve one consequential action.



    The request deliberately contains no argument values. A ``type`` request

    names only the target element index and that submission will happen; it

    never includes the text to type, and no other argument values are copied.

    """
    details: dict[str, Any] = {"tool": tool, "risk": "consequential"}
    if tool == "type":
        details["target_index"] = getattr(args, "index", None)
        details["will_submit"] = True
        message = (
            "Type into the element at index "
            f"{getattr(args, 'index', 'unknown')} and submit it"
        )
    else:
        message = f"Run the consequential action '{tool}'"
    outcome = requester(ApprovalRequest(tool=tool, message=message, details=details))
    # The protocol says the requester is async, but a SYNCHRONOUS approver is
    # a reasonable thing for an embedder to provide (a policy lookup that
    # answers immediately). Awaiting a plain value would raise TypeError and
    # turn a decision into an UNKNOWN error, so accept both shapes.
    if inspect.isawaitable(outcome):
        return await outcome
    return outcome  # type: ignore[return-value]


# Live diagnostic logs show the model calling Playwright-MCP-style tool names
# (browser_snapshot, browser_tabs, browser_new_tab) that this registry has
# never exposed β€” each became an UNKNOWN error and a wasted turn. These
# aliases resolve the familiar names onto the registry's canonical tools so
# orchestration survives the naming mismatch instead of failing it. The
# canonical name always wins in the envelope (plus an alias_for note), so the
# model can self-correct to the real schema.
TOOL_ALIASES: dict[str, str] = {
    "browser_navigate": "navigate",
    "browser_snapshot": "observe",
    "browser_click": "click",
    "browser_type": "type",
    "browser_press_key": "press_key",
    "browser_take_screenshot": "screenshot",
    "browser_tabs": "tab_list",
    "browser_tab_list": "tab_list",
    "browser_new_tab": "tab_open",
    "browser_tab_open": "tab_open",
    "browser_tab_select": "tab_select",
    "browser_close_tab": "tab_close",
    "browser_tab_close": "tab_close",
    "browser_select_option": "select_option",
    "browser_wait_for": "wait_for",
    "browser_extract_text": "extract_text",
    "browser_scroll": "scroll",
}
# Names that LOOK familiar but have no faithful registry equivalent: they stay
# unknown, and the unknown-tool error lists the real tools instead.
UNMAPPED_HINTS: tuple[str, ...] = (
    "browser_hover",
    "browser_console_messages",
    "browser_network_requests",
    "browser_evaluate",
    "browser_file_upload",
    "browser_handle_dialog",
)


async def _live_approval_request(request: ApprovalRequest) -> ApprovalResult:
    """Bridge the executor's secret-free request to the shared HITL broker."""
    from ..hitl.handler import hitl_handler

    response = await hitl_handler.request_confirmation(
        session_id="executor",
        action_type=HITLActionType.FORM_SUBMIT,
        title=f"Confirm consequential action: {request.tool}",
        message=request.message,
        details=request.details,
    )
    return response


# The production host installs the live broker explicitly. Keeping the module
# default empty makes direct executor use fail closed and keeps unit tests
# hermetic instead of accidentally waiting for a human.
approval_request: ApprovalRequester | None = None


def configure_approval_request(requester: ApprovalRequester | None) -> None:
    """Install (or clear) the process-wide live approval requester."""
    global approval_request
    approval_request = requester


def gate(spec: ToolSpec, args: Any, browser: Any = None) -> GateDecision:
    """Permission/risk hook (plan Chapter 7, step 4) β€” the single choke point.



    Phase 2 default policy: every non-consequential tool runs without approval;

    a ``consequential`` risk level is refused with APPROVAL_REQUIRED and never

    executed (the interactive approval UI wiring is Phase 3). ``type`` becomes

    consequential when it would submit (Table 5: submit counts as a

    consequential action), which only the user can approve.



    The session adds what only it can know: a click on a submit/pay control and

    an Enter keypress on a credential/payment page also SEND data. Those are

    resolved from the snapshot the session recorded, so the gate asks the

    human instead of silently sending.

    """
    risk = spec.risk
    if spec.name == "type" and bool(getattr(args, "submit", False)):
        risk = "consequential"
    elif spec.name == "click" and browser is not None:
        # An unreadable snapshot never blocks the action: if the approval
        # check itself cannot run, the action keeps its declared risk.
        with contextlib.suppress(Exception):
            if browser.element_requires_approval(args.index, args.snapshot_id):
                risk = "consequential"
    elif spec.name == "press_key" and browser is not None:
        with contextlib.suppress(Exception):
            if browser.key_requires_approval(args.key):
                risk = "consequential"
    if risk == "consequential":
        return GateDecision(
            False, risk, "this action sends or submits data and needs user approval"
        )
    return GateDecision(True, risk, None)


def _error_envelope(

    name: str,

    err: ClassifiedError,

    *,

    needs_consent: bool = False,

    data: dict[str, Any] | None = None,

    alias: dict[str, Any] | None = None,

) -> dict[str, Any]:
    envelope: dict[str, Any] = {"ok": False, "tool": name, "error": err.to_payload()}
    if data is not None:
        envelope["data"] = data
    if needs_consent:
        envelope["needs_consent"] = True
    if alias:
        envelope.update(alias)
    return envelope


def _success_envelope(

    name: str,

    data: dict[str, Any],

    alias: dict[str, Any] | None = None,

) -> dict[str, Any]:
    envelope: dict[str, Any] = {"ok": True, "tool": name, "data": data}
    tab_id = data.pop("tab_id", None)
    verification = data.pop("verification", None)
    if tab_id is not None:
        envelope["tab_id"] = tab_id
    if verification is not None:
        envelope["verification"] = verification
    if alias:
        envelope.update(alias)
    return envelope


def _invalid_arguments(

    name: str,

    message: str,

    operation: str,

    alias: dict[str, Any] | None = None,

) -> dict[str, Any]:
    err = ClassifiedError(INVALID_ARGUMENTS, message=message, operation=operation)
    write_diagnostic_log(err)
    return _error_envelope(name, err, alias=alias)


async def execute_tool(

    browser: Any,

    name: str,

    arguments: str | dict | None,

    *,

    approval_request: ApprovalRequester | None = None,

) -> dict[str, Any]:
    """Run one tool call and ALWAYS return an envelope β€” never raise.



    This wrapper is the structural guarantee of the tool contract: the chat

    loop puts the returned envelope straight into the model context, so an

    exception escaping here would abort the whole chat request. The pipeline

    below handles each failure class explicitly; this outer catch-all is the

    backstop for anything unforeseen (a malformed URL the policy module does

    not recognise, an exotic validation error, a third-party parser blowing

    up). Cancellation is the one exception: it is a control-flow signal, not a

    failure, and it propagates untouched.

    """
    canonical = TOOL_ALIASES.get(name, name)
    try:
        return await _execute_tool_pipeline(
            browser, name, arguments, approval_request=approval_request,
        )
    except asyncio.CancelledError:
        raise
    except Exception as exc:  # noqa: BLE001 β€” the contract is one envelope, always
        err = classify_exception(exc, operation=f"tool:{canonical}")
        write_diagnostic_log(err, exc)
        return _error_envelope(canonical, err)


async def _execute_tool_pipeline(

    browser: Any,

    canonical: str,

    arguments: str | dict | None,

    *,

    approval_request: ApprovalRequester | None = None,

) -> dict[str, Any]:
    """The tool pipeline itself; ``execute_tool`` wraps it with the backstop."""
    # ── 1. resolve the name against the registry (aliases included) ─────────
    requested = canonical
    canonical = TOOL_ALIASES.get(canonical, canonical)
    spec = REGISTRY.get(canonical)
    if spec is None:
        hint = ""
        if requested.lower() in UNMAPPED_HINTS:
            hint = (
                " β€” this agent has no such tool; use the registry tools listed "
                "here instead"
            )
        available = ", ".join(sorted(REGISTRY))
        err = ClassifiedError(
            UNKNOWN,
            message=f"unknown tool '{requested}'{hint}. Available tools: {available}",
            operation=f"tool:{requested}",
        )
        write_diagnostic_log(err)
        return _error_envelope(requested, err)

    operation = f"tool:{canonical}"
    alias_note: dict[str, Any] | None = (
        {"requested_alias": requested, "alias_for": canonical}
        if canonical != requested else None
    )

    # ── 2. parse the arguments (they may arrive as a JSON string) ───────────
    if isinstance(arguments, str):
        try:
            parsed = json.loads(arguments) if arguments.strip() else {}
        except json.JSONDecodeError as exc:
            return _invalid_arguments(
                canonical,
                f"arguments are not valid JSON ({exc.msg} at character {exc.pos})",
                operation,
                alias=alias_note,
            )
        except (RecursionError, ValueError) as exc:
            # A pathologically nested payload blows the JSON decoder's stack and
            # a bare number can decode to a non-object. Neither may escape as an
            # exception: the model only ever sees an envelope.
            return _invalid_arguments(
                canonical,
                f"arguments could not be decoded ({type(exc).__name__})",
                operation,
                alias=alias_note,
            )
    elif arguments is None:
        parsed = {}
    elif isinstance(arguments, dict):
        parsed = arguments
    else:
        parsed = None  # fall through to the object check below
    if not isinstance(parsed, dict):
        return _invalid_arguments(
            canonical, "arguments must be a JSON object", operation, alias=alias_note
        )

    # ── 3. validate against the registry model (extra keys rejected) ───────
    try:
        args = spec.model(**parsed)
    except ValidationError as exc:
        first = exc.errors()[0]
        loc = ".".join(str(part) for part in first.get("loc") or ())
        return _invalid_arguments(
            canonical, f"invalid arguments: {loc}: {first.get('msg')}", operation,
            alias=alias_note,
        )
    except TypeError as exc:
        # Non-string keys in a directly supplied dict make **kwargs explode.
        return _invalid_arguments(
            canonical, f"invalid arguments: {exc}", operation, alias=alias_note,
        )

    # ── 4. permission/risk gate ─────────────────────────────────────────────
    decision = gate(spec, args, browser)
    approval_envelope: dict[str, Any] | None = None
    if not decision.allowed:
        requester = approval_request if approval_request is not None else globals().get(
            "approval_request"
        )
        if requester is None:
            err = ClassifiedError(
                APPROVAL_REQUIRED,
                message=(
                    f"tool '{canonical}' requires approval, but no approval manager is "
                    "available. The action was not executed."
                ),
                operation=operation,
            )
            write_diagnostic_log(err)
            return _error_envelope(canonical, err, alias=alias_note)

        response = await _request_approval(canonical, args, requester)
        request_id = response.request_id
        if not response.approved:
            reason = (response.data or {}).get("reason", "denied")
            if str(reason).lower() == "timeout":
                message = (
                    f"approval request {request_id} timed out. The action was not executed."
                )
            else:
                message = (
                    f"approval request {request_id} was denied ({reason}). "
                    "The action was not executed."
                )
            err = ClassifiedError(
                APPROVAL_REQUIRED,
                message=message,
                operation=operation,
            )
            write_diagnostic_log(err)
            envelope = _error_envelope(canonical, err, alias=alias_note)
            envelope["approval"] = {
                "request_id": request_id,
                "approved": False,
                "reason": reason,
            }
            return envelope
        approval_envelope = {"request_id": request_id, "approved": True}

    # ── 5. URL policy, enforced in the executor (plan 7.1) ─────────────────
    if spec.url_field:
        url_value = getattr(args, spec.url_field, None)
        if url_value:
            try:
                await enforce_url_policy(
                    url_value,
                    allow_private=bool(settings.allow_private_networks),
                    context=spec.name,
                )
            except PolicyViolation as exc:
                err = ClassifiedError(
                    POLICY_BLOCKED, message=f"blocked by the URL policy: {exc}",
                    operation=operation,
                )
                write_diagnostic_log(err)
                return _error_envelope(canonical, err, alias=alias_note)

    # ── 6. browser-connected check ──────────────────────────────────────────
    # A disconnected probe is a refusal only for a browser that cannot rebuild.
    # A session carrying the documented recovery path (_ensure: close the
    # orphaned context, relaunch β€” chat_tools.py:660) heals AT the failing
    # step, which is exactly what the BROWSER_DISCONNECTED contract promises
    # (errors.py _RETRYABLE). Refusing here blocked that recovery forever: the
    # dead context stays registered in manager._contexts, so the probe kept
    # reporting disconnected and every retry re-entered this refusal instead
    # of ever reaching the handler that would clean it up.
    if spec.requires_browser:
        connected = getattr(browser, "browser_connected", None)
        if (
            callable(connected)
            and not connected()
            and not callable(getattr(browser, "_ensure", None))
        ):
            err = ClassifiedError(BROWSER_DISCONNECTED, operation=operation)
            write_diagnostic_log(err)
            return _error_envelope(canonical, err, alias=alias_note)

    # ── 7. run under a timeout; cancellation propagates untouched ──────────
    # Per-tool timeout comes from settings.browser_timeout (ms); the 1 ms
    # floor only guards against a zero/negative setting.
    timeout_s = max(int(settings.browser_timeout), 1) / 1000.0
    try:
        data = await asyncio.wait_for(spec.handler(browser, args), timeout=timeout_s)
    except TimeoutError:
        err = ClassifiedError(
            UNKNOWN,
            message=f"tool '{canonical}' timed out after {timeout_s:.2f}s",
            operation=operation,
        )
        write_diagnostic_log(err)
        return _error_envelope(canonical, err, alias=alias_note)
    except ClassifiedError as exc:
        if exc.operation is None:
            exc.operation = operation
        write_diagnostic_log(exc)
        if getattr(exc, "needs_consent", False):
            return _error_envelope(
                canonical, exc, needs_consent=True,
                data={"actual": getattr(exc, "actual", None)}, alias=alias_note,
            )
        return _error_envelope(canonical, exc, alias=alias_note)
    except PolicyViolation as exc:
        # A refusal raised INSIDE the handler (a redirect to a blocked host, a
        # domain the operator has blocked) is a policy decision, not an
        # unknown failure.
        err = ClassifiedError(
            POLICY_BLOCKED,
            message=str(exc),
            operation=operation,
        )
        write_diagnostic_log(err, exc)
        return _error_envelope(canonical, err, alias=alias_note)
    except Exception as exc:  # noqa: BLE001 β€” every failure becomes one envelope
        err = classify_exception(exc, operation=operation)
        write_diagnostic_log(err, exc)
        return _error_envelope(canonical, err, alias=alias_note)

    if not isinstance(data, dict):
        data = {"result": data}
    envelope = _success_envelope(canonical, data, alias=alias_note)
    if approval_envelope is not None:
        envelope["approval"] = approval_envelope
    return envelope


async def execute_tool_calls(

    browser: Any,

    tool_calls: Any,

    *,

    approval_request: ApprovalRequester | None = None,

) -> list[dict[str, Any]]:
    """One ``role:"tool"`` result per tool call, IN ORDER, keyed by tool_call_id.



    Handles a multi-call provider response: a failing call yields its own

    structured error and never stops the remaining calls from running.

    """
    results: list[dict[str, Any]] = []
    for call in tool_calls:
        function = getattr(call, "function", None)
        name = getattr(function, "name", None) or ""
        raw_arguments = getattr(function, "arguments", None)
        envelope = await execute_tool(
            browser, name, raw_arguments, approval_request=approval_request
        )
        results.append({
            "role": "tool",
            "tool_call_id": getattr(call, "id", None),
            "content": json.dumps(envelope, default=str)[:RESULT_TEXT_CAP],
            # The full envelope travels with the message so the chat loop can
            # build its tool trace without re-parsing the (possibly truncated)
            # content string.
            "envelope": envelope,
        })
    return results