Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,7 @@ cython_debug/
.vscode/

# Binary files
bin/
bin/

# Claude
.claude/
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@
AgenticUserAuthorization,
)

# Proactive
from .proactive import (
Conversation,
ConversationBuilder,
ConversationReferenceBuilder,
CreateConversationOptions,
Proactive,
ProactiveOptions,
)

# App State
from .state.conversation_state import ConversationState
from .state.state import State, StatePropertyAccessor, state
Expand All @@ -47,4 +57,11 @@
"Authorization",
"AuthHandler",
"AgenticUserAuthorization",
# Proactive
"Conversation",
"ConversationBuilder",
"ConversationReferenceBuilder",
"CreateConversationOptions",
"Proactive",
"ProactiveOptions",
]
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@

from ._type_defs import RouteHandler, RouteSelector
from ._routes import _RouteList, _Route, RouteRank, _agentic_selector
from .proactive import Proactive, ProactiveOptions

logger = logging.getLogger(__name__)

Expand All @@ -69,6 +70,7 @@ class AgentApplication(Agent, Generic[StateT]):
_options: ApplicationOptions
_adapter: Optional[ChannelServiceAdapter] = None
_auth: Optional[Authorization] = None
_proactive: Optional[Proactive] = None
Comment thread
axelsrz marked this conversation as resolved.
_internal_before_turn: list[Callable[[TurnContext, StateT], Awaitable[bool]]] = []
_internal_after_turn: list[Callable[[TurnContext, StateT], Awaitable[bool]]] = []
_route_list: _RouteList[StateT] = _RouteList[StateT]()
Expand Down Expand Up @@ -147,6 +149,12 @@ def __init__(
or partial(TurnState.with_storage, self._options.storage)
)

if options.proactive:
proactive_opts = copy(options.proactive)
if not proactive_opts.storage:
proactive_opts.storage = self._options.storage
self._proactive = Proactive(self, proactive_opts)

Comment thread
axelsrz marked this conversation as resolved.
# TODO: decide how to initialize the Authorization (params vs options vs kwargs)
if authorization:
self._auth = authorization
Expand Down Expand Up @@ -216,6 +224,26 @@ def options(self) -> ApplicationOptions:
"""
return self._options

@property
def proactive(self) -> Proactive:
"""
The application's proactive messaging manager.

:return: The proactive messaging manager.
:rtype: :class:`microsoft_agents.hosting.core.app.proactive.proactive.Proactive`
:raises ApplicationError: If proactive options were not configured.
"""
if not self._proactive:
logger.error(
"AgentApplication.proactive(): proactive options are not configured.",
stack_info=True,
)
raise ApplicationError("""
The `AgentApplication.proactive` property is unavailable because
no ProactiveOptions were configured in ApplicationOptions.
""")
Comment thread
axelsrz marked this conversation as resolved.
return self._proactive

def add_route(
self,
selector: RouteSelector,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from ..channel_service_adapter import ChannelServiceAdapter

from .state.turn_state import TurnState
from .proactive.proactive_options import ProactiveOptions

# from .teams_adapter import TeamsAdapter

Expand Down Expand Up @@ -89,3 +90,10 @@ class ApplicationOptions:
Optional. Authorization handler for OAuth flows.
If not provided, no OAuth flows will be supported.
"""

proactive: Optional[ProactiveOptions] = None
"""
Optional. Options for the proactive messaging subsystem.
When set, :attr:`AgentApplication.proactive` is available for storing
conversations and initiating proactive turns.
"""
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
"""

from .conversation import Conversation
from .conversation_builder import ConversationBuilder
from .conversation_reference_builder import ConversationReferenceBuilder
from .create_conversation_options import CreateConversationOptions
from .proactive import Proactive
from .proactive_options import ProactiveOptions

__all__ = [
"Conversation",
"ConversationBuilder",
"ConversationReferenceBuilder",
"CreateConversationOptions",
"Proactive",
"ProactiveOptions",
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
"""
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
"""

from __future__ import annotations

from typing import Optional, TYPE_CHECKING

from microsoft_agents.activity import ConversationReference
from microsoft_agents.hosting.core.authorization import ClaimsIdentity
from microsoft_agents.hosting.core.storage.store_item import StoreItem

if TYPE_CHECKING:
from microsoft_agents.hosting.core.turn_context import TurnContext
from microsoft_agents.hosting.core.channel_adapter import ChannelAdapter

# JWT claim keys that are persisted alongside a ConversationReference.
_PERSISTED_CLAIM_KEYS = frozenset({"aud", "azp", "appid", "idtyp", "ver", "iss", "tid"})


class Conversation(StoreItem):
"""
Bundles a :class:`~microsoft_agents.activity.ConversationReference` together
with a filtered set of JWT claims so that a proactive continuation can be
performed without holding onto the full :class:`~microsoft_agents.hosting.core.authorization.ClaimsIdentity`.

Instances are typically created via
:meth:`~microsoft_agents.hosting.core.app.proactive.conversation_builder.ConversationBuilder`
or via :meth:`from_turn_context`.

:param claims: Filtered JWT claims (``aud``, ``azp``, ``appid``, ``idtyp``,
``ver``, ``iss``, ``tid``). May be a raw ``dict`` or a
:class:`~microsoft_agents.hosting.core.authorization.ClaimsIdentity`.
:type claims: dict[str, str] or ClaimsIdentity
:param conversation_reference: The conversation reference.
:type conversation_reference: :class:`~microsoft_agents.activity.ConversationReference`
"""

def __init__(
self,
claims: "dict[str, str] | ClaimsIdentity",
conversation_reference: ConversationReference,
) -> None:
if isinstance(claims, ClaimsIdentity):
self.claims: dict[str, str] = Conversation.claims_from_identity(claims)
else:
self.claims = {
k: v for k, v in claims.items() if k in _PERSISTED_CLAIM_KEYS
}
self.conversation_reference: ConversationReference = conversation_reference

# ------------------------------------------------------------------
# Factory helpers
# ------------------------------------------------------------------

@classmethod
def from_turn_context(cls, context: "TurnContext") -> "Conversation":
"""
Create a :class:`Conversation` from the current turn context.

:param context: The active turn context.
:type context: :class:`~microsoft_agents.hosting.core.turn_context.TurnContext`
:return: A new :class:`Conversation` capturing the current turn's identity
and conversation reference.
:rtype: :class:`Conversation`
"""
from microsoft_agents.hosting.core.channel_adapter import ChannelAdapter

identity: Optional[ClaimsIdentity] = context.turn_state.get(
ChannelAdapter.AGENT_IDENTITY_KEY
)
reference = context.activity.get_conversation_reference()
return cls(identity or {}, reference)

# ------------------------------------------------------------------
# Claims helpers
# ------------------------------------------------------------------

@staticmethod
def claims_from_identity(identity: ClaimsIdentity) -> "dict[str, str]":
"""
Return the subset of claims from *identity* that are relevant for proactive
messaging (``aud``, ``azp``, ``appid``, ``idtyp``, ``ver``, ``iss``, ``tid``).

:param identity: The full claims identity.
:type identity: :class:`~microsoft_agents.hosting.core.authorization.ClaimsIdentity`
:return: Filtered claims dictionary.
:rtype: dict[str, str]
"""
return {k: v for k, v in identity.claims.items() if k in _PERSISTED_CLAIM_KEYS}

@staticmethod
def identity_from_claims(claims: "dict[str, str]") -> ClaimsIdentity:
"""
Reconstruct a :class:`~microsoft_agents.hosting.core.authorization.ClaimsIdentity`
from a previously persisted claims dict.

:param claims: Filtered claims dictionary (as produced by :meth:`claims_from_identity`).
:type claims: dict[str, str]
:return: Reconstituted claims identity.
:rtype: :class:`~microsoft_agents.hosting.core.authorization.ClaimsIdentity`
"""
return ClaimsIdentity(claims=dict(claims), is_authenticated=True)

# ------------------------------------------------------------------
# Validation
# ------------------------------------------------------------------

def validate(self) -> None:
"""
Raise :exc:`ValueError` if required fields are missing.

:raises ValueError: If ``conversation_reference``, its nested
``conversation``, or ``service_url`` are absent.
"""
if not self.conversation_reference:
raise ValueError("Conversation.conversation_reference is required.")
if not self.conversation_reference.conversation:
raise ValueError(
"Conversation.conversation_reference.conversation is required."
Comment thread
axelsrz marked this conversation as resolved.
)
if not self.conversation_reference.conversation.id:
raise ValueError(
"Conversation.conversation_reference.conversation.id is required."
)
if not self.conversation_reference.service_url:
raise ValueError(
"Conversation.conversation_reference.service_url is required."
)
Comment thread
axelsrz marked this conversation as resolved.

# ------------------------------------------------------------------
# StoreItem serialization
# ------------------------------------------------------------------

def store_item_to_json(self) -> dict:
return {
"claims": self.claims,
"conversation_reference": self.conversation_reference.model_dump(
mode="json", by_alias=True, exclude_unset=True
),
}

@staticmethod
def from_json_to_store_item(json_data: dict) -> "Conversation":
reference = ConversationReference.model_validate(
json_data.get("conversation_reference", {})
)
return Conversation(
claims=json_data.get("claims", {}),
conversation_reference=reference,
)
Loading
Loading