@labring/devbox-sdk 1.1.0

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/README.md ADDED
@@ -0,0 +1,478 @@
1
+ # devbox-sdk
2
+
3
+ **Secure Sandbox SDK for Isolated Code Execution.** Execute AI-generated code, run automation tasks, and test untrusted code with zero risk to your infrastructure.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install devbox-sdk
9
+ ```
10
+
11
+ ## Requirements
12
+
13
+ - Node.js >= 22.0.0
14
+ - Kubernetes configuration (`KUBECONFIG` environment variable or file path)
15
+
16
+ ## Quick Start
17
+
18
+ ### Secure Code Execution
19
+
20
+ ```typescript
21
+ import { DevboxSDK } from 'devbox-sdk'
22
+
23
+ // Initialize SDK
24
+ const sdk = new DevboxSDK({
25
+ kubeconfig: process.env.KUBECONFIG
26
+ })
27
+
28
+ // Create a secure sandbox
29
+ const sandbox = await sdk.createDevbox({
30
+ name: 'ai-task',
31
+ runtime: 'python',
32
+ resource: { cpu: 1, memory: 512 }
33
+ })
34
+
35
+ // Execute code safely in isolation
36
+ const result = await sandbox.codeRun('print("Hello from secure sandbox!")')
37
+ console.log(result.stdout) // "Hello from secure sandbox!"
38
+
39
+ // Clean up
40
+ await sandbox.delete()
41
+ await sdk.close()
42
+ ```
43
+
44
+ ## Features
45
+
46
+ ### 🛡️ Secure Sandbox Execution
47
+
48
+ Execute code in isolated container environments with zero risk to your infrastructure:
49
+
50
+ ```typescript
51
+ // Create isolated sandbox
52
+ const sandbox = await sdk.createDevbox({
53
+ name: 'untrusted-code',
54
+ runtime: 'node.js',
55
+ resource: { cpu: 2, memory: 4096 }
56
+ })
57
+
58
+ // Execute AI-generated or untrusted code safely
59
+ const result = await sandbox.codeRun(aiGeneratedCode)
60
+
61
+ // Each sandbox is completely isolated
62
+ // - No access to host filesystem
63
+ // - Resource limits enforced
64
+ // - Network isolation
65
+ // - Automatic cleanup on deletion
66
+ ```
67
+
68
+ **Security Features:**
69
+ - **Container Isolation** - Each sandbox runs in an isolated Kubernetes Pod
70
+ - **Path Validation** - Prevents directory traversal attacks
71
+ - **Resource Limits** - CPU and memory constraints
72
+ - **Access Control** - Kubeconfig-based authentication
73
+ - **HTTPS/TLS** - All communications encrypted
74
+
75
+ ### ⚡ Fast Code Execution
76
+
77
+ Execute code synchronously or asynchronously with real-time output:
78
+
79
+ ```typescript
80
+ // Synchronous execution (waits for completion)
81
+ const result = await sandbox.execSync({
82
+ command: 'python script.py',
83
+ cwd: '/workspace',
84
+ timeout: 60000
85
+ })
86
+ console.log(result.stdout)
87
+ console.log(result.exitCode)
88
+
89
+ // Asynchronous execution (returns immediately)
90
+ const process = await sandbox.exec({
91
+ command: 'npm run build',
92
+ cwd: '/workspace'
93
+ })
94
+
95
+ // Get process status
96
+ const status = await sandbox.getProcessStatus(process.processId)
97
+
98
+ // Get real-time logs
99
+ const logs = await sandbox.getProcessLogs(process.processId, {
100
+ lines: 100
101
+ })
102
+
103
+ // Kill process if needed
104
+ await sandbox.killProcess(process.processId)
105
+ ```
106
+
107
+ **Code Execution Methods:**
108
+ - `codeRun(code, options?)` - Execute code string directly (Node.js/Python)
109
+ - `execSync(options)` - Synchronous command execution
110
+ - `exec(options)` - Asynchronous command execution
111
+ - `execSyncStream(options)` - Stream output in real-time (SSE)
112
+
113
+ ### 📁 File Operations
114
+
115
+ Full CRUD operations with support for text and binary content:
116
+
117
+ ```typescript
118
+ // Write text file
119
+ await sandbox.writeFile('app.js', 'console.log("Hello")')
120
+
121
+ // Write binary file
122
+ await sandbox.writeFile('image.png', imageBuffer)
123
+
124
+ // Read file
125
+ const content = await sandbox.readFile('app.js')
126
+ console.log(content.toString())
127
+
128
+ // List files
129
+ const files = await sandbox.listFiles('/workspace')
130
+ console.log(files.files)
131
+
132
+ // Batch upload
133
+ await sandbox.batchUpload({
134
+ files: {
135
+ 'src/index.js': 'console.log("Hello")',
136
+ 'package.json': JSON.stringify({ name: 'my-app' })
137
+ }
138
+ })
139
+
140
+ // Download file
141
+ const fileContent = await sandbox.downloadFile('app.js', {
142
+ format: 'buffer' // or 'base64', 'text'
143
+ })
144
+
145
+ // Move and rename
146
+ await sandbox.moveFile({ from: '/old/path', to: '/new/path' })
147
+ await sandbox.renameFile({ path: '/old-name', newName: 'new-name' })
148
+ ```
149
+
150
+ ### 🔐 Git Integration
151
+
152
+ Clone, pull, push, and manage Git repositories securely:
153
+
154
+ ```typescript
155
+ // Clone repository
156
+ await sandbox.git.clone({
157
+ url: 'https://github.com/user/repo.git',
158
+ path: '/workspace/repo',
159
+ auth: {
160
+ type: 'https',
161
+ username: 'user',
162
+ password: 'token'
163
+ }
164
+ })
165
+
166
+ // Pull changes
167
+ await sandbox.git.pull({
168
+ path: '/workspace/repo',
169
+ auth: { /* ... */ }
170
+ })
171
+
172
+ // Push changes
173
+ await sandbox.git.push({
174
+ path: '/workspace/repo',
175
+ auth: { /* ... */ }
176
+ })
177
+
178
+ // Get status
179
+ const status = await sandbox.git.status('/workspace/repo')
180
+ console.log(status.branch)
181
+ console.log(status.changes)
182
+
183
+ // List branches
184
+ const branches = await sandbox.git.branches('/workspace/repo')
185
+ ```
186
+
187
+ ### 📊 Monitoring
188
+
189
+ Monitor sandbox resource usage and metrics:
190
+
191
+ ```typescript
192
+ // Get monitor data
193
+ const monitorData = await sdk.getMonitorData('sandbox-name', {
194
+ start: Date.now() - 3600000, // 1 hour ago
195
+ end: Date.now()
196
+ })
197
+
198
+ monitorData.forEach(data => {
199
+ console.log('CPU:', data.cpu)
200
+ console.log('Memory:', data.memory)
201
+ console.log('Timestamp:', data.timestamp)
202
+ })
203
+ ```
204
+
205
+ ### 🔄 Lifecycle Management
206
+
207
+ Create, start, pause, restart, and delete sandboxes:
208
+
209
+ ```typescript
210
+ // Create sandbox
211
+ const sandbox = await sdk.createDevbox({
212
+ name: 'my-sandbox',
213
+ runtime: 'node.js',
214
+ resource: { cpu: 2, memory: 4096 }
215
+ })
216
+
217
+ // Control lifecycle
218
+ await sandbox.start()
219
+ await sandbox.pause()
220
+ await sandbox.restart()
221
+ await sandbox.shutdown()
222
+ await sandbox.delete()
223
+
224
+ // List all sandboxes
225
+ const sandboxes = await sdk.listDevboxes()
226
+
227
+ // Get existing sandbox
228
+ const existing = await sdk.getDevbox('my-sandbox')
229
+ ```
230
+
231
+ ## Use Cases
232
+
233
+ ### AI Agents & Code Generation
234
+
235
+ ```typescript
236
+ // Execute AI-generated code safely
237
+ const aiCode = await llm.generateCode(prompt)
238
+ const result = await sandbox.codeRun(aiCode)
239
+
240
+ if (result.exitCode !== 0) {
241
+ console.error('Execution failed:', result.stderr)
242
+ } else {
243
+ console.log('Result:', result.stdout)
244
+ }
245
+ ```
246
+
247
+ ### Automation & Testing
248
+
249
+ ```typescript
250
+ // Run untrusted automation scripts in isolation
251
+ await sandbox.execSync({
252
+ command: 'npm test',
253
+ cwd: '/workspace',
254
+ timeout: 60000
255
+ })
256
+ ```
257
+
258
+ ### CI/CD Tasks
259
+
260
+ ```typescript
261
+ // Execute build tasks in isolated environment
262
+ await sandbox.git.clone({ url: repoUrl, path: '/workspace' })
263
+ await sandbox.execSync({ command: 'npm install' })
264
+ await sandbox.execSync({ command: 'npm run build' })
265
+ ```
266
+
267
+ ## Configuration
268
+
269
+ ### SDK Configuration
270
+
271
+ ```typescript
272
+ const sdk = new DevboxSDK({
273
+ // Required: Kubernetes config
274
+ kubeconfig: process.env.KUBECONFIG, // or file path
275
+
276
+ // Optional: API base URL
277
+ baseUrl: 'https://api.sealos.io',
278
+
279
+ // Optional: HTTP client configuration
280
+ http: {
281
+ timeout: 30000, // Request timeout in milliseconds
282
+ retries: 3, // Number of retry attempts
283
+ rejectUnauthorized: true // SSL certificate verification
284
+ }
285
+ })
286
+ ```
287
+
288
+ ### Sandbox Creation Options
289
+
290
+ ```typescript
291
+ await sdk.createDevbox({
292
+ name: 'my-sandbox', // Required: Unique name
293
+ runtime: 'node.js', // Required: Runtime environment
294
+ resource: { // Required: Resource allocation
295
+ cpu: 2, // CPU cores
296
+ memory: 4096 // Memory in MB
297
+ },
298
+ ports: [ // Optional: Port mappings
299
+ { containerPort: 3000, servicePort: 3000 }
300
+ ],
301
+ env: [ // Optional: Environment variables
302
+ { name: 'NODE_ENV', value: 'production' }
303
+ ]
304
+ })
305
+ ```
306
+
307
+ ## API Reference
308
+
309
+ ### DevboxSDK
310
+
311
+ Main SDK class for managing sandboxes.
312
+
313
+ #### Methods
314
+
315
+ - `createDevbox(config: DevboxCreateConfig): Promise<DevboxInstance>` - Create a new sandbox
316
+ - `getDevbox(name: string): Promise<DevboxInstance>` - Get an existing sandbox
317
+ - `listDevboxes(): Promise<DevboxInstance[]>` - List all sandboxes
318
+ - `getMonitorData(devboxName: string, timeRange?: TimeRange): Promise<MonitorData[]>` - Get monitoring data
319
+ - `close(): Promise<void>` - Close all connections and cleanup
320
+
321
+ ### DevboxInstance
322
+
323
+ Represents a single sandbox instance with methods for code execution, file operations, and more.
324
+
325
+ #### Properties
326
+
327
+ - `name: string` - Sandbox name
328
+ - `status: string` - Current status
329
+ - `runtime: DevboxRuntime` - Runtime environment
330
+ - `resources: ResourceInfo` - Resource allocation
331
+ - `git: Git` - Git operations interface
332
+
333
+ #### Methods
334
+
335
+ **Code Execution:**
336
+ - `codeRun(code: string, options?: CodeRunOptions): Promise<SyncExecutionResponse>`
337
+ - `execSync(options: ProcessExecOptions): Promise<SyncExecutionResponse>`
338
+ - `exec(options: ProcessExecOptions): Promise<ProcessExecResponse>`
339
+ - `execSyncStream(options: ProcessExecOptions): Promise<ReadableStream>`
340
+
341
+ **Process Management:**
342
+ - `getProcessStatus(processId: string): Promise<GetProcessStatusResponse>`
343
+ - `getProcessLogs(processId: string, options?: { lines?: number }): Promise<GetProcessLogsResponse>`
344
+ - `killProcess(processId: string, options?: KillProcessOptions): Promise<void>`
345
+ - `listProcesses(): Promise<ListProcessesResponse>`
346
+
347
+ **File Operations:**
348
+ - `writeFile(path: string, content: string | Buffer, options?: WriteOptions): Promise<void>`
349
+ - `readFile(path: string, options?: ReadOptions): Promise<Buffer>`
350
+ - `listFiles(path: string): Promise<ListFilesResponse>`
351
+ - `batchUpload(options: BatchUploadOptions): Promise<TransferResult>`
352
+ - `downloadFile(path: string, options?: DownloadFileOptions): Promise<Buffer | string>`
353
+ - `moveFile(options: MoveFileOptions): Promise<MoveFileResponse>`
354
+ - `renameFile(options: RenameFileOptions): Promise<RenameFileResponse>`
355
+
356
+ **File Watching:**
357
+ - `watchFiles(path: string, callback: (event: FileChangeEvent) => void): Promise<FileWatchWebSocket>`
358
+
359
+ **Git Operations:**
360
+ - `git.clone(options: GitCloneOptions): Promise<void>`
361
+ - `git.pull(options: GitPullOptions): Promise<void>`
362
+ - `git.push(options: GitPushOptions): Promise<void>`
363
+ - `git.status(path: string): Promise<GitStatus>`
364
+ - `git.branches(path: string): Promise<GitBranchInfo[]>`
365
+
366
+ **Lifecycle:**
367
+ - `start(): Promise<void>`
368
+ - `pause(): Promise<void>`
369
+ - `restart(): Promise<void>`
370
+ - `shutdown(): Promise<void>`
371
+ - `delete(): Promise<void>`
372
+ - `refreshInfo(): Promise<void>`
373
+
374
+ ## Error Handling
375
+
376
+ The SDK provides comprehensive error types:
377
+
378
+ ```typescript
379
+ import {
380
+ DevboxSDKError,
381
+ AuthenticationError,
382
+ ConnectionError,
383
+ FileOperationError,
384
+ DevboxNotFoundError,
385
+ ValidationError
386
+ } from 'devbox-sdk'
387
+
388
+ try {
389
+ await sandbox.writeFile('/invalid/path', 'content')
390
+ } catch (error) {
391
+ if (error instanceof FileOperationError) {
392
+ console.error('File operation failed:', error.message)
393
+ } else if (error instanceof ValidationError) {
394
+ console.error('Validation error:', error.message)
395
+ }
396
+ }
397
+ ```
398
+
399
+ ## Security Best Practices
400
+
401
+ 1. **Always validate input** before executing in sandbox
402
+ 2. **Set resource limits** to prevent resource exhaustion
403
+ 3. **Use HTTPS** for all communications
404
+ 4. **Clean up sandboxes** after use to free resources
405
+ 5. **Monitor resource usage** to detect anomalies
406
+ 6. **Use path validation** for all file operations
407
+
408
+ ## Examples
409
+
410
+ ### Complete AI Agent Workflow
411
+
412
+ ```typescript
413
+ import { DevboxSDK } from 'devbox-sdk'
414
+
415
+ async function runAIAgent() {
416
+ const sdk = new DevboxSDK({
417
+ kubeconfig: process.env.KUBECONFIG
418
+ })
419
+
420
+ try {
421
+ // Create secure sandbox
422
+ const sandbox = await sdk.createDevbox({
423
+ name: 'ai-agent',
424
+ runtime: 'python',
425
+ resource: { cpu: 2, memory: 4096 }
426
+ })
427
+
428
+ // Execute AI-generated code
429
+ const aiCode = await llm.generateCode(userPrompt)
430
+ const result = await sandbox.codeRun(aiCode)
431
+
432
+ if (result.exitCode === 0) {
433
+ console.log('Success:', result.stdout)
434
+ } else {
435
+ console.error('Error:', result.stderr)
436
+ }
437
+
438
+ // Clean up
439
+ await sandbox.delete()
440
+ } finally {
441
+ await sdk.close()
442
+ }
443
+ }
444
+
445
+ runAIAgent()
446
+ ```
447
+
448
+ ## TypeScript Support
449
+
450
+ Full TypeScript support with comprehensive type definitions:
451
+
452
+ ```typescript
453
+ import type {
454
+ DevboxSDKConfig,
455
+ DevboxCreateConfig,
456
+ DevboxInfo,
457
+ FileMap,
458
+ ProcessExecOptions,
459
+ GitCloneOptions
460
+ } from 'devbox-sdk'
461
+ ```
462
+
463
+ ## Performance
464
+
465
+ - **Connection Pooling**: Efficient HTTP connection reuse (>98% reuse rate)
466
+ - **Adaptive Transfer**: Smart file transfer strategies based on file size
467
+ - **Fast Creation**: Quick sandbox initialization
468
+ - **Type Safety**: Full TypeScript support prevents runtime errors
469
+
470
+ ## License
471
+
472
+ Apache-2.0
473
+
474
+ ## Links
475
+
476
+ - [GitHub Repository](https://github.com/zjy365/devbox-sdk)
477
+ - [Documentation](https://github.com/zjy365/devbox-sdk/tree/main/apps/docs)
478
+ - [Issue Tracker](https://github.com/zjy365/devbox-sdk/issues)