temporalio-microsoft-agent-framework 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,221 @@
1
+ """Workflow-aware stand-ins for what Agent Framework reads from the stdlib in agent code.
2
+
3
+ Agent Framework has no time, id or thread provider hook. Its modules import
4
+ ``uuid4``, ``perf_counter``, ``time`` and ``asyncio`` as module-local names,
5
+ and those modules pass through the workflow sandbox, so the plugin rebinds
6
+ the names on the module objects. Every stand-in checks
7
+ ``workflow.in_workflow()`` and falls through to the stdlib elsewhere, so
8
+ Activities and plain Agent Framework code in the same worker keep their
9
+ normal clocks, ids and threads.
10
+
11
+ What each seam feeds:
12
+
13
+ - ``_agents.uuid4``: the default ``Agent.id``.
14
+ - ``_tools.uuid4``: function-call occurrence ids a provider omitted, and
15
+ replacement approval request ids.
16
+ - ``_sessions.uuid``: the default ``AgentSession.session_id``.
17
+ - ``_tools.perf_counter`` and ``_tools.time``: the ``max_duration_seconds``
18
+ budget of the function-invocation loop, which decides whether the loop
19
+ keeps calling tools.
20
+ - ``_tools.asyncio``: ``to_thread``, which runs a synchronous tool. The
21
+ workflow event loop has no executor, so in a workflow the tool runs inline
22
+ on the workflow task; the tool object is not changed, so one shared with an
23
+ Activity or a plain agent in the same process still runs on a thread there.
24
+ - ``_sessions.asyncio``: ``to_thread``, which the file-backed session store
25
+ and history provider use for their file reads and writes. In a workflow it
26
+ raises ``MicrosoftAgentFrameworkWorkflowError`` naming the call, so the run
27
+ fails instead of the workflow task failing on the loop's
28
+ ``NotImplementedError``.
29
+ - ``observability.perf_counter``: span durations of the agent telemetry layer.
30
+
31
+ ``time_ns`` in the same modules only timestamps exceptions on spans, which
32
+ the tracer records in wall time anyway, so it is left alone.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import asyncio
38
+ import importlib
39
+ import importlib.metadata
40
+ import inspect
41
+ import logging
42
+ import threading
43
+ import time
44
+ import uuid
45
+ from collections.abc import Callable
46
+ from typing import Any
47
+
48
+ from temporalio import workflow
49
+ from temporalio.microsoft_agent_framework.workflow import (
50
+ MicrosoftAgentFrameworkWorkflowError,
51
+ )
52
+
53
+ TESTED_VERSIONS = "1.23.0 through 1.24.0"
54
+ """The ``agent-framework-core`` range the suite runs on: from the floor the plugin was first
55
+ tested on through the version ``uv.lock`` pins, which CI runs on every change. A test keeps the
56
+ upper bound equal to the lock, so a lock bump moves this string and the README sentence with it."""
57
+
58
+ logger = logging.getLogger(__name__)
59
+
60
+ _MISSING = object()
61
+
62
+
63
+ def _uuid4() -> uuid.UUID:
64
+ return workflow.uuid4() if workflow.in_workflow() else uuid.uuid4()
65
+
66
+
67
+ def _perf_counter() -> float:
68
+ return workflow.time() if workflow.in_workflow() else time.perf_counter()
69
+
70
+
71
+ def _time() -> float:
72
+ return workflow.time() if workflow.in_workflow() else time.time()
73
+
74
+
75
+ async def _to_thread(func: Callable[..., Any], /, *args: Any, **kwargs: Any) -> Any:
76
+ if workflow.in_workflow():
77
+ return func(*args, **kwargs)
78
+ return await asyncio.to_thread(func, *args, **kwargs)
79
+
80
+
81
+ async def _no_thread_in_workflow(
82
+ func: Callable[..., Any], /, *args: Any, **kwargs: Any
83
+ ) -> Any:
84
+ if workflow.in_workflow():
85
+ name = getattr(func, "__qualname__", repr(func))
86
+ raise MicrosoftAgentFrameworkWorkflowError(
87
+ f"Agent Framework tried to run {name} on a thread inside a workflow, "
88
+ "which has none. File-backed session stores and history providers "
89
+ "(FileSessionStore, FileHistoryProvider) do not work in a workflow; "
90
+ "use the default in-memory history and carry session.to_dict() across "
91
+ "continue-as-new."
92
+ )
93
+ return await asyncio.to_thread(func, *args, **kwargs)
94
+
95
+
96
+ class _UuidModule:
97
+ """Stands in for the ``uuid`` module where a module imported it whole."""
98
+
99
+ uuid4 = staticmethod(_uuid4)
100
+
101
+ def __getattr__(self, name: str) -> Any:
102
+ return getattr(uuid, name)
103
+
104
+
105
+ class _AsyncioModule:
106
+ """Stands in for the ``asyncio`` module in the framework's tool module."""
107
+
108
+ to_thread = staticmethod(_to_thread)
109
+
110
+ def __getattr__(self, name: str) -> Any:
111
+ return getattr(asyncio, name)
112
+
113
+
114
+ class _SessionsAsyncioModule:
115
+ """Stands in for the ``asyncio`` module in the framework's sessions module."""
116
+
117
+ to_thread = staticmethod(_no_thread_in_workflow)
118
+
119
+ def __getattr__(self, name: str) -> Any:
120
+ return getattr(asyncio, name)
121
+
122
+
123
+ _uuid_module = _UuidModule()
124
+ _asyncio_module = _AsyncioModule()
125
+ _sessions_asyncio_module = _SessionsAsyncioModule()
126
+
127
+ # (module, attribute, the stdlib object the attribute holds, the stand-in)
128
+ _SEAMS: tuple[tuple[str, str, Any, Any], ...] = (
129
+ ("agent_framework._agents", "uuid4", uuid.uuid4, _uuid4),
130
+ ("agent_framework._tools", "uuid4", uuid.uuid4, _uuid4),
131
+ ("agent_framework._sessions", "uuid", uuid, _uuid_module),
132
+ ("agent_framework._sessions", "asyncio", asyncio, _sessions_asyncio_module),
133
+ ("agent_framework._tools", "perf_counter", time.perf_counter, _perf_counter),
134
+ ("agent_framework._tools", "time", time.time, _time),
135
+ ("agent_framework._tools", "asyncio", asyncio, _asyncio_module),
136
+ ("agent_framework.observability", "perf_counter", time.perf_counter, _perf_counter),
137
+ )
138
+
139
+ _install_lock = threading.Lock()
140
+
141
+
142
+ def installed_version() -> str:
143
+ """Return the installed ``agent-framework-core`` version for error messages."""
144
+ try:
145
+ return importlib.metadata.version("agent-framework-core")
146
+ except importlib.metadata.PackageNotFoundError:
147
+ return "unknown"
148
+
149
+
150
+ def _unsupported(seam: str, detail: str) -> RuntimeError:
151
+ return RuntimeError(
152
+ f"agent-framework-core {installed_version()} changed {seam}: {detail}. "
153
+ "The Temporal plugin cannot make this seam replay-safe; pin "
154
+ f"agent-framework-core to a release the plugin was tested with "
155
+ f"({TESTED_VERSIONS})."
156
+ )
157
+
158
+
159
+ def check_sync_tool_seam() -> None:
160
+ """Fail unless ``FunctionTool`` still hands a synchronous tool to ``asyncio.to_thread``.
161
+
162
+ That call, through the tool module's ``asyncio`` name, is what the
163
+ ``_tools.asyncio`` stand-in intercepts. The framework's own harness flips
164
+ the private ``_invoke_sync_on_event_loop`` switch on the tool instead; the
165
+ plugin leaves that switch alone because a tool object can be shared with
166
+ code outside workflows. When the source is not available (an install that
167
+ ships only ``.pyc`` files) the check logs a warning and the seam is
168
+ installed anyway: the rebind itself does not depend on the source.
169
+ """
170
+ from agent_framework import FunctionTool
171
+
172
+ try:
173
+ source = inspect.getsource(FunctionTool._invoke_function)
174
+ except (OSError, TypeError) as err:
175
+ logger.warning(
176
+ "Cannot read the source of FunctionTool._invoke_function (%s), so the "
177
+ "agent_framework._tools.asyncio seam is installed unchecked; a "
178
+ "synchronous tool runs inline in a workflow only while the framework "
179
+ "hands it to asyncio.to_thread.",
180
+ err,
181
+ )
182
+ return
183
+ if "asyncio.to_thread(" not in source:
184
+ raise _unsupported(
185
+ "FunctionTool._invoke_function",
186
+ "it no longer runs synchronous tools through asyncio.to_thread",
187
+ )
188
+
189
+
190
+ def install_workflow_runtime() -> None:
191
+ """Rebind Agent Framework's clock, id and thread seams for Workers and Replayers.
192
+
193
+ Checks every seam before changing any of them, so a worker fails to start
194
+ with one error naming the seam and the installed version instead of
195
+ running with a replay hazard. Safe to call more than once.
196
+
197
+ Raises:
198
+ RuntimeError: If a seam is missing or holds something other than the
199
+ stdlib object or this module's stand-in.
200
+ """
201
+ with _install_lock:
202
+ modules: dict[str, Any] = {}
203
+ for module_name, attr, expected, shim in _SEAMS:
204
+ seam = f"{module_name}.{attr}"
205
+ if module_name not in modules:
206
+ try:
207
+ modules[module_name] = importlib.import_module(module_name)
208
+ except ImportError as err:
209
+ raise _unsupported(
210
+ seam, f"the module cannot be imported ({err})"
211
+ ) from err
212
+ current = getattr(modules[module_name], attr, _MISSING)
213
+ if current is _MISSING:
214
+ raise _unsupported(seam, "the name is gone")
215
+ if current is not expected and current is not shim:
216
+ raise _unsupported(
217
+ seam, f"expected the stdlib {expected!r}, found {current!r}"
218
+ )
219
+ check_sync_tool_seam()
220
+ for module_name, attr, _expected, shim in _SEAMS:
221
+ setattr(modules[module_name], attr, shim)
@@ -0,0 +1,193 @@
1
+ """Test helpers for agents that run through ``MicrosoftAgentFrameworkPlugin``.
2
+
3
+ Register a scripted client under the model name your workflow uses and the
4
+ model Activity runs offline::
5
+
6
+ plugin = MicrosoftAgentFrameworkPlugin(
7
+ chat_clients={"gpt-4o": fake_chat_client(["Paris."])}
8
+ )
9
+
10
+ ``FakeChatClient`` is a full Agent Framework chat client (function invocation,
11
+ chat middleware and the base client), so it behaves like a provider client on
12
+ the worker: with declaration-only tools it returns the scripted function calls
13
+ unexecuted and assigns their occurrence ids, as a real provider's client does.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import copy
19
+ from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
20
+ from typing import Any, ClassVar, cast
21
+
22
+ from agent_framework import (
23
+ BaseChatClient,
24
+ ChatAndFunctionMiddlewareTypes,
25
+ ChatMiddlewareLayer,
26
+ ChatResponse,
27
+ ChatResponseUpdate,
28
+ Content,
29
+ FunctionInvocationLayer,
30
+ Message,
31
+ ResponseStream,
32
+ )
33
+
34
+ __all__ = [
35
+ "FakeChatClient",
36
+ "fake_chat_client",
37
+ "function_call_response",
38
+ "text_response",
39
+ ]
40
+
41
+ ScriptEntry = str | ChatResponse | Exception
42
+ """One scripted model call: a text reply, a full response, or an error to raise."""
43
+
44
+ _STREAM_CHUNK_CHARS = 12
45
+
46
+
47
+ def text_response(text: str, *, response_id: str | None = None) -> ChatResponse:
48
+ """Return an assistant text reply."""
49
+ return ChatResponse(
50
+ messages=[Message(role="assistant", contents=[Content.from_text(text)])],
51
+ response_id=response_id,
52
+ )
53
+
54
+
55
+ def function_call_response(
56
+ name: str,
57
+ arguments: Mapping[str, Any],
58
+ *,
59
+ call_id: str,
60
+ id: str | None = None,
61
+ ) -> ChatResponse:
62
+ """Return an assistant reply that calls ``name`` with ``arguments``.
63
+
64
+ ``call_id`` is the provider's call id that the result answers. ``id`` is
65
+ the occurrence id; leave it ``None`` to script a provider that omits it,
66
+ so the client's function-invocation layer assigns one.
67
+ """
68
+ return ChatResponse(
69
+ messages=[
70
+ Message(
71
+ role="assistant",
72
+ contents=[
73
+ Content.from_function_call(
74
+ call_id, name, arguments=dict(arguments), id=id
75
+ )
76
+ ],
77
+ )
78
+ ]
79
+ )
80
+
81
+
82
+ class FakeChatClient(FunctionInvocationLayer, ChatMiddlewareLayer, BaseChatClient): # type: ignore[type-arg]
83
+ """A scripted chat client for tests.
84
+
85
+ Each model call takes the next entry of ``responses``; the last entry
86
+ repeats once the script runs out. A ``str`` becomes a text reply, a
87
+ ``ChatResponse`` is returned as is (``text_response`` and
88
+ ``function_call_response`` build the common shapes) and an ``Exception`` is
89
+ raised from the call. A streamed call splits text into updates of 12
90
+ characters and sends every other content item as one update.
91
+
92
+ ``calls`` records every call as a dict with ``messages``, ``options``,
93
+ ``kwargs`` and ``stream``, so a test can assert what reached the model.
94
+ """
95
+
96
+ OTEL_PROVIDER_NAME: ClassVar[str] = "temporal-fake"
97
+
98
+ def __init__(
99
+ self,
100
+ responses: Sequence[ScriptEntry],
101
+ *,
102
+ middleware: Sequence[ChatAndFunctionMiddlewareTypes] | None = None,
103
+ ) -> None:
104
+ """Script the client; ``responses`` must hold at least one entry."""
105
+ if not responses:
106
+ raise ValueError("FakeChatClient needs at least one scripted response.")
107
+ super().__init__(middleware=middleware)
108
+ self._responses = list(responses)
109
+ self._cursor = 0
110
+ self.calls: list[dict[str, Any]] = []
111
+
112
+ def _next(self) -> ScriptEntry:
113
+ entry = self._responses[min(self._cursor, len(self._responses) - 1)]
114
+ self._cursor += 1
115
+ return entry
116
+
117
+ def _inner_get_response(
118
+ self,
119
+ *,
120
+ messages: Sequence[Message],
121
+ stream: bool,
122
+ options: Mapping[str, Any],
123
+ **kwargs: Any,
124
+ ) -> Awaitable[ChatResponse] | ResponseStream[ChatResponseUpdate, ChatResponse]:
125
+ self.calls.append(
126
+ {
127
+ "messages": list(messages),
128
+ "options": dict(options),
129
+ "kwargs": dict(kwargs),
130
+ "stream": stream,
131
+ }
132
+ )
133
+ entry = self._next()
134
+ if stream:
135
+ return ResponseStream(
136
+ _updates(entry),
137
+ finalizer=lambda updates: ChatResponse.from_updates(
138
+ updates, output_format_type=options.get("response_format")
139
+ ),
140
+ )
141
+ return _respond(entry)
142
+
143
+
144
+ async def _respond(entry: ScriptEntry) -> ChatResponse:
145
+ return _response(entry)
146
+
147
+
148
+ def _response(entry: ScriptEntry) -> ChatResponse:
149
+ if isinstance(entry, Exception):
150
+ raise entry
151
+ if isinstance(entry, str):
152
+ return text_response(entry)
153
+ # The loop mutates responses (ids, author names); keep the script intact.
154
+ return copy.deepcopy(entry)
155
+
156
+
157
+ async def _updates(entry: ScriptEntry) -> AsyncIterator[ChatResponseUpdate]:
158
+ response = _response(entry)
159
+ for message in response.messages:
160
+ for content in message.contents:
161
+ if content.type == "text" and content.text:
162
+ text = content.text
163
+ for start in range(0, len(text), _STREAM_CHUNK_CHARS):
164
+ # Text deltas carry merge_mode="append", as the providers'
165
+ # clients emit them.
166
+ yield ChatResponseUpdate(
167
+ role=cast(Any, message.role),
168
+ contents=[
169
+ Content.from_text(
170
+ text[start : start + _STREAM_CHUNK_CHARS],
171
+ merge_mode="append",
172
+ )
173
+ ],
174
+ response_id=response.response_id,
175
+ message_id=message.message_id,
176
+ )
177
+ else:
178
+ yield ChatResponseUpdate(
179
+ role=cast(Any, message.role),
180
+ contents=[content],
181
+ response_id=response.response_id,
182
+ message_id=message.message_id,
183
+ )
184
+
185
+
186
+ def fake_chat_client(responses: Sequence[ScriptEntry]) -> Callable[[], FakeChatClient]:
187
+ """Return a ``chat_clients`` factory for one scripted ``FakeChatClient``.
188
+
189
+ The factory hands out the same instance every time, so a test can call it
190
+ to read ``calls`` after the workflow finishes.
191
+ """
192
+ client = FakeChatClient(responses)
193
+ return lambda: client
@@ -0,0 +1,213 @@
1
+ """Workflow-side helpers: the plugin's failure type and ``activity_as_tool``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ import typing
8
+ from collections.abc import Callable, Generator
9
+ from contextlib import contextmanager
10
+ from datetime import timedelta
11
+ from typing import Any, ClassVar, Literal
12
+
13
+ from agent_framework import FunctionTool
14
+
15
+ from temporalio import activity, workflow
16
+ from temporalio.common import Priority, RetryPolicy
17
+ from temporalio.exceptions import (
18
+ ActivityError,
19
+ ApplicationError,
20
+ is_cancelled_exception,
21
+ )
22
+ from temporalio.workflow import (
23
+ ActivityCancellationType,
24
+ ActivityConfig,
25
+ VersioningIntent,
26
+ )
27
+
28
+ ApprovalMode = Literal["always_require", "never_require"]
29
+ """The approval modes Agent Framework accepts on a tool."""
30
+
31
+
32
+ class MicrosoftAgentFrameworkWorkflowError(ApplicationError):
33
+ """A configuration mistake the plugin finds in workflow code.
34
+
35
+ Raised for a ``TemporalChatClient`` without a model name, an option or
36
+ tool that cannot be recorded in workflow history, and an MCP tool whose
37
+ name the agent already uses. It is a non-retryable ``ApplicationError``
38
+ of type ``MicrosoftAgentFrameworkWorkflowError``, registered as a workflow failure
39
+ type, so it fails the workflow instead of retrying the workflow task.
40
+ Match it by ``ApplicationError.type``.
41
+ """
42
+
43
+ TYPE: ClassVar[str] = "MicrosoftAgentFrameworkWorkflowError"
44
+
45
+ def __init__(self, message: str, *details: Any, non_retryable: bool = True) -> None:
46
+ """Create the error with ``message`` and optional serializable details."""
47
+ super().__init__(message, *details, type=self.TYPE, non_retryable=non_retryable)
48
+
49
+
50
+ def activity_as_tool(
51
+ activity_fn: Callable[..., Any],
52
+ *,
53
+ name: str | None = None,
54
+ description: str | None = None,
55
+ approval_mode: ApprovalMode | None = None,
56
+ task_queue: str | None = None,
57
+ schedule_to_close_timeout: timedelta | None = None,
58
+ schedule_to_start_timeout: timedelta | None = None,
59
+ start_to_close_timeout: timedelta | None = None,
60
+ heartbeat_timeout: timedelta | None = None,
61
+ retry_policy: RetryPolicy | None = None,
62
+ cancellation_type: ActivityCancellationType = ActivityCancellationType.TRY_CANCEL,
63
+ activity_id: str | None = None,
64
+ versioning_intent: VersioningIntent | None = None,
65
+ summary: str | None = None,
66
+ priority: Priority = Priority.default,
67
+ ) -> FunctionTool:
68
+ """Wrap a Temporal activity as an Agent Framework ``FunctionTool``.
69
+
70
+ ``activity_fn`` must carry ``@activity.defn`` and be a function or a method
71
+ passed as ``Class.method`` (the worker registers the bound method). The
72
+ tool's name defaults to the activity name, its description to the
73
+ docstring, and its parameter schema is inferred by Agent Framework from the
74
+ activity's signature, without a method's ``self``. When the model calls
75
+ the tool, the arguments are bound by name and the activity runs through
76
+ ``workflow.execute_activity`` with the given options; ``summary`` defaults
77
+ to the tool name.
78
+
79
+ A failed activity raises its failure cause from the tool, which Agent
80
+ Framework turns into an error result for the model. Cancellation of the
81
+ workflow or of the tool task propagates as ``asyncio.CancelledError``.
82
+
83
+ Raises:
84
+ ValueError: If ``activity_fn`` is not an ``@activity.defn`` function or
85
+ method, or takes ``*args`` or ``**kwargs``, which the tool cannot
86
+ pass by position (``@activity.defn`` itself rejects keyword-only
87
+ parameters); or if neither ``start_to_close_timeout`` nor
88
+ ``schedule_to_close_timeout`` is set.
89
+ """
90
+ if inspect.isclass(activity_fn) or not (
91
+ inspect.isfunction(activity_fn) or inspect.ismethod(activity_fn)
92
+ ):
93
+ raise ValueError(
94
+ "activity_as_tool takes a function or a method decorated with "
95
+ f"@activity.defn, not {activity_fn!r}"
96
+ )
97
+ defn = activity._Definition.from_callable(activity_fn)
98
+ if defn is None or not defn.name:
99
+ raise ValueError("activity_fn must be decorated with @activity.defn")
100
+ activity_name = defn.name
101
+
102
+ signature = inspect.signature(activity_fn)
103
+ params = list(signature.parameters.values())
104
+ # A first parameter named `self` is the receiver of a method passed as
105
+ # Class.method: the worker's bound method supplies it.
106
+ if inspect.isfunction(activity_fn) and params and params[0].name == "self":
107
+ params = params[1:]
108
+ for param in params:
109
+ if param.kind in (
110
+ inspect.Parameter.VAR_POSITIONAL,
111
+ inspect.Parameter.VAR_KEYWORD,
112
+ ):
113
+ raise ValueError(
114
+ f"Activity {activity_name!r} cannot take *args or **kwargs "
115
+ f"({param.name!r}): the tool passes one argument per parameter, "
116
+ "by position"
117
+ )
118
+ # The model's arguments bind by name; the activity still gets them by position.
119
+ call_signature = signature.replace(
120
+ parameters=[
121
+ p.replace(kind=inspect.Parameter.POSITIONAL_OR_KEYWORD)
122
+ if p.kind is inspect.Parameter.POSITIONAL_ONLY
123
+ else p
124
+ for p in params
125
+ ]
126
+ )
127
+ if start_to_close_timeout is None and schedule_to_close_timeout is None:
128
+ raise ValueError(
129
+ f"activity_as_tool({activity_name!r}) needs start_to_close_timeout or "
130
+ "schedule_to_close_timeout, as workflow.execute_activity does"
131
+ )
132
+ hints = typing.get_type_hints(activity_fn, include_extras=True)
133
+ result_type = hints.get("return")
134
+ tool_name = name or activity_name
135
+ options = ActivityConfig(
136
+ task_queue=task_queue,
137
+ schedule_to_close_timeout=schedule_to_close_timeout,
138
+ schedule_to_start_timeout=schedule_to_start_timeout,
139
+ start_to_close_timeout=start_to_close_timeout,
140
+ heartbeat_timeout=heartbeat_timeout,
141
+ retry_policy=retry_policy,
142
+ cancellation_type=cancellation_type,
143
+ activity_id=activity_id,
144
+ versioning_intent=versioning_intent,
145
+ summary=summary if summary is not None else tool_name,
146
+ priority=priority,
147
+ )
148
+
149
+ async def dispatch(**arguments: Any) -> Any:
150
+ bound = call_signature.bind(**arguments)
151
+ bound.apply_defaults()
152
+ positional = list(bound.arguments.values())
153
+ try:
154
+ with _propagate_workflow_cancellation():
155
+ if not positional:
156
+ return await workflow.execute_activity(
157
+ activity_name, result_type=result_type, **options
158
+ )
159
+ if len(positional) == 1:
160
+ return await workflow.execute_activity(
161
+ activity_name, positional[0], result_type=result_type, **options
162
+ )
163
+ return await workflow.execute_activity(
164
+ activity_name, args=positional, result_type=result_type, **options
165
+ )
166
+ except ActivityError as error:
167
+ cause = error.__cause__
168
+ # The ActivityError says "Activity task failed"; its cause carries
169
+ # the activity's own message, which is what the model should read.
170
+ if isinstance(cause, Exception):
171
+ raise cause
172
+ raise
173
+
174
+ # Agent Framework infers the parameter schema from the signature it sees.
175
+ dispatch.__signature__ = call_signature # type: ignore[attr-defined]
176
+ dispatch.__annotations__ = {
177
+ p.name: hints[p.name] for p in params if p.name in hints
178
+ }
179
+ dispatch.__name__ = tool_name
180
+ dispatch.__qualname__ = tool_name
181
+ dispatch.__doc__ = inspect.getdoc(activity_fn)
182
+ return FunctionTool(
183
+ name=tool_name,
184
+ description=description
185
+ if description is not None
186
+ else (inspect.getdoc(activity_fn) or ""),
187
+ func=dispatch,
188
+ approval_mode=approval_mode,
189
+ )
190
+
191
+
192
+ @contextmanager
193
+ def _propagate_workflow_cancellation() -> Generator[None, None, None]:
194
+ """Raise ``asyncio.CancelledError`` from a tool whose Activity the workflow's cancel ended.
195
+
196
+ Agent Framework catches ``Exception`` around a tool and would keep the run
197
+ going on an ``ActivityError``; a cancelled workflow has to stop instead.
198
+ After the task's cancellation the SDK keeps waiting for the Activity's own
199
+ resolution, so the cancelled Activity arrives as an ``ActivityError`` with
200
+ a ``CancelledError`` cause while the task's cancel count has gone up.
201
+ """
202
+ cancel_requests = _cancel_requests()
203
+ try:
204
+ yield
205
+ except ActivityError as error:
206
+ if is_cancelled_exception(error) and _cancel_requests() > cancel_requests:
207
+ raise asyncio.CancelledError() from error
208
+ raise
209
+
210
+
211
+ def _cancel_requests() -> int:
212
+ task = asyncio.current_task()
213
+ return task.cancelling() if task is not None else 0