agent-neckbeard 1.1.26 → 1.1.28

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/dist/index.cjs CHANGED
@@ -106,7 +106,12 @@ async function* decodeSseStream(chunks) {
106
106
  }
107
107
  const tail = buffer.trim();
108
108
  if (tail.length > 0) {
109
- const parsed = parseFrame(tail);
109
+ let parsed;
110
+ try {
111
+ parsed = parseFrame(tail);
112
+ } catch (error) {
113
+ throw new IncompleteSseFrameError(`Incomplete SSE data frame: ${error instanceof Error ? error.message : String(error)}`);
114
+ }
110
115
  if (parsed !== void 0) {
111
116
  yield parsed;
112
117
  }
@@ -127,9 +132,12 @@ function parseFrame(raw) {
127
132
  throw new Error(`Malformed SSE data frame: ${message}`);
128
133
  }
129
134
  }
135
+ var IncompleteSseFrameError;
130
136
  var init_sse_framing = __esm({
131
137
  "src/sse-framing.ts"() {
132
138
  "use strict";
139
+ IncompleteSseFrameError = class extends Error {
140
+ };
133
141
  }
134
142
  });
135
143
 
@@ -246,20 +254,31 @@ __export(src_exports, {
246
254
  Agent: () => Agent,
247
255
  ConfigurationError: () => ConfigurationError,
248
256
  DEFAULT_DEPENDENCIES: () => DEFAULT_DEPENDENCIES,
257
+ DefinedAgent: () => DefinedAgent,
249
258
  DeploymentError: () => DeploymentError,
250
259
  ExecutionError: () => ExecutionError,
260
+ LegacyBundledAgent: () => LegacyBundledAgent,
251
261
  NeckbeardError: () => NeckbeardError,
252
262
  RuntimeBusyError: () => RuntimeBusyError,
263
+ SKILLS_DIR: () => SKILLS_DIR,
253
264
  SandboxClient: () => SandboxClient,
265
+ TURN_PROTOCOL_VERSION: () => TURN_PROTOCOL_VERSION,
266
+ TurnLostError: () => TurnLostError,
254
267
  ValidationError: () => ValidationError,
268
+ defineAgent: () => defineAgent,
269
+ destroyProviderSandbox: () => destroyProviderSandbox,
270
+ getPiTurnResult: () => getPiTurnResult,
271
+ isDefinedAgent: () => isDefinedAgent,
255
272
  normalizeStackFramePath: () => normalizeStackFramePath,
256
273
  resolveAgentSourceFile: () => resolveAgentSourceFile,
274
+ resolveImageTag: () => resolveImageTag,
257
275
  withNeckbeardNextConfig: () => withNeckbeardNextConfig
258
276
  });
259
277
  module.exports = __toCommonJS(src_exports);
260
278
  var import_node_url = require("url");
261
279
  var import_node_fs = require("fs");
262
- var import_node_path = require("path");
280
+ var import_node_path2 = require("path");
281
+ var import_node_crypto4 = require("crypto");
263
282
  var import_node_module2 = require("module");
264
283
  init_protocol();
265
284
 
@@ -541,8 +560,91 @@ function shellQuote(value) {
541
560
  return `'${value.replace(/'/g, `'\\''`)}'`;
542
561
  }
543
562
 
544
- // src/providers/detached-process.ts
563
+ // src/tar.ts
545
564
  var import_node_buffer = require("buffer");
565
+ var import_node_util = require("util");
566
+ var import_node_zlib = require("zlib");
567
+ var gzipAsync = (0, import_node_util.promisify)(import_node_zlib.gzip);
568
+ var BLOCK_SIZE = 512;
569
+ var MAX_OCTAL_SIZE = 8589934591;
570
+ function writeString(header2, value, offset, length) {
571
+ header2.write(value, offset, length, "utf8");
572
+ }
573
+ function writeOctal(header2, value, offset, length) {
574
+ header2.write(`${value.toString(8).padStart(length - 1, "0")}\0`, offset, length, "ascii");
575
+ }
576
+ function splitUstarPath(path2) {
577
+ if (import_node_buffer.Buffer.byteLength(path2) <= 100) return { name: path2, prefix: "" };
578
+ for (let index = path2.indexOf("/"); index !== -1; index = path2.indexOf("/", index + 1)) {
579
+ const prefix = path2.slice(0, index);
580
+ const name = path2.slice(index + 1);
581
+ if (import_node_buffer.Buffer.byteLength(prefix) <= 155 && import_node_buffer.Buffer.byteLength(name) <= 100 && name) {
582
+ return { name, prefix };
583
+ }
584
+ }
585
+ return void 0;
586
+ }
587
+ function header(options) {
588
+ if (options.size > MAX_OCTAL_SIZE) {
589
+ throw new Error(`Archive entry ${options.name} is too large.`);
590
+ }
591
+ const block = import_node_buffer.Buffer.alloc(BLOCK_SIZE);
592
+ writeString(block, options.name, 0, 100);
593
+ writeOctal(block, options.mode, 100, 8);
594
+ writeOctal(block, 0, 108, 8);
595
+ writeOctal(block, 0, 116, 8);
596
+ writeOctal(block, options.size, 124, 12);
597
+ writeOctal(block, options.mtime, 136, 12);
598
+ block.fill(" ", 148, 156);
599
+ writeString(block, options.type, 156, 1);
600
+ writeString(block, "ustar\0", 257, 6);
601
+ writeString(block, "00", 263, 2);
602
+ writeString(block, options.prefix ?? "", 345, 155);
603
+ let checksum = 0;
604
+ for (const byte of block) checksum += byte;
605
+ block.write(`${checksum.toString(8).padStart(6, "0")}\0 `, 148, 8, "ascii");
606
+ return block;
607
+ }
608
+ function padding(size) {
609
+ return import_node_buffer.Buffer.alloc((BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE);
610
+ }
611
+ function paxPathRecord(path2) {
612
+ const body = ` path=${path2}
613
+ `;
614
+ let length = import_node_buffer.Buffer.byteLength(body);
615
+ while (String(length).length + import_node_buffer.Buffer.byteLength(body) !== length) {
616
+ length = String(length).length + import_node_buffer.Buffer.byteLength(body);
617
+ }
618
+ return import_node_buffer.Buffer.from(`${length}${body}`);
619
+ }
620
+ async function createTarGz(entries, mtime = Math.floor(Date.now() / 1e3)) {
621
+ const chunks = [];
622
+ for (const entry of entries) {
623
+ const isDirectory = entry.content === void 0;
624
+ const path2 = isDirectory ? `${entry.path.replace(/\/+$/u, "")}/` : entry.path;
625
+ const size = entry.content?.byteLength ?? 0;
626
+ const type = isDirectory ? "5" : "0";
627
+ const mode = isDirectory ? 493 : 420;
628
+ const split = splitUstarPath(path2);
629
+ if (split) {
630
+ chunks.push(header({ ...split, mode, size, mtime, type }));
631
+ } else {
632
+ const record = paxPathRecord(path2);
633
+ chunks.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
634
+ chunks.push(record, padding(record.byteLength));
635
+ chunks.push(header({ name: path2.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
636
+ }
637
+ if (entry.content) {
638
+ chunks.push(import_node_buffer.Buffer.from(entry.content.buffer, entry.content.byteOffset, entry.content.byteLength));
639
+ chunks.push(padding(size));
640
+ }
641
+ }
642
+ chunks.push(import_node_buffer.Buffer.alloc(BLOCK_SIZE * 2));
643
+ return gzipAsync(import_node_buffer.Buffer.concat(chunks));
644
+ }
645
+
646
+ // src/providers/detached-process.ts
647
+ var import_node_buffer2 = require("buffer");
546
648
  var import_node_crypto = require("crypto");
547
649
  var DETACHED_PROCESS_ROOT = "/tmp/agent-neckbeard-detached";
548
650
  var DETACHED_PROCESS_CONTROL_TIMEOUT_MS = 3e4;
@@ -1255,8 +1357,8 @@ function decisionFunctions(paths) {
1255
1357
  "}"
1256
1358
  ];
1257
1359
  }
1258
- function exactLifecycleMarkerFunction(functionName, variablePrefix, path, expectation) {
1259
- const quotedPath = shellQuote(path);
1360
+ function exactLifecycleMarkerFunction(functionName, variablePrefix, path2, expectation) {
1361
+ const quotedPath = shellQuote(path2);
1260
1362
  const missingMarker = expectation.kind === "populated" ? [
1261
1363
  ` if [ ! -e ${quotedPath} ] && [ ! -L ${quotedPath} ]; then return 1; fi`
1262
1364
  ] : [];
@@ -1493,25 +1595,25 @@ function buildLegacyDetachedStopCommand(pid, startTicks, providerName) {
1493
1595
  })
1494
1596
  ].join("\n");
1495
1597
  }
1496
- function atomicFile(partialPath, path, parentDirectory, write) {
1598
+ function atomicFile(partialPath, path2, parentDirectory, write) {
1497
1599
  return [
1498
1600
  `${write} || exit 1`,
1499
1601
  `sync -f ${shellQuote(partialPath)} || exit 1`,
1500
- `mv -f ${shellQuote(partialPath)} ${shellQuote(path)} || exit 1`,
1602
+ `mv -f ${shellQuote(partialPath)} ${shellQuote(path2)} || exit 1`,
1501
1603
  `sync -f ${shellQuote(parentDirectory)} || exit 1`
1502
1604
  ];
1503
1605
  }
1504
- function secureDirectory(path, create) {
1606
+ function secureDirectory(path2, create) {
1505
1607
  return [
1506
1608
  ...create ? [
1507
- `if [ ! -e ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ]; then`,
1508
- ` mkdir ${shellQuote(path)} 2>/dev/null || true`,
1609
+ `if [ ! -e ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ]; then`,
1610
+ ` mkdir ${shellQuote(path2)} 2>/dev/null || true`,
1509
1611
  "fi"
1510
1612
  ] : [],
1511
- `[ -d ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ] || exit 1`,
1512
- `directory_owner=$(stat -c %u ${shellQuote(path)} 2>/dev/null) || exit 1`,
1613
+ `[ -d ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ] || exit 1`,
1614
+ `directory_owner=$(stat -c %u ${shellQuote(path2)} 2>/dev/null) || exit 1`,
1513
1615
  '[ "$directory_owner" = "$(id -u)" ] || exit 1',
1514
- `directory_mode=$(stat -c %a ${shellQuote(path)} 2>/dev/null) || exit 1`,
1616
+ `directory_mode=$(stat -c %a ${shellQuote(path2)} 2>/dev/null) || exit 1`,
1515
1617
  '[ "$directory_mode" = 700 ] || exit 1'
1516
1618
  ];
1517
1619
  }
@@ -1521,10 +1623,10 @@ function secureDetachedRoot() {
1521
1623
  function secureLaunchDirectory(paths, create) {
1522
1624
  return secureDirectory(paths.directory, create);
1523
1625
  }
1524
- function assertSafeRegularFile(path) {
1626
+ function assertSafeRegularFile(path2) {
1525
1627
  return [
1526
- `[ -e ${shellQuote(path)} ] || return 1`,
1527
- `[ -f ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ] || exit 1`
1628
+ `[ -e ${shellQuote(path2)} ] || return 1`,
1629
+ `[ -f ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ] || exit 1`
1528
1630
  ];
1529
1631
  }
1530
1632
  function publishDecision(paths, action, partialPath) {
@@ -1581,8 +1683,8 @@ function releasedAdoptionOutcome(paths, descriptorKey, serializeGenerationChange
1581
1683
  ];
1582
1684
  }
1583
1685
  function renderShellLockAssertion(options) {
1584
- const { functionName, variablePrefix, path, descriptorFd } = options;
1585
- const pathExpression = shellQuote(path);
1686
+ const { functionName, variablePrefix, path: path2, descriptorFd } = options;
1687
+ const pathExpression = shellQuote(path2);
1586
1688
  const descriptorPathExpression = `/proc/self/fd/${descriptorFd}`;
1587
1689
  const descriptorChecks = [
1588
1690
  `[ -f ${descriptorPathExpression} ] || return 1`,
@@ -1732,23 +1834,23 @@ function cleanLifecycleShell(script, environmentMode) {
1732
1834
  delimiter
1733
1835
  ].join("\n");
1734
1836
  }
1735
- function previousLogPath(path) {
1736
- return `${path}.previous`;
1837
+ function previousLogPath(path2) {
1838
+ return `${path2}.previous`;
1737
1839
  }
1738
- function logPipePath(path) {
1739
- return `${path}.pipe`;
1840
+ function logPipePath(path2) {
1841
+ return `${path2}.pipe`;
1740
1842
  }
1741
- function logSnapshotPath(path) {
1742
- return `${path}.snapshot`;
1843
+ function logSnapshotPath(path2) {
1844
+ return `${path2}.snapshot`;
1743
1845
  }
1744
- function logSnapshotStagingPath(path) {
1745
- return `${logSnapshotPath(path)}.partial`;
1846
+ function logSnapshotStagingPath(path2) {
1847
+ return `${logSnapshotPath(path2)}.partial`;
1746
1848
  }
1747
- function legacyLogSnapshotLockPath(path) {
1748
- return `${logSnapshotPath(path)}.lock`;
1849
+ function legacyLogSnapshotLockPath(path2) {
1850
+ return `${logSnapshotPath(path2)}.lock`;
1749
1851
  }
1750
- function logChunkPath(path) {
1751
- return `${path}.chunk`;
1852
+ function logChunkPath(path2) {
1853
+ return `${path2}.chunk`;
1752
1854
  }
1753
1855
  function boundedLogProgram() {
1754
1856
  return [
@@ -2594,9 +2696,9 @@ function buildReadLegacyDetachedLogsCommand(nonce) {
2594
2696
  ].join("\n");
2595
2697
  }
2596
2698
  function readLogFiles(stdout, stderr, previous, beforePrint = []) {
2597
- const optionalPrevious = (path) => [
2598
- `if [ -e ${shellQuote(path)} ] || [ -L ${shellQuote(path)} ]; then`,
2599
- ...assertSafeRegularFile(path).map((line) => line.replace("return 1", "exit 1")).map((line) => ` ${line}`),
2699
+ const optionalPrevious = (path2) => [
2700
+ `if [ -e ${shellQuote(path2)} ] || [ -L ${shellQuote(path2)} ]; then`,
2701
+ ...assertSafeRegularFile(path2).map((line) => line.replace("return 1", "exit 1")).map((line) => ` ${line}`),
2600
2702
  "fi"
2601
2703
  ];
2602
2704
  const boundedPayload = (current, prior) => prior === void 0 ? `read_bounded_log_file ${shellQuote(current)}` : `read_bounded_log_snapshot ${shellQuote(current)} ${shellQuote(prior)} ${shellQuote(logSnapshotPath(current))}`;
@@ -2764,9 +2866,9 @@ function readLogFiles(stdout, stderr, previous, beforePrint = []) {
2764
2866
  function parseDetachedProcessLogs(output) {
2765
2867
  const lineEnd = output.indexOf("\n");
2766
2868
  if (lineEnd < 0) return null;
2767
- const header = output.slice(0, lineEnd);
2869
+ const header2 = output.slice(0, lineEnd);
2768
2870
  const match = new RegExp(`^${LOGS_PREFIX} (0|[1-9][0-9]*) (0|[1-9][0-9]*)$`, "u").exec(
2769
- header
2871
+ header2
2770
2872
  );
2771
2873
  if (!match?.[1] || !match[2]) return null;
2772
2874
  const stdoutBytes = Number(match[1]);
@@ -2787,7 +2889,7 @@ function parseDetachedProcessLogs(output) {
2787
2889
  };
2788
2890
  const stdout = decodeCanonicalBase64(stdoutBase64);
2789
2891
  const stderr = decodeCanonicalBase64(stderrBase64);
2790
- if (!stdout || !stderr || stdout.byteLength !== stdoutBytes || stderr.byteLength !== stderrBytes || !(0, import_node_buffer.isUtf8)(stdout) || !(0, import_node_buffer.isUtf8)(stderr)) {
2892
+ if (!stdout || !stderr || stdout.byteLength !== stdoutBytes || stderr.byteLength !== stderrBytes || !(0, import_node_buffer2.isUtf8)(stdout) || !(0, import_node_buffer2.isUtf8)(stderr)) {
2791
2893
  return null;
2792
2894
  }
2793
2895
  return {
@@ -2800,7 +2902,7 @@ function isStopConfirmation(output) {
2800
2902
  }
2801
2903
 
2802
2904
  // src/providers/daytona-transport.ts
2803
- var import_node_buffer2 = require("buffer");
2905
+ var import_node_buffer3 = require("buffer");
2804
2906
  function daytonaTimeoutSeconds(timeoutMs) {
2805
2907
  return Math.max(1, Math.ceil(timeoutMs / 1e3));
2806
2908
  }
@@ -2838,24 +2940,24 @@ async function executeRawDaytonaCommand(sandbox, command, options) {
2838
2940
  daytonaTimeoutSeconds(options.timeoutMs)
2839
2941
  );
2840
2942
  }
2841
- async function makeDaytonaDirectory(sandbox, path, options) {
2943
+ async function makeDaytonaDirectory(sandbox, path2, options) {
2842
2944
  return executeRawDaytonaCommand(
2843
2945
  sandbox,
2844
- `mkdir -p -- ${shellQuote(path)}`,
2946
+ `mkdir -p -- ${shellQuote(path2)}`,
2845
2947
  options
2846
2948
  );
2847
2949
  }
2848
2950
  function daytonaUploadContent(content) {
2849
- if (import_node_buffer2.Buffer.isBuffer(content)) return content;
2850
- if (typeof content === "string") return import_node_buffer2.Buffer.from(content);
2851
- if (content instanceof Uint8Array) return import_node_buffer2.Buffer.from(content);
2852
- return import_node_buffer2.Buffer.from(content);
2951
+ if (import_node_buffer3.Buffer.isBuffer(content)) return content;
2952
+ if (typeof content === "string") return import_node_buffer3.Buffer.from(content);
2953
+ if (content instanceof Uint8Array) return import_node_buffer3.Buffer.from(content);
2954
+ return import_node_buffer3.Buffer.from(content);
2853
2955
  }
2854
- async function uploadDaytonaFile(sandbox, path, content, options) {
2956
+ async function uploadDaytonaFile(sandbox, path2, content, options) {
2855
2957
  await options.beforeIo?.();
2856
2958
  await sandbox.fs.uploadFile(
2857
2959
  daytonaUploadContent(content),
2858
- path,
2960
+ path2,
2859
2961
  daytonaTimeoutSeconds(options.timeoutMs)
2860
2962
  );
2861
2963
  }
@@ -2988,29 +3090,29 @@ var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
2988
3090
  get id() {
2989
3091
  return this.sandbox.id;
2990
3092
  }
2991
- async makeDir(path) {
2992
- const result = await makeDaytonaDirectory(this.sandbox, path, {
3093
+ async makeDir(path2) {
3094
+ const result = await makeDaytonaDirectory(this.sandbox, path2, {
2993
3095
  timeoutMs: QUICK_COMMAND_TIMEOUT_MS
2994
3096
  });
2995
3097
  if (result.exitCode !== 0) {
2996
- throw this.failure(result.result || `Failed to create directory ${path}`);
3098
+ throw this.failure(result.result || `Failed to create directory ${path2}`);
2997
3099
  }
2998
3100
  }
2999
- writeFile(path, content) {
3000
- return uploadDaytonaFile(this.sandbox, path, content, {
3101
+ writeFile(path2, content) {
3102
+ return uploadDaytonaFile(this.sandbox, path2, content, {
3001
3103
  timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
3002
3104
  });
3003
3105
  }
3004
- async readFile(path) {
3106
+ async readFile(path2) {
3005
3107
  const content = await this.sandbox.fs.downloadFile(
3006
- path,
3108
+ path2,
3007
3109
  daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
3008
3110
  );
3009
3111
  return content.toString("utf8");
3010
3112
  }
3011
- async readFileBytes(path) {
3113
+ async readFileBytes(path2) {
3012
3114
  const content = await this.sandbox.fs.downloadFile(
3013
- path,
3115
+ path2,
3014
3116
  daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
3015
3117
  );
3016
3118
  return new Uint8Array(content);
@@ -3251,17 +3353,17 @@ var E2bSandboxHandle = class {
3251
3353
  get id() {
3252
3354
  return this.sandbox.sandboxId;
3253
3355
  }
3254
- async makeDir(path) {
3255
- await this.sandbox.files.makeDir(path);
3356
+ async makeDir(path2) {
3357
+ await this.sandbox.files.makeDir(path2);
3256
3358
  }
3257
- writeFile(path, content) {
3258
- return this.sandbox.files.write(path, writeContent(content)).then(() => void 0);
3359
+ writeFile(path2, content) {
3360
+ return this.sandbox.files.write(path2, writeContent(content)).then(() => void 0);
3259
3361
  }
3260
- readFile(path) {
3261
- return this.sandbox.files.read(path, { format: "text" });
3362
+ readFile(path2) {
3363
+ return this.sandbox.files.read(path2, { format: "text" });
3262
3364
  }
3263
- readFileBytes(path) {
3264
- return this.sandbox.files.read(path, { format: "bytes" });
3365
+ readFileBytes(path2) {
3366
+ return this.sandbox.files.read(path2, { format: "bytes" });
3265
3367
  }
3266
3368
  runCommand(cmd, options) {
3267
3369
  return runE2bCommand(this.sandbox, cmd, options);
@@ -3363,15 +3465,45 @@ function getModalSdk() {
3363
3465
  // src/providers/modal.ts
3364
3466
  var MODAL_DEFAULT_TEMPLATE = "node:22-bookworm";
3365
3467
  var MODAL_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
3468
+ function parseModalAllowList(value) {
3469
+ return (value ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
3470
+ }
3471
+ function modalNetworkOptions(options) {
3472
+ if (options.networkBlockAll) return { blockNetwork: true };
3473
+ const cidrs = parseModalAllowList(options.networkAllowList);
3474
+ const domains = parseModalAllowList(options.domainAllowList);
3475
+ return {
3476
+ ...cidrs.length > 0 ? { outboundCidrAllowlist: cidrs } : {},
3477
+ ...domains.length > 0 ? { outboundDomainAllowlist: domains } : {}
3478
+ };
3479
+ }
3366
3480
  function validateModalOptions(options, mode, failure) {
3367
- validateProviderOptions("Modal", options, ["environment", ...mode === "connect" ? ["sandboxId", "tokenId", "tokenSecret"] : [
3481
+ const { networkBlockAll, networkAllowList, domainAllowList, regions, command, ...rest } = options;
3482
+ validateProviderOptions("Modal", mode === "connect" ? options : rest, ["environment", ...mode === "connect" ? ["sandboxId", "tokenId", "tokenSecret"] : [
3368
3483
  "template",
3369
3484
  "appName",
3370
3485
  "timeoutMs",
3371
3486
  "cpu",
3372
3487
  "memoryMiB",
3373
- ...mode === "create" ? ["tokenId", "tokenSecret", "envs"] : []
3488
+ ...mode === "create" ? ["tokenId", "tokenSecret", "envs", "registrySecret"] : []
3374
3489
  ]], failure);
3490
+ if (command !== void 0 && (mode !== "create" || !Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string" || part.includes("\0")))) {
3491
+ throw failure(mode === "create" ? "Modal command must be a non-empty array of strings without null bytes." : 'Modal does not support option "command".');
3492
+ }
3493
+ if (regions !== void 0 && (!Array.isArray(regions) || regions.length === 0 || regions.some((region) => typeof region !== "string" || !/^[a-z0-9-]+$/u.test(region)))) {
3494
+ throw failure('Modal regions must be a non-empty array of region names such as "us" or "us-east".');
3495
+ }
3496
+ if (networkBlockAll !== void 0 && typeof networkBlockAll !== "boolean") {
3497
+ throw failure("Modal networkBlockAll must be a boolean.");
3498
+ }
3499
+ for (const [key, value] of [["networkAllowList", networkAllowList], ["domainAllowList", domainAllowList]]) {
3500
+ if (value !== void 0 && (typeof value !== "string" || parseModalAllowList(value).some((entry) => /[\s\0]/u.test(entry)))) {
3501
+ throw failure(`Modal ${key} must be a comma-separated string without whitespace or null bytes in entries.`);
3502
+ }
3503
+ }
3504
+ if (networkBlockAll && (parseModalAllowList(networkAllowList).length > 0 || parseModalAllowList(domainAllowList).length > 0)) {
3505
+ throw failure("Modal networkBlockAll cannot be combined with non-empty allow lists.");
3506
+ }
3375
3507
  if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
3376
3508
  throw failure("Modal sandboxId is required.");
3377
3509
  }
@@ -3450,16 +3582,25 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3450
3582
  let sandbox;
3451
3583
  try {
3452
3584
  const app = await client.apps.fromName(options.appName ?? "agent-neckbeard", { createIfMissing: true });
3453
- const image = client.images.fromRegistry(options.template ?? MODAL_DEFAULT_TEMPLATE).dockerfileCommands([
3585
+ const network = modalNetworkOptions(options);
3586
+ const template = options.template ?? MODAL_DEFAULT_TEMPLATE;
3587
+ const registryImage = options.registrySecret === void 0 ? client.images.fromRegistry(template) : client.images.fromRegistry(template, await client.secrets.fromName(options.registrySecret));
3588
+ const image = options.command ? registryImage : registryImage.dockerfileCommands([
3454
3589
  "USER root",
3455
3590
  "RUN apt-get update && apt-get install -y --no-install-recommends bash python3 util-linux coreutils sudo curl ca-certificates && rm -rf /var/lib/apt/lists/*",
3591
+ // The runtime starts with a fixed PATH, so images with Node elsewhere (say nvm) need links.
3592
+ 'RUN for bin in node npm npx; do target="$(command -v "$bin" || true)"; if [ -n "$target" ] && [ ! -e "/usr/local/bin/$bin" ]; then ln -s "$target" "/usr/local/bin/$bin"; fi; done',
3593
+ // The domain allow list only passes TLS, so apt installs in the sandbox need HTTPS sources.
3594
+ ...network.outboundDomainAllowlist ? ["RUN find /etc/apt -name '*.list' -o -name '*.sources' | xargs -r sed -i 's|http://|https://|g'"] : [],
3456
3595
  "WORKDIR /root"
3457
3596
  ]);
3458
3597
  sandbox = await client.sandboxes.create(app, image, {
3598
+ ...network,
3599
+ ...options.regions ? { regions: options.regions } : {},
3459
3600
  timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
3460
3601
  cpu: options.cpu,
3461
3602
  memoryMiB: options.memoryMiB,
3462
- workdir: "/root",
3603
+ ...options.command ? { command: options.command } : { workdir: "/root" },
3463
3604
  env: Object.fromEntries(Object.entries(options.envs ?? {}).filter(
3464
3605
  (entry) => entry[1] !== void 0
3465
3606
  ))
@@ -3470,6 +3611,15 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3470
3611
  sandbox?.detach();
3471
3612
  }
3472
3613
  }
3614
+ /** Terminates a sandbox by ID; one that is gone counts as terminated. */
3615
+ static async destroyById(options, failure) {
3616
+ const client = await sharedClient({
3617
+ tokenId: options.tokenId,
3618
+ tokenSecret: options.tokenSecret,
3619
+ environment: options.environment
3620
+ });
3621
+ await new _ModalSandboxHandle(options.sandboxId, client, failure).destroy();
3622
+ }
3473
3623
  static async connect(options, failure) {
3474
3624
  const client = await sharedClient({
3475
3625
  tokenId: options.tokenId,
@@ -3506,17 +3656,17 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3506
3656
  sandbox?.detach();
3507
3657
  }
3508
3658
  }
3509
- makeDir(path) {
3510
- return this.use((sandbox) => sandbox.filesystem.makeDirectory(path));
3659
+ makeDir(path2) {
3660
+ return this.use((sandbox) => sandbox.filesystem.makeDirectory(path2));
3511
3661
  }
3512
- writeFile(path, content) {
3513
- return this.use((sandbox) => typeof content === "string" ? sandbox.filesystem.writeText(content, path) : sandbox.filesystem.writeBytes(content, path));
3662
+ writeFile(path2, content) {
3663
+ return this.use((sandbox) => typeof content === "string" ? sandbox.filesystem.writeText(content, path2) : sandbox.filesystem.writeBytes(content, path2));
3514
3664
  }
3515
- readFile(path) {
3516
- return this.use((sandbox) => sandbox.filesystem.readText(path));
3665
+ readFile(path2) {
3666
+ return this.use((sandbox) => sandbox.filesystem.readText(path2));
3517
3667
  }
3518
- readFileBytes(path) {
3519
- return this.use((sandbox) => sandbox.filesystem.readBytes(path));
3668
+ readFileBytes(path2) {
3669
+ return this.use((sandbox) => sandbox.filesystem.readBytes(path2));
3520
3670
  }
3521
3671
  runCommand(command, options) {
3522
3672
  try {
@@ -3589,6 +3739,1220 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3589
3739
  }
3590
3740
  };
3591
3741
 
3742
+ // src/define.ts
3743
+ var import_promises = require("fs/promises");
3744
+ var import_node_os = __toESM(require("os"), 1);
3745
+ var import_node_path = __toESM(require("path"), 1);
3746
+
3747
+ // src/agent.ts
3748
+ var import_node_crypto3 = require("crypto");
3749
+ init_sse_framing();
3750
+
3751
+ // src/turn-protocol.ts
3752
+ var TURN_PROTOCOL_VERSION = 2;
3753
+ var MAX_TURN_REQUEST_BYTES = 4 * 1024 * 1024;
3754
+ var MAX_TURN_ID_LENGTH = 200;
3755
+ function isRecord2(value) {
3756
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3757
+ }
3758
+ function parseTurnRecord(record) {
3759
+ if (!isRecord2(record)) throw new Error("Turn record must be an object.");
3760
+ const { seq } = record;
3761
+ if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0) {
3762
+ throw new Error("Turn record seq must be a non-negative integer.");
3763
+ }
3764
+ if (record.type === "event" && "event" in record) {
3765
+ return { seq, type: "event", event: record.event };
3766
+ }
3767
+ if (record.type === "end" && (record.outcome === "completed" || record.outcome === "aborted" || record.outcome === "failed") && (record.error === void 0 || typeof record.error === "string")) {
3768
+ return {
3769
+ seq,
3770
+ type: "end",
3771
+ outcome: record.outcome,
3772
+ ...record.error === void 0 ? {} : { error: record.error }
3773
+ };
3774
+ }
3775
+ throw new Error("Turn record has an unknown shape.");
3776
+ }
3777
+ function parseTurnHealth(value) {
3778
+ if (!isRecord2(value)) throw new Error("Health response must be an object.");
3779
+ const { ok, protocolVersion, busy, turnId } = value;
3780
+ if (ok !== true || typeof protocolVersion !== "number" || typeof busy !== "boolean" || turnId !== null && typeof turnId !== "string") {
3781
+ throw new Error("Health response is not { ok: true, protocolVersion, busy, turnId }.");
3782
+ }
3783
+ return { ok, protocolVersion, busy, turnId };
3784
+ }
3785
+ function readAssistantMessageEnd(event) {
3786
+ if (!isRecord2(event) || event.type !== "message_end" || !isRecord2(event.message)) return void 0;
3787
+ const { role, content, stopReason, errorMessage: errorMessage2 } = event.message;
3788
+ if (role !== "assistant") return void 0;
3789
+ const text = (Array.isArray(content) ? content : []).flatMap((block) => isRecord2(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n").trim();
3790
+ return {
3791
+ text,
3792
+ stopReason: typeof stopReason === "string" ? stopReason : void 0,
3793
+ errorMessage: typeof errorMessage2 === "string" ? errorMessage2 : void 0
3794
+ };
3795
+ }
3796
+ function getPiTurnResult(records) {
3797
+ let end;
3798
+ let message;
3799
+ for (const record of records) {
3800
+ if (record.type === "end") {
3801
+ end = record;
3802
+ continue;
3803
+ }
3804
+ message = readAssistantMessageEnd(record.event) ?? message;
3805
+ }
3806
+ if (!end) return { completed: false, error: "The agent turn has not ended." };
3807
+ if (end.outcome !== "completed") {
3808
+ return { completed: false, error: end.error ?? `The agent turn was ${end.outcome}.` };
3809
+ }
3810
+ if (!message) return { completed: false, error: "The agent did not reply." };
3811
+ if (message.stopReason !== "stop") {
3812
+ return {
3813
+ completed: false,
3814
+ error: message.errorMessage?.trim() || `The agent stopped with ${message.stopReason ?? "no reason"}.`
3815
+ };
3816
+ }
3817
+ return { completed: true, text: message.text || null };
3818
+ }
3819
+
3820
+ // src/agent.ts
3821
+ var DEFAULT_COMMAND = ["node", "/app/agent.mjs"];
3822
+ var DEFAULT_PORT = 8080;
3823
+ var DEFAULT_START_TIMEOUT_MS = 12e4;
3824
+ var DEFAULT_PREPARE_TIMEOUT_MS = 30 * 6e4;
3825
+ var DEFAULT_RECONNECT_TIMEOUT_MS = 12e4;
3826
+ var HEALTH_POLL_INTERVAL_MS = 500;
3827
+ var RECONNECT_MIN_DELAY_MS = 250;
3828
+ var RECONNECT_MAX_DELAY_MS = 5e3;
3829
+ var REQUEST_TIMEOUT_MS = 3e4;
3830
+ var ARTIFACT_PREFIX = "nb-";
3831
+ function filterDefined(envs) {
3832
+ return Object.fromEntries(Object.entries(envs ?? {}).filter(
3833
+ (entry) => entry[1] !== void 0
3834
+ ));
3835
+ }
3836
+ function delay2(ms, signal) {
3837
+ return new Promise((resolve2, reject) => {
3838
+ if (signal?.aborted) return reject(abortError(signal));
3839
+ const onAbort = () => {
3840
+ clearTimeout(timer);
3841
+ reject(abortError(signal));
3842
+ };
3843
+ const timer = setTimeout(() => {
3844
+ signal?.removeEventListener("abort", onAbort);
3845
+ resolve2();
3846
+ }, ms);
3847
+ signal?.addEventListener("abort", onAbort, { once: true });
3848
+ });
3849
+ }
3850
+ function untilDeadline(deadline, signal) {
3851
+ const timeout = AbortSignal.timeout(Math.max(0, deadline - Date.now()));
3852
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
3853
+ }
3854
+ function untilAborted(operation, signal) {
3855
+ if (signal?.aborted) return Promise.reject(abortError(signal));
3856
+ return settleOperation(operation, signal ? { abort: { signal, createError: () => abortError(signal) } } : {});
3857
+ }
3858
+ function abortError(signal) {
3859
+ if (signal.reason instanceof Error) return signal.reason;
3860
+ const error = new Error("Operation aborted.");
3861
+ error.name = "AbortError";
3862
+ return error;
3863
+ }
3864
+ async function* textChunks(body, onChunk) {
3865
+ const decoder = new TextDecoder();
3866
+ const reader = body.getReader();
3867
+ try {
3868
+ while (true) {
3869
+ const { done, value } = await reader.read();
3870
+ if (done) break;
3871
+ onChunk();
3872
+ yield decoder.decode(value, { stream: true });
3873
+ }
3874
+ } finally {
3875
+ await reader.cancel().catch(() => void 0);
3876
+ reader.releaseLock();
3877
+ }
3878
+ }
3879
+ var EndpointRejectedError = class extends Error {
3880
+ };
3881
+ var Agent = class {
3882
+ constructor(options) {
3883
+ this.options = options;
3884
+ if (!options || typeof options !== "object") throw new ConfigurationError("Agent options must be an object.");
3885
+ if (typeof options.name !== "string" || !/^[a-z0-9]+(-[a-z0-9]+)*$/u.test(options.name)) {
3886
+ throw new ConfigurationError("Agent name must be lowercase letters, digits, and single dashes.");
3887
+ }
3888
+ if (typeof options.image !== "string" || !options.image.trim() || /\s/u.test(options.image)) {
3889
+ throw new ConfigurationError("Agent image must be a registry image reference.");
3890
+ }
3891
+ const provider = options.sandbox?.provider;
3892
+ if (provider !== "modal" && provider !== "daytona" && provider !== "e2b") {
3893
+ throw new ConfigurationError('Agent sandbox.provider must be "modal", "daytona", or "e2b".');
3894
+ }
3895
+ const command = options.command ?? DEFAULT_COMMAND;
3896
+ if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string" || !part)) {
3897
+ throw new ConfigurationError("Agent command must be a non-empty array of non-empty strings.");
3898
+ }
3899
+ const port = options.port ?? DEFAULT_PORT;
3900
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
3901
+ throw new ConfigurationError("Agent port must be between 1 and 65535.");
3902
+ }
3903
+ this.name = options.name;
3904
+ this.image = options.image;
3905
+ this.command = [...command];
3906
+ this.port = port;
3907
+ }
3908
+ name;
3909
+ image;
3910
+ command;
3911
+ port;
3912
+ endpoints = /* @__PURE__ */ new Map();
3913
+ preparing;
3914
+ get provider() {
3915
+ return this.options.sandbox.provider;
3916
+ }
3917
+ /**
3918
+ * Name of the Daytona snapshot or E2B template for this image, command, and resources. Equal
3919
+ * inputs share one, so preparing again is a lookup.
3920
+ */
3921
+ get artifactName() {
3922
+ const { sandbox } = this.options;
3923
+ const resources = sandbox.provider === "daytona" ? sandbox.resources : sandbox.provider === "e2b" ? { cpuCount: sandbox.cpuCount, memoryMB: sandbox.memoryMB } : void 0;
3924
+ const hash2 = (0, import_node_crypto3.createHash)("sha256").update(JSON.stringify([this.image, sandbox.provider === "daytona" ? this.command : [], resources ?? null])).digest("hex").slice(0, 16);
3925
+ return `${ARTIFACT_PREFIX}${this.name}-${hash2}`;
3926
+ }
3927
+ /**
3928
+ * Creates the Daytona snapshot or E2B template for the image if it is missing and waits until
3929
+ * it can start sandboxes. Run it from CI after pushing the image so no sandbox waits on a
3930
+ * build. Modal pulls the image directly, so this does nothing there. `refresh` builds it again
3931
+ * even when it exists, as after pushing new contents under a tag it was built from, since its
3932
+ * name comes from the image's reference, not its contents.
3933
+ */
3934
+ prepare(options = {}) {
3935
+ const { sandbox } = this.options;
3936
+ if (sandbox.provider === "modal") return Promise.resolve();
3937
+ if (options.signal?.aborted) return Promise.reject(abortError(options.signal));
3938
+ if (!this.preparing || options.refresh) {
3939
+ const timeoutMs = this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS;
3940
+ const deadline = AbortSignal.timeout(timeoutMs);
3941
+ const steps = { signal: deadline, refresh: options.refresh ?? false, ...options.onLog ? { onLog: options.onLog } : {} };
3942
+ this.preparing = untilAborted(
3943
+ () => sandbox.provider === "daytona" ? this.prepareDaytonaSnapshot(sandbox, steps) : this.prepareE2bTemplate(sandbox, steps),
3944
+ deadline
3945
+ ).catch((error) => {
3946
+ this.preparing = void 0;
3947
+ if (deadline.aborted) throw new DeploymentError(`Preparing ${this.artifactName} took longer than ${timeoutMs}ms.`);
3948
+ throw error;
3949
+ });
3950
+ this.preparing.catch(() => void 0);
3951
+ }
3952
+ const preparing = this.preparing;
3953
+ return untilAborted(() => preparing, options.signal);
3954
+ }
3955
+ /** Starts a sandbox from the image and waits for its runtime. Returns the sandbox ID. */
3956
+ async start(options = {}) {
3957
+ await this.prepare({ ...options.signal ? { signal: options.signal } : {} });
3958
+ const envs = {
3959
+ ...filterDefined(this.options.envs),
3960
+ ...filterDefined(options.envs),
3961
+ ...options.sessionId === void 0 ? {} : { NECKBEARD_SESSION_ID: options.sessionId },
3962
+ NECKBEARD_PORT: String(this.port)
3963
+ };
3964
+ if (options.signal?.aborted) throw abortError(options.signal);
3965
+ let sandbox;
3966
+ try {
3967
+ sandbox = await this.createSandbox(envs);
3968
+ } catch (error) {
3969
+ this.preparing = void 0;
3970
+ throw error;
3971
+ }
3972
+ try {
3973
+ if (this.options.sandbox.provider === "e2b") await this.startE2bRuntime(this.options.sandbox, sandbox.id, envs);
3974
+ await this.waitForRuntime(sandbox.id, options.signal);
3975
+ return sandbox.id;
3976
+ } catch (error) {
3977
+ this.endpoints.delete(sandbox.id);
3978
+ try {
3979
+ await sandbox.destroy();
3980
+ } catch (cleanupError) {
3981
+ const startMessage = error instanceof Error ? error.message : String(error);
3982
+ const cleanupMessage = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
3983
+ throw new DeploymentError(
3984
+ `Sandbox ${sandbox.id} failed to start (${startMessage}), and deleting it failed (${cleanupMessage}); kill() it to retry.`,
3985
+ error instanceof Error ? error : void 0,
3986
+ sandbox.id
3987
+ );
3988
+ }
3989
+ throw error;
3990
+ }
3991
+ }
3992
+ /**
3993
+ * Starts a turn and streams its records until its `end` record. Starting a turn whose
3994
+ * `turnId` the runtime already has resumes it instead of running it again.
3995
+ */
3996
+ async *prompt(sandboxId, turn, options = {}) {
3997
+ const response = await this.request(sandboxId, "POST", "/turns", turn, options.signal);
3998
+ if (response.status === 409) {
3999
+ const body = await response.json().catch(() => ({}));
4000
+ throw new RuntimeBusyError(`Sandbox ${sandboxId} is running another turn (${body.turnId ?? "unknown"}).`);
4001
+ }
4002
+ if (response.status !== 200 && response.status !== 202) {
4003
+ throw new ExecutionError(`Starting turn ${turn.turnId} failed with ${response.status}: ${await response.text()}`);
4004
+ }
4005
+ await response.body?.cancel();
4006
+ yield* this.events(sandboxId, turn.turnId, options);
4007
+ }
4008
+ /**
4009
+ * Runs a Pi turn to its end and returns its final assistant text, or null when it had none.
4010
+ * Throws `ExecutionError` when the turn did not complete or its model did not stop on its own.
4011
+ * Running a turn again with the same `turnId` replays its records from the start.
4012
+ */
4013
+ async run(sandboxId, turn, options = {}) {
4014
+ const { onRecord, ...streamOptions } = options;
4015
+ const records = [];
4016
+ for await (const record of this.prompt(sandboxId, turn, streamOptions)) {
4017
+ records.push(record);
4018
+ await onRecord?.(record);
4019
+ }
4020
+ options.signal?.throwIfAborted();
4021
+ const result = getPiTurnResult(records);
4022
+ if (!result.completed) throw new ExecutionError(`Turn ${turn.turnId} did not finish: ${result.error}`);
4023
+ return result.text;
4024
+ }
4025
+ /**
4026
+ * Streams a turn's records after `options.after` until its `end` record, reconnecting when
4027
+ * the connection drops. Throws `TurnLostError` when the runtime no longer has the turn.
4028
+ */
4029
+ async *events(sandboxId, turnId, options = {}) {
4030
+ let last = options.after ?? -1;
4031
+ const reconnectTimeoutMs = options.reconnectTimeoutMs ?? DEFAULT_RECONNECT_TIMEOUT_MS;
4032
+ let failingSince;
4033
+ let attempt = 0;
4034
+ while (true) {
4035
+ let lastError;
4036
+ const stalled = new AbortController();
4037
+ let watchdog;
4038
+ const armWatchdog = () => {
4039
+ clearTimeout(watchdog);
4040
+ const budget = failingSince === void 0 ? reconnectTimeoutMs : Math.max(0, failingSince + reconnectTimeoutMs - Date.now());
4041
+ watchdog = setTimeout(() => stalled.abort(new Error(`Turn stream sent nothing for ${budget}ms.`)), budget);
4042
+ };
4043
+ armWatchdog();
4044
+ try {
4045
+ const response = await this.request(
4046
+ sandboxId,
4047
+ "GET",
4048
+ `/turns/${encodeURIComponent(turnId)}/events?after=${last}`,
4049
+ void 0,
4050
+ options.signal ? AbortSignal.any([options.signal, stalled.signal]) : stalled.signal,
4051
+ { stream: true }
4052
+ );
4053
+ if (response.status === 404) {
4054
+ await response.body?.cancel();
4055
+ throw new TurnLostError(`Sandbox ${sandboxId} has no turn ${turnId}.`);
4056
+ }
4057
+ if (!response.ok || !response.body) {
4058
+ await response.body?.cancel();
4059
+ throw new Error(`Turn stream returned ${response.status}.`);
4060
+ }
4061
+ try {
4062
+ const onChunk = () => {
4063
+ failingSince = void 0;
4064
+ armWatchdog();
4065
+ };
4066
+ for await (const frame of decodeSseStream(textChunks(response.body, onChunk))) {
4067
+ let record;
4068
+ try {
4069
+ record = parseTurnRecord(frame);
4070
+ } catch (error) {
4071
+ const message = error instanceof Error ? error.message : String(error);
4072
+ throw new ExecutionError(`Sandbox ${sandboxId} sent an invalid record for turn ${turnId}: ${message}`);
4073
+ }
4074
+ if (record.seq <= last) {
4075
+ if (record.type === "end") return;
4076
+ continue;
4077
+ }
4078
+ last = record.seq;
4079
+ failingSince = void 0;
4080
+ attempt = 0;
4081
+ clearTimeout(watchdog);
4082
+ yield record;
4083
+ armWatchdog();
4084
+ if (record.type === "end") return;
4085
+ }
4086
+ } catch (error) {
4087
+ if (error instanceof Error && error.message.startsWith("Malformed SSE data frame")) {
4088
+ throw new ExecutionError(`Sandbox ${sandboxId} sent a malformed frame for turn ${turnId}: ${error.message}`);
4089
+ }
4090
+ if (!(error instanceof IncompleteSseFrameError)) throw error;
4091
+ }
4092
+ lastError = new Error("Turn stream ended before the turn did.");
4093
+ } catch (error) {
4094
+ if (error instanceof TurnLostError || error instanceof ExecutionError) throw error;
4095
+ if (options.signal?.aborted) throw abortError(options.signal);
4096
+ if (error instanceof EndpointRejectedError) this.endpoints.delete(sandboxId);
4097
+ lastError = stalled.signal.aborted ? stalled.signal.reason : error;
4098
+ } finally {
4099
+ clearTimeout(watchdog);
4100
+ }
4101
+ failingSince ??= Date.now();
4102
+ if (Date.now() - failingSince > reconnectTimeoutMs) {
4103
+ const message = lastError instanceof Error ? lastError.message : String(lastError);
4104
+ throw new ExecutionError(`Lost the stream of turn ${turnId} for over ${reconnectTimeoutMs}ms: ${message}`);
4105
+ }
4106
+ attempt += 1;
4107
+ await delay2(Math.min(RECONNECT_MAX_DELAY_MS, RECONNECT_MIN_DELAY_MS * 2 ** (attempt - 1)), options.signal);
4108
+ }
4109
+ }
4110
+ /** Asks the runtime to stop the turn; its stream then ends with an `aborted` record. */
4111
+ async abort(sandboxId, turnId, signal) {
4112
+ const response = await this.request(sandboxId, "POST", `/turns/${encodeURIComponent(turnId)}/abort`, void 0, signal);
4113
+ await response.body?.cancel();
4114
+ if (response.status !== 202 && response.status !== 404) {
4115
+ throw new ExecutionError(`Aborting turn ${turnId} failed with ${response.status}.`);
4116
+ }
4117
+ }
4118
+ async health(sandboxId, signal) {
4119
+ const response = await this.request(sandboxId, "GET", "/health", void 0, signal);
4120
+ if (!response.ok) throw new ExecutionError(`Health check of sandbox ${sandboxId} returned ${response.status}.`);
4121
+ return parseTurnHealth(await response.json());
4122
+ }
4123
+ /** Waits until no turn runs, for example before reading files a turn writes. */
4124
+ async waitForIdle(sandboxId, options = {}) {
4125
+ const deadline = Date.now() + (options.timeoutMs ?? 6e4);
4126
+ while (true) {
4127
+ try {
4128
+ if (!(await this.health(sandboxId, untilDeadline(deadline, options.signal))).busy) return;
4129
+ } catch (error) {
4130
+ if (options.signal?.aborted) throw error;
4131
+ }
4132
+ if (Date.now() > deadline) throw new RuntimeBusyError(`Sandbox ${sandboxId} did not become idle.`);
4133
+ await delay2(HEALTH_POLL_INTERVAL_MS, options.signal);
4134
+ }
4135
+ }
4136
+ /**
4137
+ * Deletes the sandbox without starting it. One that is already gone counts as deleted; any other
4138
+ * failure throws, so cleanup can be retried, since a Daytona sandbox need not expire on its own.
4139
+ */
4140
+ async kill(sandboxId) {
4141
+ this.endpoints.delete(sandboxId);
4142
+ const { sandbox } = this.options;
4143
+ if (sandbox.provider === "modal") {
4144
+ await destroyProviderSandbox({
4145
+ provider: "modal",
4146
+ sandboxId,
4147
+ ...sandbox.environment ? { environment: sandbox.environment } : {}
4148
+ });
4149
+ return;
4150
+ }
4151
+ await destroyProviderSandbox({ provider: sandbox.provider, sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
4152
+ }
4153
+ /** File and command access to a sandbox, for staging inputs and reading results. */
4154
+ sandbox(sandboxId) {
4155
+ const { sandbox } = this.options;
4156
+ if (sandbox.provider === "modal") {
4157
+ return SandboxClient.connect({
4158
+ provider: "modal",
4159
+ sandboxId,
4160
+ ...sandbox.environment ? { environment: sandbox.environment } : {}
4161
+ });
4162
+ }
4163
+ if (sandbox.provider === "e2b") {
4164
+ return SandboxClient.connect({
4165
+ provider: "e2b",
4166
+ sandboxId,
4167
+ ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {},
4168
+ ...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
4169
+ });
4170
+ }
4171
+ return SandboxClient.connect({ provider: "daytona", sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
4172
+ }
4173
+ /**
4174
+ * Deletes this agent's Daytona snapshots or E2B templates except the newest `keep` and the
4175
+ * current one. Returns the names it deleted.
4176
+ */
4177
+ async gc(options = {}) {
4178
+ const keep = options.keep ?? 3;
4179
+ if (!Number.isInteger(keep) || keep < 0) throw new ConfigurationError("gc keep must be a non-negative integer.");
4180
+ const { sandbox } = this.options;
4181
+ if (sandbox.provider === "modal") return [];
4182
+ const ownName = new RegExp(`^${ARTIFACT_PREFIX}${this.name}-[0-9a-f]{16}$`, "u");
4183
+ const protectedNames = /* @__PURE__ */ new Set([this.artifactName, ...options.alsoKeep ?? []]);
4184
+ const artifacts = sandbox.provider === "daytona" ? await this.listDaytonaSnapshots(sandbox, ownName) : await this.listE2bTemplates(sandbox, ownName);
4185
+ const stale = artifacts.sort((left, right) => right.createdAt - left.createdAt).filter((artifact) => !protectedNames.has(artifact.name)).slice(Math.max(0, keep - artifacts.filter((artifact) => protectedNames.has(artifact.name)).length));
4186
+ for (const artifact of stale) await artifact.delete();
4187
+ return stale.map((artifact) => artifact.name);
4188
+ }
4189
+ createSandbox(envs) {
4190
+ const { sandbox } = this.options;
4191
+ if (sandbox.provider === "modal") {
4192
+ const { provider: _provider, ...modal } = sandbox;
4193
+ return SandboxClient.create({ provider: "modal", ...modal, template: this.image, command: this.command, envs });
4194
+ }
4195
+ if (sandbox.provider === "daytona") {
4196
+ const { resources: _resources, ...daytona } = sandbox;
4197
+ return SandboxClient.create({ ...daytona, template: this.artifactName, envs });
4198
+ }
4199
+ const { cpuCount: _cpuCount, memoryMB: _memoryMB, registry: _registry, ...e2b } = sandbox;
4200
+ return SandboxClient.create({ ...e2b, template: this.artifactName, envs, allowPublicTraffic: false });
4201
+ }
4202
+ // An E2B template's start command runs once at build time, without each sandbox's environment.
4203
+ async startE2bRuntime(sandbox, sandboxId, envs) {
4204
+ const { Sandbox } = await import("e2b");
4205
+ const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
4206
+ const e2bSandbox = await Sandbox.connect(sandboxId, {
4207
+ ...apiKey ? { apiKey } : {},
4208
+ ...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
4209
+ });
4210
+ const command = await e2bSandbox.commands.run(this.command.map(shellQuote).join(" "), { background: true, envs, timeoutMs: 0 });
4211
+ await command.disconnect();
4212
+ }
4213
+ async waitForRuntime(sandboxId, signal) {
4214
+ const timeoutMs = this.options.startTimeoutMs ?? DEFAULT_START_TIMEOUT_MS;
4215
+ const deadline = Date.now() + timeoutMs;
4216
+ let lastError;
4217
+ while (Date.now() < deadline) {
4218
+ try {
4219
+ const health = await this.health(sandboxId, untilDeadline(deadline, signal));
4220
+ if (health.protocolVersion !== TURN_PROTOCOL_VERSION) {
4221
+ throw new DeploymentError(
4222
+ `Sandbox runtime speaks protocol ${health.protocolVersion}; this host speaks ${TURN_PROTOCOL_VERSION}.`
4223
+ );
4224
+ }
4225
+ return;
4226
+ } catch (error) {
4227
+ if (error instanceof DeploymentError || signal?.aborted) throw error;
4228
+ lastError = error;
4229
+ }
4230
+ await delay2(HEALTH_POLL_INTERVAL_MS, signal);
4231
+ }
4232
+ const message = lastError instanceof Error ? lastError.message : String(lastError);
4233
+ throw new DeploymentError(`Runtime in sandbox ${sandboxId} did not answer within ${timeoutMs}ms: ${message}`);
4234
+ }
4235
+ endpoint(sandboxId) {
4236
+ let endpoint = this.endpoints.get(sandboxId);
4237
+ if (!endpoint) {
4238
+ endpoint = this.sandbox(sandboxId).then((sandbox) => sandbox.getServerEndpoint(this.port));
4239
+ endpoint.catch(() => this.endpoints.delete(sandboxId));
4240
+ this.endpoints.set(sandboxId, endpoint);
4241
+ }
4242
+ return endpoint;
4243
+ }
4244
+ async request(sandboxId, method, path2, body, signal, options = {}) {
4245
+ for (let attempt = 0; ; attempt += 1) {
4246
+ const endpoint = await untilAborted(() => this.endpoint(sandboxId), signal);
4247
+ const url = new URL(`${endpoint.url}${path2}`);
4248
+ for (const [name, value] of Object.entries(endpoint.query)) url.searchParams.set(name, value);
4249
+ const timeout = options.stream ? void 0 : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
4250
+ const signals = [signal, timeout].filter((value) => value !== void 0);
4251
+ const response = await fetch(url, {
4252
+ method,
4253
+ headers: {
4254
+ ...endpoint.headers,
4255
+ ...body === void 0 ? {} : { "content-type": "application/json" },
4256
+ ...options.stream ? { accept: "text/event-stream" } : {}
4257
+ },
4258
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
4259
+ ...signals.length ? { signal: AbortSignal.any(signals) } : {}
4260
+ });
4261
+ if (response.status === 401 || response.status === 403) {
4262
+ await response.body?.cancel();
4263
+ this.endpoints.delete(sandboxId);
4264
+ if (attempt === 0) continue;
4265
+ throw new EndpointRejectedError(`Sandbox ${sandboxId} rejected its endpoint credentials (${response.status}).`);
4266
+ }
4267
+ return response;
4268
+ }
4269
+ }
4270
+ async prepareDaytonaSnapshot(sandbox, options) {
4271
+ const { Daytona, DaytonaNotFoundError } = await import("@daytona/sdk");
4272
+ const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
4273
+ const name = this.artifactName;
4274
+ const deadline = Date.now() + (this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS);
4275
+ const find = () => untilAborted(() => daytona.snapshot.get(name), options.signal).catch((error) => {
4276
+ if (error instanceof DaytonaNotFoundError) return void 0;
4277
+ throw error;
4278
+ });
4279
+ const isFailed = (found) => found.state === "error" || found.state === "build_failed";
4280
+ const isGoing = (found) => isFailed(found) || found.state === "removing";
4281
+ let snapshot = await find();
4282
+ let replaced;
4283
+ if (snapshot && snapshot.state !== "removing" && (isFailed(snapshot) || options.refresh)) {
4284
+ const old = snapshot;
4285
+ replaced = old;
4286
+ await untilAborted(() => daytona.snapshot.delete(old), options.signal).catch((error) => {
4287
+ if (!(error instanceof DaytonaNotFoundError)) throw error;
4288
+ });
4289
+ }
4290
+ while (snapshot && (isGoing(snapshot) || replaced !== void 0 && snapshot.id === replaced.id)) {
4291
+ await delay2(1e3, options.signal);
4292
+ snapshot = await find();
4293
+ }
4294
+ if (!snapshot) {
4295
+ try {
4296
+ snapshot = await untilAborted(() => daytona.snapshot.create(
4297
+ {
4298
+ name,
4299
+ image: this.image,
4300
+ entrypoint: this.command,
4301
+ ...sandbox.resources ? { resources: sandbox.resources } : {}
4302
+ },
4303
+ {
4304
+ timeout: Math.ceil((deadline - Date.now()) / 1e3),
4305
+ ...options.onLog ? { onLogs: options.onLog } : {}
4306
+ }
4307
+ ), options.signal);
4308
+ } catch (error) {
4309
+ if (options.signal.aborted) throw error;
4310
+ snapshot = await find();
4311
+ if (!snapshot) throw error;
4312
+ }
4313
+ }
4314
+ while (true) {
4315
+ if (snapshot.state === "active") return;
4316
+ if (snapshot.state === "inactive") {
4317
+ const inactive = snapshot;
4318
+ snapshot = await untilAborted(() => daytona.snapshot.activate(inactive), options.signal);
4319
+ continue;
4320
+ }
4321
+ if (isFailed(snapshot)) {
4322
+ throw new DeploymentError(`Daytona snapshot ${name} is ${snapshot.state}: ${snapshot.errorReason ?? "no reason given"}`);
4323
+ }
4324
+ await delay2(2e3, options.signal);
4325
+ snapshot = await find() ?? snapshot;
4326
+ }
4327
+ }
4328
+ async prepareE2bTemplate(sandbox, { signal, refresh, onLog }) {
4329
+ const { Template } = await import("e2b");
4330
+ const name = this.artifactName;
4331
+ const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
4332
+ const connection = { ...apiKey ? { apiKey } : {}, signal };
4333
+ const timeoutMs = this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS;
4334
+ const waitingGraceMs = Math.min(6e4, timeoutMs / 4);
4335
+ const pollMs = Math.min(2e3, waitingGraceMs / 4);
4336
+ let waitingSince;
4337
+ while (!refresh) {
4338
+ const { templates } = await this.e2bTemplates(sandbox, signal);
4339
+ const status = templates.find((template2) => [...template2.names ?? [], ...template2.aliases ?? []].includes(name))?.buildStatus;
4340
+ if (status === "ready") return;
4341
+ if (status === "waiting") {
4342
+ waitingSince ??= Date.now();
4343
+ if (Date.now() - waitingSince > waitingGraceMs) break;
4344
+ } else if (status !== "building") {
4345
+ break;
4346
+ }
4347
+ await delay2(pollMs, signal);
4348
+ }
4349
+ const template = Template().fromImage(
4350
+ this.image,
4351
+ ...sandbox.registry ? [sandbox.registry] : []
4352
+ );
4353
+ await Template.build(template, name, {
4354
+ ...connection,
4355
+ ...sandbox.cpuCount === void 0 ? {} : { cpuCount: sandbox.cpuCount },
4356
+ ...sandbox.memoryMB === void 0 ? {} : { memoryMB: sandbox.memoryMB },
4357
+ ...onLog ? { onBuildLogs: (entry) => onLog(entry.toString()) } : {}
4358
+ });
4359
+ }
4360
+ async listDaytonaSnapshots(sandbox, ownName) {
4361
+ const { Daytona } = await import("@daytona/sdk");
4362
+ const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
4363
+ const artifacts = [];
4364
+ for (let page = 1; ; page += 1) {
4365
+ const result = await daytona.snapshot.list({ page, limit: 100 });
4366
+ for (const snapshot of result.items) {
4367
+ if (!ownName.test(snapshot.name)) continue;
4368
+ artifacts.push({
4369
+ name: snapshot.name,
4370
+ createdAt: new Date(snapshot.createdAt).getTime(),
4371
+ delete: () => daytona.snapshot.delete(snapshot)
4372
+ });
4373
+ }
4374
+ if (page >= result.totalPages) return artifacts;
4375
+ }
4376
+ }
4377
+ async e2bTemplates(sandbox, signal) {
4378
+ const { ApiClient, ConnectionConfig } = await import("e2b");
4379
+ const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
4380
+ const client = new ApiClient(new ConnectionConfig(apiKey ? { apiKey } : {}));
4381
+ const { data, error } = await client.api.GET("/templates", signal ? { signal } : {});
4382
+ if (error || !data) throw new ExecutionError(`Listing E2B templates failed: ${JSON.stringify(error)}`);
4383
+ return { client, templates: data };
4384
+ }
4385
+ async listE2bTemplates(sandbox, ownName) {
4386
+ const { client, templates } = await this.e2bTemplates(sandbox);
4387
+ return templates.flatMap((template) => {
4388
+ const name = [...template.names ?? [], ...template.aliases ?? []].find((value) => ownName.test(value));
4389
+ if (!name) return [];
4390
+ return [{
4391
+ name,
4392
+ createdAt: new Date(template.createdAt).getTime(),
4393
+ delete: async () => {
4394
+ const result = await client.api.DELETE("/templates/{templateID}", {
4395
+ params: { path: { templateID: template.templateID } }
4396
+ });
4397
+ if (result.error) throw new ExecutionError(`Deleting E2B template ${name} failed: ${JSON.stringify(result.error)}`);
4398
+ }
4399
+ }];
4400
+ });
4401
+ }
4402
+ };
4403
+
4404
+ // src/braintrust.ts
4405
+ var API_KEY = "BRAINTRUST_API_KEY";
4406
+ var PROJECT_NAME = "BRAINTRUST_PROJECT_NAME";
4407
+ var FLUSH_TIMEOUT_MS = 1e4;
4408
+ var BRAINTRUST_PACKAGE = "braintrust";
4409
+ var BRAINTRUST_VERSIONS = ">=3.44.0 <4.0.0";
4410
+ var warn = (message) => console.warn(`neckbeard: ${message}`);
4411
+ var errorText = (error) => error instanceof Error ? error.message : String(error);
4412
+ function readBraintrustSettings(env, where) {
4413
+ const apiKey = env[API_KEY]?.trim();
4414
+ const projectName = env[PROJECT_NAME]?.trim();
4415
+ if (apiKey && projectName) return { apiKey, projectName };
4416
+ if (apiKey) warn(`Braintrust logging isn't configured ${where}: ${PROJECT_NAME} is not set.`);
4417
+ return void 0;
4418
+ }
4419
+ async function startBraintrust({ apiKey, projectName }) {
4420
+ const notTracing = "Braintrust tracing is off in the sandbox";
4421
+ let sdk;
4422
+ try {
4423
+ sdk = await import(
4424
+ /* webpackIgnore: true */
4425
+ BRAINTRUST_PACKAGE
4426
+ );
4427
+ } catch (error) {
4428
+ if (errorText(error).includes(`Cannot find package '${BRAINTRUST_PACKAGE}'`)) {
4429
+ warn(`${notTracing}: add ${BRAINTRUST_PACKAGE} ${BRAINTRUST_VERSIONS} to the agent's package's dependencies so the image has it.`);
4430
+ } else {
4431
+ warn(`${notTracing}: ${BRAINTRUST_PACKAGE} failed to load: ${errorText(error)}`);
4432
+ }
4433
+ return void 0;
4434
+ }
4435
+ if (typeof sdk.wrapPiCodingAgentSDK !== "function") {
4436
+ warn(`${notTracing}: its ${BRAINTRUST_PACKAGE} can't trace Pi; use ${BRAINTRUST_VERSIONS}.`);
4437
+ return void 0;
4438
+ }
4439
+ try {
4440
+ sdk.initLogger({ projectName, apiKey });
4441
+ } catch (error) {
4442
+ warn(`${notTracing}: ${errorText(error)}`);
4443
+ return void 0;
4444
+ }
4445
+ return {
4446
+ wrapPi: (pi) => sdk.wrapPiCodingAgentSDK(pi),
4447
+ async flush() {
4448
+ try {
4449
+ await withTimeout(sdk.flush(), FLUSH_TIMEOUT_MS, `not sent within ${FLUSH_TIMEOUT_MS / 1e3} seconds; it may arrive later`);
4450
+ } catch (error) {
4451
+ warn(`could not send the turn's Braintrust trace: ${errorText(error)}`);
4452
+ }
4453
+ }
4454
+ };
4455
+ }
4456
+
4457
+ // src/serve.ts
4458
+ var import_node_http = require("http");
4459
+ var HEARTBEAT_INTERVAL_MS = 15e3;
4460
+ var DEFAULT_ABORT_GRACE_MS = 1e4;
4461
+ var DEFAULT_PORT2 = 8080;
4462
+ function toPiJsonEvent(event) {
4463
+ if (!isRecord2(event) || event.type !== "message_update") return event;
4464
+ const { message, assistantMessageEvent } = event;
4465
+ if (!isRecord2(message) || message.role !== "assistant") {
4466
+ throw new Error("message_update message is not an assistant message");
4467
+ }
4468
+ if (!isRecord2(assistantMessageEvent) || typeof assistantMessageEvent.type !== "string") {
4469
+ throw new Error("message_update has no assistantMessageEvent");
4470
+ }
4471
+ const { partial, ...delta } = assistantMessageEvent;
4472
+ if (assistantMessageEvent.type === "toolcall_start") {
4473
+ const { contentIndex } = assistantMessageEvent;
4474
+ const content = isRecord2(partial) && Array.isArray(partial.content) ? partial.content : [];
4475
+ const toolCall = typeof contentIndex === "number" ? content[contentIndex] : void 0;
4476
+ if (!isRecord2(toolCall) || toolCall.type !== "toolCall" || typeof toolCall.id !== "string" || typeof toolCall.name !== "string") {
4477
+ throw new Error(`toolcall_start content at index ${String(contentIndex)} is not a tool call`);
4478
+ }
4479
+ return {
4480
+ type: "message_update",
4481
+ usage: message.usage,
4482
+ assistantMessageEvent: { ...delta, id: toolCall.id, toolName: toolCall.name }
4483
+ };
4484
+ }
4485
+ return { type: "message_update", usage: message.usage, assistantMessageEvent: delta };
4486
+ }
4487
+ var RequestError = class extends Error {
4488
+ constructor(status, message) {
4489
+ super(message);
4490
+ this.status = status;
4491
+ }
4492
+ };
4493
+ function sendJson(response, status, body) {
4494
+ response.writeHead(status, { "content-type": "application/json" });
4495
+ response.end(JSON.stringify(body));
4496
+ }
4497
+ async function readJsonBody(request) {
4498
+ const chunks = [];
4499
+ let size = 0;
4500
+ for await (const chunk of request) {
4501
+ size += chunk.byteLength;
4502
+ if (size > MAX_TURN_REQUEST_BYTES) throw new RequestError(413, "Request body is too large.");
4503
+ chunks.push(chunk);
4504
+ }
4505
+ try {
4506
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
4507
+ } catch {
4508
+ throw new RequestError(400, "Request body must be JSON.");
4509
+ }
4510
+ }
4511
+ function parseStartTurn(body) {
4512
+ if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
4513
+ const { turnId, message, env } = body;
4514
+ if (typeof turnId !== "string" || !turnId || turnId.length > MAX_TURN_ID_LENGTH) {
4515
+ throw new RequestError(400, `turnId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
4516
+ }
4517
+ if (typeof message !== "string" || !message.trim()) {
4518
+ throw new RequestError(400, "message must be a non-empty string.");
4519
+ }
4520
+ if (env !== void 0 && (!env || typeof env !== "object" || Array.isArray(env) || Object.entries(env).some(([name, value]) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || typeof value !== "string"))) {
4521
+ throw new RequestError(400, "env must map environment variable names to strings.");
4522
+ }
4523
+ return { turnId, message, ...env === void 0 ? {} : { env } };
4524
+ }
4525
+ async function serve(options) {
4526
+ const toWireEvent = options.toWireEvent ?? toPiJsonEvent;
4527
+ let sessionPromise;
4528
+ let current;
4529
+ let previous;
4530
+ let currentSessionAbort;
4531
+ const findTurn = (turnId) => current?.id === turnId ? current : previous?.id === turnId ? previous : void 0;
4532
+ const append = (turn, record) => {
4533
+ const json = JSON.stringify({ seq: turn.records.length, ...record });
4534
+ turn.records.push(json);
4535
+ for (const wake of turn.waiters) wake();
4536
+ };
4537
+ const end = (turn, outcome, error) => {
4538
+ if (turn.ended) return;
4539
+ append(turn, { type: "end", outcome, ...error === void 0 ? {} : { error } });
4540
+ turn.ended = true;
4541
+ };
4542
+ const endAfterGrace = (turn, outcome, error) => {
4543
+ if (turn.ended || turn.finishing || turn.forceEnd) return;
4544
+ turn.forceEnd = setTimeout(() => end(turn, outcome, error), options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS);
4545
+ };
4546
+ const runTurn = async (turn, request) => {
4547
+ const previousEnv = /* @__PURE__ */ new Map();
4548
+ let unsubscribe;
4549
+ let timedOut = false;
4550
+ let session;
4551
+ const timeoutMessage = `Turn exceeded ${options.maxTurnDurationMs}ms.`;
4552
+ const timer = options.maxTurnDurationMs === void 0 ? void 0 : setTimeout(() => {
4553
+ timedOut = true;
4554
+ if (session) void session.abort().catch(() => void 0);
4555
+ endAfterGrace(turn, "failed", timeoutMessage);
4556
+ }, options.maxTurnDurationMs);
4557
+ const finish = async (outcome, error) => {
4558
+ turn.finishing = true;
4559
+ if (timer) clearTimeout(timer);
4560
+ clearTimeout(turn.forceEnd);
4561
+ try {
4562
+ await session?.afterTurn?.();
4563
+ } catch {
4564
+ }
4565
+ end(turn, outcome, error);
4566
+ };
4567
+ try {
4568
+ sessionPromise ??= options.createSession();
4569
+ try {
4570
+ session = await sessionPromise;
4571
+ } catch (error) {
4572
+ sessionPromise = void 0;
4573
+ throw error;
4574
+ }
4575
+ if (timedOut) {
4576
+ end(turn, "failed", timeoutMessage);
4577
+ return;
4578
+ }
4579
+ const started = session;
4580
+ for (const [name, value] of Object.entries(request.env ?? {})) {
4581
+ previousEnv.set(name, process.env[name]);
4582
+ process.env[name] = value;
4583
+ }
4584
+ unsubscribe = session.subscribe((event) => {
4585
+ if (turn.ended) return;
4586
+ try {
4587
+ append(turn, { type: "event", event: toWireEvent(event) });
4588
+ } catch (error) {
4589
+ end(turn, "failed", `Could not convert an agent event: ${error instanceof Error ? error.message : String(error)}`);
4590
+ void started.abort().catch(() => void 0);
4591
+ }
4592
+ });
4593
+ currentSessionAbort = () => started.abort();
4594
+ if (turn.abortRequested) {
4595
+ end(turn, "aborted");
4596
+ return;
4597
+ }
4598
+ await started.prompt(request.message);
4599
+ if (timedOut) await finish("failed", timeoutMessage);
4600
+ else await finish(turn.abortRequested ? "aborted" : "completed");
4601
+ } catch (error) {
4602
+ const message = error instanceof Error ? error.message : String(error);
4603
+ if (timedOut) await finish("failed", timeoutMessage);
4604
+ else await finish(turn.abortRequested ? "aborted" : "failed", turn.abortRequested ? void 0 : message);
4605
+ } finally {
4606
+ if (timer) clearTimeout(timer);
4607
+ clearTimeout(turn.forceEnd);
4608
+ unsubscribe?.();
4609
+ currentSessionAbort = void 0;
4610
+ for (const [name, value] of previousEnv) {
4611
+ if (value === void 0) delete process.env[name];
4612
+ else process.env[name] = value;
4613
+ }
4614
+ turn.settled = true;
4615
+ }
4616
+ };
4617
+ const busy = () => Boolean(current && !current.settled);
4618
+ const startTurn = async (request) => {
4619
+ const existing = findTurn(request.turnId);
4620
+ if (existing) return { status: 200, body: { turnId: existing.id, ended: existing.ended } };
4621
+ if (current && !current.settled) {
4622
+ return { status: 409, body: { error: "Another turn is running.", turnId: current.id } };
4623
+ }
4624
+ const turn = {
4625
+ id: request.turnId,
4626
+ records: [],
4627
+ ended: false,
4628
+ settled: false,
4629
+ abortRequested: false,
4630
+ finishing: false,
4631
+ waiters: /* @__PURE__ */ new Set()
4632
+ };
4633
+ previous = current;
4634
+ current = turn;
4635
+ void runTurn(turn, request);
4636
+ return { status: 202, body: { turnId: turn.id, ended: false } };
4637
+ };
4638
+ const streamTurn = async (turn, after, request, response) => {
4639
+ response.writeHead(200, {
4640
+ "content-type": "text/event-stream",
4641
+ "cache-control": "no-cache, no-transform",
4642
+ connection: "keep-alive",
4643
+ "x-accel-buffering": "no"
4644
+ });
4645
+ response.write(": connected\n\n");
4646
+ let closed = false;
4647
+ let wake;
4648
+ const onClose = () => {
4649
+ closed = true;
4650
+ wake?.();
4651
+ };
4652
+ request.on("close", onClose);
4653
+ response.on("close", onClose);
4654
+ const heartbeat = setInterval(() => {
4655
+ if (!closed) response.write(": ping\n\n");
4656
+ }, HEARTBEAT_INTERVAL_MS);
4657
+ let next = turn.ended ? Math.min(after + 1, turn.records.length - 1) : after + 1;
4658
+ try {
4659
+ while (!closed) {
4660
+ while (!closed && next < turn.records.length) {
4661
+ const ok = response.write(`id: ${next}
4662
+ data: ${turn.records[next]}
4663
+
4664
+ `);
4665
+ next += 1;
4666
+ if (!ok && !closed) {
4667
+ let onDrain;
4668
+ await new Promise((resolve2) => {
4669
+ wake = onDrain = resolve2;
4670
+ response.once("drain", resolve2);
4671
+ });
4672
+ if (onDrain) response.off("drain", onDrain);
4673
+ wake = void 0;
4674
+ }
4675
+ }
4676
+ if (closed || turn.ended && next >= turn.records.length) break;
4677
+ await new Promise((resolve2) => {
4678
+ wake = resolve2;
4679
+ turn.waiters.add(resolve2);
4680
+ });
4681
+ if (wake) turn.waiters.delete(wake);
4682
+ wake = void 0;
4683
+ }
4684
+ } finally {
4685
+ clearInterval(heartbeat);
4686
+ request.off("close", onClose);
4687
+ response.off("close", onClose);
4688
+ if (!closed) response.end();
4689
+ }
4690
+ };
4691
+ const server = (0, import_node_http.createServer)((request, response) => {
4692
+ void (async () => {
4693
+ const url = new URL(request.url ?? "/", "http://localhost");
4694
+ const turnPath = /^\/turns\/([^/]+)\/(events|abort)$/u.exec(url.pathname);
4695
+ if (request.method === "GET" && url.pathname === "/health") {
4696
+ const health = {
4697
+ ok: true,
4698
+ protocolVersion: TURN_PROTOCOL_VERSION,
4699
+ busy: busy(),
4700
+ turnId: current?.id ?? null
4701
+ };
4702
+ return sendJson(response, 200, health);
4703
+ }
4704
+ if (request.method === "POST" && url.pathname === "/turns") {
4705
+ const { status, body } = await startTurn(parseStartTurn(await readJsonBody(request)));
4706
+ return sendJson(response, status, body);
4707
+ }
4708
+ if (turnPath) {
4709
+ const turn = findTurn(decodeURIComponent(turnPath[1]));
4710
+ if (!turn) return sendJson(response, 404, { error: "Unknown turn." });
4711
+ if (request.method === "GET" && turnPath[2] === "events") {
4712
+ const afterParam = url.searchParams.get("after");
4713
+ const after = afterParam === null ? -1 : Number(afterParam);
4714
+ if (!Number.isSafeInteger(after) || after < -1) {
4715
+ return sendJson(response, 400, { error: "after must be an integer of at least -1." });
4716
+ }
4717
+ return streamTurn(turn, after, request, response);
4718
+ }
4719
+ if (request.method === "POST" && turnPath[2] === "abort") {
4720
+ if (!turn.ended && !turn.finishing && !turn.abortRequested) {
4721
+ turn.abortRequested = true;
4722
+ if (turn === current) void currentSessionAbort?.().catch(() => void 0);
4723
+ endAfterGrace(turn, "aborted");
4724
+ }
4725
+ return sendJson(response, 202, { turnId: turn.id, ended: turn.ended });
4726
+ }
4727
+ }
4728
+ sendJson(response, 404, { error: "Not found." });
4729
+ })().catch((error) => {
4730
+ if (response.headersSent) {
4731
+ response.destroy();
4732
+ return;
4733
+ }
4734
+ const status = error instanceof RequestError ? error.status : 500;
4735
+ sendJson(response, status, { error: error instanceof Error ? error.message : String(error) });
4736
+ });
4737
+ });
4738
+ const port = options.port ?? (Number(process.env.NECKBEARD_PORT) || DEFAULT_PORT2);
4739
+ await new Promise((resolve2, reject) => {
4740
+ server.once("error", reject);
4741
+ server.listen(port, options.host ?? "0.0.0.0", () => {
4742
+ server.off("error", reject);
4743
+ resolve2();
4744
+ });
4745
+ });
4746
+ return {
4747
+ port: server.address().port,
4748
+ close: () => new Promise((resolve2, reject) => {
4749
+ server.closeAllConnections();
4750
+ server.close((error) => error ? reject(error) : resolve2());
4751
+ })
4752
+ };
4753
+ }
4754
+
4755
+ // src/define.ts
4756
+ var SKILLS_DIR = "/app/.agents/skills";
4757
+ var IMAGE_TAG_ENV_VARS = [
4758
+ "NECKBEARD_IMAGE_TAG",
4759
+ "GITHUB_SHA",
4760
+ "CI_COMMIT_SHA",
4761
+ "BITBUCKET_COMMIT",
4762
+ "CODEBUILD_RESOLVED_SOURCE_VERSION",
4763
+ "BUILDKITE_COMMIT",
4764
+ "CIRCLE_SHA1",
4765
+ "CF_PAGES_COMMIT_SHA",
4766
+ "HEROKU_BUILD_COMMIT",
4767
+ "HEROKU_SLUG_COMMIT",
4768
+ "RAILWAY_GIT_COMMIT_SHA",
4769
+ "RENDER_GIT_COMMIT",
4770
+ "VERCEL_GIT_COMMIT_SHA",
4771
+ "SOURCE_VERSION",
4772
+ "GIT_COMMIT"
4773
+ ];
4774
+ function resolveImageTag(env = process.env) {
4775
+ for (const name of IMAGE_TAG_ENV_VARS) {
4776
+ const value = env[name]?.trim();
4777
+ if (value && value !== name) return value;
4778
+ }
4779
+ return void 0;
4780
+ }
4781
+ var PI_PACKAGE = "@earendil-works/pi-coding-agent";
4782
+ var definedAgentMarker = /* @__PURE__ */ Symbol.for("agent-neckbeard.DefinedAgent");
4783
+ var DefinedAgent = class {
4784
+ constructor(definition) {
4785
+ this.definition = definition;
4786
+ if (!definition || typeof definition !== "object") throw new ConfigurationError("Agent definition must be an object.");
4787
+ if (typeof definition.name !== "string" || !/^[a-z0-9]+(-[a-z0-9]+)*$/u.test(definition.name)) {
4788
+ throw new ConfigurationError("Agent name must be lowercase letters, digits, and single dashes.");
4789
+ }
4790
+ if (Boolean(definition.pi) === Boolean(definition.createSession)) {
4791
+ throw new ConfigurationError(`Agent ${definition.name} needs exactly one of pi and createSession.`);
4792
+ }
4793
+ if (!definition.image && !definition.registry) {
4794
+ throw new ConfigurationError(`Agent ${definition.name} needs a registry or an image.`);
4795
+ }
4796
+ }
4797
+ [definedAgentMarker] = true;
4798
+ client;
4799
+ braintrustChecked = false;
4800
+ get name() {
4801
+ return this.definition.name;
4802
+ }
4803
+ /** The image this host runs: `image`, else `<registry>/<name>:<tag>` with the tag `resolveImageTag()` finds. */
4804
+ imageRef(tag = resolveImageTag()) {
4805
+ const { image, registry, name } = this.definition;
4806
+ if (image) return image;
4807
+ if (!tag) {
4808
+ throw new ConfigurationError(
4809
+ `Set NECKBEARD_IMAGE_TAG to choose agent ${name}'s image, or deploy from a platform that names the commit, such as RENDER_GIT_COMMIT.`
4810
+ );
4811
+ }
4812
+ return `${registry.replace(/\/+$/u, "")}/${name}:${tag}`;
4813
+ }
4814
+ /** The `Agent` for an image, by default the one this host runs. */
4815
+ forImage(image = this.imageRef()) {
4816
+ const { definition } = this;
4817
+ const sandbox = typeof definition.sandbox === "function" ? definition.sandbox() : definition.sandbox;
4818
+ const envs = typeof definition.envs === "function" ? definition.envs() : definition.envs;
4819
+ return new Agent({
4820
+ name: definition.name,
4821
+ image,
4822
+ sandbox,
4823
+ ...envs ? { envs } : {},
4824
+ ...definition.command ? { command: definition.command } : {},
4825
+ ...definition.port === void 0 ? {} : { port: definition.port },
4826
+ ...definition.startTimeoutMs === void 0 ? {} : { startTimeoutMs: definition.startTimeoutMs },
4827
+ ...definition.prepareTimeoutMs === void 0 ? {} : { prepareTimeoutMs: definition.prepareTimeoutMs }
4828
+ });
4829
+ }
4830
+ get agent() {
4831
+ this.client ??= this.forImage();
4832
+ return this.client;
4833
+ }
4834
+ get artifactName() {
4835
+ return this.agent.artifactName;
4836
+ }
4837
+ prepare(options) {
4838
+ return this.agent.prepare(options);
4839
+ }
4840
+ start(options) {
4841
+ if (this.definition.pi && !this.braintrustChecked) {
4842
+ this.braintrustChecked = true;
4843
+ const envs = typeof this.definition.envs === "function" ? this.definition.envs() : this.definition.envs;
4844
+ readBraintrustSettings({ ...filterDefined(envs), ...filterDefined(options?.envs) }, `for agent ${this.name}'s sandboxes`);
4845
+ }
4846
+ return this.agent.start(options);
4847
+ }
4848
+ prompt(sandboxId, turn, options) {
4849
+ return this.agent.prompt(sandboxId, turn, options);
4850
+ }
4851
+ run(sandboxId, turn, options) {
4852
+ return this.agent.run(sandboxId, turn, options);
4853
+ }
4854
+ events(sandboxId, turnId, options) {
4855
+ return this.agent.events(sandboxId, turnId, options);
4856
+ }
4857
+ abort(sandboxId, turnId, signal) {
4858
+ return this.agent.abort(sandboxId, turnId, signal);
4859
+ }
4860
+ health(sandboxId, signal) {
4861
+ return this.agent.health(sandboxId, signal);
4862
+ }
4863
+ waitForIdle(sandboxId, options) {
4864
+ return this.agent.waitForIdle(sandboxId, options);
4865
+ }
4866
+ kill(sandboxId) {
4867
+ return this.agent.kill(sandboxId);
4868
+ }
4869
+ sandbox(sandboxId) {
4870
+ return this.agent.sandbox(sandboxId);
4871
+ }
4872
+ gc(options) {
4873
+ return this.agent.gc(options);
4874
+ }
4875
+ /** Where a persisted session's file is in a sandbox whose home is `homeDir`, as for copying it out and back. */
4876
+ sessionFilePath(homeDir, sessionId) {
4877
+ return import_node_path.default.posix.join(homeDir, "agent", ".pi", "sessions", `${sessionId}.jsonl`);
4878
+ }
4879
+ /** Serves the agent's session; the image's entry point, which `neckbeard build` generates, calls it. */
4880
+ serve(options = {}) {
4881
+ const { definition } = this;
4882
+ const { pi } = definition;
4883
+ return serve({
4884
+ createSession: pi ? () => createPiSession(pi) : definition.createSession,
4885
+ ...definition.maxTurnDurationMs === void 0 ? {} : { maxTurnDurationMs: definition.maxTurnDurationMs },
4886
+ ...definition.abortGraceMs === void 0 ? {} : { abortGraceMs: definition.abortGraceMs },
4887
+ ...options
4888
+ });
4889
+ }
4890
+ };
4891
+ function defineAgent(definition) {
4892
+ return new DefinedAgent(definition);
4893
+ }
4894
+ function isDefinedAgent(value) {
4895
+ return typeof value === "object" && value !== null && definedAgentMarker in value;
4896
+ }
4897
+ async function createPiSession(config) {
4898
+ const home = import_node_os.default.homedir();
4899
+ const cwd = import_node_path.default.resolve(home, config.cwd ?? "workspace");
4900
+ await (0, import_promises.mkdir)(cwd, { recursive: true });
4901
+ process.env.NECKBEARD_CWD = cwd;
4902
+ const agentDir = import_node_path.default.join(home, "agent", ".pi");
4903
+ const loaded = await import(
4904
+ /* webpackIgnore: true */
4905
+ PI_PACKAGE
4906
+ );
4907
+ const braintrustSettings = readBraintrustSettings(process.env, "in the sandbox");
4908
+ const braintrust = braintrustSettings && await startBraintrust(braintrustSettings);
4909
+ const pi = braintrust ? braintrust.wrapPi(loaded) : loaded;
4910
+ const modelRuntime = await pi.ModelRuntime.create({ modelsPath: null });
4911
+ const separator = config.model.indexOf("/");
4912
+ const model = separator > 0 ? modelRuntime.getModel(config.model.slice(0, separator), config.model.slice(separator + 1)) : void 0;
4913
+ if (!model) throw new ConfigurationError(`Pi has no model ${config.model}; name it as provider/model.`);
4914
+ const settingsManager = pi.SettingsManager.inMemory();
4915
+ const resourceLoader = new pi.DefaultResourceLoader({
4916
+ cwd,
4917
+ agentDir,
4918
+ settingsManager,
4919
+ additionalSkillPaths: [SKILLS_DIR],
4920
+ noSkills: true,
4921
+ noExtensions: true,
4922
+ noPromptTemplates: true,
4923
+ noContextFiles: true,
4924
+ systemPrompt: config.systemPrompt
4925
+ });
4926
+ await resourceLoader.reload();
4927
+ let sessionManager;
4928
+ if (config.persist) {
4929
+ const sessionId = process.env.NECKBEARD_SESSION_ID;
4930
+ if (!sessionId) throw new ConfigurationError("A persisted Pi session needs the sessionId passed to start().");
4931
+ const sessionFile = import_node_path.default.join(agentDir, "sessions", `${sessionId}.jsonl`);
4932
+ sessionManager = pi.SessionManager.open(sessionFile, import_node_path.default.dirname(sessionFile), cwd);
4933
+ } else {
4934
+ sessionManager = pi.SessionManager.inMemory(cwd);
4935
+ }
4936
+ const { session } = await pi.createAgentSession({
4937
+ cwd,
4938
+ agentDir,
4939
+ model,
4940
+ modelRuntime,
4941
+ resourceLoader,
4942
+ settingsManager,
4943
+ sessionManager,
4944
+ ...config.thinkingLevel ? { thinkingLevel: config.thinkingLevel } : {},
4945
+ ...config.tools ? { tools: config.tools } : {}
4946
+ });
4947
+ if (!braintrust) return session;
4948
+ return {
4949
+ subscribe: (listener) => session.subscribe(listener),
4950
+ prompt: (text) => session.prompt(text),
4951
+ abort: () => session.abort(),
4952
+ afterTurn: () => braintrust.flush()
4953
+ };
4954
+ }
4955
+
3592
4956
  // src/providers/docker.ts
3593
4957
  var import_node_child_process = require("child_process");
3594
4958
  var import_node_net = require("net");
@@ -3831,18 +5195,18 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
3831
5195
  }
3832
5196
  return result;
3833
5197
  }
3834
- async makeDir(path) {
3835
- await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path]);
5198
+ async makeDir(path2) {
5199
+ await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path2]);
3836
5200
  }
3837
- async writeFile(path, content) {
5201
+ async writeFile(path2, content) {
3838
5202
  const input = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
3839
- await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path], input, DOCKER_FILE_TIMEOUT_MS);
5203
+ await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path2], input, DOCKER_FILE_TIMEOUT_MS);
3840
5204
  }
3841
- async readFile(path) {
3842
- return (await this.control("Docker file read", 'cat -- "$1"', [path], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
5205
+ async readFile(path2) {
5206
+ return (await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
3843
5207
  }
3844
- async readFileBytes(path) {
3845
- return new Uint8Array((await this.control("Docker file read", 'cat -- "$1"', [path], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout);
5208
+ async readFileBytes(path2) {
5209
+ return new Uint8Array((await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout);
3846
5210
  }
3847
5211
  async runCommand(command, options) {
3848
5212
  validateProviderCommand("Docker", command, options);
@@ -3891,8 +5255,8 @@ exec timeout --kill-after=1 ${deadlineSeconds} /bin/bash --noprofile --norc -c $
3891
5255
  };
3892
5256
 
3893
5257
  // src/index.ts
3894
- function readPackageJson(path) {
3895
- return JSON.parse((0, import_node_fs.readFileSync)(path, "utf8"));
5258
+ function readPackageJson(path2) {
5259
+ return JSON.parse((0, import_node_fs.readFileSync)(path2, "utf8"));
3896
5260
  }
3897
5261
  var getEsbuild = () => import("esbuild");
3898
5262
  var getE2b = () => import("e2b");
@@ -3922,9 +5286,11 @@ var NeckbeardError = class extends Error {
3922
5286
  }
3923
5287
  };
3924
5288
  var DeploymentError = class extends NeckbeardError {
3925
- constructor(message, cause) {
5289
+ /** A sandbox the failure left behind, for `kill()`. */
5290
+ constructor(message, cause, sandboxId) {
3926
5291
  super(message);
3927
5292
  this.cause = cause;
5293
+ this.sandboxId = sandboxId;
3928
5294
  this.name = "DeploymentError";
3929
5295
  }
3930
5296
  };
@@ -3948,6 +5314,12 @@ var RuntimeBusyError = class extends ExecutionError {
3948
5314
  this.name = "RuntimeBusyError";
3949
5315
  }
3950
5316
  };
5317
+ var TurnLostError = class extends ExecutionError {
5318
+ constructor(message) {
5319
+ super(message);
5320
+ this.name = "TurnLostError";
5321
+ }
5322
+ };
3951
5323
  var ConfigurationError = class extends NeckbeardError {
3952
5324
  constructor(message) {
3953
5325
  super(message);
@@ -3961,7 +5333,7 @@ function resolveAgentSourceFile(candidates, options = {}) {
3961
5333
  return sourceFile;
3962
5334
  }
3963
5335
  if (process.env[NECKBEARD_SANDBOX_RUNTIME_ENV] === "1") {
3964
- const sandboxSourceFile = options.sandboxSourceFile ?? (0, import_node_path.resolve)(process.cwd(), "agent.mjs");
5336
+ const sandboxSourceFile = options.sandboxSourceFile ?? (0, import_node_path2.resolve)(process.cwd(), "agent.mjs");
3965
5337
  if ((0, import_node_fs.existsSync)(sandboxSourceFile)) {
3966
5338
  return sandboxSourceFile;
3967
5339
  }
@@ -4083,7 +5455,7 @@ function appendIncludesToTraceAssets({
4083
5455
  if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
4084
5456
  continue;
4085
5457
  }
4086
- const traceDir = (0, import_node_path.dirname)((0, import_node_path.join)(outputPath, assetName));
5458
+ const traceDir = (0, import_node_path2.dirname)((0, import_node_path2.join)(outputPath, assetName));
4087
5459
  const nextSource = traceWithIncludedFiles(String(asset.source()), traceDir, includedFiles);
4088
5460
  if (rawSource && updateAsset) {
4089
5461
  updateAsset(assetName, new rawSource(nextSource));
@@ -4155,7 +5527,7 @@ function appendIncludesToTraceFiles(outputPath, appDir, sourceFiles, routeGlobs,
4155
5527
  function appendFilesToTrace(traceFile, includedFiles) {
4156
5528
  const nextSource = traceWithIncludedFiles(
4157
5529
  (0, import_node_fs.readFileSync)(traceFile, "utf8"),
4158
- (0, import_node_path.dirname)(traceFile),
5530
+ (0, import_node_path2.dirname)(traceFile),
4159
5531
  includedFiles
4160
5532
  );
4161
5533
  (0, import_node_fs.writeFileSync)(traceFile, nextSource);
@@ -4165,7 +5537,7 @@ function traceWithIncludedFiles(traceSource, traceDir, includedFiles) {
4165
5537
  const files = Array.isArray(trace.files) ? trace.files.filter((file) => typeof file === "string") : [];
4166
5538
  const nextFiles = new Set(files);
4167
5539
  for (const includedFile of includedFiles) {
4168
- nextFiles.add((0, import_node_path.relative)(traceDir, includedFile).replace(/\\/g, "/"));
5540
+ nextFiles.add((0, import_node_path2.relative)(traceDir, includedFile).replace(/\\/g, "/"));
4169
5541
  }
4170
5542
  return JSON.stringify({
4171
5543
  version: trace.version ?? 1,
@@ -4191,7 +5563,7 @@ function traceIncludeFilesForConfig(appDir, sourceFiles, traceSourceDependencies
4191
5563
  return mergeStringArray(sourceFiles, tracedFiles);
4192
5564
  }
4193
5565
  function toNextTraceIncludePath(appDir, file) {
4194
- const relativePath = (0, import_node_path.relative)(appDir, file).replace(/\\/g, "/");
5566
+ const relativePath = (0, import_node_path2.relative)(appDir, file).replace(/\\/g, "/");
4195
5567
  if (relativePath.startsWith("..")) {
4196
5568
  return relativePath;
4197
5569
  }
@@ -4200,14 +5572,14 @@ function toNextTraceIncludePath(appDir, file) {
4200
5572
  function expandTraceIncludePattern(appDir, sourceFile) {
4201
5573
  const normalized = sourceFile.replace(/\\/g, "/").replace(/^\.\//, "");
4202
5574
  if (normalized.endsWith("/**/*")) {
4203
- const dir = (0, import_node_path.resolve)(appDir, normalized.slice(0, -5));
5575
+ const dir = (0, import_node_path2.resolve)(appDir, normalized.slice(0, -5));
4204
5576
  return findFiles(dir);
4205
5577
  }
4206
5578
  if (normalized.endsWith("/*")) {
4207
- const dir = (0, import_node_path.resolve)(appDir, normalized.slice(0, -2));
5579
+ const dir = (0, import_node_path2.resolve)(appDir, normalized.slice(0, -2));
4208
5580
  return directFiles(dir);
4209
5581
  }
4210
- const file = (0, import_node_path.resolve)(appDir, normalized);
5582
+ const file = (0, import_node_path2.resolve)(appDir, normalized);
4211
5583
  return (0, import_node_fs.existsSync)(file) && (0, import_node_fs.statSync)(file).isFile() ? [file] : [];
4212
5584
  }
4213
5585
  function traceSourceDependencyFiles(appDir, sourceFiles) {
@@ -4253,12 +5625,12 @@ function traceSourceDependencyFiles(appDir, sourceFiles) {
4253
5625
  continue;
4254
5626
  }
4255
5627
  const resolvedImportPath = importRecord.external ? void 0 : resolveMetafileInput(appDir, importRecord.path);
4256
- const packageInfo = resolvedImportPath ? resolvePackageInfoFromResolvedPath(importPath, resolvedImportPath) : resolvePackageInfoSync(importPath, (0, import_node_path.dirname)(absoluteInput));
5628
+ const packageInfo = resolvedImportPath ? resolvePackageInfoFromResolvedPath(importPath, resolvedImportPath) : resolvePackageInfoSync(importPath, (0, import_node_path2.dirname)(absoluteInput));
4257
5629
  if (!packageInfo) {
4258
5630
  continue;
4259
5631
  }
4260
5632
  addFile(packageInfo.resolvedPath);
4261
- addFile((0, import_node_path.join)(packageInfo.root, "package.json"));
5633
+ addFile((0, import_node_path2.join)(packageInfo.root, "package.json"));
4262
5634
  }
4263
5635
  }
4264
5636
  return [...files];
@@ -4272,7 +5644,7 @@ function getEsbuildSync() {
4272
5644
  return packageRequire("esbuild");
4273
5645
  }
4274
5646
  function resolveMetafileInput(absWorkingDir, inputPath) {
4275
- return (0, import_node_path.resolve)(absWorkingDir, inputPath);
5647
+ return (0, import_node_path2.resolve)(absWorkingDir, inputPath);
4276
5648
  }
4277
5649
  function findTraceFiles(root) {
4278
5650
  return findFiles(root).filter((file) => file.endsWith(".nft.json"));
@@ -4290,7 +5662,7 @@ function findFiles(root) {
4290
5662
  }
4291
5663
  const files = [];
4292
5664
  for (const entry of (0, import_node_fs.readdirSync)(root)) {
4293
- files.push(...findFiles((0, import_node_path.join)(root, entry)));
5665
+ files.push(...findFiles((0, import_node_path2.join)(root, entry)));
4294
5666
  }
4295
5667
  return files;
4296
5668
  }
@@ -4298,10 +5670,10 @@ function directFiles(root) {
4298
5670
  if (!(0, import_node_fs.existsSync)(root) || !(0, import_node_fs.statSync)(root).isDirectory()) {
4299
5671
  return [];
4300
5672
  }
4301
- return (0, import_node_fs.readdirSync)(root).map((entry) => (0, import_node_path.join)(root, entry)).filter((file) => (0, import_node_fs.statSync)(file).isFile());
5673
+ return (0, import_node_fs.readdirSync)(root).map((entry) => (0, import_node_path2.join)(root, entry)).filter((file) => (0, import_node_fs.statSync)(file).isFile());
4302
5674
  }
4303
5675
  function routePathFromTraceFile(outputPath, traceFile) {
4304
- const relativeTrace = (0, import_node_path.relative)(outputPath, traceFile).replace(/\\/g, "/");
5676
+ const relativeTrace = (0, import_node_path2.relative)(outputPath, traceFile).replace(/\\/g, "/");
4305
5677
  return routePathFromRelativeTrace(outputPath, relativeTrace);
4306
5678
  }
4307
5679
  function routePathFromTraceAsset(outputPath, assetName) {
@@ -4321,7 +5693,7 @@ function routePathFromRelativeTrace(outputPath, relativeTrace) {
4321
5693
  if (normalizedTrace.startsWith("pages/")) {
4322
5694
  return normalizeTraceRoute(normalizedTrace.slice("pages/".length));
4323
5695
  }
4324
- if ((0, import_node_path.basename)(outputPath) === "app" || (0, import_node_path.basename)(outputPath) === "pages") {
5696
+ if ((0, import_node_path2.basename)(outputPath) === "app" || (0, import_node_path2.basename)(outputPath) === "pages") {
4325
5697
  return normalizeTraceRoute(relativeTrace);
4326
5698
  }
4327
5699
  return void 0;
@@ -4431,7 +5803,7 @@ function normalizeLocalDirectoryDestination(destination, name) {
4431
5803
  throw new ConfigurationError(`${name}.destination must not contain null bytes.`);
4432
5804
  }
4433
5805
  const sandboxPath = destination.replace(/\\/g, "/");
4434
- if ((0, import_node_path.isAbsolute)(destination) || import_node_path.posix.isAbsolute(sandboxPath) || import_node_path.win32.isAbsolute(destination)) {
5806
+ if ((0, import_node_path2.isAbsolute)(destination) || import_node_path2.posix.isAbsolute(sandboxPath) || import_node_path2.win32.isAbsolute(destination)) {
4435
5807
  throw new ConfigurationError(
4436
5808
  `${name}.destination must be relative to the sandbox agent directory.`
4437
5809
  );
@@ -4441,7 +5813,7 @@ function normalizeLocalDirectoryDestination(destination, name) {
4441
5813
  `${name}.destination must not traverse outside the sandbox agent directory.`
4442
5814
  );
4443
5815
  }
4444
- const normalized = import_node_path.posix.normalize(sandboxPath);
5816
+ const normalized = import_node_path2.posix.normalize(sandboxPath);
4445
5817
  if (normalized === ".") {
4446
5818
  throw new ConfigurationError(`${name}.destination must not be ".".`);
4447
5819
  }
@@ -4640,10 +6012,10 @@ function requireEnv(name) {
4640
6012
  }
4641
6013
  return value;
4642
6014
  }
4643
- var require2 = (0, import_node_module2.createRequire)((0, import_node_path.join)(process.cwd(), "__agent_neckbeard__.cjs"));
6015
+ var require2 = (0, import_node_module2.createRequire)((0, import_node_path2.join)(process.cwd(), "__agent_neckbeard__.cjs"));
4644
6016
  var packageRequire = createPackageRequire();
4645
6017
  function createPackageRequire() {
4646
- const cwdPackageJsonPath = (0, import_node_path.join)(process.cwd(), "package.json");
6018
+ const cwdPackageJsonPath = (0, import_node_path2.join)(process.cwd(), "package.json");
4647
6019
  try {
4648
6020
  if ((0, import_node_fs.existsSync)(cwdPackageJsonPath) && readPackageJson(cwdPackageJsonPath).name === NECKBEARD_PACKAGE_NAME) {
4649
6021
  return (0, import_node_module2.createRequire)(cwdPackageJsonPath);
@@ -4656,12 +6028,12 @@ function createPackageRequire() {
4656
6028
  return require2;
4657
6029
  }
4658
6030
  }
4659
- function isBareModuleImport(path) {
6031
+ function isBareModuleImport(path2) {
4660
6032
  const excludes = [".", "/", "~", "file:", "data:"];
4661
- return !excludes.some((exclude) => path.startsWith(exclude));
6033
+ return !excludes.some((exclude) => path2.startsWith(exclude));
4662
6034
  }
4663
- function isBuiltinModule(path) {
4664
- return import_node_module2.builtinModules.includes(path.replace("node:", ""));
6035
+ function isBuiltinModule(path2) {
6036
+ return import_node_module2.builtinModules.includes(path2.replace("node:", ""));
4665
6037
  }
4666
6038
  function packageNameForImportPath(importPath) {
4667
6039
  if (importPath.startsWith("@")) {
@@ -4683,10 +6055,10 @@ function resolvePackageInfoSync(importPath, resolveDir) {
4683
6055
  try {
4684
6056
  const resolvedPath = require2.resolve(importPath, { paths: [resolveDir] });
4685
6057
  const packageName = packageNameForImportPath(importPath);
4686
- let root = (0, import_node_path.dirname)(resolvedPath);
6058
+ let root = (0, import_node_path2.dirname)(resolvedPath);
4687
6059
  let packageJsonPath = null;
4688
6060
  while (true) {
4689
- const candidate = (0, import_node_path.join)(root, "package.json");
6061
+ const candidate = (0, import_node_path2.join)(root, "package.json");
4690
6062
  if ((0, import_node_fs.existsSync)(candidate)) {
4691
6063
  const candidatePackageJson = readPackageJson(candidate);
4692
6064
  if (candidatePackageJson.name === packageName) {
@@ -4694,14 +6066,14 @@ function resolvePackageInfoSync(importPath, resolveDir) {
4694
6066
  break;
4695
6067
  }
4696
6068
  }
4697
- const parent = (0, import_node_path.dirname)(root);
6069
+ const parent = (0, import_node_path2.dirname)(root);
4698
6070
  if (parent === root) break;
4699
6071
  root = parent;
4700
6072
  }
4701
6073
  if (!packageJsonPath) return null;
4702
6074
  const packageJson = readPackageJson(packageJsonPath);
4703
6075
  if (!packageJson.name || !packageJson.version) return null;
4704
- root = (0, import_node_path.dirname)(packageJsonPath);
6076
+ root = (0, import_node_path2.dirname)(packageJsonPath);
4705
6077
  return {
4706
6078
  name: packageJson.name,
4707
6079
  version: packageJson.version,
@@ -4715,9 +6087,9 @@ function resolvePackageInfoSync(importPath, resolveDir) {
4715
6087
  }
4716
6088
  function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
4717
6089
  const packageName = packageNameForImportPath(importPath);
4718
- let root = (0, import_node_path.dirname)(resolvedPath);
6090
+ let root = (0, import_node_path2.dirname)(resolvedPath);
4719
6091
  while (true) {
4720
- const packageJsonPath = (0, import_node_path.join)(root, "package.json");
6092
+ const packageJsonPath = (0, import_node_path2.join)(root, "package.json");
4721
6093
  if ((0, import_node_fs.existsSync)(packageJsonPath)) {
4722
6094
  const packageJson = readPackageJson(packageJsonPath);
4723
6095
  if (packageJson.name === packageName) {
@@ -4731,7 +6103,7 @@ function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
4731
6103
  };
4732
6104
  }
4733
6105
  }
4734
- const parent = (0, import_node_path.dirname)(root);
6106
+ const parent = (0, import_node_path2.dirname)(root);
4735
6107
  if (parent === root) return null;
4736
6108
  root = parent;
4737
6109
  }
@@ -4746,7 +6118,7 @@ function hasNativeHints(info) {
4746
6118
  function shouldAutoExternalize(info) {
4747
6119
  if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
4748
6120
  if (hasNativeHints(info)) return true;
4749
- if ((0, import_node_fs.existsSync)((0, import_node_path.join)(info.root, "binding.gyp"))) return true;
6121
+ if ((0, import_node_fs.existsSync)((0, import_node_path2.join)(info.root, "binding.gyp"))) return true;
4750
6122
  return false;
4751
6123
  }
4752
6124
  function normalizeList(value) {
@@ -4937,6 +6309,24 @@ async function connectProviderSandboxHandle(options) {
4937
6309
  });
4938
6310
  return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
4939
6311
  }
6312
+ async function destroyProviderSandbox(options) {
6313
+ if (options.provider === "modal") {
6314
+ validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
6315
+ return ModalSandboxHandle.destroyById(options, (message) => new DeploymentError(message));
6316
+ }
6317
+ if (options.provider === "daytona") {
6318
+ const { Daytona, DaytonaNotFoundError } = await getDaytona();
6319
+ const daytona = new Daytona({ apiKey: providerApiKey("daytona", options.apiKey) });
6320
+ try {
6321
+ await (await daytona.get(options.sandboxId)).delete(Math.ceil(SANDBOX_COMMAND_TIMEOUT_MS2 / 1e3), true);
6322
+ } catch (error) {
6323
+ if (!(error instanceof DaytonaNotFoundError)) throw error;
6324
+ }
6325
+ return;
6326
+ }
6327
+ const { Sandbox } = await getE2b();
6328
+ await Sandbox.kill(options.sandboxId, { apiKey: providerApiKey("e2b", options.apiKey) });
6329
+ }
4940
6330
  var SandboxClient = class _SandboxClient {
4941
6331
  constructor(handle) {
4942
6332
  this.handle = handle;
@@ -4964,17 +6354,17 @@ var SandboxClient = class _SandboxClient {
4964
6354
  outputJson: this.handle.paths.outputJson
4965
6355
  };
4966
6356
  }
4967
- async makeDir(path) {
4968
- await this.handle.makeDir(path);
6357
+ async makeDir(path2) {
6358
+ await this.handle.makeDir(path2);
4969
6359
  }
4970
- async writeFile(path, content) {
4971
- await this.handle.writeFile(path, content);
6360
+ async writeFile(path2, content) {
6361
+ await this.handle.writeFile(path2, content);
4972
6362
  }
4973
- async readFile(path) {
4974
- return this.handle.readFile(path);
6363
+ async readFile(path2) {
6364
+ return this.handle.readFile(path2);
4975
6365
  }
4976
- async readFileBytes(path) {
4977
- return this.handle.readFileBytes(path);
6366
+ async readFileBytes(path2) {
6367
+ return this.handle.readFileBytes(path2);
4978
6368
  }
4979
6369
  async runCommand(command, options) {
4980
6370
  return this.handle.runCommand(command, options);
@@ -5040,6 +6430,22 @@ var SandboxClient = class _SandboxClient {
5040
6430
  }
5041
6431
  await this.handle.setTimeout(timeoutMs);
5042
6432
  }
6433
+ /**
6434
+ * Where to reach an HTTP server the sandbox runs on `port`, with the provider's auth: send
6435
+ * `headers` with every request and add `query` to every URL.
6436
+ */
6437
+ async getServerEndpoint(port) {
6438
+ if (!this.handle.getServerEndpoint) {
6439
+ throw new ConfigurationError(`Sandbox provider "${this.provider}" does not expose server ports.`);
6440
+ }
6441
+ const { url, trafficToken } = await this.handle.getServerEndpoint(port);
6442
+ const descriptor = { provider: this.provider, trafficToken };
6443
+ return {
6444
+ url: url.replace(/\/+$/u, ""),
6445
+ headers: trafficTokenHeaders(descriptor),
6446
+ query: this.provider === "daytona" && trafficToken ? { DAYTONA_SANDBOX_AUTH_KEY: trafficToken } : {}
6447
+ };
6448
+ }
5043
6449
  async kill() {
5044
6450
  await this.handle.destroy();
5045
6451
  }
@@ -5054,7 +6460,7 @@ function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
5054
6460
  if (rawPath.startsWith("webpack-internal:")) {
5055
6461
  const afterScheme = rawPath.replace(/^webpack-internal:\/+/, "");
5056
6462
  const afterLayer = afterScheme.replace(/^\([^)]+\)\//, "");
5057
- const resolved = (0, import_node_path.resolve)(cwd, afterLayer);
6463
+ const resolved = (0, import_node_path2.resolve)(cwd, afterLayer);
5058
6464
  return (0, import_node_fs.existsSync)(resolved) ? resolved : null;
5059
6465
  }
5060
6466
  return rawPath;
@@ -5104,7 +6510,7 @@ function resolveSourceFile(sourceFile) {
5104
6510
  if (!normalized) {
5105
6511
  throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
5106
6512
  }
5107
- const resolved = (0, import_node_path.resolve)(normalized);
6513
+ const resolved = (0, import_node_path2.resolve)(normalized);
5108
6514
  if (isFrameworkBuildOutputPath(resolved)) {
5109
6515
  throw frameworkBuildOutputError(resolved);
5110
6516
  }
@@ -5139,7 +6545,7 @@ function localPathStats(localPath, upload, isSourceRoot = false) {
5139
6545
  }
5140
6546
  }
5141
6547
  function readConfiguredLocalDirectory(upload) {
5142
- const rootPath = (0, import_node_path.resolve)(process.cwd(), upload.source);
6548
+ const rootPath = (0, import_node_path2.resolve)(process.cwd(), upload.source);
5143
6549
  const rootStats = localPathStats(rootPath, upload, true);
5144
6550
  if (!rootStats.isDirectory()) {
5145
6551
  throw new ConfigurationError(`${upload.name}.source must be a directory: ${rootPath}`);
@@ -5156,7 +6562,7 @@ function readConfiguredLocalDirectory(upload) {
5156
6562
  );
5157
6563
  }
5158
6564
  for (const entry of entries) {
5159
- const localPath = (0, import_node_path.join)(currentPath, entry);
6565
+ const localPath = (0, import_node_path2.join)(currentPath, entry);
5160
6566
  const stats = localPathStats(localPath, upload);
5161
6567
  if (stats.isDirectory()) {
5162
6568
  walk(localPath);
@@ -5167,8 +6573,8 @@ function readConfiguredLocalDirectory(upload) {
5167
6573
  `${upload.name} source tree contains an unsupported filesystem entry: ${localPath}`
5168
6574
  );
5169
6575
  }
5170
- const relativePath = (0, import_node_path.relative)(rootPath, localPath).split(import_node_path.sep).join("/");
5171
- const targetPath = import_node_path.posix.join(destination, relativePath);
6576
+ const relativePath = (0, import_node_path2.relative)(rootPath, localPath).split(import_node_path2.sep).join("/");
6577
+ const targetPath = import_node_path2.posix.join(destination, relativePath);
5172
6578
  let content;
5173
6579
  try {
5174
6580
  content = (0, import_node_fs.readFileSync)(localPath);
@@ -5218,7 +6624,7 @@ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
5218
6624
  }
5219
6625
  }
5220
6626
  for (const file of filesByTarget.values()) {
5221
- let parent = import_node_path.posix.dirname(file.targetPath);
6627
+ let parent = import_node_path2.posix.dirname(file.targetPath);
5222
6628
  while (parent !== ".") {
5223
6629
  const parentFile = filesByTarget.get(parent);
5224
6630
  if (parentFile) {
@@ -5227,7 +6633,7 @@ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
5227
6633
  );
5228
6634
  }
5229
6635
  requiredDirectories.add(parent);
5230
- parent = import_node_path.posix.dirname(parent);
6636
+ parent = import_node_path2.posix.dirname(parent);
5231
6637
  }
5232
6638
  }
5233
6639
  const directories = [...requiredDirectories].sort((left, right) => {
@@ -5239,7 +6645,7 @@ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
5239
6645
  );
5240
6646
  return { directories, files };
5241
6647
  }
5242
- var Agent = class {
6648
+ var LegacyBundledAgent = class {
5243
6649
  sandbox;
5244
6650
  provider;
5245
6651
  template;
@@ -5505,7 +6911,7 @@ var Agent = class {
5505
6911
  *
5506
6912
  * @example
5507
6913
  * ```typescript
5508
- * const agent = new Agent({ ... });
6914
+ * const agent = new LegacyBundledAgent({ ... });
5509
6915
  * const sandboxId = await agent.deploy();
5510
6916
  * console.log(`Deployed to sandbox: ${sandboxId}`);
5511
6917
  *
@@ -5560,7 +6966,7 @@ var require = __neckbeard_createRequire(import.meta.url);
5560
6966
  }));
5561
6967
  build.onLoad({ filter: /.*/, namespace: "agent-shim" }, () => ({
5562
6968
  contents: `
5563
- export class Agent {
6969
+ export class LegacyBundledAgent {
5564
6970
  constructor(config) {
5565
6971
  this.inputSchema = config.inputSchema;
5566
6972
  this.outputSchema = config.outputSchema;
@@ -5666,14 +7072,21 @@ var require = __neckbeard_createRequire(import.meta.url);
5666
7072
  }
5667
7073
  }
5668
7074
  }
5669
- for (const directory of localDirectoryUploads.directories) {
5670
- await sandbox.makeDir(import_node_path.posix.join(paths.agentDir, directory));
5671
- }
5672
- for (const file of localDirectoryUploads.files) {
5673
- await sandbox.writeFile(
5674
- import_node_path.posix.join(paths.agentDir, file.targetPath),
5675
- file.content
7075
+ if (localDirectoryUploads.directories.length > 0 || localDirectoryUploads.files.length > 0) {
7076
+ const archivePath = import_node_path2.posix.join(paths.agentDir, `.neckbeard-local-directories-${(0, import_node_crypto4.randomUUID)()}.tar.gz`);
7077
+ await sandbox.writeFile(archivePath, await createTarGz([
7078
+ ...localDirectoryUploads.directories.map((directory) => ({ path: directory })),
7079
+ ...localDirectoryUploads.files.map((file) => ({ path: file.targetPath, content: file.content }))
7080
+ ]));
7081
+ const extractResult = await sandbox.runCommand(
7082
+ `tar -xzf ${shellQuote(archivePath)} --no-same-owner -C ${shellQuote(paths.agentDir)} && rm -f ${shellQuote(archivePath)}`,
7083
+ { timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2 }
5676
7084
  );
7085
+ if (extractResult.exitCode !== 0) {
7086
+ throw new DeploymentError(
7087
+ `Failed to extract local directories: ${extractResult.stderr || extractResult.stdout}`
7088
+ );
7089
+ }
5677
7090
  }
5678
7091
  await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
5679
7092
  await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
@@ -5841,18 +7254,18 @@ var require = __neckbeard_createRequire(import.meta.url);
5841
7254
  );
5842
7255
  }
5843
7256
  if (!options || typeof options !== "object") {
5844
- throw new ConfigurationError("Agent.createSession() options must be an object.");
7257
+ throw new ConfigurationError("LegacyBundledAgent.createSession() options must be an object.");
5845
7258
  }
5846
7259
  let optionsAreArray;
5847
7260
  try {
5848
7261
  optionsAreArray = Array.isArray(options);
5849
7262
  } catch {
5850
7263
  throw new ConfigurationError(
5851
- "Agent.createSession() options must have readable values."
7264
+ "LegacyBundledAgent.createSession() options must have readable values."
5852
7265
  );
5853
7266
  }
5854
7267
  if (optionsAreArray) {
5855
- throw new ConfigurationError("Agent.createSession() options must be an object.");
7268
+ throw new ConfigurationError("LegacyBundledAgent.createSession() options must be an object.");
5856
7269
  }
5857
7270
  let durability;
5858
7271
  let requestedSandboxId;
@@ -5863,22 +7276,22 @@ var require = __neckbeard_createRequire(import.meta.url);
5863
7276
  signal = options.signal;
5864
7277
  } catch {
5865
7278
  throw new ConfigurationError(
5866
- "Agent.createSession() options must have readable values."
7279
+ "LegacyBundledAgent.createSession() options must have readable values."
5867
7280
  );
5868
7281
  }
5869
7282
  if (durability !== void 0 && durability !== "attached") {
5870
7283
  throw new ConfigurationError(
5871
- "Agent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
7284
+ "LegacyBundledAgent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
5872
7285
  );
5873
7286
  }
5874
7287
  if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
5875
7288
  throw new ConfigurationError(
5876
- "Agent.createSession() sandboxId must be a non-empty string when provided."
7289
+ "LegacyBundledAgent.createSession() sandboxId must be a non-empty string when provided."
5877
7290
  );
5878
7291
  }
5879
7292
  if (signal !== void 0 && !isAbortSignal(signal)) {
5880
7293
  throw new ConfigurationError(
5881
- "Agent.createSession() signal must be an AbortSignal when provided."
7294
+ "LegacyBundledAgent.createSession() signal must be an AbortSignal when provided."
5882
7295
  );
5883
7296
  }
5884
7297
  const sandboxId = requestedSandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
@@ -5998,13 +7411,23 @@ var require = __neckbeard_createRequire(import.meta.url);
5998
7411
  Agent,
5999
7412
  ConfigurationError,
6000
7413
  DEFAULT_DEPENDENCIES,
7414
+ DefinedAgent,
6001
7415
  DeploymentError,
6002
7416
  ExecutionError,
7417
+ LegacyBundledAgent,
6003
7418
  NeckbeardError,
6004
7419
  RuntimeBusyError,
7420
+ SKILLS_DIR,
6005
7421
  SandboxClient,
7422
+ TURN_PROTOCOL_VERSION,
7423
+ TurnLostError,
6006
7424
  ValidationError,
7425
+ defineAgent,
7426
+ destroyProviderSandbox,
7427
+ getPiTurnResult,
7428
+ isDefinedAgent,
6007
7429
  normalizeStackFramePath,
6008
7430
  resolveAgentSourceFile,
7431
+ resolveImageTag,
6009
7432
  withNeckbeardNextConfig
6010
7433
  });