Skip to content

AgentCore

Core SDK for the AI Agent Platform.

AgentCore owns registered plugin wrappers and Core-local caches. Conversation operations accept explicit sessions/configuration and return new conversation values. Request and tool methods may perform provider, tool, or preparation I/O.

AgentCore

AgentCore(model_cache=None)

Provider and plugin processing pipeline.

The instance stores registered wrappers plus model, dependency, tag, and prepared-tool caches. Applications manage durable sessions and configuration. Session transformations return new values; request and tool methods may perform external I/O.

Initialize core with empty plugin pipeline.

Loggers are initialized lazily so that structlog configuration can be customized by applications before any loggers are created.

Source code in agent_core/core.py
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
def __init__(self, model_cache: Optional[ModelDiscoveryCache] = None):
    """Initialize core with empty plugin pipeline.

    Loggers are initialized lazily so that structlog configuration can
    be customized by applications before any loggers are created.
    """
    global logger, log_chunk_processing
    logger = get_logger("core")
    log_chunk_processing = get_logger("chunk_processing")

    self._providers: List[ProviderWrapper] = []
    self._features: List[FeatureWrapper] = []
    self._tools: List[ToolWrapper] = []
    # Model discovery can be shared across fresh AgentCore instances by
    # passing the same cache object. Dependency/tag/tool-preparation caches
    # remain core-local because they are tied to wrapper/runtime state.
    self._model_cache = model_cache or ModelDiscoveryCache()
    self._dependency_cache: Dict[
        Tuple[int, str, str],
        Tuple[List[str], List[str], List[str], List[str]],
    ] = {}
    self._tags_cache: Dict[Tuple[int, Tuple[int, str, str]], List[str]] = {}
    self._prepared_tool_states: Dict[Tuple[int, str], Dict[str, Any]] = {}
    self._prepared_tool_data: Dict[Tuple[int, str], Dict[str, Any]] = {}
    self._context = CoreContext(core=self)

add_message

add_message(session, role, content, metadata=None, config=None, *, multipart_content=None, after_index=None, context=None, tool_result=None)

Add a message and return an updated session.

When session.metadata contains provider-native history (native_messages) and a provider is registered, converts the newly added message to provider-native format and appends it to the stored native history. Updates verification data for integrity checks.

Parameters:

Name Type Description Default
session Session

Current session.

required
role MessageRole

Message role ("system", "user", "assistant", or "tool").

required
content Any

Message content.

required
metadata Optional[Dict[str, Any]]

Optional per-message metadata. Note: when provider-native history is enabled (session metadata contains native_messages) and the core rebuilds messages from the provider-native sequence, arbitrary metadata is not preserved by default. Persist metadata explicitly via the provider/feature/extension pipelines using the _metadata key on provider-native messages.

None
config Optional[Dict[str, Any]]

Optional configuration used to resolve provider and plugins.

None
tool_result Optional[Dict[str, Any]]

Optional structured tool result payload for this message. This is the canonical structured representation for tool messages and may be consumed by providers when appending to provider-native history.

None
after_index Optional[int]

Optional index after which to insert the message. When None (default), the message is appended at the end. after_index == -1 inserts at the beginning. Negative indices follow Python semantics relative to the end of the message list.

None

Returns:

Type Description
Session

New Session with the message added (immutable update).

Source code in agent_core/core.py
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
def add_message(
    self,
    session: Session,
    role: MessageRole,
    content: Any,
    metadata: Optional[Dict[str, Any]] = None,
    config: Optional[Dict[str, Any]] = None,
    *,
    multipart_content: Optional[List[Dict[str, Any]]] = None,
    after_index: Optional[int] = None,
    context: Optional[Dict[str, Any]] = None,
    tool_result: Optional[Dict[str, Any]] = None,
) -> Session:
    """Add a message and return an updated session.

    When session.metadata contains provider-native history (native_messages)
    and a provider is registered, converts the newly added message to
    provider-native format and appends it to the stored native history.
    Updates verification data for integrity checks.

    Args:
        session: Current session.
        role: Message role ("system", "user", "assistant", or "tool").
        content: Message content.
        metadata: Optional per-message metadata.
            Note: when provider-native history is enabled (session metadata
            contains ``native_messages``) and the core rebuilds messages
            from the provider-native sequence, arbitrary metadata is not
            preserved by default. Persist metadata explicitly via the
            provider/feature/extension pipelines using the ``_metadata``
            key on provider-native messages.
        config: Optional configuration used to resolve provider and plugins.
        tool_result: Optional structured tool result payload for this
            message. This is the canonical structured representation for
            tool messages and may be consumed by providers when appending
            to provider-native history.
        after_index: Optional index after which to insert the message.
            When ``None`` (default), the message is appended at the end.
            ``after_index == -1`` inserts at the beginning. Negative
            indices follow Python semantics relative to the end of the
            message list.

    Returns:
        New Session with the message added (immutable update).
    """
    msg_md = dict(metadata) if isinstance(metadata, dict) else {}
    message_dict: Dict[str, Any] = {
        "role": role,
        "content": content,
        "metadata": msg_md,
    }
    if multipart_content:
        message_dict["multipartContent"] = multipart_content
    if tool_result is not None:
        message_dict[TOOL_RESULT_FIELD] = tool_result
    # Compute insertion point. When after_index is None, append at end.
    message_count = len(session.messages)
    if after_index is None:
        insert_at = message_count
    else:
        if after_index == -1:
            insert_at = 0
        else:
            idx = after_index
            if idx < 0:
                idx = message_count + idx
            if idx < 0 or idx >= message_count:
                raise IndexError("after_index out of range")
            insert_at = idx + 1

    # Append uses the existing native-preserving helper. Insert at other
    # positions rebuilds native history so that provider-native messages
    # stay consistent with the updated core sequence.
    if insert_at == message_count:
        # Message-append lifecycle hook: end-appends only (inserts
        # rebuild native history on a different path), and only when a
        # config resolves the plugin context. The legacy no-config path
        # does not dispatch.
        if config:
            message_dict = self._prepare_appended_message_with_hooks(
                message_dict,
                config,
                context=context,
            )
        # Always prefer the native-preserving helper; when native history
        # cannot be safely updated, it falls back to a core-only append.

        # TODO: Legacy behavior with no config should be removed.
        new_session, _ = self._append_single_message_with_native(
            session,
            message_dict,
            config or {},
            context=context,
        )
        return new_session

    new_session, _ = self._insert_single_message_with_native(
        session,
        message_dict,
        insert_at,
        config or {},
        context=context,
    )
    return new_session

apply_feature_completion

apply_feature_completion(config, text, completion)

Ask features to transform an accepted completion into a snippet.

Iterates over registered feature plugins and calls their :meth:apply_completion hooks in registration order. The first non-empty string returned is used as the replacement snippet.

Parameters:

Name Type Description Default
config Dict[str, Any]

Application configuration for the current agent or request.

required
text str

Full buffer text after the completion has been applied.

required
completion Dict[str, Any]

Completion descriptor dict that was accepted, as previously returned by :meth:get_completions.

required

Returns:

Type Description
str

Replacement snippet string, or an empty string when no feature

str

chooses to handle the completion.

Source code in agent_core/core.py
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
def apply_feature_completion(
    self,
    config: Dict[str, Any],
    text: str,
    completion: Dict[str, Any],
) -> str:
    """Ask features to transform an accepted completion into a snippet.

    Iterates over registered feature plugins and calls their
    :meth:`apply_completion` hooks in registration order. The first
    non-empty string returned is used as the replacement snippet.

    Args:
        config: Application configuration for the current agent or
            request.
        text: Full buffer text after the completion has been applied.
        completion: Completion descriptor dict that was accepted, as
            previously returned by :meth:`get_completions`.

    Returns:
        Replacement snippet string, or an empty string when no feature
        chooses to handle the completion.
    """

    if not self._features:
        return ""

    for feature in self._features:
        out = feature.apply_completion(config, text, completion)
        if isinstance(out, str) and out:
            return out
    return ""

core_messages_to_native

core_messages_to_native(core_messages, config, *, context=None)

Convert core-shaped messages into provider-native messages.

This is a thin public wrapper around the normal provider/extension/ feature conversion path. It is intended for request-time features and actions that need to synthesize a core message and append its provider-native form to an in-flight request without re-implementing provider-specific message shaping.

Source code in agent_core/core.py
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
def core_messages_to_native(
    self,
    core_messages: List[Dict[str, Any]],
    config: Dict[str, Any],
    *,
    context: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
    """Convert core-shaped messages into provider-native messages.

    This is a thin public wrapper around the normal provider/extension/
    feature conversion path. It is intended for request-time features and
    actions that need to synthesize a core message and append its
    provider-native form to an in-flight request without re-implementing
    provider-specific message shaping.
    """

    if not isinstance(core_messages, list):
        raise TypeError("core_messages must be a list")
    if not isinstance(config, dict):
        raise TypeError("config must be a dict")

    return self._core_messages_to_native_for_config(
        core_messages,
        config,
        context=context,
    )

create_session

create_session(session_id=None)

Create a new empty session.

Parameters:

Name Type Description Default
session_id Optional[str]

Optional session identifier. Auto-generated if omitted.

None

Returns:

Type Description
Session

New immutable Session instance with no messages.

Source code in agent_core/core.py
616
617
618
619
620
621
622
623
624
625
626
627
def create_session(self, session_id: Optional[str] = None) -> Session:
    """Create a new empty session.

    Args:
        session_id: Optional session identifier. Auto-generated if omitted.

    Returns:
        New immutable Session instance with no messages.
    """
    if session_id is None:
        session_id = str(uuid.uuid4())
    return Session(session_id=session_id, messages=[])

discover_and_register

discover_and_register(modules)

Discover plugins from Python modules and register them by duck typing.

Plugin type is inferred based on the presence of methods on the class: - Provider: has 'stream_api' or 'call_api' - Provider Extension: has 'process_chunk' (and no tool/provider I/O methods) - Tool: has 'get_tool_schemas' and 'execute_tool' - Feature: otherwise

Parameters:

Name Type Description Default
modules List[str]

List of import paths to scan for plugin classes.

required

Returns:

Type Description
Dict[str, List[str]]

Summary of registered plugin names by type with keys: providers, features, tools, extensions.

Source code in agent_core/core.py
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
def discover_and_register(self, modules: List[str]) -> Dict[str, List[str]]:
    """Discover plugins from Python modules and register them by duck typing.

    Plugin type is inferred based on the presence of methods on the class:
    - Provider: has 'stream_api' or 'call_api'
    - Provider Extension: has 'process_chunk' (and no tool/provider I/O methods)
    - Tool: has 'get_tool_schemas' and 'execute_tool'
    - Feature: otherwise

    Args:
        modules: List of import paths to scan for plugin classes.

    Returns:
        Summary of registered plugin names by type with keys: providers, features, tools, extensions.
    """
    import importlib
    import inspect

    def _normalize_identifier(value: str) -> str:
        return re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_")

    def _class_identifier(obj: type) -> str:
        snake_name = re.sub(r"(?<!^)(?=[A-Z])", "_", obj.__name__)
        return _normalize_identifier(snake_name)

    providers = []
    features = []
    tools = []
    extensions = []

    for mod_path in modules:
        module = importlib.import_module(mod_path)
        module_basename = _normalize_identifier(mod_path.rsplit(".", 1)[-1])
        module_providers = []
        for _, obj in inspect.getmembers(module, inspect.isclass):
            # Only consider classes defined in the module (not imports)
            if getattr(obj, "__module__", None) != module.__name__:
                continue
            # Duck typing
            if hasattr(obj, "stream_api") or hasattr(obj, "call_api"):
                module_providers.append(obj)
            elif hasattr(obj, "get_tool_schemas") and hasattr(obj, "execute_tool"):
                tools.append(obj)
            elif hasattr(obj, "process_chunk"):
                extensions.append(obj)
            else:
                features.append(obj)
        module_providers.sort(
            key=lambda obj: (
                (
                    0
                    if _normalize_identifier(getattr(obj, "name", ""))
                    == module_basename
                    or _class_identifier(obj) == module_basename
                    else 1
                ),
                obj.__name__,
            )
        )
        providers.extend(module_providers)

    # Register a single provider (first), with all discovered extensions
    summary: Dict[str, List[str]] = {
        "providers": [],
        "features": [],
        "tools": [],
        "extensions": [],
    }
    if providers:
        provider_cls = providers[0]
        provider_name = getattr(provider_cls, "name", provider_cls.__name__)
        self.register_provider(provider_cls, extensions=extensions)
        summary["providers"].append(provider_name)
        summary["extensions"].extend(
            [getattr(ext, "name", ext.__name__) for ext in extensions]
        )

    # Register features and tools
    for feat in features:
        self.register_feature(feat)
        summary["features"].append(getattr(feat, "name", feat.__name__))
    for tool in tools:
        self.register_tool(tool)
        summary["tools"].append(getattr(tool, "name", tool.__name__))

    return summary

execute_lifecycle_actions

execute_lifecycle_actions(session, config, trigger, *, context=None)

Execute all extension/feature actions whose trigger matches trigger.

Source code in agent_core/core.py
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
def execute_lifecycle_actions(
    self,
    session: Session,
    config: Dict[str, Any],
    trigger: str,
    *,
    context: Optional[Dict[str, Any]] = None,
) -> Tuple[Session, List[Dict[str, Any]]]:
    """Execute all extension/feature actions whose trigger matches ``trigger``."""

    if not isinstance(config, dict):
        raise TypeError("config must be a dict")
    if not isinstance(trigger, str) or not trigger:
        raise ValueError("trigger must be a non-empty string")
    if not self._providers:
        return session, []

    provider, features, state, available_actions = (
        self._get_core_session_actions_and_state(config)
    )

    current_session = session
    results: List[Dict[str, Any]] = []
    for action_def in available_actions:
        if not self._action_matches_trigger(action_def, trigger):
            continue

        plugin_id = action_def.get("plugin")
        action_id = action_def.get("id")
        action_owner = action_def.get("action_owner")
        if not isinstance(plugin_id, str) or not isinstance(action_id, str):
            continue

        validated_inputs = self._validate_session_action_inputs(action_def, {})
        native_messages = self._native_messages_for_session_action(
            current_session, config
        )

        request_context = self._build_request_context(
            config=state.get("config") or config,
            provider=provider,
            enabled_extensions=provider._iter_extensions(),
            enabled_features=features,
            enabled_tools=[],
            tags=[],
            models=self._get_models_for_config(provider, config),
            available_tools=self.get_available_tools(config),
            tools=self._get_prepared_tools_for_config(config),
            session=current_session,
            extra=context,
        )
        request_runtime = self._build_request_runtime(provider, features)
        enriched_context = self._build_lifecycle_action_context(
            config=config,
            session=current_session,
            lifecycle=trigger,
            request_context=request_context,
            request_runtime=request_runtime,
            extra=context,
        )

        if action_owner == "feature":
            result: Optional[Dict[str, Any]] = None
            for feature in features:
                if feature.name != plugin_id:
                    continue
                result = feature.execute_action(
                    action_id,
                    current_session,
                    native_messages,
                    validated_inputs,
                    enriched_context,
                    state,
                )
                break
            if result is None:
                continue
        else:
            result = provider.execute_extension_action(
                plugin_id,
                action_id,
                current_session,
                native_messages,
                validated_inputs,
                enriched_context,
                state,
            )

        if not isinstance(result, dict):
            raise RuntimeError("session action must return a dict")
        current_session, public_result = self._apply_session_action_result(
            current_session,
            config,
            result,
            context=context,
        )
        results.append(
            {
                "plugin": plugin_id,
                "action_id": action_id,
                "action_owner": action_owner,
                "result": public_result,
            }
        )

    return current_session, results

execute_response_lifecycle_actions

execute_response_lifecycle_actions(session, config, trigger, *, provider, features, state, final_messages, native_messages, native_final_messages, stream, turn_native_start_index, request_context, extra_context=None)

Execute core-owned response lifecycles before finals are emitted.

Source code in agent_core/core.py
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
def execute_response_lifecycle_actions(
    self,
    session: Session,
    config: Dict[str, Any],
    trigger: str,
    *,
    provider: Any,
    features: List[Any],
    state: Dict[str, Any],
    final_messages: List[Dict[str, Any]],
    native_messages: List[Dict[str, Any]],
    native_final_messages: List[Dict[str, Any]],
    stream: bool,
    turn_native_start_index: int,
    request_context: Dict[str, Any],
    extra_context: Optional[Dict[str, Any]] = None,
) -> Tuple[
    List[Dict[str, Any]], List[Dict[str, Any]], Dict[str, Any], List[Dict[str, Any]]
]:
    """Execute core-owned response lifecycles before finals are emitted."""

    if not isinstance(config, dict):
        raise TypeError("config must be a dict")
    if not isinstance(trigger, str) or not trigger:
        raise ValueError("trigger must be a non-empty string")

    current_final_messages = [
        msg for msg in final_messages if isinstance(msg, dict)
    ]
    current_native_messages = [
        msg for msg in native_messages if isinstance(msg, dict)
    ]
    metadata_patch: Dict[str, Any] = {}
    results: List[Dict[str, Any]] = []
    request_runtime = self._build_request_runtime(provider, features)

    available_actions = self._collect_core_session_actions(
        provider, features, state
    )

    for action_def in available_actions:
        if not self._action_matches_trigger(action_def, trigger):
            continue

        plugin_id = action_def.get("plugin")
        action_id = action_def.get("id")
        action_owner = action_def.get("action_owner")
        if not isinstance(plugin_id, str) or not isinstance(action_id, str):
            continue

        validated_inputs = self._validate_session_action_inputs(action_def, {})
        enriched_context = self._build_response_lifecycle_context(
            config=config,
            session=session,
            lifecycle=trigger,
            request_context=request_context,
            request_runtime=request_runtime,
            final_messages=current_final_messages,
            native_final_messages=[
                msg for msg in native_final_messages if isinstance(msg, dict)
            ],
            native_messages=current_native_messages,
            stream=stream,
            turn_native_start_index=turn_native_start_index,
            extra=extra_context,
        )

        if action_owner == "feature":
            result: Optional[Dict[str, Any]] = None
            for feature in features:
                if feature.name != plugin_id:
                    continue
                result = feature.execute_action(
                    action_id,
                    session,
                    current_native_messages,
                    validated_inputs,
                    enriched_context,
                    state,
                )
                break
            if result is None:
                continue
        else:
            result = provider.execute_extension_action(
                plugin_id,
                action_id,
                session,
                current_native_messages,
                validated_inputs,
                enriched_context,
                state,
            )

        if not isinstance(result, dict):
            raise RuntimeError("response lifecycle action must return a dict")

        if "final_messages" in result:
            raw_finals = result.get("final_messages")
            if not isinstance(raw_finals, list) or not all(
                isinstance(item, dict) for item in raw_finals
            ):
                raise RuntimeError(
                    "response lifecycle action final_messages must be a list of dicts"
                )
            current_final_messages = [
                item for item in raw_finals if isinstance(item, dict)
            ]

        if "native_messages" in result:
            raw_native = result.get("native_messages")
            if not isinstance(raw_native, list) or not all(
                isinstance(item, dict) for item in raw_native
            ):
                raise RuntimeError(
                    "response lifecycle action native_messages must be a list of dicts"
                )
            current_native_messages = [
                item for item in raw_native if isinstance(item, dict)
            ]

        metadata_patch_raw = result.get("session_metadata")
        if isinstance(metadata_patch_raw, dict):
            metadata_patch.update(metadata_patch_raw)

        public_result = {
            key: value
            for key, value in result.items()
            if key not in {"final_messages", "native_messages", "session_metadata"}
        }
        results.append(
            {
                "plugin": plugin_id,
                "action_id": action_id,
                "action_owner": action_owner,
                "result": public_result,
            }
        )

    return current_final_messages, current_native_messages, metadata_patch, results

execute_session_action

execute_session_action(session, config, plugin_id, action_id, params, context=None)

Execute a generic session-scoped extension or feature action.

Source code in agent_core/core.py
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
def execute_session_action(
    self,
    session: Session,
    config: Dict[str, Any],
    plugin_id: str,
    action_id: str,
    params: Dict[str, Any],
    context: Optional[Dict[str, Any]] = None,
) -> Tuple[Session, Dict[str, Any]]:
    """Execute a generic session-scoped extension or feature action."""

    if not isinstance(config, dict):
        raise TypeError("config must be a dict")
    if not isinstance(plugin_id, str) or not plugin_id:
        raise ValueError("plugin_id must be a non-empty string")
    if not isinstance(action_id, str) or not action_id:
        raise ValueError("action_id must be a non-empty string")
    if not isinstance(params, dict):
        raise ValueError("params must be a mapping of action inputs")

    provider, features, state, available_actions = (
        self._get_core_session_actions_and_state(config)
    )

    action_def = self._find_session_action_definition(
        available_actions, plugin_id, action_id
    )
    if action_def is None:
        raise KeyError(
            f"Unknown session action {action_id!r} for plugin {plugin_id!r}"
        )

    validated_inputs = self._validate_session_action_inputs(action_def, params)
    native_messages = self._native_messages_for_session_action(session, config)

    request_context = self._build_request_context(
        config=state.get("config") or config,
        provider=provider,
        enabled_extensions=provider._iter_extensions(),
        enabled_features=features,
        enabled_tools=[],
        tags=[],
        models=self._get_models_for_config(provider, config),
        available_tools=self.get_available_tools(config),
        tools=self._get_prepared_tools_for_config(config),
        session=session,
        extra=context,
    )
    request_runtime = self._build_request_runtime(provider, features)
    enriched_context = self._build_session_action_context(
        config=config,
        session=session,
        request_context=request_context,
        request_runtime=request_runtime,
        extra=context,
    )

    action_owner = action_def.get("action_owner")
    if action_owner == "feature":
        result: Optional[Dict[str, Any]] = None
        for feature in features:
            if feature.name != plugin_id:
                continue
            result = feature.execute_action(
                action_id,
                session,
                native_messages,
                validated_inputs,
                enriched_context,
                state,
            )
            break
        if result is None:
            raise KeyError(
                f"Unknown feature action {action_id!r} for plugin {plugin_id!r}"
            )
    else:
        result = provider.execute_extension_action(
            plugin_id,
            action_id,
            session,
            native_messages,
            validated_inputs,
            enriched_context,
            state,
        )
    if not isinstance(result, dict):
        raise RuntimeError("session action must return a dict")
    if action_def.get("mutates_session") is False:
        forbidden = [
            key
            for key in (
                "native_messages",
                "session_metadata",
                "rebuild_messages_from_native",
            )
            if key in result
        ]
        mutations = result.get("mutations")
        if isinstance(mutations, dict) and any(mutations.values()):
            forbidden.append("mutations")
        if forbidden:
            raise RuntimeError(
                "non-mutating session action cannot return session mutation "
                f"fields: {', '.join(forbidden)}"
            )
        return session, result
    return self._apply_session_action_result(
        session,
        config,
        result,
        context=context,
    )

execute_tool_calls

execute_tool_calls(tool_calls, config, *, context=None)

Return only the final core tool message per tool call.

This is a compatibility wrapper around :meth:iter_tool_messages that ignores partial payloads and keeps only the last final tool message for each call. When a streaming tool yields no items for a call, a synthetic error message is returned.

Parameters:

Name Type Description Default
tool_calls List[Dict[str, Any]]

List of tool call dictionaries to execute.

required
config Dict[str, Any]

Current resolved request configuration.

required
context Optional[Dict[str, Any]]

Optional context for tool execution. Passed through to :meth:iter_tool_messages which enriches with Layer 1 context.

None
Source code in agent_core/core.py
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
def execute_tool_calls(
    self,
    tool_calls: List[Dict[str, Any]],
    config: Dict[str, Any],
    *,
    context: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
    """Return only the final core ``tool`` message per tool call.

    This is a compatibility wrapper around :meth:`iter_tool_messages`
    that ignores partial payloads and keeps only the last final tool
    message for each call. When a streaming tool yields no items for a
    call, a synthetic error message is returned.

    Args:
        tool_calls: List of tool call dictionaries to execute.
        config: Current resolved request configuration.
        context: Optional context for tool execution. Passed through to
            :meth:`iter_tool_messages` which enriches with Layer 1 context.
    """
    results: List[Dict[str, Any]] = []
    if not tool_calls:
        return results

    logger.debug(
        "execute_tool_calls_start",
        count=len(tool_calls),
    )

    for call in tool_calls:
        last_final: Dict[str, Any] | None = None
        executed = False

        for item in self.iter_tool_messages([call], config, context=context):
            if not isinstance(item, dict):
                continue
            if "part" in item:
                # Streaming partial; ignored in final-only API.
                continue
            last_final = item
            executed = True

        if last_final is None:
            try:
                registry = self._get_tool_interop_registry_for_config(config)
                inspected_call = registry.inspect_call(call)
                call_id = inspected_call.call_id
                name = inspected_call.tool_name
            except Exception:
                call_id = None
                name = None
            metadata: Dict[str, Any] = {
                "tool_call_id": call_id,
                "tool_name": name,
            }
            last_final = {
                "role": "tool",
                "content": f"Error: no tool handled '{name}'",
                "metadata": metadata,
            }
            executed = False

        md = last_final.get("metadata") or {}
        logger.debug(
            "execute_tool_call_complete",
            tool_name=str(md.get("tool_name")),
            executed=executed,
        )
        results.append(last_final)

    return results

export_session

export_session(session, format='json')

Export session to a serialized string.

Parameters:

Name Type Description Default
session Session

Session to serialize.

required
format str

Export format. Only "json" is supported.

'json'

Returns:

Type Description
str

Serialized string representing the session.

Raises:

Type Description
ValueError

If the format is not supported.

Source code in agent_core/core.py
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
def export_session(self, session: Session, format: str = "json") -> str:
    """Export session to a serialized string.

    Args:
        session: Session to serialize.
        format: Export format. Only "json" is supported.

    Returns:
        Serialized string representing the session.

    Raises:
        ValueError: If the format is not supported.
    """
    if format == "json":
        return json.dumps(session.to_dict(), indent=2)
    raise ValueError(f"Unsupported format: {format}")

extract_tool_calls_from_messages

extract_tool_calls_from_messages(messages)

Extract tool-call dictionaries from assistant message metadata.

Source code in agent_core/core.py
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
def extract_tool_calls_from_messages(
    self,
    messages: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
    """Extract tool-call dictionaries from assistant message metadata."""

    tool_calls: List[Dict[str, Any]] = []
    for msg in messages:
        if not isinstance(msg, dict) or msg.get("role") != "assistant":
            continue
        metadata = msg.get("metadata") or {}
        calls = metadata.get("tool_calls") or []
        if isinstance(calls, list):
            tool_calls.extend([call for call in calls if isinstance(call, dict)])
    return tool_calls

fork_session

fork_session(session, config=None, *, upto_index, new_session_id=None)

Convenience helper to fork a session up to upto_index.

Source code in agent_core/core.py
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
def fork_session(
    self,
    session: Session,
    config: Optional[Dict[str, Any]] = None,
    *,
    upto_index: int,
    new_session_id: Optional[str] = None,
) -> Session:
    """Convenience helper to fork a session up to upto_index."""
    sliced = self.slice_session(
        session,
        config,
        start=0,
        end=upto_index + 1,
    )
    if new_session_id is None or new_session_id == sliced.session_id:
        return sliced
    return Session(
        session_id=new_session_id,
        messages=sliced.messages,
        metadata=sliced.metadata,
    )

format_tool_call_preview

format_tool_call_preview(tool_call, config)

Return a preview record for a single tool call.

Source code in agent_core/core.py
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
def format_tool_call_preview(
    self,
    tool_call: Dict[str, Any],
    config: Dict[str, Any],
) -> Dict[str, Any]:
    """Return a preview record for a single tool call."""

    provider, extensions, tool_states = self._get_enabled_tool_states_for_config(
        config
    )
    registry = self._get_tool_interop_registry_for_config(
        config,
        provider=provider,
        extensions=extensions,
        tool_states=tool_states,
    )

    try:
        inspected_call = registry.inspect_call(tool_call)
    except Exception:
        inspected_call = None

    if inspected_call is None:
        return {"id": None, "preview": ""}

    tool, state, prepared, _matched_schema = self._resolve_tool_handler_for_call(
        inspected_call,
        tool_states,
        registry,
    )
    if tool is None or state is None:
        return {"id": inspected_call.call_id, "preview": ""}

    try:
        preview = tool.format_tool_call_preview(
            inspected_call.tool_name,
            inspected_call.payload,
            state,
            payload_kind=inspected_call.payload_kind,
            payload_format=inspected_call.payload_format,
            payload_metadata=inspected_call.payload_metadata,
            tool_call=inspected_call.raw,
            prepared=prepared,
        )
    except Exception:
        preview = ""

    return {
        "id": inspected_call.call_id,
        "preview": preview if isinstance(preview, str) else "",
    }

format_tool_call_previews

format_tool_call_previews(tool_calls, config)

Return preview records for all supplied tool calls.

Source code in agent_core/core.py
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
def format_tool_call_previews(
    self,
    tool_calls: List[Dict[str, Any]],
    config: Dict[str, Any],
) -> List[Dict[str, Any]]:
    """Return preview records for all supplied tool calls."""

    return [
        self.format_tool_call_preview(tool_call, config)
        for tool_call in tool_calls
        if isinstance(tool_call, dict)
    ]

get_available_tools

get_available_tools(config)

Get the full available tool catalog for a config before filtering.

Source code in agent_core/core.py
3987
3988
3989
def get_available_tools(self, config: Dict[str, Any]) -> List[ToolDescriptor]:
    """Get the full available tool catalog for a config before filtering."""
    return self._get_available_tools_for_config(config)[0]

get_completions

get_completions(config, text)

Collect completion suggestions from registered feature plugins.

Parameters:

Name Type Description Default
config Dict[str, Any]

Application configuration for the current agent or request.

required
text str

Full text before the cursor (for example, the current input line in a terminal UI).

required

Returns:

Type Description
List[Dict[str, Any]]

List of completion descriptor dictionaries contributed by

List[Dict[str, Any]]

features. The exact shape of each entry is feature- and

List[Dict[str, Any]]

application-defined; common keys include "replacement",

List[Dict[str, Any]]

"start", "display", and "display_meta".

Source code in agent_core/core.py
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
def get_completions(
    self, config: Dict[str, Any], text: str
) -> List[Dict[str, Any]]:
    """Collect completion suggestions from registered feature plugins.

    Args:
        config: Application configuration for the current agent or request.
        text: Full text before the cursor (for example, the current input
            line in a terminal UI).

    Returns:
        List of completion descriptor dictionaries contributed by
        features. The exact shape of each entry is feature- and
        application-defined; common keys include "replacement",
        "start", "display", and "display_meta".
    """

    completions: List[Dict[str, Any]] = []
    if not self._features:
        return completions

    for feature in self._features:
        try:
            items = feature.get_completions(config, text) or []
        except Exception:
            continue
        for item in items:
            if isinstance(item, dict):
                completions.append(item)
    return completions

get_config_schema

get_config_schema()

Get flattened config schema from all registered plugins.

Returns:

Type Description
List[Dict[str, Any]]

Config entry descriptors. Every dictionary contains "key" and

List[Dict[str, Any]]

the contributing "plugin" ID plus metadata supplied by that

List[Dict[str, Any]]

plugin, such as "type", "default", "required", or

List[Dict[str, Any]]

"description". Multiple plugins can contribute separate

List[Dict[str, Any]]

entries for the same key.

Source code in agent_core/core.py
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
def get_config_schema(self) -> List[Dict[str, Any]]:
    """Get flattened config schema from all registered plugins.

    Returns:
        Config entry descriptors. Every dictionary contains ``"key"`` and
        the contributing ``"plugin"`` ID plus metadata supplied by that
        plugin, such as ``"type"``, ``"default"``, ``"required"``, or
        ``"description"``. Multiple plugins can contribute separate
        entries for the same key.
    """
    entries: List[Dict[str, Any]] = []

    def _extend(schema: Dict[str, Any] | None, plugin_name: str) -> None:
        if not schema:
            return
        for key, value in schema.items():
            if not isinstance(key, str) or not key:
                continue
            if not isinstance(value, dict):
                continue
            entry: Dict[str, Any] = dict(value)
            if "plugin" not in entry:
                entry["plugin"] = plugin_name
            entry.setdefault("key", key)
            entries.append(entry)

    for provider in self._providers:
        _extend(provider.get_config_schema(), provider.name)
        # Include provider extension schemas
        for name, ext_schema in provider.get_extension_config_schemas().items():
            _extend(ext_schema, name)
    for feature in self._features:
        _extend(feature.get_config_schema(), feature.name)
    for tool in self._tools:
        _extend(tool.get_config_schema(), tool.name)
    return entries

get_models

get_models(config)

Discover models through the configured provider, extensions, and features.

Uses the same normalized descriptors and model-discovery cache as the UI and request pipeline. Each descriptor contains a non-empty id; plugin-defined order and additional metadata are preserved. Plugins may perform catalog I/O, but this method does not send an inference request or create a session.

Source code in agent_core/core.py
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
def get_models(self, config: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Discover models through the configured provider, extensions, and features.

    Uses the same normalized descriptors and model-discovery cache as the
    UI and request pipeline. Each descriptor contains a non-empty ``id``;
    plugin-defined order and additional metadata are preserved. Plugins
    may perform catalog I/O, but this method does not send an inference
    request or create a session.
    """
    if not isinstance(config, dict):
        raise TypeError("config must be a dict")
    provider = self._select_provider_for_config(config)
    return self._get_models_for_config(provider, config)

get_plugins_for_config

get_plugins_for_config(config)

Return active plugin identifiers for the given config.

The result is derived from the same tag-based dependency resolution used internally by the core. It maps plugin kinds ("providers", "extensions", "features", "tools") to lists of active plugin identifiers for this config.

Source code in agent_core/core.py
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
def get_plugins_for_config(
    self,
    config: Dict[str, Any],
) -> Dict[str, List[str]]:
    """Return active plugin identifiers for the given config.

    The result is derived from the same tag-based dependency
    resolution used internally by the core. It maps plugin kinds
    ("providers", "extensions", "features", "tools") to lists of
    active plugin identifiers for this config.
    """

    (
        provider,
        enabled_extensions,
        enabled_features,
        enabled_tools,
        _tags,
    ) = self._resolve_plugins_for_config(config)

    return {
        "providers": [provider.name],
        "extensions": [ext.name for ext in enabled_extensions],
        "features": [feat.name for feat in enabled_features],
        "tools": [tool.name for tool in enabled_tools],
    }

get_session_actions

get_session_actions(config)

Return session-scoped extension and feature actions for the config.

Source code in agent_core/core.py
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
def get_session_actions(self, config: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Return session-scoped extension and feature actions for the config."""

    if not isinstance(config, dict):
        raise TypeError("config must be a dict")
    if not self._providers:
        return []

    _provider, _features, _state, actions = (
        self._get_core_session_actions_and_state(config)
    )
    return actions

get_tool_schemas

get_tool_schemas(config)

Get the effective tool schemas for a config after feature policy.

Source code in agent_core/core.py
3980
3981
3982
3983
3984
3985
def get_tool_schemas(self, config: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Get the effective tool schemas for a config after feature policy."""
    return [
        descriptor.schema
        for descriptor in self._get_prepared_tools_for_config(config)
    ]

get_ui_schema

get_ui_schema(config)

Get flattened UI schema for the effective config.

Plugins receive additional context computed from config:

  • tags: capability/environment tags produced by the provider and enabled plugins.
  • models: model descriptors returned by get_models hooks.

Each element is a dictionary describing a UI element contributed by a provider, extension, feature, or tool. The core treats the dictionaries as opaque and simply annotates and flattens them; applications decide how to render or interpret each entry.

Every element carries a numeric order and the returned list is sorted by it (stable). An element may set an explicit order; when absent the core stamps a kind-and-position default: provider band 1000, provider extension band 2000, feature band 3000, tool band 4000, and within a band the Nth plugin defaults to band + N * 10. Elements from one plugin share the plugin default, so the stable sort keeps each plugin's declared element order. Explicit orders override the defaults on the same scale (e.g. 1990 sorts before every extension element, 2015 between the first and second extension plugins).

Source code in agent_core/core.py
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
def get_ui_schema(self, config: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Get flattened UI schema for the effective config.

    Plugins receive additional context computed from ``config``:

    - ``tags``: capability/environment tags produced by the provider and
      enabled plugins.
    - ``models``: model descriptors returned by ``get_models`` hooks.

    Each element is a dictionary describing a UI element contributed by a
    provider, extension, feature, or tool. The core treats the dictionaries
    as opaque and simply annotates and flattens them; applications decide
    how to render or interpret each entry.

    Every element carries a numeric ``order`` and the returned list is
    sorted by it (stable). An element may set an explicit ``order``; when
    absent the core stamps a kind-and-position default: provider band
    1000, provider extension band 2000, feature band 3000, tool band
    4000, and within a band the Nth plugin defaults to ``band + N * 10``.
    Elements from one plugin share the plugin default, so the stable
    sort keeps each plugin's declared element order. Explicit orders
    override the defaults on the same scale (e.g. ``1990`` sorts before
    every extension element, ``2015`` between the first and second
    extension plugins).
    """

    if not isinstance(config, dict):
        raise TypeError("config must be a dict")

    if not self._providers and not self._features and not self._tools:
        return []

    provider: Optional[ProviderWrapper] = None
    enabled_extensions: List[ExtensionWrapper] = []
    enabled_features: List[FeatureWrapper] = list(self._features)
    enabled_tools: List[ToolWrapper] = list(self._tools)
    tags: List[str] = []
    models: List[Dict[str, Any]] = []

    if self._providers:
        (
            provider,
            enabled_extensions,
            enabled_features,
            enabled_tools,
            tags,
        ) = self._resolve_plugins_for_config(config)
        provider.set_active_extensions(enabled_extensions)
        models = self._get_models_for_config(provider, config)

    enabled_features = sorted(
        enabled_features, key=lambda feat: getattr(feat, "priority", 100)
    )
    enabled_tools = sorted(
        enabled_tools, key=lambda tool: getattr(tool, "priority", 100)
    )
    available_tools = self.get_available_tools(config)
    effective_tools = self._get_prepared_tools_for_config(config)
    ui_context = self._build_plugin_context(
        config=config,
        provider=provider,
        enabled_extensions=enabled_extensions,
        enabled_features=enabled_features,
        enabled_tools=enabled_tools,
        tags=tags,
        models=models,
        available_tools=available_tools,
        tools=effective_tools,
    )
    extension_plugin_names = {ext.name for ext in enabled_extensions}
    feature_plugin_names = {feature.name for feature in enabled_features}

    elements: List[Dict[str, Any]] = []
    config_by_key: Dict[str, Dict[str, Any]] = {}

    def _extend(
        raw_elements: List[Dict[str, Any]],
        plugin_name: str,
        default_order: int,
    ) -> None:
        for el in raw_elements or []:
            if not isinstance(el, dict):
                continue
            entry: Dict[str, Any] = dict(el)
            ui_type = entry.get("ui_type")
            if not isinstance(ui_type, str) or not ui_type:
                entry["ui_type"] = "config"
                ui_type = "config"
            if "plugin" not in entry and plugin_name:
                entry["plugin"] = plugin_name

            order = entry.get("order")
            if not isinstance(order, (int, float)) or isinstance(order, bool):
                entry["order"] = default_order

            if (
                plugin_name in extension_plugin_names
                and ui_type in {"session_action", "message_action"}
                and isinstance(entry.get("action_id"), str)
                and "action_owner" not in entry
            ):
                entry["action_owner"] = "provider_extension"
            elif (
                plugin_name in feature_plugin_names
                and ui_type in {"session_action", "message_action"}
                and isinstance(entry.get("action_id"), str)
                and "action_owner" not in entry
            ):
                entry["action_owner"] = "feature"

            if ui_type == "config":
                key = entry.get("key")
                if isinstance(key, str) and key:
                    config_by_key[key] = entry
                    continue

            elements.append(entry)

    if provider is not None:
        _extend(provider.get_ui_elements(config, ui_context), provider.name, 1010)
        for ext_position, (name, ext_ui) in enumerate(
            provider.get_extension_ui_elements(config, ui_context).items()
        ):
            _extend(ext_ui, name, 2000 + (ext_position + 1) * 10)
    for feature_position, feature in enumerate(enabled_features):
        _extend(
            feature.get_ui_elements(config, ui_context),
            feature.name,
            3000 + (feature_position + 1) * 10,
        )
    for tool_position, tool in enumerate(enabled_tools):
        _extend(
            tool.get_ui_elements(config, ui_context),
            tool.name,
            4000 + (tool_position + 1) * 10,
        )

    elements.extend(config_by_key.values())
    elements.sort(key=lambda entry: entry.get("order", 0))
    return elements

import_session

import_session(data, format='json')

Import a session from a serialized string.

Parameters:

Name Type Description Default
data str

Serialized session string.

required
format str

Import format. Only "json" is supported.

'json'

Returns:

Type Description
Session

A new Session reconstructed from the serialized data.

Raises:

Type Description
ValueError

If the format is not supported.

Source code in agent_core/core.py
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
def import_session(self, data: str, format: str = "json") -> Session:
    """Import a session from a serialized string.

    Args:
        data: Serialized session string.
        format: Import format. Only "json" is supported.

    Returns:
        A new Session reconstructed from the serialized data.

    Raises:
        ValueError: If the format is not supported.
    """
    if format == "json":
        session_dict = json.loads(data)
        return Session.from_dict(session_dict)
    raise ValueError(f"Unsupported format: {format}")

initialize_action_request

initialize_action_request(native_messages, state, request_runtime, request_context)

Apply request-time initialization to session-action inputs.

Session actions should see the same request-time state that normal provider requests see, including feature/provider initialize_request changes such as compiled top-level instructions.

Source code in agent_core/core.py
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
def initialize_action_request(
    self,
    native_messages: List[Dict[str, Any]],
    state: Dict[str, Any],
    request_runtime: Dict[str, Any],
    request_context: Dict[str, Any],
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
    """Apply request-time initialization to session-action inputs.

    Session actions should see the same request-time state that normal
    provider requests see, including feature/provider `initialize_request`
    changes such as compiled top-level instructions.
    """
    if not isinstance(native_messages, list):
        raise TypeError("native_messages must be a list")
    if not isinstance(state, dict):
        raise TypeError("state must be a dict")
    if not isinstance(request_runtime, dict):
        raise TypeError("request_runtime must be a dict")
    if not isinstance(request_context, dict):
        raise TypeError("request_context must be a dict")

    provider = request_runtime.get("provider")
    if provider is None:
        raise ValueError("request_runtime must include provider")
    raw_features = request_runtime.get("features")
    if raw_features is None:
        features: List[Any] = []
    elif isinstance(raw_features, list):
        features = raw_features
    else:
        raise TypeError("request_runtime['features'] must be a list")

    next_native_messages, next_state = provider.initialize_request(
        native_messages,
        state,
        context=request_context,
    )
    initialized_native = (
        next_native_messages
        if next_native_messages != native_messages
        else native_messages
    )
    initialized_state = next_state

    for feature in features:
        next_native_messages, initialized_state = feature.initialize_request(
            initialized_native,
            initialized_state,
            context=request_context,
        )
        if next_native_messages != initialized_native:
            initialized_native = next_native_messages
        provider.set_state(initialized_state)

    return initialized_native, initialized_state

iter_tool_messages

iter_tool_messages(tool_calls, config, *, cancellation=None, context=None)

Yield a mixed stream of partial payloads and final core tool messages.

Tools stream via ToolPlugin.stream_tool. Partial display payloads are yielded as-is when they contain a "part" key. Result dictionaries are detected via the presence of a "success" key and transformed into final core tool messages at the end of each tool call.

Enabled extensions and features participate through the optional prepare_tool_call/finalize_tool_call hooks (extensions before features, priority order within each kind; shared state threaded through the chain). prepare_tool_call may transform the call; the transformed call is re-inspected before handler resolution. finalize_tool_call runs exactly once per call, on the single final message every call yields (including synthesized error results, which carry a tool_error context fact). The hooks dispatch only when the full plugin context resolves (a provider is registered and selected).

Parameters:

Name Type Description Default
tool_calls List[Dict[str, Any]]

List of tool call dictionaries to execute.

required
config Dict[str, Any]

Current resolved request configuration.

required
cancellation Any | None

Optional cancellation token.

None
context Optional[Dict[str, Any]]

Optional context for tool execution. Layer 1 context (core, config, trigger_source) is enriched by this method if not already present.

None
Source code in agent_core/core.py
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
def iter_tool_messages(
    self,
    tool_calls: List[Dict[str, Any]],
    config: Dict[str, Any],
    *,
    cancellation: Any | None = None,
    context: Optional[Dict[str, Any]] = None,
) -> Iterator[Dict[str, Any]]:
    """Yield a mixed stream of partial payloads and final core ``tool`` messages.

    Tools stream via ``ToolPlugin.stream_tool``. Partial display payloads are
    yielded as-is when they contain a ``"part"`` key. Result dictionaries are
    detected via the presence of a ``"success"`` key and transformed into final
    core ``tool`` messages at the end of each tool call.

    Enabled extensions and features participate through the optional
    ``prepare_tool_call``/``finalize_tool_call`` hooks (extensions before
    features, priority order within each kind; shared state threaded
    through the chain). ``prepare_tool_call`` may transform the call; the
    transformed call is re-inspected before handler resolution.
    ``finalize_tool_call`` runs exactly once per call, on the single final
    message every call yields (including synthesized error results, which
    carry a ``tool_error`` context fact). The hooks dispatch only when the
    full plugin context resolves (a provider is registered and selected).

    Args:
        tool_calls: List of tool call dictionaries to execute.
        config: Current resolved request configuration.
        cancellation: Optional cancellation token.
        context: Optional context for tool execution. Layer 1 context (core,
            config, trigger_source) is enriched by this method if not already
            present.
    """
    if not tool_calls:
        return

    logger.debug(
        "iter_tool_messages_start",
        count=len(tool_calls),
    )

    provider, extensions, tool_states = self._get_enabled_tool_states_for_config(
        config
    )
    registry = self._get_tool_interop_registry_for_config(
        config,
        provider=provider,
        extensions=extensions,
        tool_states=tool_states,
    )
    hook_participants = self._tool_call_hook_participants(
        provider,
        extensions,
        config,
    )
    # Shared provider state for the hook chains. When the provider has
    # initialized state, thread it through the chains and write the final
    # state back; otherwise use transient state (the request pipeline
    # re-initializes provider state per request anyway).
    provider_state = (
        provider.state
        if provider is not None
        and isinstance(getattr(provider, "state", None), dict)
        else None
    )
    hook_state: Dict[str, Any] = dict(provider_state) if provider_state else {}

    def _write_back_hook_state() -> None:
        if provider is not None and provider_state is not None:
            provider.state = hook_state

    def _record_call_facts(facts: Dict[str, Any]) -> None:
        # Record framework-owned facts into the caller's context so they
        # flow to later consumers (e.g. the append hook when the
        # application reuses this context for add_message). The context
        # reflects the most recent call.
        if isinstance(context, dict):
            context.update(facts)

    for call in tool_calls:
        try:
            inspected_call = registry.inspect_call(call)
        except Exception:
            inspected_call = None

        if inspected_call is None:
            call_id = None
            name = None
            # No matching tool found; synthesize an error message.
            metadata: Dict[str, Any] = {
                "tool_call_id": call_id,
                "tool_name": name,
            }
            message = {
                "role": "tool",
                "content": f"Error: no tool handled '{name}'",
                "metadata": metadata,
            }
            if hook_participants:
                error_context = {
                    **self._build_tool_runtime_context(config, context),
                    "tool_error": "inspect_call_failed",
                }
                _record_call_facts({"tool_error": "inspect_call_failed"})
                message, hook_state = self._dispatch_finalize_tool_call(
                    hook_participants,
                    message,
                    hook_state,
                    error_context,
                )
                _write_back_hook_state()
            yield message
            continue

        call_id = inspected_call.call_id
        name = inspected_call.tool_name

        tool, state, prepared, matched_schema = self._resolve_tool_handler_for_call(
            inspected_call,
            tool_states,
            registry,
        )

        # Layer 1: Core-level context enrichment.
        # Higher layers (application, terminal) may have already set these;
        # use setdefault so we never overwrite a richer value.
        tool_context = self._build_tool_runtime_context(config, context)

        # Framework-owned facts only: raw timestamps and the call
        # descriptor. The framework never computes durations or
        # stamps messages.
        hook_context: Dict[str, Any] = {}
        if hook_participants:
            started_at = datetime.now(timezone.utc).isoformat()
            started_at_mono = time.monotonic()
            hook_context = {
                **tool_context,
                "tool_call_id": call_id,
                "tool_name": name,
                "tool_plugin": (
                    getattr(tool, "name", None) if tool is not None else None
                ),
                "started_at": started_at,
                "started_at_mono": started_at_mono,
            }
            effective_call, hook_state = self._dispatch_prepare_tool_call(
                hook_participants,
                inspected_call.raw,
                hook_state,
                hook_context,
            )
            _write_back_hook_state()
            _record_call_facts(
                {
                    "tool_call_id": call_id,
                    "tool_name": name,
                    "tool_plugin": hook_context.get("tool_plugin"),
                    "started_at": started_at,
                    "started_at_mono": started_at_mono,
                }
            )
            if effective_call != inspected_call.raw:
                # A participant transformed the call; re-inspect before
                # resolving the handler. A transformed call that no
                # longer inspects follows the synthesized-error path.
                try:
                    inspected_call = registry.inspect_call(effective_call)
                except Exception:
                    inspected_call = None
                if inspected_call is None:
                    metadata = {
                        "tool_call_id": call_id,
                        "tool_name": name,
                    }
                    message = {
                        "role": "tool",
                        "content": f"Error: no tool handled '{name}'",
                        "metadata": metadata,
                    }
                    error_context = {
                        **hook_context,
                        "tool_error": "inspect_call_failed_after_prepare",
                    }
                    message, hook_state = self._dispatch_finalize_tool_call(
                        hook_participants,
                        message,
                        hook_state,
                        error_context,
                    )
                    _write_back_hook_state()
                    yield message
                    continue
                call_id = inspected_call.call_id
                name = inspected_call.tool_name
                hook_context = {
                    **hook_context,
                    "tool_call_id": call_id,
                    "tool_name": name,
                }
                tool, state, prepared, matched_schema = (
                    self._resolve_tool_handler_for_call(
                        inspected_call,
                        tool_states,
                        registry,
                    )
                )
                _record_call_facts(
                    {
                        "tool_call_id": call_id,
                        "tool_name": name,
                        "tool_plugin": (
                            getattr(tool, "name", None)
                            if tool is not None
                            else None
                        ),
                    }
                )

        if tool is None or state is None:
            metadata = {
                "tool_call_id": call_id,
                "tool_name": name,
            }
            message = {
                "role": "tool",
                "content": f"Error: no tool handled '{name}'",
                "metadata": metadata,
            }
            if hook_participants:
                error_context = {
                    **hook_context,
                    "tool_error": f"no tool handled '{name}'",
                }
                _record_call_facts({"tool_error": f"no tool handled '{name}'"})
                message, hook_state = self._dispatch_finalize_tool_call(
                    hook_participants,
                    message,
                    hook_state,
                    error_context,
                )
                _write_back_hook_state()
            yield message
            continue
        last_result: Dict[str, Any] | None = None
        had_result = False
        stream_error: str | None = None

        try:
            iterator = tool.stream_tool(
                name,
                inspected_call.payload,
                state,
                payload_kind=inspected_call.payload_kind,
                payload_format=inspected_call.payload_format,
                payload_metadata=inspected_call.payload_metadata,
                tool_call=inspected_call.raw,
                cancellation=cancellation,
                context=tool_context,
                prepared=prepared,
            )
            iterator = iter(iterator)
        except Exception as exc:
            iterator = None
            stream_error = f"Tool error: {exc}"

        if iterator is not None:
            try:
                for chunk in iterator:
                    if not isinstance(chunk, dict):
                        continue
                    if "success" in chunk:
                        last_result = chunk
                        had_result = True
                    elif "part" in chunk:
                        # Partial display payload; forward as-is.
                        yield chunk
                    else:
                        # Backwards-compatible: treat any other dict as a partial payload.
                        yield {"part": chunk}
            except Exception as exc:
                stream_error = f"Tool error: {exc}"
                logger.error(
                    "iter_tool_messages_stream_error",
                    tool_name=str(name),
                    error=str(exc),
                )

        if not had_result:
            # No RESULT dict was produced; synthesize an error message.
            content = stream_error or f"Error: no tool handled '{name}'"
            metadata = {
                "tool_call_id": call_id,
                "tool_name": name,
            }
            plugin_name = getattr(tool, "name", None)
            if isinstance(plugin_name, str) and plugin_name:
                metadata["tool_plugin"] = plugin_name
            message = {
                "role": "tool",
                "content": content,
                "metadata": metadata,
            }
            if hook_participants:
                finalize_context: Dict[str, Any] = {
                    **hook_context,
                    "finished_at": datetime.now(timezone.utc).isoformat(),
                    "finished_at_mono": time.monotonic(),
                    "tool_error": content,
                }
                _record_call_facts(
                    {
                        "finished_at": finalize_context["finished_at"],
                        "finished_at_mono": finalize_context["finished_at_mono"],
                        "tool_error": content,
                    }
                )
                message, hook_state = self._dispatch_finalize_tool_call(
                    hook_participants,
                    message,
                    hook_state,
                    finalize_context,
                )
                _write_back_hook_state()
            yield message
            continue

        assert last_result is not None
        try:
            formatted_content = tool.format_tool_result(last_result, state)
        except Exception as exc:
            formatted_content = f"Tool formatting error: {exc}"

        inspected_result = registry.inspect_result(formatted_content)
        display_text = inspected_result.text
        display_payload: Dict[str, Any] | None = None
        try:
            display_candidate = tool.to_display_format(
                display_text,
                last_result,
                state,
            )
            if isinstance(display_candidate, dict):
                display_payload = display_candidate
        except Exception:
            display_payload = None

        if (
            isinstance(display_payload, dict)
            and display_payload.get("type") == "text"
            and display_payload.get("content") == display_text
            and "single_line" not in display_payload
            and isinstance(inspected_result.display, dict)
        ):
            display_payload = inspected_result.display

        tool_result_value: Dict[str, Any]
        if isinstance(formatted_content, dict) and (
            inspected_result.format_id != CORE_TEXT_TOOL_RESULT_FORMAT_ID
        ):
            tool_result_value = formatted_content
        else:
            converted_result = registry.convert_tool_result(
                formatted_content,
                target=ToolInteropTarget("core.tool_result"),
                target_formats=[CORE_TEXT_TOOL_RESULT_FORMAT_ID],
            )
            if isinstance(converted_result, dict):
                tool_result_value = converted_result
            else:
                tool_result_value = {
                    "type": "tool_result",
                    "text": inspected_result.text,
                }

        if display_payload is None:
            canonical_result = registry.inspect_result(tool_result_value)
            if isinstance(canonical_result.display, dict):
                display_payload = canonical_result.display

        metadata = {
            "tool_call_id": call_id,
            "tool_name": name,
        }
        if matched_schema is not None:
            metadata["tool_schema"] = matched_schema
        plugin_name = getattr(tool, "name", None)
        if isinstance(plugin_name, str) and plugin_name:
            metadata["tool_plugin"] = plugin_name
        if display_payload is not None:
            metadata["display"] = display_payload

        # Merge tool-supplied metadata from the result dict. Tools may
        # return a ``metadata`` mapping (e.g. ``{"bash": {"end_cwd": ...}}``)
        # to attach immutable, session-persistent metadata to the tool
        # result message. Core-managed keys above are not overwritten.
        result_metadata = (
            last_result.get("metadata") if isinstance(last_result, dict) else None
        )
        if isinstance(result_metadata, dict) and result_metadata:
            for key, value in result_metadata.items():
                if key not in metadata:
                    metadata[key] = value

        tool_message = {
            "role": "tool",
            "content": registry.inspect_result(tool_result_value).text,
            "metadata": metadata,
            TOOL_RESULT_FIELD: tool_result_value,
        }

        if hook_participants:
            finalize_context = {
                **hook_context,
                "finished_at": datetime.now(timezone.utc).isoformat(),
                "finished_at_mono": time.monotonic(),
            }
            _record_call_facts(
                {
                    "finished_at": finalize_context["finished_at"],
                    "finished_at_mono": finalize_context["finished_at_mono"],
                }
            )
            tool_message, hook_state = self._dispatch_finalize_tool_call(
                hook_participants,
                tool_message,
                hook_state,
                finalize_context,
            )
            _write_back_hook_state()

        yield tool_message

join_sessions

join_sessions(prefix, suffix, config=None)

Join two sessions end-to-end, preserving native history when possible.

This helper concatenates the core messages from prefix and suffix and, when both sessions contain provider-native history, combines their native histories and rebuilds core messages from the merged native sequence.

Note: arbitrary per-message Message.metadata is not preserved by default across the native-history rebuild step. If metadata must survive native rebuilds, it must be persisted into provider-native messages via the _metadata key and reconstructed in from_native_messages.

Parameters:

Name Type Description Default
prefix Session

First session segment.

required
suffix Session

Second session segment that should follow prefix.

required
config Optional[Dict[str, Any]]

Optional configuration used when rebuilding from native history. When omitted, joins are performed in core-only mode.

None

Returns:

Type Description
Session

New Session instance representing the concatenation of prefix

Session

and suffix.

Source code in agent_core/core.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
def join_sessions(
    self,
    prefix: Session,
    suffix: Session,
    config: Optional[Dict[str, Any]] = None,
) -> Session:
    """Join two sessions end-to-end, preserving native history when possible.

    This helper concatenates the core messages from ``prefix`` and
    ``suffix`` and, when both sessions contain provider-native history,
    combines their native histories and rebuilds core messages from the
    merged native sequence.

    Note: arbitrary per-message ``Message.metadata`` is not preserved by
    default across the native-history rebuild step. If metadata must
    survive native rebuilds, it must be persisted into provider-native
    messages via the ``_metadata`` key and reconstructed in
    ``from_native_messages``.

    Args:
        prefix: First session segment.
        suffix: Second session segment that should follow ``prefix``.
        config: Optional configuration used when rebuilding from native
            history. When omitted, joins are performed in core-only mode.

    Returns:
        New Session instance representing the concatenation of ``prefix``
        and ``suffix``.
    """

    from agent_core.types import Message  # local import to avoid cycles

    # Core-only join when native history is not consistently available on
    # both sessions or when no configuration is provided.
    has_prefix_native = isinstance(prefix.metadata, dict) and isinstance(
        prefix.metadata.get("native_messages"), list
    )
    has_suffix_native = isinstance(suffix.metadata, dict) and isinstance(
        suffix.metadata.get("native_messages"), list
    )

    if not config or not (has_prefix_native and has_suffix_native):
        combined_messages: List[Message] = [*prefix.messages, *suffix.messages]
        new_metadata: Dict[str, Any] = (
            dict(prefix.metadata) if isinstance(prefix.metadata, dict) else {}
        )
        new_metadata.pop("native_messages", None)
        new_metadata.pop("native_messages_integrity", None)
        return Session(
            session_id=prefix.session_id,
            messages=combined_messages,
            metadata=new_metadata,
        )

    # Native-preserving join: concatenate native histories and rebuild
    # core messages from the combined native sequence.
    native_prefix = prefix.metadata.get("native_messages") or []
    native_suffix = suffix.metadata.get("native_messages") or []
    new_native: List[Dict[str, Any]] = list(native_prefix) + list(native_suffix)

    # Skip initialize_request for session join operations.
    # This prevents features like SystemMessageFeature from adding
    # synthetic messages during join, which would cause duplicates
    # if one of the sessions already has a system message.
    rebuilt_messages, post_init_native = self._rebuild_core_from_native(
        new_native, config or {}, skip_initialize=True
    )

    new_metadata = (
        dict(prefix.metadata) if isinstance(prefix.metadata, dict) else {}
    )
    new_metadata["native_messages"] = post_init_native
    new_metadata["native_messages_integrity"] = self._compute_native_integrity(
        rebuilt_messages
    )

    return Session(
        session_id=prefix.session_id,
        messages=rebuilt_messages,
        metadata=new_metadata,
    )

modify_message

modify_message(session, index, content, config=None, *, context=None)

Modify message content and return an updated session.

Only system, user, and assistant messages are supported. The message role, metadata, and multipart content remain unchanged. When provider-native history is present and safely mappable via native_indices, the corresponding native messages are updated. Otherwise, native history is dropped and will be reconstructed on the next request.

Parameters:

Name Type Description Default
session Session

Current session.

required
index int

Message index to modify (0-based; negative indices supported).

required
content str

New message content.

required
config Optional[Dict[str, Any]]

Optional configuration used to resolve provider and plugins when updating native history.

None

Returns:

Type Description
Session

New Session with the modified message (immutable update).

Source code in agent_core/core.py
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
def modify_message(
    self,
    session: Session,
    index: int,
    content: str,
    config: Optional[Dict[str, Any]] = None,
    *,
    context: Optional[Dict[str, Any]] = None,
) -> Session:
    """Modify message content and return an updated session.

    Only `system`, `user`, and `assistant` messages are supported. The
    message role, metadata, and multipart content remain unchanged. When
    provider-native history is present and safely mappable via
    `native_indices`, the corresponding native messages are updated.
    Otherwise, native history
    is dropped and will be reconstructed on the next request.

    Args:
        session: Current session.
        index: Message index to modify (0-based; negative indices supported).
        content: New message content.
        config: Optional configuration used to resolve provider and plugins
            when updating native history.

    Returns:
        New Session with the modified message (immutable update).
    """
    return self._modify_single_message_with_native(
        session, index, content, config or {}, context=context
    )

patch_native_internal_metadata

patch_native_internal_metadata(native_messages, indices, patch)

Immutably merge patch into _metadata on selected native items.

Source code in agent_core/core.py
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
def patch_native_internal_metadata(
    self,
    native_messages: List[Dict[str, Any]],
    indices: List[int],
    patch: Dict[str, Any],
) -> List[Dict[str, Any]]:
    """Immutably merge ``patch`` into `_metadata` on selected native items."""

    if not indices or not isinstance(patch, dict) or not patch:
        return native_messages

    out: Optional[List[Dict[str, Any]]] = None
    for idx in sorted({i for i in indices if isinstance(i, int)}):
        if idx < 0 or idx >= len(native_messages):
            continue
        item = native_messages[idx]
        if not isinstance(item, dict):
            continue
        raw_internal = item.get("_metadata")
        internal = dict(raw_internal) if isinstance(raw_internal, dict) else {}
        merged_internal = {**internal, **patch}
        if merged_internal == internal:
            continue
        if out is None:
            out = list(native_messages)
        out[idx] = {**item, "_metadata": merged_internal}
    return out if out is not None else native_messages

rebuild_native_history

rebuild_native_history(session, config=None, *, start=None, end=None, context=None)

Rebuild provider-native history from the current core messages.

This helper converts the session's core messages to provider-native form using the configured provider, extensions, and features, then rebuilds the full core message sequence from that native history. When start/end are provided, only the visible message slice session.messages[start:end] is rebuilt back into native history before the canonical full core transcript is reconstructed.

Parameters:

Name Type Description Default
session Session

Current session.

required
config Optional[Dict[str, Any]]

Configuration used to resolve provider and plugins.

None
start Optional[int]

Optional inclusive visible-message start index for selective rebuild. Requires retained native history on the session.

None
end Optional[int]

Optional exclusive visible-message end index for selective rebuild. Requires retained native history on the session.

None

Returns:

Type Description
Session

New Session with native history rebuilt from core messages.

Source code in agent_core/core.py
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
def rebuild_native_history(
    self,
    session: Session,
    config: Optional[Dict[str, Any]] = None,
    *,
    start: Optional[int] = None,
    end: Optional[int] = None,
    context: Optional[Dict[str, Any]] = None,
) -> Session:
    """Rebuild provider-native history from the current core messages.

    This helper converts the session's core messages to provider-native
    form using the configured provider, extensions, and features, then
    rebuilds the full core message sequence from that native history. When
    ``start``/``end`` are provided, only the visible message slice
    ``session.messages[start:end]`` is rebuilt back into native history
    before the canonical full core transcript is reconstructed.

    Args:
        session: Current session.
        config: Configuration used to resolve provider and plugins.
        start: Optional inclusive visible-message start index for selective
            rebuild. Requires retained native history on the session.
        end: Optional exclusive visible-message end index for selective
            rebuild. Requires retained native history on the session.

    Returns:
        New Session with native history rebuilt from core messages.
    """

    if config is None:
        raise ValueError("config must be provided to rebuild native history")

    if not isinstance(config, dict):
        raise TypeError("config must be a dict when rebuilding native history")

    if start is not None or end is not None:
        message_count = len(session.messages)
        start_idx = 0 if start is None else start
        end_idx = message_count if end is None else end
        if (
            start_idx < 0
            or end_idx < 0
            or start_idx >= end_idx
            or end_idx > message_count
        ):
            raise ValueError(
                "start/end must select a non-empty visible message slice"
            )

        retained_native = None
        base_metadata: Dict[str, Any] = (
            dict(session.metadata) if isinstance(session.metadata, dict) else {}
        )
        rn = base_metadata.get("native_messages")
        if isinstance(rn, list):
            retained_native = rn

        if retained_native is None:
            raise RuntimeError(
                "selective rebuild requires retained native history on the session"
            )

        self._verify_native_integrity(session)

        target_messages = session.messages[start_idx:end_idx]
        target_native_indices: List[int] = []
        for message in target_messages:
            metadata = (
                message.metadata if isinstance(message.metadata, dict) else {}
            )
            native_indices = metadata.get("native_indices")
            if not isinstance(native_indices, list) or not native_indices:
                raise RuntimeError(
                    "selective rebuild requires native_indices for every selected message"
                )
            target_native_indices.extend(
                index for index in native_indices if isinstance(index, int)
            )

        if not target_native_indices:
            raise RuntimeError(
                "selected visible message slice maps to no native history"
            )

        unique_indices = sorted(set(target_native_indices))
        expected_indices = list(range(unique_indices[0], unique_indices[-1] + 1))
        if unique_indices != expected_indices:
            raise RuntimeError(
                "selected visible message slice does not map to a contiguous native slice"
            )

        replacement_core = [message.to_dict() for message in target_messages]
        replacement_native = self._core_messages_to_native_for_config(
            replacement_core,
            config,
            context=context,
        )

        before = retained_native[: unique_indices[0]]
        after = retained_native[unique_indices[-1] + 1 :]
        new_native = [*before, *replacement_native, *after]

        rebuilt_messages, post_init_native = self._rebuild_core_from_native(
            new_native, config, context=context
        )

        base_metadata["native_messages"] = post_init_native
        base_metadata["native_messages_integrity"] = self._compute_native_integrity(
            rebuilt_messages
        )

        return Session(
            session_id=session.session_id,
            messages=rebuilt_messages,
            metadata=base_metadata,
        )

    # Convert core messages to provider-native history.
    core_dicts: List[Dict[str, Any]] = [m.to_dict() for m in session.messages]
    new_native = self._core_messages_to_native_for_config(
        core_dicts,
        config,
        context=context,
    )

    # Rebuild canonical core messages from the new native history so that
    # provider/feature transformations and native_indices are normalized.
    # Use post-initialize native to capture any structural changes from features.
    rebuilt_messages, post_init_native = self._rebuild_core_from_native(
        new_native, config, context=context
    )

    new_metadata: Dict[str, Any] = (
        dict(session.metadata) if isinstance(session.metadata, dict) else {}
    )
    new_metadata["native_messages"] = post_init_native
    new_metadata["native_messages_integrity"] = self._compute_native_integrity(
        rebuilt_messages
    )

    return Session(
        session_id=session.session_id,
        messages=rebuilt_messages,
        metadata=new_metadata,
    )

register_feature

register_feature(plugin_class)

Register a feature plugin class.

Parameters:

Name Type Description Default
plugin_class type

Feature plugin class.

required
Source code in agent_core/core.py
596
597
598
599
600
601
602
603
604
def register_feature(self, plugin_class: type) -> None:
    """Register a feature plugin class.

    Args:
        plugin_class: Feature plugin class.
    """
    wrapper = FeatureWrapper(plugin_class)
    self._features.append(wrapper)
    self._reset_caches()

register_provider

register_provider(plugin_class, extensions=None)

Register provider plugin class with optional provider extensions.

Extensions are loaded by the provider wrapper (same language, hot path).

Parameters:

Name Type Description Default
plugin_class type

Provider plugin class.

required
extensions Optional[List[type]]

Optional list of provider extension classes to register with the provider.

None
Source code in agent_core/core.py
581
582
583
584
585
586
587
588
589
590
591
592
593
594
def register_provider(
    self, plugin_class: type, extensions: Optional[List[type]] = None
) -> None:
    """Register provider plugin class with optional provider extensions.

    Extensions are loaded by the provider wrapper (same language, hot path).

    Args:
        plugin_class: Provider plugin class.
        extensions: Optional list of provider extension classes to register with the provider.
    """
    wrapper = ProviderWrapper(plugin_class, extensions or [])
    self._providers = [*self._providers, wrapper]
    self._reset_caches()

register_tool

register_tool(plugin_class)

Register a tool plugin class.

Parameters:

Name Type Description Default
plugin_class type

Tool plugin class.

required
Source code in agent_core/core.py
606
607
608
609
610
611
612
613
614
def register_tool(self, plugin_class: type) -> None:
    """Register a tool plugin class.

    Args:
        plugin_class: Tool plugin class.
    """
    wrapper = ToolWrapper(plugin_class)
    self._tools.append(wrapper)
    self._reset_caches()

send_request

send_request(session, config, *, request_id=None, cancellation=None, context=None)

Send request and return a new session with the response.

Runs provider call + finalize with features operating on provider-native data; converts provider-native finals to core at the end and appends them to the session.

Parameters:

Name Type Description Default
session Session

Current session.

required
config Dict[str, Any]

Application-provided configuration for this request.

required

Returns:

Type Description
Session

Tuple of (new_session, final_core_messages) where the new session includes the

List[Dict[str, Any]]

appended final messages and retained provider-native history for this turn.

Raises:

Type Description
RuntimeError

If no provider is registered.

Source code in agent_core/core.py
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
def send_request(
    self,
    session: Session,
    config: Dict[str, Any],
    *,
    request_id: str | None = None,
    cancellation: Any | None = None,
    context: Optional[Dict[str, Any]] = None,
) -> Tuple[Session, List[Dict[str, Any]]]:
    """Send request and return a new session with the response.

    Runs provider call + finalize with features operating on provider-native data;
    converts provider-native finals to core at the end and appends them to the session.

    Args:
        session: Current session.
        config: Application-provided configuration for this request.

    Returns:
        Tuple of (new_session, final_core_messages) where the new session includes the
        appended final messages and retained provider-native history for this turn.

    Raises:
        RuntimeError: If no provider is registered.
    """
    if not self._providers:
        raise RuntimeError("No provider registered")

    provider, enabled_extensions, features, tools, _tags = (
        self._resolve_plugins_for_config(config)
    )

    features = sorted(features, key=lambda feat: getattr(feat, "priority", 100))

    logger.debug(
        "plugins_resolved_for_config",
        provider=provider.name,
        extensions=[ext.name for ext in enabled_extensions],
        features=[feat.name for feat in features],
        tools=[tool.name for tool in tools],
        tags=_tags,
    )

    provider.set_active_extensions(enabled_extensions)
    cancel_token: Any | None = None
    if request_id and cancellation is not None:
        try:
            cancel_token = cancellation.add_callback(
                lambda: provider.cancel_request(request_id)
            )
        except Exception:
            cancel_token = None

    try:
        messages, native_messages, state, native_history_changed = (
            self._pre_request(
                session,
                config,
                provider,
                features,
                tools,
                request_id=request_id,
                tags=_tags,
                models=self._get_models_for_config(provider, config),
                context=context,
            )
        )
        baseline_native_len = len(native_messages)
        request_context = self._build_request_context(
            config=state.get("config") or config,
            provider=provider,
            enabled_extensions=provider._iter_extensions(),
            enabled_features=features,
            enabled_tools=tools,
            tags=_tags,
            models=self._get_models_for_config(provider, config),
            available_tools=self.get_available_tools(config),
            tools=self._get_prepared_tools_for_config(config),
            session=session,
            request_id=request_id,
            stream=False,
            extra=context,
        )

        logger.debug(
            "sending request",
            native_messages=str(native_messages)[:1000],
            request=str(state.get("request"))[:1000],
        )

        _partials, final_native_1, native_messages, state = provider.call_api(
            native_messages,
            state,
            request_id=request_id,
        )
    finally:
        if cancellation is not None and cancel_token is not None:
            try:
                cancellation.remove_callback(cancel_token)
            except Exception:
                pass

    # Provider finalize returns provider-native finals and full native history
    # Provider-call facts (symmetric with the tool-call hooks): raw
    # finished timestamps, captured after the provider call completes.
    finalize_context: Dict[str, Any] = {
        **request_context,
        "finished_at": datetime.now(timezone.utc).isoformat(),
        "finished_at_mono": time.monotonic(),
    }
    final_native_2, native_messages, state = provider.finalize(
        native_messages,
        state,
        context=finalize_context,
    )

    # Combine provider-native finals from call_api and provider.finalize
    final_native = final_native_1 + final_native_2

    # Feature finalize chain over provider-native finals (native cold path)
    for feature in features:
        final_native, native_messages, state = feature.finalize(
            final_native,
            native_messages,
            state,
            context=finalize_context,
        )

    # Convert provider-native finals to core messages once finalization completes
    final_core = provider.from_native_messages(
        final_native,
        state,
        context=request_context,
    )
    # Apply extension and feature from-native transforms (iterate to pass state to each)
    for ext in enabled_extensions:
        final_core = ext.from_native_messages(
            final_native,
            final_core,
            state,
            context=request_context,
        )
    for feature in features:
        final_core = feature.from_native_messages(
            final_native,
            final_core,
            state,
            context=request_context,
        )

    # Attach global native_indices for final core messages
    final_core = self._normalize_final_core_with_native_indices(
        final_core,
        final_native,
        baseline_native_len,
    )

    final_core, native_messages, response_metadata_patch, _response_results = (
        self.execute_response_lifecycle_actions(
            session,
            config,
            "response_finalize",
            provider=provider,
            features=features,
            state=state,
            final_messages=final_core,
            native_messages=native_messages,
            native_final_messages=final_native,
            stream=False,
            turn_native_start_index=baseline_native_len,
            request_context=request_context,
            extra_context=context,
        )
    )
    state_metadata_patch = (
        state.get("session_metadata_patch")
        if isinstance(state.get("session_metadata_patch"), dict)
        else {}
    )
    if state_metadata_patch:
        response_metadata_patch = {
            **state_metadata_patch,
            **(response_metadata_patch or {}),
        }

    # Build new session messages by appending new Message objects
    new_metadata = dict(session.metadata)
    if response_metadata_patch:
        new_metadata.update(response_metadata_patch)
    # Persist full provider-native history for the turn (implementation detail)
    new_metadata["native_messages"] = native_messages
    if native_history_changed:
        all_messages_after, _ = self._rebuild_core_from_native(
            native_messages,
            config,
            context=context,
        )
    else:
        appended: List[Message] = [Message.from_dict(m) for m in final_core]
        all_messages_after = [*session.messages, *appended]
    new_metadata["native_messages_integrity"] = self._compute_native_integrity(
        all_messages_after
    )
    new_session = Session(session.session_id, all_messages_after, new_metadata)

    logger.info(
        "send_request_complete",
        final_native=final_native,
        final_core=final_core,
    )

    return new_session, final_core

send_request_stream

send_request_stream(session, config, *, request_id=None, cancellation=None, context=None)

Stream request and yield partial events, then the final session.

Uses provider streaming with optimized hot-path processing; features operate on the provider-native finals at finalize, then core converts once and appends to the session.

Parameters:

Name Type Description Default
session Session

Current session.

required
config Dict[str, Any]

Application-provided configuration for this request.

required

Yields:

Type Description
Dict[str, Any]

Event dictionaries:

Dict[str, Any]
  • {"type": "partial", "message": core-like partial dict}
Dict[str, Any]
  • {"type": "final", "session": new_session, "messages": final_core_messages}

Raises:

Type Description
RuntimeError

If no provider is registered.

Source code in agent_core/core.py
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
def send_request_stream(
    self,
    session: Session,
    config: Dict[str, Any],
    *,
    request_id: str | None = None,
    cancellation: Any | None = None,
    context: Optional[Dict[str, Any]] = None,
) -> Iterator[Dict[str, Any]]:
    """Stream request and yield partial events, then the final session.

    Uses provider streaming with optimized hot-path processing; features operate on the
    provider-native finals at finalize, then core converts once and appends to the session.

    Args:
        session: Current session.
        config: Application-provided configuration for this request.

    Yields:
        Event dictionaries:
        - {"type": "partial", "message": core-like partial dict}
        - {"type": "final", "session": new_session, "messages": final_core_messages}

    Raises:
        RuntimeError: If no provider is registered.
    """
    if not self._providers:
        raise RuntimeError("No provider registered")

    provider, enabled_extensions, features, tools, _tags = (
        self._resolve_plugins_for_config(config)
    )

    features = sorted(features, key=lambda feat: getattr(feat, "priority", 100))

    logger.debug(
        "plugins_resolved_for_config",
        provider=provider.name,
        extensions=[ext.name for ext in enabled_extensions],
        features=[feat.name for feat in features],
        tools=[tool.name for tool in tools],
        tags=_tags,
    )

    provider.set_active_extensions(enabled_extensions)
    cancel_token: Any | None = None
    if request_id and cancellation is not None:
        try:
            cancel_token = cancellation.add_callback(
                lambda: provider.cancel_request(request_id)
            )
        except Exception:
            cancel_token = None

    try:
        messages, native_messages, state, native_history_changed = (
            self._pre_request(
                session,
                config,
                provider,
                features,
                tools,
                request_id=request_id,
                tags=_tags,
                models=self._get_models_for_config(provider, config),
                context=context,
            )
        )
        baseline_native_len = len(native_messages)
        request_context = self._build_request_context(
            config=state.get("config") or config,
            provider=provider,
            enabled_extensions=provider._iter_extensions(),
            enabled_features=features,
            enabled_tools=tools,
            tags=_tags,
            models=self._get_models_for_config(provider, config),
            available_tools=self.get_available_tools(config),
            tools=self._get_prepared_tools_for_config(config),
            session=session,
            request_id=request_id,
            stream=True,
            extra=context,
        )

        logger.debug(
            "start streaming request",
            native_messages=str(native_messages)[:1000],
            requrest=str(state.get("request", None))[:1000],
        )

        aggregated_native_finals: List[Dict[str, Any]] = []

        # Stream from provider using optimized streaming
        partial_count = 0
        for event in provider.stream_messages(
            native_messages, state, request_id=request_id
        ):
            # logger.debug("streaming event received", _event=event) # the first positional argument is also named 'event', we cannot use that name
            if event["type"] == "partial":
                partial_count += 1
                log_chunk_processing.debug(
                    "partial message received", partial=event["message"]
                )
                yield {"type": "partial", "message": event["message"]}
            elif event["type"] == "final_messages":
                # These are provider-native finals
                log_chunk_processing.debug(
                    "final message received", final=event.get("messages")
                )
                aggregated_native_finals.extend(event["messages"])
    finally:
        if cancellation is not None and cancel_token is not None:
            try:
                cancellation.remove_callback(cancel_token)
            except Exception:
                pass

    # Finalize using the last accumulated native messages
    # Provider-call facts: raw finished timestamps after the provider
    # call completes (symmetric with the tool-call hooks).
    finalize_context: Dict[str, Any] = {
        **request_context,
        "finished_at": datetime.now(timezone.utc).isoformat(),
        "finished_at_mono": time.monotonic(),
    }
    final_native, native_messages, state = provider.finalize(
        provider.get_last_native_messages(),
        provider.get_state(),
        context=finalize_context,
    )

    combined_native_finals = [*aggregated_native_finals, *final_native]

    # Feature finalize chain (native)
    for feature in features:
        combined_native_finals, native_messages, state = feature.finalize(
            combined_native_finals,
            native_messages,
            state,
            context=finalize_context,
        )

    logger.debug(
        "streaming complete", combined_native_finals=combined_native_finals
    )

    # Convert provider-native finals to core messages
    final_core = provider.from_native_messages(
        combined_native_finals,
        state,
        context=request_context,
    )

    # Apply extension and feature from-native transforms (iterate to pass state to each)
    for ext in enabled_extensions:
        final_core = ext.from_native_messages(
            combined_native_finals,
            final_core,
            state,
            context=request_context,
        )
    for feature in features:
        final_core = feature.from_native_messages(
            combined_native_finals,
            final_core,
            state,
            context=request_context,
        )

    # Attach global native_indices for final core messages
    final_core = self._normalize_final_core_with_native_indices(
        final_core,
        combined_native_finals,
        baseline_native_len,
    )

    final_core, native_messages, response_metadata_patch, _response_results = (
        self.execute_response_lifecycle_actions(
            session,
            config,
            "response_finalize",
            provider=provider,
            features=features,
            state=state,
            final_messages=final_core,
            native_messages=native_messages,
            native_final_messages=combined_native_finals,
            stream=True,
            turn_native_start_index=baseline_native_len,
            request_context=request_context,
            extra_context=context,
        )
    )
    state_metadata_patch = (
        state.get("session_metadata_patch")
        if isinstance(state.get("session_metadata_patch"), dict)
        else {}
    )
    if state_metadata_patch:
        response_metadata_patch = {
            **state_metadata_patch,
            **(response_metadata_patch or {}),
        }

    new_metadata = dict(session.metadata)
    if response_metadata_patch:
        new_metadata.update(response_metadata_patch)
    new_metadata["native_messages"] = native_messages
    if native_history_changed:
        # Rebuild core from the post-initialize native (after structural changes)
        all_messages_after, _ = self._rebuild_core_from_native(
            native_messages,
            config,
            context=context,
        )
    else:
        appended: List[Message] = [Message.from_dict(m) for m in final_core]
        all_messages_after = [*session.messages, *appended]
    new_metadata["native_messages_integrity"] = self._compute_native_integrity(
        all_messages_after
    )
    new_session = Session(session.session_id, all_messages_after, new_metadata)

    logger.debug("streaming request complete", final_message=final_core)

    yield {"type": "final", "session": new_session, "messages": final_core}

send_request_stream_async async

send_request_stream_async(session, config, *, request_id=None, cancellation=None, context=None)

Async version of send_request_stream.

Parameters:

Name Type Description Default
session Session

Current session.

required
config Dict[str, Any]

Application-provided configuration for this request.

required

Yields:

Type Description
AsyncIterator[Dict[str, Any]]

Event dictionaries analogous to send_request_stream, but from an async iterator.

Raises:

Type Description
RuntimeError

If no provider is registered.

Source code in agent_core/core.py
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
async def send_request_stream_async(
    self,
    session: Session,
    config: Dict[str, Any],
    *,
    request_id: str | None = None,
    cancellation: Any | None = None,
    context: Optional[Dict[str, Any]] = None,
) -> AsyncIterator[Dict[str, Any]]:
    """Async version of send_request_stream.

    Args:
        session: Current session.
        config: Application-provided configuration for this request.

    Yields:
        Event dictionaries analogous to send_request_stream, but from an async iterator.

    Raises:
        RuntimeError: If no provider is registered.
    """
    if not self._providers:
        raise RuntimeError("No provider registered")
    provider, enabled_extensions, features, tools, _tags = (
        self._resolve_plugins_for_config(config)
    )

    features = sorted(features, key=lambda feat: getattr(feat, "priority", 100))

    logger.debug(
        "plugins_resolved_for_config",
        provider=provider.name,
        extensions=[ext.name for ext in enabled_extensions],
        features=[feat.name for feat in features],
        tools=[tool.name for tool in tools],
        tags=_tags,
    )

    provider.set_active_extensions(enabled_extensions)
    cancel_token: Any | None = None
    if request_id and cancellation is not None:
        try:
            cancel_token = cancellation.add_callback(
                lambda: provider.cancel_request(request_id)
            )
        except Exception:
            cancel_token = None

    try:
        messages, native_messages, state, native_history_changed = (
            self._pre_request(
                session,
                config,
                provider,
                features,
                tools,
                request_id=request_id,
                tags=_tags,
                models=self._get_models_for_config(provider, config),
                context=context,
            )
        )
        baseline_native_len = len(native_messages)
        request_context = self._build_request_context(
            config=state.get("config") or config,
            provider=provider,
            enabled_extensions=provider._iter_extensions(),
            enabled_features=features,
            enabled_tools=tools,
            tags=_tags,
            models=self._get_models_for_config(provider, config),
            available_tools=self.get_available_tools(config),
            tools=self._get_prepared_tools_for_config(config),
            session=session,
            request_id=request_id,
            stream=True,
            extra=context,
        )

        aggregated_native_finals: List[Dict[str, Any]] = []

        # Stream from provider (async) using optimized streaming
        async for event in provider.stream_messages_async(
            native_messages,
            state,
            request_id=request_id,
        ):
            if event["type"] == "partial":
                yield {"type": "partial", "message": event["message"]}
            elif event["type"] == "final_messages":
                aggregated_native_finals.extend(event["messages"])  # native finals
    finally:
        if cancellation is not None and cancel_token is not None:
            try:
                cancellation.remove_callback(cancel_token)
            except Exception:
                pass

    # Provider-call facts: raw finished timestamps after the provider
    # call completes (symmetric with the tool-call hooks).
    finalize_context: Dict[str, Any] = {
        **request_context,
        "finished_at": datetime.now(timezone.utc).isoformat(),
        "finished_at_mono": time.monotonic(),
    }
    final_native, native_messages, state = provider.finalize(
        provider.get_last_native_messages(),
        provider.get_state(),
        context=finalize_context,
    )

    combined_native_finals = [*aggregated_native_finals, *final_native]

    # Feature finalize chain (native)
    for feature in features:
        combined_native_finals, native_messages, state = feature.finalize(
            combined_native_finals,
            native_messages,
            state,
            context=finalize_context,
        )

    # Convert provider-native finals to core messages
    final_core = provider.from_native_messages(
        combined_native_finals,
        state,
        context=request_context,
    )

    # Apply extension and feature from-native transforms (iterate to pass state to each)
    for ext in enabled_extensions:
        final_core = ext.from_native_messages(
            combined_native_finals,
            final_core,
            state,
            context=request_context,
        )
    for feature in features:
        final_core = feature.from_native_messages(
            combined_native_finals,
            final_core,
            state,
            context=request_context,
        )

    # Attach global native_indices for final core messages
    final_core = self._normalize_final_core_with_native_indices(
        final_core,
        combined_native_finals,
        baseline_native_len,
    )

    final_core, native_messages, response_metadata_patch, _response_results = (
        self.execute_response_lifecycle_actions(
            session,
            config,
            "response_finalize",
            provider=provider,
            features=features,
            state=state,
            final_messages=final_core,
            native_messages=native_messages,
            native_final_messages=combined_native_finals,
            stream=True,
            turn_native_start_index=baseline_native_len,
            request_context=request_context,
            extra_context=context,
        )
    )
    state_metadata_patch = (
        state.get("session_metadata_patch")
        if isinstance(state.get("session_metadata_patch"), dict)
        else {}
    )
    if state_metadata_patch:
        response_metadata_patch = {
            **state_metadata_patch,
            **(response_metadata_patch or {}),
        }

    new_metadata = dict(session.metadata)
    if response_metadata_patch:
        new_metadata.update(response_metadata_patch)
    new_metadata["native_messages"] = native_messages
    if native_history_changed:
        # Rebuild core from the post-initialize native (after structural changes)
        all_messages_after, _ = self._rebuild_core_from_native(
            native_messages,
            config,
            context=context,
        )
    else:
        appended: List[Message] = [Message.from_dict(m) for m in final_core]
        all_messages_after = [*session.messages, *appended]
    new_metadata["native_messages_integrity"] = self._compute_native_integrity(
        all_messages_after
    )
    new_session = Session(session.session_id, all_messages_after, new_metadata)

    yield {"type": "final", "session": new_session, "messages": final_core}

session_action_mutates

session_action_mutates(config, plugin_id, action_id)

Return whether a session action uses the mutating session path.

Source code in agent_core/core.py
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
def session_action_mutates(
    self,
    config: Dict[str, Any],
    plugin_id: str,
    action_id: str,
) -> bool:
    """Return whether a session action uses the mutating session path."""

    if not isinstance(config, dict):
        raise TypeError("config must be a dict")
    if not isinstance(plugin_id, str) or not plugin_id:
        raise ValueError("plugin_id must be a non-empty string")
    if not isinstance(action_id, str) or not action_id:
        raise ValueError("action_id must be a non-empty string")

    action_def = self._find_session_action_definition(
        self.get_session_actions(config),
        plugin_id,
        action_id,
    )
    if action_def is None:
        raise KeyError(
            f"Unknown session action {action_id!r} for plugin {plugin_id!r}"
        )
    return action_def.get("mutates_session") is not False

slice_session

slice_session(session, config=None, *, start=None, end=None, remove_indices=None, return_removed=False)

Return a new session with messages sliced/removed.

Operations are expressed in core message indices but, when possible, provider-native history is adjusted consistently and preserved.

Source code in agent_core/core.py
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
def slice_session(
    self,
    session: Session,
    config: Optional[Dict[str, Any]] = None,
    *,
    start: Optional[int] = None,
    end: Optional[int] = None,
    remove_indices: Optional[List[int]] = None,
    return_removed: bool = False,
) -> Session:
    """Return a new session with messages sliced/removed.

    Operations are expressed in core message indices but, when possible,
    provider-native history is adjusted consistently and preserved.
    """
    messages = session.messages
    message_count = len(messages)
    all_indices: Set[int] = set(range(message_count))

    def _normalize_bound(bound: Optional[int], default: int) -> int:
        if bound is None:
            return default
        value = bound
        if value < 0:
            value = message_count + value
        if value < 0:
            return 0
        if value > message_count:
            return message_count
        return value

    start_idx = _normalize_bound(start, 0)
    end_idx = _normalize_bound(end, message_count)

    range_indices: Optional[Set[int]] = None
    if start is not None or end is not None:
        if start_idx >= end_idx:
            range_indices = set()
        else:
            range_indices = set(range(start_idx, end_idx))

    remove_set: Set[int] = set()
    if remove_indices:
        for idx in remove_indices:
            if not isinstance(idx, int):
                continue
            value = idx
            if value < 0:
                value = message_count + value
            if 0 <= value < message_count:
                remove_set.add(value)

    if range_indices is not None:
        keep_set: Set[int] = range_indices.difference(remove_set)
    else:
        keep_set = all_indices.difference(remove_set)

    remove_set: Set[int] = all_indices.difference(keep_set)

    if keep_set == all_indices:
        if not return_removed:
            return session
        # No messages removed; return an empty complement session that
        # mirrors the original metadata shape but without native history.
        empty = self._slice_session_core_only(session, set())
        return (session, empty)  # type: ignore[return-value]

    if (
        config is None
        or not isinstance(session.metadata, dict)
        or len(self._providers) != 1
    ):
        kept = self._slice_session_core_only(session, keep_set)
        if not return_removed:
            return kept
        removed = self._slice_session_core_only(session, remove_set)
        return (kept, removed)  # type: ignore[return-value]

    original_native = session.metadata.get("native_messages")
    if not isinstance(original_native, list):
        kept = self._slice_session_core_only(session, keep_set)
        if not return_removed:
            return kept
        removed = self._slice_session_core_only(session, remove_set)
        return (kept, removed)  # type: ignore[return-value]

    try:
        self._verify_native_integrity(session)
    except Exception:
        kept = self._slice_session_core_only(session, keep_set)
        if not return_removed:
            return kept
        removed = self._slice_session_core_only(session, remove_set)
        return (kept, removed)  # type: ignore[return-value]

    native_len = len(original_native)

    core_to_native: Dict[int, List[int]] = {}
    native_to_core: Dict[int, Set[int]] = {}

    for idx, msg in enumerate(messages):
        md = msg.metadata if isinstance(msg.metadata, dict) else {}
        native_indices = md.get("native_indices")
        if native_indices is None:
            continue
        if not isinstance(native_indices, list) or not all(
            isinstance(j, int) for j in native_indices
        ):
            kept = self._slice_session_core_only(session, keep_set)
            if not return_removed:
                return kept
            removed = self._slice_session_core_only(session, remove_set)
            return (kept, removed)  # type: ignore[return-value]
        normalized_indices: List[int] = []
        for j in native_indices:
            if j < 0 or j >= native_len:
                kept = self._slice_session_core_only(session, keep_set)
                if not return_removed:
                    return kept
                removed = self._slice_session_core_only(session, remove_set)
                return (kept, removed)  # type: ignore[return-value]
            if j not in normalized_indices:
                normalized_indices.append(j)
        if not normalized_indices:
            continue
        core_to_native[idx] = normalized_indices
        for j in normalized_indices:
            owners = native_to_core.get(j)
            if owners is None:
                native_to_core[j] = {idx}
            else:
                owners.add(idx)

    for idx in keep_set:
        if idx not in core_to_native:
            kept = self._slice_session_core_only(session, keep_set)
            if not return_removed:
                return kept
            removed = self._slice_session_core_only(session, remove_set)
            return (kept, removed)  # type: ignore[return-value]

    # Build native subsets for kept and removed halves in one pass so we
    # can support split-like operations without duplicating logic.
    native_candidates_keep: Set[int] = set()
    native_candidates_remove: Set[int] = set()
    for idx in keep_set:
        for j in core_to_native.get(idx, []):
            native_candidates_keep.add(j)
    for idx in remove_set:
        for j in core_to_native.get(idx, []):
            native_candidates_remove.add(j)

    if not native_candidates_keep:
        new_native_keep: List[Dict[str, Any]] = []
    else:
        final_native_indices_keep = {
            j
            for j in native_candidates_keep
            if native_to_core.get(j, set()).issubset(keep_set)
        }
        sorted_keep = sorted(final_native_indices_keep)
        new_native_keep = [original_native[j] for j in sorted_keep]

    if not native_candidates_remove:
        new_native_remove: List[Dict[str, Any]] = []
    else:
        final_native_indices_remove = {
            j
            for j in native_candidates_remove
            if native_to_core.get(j, set()).issubset(remove_set)
        }
        sorted_remove = sorted(final_native_indices_remove)
        new_native_remove = [original_native[j] for j in sorted_remove]

    try:
        # Skip initialize_request for session split operations.
        # This prevents features like SystemMessageFeature from adding
        # synthetic messages to partial sessions during split, which
        # would cause duplicates when the sessions are joined back.
        new_messages_keep, post_init_keep = self._rebuild_core_from_native(
            new_native_keep, config, skip_initialize=True
        )
        if new_native_remove:
            new_messages_remove, post_init_remove = self._rebuild_core_from_native(
                new_native_remove, config, skip_initialize=True
            )
        else:
            new_messages_remove = []
            post_init_remove = []
    except Exception:
        kept = self._slice_session_core_only(session, keep_set)
        if not return_removed:
            return kept
        removed = self._slice_session_core_only(session, remove_set)
        return (kept, removed)  # type: ignore[return-value]

    new_metadata_keep = dict(session.metadata)
    new_metadata_keep["native_messages"] = post_init_keep
    new_metadata_keep["native_messages_integrity"] = self._compute_native_integrity(
        new_messages_keep
    )

    kept_session = Session(
        session_id=session.session_id,
        messages=new_messages_keep,
        metadata=new_metadata_keep,
    )

    if not return_removed:
        return kept_session

    new_metadata_remove = dict(session.metadata)
    new_metadata_remove["native_messages"] = post_init_remove
    new_metadata_remove["native_messages_integrity"] = (
        self._compute_native_integrity(new_messages_remove)
    )

    removed_session = Session(
        session_id=session.session_id,
        messages=new_messages_remove,
        metadata=new_metadata_remove,
    )

    return (kept_session, removed_session)  # type: ignore[return-value]

stream_tool_call

stream_tool_call(tool_call, config, *, context=None)

Stream partial results for a single tool call.

Uses the same tool resolution logic as :meth:execute_tool_calls but invokes the optional :meth:ToolPlugin.stream_tool hook instead of the synchronous execute/format path. If no tool provides streaming for the given call, yields nothing.

Parameters:

Name Type Description Default
tool_call Dict[str, Any]

Tool call dictionary to execute.

required
config Dict[str, Any]

Current resolved request configuration.

required
context Optional[Dict[str, Any]]

Optional context for tool execution. Layer 1 context (core, config, trigger_source) is enriched by this method if not already present.

None
Source code in agent_core/core.py
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
def stream_tool_call(
    self,
    tool_call: Dict[str, Any],
    config: Dict[str, Any],
    *,
    context: Optional[Dict[str, Any]] = None,
) -> Iterator[Dict[str, Any]]:
    """Stream partial results for a single tool call.

    Uses the same tool resolution logic as :meth:`execute_tool_calls` but
    invokes the optional :meth:`ToolPlugin.stream_tool` hook instead of the
    synchronous execute/format path. If no tool provides streaming for the
    given call, yields nothing.

    Args:
        tool_call: Tool call dictionary to execute.
        config: Current resolved request configuration.
        context: Optional context for tool execution. Layer 1 context (core,
            config, trigger_source) is enriched by this method if not already
            present.
    """
    if not self._tools:
        return

    provider, extensions, tool_states = self._get_enabled_tool_states_for_config(
        config
    )
    registry = self._get_tool_interop_registry_for_config(
        config,
        provider=provider,
        extensions=extensions,
        tool_states=tool_states,
    )
    try:
        inspected_call = registry.inspect_call(tool_call)
    except Exception:
        return

    tool, state, prepared, _schema = self._resolve_tool_handler_for_call(
        inspected_call,
        tool_states,
        registry,
    )
    if tool is None or state is None:
        return

    # Layer 1: Core-level context enrichment.
    tool_context = self._build_tool_runtime_context(config, context)

    try:
        iterator = tool.stream_tool(
            inspected_call.tool_name,
            inspected_call.payload,
            state,
            payload_kind=inspected_call.payload_kind,
            payload_format=inspected_call.payload_format,
            payload_metadata=inspected_call.payload_metadata,
            tool_call=inspected_call.raw,
            context=tool_context,
            prepared=prepared,
        )
        iterator = iter(iterator)
    except Exception:
        return
    for chunk in iterator:
        if isinstance(chunk, dict):
            yield chunk