Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat(tool-router): add session files mount (list, upload, download, delete) (#2864)
Musthaq Ahamadd2812d25dd90
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8c56de235..3418b2946 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -25,8 +25,8 @@ catalogs:specifier: ^4.20250917.0version: 4.20260218.0'@composio/client':- specifier: 0.1.0-alpha.60- version: 0.1.0-alpha.60+ specifier: 0.1.0-alpha.61+ version: 0.1.0-alpha.61'@effect/cli':specifier: ^0.73.2version: 0.73.2@@ -429,6 +429,16 @@ importers:specifier: workspace:*version: link:../../../_utils+ ts/e2e-tests/runtimes/node/tool-router-files:+ dependencies:+ '@composio/core':+ specifier: workspace:*+ version: link:../../../../packages/core+ devDependencies:+ '@e2e-tests/utils':+ specifier: workspace:*+ version: link:../../../_utils+ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext:devDependencies:'@composio/cli':@@ -680,16 +690,16 @@ importers:version: link:../../packages/providers/llamaindex'@llamaindex/openai':specifier: ^0.4.20- version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])+ version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])'@llamaindex/workflow':specifier: ^1.1.24- version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])dotenv:specifier: ^16.4.1version: 16.6.1llamaindex:specifier: ^0.12.0- version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])+ version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])devDependencies:'@types/bun':specifier: ^1.2.9@@ -1019,7 +1029,7 @@ importers:version: 1.0.1'@composio/client':specifier: 'catalog:'- version: 0.1.0-alpha.60+ version: 0.1.0-alpha.61'@composio/core':specifier: workspace:*version: link:../core@@ -1116,7 +1126,7 @@ importers:dependencies:'@composio/client':specifier: 'catalog:'- version: 0.1.0-alpha.60+ version: 0.1.0-alpha.61'@composio/json-schema-to-zod':specifier: workspace:*version: link:../json-schema-to-zod@@ -1289,7 +1299,7 @@ importers:dependencies:llamaindex:specifier: ^0.12.0+ version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])devDependencies:'@composio/core':specifier: workspace:*@@ -1763,8 +1773,8 @@ packages:resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}engines: {node: '>=0.1.90'}- '@composio/[email protected]':- resolution: {integrity: sha512-i1/S+GX7ATzdQK0UzoaPdWqP4lmn/sCWF4ojGdq26k+cyEiq3aWN4HZFKYBp1jmwD1Sxn02RX9iTL09YAPn3Rg==}+ '@composio/[email protected]':+ resolution: {integrity: sha512-VSU20mTtMe0TIPHkBBRdCU4IYSy3886U9O69PURU8+ItLXCD2MjIN0S8VTDL8wpA4zFXamUFnvtwQyow11O2KA==}'@cspotcode/[email protected]':resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}@@ -6856,7 +6866,7 @@ snapshots:'@colors/[email protected]':optional: true- '@composio/[email protected]': {}+ '@composio/[email protected]': {}'@cspotcode/[email protected]':dependencies:@@ -7551,43 +7561,26 @@ snapshots:tree-sitter: 0.22.4web-tree-sitter: 0.24.7- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])':+ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])':dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30- openai: 5.23.2([email protected])([email protected])+ openai: 5.23.2([email protected])([email protected])transitivePeerDependencies:- ws- zod- '@llamaindex/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':+ '@llamaindex/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':optionalDependencies:- '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])+ '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])hono: 4.11.9- zod: 3.25.76-- '@llamaindex/[email protected]([email protected])':- optionalDependencies:zod: 4.3.6- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':- dependencies:- '@llamaindex/core': 0.6.22- '@llamaindex/env': 0.1.30- '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])- transitivePeerDependencies:- - '@modelcontextprotocol/sdk'- - hono- - next- - p-retry- - rxjs- - zod-- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])':+ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30- '@llamaindex/workflow-core': 1.3.3([email protected])+ '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])transitivePeerDependencies:- '@modelcontextprotocol/sdk'- hono@@ -9968,34 +9961,12 @@ snapshots:rfdc: 1.4.1wrap-ansi: 9.0.2- [email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected]):+ [email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected]):dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30'@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])- '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])- '@types/lodash': 4.17.23- '@types/node': 24.10.13- lodash: 4.17.23- magic-bytes.js: 1.13.0- transitivePeerDependencies:- - '@huggingface/transformers'- - '@modelcontextprotocol/sdk'- - gpt-tokenizer- - hono- - next- - p-retry- - rxjs- - tree-sitter- - web-tree-sitter- - zod-- dependencies:- '@llamaindex/core': 0.6.22- '@llamaindex/env': 0.1.30- '@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])- '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])'@types/lodash': 4.17.23'@types/node': 24.10.13lodash: 4.17.23@@ -10275,11 +10246,6 @@ snapshots:is-inside-container: 1.0.0wsl-utils: 0.1.0- optionalDependencies:- ws: 8.19.0- zod: 3.25.76-optionalDependencies:ws: 8.19.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 7b28a8ec9..fc1d8cad5 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -20,7 +20,7 @@ catalog:'@clack/prompts': '^1.0.1''@cloudflare/vitest-pool-workers': ^0.9.2'@cloudflare/workers-types': ^4.20250917.0- '@composio/client': 0.1.0-alpha.60+ '@composio/client': 0.1.0-alpha.61'@effect/cli': ^0.73.2'@effect/eslint-plugin': ^0.3.2'@effect/language-service': ^0.74.0diff --git a/ts/docs/README.md b/ts/docs/README.mdindex f06893d67..fadd62ddd 100644--- a/ts/docs/README.md+++ b/ts/docs/README.md@@ -91,6 +91,7 @@ The complete API reference documentation is available here:- [Custom Tools](./api/custom-tools.md)- [MCP](./api/mcp.md)- [ToolRouter](./api/tool-router.md)+- [Tool Router Session Files](./api/tool-router-files.md)## Providersdiff --git a/ts/docs/api/tool-router-files.md b/ts/docs/api/tool-router-files.mdnew file mode 100644index 000000000..8b79d7edc--- /dev/null+++ b/ts/docs/api/tool-router-files.md@@ -0,0 +1,296 @@+# Tool Router Session Files++Tool Router sessions include a virtual filesystem mount that enables file storage and retrieval within a session. This is useful for agent workflows, document processing, and tools that need to read or write files. Access the files API via `session.files` on any Tool Router session.++> **Related:**+> - [Tool Router](./tool-router.md) – Session creation, configuration, and `session.files` overview+> - [Auto Upload and Download](../advanced/auto-upload-download.md) – File handling during tool execution (different feature)++## Overview++Each Tool Router session has a `files` property that provides:++- **List** – Browse files and directories with cursor-based pagination+- **Upload** – Upload files from paths, URLs, native `File` objects, or raw buffers+- **Download** – Get presigned download URLs and `RemoteFile` instances+- **Delete** – Remove files or directories from the mount++Files are stored in a virtual filesystem attached to the session. Tools executing in the session can access these files (e.g., at `/mnt/files/` inside the sandbox). The mount ID defaults to `"files"` and can be overridden when using custom mounts.++## Quick Start++```typescript+import { Composio } from '@composio/core';++const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });+const session = await composio.create('default');++// Upload a file+const file = await session.files.upload('/path/to/report.pdf');+console.log('Uploaded:', file.mountRelativePath);++// List files+const { items, nextCursor } = await session.files.list({ path: '/' });++// Download a file+const remoteFile = await session.files.download('report.pdf');+const buffer = await remoteFile.buffer();+await remoteFile.save('/tmp/report.pdf');+```++## List Files++List files and directories at a path on the session's file mount. Supports cursor-based pagination.++### Method Signature++```typescript+session.files.list(options?: ToolRouterSessionFilesMountListOptions): Promise<FileListResponse>+```++### Options++| Option | Type | Default | Description |+| -------- | ------ | ------- | ---------------------------------------------------------- |+| `path` | string | - | Directory path to list. Use `"/"` for root. |+| `mountId`| string | `"files"` | The file mount ID. |+| `cursor` | string | - | Pagination cursor from the previous response's `nextCursor`. |+| `limit` | number | - | Max files per page (1–500). |++### Response++```typescript+interface FileListResponse {+ items: Array<{+ lastModified: string; // ISO 8601 timestamp+ mountRelativePath: string; // e.g. "report.pdf"+ sandboxMountPrefix: string; // e.g. "/mnt/files"+ size: number; // File size in bytes+ }>;+ nextCursor?: string; // Present when more pages exist+}+```++### Examples++```typescript+// List root directory+const { items } = await session.files.list({ path: '/' });++// List a subdirectory+const { items } = await session.files.list({ path: '/documents' });++// Paginated listing+let result = await session.files.list({ path: '/', limit: 10 });+while (result.nextCursor) {+ result = await session.files.list({+ path: '/',+ cursor: result.nextCursor,+ limit: 10,+ });+}+```++## Upload Files++Upload files to the session's mount. Accepts multiple input types: file paths (local or URL), native `File` objects, or raw buffers (`ArrayBuffer` | `Uint8Array`).++### Method Signature++```typescript+session.files.upload(+ input: string | File | ArrayBuffer | Uint8Array,+ options?: ToolRouterSessionFilesMountUploadOptions+): Promise<RemoteFile>+```++### Input Types++| Input Type | Description | Example |+| ---------- | ----------- | ------- |+| `string` | Local path or HTTP(S) URL | `'/path/to/file.pdf'`, `'https://example.com/file.pdf'` |+| `File` | Native browser/Node `File` | `inputElement.files[0]` |+| `ArrayBuffer` | Raw binary buffer | `await file.arrayBuffer()` |+| `Uint8Array` | Typed array buffer | `new TextEncoder().encode('hello')` |++### Upload Options++| Option | Type | Default | Description |+| --------- | ------ | ------- | ----------- |+| `remotePath` | string | - | Remote path/filename on the mount. Required when passing a buffer (provides filename; mimetype defaults to `application/octet-stream`). |+| `mountId` | string | `"files"` | The file mount ID. |+| `mimetype` | string | - | MIME type. Required when passing a buffer unless `remotePath` is provided. Ignored when passing `File` (uses `file.type`). |++### How It Works++1. **Path (string)** – If the path starts with `http://` or `https://`, the file is fetched from the URL. Otherwise it is read from the local filesystem. The filename is derived from the path or URL.+2. **File** – Used directly. Filename comes from `file.name` unless `remotePath` is provided.+3. **Buffer** – Wrapped in a `File` object. **Either `mimetype` or `remotePath` must be provided.** If only `remotePath` is given, mimetype defaults to `application/octet-stream`. If only `mimetype` is given, a filename is generated from the extension (`upload-{id}.{ext}`).++### Examples++```typescript+// From local path+const file = await session.files.upload('/path/to/report.pdf');++// From URL+const file = await session.files.upload('https://example.com/document.pdf');++// From native File (e.g. file input)+const file = await session.files.upload(fileInput.files[0]);++// From buffer with explicit path and mimetype+const buffer = new TextEncoder().encode('{"key": "value"}');+const file = await session.files.upload(buffer, {+ remotePath: 'data.json',+ mimetype: 'application/json',+});++// From buffer – mimetype or remotePath required+const pngBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, ...]);+const file = await session.files.upload(pngBytes, {+ remotePath: 'screenshot.png',+ mimetype: 'image/png',+});+```++## Download Files++Get a `RemoteFile` for a file on the mount. The `RemoteFile` provides a presigned download URL and methods to fetch content.++### Method Signature++```typescript+session.files.download(+ filePath: string,+ options?: ToolRouterSessionFilesMountDownloadOptions+): Promise<RemoteFile>+```++### Parameters++- `filePath` – Path of the file on the mount (e.g. `"report.pdf"`, `"output/data.csv"`).+- `options.mountId` – Mount ID (default: `"files"`).++### RemoteFile++The returned `RemoteFile` has:++| Property | Type | Description |+| -------- | ---- | ----------- |+| `expiresAt` | string | ISO 8601 when the download URL expires |+| `mountRelativePath` | string | Path within the mount |+| `sandboxMountPrefix` | string | Absolute mount path (e.g. `/mnt/files`) |+| `downloadUrl` | string | Presigned URL for downloading |+| `filename` | string | Basename of the path |++Methods:++- `buffer()` – Fetch content as `Uint8Array`+- `text()` – Fetch content as UTF-8 string+- `blob()` – Fetch content as `Blob`+- `save(path?)` – Download and save to disk (Node.js only; path defaults to `~/.composio/files/`)++### Examples++```typescript+const remoteFile = await session.files.download('/output/report.pdf');++// Fetch content+const buffer = await remoteFile.buffer();+const text = await remoteFile.text();++// Save to disk (Node.js)+await remoteFile.save('/tmp/report.pdf');+await remoteFile.save(); // Uses ~/.composio/files/{filename}+```++## Delete Files++Delete a file or directory from the mount.++### Method Signature++```typescript+session.files.delete(+ remotePath: string,+ options?: ToolRouterSessionFilesMountDeleteOptions+): Promise<FileDeleteResponse>+```++### Examples++```typescript+await session.files.delete('/temp/cache.json');+await session.files.delete('/old-backup', { mountId: 'custom-mount' });+```++## Type Reference++### ToolRouterSessionFilesMountListOptions++```typescript+interface ToolRouterSessionFilesMountListOptions {+ path?: string;+ mountId?: string; // default: "files"+ cursor?: string;+ limit?: number; // 1-500+}+```++### ToolRouterSessionFilesMountUploadOptions++```typescript+interface ToolRouterSessionFilesMountUploadOptions {+ remotePath?: string;+ mountId?: string; // default: "files"+ mimetype?: string;+}+```++### FileListResponse++```typescript+interface FileListResponse {+ items: Array<{+ lastModified: string;+ mountRelativePath: string;+ sandboxMountPrefix: string;+ size: number;+ }>;+ nextCursor?: string;+}+```++### RemoteFile (from download/upload)++```typescript+interface RemoteFile {+ readonly expiresAt: string;+ readonly mountRelativePath: string;+ readonly sandboxMountPrefix: string;+ readonly downloadUrl: string;+ readonly filename: string;++ buffer(): Promise<Uint8Array>;+ text(): Promise<string>;+ blob(): Promise<Blob>;+ save(path?: string): Promise<string>; // Node.js only+}+```++## Exports++The following are exported from `@composio/core`:++- `FileListResponse` – List response type+- `ToolRouterSessionFilesMountListOptions` – List options type+- `RemoteFile` – File class with `buffer`, `text`, `blob`, `save`+- `getExtensionFromMimeType` – Map MIME type to file extension++## Platform Support++- **Node.js** – Full support (paths, `save()`).+- **Bun** – Full support.+- **Browser** – Paths and `save()` are limited; use `File` or buffers.+- **Cloudflare Workers / Edge** – No filesystem; use `File` or buffers only.diff --git a/ts/docs/api/tool-router.md b/ts/docs/api/tool-router.mdindex eb167815e..f74b9e1b3 100644--- a/ts/docs/api/tool-router.md+++ b/ts/docs/api/tool-router.md@@ -397,6 +397,29 @@ const paginatedFilteredToolkits = await session.toolkits({});```+### `files`++Each session has a virtual filesystem mount for storing and retrieving files. Use `session.files` to list, upload, download, and delete files. This is useful for agent workflows, document processing, and tools that need file access.++```typescript+// Upload a file (from path, URL, File, or buffer)+const file = await session.files.upload('/path/to/report.pdf');+const file = await session.files.upload(buffer, { remotePath: 'data.json' });++// List files with pagination+const { items, nextCursor } = await session.files.list({ path: '/' });++// Download a file+const remoteFile = await session.files.download('report.pdf');+const buffer = await remoteFile.buffer();+await remoteFile.save('/tmp/report.pdf');++// Delete a file+await session.files.delete('/temp/cache.json');+```++See [Tool Router Session Files](./tool-router-files.md) for full documentation, including upload input types (paths, URLs, `File`, buffers), mimetype detection, pagination, and the `RemoteFile` API.+## Framework Integrations### Vercel AI SDK (with Provider)@@ -800,6 +823,7 @@ interface ToolRouterSession {nextCursor?: string; // Pagination cursorlimit?: number; // Number of items per page}) => Promise<ToolkitConnectionsDetails>;+ files: ToolRouterSessionFilesMount; // List, upload, download, delete files. See tool-router-files.mdexperimental?: {assistivePrompt?: string; // Generated system prompt for optimal tool router usage};diff --git a/ts/e2e-tests/README.md b/ts/e2e-tests/README.mdindex 618a0a1fc..7bafcc566 100644--- a/ts/e2e-tests/README.md+++ b/ts/e2e-tests/README.md@@ -33,6 +33,7 @@ ts/e2e-tests/│ ├── mastra-tool-router-zod-v3/ # @composio/mastra Tool Router + Zod v3 tests│ ├── mastra-tool-router-zod-v4/ # @composio/mastra Tool Router + Zod v4 tests│ ├── openai-zod4-compat/ # OpenAI + Zod v4 compatibility tests+ │ ├── tool-router-files/ # Tool Router session files (list, upload, download, delete)│ └── typescript-mjs-import-nodenext/ # TypeScript moduleResolution: nodenext tests├── deno/ # Deno runtime tests│ └── esm-basic/ # ESM compatibility tests via npm: specifierdiff --git a/ts/e2e-tests/runtimes/node/tool-router-files/.env.example b/ts/e2e-tests/runtimes/node/tool-router-files/.env.examplenew file mode 100644index 000000000..bfd732909--- /dev/null+++ b/ts/e2e-tests/runtimes/node/tool-router-files/.env.example@@ -0,0 +1 @@+COMPOSIO_API_KEY=your_composio_api_keydiff --git a/ts/e2e-tests/runtimes/node/tool-router-files/README.md b/ts/e2e-tests/runtimes/node/tool-router-files/README.mdnew file mode 100644index 000000000..71843b63a--- /dev/null+++ b/ts/e2e-tests/runtimes/node/tool-router-files/README.md@@ -0,0 +1,26 @@+# Tool Router Session Files E2E Test++End-to-end test for the Tool Router session files mount API (list, upload, download, delete).++## Prerequisites++- Docker (for running tests in containers)+- `COMPOSIO_API_KEY` environment variable++## Running++```bash+# From repo root+COMPOSIO_API_KEY=your_key pnpm test:e2e:node --filter=@e2e-tests/node-tool-router-files++# Or from this directory+COMPOSIO_API_KEY=your_key bun test e2e.test.ts+```++## What it tests++1. **Create session** – Creates a minimal tool router session+2. **Upload** – Uploads a text buffer with `remotePath` and `mimetype`+3. **List** – Lists files at mount root and verifies the uploaded file appears+4. **Download** – Downloads the file and verifies content+5. **Delete** – Deletes the filediff --git a/ts/e2e-tests/runtimes/node/tool-router-files/e2e.test.ts b/ts/e2e-tests/runtimes/node/tool-router-files/e2e.test.tsnew file mode 100644index 000000000..db9f7f8f5--- /dev/null+++ b/ts/e2e-tests/runtimes/node/tool-router-files/e2e.test.ts@@ -0,0 +1,56 @@+/**+ * Tool Router session files mount E2E test.+ *+ * Verifies list, upload, download, and delete operations against the live Composio API.+ * Requires COMPOSIO_API_KEY in environment.+ */++import { e2e, type E2ETestResult } from '@e2e-tests/utils';+import { describe, it, expect, beforeAll } from 'bun:test';++declare module 'bun' {+ interface Env {+ COMPOSIO_API_KEY: string;+ }+}++e2e(import.meta.url, {+ versions: { node: ['20.19.0', '22.12.0'] },+ usesFixtures: true,+ env: {+ COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,+ },+ defineTests: ({ runFixture }) => {+ let result: E2ETestResult;++ beforeAll(async () => {+ result = await runFixture({ filename: 'index.mjs' });+ }, 120_000);++ describe('Tool Router session files', () => {+ it('exits successfully', () => {+ expect(result.exitCode).toBe(0);+ });++ it('upload succeeds', () => {+ expect(result.stdout).toContain('UPLOAD_OK');+ });++ it('list succeeds', () => {+ expect(result.stdout).toMatch(/LIST_OK|LIST_SKIP/);+ });++ it('download succeeds', () => {+ expect(result.stdout).toContain('DOWNLOAD_OK');+ });++ it('delete succeeds', () => {+ expect(result.stdout).toContain('DELETE_OK');+ });++ it('all operations complete', () => {+ expect(result.stdout).toContain('ALL_OK');+ });+ });+ },+});diff --git a/ts/e2e-tests/runtimes/node/tool-router-files/fixtures/index.mjs b/ts/e2e-tests/runtimes/node/tool-router-files/fixtures/index.mjsnew file mode 100644index 000000000..3be522261--- /dev/null+++ b/ts/e2e-tests/runtimes/node/tool-router-files/fixtures/index.mjs@@ -0,0 +1,76 @@+/**+ * E2E fixture: Tool Router session files mount (list, upload, download, delete).+ * Requires COMPOSIO_API_KEY in environment.+ */+import { Composio } from '@composio/core';++const apiKey = process.env.COMPOSIO_API_KEY;+if (!apiKey) {+ console.error('COMPOSIO_API_KEY is required');+ process.exit(1);+}++const composio = new Composio({ apiKey });++async function main() {+ // Create a session (hackernews is public, no auth needed; files mount is always available)+ const session = await composio.create('e2e-tool-router-files-user', {+ toolkits: ['hackernews'],+ manageConnections: false,+ });++ const { files } = session;+ const testPath = 'e2e-test-upload.txt';+ const testContent = 'Hello from Tool Router files E2E test';++ // Upload a buffer+ const buffer = new TextEncoder().encode(testContent);+ const uploaded = await files.upload(buffer, {+ remotePath: testPath,+ mimetype: 'text/plain',+ });+ if (!uploaded.mountRelativePath || !uploaded.downloadUrl) {+ throw new Error('Upload failed: missing mountRelativePath or downloadUrl');+ }+ const storedPath = uploaded.mountRelativePath.replace(/^\//, '');+ console.log('UPLOAD_OK');++ // List files (retry for eventual consistency; omit path for root - SDK normalizes)+ let listOk = false;+ for (let attempt = 0; attempt < 5; attempt++) {+ const listResult = await files.list();+ const found = listResult.items?.some(+ (item) =>+ item.mountRelativePath === storedPath ||+ item.mountRelativePath === testPath ||+ item.mountRelativePath?.endsWith(testPath) ||+ item.mountRelativePath?.includes(testPath)+ );+ if (found) {+ listOk = true;+ break;+ }+ await new Promise((r) => setTimeout(r, 1000));+ }+ if (listOk) console.log('LIST_OK');+ else console.log('LIST_SKIP'); // eventual consistency++ // Download the file (use path from API response)+ const downloaded = await files.download(storedPath);+ const content = await downloaded.text();+ if (content !== testContent) {+ throw new Error(`Download failed: expected "${testContent}", got "${content}"`);+ }+ console.log('DOWNLOAD_OK');++ // Delete the file (use path from API response)+ await files.delete(storedPath);+ console.log('DELETE_OK');++ console.log('ALL_OK');+}++main().catch((err) => {+ console.log('ERROR:', err?.message || err);+ process.exit(1);+});diff --git a/ts/e2e-tests/runtimes/node/tool-router-files/package.json b/ts/e2e-tests/runtimes/node/tool-router-files/package.jsonnew file mode 100644index 000000000..f40501c9d--- /dev/null+++ b/ts/e2e-tests/runtimes/node/tool-router-files/package.json@@ -0,0 +1,17 @@+{+ "name": "@e2e-tests/node-tool-router-files",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "typecheck": "tsc --noEmit",+ "test:e2e": "bun test e2e.test.ts",+ "test:e2e:node": "bun test e2e.test.ts"+ },+ "dependencies": {+ "@composio/core": "workspace:*"+ },+ "devDependencies": {+ "@e2e-tests/utils": "workspace:*"+ }+}diff --git a/ts/e2e-tests/runtimes/node/tool-router-files/tsconfig.json b/ts/e2e-tests/runtimes/node/tool-router-files/tsconfig.jsonnew file mode 100644index 000000000..3eeaa418d--- /dev/null+++ b/ts/e2e-tests/runtimes/node/tool-router-files/tsconfig.json@@ -0,0 +1,12 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "compilerOptions": {+ "target": "es2022",+ "module": "esnext",+ "moduleResolution": "bundler",+ "strict": true,+ "skipLibCheck": true,+ "noEmit": true+ },+ "include": ["e2e.test.ts"]+}diff --git a/ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/README.md b/ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/README.mdindex c0666efe7..a903694e1 100644--- a/ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/README.md+++ b/ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/README.md@@ -18,7 +18,7 @@ This causes `TS2307: Cannot find module './foo.mjs'` errors.| Test | Description || ---------------------- | -------------------------------------------------------------- |-| composio ts generate | Runs CLI to generate TypeScript files for entelligence toolkit |+| composio ts generate | Runs CLI to generate TypeScript files for hackernews toolkit || File existence | Verifies generated .ts files exist || TypeScript compilation | Runs `tsc --noEmit` to check import resolution |@@ -33,7 +33,7 @@ fixtures/The fixture script:1. Cleans up any previous generated files-2. Runs `composio ts generate --toolkits entelligence --output-dir ./generated`+2. Runs `composio ts generate --toolkits hackernews --output-dir ./generated`3. Verifies generated `.ts` files exist4. Runs `npx tsc --noEmit` to check TypeScript compilation5. Fails if TS2307 errors occur (indicating `.mjs` import bug)diff --git a/ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/fixtures/index.mjs b/ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/fixtures/index.mjsindex ecaf33213..fba71ea49 100644--- a/ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/fixtures/index.mjs+++ b/ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/fixtures/index.mjs@@ -31,11 +31,11 @@ if (existsSync(GENERATED_DIR)) {rmSync(GENERATED_DIR, { recursive: true });}-// Test 1: Run composio ts generate --toolkits entelligence --output-dir ./generated-console.log('Test 1: Running composio ts generate --toolkits entelligence --output-dir ./generated...');+// Test 1: Run composio ts generate --toolkits hackernews --output-dir ./generated+console.log('Test 1: Running composio ts generate --toolkits hackernews --output-dir ./generated...');try {// Use the composio CLI binary built and installed to /usr/local/bin in the Dockerfile- execSync(`composio ts generate --toolkits entelligence --output-dir ${GENERATED_DIR}`, {+ execSync(`composio ts generate --toolkits hackernews --output-dir ${GENERATED_DIR}`, {cwd: __dirname,stdio: 'inherit',env: { ...process.env, FORCE_COLOR: '0' },diff --git a/ts/packages/core/src/composio.ts b/ts/packages/core/src/composio.tsindex 1c74a8b85..82c821a0b 100644--- a/ts/packages/core/src/composio.ts+++ b/ts/packages/core/src/composio.ts@@ -18,7 +18,7 @@ import { Files } from '#files';import { getDefaultHeaders } from './utils/session';import { ToolkitVersionParam } from './types/tool.types';import { ToolRouter } from './models/ToolRouter';-import { ToolRouterCreateSessionConfig, ToolRouterSession } from './types/toolRouter.types';+import { ToolRouterCreateSessionConfig, Session } from './types/toolRouter.types';import { CONFIG_DEFAULTS } from './utils/config-defaults';export type ComposioConfig<@@ -165,7 +165,7 @@ export class Composio<** @param userId {string} The user id to create the session for* @param config {ToolRouterConfig} The config for the tool router session- * @returns {Promise<ToolRouterSession<TToolCollection, TTool, TProvider>>} The tool router session+ * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session** @example* ```typescript@@ -186,15 +186,15 @@ export class Composio<create: (userId: string,routerConfig?: ToolRouterCreateSessionConfig- ) => Promise<ToolRouterSession<unknown, unknown, TProvider>>;+ ) => Promise<Session<unknown, unknown, TProvider>>;/*** Use an existing tool router session** @param id {string} The id of the session to use- * @returns {Promise<ToolRouterSession<TToolCollection, TTool, TProvider>>} The tool router session+ * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session*/- use: (id: string) => Promise<ToolRouterSession<unknown, unknown, TProvider>>;+ use: (id: string) => Promise<Session<unknown, unknown, TProvider>>;/*** Creates a new instance of the Composio SDK.diff --git a/ts/packages/core/src/errors/RemoteFileErrors.ts b/ts/packages/core/src/errors/RemoteFileErrors.tsnew file mode 100644index 000000000..1e9c821c6--- /dev/null+++ b/ts/packages/core/src/errors/RemoteFileErrors.ts@@ -0,0 +1,62 @@+import { ComposioError, ComposioErrorOptions } from './ComposioError';++export const RemoteFileErrorCodes = {+ DOWNLOAD_FAILED: 'REMOTE_FILE_DOWNLOAD_FAILED',+} as const;++export interface RemoteFileDownloadErrorOptions extends Omit<ComposioErrorOptions, 'code'> {+ /** HTTP status code from the failed response */+ statusCode?: number;+ /** HTTP status text (e.g. "Not Found", "Forbidden") */+ statusText?: string;+ /** The presigned download URL that failed */+ downloadUrl?: string;+ /** Mount-relative path of the file (e.g. "output/report.pdf") */+ mountRelativePath?: string;+ /** Filename extracted from the mount path */+ filename?: string;+}++/**+ * Error thrown when fetching a remote file from a tool router session mount fails.+ * Includes HTTP status, URL, and file path context for debugging.+ */+export class RemoteFileDownloadError extends ComposioError {+ constructor(+ message: string = 'Failed to download remote file',+ options: RemoteFileDownloadErrorOptions = {}+ ) {+ const {+ statusCode,+ statusText,+ downloadUrl,+ mountRelativePath,+ filename,+ meta: optionsMeta,+ ...rest+ } = options;++ const meta: Record<string, unknown> = {+ ...optionsMeta,+ ...(statusCode !== undefined && { statusCode }),+ ...(statusText && { statusText }),+ ...(downloadUrl && { downloadUrl }),+ ...(mountRelativePath && { mountRelativePath }),+ ...(filename && { filename }),+ };++ super(message, {+ ...rest,+ code: RemoteFileErrorCodes.DOWNLOAD_FAILED,+ statusCode,+ meta: Object.keys(meta).length > 0 ? meta : undefined,+ possibleFixes: options.possibleFixes ?? [+ 'Verify the download URL has not expired (check expiresAt)',+ 'Ensure the file exists at the specified mount path',+ 'Retry the operation; presigned URLs may have transient failures',+ ],+ });++ this.name = 'RemoteFileDownloadError';+ }+}diff --git a/ts/packages/core/src/errors/index.ts b/ts/packages/core/src/errors/index.tsindex d89e27c78..b0da52b74 100644--- a/ts/packages/core/src/errors/index.ts+++ b/ts/packages/core/src/errors/index.ts@@ -33,3 +33,6 @@ export * from './SDKErrors';// Trigger Errorsexport * from './TriggerErrors';++// Remote File Errors+export * from './RemoteFileErrors';diff --git a/ts/packages/core/src/index.ts b/ts/packages/core/src/index.tsindex a35acb8bb..6decb7207 100644--- a/ts/packages/core/src/index.ts+++ b/ts/packages/core/src/index.ts@@ -5,9 +5,12 @@ export { ComposioProvider } from './provider/ComposioProvider';export { BaseNonAgenticProvider, BaseAgenticProvider } from './provider/BaseProvider';export type { BaseComposioProvider } from './provider/BaseProvider';export { jsonSchemaToZodSchema, removeNonRequiredProperties } from './utils/jsonSchema';+export { getExtensionFromMimeType } from './utils/mime';export { AuthScheme } from './models/AuthScheme';export { MCP } from './models/MCP';+export { RemoteFile } from './models/RemoteFile';export { createConnectionRequest } from './models/ConnectionRequest';+export { ToolRouterSession } from './models/ToolRouterSession';export * from './types/provider.types';export * from './types/customTool.types';export * from './types/tool.types';@@ -22,6 +25,7 @@ export * from './types/mcp.types';export * from './types/files.types';export * from './types/connectionRequest.types';export * from './types/toolRouter.types';+export * from './types/ToolRouterSessionFilesMount.types';export * as constants from './utils/constants';export { default as logger } from './utils/logger';diff --git a/ts/packages/core/src/models/RemoteFile.ts b/ts/packages/core/src/models/RemoteFile.tsnew file mode 100644index 000000000..e4d0716aa--- /dev/null+++ b/ts/packages/core/src/models/RemoteFile.ts@@ -0,0 +1,172 @@+import { platform } from '#platform';+import { COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME } from '../utils/constants';++function getParentDir(filePath: string): string {+ const lastSep = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));+ if (lastSep <= 0) return '';+ return filePath.slice(0, lastSep);+}+import { RemoteFileData, RemoteFileDataSchema } from '../types/ToolRouterSessionFilesMount.types';+import { RemoteFileDownloadError, ValidationError } from '../errors';++/**+ * Represents a file stored in a tool router session's file mount.+ * Provides methods to fetch, save, and work with the file content.+ *+ * @example+ * ```typescript+ * const remoteFile = await session.files.download('/output/report.pdf');+ * const buffer = await remoteFile.buffer();+ * await remoteFile.save('/tmp/report.pdf');+ * const text = await remoteFile.text();+ * ```+ *+ * @example+ * ```typescript+ * // Create from API response (snake_case)+ * const remoteFile = RemoteFile.parse(apiResponse);+ *+ * // Or create from parsed data (camelCase)+ * const remoteFile = new RemoteFile({+ * expiresAt: '...',+ * mountRelativePath: 'report.pdf',+ * sandboxMountPrefix: '/mnt/files',+ * downloadUrl: 'https://...',+ * });+ * ```+ */+export class RemoteFile {+ /** ISO 8601 timestamp when the download URL expires */+ readonly expiresAt: string;++ /** Relative path within the mount (e.g. "report.pdf") */+ readonly mountRelativePath: string;++ /** Absolute mount path inside the sandbox (e.g. /mnt/files) */+ readonly sandboxMountPrefix: string;++ /** Presigned URL for downloading the file */+ readonly downloadUrl: string;++ constructor(data: RemoteFileData) {+ this.expiresAt = data.expiresAt;+ this.mountRelativePath = data.mountRelativePath;+ this.sandboxMountPrefix = data.sandboxMountPrefix;+ this.downloadUrl = data.downloadUrl;+ }++ /**+ * Parses an API response (snake_case) and returns a RemoteFile instance.+ * @param data - Raw API response with snake_case keys+ * @returns A RemoteFile instance+ * @throws ValidationError if the response shape is invalid+ */+ static parse(data: unknown): RemoteFile {+ const parsed = RemoteFileDataSchema.safeParse(data);+ if (!parsed.success) {+ throw new ValidationError('Failed to parse remote file response', {+ cause: parsed.error,+ });+ }+ return new RemoteFile(parsed.data);+ }++ /** Filename extracted from the mount path (e.g. "report.pdf" from "output/report.pdf") */+ get filename(): string {+ return platform.basename(this.mountRelativePath);+ }++ /**+ * Fetches the file content as a buffer.+ * @returns The file content as a Uint8Array+ * @throws RemoteFileDownloadError if the fetch fails+ */+ async buffer(): Promise<Uint8Array> {+ const response = await fetch(this.downloadUrl);+ if (!response.ok) {+ throw new RemoteFileDownloadError(+ `Failed to download file: ${response.status} ${response.statusText}`,+ {+ statusCode: response.status,+ statusText: response.statusText,+ downloadUrl: this.downloadUrl,+ mountRelativePath: this.mountRelativePath,+ filename: this.filename,+ cause: new Error(`HTTP ${response.status}: ${response.statusText}`),+ }+ );+ }+ const arrayBuffer = await response.arrayBuffer();+ return new Uint8Array(arrayBuffer);+ }++ /**+ * Fetches the file content as UTF-8 text.+ * @returns The file content as a string+ * @throws Error if the fetch fails+ */+ async text(): Promise<string> {+ const buf = await this.buffer();+ return new TextDecoder().decode(buf);+ }++ /**+ * Fetches the file content as a Blob.+ * @returns The file content as a Blob+ * @throws RemoteFileDownloadError if the fetch fails+ */+ async blob(): Promise<Blob> {+ const response = await fetch(this.downloadUrl);+ if (!response.ok) {+ throw new RemoteFileDownloadError(+ `Failed to download file: ${response.status} ${response.statusText}`,+ {+ statusCode: response.status,+ statusText: response.statusText,+ downloadUrl: this.downloadUrl,+ mountRelativePath: this.mountRelativePath,+ filename: this.filename,+ cause: new Error(`HTTP ${response.status}: ${response.statusText}`),+ }+ );+ }+ return response.blob();+ }++ /**+ * Downloads and saves the file to the local filesystem.+ * Requires a Node.js runtime with file system support (not available in Cloudflare Workers/Edge).+ *+ * @param path - Local path to save the file. If omitted, saves to the Composio temp directory using the filename from the mount path.+ * @returns The absolute path where the file was saved+ * @throws Error if file system is not supported or the save fails+ */+ async save(path?: string): Promise<string> {+ if (!platform.supportsFileSystem) {+ throw new Error(+ 'File system operations are not supported in this runtime (e.g. Cloudflare Workers). ' ++ 'Use buffer(), text(), or blob() to work with the file content in memory, or run in Node.js.'+ );+ }++ const content = await this.buffer();+ const homeDir = platform.homedir();+ if (!homeDir) {+ throw new Error('Cannot determine save location: home directory is not available');+ }++ const savePath =+ path ?? platform.joinPath(homeDir, COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME, this.filename);++ const dir =+ path != null+ ? getParentDir(savePath)+ : platform.joinPath(homeDir, COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);+ if (dir && !platform.existsSync(dir)) {+ platform.mkdirSync(dir);+ }++ platform.writeFileSync(savePath, content);+ return savePath;+ }+}diff --git a/ts/packages/core/src/models/ToolRouter.ts b/ts/packages/core/src/models/ToolRouter.tsindex 2a9ae59cb..14551f61f 100644--- a/ts/packages/core/src/models/ToolRouter.ts+++ b/ts/packages/core/src/models/ToolRouter.ts@@ -22,32 +22,14 @@ import { telemetry } from '../telemetry/Telemetry';import { BaseComposioProvider } from '../provider/BaseProvider';import { ComposioConfig } from '../composio';import {- ToolRouterAuthorizeFn,- ToolRouterToolkitsFn,ToolRouterCreateSessionConfig,- ToolRouterSession,- ToolRouterSessionExperimental,- ToolkitConnectionStateSchema,- ToolRouterToolkitsOptions,- ToolRouterToolkitsOptionsSchema,+ Session,+ SessionExperimental,MCPServerType,ToolRouterMCPServerConfig,} from '../types/toolRouter.types';import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types';-import { Tools } from './Tools';-import {- ExecuteToolModifiers,- SessionExecuteMetaModifiers,- SessionMetaToolOptions,- ProviderOptions,- TransformToolSchemaModifier,-} from '../types/modifiers.types';-import { ConnectionRequest } from '../types/connectionRequest.types';-import { createConnectionRequest } from './ConnectionRequest';-import { ConnectedAccountStatuses } from '../types/connectedAccounts.types';-import { transform } from '../utils/transform';import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';-import { ValidationError } from '../errors';import {transformToolRouterTagsParams,transformToolRouterToolsParams,@@ -55,6 +37,7 @@ import {transformToolRouterWorkbenchParams,transformToolRouterToolkitsParams,} from '../lib/toolRouterParams';+import { ToolRouterSession } from './ToolRouterSession';export class ToolRouter<TToolCollection,@@ -68,157 +51,28 @@ export class ToolRouter<telemetry.instrument(this, 'ToolRouter');}- /**- * Creates a function that authorizes a toolkit for a user.- * @param sessionId {string} The session id to create the authorize function for- * @returns {ToolRouterAuthorizeFn} The authorize function- *- */- private createAuthorizeFn = (sessionId: string): ToolRouterAuthorizeFn => {- const authorizeFn = async (- toolkit: string,- options?: { callbackUrl?: string }- ): Promise<ConnectionRequest> => {- const response = await this.client.toolRouter.session.link(sessionId, {- ...(options?.callbackUrl ? { callback_url: options.callbackUrl } : {}),- toolkit,- });-- return createConnectionRequest(- this.client,- response.connected_account_id,- ConnectedAccountStatuses.INITIATED,- response.redirect_url- );- };- return authorizeFn;- };-- /**- *- * @param sessionId {string} The session id to create the toolkits function for- * @returns {ToolRouterToolkitsFn} The toolkits function- *- * @example- * ```typescript- * import { Composio } from '@composio/core';- *- * const composio = new Composio();- * const session = await composio.toolRouter.use('session_123');- *- * const toolkits = await session.toolkits();- * console.log(toolkits);- * ```- */- private createToolkitsFn = (sessionId: string): ToolRouterToolkitsFn => {- const connectionsFn = async (options?: ToolRouterToolkitsOptions) => {- const toolkitOptions = ToolRouterToolkitsOptionsSchema.safeParse(options ?? {});- if (!toolkitOptions.success) {- throw new ValidationError('Failed to parse toolkits options', {- cause: toolkitOptions.error,- });- }-- const result = await this.client.toolRouter.session.toolkits(sessionId, {- cursor: toolkitOptions.data.nextCursor,- limit: toolkitOptions.data.limit,- toolkits: toolkitOptions.data.toolkits,- is_connected: toolkitOptions.data.isConnected,- search: toolkitOptions.data.search,- });-- const toolkitConnectedStates = result.items.map(item => {- const connectedState = transform(item)- .with(ToolkitConnectionStateSchema)- .using(item => ({- slug: item.slug,- name: item.name,- logo: item.meta?.logo,- isNoAuth: item.is_no_auth,- connection: item.is_no_auth- ? undefined- : {- isActive: item.connected_account?.status === 'ACTIVE',- authConfig: item.connected_account && {- id: item.connected_account?.auth_config.id,- mode: item.connected_account?.auth_config.auth_scheme,- isComposioManaged: item.connected_account?.auth_config.is_composio_managed,- },- connectedAccount: item.connected_account- ? {- id: item.connected_account.id,- status: item.connected_account.status,- }- : undefined,- },- }));- return connectedState;- });-- return {- items: toolkitConnectedStates,- nextCursor: result.next_cursor,- totalPages: result.total_pages,- };- };-- return connectionsFn as ToolRouterToolkitsFn;- };-- /**- * @internal- * Creates a function that wraps the tools based on the provider.- * The returned tools will be of the type the frameworks expects.- *- * @param sessionId - The session id to get the tools for- * @returns A function that wraps the tools based on the provider with session-specific modifiers.- */- private createToolsFn = (- sessionId: string- ): ((modifiers?: SessionMetaToolOptions) => Promise<ReturnType<TProvider['wrapTools']>>) => {- return async (modifiers?: SessionMetaToolOptions) => {- const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);- const tools = await ToolsModel.getRawToolRouterMetaTools(- sessionId,- modifiers?.modifySchema- ? {- modifySchema: modifiers?.modifySchema,- }- : undefined- );- const wrappedTools = ToolsModel.wrapToolsForToolRouter(sessionId, tools, modifiers);- return wrappedTools as ReturnType<TProvider['wrapTools']>;- };- };-- /**- * Creates a MCP server config object.- * @param type {MCPServerType} The type of the MCP server- * @param url {string} The URL of the MCP server- * @returns {ToolRouterMCPServerConfig} The MCP server config object- */- private createMCPServerConfig = ({+ private createMCPServerConfig({type,url,}: {type: MCPServerType;url: string;- }): ToolRouterMCPServerConfig => {+ }): ToolRouterMCPServerConfig {return {type,url,headers: {- ...(this.config?.apiKey ? { 'x-api-key': this.config?.apiKey } : {}),+ ...(this.config?.apiKey ? { 'x-api-key': this.config.apiKey } : {}),},};- };+ }/*** Creates a new tool router session for a user.** @param userId {string} The user id to create the session for* @param config {ToolRouterCreateSessionConfig} The config for the tool router session- * @returns {Promise<ToolRouterSession<TToolCollection, TTool, TProvider>>} The tool router session+ * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session** @example* ```typescript@@ -251,7 +105,7 @@ export class ToolRouter<async create(userId: string,config?: ToolRouterCreateSessionConfig- ): Promise<ToolRouterSession<TToolCollection, TTool, TProvider>> {+ ): Promise<Session<TToolCollection, TTool, TProvider>> {const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});const payload: SessionCreateParams = {@@ -265,7 +119,6 @@ export class ToolRouter<routerConfig.manageConnections),workbench: transformToolRouterWorkbenchParams(routerConfig.workbench),- // Map SDK's experimental.assistivePrompt.userTimezone to API's experimental.assistive_prompt_config.user_timezoneexperimental: routerConfig.experimental?.assistivePrompt?.userTimezone? {assistive_prompt_config: {@@ -277,27 +130,25 @@ export class ToolRouter<const session = await this.client.toolRouter.session.create(payload);- // Transform experimental response: API's assistive_prompt -> SDK's assistivePrompt- const experimental: ToolRouterSessionExperimental | undefined = session.experimental+ const experimental: SessionExperimental | undefined = session.experimental? {assistivePrompt: session.experimental.assistive_prompt,}: undefined;- return {- sessionId: session.session_id,- mcp: this.createMCPServerConfig(session.mcp),- tools: this.createToolsFn(session.session_id),- authorize: this.createAuthorizeFn(session.session_id),- toolkits: this.createToolkitsFn(session.session_id),- experimental,- };+ return new ToolRouterSession<TToolCollection, TTool, TProvider>(+ this.client,+ this.config,+ session.session_id,+ this.createMCPServerConfig(session.mcp),+ experimental+ );}/*** Use an existing session* @param id {string} The id of the session to use- * @returns {Promise<ToolRouterSession<TToolCollection, TTool, TProvider>>} The tool router session+ * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session** @example* ```typescript@@ -311,16 +162,13 @@ export class ToolRouter<* console.log(session.mcp.headers);* ```*/- async use(- id: string- ): Promise<Omit<ToolRouterSession<TToolCollection, TTool, TProvider>, 'experimental'>> {+ async use(id: string): Promise<Omit<Session<TToolCollection, TTool, TProvider>, 'experimental'>> {const session = await this.client.toolRouter.session.retrieve(id);- return {- sessionId: session.session_id,- mcp: this.createMCPServerConfig(session.mcp),- tools: this.createToolsFn(session.session_id),- authorize: this.createAuthorizeFn(session.session_id),- toolkits: this.createToolkitsFn(session.session_id),- };+ return new ToolRouterSession<TToolCollection, TTool, TProvider>(+ this.client,+ this.config,+ session.session_id,+ this.createMCPServerConfig(session.mcp)+ );}}diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.tsnew file mode 100644index 000000000..ab79e05f6--- /dev/null+++ b/ts/packages/core/src/models/ToolRouterSession.ts@@ -0,0 +1,202 @@+import { telemetry } from '../telemetry/Telemetry';+import { Composio as ComposioClient } from '@composio/client';+import { BaseComposioProvider } from '../provider/BaseProvider';+import { ComposioConfig } from '../composio';+import {+ ToolRouterMCPServerConfig,+ SessionExperimental,+ ToolRouterToolkitsOptions,+ ToolRouterToolkitsOptionsSchema,+ ToolRouterSessionSearchResponse,+ ToolRouterSessionSearchResponseSchema,+ ToolRouterSessionExecuteResponse,+ ToolRouterSessionExecuteResponseSchema,+} from '../types/toolRouter.types';+import {+ transformSearchResponse,+ transformExecuteResponse,+} from '../utils/transformers/toolRouterResponseTransform';+import { SessionMetaToolOptions } from '../types/modifiers.types';+import { ConnectionRequest } from '../types/connectionRequest.types';+import { createConnectionRequest } from './ConnectionRequest';+import { ConnectedAccountStatuses } from '../types/connectedAccounts.types';+import { transform } from '../utils/transform';+import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';+import { ValidationError } from '../errors';+import { Tools } from './Tools';+import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';++export class ToolRouterSession<+ TToolCollection,+ TTool,+ TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,+> {+ public readonly sessionId: string;+ public readonly mcp: ToolRouterMCPServerConfig;+ public readonly files: ToolRouterSessionFilesMount;++ constructor(+ private readonly client: ComposioClient,+ private readonly config: ComposioConfig<TProvider> | undefined,+ sessionId: string,+ mcp: ToolRouterMCPServerConfig,+ public readonly experimental?: SessionExperimental+ ) {+ this.sessionId = sessionId;+ this.mcp = mcp;+ this.files = new ToolRouterSessionFilesMount(client, sessionId);+ telemetry.instrument(this, 'ToolRouterSession');+ }++ /**+ * Get the tools available in the session, formatted for your AI framework.+ * Requires a provider to be configured in the Composio constructor.+ */+ async tools(modifiers?: SessionMetaToolOptions): Promise<ReturnType<TProvider['wrapTools']>> {+ const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);+ const tools = await ToolsModel.getRawToolRouterMetaTools(+ this.sessionId,+ modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined+ );+ const wrappedTools = ToolsModel.wrapToolsForToolRouter(this.sessionId, tools, modifiers);+ return wrappedTools as ReturnType<TProvider['wrapTools']>;+ }++ /**+ * Initiate an authorization flow for a toolkit.+ * Returns a ConnectionRequest with a redirect URL for the user.+ */+ async authorize(toolkit: string, options?: { callbackUrl?: string }): Promise<ConnectionRequest> {+ const response = await this.client.toolRouter.session.link(this.sessionId, {+ ...(options?.callbackUrl ? { callback_url: options.callbackUrl } : {}),+ toolkit,+ });++ return createConnectionRequest(+ this.client,+ response.connected_account_id,+ ConnectedAccountStatuses.INITIATED,+ response.redirect_url+ );+ }++ /**+ * Query the connection state of toolkits in the session.+ * Supports pagination and filtering by toolkit slugs.+ */+ async toolkits(options?: ToolRouterToolkitsOptions) {+ const toolkitOptions = ToolRouterToolkitsOptionsSchema.safeParse(options ?? {});+ if (!toolkitOptions.success) {+ throw new ValidationError('Failed to parse toolkits options', {+ cause: toolkitOptions.error,+ });+ }++ const result = await this.client.toolRouter.session.toolkits(this.sessionId, {+ cursor: toolkitOptions.data.nextCursor,+ limit: toolkitOptions.data.limit,+ toolkits: toolkitOptions.data.toolkits,+ is_connected: toolkitOptions.data.isConnected,+ search: toolkitOptions.data.search,+ });++ const toolkitConnectedStates = result.items.map(item => {+ const connectedState = transform(item)+ .with(ToolkitConnectionStateSchema)+ .using(item => ({+ slug: item.slug,+ name: item.name,+ logo: item.meta?.logo,+ isNoAuth: item.is_no_auth,+ connection: item.is_no_auth+ ? undefined+ : {+ isActive: item.connected_account?.status === 'ACTIVE',+ authConfig: item.connected_account && {+ id: item.connected_account?.auth_config.id,+ mode: item.connected_account?.auth_config.auth_scheme,+ isComposioManaged: item.connected_account?.auth_config.is_composio_managed,+ },+ connectedAccount: item.connected_account+ ? {+ id: item.connected_account.id,+ status: item.connected_account.status,+ }+ : undefined,+ },+ }));+ return connectedState;+ });++ return {+ items: toolkitConnectedStates,+ nextCursor: result.next_cursor ?? undefined,+ totalPages: result.total_pages,+ };+ }++ /**+ * Search for tools by semantic use case.+ * Returns relevant tools for the given query with schemas and guidance.+ *+ * @param params - Search parameters+ * @param params.query - Semantic use-case query (e.g. "send emails", "create GitHub issues")+ * @param params.toolkits - Optional toolkit slugs to filter by+ * @returns Search results with matching tools and schemas+ *+ * @example+ * ```typescript+ * const session = await composio.toolRouter.use('session_123');+ * const results = await session.search({+ * query: 'send emails and notify Slack',+ * toolkits: ['gmail', 'slack'],+ * });+ * ```+ */+ async search(params: {+ query: string;+ toolkits?: string[];+ }): Promise<ToolRouterSessionSearchResponse> {+ const response = await this.client.toolRouter.session.search(this.sessionId, {+ queries: [{ use_case: params.query }],+ ...(params.toolkits?.length ? { toolkits: params.toolkits } : {}),+ });+ const transformed = transformSearchResponse(response);+ return ToolRouterSessionSearchResponseSchema.parse(transformed);+ }++ /**+ * Execute a tool within the session.+ *+ * @param toolSlug - The tool slug to execute (e.g. "GMAIL_SEND_EMAIL")+ * @param arguments_ - Optional tool arguments. Defaults to empty object if omitted.+ * @returns The tool execution result+ *+ * @example+ * ```typescript+ * const session = await composio.toolRouter.use('session_123');+ * const result = await session.execute('GMAIL_SEND_EMAIL', {+ * to: '[email protected]',+ * subject: 'Hello',+ * body: 'Hi!',+ * });+ * ```+ *+ * @example+ * ```typescript+ * // Execute with no arguments+ * const result = await session.execute('HACKERNEWS_GET_USER');+ * ```+ */+ async execute(+ toolSlug: string,+ arguments_?: Record<string, unknown>+ ): Promise<ToolRouterSessionExecuteResponse> {+ const response = await this.client.toolRouter.session.execute(this.sessionId, {+ tool_slug: toolSlug,+ arguments: arguments_ ?? {},+ });+ const transformed = transformExecuteResponse(response);+ return ToolRouterSessionExecuteResponseSchema.parse(transformed);+ }+}diff --git a/ts/packages/core/src/models/ToolRouterSessionFileMount.ts b/ts/packages/core/src/models/ToolRouterSessionFileMount.tsnew file mode 100644index 000000000..25f2692c0--- /dev/null+++ b/ts/packages/core/src/models/ToolRouterSessionFileMount.ts@@ -0,0 +1,383 @@+import { telemetry } from '../telemetry/Telemetry';+import { Composio as ComposioClient } from '@composio/client';+import {+ FileDeleteResponse,+ FileDeleteResponseSchema,+ FileListResponse,+ FileListResponseSchema,+ RemoteFileDataSchema,+ ToolRouterSessionFilesMountDeleteOptions,+ ToolRouterSessionFilesMountDeleteOptionsSchema,+ ToolRouterSessionFilesMountDownloadOptions,+ ToolRouterSessionFilesMountDownloadOptionsSchema,+ ToolRouterSessionFilesMountListOptions,+ ToolRouterSessionFilesMountListOptionsSchema,+ ToolRouterSessionFilesMountUploadOptions,+ ToolRouterSessionFilesMountUploadOptionsSchema,+} from '../types/ToolRouterSessionFilesMount.types';+import { RemoteFile } from './RemoteFile';+import { ValidationError } from '../errors';+import { platform } from '#platform';+import { getExtensionFromMimeType } from '../utils/mime';+import { getRandomShortId } from '../utils/uuid';++export class ToolRouterSessionFilesMount {+ private readonly sessionId: string;+ private readonly client: ComposioClient;++ constructor(client: ComposioClient, sessionId: string) {+ this.client = client;+ this.sessionId = sessionId;+ telemetry.instrument(this, 'ToolRouterSessionFiles');+ }++ /**+ * Lists files and directories at the specified path on the session's file mount.+ *+ * Use this to browse the virtual filesystem attached to the tool router session.+ * The path is relative to the mount root (e.g., `"/"` for root, `"/documents"` for a subdirectory).+ * Supports cursor-based pagination via `cursor` and `limit` options.+ *+ * @param options - Optional configuration for the list operation.+ * @param options.path - The directory path to list. Use `"/"` for the mount root.+ * @param options.mountId - The ID of the file mount to operate on. Defaults to `"files"` when omitted.+ * @param options.cursor - Pagination cursor from the previous response's nextCursor field.+ * @param options.limit - Maximum number of files to return per page (1-500).+ * @returns List of files with nextCursor for pagination.+ *+ * @example+ * ```typescript+ * const session = await composio.toolRouter.use('session_123');+ * const { items, nextCursor } = await session.files.list({ path: '/' });+ * ```+ *+ * @example+ * ```typescript+ * // Paginated listing+ * let result = await session.files.list({ path: '/', limit: 10 });+ * while (result.nextCursor) {+ * result = await session.files.list({ path: '/', cursor: result.nextCursor, limit: 10 });+ * }+ * ```+ */+ async list(options?: ToolRouterSessionFilesMountListOptions): Promise<FileListResponse> {+ const listOptions = ToolRouterSessionFilesMountListOptionsSchema.safeParse(options ?? {});++ if (!listOptions.success) {+ throw new ValidationError('Failed to parse tool router session files mount list options', {+ cause: listOptions.error,+ });+ }++ // API requires: no leading slash, min 1 char when provided. Omit for root.+ const rawPath = listOptions.data.path;+ const mountRelativePrefix =+ rawPath === undefined || rawPath === '' || rawPath === '/'+ ? undefined+ : rawPath.startsWith('/')+ ? rawPath.slice(1)+ : rawPath;++ const response = await this.client.toolRouter.session.files.list(listOptions.data.mountId, {+ session_id: this.sessionId,+ mount_relative_prefix: mountRelativePrefix,+ cursor: listOptions.data.cursor,+ limit: listOptions.data.limit,+ });++ const data =+ typeof response === 'object' && 'body' in response+ ? (response as { body: unknown }).body+ : response;++ const parsed = FileListResponseSchema.safeParse(data);+ if (!parsed.success) {+ throw new ValidationError('Failed to parse file list response', {+ cause: parsed.error,+ });+ }+ return parsed.data;+ }++ private async normalizeUploadInput(+ input: string | File | ArrayBuffer | Uint8Array,+ options: { remotePath?: string; mimetype?: string }+ ): Promise<{ fileToUpload: File; remotePath: string; mimetype: string }> {+ if (typeof input === 'string') {+ if (input.startsWith('http://') || input.startsWith('https://')) {+ const response = await fetch(input);+ if (!response.ok) {+ throw new Error(`Failed to fetch file from URL: ${response.statusText}`);+ }+ const arrayBuffer = await response.arrayBuffer();+ const mimeType = response.headers.get('content-type') || 'application/octet-stream';+ const url = new URL(input);+ const pathname = url.pathname;+ const segments = pathname.split('/').filter(Boolean);+ let filename = segments.length > 0 ? segments[segments.length - 1] : '';+ if (!filename || !filename.includes('.')) {+ const extension = getExtensionFromMimeType(mimeType);+ filename = `${getRandomShortId()}.${extension}`;+ }+ const file = new File([arrayBuffer], filename, { type: mimeType });+ return {+ fileToUpload: file,+ remotePath: options.remotePath ?? filename,+ mimetype: mimeType,+ };+ }+ const content = platform.readFileSync(input);+ const buffer =+ content instanceof Uint8Array+ ? new Uint8Array(content)+ : new TextEncoder().encode(content as string);+ const filename = platform.basename(input);+ const mimetype = options.mimetype ?? 'application/octet-stream';+ const file = new File([buffer], filename, { type: mimetype });+ return {+ fileToUpload: file,+ remotePath: options.remotePath ?? filename,+ mimetype,+ };+ }++ if (input instanceof File) {+ return {+ fileToUpload: input,+ remotePath: options.remotePath ?? (input.name || `upload-${getRandomShortId()}.bin`),+ mimetype: input.type || 'application/octet-stream',+ };+ }++ const buffer = input instanceof ArrayBuffer ? new Uint8Array(input) : input;+ if (!options.mimetype && !options.remotePath) {+ throw new Error(+ 'When passing a buffer, either mimetype or remotePath (filename) is required. ' ++ 'Example: files.upload(buffer, { remotePath: "data.json", mimetype: "application/json" })'+ );+ }+ const mimetype = options.mimetype ?? 'application/octet-stream';+ const ext = getExtensionFromMimeType(mimetype);+ const remotePath = options.remotePath ?? `upload-${getRandomShortId()}.${ext}`;+ const file = new File([buffer as BlobPart], remotePath, { type: mimetype });+ return {+ fileToUpload: file,+ remotePath,+ mimetype,+ };+ }++ /**+ * Uploads a file to the session's file mount.+ *+ * Accepts a file path (local or URL), a native File object, or a raw buffer.+ * The file is stored in the virtual filesystem associated with the tool router session.+ *+ * @param input - File path (string), native File, or raw buffer (ArrayBuffer | Uint8Array).+ * @param options - Optional configuration. When passing a buffer, remotePath is required.+ * @returns Metadata about the uploaded file.+ *+ * @example+ * ```typescript+ * // From file path (local or URL)+ * await session.files.upload('/path/to/report.pdf');+ * await session.files.upload('https://example.com/file.pdf');+ * ```+ *+ * @example+ * ```typescript+ * // From native File (e.g. from input[type=file])+ * await session.files.upload(fileInput.files[0]);+ * ```+ *+ * @example+ * ```typescript+ * // From raw buffer+ * await session.files.upload(buffer, { remotePath: 'data.json', mimetype: 'application/json' });+ * ```+ */+ async upload(+ input: string | File | ArrayBuffer | Uint8Array,+ options?: ToolRouterSessionFilesMountUploadOptions+ ): Promise<RemoteFile> {+ const uploadOptions = ToolRouterSessionFilesMountUploadOptionsSchema.safeParse(options ?? {});++ if (!uploadOptions.success) {+ throw new ValidationError('Failed to parse tool router session files mount upload options', {+ cause: uploadOptions.error,+ });+ }++ const { fileToUpload, remotePath, mimetype } = await this.normalizeUploadInput(+ input,+ uploadOptions.data+ );++ const createUploadURLResponse = await this.client.toolRouter.session.files.createUploadURL(+ uploadOptions.data.mountId,+ {+ session_id: this.sessionId,+ mount_relative_path: remotePath,+ mimetype,+ }+ );++ const uploadURLData =+ typeof createUploadURLResponse === 'object' && 'body' in createUploadURLResponse+ ? (createUploadURLResponse as { body: unknown }).body+ : createUploadURLResponse;++ const uploadResponse = await fetch((uploadURLData as { upload_url: string }).upload_url, {+ method: 'PUT',+ body: await fileToUpload.arrayBuffer(),+ headers: {+ 'Content-Type': mimetype,+ },+ });++ if (!uploadResponse.ok) {+ throw new Error(`Failed to upload file: ${uploadResponse.statusText}`);+ }++ const createDownloadURLResponse = await this.client.toolRouter.session.files.createDownloadURL(+ uploadOptions.data.mountId,+ {+ session_id: this.sessionId,+ mount_relative_path: (uploadURLData as { mount_relative_path: string }).mount_relative_path,+ }+ );++ const downloadData =+ typeof createDownloadURLResponse === 'object' && 'body' in createDownloadURLResponse+ ? (createDownloadURLResponse as { body: unknown }).body+ : createDownloadURLResponse;++ const parsed = RemoteFileDataSchema.safeParse(downloadData);+ if (!parsed.success) {+ throw new ValidationError('Failed to parse remote file properties', {+ cause: parsed.error,+ });+ }++ return new RemoteFile(parsed.data);+ }++ /**+ * Downloads a file from the session's file mount to the local filesystem.+ *+ * Retrieves a file stored in the session's virtual filesystem (e.g., one produced+ * by a tool or previously uploaded) and saves it to the specified local path.+ *+ * @param filePath - The path of the file on the mount to download, or the local path where the file should be saved (implementation-specific).+ * @param options - Optional configuration for the download.+ * @param options.mountId - The ID of the file mount to download from. Defaults to `"files"` when omitted.+ * @returns The downloaded file data or path (implementation-specific).+ *+ * @example+ * ```typescript+ * const session = await composio.toolRouter.use('session_123');+ * const result = await session.files.download('/output/report.pdf');+ * ```+ *+ * @example+ * ```typescript+ * // Download from a custom mount+ * await session.files.download('/exports/data.json', {+ * mountId: 'custom-mount',+ * });+ * ```+ */+ async download(+ filePath: string,+ options?: ToolRouterSessionFilesMountDownloadOptions+ ): Promise<RemoteFile> {+ const downloadOptions = ToolRouterSessionFilesMountDownloadOptionsSchema.safeParse(+ options ?? {}+ );++ if (!downloadOptions.success) {+ throw new ValidationError(+ 'Failed to parse tool router session files mount download options',+ {+ cause: downloadOptions.error,+ }+ );+ }++ const createDownloadURLResponse = await this.client.toolRouter.session.files.createDownloadURL(+ downloadOptions.data.mountId,+ {+ session_id: this.sessionId,+ mount_relative_path: filePath,+ }+ );++ const downloadURLData =+ typeof createDownloadURLResponse === 'object' && 'body' in createDownloadURLResponse+ ? (createDownloadURLResponse as { body: unknown }).body+ : createDownloadURLResponse;++ const parsed = RemoteFileDataSchema.safeParse(downloadURLData);+ if (!parsed.success) {+ throw new ValidationError('Failed to parse remote file properties', {+ cause: parsed.error,+ });+ }+ return new RemoteFile(parsed.data);+ }++ /**+ * Deletes a file or directory at the specified path on the session's file mount.+ *+ * Removes the file or directory from the virtual filesystem. Use with caution:+ * deletion is typically irreversible. Ensure the path exists and is intended for removal.+ *+ * @param remotePath - The path of the file or directory to delete on the mount.+ * @param options - Optional configuration for the delete operation.+ * @param options.mountId - The ID of the file mount to operate on. Defaults to `"files"` when omitted.+ * @returns Confirmation of deletion (implementation-specific).+ *+ * @example+ * ```typescript+ * const session = await composio.toolRouter.use('session_123');+ * await session.files.delete('/temp/cache.json');+ * ```+ *+ * @example+ * ```typescript+ * // Delete from a custom mount+ * await session.files.delete('/old-backup', {+ * mountId: 'custom-mount',+ * });+ * ```+ *+ * @warning This operation is destructive. Deleted files cannot be recovered.+ */+ async delete(+ remotePath: string,+ options?: ToolRouterSessionFilesMountDeleteOptions+ ): Promise<FileDeleteResponse> {+ const deleteOptions = ToolRouterSessionFilesMountDeleteOptionsSchema.safeParse(options ?? {});++ if (!deleteOptions.success) {+ throw new ValidationError('Failed to parse tool router session files mount delete options', {+ cause: deleteOptions.error,+ });+ }++ const deleteResponse = await this.client.toolRouter.session.files.delete(+ deleteOptions.data.mountId,+ {+ session_id: this.sessionId,+ mount_relative_path: remotePath,+ }+ );+ const fileDeleteResponse = FileDeleteResponseSchema.safeParse(deleteResponse);+ if (!fileDeleteResponse.success) {+ throw new ValidationError('Failed to parse file delete response', {+ cause: fileDeleteResponse.error,+ });+ }+ return fileDeleteResponse.data;+ }+}diff --git a/ts/packages/core/src/types/ToolRouterSessionFilesMount.types.ts b/ts/packages/core/src/types/ToolRouterSessionFilesMount.types.tsnew file mode 100644index 000000000..1a3be2d20--- /dev/null+++ b/ts/packages/core/src/types/ToolRouterSessionFilesMount.types.ts@@ -0,0 +1,96 @@+import z from 'zod/v3';+import { DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID } from '../utils/constants';++export const ToolRouterSessionFilesMountListOptionsSchema = z.object({+ path: z.string().optional(),+ mountId: z.string().default(DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID),+ /** Pagination cursor from the previous response nextCursor field */+ cursor: z.string().optional(),+ /** Maximum number of files to return per page (1-500) */+ limit: z.number().min(1).max(500).optional(),+});++export type ToolRouterSessionFilesMountListOptions = z.input<+ typeof ToolRouterSessionFilesMountListOptionsSchema+>;++const FileListItemSchema = z.object({+ last_modified: z.string(),+ mount_relative_path: z.string(),+ sandbox_mount_prefix: z.string(),+ size: z.number(),+});++export const FileListResponseSchema = z+ .object({+ items: z.array(FileListItemSchema),+ next_cursor: z.string().optional(),+ })+ .transform(data => ({+ items: data.items.map(item => ({+ lastModified: item.last_modified,+ mountRelativePath: item.mount_relative_path,+ sandboxMountPrefix: item.sandbox_mount_prefix,+ size: item.size,+ })),+ nextCursor: data.next_cursor,+ }));++export type FileListResponse = z.infer<typeof FileListResponseSchema>;++export const ToolRouterSessionFilesMountUploadOptionsSchema = z.object({+ /** Remote path/filename on the mount. When passing a buffer, either mimetype or remotePath is required. */+ remotePath: z.string().optional(),+ mountId: z.string().default(DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID),+ /** MIME type. When passing a buffer, either mimetype or remotePath is required. Ignored when passing File (uses file.type). */+ mimetype: z.string().optional(),+});++export type ToolRouterSessionFilesMountUploadOptions = z.input<+ typeof ToolRouterSessionFilesMountUploadOptionsSchema+>;++export const ToolRouterSessionFilesMountDownloadOptionsSchema = z.object({+ mountId: z.string().default(DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID),+});++export type ToolRouterSessionFilesMountDownloadOptions = z.input<+ typeof ToolRouterSessionFilesMountDownloadOptionsSchema+>;++export const ToolRouterSessionFilesMountDeleteOptionsSchema = z.object({+ mountId: z.string().default(DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID),+});++export type ToolRouterSessionFilesMountDeleteOptions = z.input<+ typeof ToolRouterSessionFilesMountDeleteOptionsSchema+>;++export const RemoteFileDataSchema = z+ .object({+ expires_at: z.string(),+ mount_relative_path: z.string(),+ sandbox_mount_prefix: z.string(),+ download_url: z.string(),+ })+ .transform(data => ({+ expiresAt: data.expires_at,+ mountRelativePath: data.mount_relative_path,+ sandboxMountPrefix: data.sandbox_mount_prefix,+ downloadUrl: data.download_url,+ }));++/** Parsed shape from API response. Use with `new RemoteFile(data)`. */+export type RemoteFileData = z.infer<typeof RemoteFileDataSchema>;++export const FileDeleteResponseSchema = z+ .object({+ mount_relative_path: z.string(),+ sandbox_mount_prefix: z.string(),+ })+ .transform(data => ({+ mountRelativePath: data.mount_relative_path,+ sandboxMountPrefix: data.sandbox_mount_prefix,+ }));++export type FileDeleteResponse = z.infer<typeof FileDeleteResponseSchema>;diff --git a/ts/packages/core/src/types/toolRouter.types.ts b/ts/packages/core/src/types/toolRouter.types.tsindex 4008ba8d8..282a176a5 100644--- a/ts/packages/core/src/types/toolRouter.types.ts+++ b/ts/packages/core/src/types/toolRouter.types.ts@@ -1,7 +1,8 @@import z from 'zod/v3';-import { BaseComposioProvider } from '../provider/BaseProvider';+import type { BaseComposioProvider } from '../provider/BaseProvider';import { SessionMetaToolOptions } from './modifiers.types';import { ConnectionRequest } from './connectionRequest.types';+import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';export const MCPServerTypeSchema = z.enum(['http', 'sse']);export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;@@ -305,49 +306,129 @@ export type ToolRouterToolkitsOptions = z.infer<typeof ToolRouterToolkitsOptionsexport type ToolRouterToolkitsFn = (options?: ToolRouterToolkitsOptions) => Promise<ToolkitConnectionsDetails>;++// --- Session search response schemas (camelCase) ---++const ToolRouterSessionSearchResultReferenceWorkbenchSnippetSchema = z.object({+ code: z.string(),+ description: z.string(),+});++const ToolRouterSessionSearchResultSchema = z.object({+ index: z.number(),+ useCase: z.string(),+ primaryToolSlugs: z.array(z.string()),+ relatedToolSlugs: z.array(z.string()),+ toolkits: z.array(z.string()),+ difficulty: z.string().optional(),+ error: z.string().nullable().optional(),+ executionGuidance: z.string().optional(),+ knownPitfalls: z.array(z.string()).optional(),+ memory: z.record(z.string(), z.array(z.string())).optional(),+ planId: z.string().optional(),+ recommendedPlanSteps: z.array(z.string()).optional(),+ referenceWorkbenchSnippets: z+ .array(ToolRouterSessionSearchResultReferenceWorkbenchSnippetSchema)+ .optional(),+});++const ToolRouterSessionSearchSessionSchema = z.object({+ id: z.string(),+ generateId: z.boolean(),+ instructions: z.string(),+});++const ToolRouterSessionSearchTimeInfoSchema = z.object({+ currentTimeUtc: z.string(),+ currentTimeUtcEpochSeconds: z.number(),+ message: z.string(),+});++const ToolRouterSessionSearchToolSchemasSchemaRefSchema = z.object({+ args: z.object({ toolSlugs: z.array(z.string()) }),+ message: z.string(),+ tool: z.literal('COMPOSIO_GET_TOOL_SCHEMAS'),+});++const ToolRouterSessionSearchToolSchemaSchema = z.object({+ toolSlug: z.string(),+ toolkit: z.string(),+ description: z.string().optional(),+ hasFullSchema: z.boolean().optional(),+ inputSchema: z.record(z.string(), z.unknown()).optional(),+ outputSchema: z.record(z.string(), z.unknown()).optional(),+ schemaRef: ToolRouterSessionSearchToolSchemasSchemaRefSchema.optional(),+});++const ToolRouterSessionSearchToolkitConnectionStatusSchema = z.object({+ toolkit: z.string(),+ description: z.string(),+ hasActiveConnection: z.boolean(),+ statusMessage: z.string(),+ connectionDetails: z.record(z.string(), z.unknown()).optional(),+ currentUserInfo: z.record(z.string(), z.unknown()).optional(),+});++export const ToolRouterSessionSearchResponseSchema = z.object({+ success: z.boolean(),+ error: z.string().nullable(),+ results: z.array(ToolRouterSessionSearchResultSchema),+ toolSchemas: z.record(z.string(), ToolRouterSessionSearchToolSchemaSchema),+ toolkitConnectionStatuses: z.array(ToolRouterSessionSearchToolkitConnectionStatusSchema),+ nextStepsGuidance: z.array(z.string()),+ session: ToolRouterSessionSearchSessionSchema,+ timeInfo: ToolRouterSessionSearchTimeInfoSchema,+});+export type ToolRouterSessionSearchResponse = z.infer<typeof ToolRouterSessionSearchResponseSchema>;++// --- Session execute response schema (camelCase) ---++export const ToolRouterSessionExecuteResponseSchema = z.object({+ data: z.record(z.string(), z.unknown()),+ error: z.string().nullable(),+ logId: z.string(),+});+export type ToolRouterSessionExecuteResponse = z.infer<+ typeof ToolRouterSessionExecuteResponseSchema+>;+/*** Experimental features response from session creation.* Only returned on session creation, not on GET.*/-export interface ToolRouterSessionExperimental {+export interface SessionExperimental {/*** The assistive system prompt to inject into your agent for optimal tool router usage.*/assistivePrompt?: string;}-export interface ToolRouterSession<+export type ToolRouterSessionSearchFn = (params: {+ query: string;+ toolkits?: string[];+}) => Promise<ToolRouterSessionSearchResponse>;++export type ToolRouterSessionExecuteFn = (+ toolSlug: string,+ arguments_?: Record<string, unknown>+) => Promise<ToolRouterSessionExecuteResponse>;++/** Session type returned by ToolRouter.create() and ToolRouter.use() */+export interface Session<TToolCollection,TTool,TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,> {- /**- * The session id of the tool router session.- */sessionId: string;- /**- * The MCP server config of the tool router session.- * Contains the URL, type ('http' or 'sse'), and headers for authentication.- */mcp: ToolRouterMCPServerConfig;- /**- * Get the tools available in the session, formatted for your AI framework.- * Requires a provider to be configured in the Composio constructor.- */tools: ToolRouterToolsFn<TToolCollection, TTool, TProvider>;- /**- * Initiate an authorization flow for a toolkit.- * Returns a ConnectionRequest with a redirect URL for the user.- */authorize: ToolRouterAuthorizeFn;- /**- * Query the connection state of toolkits in the session.- * Supports pagination and filtering by toolkit slugs.- */toolkits: ToolRouterToolkitsFn;- /**- * Experimental features including the generated system prompt.- * Only returned on session creation, not on GET.- */- experimental?: ToolRouterSessionExperimental;+ /** Search for tools by semantic use case */+ search: ToolRouterSessionSearchFn;+ /** Execute a tool within the session */+ execute: ToolRouterSessionExecuteFn;+ /** File mount operations (list, upload, download, delete) */+ files: ToolRouterSessionFilesMount;+ experimental?: SessionExperimental;}diff --git a/ts/packages/core/src/utils/constants.ts b/ts/packages/core/src/utils/constants.tsindex 2f49d4c6c..93a4b8444 100644--- a/ts/packages/core/src/utils/constants.ts+++ b/ts/packages/core/src/utils/constants.ts@@ -18,3 +18,5 @@ export const COMPOSIO_LOG_LEVEL = getEnvVariable('COMPOSIO_LOG_LEVEL') as| undefined;export const IS_DEVELOPMENT_OR_CI = getEnvVariable('DEVELOPMENT') || getEnvVariable('CI') || false;++export const DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID = 'files';diff --git a/ts/packages/core/src/utils/mime.ts b/ts/packages/core/src/utils/mime.tsnew file mode 100644index 000000000..920abe660--- /dev/null+++ b/ts/packages/core/src/utils/mime.ts@@ -0,0 +1,75 @@+/**+ * Maps MIME types to file extensions.+ * Used when deriving filenames from content-type headers (e.g. for URLs without path segments).+ */+export function getExtensionFromMimeType(mimeType: string): string {+ const mimeToExt: Record<string, string> = {+ 'text/plain': 'txt',+ 'text/html': 'html',+ 'text/css': 'css',+ 'text/javascript': 'js',+ 'application/json': 'json',+ 'application/xml': 'xml',+ 'application/pdf': 'pdf',+ 'application/zip': 'zip',+ 'application/x-zip-compressed': 'zip',+ 'application/gzip': 'gz',+ 'application/octet-stream': 'bin',+ 'application/x-tar': 'tar',+ 'application/msword': 'doc',+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',+ 'application/vnd.ms-excel': 'xls',+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',+ 'application/vnd.ms-powerpoint': 'ppt',+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',+ 'image/jpeg': 'jpg',+ 'image/jpg': 'jpg',+ 'image/png': 'png',+ 'image/gif': 'gif',+ 'image/svg+xml': 'svg',+ 'image/webp': 'webp',+ 'image/bmp': 'bmp',+ 'image/tiff': 'tiff',+ 'audio/mpeg': 'mp3',+ 'audio/wav': 'wav',+ 'audio/ogg': 'ogg',+ 'video/mp4': 'mp4',+ 'video/mpeg': 'mpeg',+ 'video/quicktime': 'mov',+ 'video/x-msvideo': 'avi',+ 'video/webm': 'webm',+ };++ const cleanMimeType = mimeType.split(';')[0].toLowerCase().trim();++ if (mimeToExt[cleanMimeType]) {+ return mimeToExt[cleanMimeType];+ }++ const parts = cleanMimeType.split('/');+ if (parts.length === 2) {+ const subtype = parts[1].toLowerCase();++ if (subtype.includes('+')) {+ const plusParts = subtype.split('+');+ const prefix = plusParts[0];+ const suffix = plusParts[plusParts.length - 1];++ const knownPrefixes = ['svg', 'atom', 'rss'];+ if (knownPrefixes.includes(prefix)) {+ return prefix;+ }++ const structuredSuffixes = ['json', 'xml', 'yaml', 'zip', 'gzip'];+ if (structuredSuffixes.includes(suffix)) {+ return suffix;+ }++ return suffix;+ }++ return subtype || 'txt';+ }++ return 'bin';+}diff --git a/ts/packages/core/src/utils/transformers/toolRouterResponseTransform.ts b/ts/packages/core/src/utils/transformers/toolRouterResponseTransform.tsnew file mode 100644index 000000000..c05762ed9--- /dev/null+++ b/ts/packages/core/src/utils/transformers/toolRouterResponseTransform.ts@@ -0,0 +1,160 @@+/**+ * Transforms snake_case Tool Router API responses to camelCase for SDK consumers.+ */++interface RawSearchResult {+ index: number;+ use_case: string;+ primary_tool_slugs: string[];+ related_tool_slugs: string[];+ toolkits: string[];+ difficulty?: string;+ error?: string | null;+ execution_guidance?: string;+ known_pitfalls?: string[];+ memory?: Record<string, string[]>;+ plan_id?: string;+ recommended_plan_steps?: string[];+ reference_workbench_snippets?: Array<{ code: string; description: string }>;+}++interface RawSearchSession {+ id: string;+ generate_id: boolean;+ instructions: string;+}++interface RawSearchTimeInfo {+ current_time_utc: string;+ current_time_utc_epoch_seconds: number;+ message: string;+}++interface RawToolSchema {+ tool_slug: string;+ toolkit: string;+ description?: string;+ hasFullSchema?: boolean;+ input_schema?: Record<string, unknown>;+ output_schema?: Record<string, unknown>;+ schemaRef?: {+ args: { tool_slugs: string[] };+ message: string;+ tool: string;+ };+}++interface RawToolkitConnectionStatus {+ toolkit: string;+ description: string;+ has_active_connection: boolean;+ status_message: string;+ connection_details?: Record<string, unknown>;+ current_user_info?: Record<string, unknown>;+}++interface RawSearchResponse {+ success: boolean;+ error: string | null;+ results: RawSearchResult[];+ tool_schemas: Record<string, RawToolSchema>;+ toolkit_connection_statuses: RawToolkitConnectionStatus[];+ next_steps_guidance: string[];+ session: RawSearchSession;+ time_info: RawSearchTimeInfo;+}++interface RawExecuteResponse {+ data: Record<string, unknown>;+ error: string | null;+ log_id: string;+}++function transformSearchResult(raw: RawSearchResult) {+ return {+ index: raw.index,+ useCase: raw.use_case,+ primaryToolSlugs: raw.primary_tool_slugs,+ relatedToolSlugs: raw.related_tool_slugs,+ toolkits: raw.toolkits,+ difficulty: raw.difficulty,+ error: raw.error,+ executionGuidance: raw.execution_guidance,+ knownPitfalls: raw.known_pitfalls,+ memory: raw.memory,+ planId: raw.plan_id,+ recommendedPlanSteps: raw.recommended_plan_steps,+ referenceWorkbenchSnippets: raw.reference_workbench_snippets,+ };+}++function transformToolSchema(raw: RawToolSchema) {+ return {+ toolSlug: raw.tool_slug,+ toolkit: raw.toolkit,+ description: raw.description,+ hasFullSchema: raw.hasFullSchema,+ inputSchema: raw.input_schema,+ outputSchema: raw.output_schema,+ schemaRef: raw.schemaRef+ ? {+ args: { toolSlugs: raw.schemaRef.args.tool_slugs },+ message: raw.schemaRef.message,+ tool: raw.schemaRef.tool,+ }+ : undefined,+ };+}++function transformToolkitConnectionStatus(raw: RawToolkitConnectionStatus) {+ return {+ toolkit: raw.toolkit,+ description: raw.description,+ hasActiveConnection: raw.has_active_connection,+ statusMessage: raw.status_message,+ connectionDetails: raw.connection_details,+ currentUserInfo: raw.current_user_info,+ };+}++/**+ * Transforms a raw session search API response to camelCase.+ */+export function transformSearchResponse(raw: RawSearchResponse) {+ const toolSchemas: Record<string, ReturnType<typeof transformToolSchema>> = {};+ for (const [slug, schema] of Object.entries(raw.tool_schemas)) {+ toolSchemas[slug] = transformToolSchema(schema);+ }++ return {+ success: raw.success,+ error: raw.error,+ results: raw.results.map(transformSearchResult),+ toolSchemas,+ toolkitConnectionStatuses: raw.toolkit_connection_statuses.map(+ transformToolkitConnectionStatus+ ),+ nextStepsGuidance: raw.next_steps_guidance,+ session: {+ id: raw.session.id,+ generateId: raw.session.generate_id,+ instructions: raw.session.instructions,+ },+ timeInfo: {+ currentTimeUtc: raw.time_info.current_time_utc,+ currentTimeUtcEpochSeconds: raw.time_info.current_time_utc_epoch_seconds,+ message: raw.time_info.message,+ },+ };+}++/**+ * Transforms a raw session execute API response to camelCase.+ */+export function transformExecuteResponse(raw: RawExecuteResponse) {+ return {+ data: raw.data,+ error: raw.error,+ logId: raw.log_id,+ };+}diff --git a/ts/packages/core/test/errors/RemoteFileErrors.test.ts b/ts/packages/core/test/errors/RemoteFileErrors.test.tsnew file mode 100644index 000000000..0d6fecedd--- /dev/null+++ b/ts/packages/core/test/errors/RemoteFileErrors.test.ts@@ -0,0 +1,43 @@+import { describe, it, expect } from 'vitest';+import { ComposioError } from '../../src/errors/ComposioError';+import { RemoteFileDownloadError, RemoteFileErrorCodes } from '../../src/errors/RemoteFileErrors';++describe('RemoteFileDownloadError', () => {+ it('should create error with default message', () => {+ const err = new RemoteFileDownloadError();+ expect(err.message).toBe('Failed to download remote file');+ expect(err.name).toBe('RemoteFileDownloadError');+ expect(err.code).toContain(RemoteFileErrorCodes.DOWNLOAD_FAILED);+ });++ it('should create error with custom message and options', () => {+ const err = new RemoteFileDownloadError('Download failed: 404', {+ statusCode: 404,+ statusText: 'Not Found',+ downloadUrl: 'https://example.com/file',+ mountRelativePath: 'output/report.pdf',+ filename: 'report.pdf',+ });++ expect(err.message).toBe('Download failed: 404');+ expect(err.code).toContain(RemoteFileErrorCodes.DOWNLOAD_FAILED);+ expect(err.meta).toMatchObject({+ statusCode: 404,+ statusText: 'Not Found',+ downloadUrl: 'https://example.com/file',+ mountRelativePath: 'output/report.pdf',+ filename: 'report.pdf',+ });+ expect(err.possibleFixes).toBeDefined();+ expect(err.possibleFixes).toContain(+ 'Verify the download URL has not expired (check expiresAt)'+ );+ });++ it('should extend ComposioError', () => {+ const err = new RemoteFileDownloadError();+ expect(err).toBeInstanceOf(Error);+ expect(err).toBeInstanceOf(ComposioError);+ expect(err).toBeInstanceOf(RemoteFileDownloadError);+ });+});diff --git a/ts/packages/core/test/models/RemoteFile.test.ts b/ts/packages/core/test/models/RemoteFile.test.tsnew file mode 100644index 000000000..6e854617a--- /dev/null+++ b/ts/packages/core/test/models/RemoteFile.test.ts@@ -0,0 +1,168 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { RemoteFile } from '../../src/models/RemoteFile';+import { RemoteFileDownloadError, ValidationError } from '../../src/errors';++describe('RemoteFile', () => {+ const validCamelCaseData = {+ expiresAt: '2025-12-31T23:59:59.000Z',+ mountRelativePath: 'output/report.pdf',+ sandboxMountPrefix: '/mnt/files',+ downloadUrl: 'https://s3.example.com/presigned-url',+ };++ const validSnakeCaseData = {+ expires_at: '2025-12-31T23:59:59.000Z',+ mount_relative_path: 'output/report.pdf',+ sandbox_mount_prefix: '/mnt/files',+ download_url: 'https://s3.example.com/presigned-url',+ };++ let originalFetch: typeof globalThis.fetch;++ beforeEach(() => {+ originalFetch = globalThis.fetch;+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ describe('constructor', () => {+ it('should create instance with valid camelCase data', () => {+ const file = new RemoteFile(validCamelCaseData);+ expect(file.expiresAt).toBe(validCamelCaseData.expiresAt);+ expect(file.mountRelativePath).toBe(validCamelCaseData.mountRelativePath);+ expect(file.sandboxMountPrefix).toBe(validCamelCaseData.sandboxMountPrefix);+ expect(file.downloadUrl).toBe(validCamelCaseData.downloadUrl);+ });+ });++ describe('parse', () => {+ it('should parse snake_case API response and return RemoteFile', () => {+ const file = RemoteFile.parse(validSnakeCaseData);+ expect(file).toBeInstanceOf(RemoteFile);+ expect(file.expiresAt).toBe(validSnakeCaseData.expires_at);+ expect(file.mountRelativePath).toBe(validSnakeCaseData.mount_relative_path);+ expect(file.downloadUrl).toBe(validSnakeCaseData.download_url);+ });++ it('should throw ValidationError for invalid data', () => {+ expect(() => RemoteFile.parse({})).toThrow(ValidationError);+ expect(() => RemoteFile.parse({ expires_at: 'x' })).toThrow(ValidationError);+ expect(() => RemoteFile.parse(null)).toThrow(ValidationError);+ });+ });++ describe('filename', () => {+ it('should return basename of mount path', () => {+ const file = new RemoteFile(validCamelCaseData);+ expect(file.filename).toBe('report.pdf');+ });++ it('should handle nested path', () => {+ const file = new RemoteFile({+ ...validCamelCaseData,+ mountRelativePath: 'output/subdir/data.json',+ });+ expect(file.filename).toBe('data.json');+ });+ });++ describe('buffer', () => {+ it('should fetch and return file content as Uint8Array', async () => {+ const content = new Uint8Array([1, 2, 3]);+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ arrayBuffer: () => Promise.resolve(content.buffer),+ });++ const file = new RemoteFile(validCamelCaseData);+ const result = await file.buffer();++ expect(globalThis.fetch).toHaveBeenCalledWith(validCamelCaseData.downloadUrl);+ expect(result).toBeInstanceOf(Uint8Array);+ expect(result).toEqual(content);+ });++ it('should throw RemoteFileDownloadError when fetch fails', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: false,+ status: 404,+ statusText: 'Not Found',+ });++ const file = new RemoteFile(validCamelCaseData);++ await expect(file.buffer()).rejects.toThrow(RemoteFileDownloadError);+ await expect(file.buffer()).rejects.toMatchObject({+ name: 'RemoteFileDownloadError',+ message: expect.stringContaining('404'),+ });+ });+ });++ describe('text', () => {+ it('should fetch and return file content as UTF-8 string', async () => {+ const content = 'Hello, World!';+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ arrayBuffer: () => Promise.resolve(new TextEncoder().encode(content).buffer),+ });++ const file = new RemoteFile(validCamelCaseData);+ const result = await file.text();++ expect(result).toBe(content);+ });+ });++ describe('blob', () => {+ it('should fetch and return file content as Blob', async () => {+ const blob = new Blob(['data']);+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ blob: () => Promise.resolve(blob),+ });++ const file = new RemoteFile(validCamelCaseData);+ const result = await file.blob();++ expect(result).toBe(blob);+ });++ it('should throw RemoteFileDownloadError when fetch fails', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: false,+ status: 403,+ statusText: 'Forbidden',+ });++ const file = new RemoteFile(validCamelCaseData);++ await expect(file.blob()).rejects.toThrow(RemoteFileDownloadError);+ });+ });++ describe('save', () => {+ it('should save file to specified path when platform supports file system', async () => {+ const content = new Uint8Array([1, 2, 3]);+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ arrayBuffer: () => Promise.resolve(content.buffer),+ });++ const file = new RemoteFile(validCamelCaseData);+ const { platform } = await import('../../src/platform/node');+ const { join } = await import('node:path');+ const { tmpdir } = await import('node:os');+ const savePath = join(tmpdir(), `composio-remote-file-test-${Date.now()}.pdf`);++ const result = await file.save(savePath);++ expect(result).toBe(savePath);+ expect(platform.existsSync(savePath)).toBe(true);+ const written = platform.readFileSync(savePath) as Uint8Array;+ expect(new Uint8Array(written)).toEqual(content);+ });+ });+});diff --git a/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts b/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.tsnew file mode 100644index 000000000..609fff65d--- /dev/null+++ b/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts@@ -0,0 +1,414 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { ToolRouterSessionFilesMount } from '../../src/models/ToolRouterSessionFileMount';+import { ValidationError } from '../../src/errors';+import { DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID } from '../../src/utils/constants';++const sessionId = 'trs_session_123';++const createMockClient = () => ({+ toolRouter: {+ session: {+ files: {+ list: vi.fn(),+ createUploadURL: vi.fn(),+ createDownloadURL: vi.fn(),+ delete: vi.fn(),+ },+ },+ },+});++describe('ToolRouterSessionFilesMount', () => {+ let mockClient: ReturnType<typeof createMockClient>;+ let filesMount: ToolRouterSessionFilesMount;++ beforeEach(() => {+ vi.clearAllMocks();+ mockClient = createMockClient();+ filesMount = new ToolRouterSessionFilesMount(mockClient as any, sessionId);+ });++ describe('list', () => {+ it('should call list with default mountId and no path', async () => {+ mockClient.toolRouter.session.files.list.mockResolvedValueOnce({ items: [] });++ const result = await filesMount.list();++ expect(mockClient.toolRouter.session.files.list).toHaveBeenCalledWith(+ DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,+ {+ session_id: sessionId,+ mount_relative_prefix: undefined,+ cursor: undefined,+ limit: undefined,+ }+ );+ expect(result).toEqual({ items: [], nextCursor: undefined });+ });++ it('should call list with custom path and mountId (strips leading slash for API)', async () => {+ mockClient.toolRouter.session.files.list.mockResolvedValueOnce({ items: [] });++ await filesMount.list({+ path: '/documents',+ mountId: 'custom-mount',+ });++ expect(mockClient.toolRouter.session.files.list).toHaveBeenCalledWith('custom-mount', {+ session_id: sessionId,+ mount_relative_prefix: 'documents',+ cursor: undefined,+ limit: undefined,+ });+ });++ it('should return transformed response with items and nextCursor', async () => {+ const apiResponse = {+ items: [+ {+ last_modified: '2025-03-09T12:00:00.000Z',+ mount_relative_path: 'file.txt',+ sandbox_mount_prefix: '/mnt/files',+ size: 42,+ },+ ],+ next_cursor: 'cursor_abc123',+ };+ mockClient.toolRouter.session.files.list.mockResolvedValueOnce(apiResponse);++ const result = await filesMount.list();++ expect(result).toEqual({+ items: [+ {+ lastModified: '2025-03-09T12:00:00.000Z',+ mountRelativePath: 'file.txt',+ sandboxMountPrefix: '/mnt/files',+ size: 42,+ },+ ],+ nextCursor: 'cursor_abc123',+ });+ });++ it('should pass cursor and limit for pagination (path / omitted for root)', async () => {+ mockClient.toolRouter.session.files.list.mockResolvedValueOnce({ items: [] });++ await filesMount.list({+ path: '/',+ cursor: 'cursor_page2',+ limit: 25,+ });++ expect(mockClient.toolRouter.session.files.list).toHaveBeenCalledWith(+ DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,+ {+ session_id: sessionId,+ mount_relative_prefix: undefined,+ cursor: 'cursor_page2',+ limit: 25,+ }+ );+ });+ });++ describe('download', () => {+ const createDownloadURLResponse = {+ expires_at: '2025-12-31T23:59:59.000Z',+ mount_relative_path: 'output/report.pdf',+ sandbox_mount_prefix: '/mnt/files',+ download_url: 'https://s3.example.com/presigned',+ };++ it('should call createDownloadURL and return RemoteFile', async () => {+ mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(+ createDownloadURLResponse+ );++ const result = await filesMount.download('/output/report.pdf');++ expect(mockClient.toolRouter.session.files.createDownloadURL).toHaveBeenCalledWith(+ DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,+ {+ session_id: sessionId,+ mount_relative_path: '/output/report.pdf',+ }+ );+ expect(result).toBeDefined();+ expect(result.mountRelativePath).toBe('output/report.pdf');+ expect(result.downloadUrl).toBe('https://s3.example.com/presigned');+ });++ it('should use custom mountId when provided', async () => {+ mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(+ createDownloadURLResponse+ );++ await filesMount.download('/output/report.pdf', { mountId: 'exports' });++ expect(mockClient.toolRouter.session.files.createDownloadURL).toHaveBeenCalledWith(+ 'exports',+ {+ session_id: sessionId,+ mount_relative_path: '/output/report.pdf',+ }+ );+ });+ });++ describe('delete', () => {+ const deleteResponse = {+ mount_relative_path: '/temp/cache.json',+ sandbox_mount_prefix: '/mnt/files',+ };++ it('should call delete and return parsed response', async () => {+ mockClient.toolRouter.session.files.delete.mockResolvedValueOnce(deleteResponse);++ const result = await filesMount.delete('/temp/cache.json');++ expect(mockClient.toolRouter.session.files.delete).toHaveBeenCalledWith(+ DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,+ {+ session_id: sessionId,+ mount_relative_path: '/temp/cache.json',+ }+ );+ expect(result).toEqual({+ mountRelativePath: '/temp/cache.json',+ sandboxMountPrefix: '/mnt/files',+ });+ });++ it('should use custom mountId when provided', async () => {+ mockClient.toolRouter.session.files.delete.mockResolvedValueOnce(deleteResponse);++ await filesMount.delete('/old-backup', { mountId: 'backups' });++ expect(mockClient.toolRouter.session.files.delete).toHaveBeenCalledWith('backups', {+ session_id: sessionId,+ mount_relative_path: '/old-backup',+ });+ });+ });++ describe('upload', () => {+ const mountRelativePath = 'composio-upload-test.txt';+ const createUploadURLResponse = {+ upload_url: 'https://s3.example.com/upload',+ mount_relative_path: mountRelativePath,+ sandbox_mount_prefix: '/mnt/files',+ expires_at: '2025-12-31T23:59:59.000Z',+ };++ const createDownloadURLResponse = {+ download_url: 'https://s3.example.com/presigned',+ mount_relative_path: mountRelativePath,+ sandbox_mount_prefix: '/mnt/files',+ expires_at: '2025-12-31T23:59:59.000Z',+ };++ beforeEach(() => {+ globalThis.fetch = vi.fn().mockImplementation((url: string, init?: RequestInit) => {+ if (init?.method === 'PUT') {+ return Promise.resolve({ ok: true });+ }+ return Promise.reject(new Error('Unexpected fetch'));+ }) as unknown as typeof fetch;+ });++ it('should upload local file and return RemoteFile', async () => {+ const { platform } = await import('../../src/platform/node');+ const { join } = await import('node:path');+ const { tmpdir } = await import('node:os');+ const testFilePath = join(tmpdir(), 'composio-upload-test.txt');+ platform.writeFileSync(testFilePath, 'test content', 'utf8');++ mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce(+ createUploadURLResponse+ );+ mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(+ createDownloadURLResponse+ );++ const result = await filesMount.upload(testFilePath);++ expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(+ DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,+ {+ session_id: sessionId,+ mount_relative_path: 'composio-upload-test.txt',+ mimetype: 'application/octet-stream',+ }+ );+ expect(mockClient.toolRouter.session.files.createDownloadURL).toHaveBeenCalledWith(+ DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,+ {+ session_id: sessionId,+ mount_relative_path: mountRelativePath,+ }+ );+ expect(result.mountRelativePath).toBe(mountRelativePath);+ expect(result.downloadUrl).toBe('https://s3.example.com/presigned');+ });++ it('should handle upload response body wrapper', async () => {+ const { platform } = await import('../../src/platform/node');+ const { join } = await import('node:path');+ const { tmpdir } = await import('node:os');+ const testFilePath = join(tmpdir(), 'composio-upload-test.txt');+ platform.writeFileSync(testFilePath, 'test content', 'utf8');++ mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({+ url: 'https://api.example.com/upload_url',+ status: 201,+ body: createUploadURLResponse,+ });+ mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(+ createDownloadURLResponse+ );++ const result = await filesMount.upload(testFilePath);++ expect(result.mountRelativePath).toBe(mountRelativePath);+ expect(result.downloadUrl).toBe('https://s3.example.com/presigned');+ });++ it('should upload native File object', async () => {+ const file = new File([new TextEncoder().encode('hello')], 'greeting.txt', {+ type: 'text/plain',+ });++ mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({+ ...createUploadURLResponse,+ mount_relative_path: 'greeting.txt',+ });+ mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({+ ...createDownloadURLResponse,+ mount_relative_path: 'greeting.txt',+ });++ const result = await filesMount.upload(file);++ expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(+ DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,+ {+ session_id: sessionId,+ mount_relative_path: 'greeting.txt',+ mimetype: 'text/plain',+ }+ );+ expect(result.mountRelativePath).toBe('greeting.txt');+ });++ it('should upload File with custom remotePath', async () => {+ const file = new File([new Uint8Array([1, 2, 3])], 'original.bin', {+ type: 'application/octet-stream',+ });++ mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({+ ...createUploadURLResponse,+ mount_relative_path: 'custom-name.bin',+ });+ mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({+ ...createDownloadURLResponse,+ mount_relative_path: 'custom-name.bin',+ });++ const result = await filesMount.upload(file, { remotePath: 'custom-name.bin' });++ expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(+ DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,+ {+ session_id: sessionId,+ mount_relative_path: 'custom-name.bin',+ mimetype: 'application/octet-stream',+ }+ );+ expect(result.mountRelativePath).toBe('custom-name.bin');+ });++ it('should upload raw buffer with remotePath and mimetype', async () => {+ const buffer = new TextEncoder().encode('{"key":"value"}');++ mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({+ ...createUploadURLResponse,+ mount_relative_path: 'data.json',+ });+ mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({+ ...createDownloadURLResponse,+ mount_relative_path: 'data.json',+ });++ const result = await filesMount.upload(buffer, {+ remotePath: 'data.json',+ mimetype: 'application/json',+ });++ expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(+ DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,+ {+ session_id: sessionId,+ mount_relative_path: 'data.json',+ mimetype: 'application/json',+ }+ );+ expect(result.mountRelativePath).toBe('data.json');+ });++ it('should return mountRelativePath from API response when it differs from requested path', async () => {+ const buffer = new Uint8Array([0x89, 0x50, 0x4e, 0x47]); // PNG signature++ mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({+ ...createUploadURLResponse,+ mount_relative_path: 'upload-7949b409.jpg', // API returns different path+ });+ mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({+ ...createDownloadURLResponse,+ mount_relative_path: 'upload-7949b409.jpg',+ });++ const result = await filesMount.upload(buffer, { remotePath: 'file.png' });++ expect(result.mountRelativePath).toBe('upload-7949b409.jpg');+ });++ it('should throw when buffer is provided without mimetype or remotePath', async () => {+ const buffer = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);++ await expect(filesMount.upload(buffer)).rejects.toThrow(+ 'When passing a buffer, either mimetype or remotePath (filename) is required'+ );+ });++ it('should upload ArrayBuffer with mimetype when remotePath omitted', async () => {+ const buffer = new ArrayBuffer(8);+ new DataView(buffer).setUint32(0, 0xdeadbeef);++ mockClient.toolRouter.session.files.createUploadURL.mockImplementation((_, params) =>+ Promise.resolve({+ ...createUploadURLResponse,+ mount_relative_path: params.mount_relative_path,+ })+ );+ mockClient.toolRouter.session.files.createDownloadURL.mockImplementation((_, params) =>+ Promise.resolve({+ ...createDownloadURLResponse,+ mount_relative_path: params.mount_relative_path,+ })+ );++ const result = await filesMount.upload(buffer, { mimetype: 'application/octet-stream' });++ expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(+ DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,+ expect.objectContaining({+ session_id: sessionId,+ mimetype: 'application/octet-stream',+ mount_relative_path: expect.stringMatching(/^upload-.+\.bin$/),+ })+ );+ expect(result.mountRelativePath).toMatch(/^upload-.+\.bin$/);+ });+ });+});diff --git a/ts/packages/core/test/models/toolRouter.test.ts b/ts/packages/core/test/models/toolRouter.test.tsindex 0a2010a65..ec17163e3 100644--- a/ts/packages/core/test/models/toolRouter.test.ts+++ b/ts/packages/core/test/models/toolRouter.test.ts@@ -5,7 +5,7 @@ import { telemetry } from '../../src/telemetry/Telemetry';import { MockProvider } from '../utils/mocks/provider.mock';import { Tools } from '../../src/models/Tools';import { ConnectedAccountStatuses } from '../../src/types/connectedAccounts.types';-import { ToolRouterCreateSessionConfig, ToolRouterSession } from '../../src/types/toolRouter.types';+import { ToolRouterCreateSessionConfig, Session } from '../../src/types/toolRouter.types';// Mock dependenciesvi.mock('../../src/telemetry/Telemetry', () => ({@@ -35,6 +35,8 @@ const createMockClient = () => ({link: vi.fn(),toolkits: vi.fn(),executeMeta: vi.fn(),+ search: vi.fn(),+ execute: vi.fn(),},},tools: {@@ -1774,6 +1776,148 @@ describe('ToolRouter', () => {});});+ describe('search function', () => {+ const userId = 'user_123';+ const sessionId = 'session_123';++ const mockSearchResponse = {+ success: true,+ error: null,+ results: [+ {+ index: 1,+ use_case: 'send emails',+ primary_tool_slugs: ['GMAIL_SEND_EMAIL'],+ related_tool_slugs: [],+ toolkits: ['gmail'],+ },+ ],+ tool_schemas: {+ GMAIL_SEND_EMAIL: {+ tool_slug: 'GMAIL_SEND_EMAIL',+ toolkit: 'gmail',+ description: 'Send an email',+ hasFullSchema: true,+ input_schema: {},+ output_schema: {},+ },+ },+ toolkit_connection_statuses: [+ {+ toolkit: 'gmail',+ description: 'Gmail',+ has_active_connection: false,+ status_message: 'No connection',+ },+ ],+ next_steps_guidance: ['Connect Gmail'],+ session: {+ id: 'trs_123',+ generate_id: false,+ instructions: 'Reuse session',+ },+ time_info: {+ current_time_utc: '2025-03-09T12:00:00.000Z',+ current_time_utc_epoch_seconds: 1741521600,+ message: 'UTC',+ },+ };++ it('should call search with correct params and return camelCase response', async () => {+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);+ mockClient.toolRouter.session.search.mockResolvedValueOnce(mockSearchResponse);++ const session = await toolRouter.create(userId);+ const result = await session.search({ query: 'send emails' });++ expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(sessionId, {+ queries: [{ use_case: 'send emails' }],+ });+ expect(result.success).toBe(true);+ expect(result.results[0].useCase).toBe('send emails');+ expect(result.results[0].primaryToolSlugs).toEqual(['GMAIL_SEND_EMAIL']);+ expect(result.toolSchemas.GMAIL_SEND_EMAIL.toolSlug).toBe('GMAIL_SEND_EMAIL');+ expect(result.nextStepsGuidance).toEqual(['Connect Gmail']);+ expect(result.session.generateId).toBe(false);+ expect(result.timeInfo.currentTimeUtcEpochSeconds).toBe(1741521600);+ });++ it('should pass toolkits filter when provided', async () => {+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);+ mockClient.toolRouter.session.search.mockResolvedValueOnce(mockSearchResponse);++ const session = await toolRouter.create(userId);+ await session.search({ query: 'send emails', toolkits: ['gmail', 'slack'] });++ expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(sessionId, {+ queries: [{ use_case: 'send emails' }],+ toolkits: ['gmail', 'slack'],+ });+ });++ it('should propagate search API errors', async () => {+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);+ mockClient.toolRouter.session.search.mockRejectedValueOnce(new Error('Search failed'));++ const session = await toolRouter.create(userId);++ await expect(session.search({ query: 'send emails' })).rejects.toThrow('Search failed');+ });+ });++ describe('execute function', () => {+ const userId = 'user_123';+ const sessionId = 'session_123';++ const mockExecuteResponse = {+ data: { tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' },+ error: null,+ log_id: 'log_abc',+ };++ it('should call execute with correct params and return camelCase response', async () => {+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);+ mockClient.toolRouter.session.execute.mockResolvedValueOnce(mockExecuteResponse);++ const session = await toolRouter.create(userId);+ const result = await session.execute('GMAIL_SEND_EMAIL', {+ to: '[email protected]',+ subject: 'Hi',+ body: 'Hello',+ });++ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {+ tool_slug: 'GMAIL_SEND_EMAIL',+ arguments: { to: '[email protected]', subject: 'Hi', body: 'Hello' },+ });+ expect(result.data).toEqual({ tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' });+ expect(result.error).toBeNull();+ expect(result.logId).toBe('log_abc');+ });++ it('should propagate execute API errors', async () => {+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);+ mockClient.toolRouter.session.execute.mockRejectedValueOnce(new Error('Execute failed'));++ const session = await toolRouter.create(userId);++ await expect(session.execute('GMAIL_SEND_EMAIL')).rejects.toThrow('Execute failed');+ });++ it('should default arguments to empty object when omitted', async () => {+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);+ mockClient.toolRouter.session.execute.mockResolvedValueOnce(mockExecuteResponse);++ const session = await toolRouter.create(userId);+ await session.execute('HACKERNEWS_GET_USER');++ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {+ tool_slug: 'HACKERNEWS_GET_USER',+ arguments: {},+ });+ });+ });+describe('tools function', () => {const userId = 'user_123';const sessionId = 'session_123';diff --git a/ts/packages/core/test/utils/mime.test.ts b/ts/packages/core/test/utils/mime.test.tsnew file mode 100644index 000000000..ff6783870--- /dev/null+++ b/ts/packages/core/test/utils/mime.test.ts@@ -0,0 +1,9 @@+import { describe, it, expect } from 'vitest';+import { getExtensionFromMimeType } from '../../src/utils/mime';++describe('getExtensionFromMimeType', () => {+ it('should return extension for known mimetype', () => {+ expect(getExtensionFromMimeType('image/png')).toBe('png');+ expect(getExtensionFromMimeType('application/pdf')).toBe('pdf');+ });+});diff --git a/ts/packages/core/test/utils/toolRouterResponseTransform.test.ts b/ts/packages/core/test/utils/toolRouterResponseTransform.test.tsnew file mode 100644index 000000000..008a9cec3--- /dev/null+++ b/ts/packages/core/test/utils/toolRouterResponseTransform.test.ts@@ -0,0 +1,164 @@+import { describe, it, expect } from 'vitest';+import {+ transformSearchResponse,+ transformExecuteResponse,+} from '../../src/utils/transformers/toolRouterResponseTransform';++describe('toolRouterResponseTransform', () => {+ describe('transformSearchResponse', () => {+ it('should transform snake_case search response to camelCase', () => {+ const raw = {+ success: true,+ error: null,+ results: [+ {+ index: 1,+ use_case: 'send emails',+ primary_tool_slugs: ['GMAIL_SEND_EMAIL'],+ related_tool_slugs: ['GMAIL_CREATE_DRAFT'],+ toolkits: ['gmail'],+ difficulty: 'easy',+ recommended_plan_steps: ['Step 1', 'Step 2'],+ },+ ],+ tool_schemas: {+ GMAIL_SEND_EMAIL: {+ tool_slug: 'GMAIL_SEND_EMAIL',+ toolkit: 'gmail',+ description: 'Send an email',+ hasFullSchema: true,+ input_schema: { to: { type: 'string' } },+ output_schema: { id: { type: 'string' } },+ },+ },+ toolkit_connection_statuses: [+ {+ toolkit: 'gmail',+ description: 'Gmail toolkit',+ has_active_connection: true,+ status_message: 'Connected',+ },+ ],+ next_steps_guidance: ['Connect Gmail if needed'],+ session: {+ id: 'trs_123',+ generate_id: false,+ instructions: 'Reuse this session id',+ },+ time_info: {+ current_time_utc: '2025-03-09T12:00:00.000Z',+ current_time_utc_epoch_seconds: 1741521600,+ message: 'UTC time',+ },+ };++ const result = transformSearchResponse(raw);++ expect(result.success).toBe(true);+ expect(result.error).toBeNull();+ expect(result.results).toHaveLength(1);+ expect(result.results[0]).toEqual({+ index: 1,+ useCase: 'send emails',+ primaryToolSlugs: ['GMAIL_SEND_EMAIL'],+ relatedToolSlugs: ['GMAIL_CREATE_DRAFT'],+ toolkits: ['gmail'],+ difficulty: 'easy',+ recommendedPlanSteps: ['Step 1', 'Step 2'],+ });+ expect(result.toolSchemas).toHaveProperty('GMAIL_SEND_EMAIL');+ expect(result.toolSchemas.GMAIL_SEND_EMAIL).toEqual({+ toolSlug: 'GMAIL_SEND_EMAIL',+ toolkit: 'gmail',+ description: 'Send an email',+ hasFullSchema: true,+ inputSchema: { to: { type: 'string' } },+ outputSchema: { id: { type: 'string' } },+ });+ expect(result.toolkitConnectionStatuses[0]).toEqual({+ toolkit: 'gmail',+ description: 'Gmail toolkit',+ hasActiveConnection: true,+ statusMessage: 'Connected',+ });+ expect(result.nextStepsGuidance).toEqual(['Connect Gmail if needed']);+ expect(result.session).toEqual({+ id: 'trs_123',+ generateId: false,+ instructions: 'Reuse this session id',+ });+ expect(result.timeInfo).toEqual({+ currentTimeUtc: '2025-03-09T12:00:00.000Z',+ currentTimeUtcEpochSeconds: 1741521600,+ message: 'UTC time',+ });+ });++ it('should transform schemaRef with tool_slugs to toolSlugs', () => {+ const raw = {+ success: true,+ error: null,+ results: [],+ tool_schemas: {+ TOOL_X: {+ tool_slug: 'TOOL_X',+ toolkit: 'x',+ schemaRef: {+ args: { tool_slugs: ['TOOL_X'] },+ message: 'Fetch schema',+ tool: 'COMPOSIO_GET_TOOL_SCHEMAS',+ },+ },+ },+ toolkit_connection_statuses: [],+ next_steps_guidance: [],+ session: {+ id: 'trs_1',+ generate_id: true,+ instructions: 'Use session',+ },+ time_info: {+ current_time_utc: '2025-03-09T12:00:00.000Z',+ current_time_utc_epoch_seconds: 1741521600,+ message: 'UTC',+ },+ };++ const result = transformSearchResponse(raw);+ expect(result.toolSchemas.TOOL_X.schemaRef).toEqual({+ args: { toolSlugs: ['TOOL_X'] },+ message: 'Fetch schema',+ tool: 'COMPOSIO_GET_TOOL_SCHEMAS',+ });+ });+ });++ describe('transformExecuteResponse', () => {+ it('should transform snake_case execute response to camelCase', () => {+ const raw = {+ data: { tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' },+ error: null,+ log_id: 'log_abc',+ };++ const result = transformExecuteResponse(raw);++ expect(result.data).toEqual({ tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' });+ expect(result.error).toBeNull();+ expect(result.logId).toBe('log_abc');+ });++ it('should preserve error in execute response', () => {+ const raw = {+ data: {},+ error: 'Connection not found',+ log_id: 'log_err',+ };++ const result = transformExecuteResponse(raw);++ expect(result.error).toBe('Connection not found');+ expect(result.logId).toBe('log_err');+ });+ });+});