Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 04:45 UTC
| 1 | import { telemetry } from '../telemetry/Telemetry'; |
| 2 | import { Composio as ComposioClient } from '@composio/client'; |
| 3 | import { |
| 4 | FileDeleteResponse, |
| 5 | FileDeleteResponseSchema, |
| 6 | FileListResponse, |
| 7 | FileListResponseSchema, |
| 8 | RemoteFileDataSchema, |
| 9 | ToolRouterSessionFilesMountDeleteOptions, |
| 10 | ToolRouterSessionFilesMountDeleteOptionsSchema, |
| 11 | ToolRouterSessionFilesMountDownloadOptions, |
| 12 | ToolRouterSessionFilesMountDownloadOptionsSchema, |
| 13 | ToolRouterSessionFilesMountListOptions, |
| 14 | ToolRouterSessionFilesMountListOptionsSchema, |
| 15 | ToolRouterSessionFilesMountUploadOptions, |
| 16 | ToolRouterSessionFilesMountUploadOptionsSchema, |
| 17 | } from '../types/ToolRouterSessionFilesMount.types'; |
| 18 | import { RemoteFile } from './RemoteFile'; |
| 19 | import { ValidationError } from '../errors'; |
| 20 | import { platform } from '#platform'; |
| 21 | import { ssrfSafeFetch, ssrfSafeFetchWhereSupported } from '#ssrf_guard'; |
| 22 | import { getExtensionFromMimeType } from '../utils/mime'; |
| 23 | import { readResponseBodyWithLimit } from '../utils/readResponseBody'; |
| 24 | import { getRandomShortId } from '../utils/uuid'; |
| 25 | |
| 26 | /** |
| 27 | * File mount for a Composio session, reached via `session.experimental.files` |
| 28 | * on a session created with `composio.sessions.create(...)`. Upload, list, |
| 29 | * download, and delete files scoped to a single session. |
| 30 | */ |
| 31 | export class ToolRouterSessionFilesMount { |
| 32 | private readonly sessionId: string; |
| 33 | private readonly client: ComposioClient; |
| 34 | |
| 35 | constructor(client: ComposioClient, sessionId: string) { |
| 36 | this.client = client; |
| 37 | this.sessionId = sessionId; |
| 38 | telemetry.instrument(this, 'ToolRouterSessionFiles'); |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Lists files and directories at the specified path on the session's file mount. |
| 43 | * |
| 44 | * Use this to browse the virtual filesystem attached to the tool router session. |
| 45 | * The path is relative to the mount root (e.g., `"/"` for root, `"/documents"` for a subdirectory). |
| 46 | * Supports cursor-based pagination via `cursor` and `limit` options. |
| 47 | * |
| 48 | * @param options - Optional configuration for the list operation. |
| 49 | * @param options.path - The directory path to list. Use `"/"` for the mount root. |
| 50 | * @param options.mountId - The ID of the file mount to operate on. Defaults to `"files"` when omitted. |
| 51 | * @param options.cursor - Pagination cursor from the previous response's nextCursor field. |
| 52 | * @param options.limit - Maximum number of files to return per page (1-500). |
| 53 | * @returns List of files with nextCursor for pagination. |
| 54 | * |
| 55 | * @example |
| 56 | * ```typescript |
| 57 | * const session = await composio.toolRouter.use('session_123'); |
| 58 | * const { items, nextCursor } = await session.experimental.files.list({ path: '/' }); |
| 59 | * ``` |
| 60 | * |
| 61 | * @example |
| 62 | * ```typescript |
| 63 | * // Paginated listing |
| 64 | * let result = await session.experimental.files.list({ path: '/', limit: 10 }); |
| 65 | * while (result.nextCursor) { |
| 66 | * result = await session.experimental.files.list({ path: '/', cursor: result.nextCursor, limit: 10 }); |
| 67 | * } |
| 68 | * ``` |
| 69 | */ |
| 70 | async list(options?: ToolRouterSessionFilesMountListOptions): Promise<FileListResponse> { |
| 71 | const listOptions = ToolRouterSessionFilesMountListOptionsSchema.safeParse(options ?? {}); |
| 72 | |
| 73 | if (!listOptions.success) { |
| 74 | throw new ValidationError('Failed to parse tool router session files mount list options', { |
| 75 | cause: listOptions.error, |
| 76 | }); |
| 77 | } |
| 78 | |
| 79 | // API requires: no leading slash, min 1 char when provided. Omit for root. |
| 80 | const rawPath = listOptions.data.path; |
| 81 | const mountRelativePrefix = |
| 82 | rawPath === undefined || rawPath === '' || rawPath === '/' |
| 83 | ? undefined |
| 84 | : rawPath.startsWith('/') |
| 85 | ? rawPath.slice(1) |
| 86 | : rawPath; |
| 87 | |
| 88 | const response = await this.client.toolRouter.session.files.list(listOptions.data.mountId, { |
| 89 | session_id: this.sessionId, |
| 90 | mount_relative_prefix: mountRelativePrefix, |
| 91 | cursor: listOptions.data.cursor, |
| 92 | limit: listOptions.data.limit, |
| 93 | }); |
| 94 | |
| 95 | const data = |
| 96 | typeof response === 'object' && 'body' in response |
| 97 | ? (response as { body: unknown }).body |
| 98 | : response; |
| 99 | |
| 100 | const parsed = FileListResponseSchema.safeParse(data); |
| 101 | if (!parsed.success) { |
| 102 | throw new ValidationError('Failed to parse file list response', { |
| 103 | cause: parsed.error, |
| 104 | }); |
| 105 | } |
| 106 | return parsed.data; |
| 107 | } |
| 108 | |
| 109 | private async normalizeUploadInput( |
| 110 | input: string | File | ArrayBuffer | Uint8Array, |
| 111 | options: { remotePath?: string; mimetype?: string } |
| 112 | ): Promise<{ fileToUpload: File; remotePath: string; mimetype: string }> { |
| 113 | if (typeof input === 'string') { |
| 114 | if (input.startsWith('http://') || input.startsWith('https://')) { |
| 115 | const response = await ssrfSafeFetch(input); |
| 116 | if (!response.ok) { |
| 117 | // The error path never reads the body, so release it explicitly (mirrors |
| 118 | // `readResponseBodyWithLimit`) instead of leaving it to the garbage collector. |
| 119 | await response.body?.cancel().catch(() => undefined); |
| 120 | throw new Error(`Failed to fetch file from URL: ${response.statusText}`); |
| 121 | } |
| 122 | const content = await readResponseBodyWithLimit(response); |
| 123 | const rawContentType = response.headers.get('content-type') || 'application/octet-stream'; |
| 124 | const mimeType = rawContentType.split(';')[0].trim(); |
| 125 | const url = new URL(input); |
| 126 | const pathname = url.pathname; |
| 127 | const segments = pathname.split('/').filter(Boolean); |
| 128 | let filename = segments.length > 0 ? segments[segments.length - 1] : ''; |
| 129 | if (!filename || !filename.includes('.')) { |
| 130 | const extension = getExtensionFromMimeType(mimeType); |
| 131 | filename = `${getRandomShortId()}.${extension}`; |
| 132 | } |
| 133 | const file = new File([content as BlobPart], filename, { type: mimeType }); |
| 134 | return { |
| 135 | fileToUpload: file, |
| 136 | remotePath: options.remotePath ?? filename, |
| 137 | mimetype: mimeType, |
| 138 | }; |
| 139 | } |
| 140 | const content = platform.readFileSync(input); |
| 141 | const buffer = |
| 142 | content instanceof Uint8Array |
| 143 | ? new Uint8Array(content) |
| 144 | : new TextEncoder().encode(content as string); |
| 145 | const filename = platform.basename(input); |
| 146 | const mimetype = options.mimetype ?? 'application/octet-stream'; |
| 147 | const file = new File([buffer], filename, { type: mimetype }); |
| 148 | return { |
| 149 | fileToUpload: file, |
| 150 | remotePath: options.remotePath ?? filename, |
| 151 | mimetype, |
| 152 | }; |
| 153 | } |
| 154 | |
| 155 | if (input instanceof File) { |
| 156 | return { |
| 157 | fileToUpload: input, |
| 158 | remotePath: options.remotePath ?? (input.name || `upload-${getRandomShortId()}.bin`), |
| 159 | mimetype: input.type || 'application/octet-stream', |
| 160 | }; |
| 161 | } |
| 162 | |
| 163 | const buffer = input instanceof ArrayBuffer ? new Uint8Array(input) : input; |
| 164 | if (!options.mimetype && !options.remotePath) { |
| 165 | throw new Error( |
| 166 | 'When passing a buffer, either mimetype or remotePath (filename) is required. ' + |
| 167 | 'Example: files.upload(buffer, { remotePath: "data.json", mimetype: "application/json" })' |
| 168 | ); |
| 169 | } |
| 170 | const mimetype = options.mimetype ?? 'application/octet-stream'; |
| 171 | const ext = getExtensionFromMimeType(mimetype); |
| 172 | const remotePath = options.remotePath ?? `upload-${getRandomShortId()}.${ext}`; |
| 173 | const file = new File([buffer as BlobPart], remotePath, { type: mimetype }); |
| 174 | return { |
| 175 | fileToUpload: file, |
| 176 | remotePath, |
| 177 | mimetype, |
| 178 | }; |
| 179 | } |
| 180 | |
| 181 | /** |
| 182 | * Uploads a file to the session's file mount. |
| 183 | * |
| 184 | * Accepts a file path (local or URL), a native File object, or a raw buffer. |
| 185 | * The file is stored in the virtual filesystem associated with the tool router session. |
| 186 | * URL inputs require a Node.js or Bun runtime so the destination can be DNS-validated; |
| 187 | * edge runtimes must fetch the file themselves and pass a File or ArrayBuffer. |
| 188 | * |
| 189 | * @param input - File path (string), native File, or raw buffer (ArrayBuffer | Uint8Array). |
| 190 | * @param options - Optional configuration. When passing a buffer, remotePath is required. |
| 191 | * @returns Metadata about the uploaded file. |
| 192 | * |
| 193 | * @example |
| 194 | * ```typescript |
| 195 | * // From file path (local or URL) |
| 196 | * await session.experimental.files.upload('/path/to/report.pdf'); |
| 197 | * await session.experimental.files.upload('https://example.com/file.pdf'); |
| 198 | * ``` |
| 199 | * |
| 200 | * @example |
| 201 | * ```typescript |
| 202 | * // From native File (e.g. from input[type=file]) |
| 203 | * await session.experimental.files.upload(fileInput.files[0]); |
| 204 | * ``` |
| 205 | * |
| 206 | * @example |
| 207 | * ```typescript |
| 208 | * // From raw buffer |
| 209 | * await session.experimental.files.upload(buffer, { remotePath: 'data.json', mimetype: 'application/json' }); |
| 210 | * ``` |
| 211 | */ |
| 212 | async upload( |
| 213 | input: string | File | ArrayBuffer | Uint8Array, |
| 214 | options?: ToolRouterSessionFilesMountUploadOptions |
| 215 | ): Promise<RemoteFile> { |
| 216 | const uploadOptions = ToolRouterSessionFilesMountUploadOptionsSchema.safeParse(options ?? {}); |
| 217 | |
| 218 | if (!uploadOptions.success) { |
| 219 | throw new ValidationError('Failed to parse tool router session files mount upload options', { |
| 220 | cause: uploadOptions.error, |
| 221 | }); |
| 222 | } |
| 223 | |
| 224 | const { fileToUpload, remotePath, mimetype } = await this.normalizeUploadInput( |
| 225 | input, |
| 226 | uploadOptions.data |
| 227 | ); |
| 228 | |
| 229 | const createUploadURLResponse = await this.client.toolRouter.session.files.createUploadURL( |
| 230 | uploadOptions.data.mountId, |
| 231 | { |
| 232 | session_id: this.sessionId, |
| 233 | mount_relative_path: remotePath, |
| 234 | mimetype, |
| 235 | } |
| 236 | ); |
| 237 | |
| 238 | const uploadURLData = |
| 239 | typeof createUploadURLResponse === 'object' && 'body' in createUploadURLResponse |
| 240 | ? (createUploadURLResponse as { body: unknown }).body |
| 241 | : createUploadURLResponse; |
| 242 | |
| 243 | // SSRF guard: `upload_url` comes from the API response, so the target is |
| 244 | // validated before the file's bytes are sent to it — the same treatment the |
| 245 | // user-supplied URL above already gets. See ssrfGuard.node.ts. |
| 246 | const uploadResponse = await ssrfSafeFetchWhereSupported( |
| 247 | (uploadURLData as { upload_url: string }).upload_url, |
| 248 | { |
| 249 | method: 'PUT', |
| 250 | body: await fileToUpload.arrayBuffer(), |
| 251 | headers: { |
| 252 | 'Content-Type': mimetype, |
| 253 | }, |
| 254 | } |
| 255 | ); |
| 256 | |
| 257 | if (!uploadResponse.ok) { |
| 258 | throw new Error(`Failed to upload file: ${uploadResponse.statusText}`); |
| 259 | } |
| 260 | |
| 261 | const createDownloadURLResponse = await this.client.toolRouter.session.files.createDownloadURL( |
| 262 | uploadOptions.data.mountId, |
| 263 | { |
| 264 | session_id: this.sessionId, |
| 265 | mount_relative_path: (uploadURLData as { mount_relative_path: string }).mount_relative_path, |
| 266 | } |
| 267 | ); |
| 268 | |
| 269 | const downloadData = |
| 270 | typeof createDownloadURLResponse === 'object' && 'body' in createDownloadURLResponse |
| 271 | ? (createDownloadURLResponse as { body: unknown }).body |
| 272 | : createDownloadURLResponse; |
| 273 | |
| 274 | const parsed = RemoteFileDataSchema.safeParse(downloadData); |
| 275 | if (!parsed.success) { |
| 276 | throw new ValidationError('Failed to parse remote file properties', { |
| 277 | cause: parsed.error, |
| 278 | }); |
| 279 | } |
| 280 | |
| 281 | return new RemoteFile(parsed.data); |
| 282 | } |
| 283 | |
| 284 | /** |
| 285 | * Downloads a file from the session's file mount to the local filesystem. |
| 286 | * |
| 287 | * Retrieves a file stored in the session's virtual filesystem (e.g., one produced |
| 288 | * by a tool or previously uploaded) and saves it to the specified local path. |
| 289 | * |
| 290 | * @param filePath - The path of the file on the mount to download, or the local path where the file should be saved (implementation-specific). |
| 291 | * @param options - Optional configuration for the download. |
| 292 | * @param options.mountId - The ID of the file mount to download from. Defaults to `"files"` when omitted. |
| 293 | * @returns The downloaded file data or path (implementation-specific). |
| 294 | * |
| 295 | * @example |
| 296 | * ```typescript |
| 297 | * const session = await composio.toolRouter.use('session_123'); |
| 298 | * const result = await session.experimental.files.download('/output/report.pdf'); |
| 299 | * ``` |
| 300 | * |
| 301 | * @example |
| 302 | * ```typescript |
| 303 | * // Download from a custom mount |
| 304 | * await session.experimental.files.download('/exports/data.json', { |
| 305 | * mountId: 'custom-mount', |
| 306 | * }); |
| 307 | * ``` |
| 308 | */ |
| 309 | async download( |
| 310 | filePath: string, |
| 311 | options?: ToolRouterSessionFilesMountDownloadOptions |
| 312 | ): Promise<RemoteFile> { |
| 313 | const downloadOptions = ToolRouterSessionFilesMountDownloadOptionsSchema.safeParse( |
| 314 | options ?? {} |
| 315 | ); |
| 316 | |
| 317 | if (!downloadOptions.success) { |
| 318 | throw new ValidationError( |
| 319 | 'Failed to parse tool router session files mount download options', |
| 320 | { |
| 321 | cause: downloadOptions.error, |
| 322 | } |
| 323 | ); |
| 324 | } |
| 325 | |
| 326 | const createDownloadURLResponse = await this.client.toolRouter.session.files.createDownloadURL( |
| 327 | downloadOptions.data.mountId, |
| 328 | { |
| 329 | session_id: this.sessionId, |
| 330 | mount_relative_path: filePath, |
| 331 | } |
| 332 | ); |
| 333 | |
| 334 | const downloadURLData = |
| 335 | typeof createDownloadURLResponse === 'object' && 'body' in createDownloadURLResponse |
| 336 | ? (createDownloadURLResponse as { body: unknown }).body |
| 337 | : createDownloadURLResponse; |
| 338 | |
| 339 | const parsed = RemoteFileDataSchema.safeParse(downloadURLData); |
| 340 | if (!parsed.success) { |
| 341 | throw new ValidationError('Failed to parse remote file properties', { |
| 342 | cause: parsed.error, |
| 343 | }); |
| 344 | } |
| 345 | return new RemoteFile(parsed.data); |
| 346 | } |
| 347 | |
| 348 | /** |
| 349 | * Deletes a file or directory at the specified path on the session's file mount. |
| 350 | * |
| 351 | * Removes the file or directory from the virtual filesystem. Use with caution: |
| 352 | * deletion is typically irreversible. Ensure the path exists and is intended for removal. |
| 353 | * |
| 354 | * @param remotePath - The path of the file or directory to delete on the mount. |
| 355 | * @param options - Optional configuration for the delete operation. |
| 356 | * @param options.mountId - The ID of the file mount to operate on. Defaults to `"files"` when omitted. |
| 357 | * @returns Confirmation of deletion (implementation-specific). |
| 358 | * |
| 359 | * @example |
| 360 | * ```typescript |
| 361 | * const session = await composio.toolRouter.use('session_123'); |
| 362 | * await session.experimental.files.delete('/temp/cache.json'); |
| 363 | * ``` |
| 364 | * |
| 365 | * @example |
| 366 | * ```typescript |
| 367 | * // Delete from a custom mount |
| 368 | * await session.experimental.files.delete('/old-backup', { |
| 369 | * mountId: 'custom-mount', |
| 370 | * }); |
| 371 | * ``` |
| 372 | * |
| 373 | * @warning This operation is destructive. Deleted files cannot be recovered. |
| 374 | */ |
| 375 | async delete( |
| 376 | remotePath: string, |
| 377 | options?: ToolRouterSessionFilesMountDeleteOptions |
| 378 | ): Promise<FileDeleteResponse> { |
| 379 | const deleteOptions = ToolRouterSessionFilesMountDeleteOptionsSchema.safeParse(options ?? {}); |
| 380 | |
| 381 | if (!deleteOptions.success) { |
| 382 | throw new ValidationError('Failed to parse tool router session files mount delete options', { |
| 383 | cause: deleteOptions.error, |
| 384 | }); |
| 385 | } |
| 386 | |
| 387 | const deleteResponse = await this.client.toolRouter.session.files.delete( |
| 388 | deleteOptions.data.mountId, |
| 389 | { |
| 390 | session_id: this.sessionId, |
| 391 | mount_relative_path: remotePath, |
| 392 | } |
| 393 | ); |
| 394 | const fileDeleteResponse = FileDeleteResponseSchema.safeParse(deleteResponse); |
| 395 | if (!fileDeleteResponse.success) { |
| 396 | throw new ValidationError('Failed to parse file delete response', { |
| 397 | cause: fileDeleteResponse.error, |
| 398 | }); |
| 399 | } |
| 400 | return fileDeleteResponse.data; |
| 401 | } |
| 402 | } |