-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathroute.ts
More file actions
2070 lines (1873 loc) · 63.6 KB
/
Copy pathroute.ts
File metadata and controls
2070 lines (1873 loc) · 63.6 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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createLogger } from '@sim/logger'
import { sha256Hex } from '@sim/security/hash'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { functionExecuteContract } from '@/lib/api/contracts'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import {
FORMAT_TO_CONTENT_TYPE,
getOutputFileDeclarations,
normalizeOutputWorkspaceFileName,
type OutputFileDeclaration,
resolveOutputFormat,
} from '@/lib/copilot/request/tools/files'
import {
validateWorkspaceFileWriteTarget,
writeWorkspaceFileByPath,
} from '@/lib/copilot/vfs/resource-writer'
import { isE2bEnabled } from '@/lib/core/config/env-flags'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { executeInE2B, executeShellInE2B, SIM_RESULT_PREFIX } from '@/lib/execution/e2b'
import { executeInIsolatedVM, type IsolatedVMBrokerHandler } from '@/lib/execution/isolated-vm'
import { CodeLanguage, DEFAULT_CODE_LANGUAGE, isValidCodeLanguage } from '@/lib/execution/languages'
import { recordMaterializedAccessKeys } from '@/lib/execution/payloads/access-keys'
import {
isLargeArrayManifest,
materializeLargeArrayManifest,
} from '@/lib/execution/payloads/large-array-manifest'
import { containsLargeValueRef, isLargeValueRef } from '@/lib/execution/payloads/large-value-ref'
import {
MAX_FUNCTION_INLINE_BYTES,
MAX_INLINE_MATERIALIZATION_BYTES,
readUserFileContent,
unavailableLargeValueError,
} from '@/lib/execution/payloads/materialization.server'
import { compactExecutionPayload } from '@/lib/execution/payloads/serializer'
import { materializeLargeValueRef } from '@/lib/execution/payloads/store'
import { isExecutionResourceLimitError } from '@/lib/execution/resource-errors'
import {
fetchWorkspaceFileBuffer,
resolveWorkspaceFileReference,
} from '@/lib/uploads/contexts/workspace/workspace-file-manager'
import { getWorkflowById } from '@/lib/workflows/utils'
import { escapeRegExp, normalizeName, REFERENCE } from '@/executor/constants'
import { type OutputSchema, resolveBlockReference } from '@/executor/utils/block-reference'
import { formatLiteralForCode } from '@/executor/utils/code-formatting'
import {
createEnvVarPattern,
createReferencePattern,
createWorkflowVariablePattern,
} from '@/executor/utils/reference-validation'
export const dynamic = 'force-dynamic'
export const runtime = 'nodejs'
const logger = createLogger('FunctionExecuteAPI')
const TAG_PATTERN = createReferencePattern()
const E2B_JS_WRAPPER_LINES = 3
const E2B_PYTHON_WRAPPER_LINES = 1
const MAX_SANDBOX_OUTPUT_FILES = 20
const MAX_SANDBOX_OUTPUT_BYTES = 50 * 1024 * 1024
/** Matches valid JS identifier names (letters, digits, underscore; no leading digit). */
const SAFE_IDENTIFIER = /^[a-zA-Z_][a-zA-Z0-9_]*$/
/** ES2023 reserved words — using these as `const` variable names produces a SyntaxError. */
const JS_RESERVED_WORDS = new Set([
'break',
'case',
'catch',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'else',
'export',
'extends',
'false',
'finally',
'for',
'function',
'if',
'import',
'in',
'instanceof',
'let',
'new',
'null',
'return',
'static',
'super',
'switch',
'this',
'throw',
'true',
'try',
'typeof',
'var',
'void',
'while',
'with',
'yield',
'enum',
'await',
'implements',
'interface',
'package',
'private',
'protected',
'public',
])
type TypeScriptModule = typeof import('@typescript/typescript6')
let typescriptModulePromise: Promise<TypeScriptModule> | null = null
async function loadTypeScriptModule(): Promise<TypeScriptModule> {
if (!typescriptModulePromise) {
typescriptModulePromise = import('@typescript/typescript6').then(
(mod) => (mod?.default ?? mod) as TypeScriptModule,
(error) => {
typescriptModulePromise = null
throw error
}
)
}
return typescriptModulePromise
}
async function extractJavaScriptImports(
code: string
): Promise<{ imports: string; remainingCode: string; importLineCount: number }> {
try {
const tsModule = await loadTypeScriptModule()
const sourceFile = tsModule.createSourceFile(
'user-code.js',
code,
tsModule.ScriptTarget.Latest,
true,
tsModule.ScriptKind.JS
)
const importSegments: Array<{ text: string; start: number; end: number }> = []
sourceFile.statements.forEach((statement) => {
if (
tsModule.isImportDeclaration(statement) ||
tsModule.isImportEqualsDeclaration(statement)
) {
importSegments.push({
text: statement.getFullText(sourceFile).trim(),
start: statement.getFullStart(),
end: statement.getEnd(),
})
}
})
if (importSegments.length === 0) {
return { imports: '', remainingCode: code, importLineCount: 0 }
}
importSegments.sort((a, b) => a.start - b.start)
const imports = importSegments.map((segment) => segment.text).join('\n')
let cursor = 0
const parts: string[] = []
let importLineCount = 0
for (const segment of importSegments) {
if (segment.start > cursor) {
parts.push(code.slice(cursor, segment.start))
}
const removedSegment = code.slice(segment.start, segment.end)
importLineCount += removedSegment.split('\n').length - 1
const newlinePlaceholder = removedSegment.replace(/[^\n]/g, '')
parts.push(newlinePlaceholder)
cursor = segment.end
}
if (cursor < code.length) {
parts.push(code.slice(cursor))
}
const remainingCode = parts.join('')
return { imports, remainingCode, importLineCount: Math.max(importLineCount, 0) }
} catch (error) {
logger.error('Failed to extract JavaScript imports', { error })
return { imports: '', remainingCode: code, importLineCount: 0 }
}
}
/**
* Enhanced error information interface
*/
interface EnhancedError {
message: string
line?: number
column?: number
stack?: string
name: string
originalError: any
lineContent?: string
}
/**
* Extract enhanced error information from VM execution errors
*/
function extractEnhancedError(
error: any,
userCodeStartLine: number,
userCode?: string
): EnhancedError {
const enhanced: EnhancedError = {
message: error.message || 'Unknown error',
name: error.name || 'Error',
originalError: error,
}
if (error.stack) {
enhanced.stack = error.stack
const stackLines: string[] = error.stack.split('\n')
for (const line of stackLines) {
let match = line.match(/user-function\.js:(\d+)(?::(\d+))?/)
if (!match) {
match = line.match(/at\s+user-function\.js:(\d+):(\d+)/)
}
if (match) {
const stackLine = Number.parseInt(match[1], 10)
const stackColumn = match[2] ? Number.parseInt(match[2], 10) : undefined
const adjustedLine = stackLine - userCodeStartLine + 1
const isWrapperSyntaxError =
stackLine > userCodeStartLine &&
error.name === 'SyntaxError' &&
(error.message.includes('Unexpected token') ||
error.message.includes('Unexpected end of input'))
if (isWrapperSyntaxError && userCode) {
const codeLines = userCode.split('\n')
const lastUserLine = codeLines.length
enhanced.line = lastUserLine
enhanced.column = codeLines[lastUserLine - 1]?.length || 0
enhanced.lineContent = codeLines[lastUserLine - 1]?.trim()
break
}
if (adjustedLine > 0) {
enhanced.line = adjustedLine
enhanced.column = stackColumn
if (userCode) {
const codeLines = userCode.split('\n')
if (adjustedLine <= codeLines.length) {
enhanced.lineContent = codeLines[adjustedLine - 1]?.trim()
}
}
break
}
if (stackLine <= userCodeStartLine) {
enhanced.line = stackLine
enhanced.column = stackColumn
break
}
}
}
const cleanedStackLines: string[] = stackLines
.filter(
(line: string) =>
line.includes('user-function.js') ||
(!line.includes('vm.js') && !line.includes('internal/'))
)
.map((line: string) => line.replace(/\s+at\s+/, ' at '))
if (cleanedStackLines.length > 0) {
enhanced.stack = cleanedStackLines.join('\n')
}
}
return enhanced
}
/**
* Parse and format E2B error message
* Removes E2B-specific line references and adds correct user line numbers
*/
function formatE2BError(
errorMessage: string,
errorOutput: string,
language: CodeLanguage,
userCode: string,
prologueLineCount: number
): { formattedError: string; cleanedOutput: string } {
const wrapperLines =
language === CodeLanguage.Python ? E2B_PYTHON_WRAPPER_LINES : E2B_JS_WRAPPER_LINES
const totalOffset = prologueLineCount + wrapperLines
let userLine: number | undefined
let cleanErrorType = ''
let cleanErrorMsg = ''
if (language === CodeLanguage.Python) {
const cellMatch = errorOutput.match(/Cell In\[\d+\], line (\d+)/)
if (cellMatch) {
const originalLine = Number.parseInt(cellMatch[1], 10)
userLine = originalLine - totalOffset
}
cleanErrorMsg = errorMessage
.replace(/\s*\(detected at line \d+\)/g, '')
.replace(/\s*\([^)]+\.py, line \d+\)/g, '')
.trim()
} else if (language === CodeLanguage.JavaScript) {
const firstLineEnd = errorMessage.indexOf('\n')
const firstLine = firstLineEnd > 0 ? errorMessage.substring(0, firstLineEnd) : errorMessage
const jsErrorMatch = firstLine.match(/^(\w+Error):\s*[^:]+:\s*([^(]+)\.\s*\((\d+):(\d+)\)/)
if (jsErrorMatch) {
cleanErrorType = jsErrorMatch[1]
cleanErrorMsg = jsErrorMatch[2].trim()
const originalLine = Number.parseInt(jsErrorMatch[3], 10)
userLine = originalLine - totalOffset
} else {
const arrowMatch = errorMessage.match(/^>\s*(\d+)\s*\|/m)
if (arrowMatch) {
const originalLine = Number.parseInt(arrowMatch[1], 10)
userLine = originalLine - totalOffset
}
const errorMatch = firstLine.match(/^(\w+Error):\s*(.+)/)
if (errorMatch) {
cleanErrorType = errorMatch[1]
cleanErrorMsg = errorMatch[2]
.replace(/^[^:]+:\s*/, '') // Remove file path
.replace(/\s*\(\d+:\d+\)\s*$/, '') // Remove line:col at end
.trim()
} else {
cleanErrorMsg = firstLine
}
}
}
const finalErrorMsg =
cleanErrorType && cleanErrorMsg
? `${cleanErrorType}: ${cleanErrorMsg}`
: cleanErrorMsg || errorMessage
let formattedError = finalErrorMsg
if (userLine && userLine > 0) {
const codeLines = userCode.split('\n')
// Clamp userLine to the actual user code range
const actualUserLine = Math.min(userLine, codeLines.length)
if (actualUserLine > 0 && actualUserLine <= codeLines.length) {
const lineContent = codeLines[actualUserLine - 1]?.trim()
if (lineContent) {
formattedError = `Line ${actualUserLine}: \`${lineContent}\` - ${finalErrorMsg}`
} else {
formattedError = `Line ${actualUserLine} - ${finalErrorMsg}`
}
}
}
const cleanedOutput = finalErrorMsg
return { formattedError, cleanedOutput }
}
/**
* Create a detailed error message for users
*/
function createUserFriendlyErrorMessage(
enhanced: EnhancedError,
requestId: string,
userCode?: string
): string {
let errorMessage = enhanced.message
if (enhanced.line !== undefined) {
let lineInfo = `Line ${enhanced.line}`
// Add the actual line content if available
if (enhanced.lineContent) {
lineInfo += `: \`${enhanced.lineContent}\``
}
errorMessage = `${lineInfo} - ${errorMessage}`
} else {
if (enhanced.stack) {
const stackMatch = enhanced.stack.match(/user-function\.js:(\d+)(?::(\d+))?/)
if (stackMatch) {
const line = Number.parseInt(stackMatch[1], 10)
let lineInfo = `Line ${line}`
if (userCode) {
const codeLines = userCode.split('\n')
if (line <= codeLines.length) {
const lineContent = codeLines[line - 1]?.trim()
if (lineContent) {
lineInfo += `: \`${lineContent}\``
}
}
}
errorMessage = `${lineInfo} - ${errorMessage}`
}
}
}
if (enhanced.name !== 'Error') {
const errorTypePrefix =
enhanced.name === 'SyntaxError'
? 'Syntax Error'
: enhanced.name === 'TypeError'
? 'Type Error'
: enhanced.name === 'ReferenceError'
? 'Reference Error'
: enhanced.name
if (!errorMessage.toLowerCase().includes(errorTypePrefix.toLowerCase())) {
errorMessage = `${errorTypePrefix}: ${errorMessage}`
}
}
return errorMessage
}
function getErrorDisplayCode(sourceCode: string | undefined, resolvedCode: string): string {
return sourceCode && sourceCode.length > 0 ? sourceCode : resolvedCode
}
function getLineContent(code: string, line: number | undefined): string | undefined {
if (line === undefined || line < 1) {
return undefined
}
return code.split('\n')[line - 1]?.trim()
}
function getErrorDisplayMessage(
message: string,
sourceCode: string | undefined,
resolvedCode: string
): string {
if (!sourceCode || sourceCode === resolvedCode || !resolvedCode.includes('__blockRef_')) {
return message
}
return message.replace(/\s+["']globalThis["']/g, '')
}
function resolveWorkflowVariables(
code: string,
workflowVariables: Record<string, any>,
contextVariables: Record<string, any>
): string {
let resolvedCode = code
const regex = createWorkflowVariablePattern()
let match: RegExpExecArray | null
const replacements: Array<{
match: string
index: number
variableName: string
variableValue: unknown
}> = []
while ((match = regex.exec(code)) !== null) {
const variableName = match[1].trim()
const foundVariable = Object.entries(workflowVariables).find(
([_, variable]) => normalizeName(variable.name || '') === variableName
)
if (!foundVariable) {
const availableVars = Object.values(workflowVariables)
.map((v) => v.name)
.filter(Boolean)
throw new Error(
`Variable "${variableName}" doesn't exist.` +
(availableVars.length > 0 ? ` Available: ${availableVars.join(', ')}` : '')
)
}
const variable = foundVariable[1]
let variableValue: unknown = variable.value
if (variable.value !== undefined && variable.value !== null) {
const type = variable.type === 'string' ? 'plain' : variable.type
if (type === 'number') {
variableValue = Number(variableValue)
} else if (type === 'boolean') {
if (typeof variableValue === 'boolean') {
// Already a boolean, keep as-is
} else {
const normalized = String(variableValue).toLowerCase().trim()
variableValue = normalized === 'true'
}
} else if (type === 'json' && typeof variableValue === 'string') {
try {
variableValue = JSON.parse(variableValue)
} catch {
// Keep as-is
}
}
}
replacements.push({
match: match[0],
index: match.index,
variableName,
variableValue,
})
}
for (let i = replacements.length - 1; i >= 0; i--) {
const { match: matchStr, index, variableName, variableValue } = replacements[i]
const safeVarName = `__variable_${variableName.replace(/[^a-zA-Z0-9_]/g, '_')}`
contextVariables[safeVarName] = variableValue
resolvedCode =
resolvedCode.slice(0, index) + safeVarName + resolvedCode.slice(index + matchStr.length)
}
return resolvedCode
}
function resolveEnvironmentVariables(
code: string,
params: Record<string, any>,
envVars: Record<string, string>,
contextVariables: Record<string, any>
): string {
let resolvedCode = code
const regex = createEnvVarPattern()
let match: RegExpExecArray | null
const replacements: Array<{ match: string; index: number; varName: string; varValue: string }> =
[]
const resolverVars: Record<string, string> = {}
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
resolverVars[key] = String(value)
}
})
Object.entries(envVars).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
resolverVars[key] = value
}
})
while ((match = regex.exec(code)) !== null) {
const varName = match[1].trim()
if (!(varName in resolverVars)) {
continue
}
replacements.push({
match: match[0],
index: match.index,
varName,
varValue: resolverVars[varName],
})
}
for (let i = replacements.length - 1; i >= 0; i--) {
const { match: matchStr, index, varName, varValue } = replacements[i]
const safeVarName = `__var_${varName.replace(/[^a-zA-Z0-9_]/g, '_')}`
contextVariables[safeVarName] = varValue
resolvedCode =
resolvedCode.slice(0, index) + safeVarName + resolvedCode.slice(index + matchStr.length)
}
return resolvedCode
}
function resolveTagVariables(
code: string,
blockData: Record<string, unknown>,
blockNameMapping: Record<string, string>,
blockOutputSchemas: Record<string, OutputSchema>,
contextVariables: Record<string, unknown>,
language = 'javascript'
): string {
let resolvedCode = code
const undefinedLiteral = language === 'python' ? 'None' : 'undefined'
const tagMatches = resolvedCode.match(TAG_PATTERN) || []
for (const match of tagMatches) {
const tagName = match.slice(REFERENCE.START.length, -REFERENCE.END.length).trim()
const pathParts = tagName.split(REFERENCE.PATH_DELIMITER)
const blockName = pathParts[0]
const fieldPath = pathParts.slice(1)
const result = resolveBlockReference(blockName, fieldPath, {
blockNameMapping,
blockData,
blockOutputSchemas,
})
if (!result) {
continue
}
let tagValue = result.value
if (tagValue === undefined) {
resolvedCode = resolvedCode.replace(new RegExp(escapeRegExp(match), 'g'), undefinedLiteral)
continue
}
if (typeof tagValue === 'string') {
const trimmed = tagValue.trimStart()
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
try {
tagValue = JSON.parse(tagValue)
} catch {
// Keep as string if not valid JSON
}
}
}
const safeVarName = `__tag_${tagName.replace(/_/g, '_1').replace(/\./g, '_0')}`
contextVariables[safeVarName] = tagValue
resolvedCode = resolvedCode.replace(new RegExp(escapeRegExp(match), 'g'), safeVarName)
}
return resolvedCode
}
/**
* Resolves environment variables and tags in code
* @param code - Code with variables
* @param params - Parameters that may contain variable values
* @param envVars - Environment variables from the workflow
* @returns Resolved code
*/
function resolveCodeVariables(
code: string,
params: Record<string, unknown>,
envVars: Record<string, string> = {},
blockData: Record<string, unknown> = {},
blockNameMapping: Record<string, string> = {},
blockOutputSchemas: Record<string, OutputSchema> = {},
workflowVariables: Record<string, unknown> = {},
language = 'javascript'
): { resolvedCode: string; contextVariables: Record<string, unknown> } {
let resolvedCode = code
const contextVariables: Record<string, unknown> = {}
resolvedCode = resolveWorkflowVariables(resolvedCode, workflowVariables, contextVariables)
resolvedCode = resolveEnvironmentVariables(resolvedCode, params, envVars, contextVariables)
resolvedCode = resolveTagVariables(
resolvedCode,
blockData,
blockNameMapping,
blockOutputSchemas,
contextVariables,
language
)
return { resolvedCode, contextVariables }
}
/**
* Remove one trailing newline from stdout
* This handles the common case where print() or console.log() adds a trailing \n
* that users don't expect to see in the output
*/
/**
* Heuristic: did the sandbox die from an infrastructure failure (OOM kill,
* timeout, lost connection) rather than a normal code error? Python/JS code
* exceptions surface via execution.error; an OOM kill instead makes runCode
* throw, often with an empty or cryptic message.
*/
function isLikelySandboxKill(error: any): boolean {
const msg = `${error?.name ?? ''} ${error?.message ?? ''} ${error?.code ?? ''}`
.toLowerCase()
.trim()
if (!msg) return true
return [
'out of memory',
'oom',
'killed',
'sigkill',
'code 137',
'signal 9',
'terminated',
'econnreset',
'epipe',
'socket hang up',
'connection closed',
'connection reset',
'websocket',
'timed out',
'timeout',
'deadline',
].some((s) => msg.includes(s))
}
function cleanStdout(stdout: string): string {
if (stdout.endsWith('\n')) {
return stdout.slice(0, -1)
}
return stdout
}
/**
* Serializes a value for use as a shell environment variable. Strings pass through
* unchanged; primitives are coerced via `String`; objects, arrays, and other complex
* values are JSON-stringified so that referencing them via `$VAR` yields a useful
* representation instead of `[object Object]`. `null`/`undefined` become an empty
* string to match POSIX env semantics.
*/
function serializeForShellEnv(value: unknown, nullValue = ''): string {
if (value === null || value === undefined) return nullValue
if (typeof value === 'string') return value
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
return String(value)
}
try {
return JSON.stringify(value) ?? ''
} catch {
return String(value)
}
}
interface FunctionRouteExecutionContext {
workflowId?: string
workspaceId?: string
executionId?: string
largeValueExecutionIds?: string[]
largeValueKeys?: string[]
fileKeys?: string[]
allowLargeValueWorkflowScope?: boolean
userId?: string
requestId: string
}
function asRecord(value: unknown): Record<string, unknown> {
return value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: {}
}
function getPositiveNumber(value: unknown): number | undefined {
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
return undefined
}
return value
}
function clampInlineBytes(value: unknown, limit = MAX_FUNCTION_INLINE_BYTES): number {
const requested = getPositiveNumber(value)
return Math.min(requested ?? limit, limit)
}
function getBrokerFileArgs(args: unknown): {
file: unknown
maxBytes: number
offset?: number
length?: number
} {
const record = asRecord(args)
const options = asRecord(record.options)
return {
file: record.file,
maxBytes: clampInlineBytes(options.maxBytes),
offset: getPositiveNumber(options.offset),
length: getPositiveNumber(options.length),
}
}
function createFunctionRuntimeBrokers(
context: FunctionRouteExecutionContext
): Record<string, IsolatedVMBrokerHandler> {
context.largeValueKeys ??= []
context.fileKeys ??= []
const largeValueKeys = context.largeValueKeys
const fileKeys = context.fileKeys
const base = {
requestId: context.requestId,
workflowId: context.workflowId,
workspaceId: context.workspaceId,
executionId: context.executionId,
largeValueExecutionIds: context.largeValueExecutionIds,
largeValueKeys,
fileKeys,
allowLargeValueWorkflowScope: context.allowLargeValueWorkflowScope,
userId: context.userId,
logger,
}
const recordMaterializedKeys = (value: unknown) =>
recordMaterializedAccessKeys({ largeValueKeys, fileKeys }, value)
const readFile = async (args: unknown, encoding: 'base64' | 'text', chunked = false) => {
const fileArgs = getBrokerFileArgs(args)
return readUserFileContent(fileArgs.file, {
...base,
encoding,
maxBytes: fileArgs.maxBytes,
chunked,
offset: chunked ? fileArgs.offset : undefined,
length: chunked ? fileArgs.length : undefined,
})
}
return {
'sim.files.readBase64': (args) => readFile(args, 'base64'),
'sim.files.readText': (args) => readFile(args, 'text'),
'sim.files.readBase64Chunk': (args) => readFile(args, 'base64', true),
'sim.files.readTextChunk': (args) => readFile(args, 'text', true),
'sim.values.read': async (args) => {
const record = asRecord(args)
const options = asRecord(record.options)
const ref = record.ref
if (!isLargeValueRef(ref)) {
throw new Error('Expected a large execution value reference.')
}
if (!context.executionId) {
throw new Error('Large execution values require an execution context.')
}
const value = await materializeLargeValueRef(ref, {
...base,
maxBytes: clampInlineBytes(options.maxBytes, MAX_INLINE_MATERIALIZATION_BYTES),
})
if (value === undefined) {
throw unavailableLargeValueError(ref)
}
recordMaterializedKeys(value)
return value
},
'sim.values.readArray': async (args) => {
const record = asRecord(args)
const options = asRecord(record.options)
const manifest = record.ref
if (!isLargeArrayManifest(manifest)) {
throw new Error('Expected a large array manifest.')
}
if (!context.executionId) {
throw new Error('Large array manifests require an execution context.')
}
const value = await materializeLargeArrayManifest(manifest, {
...base,
maxBytes: clampInlineBytes(options.maxBytes, MAX_INLINE_MATERIALIZATION_BYTES),
})
recordMaterializedKeys(value)
return value
},
}
}
async function compactFunctionRouteBody<T>(
body: T,
context: FunctionRouteExecutionContext
): Promise<T> {
return compactExecutionPayload(body, {
workflowId: context.workflowId,
workspaceId: context.workspaceId,
executionId: context.executionId,
userId: context.userId,
preserveRoot: true,
requireDurable: Boolean(context.workspaceId && context.workflowId && context.executionId),
})
}
async function functionJsonResponse<T>(
body: T,
context: FunctionRouteExecutionContext,
init?: ResponseInit
) {
return NextResponse.json(
await compactFunctionRouteBody(
{
...body,
largeValueKeys: context.largeValueKeys,
fileKeys: context.fileKeys,
},
context
),
init
)
}
/**
* Compares an about-to-be-exported buffer against the overwrite target's
* current content. `identical: true` means the export is a byte-for-byte no-op:
* either a legitimately idempotent regeneration, or the incident signature of
* code that never wrote to the declared sandboxPath (the file still holds the
* mounted input). Only the model can tell those apart, so callers surface the
* fact loudly in the receipt instead of failing the write. Comparison failures
* never block the write; the current content is only downloaded when the sizes
* already match.
*/
async function checkOverwriteTarget(
workspaceId: string,
targetPath: string,
buffer: Buffer
): Promise<{ previousSize?: number; identical: boolean }> {
try {
const existing = await resolveWorkspaceFileReference(workspaceId, targetPath)
if (!existing) return { identical: false }
if (existing.size !== buffer.length) {
return { previousSize: existing.size, identical: false }
}
const current = await fetchWorkspaceFileBuffer(existing)
return { previousSize: existing.size, identical: current.equals(buffer) }
} catch {
return { identical: false }
}
}
function formatExportReceipt(bytes: number, previousSize: number | undefined, sha256: string) {
return `(${bytes} bytes${
previousSize !== undefined ? `, replaced ${previousSize} bytes` : ''
}, sha256:${sha256.slice(0, 16)})`
}
function exportUnchangedNote(sandboxPath?: string): string {
return (
'WARNING: content is byte-identical to the previous version — nothing changed.' +
(sandboxPath
? ` If you expected new content, your code did not modify the sandbox file at "${sandboxPath}" (it still holds the mounted input); write the new content to exactly that path and export again.`
: ' If you expected new content, the code returned the same bytes as before.')
)
}
async function maybeExportSandboxFileToWorkspace(args: {
authUserId: string
workflowId?: string
workspaceId?: string
outputPath?: string
outputFormat?: string
outputMimeType?: string
outputSandboxPath?: string
overwriteFileId?: string
outputMode?: 'create' | 'overwrite'
exportedFileContent?: string
stdout: string
executionTime: number
}) {
const {
authUserId,
workflowId,
workspaceId,
outputPath,
outputFormat,
outputMimeType,
outputSandboxPath,
overwriteFileId,
outputMode,
exportedFileContent,
stdout,
executionTime,
} = args
if (!outputSandboxPath) return null
if (!outputPath) {
return NextResponse.json(
{
success: false,
error:
'outputSandboxPath requires outputPath. Set outputPath to the destination workspace file, e.g. "files/result.csv".',
output: { result: null, stdout: cleanStdout(stdout), executionTime },
},
{ status: 400 }
)
}
const resolvedWorkspaceId =
workspaceId || (workflowId ? (await getWorkflowById(workflowId))?.workspaceId : undefined)
if (!resolvedWorkspaceId) {
return NextResponse.json(
{
success: false,
error: 'Workspace context required to save sandbox file to workspace',