Open History to see the last commit
1import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
2import { join } from 'node:path'
3import { existsSync } from 'node:fs'
4import { createDefaultTrustStrategy } from '../trust-strategies'
5import type {
6 Snippet,
7 SnippetIndexEntry,
8 SnippetSearchOptions,
9 SnippetStorage,
10} from '../types'
11import type { TrustStrategy } from '../trust-strategies'
12
13export interface FileSnippetStorageOptions {
14 /**
15 * Directory path for storing snippets
16 */
17 directory: string
18
19 /**
20 * Trust strategy for determining snippet trust levels
21 * @default createDefaultTrustStrategy()
22 */
23 trustStrategy?: TrustStrategy
24}
25
26/**
27 * File-system based snippet storage
28 *
29 * Directory structure:
30 * .snippets/
31 * _index.json # Fast catalog loading
32 * fetch_github_stats/
33 * meta.json # Metadata (description, schemas, hints, stats)
34 * code.ts # The actual TypeScript code
35 * deploy_to_prod/
36 * meta.json
37 * code.ts
38 */
39export function createFileSnippetStorage(
40 directoryOrOptions: string | FileSnippetStorageOptions,
41): SnippetStorage {
42 const options =
43 typeof directoryOrOptions === 'string'
44 ? { directory: directoryOrOptions }
45 : directoryOrOptions
46
47 const { directory, trustStrategy = createDefaultTrustStrategy() } = options
48 const indexPath = join(directory, '_index.json')
49
50 console.log('[FileSnippetStorage] Initialized with directory:', directory)
51
52 // Snippet names are used both as on-disk directory segments and as
53 // `snippet_<name>` sandbox tool names, so they must be a single safe
54 // identifier segment. Rejecting anything else keeps an LLM-supplied name
55 // (e.g. `../../etc`) from escaping `directory` during read/write/delete.
56 const SAFE_SNIPPET_NAME = /^[A-Za-z0-9_-]+$/
57
58 function isSafeSnippetName(name: string): boolean {
59 return typeof name === 'string' && SAFE_SNIPPET_NAME.test(name)
60 }
61
62 function assertSafeSnippetName(name: string): void {
63 if (!isSafeSnippetName(name)) {
64 throw new Error(
65 `Invalid snippet name ${JSON.stringify(
66 name,
67 )}: names must match /^[A-Za-z0-9_-]+$/ (no path separators or traversal).`,
68 )
69 }
70 }
71
72 async function ensureDirectory(): Promise<void> {
73 if (!existsSync(directory)) {
74 console.log('[FileSnippetStorage] Creating directory:', directory)
75 await mkdir(directory, { recursive: true })
76 }
77 }
78
79 async function loadIndex(): Promise<Array<SnippetIndexEntry>> {
80 await ensureDirectory()
81
82 if (!existsSync(indexPath)) {
83 return []
84 }
85
86 const content = await readFile(indexPath, 'utf-8')
87 return JSON.parse(content) as Array<SnippetIndexEntry>
88 }
89
90 async function loadAll(): Promise<Array<Snippet>> {
91 const index = await loadIndex()
92 const snippets: Array<Snippet> = []
93
94 for (const entry of index) {
95 const snippet = await get(entry.name)
96 if (snippet) {
97 snippets.push(snippet)
98 }
99 }
100
101 return snippets
102 }
103
104 async function saveIndex(index: Array<SnippetIndexEntry>): Promise<void> {
105 await writeFile(indexPath, JSON.stringify(index, null, 2))
106 }
107
108 async function get(name: string): Promise<Snippet | null> {
109 // Treat an unsafe name as "not found" rather than reading outside `directory`.
110 if (!isSafeSnippetName(name)) {
111 return null
112 }
113
114 const snippetDir = join(directory, name)
115 const metaPath = join(snippetDir, 'meta.json')
116 const codePath = join(snippetDir, 'code.ts')
117
118 if (!existsSync(metaPath)) {
119 return null
120 }
121
122 const [metaContent, code] = await Promise.all([
123 readFile(metaPath, 'utf-8'),
124 readFile(codePath, 'utf-8'),
125 ])
126
127 const meta = JSON.parse(metaContent) as Omit<Snippet, 'code'>
128 return { ...meta, code }
129 }
130
131 async function save(
132 snippet: Omit<Snippet, 'createdAt' | 'updatedAt'>,
133 ): Promise<Snippet> {
134 assertSafeSnippetName(snippet.name)
135 await ensureDirectory()
136
137 const snippetDir = join(directory, snippet.name)
138 const metaPath = join(snippetDir, 'meta.json')
139 const codePath = join(snippetDir, 'code.ts')
140
141 const now = new Date().toISOString()
142 const existing = await get(snippet.name)
143
144 const fullSnippet: Snippet = {
145 ...snippet,
146 createdAt: existing?.createdAt ?? now,
147 updatedAt: now,
148 }
149
150 // Separate code from metadata
151 const { code, ...meta } = fullSnippet
152
153 // Write snippet files
154 await mkdir(snippetDir, { recursive: true })
155 await Promise.all([
156 writeFile(metaPath, JSON.stringify(meta, null, 2)),
157 writeFile(codePath, code),
158 ])
159
160 // Update index
161 const index = await loadIndex()
162 const indexEntry: SnippetIndexEntry = {
163 id: fullSnippet.id,
164 name: fullSnippet.name,
165 description: fullSnippet.description,
166 usageHints: fullSnippet.usageHints,
167 trustLevel: fullSnippet.trustLevel,
168 }
169
170 const existingIdx = index.findIndex((s) => s.name === snippet.name)
171 if (existingIdx >= 0) {
172 index[existingIdx] = indexEntry
173 } else {
174 index.push(indexEntry)
175 }
176 await saveIndex(index)
177
178 return fullSnippet
179 }
180
181 async function deleteSnippet(name: string): Promise<boolean> {
182 assertSafeSnippetName(name)
183
184 const snippetDir = join(directory, name)
185
186 if (!existsSync(snippetDir)) {
187 return false
188 }
189
190 await rm(snippetDir, { recursive: true })
191
192 // Update index
193 const index = await loadIndex()
194 const filtered = index.filter((s) => s.name !== name)
195 await saveIndex(filtered)
196
197 return true
198 }
199
200 async function search(
201 query: string,
202 searchOptions: SnippetSearchOptions = {},
203 ): Promise<Array<SnippetIndexEntry>> {
204 const { limit = 5 } = searchOptions
205 const index = await loadIndex()
206
207 // Simple text matching - can be replaced with embeddings
208 const queryLower = query.toLowerCase()
209 const terms = queryLower.split(/\s+/)
210
211 const scored = index.map((snippet) => {
212 let score = 0
213 const searchText = [
214 snippet.name,
215 snippet.description,
216 ...snippet.usageHints,
217 ]
218 .join(' ')
219 .toLowerCase()
220
221 for (const term of terms) {
222 if (searchText.includes(term)) {
223 score += 1
224 }
225 // Boost exact name matches
226 if (snippet.name.toLowerCase().includes(term)) {
227 score += 2
228 }
229 }
230
231 return { snippet, score }
232 })
233
234 return scored
235 .filter((s) => s.score > 0)
236 .sort((a, b) => b.score - a.score)
237 .slice(0, limit)
238 .map((s) => s.snippet)
239 }
240
241 async function updateStats(name: string, success: boolean): Promise<void> {
242 const snippet = await get(name)
243 if (!snippet) return
244
245 const { executions, successRate } = snippet.stats
246 const newExecutions = executions + 1
247 const newSuccessRate =
248 (successRate * executions + (success ? 1 : 0)) / newExecutions
249
250 const newStats = { executions: newExecutions, successRate: newSuccessRate }
251
252 // Use trust strategy to calculate new trust level
253 const newTrustLevel = trustStrategy.calculateTrustLevel(
254 snippet.trustLevel,
255 newStats,
256 )
257
258 await save({
259 ...snippet,
260 stats: newStats,
261 trustLevel: newTrustLevel,
262 })
263 }
264
265 return {
266 loadIndex,
267 loadAll,
268 get,
269 save,
270 delete: deleteSnippet,
271 search,
272 updateStats,
273 trustStrategy,
274 }
275}