agent-neckbeard 1.1.16 → 1.1.18

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 ADDED
@@ -0,0 +1,6 @@
1
+ # Changelog
2
+
3
+ ## 1.1.18 - 2026-08-05
4
+
5
+ - Add harness-neutral `localDirectories` uploads beneath the sandbox agent directory, with recursive byte-preserving copies and deployment preflight validation.
6
+ - Deprecate `claudeDir` in favor of an explicit `localDirectories` mapping while keeping its `.claude` upload behavior backward compatible.
package/README.md CHANGED
@@ -8,6 +8,12 @@ The intent is simple: your production process should not run the agent. The sand
8
8
 
9
9
  This is designed to work from short-lived request handlers and long-running workers, including Vercel Functions, Hatchet workers, and Trigger.dev tasks. See `docs/CONSUMER_ENVIRONMENTS.md` before changing lifecycle, timeout, streaming, or cleanup behavior for those environments.
10
10
 
11
+ The three primary usage patterns:
12
+
13
+ - Workflows: a run-output agent runs once per background task and returns one validated output (Run-Output Agents below).
14
+ - Streaming: a persistent sandbox server emits typed progress frames while work runs (Streaming Agents below).
15
+ - Direct sandbox access: `SandboxClient` wraps E2B and Daytona behind one filesystem/command API, no agent required (Direct Sandbox Access below).
16
+
11
17
  ## What This Does
12
18
 
13
19
  You write an agent:
@@ -61,6 +67,8 @@ new Agent({
61
67
  });
62
68
  ```
63
69
 
70
+ When the right path differs between environments (for example a monorepo dev server versus a deployed worker), `resolveAgentSourceFile(candidates, { errorMessage })` returns the first candidate path that exists and falls back to the bundled agent module when running inside the sandbox.
71
+
64
72
  For Next.js/Vercel-style deployments, keep `agent-neckbeard` external to the server bundle and make sure the referenced source file is included in the production artifact:
65
73
 
66
74
  ```typescript
@@ -69,6 +77,10 @@ import { withNeckbeardNextConfig } from 'agent-neckbeard';
69
77
 
70
78
  const nextConfig = withNeckbeardNextConfig({
71
79
  // your existing Next config
80
+ outputFileTracingIncludes: {
81
+ // Include every localDirectories source tree used by deploy().
82
+ '/api/my-agent': ['./packages/my-agent/.agents/**/*'],
83
+ },
72
84
  }, {
73
85
  routeGlob: '/api/my-agent',
74
86
  sourceFiles: ['./packages/my-agent/src/agent.ts'],
@@ -77,7 +89,7 @@ const nextConfig = withNeckbeardNextConfig({
77
89
  export default nextConfig;
78
90
  ```
79
91
 
80
- The helper traces files imported by those source entries by default, including package entry metadata that `deploy()` needs when it rebundles the agent at runtime. For Next 13 configs that still use `experimental.serverComponentsExternalPackages`, the helper automatically uses the matching experimental tracing fields when it sees that shape. Set `outputFileTracingRoot` when the agent source is outside the app root.
92
+ The helper traces files imported by those source entries by default, including package entry metadata that `deploy()` needs when it rebundles the agent at runtime. It preserves and merges existing `outputFileTracingIncludes`, such as the `.agents/**/*` entry above. A `localDirectories.source` is read by the deployed process, so its complete tree must be included in the production function artifact. Set `outputFileTracingRoot` when the agent source or local directory is outside the app root.
81
93
 
82
94
  This repo tests that shape locally with `npm run test:compat:next`, which builds and runs a Dockerized Next App Router fixture without pushing to Vercel. The fixture also checks the runtime env contract, Node major, and traced standalone files so source-level tests do not mask deployment artifact problems.
83
95
 
@@ -141,9 +153,25 @@ run: async (input, ctx) => {
141
153
 
142
154
  Use `ctx.sandbox.homeDir` and `ctx.sandbox.agentDir` instead of hardcoding `/home/user` if you want the same agent code to work on both providers.
143
155
 
156
+ Run-output agents fit background workflows (Hatchet tasks, Trigger.dev jobs, queue workers). The usual shape is one sandbox per task:
157
+
158
+ ```typescript
159
+ const sandboxId = await agent.deploy({ fresh: true });
160
+
161
+ try {
162
+ const result = await agent.run(input, { sandboxId });
163
+ if (!result.ok) throw result.error;
164
+ return result.output;
165
+ } finally {
166
+ await agent.kill(sandboxId);
167
+ }
168
+ ```
169
+
170
+ `deploy({ fresh: true })` keeps concurrent tasks from sharing one cached sandbox; see Reusing Sandboxes for the caching behavior.
171
+
144
172
  ## Streaming Agents
145
173
 
146
- Use `server.handler` when you want progress frames while the sandbox work is still running:
174
+ Use `server.handler` when you want progress frames while the sandbox work is still running, such as relaying tool calls and assistant text to a UI or event log:
147
175
 
148
176
  ```typescript
149
177
  const agent = new Agent({
@@ -172,7 +200,7 @@ for await (const frame of agent.invoke({ prompt: 'hi' }, { sandboxId })) {
172
200
  }
173
201
  ```
174
202
 
175
- Internally, streaming uses Server-Sent Events from the sandbox `/invoke` endpoint. Neckbeard wraps user frames in harness events so errors, completion, and run-output results are handled consistently.
203
+ Internally, streaming uses Server-Sent Events from the sandbox `/invoke` endpoint. Neckbeard wraps user frames in harness events so errors, completion, and run-output results are handled consistently. `invoke()` also accepts an abort signal for host-side cancellation: `agent.invoke(input, { sandboxId, signal })`.
176
204
 
177
205
  ## Reusing Sandboxes
178
206
 
@@ -189,6 +217,8 @@ const result = await agent.run({ topic: 'hello' }, { sandboxId: savedSandboxId }
189
217
 
190
218
  Neckbeard rehydrates the sandbox endpoint and provider traffic token from the sandbox ID using the configured provider SDK. E2B traffic tokens are sent as the `e2b-traffic-access-token` header. Daytona preview tokens are sent as the `DAYTONA_SANDBOX_AUTH_KEY` query parameter. Consumers only need to store the sandbox ID and configure the same provider/API key in the process that reconnects.
191
219
 
220
+ `deploy()` caches the sandbox on the agent instance and returns the cached ID on later calls. Use `deploy({ fresh: true })` to provision a new sandbox without touching the instance cache, which is useful when one agent instance serves concurrent runs that each need their own sandbox. The caller owns the returned sandbox ID: pass it to `run()`/`invoke()` and `kill()` it explicitly.
221
+
192
222
  ### Environment Changes with Reused Sandboxes
193
223
 
194
224
  `envs` are applied when Neckbeard creates the sandbox and starts the sandbox server. If the host app was missing a required value such as `ANTHROPIC_API_KEY` when the sandbox was created, the sandbox can remain healthy but unauthenticated even after you fix the host environment and redeploy the app.
@@ -197,30 +227,36 @@ Updating Vercel, Render, or 1Password environment variables does not mutate alre
197
227
 
198
228
  ## Direct Sandbox Access
199
229
 
200
- Use `SandboxClient` when host code needs provider-neutral filesystem or command access without running an agent invocation:
230
+ Use `SandboxClient` when host code needs provider-neutral filesystem or command access without running an agent invocation, such as staging documents into a sandbox before an agent runs or pulling artifacts out afterward:
201
231
 
202
232
  ```typescript
203
233
  import { SandboxClient } from 'agent-neckbeard';
204
234
 
205
- const sandbox = await SandboxClient.connect({
206
- provider: 'e2b',
207
- sandboxId,
208
- timeoutMs: 30 * 60 * 1000,
235
+ const sandbox = await SandboxClient.create({
236
+ provider: 'daytona',
237
+ template: 'daytona-small',
238
+ domainAllowList: '*.example.com',
239
+ autoDeleteInterval: 30,
209
240
  });
210
241
 
211
- await sandbox.makeDir('/home/user/documents');
212
- await sandbox.writeFile('/home/user/documents/input.txt', 'hello');
242
+ const documentsDir = `${sandbox.paths.homeDir}/documents`;
243
+ await sandbox.makeDir(documentsDir);
244
+ await sandbox.writeFile(`${documentsDir}/input.txt`, 'hello');
213
245
  const result = await sandbox.runCommand('ls documents', {
214
- cwd: '/home/user',
246
+ cwd: sandbox.paths.homeDir,
215
247
  timeoutMs: 60_000,
216
248
  });
249
+ const bytes = await sandbox.readFileBytes(`${documentsDir}/input.txt`);
250
+ await sandbox.kill();
217
251
  ```
218
252
 
219
- `SandboxClient.create()` and `SandboxClient.connect()` support E2B and Daytona. E2B supports `setTimeout()` for sandbox lifetime extension; providers without that lifecycle primitive throw a `ConfigurationError`.
253
+ Reconnect to an existing sandbox with `SandboxClient.connect({ provider, sandboxId })`. `create()` accepts provider-specific lifetime options: `timeoutMs` on E2B and `autoDeleteInterval` in minutes on Daytona (`-1`, the default, disables auto-delete). `sandbox.paths` exposes the same provider-neutral paths agents receive as `ctx.sandbox`. E2B supports `setTimeout()` for sandbox lifetime extension; providers without that lifecycle primitive throw a `ConfigurationError`.
220
254
 
221
255
  ## Configuration
222
256
 
223
257
  ```typescript
258
+ import type { LocalDirectoryUpload } from 'agent-neckbeard';
259
+
224
260
  new Agent({
225
261
  sandbox: {
226
262
  provider: 'e2b' | 'daytona',
@@ -237,8 +273,13 @@ new Agent({
237
273
  commands?: string[],
238
274
  },
239
275
  files?: [{ url, path }],
240
- claudeDir?: string,
276
+ localDirectories?: LocalDirectoryUpload[],
277
+ claudeDir?: string, // deprecated; use localDirectories
241
278
  envs?: Record<string, string | undefined>,
279
+ build?: {
280
+ external?: string[],
281
+ autoDetectExternal?: boolean,
282
+ },
242
283
  // Run-output agents require:
243
284
  outputSchema: ZodSchema,
244
285
  run: (input, ctx) => Promise<output>,
@@ -251,9 +292,52 @@ new Agent({
251
292
  });
252
293
  ```
253
294
 
254
- The `files` option downloads files into the sandbox before the server starts. Relative paths resolve from the sandbox home directory: `/home/user` on E2B and `/home/daytona` on Daytona.
295
+ The `files` option downloads files into the sandbox before the server starts. Relative paths resolve from the sandbox home directory: `/home/user` on E2B and the sandbox user's home on Daytona (`/home/daytona` on default snapshots).
296
+
297
+ `LocalDirectoryUpload` is exported by the package and has this shape:
298
+
299
+ ```typescript
300
+ interface LocalDirectoryUpload {
301
+ source: string;
302
+ destination: string;
303
+ }
304
+ ```
305
+
306
+ `localDirectories` recursively copies consumer-selected local directories beneath `ctx.sandbox.agentDir` during `deploy()`. Relative sources resolve from the deploying process's current working directory; absolute sources are also supported. Nested paths and dotfiles are included, text and binary files retain their exact bytes, and parent directories are created as needed. Empty directories are not preserved.
255
307
 
256
- The `claudeDir` option uploads a local `.claude/` directory to the sandbox, enabling Claude Agent SDK skills. Point it at a directory containing `.claude/skills/*/SKILL.md` files.
308
+ Each `destination` is relative to the sandbox agent directory. For example, this Pi-oriented configuration produces `<sandbox agentDir>/.agents/skills/...` on both E2B and Daytona:
309
+
310
+ ```typescript
311
+ const agent = new Agent({
312
+ localDirectories: [
313
+ {
314
+ source: './packages/my-agent/.agents',
315
+ destination: '.agents',
316
+ },
317
+ ],
318
+ // ...run-output or streaming agent configuration
319
+ });
320
+ ```
321
+
322
+ Copying skills to `.agents/skills` does not guarantee that Pi or another harness will discover them automatically. If the harness working directory is elsewhere, pass `${ctx.sandbox.agentDir}/.agents/skills` to it as an explicit skill path. Neckbeard does not detect harnesses or change their discovery and trust settings.
323
+
324
+ Before creating a sandbox, Neckbeard validates and enumerates every local upload. A source must exist and be a directory. `localDirectories` rejects symbolic links anywhere in a source tree, with the local path in the error. Empty destinations, `.`, absolute destinations, traversal outside the agent directory, and duplicate sandbox targets are rejected with `ConfigurationError`; this includes collisions with another entry or with `claudeDir`.
325
+
326
+ For Next.js/Vercel and other bundled deployment environments, ensure each source tree is present in the runtime artifact. Include it with `withNeckbeardNextConfig` as shown above, with raw `outputFileTracingIncludes`, or with the equivalent artifact-inclusion setting for the host framework.
327
+
328
+ `claudeDir` is deprecated but remains functional for backward compatibility. It uploads the contents of a local `.claude` directory to `<sandbox agentDir>/.claude`, preserving existing Claude Agent SDK behavior. Replace it with an explicit `localDirectories` mapping:
329
+
330
+ ```typescript
331
+ const agent = new Agent({
332
+ localDirectories: [
333
+ {
334
+ source: './my-project/.claude',
335
+ destination: '.claude',
336
+ },
337
+ ],
338
+ // ...agent configuration
339
+ });
340
+ ```
257
341
 
258
342
  The `envs` option passes environment variables to the sandbox. Undefined values are filtered out:
259
343
 
@@ -271,21 +355,17 @@ const agent = new Agent({
271
355
  });
272
356
  ```
273
357
 
274
- Some packages cannot be bundled because they spawn child processes or have native modules. The Claude Agent SDK is like this. These packages are automatically marked external and installed with npm in the sandbox.
358
+ Some packages cannot be bundled because they spawn child processes or have native modules. The Claude Agent SDK is like this. These packages are automatically marked external and installed with npm in the sandbox. The `build` option tunes this: `build.external` adds package globs to mark external, and `build.autoDetectExternal: false` disables the native-module auto-detection.
275
359
 
276
360
  ## Cleanup
277
361
 
278
- ```typescript
279
- const sandboxId = await agent.deploy();
362
+ Neckbeard never kills a sandbox on its own; sandboxes run until you kill them or the provider's lifetime settings expire them. Kill every sandbox you deploy, as in the workflow example above. `kill()` accepts a sandbox ID. If omitted, it kills the sandbox cached on the agent instance.
280
363
 
281
- try {
282
- const result = await agent.run(input, { sandboxId });
283
- } finally {
284
- await agent.kill(sandboxId);
285
- }
286
- ```
364
+ ## Errors
365
+
366
+ All errors extend `NeckbeardError`. `ConfigurationError` covers invalid agent config, missing provider API keys, and provider features a sandbox does not support. `DeploymentError` covers sandbox creation, dependency install, and runtime server startup failures, and includes captured server logs when the health check fails. `ValidationError` wraps input/output schema failures with the parser error as `cause`. `ExecutionError` represents agent handler failures.
287
367
 
288
- `kill()` accepts a sandbox ID. If omitted, it kills the sandbox cached on the agent instance.
368
+ `run()` never throws; it returns `{ ok: false, error }`. `invoke()` throws.
289
369
 
290
370
  ## Testing
291
371
 
package/dist/index.cjs CHANGED
@@ -327,35 +327,6 @@ function withNeckbeardNextConfig(nextConfig, options) {
327
327
  sourceFiles,
328
328
  traceSourceDependencies
329
329
  );
330
- const experimental = asRecord(nextConfig.experimental);
331
- const useLegacyExperimental = options.legacyExperimental ?? ("serverComponentsExternalPackages" in experimental || "outputFileTracingIncludes" in experimental || "outputFileTracingRoot" in experimental);
332
- if (useLegacyExperimental) {
333
- const nextExperimental = {
334
- ...experimental,
335
- serverComponentsExternalPackages: mergeStringArray(
336
- experimental.serverComponentsExternalPackages,
337
- [NECKBEARD_PACKAGE_NAME]
338
- ),
339
- outputFileTracingIncludes: mergeTracingIncludes(
340
- experimental.outputFileTracingIncludes,
341
- routeGlobs,
342
- traceIncludeFiles
343
- )
344
- };
345
- if (options.outputFileTracingRoot !== void 0) {
346
- nextExperimental.outputFileTracingRoot = options.outputFileTracingRoot;
347
- }
348
- return {
349
- ...nextConfig,
350
- experimental: nextExperimental,
351
- webpack: withNextTraceIncludeWebpack(
352
- nextConfig.webpack,
353
- sourceFiles,
354
- routeGlobs,
355
- traceSourceDependencies
356
- )
357
- };
358
- }
359
330
  const result = {
360
331
  ...nextConfig,
361
332
  serverExternalPackages: mergeStringArray(nextConfig.serverExternalPackages, [
@@ -773,6 +744,53 @@ function requireSchemaLike(name, value) {
773
744
  }
774
745
  return value;
775
746
  }
747
+ function normalizeLocalDirectoryDestination(destination, name) {
748
+ if (destination.trim() === "") {
749
+ throw new ConfigurationError(`${name}.destination must be a non-empty relative path.`);
750
+ }
751
+ if (destination.includes("\0")) {
752
+ throw new ConfigurationError(`${name}.destination must not contain null bytes.`);
753
+ }
754
+ const sandboxPath = destination.replace(/\\/g, "/");
755
+ if ((0, import_node_path.isAbsolute)(destination) || import_node_path.posix.isAbsolute(sandboxPath) || import_node_path.win32.isAbsolute(destination)) {
756
+ throw new ConfigurationError(
757
+ `${name}.destination must be relative to the sandbox agent directory.`
758
+ );
759
+ }
760
+ if (sandboxPath.split("/").includes("..")) {
761
+ throw new ConfigurationError(
762
+ `${name}.destination must not traverse outside the sandbox agent directory.`
763
+ );
764
+ }
765
+ const normalized = import_node_path.posix.normalize(sandboxPath);
766
+ if (normalized === ".") {
767
+ throw new ConfigurationError(`${name}.destination must not be ".".`);
768
+ }
769
+ return normalized;
770
+ }
771
+ function validateLocalDirectoriesConfig(value) {
772
+ if (value === void 0) return;
773
+ if (!Array.isArray(value)) {
774
+ throw new ConfigurationError("localDirectories must be an array when provided.");
775
+ }
776
+ for (const [index, entry] of value.entries()) {
777
+ const name = `localDirectories[${index}]`;
778
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
779
+ throw new ConfigurationError(`${name} must be an object.`);
780
+ }
781
+ const candidate = entry;
782
+ if (typeof candidate.source !== "string" || candidate.source.trim() === "") {
783
+ throw new ConfigurationError(`${name}.source must be a non-empty string.`);
784
+ }
785
+ if (candidate.source.includes("\0")) {
786
+ throw new ConfigurationError(`${name}.source must not contain null bytes.`);
787
+ }
788
+ if (typeof candidate.destination !== "string") {
789
+ throw new ConfigurationError(`${name}.destination must be a string.`);
790
+ }
791
+ normalizeLocalDirectoryDestination(candidate.destination, name);
792
+ }
793
+ }
776
794
  function validateAgentConfig(config) {
777
795
  if (!config || typeof config !== "object") {
778
796
  throw new ConfigurationError("Agent config must be an object.");
@@ -793,6 +811,7 @@ function validateAgentConfig(config) {
793
811
  if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
794
812
  throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
795
813
  }
814
+ validateLocalDirectoriesConfig(config.localDirectories);
796
815
  if (isServerAgentConfig(config)) {
797
816
  if ("run" in config && typeof config.run === "function") {
798
817
  throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
@@ -1151,8 +1170,8 @@ var E2bSandboxHandle = class {
1151
1170
  trafficToken: this.sandbox.trafficAccessToken
1152
1171
  };
1153
1172
  }
1154
- destroy() {
1155
- return this.sandbox.kill();
1173
+ async destroy() {
1174
+ await this.sandbox.kill();
1156
1175
  }
1157
1176
  };
1158
1177
  var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
@@ -1411,30 +1430,131 @@ function resolveSourceFile(sourceFile) {
1411
1430
  }
1412
1431
  return resolved;
1413
1432
  }
1414
- function readDirectoryRecursively(dirPath) {
1433
+ function localPathStats(localPath, upload, isSourceRoot = false) {
1434
+ let stats;
1435
+ try {
1436
+ stats = (0, import_node_fs.lstatSync)(localPath);
1437
+ } catch (error) {
1438
+ const code = error.code;
1439
+ const detail = isSourceRoot && code === "ENOENT" ? "source does not exist" : "could not read local path";
1440
+ throw new ConfigurationError(
1441
+ `${upload.name} ${detail}: ${localPath} (${errorMessage(error)})`
1442
+ );
1443
+ }
1444
+ if (!stats.isSymbolicLink()) return stats;
1445
+ if (upload.rejectSymlinks) {
1446
+ throw new ConfigurationError(
1447
+ `${upload.name} source tree contains a symbolic link: ${localPath}`
1448
+ );
1449
+ }
1450
+ try {
1451
+ return (0, import_node_fs.statSync)(localPath);
1452
+ } catch (error) {
1453
+ throw new ConfigurationError(
1454
+ `${upload.name} could not follow legacy symbolic link: ${localPath} (${errorMessage(error)})`
1455
+ );
1456
+ }
1457
+ }
1458
+ function readConfiguredLocalDirectory(upload) {
1459
+ const rootPath = (0, import_node_path.resolve)(process.cwd(), upload.source);
1460
+ const rootStats = localPathStats(rootPath, upload, true);
1461
+ if (!rootStats.isDirectory()) {
1462
+ throw new ConfigurationError(`${upload.name}.source must be a directory: ${rootPath}`);
1463
+ }
1464
+ const destination = normalizeLocalDirectoryDestination(upload.destination, upload.name);
1415
1465
  const files = [];
1416
- function walkDir(currentPath) {
1417
- const entries = (0, import_node_fs.readdirSync)(currentPath);
1466
+ function walk(currentPath) {
1467
+ let entries;
1468
+ try {
1469
+ entries = (0, import_node_fs.readdirSync)(currentPath).sort((left, right) => left.localeCompare(right));
1470
+ } catch (error) {
1471
+ throw new ConfigurationError(
1472
+ `${upload.name} could not read local directory: ${currentPath} (${errorMessage(error)})`
1473
+ );
1474
+ }
1418
1475
  for (const entry of entries) {
1419
- const fullPath = (0, import_node_path.join)(currentPath, entry);
1420
- const stat = (0, import_node_fs.statSync)(fullPath);
1421
- if (stat.isDirectory()) {
1422
- walkDir(fullPath);
1423
- } else if (stat.isFile()) {
1424
- const relPath = (0, import_node_path.relative)(dirPath, fullPath);
1425
- const isBinary = /\.(png|jpg|jpeg|gif|ico|pdf|zip|tar|gz|bin|exe|dll|so|dylib|wasm)$/i.test(entry);
1426
- if (isBinary) {
1427
- const buffer = (0, import_node_fs.readFileSync)(fullPath);
1428
- const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
1429
- files.push({ relativePath: relPath, content: arrayBuffer });
1430
- } else {
1431
- files.push({ relativePath: relPath, content: (0, import_node_fs.readFileSync)(fullPath, "utf-8") });
1432
- }
1476
+ const localPath = (0, import_node_path.join)(currentPath, entry);
1477
+ const stats = localPathStats(localPath, upload);
1478
+ if (stats.isDirectory()) {
1479
+ walk(localPath);
1480
+ continue;
1481
+ }
1482
+ if (!stats.isFile()) {
1483
+ throw new ConfigurationError(
1484
+ `${upload.name} source tree contains an unsupported filesystem entry: ${localPath}`
1485
+ );
1433
1486
  }
1487
+ const relativePath = (0, import_node_path.relative)(rootPath, localPath).split(import_node_path.sep).join("/");
1488
+ const targetPath = import_node_path.posix.join(destination, relativePath);
1489
+ let content;
1490
+ try {
1491
+ content = (0, import_node_fs.readFileSync)(localPath);
1492
+ } catch (error) {
1493
+ throw new ConfigurationError(
1494
+ `${upload.name} could not read local file: ${localPath} (${errorMessage(error)})`
1495
+ );
1496
+ }
1497
+ files.push({ localPath, targetPath, content });
1498
+ }
1499
+ }
1500
+ walk(rootPath);
1501
+ return { rootPath, files };
1502
+ }
1503
+ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
1504
+ const uploads = localDirectories.map((entry, index) => ({
1505
+ ...entry,
1506
+ name: `localDirectories[${index}]`,
1507
+ rejectSymlinks: true,
1508
+ preserveRootDirectory: false
1509
+ }));
1510
+ if (claudeDir) {
1511
+ uploads.push({
1512
+ source: claudeDir,
1513
+ destination: ".claude",
1514
+ name: "claudeDir",
1515
+ rejectSymlinks: false,
1516
+ preserveRootDirectory: true
1517
+ });
1518
+ }
1519
+ const filesByTarget = /* @__PURE__ */ new Map();
1520
+ const requiredDirectories = /* @__PURE__ */ new Set();
1521
+ for (const upload of uploads) {
1522
+ const prepared = readConfiguredLocalDirectory(upload);
1523
+ const destination = normalizeLocalDirectoryDestination(upload.destination, upload.name);
1524
+ if (upload.preserveRootDirectory) {
1525
+ requiredDirectories.add(destination);
1526
+ }
1527
+ for (const file of prepared.files) {
1528
+ const existing = filesByTarget.get(file.targetPath);
1529
+ if (existing) {
1530
+ throw new ConfigurationError(
1531
+ `Duplicate sandbox target "${file.targetPath}" from local files "${existing.localPath}" and "${file.localPath}".`
1532
+ );
1533
+ }
1534
+ filesByTarget.set(file.targetPath, file);
1434
1535
  }
1435
1536
  }
1436
- walkDir(dirPath);
1437
- return files;
1537
+ for (const file of filesByTarget.values()) {
1538
+ let parent = import_node_path.posix.dirname(file.targetPath);
1539
+ while (parent !== ".") {
1540
+ const parentFile = filesByTarget.get(parent);
1541
+ if (parentFile) {
1542
+ throw new ConfigurationError(
1543
+ `Sandbox target collision: local file "${parentFile.localPath}" maps to "${parent}", which must be a directory for "${file.localPath}".`
1544
+ );
1545
+ }
1546
+ requiredDirectories.add(parent);
1547
+ parent = import_node_path.posix.dirname(parent);
1548
+ }
1549
+ }
1550
+ const directories = [...requiredDirectories].sort((left, right) => {
1551
+ const depthDifference = left.split("/").length - right.split("/").length;
1552
+ return depthDifference || left.localeCompare(right);
1553
+ });
1554
+ const files = [...filesByTarget.values()].sort(
1555
+ (left, right) => left.targetPath.localeCompare(right.targetPath)
1556
+ );
1557
+ return { directories, files };
1438
1558
  }
1439
1559
  var Agent = class {
1440
1560
  sandbox;
@@ -1449,6 +1569,8 @@ var Agent = class {
1449
1569
  maxDuration;
1450
1570
  dependencies;
1451
1571
  files;
1572
+ localDirectories;
1573
+ /** @deprecated Use `localDirectories` with destination `.claude` instead. */
1452
1574
  claudeDir;
1453
1575
  envs;
1454
1576
  build;
@@ -1470,6 +1592,7 @@ var Agent = class {
1470
1592
  this._sourceFile = resolveSourceFile(config.sourceFile);
1471
1593
  this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
1472
1594
  this.files = config.files ?? [];
1595
+ this.localDirectories = (config.localDirectories ?? []).map((entry) => ({ ...entry }));
1473
1596
  this.claudeDir = config.claudeDir;
1474
1597
  this.envs = config.envs ?? {};
1475
1598
  this.build = config.build ?? {};
@@ -1672,6 +1795,10 @@ ${parts.join("\n\n")}`;
1672
1795
  }
1673
1796
  async _deploy(options) {
1674
1797
  if (!options?.fresh && this._serverRuntime) return this._serverRuntime.connection.sandboxId;
1798
+ const localDirectoryUploads = prepareLocalDirectoryUploads(
1799
+ this.localDirectories,
1800
+ this.claudeDir
1801
+ );
1675
1802
  const esbuild = await getEsbuild();
1676
1803
  const externalPatterns = Array.from(
1677
1804
  /* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
@@ -1805,21 +1932,14 @@ var require = __neckbeard_createRequire(import.meta.url);
1805
1932
  }
1806
1933
  }
1807
1934
  }
1808
- if (this.claudeDir) {
1809
- const claudeFiles = readDirectoryRecursively(this.claudeDir);
1810
- await sandbox.runCommand(`mkdir -p ${shellEscape(paths.claudeDir)}`, {
1811
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
1812
- });
1813
- for (const file of claudeFiles) {
1814
- const destPath = `${paths.claudeDir}/${file.relativePath}`;
1815
- const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
1816
- if (parentDir && parentDir !== paths.claudeDir) {
1817
- await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
1818
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
1819
- });
1820
- }
1821
- await sandbox.writeFile(destPath, file.content);
1822
- }
1935
+ for (const directory of localDirectoryUploads.directories) {
1936
+ await sandbox.makeDir(import_node_path.posix.join(paths.agentDir, directory));
1937
+ }
1938
+ for (const file of localDirectoryUploads.files) {
1939
+ await sandbox.writeFile(
1940
+ import_node_path.posix.join(paths.agentDir, file.targetPath),
1941
+ file.content
1942
+ );
1823
1943
  }
1824
1944
  await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
1825
1945
  await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
package/dist/index.d.cts CHANGED
@@ -114,13 +114,6 @@ interface NeckbeardNextConfigOptions {
114
114
  * live outside the app directory.
115
115
  */
116
116
  outputFileTracingRoot?: string;
117
- /**
118
- * Force the older Next.js experimental config placement used by Next 13.
119
- *
120
- * By default this is inferred when the provided config already uses
121
- * `experimental.serverComponentsExternalPackages` or experimental tracing.
122
- */
123
- legacyExperimental?: boolean;
124
117
  }
125
118
  interface ResolveAgentSourceFileOptions {
126
119
  /** Custom error prefix when no source file candidate exists outside the sandbox runtime. */
@@ -134,7 +127,6 @@ interface ResolveAgentSourceFileOptions {
134
127
  }
135
128
  declare function resolveAgentSourceFile(candidates: string[], options?: ResolveAgentSourceFileOptions): string;
136
129
  type NextConfigObject = {
137
- experimental?: Record<string, unknown>;
138
130
  outputFileTracingIncludes?: Record<string, unknown>;
139
131
  outputFileTracingRoot?: string;
140
132
  serverExternalPackages?: string[];
@@ -167,6 +159,23 @@ interface FileDownload {
167
159
  */
168
160
  path: string;
169
161
  }
162
+ /**
163
+ * Configuration for recursively copying a local directory into the sandbox
164
+ * agent directory during deploy().
165
+ */
166
+ interface LocalDirectoryUpload {
167
+ /**
168
+ * Local source directory. Relative paths resolve from the deploying
169
+ * process's current working directory.
170
+ */
171
+ source: string;
172
+ /**
173
+ * Destination directory relative to `ctx.sandbox.agentDir`.
174
+ * Absolute paths and paths that traverse outside the agent directory are
175
+ * rejected.
176
+ */
177
+ destination: string;
178
+ }
170
179
  /** Default dependencies - empty by default, specify what you need */
171
180
  declare const DEFAULT_DEPENDENCIES: OsDependencies;
172
181
  interface AgentSharedConfig<TInput> {
@@ -182,7 +191,7 @@ interface AgentSharedConfig<TInput> {
182
191
  * Next.js route handler running from `.next/server/chunks/*.js`.
183
192
  */
184
193
  sourceFile?: string;
185
- /** OS-level dependencies to install in the sandbox. Defaults to Claude Code. Set to {} to skip. */
194
+ /** OS-level dependencies to install in the sandbox. Defaults to none. */
186
195
  dependencies?: OsDependencies;
187
196
  /**
188
197
  * Files to download and initialize in the sandbox filesystem.
@@ -191,7 +200,19 @@ interface AgentSharedConfig<TInput> {
191
200
  */
192
201
  files?: FileDownload[];
193
202
  /**
194
- * Local path to a .claude directory containing skills and settings.
203
+ * Local directories to recursively upload beneath the sandbox agent
204
+ * directory. Dotfiles and exact file bytes are preserved. Symbolic links
205
+ * are rejected.
206
+ *
207
+ * @example
208
+ * ```typescript
209
+ * localDirectories: [{ source: './.agents', destination: '.agents' }]
210
+ * ```
211
+ */
212
+ localDirectories?: LocalDirectoryUpload[];
213
+ /**
214
+ * Legacy Claude-specific convenience option. Local path to a .claude
215
+ * directory containing skills and settings.
195
216
  * The directory will be uploaded to {homeDir}/agent/.claude/ in the sandbox.
196
217
  * This enables Claude Agent SDK to access skills defined in SKILL.md files
197
218
  * within .claude/skills/ subdirectories.
@@ -202,6 +223,8 @@ interface AgentSharedConfig<TInput> {
202
223
  * - cwd is set to {homeDir}/agent/ (containing .claude/)
203
224
  * - settingSources includes 'project'
204
225
  * - allowedTools includes 'Skill'
226
+ *
227
+ * @deprecated Use `localDirectories` with destination `.claude` instead.
205
228
  */
206
229
  claudeDir?: string;
207
230
  /**
@@ -386,6 +409,8 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
386
409
  readonly maxDuration: number;
387
410
  readonly dependencies: OsDependencies;
388
411
  readonly files: FileDownload[];
412
+ readonly localDirectories: LocalDirectoryUpload[];
413
+ /** @deprecated Use `localDirectories` with destination `.claude` instead. */
389
414
  readonly claudeDir?: string;
390
415
  readonly envs: Record<string, string | undefined>;
391
416
  readonly build: BuildOptions;
@@ -485,4 +510,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
485
510
  }): AsyncGenerator<TFrame>;
486
511
  }
487
512
 
488
- export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, SandboxClient, type SandboxClientConnectOptions, type SandboxClientCreateOptions, type SandboxCommandOptions, type SandboxCommandResult, type SandboxConfig, type SandboxFileContent, type SandboxProvider, type ServerAgentConfig, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
513
+ export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, type LocalDirectoryUpload, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, SandboxClient, type SandboxClientConnectOptions, type SandboxClientCreateOptions, type SandboxCommandOptions, type SandboxCommandResult, type SandboxConfig, type SandboxFileContent, type SandboxProvider, type ServerAgentConfig, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
package/dist/index.d.ts CHANGED
@@ -114,13 +114,6 @@ interface NeckbeardNextConfigOptions {
114
114
  * live outside the app directory.
115
115
  */
116
116
  outputFileTracingRoot?: string;
117
- /**
118
- * Force the older Next.js experimental config placement used by Next 13.
119
- *
120
- * By default this is inferred when the provided config already uses
121
- * `experimental.serverComponentsExternalPackages` or experimental tracing.
122
- */
123
- legacyExperimental?: boolean;
124
117
  }
125
118
  interface ResolveAgentSourceFileOptions {
126
119
  /** Custom error prefix when no source file candidate exists outside the sandbox runtime. */
@@ -134,7 +127,6 @@ interface ResolveAgentSourceFileOptions {
134
127
  }
135
128
  declare function resolveAgentSourceFile(candidates: string[], options?: ResolveAgentSourceFileOptions): string;
136
129
  type NextConfigObject = {
137
- experimental?: Record<string, unknown>;
138
130
  outputFileTracingIncludes?: Record<string, unknown>;
139
131
  outputFileTracingRoot?: string;
140
132
  serverExternalPackages?: string[];
@@ -167,6 +159,23 @@ interface FileDownload {
167
159
  */
168
160
  path: string;
169
161
  }
162
+ /**
163
+ * Configuration for recursively copying a local directory into the sandbox
164
+ * agent directory during deploy().
165
+ */
166
+ interface LocalDirectoryUpload {
167
+ /**
168
+ * Local source directory. Relative paths resolve from the deploying
169
+ * process's current working directory.
170
+ */
171
+ source: string;
172
+ /**
173
+ * Destination directory relative to `ctx.sandbox.agentDir`.
174
+ * Absolute paths and paths that traverse outside the agent directory are
175
+ * rejected.
176
+ */
177
+ destination: string;
178
+ }
170
179
  /** Default dependencies - empty by default, specify what you need */
171
180
  declare const DEFAULT_DEPENDENCIES: OsDependencies;
172
181
  interface AgentSharedConfig<TInput> {
@@ -182,7 +191,7 @@ interface AgentSharedConfig<TInput> {
182
191
  * Next.js route handler running from `.next/server/chunks/*.js`.
183
192
  */
184
193
  sourceFile?: string;
185
- /** OS-level dependencies to install in the sandbox. Defaults to Claude Code. Set to {} to skip. */
194
+ /** OS-level dependencies to install in the sandbox. Defaults to none. */
186
195
  dependencies?: OsDependencies;
187
196
  /**
188
197
  * Files to download and initialize in the sandbox filesystem.
@@ -191,7 +200,19 @@ interface AgentSharedConfig<TInput> {
191
200
  */
192
201
  files?: FileDownload[];
193
202
  /**
194
- * Local path to a .claude directory containing skills and settings.
203
+ * Local directories to recursively upload beneath the sandbox agent
204
+ * directory. Dotfiles and exact file bytes are preserved. Symbolic links
205
+ * are rejected.
206
+ *
207
+ * @example
208
+ * ```typescript
209
+ * localDirectories: [{ source: './.agents', destination: '.agents' }]
210
+ * ```
211
+ */
212
+ localDirectories?: LocalDirectoryUpload[];
213
+ /**
214
+ * Legacy Claude-specific convenience option. Local path to a .claude
215
+ * directory containing skills and settings.
195
216
  * The directory will be uploaded to {homeDir}/agent/.claude/ in the sandbox.
196
217
  * This enables Claude Agent SDK to access skills defined in SKILL.md files
197
218
  * within .claude/skills/ subdirectories.
@@ -202,6 +223,8 @@ interface AgentSharedConfig<TInput> {
202
223
  * - cwd is set to {homeDir}/agent/ (containing .claude/)
203
224
  * - settingSources includes 'project'
204
225
  * - allowedTools includes 'Skill'
226
+ *
227
+ * @deprecated Use `localDirectories` with destination `.claude` instead.
205
228
  */
206
229
  claudeDir?: string;
207
230
  /**
@@ -386,6 +409,8 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
386
409
  readonly maxDuration: number;
387
410
  readonly dependencies: OsDependencies;
388
411
  readonly files: FileDownload[];
412
+ readonly localDirectories: LocalDirectoryUpload[];
413
+ /** @deprecated Use `localDirectories` with destination `.claude` instead. */
389
414
  readonly claudeDir?: string;
390
415
  readonly envs: Record<string, string | undefined>;
391
416
  readonly build: BuildOptions;
@@ -485,4 +510,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
485
510
  }): AsyncGenerator<TFrame>;
486
511
  }
487
512
 
488
- export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, SandboxClient, type SandboxClientConnectOptions, type SandboxClientCreateOptions, type SandboxCommandOptions, type SandboxCommandResult, type SandboxConfig, type SandboxFileContent, type SandboxProvider, type ServerAgentConfig, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
513
+ export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, type LocalDirectoryUpload, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, SandboxClient, type SandboxClientConnectOptions, type SandboxClientCreateOptions, type SandboxCommandOptions, type SandboxCommandResult, type SandboxConfig, type SandboxFileContent, type SandboxProvider, type ServerAgentConfig, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
package/dist/index.js CHANGED
@@ -4,8 +4,25 @@ import {
4
4
 
5
5
  // src/index.ts
6
6
  import { fileURLToPath } from "url";
7
- import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "fs";
8
- import { basename, dirname, join, relative, resolve } from "path";
7
+ import {
8
+ existsSync,
9
+ lstatSync,
10
+ readdirSync,
11
+ readFileSync,
12
+ statSync,
13
+ writeFileSync
14
+ } from "fs";
15
+ import {
16
+ basename,
17
+ dirname,
18
+ isAbsolute,
19
+ join,
20
+ posix,
21
+ relative,
22
+ resolve,
23
+ sep,
24
+ win32
25
+ } from "path";
9
26
  import { builtinModules, createRequire } from "module";
10
27
 
11
28
  // src/runtime/server-source.generated.ts
@@ -93,35 +110,6 @@ function withNeckbeardNextConfig(nextConfig, options) {
93
110
  sourceFiles,
94
111
  traceSourceDependencies
95
112
  );
96
- const experimental = asRecord(nextConfig.experimental);
97
- const useLegacyExperimental = options.legacyExperimental ?? ("serverComponentsExternalPackages" in experimental || "outputFileTracingIncludes" in experimental || "outputFileTracingRoot" in experimental);
98
- if (useLegacyExperimental) {
99
- const nextExperimental = {
100
- ...experimental,
101
- serverComponentsExternalPackages: mergeStringArray(
102
- experimental.serverComponentsExternalPackages,
103
- [NECKBEARD_PACKAGE_NAME]
104
- ),
105
- outputFileTracingIncludes: mergeTracingIncludes(
106
- experimental.outputFileTracingIncludes,
107
- routeGlobs,
108
- traceIncludeFiles
109
- )
110
- };
111
- if (options.outputFileTracingRoot !== void 0) {
112
- nextExperimental.outputFileTracingRoot = options.outputFileTracingRoot;
113
- }
114
- return {
115
- ...nextConfig,
116
- experimental: nextExperimental,
117
- webpack: withNextTraceIncludeWebpack(
118
- nextConfig.webpack,
119
- sourceFiles,
120
- routeGlobs,
121
- traceSourceDependencies
122
- )
123
- };
124
- }
125
113
  const result = {
126
114
  ...nextConfig,
127
115
  serverExternalPackages: mergeStringArray(nextConfig.serverExternalPackages, [
@@ -539,6 +527,53 @@ function requireSchemaLike(name, value) {
539
527
  }
540
528
  return value;
541
529
  }
530
+ function normalizeLocalDirectoryDestination(destination, name) {
531
+ if (destination.trim() === "") {
532
+ throw new ConfigurationError(`${name}.destination must be a non-empty relative path.`);
533
+ }
534
+ if (destination.includes("\0")) {
535
+ throw new ConfigurationError(`${name}.destination must not contain null bytes.`);
536
+ }
537
+ const sandboxPath = destination.replace(/\\/g, "/");
538
+ if (isAbsolute(destination) || posix.isAbsolute(sandboxPath) || win32.isAbsolute(destination)) {
539
+ throw new ConfigurationError(
540
+ `${name}.destination must be relative to the sandbox agent directory.`
541
+ );
542
+ }
543
+ if (sandboxPath.split("/").includes("..")) {
544
+ throw new ConfigurationError(
545
+ `${name}.destination must not traverse outside the sandbox agent directory.`
546
+ );
547
+ }
548
+ const normalized = posix.normalize(sandboxPath);
549
+ if (normalized === ".") {
550
+ throw new ConfigurationError(`${name}.destination must not be ".".`);
551
+ }
552
+ return normalized;
553
+ }
554
+ function validateLocalDirectoriesConfig(value) {
555
+ if (value === void 0) return;
556
+ if (!Array.isArray(value)) {
557
+ throw new ConfigurationError("localDirectories must be an array when provided.");
558
+ }
559
+ for (const [index, entry] of value.entries()) {
560
+ const name = `localDirectories[${index}]`;
561
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
562
+ throw new ConfigurationError(`${name} must be an object.`);
563
+ }
564
+ const candidate = entry;
565
+ if (typeof candidate.source !== "string" || candidate.source.trim() === "") {
566
+ throw new ConfigurationError(`${name}.source must be a non-empty string.`);
567
+ }
568
+ if (candidate.source.includes("\0")) {
569
+ throw new ConfigurationError(`${name}.source must not contain null bytes.`);
570
+ }
571
+ if (typeof candidate.destination !== "string") {
572
+ throw new ConfigurationError(`${name}.destination must be a string.`);
573
+ }
574
+ normalizeLocalDirectoryDestination(candidate.destination, name);
575
+ }
576
+ }
542
577
  function validateAgentConfig(config) {
543
578
  if (!config || typeof config !== "object") {
544
579
  throw new ConfigurationError("Agent config must be an object.");
@@ -559,6 +594,7 @@ function validateAgentConfig(config) {
559
594
  if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
560
595
  throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
561
596
  }
597
+ validateLocalDirectoriesConfig(config.localDirectories);
562
598
  if (isServerAgentConfig(config)) {
563
599
  if ("run" in config && typeof config.run === "function") {
564
600
  throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
@@ -917,8 +953,8 @@ var E2bSandboxHandle = class {
917
953
  trafficToken: this.sandbox.trafficAccessToken
918
954
  };
919
955
  }
920
- destroy() {
921
- return this.sandbox.kill();
956
+ async destroy() {
957
+ await this.sandbox.kill();
922
958
  }
923
959
  };
924
960
  var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
@@ -1177,30 +1213,131 @@ function resolveSourceFile(sourceFile) {
1177
1213
  }
1178
1214
  return resolved;
1179
1215
  }
1180
- function readDirectoryRecursively(dirPath) {
1216
+ function localPathStats(localPath, upload, isSourceRoot = false) {
1217
+ let stats;
1218
+ try {
1219
+ stats = lstatSync(localPath);
1220
+ } catch (error) {
1221
+ const code = error.code;
1222
+ const detail = isSourceRoot && code === "ENOENT" ? "source does not exist" : "could not read local path";
1223
+ throw new ConfigurationError(
1224
+ `${upload.name} ${detail}: ${localPath} (${errorMessage(error)})`
1225
+ );
1226
+ }
1227
+ if (!stats.isSymbolicLink()) return stats;
1228
+ if (upload.rejectSymlinks) {
1229
+ throw new ConfigurationError(
1230
+ `${upload.name} source tree contains a symbolic link: ${localPath}`
1231
+ );
1232
+ }
1233
+ try {
1234
+ return statSync(localPath);
1235
+ } catch (error) {
1236
+ throw new ConfigurationError(
1237
+ `${upload.name} could not follow legacy symbolic link: ${localPath} (${errorMessage(error)})`
1238
+ );
1239
+ }
1240
+ }
1241
+ function readConfiguredLocalDirectory(upload) {
1242
+ const rootPath = resolve(process.cwd(), upload.source);
1243
+ const rootStats = localPathStats(rootPath, upload, true);
1244
+ if (!rootStats.isDirectory()) {
1245
+ throw new ConfigurationError(`${upload.name}.source must be a directory: ${rootPath}`);
1246
+ }
1247
+ const destination = normalizeLocalDirectoryDestination(upload.destination, upload.name);
1181
1248
  const files = [];
1182
- function walkDir(currentPath) {
1183
- const entries = readdirSync(currentPath);
1249
+ function walk(currentPath) {
1250
+ let entries;
1251
+ try {
1252
+ entries = readdirSync(currentPath).sort((left, right) => left.localeCompare(right));
1253
+ } catch (error) {
1254
+ throw new ConfigurationError(
1255
+ `${upload.name} could not read local directory: ${currentPath} (${errorMessage(error)})`
1256
+ );
1257
+ }
1184
1258
  for (const entry of entries) {
1185
- const fullPath = join(currentPath, entry);
1186
- const stat = statSync(fullPath);
1187
- if (stat.isDirectory()) {
1188
- walkDir(fullPath);
1189
- } else if (stat.isFile()) {
1190
- const relPath = relative(dirPath, fullPath);
1191
- const isBinary = /\.(png|jpg|jpeg|gif|ico|pdf|zip|tar|gz|bin|exe|dll|so|dylib|wasm)$/i.test(entry);
1192
- if (isBinary) {
1193
- const buffer = readFileSync(fullPath);
1194
- const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
1195
- files.push({ relativePath: relPath, content: arrayBuffer });
1196
- } else {
1197
- files.push({ relativePath: relPath, content: readFileSync(fullPath, "utf-8") });
1198
- }
1259
+ const localPath = join(currentPath, entry);
1260
+ const stats = localPathStats(localPath, upload);
1261
+ if (stats.isDirectory()) {
1262
+ walk(localPath);
1263
+ continue;
1264
+ }
1265
+ if (!stats.isFile()) {
1266
+ throw new ConfigurationError(
1267
+ `${upload.name} source tree contains an unsupported filesystem entry: ${localPath}`
1268
+ );
1269
+ }
1270
+ const relativePath = relative(rootPath, localPath).split(sep).join("/");
1271
+ const targetPath = posix.join(destination, relativePath);
1272
+ let content;
1273
+ try {
1274
+ content = readFileSync(localPath);
1275
+ } catch (error) {
1276
+ throw new ConfigurationError(
1277
+ `${upload.name} could not read local file: ${localPath} (${errorMessage(error)})`
1278
+ );
1199
1279
  }
1280
+ files.push({ localPath, targetPath, content });
1200
1281
  }
1201
1282
  }
1202
- walkDir(dirPath);
1203
- return files;
1283
+ walk(rootPath);
1284
+ return { rootPath, files };
1285
+ }
1286
+ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
1287
+ const uploads = localDirectories.map((entry, index) => ({
1288
+ ...entry,
1289
+ name: `localDirectories[${index}]`,
1290
+ rejectSymlinks: true,
1291
+ preserveRootDirectory: false
1292
+ }));
1293
+ if (claudeDir) {
1294
+ uploads.push({
1295
+ source: claudeDir,
1296
+ destination: ".claude",
1297
+ name: "claudeDir",
1298
+ rejectSymlinks: false,
1299
+ preserveRootDirectory: true
1300
+ });
1301
+ }
1302
+ const filesByTarget = /* @__PURE__ */ new Map();
1303
+ const requiredDirectories = /* @__PURE__ */ new Set();
1304
+ for (const upload of uploads) {
1305
+ const prepared = readConfiguredLocalDirectory(upload);
1306
+ const destination = normalizeLocalDirectoryDestination(upload.destination, upload.name);
1307
+ if (upload.preserveRootDirectory) {
1308
+ requiredDirectories.add(destination);
1309
+ }
1310
+ for (const file of prepared.files) {
1311
+ const existing = filesByTarget.get(file.targetPath);
1312
+ if (existing) {
1313
+ throw new ConfigurationError(
1314
+ `Duplicate sandbox target "${file.targetPath}" from local files "${existing.localPath}" and "${file.localPath}".`
1315
+ );
1316
+ }
1317
+ filesByTarget.set(file.targetPath, file);
1318
+ }
1319
+ }
1320
+ for (const file of filesByTarget.values()) {
1321
+ let parent = posix.dirname(file.targetPath);
1322
+ while (parent !== ".") {
1323
+ const parentFile = filesByTarget.get(parent);
1324
+ if (parentFile) {
1325
+ throw new ConfigurationError(
1326
+ `Sandbox target collision: local file "${parentFile.localPath}" maps to "${parent}", which must be a directory for "${file.localPath}".`
1327
+ );
1328
+ }
1329
+ requiredDirectories.add(parent);
1330
+ parent = posix.dirname(parent);
1331
+ }
1332
+ }
1333
+ const directories = [...requiredDirectories].sort((left, right) => {
1334
+ const depthDifference = left.split("/").length - right.split("/").length;
1335
+ return depthDifference || left.localeCompare(right);
1336
+ });
1337
+ const files = [...filesByTarget.values()].sort(
1338
+ (left, right) => left.targetPath.localeCompare(right.targetPath)
1339
+ );
1340
+ return { directories, files };
1204
1341
  }
1205
1342
  var Agent = class {
1206
1343
  sandbox;
@@ -1215,6 +1352,8 @@ var Agent = class {
1215
1352
  maxDuration;
1216
1353
  dependencies;
1217
1354
  files;
1355
+ localDirectories;
1356
+ /** @deprecated Use `localDirectories` with destination `.claude` instead. */
1218
1357
  claudeDir;
1219
1358
  envs;
1220
1359
  build;
@@ -1236,6 +1375,7 @@ var Agent = class {
1236
1375
  this._sourceFile = resolveSourceFile(config.sourceFile);
1237
1376
  this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
1238
1377
  this.files = config.files ?? [];
1378
+ this.localDirectories = (config.localDirectories ?? []).map((entry) => ({ ...entry }));
1239
1379
  this.claudeDir = config.claudeDir;
1240
1380
  this.envs = config.envs ?? {};
1241
1381
  this.build = config.build ?? {};
@@ -1438,6 +1578,10 @@ ${parts.join("\n\n")}`;
1438
1578
  }
1439
1579
  async _deploy(options) {
1440
1580
  if (!options?.fresh && this._serverRuntime) return this._serverRuntime.connection.sandboxId;
1581
+ const localDirectoryUploads = prepareLocalDirectoryUploads(
1582
+ this.localDirectories,
1583
+ this.claudeDir
1584
+ );
1441
1585
  const esbuild = await getEsbuild();
1442
1586
  const externalPatterns = Array.from(
1443
1587
  /* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
@@ -1571,21 +1715,14 @@ var require = __neckbeard_createRequire(import.meta.url);
1571
1715
  }
1572
1716
  }
1573
1717
  }
1574
- if (this.claudeDir) {
1575
- const claudeFiles = readDirectoryRecursively(this.claudeDir);
1576
- await sandbox.runCommand(`mkdir -p ${shellEscape(paths.claudeDir)}`, {
1577
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
1578
- });
1579
- for (const file of claudeFiles) {
1580
- const destPath = `${paths.claudeDir}/${file.relativePath}`;
1581
- const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
1582
- if (parentDir && parentDir !== paths.claudeDir) {
1583
- await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
1584
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
1585
- });
1586
- }
1587
- await sandbox.writeFile(destPath, file.content);
1588
- }
1718
+ for (const directory of localDirectoryUploads.directories) {
1719
+ await sandbox.makeDir(posix.join(paths.agentDir, directory));
1720
+ }
1721
+ for (const file of localDirectoryUploads.files) {
1722
+ await sandbox.writeFile(
1723
+ posix.join(paths.agentDir, file.targetPath),
1724
+ file.content
1725
+ );
1589
1726
  }
1590
1727
  await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
1591
1728
  await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-neckbeard",
3
- "version": "1.1.16",
3
+ "version": "1.1.18",
4
4
  "description": "Deploy AI agents to E2B and Daytona sandboxes",
5
5
  "type": "module",
6
6
  "exports": {
@@ -20,7 +20,8 @@
20
20
  "types": "./dist/index.d.cts",
21
21
  "sideEffects": false,
22
22
  "files": [
23
- "dist"
23
+ "dist",
24
+ "CHANGELOG.md"
24
25
  ],
25
26
  "engines": {
26
27
  "node": ">=20.0.0"