@devries-cameron20 / composio Mirror · read-only / commits / 31e8b3f8e
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 09:45 UTC

feat(core)!: update owned clients to 2.0.0-rc.11 and drop dead API surface (#4782)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4775 - updates `@composio/client` to `2.0.0-rc.11` and `composio-client` to `2.0.0rc11` (generated from the API as served on 2026-10-08), with the lockfiles; core, slim and the CLI share the catalog pin - requires `result_type` on session execute answers: success is `result_type === "completed"`, and an answer without a known `result_type` raises the SDK's validation error instead of being guessed from the error text - rethrows the input-required error from the remote half of a mixed local and remote multi-execute batch (local results in that batch are discarded by the throw) - makes the experimental workbench Python helper branch on `result_type`, so a failed or input-required answer comes back as a helper error - removes surface the API no longer has: `ToolRouterInstantResponseSchema` / `ToolRouterInstantResponse`, the usage `instant_charge` re-parse shim, the never-forwarded Python `allow_tracing` / `entity_id` execute params, and tests and reference docs that still named `premium_usage` - breaking: - `ToolRouterSessionExecuteResponse.resultType` is required; a custom `ToolCallSession` passed to a provider must return it - `ToolRouterInstantResponseSchema` and `ToolRouterInstantResponse` are no longer exported from `@composio/core` - Python `ToolExecuteParams` loses `allow_tracing` and `entity_id`; `is_execution_successful` takes one argument ## Context What stays, and why, checked against production on 2026-10-08: - deprecated operations (`authConfigs.updateStatus`, `connectedAccounts.updateStatus` / `refresh`, `tools.getInput`, `mcp.*`, `managed_by`) still answer, so the SDK keeps them - `expectedConfigVersion` / `expected_config_version` on session update is kept deliberately, although production currently rejects it with a 400; it depends on https://github.com/ComposioHQ/platform/pull/13157 - the approval flow (`require_approval`, input-required answers) is behind the per-project `toolRouterApprovalModeEnabled` flag, off by default; the SDK raises the typed input-required error and cannot send answers yet ## Testing Against the published rc.11: `pnpm typecheck` (14/14 tasks), `pnpm lint`, `pnpm validate:changesets`, core tests (1735 passed), CLI tests (1448 passed), experimental tests (47 passed); Python `nox -s chk tst` on 3.12 (2218 passed, plus provider suites). Live smoke through the built TypeScript and Python SDKs against production (toolkits, auth configs, connected accounts, session create / search / execute / update / config history / delete): every response parsed through the SDK's own schemas. Not run: e2e suites, the docs site build. Not exercised live: a successful app-tool execution, which needs a connected account.

Alberto Schiabel committed Oct 8, 2026 at 14:32 UTC 31e8b3f8e6bedbdad316c5182f0e47a4b93bfdaf
48 files changed +579 -191
.changeset/owned-client-rc10.md
+6 -2
@@ -3,14 +3,18 @@
3 '@composio/slim': minor
4 ---
5
6 -Update the owned API client to `@composio/client@2.0.0-rc.10`.
6 +Update the owned API client to `@composio/client@2.0.0-rc.11`.
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.
10 +Every session tool that ran 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 `resultType`, which is always present; 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 alone, so a failure without error text is no longer reported as successful. `error` is returned as the API sent it. A session execute answer without `result_type`, or with a value this SDK does not know, throws `ValidationError` instead of being read as a success or a failure.
11 +
12 +A `COMPOSIO_MULTI_EXECUTE_TOOL` batch that mixes local custom tools with remote tools now throws `ComposioToolInputRequiredError` when the remote half needs user input, as an all-remote batch already did. It used to report the input request as a failure message on each remote tool, without `inputRequests` or `requestState`. Local tools in that batch have already run by then, and their results are discarded by the throw.
13
14 Breaking changes:
15
16 - `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.
17 - 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`.
18 - The session config is returned as the API sent it. The SDK no longer validates `instant` at runtime or removes a `premium_usage` key.
19 +- `ToolRouterSessionExecuteResponse` requires `resultType`. A custom `ToolCallSession` passed to a provider must return it from `execute()`, because `successful` is no longer derived from `error`.
20 +- Removed the unused `ToolRouterInstantResponseSchema` and `ToolRouterInstantResponse` exports. Use `ToolRouterSessionConfig['instant']` for the Instant policy the API returns.
.changeset/workbench-helper-result-type.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/experimental': patch
3 +---
4 +
5 +Report a failed tool execution and a call that needs user input as errors from the Python workbench helpers. `run_composio_tool` returned an empty error, which reads as success, for a `failed` execution without error text and for an `input_required` answer, and `proxy_execute` returned `(None, "")` for a proxied call that needs user input. Both now return a non-empty error. For `input_required` the error says that the call needs user input and was not executed, and `run_composio_tool` returns the questions as `input_requests` without the opaque `request_state`.
docs/content/reference/sdk-reference/python/index.mdx
+4 -4
@@ -46,7 +46,7 @@ result = composio.tools.execute(
46
47 ### before_execute
48
49 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L280)
49 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L278)
50
51 ```python
52 @before_execute(modifier: BeforeExecute | None = ..., tools: List[str | None] = ..., toolkits: List[str | None] = ...)
@@ -56,7 +56,7 @@ def my_modifier(...):
56
57 ### after_execute
58
59 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L241)
59 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L239)
60
61 ```python
62 @after_execute(modifier: AfterExecute | None = ..., tools: List[str | None] = ..., toolkits: List[str | None] = ...)
@@ -68,7 +68,7 @@ def my_modifier(...):
68
69 Build a `Modifier` for the file-upload hook (same scoping pattern as `before_execute`). Your callable may take **either**: - a single `context` argument (`BeforeFileUploadContext`) — the preferred form, exposes `context["source"]` (`"path"` or `"url"`), or - three positional arguments `(path, tool, toolkit)` — legacy form, kept for back-compat. Return a new path/URL string to substitute, or `False` to abort the upload (raises `FileUploadAbortedError`). Pass the returned `Modifier` in `modifiers=[...]` on `composio.core.models.tools.Tools.execute` or `tools.get`. Multiple such modifiers are composed in list order.
70
71 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L319)
71 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L317)
72
73 ```python
74 @before_file_upload(modifier: BeforeFileUploadLike | None = ..., tools: List[str | None] = ..., toolkits: List[str | None] = ...)
@@ -78,7 +78,7 @@ def my_modifier(...):
78
79 ### schema_modifier
80
81 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L377)
81 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L375)
82
83 ```python
84 @schema_modifier(modifier: SchemaModifier | None = ..., tools: List[str | None] = ..., toolkits: List[str | None] = ...)
docs/content/reference/sdk-reference/python/session.mdx
+15 -6
@@ -87,7 +87,7 @@ def toolkits(toolkits: List[str | None] = ..., next_cursor: str | None = ..., li
87 Search for tools by semantic use case. Returns relevant tools for the given query with schemas and guidance.
88
89 ```python
90 -def search(query: str, model: str | None = ...) -> SessionSearchResponse
90 +def search(query: str, model: str | None = ...) -> ToolRouterSessionSearchResponse
91 ```
92
93 **Parameters**
@@ -99,7 +99,7 @@ def search(query: str, model: str | None = ...) -> SessionSearchResponse
99
100 **Returns**
101
102 -`SessionSearchResponse`
102 +`ToolRouterSessionSearchResponse`
103
104 ---
105
@@ -123,6 +123,11 @@ def execute(tool_slug: str, arguments: Dict[str, Any | None] = ..., account: str
123
124 `ToolRouterSessionExecuteResponse`
125
126 +**Raises**
127 +
128 +- `ToolInputRequiredError` — If the tool needs input from the user (for example an approval) before it can run. Nothing was executed.
129 +- `ValidationError` — If the API response carries no `result_type`, or one this SDK does not know.
130 +
131 ---
132
133 ### custom_tools()
@@ -181,14 +186,18 @@ def proxy_execute(toolkit: str, endpoint: str, method: Literal['GET', 'POST', 'P
186
187 `ToolRouterSessionProxyExecuteResponse` — Proxied API response
188
189 +**Raises**
190 +
191 +- `ToolInputRequiredError` — If the call needs input from the user before it can run. Nothing was executed.
192 +
193 ---
194
195 ### update()
196
188 -Partially update the session configuration. Only the fields provided are changed; omitted fields are preserved. For each policy block `None` removes the stored override (which can increase access: `toolkits=None` restores the unrestricted default, while `toolkits={"enable": []}` denies every app toolkit and is sent as-is). Supplied `tools`, `auth_configs` and `connected_accounts` maps replace the stored map entirely. Inside `manage_connections`, `callback_url=None` removes only the stored callback URL. Experimental `premium_usage` accepts `False` to disable billed access or an object to set its filters; it does not accept `None`. Any object, even one that only sets `return_premium_charge`, re-enables premium usage on a Session set to `False`. By default the request carries no precondition: the last writer wins. Pass `expected_config_version` (for example this object's `config_version`) to make the update conditional: the API then applies it only when the stored version still matches, and a concurrent change raises `SessionConfigConflictError` (HTTP 409) instead of being overwritten. The API must support the `expected_config_version` field; otherwise it rejects the request with a 400. `expected_config_version=False` is the same as omitting it. The PATCH is never retried by the transport, so a 409 is reported exactly once. On conflict this object stays unchanged: re-fetch the session with `composio.sessions.use(session_id)` and retry against the fresh `config_version`. `config`, `config_version` and `preload` are refreshed in place only after a successful response, and the updated `config` is returned. `workbench` is a backwards-compatible alias for `sandbox`. Prefer `sandbox` in new code. All other parameters use the same types as the generated `client.tool_router.session.patch()` method.
197 +Partially update the session configuration. Only the fields provided are changed; omitted fields are preserved. For each policy block `None` removes the stored override (which can increase access: `toolkits=None` restores the unrestricted default, while `toolkits={"enable": []}` denies every app toolkit and is sent as-is). Supplied `tools`, `auth_configs` and `connected_accounts` maps replace the stored map entirely. Inside `manage_connections`, `callback_url=None` removes only the stored callback URL. Experimental `instant` accepts `False` to disable billed access or an object to set its filters; it does not accept `None`. Any object, even one that only sets `return_instant_charge`, re-enables Instant usage on a Session set to `False`. By default the request carries no precondition: the last writer wins. Pass `expected_config_version` (for example this object's `config_version`) to make the update conditional: the API then applies it only when the stored version still matches, and a concurrent change raises `SessionConfigConflictError` (HTTP 409) instead of being overwritten. The API must support the `expected_config_version` field; otherwise it rejects the request with a 400. `expected_config_version=False` is the same as omitting it. The PATCH is never retried by the transport, so a 409 is reported exactly once. On conflict this object stays unchanged: re-fetch the session with `composio.sessions.use(session_id)` and retry against the fresh `config_version`. `config`, `config_version` and `preload` are refreshed in place only after a successful response, and the updated `config` is returned. `workbench` is a backwards-compatible alias for `sandbox`. Prefer `sandbox` in new code. All other parameters use the same types as the generated `client.tool_router.session.patch()` method.
198
199 ```python
191 -def update(toolkits: Union[session_patch_params.Toolkits | None, 'Omit'] = ..., premium_usage: Union[Literal[False], ToolRouterPremiumUsageConfig, 'Omit'] = ..., tools: Union[Dict[str, session_patch_params.Tools | None], 'Omit'] = ..., tags: Union[session_patch_params.Tags | None, 'Omit'] = ..., auth_configs: Union[Dict[str, str | None], 'Omit'] = ..., connected_accounts: Union[Dict[str, SequenceNotStr[str | None]], 'Omit'] = ..., manage_connections: Union[session_patch_params.ManageConnections | None, ToolRouterUpdateManageConnectionsConfig | None, 'Omit'] = ..., sandbox: Union[session_patch_params.Workbench | None, 'Omit'] = ..., workbench: Union[session_patch_params.Workbench | None, 'Omit'] = ..., multi_account: Union[session_patch_params.MultiAccount | None, ToolRouterUpdateMultiAccountConfig | None, 'Omit'] = ..., preload: Union[session_patch_params.Preload | None, 'Omit'] = ..., search: Union[session_patch_params.Search | None, 'Omit'] = ..., execute: Union[session_patch_params.Execute | None, 'Omit'] = ..., experimental: Union[session_patch_params.Experimental | None, ToolRouterUpdateExperimentalConfig | None, 'Omit'] = ..., expected_config_version: Union[int, None, Literal[False]] = ...) -> ToolRouterSessionConfig
200 +def update(toolkits: Union[session_patch_params.Toolkits | None, 'Omit'] = ..., instant: Union[Literal[False], ToolRouterInstantConfig, 'Omit'] = ..., tools: Union[Dict[str, session_patch_params.Tools | None], 'Omit'] = ..., tags: Union[session_patch_params.Tags | None, 'Omit'] = ..., auth_configs: Union[Dict[str, str | None], 'Omit'] = ..., connected_accounts: Union[Dict[str, SequenceNotStr[str | None]], 'Omit'] = ..., manage_connections: Union[session_patch_params.ManageConnections | None, ToolRouterUpdateManageConnectionsConfig | None, 'Omit'] = ..., sandbox: Union[session_patch_params.Workbench | None, 'Omit'] = ..., workbench: Union[session_patch_params.Workbench | None, 'Omit'] = ..., multi_account: Union[session_patch_params.MultiAccount | None, ToolRouterUpdateMultiAccountConfig | None, 'Omit'] = ..., preload: Union[session_patch_params.Preload | None, 'Omit'] = ..., search: Union[session_patch_params.Search | None, 'Omit'] = ..., execute: Union[session_patch_params.Execute | None, 'Omit'] = ..., experimental: Union[session_patch_params.Experimental | None, ToolRouterUpdateExperimentalConfig | None, 'Omit'] = ..., expected_config_version: Union[int, None, Literal[False]] = ...) -> ToolRouterSessionConfig
201 ```
202
203 **Parameters**
@@ -196,7 +205,7 @@ def update(toolkits: Union[session_patch_params.Toolkits | None, 'Omit'] = ...,
205 | Name | Type |
206 |------|------|
207 | `toolkits?` | `Union[session_patch_params.Toolkits \| None, 'Omit']` |
199 -| `premium_usage?` | `Union[Literal[False], ToolRouterPremiumUsageConfig, 'Omit']` |
208 +| `instant?` | `Union[Literal[False], ToolRouterInstantConfig, 'Omit']` |
209 | `tools?` | `Union[Dict[str, session_patch_params.Tools \| None], 'Omit']` |
210 | `tags?` | `Union[session_patch_params.Tags \| None, 'Omit']` |
211 | `auth_configs?` | `Union[Dict[str, str \| None], 'Omit']` |
@@ -259,4 +268,4 @@ def delete() -> ToolRouterSessionDeleteResponse
268
269 ---
270
262 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tool_router_session.py#L184)
271 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tool_router_session.py#L210)
docs/content/reference/sdk-reference/python/tools.mdx
+1 -1
@@ -182,4 +182,4 @@ def proxy(endpoint: str, method: Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH'
182
183 ---
184
185 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tools.py#L135)
185 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tools.py#L213)
pnpm-lock.yaml
+10 -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.10
32 - version: 2.0.0-rc.10
31 + specifier: 2.0.0-rc.11
32 + version: 2.0.0-rc.11
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.10
978 + version: 2.0.0-rc.11
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.10
1229 + version: 2.0.0-rc.11
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.10
1347 + version: 2.0.0-rc.11
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.10
1743 + version: 2.0.0-rc.11
1744 '@composio/json-schema-to-zod':
1745 specifier: workspace:*
1746 version: link:../json-schema-to-zod
@@ -2245,6 +2245,7 @@ packages:
2245
2246 '@cloudflare/vitest-pool-workers@0.22.0':
2247 resolution: {integrity: sha512-OJv/qikkOgxnKxJ5xrLS7zuOLZhc/6iziU+llqZm4tiQf2CJUYwlMuXN68VaWIQebORd1AUx4w6A0oy8XRbuaQ==}
2248 + deprecated: '@cloudflare/vitest-pool-workers has been renamed to @cloudflare/vitest-plugin. This package will not receive future updates.'
2249 peerDependencies:
2250 '@vitest/runner': ^4.1.0
2251 '@vitest/snapshot': ^4.1.0
@@ -2317,8 +2318,8 @@ packages:
2318 resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
2319 engines: {node: '>=0.1.90'}
2320
2320 - '@composio/client@2.0.0-rc.10':
2321 - resolution: {integrity: sha512-HqQ+Cx2tHO759T0nB5xyAhCNLljAi83fPylO1sFO/hyco/LRfkDr24rF4lp6s30PKucRTFpGitL4W56RJMNfyQ==}
2321 + '@composio/client@2.0.0-rc.11':
2322 + resolution: {integrity: sha512-jACnskE/mH0dETIBY5C8wpbeszlr1UdPH+y5bCB+CYome2zPVXi41V5bEF+vCDOowOTXhT37y3uyWsezB8gkkw==}
2323 engines: {node: '>=22'}
2324
2325 '@cspotcode/source-map-support@0.8.1':
@@ -7464,7 +7465,7 @@ snapshots:
7465 '@colors/colors@1.5.0':
7466 optional: true
7467
7467 - '@composio/client@2.0.0-rc.10': {}
7468 + '@composio/client@2.0.0-rc.11': {}
7469
7470 '@cspotcode/source-map-support@0.8.1':
7471 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.10
37 + '@composio/client': 2.0.0-rc.11
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/_modifiers.py
-2
@@ -11,12 +11,10 @@ if t.TYPE_CHECKING:
11
12 # TODO: Maybe use `te.Unpack` in tools.execute?
13 class ToolExecuteParams(te.TypedDict):
14 - allow_tracing: te.NotRequired[t.Optional[bool]]
14 arguments: t.Dict[str, t.Optional[t.Any]]
15 connected_account_id: te.NotRequired[str]
16 custom_auth_params: te.NotRequired["tool_execute_params.CustomAuthParams"]
17 custom_connection_data: te.NotRequired["tool_execute_params.CustomConnectionData"]
19 - entity_id: te.NotRequired[str]
18 text: te.NotRequired[str]
19 user_id: te.NotRequired[str]
20 version: te.NotRequired[str]
python/composio/core/models/session_context.py
+7 -3
@@ -27,7 +27,11 @@ 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, require_executed
30 +from composio.core.models.tools import (
31 + _serialize_arguments,
32 + require_execute_result,
33 + require_executed,
34 +)
35 from composio.exceptions import ValidationError
36
37
@@ -173,7 +177,7 @@ class SessionContextImpl:
177
178 # Disable retries: a session execution is a non-idempotent write, and a
179 # silent retry after a read timeout can duplicate the side effect.
176 - return require_executed(
180 + return require_execute_result(
181 self._client.without_retries.tool_router.session.execute(
182 session_id=self._session_id,
183 tool_slug=tool_slug,
@@ -182,7 +186,7 @@ class SessionContextImpl:
186 self._inline_custom_tools_payload
187 ),
188 ),
185 - f"Tool {tool_slug}",
189 + tool_slug,
190 )
191
192 def proxy_execute(
python/composio/core/models/tool_router_session.py
+11 -5
@@ -72,7 +72,7 @@ from composio.core.models.tool_router_session_delete import (
72 from composio.core.models.tools import (
73 ToolExecuteParams,
74 ToolExecutionResponse,
75 - require_executed,
75 + require_execute_result,
76 )
77 from composio.core.provider import TTool, TToolCollection
78 from composio.core.provider.base import BaseProvider
@@ -643,6 +643,11 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
643 if remote_future:
644 try:
645 remote_result = remote_future.result()
646 + except exceptions.ToolInputRequiredError:
647 + # An input request is not a per-tool failure: re-raise it so
648 + # the caller gets `input_requests` and `request_state`.
649 + # Accepted: local tools in this batch already ran and their results are discarded.
650 + raise
651 except Exception as error:
652 remote_error_message = str(error) or "Remote tool execution failed"
653
@@ -914,11 +919,12 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
919 ``error``, ``log_id``, ``result_type``, and ``instant_charge``
920 attributes. ``result_type`` is ``"completed"`` or ``"failed"``; a failed
921 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.
922 + ``result_type`` to tell the two apart.
923
924 :raises ToolInputRequiredError: If the tool needs input from the user
925 (for example an approval) before it can run. Nothing was executed.
926 + :raises ValidationError: If the API response carries no ``result_type``,
927 + or one this SDK does not know.
928 """
929 # Check if this is a local tool (by original or final slug)
930 entry = find_custom_tool(self._custom_tools_map, tool_slug)
@@ -935,7 +941,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
941
942 # Disable retries: a session execution is a non-idempotent write, and a
943 # silent retry after a read timeout can duplicate the side effect.
938 - return require_executed(
944 + return require_execute_result(
945 self._client.without_retries.tool_router.session.execute(
946 session_id=self.session_id,
947 tool_slug=tool_slug,
@@ -945,7 +951,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
951 self._inline_custom_tools_payload
952 ),
953 ),
948 - f"Tool {tool_slug}",
954 + tool_slug,
955 )
956
957 def custom_tools(
python/composio/core/models/tools.py
+33 -20
@@ -9,6 +9,7 @@ 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 + SessionExecuteResponse,
13 )
14 from composio_client.types.tool_router.session_proxy_execute_response import (
15 SessionProxyExecuteInputRequiredResponse,
@@ -39,6 +40,7 @@ from composio.exceptions import (
40 ToolInputRequiredError,
41 ToolNotFoundError,
42 ToolVersionRequiredError,
43 + ValidationError,
44 )
45 from composio.utils.pydantic import none_to_omit
46 from composio.utils.toolkit_version import get_toolkit_version
@@ -158,22 +160,36 @@ def require_executed(
160 )
161
162
161 -def is_execution_successful(
162 - result_type: t.Optional[str], error: t.Optional[str]
163 -) -> bool:
163 +def require_execute_result(
164 + response: t.Union[SessionExecuteResponse, SessionExecuteInputRequiredResponse],
165 + slug: str,
166 +) -> SessionExecuteResponse:
167 + """Narrow a session execute response to a tool that ran.
168 +
169 + Every session execute response carries a ``result_type``. One without it,
170 + or with a value this SDK does not know, is neither a success nor a failure,
171 + so it is raised instead of being read as one. The TypeScript SDK applies
172 + the same rule.
173 +
174 + :raises ToolInputRequiredError: If the tool asked for user input instead of
175 + running.
176 + :raises ValidationError: If ``result_type`` is missing or unknown.
177 + """
178 + executed = require_executed(response, f"Tool {slug}")
179 + if getattr(executed, "result_type", None) not in ("completed", "failed"):
180 + raise ValidationError(
181 + f"Tool {slug} returned an execute response without a known result_type"
182 + )
183 + return executed
184 +
185 +
186 +def is_execution_successful(result_type: t.Optional[str]) -> bool:
187 """Whether a session tool execution succeeded.
188
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.
189 + ``result_type`` decides: a ``failed`` execution is not successful even when
190 + its ``error`` is ``None`` or empty. The TypeScript SDK applies the same rule.
191 """
172 - if result_type == "completed":
173 - return True
174 - if result_type == "failed":
175 - return False
176 - return not error
192 + return result_type == "completed"
193
194
195 class InstantCharge(te.TypedDict):
@@ -629,7 +645,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
645
646 # Disable retries: a session execution is a non-idempotent write, and a
647 # silent retry after a read timeout can duplicate the side effect.
632 - response = require_executed(
648 + response = require_execute_result(
649 self._client.without_retries.tool_router.session.execute(
650 session_id=session_id,
651 tool_slug=slug,
@@ -641,17 +657,14 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
657 inline_custom_tools_payload
658 ),
659 ),
644 - f"Tool {slug}",
660 + slug,
661 )
662
663 # Convert response to standard format
648 - error = response.error if hasattr(response, "error") else None
664 result: ToolExecutionResponse = {
665 "data": response.data if hasattr(response, "data") else {},
651 - "error": error,
652 - "successful": is_execution_successful(
653 - getattr(response, "result_type", None), error
654 - ),
666 + "error": response.error if hasattr(response, "error") else None,
667 + "successful": is_execution_successful(response.result_type),
668 }
669 instant_charge = getattr(response, "instant_charge", None)
670 if isinstance(instant_charge, PydanticBaseModel):
python/composio/core/provider/base.py
+1 -3
@@ -128,7 +128,5 @@ class BaseProvider(t.Generic[TTool, TToolCollection]):
128 return {
129 "data": t.cast(t.Dict, result.data),
130 "error": result.error,
131 - "successful": is_execution_successful(
132 - getattr(result, "result_type", None), result.error
133 - ),
131 + "successful": is_execution_successful(result.result_type),
132 }
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.0rc10",
10 + "composio-client==2.0.0rc11",
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.0rc10",
28 + "composio-client==2.0.0rc11",
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
+6 -5
@@ -789,7 +789,7 @@ class TestSessionContextImpl:
789 m = build_custom_tools_map([grep_tool])
790 mock_client = mock_http_client(MagicMock)
791 mock_client.tool_router.session.execute.return_value = SessionExecuteResponse(
792 - data={"remote": True}, error=None, log_id="log_123"
792 + data={"remote": True}, error=None, log_id="log_123", result_type="completed"
793 )
794 ctx = SessionContextImpl(
795 client=mock_client, user_id="u", session_id="s", custom_tools_map=m
@@ -805,7 +805,7 @@ class TestSessionContextImpl:
805 def test_remote_fallback_passes_inline_custom_tools(self):
806 mock_client = mock_http_client(MagicMock)
807 mock_client.tool_router.session.execute.return_value = SessionExecuteResponse(
808 - data={"remote": True}, error=None, log_id="log_123"
808 + data={"remote": True}, error=None, log_id="log_123", result_type="completed"
809 )
810 inline_payload = {
811 "custom_tools": [
@@ -989,7 +989,7 @@ class TestToolRouterSessionCustomTools:
989
990 def test_execute_remote(self, mock_session_deps):
991 mock_response = SessionExecuteResponse(
992 - data={"sent": True}, error=None, log_id="log_123"
992 + data={"sent": True}, error=None, log_id="log_123", result_type="completed"
993 )
994 mock_session_deps[
995 "client"
@@ -1015,6 +1015,7 @@ class TestToolRouterSessionCustomTools:
1015 ].tool_router.session.execute.return_value = (
1016 SessionExecuteResponse.model_validate(
1017 {
1018 + "result_type": "completed",
1019 "data": {"sent": True},
1020 "error": None,
1021 "log_id": "log_123",
@@ -1037,7 +1038,7 @@ class TestToolRouterSessionCustomTools:
1038 mock_session_deps[
1039 "client"
1040 ].tool_router.session.execute.return_value = SessionExecuteResponse(
1040 - data={"sent": True}, error=None, log_id="log_123"
1041 + data={"sent": True}, error=None, log_id="log_123", result_type="completed"
1042 )
1043 s = _session(mock_session_deps)
1044
@@ -1047,7 +1048,7 @@ class TestToolRouterSessionCustomTools:
1048
1049 def test_execute_remote_passes_inline_custom_tools(self, mock_session_deps):
1050 mock_response = SessionExecuteResponse(
1050 - data={"sent": True}, error=None, log_id="log_123"
1051 + data={"sent": True}, error=None, log_id="log_123", result_type="completed"
1052 )
1053 mock_session_deps[
1054 "client"
python/tests/test_google_provider.py
+4 -1
@@ -66,7 +66,10 @@ def _function_call_response() -> Any:
66 def _session() -> Mock:
67 session = Mock()
68 session.execute.return_value = SimpleNamespace(
69 - data={"results": []}, error=None, log_id="log-session"
69 + data={"results": []},
70 + error=None,
71 + log_id="log-session",
72 + result_type="completed",
73 )
74 return session
75
python/tests/test_provider.py
+7 -2
@@ -445,6 +445,7 @@ class TestNonAgenticProviderHelperMethods:
445 data={"tools": ["GMAIL_SEND_EMAIL"]},
446 error=None,
447 log_id="log-session",
448 + result_type="completed",
449 )
450 completion = SimpleNamespace(
451 choices=[
@@ -494,8 +495,12 @@ class TestNonAgenticProviderHelperMethods:
495 Tools(client=mock_client, provider=provider)
496 session = Mock()
497 session.execute.side_effect = [
497 - SimpleNamespace(data={"index": 1}, error=None, log_id="log-1"),
498 - SimpleNamespace(data={"index": 2}, error="failed", log_id="log-2"),
498 + SimpleNamespace(
499 + data={"index": 1}, error=None, log_id="log-1", result_type="completed"
500 + ),
501 + SimpleNamespace(
502 + data={"index": 2}, error="failed", log_id="log-2", result_type="failed"
503 + ),
504 ]
505 response = Response.model_construct(
506 output=[
python/tests/test_tool_execution.py
+6 -2
@@ -115,7 +115,9 @@ class TestToolExecution:
115 result = tools.get_raw_tool_router_meta_tools(
116 "session_123", modifiers=[observe_toolkit]
117 )
118 - mock_client.tool_router.session.execute.return_value = Mock(data={}, error=None)
118 + mock_client.tool_router.session.execute.return_value = Mock(
119 + data={}, error=None, result_type="completed"
120 + )
121 execute = tools._wrap_execute_tool_for_tool_router(
122 "session_123", modifiers=[observe_before_execute, observe_after_execute]
123 )
@@ -162,7 +164,9 @@ class TestToolExecution:
164 "required": ["attachment"],
165 }
166 tools._tool_schemas[tool.slug] = tool
165 - mock_client.tool_router.session.execute.return_value = Mock(data={}, error=None)
167 + mock_client.tool_router.session.execute.return_value = Mock(
168 + data={}, error=None, result_type="completed"
169 + )
170 execute = tools._wrap_execute_tool_for_tool_router("session_123")
171 arguments = {
172 "attachment": value,
python/tests/test_tool_router.py
+110 -18
@@ -188,7 +188,6 @@ class TestToolRouter:
188 tool_router.create(user_id="user_123", instant=policy)
189 kwargs = mock_client.tool_router.session.create.call_args.kwargs
190 assert kwargs["instant"] == policy
191 - assert "premium_usage" not in kwargs
191
192 mock_client.tool_router.session.create.reset_mock()
193 tool_router.create(user_id="user_123")
@@ -1411,6 +1410,7 @@ class TestToolRouter:
1410 mock_execute_response = MagicMock()
1411 mock_execute_response.data = {"ok": True}
1412 mock_execute_response.error = None
1413 + mock_execute_response.result_type = "completed"
1414 mock_execute_response.log_id = "log_123"
1415 mock_client.tool_router.session.execute.return_value = mock_execute_response
1416
@@ -2020,6 +2020,7 @@ class TestToolRouterExecution:
2020 mock_execute_response = MagicMock()
2021 mock_execute_response.data = {"result": "success"}
2022 mock_execute_response.error = None
2023 + mock_execute_response.result_type = "completed"
2024 mock_client.tool_router.session.execute.return_value = mock_execute_response
2025
2026 # Create a real Tools instance to test the execute function
@@ -2066,6 +2067,7 @@ class TestToolRouterExecution:
2067 mock_client.tool_router.session.execute.return_value = (
2068 SessionExecuteResponse.model_validate(
2069 {
2070 + "result_type": "completed",
2071 "data": {"result": "success"},
2072 "error": None,
2073 "log_id": "log_123",
@@ -2093,6 +2095,7 @@ class TestToolRouterExecution:
2095 mock_execute_response = MagicMock()
2096 mock_execute_response.data = {"result": "success"}
2097 mock_execute_response.error = None
2098 + mock_execute_response.result_type = "completed"
2099 mock_client.tool_router.session.execute.return_value = mock_execute_response
2100
2101 from composio.core.models.tools import Tools as RealTools
@@ -2134,6 +2137,7 @@ class TestToolRouterExecution:
2137 mock_execute_response = MagicMock()
2138 mock_execute_response.data = {"result": "success"}
2139 mock_execute_response.error = None
2140 + mock_execute_response.result_type = "completed"
2141 mock_client.tool_router.session.execute.return_value = mock_execute_response
2142
2143 # Create modifier functions
@@ -2187,6 +2191,7 @@ class TestToolRouterExecution:
2191 mock_execute_response = MagicMock()
2192 mock_execute_response.data = {}
2193 mock_execute_response.error = "Authentication failed"
2194 + mock_execute_response.result_type = "failed"
2195 mock_client.tool_router.session.execute.return_value = mock_execute_response
2196
2197 # Create a real execute function
@@ -2328,14 +2333,12 @@ class TestInstantContractTransport:
2333 router = ToolRouter(client=client, provider=MagicMock())
2334 session = router.create(user_id="user_123", instant=policy)
2335 body = json.loads(requests[0].content)
2331 - assert "premium_usage" not in body
2336 if policy is None:
2337 assert "instant" not in body
2338 else:
2339 assert body["instant"] == policy
2340 assert not isinstance(session.config.instant, bool)
2341 assert session.config.instant.return_instant_charge is True
2338 - assert "premium_usage" not in session.config.model_dump()
2342
2343 if policy is None:
2344 session.update(expected_config_version=3)
@@ -2343,14 +2346,12 @@ class TestInstantContractTransport:
2346 session.update(instant=policy, expected_config_version=3)
2347 body = json.loads(requests[-1].content)
2348 assert body["expected_config_version"] == 3
2346 - assert "premium_usage" not in body
2349 if policy is None:
2350 assert "instant" not in body
2351 else:
2352 assert body["instant"] == policy
2353 assert not isinstance(session.config.instant, bool)
2354 assert session.config.instant.return_instant_charge is True
2353 - assert "premium_usage" not in session.config.model_dump()
2355
2356 attached = router.use(session_id="session_123")
2357 assert not isinstance(attached.config.instant, bool)
@@ -2366,6 +2367,7 @@ class TestInstantContractTransport:
2367 return httpx.Response(
2368 200,
2369 json={
2370 + "result_type": "completed",
2371 "data": {},
2372 "error": None,
2373 "log_id": "log_123",
@@ -2390,7 +2392,6 @@ class TestInstantContractTransport:
2392 assert result.instant_charge is not None
2393 assert result.instant_charge.amount == "0.012"
2394 assert result.instant_charge.model_dump() == charge
2393 - assert "premium_charge" not in result.model_dump()
2395 status = session.search(query="search").toolkit_connection_statuses[0]
2396 assert status.instant_account is not None
2397 assert status.instant_account.allowed_tool_slugs == ["EXA_SEARCH"]
@@ -2710,30 +2711,69 @@ class TestCustomToolBodyRequiresUserInput:
2711 assert result.result_type == "failed"
2712
2713
2714 +class TestMixedMultiExecuteRequiresUserInput:
2715 + """A ``COMPOSIO_MULTI_EXECUTE_TOOL`` batch that mixes local and remote
2716 + tools turns a raised backend error into per-tool failures. An input request
2717 + is not one: the caller needs the questions and the request state.
2718 + """
2719 +
2720 + def test_remote_half_input_required_raises(self):
2721 + from composio.core.models.tools import Tools
2722 +
2723 + client, requests = _answering_client(_INPUT_REQUIRED_JSON)
2724 + local_calls: t.List[bool] = []
2725 + session = _session_with_custom_tools(
2726 + client, _custom_tool_calling(lambda ctx: local_calls.append(True))
2727 + )
2728 + tools = Tools(
2729 + client=client,
2730 + provider=MagicMock(),
2731 + dangerously_allow_auto_upload_download_files=False,
2732 + )
2733 + # Keep the (read) tool-schema lookup off the transport.
2734 + tools._tool_schemas["COMPOSIO_MULTI_EXECUTE_TOOL"] = MagicMock()
2735 +
2736 + with pytest.raises(ToolInputRequiredError) as raised:
2737 + session._route_multi_execute(
2738 + {
2739 + "tools": [
2740 + {"tool_slug": "SEND_WELCOME_EMAIL", "arguments": {}},
2741 + {"tool_slug": "GMAIL_SEND_EMAIL", "arguments": {}},
2742 + ]
2743 + },
2744 + tools,
2745 + )
2746 +
2747 + error = raised.value
2748 + assert "Tool COMPOSIO_MULTI_EXECUTE_TOOL requires user input" in error.message
2749 + assert list(error.input_requests) == ["approval_1"]
2750 + assert error.request_state == "opaque-state-token"
2751 + # Only the remote half reached the API, once.
2752 + assert len(requests) == 1
2753 + assert [
2754 + tool["tool_slug"]
2755 + for tool in json.loads(requests[0].content)["arguments"]["tools"]
2756 + ] == ["GMAIL_SEND_EMAIL"]
2757 + # The local tool had already run; its result is discarded by the raise.
2758 + assert local_calls == [True]
2759 +
2760 +
2761 _EXECUTED_ANSWERS = [
2762 pytest.param("failed", None, False, id="failed with a null error"),
2763 pytest.param("failed", "", False, id="failed with an empty error"),
2764 pytest.param("failed", "Boom", False, id="failed with a message"),
2765 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"),
2766 ]
2767
2768
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
2769 +def _executed_json(result_type: str, error: t.Optional[str]) -> t.Dict[str, t.Any]:
2770 + return {"result_type": result_type, "data": {}, "error": error, "log_id": "log"}
2771
2772
2773 class TestSessionExecutionSuccess:
2774 """``result_type`` says whether a tool that ran succeeded. A failed
2775 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``.
2776 + ``result_type`` alone.
2777 """
2778
2779 @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS)
@@ -2782,6 +2822,59 @@ class TestSessionExecutionSuccess:
2822 assert result.error == error
2823
2824
2825 +_INVALID_ANSWERS = [
2826 + pytest.param({"data": {}, "error": None, "log_id": "log"}, id="no result_type"),
2827 + pytest.param(
2828 + {"result_type": "deferred", "data": {}, "error": None, "log_id": "log"},
2829 + id="an unknown result_type",
2830 + ),
2831 +]
2832 +
2833 +
2834 +@pytest.mark.parametrize("body", _INVALID_ANSWERS)
2835 +class TestSessionExecuteAnswerWithoutAKnownResultType:
2836 + """Every session execute answer carries a ``result_type``. One without it,
2837 + or with a value this SDK does not know, is not a result: reading it as a
2838 + success or as a failure would be a guess, so each path raises instead.
2839 + """
2840 +
2841 + _MESSAGE = (
2842 + "Tool GMAIL_SEND_EMAIL returned an execute response without a known result_type"
2843 + )
2844 +
2845 + def test_provider_wrapped_session_tool_raises(self, body):
2846 + client, requests = _answering_client(body)
2847 +
2848 + with pytest.raises(ValidationError, match=self._MESSAGE):
2849 + _session_tool_execute_fn(client)("GMAIL_SEND_EMAIL", {})
2850 +
2851 + assert len(requests) == 1
2852 +
2853 + def test_provider_tool_call_bound_to_a_session_raises(self, body):
2854 + from composio.core.provider._openai import OpenAIProvider
2855 +
2856 + client, _ = _answering_client(body)
2857 +
2858 + with pytest.raises(ValidationError, match=self._MESSAGE):
2859 + OpenAIProvider().execute_tool_for_target(
2860 + target=_created_session(client), slug="GMAIL_SEND_EMAIL", arguments={}
2861 + )
2862 +
2863 + def test_session_execute_raises(self, body):
2864 + client, _ = _answering_client(body)
2865 +
2866 + with pytest.raises(ValidationError, match=self._MESSAGE):
2867 + _created_session(client).execute("GMAIL_SEND_EMAIL")
2868 +
2869 + def test_custom_tool_context_execute_raises(self, body):
2870 + client, _ = _answering_client(body)
2871 +
2872 + with pytest.raises(ValidationError, match=self._MESSAGE):
2873 + SessionContextImpl(client, "user_123", "session_123").execute(
2874 + "GMAIL_SEND_EMAIL", {}
2875 + )
2876 +
2877 +
2878 def _session_tool_execute_fn(client: HttpClient) -> t.Callable[..., t.Any]:
2879 """The execute function providers wrap session tools with."""
2880 from composio.core.models.tools import Tools
@@ -3104,7 +3197,6 @@ class TestSessionUpdateContract:
3197 "toolkits": {"enable": ["exa"]},
3198 "return_instant_charge": True,
3199 }
3107 - assert "premium_usage" not in kwargs
3200
3201 def test_instant_can_be_disabled(self, session, mock_client):
3202 session.update(instant=False)
python/tests/test_tool_schema_aliasing.py
+1 -1
@@ -353,7 +353,7 @@ def test_anthropic_wrap_tool_aliases_schema_and_restores_arguments(monkeypatch):
353
354 session = Mock()
355 session.execute.return_value = SimpleNamespace(
356 - data={"ok": True}, error=None, log_id="log-session"
356 + data={"ok": True}, error=None, log_id="log-session", result_type="completed"
357 )
358 provider.execute_tool.reset_mock()
359 result = provider.execute_tool_call(session=session, tool_call=tool_call)
python/tests/test_typesafe_provider.py
+3 -1
@@ -1350,7 +1350,9 @@ class TestExecute:
1350
1351 def test_executes_through_a_session_which_takes_no_modifiers(self) -> None:
1352 session = Mock()
1353 - session.execute.return_value = Mock(data={"ok": True}, error=None)
1353 + session.execute.return_value = Mock(
1354 + data={"ok": True}, error=None, result_type="completed"
1355 + )
1356 result = self.provider.execute(
1357 session=session, decision=PARTIAL, arguments={"body": "text"}
1358 )
ts/packages/cli/CHANGELOG.md
+4 -3
@@ -11,9 +11,10 @@
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.
14 +- `composio execute` now reads whether a tool succeeded from the `result_type`
15 + the API returns with every execution, so a tool that ran and failed is
16 + reported as failed even when the API returns no error text. It used to read a
17 + failed execution with a `null` error as successful.
18
19 - `composio execute` now validates the arguments before it sends the tool
20 call, so a call that fails local validation is never run. Validation used to
ts/packages/cli/src/services/tools-executor.ts
+5 -12
@@ -99,20 +99,13 @@ export const ToolsExecutor = Context.Service<ToolsExecutor>('services/ToolsExecu
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.
102 + * `result_type` decides: a `failed` execution is not successful even when its
103 + * `error` is `null` or empty. `@composio/core` applies the same rule to
104 + * session executions.
105 */
106 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 -};
107 + readonly result_type: 'completed' | 'failed';
108 +}): boolean => raw.result_type === 'completed';
109
110 /**
111 * Normalize the raw Tool Router response into the shape the CLI commands expect.
ts/packages/cli/test/__utils__/services/test-layer.ts
+2
@@ -1299,6 +1299,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1299 execute:
1300 toolRouterOverrides?.execute ??
1301 (async (_sessionId: string, params: SessionExecuteParams) => ({
1302 + result_type: 'completed' as const,
1303 data: { tool_slug: params.tool_slug, arguments: params.arguments },
1304 error: null,
1305 log_id: 'log_test',
@@ -1306,6 +1307,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1307 executeMeta:
1308 toolRouterOverrides?.executeMeta ??
1309 (async (_sessionId: string, params: SessionExecuteMetaParams) => ({
1310 + result_type: 'completed' as const,
1311 data: { slug: params.slug, arguments: params.arguments },
1312 error: null,
1313 log_id: 'log_test',
ts/packages/cli/test/src/services/tools-executor.test.ts
+4 -6
@@ -5,22 +5,20 @@ describe('isExecutionSuccessful', () => {
5 it.each([
6 {
7 name: 'failed with a null error',
8 - raw: { result_type: 'failed', error: null },
8 + raw: { result_type: 'failed' as const, error: null },
9 expected: false,
10 },
11 {
12 name: 'failed with an empty error',
13 - raw: { result_type: 'failed', error: '' },
13 + raw: { result_type: 'failed' as const, error: '' },
14 expected: false,
15 },
16 {
17 name: 'failed with a message',
18 - raw: { result_type: 'failed', error: 'Boom' },
18 + raw: { result_type: 'failed' as const, 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 },
21 + { name: 'completed', raw: { result_type: 'completed' as const, error: null }, expected: true },
22 ])('[Given] $name [Then] successful is $expected', ({ raw, expected }) => {
23 expect(isExecutionSuccessful(raw)).toBe(expected);
24 });
ts/packages/core/src/models/ToolRouterSession.ts
+10 -1
@@ -6,7 +6,10 @@ import type { ComposioRequestOptions } from '../types/requestOptions.types';
6 import { withCancellation } from '../utils/cancellation';
7 import { withoutRetries } from '../utils/retries';
8 import { ComposioRequestCancelledError } from '../errors/SDKErrors';
9 -import { ComposioSessionConfigConflictError } from '../errors/ToolRouterErrors';
9 +import {
10 + ComposioSessionConfigConflictError,
11 + ComposioToolInputRequiredError,
12 +} from '../errors/ToolRouterErrors';
13 import {
14 ToolRouterMCPServerConfig,
15 SessionExperimental,
@@ -1055,6 +1058,12 @@ export class ToolRouterSession<
1058
1059 const remoteTransportFailed = !!remoteOutcome && 'error' in remoteOutcome;
1060 const remoteTransportError = remoteTransportFailed ? remoteOutcome.error : null;
1061 + // An input request is not a per-tool failure: rethrow it so the caller gets
1062 + // `inputRequests` and `requestState`.
1063 + // Accepted: local tools in this batch already ran and their results are discarded.
1064 + if (remoteTransportError instanceof ComposioToolInputRequiredError) {
1065 + throw remoteTransportError;
1066 + }
1067 const remoteErrorMessage = remoteTransportFailed
1068 ? (remoteTransportError instanceof Error
1069 ? remoteTransportError.message
ts/packages/core/src/models/Tools.ts
+1 -1
@@ -1246,7 +1246,7 @@ export class Tools<
1246 let result: ToolExecuteResponse = {
1247 data,
1248 error,
1249 - successful: isExecutionSuccessful({ resultType, error }),
1249 + successful: isExecutionSuccessful({ resultType }),
1250 logId,
1251 ...(instantCharge !== undefined && { instantCharge }),
1252 };
ts/packages/core/src/types/toolRouter.types.ts
+2 -16
@@ -633,10 +633,9 @@ export const ToolRouterSessionExecuteResponseSchema = z.object({
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`.
636 + * read this rather than `error` to tell the two apart.
637 */
639 - resultType: z.enum(['completed', 'failed']).optional(),
638 + resultType: z.enum(['completed', 'failed']),
639 /** Actual Instant usage charge when the Session opts into returning it. */
640 instantCharge: z.unknown().optional(),
641 });
@@ -716,19 +715,6 @@ export type ToolRouterSessionWorkbenchConfig = SessionCreateResponse.Config.Work
715
716 export type ToolRouterSessionWarning = SessionCreateResponse.Warning;
717
719 -const ToolRouterInstantResponseFilterSchema = z.union([
720 - z.object({ enabled: z.array(z.string()) }),
721 - z.object({ disabled: z.array(z.string()) }),
722 -]);
723 -
724 -/** Instant policy in the server's Session config (wire field casing). */
725 -export const ToolRouterInstantResponseSchema = z.object({
726 - toolkits: ToolRouterInstantResponseFilterSchema.optional(),
727 - tools: z.record(z.string(), ToolRouterInstantResponseFilterSchema).optional(),
728 - return_instant_charge: z.boolean(),
729 -});
730 -export type ToolRouterInstantResponse = z.infer<typeof ToolRouterInstantResponseSchema>;
731 -
718 /**
719 * Server-side session configuration as returned by the API: toolkit/tool
720 * allowlists, tags, auth configs, connected accounts, manage_connections,
ts/packages/core/src/utils/transformers/toolRouterResponseTransform.ts
+16 -18
@@ -7,29 +7,20 @@ import type {
7 } from '@composio/client/resources/tool-router/session/session.mjs';
8 import z from 'zod/v3';
9 import { ComposioToolInputRequiredError } from '../../errors/ToolRouterErrors';
10 +import { ValidationError } from '../../errors/ValidationErrors';
11 import type { ToolRouterSessionExecuteResponse } from '../../types/toolRouter.types';
12
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);
13 +/** The `result_type` values of a call that ran. `input_required` is raised before this is read. */
14 +const ExecutedResponseSchema = z.object({ result_type: z.enum(['completed', 'failed']) });
15
16 /**
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.
17 + * Whether a session tool execution succeeded. `resultType` decides: a `failed`
18 + * execution is not successful even when its `error` is `null` or empty.
19 */
20 export function isExecutionSuccessful(
29 - result: Pick<ToolRouterSessionExecuteResponse, 'resultType' | 'error'>
21 + result: Pick<ToolRouterSessionExecuteResponse, 'resultType'>
22 ): boolean {
31 - if (result.resultType !== undefined) return result.resultType === 'completed';
32 - return !result.error;
23 + return result.resultType === 'completed';
24 }
25
26 type InputRequiredResponse = Extract<
@@ -211,15 +202,22 @@ export function transformSearchResponse(raw: RawSearchResponse) {
202 * Transforms a raw session execute API response to camelCase.
203 *
204 * @throws {ComposioToolInputRequiredError} If the tool asked for user input instead of running
205 + * @throws {ValidationError} If the response carries no `result_type`, or one this SDK does not know
206 */
207 export function transformExecuteResponse(raw: SessionExecuteResponse, toolSlug: string) {
208 assertNotInputRequired(raw, `Tool ${toolSlug}`);
217 - const resultType = ExecutedResultTypeSchema.parse(raw.result_type);
209 + const executed = ExecutedResponseSchema.safeParse(raw);
210 + if (!executed.success) {
211 + throw new ValidationError(
212 + `Tool ${toolSlug} returned an execute response without a known result_type`,
213 + { cause: executed.error }
214 + );
215 + }
216 return {
217 data: raw.data,
218 error: raw.error,
219 logId: raw.log_id,
222 - ...(resultType !== undefined && { resultType }),
220 + resultType: executed.data.result_type,
221 ...(raw.instant_charge !== undefined && { instantCharge: raw.instant_charge }),
222 };
223 }
ts/packages/core/src/utils/transformers/usage.ts
+1 -4
@@ -4,7 +4,6 @@ import type {
4 UsageRetrieveSummaryParams as RawUsageSummaryParams,
5 UsageRetrieveSummaryResponse as RawUsageSummaryResponse,
6 } from '@composio/client/resources/project/usage';
7 -import { z } from 'zod/v3';
7 import {
8 UsageBreakdownParams,
9 UsageBreakdownResponse,
@@ -43,8 +42,6 @@ export const transformUsageBreakdownParams = (
42 export const transformUsageSummaryResponse = (
43 response: RawUsageSummaryResponse
44 ): UsageSummaryResponse => {
46 - // The pinned generated client predates this response field but preserves the raw JSON.
47 - const { instant_charge } = z.object({ instant_charge: z.string() }).parse(response);
45 return transform(response)
46 .with(UsageSummaryResponseSchema)
47 .using(response => ({
@@ -58,7 +55,7 @@ export const transformUsageSummaryResponse = (
55 },
56 ])
57 ),
61 - instantCharge: instant_charge,
58 + instantCharge: response.instant_charge,
59 }));
60 };
61
ts/packages/core/test/models/customTool.test.ts
+12 -1
@@ -798,6 +798,7 @@ describe('SessionContextImpl', () => {
798
799 it('should delegate execute() to client.toolRouter.session.execute()', async () => {
800 mockClient.toolRouter.session.execute.mockResolvedValue({
801 + result_type: 'completed',
802 data: { result: 'ok' },
803 error: null,
804 log_id: 'log_1',
@@ -818,11 +819,13 @@ describe('SessionContextImpl', () => {
819 data: { result: 'ok' },
820 error: null,
821 logId: 'log_1',
822 + resultType: 'completed',
823 });
824 });
825
826 it('should pass inline custom tools when delegating execute() to backend', async () => {
827 mockClient.toolRouter.session.execute.mockResolvedValue({
828 + result_type: 'completed',
829 data: { result: 'ok' },
830 error: null,
831 log_id: 'log_1',
@@ -855,6 +858,7 @@ describe('SessionContextImpl', () => {
858
859 it('should preserve logId and error when execute() returns an error', async () => {
860 mockClient.toolRouter.session.execute.mockResolvedValue({
861 + result_type: 'failed',
862 data: {},
863 error: 'something went wrong',
864 log_id: 'log_2',
@@ -940,6 +944,7 @@ describe('SessionContextImpl', () => {
944 }),
945 ]);
946 mockClient.toolRouter.session.execute.mockResolvedValue({
947 + result_type: 'completed',
948 data: { remote: true },
949 error: null,
950 log_id: 'log_3',
@@ -956,11 +961,17 @@ describe('SessionContextImpl', () => {
961 },
962 { maxRetries: 0 }
963 );
959 - expect(result).toEqual({ data: { remote: true }, error: null, logId: 'log_3' });
964 + expect(result).toEqual({
965 + data: { remote: true },
966 + error: null,
967 + logId: 'log_3',
968 + resultType: 'completed',
969 + });
970 });
971
972 it('should delegate to remote when no customToolsMap is provided', async () => {
973 mockClient.toolRouter.session.execute.mockResolvedValue({
974 + result_type: 'completed',
975 data: { remote: true },
976 error: null,
977 log_id: 'log_4',
ts/packages/core/test/models/customToolRouting.test.ts
+37 -1
@@ -1,8 +1,9 @@
1 -import { describe, it, expect, vi, beforeEach } from 'vitest';
1 +import { describe, it, expect, vi, beforeEach, assert } from 'vitest';
2 import { z } from 'zod/v3';
3 import { ToolRouter } from '../../src/models/ToolRouter';
4 import { ToolRouterSession } from '../../src/models/ToolRouterSession';
5 import { createCustomTool, buildCustomToolsMap } from '../../src/models/CustomTool';
6 +import { ComposioToolInputRequiredError } from '../../src/errors';
7 import { MockProvider } from '../utils/mocks/provider.mock';
8 import ComposioClient from '@composio/client';
9 import type { CustomTool, SessionContext } from '../../src/types/customTool.types';
@@ -110,6 +111,7 @@ const createMockClient = () => ({
111 headers: { 'x-test': '1' },
112 }),
113 execute: vi.fn().mockResolvedValue({
114 + result_type: 'completed',
115 data: { remote_result: true },
116 error: null,
117 log_id: 'log_remote',
@@ -840,6 +842,40 @@ describe('ToolRouterSession execution routing', () => {
842 });
843 });
844
845 + it('should rethrow an input request from the remote half of a mixed batch', async () => {
846 + const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
847 +
848 + // What `executeSessionTool` throws when the API answers `input_required`.
849 + const inputRequired = new ComposioToolInputRequiredError('Tool COMPOSIO_MULTI_EXECUTE_TOOL', {
850 + inputRequests: {
851 + approval_1: {
852 + type: 'elicitation',
853 + mode: 'form',
854 + message: 'Allow GMAIL_SEND_EMAIL to send this email?',
855 + requestedSchema: { type: 'object' },
856 + },
857 + },
858 + requestState: 'opaque-state-token',
859 + });
860 + toolsInstance.executeSessionTool.mockRejectedValueOnce(inputRequired);
861 +
862 + const error = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
863 + tools: [
864 + { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'approval' } },
865 + { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } },
866 + ],
867 + sync_response_to_workbench: false,
868 + }).catch((caught: unknown) => caught);
869 +
870 + // The caller gets the questions and the state, not per-tool failure strings.
871 + expect(error).toBe(inputRequired);
872 + assert(error instanceof ComposioToolInputRequiredError);
873 + expect(Object.keys(error.inputRequests)).toEqual(['approval_1']);
874 + expect(error.requestState).toBe('opaque-state-token');
875 + // The local tool had already run; its result is discarded by the throw.
876 + expect(localExecute).toHaveBeenCalledTimes(1);
877 + });
878 +
879 it('should recompute remote counters when local results are merged', async () => {
880 const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
881
ts/packages/core/test/models/inputRequiredExecution.test.ts
+35 -16
@@ -5,7 +5,7 @@ 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';
8 +import { ComposioError, ComposioToolInputRequiredError, ValidationError } 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';
@@ -326,11 +326,10 @@ describe('custom tool whose body requires user input', () => {
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`.
329 +// carry a `null` or empty `error`, so success is read from `result_type` alone.
330 const executedAnswers: Array<{
331 name: string;
333 - result_type?: 'completed' | 'failed';
332 + result_type: 'completed' | 'failed';
333 error: string | null;
334 successful: boolean;
335 }> = [
@@ -338,12 +337,10 @@ const executedAnswers: Array<{
337 { name: 'failed with an empty error', result_type: 'failed', error: '', successful: false },
338 { name: 'failed with a message', result_type: 'failed', error: 'Boom', successful: false },
339 { 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 },
340 ];
341
342 const wireBody = ({ result_type, error }: (typeof executedAnswers)[number]) => ({
346 - ...(result_type !== undefined && { result_type }),
343 + result_type,
344 data: {},
345 error,
346 log_id: 'log',
@@ -411,17 +408,39 @@ describe('session execution success', () => {
408 expect(result.error).toBe(answer.error);
409 }
410 );
411 +});
412
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 - });
413 +// Every session execute answer carries a `result_type`. One without it, or with
414 +// a value this SDK does not know, is not a result: reading it as a success or
415 +// as a failure would be a guess, so each path raises instead.
416 +const invalidAnswers = [
417 + { name: 'no result_type', body: { data: {}, error: null, log_id: 'log' } },
418 + {
419 + name: 'an unknown result_type',
420 + body: { result_type: 'deferred', data: {}, error: null, log_id: 'log' },
421 + },
422 +];
423
423 - const result = await createSession(client).execute('GMAIL_SEND_EMAIL', {});
424 +const executePaths = executionPaths.filter(path => !path.name.includes('proxyExecute'));
425
425 - expect(result.resultType).toBeUndefined();
426 +describe.each(invalidAnswers)('session execute answer with $name', ({ body }) => {
427 + it.each(executePaths)('$name raises ValidationError', async ({ run }) => {
428 + const { client, fetch } = createClient(body);
429 +
430 + const error = await run(client).catch((caught: unknown) => caught);
431 +
432 + assert(error instanceof ValidationError);
433 + expect(error.message).toContain(
434 + 'Tool GMAIL_SEND_EMAIL returned an execute response without a known result_type'
435 + );
436 + expect(fetch).toHaveBeenCalledTimes(1);
437 + });
438 +
439 + it('provider tool call bound to a session raises ValidationError', async () => {
440 + const { client } = createClient(body);
441 +
442 + await expect(new TargetProvider().executeFor(createSession(client))).rejects.toBeInstanceOf(
443 + ValidationError
444 + );
445 });
446 });
ts/packages/core/test/models/toolRouter.test.ts
+2
@@ -2874,6 +2874,7 @@ describe('ToolRouter', () => {
2874 const sessionId = 'session_123';
2875
2876 const mockExecuteResponse = {
2877 + result_type: 'completed',
2878 data: { tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' },
2879 error: null,
2880 log_id: 'log_abc',
@@ -4578,6 +4579,7 @@ describe('ToolRouter', () => {
4579 },
4580 });
4581 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
4582 + result_type: 'completed',
4583 data: {},
4584 error: null,
4585 log_id: 'log_1',
ts/packages/core/test/provider/openai-provider.test.ts
+2
@@ -199,6 +199,7 @@ describe('OpenAIProvider', () => {
199 data: { tools: ['GMAIL_SEND_EMAIL'] },
200 error: null,
201 logId: 'log-session',
202 + resultType: 'completed',
203 }),
204 };
205 const chatCompletion = {
@@ -234,6 +235,7 @@ describe('OpenAIProvider', () => {
235 data: { tools: ['GMAIL_SEND_EMAIL'] },
236 error: null,
237 logId: 'log-session',
238 + resultType: 'completed',
239 successful: true,
240 }),
241 },
ts/packages/core/test/tools/fileModifiers.test.ts
+3
@@ -2095,6 +2095,7 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
2095 s3key: 'uploads/file.txt',
2096 });
2097 mockClient.toolRouter.session.execute.mockResolvedValue({
2098 + result_type: 'completed',
2099 data: { uploaded: true },
2100 error: null,
2101 log_id: 'session-log',
@@ -2289,6 +2290,7 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
2290 };
2291 const beforeExecute = vi.fn(({ params }) => params);
2292 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
2293 + result_type: 'completed',
2294 data: { ok: true },
2295 error: null,
2296 log_id: 'session-log',
@@ -2356,6 +2358,7 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
2358 next_cursor: null,
2359 });
2360 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
2361 + result_type: 'completed',
2362 data: { ok: true },
2363 error: null,
2364 log_id: 'session-log',
ts/packages/core/test/tools/tools.test.ts
+9
@@ -1341,6 +1341,7 @@ describe('Tools', () => {
1341 };
1342
1343 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1344 + result_type: 'completed',
1345 data: { results: true },
1346 error: null,
1347 log_id: '123',
@@ -1367,6 +1368,7 @@ describe('Tools', () => {
1368
1369 it('returns the Instant charge for provider-wrapped session tools', async () => {
1370 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1371 + result_type: 'completed',
1372 data: {},
1373 error: null,
1374 log_id: '123',
@@ -1389,6 +1391,7 @@ describe('Tools', () => {
1391 };
1392
1393 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1394 + result_type: 'completed',
1395 data: { results: true },
1396 error: null,
1397 log_id: '123',
@@ -1457,6 +1460,7 @@ describe('Tools', () => {
1460 };
1461
1462 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1463 + result_type: 'completed',
1464 data: { results: true },
1465 error: null,
1466 log_id: '123',
@@ -1505,6 +1509,7 @@ describe('Tools', () => {
1509 };
1510
1511 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1512 + result_type: 'completed',
1513 data: { results: true },
1514 error: null,
1515 log_id: '123',
@@ -1545,6 +1550,7 @@ describe('Tools', () => {
1550 };
1551
1552 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1553 + result_type: 'failed',
1554 data: null,
1555 error: 'Something went wrong',
1556 log_id: '456',
@@ -1573,6 +1579,7 @@ describe('Tools', () => {
1579 };
1580
1581 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1582 + result_type: 'completed',
1583 data: { results: true },
1584 error: null,
1585 log_id: '123',
@@ -1636,6 +1643,7 @@ describe('Tools', () => {
1643 context.tools.wrapToolsForToolRouter(sessionId, tools);
1644
1645 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1646 + result_type: 'completed',
1647 data: { results: true },
1648 error: null,
1649 log_id: '123',
@@ -1683,6 +1691,7 @@ describe('Tools', () => {
1691 context.tools.wrapToolsForToolRouter(sessionId, tools, modifiers);
1692
1693 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1694 + result_type: 'completed',
1695 data: { results: true },
1696 error: null,
1697 log_id: '123',
ts/packages/core/type-tests/instant-contract.test-d.ts
-11
@@ -35,17 +35,6 @@ async function instantContract(): Promise<void> {
35 const log = await composio.logs.get('log_1');
36 const loggedCharge: string | undefined = log.metadata.instant_charge;
37 void loggedCharge;
38 -
39 - // @ts-expect-error the previous policy name is no longer an SDK input
40 - await composio.create('user_123', { premiumUsage: false });
41 - // @ts-expect-error the previous visibility field is no longer accepted
42 - await session.update({ instant: { returnPremiumCharge: true } });
43 - // @ts-expect-error server-side config exposes the Instant policy
44 - void session.config.premium_usage;
45 - // @ts-expect-error config history exposes the Instant policy
46 - void historical?.config.premium_usage;
47 - // @ts-expect-error usage summaries expose the Instant charge
48 - void summary.premiumUsageCharge;
38 }
39
40 void instantContract;
ts/packages/experimental/src/workbench/python-helpers.generated.ts
+1 -1
@@ -1,4 +1,4 @@
1 // GENERATED by scripts/build-python-helpers.ts — do not edit; edit the .py source.
2 // Source: src/workbench/python-helpers/composio_helper.py
3 export const PYTHON_WORKBENCH_HELPER_SOURCE =
4 - 'import json\nimport os\nimport random\nimport time\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nimport uuid\nfrom typing import Any, Dict, Literal, Optional\n\n\n# Config is injected by the SDK via an `_INTERNAL` dict in a prologue prepended\n# at runtime. When running this file directly (e.g. pytest), default to empty.\ntry:\n _INTERNAL\nexcept NameError:\n _INTERNAL = {}\n\n\nDEFAULT_INVOKE_LLM_MODEL = _INTERNAL.get("invoke_llm_model", "openai/gpt-oss-120b")\nRATE_LIMIT_PATTERNS = (\n "rate limit",\n "ratelimit",\n "too many requests",\n "quota exceeded",\n "resource exhausted",\n)\n\n\ndef _read_env(name, default=None):\n value = os.environ.get(name)\n return default if value is None or value == "" else value\n\n\ndef _require_value(value, label):\n if value is None or value == "":\n raise RuntimeError("%s is required" % label)\n return value\n\n\ndef _request_id():\n return str(uuid.uuid4())\n\n\ndef _session_execute_url():\n backend_url = _read_env("BACKEND_URL", "https://backend.composio.dev").rstrip("/")\n session_id = _require_value(\n _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"),\n "COMPOSIO_TOOLROUTER_SESSION_ID",\n )\n encoded_session_id = urllib.parse.quote(session_id, safe="")\n return "%s/api/v3/tool_router/session/%s/execute" % (backend_url, encoded_session_id)\n\n\ndef _session_proxy_execute_url():\n backend_url = _read_env("BACKEND_URL", "https://backend.composio.dev").rstrip("/")\n session_id = _require_value(\n _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"),\n "COMPOSIO_TOOLROUTER_SESSION_ID",\n )\n encoded_session_id = urllib.parse.quote(session_id, safe="")\n return "%s/api/v3/tool_router/session/%s/proxy_execute" % (\n backend_url,\n encoded_session_id,\n )\n\n\ndef _post_json(url, headers, payload, timeout=120):\n body = json.dumps(payload).encode("utf-8")\n request = urllib.request.Request(url, data=body, headers=headers, method="POST")\n try:\n with urllib.request.urlopen(request, timeout=timeout) as response:\n return response.status, dict(response.headers), response.read().decode("utf-8")\n except urllib.error.HTTPError as error:\n return error.code, dict(error.headers), error.read().decode("utf-8")\n\n\ndef _parse_json(text):\n if not text:\n return {}\n return json.loads(text)\n\n\ndef _safe_json(text):\n try:\n return _parse_json(text)\n except json.JSONDecodeError:\n return {"raw": text}\n\n\ndef _contains_rate_limit_error(payload):\n # Only inspect the API "error" field, not the whole body — otherwise benign\n # tool output mentioning "rate limit"/"quota" triggers spurious retries.\n if not isinstance(payload, dict):\n return False\n error = payload.get("error")\n if not error:\n return False\n text = json.dumps(error, default=str).lower()\n return any(pattern in text for pattern in RATE_LIMIT_PATTERNS)\n\n\ndef _retry_delay(attempt, delay_ms):\n base_delay = max(delay_ms, 0) / 1000.0\n if base_delay == 0:\n return\n # Exponential backoff: double the delay each attempt (parity with Apollo).\n backoff = base_delay * (2 ** attempt)\n jitter = random.uniform(0, min(backoff * 0.2, 0.5))\n time.sleep(backoff + jitter)\n\n\ndef _json_shape(value):\n if isinstance(value, dict):\n return {key: _json_shape(item) for key, item in value.items()}\n if isinstance(value, list):\n return [_json_shape(value[0])] if value else []\n if value is None:\n return "null"\n return type(value).__name__\n\n\ndef print_json_structure(value):\n print(json.dumps(_json_shape(value), indent=2, sort_keys=True))\n\n\ndef _track_helper_event(*_args, **_kwargs):\n return None\n\n\ndef run_composio_tool(\n tool_slug,\n arguments=None,\n retry_params=None,\n print_schema_for_tool=True,\n *,\n account=None,\n):\n if not tool_slug:\n return {}, "tool_slug is required"\n\n api_key = _require_value(_read_env("COMPOSIO_API_KEY"), "COMPOSIO_API_KEY")\n retry_config = {"max_retries": 3, "delay_ms": 2000}\n if retry_params:\n retry_config.update(retry_params)\n\n payload = {\n "tool_slug": str(tool_slug).strip().upper(),\n "arguments": arguments or {},\n }\n if account is not None:\n payload["account"] = account\n\n headers = {\n "Content-Type": "application/json",\n "x-api-key": api_key,\n "x-request-id": _request_id(),\n }\n max_retries = int(retry_config.get("max_retries", 3))\n delay_ms = int(retry_config.get("delay_ms", 2000))\n\n for attempt in range(max_retries + 1):\n try:\n status, _headers, text = _post_json(_session_execute_url(), headers, payload)\n except (urllib.error.URLError, TimeoutError) as error:\n # Network failure (timeout, connection/DNS error). Never retry it:\n # the backend may already have run the tool and does not deduplicate\n # executions, so re-sending can repeat the side effect. Surface it as\n # the error tuple instead of throwing.\n return {}, "Composio tool request failed: %s" % error\n\n if status == 429 and attempt < max_retries:\n _retry_delay(attempt, delay_ms)\n continue\n\n if status >= 400:\n response_data = _safe_json(text)\n return response_data, "Composio tool execution failed with HTTP %s" % status\n\n try:\n response_data = _parse_json(text)\n except json.JSONDecodeError as error:\n return {"raw": text}, "Failed to parse Composio tool response as JSON: %s" % error\n\n if _contains_rate_limit_error(response_data) and attempt < max_retries:\n _retry_delay(attempt, delay_ms)\n continue\n\n # A failed tool call returns HTTP 200 with a top-level "error" field;\n # surface it as the error tuple element so callers don\'t read it as success.\n if isinstance(response_data, dict) and response_data.get("error"):\n return response_data, str(response_data["error"])\n\n if print_schema_for_tool:\n print_json_structure(response_data)\n return response_data, ""\n\n return {}, "Composio tool execution failed after retries"\n\n\ndef _strip_code_fence(content):\n stripped = content.strip()\n code_fence = chr(96) * 3\n if stripped.startswith(code_fence):\n stripped = stripped[3:].strip()\n if stripped.lower().startswith("json"):\n stripped = stripped[4:].strip()\n if stripped.endswith(code_fence):\n stripped = stripped[:-3].strip()\n elif stripped.lower().startswith("json\\n"):\n stripped = stripped[5:].strip()\n return stripped.strip()\n\n\ndef invoke_llm(query, reasoning_effort=None):\n if not query:\n return "", "query is required"\n\n system_prompt = (\n "You are a generic, smart large language model. "\n "When asked to output a JSON, respond only with valid JSON - "\n "no other text / code fences / quotes around the JSON."\n )\n response, error = run_composio_tool(\n "COMPOSIO_SEARCH_GROQ_CHAT",\n {\n "model": DEFAULT_INVOKE_LLM_MODEL,\n "messages": [\n {"role": "system", "content": system_prompt},\n {"role": "user", "content": query},\n ],\n "temperature": 0.5,\n },\n None,\n False,\n )\n _track_helper_event("invoke_llm", {"reasoning_effort": reasoning_effort})\n\n if error:\n return "", error\n\n choices = (response.get("data") or {}).get("choices", "")\n if not choices:\n return "", "No choices returned from invoke_llm"\n\n first_choice = choices[0] if isinstance(choices, list) else choices\n content = (first_choice.get("message") or {}).get("content", "")\n if not content:\n return "", "No content returned from invoke_llm"\n return _strip_code_fence(content), ""\n\n\ndef web_search(query):\n if not query:\n return "", "query is required"\n\n response, error = run_composio_tool(\n "COMPOSIO_SEARCH_EXA_ANSWER",\n {"content": query},\n None,\n False,\n )\n _track_helper_event("web_search", {})\n\n if error:\n return "", error\n return (response.get("data") or {}).get("answer", ""), ""\n\n\ndef proxy_execute(\n method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"],\n endpoint: str,\n toolkit: str,\n query_params: Optional[Dict[str, str]] = None,\n body: Optional[object] = None,\n headers: Optional[Dict[str, str]] = None,\n) -> tuple[Any, str]:\n """Call a toolkit\'s API directly when no Composio tool exists.\n\n The session resolves the connected account and injects auth server-side, so\n your code never handles raw credentials.\n\n Args:\n method: HTTP method to use for the request. Example: "GET"\n endpoint: API endpoint to call. Example: "/repos/owner/repo"\n toolkit: Name of the toolkit. Example: "GITHUB"\n query_params: Query parameters as key-value pairs. Example: {"q": "is:unread"}\n body: The request body (required for POST, PUT, and PATCH requests)\n headers: HTTP headers as key-value pairs. Example: {"Accept": "application/json"}\n\n Returns:\n tuple[Any, str]:\n - data: Response data from the API (None if error)\n - error: Error message ("" if no error)\n """\n # Wrapped end-to-end so the helper always returns a (data, error) tuple\n # rather than raising.\n try:\n valid_methods = ["GET", "POST", "PUT", "DELETE", "PATCH"]\n if method.upper() not in valid_methods:\n return None, "Invalid HTTP method: " + method\n\n if not endpoint.strip():\n return None, "Endpoint cannot be empty"\n\n if not toolkit.strip():\n return None, "Toolkit cannot be empty"\n\n if query_params is not None and not isinstance(query_params, dict):\n return None, (\n "Invalid query_params type: expected dict or None, got "\n + type(query_params).__name__\n )\n\n if headers is not None and not isinstance(headers, dict):\n return None, (\n "Invalid headers type: expected dict or None, got "\n + type(headers).__name__\n )\n\n if method.upper() in ["POST", "PUT", "PATCH"] and body is None:\n return None, "Body is required for " + method.upper() + " requests"\n\n if method.upper() in ["GET", "DELETE"] and body is not None:\n return None, "Body should not be provided for " + method.upper() + " requests"\n\n api_key = _read_env("COMPOSIO_API_KEY")\n if not api_key:\n return None, "Missing environment variable COMPOSIO_API_KEY"\n if not _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"):\n return None, "Missing environment variable COMPOSIO_TOOLROUTER_SESSION_ID"\n\n # Convert query_params and headers dicts to the flat parameters array.\n parameters = []\n if query_params:\n for key, value in query_params.items():\n parameters.append({"name": key, "value": str(value), "type": "query"})\n if headers:\n for key, value in headers.items():\n parameters.append({"name": key, "value": str(value), "type": "header"})\n\n payload = {\n "toolkit_slug": toolkit.lower(),\n "endpoint": endpoint,\n "method": method.upper(),\n }\n if parameters:\n payload["parameters"] = parameters\n if body is not None:\n payload["body"] = body\n\n request_headers = {\n "Content-Type": "application/json",\n "x-api-key": api_key,\n "x-request-id": _request_id(),\n }\n\n status, _response_headers, text = _post_json(\n _session_proxy_execute_url(), request_headers, payload\n )\n\n # Handle HTTP errors explicitly. Always surface a non-empty message so a\n # >=400 response never looks like success (an empty error/message field\n # must not win over the default).\n if status >= 400:\n error_msg = "HTTP " + str(status) + " Error"\n try:\n error_data = json.loads(text)\n if isinstance(error_data, dict):\n error_msg = (\n error_data.get("error") or error_data.get("message") or error_msg\n )\n except (ValueError, TypeError):\n if text:\n sanitized = text[:200].replace("\\n", " ").strip()\n error_msg = "HTTP " + str(status) + ": " + sanitized\n return None, str(error_msg)\n\n response_data = json.loads(text)\n\n # The session wraps the proxied response as {data, status, headers}; the\n # toolkit\'s own API may still report a >=400 status inside that envelope.\n # `status` can arrive as a string or null, so coerce it before comparing\n # — a bare `>= 400` against a non-int would raise and mask a valid result.\n if isinstance(response_data, dict):\n try:\n api_status = int(response_data.get("status", 200))\n except (TypeError, ValueError):\n api_status = 200\n if api_status >= 400:\n error_msg = "API request failed"\n if isinstance(response_data.get("data"), dict):\n error_msg = response_data["data"].get(\n "message", response_data["data"].get("error", error_msg)\n )\n return response_data, "API returned status " + str(api_status) + ": " + str(error_msg)\n return response_data.get("data"), ""\n\n return response_data, ""\n except Exception as error:\n return None, "Failed to execute proxy request: " + str(error)\n';
4 + 'import json\nimport os\nimport random\nimport time\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nimport uuid\nfrom typing import Any, Dict, Literal, Optional\n\n\n# Config is injected by the SDK via an `_INTERNAL` dict in a prologue prepended\n# at runtime. When running this file directly (e.g. pytest), default to empty.\ntry:\n _INTERNAL\nexcept NameError:\n _INTERNAL = {}\n\n\nDEFAULT_INVOKE_LLM_MODEL = _INTERNAL.get("invoke_llm_model", "openai/gpt-oss-120b")\nRATE_LIMIT_PATTERNS = (\n "rate limit",\n "ratelimit",\n "too many requests",\n "quota exceeded",\n "resource exhausted",\n)\n\n\ndef _read_env(name, default=None):\n value = os.environ.get(name)\n return default if value is None or value == "" else value\n\n\ndef _require_value(value, label):\n if value is None or value == "":\n raise RuntimeError("%s is required" % label)\n return value\n\n\ndef _request_id():\n return str(uuid.uuid4())\n\n\ndef _session_execute_url():\n backend_url = _read_env("BACKEND_URL", "https://backend.composio.dev").rstrip("/")\n session_id = _require_value(\n _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"),\n "COMPOSIO_TOOLROUTER_SESSION_ID",\n )\n encoded_session_id = urllib.parse.quote(session_id, safe="")\n return "%s/api/v3/tool_router/session/%s/execute" % (backend_url, encoded_session_id)\n\n\ndef _session_proxy_execute_url():\n backend_url = _read_env("BACKEND_URL", "https://backend.composio.dev").rstrip("/")\n session_id = _require_value(\n _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"),\n "COMPOSIO_TOOLROUTER_SESSION_ID",\n )\n encoded_session_id = urllib.parse.quote(session_id, safe="")\n return "%s/api/v3/tool_router/session/%s/proxy_execute" % (\n backend_url,\n encoded_session_id,\n )\n\n\ndef _post_json(url, headers, payload, timeout=120):\n body = json.dumps(payload).encode("utf-8")\n request = urllib.request.Request(url, data=body, headers=headers, method="POST")\n try:\n with urllib.request.urlopen(request, timeout=timeout) as response:\n return response.status, dict(response.headers), response.read().decode("utf-8")\n except urllib.error.HTTPError as error:\n return error.code, dict(error.headers), error.read().decode("utf-8")\n\n\ndef _parse_json(text):\n if not text:\n return {}\n return json.loads(text)\n\n\ndef _safe_json(text):\n try:\n return _parse_json(text)\n except json.JSONDecodeError:\n return {"raw": text}\n\n\ndef _contains_rate_limit_error(payload):\n # Only inspect the API "error" field, not the whole body — otherwise benign\n # tool output mentioning "rate limit"/"quota" triggers spurious retries.\n if not isinstance(payload, dict):\n return False\n error = payload.get("error")\n if not error:\n return False\n text = json.dumps(error, default=str).lower()\n return any(pattern in text for pattern in RATE_LIMIT_PATTERNS)\n\n\ndef _retry_delay(attempt, delay_ms):\n base_delay = max(delay_ms, 0) / 1000.0\n if base_delay == 0:\n return\n # Exponential backoff: double the delay each attempt (parity with Apollo).\n backoff = base_delay * (2 ** attempt)\n jitter = random.uniform(0, min(backoff * 0.2, 0.5))\n time.sleep(backoff + jitter)\n\n\ndef _json_shape(value):\n if isinstance(value, dict):\n return {key: _json_shape(item) for key, item in value.items()}\n if isinstance(value, list):\n return [_json_shape(value[0])] if value else []\n if value is None:\n return "null"\n return type(value).__name__\n\n\ndef print_json_structure(value):\n print(json.dumps(_json_shape(value), indent=2, sort_keys=True))\n\n\ndef _track_helper_event(*_args, **_kwargs):\n return None\n\n\ndef _is_input_required(payload):\n return isinstance(payload, dict) and payload.get("result_type") == "input_required"\n\n\ndef _input_required_error(subject, payload):\n # The message names the call and counts the questions. `request_state` is\n # opaque continuation state, so it stays out of the message.\n input_requests = payload.get("input_requests")\n count = len(input_requests) if isinstance(input_requests, dict) else 0\n return "%s requires user input before it can run (%d input request%s) and was not executed" % (\n subject,\n count,\n "" if count == 1 else "s",\n )\n\n\ndef run_composio_tool(\n tool_slug,\n arguments=None,\n retry_params=None,\n print_schema_for_tool=True,\n *,\n account=None,\n):\n if not tool_slug:\n return {}, "tool_slug is required"\n\n api_key = _require_value(_read_env("COMPOSIO_API_KEY"), "COMPOSIO_API_KEY")\n retry_config = {"max_retries": 3, "delay_ms": 2000}\n if retry_params:\n retry_config.update(retry_params)\n\n payload = {\n "tool_slug": str(tool_slug).strip().upper(),\n "arguments": arguments or {},\n }\n if account is not None:\n payload["account"] = account\n\n headers = {\n "Content-Type": "application/json",\n "x-api-key": api_key,\n "x-request-id": _request_id(),\n }\n max_retries = int(retry_config.get("max_retries", 3))\n delay_ms = int(retry_config.get("delay_ms", 2000))\n\n for attempt in range(max_retries + 1):\n try:\n status, _headers, text = _post_json(_session_execute_url(), headers, payload)\n except (urllib.error.URLError, TimeoutError) as error:\n # Network failure (timeout, connection/DNS error). Never retry it:\n # the backend may already have run the tool and does not deduplicate\n # executions, so re-sending can repeat the side effect. Surface it as\n # the error tuple instead of throwing.\n return {}, "Composio tool request failed: %s" % error\n\n if status == 429 and attempt < max_retries:\n _retry_delay(attempt, delay_ms)\n continue\n\n if status >= 400:\n response_data = _safe_json(text)\n return response_data, "Composio tool execution failed with HTTP %s" % status\n\n try:\n response_data = _parse_json(text)\n except json.JSONDecodeError as error:\n return {"raw": text}, "Failed to parse Composio tool response as JSON: %s" % error\n\n if _contains_rate_limit_error(response_data) and attempt < max_retries:\n _retry_delay(attempt, delay_ms)\n continue\n\n # The call needs the user\'s input (an approval, for example) and did not\n # run. Hand back the questions, without `request_state`, as an error.\n if _is_input_required(response_data):\n return (\n {\n "result_type": "input_required",\n "input_requests": response_data.get("input_requests") or {},\n },\n _input_required_error("Tool %s" % payload["tool_slug"], response_data),\n )\n\n # A failed tool call returns HTTP 200. `result_type` says it failed even\n # when "error" is null or empty; a response without `result_type` is\n # failed when it carries an "error". Surface either as the error tuple\n # element so callers don\'t read it as success.\n if isinstance(response_data, dict) and (\n response_data.get("result_type") == "failed" or response_data.get("error")\n ):\n return response_data, str(\n response_data.get("error") or "Composio tool execution failed without an error message"\n )\n\n if print_schema_for_tool:\n print_json_structure(response_data)\n return response_data, ""\n\n return {}, "Composio tool execution failed after retries"\n\n\ndef _strip_code_fence(content):\n stripped = content.strip()\n code_fence = chr(96) * 3\n if stripped.startswith(code_fence):\n stripped = stripped[3:].strip()\n if stripped.lower().startswith("json"):\n stripped = stripped[4:].strip()\n if stripped.endswith(code_fence):\n stripped = stripped[:-3].strip()\n elif stripped.lower().startswith("json\\n"):\n stripped = stripped[5:].strip()\n return stripped.strip()\n\n\ndef invoke_llm(query, reasoning_effort=None):\n if not query:\n return "", "query is required"\n\n system_prompt = (\n "You are a generic, smart large language model. "\n "When asked to output a JSON, respond only with valid JSON - "\n "no other text / code fences / quotes around the JSON."\n )\n response, error = run_composio_tool(\n "COMPOSIO_SEARCH_GROQ_CHAT",\n {\n "model": DEFAULT_INVOKE_LLM_MODEL,\n "messages": [\n {"role": "system", "content": system_prompt},\n {"role": "user", "content": query},\n ],\n "temperature": 0.5,\n },\n None,\n False,\n )\n _track_helper_event("invoke_llm", {"reasoning_effort": reasoning_effort})\n\n if error:\n return "", error\n\n choices = (response.get("data") or {}).get("choices", "")\n if not choices:\n return "", "No choices returned from invoke_llm"\n\n first_choice = choices[0] if isinstance(choices, list) else choices\n content = (first_choice.get("message") or {}).get("content", "")\n if not content:\n return "", "No content returned from invoke_llm"\n return _strip_code_fence(content), ""\n\n\ndef web_search(query):\n if not query:\n return "", "query is required"\n\n response, error = run_composio_tool(\n "COMPOSIO_SEARCH_EXA_ANSWER",\n {"content": query},\n None,\n False,\n )\n _track_helper_event("web_search", {})\n\n if error:\n return "", error\n return (response.get("data") or {}).get("answer", ""), ""\n\n\ndef proxy_execute(\n method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"],\n endpoint: str,\n toolkit: str,\n query_params: Optional[Dict[str, str]] = None,\n body: Optional[object] = None,\n headers: Optional[Dict[str, str]] = None,\n) -> tuple[Any, str]:\n """Call a toolkit\'s API directly when no Composio tool exists.\n\n The session resolves the connected account and injects auth server-side, so\n your code never handles raw credentials.\n\n Args:\n method: HTTP method to use for the request. Example: "GET"\n endpoint: API endpoint to call. Example: "/repos/owner/repo"\n toolkit: Name of the toolkit. Example: "GITHUB"\n query_params: Query parameters as key-value pairs. Example: {"q": "is:unread"}\n body: The request body (required for POST, PUT, and PATCH requests)\n headers: HTTP headers as key-value pairs. Example: {"Accept": "application/json"}\n\n Returns:\n tuple[Any, str]:\n - data: Response data from the API (None if error)\n - error: Error message ("" if no error)\n """\n # Wrapped end-to-end so the helper always returns a (data, error) tuple\n # rather than raising.\n try:\n valid_methods = ["GET", "POST", "PUT", "DELETE", "PATCH"]\n if method.upper() not in valid_methods:\n return None, "Invalid HTTP method: " + method\n\n if not endpoint.strip():\n return None, "Endpoint cannot be empty"\n\n if not toolkit.strip():\n return None, "Toolkit cannot be empty"\n\n if query_params is not None and not isinstance(query_params, dict):\n return None, (\n "Invalid query_params type: expected dict or None, got "\n + type(query_params).__name__\n )\n\n if headers is not None and not isinstance(headers, dict):\n return None, (\n "Invalid headers type: expected dict or None, got "\n + type(headers).__name__\n )\n\n if method.upper() in ["POST", "PUT", "PATCH"] and body is None:\n return None, "Body is required for " + method.upper() + " requests"\n\n if method.upper() in ["GET", "DELETE"] and body is not None:\n return None, "Body should not be provided for " + method.upper() + " requests"\n\n api_key = _read_env("COMPOSIO_API_KEY")\n if not api_key:\n return None, "Missing environment variable COMPOSIO_API_KEY"\n if not _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"):\n return None, "Missing environment variable COMPOSIO_TOOLROUTER_SESSION_ID"\n\n # Convert query_params and headers dicts to the flat parameters array.\n parameters = []\n if query_params:\n for key, value in query_params.items():\n parameters.append({"name": key, "value": str(value), "type": "query"})\n if headers:\n for key, value in headers.items():\n parameters.append({"name": key, "value": str(value), "type": "header"})\n\n payload = {\n "toolkit_slug": toolkit.lower(),\n "endpoint": endpoint,\n "method": method.upper(),\n }\n if parameters:\n payload["parameters"] = parameters\n if body is not None:\n payload["body"] = body\n\n request_headers = {\n "Content-Type": "application/json",\n "x-api-key": api_key,\n "x-request-id": _request_id(),\n }\n\n status, _response_headers, text = _post_json(\n _session_proxy_execute_url(), request_headers, payload\n )\n\n # Handle HTTP errors explicitly. Always surface a non-empty message so a\n # >=400 response never looks like success (an empty error/message field\n # must not win over the default).\n if status >= 400:\n error_msg = "HTTP " + str(status) + " Error"\n try:\n error_data = json.loads(text)\n if isinstance(error_data, dict):\n error_msg = (\n error_data.get("error") or error_data.get("message") or error_msg\n )\n except (ValueError, TypeError):\n if text:\n sanitized = text[:200].replace("\\n", " ").strip()\n error_msg = "HTTP " + str(status) + ": " + sanitized\n return None, str(error_msg)\n\n response_data = json.loads(text)\n\n # The call needs the user\'s input (an approval, for example) and was\n # never proxied: it has no status or data to return.\n if _is_input_required(response_data):\n return None, _input_required_error(\n "%s proxy call for toolkit %s" % (method.upper(), toolkit.lower()),\n response_data,\n )\n\n # The session wraps the proxied response as {data, status, headers}; the\n # toolkit\'s own API may still report a >=400 status inside that envelope.\n # `status` can arrive as a string or null, so coerce it before comparing\n # — a bare `>= 400` against a non-int would raise and mask a valid result.\n if isinstance(response_data, dict):\n try:\n api_status = int(response_data.get("status", 200))\n except (TypeError, ValueError):\n api_status = 200\n if api_status >= 400:\n error_msg = "API request failed"\n if isinstance(response_data.get("data"), dict):\n error_msg = response_data["data"].get(\n "message", response_data["data"].get("error", error_msg)\n )\n return response_data, "API returned status " + str(api_status) + ": " + str(error_msg)\n return response_data.get("data"), ""\n\n return response_data, ""\n except Exception as error:\n return None, "Failed to execute proxy request: " + str(error)\n';
ts/packages/experimental/src/workbench/python-helpers/composio_helper.py
+45 -4
@@ -128,6 +128,22 @@ def _track_helper_event(*_args, **_kwargs):
128 return None
129
130
131 +def _is_input_required(payload):
132 + return isinstance(payload, dict) and payload.get("result_type") == "input_required"
133 +
134 +
135 +def _input_required_error(subject, payload):
136 + # The message names the call and counts the questions. `request_state` is
137 + # opaque continuation state, so it stays out of the message.
138 + input_requests = payload.get("input_requests")
139 + count = len(input_requests) if isinstance(input_requests, dict) else 0
140 + return "%s requires user input before it can run (%d input request%s) and was not executed" % (
141 + subject,
142 + count,
143 + "" if count == 1 else "s",
144 + )
145 +
146 +
147 def run_composio_tool(
148 tool_slug,
149 arguments=None,
@@ -186,10 +202,27 @@ def run_composio_tool(
202 _retry_delay(attempt, delay_ms)
203 continue
204
189 - # A failed tool call returns HTTP 200 with a top-level "error" field;
190 - # surface it as the error tuple element so callers don't read it as success.
191 - if isinstance(response_data, dict) and response_data.get("error"):
192 - return response_data, str(response_data["error"])
205 + # The call needs the user's input (an approval, for example) and did not
206 + # run. Hand back the questions, without `request_state`, as an error.
207 + if _is_input_required(response_data):
208 + return (
209 + {
210 + "result_type": "input_required",
211 + "input_requests": response_data.get("input_requests") or {},
212 + },
213 + _input_required_error("Tool %s" % payload["tool_slug"], response_data),
214 + )
215 +
216 + # A failed tool call returns HTTP 200. `result_type` says it failed even
217 + # when "error" is null or empty; a response without `result_type` is
218 + # failed when it carries an "error". Surface either as the error tuple
219 + # element so callers don't read it as success.
220 + if isinstance(response_data, dict) and (
221 + response_data.get("result_type") == "failed" or response_data.get("error")
222 + ):
223 + return response_data, str(
224 + response_data.get("error") or "Composio tool execution failed without an error message"
225 + )
226
227 if print_schema_for_tool:
228 print_json_structure(response_data)
@@ -378,6 +411,14 @@ def proxy_execute(
411
412 response_data = json.loads(text)
413
414 + # The call needs the user's input (an approval, for example) and was
415 + # never proxied: it has no status or data to return.
416 + if _is_input_required(response_data):
417 + return None, _input_required_error(
418 + "%s proxy call for toolkit %s" % (method.upper(), toolkit.lower()),
419 + response_data,
420 + )
421 +
422 # The session wraps the proxied response as {data, status, headers}; the
423 # toolkit's own API may still report a >=400 status inside that envelope.
424 # `status` can arrive as a string or null, so coerce it before comparing
ts/packages/experimental/test/workbench/shim.test.ts
+117
@@ -175,6 +175,123 @@ print(_json.dumps({
175 }
176 });
177
178 + it('reports a failed execution and an input request through the error channel', () => {
179 + const source = experimental_createPythonWorkbenchHelperSource();
180 + const directory = mkdtempSync(join(tmpdir(), 'composio-helper-'));
181 + const scriptPath = join(directory, 'helper_result_type_test.py');
182 + const testScript = `${source}
183 +
184 +import json as _json
185 +
186 +_INPUT_REQUIRED = {
187 + "result_type": "input_required",
188 + "input_requests": {
189 + "approval_1": {
190 + "type": "elicitation",
191 + "mode": "form",
192 + "message": "Allow GMAIL_SEND_EMAIL to send this email?",
193 + "requested_schema": {"type": "object"},
194 + }
195 + },
196 + "request_state": "opaque-state-token",
197 +}
198 +
199 +_answers = {
200 + # A failed execution can carry a null or empty error.
201 + "failed_null": {"result_type": "failed", "data": {}, "error": None, "log_id": "log"},
202 + "failed_empty": {"result_type": "failed", "data": {}, "error": "", "log_id": "log"},
203 + "failed_message": {"result_type": "failed", "data": {}, "error": "Boom", "log_id": "log"},
204 + "completed": {"result_type": "completed", "data": {"ok": True}, "error": None, "log_id": "log"},
205 + "input_required": _INPUT_REQUIRED,
206 +}
207 +_calls = []
208 +_results = {}
209 +
210 +for _name, _answer in _answers.items():
211 + def _post_json(url, headers, payload, timeout=120, _answer=_answer):
212 + _calls.append(_name)
213 + return 200, {}, _json.dumps(_answer)
214 +
215 + _data, _error = run_composio_tool("gmail_send_email", {}, {"delay_ms": 0}, False)
216 + _results[_name] = {"data": _data, "error": _error}
217 +
218 +def _post_json(url, headers, payload, timeout=120):
219 + return 200, {}, _json.dumps(_INPUT_REQUIRED)
220 +
221 +_proxy_data, _proxy_error = proxy_execute("POST", "/user/repos", "GitHub", body={"name": "repo"})
222 +_results["proxy_input_required"] = {"data": _proxy_data, "error": _proxy_error}
223 +
224 +def _post_json(url, headers, payload, timeout=120):
225 + return 200, {}, _json.dumps({"result_type": "completed", "data": {"id": 1}, "status": 201})
226 +
227 +_proxy_data, _proxy_error = proxy_execute("POST", "/user/repos", "github", body={"name": "repo"})
228 +_results["proxy_completed"] = {"data": _proxy_data, "error": _proxy_error}
229 +
230 +print(_json.dumps({"calls": _calls, "results": _results}))
231 +`;
232 +
233 + try {
234 + writeFileSync(scriptPath, testScript);
235 + const output = execFileSync('python3', [scriptPath], {
236 + env: {
237 + ...process.env,
238 + BACKEND_URL: 'https://backend.test/',
239 + COMPOSIO_TOOLROUTER_SESSION_ID: 'session_123',
240 + COMPOSIO_API_KEY: 'project_key',
241 + },
242 + encoding: 'utf8',
243 + });
244 + const { calls, results } = JSON.parse(output);
245 +
246 + expect(results.failed_null.error).toBe(
247 + 'Composio tool execution failed without an error message'
248 + );
249 + expect(results.failed_null.data).toMatchObject({ result_type: 'failed', log_id: 'log' });
250 + expect(results.failed_empty.error).toBe(
251 + 'Composio tool execution failed without an error message'
252 + );
253 + expect(results.failed_message.error).toBe('Boom');
254 + expect(results.completed).toEqual({
255 + data: { result_type: 'completed', data: { ok: true }, error: null, log_id: 'log' },
256 + error: '',
257 + });
258 +
259 + expect(results.input_required.error).toBe(
260 + 'Tool GMAIL_SEND_EMAIL requires user input before it can run (1 input request) and was not executed'
261 + );
262 + expect(results.input_required.data).toEqual({
263 + result_type: 'input_required',
264 + input_requests: {
265 + approval_1: {
266 + type: 'elicitation',
267 + mode: 'form',
268 + message: 'Allow GMAIL_SEND_EMAIL to send this email?',
269 + requested_schema: { type: 'object' },
270 + },
271 + },
272 + });
273 + expect(results.proxy_input_required).toEqual({
274 + data: null,
275 + error:
276 + 'POST proxy call for toolkit github requires user input before it can run (1 input request) and was not executed',
277 + });
278 + expect(results.proxy_completed).toEqual({ data: { id: 1 }, error: '' });
279 +
280 + // The opaque continuation state reaches neither the data nor the message.
281 + expect(output).not.toContain('opaque-state-token');
282 + // Nothing is re-sent: a failure or an input request is not a retry signal.
283 + expect(calls).toEqual([
284 + 'failed_null',
285 + 'failed_empty',
286 + 'failed_message',
287 + 'completed',
288 + 'input_required',
289 + ]);
290 + } finally {
291 + rmSync(directory, { recursive: true, force: true });
292 + }
293 + });
294 +
295 it('round-trips helper calls through the session execute endpoint shape', () => {
296 const source = experimental_createPythonWorkbenchHelperSource({
297 invokeLlmModel: 'test/model',
ts/packages/providers/anthropic/test/anthropic.test.ts
+2
@@ -217,11 +217,13 @@ describe('AnthropicProvider', () => {
217 data: { result: 'success' },
218 error: null,
219 logId: 'log-success',
220 + resultType: 'completed',
221 })
222 .mockResolvedValueOnce({
223 data: {},
224 error: 'Tool execution failed',
225 logId: 'log-failure',
226 + resultType: 'failed',
227 }),
228 };
229
ts/packages/providers/anthropic/test/sanitize-keys.test.ts
+1
@@ -625,6 +625,7 @@ describe('AnthropicProvider key sanitization', () => {
625 data: { ok: true },
626 error: null,
627 logId: 'log-session',
628 + resultType: 'completed',
629 }),
630 };
631 provider._setExecuteToolFn(directExecute);
ts/packages/providers/cloudflare/test/cloudflare.test.ts
+8 -1
@@ -317,6 +317,7 @@ describe('CloudflareProvider', () => {
317 data: { result: 'session-success' },
318 error: null,
319 logId: 'log-session',
320 + resultType: 'completed',
321 }),
322 };
323
@@ -333,13 +334,19 @@ describe('CloudflareProvider', () => {
334 data: { result: 'session-success' },
335 error: null,
336 logId: 'log-session',
337 + resultType: 'completed',
338 successful: true,
339 });
340 });
341
342 it('reports a failed session execution in the result', async () => {
343 const session = {
342 - execute: vi.fn().mockResolvedValue({ data: {}, error: 'Tool failed', logId: 'log-fail' }),
344 + execute: vi.fn().mockResolvedValue({
345 + data: {},
346 + error: 'Tool failed',
347 + logId: 'log-fail',
348 + resultType: 'failed',
349 + }),
350 };
351
352 const result = await provider.executeToolCall(session, {
ts/packages/providers/google/test/google.test.ts
+8 -1
@@ -269,6 +269,7 @@ describe('GoogleProvider', () => {
269 data: { result: 'session-success' },
270 error: null,
271 logId: 'log-session',
272 + resultType: 'completed',
273 }),
274 };
275
@@ -285,13 +286,19 @@ describe('GoogleProvider', () => {
286 data: { result: 'session-success' },
287 error: null,
288 logId: 'log-session',
289 + resultType: 'completed',
290 successful: true,
291 });
292 });
293
294 it('reports a failed session execution in the result', async () => {
295 const session = {
294 - execute: vi.fn().mockResolvedValue({ data: {}, error: 'Tool failed', logId: 'log-fail' }),
296 + execute: vi.fn().mockResolvedValue({
297 + data: {},
298 + error: 'Tool failed',
299 + logId: 'log-fail',
300 + resultType: 'failed',
301 + }),
302 };
303
304 const result = await provider.executeToolCall(session, {
ts/packages/providers/openai/test/opeanai-responses.test.ts
+9 -1
@@ -444,7 +444,12 @@ describe('OpenAIResponsesProvider', () => {
444 const session = {
445 execute: vi
446 .fn()
447 - .mockResolvedValueOnce({ data: { index: 1 }, error: null, logId: 'log-1' })
447 + .mockResolvedValueOnce({
448 + data: { index: 1 },
449 + error: null,
450 + logId: 'log-1',
451 + resultType: 'completed',
452 + })
453 .mockRejectedValueOnce(new Error('session execution failed')),
454 };
455 const toolCalls = [
@@ -481,6 +486,7 @@ describe('OpenAIResponsesProvider', () => {
486 data: { index: 1 },
487 error: null,
488 logId: 'log-1',
489 + resultType: 'completed',
490 successful: true,
491 }),
492 status: 'completed',
@@ -695,6 +701,7 @@ describe('OpenAIResponsesProvider', () => {
701 data: { result: 'session-success' },
702 error: null,
703 logId: 'log-session',
704 + resultType: 'completed',
705 }),
706 };
707 const response = {
@@ -724,6 +731,7 @@ describe('OpenAIResponsesProvider', () => {
731 data: { result: 'session-success' },
732 error: null,
733 logId: 'log-session',
734 + resultType: 'completed',
735 successful: true,
736 }),
737 status: 'completed',
ts/packages/providers/typesafe/test/execute.test.ts
+6 -1
@@ -124,7 +124,12 @@ describe('execute', () => {
124
125 it('executes through a session, which takes no modifiers', async () => {
126 const session = {
127 - execute: vi.fn().mockResolvedValue({ data: { ok: true }, error: null, logId: 'log_1' }),
127 + execute: vi.fn().mockResolvedValue({
128 + data: { ok: true },
129 + error: null,
130 + logId: 'log_1',
131 + resultType: 'completed',
132 + }),
133 };
134 const result = await provider.execute(session as ToolCallSession, partial, {
135 arguments: { body: 'text' },
uv.lock
+4 -4
@@ -820,7 +820,7 @@ dev = [
820
821 [package.metadata]
822 requires-dist = [
823 - { name = "composio-client", specifier = "==2.0.0rc10" },
823 + { name = "composio-client", specifier = "==2.0.0rc11" },
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.0rc10"
869 +version = "2.0.0rc11"
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/9e/30/a7d9a34fd271a08d498adc33c3aa94d9ffafe5d0ac96e13df5d6985ce8e1/composio_client-2.0.0rc10.tar.gz", hash = "sha256:d84df3f188812af9387e22a19978f25f2e611df652910902e08b792020c7e001", size = 609782, upload-time = "2026-10-07T16:26:21.483Z" }
876 +sdist = { url = "https://files.pythonhosted.org/packages/ff/a3/249e8e1e5d089b32b1fae4d876efa7b9b378266ec53f330d94e596edccbe/composio_client-2.0.0rc11.tar.gz", hash = "sha256:b8adb6992a11be5b92755009c13fe3910d20f11cdf07bde6e3e2ec02a6c0644d", size = 611611, upload-time = "2026-10-08T09:11:40.357Z" }
877 wheels = [
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" },
878 + { url = "https://files.pythonhosted.org/packages/2d/3f/5cc58556d8b5c3278d8c36aa07c136d6d0d268746682d2529f1a425d490c/composio_client-2.0.0rc11-py3-none-any.whl", hash = "sha256:7882126151ad9e1f8a81c673afd90a3c34c703bbece76d7ebbc6dc3d441dafc2", size = 445000, upload-time = "2026-10-08T09:11:38.915Z" },
879 ]
880
881 [[package]]