@devries-cameron20 / composio-1 / commits / e7580cf37
Fork 0

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

feat(core): adopt Instant session and account contracts (#4694)

## Summary Adopt the session and account contracts from [platform PR #13432](https://github.com/ComposioHQ/platform/pull/13432) ([PLEN-4181](https://linear.app/composio/issue/PLEN-4181/update-api-contract-to-new-names)). Follow-up to merged #4693. This PR now targets `next` and has been rebased onto its latest commit (`ae3c06914dba8ee39b1f8db4614caa9efbe06f3e`). The merge conflicts are resolved. ## Changes - Rename the session policy to `instant` and map TypeScript `returnInstantCharge` to wire `return_instant_charge` on create and update. Python sends the new block via `extra_body`, since the pinned generated client still exposes the old keyword. - Type returned Session config under `instant.return_instant_charge`; retain existing policy fields and version preconditions. - Rename execution charges to TypeScript `instantCharge`, Python `instant_charge`, and exported Python `InstantCharge`. Preserve provider and mixed local/remote charge forwarding. - Rename Session search account metadata to TypeScript `instantAccount` and Python `instant_account`, with typed Python account coverage. Document explicit `instant_account` execution selectors. - Update the Instant guide for project configuration `enable_instant`, catalog `instant_account_available`, new variables and the settings migration. Those project-settings/catalog endpoints are not high-level SDK methods, so this PR documents their names without inventing new endpoints. - Add focused transport/type regression coverage and a core changeset. Do not modify generated clients or add old-name aliases. ## Type of change - [x] Bug fix - [x] Breaking change - [x] Documentation ## How Has This Been Tested? - TypeScript: 384 focused session, tools, parameter and transformer tests; core typecheck including new public-contract type tests; core build; Oxlint (existing unused-import warnings). - Python: 227 session/custom-tool tests, including generated-client HTTP transport coverage for create/update, version preconditions, attach, selector/charge execution and search coverage. Combined with parent usage/log tests: 237 passed. - Python: mypy passes for all four changed source modules; Ruff check/format; public imports from `composio.types`. - Docs: 608 static tests; typecheck; full production build; link validation; semantic artifact check with `--allow-stale`. - Changeset validation and `git diff --check`. ## Checklist - [x] I have read the Code of Conduct and this PR adheres to it - [x] I have read and understand every line of this diff, including any LLM-generated code - [x] Any third-party docs links or promotional content follow the third-party links policy - [x] I ran linters/tests locally and they passed - [x] I updated documentation as needed - [x] I added tests or explain why not applicable - [x] I added a changeset if this change affects published packages ## Additional context Designated reviewer: @jkomyno. Both generated clients are still at rc8, the newest published release candidate. SDK-owned request/response contracts bridge the new API fields. The Instant guide keeps its existing `@noErrors` snippet annotations because the docs build consumes published `@composio/core@0.21.0`; the new `instant-contract.test-d.ts` validates those examples against the local SDK and rejects the old input names. Existing project opt-ins and Session restrictions must be re-saved under the new Instant names, as required by the backend migration. ## Production client regeneration follow-up The production `/api/v3.1/openapi.json` now contains the Instant contract. Both generated clients have been regenerated from that unmodified production snapshot and validated locally. The cleanup that removes the SDK-owned Instant request/response type bridges, config transformer, Python protocol/wrappers, and Instant `extra_body` workaround is also prepared and tested against the packed regenerated client. Generated client checks: lint, both TypeScript compilers, codegen drift check, 1,218 TypeScript tests, npm build/pack/import checks, Python Ruff/mypy, 2,807 Python tests and all 113 wheel operation checks. Cleanup checks: complete SDK TypeScript workspace typecheck, 397 core tests, 100 CLI tests, core build, Python mypy and 237 focused SDK tests. Publishing is blocked by repository access: `prachi005` has no push permission to `ComposioHQ/composio-client`, and that repository disables forks. The SSH-signed regeneration and cleanup commits are ready locally. This PR retains the rc8 compatibility bridges until new client versions are published; then its dependency pins and cleanup can be updated together. --------- Co-authored-by: jkomyno <alberto@composio.dev>

Prachi Mandil committed Sep 29, 2026 at 20:36 UTC e7580cf378c415105f2f70e5cf63f87daf38a796
20 files changed +650 -241
.changeset/instant-session-contract.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +"@composio/core": minor
3 +---
4 +
5 +Align session creation and updates with `instant.return_instant_charge`, expose `instantCharge` on execution results, and rename search account metadata to `instantAccount`. Use `instant_account` for explicit account selection.
docs/content/docs/instant-tools.mdx
+47 -34
@@ -1,25 +1,29 @@
1 ---
2 title: Instant Tools
3 description: Use supported tools in a Session without asking every user to connect a provider account
4 -keywords: [Instant Tools, Sessions, premium usage, hosted account]
4 +keywords: [Instant Tools, Sessions, Instant usage, Instant account]
5 experimental: true
6 ---
7
8 -Instant Tools let your Session run supported tools without an end-user provider connection. A Composio hosted account provides access for eligible tools. Premium usage charges for those calls come from your organization's available balance.
8 +Instant Tools let your Session run supported tools without an end-user provider connection. A Composio Instant account provides access for eligible tools. Instant usage charges for those calls come from your organization's available balance.
9
10 <Callout type="warning" title="Experimental access">
11 This feature requires a project setting that is not yet self-service. Email [support@composio.dev](mailto:support@composio.dev) to enable it for your project and confirm which tools and rates are available. Session configuration cannot override a project where the setting is off.
12 </Callout>
13
14 -Once the project setting is enabled, new Sessions can use eligible Instant Tools by default, even if `premium_usage` is omitted. Set `premium_usage=False` in Python or `premiumUsage: false` in TypeScript when creating a Session that must not incur premium usage charges.
14 +Once the project setting is enabled, new Sessions can use eligible Instant Tools by default, even if `instant` is omitted. Set `instant=False` in Python or `instant: false` in TypeScript when creating a Session that must not incur Instant usage charges.
15 +
16 +Project configuration uses `enable_instant` in API requests and responses. The SDK has no project-settings setter; configure the project before creating a Session. Existing project and Session settings saved under the previous premium names must be saved again under the Instant names. The previous names are not aliases.
17
18 ## Find eligible tools
19
20 Instant tool coverage is per tool, not per toolkit. The current [toolkit listing API](/reference/api-reference/toolkits/getToolkits) does not return instant tool availability or offer an instant tool filter. Its `no_auth` and `composio_managed_auth_schemes` fields mean different things and should not be used as substitutes. During Experimental access, ask [support@composio.dev](mailto:support@composio.dev) for the supported tools and rates before allowing them in a production Session.
21
22 +Catalogs that expose Instant account coverage use `instant_account_available`. This field describes coverage; project permission and Session restrictions still apply at execution time.
23 +
24 ## Create a Session
25
22 -After your project is enabled, create a Session. This example makes Exa available and permits premium usage for its eligible tools:
26 +After your project is enabled, create a Session. This example makes Exa available and permits Instant usage for its eligible tools:
27
28 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
29 <Tab value="Python">
@@ -30,9 +34,9 @@ composio = Composio()
34 session = composio.sessions.create(
35 user_id="user_123",
36 toolkits=["exa"],
33 - premium_usage={
37 + instant={
38 "toolkits": {"enable": ["exa"]},
35 - "return_premium_charge": True,
39 + "return_instant_charge": True,
40 },
41 )
42 ```
@@ -45,20 +49,20 @@ import { Composio } from "@composio/core";
49 const composio = new Composio();
50 const session = await composio.create("user_123", {
51 toolkits: ["exa"],
48 - premiumUsage: {
52 + instant: {
53 toolkits: { enable: ["exa"] },
50 - returnPremiumCharge: true,
54 + returnInstantCharge: true,
55 },
56 });
57 ```
58 </Tab>
59 </Tabs>
60
57 -Top-level `toolkits` controls which tools the Session can discover and run. Omit it to make all toolkits discoverable. `premium_usage.toolkits` (or `premiumUsage.toolkits` in TypeScript) separately restricts which eligible tools can incur premium usage charges. Omitting `premium_usage.toolkits` does not restrict premium usage: eligible tools remain available when the project and Session permit them. `return_premium_charge` defaults to `false` and only controls whether the actual charge appears in the immediate tool response. An Instant toolkit can still contain tools that need a connected account; hosted account coverage is tool-specific.
61 +Top-level `toolkits` controls which tools the Session can discover and run. Omit it to make all toolkits discoverable. `instant.toolkits` separately restricts which eligible tools can incur Instant usage charges. Omitting `instant.toolkits` does not restrict Instant usage: eligible tools remain available when the project and Session permit them. `return_instant_charge` defaults to `false` and only controls whether the actual charge appears in the immediate tool response. An Instant toolkit can still contain tools that need a connected account; Instant account coverage is tool-specific.
62
63 ## Find and run a tool
64
61 -Pass `session.tools()` to your agent as in the [Quickstart](/docs/quickstart), so it can discover and run eligible tools. If your agent uses MCP, expose the same Session through `session.mcp` as described in [Using sessions via MCP](/docs/sessions-via-mcp). The premium usage policy applies to that Session in either path; your agent does not need a separate premium usage setting.
65 +Pass `session.tools()` to your agent as in the [Quickstart](/docs/quickstart), so it can discover and run eligible tools. If your agent uses MCP, expose the same Session through `session.mcp` as described in [Using sessions via MCP](/docs/sessions-via-mcp). The Instant usage policy applies to that Session in either path; your agent does not need a separate Instant usage setting.
66
67 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
68 <Tab value="Python">
@@ -96,37 +100,37 @@ const result = await session.execute("EXA_SEARCH", { query: "Composio documentat
100 </Tab>
101 </Tabs>
102
99 -Check the current [tool input schema](/reference/api-reference/tools/getToolsByToolSlug) before constructing arguments. A tool appearing in a toolkit does not mean hosted account access is available for that tool. Confirm supported tools and rates during Experimental access.
103 +Check the current [tool input schema](/reference/api-reference/tools/getToolsByToolSlug) before constructing arguments. A tool appearing in a toolkit does not mean Instant account access is available for that tool. Confirm supported tools and rates during Experimental access.
104
105 ### Read charge details in Python
106
103 -With `premium_usage.return_premium_charge` enabled, `session.execute()` returns charge details when available in the typed `premium_charge` field on `ToolRouterSessionExecuteResponse`. Read it from the result above:
107 +With `instant.return_instant_charge` enabled, `session.execute()` returns charge details when available in the typed `instant_charge` field on `ToolRouterSessionExecuteResponse`. Read it from the result above:
108
109 ```python
106 -charge = result.premium_charge
110 +charge = result.instant_charge
111 if charge is not None:
112 print(charge["amount"], charge["currency"], charge["charged_by"])
113 ```
114
111 -The `PremiumCharge` type is exported from `composio.types` and includes `amount`, `currency`, and `charged_by`. Python provider integrations and mixed local/remote multi-tool execution also preserve these charge details.
115 +The `InstantCharge` type is exported from `composio.types` and includes `amount`, `currency`, and `charged_by`. Python provider integrations and mixed local/remote multi-tool execution also preserve these charge details.
116
113 -## Control premium usage
117 +## Control Instant usage
118
115 -`premium_usage` is a Session policy (`premiumUsage` in TypeScript). It does not enable a toolkit that top-level `toolkits` excludes, and it does not change a connected account you explicitly selected.
119 +`instant` is a Session policy in both SDKs. It does not enable a toolkit that top-level `toolkits` excludes, and it does not change a connected account you explicitly selected.
120
117 -The toolkit filter and per-tool filter intersect. A `tools.exa` rule alone does not disable premium usage for other eligible toolkits. Use `premium_usage.toolkits` when you need a toolkit allowlist. Each filter accepts either `enable` or `disable`, not both.
121 +The toolkit filter and per-tool filter intersect. A `tools.exa` rule alone does not disable Instant usage for other eligible toolkits. Use `instant.toolkits` when you need a toolkit allowlist. Each filter accepts either `enable` or `disable`, not both.
122
119 -The examples below use Python and REST field names. In TypeScript, use `premiumUsage` and `returnPremiumCharge`, and read the charge from `premiumCharge` on the tool result.
123 +The examples below use Python and REST field names. In TypeScript, use `instant` and `returnInstantCharge`, and read the charge from `instantCharge` on the tool result.
124
125 | Session value | Effect |
126 |---|---|
123 -| Omitted or `{}` | Permits premium usage for eligible tools, subject to the project setting and normal Session filters. The charge is not returned in tool responses by default. |
124 -| `false` | Disables premium usage for that Session. Your own connected-account routes remain available. |
125 -| `{ "toolkits": { "enable": ["exa"] } }` | Permits premium usage only for listed toolkits. Use `disable` instead to exclude selected toolkits. |
126 -| `{ "tools": { "exa": { "enable": ["EXA_SEARCH"] } } }` | Narrows premium usage to selected tools within a toolkit. |
127 -| `{ "return_premium_charge": true }` | Requests the actual `premium_charge` in an eligible Session tool response. On create, this changes charge visibility, not permission to spend. On update, it also re-enables premium usage on a Session set to `false`, like any other object. |
127 +| Omitted or `{}` | Permits Instant usage for eligible tools, subject to the project setting and normal Session filters. The charge is not returned in tool responses by default. |
128 +| `false` | Disables Instant usage for that Session. Your own connected-account routes remain available. |
129 +| `{ "toolkits": { "enable": ["exa"] } }` | Permits Instant usage only for listed toolkits. Use `disable` instead to exclude selected toolkits. |
130 +| `{ "tools": { "exa": { "enable": ["EXA_SEARCH"] } } }` | Narrows Instant usage to selected tools within a toolkit. |
131 +| `{ "return_instant_charge": true }` | Requests the actual `instant_charge` in an eligible Session tool response. On create, this changes charge visibility, not permission to spend. On update, it also re-enables Instant usage on a Session set to `false`, like any other object. |
132
129 -For example, keep Exa and Firecrawl available, but permit premium usage only for `EXA_SEARCH`:
133 +For example, keep Exa and Firecrawl available, but permit Instant usage only for `EXA_SEARCH`:
134
135 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
136 <Tab value="Python">
@@ -134,7 +138,7 @@ For example, keep Exa and Firecrawl available, but permit premium usage only for
138 session = composio.sessions.create(
139 user_id="user_123",
140 toolkits=["exa", "firecrawl"],
137 - premium_usage={
141 + instant={
142 "toolkits": {"enable": ["exa"]},
143 "tools": {"exa": {"enable": ["EXA_SEARCH"]}},
144 },
@@ -144,9 +148,12 @@ session = composio.sessions.create(
148 <Tab value="TypeScript">
149 ```typescript
150 // @noErrors
151 +import { Composio } from "@composio/core";
152 +const composio = new Composio();
153 +// ---cut---
154 const session = await composio.create("user_123", {
155 toolkits: ["exa", "firecrawl"],
149 - premiumUsage: {
156 + instant: {
157 toolkits: { enable: ["exa"] },
158 tools: { exa: { enable: ["EXA_SEARCH"] } },
159 },
@@ -155,32 +162,38 @@ const session = await composio.create("user_123", {
162 </Tab>
163 </Tabs>
164
158 -To stop premium usage on an existing Session, update its policy:
165 +To stop Instant usage on an existing Session, update its policy:
166
167 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
168 <Tab value="Python">
169 ```python
163 -session.update(premium_usage=False)
170 +session.update(instant=False)
171 ```
172 </Tab>
173 <Tab value="TypeScript">
174 ```typescript
175 // @noErrors
169 -await session.update({ premiumUsage: false });
176 +import { Composio } from "@composio/core";
177 +const composio = new Composio();
178 +const session = await composio.create("user_123");
179 +// ---cut---
180 +await session.update({ instant: false });
181 ```
182 </Tab>
183 </Tabs>
184
174 -On patch, omitted `premium_usage` fields keep their existing values. Supplying any object after `false`, even one that only sets `return_premium_charge`, enables this Session policy again, provided the project allows it.
185 +On patch, omitted `instant` fields keep their existing values. Supplying any object after `false`, even one that only sets `return_instant_charge`, enables this Session policy again, provided the project allows it.
186
187 ## Know which account runs the tool
188
178 -A hosted account is a provider account held by Composio for specific tools. It is different from **Composio-managed auth**, where Composio supplies OAuth application credentials but your user still connects their own account. Composio-managed auth alone does not make a tool Instant.
189 +An Instant account is a provider account held by Composio for specific tools. It is different from **Composio-managed auth**, where Composio supplies OAuth application credentials but your user still connects their own account. Composio-managed auth alone does not make a tool Instant.
190 +
191 +If you select a connected account explicitly, that route wins and does not fall back to the Instant account on failure. Otherwise, available user or shared connections take priority over an Instant account. If the chosen tool is not supported by an Instant account, it follows the normal connection flow.
192
180 -If you select a connected account explicitly, that route wins and does not fall back to the hosted account on failure. Otherwise, available user or shared connections take priority over a hosted account. If the chosen tool is not supported by a hosted account, it follows the normal connection flow.
193 +Session search tells you when an Instant account serves a toolkit. The toolkit's connection status includes `instant_account.allowed_tool_slugs` (`instantAccount.allowedToolSlugs` in TypeScript), which lists the tools that run on it. Any other tool in that toolkit needs the user's own connection.
194
182 -Session search tells you when a hosted account serves a toolkit. The toolkit's connection status includes `hosted_account.allowed_tool_slugs` (`hostedAccount.allowedToolSlugs` in TypeScript), which lists the tools that run on it. Any other tool in that toolkit needs the user's own connection.
195 +To explicitly select the Composio Instant account, pass `account="instant_account"` to Python `session.execute()` or `{ account: 'instant_account' }` as the TypeScript execution options. For direct `composio.tools.execute()`, pass `connected_account_id="instant_account"` in Python or `connectedAccountId: 'instant_account'` in TypeScript. This selection does not fall back to another credential if the call fails.
196
184 -Hosted accounts cannot run arbitrary provider requests through proxy execution. Use supported tool actions. Direct execution outside a Session does not inherit its `premium_usage` policy.
197 +Instant accounts cannot run arbitrary provider requests through proxy execution. Use supported tool actions. Direct execution outside a Session does not inherit its `instant` policy.
198
199 See [Configuring Sessions](/docs/configuring-sessions) for general toolkit and tool filters and the [create Session API reference](/reference/api-reference/tool-router/postToolRouterSession) for the complete request schema.
python/composio/core/models/tool_router.py
+13 -17
@@ -49,8 +49,9 @@ from composio.core.models.tool_router_constants import (
49 SESSION_PRESET_DIRECT_TOOLS,
50 )
51 from composio.core.models.tool_router_session import (
52 - ToolRouterPremiumUsageConfig,
52 + ToolRouterInstantConfig,
53 ToolRouterSession,
54 + ToolRouterSessionConfig,
55 ToolRouterSessionPreloadConfig,
56 ToolRouterSessionWithMcp,
57 ToolRouterUpdateExperimentalConfig,
@@ -727,9 +728,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
728 preload: t.Optional[ToolRouterPreloadConfig] = None,
729 session_preset: t.Optional[SessionPreset] = None,
730 experimental: t.Optional[ToolRouterExperimentalConfig] = None,
730 - premium_usage: t.Optional[
731 - t.Union[t.Literal[False], ToolRouterPremiumUsageConfig]
732 - ] = None,
731 + instant: t.Optional[t.Union[t.Literal[False], ToolRouterInstantConfig]] = None,
732 mcp: t.Literal[True],
733 ) -> ToolRouterSessionWithMcp[TTool, TToolCollection]: ...
734
@@ -758,9 +757,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
757 preload: t.Optional[ToolRouterPreloadConfig] = None,
758 session_preset: t.Optional[SessionPreset] = None,
759 experimental: t.Optional[ToolRouterExperimentalConfig] = None,
761 - premium_usage: t.Optional[
762 - t.Union[t.Literal[False], ToolRouterPremiumUsageConfig]
763 - ] = None,
760 + instant: t.Optional[t.Union[t.Literal[False], ToolRouterInstantConfig]] = None,
761 mcp: t.Literal[False] = False,
762 ) -> ToolRouterSession[TTool, TToolCollection]: ...
763
@@ -788,9 +785,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
785 preload: t.Optional[ToolRouterPreloadConfig] = None,
786 session_preset: t.Optional[SessionPreset] = None,
787 experimental: t.Optional[ToolRouterExperimentalConfig] = None,
791 - premium_usage: t.Optional[
792 - t.Union[t.Literal[False], ToolRouterPremiumUsageConfig]
793 - ] = None,
788 + instant: t.Optional[t.Union[t.Literal[False], ToolRouterInstantConfig]] = None,
789 mcp: bool = False,
790 ) -> ToolRouterSession[TTool, TToolCollection]:
791 """
@@ -898,9 +893,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
893 it directly from session.tools(); otherwise custom tools
894 remain search-only.
895 Example: {'assistive_prompt': {'user_timezone': 'America/New_York'}}
901 - :param premium_usage: Experimental premium usage policy. The project
902 - must allow premium usage. ``False`` disables it for this
903 - Session; a policy can restrict eligible toolkits and tools.
896 + :param instant: Experimental Instant usage policy. The project
897 + must allow Instant usage. ``False`` disables it for this
898 + Session; a policy can restrict eligible toolkits and tools.
899 :param mcp: When True, the returned session surfaces its hosted MCP
900 endpoint (``session.mcp.url`` / ``session.mcp.headers``) in
901 the type (returns ToolRouterSessionWithMcp). The endpoint
@@ -1094,8 +1089,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1089 create_params: t.Dict[str, t.Any] = {
1090 "user_id": user_id,
1091 }
1097 - if premium_usage is not None:
1098 - create_params["premium_usage"] = premium_usage
1092 + if instant is not None:
1093 + # The pinned generated client has no `instant` keyword yet.
1094 + create_params["extra_body"] = {"instant": instant}
1095
1096 # Build connections config
1097 connections_config: t.Dict[str, t.Any] = {
@@ -1247,7 +1243,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1243 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
1244 file_upload_dirs=self._file_upload_dirs,
1245 session_id=session.session_id,
1250 - config=session.config,
1246 + config=t.cast(ToolRouterSessionConfig, session.config),
1247 config_version=session.config_version,
1248 mcp=self._create_mcp_server_config(
1249 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
@@ -1407,7 +1403,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1403 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
1404 file_upload_dirs=self._file_upload_dirs,
1405 session_id=session.session_id,
1410 - config=session.config,
1406 + config=t.cast(ToolRouterSessionConfig, session.config),
1407 config_version=session.config_version,
1408 mcp=self._create_mcp_server_config(
1409 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
python/composio/core/models/tool_router_session.py
+144 -59
@@ -21,19 +21,15 @@ from composio_client.types.tool_list_response import (
21 ItemToolkit,
22 )
23 from composio_client.types.tool_router import (
24 - session_attach_response,
24 session_create_response,
25 session_link_params,
26 session_patch_params,
28 - session_patch_response,
29 - session_retrieve_response,
27 + session_search_response,
28 )
29 from composio_client.types.tool_router.session_execute_response import (
30 SessionExecuteResponse,
31 )
34 -from composio_client.types.tool_router.session_search_response import (
35 - SessionSearchResponse,
36 -)
32 +from pydantic import BaseModel
33
34 from composio import exceptions
35 from composio.client import HttpClient
@@ -75,7 +71,7 @@ from composio.core.models.tool_router_session_delete import (
71 delete_tool_router_session,
72 )
73 from composio.core.models.tools import (
78 - PremiumCharge,
74 + InstantCharge,
75 ToolExecuteParams,
76 ToolExecutionResponse,
77 )
@@ -103,42 +99,123 @@ class ToolRouterSessionPreloadConfig:
99 tools: t.Union[t.List[str], t.Literal["all"]]
100
101
106 -#: Server-side session configuration as returned by the API: toolkit and tool
107 -#: allowlists, tags, auth configs, connected accounts, ``manage_connections``,
108 -#: preload, sandbox (``workbench``), search and execute settings. The four
109 -#: generated response models carry the same fields.
110 -ToolRouterSessionConfig = t.Union[
111 - session_create_response.Config,
112 - session_retrieve_response.Config,
113 - session_attach_response.Config,
114 - session_patch_response.Config,
115 -]
102 +class ToolRouterInstantResponseEnable(te.TypedDict):
103 + enabled: t.List[str]
104 +
105 +
106 +class ToolRouterInstantResponseDisable(te.TypedDict):
107 + disabled: t.List[str]
108 +
109 +
110 +class ToolRouterInstantResponse(te.TypedDict):
111 + """Stored Instant policy returned in Session config, using API field casing."""
112 +
113 + toolkits: te.NotRequired[
114 + t.Union[ToolRouterInstantResponseEnable, ToolRouterInstantResponseDisable]
115 + ]
116 + tools: te.NotRequired[
117 + t.Dict[
118 + str,
119 + t.Union[ToolRouterInstantResponseEnable, ToolRouterInstantResponseDisable],
120 + ]
121 + ]
122 + return_instant_charge: bool
123 +
124 +
125 +class ToolRouterSessionConfig(t.Protocol):
126 + """Server-side Session config. New Instant fields are retained by the client
127 + as Pydantic extras until its generated response types adopt this contract.
128 + """
129 +
130 + user_id: str
131 + instant: t.Union[t.Literal[False], ToolRouterInstantResponse]
132 + auth_configs: t.Optional[t.Dict[str, str]]
133 + connected_accounts: t.Optional[t.Dict[str, t.List[str]]]
134 + execute: session_create_response.ConfigExecute
135 + manage_connections: t.Optional[session_create_response.ConfigManageConnections]
136 + multi_account: t.Optional[session_create_response.ConfigMultiAccount]
137 + preload: session_create_response.ConfigPreload
138 + search: session_create_response.ConfigSearch
139 + tags: t.Optional[session_create_response.ConfigTags]
140 + toolkits: t.Union[
141 + session_create_response.ConfigToolkitsEnabled,
142 + session_create_response.ConfigToolkitsDisabled,
143 + None,
144 + ]
145 + tools: t.Optional[
146 + t.Dict[
147 + str,
148 + t.Union[
149 + session_create_response.ConfigToolsEnabled,
150 + session_create_response.ConfigToolsDisabled,
151 + session_create_response.ConfigToolsTags,
152 + ],
153 + ]
154 + ]
155 + workbench: t.Optional[session_create_response.ConfigWorkbench]
156 +
157 + def model_dump(self, **kwargs: t.Any) -> t.Dict[str, t.Any]: ...
158 +
159 + def model_dump_json(self, **kwargs: t.Any) -> str: ...
160 +
161 + def model_copy(self, **kwargs: t.Any) -> ToolRouterSessionConfig: ...
162
163
118 -class ToolRouterPremiumUsageEnable(te.TypedDict):
164 +class ToolRouterInstantEnable(te.TypedDict):
165 enable: t.List[str]
166
167
122 -class ToolRouterPremiumUsageDisable(te.TypedDict):
168 +class ToolRouterInstantDisable(te.TypedDict):
169 disable: t.List[str]
170
171
126 -class ToolRouterPremiumUsageConfig(te.TypedDict, total=False):
127 - """Experimental premium usage policy for a Session."""
172 +class ToolRouterInstantConfig(te.TypedDict, total=False):
173 + """Experimental Instant usage policy for a Session."""
174
129 - toolkits: t.Union[ToolRouterPremiumUsageEnable, ToolRouterPremiumUsageDisable]
130 - tools: t.Dict[
131 - str, t.Union[ToolRouterPremiumUsageEnable, ToolRouterPremiumUsageDisable]
132 - ]
133 - return_premium_charge: bool
175 + toolkits: t.Union[ToolRouterInstantEnable, ToolRouterInstantDisable]
176 + tools: t.Dict[str, t.Union[ToolRouterInstantEnable, ToolRouterInstantDisable]]
177 + return_instant_charge: bool
178
179
180 class ToolRouterSessionExecuteResponse(SessionExecuteResponse):
181 """Result of :meth:`ToolRouterSession.execute`."""
182
139 - premium_charge: t.Optional[PremiumCharge] = None
183 + instant_charge: t.Optional[InstantCharge] = None
184 """Present only when the Session sets
141 - ``premium_usage.return_premium_charge`` and a charge is available."""
185 + ``instant.return_instant_charge`` and a charge is available."""
186 +
187 +
188 +class ToolRouterInstantAccount(BaseModel):
189 + """Tools served by the Composio Instant account for a toolkit."""
190 +
191 + allowed_tool_slugs: t.List[str]
192 +
193 +
194 +class ToolRouterToolkitConnectionStatus(
195 + session_search_response.ToolkitConnectionStatus
196 +):
197 + instant_account: t.Optional[ToolRouterInstantAccount] = None
198 +
199 +
200 +class ToolRouterSessionSearchResponse(session_search_response.SessionSearchResponse):
201 + """Session search result, including typed Instant account coverage."""
202 +
203 + # Narrows the generated list item type; `list` is invariant for mypy.
204 + toolkit_connection_statuses: t.List[ToolRouterToolkitConnectionStatus] # type: ignore[assignment]
205 +
206 +
207 +def _with_instant_account(status: t.Any) -> t.Any:
208 + if not isinstance(status, BaseModel):
209 + return status
210 + fields = dict(status)
211 + account = fields.get("instant_account")
212 + if isinstance(account, dict):
213 + fields["instant_account"] = ToolRouterInstantAccount.model_construct(
214 + _fields_set=set(account), **account
215 + )
216 + return ToolRouterToolkitConnectionStatus.model_construct(
217 + _fields_set=status.model_fields_set, **fields
218 + )
219
220
221 class ToolRouterUpdateManageConnectionsConfig(te.TypedDict, total=False):
@@ -247,12 +324,15 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
324 self.preload = preload or ToolRouterSessionPreloadConfig(tools=[])
325 # Sessions built from an API response always carry their config; the
326 # fallback only covers direct construction without one (tests).
250 - self.config = config or session_create_response.Config(
251 - user_id=user_id or "",
252 - execute=session_create_response.ConfigExecute(),
253 - search=session_create_response.ConfigSearch(),
254 - preload=session_create_response.ConfigPreload(tools=self.preload.tools),
255 - premium_usage=False,
327 + self.config = config or t.cast(
328 + ToolRouterSessionConfig,
329 + session_create_response.Config.model_construct(
330 + user_id=user_id or "",
331 + execute=session_create_response.ConfigExecute(),
332 + search=session_create_response.ConfigSearch(),
333 + preload=session_create_response.ConfigPreload(tools=self.preload.tools),
334 + instant=False,
335 + ),
336 )
337 # The MCP endpoint exists on every session at runtime (kept for
338 # backwards compatibility), but is only typed via
@@ -707,8 +787,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
787 "error": error_message,
788 "successful": not has_any_error,
789 }
710 - if remote_result and remote_result.get("premium_charge") is not None:
711 - merged["premium_charge"] = remote_result["premium_charge"]
790 + if remote_result and remote_result.get("instant_charge") is not None:
791 + merged["instant_charge"] = remote_result["instant_charge"]
792 return merged
793
794 def authorize(
@@ -843,13 +923,13 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
923 *,
924 query: str,
925 model: t.Optional[str] = None,
846 - ) -> SessionSearchResponse:
926 + ) -> ToolRouterSessionSearchResponse:
927 """
928 Search for tools by semantic use case.
929
930 Returns relevant tools for the given query with schemas and guidance.
931 """
852 - return self._client.tool_router.session.search(
932 + response = self._client.tool_router.session.search(
933 session_id=self.session_id,
934 queries=[{"use_case": query}],
935 model=model if model else omit,
@@ -857,6 +937,18 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
937 self._inline_custom_tools_payload
938 ),
939 )
940 + # The client already built the response without enforcing its schema.
941 + # Construct without revalidating so an unexpected field can't fail a
942 + # search; only the Instant account coverage gains a typed model.
943 + fields = dict(response)
944 + statuses = fields.get("toolkit_connection_statuses")
945 + if isinstance(statuses, list):
946 + fields["toolkit_connection_statuses"] = [
947 + _with_instant_account(status) for status in statuses
948 + ]
949 + return ToolRouterSessionSearchResponse.model_construct(
950 + _fields_set=response.model_fields_set, **fields
951 + )
952
953 def execute(
954 self,
@@ -878,7 +970,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
970 top-level field or define their own account-selection fields.
971
972 Both paths return a ``ToolRouterSessionExecuteResponse`` with ``data``,
881 - ``error``, ``log_id``, and ``premium_charge`` attributes.
973 + ``error``, ``log_id``, and ``instant_charge`` attributes.
974 """
975 # Check if this is a local tool (by original or final slug)
976 entry = find_custom_tool(self._custom_tools_map, tool_slug)
@@ -902,7 +994,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
994 ),
995 )
996 # The client already validated data/error/log_id and kept the
905 - # undeclared premium_charge as an extra. Construct without
997 + # undeclared instant_charge as an extra. Construct without
998 # revalidating so a malformed charge can't fail an executed call.
999 return ToolRouterSessionExecuteResponse.model_construct(**dict(response))
1000
@@ -1015,9 +1107,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1107 self,
1108 *,
1109 toolkits: t.Union[t.Optional[session_patch_params.Toolkits], "Omit"] = omit,
1018 - premium_usage: t.Union[
1019 - t.Literal[False], ToolRouterPremiumUsageConfig, "Omit"
1020 - ] = omit,
1110 + instant: t.Union[t.Literal[False], ToolRouterInstantConfig, "Omit"] = omit,
1111 tools: t.Union[
1112 t.Optional[t.Dict[str, session_patch_params.Tools]], "Omit"
1113 ] = omit,
@@ -1057,10 +1147,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1147 as-is). Supplied ``tools``, ``auth_configs`` and ``connected_accounts``
1148 maps replace the stored map entirely. Inside ``manage_connections``,
1149 ``callback_url=None`` removes only the stored callback URL.
1060 - Experimental ``premium_usage`` accepts ``False`` to disable billed
1150 + Experimental ``instant`` accepts ``False`` to disable billed
1151 access or an object to set its filters; it does not accept ``None``.
1062 - Any object, even one that only sets ``return_premium_charge``,
1063 - re-enables premium usage on a Session set to ``False``.
1152 + Any object, even one that only sets ``return_instant_charge``,
1153 + re-enables Instant usage on a Session set to ``False``.
1154
1155 By default the request carries no precondition: the last writer wins.
1156 Pass ``expected_config_version`` (for example this object's
@@ -1092,10 +1182,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1182 "Pass either `sandbox` or `workbench`, not both. "
1183 "`workbench` is a backwards-compatible alias for `sandbox`."
1184 )
1095 - if premium_usage is None:
1185 + if instant is None:
1186 raise exceptions.InvalidParams(
1097 - "`premium_usage` does not accept None; pass False to disable "
1098 - "premium usage, or omit it to keep the stored policy"
1187 + "`instant` does not accept None; pass False to disable "
1188 + "Instant usage, or omit it to keep the stored policy"
1189 )
1190
1191 precondition: t.Union[int, "Omit"]
@@ -1113,11 +1203,14 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1203
1204 # The generated client has no typed parameter for the precondition, so
1205 # it travels as an extra root body field.
1116 - extra_body = (
1206 + extra_body: t.Optional[t.Dict[str, t.Any]] = (
1207 None
1208 if isinstance(precondition, Omit)
1209 else {"expected_config_version": precondition}
1210 )
1211 + if not isinstance(instant, Omit):
1212 + # Send the new wire contract without passing the old generated keyword.
1213 + extra_body = {**(extra_body or {}), "instant": instant}
1214
1215 # The generated client does not type ``None`` for every policy block
1216 # although the API accepts it (it removes the stored override), nor the
@@ -1151,14 +1244,6 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1244 t.Union[t.Optional[session_patch_params.Experimental], "Omit"],
1245 experimental,
1246 ),
1154 - premium_usage=t.cast(
1155 - t.Union[
1156 - t.Literal[False],
1157 - session_patch_params.CurrentPremiumUsageVariant1,
1158 - "Omit",
1159 - ],
1160 - premium_usage,
1161 - ),
1247 extra_body=extra_body,
1248 # A stale precondition is a deterministic 409: never retry it.
1249 request_options={"max_retries": 0},
@@ -1181,7 +1266,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1266 None if isinstance(precondition, Omit) else precondition
1267 ),
1268 ) from exc
1184 - self.config = response.config
1269 + self.config = t.cast(ToolRouterSessionConfig, response.config)
1270 self.config_version = response.config_version
1271 self.preload = _session_preload_config(response.config.preload)
1272 return self.config
python/composio/core/models/tools.py
+10 -9
@@ -114,8 +114,8 @@ def _serialize_arguments(arguments: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
114 return {k: _serialize_value(v) for k, v in arguments.items()}
115
116
117 -class PremiumCharge(te.TypedDict):
118 - """Premium usage charge reported for a Session tool execution."""
117 +class InstantCharge(te.TypedDict):
118 + """Instant usage charge reported for a Session tool execution."""
119
120 amount: str
121 """Exact non-negative USD decimal string, e.g. ``"0.01"``."""
@@ -127,9 +127,9 @@ class ToolExecutionResponse(te.TypedDict):
127 data: t.Dict
128 error: t.Optional[str]
129 successful: bool
130 - premium_charge: te.NotRequired[PremiumCharge]
130 + instant_charge: te.NotRequired[InstantCharge]
131 """Present only when the Session sets
132 - ``premium_usage.return_premium_charge`` and a charge is available."""
132 + ``instant.return_instant_charge`` and a charge is available."""
133
134
135 class Tools(Resource, t.Generic[TTool, TToolCollection]):
@@ -583,9 +583,9 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
583 "error": response.error if hasattr(response, "error") else None,
584 "successful": not (hasattr(response, "error") and response.error),
585 }
586 - premium_charge = getattr(response, "premium_charge", None)
587 - if isinstance(premium_charge, dict):
588 - result["premium_charge"] = t.cast(PremiumCharge, premium_charge)
586 + instant_charge = getattr(response, "instant_charge", None)
587 + if isinstance(instant_charge, dict):
588 + result["instant_charge"] = t.cast(InstantCharge, instant_charge)
589
590 # Apply after_execute modifiers
591 if modifiers is not None:
@@ -678,7 +678,8 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
678
679 :param slug: The slug of the tool to execute.
680 :param arguments: The arguments to pass to the tool.
681 - :param connected_account_id: The ID of the connected account to use for the tool.
681 + :param connected_account_id: The connected account ID, or ``instant_account``
682 + to explicitly use the Composio Instant account.
683 :param custom_auth_params: The custom auth params to use for the tool.
684 :param custom_connection_data: The custom connection data to use for the tool, takes priority over custom_auth_params.
685 :param user_id: The ID of the user to execute the tool for.
@@ -816,7 +817,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
817
818 __all__ = [
819 "Tools",
819 - "PremiumCharge",
820 + "InstantCharge",
821 "ToolExecuteParams",
822 "ToolExecutionResponse",
823 "Modifiers",
python/composio/types.py
+10 -2
@@ -1,9 +1,14 @@
1 from composio.client.types import Tool
2 from composio.core.models.connected_accounts import auth_scheme
3 from composio.core.models.experimental import UsageSummaryResponse
4 +from composio.core.models.tool_router_session import (
5 + ToolRouterInstantConfig,
6 + ToolRouterSessionConfig,
7 + ToolRouterSessionSearchResponse,
8 +)
9 from composio.core.models.tools import (
10 + InstantCharge,
11 Modifiers,
6 - PremiumCharge,
12 ToolExecuteParams,
13 ToolExecutionResponse,
14 )
@@ -21,7 +26,10 @@ __all__ = [
26 "Tool",
27 "TTool",
28 "TToolCollection",
24 - "PremiumCharge",
29 + "InstantCharge",
30 + "ToolRouterInstantConfig",
31 + "ToolRouterSessionConfig",
32 + "ToolRouterSessionSearchResponse",
33 "ToolExecuteParams",
34 "ToolExecutionResponse",
35 "UsageSummaryResponse",
python/tests/test_custom_tools.py
+9 -9
@@ -981,7 +981,7 @@ class TestToolRouterSessionCustomTools:
981 assert result.data == {"sent": True}
982 assert result.log_id == "log_123"
983
984 - def test_execute_remote_exposes_premium_charge(self, mock_session_deps):
984 + def test_execute_remote_exposes_instant_charge(self, mock_session_deps):
985 charge = {"amount": "0.01", "currency": "USD", "charged_by": "composio"}
986 mock_session_deps[
987 "client"
@@ -991,7 +991,7 @@ class TestToolRouterSessionCustomTools:
991 "data": {"sent": True},
992 "error": None,
993 "log_id": "log_123",
994 - "premium_charge": charge,
994 + "instant_charge": charge,
995 }
996 )
997 )
@@ -1001,11 +1001,11 @@ class TestToolRouterSessionCustomTools:
1001
1002 assert isinstance(result, ToolRouterSessionExecuteResponse)
1003 assert isinstance(result, SessionExecuteResponse)
1004 - assert result.premium_charge == charge
1004 + assert result.instant_charge == charge
1005 assert result.data == {"sent": True}
1006 assert result.log_id == "log_123"
1007
1008 - def test_execute_remote_without_premium_charge(self, mock_session_deps):
1008 + def test_execute_remote_without_instant_charge(self, mock_session_deps):
1009 mock_session_deps[
1010 "client"
1011 ].tool_router.session.execute.return_value = SessionExecuteResponse(
@@ -1015,7 +1015,7 @@ class TestToolRouterSessionCustomTools:
1015
1016 result = s.execute("GMAIL_SEND_EMAIL", arguments={"to": "a@b.com"})
1017
1018 - assert result.premium_charge is None
1018 + assert result.instant_charge is None
1019
1020 def test_execute_remote_passes_inline_custom_tools(self, mock_session_deps):
1021 mock_response = SessionExecuteResponse(
@@ -1341,9 +1341,9 @@ class TestMultiExecuteRouting:
1341 assert result["data"]["total_count"] == 2
1342 assert result["data"]["success_count"] == 2
1343 assert result["data"]["error_count"] == 0
1344 - assert "premium_charge" not in result
1344 + assert "instant_charge" not in result
1345
1346 - def test_mixed_preserves_remote_premium_charge(self, grep_tool):
1346 + def test_mixed_preserves_remote_instant_charge(self, grep_tool):
1347 s = self._make_session(grep_tool)
1348 tm = MagicMock()
1349 charge = {"amount": "0.01", "currency": "USD", "charged_by": "composio"}
@@ -1355,7 +1355,7 @@ class TestMultiExecuteRouting:
1355 },
1356 "error": None,
1357 "successful": True,
1358 - "premium_charge": charge,
1358 + "instant_charge": charge,
1359 }
1360 tm._wrap_execute_tool_for_tool_router.return_value = lambda slug, args: remote
1361 result = s._route_multi_execute(
@@ -1368,7 +1368,7 @@ class TestMultiExecuteRouting:
1368 tm,
1369 )
1370
1371 - assert result["premium_charge"] == charge
1371 + assert result["instant_charge"] == charge
1372
1373 def test_failure_propagated(self):
1374 @exp.tool()
python/tests/test_tool_router.py
+168 -26
@@ -1,5 +1,6 @@
1 """Test ToolRouter functionality."""
2
3 +import json
4 import logging
5 import os
6 import typing as t
@@ -8,6 +9,9 @@ from unittest.mock import MagicMock, patch
9 import httpx
10 import pytest
11 from composio_client import ConflictError, omit
12 +from composio_client.types.tool_router.session_search_response import (
13 + SessionSearchResponse,
14 +)
15 from pydantic import BaseModel, Field
16
17 from composio.client import HttpClient
@@ -76,6 +80,9 @@ def mock_client():
80 client.tool_router.session.create.return_value = mock_session_response
81 client.tool_router.session.retrieve.return_value = mock_session_response
82 client.tool_router.session.attach.return_value = mock_session_response
83 + client.tool_router.session.search.return_value = (
84 + SessionSearchResponse.model_validate(_search_json())
85 + )
86
87 # Mock link response
88 mock_link_response = MagicMock()
@@ -172,23 +179,25 @@ class TestToolRouter:
179 # Verify API was called
180 mock_client.tool_router.session.create.assert_called_once()
181
175 - def test_create_with_premium_usage_policy(self, tool_router, mock_client):
176 - policy = {"toolkits": {"enable": ["exa"]}, "return_premium_charge": True}
177 - tool_router.create(user_id="user_123", premium_usage=policy)
182 + def test_create_with_instant_policy(self, tool_router, mock_client):
183 + policy = {"toolkits": {"enable": ["exa"]}, "return_instant_charge": True}
184 + tool_router.create(user_id="user_123", instant=policy)
185 kwargs = mock_client.tool_router.session.create.call_args.kwargs
179 - assert kwargs["premium_usage"] == policy
180 - assert "extra_body" not in kwargs
186 + assert kwargs["extra_body"]["instant"] == policy
187 + assert "premium_usage" not in kwargs
188
189 mock_client.tool_router.session.create.reset_mock()
190 tool_router.create(user_id="user_123")
191 + assert "instant" not in mock_client.tool_router.session.create.call_args.kwargs
192 assert (
185 - "premium_usage"
186 - not in mock_client.tool_router.session.create.call_args.kwargs
193 + "extra_body" not in mock_client.tool_router.session.create.call_args.kwargs
194 )
195
189 - tool_router.create(user_id="user_123", premium_usage=False)
196 + tool_router.create(user_id="user_123", instant=False)
197 assert (
191 - mock_client.tool_router.session.create.call_args.kwargs["premium_usage"]
198 + mock_client.tool_router.session.create.call_args.kwargs["extra_body"][
199 + "instant"
200 + ]
201 is False
202 )
203
@@ -2040,12 +2049,12 @@ class TestToolRouterExecution:
2049 assert result["data"] == {"result": "success"}
2050 assert result["error"] is None
2051 assert result["successful"] is True
2043 - assert "premium_charge" not in result
2052 + assert "instant_charge" not in result
2053
2045 - def test_execute_endpoint_preserves_premium_charge(
2054 + def test_execute_endpoint_preserves_instant_charge(
2055 self, tool_router, mock_client, mock_provider
2056 ):
2048 - """Provider-wrapped session tools keep the reported premium charge."""
2057 + """Provider-wrapped session tools keep the reported Instant charge."""
2058 from composio_client.types.tool_router.session_execute_response import (
2059 SessionExecuteResponse,
2060 )
@@ -2059,7 +2068,7 @@ class TestToolRouterExecution:
2068 "data": {"result": "success"},
2069 "error": None,
2070 "log_id": "log_123",
2062 - "premium_charge": charge,
2071 + "instant_charge": charge,
2072 }
2073 )
2074 )
@@ -2074,7 +2083,7 @@ class TestToolRouterExecution:
2083
2084 result = execute_fn("GMAIL_SEND_EMAIL", {"to": "test@example.com"})
2085
2077 - assert result["premium_charge"] == charge
2086 + assert result["instant_charge"] == charge
2087
2088 def test_execute_endpoint_passes_inline_custom_tools(
2089 self, tool_router, mock_client, mock_provider
@@ -2270,6 +2279,7 @@ def _session_json(mcp_url: str) -> t.Dict[str, t.Any]:
2279 "mcp": {"type": "http", "url": mcp_url},
2280 "config": {
2281 "user_id": "user_123",
2282 + "instant": {"return_instant_charge": True},
2283 "execute": {},
2284 "search": {},
2285 "preload": {"tools": []},
@@ -2279,6 +2289,136 @@ def _session_json(mcp_url: str) -> t.Dict[str, t.Any]:
2289 }
2290
2291
2292 +def _search_json() -> t.Dict[str, t.Any]:
2293 + return {
2294 + "success": True,
2295 + "error": None,
2296 + "results": [],
2297 + "tool_schemas": {},
2298 + "toolkit_connection_statuses": [
2299 + {
2300 + "toolkit": "exa",
2301 + "description": "Search",
2302 + "has_active_connection": True,
2303 + "status_message": "Instant account available",
2304 + "instant_account": {"allowed_tool_slugs": ["EXA_SEARCH"]},
2305 + }
2306 + ],
2307 + "next_steps_guidance": [],
2308 + "session": {"id": "session_123", "generate_id": False, "instructions": ""},
2309 + "time_info": {
2310 + "current_time_utc": "2026-09-29T12:00:00Z",
2311 + "current_time_utc_epoch_seconds": 1790683200,
2312 + "message": "UTC",
2313 + },
2314 + }
2315 +
2316 +
2317 +class TestInstantContractTransport:
2318 + """Exercise new wire fields through the pinned generated client."""
2319 +
2320 + @pytest.mark.parametrize(
2321 + "policy", [False, {}, {"return_instant_charge": True}, None]
2322 + )
2323 + def test_create_and_patch_send_new_policy(self, policy):
2324 + client, requests = _transport_client(
2325 + api_key="ak_test", base_url="https://backend.composio.dev"
2326 + )
2327 + router = ToolRouter(client=client, provider=MagicMock())
2328 + session = router.create(user_id="user_123", instant=policy)
2329 + body = json.loads(requests[0].content)
2330 + assert "premium_usage" not in body
2331 + if policy is None:
2332 + assert "instant" not in body
2333 + else:
2334 + assert body["instant"] == policy
2335 + assert session.config.instant == {"return_instant_charge": True}
2336 + assert "premium_usage" not in session.config.model_dump()
2337 +
2338 + if policy is None:
2339 + session.update(expected_config_version=3)
2340 + else:
2341 + session.update(instant=policy, expected_config_version=3)
2342 + body = json.loads(requests[-1].content)
2343 + assert body["expected_config_version"] == 3
2344 + assert "premium_usage" not in body
2345 + if policy is None:
2346 + assert "instant" not in body
2347 + else:
2348 + assert body["instant"] == policy
2349 + assert session.config.instant == {"return_instant_charge": True}
2350 + assert "premium_usage" not in session.config.model_dump()
2351 +
2352 + attached = router.use(session_id="session_123")
2353 + assert attached.config.instant == {"return_instant_charge": True}
2354 +
2355 + def test_execute_selector_charge_and_search_coverage(self):
2356 + requests: t.List[httpx.Request] = []
2357 + charge = {"amount": "0.012", "currency": "USD", "charged_by": "composio"}
2358 +
2359 + def handler(request):
2360 + requests.append(request)
2361 + if request.url.path.endswith("/execute"):
2362 + return httpx.Response(
2363 + 200,
2364 + json={
2365 + "data": {},
2366 + "error": None,
2367 + "log_id": "log_123",
2368 + "instant_charge": charge,
2369 + },
2370 + )
2371 + if request.url.path.endswith("/search"):
2372 + return httpx.Response(200, json=_search_json())
2373 + return httpx.Response(200, json=_session_json(MCP_SAME_ORIGIN_URL))
2374 +
2375 + client = HttpClient(
2376 + provider="test",
2377 + api_key="ak_test",
2378 + base_url="https://backend.composio.dev",
2379 + http_client=httpx.Client(transport=httpx.MockTransport(handler)),
2380 + )
2381 + session = ToolRouter(client=client, provider=MagicMock()).create(
2382 + user_id="user_123"
2383 + )
2384 + result = session.execute("EXA_SEARCH", arguments={}, account="instant_account")
2385 + assert json.loads(requests[-1].content)["account"] == "instant_account"
2386 + assert result.instant_charge == charge
2387 + assert "premium_charge" not in result.model_dump()
2388 + status = session.search(query="search").toolkit_connection_statuses[0]
2389 + assert status.instant_account is not None
2390 + assert status.instant_account.allowed_tool_slugs == ["EXA_SEARCH"]
2391 + assert "hosted_account" not in status.model_dump()
2392 +
2393 + def test_search_keeps_lenient_generated_response(self):
2394 + payload = _search_json()
2395 + payload["toolkit_connection_statuses"][0]["account_type"] = "INSTANT"
2396 + del payload["time_info"]
2397 +
2398 + def handler(request):
2399 + if request.url.path.endswith("/search"):
2400 + return httpx.Response(200, json=payload)
2401 + return httpx.Response(200, json=_session_json(MCP_SAME_ORIGIN_URL))
2402 +
2403 + client = HttpClient(
2404 + provider="test",
2405 + api_key="ak_test",
2406 + base_url="https://backend.composio.dev",
2407 + http_client=httpx.Client(transport=httpx.MockTransport(handler)),
2408 + )
2409 + session = ToolRouter(client=client, provider=MagicMock()).create(
2410 + user_id="user_123"
2411 + )
2412 + result = session.search(query="search")
2413 +
2414 + assert isinstance(result, SessionSearchResponse)
2415 + status = result.toolkit_connection_statuses[0]
2416 + assert status.account_type == "INSTANT"
2417 + assert status.instant_account is not None
2418 + assert status.instant_account.allowed_tool_slugs == ["EXA_SEARCH"]
2419 + assert result.to_dict() == payload
2420 +
2421 +
2422 def _transport_client(
2423 *,
2424 api_key: t.Optional[str],
@@ -2575,30 +2715,32 @@ class TestSessionUpdateContract:
2715 def test_session_tracks_config_version(self, session):
2716 assert session.config_version == 7
2717
2578 - def test_premium_usage_policy_is_sent(self, session, mock_client):
2718 + def test_instant_policy_is_sent(self, session, mock_client):
2719 session.update(
2580 - premium_usage={
2720 + instant={
2721 "toolkits": {"enable": ["exa"]},
2582 - "return_premium_charge": True,
2722 + "return_instant_charge": True,
2723 }
2724 )
2725 kwargs = mock_client.tool_router.session.patch.call_args.kwargs
2586 - assert kwargs["premium_usage"] == {
2726 + assert kwargs["extra_body"]["instant"] == {
2727 "toolkits": {"enable": ["exa"]},
2588 - "return_premium_charge": True,
2728 + "return_instant_charge": True,
2729 }
2590 - assert kwargs["extra_body"] is None
2730 + assert "premium_usage" not in kwargs
2731
2592 - def test_premium_usage_can_be_disabled(self, session, mock_client):
2593 - session.update(premium_usage=False)
2732 + def test_instant_can_be_disabled(self, session, mock_client):
2733 + session.update(instant=False)
2734 assert (
2595 - mock_client.tool_router.session.patch.call_args.kwargs["premium_usage"]
2735 + mock_client.tool_router.session.patch.call_args.kwargs["extra_body"][
2736 + "instant"
2737 + ]
2738 is False
2739 )
2740
2599 - def test_premium_usage_rejects_none(self, session, mock_client):
2600 - with pytest.raises(InvalidParams, match="premium_usage"):
2601 - session.update(premium_usage=None) # type: ignore[arg-type]
2741 + def test_instant_rejects_none(self, session, mock_client):
2742 + with pytest.raises(InvalidParams, match="instant"):
2743 + session.update(instant=None) # type: ignore[arg-type]
2744 mock_client.tool_router.session.patch.assert_not_called()
2745
2746 def test_update_sends_no_precondition_by_default_without_retries(
ts/packages/core/src/lib/toolRouterParams.ts
+18 -10
@@ -17,7 +17,7 @@ import {
17 ToolRouterUpdateManageConnectionsSchema,
18 ToolRouterUpdateExperimentalConfig,
19 ToolRouterSandboxConfig,
20 - ToolRouterPremiumUsage,
20 + ToolRouterInstant,
21 } from '../types/toolRouter.types';
22 import { ValidationError } from '../errors';
23 import { z } from 'zod';
@@ -195,25 +195,33 @@ export type SessionPatchBody = Omit<
195 SessionPatchParams,
196 'toolkits' | 'tools' | 'tags' | 'auth_configs' | 'preload' | 'search' | 'execute'
197 >,
198 - 'manage_connections' | 'multi_account' | 'experimental'
198 + 'manage_connections' | 'multi_account' | 'experimental' | 'premium_usage'
199 > & {
200 manage_connections?: SessionPatchManageConnectionsBody | null;
201 multi_account?: SessionPatchMultiAccountBody | null;
202 experimental?: SessionPatchExperimentalBody | null;
203 expected_config_version?: number;
204 + instant?: SessionInstantBody;
205 };
206
206 -export type SessionPremiumUsageBody = NonNullable<SessionPatchParams['premium_usage']>;
207 +/** SDK-owned wire contract until the generated client adopts the Instant names. */
208 +export type SessionInstantBody =
209 + | false
210 + | (Omit<Exclude<ToolRouterInstant, false>, 'returnInstantCharge'> & {
211 + return_instant_charge?: boolean;
212 + });
213 +
214 +export type SessionCreateBody = Omit<SessionCreateParams, 'premium_usage'> & {
215 + instant?: SessionInstantBody;
216 +};
217
208 -export const transformToolRouterPremiumUsageParams = (
209 - config: ToolRouterPremiumUsage
210 -): SessionPremiumUsageBody => {
218 +export const transformToolRouterInstantParams = (config: ToolRouterInstant): SessionInstantBody => {
219 if (config === false) return false;
220 return {
221 ...(config.toolkits !== undefined && { toolkits: config.toolkits }),
222 ...(config.tools !== undefined && { tools: config.tools }),
215 - ...(config.returnPremiumCharge !== undefined && {
216 - return_premium_charge: config.returnPremiumCharge,
223 + ...(config.returnInstantCharge !== undefined && {
224 + return_instant_charge: config.returnInstantCharge,
225 }),
226 };
227 };
@@ -354,8 +362,8 @@ export const transformToolRouterUpdateParams = (
362 params.toolkits =
363 config.toolkits === null ? null : transformToolRouterToolkitsParams(config.toolkits);
364 }
357 - if (config.premiumUsage !== undefined) {
358 - params.premium_usage = transformToolRouterPremiumUsageParams(config.premiumUsage);
365 + if (config.instant !== undefined) {
366 + params.instant = transformToolRouterInstantParams(config.instant);
367 }
368 if (config.tools !== undefined) {
369 params.tools = config.tools === null ? null : transformToolRouterToolsParams(config.tools);
ts/packages/core/src/models/ToolRouter.ts
+7 -5
@@ -44,19 +44,21 @@ import type {
44 InlineCustomToolsWirePayload,
45 } from '../types/customTool.types';
46 import {
47 + type SessionCreateBody,
48 transformToolRouterTagsParams,
49 transformToolRouterToolsParams,
50 transformToolRouterManageConnectionsParams,
51 transformToolRouterSandboxParams,
52 transformToolRouterToolkitsParams,
53 transformToolRouterMultiAccountParams,
53 - transformToolRouterPremiumUsageParams,
54 + transformToolRouterInstantParams,
55 resolveToolRouterSandboxConfig,
56 } from '../lib/toolRouterParams';
57 import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
58 import { buildMCPServerConfig } from '../lib/toolRouterMcp';
59 import { parseSessionConfigInput } from '../lib/sessionConfigConflict';
60 import { getSourceSessionConfig } from '../lib/toolRouterSourceSessionConfig';
61 +import { transformSessionConfig } from '../utils/transformers/toolRouterResponseTransform';
62 import { ToolRouterSession } from './ToolRouterSession';
63 import { ComposioRequestOptions } from '../types/requestOptions.types';
64 import { withCancellation } from '../utils/cancellation';
@@ -75,7 +77,7 @@ function getSessionMetadata(
77 session: SessionCreateResponse | SessionRetrieveResponse | SessionAttachResponse
78 ) {
79 const metadata: ToolRouterSessionMetadata = {
78 - config: session.config,
80 + config: transformSessionConfig(session.config),
81 preload: session.config.preload,
82 workbench: session.config.workbench,
83 configVersion: session.config_version,
@@ -267,13 +269,13 @@ export class ToolRouter<
269 ])
270 );
271
270 - const payload: SessionCreateParams = {
272 + const payload: SessionCreateBody = {
273 user_id: userId,
274 auth_configs: routerConfig.authConfigs,
275 connected_accounts: connectedAccountsPayload,
276 toolkits: transformToolRouterToolkitsParams(routerConfig.toolkits),
275 - ...(routerConfig.premiumUsage !== undefined && {
276 - premium_usage: transformToolRouterPremiumUsageParams(routerConfig.premiumUsage),
277 + ...(routerConfig.instant !== undefined && {
278 + instant: transformToolRouterInstantParams(routerConfig.instant),
279 }),
280 tools: transformToolRouterToolsParams(routerConfig.tools),
281 tags: transformToolRouterTagsParams(routerConfig.tags),
ts/packages/core/src/models/ToolRouterSession.ts
+6 -5
@@ -35,6 +35,7 @@ import {
35 import {
36 transformSearchResponse,
37 transformExecuteResponse,
38 + transformSessionConfig,
39 } from '../utils/transformers/toolRouterResponseTransform';
40 import { SessionMetaToolOptions } from '../types/modifiers.types';
41 import { ConnectionRequest } from '../types/connectionRequest.types';
@@ -167,7 +168,7 @@ export class ToolRouterSession<
168 execute: {},
169 search: {},
170 preload: { tools: [] },
170 - premium_usage: false,
171 + instant: false,
172 };
173 if (customToolsMap && !userId) {
174 throw new Error('userId is required when custom tools are bound to a session.');
@@ -855,7 +856,7 @@ export class ToolRouterSession<
856 }
857
858 this.configVersion = response.config_version;
858 - this.config = response.config;
859 + this.config = transformSessionConfig(response.config);
860 this.preload = response.config.preload;
861 this.sandbox = response.config.workbench;
862 this.warnings = response.warnings ?? [];
@@ -912,7 +913,7 @@ export class ToolRouterSession<
913 version: item.version,
914 createdAt: item.created_at,
915 isCurrent: item.is_current,
915 - config: item.config,
916 + config: transformSessionConfig(item.config),
917 })),
918 nextCursor: response.next_cursor ?? null,
919 totalPages: response.total_pages,
@@ -1118,8 +1119,8 @@ export class ToolRouterSession<
1119 : `${failedCount} out of ${allResults.length} tools failed`
1120 : null,
1121 successful: !hasAnyError,
1121 - ...(remoteResult?.premiumCharge !== undefined && {
1122 - premiumCharge: remoteResult.premiumCharge,
1122 + ...(remoteResult?.instantCharge !== undefined && {
1123 + instantCharge: remoteResult.instantCharge,
1124 }),
1125 };
1126 }
ts/packages/core/src/models/Tools.ts
+2 -2
@@ -1258,13 +1258,13 @@ export class Tools<
1258 requestOptions?.signal
1259 );
1260
1261 - const { data, error, logId, premiumCharge } = transformExecuteResponse(response);
1261 + const { data, error, logId, instantCharge } = transformExecuteResponse(response);
1262 let result: ToolExecuteResponse = {
1263 data,
1264 error,
1265 successful: !error,
1266 logId,
1267 - ...(premiumCharge !== undefined && { premiumCharge }),
1267 + ...(instantCharge !== undefined && { instantCharge }),
1268 };
1269
1270 // Apply afterExecute modifier if provided
ts/packages/core/src/types/tool.types.ts
+3 -3
@@ -347,7 +347,7 @@ export type CustomAuthParams = z.infer<typeof CustomAuthParamsSchema>;
347 * Parameters for tool execution.
348 *
349 * @property {boolean} [allowTracing] - Enable tracing for this tool execution
350 - * @property {string} [connectedAccountId] - The connected account ID to use for authenticated tools
350 + * @property {string} [connectedAccountId] - Connected account ID, or `instant_account` to explicitly use the Composio Instant account
351 * @property {CustomAuthParams} [customAuthParams] - Custom authentication parameters
352 * @property {CustomConnectionData} [customConnectionData] - Custom connection data (takes priority over customAuthParams)
353 * @property {Record<string, unknown>} [arguments] - The arguments to pass to the tool
@@ -407,8 +407,8 @@ export const ToolExecuteResponseSchema = z.object({
407 successful: z.boolean(),
408 logId: z.string().optional(),
409 sessionInfo: z.unknown().optional(),
410 - /** Actual premium usage charge when the Session opts into returning it. */
411 - premiumCharge: z.unknown().optional(),
410 + /** Actual Instant usage charge when the Session opts into returning it. */
411 + instantCharge: z.unknown().optional(),
412 });
413 export type ToolExecuteResponse = z.infer<typeof ToolExecuteResponseSchema>;
414
ts/packages/core/src/types/toolRouter.types.ts
+43 -21
@@ -108,8 +108,8 @@ export const ToolRouterToolkitsEnabledConfigSchema = z
108 })
109 .strict();
110
111 -/** Experimental premium usage policy for a Session. */
112 -export const ToolRouterPremiumUsageSchema = z.union([
111 +/** Experimental Instant usage policy for a Session. */
112 +export const ToolRouterInstantSchema = z.union([
113 z.literal(false),
114 z
115 .object({
@@ -126,15 +126,15 @@ export const ToolRouterPremiumUsageSchema = z.union([
126 )
127 .optional(),
128 /**
129 - * Return the actual premium charge in Session tool responses. Controls
130 - * visibility only; on update, any policy object still re-enables premium
129 + * Return the actual Instant charge in Session tool responses. Controls
130 + * visibility only; on update, any policy object still re-enables Instant
131 * usage on a Session set to `false`.
132 */
133 - returnPremiumCharge: z.boolean().optional(),
133 + returnInstantCharge: z.boolean().optional(),
134 })
135 .strict(),
136 ]);
137 -export type ToolRouterPremiumUsage = z.infer<typeof ToolRouterPremiumUsageSchema>;
137 +export type ToolRouterInstant = z.infer<typeof ToolRouterInstantSchema>;
138
139 export const ToolRouterManageConnectionsConfigSchema = z.object({
140 enable: z
@@ -265,8 +265,8 @@ const ToolRouterCreateSessionConfigBaseSchema = z
265 .optional()
266 .describe('The toolkits to use in the tool router session'),
267
268 - premiumUsage: ToolRouterPremiumUsageSchema.optional().describe(
269 - 'Experimental premium usage policy. Omission permits eligible tools when the project allows premium usage; false disables it for this Session.'
268 + instant: ToolRouterInstantSchema.optional().describe(
269 + 'Experimental Instant usage policy. Omission permits eligible tools when the project allows Instant usage; false disables it for this Session.'
270 ),
271
272 authConfigs: z
@@ -426,7 +426,7 @@ export const ToolRouterCreateSessionConfigSchema = z
426 * @param {Array<'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'>} tags - Global tags to filter tools by behavior
427 * @param {Record<string, string>} authConfigs - The auth configs to use in the tool router session
428 * @param {Record<string, string | string[]>} connectedAccounts - The connected accounts to use in the tool router session. A single string is coerced to a single-element array before being sent to the backend.
429 - * @param {ToolRouterPremiumUsage} [premiumUsage] - Experimental premium usage policy. The project must allow premium usage.
429 + * @param {ToolRouterInstant} [instant] - Experimental Instant usage policy. The project must allow Instant usage.
430 * @param {ToolRouterConfigManageConnectionsSchema | boolean} manageConnections - The config for the manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually. If set to an object, you can configure the manage connections settings.
431 * @param {boolean} [manageConnections.enable] - Whether to use tools to manage connections in the tool router session @default true
432 * @param {string} [manageConnections.callbackUrl] - The callback url to use in the tool router session
@@ -608,8 +608,8 @@ const ToolRouterSessionSearchToolkitConnectionStatusSchema = z.object({
608 statusMessage: z.string(),
609 connectionDetails: z.record(z.string(), z.unknown()).optional(),
610 currentUserInfo: z.record(z.string(), z.unknown()).optional(),
611 - /** Present when the toolkit runs on a Composio hosted account; only these tools run on it. */
612 - hostedAccount: z.object({ allowedToolSlugs: z.array(z.string()) }).optional(),
611 + /** Present when the toolkit runs on a Composio Instant account; only these tools run on it. */
612 + instantAccount: z.object({ allowedToolSlugs: z.array(z.string()) }).optional(),
613 });
614
615 export const ToolRouterSessionSearchResponseSchema = z.object({
@@ -630,8 +630,8 @@ export const ToolRouterSessionExecuteResponseSchema = z.object({
630 data: z.record(z.string(), z.unknown()),
631 error: z.string().nullable(),
632 logId: z.string(),
633 - /** Actual premium usage charge when the Session opts into returning it. */
634 - premiumCharge: z.unknown().optional(),
633 + /** Actual Instant usage charge when the Session opts into returning it. */
634 + instantCharge: z.unknown().optional(),
635 });
636 export type ToolRouterSessionExecuteResponse = z.infer<
637 typeof ToolRouterSessionExecuteResponseSchema
@@ -692,7 +692,8 @@ export type ToolRouterSessionExecuteFn = (
692
693 export interface ToolRouterSessionExecuteOptions {
694 /**
695 - * Account identifier for direct app tool execution. Accepted on every project:
695 + * Account identifier for direct app tool execution. Use `instant_account` to
696 + * explicitly select the Composio Instant account. Accepted on every project:
697 * in multi-account sessions it picks the account; on single-account projects it
698 * must match one of the session's active connections for the toolkit.
699 * Meta/helper tools either ignore this top-level field or define
@@ -708,12 +709,28 @@ export type ToolRouterSessionWorkbenchConfig = SessionCreateResponse.Config.Work
709
710 export type ToolRouterSessionWarning = SessionCreateResponse.Warning;
711
712 +const ToolRouterInstantResponseFilterSchema = z.union([
713 + z.object({ enabled: z.array(z.string()) }),
714 + z.object({ disabled: z.array(z.string()) }),
715 +]);
716 +
717 +/** Instant policy in the server's Session config (wire field casing). */
718 +export const ToolRouterInstantResponseSchema = z.object({
719 + toolkits: ToolRouterInstantResponseFilterSchema.optional(),
720 + tools: z.record(z.string(), ToolRouterInstantResponseFilterSchema).optional(),
721 + return_instant_charge: z.boolean(),
722 +});
723 +export type ToolRouterInstantResponse = z.infer<typeof ToolRouterInstantResponseSchema>;
724 +
725 /**
712 - * Server-side session configuration as returned by the API: toolkit and tool
726 + * Server-side session configuration as returned by the API: toolkit/tool
727 * allowlists, tags, auth configs, connected accounts, manage_connections,
714 - * preload, sandbox (`workbench`), search and execute settings.
728 + * preload, sandbox (`workbench`), search, execute and Instant settings.
729 + * The generated client still declares the old policy name.
730 */
716 -export type ToolRouterSessionConfig = SessionCreateResponse.Config;
731 +export type ToolRouterSessionConfig = Omit<SessionCreateResponse.Config, 'premium_usage'> & {
732 + instant?: false | ToolRouterInstantResponse;
733 +};
734
735 export interface ToolRouterSessionMetadata {
736 /** Present on every session built from an API response; the constructor synthesises a minimal config when absent. */
@@ -858,8 +875,8 @@ export type ToolRouterUpdateExperimentalConfig = z.infer<typeof ToolRouterUpdate
875 */
876 export const ToolRouterUpdateSessionConfigSchema = z
877 .object({
861 - premiumUsage: ToolRouterPremiumUsageSchema.optional().describe(
862 - 'Experimental premium usage policy. False disables it. Any supplied object, even one that only sets returnPremiumCharge, re-enables it. Omitted subfields keep their stored values.'
878 + instant: ToolRouterInstantSchema.optional().describe(
879 + 'Experimental Instant usage policy. False disables it. Any supplied object, even one that only sets returnInstantCharge, re-enables it. Omitted subfields keep their stored values.'
880 ),
881 toolkits: z
882 .union([
@@ -1027,9 +1044,14 @@ export type ToolRouterSessionListConfigHistoryOptions = z.infer<
1044
1045 /**
1046 * The session configuration at one version, as stored by the API. This is
1030 - * the wire shape (snake_case), typed from the generated client.
1047 + * the wire shape (snake_case), with the Instant policy under `instant`.
1048 */
1032 -export type ToolRouterSessionConfigHistoryConfig = SessionConfigHistoryResponse.Item.Config;
1049 +export type ToolRouterSessionConfigHistoryConfig = Omit<
1050 + SessionConfigHistoryResponse.Item.Config,
1051 + 'premium_usage'
1052 +> & {
1053 + instant?: false | ToolRouterInstantResponse;
1054 +};
1055
1056 export type ToolRouterSessionConfigHistoryItem = {
1057 /** The config version this entry represents. */
ts/packages/core/src/utils/transformers/toolRouterResponseTransform.ts
+23 -5
@@ -1,6 +1,24 @@
1 /**
2 * Transforms snake_case Tool Router API responses to camelCase for SDK consumers.
3 */
4 +import { z } from 'zod/v3';
5 +import {
6 + ToolRouterInstantResponseSchema,
7 + type ToolRouterInstantResponse,
8 +} from '../../types/toolRouter.types';
9 +
10 +const SessionConfigInstantSchema = z.object({
11 + instant: z.union([z.literal(false), ToolRouterInstantResponseSchema]).optional(),
12 +});
13 +
14 +/** Session config retains its API casing, including `instant.return_instant_charge`. */
15 +export function transformSessionConfig<Config extends { premium_usage?: unknown }>(
16 + raw: Config
17 +): Omit<Config, 'premium_usage'> & { instant?: false | ToolRouterInstantResponse } {
18 + const { instant } = SessionConfigInstantSchema.parse(raw);
19 + const { premium_usage: _previousPolicy, ...config } = raw;
20 + return { ...config, ...(instant !== undefined && { instant }) };
21 +}
22
23 interface RawSearchResult {
24 index: number;
@@ -51,7 +69,7 @@ interface RawToolkitConnectionStatus {
69 status_message: string;
70 connection_details?: Record<string, unknown>;
71 current_user_info?: Record<string, unknown>;
54 - hosted_account?: { allowed_tool_slugs: string[] };
72 + instant_account?: { allowed_tool_slugs: string[] };
73 }
74
75 interface RawSearchResponse {
@@ -69,7 +87,7 @@ interface RawExecuteResponse {
87 data: Record<string, unknown>;
88 error: string | null;
89 log_id: string;
72 - premium_charge?: unknown;
90 + instant_charge?: unknown;
91 }
92
93 function transformSearchResult(raw: RawSearchResult) {
@@ -116,8 +134,8 @@ function transformToolkitConnectionStatus(raw: RawToolkitConnectionStatus) {
134 statusMessage: raw.status_message,
135 connectionDetails: raw.connection_details,
136 currentUserInfo: raw.current_user_info,
119 - ...(raw.hosted_account !== undefined && {
120 - hostedAccount: { allowedToolSlugs: raw.hosted_account.allowed_tool_slugs },
137 + ...(raw.instant_account !== undefined && {
138 + instantAccount: { allowedToolSlugs: raw.instant_account.allowed_tool_slugs },
139 }),
140 };
141 }
@@ -161,6 +179,6 @@ export function transformExecuteResponse(raw: RawExecuteResponse) {
179 data: raw.data,
180 error: raw.error,
181 logId: raw.log_id,
164 - ...(raw.premium_charge !== undefined && { premiumCharge: raw.premium_charge }),
182 + ...(raw.instant_charge !== undefined && { instantCharge: raw.instant_charge }),
183 };
184 }
ts/packages/core/test/lib/toolRouterParams.test.ts
+5 -5
@@ -183,14 +183,14 @@ describe('transformToolRouterTagsParams', () => {
183 });
184
185 describe('transformToolRouterUpdateParams', () => {
186 - it('maps the experimental premium usage policy without changing other session settings', () => {
186 + it('maps the experimental Instant usage policy without changing other session settings', () => {
187 expect(
188 transformToolRouterUpdateParams({
189 - premiumUsage: { toolkits: { disable: ['exa'] }, returnPremiumCharge: true },
189 + instant: { toolkits: { disable: ['exa'] }, returnInstantCharge: true },
190 })
191 - ).toEqual({ premium_usage: { toolkits: { disable: ['exa'] }, return_premium_charge: true } });
192 - expect(transformToolRouterUpdateParams({ premiumUsage: false })).toEqual({
193 - premium_usage: false,
191 + ).toEqual({ instant: { toolkits: { disable: ['exa'] }, return_instant_charge: true } });
192 + expect(transformToolRouterUpdateParams({ instant: false })).toEqual({
193 + instant: false,
194 });
195 });
196
ts/packages/core/test/models/toolRouter.test.ts
+50 -16
@@ -201,26 +201,24 @@ describe('ToolRouter', () => {
201 describe('create method', () => {
202 const userId = 'user_123';
203
204 - it('passes premium usage only when requested', async () => {
204 + it('passes Instant usage only when requested', async () => {
205 mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
206 await toolRouter.create(userId, {
207 - premiumUsage: { toolkits: { enable: ['exa'] }, returnPremiumCharge: true },
207 + instant: { toolkits: { enable: ['exa'] }, returnInstantCharge: true },
208 });
209 expect(mockClient.toolRouter.session.create.mock.calls[0]?.[0]).toMatchObject({
210 - premium_usage: { toolkits: { enable: ['exa'] }, return_premium_charge: true },
210 + instant: { toolkits: { enable: ['exa'] }, return_instant_charge: true },
211 });
212
213 mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
214 - await toolRouter.create(userId, { premiumUsage: false });
214 + await toolRouter.create(userId, { instant: false });
215 expect(mockClient.toolRouter.session.create.mock.calls[1]?.[0]).toMatchObject({
216 - premium_usage: false,
216 + instant: false,
217 });
218
219 mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
220 await toolRouter.create(userId);
221 - expect(mockClient.toolRouter.session.create.mock.calls[2]?.[0]).not.toHaveProperty(
222 - 'premium_usage'
223 - );
221 + expect(mockClient.toolRouter.session.create.mock.calls[2]?.[0]).not.toHaveProperty('instant');
222 });
223
224 describe('basic session creation', () => {
@@ -2838,7 +2836,7 @@ describe('ToolRouter', () => {
2836 );
2837 });
2838
2841 - it('should return the hosted account allowlist on toolkit connection statuses', async () => {
2839 + it('should return the Instant account allowlist on toolkit connection statuses', async () => {
2840 mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
2841 mockClient.toolRouter.session.search.mockResolvedValueOnce({
2842 ...mockSearchResponse,
@@ -2847,8 +2845,8 @@ describe('ToolRouter', () => {
2845 toolkit: 'exa',
2846 description: 'Exa',
2847 has_active_connection: true,
2850 - hosted_account: { allowed_tool_slugs: ['EXA_SEARCH'] },
2851 - status_message: 'Connected via the Composio hosted account.',
2848 + instant_account: { allowed_tool_slugs: ['EXA_SEARCH'] },
2849 + status_message: 'Connected via the Composio Instant account.',
2850 },
2851 ],
2852 });
@@ -2856,7 +2854,7 @@ describe('ToolRouter', () => {
2854 const session = await toolRouter.create(userId);
2855 const result = await session.search({ query: 'search the web' });
2856
2859 - expect(result.toolkitConnectionStatuses[0].hostedAccount).toEqual({
2857 + expect(result.toolkitConnectionStatuses[0].instantAccount).toEqual({
2858 allowedToolSlugs: ['EXA_SEARCH'],
2859 });
2860 });
@@ -2905,19 +2903,19 @@ describe('ToolRouter', () => {
2903 expect(result.logId).toBe('log_abc');
2904 });
2905
2908 - it('returns the premium charge when the API includes one', async () => {
2906 + it('returns the Instant charge when the API includes one', async () => {
2907 mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
2908 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
2909 ...mockExecuteResponse,
2912 - premium_charge: { amount: '0.01', currency: 'USD' },
2910 + instant_charge: { amount: '0.01', currency: 'USD' },
2911 });
2912
2913 const session = await toolRouter.create(userId, {
2916 - premiumUsage: { returnPremiumCharge: true },
2914 + instant: { returnInstantCharge: true },
2915 });
2916 const result = await session.execute('GMAIL_SEND_EMAIL');
2917
2920 - expect(result.premiumCharge).toEqual({ amount: '0.01', currency: 'USD' });
2918 + expect(result.instantCharge).toEqual({ amount: '0.01', currency: 'USD' });
2919 });
2920
2921 it('should propagate execute API errors', async () => {
@@ -4108,6 +4106,42 @@ describe('ToolRouter', () => {
4106 });
4107 });
4108
4109 + it('should expose each historical Instant policy under instant', async () => {
4110 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(mockSessionRetrieveResponse);
4111 + mockClient.toolRouter.session.configHistory.mockResolvedValueOnce({
4112 + items: [
4113 + {
4114 + ...rawHistoryItem,
4115 + config: {
4116 + ...rawHistoryItem.config,
4117 + premium_usage: false,
4118 + instant: { toolkits: { enabled: ['exa'] }, return_instant_charge: true },
4119 + },
4120 + },
4121 + {
4122 + ...rawHistoryItem,
4123 + version: 1,
4124 + is_current: false,
4125 + config: { ...rawHistoryItem.config, instant: false },
4126 + },
4127 + ],
4128 + total_pages: 1,
4129 + current_page: 1,
4130 + total_items: 2,
4131 + });
4132 +
4133 + const session = await toolRouter.use(sessionId);
4134 + const { items } = await session.listConfigHistory();
4135 +
4136 + expect(items.map(item => item.config)).toEqual([
4137 + {
4138 + ...rawHistoryItem.config,
4139 + instant: { toolkits: { enabled: ['exa'] }, return_instant_charge: true },
4140 + },
4141 + { ...rawHistoryItem.config, instant: false },
4142 + ]);
4143 + });
4144 +
4145 it('should default nextCursor to null and forward request options', async () => {
4146 mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(mockSessionRetrieveResponse);
4147 mockClient.toolRouter.session.configHistory.mockResolvedValueOnce({
ts/packages/core/test/tools/tools.test.ts
+3 -3
@@ -1365,12 +1365,12 @@ describe('Tools', () => {
1365 });
1366 });
1367
1368 - it('returns the premium charge for provider-wrapped session tools', async () => {
1368 + it('returns the Instant charge for provider-wrapped session tools', async () => {
1369 mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1370 data: {},
1371 error: null,
1372 log_id: '123',
1373 - premium_charge: { amount: '0.01', currency: 'USD' },
1373 + instant_charge: { amount: '0.01', currency: 'USD' },
1374 });
1375
1376 const result = await context.tools.executeSessionTool('EXA_SEARCH', {
@@ -1378,7 +1378,7 @@ describe('Tools', () => {
1378 arguments: {},
1379 });
1380
1381 - expect(result.premiumCharge).toEqual({ amount: '0.01', currency: 'USD' });
1381 + expect(result.instantCharge).toEqual({ amount: '0.01', currency: 'USD' });
1382 });
1383
1384 it('should pass inline custom tools to tool router session execute', async () => {
ts/packages/core/test/utils/toolRouterResponseTransform.test.ts
+33 -10
@@ -2,9 +2,31 @@ import { describe, it, expect } from 'vitest';
2 import {
3 transformSearchResponse,
4 transformExecuteResponse,
5 + transformSessionConfig,
6 } from '../../src/utils/transformers/toolRouterResponseTransform';
7
8 describe('toolRouterResponseTransform', () => {
9 + it('preserves the new Instant policy in server-side session config', () => {
10 + const config = {
11 + user_id: 'user_1',
12 + execute: {},
13 + search: {},
14 + preload: { tools: [] },
15 + instant: { toolkits: { enabled: ['exa'] }, return_instant_charge: true },
16 + premium_usage: false as const,
17 + };
18 + expect(transformSessionConfig(config)).toEqual({
19 + user_id: 'user_1',
20 + execute: {},
21 + search: {},
22 + preload: { tools: [] },
23 + instant: { toolkits: { enabled: ['exa'] }, return_instant_charge: true },
24 + });
25 + expect(transformSessionConfig({ ...config, instant: false }).instant).toBe(false);
26 + expect(() =>
27 + transformSessionConfig({ ...config, instant: { return_instant_charge: 'yes' } })
28 + ).toThrow();
29 + });
30 describe('transformSearchResponse', () => {
31 it('should transform snake_case search response to camelCase', () => {
32 const raw = {
@@ -132,7 +154,7 @@ describe('toolRouterResponseTransform', () => {
154 });
155 });
156
135 - it('maps the hosted account allowlist only when the API sends one', () => {
157 + it('maps the Instant account allowlist only when the API sends one', () => {
158 const raw = {
159 success: true,
160 error: null,
@@ -143,8 +165,8 @@ describe('toolRouterResponseTransform', () => {
165 toolkit: 'exa',
166 description: 'Exa',
167 has_active_connection: true,
146 - status_message: 'Connected via the Composio hosted account.',
147 - hosted_account: { allowed_tool_slugs: ['EXA_SEARCH'] },
168 + status_message: 'Connected via the Composio Instant account.',
169 + instant_account: { allowed_tool_slugs: ['EXA_SEARCH'] },
170 },
171 {
172 toolkit: 'gmail',
@@ -166,9 +188,10 @@ describe('toolRouterResponseTransform', () => {
188 },
189 };
190
169 - const [hosted, notHosted] = transformSearchResponse(raw).toolkitConnectionStatuses;
170 - expect(hosted.hostedAccount).toEqual({ allowedToolSlugs: ['EXA_SEARCH'] });
171 - expect(notHosted).not.toHaveProperty('hostedAccount');
191 + const [instantAccount, notInstantAccount] =
192 + transformSearchResponse(raw).toolkitConnectionStatuses;
193 + expect(instantAccount.instantAccount).toEqual({ allowedToolSlugs: ['EXA_SEARCH'] });
194 + expect(notInstantAccount).not.toHaveProperty('instantAccount');
195 });
196 });
197
@@ -200,18 +223,18 @@ describe('toolRouterResponseTransform', () => {
223 expect(result.logId).toBe('log_err');
224 });
225
203 - it('preserves the optional premium charge without inventing one', () => {
226 + it('preserves the optional Instant charge without inventing one', () => {
227 expect(
228 transformExecuteResponse({
229 data: {},
230 error: null,
231 log_id: 'log_paid',
209 - premium_charge: { amount: '0.01', currency: 'USD' },
210 - }).premiumCharge
232 + instant_charge: { amount: '0.01', currency: 'USD' },
233 + }).instantCharge
234 ).toEqual({ amount: '0.01', currency: 'USD' });
235 expect(
236 transformExecuteResponse({ data: {}, error: null, log_id: 'log_free' })
214 - ).not.toHaveProperty('premiumCharge');
237 + ).not.toHaveProperty('instantCharge');
238 });
239 });
240 });
ts/packages/core/type-tests/instant-contract.test-d.ts new
+51
@@ -0,0 +1,51 @@
1 +/** Instant guide examples are checked against the local SDK before publication. */
2 +import { Composio } from '../src';
3 +
4 +declare const composio: Composio;
5 +
6 +async function instantContract(): Promise<void> {
7 + const session = await composio.create('user_123', {
8 + toolkits: ['exa'],
9 + instant: { toolkits: { enable: ['exa'] }, returnInstantCharge: true },
10 + });
11 + await composio.sessions.create('user_123', {
12 + toolkits: ['exa', 'firecrawl'],
13 + instant: {
14 + toolkits: { enable: ['exa'] },
15 + tools: { exa: { enable: ['EXA_SEARCH'] } },
16 + },
17 + });
18 + await session.update({ instant: false });
19 + await session.execute('EXA_SEARCH', {}, { account: 'instant_account' });
20 + if (session.config.instant) {
21 + const returnsCharge: boolean = session.config.instant.return_instant_charge;
22 + void returnsCharge;
23 + }
24 +
25 + const { items } = await session.listConfigHistory();
26 + const [historical] = items;
27 + if (historical?.config.instant) {
28 + const returnedCharge: boolean = historical.config.instant.return_instant_charge;
29 + void returnedCharge;
30 + }
31 +
32 + const summary = await composio.experimental.usage.summary();
33 + const charge: string = summary.instantCharge;
34 + void charge;
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;
49 +}
50 +
51 +void instantContract;