@loopstack/sandbox-filesystem 0.5.5 → 0.5.7

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/package.json CHANGED
@@ -7,7 +7,7 @@
7
7
  "filesystem",
8
8
  "sandbox"
9
9
  ],
10
- "version": "0.5.5",
10
+ "version": "0.5.7",
11
11
  "license": "MIT",
12
12
  "author": {
13
13
  "name": "Tobias Blättermann, Jakob Klippel"
@@ -15,8 +15,7 @@
15
15
  "main": "dist/index.js",
16
16
  "types": "dist/index.d.ts",
17
17
  "exports": {
18
- ".": "./dist/index.js",
19
- "./src/*": "./src/*"
18
+ ".": "./dist/index.js"
20
19
  },
21
20
  "scripts": {
22
21
  "build": "nest build",
@@ -27,14 +26,13 @@
27
26
  "watch": "nest build --watch"
28
27
  },
29
28
  "dependencies": {
30
- "@loopstack/common": "^0.27.0",
31
- "@loopstack/sandbox-tool": "^0.5.5",
29
+ "@loopstack/common": "^0.29.0",
30
+ "@loopstack/sandbox-tool": "^0.5.7",
32
31
  "@nestjs/common": "^11.1.19",
33
32
  "zod": "^4.3.6"
34
33
  },
35
34
  "files": [
36
- "dist",
37
- "src"
35
+ "dist"
38
36
  ],
39
37
  "jest": {
40
38
  "testEnvironment": "node",
@@ -55,7 +53,6 @@
55
53
  }
56
54
  ],
57
55
  "installModes": [
58
- "add",
59
56
  "install"
60
57
  ]
61
58
  }
package/src/index.ts DELETED
@@ -1,8 +0,0 @@
1
- export * from './sandbox-filesystem.module';
2
- export * from './tools/sandbox-read-file.tool';
3
- export * from './tools/sandbox-write-file.tool';
4
- export * from './tools/sandbox-list-directory.tool';
5
- export * from './tools/sandbox-create-directory.tool';
6
- export * from './tools/sandbox-delete.tool';
7
- export * from './tools/sandbox-exists.tool';
8
- export * from './tools/sandbox-file-info.tool';
@@ -1,32 +0,0 @@
1
- import { Module } from '@nestjs/common';
2
- import { SandboxToolModule } from '@loopstack/sandbox-tool';
3
- import { SandboxCreateDirectory } from './tools/sandbox-create-directory.tool';
4
- import { SandboxDelete } from './tools/sandbox-delete.tool';
5
- import { SandboxExists } from './tools/sandbox-exists.tool';
6
- import { SandboxFileInfo } from './tools/sandbox-file-info.tool';
7
- import { SandboxListDirectory } from './tools/sandbox-list-directory.tool';
8
- import { SandboxReadFile } from './tools/sandbox-read-file.tool';
9
- import { SandboxWriteFile } from './tools/sandbox-write-file.tool';
10
-
11
- @Module({
12
- imports: [SandboxToolModule],
13
- providers: [
14
- SandboxReadFile,
15
- SandboxWriteFile,
16
- SandboxListDirectory,
17
- SandboxCreateDirectory,
18
- SandboxDelete,
19
- SandboxExists,
20
- SandboxFileInfo,
21
- ],
22
- exports: [
23
- SandboxReadFile,
24
- SandboxWriteFile,
25
- SandboxListDirectory,
26
- SandboxCreateDirectory,
27
- SandboxDelete,
28
- SandboxExists,
29
- SandboxFileInfo,
30
- ],
31
- })
32
- export class SandboxFilesystemModule {}
@@ -1,73 +0,0 @@
1
- import { Logger } from '@nestjs/common';
2
- import { z } from 'zod';
3
- import { BaseTool, InjectTool, Tool, ToolResult } from '@loopstack/common';
4
- import { SandboxCommand } from '@loopstack/sandbox-tool';
5
-
6
- const inputSchema = z
7
- .object({
8
- containerId: z.string().describe('The ID of the container to create the directory in'),
9
- path: z.string().describe('The path of the directory to create'),
10
- recursive: z.boolean().default(true).describe("Whether to create parent directories if they don't exist"),
11
- })
12
- .strict();
13
-
14
- type SandboxCreateDirectoryArgs = z.infer<typeof inputSchema>;
15
-
16
- interface SandboxCreateDirectoryResult {
17
- path: string;
18
- created: boolean;
19
- }
20
-
21
- @Tool({
22
- uiConfig: {
23
- description: 'Create a directory in a sandbox container',
24
- },
25
- schema: inputSchema,
26
- })
27
- export class SandboxCreateDirectory extends BaseTool {
28
- private readonly logger = new Logger(SandboxCreateDirectory.name);
29
-
30
- @InjectTool() private sandboxCommand: SandboxCommand;
31
-
32
- async call(args: SandboxCreateDirectoryArgs): Promise<ToolResult<SandboxCreateDirectoryResult>> {
33
- const { containerId, path: dirPath, recursive } = args;
34
-
35
- this.logger.debug(`Creating directory ${dirPath} in container ${containerId} (recursive: ${recursive})`);
36
-
37
- const mkdirArgs = recursive ? ['-p', dirPath] : [dirPath];
38
-
39
- const result = await this.sandboxCommand.call({
40
- containerId,
41
- executable: 'mkdir',
42
- args: mkdirArgs,
43
- workingDirectory: '/',
44
- timeout: 10000,
45
- });
46
-
47
- if (!result.data) {
48
- this.logger.error(`Failed to create directory ${dirPath}: No result data`);
49
- throw new Error(`Failed to create directory ${dirPath}: No result data`);
50
- }
51
-
52
- // Exit code 0 means success, exit code 1 with "File exists" is okay if directory already exists
53
- const alreadyExists = result.data.exitCode !== 0 && result.data.stderr.includes('File exists');
54
-
55
- if (result.data.exitCode !== 0 && !alreadyExists) {
56
- this.logger.error(`Failed to create directory ${dirPath}: ${result.data.stderr || 'Unknown error'}`);
57
- throw new Error(`Failed to create directory ${dirPath}: ${result.data.stderr || 'Unknown error'}`);
58
- }
59
-
60
- if (alreadyExists) {
61
- this.logger.debug(`Directory ${dirPath} already exists`);
62
- } else {
63
- this.logger.log(`Successfully created directory ${dirPath} in container ${containerId}`);
64
- }
65
-
66
- return {
67
- data: {
68
- path: dirPath,
69
- created: result.data.exitCode === 0,
70
- },
71
- };
72
- }
73
- }
@@ -1,70 +0,0 @@
1
- import { Logger } from '@nestjs/common';
2
- import { z } from 'zod';
3
- import { BaseTool, InjectTool, Tool, ToolResult } from '@loopstack/common';
4
- import { SandboxCommand } from '@loopstack/sandbox-tool';
5
-
6
- const inputSchema = z
7
- .object({
8
- containerId: z.string().describe('The ID of the container to delete the file/directory from'),
9
- path: z.string().describe('The path to the file or directory to delete'),
10
- recursive: z.boolean().default(false).describe('Whether to recursively delete directories and their contents'),
11
- force: z.boolean().default(false).describe('Whether to force deletion without prompting for confirmation'),
12
- })
13
- .strict();
14
-
15
- type SandboxDeleteArgs = z.infer<typeof inputSchema>;
16
-
17
- interface SandboxDeleteResult {
18
- path: string;
19
- deleted: boolean;
20
- }
21
-
22
- @Tool({
23
- uiConfig: {
24
- description: 'Delete a file or directory in a sandbox container',
25
- },
26
- schema: inputSchema,
27
- })
28
- export class SandboxDelete extends BaseTool {
29
- private readonly logger = new Logger(SandboxDelete.name);
30
-
31
- @InjectTool() private sandboxCommand: SandboxCommand;
32
-
33
- async call(args: SandboxDeleteArgs): Promise<ToolResult<SandboxDeleteResult>> {
34
- const { containerId, path: targetPath, recursive, force } = args;
35
-
36
- this.logger.debug(`Deleting ${targetPath} in container ${containerId} (recursive: ${recursive}, force: ${force})`);
37
-
38
- const rmArgs: string[] = [];
39
- if (recursive) rmArgs.push('-r');
40
- if (force) rmArgs.push('-f');
41
- rmArgs.push(targetPath);
42
-
43
- const result = await this.sandboxCommand.call({
44
- containerId,
45
- executable: 'rm',
46
- args: rmArgs,
47
- workingDirectory: '/',
48
- timeout: 30000,
49
- });
50
-
51
- if (!result.data) {
52
- this.logger.error(`Failed to delete ${targetPath}: No result data`);
53
- throw new Error(`Failed to delete ${targetPath}: No result data`);
54
- }
55
-
56
- if (result.data.exitCode !== 0) {
57
- this.logger.error(`Failed to delete ${targetPath}: ${result.data.stderr || 'Unknown error'}`);
58
- throw new Error(`Failed to delete ${targetPath}: ${result.data.stderr || 'Unknown error'}`);
59
- }
60
-
61
- this.logger.log(`Successfully deleted ${targetPath} in container ${containerId}`);
62
-
63
- return {
64
- data: {
65
- path: targetPath,
66
- deleted: true,
67
- },
68
- };
69
- }
70
- }
@@ -1,86 +0,0 @@
1
- import { Logger } from '@nestjs/common';
2
- import { z } from 'zod';
3
- import { BaseTool, InjectTool, Tool, ToolResult } from '@loopstack/common';
4
- import { SandboxCommand } from '@loopstack/sandbox-tool';
5
-
6
- const inputSchema = z
7
- .object({
8
- containerId: z.string().describe('The ID of the container to check for file existence'),
9
- path: z.string().describe('The path to check for existence'),
10
- })
11
- .strict();
12
-
13
- type SandboxExistsArgs = z.infer<typeof inputSchema>;
14
-
15
- interface SandboxExistsResult {
16
- path: string;
17
- exists: boolean;
18
- type: 'file' | 'directory' | 'symlink' | 'other' | null;
19
- }
20
-
21
- @Tool({
22
- uiConfig: {
23
- description: 'Check if a file or directory exists in a sandbox container',
24
- },
25
- schema: inputSchema,
26
- })
27
- export class SandboxExists extends BaseTool {
28
- private readonly logger = new Logger(SandboxExists.name);
29
-
30
- @InjectTool()
31
- private sandboxCommand: SandboxCommand;
32
-
33
- async call(args: SandboxExistsArgs): Promise<ToolResult<SandboxExistsResult>> {
34
- const { containerId, path: targetPath } = args;
35
-
36
- this.logger.debug(`Checking existence of ${targetPath} in container ${containerId}`);
37
-
38
- // Use test command to check existence and stat to get type
39
- const result = await this.sandboxCommand.call({
40
- containerId,
41
- executable: 'sh',
42
- args: [
43
- '-c',
44
- `if [ -e '${targetPath.replace(/'/g, "'\\''")}' ]; then stat -c '%F' '${targetPath.replace(/'/g, "'\\''")}'; else echo 'NOT_FOUND'; fi`,
45
- ],
46
- workingDirectory: '/',
47
- timeout: 10000,
48
- });
49
-
50
- if (!result.data) {
51
- this.logger.error(`Failed to check existence of ${targetPath}: No result data`);
52
- throw new Error(`Failed to check existence of ${targetPath}: No result data`);
53
- }
54
-
55
- if (result.data.exitCode !== 0) {
56
- this.logger.error(`Failed to check existence of ${targetPath}: ${result.data.stderr || 'Unknown error'}`);
57
- throw new Error(`Failed to check existence of ${targetPath}: ${result.data.stderr || 'Unknown error'}`);
58
- }
59
-
60
- const output = result.data.stdout.trim();
61
- const exists = output !== 'NOT_FOUND';
62
-
63
- let type: SandboxExistsResult['type'] = null;
64
- if (exists) {
65
- type = this.parseFileType(output);
66
- }
67
-
68
- this.logger.debug(`Path ${targetPath} exists: ${exists}${exists ? `, type: ${type}` : ''}`);
69
-
70
- return {
71
- data: {
72
- path: targetPath,
73
- exists,
74
- type,
75
- },
76
- };
77
- }
78
-
79
- private parseFileType(statOutput: string): SandboxExistsResult['type'] {
80
- const lower = statOutput.toLowerCase();
81
- if (lower.includes('regular')) return 'file';
82
- if (lower.includes('directory')) return 'directory';
83
- if (lower.includes('symbolic link')) return 'symlink';
84
- return 'other';
85
- }
86
- }
@@ -1,102 +0,0 @@
1
- import { Logger } from '@nestjs/common';
2
- import { z } from 'zod';
3
- import { BaseTool, InjectTool, Tool, ToolResult } from '@loopstack/common';
4
- import { SandboxCommand } from '@loopstack/sandbox-tool';
5
-
6
- const inputSchema = z
7
- .object({
8
- containerId: z.string().describe('The ID of the container to get file info from'),
9
- path: z.string().describe('The path to the file or directory'),
10
- })
11
- .strict();
12
-
13
- type SandboxFileInfoArgs = z.infer<typeof inputSchema>;
14
-
15
- interface SandboxFileInfoResult {
16
- path: string;
17
- name: string;
18
- type: 'file' | 'directory' | 'symlink' | 'other';
19
- size: number;
20
- permissions: string;
21
- owner: string;
22
- group: string;
23
- modifiedAt: string;
24
- accessedAt: string;
25
- createdAt: string;
26
- }
27
-
28
- @Tool({
29
- uiConfig: {
30
- description: 'Get detailed information about a file or directory in a sandbox container',
31
- },
32
- schema: inputSchema,
33
- })
34
- export class SandboxFileInfo extends BaseTool {
35
- private readonly logger = new Logger(SandboxFileInfo.name);
36
-
37
- @InjectTool() private sandboxCommand: SandboxCommand;
38
-
39
- async call(args: SandboxFileInfoArgs): Promise<ToolResult<SandboxFileInfoResult>> {
40
- const { containerId, path: targetPath } = args;
41
-
42
- this.logger.debug(`Getting file info for ${targetPath} in container ${containerId}`);
43
-
44
- // Use stat to get detailed file information
45
- // Format: type|size|permissions|owner|group|mtime|atime|ctime
46
- const result = await this.sandboxCommand.call({
47
- containerId,
48
- executable: 'stat',
49
- args: ['-c', '%F|%s|%A|%U|%G|%y|%x|%w', targetPath],
50
- workingDirectory: '/',
51
- timeout: 10000,
52
- });
53
-
54
- if (!result.data) {
55
- this.logger.error(`Failed to get file info for ${targetPath}: No result data`);
56
- throw new Error(`Failed to get file info for ${targetPath}: No result data`);
57
- }
58
-
59
- if (result.data.exitCode !== 0) {
60
- this.logger.error(`Failed to get file info for ${targetPath}: ${result.data.stderr || 'Unknown error'}`);
61
- throw new Error(`Failed to get file info for ${targetPath}: ${result.data.stderr || 'Unknown error'}`);
62
- }
63
-
64
- const output = result.data.stdout.trim();
65
- const parts = output.split('|');
66
-
67
- if (parts.length < 8) {
68
- this.logger.error(`Unexpected stat output format: ${output}`);
69
- throw new Error(`Unexpected stat output format: ${output}`);
70
- }
71
-
72
- const [typeStr, sizeStr, permissions, owner, group, mtime, atime, ctime] = parts;
73
-
74
- const name = targetPath.split('/').pop() || targetPath;
75
- const fileType = this.parseFileType(typeStr);
76
-
77
- this.logger.debug(`Retrieved info for ${targetPath}: type=${fileType}, size=${sizeStr}`);
78
-
79
- return {
80
- data: {
81
- path: targetPath,
82
- name,
83
- type: fileType,
84
- size: parseInt(sizeStr, 10),
85
- permissions,
86
- owner,
87
- group,
88
- modifiedAt: mtime,
89
- accessedAt: atime,
90
- createdAt: ctime === '-' ? mtime : ctime,
91
- },
92
- };
93
- }
94
-
95
- private parseFileType(typeStr: string): SandboxFileInfoResult['type'] {
96
- const lower = typeStr.toLowerCase();
97
- if (lower.includes('regular')) return 'file';
98
- if (lower.includes('directory')) return 'directory';
99
- if (lower.includes('symbolic link')) return 'symlink';
100
- return 'other';
101
- }
102
- }
@@ -1,111 +0,0 @@
1
- import { Logger } from '@nestjs/common';
2
- import { z } from 'zod';
3
- import { BaseTool, InjectTool, Tool, ToolResult } from '@loopstack/common';
4
- import { SandboxCommand } from '@loopstack/sandbox-tool';
5
-
6
- const inputSchema = z
7
- .object({
8
- containerId: z.string().describe('The ID of the container to list the directory from'),
9
- path: z.string().describe('The path to the directory to list'),
10
- recursive: z.boolean().default(false).describe('Whether to list directories recursively'),
11
- })
12
- .strict();
13
-
14
- type SandboxListDirectoryArgs = z.infer<typeof inputSchema>;
15
-
16
- interface FileEntry {
17
- name: string;
18
- type: 'file' | 'directory' | 'symlink' | 'other';
19
- size: number;
20
- path: string;
21
- }
22
-
23
- interface SandboxListDirectoryResult {
24
- path: string;
25
- entries: FileEntry[];
26
- }
27
-
28
- @Tool({
29
- uiConfig: {
30
- description: 'List files and directories in a sandbox container',
31
- },
32
- schema: inputSchema,
33
- })
34
- export class SandboxListDirectory extends BaseTool {
35
- private readonly logger = new Logger(SandboxListDirectory.name);
36
-
37
- @InjectTool() private sandboxCommand: SandboxCommand;
38
-
39
- async call(args: SandboxListDirectoryArgs): Promise<ToolResult<SandboxListDirectoryResult>> {
40
- const { containerId, path: dirPath, recursive } = args;
41
-
42
- this.logger.debug(`Listing directory ${dirPath} in container ${containerId} (recursive: ${recursive})`);
43
-
44
- // Use find for recursive, ls for non-recursive
45
- // Output format: type size path
46
- const command = recursive
47
- ? `find '${dirPath.replace(/'/g, "'\\''")}' -printf '%y %s %p\\n'`
48
- : `find '${dirPath.replace(/'/g, "'\\''")}' -maxdepth 1 -printf '%y %s %p\\n'`;
49
-
50
- const result = await this.sandboxCommand.call({
51
- containerId,
52
- executable: 'sh',
53
- args: ['-c', command],
54
- workingDirectory: '/',
55
- timeout: 30000,
56
- });
57
-
58
- if (!result.data) {
59
- this.logger.error(`Failed to list directory ${dirPath}: No result data`);
60
- throw new Error(`Failed to list directory ${dirPath}: No result data`);
61
- }
62
-
63
- if (result.data.exitCode !== 0) {
64
- this.logger.error(`Failed to list directory ${dirPath}: ${result.data.stderr || 'Unknown error'}`);
65
- throw new Error(`Failed to list directory ${dirPath}: ${result.data.stderr || 'Unknown error'}`);
66
- }
67
-
68
- const entries: FileEntry[] = [];
69
- const lines = result.data.stdout.split('\n').filter((line) => line.trim());
70
-
71
- for (const line of lines) {
72
- const match = line.match(/^(\S)\s+(\d+)\s+(.+)$/);
73
- if (match) {
74
- const [, typeChar, sizeStr, fullPath] = match;
75
- const name = fullPath.split('/').pop() || fullPath;
76
-
77
- // Skip the directory itself in non-recursive mode
78
- if (fullPath === dirPath) continue;
79
-
80
- entries.push({
81
- name,
82
- type: this.parseFileType(typeChar),
83
- size: parseInt(sizeStr, 10),
84
- path: fullPath,
85
- });
86
- }
87
- }
88
-
89
- this.logger.debug(`Listed ${entries.length} entries in ${dirPath}`);
90
-
91
- return {
92
- data: {
93
- path: dirPath,
94
- entries,
95
- },
96
- };
97
- }
98
-
99
- private parseFileType(typeChar: string): FileEntry['type'] {
100
- switch (typeChar) {
101
- case 'f':
102
- return 'file';
103
- case 'd':
104
- return 'directory';
105
- case 'l':
106
- return 'symlink';
107
- default:
108
- return 'other';
109
- }
110
- }
111
- }
@@ -1,65 +0,0 @@
1
- import { Logger } from '@nestjs/common';
2
- import { z } from 'zod';
3
- import { BaseTool, InjectTool, Tool, ToolResult } from '@loopstack/common';
4
- import { SandboxCommand } from '@loopstack/sandbox-tool';
5
-
6
- const inputSchema = z
7
- .object({
8
- containerId: z.string().describe('The ID of the container to read the file from'),
9
- path: z.string().describe('The path to the file to read'),
10
- encoding: z.enum(['utf8', 'base64']).default('utf8').describe('The encoding to use when reading the file'),
11
- })
12
- .strict();
13
-
14
- type SandboxReadFileArgs = z.infer<typeof inputSchema>;
15
-
16
- interface SandboxReadFileResult {
17
- content: string;
18
- encoding: string;
19
- }
20
-
21
- @Tool({
22
- uiConfig: {
23
- description: 'Read file contents from a sandbox container',
24
- },
25
- schema: inputSchema,
26
- })
27
- export class SandboxReadFile extends BaseTool {
28
- private readonly logger = new Logger(SandboxReadFile.name);
29
-
30
- @InjectTool() private sandboxCommand: SandboxCommand;
31
-
32
- async call(args: SandboxReadFileArgs): Promise<ToolResult<SandboxReadFileResult>> {
33
- const { containerId, path, encoding } = args;
34
-
35
- this.logger.debug(`Reading file ${path} from container ${containerId} (encoding: ${encoding})`);
36
-
37
- const executable = encoding === 'base64' ? 'base64' : 'cat';
38
- const result = await this.sandboxCommand.call({
39
- containerId,
40
- executable,
41
- args: [path],
42
- workingDirectory: '/',
43
- timeout: 30000,
44
- });
45
-
46
- if (!result.data) {
47
- this.logger.error(`Failed to read file ${path}: No result data`);
48
- throw new Error(`Failed to read file ${path}: No result data`);
49
- }
50
-
51
- if (result.data.exitCode !== 0) {
52
- this.logger.error(`Failed to read file ${path}: ${result.data.stderr || 'Unknown error'}`);
53
- throw new Error(`Failed to read file ${path}: ${result.data.stderr || 'Unknown error'}`);
54
- }
55
-
56
- this.logger.debug(`Successfully read file ${path} (${result.data.stdout.length} characters)`);
57
-
58
- return {
59
- data: {
60
- content: result.data.stdout,
61
- encoding,
62
- },
63
- };
64
- }
65
- }
@@ -1,104 +0,0 @@
1
- import { Logger } from '@nestjs/common';
2
- import * as path from 'path';
3
- import { z } from 'zod';
4
- import { BaseTool, InjectTool, Tool, ToolResult } from '@loopstack/common';
5
- import { SandboxCommand } from '@loopstack/sandbox-tool';
6
-
7
- const inputSchema = z
8
- .object({
9
- containerId: z.string().describe('The ID of the container to write the file to'),
10
- path: z.string().describe('The path where the file should be written'),
11
- content: z.string().describe('The content to write to the file'),
12
- encoding: z.enum(['utf8', 'base64']).default('utf8').describe('The encoding of the content'),
13
- createParentDirs: z.boolean().default(true).describe("Whether to create parent directories if they don't exist"),
14
- })
15
- .strict();
16
-
17
- type SandboxWriteFileArgs = z.infer<typeof inputSchema>;
18
-
19
- interface SandboxWriteFileResult {
20
- path: string;
21
- bytesWritten: number;
22
- }
23
-
24
- @Tool({
25
- uiConfig: {
26
- description: 'Write content to a file in a sandbox container',
27
- },
28
- schema: inputSchema,
29
- })
30
- export class SandboxWriteFile extends BaseTool {
31
- private readonly logger = new Logger(SandboxWriteFile.name);
32
-
33
- @InjectTool() private sandboxCommand: SandboxCommand;
34
-
35
- async call(args: SandboxWriteFileArgs): Promise<ToolResult<SandboxWriteFileResult>> {
36
- const { containerId, path: filePath, content, encoding, createParentDirs } = args;
37
-
38
- this.logger.debug(`Writing file ${filePath} to container ${containerId} (encoding: ${encoding})`);
39
-
40
- // Create parent directories if needed
41
- if (createParentDirs) {
42
- const parentDir = path.posix.dirname(filePath);
43
- if (parentDir !== '/' && parentDir !== '.') {
44
- this.logger.debug(`Creating parent directory ${parentDir}`);
45
- const mkdirResult = await this.sandboxCommand.call({
46
- containerId,
47
- executable: 'mkdir',
48
- args: ['-p', parentDir],
49
- workingDirectory: '/',
50
- timeout: 5000,
51
- });
52
-
53
- if (!mkdirResult.data) {
54
- this.logger.error(`Failed to create parent directory ${parentDir}: No result data`);
55
- throw new Error(`Failed to create parent directory ${parentDir}: No result data`);
56
- }
57
-
58
- if (mkdirResult.data.exitCode !== 0) {
59
- this.logger.error(
60
- `Failed to create parent directory ${parentDir}: ${mkdirResult.data.stderr || 'Unknown error'}`,
61
- );
62
- throw new Error(
63
- `Failed to create parent directory ${parentDir}: ${mkdirResult.data.stderr || 'Unknown error'}`,
64
- );
65
- }
66
- }
67
- }
68
-
69
- // Encode content as base64 for safe transfer
70
- const base64Content =
71
- encoding === 'utf8' ? Buffer.from(content, 'utf8').toString('base64') : content.replace(/[^A-Za-z0-9+/=]/g, '');
72
-
73
- // Write file using base64 decode
74
- const result = await this.sandboxCommand.call({
75
- containerId,
76
- executable: 'sh',
77
- args: ['-c', `echo '${base64Content}' | base64 -d > '${filePath.replace(/'/g, "'\\''")}'`],
78
- workingDirectory: '/',
79
- timeout: 30000,
80
- });
81
-
82
- if (!result.data) {
83
- this.logger.error(`Failed to write file ${filePath}: No result data`);
84
- throw new Error(`Failed to write file ${filePath}: No result data`);
85
- }
86
-
87
- if (result.data.exitCode !== 0) {
88
- this.logger.error(`Failed to write file ${filePath}: ${result.data.stderr || 'Unknown error'}`);
89
- throw new Error(`Failed to write file ${filePath}: ${result.data.stderr || 'Unknown error'}`);
90
- }
91
-
92
- const bytesWritten =
93
- encoding === 'utf8' ? Buffer.from(content, 'utf8').length : Buffer.from(content, 'base64').length;
94
-
95
- this.logger.log(`Successfully wrote ${bytesWritten} bytes to ${filePath} in container ${containerId}`);
96
-
97
- return {
98
- data: {
99
- path: filePath,
100
- bytesWritten,
101
- },
102
- };
103
- }
104
- }