@devries-cameron20 / composio-1 / commits / 55ed9e2db
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.

feat(core)!: update owned clients to 2.0.0-rc.10 (#4775)

This PR: - updates `@composio/client` to `2.0.0-rc.10` and `composio-client` to `2.0.0rc10` (released from https://github.com/ComposioHQ/composio-client/pull/64 and https://github.com/ComposioHQ/composio-client/pull/68), with the lockfiles - handles the new `result_type: "input_required"` answer of session `execute` / `proxyExecute`: `ComposioToolInputRequiredError` (TypeScript) and `ToolInputRequiredError` (Python) carry the input requests and `request_state`; the CLI fails with a clear message instead of printing an empty result - fixes a Python provider-wrapped path that would have reported `successful: True` for a tool that never ran - derives `successful` from `result_type` when the API sends it (`failed` with no error text is no longer reported as success), in core, the CLI and Python; TypeScript `session.execute()` results gain an optional `resultType` - rethrows the input-required error from custom-tool wrappers instead of flattening it into a failed result, and rejects an input-required answer in the CLI run harness `proxy()` helper, which used to surface it as an empty HTTP 200 - keeps `requestState` out of error inspection and JSON serialization in TypeScript (non-enumerable; still readable as `error.requestState`) - replaces the SDK's own `instant` shims with the client's session config and Instant types, which now include `require_approval`-only `toolkits` / `tools` entries and `proxy_execute` - passes request options third to `custom.deleteToolkit`, ahead of the client removing the legacy overload (https://github.com/ComposioHQ/composio-client/issues/66) - adds a `minor` changeset for `@composio/core` and `@composio/slim`; the Python version is left for the release commit, per the repo convention (next would be 0.26.0) - breaking: - TypeScript: `ToolRouterSessionConfig` and `ToolRouterSessionConfigHistoryConfig` are the client's types; `instant` is always present, `toolkits` / `tools` entries can be `{ require_approval }`-only, and the config is returned as the API sent it (no runtime validation of `instant`, no stripping of `premium_usage`) - Python: `session.execute().instant_charge`, `session.config.instant` and `log.metadata.instant_charge` are models, not dicts (`charge.amount`, not `charge["amount"]`) - Python: `ToolRouterSessionExecuteResponse` and `ToolRouterSessionSearchResponse` alias the client's classes, and the `ToolRouterInstant*` shim names are gone from `composio.core.models.tool_router_session` ## Context The SDK cannot answer an input request yet: sending `input_responses` and `request_state` back on execute is not exposed, so the error is the conservative behaviour until that is designed. Not adopted here: `require_approval` and `proxy_execute` as SDK create/update inputs, `COMPOSIO_PROXY_EXECUTE` in the CLI's meta-tool list, and moving off the calls the API newly deprecates (`auth_configs.update_status`, `connected_accounts.update_status`, the `managed_by` query). ## Testing Against the published rc.10: `pnpm typecheck` (14/14 tasks), `pnpm lint`, core tests (1735 passed) and CLI tests (1450 passed), `pnpm validate:changesets`; Python `nox -s chk tst` on 3.12 (2217 passed, plus provider suites). Not run: e2e suites, provider package tests, the docs site build. ## Known gaps - `ts/packages/experimental` workbench Python helper posts to `/execute` and `/proxy_execute` over raw HTTP and does not read `result_type` - in a mixed local and remote multi-execute batch, an input-required answer from the remote half is still reported as per-tool failures - Python release notes (dict-to-model changes, removed `ToolRouterInstant*` names, `ToolInputRequiredError`) belong in the release commit's `docs/content/changelog` entry, per the repo convention

Alberto Schiabel committed Oct 8, 2026 at 01:18 UTC 55ed9e2db1e743c295a4c7ad55b76fd60232c3f3
48 files changed +1862 -337
.changeset/owned-client-rc10.md new
+16
@@ -0,0 +1,16 @@
1 +---
2 +'@composio/core': minor
3 +'@composio/slim': minor
4 +---
5 +
6 +Update the owned API client to `@composio/client@2.0.0-rc.10`.
7 +
8 +A session tool can now ask for user input, such as an approval, instead of running: the API answers the call with `result_type: "input_required"`. `session.execute()`, `session.proxyExecute()`, provider-wrapped session tools, and the `execute` / `proxyExecute` helpers passed to custom tools throw the new `ComposioToolInputRequiredError` in that case. A local custom tool whose body makes such a call lets the error through instead of returning it as a failed result. The error carries the questions on `inputRequests` and the opaque `request_state` on `requestState`. `requestState` is continuation state, so it is a non-enumerable property: read it as `error.requestState`, and `console.error(error)`, `util.inspect(error)` and `JSON.stringify(error)` leave it out. Nothing was executed and the call is not retried. The SDK does not submit answers yet.
9 +
10 +A tool that ran now reports `result_type` as `completed` or `failed`, and a failed execution can carry a `null` or empty `error`. `session.execute()` and the custom tool `execute` helper return it as the new optional `resultType`; read it rather than `error` to tell a failure from a success. Provider-wrapped session tools, provider tool calls bound to a session, and the merged `COMPOSIO_MULTI_EXECUTE_TOOL` result set `successful` from it, so a failure without error text is no longer reported as successful. `error` is returned as the API sent it. When the API sends no `result_type`, `successful` still follows the error text.
11 +
12 +Breaking changes:
13 +
14 +- `ToolRouterSessionConfig` (`session.config`, the result of `session.update()`) and `ToolRouterSessionConfigHistoryConfig` (`session.listConfigHistory()`) are now the client's own config types. `instant` is always present (`false` or the policy object) instead of optional.
15 +- In those config types, `toolkits` and each `tools` entry can be a `{ require_approval }`-only object, so a check for `enabled` or `disabled` no longer covers every case. `tags` can carry `require_approval`, and the config can carry `proxy_execute`.
16 +- The session config is returned as the API sent it. The SDK no longer validates `instant` at runtime or removes a `premium_usage` key.
docs/content/docs/instant-tools.mdx
+2 -2
@@ -189,7 +189,7 @@ With `instant.return_instant_charge` enabled (`instant.returnInstantCharge` in T
189 ```python
190 charge = result.instant_charge
191 if charge is not None:
192 - print(charge["amount"], charge["currency"], charge["charged_by"])
192 + print(charge.amount, charge.currency, charge.charged_by)
193 ```
194 </Tab>
195 <Tab value="TypeScript">
@@ -209,7 +209,7 @@ console.log(result.instantCharge ?? "No Instant charge");
209 </Tab>
210 </Tabs>
211
212 -The `InstantCharge` type is exported from `composio.types` and includes `amount`, `currency`, and `charged_by`. Python provider integrations and mixed local/remote multi-tool execution also preserve these charge details.
212 +The charge includes `amount`, `currency`, and `charged_by`. Python provider integrations and mixed local/remote multi-tool execution also preserve these charge details, as a dictionary typed by `InstantCharge` from `composio.types`.
213
214 ## Control Instant usage
215
pnpm-lock.yaml
+9 -9
@@ -28,8 +28,8 @@ catalogs:
28 specifier: ^5.20260922.1
29 version: 5.20260925.1
30 '@composio/client':
31 - specifier: 2.0.0-rc.9
32 - version: 2.0.0-rc.9
31 + specifier: 2.0.0-rc.10
32 + version: 2.0.0-rc.10
33 '@effect/language-service':
34 specifier: ^0.87.2
35 version: 0.87.2
@@ -975,7 +975,7 @@ importers:
975 dependencies:
976 '@composio/client':
977 specifier: 'catalog:'
978 - version: 2.0.0-rc.9
978 + version: 2.0.0-rc.10
979 '@composio/core':
980 specifier: workspace:*
981 version: link:../../packages/core
@@ -1226,7 +1226,7 @@ importers:
1226 version: link:../cli-keyring
1227 '@composio/client':
1228 specifier: 'catalog:'
1229 - version: 2.0.0-rc.9
1229 + version: 2.0.0-rc.10
1230 '@composio/core':
1231 specifier: workspace:*
1232 version: link:../core
@@ -1344,7 +1344,7 @@ importers:
1344 dependencies:
1345 '@composio/client':
1346 specifier: 'catalog:'
1347 - version: 2.0.0-rc.9
1347 + version: 2.0.0-rc.10
1348 '@composio/json-schema-to-zod':
1349 specifier: workspace:*
1350 version: link:../json-schema-to-zod
@@ -1740,7 +1740,7 @@ importers:
1740 dependencies:
1741 '@composio/client':
1742 specifier: 'catalog:'
1743 - version: 2.0.0-rc.9
1743 + version: 2.0.0-rc.10
1744 '@composio/json-schema-to-zod':
1745 specifier: workspace:*
1746 version: link:../json-schema-to-zod
@@ -2317,8 +2317,8 @@ packages:
2317 resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
2318 engines: {node: '>=0.1.90'}
2319
2320 - '@composio/client@2.0.0-rc.9':
2321 - resolution: {integrity: sha512-D70nP7Ai/Sc2tpuQislr4hhWKR5I3RVmw4zUKibZkvsihbfSS8rrYgUKpo2Kt4jo9AHDD8KtG48At8+KSUk8DA==}
2320 + '@composio/client@2.0.0-rc.10':
2321 + resolution: {integrity: sha512-HqQ+Cx2tHO759T0nB5xyAhCNLljAi83fPylO1sFO/hyco/LRfkDr24rF4lp6s30PKucRTFpGitL4W56RJMNfyQ==}
2322 engines: {node: '>=22'}
2323
2324 '@cspotcode/source-map-support@0.8.1':
@@ -7464,7 +7464,7 @@ snapshots:
7464 '@colors/colors@1.5.0':
7465 optional: true
7466
7467 - '@composio/client@2.0.0-rc.9': {}
7467 + '@composio/client@2.0.0-rc.10': {}
7468
7469 '@cspotcode/source-map-support@0.8.1':
7470 dependencies:
pnpm-workspace.yaml
+1 -1
@@ -34,7 +34,7 @@ catalog:
34 '@clack/prompts': '^1.8.1'
35 '@cloudflare/vitest-pool-workers': 0.22.0
36 '@cloudflare/workers-types': ^5.20260922.1
37 - '@composio/client': 2.0.0-rc.9
37 + '@composio/client': 2.0.0-rc.10
38 '@effect/language-service': ^0.87.2
39 '@effect/platform-bun': 4.0.0-rc.117
40 '@effect/vitest': 4.0.0-rc.117
python/composio/core/models/custom_tool_execution.py
+9 -1
@@ -17,7 +17,7 @@ import typing as t
17
18 from pydantic import ValidationError as PydanticValidationError
19
20 -from composio.exceptions import ValidationError
20 +from composio.exceptions import ToolInputRequiredError, ValidationError
21
22 from .custom_tool_types import (
23 CustomToolsMap,
@@ -81,6 +81,9 @@ def execute_custom_tool(
81
82 Validates input via the Pydantic model, calls the user's execute function,
83 and wraps the result into the standard response format.
84 +
85 + :raises ToolInputRequiredError: If a call the tool made through the session
86 + context needs user input before it can run.
87 """
88 handle = entry.handle
89
@@ -103,6 +106,11 @@ def execute_custom_tool(
106 "error": None,
107 "successful": True,
108 }
109 + except ToolInputRequiredError:
110 + # ``ctx.execute()`` / ``ctx.proxy_execute()`` asked for user input:
111 + # nothing ran. Flattening it into a failed result would drop the
112 + # questions and the request state the caller needs to answer them.
113 + raise
114 except Exception as e:
115 return {
116 "data": {},
python/composio/core/models/logs.py
+2 -2
@@ -36,7 +36,7 @@ class Logs(Resource):
36 :param time_range: Time window to search within.
37 :return: Matching logs plus a ``next_cursor`` for pagination. A charged
38 tool log has an exact USD string at
39 - ``log.metadata["instant_charge"]``.
39 + ``log.metadata.instant_charge``.
40
41 Example:
42 page = composio.logs.search(
@@ -58,7 +58,7 @@ class Logs(Resource):
58
59 :param id: The log id.
60 :return: The full log entry. For charged calls,
61 - ``log.metadata["instant_charge"]`` is the exact USD amount.
61 + ``log.metadata.instant_charge`` is the exact USD amount.
62
63 Example:
64 log = composio.logs.get("log_123")
python/composio/core/models/session_context.py
+21 -14
@@ -27,7 +27,7 @@ from composio.core.models.custom_tool_types import (
27 from composio.core.models.inline_custom_tools_payload import (
28 inline_custom_tools_execute_experimental,
29 )
30 -from composio.core.models.tools import _serialize_arguments
30 +from composio.core.models.tools import _serialize_arguments, require_executed
31 from composio.exceptions import ValidationError
32
33
@@ -84,13 +84,16 @@ def proxy_execute_impl(
84
85 # Disable retries: a proxied call is a non-idempotent write, and a silent
86 # retry after a read timeout can duplicate the side effect.
87 - response = client.without_retries.tool_router.session.proxy_execute(
88 - session_id=session_id,
89 - toolkit_slug=toolkit,
90 - endpoint=endpoint,
91 - method=method,
92 - body=body if body is not None else omit,
93 - parameters=api_params if api_params else omit,
87 + response = require_executed(
88 + client.without_retries.tool_router.session.proxy_execute(
89 + session_id=session_id,
90 + toolkit_slug=toolkit,
91 + endpoint=endpoint,
92 + method=method,
93 + body=body if body is not None else omit,
94 + parameters=api_params if api_params else omit,
95 + ),
96 + f"{method} proxy call for toolkit {toolkit}",
97 )
98
99 # ``status`` and ``size`` are ``float`` on the generated model and pydantic
@@ -160,6 +163,7 @@ class SessionContextImpl:
163 data=result["data"],
164 error=result["error"],
165 log_id="",
166 + result_type="completed" if result["successful"] else "failed",
167 )
168
169 assert_unambiguous_custom_tool_slug(self._custom_tools_map, tool_slug)
@@ -169,13 +173,16 @@ class SessionContextImpl:
173
174 # Disable retries: a session execution is a non-idempotent write, and a
175 # silent retry after a read timeout can duplicate the side effect.
172 - return self._client.without_retries.tool_router.session.execute(
173 - session_id=self._session_id,
174 - tool_slug=tool_slug,
175 - arguments=serialized,
176 - experimental=inline_custom_tools_execute_experimental(
177 - self._inline_custom_tools_payload
176 + return require_executed(
177 + self._client.without_retries.tool_router.session.execute(
178 + session_id=self._session_id,
179 + tool_slug=tool_slug,
180 + arguments=serialized,
181 + experimental=inline_custom_tools_execute_experimental(
182 + self._inline_custom_tools_payload
183 + ),
184 ),
185 + f"Tool {tool_slug}",
186 )
187
188 def proxy_execute(
python/composio/core/models/tool_router.py
+1 -2
@@ -1090,8 +1090,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1090 "user_id": user_id,
1091 }
1092 if instant is not None:
1093 - # The pinned generated client has no `instant` keyword yet.
1094 - create_params["extra_body"] = {"instant": instant}
1093 + create_params["instant"] = instant
1094
1095 # Build connections config
1096 connections_config: t.Dict[str, t.Any] = {
python/composio/core/models/tool_router_session.py
+57 -102
@@ -29,7 +29,6 @@ from composio_client.types.tool_router import (
29 from composio_client.types.tool_router.session_execute_response import (
30 SessionExecuteResponse,
31 )
32 -from pydantic import BaseModel
32
33 from composio import exceptions
34 from composio.client import HttpClient
@@ -71,9 +70,9 @@ from composio.core.models.tool_router_session_delete import (
70 delete_tool_router_session,
71 )
72 from composio.core.models.tools import (
74 - InstantCharge,
73 ToolExecuteParams,
74 ToolExecutionResponse,
75 + require_executed,
76 )
77 from composio.core.provider import TTool, TToolCollection
78 from composio.core.provider.base import BaseProvider
@@ -99,36 +98,13 @@ class ToolRouterSessionPreloadConfig:
98 tools: t.Union[t.List[str], t.Literal["all"]]
99
100
102 -class ToolRouterInstantResponseEnable(te.TypedDict):
103 - enabled: t.List[str]
104 -
105 -
106 -class ToolRouterInstantResponseDisable(te.TypedDict):
107 - disabled: t.List[str]
108 -
109 -
110 -class ToolRouterInstantResponse(te.TypedDict):
111 - """Stored Instant policy returned in Session config, using API field casing."""
112 -
113 - toolkits: te.NotRequired[
114 - t.Union[ToolRouterInstantResponseEnable, ToolRouterInstantResponseDisable]
115 - ]
116 - tools: te.NotRequired[
117 - t.Dict[
118 - str,
119 - t.Union[ToolRouterInstantResponseEnable, ToolRouterInstantResponseDisable],
120 - ]
121 - ]
122 - return_instant_charge: bool
123 -
124 -
101 class ToolRouterSessionConfig(t.Protocol):
126 - """Server-side Session config. New Instant fields are retained by the client
127 - as Pydantic extras until its generated response types adopt this contract.
128 - """
102 + """Server-side Session config, as the generated client models it."""
103
104 user_id: str
131 - instant: t.Union[t.Literal[False], ToolRouterInstantResponse]
105 + instant: t.Union[
106 + t.Literal[False], session_create_response.CurrentConfigInstantVariant1
107 + ]
108 auth_configs: t.Optional[t.Dict[str, str]]
109 connected_accounts: t.Optional[t.Dict[str, t.List[str]]]
110 execute: session_create_response.ConfigExecute
@@ -140,6 +116,7 @@ class ToolRouterSessionConfig(t.Protocol):
116 toolkits: t.Union[
117 session_create_response.ConfigToolkitsEnabled,
118 session_create_response.ConfigToolkitsDisabled,
119 + session_create_response.ConfigToolkitsRequireApproval,
120 None,
121 ]
122 tools: t.Optional[
@@ -149,10 +126,12 @@ class ToolRouterSessionConfig(t.Protocol):
126 session_create_response.ConfigToolsEnabled,
127 session_create_response.ConfigToolsDisabled,
128 session_create_response.ConfigToolsTags,
129 + session_create_response.ConfigToolsRequireApproval,
130 ],
131 ]
132 ]
133 workbench: t.Optional[session_create_response.ConfigWorkbench]
134 + proxy_execute: t.Optional[session_create_response.CurrentConfigProxyExecute]
135
136 def model_dump(self, **kwargs: t.Any) -> t.Dict[str, t.Any]: ...
137
@@ -177,45 +156,15 @@ class ToolRouterInstantConfig(te.TypedDict, total=False):
156 return_instant_charge: bool
157
158
180 -class ToolRouterSessionExecuteResponse(SessionExecuteResponse):
181 - """Result of :meth:`ToolRouterSession.execute`."""
182 -
183 - instant_charge: t.Optional[InstantCharge] = None
184 - """Present only when the Session sets
185 - ``instant.return_instant_charge`` and a charge is available."""
186 -
159 +ToolRouterSessionExecuteResponse = SessionExecuteResponse
160 +"""Result of :meth:`ToolRouterSession.execute`. ``instant_charge`` is present
161 +only when the Session sets ``instant.return_instant_charge`` and a charge is
162 +available."""
163
188 -class ToolRouterInstantAccount(BaseModel):
189 - """Tools served by the Composio Instant account for a toolkit."""
190 -
191 - allowed_tool_slugs: t.List[str]
192 -
193 -
194 -class ToolRouterToolkitConnectionStatus(
195 - session_search_response.ToolkitConnectionStatus
196 -):
197 - instant_account: t.Optional[ToolRouterInstantAccount] = None
198 -
199 -
200 -class ToolRouterSessionSearchResponse(session_search_response.SessionSearchResponse):
201 - """Session search result, including typed Instant account coverage."""
202 -
203 - # Narrows the generated list item type; `list` is invariant for mypy.
204 - toolkit_connection_statuses: t.List[ToolRouterToolkitConnectionStatus] # type: ignore[assignment]
205 -
206 -
207 -def _with_instant_account(status: t.Any) -> t.Any:
208 - if not isinstance(status, BaseModel):
209 - return status
210 - fields = dict(status)
211 - account = fields.get("instant_account")
212 - if isinstance(account, dict):
213 - fields["instant_account"] = ToolRouterInstantAccount.model_construct(
214 - _fields_set=set(account), **account
215 - )
216 - return ToolRouterToolkitConnectionStatus.model_construct(
217 - _fields_set=status.model_fields_set, **fields
218 - )
164 +ToolRouterSessionSearchResponse = session_search_response.SessionSearchResponse
165 +"""Session search result. A toolkit served by a Composio Instant account
166 +lists the covered tools at ``instant_account.allowed_tool_slugs`` on its
167 +connection status."""
168
169
170 class ToolRouterUpdateManageConnectionsConfig(te.TypedDict, total=False):
@@ -771,21 +720,25 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
720 remote_error = (
721 str(raw_remote_error) if raw_remote_error is not None else None
722 )
774 - has_any_error = any(r.get("error") for _, r in local_results) or bool(
775 - remote_error
723 + # A failed execution can carry no error text, so success is read from
724 + # each result's own verdict and not from the absence of an error message.
725 + has_any_failure = (
726 + any(not r["successful"] for _, r in local_results)
727 + or (remote_result is not None and remote_result.get("successful") is False)
728 + or bool(remote_error)
729 )
730 error_message = None
778 - if has_any_error:
731 + if has_any_failure:
732 error_message = (
780 - remote_error
781 - if remote_error is not None and failed == 0
782 - else f"{failed} out of {len(all_results)} tools failed"
733 + f"{failed} out of {len(all_results)} tools failed"
734 + if failed > 0
735 + else remote_error
736 )
737
738 merged: t.Dict[str, t.Any] = {
739 "data": merged_data,
740 "error": error_message,
788 - "successful": not has_any_error,
741 + "successful": not has_any_failure,
742 }
743 if remote_result and remote_result.get("instant_charge") is not None:
744 merged["instant_charge"] = remote_result["instant_charge"]
@@ -929,7 +882,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
882
883 Returns relevant tools for the given query with schemas and guidance.
884 """
932 - response = self._client.tool_router.session.search(
885 + return self._client.tool_router.session.search(
886 session_id=self.session_id,
887 queries=[{"use_case": query}],
888 model=model if model else omit,
@@ -937,18 +890,6 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
890 self._inline_custom_tools_payload
891 ),
892 )
940 - # The client already built the response without enforcing its schema.
941 - # Construct without revalidating so an unexpected field can't fail a
942 - # search; only the Instant account coverage gains a typed model.
943 - fields = dict(response)
944 - statuses = fields.get("toolkit_connection_statuses")
945 - if isinstance(statuses, list):
946 - fields["toolkit_connection_statuses"] = [
947 - _with_instant_account(status) for status in statuses
948 - ]
949 - return ToolRouterSessionSearchResponse.model_construct(
950 - _fields_set=response.model_fields_set, **fields
951 - )
893
894 def execute(
895 self,
@@ -970,7 +911,14 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
911 top-level field or define their own account-selection fields.
912
913 Both paths return a ``ToolRouterSessionExecuteResponse`` with ``data``,
973 - ``error``, ``log_id``, and ``instant_charge`` attributes.
914 + ``error``, ``log_id``, ``result_type``, and ``instant_charge``
915 + attributes. ``result_type`` is ``"completed"`` or ``"failed"``; a failed
916 + execution can carry a ``None`` or empty ``error``, so read
917 + ``result_type`` to tell the two apart. It is ``None`` when the API sent
918 + none.
919 +
920 + :raises ToolInputRequiredError: If the tool needs input from the user
921 + (for example an approval) before it can run. Nothing was executed.
922 """
923 # Check if this is a local tool (by original or final slug)
924 entry = find_custom_tool(self._custom_tools_map, tool_slug)
@@ -980,25 +928,25 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
928 data=result["data"],
929 error=result["error"],
930 log_id="",
931 + result_type="completed" if result["successful"] else "failed",
932 )
933
934 assert_unambiguous_custom_tool_slug(self._custom_tools_map, tool_slug)
935
936 # Disable retries: a session execution is a non-idempotent write, and a
937 # silent retry after a read timeout can duplicate the side effect.
989 - response = self._client.without_retries.tool_router.session.execute(
990 - session_id=self.session_id,
991 - tool_slug=tool_slug,
992 - arguments=arguments if arguments is not None else omit,
993 - account=account if account is not None else omit,
994 - experimental=inline_custom_tools_execute_experimental(
995 - self._inline_custom_tools_payload
938 + return require_executed(
939 + self._client.without_retries.tool_router.session.execute(
940 + session_id=self.session_id,
941 + tool_slug=tool_slug,
942 + arguments=arguments if arguments is not None else omit,
943 + account=account if account is not None else omit,
944 + experimental=inline_custom_tools_execute_experimental(
945 + self._inline_custom_tools_payload
946 + ),
947 ),
948 + f"Tool {tool_slug}",
949 )
998 - # The client already validated data/error/log_id and kept the
999 - # undeclared instant_charge as an extra. Construct without
1000 - # revalidating so a malformed charge can't fail an executed call.
1001 - return ToolRouterSessionExecuteResponse.model_construct(**dict(response))
950
951 def custom_tools(
952 self, *, toolkit: t.Optional[str] = None
@@ -1094,6 +1042,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1042 :param body: Request body (for POST, PUT, PATCH)
1043 :param parameters: Query/header parameters
1044 :returns: Proxied API response
1045 + :raises ToolInputRequiredError: If the call needs input from the user
1046 + before it can run. Nothing was executed.
1047 """
1048 return proxy_execute_impl(
1049 self._client,
@@ -1210,9 +1160,6 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1160 if isinstance(precondition, Omit)
1161 else {"expected_config_version": precondition}
1162 )
1213 - if not isinstance(instant, Omit):
1214 - # Send the new wire contract without passing the old generated keyword.
1215 - extra_body = {**(extra_body or {}), "instant": instant}
1163
1164 # The generated client does not type ``None`` for every policy block
1165 # although the API accepts it (it removes the stored override), nor the
@@ -1228,6 +1175,14 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1175 t.Union[t.Dict[str, session_patch_params.Tools], "Omit"], tools
1176 ),
1177 tags=t.cast(t.Union[session_patch_params.Tags, "Omit"], tags),
1178 + instant=t.cast(
1179 + t.Union[
1180 + t.Literal[False],
1181 + session_patch_params.CurrentInstantVariant1,
1182 + "Omit",
1183 + ],
1184 + instant,
1185 + ),
1186 auth_configs=t.cast(t.Union[t.Dict[str, str], "Omit"], auth_configs),
1187 connected_accounts=connected_accounts,
1188 manage_connections=t.cast(
python/composio/core/models/tools.py
+83 -13
@@ -7,6 +7,12 @@ from pathlib import Path
7
8 import typing_extensions as te
9 from composio_client import APIStatusError, omit
10 +from composio_client.types.tool_router.session_execute_response import (
11 + SessionExecuteInputRequiredResponse,
12 +)
13 +from composio_client.types.tool_router.session_proxy_execute_response import (
14 + SessionProxyExecuteInputRequiredResponse,
15 +)
16 from pydantic import BaseModel as PydanticBaseModel
17
18 from composio.client import HttpClient
@@ -30,6 +36,7 @@ from composio.core.provider.none_agentic import NonAgenticProvider
36 from composio.core.types import ToolkitVersionParam
37 from composio.exceptions import (
38 InvalidParams,
39 + ToolInputRequiredError,
40 ToolNotFoundError,
41 ToolVersionRequiredError,
42 )
@@ -114,6 +121,61 @@ def _serialize_arguments(arguments: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
121 return {k: _serialize_value(v) for k, v in arguments.items()}
122
123
124 +_ExecutedT = t.TypeVar("_ExecutedT")
125 +
126 +
127 +def require_executed(
128 + response: t.Union[
129 + _ExecutedT,
130 + SessionExecuteInputRequiredResponse,
131 + SessionProxyExecuteInputRequiredResponse,
132 + ],
133 + subject: str,
134 +) -> _ExecutedT:
135 + """Narrow an execute-family response to the variants that carry a result.
136 +
137 + ``input_required`` means the call did not run: it is raised as a
138 + :class:`~composio.exceptions.ToolInputRequiredError` instead of being
139 + returned as a result it is not.
140 + """
141 + if not isinstance(
142 + response,
143 + (SessionExecuteInputRequiredResponse, SessionProxyExecuteInputRequiredResponse),
144 + ):
145 + return response
146 + raise ToolInputRequiredError(
147 + subject,
148 + input_requests={
149 + request_id: {
150 + "type": request.type,
151 + "mode": request.mode,
152 + "message": request.message,
153 + "requested_schema": request.requested_schema,
154 + }
155 + for request_id, request in response.input_requests.items()
156 + },
157 + request_state=response.request_state,
158 + )
159 +
160 +
161 +def is_execution_successful(
162 + result_type: t.Optional[str], error: t.Optional[str]
163 +) -> bool:
164 + """Whether a session tool execution succeeded.
165 +
166 + ``result_type`` decides when the API sent one: a ``failed`` execution is
167 + not successful even when its ``error`` is ``None`` or empty. Without a
168 + known ``result_type``, for example from a server that predates it, an
169 + execution is successful when it carries no error text. The TypeScript SDK
170 + applies the same rule.
171 + """
172 + if result_type == "completed":
173 + return True
174 + if result_type == "failed":
175 + return False
176 + return not error
177 +
178 +
179 class InstantCharge(te.TypedDict):
180 """Instant usage charge reported for a Session tool execution."""
181
@@ -567,27 +629,35 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
629
630 # Disable retries: a session execution is a non-idempotent write, and a
631 # silent retry after a read timeout can duplicate the side effect.
570 - response = self._client.without_retries.tool_router.session.execute(
571 - session_id=session_id,
572 - tool_slug=slug,
573 - arguments=processed_arguments,
574 - # Provider-wrapped session tools are agentic calls, so they opt into
575 - # direct tool offload when the backend session workbench allows it.
576 - enable_auto_workbench_offload=True,
577 - experimental=inline_custom_tools_execute_experimental(
578 - inline_custom_tools_payload
632 + response = require_executed(
633 + self._client.without_retries.tool_router.session.execute(
634 + session_id=session_id,
635 + tool_slug=slug,
636 + arguments=processed_arguments,
637 + # Provider-wrapped session tools are agentic calls, so they opt into
638 + # direct tool offload when the backend session workbench allows it.
639 + enable_auto_workbench_offload=True,
640 + experimental=inline_custom_tools_execute_experimental(
641 + inline_custom_tools_payload
642 + ),
643 ),
644 + f"Tool {slug}",
645 )
646
647 # Convert response to standard format
648 + error = response.error if hasattr(response, "error") else None
649 result: ToolExecutionResponse = {
650 "data": response.data if hasattr(response, "data") else {},
585 - "error": response.error if hasattr(response, "error") else None,
586 - "successful": not (hasattr(response, "error") and response.error),
651 + "error": error,
652 + "successful": is_execution_successful(
653 + getattr(response, "result_type", None), error
654 + ),
655 }
656 instant_charge = getattr(response, "instant_charge", None)
589 - if isinstance(instant_charge, dict):
590 - result["instant_charge"] = t.cast(InstantCharge, instant_charge)
657 + if isinstance(instant_charge, PydanticBaseModel):
658 + result["instant_charge"] = t.cast(
659 + InstantCharge, instant_charge.model_dump()
660 + )
661
662 # Apply after_execute modifiers
663 if modifiers is not None:
python/composio/core/provider/base.py
+6 -1
@@ -121,9 +121,14 @@ class BaseProvider(t.Generic[TTool, TToolCollection]):
121 "Direct execution modifiers cannot be used with a Tool Router session"
122 )
123
124 + # Imported here: the tools module imports this one.
125 + from composio.core.models.tools import is_execution_successful
126 +
127 result = target.execute(tool_slug=slug, arguments=arguments)
128 return {
129 "data": t.cast(t.Dict, result.data),
130 "error": result.error,
128 - "successful": result.error is None,
131 + "successful": is_execution_successful(
132 + getattr(result, "result_type", None), result.error
133 + ),
134 }
python/composio/exceptions.py
+50
@@ -5,6 +5,8 @@ Composio exceptions.
5 import difflib
6 import typing as t
7
8 +import typing_extensions as te
9 +
10 from composio_client import ComposioDeprecationWarning as ComposioDeprecationWarning
11
12 ENV_COMPOSIO_API_KEY = "COMPOSIO_API_KEY"
@@ -382,6 +384,54 @@ class SessionConfigConflictError(ComposioClientError):
384 self.expected_config_version = expected_config_version
385
386
387 +class ToolInputRequest(te.TypedDict):
388 + """One question a tool asks the user before it can run."""
389 +
390 + type: str
391 + """Kind of input requested, currently ``"elicitation"``."""
392 + mode: str
393 + """How the client collects the input, currently ``"form"``."""
394 + message: str
395 + """Message to show the user."""
396 + requested_schema: t.Dict[str, t.Any]
397 + """JSON Schema for the answer: a flat object with string, number, boolean
398 + or enum fields."""
399 +
400 +
401 +class ToolInputRequiredError(ComposioClientError):
402 + """Raised when a session tool execution or proxied call did not run
403 + because it needs input from the user first, for example an approval. The
404 + API answers such a call with ``result_type: "input_required"`` instead of
405 + a result.
406 +
407 + ``input_requests`` holds the questions, keyed by the ID the answers must
408 + reuse. ``request_state`` is the opaque state the API returned; when present
409 + it must be sent back unchanged together with the answers. The SDK does not
410 + submit answers yet, so nothing was executed and the call is not retried.
411 +
412 + ``request_state`` is continuation state, so it is kept out of logs: read it
413 + as an attribute. ``str()``, ``repr()``, ``args`` and a formatted traceback
414 + do not include it.
415 + """
416 +
417 + def __init__(
418 + self,
419 + subject: str,
420 + *,
421 + input_requests: t.Dict[str, ToolInputRequest],
422 + request_state: t.Optional[str] = None,
423 + ) -> None:
424 + count = len(input_requests)
425 + super().__init__(
426 + f"{subject} requires user input before it can run "
427 + f"({count} input request{'' if count == 1 else 's'}) and was not "
428 + "executed. The questions are on `input_requests` and the opaque "
429 + "`request_state` to send back with the answers is on `request_state`."
430 + )
431 + self.input_requests = input_requests
432 + self.request_state = request_state
433 +
434 +
435 class ResourceError(ComposioClientError):
436 pass
437
python/providers/claude_agent_sdk/uv.lock
+5 -5
@@ -474,7 +474,7 @@ name = "exceptiongroup"
474 version = "1.3.1"
475 source = { registry = "https://pypi.org/simple" }
476 dependencies = [
477 - { name = "typing-extensions", marker = "python_full_version < '3.11'" },
477 + { name = "typing-extensions" },
478 ]
479 sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }
480 wheels = [
@@ -508,8 +508,8 @@ name = "httpcore2"
508 version = "2.13.0"
509 source = { registry = "https://pypi.org/simple" }
510 dependencies = [
511 - { name = "h11", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" },
512 - { name = "truststore", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" },
511 + { name = "h11" },
512 + { name = "truststore" },
513 ]
514 sdist = { url = "https://files.pythonhosted.org/packages/15/8c/e925b1c92018abb3a1863ce1549d76d2381e334d21d65d4ac8f65dabd78a/httpcore2-2.13.0.tar.gz", hash = "sha256:2adc8be4fb285fbcd6d894298db3b52c177e74b6674eda3a76bd36be3292a3db", size = 67740, upload-time = "2026-09-14T14:18:04.717Z" }
515 wheels = [
@@ -1362,8 +1362,8 @@ name = "uvicorn"
1362 version = "0.53.0"
1363 source = { registry = "https://pypi.org/simple" }
1364 dependencies = [
1365 - { name = "click", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" },
1366 - { name = "h11", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" },
1365 + { name = "click" },
1366 + { name = "h11" },
1367 { name = "typing-extensions", marker = "python_full_version < '3.11'" },
1368 ]
1369 sdist = { url = "https://files.pythonhosted.org/packages/5d/ad/04bbb797c84fc1f26cb171f7394716f4865ffb8d8c5e1eef42565c2dfa6b/uvicorn-0.53.0.tar.gz", hash = "sha256:a9356f0cb89b3b8621529c5d5eebd69bfe154f4c3f68b4cf2de47e45fa855c2e", size = 110881, upload-time = "2026-09-14T07:44:23.815Z" }
python/pyproject.toml
+1 -1
@@ -7,7 +7,7 @@ requires-python = ">=3.10,<4"
7 dependencies = [
8 "pysher>=1.0.8",
9 "pydantic>=2.11.9",
10 - "composio-client==2.0.0rc9",
10 + "composio-client==2.0.0rc10",
11 "typing-extensions>=4.16.0",
12 "openai>=2.48.0",
13 "json-schema-to-pydantic>=0.4.11",
python/setup.py
+1 -1
@@ -25,7 +25,7 @@ setup(
25 install_requires=[
26 "pysher>=1.0.8",
27 "pydantic>=2.11.9",
28 - "composio-client==2.0.0rc9",
28 + "composio-client==2.0.0rc10",
29 "typing-extensions>=4.16.0",
30 "openai>=2.48.0",
31 "json-schema-to-pydantic>=0.4.11",
python/tests/test_custom_tools.py
+42 -1
@@ -954,6 +954,28 @@ def _session(deps, **overrides):
954
955
956 class TestToolRouterSessionCustomTools:
957 + def test_execute_local_failure_without_message_is_failed(self):
958 + @exp.tool()
959 + def silent(input: GrepInput, ctx):
960 + """Raises an error with no message."""
961 + raise RuntimeError("")
962 +
963 + s = ToolRouterSession(
964 + client=mock_http_client(MagicMock),
965 + provider=MagicMock(),
966 + dangerously_allow_auto_upload_download_files=True,
967 + session_id="s",
968 + mcp=MagicMock(),
969 + experimental=MagicMock(),
970 + custom_tools_map=build_custom_tools_map([silent]),
971 + user_id="u",
972 + )
973 +
974 + result = s.execute("SILENT", arguments={"pattern": "x"})
975 +
976 + assert result.error == ""
977 + assert result.result_type == "failed"
978 +
979 def test_execute_local(self, mock_session_deps):
980 s = _session(mock_session_deps)
981 result = s.execute("GREP", arguments={"pattern": "x"})
@@ -961,6 +983,7 @@ class TestToolRouterSessionCustomTools:
983 assert isinstance(result, SessionExecuteResponse)
984 assert result.error is None
985 assert result.log_id == ""
986 + assert result.result_type == "completed"
987 assert result.data["matches"] == ["x"]
988 mock_session_deps["client"].tool_router.session.execute.assert_not_called()
989
@@ -1005,7 +1028,8 @@ class TestToolRouterSessionCustomTools:
1028
1029 assert isinstance(result, ToolRouterSessionExecuteResponse)
1030 assert isinstance(result, SessionExecuteResponse)
1008 - assert result.instant_charge == charge
1031 + assert result.instant_charge is not None
1032 + assert result.instant_charge.model_dump() == charge
1033 assert result.data == {"sent": True}
1034 assert result.log_id == "log_123"
1035
@@ -1475,6 +1499,23 @@ class TestMultiExecuteRouting:
1499 assert result["successful"] is False
1500 assert result["data"]["results"][1]["error"] == "Remote tool execution failed"
1501
1502 + def test_failed_remote_batch_without_error_text_is_unsuccessful(self, grep_tool):
1503 + s = self._make_session(grep_tool)
1504 + tm = MagicMock()
1505 + remote = {"data": {}, "error": None, "successful": False}
1506 + tm._wrap_execute_tool_for_tool_router.return_value = lambda slug, args: remote
1507 + result = s._route_multi_execute(
1508 + {
1509 + "tools": [
1510 + {"tool_slug": "GREP", "arguments": {"pattern": "x"}},
1511 + {"tool_slug": "REMOTE", "arguments": {}},
1512 + ]
1513 + },
1514 + tm,
1515 + )
1516 + assert result["successful"] is False
1517 + assert result["error"] is None
1518 +
1519 def test_remote_batch_error_without_item_errors_uses_batch_message(self, grep_tool):
1520 s = self._make_session(grep_tool)
1521 tm = MagicMock()
python/tests/test_logs.py
+2 -2
@@ -46,7 +46,7 @@ class TestLogs:
46
47 result = logs.search()
48
49 - assert result.logs[0].metadata["instant_charge"] == "0.012"
49 + assert result.logs[0].metadata.instant_charge == "0.012"
50
51 def test_search_passes_params_through(self, logs, mock_client):
52 mock_client.logs.create_tool_execution.return_value = "page"
@@ -96,4 +96,4 @@ class TestLogs:
96
97 result = logs.get("log_1")
98
99 - assert result.metadata["instant_charge"] == "0.012"
99 + assert result.metadata.instant_charge == "0.012"
python/tests/test_tool_router.py
+387 -14
@@ -3,6 +3,7 @@
3 import json
4 import logging
5 import os
6 +import traceback
7 import typing as t
8 from unittest.mock import MagicMock, patch
9
@@ -34,10 +35,12 @@ from composio.core.models.tool_router_session import (
35 ToolRouterSession,
36 ToolRouterSessionWithMcp,
37 )
38 +from composio.core.models.session_context import SessionContextImpl
39 from composio.exceptions import (
40 InvalidParams,
41 MCPDestinationError,
42 SessionConfigConflictError,
43 + ToolInputRequiredError,
44 ValidationError,
45 )
46 from tests.conftest import mock_http_client
@@ -184,7 +187,7 @@ class TestToolRouter:
187 policy = {"toolkits": {"enable": ["exa"]}, "return_instant_charge": True}
188 tool_router.create(user_id="user_123", instant=policy)
189 kwargs = mock_client.tool_router.session.create.call_args.kwargs
187 - assert kwargs["extra_body"]["instant"] == policy
190 + assert kwargs["instant"] == policy
191 assert "premium_usage" not in kwargs
192
193 mock_client.tool_router.session.create.reset_mock()
@@ -196,10 +199,7 @@ class TestToolRouter:
199
200 tool_router.create(user_id="user_123", instant=False)
201 assert (
199 - mock_client.tool_router.session.create.call_args.kwargs["extra_body"][
200 - "instant"
201 - ]
202 - is False
202 + mock_client.tool_router.session.create.call_args.kwargs["instant"] is False
203 )
204
205 def test_create_session_default_returns_base_session(self, tool_router):
@@ -2333,7 +2333,8 @@ class TestInstantContractTransport:
2333 assert "instant" not in body
2334 else:
2335 assert body["instant"] == policy
2336 - assert session.config.instant == {"return_instant_charge": True}
2336 + assert not isinstance(session.config.instant, bool)
2337 + assert session.config.instant.return_instant_charge is True
2338 assert "premium_usage" not in session.config.model_dump()
2339
2340 if policy is None:
@@ -2347,11 +2348,13 @@ class TestInstantContractTransport:
2348 assert "instant" not in body
2349 else:
2350 assert body["instant"] == policy
2350 - assert session.config.instant == {"return_instant_charge": True}
2351 + assert not isinstance(session.config.instant, bool)
2352 + assert session.config.instant.return_instant_charge is True
2353 assert "premium_usage" not in session.config.model_dump()
2354
2355 attached = router.use(session_id="session_123")
2354 - assert attached.config.instant == {"return_instant_charge": True}
2356 + assert not isinstance(attached.config.instant, bool)
2357 + assert attached.config.instant.return_instant_charge is True
2358
2359 def test_execute_selector_charge_and_search_coverage(self):
2360 requests: t.List[httpx.Request] = []
@@ -2384,7 +2387,9 @@ class TestInstantContractTransport:
2387 )
2388 result = session.execute("EXA_SEARCH", arguments={}, account="instant_account")
2389 assert json.loads(requests[-1].content)["account"] == "instant_account"
2387 - assert result.instant_charge == charge
2390 + assert result.instant_charge is not None
2391 + assert result.instant_charge.amount == "0.012"
2392 + assert result.instant_charge.model_dump() == charge
2393 assert "premium_charge" not in result.model_dump()
2394 status = session.search(query="search").toolkit_connection_statuses[0]
2395 assert status.instant_account is not None
@@ -2420,6 +2425,377 @@ class TestInstantContractTransport:
2425 assert result.to_dict() == payload
2426
2427
2428 +_INPUT_REQUIRED_JSON: t.Dict[str, t.Any] = {
2429 + "result_type": "input_required",
2430 + "input_requests": {
2431 + "approval_1": {
2432 + "type": "elicitation",
2433 + "mode": "form",
2434 + "message": "Allow GMAIL_SEND_EMAIL to send this email?",
2435 + "requested_schema": {
2436 + "type": "object",
2437 + "properties": {"approved": {"type": "boolean"}},
2438 + "required": ["approved"],
2439 + },
2440 + }
2441 + },
2442 + "request_state": "opaque-state-token",
2443 +}
2444 +
2445 +_PROXY_PARAMS: t.Dict[str, t.Any] = {
2446 + "toolkit": "github",
2447 + "endpoint": "https://api.github.com/user/repos?token=secret",
2448 + "method": "POST",
2449 + "body": {"name": "repo"},
2450 +}
2451 +
2452 +
2453 +def _answering_client(
2454 + body: t.Dict[str, t.Any],
2455 +) -> t.Tuple[HttpClient, t.List[httpx.Request]]:
2456 + """A real client whose execute and proxy calls are answered with ``body``."""
2457 + requests: t.List[httpx.Request] = []
2458 +
2459 + def handler(request: httpx.Request) -> httpx.Response:
2460 + if request.url.path.endswith(("/execute", "/proxy_execute")):
2461 + requests.append(request)
2462 + return httpx.Response(200, json=body)
2463 + return httpx.Response(200, json=_session_json(MCP_SAME_ORIGIN_URL))
2464 +
2465 + client = HttpClient(
2466 + provider="test",
2467 + api_key="ak_test",
2468 + base_url="https://backend.composio.dev",
2469 + http_client=httpx.Client(transport=httpx.MockTransport(handler)),
2470 + )
2471 + return client, requests
2472 +
2473 +
2474 +def _created_session(client: HttpClient) -> ToolRouterSession:
2475 + return ToolRouter(client=client, provider=MagicMock()).create(user_id="user_123")
2476 +
2477 +
2478 +class TestExecutionRequiresUserInput:
2479 + """``result_type: "input_required"`` carries no data, log ID or HTTP status,
2480 + so every execution path raises it instead of returning it as a result.
2481 +
2482 + The cases run a real client over a stub transport so they cover the wire
2483 + shape the generated client hands to the SDK.
2484 + """
2485 +
2486 + @pytest.mark.parametrize(
2487 + ("run", "subject"),
2488 + [
2489 + pytest.param(
2490 + lambda client: _created_session(client).execute(
2491 + "GMAIL_SEND_EMAIL", arguments={"to": "test@test.com"}
2492 + ),
2493 + "Tool GMAIL_SEND_EMAIL",
2494 + id="session.execute",
2495 + ),
2496 + pytest.param(
2497 + lambda client: _created_session(client).proxy_execute(**_PROXY_PARAMS),
2498 + "POST proxy call for toolkit github",
2499 + id="session.proxy_execute",
2500 + ),
2501 + pytest.param(
2502 + lambda client: SessionContextImpl(
2503 + client, "user_123", "session_123"
2504 + ).execute("GMAIL_SEND_EMAIL", {"to": "test@test.com"}),
2505 + "Tool GMAIL_SEND_EMAIL",
2506 + id="custom tool context execute",
2507 + ),
2508 + pytest.param(
2509 + lambda client: SessionContextImpl(
2510 + client, "user_123", "session_123"
2511 + ).proxy_execute(**_PROXY_PARAMS),
2512 + "POST proxy call for toolkit github",
2513 + id="custom tool context proxy_execute",
2514 + ),
2515 + pytest.param(
2516 + lambda client: _session_tool_execute_fn(client)(
2517 + "GMAIL_SEND_EMAIL", {"to": "test@test.com"}
2518 + ),
2519 + "Tool GMAIL_SEND_EMAIL",
2520 + id="provider-wrapped session tool",
2521 + ),
2522 + ],
2523 + )
2524 + def test_raises_tool_input_required_error(self, run, subject):
2525 + client, requests = _answering_client(_INPUT_REQUIRED_JSON)
2526 +
2527 + with pytest.raises(ToolInputRequiredError) as raised:
2528 + run(client)
2529 +
2530 + error = raised.value
2531 + assert f"{subject} requires user input" in error.message
2532 + assert "request_state" in error.message
2533 + # The opaque state and the proxied URL stay out of the message.
2534 + assert "opaque-state-token" not in error.message
2535 + assert "secret" not in error.message
2536 + assert error.request_state == "opaque-state-token"
2537 + assert error.input_requests == {
2538 + "approval_1": {
2539 + "type": "elicitation",
2540 + "mode": "form",
2541 + "message": "Allow GMAIL_SEND_EMAIL to send this email?",
2542 + "requested_schema": {
2543 + "type": "object",
2544 + "properties": {"approved": {"type": "boolean"}},
2545 + "required": ["approved"],
2546 + },
2547 + }
2548 + }
2549 + # The call is not repeated: answering needs the user.
2550 + assert len(requests) == 1
2551 +
2552 + def test_request_state_stays_out_of_str_repr_and_args(self):
2553 + """``request_state`` is continuation state: readable as an attribute
2554 + for the code that answers the request, absent from what an exception
2555 + is routinely logged as."""
2556 + client, _ = _answering_client(_INPUT_REQUIRED_JSON)
2557 +
2558 + with pytest.raises(ToolInputRequiredError) as raised:
2559 + _created_session(client).execute("GMAIL_SEND_EMAIL")
2560 +
2561 + error = raised.value
2562 + assert error.request_state == "opaque-state-token"
2563 + assert "opaque-state-token" not in str(error)
2564 + assert "opaque-state-token" not in repr(error)
2565 + assert "opaque-state-token" not in repr(error.args)
2566 + assert error.args == (error.message,)
2567 + formatted = "".join(
2568 + traceback.format_exception(type(error), error, error.__traceback__)
2569 + )
2570 + assert "ToolInputRequiredError" in formatted
2571 + assert "opaque-state-token" not in formatted
2572 +
2573 + def test_request_state_is_none_when_the_api_returns_none(self):
2574 + body = {k: v for k, v in _INPUT_REQUIRED_JSON.items() if k != "request_state"}
2575 + client, _ = _answering_client(body)
2576 +
2577 + with pytest.raises(ToolInputRequiredError) as raised:
2578 + _created_session(client).execute("GMAIL_SEND_EMAIL")
2579 +
2580 + assert raised.value.request_state is None
2581 +
2582 + @pytest.mark.parametrize(
2583 + ("result_type", "error"),
2584 + [("completed", None), ("failed", "Connection not found")],
2585 + )
2586 + def test_execute_still_returns_a_result(self, result_type, error):
2587 + client, _ = _answering_client(
2588 + {
2589 + "result_type": result_type,
2590 + "data": {"id": "msg_1"},
2591 + "error": error,
2592 + "log_id": "log_1",
2593 + }
2594 + )
2595 +
2596 + result = _created_session(client).execute("GMAIL_SEND_EMAIL")
2597 +
2598 + assert result.result_type == result_type
2599 + assert result.data == {"id": "msg_1"}
2600 + assert result.error == error
2601 + assert result.log_id == "log_1"
2602 +
2603 + def test_proxy_execute_still_returns_a_completed_result(self):
2604 + client, _ = _answering_client(
2605 + {
2606 + "result_type": "completed",
2607 + "status": 201,
2608 + "data": {"id": 1},
2609 + "headers": {"x-request-id": "req_1"},
2610 + }
2611 + )
2612 +
2613 + result = _created_session(client).proxy_execute(**_PROXY_PARAMS)
2614 +
2615 + assert result == {
2616 + "status": 201,
2617 + "data": {"id": 1},
2618 + "headers": {"x-request-id": "req_1"},
2619 + }
2620 +
2621 +
2622 +class _NoInput(BaseModel):
2623 + pass
2624 +
2625 +
2626 +def _custom_tool_calling(call: t.Callable[[t.Any], t.Any]) -> t.Any:
2627 + """A custom tools map with one local tool whose body runs ``call(ctx)``."""
2628 + from composio.core.models.custom_tool import build_custom_tools_map
2629 +
2630 + @experimental_api.tool()
2631 + def send_welcome_email(input: _NoInput, ctx: t.Any) -> t.Dict[str, t.Any]:
2632 + """Sends the welcome email through a session helper."""
2633 + return {"sent": call(ctx)}
2634 +
2635 + return build_custom_tools_map([send_welcome_email])
2636 +
2637 +
2638 +def _session_with_custom_tools(
2639 + client: HttpClient, custom_tools_map: t.Any
2640 +) -> ToolRouterSession:
2641 + return ToolRouterSession(
2642 + client=client,
2643 + provider=MagicMock(),
2644 + dangerously_allow_auto_upload_download_files=False,
2645 + session_id="session_123",
2646 + mcp=MagicMock(),
2647 + experimental=MagicMock(),
2648 + custom_tools_map=custom_tools_map,
2649 + user_id="user_123",
2650 + )
2651 +
2652 +
2653 +def _raise_boom(ctx: t.Any) -> t.Any:
2654 + raise RuntimeError("boom")
2655 +
2656 +
2657 +class TestCustomToolBodyRequiresUserInput:
2658 + """A local custom tool reaches the API through ``ctx.execute()`` and
2659 + ``ctx.proxy_execute()``. The wrapper that runs the tool turns whatever it
2660 + raises into a failed result, which must not happen to an input request: the
2661 + caller needs the questions and the request state, not a message.
2662 + """
2663 +
2664 + _BODIES = [
2665 + pytest.param(
2666 + lambda ctx: ctx.execute("GMAIL_SEND_EMAIL", {"to": "test@test.com"}),
2667 + "Tool GMAIL_SEND_EMAIL",
2668 + id="ctx.execute",
2669 + ),
2670 + pytest.param(
2671 + lambda ctx: ctx.proxy_execute(**_PROXY_PARAMS),
2672 + "POST proxy call for toolkit github",
2673 + id="ctx.proxy_execute",
2674 + ),
2675 + ]
2676 +
2677 + @pytest.mark.parametrize(("call", "subject"), _BODIES)
2678 + def test_session_execute_of_a_custom_tool_raises(self, call, subject):
2679 + client, requests = _answering_client(_INPUT_REQUIRED_JSON)
2680 + session = _session_with_custom_tools(client, _custom_tool_calling(call))
2681 +
2682 + with pytest.raises(ToolInputRequiredError) as raised:
2683 + session.execute("SEND_WELCOME_EMAIL", arguments={})
2684 +
2685 + error = raised.value
2686 + assert f"{subject} requires user input" in error.message
2687 + assert error.request_state == "opaque-state-token"
2688 + assert list(error.input_requests) == ["approval_1"]
2689 + assert len(requests) == 1
2690 +
2691 + @pytest.mark.parametrize(("call", "subject"), _BODIES)
2692 + def test_sibling_custom_tool_raises_through_ctx_execute(self, call, subject):
2693 + client, _ = _answering_client(_INPUT_REQUIRED_JSON)
2694 + context = SessionContextImpl(
2695 + client, "user_123", "session_123", _custom_tool_calling(call)
2696 + )
2697 +
2698 + with pytest.raises(ToolInputRequiredError) as raised:
2699 + context.execute("SEND_WELCOME_EMAIL", {})
2700 +
2701 + assert raised.value.request_state == "opaque-state-token"
2702 +
2703 + def test_any_other_error_is_still_a_failed_result(self):
2704 + client, _ = _answering_client(_INPUT_REQUIRED_JSON)
2705 + session = _session_with_custom_tools(client, _custom_tool_calling(_raise_boom))
2706 +
2707 + result = session.execute("SEND_WELCOME_EMAIL", arguments={})
2708 +
2709 + assert result.error == "boom"
2710 + assert result.result_type == "failed"
2711 +
2712 +
2713 +_EXECUTED_ANSWERS = [
2714 + pytest.param("failed", None, False, id="failed with a null error"),
2715 + pytest.param("failed", "", False, id="failed with an empty error"),
2716 + pytest.param("failed", "Boom", False, id="failed with a message"),
2717 + pytest.param("completed", None, True, id="completed"),
2718 + pytest.param(None, None, True, id="no result_type and no error"),
2719 + pytest.param(None, "Boom", False, id="no result_type and an error"),
2720 +]
2721 +
2722 +
2723 +def _executed_json(
2724 + result_type: t.Optional[str], error: t.Optional[str]
2725 +) -> t.Dict[str, t.Any]:
2726 + body: t.Dict[str, t.Any] = {"data": {}, "error": error, "log_id": "log"}
2727 + if result_type is not None:
2728 + body["result_type"] = result_type
2729 + return body
2730 +
2731 +
2732 +class TestSessionExecutionSuccess:
2733 + """``result_type`` says whether a tool that ran succeeded. A failed
2734 + execution can carry a ``None`` or empty ``error``, so success is read from
2735 + ``result_type`` and only falls back to the error text when the API sent no
2736 + ``result_type``.
2737 + """
2738 +
2739 + @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS)
2740 + def test_provider_wrapped_session_tool(self, result_type, error, successful):
2741 + client, _ = _answering_client(_executed_json(result_type, error))
2742 +
2743 + result = _session_tool_execute_fn(client)("GMAIL_SEND_EMAIL", {})
2744 +
2745 + # The error is passed through as the API sent it.
2746 + assert result == {"data": {}, "error": error, "successful": successful}
2747 +
2748 + @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS)
2749 + def test_provider_tool_call_bound_to_a_session(
2750 + self, result_type, error, successful
2751 + ):
2752 + from composio.core.provider._openai import OpenAIProvider
2753 +
2754 + client, _ = _answering_client(_executed_json(result_type, error))
2755 +
2756 + result = OpenAIProvider().execute_tool_for_target(
2757 + target=_created_session(client), slug="GMAIL_SEND_EMAIL", arguments={}
2758 + )
2759 +
2760 + assert result == {"data": {}, "error": error, "successful": successful}
2761 +
2762 + @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS)
2763 + def test_session_execute_exposes_result_type(self, result_type, error, successful):
2764 + client, _ = _answering_client(_executed_json(result_type, error))
2765 +
2766 + result = _created_session(client).execute("GMAIL_SEND_EMAIL")
2767 +
2768 + assert result.result_type == result_type
2769 + assert result.error == error
2770 +
2771 + @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS)
2772 + def test_custom_tool_context_execute_exposes_result_type(
2773 + self, result_type, error, successful
2774 + ):
2775 + client, _ = _answering_client(_executed_json(result_type, error))
2776 +
2777 + result = SessionContextImpl(client, "user_123", "session_123").execute(
2778 + "GMAIL_SEND_EMAIL", {}
2779 + )
2780 +
2781 + assert result.result_type == result_type
2782 + assert result.error == error
2783 +
2784 +
2785 +def _session_tool_execute_fn(client: HttpClient) -> t.Callable[..., t.Any]:
2786 + """The execute function providers wrap session tools with."""
2787 + from composio.core.models.tools import Tools
2788 +
2789 + tools = Tools(
2790 + client=client,
2791 + provider=MagicMock(),
2792 + dangerously_allow_auto_upload_download_files=False,
2793 + )
2794 + # Keep the (read) tool-schema lookup off the transport.
2795 + tools._tool_schemas["GMAIL_SEND_EMAIL"] = MagicMock()
2796 + return tools._wrap_execute_tool_for_tool_router(session_id="session_123")
2797 +
2798 +
2799 def _transport_client(
2800 *,
2801 api_key: t.Optional[str],
@@ -2724,7 +3100,7 @@ class TestSessionUpdateContract:
3100 }
3101 )
3102 kwargs = mock_client.tool_router.session.patch.call_args.kwargs
2727 - assert kwargs["extra_body"]["instant"] == {
3103 + assert kwargs["instant"] == {
3104 "toolkits": {"enable": ["exa"]},
3105 "return_instant_charge": True,
3106 }
@@ -2733,10 +3109,7 @@ class TestSessionUpdateContract:
3109 def test_instant_can_be_disabled(self, session, mock_client):
3110 session.update(instant=False)
3111 assert (
2736 - mock_client.tool_router.session.patch.call_args.kwargs["extra_body"][
2737 - "instant"
2738 - ]
2739 - is False
3112 + mock_client.tool_router.session.patch.call_args.kwargs["instant"] is False
3113 )
3114
3115 def test_instant_rejects_none(self, session, mock_client):
ts/packages/cli/CHANGELOG.md
+11
@@ -4,6 +4,17 @@
4
5 ### Patch Changes
6
7 +- `composio execute` (including meta tools), `composio proxy`, the `proxy()`
8 + helper in `composio run` scripts, and the custom tool schema lookup in
9 + `composio search` now fail with a clear error when the call needs user input,
10 + such as an approval, before it can run. The CLI cannot answer input requests
11 + yet, and it no longer treats such an answer as a result. The `proxy()` helper
12 + used to return an empty `200` response for a call that never ran.
13 +
14 +- `composio execute` now reports a tool that ran and failed as failed even when
15 + the API returns no error text. It used to read a failed execution with a
16 + `null` error as successful.
17 +
18 - `composio execute` now validates the arguments before it sends the tool
19 call, so a call that fails local validation is never run. Validation used to
20 race the request, and the tool could execute while the CLI reported a
ts/packages/cli/src/commands/proxy.cmd.ts
+14 -4
@@ -22,6 +22,7 @@ import {
22 mapComposioError,
23 } from 'src/services/composio-error-overrides';
24 import { parseJsonRecord } from 'src/utils/parse-json';
25 +import { assertNotInputRequired } from 'src/utils/tool-input-required';
26 import { resolveConnectedAccountForToolkit } from 'src/services/connected-account-selection';
27
28 const endpoint = Argument.String('url').pipe(
@@ -119,7 +120,10 @@ export const parseProxyBody = (raw: string): unknown =>
120 Result.getOrElse(parseJsonRecord(raw), (): unknown => raw);
121
122 const formatProxyOutput = (
122 - result: Pick<SessionProxyExecuteResponse, 'status' | 'data' | 'headers' | 'binary_data'>
123 + result: Pick<
124 + Extract<SessionProxyExecuteResponse, { result_type: 'completed' }>,
125 + 'status' | 'data' | 'headers' | 'binary_data'
126 + >
127 ) => {
128 if (result.binary_data) {
129 return JSON.stringify(
@@ -352,8 +356,8 @@ export const proxyCmd = Command.make('proxy', {
356 });
357
358 return yield* Effect.tryPromise({
355 - try: () =>
356 - client.toolRouter.session.proxyExecute(
359 + try: async () => {
360 + const response = await client.toolRouter.session.proxyExecute(
361 sessionId,
362 {
363 toolkit_slug: normalizedToolkit,
@@ -365,7 +369,13 @@ export const proxyCmd = Command.make('proxy', {
369 // Never retry a proxied call: a retry after the upstream API
370 // already acted duplicates the side effect.
371 { maxRetries: 0 }
368 - ),
372 + );
373 + assertNotInputRequired(
374 + `${normalizedMethod} proxy call via "${normalizedToolkit}"`,
375 + response
376 + );
377 + return response;
378 + },
379 catch: cause =>
380 new ProxyRequestError({
381 message: `Failed to proxy ${normalizedMethod} ${endpoint} via "${normalizedToolkit}".`,
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+2
@@ -17,6 +17,7 @@ import {
17 } from 'src/services/command-project';
18 import { commandHintExample, commandHintStep } from 'src/services/command-hints';
19 import { isRemoteCustomToolSlug } from 'src/utils/remote-custom-toolkit';
20 +import { assertNotInputRequired } from 'src/utils/tool-input-required';
21 import {
22 primeConsumerConnectedToolkitsCacheInBackground,
23 writeConsumerConnectedToolkitsCache,
@@ -393,6 +394,7 @@ const runToolsSearch = (params: {
394 slug: 'COMPOSIO_GET_TOOL_SCHEMAS',
395 arguments: { tool_slugs: customToolSlugsMissingSchemas },
396 });
397 + assertNotInputRequired('COMPOSIO_GET_TOOL_SCHEMAS', schemaResponse);
398 if (schemaResponse.error) {
399 throw new Error(schemaResponse.error);
400 }
ts/packages/cli/src/services/run-helpers-runtime.ts
+35 -3
@@ -23,6 +23,7 @@ import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
23 import { NodeOs } from 'src/services/node-os';
24 import { collectText } from 'src/services/command-runner';
25 import { debugFlagsToChildEnv } from 'src/services/runtime-flags';
26 +import { toolInputRequiredError } from 'src/utils/tool-input-required';
27
28 // One Bun platform runtime shared by every CLI child process this module spawns. ManagedRuntime
29 // builds the layer lazily on first use, so importers that never spawn a child pay nothing, and a
@@ -72,13 +73,34 @@ const decodeExperimentalSubagentConfig = Schema.decodeUnknownSync(
73 Schema.fromJsonString(ExperimentalSubagentConfig)
74 );
75 const ProxySessionResponse = Schema.Struct({ session_id: Schema.NonEmptyString });
75 -const ProxyExecuteResponse = Schema.Struct({
76 +const ProxyExecuteCompletedResponse = Schema.Struct({
77 + // Absent when an older server answers; any other value fails the decode
78 + // instead of being read as a completed call.
79 + result_type: Schema.optional(Schema.Literal('completed')),
80 headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
81 binary_data: Schema.optional(Schema.Struct({ url: Schema.optional(Schema.String) })),
82 data: Schema.optional(Schema.Unknown),
83 status: Schema.optional(Schema.Number),
84 });
81 -type ProxyExecuteResponse = Schema.Schema.Type<typeof ProxyExecuteResponse>;
85 +type ProxyExecuteCompletedResponse = Schema.Schema.Type<typeof ProxyExecuteCompletedResponse>;
86 +const ProxyExecuteInputRequiredResponse = Schema.Struct({
87 + result_type: Schema.Literal('input_required'),
88 + input_requests: Schema.Record(
89 + Schema.String,
90 + Schema.Struct({
91 + type: Schema.Literal('elicitation'),
92 + mode: Schema.Literal('form'),
93 + message: Schema.String,
94 + requested_schema: Schema.Record(Schema.String, Schema.Unknown),
95 + })
96 + ),
97 + request_state: Schema.optional(Schema.String),
98 +});
99 +const ProxyExecuteResponse = Schema.Union([
100 + ProxyExecuteInputRequiredResponse,
101 + ProxyExecuteCompletedResponse,
102 +]);
103 +const isProxyInputRequired = Schema.is(ProxyExecuteInputRequiredResponse);
104
105 const experimentalSubAgentSchema = {
106 type: 'function',
@@ -443,7 +465,7 @@ const normalizeFetchInput = async (input: unknown, init: RequestInit = {}) => {
465 };
466 };
467
446 -const toProxyResponse = async (result: ProxyExecuteResponse) => {
468 +const toProxyResponse = async (result: ProxyExecuteCompletedResponse) => {
469 const headers = new Headers(result?.headers || {});
470 if (result?.binary_data?.url) {
471 const binaryResponse = await ssrfSafeFetch(
@@ -998,6 +1020,16 @@ const createProxyHelper = (params: {
1020 : {}),
1021 })
1022 );
1023 + // An approval request is not a response from the proxied API: converting
1024 + // it would hand the script an empty 200 for a call that never ran.
1025 + if (isProxyInputRequired(result)) {
1026 + // The error is thrown into the user's script, where it is likely to be
1027 + // logged whole. `request_state` is continuation state the CLI cannot
1028 + // use yet, so it is left off the error.
1029 + throw toolInputRequiredError(`${request.method} proxy call via "${normalizedToolkit}"`, {
1030 + input_requests: result.input_requests,
1031 + });
1032 + }
1033 return toProxyResponse(result);
1034 };
1035 Object.defineProperty(proxyFetch, 'toolkit', { value: normalizedToolkit });
ts/packages/cli/src/services/tools-executor.ts
+42 -19
@@ -19,6 +19,7 @@ import { ToolFileUploadError, uploadToolInputFiles } from 'src/services/tool-fil
19 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
20 import { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';
21 import { isMetaToolSlug } from 'src/utils/meta-tool-slugs';
22 +import { assertNotInputRequired } from 'src/utils/tool-input-required';
23 import type { NodeOs } from 'src/services/node-os';
24 import type { NodeProcess } from 'src/services/node-process';
25 import type { ComposioUserContext } from 'src/services/user-context';
@@ -95,14 +96,35 @@ export interface ToolsExecutor {
96
97 export const ToolsExecutor = Context.Service<ToolsExecutor>('services/ToolsExecutor');
98
99 +/**
100 + * Whether an execution answer describes a tool that ran and succeeded.
101 + *
102 + * `result_type` decides when the API sent one: a `failed` execution is not
103 + * successful even when its `error` is `null` or empty. Without a known
104 + * `result_type`, for example from a server that predates it, an execution is
105 + * successful when it carries no error text. `@composio/core` applies the same
106 + * rule to session executions.
107 + */
108 +export const isExecutionSuccessful = (raw: {
109 + readonly result_type?: string;
110 + readonly error?: string | null;
111 +}): boolean => {
112 + if (raw.result_type === 'completed') return true;
113 + if (raw.result_type === 'failed') return false;
114 + return !raw.error;
115 +};
116 +
117 /**
118 * Normalize the raw Tool Router response into the shape the CLI commands expect.
119 */
120 const normalizeResponse = (
102 - raw: SessionExecuteResponse | SessionExecuteMetaResponse,
121 + raw: Exclude<
122 + SessionExecuteResponse | SessionExecuteMetaResponse,
123 + { result_type: 'input_required' }
124 + >,
125 permissionGateResult?: PermissionGateResult
126 ): ToolExecuteResponse => ({
105 - successful: raw.error === null,
127 + successful: isExecutionSuccessful(raw),
128 data: raw.data,
129 error: raw.error,
130 logId: raw.log_id,
@@ -211,27 +233,28 @@ export const ToolsExecutorLive = Layer.effect(
233 })
234 );
235
214 - const raw: SessionExecuteResponse | SessionExecuteMetaResponse = yield* Effect.tryPromise(
215 - {
216 - // Never retry an execution: a retry after the backend already acted
217 - // duplicates the side effect (e.g. sends the same email twice).
218 - try: () => {
219 - if (isMetaToolSlug(slug)) {
220 - return resolvedClient.toolRouter.session.executeMeta(
236 + const raw = yield* Effect.tryPromise({
237 + // Never retry an execution: a retry after the backend already acted
238 + // duplicates the side effect (e.g. sends the same email twice).
239 + try: async () => {
240 + const response: SessionExecuteResponse | SessionExecuteMetaResponse = isMetaToolSlug(
241 + slug
242 + )
243 + ? await resolvedClient.toolRouter.session.executeMeta(
244 sessionId,
245 { slug, arguments: normalizedArguments },
246 { maxRetries: 0 }
247 + )
248 + : await resolvedClient.toolRouter.session.execute(
249 + sessionId,
250 + { tool_slug: slug, arguments: normalizedArguments },
251 + { maxRetries: 0 }
252 );
225 - }
226 - return resolvedClient.toolRouter.session.execute(
227 - sessionId,
228 - { tool_slug: slug, arguments: normalizedArguments },
229 - { maxRetries: 0 }
230 - );
231 - },
232 - catch: cause => cause,
233 - }
234 - );
253 + assertNotInputRequired(`Tool ${slug}`, response);
254 + return response;
255 + },
256 + catch: cause => cause,
257 + });
258
259 return normalizeResponse(raw, permissionGateResult);
260 }).pipe(
ts/packages/cli/src/utils/tool-input-required.ts new
+52
@@ -0,0 +1,52 @@
1 +import { Data } from 'effect';
2 +import type {
3 + SessionExecuteMetaResponse,
4 + SessionExecuteResponse,
5 + SessionProxyExecuteResponse,
6 +} from '@composio/client/resources/tool-router';
7 +
8 +type ExecuteFamilyResponse =
9 + SessionExecuteResponse | SessionExecuteMetaResponse | SessionProxyExecuteResponse;
10 +
11 +type InputRequiredResponse = Extract<ExecuteFamilyResponse, { result_type: 'input_required' }>;
12 +
13 +/**
14 + * A tool execution or proxied call that did not run because it needs input
15 + * from the user first, for example an approval. The API answers such a call
16 + * with `result_type: "input_required"` instead of a result, and the CLI has no
17 + * flow to collect and submit the answers.
18 + */
19 +export class ToolInputRequiredError extends Data.TaggedError('utils/ToolInputRequiredError')<{
20 + readonly message: string;
21 + readonly inputRequests: InputRequiredResponse['input_requests'];
22 + readonly requestState: string | undefined;
23 +}> {}
24 +
25 +/**
26 + * Builds the error for an `input_required` answer. `subject` names the call
27 + * that did not run, for example `Tool GMAIL_SEND_EMAIL`.
28 + */
29 +export const toolInputRequiredError = (
30 + subject: string,
31 + response: Pick<InputRequiredResponse, 'input_requests' | 'request_state'>
32 +): ToolInputRequiredError => {
33 + const count = Object.keys(response.input_requests).length;
34 + return new ToolInputRequiredError({
35 + message: `${subject} requires user input before it can run (${count} input request${count === 1 ? '' : 's'}) and was not executed. The CLI cannot answer input requests yet.`,
36 + inputRequests: response.input_requests,
37 + requestState: response.request_state,
38 + });
39 +};
40 +
41 +/**
42 + * Narrows an execute-family response to the variants that carry a result.
43 + *
44 + * @throws {ToolInputRequiredError} If the call asked for user input instead of running
45 + */
46 +export function assertNotInputRequired<Response extends ExecuteFamilyResponse>(
47 + subject: string,
48 + response: Response
49 +): asserts response is Exclude<Response, InputRequiredResponse> {
50 + if (response.result_type !== 'input_required') return;
51 + throw toolInputRequiredError(subject, response);
52 +}
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+1 -1
@@ -105,7 +105,7 @@ describe('CLI: composio dev connected-accounts link', () => {
105 execute: {},
106 search: {},
107 preload: { tools: [] },
108 - premium_usage: false as const,
108 + instant: false as const,
109 },
110 config_version: 1,
111 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
ts/packages/cli/test/src/commands/proxy.cmd.test.ts
+50 -2
@@ -111,7 +111,7 @@ describe('CLI: composio proxy', () => {
111 execute: {},
112 search: {},
113 preload: { tools: [] },
114 - premium_usage: false,
114 + instant: false,
115 },
116 config_version: 1,
117 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -126,6 +126,7 @@ describe('CLI: composio proxy', () => {
126 proxyParams = { sessionId, params };
127 proxyOptions = options;
128 return {
129 + result_type: 'completed' as const,
130 status: 200,
131 data: {
132 ok: true,
@@ -216,7 +217,7 @@ describe('CLI: composio proxy', () => {
217 execute: {},
218 search: {},
219 preload: { tools: [] },
219 - premium_usage: false,
220 + instant: false,
221 },
222 config_version: 1,
223 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -300,4 +301,51 @@ describe('CLI: composio proxy', () => {
301 );
302 }
303 );
304 +
305 + layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
306 + '[Given] proxy_execute asks for user input [Then] proxy fails without a response',
307 + it => {
308 + it.effect('reports that the proxied call requires user input', () =>
309 + Effect.gen(function* () {
310 + const live = TestLive({
311 + baseConfigProvider: testConfigProvider,
312 + fixture: 'global-test-user-id',
313 + toolRouter: {
314 + proxyExecute: async () => ({
315 + result_type: 'input_required' as const,
316 + input_requests: {
317 + approval_1: {
318 + type: 'elicitation' as const,
319 + mode: 'form' as const,
320 + message: 'Allow this request to Gmail?',
321 + requested_schema: { type: 'object' },
322 + },
323 + },
324 + request_state: 'opaque-state-token',
325 + }),
326 + },
327 + });
328 +
329 + const { exit, output } = yield* Effect.gen(function* () {
330 + const exit = yield* cli([
331 + 'proxy',
332 + 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
333 + '--toolkit',
334 + 'gmail',
335 + '--skip-connection-check',
336 + ]).pipe(Effect.exit);
337 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
338 + return { exit, output: lines.join('\n') };
339 + }).pipe(Effect.provide(live));
340 +
341 + expect(Exit.isFailure(exit)).toBe(true);
342 + expect(output).toContain(
343 + 'GET proxy call via \\"gmail\\" requires user input before it can run (1 input request) and was not executed.'
344 + );
345 + expect(output).not.toContain('Status:');
346 + expect(output).not.toContain('opaque-state-token');
347 + })
348 + );
349 + }
350 + );
351 });
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+92 -7
@@ -3,7 +3,7 @@ import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { describe, expect, it, layer } from '@effect/vitest';
5 import { vi, beforeEach, afterEach } from 'vitest';
6 -import { Config, ConfigProvider, DateTime, Effect, Option, Predicate } from 'effect';
6 +import { Config, ConfigProvider, DateTime, Effect, Exit, Option, Predicate } from 'effect';
7 import { extendConfigProvider } from 'src/services/config';
8 import { APIError } from '@composio/client';
9 import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';
@@ -331,7 +331,7 @@ describe('CLI: composio execute', () => {
331 execute: {},
332 search: {},
333 preload: { tools: [] },
334 - premium_usage: false,
334 + instant: false,
335 },
336 config_version: 1,
337 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -341,6 +341,7 @@ describe('CLI: composio execute', () => {
341 execute: async (_sessionId, params, options) => {
342 recordedExecuteOptions.push(options);
343 return {
344 + result_type: 'completed' as const,
345 data: { tool_slug: params.tool_slug, arguments: params.arguments },
346 error: null,
347 log_id: 'log_gmail_default',
@@ -349,6 +350,7 @@ describe('CLI: composio execute', () => {
350 executeMeta: async (_sessionId, params, options) => {
351 recordedExecuteOptions.push(options);
352 return {
353 + result_type: 'completed' as const,
354 data: { slug: params.slug, arguments: params.arguments },
355 error: null,
356 log_id: 'log_meta_default',
@@ -469,7 +471,7 @@ describe('CLI: composio execute', () => {
471 execute: {},
472 search: {},
473 preload: { tools: [] },
472 - premium_usage: false,
474 + instant: false,
475 },
476 config_version: 1,
477 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -477,6 +479,7 @@ describe('CLI: composio execute', () => {
479 };
480 },
481 execute: async (_sessionId, params) => ({
482 + result_type: 'completed' as const,
483 data: { tool_slug: params.tool_slug, arguments: params.arguments },
484 error: null,
485 log_id: 'log_gmail_explicit',
@@ -631,7 +634,7 @@ describe('CLI: composio execute', () => {
634 execute: {},
635 search: {},
636 preload: { tools: [] },
634 - premium_usage: false,
637 + instant: false,
638 },
639 config_version: 1,
640 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -639,6 +642,7 @@ describe('CLI: composio execute', () => {
642 };
643 },
644 execute: async (_sessionId, params) => ({
645 + result_type: 'completed' as const,
646 data: { tool_slug: params.tool_slug, arguments: params.arguments },
647 error: null,
648 log_id: 'log_google_analytics',
@@ -731,7 +735,7 @@ describe('CLI: composio execute', () => {
735 execute: {},
736 search: {},
737 preload: { tools: [] },
734 - premium_usage: false,
738 + instant: false,
739 },
740 config_version: 1,
741 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -739,6 +743,7 @@ describe('CLI: composio execute', () => {
743 };
744 },
745 execute: async (_sessionId, params) => ({
746 + result_type: 'completed' as const,
747 data: { tool_slug: params.tool_slug, arguments: params.arguments },
748 error: null,
749 log_id: 'log_custom_grain',
@@ -867,7 +872,7 @@ describe('CLI: composio execute', () => {
872 execute: {},
873 search: {},
874 preload: { tools: [] },
870 - premium_usage: false,
875 + instant: false,
876 },
877 config_version: 1,
878 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -875,6 +880,7 @@ describe('CLI: composio execute', () => {
880 };
881 },
882 execute: async (_sessionId, params) => ({
883 + result_type: 'completed' as const,
884 data: { tool_slug: params.tool_slug, arguments: params.arguments },
885 error: null,
886 log_id: 'log_posthog_test',
@@ -925,7 +931,7 @@ describe('CLI: composio execute', () => {
931 execute: {},
932 search: {},
933 preload: { tools: [] },
928 - premium_usage: false,
934 + instant: false,
935 },
936 config_version: 1,
937 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -933,6 +939,7 @@ describe('CLI: composio execute', () => {
939 };
940 },
941 execute: async (_sessionId, params) => ({
942 + result_type: 'completed' as const,
943 data: { tool_slug: params.tool_slug, arguments: params.arguments },
944 error: null,
945 log_id: 'log_posthog_cached',
@@ -1668,6 +1675,7 @@ describe('CLI: composio execute', () => {
1675 throw new Error('gmail execution failed');
1676 }
1677 return {
1678 + result_type: 'completed' as const,
1679 data: { tool_slug: params.tool_slug, arguments: params.arguments },
1680 error: null,
1681 log_id: 'log_parallel_success',
@@ -2618,6 +2626,7 @@ describe('CLI: composio execute', () => {
2626 stdin: { isTTY: true, data: '' },
2627 toolRouter: {
2628 execute: async (_sessionId, params) => ({
2629 + result_type: 'completed' as const,
2630 data: { tool_slug: params.tool_slug, custom: 'response' },
2631 error: null,
2632 log_id: 'log_custom',
@@ -2639,6 +2648,82 @@ describe('CLI: composio execute', () => {
2648 );
2649 });
2650
2651 + layer(
2652 + TestLive({
2653 + baseConfigProvider: testConfigProvider,
2654 + fixture: 'global-test-user-id',
2655 + stdin: { isTTY: true, data: '' },
2656 + toolRouter: {
2657 + execute: async () => ({
2658 + result_type: 'failed' as const,
2659 + data: {},
2660 + error: null,
2661 + log_id: 'log_failed',
2662 + }),
2663 + },
2664 + })
2665 + )('[Given] Tool Router reports a failed execution with no error text', it => {
2666 + it.effect('[Then] execute fails instead of reporting success', () =>
2667 + Effect.gen(function* () {
2668 + const exit = yield* cli([
2669 + 'execute',
2670 + 'GITHUB_STAR_REPO',
2671 + '-d',
2672 + '{"owner":"composio","repo":"composio"}',
2673 + ]).pipe(Effect.exit);
2674 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
2675 + const output = parseLastJson(lines);
2676 +
2677 + expect(Exit.isFailure(exit)).toBe(true);
2678 + expect(output.successful).toBe(false);
2679 + expect(output.error).toBeNull();
2680 + expect(output.logId).toBe('log_failed');
2681 + })
2682 + );
2683 + });
2684 +
2685 + layer(
2686 + TestLive({
2687 + baseConfigProvider: testConfigProvider,
2688 + fixture: 'global-test-user-id',
2689 + stdin: { isTTY: true, data: '' },
2690 + toolRouter: {
2691 + execute: async () => ({
2692 + result_type: 'input_required' as const,
2693 + input_requests: {
2694 + approval_1: {
2695 + type: 'elicitation' as const,
2696 + mode: 'form' as const,
2697 + message: 'Allow GITHUB_STAR_REPO to star this repository?',
2698 + requested_schema: { type: 'object', properties: { approved: { type: 'boolean' } } },
2699 + },
2700 + },
2701 + request_state: 'opaque-state-token',
2702 + }),
2703 + },
2704 + })
2705 + )('[Given] Tool Router asks for user input [Then] execute fails without a result', it => {
2706 + it.effect('reports that the tool requires user input', () =>
2707 + Effect.gen(function* () {
2708 + const exit = yield* cli([
2709 + 'execute',
2710 + 'GITHUB_STAR_REPO',
2711 + '-d',
2712 + '{"owner":"composio","repo":"composio"}',
2713 + ]).pipe(Effect.exit);
2714 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
2715 + const output = parseLastJson(lines);
2716 +
2717 + expect(Exit.isFailure(exit)).toBe(true);
2718 + expect(output.successful).toBe(false);
2719 + expect(output.error).toContain(
2720 + 'Tool GITHUB_STAR_REPO requires user input before it can run (1 input request) and was not executed.'
2721 + );
2722 + expect(lines.join('\n')).not.toContain('opaque-state-token');
2723 + })
2724 + );
2725 + });
2726 +
2727 layer(
2728 TestLive({
2729 baseConfigProvider: testConfigProvider,
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+4 -3
@@ -241,6 +241,7 @@ describe('CLI: composio search', () => {
241 executeMeta: async (_sessionId, params) => {
242 schemaRequestSlugs = params.arguments?.tool_slugs;
243 return {
244 + result_type: 'completed' as const,
245 data: {
246 success: true,
247 tool_schemas: {
@@ -542,7 +543,7 @@ describe('CLI: composio search', () => {
543 execute: {},
544 search: {},
545 preload: { tools: [] },
545 - premium_usage: false,
546 + instant: false,
547 },
548 config_version: 1,
549 mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
@@ -627,7 +628,7 @@ describe('CLI: composio search', () => {
628 execute: {},
629 search: {},
630 preload: { tools: [] },
630 - premium_usage: false,
631 + instant: false,
632 },
633 config_version: 1,
634 mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
@@ -823,7 +824,7 @@ describe('CLI: composio search', () => {
824 execute: {},
825 search: {},
826 preload: { tools: [] },
826 - premium_usage: false,
827 + instant: false,
828 },
829 config_version: 1,
830 mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
ts/packages/cli/test/src/services/run-helpers-runtime.test.ts
+116 -1
@@ -1,6 +1,8 @@
1 +import { inspect } from 'node:util';
2 import { Predicate } from 'effect';
2 -import { afterEach, describe, expect, it, vi } from 'vitest';
3 +import { afterEach, assert, describe, expect, it, vi } from 'vitest';
4 import { installRunHelpers } from 'src/services/run-helpers-runtime';
5 +import { ToolInputRequiredError } from 'src/utils/tool-input-required';
6
7 const installedGlobalNames = [
8 'z',
@@ -62,6 +64,119 @@ describe('run-helpers-runtime', () => {
64 expect(fetchMock).toHaveBeenCalledOnce();
65 });
66
67 + it('[Given] a proxy call that needs user input [Then] it rejects instead of returning an empty 200', async () => {
68 + const fetchMock = vi
69 + .fn()
70 + .mockResolvedValueOnce(
71 + new Response(JSON.stringify({ session_id: 'session-1' }), {
72 + status: 200,
73 + headers: { 'content-type': 'application/json' },
74 + })
75 + )
76 + .mockResolvedValueOnce(
77 + new Response(
78 + JSON.stringify({
79 + result_type: 'input_required',
80 + input_requests: {
81 + approval_1: {
82 + type: 'elicitation',
83 + mode: 'form',
84 + message: 'Allow this request to GitHub?',
85 + requested_schema: { type: 'object' },
86 + },
87 + },
88 + request_state: 'opaque-state-token',
89 + }),
90 + {
91 + status: 200,
92 + headers: { 'content-type': 'application/json' },
93 + }
94 + )
95 + );
96 + vi.stubGlobal('fetch', fetchMock);
97 +
98 + await installRunHelpers({
99 + cliPrefix: ['composio'],
100 + helperContext: {
101 + apiKey: 'test-key',
102 + orgId: 'test-org',
103 + consumerProjectId: 'test-project',
104 + consumerUserId: 'test-user',
105 + },
106 + });
107 +
108 + const installedGlobals: unknown = globalThis;
109 + assert(
110 + Predicate.hasProperty(installedGlobals, 'proxy') &&
111 + typeof installedGlobals.proxy === 'function',
112 + 'installRunHelpers() did not install proxy().'
113 + );
114 +
115 + const proxyFetch = await installedGlobals.proxy('github');
116 + const error: unknown = await proxyFetch('https://api.github.com/user/repos', {
117 + method: 'POST',
118 + }).catch((caught: unknown) => caught);
119 +
120 + assert(error instanceof ToolInputRequiredError);
121 + expect(error.message).toBe(
122 + 'POST proxy call via "github" requires user input before it can run (1 input request) and was not executed. The CLI cannot answer input requests yet.'
123 + );
124 + // The script is likely to log the error whole, so the continuation state
125 + // is not on it.
126 + expect(inspect(error, { depth: null })).not.toContain('opaque-state-token');
127 + expect(JSON.stringify(error)).not.toContain('opaque-state-token');
128 + expect(Object.keys(error.inputRequests)).toEqual(['approval_1']);
129 + expect(fetchMock).toHaveBeenCalledTimes(2);
130 + });
131 +
132 + it.each([
133 + {
134 + name: 'a completed answer',
135 + body: { result_type: 'completed', status: 201, data: { id: 1 } },
136 + },
137 + { name: 'an answer with no result_type', body: { status: 201, data: { id: 1 } } },
138 + ])('[Given] $name from the proxy [Then] it returns the proxied response', async ({ body }) => {
139 + const fetchMock = vi
140 + .fn()
141 + .mockResolvedValueOnce(
142 + new Response(JSON.stringify({ session_id: 'session-1' }), {
143 + status: 200,
144 + headers: { 'content-type': 'application/json' },
145 + })
146 + )
147 + .mockResolvedValueOnce(
148 + new Response(JSON.stringify(body), {
149 + status: 200,
150 + headers: { 'content-type': 'application/json' },
151 + })
152 + );
153 + vi.stubGlobal('fetch', fetchMock);
154 +
155 + await installRunHelpers({
156 + cliPrefix: ['composio'],
157 + helperContext: {
158 + apiKey: 'test-key',
159 + orgId: 'test-org',
160 + consumerProjectId: 'test-project',
161 + consumerUserId: 'test-user',
162 + },
163 + });
164 +
165 + const installedGlobals: unknown = globalThis;
166 + assert(
167 + Predicate.hasProperty(installedGlobals, 'proxy') &&
168 + typeof installedGlobals.proxy === 'function',
169 + 'installRunHelpers() did not install proxy().'
170 + );
171 +
172 + const proxyFetch = await installedGlobals.proxy('github');
173 + const response: Response = await proxyFetch('https://api.github.com/user');
174 +
175 + expect(response.status).toBe(201);
176 + expect(response.ok).toBe(true);
177 + await expect(response.json()).resolves.toEqual({ id: 1 });
178 + });
179 +
180 it('[Given] a proxy binary URL targets cloud metadata [Then] it blocks the download', async () => {
181 const fetchMock = vi
182 .fn()
ts/packages/cli/test/src/services/tools-executor.test.ts new
+27
@@ -0,0 +1,27 @@
1 +import { describe, expect, it } from 'vitest';
2 +import { isExecutionSuccessful } from 'src/services/tools-executor';
3 +
4 +describe('isExecutionSuccessful', () => {
5 + it.each([
6 + {
7 + name: 'failed with a null error',
8 + raw: { result_type: 'failed', error: null },
9 + expected: false,
10 + },
11 + {
12 + name: 'failed with an empty error',
13 + raw: { result_type: 'failed', error: '' },
14 + expected: false,
15 + },
16 + {
17 + name: 'failed with a message',
18 + raw: { result_type: 'failed', error: 'Boom' },
19 + expected: false,
20 + },
21 + { name: 'completed', raw: { result_type: 'completed', error: null }, expected: true },
22 + { name: 'no result_type and no error', raw: { error: null }, expected: true },
23 + { name: 'no result_type and an error', raw: { error: 'Boom' }, expected: false },
24 + ])('[Given] $name [Then] successful is $expected', ({ raw, expected }) => {
25 + expect(isExecutionSuccessful(raw)).toBe(expected);
26 + });
27 +});
ts/packages/core/src/errors/ToolRouterErrors.ts
+65
@@ -3,8 +3,21 @@ import { ComposioError, ComposioErrorOptions } from './ComposioError';
3 export const ToolRouterErrorCodes = {
4 MCP_DESTINATION_REJECTED: 'MCP_DESTINATION_REJECTED',
5 SESSION_CONFIG_CONFLICT: 'SESSION_CONFIG_CONFLICT',
6 + TOOL_INPUT_REQUIRED: 'TOOL_INPUT_REQUIRED',
7 };
8
9 +/** One question a tool asks the user before it can run. */
10 +export interface ToolRouterInputRequest {
11 + /** Kind of input requested. */
12 + type: 'elicitation';
13 + /** How the client collects the input. */
14 + mode: 'form';
15 + /** Message to show the user. */
16 + message: string;
17 + /** JSON Schema for the answer: a flat object with string, number, boolean or enum fields. */
18 + requestedSchema: Record<string, unknown>;
19 +}
20 +
21 /**
22 * Thrown when a session's hosted MCP endpoint is not a destination the SDK
23 * will hand the session credential to. The SDK only attaches its credential
@@ -59,3 +72,55 @@ export class ComposioSessionConfigConflictError extends ComposioError {
72 this.name = 'ComposioSessionConfigConflictError';
73 }
74 }
75 +
76 +/**
77 + * Thrown when a session tool execution or proxied call did not run because it
78 + * needs input from the user first, for example an approval. The API answers
79 + * such a call with `result_type: "input_required"` instead of a result.
80 + *
81 + * `inputRequests` holds the questions, keyed by the ID the answers must
82 + * reuse. `requestState` is the opaque `request_state` the API returned; when
83 + * present it must be sent back unchanged together with the answers. The SDK
84 + * does not submit answers yet, so nothing was executed and the call is not
85 + * retried.
86 + */
87 +export class ComposioToolInputRequiredError extends ComposioError {
88 + /** Questions for the user, keyed by the ID the answers must reuse. */
89 + public readonly inputRequests: Record<string, ToolRouterInputRequest>;
90 + /**
91 + * Opaque `request_state` from the API, to be sent back unchanged with the answers.
92 + *
93 + * It is continuation state, so it is kept out of logs: the property is
94 + * non-enumerable. Read it as `error.requestState`; `console.error(error)`,
95 + * `util.inspect(error)`, `JSON.stringify(error)` and object spread leave it out.
96 + */
97 + declare public readonly requestState?: string;
98 +
99 + constructor(
100 + subject: string,
101 + details: { inputRequests: Record<string, ToolRouterInputRequest>; requestState?: string },
102 + options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
103 + ) {
104 + const count = Object.keys(details.inputRequests).length;
105 + super(
106 + `${subject} requires user input before it can run (${count} input request${count === 1 ? '' : 's'}) and was not executed. ` +
107 + 'The questions are on `inputRequests` and the opaque `request_state` to send back with the answers is on `requestState`.',
108 + {
109 + ...options,
110 + code: ToolRouterErrorCodes.TOOL_INPUT_REQUIRED,
111 + possibleFixes: options.possibleFixes ?? [
112 + 'Collect the answers described by `inputRequests`, then call the session execute endpoint again with `input_responses` and the unchanged `request_state`',
113 + 'Remove the tool, its toolkit or its tags from the `require_approval` lists of the session configuration if no approval is intended',
114 + ],
115 + }
116 + );
117 + this.name = 'ComposioToolInputRequiredError';
118 + this.inputRequests = details.inputRequests;
119 + Object.defineProperty(this, 'requestState', {
120 + value: details.requestState,
121 + enumerable: false,
122 + writable: false,
123 + configurable: true,
124 + });
125 + }
126 +}
ts/packages/core/src/lib/toolRouterParams.ts
+4 -14
@@ -195,27 +195,17 @@ export type SessionPatchBody = Omit<
195 SessionPatchParams,
196 'toolkits' | 'tools' | 'tags' | 'auth_configs' | 'preload' | 'search' | 'execute'
197 >,
198 - 'manage_connections' | 'multi_account' | 'experimental' | 'premium_usage'
198 + 'manage_connections' | 'multi_account' | 'experimental'
199 > & {
200 manage_connections?: SessionPatchManageConnectionsBody | null;
201 multi_account?: SessionPatchMultiAccountBody | null;
202 experimental?: SessionPatchExperimentalBody | null;
203 expected_config_version?: number;
204 - instant?: SessionInstantBody;
204 };
205
207 -/** SDK-owned wire contract until the generated client adopts the Instant names. */
208 -export type SessionInstantBody =
209 - | false
210 - | (Omit<Exclude<ToolRouterInstant, false>, 'returnInstantCharge'> & {
211 - return_instant_charge?: boolean;
212 - });
213 -
214 -export type SessionCreateBody = Omit<SessionCreateParams, 'premium_usage'> & {
215 - instant?: SessionInstantBody;
216 -};
217 -
218 -export const transformToolRouterInstantParams = (config: ToolRouterInstant): SessionInstantBody => {
206 +export const transformToolRouterInstantParams = (
207 + config: ToolRouterInstant
208 +): NonNullable<SessionCreateParams['instant']> => {
209 if (config === false) return false;
210 return {
211 ...(config.toolkits !== undefined && { toolkits: config.toolkits }),
ts/packages/core/src/models/CustomToolkits.ts
+1 -1
@@ -161,7 +161,7 @@ export class CustomToolkits {
161 requestOptions?: ComposioRequestOptions
162 ): Promise<CustomToolkitDeleteResponse> {
163 const result = await withCancellation(
164 - () => this.client.custom.deleteToolkit(slug, requestOptions),
164 + () => this.client.custom.deleteToolkit(slug, {}, requestOptions),
165 requestOptions?.signal
166 );
167 return transformCustomToolkitDeleteResponse(result);
ts/packages/core/src/models/SessionContext.ts
+12 -2
@@ -23,7 +23,10 @@ import {
23 findCustomTool,
24 executeCustomTool,
25 } from './customToolExecution';
26 -import { transformExecuteResponse } from '../utils/transformers/toolRouterResponseTransform';
26 +import {
27 + assertNotInputRequired,
28 + transformExecuteResponse,
29 +} from '../utils/transformers/toolRouterResponseTransform';
30 import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
31 import { inlineCustomToolsExperimental } from './inlineCustomToolsPayload';
32 import { withCancellation } from '../utils/cancellation';
@@ -85,6 +88,7 @@ export class SessionContextImpl implements SessionContext {
88 data: result.data,
89 error: result.error,
90 logId: '',
91 + resultType: result.successful ? 'completed' : 'failed',
92 });
93 }
94 assertUnambiguousCustomToolSlug(this.customToolsMap, toolSlug);
@@ -109,7 +113,9 @@ export class SessionContextImpl implements SessionContext {
113 ),
114 requestOptions?.signal
115 );
112 - return ToolRouterSessionExecuteResponseSchema.parse(transformExecuteResponse(response));
116 + return ToolRouterSessionExecuteResponseSchema.parse(
117 + transformExecuteResponse(response, toolSlug)
118 + );
119 }
120
121 /**
@@ -138,6 +144,10 @@ export class SessionContextImpl implements SessionContext {
144 requestOptions?.signal
145 );
146
147 + assertNotInputRequired(
148 + response,
149 + `${validated.data.method} proxy call for toolkit ${validated.data.toolkit}`
150 + );
151 return {
152 status: response.status,
153 data: response.data,
ts/packages/core/src/models/ToolRouter.ts
+2 -4
@@ -44,7 +44,6 @@ import type {
44 InlineCustomToolsWirePayload,
45 } from '../types/customTool.types';
46 import {
47 - type SessionCreateBody,
47 transformToolRouterTagsParams,
48 transformToolRouterToolsParams,
49 transformToolRouterManageConnectionsParams,
@@ -58,7 +57,6 @@ import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
57 import { buildMCPServerConfig } from '../lib/toolRouterMcp';
58 import { parseSessionConfigInput } from '../lib/sessionConfigConflict';
59 import { getSourceSessionConfig } from '../lib/toolRouterSourceSessionConfig';
61 -import { transformSessionConfig } from '../utils/transformers/toolRouterResponseTransform';
60 import { ToolRouterSession } from './ToolRouterSession';
61 import { ComposioRequestOptions } from '../types/requestOptions.types';
62 import { withCancellation } from '../utils/cancellation';
@@ -77,7 +75,7 @@ function getSessionMetadata(
75 session: SessionCreateResponse | SessionRetrieveResponse | SessionAttachResponse
76 ) {
77 const metadata: ToolRouterSessionMetadata = {
80 - config: transformSessionConfig(session.config),
78 + config: session.config,
79 preload: session.config.preload,
80 workbench: session.config.workbench,
81 configVersion: session.config_version,
@@ -269,7 +267,7 @@ export class ToolRouter<
267 ])
268 );
269
272 - const payload: SessionCreateBody = {
270 + const payload: SessionCreateParams = {
271 user_id: userId,
272 auth_configs: routerConfig.authConfigs,
273 connected_accounts: connectedAccountsPayload,
ts/packages/core/src/models/ToolRouterSession.ts
+22 -10
@@ -34,9 +34,9 @@ import {
34 type ToolRouterSessionDeleteResponse,
35 } from '../types/toolRouter.types';
36 import {
37 + assertNotInputRequired,
38 transformSearchResponse,
39 transformExecuteResponse,
39 - transformSessionConfig,
40 } from '../utils/transformers/toolRouterResponseTransform';
41 import { SessionMetaToolOptions } from '../types/modifiers.types';
42 import { ConnectionRequest } from '../types/connectionRequest.types';
@@ -680,6 +680,7 @@ export class ToolRouterSession<
680 * @param options - Optional execution options
681 * @param options.account - Account identifier for direct app tool execution. Accepted on every project: in multi-account sessions it picks the account; on single-account projects it must match one of the session's active connections for the toolkit. Helper/meta tools either ignore this top-level field or define their own account-selection fields.
682 * @returns The tool execution result
683 + * @throws {ComposioToolInputRequiredError} If the tool needs input from the user (for example an approval) before it can run
684 */
685 async execute(
686 toolSlug: string,
@@ -705,6 +706,7 @@ export class ToolRouterSession<
706 data: result.data,
707 error: result.error,
708 logId: '',
709 + resultType: result.successful ? 'completed' : 'failed',
710 };
711 }
712 assertUnambiguousCustomToolSlug(this.customToolsMap, toolSlug);
@@ -733,7 +735,7 @@ export class ToolRouterSession<
735 ),
736 requestOptions?.signal
737 );
736 - const transformed = transformExecuteResponse(response);
738 + const transformed = transformExecuteResponse(response, toolSlug);
739 return ToolRouterSessionExecuteResponseSchema.parse(transformed);
740 }
741
@@ -743,6 +745,7 @@ export class ToolRouterSession<
745 *
746 * @param params - Proxy request parameters (toolkit, endpoint, method, body, headers/query params)
747 * @returns The proxied API response with status, data, headers
748 + * @throws {ComposioToolInputRequiredError} If the call needs input from the user before it can run
749 */
750 async proxyExecute(
751 params: SessionProxyExecuteParams,
@@ -764,6 +767,10 @@ export class ToolRouterSession<
767 requestOptions?.signal
768 );
769
770 + assertNotInputRequired(
771 + response,
772 + `${validated.data.method} proxy call for toolkit ${validated.data.toolkit}`
773 + );
774 return {
775 status: response.status,
776 data: response.data,
@@ -866,7 +873,7 @@ export class ToolRouterSession<
873 }
874
875 this.configVersion = response.config_version;
869 - this.config = transformSessionConfig(response.config);
876 + this.config = response.config;
877 this.preload = response.config.preload;
878 this.sandbox = response.config.workbench;
879 this.warnings = response.warnings ?? [];
@@ -923,7 +930,7 @@ export class ToolRouterSession<
930 version: item.version,
931 createdAt: item.created_at,
932 isCurrent: item.is_current,
926 - config: transformSessionConfig(item.config),
933 + config: item.config,
934 })),
935 nextCursor: response.next_cursor ?? null,
936 totalPages: response.total_pages,
@@ -1119,16 +1126,21 @@ export class ToolRouterSession<
1126 }
1127 const remoteError =
1128 remoteErrorMessage ?? (typeof remoteResult?.error === 'string' ? remoteResult.error : null);
1122 - const hasAnyError = localResults.some(r => r.result.error) || !!remoteError;
1129 + // A failed execution can carry no error text, so success is read from each
1130 + // result's own verdict and not from the absence of an error message.
1131 + const hasAnyFailure =
1132 + localResults.some(r => !r.result.successful) ||
1133 + remoteResult?.successful === false ||
1134 + !!remoteError;
1135
1136 return {
1137 data: mergedData,
1126 - error: hasAnyError
1127 - ? remoteError && failedCount === 0
1128 - ? remoteError
1129 - : `${failedCount} out of ${allResults.length} tools failed`
1138 + error: hasAnyFailure
1139 + ? failedCount > 0
1140 + ? `${failedCount} out of ${allResults.length} tools failed`
1141 + : remoteError
1142 : null,
1131 - successful: !hasAnyError,
1143 + successful: !hasAnyFailure,
1144 ...(remoteResult?.instantCharge !== undefined && {
1145 instantCharge: remoteResult.instantCharge,
1146 }),
ts/packages/core/src/models/Tools.ts
+9 -3
@@ -63,7 +63,10 @@ import { dereferenceJsonSchema } from '../utils/jsonSchema';
63 import { ComposioRequestOptions } from '../types/requestOptions.types';
64 import { withCancellation } from '../utils/cancellation';
65 import { withoutRetries } from '../utils/retries';
66 -import { transformExecuteResponse } from '../utils/transformers/toolRouterResponseTransform';
66 +import {
67 + isExecutionSuccessful,
68 + transformExecuteResponse,
69 +} from '../utils/transformers/toolRouterResponseTransform';
70 import { ComposioRequestCancelledError } from '../errors/SDKErrors';
71
72 const TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500;
@@ -1236,11 +1239,14 @@ export class Tools<
1239 requestOptions?.signal
1240 );
1241
1239 - const { data, error, logId, instantCharge } = transformExecuteResponse(response);
1242 + const { data, error, logId, resultType, instantCharge } = transformExecuteResponse(
1243 + response,
1244 + toolSlug
1245 + );
1246 let result: ToolExecuteResponse = {
1247 data,
1248 error,
1243 - successful: !error,
1249 + successful: isExecutionSuccessful({ resultType, error }),
1250 logId,
1251 ...(instantCharge !== undefined && { instantCharge }),
1252 };
ts/packages/core/src/models/customToolExecution.ts
+10
@@ -10,6 +10,7 @@ import type {
10 import type { ToolExecuteResponse } from '../types/tool.types';
11 import { ValidationError } from '../errors';
12 import { ComposioRequestCancelledError, isRequestAbortError } from '../errors/SDKErrors';
13 +import { ComposioToolInputRequiredError } from '../errors/ToolRouterErrors';
14
15 /**
16 * Find a custom tool entry by slug.
@@ -59,6 +60,9 @@ export function assertUnambiguousCustomToolSlug(
60 * and wraps the result into the standard response format.
61 *
62 * Callers provide a pre-built SessionContext (which may include sibling routing).
63 + *
64 + * @throws {ComposioToolInputRequiredError} If a call the tool made through the
65 + * session context needs user input before it can run
66 */
67 export async function executeCustomTool(
68 entry: CustomToolsMapEntry,
@@ -103,6 +107,12 @@ export async function executeCustomTool(
107 if (err instanceof ComposioRequestCancelledError) {
108 throw err;
109 }
110 + // `ctx.execute()` / `ctx.proxyExecute()` asked for user input: nothing ran.
111 + // Flattening it into a failed result would drop the questions and the
112 + // request state the caller needs to answer them.
113 + if (err instanceof ComposioToolInputRequiredError) {
114 + throw err;
115 + }
116 if (options?.signal?.aborted && isRequestAbortError(err)) {
117 throw new ComposioRequestCancelledError(undefined, {
118 cause: err instanceof Error ? err : undefined,
ts/packages/core/src/provider/BaseProvider.ts
+2 -1
@@ -8,6 +8,7 @@ import {
8 ToolCallExecutionTarget,
9 } from '../types/provider.types';
10 import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
11 +import { isExecutionSuccessful } from '../utils/transformers/toolRouterResponseTransform';
12
13 /**
14 * @internal
@@ -108,7 +109,7 @@ abstract class BaseProvider<TMcpResponse> {
109 const result = await target.execute(toolSlug, arguments_);
110 return {
111 ...result,
111 - successful: result.error === null,
112 + successful: isExecutionSuccessful(result),
113 };
114 }
115
ts/packages/core/src/types/toolRouter.types.ts
+11 -11
@@ -630,6 +630,13 @@ export const ToolRouterSessionExecuteResponseSchema = z.object({
630 data: z.record(z.string(), z.unknown()),
631 error: z.string().nullable(),
632 logId: z.string(),
633 + /**
634 + * Whether the tool ran and succeeded (`completed`) or ran and failed
635 + * (`failed`). A failed execution can carry a `null` or empty `error`, so
636 + * read this rather than `error` to tell the two apart. Absent when the API
637 + * sent no `result_type`.
638 + */
639 + resultType: z.enum(['completed', 'failed']).optional(),
640 /** Actual Instant usage charge when the Session opts into returning it. */
641 instantCharge: z.unknown().optional(),
642 });
@@ -725,12 +732,10 @@ export type ToolRouterInstantResponse = z.infer<typeof ToolRouterInstantResponse
732 /**
733 * Server-side session configuration as returned by the API: toolkit/tool
734 * allowlists, tags, auth configs, connected accounts, manage_connections,
728 - * preload, sandbox (`workbench`), search, execute and Instant settings.
729 - * The generated client still declares the old policy name.
735 + * preload, sandbox (`workbench`), search, execute, proxy execute and Instant
736 + * settings.
737 */
731 -export type ToolRouterSessionConfig = Omit<SessionCreateResponse.Config, 'premium_usage'> & {
732 - instant?: false | ToolRouterInstantResponse;
733 -};
738 +export type ToolRouterSessionConfig = SessionCreateResponse.Config;
739
740 export interface ToolRouterSessionMetadata {
741 /** Present on every session built from an API response; the constructor synthesises a minimal config when absent. */
@@ -1046,12 +1051,7 @@ export type ToolRouterSessionListConfigHistoryOptions = z.infer<
1051 * The session configuration at one version, as stored by the API. This is
1052 * the wire shape (snake_case), with the Instant policy under `instant`.
1053 */
1049 -export type ToolRouterSessionConfigHistoryConfig = Omit<
1050 - SessionConfigHistoryResponse.Item.Config,
1051 - 'premium_usage'
1052 -> & {
1053 - instant?: false | ToolRouterInstantResponse;
1054 -};
1054 +export type ToolRouterSessionConfigHistoryConfig = SessionConfigHistoryResponse.Item.Config;
1055
1056 export type ToolRouterSessionConfigHistoryItem = {
1057 /** The config version this entry represents. */
ts/packages/core/src/utils/transformers/toolRouterResponseTransform.ts
+66 -25
@@ -1,23 +1,66 @@
1 /**
2 * Transforms snake_case Tool Router API responses to camelCase for SDK consumers.
3 */
4 -import { z } from 'zod/v3';
5 -import {
6 - ToolRouterInstantResponseSchema,
7 - type ToolRouterInstantResponse,
8 -} from '../../types/toolRouter.types';
9 -
10 -const SessionConfigInstantSchema = z.object({
11 - instant: z.union([z.literal(false), ToolRouterInstantResponseSchema]).optional(),
12 -});
13 -
14 -/** Session config retains its API casing, including `instant.return_instant_charge`. */
15 -export function transformSessionConfig<Config extends { premium_usage?: unknown }>(
16 - raw: Config
17 -): Omit<Config, 'premium_usage'> & { instant?: false | ToolRouterInstantResponse } {
18 - const { instant } = SessionConfigInstantSchema.parse(raw);
19 - const { premium_usage: _previousPolicy, ...config } = raw;
20 - return { ...config, ...(instant !== undefined && { instant }) };
4 +import type {
5 + SessionExecuteResponse,
6 + SessionProxyExecuteResponse,
7 +} from '@composio/client/resources/tool-router/session/session.mjs';
8 +import z from 'zod/v3';
9 +import { ComposioToolInputRequiredError } from '../../errors/ToolRouterErrors';
10 +import type { ToolRouterSessionExecuteResponse } from '../../types/toolRouter.types';
11 +
12 +/**
13 + * The `result_type` values that describe a call that ran. A server that
14 + * predates `result_type` sends none, and a value this SDK does not know is
15 + * treated the same way, so both fall back to the error-based rule in
16 + * {@link isExecutionSuccessful}.
17 + */
18 +const ExecutedResultTypeSchema = z.enum(['completed', 'failed']).optional().catch(undefined);
19 +
20 +/**
21 + * Whether a session tool execution succeeded.
22 + *
23 + * `resultType` decides when the API sent one: a `failed` execution is not
24 + * successful even when its `error` is `null` or empty. Without it, for example
25 + * from a server that predates `result_type`, an execution is successful when
26 + * it carries no error text.
27 + */
28 +export function isExecutionSuccessful(
29 + result: Pick<ToolRouterSessionExecuteResponse, 'resultType' | 'error'>
30 +): boolean {
31 + if (result.resultType !== undefined) return result.resultType === 'completed';
32 + return !result.error;
33 +}
34 +
35 +type InputRequiredResponse = Extract<
36 + SessionExecuteResponse | SessionProxyExecuteResponse,
37 + { result_type: 'input_required' }
38 +>;
39 +
40 +/**
41 + * Narrows an execute-family response to the variants that carry a result.
42 + * `input_required` means the call did not run: it is raised as a
43 + * {@link ComposioToolInputRequiredError} instead of being returned as a result
44 + * it is not.
45 + */
46 +export function assertNotInputRequired<
47 + Response extends SessionExecuteResponse | SessionProxyExecuteResponse,
48 +>(raw: Response, subject: string): asserts raw is Exclude<Response, InputRequiredResponse> {
49 + if (raw.result_type !== 'input_required') return;
50 + throw new ComposioToolInputRequiredError(subject, {
51 + inputRequests: Object.fromEntries(
52 + Object.entries(raw.input_requests).map(([id, request]) => [
53 + id,
54 + {
55 + type: request.type,
56 + mode: request.mode,
57 + message: request.message,
58 + requestedSchema: request.requested_schema,
59 + },
60 + ])
61 + ),
62 + requestState: raw.request_state,
63 + });
64 }
65
66 interface RawSearchResult {
@@ -83,13 +126,6 @@ interface RawSearchResponse {
126 time_info: RawSearchTimeInfo;
127 }
128
86 -interface RawExecuteResponse {
87 - data: Record<string, unknown>;
88 - error: string | null;
89 - log_id: string;
90 - instant_charge?: unknown;
91 -}
92 -
129 function transformSearchResult(raw: RawSearchResult) {
130 return {
131 index: raw.index,
@@ -173,12 +209,17 @@ export function transformSearchResponse(raw: RawSearchResponse) {
209
210 /**
211 * Transforms a raw session execute API response to camelCase.
212 + *
213 + * @throws {ComposioToolInputRequiredError} If the tool asked for user input instead of running
214 */
177 -export function transformExecuteResponse(raw: RawExecuteResponse) {
215 +export function transformExecuteResponse(raw: SessionExecuteResponse, toolSlug: string) {
216 + assertNotInputRequired(raw, `Tool ${toolSlug}`);
217 + const resultType = ExecutedResultTypeSchema.parse(raw.result_type);
218 return {
219 data: raw.data,
220 error: raw.error,
221 logId: raw.log_id,
222 + ...(resultType !== undefined && { resultType }),
223 ...(raw.instant_charge !== undefined && { instantCharge: raw.instant_charge }),
224 };
225 }
ts/packages/core/test/models/customTool.test.ts
+6 -1
@@ -920,7 +920,12 @@ describe('SessionContextImpl', () => {
920 const result = await ctx.execute('SIBLING_TOOL', { key: 'val' });
921
922 expect(siblingExecute).toHaveBeenCalledWith({ key: 'val' }, ctx);
923 - expect(result).toEqual({ data: { local: true }, error: null, logId: '' });
923 + expect(result).toEqual({
924 + data: { local: true },
925 + error: null,
926 + logId: '',
927 + resultType: 'completed',
928 + });
929 // Should NOT call remote
930 expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
931 });
ts/packages/core/test/models/customToolRouting.test.ts
+40
@@ -323,6 +323,7 @@ describe('ToolRouterSession execution routing', () => {
323
324 expect(result.data).toEqual({ local_result: true });
325 expect(result.logId).toBe('');
326 + expect(result.resultType).toBe('completed');
327 expect(localExecute).toHaveBeenCalledWith(
328 { category: 'prefs' },
329 expect.objectContaining({ userId: 'user_1' })
@@ -509,6 +510,24 @@ describe('ToolRouterSession execution routing', () => {
510
511 expect(result.error).toBe('boom');
512 expect(result.data).toEqual({});
513 + expect(result.resultType).toBe('failed');
514 + });
515 +
516 + it('should mark a local tool that throws an empty message as failed', async () => {
517 + const throwingTool = createCustomTool('SILENT_THROW', {
518 + name: 'Silent throw',
519 + description: 'Throws an error with no message',
520 + inputParams: z.object({}),
521 + execute: async () => {
522 + throw new Error('');
523 + },
524 + });
525 +
526 + const session = createSession(mockClient, [throwingTool]);
527 + const result = await session.execute('SILENT_THROW', {});
528 +
529 + expect(result.error).toBe('');
530 + expect(result.resultType).toBe('failed');
531 });
532
533 it('should apply Zod defaults when input is missing optional fields', async () => {
@@ -938,6 +957,27 @@ describe('ToolRouterSession execution routing', () => {
957 expect(result.error).toBe('Remote batch failed before per-tool results were produced');
958 });
959
960 + it('should report a failed remote batch that carries no error text as unsuccessful', async () => {
961 + const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
962 +
963 + toolsInstance.executeSessionTool.mockResolvedValueOnce({
964 + data: {},
965 + error: null,
966 + successful: false,
967 + });
968 +
969 + const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
970 + tools: [
971 + { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'x' } },
972 + { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } },
973 + ],
974 + sync_response_to_workbench: false,
975 + });
976 +
977 + expect(result.successful).toBe(false);
978 + expect(result.error).toBeNull();
979 + });
980 +
981 it('should forward to backend when tools array is empty', async () => {
982 const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
983
ts/packages/core/test/models/customToolkits.test.ts
+5 -1
@@ -184,7 +184,11 @@ describe('Experimental.customToolkits', () => {
184
185 const result = await customToolkits.delete('CUSTOM_MY_TOOLKIT');
186
187 - expect(mockClient.custom.deleteToolkit).toHaveBeenCalledWith('CUSTOM_MY_TOOLKIT', undefined);
187 + expect(mockClient.custom.deleteToolkit).toHaveBeenCalledWith(
188 + 'CUSTOM_MY_TOOLKIT',
189 + {},
190 + undefined
191 + );
192 expect(result).toEqual({
193 slug: 'CUSTOM_MY_TOOLKIT',
194 deleted: true,
ts/packages/core/test/models/inputRequiredExecution.test.ts new
+427
@@ -0,0 +1,427 @@
1 +import { describe, it, expect, vi, assert } from 'vitest';
2 +import ComposioClient from '@composio/client';
3 +import { z } from 'zod/v3';
4 +import { Tools } from '../../src/models/Tools';
5 +import { ToolRouterSession } from '../../src/models/ToolRouterSession';
6 +import { SessionContextImpl } from '../../src/models/SessionContext';
7 +import { inspect, format } from 'node:util';
8 +import { ComposioError, ComposioToolInputRequiredError } from '../../src/errors';
9 +import logger from '../../src/utils/logger';
10 +import { buildCustomToolsMap, createCustomTool } from '../../src/models/CustomTool';
11 +import type { CustomToolsMap, SessionContext } from '../../src/types/customTool.types';
12 +import { MockProvider } from '../utils/mocks/provider.mock';
13 +
14 +vi.mock('../../src/telemetry/Telemetry', () => ({
15 + telemetry: { instrument: vi.fn() },
16 +}));
17 +
18 +// The execute and proxy-execute endpoints answer `result_type: "input_required"`
19 +// when a call needs the user's input (an approval, for example) before it can
20 +// run. That answer carries no data, log ID or HTTP status, so it cannot be
21 +// returned as an execution result: every execution path raises it as a typed
22 +// error that carries the questions and the opaque `request_state`.
23 +//
24 +// These tests run a real client against a stubbed `fetch` so they cover the
25 +// wire shape the generated client hands to the SDK.
26 +
27 +const SESSION_ID = 'sess_123';
28 +
29 +const inputRequired = {
30 + result_type: 'input_required',
31 + input_requests: {
32 + approval_1: {
33 + type: 'elicitation',
34 + mode: 'form',
35 + message: 'Allow GMAIL_SEND_EMAIL to send this email?',
36 + requested_schema: {
37 + type: 'object',
38 + properties: { approved: { type: 'boolean' } },
39 + required: ['approved'],
40 + },
41 + },
42 + },
43 + request_state: 'opaque-state-token',
44 +};
45 +
46 +const createClient = (body: unknown) => {
47 + const fetch = vi.fn<typeof globalThis.fetch>(
48 + async () =>
49 + new Response(JSON.stringify(body), {
50 + status: 200,
51 + headers: { 'content-type': 'application/json' },
52 + })
53 + );
54 + const client = new ComposioClient({
55 + apiKey: 'test-api-key',
56 + baseURL: 'https://backend.invalid',
57 + fetch,
58 + });
59 + return { client, fetch };
60 +};
61 +
62 +const createSession = (client: ComposioClient) =>
63 + new ToolRouterSession(client, { apiKey: 'key', provider: new MockProvider() }, SESSION_ID, {
64 + type: 'http' as const,
65 + url: `https://backend.invalid/api/v3/tool_router/session/${SESSION_ID}`,
66 + });
67 +
68 +const proxyParams = {
69 + toolkit: 'github',
70 + endpoint: 'https://api.github.com/user/repos?token=secret',
71 + method: 'POST' as const,
72 + body: { name: 'repo' },
73 +};
74 +
75 +const executionPaths: Array<{
76 + name: string;
77 + subject: string;
78 + run: (client: ComposioClient) => Promise<unknown>;
79 +}> = [
80 + {
81 + name: 'provider-wrapped session tool',
82 + subject: 'Tool GMAIL_SEND_EMAIL',
83 + run: client =>
84 + new Tools(client, { provider: new MockProvider() }).executeSessionTool('GMAIL_SEND_EMAIL', {
85 + sessionId: SESSION_ID,
86 + arguments: { to: 'test@test.com' },
87 + }),
88 + },
89 + {
90 + name: 'session.execute',
91 + subject: 'Tool GMAIL_SEND_EMAIL',
92 + run: client => createSession(client).execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' }),
93 + },
94 + {
95 + name: 'session.proxyExecute',
96 + subject: 'POST proxy call for toolkit github',
97 + run: client => createSession(client).proxyExecute(proxyParams),
98 + },
99 + {
100 + name: 'custom tool context execute',
101 + subject: 'Tool GMAIL_SEND_EMAIL',
102 + run: client =>
103 + new SessionContextImpl(client, 'test-user', SESSION_ID).execute('GMAIL_SEND_EMAIL', {
104 + to: 'test@test.com',
105 + }),
106 + },
107 + {
108 + name: 'custom tool context proxyExecute',
109 + subject: 'POST proxy call for toolkit github',
110 + run: client =>
111 + new SessionContextImpl(client, 'test-user', SESSION_ID).proxyExecute(proxyParams),
112 + },
113 +];
114 +
115 +describe('execution that requires user input', () => {
116 + it.each(executionPaths)(
117 + '$name raises ComposioToolInputRequiredError',
118 + async ({ run, subject }) => {
119 + const { client, fetch } = createClient(inputRequired);
120 +
121 + const error = await run(client).catch((caught: unknown) => caught);
122 +
123 + assert(error instanceof ComposioToolInputRequiredError);
124 + expect(error.code).toBe('TS-SDK::TOOL_INPUT_REQUIRED');
125 + expect(error.message).toContain(`${subject} requires user input`);
126 + expect(error.message).toContain('request_state');
127 + // The opaque state and the proxied URL stay out of the message.
128 + expect(error.message).not.toContain('opaque-state-token');
129 + expect(error.message).not.toContain('secret');
130 + expect(error.requestState).toBe('opaque-state-token');
131 + expect(error.inputRequests).toEqual({
132 + approval_1: {
133 + type: 'elicitation',
134 + mode: 'form',
135 + message: 'Allow GMAIL_SEND_EMAIL to send this email?',
136 + requestedSchema: {
137 + type: 'object',
138 + properties: { approved: { type: 'boolean' } },
139 + required: ['approved'],
140 + },
141 + },
142 + });
143 + // The call is not repeated: answering needs the user.
144 + expect(fetch).toHaveBeenCalledTimes(1);
145 + }
146 + );
147 +
148 + // `request_state` is continuation state. It stays readable for the code that
149 + // answers the request and out of everything an error is routinely dumped into.
150 + it('keeps requestState out of inspection, serialization and pretty printing', async () => {
151 + const { client } = createClient(inputRequired);
152 + const logged = vi.spyOn(logger, 'error').mockImplementation(() => {});
153 +
154 + const error = await createSession(client)
155 + .execute('GMAIL_SEND_EMAIL', {})
156 + .catch((caught: unknown) => caught);
157 +
158 + assert(error instanceof ComposioToolInputRequiredError);
159 + expect(error.requestState).toBe('opaque-state-token');
160 +
161 + const inspected = inspect(error, { depth: null });
162 + expect(inspected).toContain('ComposioToolInputRequiredError');
163 + expect(inspected).toContain('approval_1');
164 + expect(inspected).not.toContain('opaque-state-token');
165 + // The message names the property; the property itself is not printed.
166 + expect(inspected).not.toMatch(/requestState:/);
167 + // What `console.error(error)` writes.
168 + expect(format(error)).not.toContain('opaque-state-token');
169 +
170 + const serialized = JSON.stringify(error);
171 + expect(serialized).toContain('approval_1');
172 + expect(serialized).not.toContain('opaque-state-token');
173 + expect(JSON.parse(serialized)).not.toHaveProperty('requestState');
174 +
175 + expect(Object.keys(error)).not.toContain('requestState');
176 + expect({ ...error }).not.toHaveProperty('requestState');
177 +
178 + error.prettyPrint(true);
179 + ComposioError.handle(error, { includeStack: true });
180 + expect(logged).toHaveBeenCalled();
181 + expect(JSON.stringify(logged.mock.calls)).not.toContain('opaque-state-token');
182 + logged.mockRestore();
183 + });
184 +
185 + it('leaves requestState undefined when the API returns none', async () => {
186 + const { client } = createClient({ ...inputRequired, request_state: undefined });
187 +
188 + const error = await createSession(client)
189 + .execute('GMAIL_SEND_EMAIL', {})
190 + .catch((caught: unknown) => caught);
191 +
192 + assert(error instanceof ComposioToolInputRequiredError);
193 + expect(error.requestState).toBeUndefined();
194 + });
195 +
196 + it.each([
197 + { name: 'completed', result_type: 'completed' as const, error: null },
198 + { name: 'failed', result_type: 'failed' as const, error: 'Connection not found' },
199 + ])('session.execute still returns a $name result', async ({ result_type, error }) => {
200 + const { client } = createClient({ result_type, data: { id: 'msg_1' }, error, log_id: 'log_1' });
201 +
202 + await expect(createSession(client).execute('GMAIL_SEND_EMAIL', {})).resolves.toEqual({
203 + data: { id: 'msg_1' },
204 + error,
205 + logId: 'log_1',
206 + resultType: result_type,
207 + });
208 + });
209 +
210 + it('session.proxyExecute still returns a completed result', async () => {
211 + const { client } = createClient({
212 + result_type: 'completed',
213 + status: 201,
214 + data: { id: 1 },
215 + headers: { 'x-request-id': 'req_1' },
216 + });
217 +
218 + await expect(createSession(client).proxyExecute(proxyParams)).resolves.toEqual({
219 + status: 201,
220 + data: { id: 1 },
221 + headers: { 'x-request-id': 'req_1' },
222 + });
223 + });
224 +});
225 +
226 +// A local custom tool reaches the API through the `ctx.execute()` and
227 +// `ctx.proxyExecute()` helpers. The wrapper that runs the tool turns whatever
228 +// it throws into a failed result, which must not happen to an input request:
229 +// the caller needs the questions and the request state, not a message.
230 +const customToolCalling = (call: (ctx: SessionContext) => Promise<unknown>) =>
231 + buildCustomToolsMap([
232 + createCustomTool('SEND_WELCOME_EMAIL', {
233 + name: 'Send welcome email',
234 + description: 'Sends the welcome email through a session helper',
235 + inputParams: z.object({}),
236 + execute: async (_input, ctx) => ({ sent: await call(ctx) }),
237 + }),
238 + ]);
239 +
240 +const enclosingToolBodies: Array<{
241 + name: string;
242 + subject: string;
243 + call: (ctx: SessionContext) => Promise<unknown>;
244 +}> = [
245 + {
246 + name: 'ctx.execute()',
247 + subject: 'Tool GMAIL_SEND_EMAIL',
248 + call: ctx => ctx.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' }),
249 + },
250 + {
251 + name: 'ctx.proxyExecute()',
252 + subject: 'POST proxy call for toolkit github',
253 + call: ctx => ctx.proxyExecute(proxyParams),
254 + },
255 +];
256 +
257 +const createSessionWithCustomTools = (client: ComposioClient, customToolsMap: CustomToolsMap) =>
258 + new ToolRouterSession(
259 + client,
260 + { apiKey: 'key', provider: new MockProvider() },
261 + SESSION_ID,
262 + {
263 + type: 'http' as const,
264 + url: `https://backend.invalid/api/v3/tool_router/session/${SESSION_ID}`,
265 + },
266 + undefined,
267 + customToolsMap,
268 + 'test-user'
269 + );
270 +
271 +describe('custom tool whose body requires user input', () => {
272 + it.each(enclosingToolBodies)(
273 + 'session.execute of a custom tool calling $name raises ComposioToolInputRequiredError',
274 + async ({ call, subject }) => {
275 + const { client, fetch } = createClient(inputRequired);
276 + const session = createSessionWithCustomTools(client, customToolCalling(call));
277 +
278 + const error = await session
279 + .execute('SEND_WELCOME_EMAIL', {})
280 + .catch((caught: unknown) => caught);
281 +
282 + assert(error instanceof ComposioToolInputRequiredError);
283 + expect(error.message).toContain(`${subject} requires user input`);
284 + expect(error.requestState).toBe('opaque-state-token');
285 + expect(Object.keys(error.inputRequests)).toEqual(['approval_1']);
286 + expect(fetch).toHaveBeenCalledTimes(1);
287 + }
288 + );
289 +
290 + it.each(enclosingToolBodies)(
291 + 'a sibling custom tool calling $name raises through ctx.execute()',
292 + async ({ call }) => {
293 + const { client } = createClient(inputRequired);
294 + const context = new SessionContextImpl(
295 + client,
296 + 'test-user',
297 + SESSION_ID,
298 + customToolCalling(call)
299 + );
300 +
301 + const error = await context
302 + .execute('SEND_WELCOME_EMAIL', {})
303 + .catch((caught: unknown) => caught);
304 +
305 + assert(error instanceof ComposioToolInputRequiredError);
306 + expect(error.requestState).toBe('opaque-state-token');
307 + }
308 + );
309 +
310 + it('still turns any other error thrown by the tool into a failed result', async () => {
311 + const { client } = createClient(inputRequired);
312 + const session = createSessionWithCustomTools(
313 + client,
314 + customToolCalling(async () => {
315 + throw new Error('boom');
316 + })
317 + );
318 +
319 + await expect(session.execute('SEND_WELCOME_EMAIL', {})).resolves.toEqual({
320 + data: {},
321 + error: 'boom',
322 + logId: '',
323 + resultType: 'failed',
324 + });
325 + });
326 +});
327 +
328 +// `result_type` says whether a tool that ran succeeded. A failed execution can
329 +// carry a `null` or empty `error`, so success is read from `result_type` and
330 +// only falls back to the error text when the API sent no `result_type`.
331 +const executedAnswers: Array<{
332 + name: string;
333 + result_type?: 'completed' | 'failed';
334 + error: string | null;
335 + successful: boolean;
336 +}> = [
337 + { name: 'failed with a null error', result_type: 'failed', error: null, successful: false },
338 + { name: 'failed with an empty error', result_type: 'failed', error: '', successful: false },
339 + { name: 'failed with a message', result_type: 'failed', error: 'Boom', successful: false },
340 + { name: 'completed', result_type: 'completed', error: null, successful: true },
341 + { name: 'no result_type and no error', error: null, successful: true },
342 + { name: 'no result_type and an error', error: 'Boom', successful: false },
343 +];
344 +
345 +const wireBody = ({ result_type, error }: (typeof executedAnswers)[number]) => ({
346 + ...(result_type !== undefined && { result_type }),
347 + data: {},
348 + error,
349 + log_id: 'log',
350 +});
351 +
352 +class TargetProvider extends MockProvider {
353 + executeFor(session: ToolRouterSession) {
354 + return this.executeToolForTarget(session, 'GMAIL_SEND_EMAIL', {});
355 + }
356 +}
357 +
358 +describe('session execution success', () => {
359 + it.each(executedAnswers)(
360 + 'provider-wrapped session tool: $name is successful=$successful',
361 + async answer => {
362 + const { client } = createClient(wireBody(answer));
363 +
364 + const result = await new Tools(client, { provider: new MockProvider() }).executeSessionTool(
365 + 'GMAIL_SEND_EMAIL',
366 + { sessionId: SESSION_ID, arguments: {} }
367 + );
368 +
369 + expect(result).toEqual({
370 + data: {},
371 + // The error is passed through as the API sent it.
372 + error: answer.error,
373 + successful: answer.successful,
374 + logId: 'log',
375 + });
376 + }
377 + );
378 +
379 + it.each(executedAnswers)(
380 + 'provider tool call bound to a session: $name is successful=$successful',
381 + async answer => {
382 + const { client } = createClient(wireBody(answer));
383 +
384 + const result = await new TargetProvider().executeFor(createSession(client));
385 +
386 + expect(result.successful).toBe(answer.successful);
387 + expect(result.error).toBe(answer.error);
388 + }
389 + );
390 +
391 + it.each(executedAnswers)('session.execute: $name exposes resultType', async answer => {
392 + const { client } = createClient(wireBody(answer));
393 +
394 + const result = await createSession(client).execute('GMAIL_SEND_EMAIL', {});
395 +
396 + expect(result.resultType).toBe(answer.result_type);
397 + expect(result.error).toBe(answer.error);
398 + });
399 +
400 + it.each(executedAnswers)(
401 + 'custom tool context execute: $name exposes resultType',
402 + async answer => {
403 + const { client } = createClient(wireBody(answer));
404 +
405 + const result = await new SessionContextImpl(client, 'test-user', SESSION_ID).execute(
406 + 'GMAIL_SEND_EMAIL',
407 + {}
408 + );
409 +
410 + expect(result.resultType).toBe(answer.result_type);
411 + expect(result.error).toBe(answer.error);
412 + }
413 + );
414 +
415 + it('falls back to the error text when result_type is a value the SDK does not know', async () => {
416 + const { client } = createClient({
417 + result_type: 'deferred',
418 + data: {},
419 + error: null,
420 + log_id: 'l',
421 + });
422 +
423 + const result = await createSession(client).execute('GMAIL_SEND_EMAIL', {});
424 +
425 + expect(result.resultType).toBeUndefined();
426 + });
427 +});
ts/packages/core/test/models/toolRouter.test.ts
-1
@@ -4114,7 +4114,6 @@ describe('ToolRouter', () => {
4114 ...rawHistoryItem,
4115 config: {
4116 ...rawHistoryItem.config,
4117 - premium_usage: false,
4117 instant: { toolkits: { enabled: ['exa'] }, return_instant_charge: true },
4118 },
4119 },
ts/packages/core/test/utils/toolRouterResponseTransform.test.ts
+19 -32
@@ -2,31 +2,9 @@ import { describe, it, expect } from 'vitest';
2 import {
3 transformSearchResponse,
4 transformExecuteResponse,
5 - transformSessionConfig,
5 } from '../../src/utils/transformers/toolRouterResponseTransform';
6
7 describe('toolRouterResponseTransform', () => {
9 - it('preserves the new Instant policy in server-side session config', () => {
10 - const config = {
11 - user_id: 'user_1',
12 - execute: {},
13 - search: {},
14 - preload: { tools: [] },
15 - instant: { toolkits: { enabled: ['exa'] }, return_instant_charge: true },
16 - premium_usage: false as const,
17 - };
18 - expect(transformSessionConfig(config)).toEqual({
19 - user_id: 'user_1',
20 - execute: {},
21 - search: {},
22 - preload: { tools: [] },
23 - instant: { toolkits: { enabled: ['exa'] }, return_instant_charge: true },
24 - });
25 - expect(transformSessionConfig({ ...config, instant: false }).instant).toBe(false);
26 - expect(() =>
27 - transformSessionConfig({ ...config, instant: { return_instant_charge: 'yes' } })
28 - ).toThrow();
29 - });
8 describe('transformSearchResponse', () => {
9 it('should transform snake_case search response to camelCase', () => {
10 const raw = {
@@ -198,12 +176,13 @@ describe('toolRouterResponseTransform', () => {
176 describe('transformExecuteResponse', () => {
177 it('should transform snake_case execute response to camelCase', () => {
178 const raw = {
179 + result_type: 'completed' as const,
180 data: { tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' },
181 error: null,
182 log_id: 'log_abc',
183 };
184
206 - const result = transformExecuteResponse(raw);
185 + const result = transformExecuteResponse(raw, 'GMAIL_SEND_EMAIL');
186
187 expect(result.data).toEqual({ tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' });
188 expect(result.error).toBeNull();
@@ -212,12 +191,13 @@ describe('toolRouterResponseTransform', () => {
191
192 it('should preserve error in execute response', () => {
193 const raw = {
194 + result_type: 'failed' as const,
195 data: {},
196 error: 'Connection not found',
197 log_id: 'log_err',
198 };
199
220 - const result = transformExecuteResponse(raw);
200 + const result = transformExecuteResponse(raw, 'GMAIL_SEND_EMAIL');
201
202 expect(result.error).toBe('Connection not found');
203 expect(result.logId).toBe('log_err');
@@ -225,15 +205,22 @@ describe('toolRouterResponseTransform', () => {
205
206 it('preserves the optional Instant charge without inventing one', () => {
207 expect(
228 - transformExecuteResponse({
229 - data: {},
230 - error: null,
231 - log_id: 'log_paid',
232 - instant_charge: { amount: '0.01', currency: 'USD' },
233 - }).instantCharge
234 - ).toEqual({ amount: '0.01', currency: 'USD' });
208 + transformExecuteResponse(
209 + {
210 + result_type: 'completed',
211 + data: {},
212 + error: null,
213 + log_id: 'log_paid',
214 + instant_charge: { amount: '0.01', currency: 'USD', charged_by: 'composio' },
215 + },
216 + 'EXA_SEARCH'
217 + ).instantCharge
218 + ).toEqual({ amount: '0.01', currency: 'USD', charged_by: 'composio' });
219 expect(
236 - transformExecuteResponse({ data: {}, error: null, log_id: 'log_free' })
220 + transformExecuteResponse(
221 + { result_type: 'completed', data: {}, error: null, log_id: 'log_free' },
222 + 'EXA_SEARCH'
223 + )
224 ).not.toHaveProperty('instantCharge');
225 });
226 });
uv.lock
+20 -20
@@ -820,7 +820,7 @@ dev = [
820
821 [package.metadata]
822 requires-dist = [
823 - { name = "composio-client", specifier = "==2.0.0rc9" },
823 + { name = "composio-client", specifier = "==2.0.0rc10" },
824 { name = "json-schema-to-pydantic", specifier = ">=0.4.11" },
825 { name = "jsonschema", specifier = ">=4.23.0" },
826 { name = "openai", specifier = ">=2.48.0" },
@@ -866,16 +866,16 @@ requires-dist = [
866
867 [[package]]
868 name = "composio-client"
869 -version = "2.0.0rc9"
869 +version = "2.0.0rc10"
870 source = { registry = "https://pypi.org/simple" }
871 dependencies = [
872 { name = "httpx" },
873 { name = "pydantic" },
874 { name = "typing-extensions" },
875 ]
876 -sdist = { url = "https://files.pythonhosted.org/packages/0d/f8/c8f9417ad326774f336b9c403db4716b8ee4b3045380c4d9522d27564f40/composio_client-2.0.0rc9.tar.gz", hash = "sha256:3fa445e0c371d126fac5ed9fb51832e643b93c043a330d3dd0b3138c121b37ad", size = 594983, upload-time = "2026-09-30T14:42:40.499Z" }
876 +sdist = { url = "https://files.pythonhosted.org/packages/9e/30/a7d9a34fd271a08d498adc33c3aa94d9ffafe5d0ac96e13df5d6985ce8e1/composio_client-2.0.0rc10.tar.gz", hash = "sha256:d84df3f188812af9387e22a19978f25f2e611df652910902e08b792020c7e001", size = 609782, upload-time = "2026-10-07T16:26:21.483Z" }
877 wheels = [
878 - { url = "https://files.pythonhosted.org/packages/7d/47/41cc984f607ee4858321c7f45076ad04f911161b80bb13e80c7d6c3a86ec/composio_client-2.0.0rc9-py3-none-any.whl", hash = "sha256:676e50d617dcb4a3aef0d37fb7161a364d729f749a0edc25600e8f7def931b33", size = 433199, upload-time = "2026-09-30T14:42:39.006Z" },
878 + { url = "https://files.pythonhosted.org/packages/e3/0f/0404d9e9acaf80d1a62d2a5dd7924a2f46fd65cde8f2c8b5d355ce8f1dd1/composio_client-2.0.0rc10-py3-none-any.whl", hash = "sha256:26b28ee8d89026ee6f590c35c9f7e7fa7a9f0fdcb649c49079b24bad4acbbc67", size = 443195, upload-time = "2026-10-07T16:26:19.532Z" },
879 ]
880
881 [[package]]
@@ -1216,7 +1216,7 @@ name = "exceptiongroup"
1216 version = "1.3.1"
1217 source = { registry = "https://pypi.org/simple" }
1218 dependencies = [
1219 - { name = "typing-extensions", marker = "python_full_version < '3.11'" },
1219 + { name = "typing-extensions" },
1220 ]
1221 sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }
1222 wheels = [
@@ -1867,8 +1867,8 @@ name = "httpcore2"
1867 version = "2.13.0"
1868 source = { registry = "https://pypi.org/simple" }
1869 dependencies = [
1870 - { name = "h11", marker = "python_full_version != '3.12.*' or sys_platform != 'emscripten'" },
1871 - { name = "truststore", marker = "python_full_version != '3.12.*' or sys_platform != 'emscripten'" },
1870 + { name = "h11" },
1871 + { name = "truststore" },
1872 ]
1873 sdist = { url = "https://files.pythonhosted.org/packages/15/8c/e925b1c92018abb3a1863ce1549d76d2381e334d21d65d4ac8f65dabd78a/httpcore2-2.13.0.tar.gz", hash = "sha256:2adc8be4fb285fbcd6d894298db3b52c177e74b6674eda3a76bd36be3292a3db", size = 67740, upload-time = "2026-09-14T14:18:04.717Z" }
1874 wheels = [
@@ -2123,7 +2123,7 @@ name = "importlib-metadata"
2123 version = "9.0.1"
2124 source = { registry = "https://pypi.org/simple" }
2125 dependencies = [
2126 - { name = "zipp", marker = "python_full_version < '3.12'" },
2126 + { name = "zipp" },
2127 ]
2128 sdist = { url = "https://files.pythonhosted.org/packages/6f/7e/1e7e8dc30634b93ebb3d58a3dea569ad146e656218d3960ab04f62047b29/importlib_metadata-9.0.1.tar.gz", hash = "sha256:ab830580bc0ef3db61ce8fae716389e5462b67e033018bab6d8f80ef17172f99", size = 59124, upload-time = "2026-08-28T15:30:34.646Z" }
2129 wheels = [
@@ -3495,11 +3495,11 @@ resolution-markers = [
3495 "python_full_version < '3.11'",
3496 ]
3497 dependencies = [
3498 - { name = "flatbuffers", marker = "python_full_version < '3.11'" },
3499 - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
3500 - { name = "packaging", marker = "python_full_version < '3.11'" },
3501 - { name = "protobuf", marker = "python_full_version < '3.11'" },
3502 - { name = "sympy", marker = "python_full_version < '3.11'" },
3498 + { name = "flatbuffers" },
3499 + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },
3500 + { name = "packaging" },
3501 + { name = "protobuf" },
3502 + { name = "sympy" },
3503 ]
3504 wheels = [
3505 { url = "https://files.pythonhosted.org/packages/15/41/3253db975a90c3ce1d475e2a230773a21cd7998537f0657947df6fb79861/onnxruntime-1.24.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3e6456801c66b095c5cd68e690ca25db970ea5202bd0c5b84a2c3ef7731c5a3c", size = 17332766, upload-time = "2026-03-05T17:18:59.714Z" },
@@ -3541,11 +3541,11 @@ resolution-markers = [
3541 "python_full_version == '3.11.*'",
3542 ]
3543 dependencies = [
3544 - { name = "flatbuffers", marker = "python_full_version >= '3.11'" },
3545 - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
3544 + { name = "flatbuffers" },
3545 + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
3546 { name = "numpy", version = "2.5.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
3547 - { name = "packaging", marker = "python_full_version >= '3.11'" },
3548 - { name = "protobuf", marker = "python_full_version >= '3.11'" },
3547 + { name = "packaging" },
3548 + { name = "protobuf" },
3549 ]
3550 wheels = [
3551 { url = "https://files.pythonhosted.org/packages/73/b6/e2fa6dfc8c3cd19639d452c3120fb0e02f5176b4e24ecabb24b5362be725/onnxruntime-1.30.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:f36c87ec504f4f328e968ee322e4ba9682abe66280b3425625afcbed5333fed7", size = 21533037, upload-time = "2026-09-10T16:31:03.582Z" },
@@ -5464,8 +5464,8 @@ name = "secretstorage"
5464 version = "3.5.0"
5465 source = { registry = "https://pypi.org/simple" }
5466 dependencies = [
5467 - { name = "cryptography", marker = "python_full_version != '3.12.*' or sys_platform != 'emscripten'" },
5468 - { name = "jeepney", marker = "python_full_version != '3.12.*' or sys_platform != 'emscripten'" },
5467 + { name = "cryptography" },
5468 + { name = "jeepney" },
5469 ]
5470 sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" }
5471 wheels = [
@@ -5548,7 +5548,7 @@ name = "sympy"
5548 version = "1.14.0"
5549 source = { registry = "https://pypi.org/simple" }
5550 dependencies = [
5551 - { name = "mpmath", marker = "python_full_version < '3.11'" },
5551 + { name = "mpmath" },
5552 ]
5553 sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" }
5554 wheels = [