-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtoolfs.go
More file actions
1918 lines (1669 loc) · 55.1 KB
/
toolfs.go
File metadata and controls
1918 lines (1669 loc) · 55.1 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
package toolfs
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
// FileInfo represents file metadata
type FileInfo struct {
Size int64
ModTime time.Time
IsDir bool
}
// Mount represents a mounted directory with its permissions
type Mount struct {
LocalPath string
ReadOnly bool
}
// MemoryEntry represents a memory entry with content and metadata
type MemoryEntry struct {
ID string `json:"id"`
Content string `json:"content"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
// RAGResult represents a single RAG search result
type RAGResult struct {
ID string `json:"id"`
Content string `json:"content"`
Score float64 `json:"score"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
// RAGSearchResults represents RAG search results
type RAGSearchResults struct {
Query string `json:"query"`
TopK int `json:"top_k"`
Results []RAGResult `json:"results"`
}
// MemoryStore defines the interface for memory storage
type MemoryStore interface {
Get(id string) (*MemoryEntry, error)
Set(id string, content string, metadata map[string]interface{}) error
List() ([]string, error)
}
// RAGStore defines the interface for RAG storage and search
type RAGStore interface {
Search(query string, topK int) ([]RAGResult, error)
}
// AuditLogEntry represents a single audit log entry
type AuditLogEntry struct {
Timestamp time.Time `json:"timestamp"`
SessionID string `json:"session_id"`
Operation string `json:"operation"` // "ReadFile", "WriteFile", "ListDir", "Stat"
Path string `json:"path"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
BytesRead int64 `json:"bytes_read,omitempty"`
BytesWritten int64 `json:"bytes_written,omitempty"`
AccessDenied bool `json:"access_denied,omitempty"`
}
// AuditLogger defines the interface for audit logging
type AuditLogger interface {
Log(entry AuditLogEntry) error
}
// StdoutAuditLogger logs audit entries to stdout as JSON
type StdoutAuditLogger struct{}
// Log writes an audit entry to stdout as JSON
func (l *StdoutAuditLogger) Log(entry AuditLogEntry) error {
data, err := json.Marshal(entry)
if err != nil {
return err
}
fmt.Println(string(data))
return nil
}
// Session represents an isolated LLM session with access restrictions
type Session struct {
ID string
CreatedAt time.Time
AllowedPaths []string // List of allowed path prefixes
AuditLogger AuditLogger
CommandValidator CommandValidator // Optional command validator
}
// NewSession creates a new session with the given ID and allowed paths
func NewSession(id string, allowedPaths []string) *Session {
return &Session{
ID: id,
CreatedAt: time.Now(),
AllowedPaths: allowedPaths,
AuditLogger: &StdoutAuditLogger{},
}
}
// SetAuditLogger sets a custom audit logger for the session
func (s *Session) SetAuditLogger(logger AuditLogger) {
s.AuditLogger = logger
}
// SetCommandValidator sets a command validator for the session
func (s *Session) SetCommandValidator(validator CommandValidator) {
s.CommandValidator = validator
}
// ValidateCommand checks if a command is allowed for this session
func (s *Session) ValidateCommand(command string, args []string) (bool, string) {
if s.CommandValidator == nil {
return true, "" // No filter means all commands allowed
}
return s.CommandValidator.IsCommandAllowed(command, args)
}
// IsPathAllowed checks if a path is allowed for this session
func (s *Session) IsPathAllowed(path string) bool {
if len(s.AllowedPaths) == 0 {
return true // No restrictions if no paths specified
}
path = normalizeVirtualPath(path)
for _, allowed := range s.AllowedPaths {
allowed = normalizeVirtualPath(allowed)
if strings.HasPrefix(path, allowed) {
return true
}
}
return false
}
// logAudit logs an audit entry for this session
func (s *Session) logAudit(operation, path string, success bool, err error, bytesRead, bytesWritten int64) {
if s.AuditLogger == nil {
return
}
entry := AuditLogEntry{
Timestamp: time.Now(),
SessionID: s.ID,
Operation: operation,
Path: path,
Success: success,
BytesRead: bytesRead,
BytesWritten: bytesWritten,
AccessDenied: !success && err != nil && strings.Contains(err.Error(), "access denied"),
}
if err != nil {
entry.Error = err.Error()
}
s.AuditLogger.Log(entry)
}
// SnapshotMetadata represents metadata for a snapshot
type SnapshotMetadata struct {
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
Size int64 `json:"size"` // Total size of snapshot data
FileCount int `json:"file_count"` // Number of files in snapshot
}
// FileSnapshot represents a snapshot of a single file
type FileSnapshot struct {
Path string `json:"path"`
Content []byte `json:"content"`
Size int64 `json:"size"`
ModTime time.Time `json:"mod_time"`
IsDir bool `json:"is_dir"`
Operation string `json:"operation"` // "created", "modified", "deleted", "unchanged"
}
// Snapshot represents a complete filesystem snapshot
type Snapshot struct {
Metadata SnapshotMetadata `json:"metadata"`
Files map[string]*FileSnapshot `json:"files"` // Path -> FileSnapshot
Changes []ChangeRecord `json:"changes"` // Tracked changes
BaseSnapshot string `json:"base_snapshot,omitempty"` // For copy-on-write
}
// ChangeRecord tracks a change made after snapshot creation
type ChangeRecord struct {
Path string `json:"path"`
Operation string `json:"operation"` // "write", "delete", "create"
Timestamp time.Time `json:"timestamp"`
SessionID string `json:"session_id,omitempty"`
}
// SandboxBackend defines interface for optional sandbox/MicroVM integration
type SandboxBackend interface {
CreateSnapshot(name string) error
RestoreSnapshot(name string) error
DeleteSnapshot(name string) error
ListSnapshots() ([]string, error)
}
// SkillMount represents a skill mounted to a path
type SkillMount struct {
SkillName string
Skill SkillExecutor
ReadOnly bool // Whether the skill mount is read-only
}
// ToolFS represents the filesystem instance
type ToolFS struct {
rootPath string
mounts map[string]*Mount
skillMounts map[string]*SkillMount // Path -> SkillMount (formerly SkillMount)
memoryStore MemoryStore
ragStore RAGStore
sessions map[string]*Session
snapshots map[string]*Snapshot
currentSnapshot string // Currently active snapshot (if any)
sandboxBackend SandboxBackend // Optional sandbox integration
executorManager *SkillExecutorManager // Optional skill manager
executorRegistry *SkillExecutorRegistry // Optional direct skill registry
skillDocManager *SkillDocumentManager // Skill document manager
skillRegistry *SkillRegistry // Skill registry for managing skills
builtinSkills *BuiltinSkills // Built-in skills (Memory, RAG)
// Performance optimizations: cached paths
memoryPath string // Cached memory path: rootPath + "/memory"
ragPath string // Cached RAG path: rootPath + "/rag"
pathNormalizeCache sync.Map // Cache for path normalization results
pathResolveCache sync.Map // Cache for path resolution results (path -> *resolveCacheEntry)
}
// resolveCacheEntry represents a cached path resolution result
type resolveCacheEntry struct {
localPath string
mount *Mount
mu sync.RWMutex
}
// NewToolFS creates a new ToolFS instance with the specified root path
func NewToolFS(rootPath string) *ToolFS {
rootPath = normalizeVirtualPath(rootPath)
fs := &ToolFS{
rootPath: rootPath,
mounts: make(map[string]*Mount),
skillMounts: make(map[string]*SkillMount),
memoryStore: NewInMemoryStore(),
ragStore: NewInMemoryRAGStore(),
sessions: make(map[string]*Session),
snapshots: make(map[string]*Snapshot),
currentSnapshot: "",
skillDocManager: NewSkillDocumentManager(),
}
// Pre-compute and cache virtual paths for performance
fs.memoryPath = normalizeVirtualPath(rootPath + "/memory")
fs.ragPath = normalizeVirtualPath(rootPath + "/rag")
// Load built-in skill documents from filesystem
_ = fs.skillDocManager.LoadBuiltinSkillDocs()
return fs
}
// SetSkillExecutorManager sets the skill manager for ToolFS skill mounts
// If builtin skills haven't been registered yet, they will be registered automatically
func (fs *ToolFS) SetSkillExecutorManager(manager *SkillExecutorManager) {
fs.executorManager = manager
// Auto-register builtin skills if not already registered
if fs.builtinSkills == nil && manager != nil {
// Create a default session for builtin skills
defaultSession, _ := fs.NewSession("__builtin__", []string{})
builtinSkills, err := RegisterBuiltinSkills(fs, manager, defaultSession)
if err == nil {
fs.builtinSkills = builtinSkills
// Register builtin skills with skill document manager
if fs.skillDocManager != nil {
fs.skillDocManager.RegisterExecutor(builtinSkills.Memory)
fs.skillDocManager.RegisterExecutor(builtinSkills.RAG)
}
}
}
}
// SetSandboxBackend sets an optional sandbox backend for snapshot integration
func (fs *ToolFS) SetSandboxBackend(backend SandboxBackend) {
fs.sandboxBackend = backend
}
// NewSession creates a new session and registers it with the ToolFS instance
func (fs *ToolFS) NewSession(sessionID string, allowedPaths []string) (*Session, error) {
if _, exists := fs.sessions[sessionID]; exists {
return nil, errors.New("session already exists")
}
session := NewSession(sessionID, allowedPaths)
fs.sessions[sessionID] = session
return session, nil
}
// GetSession retrieves a session by ID
func (fs *ToolFS) GetSession(sessionID string) (*Session, error) {
session, exists := fs.sessions[sessionID]
if !exists {
return nil, errors.New("session not found")
}
return session, nil
}
// DeleteSession removes a session
func (fs *ToolFS) DeleteSession(sessionID string) {
delete(fs.sessions, sessionID)
}
// SetMemoryStore sets the memory store for the ToolFS instance
func (fs *ToolFS) SetMemoryStore(store MemoryStore) {
fs.memoryStore = store
}
// SetRAGStore sets the RAG store for the ToolFS instance
func (fs *ToolFS) SetRAGStore(store RAGStore) {
fs.ragStore = store
}
// GetSkillDocumentManager returns the skill document manager
func (fs *ToolFS) GetSkillDocumentManager() *SkillDocumentManager {
return fs.skillDocManager
}
// normalizeVirtualPath normalizes a virtual path to use forward slashes
// Optimized: uses builder to reduce allocations and handles common cases efficiently
func normalizeVirtualPath(path string) string {
if path == "" {
return ""
}
// Fast path: check if path is already normalized (common case)
needsNormalization := false
for i := 0; i < len(path); i++ {
if path[i] == '\\' || (i < len(path)-1 && path[i] == '/' && path[i+1] == '/') {
needsNormalization = true
break
}
}
if !needsNormalization && !strings.HasPrefix(path, "./") {
return path
}
// Slow path: normalize the path
var builder strings.Builder
builder.Grow(len(path)) // Pre-allocate capacity
skipSlash := false
start := 0
// Skip "./" prefix
if strings.HasPrefix(path, "./") {
start = 2
}
for i := start; i < len(path); i++ {
c := path[i]
if c == '\\' {
// Replace backslash with forward slash
if !skipSlash {
builder.WriteByte('/')
skipSlash = true
}
} else if c == '/' {
// Skip duplicate slashes
if !skipSlash {
builder.WriteByte('/')
skipSlash = true
}
} else {
builder.WriteByte(c)
skipSlash = false
}
}
result := builder.String()
// Remove trailing slash if it's not the root
if len(result) > 1 && result[len(result)-1] == '/' {
result = result[:len(result)-1]
}
return result
}
// MountLocal mounts a local directory at the specified mount point
// mountPoint is the path within the ToolFS root (e.g., "/data")
// localPath is the actual local filesystem path
// readOnly determines if the mount is read-only
func (fs *ToolFS) MountLocal(mountPoint string, localPath string, readOnly bool) error {
// Normalize mount point to use forward slashes
mountPoint = normalizeVirtualPath(mountPoint)
if !strings.HasPrefix(mountPoint, fs.rootPath) {
// Join with root path, ensuring forward slashes
if !strings.HasPrefix(mountPoint, "/") {
mountPoint = "/" + mountPoint
}
mountPoint = normalizeVirtualPath(fs.rootPath + mountPoint)
}
// Verify local path exists
info, err := os.Stat(localPath)
if err != nil {
return err
}
if !info.IsDir() {
return errors.New("local path must be a directory")
}
fs.mounts[mountPoint] = &Mount{
LocalPath: localPath,
ReadOnly: readOnly,
}
// Invalidate path resolution cache since mounts changed
fs.pathResolveCache.Range(func(key, value interface{}) bool {
path := key.(string)
// Remove cache entries that might be affected by this mount
if strings.HasPrefix(path, mountPoint) || strings.HasPrefix(mountPoint, path) {
fs.pathResolveCache.Delete(key)
}
return true
})
return nil
}
// isVirtualPath checks if the path is a virtual path (memory or rag)
// Optimized: uses pre-computed cached paths
func (fs *ToolFS) isVirtualPath(path string) (bool, string) {
path = normalizeVirtualPath(path)
if strings.HasPrefix(path, fs.memoryPath) {
return true, "memory"
}
if strings.HasPrefix(path, fs.ragPath) {
return true, "rag"
}
return false, ""
}
// isSkillMount checks if the path is mounted to a skill
func (fs *ToolFS) isSkillMount(path string) (*SkillMount, string) {
path = normalizeVirtualPath(path)
// Find the longest matching skill mount point
var bestMount *SkillMount
var bestMountPoint string
var relPath string
for mountPoint, skillMount := range fs.skillMounts {
mountPoint = normalizeVirtualPath(mountPoint)
if strings.HasPrefix(path, mountPoint) {
if len(mountPoint) > len(bestMountPoint) {
bestMountPoint = mountPoint
bestMount = skillMount
relPath = strings.TrimPrefix(path, mountPoint)
relPath = strings.TrimPrefix(relPath, "/")
if relPath == "" {
relPath = "/"
} else {
relPath = "/" + relPath
}
}
}
}
if bestMount != nil {
return bestMount, relPath
}
return nil, ""
}
// MountSkillExecutor mounts a skill to a ToolFS path.
// When operations are performed on paths under the mount point,
// they are forwarded to the skill's Execute method.
//
// Example:
//
// fs.MountSkillExecutor("/toolfs/rag", "rag-skill")
// // ReadFile("/toolfs/rag/query?text=test") will forward to skill
func (fs *ToolFS) MountSkillExecutor(path string, skillName string) error {
if path == "" {
return errors.New("mount path cannot be empty")
}
if skillName == "" {
return errors.New("skill name cannot be empty")
}
// Normalize path
path = normalizeVirtualPath(path)
if !strings.HasPrefix(path, fs.rootPath) {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
path = normalizeVirtualPath(fs.rootPath + path)
}
// Check if skill exists in skill manager or registry
var skill SkillExecutor
registry := fs.GetSkillExecutorRegistry()
if registry != nil {
var err error
skill, err = registry.Get(skillName)
if err != nil {
return fmt.Errorf("skill '%s' not found in registry: %w", skillName, err)
}
} else {
return errors.New("skill registry not set, use AddSkillExecutorRegistry() or SetSkillExecutorManager() first")
}
// Check if path is already mounted
if _, exists := fs.skillMounts[path]; exists {
return fmt.Errorf("path '%s' is already mounted to a skill", path)
}
// Create skill mount
fs.skillMounts[path] = &SkillMount{
SkillName: skillName,
Skill: skill,
ReadOnly: true, // Skills are read-only by default for safety
}
// Invalidate path resolution cache since skill mounts changed
fs.pathResolveCache.Range(func(key, value interface{}) bool {
pathKey := key.(string)
// Remove cache entries that might be affected by this mount
if strings.HasPrefix(pathKey, path) || strings.HasPrefix(path, pathKey) {
fs.pathResolveCache.Delete(key)
}
return true
})
return nil
}
// UnmountSkillExecutor removes a skill mount from a path.
func (fs *ToolFS) UnmountSkillExecutor(path string) error {
path = normalizeVirtualPath(path)
if !strings.HasPrefix(path, fs.rootPath) {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
path = normalizeVirtualPath(fs.rootPath + path)
}
if _, exists := fs.skillMounts[path]; !exists {
return fmt.Errorf("no skill mounted at path '%s'", path)
}
delete(fs.skillMounts, path)
// Invalidate path resolution cache since skill mounts changed
fs.pathResolveCache.Range(func(key, value interface{}) bool {
pathKey := key.(string)
// Remove cache entries that might be affected by this unmount
if strings.HasPrefix(pathKey, path) {
fs.pathResolveCache.Delete(key)
}
return true
})
return nil
}
// executeSkillMount executes a skill for a given path and operation.
func (fs *ToolFS) executeSkillMount(skillMount *SkillMount, path, relPath, operation string, inputData []byte, session *Session) ([]byte, error) {
// Create skill request
request := SkillRequest{
Operation: operation,
Path: path,
Data: map[string]interface{}{
"relative_path": relPath,
"full_path": path,
},
}
// Add input data if provided
if inputData != nil {
request.Data["input"] = string(inputData)
}
// Add session info if available
if session != nil {
request.Data["session_id"] = session.ID
}
// Marshal request
requestBytes, err := json.Marshal(request)
if err != nil {
return nil, fmt.Errorf("failed to create skill request: %w", err)
}
// Execute skill with error recovery
var output []byte
var execErr error
func() {
defer func() {
if r := recover(); r != nil {
// Skill execution panicked - convert to error but don't crash
execErr = fmt.Errorf("skill execution panicked: %v", r)
}
}()
// Execute skill
output, execErr = skillMount.Skill.Execute(requestBytes)
}()
if execErr != nil {
return nil, fmt.Errorf("skill execution failed: %w", execErr)
}
// Parse skill response
var response SkillResponse
if err := json.Unmarshal(output, &response); err != nil {
return nil, fmt.Errorf("failed to parse skill response: %w", err)
}
if !response.Success {
return nil, fmt.Errorf("skill returned error: %s", response.Error)
}
// Extract result
if resultStr, ok := response.Result.(string); ok {
return []byte(resultStr), nil
}
// Try to marshal result to JSON if it's not a string
resultBytes, err := json.Marshal(response.Result)
if err != nil {
return nil, fmt.Errorf("failed to marshal skill result: %w", err)
}
return resultBytes, nil
}
// resolvePath resolves a ToolFS path to a local filesystem path
// Optimized: uses result caching to avoid repeated resolution
func (fs *ToolFS) resolvePath(path string) (string, *Mount, error) {
// Normalize the virtual path to use forward slashes
path = normalizeVirtualPath(path)
// Try to get from cache first
// Note: Cache is invalidated when mounts change (MountLocal/UnmountSkillExecutor)
if cached, ok := fs.pathResolveCache.Load(path); ok {
entry := cached.(*resolveCacheEntry)
entry.mu.RLock()
localPath := entry.localPath
mount := entry.mount
entry.mu.RUnlock()
// Return cached result
// Cache is invalidated when mounts change, so this is safe
return localPath, mount, nil
}
// Not in cache, resolve the path
var localPath string
var mount *Mount
var err error
// Check if this is a skill mount first (highest priority)
if skillMount, relPath := fs.isSkillMount(path); skillMount != nil {
// Return special marker for skill mount
localPath = relPath
mount = &Mount{LocalPath: "__SKILL_MOUNT__:" + skillMount.SkillName, ReadOnly: skillMount.ReadOnly}
} else if isVirtual, vType := fs.isVirtualPath(path); isVirtual {
// Check if this is a virtual path (memory or rag)
localPath = ""
if vType == "memory" {
mount = &Mount{LocalPath: "__VIRTUAL_MEMORY__", ReadOnly: false}
} else if vType == "rag" {
mount = &Mount{LocalPath: "__VIRTUAL_RAG__", ReadOnly: true}
}
} else {
// Find the longest matching mount point
var bestMount *Mount
var bestMountPoint string
var bestLocalPath string
for mountPoint, m := range fs.mounts {
if strings.HasPrefix(path, mountPoint) {
if len(mountPoint) > len(bestMountPoint) {
bestMountPoint = mountPoint
bestMount = m
// Calculate the relative path within the mount
relPath := strings.TrimPrefix(path, mountPoint)
relPath = strings.TrimPrefix(relPath, "/")
relPath = strings.TrimPrefix(relPath, "\\")
if relPath == "" {
bestLocalPath = m.LocalPath
} else {
bestLocalPath = filepath.Join(m.LocalPath, relPath)
}
}
}
}
if bestMount == nil {
err = errors.New("path not found in any mount")
return "", nil, err
}
localPath = bestLocalPath
mount = bestMount
}
// Cache the result (only for successful resolutions)
// Note: err is nil at this point if we reached here
entry := &resolveCacheEntry{
localPath: localPath,
mount: mount,
}
fs.pathResolveCache.Store(path, entry)
return localPath, mount, nil
}
// ReadFile reads a file from the ToolFS
func (fs *ToolFS) ReadFile(path string) ([]byte, error) {
return fs.ReadFileWithSession(path, nil)
}
// ReadFileWithSession reads a file from the ToolFS with session-based access control
func (fs *ToolFS) ReadFileWithSession(path string, session *Session) ([]byte, error) {
// Check access control
if session != nil && !session.IsPathAllowed(path) {
err := fmt.Errorf("access denied: path '%s' is not allowed for session '%s'", path, session.ID)
session.logAudit("ReadFile", path, false, err, 0, 0)
return nil, err
}
localPath, mount, err := fs.resolvePath(path)
if err != nil {
if session != nil {
session.logAudit("ReadFile", path, false, err, 0, 0)
}
return nil, err
}
var data []byte
// Handle skill mounts
if strings.HasPrefix(mount.LocalPath, "__SKILL_MOUNT__:") {
skillName := strings.TrimPrefix(mount.LocalPath, "__SKILL_MOUNT__:")
// Find the skill mount by matching path prefix
var skillMount *SkillMount
var mountPoint string
for mp, pm := range fs.skillMounts {
if pm.SkillName == skillName && strings.HasPrefix(path, mp) {
if len(mp) > len(mountPoint) {
mountPoint = mp
skillMount = pm
}
}
}
if skillMount != nil {
// Execute skill with error recovery
data, err = fs.executeSkillMount(skillMount, path, localPath, "read_file", nil, session)
if err != nil {
// Return error but don't crash
return nil, err
}
} else {
return nil, fmt.Errorf("skill mount not found for path: %s", path)
}
} else if mount.LocalPath == "__VIRTUAL_MEMORY__" {
data, err = fs.readMemory(path)
} else if mount.LocalPath == "__VIRTUAL_RAG__" {
data, err = fs.readRAG(path)
} else {
data, err = os.ReadFile(localPath)
}
// Log audit entry
if session != nil {
bytesRead := int64(0)
if err == nil {
bytesRead = int64(len(data))
}
session.logAudit("ReadFile", path, err == nil, err, bytesRead, 0)
}
return data, err
}
// readMemory reads a memory entry
// Optimized: uses pre-computed cached memoryPath
func (fs *ToolFS) readMemory(path string) ([]byte, error) {
path = normalizeVirtualPath(path)
memoryPathWithSlash := fs.memoryPath + "/"
// Extract memory entry ID
relPath := strings.TrimPrefix(path, memoryPathWithSlash)
parts := strings.Split(relPath, "/")
if len(parts) == 0 || parts[0] == "" {
// Listing memory directory - return empty for now
return nil, errors.New("cannot read memory directory directly, use ListDir")
}
entryID := parts[0]
entry, err := fs.memoryStore.Get(entryID)
if err != nil {
return nil, err
}
// Return JSON representation for consistent API behavior
return json.Marshal(entry)
}
// readRAG performs a RAG search
// Optimized: uses pre-computed cached ragPath
func (fs *ToolFS) readRAG(path string) ([]byte, error) {
path = normalizeVirtualPath(path)
ragPathWithSlash := fs.ragPath + "/"
// Check if this is a query
relPath := strings.TrimPrefix(path, ragPathWithSlash)
if strings.HasPrefix(relPath, "query") {
// Split on "?" to separate path from query string
parts := strings.SplitN(relPath, "?", 2)
if len(parts) < 2 {
return nil, errors.New("invalid RAG query format, missing query parameters")
}
// Parse query parameters
queryURL, err := url.ParseQuery(parts[1])
if err != nil {
return nil, errors.New("invalid RAG query format")
}
query := queryURL.Get("text")
if query == "" {
query = queryURL.Get("q")
}
if query == "" {
return nil, errors.New("missing 'text' or 'q' parameter in RAG query")
}
// Decode URL-encoded query (e.g., "AI+agent" -> "AI agent")
decodedQuery, err := url.QueryUnescape(query)
if err == nil {
query = decodedQuery
}
topK := 5 // default
if topKStr := queryURL.Get("top_k"); topKStr != "" {
var err error
topK, err = strconv.Atoi(topKStr)
if err != nil || topK <= 0 {
return nil, errors.New("invalid top_k parameter")
}
}
results, err := fs.ragStore.Search(query, topK)
if err != nil {
return nil, err
}
searchResults := RAGSearchResults{
Query: query,
TopK: topK,
Results: results,
}
return json.Marshal(searchResults)
}
return nil, errors.New("invalid RAG path, use /toolfs/rag/query?text=...&top_k=...")
}
// WriteFile writes data to a file in the ToolFS
func (fs *ToolFS) WriteFile(path string, data []byte) error {
return fs.WriteFileWithSession(path, data, nil)
}
// WriteFileWithSession writes data to a file in the ToolFS with session-based access control
func (fs *ToolFS) WriteFileWithSession(path string, data []byte, session *Session) error {
// Check access control
if session != nil && !session.IsPathAllowed(path) {
err := fmt.Errorf("access denied: path '%s' is not allowed for session '%s'", path, session.ID)
session.logAudit("WriteFile", path, false, err, 0, 0)
return err
}
localPath, mount, err := fs.resolvePath(path)
if err != nil {
if session != nil {
session.logAudit("WriteFile", path, false, err, 0, 0)
}
return err
}
// Handle skill mounts
if strings.HasPrefix(mount.LocalPath, "__SKILL_MOUNT__:") {
skillName := strings.TrimPrefix(mount.LocalPath, "__SKILL_MOUNT__:")
var skillMount *SkillMount
var mountPoint string
for mp, pm := range fs.skillMounts {
if pm.SkillName == skillName && strings.HasPrefix(path, mp) {
if len(mp) > len(mountPoint) {
mountPoint = mp
skillMount = pm
}
}
}
if skillMount != nil {
if skillMount.ReadOnly {
err := errors.New("cannot write to read-only skill mount")
if session != nil {
session.logAudit("WriteFile", path, false, err, 0, 0)
}
return err
}
// Execute skill for write_file operation
_, err = fs.executeSkillMount(skillMount, path, localPath, "write_file", data, session)
if err != nil {
// Return error but don't crash
if session != nil {
session.logAudit("WriteFile", path, false, err, 0, 0)
}
return err
}
} else {
err = fmt.Errorf("skill mount not found for path: %s", path)
}
} else if mount.ReadOnly {
err := errors.New("cannot write to read-only mount")
if session != nil {
session.logAudit("WriteFile", path, false, err, 0, 0)
}
return err
} else if mount.LocalPath == "__VIRTUAL_MEMORY__" {
err = fs.writeMemory(path, data)
} else if mount.LocalPath == "__VIRTUAL_RAG__" {
err = errors.New("cannot write to RAG store")
} else {
// Create parent directory if it doesn't exist
parentDir := filepath.Dir(localPath)
if err := os.MkdirAll(parentDir, 0o755); err != nil {
if session != nil {
session.logAudit("WriteFile", path, false, err, 0, 0)
}
return err
}
err = os.WriteFile(localPath, data, 0o644)
}
// Log audit entry
if session != nil {
bytesWritten := int64(0)
if err == nil {
bytesWritten = int64(len(data))
}
session.logAudit("WriteFile", path, err == nil, err, 0, bytesWritten)
}
// Track change for snapshot
if err == nil {
sessionID := ""
if session != nil {
sessionID = session.ID
}
// Optimization: Check file existence before write to avoid extra Stat call
// We can use os.Stat on localPath before writing to determine create vs modify
operation := "write"
if localPath != "" && mount != nil && mount.LocalPath != "__VIRTUAL_MEMORY__" && mount.LocalPath != "__VIRTUAL_RAG__" {
// Check if file existed before write (optimize: only for local filesystem)
if _, statErr := os.Stat(localPath); statErr != nil {
operation = "create"
}
}
// Note: For virtual paths, we default to "write" since existence check
// would require calling the virtual store, which may be expensive