@aigne/afs-sandbox 1.11.0-beta.7 → 1.11.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +15 -109
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +15 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AFSAccessMode, AFSDeleteResult, AFSEntry, AFSExecResult, AFSExplainResult, AFSListResult, AFSModuleLoadParams, AFSRoot, AFSStatResult, AFSWriteEntryPayload, AFSWriteResult } from "@aigne/afs";
|
|
1
|
+
import { AFSAccessMode, AFSDeleteResult, AFSEntry, AFSExecResult, AFSExplainResult, AFSListResult, AFSModuleLoadParams, AFSRoot, AFSStatResult, AFSWriteEntryPayload, AFSWriteResult, ProviderManifest } from "@aigne/afs";
|
|
2
2
|
import { AFSBaseProvider, RouteContext } from "@aigne/afs/provider";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
|
|
@@ -246,128 +246,34 @@ declare class AFSSandbox extends AFSBaseProvider {
|
|
|
246
246
|
static schema(): z.ZodObject<{
|
|
247
247
|
name: z.ZodOptional<z.ZodString>;
|
|
248
248
|
description: z.ZodOptional<z.ZodString>;
|
|
249
|
-
accessMode: z.ZodOptional<z.ZodEnum<
|
|
249
|
+
accessMode: z.ZodOptional<z.ZodEnum<{
|
|
250
|
+
readonly: "readonly";
|
|
251
|
+
readwrite: "readwrite";
|
|
252
|
+
}>>;
|
|
250
253
|
runtime: z.ZodOptional<z.ZodObject<{
|
|
251
254
|
timeout: z.ZodOptional<z.ZodNumber>;
|
|
252
255
|
memoryLimit: z.ZodOptional<z.ZodNumber>;
|
|
253
|
-
},
|
|
254
|
-
timeout?: number | undefined;
|
|
255
|
-
memoryLimit?: number | undefined;
|
|
256
|
-
}, {
|
|
257
|
-
timeout?: number | undefined;
|
|
258
|
-
memoryLimit?: number | undefined;
|
|
259
|
-
}>>;
|
|
256
|
+
}, z.core.$strip>>;
|
|
260
257
|
capabilities: z.ZodOptional<z.ZodObject<{
|
|
261
258
|
afs: z.ZodOptional<z.ZodObject<{
|
|
262
259
|
read: z.ZodOptional<z.ZodBoolean>;
|
|
263
260
|
write: z.ZodOptional<z.ZodBoolean>;
|
|
264
|
-
allowPaths: z.ZodOptional<z.ZodArray<z.ZodString
|
|
265
|
-
denyPaths: z.ZodOptional<z.ZodArray<z.ZodString
|
|
266
|
-
},
|
|
267
|
-
|
|
268
|
-
write?: boolean | undefined;
|
|
269
|
-
allowPaths?: string[] | undefined;
|
|
270
|
-
denyPaths?: string[] | undefined;
|
|
271
|
-
}, {
|
|
272
|
-
read?: boolean | undefined;
|
|
273
|
-
write?: boolean | undefined;
|
|
274
|
-
allowPaths?: string[] | undefined;
|
|
275
|
-
denyPaths?: string[] | undefined;
|
|
276
|
-
}>>;
|
|
277
|
-
}, "strip", z.ZodTypeAny, {
|
|
278
|
-
afs?: {
|
|
279
|
-
read?: boolean | undefined;
|
|
280
|
-
write?: boolean | undefined;
|
|
281
|
-
allowPaths?: string[] | undefined;
|
|
282
|
-
denyPaths?: string[] | undefined;
|
|
283
|
-
} | undefined;
|
|
284
|
-
}, {
|
|
285
|
-
afs?: {
|
|
286
|
-
read?: boolean | undefined;
|
|
287
|
-
write?: boolean | undefined;
|
|
288
|
-
allowPaths?: string[] | undefined;
|
|
289
|
-
denyPaths?: string[] | undefined;
|
|
290
|
-
} | undefined;
|
|
291
|
-
}>>;
|
|
261
|
+
allowPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
262
|
+
denyPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
263
|
+
}, z.core.$strip>>;
|
|
264
|
+
}, z.core.$strip>>;
|
|
292
265
|
audit: z.ZodOptional<z.ZodObject<{
|
|
293
266
|
enabled: z.ZodBoolean;
|
|
294
|
-
onEvent: z.ZodOptional<z.
|
|
267
|
+
onEvent: z.ZodOptional<z.ZodAny>;
|
|
295
268
|
maxEntries: z.ZodOptional<z.ZodNumber>;
|
|
296
|
-
},
|
|
297
|
-
enabled: boolean;
|
|
298
|
-
onEvent?: ((...args: unknown[]) => unknown) | undefined;
|
|
299
|
-
maxEntries?: number | undefined;
|
|
300
|
-
}, {
|
|
301
|
-
enabled: boolean;
|
|
302
|
-
onEvent?: ((...args: unknown[]) => unknown) | undefined;
|
|
303
|
-
maxEntries?: number | undefined;
|
|
304
|
-
}>>;
|
|
269
|
+
}, z.core.$strip>>;
|
|
305
270
|
rateLimit: z.ZodOptional<z.ZodObject<{
|
|
306
271
|
maxExecutionsPerMinute: z.ZodOptional<z.ZodNumber>;
|
|
307
272
|
maxExecutionsPerMinutePerUser: z.ZodOptional<z.ZodNumber>;
|
|
308
273
|
maxExecutionsPerMinutePerScript: z.ZodOptional<z.ZodNumber>;
|
|
309
|
-
},
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
maxExecutionsPerMinutePerScript?: number | undefined;
|
|
313
|
-
}, {
|
|
314
|
-
maxExecutionsPerMinute?: number | undefined;
|
|
315
|
-
maxExecutionsPerMinutePerUser?: number | undefined;
|
|
316
|
-
maxExecutionsPerMinutePerScript?: number | undefined;
|
|
317
|
-
}>>;
|
|
318
|
-
}, "strip", z.ZodTypeAny, {
|
|
319
|
-
name?: string | undefined;
|
|
320
|
-
description?: string | undefined;
|
|
321
|
-
accessMode?: "readonly" | "readwrite" | undefined;
|
|
322
|
-
runtime?: {
|
|
323
|
-
timeout?: number | undefined;
|
|
324
|
-
memoryLimit?: number | undefined;
|
|
325
|
-
} | undefined;
|
|
326
|
-
capabilities?: {
|
|
327
|
-
afs?: {
|
|
328
|
-
read?: boolean | undefined;
|
|
329
|
-
write?: boolean | undefined;
|
|
330
|
-
allowPaths?: string[] | undefined;
|
|
331
|
-
denyPaths?: string[] | undefined;
|
|
332
|
-
} | undefined;
|
|
333
|
-
} | undefined;
|
|
334
|
-
audit?: {
|
|
335
|
-
enabled: boolean;
|
|
336
|
-
onEvent?: ((...args: unknown[]) => unknown) | undefined;
|
|
337
|
-
maxEntries?: number | undefined;
|
|
338
|
-
} | undefined;
|
|
339
|
-
rateLimit?: {
|
|
340
|
-
maxExecutionsPerMinute?: number | undefined;
|
|
341
|
-
maxExecutionsPerMinutePerUser?: number | undefined;
|
|
342
|
-
maxExecutionsPerMinutePerScript?: number | undefined;
|
|
343
|
-
} | undefined;
|
|
344
|
-
}, {
|
|
345
|
-
name?: string | undefined;
|
|
346
|
-
description?: string | undefined;
|
|
347
|
-
accessMode?: "readonly" | "readwrite" | undefined;
|
|
348
|
-
runtime?: {
|
|
349
|
-
timeout?: number | undefined;
|
|
350
|
-
memoryLimit?: number | undefined;
|
|
351
|
-
} | undefined;
|
|
352
|
-
capabilities?: {
|
|
353
|
-
afs?: {
|
|
354
|
-
read?: boolean | undefined;
|
|
355
|
-
write?: boolean | undefined;
|
|
356
|
-
allowPaths?: string[] | undefined;
|
|
357
|
-
denyPaths?: string[] | undefined;
|
|
358
|
-
} | undefined;
|
|
359
|
-
} | undefined;
|
|
360
|
-
audit?: {
|
|
361
|
-
enabled: boolean;
|
|
362
|
-
onEvent?: ((...args: unknown[]) => unknown) | undefined;
|
|
363
|
-
maxEntries?: number | undefined;
|
|
364
|
-
} | undefined;
|
|
365
|
-
rateLimit?: {
|
|
366
|
-
maxExecutionsPerMinute?: number | undefined;
|
|
367
|
-
maxExecutionsPerMinutePerUser?: number | undefined;
|
|
368
|
-
maxExecutionsPerMinutePerScript?: number | undefined;
|
|
369
|
-
} | undefined;
|
|
370
|
-
}>;
|
|
274
|
+
}, z.core.$strip>>;
|
|
275
|
+
}, z.core.$strip>;
|
|
276
|
+
static manifest(): ProviderManifest;
|
|
371
277
|
/**
|
|
372
278
|
* Loads a module instance from configuration
|
|
373
279
|
*/
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types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OAAA,CAAQ,aAAA;EAvT9D;;;EAyUL,cAAA,CAAe,IAAA,EAAM,YAAA,GAAe,OAAA,CAAQ,aAAA;EA7PvC;;;EA2QL,YAAA,CAAa,IAAA,EAAM,YAAA,GAAe,OAAA,CAAQ,aAAA;EAjQe;;;EAiRzD,WAAA,CAAY,IAAA,EAAM,YAAA,GAAe,OAAA,CAAQ,gBAAA;EAxPxC;;;EAiTD,aAAA,CAAc,GAAA,EAAK,YAAA;IAAe,UAAA;EAAA,KAAwB,OAAA,CAAQ,gBAAA;EA7M7D;;;EAqPL,gBAAA,CAAiB,IAAA,EAAM,YAAA,GAAe,OAAA,CAAQ,QAAA;EA1OzC;;;EAAA,QAgSH,gBAAA;EArR4B;;;EAAA,QA4S5B,0BAAA;EAxQc;;;EAAA,QAoRd,4BAAA;EAxP4C;;;EAAA,QAwQ5C,0BAAA;EA1PyD;;;EAAA,QA0QzD,wBAAA;EA1OiB;;;EAAA,QAsPjB,QAAA;EAtOuC;;;EAAA,QAgQvC,cAAA;EAvMwD;;;EAAA,QAkPxD,eAAA;EAt3CsB;;;EAAA,QA04CtB,aAAA;EAz4CU;;;EAAA,QAy7CV,iBAAA;EAr7CS;;;EAAA,QA48CT,aAAA;EAt8CS;;;EAAA,QAi9CH,aAAA;AAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -343,7 +343,7 @@ const afsSandboxOptionsSchema = z.object({
|
|
|
343
343
|
}).optional().describe("AFS access configuration") }).optional().describe("Capabilities configuration"),
|
|
344
344
|
audit: z.object({
|
|
345
345
|
enabled: z.boolean().describe("Enable audit logging"),
|
|
346
|
-
onEvent: z.
|
|
346
|
+
onEvent: z.any().optional(),
|
|
347
347
|
maxEntries: z.number().positive().optional().describe("Max audit entries to keep")
|
|
348
348
|
}).optional().describe("Audit configuration"),
|
|
349
349
|
rateLimit: z.object({
|
|
@@ -501,6 +501,20 @@ var AFSSandbox = class AFSSandbox extends AFSBaseProvider {
|
|
|
501
501
|
static schema() {
|
|
502
502
|
return afsSandboxOptionsSchema;
|
|
503
503
|
}
|
|
504
|
+
static manifest() {
|
|
505
|
+
return {
|
|
506
|
+
name: "sandbox",
|
|
507
|
+
description: "Sandboxed JavaScript execution environment for LLM-generated code",
|
|
508
|
+
uriTemplate: "sandbox://",
|
|
509
|
+
category: "compute",
|
|
510
|
+
schema: z.object({}),
|
|
511
|
+
tags: [
|
|
512
|
+
"sandbox",
|
|
513
|
+
"compute",
|
|
514
|
+
"javascript"
|
|
515
|
+
]
|
|
516
|
+
};
|
|
517
|
+
}
|
|
504
518
|
/**
|
|
505
519
|
* Loads a module instance from configuration
|
|
506
520
|
*/
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["result","storedScript","promotedAction"],"sources":["../src/capabilities/index.ts","../src/runtime/isolate.ts","../src/index.ts"],"sourcesContent":["import type { AFSRoot } from \"@aigne/afs\";\nimport type { CapabilitiesConfig } from \"../types.js\";\n\n/**\n * Capability functions that can be called from within the sandbox.\n * These are injected as `afs.*` methods.\n */\nexport type CapabilityFunctions = Record<string, (...args: unknown[]) => Promise<unknown>>;\n\n/**\n * Check if a path matches any patterns in the list.\n */\nfunction pathMatchesPatterns(path: string, patterns: string[]): boolean {\n for (const pattern of patterns) {\n // Simple glob-like matching\n if (pattern === \"*\" || pattern === \"**\") return true;\n if (pattern.endsWith(\"/**\") && path.startsWith(pattern.slice(0, -3))) {\n return true;\n }\n if (pattern.endsWith(\"/*\") && path.startsWith(pattern.slice(0, -2))) {\n // Only match direct children\n const rest = path.slice(pattern.length - 2);\n if (!rest.includes(\"/\") || rest === \"\") return true;\n }\n if (path === pattern) return true;\n if (path.startsWith(`${pattern}/`)) return true;\n }\n return false;\n}\n\n/**\n * Check if a path is allowed based on allow/deny patterns.\n */\nfunction isPathAllowed(path: string, allowPaths?: string[], denyPaths?: string[]): boolean {\n // If deny patterns exist and path matches, deny\n if (denyPaths && denyPaths.length > 0 && pathMatchesPatterns(path, denyPaths)) {\n return false;\n }\n\n // If allow patterns exist, path must match\n if (allowPaths && allowPaths.length > 0) {\n return pathMatchesPatterns(path, allowPaths);\n }\n\n // No restrictions, allow\n return true;\n}\n\n/**\n * Normalize and validate a path for security.\n * Checks for path traversal attacks, null bytes, etc.\n */\nfunction normalizePath(path: string): string {\n // Check for null bytes\n if (path.includes(\"\\x00\")) {\n throw new Error(\"Invalid path: null byte detected\");\n }\n\n // URL decode the path to catch encoded attacks\n let decoded = path;\n try {\n decoded = decodeURIComponent(path);\n } catch {\n // If decoding fails, use original\n }\n\n // Check for path traversal after decoding\n if (decoded.includes(\"..\")) {\n throw new Error(\"Path traversal not allowed\");\n }\n\n // Check for control characters (ASCII 0-31 and 127)\n for (const char of decoded) {\n const code = char.charCodeAt(0);\n if (code < 32 || code === 127) {\n throw new Error(\"Invalid path: control characters detected\");\n }\n }\n\n return decoded;\n}\n\n/**\n * Create capability functions based on configuration.\n *\n * @param afs - The AFS root for filesystem operations\n * @param config - Capabilities configuration\n * @returns Record of capability functions to inject into sandbox\n */\nexport function createCapabilities(\n afs: AFSRoot | undefined,\n config: CapabilitiesConfig,\n): CapabilityFunctions {\n const capabilities: CapabilityFunctions = {};\n\n // AFS read capability\n if (afs?.read && config.afs?.read !== false) {\n const afsRead = afs.read.bind(afs);\n capabilities.read = async (path: unknown): Promise<string | null> => {\n if (typeof path !== \"string\") {\n throw new Error(\"afs.read: path must be a string\");\n }\n\n // Check path permissions\n if (!isPathAllowed(path, config.afs?.allowPaths, config.afs?.denyPaths)) {\n throw new Error(`afs.read: access denied to path \"${path}\"`);\n }\n\n try {\n const result = await afsRead(path);\n if (!result.data) {\n return null;\n }\n\n // Return content as string\n const content = result.data.content;\n if (content === undefined || content === null) {\n return null;\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n // For non-string content, serialize to JSON\n return JSON.stringify(content);\n } catch (error) {\n throw new Error(\n `afs.read: failed to read \"${path}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n };\n }\n\n // AFS write capability (Phase 2)\n if (afs?.write && config.afs?.write === true) {\n const afsWrite = afs.write.bind(afs);\n capabilities.write = async (\n path: unknown,\n content: unknown,\n ): Promise<{ success: boolean; path: string }> => {\n // Validate path\n if (path === undefined || path === null) {\n throw new Error(\"afs.write: path is required\");\n }\n if (typeof path !== \"string\") {\n throw new Error(\"afs.write: path must be a string\");\n }\n\n // Validate content\n if (typeof content !== \"string\") {\n throw new Error(\"afs.write: content must be a string\");\n }\n if (content === \"\") {\n throw new Error(\"afs.write: content cannot be empty\");\n }\n\n // Normalize and check for path traversal attacks\n let normalizedPath: string;\n try {\n normalizedPath = normalizePath(path);\n } catch (error) {\n throw new Error(`afs.write: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n // Check path permissions\n if (!isPathAllowed(normalizedPath, config.afs?.allowPaths, config.afs?.denyPaths)) {\n throw new Error(`afs.write: access denied to path \"${path}\"`);\n }\n\n try {\n await afsWrite(normalizedPath, { content });\n return { success: true, path: normalizedPath };\n } catch (error) {\n throw new Error(\n `afs.write: failed to write \"${path}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n };\n } else {\n // Provide a stub that throws when write is disabled\n capabilities.write = async (): Promise<never> => {\n throw new Error(\"afs.write: write capability not enabled\");\n };\n }\n\n // AFS list capability (useful for Phase 2, but add basic support now)\n if (afs?.list && config.afs?.read !== false) {\n const afsList = afs.list.bind(afs);\n capabilities.list = async (\n path: unknown,\n options?: unknown,\n ): Promise<{ path: string; type: string }[]> => {\n if (typeof path !== \"string\") {\n throw new Error(\"afs.list: path must be a string\");\n }\n\n // Check path permissions\n if (!isPathAllowed(path, config.afs?.allowPaths, config.afs?.denyPaths)) {\n throw new Error(`afs.list: access denied to path \"${path}\"`);\n }\n\n try {\n const listOptions = typeof options === \"object\" && options !== null ? options : {};\n const result = await afsList(path, listOptions as Record<string, unknown>);\n\n // Return simplified entry info\n return result.data.map((entry) => ({\n path: entry.path,\n type: (entry.meta?.type as string | undefined) ?? \"unknown\",\n }));\n } catch (error) {\n throw new Error(\n `afs.list: failed to list \"${path}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n };\n }\n\n return capabilities;\n}\n","import { getQuickJS } from \"quickjs-emscripten\";\nimport type {\n ExecutionContext,\n ExecutionResult,\n LogEntry,\n LogLevel,\n RuntimeOptions,\n} from \"../types.js\";\n\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst DEFAULT_MEMORY_LIMIT_MB = 128;\n\n/**\n * Sandbox runtime using QuickJS (WebAssembly) for secure JavaScript execution.\n *\n * Provides sandboxed execution with:\n * - Memory limits\n * - CPU time limits (timeout via interrupt)\n * - Capability injection for controlled AFS access\n *\n * Note: Async/await in sandbox code is limited. Capability functions return\n * Promises that can be used for type checking, but full async execution\n * requires calling capabilities synchronously for now.\n */\nexport class SandboxRuntime {\n private readonly timeout: number;\n private readonly memoryLimit: number;\n\n constructor(options: RuntimeOptions = {}) {\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n this.memoryLimit = options.memoryLimit ?? DEFAULT_MEMORY_LIMIT_MB;\n }\n\n /**\n * Execute JavaScript code in an isolated QuickJS sandbox.\n *\n * @param code - JavaScript source code to execute\n * @param capabilities - Capability functions to inject into sandbox\n * @param context - Execution context with args and tracking info\n * @returns Execution result with success status, return value, errors, and logs\n */\n async execute(\n code: string,\n capabilities: Record<string, (...args: unknown[]) => Promise<unknown>>,\n context: ExecutionContext = {},\n ): Promise<ExecutionResult> {\n const logs: LogEntry[] = [];\n const startTime = Date.now();\n\n // Get QuickJS instance\n const QuickJS = await getQuickJS();\n\n // Create runtime with memory limit\n const runtime = QuickJS.newRuntime();\n runtime.setMemoryLimit(this.memoryLimit * 1024 * 1024);\n\n // Set up interrupt handler for timeout\n let timedOut = false;\n const deadline = Date.now() + this.timeout;\n runtime.setInterruptHandler(() => {\n if (Date.now() > deadline) {\n timedOut = true;\n return true; // Interrupt execution\n }\n return false;\n });\n\n // Create context\n const vm = runtime.newContext();\n\n try {\n // Inject logging function\n const logFn = vm.newFunction(\"log\", (levelHandle, messageHandle) => {\n const level = vm.getString(levelHandle) as LogLevel;\n const message = vm.getString(messageHandle);\n logs.push({\n level,\n message,\n timestamp: Date.now(),\n });\n });\n vm.setProp(vm.global, \"__log\", logFn);\n logFn.dispose();\n\n // Inject args\n const argsJson = JSON.stringify(context.args ?? {});\n vm.evalCode(`const __args = ${argsJson};`);\n\n // Inject context object (timestamp, executionId, userId, sessionId)\n const contextObj = {\n timestamp: context.timestamp ?? Date.now(),\n executionId: context.executionId ?? `exec-${Date.now()}`,\n userId: context.userId,\n sessionId: context.sessionId,\n };\n const contextJson = JSON.stringify(contextObj);\n vm.evalCode(`const __context = ${contextJson};`);\n\n // Create pending promises tracker for async capabilities\n const pendingPromises: Map<\n number,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n }\n > = new Map();\n let promiseId = 0;\n\n // Inject capability functions\n for (const [name, fn] of Object.entries(capabilities)) {\n // Create a sync function that returns a promise ID\n const capFn = vm.newFunction(`__cap_${name}`, (...argHandles) => {\n const args = argHandles.map((h) => {\n const type = vm.typeof(h);\n if (type === \"string\") return vm.getString(h);\n if (type === \"number\") return vm.getNumber(h);\n if (type === \"boolean\") return vm.dump(h);\n if (type === \"object\" || type === \"undefined\") return vm.dump(h);\n return vm.dump(h);\n });\n\n // Store the promise for later resolution\n const id = promiseId++;\n\n // Execute the capability async\n fn(...args)\n .then((result) => {\n pendingPromises.get(id)?.resolve(result);\n pendingPromises.delete(id);\n })\n .catch((error) => {\n pendingPromises\n .get(id)\n ?.reject(error instanceof Error ? error : new Error(String(error)));\n pendingPromises.delete(id);\n });\n\n return vm.newNumber(id);\n });\n vm.setProp(vm.global, `__cap_${name}`, capFn);\n capFn.dispose();\n }\n\n // Build the afs object and wrapper code\n const capabilitySetups = Object.keys(capabilities)\n .map(\n (name) => `\n ${name}: function(...args) {\n return new Promise((resolve, reject) => {\n const id = __cap_${name}(...args);\n __pendingResolvers[id] = { resolve, reject };\n });\n }`,\n )\n .join(\",\\n\");\n\n const wrapperCode = `\n(function() {\n // Pending promise resolvers\n const __pendingResolvers = {};\n globalThis.__pendingResolvers = __pendingResolvers;\n\n // Set up afs object with logging and capabilities\n const afs = {\n log: function(level, message) {\n __log(String(level), String(message));\n },\n ${capabilitySetups}\n };\n\n // Get arguments and context\n const args = __args;\n const context = Object.freeze(__context);\n\n // User code\n ${code}\n})();\n`;\n\n // Execute the code\n const result = vm.evalCode(wrapperCode);\n\n if (timedOut) {\n result.dispose();\n return {\n success: false,\n error: `Script execution timed out after ${this.timeout}ms`,\n logs,\n duration: Date.now() - startTime,\n timedOut: true,\n };\n }\n\n if (result.error) {\n const errorValue = vm.dump(result.error);\n result.error.dispose();\n\n const errorMessage =\n typeof errorValue === \"object\" && errorValue !== null\n ? ((errorValue as { message?: string }).message ?? String(errorValue))\n : String(errorValue);\n\n return {\n success: false,\n error: errorMessage,\n stack:\n typeof errorValue === \"object\" && errorValue !== null\n ? (errorValue as { stack?: string }).stack\n : undefined,\n logs,\n duration: Date.now() - startTime,\n };\n }\n\n // Get the result value\n const resultValue = vm.dump(result.value);\n result.value.dispose();\n\n return {\n success: true,\n result: resultValue,\n logs,\n duration: Date.now() - startTime,\n timedOut: false,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n return {\n success: false,\n error: errorMessage,\n stack,\n logs,\n duration: Date.now() - startTime,\n };\n } finally {\n // Cleanup\n vm.dispose();\n runtime.dispose();\n }\n }\n}\n","import {\n type AFSAccessMode,\n type AFSDeleteResult,\n type AFSEntry,\n type AFSExecResult,\n type AFSExplainResult,\n type AFSListResult,\n type AFSModuleClass,\n type AFSModuleLoadParams,\n AFSNotFoundError,\n type AFSRoot,\n type AFSStatResult,\n type AFSWriteEntryPayload,\n type AFSWriteResult,\n type CapabilitiesManifest,\n} from \"@aigne/afs\";\nimport {\n Actions,\n AFSBaseProvider,\n Delete,\n Exec,\n Explain,\n List,\n Meta,\n Read,\n type RouteContext,\n Stat,\n Write,\n} from \"@aigne/afs/provider\";\nimport { joinURL } from \"ufo\";\nimport { z } from \"zod\";\nimport { type CapabilityFunctions, createCapabilities } from \"./capabilities/index.js\";\nimport { SandboxRuntime } from \"./runtime/isolate.js\";\nimport type {\n AFSSandboxOptions,\n AuditConfig,\n AuditEvent,\n ExecutionContext,\n ExecutionHistoryEntry,\n ExecutionMetrics,\n ExecutionResult,\n PromotedAction,\n RateLimitConfig,\n ScriptMetadata,\n ScriptTemplate,\n ScriptVersion,\n StoredScript,\n} from \"./types.js\";\n\nexport type {\n AFSSandboxOptions,\n AuditConfig,\n AuditEvent,\n AuditEventType,\n ExecutionMetrics,\n ExecutionResult,\n LogEntry,\n LogLevel,\n PromotedAction,\n RateLimitConfig,\n ScriptTemplate,\n} from \"./types.js\";\n\n/** Maximum number of versions to keep per script */\nconst MAX_VERSIONS = 5;\n/** Maximum number of execution history entries per script */\nconst MAX_EXEC_HISTORY = 100;\n/** Sensitive fields to redact from execution history */\nconst SENSITIVE_FIELDS = [\"password\", \"secret\", \"token\", \"key\", \"credential\", \"auth\"];\n\n/**\n * Generate a unique execution ID\n */\nfunction generateExecutionId(): string {\n return `exec-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Sanitize args by redacting sensitive fields\n */\nfunction sanitizeArgs(args: Record<string, unknown>): Record<string, unknown> {\n const sanitized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (SENSITIVE_FIELDS.some((f) => key.toLowerCase().includes(f))) {\n sanitized[key] = \"[REDACTED]\";\n } else if (typeof value === \"object\" && value !== null) {\n sanitized[key] = sanitizeArgs(value as Record<string, unknown>);\n } else {\n sanitized[key] = value;\n }\n }\n return sanitized;\n}\n\n/**\n * Zod schema for configuration validation\n */\nconst afsSandboxOptionsSchema = z.object({\n name: z.string().optional().describe(\"Module name\"),\n description: z.string().optional().describe(\"Module description\"),\n accessMode: z.enum([\"readonly\", \"readwrite\"]).optional().describe(\"Access mode for this module\"),\n runtime: z\n .object({\n timeout: z.number().positive().optional().describe(\"Execution timeout in milliseconds\"),\n memoryLimit: z.number().positive().optional().describe(\"Memory limit in MB\"),\n })\n .optional()\n .describe(\"Runtime configuration\"),\n capabilities: z\n .object({\n afs: z\n .object({\n read: z.boolean().optional().describe(\"Enable read operations\"),\n write: z.boolean().optional().describe(\"Enable write operations\"),\n allowPaths: z.array(z.string()).optional().describe(\"Allowed path patterns\"),\n denyPaths: z.array(z.string()).optional().describe(\"Denied path patterns\"),\n })\n .optional()\n .describe(\"AFS access configuration\"),\n })\n .optional()\n .describe(\"Capabilities configuration\"),\n audit: z\n .object({\n enabled: z.boolean().describe(\"Enable audit logging\"),\n onEvent: z.function().optional().describe(\"Callback for audit events\"),\n maxEntries: z.number().positive().optional().describe(\"Max audit entries to keep\"),\n })\n .optional()\n .describe(\"Audit configuration\"),\n rateLimit: z\n .object({\n maxExecutionsPerMinute: z.number().positive().optional(),\n maxExecutionsPerMinutePerUser: z.number().positive().optional(),\n maxExecutionsPerMinutePerScript: z.number().positive().optional(),\n })\n .optional()\n .describe(\"Rate limiting configuration\"),\n});\n\n/** Reserved action names that cannot be used for promoted actions */\nconst RESERVED_ACTION_NAMES = [\"run\", \"validate\", \"rollback\", \"promote\", \"create-from-template\"];\n\n/** Built-in script templates */\nconst BUILT_IN_TEMPLATES: ScriptTemplate[] = [\n {\n name: \"basic\",\n description: \"A basic script template\",\n content: `// Basic script template\nreturn args.input;`,\n category: \"general\",\n },\n {\n name: \"data-transform\",\n description: \"Transform input data to output format\",\n content: `// Data transformation script\nconst {{inputField}} = args.{{inputField}};\nconst {{outputField}} = {{inputField}};\nreturn { {{outputField}} };`,\n variables: [\n { name: \"inputField\", description: \"Name of the input field\", required: true },\n { name: \"outputField\", description: \"Name of the output field\", required: true },\n ],\n category: \"data\",\n },\n {\n name: \"validation\",\n description: \"Validate input data against rules\",\n content: `// Validation script\nconst value = args.{{fieldName}};\nconst errors = [];\n\nif (value === undefined || value === null) {\n errors.push('{{fieldName}} is required');\n}\n\nreturn { valid: errors.length === 0, errors };`,\n variables: [\n { name: \"fieldName\", description: \"Name of the field to validate\", required: true },\n ],\n category: \"validation\",\n },\n {\n name: \"aggregation\",\n description: \"Aggregate array data\",\n content: `// Aggregation script\nconst items = args.items || [];\nconst sum = items.reduce((acc, item) => acc + (item.{{valueField}} || 0), 0);\nconst count = items.length;\nconst average = count > 0 ? sum / count : 0;\n\nreturn { sum, count, average };`,\n variables: [\n { name: \"valueField\", description: \"Field to aggregate\", required: true, default: \"value\" },\n ],\n category: \"data\",\n },\n];\n\n/**\n * AFS Sandbox Provider\n *\n * Provides a sandboxed JavaScript execution environment for LLM-generated code.\n * Scripts are stored at `/scripts/{name}.js` and executed directly via exec().\n *\n * Structure:\n * - `/` - root directory\n * - `/scripts` - stored scripts directory\n * - `/scripts/{name}.js` - individual script files (executable)\n * - `/templates` - script templates\n * - `/templates/{name}` - individual templates\n * - `/metrics` - execution metrics\n * - `/audit` - audit log\n * - `/.actions` - root-level actions (run, validate, promote, create-from-template)\n * - `/scripts/{name}.js/.actions` - script-level actions (exec, history, exec-history)\n *\n * @example\n * ```typescript\n * const sandbox = new AFSSandbox({ name: \"sandbox\" });\n * afs.mount(sandbox);\n *\n * // Write a script\n * await afs.write(\"/modules/sandbox/scripts/greet.js\", {\n * content: `\n * afs.log(\"info\", \"Hello from sandbox!\");\n * return \"Hello, \" + args.name;\n * `\n * });\n *\n * // Execute the script\n * const result = await afs.exec(\"/modules/sandbox/scripts/greet.js\", { name: \"World\" });\n * // result.data = { success: true, result: \"Hello, World\", logs: [...] }\n * ```\n */\nexport class AFSSandbox extends AFSBaseProvider {\n override readonly name: string;\n override readonly description?: string;\n override readonly accessMode: AFSAccessMode;\n\n private readonly runtime: SandboxRuntime;\n private readonly options: AFSSandboxOptions;\n private readonly scripts: Map<string, StoredScript> = new Map();\n private capabilities: CapabilityFunctions = {};\n\n // Promoted actions storage\n private readonly promotedActions: Map<string, PromotedAction> = new Map();\n\n // Audit logging\n private readonly auditLog: AuditEvent[] = [];\n private readonly auditConfig?: AuditConfig;\n\n // Rate limiting\n private readonly rateLimitConfig?: RateLimitConfig;\n private readonly executionTimestamps: number[] = [];\n private readonly userExecutionTimestamps: Map<string, number[]> = new Map();\n private readonly scriptExecutionTimestamps: Map<string, number[]> = new Map();\n\n // Metrics\n private metrics: ExecutionMetrics = {\n totalExecutions: 0,\n successCount: 0,\n failureCount: 0,\n timeoutCount: 0,\n averageDuration: 0,\n totalDuration: 0,\n };\n private readonly scriptMetrics: Map<string, ExecutionMetrics> = new Map();\n\n constructor(options: AFSSandboxOptions = {}) {\n super();\n this.options = afsSandboxOptionsSchema.parse(options);\n this.name = options.name ?? \"sandbox\";\n this.description = options.description ?? \"JavaScript sandbox for LLM code execution\";\n this.accessMode = options.accessMode ?? \"readwrite\";\n this.runtime = new SandboxRuntime(options.runtime);\n this.auditConfig = options.audit;\n this.rateLimitConfig = options.rateLimit;\n // Initialize capabilities with undefined AFS (stubs only)\n this.capabilities = createCapabilities(undefined, this.options.capabilities ?? {});\n }\n\n /**\n * Returns the Zod schema for configuration validation\n */\n static schema() {\n return afsSandboxOptionsSchema;\n }\n\n /**\n * Loads a module instance from configuration\n */\n static async load({ config }: AFSModuleLoadParams = {}): Promise<AFSSandbox> {\n const validated = afsSandboxOptionsSchema.parse(config);\n return new AFSSandbox(validated);\n }\n\n /**\n * Called when the module is mounted to AFS\n */\n onMount(afs: AFSRoot): void {\n this.capabilities = createCapabilities(afs, this.options.capabilities ?? {});\n }\n\n // ========== List Handlers ==========\n\n /**\n * List root directory children\n */\n @List(\"/\")\n async listRoot(_ctx: RouteContext): Promise<AFSListResult> {\n return {\n data: [\n this.buildScriptsDirectoryEntry(),\n this.buildTemplatesDirectoryEntry(),\n this.buildMetricsDirectoryEntry(),\n this.buildAuditDirectoryEntry(),\n ],\n };\n }\n\n /**\n * List all scripts\n */\n @List(\"/scripts\")\n async listScripts(_ctx: RouteContext): Promise<AFSListResult> {\n const entries: AFSEntry[] = [];\n for (const [name, script] of this.scripts) {\n entries.push(this.buildScriptEntry(name, script));\n }\n return { data: entries };\n }\n\n /**\n * List script children (@history, @execHistory)\n */\n @List(\"/scripts/:scriptName\")\n async listScript(ctx: RouteContext<{ scriptName: string }>): Promise<AFSListResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path);\n }\n const basePath = joinURL(\"/scripts\", ctx.params.scriptName);\n return {\n data: [\n {\n id: joinURL(basePath, \"@history\"),\n path: joinURL(basePath, \"@history\"),\n summary: \"Version history\",\n meta: { kind: \"sandbox:history\", type: \"history\", count: (script.versions ?? []).length },\n },\n {\n id: joinURL(basePath, \"@execHistory\"),\n path: joinURL(basePath, \"@execHistory\"),\n summary: \"Execution history\",\n meta: {\n kind: \"sandbox:exec-history\",\n type: \"execHistory\",\n count: (script.execHistory ?? []).length,\n },\n },\n ],\n };\n }\n\n /**\n * List @history children (leaf node)\n */\n @List(\"/scripts/:scriptName/@history\")\n async listScriptHistory(ctx: RouteContext<{ scriptName: string }>): Promise<AFSListResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n if (!this.scripts.has(name)) {\n throw new AFSNotFoundError(ctx.path);\n }\n return { data: [] };\n }\n\n /**\n * List @execHistory children (leaf node)\n */\n @List(\"/scripts/:scriptName/@execHistory\")\n async listScriptExecHistoryEntries(\n ctx: RouteContext<{ scriptName: string }>,\n ): Promise<AFSListResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n if (!this.scripts.has(name)) {\n throw new AFSNotFoundError(ctx.path);\n }\n return { data: [] };\n }\n\n /**\n * List all templates\n */\n @List(\"/templates\")\n async listTemplates(_ctx: RouteContext): Promise<AFSListResult> {\n const entries = BUILT_IN_TEMPLATES.map((t) => ({\n id: joinURL(\"/templates\", t.name),\n path: joinURL(\"/templates\", t.name),\n summary: t.description,\n meta: {\n kind: \"sandbox:template\",\n type: \"template\",\n category: t.category,\n variables: t.variables,\n },\n }));\n return { data: entries };\n }\n\n /**\n * List template children (leaf node)\n */\n @List(\"/templates/:templateName\")\n async listTemplate(ctx: RouteContext<{ templateName: string }>): Promise<AFSListResult> {\n const template = BUILT_IN_TEMPLATES.find((t) => t.name === ctx.params.templateName);\n if (!template) {\n throw new AFSNotFoundError(ctx.path);\n }\n return { data: [] };\n }\n\n /**\n * List metrics children\n */\n @List(\"/metrics\")\n async listMetrics(_ctx: RouteContext): Promise<AFSListResult> {\n if (this.scriptMetrics.size === 0) {\n return { data: [] };\n }\n return {\n data: [\n {\n id: \"/metrics/scripts\",\n path: \"/metrics/scripts\",\n summary: \"Per-script execution metrics\",\n meta: {\n kind: \"sandbox:directory\",\n type: \"directory\",\n childrenCount: this.scriptMetrics.size,\n },\n },\n ],\n };\n }\n\n /**\n * List per-script metrics\n */\n @List(\"/metrics/scripts\")\n async listScriptMetrics(_ctx: RouteContext): Promise<AFSListResult> {\n const entries: AFSEntry[] = [];\n for (const [name, metrics] of this.scriptMetrics) {\n entries.push({\n id: joinURL(\"/metrics/scripts\", name),\n path: joinURL(\"/metrics/scripts\", name),\n meta: {\n kind: \"sandbox:metrics\",\n type: \"script-metrics\",\n totalExecutions: metrics.totalExecutions,\n },\n });\n }\n return { data: entries };\n }\n\n /**\n * List audit children (leaf node)\n */\n @List(\"/audit\")\n async listAudit(_ctx: RouteContext): Promise<AFSListResult> {\n return { data: [] };\n }\n\n // ========== Actions Listing ==========\n\n /**\n * List root-level actions\n */\n @Actions(\"/\")\n async listRootActions(_ctx: RouteContext): Promise<AFSListResult> {\n const entries: AFSEntry[] = [\n {\n id: \"run\",\n path: \"/.actions/run\",\n summary: \"Run inline JavaScript code\",\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: \"run\",\n description: \"Execute inline JavaScript code\",\n inputSchema: {\n type: \"object\",\n properties: {\n code: { type: \"string\", description: \"JavaScript code to execute\" },\n args: { type: \"object\", description: \"Arguments to pass to the code\" },\n },\n required: [\"code\"],\n },\n },\n },\n {\n id: \"validate\",\n path: \"/.actions/validate\",\n summary: \"Validate JavaScript syntax\",\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: \"validate\",\n description: \"Check JavaScript code for syntax errors\",\n inputSchema: {\n type: \"object\",\n properties: {\n code: { type: \"string\", description: \"JavaScript code to validate\" },\n },\n required: [\"code\"],\n },\n },\n },\n {\n id: \"promote\",\n path: \"/.actions/promote\",\n summary: \"Promote a script to a formal action\",\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: \"promote\",\n description: \"Promote a tested script to a formal action\",\n inputSchema: {\n type: \"object\",\n properties: {\n script: { type: \"string\", description: \"Script name to promote\" },\n name: { type: \"string\", description: \"Action name\" },\n description: { type: \"string\", description: \"Action description\" },\n inputSchema: { type: \"object\", description: \"JSON schema for inputs\" },\n outputSchema: { type: \"object\", description: \"JSON schema for outputs\" },\n },\n required: [\"script\", \"name\"],\n },\n },\n },\n {\n id: \"create-from-template\",\n path: \"/.actions/create-from-template\",\n summary: \"Create a script from a template\",\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: \"create-from-template\",\n description: \"Create a new script from a template\",\n inputSchema: {\n type: \"object\",\n properties: {\n template: { type: \"string\", description: \"Template name\" },\n name: { type: \"string\", description: \"Script name to create\" },\n variables: { type: \"object\", description: \"Template variables\" },\n },\n required: [\"template\", \"name\"],\n },\n },\n },\n ];\n\n // Add promoted actions\n for (const [actionName, action] of this.promotedActions) {\n entries.push({\n id: actionName,\n path: joinURL(\"/.actions\", actionName),\n summary: action.description ?? `Promoted action: ${actionName}`,\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: actionName,\n description: action.description ?? `Execute ${actionName}`,\n inputSchema: action.inputSchema,\n outputSchema: action.outputSchema,\n },\n });\n }\n\n return { data: entries };\n }\n\n /**\n * List script-level actions\n */\n @Actions(\"/scripts/:scriptName\")\n async listScriptActions(ctx: RouteContext<{ scriptName: string }>): Promise<AFSListResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path);\n }\n\n const basePath = joinURL(\"/scripts\", ctx.params.scriptName, \".actions\");\n return {\n data: [\n {\n id: \"exec\",\n path: joinURL(basePath, \"exec\"),\n summary: `Execute script ${name}`,\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: \"exec\",\n description: `Execute the ${name} script`,\n inputSchema: {\n type: \"object\",\n description: \"Arguments passed to the script's default export function\",\n },\n },\n },\n ],\n };\n }\n\n // ========== Read Handlers ==========\n\n /**\n * Read root entry\n */\n @Read(\"/\")\n async readRoot(_ctx: RouteContext): Promise<AFSEntry> {\n const actions = [\n { name: \"run\", description: \"Run inline JavaScript code\" },\n { name: \"validate\", description: \"Validate JavaScript syntax\" },\n { name: \"promote\", description: \"Promote a script to a formal action\" },\n { name: \"create-from-template\", description: \"Create a script from a template\" },\n ...Array.from(this.promotedActions.entries()).map(([name, action]) => ({\n name,\n description: action.description ?? `Promoted action: ${name}`,\n })),\n ];\n return {\n id: \"/\",\n path: \"/\",\n meta: { type: \"directory\", childrenCount: 4 },\n actions,\n };\n }\n\n /**\n * Read scripts directory\n */\n @Read(\"/scripts\")\n async readScriptsDir(_ctx: RouteContext): Promise<AFSEntry> {\n return this.buildScriptsDirectoryEntry();\n }\n\n /**\n * Read a specific script\n */\n @Read(\"/scripts/:scriptName\")\n async readScript(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n return this.buildScriptEntry(name, script);\n }\n\n /**\n * Read version history for a script\n */\n @Read(\"/scripts/:scriptName/@history\")\n async readScriptHistory(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const versions = script.versions ?? [];\n return {\n id: joinURL(\"/scripts\", `${name}.js`, \"@history\"),\n path: joinURL(\"/scripts\", `${name}.js`, \"@history\"),\n content: versions,\n meta: { type: \"history\", count: versions.length },\n };\n }\n\n /**\n * Read a specific version\n */\n @Read(\"/scripts/:scriptName/@history/:version\")\n async readScriptVersion(\n ctx: RouteContext<{ scriptName: string; version: string }>,\n ): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const versionNum = Number.parseInt(ctx.params.version, 10);\n if (Number.isNaN(versionNum) || versionNum < 0) {\n throw new AFSNotFoundError(ctx.path, \"Invalid version number\");\n }\n const versions = script.versions ?? [];\n const version = versions.find((v) => v.version === versionNum);\n if (!version) {\n throw new AFSNotFoundError(ctx.path, `Version ${versionNum} not found`);\n }\n return {\n id: joinURL(\"/scripts\", `${name}.js`, \"@history\", String(versionNum)),\n path: joinURL(\"/scripts\", `${name}.js`, \"@history\", String(versionNum)),\n content: version.content,\n meta: {\n type: \"version\",\n version: version.version,\n timestamp: version.timestamp,\n size: version.size,\n },\n };\n }\n\n /**\n * Read execution history for a script\n */\n @Read(\"/scripts/:scriptName/@execHistory\")\n async readScriptExecHistory(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const execHistory = script.execHistory ?? [];\n return {\n id: joinURL(\"/scripts\", `${name}.js`, \"@execHistory\"),\n path: joinURL(\"/scripts\", `${name}.js`, \"@execHistory\"),\n content: execHistory,\n meta: { type: \"execHistory\", count: execHistory.length },\n };\n }\n\n /**\n * Read templates directory\n */\n @Read(\"/templates\")\n async readTemplatesDir(_ctx: RouteContext): Promise<AFSEntry> {\n return this.buildTemplatesDirectoryEntry();\n }\n\n /**\n * Read a specific template\n */\n @Read(\"/templates/:templateName\")\n async readTemplate(ctx: RouteContext<{ templateName: string }>): Promise<AFSEntry> {\n const template = BUILT_IN_TEMPLATES.find((t) => t.name === ctx.params.templateName);\n if (!template) {\n throw new AFSNotFoundError(ctx.path, `Template not found: ${ctx.params.templateName}`);\n }\n return {\n id: joinURL(\"/templates\", template.name),\n path: joinURL(\"/templates\", template.name),\n content: template.content,\n meta: {\n type: \"template\",\n description: template.description,\n category: template.category,\n variables: template.variables,\n },\n };\n }\n\n /**\n * Read metrics\n */\n @Read(\"/metrics\")\n async readMetrics(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/metrics\",\n path: \"/metrics\",\n content: this.metrics,\n meta: { type: \"metrics\" },\n };\n }\n\n /**\n * Read per-script metrics\n */\n @Read(\"/metrics/scripts/:scriptName\")\n async readScriptMetrics(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const scriptMetrics = this.scriptMetrics.get(ctx.params.scriptName);\n if (!scriptMetrics) {\n throw new AFSNotFoundError(ctx.path, `Script metrics not found: ${ctx.params.scriptName}`);\n }\n return {\n id: joinURL(\"/metrics/scripts\", ctx.params.scriptName),\n path: joinURL(\"/metrics/scripts\", ctx.params.scriptName),\n content: { executionCount: scriptMetrics.totalExecutions, ...scriptMetrics },\n meta: { type: \"script-metrics\", scriptName: ctx.params.scriptName },\n };\n }\n\n /**\n * Read audit log\n */\n @Read(\"/audit\")\n async readAudit(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/audit\",\n path: \"/audit\",\n content: this.auditLog,\n meta: { type: \"audit\", count: this.auditLog.length },\n };\n }\n\n // ========== Meta Handlers ==========\n\n /**\n * Root metadata\n */\n @Meta(\"/\")\n async readRootMeta(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/.meta\",\n path: \"/.meta\",\n content: { type: \"directory\", childrenCount: 4 },\n meta: { type: \"directory\", childrenCount: 4 },\n };\n }\n\n /**\n * Scripts directory metadata\n */\n @Meta(\"/scripts\")\n async readScriptsMeta(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/scripts/.meta\",\n path: \"/scripts/.meta\",\n content: { type: \"directory\", childrenCount: this.scripts.size },\n meta: { type: \"directory\", childrenCount: this.scripts.size },\n };\n }\n\n /**\n * Script metadata\n */\n @Meta(\"/scripts/:scriptName\")\n async readScriptMeta(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const entry = this.buildScriptEntry(name, script);\n return {\n id: joinURL(\"/scripts\", ctx.params.scriptName, \".meta\"),\n path: joinURL(\"/scripts\", ctx.params.scriptName, \".meta\"),\n content: entry.meta ?? {},\n meta: entry.meta ?? {},\n };\n }\n\n /**\n * @history metadata\n */\n @Meta(\"/scripts/:scriptName/@history\")\n async readScriptHistoryMeta(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const meta = { type: \"history\", count: (script.versions ?? []).length };\n return {\n id: joinURL(\"/scripts\", ctx.params.scriptName, \"@history\", \".meta\"),\n path: joinURL(\"/scripts\", ctx.params.scriptName, \"@history\", \".meta\"),\n content: meta,\n meta,\n };\n }\n\n /**\n * @execHistory metadata\n */\n @Meta(\"/scripts/:scriptName/@execHistory\")\n async readScriptExecHistoryMeta(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const meta = { type: \"execHistory\", count: (script.execHistory ?? []).length };\n return {\n id: joinURL(\"/scripts\", ctx.params.scriptName, \"@execHistory\", \".meta\"),\n path: joinURL(\"/scripts\", ctx.params.scriptName, \"@execHistory\", \".meta\"),\n content: meta,\n meta,\n };\n }\n\n /**\n * Templates directory metadata\n */\n @Meta(\"/templates\")\n async readTemplatesMeta(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/templates/.meta\",\n path: \"/templates/.meta\",\n content: { type: \"directory\", childrenCount: BUILT_IN_TEMPLATES.length },\n meta: { type: \"directory\", childrenCount: BUILT_IN_TEMPLATES.length },\n };\n }\n\n /**\n * Template metadata\n */\n @Meta(\"/templates/:templateName\")\n async readTemplateMeta(ctx: RouteContext<{ templateName: string }>): Promise<AFSEntry> {\n const template = BUILT_IN_TEMPLATES.find((t) => t.name === ctx.params.templateName);\n if (!template) {\n throw new AFSNotFoundError(ctx.path, `Template not found: ${ctx.params.templateName}`);\n }\n const meta = {\n type: \"template\",\n description: template.description,\n category: template.category,\n variables: template.variables,\n };\n return {\n id: joinURL(\"/templates\", ctx.params.templateName, \".meta\"),\n path: joinURL(\"/templates\", ctx.params.templateName, \".meta\"),\n content: meta,\n meta,\n };\n }\n\n /**\n * Metrics metadata\n */\n @Meta(\"/metrics\")\n async readMetricsMeta(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/metrics/.meta\",\n path: \"/metrics/.meta\",\n content: { type: \"metrics\" },\n meta: { type: \"metrics\" },\n };\n }\n\n /**\n * Audit metadata\n */\n @Meta(\"/audit\")\n async readAuditMeta(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/audit/.meta\",\n path: \"/audit/.meta\",\n content: { type: \"audit\", entryCount: this.auditLog.length },\n meta: { type: \"audit\", entryCount: this.auditLog.length },\n };\n }\n\n // ========== Write Handlers ==========\n\n /**\n * Write (create or update) a script\n */\n @Write(\"/scripts/:scriptName\")\n async writeScript(\n ctx: RouteContext<{ scriptName: string }>,\n entry: AFSWriteEntryPayload,\n ): Promise<AFSWriteResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n\n const now = new Date();\n const existing = this.scripts.get(name);\n\n // Handle meta-only writes — preserve existing content\n if (entry.content === undefined && existing) {\n const meta: ScriptMetadata = {\n name,\n createdAt: existing.meta.createdAt,\n updatedAt: now,\n lastRun: existing.meta.lastRun,\n runCount: existing.meta.runCount,\n };\n const storedScript: StoredScript = {\n content: existing.content,\n meta,\n versions: existing.versions,\n execHistory: existing.execHistory,\n };\n this.scripts.set(name, storedScript);\n return {\n data: this.buildScriptEntry(name, storedScript),\n message: \"Script updated\",\n };\n }\n\n const content =\n typeof entry.content === \"string\" ? entry.content : JSON.stringify(entry.content);\n\n // Build version history\n const versions: ScriptVersion[] = existing?.versions ? [...existing.versions] : [];\n const maxVersion = versions.length > 0 ? Math.max(...versions.map((v) => v.version)) : 0;\n const newVersion: ScriptVersion = {\n version: maxVersion + 1,\n content,\n timestamp: now,\n size: new TextEncoder().encode(content).length,\n };\n versions.push(newVersion);\n\n // Keep only last MAX_VERSIONS\n while (versions.length > MAX_VERSIONS) {\n versions.shift();\n }\n\n const meta: ScriptMetadata = {\n name,\n createdAt: existing?.meta.createdAt ?? now,\n updatedAt: now,\n lastRun: existing?.meta.lastRun,\n runCount: existing?.meta.runCount ?? 0,\n };\n\n const storedScript: StoredScript = {\n content,\n meta,\n versions,\n execHistory: existing?.execHistory ?? [],\n };\n this.scripts.set(name, storedScript);\n\n return {\n data: this.buildScriptEntry(name, storedScript),\n message: existing ? \"Script updated\" : \"Script created\",\n };\n }\n\n /**\n * Reject writes to @history paths\n */\n @Write(\"/scripts/:scriptName/@history/:version\")\n async writeScriptHistory(\n _ctx: RouteContext<{ scriptName: string; version: string }>,\n _entry: AFSWriteEntryPayload,\n ): Promise<AFSWriteResult> {\n throw new Error(\"Cannot write to history directly\");\n }\n\n // ========== Delete Handlers ==========\n\n /**\n * Delete a stored script\n */\n @Delete(\"/scripts/:scriptName\")\n async deleteScript(ctx: RouteContext<{ scriptName: string }>): Promise<AFSDeleteResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n if (!this.scripts.has(name)) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n this.scripts.delete(name);\n this.scriptMetrics.delete(name);\n return { message: `Script '${name}' deleted` };\n }\n\n /**\n * Catch-all delete handler for unsupported paths\n */\n @Delete(\"/:path*\")\n async deleteCatchAll(ctx: RouteContext<{ path: string }>): Promise<AFSDeleteResult> {\n throw new AFSNotFoundError(ctx.path);\n }\n\n // ========== Exec Handlers ==========\n\n /**\n * Execute a stored script directly\n */\n @Actions.Exec(\"/scripts/:scriptName\", \"exec\")\n async execScript(\n ctx: RouteContext<{ scriptName: string }>,\n args: Record<string, unknown>,\n ): Promise<AFSExecResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n return {\n success: false,\n data: {\n error: `Script not found: ${name}`,\n logs: [],\n duration: 0,\n },\n };\n }\n\n const options = (ctx.options as { context?: { userId?: string; sessionId?: string } }) ?? {};\n\n // Check rate limit\n const rateCheck = this.checkRateLimit(options.context?.userId, name);\n if (rateCheck.limited) {\n return {\n success: false,\n data: {\n error: `Rate limit exceeded: ${rateCheck.reason}`,\n logs: [],\n duration: 0,\n rateLimited: true,\n },\n };\n }\n\n // Record execution for rate limiting\n this.recordExecution(options.context?.userId, name);\n\n // Update metadata\n script.meta.lastRun = new Date();\n script.meta.runCount++;\n\n // Generate execution context\n const executionId = generateExecutionId();\n const timestamp = Date.now();\n\n const execContext: ExecutionContext = {\n args,\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n timestamp,\n executionId,\n };\n\n // Log audit event\n this.logAudit({\n type: \"execution\",\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n scriptName: name,\n details: { args: sanitizeArgs(args) },\n });\n\n const result = await this.runtime.execute(script.content, this.capabilities, execContext);\n const scriptExecResult = result as ExecutionResult;\n\n // Update metrics\n this.updateMetrics(name, scriptExecResult);\n\n // Record execution history\n const historyEntry: ExecutionHistoryEntry = {\n executionId,\n timestamp: new Date(timestamp),\n success: scriptExecResult.success,\n duration: scriptExecResult.duration,\n error: scriptExecResult.error,\n timedOut: scriptExecResult.timedOut,\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n args: sanitizeArgs(args),\n };\n\n script.execHistory = script.execHistory ?? [];\n script.execHistory.push(historyEntry);\n\n while (script.execHistory.length > MAX_EXEC_HISTORY) {\n script.execHistory.shift();\n }\n\n const { success, ...data } = result as unknown as {\n success: boolean;\n [key: string]: unknown;\n };\n return { success, data: data as Record<string, unknown> };\n }\n\n /**\n * Execute a stored script directly via exec(\"/scripts/:name\")\n */\n @Exec(\"/scripts/:scriptName\")\n async execScriptDirect(\n ctx: RouteContext<{ scriptName: string }>,\n args: Record<string, unknown>,\n ): Promise<AFSExecResult> {\n return this.execScript(ctx, args);\n }\n\n /**\n * Execute root-level actions (run, validate, promote, create-from-template, promoted actions)\n */\n @Actions.Exec(\"/\")\n async execRootAction(\n ctx: RouteContext<{ action: string }>,\n args: Record<string, unknown>,\n ): Promise<AFSExecResult> {\n const actionName = ctx.params.action;\n return this.executeAction(actionName, args, ctx);\n }\n\n // ========== Stat Handlers ==========\n\n /**\n * Stat root → sandbox overview\n */\n @Stat(\"/\")\n async statRoot(_ctx: RouteContext): Promise<AFSStatResult> {\n return {\n data: {\n id: \"/\",\n path: \"/\",\n meta: {\n type: \"directory\",\n childrenCount: 4,\n scriptCount: this.scripts.size,\n templateCount: BUILT_IN_TEMPLATES.length,\n totalExecutions: this.metrics.totalExecutions,\n successCount: this.metrics.successCount,\n failureCount: this.metrics.failureCount,\n },\n },\n };\n }\n\n /**\n * Stat scripts directory\n */\n @Stat(\"/scripts\")\n async statScriptsDir(_ctx: RouteContext): Promise<AFSStatResult> {\n return {\n data: {\n id: \"/scripts\",\n path: \"/scripts\",\n meta: { type: \"directory\", childrenCount: this.scripts.size },\n },\n };\n }\n\n /**\n * Stat a specific script → runCount, lastRun, versionCount\n */\n @Stat(\"/scripts/:scriptName\")\n async statScript(ctx: RouteContext<{ scriptName: string }>): Promise<AFSStatResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n return {\n data: {\n id: joinURL(\"/scripts\", `${name}.js`),\n path: joinURL(\"/scripts\", `${name}.js`),\n createdAt: script.meta.createdAt,\n updatedAt: script.meta.updatedAt,\n meta: {\n type: \"file\",\n kind: \"afs:script\",\n scriptName: name,\n runCount: script.meta.runCount,\n lastRun: script.meta.lastRun ?? null,\n versionCount: (script.versions ?? []).length,\n },\n },\n };\n }\n\n /**\n * Stat templates directory\n */\n @Stat(\"/templates\")\n async statTemplatesDir(_ctx: RouteContext): Promise<AFSStatResult> {\n return {\n data: {\n id: \"/templates\",\n path: \"/templates\",\n meta: { type: \"directory\", childrenCount: BUILT_IN_TEMPLATES.length },\n },\n };\n }\n\n /**\n * Stat a specific template\n */\n @Stat(\"/templates/:templateName\")\n async statTemplate(ctx: RouteContext<{ templateName: string }>): Promise<AFSStatResult> {\n const template = BUILT_IN_TEMPLATES.find((t) => t.name === ctx.params.templateName);\n if (!template) {\n throw new AFSNotFoundError(ctx.path);\n }\n return {\n data: {\n id: joinURL(\"/templates\", template.name),\n path: joinURL(\"/templates\", template.name),\n meta: { type: \"template\", category: template.category },\n },\n };\n }\n\n /**\n * Stat metrics directory\n */\n @Stat(\"/metrics\")\n async statMetricsDir(_ctx: RouteContext): Promise<AFSStatResult> {\n return {\n data: {\n id: \"/metrics\",\n path: \"/metrics\",\n meta: { type: \"metrics\", childrenCount: this.scriptMetrics.size > 0 ? 1 : 0 },\n },\n };\n }\n\n /**\n * Stat audit directory\n */\n @Stat(\"/audit\")\n async statAuditDir(_ctx: RouteContext): Promise<AFSStatResult> {\n return {\n data: {\n id: \"/audit\",\n path: \"/audit\",\n meta: { type: \"audit\", entryCount: this.auditLog.length },\n },\n };\n }\n\n // ========== Explain Handlers ==========\n\n /**\n * Explain root → sandbox overview with security limits, templates, metrics\n */\n @Explain(\"/\")\n async explainRoot(_ctx: RouteContext): Promise<AFSExplainResult> {\n const lines: string[] = [];\n lines.push(`# ${this.name}`);\n lines.push(\"\");\n if (this.description) {\n lines.push(this.description);\n lines.push(\"\");\n }\n lines.push(\"## Overview\");\n lines.push(\"\");\n lines.push(`- **Scripts**: ${this.scripts.size}`);\n lines.push(`- **Templates**: ${BUILT_IN_TEMPLATES.length}`);\n lines.push(`- **Total Executions**: ${this.metrics.totalExecutions}`);\n lines.push(\n `- **Success Rate**: ${this.metrics.totalExecutions > 0 ? ((this.metrics.successCount / this.metrics.totalExecutions) * 100).toFixed(1) : 0}%`,\n );\n lines.push(\"\");\n lines.push(\"## Security & Isolation\");\n lines.push(\"\");\n lines.push(\"Scripts execute in an isolated sandbox environment with:\");\n lines.push(`- **Timeout**: ${this.options.runtime?.timeout ?? 5000}ms`);\n lines.push(`- **Memory Limit**: ${this.options.runtime?.memoryLimit ?? \"default\"}MB`);\n if (this.options.capabilities?.afs) {\n const afsCaps = this.options.capabilities.afs;\n lines.push(`- **AFS Read**: ${afsCaps.read ?? false}`);\n lines.push(`- **AFS Write**: ${afsCaps.write ?? false}`);\n if (afsCaps.allowPaths?.length) {\n lines.push(`- **Allowed Paths**: ${afsCaps.allowPaths.join(\", \")}`);\n }\n if (afsCaps.denyPaths?.length) {\n lines.push(`- **Denied Paths**: ${afsCaps.denyPaths.join(\", \")}`);\n }\n }\n lines.push(\"\");\n lines.push(\"## Templates\");\n lines.push(\"\");\n for (const t of BUILT_IN_TEMPLATES) {\n lines.push(`- **${t.name}** (${t.category}): ${t.description}`);\n }\n lines.push(\"\");\n if (this.scripts.size > 0) {\n lines.push(\"## Scripts\");\n lines.push(\"\");\n for (const [name, script] of this.scripts) {\n const lastRun = script.meta.lastRun ? new Date(script.meta.lastRun).toISOString() : \"never\";\n lines.push(`- **${name}.js**: ${script.meta.runCount} execution(s), last run: ${lastRun}`);\n }\n lines.push(\"\");\n }\n\n return { format: \"markdown\", content: lines.join(\"\\n\") };\n }\n\n /**\n * Explain a specific script → run count, code summary\n */\n @Explain(\"/scripts/:scriptName\")\n async explainScript(ctx: RouteContext<{ scriptName: string }>): Promise<AFSExplainResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n\n const lines: string[] = [];\n lines.push(`# Script: ${name}.js`);\n lines.push(\"\");\n lines.push(\"## Metadata\");\n lines.push(\"\");\n lines.push(`- **Created**: ${new Date(script.meta.createdAt).toISOString()}`);\n lines.push(`- **Updated**: ${new Date(script.meta.updatedAt).toISOString()}`);\n lines.push(`- **Run Count**: ${script.meta.runCount}`);\n lines.push(\n `- **Last Run**: ${script.meta.lastRun ? new Date(script.meta.lastRun).toISOString() : \"never\"}`,\n );\n lines.push(`- **Versions**: ${(script.versions ?? []).length}`);\n lines.push(`- **Size**: ${new TextEncoder().encode(script.content).length} bytes`);\n lines.push(\"\");\n lines.push(\"## Code Summary\");\n lines.push(\"\");\n const codeLines = script.content.split(\"\\n\");\n lines.push(`- **Lines**: ${codeLines.length}`);\n const firstLine = codeLines[0]?.trim() ?? \"\";\n if (firstLine.startsWith(\"//\")) {\n lines.push(`- **Description**: ${firstLine.slice(2).trim()}`);\n }\n lines.push(\"\");\n\n return { format: \"markdown\", content: lines.join(\"\\n\") };\n }\n\n // ========== Capabilities ==========\n\n /**\n * Read /.meta/.capabilities → capabilities manifest with action catalog\n */\n @Read(\"/.meta/.capabilities\")\n async readCapabilities(_ctx: RouteContext): Promise<AFSEntry> {\n const rootActionCatalog = [\n { name: \"run\", description: \"Execute inline JavaScript code\" },\n { name: \"validate\", description: \"Validate JavaScript syntax\" },\n { name: \"promote\", description: \"Promote a script to a formal action\" },\n { name: \"create-from-template\", description: \"Create a script from a template\" },\n ];\n\n // Add promoted actions\n for (const [actionName, action] of this.promotedActions) {\n rootActionCatalog.push({\n name: actionName,\n description: action.description ?? `Promoted action: ${actionName}`,\n });\n }\n\n const manifest: CapabilitiesManifest = {\n schemaVersion: 1,\n provider: this.name,\n description: this.description,\n tools: [],\n operations: this.getOperationsDeclaration(),\n actions: [\n {\n description: \"Root-level sandbox actions\",\n catalog: rootActionCatalog,\n discovery: { pathTemplate: \"/.actions\" },\n },\n {\n kind: \"afs:script\",\n description: \"Script-level actions\",\n catalog: [{ name: \"exec\", description: \"Execute the script\" }],\n discovery: { pathTemplate: \"/scripts/:scriptName/.actions\" },\n },\n ],\n };\n\n return {\n id: \"/.meta/.capabilities\",\n path: \"/.meta/.capabilities\",\n content: manifest,\n meta: {\n kind: \"afs:capabilities\",\n description: \"Sandbox provider capabilities manifest\",\n operations: [\"list\", \"read\", \"write\", \"delete\", \"exec\", \"stat\", \"explain\"],\n },\n };\n }\n\n // ========== Private Helpers ==========\n\n /**\n * Build AFSEntry for a stored script\n */\n private buildScriptEntry(name: string, script: StoredScript): AFSEntry {\n return {\n id: joinURL(\"/scripts\", `${name}.js`),\n path: joinURL(\"/scripts\", `${name}.js`),\n content: script.content,\n createdAt: script.meta.createdAt,\n updatedAt: script.meta.updatedAt,\n meta: {\n type: \"file\",\n kind: \"afs:script\",\n kinds: [\"afs:script\", \"afs:executable\", \"afs:node\"],\n childrenCount: 2,\n scriptName: name,\n lastRun: script.meta.lastRun,\n runCount: script.meta.runCount,\n },\n actions: [{ name: \"exec\", description: `Execute script ${name}` }],\n };\n }\n\n /**\n * Build scripts directory entry\n */\n private buildScriptsDirectoryEntry(): AFSEntry {\n return {\n id: \"/scripts\",\n path: \"/scripts\",\n summary: \"Stored JavaScript scripts\",\n meta: { kind: \"sandbox:directory\", type: \"directory\", childrenCount: this.scripts.size },\n };\n }\n\n /**\n * Build templates directory entry\n */\n private buildTemplatesDirectoryEntry(): AFSEntry {\n return {\n id: \"/templates\",\n path: \"/templates\",\n summary: \"Script templates\",\n meta: {\n kind: \"sandbox:directory\",\n type: \"directory\",\n childrenCount: BUILT_IN_TEMPLATES.length,\n },\n };\n }\n\n /**\n * Build metrics directory entry\n */\n private buildMetricsDirectoryEntry(): AFSEntry {\n return {\n id: \"/metrics\",\n path: \"/metrics\",\n summary: \"Execution metrics\",\n meta: {\n kind: \"sandbox:directory\",\n type: \"metrics\",\n childrenCount: this.scriptMetrics.size > 0 ? 1 : 0,\n },\n };\n }\n\n /**\n * Build audit directory entry\n */\n private buildAuditDirectoryEntry(): AFSEntry {\n return {\n id: \"/audit\",\n path: \"/audit\",\n summary: \"Audit log\",\n meta: { kind: \"sandbox:directory\", type: \"audit\", entryCount: this.auditLog.length },\n };\n }\n\n /**\n * Log an audit event\n */\n private logAudit(event: Omit<AuditEvent, \"timestamp\">): void {\n if (!this.auditConfig?.enabled) return;\n\n const fullEvent: AuditEvent = {\n ...event,\n timestamp: Date.now(),\n };\n\n this.auditLog.push(fullEvent);\n const maxEntries = this.auditConfig.maxEntries ?? 1000;\n while (this.auditLog.length > maxEntries) {\n this.auditLog.shift();\n }\n\n if (this.auditConfig.onEvent) {\n try {\n this.auditConfig.onEvent(fullEvent);\n } catch {\n // Ignore callback errors\n }\n }\n }\n\n /**\n * Check if execution is rate limited\n */\n private checkRateLimit(\n userId?: string,\n scriptName?: string,\n ): { limited: boolean; reason?: string } {\n if (!this.rateLimitConfig) return { limited: false };\n\n const now = Date.now();\n const oneMinuteAgo = now - 60000;\n const cleanTimestamps = (arr: number[]) => arr.filter((t) => t > oneMinuteAgo);\n\n if (this.rateLimitConfig.maxExecutionsPerMinute) {\n const recentExecutions = cleanTimestamps(this.executionTimestamps);\n this.executionTimestamps.length = 0;\n this.executionTimestamps.push(...recentExecutions);\n if (recentExecutions.length >= this.rateLimitConfig.maxExecutionsPerMinute) {\n return { limited: true, reason: \"Global rate limit exceeded\" };\n }\n }\n\n if (userId && this.rateLimitConfig.maxExecutionsPerMinutePerUser) {\n const userTimestamps = cleanTimestamps(this.userExecutionTimestamps.get(userId) ?? []);\n this.userExecutionTimestamps.set(userId, userTimestamps);\n if (userTimestamps.length >= this.rateLimitConfig.maxExecutionsPerMinutePerUser) {\n return { limited: true, reason: \"Per-user rate limit exceeded\" };\n }\n }\n\n if (scriptName && this.rateLimitConfig.maxExecutionsPerMinutePerScript) {\n const scriptTimestamps = cleanTimestamps(\n this.scriptExecutionTimestamps.get(scriptName) ?? [],\n );\n this.scriptExecutionTimestamps.set(scriptName, scriptTimestamps);\n if (scriptTimestamps.length >= this.rateLimitConfig.maxExecutionsPerMinutePerScript) {\n return { limited: true, reason: \"Per-script rate limit exceeded\" };\n }\n }\n\n return { limited: false };\n }\n\n /**\n * Record execution for rate limiting\n */\n private recordExecution(userId?: string, scriptName?: string): void {\n const now = Date.now();\n this.executionTimestamps.push(now);\n\n if (userId) {\n const userTimestamps = this.userExecutionTimestamps.get(userId) ?? [];\n userTimestamps.push(now);\n this.userExecutionTimestamps.set(userId, userTimestamps);\n }\n\n if (scriptName) {\n const scriptTimestamps = this.scriptExecutionTimestamps.get(scriptName) ?? [];\n scriptTimestamps.push(now);\n this.scriptExecutionTimestamps.set(scriptName, scriptTimestamps);\n }\n }\n\n /**\n * Update execution metrics\n */\n private updateMetrics(scriptName: string | undefined, result: ExecutionResult): void {\n this.metrics.totalExecutions++;\n this.metrics.totalDuration += result.duration;\n this.metrics.averageDuration = this.metrics.totalDuration / this.metrics.totalExecutions;\n\n if (result.success) {\n this.metrics.successCount++;\n } else {\n this.metrics.failureCount++;\n }\n\n if (result.timedOut) {\n this.metrics.timeoutCount++;\n }\n\n if (scriptName) {\n let scriptMetrics = this.scriptMetrics.get(scriptName);\n if (!scriptMetrics) {\n scriptMetrics = {\n totalExecutions: 0,\n successCount: 0,\n failureCount: 0,\n timeoutCount: 0,\n averageDuration: 0,\n totalDuration: 0,\n };\n this.scriptMetrics.set(scriptName, scriptMetrics);\n }\n\n scriptMetrics.totalExecutions++;\n scriptMetrics.totalDuration += result.duration;\n scriptMetrics.averageDuration = scriptMetrics.totalDuration / scriptMetrics.totalExecutions;\n\n if (result.success) {\n scriptMetrics.successCount++;\n } else {\n scriptMetrics.failureCount++;\n }\n\n if (result.timedOut) {\n scriptMetrics.timeoutCount++;\n }\n }\n }\n\n /**\n * Validate action name\n */\n private isValidActionName(name: string): { valid: boolean; error?: string } {\n if (!name || typeof name !== \"string\") {\n return { valid: false, error: \"Action name is required\" };\n }\n if (RESERVED_ACTION_NAMES.includes(name)) {\n return { valid: false, error: `Action name \"${name}\" is reserved` };\n }\n if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)) {\n return {\n valid: false,\n error:\n \"Action name must start with a letter and contain only letters, numbers, hyphens, and underscores\",\n };\n }\n if (name.includes(\"..\") || name.includes(\"/\") || name.includes(\"\\\\\")) {\n return { valid: false, error: \"Action name cannot contain path separators\" };\n }\n return { valid: true };\n }\n\n /**\n * Apply template variables to content\n */\n private applyTemplate(content: string, variables: Record<string, string>): string {\n let result = content;\n for (const [key, value] of Object.entries(variables)) {\n result = result.replace(new RegExp(`\\\\{\\\\{${key}\\\\}\\\\}`, \"g\"), value);\n }\n return result;\n }\n\n /**\n * Execute a built-in or promoted action\n */\n private async executeAction(\n actionName: string,\n args: Record<string, unknown>,\n ctx: RouteContext,\n ): Promise<AFSExecResult> {\n const options = (ctx.options as { context?: { userId?: string; sessionId?: string } }) ?? {};\n\n if (actionName === \"run\") {\n const code = args.code;\n if (typeof code !== \"string\") {\n throw new Error(\"action 'run' requires 'code' parameter as string\");\n }\n\n const rateCheck = this.checkRateLimit(options.context?.userId, undefined);\n if (rateCheck.limited) {\n return {\n success: false,\n data: {\n error: `Rate limit exceeded: ${rateCheck.reason}`,\n logs: [],\n duration: 0,\n rateLimited: true,\n },\n };\n }\n\n this.recordExecution(options.context?.userId, undefined);\n\n const executionId = generateExecutionId();\n const timestamp = Date.now();\n\n const execContext: ExecutionContext = {\n args: (args.args as Record<string, unknown>) ?? {},\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n timestamp,\n executionId,\n };\n\n this.logAudit({\n type: \"execution\",\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n actionName: \"run\",\n details: { codeLength: code.length },\n });\n\n const result = await this.runtime.execute(code, this.capabilities, execContext);\n const runExecResult = result as ExecutionResult;\n\n this.updateMetrics(undefined, runExecResult);\n\n const { success: runSuccess, ...runData } = result as unknown as {\n success: boolean;\n [key: string]: unknown;\n };\n return { success: runSuccess, data: runData as Record<string, unknown> };\n }\n\n if (actionName === \"validate\") {\n const code = args.code;\n if (typeof code !== \"string\") {\n throw new Error(\"action 'validate' requires 'code' parameter as string\");\n }\n\n try {\n new Function(`\"use strict\"; return async () => { ${code} }`);\n return {\n success: true,\n data: { valid: true, message: \"Syntax is valid\" },\n };\n } catch (error) {\n return {\n success: true,\n data: {\n valid: false,\n error: error instanceof Error ? error.message : String(error),\n },\n };\n }\n }\n\n if (actionName === \"rollback\") {\n const scriptName = args.script;\n const version = args.version;\n\n if (typeof scriptName !== \"string\") {\n throw new Error(\"action 'rollback' requires 'script' parameter as string\");\n }\n if (typeof version !== \"number\" || version < 1) {\n throw new Error(\"action 'rollback' requires 'version' parameter as positive number\");\n }\n\n const script = this.scripts.get(scriptName);\n if (!script) {\n return { success: false, data: { error: `Script not found: ${scriptName}` } };\n }\n\n const versions = script.versions ?? [];\n const targetVersion = versions.find((v) => v.version === version);\n if (!targetVersion) {\n return { success: false, data: { error: `Version ${version} not found` } };\n }\n\n await this.writeScript(\n {\n path: joinURL(\"/scripts\", `${scriptName}.js`),\n params: { scriptName: `${scriptName}.js` },\n options: {},\n },\n { content: targetVersion.content },\n );\n\n return {\n success: true,\n data: {\n message: `Rolled back to version ${version}`,\n newVersion: script.versions?.length ?? 0,\n },\n };\n }\n\n if (actionName === \"promote\") {\n const scriptName = args.script as string | undefined;\n const actionNameArg = args.name as string | undefined;\n\n if (!scriptName || typeof scriptName !== \"string\") {\n return {\n success: false,\n data: { error: \"action 'promote' requires 'script' parameter as string\" },\n };\n }\n if (!actionNameArg || typeof actionNameArg !== \"string\") {\n return {\n success: false,\n data: { error: \"action 'promote' requires 'name' parameter as string\" },\n };\n }\n\n const nameValidation = this.isValidActionName(actionNameArg);\n if (!nameValidation.valid) {\n return { success: false, data: { error: nameValidation.error } };\n }\n\n const script = this.scripts.get(scriptName);\n if (!script) {\n return { success: false, data: { error: `Script not found: ${scriptName}` } };\n }\n\n try {\n new Function(`\"use strict\"; return async () => { ${script.content} }`);\n } catch (error) {\n return {\n success: false,\n data: {\n error: `Script has syntax error: ${error instanceof Error ? error.message : String(error)}`,\n },\n };\n }\n\n const currentVersion = script.versions?.length\n ? Math.max(...script.versions.map((v) => v.version))\n : 1;\n\n const existing = this.promotedActions.get(actionNameArg);\n const promotedAction: PromotedAction = {\n name: actionNameArg,\n description: (args.description as string) ?? existing?.description,\n sourceScript: scriptName,\n sourceVersion: currentVersion,\n inputSchema: (args.inputSchema as Record<string, unknown>) ?? existing?.inputSchema,\n outputSchema: (args.outputSchema as Record<string, unknown>) ?? existing?.outputSchema,\n promotedAt: new Date(),\n version: (existing?.version ?? 0) + 1,\n };\n\n this.promotedActions.set(actionNameArg, promotedAction);\n\n this.logAudit({\n type: \"action_promote\",\n actionName: actionNameArg,\n scriptName,\n details: { version: promotedAction.version },\n });\n\n return {\n success: true,\n data: {\n message: `Script '${scriptName}' promoted to action '${actionNameArg}' (version ${promotedAction.version})`,\n action: promotedAction,\n },\n };\n }\n\n if (actionName === \"create-from-template\") {\n const templateName = args.template as string | undefined;\n const scriptName = args.name as string | undefined;\n const variables = (args.variables as Record<string, string>) ?? {};\n\n if (!templateName || typeof templateName !== \"string\") {\n return {\n success: false,\n data: { error: \"action 'create-from-template' requires 'template' parameter as string\" },\n };\n }\n if (!scriptName || typeof scriptName !== \"string\") {\n return {\n success: false,\n data: { error: \"action 'create-from-template' requires 'name' parameter as string\" },\n };\n }\n\n if (\n templateName.includes(\"..\") ||\n templateName.includes(\"/\") ||\n templateName.includes(\"\\\\\")\n ) {\n return { success: false, data: { error: \"Invalid template name\" } };\n }\n\n const template = BUILT_IN_TEMPLATES.find((t) => t.name === templateName);\n if (!template) {\n return { success: false, data: { error: `Template not found: ${templateName}` } };\n }\n\n if (template.variables) {\n for (const v of template.variables) {\n if (v.required && variables[v.name] === undefined && v.default === undefined) {\n return { success: false, data: { error: `Missing required variable: ${v.name}` } };\n }\n }\n for (const v of template.variables) {\n if (variables[v.name] === undefined && v.default !== undefined) {\n variables[v.name] = v.default;\n }\n }\n }\n\n const content = this.applyTemplate(template.content, variables);\n\n await this.writeScript(\n {\n path: joinURL(\"/scripts\", `${scriptName}.js`),\n params: { scriptName: `${scriptName}.js` },\n options: {},\n },\n { content },\n );\n\n return {\n success: true,\n data: {\n message: `Script '${scriptName}' created from template '${templateName}'`,\n path: joinURL(\"/scripts\", `${scriptName}.js`),\n },\n };\n }\n\n // Check if it's a promoted action\n const promotedAction = this.promotedActions.get(actionName);\n if (promotedAction) {\n const script = this.scripts.get(promotedAction.sourceScript);\n if (!script) {\n return {\n success: false,\n data: {\n error: `Source script not found: ${promotedAction.sourceScript}`,\n logs: [],\n duration: 0,\n },\n };\n }\n\n const rateCheck = this.checkRateLimit(options.context?.userId, promotedAction.sourceScript);\n if (rateCheck.limited) {\n return {\n success: false,\n data: {\n error: `Rate limit exceeded: ${rateCheck.reason}`,\n logs: [],\n duration: 0,\n rateLimited: true,\n },\n };\n }\n\n this.recordExecution(options.context?.userId, promotedAction.sourceScript);\n\n const executionId = generateExecutionId();\n const timestamp = Date.now();\n\n const execContext: ExecutionContext = {\n args,\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n timestamp,\n executionId,\n };\n\n this.logAudit({\n type: \"execution\",\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n actionName,\n scriptName: promotedAction.sourceScript,\n details: { args: sanitizeArgs(args) },\n });\n\n const result = await this.runtime.execute(script.content, this.capabilities, execContext);\n const promotedExecResult = result as ExecutionResult;\n\n this.updateMetrics(promotedAction.sourceScript, promotedExecResult);\n\n const { success: promotedSuccess, ...promotedData } = result as unknown as {\n success: boolean;\n [key: string]: unknown;\n };\n return { success: promotedSuccess, data: promotedData as Record<string, unknown> };\n }\n\n throw new Error(`Unknown action: ${actionName}`);\n }\n}\n\n// Type check to ensure AFSSandbox implements AFSModuleClass\nconst _typeCheck: AFSModuleClass<AFSSandbox, AFSSandboxOptions> = AFSSandbox;\n\nexport default AFSSandbox;\n"],"mappings":";;;;;;;;;;AAYA,SAAS,oBAAoB,MAAc,UAA6B;AACtE,MAAK,MAAM,WAAW,UAAU;AAE9B,MAAI,YAAY,OAAO,YAAY,KAAM,QAAO;AAChD,MAAI,QAAQ,SAAS,MAAM,IAAI,KAAK,WAAW,QAAQ,MAAM,GAAG,GAAG,CAAC,CAClE,QAAO;AAET,MAAI,QAAQ,SAAS,KAAK,IAAI,KAAK,WAAW,QAAQ,MAAM,GAAG,GAAG,CAAC,EAAE;GAEnE,MAAM,OAAO,KAAK,MAAM,QAAQ,SAAS,EAAE;AAC3C,OAAI,CAAC,KAAK,SAAS,IAAI,IAAI,SAAS,GAAI,QAAO;;AAEjD,MAAI,SAAS,QAAS,QAAO;AAC7B,MAAI,KAAK,WAAW,GAAG,QAAQ,GAAG,CAAE,QAAO;;AAE7C,QAAO;;;;;AAMT,SAAS,cAAc,MAAc,YAAuB,WAA+B;AAEzF,KAAI,aAAa,UAAU,SAAS,KAAK,oBAAoB,MAAM,UAAU,CAC3E,QAAO;AAIT,KAAI,cAAc,WAAW,SAAS,EACpC,QAAO,oBAAoB,MAAM,WAAW;AAI9C,QAAO;;;;;;AAOT,SAAS,cAAc,MAAsB;AAE3C,KAAI,KAAK,SAAS,KAAO,CACvB,OAAM,IAAI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O,UAAU;YAUjB,QAAQ,KAAK,wBAAwB,OAAO;YAkG5C,KAAK,uBAAuB;YAW5B,QAAQ,KAAK,IAAI;YAcjB,KAAK,IAAI;YAsBT,KAAK,WAAW;YAchB,KAAK,uBAAuB;YA4B5B,KAAK,aAAa;YAclB,KAAK,2BAA2B;YAkBhC,KAAK,WAAW;YAchB,KAAK,SAAS;YAgBd,QAAQ,IAAI;YAyDZ,QAAQ,uBAAuB;YAwC/B,KAAK,uBAAuB;AAwnB/B,kBAAe"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["result","storedScript","promotedAction"],"sources":["../src/capabilities/index.ts","../src/runtime/isolate.ts","../src/index.ts"],"sourcesContent":["import type { AFSRoot } from \"@aigne/afs\";\nimport type { CapabilitiesConfig } from \"../types.js\";\n\n/**\n * Capability functions that can be called from within the sandbox.\n * These are injected as `afs.*` methods.\n */\nexport type CapabilityFunctions = Record<string, (...args: unknown[]) => Promise<unknown>>;\n\n/**\n * Check if a path matches any patterns in the list.\n */\nfunction pathMatchesPatterns(path: string, patterns: string[]): boolean {\n for (const pattern of patterns) {\n // Simple glob-like matching\n if (pattern === \"*\" || pattern === \"**\") return true;\n if (pattern.endsWith(\"/**\") && path.startsWith(pattern.slice(0, -3))) {\n return true;\n }\n if (pattern.endsWith(\"/*\") && path.startsWith(pattern.slice(0, -2))) {\n // Only match direct children\n const rest = path.slice(pattern.length - 2);\n if (!rest.includes(\"/\") || rest === \"\") return true;\n }\n if (path === pattern) return true;\n if (path.startsWith(`${pattern}/`)) return true;\n }\n return false;\n}\n\n/**\n * Check if a path is allowed based on allow/deny patterns.\n */\nfunction isPathAllowed(path: string, allowPaths?: string[], denyPaths?: string[]): boolean {\n // If deny patterns exist and path matches, deny\n if (denyPaths && denyPaths.length > 0 && pathMatchesPatterns(path, denyPaths)) {\n return false;\n }\n\n // If allow patterns exist, path must match\n if (allowPaths && allowPaths.length > 0) {\n return pathMatchesPatterns(path, allowPaths);\n }\n\n // No restrictions, allow\n return true;\n}\n\n/**\n * Normalize and validate a path for security.\n * Checks for path traversal attacks, null bytes, etc.\n */\nfunction normalizePath(path: string): string {\n // Check for null bytes\n if (path.includes(\"\\x00\")) {\n throw new Error(\"Invalid path: null byte detected\");\n }\n\n // URL decode the path to catch encoded attacks\n let decoded = path;\n try {\n decoded = decodeURIComponent(path);\n } catch {\n // If decoding fails, use original\n }\n\n // Check for path traversal after decoding\n if (decoded.includes(\"..\")) {\n throw new Error(\"Path traversal not allowed\");\n }\n\n // Check for control characters (ASCII 0-31 and 127)\n for (const char of decoded) {\n const code = char.charCodeAt(0);\n if (code < 32 || code === 127) {\n throw new Error(\"Invalid path: control characters detected\");\n }\n }\n\n return decoded;\n}\n\n/**\n * Create capability functions based on configuration.\n *\n * @param afs - The AFS root for filesystem operations\n * @param config - Capabilities configuration\n * @returns Record of capability functions to inject into sandbox\n */\nexport function createCapabilities(\n afs: AFSRoot | undefined,\n config: CapabilitiesConfig,\n): CapabilityFunctions {\n const capabilities: CapabilityFunctions = {};\n\n // AFS read capability\n if (afs?.read && config.afs?.read !== false) {\n const afsRead = afs.read.bind(afs);\n capabilities.read = async (path: unknown): Promise<string | null> => {\n if (typeof path !== \"string\") {\n throw new Error(\"afs.read: path must be a string\");\n }\n\n // Check path permissions\n if (!isPathAllowed(path, config.afs?.allowPaths, config.afs?.denyPaths)) {\n throw new Error(`afs.read: access denied to path \"${path}\"`);\n }\n\n try {\n const result = await afsRead(path);\n if (!result.data) {\n return null;\n }\n\n // Return content as string\n const content = result.data.content;\n if (content === undefined || content === null) {\n return null;\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n // For non-string content, serialize to JSON\n return JSON.stringify(content);\n } catch (error) {\n throw new Error(\n `afs.read: failed to read \"${path}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n };\n }\n\n // AFS write capability (Phase 2)\n if (afs?.write && config.afs?.write === true) {\n const afsWrite = afs.write.bind(afs);\n capabilities.write = async (\n path: unknown,\n content: unknown,\n ): Promise<{ success: boolean; path: string }> => {\n // Validate path\n if (path === undefined || path === null) {\n throw new Error(\"afs.write: path is required\");\n }\n if (typeof path !== \"string\") {\n throw new Error(\"afs.write: path must be a string\");\n }\n\n // Validate content\n if (typeof content !== \"string\") {\n throw new Error(\"afs.write: content must be a string\");\n }\n if (content === \"\") {\n throw new Error(\"afs.write: content cannot be empty\");\n }\n\n // Normalize and check for path traversal attacks\n let normalizedPath: string;\n try {\n normalizedPath = normalizePath(path);\n } catch (error) {\n throw new Error(`afs.write: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n // Check path permissions\n if (!isPathAllowed(normalizedPath, config.afs?.allowPaths, config.afs?.denyPaths)) {\n throw new Error(`afs.write: access denied to path \"${path}\"`);\n }\n\n try {\n await afsWrite(normalizedPath, { content });\n return { success: true, path: normalizedPath };\n } catch (error) {\n throw new Error(\n `afs.write: failed to write \"${path}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n };\n } else {\n // Provide a stub that throws when write is disabled\n capabilities.write = async (): Promise<never> => {\n throw new Error(\"afs.write: write capability not enabled\");\n };\n }\n\n // AFS list capability (useful for Phase 2, but add basic support now)\n if (afs?.list && config.afs?.read !== false) {\n const afsList = afs.list.bind(afs);\n capabilities.list = async (\n path: unknown,\n options?: unknown,\n ): Promise<{ path: string; type: string }[]> => {\n if (typeof path !== \"string\") {\n throw new Error(\"afs.list: path must be a string\");\n }\n\n // Check path permissions\n if (!isPathAllowed(path, config.afs?.allowPaths, config.afs?.denyPaths)) {\n throw new Error(`afs.list: access denied to path \"${path}\"`);\n }\n\n try {\n const listOptions = typeof options === \"object\" && options !== null ? options : {};\n const result = await afsList(path, listOptions as Record<string, unknown>);\n\n // Return simplified entry info\n return result.data.map((entry) => ({\n path: entry.path,\n type: (entry.meta?.type as string | undefined) ?? \"unknown\",\n }));\n } catch (error) {\n throw new Error(\n `afs.list: failed to list \"${path}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n };\n }\n\n return capabilities;\n}\n","import { getQuickJS } from \"quickjs-emscripten\";\nimport type {\n ExecutionContext,\n ExecutionResult,\n LogEntry,\n LogLevel,\n RuntimeOptions,\n} from \"../types.js\";\n\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst DEFAULT_MEMORY_LIMIT_MB = 128;\n\n/**\n * Sandbox runtime using QuickJS (WebAssembly) for secure JavaScript execution.\n *\n * Provides sandboxed execution with:\n * - Memory limits\n * - CPU time limits (timeout via interrupt)\n * - Capability injection for controlled AFS access\n *\n * Note: Async/await in sandbox code is limited. Capability functions return\n * Promises that can be used for type checking, but full async execution\n * requires calling capabilities synchronously for now.\n */\nexport class SandboxRuntime {\n private readonly timeout: number;\n private readonly memoryLimit: number;\n\n constructor(options: RuntimeOptions = {}) {\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n this.memoryLimit = options.memoryLimit ?? DEFAULT_MEMORY_LIMIT_MB;\n }\n\n /**\n * Execute JavaScript code in an isolated QuickJS sandbox.\n *\n * @param code - JavaScript source code to execute\n * @param capabilities - Capability functions to inject into sandbox\n * @param context - Execution context with args and tracking info\n * @returns Execution result with success status, return value, errors, and logs\n */\n async execute(\n code: string,\n capabilities: Record<string, (...args: unknown[]) => Promise<unknown>>,\n context: ExecutionContext = {},\n ): Promise<ExecutionResult> {\n const logs: LogEntry[] = [];\n const startTime = Date.now();\n\n // Get QuickJS instance\n const QuickJS = await getQuickJS();\n\n // Create runtime with memory limit\n const runtime = QuickJS.newRuntime();\n runtime.setMemoryLimit(this.memoryLimit * 1024 * 1024);\n\n // Set up interrupt handler for timeout\n let timedOut = false;\n const deadline = Date.now() + this.timeout;\n runtime.setInterruptHandler(() => {\n if (Date.now() > deadline) {\n timedOut = true;\n return true; // Interrupt execution\n }\n return false;\n });\n\n // Create context\n const vm = runtime.newContext();\n\n try {\n // Inject logging function\n const logFn = vm.newFunction(\"log\", (levelHandle, messageHandle) => {\n const level = vm.getString(levelHandle) as LogLevel;\n const message = vm.getString(messageHandle);\n logs.push({\n level,\n message,\n timestamp: Date.now(),\n });\n });\n vm.setProp(vm.global, \"__log\", logFn);\n logFn.dispose();\n\n // Inject args\n const argsJson = JSON.stringify(context.args ?? {});\n vm.evalCode(`const __args = ${argsJson};`);\n\n // Inject context object (timestamp, executionId, userId, sessionId)\n const contextObj = {\n timestamp: context.timestamp ?? Date.now(),\n executionId: context.executionId ?? `exec-${Date.now()}`,\n userId: context.userId,\n sessionId: context.sessionId,\n };\n const contextJson = JSON.stringify(contextObj);\n vm.evalCode(`const __context = ${contextJson};`);\n\n // Create pending promises tracker for async capabilities\n const pendingPromises: Map<\n number,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n }\n > = new Map();\n let promiseId = 0;\n\n // Inject capability functions\n for (const [name, fn] of Object.entries(capabilities)) {\n // Create a sync function that returns a promise ID\n const capFn = vm.newFunction(`__cap_${name}`, (...argHandles) => {\n const args = argHandles.map((h) => {\n const type = vm.typeof(h);\n if (type === \"string\") return vm.getString(h);\n if (type === \"number\") return vm.getNumber(h);\n if (type === \"boolean\") return vm.dump(h);\n if (type === \"object\" || type === \"undefined\") return vm.dump(h);\n return vm.dump(h);\n });\n\n // Store the promise for later resolution\n const id = promiseId++;\n\n // Execute the capability async\n fn(...args)\n .then((result) => {\n pendingPromises.get(id)?.resolve(result);\n pendingPromises.delete(id);\n })\n .catch((error) => {\n pendingPromises\n .get(id)\n ?.reject(error instanceof Error ? error : new Error(String(error)));\n pendingPromises.delete(id);\n });\n\n return vm.newNumber(id);\n });\n vm.setProp(vm.global, `__cap_${name}`, capFn);\n capFn.dispose();\n }\n\n // Build the afs object and wrapper code\n const capabilitySetups = Object.keys(capabilities)\n .map(\n (name) => `\n ${name}: function(...args) {\n return new Promise((resolve, reject) => {\n const id = __cap_${name}(...args);\n __pendingResolvers[id] = { resolve, reject };\n });\n }`,\n )\n .join(\",\\n\");\n\n const wrapperCode = `\n(function() {\n // Pending promise resolvers\n const __pendingResolvers = {};\n globalThis.__pendingResolvers = __pendingResolvers;\n\n // Set up afs object with logging and capabilities\n const afs = {\n log: function(level, message) {\n __log(String(level), String(message));\n },\n ${capabilitySetups}\n };\n\n // Get arguments and context\n const args = __args;\n const context = Object.freeze(__context);\n\n // User code\n ${code}\n})();\n`;\n\n // Execute the code\n const result = vm.evalCode(wrapperCode);\n\n if (timedOut) {\n result.dispose();\n return {\n success: false,\n error: `Script execution timed out after ${this.timeout}ms`,\n logs,\n duration: Date.now() - startTime,\n timedOut: true,\n };\n }\n\n if (result.error) {\n const errorValue = vm.dump(result.error);\n result.error.dispose();\n\n const errorMessage =\n typeof errorValue === \"object\" && errorValue !== null\n ? ((errorValue as { message?: string }).message ?? String(errorValue))\n : String(errorValue);\n\n return {\n success: false,\n error: errorMessage,\n stack:\n typeof errorValue === \"object\" && errorValue !== null\n ? (errorValue as { stack?: string }).stack\n : undefined,\n logs,\n duration: Date.now() - startTime,\n };\n }\n\n // Get the result value\n const resultValue = vm.dump(result.value);\n result.value.dispose();\n\n return {\n success: true,\n result: resultValue,\n logs,\n duration: Date.now() - startTime,\n timedOut: false,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n return {\n success: false,\n error: errorMessage,\n stack,\n logs,\n duration: Date.now() - startTime,\n };\n } finally {\n // Cleanup\n vm.dispose();\n runtime.dispose();\n }\n }\n}\n","import {\n type AFSAccessMode,\n type AFSDeleteResult,\n type AFSEntry,\n type AFSExecResult,\n type AFSExplainResult,\n type AFSListResult,\n type AFSModuleClass,\n type AFSModuleLoadParams,\n AFSNotFoundError,\n type AFSRoot,\n type AFSStatResult,\n type AFSWriteEntryPayload,\n type AFSWriteResult,\n type CapabilitiesManifest,\n type ProviderManifest,\n} from \"@aigne/afs\";\nimport {\n Actions,\n AFSBaseProvider,\n Delete,\n Exec,\n Explain,\n List,\n Meta,\n Read,\n type RouteContext,\n Stat,\n Write,\n} from \"@aigne/afs/provider\";\nimport { joinURL } from \"ufo\";\nimport { z } from \"zod\";\nimport { type CapabilityFunctions, createCapabilities } from \"./capabilities/index.js\";\nimport { SandboxRuntime } from \"./runtime/isolate.js\";\nimport type {\n AFSSandboxOptions,\n AuditConfig,\n AuditEvent,\n ExecutionContext,\n ExecutionHistoryEntry,\n ExecutionMetrics,\n ExecutionResult,\n PromotedAction,\n RateLimitConfig,\n ScriptMetadata,\n ScriptTemplate,\n ScriptVersion,\n StoredScript,\n} from \"./types.js\";\n\nexport type {\n AFSSandboxOptions,\n AuditConfig,\n AuditEvent,\n AuditEventType,\n ExecutionMetrics,\n ExecutionResult,\n LogEntry,\n LogLevel,\n PromotedAction,\n RateLimitConfig,\n ScriptTemplate,\n} from \"./types.js\";\n\n/** Maximum number of versions to keep per script */\nconst MAX_VERSIONS = 5;\n/** Maximum number of execution history entries per script */\nconst MAX_EXEC_HISTORY = 100;\n/** Sensitive fields to redact from execution history */\nconst SENSITIVE_FIELDS = [\"password\", \"secret\", \"token\", \"key\", \"credential\", \"auth\"];\n\n/**\n * Generate a unique execution ID\n */\nfunction generateExecutionId(): string {\n return `exec-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Sanitize args by redacting sensitive fields\n */\nfunction sanitizeArgs(args: Record<string, unknown>): Record<string, unknown> {\n const sanitized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (SENSITIVE_FIELDS.some((f) => key.toLowerCase().includes(f))) {\n sanitized[key] = \"[REDACTED]\";\n } else if (typeof value === \"object\" && value !== null) {\n sanitized[key] = sanitizeArgs(value as Record<string, unknown>);\n } else {\n sanitized[key] = value;\n }\n }\n return sanitized;\n}\n\n/**\n * Zod schema for configuration validation\n */\nconst afsSandboxOptionsSchema = z.object({\n name: z.string().optional().describe(\"Module name\"),\n description: z.string().optional().describe(\"Module description\"),\n accessMode: z.enum([\"readonly\", \"readwrite\"]).optional().describe(\"Access mode for this module\"),\n runtime: z\n .object({\n timeout: z.number().positive().optional().describe(\"Execution timeout in milliseconds\"),\n memoryLimit: z.number().positive().optional().describe(\"Memory limit in MB\"),\n })\n .optional()\n .describe(\"Runtime configuration\"),\n capabilities: z\n .object({\n afs: z\n .object({\n read: z.boolean().optional().describe(\"Enable read operations\"),\n write: z.boolean().optional().describe(\"Enable write operations\"),\n allowPaths: z.array(z.string()).optional().describe(\"Allowed path patterns\"),\n denyPaths: z.array(z.string()).optional().describe(\"Denied path patterns\"),\n })\n .optional()\n .describe(\"AFS access configuration\"),\n })\n .optional()\n .describe(\"Capabilities configuration\"),\n audit: z\n .object({\n enabled: z.boolean().describe(\"Enable audit logging\"),\n onEvent: z.any().optional(),\n maxEntries: z.number().positive().optional().describe(\"Max audit entries to keep\"),\n })\n .optional()\n .describe(\"Audit configuration\"),\n rateLimit: z\n .object({\n maxExecutionsPerMinute: z.number().positive().optional(),\n maxExecutionsPerMinutePerUser: z.number().positive().optional(),\n maxExecutionsPerMinutePerScript: z.number().positive().optional(),\n })\n .optional()\n .describe(\"Rate limiting configuration\"),\n});\n\n/** Reserved action names that cannot be used for promoted actions */\nconst RESERVED_ACTION_NAMES = [\"run\", \"validate\", \"rollback\", \"promote\", \"create-from-template\"];\n\n/** Built-in script templates */\nconst BUILT_IN_TEMPLATES: ScriptTemplate[] = [\n {\n name: \"basic\",\n description: \"A basic script template\",\n content: `// Basic script template\nreturn args.input;`,\n category: \"general\",\n },\n {\n name: \"data-transform\",\n description: \"Transform input data to output format\",\n content: `// Data transformation script\nconst {{inputField}} = args.{{inputField}};\nconst {{outputField}} = {{inputField}};\nreturn { {{outputField}} };`,\n variables: [\n { name: \"inputField\", description: \"Name of the input field\", required: true },\n { name: \"outputField\", description: \"Name of the output field\", required: true },\n ],\n category: \"data\",\n },\n {\n name: \"validation\",\n description: \"Validate input data against rules\",\n content: `// Validation script\nconst value = args.{{fieldName}};\nconst errors = [];\n\nif (value === undefined || value === null) {\n errors.push('{{fieldName}} is required');\n}\n\nreturn { valid: errors.length === 0, errors };`,\n variables: [\n { name: \"fieldName\", description: \"Name of the field to validate\", required: true },\n ],\n category: \"validation\",\n },\n {\n name: \"aggregation\",\n description: \"Aggregate array data\",\n content: `// Aggregation script\nconst items = args.items || [];\nconst sum = items.reduce((acc, item) => acc + (item.{{valueField}} || 0), 0);\nconst count = items.length;\nconst average = count > 0 ? sum / count : 0;\n\nreturn { sum, count, average };`,\n variables: [\n { name: \"valueField\", description: \"Field to aggregate\", required: true, default: \"value\" },\n ],\n category: \"data\",\n },\n];\n\n/**\n * AFS Sandbox Provider\n *\n * Provides a sandboxed JavaScript execution environment for LLM-generated code.\n * Scripts are stored at `/scripts/{name}.js` and executed directly via exec().\n *\n * Structure:\n * - `/` - root directory\n * - `/scripts` - stored scripts directory\n * - `/scripts/{name}.js` - individual script files (executable)\n * - `/templates` - script templates\n * - `/templates/{name}` - individual templates\n * - `/metrics` - execution metrics\n * - `/audit` - audit log\n * - `/.actions` - root-level actions (run, validate, promote, create-from-template)\n * - `/scripts/{name}.js/.actions` - script-level actions (exec, history, exec-history)\n *\n * @example\n * ```typescript\n * const sandbox = new AFSSandbox({ name: \"sandbox\" });\n * afs.mount(sandbox);\n *\n * // Write a script\n * await afs.write(\"/modules/sandbox/scripts/greet.js\", {\n * content: `\n * afs.log(\"info\", \"Hello from sandbox!\");\n * return \"Hello, \" + args.name;\n * `\n * });\n *\n * // Execute the script\n * const result = await afs.exec(\"/modules/sandbox/scripts/greet.js\", { name: \"World\" });\n * // result.data = { success: true, result: \"Hello, World\", logs: [...] }\n * ```\n */\nexport class AFSSandbox extends AFSBaseProvider {\n override readonly name: string;\n override readonly description?: string;\n override readonly accessMode: AFSAccessMode;\n\n private readonly runtime: SandboxRuntime;\n private readonly options: AFSSandboxOptions;\n private readonly scripts: Map<string, StoredScript> = new Map();\n private capabilities: CapabilityFunctions = {};\n\n // Promoted actions storage\n private readonly promotedActions: Map<string, PromotedAction> = new Map();\n\n // Audit logging\n private readonly auditLog: AuditEvent[] = [];\n private readonly auditConfig?: AuditConfig;\n\n // Rate limiting\n private readonly rateLimitConfig?: RateLimitConfig;\n private readonly executionTimestamps: number[] = [];\n private readonly userExecutionTimestamps: Map<string, number[]> = new Map();\n private readonly scriptExecutionTimestamps: Map<string, number[]> = new Map();\n\n // Metrics\n private metrics: ExecutionMetrics = {\n totalExecutions: 0,\n successCount: 0,\n failureCount: 0,\n timeoutCount: 0,\n averageDuration: 0,\n totalDuration: 0,\n };\n private readonly scriptMetrics: Map<string, ExecutionMetrics> = new Map();\n\n constructor(options: AFSSandboxOptions = {}) {\n super();\n this.options = afsSandboxOptionsSchema.parse(options);\n this.name = options.name ?? \"sandbox\";\n this.description = options.description ?? \"JavaScript sandbox for LLM code execution\";\n this.accessMode = options.accessMode ?? \"readwrite\";\n this.runtime = new SandboxRuntime(options.runtime);\n this.auditConfig = options.audit;\n this.rateLimitConfig = options.rateLimit;\n // Initialize capabilities with undefined AFS (stubs only)\n this.capabilities = createCapabilities(undefined, this.options.capabilities ?? {});\n }\n\n /**\n * Returns the Zod schema for configuration validation\n */\n static schema() {\n return afsSandboxOptionsSchema;\n }\n\n static manifest(): ProviderManifest {\n return {\n name: \"sandbox\",\n description: \"Sandboxed JavaScript execution environment for LLM-generated code\",\n uriTemplate: \"sandbox://\",\n category: \"compute\",\n schema: z.object({}),\n tags: [\"sandbox\", \"compute\", \"javascript\"],\n };\n }\n\n /**\n * Loads a module instance from configuration\n */\n static async load({ config }: AFSModuleLoadParams = {}): Promise<AFSSandbox> {\n const validated = afsSandboxOptionsSchema.parse(config);\n return new AFSSandbox(validated);\n }\n\n /**\n * Called when the module is mounted to AFS\n */\n onMount(afs: AFSRoot): void {\n this.capabilities = createCapabilities(afs, this.options.capabilities ?? {});\n }\n\n // ========== List Handlers ==========\n\n /**\n * List root directory children\n */\n @List(\"/\")\n async listRoot(_ctx: RouteContext): Promise<AFSListResult> {\n return {\n data: [\n this.buildScriptsDirectoryEntry(),\n this.buildTemplatesDirectoryEntry(),\n this.buildMetricsDirectoryEntry(),\n this.buildAuditDirectoryEntry(),\n ],\n };\n }\n\n /**\n * List all scripts\n */\n @List(\"/scripts\")\n async listScripts(_ctx: RouteContext): Promise<AFSListResult> {\n const entries: AFSEntry[] = [];\n for (const [name, script] of this.scripts) {\n entries.push(this.buildScriptEntry(name, script));\n }\n return { data: entries };\n }\n\n /**\n * List script children (@history, @execHistory)\n */\n @List(\"/scripts/:scriptName\")\n async listScript(ctx: RouteContext<{ scriptName: string }>): Promise<AFSListResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path);\n }\n const basePath = joinURL(\"/scripts\", ctx.params.scriptName);\n return {\n data: [\n {\n id: joinURL(basePath, \"@history\"),\n path: joinURL(basePath, \"@history\"),\n summary: \"Version history\",\n meta: { kind: \"sandbox:history\", type: \"history\", count: (script.versions ?? []).length },\n },\n {\n id: joinURL(basePath, \"@execHistory\"),\n path: joinURL(basePath, \"@execHistory\"),\n summary: \"Execution history\",\n meta: {\n kind: \"sandbox:exec-history\",\n type: \"execHistory\",\n count: (script.execHistory ?? []).length,\n },\n },\n ],\n };\n }\n\n /**\n * List @history children (leaf node)\n */\n @List(\"/scripts/:scriptName/@history\")\n async listScriptHistory(ctx: RouteContext<{ scriptName: string }>): Promise<AFSListResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n if (!this.scripts.has(name)) {\n throw new AFSNotFoundError(ctx.path);\n }\n return { data: [] };\n }\n\n /**\n * List @execHistory children (leaf node)\n */\n @List(\"/scripts/:scriptName/@execHistory\")\n async listScriptExecHistoryEntries(\n ctx: RouteContext<{ scriptName: string }>,\n ): Promise<AFSListResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n if (!this.scripts.has(name)) {\n throw new AFSNotFoundError(ctx.path);\n }\n return { data: [] };\n }\n\n /**\n * List all templates\n */\n @List(\"/templates\")\n async listTemplates(_ctx: RouteContext): Promise<AFSListResult> {\n const entries = BUILT_IN_TEMPLATES.map((t) => ({\n id: joinURL(\"/templates\", t.name),\n path: joinURL(\"/templates\", t.name),\n summary: t.description,\n meta: {\n kind: \"sandbox:template\",\n type: \"template\",\n category: t.category,\n variables: t.variables,\n },\n }));\n return { data: entries };\n }\n\n /**\n * List template children (leaf node)\n */\n @List(\"/templates/:templateName\")\n async listTemplate(ctx: RouteContext<{ templateName: string }>): Promise<AFSListResult> {\n const template = BUILT_IN_TEMPLATES.find((t) => t.name === ctx.params.templateName);\n if (!template) {\n throw new AFSNotFoundError(ctx.path);\n }\n return { data: [] };\n }\n\n /**\n * List metrics children\n */\n @List(\"/metrics\")\n async listMetrics(_ctx: RouteContext): Promise<AFSListResult> {\n if (this.scriptMetrics.size === 0) {\n return { data: [] };\n }\n return {\n data: [\n {\n id: \"/metrics/scripts\",\n path: \"/metrics/scripts\",\n summary: \"Per-script execution metrics\",\n meta: {\n kind: \"sandbox:directory\",\n type: \"directory\",\n childrenCount: this.scriptMetrics.size,\n },\n },\n ],\n };\n }\n\n /**\n * List per-script metrics\n */\n @List(\"/metrics/scripts\")\n async listScriptMetrics(_ctx: RouteContext): Promise<AFSListResult> {\n const entries: AFSEntry[] = [];\n for (const [name, metrics] of this.scriptMetrics) {\n entries.push({\n id: joinURL(\"/metrics/scripts\", name),\n path: joinURL(\"/metrics/scripts\", name),\n meta: {\n kind: \"sandbox:metrics\",\n type: \"script-metrics\",\n totalExecutions: metrics.totalExecutions,\n },\n });\n }\n return { data: entries };\n }\n\n /**\n * List audit children (leaf node)\n */\n @List(\"/audit\")\n async listAudit(_ctx: RouteContext): Promise<AFSListResult> {\n return { data: [] };\n }\n\n // ========== Actions Listing ==========\n\n /**\n * List root-level actions\n */\n @Actions(\"/\")\n async listRootActions(_ctx: RouteContext): Promise<AFSListResult> {\n const entries: AFSEntry[] = [\n {\n id: \"run\",\n path: \"/.actions/run\",\n summary: \"Run inline JavaScript code\",\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: \"run\",\n description: \"Execute inline JavaScript code\",\n inputSchema: {\n type: \"object\",\n properties: {\n code: { type: \"string\", description: \"JavaScript code to execute\" },\n args: { type: \"object\", description: \"Arguments to pass to the code\" },\n },\n required: [\"code\"],\n },\n },\n },\n {\n id: \"validate\",\n path: \"/.actions/validate\",\n summary: \"Validate JavaScript syntax\",\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: \"validate\",\n description: \"Check JavaScript code for syntax errors\",\n inputSchema: {\n type: \"object\",\n properties: {\n code: { type: \"string\", description: \"JavaScript code to validate\" },\n },\n required: [\"code\"],\n },\n },\n },\n {\n id: \"promote\",\n path: \"/.actions/promote\",\n summary: \"Promote a script to a formal action\",\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: \"promote\",\n description: \"Promote a tested script to a formal action\",\n inputSchema: {\n type: \"object\",\n properties: {\n script: { type: \"string\", description: \"Script name to promote\" },\n name: { type: \"string\", description: \"Action name\" },\n description: { type: \"string\", description: \"Action description\" },\n inputSchema: { type: \"object\", description: \"JSON schema for inputs\" },\n outputSchema: { type: \"object\", description: \"JSON schema for outputs\" },\n },\n required: [\"script\", \"name\"],\n },\n },\n },\n {\n id: \"create-from-template\",\n path: \"/.actions/create-from-template\",\n summary: \"Create a script from a template\",\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: \"create-from-template\",\n description: \"Create a new script from a template\",\n inputSchema: {\n type: \"object\",\n properties: {\n template: { type: \"string\", description: \"Template name\" },\n name: { type: \"string\", description: \"Script name to create\" },\n variables: { type: \"object\", description: \"Template variables\" },\n },\n required: [\"template\", \"name\"],\n },\n },\n },\n ];\n\n // Add promoted actions\n for (const [actionName, action] of this.promotedActions) {\n entries.push({\n id: actionName,\n path: joinURL(\"/.actions\", actionName),\n summary: action.description ?? `Promoted action: ${actionName}`,\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: actionName,\n description: action.description ?? `Execute ${actionName}`,\n inputSchema: action.inputSchema,\n outputSchema: action.outputSchema,\n },\n });\n }\n\n return { data: entries };\n }\n\n /**\n * List script-level actions\n */\n @Actions(\"/scripts/:scriptName\")\n async listScriptActions(ctx: RouteContext<{ scriptName: string }>): Promise<AFSListResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path);\n }\n\n const basePath = joinURL(\"/scripts\", ctx.params.scriptName, \".actions\");\n return {\n data: [\n {\n id: \"exec\",\n path: joinURL(basePath, \"exec\"),\n summary: `Execute script ${name}`,\n meta: {\n kind: \"afs:executable\",\n kinds: [\"afs:executable\", \"afs:node\"],\n name: \"exec\",\n description: `Execute the ${name} script`,\n inputSchema: {\n type: \"object\",\n description: \"Arguments passed to the script's default export function\",\n },\n },\n },\n ],\n };\n }\n\n // ========== Read Handlers ==========\n\n /**\n * Read root entry\n */\n @Read(\"/\")\n async readRoot(_ctx: RouteContext): Promise<AFSEntry> {\n const actions = [\n { name: \"run\", description: \"Run inline JavaScript code\" },\n { name: \"validate\", description: \"Validate JavaScript syntax\" },\n { name: \"promote\", description: \"Promote a script to a formal action\" },\n { name: \"create-from-template\", description: \"Create a script from a template\" },\n ...Array.from(this.promotedActions.entries()).map(([name, action]) => ({\n name,\n description: action.description ?? `Promoted action: ${name}`,\n })),\n ];\n return {\n id: \"/\",\n path: \"/\",\n meta: { type: \"directory\", childrenCount: 4 },\n actions,\n };\n }\n\n /**\n * Read scripts directory\n */\n @Read(\"/scripts\")\n async readScriptsDir(_ctx: RouteContext): Promise<AFSEntry> {\n return this.buildScriptsDirectoryEntry();\n }\n\n /**\n * Read a specific script\n */\n @Read(\"/scripts/:scriptName\")\n async readScript(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n return this.buildScriptEntry(name, script);\n }\n\n /**\n * Read version history for a script\n */\n @Read(\"/scripts/:scriptName/@history\")\n async readScriptHistory(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const versions = script.versions ?? [];\n return {\n id: joinURL(\"/scripts\", `${name}.js`, \"@history\"),\n path: joinURL(\"/scripts\", `${name}.js`, \"@history\"),\n content: versions,\n meta: { type: \"history\", count: versions.length },\n };\n }\n\n /**\n * Read a specific version\n */\n @Read(\"/scripts/:scriptName/@history/:version\")\n async readScriptVersion(\n ctx: RouteContext<{ scriptName: string; version: string }>,\n ): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const versionNum = Number.parseInt(ctx.params.version, 10);\n if (Number.isNaN(versionNum) || versionNum < 0) {\n throw new AFSNotFoundError(ctx.path, \"Invalid version number\");\n }\n const versions = script.versions ?? [];\n const version = versions.find((v) => v.version === versionNum);\n if (!version) {\n throw new AFSNotFoundError(ctx.path, `Version ${versionNum} not found`);\n }\n return {\n id: joinURL(\"/scripts\", `${name}.js`, \"@history\", String(versionNum)),\n path: joinURL(\"/scripts\", `${name}.js`, \"@history\", String(versionNum)),\n content: version.content,\n meta: {\n type: \"version\",\n version: version.version,\n timestamp: version.timestamp,\n size: version.size,\n },\n };\n }\n\n /**\n * Read execution history for a script\n */\n @Read(\"/scripts/:scriptName/@execHistory\")\n async readScriptExecHistory(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const execHistory = script.execHistory ?? [];\n return {\n id: joinURL(\"/scripts\", `${name}.js`, \"@execHistory\"),\n path: joinURL(\"/scripts\", `${name}.js`, \"@execHistory\"),\n content: execHistory,\n meta: { type: \"execHistory\", count: execHistory.length },\n };\n }\n\n /**\n * Read templates directory\n */\n @Read(\"/templates\")\n async readTemplatesDir(_ctx: RouteContext): Promise<AFSEntry> {\n return this.buildTemplatesDirectoryEntry();\n }\n\n /**\n * Read a specific template\n */\n @Read(\"/templates/:templateName\")\n async readTemplate(ctx: RouteContext<{ templateName: string }>): Promise<AFSEntry> {\n const template = BUILT_IN_TEMPLATES.find((t) => t.name === ctx.params.templateName);\n if (!template) {\n throw new AFSNotFoundError(ctx.path, `Template not found: ${ctx.params.templateName}`);\n }\n return {\n id: joinURL(\"/templates\", template.name),\n path: joinURL(\"/templates\", template.name),\n content: template.content,\n meta: {\n type: \"template\",\n description: template.description,\n category: template.category,\n variables: template.variables,\n },\n };\n }\n\n /**\n * Read metrics\n */\n @Read(\"/metrics\")\n async readMetrics(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/metrics\",\n path: \"/metrics\",\n content: this.metrics,\n meta: { type: \"metrics\" },\n };\n }\n\n /**\n * Read per-script metrics\n */\n @Read(\"/metrics/scripts/:scriptName\")\n async readScriptMetrics(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const scriptMetrics = this.scriptMetrics.get(ctx.params.scriptName);\n if (!scriptMetrics) {\n throw new AFSNotFoundError(ctx.path, `Script metrics not found: ${ctx.params.scriptName}`);\n }\n return {\n id: joinURL(\"/metrics/scripts\", ctx.params.scriptName),\n path: joinURL(\"/metrics/scripts\", ctx.params.scriptName),\n content: { executionCount: scriptMetrics.totalExecutions, ...scriptMetrics },\n meta: { type: \"script-metrics\", scriptName: ctx.params.scriptName },\n };\n }\n\n /**\n * Read audit log\n */\n @Read(\"/audit\")\n async readAudit(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/audit\",\n path: \"/audit\",\n content: this.auditLog,\n meta: { type: \"audit\", count: this.auditLog.length },\n };\n }\n\n // ========== Meta Handlers ==========\n\n /**\n * Root metadata\n */\n @Meta(\"/\")\n async readRootMeta(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/.meta\",\n path: \"/.meta\",\n content: { type: \"directory\", childrenCount: 4 },\n meta: { type: \"directory\", childrenCount: 4 },\n };\n }\n\n /**\n * Scripts directory metadata\n */\n @Meta(\"/scripts\")\n async readScriptsMeta(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/scripts/.meta\",\n path: \"/scripts/.meta\",\n content: { type: \"directory\", childrenCount: this.scripts.size },\n meta: { type: \"directory\", childrenCount: this.scripts.size },\n };\n }\n\n /**\n * Script metadata\n */\n @Meta(\"/scripts/:scriptName\")\n async readScriptMeta(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const entry = this.buildScriptEntry(name, script);\n return {\n id: joinURL(\"/scripts\", ctx.params.scriptName, \".meta\"),\n path: joinURL(\"/scripts\", ctx.params.scriptName, \".meta\"),\n content: entry.meta ?? {},\n meta: entry.meta ?? {},\n };\n }\n\n /**\n * @history metadata\n */\n @Meta(\"/scripts/:scriptName/@history\")\n async readScriptHistoryMeta(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const meta = { type: \"history\", count: (script.versions ?? []).length };\n return {\n id: joinURL(\"/scripts\", ctx.params.scriptName, \"@history\", \".meta\"),\n path: joinURL(\"/scripts\", ctx.params.scriptName, \"@history\", \".meta\"),\n content: meta,\n meta,\n };\n }\n\n /**\n * @execHistory metadata\n */\n @Meta(\"/scripts/:scriptName/@execHistory\")\n async readScriptExecHistoryMeta(ctx: RouteContext<{ scriptName: string }>): Promise<AFSEntry> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n const meta = { type: \"execHistory\", count: (script.execHistory ?? []).length };\n return {\n id: joinURL(\"/scripts\", ctx.params.scriptName, \"@execHistory\", \".meta\"),\n path: joinURL(\"/scripts\", ctx.params.scriptName, \"@execHistory\", \".meta\"),\n content: meta,\n meta,\n };\n }\n\n /**\n * Templates directory metadata\n */\n @Meta(\"/templates\")\n async readTemplatesMeta(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/templates/.meta\",\n path: \"/templates/.meta\",\n content: { type: \"directory\", childrenCount: BUILT_IN_TEMPLATES.length },\n meta: { type: \"directory\", childrenCount: BUILT_IN_TEMPLATES.length },\n };\n }\n\n /**\n * Template metadata\n */\n @Meta(\"/templates/:templateName\")\n async readTemplateMeta(ctx: RouteContext<{ templateName: string }>): Promise<AFSEntry> {\n const template = BUILT_IN_TEMPLATES.find((t) => t.name === ctx.params.templateName);\n if (!template) {\n throw new AFSNotFoundError(ctx.path, `Template not found: ${ctx.params.templateName}`);\n }\n const meta = {\n type: \"template\",\n description: template.description,\n category: template.category,\n variables: template.variables,\n };\n return {\n id: joinURL(\"/templates\", ctx.params.templateName, \".meta\"),\n path: joinURL(\"/templates\", ctx.params.templateName, \".meta\"),\n content: meta,\n meta,\n };\n }\n\n /**\n * Metrics metadata\n */\n @Meta(\"/metrics\")\n async readMetricsMeta(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/metrics/.meta\",\n path: \"/metrics/.meta\",\n content: { type: \"metrics\" },\n meta: { type: \"metrics\" },\n };\n }\n\n /**\n * Audit metadata\n */\n @Meta(\"/audit\")\n async readAuditMeta(_ctx: RouteContext): Promise<AFSEntry> {\n return {\n id: \"/audit/.meta\",\n path: \"/audit/.meta\",\n content: { type: \"audit\", entryCount: this.auditLog.length },\n meta: { type: \"audit\", entryCount: this.auditLog.length },\n };\n }\n\n // ========== Write Handlers ==========\n\n /**\n * Write (create or update) a script\n */\n @Write(\"/scripts/:scriptName\")\n async writeScript(\n ctx: RouteContext<{ scriptName: string }>,\n entry: AFSWriteEntryPayload,\n ): Promise<AFSWriteResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n\n const now = new Date();\n const existing = this.scripts.get(name);\n\n // Handle meta-only writes — preserve existing content\n if (entry.content === undefined && existing) {\n const meta: ScriptMetadata = {\n name,\n createdAt: existing.meta.createdAt,\n updatedAt: now,\n lastRun: existing.meta.lastRun,\n runCount: existing.meta.runCount,\n };\n const storedScript: StoredScript = {\n content: existing.content,\n meta,\n versions: existing.versions,\n execHistory: existing.execHistory,\n };\n this.scripts.set(name, storedScript);\n return {\n data: this.buildScriptEntry(name, storedScript),\n message: \"Script updated\",\n };\n }\n\n const content =\n typeof entry.content === \"string\" ? entry.content : JSON.stringify(entry.content);\n\n // Build version history\n const versions: ScriptVersion[] = existing?.versions ? [...existing.versions] : [];\n const maxVersion = versions.length > 0 ? Math.max(...versions.map((v) => v.version)) : 0;\n const newVersion: ScriptVersion = {\n version: maxVersion + 1,\n content,\n timestamp: now,\n size: new TextEncoder().encode(content).length,\n };\n versions.push(newVersion);\n\n // Keep only last MAX_VERSIONS\n while (versions.length > MAX_VERSIONS) {\n versions.shift();\n }\n\n const meta: ScriptMetadata = {\n name,\n createdAt: existing?.meta.createdAt ?? now,\n updatedAt: now,\n lastRun: existing?.meta.lastRun,\n runCount: existing?.meta.runCount ?? 0,\n };\n\n const storedScript: StoredScript = {\n content,\n meta,\n versions,\n execHistory: existing?.execHistory ?? [],\n };\n this.scripts.set(name, storedScript);\n\n return {\n data: this.buildScriptEntry(name, storedScript),\n message: existing ? \"Script updated\" : \"Script created\",\n };\n }\n\n /**\n * Reject writes to @history paths\n */\n @Write(\"/scripts/:scriptName/@history/:version\")\n async writeScriptHistory(\n _ctx: RouteContext<{ scriptName: string; version: string }>,\n _entry: AFSWriteEntryPayload,\n ): Promise<AFSWriteResult> {\n throw new Error(\"Cannot write to history directly\");\n }\n\n // ========== Delete Handlers ==========\n\n /**\n * Delete a stored script\n */\n @Delete(\"/scripts/:scriptName\")\n async deleteScript(ctx: RouteContext<{ scriptName: string }>): Promise<AFSDeleteResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n if (!this.scripts.has(name)) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n this.scripts.delete(name);\n this.scriptMetrics.delete(name);\n return { message: `Script '${name}' deleted` };\n }\n\n /**\n * Catch-all delete handler for unsupported paths\n */\n @Delete(\"/:path*\")\n async deleteCatchAll(ctx: RouteContext<{ path: string }>): Promise<AFSDeleteResult> {\n throw new AFSNotFoundError(ctx.path);\n }\n\n // ========== Exec Handlers ==========\n\n /**\n * Execute a stored script directly\n */\n @Actions.Exec(\"/scripts/:scriptName\", \"exec\")\n async execScript(\n ctx: RouteContext<{ scriptName: string }>,\n args: Record<string, unknown>,\n ): Promise<AFSExecResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n return {\n success: false,\n data: {\n error: `Script not found: ${name}`,\n logs: [],\n duration: 0,\n },\n };\n }\n\n const options = (ctx.options as { context?: { userId?: string; sessionId?: string } }) ?? {};\n\n // Check rate limit\n const rateCheck = this.checkRateLimit(options.context?.userId, name);\n if (rateCheck.limited) {\n return {\n success: false,\n data: {\n error: `Rate limit exceeded: ${rateCheck.reason}`,\n logs: [],\n duration: 0,\n rateLimited: true,\n },\n };\n }\n\n // Record execution for rate limiting\n this.recordExecution(options.context?.userId, name);\n\n // Update metadata\n script.meta.lastRun = new Date();\n script.meta.runCount++;\n\n // Generate execution context\n const executionId = generateExecutionId();\n const timestamp = Date.now();\n\n const execContext: ExecutionContext = {\n args,\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n timestamp,\n executionId,\n };\n\n // Log audit event\n this.logAudit({\n type: \"execution\",\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n scriptName: name,\n details: { args: sanitizeArgs(args) },\n });\n\n const result = await this.runtime.execute(script.content, this.capabilities, execContext);\n const scriptExecResult = result as ExecutionResult;\n\n // Update metrics\n this.updateMetrics(name, scriptExecResult);\n\n // Record execution history\n const historyEntry: ExecutionHistoryEntry = {\n executionId,\n timestamp: new Date(timestamp),\n success: scriptExecResult.success,\n duration: scriptExecResult.duration,\n error: scriptExecResult.error,\n timedOut: scriptExecResult.timedOut,\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n args: sanitizeArgs(args),\n };\n\n script.execHistory = script.execHistory ?? [];\n script.execHistory.push(historyEntry);\n\n while (script.execHistory.length > MAX_EXEC_HISTORY) {\n script.execHistory.shift();\n }\n\n const { success, ...data } = result as unknown as {\n success: boolean;\n [key: string]: unknown;\n };\n return { success, data: data as Record<string, unknown> };\n }\n\n /**\n * Execute a stored script directly via exec(\"/scripts/:name\")\n */\n @Exec(\"/scripts/:scriptName\")\n async execScriptDirect(\n ctx: RouteContext<{ scriptName: string }>,\n args: Record<string, unknown>,\n ): Promise<AFSExecResult> {\n return this.execScript(ctx, args);\n }\n\n /**\n * Execute root-level actions (run, validate, promote, create-from-template, promoted actions)\n */\n @Actions.Exec(\"/\")\n async execRootAction(\n ctx: RouteContext<{ action: string }>,\n args: Record<string, unknown>,\n ): Promise<AFSExecResult> {\n const actionName = ctx.params.action;\n return this.executeAction(actionName, args, ctx);\n }\n\n // ========== Stat Handlers ==========\n\n /**\n * Stat root → sandbox overview\n */\n @Stat(\"/\")\n async statRoot(_ctx: RouteContext): Promise<AFSStatResult> {\n return {\n data: {\n id: \"/\",\n path: \"/\",\n meta: {\n type: \"directory\",\n childrenCount: 4,\n scriptCount: this.scripts.size,\n templateCount: BUILT_IN_TEMPLATES.length,\n totalExecutions: this.metrics.totalExecutions,\n successCount: this.metrics.successCount,\n failureCount: this.metrics.failureCount,\n },\n },\n };\n }\n\n /**\n * Stat scripts directory\n */\n @Stat(\"/scripts\")\n async statScriptsDir(_ctx: RouteContext): Promise<AFSStatResult> {\n return {\n data: {\n id: \"/scripts\",\n path: \"/scripts\",\n meta: { type: \"directory\", childrenCount: this.scripts.size },\n },\n };\n }\n\n /**\n * Stat a specific script → runCount, lastRun, versionCount\n */\n @Stat(\"/scripts/:scriptName\")\n async statScript(ctx: RouteContext<{ scriptName: string }>): Promise<AFSStatResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n return {\n data: {\n id: joinURL(\"/scripts\", `${name}.js`),\n path: joinURL(\"/scripts\", `${name}.js`),\n createdAt: script.meta.createdAt,\n updatedAt: script.meta.updatedAt,\n meta: {\n type: \"file\",\n kind: \"afs:script\",\n scriptName: name,\n runCount: script.meta.runCount,\n lastRun: script.meta.lastRun ?? null,\n versionCount: (script.versions ?? []).length,\n },\n },\n };\n }\n\n /**\n * Stat templates directory\n */\n @Stat(\"/templates\")\n async statTemplatesDir(_ctx: RouteContext): Promise<AFSStatResult> {\n return {\n data: {\n id: \"/templates\",\n path: \"/templates\",\n meta: { type: \"directory\", childrenCount: BUILT_IN_TEMPLATES.length },\n },\n };\n }\n\n /**\n * Stat a specific template\n */\n @Stat(\"/templates/:templateName\")\n async statTemplate(ctx: RouteContext<{ templateName: string }>): Promise<AFSStatResult> {\n const template = BUILT_IN_TEMPLATES.find((t) => t.name === ctx.params.templateName);\n if (!template) {\n throw new AFSNotFoundError(ctx.path);\n }\n return {\n data: {\n id: joinURL(\"/templates\", template.name),\n path: joinURL(\"/templates\", template.name),\n meta: { type: \"template\", category: template.category },\n },\n };\n }\n\n /**\n * Stat metrics directory\n */\n @Stat(\"/metrics\")\n async statMetricsDir(_ctx: RouteContext): Promise<AFSStatResult> {\n return {\n data: {\n id: \"/metrics\",\n path: \"/metrics\",\n meta: { type: \"metrics\", childrenCount: this.scriptMetrics.size > 0 ? 1 : 0 },\n },\n };\n }\n\n /**\n * Stat audit directory\n */\n @Stat(\"/audit\")\n async statAuditDir(_ctx: RouteContext): Promise<AFSStatResult> {\n return {\n data: {\n id: \"/audit\",\n path: \"/audit\",\n meta: { type: \"audit\", entryCount: this.auditLog.length },\n },\n };\n }\n\n // ========== Explain Handlers ==========\n\n /**\n * Explain root → sandbox overview with security limits, templates, metrics\n */\n @Explain(\"/\")\n async explainRoot(_ctx: RouteContext): Promise<AFSExplainResult> {\n const lines: string[] = [];\n lines.push(`# ${this.name}`);\n lines.push(\"\");\n if (this.description) {\n lines.push(this.description);\n lines.push(\"\");\n }\n lines.push(\"## Overview\");\n lines.push(\"\");\n lines.push(`- **Scripts**: ${this.scripts.size}`);\n lines.push(`- **Templates**: ${BUILT_IN_TEMPLATES.length}`);\n lines.push(`- **Total Executions**: ${this.metrics.totalExecutions}`);\n lines.push(\n `- **Success Rate**: ${this.metrics.totalExecutions > 0 ? ((this.metrics.successCount / this.metrics.totalExecutions) * 100).toFixed(1) : 0}%`,\n );\n lines.push(\"\");\n lines.push(\"## Security & Isolation\");\n lines.push(\"\");\n lines.push(\"Scripts execute in an isolated sandbox environment with:\");\n lines.push(`- **Timeout**: ${this.options.runtime?.timeout ?? 5000}ms`);\n lines.push(`- **Memory Limit**: ${this.options.runtime?.memoryLimit ?? \"default\"}MB`);\n if (this.options.capabilities?.afs) {\n const afsCaps = this.options.capabilities.afs;\n lines.push(`- **AFS Read**: ${afsCaps.read ?? false}`);\n lines.push(`- **AFS Write**: ${afsCaps.write ?? false}`);\n if (afsCaps.allowPaths?.length) {\n lines.push(`- **Allowed Paths**: ${afsCaps.allowPaths.join(\", \")}`);\n }\n if (afsCaps.denyPaths?.length) {\n lines.push(`- **Denied Paths**: ${afsCaps.denyPaths.join(\", \")}`);\n }\n }\n lines.push(\"\");\n lines.push(\"## Templates\");\n lines.push(\"\");\n for (const t of BUILT_IN_TEMPLATES) {\n lines.push(`- **${t.name}** (${t.category}): ${t.description}`);\n }\n lines.push(\"\");\n if (this.scripts.size > 0) {\n lines.push(\"## Scripts\");\n lines.push(\"\");\n for (const [name, script] of this.scripts) {\n const lastRun = script.meta.lastRun ? new Date(script.meta.lastRun).toISOString() : \"never\";\n lines.push(`- **${name}.js**: ${script.meta.runCount} execution(s), last run: ${lastRun}`);\n }\n lines.push(\"\");\n }\n\n return { format: \"markdown\", content: lines.join(\"\\n\") };\n }\n\n /**\n * Explain a specific script → run count, code summary\n */\n @Explain(\"/scripts/:scriptName\")\n async explainScript(ctx: RouteContext<{ scriptName: string }>): Promise<AFSExplainResult> {\n const name = ctx.params.scriptName.replace(/\\.js$/, \"\");\n const script = this.scripts.get(name);\n if (!script) {\n throw new AFSNotFoundError(ctx.path, `Script not found: ${name}`);\n }\n\n const lines: string[] = [];\n lines.push(`# Script: ${name}.js`);\n lines.push(\"\");\n lines.push(\"## Metadata\");\n lines.push(\"\");\n lines.push(`- **Created**: ${new Date(script.meta.createdAt).toISOString()}`);\n lines.push(`- **Updated**: ${new Date(script.meta.updatedAt).toISOString()}`);\n lines.push(`- **Run Count**: ${script.meta.runCount}`);\n lines.push(\n `- **Last Run**: ${script.meta.lastRun ? new Date(script.meta.lastRun).toISOString() : \"never\"}`,\n );\n lines.push(`- **Versions**: ${(script.versions ?? []).length}`);\n lines.push(`- **Size**: ${new TextEncoder().encode(script.content).length} bytes`);\n lines.push(\"\");\n lines.push(\"## Code Summary\");\n lines.push(\"\");\n const codeLines = script.content.split(\"\\n\");\n lines.push(`- **Lines**: ${codeLines.length}`);\n const firstLine = codeLines[0]?.trim() ?? \"\";\n if (firstLine.startsWith(\"//\")) {\n lines.push(`- **Description**: ${firstLine.slice(2).trim()}`);\n }\n lines.push(\"\");\n\n return { format: \"markdown\", content: lines.join(\"\\n\") };\n }\n\n // ========== Capabilities ==========\n\n /**\n * Read /.meta/.capabilities → capabilities manifest with action catalog\n */\n @Read(\"/.meta/.capabilities\")\n async readCapabilities(_ctx: RouteContext): Promise<AFSEntry> {\n const rootActionCatalog = [\n { name: \"run\", description: \"Execute inline JavaScript code\" },\n { name: \"validate\", description: \"Validate JavaScript syntax\" },\n { name: \"promote\", description: \"Promote a script to a formal action\" },\n { name: \"create-from-template\", description: \"Create a script from a template\" },\n ];\n\n // Add promoted actions\n for (const [actionName, action] of this.promotedActions) {\n rootActionCatalog.push({\n name: actionName,\n description: action.description ?? `Promoted action: ${actionName}`,\n });\n }\n\n const manifest: CapabilitiesManifest = {\n schemaVersion: 1,\n provider: this.name,\n description: this.description,\n tools: [],\n operations: this.getOperationsDeclaration(),\n actions: [\n {\n description: \"Root-level sandbox actions\",\n catalog: rootActionCatalog,\n discovery: { pathTemplate: \"/.actions\" },\n },\n {\n kind: \"afs:script\",\n description: \"Script-level actions\",\n catalog: [{ name: \"exec\", description: \"Execute the script\" }],\n discovery: { pathTemplate: \"/scripts/:scriptName/.actions\" },\n },\n ],\n };\n\n return {\n id: \"/.meta/.capabilities\",\n path: \"/.meta/.capabilities\",\n content: manifest,\n meta: {\n kind: \"afs:capabilities\",\n description: \"Sandbox provider capabilities manifest\",\n operations: [\"list\", \"read\", \"write\", \"delete\", \"exec\", \"stat\", \"explain\"],\n },\n };\n }\n\n // ========== Private Helpers ==========\n\n /**\n * Build AFSEntry for a stored script\n */\n private buildScriptEntry(name: string, script: StoredScript): AFSEntry {\n return {\n id: joinURL(\"/scripts\", `${name}.js`),\n path: joinURL(\"/scripts\", `${name}.js`),\n content: script.content,\n createdAt: script.meta.createdAt,\n updatedAt: script.meta.updatedAt,\n meta: {\n type: \"file\",\n kind: \"afs:script\",\n kinds: [\"afs:script\", \"afs:executable\", \"afs:node\"],\n childrenCount: 2,\n scriptName: name,\n lastRun: script.meta.lastRun,\n runCount: script.meta.runCount,\n },\n actions: [{ name: \"exec\", description: `Execute script ${name}` }],\n };\n }\n\n /**\n * Build scripts directory entry\n */\n private buildScriptsDirectoryEntry(): AFSEntry {\n return {\n id: \"/scripts\",\n path: \"/scripts\",\n summary: \"Stored JavaScript scripts\",\n meta: { kind: \"sandbox:directory\", type: \"directory\", childrenCount: this.scripts.size },\n };\n }\n\n /**\n * Build templates directory entry\n */\n private buildTemplatesDirectoryEntry(): AFSEntry {\n return {\n id: \"/templates\",\n path: \"/templates\",\n summary: \"Script templates\",\n meta: {\n kind: \"sandbox:directory\",\n type: \"directory\",\n childrenCount: BUILT_IN_TEMPLATES.length,\n },\n };\n }\n\n /**\n * Build metrics directory entry\n */\n private buildMetricsDirectoryEntry(): AFSEntry {\n return {\n id: \"/metrics\",\n path: \"/metrics\",\n summary: \"Execution metrics\",\n meta: {\n kind: \"sandbox:directory\",\n type: \"metrics\",\n childrenCount: this.scriptMetrics.size > 0 ? 1 : 0,\n },\n };\n }\n\n /**\n * Build audit directory entry\n */\n private buildAuditDirectoryEntry(): AFSEntry {\n return {\n id: \"/audit\",\n path: \"/audit\",\n summary: \"Audit log\",\n meta: { kind: \"sandbox:directory\", type: \"audit\", entryCount: this.auditLog.length },\n };\n }\n\n /**\n * Log an audit event\n */\n private logAudit(event: Omit<AuditEvent, \"timestamp\">): void {\n if (!this.auditConfig?.enabled) return;\n\n const fullEvent: AuditEvent = {\n ...event,\n timestamp: Date.now(),\n };\n\n this.auditLog.push(fullEvent);\n const maxEntries = this.auditConfig.maxEntries ?? 1000;\n while (this.auditLog.length > maxEntries) {\n this.auditLog.shift();\n }\n\n if (this.auditConfig.onEvent) {\n try {\n this.auditConfig.onEvent(fullEvent);\n } catch {\n // Ignore callback errors\n }\n }\n }\n\n /**\n * Check if execution is rate limited\n */\n private checkRateLimit(\n userId?: string,\n scriptName?: string,\n ): { limited: boolean; reason?: string } {\n if (!this.rateLimitConfig) return { limited: false };\n\n const now = Date.now();\n const oneMinuteAgo = now - 60000;\n const cleanTimestamps = (arr: number[]) => arr.filter((t) => t > oneMinuteAgo);\n\n if (this.rateLimitConfig.maxExecutionsPerMinute) {\n const recentExecutions = cleanTimestamps(this.executionTimestamps);\n this.executionTimestamps.length = 0;\n this.executionTimestamps.push(...recentExecutions);\n if (recentExecutions.length >= this.rateLimitConfig.maxExecutionsPerMinute) {\n return { limited: true, reason: \"Global rate limit exceeded\" };\n }\n }\n\n if (userId && this.rateLimitConfig.maxExecutionsPerMinutePerUser) {\n const userTimestamps = cleanTimestamps(this.userExecutionTimestamps.get(userId) ?? []);\n this.userExecutionTimestamps.set(userId, userTimestamps);\n if (userTimestamps.length >= this.rateLimitConfig.maxExecutionsPerMinutePerUser) {\n return { limited: true, reason: \"Per-user rate limit exceeded\" };\n }\n }\n\n if (scriptName && this.rateLimitConfig.maxExecutionsPerMinutePerScript) {\n const scriptTimestamps = cleanTimestamps(\n this.scriptExecutionTimestamps.get(scriptName) ?? [],\n );\n this.scriptExecutionTimestamps.set(scriptName, scriptTimestamps);\n if (scriptTimestamps.length >= this.rateLimitConfig.maxExecutionsPerMinutePerScript) {\n return { limited: true, reason: \"Per-script rate limit exceeded\" };\n }\n }\n\n return { limited: false };\n }\n\n /**\n * Record execution for rate limiting\n */\n private recordExecution(userId?: string, scriptName?: string): void {\n const now = Date.now();\n this.executionTimestamps.push(now);\n\n if (userId) {\n const userTimestamps = this.userExecutionTimestamps.get(userId) ?? [];\n userTimestamps.push(now);\n this.userExecutionTimestamps.set(userId, userTimestamps);\n }\n\n if (scriptName) {\n const scriptTimestamps = this.scriptExecutionTimestamps.get(scriptName) ?? [];\n scriptTimestamps.push(now);\n this.scriptExecutionTimestamps.set(scriptName, scriptTimestamps);\n }\n }\n\n /**\n * Update execution metrics\n */\n private updateMetrics(scriptName: string | undefined, result: ExecutionResult): void {\n this.metrics.totalExecutions++;\n this.metrics.totalDuration += result.duration;\n this.metrics.averageDuration = this.metrics.totalDuration / this.metrics.totalExecutions;\n\n if (result.success) {\n this.metrics.successCount++;\n } else {\n this.metrics.failureCount++;\n }\n\n if (result.timedOut) {\n this.metrics.timeoutCount++;\n }\n\n if (scriptName) {\n let scriptMetrics = this.scriptMetrics.get(scriptName);\n if (!scriptMetrics) {\n scriptMetrics = {\n totalExecutions: 0,\n successCount: 0,\n failureCount: 0,\n timeoutCount: 0,\n averageDuration: 0,\n totalDuration: 0,\n };\n this.scriptMetrics.set(scriptName, scriptMetrics);\n }\n\n scriptMetrics.totalExecutions++;\n scriptMetrics.totalDuration += result.duration;\n scriptMetrics.averageDuration = scriptMetrics.totalDuration / scriptMetrics.totalExecutions;\n\n if (result.success) {\n scriptMetrics.successCount++;\n } else {\n scriptMetrics.failureCount++;\n }\n\n if (result.timedOut) {\n scriptMetrics.timeoutCount++;\n }\n }\n }\n\n /**\n * Validate action name\n */\n private isValidActionName(name: string): { valid: boolean; error?: string } {\n if (!name || typeof name !== \"string\") {\n return { valid: false, error: \"Action name is required\" };\n }\n if (RESERVED_ACTION_NAMES.includes(name)) {\n return { valid: false, error: `Action name \"${name}\" is reserved` };\n }\n if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)) {\n return {\n valid: false,\n error:\n \"Action name must start with a letter and contain only letters, numbers, hyphens, and underscores\",\n };\n }\n if (name.includes(\"..\") || name.includes(\"/\") || name.includes(\"\\\\\")) {\n return { valid: false, error: \"Action name cannot contain path separators\" };\n }\n return { valid: true };\n }\n\n /**\n * Apply template variables to content\n */\n private applyTemplate(content: string, variables: Record<string, string>): string {\n let result = content;\n for (const [key, value] of Object.entries(variables)) {\n result = result.replace(new RegExp(`\\\\{\\\\{${key}\\\\}\\\\}`, \"g\"), value);\n }\n return result;\n }\n\n /**\n * Execute a built-in or promoted action\n */\n private async executeAction(\n actionName: string,\n args: Record<string, unknown>,\n ctx: RouteContext,\n ): Promise<AFSExecResult> {\n const options = (ctx.options as { context?: { userId?: string; sessionId?: string } }) ?? {};\n\n if (actionName === \"run\") {\n const code = args.code;\n if (typeof code !== \"string\") {\n throw new Error(\"action 'run' requires 'code' parameter as string\");\n }\n\n const rateCheck = this.checkRateLimit(options.context?.userId, undefined);\n if (rateCheck.limited) {\n return {\n success: false,\n data: {\n error: `Rate limit exceeded: ${rateCheck.reason}`,\n logs: [],\n duration: 0,\n rateLimited: true,\n },\n };\n }\n\n this.recordExecution(options.context?.userId, undefined);\n\n const executionId = generateExecutionId();\n const timestamp = Date.now();\n\n const execContext: ExecutionContext = {\n args: (args.args as Record<string, unknown>) ?? {},\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n timestamp,\n executionId,\n };\n\n this.logAudit({\n type: \"execution\",\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n actionName: \"run\",\n details: { codeLength: code.length },\n });\n\n const result = await this.runtime.execute(code, this.capabilities, execContext);\n const runExecResult = result as ExecutionResult;\n\n this.updateMetrics(undefined, runExecResult);\n\n const { success: runSuccess, ...runData } = result as unknown as {\n success: boolean;\n [key: string]: unknown;\n };\n return { success: runSuccess, data: runData as Record<string, unknown> };\n }\n\n if (actionName === \"validate\") {\n const code = args.code;\n if (typeof code !== \"string\") {\n throw new Error(\"action 'validate' requires 'code' parameter as string\");\n }\n\n try {\n new Function(`\"use strict\"; return async () => { ${code} }`);\n return {\n success: true,\n data: { valid: true, message: \"Syntax is valid\" },\n };\n } catch (error) {\n return {\n success: true,\n data: {\n valid: false,\n error: error instanceof Error ? error.message : String(error),\n },\n };\n }\n }\n\n if (actionName === \"rollback\") {\n const scriptName = args.script;\n const version = args.version;\n\n if (typeof scriptName !== \"string\") {\n throw new Error(\"action 'rollback' requires 'script' parameter as string\");\n }\n if (typeof version !== \"number\" || version < 1) {\n throw new Error(\"action 'rollback' requires 'version' parameter as positive number\");\n }\n\n const script = this.scripts.get(scriptName);\n if (!script) {\n return { success: false, data: { error: `Script not found: ${scriptName}` } };\n }\n\n const versions = script.versions ?? [];\n const targetVersion = versions.find((v) => v.version === version);\n if (!targetVersion) {\n return { success: false, data: { error: `Version ${version} not found` } };\n }\n\n await this.writeScript(\n {\n path: joinURL(\"/scripts\", `${scriptName}.js`),\n params: { scriptName: `${scriptName}.js` },\n options: {},\n },\n { content: targetVersion.content },\n );\n\n return {\n success: true,\n data: {\n message: `Rolled back to version ${version}`,\n newVersion: script.versions?.length ?? 0,\n },\n };\n }\n\n if (actionName === \"promote\") {\n const scriptName = args.script as string | undefined;\n const actionNameArg = args.name as string | undefined;\n\n if (!scriptName || typeof scriptName !== \"string\") {\n return {\n success: false,\n data: { error: \"action 'promote' requires 'script' parameter as string\" },\n };\n }\n if (!actionNameArg || typeof actionNameArg !== \"string\") {\n return {\n success: false,\n data: { error: \"action 'promote' requires 'name' parameter as string\" },\n };\n }\n\n const nameValidation = this.isValidActionName(actionNameArg);\n if (!nameValidation.valid) {\n return { success: false, data: { error: nameValidation.error } };\n }\n\n const script = this.scripts.get(scriptName);\n if (!script) {\n return { success: false, data: { error: `Script not found: ${scriptName}` } };\n }\n\n try {\n new Function(`\"use strict\"; return async () => { ${script.content} }`);\n } catch (error) {\n return {\n success: false,\n data: {\n error: `Script has syntax error: ${error instanceof Error ? error.message : String(error)}`,\n },\n };\n }\n\n const currentVersion = script.versions?.length\n ? Math.max(...script.versions.map((v) => v.version))\n : 1;\n\n const existing = this.promotedActions.get(actionNameArg);\n const promotedAction: PromotedAction = {\n name: actionNameArg,\n description: (args.description as string) ?? existing?.description,\n sourceScript: scriptName,\n sourceVersion: currentVersion,\n inputSchema: (args.inputSchema as Record<string, unknown>) ?? existing?.inputSchema,\n outputSchema: (args.outputSchema as Record<string, unknown>) ?? existing?.outputSchema,\n promotedAt: new Date(),\n version: (existing?.version ?? 0) + 1,\n };\n\n this.promotedActions.set(actionNameArg, promotedAction);\n\n this.logAudit({\n type: \"action_promote\",\n actionName: actionNameArg,\n scriptName,\n details: { version: promotedAction.version },\n });\n\n return {\n success: true,\n data: {\n message: `Script '${scriptName}' promoted to action '${actionNameArg}' (version ${promotedAction.version})`,\n action: promotedAction,\n },\n };\n }\n\n if (actionName === \"create-from-template\") {\n const templateName = args.template as string | undefined;\n const scriptName = args.name as string | undefined;\n const variables = (args.variables as Record<string, string>) ?? {};\n\n if (!templateName || typeof templateName !== \"string\") {\n return {\n success: false,\n data: { error: \"action 'create-from-template' requires 'template' parameter as string\" },\n };\n }\n if (!scriptName || typeof scriptName !== \"string\") {\n return {\n success: false,\n data: { error: \"action 'create-from-template' requires 'name' parameter as string\" },\n };\n }\n\n if (\n templateName.includes(\"..\") ||\n templateName.includes(\"/\") ||\n templateName.includes(\"\\\\\")\n ) {\n return { success: false, data: { error: \"Invalid template name\" } };\n }\n\n const template = BUILT_IN_TEMPLATES.find((t) => t.name === templateName);\n if (!template) {\n return { success: false, data: { error: `Template not found: ${templateName}` } };\n }\n\n if (template.variables) {\n for (const v of template.variables) {\n if (v.required && variables[v.name] === undefined && v.default === undefined) {\n return { success: false, data: { error: `Missing required variable: ${v.name}` } };\n }\n }\n for (const v of template.variables) {\n if (variables[v.name] === undefined && v.default !== undefined) {\n variables[v.name] = v.default;\n }\n }\n }\n\n const content = this.applyTemplate(template.content, variables);\n\n await this.writeScript(\n {\n path: joinURL(\"/scripts\", `${scriptName}.js`),\n params: { scriptName: `${scriptName}.js` },\n options: {},\n },\n { content },\n );\n\n return {\n success: true,\n data: {\n message: `Script '${scriptName}' created from template '${templateName}'`,\n path: joinURL(\"/scripts\", `${scriptName}.js`),\n },\n };\n }\n\n // Check if it's a promoted action\n const promotedAction = this.promotedActions.get(actionName);\n if (promotedAction) {\n const script = this.scripts.get(promotedAction.sourceScript);\n if (!script) {\n return {\n success: false,\n data: {\n error: `Source script not found: ${promotedAction.sourceScript}`,\n logs: [],\n duration: 0,\n },\n };\n }\n\n const rateCheck = this.checkRateLimit(options.context?.userId, promotedAction.sourceScript);\n if (rateCheck.limited) {\n return {\n success: false,\n data: {\n error: `Rate limit exceeded: ${rateCheck.reason}`,\n logs: [],\n duration: 0,\n rateLimited: true,\n },\n };\n }\n\n this.recordExecution(options.context?.userId, promotedAction.sourceScript);\n\n const executionId = generateExecutionId();\n const timestamp = Date.now();\n\n const execContext: ExecutionContext = {\n args,\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n timestamp,\n executionId,\n };\n\n this.logAudit({\n type: \"execution\",\n userId: options.context?.userId,\n sessionId: options.context?.sessionId,\n actionName,\n scriptName: promotedAction.sourceScript,\n details: { args: sanitizeArgs(args) },\n });\n\n const result = await this.runtime.execute(script.content, this.capabilities, execContext);\n const promotedExecResult = result as ExecutionResult;\n\n this.updateMetrics(promotedAction.sourceScript, promotedExecResult);\n\n const { success: promotedSuccess, ...promotedData } = result as unknown as {\n success: boolean;\n [key: string]: unknown;\n };\n return { success: promotedSuccess, data: promotedData as Record<string, unknown> };\n }\n\n throw new Error(`Unknown action: ${actionName}`);\n }\n}\n\n// Type check to ensure AFSSandbox implements AFSModuleClass\nconst _typeCheck: AFSModuleClass<AFSSandbox, AFSSandboxOptions> = AFSSandbox;\n\nexport default AFSSandbox;\n"],"mappings":";;;;;;;;;;AAYA,SAAS,oBAAoB,MAAc,UAA6B;AACtE,MAAK,MAAM,WAAW,UAAU;AAE9B,MAAI,YAAY,OAAO,YAAY,KAAM,QAAO;AAChD,MAAI,QAAQ,SAAS,MAAM,IAAI,KAAK,WAAW,QAAQ,MAAM,GAAG,GAAG,CAAC,CAClE,QAAO;AAET,MAAI,QAAQ,SAAS,KAAK,IAAI,KAAK,WAAW,QAAQ,MAAM,GAAG,GAAG,CAAC,EAAE;GAEnE,MAAM,OAAO,KAAK,MAAM,QAAQ,SAAS,EAAE;AAC3C,OAAI,CAAC,KAAK,SAAS,IAAI,IAAI,SAAS,GAAI,QAAO;;AAEjD,MAAI,SAAS,QAAS,QAAO;AAC7B,MAAI,KAAK,WAAW,GAAG,QAAQ,GAAG,CAAE,QAAO;;AAE7C,QAAO;;;;;AAMT,SAAS,cAAc,MAAc,YAAuB,WAA+B;AAEzF,KAAI,aAAa,UAAU,SAAS,KAAK,oBAAoB,MAAM,UAAU,CAC3E,QAAO;AAIT,KAAI,cAAc,WAAW,SAAS,EACpC,QAAO,oBAAoB,MAAM,WAAW;AAI9C,QAAO;;;;;;AAOT,SAAS,cAAc,MAAsB;AAE3C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;YAmBrC,KAAK,oCAAoC;YAmBzC,KAAK,aAAa;YAalB,KAAK,2BAA2B;YAuBhC,KAAK,WAAW;YAahB,KAAK,SAAS;YAed,MAAM,uBAAuB;YA4E7B,MAAM,yCAAyC;YAa/C,OAAO,uBAAuB;YAc9B,OAAO,UAAU;YAUjB,QAAQ,KAAK,wBAAwB,OAAO;YAkG5C,KAAK,uBAAuB;YAW5B,QAAQ,KAAK,IAAI;YAcjB,KAAK,IAAI;YAsBT,KAAK,WAAW;YAchB,KAAK,uBAAuB;YA4B5B,KAAK,aAAa;YAclB,KAAK,2BAA2B;YAkBhC,KAAK,WAAW;YAchB,KAAK,SAAS;YAgBd,QAAQ,IAAI;YAyDZ,QAAQ,uBAAuB;YAwC/B,KAAK,uBAAuB;AAwnB/B,kBAAe"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aigne/afs-sandbox",
|
|
3
|
-
"version": "1.11.0-beta.
|
|
3
|
+
"version": "1.11.0-beta.8",
|
|
4
4
|
"description": "AIGNE AFS sandbox provider for executing JavaScript code in isolated environments",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"publishConfig": {
|
|
@@ -35,8 +35,8 @@
|
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"quickjs-emscripten": "^0.31.0",
|
|
37
37
|
"ufo": "^1.6.3",
|
|
38
|
-
"zod": "^
|
|
39
|
-
"@aigne/afs": "^1.11.0-beta.
|
|
38
|
+
"zod": "^4.0.0",
|
|
39
|
+
"@aigne/afs": "^1.11.0-beta.8"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"@types/bun": "^1.3.6",
|
|
@@ -44,8 +44,8 @@
|
|
|
44
44
|
"rimraf": "^6.1.2",
|
|
45
45
|
"tsdown": "0.20.0-beta.3",
|
|
46
46
|
"typescript": "5.9.2",
|
|
47
|
-
"@aigne/afs-json": "1.11.0-beta.
|
|
48
|
-
"@aigne/afs-testing": "1.11.0-beta.
|
|
47
|
+
"@aigne/afs-json": "1.11.0-beta.8",
|
|
48
|
+
"@aigne/afs-testing": "1.11.0-beta.8",
|
|
49
49
|
"@aigne/scripts": "0.0.0",
|
|
50
50
|
"@aigne/typescript-config": "0.0.0"
|
|
51
51
|
},
|