@larkup/sandbox 0.1.1

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.
@@ -0,0 +1,6 @@
1
+ (node:18200) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
2
+ (Use `node --trace-warnings ...` to show where the warning was created)
3
+
4
+ > @larkup/sandbox@0.1.0 build /Users/abdelrahmanabounida/Desktop/my-ai-startup/larkup/larkup/packages/sandbox
5
+ > tsc --outDir dist
6
+
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @larkup/sandbox
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 4e54939: feat: add doc-editor tool and canvas preview
package/Dockerfile ADDED
@@ -0,0 +1,30 @@
1
+ FROM python:3.12-slim
2
+
3
+ LABEL maintainer="larkup" \
4
+ description="Larkup sandbox for data analysis code execution"
5
+
6
+ # Install data analysis libraries
7
+ RUN pip install --no-cache-dir \
8
+ pandas==2.2.3 \
9
+ numpy==2.2.6 \
10
+ matplotlib==3.10.3 \
11
+ openpyxl==3.1.5 \
12
+ scipy==1.15.3 \
13
+ scikit-learn==1.7.0 \
14
+ seaborn==0.13.2 \
15
+ xlrd==2.0.1 \
16
+ pypdf==5.1.0 \
17
+ python-docx==1.1.2 \
18
+ python-pptx==1.0.2 \
19
+ Pillow==11.1.0
20
+
21
+ # Matplotlib non-interactive backend (no display needed)
22
+ ENV MPLBACKEND=Agg
23
+
24
+ WORKDIR /sandbox
25
+
26
+ # Non-root user for security
27
+ RUN useradd -m -s /bin/bash sandboxuser
28
+ USER sandboxuser
29
+
30
+ ENTRYPOINT ["python3", "-c"]
package/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Docker-based sandbox runner.
3
+ *
4
+ * Uses `dockerode` to manage ephemeral containers for code execution.
5
+ * Each execution spins up a container, runs the code, captures output +
6
+ * generated files, then auto-removes the container.
7
+ */
8
+ import type { DockerConfig, ExecutionRequest, ExecutionResult, SandboxHealthCheck } from './types.js';
9
+ export declare function checkDockerHealth(): Promise<SandboxHealthCheck>;
10
+ export declare function buildSandboxImage(onProgress?: (msg: string) => void): Promise<void>;
11
+ export declare function ensureImage(): Promise<boolean>;
12
+ export declare function executeInDocker(request: ExecutionRequest, config: DockerConfig): Promise<ExecutionResult>;
@@ -0,0 +1,438 @@
1
+ /**
2
+ * Docker-based sandbox runner.
3
+ *
4
+ * Uses `dockerode` to manage ephemeral containers for code execution.
5
+ * Each execution spins up a container, runs the code, captures output +
6
+ * generated files, then auto-removes the container.
7
+ */
8
+ import Docker from 'dockerode';
9
+ import { promises as fs } from 'node:fs';
10
+ import path from 'node:path';
11
+ import os from 'node:os';
12
+ import { randomUUID } from 'node:crypto';
13
+ const SANDBOX_IMAGE = 'larkup-sandbox:latest';
14
+ const OUTPUT_DIR = '/sandbox/output';
15
+ const INPUT_DIR = '/sandbox/input';
16
+ const DOCKERFILE_DIR = path.join(import.meta.dirname ?? __dirname, '..');
17
+ let dockerInstance = null;
18
+ function getDocker() {
19
+ if (!dockerInstance) {
20
+ dockerInstance = new Docker();
21
+ }
22
+ return dockerInstance;
23
+ }
24
+ /* ------------------------------------------------------------------ */
25
+ /* Health check */
26
+ /* ------------------------------------------------------------------ */
27
+ export async function checkDockerHealth() {
28
+ const docker = getDocker();
29
+ try {
30
+ const info = await docker.version();
31
+ const images = await docker.listImages({
32
+ filters: { reference: [SANDBOX_IMAGE] },
33
+ });
34
+ return {
35
+ status: images.length > 0 ? 'ready' : 'image-not-found',
36
+ backend: 'docker',
37
+ dockerVersion: info.Version,
38
+ imageReady: images.length > 0,
39
+ };
40
+ }
41
+ catch (err) {
42
+ return {
43
+ status: 'docker-not-found',
44
+ backend: 'docker',
45
+ error: err.message ?? 'Docker daemon not available',
46
+ };
47
+ }
48
+ }
49
+ /* ------------------------------------------------------------------ */
50
+ /* Image management */
51
+ /* ------------------------------------------------------------------ */
52
+ export async function buildSandboxImage(onProgress) {
53
+ const docker = getDocker();
54
+ const dockerfilePath = path.join(DOCKERFILE_DIR, 'Dockerfile');
55
+ // Check if Dockerfile exists in the package
56
+ try {
57
+ await fs.access(dockerfilePath);
58
+ }
59
+ catch {
60
+ throw new Error(`Sandbox Dockerfile not found at ${dockerfilePath}. ` +
61
+ `Ensure the @larkup/sandbox package is properly installed.`);
62
+ }
63
+ onProgress?.('Building sandbox image…');
64
+ const stream = await docker.buildImage({ context: DOCKERFILE_DIR, src: ['Dockerfile'] }, { t: SANDBOX_IMAGE });
65
+ // Follow the build stream to completion
66
+ await new Promise((resolve, reject) => {
67
+ docker.modem.followProgress(stream, (err) => {
68
+ if (err)
69
+ reject(err);
70
+ else
71
+ resolve();
72
+ }, (event) => {
73
+ if (event.stream) {
74
+ onProgress?.(event.stream.trim());
75
+ }
76
+ });
77
+ });
78
+ onProgress?.('Sandbox image built successfully ✓');
79
+ }
80
+ export async function ensureImage() {
81
+ const docker = getDocker();
82
+ const images = await docker.listImages({
83
+ filters: { reference: [SANDBOX_IMAGE] },
84
+ });
85
+ if (images.length > 0)
86
+ return true;
87
+ try {
88
+ await buildSandboxImage();
89
+ return true;
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
95
+ /* ------------------------------------------------------------------ */
96
+ /* Code execution */
97
+ /* ------------------------------------------------------------------ */
98
+ /**
99
+ * Build the Python wrapper script that:
100
+ * 1. Sets up pandas compatibility shims to handle deprecated APIs
101
+ * 2. Auto-imports common data analysis modules
102
+ * 3. Runs the user code with robust error handling
103
+ * 4. Saves any matplotlib figures to /sandbox/output/
104
+ * 5. Lists generated artifacts
105
+ */
106
+ function wrapPythonCode(code) {
107
+ return `
108
+ import sys, os, json, traceback
109
+
110
+ # Ensure output directory exists
111
+ os.makedirs("${OUTPUT_DIR}", exist_ok=True)
112
+
113
+ # ============================================================
114
+ # SAFETY PREAMBLE: Suppress warnings & patch deprecated APIs
115
+ # ============================================================
116
+ import warnings
117
+ warnings.filterwarnings('ignore', category=FutureWarning)
118
+ warnings.filterwarnings('ignore', category=DeprecationWarning)
119
+ warnings.filterwarnings('ignore', category=UserWarning)
120
+
121
+ # Auto-import common data analysis modules
122
+ import numpy as np
123
+
124
+ try:
125
+ import pandas as pd
126
+
127
+ # --- Patch 1: DataFrame.append() was removed in pandas 2.0 ---
128
+ if not hasattr(pd.DataFrame, 'append'):
129
+ def _df_append(self, other, ignore_index=False, verify_integrity=False, sort=False, **kwargs):
130
+ """Backwards-compatible append using pd.concat."""
131
+ if isinstance(other, (list, tuple)):
132
+ to_concat = [self] + list(other)
133
+ elif isinstance(other, dict):
134
+ to_concat = [self, pd.DataFrame([other])]
135
+ else:
136
+ to_concat = [self, other]
137
+ return pd.concat(to_concat, ignore_index=ignore_index, verify_integrity=verify_integrity, sort=sort)
138
+ pd.DataFrame.append = _df_append
139
+
140
+ # --- Patch 2: Series.append() was removed in pandas 2.0 ---
141
+ if not hasattr(pd.Series, 'append'):
142
+ def _series_append(self, to_append, ignore_index=False, verify_integrity=False):
143
+ """Backwards-compatible Series.append using pd.concat."""
144
+ if isinstance(to_append, (list, tuple)):
145
+ to_concat = [self] + list(to_append)
146
+ else:
147
+ to_concat = [self, to_append]
148
+ return pd.concat(to_concat, ignore_index=ignore_index, verify_integrity=verify_integrity)
149
+ pd.Series.append = _series_append
150
+
151
+ # --- Patch 3: Fix deprecated resample frequency aliases ---
152
+ # "M" -> "ME", "Q" -> "QE", "Y" -> "YE", "H" -> "h", "T" -> "min", "S" -> "s"
153
+ _original_resample = pd.DataFrame.resample
154
+ _FREQ_ALIAS_MAP = {
155
+ 'M': 'ME', 'Q': 'QE', 'Y': 'YE', 'A': 'YE',
156
+ 'BM': 'BME', 'BQ': 'BQE', 'BA': 'BYE', 'BY': 'BYE',
157
+ 'BMS': 'BMS', 'QS': 'QS', 'AS': 'YS', 'BAS': 'BYS',
158
+ 'H': 'h', 'T': 'min', 'S': 's', 'L': 'ms', 'U': 'us', 'N': 'ns',
159
+ }
160
+ def _patched_resample(self, rule, *args, **kwargs):
161
+ if isinstance(rule, str) and rule in _FREQ_ALIAS_MAP:
162
+ rule = _FREQ_ALIAS_MAP[rule]
163
+ return _original_resample(self, rule, *args, **kwargs)
164
+ pd.DataFrame.resample = _patched_resample
165
+
166
+ # Also patch Series.resample
167
+ _original_series_resample = pd.Series.resample
168
+ def _patched_series_resample(self, rule, *args, **kwargs):
169
+ if isinstance(rule, str) and rule in _FREQ_ALIAS_MAP:
170
+ rule = _FREQ_ALIAS_MAP[rule]
171
+ return _original_series_resample(self, rule, *args, **kwargs)
172
+ pd.Series.resample = _patched_series_resample
173
+
174
+ # --- Patch 4: Fix pd.Grouper freq aliases ---
175
+ _original_grouper = pd.Grouper
176
+ class _PatchedGrouper(_original_grouper):
177
+ def __init__(self, *args, **kwargs):
178
+ if 'freq' in kwargs and isinstance(kwargs['freq'], str):
179
+ kwargs['freq'] = _FREQ_ALIAS_MAP.get(kwargs['freq'], kwargs['freq'])
180
+ super().__init__(*args, **kwargs)
181
+ pd.Grouper = _PatchedGrouper
182
+
183
+ except ImportError:
184
+ pass
185
+
186
+ # ============================================================
187
+ # Patch matplotlib to auto-save figures
188
+ # ============================================================
189
+ _figure_count = [0]
190
+ try:
191
+ import matplotlib
192
+ matplotlib.use("Agg")
193
+ import matplotlib.pyplot as plt
194
+
195
+ _original_show = plt.show
196
+ def _patched_show(*args, **kwargs):
197
+ for fig_num in plt.get_fignums():
198
+ fig = plt.figure(fig_num)
199
+ fname = f"${OUTPUT_DIR}/chart_{_figure_count[0]}.png"
200
+ fig.savefig(fname, dpi=150, bbox_inches="tight", facecolor="white")
201
+ _figure_count[0] += 1
202
+ plt.close("all")
203
+ plt.show = _patched_show
204
+ except ImportError:
205
+ pass
206
+
207
+ # ============================================================
208
+ # Execute user code with robust error handling
209
+ # ============================================================
210
+ try:
211
+ exec(${JSON.stringify(code)})
212
+
213
+ # Auto-save any remaining matplotlib figures
214
+ try:
215
+ import matplotlib.pyplot as plt
216
+ if plt.get_fignums():
217
+ plt.show()
218
+ except (ImportError, Exception):
219
+ pass
220
+ except SystemExit as e:
221
+ # Let explicit sys.exit() calls through
222
+ if e.code != 0:
223
+ sys.exit(e.code)
224
+ except Exception as e:
225
+ # Print a clean, user-readable error instead of raw traceback
226
+ error_type = type(e).__name__
227
+ error_msg = str(e)
228
+ print(f"Error ({error_type}): {error_msg}", file=sys.stderr)
229
+ # Also print the relevant part of the traceback for debugging
230
+ tb = traceback.extract_tb(sys.exc_info()[2])
231
+ # Filter to only show the exec'd code frames (skip wrapper frames)
232
+ user_frames = [f for f in tb if f.filename == '<string>']
233
+ if user_frames:
234
+ last = user_frames[-1]
235
+ print(f" at line {last.lineno}: {last.line}", file=sys.stderr)
236
+ sys.exit(1)
237
+
238
+ # List generated artifacts
239
+ artifacts = []
240
+ if os.path.isdir("${OUTPUT_DIR}"):
241
+ for f in sorted(os.listdir("${OUTPUT_DIR}")):
242
+ fp = os.path.join("${OUTPUT_DIR}", f)
243
+ if os.path.isfile(fp):
244
+ artifacts.append(f)
245
+ if artifacts:
246
+ print("\\n__ARTIFACTS__:" + json.dumps(artifacts))
247
+ `;
248
+ }
249
+ export async function executeInDocker(request, config) {
250
+ const docker = getDocker();
251
+ const startTime = Date.now();
252
+ // Create a temporary directory for input files
253
+ const tmpDir = path.join(os.tmpdir(), `larkup-sandbox-${randomUUID()}`);
254
+ const inputDir = path.join(tmpDir, 'input');
255
+ const outputDir = path.join(tmpDir, 'output');
256
+ await fs.mkdir(inputDir, { recursive: true });
257
+ await fs.mkdir(outputDir, { recursive: true });
258
+ // Write input files
259
+ if (request.files) {
260
+ for (const file of request.files) {
261
+ const filePath = path.join(inputDir, file.name);
262
+ if (file.isBase64) {
263
+ await fs.writeFile(filePath, Buffer.from(file.content, 'base64'));
264
+ }
265
+ else {
266
+ await fs.writeFile(filePath, file.content, 'utf8');
267
+ }
268
+ }
269
+ }
270
+ // Prepare the execution code
271
+ let execCode;
272
+ let cmd;
273
+ if (request.language === 'python') {
274
+ execCode = wrapPythonCode(request.code);
275
+ const scriptPath = path.join(tmpDir, 'run.py');
276
+ await fs.writeFile(scriptPath, execCode, 'utf8');
277
+ cmd = ['python3', '/sandbox/run.py'];
278
+ }
279
+ else {
280
+ // JavaScript/TypeScript (future)
281
+ const scriptPath = path.join(tmpDir, 'run.js');
282
+ await fs.writeFile(scriptPath, request.code, 'utf8');
283
+ cmd = ['node', '/sandbox/run.js'];
284
+ }
285
+ const timeout = request.timeout ?? config.timeoutMs;
286
+ let container = null;
287
+ try {
288
+ container = await docker.createContainer({
289
+ Image: config.imageName,
290
+ Cmd: cmd,
291
+ Entrypoint: [],
292
+ WorkingDir: '/sandbox/input',
293
+ HostConfig: {
294
+ AutoRemove: false,
295
+ Memory: config.memoryMB * 1024 * 1024,
296
+ CpuShares: config.cpuShares,
297
+ NetworkMode: config.networkDisabled ? 'none' : 'bridge',
298
+ Binds: [
299
+ `${inputDir}:${INPUT_DIR}:ro`,
300
+ `${outputDir}:${OUTPUT_DIR}:rw`,
301
+ `${tmpDir}/run.py:/sandbox/run.py:ro`,
302
+ ],
303
+ ReadonlyRootfs: false,
304
+ },
305
+ Tty: false,
306
+ AttachStdout: true,
307
+ AttachStderr: true,
308
+ });
309
+ await container.start();
310
+ // Wait for completion with timeout
311
+ const waitPromise = container.wait();
312
+ const timeoutPromise = new Promise((_, reject) => {
313
+ setTimeout(async () => {
314
+ try {
315
+ await container?.kill();
316
+ }
317
+ catch {
318
+ /* container may have already stopped */
319
+ }
320
+ reject(new Error(`Execution timed out after ${timeout}ms`));
321
+ }, timeout);
322
+ });
323
+ const result = await Promise.race([waitPromise, timeoutPromise]);
324
+ // Capture logs
325
+ const logs = await container.logs({
326
+ stdout: true,
327
+ stderr: true,
328
+ follow: false,
329
+ });
330
+ const logStr = demuxDockerStream(logs);
331
+ // Collect artifacts from output directory
332
+ const artifacts = [];
333
+ try {
334
+ const files = await fs.readdir(outputDir);
335
+ for (const file of files) {
336
+ const filePath = path.join(outputDir, file);
337
+ const content = await fs.readFile(filePath);
338
+ const ext = path.extname(file).toLowerCase();
339
+ const mimeType = getMimeType(ext);
340
+ artifacts.push({
341
+ name: file,
342
+ mimeType,
343
+ data: content.toString('base64'),
344
+ });
345
+ }
346
+ }
347
+ catch {
348
+ /* output dir may not exist */
349
+ }
350
+ // Parse stdout/stderr from demuxed logs
351
+ const { stdout, stderr } = logStr;
352
+ return {
353
+ stdout: cleanArtifactMarkers(stdout),
354
+ stderr,
355
+ exitCode: result.StatusCode ?? 1,
356
+ artifacts,
357
+ executionTimeMs: Date.now() - startTime,
358
+ };
359
+ }
360
+ catch (err) {
361
+ return {
362
+ stdout: '',
363
+ stderr: err.message ?? 'Execution failed',
364
+ exitCode: 1,
365
+ artifacts: [],
366
+ executionTimeMs: Date.now() - startTime,
367
+ };
368
+ }
369
+ finally {
370
+ // Cleanup
371
+ if (container) {
372
+ try {
373
+ await container.remove({ force: true });
374
+ }
375
+ catch {
376
+ /* already removed */
377
+ }
378
+ }
379
+ try {
380
+ await fs.rm(tmpDir, { recursive: true, force: true });
381
+ }
382
+ catch {
383
+ /* best effort */
384
+ }
385
+ }
386
+ }
387
+ /* ------------------------------------------------------------------ */
388
+ /* Helpers */
389
+ /* ------------------------------------------------------------------ */
390
+ /**
391
+ * Docker multiplexes stdout/stderr into a single stream with 8-byte headers.
392
+ * Header format: [type(1)][0(3)][size(4)] where type: 1=stdout, 2=stderr
393
+ */
394
+ function demuxDockerStream(buffer) {
395
+ let stdout = '';
396
+ let stderr = '';
397
+ if (typeof buffer === 'string') {
398
+ return { stdout: buffer, stderr: '' };
399
+ }
400
+ let offset = 0;
401
+ while (offset < buffer.length) {
402
+ if (offset + 8 > buffer.length)
403
+ break;
404
+ const type = buffer.readUInt8(offset);
405
+ const size = buffer.readUInt32BE(offset + 4);
406
+ offset += 8;
407
+ if (offset + size > buffer.length)
408
+ break;
409
+ const payload = buffer.subarray(offset, offset + size).toString('utf8');
410
+ if (type === 1)
411
+ stdout += payload;
412
+ else if (type === 2)
413
+ stderr += payload;
414
+ offset += size;
415
+ }
416
+ if (!stdout && !stderr && buffer.length > 0) {
417
+ stdout = buffer.toString('utf8');
418
+ }
419
+ return { stdout, stderr };
420
+ }
421
+ function cleanArtifactMarkers(stdout) {
422
+ return stdout.replace(/\n__ARTIFACTS__:.*$/m, '').trimEnd();
423
+ }
424
+ function getMimeType(ext) {
425
+ const map = {
426
+ '.png': 'image/png',
427
+ '.jpg': 'image/jpeg',
428
+ '.jpeg': 'image/jpeg',
429
+ '.svg': 'image/svg+xml',
430
+ '.gif': 'image/gif',
431
+ '.csv': 'text/csv',
432
+ '.json': 'application/json',
433
+ '.txt': 'text/plain',
434
+ '.html': 'text/html',
435
+ '.pdf': 'application/pdf',
436
+ };
437
+ return map[ext] ?? 'application/octet-stream';
438
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @larkup/sandbox — Main entry point.
3
+ *
4
+ * Re-exports the public API for the sandbox package.
5
+ */
6
+ export { SandboxManager } from './sandbox-manager.js';
7
+ export { checkDockerHealth, buildSandboxImage, ensureImage, executeInDocker, } from './docker-runner.js';
8
+ export type { SandboxBackend, SandboxConfig, DockerConfig, RemoteConfig, SandboxLanguage, SandboxFile, ExecutionRequest, ExecutionResult, ExecutionArtifact, SandboxStatus, SandboxHealthCheck, } from './types.js';