@devries-cameron20 / composio-1 / commits / 7434e02d8
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix: move to @composio/client rc.22 and drop the spec-gap workarounds (#5090)

This PR: - moves core, the CLI and the Python SDK to `@composio/client@2.0.0-rc.22` / `composio-client==2.0.0rc22` (https://github.com/ComposioHQ/composio-client/pull/108 spec refresh, https://github.com/ComposioHQ/composio-client/pull/109 `client._internal`) - types session `hooks`, the `blocked` execute variant and `hook_results` from the client instead of SDK copies, in core (`toolRouterParams.ts`, `toolRouterResponseTransform.ts`) and Python (`tool_router.py`, `tools.py`, `session_context.py`); Python's `ToolRouterSessionExecuteResponse` becomes a subclass that keeps `hook_results` as the SDK's dicts, as in 0.30.0 - keeps the `expected_config_version` / nullable patch-block workaround, now citing ComposioHQ/platform#13157 (still open) - populates `meta.appUrl` on `toolkits.get()`, accepts `require_approval` (and approval-only entries) in stored session-config policies, and reports hook-blocked calls in the CLI (`execute`, `proxy`, Dashboard transport) as failures carrying the hook's message - moves the CLI to `client._internal` for the `x-internal` operations (login sessions, realtime, logs, consumer projects), opting in once via `@composio/client/effect/internal` - drops the CLI's dead `org_member.user_id` / `api_key.api_key` fallbacks; production sends neither (verified against `auth/session/info`) ## Validation On this branch with the published rc.22: - `pnpm typecheck`, `typecheck:examples`, `lint:examples`; core 1944 passed; CLI 2373 passed, 1 skipped - Python: `nox -s chk tst` (ruff + mypy clean; 2597 passed, 32 skipped) - the composio-client release acceptance (`downstream-compile`, `downstream-python`, `effect-subpath`) passed against this branch: https://github.com/ComposioHQ/composio-client/actions/runs/39958949141

Alberto Schiabel committed Oct 23, 2026 at 22:03 UTC 7434e02d8dc740d9218360b9ef194be316c55745
51 files changed +570 -511
.changeset/client-spec-gaps.md new
+6
@@ -0,0 +1,6 @@
1 +---
2 +'@composio/core': minor
3 +'@composio/slim': minor
4 +---
5 +
6 +Requires `@composio/client` `2.0.0-rc.22`. `composio.toolkits.get(slug)` now returns `meta.appUrl` when the API sends the toolkit's app URL; it was always left out before. `composio.sessionConfigs.get()` keeps the `require_approval` lists of a stored policy, and no longer fails validation on a policy entry that only sets `require_approval`; `SessionConfigPolicy` gains the matching optional `require_approval` fields and the approval-only entry. Session hooks, blocked calls and hook results are read from the API types of `@composio/client` instead of SDK copies, with the same results and errors for well-formed responses; a malformed `hook_results` or blocked response is no longer re-validated by the SDK, matching every other API response.
pnpm-lock.yaml
+9 -9
@@ -28,8 +28,8 @@ catalogs:
28 specifier: ^5.20261019.1
29 version: 5.20261019.1
30 '@composio/client':
31 - specifier: 2.0.0-rc.21
32 - version: 2.0.0-rc.21
31 + specifier: 2.0.0-rc.22
32 + version: 2.0.0-rc.22
33 '@effect/language-service':
34 specifier: ^0.87.5
35 version: 0.87.5
@@ -990,7 +990,7 @@ importers:
990 dependencies:
991 '@composio/client':
992 specifier: 'catalog:'
993 - version: 2.0.0-rc.21(effect@4.0.5)
993 + version: 2.0.0-rc.22(effect@4.0.5)
994 '@composio/core':
995 specifier: workspace:*
996 version: link:../../packages/core
@@ -1238,7 +1238,7 @@ importers:
1238 version: link:../cli-keyring
1239 '@composio/client':
1240 specifier: 'catalog:'
1241 - version: 2.0.0-rc.21(effect@4.0.5)
1241 + version: 2.0.0-rc.22(effect@4.0.5)
1242 '@composio/core':
1243 specifier: workspace:*
1244 version: link:../core
@@ -1344,7 +1344,7 @@ importers:
1344 dependencies:
1345 '@composio/client':
1346 specifier: 'catalog:'
1347 - version: 2.0.0-rc.21(effect@4.0.5)
1347 + version: 2.0.0-rc.22(effect@4.0.5)
1348 '@composio/json-schema-to-zod':
1349 specifier: workspace:*
1350 version: link:../json-schema-to-zod
@@ -1758,7 +1758,7 @@ importers:
1758 dependencies:
1759 '@composio/client':
1760 specifier: 'catalog:'
1761 - version: 2.0.0-rc.21(effect@4.0.5)
1761 + version: 2.0.0-rc.22(effect@4.0.5)
1762 '@composio/json-schema-to-zod':
1763 specifier: workspace:*
1764 version: link:../json-schema-to-zod
@@ -2332,8 +2332,8 @@ packages:
2332 resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
2333 engines: {node: '>=0.1.90'}
2334
2335 - '@composio/client@2.0.0-rc.21':
2336 - resolution: {integrity: sha512-dmFyDbbJMTmQ/Q08GYf6YOpH9/h04+Y2YSKZcJAG3TP15OpeTspHaLhU9G++7C6GdgC3K5a144cjnCLidMu5Mw==}
2335 + '@composio/client@2.0.0-rc.22':
2336 + resolution: {integrity: sha512-3qij4JrE3/7L2oV/vMEzrKTIrivckGHYB5PV/OSC5d/jsbCJzIz1RLs8UfEpGAcvTVNZx6vRqEsMDKUYjpjm0Q==}
2337 engines: {node: '>=22'}
2338 peerDependencies:
2339 effect: '*'
@@ -7635,7 +7635,7 @@ snapshots:
7635 '@colors/colors@1.5.0':
7636 optional: true
7637
7638 - '@composio/client@2.0.0-rc.21(effect@4.0.5)':
7638 + '@composio/client@2.0.0-rc.22(effect@4.0.5)':
7639 optionalDependencies:
7640 effect: 4.0.5
7641
pnpm-workspace.yaml
+1 -1
@@ -33,7 +33,7 @@ catalog:
33 '@clack/prompts': '^1.8.1'
34 '@cloudflare/vitest-pool-workers': 0.23.0
35 '@cloudflare/workers-types': ^5.20261019.1
36 - '@composio/client': 2.0.0-rc.21
36 + '@composio/client': 2.0.0-rc.22
37 '@effect/language-service': ^0.87.5
38 '@effect/platform-bun': 4.0.5
39 '@effect/vitest': 4.0.5
python/composio/core/models/session_context.py
+20 -20
@@ -13,6 +13,9 @@ from composio_client.types.tool_router.session_execute_response import (
13 SessionExecuteResponse,
14 )
15 from composio_client.types.tool_router.session_proxy_execute_params import Parameter
16 +from composio_client.types.tool_router.session_proxy_execute_response import (
17 + SessionProxyExecuteBlockedResponse,
18 +)
19
20 from composio.client import HttpClient
21 from composio.core.models.custom_tool_execution import (
@@ -32,8 +35,7 @@ from composio.core.models.inline_custom_tools_payload import (
35 )
36 from composio.core.models.tools import (
37 _serialize_arguments,
35 - parse_blocked_response,
36 - parse_hook_results,
38 + hook_results_of,
39 require_execute_result,
40 require_executed,
41 )
@@ -93,32 +95,30 @@ def proxy_execute_impl(
95 subject = f"{method} proxy call for toolkit {toolkit}"
96 # Disable retries: a proxied call is a non-idempotent write, and a silent
97 # retry after a read timeout can duplicate the side effect.
96 - response = require_executed(
97 - client.without_retries.tool_router.session.proxy_execute(
98 - session_id=session_id,
99 - toolkit_slug=toolkit,
100 - endpoint=endpoint,
101 - method=method,
102 - body=body if body is not None else omit,
103 - parameters=api_params if api_params else omit,
104 - ),
105 - subject,
98 + raw = client.without_retries.tool_router.session.proxy_execute(
99 + session_id=session_id,
100 + toolkit_slug=toolkit,
101 + endpoint=endpoint,
102 + method=method,
103 + body=body if body is not None else omit,
104 + parameters=api_params if api_params else omit,
105 )
106
107 # A blocked request has no HTTP response, so it is read before ``status``.
109 - blocked = parse_blocked_response(response, subject)
110 - if blocked is not None:
108 + if isinstance(raw, SessionProxyExecuteBlockedResponse):
109 blocked_result: ToolRouterSessionProxyExecuteBlocked = {
110 "result_type": "blocked",
111 "block_reason": {
114 - "type": blocked.reason.type,
115 - "hook_id": blocked.reason.hook_id,
112 + "type": raw.reason.type,
113 + "hook_id": raw.reason.hook_id,
114 },
117 - "message": blocked.message,
115 + "message": raw.message,
116 }
119 - if blocked.hook_results is not None:
120 - blocked_result["hook_results"] = blocked.hook_results
117 + blocked_hook_results = hook_results_of(raw.hook_results)
118 + if blocked_hook_results is not None:
119 + blocked_result["hook_results"] = blocked_hook_results
120 return blocked_result
121 + response = require_executed(raw, subject)
122
123 # ``status`` and ``size`` are ``float`` on the generated model and pydantic
124 # coerces, so they arrive as ``200.0``/``123.0``. Narrow them here: an HTTP
@@ -129,7 +129,7 @@ def proxy_execute_impl(
129 "data": response.data,
130 "headers": response.headers,
131 }
132 - hook_results = parse_hook_results(response, subject)
132 + hook_results = hook_results_of(response.hook_results)
133 if hook_results is not None:
134 result["hook_results"] = hook_results
135 binary_data = response.binary_data
python/composio/core/models/tool_router.py
+1 -2
@@ -1200,8 +1200,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1200 "`experimental={'session_config_id': ...}`; create the session "
1201 "from the saved config and add hooks in a separate update() call"
1202 )
1203 - # The generated client has no typed parameter for ``hooks`` yet.
1204 - create_params["extra_body"] = {"hooks": hooks}
1203 + create_params["hooks"] = hooks
1204
1205 # Build connections config
1206 connections_config: t.Dict[str, t.Any] = {
python/composio/core/models/tool_router_session.py
+29 -21
@@ -27,9 +27,6 @@ from composio_client.types.tool_router import (
27 session_patch_params,
28 session_search_response,
29 )
30 -from composio_client.types.tool_router.session_execute_response import (
31 - SessionExecuteResponse,
32 -)
30
31 from composio import exceptions
32 from composio.client import HttpClient
@@ -74,6 +71,7 @@ from composio.core.models.tool_router_session_delete import (
71 from composio.core.models.tools import (
72 ToolExecuteParams,
73 ToolExecutionResponse,
74 + ToolRouterSessionExecuteResponse,
75 require_execute_meta_result,
76 require_execute_result,
77 )
@@ -238,11 +236,6 @@ ToolRouterHook = t.Union[ToolRouterBeforeExecuteHook, ToolRouterAfterExecuteHook
236 """A hook on a session's tool calls."""
237
238
241 -ToolRouterSessionExecuteResponse = SessionExecuteResponse
242 -"""Result of :meth:`ToolRouterSession.execute`. ``instant_charge`` is present
243 -only when the Session sets ``instant.return_instant_charge`` and a charge is
244 -available."""
245 -
239 ToolRouterInputResponse = session_execute_params.CurrentInputResponsesValue
240 """Experimental. The user's answer to one question of a
241 ``ToolInputRequiredError``, in the shape of an MCP elicitation result:
@@ -1362,19 +1355,20 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1355
1356 workbench_payload = sandbox if sandbox is not omit else workbench
1357
1365 - # The generated client has no typed parameter for the precondition or
1366 - # for ``hooks``, so they travel as extra root body fields.
1367 - extra_fields: t.Dict[str, t.Any] = {}
1368 - if not isinstance(precondition, Omit):
1369 - extra_fields["expected_config_version"] = precondition
1370 - if not isinstance(hooks, Omit):
1371 - extra_fields["hooks"] = hooks
1372 - extra_body: t.Optional[t.Dict[str, t.Any]] = extra_fields or None
1373 -
1374 - # The generated client does not type ``None`` for every policy block
1375 - # although the API accepts it (it removes the stored override), nor the
1376 - # subfield removals inside ``manage_connections``, ``multi_account`` and
1377 - # ``experimental``; the values are serialized as-is.
1358 + # The spec does not declare the ``expected_config_version`` precondition
1359 + # until ComposioHQ/platform#13157 lands, so it travels as an extra root
1360 + # body field.
1361 + extra_body: t.Optional[t.Dict[str, t.Any]] = (
1362 + None
1363 + if isinstance(precondition, Omit)
1364 + else {"expected_config_version": precondition}
1365 + )
1366 +
1367 + # Until ComposioHQ/platform#13157 lands, the spec does not mark every
1368 + # policy block nullable although the API accepts ``None`` (it removes the
1369 + # stored override), nor the subfield removals inside
1370 + # ``manage_connections``, ``multi_account`` and ``experimental``; the
1371 + # values are serialized as-is.
1372 try:
1373 response = self._client.tool_router.session.patch(
1374 session_id=self.session_id,
@@ -1416,6 +1410,20 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1410 t.Union[t.Optional[session_patch_params.Experimental], "Omit"],
1411 experimental,
1412 ),
1413 + hooks=t.cast(
1414 + t.Union[
1415 + t.Optional[
1416 + t.Iterable[
1417 + t.Union[
1418 + session_patch_params.CurrentHookVariant0,
1419 + session_patch_params.CurrentHookVariant1,
1420 + ]
1421 + ]
1422 + ],
1423 + "Omit",
1424 + ],
1425 + hooks,
1426 + ),
1427 extra_body=extra_body,
1428 # A stale precondition is a deterministic 409: never retry it.
1429 request_options={"max_retries": 0},
python/composio/core/models/tools.py
+66 -107
@@ -8,19 +8,20 @@ from pathlib import Path
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 (
@@ -174,102 +175,75 @@ def require_executed(
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``
@@ -283,40 +257,23 @@ def require_execute_result(
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
@@ -327,6 +284,8 @@ def require_execute_meta_result(
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.
python/pyproject.toml
+1 -1
@@ -14,7 +14,7 @@ dependencies = [
14 "pysher==1.0.8",
15 "websocket-client<2",
16 "pydantic>=2.11.9,<3",
17 - "composio-client==2.0.0rc21",
17 + "composio-client==2.0.0rc22",
18 "typing-extensions>=4.16.0,<5",
19 "openai>=2.48.0,<4",
20 "json-schema-to-pydantic>=0.4.11,<1",
python/setup.py
+1 -1
@@ -28,7 +28,7 @@ setup(
28 "pysher==1.0.8",
29 "websocket-client<2",
30 "pydantic>=2.11.9,<3",
31 - "composio-client==2.0.0rc21",
31 + "composio-client==2.0.0rc22",
32 "typing-extensions>=4.16.0,<5",
33 "openai>=2.48.0,<4",
34 "json-schema-to-pydantic>=0.4.11,<1",
python/tests/test_tool_execution.py
+21 -4
@@ -6,6 +6,9 @@ from unittest.mock import Mock, patch
6
7 import httpx
8 import pytest
9 +from composio_client.types.tool_router.session_execute_response import (
10 + SessionExecuteResponse,
11 +)
12 from composio_client import ProjectAuth, omit
13 from pydantic import BaseModel, Field, RootModel
14
@@ -119,8 +122,15 @@ class TestToolExecution:
122 result = tools.get_raw_tool_router_meta_tools(
123 "session_123", modifiers=[observe_toolkit]
124 )
122 - mock_client.tool_router.session.execute.return_value = Mock(
123 - data={}, error=None, result_type="completed"
125 + mock_client.tool_router.session.execute.return_value = (
126 + SessionExecuteResponse.model_validate(
127 + {
128 + "data": {},
129 + "error": None,
130 + "result_type": "completed",
131 + "log_id": "log_1",
132 + }
133 + )
134 )
135 execute = tools._wrap_execute_tool_for_tool_router(
136 "session_123", modifiers=[observe_before_execute, observe_after_execute]
@@ -168,8 +178,15 @@ class TestToolExecution:
178 "required": ["attachment"],
179 }
180 tools._tool_schemas[tool.slug] = tool
171 - mock_client.tool_router.session.execute.return_value = Mock(
172 - data={}, error=None, result_type="completed"
181 + mock_client.tool_router.session.execute.return_value = (
182 + SessionExecuteResponse.model_validate(
183 + {
184 + "data": {},
185 + "error": None,
186 + "result_type": "completed",
187 + "log_id": "log_1",
188 + }
189 + )
190 )
191 execute = tools._wrap_execute_tool_for_tool_router("session_123")
192 arguments = {
python/tests/test_tool_router.py
+74 -76
@@ -5,6 +5,7 @@ import logging
5 import os
6 import traceback
7 import typing as t
8 +import warnings
9 from unittest.mock import MagicMock, patch
10
11 import httpx
@@ -20,6 +21,9 @@ from composio_client import (
21 omit,
22 )
23 from composio_client import ComposioError as ClientComposioError
24 +from composio_client.types.tool_router.session_execute_response import (
25 + SessionExecuteResponse,
26 +)
27 from composio_client.types.tool_router.session_search_response import (
28 SessionSearchResponse,
29 )
@@ -2052,11 +2056,16 @@ class TestToolRouterExecution:
2056 self, tool_router, mock_client, mock_provider
2057 ):
2058 """Test that session execute is called for agentic tool execution."""
2055 - mock_execute_response = MagicMock()
2056 - mock_execute_response.data = {"result": "success"}
2057 - mock_execute_response.error = None
2058 - mock_execute_response.result_type = "completed"
2059 - mock_client.tool_router.session.execute.return_value = mock_execute_response
2059 + mock_client.tool_router.session.execute.return_value = (
2060 + SessionExecuteResponse.model_validate(
2061 + {
2062 + "result_type": "completed",
2063 + "data": {"result": "success"},
2064 + "error": None,
2065 + "log_id": "log_123",
2066 + }
2067 + )
2068 + )
2069
2070 # Create a real Tools instance to test the execute function
2071 from composio.core.models.tools import Tools as RealTools
@@ -2223,11 +2232,16 @@ class TestToolRouterExecution:
2232
2233 def test_execute_tool_error_handling(self, tool_router, mock_client, mock_provider):
2234 """Test that tool execution errors are handled correctly."""
2226 - mock_execute_response = MagicMock()
2227 - mock_execute_response.data = {}
2228 - mock_execute_response.error = "Authentication failed"
2229 - mock_execute_response.result_type = "failed"
2230 - mock_client.tool_router.session.execute.return_value = mock_execute_response
2235 + mock_client.tool_router.session.execute.return_value = (
2236 + SessionExecuteResponse.model_validate(
2237 + {
2238 + "result_type": "failed",
2239 + "data": {},
2240 + "error": "Authentication failed",
2241 + "log_id": "log_123",
2242 + }
2243 + )
2244 + )
2245
2246 # Create a real execute function
2247 from composio.core.models.tools import Tools as RealTools
@@ -2849,13 +2863,13 @@ class TestSessionHooks:
2863 tool_router.create(user_id="user_123", hooks=self._HOOKS)
2864
2865 kwargs = mock_client.tool_router.session.create.call_args.kwargs
2852 - assert kwargs["extra_body"] == {"hooks": self._HOOKS}
2866 + assert kwargs["hooks"] == self._HOOKS
2867
2868 def test_create_omits_hooks_by_default(self, tool_router, mock_client):
2869 tool_router.create(user_id="user_123")
2870
2871 kwargs = mock_client.tool_router.session.create.call_args.kwargs
2858 - assert "extra_body" not in kwargs
2872 + assert "hooks" not in kwargs
2873
2874 @pytest.mark.parametrize(
2875 ("hooks", "expected"),
@@ -2940,6 +2954,38 @@ class TestSessionHooks:
2954 {"id": "no_external_email", "status": "evaluated", "outcome": "block"}
2955 ]
2956
2957 + @pytest.mark.parametrize(
2958 + "body",
2959 + [
2960 + pytest.param(_BLOCKED_CALL_JSON, id="blocked"),
2961 + pytest.param(
2962 + {
2963 + "data": {"sent": True},
2964 + "error": None,
2965 + "log_id": "log_1",
2966 + "result_type": "completed",
2967 + "hook_results": [
2968 + {"id": "block_injection", "status": "unavailable"}
2969 + ],
2970 + },
2971 + id="completed",
2972 + ),
2973 + ],
2974 + )
2975 + def test_a_result_dumps_its_hook_results_as_the_dicts_it_holds(self, body):
2976 + """The client types ``hook_results`` as models and the SDK's result
2977 + holds them as its own dicts, so dumping it must not warn."""
2978 + client, _ = _answering_client(body)
2979 + result = _created_session(client).execute(
2980 + "GMAIL_SEND_EMAIL", arguments={"to": "ceo@rival.com"}
2981 + )
2982 +
2983 + with warnings.catch_warnings():
2984 + warnings.simplefilter("error")
2985 + dumped = result.model_dump()
2986 +
2987 + assert dumped["hook_results"] == body["hook_results"]
2988 +
2989 def test_blocked_call_reaches_the_agent_as_a_failed_call(self):
2990 """Every provider hands the agent ``data``, ``error`` and
2991 ``successful``, so this is what the agent sees in any framework."""
@@ -2996,66 +3042,6 @@ class TestSessionHooks:
3042 {"id": "block_injection", "status": "unavailable"}
3043 ]
3044
2999 - def test_blocked_response_from_typed_client_models(self):
3000 - """A regenerated client returns ``reason`` and ``hook_results`` as its
3001 - own nested models instead of dicts."""
3002 - from composio.core.models.tools import parse_blocked_response
3003 -
3004 - class _Reason(BaseModel):
3005 - type: str
3006 - hook_id: str
3007 -
3008 - class _HookResult(BaseModel):
3009 - id: str
3010 - status: str
3011 - outcome: t.Optional[str] = None
3012 -
3013 - class _Blocked(BaseModel):
3014 - result_type: str
3015 - reason: _Reason
3016 - message: str
3017 - hook_results: t.List[_HookResult]
3018 -
3019 - blocked = parse_blocked_response(
3020 - _Blocked(
3021 - result_type="blocked",
3022 - reason=_Reason(type="request_blocked", hook_id="no_external_email"),
3023 - message="Blocked by session policy",
3024 - hook_results=[
3025 - _HookResult(
3026 - id="no_external_email", status="evaluated", outcome="block"
3027 - )
3028 - ],
3029 - ),
3030 - "Tool GMAIL_SEND_EMAIL",
3031 - )
3032 -
3033 - assert blocked is not None
3034 - assert blocked.reason.hook_id == "no_external_email"
3035 - assert blocked.hook_results == [
3036 - {"id": "no_external_email", "status": "evaluated", "outcome": "block"}
3037 - ]
3038 -
3039 - def test_malformed_blocked_response_is_raised(self):
3040 - malformed = {k: v for k, v in _BLOCKED_CALL_JSON.items() if k != "reason"}
3041 - client, _ = _answering_client(malformed)
3042 -
3043 - with pytest.raises(ValidationError):
3044 - _created_session(client).execute("GMAIL_SEND_EMAIL", arguments={})
3045 -
3046 - def test_malformed_hook_results_is_raised(self):
3047 - """A completed response whose hook results violate the schema raises a
3048 - malformed hook results error, not an unknown result_type."""
3049 - client, _ = _answering_client(
3050 - {
3051 - **_COMPLETED_JSON,
3052 - "hook_results": [{"id": "block_injection", "status": "nope"}],
3053 - }
3054 - )
3055 -
3056 - with pytest.raises(ValidationError, match="malformed hook results"):
3057 - _created_session(client).execute("GMAIL_SEND_EMAIL", arguments={})
3058 -
3045 @pytest.mark.parametrize(
3046 "run",
3047 [
@@ -3085,19 +3071,31 @@ class TestSessionHooks:
3071 ],
3072 }
3073
3088 - def test_proxy_execute_malformed_hook_results_is_raised(self):
3074 + def test_proxy_execute_returns_the_hook_results_of_a_sent_request(self):
3075 client, _ = _answering_client(
3076 {
3077 "result_type": "completed",
3078 "status": 200,
3079 "data": {"id": 1},
3080 "headers": {},
3095 - "hook_results": [{"id": "block_injection", "status": "nope"}],
3081 + "hook_results": [
3082 + {
3083 + "id": "no_external_email",
3084 + "status": "evaluated",
3085 + "outcome": "continue",
3086 + },
3087 + {"id": "block_injection", "status": "unavailable"},
3088 + ],
3089 }
3090 )
3091
3099 - with pytest.raises(ValidationError, match="malformed hook results"):
3100 - _created_session(client).proxy_execute(**_PROXY_PARAMS)
3092 + result = _created_session(client).proxy_execute(**_PROXY_PARAMS)
3093 +
3094 + assert result["result_type"] == "completed"
3095 + assert result.get("hook_results") == [
3096 + {"id": "no_external_email", "status": "evaluated", "outcome": "continue"},
3097 + {"id": "block_injection", "status": "unavailable"},
3098 + ]
3099
3100
3101 class _NoInput(BaseModel):
ts/examples/session-management/src/session-configs.ts
+6 -4
@@ -80,10 +80,12 @@ async function expectStatus(status: number, run: () => Promise<unknown>): Promis
80
81 /** The saved policy uses enable/disable; the session snapshot uses enabled/disabled. */
82 function toolkitsAsSnapshot(policy: SessionConfigPolicy): unknown {
83 - if (!policy.toolkits) return undefined;
84 - return 'enable' in policy.toolkits
85 - ? { enabled: policy.toolkits.enable }
86 - : { disabled: policy.toolkits.disable };
83 + const toolkits = policy.toolkits;
84 + if (!toolkits) return undefined;
85 + if ('enable' in toolkits) return { enabled: toolkits.enable };
86 + if ('disable' in toolkits) return { disabled: toolkits.disable };
87 + // An approval-only policy filters no toolkit.
88 + return undefined;
89 }
90
91 function sameToolkits(actual: unknown, expected: unknown): boolean {
ts/packages/cli/AGENTS.md
+1 -1
@@ -154,7 +154,7 @@ Steps 3–4 (and the TypeScript compiler they need) ship as the `generation-runt
154
155 ### Key Dependencies
156
157 -`effect` (pinned `4.0.3`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.21` via the workspace catalog; the CLI calls it through the `@composio/client/effect` entry point and imports only types from the rest of the package), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
157 +`effect` (pinned `4.0.3`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.22` via the workspace catalog; the CLI calls it through the `@composio/client/effect` entry point and imports only types from the rest of the package), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
158
159 ## Output Conventions: Composable CLI Output
160
ts/packages/cli/CHANGELOG.md
+8 -1
@@ -12,6 +12,13 @@
12
13 ### Patch Changes
14
15 +- A tool call or proxied request that a session hook blocks is now reported as
16 + a failure carrying the hook's message. `composio execute` prints it as a
17 + failed call (`successful: false`) with the message in `error`; on consumer
18 + projects, whose calls go through the Dashboard, it used to fail as a response
19 + the CLI could not read. `composio proxy` fails naming the hook instead of
20 + printing a response with no status.
21 +
22 - `composio connections list` now prints each account's `id`, its `alias`
23 whenever it has one (previously only when a toolkit had several accounts),
24 and `display_name` — the provider identity from `state.val.displayName`,
@@ -23,7 +30,7 @@
30 response does not match the shape this CLI expects, naming the mismatched
31 fields. They used to warn and continue with the unchecked response.
32
26 -- The CLI now uses `@composio/client@2.0.0-rc.21` (up from `2.0.0-rc.20`). No
33 +- The CLI now uses `@composio/client@2.0.0-rc.22` (up from `2.0.0-rc.20`). No
34 command changes.
35
36 - `composio dev triggers create` now accepts `--user-id` and sends it with the
ts/packages/cli/src/commands/logs/format.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import type { ToolListResponse, ToolRetrieveResponse } from '@composio/client/resources/logs';
1 +import type { ToolListResponse, ToolRetrieveResponse } from '@composio/client/resources/_internal/logs';
2 import type { TriggerLogRecord } from 'src/commands/logs/trigger-log-record';
3 import { bold, gray, green, red } from 'src/ui/colors';
4 import { truncate } from 'src/ui/truncate';
ts/packages/cli/src/commands/logs/tools/logs.tools.handler.ts
+2 -2
@@ -76,7 +76,7 @@ const showToolLog = (toolLogId: string) =>
76 const client = yield* (yield* ComposioClientSingleton).get();
77 const toolLog = yield* ui.withSpinner(
78 `Fetching tool log "${toolLogId}"...`,
79 - client.logs.tools
79 + client._internal.logs.tools
80 .retrieve(toolLogId, idempotent)
81 .pipe(failedWith(ToolLogsRequestError, `Failed to fetch tool log "${toolLogId}".`))
82 );
@@ -123,7 +123,7 @@ const listToolLogs = ({
123
124 const response = yield* ui.withSpinner(
125 'Fetching tool logs...',
126 - client.logs.tools
126 + client._internal.logs.tools
127 .list(
128 {
129 ...optionalParams({ from, to }),
ts/packages/cli/src/commands/logs/triggers/logs.triggers.handler.ts
+3 -3
@@ -1,4 +1,4 @@
1 -import type { TriggerListParams } from '@composio/client/resources/logs';
1 +import type { TriggerListParams } from '@composio/client/resources/_internal/logs';
2 import { Array as Arr, Effect, Option, String as Str } from 'effect';
3 import { CommandSurface } from 'src/commands/surface';
4 import { parseCsv } from 'src/commands/triggers/parse-csv';
@@ -51,7 +51,7 @@ const showTriggerLog = (triggerLogId: string) =>
51 const client = yield* (yield* ComposioClientSingleton).get();
52 const triggerLog = yield* ui.withSpinner(
53 `Fetching trigger log "${triggerLogId}"...`,
54 - client.logs.triggers
54 + client._internal.logs.triggers
55 .retrieve(triggerLogId, idempotent)
56 .pipe(failedWith(TriggerLogsRequestError, `Failed to fetch trigger log "${triggerLogId}".`))
57 );
@@ -92,7 +92,7 @@ const listTriggerLogs = ({
92
93 const response = yield* ui.withSpinner(
94 'Fetching trigger logs...',
95 - client.logs.triggers
95 + client._internal.logs.triggers
96 .list(
97 {
98 ...optionalParams({ cursor, from, to, time, search }),
ts/packages/cli/src/commands/proxy.cmd.ts
+21 -10
@@ -386,18 +386,29 @@ export const proxyCmd = Command.make('proxy', {
386 )
387 .pipe(
388 Effect.mapError(failed),
389 - Effect.flatMap(response =>
390 - response.result_type === 'input_required'
391 - ? Effect.fail(
392 - failed(
393 - toolInputRequiredError(
394 - `${normalizedMethod} proxy call via "${normalizedToolkit}"`,
395 - response
396 - )
389 + Effect.flatMap(response => {
390 + if (response.result_type === 'input_required') {
391 + return Effect.fail(
392 + failed(
393 + toolInputRequiredError(
394 + `${normalizedMethod} proxy call via "${normalizedToolkit}"`,
395 + response
396 )
397 )
399 - : Effect.succeed(response)
400 - ),
398 + );
399 + }
400 + // A session hook blocked the request: there is no HTTP
401 + // response to print, only the hook's message.
402 + if (response.result_type === 'blocked') {
403 + return Effect.fail(
404 + new ProxyRequestError({
405 + message: `${normalizedMethod} proxy call via "${normalizedToolkit}" was blocked by session hook "${response.reason.hook_id}": ${response.message}`,
406 + cause: response.reason,
407 + })
408 + );
409 + }
410 + return Effect.succeed(response);
411 + }),
412 Effect.matchEffect({
413 onFailure: error =>
414 handleProxyExecutionError({
ts/packages/cli/src/commands/tools/search/tools.search.handler.ts
+3
@@ -203,6 +203,9 @@ export const runToolsSearch = (params: ToolsSearchParams) =>
203 toolInputRequiredError('COMPOSIO_GET_TOOL_SCHEMAS', schemaResponse)
204 );
205 }
206 + if (schemaResponse.result_type === 'blocked') {
207 + return yield* schemasFailed(new Error(schemaResponse.message));
208 + }
209 if (schemaResponse.error) {
210 return yield* schemasFailed(new Error(schemaResponse.error));
211 }
ts/packages/cli/src/effects/request-error.ts
+1 -1
@@ -28,7 +28,7 @@ export const requestError = <Tag extends string>(
28 *
29 * @example
30 * ```ts
31 - * client.logs.tools.list(query, idempotent).pipe(failedWith(ToolLogsRequestError, 'Failed to fetch tool logs.'))
31 + * client._internal.logs.tools.list(query, idempotent).pipe(failedWith(ToolLogsRequestError, 'Failed to fetch tool logs.'))
32 * ```
33 */
34 export const failedWith =
ts/packages/cli/src/services/composio-account.ts
+9 -29
@@ -1,10 +1,10 @@
1 -import { Data, Effect, Predicate, String } from 'effect';
1 +import { Data, Effect, String } from 'effect';
2 import type { RequestOptions } from '@composio/client/effect';
3 import type { OrgListResponse, ProjectListResponse } from '@composio/client/resources/org';
4 import type {
5 ConsumerListConnectedToolkitsResponse,
6 ProjectResolveResponse,
7 -} from '@composio/client/resources/org/consumer';
7 +} from '@composio/client/resources/_internal/org/consumer';
8 import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
9 import { LatestToolVersionResponse } from 'src/models/tools';
10 import { ComposioClientSingleton } from './composio-clients';
@@ -39,32 +39,12 @@ const requireSessionProject = (
39 )
40 : Effect.succeed({ ...info, project: info.project });
41
42 -/**
43 - * The org member's user id, falling back to the member id. The backend still
44 - * sends `org_member.user_id` although the v3.1 spec omits it, and the persisted
45 - * test user id derives from it, so it is read defensively.
46 - */
47 -export const sessionUserIdOf = (info: SessionInfoResponse): string => {
48 - const member: object = info.org_member;
49 - return Predicate.hasProperty(member, 'user_id') && Predicate.isString(member.user_id)
50 - ? member.user_id
51 - : info.org_member.id;
52 -};
42 +/** The org member's id. The persisted playground test user id derives from it. */
43 +export const sessionUserIdOf = (info: SessionInfoResponse): string => info.org_member.id;
44
54 -/**
55 - * The project API key carried by a session, or null. The v3.1 spec names the
56 - * field `key`, and older responses spell it `api_key`; reading both keeps
57 - * `composio dev init` from minting a second key when the backend sends the
58 - * older spelling.
59 - */
60 -export const sessionProjectApiKeyOf = (info: SessionInfoResponse): string | null => {
61 - const apiKey: object | null = info.api_key;
62 - if (apiKey === null) return null;
63 - if (Predicate.hasProperty(apiKey, 'api_key') && Predicate.isString(apiKey.api_key)) {
64 - return apiKey.api_key;
65 - }
66 - return info.api_key?.key ?? null;
67 -};
45 +/** The project API key carried by a session, or null. */
46 +export const sessionProjectApiKeyOf = (info: SessionInfoResponse): string | null =>
47 + info.api_key?.key ?? null;
48
49 /**
50 * A single project entry returned by GET /api/v3.1/org/project/list.
@@ -280,7 +260,7 @@ export const resolveConsumerProject = (params: {
260 Effect.gen(function* () {
261 const clientSingleton = yield* ComposioClientSingleton;
262 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
283 - return yield* client.org.consumer.project.resolve(
263 + return yield* client._internal.org.consumer.project.resolve(
264 {
265 'x-user-api-key': params.apiKey,
266 'x-org-id': params.orgId,
@@ -335,7 +315,7 @@ export const getConsumerConnectedToolkits = (params: {
315 Effect.gen(function* () {
316 const clientSingleton = yield* ComposioClientSingleton;
317 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
338 - return yield* client.org.consumer.listConnectedToolkits(
318 + return yield* client._internal.org.consumer.listConnectedToolkits(
319 {
320 user_id: params.consumerUserId,
321 'x-user-api-key': params.apiKey,
ts/packages/cli/src/services/composio-clients.ts
+9 -4
@@ -9,6 +9,9 @@ import {
9 type ComposioClientShape,
10 type ConfigurationError,
11 } from '@composio/client/effect';
12 +// Types `client._internal`: the CLI-only operations the spec tags `x-internal`
13 +// (login sessions, realtime credentials, logs, consumer projects).
14 +import type {} from '@composio/client/effect/internal';
15 import { Toolkit, Toolkits, ToolkitDetailed } from 'src/models/toolkits';
16 import { ToolsAsEnums, Tools } from 'src/models/tools';
17 import {
@@ -502,7 +505,7 @@ const makeComposioSessionRepository = Effect.gen(function* () {
505 */
506 createSession: (params?: { scope?: 'user' | 'project' }) =>
507 client.pipe(
505 - Effect.flatMap(c => c.cli.createSession({ scope: params?.scope ?? 'user' })),
508 + Effect.flatMap(c => c._internal.cli.createSession({ scope: params?.scope ?? 'user' })),
509 Effect.flatMap(decode(Session))
510 ),
511 /**
@@ -510,13 +513,15 @@ const makeComposioSessionRepository = Effect.gen(function* () {
513 */
514 getSession: (session: { id: string }) =>
515 client.pipe(
513 - Effect.flatMap(c => c.cli.getSession({ id: session.id }, idempotent)),
516 + Effect.flatMap(c => c._internal.cli.getSession({ id: session.id }, idempotent)),
517 Effect.flatMap(decode(RetrievedSession))
518 ),
519 getRealtimeCredentials: () =>
517 - Effect.flatMap(client, c => c.cli.realtime.credentials({ ...idempotent, ...validated })),
520 + Effect.flatMap(client, c =>
521 + c._internal.cli.realtime.credentials({ ...idempotent, ...validated })
522 + ),
523 authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
519 - Effect.flatMap(client, c => c.cli.realtime.auth(params, idempotent)),
524 + Effect.flatMap(client, c => c._internal.cli.realtime.auth(params, idempotent)),
525 };
526 });
527
ts/packages/cli/src/services/dashboard-tool-execution.ts
+3 -3
@@ -63,10 +63,10 @@ export type DashboardExecutionResult = Exclude<
63
64 // The backend's answer is relayed as the backend sent it. Like the backend
65 // transport, the CLI checks only what tells a result from a request for input:
66 -// the tool has already run, so a missing field must not turn its result into
67 -// an error.
66 +// the tool has already run (or a session hook blocked it), so a missing field
67 +// must not turn its result into an error.
68 const ExecutionResult = Schema.StructWithRest(
69 - Schema.Struct({ result_type: Schema.Literals(['completed', 'failed']) }),
69 + Schema.Struct({ result_type: Schema.Literals(['completed', 'failed', 'blocked']) }),
70 [JsonObject]
71 );
72
ts/packages/cli/src/services/tools-executor.ts
+9 -4
@@ -136,7 +136,7 @@ export const ToolsExecutor = Context.Service<ToolsExecutor>('services/ToolsExecu
136 * session executions.
137 */
138 export const isExecutionSuccessful = (raw: {
139 - readonly result_type: 'completed' | 'failed';
139 + readonly result_type: 'completed' | 'failed' | 'blocked';
140 }): boolean => raw.result_type === 'completed';
141
142 /** A Tool Router answer that carries a result rather than a request for more input. */
@@ -170,11 +170,16 @@ export const normalizeResponse = (
170 raw: ExecutedSessionResponse,
171 permissionGateResult?: PermissionGateResult
172 ): ToolExecuteResponse => {
173 + // A call a session hook blocked carries the hook's message instead of a
174 + // result. Like `@composio/core`, the CLI reports it as a failed call with
175 + // that message.
176 + const outcome =
177 + raw.result_type === 'blocked'
178 + ? { data: {}, error: raw.message, logId: raw.log_id ?? '' }
179 + : { data: raw.data, error: raw.error, logId: raw.log_id };
180 const response: ToolExecuteResponse = {
181 successful: isExecutionSuccessful(raw),
175 - data: raw.data,
176 - error: raw.error,
177 - logId: raw.log_id,
182 + ...outcome,
183 ...(permissionGateResult?.approvalStatus
184 ? { permissionApproval: permissionGateResult.approvalStatus }
185 : {}),
ts/packages/cli/src/services/triggers-realtime.ts
+3 -3
@@ -13,7 +13,7 @@ import { JsonRecordSchema } from 'src/effects/json';
13 import type {
14 RealtimeAuthResponse as CliRealtimeAuthResponse,
15 RealtimeCredentialsResponse as CliRealtimeCredentialsResponse,
16 -} from '@composio/client/resources/cli';
16 +} from '@composio/client/resources/_internal/cli';
17 import { ComposioClientSingleton, ComposioSessionRepository } from 'src/services/composio-clients';
18 import { idempotent, validated } from 'src/services/composio-request';
19
@@ -297,11 +297,11 @@ const makeTriggersRealtime = Effect.gen(function* () {
297
298 return yield* listenWith({
299 getRealtimeCredentials: () =>
300 - client.cli.realtime
300 + client._internal.cli.realtime
301 .credentials({ ...idempotent, ...validated })
302 .pipe(Effect.mapError(subscriptionError('Failed to fetch realtime credentials'))),
303 authRealtimeChannel: params =>
304 - client.cli.realtime
304 + client._internal.cli.realtime
305 .auth(params, idempotent)
306 .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),
307 onEvent,
ts/packages/cli/src/utils/optional-params.ts
+1 -1
@@ -14,7 +14,7 @@ export type OptionalParams<R extends Readonly<Record<string, Option.Option<unkno
14 * `Option.getOrUndefined` per field at the call site.
15 *
16 * @example
17 - * client.logs.triggers.list({ ...optionalParams({ cursor, from, to }), limit })
17 + * client._internal.logs.triggers.list({ ...optionalParams({ cursor, from, to }), limit })
18 */
19 export const optionalParams = <const R extends Readonly<Record<string, Option.Option<unknown>>>>(
20 flags: R
ts/packages/cli/test/__utils__/layers/accounts.ts
+29 -25
@@ -140,35 +140,39 @@ export const mockAccountResources = (accountData: AccountTestData, base: MockReq
140 );
141 },
142 },
143 - consumer: {
144 - project: {
145 - resolve: (
146 - params: { 'x-user-api-key': string; 'x-org-id': string },
143 + },
144 + _internal: {
145 + org: {
146 + consumer: {
147 + project: {
148 + resolve: (
149 + params: { 'x-user-api-key': string; 'x-org-id': string },
150 + options?: RequestOptions
151 + ) => {
152 + record('org.consumer.project.resolve', options, params);
153 + const orgId = params['x-org-id'];
154 + return Effect.succeed({
155 + project_id: 'consumer_project_id_test',
156 + project_nano_id: 'consumer_project_test',
157 + project_name: 'Consumer Project',
158 + org_id: orgId,
159 + project_type: 'CONSUMER' as const,
160 + config: { consumer_experience_enabled: true, enhanced_controls: false },
161 + consumer_user_id: `consumer-user-${orgId}`,
162 + });
163 + },
164 + },
165 + listConnectedToolkits: (
166 + params: { user_id: string; 'x-user-api-key': string; 'x-org-id': string },
167 options?: RequestOptions
168 ) => {
149 - record('org.consumer.project.resolve', options, params);
150 - const orgId = params['x-org-id'];
151 - return Effect.succeed({
152 - project_id: 'consumer_project_id_test',
153 - project_nano_id: 'consumer_project_test',
154 - project_name: 'Consumer Project',
155 - org_id: orgId,
156 - project_type: 'CONSUMER' as const,
157 - config: { consumer_experience_enabled: true, enhanced_controls: false },
158 - consumer_user_id: `consumer-user-${orgId}`,
159 - });
169 + record('org.consumer.listConnectedToolkits', options, params);
170 + return withTestData(
171 + accountData.connectedToolkits,
172 + 'org.consumer.listConnectedToolkits'
173 + ).pipe(Effect.map(toolkits => ({ toolkits: [...toolkits] })));
174 },
175 },
162 - listConnectedToolkits: (
163 - params: { user_id: string; 'x-user-api-key': string; 'x-org-id': string },
164 - options?: RequestOptions
165 - ) => {
166 - record('org.consumer.listConnectedToolkits', options, params);
167 - return withTestData(
168 - accountData.connectedToolkits,
169 - 'org.consumer.listConnectedToolkits'
170 - ).pipe(Effect.map(toolkits => ({ toolkits: [...toolkits] })));
171 - },
176 },
177 },
178 auth: {
ts/packages/cli/test/__utils__/layers/agents.ts
-1
@@ -39,7 +39,6 @@ const clientFor = (scope: MockRequestScope): ComposioClientShape =>
39 orgId: scope.orgId ?? 'org_agent',
40 orgName: 'Agent Org',
41 orgMemberId: 'mem_agent',
42 - userId: 'user_agent',
42 email: 'agent@agent.composio.ai',
43 }),
44 },
ts/packages/cli/test/__utils__/models/account.ts
-3
@@ -15,7 +15,6 @@ export const makeSessionInfo = (
15 readonly projectNanoId?: string;
16 readonly projectName?: string;
17 readonly orgMemberId?: string;
18 - readonly userId?: string;
18 readonly email?: string;
19 readonly name?: string;
20 readonly apiKey?: string;
@@ -64,8 +63,6 @@ export const makeSessionInfo = (
63 name: params.name ?? 'CLI User',
64 role: 'admin',
65 metadata: {},
67 - // Sent by the backend although the v3.1 spec omits it.
68 - ...(params.userId === undefined ? {} : { user_id: params.userId }),
66 },
67 };
68 };
ts/packages/cli/test/src/commands/login/login.cmd.test.ts
-4
@@ -424,13 +424,11 @@ describe('CLI: composio login', () => {
424 ? makeSessionInfo({
425 orgId: 'org_default',
426 orgMemberId: 'member_default',
427 - userId: 'user_123',
427 })
428 : makeSessionInfo({
429 orgId: scope.orgId,
430 orgName: 'Selected Org',
431 orgMemberId: 'member_selected',
433 - userId: 'user_123',
432 }),
433 onRequest: request => directLoginRequests.push(request),
434 },
@@ -509,7 +507,6 @@ describe('CLI: composio login', () => {
507 orgId: 'org_home',
508 orgName: 'Home Org',
509 orgMemberId: 'member_home',
512 - userId: 'user_123',
510 email: 'poll@example.com',
511 name: 'Poll User',
512 })
@@ -517,7 +514,6 @@ describe('CLI: composio login', () => {
514 orgId: scope.orgId,
515 orgName: 'Selected Org',
516 orgMemberId: 'member_selected',
520 - userId: 'user_123',
517 email: 'poll@example.com',
518 name: 'Poll User',
519 });
ts/packages/cli/test/src/commands/login/login.handler.test.ts
+2 -4
@@ -81,7 +81,6 @@ const HOME_SESSION_INFO = makeSessionInfo({
81 orgId: 'org_home',
82 orgName: 'Home Org',
83 orgMemberId: 'member_home',
84 - userId: 'user_123',
84 email: 'cli@example.com',
85 });
86
@@ -93,7 +92,6 @@ const sessionInfoFor = (scope: MockRequestScope) =>
92 orgId: scope.orgId,
93 orgName: `${scope.orgId} name`,
94 orgMemberId: `member_${scope.orgId}`,
96 - userId: 'user_123',
95 email: 'cli@example.com',
96 });
97
@@ -389,7 +387,7 @@ describe('handlePollLogin', () => {
387 yield* handlePollLogin({ noSkillInstall: true });
388
389 expect(logins).toEqual([
392 - { apiKey: 'uak_linked', orgId: 'org_first', testUserId: 'pg-test-user_123' },
390 + { apiKey: 'uak_linked', orgId: 'org_first', testUserId: 'pg-test-member_org_first' },
391 ]);
392 expect(analytics.linked).toEqual(['member_org_first']);
393 expect(Option.isNone(pending.current())).toBe(true);
@@ -511,7 +509,7 @@ describe('handleDirectLogin', () => {
509 });
510
511 expect(logins).toEqual([
514 - { apiKey: 'uak_direct', orgId: 'org_second', testUserId: 'pg-test-user_123' },
512 + { apiKey: 'uak_direct', orgId: 'org_second', testUserId: 'pg-test-member_home' },
513 ]);
514 expect(outputs).toEqual([
515 JSON.stringify({ email: 'cli@example.com', org_id: 'org_second', org_name: 'Second Org' }),
ts/packages/cli/test/src/commands/logs/format.test.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import type { ToolListResponse, ToolRetrieveResponse } from '@composio/client/resources/logs';
1 +import type { ToolListResponse, ToolRetrieveResponse } from '@composio/client/resources/_internal/logs';
2 import { describe, expect, it } from 'vitest';
3 import {
4 formatTriggerLogInfo,
ts/packages/cli/test/src/commands/logs/tools/logs.tools.client.cmd.test.ts
+5 -5
@@ -43,7 +43,7 @@ describe('CLI: composio dev logs tools over the API client', () => {
43 layer(testLayer)('[Given] a page of tool logs', it => {
44 it.effect('[Then] the logs are listed as a table and printed as the API returned them', () =>
45 Effect.gen(function* () {
46 - const stub = stubClientResources(['logs'], () => Response.json(page));
46 + const stub = stubClientResources(['_internal'], () => Response.json(page));
47 yield* cli(['dev', 'logs', 'tools', '--toolkit', 'gmail']).pipe(Effect.provide(stub.layer));
48 const lines = yield* MockConsole.getLines({ stripAnsi: true });
49
@@ -87,7 +87,7 @@ describe('CLI: composio dev logs tools over the API client', () => {
87 },
88 ])('[Then] each user id is sent as a search param when passed $name', ({ args }) =>
89 Effect.gen(function* () {
90 - const stub = stubClientResources(['logs'], () => Response.json({ data: [] }));
90 + const stub = stubClientResources(['_internal'], () => Response.json({ data: [] }));
91 yield* cli(args).pipe(Effect.provide(stub.layer));
92
93 expect(stub.requests).toMatchObject([
@@ -107,7 +107,7 @@ describe('CLI: composio dev logs tools over the API client', () => {
107 layer(testLayer)('[Given] the API rejects the request', it => {
108 it.effect('[Then] the command fails with the status and response body as the cause', () =>
109 Effect.gen(function* () {
110 - const stub = stubClientResources(['logs'], () =>
110 + const stub = stubClientResources(['_internal'], () =>
111 Response.json(
112 { error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 } },
113 { status: 403 }
@@ -147,7 +147,7 @@ describe('CLI: composio dev logs tools over the API client', () => {
147 },
148 ],
149 };
150 - const stub = stubClientResources(['logs'], () => Response.json(driftedPage));
150 + const stub = stubClientResources(['_internal'], () => Response.json(driftedPage));
151 yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
152 const lines = yield* MockConsole.getLines({ stripAnsi: true });
153
@@ -179,7 +179,7 @@ describe('CLI: composio dev logs tools over the API client', () => {
179 payloadReceived: { recipient_email: 'a@b.c' },
180 response: { id: 'msg_1' },
181 };
182 - const stub = stubClientResources(['logs'], () => Response.json(driftedLog));
182 + const stub = stubClientResources(['_internal'], () => Response.json(driftedLog));
183 yield* cli(['dev', 'logs', 'tools', 'log_drift_1']).pipe(Effect.provide(stub.layer));
184 const lines = yield* MockConsole.getLines({ stripAnsi: true });
185
ts/packages/cli/test/src/commands/logs/tools/logs.tools.cmd.test.ts
+6 -6
@@ -79,7 +79,7 @@ describe('CLI: composio dev logs tools', () => {
79 it.effect('[Then] it warns and prints the empty page as the API returned it', () =>
80 Effect.gen(function* () {
81 const page = { data: [], nextCursor: null };
82 - const stub = stubClientResources(['logs'], () => Response.json(page));
82 + const stub = stubClientResources(['_internal'], () => Response.json(page));
83 yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
84 const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
85 const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
@@ -99,7 +99,7 @@ describe('CLI: composio dev logs tools', () => {
99 '[Then] each is sent as search params in a fixed order and the limit is clamped',
100 () =>
101 Effect.gen(function* () {
102 - const stub = stubClientResources(['logs'], () => Response.json({ data: [] }));
102 + const stub = stubClientResources(['_internal'], () => Response.json({ data: [] }));
103 yield* cli([
104 'dev',
105 'logs',
@@ -167,7 +167,7 @@ describe('CLI: composio dev logs tools', () => {
167 it.effect('[Then] it lists the logs, hints at the first one, and prints the cursor', () =>
168 Effect.gen(function* () {
169 const page = { data: [log], nextCursor: 42 };
170 - const stub = stubClientResources(['logs'], () => Response.json(page));
170 + const stub = stubClientResources(['_internal'], () => Response.json(page));
171 yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
172 const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
173 const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
@@ -186,7 +186,7 @@ describe('CLI: composio dev logs tools', () => {
186 it.effect('[Then] it fetches that log alone and prints it as the API returned it', () =>
187 Effect.gen(function* () {
188 const toolLog = { ...log, payloadReceived: { to: 'a@b.c' }, response: { id: 'msg_1' } };
189 - const stub = stubClientResources(['logs'], () => Response.json(toolLog));
189 + const stub = stubClientResources(['_internal'], () => Response.json(toolLog));
190 yield* cli(['dev', 'logs', 'tools', 'log_1']).pipe(Effect.provide(stub.layer));
191 const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
192 const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
@@ -203,7 +203,7 @@ describe('CLI: composio dev logs tools', () => {
203 layer(testLayer)('[Given] an empty log id argument', it => {
204 it.effect('[Then] it lists logs instead of fetching one', () =>
205 Effect.gen(function* () {
206 - const stub = stubClientResources(['logs'], () => Response.json({ data: [] }));
206 + const stub = stubClientResources(['_internal'], () => Response.json({ data: [] }));
207 yield* cli(['dev', 'logs', 'tools', '']).pipe(Effect.provide(stub.layer));
208
209 expect(stub.requests).toMatchObject([{ method: 'POST' }]);
@@ -214,7 +214,7 @@ describe('CLI: composio dev logs tools', () => {
214 layer(testLayer)('[Given] the API rejects the request for one log', it => {
215 it.effect('[Then] the failure names the log id', () =>
216 Effect.gen(function* () {
217 - const stub = stubClientResources(['logs'], () =>
217 + const stub = stubClientResources(['_internal'], () =>
218 Response.json(
219 { error: { message: 'Not found', code: 1404, slug: 'Not_Found', status: 404 } },
220 { status: 404 }
ts/packages/cli/test/src/commands/logs/triggers/logs.triggers.client.cmd.test.ts
+3 -3
@@ -27,7 +27,7 @@ describe('CLI: composio dev logs triggers over the API client', () => {
27 it.effect('[Then] the logs are listed and printed as the API returned them', () =>
28 Effect.gen(function* () {
29 const page = { data: [olderLog] };
30 - const stub = stubClientResources(['logs'], () => Response.json(page));
30 + const stub = stubClientResources(['_internal'], () => Response.json(page));
31 yield* cli(['dev', 'logs', 'triggers']).pipe(Effect.provide(stub.layer));
32 const lines = yield* MockConsole.getLines({ stripAnsi: true });
33
@@ -50,7 +50,7 @@ describe('CLI: composio dev logs triggers over the API client', () => {
50 },
51 ])('[Then] each user id is sent as a search param when passed $name', ({ args }) =>
52 Effect.gen(function* () {
53 - const stub = stubClientResources(['logs'], () => Response.json({ data: [] }));
53 + const stub = stubClientResources(['_internal'], () => Response.json({ data: [] }));
54 yield* cli(args).pipe(Effect.provide(stub.layer));
55
56 expect(JSON.stringify(stub.requests)).toContain(
@@ -66,7 +66,7 @@ describe('CLI: composio dev logs triggers over the API client', () => {
66 layer(testLayer)('[Given] one trigger log in an older response shape', it => {
67 it.effect('[Then] its details are shown and it is printed as the API returned it', () =>
68 Effect.gen(function* () {
69 - const stub = stubClientResources(['logs'], () => Response.json(olderLog));
69 + const stub = stubClientResources(['_internal'], () => Response.json(olderLog));
70 yield* cli(['dev', 'logs', 'triggers', 'log_older_1']).pipe(Effect.provide(stub.layer));
71 const lines = yield* MockConsole.getLines({ stripAnsi: true });
72
ts/packages/cli/test/src/commands/logs/triggers/logs.triggers.cmd.test.ts
+7 -7
@@ -25,7 +25,7 @@ describe('CLI: composio dev logs triggers', () => {
25 it.effect('[Then] it warns and prints the empty page as the API returned it', () =>
26 Effect.gen(function* () {
27 const page = { data: [] };
28 - const stub = stubClientResources(['logs'], () => Response.json(page));
28 + const stub = stubClientResources(['_internal'], () => Response.json(page));
29 yield* cli(['dev', 'logs', 'triggers']).pipe(Effect.provide(stub.layer));
30 const lines = yield* MockConsole.getLines({ stripAnsi: true });
31
@@ -42,7 +42,7 @@ describe('CLI: composio dev logs triggers', () => {
42 layer(testLayer)('[Given] every filter flag', it => {
43 it.effect('[Then] each is sent as search params in a fixed order and the limit is clamped', () =>
44 Effect.gen(function* () {
45 - const stub = stubClientResources(['logs'], () => Response.json({ data: [] }));
45 + const stub = stubClientResources(['_internal'], () => Response.json({ data: [] }));
46 yield* cli([
47 'dev',
48 'logs',
@@ -102,7 +102,7 @@ describe('CLI: composio dev logs triggers', () => {
102 it.effect('[Then] it lists the logs, hints at the first one, and prints the cursor', () =>
103 Effect.gen(function* () {
104 const page = { data: [log], nextCursor: 'cur_2' };
105 - const stub = stubClientResources(['logs'], () => Response.json(page));
105 + const stub = stubClientResources(['_internal'], () => Response.json(page));
106 yield* cli(['dev', 'logs', 'triggers']).pipe(Effect.provide(stub.layer));
107 const lines = yield* MockConsole.getLines({ stripAnsi: true });
108 const output = lines.join('\n');
@@ -119,7 +119,7 @@ describe('CLI: composio dev logs triggers', () => {
119 layer(testLayer)('[Given] a log id argument', it => {
120 it.effect('[Then] it fetches that log alone and prints it as the API returned it', () =>
121 Effect.gen(function* () {
122 - const stub = stubClientResources(['logs'], () => Response.json(log));
122 + const stub = stubClientResources(['_internal'], () => Response.json(log));
123 yield* cli(['dev', 'logs', 'triggers', 'log_1']).pipe(Effect.provide(stub.layer));
124 const lines = yield* MockConsole.getLines({ stripAnsi: true });
125
@@ -134,7 +134,7 @@ describe('CLI: composio dev logs triggers', () => {
134 layer(testLayer)('[Given] an empty log id argument', it => {
135 it.effect('[Then] it lists logs instead of fetching one', () =>
136 Effect.gen(function* () {
137 - const stub = stubClientResources(['logs'], () => Response.json({ data: [] }));
137 + const stub = stubClientResources(['_internal'], () => Response.json({ data: [] }));
138 yield* cli(['dev', 'logs', 'triggers', '']).pipe(Effect.provide(stub.layer));
139
140 expect(stub.requests).toMatchObject([{ method: 'POST' }]);
@@ -145,7 +145,7 @@ describe('CLI: composio dev logs triggers', () => {
145 layer(testLayer)('[Given] the API rejects the list request', it => {
146 it.effect('[Then] the command fails with TriggerLogsRequestError', () =>
147 Effect.gen(function* () {
148 - const stub = stubClientResources(['logs'], () =>
148 + const stub = stubClientResources(['_internal'], () =>
149 Response.json(
150 { error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 } },
151 { status: 403 }
@@ -167,7 +167,7 @@ describe('CLI: composio dev logs triggers', () => {
167 layer(testLayer)('[Given] the API rejects the request for one log', it => {
168 it.effect('[Then] the failure names the log id', () =>
169 Effect.gen(function* () {
170 - const stub = stubClientResources(['logs'], () =>
170 + const stub = stubClientResources(['_internal'], () =>
171 Response.json(
172 { error: { message: 'Not found', code: 1404, slug: 'Not_Found', status: 404 } },
173 { status: 404 }
ts/packages/cli/test/src/commands/proxy.cmd.test.ts
+40
@@ -357,4 +357,44 @@ describe('CLI: composio proxy', () => {
357 );
358 }
359 );
360 +
361 + layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
362 + '[Given] a session hook blocks the proxied request [Then] proxy fails with the hook message',
363 + it => {
364 + it.effect('reports the hook that blocked the request', () =>
365 + Effect.gen(function* () {
366 + const live = TestLive({
367 + baseConfigProvider: testConfigProvider,
368 + fixture: 'global-test-user-id',
369 + toolRouter: {
370 + proxyExecute: () =>
371 + Effect.succeed({
372 + result_type: 'blocked' as const,
373 + reason: { type: 'request_blocked' as const, hook_id: 'no_external_email' },
374 + message: 'Blocked by session policy: No external email',
375 + }),
376 + },
377 + });
378 +
379 + const { failure, output } = yield* Effect.gen(function* () {
380 + const failure = yield* cli([
381 + 'proxy',
382 + 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
383 + '--toolkit',
384 + 'gmail',
385 + '--skip-connection-check',
386 + ]).pipe(Effect.flip);
387 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
388 + return { failure, output: lines.join('\n') };
389 + }).pipe(Effect.provide(live));
390 +
391 + expect(failure).toMatchObject({ _tag: 'commands/ProxyRequestError' });
392 + expect(output).toContain(
393 + 'GET proxy call via \\"gmail\\" was blocked by session hook \\"no_external_email\\": Blocked by session policy: No external email'
394 + );
395 + expect(output).not.toContain('Status:');
396 + })
397 + );
398 + }
399 + );
400 });
ts/packages/cli/test/src/commands/request-failures.client.test.ts
+3 -3
@@ -52,21 +52,21 @@ const rejectedRequests: ReadonlyArray<{
52 {
53 command: 'dev logs tools <id>',
54 args: ['dev', 'logs', 'tools', 'log_1'],
55 - resources: ['logs'],
55 + resources: ['_internal'],
56 tag: 'commands/ToolLogsRequestError',
57 message: 'Failed to fetch tool log "log_1".',
58 },
59 {
60 command: 'dev logs triggers',
61 args: ['dev', 'logs', 'triggers'],
62 - resources: ['logs'],
62 + resources: ['_internal'],
63 tag: 'commands/TriggerLogsRequestError',
64 message: 'Failed to fetch trigger logs.',
65 },
66 {
67 command: 'dev logs triggers <id>',
68 args: ['dev', 'logs', 'triggers', 'log_1'],
69 - resources: ['logs'],
69 + resources: ['_internal'],
70 tag: 'commands/TriggerLogsRequestError',
71 message: 'Failed to fetch trigger log "log_1".',
72 },
ts/packages/cli/test/src/services/tools-executor.test.ts
+34
@@ -18,6 +18,7 @@ describe('isExecutionSuccessful', () => {
18 raw: { result_type: 'failed' as const, error: 'Boom' },
19 expected: false,
20 },
21 + { name: 'blocked', raw: { result_type: 'blocked' as const }, expected: false },
22 { name: 'completed', raw: { result_type: 'completed' as const, error: null }, expected: true },
23 ])('[Given] $name [Then] successful is $expected', ({ raw, expected }) => {
24 expect(isExecutionSuccessful(raw)).toBe(expected);
@@ -56,4 +57,37 @@ describe('normalizeResponse', () => {
57 logId: 'log_test',
58 });
59 });
60 +
61 + it('[Given] a call a session hook blocked [Then] it is a failed call with the hook message', () => {
62 + const response = normalizeResponse({
63 + result_type: 'blocked',
64 + reason: { type: 'request_blocked', hook_id: 'no_external_email' },
65 + message: 'Blocked by session policy: No external email',
66 + });
67 +
68 + expect(response).toEqual({
69 + successful: false,
70 + data: {},
71 + error: 'Blocked by session policy: No external email',
72 + logId: '',
73 + });
74 + });
75 +
76 + it('[Given] a blocked result of a call that ran [Then] it keeps the log id and the charge', () => {
77 + const response = normalizeResponse({
78 + result_type: 'blocked',
79 + reason: { type: 'response_blocked', hook_id: 'no_outside_data' },
80 + message: 'Blocked by session policy',
81 + log_id: 'log_456',
82 + instant_charge: { amount: '0.01', currency: 'USD', charged_by: 'composio' },
83 + });
84 +
85 + expect(response).toEqual({
86 + successful: false,
87 + data: {},
88 + error: 'Blocked by session policy',
89 + logId: 'log_456',
90 + instantCharge: { amount: '0.01', currency: 'USD', chargedBy: 'composio' },
91 + });
92 + });
93 });
ts/packages/core/src/lib/toolRouterParams.ts
+16 -23
@@ -167,13 +167,16 @@ export const transformToolRouterWorkbenchParams = transformToolRouterSandboxPara
167 * PATCH-safe variant of transformToolRouterManageConnectionsParams.
168 * Does NOT apply defaults — only includes fields explicitly present in the input.
169 */
170 -/** Widens the listed keys of a generated request type so `null` can travel on the wire. */
170 +/**
171 + * Widens the listed keys of a generated request type so `null` can travel on
172 + * the wire. The spec does not mark these nullable until ComposioHQ/platform#13157
173 + * lands.
174 + */
175 type WithNull<T, K extends keyof T> = Omit<T, K> & { [P in K]?: NonNullable<T[P]> | null };
176
177 /**
178 * `manage_connections` as sent by `session.update()`. Only the supplied
175 - * subfields travel; `callback_url: null` removes the stored callback, which
176 - * the generated client types as string-only.
179 + * subfields travel; `callback_url: null` removes the stored callback.
180 */
181 export type SessionPatchManageConnectionsBody = WithNull<
182 NonNullable<SessionPatchParams['manage_connections']>,
@@ -192,29 +195,20 @@ export type SessionPatchExperimentalBody = WithNull<
195 'permissions' | 'link_url_overwrite' | 'fast_mode' | 'submit_feedback'
196 >;
197
195 -/** A hook as the API takes it, in snake_case. The generated client does not type `hooks` yet. */
196 -export type SessionHookBody = {
197 - type: 'before_execute' | 'after_execute';
198 - id: string;
199 - name?: string;
200 - applies_to: 'all' | { toolkits: string[] };
201 - handler:
202 - | { type: 'condition_check'; condition: string; action: 'block' }
203 - | { type: 'prompt_injection_check'; action: 'block' };
204 -};
205 -
206 -/** Request body of `sessions.create()`: the generated `SessionCreateParams` plus `hooks`. */
207 -export type SessionCreateBody = SessionCreateParams & { hooks?: SessionHookBody[] };
208 -
209 -/** `hooks` as sent on create and update: `appliesTo` becomes `applies_to`. */
210 -export const transformToolRouterHooksParams = (hooks: ToolRouterHook[]): SessionHookBody[] =>
198 +/**
199 + * `hooks` as sent on create and update: `appliesTo` becomes `applies_to`.
200 + * Create and patch take the same hook shape.
201 + */
202 +export const transformToolRouterHooksParams = (
203 + hooks: ToolRouterHook[]
204 +): NonNullable<SessionCreateParams['hooks']> =>
205 hooks.map(({ appliesTo, ...hook }) => ({ ...hook, applies_to: appliesTo }));
206
207 /**
208 * Request body of `session.update()`. Extends the generated `SessionPatchParams`
215 - * with the nullable policy blocks (`null` removes the stored override), `hooks`
216 - * and the `expected_config_version` root precondition, none of which the
217 - * generated client types yet.
209 + * with the nullable policy blocks (`null` removes the stored override) and the
210 + * `expected_config_version` root precondition, which the spec does not declare
211 + * until ComposioHQ/platform#13157 lands.
212 */
213 export type SessionPatchBody = Omit<
214 WithNull<
@@ -226,7 +220,6 @@ export type SessionPatchBody = Omit<
220 manage_connections?: SessionPatchManageConnectionsBody | null;
221 multi_account?: SessionPatchMultiAccountBody | null;
222 experimental?: SessionPatchExperimentalBody | null;
229 - hooks?: SessionHookBody[] | null;
223 expected_config_version?: number;
224 };
225
ts/packages/core/src/models/ToolRouter.ts
+1 -2
@@ -53,7 +53,6 @@ import {
53 transformToolRouterInstantParams,
54 transformToolRouterProxyExecuteParams,
55 transformToolRouterHooksParams,
56 - type SessionCreateBody,
56 resolveToolRouterSandboxConfig,
57 } from '../lib/toolRouterParams';
58 import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
@@ -277,7 +276,7 @@ export class ToolRouter<
276 ])
277 );
278
280 - const payload: SessionCreateBody = {
279 + const payload: SessionCreateParams = {
280 user_id: userId,
281 auth_configs: routerConfig.authConfigs,
282 connected_accounts: connectedAccountsPayload,
ts/packages/core/src/models/ToolRouterSession.ts
+3 -2
@@ -896,8 +896,9 @@ export class ToolRouterSession<
896 () =>
897 this.client.toolRouter.session.patch(
898 this.sessionId,
899 - // The generated client does not type `expected_config_version` or
900 - // the nullable policy blocks; the body is serialized as-is.
899 + // `expected_config_version` and the nullable policy blocks are not in
900 + // the spec until ComposioHQ/platform#13157 lands; the body is
901 + // serialized as-is.
902 body as SessionPatchParams,
903 { ...requestOptions, maxRetries: 0 }
904 ),
ts/packages/core/src/types/sessionConfigs.types.ts
+17 -6
@@ -43,25 +43,36 @@ export type SessionConfigListResponse = z.infer<typeof SessionConfigListResponse
43 const SessionConfigTagPolicySchema = z.object({
44 enable: z.array(ToolRouterTagsParamSchema.element).optional(),
45 disable: z.array(ToolRouterTagsParamSchema.element).optional(),
46 + /** Tags whose tools need the user's approval before they run. */
47 + require_approval: z.array(ToolRouterTagsParamSchema.element).optional(),
48 });
49
50 +/** What in a policy entry needs the user's approval before it runs. */
51 +const requireApproval = { require_approval: z.array(z.string()).optional() };
52 +const ApprovalOnlyPolicySchema = z.object({ require_approval: z.array(z.string()) });
53 +
54 /**
55 * The access policy stored in a saved Session config, in the backend's
50 - * `enable`/`disable` shape. Toolkit slug keys and tag names are kept exactly
51 - * as the backend sends them.
56 + * `enable`/`disable`/`require_approval` shape. Toolkit slug keys and tag names
57 + * are kept exactly as the backend sends them.
58 */
59 export const SessionConfigPolicySchema = z.object({
60 toolkits: z
55 - .union([z.object({ enable: z.array(z.string()) }), z.object({ disable: z.array(z.string()) })])
61 + .union([
62 + z.object({ enable: z.array(z.string()), ...requireApproval }),
63 + z.object({ disable: z.array(z.string()), ...requireApproval }),
64 + ApprovalOnlyPolicySchema,
65 + ])
66 .optional(),
67 /** Per-toolkit tool policy, keyed by toolkit slug. */
68 tools: z
69 .record(
70 z.string(),
71 z.union([
62 - z.object({ enable: z.array(z.string()) }),
63 - z.object({ disable: z.array(z.string()) }),
64 - z.object({ tags: SessionConfigTagPolicySchema }),
72 + z.object({ enable: z.array(z.string()), ...requireApproval }),
73 + z.object({ disable: z.array(z.string()), ...requireApproval }),
74 + z.object({ tags: SessionConfigTagPolicySchema, ...requireApproval }),
75 + ApprovalOnlyPolicySchema,
76 ])
77 )
78 .optional(),
ts/packages/core/src/utils/transformers/sessionConfigs.ts
+2 -2
@@ -45,8 +45,8 @@ export const transformSessionConfig = (response: RawSessionConfig): SessionConfi
45 name: response.name,
46 description: response.description,
47 archived: response.archived,
48 - // The policy has no snake_case keys: copy it as-is so toolkit slugs
49 - // and tag names survive.
48 + // The policy keeps the backend's wire shape: copy it as-is so toolkit
49 + // slugs and tag names survive.
50 config: response.config,
51 createdAt: response.created_at,
52 updatedAt: response.updated_at,
ts/packages/core/src/utils/transformers/toolRouterResponseTransform.ts
+22 -74
@@ -8,53 +8,24 @@ import type {
8 import z from 'zod/v3';
9 import { ComposioToolInputRequiredError } from '../../errors/ToolRouterErrors';
10 import { ValidationError } from '../../errors/ValidationErrors';
11 -import {
12 - ToolRouterHookResultSchema,
13 - type ToolRouterSessionExecuteResponse,
14 - type ToolRouterSessionProxyExecuteResponse,
11 +import type {
12 + ToolRouterBlockReason,
13 + ToolRouterSessionExecuteResponse,
14 + ToolRouterSessionProxyExecuteResponse,
15 } from '../../types/toolRouter.types';
16
17 /**
18 * The `result_type` values of a call that ran. `input_required` and `blocked`
19 - * are handled before this is read. `hook_results` is validated in its own step
20 - * so a shape drift there doesn't read as an unknown `result_type`.
19 + * are handled before this is read.
20 */
21 const ExecutedResponseSchema = z.object({
22 result_type: z.enum(['completed', 'failed']),
23 });
24
26 -/** A call a session hook blocked. The generated client does not type it yet. */
27 -const BlockedResponseSchema = z.object({
28 - result_type: z.literal('blocked'),
29 - reason: z.object({
30 - type: z.enum(['request_blocked', 'response_blocked']),
31 - hook_id: z.string(),
32 - }),
33 - message: z.string(),
34 - // Only session execute carries these; session proxy execute leaves them out.
35 - log_id: z.string().optional(),
36 - instant_charge: z.unknown().optional(),
37 - hook_results: z.array(ToolRouterHookResultSchema).optional(),
38 -});
39 -type BlockedResponse = z.infer<typeof BlockedResponseSchema>;
40 -
41 -const IsBlockedSchema = z.object({ result_type: z.literal('blocked') });
42 -
43 -/**
44 - * Reads a `blocked` response, or returns `undefined` for any other
45 - * `result_type`. A `blocked` response that does not match its schema is
46 - * raised rather than read as a result.
47 - */
48 -function parseBlockedResponse(raw: unknown, subject: string): BlockedResponse | undefined {
49 - if (!IsBlockedSchema.safeParse(raw).success) return undefined;
50 - const blocked = BlockedResponseSchema.safeParse(raw);
51 - if (!blocked.success) {
52 - throw new ValidationError(`${subject} returned a malformed blocked response`, {
53 - cause: blocked.error,
54 - });
55 - }
56 - return blocked.data;
57 -}
25 +/** The `reason` of a call a session hook blocked, in camelCase. */
26 +const toBlockReason = (
27 + reason: Extract<SessionExecuteResponse, { result_type: 'blocked' }>['reason']
28 +): ToolRouterBlockReason => ({ type: reason.type, hookId: reason.hook_id });
29
30 /**
31 * Whether a session tool execution succeeded. `resultType` decides: a `failed`
@@ -251,25 +222,24 @@ export function transformSearchResponse(raw: RawSearchResponse) {
222 * Transforms a raw session execute API response to camelCase.
223 *
224 * @throws {ComposioToolInputRequiredError} If the tool asked for user input instead of running
254 - * @throws {ValidationError} If the response carries no `result_type`, one this SDK does not know, or malformed `hook_results`
225 + * @throws {ValidationError} If the response carries no `result_type`, or one this SDK does not know
226 */
227 export function transformExecuteResponse(
228 raw: SessionExecuteResponse,
229 toolSlug: string
230 ): ToolRouterSessionExecuteResponse {
231 assertNotInputRequired(raw, `Tool ${toolSlug}`);
261 - const blocked = parseBlockedResponse(raw, `Tool ${toolSlug}`);
262 - if (blocked) {
232 + if (raw.result_type === 'blocked') {
233 // The agent reads `error`, so a blocked call reaches it as a failed call
234 // with the hook's message.
235 return {
236 data: {},
267 - error: blocked.message,
268 - logId: blocked.log_id ?? '',
237 + error: raw.message,
238 + logId: raw.log_id ?? '',
239 resultType: 'blocked',
270 - blockReason: { type: blocked.reason.type, hookId: blocked.reason.hook_id },
271 - ...(blocked.hook_results !== undefined && { hookResults: blocked.hook_results }),
272 - ...(blocked.instant_charge !== undefined && { instantCharge: blocked.instant_charge }),
240 + blockReason: toBlockReason(raw.reason),
241 + ...(raw.hook_results !== undefined && { hookResults: raw.hook_results }),
242 + ...(raw.instant_charge !== undefined && { instantCharge: raw.instant_charge }),
243 };
244 }
245 const executed = ExecutedResponseSchema.safeParse(raw);
@@ -279,29 +249,16 @@ export function transformExecuteResponse(
249 { cause: executed.error }
250 );
251 }
282 - const hookResults = CompletedHookResultsSchema.safeParse(raw);
283 - if (!hookResults.success) {
284 - throw new ValidationError(`Tool ${toolSlug} returned malformed hook results`, {
285 - cause: hookResults.error,
286 - });
287 - }
252 return {
253 data: raw.data,
254 error: raw.error,
255 logId: raw.log_id,
256 resultType: executed.data.result_type,
257 ...(raw.instant_charge !== undefined && { instantCharge: raw.instant_charge }),
294 - ...(hookResults.data.hook_results !== undefined && {
295 - hookResults: hookResults.data.hook_results,
296 - }),
258 + ...(raw.hook_results !== undefined && { hookResults: raw.hook_results }),
259 };
260 }
261
300 -/** Hook results on a call that ran: session execute, or a proxied request that was sent. */
301 -const CompletedHookResultsSchema = z.object({
302 - hook_results: z.array(ToolRouterHookResultSchema).optional(),
303 -});
304 -
262 /**
263 * Projects a session proxy execute response onto the SDK's shape: a request a
264 * session hook blocked comes back as `resultType: 'blocked'` with no HTTP
@@ -312,21 +269,14 @@ export function transformProxyExecuteResponse(
269 subject: string
270 ): ToolRouterSessionProxyExecuteResponse {
271 assertNotInputRequired(raw, subject);
315 - const blocked = parseBlockedResponse(raw, subject);
316 - if (blocked) {
272 + if (raw.result_type === 'blocked') {
273 return {
274 resultType: 'blocked',
319 - blockReason: { type: blocked.reason.type, hookId: blocked.reason.hook_id },
320 - message: blocked.message,
321 - ...(blocked.hook_results !== undefined && { hookResults: blocked.hook_results }),
275 + blockReason: toBlockReason(raw.reason),
276 + message: raw.message,
277 + ...(raw.hook_results !== undefined && { hookResults: raw.hook_results }),
278 };
279 }
324 - const hookResults = CompletedHookResultsSchema.safeParse(raw);
325 - if (!hookResults.success) {
326 - throw new ValidationError(`${subject} returned malformed hook results`, {
327 - cause: hookResults.error,
328 - });
329 - }
280 return {
281 resultType: 'completed',
282 status: raw.status,
@@ -340,8 +290,6 @@ export function transformProxyExecuteResponse(
290 expiresAt: raw.binary_data.expires_at,
291 },
292 }),
343 - ...(hookResults.data.hook_results !== undefined && {
344 - hookResults: hookResults.data.hook_results,
345 - }),
293 + ...(raw.hook_results !== undefined && { hookResults: raw.hook_results }),
294 };
295 }
ts/packages/core/src/utils/transformers/toolkits.ts
+1 -1
@@ -152,7 +152,7 @@ export const transformToolkitRetrieveResponse = (
152 name: category.name,
153 })),
154 availableVersions: response.meta.available_versions,
155 - // appUrl: response.meta.app_url, @TODO Update the client type to include this
155 + ...(response.meta.app_url != null && { appUrl: response.meta.app_url }),
156 },
157 isLocalToolkit: response.is_local_toolkit,
158 composioManagedAuthSchemes: response.composio_managed_auth_schemes,
ts/packages/core/test/models/sessionConfigs.test.ts
+17
@@ -190,6 +190,23 @@ describe('SessionConfigs', () => {
190 expect('tags' in result.config).toBe(false);
191 });
192
193 + it('keeps the require_approval lists of a stored policy', async () => {
194 + const config = {
195 + toolkits: { require_approval: ['gmail'] },
196 + tools: {
197 + github: { enable: ['GITHUB_GET_REPO'], require_approval: ['GITHUB_GET_REPO'] },
198 + slack: { require_approval: ['SLACK_SEND_MESSAGE'] },
199 + google_calendar: { tags: { require_approval: ['destructiveHint'] } },
200 + },
201 + tags: { enable: ['readOnlyHint'], require_approval: ['destructiveHint'] },
202 + };
203 + mockClient.sessionConfigs.retrieve.mockResolvedValue({ ...rawConfig, config });
204 +
205 + const result = await sessionConfigs.get('sc_1');
206 +
207 + expect(result.config).toEqual(config);
208 + });
209 +
210 it.each(['', ' '])('rejects the id %j with a ValidationError and makes no call', async id => {
211 await expect(sessionConfigs.get(id)).rejects.toBeInstanceOf(ValidationError);
212 expect(mockClient.sessionConfigs.retrieve).not.toHaveBeenCalled();
ts/packages/core/test/models/sessionHooksExecution.test.ts
+12 -26
@@ -3,7 +3,6 @@ import ComposioClient, { Auth, createFetchTransport } from '@composio/client';
3 import { Tools } from '../../src/models/Tools';
4 import { ToolRouterSession } from '../../src/models/ToolRouterSession';
5 import { SessionContextImpl } from '../../src/models/SessionContext';
6 -import { ValidationError } from '../../src/errors';
6 import { MockProvider } from '../utils/mocks/provider.mock';
7
8 vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -149,26 +148,12 @@ describe('session execute when a hook blocks the call', () => {
148 });
149 });
150
152 - it('raises a blocked response that is missing its reason', async () => {
153 - const { reason: _reason, ...malformed } = blockedCall;
154 - const { client } = createClient(malformed);
151 + it('leaves hookResults out of a blocked call that reports none', async () => {
152 + const { hook_results: _hookResults, ...withoutHookResults } = blockedCall;
153 + const { client } = createClient(withoutHookResults);
154
156 - await expect(createSession(client).execute('GMAIL_SEND_EMAIL', {})).rejects.toThrow(
157 - ValidationError
158 - );
159 - });
160 -
161 - it('raises malformed hook results on a completed call as malformed hook results', async () => {
162 - const { client } = createClient({
163 - result_type: 'completed',
164 - data: { id: 'msg_1' },
165 - error: null,
166 - log_id: 'log_1',
167 - hook_results: [{ id: 'no_external_email', status: 'nope' }],
168 - });
169 -
170 - await expect(createSession(client).execute('GMAIL_SEND_EMAIL', {})).rejects.toThrow(
171 - 'returned malformed hook results'
155 + await expect(createSession(client).execute('GMAIL_SEND_EMAIL', {})).resolves.not.toHaveProperty(
156 + 'hookResults'
157 );
158 });
159 });
@@ -211,17 +196,18 @@ describe('session proxy execute when a hook blocks the request', () => {
196 });
197 });
198
214 - it('raises malformed hook results on a completed response as malformed hook results', async () => {
199 + it('returns the hook results of a request that was sent', async () => {
200 + const hookResults = [{ id: 'no_external_email', status: 'evaluated', outcome: 'continue' }];
201 const { client } = createClient({
202 result_type: 'completed',
203 status: 200,
204 data: { id: 'msg_1' },
219 - headers: {},
220 - hook_results: [{ id: 'no_external_email', status: 'nope' }],
205 + hook_results: hookResults,
206 });
207
223 - await expect(createSession(client).proxyExecute(proxyParams)).rejects.toThrow(
224 - 'returned malformed hook results'
225 - );
208 + await expect(createSession(client).proxyExecute(proxyParams)).resolves.toMatchObject({
209 + resultType: 'completed',
210 + hookResults,
211 + });
212 });
213 });
ts/packages/core/test/models/toolRouter.test.ts
+17
@@ -268,6 +268,23 @@ describe('ToolRouter', () => {
268 expect(bodies[1]).not.toHaveProperty('hooks');
269 });
270
271 + it('rejects a prompt injection check on a before_execute hook, as the API does', async () => {
272 + await expect(
273 + toolRouter.create(userId, {
274 + hooks: [
275 + {
276 + type: 'before_execute',
277 + id: 'block_injection',
278 + appliesTo: 'all',
279 + // @ts-expect-error a before_execute hook only takes a condition_check handler
280 + handler: { type: 'prompt_injection_check', action: 'block' },
281 + },
282 + ],
283 + })
284 + ).rejects.toThrow();
285 + expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled();
286 + });
287 +
288 it('rejects hooks together with a saved session config', async () => {
289 await expect(
290 toolRouter.create(
ts/packages/core/test/utils/transformers/toolkits.test.ts
+19
@@ -176,6 +176,25 @@ describe('transformToolkitRetrieveResponse', () => {
176 expect(details?.authHintUrl).toBe('https://shopify.dev/api-keys');
177 });
178
179 + it('maps meta.app_url to meta.appUrl', () => {
180 + const withAppUrl = {
181 + ...rawToolkit,
182 + meta: { ...rawToolkit.meta, app_url: 'https://shopify.com' },
183 + } as RawRetrieveResponse;
184 +
185 + expect(transformToolkitRetrieveResponse(withAppUrl).meta.appUrl).toBe('https://shopify.com');
186 + });
187 +
188 + it('omits meta.appUrl when the API sends app_url as null or leaves it out', () => {
189 + const withNullAppUrl = {
190 + ...rawToolkit,
191 + meta: { ...rawToolkit.meta, app_url: null },
192 + } as RawRetrieveResponse;
193 +
194 + expect(transformToolkitRetrieveResponse(withNullAppUrl).meta).not.toHaveProperty('appUrl');
195 + expect(transformToolkitRetrieveResponse(rawToolkit).meta).not.toHaveProperty('appUrl');
196 + });
197 +
198 /**
199 * `toEqual` treats a missing property and one holding `undefined` as equal, so
200 * these assertions use `toHaveProperty`. Creating the key unconditionally would
uv.lock
+4 -4
@@ -806,7 +806,7 @@ release = [
806 [package.metadata]
807 requires-dist = [
808 { name = "certifi", specifier = ">=2026.10.19" },
809 - { name = "composio-client", specifier = "==2.0.0rc21" },
809 + { name = "composio-client", specifier = "==2.0.0rc22" },
810 { name = "json-schema-to-pydantic", specifier = ">=0.4.11,<1" },
811 { name = "jsonschema", specifier = ">=4.23.0,<5" },
812 { name = "openai", specifier = ">=2.48.0,<4" },
@@ -857,16 +857,16 @@ requires-dist = [
857
858 [[package]]
859 name = "composio-client"
860 -version = "2.0.0rc21"
860 +version = "2.0.0rc22"
861 source = { registry = "https://pypi.org/simple" }
862 dependencies = [
863 { name = "httpx" },
864 { name = "pydantic" },
865 { name = "typing-extensions" },
866 ]
867 -sdist = { url = "https://files.pythonhosted.org/packages/27/ff/5b7d50aacf90bb0055af14898045322ef0d219cc280b0faae0146d7bdb66/composio_client-2.0.0rc21.tar.gz", hash = "sha256:b435e256462d0bfc8928ec45c85a456b2aa2fbef98d3801a3408140314777fc5", size = 566876, upload-time = "2026-10-22T15:16:21.759Z" }
867 +sdist = { url = "https://files.pythonhosted.org/packages/46/d5/49c1a94b0d3d1afe5460b433f0ab752e1cba06b7ca61ca8cfae6ebc0e704/composio_client-2.0.0rc22.tar.gz", hash = "sha256:0d8e0adaa202c5bcc6366dc0ab362b61fb1c664530cd2b262e3e8fbb9d5616cd", size = 579602, upload-time = "2026-10-23T13:22:27.64Z" }
868 wheels = [
869 - { url = "https://files.pythonhosted.org/packages/73/61/12a65736ee060bc333efea9ac242d1276380022fbdf3ee630ab336a28a2b/composio_client-2.0.0rc21-py3-none-any.whl", hash = "sha256:c9dabca054205e27dfc34150a829a771ea6d1d244e0988cd74318a07871c8eab", size = 452217, upload-time = "2026-10-22T15:16:19.622Z" },
869 + { url = "https://files.pythonhosted.org/packages/68/d1/cc5945b9bfebb141577cae13e6eecbb4fbff170e5049907c0fae0d06bf16/composio_client-2.0.0rc22-py3-none-any.whl", hash = "sha256:4400522de2311e3b69fa6dca68e55d905b22dfd0c841d873d9ca787e5d78419e", size = 466491, upload-time = "2026-10-23T13:22:25.339Z" },
870 ]
871
872 [[package]]