
    `gj                     l   U d Z ddlZddlZddlZddlZddlmZ ddlmZm	Z	m
Z
mZmZ  ej                  e      Z	 ddlmZ  edd       i Ze	eef   ed	<   i Ze	eef   ed
<   dZd ZdefdZdefdZd ZdedefdZdZdefdZ dedefdZ!dedefdZ"g dZ#dhdee	eef      dee   fdZ$dhdee	eef      defdZ%dhdee	eef      defdZ&dee
e      fdZ'g dZ(dedefd Z)dedefd!Z*d"e
e	   de
e	   fd#Z+d$Z,defd%Z-de
e	   fd&Z.d'e
e	   deee
e	      e
e	   f   fd(Z/d)edefd*Z0d+e	defd,Z1defd-Z2	 	 	 	 	 didefd.Z3	 	 	 	 	 	 djd/ed'e
e	   d"ee
e	      d0e4d1ee5   d2ee5   d3ee
e      d4ee	   de	eef   fd5Z6	 	 	 	 	 	 djded/ed'e
e	   d"ee
e	      d0e4d1ee5   d2ee5   d3ee
e      d4ee	   defd6Z7	 	 	 	 	 	 djded/ed'e
e	   d"ee
e	      d0e4d1ee5   d2ee5   d3ee
e      d4ee	   defd7Z8i Z9e	eef   ed8<   d9Z:d: Z;	 dhded;ee
e      de
e	eef      fd<Z<d=edefd>Z= ej|                  d?ej~                         ej|                  d@ej~                         ej|                  dAej~                        gZ@ ej|                  dBej~                         ej|                  dCej~                         ej|                  dDej~                        gZA ej|                  dEej~                         ej|                  dFej~                         ej|                  dGej~                        gZBdHedefdIZCdHedefdJZDi dKdLdMdLdNdLdOdLdPdLdQdLdRdLdSdTdUdTdVdTdWdTdXdTdYdTdZdTd[dTd\dTd]d^d^d_d_d_d_d_d_d`ZEe	ee4f   eda<   d_ZFdbZGdcZHdede4fddZIdededee4   fdeZJdkdededfede4fdgZKy# e$ r Y gw xY w)lu  AWS Bedrock Converse API adapter for Hermes Agent.

Provides native integration with Amazon Bedrock using the Converse API,
bypassing the OpenAI-compatible endpoint in favor of direct AWS SDK calls.
This enables full access to the Bedrock ecosystem:

  - **Native Converse API**: Unified interface for all Bedrock models
    (Claude, Nova, Llama, Mistral, etc.) with streaming support.
  - **AWS credential chain**: IAM roles, SSO profiles, environment variables,
    instance metadata — zero API key management for AWS-native environments.
  - **Dynamic model discovery**: Auto-discovers available foundation models
    and cross-region inference profiles via the Bedrock control plane.
  - **Guardrails support**: Optional Bedrock Guardrails configuration for
    content filtering and safety policies.
  - **Inference profiles**: Supports cross-region inference profiles
    (us.anthropic.claude-*, global.anthropic.claude-*) for better capacity
    and automatic failover.

Architecture follows the same pattern as ``anthropic_adapter.py``:
  - All Bedrock-specific logic is isolated in this module.
  - Messages/tools are converted between OpenAI format and Converse format.
  - Responses are normalized back to OpenAI-compatible objects for the agent loop.

Reference: OpenClaw's ``extensions/amazon-bedrock/`` plugin, which implements
the same Converse API integration in TypeScript via ``@aws-sdk/client-bedrock``.

Requires: ``boto3`` (optional dependency — only needed when using the Bedrock provider).
    N)SimpleNamespace)AnyDictListOptionalTuple)ensurezprovider.bedrockF)prompt_bedrock_runtime_client_cache_bedrock_control_client_cache)   "   ;   c                     	 ddl } 	 t        d | j                  j	                  d      dd D              }|t        k  rt        d| j                   d      | S # t        $ r t        d      w xY w# t
        t        f$ r | cY S w xY w)	z@Import boto3, raising a clear error if not installed or too old.r   NzThe 'boto3' package is required for the AWS Bedrock provider. Install it with: pip install boto3
Or install Hermes with Bedrock support: pip install -e '.[bedrock]'c              3   2   K   | ]  }t        |        y wN)int).0xs     H/root/.hermes/venv/lib/python3.12/site-packages/agent/bedrock_adapter.py	<genexpr>z!_require_boto3.<locals>.<genexpr>O   s     I1AIs   .   zboto3 zg does not support converse_stream (minimum 1.34.59 required). Upgrade with: pip install --upgrade boto3)	boto3ImportErrortuple__version__splitAttributeError
ValueError_MIN_BOTO3_VERSIONRuntimeError)r   versions     r   _require_boto3r$   @   s    
I(9(9(?(?(DRa(HII ##U&&' (* +
 	

 L)  
R
 	

 J' s   A .A1 A.1BBregionc                 l    | t         vr$t               }|j                  d|       t         | <   t         |    S )u   Get or create a cached ``bedrock-runtime`` client for the given region.

    Uses the default AWS credential chain (env vars → profile → instance role).
    zbedrock-runtimeregion_name)r   r$   clientr%   r   s     r   _get_bedrock_runtime_clientr+   [   s@    
 22 056 1= 1
%f- )00    c                 l    | t         vr$t               }|j                  d|       t         | <   t         |    S )zLGet or create a cached ``bedrock`` control-plane client for model discovery.bedrockr'   )r   r$   r)   r*   s     r   _get_bedrock_control_clientr/   h   s>    22 056 1= 1
%f- )00r,   c                  T    t         j                          t        j                          y)z?Clear cached boto3 clients. Used in tests and profile switches.N)r   clearr    r,   r   reset_client_cacher3   r   s    !'')!'')r,   returnc                 B    | t         v }t         j                  | d       |S )a  Evict the cached ``bedrock-runtime`` client for a single region.

    Per-region counterpart to :func:`reset_client_cache`. Used by the converse
    call wrappers to discard clients whose underlying HTTP connection has
    gone stale, so the next call allocates a fresh client (with a fresh
    connection pool) instead of reusing a dead socket.

    Returns True if a cached entry was evicted, False if the region was not
    cached.
    N)r   pop)r%   existeds     r   invalidate_runtime_clientr8   x   s$     55G!%%fd3Nr,   )zurllib3.z	botocore.zboto3.excc              #      K   t        | dd      }|@|j                  }|j                  j                  dd      }|xs d |j                  }|?yyw)zJYield ``__name__``-style module strings for each frame in exc's traceback.__traceback__N__name__ )getattrtb_frame	f_globalsgettb_next)r9   tbframemodules       r   _traceback_frames_modulesrF      sR     	ot	,B
.$$Z4lZZ	 .s   AAAc                 4   	 ddl m}m} ||f}|rt	        | |      ry	 ddlm}m}m} |||f}|rt	        | |      ryt	        | t              r*t        |       D ]  t        fdt        D              s y y# t        $ r d}Y vw xY w# t        $ r d}Y hw xY w)u  Return True if ``exc`` indicates a dead/stale Bedrock HTTP connection.

    Matches:
      * ``botocore.exceptions.ConnectionError`` and subclasses
        (``ConnectionClosedError``, ``EndpointConnectionError``,
        ``ReadTimeoutError``, ``ConnectTimeoutError``).
      * ``urllib3.exceptions.ProtocolError`` / ``NewConnectionError`` /
        ``ConnectionError`` (best-effort import — urllib3 is a transitive
        dependency of botocore so it is always available in practice).
      * Bare ``AssertionError`` raised from a frame inside urllib3, botocore,
        or boto3. These are internal-invariant failures (typically triggered
        by corrupted connection-pool state after a dropped socket) and are
        recoverable by swapping the client.

    Non-library ``AssertionError``s (from application code or tests) are
    intentionally not matched — only library-internal asserts signal stale
    connection state.
    r   )ConnectionErrorHTTPClientErrorr2   T)ProtocolErrorNewConnectionErrorrH   c              3   @   K   | ]  }j                  |        y wr   )
startswith)r   prefixrE   s     r   r   z,is_stale_connection_error.<locals>.<genexpr>   s     V6$$V,V   F)botocore.exceptionsrH   rI   r   
isinstanceurllib3.exceptionsrJ   rK   AssertionErrorrF   any_STALE_LIB_MODULE_PREFIXES)	r9   BotoConnectionErrorrI   botocore_errorsrJ   rK   Urllib3ConnectionErrorurllib3_errorsrE   s	           @r   is_stale_connection_errorrZ      s    .	
 #6!G :c?;	
 	

 ();=ST *S.9 #~&/4 	FV;UVV	 1    s"   A8 B	 8BB	BBc                    t        |       j                         }d|vry	 ddlm} |At        | |      r5t        | dd      xs i j                  di       j                  dd	      }|d
v S d|v xs d|v S # t        $ r d}Y Zw xY w)u  Return True when AWS denied the ``bedrock:InvokeModelWithResponseStream`` action.

    IAM policies scoped to ``bedrock:InvokeModel`` only (a common least-privilege
    setup) reject ``converse_stream()`` with an ``AccessDeniedException`` whose
    message names the streaming action, e.g.::

        User: arn:aws:iam::123456789012:user/x is not authorized to perform:
        bedrock:InvokeModelWithResponseStream on resource: ...

    This is permanent for the session — retrying the stream can never succeed —
    so callers should flip to the non-streaming ``converse()`` path (which maps
    to ``bedrock:InvokeModel``) instead of burning retries.

    Detection is deliberately message-based: boto3 surfaces this as a
    ``ClientError`` with ``Error.Code == "AccessDeniedException"``, and the
    AnthropicBedrock SDK wraps the same AWS response in its own exception
    types, but both preserve the action name in the message.
    invokemodelwithresponsestreamFr   )ClientErrorNresponseErrorCoder=   )AccessDeniedExceptionUnauthorizedExceptionznot authorizedaccessdenied)strlowerrP   r]   r   rQ   r>   rA   )r9   msgr]   codes       r    is_streaming_access_denied_errorrh      s    & c(..
C&c13 :c;#?Z.4"99'2FJJ6SUVIII s";n&;;  s   A3 3B B)AWS_BEARER_TOKEN_BEDROCKAWS_ACCESS_KEY_IDAWS_PROFILE&AWS_CONTAINER_CREDENTIALS_RELATIVE_URIAWS_WEB_IDENTITY_TOKEN_FILEenvc                 t   | | nt         j                  } | j                  dd      j                         ry| j                  dd      j                         r!| j                  dd      j                         ry| j                  dd      j                         ry| j                  dd      j                         ry| j                  dd      j                         ry	 d	dl}|j
                  j                         }|j                         }||j                         }|r|j                  ry
y# t        $ r Y yw xY w)u  Return the name of the AWS auth source that is active, or None.

    Checks environment variables first, then falls back to boto3's credential
    chain for implicit sources (EC2 IMDS, ECS task role, etc.).

    This mirrors OpenClaw's ``resolveAwsSdkEnvVarName()`` — used to detect
    whether the user has any AWS credentials configured without actually
    attempting to authenticate.
    Nri   r=   rj   AWS_SECRET_ACCESS_KEYrk   rl   rm   r   ziam-role)osenvironrA   stripbotocore.sessionsessionget_sessionget_credentialsget_frozen_credentials
access_key	Exceptionrn   botocoreru   credentialsresolveds        r   resolve_aws_auth_env_varr     s    #bjjC
ww)2.446)#R(..0/4::<"
ww}b!'')
ww7<BBD7
ww,b1779,	""..0--/""99;HH//!   s   AD+ +	D76D7c                     t        |       y	 ddl}|j                  j                         }|j	                         }||j                         }|r|j                  ryy# t        $ r Y yw xY w)a`  Return True if any AWS credential source is detected.

    Checks environment variables first (fast, no I/O), then falls back to
    boto3's credential chain which covers EC2 instance roles, ECS task roles,
    Lambda execution roles, and other IMDS-based sources that don't set
    environment variables.

    This two-tier approach mirrors the pattern from OpenClaw PR #62673:
    cloud environments (EC2, ECS, Lambda) provide credentials via instance
    metadata, not environment variables. The env-var check is a fast path
    for local development; the boto3 fallback covers all cloud deployments.
    NTr   F)r   rt   ru   rv   rw   rx   ry   rz   r{   s        r   has_aws_credentialsr   E  sz      $0	""..0--/""99;HH//   s   AA 	A*)A*c                 <   | | nt         j                  } | j                  dd      j                         xs  | j                  dd      j                         }|r|S 	 ddl}|j
                  j                         j                  d      }|r|S 	 y# t        $ r Y yw xY w)u  Resolve the AWS region for Bedrock API calls.

    Priority:
      1. AWS_REGION env var
      2. AWS_DEFAULT_REGION env var
      3. boto3/botocore configured region (from ~/.aws/config or SSO profile)
      4. us-east-1 (hard fallback)

    The boto3 fallback is critical for EU/AP users who configure their region
    in ~/.aws/config via a named profile rather than env vars — without it,
    live model discovery would always return us.* profile IDs regardless of
    the user's actual region.
    N
AWS_REGIONr=   AWS_DEFAULT_REGIONr   r%   z	us-east-1)	rq   rr   rA   rs   rt   ru   rv   get_config_variablerz   )rn   explicitr|   r%   s       r   resolve_bedrock_regionr   d  s     #bjjCb!'') 	577',224  !!--/CCHMM    s   0B 	BBc                      	 t        t                     } | r| D cg c]  }|d   	 c}S 	 yc c}w # t        $ r Y yw xY w)u  Live-discover Bedrock model IDs for the active region.

    Returns a list of model ID strings if discovery succeeds and yields
    at least one model, or ``None`` on failure / empty result.  Callers
    should fall back to the static curated list when ``None`` is returned.

    This helper consolidates the discover → extract-ids → fallback
    pattern that was previously duplicated across ``provider_model_ids``,
    ``list_authenticated_providers`` section 2, and section 3.
    idN)discover_bedrock_modelsr   rz   )
discoveredms     r   bedrock_model_ids_or_noner     sQ    ,-C-EF
%/0AdG00   1 s   1 ,1 1 	==)zdeepseek.r1zdeepseek-r1z
stability.zcohere.embedzamazon.titan-embedmodel_idc                 V    | j                         t        fdt        D               S )zReturn True if the model is expected to support tool/function calling.

    Models in the denylist are known to reject toolConfig in the Converse API.
    Unknown models default to True (assume tool support).
    c              3   &   K   | ]  }|v  
 y wr   r2   )r   patternmodel_lowers     r   r   z+_model_supports_tool_use.<locals>.<genexpr>  s     Tg7k)Ts   )re   rT   _NON_TOOL_CALLING_PATTERNS)r   r   s    @r   _model_supports_tool_user     s&     .."KT9STTTTr,   c                     | j                         }dD ]#  }|j                  |      s|t        |      d } n |j                  d      S )a  Return True if the model is an Anthropic Claude model on Bedrock.

    These models should use the AnthropicBedrock SDK path for full feature
    parity (prompt caching, thinking budgets, adaptive thinking).
    Non-Claude models use the Converse API path.

    Matches:
      - ``anthropic.claude-*`` (foundation model IDs)
      - ``us.anthropic.claude-*`` (US inference profiles)
      - ``global.anthropic.claude-*`` (global inference profiles)
      - ``eu.anthropic.claude-*`` (EU inference profiles)
    )global.zus.zeu.zapac.zap.zau.zjp.zca.zsa.zme.zaf.Nzanthropic.claude)re   rM   len)r   r   rN   s      r   is_anthropic_bedrock_modelr     sX     .."K  !!&)%c&kl3K !!"455r,   toolsc                     | sg S g }| D ]f  }|j                  di       }|j                  dd      }|j                  dd      }|j                  ddi d      }|j                  d||d	|id
i       h |S )a  Convert OpenAI-format tool definitions to Bedrock Converse ``toolConfig``.

    OpenAI format::

        {"type": "function", "function": {"name": "...", "description": "...",
         "parameters": {"type": "object", "properties": {...}}}}

    Converse format::

        {"toolSpec": {"name": "...", "description": "...",
         "inputSchema": {"json": {"type": "object", "properties": {...}}}}}
    functionnamer=   description
parametersobject)type
propertiestoolSpecjson)r   r   inputSchema)rA   append)r   resulttfnr   r   r   s          r   convert_tools_to_converser     s     	F UU:r"vvfb!ff]B/VVL82*NO
* &
3
 	 Mr,   z(empty)c                 x    | t         S t        | t              st        |       } | j                         r| S t         S )u   Return ``text`` if it's non-whitespace, else a non-whitespace placeholder.

    Handles None, empty string, and whitespace-only string (spaces, tabs,
    newlines) — all of which Bedrock's Converse API rejects as text content.
    )_EMPTY_TEXT_PLACEHOLDERrQ   rd   rs   )texts    r   
_safe_textr     s6     |&&dC 4y::<4<%<<r,   c                    | dt        |       igS t        | t              rdt        |       igS t        | t              rg }| D ]v  }t        |t              r|j	                  dt        |      i       1t        |t
              sB|j                  dd      }|dk(  r/|j                  dd      }|j	                  dt        |      i       |dk(  s|j                  di       }t        |t
              r|j                  dd      nd}|j                  d      r|j                  d      \  }}}	d	}
|j                  d      r|d
d j                  d      d   }|r|}
ddl
}	 |j                  |	      }|j	                  dd|
v r|
j                  d      d   ndd|idi       `|j	                  dd| di       y |r|S dt        igS dt        |       igS # t        $ r |	j                  d      }Y w xY w)u  Convert OpenAI message content (string or list) to Converse content blocks.

    Handles:
      - Plain text strings → [{"text": "..."}]
      - Content arrays with text/image_url parts → mixed text/image blocks

    Replaces empty/whitespace-only text blocks with a non-whitespace
    placeholder — Bedrock's Converse API rejects messages where a text
    content block is empty or whitespace-only (ValidationException:
    "text content blocks must contain non-whitespace text"). Ref: issue #9486.
    Nr   r   r=   	image_urlurlzdata:,z
image/jpeg   ;r   zutf-8image/jpegbytes)formatsourcez[Image: ])r   rQ   rd   listr   dictrA   rM   	partitionr   base64	b64decoderz   encoder   )contentblockspart	part_typer   r   r   header_data
media_type	mime_partr   	raw_bytess                 r   _convert_content_to_converser     s    G,-..'3G,-..'4  '	?D$$vz$'789dD),IF"xx+vz$'789k) HH["5	2<Y2MimmE2.SU>>'*&)mmC&8OFAt!-J((1$*12J$4$4S$9!$<	$)2J
 "9$*$4$4T$:	 MMCF*CTj&6&6s&;B&?Z`'.	&:"#  MM6XcU!+<"=>O'	?P  vHv/F&G%HHZ()** % 9$(KK$8	9s   !GG65G6messagesc           
         g }g }| D ]=  }|j                  dd      }|j                  d      }|dk(  rt        |t              r$|j                         r|j	                  d|i       nt        |t
              r|D ]  }t        |t              r\|j                  d      dk(  rH|j                  dd      }t        |t              sJ|j                         s[|j	                  d|i       ot        |t              s|j                         s|j	                  d|i        |dk(  r|j                  dd      }t        |t              r|nt        j                  |      }	d	|dt        |	      igd
i}
|r#|d   d   dk(  r|d   d   j	                  |
       n|j	                  d|
gd       |dk(  rFg }t        |t              r$|j                         r|j	                  d|i       n*t        |t
              r|j                  t        |             |j                  dg       }|xs g D ]  }|j                  di       }|j                  dd      }	 t        |t              rt        j                  |      n|}|j	                  d|j                  dd      |j                  dd      |di        |s	dt        ig}|r#|d   d   dk(  r|d   d   j                  |       n|j	                  d|d       |dk(  st        |      }|r#|d   d   dk(  r|d   d   j                  |       n|j	                  d|d       @ |r'|d   d   dk7  r|j!                  dddt        igd       |r&|d   d   dk7  r|j	                  ddt        igd       |r||fS d|fS # t        j                  t        f$ r i }Y Fw xY w)u  Convert OpenAI-format messages to Bedrock Converse format.

    Returns ``(system_prompt, converse_messages)`` where:
      - ``system_prompt`` is a list of system content blocks (or None)
      - ``converse_messages`` is the conversation in Converse format

    Handles:
      - System messages → extracted as system prompt
      - User messages → ``{"role": "user", "content": [...]}``
      - Assistant messages → ``{"role": "assistant", "content": [...]}``
      - Tool calls → ``{"toolUse": {"toolUseId": ..., "name": ..., "input": ...}}``
      - Tool results → ``{"toolResult": {"toolUseId": ..., "content": [...]}}``

    Converse requires strict user/assistant alternation. Consecutive messages
    with the same role are merged into a single message.
    roler=   r   systemr   r   tooltool_call_id
toolResult)	toolUseIdr   r   userr   r   	assistant
tool_callsr   	argumentsz{}toolUser   r   )r   r   inputr   N)rA   rQ   rd   rs   r   r   r   r   dumpsr   extendr   loadsJSONDecodeError	TypeErrorr   insert)r   system_blocksconverse_msgsrf   r   r   r   r   r   result_contenttool_result_blockcontent_blocksr   tcr   args_str	args_dicts                    r   convert_messages_to_converser   B  s   & !#M "M Xwwvr"'')$8 '3'GMMO$$fg%67GT*# =D!$-$((62Bf2L#xx3%dC0TZZ\)00&$@#D#.4::<%,,fd^<= 6>77>26L(27C(@WdjjQXFYN!-!'N)C DE! r!26!:f!Db!),334EF$$" 12&  ;N'3'GMMO%%vw&78GT*%%&B7&KL r2J!'R VVJ+66+t4#8B8S8Q

8 4W_I %%%'VVD"%5 "vr 2!* '  "#)+B"C!D r!26!:k!Ib!),33NC$$'-&  6>9'BNr!26!:f!Db!),33NC$$"-&  qXv q)&1V;QfF]=^<_ `a r*62f<f6CZ:[9\]^*MmDDmDDW ,,i8 # "I#s   'N##OOstop_reasonc                 8    ddddddd}|j                  | d      S )zAMap Bedrock Converse stop reasons to OpenAI finish_reason values.stopr   lengthcontent_filter)end_turnstop_sequencetool_use
max_tokenscontent_filteredguardrail_intervened)rA   )r   mappings     r   _converse_stop_reason_to_openair     s0      , 0G ;;{F++r,   r^   c                    | j                  di       }|j                  di       }|j                  dg       }| j                  dd      }g }g }g }|D ]  }d|v r|j                  |d          d|v rF|d   }	t        |	t              s6|	j                  dd      }
|
sK|j                  t	        |
             fd	|v sk|d	   }|j                  t        |j                  d
d      dt        |j                  dd      t        j                  |j                  di                                 t        d|rdj                  |      nd|r|nd|rdj                  |      nd      }| j                  di       }t        |j                  dd      |j                  dd      |j                  dd      |j                  dd      z         }t        |      }|r|dk(  rd}t        d||      }t        |g|| j                  dd            S )u  Convert a Bedrock Converse API response to an OpenAI-compatible object.

    The agent loop in ``run_agent.py`` expects responses shaped like
    ``openai.ChatCompletion`` — this function bridges the gap.

    Returns a SimpleNamespace with:
      - ``.choices[0].message.content`` — text response
      - ``.choices[0].message.tool_calls`` — tool call list (if any)
      - ``.choices[0].finish_reason`` — stop/tool_calls/length
      - ``.usage`` — token usage stats
    outputmessager   
stopReasonr   r   reasoningContentr=   r   r   r   r   r   r   r   r   r   r   r   
N

r   r   r   reasoning_contentusageinputTokensr   outputTokensprompt_tokenscompletion_tokenstotal_tokensr   r   indexr   finish_reasonmodelIdchoicesr  model)
rA   r   rQ   r   rd   r   r   r   joinr   )r^   r   r   r   r   
text_partsreasoning_partsr   block	reasoningthinking_textturf   
usage_datar  r  choices                    r   normalize_converse_responser    s    \\(B'FjjB'G[[B/N,,|Z8KJOJ U?eFm,5(01I)T* )fb 9 #**3}+=>%y!Bo66+r*(+"jj)<= * )3		*%!+::I&++o6t	C gr*J nn]A6$..;NN=!,z~~na/PP	E 4K@Mmv-$#F ll9b) r,   c                     t        |       S )u  Consume a Bedrock ConverseStream event stream and build an OpenAI-compatible response.

    Processes the stream events in order:
      - ``messageStart`` — role info
      - ``contentBlockStart`` — new text or toolUse block
      - ``contentBlockDelta`` — incremental text or toolUse input
      - ``contentBlockStop`` — block complete
      - ``messageStop`` — stop reason
      - ``metadata`` — usage stats

    Returns the same shape as ``normalize_converse_response()``.
    )stream_converse_with_callbacks)event_streams    r    normalize_converse_stream_eventsr    s     *,77r,   c                    g }g }g }d}	g }
d}d}i }| j                  dg       D ]L  }|	  |        |r
 |       r n6d|v r{|d   j                  di       }d|v s8d}|
r"|j                  d	j                  |
             g }
|d   j                  d
d	      |d   j                  dd	      d	d}	|s ||	d          d|v r|d   j                  di       }d|v r%|d   }|
j                  |       |s|r ||       d|v r%|	|	dxx   |d   j                  dd	      z  cc<   d|v s
|d   }t	        |t
              s!|j                  dd	      }|s7|j                  t        |             |sU ||       _d|v r|	e	 |	d   rt        j                  |	d         ni }|j                  t        |	d
   dt        |	d   t        j                  |                         d}	|
s|j                  d	j                  |
             g }
d|v r|d   j                  dd      }d|v s|d   j                  di       }|j                  dd      |j                  dd      d}O |
r |j                  d	j                  |
             t        d|rd j                  |      nd|r|nd|rd!j                  |      nd"      }t        |j                  dd      |j                  dd      |j                  dd      |j                  dd      z   #      }t        |      }|r|d$k(  rd%}t        d||&      }t        |g|d	'      S # t        $ r Y +w xY w# t        j                  t        f$ r i }Y w xY w)(an  Process a Bedrock ConverseStream event stream with real-time callbacks.

    This is the core streaming function that powers both the CLI's live token
    display and the gateway's progressive message updates.

    Args:
        event_stream: The boto3 ``converse_stream()`` response containing a
            ``stream`` key with an iterable of events.
        on_text_delta: Called with each text chunk as it arrives. Only fires
            when no tool_use blocks have been seen (same semantics as the
            Anthropic and chat_completions streaming paths).
        on_tool_start: Called with the tool name when a toolUse block begins.
            Lets the TUI show a spinner while tool arguments are generated.
        on_reasoning_delta: Called with reasoning/thinking text chunks.
            Bedrock surfaces thinking via ``reasoning`` content block deltas
            on supported models (Claude 4.6+).
        on_interrupt_check: Called on each event. Should return True if the
            agent has been interrupted and streaming should stop.
        on_event: Called once at the top of the loop body for EVERY yielded
            Bedrock event (text/tool-input/reasoning/metadata deltas alike),
            before any branching. Provides a wire-level liveness signal so an
            external watchdog can distinguish "still receiving events" from
            "stream wedged with no data". Errors raised by the callback are
            swallowed so a liveness hook can never abort the stream.

    Returns:
        An OpenAI-compatible SimpleNamespace response, identical in shape to
        ``normalize_converse_response()``.
    NFr   streamcontentBlockStartstartr   Tr=   r   r   )r   r   
input_jsoncontentBlockDeltadeltar   r#  r   r   contentBlockStopr   r   r   messageStopr   metadatar  r  r   r  )r  r  r   r   r   r  r  r   r   r
  r  )rA   rz   r   r  rQ   r   rd   r   r   r   r   r   r   r   )r  on_text_deltaon_tool_starton_reasoning_deltaon_interrupt_checkon_eventr  r  r   current_toolcurrent_text_bufferhas_tool_user   r  eventr"  r%  r   r  r  
input_dict
meta_usagerf   r  r  r  s                             r   r  r  .  s   J J!#O(*J#'L%'LK!#J!!(B/ O
 
 "4"6%'-.227B?EE!#&%%bgg.A&BC*,'!&y!1!5!5k2!F!),00<"$ 
 !!,v"67 E)-.227B?EV}#**40 !!$'e#+ .%	2B2F2FwPR2SS.#u,!"45	i.$-MM&"$=M$'..s=/AB-.}=5('$KWXdKeL,F!GkmJ !!/#K0#,)&1"&**Z"8#   $$!!"''*=">?&(#e#.22<LK5 z*..w;J)~~mQ? *~q AJYOd "''"567
)3		*%!+::I&++o6t	C  nn]A6$..;NN=!,z~~na/PP	E 4K@Mmv-$#F  M  ` ,,i8 $!#J$s#   M	M 	MM M?>M?r  r   temperaturetop_pstop_sequencesguardrail_configc                    t        |      \  }}	| |	d|id}
|r||
d<   ddlm}  ||       s|||
d   d<   |||
d   d<   |r||
d   d	<   |r6t        |      }|r)t	        |       rd
|i|
d<   nt
        j                  d|        |r||
d<   |
S )zBuild kwargs for ``bedrock-runtime.converse()`` or ``converse_stream()``.

    Converts OpenAI-format inputs to Converse API parameters.
    	maxTokensr  r   inferenceConfigr   r   )_forbids_sampling_paramsr;  r4  topPstopSequencesr   
toolConfigud   Model %s does not support tool calling — tools stripped. The agent will operate in text-only mode.guardrailConfig)r   agent.anthropic_adapterr<  r   r   loggerwarning)r  r   r   r   r4  r5  r6  r7  system_promptconverse_messageskwargsr<  converse_toolss                r   build_converse_kwargsrH    s     (DH'M$M$ %
F (x@#E*"7BF$%m405F$%f-5C !/2259 (.(/'@|$@AF
 $4 !Mr,   c	           
          t        |       }	t        ||||||||      }
	  |	j                  di |
}t        |      S # t        $ rG}t	        |      r6t
        j                  d| |t        |      j                         t        |         d}~ww xY w)zCall Bedrock Converse API (non-streaming) and return an OpenAI-compatible response.

    This is the primary entry point for the agent loop when using the Bedrock provider.
    r  r   r   r   r4  r5  r6  r7  u|   bedrock: stale-connection error on converse(region=%s, model=%s): %s — evicting cached client so the next call reconnects.Nr2   )r+   rH  converserz   rZ   rB  rC  r   r<   r8   r  r%   r  r   r   r   r4  r5  r6  r7  r)   rF  r^   r9   s                r   call_converserM    s     )0F"%)	F
"6??,V, 'x00  $S)NNMtCy11
 &f-s   = 	BABBc	           
         t        |       }	t        ||||||||      }
	  |	j                  di |
}t        |      S # t        $ r}t	        |      r7t
        j                  d| |       t         |	j                  di |
      cY d}~S t        |      r6t
        j                  d| |t        |      j                         t        |         d}~ww xY w)zCall Bedrock ConverseStream API and return an OpenAI-compatible response.

    Consumes the full stream and returns the assembled response. For true
    streaming with delta callbacks, use ``iter_converse_stream()`` instead.
    rJ  um   bedrock: converse_stream denied by IAM on (region=%s, model=%s) — falling back to non-streaming converse().Nu   bedrock: stale-connection error on converse_stream(region=%s, model=%s): %s — evicting cached client so the next call reconnects.r2   )r+   rH  converse_streamrz   rh   rB  infor  rK  rZ   rC  r   r<   r8   r  rL  s                r   call_converse_streamrQ  ;  s      )0F"%)	F)6))3F3( ,H55'  +C0 KK<
 /v/H/HII$S)NNXtCy11
 &f-%s"   = 	C<C
CAC

C_discovery_cachei  c                  ,    t         j                          y)z/Clear the model discovery cache. Used in tests.N)rR  r1   r2   r,   r   reset_discovery_cacherT  w  s    r,   provider_filterc           
      @   ddl }|  ddj                  t        |xs g              }t        j	                  |      }|r"|j                         |d   z
  t
        k  r|d   S 	 t        |       }g }t               }|xs g D 	ch c]  }	|	j                          c}		 |j                         }
|
j	                  dg       D ]h  }|j	                  d	      xs d
j                         }|s*rT|j	                  d      xs d
j                         }d|v r"|j                  d      d   j                         nd
}|vr|vr|j	                  di       }|j	                  dd
      j                         dk7  r|j	                  dd      s|j	                  dg       }d|vr|j!                  ||j	                  d      xs |j                         |j	                  d      xs d
j                         |j	                  dg       |dd       |j#                  |j                                k 	 	 g }d}	 i }|r||d<    |j$                  d#i |}
|
j	                  dg       D ]  }|j!                  |        |
j	                  d      }|snX|D ]  }|j	                  d      xs d
j                         }|s)|j	                  d      dk7  r>|j                         |v rQr)|j	                  dg       }t'        fd|D              }|s||j!                  ||j	                  d      xs |j                         ddgdgdd       |j#                  |j                                 	 |j+                  d  !       |j                         |d"t        |<   |S # t        $ r"}t        j                  d|       g cY d}~S d}~ww xY wc c}	w # t        $ r!}t        j                  d|       Y d}~d}~ww xY w# t        $ r }t        j)                  d|       Y d}~d}~ww xY w)$a  Discover available Bedrock foundation models and inference profiles.

    Returns a list of model info dicts with keys:
      - ``id``: Model ID (e.g. "anthropic.claude-sonnet-4-6-20250514-v1:0")
      - ``name``: Human-readable name
      - ``provider``: Model provider (e.g. "Anthropic", "Amazon", "Meta")
      - ``input_modalities``: List of input types (e.g. ["TEXT", "IMAGE"])
      - ``output_modalities``: List of output types
      - ``streaming``: Whether streaming is supported

    Caches results for 1 hour per region to avoid repeated API calls.

    Mirrors OpenClaw's ``discoverBedrockModels()`` in
    ``extensions/amazon-bedrock/discovery.ts``.
    r   N:r   	timestampmodelsz7Failed to create Bedrock client for model discovery: %smodelSummariesr  r=   providerNamer   modelLifecyclestatusACTIVEresponseStreamingSupportedFoutputModalitiesTEXT	modelNameinputModalitiesT)r   r   providerinput_modalitiesoutput_modalities	streamingz,Failed to list Bedrock foundation models: %s	nextTokeninferenceProfileSummariesinferenceProfileIdc              3   t   K   | ]/  }t        |j                  d d            j                         v  1 yw)modelArnr=   N)_extract_provider_from_arnrA   re   )r   r   
filter_sets     r   r   z*discover_bedrock_models.<locals>.<genexpr>  s8       /quuZ/DEKKMQ[[s   58inferenceProfileNamezinference-profilez(Skipping inference profile discovery: %sc                 X    | d   j                  d      rdnd| d   j                         fS )Nr   r   r   r   r   )rM   re   )r   s    r   <lambda>z)discover_bedrock_models.<locals>.<lambda>  s-    tW	*	&	 r,   )key)rX  rY  r2   )timer  sortedrR  rA   _DISCOVERY_CACHE_TTL_SECONDSr/   rz   rB  rC  setre   list_foundation_modelsrs   r   upperr   addlist_inference_profilesrT   debugsort)r%   rU  rs  	cache_keycachedr)   erY  seen_idsfr^   summaryr   provider_namemodel_prefix	lifecycleoutput_modsprofiles
next_tokenrF  profile
profile_idprofile_modelsmatchesrn  s                           @r   r   r   |  s'   & (!CHHVO,Ar%BCDEI!!),F499;!448TTh,V4
 FuH&5&;=!'')=J"J002||$4b9 	+GI.4";;=H !(^!<!B I I KADx~~c215;;=VX 
2|:7U  $4b9I}}Xr*002h>;;;UC!++&8"=K[(MM [1=XDDF$[[8>BEEG$+KK0A2$F%0!  LL)*=	+F+D
F&0{#5v55??H#<<(CRH )()!k2J    	-G!++&:;ArHHJJ{{8$0!X- !(Xr!: +  MM  %;<J
QQS/%+H&,X!  LL))+,7	-@ KK K  YY[#Y MK  PRST	 >H  JEqIIJ\  D?CCDsV   #N OFO -D7O4 	N?N:4N?:N?	O1O,,O14	P=PParnc                 X    t        j                  d|       }|r|j                  d      S dS )u   Extract the model provider from a Bedrock model ARN.

    Example: "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-v2"
    → "anthropic"
    zfoundation-model/([^.]+)r   r=   )researchgroup)r  matchs     r   rm  rm     s*     II137E"5;;q>**r,   zNValidationException.*(?:input is too long|max input token|input token.*exceed)zVValidationException.*(?:exceeds? the (?:maximum|max) (?:number of )?(?:input )?tokens)zFModelStreamErrorException.*(?:Input is too long|too many input tokens)ThrottlingExceptionzToo many concurrent requestsServiceQuotaExceededExceptionModelNotReadyExceptionModelTimeoutExceptionInternalServerExceptionerror_messagec                 4     t         fdt        D              S )zReturn True if the error indicates the input context was too large.

    When this returns True, the agent should compress context and retry
    rather than treating it as a fatal error.
    c              3   @   K   | ]  }|j                          y wr   r  r   pr  s     r   r   z,is_context_overflow_error.<locals>.<genexpr>+  s     J1qxx&JrO   )rT   CONTEXT_OVERFLOW_PATTERNSr  s   `r   is_context_overflow_errorr  %  s     J0IJJJr,   c                      t               ryt         fdt        D              ryt         fdt        D              ryy)uC  Classify a Bedrock error for retry/failover decisions.

    Returns:
      - ``"context_overflow"`` — input too long, compress and retry
      - ``"rate_limit"`` — throttled, backoff and retry
      - ``"overloaded"`` — model temporarily unavailable, retry with delay
      - ``"unknown"`` — unclassified error
    context_overflowc              3   @   K   | ]  }|j                          y wr   r  r  s     r   r   z)classify_bedrock_error.<locals>.<genexpr>9       
>q188M"
>rO   
rate_limitc              3   @   K   | ]  }|j                          y wr   r  r  s     r   r   z)classify_bedrock_error.<locals>.<genexpr>;  r  rO   
overloadedunknown)r  rT   THROTTLE_PATTERNSOVERLOAD_PATTERNSr  s   `r   classify_bedrock_errorr  .  s7     !/!

>,=
>>

>,=
>>r,   zanthropic.claude-fable-5i@B zanthropic.claude-fablezanthropic.claude-sonnet-5zanthropic.claude-opus-4-8zanthropic.claude-opus-4-7zanthropic.claude-opus-4-6zanthropic.claude-sonnet-4-6zanthropic.claude-sonnet-4-5i@ zanthropic.claude-haiku-4-5zanthropic.claude-opus-4zanthropic.claude-sonnet-4zanthropic.claude-3-5-sonnetzanthropic.claude-3-5-haikuzanthropic.claude-3-opuszanthropic.claude-3-sonnetzanthropic.claude-3-haikuzamazon.nova-proi i  )zamazon.nova-litezamazon.nova-microzmeta.llama4-maverickzmeta.llama4-scoutzmeta.llama3-3-70b-instructzmistral.mistral-largezdeepseek.v3BEDROCK_CONTEXT_LENGTHS)i  i! g?c                     | j                         }d}t        }t        j                         D ]&  \  }}||v st	        |      t	        |      kD  s#|}|}( |S )zLongest-substring-match lookup against the static fallback table.

    Uses substring matching so versioned IDs like
    ``anthropic.claude-sonnet-4-6-20250514-v1:0`` resolve correctly.
    r=   )re   BEDROCK_DEFAULT_CONTEXT_LENGTHr  itemsr   )r   r   best_keybest_valrr  vals         r   _static_bedrock_context_lengthr    s^     .."KH-H+113 S+#c(S]":HH Or,   c                 :   	 ddl m} 	 t        |      }d}t        D ]S  }t        |t        z        }d|z  }	 |j                  | dd|igd	gd
di       t
        j                  d| |d       |c S  t
        j                  d| |dd        y# t        $ r Y yw xY w# t        $ r!}t
        j                  d| |       Y d}~yd}~ww xY w# t        $ rH}t        |      }	|	} ||	      }
|
r'|
dk\  r"t
        j                  d| |
d       |
cY d}~c S Y d}~d}~ww xY w)u  Discover a Bedrock model's real context window by provoking a length error.

    Bedrock does not expose the context window via any metadata API
    (``get-foundation-model`` omits it, ``Converse`` metrics omit it,
    ``CountTokens`` is unsupported on several models).  The only authoritative
    source is the ``ValidationException`` raised when a prompt exceeds the
    window:

        "The model returned the following errors: prompt is too long:
         1300032 tokens > 1000000 maximum"

    Length validation happens *before* inference, so an oversized request is
    rejected immediately and cheaply — no tokens are generated and no input is
    actually processed.  We pad a request just past each tier in
    ``_BEDROCK_PROBE_TIERS`` and parse the reported ``maximum``.  Tiers exist
    because (a) a *wildly* oversized payload makes Bedrock fail with an opaque
    InternalServerException instead of a clean length error, and (b) stepping
    up discovers larger windows without over-padding smaller ones.

    Returns the detected window, or ``None`` if the probe could not run
    (missing credentials, network error, or no parseable limit) so the caller
    can fall back to the static table.
    r   )parse_context_limit_from_errorNz(Bedrock context probe skipped for %s: %sr=   zdata r   r   r   r9     r:  zOBedrock context probe for %s accepted ~%s-token prompt; window is at least thatr   i   z/Probed Bedrock context window for %s: %s tokensz<Bedrock context probe for %s returned no parseable limit: %s   )agent.model_metadatar  r   r+   rz   rB  r{  _BEDROCK_PROBE_TIERSr   _WORDS_PER_TOKENrK  rd   rP  )r   r%   r  r)   r9   
last_errortier_tokens	pad_words	oversizedrf   limits              r   probe_bedrock_context_lengthr    sT   0G,V4
 J+ &667	i'		OO #)	7J6KLM!,a 0   LL*+3A !@ LLF*Tc" ]  
  ?3O,  	c(CJ237E$Eq	  	sE   B B 7C		BB	C%CC		D6DDDprobec                 @    |r|rt        | |      }|r|S t        |       S )u+  Resolve the context window for a Bedrock model.

    Resolution order:
      1. Live probe against Bedrock (authoritative; cached by the caller).
      2. Static fallback table (longest-substring match).
      3. Conservative default.

    The static table is intentionally a *fallback*, not the primary source:
    AWS ships new model versions (opus-4-7, opus-4-8, ...) faster than the
    table can track, and a stale entry silently caps the window (e.g. a
    1M-token Opus pinned to 200K via an ``opus-4`` substring match).  The
    probe asks Bedrock directly so every model — current or future — gets its
    real window with no table maintenance.

    ``probe=False`` (or an empty ``region``) skips the network call and uses
    the static table only — used by pure-offline/display code paths.
    )r  r  )r   r%   r  probeds       r   get_bedrock_context_lengthr    s(    $ -h?M)(33r,   r   )NNNNN)Ni   NNNN)r=   T)L__doc__r   loggingrq   r  typesr   typingr   r   r   r   r   	getLoggerr<   rB  tools.lazy_depsr	   rz   r   rd   __annotations__r   r!   r$   r+   r/   r3   boolr8   rU   BaseExceptionrF   rZ   rh   _AWS_CREDENTIAL_ENV_VARSr   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   floatrH  rM  rQ  rR  ru  rT  r   rm  compile
IGNORECASEr  r  r  r  r  r  r  r  r  r  r  r  r2   r,   r   <module>r     sA  :   	 	 ! 3 3			8	$	&
e, 13 tCH~ 202 tCH~ 2 ! 6
1 
11 1*c d F = 5= 5T 5p <-  <D  <X '(4S>": 'hsm 'TXd38n5  >c3h 8 C >8DI#6 < Us Ut U6 6 6:T$Z DJ F $ 
= 
=;+T$Z ;+|xE4jxE
8DJd+,xE~
, 
, 
,I$ I? I`8o 8$ ` `T #'#'!*.'+::4j: DJ: 	:
 %: E?: T#Y': tn: 
#s(^:B #'#'!*.'+&1&1&1 4j&1 DJ	&1
 &1 %&1 E?&1 T#Y'&1 tn&1 &1Z #'#'!*.'+161616 4j16 DJ	16
 16 %16 E?16 T#Y'16 tn16 16p $& $sCx. %#  ,0AAd3i(A 
$sCx.AH+C +C +" BJJ`bdbobopBJJhjljwjwxBJJXZ\ZgZgh  BJJ%r}}5BJJ.>BJJ/?  BJJ("--8BJJ'7BJJ)2==9 KS KT K# # 2(+ Y(+ Y(+  Y(+  Y(+   Y!(+"  Y#(+$ "Y%(+& "W'(+( !W)(+* W+(+,  W-(+. "W/(+0 !W1(+2 W3(+4  W5(+6 W7(+: W;(+< &-%,%,%,%,%,%,O(+ c3h (V ")  .  S S  H3 H H HV4 4c 4t 4WZ 4[-  		s   N* *N32N3