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

next
ts 237 lines 8.32 KB
Raw
1 import { platform } from '#platform';
2 import { ssrfSafeFetchWhereSupported } from '#ssrf_guard';
3 import { COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME } from '../utils/constants';
4 import { z } from 'zod';
5
6 const existingFileError = z.object({ code: z.literal('EEXIST') });
7
8 function getParentDir(filePath: string): string {
9 const lastSep = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
10 if (lastSep <= 0) return '';
11 return filePath.slice(0, lastSep);
12 }
13 import { RemoteFileData, RemoteFileDataSchema } from '../types/ToolRouterSessionFilesMount.types';
14 import {
15 ComposioBlockedInternalUrlError,
16 RemoteFileDownloadError,
17 ValidationError,
18 } from '../errors';
19 import { readResponseBodyWithLimit } from '../utils/readResponseBody';
20 import { numberedBasename, safeBasename, untrustedBasename } from '../utils/safePath';
21
22 /**
23 * Represents a file stored in a tool router session's file mount.
24 * Provides methods to fetch, save, and work with the file content.
25 *
26 * @example
27 * ```typescript
28 * const remoteFile = await session.experimental.files.download('/output/report.pdf');
29 * const buffer = await remoteFile.buffer();
30 * await remoteFile.save('/tmp/report.pdf');
31 * const text = await remoteFile.text();
32 * ```
33 *
34 * @example
35 * ```typescript
36 * // Create from API response (snake_case)
37 * const remoteFile = RemoteFile.parse(apiResponse);
38 *
39 * // Or create from parsed data (camelCase)
40 * const remoteFile = new RemoteFile({
41 * expiresAt: '...',
42 * mountRelativePath: 'report.pdf',
43 * sandboxMountPrefix: '/mnt/files',
44 * downloadUrl: 'https://...',
45 * });
46 * ```
47 */
48 export class RemoteFile {
49 /** ISO 8601 timestamp when the download URL expires */
50 readonly expiresAt: string;
51
52 /** Relative path within the mount (e.g. "report.pdf") */
53 readonly mountRelativePath: string;
54
55 /** Absolute mount path inside the sandbox (e.g. /mnt/files) */
56 readonly sandboxMountPrefix: string;
57
58 /** Presigned URL for downloading the file */
59 readonly downloadUrl: string;
60
61 constructor(data: RemoteFileData) {
62 this.expiresAt = data.expiresAt;
63 this.mountRelativePath = data.mountRelativePath;
64 this.sandboxMountPrefix = data.sandboxMountPrefix;
65 this.downloadUrl = data.downloadUrl;
66 }
67
68 /**
69 * Parses an API response (snake_case) and returns a RemoteFile instance.
70 * @param data - Raw API response with snake_case keys
71 * @returns A RemoteFile instance
72 * @throws ValidationError if the response shape is invalid
73 */
74 static parse(data: unknown): RemoteFile {
75 const parsed = RemoteFileDataSchema.safeParse(data);
76 if (!parsed.success) {
77 throw new ValidationError('Failed to parse remote file response', {
78 cause: parsed.error,
79 });
80 }
81 return new RemoteFile(parsed.data);
82 }
83
84 /**
85 * Filename extracted from the mount path (e.g. "report.pdf" from "output/report.pdf").
86 *
87 * Deliberately non-throwing: this is a display value, and `downloadBytes()`
88 * reads it while constructing `RemoteFileDownloadError`. A validator here
89 * would replace a genuine download error with a validation error thrown from
90 * inside the error constructor. {@link save} validates instead, at the point
91 * the value actually becomes a path.
92 *
93 * Both `/` and `\` count as separators, as in the Python SDK, so a mount path
94 * crafted for a Windows target is reduced the same way on every platform.
95 */
96 get filename(): string {
97 return untrustedBasename(this.mountRelativePath);
98 }
99
100 private downloadError(message: string, cause: unknown, response?: Response) {
101 return new RemoteFileDownloadError(message, {
102 statusCode: response?.status,
103 statusText: response?.statusText,
104 downloadUrl: this.downloadUrl,
105 mountRelativePath: this.mountRelativePath,
106 filename: this.filename,
107 cause,
108 });
109 }
110
111 private async downloadBytes(): Promise<{ content: Uint8Array; contentType: string }> {
112 let response: Response;
113 try {
114 response = await ssrfSafeFetchWhereSupported(this.downloadUrl);
115 } catch (error) {
116 if (error instanceof ComposioBlockedInternalUrlError) {
117 throw error;
118 }
119 throw this.downloadError('Failed to download file', error);
120 }
121
122 if (!response.ok) {
123 await response.body?.cancel().catch(() => undefined);
124 throw this.downloadError(
125 `Failed to download file: ${response.status} ${response.statusText}`,
126 new Error(`HTTP ${response.status}: ${response.statusText}`),
127 response
128 );
129 }
130
131 try {
132 const content = response.body
133 ? await readResponseBodyWithLimit(response)
134 : new Uint8Array(await response.arrayBuffer());
135 return {
136 content,
137 contentType: response.headers?.get?.('content-type') ?? '',
138 };
139 } catch (error) {
140 await response.body?.cancel().catch(() => undefined);
141 throw this.downloadError('Failed to read downloaded file', error, response);
142 }
143 }
144
145 /**
146 * Fetches the file content as a buffer.
147 * @returns The file content as a Uint8Array
148 * @throws RemoteFileDownloadError if the fetch fails
149 */
150 async buffer(): Promise<Uint8Array> {
151 return (await this.downloadBytes()).content;
152 }
153
154 /**
155 * Fetches the file content as UTF-8 text.
156 * @returns The file content as a string
157 * @throws Error if the fetch fails
158 */
159 async text(): Promise<string> {
160 const buf = await this.buffer();
161 return new TextDecoder().decode(buf);
162 }
163
164 /**
165 * Fetches the file content as a Blob.
166 * @returns The file content as a Blob
167 * @throws RemoteFileDownloadError if the fetch fails
168 */
169 async blob(): Promise<Blob> {
170 const { content, contentType } = await this.downloadBytes();
171 return new Blob([content as BlobPart], { type: contentType });
172 }
173
174 /**
175 * Downloads and saves the file to the local filesystem.
176 * Requires a Node.js runtime with file system support (not available in Cloudflare Workers/Edge).
177 *
178 * @param path - Local path to save the file. An explicit path does not require a home directory.
179 * If omitted, saves to the Composio temp directory using the filename from the mount path.
180 * An existing default destination gets a copy number before its extension.
181 * @returns The absolute path where the file was saved
182 * @throws Error if file system is not supported or the save fails
183 * @throws ValidationError if `path` is omitted and the mount path yields no usable filename
184 */
185 async save(path?: string): Promise<string> {
186 if (!platform.supportsFileSystem) {
187 throw new Error(
188 'File system operations are not supported in this runtime (e.g. Cloudflare Workers). ' +
189 'Use buffer(), text(), or blob() to work with the file content in memory, or run in Node.js.'
190 );
191 }
192
193 // An explicit `path` is the caller's own, so it needs no home directory.
194 if (path != null) {
195 const content = await this.buffer();
196 const dir = getParentDir(path);
197 if (dir && !platform.existsSync(dir)) {
198 platform.mkdirSync(dir);
199 }
200 platform.writeFileSync(path, content);
201 return path;
202 }
203
204 const homeDir = platform.homedir();
205 if (!homeDir) {
206 throw new Error('Cannot determine save location: home directory is not available');
207 }
208
209 // The default path is built from `mountRelativePath`, a server-controlled
210 // response field, so it is validated first (SEC-316, mirroring the Python
211 // SDK): a value such as `""`, `"."` or `"foo/.."` would otherwise make
212 // `savePath` its own directory or the parent, and fail with a raw `EISDIR`
213 // only after `mkdirSync` had run.
214 const defaultDir = platform.joinPath(homeDir, COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
215 const defaultName = safeBasename(this.mountRelativePath, 'mount path');
216 const savePath = platform.joinPath(defaultDir, defaultName);
217
218 const content = await this.buffer();
219
220 if (!platform.existsSync(defaultDir)) {
221 platform.mkdirSync(defaultDir);
222 }
223
224 // Server names can equal a digest-tagged name literally. Reserve a new
225 // destination atomically so either save order keeps both downloads.
226 for (let copy = 0; ; copy++) {
227 const destination =
228 copy === 0 ? savePath : platform.joinPath(defaultDir, numberedBasename(defaultName, copy));
229 try {
230 platform.writeFileExclusiveSync(destination, content);
231 return destination;
232 } catch (error) {
233 if (!existingFileError.safeParse(error).success) throw error;
234 }
235 }
236 }
237 }