8
import typing_extensions as te
9
from composio_client import APIStatusError, omit
10
from composio_client.types.tool_router.session_execute_meta_response import (
11
+ SessionExecuteMetaBlockedResponse,
12
SessionExecuteMetaInputRequiredResponse,
12
- SessionExecuteMetaResponse,
13
+ SessionExecuteMetaResult,
14
)
15
from composio_client.types.tool_router.session_execute_response import (
16
+ SessionExecuteBlockedResponse,
17
SessionExecuteInputRequiredResponse,
18
SessionExecuteResponse,
19
+ SessionExecuteResult,
20
)
21
from composio_client.types.tool_router.session_proxy_execute_response import (
22
SessionProxyExecuteInputRequiredResponse,
23
)
24
from pydantic import BaseModel as PydanticBaseModel
22
-from pydantic import TypeAdapter
23
-from pydantic import ValidationError as PydanticValidationError
25
26
from composio.client import HttpClient
27
from composio.client.types import (
175
)
176
177
177
-class _BlockReasonWire(PydanticBaseModel):
178
- type: t.Literal["request_blocked", "response_blocked"]
179
- hook_id: str
178
+class ToolRouterSessionExecuteResponse(SessionExecuteResponse):
179
+ """Result of a session tool execution.
180
181
-
182
-class BlockedResponse(PydanticBaseModel):
183
- """A call a session hook blocked, as the API returns it.
184
-
185
- The generated client does not type it yet, so it is validated here.
186
- ``log_id`` and ``instant_charge`` come only from session execute; session
187
- proxy execute leaves them out.
181
+ The client's model, with ``hook_results`` as the SDK's own
182
+ :class:`ToolRouterHookResult` dicts, as they were before the client typed
183
+ them. ``instant_charge`` is present only when the Session sets
184
+ ``instant.return_instant_charge`` and a charge is available.
185
"""
186
190
- result_type: t.Literal["blocked"]
191
- reason: _BlockReasonWire
192
- message: str
193
- log_id: t.Optional[str] = None
194
- instant_charge: t.Optional[t.Any] = None
195
- hook_results: t.Optional[t.List[ToolRouterHookResult]] = None
196
-
197
-
198
-_HOOK_RESULTS_ADAPTER: TypeAdapter[t.List[ToolRouterHookResult]] = TypeAdapter(
199
- t.List[ToolRouterHookResult]
200
-)
201
-
187
+ hook_results: t.Optional[t.List[ToolRouterHookResult]] = None # type: ignore[assignment]
188
203
-def parse_blocked_response(
204
- response: t.Any, subject: str
205
-) -> t.Optional[BlockedResponse]:
206
- """Read a ``blocked`` response, or return ``None`` for any other ``result_type``.
207
-
208
- :raises ValidationError: If a ``blocked`` response does not match its shape.
209
- """
210
- if getattr(response, "result_type", None) != "blocked":
211
- return None
212
- try:
213
- return BlockedResponse.model_validate(
214
- {
215
- # ``instant_charge`` stays the client's model: the provider
216
- # execute path reads it as one.
217
- key: value if key == "instant_charge" else _plain(value)
218
- for key, value in dict(response).items()
219
- }
220
- )
221
- except PydanticValidationError as exc:
222
- raise ValidationError(
223
- f"{subject} returned a malformed blocked response"
224
- ) from exc
189
226
-
227
-def _plain(value: t.Any) -> t.Any:
228
- """Nested client models as plain data.
229
-
230
- The generated client may return ``reason`` and ``hook_results`` as its own
231
- nested models; the SDK validates plain data against its own types.
232
- """
233
- if isinstance(value, PydanticBaseModel):
234
- return value.model_dump()
235
- if isinstance(value, list):
236
- return [_plain(item) for item in value]
237
- return value
190
+def _session_execute_result(
191
+ fields: t.Mapping[str, t.Any], fields_set: t.AbstractSet[str]
192
+) -> ToolRouterSessionExecuteResponse:
193
+ """The SDK's result over fields the client already parsed, without parsing them again."""
194
+ return ToolRouterSessionExecuteResponse.model_construct(
195
+ _fields_set=set(fields_set), **fields
196
+ )
197
198
240
-def _response_field(response: t.Any, name: str) -> t.Any:
241
- """A field of a generated client response model, declared or not.
199
+def hook_results_of(
200
+ hook_results: t.Optional[t.Sequence[PydanticBaseModel]],
201
+) -> t.Optional[t.List[ToolRouterHookResult]]:
202
+ """The client's typed ``hook_results`` as the SDK's own plain dicts.
203
243
- The generated client keeps fields it does not type yet (``hook_results``)
244
- as extras; once it types them they become declared fields.
204
+ The SDK returns hook results as :class:`ToolRouterHookResult` dicts, as it
205
+ did before the client typed them.
206
"""
246
- if not isinstance(response, PydanticBaseModel):
207
+ if hook_results is None:
208
return None
248
- if name in type(response).model_fields:
249
- return getattr(response, name, None)
250
- return (response.model_extra or {}).get(name)
209
+ return [
210
+ t.cast(ToolRouterHookResult, hook_result.model_dump())
211
+ for hook_result in hook_results
212
+ ]
213
214
253
-def parse_hook_results(
254
- response: t.Any, subject: str
255
-) -> t.Optional[t.List[ToolRouterHookResult]]:
256
- """The ``hook_results`` of a call that ran, or ``None`` when no hook applied.
215
+def _blocked_execute_result(
216
+ blocked: t.Union[SessionExecuteBlockedResponse, SessionExecuteMetaBlockedResponse],
217
+) -> ToolRouterSessionExecuteResponse:
218
+ """A call a session hook blocked, as the session execute model.
219
258
- :raises ValidationError: If ``hook_results`` does not match its shape.
220
+ The agent reads ``error``, so a blocked call reaches it as a failed call
221
+ with the hook's message. The fields are carried over as the client parsed
222
+ them instead of being validated a second time.
223
"""
260
- raw = _plain(_response_field(response, "hook_results"))
261
- if raw is None:
262
- return None
263
- try:
264
- return _HOOK_RESULTS_ADAPTER.validate_python(raw)
265
- except PydanticValidationError as exc:
266
- raise ValidationError(f"{subject} returned malformed hook results") from exc
224
+ fields: t.Dict[str, t.Any] = {
225
+ "data": {},
226
+ "error": blocked.message,
227
+ "log_id": blocked.log_id or "",
228
+ "result_type": "blocked",
229
+ "block_reason": {
230
+ "type": blocked.reason.type,
231
+ "hook_id": blocked.reason.hook_id,
232
+ },
233
+ }
234
+ hook_results = hook_results_of(blocked.hook_results)
235
+ if hook_results is not None:
236
+ fields["hook_results"] = hook_results
237
+ if blocked.instant_charge is not None:
238
+ # The client's model: the provider execute path reads it as one.
239
+ fields["instant_charge"] = blocked.instant_charge
240
+ return _session_execute_result(fields, fields.keys())
241
242
243
def require_execute_result(
270
- response: t.Union[SessionExecuteResponse, SessionExecuteInputRequiredResponse],
244
+ response: SessionExecuteResult,
245
slug: str,
272
-) -> SessionExecuteResponse:
246
+) -> ToolRouterSessionExecuteResponse:
247
"""Narrow a session execute response to a tool that ran.
248
249
Every session execute response carries a ``result_type``. A ``blocked``
257
running.
258
:raises ValidationError: If ``result_type`` is missing or unknown.
259
"""
260
+ if isinstance(response, SessionExecuteBlockedResponse):
261
+ return _blocked_execute_result(response)
262
executed = require_executed(response, f"Tool {slug}")
287
- blocked = parse_blocked_response(executed, f"Tool {slug}")
288
- if blocked is not None:
289
- # The agent reads ``error``, so a blocked call reaches it as a failed
290
- # call with the hook's message.
291
- fields: t.Dict[str, t.Any] = {
292
- "data": {},
293
- "error": blocked.message,
294
- "log_id": blocked.log_id or "",
295
- "result_type": "blocked",
296
- "block_reason": {
297
- "type": blocked.reason.type,
298
- "hook_id": blocked.reason.hook_id,
299
- },
300
- }
301
- if blocked.hook_results is not None:
302
- fields["hook_results"] = blocked.hook_results
303
- if blocked.instant_charge is not None:
304
- fields["instant_charge"] = blocked.instant_charge
305
- return SessionExecuteResponse.model_construct(_fields_set=set(fields), **fields)
306
- if getattr(executed, "result_type", None) not in ("completed", "failed"):
263
+ if executed.result_type not in ("completed", "failed"):
264
raise ValidationError(
265
f"Tool {slug} returned an execute response without a known result_type"
266
)
310
- parse_hook_results(executed, f"Tool {slug}")
311
- return executed
267
+ return _session_execute_result(
268
+ {**dict(executed), "hook_results": hook_results_of(executed.hook_results)},
269
+ executed.model_fields_set,
270
+ )
271
272
273
def require_execute_meta_result(
315
- response: t.Union[
316
- SessionExecuteMetaResponse, SessionExecuteMetaInputRequiredResponse
317
- ],
274
+ response: SessionExecuteMetaResult,
275
slug: str,
319
-) -> SessionExecuteResponse:
276
+) -> ToolRouterSessionExecuteResponse:
277
"""Narrow a session execute_meta response to a meta tool that ran.
278
279
The meta endpoint answers in the same shape as session execute, so the
284
running.
285
:raises ValidationError: If ``result_type`` is missing or unknown.
286
"""
287
+ if isinstance(response, SessionExecuteMetaBlockedResponse):
288
+ return _blocked_execute_result(response)
289
executed = require_executed(response, f"Tool {slug}")
290
# Carry the fields over as the client parsed them instead of validating
291
# them a second time.