@larkup/sandbox 0.1.10 → 0.1.12

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @larkup/sandbox
2
2
 
3
+ ## 0.1.12
4
+
5
+ ### Patch Changes
6
+
7
+ - Improve compound clinical-data analysis with reliable multi-file routing, safer aggregation validation, complete artifact evidence, robust generated Python repair, captured analysis charts, and clearer PDF endpoint synthesis.
8
+
9
+ ## 0.1.11
10
+
11
+ ### Patch Changes
12
+
13
+ - 3bf4b48: Stage E2B input files through its filesystem API so large analysis datasets are not embedded in process command arguments.
14
+
3
15
  ## 0.1.10
4
16
 
5
17
  ### Patch Changes
@@ -76,7 +76,9 @@ async function execute(request, credentials) {
76
76
  }
77
77
  throw err;
78
78
  }
79
- }, request);
79
+ }, request, async (files) => {
80
+ await withTimeout(activeSandbox.files.write(files), timeoutMs, 'E2B file staging');
81
+ });
80
82
  }
81
83
  catch (err) {
82
84
  return failedResult(err instanceof Error ? err.message : 'E2B execution failed.', startTime);
@@ -7,10 +7,10 @@
7
7
  * with a different SDK shape (commands.run, runCommand, exec, ...). Rather
8
8
  * than re-implement file staging + artifact capture per provider, adapters
9
9
  * plug their SDK's exec call in as a `RemoteExecFn` and hand it to
10
- * `runScriptedExecution`, which builds one POSIX shell script that writes
11
- * any input files, runs the code, and reports back any files written to an
12
- * output directory (mirroring what the Docker adapter gets for free via a
13
- * bind mount).
10
+ * `runScriptedExecution`, which stages inputs, runs the code, and reports
11
+ * back files written to an output directory (mirroring what the Docker
12
+ * adapter gets for free via a bind mount). Providers with a native filesystem
13
+ * API can stage large files without embedding them in a process command.
14
14
  */
15
15
  import type { ExecutionRequest, ExecutionResult } from './types.js';
16
16
  /** Default per-execution timeout for remote adapters when a request doesn't specify one. */
@@ -22,14 +22,23 @@ export interface RemoteCommandResult {
22
22
  }
23
23
  /** Runs a single shell command/script inside a provider's sandbox instance. */
24
24
  export type RemoteExecFn = (script: string) => Promise<RemoteCommandResult>;
25
+ export interface RemoteExecutionFile {
26
+ path: string;
27
+ data: string | ArrayBuffer;
28
+ }
29
+ /** Optional native filesystem staging used by providers that support it. */
30
+ export type RemoteStageFilesFn = (files: RemoteExecutionFile[]) => Promise<void>;
25
31
  /** Builds the POSIX shell script a remote adapter hands to its provider's exec call. */
26
- export declare function buildExecutionScript(request: ExecutionRequest): string;
32
+ export declare function buildExecutionScript(request: ExecutionRequest, filesAlreadyStaged?: boolean): string;
27
33
  /**
28
- * Runs `request` via `execFn` and reassembles an `ExecutionResult`,
29
- * including a best-effort fetch of any files the code wrote to the output
34
+ * Runs `request` via `execFn` and reassembles an `ExecutionResult`. When
35
+ * `stageFiles` is supplied, inputs are written through the provider filesystem;
36
+ * otherwise the portable shell-script staging path is used.
37
+ *
38
+ * It includes a best-effort fetch of any files the code wrote to the output
30
39
  * directory (one follow-up `base64 <file>` call per artifact).
31
40
  */
32
- export declare function runScriptedExecution(execFn: RemoteExecFn, request: ExecutionRequest): Promise<ExecutionResult>;
41
+ export declare function runScriptedExecution(execFn: RemoteExecFn, request: ExecutionRequest, stageFiles?: RemoteStageFilesFn): Promise<ExecutionResult>;
33
42
  /** Uniform safety net for providers whose SDK doesn't take its own per-call timeout. */
34
43
  export declare function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T>;
35
44
  /**
@@ -7,10 +7,10 @@
7
7
  * with a different SDK shape (commands.run, runCommand, exec, ...). Rather
8
8
  * than re-implement file staging + artifact capture per provider, adapters
9
9
  * plug their SDK's exec call in as a `RemoteExecFn` and hand it to
10
- * `runScriptedExecution`, which builds one POSIX shell script that writes
11
- * any input files, runs the code, and reports back any files written to an
12
- * output directory (mirroring what the Docker adapter gets for free via a
13
- * bind mount).
10
+ * `runScriptedExecution`, which stages inputs, runs the code, and reports
11
+ * back files written to an output directory (mirroring what the Docker
12
+ * adapter gets for free via a bind mount). Providers with a native filesystem
13
+ * API can stage large files without embedding them in a process command.
14
14
  */
15
15
  import { getMimeType } from './mime.js';
16
16
  /** Default per-execution timeout for remote adapters when a request doesn't specify one. */
@@ -36,8 +36,39 @@ function shellSingleQuote(value) {
36
36
  function writeBase64FileScript(name, base64) {
37
37
  return `base64 -d > ${shellSingleQuote(name)} <<'${HEREDOC_DELIMITER}'\n${base64}\n${HEREDOC_DELIMITER}`;
38
38
  }
39
+ /** Add the same headless chart capture contract used by the local sandbox. */
40
+ function executionSource(request) {
41
+ if (request.language !== 'python')
42
+ return request.code;
43
+ const encodedCode = Buffer.from(request.code, 'utf8').toString('base64');
44
+ return `import base64, os
45
+ os.makedirs(${JSON.stringify(OUTPUT_DIR)}, exist_ok=True)
46
+ _larkup_figure_count = [0]
47
+ try:
48
+ import matplotlib
49
+ matplotlib.use('Agg')
50
+ import matplotlib.pyplot as plt
51
+ def _larkup_save_figures(*args, **kwargs):
52
+ for number in plt.get_fignums():
53
+ figure = plt.figure(number)
54
+ filename = os.path.join(${JSON.stringify(OUTPUT_DIR)}, f'chart_{_larkup_figure_count[0]}.png')
55
+ figure.savefig(filename, dpi=150, bbox_inches='tight', facecolor='white')
56
+ _larkup_figure_count[0] += 1
57
+ plt.close('all')
58
+ plt.show = _larkup_save_figures
59
+ except ImportError:
60
+ pass
61
+ _larkup_encoded_code = ${JSON.stringify(encodedCode)}
62
+ exec(compile(base64.b64decode(_larkup_encoded_code), 'analysis.py', 'exec'), globals(), globals())
63
+ try:
64
+ if 'plt' in globals() and plt.get_fignums():
65
+ plt.show()
66
+ except Exception:
67
+ pass
68
+ `;
69
+ }
39
70
  /** Builds the POSIX shell script a remote adapter hands to its provider's exec call. */
40
- export function buildExecutionScript(request) {
71
+ export function buildExecutionScript(request, filesAlreadyStaged = false) {
41
72
  const lines = [
42
73
  'set -e',
43
74
  `mkdir -p ${shellSingleQuote(OUTPUT_DIR)}`,
@@ -45,6 +76,8 @@ export function buildExecutionScript(request) {
45
76
  ];
46
77
  for (const file of request.files ?? []) {
47
78
  assertSafeFileName(file.name);
79
+ if (filesAlreadyStaged)
80
+ continue;
48
81
  const base64 = file.isBase64
49
82
  ? file.content
50
83
  : Buffer.from(file.content, 'utf8').toString('base64');
@@ -52,12 +85,27 @@ export function buildExecutionScript(request) {
52
85
  }
53
86
  const scriptName = request.language === 'python' ? 'run.py' : 'run.js';
54
87
  const runner = request.language === 'python' ? 'python3' : 'node';
55
- const codeBase64 = Buffer.from(request.code, 'utf8').toString('base64');
56
- lines.push(writeBase64FileScript(scriptName, codeBase64));
88
+ if (!filesAlreadyStaged) {
89
+ const codeBase64 = Buffer.from(executionSource(request), 'utf8').toString('base64');
90
+ lines.push(writeBase64FileScript(scriptName, codeBase64));
91
+ }
57
92
  lines.push(`${runner} ${shellSingleQuote(scriptName)}`);
58
93
  lines.push(`if [ -d ${shellSingleQuote(OUTPUT_DIR)} ]; then echo "${ARTIFACT_MARKER}$(ls -1 ${shellSingleQuote(OUTPUT_DIR)} 2>/dev/null | tr '\\n' ',')"; fi`);
59
94
  return lines.join('\n');
60
95
  }
96
+ function executionFiles(request) {
97
+ const files = (request.files ?? []).map((file) => {
98
+ assertSafeFileName(file.name);
99
+ if (!file.isBase64)
100
+ return { path: `${WORKDIR}/${file.name}`, data: file.content };
101
+ const bytes = Buffer.from(file.content, 'base64');
102
+ const data = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
103
+ return { path: `${WORKDIR}/${file.name}`, data };
104
+ });
105
+ const scriptName = request.language === 'python' ? 'run.py' : 'run.js';
106
+ files.push({ path: `${WORKDIR}/${scriptName}`, data: executionSource(request) });
107
+ return files;
108
+ }
61
109
  function extractArtifactMarker(stdout) {
62
110
  const markerIndex = stdout.lastIndexOf(ARTIFACT_MARKER);
63
111
  if (markerIndex === -1)
@@ -74,13 +122,18 @@ function extractArtifactMarker(stdout) {
74
122
  return { stdout: (before + rest).replace(/\n$/, ''), artifactNames };
75
123
  }
76
124
  /**
77
- * Runs `request` via `execFn` and reassembles an `ExecutionResult`,
78
- * including a best-effort fetch of any files the code wrote to the output
125
+ * Runs `request` via `execFn` and reassembles an `ExecutionResult`. When
126
+ * `stageFiles` is supplied, inputs are written through the provider filesystem;
127
+ * otherwise the portable shell-script staging path is used.
128
+ *
129
+ * It includes a best-effort fetch of any files the code wrote to the output
79
130
  * directory (one follow-up `base64 <file>` call per artifact).
80
131
  */
81
- export async function runScriptedExecution(execFn, request) {
132
+ export async function runScriptedExecution(execFn, request, stageFiles) {
82
133
  const startTime = Date.now();
83
- const script = buildExecutionScript(request);
134
+ if (stageFiles)
135
+ await stageFiles(executionFiles(request));
136
+ const script = buildExecutionScript(request, Boolean(stageFiles));
84
137
  const main = await execFn(script);
85
138
  const { stdout, artifactNames } = extractArtifactMarker(main.stdout);
86
139
  const artifacts = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@larkup/sandbox",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -46,11 +46,11 @@
46
46
  "e2b": "^2.39.0",
47
47
  "@vercel/sandbox": "^3.0.0",
48
48
  "modal": "^0.11.0",
49
- "@daytona/sdk": "^0.224.1",
49
+ "@daytona/sdk": "^0.226.1",
50
50
  "@browserbasehq/sdk": "^2.17.0",
51
51
  "playwright-core": "^1.62.1",
52
52
  "@fly/sprites": "^0.2.0",
53
- "@northflank/js-client": "^0.11.0"
53
+ "@northflank/js-client": "^0.12.0"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@types/dockerode": "^4.0.1",