-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathworkspace-vfs.ts
More file actions
2199 lines (2072 loc) · 78.6 KB
/
Copy pathworkspace-vfs.ts
File metadata and controls
2199 lines (2072 loc) · 78.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 { trace } from '@opentelemetry/api'
import { db } from '@sim/db'
import {
a2aAgent,
chat as chatTable,
copilotChats,
document,
jobExecutionLogs,
knowledgeConnector,
mcpServers as mcpServersTable,
workflowDeploymentVersion,
workflowExecutionLogs,
workflowFolder,
workflowMcpServer,
workflowMcpTool,
workflowSchedule,
} from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { and, desc, eq, isNotNull, isNull, ne, sql } from 'drizzle-orm'
import { listApiKeys } from '@/lib/api-key/service'
import {
buildWorkspaceContextMd,
buildWorkspaceMd,
type WorkspaceMdData,
} from '@/lib/copilot/chat/workspace-context'
import { TraceAttr } from '@/lib/copilot/generated/trace-attributes-v1'
import { TraceSpan } from '@/lib/copilot/generated/trace-spans-v1'
import { getExposedIntegrationTools } from '@/lib/copilot/integration-tools'
import { recordVfsMaterialize } from '@/lib/copilot/request/metrics'
import { markSpanForError } from '@/lib/copilot/request/otel'
import { compileDoc, getE2BDocFormat } from '@/lib/copilot/tools/server/files/doc-compile'
import { extractDocText, isExtractableDocExt } from '@/lib/copilot/tools/server/files/doc-extract'
import { runE2BCompiledCheck } from '@/lib/copilot/tools/server/files/doc-recalc'
import { isRenderableDocExt, renderDocToGrid } from '@/lib/copilot/tools/server/files/doc-render'
import {
collectWorkflowFieldIssues,
lintEditedWorkflowState,
} from '@/lib/copilot/tools/server/workflow/edit-workflow/lint'
import { UNRESOLVABLE_AT_LINT_NOTE } from '@/lib/copilot/tools/server/workflow/edit-workflow/validation'
import { extractDocumentStyle } from '@/lib/copilot/vfs/document-style'
import { type FileReadResult, readFileRecord } from '@/lib/copilot/vfs/file-reader'
import { normalizeVfsSegment } from '@/lib/copilot/vfs/normalize-segment'
import type { GrepMatch, GrepOptions, ReadResult } from '@/lib/copilot/vfs/operations'
import * as ops from '@/lib/copilot/vfs/operations'
import {
buildVfsFolderPathMap,
canonicalWorkflowVfsDir,
canonicalWorkspaceFilePath,
encodeVfsPathSegments,
} from '@/lib/copilot/vfs/path-utils'
import type { DeploymentData } from '@/lib/copilot/vfs/serializers'
import {
serializeApiKeys,
serializeBlockSchema,
serializeBuiltinTriggerSchema,
serializeConnectorOverview,
serializeConnectorSchema,
serializeConnectors,
serializeCredentials,
serializeCustomTool,
serializeDeployments,
serializeDocuments,
serializeEnvironmentVariables,
serializeFileMeta,
serializeIntegrationSchema,
serializeJobMeta,
serializeKBMeta,
serializeMcpServer,
serializeRecentExecutions,
serializeSkill,
serializeTableMeta,
serializeTaskChat,
serializeTaskSession,
serializeTriggerOverview,
serializeTriggerSchema,
serializeVersions,
serializeWorkflowMeta,
} from '@/lib/copilot/vfs/serializers'
import {
buildWorkflowAliasLinks,
isWorkflowAliasBackingPath,
WORKFLOW_ALIAS_LINKS_NAME,
WORKFLOW_CHANGELOG_ALIAS_NAME,
WORKFLOW_PLANS_ALIAS_DIR,
WORKFLOW_PLANS_BACKING_FOLDER,
WORKSPACE_PLANS_BACKING_FOLDER,
workflowChangelogBackingPath,
workspacePlanBackingPath,
workspacePlansBackingFolderPath,
} from '@/lib/copilot/vfs/workflow-aliases'
import { isE2BDocEnabled } from '@/lib/core/config/env-flags'
import { isFeatureEnabled } from '@/lib/core/config/feature-flags'
import {
getAccessibleEnvCredentials,
getAccessibleOAuthCredentials,
} from '@/lib/credentials/environment'
import { getPersonalAndWorkspaceEnv } from '@/lib/environment/utils'
import { BINARY_DOC_TASKS, MAX_DOCUMENT_PREVIEW_CODE_BYTES } from '@/lib/execution/constants'
import { runSandboxTask, SandboxUserCodeError } from '@/lib/execution/sandbox/run-task'
import { getKnowledgeBases } from '@/lib/knowledge/service'
import { validateMermaidSource } from '@/lib/mermaid/validate'
import { listTables } from '@/lib/table/service'
import { listWorkspaceFileFolders } from '@/lib/uploads/contexts/workspace/workspace-file-folder-manager'
import {
fetchWorkspaceFileBuffer,
findWorkspaceFileRecord,
listWorkspaceFiles,
type WorkspaceFileRecord,
} from '@/lib/uploads/contexts/workspace/workspace-file-manager'
import { listCustomTools } from '@/lib/workflows/custom-tools/operations'
import {
loadWorkflowDeploymentSnapshot,
loadWorkflowFromNormalizedTables,
} from '@/lib/workflows/persistence/utils'
import { sanitizeForCopilot } from '@/lib/workflows/sanitization/json-sanitizer'
import { listSkills } from '@/lib/workflows/skills/operations'
import { listFolders, listWorkflows } from '@/lib/workflows/utils'
import {
assertActiveWorkspaceAccess,
getUsersWithPermissions,
getWorkspaceWithOwner,
} from '@/lib/workspaces/permissions/utils'
import { computeNeedsRedeployment } from '@/app/api/workflows/utils'
import { getAllBlocks } from '@/blocks/registry'
import { CONNECTOR_REGISTRY } from '@/connectors/registry'
import type { WorkflowState } from '@/stores/workflows/workflow/types'
import { TRIGGER_REGISTRY } from '@/triggers/registry'
const logger = createLogger('WorkspaceVFS')
const MAX_COMPILED_ATTACHMENT_BYTES = 5 * 1024 * 1024
/** Static component files, computed once and shared across all VFS instances */
let staticComponentFiles: Map<string, string> | null = null
// On-the-fly doc reads (render/extract) download the binary into the Sim process
// and base64-stage it to E2B, so bound the input like the compile path's staging
// caps — otherwise an authenticated member could OOM the worker with a multi-GB
// upload (uploads are capped at 5GB).
const MAX_DOC_READ_INPUT_BYTES = 50 * 1024 * 1024
/**
* True when the buffer is an actual compiled/uploaded binary (vs a source-backed
* generated doc). OOXML (pptx/docx/xlsx) is a ZIP (starts `PK`); PDFs may carry a
* BOM or leading whitespace before `%PDF`, so scan the head rather than offset 0.
*/
function isBinaryDocBuffer(buffer: Buffer, ext: string): boolean {
if (ext === 'pdf') return buffer.subarray(0, 1024).toString('latin1').includes('%PDF')
return buffer.subarray(0, 2).toString('latin1') === 'PK'
}
/**
* Build the static component files from block and tool registries.
* This only needs to happen once per process.
*
* Integration paths are derived deterministically from the block registry's
* `tools.access` arrays rather than splitting tool IDs on underscores.
* Each block declares which tools it owns, and the block type (minus version
* suffix) becomes the service directory name.
*/
function getStaticComponentFiles(): Map<string, string> {
if (staticComponentFiles) return staticComponentFiles
const files = new Map<string, string>()
const allBlocks = getAllBlocks()
const visibleBlocks = allBlocks.filter((b) => !b.hideFromToolbar)
let blocksFiltered = 0
for (const block of visibleBlocks) {
const path = `components/blocks/${block.type}.json`
files.set(path, serializeBlockSchema(block))
}
blocksFiltered = allBlocks.length - visibleBlocks.length
let integrationCount = 0
const oauthServices = new Map<string, { provider: string; operations: string[] }>()
const apiKeyServices = new Map<string, { params: string[]; operations: string[] }>()
// Integration tools come from the shared exposed-tool set (latest version of
// each operation owned by a visible block), the same set used to build the
// deferred callable tools — so discovery and execution can never drift.
for (const { config: tool, service, operation } of getExposedIntegrationTools()) {
const path = `components/integrations/${service}/${operation}.json`
files.set(path, serializeIntegrationSchema(tool))
integrationCount++
if (tool.oauth?.required) {
const existing = oauthServices.get(service)
if (existing) {
existing.operations.push(operation)
} else {
oauthServices.set(service, { provider: tool.oauth.provider, operations: [operation] })
}
} else if (tool.hosting?.apiKeyParam) {
const existing = apiKeyServices.get(service)
if (existing) {
if (!existing.params.includes(tool.hosting.apiKeyParam)) {
existing.params.push(tool.hosting.apiKeyParam)
}
existing.operations.push(operation)
} else {
apiKeyServices.set(service, {
params: [tool.hosting.apiKeyParam],
operations: [operation],
})
}
}
}
files.set(
'environment/oauth-integrations.json',
JSON.stringify(Object.fromEntries(oauthServices), null, 2)
)
files.set(
'environment/api-key-integrations.json',
JSON.stringify(Object.fromEntries(apiKeyServices), null, 2)
)
files.set(
'components/blocks/loop.json',
JSON.stringify(
{
type: 'loop',
name: 'Loop',
description:
'Iterate over a collection or repeat a fixed number of times. Blocks inside the loop run once per iteration.',
inputs: {
loopType: {
type: 'string',
enum: ['for', 'forEach', 'while', 'doWhile'],
description: 'Loop strategy',
},
iterations: { type: 'number', description: 'Number of iterations (for loopType "for")' },
collection: {
type: 'string',
description: 'Collection expression to iterate (for loopType "forEach")',
},
condition: {
type: 'string',
description: 'Condition expression (for loopType "while" or "doWhile")',
},
},
sourceHandles: ['loop-start-source', 'loop-end-source'],
notes:
'Use "loop-start-source" to connect to blocks INSIDE the loop. Use "loop-end-source" for the edge that runs AFTER the loop completes. Do NOT use "source" for a loop block — it is rejected; the only valid source handles are "loop-start-source", "loop-end-source", and "error". Blocks inside the loop must have parentId set to the loop block ID.',
},
null,
2
)
)
files.set(
'components/blocks/parallel.json',
JSON.stringify(
{
type: 'parallel',
name: 'Parallel',
description: 'Run blocks in parallel branches. All branches execute concurrently.',
inputs: {
parallelType: {
type: 'string',
enum: ['count', 'collection'],
description: 'Parallel strategy',
},
count: {
type: 'number',
description: 'Number of parallel branches (for parallelType "count")',
},
collection: {
type: 'string',
description: 'Collection to distribute (for parallelType "collection")',
},
},
sourceHandles: ['parallel-start-source', 'parallel-end-source'],
notes:
'Use "parallel-start-source" to connect to blocks INSIDE the parallel container. Use "parallel-end-source" for the edge AFTER all branches complete. Do NOT use "source" for a parallel block — it is rejected; the only valid source handles are "parallel-start-source", "parallel-end-source", and "error". Blocks inside must have parentId set to the parallel block ID.',
},
null,
2
)
)
const connectorConfigs = Object.values(CONNECTOR_REGISTRY).map((c) => ({
id: c.id,
name: c.name,
description: c.description,
version: c.version,
auth: c.auth,
configFields: c.configFields,
tagDefinitions: c.tagDefinitions,
supportsIncrementalSync: c.supportsIncrementalSync,
}))
files.set('knowledgebases/connectors/connectors.md', serializeConnectorOverview(connectorConfigs))
for (const cc of connectorConfigs) {
files.set(`knowledgebases/connectors/${cc.id}.json`, serializeConnectorSchema(cc))
}
const builtinTriggerBlocks = allBlocks.filter((b) => b.category === 'triggers')
for (const block of builtinTriggerBlocks) {
files.set(`components/triggers/sim/${block.type}.json`, serializeBuiltinTriggerSchema(block))
}
let externalTriggerCount = 0
for (const [triggerId, trigger] of Object.entries(TRIGGER_REGISTRY)) {
const path = `components/triggers/${trigger.provider}/${triggerId}.json`
files.set(path, serializeTriggerSchema(trigger))
externalTriggerCount++
}
files.set(
'components/triggers/triggers.md',
serializeTriggerOverview(
builtinTriggerBlocks.map((b) => ({
id: b.type,
name: b.name,
provider: 'sim',
description: b.description,
})),
Object.entries(TRIGGER_REGISTRY).map(([id, t]) => ({
id,
name: t.name,
provider: t.provider,
description: t.description,
}))
)
)
logger.info('Static component files built', {
blocks: visibleBlocks.length,
blocksFiltered,
integrations: integrationCount,
connectors: connectorConfigs.length,
builtinTriggers: builtinTriggerBlocks.length,
externalTriggers: externalTriggerCount,
})
staticComponentFiles = files
return staticComponentFiles
}
/**
* Virtual Filesystem that materializes workspace data into an in-memory Map.
*
* Structure:
* WORKSPACE_CONTEXT.md — full dynamic workspace/user context (auto-generated)
* WORKSPACE.md — workspace inventory summary (auto-generated)
* workflows/{name}/meta.json (root-level workflows)
* workflows/{name}/state.json (sanitized blocks with embedded connections)
* workflows/{name}/lint.json (sources/sinks, required-field, credential/resource issues)
* workflows/{name}/executions.json
* workflows/{name}/deployment.json
* workflows/{folder}/{name}/... (workflows inside folders, nested folders supported)
* knowledgebases/{name}/meta.json
* knowledgebases/{name}/documents.json
* knowledgebases/{name}/connectors.json
* tables/{name}/meta.json
* files/{name} (workspace file leaf; dynamic content on read)
* files/{path}/{name}/style (dynamic — style extraction for .docx/.pptx/.pdf)
* files/{path}/{name}/compiled-check (dynamic — compile generated source / validate diagrams, returns {ok,error?})
* jobs/{title}/meta.json
* jobs/{title}/history.json
* jobs/{title}/executions.json
* tasks/{title}/session.md
* tasks/{title}/chat.json
* custom-tools/{name}.json
* environment/credentials.json
* environment/api-keys.json
* environment/variables.json
* knowledgebases/connectors/connectors.md (available connector types overview)
* knowledgebases/connectors/{type}.json (per-connector config schema)
* components/blocks/{type}.json
* components/integrations/{service}/{operation}.json
* components/triggers/triggers.md (overview of all built-in and external triggers)
* components/triggers/sim/{type}.json (built-in trigger blocks: start, schedule, webhook)
* components/triggers/{provider}/{id}.json (external triggers: github, slack, etc.)
*/
export class WorkspaceVFS {
private files: Map<string, string> = new Map()
private _workspaceId = ''
private _betaEnabled = false
get workspaceId(): string {
return this._workspaceId
}
/**
* Materialize workspace data into the VFS.
* Uses shared service functions for all data access, then generates
* WORKSPACE.md from the summaries returned by each materializer.
*/
async materialize(workspaceId: string, userId: string): Promise<void> {
const start = Date.now()
this.files = new Map()
this._workspaceId = workspaceId
this._betaEnabled = await isFeatureEnabled('mothership-beta', { userId })
// Per-phase wall-clock, stamped on the span so a slow materialize in a
// trace names its bottleneck instead of showing up as unattributed dead
// time inside read/glob/grep (how the v0.7 lint.json regression hid).
const phaseMs: Record<string, number> = {}
const timed = <T>(phase: string, promise: Promise<T>): Promise<T> => {
const t0 = Date.now()
return promise.finally(() => {
phaseMs[phase] = Date.now() - t0
})
}
await trace
.getTracer('sim-copilot-vfs', '1.0.0')
.startActiveSpan(
TraceSpan.CopilotVfsMaterialize,
{ attributes: { [TraceAttr.WorkspaceId]: workspaceId } },
async (span) => {
try {
const [
wfSummary,
kbSummary,
tblSummary,
fileSummary,
envSummary,
toolsSummary,
mcpServersSummary,
skillsSummary,
taskSummary,
jobsSummary,
wsRow,
members,
] = await Promise.all([
timed('workflows', this.materializeWorkflows(workspaceId)),
timed('knowledge_bases', this.materializeKnowledgeBases(workspaceId, userId)),
timed('tables', this.materializeTables(workspaceId)),
timed('files', this.materializeFiles(workspaceId)),
timed('environment', this.materializeEnvironment(workspaceId, userId)),
timed('custom_tools', this.materializeCustomTools(workspaceId, userId)),
timed('mcp_servers', this.materializeMcpServers(workspaceId)),
timed('skills', this.materializeSkills(workspaceId)),
timed('tasks', this.materializeTasks(workspaceId, userId)),
timed('jobs', this.materializeJobs(workspaceId)),
timed('workspace_row', getWorkspaceWithOwner(workspaceId)),
timed('members', getUsersWithPermissions(workspaceId)),
])
const workspaceMdData = {
workspace: wsRow,
members,
workflows: wfSummary,
knowledgeBases: kbSummary,
tables: tblSummary,
files: fileSummary,
oauthIntegrations: envSummary.oauthIntegrations,
envVariables: envSummary.envVariables,
tasks: taskSummary,
customTools: toolsSummary,
mcpServers: mcpServersSummary,
skills: skillsSummary,
jobs: jobsSummary,
}
this.files.set('WORKSPACE.md', buildWorkspaceMd(workspaceMdData))
this.files.set('WORKSPACE_CONTEXT.md', buildWorkspaceContextMd(workspaceMdData))
await timed('recently_deleted', this.materializeRecentlyDeleted(workspaceId, userId))
for (const [path, content] of getStaticComponentFiles()) {
this.files.set(path, content)
}
span.setAttributes({
[TraceAttr.CopilotVfsMaterializeFileCount]: this.files.size,
[TraceAttr.CopilotVfsMaterializePhaseMs]: JSON.stringify(phaseMs),
})
} catch (err) {
markSpanForError(span, err)
throw err
} finally {
// Record on success AND failure: a mid-phase failure (e.g. a DB
// timeout) still belongs in copilot.vfs.materialize.duration, else
// p50/p99 skew toward successes only. phaseMs holds whatever phases
// completed before the failure.
for (const [phase, ms] of Object.entries(phaseMs)) {
recordVfsMaterialize(phase, ms)
}
recordVfsMaterialize('total', Date.now() - start)
span.end()
}
}
)
// Durable Grafana signal for "how long does VFS materialize" — total plus
// per-phase (bounded phase set). getOrMaterializeVFS runs per VFS tool call
// with no cross-request cache, so this reveals whether materialize is the
// bottleneck (observability only; not a fix). Recorded inside the span's
// finally above so a failed materialize is captured too, not just successes.
const totalMs = Date.now() - start
logger.info('VFS materialized', {
workspaceId,
fileCount: this.files.size,
durationMs: totalMs,
phaseMs,
})
}
private activeFiles(): Map<string, string> {
const filtered = new Map<string, string>()
for (const [key, value] of this.files) {
if (!key.startsWith('recently-deleted/')) {
filtered.set(key, value)
}
}
return filtered
}
private filesForPath(path?: string): Map<string, string> {
if (path?.startsWith('recently-deleted')) return this.files
return this.activeFiles()
}
grep(
pattern: string,
path?: string,
options?: GrepOptions
): GrepMatch[] | string[] | ops.GrepCountEntry[] {
return ops.grep(this.filesForPath(path), pattern, path, options)
}
/**
* Grep the *content* of a single workspace file (under `files/`), as opposed to
* {@link grep} which searches the in-memory VFS map (workflow JSON, metadata,
* plans, memories — workspace files appear there only as metadata).
*
* Content search applies to workspace files only and must target exactly one
* file (`files/<name>` or `files/<name>/content`, plus the `recently-deleted/`
* variants). A folder, the whole `files/` tree, or any path that does not
* resolve to a single file leaf throws — grepping multiple workspace files at
* once is intentionally unsupported.
*
* Per file type the file's text is resolved via {@link readFileContent} (the
* same extraction `read` uses): text-like files are read as UTF-8, parseable
* documents (pdf/docx/xlsx/pptx/…) are parsed to text, and the regex runs over
* that text. Images and binary files have no searchable text and throw, as do
* files too large for the inline read cap. Reading exactly one file (bounded by
* the existing per-type read caps) keeps this from loading the workspace into
* memory.
*/
async grepFile(
path: string,
pattern: string,
options?: GrepOptions
): Promise<GrepMatch[] | string[] | ops.GrepCountEntry[]> {
const normalized = path.replace(/^\/+/, '')
// Prefer the path verbatim when it is itself a file leaf (e.g. a file literally
// named "content"); otherwise drop a trailing "/content" read suffix.
const leaf = this.files.has(normalized) ? normalized : normalized.replace(/\/content$/, '')
const isWorkspaceFilePath = /^(recently-deleted\/)?files(\/|$)/.test(leaf)
if (!isWorkspaceFilePath || !this.files.has(leaf)) {
const suggestions = this.suggestSimilar(leaf)
const hint =
suggestions.length > 0
? ` Did you mean: ${suggestions.join(', ')}?`
: ' Use glob to find the exact file path, then grep that single file.'
throw new ops.WorkspaceFileGrepError(
`Grep over workspace file content must target a single workspace file (e.g. path: "files/report.csv"). "${path}" is not a single workspace file.${hint}`
)
}
const contentPath = `${leaf}/content`
const result = await this.readFileContent(contentPath)
if (!result) {
throw new ops.WorkspaceFileGrepError(`Workspace file content not found for "${path}".`)
}
return ops.grepReadResult(leaf, result, pattern, contentPath, options)
}
glob(pattern: string): string[] {
const target = pattern.startsWith('recently-deleted') ? this.files : this.activeFiles()
return ops.glob(target, pattern)
}
read(path: string, offset?: number, limit?: number): ReadResult | null {
return ops.read(this.files, path, offset, limit)
}
suggestSimilar(missingPath: string, max?: number): string[] {
return ops.suggestSimilar(this.files, missingPath, max)
}
private async resolveWorkspaceFileForDynamicRead(
path: string,
suffix: 'style' | 'compiled-check' | 'compiled' | 'render' | 'extract'
): Promise<WorkspaceFileRecord | null> {
if (!this._betaEnabled && isWorkflowAliasBackingPath(path)) {
return null
}
const canonicalMatch = path.match(new RegExp(`^files/(.+)/${suffix}$`))
if (!canonicalMatch?.[1]) return null
const files = await listWorkspaceFiles(this._workspaceId, { includeReservedSystemFiles: true })
return findWorkspaceFileRecord(files, `files/${canonicalMatch[1]}`)
}
/**
* Renders a renderable doc (pptx/docx/pdf) record to a contact-sheet image and
* returns it as a model readable JPEG attachment. Shared by the `/render` and
* `/compiled` reads so a binary doc is NEVER attached as a raw (non-PDF)
* `document` block — the model only reads images and application/pdf. Compiles
* the source first when needed (E2B doc sandbox, else isolated-vm); uses the
* binary directly for already-binary uploads. Throws on compile/render failure
* (the caller's try/catch reports it).
*/
private async renderDocRecordResult(
record: WorkspaceFileRecord,
ext: string,
buildMessage: (pageCount: number) => string
): Promise<FileReadResult> {
if (typeof record.size === 'number' && record.size > MAX_DOC_READ_INPUT_BYTES) {
return {
content: JSON.stringify({ ok: false, error: 'File is too large to render' }),
totalLines: 1,
}
}
const buffer = await fetchWorkspaceFileBuffer(record)
if (buffer.length > MAX_DOC_READ_INPUT_BYTES) {
return {
content: JSON.stringify({ ok: false, error: 'File is too large to render' }),
totalLines: 1,
}
}
// Already-binary uploads render directly; source files are compiled first
// (E2B regime -> doc sandbox: Node pptx/docx, Python pdf; otherwise
// isolated-vm pptxgenjs/docx-js/pdf-lib).
let bin: Buffer
if (isBinaryDocBuffer(buffer, ext)) {
bin = buffer
} else {
const code = buffer.toString('utf-8')
if (Buffer.byteLength(code, 'utf-8') > MAX_DOCUMENT_PREVIEW_CODE_BYTES) {
return {
content: JSON.stringify({ ok: false, error: 'File source exceeds maximum size' }),
totalLines: 1,
}
}
if (isE2BDocEnabled && (await getE2BDocFormat(record.name))) {
bin = (
await compileDoc({ source: code, fileName: record.name, workspaceId: this._workspaceId })
).buffer
} else {
const taskId = BINARY_DOC_TASKS[ext]
if (!taskId) {
return {
content: JSON.stringify({ ok: false, error: 'Cannot render this file' }),
totalLines: 1,
}
}
bin = await runSandboxTask(taskId, { code, workspaceId: this._workspaceId })
}
}
const { grid, pageCount } = await renderDocToGrid({
binary: bin,
ext,
workspaceId: this._workspaceId,
})
return {
content: buildMessage(pageCount),
totalLines: 1,
attachment: {
// The rendered contact sheet is a JPEG, so it must be an image block.
// Tagging it 'file' routes it to a provider document block, which only
// accepts application/pdf — Anthropic rejects image/jpeg there with a
// 400 that surfaces to the client as a "Stream error".
type: 'image',
name: `${record.name}.render.jpg`,
source: { type: 'base64', media_type: 'image/jpeg', data: grid.toString('base64') },
},
}
}
/**
* Attempt to read dynamic workspace file content from storage.
* Handles explicit /content reads for images, PDFs, documents, and text files.
* Also handles:
* `files/{path}/{name}/style` — style extraction (.docx / .pptx / .pdf)
* `files/{path}/{name}/compiled-check` — compile JS-source binary files or validate Mermaid diagrams
* `files/{path}/{name}/compiled` — compile JS-source binary files and return the compiled artifact as an attachment
* Files are resolved by their sanitized canonical path only.
* Returns null if the path doesn't match a dynamic file path or the file isn't found.
*/
async readFileContent(path: string): Promise<FileReadResult | null> {
const compiledMatch = /^files\/.+\/compiled$/.test(path)
if (compiledMatch) {
let record: WorkspaceFileRecord | null = null
try {
record = await this.resolveWorkspaceFileForDynamicRead(path, 'compiled')
if (!record) return null
const ext = record.name.split('.').pop()?.toLowerCase() ?? ''
const e2bFmt = isE2BDocEnabled ? await getE2BDocFormat(record.name) : null
const taskId = BINARY_DOC_TASKS[ext]
if (!e2bFmt && !taskId) return null
// Only PDF can be attached as a model-readable `document` block —
// Bedrock/Anthropic document blocks accept application/pdf ONLY. Attaching
// raw pptx/docx/xlsx binary is rejected by the provider (400). So for
// pptx/docx, render to page images (which the model CAN read) and return
// those directly — /compiled can never emit an invalid document block for
// these formats. xlsx isn't renderable; direct to /extract for its content.
if (ext !== 'pdf') {
if (isRenderableDocExt(ext)) {
const compiledName = record.name
return await this.renderDocRecordResult(
record,
ext,
(pageCount) =>
`${compiledName}: the raw ${ext.toUpperCase()} binary isn't model-readable, so it was rendered to ${pageCount} page image(s) for inspection.`
)
}
const extractPath = `${canonicalWorkspaceFilePath({
folderPath: record.folderPath,
name: record.name,
})}/extract`
return {
content: `${record.name} is a spreadsheet — read "${extractPath}" for its contents.`,
totalLines: 1,
}
}
const buffer = await fetchWorkspaceFileBuffer(record)
const code = buffer.toString('utf-8')
if (Buffer.byteLength(code, 'utf-8') > MAX_DOCUMENT_PREVIEW_CODE_BYTES) {
return {
content: JSON.stringify({ ok: false, error: 'File source exceeds maximum size' }),
totalLines: 1,
}
}
const compiled = e2bFmt
? (
await compileDoc({
source: code,
fileName: record.name,
workspaceId: this._workspaceId,
})
).buffer
: await runSandboxTask(taskId, { code, workspaceId: this._workspaceId })
if (compiled.length > MAX_COMPILED_ATTACHMENT_BYTES) {
return {
content: `[Compiled artifact too large: ${record.name} (${compiled.length} bytes, limit ${MAX_COMPILED_ATTACHMENT_BYTES})]`,
totalLines: 1,
}
}
return {
content: `Compiled file: ${record.name} (${compiled.length} bytes, application/pdf)`,
totalLines: 1,
attachment: {
type: 'file',
name: record.name,
source: {
type: 'base64',
media_type: 'application/pdf',
data: compiled.toString('base64'),
},
},
}
} catch (err) {
logger.warn('Compiled artifact read failed via VFS', {
workspaceId: this._workspaceId,
path,
fileId: record?.id,
error: toError(err).message,
})
if (err instanceof SandboxUserCodeError) {
const json = JSON.stringify({
ok: false,
error: toError(err).message,
errorName: err.name,
})
return { content: json, totalLines: 1 }
}
return null
}
}
const renderMatch = /^files\/.+\/render$/.test(path)
if (renderMatch) {
let record: WorkspaceFileRecord | null = null
try {
record = await this.resolveWorkspaceFileForDynamicRead(path, 'render')
if (!record) return null
const ext = record.name.split('.').pop()?.toLowerCase() ?? ''
if (!isRenderableDocExt(ext)) {
return {
content: JSON.stringify({
ok: false,
error: 'Render supports .pptx, .docx, and .pdf only',
}),
totalLines: 1,
}
}
const renderName = record.name
return await this.renderDocRecordResult(
record,
ext,
(pageCount) =>
`Rendered ${pageCount} page(s) of ${renderName} as a contact-sheet grid for visual QA. Inspect each page for text overflow/cutoff, overlapping elements, low contrast, misalignment, and leftover placeholder text; fix and re-render until clean.`
)
} catch (err) {
logger.warn('Render read failed via VFS', {
workspaceId: this._workspaceId,
path,
fileId: record?.id,
error: toError(err).message,
})
// Return an explicit error (not null) once the file resolved — a null read
// looks like a missing path and sends the agent hunting for the "correct"
// render path instead of surfacing the real compile/render failure.
return {
content: JSON.stringify({ ok: false, error: toError(err).message }),
totalLines: 1,
}
}
}
const extractMatch = /^files\/.+\/extract$/.test(path)
if (extractMatch && isE2BDocEnabled) {
let record: WorkspaceFileRecord | null = null
try {
record = await this.resolveWorkspaceFileForDynamicRead(path, 'extract')
if (!record) return null
const ext = record.name.split('.').pop()?.toLowerCase() ?? ''
if (!isExtractableDocExt(ext)) {
return {
content: JSON.stringify({
ok: false,
error: 'Extraction supports .pdf, .pptx, .docx, and .xlsx only',
}),
totalLines: 1,
}
}
// Bound the input before downloading + base64-staging it in-process.
if (typeof record.size === 'number' && record.size > MAX_DOC_READ_INPUT_BYTES) {
return {
content: JSON.stringify({ ok: false, error: 'File is too large to extract' }),
totalLines: 1,
}
}
const buffer = await fetchWorkspaceFileBuffer(record)
if (buffer.length > MAX_DOC_READ_INPUT_BYTES) {
return {
content: JSON.stringify({ ok: false, error: 'File is too large to extract' }),
totalLines: 1,
}
}
// Extraction reads the binary. A source-backed generated doc (text source,
// no binary magic) should be read directly instead — point the agent there.
if (!isBinaryDocBuffer(buffer, ext)) {
return {
content: JSON.stringify({
ok: false,
error: 'This is a source-backed generated file; read its content directly instead.',
}),
totalLines: 1,
}
}
const { text, truncated } = await extractDocText({ binary: buffer, ext })
const note = truncated
? '\n\n[... truncated — read the file directly for the full content]'
: ''
return {
content: `${text || '[no extractable text found]'}${note}`,
totalLines: 1,
}
} catch (err) {
logger.warn('Extract read failed via VFS', {
workspaceId: this._workspaceId,
path,
fileId: record?.id,
error: toError(err).message,
})
return {
content: JSON.stringify({ ok: false, error: toError(err).message }),
totalLines: 1,
}
}
}
const compiledCheckMatch = /^files\/.+\/compiled-check$/.test(path)
if (compiledCheckMatch) {
let record: WorkspaceFileRecord | null = null
try {
record = await this.resolveWorkspaceFileForDynamicRead(path, 'compiled-check')
if (!record) return null
const ext = record.name.split('.').pop()?.toLowerCase() ?? ''
const e2bFmt = isE2BDocEnabled ? await getE2BDocFormat(record.name) : null
const taskId = BINARY_DOC_TASKS[ext]
const isMermaidFile = ext === 'mmd' || ext === 'mermaid'
if (!e2bFmt && !taskId && !isMermaidFile) return null
const buffer = await fetchWorkspaceFileBuffer(record)
const code = buffer.toString('utf-8')
if (Buffer.byteLength(code, 'utf-8') > MAX_DOCUMENT_PREVIEW_CODE_BYTES) {
return {
content: JSON.stringify({ ok: false, error: 'File source exceeds maximum size' }),
totalLines: 1,
}
}
if (isMermaidFile) {
const result = await validateMermaidSource(code)
const json = JSON.stringify(result)
return { content: json, totalLines: 1 }
}
let result: { ok: boolean; error?: string; errorName?: string }
if (e2bFmt) {
// Loads the artifact if present, else compiles once (and recalc-scans
// xlsx). Only a script error is { ok: false }; infra failures rethrow to
// the outer catch so an E2B/S3 outage isn't reported as a bad script.
result = await runE2BCompiledCheck({
source: code,
fileName: record.name,
workspaceId: this._workspaceId,
ext,
})
} else {
try {
if (!taskId) return null
await runSandboxTask(taskId, { code, workspaceId: this._workspaceId })
result = { ok: true }
} catch (err) {
if (err instanceof SandboxUserCodeError) {
result = { ok: false, error: toError(err).message, errorName: err.name }
} else {
throw err
}
}
}
const json = JSON.stringify(result)
return { content: json, totalLines: 1 }
} catch (err) {
logger.warn('Compiled check failed via VFS', {
workspaceId: this._workspaceId,
path,
fileId: record?.id,
error: toError(err).message,
})
return null
}
}
const styleMatch = /^files\/.+\/style$/.test(path)
if (styleMatch) {
let record: WorkspaceFileRecord | null = null
try {
record = await this.resolveWorkspaceFileForDynamicRead(path, 'style')
if (!record) return null
const rawExt = record.name.split('.').pop()?.toLowerCase()
if (rawExt !== 'docx' && rawExt !== 'pptx' && rawExt !== 'pdf') return null
const ext: 'docx' | 'pptx' | 'pdf' = rawExt
const buffer = await fetchWorkspaceFileBuffer(record)
const summary = await extractDocumentStyle(buffer, ext)
if (!summary) return null
const json = JSON.stringify(summary, null, 2)
return { content: json, totalLines: json.split('\n').length }
} catch (err) {
logger.warn('Failed to extract document style via VFS', {
workspaceId: this._workspaceId,
path,
fileId: record?.id,
error: toError(err).message,
})
return null
}
}
const deletedMatch = path.match(/^recently-deleted\/files\/(.+)\/content$/)
const activeMatch = path.match(/^files\/(.+)\/content$/)
const match = deletedMatch || activeMatch
if (!match) return null
const fileReference = path
.replace(/^recently-deleted\//, '')
.replace(/\/content$/, '')
.replace(/^\/+/, '')
if (!this._betaEnabled && isWorkflowAliasBackingPath(fileReference)) {
return null
}
if (fileReference.endsWith('/meta.json') || path.endsWith('/meta.json')) return null
const scope = deletedMatch ? 'archived' : 'active'
try {
const files = await listWorkspaceFiles(this._workspaceId, {
scope,
includeReservedSystemFiles: this._betaEnabled,
})
const record = findWorkspaceFileRecord(files, fileReference)
if (!record) return null
return readFileRecord(record)
} catch (err) {
logger.warn('Failed to list workspace files for readFileContent', {