-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathfile.ts
More file actions
443 lines (417 loc) · 14.2 KB
/
file.ts
File metadata and controls
443 lines (417 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import { createLogger } from '@sim/logger'
import { DocumentIcon } from '@/components/icons'
import { inferContextFromKey } from '@/lib/uploads/utils/file-utils'
import type { BlockConfig, SubBlockType } from '@/blocks/types'
import { IntegrationType } from '@/blocks/types'
import { createVersionedToolSelector, normalizeFileInput } from '@/blocks/utils'
import type { FileParserOutput, FileParserV3Output } from '@/tools/file/types'
const logger = createLogger('FileBlock')
const resolveFilePathFromInput = (fileInput: unknown): string | null => {
if (!fileInput || typeof fileInput !== 'object') {
return null
}
const record = fileInput as Record<string, unknown>
if (typeof record.path === 'string' && record.path.trim() !== '') {
return record.path
}
if (typeof record.url === 'string' && record.url.trim() !== '') {
return record.url
}
if (typeof record.key === 'string' && record.key.trim() !== '') {
const key = record.key.trim()
const context = typeof record.context === 'string' ? record.context : inferContextFromKey(key)
return `/api/files/serve/${encodeURIComponent(key)}?context=${context}`
}
return null
}
const resolveFilePathsFromInput = (fileInput: unknown): string[] => {
if (!fileInput) {
return []
}
if (Array.isArray(fileInput)) {
return fileInput
.map((file) => resolveFilePathFromInput(file))
.filter((path): path is string => Boolean(path))
}
const resolved = resolveFilePathFromInput(fileInput)
return resolved ? [resolved] : []
}
export const FileBlock: BlockConfig<FileParserOutput> = {
type: 'file',
name: 'File (Legacy)',
description: 'Read and parse multiple files',
longDescription: `Integrate File into the workflow. Can upload a file manually or insert a file url.`,
bestPractices: `
- You should always use the File URL input method and enter the file URL if the user gives it to you or clarify if they have one.
`,
docsLink: 'https://docs.sim.ai/tools/file',
category: 'tools',
integrationType: IntegrationType.FileStorage,
tags: ['document-processing'],
bgColor: '#40916C',
icon: DocumentIcon,
hideFromToolbar: true,
subBlocks: [
{
id: 'inputMethod',
title: 'Select Input Method',
type: 'dropdown' as SubBlockType,
options: [
{ id: 'url', label: 'File URL' },
{ id: 'upload', label: 'Uploaded Files' },
],
},
{
id: 'filePath',
title: 'File URL',
type: 'short-input' as SubBlockType,
placeholder: 'Enter URL to a file (https://example.com/document.pdf)',
condition: {
field: 'inputMethod',
value: 'url',
},
},
{
id: 'file',
title: 'Process Files',
type: 'file-upload' as SubBlockType,
acceptedTypes:
'.pdf,.csv,.doc,.docx,.txt,.md,.xlsx,.xls,.html,.htm,.pptx,.ppt,.json,.xml,.rtf',
multiple: true,
condition: {
field: 'inputMethod',
value: 'upload',
},
maxSize: 100, // 100MB max via direct upload
},
],
tools: {
access: ['file_parser'],
config: {
tool: () => 'file_parser',
params: (params) => {
// Determine input method - default to 'url' if not specified
const inputMethod = params.inputMethod || 'url'
if (inputMethod === 'url') {
if (!params.filePath || params.filePath.trim() === '') {
logger.error('Missing file URL')
throw new Error('File URL is required')
}
const fileUrl = params.filePath.trim()
return {
filePath: fileUrl,
fileType: params.fileType || 'auto',
workspaceId: params._context?.workspaceId,
}
}
// Handle file upload input
if (inputMethod === 'upload') {
const filePaths = resolveFilePathsFromInput(params.file)
if (filePaths.length > 0) {
return {
filePath: filePaths.length === 1 ? filePaths[0] : filePaths,
fileType: params.fileType || 'auto',
}
}
// If no files, return error
logger.error('No files provided for upload method')
throw new Error('Please upload a file')
}
// This part should ideally not be reached if logic above is correct
logger.error(`Invalid configuration or state: ${inputMethod}`)
throw new Error('Invalid configuration: Unable to determine input method')
},
},
},
inputs: {
inputMethod: { type: 'string', description: 'Input method selection' },
filePath: { type: 'string', description: 'File URL path' },
fileType: { type: 'string', description: 'File type' },
file: { type: 'json', description: 'Uploaded file data' },
},
outputs: {
files: {
type: 'file[]',
description: 'Array of parsed file objects with content, metadata, and file properties',
},
combinedContent: {
type: 'string',
description: 'All file contents merged into a single text string',
},
processedFiles: {
type: 'file[]',
description: 'Array of UserFile objects for downstream use (attachments, uploads, etc.)',
},
},
}
export const FileV2Block: BlockConfig<FileParserOutput> = {
...FileBlock,
type: 'file_v2',
name: 'File (Legacy)',
description: 'Read and parse multiple files',
hideFromToolbar: true,
subBlocks: [
{
id: 'file',
title: 'Files',
type: 'file-upload' as SubBlockType,
canonicalParamId: 'fileInput',
acceptedTypes:
'.pdf,.csv,.doc,.docx,.txt,.md,.xlsx,.xls,.html,.htm,.pptx,.ppt,.json,.xml,.rtf',
placeholder: 'Upload files to process',
multiple: true,
mode: 'basic',
maxSize: 100,
},
{
id: 'filePath',
title: 'Files',
type: 'short-input' as SubBlockType,
canonicalParamId: 'fileInput',
placeholder: 'File URL',
mode: 'advanced',
},
],
tools: {
access: ['file_parser_v2'],
config: {
tool: createVersionedToolSelector({
baseToolSelector: () => 'file_parser',
suffix: '_v2',
fallbackToolId: 'file_parser_v2',
}),
params: (params) => {
// Use canonical 'fileInput' param directly
const fileInput = params.fileInput
if (!fileInput) {
logger.error('No file input provided')
throw new Error('File is required')
}
// First, try to normalize as file objects (handles JSON strings from advanced mode)
const normalizedFiles = normalizeFileInput(fileInput)
if (normalizedFiles) {
const filePaths = resolveFilePathsFromInput(normalizedFiles)
if (filePaths.length > 0) {
return {
filePath: filePaths.length === 1 ? filePaths[0] : filePaths,
fileType: params.fileType || 'auto',
workspaceId: params._context?.workspaceId,
}
}
}
// If normalization fails, treat as direct URL string
if (typeof fileInput === 'string' && fileInput.trim()) {
return {
filePath: fileInput.trim(),
fileType: params.fileType || 'auto',
workspaceId: params._context?.workspaceId,
}
}
logger.error('Invalid file input format')
throw new Error('Invalid file input')
},
},
},
inputs: {
fileInput: { type: 'json', description: 'File input (canonical param)' },
fileType: { type: 'string', description: 'File type' },
},
outputs: {
files: {
type: 'file[]',
description: 'Array of parsed file objects with content, metadata, and file properties',
},
combinedContent: {
type: 'string',
description: 'All file contents merged into a single text string',
},
},
}
export const FileV3Block: BlockConfig<FileParserV3Output> = {
type: 'file_v3',
name: 'File',
description: 'Read and write workspace files',
longDescription:
'Read and parse files from uploads or URLs, write new workspace files, or append content to existing files.',
docsLink: 'https://docs.sim.ai/tools/file',
category: 'tools',
integrationType: IntegrationType.FileStorage,
tags: ['document-processing'],
bgColor: '#40916C',
icon: DocumentIcon,
subBlocks: [
{
id: 'operation',
title: 'Operation',
type: 'dropdown' as SubBlockType,
options: [
{ label: 'Read', id: 'file_parser_v3' },
{ label: 'Write', id: 'file_write' },
{ label: 'Append', id: 'file_append' },
],
value: () => 'file_parser_v3',
},
{
id: 'file',
title: 'Files',
type: 'file-upload' as SubBlockType,
canonicalParamId: 'fileInput',
acceptedTypes: '*',
placeholder: 'Upload files to process',
multiple: true,
mode: 'basic',
maxSize: 100,
required: { field: 'operation', value: 'file_parser_v3' },
condition: { field: 'operation', value: 'file_parser_v3' },
},
{
id: 'fileUrl',
title: 'File URL',
type: 'short-input' as SubBlockType,
canonicalParamId: 'fileInput',
placeholder: 'https://example.com/document.pdf',
mode: 'advanced',
required: { field: 'operation', value: 'file_parser_v3' },
condition: { field: 'operation', value: 'file_parser_v3' },
},
{
id: 'fileName',
title: 'File Name',
type: 'short-input' as SubBlockType,
placeholder: 'File name (e.g., data.csv)',
condition: { field: 'operation', value: 'file_write' },
required: { field: 'operation', value: 'file_write' },
},
{
id: 'content',
title: 'Content',
type: 'long-input' as SubBlockType,
placeholder: 'File content to write...',
condition: { field: 'operation', value: 'file_write' },
required: { field: 'operation', value: 'file_write' },
},
{
id: 'contentType',
title: 'Content Type',
type: 'short-input' as SubBlockType,
placeholder: 'text/plain (auto-detected from extension)',
condition: { field: 'operation', value: 'file_write' },
mode: 'advanced',
},
{
id: 'appendFileName',
title: 'File',
type: 'dropdown' as SubBlockType,
placeholder: 'Select a workspace file...',
condition: { field: 'operation', value: 'file_append' },
required: { field: 'operation', value: 'file_append' },
options: [],
fetchOptions: async () => {
const { useWorkflowRegistry } = await import('@/stores/workflows/registry/store')
const workspaceId = useWorkflowRegistry.getState().hydration.workspaceId
if (!workspaceId) return []
const response = await fetch(`/api/workspaces/${workspaceId}/files`)
const data = await response.json()
if (!data.success || !data.files) return []
return data.files.map((f: { name: string }) => ({ label: f.name, id: f.name }))
},
},
{
id: 'appendContent',
title: 'Content',
type: 'long-input' as SubBlockType,
placeholder: 'Content to append...',
condition: { field: 'operation', value: 'file_append' },
required: { field: 'operation', value: 'file_append' },
},
],
tools: {
access: ['file_parser_v3', 'file_write', 'file_append'],
config: {
tool: (params) => params.operation || 'file_parser_v3',
params: (params) => {
const operation = params.operation || 'file_parser_v3'
if (operation === 'file_write') {
return {
fileName: params.fileName,
content: params.content,
contentType: params.contentType,
workspaceId: params._context?.workspaceId,
}
}
if (operation === 'file_append') {
return {
fileName: params.appendFileName,
content: params.appendContent,
workspaceId: params._context?.workspaceId,
}
}
const fileInput = params.fileInput
if (!fileInput) {
logger.error('No file input provided')
throw new Error('File input is required')
}
const normalizedFiles = normalizeFileInput(fileInput)
if (normalizedFiles) {
const filePaths = resolveFilePathsFromInput(normalizedFiles)
if (filePaths.length > 0) {
return {
filePath: filePaths.length === 1 ? filePaths[0] : filePaths,
fileType: params.fileType || 'auto',
workspaceId: params._context?.workspaceId,
workflowId: params._context?.workflowId,
executionId: params._context?.executionId,
}
}
}
if (typeof fileInput === 'string' && fileInput.trim()) {
return {
filePath: fileInput.trim(),
fileType: params.fileType || 'auto',
workspaceId: params._context?.workspaceId,
workflowId: params._context?.workflowId,
executionId: params._context?.executionId,
}
}
logger.error('Invalid file input format')
throw new Error('File input is required')
},
},
},
inputs: {
operation: { type: 'string', description: 'Operation to perform (read, write, or append)' },
fileInput: { type: 'json', description: 'File input for read (canonical param)' },
fileType: { type: 'string', description: 'File type for read' },
fileName: { type: 'string', description: 'Name for a new file (write)' },
content: { type: 'string', description: 'File content to write' },
contentType: { type: 'string', description: 'MIME content type for write' },
appendFileName: { type: 'string', description: 'Name of existing file to append to' },
appendContent: { type: 'string', description: 'Content to append to file' },
},
outputs: {
files: {
type: 'file[]',
description: 'Parsed files as UserFile objects (read)',
},
combinedContent: {
type: 'string',
description: 'All file contents merged into a single text string (read)',
},
id: {
type: 'string',
description: 'File ID (write)',
},
name: {
type: 'string',
description: 'File name (write)',
},
size: {
type: 'number',
description: 'File size in bytes (write)',
},
url: {
type: 'string',
description: 'URL to access the file (write)',
},
},
}