@devries-cameron20 / composio Mirror · read-only / commits / de5e3f609
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, 11:00 UTC

feat(core): support saved Session configs (#4601)

This PR: - lets TypeScript users read the project's saved Session configs with `composio.sessionConfigs.list()` / `.get()` (the endpoints need Session configs enabled for the project) - lets `composio.sessions.create()` start a session from a saved config via `experimental.sessionConfigId`; without it, the create payload is byte-for-byte unchanged - rejects a saved config mixed with inline access fields before any request: on create with `toolkits`, `tools`, `tags`, `experimental.customTools` or `experimental.customToolkits`; on `session.update()` with `toolkits`, `tools` or `tags` (`null` counts). TypeScript reports it at compile time; at runtime it throws `ValidationError`, while other invalid input keeps throwing `ZodError` - exposes `session.experimental.sourceSessionConfig` (`{ id }` of the last config applied) after `create()`, `sessions.use()` and a successful `update()` - replaces the misleading "no longer at version N" 409 message when `update()` applies a config: it now names the session and the config and says to re-fetch and retry (`meta.sessionConfigId` is set) - documents the feature in `configuring-sessions.mdx`, regenerates the TypeScript SDK reference, adds a minor changeset for `@composio/core`, and adds `pnpm --filter session-management-example start:session-configs` for manual verification ## Context Session configs are saved `sc_…` access policies built in the Dashboard. The backend and `@composio/client` 2.0.0-rc.8 already support them; `@composio/core` only had `sessionConfigId` on `update()`. The SDK stays a thin wrapper: the backend resolves and enforces every policy, and no failure path falls back to an unrestricted session. Missing, archived and cross-project configs surface as the backend's `404`; `400`/`403` surface unchanged. `ToolRouterCreateSessionConfig` and `ToolRouterUpdateSessionConfig` are now unions (inline access vs saved config). Existing inline callers, both `create()` overloads (including `{ mcp: true }`) and trailing `requestOptions` still type-check; `type-tests/session-configs.test-d.ts` pins this. TypeScript only. Python parity and CLI commands are follow-up work. ## Before merge - [x] Run the manual script against an enabled production project with active and archived configs. All configured checks and cleanup passed. The optional feature-disabled-project check was skipped. - [ ] Record whether `sessionPreset: SessionPreset.DIRECT_TOOLS` works with a saved config, and add the result to `configuring-sessions.mdx`. The preset injects `preload: { tools: 'all' }`, which the backend may reject for a denylist-only config; the SDK surfaces that `400` unchanged. - [ ] Add the Linear issue link ## Testing - `pnpm --filter @composio/core test`: 1578 passed, 2 expected failures, including HTTP-level saved-config PATCH regression tests - `pnpm --filter @composio/core typecheck`, including new type tests; each `@ts-expect-error` was checked to fail for the intended reason - `pnpm typecheck` (16/16), `pnpm lint:packages` (no new warnings), `pnpm test:examples`, `pnpm --filter session-management-example typecheck` - `pnpm --filter @composio/core generate:docs` exits 0; only pages this change touches were regenerated - Live manual script: passed against production, including default saved-config PATCH, archived and missing config errors, DIRECT_TOOLS with the tested selected-toolkit config, and deletion of all created Sessions. - Example pagination and cleanup tests: 6 passed. SDK build and core/example type checks passed. - Integrated `next` and its opt-in version-check fix (#4603), preserving explicit preconditions and no-retry behavior. Code review: multi-reviewer pass plus an independent cross-model adversarial pass. The one validated finding (hand-rolled error-status guard in the example script) is fixed. ## Post-Deploy Monitoring & Validation No additional operational monitoring required: this is a client SDK change behind experimental APIs; requests go to existing backend endpoints, and callers that don't pass `sessionConfigId` send unchanged payloads. After release, watch SDK issues for `ValidationError` reports that mention `experimental.sessionConfigId` from callers who didn't expect the mixed-input rule. --------- Co-authored-by: Shubham Mehta <80706620+shubham22@users.noreply.github.com>

Alberto Schiabel committed Sep 24, 2026 at 13:23 UTC de5e3f609e73864fd6efc8bfe0bafe08fb1951d1
33 files changed +2126 -68
.changeset/session-config-read-api-annotations.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Remove experimental annotations from the top-level Session config read methods. Applying a config and reading its source metadata remain under `experimental`.
.changeset/session-configs.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Add experimental support for saved Session configs. `composio.sessionConfigs.list()` and `composio.sessionConfigs.get()` read the project's saved `sc_…` configs, and `experimental.sessionConfigId` on `composio.sessions.create()` starts a session from one. Combining `sessionConfigId` with inline access fields now fails before any request: on create with `toolkits`, `tools`, `tags`, `experimental.customTools` or `experimental.customToolkits`, and on `session.update()` with `toolkits`, `tools` or `tags` (including `null`). TypeScript reports the mix at compile time and the SDK throws `ValidationError` at runtime; other invalid inputs keep throwing `ZodError`. `session.experimental.sourceSessionConfig` exposes the last config applied to the session after `create()`, `sessions.use()` and `update()`. A 409 while `update()` applies a config now says that the session or the config changed and to re-fetch and retry, instead of reporting a stale version.
docs/content/docs/configuring-sessions.mdx
+81 -1
@@ -35,6 +35,86 @@ If you use a [scoped project API key](/reference/authenticating-to-composio/proj
35
36 Enable both permissions if your application manages sessions and executes tools through them.
37
38 +## Using a saved Session config
39 +
40 +A **Session config** is a saved, named access policy (`sc_…`) that you build in the Composio Dashboard under Sessions → Configs. Start a session from one instead of repeating `toolkits`, `tools`, and `tags` in your code:
41 +
42 +```typescript
43 +// @noErrors
44 +import { Composio } from '@composio/core';
45 +const composio = new Composio({ apiKey: 'your_api_key' });
46 +// ---cut---
47 +const { items } = await composio.sessionConfigs.list({ search: "support" });
48 +
49 +const session = await composio.sessions.create("user_123", {
50 + authConfigs: { github: "ac_123" },
51 + experimental: { sessionConfigId: items[0].id },
52 +});
53 +
54 +console.log(session.experimental.sourceSessionConfig); // { id: "sc_..." }
55 +```
56 +
57 +The backend resolves the config when it creates the session, so the session gets exactly the access the config grants. Later edits to the config in the Dashboard don't change sessions that already exist.
58 +
59 +<Callout type="info">
60 +The top-level `composio.sessionConfigs` read methods are available in TypeScript. Applying a config and reading its source metadata use `experimental`. Reads require Session configs enabled for your project; otherwise they return `403`. With a [scoped project API key](/reference/authenticating-to-composio/project-api-key-permissions#session-management), they need the **Session management** read permission.
61 +</Callout>
62 +
63 +### Finding a config
64 +
65 +`composio.sessionConfigs.list()` returns summaries (`id`, `name`, `archived`, `createdAt`, `updatedAt`) and a `nextCursor`. It returns active configs unless you pass `archived: true`, which returns only archived ones. Pass `search` to match names and `limit` and `cursor` to page; the backend returns 20 per page by default and at most 100.
66 +
67 +`composio.sessionConfigs.get(id)` adds the `description` and the stored policy under `config`:
68 +
69 +```typescript
70 +// @noErrors
71 +import { Composio } from '@composio/core';
72 +const composio = new Composio({ apiKey: 'your_api_key' });
73 +// ---cut---
74 +const sessionConfig = await composio.sessionConfigs.get("sc_123");
75 +
76 +console.log(sessionConfig.config);
77 +// { toolkits: { enable: ["github"] }, tags: { disable: ["destructiveHint"] } }
78 +```
79 +
80 +A saved policy uses `enable` and `disable`, the same shape you send on create. `session.config` is the server's snapshot of a live session and names the same lists `enabled` and `disabled`.
81 +
82 +### What you can combine with a config
83 +
84 +The config owns the session's toolkit, tool, and tag access. On `create()`, you can't pass `sessionConfigId` together with `toolkits`, `tools`, `tags`, `experimental.customTools`, or `experimental.customToolkits`. TypeScript reports the mix at compile time, and the SDK throws `ValidationError` before it sends a request. An empty list such as `toolkits: []` counts as set.
85 +
86 +Per-session settings stay yours: `authConfigs`, `connectedAccounts`, `manageConnections`, `sandbox`, `multiAccount`, `preload`, `sessionPreset`, `mcp`, and `experimental.assistivePrompt`.
87 +
88 +`SessionPreset.DIRECT_TOOLS` defaults to `preload: { tools: "all" }` when you omit `preload`. With a saved config, the backend resolves its policy before validating that preload. The policy must select toolkits with `enable`, enable specific tools, or enable tags within a named toolkit's tool rule. An unrestricted policy, a denylist-only policy, or top-level tags alone returns `400`. The resolved tool set must also contain at most 1,000 tools.
89 +
90 +Live verification accepted `DIRECT_TOOLS` with a saved config that provided a positive toolkit/tool scope. The no-positive-scope case was not exercised in that run; its `400` behavior is enforced by the API's preload validation. The SDK passes these API errors through unchanged.
91 +
92 +### Applying a config to an existing session
93 +
94 +Pass `sessionConfigId` in the `experimental` block of `session.update()` to replace the session's toolkit, tool, and tag access with the config's policy. Other settings are preserved.
95 +
96 +```typescript
97 +// @noErrors
98 +import { Composio } from '@composio/core';
99 +const composio = new Composio({ apiKey: 'your_api_key' });
100 +// ---cut---
101 +const session = await composio.sessions.use("session_id");
102 +
103 +await session.update({ experimental: { sessionConfigId: "sc_123" } });
104 +```
105 +
106 +The same rule applies here: `sessionConfigId` can't be combined with `toolkits`, `tools`, or `tags`, and `null` counts as set. A saved config and custom tools don't mix on update either: if the session was created with inline custom tools, the backend rejects a conflicting config with a `400`.
107 +
108 +A `409` while applying a config means the session or the config changed during the update. The SDK raises `ComposioSessionConfigConflictError`, and nothing was written: re-fetch the session with `sessions.use()` and retry.
109 +
110 +### Which config a session came from
111 +
112 +`session.experimental.sourceSessionConfig` holds `{ id }` of the last config applied to the session. The SDK sets it after `create()`, `sessions.use()`, and a successful `update()`. It stays set after later inline updates such as `update({ toolkits: [...] })`, and it's `undefined` when no config was applied. It reflects the last response this session object saw, so an update from another process leaves it stale until you call `sessions.use()` again.
113 +
114 +### When a config can't be used
115 +
116 +The SDK never retries without the config or falls back to an unrestricted session. A missing, archived, or cross-project config fails with the backend's `404`, and a project without Session configs fails with `403`. A failed `update()` leaves the session object unchanged.
117 +
118 ## Reading and updating session configuration
119
120 In TypeScript, `session.config` exposes the configuration returned by the server. Call `session.update()` to change selected fields. It preserves omitted fields, updates `session.config` in place, and returns the updated configuration. See [Updating a session](/docs/how-composio-works#how-sessions-behave) for an example.
@@ -917,7 +997,7 @@ await session.update({
997
998 Both blocks are on by default. `search` controls the session's search helper, so disabling it leaves the agent with the tools you preloaded. `execute.enableMultiExecute` controls whether the agent can run several tool calls in one request. `manageConnections.enableConnectionRemoval` is update-only as well, and controls whether the session exposes the connection-removal tool.
999
920 -The `experimental` block on update holds server-side session settings: `permissions`, `linkUrlOverwrite`, `fastMode`, `submitFeedback`, and `sessionConfigId`. It is a different field from the `experimental` option on `create()`, which holds [custom tools and toolkits](/docs/extending-sessions/custom-tools-and-toolkits) that run in your process, so `experimental: null` on an update leaves those alone.
1000 +The `experimental` block on update holds server-side session settings: `permissions`, `linkUrlOverwrite`, `fastMode`, `submitFeedback`, and `sessionConfigId`. `sessionConfigId` applies a [saved Session config](#applying-a-config-to-an-existing-session) and can't be combined with `toolkits`, `tools`, or `tags`. The `experimental` block on update is a different field from the `experimental` option on `create()`, which holds [custom tools and toolkits](/docs/extending-sessions/custom-tools-and-toolkits) that run in your process, so `experimental: null` on an update leaves those alone.
1001
1002 ### Multi-account mode after an update
1003
docs/content/reference/sdk-reference/typescript/composio.mdx
+2 -1
@@ -53,13 +53,14 @@ const composio = new Composio({
53 |------|------|-------------|
54 | `authConfigs` | `AuthConfigs` | Manage authentication configurations for toolkits |
55 | `connectedAccounts` | `ConnectedAccounts` | Manage authenticated connections |
56 -| `create` | `(userId: string, config: \{ authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string \| ...[]>; experimental?: \{ assistivePrompt?: \{ userTimezone?: string \}; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] \}; manageConnections?: boolean \| \{ callbackUrl?: string; enable?: boolean; waitForConnections?: boolean \}; mcp?: boolean; multiAccount?: \{ enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean \}; preload?: \{ tools?: ...[] \| 'all' \}; premiumUsage?: false \| \{ returnPremiumCharge?: boolean; toolkits?: ... \| ...; tools?: Record<..., ...> \}; sandbox?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \}; sessionPreset?: 'direct_tools'; tags?: ... \| ... \| ... \| ...[] \| \{ disable?: ...[]; enable?: ...[] \}; toolkits?: string[] \| \{ disable: ...[] \} \| \{ enable: ...[] \}; tools?: Record<string, ...[] \| \{ enable: ... \} \| \{ disable: ... \} \| \{ tags: ... \}>; workbench?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \} & \{ mcp: true \}, requestOptions: ComposioRequestOptions) => Promise<Session>` | Creates a new tool router session for a user. Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools should be exposed directly; see `ToolRouterCreateSessionConfig`. |
56 +| `create` | `(...) => Promise<Session>` | Creates a new tool router session for a user. Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools should be exposed directly; see `ToolRouterCreateSessionConfig`. |
57 | `experimental` | `Experimental` | Experimental SDK methods whose shape may change in future releases. Prefer domain-specific mounts (for example `composio.connectedAccounts.updateAcl(...)`) when available; this namespace keeps compatibility aliases while APIs are experimental. Stateless experimental factories (e.g. `experimental_createTool`) stay at the top level. |
58 | `files` | `Files` | Upload and download files |
59 | `keyring` | `Keyring` | Public transfer keys of the organization's customer-managed keyring |
60 | `logs` | `Logs` | Search and inspect tool-execution logs |
61 | `mcp` | `MCP` | Model Context Protocol server management. |
62 | `provider` | `TProvider` | The tool provider instance used for wrapping tools in framework-specific formats |
63 +| `sessionConfigs` | `SessionConfigs` | Read the project's saved Session configs. Apply one with `experimental.sessionConfigId` on `sessions.create()` or `session.update()`. Requires Session configs to be enabled for the project. |
64 | `sessions` | `Sessions` | Create and reuse Composio sessions. Prefer `composio.sessions.create(...)` for new code. The top-level `composio.create(...)` method is kept as an alias. |
65 | `toolkits` | `Toolkits` | Retrieve toolkit metadata and authorize user connections |
66 | `toolRouter` | `ToolRouter` | Legacy alias for `composio.sessions`. |
docs/content/reference/sdk-reference/typescript/index.mdx
+1
@@ -26,6 +26,7 @@ description: "Complete API reference for the Composio TypeScript SDK (@composio/
26 | [`Session files`](/reference/sdk-reference/typescript/session-files) | File mount for a Composio session, reached via `session.experimental.files` |
27 | [`Tools`](/reference/sdk-reference/typescript/tools) | This class is used to manage tools in the Composio SDK. |
28 | [`Triggers`](/reference/sdk-reference/typescript/triggers) | Trigger (Instance) class |
29 +| [`SessionConfigs`](/reference/sdk-reference/typescript/session-configs) | `composio.sessionConfigs` — saved, reusable Session configs. |
30 | [`Usage`](/reference/sdk-reference/typescript/usage) | `composio.experimental.usage` — metering for the project the API key |
31 | [`WebhookEndpoints`](/reference/sdk-reference/typescript/webhook-endpoints) | `composio.webhooks.endpoints` — inbound webhook endpoints. Each endpoint is |
32 | [`Webhooks`](/reference/sdk-reference/typescript/webhooks) | `composio.webhooks` namespace. |
docs/content/reference/sdk-reference/typescript/meta.json
+1
@@ -16,6 +16,7 @@
16 "session-files",
17 "tools",
18 "triggers",
19 + "session-configs",
20 "usage",
21 "webhook-endpoints",
22 "webhooks",
docs/content/reference/sdk-reference/typescript/session-configs.mdx new
+83
@@ -0,0 +1,83 @@
1 +---
2 +title: "SessionConfigs"
3 +description: "`composio.sessionConfigs` — saved, reusable Session configs. A Session config is a named access policy (`sc_…`) built in the Composio Dashboard under Sessions → Configs. Pass its id as `experimental.sessionConfigId` to `composio.sessions.create()` or `session.update()` to apply it. These endpoints require Session configs to be enabled for the project; otherwise the backend returns 403."
4 +---
5 +
6 +## Usage
7 +
8 +Access this class through the `composio.sessionConfigs` property:
9 +
10 +```typescript
11 +const composio = new Composio({ apiKey: 'your-api-key' });
12 +const result = await composio.sessionConfigs.list();
13 +```
14 +
15 +## Methods
16 +
17 +### get()
18 +
19 +Retrieve one saved Session config with its description and access
20 +policy. A missing or cross-project id surfaces as the backend's 404.
21 +
22 +Requires Session configs to be enabled for the project.
23 +
24 +```typescript
25 +async get(id: string, requestOptions?: ComposioRequestOptions): Promise<{ archived: boolean; config: { tags?: { disable?: ... | ... | ... | ...[]; enable?: ... | ... | ... | ...[] }; toolkits?: { enable: ...[] } | { disable: ...[] }; tools?: Record<string, { enable: ... } | { disable: ... } | { tags: ... }> }; createdAt: string; description: string | null; id: string; name: string; updatedAt: string }>
26 +```
27 +
28 +**Parameters**
29 +
30 +| Name | Type | Description |
31 +|------|------|-------------|
32 +| `id` | `string` | The `sc_…` id of the Session config |
33 +| `requestOptions?` | `ComposioRequestOptions` | |
34 +
35 +**Returns**
36 +
37 +`Promise<\{ archived: boolean; config: \{ tags?: \{ disable?: ... \| ... \| ... \| ...[]; enable?: ... \| ... \| ... \| ...[] \}; toolkits?: \{ enable: ...[] \} \| \{ disable: ...[] \}; tools?: Record<string, \{ enable: ... \} \| \{ disable: ... \} \| \{ tags: ... \}> \}; createdAt: string; description: string \| null; id: string; name: string; updatedAt: string \}>` — The config and its policy
38 +
39 +**Example**
40 +
41 +```typescript
42 +const sessionConfig = await composio.sessionConfigs.get('sc_abc123');
43 +console.log(sessionConfig.config.toolkits);
44 +```
45 +
46 +---
47 +
48 +### list()
49 +
50 +List the project's saved Session configs with cursor pagination.
51 +
52 +Omitting `archived` returns active configs; `archived: true` returns only
53 +archived ones. The backend defaults `limit` to 20 and caps it at 100.
54 +
55 +Requires Session configs to be enabled for the project.
56 +
57 +```typescript
58 +async list(params?: { archived?: boolean; cursor?: string; limit?: number; search?: string }, requestOptions?: ComposioRequestOptions): Promise<{ items: { archived: boolean; createdAt: string; id: string; name: string; updatedAt: string }[]; nextCursor: string | null }>
59 +```
60 +
61 +**Parameters**
62 +
63 +| Name | Type | Description |
64 +|------|------|-------------|
65 +| `params?` | `\{ archived?: boolean; cursor?: string; limit?: number; search?: string \}` | `search`, `archived`, `limit` and `cursor` |
66 +| `requestOptions?` | `ComposioRequestOptions` | |
67 +
68 +**Returns**
69 +
70 +`Promise<\{ items: \{ archived: boolean; createdAt: string; id: string; name: string; updatedAt: string \}[]; nextCursor: string \| null \}>` — Config summaries and the next cursor
71 +
72 +**Example**
73 +
74 +```typescript
75 +let cursor: string | undefined;
76 +do {
77 + const page = await composio.sessionConfigs.list({ cursor });
78 + for (const item of page.items) console.log(item.id, item.name);
79 + cursor = page.nextCursor ?? undefined;
80 +} while (cursor);
81 +```
82 +
83 +---
docs/content/reference/sdk-reference/typescript/session.mdx
+13 -6
@@ -7,7 +7,7 @@ description: "A Composio session — the object returned by `composio.sessions.c
7
8 | Name | Type | Description |
9 |------|------|-------------|
10 -| `config` | `Config` | Server-side session configuration (toolkit/tool allowlists, tags, preload, sandbox, manage_connections) as returned by the API. Refreshed in place by `update()`. |
10 +| `config` | `Config` | The session's current configuration (policy snapshot and runtime settings). Refreshed in place by `update()`. For saved, reusable Session configs, see `composio.sessionConfigs`. |
11 | `configVersion` | `number` | Version of the server-side configuration this object last observed. Refreshed in place by `update()`. Pass it as `expectedConfigVersion` to make an update conditional. |
12 | `experimental` | `SessionExperimental` | |
13 | `mcp` | `\{ headers?: Record<string, string>; type: 'http' \| 'sse'; url: string \}` | Hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`). Exists on every session at runtime, but only surfaced in the type when the session is created with `\{ mcp: true \}` (which returns `Session`); the default `SessionWithoutMcp` omits `mcp`, so MCP is an explicit opt-in. See https://docs.composio.dev/docs/sessions-via-mcp |
@@ -326,19 +326,26 @@ so a 409 is reported exactly once. On conflict this object is left
326 unchanged: re-fetch the session with `sessions.use(sessionId)` and retry
327 against the fresh `configVersion`.
328
329 -`config`, `configVersion`, `preload`, `sandbox` and `warnings` are
330 -refreshed in place only after a successful response, and the updated
331 -`config` is returned.
329 +`experimental.sessionConfigId` applies a saved Session config: it
330 +replaces the session's toolkit, tool and tag access and cannot be combined
331 +with `toolkits`, `tools` or `tags` (a `ValidationError` is thrown before
332 +any request). A 409 while applying it means the session or the config
333 +changed; re-fetch the session and retry. Backend 400, 403 and 404 errors,
334 +for example for an archived or missing config, surface unchanged.
335 +
336 +`config`, `configVersion`, `preload`, `sandbox`, `warnings` and
337 +`experimental.sourceSessionConfig` are refreshed in place only after a
338 +successful response, and the updated `config` is returned.
339
340 ```typescript
334 -async update(config: { authConfigs?: Record<string, string> | null; connectedAccounts?: Record<string, string[]> | null; execute?: { enableMultiExecute?: boolean } | null; expectedConfigVersion?: number | false; experimental?: { fastMode?: boolean | null; linkUrlOverwrite?: string | null; permissions?: { default: ... | ... | ...; overrides?: Record<..., ...> } | null; sessionConfigId?: string; submitFeedback?: { enable: boolean } | null } | null; manageConnections?: boolean | { callbackUrl?: string | null; enable?: boolean; enableConnectionRemoval?: boolean | null; waitForConnections?: boolean } | null; multiAccount?: { enable?: boolean; maxAccountsPerToolkit?: number | null; requireExplicitSelection?: boolean } | null; preload?: { tools?: string[] | 'all' } | null; premiumUsage?: false | { returnPremiumCharge?: boolean; toolkits?: { disable: ...[] } | { enable: ...[] }; tools?: Record<string, { enable: ... } | { disable: ... }> }; sandbox?: { autoOffloadThreshold?: number; enable?: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' } | null; search?: { enable?: boolean } | null; tags?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[] | { disable?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[]; enable?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[] } | null; toolkits?: string[] | { disable: string[] } | { enable: string[] } | null; tools?: Record<string, string[] | { enable: ...[] } | { disable: ...[] } | { tags: ... | ... }> | null; workbench?: { autoOffloadThreshold?: number; enable?: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' } | null }, requestOptions?: ComposioRequestOptions): Promise<Config>
341 +async update(config: ToolRouterUpdateSessionConfig, requestOptions?: ComposioRequestOptions): Promise<Config>
342 ```
343
344 **Parameters**
345
346 | Name | Type |
347 |------|------|
341 -| `config` | `\{ authConfigs?: Record<string, string> \| null; connectedAccounts?: Record<string, string[]> \| null; execute?: \{ enableMultiExecute?: boolean \} \| null; expectedConfigVersion?: number \| false; experimental?: \{ fastMode?: boolean \| null; linkUrlOverwrite?: string \| null; permissions?: \{ default: ... \| ... \| ...; overrides?: Record<..., ...> \} \| null; sessionConfigId?: string; submitFeedback?: \{ enable: boolean \} \| null \} \| null; manageConnections?: boolean \| \{ callbackUrl?: string \| null; enable?: boolean; enableConnectionRemoval?: boolean \| null; waitForConnections?: boolean \} \| null; multiAccount?: \{ enable?: boolean; maxAccountsPerToolkit?: number \| null; requireExplicitSelection?: boolean \} \| null; preload?: \{ tools?: string[] \| 'all' \} \| null; premiumUsage?: false \| \{ returnPremiumCharge?: boolean; toolkits?: \{ disable: ...[] \} \| \{ enable: ...[] \}; tools?: Record<string, \{ enable: ... \} \| \{ disable: ... \}> \}; sandbox?: \{ autoOffloadThreshold?: number; enable?: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \| null; search?: \{ enable?: boolean \} \| null; tags?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \| \{ disable?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[]; enable?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \} \| null; toolkits?: string[] \| \{ disable: string[] \} \| \{ enable: string[] \} \| null; tools?: Record<string, string[] \| \{ enable: ...[] \} \| \{ disable: ...[] \} \| \{ tags: ... \| ... \}> \| null; workbench?: \{ autoOffloadThreshold?: number; enable?: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \| null \}` |
348 +| `config` | `ToolRouterUpdateSessionConfig` |
349 | `requestOptions?` | `ComposioRequestOptions` |
350
351 **Returns**
docs/content/reference/sdk-reference/typescript/sessions.mdx
+10 -4
@@ -30,7 +30,7 @@ origins is logged, so native tools keep working.
30 **Overload 1**
31
32 ```typescript
33 -async create(userId: string, config: { authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string | string[]>; experimental?: { assistivePrompt?: { userTimezone?: string }; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] }; manageConnections?: boolean | { callbackUrl?: string; enable?: boolean; waitForConnections?: boolean }; mcp?: boolean; multiAccount?: { enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean }; preload?: { tools?: string[] | 'all' }; premiumUsage?: false | { returnPremiumCharge?: boolean; toolkits?: { disable: ... } | { enable: ... }; tools?: Record<string, ... | ...> }; sandbox?: { autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' }; sessionPreset?: 'direct_tools'; tags?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[] | { disable?: ... | ... | ... | ...[]; enable?: ... | ... | ... | ...[] }; toolkits?: string[] | { disable: string[] } | { enable: string[] }; tools?: Record<string, string[] | { enable: ...[] } | { disable: ...[] } | { tags: ... | ... }>; workbench?: { autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' } } & { mcp: true }, requestOptions?: ComposioRequestOptions): Promise<Session<TToolCollection, TTool, TProvider>>
33 +async create(userId: string, config: ToolRouterCreateSessionConfig & { mcp: true }, requestOptions?: ComposioRequestOptions): Promise<Session<TToolCollection, TTool, TProvider>>
34 ```
35
36 **Parameters**
@@ -38,7 +38,7 @@ async create(userId: string, config: { authConfigs?: Record<string, string>; con
38 | Name | Type | Description |
39 |------|------|-------------|
40 | `userId` | `string` | \{string\} The user id to create the session for |
41 -| `config` | `\{ authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string \| string[]>; experimental?: \{ assistivePrompt?: \{ userTimezone?: string \}; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] \}; manageConnections?: boolean \| \{ callbackUrl?: string; enable?: boolean; waitForConnections?: boolean \}; mcp?: boolean; multiAccount?: \{ enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean \}; preload?: \{ tools?: string[] \| 'all' \}; premiumUsage?: false \| \{ returnPremiumCharge?: boolean; toolkits?: \{ disable: ... \} \| \{ enable: ... \}; tools?: Record<string, ... \| ...> \}; sandbox?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \}; sessionPreset?: 'direct_tools'; tags?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \| \{ disable?: ... \| ... \| ... \| ...[]; enable?: ... \| ... \| ... \| ...[] \}; toolkits?: string[] \| \{ disable: string[] \} \| \{ enable: string[] \}; tools?: Record<string, string[] \| \{ enable: ...[] \} \| \{ disable: ...[] \} \| \{ tags: ... \| ... \}>; workbench?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \} & \{ mcp: true \}` | \{ToolRouterCreateSessionConfig\} The config for the tool router session |
41 +| `config` | `ToolRouterCreateSessionConfig & \{ mcp: true \}` | \{ToolRouterCreateSessionConfig\} The config for the tool router session |
42 | `requestOptions?` | `ComposioRequestOptions` | |
43
44 **Returns**
@@ -48,7 +48,7 @@ async create(userId: string, config: { authConfigs?: Record<string, string>; con
48 **Overload 2**
49
50 ```typescript
51 -async create(userId: string, config?: { authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string | string[]>; experimental?: { assistivePrompt?: { userTimezone?: string }; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] }; manageConnections?: boolean | { callbackUrl?: string; enable?: boolean; waitForConnections?: boolean }; mcp?: boolean; multiAccount?: { enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean }; preload?: { tools?: string[] | 'all' }; premiumUsage?: false | { returnPremiumCharge?: boolean; toolkits?: { disable: ...[] } | { enable: ...[] }; tools?: Record<string, { enable: ... } | { disable: ... }> }; sandbox?: { autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' }; sessionPreset?: 'direct_tools'; tags?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[] | { disable?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[]; enable?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[] }; toolkits?: string[] | { disable: string[] } | { enable: string[] }; tools?: Record<string, string[] | { enable: string[] } | { disable: string[] } | { tags: ...[] | { disable?: ...; enable?: ... } }>; workbench?: { autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' } }, requestOptions?: ComposioRequestOptions): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>
51 +async create(userId: string, config?: ToolRouterCreateSessionConfig, requestOptions?: ComposioRequestOptions): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>
52 ```
53
54 **Parameters**
@@ -56,7 +56,7 @@ async create(userId: string, config?: { authConfigs?: Record<string, string>; co
56 | Name | Type | Description |
57 |------|------|-------------|
58 | `userId` | `string` | \{string\} The user id to create the session for |
59 -| `config?` | `\{ authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string \| string[]>; experimental?: \{ assistivePrompt?: \{ userTimezone?: string \}; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] \}; manageConnections?: boolean \| \{ callbackUrl?: string; enable?: boolean; waitForConnections?: boolean \}; mcp?: boolean; multiAccount?: \{ enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean \}; preload?: \{ tools?: string[] \| 'all' \}; premiumUsage?: false \| \{ returnPremiumCharge?: boolean; toolkits?: \{ disable: ...[] \} \| \{ enable: ...[] \}; tools?: Record<string, \{ enable: ... \} \| \{ disable: ... \}> \}; sandbox?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \}; sessionPreset?: 'direct_tools'; tags?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \| \{ disable?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[]; enable?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \}; toolkits?: string[] \| \{ disable: string[] \} \| \{ enable: string[] \}; tools?: Record<string, string[] \| \{ enable: string[] \} \| \{ disable: string[] \} \| \{ tags: ...[] \| \{ disable?: ...; enable?: ... \} \}>; workbench?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \}` | \{ToolRouterCreateSessionConfig\} The config for the tool router session |
59 +| `config?` | `ToolRouterCreateSessionConfig` | \{ToolRouterCreateSessionConfig\} The config for the tool router session |
60 | `requestOptions?` | `ComposioRequestOptions` | |
61
62 **Returns**
@@ -78,6 +78,12 @@ const session = await composio.sessions.create('user_123', {
78 customToolkits: [myToolkit],
79 },
80 });
81 +
82 +// Start from a saved Session config instead of inline access fields
83 +const configured = await composio.sessions.create('user_123', {
84 + authConfigs: { github: 'ac_123' },
85 + experimental: { sessionConfigId: 'sc_123' },
86 +});
87 ```
88
89 ---
pnpm-lock.yaml
+37 -28
@@ -739,7 +739,7 @@ importers:
739 version: 2.22.0(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4))
740 '@modelcontextprotocol/sdk':
741 specifier: 'catalog:'
742 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
742 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
743 dotenv:
744 specifier: 'catalog:'
745 version: 17.4.2
@@ -891,7 +891,7 @@ importers:
891 version: link:../../packages/providers/vercel
892 '@modelcontextprotocol/sdk':
893 specifier: 'catalog:'
894 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
894 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
895 ai:
896 specifier: 'catalog:'
897 version: 7.0.101(zod@4.5.4)
@@ -944,7 +944,7 @@ importers:
944 version: link:../../packages/providers/openai-agents
945 '@modelcontextprotocol/sdk':
946 specifier: 'catalog:'
947 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
947 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
948 '@openai/agents':
949 specifier: ^0.18.0
950 version: 0.18.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(supports-color@10.2.2)(undici@6.28.0)(ws@8.21.3)(zod@4.5.4)
@@ -976,6 +976,9 @@ importers:
976
977 ts/examples/session-management:
978 dependencies:
979 + '@composio/client':
980 + specifier: 'catalog:'
981 + version: 2.0.0-rc.8
982 '@composio/core':
983 specifier: workspace:*
984 version: link:../../packages/core
@@ -1170,7 +1173,7 @@ importers:
1173 version: link:../../packages/providers/vercel
1174 '@modelcontextprotocol/sdk':
1175 specifier: 'catalog:'
1173 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
1176 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
1177 ai:
1178 specifier: 'catalog:'
1179 version: 7.0.101(zod@4.5.4)
@@ -1247,7 +1250,7 @@ importers:
1250 version: 4.0.0-rc.115(effect@4.0.0-rc.115)
1251 '@modelcontextprotocol/sdk':
1252 specifier: 'catalog:'
1250 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
1253 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
1254 '@zed-industries/claude-code-acp':
1255 specifier: ^0.16.2
1256 version: 0.16.2(@cfworker/json-schema@4.1.1)(zod@4.5.4)
@@ -1350,7 +1353,7 @@ importers:
1353 version: link:../core
1354 '@modelcontextprotocol/sdk':
1355 specifier: 'catalog:'
1353 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
1356 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
1357 extract-zip:
1358 specifier: ^2.0.1
1359 version: 2.0.1(supports-color@10.2.2)
@@ -1407,12 +1410,18 @@ importers:
1410 specifier: 'catalog:'
1411 version: 3.25.2(zod@4.5.4)
1412 devDependencies:
1413 + '@hono/node-server':
1414 + specifier: ^2.1.1
1415 + version: 2.1.1(hono@4.13.7)
1416 '@type-challenges/utils':
1417 specifier: ^0.1.1
1418 version: 0.1.1
1419 '@types/semver':
1420 specifier: ^7.8.0
1421 version: 7.8.0
1422 + hono:
1423 + specifier: 'catalog:'
1424 + version: 4.13.7
1425 tsdown:
1426 specifier: 'catalog:'
1427 version: 0.23.0(@arethetypeswrong/core@0.18.5)(@typescript/typescript6@6.0.2)(publint@0.3.24)(tsx@4.23.13)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3))
@@ -1563,7 +1572,7 @@ importers:
1572 version: link:../../core
1573 '@modelcontextprotocol/sdk':
1574 specifier: 'catalog:'
1566 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
1575 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
1576 tsdown:
1577 specifier: 'catalog:'
1578 version: 0.23.0(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.13)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3))
@@ -6756,7 +6765,7 @@ snapshots:
6765 '@standard-schema/spec': 1.1.0
6766 '@workflow/serde': 4.1.0
6767 eventsource-parser: 3.1.1
6759 - undici: 7.29.0
6768 + undici: 7.29.1
6769 zod: 3.25.76
6770
6771 '@ai-sdk/provider-utils@5.0.40(zod@4.5.4)':
@@ -6765,7 +6774,7 @@ snapshots:
6774 '@standard-schema/spec': 1.1.0
6775 '@workflow/serde': 4.1.0
6776 eventsource-parser: 3.1.1
6768 - undici: 7.29.0
6777 + undici: 7.29.1
6778 zod: 4.5.4
6779
6780 '@ai-sdk/provider@1.1.3':
@@ -6848,7 +6857,7 @@ snapshots:
6857 '@anthropic-ai/claude-agent-sdk@0.3.272(@anthropic-ai/sdk@0.125.0(zod@4.5.4))(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4))(zod@4.5.4)':
6858 dependencies:
6859 '@anthropic-ai/sdk': 0.125.0(zod@4.5.4)
6851 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
6860 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
6861 zod: 4.5.4
6862 optionalDependencies:
6863 '@anthropic-ai/claude-agent-sdk-darwin-arm64': 0.3.272
@@ -7547,7 +7556,7 @@ snapshots:
7556 protobufjs: 7.6.5
7557 ws: 8.21.3
7558 optionalDependencies:
7550 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
7559 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
7560 transitivePeerDependencies:
7561 - bufferutil
7562 - supports-color
@@ -7560,7 +7569,7 @@ snapshots:
7569 protobufjs: 7.6.5
7570 ws: 8.21.3
7571 optionalDependencies:
7563 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
7572 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
7573 transitivePeerDependencies:
7574 - bufferutil
7575 - supports-color
@@ -7823,7 +7832,7 @@ snapshots:
7832 dependencies:
7833 '@langchain/core': 1.2.11(@opentelemetry/api@1.9.1)(openai@7.15.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(undici@6.28.0)(ws@8.21.3)(zod@4.5.4))(ws@8.21.3)
7834 '@langchain/langgraph': 1.4.15(@langchain/core@1.2.11(@opentelemetry/api@1.9.1)(openai@7.15.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(undici@6.28.0)(ws@8.21.3)(zod@4.5.4))(ws@8.21.3))(zod@4.5.4)
7826 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
7835 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
7836 debug: 4.4.3(supports-color@10.2.2)
7837 zod: 4.5.4
7838 optionalDependencies:
@@ -7900,7 +7909,7 @@ snapshots:
7909
7910 '@llamaindex/workflow-core@1.3.4(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4))(hono@4.13.7)(zod@4.5.4)':
7911 optionalDependencies:
7903 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
7912 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
7913 hono: 4.13.7
7914 zod: 4.5.4
7915
@@ -8058,7 +8067,7 @@ snapshots:
8067 '@isaacs/ttlcache': 2.1.5
8068 '@lukeed/uuid': 2.0.1
8069 '@mastra/schema-compat': 1.3.4(zod@4.5.4)
8061 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
8070 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
8071 '@sindresorhus/slugify': 2.2.1
8072 '@standard-schema/spec': 1.1.0
8073 ajv: 8.20.0
@@ -8119,7 +8128,7 @@ snapshots:
8128 '@modelcontextprotocol/core': 2.0.0
8129 '@modelcontextprotocol/ext-apps': 1.7.5(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4))(zod@4.5.4)
8130 '@modelcontextprotocol/node': 2.0.0(@modelcontextprotocol/server@2.0.0)(hono@4.13.7)
8122 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
8131 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
8132 '@modelcontextprotocol/server': 2.0.0
8133 '@modelcontextprotocol/server-legacy': 2.0.0(express@5.2.1)
8134 exit-hook: 5.1.0
@@ -8177,7 +8186,7 @@ snapshots:
8186
8187 '@modelcontextprotocol/ext-apps@1.7.5(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4))(zod@4.5.4)':
8188 dependencies:
8180 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
8189 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)
8190 '@standard-schema/spec': 1.1.0
8191 zod: 4.5.4
8192
@@ -8199,7 +8208,7 @@ snapshots:
8208 eventsource: 3.0.7
8209 eventsource-parser: 3.1.1
8210 express: 5.2.1
8202 - express-rate-limit: 8.6.2(express@5.2.1)
8211 + express-rate-limit: 8.6.2(express@5.2.1)(supports-color@10.2.2)
8212 hono: 4.13.7
8213 jose: 6.2.9
8214 json-schema-typed: 8.0.2
@@ -8212,7 +8221,7 @@ snapshots:
8221 transitivePeerDependencies:
8222 - supports-color
8223
8215 - '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)':
8224 + '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.5.4)':
8225 dependencies:
8226 '@hono/node-server': 2.1.1(hono@4.13.7)
8227 ajv: 8.20.0
@@ -8223,20 +8232,20 @@ snapshots:
8232 eventsource: 3.0.7
8233 eventsource-parser: 3.1.1
8234 express: 5.2.1
8226 - express-rate-limit: 8.6.2(express@5.2.1)
8235 + express-rate-limit: 8.6.2(express@5.2.1)(supports-color@10.2.2)
8236 hono: 4.13.7
8237 jose: 6.2.9
8238 json-schema-typed: 8.0.2
8239 pkce-challenge: 5.0.1
8240 raw-body: 3.0.2
8232 - zod: 3.25.76
8233 - zod-to-json-schema: 3.25.2(zod@3.25.76)
8241 + zod: 4.5.4
8242 + zod-to-json-schema: 3.25.2(zod@4.5.4)
8243 optionalDependencies:
8244 '@cfworker/json-schema': 4.1.1
8245 transitivePeerDependencies:
8246 - supports-color
8247
8239 - '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)':
8248 + '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)':
8249 dependencies:
8250 '@hono/node-server': 2.1.1(hono@4.13.7)
8251 ajv: 8.20.0
@@ -8247,14 +8256,14 @@ snapshots:
8256 eventsource: 3.0.7
8257 eventsource-parser: 3.1.1
8258 express: 5.2.1
8250 - express-rate-limit: 8.6.2(express@5.2.1)
8259 + express-rate-limit: 8.6.2(express@5.2.1)(supports-color@10.2.2)
8260 hono: 4.13.7
8261 jose: 6.2.9
8262 json-schema-typed: 8.0.2
8263 pkce-challenge: 5.0.1
8264 raw-body: 3.0.2
8256 - zod: 4.5.4
8257 - zod-to-json-schema: 3.25.2(zod@4.5.4)
8265 + zod: 3.25.76
8266 + zod-to-json-schema: 3.25.2(zod@3.25.76)
8267 optionalDependencies:
8268 '@cfworker/json-schema': 4.1.1
8269 transitivePeerDependencies:
@@ -8265,7 +8274,7 @@ snapshots:
8274 '@modelcontextprotocol/core': 2.0.0
8275 content-type: 1.0.5
8276 cors: 2.8.6
8268 - express-rate-limit: 8.6.2(express@5.2.1)
8277 + express-rate-limit: 8.6.2(express@5.2.1)(supports-color@10.2.2)
8278 pkce-challenge: 5.0.1
8279 raw-body: 3.0.2
8280 zod: 4.5.4
@@ -9556,7 +9565,7 @@ snapshots:
9565
9566 expect-type@1.4.0: {}
9567
9559 - express-rate-limit@8.6.2(express@5.2.1):
9568 + express-rate-limit@8.6.2(express@5.2.1)(supports-color@10.2.2):
9569 dependencies:
9570 debug: 4.4.3(supports-color@10.2.2)
9571 express: 5.2.1
ts/examples/session-management/README.md
+16
@@ -33,6 +33,22 @@ pnpm dev
33 - Fetches available tools
34 - Demonstrates basic usage patterns
35
36 +## Verifying saved Session configs
37 +
38 +`src/session-configs.ts` checks saved Session configs against a real project. It creates sessions, prints `PASS` or `FAIL` for each check, deletes the sessions it created, and exits non-zero on any failure. It never runs as part of `pnpm start`.
39 +
40 +```bash
41 +COMPOSIO_API_KEY=... \
42 +SESSION_CONFIG_ID=sc_... \
43 +ARCHIVED_SESSION_CONFIG_ID=sc_... \
44 +COMPOSIO_API_KEY_NO_FEATURE=... \
45 +pnpm start:session-configs
46 +```
47 +
48 +`COMPOSIO_API_KEY` must belong to a project with Session configs enabled, with one active and one archived config. `COMPOSIO_API_KEY_NO_FEATURE` is optional and belongs to a project without the feature, for the `403` check. The script also records whether `sessionPreset: SessionPreset.DIRECT_TOOLS` works with a saved config.
49 +
50 +The checks follow every page of active and archived configs. Cleanup attempts every created Session and fails the run if any deletion fails. Run `pnpm test` to verify pagination and cleanup without an API key.
51 +
52 ## Customization
53
54 Edit `src/index.ts` to:
ts/examples/session-management/package.json
+3 -1
@@ -8,8 +8,9 @@
8 "clean": "git clean -xdf node_modules",
9 "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 + "start:session-configs": "bun src/session-configs.ts",
12 "dev": "bun --watch src/index.ts",
12 - "test": "echo \"Error: no test specified\" && exit 1"
13 + "test": "bun test test/"
14 },
15 "keywords": [
16 "composio",
@@ -19,6 +20,7 @@
20 "author": "",
21 "license": "ISC",
22 "dependencies": {
23 + "@composio/client": "catalog:",
24 "@composio/core": "workspace:*",
25 "dotenv": "catalog:"
26 },
ts/examples/session-management/src/session-config-verification.ts new
+39
@@ -0,0 +1,39 @@
1 +import type { SessionConfigs, SessionConfigListParams, SessionConfigSummary } from '@composio/core';
2 +
3 +export async function listAllSessionConfigs(
4 + sessionConfigs: Pick<SessionConfigs, 'list'>,
5 + params: Pick<SessionConfigListParams, 'archived'> = {}
6 +): Promise<SessionConfigSummary[]> {
7 + const items: SessionConfigSummary[] = [];
8 + const seenCursors = new Set<string>();
9 + let cursor: string | undefined;
10 + do {
11 + const page = await sessionConfigs.list({ ...params, limit: 100, cursor });
12 + items.push(...page.items);
13 + cursor = page.nextCursor ?? undefined;
14 + if (cursor !== undefined) {
15 + if (seenCursors.has(cursor))
16 + throw new Error(`Session config pagination repeated cursor: ${cursor}`);
17 + seenCursors.add(cursor);
18 + }
19 + } while (cursor !== undefined);
20 + return items;
21 +}
22 +
23 +export async function cleanupVerificationSessions(
24 + sessionIds: string[],
25 + deleteSession: (id: string) => Promise<{ deleted: boolean }>
26 +): Promise<void> {
27 + const failures: Error[] = [];
28 + for (const id of sessionIds) {
29 + try {
30 + const result = await deleteSession(id);
31 + if (!result.deleted) throw new Error('API did not confirm deletion');
32 + } catch (cause) {
33 + failures.push(new Error(`Could not delete session ${id}`, { cause }));
34 + }
35 + }
36 + if (failures.length > 0) {
37 + throw new AggregateError(failures, failures.map(error => error.message).join('; '));
38 + }
39 +}
ts/examples/session-management/src/session-configs.ts new
+228
@@ -0,0 +1,228 @@
1 +/**
2 + * Manual verification for saved Session configs.
3 + *
4 + * Runs each check against a real project and prints PASS or FAIL. Any failure
5 + * sets a non-zero exit code. Sessions created here are deleted at the end.
6 + *
7 + * Required environment:
8 + * - COMPOSIO_API_KEY: a project with Session configs enabled
9 + * - SESSION_CONFIG_ID: an active `sc_…` config in that project
10 + * - ARCHIVED_SESSION_CONFIG_ID: an archived `sc_…` config in that project
11 + *
12 + * Optional:
13 + * - COMPOSIO_API_KEY_NO_FEATURE: a project without Session configs (403 check)
14 + *
15 + * Run: pnpm start:session-configs
16 + */
17 +import { APIError } from '@composio/client';
18 +import {
19 + Composio,
20 + SessionPreset,
21 + type SessionConfigPolicy,
22 + type ToolRouterCreateSessionConfig,
23 +} from '@composio/core';
24 +import 'dotenv/config';
25 +import { cleanupVerificationSessions, listAllSessionConfigs } from './session-config-verification';
26 +
27 +const required = ['COMPOSIO_API_KEY', 'SESSION_CONFIG_ID', 'ARCHIVED_SESSION_CONFIG_ID'] as const;
28 +const missing = required.filter(name => !process.env[name]);
29 +if (missing.length > 0) {
30 + console.error(`Missing required environment variables: ${missing.join(', ')}`);
31 + process.exit(1);
32 +}
33 +
34 +const sessionConfigId = process.env.SESSION_CONFIG_ID!;
35 +const archivedSessionConfigId = process.env.ARCHIVED_SESSION_CONFIG_ID!;
36 +const noFeatureApiKey = process.env.COMPOSIO_API_KEY_NO_FEATURE;
37 +const userId = `session-configs-check-${Date.now()}`;
38 +
39 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
40 +const createdSessionIds: string[] = [];
41 +let failures = 0;
42 +
43 +async function createTrackedSession(config: ToolRouterCreateSessionConfig) {
44 + const session = await composio.sessions.create(userId, config);
45 + createdSessionIds.push(session.sessionId);
46 + return session;
47 +}
48 +
49 +async function check(label: string, run: () => Promise<void>): Promise<void> {
50 + try {
51 + await run();
52 + console.log(`PASS ${label}`);
53 + } catch (error) {
54 + failures += 1;
55 + console.log(`FAIL ${label}\n ${error instanceof Error ? error.message : String(error)}`);
56 + }
57 +}
58 +
59 +function assert(condition: unknown, message: string): asserts condition {
60 + if (!condition) {
61 + throw new Error(message);
62 + }
63 +}
64 +
65 +/** HTTP status of a client error, or undefined for anything else. */
66 +function statusOf(error: unknown): number | undefined {
67 + return error instanceof APIError ? error.status : undefined;
68 +}
69 +
70 +async function expectStatus(status: number, run: () => Promise<unknown>): Promise<void> {
71 + let result: unknown;
72 + try {
73 + result = await run();
74 + } catch (error) {
75 + assert(statusOf(error) === status, `expected ${status}, got ${statusOf(error) ?? error}`);
76 + return;
77 + }
78 + throw new Error(`expected ${status}, but the call succeeded with ${JSON.stringify(result)}`);
79 +}
80 +
81 +/** The saved policy uses enable/disable; the session snapshot uses enabled/disabled. */
82 +function toolkitsAsSnapshot(policy: SessionConfigPolicy): unknown {
83 + if (!policy.toolkits) return undefined;
84 + return 'enable' in policy.toolkits
85 + ? { enabled: policy.toolkits.enable }
86 + : { disabled: policy.toolkits.disable };
87 +}
88 +
89 +function sameToolkits(actual: unknown, expected: unknown): boolean {
90 + return JSON.stringify(actual) === JSON.stringify(expected);
91 +}
92 +
93 +async function main(): Promise<void> {
94 + let policy: SessionConfigPolicy | undefined;
95 +
96 + await check('list() returns the active config', async () => {
97 + const items = await listAllSessionConfigs(composio.sessionConfigs);
98 + assert(
99 + items.some(item => item.id === sessionConfigId),
100 + `${sessionConfigId} missing from active configs`
101 + );
102 + });
103 +
104 + await check('list({ archived: true }) returns only archived configs', async () => {
105 + const items = await listAllSessionConfigs(composio.sessionConfigs, { archived: true });
106 + assert(
107 + items.some(item => item.id === archivedSessionConfigId),
108 + `${archivedSessionConfigId} missing`
109 + );
110 + assert(!items.some(item => item.id === sessionConfigId), `${sessionConfigId} is listed`);
111 + assert(
112 + items.every(item => item.archived),
113 + 'a non-archived config is listed'
114 + );
115 + });
116 +
117 + await check('get() returns the policy', async () => {
118 + const sessionConfig = await composio.sessionConfigs.get(sessionConfigId);
119 + assert(sessionConfig.id === sessionConfigId, `got ${sessionConfig.id}`);
120 + policy = sessionConfig.config;
121 + console.log(` policy: ${JSON.stringify(policy)}`);
122 + });
123 +
124 + await check('create() from the config sets sourceSessionConfig and its access', async () => {
125 + const session = await createTrackedSession({
126 + experimental: { sessionConfigId },
127 + });
128 + assert(
129 + session.experimental.sourceSessionConfig?.id === sessionConfigId,
130 + `sourceSessionConfig is ${JSON.stringify(session.experimental.sourceSessionConfig)}`
131 + );
132 + assert(policy, 'policy was not read');
133 + assert(
134 + sameToolkits(session.config.toolkits, toolkitsAsSnapshot(policy)),
135 + `session toolkits ${JSON.stringify(session.config.toolkits)} do not match the policy`
136 + );
137 + const tools = await session.tools();
138 + console.log(` tools(): ${tools.length} tools`);
139 + });
140 +
141 + let narrowedSessionId: string | undefined;
142 + await check('update() applies the config to a broad inline session', async () => {
143 + const session = await createTrackedSession({
144 + toolkits: ['github', 'gmail', 'slack', 'googlecalendar'],
145 + });
146 + await session.update({ experimental: { sessionConfigId } });
147 + narrowedSessionId = session.sessionId;
148 + assert(
149 + session.experimental.sourceSessionConfig?.id === sessionConfigId,
150 + `sourceSessionConfig is ${JSON.stringify(session.experimental.sourceSessionConfig)}`
151 + );
152 + assert(policy, 'policy was not read');
153 + assert(
154 + sameToolkits(session.config.toolkits, toolkitsAsSnapshot(policy)),
155 + `session toolkits ${JSON.stringify(session.config.toolkits)} do not match the policy`
156 + );
157 + });
158 +
159 + await check('create() with an archived config fails with 404', () =>
160 + expectStatus(404, () =>
161 + createTrackedSession({
162 + experimental: { sessionConfigId: archivedSessionConfigId },
163 + })
164 + )
165 + );
166 +
167 + await check('create() with a missing config fails with 404', () =>
168 + expectStatus(404, () =>
169 + createTrackedSession({
170 + experimental: { sessionConfigId: 'sc_doesnotexist' },
171 + })
172 + )
173 + );
174 +
175 + await check('update() with an archived config fails with 404 and changes nothing', async () => {
176 + assert(narrowedSessionId, 'the narrowed session was not created');
177 + const before = await composio.sessions.use(narrowedSessionId);
178 + await expectStatus(404, () =>
179 + before.update({ experimental: { sessionConfigId: archivedSessionConfigId } })
180 + );
181 + const after = await composio.sessions.use(narrowedSessionId);
182 + assert(
183 + JSON.stringify(after.config) === JSON.stringify(before.config),
184 + 'config changed after a failed update'
185 + );
186 + assert(
187 + after.experimental.sourceSessionConfig?.id === before.experimental.sourceSessionConfig?.id,
188 + 'sourceSessionConfig changed after a failed update'
189 + );
190 + });
191 +
192 + if (noFeatureApiKey) {
193 + await check('list() without the feature fails with 403', () =>
194 + expectStatus(403, () => new Composio({ apiKey: noFeatureApiKey }).sessionConfigs.list())
195 + );
196 + } else {
197 + console.log('SKIP list() without the feature (COMPOSIO_API_KEY_NO_FEATURE not set)');
198 + }
199 +
200 + // Informational: records whether the direct tools preset works with a saved
201 + // config. The SDK surfaces a backend rejection unchanged either way.
202 + try {
203 + await createTrackedSession({
204 + sessionPreset: SessionPreset.DIRECT_TOOLS,
205 + experimental: { sessionConfigId },
206 + });
207 + console.log('INFO DIRECT_TOOLS with a saved config: accepted');
208 + } catch (error) {
209 + console.log(
210 + `INFO DIRECT_TOOLS with a saved config: rejected with ${statusOf(error) ?? 'no status'}: ${
211 + error instanceof Error ? error.message : String(error)
212 + }`
213 + );
214 + }
215 +}
216 +
217 +main()
218 + .catch(error => {
219 + failures += 1;
220 + console.error(error);
221 + })
222 + .finally(async () => {
223 + await check('delete all created Sessions', () =>
224 + cleanupVerificationSessions(createdSessionIds, id => composio.sessions.delete(id))
225 + );
226 + console.log(failures === 0 ? '\nAll checks passed' : `\n${failures} check(s) failed`);
227 + process.exitCode = failures === 0 ? 0 : 1;
228 + });
ts/examples/session-management/test/session-config-verification.test.ts new
+67
@@ -0,0 +1,67 @@
1 +import { describe, expect, test } from 'bun:test';
2 +import {
3 + cleanupVerificationSessions,
4 + listAllSessionConfigs,
5 +} from '../src/session-config-verification';
6 +
7 +describe('Session config verification', () => {
8 + test.each([false, true])('reads every page with archived=%s', async archived => {
9 + const cursors: (string | undefined)[] = [];
10 + const items = await listAllSessionConfigs(
11 + {
12 + async list(params) {
13 + expect(params?.archived).toBe(archived);
14 + cursors.push(params?.cursor);
15 + return {
16 + items: [
17 + {
18 + id: params?.cursor === undefined ? 'sc_first' : 'sc_target',
19 + name: 'Verification config',
20 + archived,
21 + createdAt: '2026-09-01T00:00:00Z',
22 + updatedAt: '2026-09-01T00:00:00Z',
23 + },
24 + ],
25 + nextCursor: params?.cursor === undefined ? 'page_2' : null,
26 + };
27 + },
28 + },
29 + { archived }
30 + );
31 +
32 + expect(items.map(item => item.id)).toEqual(['sc_first', 'sc_target']);
33 + expect(cursors).toEqual([undefined, 'page_2']);
34 + });
35 +
36 + test('stops a repeated cursor instead of hanging', async () => {
37 + await expect(
38 + listAllSessionConfigs({
39 + list: async () => ({ items: [], nextCursor: 'same_page' }),
40 + })
41 + ).rejects.toThrow('pagination repeated cursor');
42 + });
43 +
44 + test('surfaces cleanup errors and still tries the remaining Sessions', async () => {
45 + const attempted: string[] = [];
46 + await expect(
47 + cleanupVerificationSessions(['trs_failed', 'trs_ok'], async id => {
48 + attempted.push(id);
49 + if (id === 'trs_failed') throw new Error('Deletion failed');
50 + return { deleted: true };
51 + })
52 + ).rejects.toThrow('Could not delete session trs_failed');
53 + expect(attempted).toEqual(['trs_failed', 'trs_ok']);
54 + });
55 +
56 + test('treats an unconfirmed deletion as a cleanup failure', async () => {
57 + await expect(
58 + cleanupVerificationSessions(['trs_failed'], async () => ({ deleted: false }))
59 + ).rejects.toThrow('Could not delete session trs_failed');
60 + });
61 +
62 + test('succeeds when every Session is deleted', async () => {
63 + await expect(
64 + cleanupVerificationSessions(['trs_ok'], async () => ({ deleted: true }))
65 + ).resolves.toBeUndefined();
66 + });
67 +});
ts/packages/core/package.json
+2
@@ -119,8 +119,10 @@
119 ],
120 "license": "ISC",
121 "devDependencies": {
122 + "@hono/node-server": "^2.1.1",
123 "@type-challenges/utils": "^0.1.1",
124 "@types/semver": "^7.8.0",
125 + "hono": "catalog:",
126 "tsdown": "catalog:",
127 "tsx": "catalog:",
128 "typedoc": "^0.28.20",
ts/packages/core/src/composio.ts
+8
@@ -10,6 +10,7 @@ import { Experimental } from './models/Experimental';
10 import { MCP } from './models/MCP';
11 import { Webhooks } from './models/Webhooks';
12 import { Logs } from './models/Logs';
13 +import { SessionConfigs } from './models/SessionConfigs';
14 import { Keyring } from './models/Keyring';
15 import { telemetry } from './telemetry/Telemetry';
16 import {
@@ -362,6 +363,12 @@ export class Composio<
363 * `composio.create(...)` method is kept as an alias.
364 */
365 sessions: Sessions<unknown, unknown, TProvider>;
366 + /**
367 + * Read the project's saved Session configs. Apply one with
368 + * `experimental.sessionConfigId` on `sessions.create()` or `session.update()`.
369 + * Requires Session configs to be enabled for the project.
370 + */
371 + sessionConfigs: SessionConfigs;
372 /**
373 * Legacy alias for `composio.sessions`.
374 * @deprecated Use `composio.sessions` instead — `toolRouter` was renamed to `sessions` and is kept only for backwards compatibility. Prefer `composio.sessions`; do not generate new code against `composio.toolRouter`.
@@ -549,6 +556,7 @@ export class Composio<
556 this.experimental = new Experimental(this.client);
557 this.sessions = new Sessions(this.client, this.config);
558 this.toolRouter = this.sessions;
559 + this.sessionConfigs = new SessionConfigs(this.client);
560
561 /**
562 * Initialize session aliases.
ts/packages/core/src/errors/ToolRouterErrors.ts
+4
@@ -37,6 +37,10 @@ export class ComposioMCPDestinationError extends ComposioError {
37 * local session object is left as it was before the call. Re-fetch the session
38 * with `sessions.use(sessionId)` and retry the update against the fresh
39 * `configVersion`.
40 + *
41 + * Applying a saved Session config with `experimental.sessionConfigId` can
42 + * also conflict when the session or the config changes while the update is
43 + * applied; `meta.sessionConfigId` then names the config.
44 */
45 export class ComposioSessionConfigConflictError extends ComposioError {
46 constructor(
ts/packages/core/src/index.ts
+2
@@ -54,6 +54,7 @@ export { RemoteFile } from './models/RemoteFile';
54 export { createConnectionRequest } from './models/ConnectionRequest';
55 export { ToolRouterSession } from './models/ToolRouterSession';
56 export { Sessions } from './models/Sessions';
57 +export { SessionConfigs } from './models/SessionConfigs';
58 export * from './types/provider.types';
59 export * from './types/customTool.types';
60 export * from './types/tool.types';
@@ -73,6 +74,7 @@ export * from './types/mcp.types';
74 export * from './types/files.types';
75 export * from './types/connectionRequest.types';
76 export * from './types/toolRouter.types';
77 +export * from './types/sessionConfigs.types';
78 export * from './types/ToolRouterSessionFilesMount.types';
79 export * from './types/requestOptions.types';
80 export * as constants from './utils/constants';
ts/packages/core/src/lib/sessionConfigConflict.ts new
+43
@@ -0,0 +1,43 @@
1 +import { z } from 'zod/v3';
2 +import { ValidationError } from '../errors/ValidationErrors';
3 +
4 +const SESSION_CONFIG_CONFLICT_MARKER = 'sessionConfigConflict';
5 +
6 +/**
7 + * Adds the issue raised when a saved Session config (`experimental.sessionConfigId`)
8 + * is combined with inline access fields. `fields` lists every conflicting
9 + * field that was provided; nothing is added when it is empty.
10 + */
11 +export const addSessionConfigConflictIssue = (ctx: z.RefinementCtx, fields: string[]): void => {
12 + if (fields.length === 0) {
13 + return;
14 + }
15 + ctx.addIssue({
16 + code: z.ZodIssueCode.custom,
17 + message: `experimental.sessionConfigId cannot be combined with ${fields.join(', ')}. A saved Session config sets the session's toolkit, tool and tag access; remove ${fields.length === 1 ? 'that field' : 'those fields'} or sessionConfigId`,
18 + path: ['experimental', 'sessionConfigId'],
19 + params: { [SESSION_CONFIG_CONFLICT_MARKER]: true },
20 + });
21 +};
22 +
23 +/**
24 + * Parses session create or update input. A saved Session config combined with
25 + * inline access fields throws `ValidationError`; any other failure rethrows the
26 + * original `ZodError`, as `schema.parse()` would.
27 + */
28 +export const parseSessionConfigInput = <TSchema extends z.ZodTypeAny>(
29 + schema: TSchema,
30 + input: unknown
31 +): z.output<TSchema> => {
32 + const result = schema.safeParse(input);
33 + if (result.success) {
34 + return result.data;
35 + }
36 + const isConflict = result.error.issues.some(
37 + issue => issue.code === z.ZodIssueCode.custom && issue.params?.[SESSION_CONFIG_CONFLICT_MARKER]
38 + );
39 + if (isConflict) {
40 + throw new ValidationError('Invalid session config', { cause: result.error });
41 + }
42 + throw result.error;
43 +};
ts/packages/core/src/lib/toolRouterParams.ts
+15 -9
@@ -8,11 +8,11 @@ import {
8 ToolRouterConfigToolsSchema,
9 ToolRouterToolsParam,
10 ToolRouterConfigManageConnectionsSchema,
11 - ToolRouterCreateSessionConfig,
11 + ToolRouterCreateSessionConfigSchema,
12 ToolRouterToolkitsParamSchema,
13 ToolRouterToolkitsDisabledConfigSchema,
14 ToolRouterToolkitsEnabledConfigSchema,
15 - ToolRouterUpdateSessionConfig,
15 + ToolRouterUpdateSessionConfigSchema,
16 ToolRouterUpdateManageConnectionsConfig,
17 ToolRouterUpdateManageConnectionsSchema,
18 ToolRouterUpdateExperimentalConfig,
@@ -21,6 +21,12 @@ import {
21 } from '../types/toolRouter.types';
22 import { ValidationError } from '../errors';
23 import { z } from 'zod';
24 +import type { TypeOf } from 'zod/v3';
25 +
26 +/** Parsed create input; the public `ToolRouterCreateSessionConfig` is a union over it. */
27 +type ParsedCreateSessionConfig = TypeOf<typeof ToolRouterCreateSessionConfigSchema>;
28 +/** Parsed update input; the public `ToolRouterUpdateSessionConfig` is a union over it. */
29 +type ParsedUpdateSessionConfig = TypeOf<typeof ToolRouterUpdateSessionConfigSchema>;
30
31 export const transformToolRouterToolsParams = (
32 params?: Record<string, ToolRouterToolsParam | ToolRouterConfigTools> | undefined
@@ -121,8 +127,8 @@ export const transformToolRouterManageConnectionsParams = (
127 };
128
129 export const resolveToolRouterSandboxConfig = (
124 - config: Pick<ToolRouterCreateSessionConfig, 'sandbox' | 'workbench'>
125 -): ToolRouterCreateSessionConfig['sandbox'] | ToolRouterCreateSessionConfig['workbench'] => {
130 + config: Pick<ParsedCreateSessionConfig, 'sandbox' | 'workbench'>
131 +): ParsedCreateSessionConfig['sandbox'] | ParsedCreateSessionConfig['workbench'] => {
132 if (config.sandbox !== undefined && config.workbench !== undefined) {
133 throw new ValidationError(
134 'Pass either sandbox or workbench, not both. workbench is a backwards-compatible alias for sandbox.'
@@ -132,7 +138,7 @@ export const resolveToolRouterSandboxConfig = (
138 };
139
140 export const transformToolRouterSandboxParams = (
135 - params?: ToolRouterCreateSessionConfig['sandbox'] | ToolRouterCreateSessionConfig['workbench']
141 + params?: ParsedCreateSessionConfig['sandbox'] | ParsedCreateSessionConfig['workbench']
142 ): SessionCreateParams.Workbench | undefined => {
143 if (!params) {
144 return undefined;
@@ -292,7 +298,7 @@ export const transformToolRouterUpdateSandboxParams = (
298 export const transformToolRouterUpdateWorkbenchParams = transformToolRouterUpdateSandboxParams;
299
300 export const transformToolRouterMultiAccountParams = (
295 - params?: ToolRouterCreateSessionConfig['multiAccount']
301 + params?: ParsedCreateSessionConfig['multiAccount']
302 ): SessionCreateParams.MultiAccount | undefined => {
303 if (!params) {
304 return undefined;
@@ -317,7 +323,7 @@ export const transformToolRouterMultiAccountParams = (
323 };
324
325 export const transformToolRouterToolkitsParams = (
320 - params?: ToolRouterCreateSessionConfig['toolkits']
326 + params?: ParsedCreateSessionConfig['toolkits']
327 ): SessionCreateParams.Enable | SessionCreateParams.Disable | undefined => {
328 if (!params) {
329 return undefined;
@@ -337,10 +343,10 @@ export const transformToolRouterToolkitsParams = (
343 * including `null` (remove the stored override) and empty collections (an
344 * empty toolkit allowlist denies every app toolkit). The
345 * `expectedConfigVersion` option is not a body field here: the session
340 - * resolves the precondition against its observed `configVersion`.
346 + * adds it only when the caller explicitly supplies a numeric version.
347 */
348 export const transformToolRouterUpdateParams = (
343 - config: ToolRouterUpdateSessionConfig
349 + config: ParsedUpdateSessionConfig
350 ): SessionPatchBody => {
351 const params: SessionPatchBody = {};
352
ts/packages/core/src/lib/toolRouterSourceSessionConfig.ts new
+12
@@ -0,0 +1,12 @@
1 +import type { SessionExperimental } from '../types/toolRouter.types';
2 +
3 +/**
4 + * Reads the saved Session config most recently applied to a session from a
5 + * create, retrieve, attach or patch response. Copies only `id`.
6 + */
7 +export const getSourceSessionConfig = (response: {
8 + experimental?: { source_session_config?: { id: string } };
9 +}): SessionExperimental['sourceSessionConfig'] => {
10 + const source = response.experimental?.source_session_config;
11 + return source ? { id: source.id } : undefined;
12 +};
ts/packages/core/src/models/SessionConfigs.ts new
+117
@@ -0,0 +1,117 @@
1 +/**
2 + * @fileoverview The `composio.sessionConfigs` namespace: read the saved
3 + * Session configs of the project.
4 + *
5 + * @module SessionConfigs
6 + */
7 +import ComposioClient from '@composio/client';
8 +import {
9 + SessionConfig,
10 + SessionConfigListParams,
11 + SessionConfigListParamsSchema,
12 + SessionConfigListResponse,
13 +} from '../types/sessionConfigs.types';
14 +import { ComposioRequestOptions } from '../types/requestOptions.types';
15 +import { ValidationError } from '../errors/ValidationErrors';
16 +import { telemetry } from '../telemetry/Telemetry';
17 +import { withCancellation } from '../utils/cancellation';
18 +import {
19 + transformSessionConfig,
20 + transformSessionConfigListResponse,
21 +} from '../utils/transformers/sessionConfigs';
22 +
23 +/**
24 + * `composio.sessionConfigs` — saved, reusable Session configs.
25 + *
26 + * A Session config is a named access policy (`sc_…`) built in the Composio
27 + * Dashboard under Sessions → Configs. Pass its id as
28 + * `experimental.sessionConfigId` to `composio.sessions.create()` or
29 + * `session.update()` to apply it.
30 + *
31 + * These endpoints require Session configs to be enabled for the project;
32 + * otherwise the backend returns 403.
33 + *
34 + * @example
35 + * ```typescript
36 + * const { items } = await composio.sessionConfigs.list({ search: 'support' });
37 + * const sessionConfig = await composio.sessionConfigs.get(items[0].id);
38 + * const session = await composio.sessions.create('user_123', {
39 + * experimental: { sessionConfigId: sessionConfig.id },
40 + * });
41 + * ```
42 + */
43 +export class SessionConfigs {
44 + private client: ComposioClient;
45 +
46 + constructor(client: ComposioClient) {
47 + this.client = client;
48 + telemetry.instrument(this, 'SessionConfigs');
49 + }
50 +
51 + /**
52 + * List the project's saved Session configs with cursor pagination.
53 + *
54 + * Omitting `archived` returns active configs; `archived: true` returns only
55 + * archived ones. The backend defaults `limit` to 20 and caps it at 100.
56 + *
57 + * Requires Session configs to be enabled for the project.
58 + *
59 + * @param {SessionConfigListParams} [params] - `search`, `archived`, `limit` and `cursor`
60 + * @returns {Promise<SessionConfigListResponse>} Config summaries and the next cursor
61 + * @throws {ValidationError} If the params fail validation
62 + *
63 + * @example
64 + * ```typescript
65 + * let cursor: string | undefined;
66 + * do {
67 + * const page = await composio.sessionConfigs.list({ cursor });
68 + * for (const item of page.items) console.log(item.id, item.name);
69 + * cursor = page.nextCursor ?? undefined;
70 + * } while (cursor);
71 + * ```
72 + */
73 + async list(
74 + params?: SessionConfigListParams,
75 + requestOptions?: ComposioRequestOptions
76 + ): Promise<SessionConfigListResponse> {
77 + const parsedParams = SessionConfigListParamsSchema.safeParse(params ?? {});
78 + if (!parsedParams.success) {
79 + throw new ValidationError('Failed to parse session config list params', {
80 + cause: parsedParams.error,
81 + });
82 + }
83 + const result = await withCancellation(
84 + () => this.client.sessionConfigs.list(parsedParams.data, requestOptions),
85 + requestOptions?.signal
86 + );
87 + return transformSessionConfigListResponse(result);
88 + }
89 +
90 + /**
91 + * Retrieve one saved Session config with its description and access
92 + * policy. A missing or cross-project id surfaces as the backend's 404.
93 + *
94 + * Requires Session configs to be enabled for the project.
95 + *
96 + * @param {string} id - The `sc_…` id of the Session config
97 + * @returns {Promise<SessionConfig>} The config and its policy
98 + * @throws {ValidationError} If `id` is empty
99 + *
100 + * @example
101 + * ```typescript
102 + * const sessionConfig = await composio.sessionConfigs.get('sc_abc123');
103 + * console.log(sessionConfig.config.toolkits);
104 + * ```
105 + */
106 + async get(id: string, requestOptions?: ComposioRequestOptions): Promise<SessionConfig> {
107 + // An empty id would request the collection path and return a list page.
108 + if (id.trim() === '') {
109 + throw new ValidationError('Session config id must be a non-empty string');
110 + }
111 + const result = await withCancellation(
112 + () => this.client.sessionConfigs.retrieve(id, requestOptions),
113 + requestOptions?.signal
114 + );
115 + return transformSessionConfig(result);
116 + }
117 +}
ts/packages/core/src/models/ToolRouter.ts
+15 -3
@@ -55,6 +55,8 @@ import {
55 } from '../lib/toolRouterParams';
56 import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
57 import { buildMCPServerConfig } from '../lib/toolRouterMcp';
58 +import { parseSessionConfigInput } from '../lib/sessionConfigConflict';
59 +import { getSourceSessionConfig } from '../lib/toolRouterSourceSessionConfig';
60 import { ToolRouterSession } from './ToolRouterSession';
61 import { ComposioRequestOptions } from '../types/requestOptions.types';
62 import { withCancellation } from '../utils/cancellation';
@@ -190,6 +192,12 @@ export class ToolRouter<
192 * customToolkits: [myToolkit],
193 * },
194 * });
195 + *
196 + * // Start from a saved Session config instead of inline access fields
197 + * const configured = await composio.sessions.create('user_123', {
198 + * authConfigs: { github: 'ac_123' },
199 + * experimental: { sessionConfigId: 'sc_123' },
200 + * });
201 * ```
202 */
203 // Overloads: passing `{ mcp: true }` surfaces `session.mcp` in the returned
@@ -210,7 +218,7 @@ export class ToolRouter<
218 config?: ToolRouterCreateSessionConfig,
219 requestOptions?: ComposioRequestOptions
220 ): Promise<Session<TToolCollection, TTool, TProvider>> {
213 - const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});
221 + const routerConfig = parseSessionConfigInput(ToolRouterCreateSessionConfigSchema, config ?? {});
222 const isDirectToolsPreset = routerConfig.sessionPreset === SessionPreset.DIRECT_TOOLS;
223
224 // Extract custom tools/toolkits from experimental config
@@ -227,6 +235,10 @@ export class ToolRouter<
235 // Build the typed experimental payload for the backend
236 const experimentalPayload: SessionCreateParams['experimental'] = {};
237
238 + if (routerConfig.experimental?.sessionConfigId !== undefined) {
239 + experimentalPayload.session_config_id = routerConfig.experimental.sessionConfigId;
240 + }
241 +
242 if (routerConfig.experimental?.assistivePrompt?.userTimezone) {
243 experimentalPayload.assistive_prompt_config = {
244 user_timezone: routerConfig.experimental.assistivePrompt.userTimezone,
@@ -306,7 +318,7 @@ export class ToolRouter<
318 this.config,
319 session.session_id,
320 this.createMCPServerConfig(session.mcp, routerConfig.mcp === true),
309 - { assistivePrompt },
321 + { assistivePrompt, sourceSessionConfig: getSourceSessionConfig(session) },
322 customToolsMap,
323 userId,
324 metadata
@@ -417,7 +429,7 @@ export class ToolRouter<
429 this.config,
430 session.session_id,
431 this.createMCPServerConfig(session.mcp, options?.mcp === true),
420 - undefined,
432 + { sourceSessionConfig: getSourceSessionConfig(session) },
433 customToolsMap,
434 userId,
435 metadata
ts/packages/core/src/models/ToolRouterSession.ts
+29 -8
@@ -86,6 +86,8 @@ import {
86 import { transformProxyParams } from './proxyParamsTransform';
87 import { inlineCustomToolsExperimental } from './inlineCustomToolsPayload';
88 import { transformToolRouterUpdateParams } from '../lib/toolRouterParams';
89 +import { parseSessionConfigInput } from '../lib/sessionConfigConflict';
90 +import { getSourceSessionConfig } from '../lib/toolRouterSourceSessionConfig';
91 import { deleteToolRouterSession } from '../lib/toolRouterSessionDelete';
92
93 const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';
@@ -129,9 +131,9 @@ export class ToolRouterSession<
131 public readonly mcp: ToolRouterMCPServerConfig;
132 public readonly experimental: SessionExperimental;
133 /**
132 - * Server-side session configuration (toolkit/tool allowlists, tags, preload,
133 - * sandbox, manage_connections) as returned by the API. Refreshed in place by
134 - * `update()`.
134 + * The session's current configuration (policy snapshot and runtime
135 + * settings). Refreshed in place by `update()`. For saved, reusable Session
136 + * configs, see `composio.sessionConfigs`.
137 */
138 public config: ToolRouterSessionConfig;
139 public preload: ToolRouterSessionPreloadConfig;
@@ -155,7 +157,7 @@ export class ToolRouterSession<
157 private readonly sdkConfig: ComposioConfig<TProvider> | undefined,
158 sessionId: string,
159 mcp: ToolRouterMCPServerConfig,
158 - experimentalOverrides?: Pick<SessionExperimental, 'assistivePrompt'>,
160 + experimentalOverrides?: Pick<SessionExperimental, 'assistivePrompt' | 'sourceSessionConfig'>,
161 private readonly customToolsMap?: CustomToolsMap,
162 private readonly userId?: string,
163 metadata?: ToolRouterSessionMetadata
@@ -175,6 +177,7 @@ export class ToolRouterSession<
177 this.experimental = {
178 assistivePrompt: experimentalOverrides?.assistivePrompt,
179 files: new ToolRouterSessionFilesMount(client, sessionId),
180 + sourceSessionConfig: experimentalOverrides?.sourceSessionConfig,
181 };
182 this.config = config;
183 this.preload = metadata?.preload ?? config.preload;
@@ -790,15 +793,22 @@ export class ToolRouterSession<
793 * unchanged: re-fetch the session with `sessions.use(sessionId)` and retry
794 * against the fresh `configVersion`.
795 *
793 - * `config`, `configVersion`, `preload`, `sandbox` and `warnings` are
794 - * refreshed in place only after a successful response, and the updated
795 - * `config` is returned.
796 + * `experimental.sessionConfigId` applies a saved Session config: it
797 + * replaces the session's toolkit, tool and tag access and cannot be combined
798 + * with `toolkits`, `tools` or `tags` (a `ValidationError` is thrown before
799 + * any request). A 409 while applying it means the session or the config
800 + * changed; re-fetch the session and retry. Backend 400, 403 and 404 errors,
801 + * for example for an archived or missing config, surface unchanged.
802 + *
803 + * `config`, `configVersion`, `preload`, `sandbox`, `warnings` and
804 + * `experimental.sourceSessionConfig` are refreshed in place only after a
805 + * successful response, and the updated `config` is returned.
806 */
807 async update(
808 config: ToolRouterUpdateSessionConfig,
809 requestOptions?: ComposioRequestOptions
810 ): Promise<ToolRouterSessionConfig> {
801 - const parsed = ToolRouterUpdateSessionConfigSchema.parse(config);
811 + const parsed = parseSessionConfigInput(ToolRouterUpdateSessionConfigSchema, config);
812 const body = transformToolRouterUpdateParams(parsed);
813 const expectedConfigVersion =
814 parsed.expectedConfigVersion === false ? undefined : parsed.expectedConfigVersion;
@@ -821,6 +831,16 @@ export class ToolRouterSession<
831 );
832 } catch (error) {
833 if (error instanceof ConflictError) {
834 + const sessionConfigId = parsed.experimental?.sessionConfigId;
835 + if (sessionConfigId !== undefined) {
836 + throw new ComposioSessionConfigConflictError(
837 + `Session ${this.sessionId} or Session config ${sessionConfigId} changed while the config was being applied; re-fetch the session and retry the update`,
838 + {
839 + cause: error,
840 + meta: { sessionId: this.sessionId, sessionConfigId, expectedConfigVersion },
841 + }
842 + );
843 + }
844 throw new ComposioSessionConfigConflictError(
845 expectedConfigVersion === undefined
846 ? `Session ${this.sessionId} configuration changed while this update was in flight; re-fetch the session and retry the update`
@@ -839,6 +859,7 @@ export class ToolRouterSession<
859 this.preload = response.config.preload;
860 this.sandbox = response.config.workbench;
861 this.warnings = response.warnings ?? [];
862 + this.experimental.sourceSessionConfig = getSourceSessionConfig(response);
863 return this.config;
864 }
865
ts/packages/core/src/types/sessionConfigs.types.ts new
+81
@@ -0,0 +1,81 @@
1 +import { z } from 'zod/v3';
2 +import { ToolRouterTagsParamSchema } from './toolRouter.types';
3 +
4 +/**
5 + * Params for `composio.sessionConfigs.list()`. The backend owns the defaults:
6 + * active configs only, 20 per page, at most 100.
7 + */
8 +export const SessionConfigListParamsSchema = z.object({
9 + /** Case-insensitive substring match against the config name. */
10 + search: z.string().optional(),
11 + /** `true` returns only archived configs. Omitted returns active configs. */
12 + archived: z.boolean().optional(),
13 + /** Page size. The backend defaults to 20 and caps it at 100. */
14 + limit: z.number().optional(),
15 + /** `nextCursor` from a previous page. */
16 + cursor: z.string().optional(),
17 +});
18 +export type SessionConfigListParams = z.infer<typeof SessionConfigListParamsSchema>;
19 +
20 +/**
21 + * A saved Session config as listed by `composio.sessionConfigs.list()`.
22 + */
23 +export const SessionConfigSummarySchema = z.object({
24 + /** Stable `sc_…` identifier. */
25 + id: z.string(),
26 + /** Project-unique display name. */
27 + name: z.string(),
28 + archived: z.boolean(),
29 + /** ISO 8601 timestamp. */
30 + createdAt: z.string(),
31 + /** ISO 8601 timestamp. */
32 + updatedAt: z.string(),
33 +});
34 +export type SessionConfigSummary = z.infer<typeof SessionConfigSummarySchema>;
35 +
36 +export const SessionConfigListResponseSchema = z.object({
37 + items: z.array(SessionConfigSummarySchema),
38 + /** Cursor for the next page, or `null` on the last page. */
39 + nextCursor: z.string().nullable(),
40 +});
41 +export type SessionConfigListResponse = z.infer<typeof SessionConfigListResponseSchema>;
42 +
43 +const SessionConfigTagPolicySchema = z.object({
44 + enable: z.array(ToolRouterTagsParamSchema.element).optional(),
45 + disable: z.array(ToolRouterTagsParamSchema.element).optional(),
46 +});
47 +
48 +/**
49 + * The access policy stored in a saved Session config, in the backend's
50 + * `enable`/`disable` shape. Toolkit slug keys and tag names are kept exactly
51 + * as the backend sends them.
52 + */
53 +export const SessionConfigPolicySchema = z.object({
54 + toolkits: z
55 + .union([z.object({ enable: z.array(z.string()) }), z.object({ disable: z.array(z.string()) })])
56 + .optional(),
57 + /** Per-toolkit tool policy, keyed by toolkit slug. */
58 + tools: z
59 + .record(
60 + z.string(),
61 + z.union([
62 + z.object({ enable: z.array(z.string()) }),
63 + z.object({ disable: z.array(z.string()) }),
64 + z.object({ tags: SessionConfigTagPolicySchema }),
65 + ])
66 + )
67 + .optional(),
68 + /** Global tag policy. */
69 + tags: SessionConfigTagPolicySchema.optional(),
70 +});
71 +export type SessionConfigPolicy = z.infer<typeof SessionConfigPolicySchema>;
72 +
73 +/**
74 + * A saved Session config with its description and access policy, as returned
75 + * by `composio.sessionConfigs.get()`.
76 + */
77 +export const SessionConfigSchema = SessionConfigSummarySchema.extend({
78 + description: z.string().nullable(),
79 + config: SessionConfigPolicySchema,
80 +});
81 +export type SessionConfig = z.infer<typeof SessionConfigSchema>;
ts/packages/core/src/types/toolRouter.types.ts
+108 -6
@@ -17,6 +17,7 @@ import type {
17 RegisteredCustomToolkit,
18 } from './customTool.types';
19 import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
20 +import { addSessionConfigConflictIssue } from '../lib/sessionConfigConflict';
21
22 export const SessionPreset = {
23 DIRECT_TOOLS: 'direct_tools',
@@ -356,12 +357,32 @@ const ToolRouterCreateSessionConfigBaseSchema = z
357 .describe(
358 'Custom toolkits to include in this session. Created via createCustomToolkit() from @composio/core/experimental.'
359 ),
360 + sessionConfigId: z
361 + .string()
362 + .min(1)
363 + .optional()
364 + .describe(
365 + 'ID of a saved Session config (`sc_…`) to apply when the session is created. Cannot be combined with toolkits, tools, tags, customTools or customToolkits.'
366 + ),
367 })
368 .optional()
369 .describe('Experimental features configuration - not stable, may be modified or removed'),
370 })
371 .partial()
372 .superRefine((config, ctx) => {
373 + // "Provided" means `!== undefined`, so empty arrays conflict too.
374 + if (config.experimental?.sessionConfigId !== undefined) {
375 + addSessionConfigConflictIssue(
376 + ctx,
377 + [
378 + config.toolkits !== undefined && 'toolkits',
379 + config.tools !== undefined && 'tools',
380 + config.tags !== undefined && 'tags',
381 + config.experimental.customTools !== undefined && 'experimental.customTools',
382 + config.experimental.customToolkits !== undefined && 'experimental.customToolkits',
383 + ].filter((field): field is string => field !== false)
384 + );
385 + }
386 if (config.sandbox !== undefined && config.workbench !== undefined) {
387 ctx.addIssue({
388 code: z.ZodIssueCode.custom,
@@ -421,8 +442,39 @@ export const ToolRouterCreateSessionConfigSchema = z
442 * @param {boolean} [multiAccount.requireExplicitSelection] - When true, require explicit account selection when multiple accounts are connected
443 * @param {object} [preload] - Tools to preload into session.tools() and the MCP tool list
444 * @param {string[] | 'all'} [preload.tools] - Tool slugs to preload, or "all" to preload every app tool allowed by the session filters. "all" requires a positive filter such as toolkits, tools, or tags; the backend validates and caps the final tool set.
445 + * @param {object} [experimental] - Experimental features configuration. Not stable; may change or be removed.
446 + * @param {string} [experimental.sessionConfigId] - ID of a saved Session config (`sc_…`) to apply at creation; see `composio.sessionConfigs`. Cannot be combined with `toolkits`, `tools`, `tags`, `experimental.customTools` or `experimental.customToolkits`. Per-session fields such as `authConfigs`, `connectedAccounts`, `manageConnections`, `sandbox`, `multiAccount` and `preload` stay allowed.
447 */
425 -export type ToolRouterCreateSessionConfig = z.infer<typeof ToolRouterCreateSessionConfigSchema>;
448 +export type ToolRouterCreateSessionConfig =
449 + InlineAccessCreateSessionConfig | SavedConfigCreateSessionConfig;
450 +
451 +type ParsedCreateSessionConfig = z.infer<typeof ToolRouterCreateSessionConfigSchema>;
452 +type ParsedCreateSessionExperimental = NonNullable<ParsedCreateSessionConfig['experimental']>;
453 +
454 +/** Create input that sets access inline and applies no saved Session config. */
455 +type InlineAccessCreateSessionConfig = Omit<ParsedCreateSessionConfig, 'experimental'> & {
456 + experimental?: Omit<ParsedCreateSessionExperimental, 'sessionConfigId'> & {
457 + sessionConfigId?: never;
458 + };
459 +};
460 +
461 +/** Create input that takes its access policy from a saved Session config. */
462 +type SavedConfigCreateSessionConfig = Omit<
463 + ParsedCreateSessionConfig,
464 + 'toolkits' | 'tools' | 'tags' | 'experimental'
465 +> & {
466 + toolkits?: never;
467 + tools?: never;
468 + tags?: never;
469 + experimental: Omit<
470 + ParsedCreateSessionExperimental,
471 + 'sessionConfigId' | 'customTools' | 'customToolkits'
472 + > & {
473 + sessionConfigId: string;
474 + customTools?: never;
475 + customToolkits?: never;
476 + };
477 +};
478
479 export const ToolkitConnectionStateSchema = z
480 .object({
@@ -617,6 +669,14 @@ export interface SessionExperimental {
669 * File mount operations (list, upload, download, delete) for the session's virtual filesystem.
670 */
671 files: ToolRouterSessionFilesMount;
672 + /**
673 + * The last saved Session config applied to this session, set from the
674 + * create, `use()` and `update()` responses. Later inline access updates
675 + * keep it. It reflects the last response this object saw: an update from
676 + * another process leaves it stale until `sessions.use()`.
677 + * @experimental
678 + */
679 + sourceSessionConfig?: { id: string };
680 }
681
682 export type ToolRouterSessionSearchFn = (params: {
@@ -781,8 +841,11 @@ export const ToolRouterUpdateExperimentalSchema = z
841 ),
842 sessionConfigId: z
843 .string()
844 + .min(1)
845 .optional()
785 - .describe('Apply the latest active Session config from this project to this session'),
846 + .describe(
847 + "Apply the latest active saved Session config (`sc_…`) from this project to this session. Replaces the session's toolkit, tool and tag access and cannot be combined with toolkits, tools or tags"
848 + ),
849 })
850 .strict();
851 export type ToolRouterUpdateExperimentalConfig = z.infer<typeof ToolRouterUpdateExperimentalSchema>;
@@ -888,6 +951,17 @@ export const ToolRouterUpdateSessionConfigSchema = z
951 })
952 .partial()
953 .superRefine((config, ctx) => {
954 + // "Provided" means `!== undefined`, so `null` conflicts too.
955 + if (config.experimental?.sessionConfigId !== undefined) {
956 + addSessionConfigConflictIssue(
957 + ctx,
958 + [
959 + config.toolkits !== undefined && 'toolkits',
960 + config.tools !== undefined && 'tools',
961 + config.tags !== undefined && 'tags',
962 + ].filter((field): field is string => field !== false)
963 + );
964 + }
965 if (config.sandbox !== undefined && config.workbench !== undefined) {
966 ctx.addIssue({
967 code: z.ZodIssueCode.custom,
@@ -898,7 +972,35 @@ export const ToolRouterUpdateSessionConfigSchema = z
972 }
973 });
974
901 -export type ToolRouterUpdateSessionConfig = z.infer<typeof ToolRouterUpdateSessionConfigSchema>;
975 +/**
976 + * Options for `session.update()`. `experimental.sessionConfigId` applies a
977 + * saved Session config and cannot be combined with `toolkits`, `tools` or
978 + * `tags` (including `null`).
979 + */
980 +export type ToolRouterUpdateSessionConfig =
981 + InlineAccessUpdateSessionConfig | SavedConfigUpdateSessionConfig;
982 +
983 +type ParsedUpdateSessionConfig = z.infer<typeof ToolRouterUpdateSessionConfigSchema>;
984 +type ParsedUpdateSessionExperimental = NonNullable<ParsedUpdateSessionConfig['experimental']>;
985 +
986 +/** Update input that sets access inline and applies no saved Session config. */
987 +type InlineAccessUpdateSessionConfig = Omit<ParsedUpdateSessionConfig, 'experimental'> & {
988 + experimental?:
989 + (Omit<ParsedUpdateSessionExperimental, 'sessionConfigId'> & { sessionConfigId?: never }) | null;
990 +};
991 +
992 +/** Update input that applies a saved Session config. */
993 +type SavedConfigUpdateSessionConfig = Omit<
994 + ParsedUpdateSessionConfig,
995 + 'toolkits' | 'tools' | 'tags' | 'experimental'
996 +> & {
997 + toolkits?: never;
998 + tools?: never;
999 + tags?: never;
1000 + experimental: Omit<ParsedUpdateSessionExperimental, 'sessionConfigId'> & {
1001 + sessionConfigId: string;
1002 + };
1003 +};
1004
1005 export type ToolRouterSessionUpdateFn = (
1006 config: ToolRouterUpdateSessionConfig
@@ -995,9 +1097,9 @@ export interface Session<
1097 sessionId: string;
1098 mcp: ToolRouterMCPServerConfig;
1099 /**
998 - * Server-side session configuration (toolkit/tool allowlists, tags, preload,
999 - * sandbox, manage_connections) as returned by the API. Refreshed in place by
1000 - * `update()`.
1100 + * The session's current configuration (policy snapshot and runtime
1101 + * settings). Refreshed in place by `update()`. For saved, reusable Session
1102 + * configs, see `composio.sessionConfigs`.
1103 */
1104 config: ToolRouterSessionConfig;
1105 /** Stored preload configuration for this session. */
ts/packages/core/src/utils/transformers/sessionConfigs.ts new
+54
@@ -0,0 +1,54 @@
1 +import type {
2 + SessionConfigsListResponse as RawSessionConfigListResponse,
3 + SessionConfigsRetrieveResponse as RawSessionConfig,
4 +} from '@composio/client/resources/session-configs';
5 +import {
6 + SessionConfig,
7 + SessionConfigListResponse,
8 + SessionConfigListResponseSchema,
9 + SessionConfigSchema,
10 + SessionConfigSummary,
11 + SessionConfigSummarySchema,
12 +} from '../../types/sessionConfigs.types';
13 +import { transform } from '../transform';
14 +
15 +export const transformSessionConfigSummary = (
16 + response: RawSessionConfigListResponse.Item
17 +): SessionConfigSummary => {
18 + return transform(response)
19 + .with(SessionConfigSummarySchema)
20 + .using(response => ({
21 + id: response.id,
22 + name: response.name,
23 + archived: response.archived,
24 + createdAt: response.created_at,
25 + updatedAt: response.updated_at,
26 + }));
27 +};
28 +
29 +export const transformSessionConfigListResponse = (
30 + response: RawSessionConfigListResponse
31 +): SessionConfigListResponse => {
32 + return transform(response)
33 + .with(SessionConfigListResponseSchema)
34 + .using(response => ({
35 + items: response.items.map(transformSessionConfigSummary),
36 + nextCursor: response.next_cursor,
37 + }));
38 +};
39 +
40 +export const transformSessionConfig = (response: RawSessionConfig): SessionConfig => {
41 + return transform(response)
42 + .with(SessionConfigSchema)
43 + .using(response => ({
44 + id: response.id,
45 + name: response.name,
46 + description: response.description,
47 + archived: response.archived,
48 + // The policy has no snake_case keys: copy it as-is so toolkit slugs
49 + // and tag names survive.
50 + config: response.config,
51 + createdAt: response.created_at,
52 + updatedAt: response.updated_at,
53 + }));
54 +};
ts/packages/core/test/core/session.test.ts
+7
@@ -3,6 +3,7 @@ import * as fs from 'node:fs';
3 import * as os from 'node:os';
4 import * as path from 'node:path';
5 import { Composio } from '../../src/composio';
6 +import { SessionConfigs } from '../../src/models/SessionConfigs';
7 import { MockProvider } from '../utils/mocks/provider.mock';
8 import { OpenAIProvider } from '../../src/provider/OpenAIProvider';
9 import { getDefaultHeaders, getSessionHeaders } from '../../src/utils/session';
@@ -153,6 +154,12 @@ describe('Composio Session Management', () => {
154 expect(sessionFromCanonicalApi.sessionId).toBe('session_123');
155 expect(sessionFromAlias.sessionId).toBe('session_123');
156 });
157 +
158 + it('should expose sessionConfigs as a SessionConfigs instance', () => {
159 + const composio = new Composio(baseConfig);
160 +
161 + expect(composio.sessionConfigs).toBeInstanceOf(SessionConfigs);
162 + });
163 });
164
165 describe('Session Headers Generation', () => {
ts/packages/core/test/models/sessionConfigUpdate.integration.test.ts new
+161
@@ -0,0 +1,161 @@
1 +import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2 +import { serve, type ServerType } from '@hono/node-server';
3 +import { Hono } from 'hono';
4 +import { z } from 'zod/v3';
5 +import { BadRequestError } from '@composio/client';
6 +import { Composio } from '../../src/composio';
7 +import { ComposioSessionConfigConflictError } from '../../src/errors/ToolRouterErrors';
8 +
9 +// Production rejects unknown PATCH keys. Keep this boundary independent of
10 +// the SDK's input schema so accidental additions fail through the HTTP client.
11 +const patchSchema = z.union([
12 + z.object({ experimental: z.object({ session_config_id: z.string() }).strict() }).strict(),
13 + z.object({ toolkits: z.object({ enable: z.array(z.string()) }).strict() }).strict(),
14 +]);
15 +
16 +describe('Session configs over HTTP', () => {
17 + let server: ServerType;
18 + let composio: Composio;
19 + let patchRequests: unknown[];
20 + let listQueries: Record<string, string>[];
21 + let conflict: boolean;
22 + const originalConfig = {
23 + user_id: 'session-config-test',
24 + toolkits: { enabled: ['github'] },
25 + preload: { tools: [] },
26 + };
27 + const updatedConfig = {
28 + ...originalConfig,
29 + toolkits: { enabled: ['gmail'] },
30 + tags: { enabled: ['readOnlyHint'] },
31 + };
32 +
33 + beforeEach(async () => {
34 + patchRequests = [];
35 + listQueries = [];
36 + conflict = false;
37 + const app = new Hono();
38 + app.get('/api/v3.1/session_configs', c => {
39 + listQueries.push(c.req.query());
40 + return c.json({ items: [], next_cursor: null });
41 + });
42 + const sessionPath = '/api/v3.1/tool_router/session/trs_test';
43 + app.get(sessionPath, c =>
44 + c.json({
45 + session_id: 'trs_test',
46 + config_version: 7,
47 + config: originalConfig,
48 + tool_router_tools: [],
49 + mcp: { type: 'http', url: new URL('/mcp', c.req.url).href },
50 + })
51 + );
52 + app.patch(sessionPath, async c => {
53 + const payload: unknown = await c.req.json();
54 + patchRequests.push(payload);
55 + const parsed = patchSchema.safeParse(payload);
56 + if (!parsed.success || conflict) {
57 + return c.json(
58 + { error: { message: conflict ? 'Config changed' : 'Unrecognized PATCH field' } },
59 + conflict ? 409 : 400
60 + );
61 + }
62 + return c.json({
63 + session_id: 'trs_test',
64 + config_version: 8,
65 + config: updatedConfig,
66 + warnings: [],
67 + ...('experimental' in parsed.data && {
68 + experimental: {
69 + source_session_config: { id: parsed.data.experimental.session_config_id },
70 + },
71 + }),
72 + });
73 + });
74 + app.notFound(c => c.json({ error: { message: 'Unexpected endpoint' } }, 404));
75 + const baseURL = await new Promise<string>(resolve => {
76 + server = serve({ fetch: app.fetch, port: 0, hostname: '127.0.0.1' }, address =>
77 + resolve(`http://127.0.0.1:${address.port}`)
78 + );
79 + });
80 + composio = new Composio({
81 + apiKey: 'test-key',
82 + baseURL,
83 + allowTracking: false,
84 + allowTracing: false,
85 + });
86 + });
87 +
88 + afterEach(async () => {
89 + await new Promise<void>((resolve, reject) =>
90 + server.close(error => (error ? reject(error) : resolve()))
91 + );
92 + });
93 +
94 + it('omits undefined list parameters while preserving false', async () => {
95 + await composio.sessionConfigs.list({
96 + search: undefined,
97 + archived: false,
98 + limit: undefined,
99 + cursor: undefined,
100 + });
101 +
102 + expect(listQueries).toEqual([{ archived: 'false' }]);
103 + });
104 +
105 + it('applies the documented saved-config update without extra wire fields', async () => {
106 + const session = await composio.sessions.use('trs_test');
107 +
108 + await session.update({ experimental: { sessionConfigId: 'sc_test' } });
109 +
110 + expect(patchRequests).toEqual([{ experimental: { session_config_id: 'sc_test' } }]);
111 + expect(session.config).toEqual(updatedConfig);
112 + expect(session.configVersion).toBe(8);
113 + expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_test' });
114 + });
115 +
116 + it('also applies inline updates without an implicit precondition', async () => {
117 + const session = await composio.sessions.use('trs_test');
118 +
119 + await session.update({ toolkits: ['gmail'] });
120 +
121 + expect(patchRequests).toEqual([{ toolkits: { enable: ['gmail'] } }]);
122 + expect(session.config.toolkits).toEqual({ enabled: ['gmail'] });
123 + });
124 +
125 + it('preserves an explicit version check and surfaces rejection without retrying', async () => {
126 + const session = await composio.sessions.use('trs_test');
127 + const before = session.config;
128 +
129 + await expect(
130 + session.update({
131 + experimental: { sessionConfigId: 'sc_test' },
132 + expectedConfigVersion: 7,
133 + })
134 + ).rejects.toBeInstanceOf(BadRequestError);
135 +
136 + expect(patchRequests).toEqual([
137 + {
138 + experimental: { session_config_id: 'sc_test' },
139 + expected_config_version: 7,
140 + },
141 + ]);
142 + expect(session.config).toBe(before);
143 + expect(session.configVersion).toBe(7);
144 + expect(session.experimental.sourceSessionConfig).toBeUndefined();
145 + });
146 +
147 + it('surfaces an apply-time conflict without retrying or refreshing local state', async () => {
148 + const session = await composio.sessions.use('trs_test');
149 + const before = session.config;
150 + conflict = true;
151 +
152 + await expect(
153 + session.update({ experimental: { sessionConfigId: 'sc_test' } })
154 + ).rejects.toBeInstanceOf(ComposioSessionConfigConflictError);
155 +
156 + expect(patchRequests).toHaveLength(1);
157 + expect(session.config).toBe(before);
158 + expect(session.configVersion).toBe(7);
159 + expect(session.experimental.sourceSessionConfig).toBeUndefined();
160 + });
161 +});
ts/packages/core/test/models/sessionConfigs.test.ts new
+215
@@ -0,0 +1,215 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import ComposioClient, {
3 + APIUserAbortError,
4 + NotFoundError,
5 + PermissionDeniedError,
6 +} from '@composio/client';
7 +import { SessionConfigs } from '../../src/models/SessionConfigs';
8 +import { telemetry } from '../../src/telemetry/Telemetry';
9 +import { ValidationError } from '../../src/errors/ValidationErrors';
10 +import { ComposioRequestCancelledError } from '../../src/errors/SDKErrors';
11 +
12 +vi.mock('../../src/telemetry/Telemetry', () => ({
13 + telemetry: {
14 + instrument: vi.fn(),
15 + },
16 +}));
17 +
18 +const createMockClient = () => ({
19 + baseURL: 'https://api.composio.dev',
20 + apiKey: 'test-api-key',
21 + sessionConfigs: {
22 + list: vi.fn(),
23 + retrieve: vi.fn(),
24 + },
25 +});
26 +
27 +const rawSummary = {
28 + id: 'sc_1',
29 + name: 'Daily digest',
30 + archived: false,
31 + created_at: '2026-01-01T00:00:00.000Z',
32 + updated_at: '2026-01-02T00:00:00.000Z',
33 +};
34 +const summary = {
35 + id: 'sc_1',
36 + name: 'Daily digest',
37 + archived: false,
38 + createdAt: '2026-01-01T00:00:00.000Z',
39 + updatedAt: '2026-01-02T00:00:00.000Z',
40 +};
41 +
42 +describe('SessionConfigs', () => {
43 + let sessionConfigs: SessionConfigs;
44 + let mockClient: ReturnType<typeof createMockClient>;
45 +
46 + beforeEach(() => {
47 + vi.clearAllMocks();
48 + mockClient = createMockClient();
49 + sessionConfigs = new SessionConfigs(mockClient as unknown as ComposioClient);
50 + });
51 +
52 + it('instruments the class with telemetry', () => {
53 + expect(telemetry.instrument).toHaveBeenCalledWith(sessionConfigs, 'SessionConfigs');
54 + });
55 +
56 + describe('list', () => {
57 + it('sends an empty query when called without params', async () => {
58 + mockClient.sessionConfigs.list.mockResolvedValue({ items: [], next_cursor: null });
59 +
60 + const result = await sessionConfigs.list();
61 +
62 + expect(mockClient.sessionConfigs.list).toHaveBeenCalledWith({}, undefined);
63 + expect(result).toEqual({ items: [], nextCursor: null });
64 + });
65 +
66 + it('forwards search, archived, limit and cursor unchanged', async () => {
67 + mockClient.sessionConfigs.list.mockResolvedValue({ items: [], next_cursor: null });
68 + const signal = new AbortController().signal;
69 +
70 + await sessionConfigs.list(
71 + { search: 'Daily', archived: true, limit: 50, cursor: 'c1' },
72 + { signal }
73 + );
74 +
75 + expect(mockClient.sessionConfigs.list).toHaveBeenCalledWith(
76 + { search: 'Daily', archived: true, limit: 50, cursor: 'c1' },
77 + { signal }
78 + );
79 + });
80 +
81 + it('forwards a limit above the backend cap without clamping', async () => {
82 + mockClient.sessionConfigs.list.mockResolvedValue({ items: [], next_cursor: null });
83 +
84 + await sessionConfigs.list({ limit: 500 });
85 +
86 + expect(mockClient.sessionConfigs.list).toHaveBeenCalledWith({ limit: 500 }, undefined);
87 + });
88 +
89 + it('camelCases each item and the next cursor, keeping ISO strings unchanged', async () => {
90 + mockClient.sessionConfigs.list.mockResolvedValue({
91 + items: [rawSummary, { ...rawSummary, id: 'sc_2', archived: true }],
92 + next_cursor: 'c2',
93 + });
94 +
95 + const result = await sessionConfigs.list();
96 +
97 + expect(result).toEqual({
98 + items: [summary, { ...summary, id: 'sc_2', archived: true }],
99 + nextCursor: 'c2',
100 + });
101 + });
102 +
103 + it('returns a null next cursor on the last page', async () => {
104 + mockClient.sessionConfigs.list.mockResolvedValue({
105 + items: [rawSummary],
106 + next_cursor: null,
107 + });
108 +
109 + const result = await sessionConfigs.list({ cursor: 'c2' });
110 +
111 + expect(result.nextCursor).toBeNull();
112 + });
113 +
114 + it('throws a ValidationError for a non-numeric limit and makes no call', async () => {
115 + await expect(
116 + sessionConfigs.list({ limit: 'ten' as unknown as number })
117 + ).rejects.toBeInstanceOf(ValidationError);
118 + expect(mockClient.sessionConfigs.list).not.toHaveBeenCalled();
119 + });
120 +
121 + it('propagates a 403 from the client unchanged', async () => {
122 + const error = new PermissionDeniedError(403, undefined, 'Forbidden', {});
123 + mockClient.sessionConfigs.list.mockRejectedValue(error);
124 +
125 + await expect(sessionConfigs.list()).rejects.toBe(error);
126 + });
127 +
128 + it('reports a cancelled request when the signal is aborted', async () => {
129 + const controller = new AbortController();
130 + controller.abort();
131 + mockClient.sessionConfigs.list.mockRejectedValue(new APIUserAbortError());
132 +
133 + await expect(sessionConfigs.list({}, { signal: controller.signal })).rejects.toBeInstanceOf(
134 + ComposioRequestCancelledError
135 + );
136 + });
137 + });
138 +
139 + describe('get', () => {
140 + const rawConfig = {
141 + ...rawSummary,
142 + description: null,
143 + config: {
144 + toolkits: { enable: ['github', 'google_calendar'] },
145 + tools: {
146 + github: { enable: ['GITHUB_GET_REPO'] },
147 + google_calendar: { tags: { enable: ['readOnlyHint'], disable: ['destructiveHint'] } },
148 + },
149 + tags: { disable: ['destructiveHint'] },
150 + },
151 + };
152 +
153 + it('retrieves a config by id and camelCases only the metadata fields', async () => {
154 + mockClient.sessionConfigs.retrieve.mockResolvedValue(rawConfig);
155 +
156 + const result = await sessionConfigs.get('sc_1');
157 +
158 + expect(mockClient.sessionConfigs.retrieve).toHaveBeenCalledWith('sc_1', undefined);
159 + expect(result).toEqual({
160 + ...summary,
161 + description: null,
162 + config: rawConfig.config,
163 + });
164 + });
165 +
166 + it('keeps toolkit slug keys and tag names exactly as sent', async () => {
167 + mockClient.sessionConfigs.retrieve.mockResolvedValue(rawConfig);
168 +
169 + const result = await sessionConfigs.get('sc_1');
170 +
171 + expect(Object.keys(result.config.tools ?? {})).toEqual(['github', 'google_calendar']);
172 + expect(result.config.tools?.google_calendar).toEqual({
173 + tags: { enable: ['readOnlyHint'], disable: ['destructiveHint'] },
174 + });
175 + expect(result.config.tags).toEqual({ disable: ['destructiveHint'] });
176 + });
177 +
178 + it('does not invent tools or tags for a toolkit-only policy', async () => {
179 + mockClient.sessionConfigs.retrieve.mockResolvedValue({
180 + ...rawConfig,
181 + description: 'Read-only access',
182 + config: { toolkits: { disable: ['gmail'] } },
183 + });
184 +
185 + const result = await sessionConfigs.get('sc_1');
186 +
187 + expect(result.description).toBe('Read-only access');
188 + expect(result.config).toEqual({ toolkits: { disable: ['gmail'] } });
189 + expect('tools' in result.config).toBe(false);
190 + expect('tags' in result.config).toBe(false);
191 + });
192 +
193 + it.each(['', ' '])('rejects the id %j with a ValidationError and makes no call', async id => {
194 + await expect(sessionConfigs.get(id)).rejects.toBeInstanceOf(ValidationError);
195 + expect(mockClient.sessionConfigs.retrieve).not.toHaveBeenCalled();
196 + });
197 +
198 + it('propagates a 404 from the client unchanged', async () => {
199 + const error = new NotFoundError(404, undefined, 'Not found', {});
200 + mockClient.sessionConfigs.retrieve.mockRejectedValue(error);
201 +
202 + await expect(sessionConfigs.get('sc_missing')).rejects.toBe(error);
203 + });
204 +
205 + it('reports a cancelled request when the signal is aborted', async () => {
206 + const controller = new AbortController();
207 + controller.abort();
208 + mockClient.sessionConfigs.retrieve.mockRejectedValue(new APIUserAbortError());
209 +
210 + await expect(
211 + sessionConfigs.get('sc_1', { signal: controller.signal })
212 + ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
213 + });
214 + });
215 +});
ts/packages/core/test/models/toolRouter.test.ts
+456 -1
@@ -1,7 +1,12 @@
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import { z } from 'zod/v3';
3 import { ToolRouter } from '../../src/models/ToolRouter';
4 -import ComposioClient, { ConflictError } from '@composio/client';
4 +import ComposioClient, {
5 + BadRequestError,
6 + ConflictError,
7 + NotFoundError,
8 + PermissionDeniedError,
9 +} from '@composio/client';
10 import { telemetry } from '../../src/telemetry/Telemetry';
11 import { MockProvider } from '../utils/mocks/provider.mock';
12 import { Tools } from '../../src/models/Tools';
@@ -1828,6 +1833,173 @@ describe('ToolRouter', () => {
1833 });
1834 });
1835
1836 + describe('session configs', () => {
1837 + const createPayload = () => mockClient.toolRouter.session.create.mock.calls[0][0];
1838 +
1839 + it('sends sessionConfigId as experimental.session_config_id', async () => {
1840 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1841 +
1842 + await toolRouter.create(userId, { experimental: { sessionConfigId: 'sc_1' } });
1843 +
1844 + expect(createPayload().experimental).toEqual({ session_config_id: 'sc_1' });
1845 + });
1846 +
1847 + it('sends the same payload as before when no sessionConfigId is set', async () => {
1848 + mockClient.toolRouter.session.create.mockResolvedValue(mockSessionCreateResponse);
1849 +
1850 + await toolRouter.create(userId);
1851 + await toolRouter.create(userId, { toolkits: ['gmail'] });
1852 +
1853 + const [[bare], [withToolkits]] = mockClient.toolRouter.session.create.mock.calls;
1854 + expect(bare.experimental).toBeUndefined();
1855 + expect(withToolkits.experimental).toBeUndefined();
1856 + expect(JSON.stringify(bare)).toBe(
1857 + JSON.stringify({ user_id: userId, manage_connections: { enable: true } })
1858 + );
1859 + expect(JSON.stringify(withToolkits)).toBe(
1860 + JSON.stringify({
1861 + user_id: userId,
1862 + toolkits: { enable: ['gmail'] },
1863 + manage_connections: { enable: true },
1864 + })
1865 + );
1866 + });
1867 +
1868 + it('sends session_config_id together with assistive_prompt_config', async () => {
1869 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1870 +
1871 + await toolRouter.create(userId, {
1872 + experimental: {
1873 + sessionConfigId: 'sc_1',
1874 + assistivePrompt: { userTimezone: 'Europe/Rome' },
1875 + },
1876 + });
1877 +
1878 + expect(createPayload().experimental).toEqual({
1879 + session_config_id: 'sc_1',
1880 + assistive_prompt_config: { user_timezone: 'Europe/Rome' },
1881 + });
1882 + });
1883 +
1884 + it('sends every per-session field unchanged next to sessionConfigId', async () => {
1885 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1886 +
1887 + await toolRouter.create(userId, {
1888 + authConfigs: { github: 'ac_1' },
1889 + connectedAccounts: { github: 'ca_1' },
1890 + manageConnections: false,
1891 + sandbox: { enable: false },
1892 + multiAccount: { enable: true, maxAccountsPerToolkit: 3 },
1893 + preload: { tools: ['GITHUB_GET_REPO'] },
1894 + experimental: { sessionConfigId: 'sc_1' },
1895 + });
1896 +
1897 + expect(createPayload()).toEqual({
1898 + user_id: userId,
1899 + auth_configs: { github: 'ac_1' },
1900 + connected_accounts: { github: ['ca_1'] },
1901 + manage_connections: { enable: false },
1902 + workbench: { enable: false },
1903 + multi_account: {
1904 + enable: true,
1905 + max_accounts_per_toolkit: 3,
1906 + require_explicit_selection: true,
1907 + },
1908 + preload: { tools: ['GITHUB_GET_REPO'] },
1909 + experimental: { session_config_id: 'sc_1' },
1910 + });
1911 + });
1912 +
1913 + it('rejects an empty sessionConfigId before any client call', async () => {
1914 + await expect(
1915 + toolRouter.create(userId, { experimental: { sessionConfigId: '' } })
1916 + ).rejects.toThrow();
1917 + expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled();
1918 + });
1919 +
1920 + // Plain JavaScript callers bypass the compile-time union, so these go
1921 + // through `unknown`.
1922 + const createUnchecked = (config: Record<string, unknown>) =>
1923 + toolRouter.create(userId, config as unknown as ToolRouterCreateSessionConfig);
1924 + const customTool = { slug: 'MY_TOOL' };
1925 + const customToolkit = { slug: 'MY_TOOLKIT', tools: [] };
1926 +
1927 + it.each([
1928 + ['toolkits', { toolkits: ['github'] }],
1929 + ['toolkits', { toolkits: { disable: ['x'] } }],
1930 + ['tools', { tools: { github: ['GITHUB_GET_REPO'] } }],
1931 + ['tags', { tags: ['readOnlyHint'] }],
1932 + ['experimental.customTools', { experimental: { customTools: [customTool] } }],
1933 + ['experimental.customToolkits', { experimental: { customToolkits: [customToolkit] } }],
1934 + ['toolkits', { toolkits: [] }],
1935 + ['experimental.customTools', { experimental: { customTools: [] } }],
1936 + ])(
1937 + 'rejects sessionConfigId combined with %s (%j) without calling the API',
1938 + async (field, inline) => {
1939 + const inlineExperimental = (inline as { experimental?: object }).experimental;
1940 + const error = await createUnchecked({
1941 + ...inline,
1942 + experimental: { ...inlineExperimental, sessionConfigId: 'sc_1' },
1943 + }).catch(e => e);
1944 +
1945 + expect(error).toBeInstanceOf(ValidationError);
1946 + expect(error.message).toContain(
1947 + `experimental.sessionConfigId cannot be combined with ${field}`
1948 + );
1949 + expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled();
1950 + }
1951 + );
1952 +
1953 + it('names every conflicting field in one error', async () => {
1954 + const error = await createUnchecked({
1955 + toolkits: ['github'],
1956 + tags: ['readOnlyHint'],
1957 + experimental: { sessionConfigId: 'sc_1', customTools: [customTool] },
1958 + }).catch(e => e);
1959 +
1960 + expect(error).toBeInstanceOf(ValidationError);
1961 + expect(error.message).toContain(
1962 + 'experimental.sessionConfigId cannot be combined with toolkits, tags, experimental.customTools'
1963 + );
1964 + expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled();
1965 + });
1966 +
1967 + it('treats an explicit undefined inline field as absent', async () => {
1968 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1969 +
1970 + await toolRouter.create(userId, {
1971 + toolkits: undefined,
1972 + experimental: { sessionConfigId: 'sc_1' },
1973 + });
1974 +
1975 + expect(createPayload().experimental).toEqual({ session_config_id: 'sc_1' });
1976 + });
1977 +
1978 + it('keeps throwing ZodError for unrelated invalid input', async () => {
1979 + const error = await createUnchecked({
1980 + multiAccount: { maxAccountsPerToolkit: 1 },
1981 + }).catch(e => e);
1982 +
1983 + expect(error).toBeInstanceOf(z.ZodError);
1984 + expect(error).not.toBeInstanceOf(ValidationError);
1985 + expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled();
1986 + });
1987 +
1988 + it('allows the direct tools preset with a saved config and sends preload all', async () => {
1989 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1990 +
1991 + await toolRouter.create(userId, {
1992 + sessionPreset: SessionPreset.DIRECT_TOOLS,
1993 + experimental: { sessionConfigId: 'sc_1' },
1994 + });
1995 +
1996 + expect(createPayload()).toMatchObject({
1997 + preload: { tools: 'all' },
1998 + experimental: { session_config_id: 'sc_1' },
1999 + });
2000 + });
2001 + });
2002 +
2003 describe('error handling', () => {
2004 it('should throw error if API call fails', async () => {
2005 const apiError = new Error('API error: Invalid session configuration');
@@ -4168,4 +4340,287 @@ describe('ToolRouter', () => {
4340 });
4341 });
4342 });
4343 +
4344 + describe('saved Session configs on an existing session', () => {
4345 + const sessionId = 'session_123';
4346 +
4347 + const patchResponse = (configVersion: number, experimental?: Record<string, unknown>) => ({
4348 + session_id: sessionId,
4349 + config: mockSessionRetrieveResponse.config,
4350 + config_version: configVersion,
4351 + warnings: [],
4352 + ...(experimental && { experimental }),
4353 + });
4354 +
4355 + const patchBody = (callIndex = 0) =>
4356 + mockClient.toolRouter.session.patch.mock.calls[callIndex][1] as Record<string, unknown>;
4357 +
4358 + // Plain JavaScript callers bypass the compile-time union.
4359 + type UpdateInput = Parameters<Session<unknown, unknown, MockProvider>['update']>[0];
4360 + const unchecked = (config: Record<string, unknown>) => config as unknown as UpdateInput;
4361 +
4362 + beforeEach(() => {
4363 + mockClient.toolRouter.session.patch.mockResolvedValue(patchResponse(8));
4364 + });
4365 +
4366 + describe('mixed-input rejection', () => {
4367 + it.each([
4368 + ['toolkits', { toolkits: ['gmail'] }],
4369 + ['toolkits', { toolkits: null }],
4370 + ['tools', { tools: { gmail: ['GMAIL_SEND_EMAIL'] } }],
4371 + ['tools', { tools: null }],
4372 + ['tags', { tags: ['readOnlyHint'] }],
4373 + ['tags', { tags: null }],
4374 + ])('rejects sessionConfigId combined with %s (%j) without a PATCH', async (field, inline) => {
4375 + const session = await toolRouter.use(sessionId);
4376 +
4377 + const error = await session
4378 + .update(unchecked({ ...inline, experimental: { sessionConfigId: 'sc_1' } }))
4379 + .catch(e => e);
4380 +
4381 + expect(error).toBeInstanceOf(ValidationError);
4382 + expect(error.message).toContain(
4383 + `experimental.sessionConfigId cannot be combined with ${field}`
4384 + );
4385 + expect(mockClient.toolRouter.session.patch).not.toHaveBeenCalled();
4386 + });
4387 +
4388 + it('sends sessionConfigId next to per-session fields', async () => {
4389 + const session = await toolRouter.use(sessionId);
4390 +
4391 + await session.update({
4392 + authConfigs: { github: 'ac_1' },
4393 + preload: null,
4394 + experimental: { sessionConfigId: 'sc_1' },
4395 + });
4396 +
4397 + expect(patchBody()).toEqual({
4398 + auth_configs: { github: 'ac_1' },
4399 + preload: null,
4400 + experimental: { session_config_id: 'sc_1' },
4401 + });
4402 + });
4403 +
4404 + it('allows sessionConfigId with other experimental settings', async () => {
4405 + const session = await toolRouter.use(sessionId);
4406 +
4407 + await session.update({ experimental: { sessionConfigId: 'sc_1', fastMode: true } });
4408 +
4409 + expect(patchBody().experimental).toEqual({ session_config_id: 'sc_1', fast_mode: true });
4410 + });
4411 +
4412 + it('treats an explicit undefined toolkits as absent', async () => {
4413 + const session = await toolRouter.use(sessionId);
4414 +
4415 + await session.update({ toolkits: undefined, experimental: { sessionConfigId: 'sc_1' } });
4416 +
4417 + expect(patchBody()).not.toHaveProperty('toolkits');
4418 + expect(patchBody().experimental).toEqual({ session_config_id: 'sc_1' });
4419 + });
4420 +
4421 + it('rejects an empty sessionConfigId before any PATCH', async () => {
4422 + const session = await toolRouter.use(sessionId);
4423 +
4424 + await expect(session.update({ experimental: { sessionConfigId: '' } })).rejects.toThrow();
4425 + expect(mockClient.toolRouter.session.patch).not.toHaveBeenCalled();
4426 + });
4427 +
4428 + it('keeps throwing ZodError for unrelated invalid input', async () => {
4429 + const session = await toolRouter.use(sessionId);
4430 +
4431 + const error = await session.update({ expectedConfigVersion: 0 }).catch(e => e);
4432 +
4433 + expect(error).toBeInstanceOf(z.ZodError);
4434 + expect(error).not.toBeInstanceOf(ValidationError);
4435 + expect(mockClient.toolRouter.session.patch).not.toHaveBeenCalled();
4436 + });
4437 + });
4438 +
4439 + describe('sourceSessionConfig', () => {
4440 + const withSource = <T extends object>(response: T, id: string) => ({
4441 + ...response,
4442 + experimental: { source_session_config: { id } },
4443 + });
4444 +
4445 + it('is set from the create response', async () => {
4446 + mockClient.toolRouter.session.create.mockResolvedValueOnce(
4447 + withSource(mockSessionCreateResponse, 'sc_1')
4448 + );
4449 +
4450 + const session = await toolRouter.create('user_123', {
4451 + experimental: { sessionConfigId: 'sc_1' },
4452 + });
4453 +
4454 + expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_1' });
4455 + });
4456 +
4457 + it('is undefined when the create response has no experimental block', async () => {
4458 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
4459 +
4460 + const session = await toolRouter.create('user_123');
4461 +
4462 + expect(session.experimental.sourceSessionConfig).toBeUndefined();
4463 + });
4464 +
4465 + it('is set from the retrieve response on use()', async () => {
4466 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(
4467 + withSource(mockSessionRetrieveResponse, 'sc_1')
4468 + );
4469 +
4470 + const session = await toolRouter.use(sessionId);
4471 +
4472 + expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_1' });
4473 + });
4474 +
4475 + it('is set from the attach response on use() with custom tools', async () => {
4476 + const customTool = createCustomTool('MY_TOOL', {
4477 + name: 'My tool',
4478 + description: 'Does a thing',
4479 + inputParams: z.object({}),
4480 + execute: async () => ({ ok: true }),
4481 + });
4482 + mockClient.toolRouter.session.attach.mockResolvedValueOnce(
4483 + withSource(mockSessionRetrieveResponse, 'sc_1')
4484 + );
4485 +
4486 + const session = await toolRouter.use(sessionId, { customTools: [customTool] });
4487 +
4488 + expect(mockClient.toolRouter.session.attach).toHaveBeenCalled();
4489 + expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_1' });
4490 + });
4491 +
4492 + it('copies only the id', async () => {
4493 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce({
4494 + ...mockSessionRetrieveResponse,
4495 + experimental: { source_session_config: { id: 'sc_1', name: 'Daily digest' } },
4496 + });
4497 +
4498 + const session = await toolRouter.use(sessionId);
4499 +
4500 + expect(session.experimental.sourceSessionConfig).toStrictEqual({ id: 'sc_1' });
4501 + });
4502 +
4503 + it('is replaced by the config the update response reports', async () => {
4504 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(
4505 + withSource(mockSessionRetrieveResponse, 'sc_1')
4506 + );
4507 + mockClient.toolRouter.session.patch.mockResolvedValueOnce(
4508 + withSource(patchResponse(8), 'sc_2')
4509 + );
4510 + const session = await toolRouter.use(sessionId);
4511 +
4512 + await session.update({ experimental: { sessionConfigId: 'sc_2' } });
4513 +
4514 + expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_2' });
4515 + });
4516 +
4517 + it('survives an inline update whose response still carries it, then clears when omitted', async () => {
4518 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(
4519 + withSource(mockSessionRetrieveResponse, 'sc_1')
4520 + );
4521 + mockClient.toolRouter.session.patch
4522 + .mockResolvedValueOnce(withSource(patchResponse(8), 'sc_1'))
4523 + .mockResolvedValueOnce(patchResponse(9));
4524 + const session = await toolRouter.use(sessionId);
4525 +
4526 + await session.update({ toolkits: ['gmail'] });
4527 + expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_1' });
4528 +
4529 + await session.update({ toolkits: ['slack'] });
4530 + expect(session.experimental.sourceSessionConfig).toBeUndefined();
4531 + });
4532 +
4533 + it('makes no extra lookups from tools(), search() or execute()', async () => {
4534 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(
4535 + withSource(mockSessionRetrieveResponse, 'sc_1')
4536 + );
4537 + mockClient.toolRouter.session.search.mockResolvedValueOnce({
4538 + success: true,
4539 + error: null,
4540 + results: [],
4541 + tool_schemas: {},
4542 + toolkit_connection_statuses: [],
4543 + next_steps_guidance: [],
4544 + session: { id: sessionId, generate_id: false, instructions: '' },
4545 + time_info: {
4546 + current_time_utc: '2026-01-01T00:00:00Z',
4547 + current_time_utc_epoch_seconds: 0,
4548 + message: '',
4549 + },
4550 + });
4551 + mockClient.toolRouter.session.execute.mockResolvedValueOnce({
4552 + data: {},
4553 + error: null,
4554 + log_id: 'log_1',
4555 + });
4556 + const session = await toolRouter.use(sessionId);
4557 +
4558 + await session.tools();
4559 + await session.search({ query: 'send an email' });
4560 + await session.execute('GMAIL_SEND_EMAIL', {});
4561 +
4562 + // The mock client has no `sessionConfigs`, so any lookup would throw.
4563 + expect(mockClient.toolRouter.session.retrieve).toHaveBeenCalledTimes(1);
4564 + });
4565 + });
4566 +
4567 + describe('fail closed', () => {
4568 + it.each([
4569 + [new BadRequestError(400, undefined, 'Bad request', {}), {}],
4570 + [new PermissionDeniedError(403, undefined, 'Forbidden', {}), {}],
4571 + [new NotFoundError(404, undefined, 'Not found', {}), {}],
4572 + [new ConflictError(409, undefined, 'Conflict', {}), {}],
4573 + [new ConflictError(409, undefined, 'Conflict', {}), { expectedConfigVersion: 7 }],
4574 + ])('preserves state and does not retry after %s with %j', async (error, precondition) => {
4575 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce({
4576 + ...mockSessionRetrieveResponse,
4577 + experimental: { source_session_config: { id: 'sc_1' } },
4578 + });
4579 + mockClient.toolRouter.session.patch.mockRejectedValueOnce(error);
4580 + const session = await toolRouter.use(sessionId);
4581 + const configBefore = session.config;
4582 +
4583 + const failure = await session
4584 + .update({ experimental: { sessionConfigId: 'sc_2' }, ...precondition })
4585 + .catch(e => e);
4586 +
4587 + if (error.status === 409) {
4588 + expect(failure).toBeInstanceOf(ComposioSessionConfigConflictError);
4589 + expect(failure.statusCode).toBe(409);
4590 + expect(failure.message).toContain(sessionId);
4591 + expect(failure.message).toContain('sc_2');
4592 + expect(failure.message).toMatch(/re-fetch/i);
4593 + expect(failure.message).toMatch(/retry/i);
4594 + expect(failure.message).not.toMatch(/no longer at version/);
4595 + expect(failure.meta).toMatchObject({ sessionId, sessionConfigId: 'sc_2' });
4596 + } else {
4597 + expect(failure).toBe(error);
4598 + }
4599 + expect(mockClient.toolRouter.session.patch).toHaveBeenCalledTimes(1);
4600 + expect(session.config).toBe(configBefore);
4601 + expect(session.configVersion).toBe(7);
4602 + expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_1' });
4603 + });
4604 +
4605 + it.each([
4606 + ['403', () => new PermissionDeniedError(403, undefined, 'Forbidden', {})],
4607 + ['404', () => new NotFoundError(404, undefined, 'Not found', {})],
4608 + ])(
4609 + 'surfaces a %s from create unchanged and never retries without the config',
4610 + async (_status, makeError) => {
4611 + const error = makeError();
4612 + mockClient.toolRouter.session.create.mockRejectedValueOnce(error);
4613 +
4614 + await expect(
4615 + toolRouter.create('user_123', { experimental: { sessionConfigId: 'sc_archived' } })
4616 + ).rejects.toBe(error);
4617 +
4618 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledTimes(1);
4619 + expect(mockClient.toolRouter.session.create.mock.calls[0][0].experimental).toEqual({
4620 + session_config_id: 'sc_archived',
4621 + });
4622 + }
4623 + );
4624 + });
4625 + });
4626 });
ts/packages/core/type-tests/session-configs.test-d.ts new
+206
@@ -0,0 +1,206 @@
1 +/**
2 + * Type-level tests for saved Session configs.
3 + *
4 + * These tests fail the build (tsconfig.type-tests.json) if the public read
5 + * types drift from the generated client.
6 + */
7 +import type {
8 + SessionConfigsListResponse,
9 + SessionConfigsRetrieveResponse,
10 +} from '@composio/client/resources/session-configs';
11 +import {
12 + Composio,
13 + experimental_createTool,
14 + experimental_createToolkit,
15 + SessionPreset,
16 + type SessionConfig,
17 + type SessionConfigListResponse,
18 + type SessionConfigPolicy,
19 + type SessionConfigSummary,
20 +} from '../src';
21 +
22 +declare const composio: Composio;
23 +
24 +async function reads(): Promise<void> {
25 + const page: SessionConfigListResponse = await composio.sessionConfigs.list();
26 + const nextCursor: string | null = page.nextCursor;
27 + void nextCursor;
28 + await composio.sessionConfigs.list({ search: 'Daily', archived: true, limit: 50, cursor: 'c1' });
29 + // @ts-expect-error limit is a number
30 + await composio.sessionConfigs.list({ limit: '10' });
31 +
32 + const sessionConfig: SessionConfig = await composio.sessionConfigs.get('sc_1', {
33 + signal: new AbortController().signal,
34 + });
35 + const description: string | null = sessionConfig.description;
36 + void description;
37 +}
38 +
39 +// The SDK policy and the client policy are mutually assignable.
40 +function policyMatchesClient(
41 + clientPolicy: SessionConfigsRetrieveResponse['config'],
42 + sdkPolicy: SessionConfigPolicy
43 +): void {
44 + const _fromClient: SessionConfigPolicy = clientPolicy;
45 + const _toClient: SessionConfigsRetrieveResponse['config'] = sdkPolicy;
46 + void _fromClient;
47 + void _toClient;
48 +}
49 +
50 +// Every client list item field has a camelCased SDK counterpart.
51 +function summaryMatchesClient(item: SessionConfigsListResponse.Item): SessionConfigSummary {
52 + return {
53 + id: item.id,
54 + name: item.name,
55 + archived: item.archived,
56 + createdAt: item.created_at,
57 + updatedAt: item.updated_at,
58 + };
59 +}
60 +
61 +// A saved Session config replaces the inline access fields on create. Each
62 +// forbidden field is rejected on every create entry point.
63 +declare const customTool: ReturnType<typeof experimental_createTool>;
64 +declare const customToolkit: ReturnType<typeof experimental_createToolkit>;
65 +
66 +async function createRejectsMixedInputs(): Promise<void> {
67 + const experimental = { sessionConfigId: 'sc_1' };
68 +
69 + // @ts-expect-error toolkits cannot be combined with sessionConfigId
70 + await composio.create('u', { toolkits: ['github'], experimental });
71 + // @ts-expect-error tools cannot be combined with sessionConfigId
72 + await composio.create('u', { tools: { github: ['GITHUB_GET_REPO'] }, experimental });
73 + // @ts-expect-error tags cannot be combined with sessionConfigId
74 + await composio.create('u', { tags: ['readOnlyHint'], experimental });
75 + await composio.create('u', {
76 + // @ts-expect-error customTools cannot be combined with sessionConfigId
77 + experimental: { sessionConfigId: 'sc_1', customTools: [customTool] },
78 + });
79 + await composio.create('u', {
80 + // @ts-expect-error customToolkits cannot be combined with sessionConfigId
81 + experimental: { sessionConfigId: 'sc_1', customToolkits: [customToolkit] },
82 + });
83 +
84 + // @ts-expect-error toolkits cannot be combined with sessionConfigId
85 + await composio.sessions.create('u', { toolkits: ['github'], experimental });
86 + // @ts-expect-error tools cannot be combined with sessionConfigId
87 + await composio.sessions.create('u', { tools: { github: ['GITHUB_GET_REPO'] }, experimental });
88 + // @ts-expect-error tags cannot be combined with sessionConfigId
89 + await composio.sessions.create('u', { tags: ['readOnlyHint'], experimental });
90 + await composio.sessions.create('u', {
91 + // @ts-expect-error customTools cannot be combined with sessionConfigId
92 + experimental: { sessionConfigId: 'sc_1', customTools: [customTool] },
93 + });
94 + await composio.sessions.create('u', {
95 + // @ts-expect-error customToolkits cannot be combined with sessionConfigId
96 + experimental: { sessionConfigId: 'sc_1', customToolkits: [customToolkit] },
97 + });
98 +
99 + // @ts-expect-error toolkits cannot be combined with sessionConfigId
100 + await composio.create('u', { mcp: true, toolkits: ['github'], experimental });
101 + // @ts-expect-error tools cannot be combined with sessionConfigId
102 + await composio.create('u', { mcp: true, tools: { github: ['GITHUB_GET_REPO'] }, experimental });
103 + // @ts-expect-error tags cannot be combined with sessionConfigId
104 + await composio.create('u', { mcp: true, tags: ['readOnlyHint'], experimental });
105 + await composio.create('u', {
106 + mcp: true,
107 + // @ts-expect-error customTools cannot be combined with sessionConfigId
108 + experimental: { sessionConfigId: 'sc_1', customTools: [customTool] },
109 + });
110 + await composio.create('u', {
111 + mcp: true,
112 + // @ts-expect-error customToolkits cannot be combined with sessionConfigId
113 + experimental: { sessionConfigId: 'sc_1', customToolkits: [customToolkit] },
114 + });
115 +}
116 +
117 +async function createFromSavedConfig(): Promise<void> {
118 + // `{ mcp: true }` still surfaces `session.mcp`.
119 + const mcpSession = await composio.create('u', {
120 + mcp: true,
121 + authConfigs: { github: 'ac_1' },
122 + experimental: { sessionConfigId: 'sc_1' },
123 + });
124 + const _url: string = mcpSession.mcp.url;
125 + void _url;
126 +
127 + const session = await composio.sessions.create('u', {
128 + experimental: { sessionConfigId: 'sc_1' },
129 + });
130 + // @ts-expect-error mcp is hidden from the type unless `{ mcp: true }` is passed
131 + void session.mcp;
132 +
133 + // Every per-session field stays allowed, with a trailing requestOptions.
134 + await composio.sessions.create(
135 + 'u',
136 + {
137 + authConfigs: { github: 'ac_1' },
138 + connectedAccounts: { github: 'ca_1' },
139 + manageConnections: false,
140 + sandbox: { enable: false },
141 + multiAccount: { enable: true },
142 + preload: { tools: ['GITHUB_GET_REPO'] },
143 + sessionPreset: SessionPreset.DIRECT_TOOLS,
144 + experimental: { sessionConfigId: 'sc_1', assistivePrompt: { userTimezone: 'UTC' } },
145 + },
146 + { signal: new AbortController().signal }
147 + );
148 + await composio.create('u', {
149 + workbench: { enable: true },
150 + experimental: { sessionConfigId: 'sc_1' },
151 + });
152 +
153 + // An explicit `undefined` counts as absent.
154 + await composio.create('u', { toolkits: undefined, experimental: { sessionConfigId: 'sc_1' } });
155 +}
156 +
157 +async function createInline(): Promise<void> {
158 + await composio.create('u', {
159 + toolkits: ['github'],
160 + tools: { github: ['GITHUB_GET_REPO'] },
161 + tags: ['readOnlyHint'],
162 + experimental: { customTools: [customTool], customToolkits: [customToolkit] },
163 + });
164 + await composio.create('u', { mcp: true, toolkits: { disable: ['gmail'] } });
165 +}
166 +
167 +// On update, a saved Session config replaces toolkits, tools and tags.
168 +// `null` counts as provided.
169 +async function updateRejectsMixedInputs(): Promise<void> {
170 + const session = await composio.use('session_123');
171 + const experimental = { sessionConfigId: 'sc_1' };
172 +
173 + // @ts-expect-error toolkits cannot be combined with sessionConfigId
174 + await session.update({ toolkits: ['gmail'], experimental });
175 + // @ts-expect-error toolkits: null cannot be combined with sessionConfigId
176 + await session.update({ toolkits: null, experimental });
177 + // @ts-expect-error tools cannot be combined with sessionConfigId
178 + await session.update({ tools: { gmail: ['GMAIL_SEND_EMAIL'] }, experimental });
179 + // @ts-expect-error tools: null cannot be combined with sessionConfigId
180 + await session.update({ tools: null, experimental });
181 + // @ts-expect-error tags cannot be combined with sessionConfigId
182 + await session.update({ tags: ['readOnlyHint'], experimental });
183 + // @ts-expect-error tags: null cannot be combined with sessionConfigId
184 + await session.update({ tags: null, experimental });
185 +}
186 +
187 +async function updateWithSavedConfig(): Promise<void> {
188 + const session = await composio.use('session_123');
189 + await session.update({
190 + authConfigs: { github: 'ac_1' },
191 + preload: null,
192 + experimental: { sessionConfigId: 'sc_1', fastMode: true },
193 + });
194 + await session.update({ toolkits: undefined, experimental: { sessionConfigId: 'sc_1' } });
195 + await session.update({ toolkits: ['gmail'], experimental: { fastMode: true } });
196 + await session.update({ toolkits: null, experimental: null });
197 +}
198 +
199 +void reads;
200 +void policyMatchesClient;
201 +void summaryMatchesClient;
202 +void createRejectsMixedInputs;
203 +void createFromSavedConfig;
204 +void createInline;
205 +void updateRejectsMixedInputs;
206 +void updateWithSavedConfig;