agent-neckbeard 1.1.27 → 1.1.29

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,21 +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");
263
- var import_node_crypto3 = require("crypto");
280
+ var import_node_path2 = require("path");
281
+ var import_node_crypto4 = require("crypto");
264
282
  var import_node_module2 = require("module");
265
283
  init_protocol();
266
284
 
@@ -555,11 +573,11 @@ function writeString(header2, value, offset, length) {
555
573
  function writeOctal(header2, value, offset, length) {
556
574
  header2.write(`${value.toString(8).padStart(length - 1, "0")}\0`, offset, length, "ascii");
557
575
  }
558
- function splitUstarPath(path) {
559
- if (import_node_buffer.Buffer.byteLength(path) <= 100) return { name: path, prefix: "" };
560
- for (let index = path.indexOf("/"); index !== -1; index = path.indexOf("/", index + 1)) {
561
- const prefix = path.slice(0, index);
562
- const name = path.slice(index + 1);
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);
563
581
  if (import_node_buffer.Buffer.byteLength(prefix) <= 155 && import_node_buffer.Buffer.byteLength(name) <= 100 && name) {
564
582
  return { name, prefix };
565
583
  }
@@ -590,8 +608,8 @@ function header(options) {
590
608
  function padding(size) {
591
609
  return import_node_buffer.Buffer.alloc((BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE);
592
610
  }
593
- function paxPathRecord(path) {
594
- const body = ` path=${path}
611
+ function paxPathRecord(path2) {
612
+ const body = ` path=${path2}
595
613
  `;
596
614
  let length = import_node_buffer.Buffer.byteLength(body);
597
615
  while (String(length).length + import_node_buffer.Buffer.byteLength(body) !== length) {
@@ -603,18 +621,18 @@ async function createTarGz(entries, mtime = Math.floor(Date.now() / 1e3)) {
603
621
  const chunks = [];
604
622
  for (const entry of entries) {
605
623
  const isDirectory = entry.content === void 0;
606
- const path = isDirectory ? `${entry.path.replace(/\/+$/u, "")}/` : entry.path;
624
+ const path2 = isDirectory ? `${entry.path.replace(/\/+$/u, "")}/` : entry.path;
607
625
  const size = entry.content?.byteLength ?? 0;
608
626
  const type = isDirectory ? "5" : "0";
609
627
  const mode = isDirectory ? 493 : 420;
610
- const split = splitUstarPath(path);
628
+ const split = splitUstarPath(path2);
611
629
  if (split) {
612
630
  chunks.push(header({ ...split, mode, size, mtime, type }));
613
631
  } else {
614
- const record = paxPathRecord(path);
632
+ const record = paxPathRecord(path2);
615
633
  chunks.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
616
634
  chunks.push(record, padding(record.byteLength));
617
- chunks.push(header({ name: path.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
635
+ chunks.push(header({ name: path2.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
618
636
  }
619
637
  if (entry.content) {
620
638
  chunks.push(import_node_buffer.Buffer.from(entry.content.buffer, entry.content.byteOffset, entry.content.byteLength));
@@ -1339,8 +1357,8 @@ function decisionFunctions(paths) {
1339
1357
  "}"
1340
1358
  ];
1341
1359
  }
1342
- function exactLifecycleMarkerFunction(functionName, variablePrefix, path, expectation) {
1343
- const quotedPath = shellQuote(path);
1360
+ function exactLifecycleMarkerFunction(functionName, variablePrefix, path2, expectation) {
1361
+ const quotedPath = shellQuote(path2);
1344
1362
  const missingMarker = expectation.kind === "populated" ? [
1345
1363
  ` if [ ! -e ${quotedPath} ] && [ ! -L ${quotedPath} ]; then return 1; fi`
1346
1364
  ] : [];
@@ -1577,25 +1595,25 @@ function buildLegacyDetachedStopCommand(pid, startTicks, providerName) {
1577
1595
  })
1578
1596
  ].join("\n");
1579
1597
  }
1580
- function atomicFile(partialPath, path, parentDirectory, write) {
1598
+ function atomicFile(partialPath, path2, parentDirectory, write) {
1581
1599
  return [
1582
1600
  `${write} || exit 1`,
1583
1601
  `sync -f ${shellQuote(partialPath)} || exit 1`,
1584
- `mv -f ${shellQuote(partialPath)} ${shellQuote(path)} || exit 1`,
1602
+ `mv -f ${shellQuote(partialPath)} ${shellQuote(path2)} || exit 1`,
1585
1603
  `sync -f ${shellQuote(parentDirectory)} || exit 1`
1586
1604
  ];
1587
1605
  }
1588
- function secureDirectory(path, create) {
1606
+ function secureDirectory(path2, create) {
1589
1607
  return [
1590
1608
  ...create ? [
1591
- `if [ ! -e ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ]; then`,
1592
- ` mkdir ${shellQuote(path)} 2>/dev/null || true`,
1609
+ `if [ ! -e ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ]; then`,
1610
+ ` mkdir ${shellQuote(path2)} 2>/dev/null || true`,
1593
1611
  "fi"
1594
1612
  ] : [],
1595
- `[ -d ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ] || exit 1`,
1596
- `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`,
1597
1615
  '[ "$directory_owner" = "$(id -u)" ] || exit 1',
1598
- `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`,
1599
1617
  '[ "$directory_mode" = 700 ] || exit 1'
1600
1618
  ];
1601
1619
  }
@@ -1605,10 +1623,10 @@ function secureDetachedRoot() {
1605
1623
  function secureLaunchDirectory(paths, create) {
1606
1624
  return secureDirectory(paths.directory, create);
1607
1625
  }
1608
- function assertSafeRegularFile(path) {
1626
+ function assertSafeRegularFile(path2) {
1609
1627
  return [
1610
- `[ -e ${shellQuote(path)} ] || return 1`,
1611
- `[ -f ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ] || exit 1`
1628
+ `[ -e ${shellQuote(path2)} ] || return 1`,
1629
+ `[ -f ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ] || exit 1`
1612
1630
  ];
1613
1631
  }
1614
1632
  function publishDecision(paths, action, partialPath) {
@@ -1665,8 +1683,8 @@ function releasedAdoptionOutcome(paths, descriptorKey, serializeGenerationChange
1665
1683
  ];
1666
1684
  }
1667
1685
  function renderShellLockAssertion(options) {
1668
- const { functionName, variablePrefix, path, descriptorFd } = options;
1669
- const pathExpression = shellQuote(path);
1686
+ const { functionName, variablePrefix, path: path2, descriptorFd } = options;
1687
+ const pathExpression = shellQuote(path2);
1670
1688
  const descriptorPathExpression = `/proc/self/fd/${descriptorFd}`;
1671
1689
  const descriptorChecks = [
1672
1690
  `[ -f ${descriptorPathExpression} ] || return 1`,
@@ -1816,23 +1834,23 @@ function cleanLifecycleShell(script, environmentMode) {
1816
1834
  delimiter
1817
1835
  ].join("\n");
1818
1836
  }
1819
- function previousLogPath(path) {
1820
- return `${path}.previous`;
1837
+ function previousLogPath(path2) {
1838
+ return `${path2}.previous`;
1821
1839
  }
1822
- function logPipePath(path) {
1823
- return `${path}.pipe`;
1840
+ function logPipePath(path2) {
1841
+ return `${path2}.pipe`;
1824
1842
  }
1825
- function logSnapshotPath(path) {
1826
- return `${path}.snapshot`;
1843
+ function logSnapshotPath(path2) {
1844
+ return `${path2}.snapshot`;
1827
1845
  }
1828
- function logSnapshotStagingPath(path) {
1829
- return `${logSnapshotPath(path)}.partial`;
1846
+ function logSnapshotStagingPath(path2) {
1847
+ return `${logSnapshotPath(path2)}.partial`;
1830
1848
  }
1831
- function legacyLogSnapshotLockPath(path) {
1832
- return `${logSnapshotPath(path)}.lock`;
1849
+ function legacyLogSnapshotLockPath(path2) {
1850
+ return `${logSnapshotPath(path2)}.lock`;
1833
1851
  }
1834
- function logChunkPath(path) {
1835
- return `${path}.chunk`;
1852
+ function logChunkPath(path2) {
1853
+ return `${path2}.chunk`;
1836
1854
  }
1837
1855
  function boundedLogProgram() {
1838
1856
  return [
@@ -2678,9 +2696,9 @@ function buildReadLegacyDetachedLogsCommand(nonce) {
2678
2696
  ].join("\n");
2679
2697
  }
2680
2698
  function readLogFiles(stdout, stderr, previous, beforePrint = []) {
2681
- const optionalPrevious = (path) => [
2682
- `if [ -e ${shellQuote(path)} ] || [ -L ${shellQuote(path)} ]; then`,
2683
- ...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}`),
2684
2702
  "fi"
2685
2703
  ];
2686
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))}`;
@@ -2922,10 +2940,10 @@ async function executeRawDaytonaCommand(sandbox, command, options) {
2922
2940
  daytonaTimeoutSeconds(options.timeoutMs)
2923
2941
  );
2924
2942
  }
2925
- async function makeDaytonaDirectory(sandbox, path, options) {
2943
+ async function makeDaytonaDirectory(sandbox, path2, options) {
2926
2944
  return executeRawDaytonaCommand(
2927
2945
  sandbox,
2928
- `mkdir -p -- ${shellQuote(path)}`,
2946
+ `mkdir -p -- ${shellQuote(path2)}`,
2929
2947
  options
2930
2948
  );
2931
2949
  }
@@ -2935,11 +2953,11 @@ function daytonaUploadContent(content) {
2935
2953
  if (content instanceof Uint8Array) return import_node_buffer3.Buffer.from(content);
2936
2954
  return import_node_buffer3.Buffer.from(content);
2937
2955
  }
2938
- async function uploadDaytonaFile(sandbox, path, content, options) {
2956
+ async function uploadDaytonaFile(sandbox, path2, content, options) {
2939
2957
  await options.beforeIo?.();
2940
2958
  await sandbox.fs.uploadFile(
2941
2959
  daytonaUploadContent(content),
2942
- path,
2960
+ path2,
2943
2961
  daytonaTimeoutSeconds(options.timeoutMs)
2944
2962
  );
2945
2963
  }
@@ -3072,29 +3090,29 @@ var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
3072
3090
  get id() {
3073
3091
  return this.sandbox.id;
3074
3092
  }
3075
- async makeDir(path) {
3076
- const result = await makeDaytonaDirectory(this.sandbox, path, {
3093
+ async makeDir(path2) {
3094
+ const result = await makeDaytonaDirectory(this.sandbox, path2, {
3077
3095
  timeoutMs: QUICK_COMMAND_TIMEOUT_MS
3078
3096
  });
3079
3097
  if (result.exitCode !== 0) {
3080
- throw this.failure(result.result || `Failed to create directory ${path}`);
3098
+ throw this.failure(result.result || `Failed to create directory ${path2}`);
3081
3099
  }
3082
3100
  }
3083
- writeFile(path, content) {
3084
- return uploadDaytonaFile(this.sandbox, path, content, {
3101
+ writeFile(path2, content) {
3102
+ return uploadDaytonaFile(this.sandbox, path2, content, {
3085
3103
  timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
3086
3104
  });
3087
3105
  }
3088
- async readFile(path) {
3106
+ async readFile(path2) {
3089
3107
  const content = await this.sandbox.fs.downloadFile(
3090
- path,
3108
+ path2,
3091
3109
  daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
3092
3110
  );
3093
3111
  return content.toString("utf8");
3094
3112
  }
3095
- async readFileBytes(path) {
3113
+ async readFileBytes(path2) {
3096
3114
  const content = await this.sandbox.fs.downloadFile(
3097
- path,
3115
+ path2,
3098
3116
  daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
3099
3117
  );
3100
3118
  return new Uint8Array(content);
@@ -3335,17 +3353,17 @@ var E2bSandboxHandle = class {
3335
3353
  get id() {
3336
3354
  return this.sandbox.sandboxId;
3337
3355
  }
3338
- async makeDir(path) {
3339
- await this.sandbox.files.makeDir(path);
3356
+ async makeDir(path2) {
3357
+ await this.sandbox.files.makeDir(path2);
3340
3358
  }
3341
- writeFile(path, content) {
3342
- 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);
3343
3361
  }
3344
- readFile(path) {
3345
- return this.sandbox.files.read(path, { format: "text" });
3362
+ readFile(path2) {
3363
+ return this.sandbox.files.read(path2, { format: "text" });
3346
3364
  }
3347
- readFileBytes(path) {
3348
- return this.sandbox.files.read(path, { format: "bytes" });
3365
+ readFileBytes(path2) {
3366
+ return this.sandbox.files.read(path2, { format: "bytes" });
3349
3367
  }
3350
3368
  runCommand(cmd, options) {
3351
3369
  return runE2bCommand(this.sandbox, cmd, options);
@@ -3460,15 +3478,18 @@ function modalNetworkOptions(options) {
3460
3478
  };
3461
3479
  }
3462
3480
  function validateModalOptions(options, mode, failure) {
3463
- const { networkBlockAll, networkAllowList, domainAllowList, regions, ...rest } = options;
3481
+ const { networkBlockAll, networkAllowList, domainAllowList, regions, command, ...rest } = options;
3464
3482
  validateProviderOptions("Modal", mode === "connect" ? options : rest, ["environment", ...mode === "connect" ? ["sandboxId", "tokenId", "tokenSecret"] : [
3465
3483
  "template",
3466
3484
  "appName",
3467
3485
  "timeoutMs",
3468
3486
  "cpu",
3469
3487
  "memoryMiB",
3470
- ...mode === "create" ? ["tokenId", "tokenSecret", "envs"] : []
3488
+ ...mode === "create" ? ["tokenId", "tokenSecret", "envs", "registrySecret"] : []
3471
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
+ }
3472
3493
  if (regions !== void 0 && (!Array.isArray(regions) || regions.length === 0 || regions.some((region) => typeof region !== "string" || !/^[a-z0-9-]+$/u.test(region)))) {
3473
3494
  throw failure('Modal regions must be a non-empty array of region names such as "us" or "us-east".');
3474
3495
  }
@@ -3562,7 +3583,9 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3562
3583
  try {
3563
3584
  const app = await client.apps.fromName(options.appName ?? "agent-neckbeard", { createIfMissing: true });
3564
3585
  const network = modalNetworkOptions(options);
3565
- const image = client.images.fromRegistry(options.template ?? MODAL_DEFAULT_TEMPLATE).dockerfileCommands([
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([
3566
3589
  "USER root",
3567
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/*",
3568
3591
  // The runtime starts with a fixed PATH, so images with Node elsewhere (say nvm) need links.
@@ -3577,7 +3600,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3577
3600
  timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
3578
3601
  cpu: options.cpu,
3579
3602
  memoryMiB: options.memoryMiB,
3580
- workdir: "/root",
3603
+ ...options.command ? { command: options.command } : { workdir: "/root" },
3581
3604
  env: Object.fromEntries(Object.entries(options.envs ?? {}).filter(
3582
3605
  (entry) => entry[1] !== void 0
3583
3606
  ))
@@ -3588,6 +3611,15 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3588
3611
  sandbox?.detach();
3589
3612
  }
3590
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
+ }
3591
3623
  static async connect(options, failure) {
3592
3624
  const client = await sharedClient({
3593
3625
  tokenId: options.tokenId,
@@ -3624,17 +3656,17 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3624
3656
  sandbox?.detach();
3625
3657
  }
3626
3658
  }
3627
- makeDir(path) {
3628
- return this.use((sandbox) => sandbox.filesystem.makeDirectory(path));
3659
+ makeDir(path2) {
3660
+ return this.use((sandbox) => sandbox.filesystem.makeDirectory(path2));
3629
3661
  }
3630
- writeFile(path, content) {
3631
- 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));
3632
3664
  }
3633
- readFile(path) {
3634
- return this.use((sandbox) => sandbox.filesystem.readText(path));
3665
+ readFile(path2) {
3666
+ return this.use((sandbox) => sandbox.filesystem.readText(path2));
3635
3667
  }
3636
- readFileBytes(path) {
3637
- return this.use((sandbox) => sandbox.filesystem.readBytes(path));
3668
+ readFileBytes(path2) {
3669
+ return this.use((sandbox) => sandbox.filesystem.readBytes(path2));
3638
3670
  }
3639
3671
  runCommand(command, options) {
3640
3672
  try {
@@ -3707,6 +3739,1375 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3707
3739
  }
3708
3740
  };
3709
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 = 3;
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") && (record.undeliveredSteerIds === void 0 || Array.isArray(record.undeliveredSteerIds) && record.undeliveredSteerIds.every((id) => typeof id === "string"))) {
3768
+ return {
3769
+ seq,
3770
+ type: "end",
3771
+ outcome: record.outcome,
3772
+ ...record.error === void 0 ? {} : { error: record.error },
3773
+ ...record.undeliveredSteerIds === void 0 ? {} : { undeliveredSteerIds: record.undeliveredSteerIds }
3774
+ };
3775
+ }
3776
+ throw new Error("Turn record has an unknown shape.");
3777
+ }
3778
+ function parseTurnHealth(value) {
3779
+ if (!isRecord2(value)) throw new Error("Health response must be an object.");
3780
+ const { ok, protocolVersion, busy, turnId } = value;
3781
+ if (ok !== true || typeof protocolVersion !== "number" || typeof busy !== "boolean" || turnId !== null && typeof turnId !== "string") {
3782
+ throw new Error("Health response is not { ok: true, protocolVersion, busy, turnId }.");
3783
+ }
3784
+ return { ok, protocolVersion, busy, turnId };
3785
+ }
3786
+ function readAssistantMessageEnd(event) {
3787
+ if (!isRecord2(event) || event.type !== "message_end" || !isRecord2(event.message)) return void 0;
3788
+ const { role, content, stopReason, errorMessage: errorMessage2 } = event.message;
3789
+ if (role !== "assistant") return void 0;
3790
+ const text = (Array.isArray(content) ? content : []).flatMap((block) => isRecord2(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n").trim();
3791
+ return {
3792
+ text,
3793
+ stopReason: typeof stopReason === "string" ? stopReason : void 0,
3794
+ errorMessage: typeof errorMessage2 === "string" ? errorMessage2 : void 0
3795
+ };
3796
+ }
3797
+ function getPiTurnResult(records) {
3798
+ let end;
3799
+ let message;
3800
+ for (const record of records) {
3801
+ if (record.type === "end") {
3802
+ end = record;
3803
+ continue;
3804
+ }
3805
+ message = readAssistantMessageEnd(record.event) ?? message;
3806
+ }
3807
+ if (!end) return { completed: false, error: "The agent turn has not ended." };
3808
+ if (end.outcome !== "completed") {
3809
+ return { completed: false, error: end.error ?? `The agent turn was ${end.outcome}.` };
3810
+ }
3811
+ if (!message) return { completed: false, error: "The agent did not reply." };
3812
+ if (message.stopReason !== "stop") {
3813
+ return {
3814
+ completed: false,
3815
+ error: message.errorMessage?.trim() || `The agent stopped with ${message.stopReason ?? "no reason"}.`
3816
+ };
3817
+ }
3818
+ return { completed: true, text: message.text || null };
3819
+ }
3820
+
3821
+ // src/agent.ts
3822
+ var DEFAULT_COMMAND = ["node", "/app/agent.mjs"];
3823
+ var DEFAULT_PORT = 8080;
3824
+ var DEFAULT_START_TIMEOUT_MS = 12e4;
3825
+ var DEFAULT_PREPARE_TIMEOUT_MS = 30 * 6e4;
3826
+ var DEFAULT_RECONNECT_TIMEOUT_MS = 12e4;
3827
+ var HEALTH_POLL_INTERVAL_MS = 500;
3828
+ var RECONNECT_MIN_DELAY_MS = 250;
3829
+ var RECONNECT_MAX_DELAY_MS = 5e3;
3830
+ var REQUEST_TIMEOUT_MS = 3e4;
3831
+ var ARTIFACT_PREFIX = "nb-";
3832
+ function filterDefined(envs) {
3833
+ return Object.fromEntries(Object.entries(envs ?? {}).filter(
3834
+ (entry) => entry[1] !== void 0
3835
+ ));
3836
+ }
3837
+ function delay2(ms, signal) {
3838
+ return new Promise((resolve2, reject) => {
3839
+ if (signal?.aborted) return reject(abortError(signal));
3840
+ const onAbort = () => {
3841
+ clearTimeout(timer);
3842
+ reject(abortError(signal));
3843
+ };
3844
+ const timer = setTimeout(() => {
3845
+ signal?.removeEventListener("abort", onAbort);
3846
+ resolve2();
3847
+ }, ms);
3848
+ signal?.addEventListener("abort", onAbort, { once: true });
3849
+ });
3850
+ }
3851
+ function untilDeadline(deadline, signal) {
3852
+ const timeout = AbortSignal.timeout(Math.max(0, deadline - Date.now()));
3853
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
3854
+ }
3855
+ function untilAborted(operation, signal) {
3856
+ if (signal?.aborted) return Promise.reject(abortError(signal));
3857
+ return settleOperation(operation, signal ? { abort: { signal, createError: () => abortError(signal) } } : {});
3858
+ }
3859
+ function abortError(signal) {
3860
+ if (signal.reason instanceof Error) return signal.reason;
3861
+ const error = new Error("Operation aborted.");
3862
+ error.name = "AbortError";
3863
+ return error;
3864
+ }
3865
+ async function* textChunks(body, onChunk) {
3866
+ const decoder = new TextDecoder();
3867
+ const reader = body.getReader();
3868
+ try {
3869
+ while (true) {
3870
+ const { done, value } = await reader.read();
3871
+ if (done) break;
3872
+ onChunk();
3873
+ yield decoder.decode(value, { stream: true });
3874
+ }
3875
+ } finally {
3876
+ await reader.cancel().catch(() => void 0);
3877
+ reader.releaseLock();
3878
+ }
3879
+ }
3880
+ var EndpointRejectedError = class extends Error {
3881
+ };
3882
+ var Agent = class {
3883
+ constructor(options) {
3884
+ this.options = options;
3885
+ if (!options || typeof options !== "object") throw new ConfigurationError("Agent options must be an object.");
3886
+ if (typeof options.name !== "string" || !/^[a-z0-9]+(-[a-z0-9]+)*$/u.test(options.name)) {
3887
+ throw new ConfigurationError("Agent name must be lowercase letters, digits, and single dashes.");
3888
+ }
3889
+ if (typeof options.image !== "string" || !options.image.trim() || /\s/u.test(options.image)) {
3890
+ throw new ConfigurationError("Agent image must be a registry image reference.");
3891
+ }
3892
+ const provider = options.sandbox?.provider;
3893
+ if (provider !== "modal" && provider !== "daytona" && provider !== "e2b") {
3894
+ throw new ConfigurationError('Agent sandbox.provider must be "modal", "daytona", or "e2b".');
3895
+ }
3896
+ const command = options.command ?? DEFAULT_COMMAND;
3897
+ if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string" || !part)) {
3898
+ throw new ConfigurationError("Agent command must be a non-empty array of non-empty strings.");
3899
+ }
3900
+ const port = options.port ?? DEFAULT_PORT;
3901
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
3902
+ throw new ConfigurationError("Agent port must be between 1 and 65535.");
3903
+ }
3904
+ this.name = options.name;
3905
+ this.image = options.image;
3906
+ this.command = [...command];
3907
+ this.port = port;
3908
+ }
3909
+ name;
3910
+ image;
3911
+ command;
3912
+ port;
3913
+ endpoints = /* @__PURE__ */ new Map();
3914
+ preparing;
3915
+ get provider() {
3916
+ return this.options.sandbox.provider;
3917
+ }
3918
+ /**
3919
+ * Name of the Daytona snapshot or E2B template for this image, command, and resources. Equal
3920
+ * inputs share one, so preparing again is a lookup.
3921
+ */
3922
+ get artifactName() {
3923
+ const { sandbox } = this.options;
3924
+ const resources = sandbox.provider === "daytona" ? sandbox.resources : sandbox.provider === "e2b" ? { cpuCount: sandbox.cpuCount, memoryMB: sandbox.memoryMB } : void 0;
3925
+ 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);
3926
+ return `${ARTIFACT_PREFIX}${this.name}-${hash2}`;
3927
+ }
3928
+ /**
3929
+ * Creates the Daytona snapshot or E2B template for the image if it is missing and waits until
3930
+ * it can start sandboxes. Run it from CI after pushing the image so no sandbox waits on a
3931
+ * build. Modal pulls the image directly, so this does nothing there. `refresh` builds it again
3932
+ * even when it exists, as after pushing new contents under a tag it was built from, since its
3933
+ * name comes from the image's reference, not its contents.
3934
+ */
3935
+ prepare(options = {}) {
3936
+ const { sandbox } = this.options;
3937
+ if (sandbox.provider === "modal") return Promise.resolve();
3938
+ if (options.signal?.aborted) return Promise.reject(abortError(options.signal));
3939
+ if (!this.preparing || options.refresh) {
3940
+ const timeoutMs = this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS;
3941
+ const deadline = AbortSignal.timeout(timeoutMs);
3942
+ const steps = { signal: deadline, refresh: options.refresh ?? false, ...options.onLog ? { onLog: options.onLog } : {} };
3943
+ this.preparing = untilAborted(
3944
+ () => sandbox.provider === "daytona" ? this.prepareDaytonaSnapshot(sandbox, steps) : this.prepareE2bTemplate(sandbox, steps),
3945
+ deadline
3946
+ ).catch((error) => {
3947
+ this.preparing = void 0;
3948
+ if (deadline.aborted) throw new DeploymentError(`Preparing ${this.artifactName} took longer than ${timeoutMs}ms.`);
3949
+ throw error;
3950
+ });
3951
+ this.preparing.catch(() => void 0);
3952
+ }
3953
+ const preparing = this.preparing;
3954
+ return untilAborted(() => preparing, options.signal);
3955
+ }
3956
+ /** Starts a sandbox from the image and waits for its runtime. Returns the sandbox ID. */
3957
+ async start(options = {}) {
3958
+ await this.prepare({ ...options.signal ? { signal: options.signal } : {} });
3959
+ const envs = {
3960
+ ...filterDefined(this.options.envs),
3961
+ ...filterDefined(options.envs),
3962
+ ...options.sessionId === void 0 ? {} : { NECKBEARD_SESSION_ID: options.sessionId },
3963
+ NECKBEARD_PORT: String(this.port)
3964
+ };
3965
+ if (options.signal?.aborted) throw abortError(options.signal);
3966
+ let sandbox;
3967
+ try {
3968
+ sandbox = await this.createSandbox(envs);
3969
+ } catch (error) {
3970
+ this.preparing = void 0;
3971
+ throw error;
3972
+ }
3973
+ try {
3974
+ if (this.options.sandbox.provider === "e2b") await this.startE2bRuntime(this.options.sandbox, sandbox.id, envs);
3975
+ await this.waitForRuntime(sandbox.id, options.signal);
3976
+ return sandbox.id;
3977
+ } catch (error) {
3978
+ this.endpoints.delete(sandbox.id);
3979
+ try {
3980
+ await sandbox.destroy();
3981
+ } catch (cleanupError) {
3982
+ const startMessage = error instanceof Error ? error.message : String(error);
3983
+ const cleanupMessage = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
3984
+ throw new DeploymentError(
3985
+ `Sandbox ${sandbox.id} failed to start (${startMessage}), and deleting it failed (${cleanupMessage}); kill() it to retry.`,
3986
+ error instanceof Error ? error : void 0,
3987
+ sandbox.id
3988
+ );
3989
+ }
3990
+ throw error;
3991
+ }
3992
+ }
3993
+ /**
3994
+ * Starts a turn and streams its records until its `end` record. Starting a turn whose
3995
+ * `turnId` the runtime already has resumes it instead of running it again.
3996
+ */
3997
+ async *prompt(sandboxId, turn, options = {}) {
3998
+ const response = await this.request(sandboxId, "POST", "/turns", turn, options.signal);
3999
+ if (response.status === 409) {
4000
+ const body = await response.json().catch(() => ({}));
4001
+ throw new RuntimeBusyError(`Sandbox ${sandboxId} is running another turn (${body.turnId ?? "unknown"}).`);
4002
+ }
4003
+ if (response.status !== 200 && response.status !== 202) {
4004
+ throw new ExecutionError(`Starting turn ${turn.turnId} failed with ${response.status}: ${await response.text()}`);
4005
+ }
4006
+ await response.body?.cancel();
4007
+ yield* this.events(sandboxId, turn.turnId, options);
4008
+ }
4009
+ /**
4010
+ * Runs a Pi turn to its end and returns its final assistant text, or null when it had none.
4011
+ * Throws `ExecutionError` when the turn did not complete or its model did not stop on its own.
4012
+ * Running a turn again with the same `turnId` replays its records from the start.
4013
+ */
4014
+ async run(sandboxId, turn, options = {}) {
4015
+ const { onRecord, ...streamOptions } = options;
4016
+ const records = [];
4017
+ for await (const record of this.prompt(sandboxId, turn, streamOptions)) {
4018
+ records.push(record);
4019
+ await onRecord?.(record);
4020
+ }
4021
+ options.signal?.throwIfAborted();
4022
+ const result = getPiTurnResult(records);
4023
+ if (!result.completed) throw new ExecutionError(`Turn ${turn.turnId} did not finish: ${result.error}`);
4024
+ return result.text;
4025
+ }
4026
+ /**
4027
+ * Streams a turn's records after `options.after` until its `end` record, reconnecting when
4028
+ * the connection drops. Throws `TurnLostError` when the runtime no longer has the turn.
4029
+ */
4030
+ async *events(sandboxId, turnId, options = {}) {
4031
+ let last = options.after ?? -1;
4032
+ const reconnectTimeoutMs = options.reconnectTimeoutMs ?? DEFAULT_RECONNECT_TIMEOUT_MS;
4033
+ let failingSince;
4034
+ let attempt = 0;
4035
+ while (true) {
4036
+ let lastError;
4037
+ const stalled = new AbortController();
4038
+ let watchdog;
4039
+ const armWatchdog = () => {
4040
+ clearTimeout(watchdog);
4041
+ const budget = failingSince === void 0 ? reconnectTimeoutMs : Math.max(0, failingSince + reconnectTimeoutMs - Date.now());
4042
+ watchdog = setTimeout(() => stalled.abort(new Error(`Turn stream sent nothing for ${budget}ms.`)), budget);
4043
+ };
4044
+ armWatchdog();
4045
+ try {
4046
+ const response = await this.request(
4047
+ sandboxId,
4048
+ "GET",
4049
+ `/turns/${encodeURIComponent(turnId)}/events?after=${last}`,
4050
+ void 0,
4051
+ options.signal ? AbortSignal.any([options.signal, stalled.signal]) : stalled.signal,
4052
+ { stream: true }
4053
+ );
4054
+ if (response.status === 404) {
4055
+ await response.body?.cancel();
4056
+ throw new TurnLostError(`Sandbox ${sandboxId} has no turn ${turnId}.`);
4057
+ }
4058
+ if (!response.ok || !response.body) {
4059
+ await response.body?.cancel();
4060
+ throw new Error(`Turn stream returned ${response.status}.`);
4061
+ }
4062
+ try {
4063
+ const onChunk = () => {
4064
+ failingSince = void 0;
4065
+ armWatchdog();
4066
+ };
4067
+ for await (const frame of decodeSseStream(textChunks(response.body, onChunk))) {
4068
+ let record;
4069
+ try {
4070
+ record = parseTurnRecord(frame);
4071
+ } catch (error) {
4072
+ const message = error instanceof Error ? error.message : String(error);
4073
+ throw new ExecutionError(`Sandbox ${sandboxId} sent an invalid record for turn ${turnId}: ${message}`);
4074
+ }
4075
+ if (record.seq <= last) {
4076
+ if (record.type === "end") return;
4077
+ continue;
4078
+ }
4079
+ last = record.seq;
4080
+ failingSince = void 0;
4081
+ attempt = 0;
4082
+ clearTimeout(watchdog);
4083
+ yield record;
4084
+ armWatchdog();
4085
+ if (record.type === "end") return;
4086
+ }
4087
+ } catch (error) {
4088
+ if (error instanceof Error && error.message.startsWith("Malformed SSE data frame")) {
4089
+ throw new ExecutionError(`Sandbox ${sandboxId} sent a malformed frame for turn ${turnId}: ${error.message}`);
4090
+ }
4091
+ if (!(error instanceof IncompleteSseFrameError)) throw error;
4092
+ }
4093
+ lastError = new Error("Turn stream ended before the turn did.");
4094
+ } catch (error) {
4095
+ if (error instanceof TurnLostError || error instanceof ExecutionError) throw error;
4096
+ if (options.signal?.aborted) throw abortError(options.signal);
4097
+ if (error instanceof EndpointRejectedError) this.endpoints.delete(sandboxId);
4098
+ lastError = stalled.signal.aborted ? stalled.signal.reason : error;
4099
+ } finally {
4100
+ clearTimeout(watchdog);
4101
+ }
4102
+ failingSince ??= Date.now();
4103
+ if (Date.now() - failingSince > reconnectTimeoutMs) {
4104
+ const message = lastError instanceof Error ? lastError.message : String(lastError);
4105
+ throw new ExecutionError(`Lost the stream of turn ${turnId} for over ${reconnectTimeoutMs}ms: ${message}`);
4106
+ }
4107
+ attempt += 1;
4108
+ await delay2(Math.min(RECONNECT_MAX_DELAY_MS, RECONNECT_MIN_DELAY_MS * 2 ** (attempt - 1)), options.signal);
4109
+ }
4110
+ }
4111
+ /** Asks the runtime to stop the turn; its stream then ends with an `aborted` record. */
4112
+ async abort(sandboxId, turnId, signal) {
4113
+ const response = await this.request(sandboxId, "POST", `/turns/${encodeURIComponent(turnId)}/abort`, void 0, signal);
4114
+ await response.body?.cancel();
4115
+ if (response.status !== 202 && response.status !== 404) {
4116
+ throw new ExecutionError(`Aborting turn ${turnId} failed with ${response.status}.`);
4117
+ }
4118
+ }
4119
+ /**
4120
+ * Queues a message for a running turn, which Pi takes after its current tool calls. Resolves to
4121
+ * true once the session has queued it: it is then delivered into the turn, or named in the end
4122
+ * record's `undeliveredSteerIds`. Resolves to false when the turn can no longer take it, or the
4123
+ * runtime no longer has it, so the caller can send the message as a turn of its own. Throws when
4124
+ * queueing failed or the request did; calling again with the same `steerId` never queues it twice.
4125
+ */
4126
+ async steer(sandboxId, turnId, steer, signal) {
4127
+ const response = await this.request(sandboxId, "POST", `/turns/${encodeURIComponent(turnId)}/steer`, steer, signal);
4128
+ if (response.status === 200 || response.status === 202) {
4129
+ await response.body?.cancel();
4130
+ return true;
4131
+ }
4132
+ if (response.status === 409 || response.status === 404) {
4133
+ await response.body?.cancel();
4134
+ return false;
4135
+ }
4136
+ throw new ExecutionError(`Steering turn ${turnId} failed with ${response.status}: ${await response.text()}`);
4137
+ }
4138
+ async health(sandboxId, signal) {
4139
+ const response = await this.request(sandboxId, "GET", "/health", void 0, signal);
4140
+ if (!response.ok) throw new ExecutionError(`Health check of sandbox ${sandboxId} returned ${response.status}.`);
4141
+ return parseTurnHealth(await response.json());
4142
+ }
4143
+ /** Waits until no turn runs, for example before reading files a turn writes. */
4144
+ async waitForIdle(sandboxId, options = {}) {
4145
+ const deadline = Date.now() + (options.timeoutMs ?? 6e4);
4146
+ while (true) {
4147
+ try {
4148
+ if (!(await this.health(sandboxId, untilDeadline(deadline, options.signal))).busy) return;
4149
+ } catch (error) {
4150
+ if (options.signal?.aborted) throw error;
4151
+ }
4152
+ if (Date.now() > deadline) throw new RuntimeBusyError(`Sandbox ${sandboxId} did not become idle.`);
4153
+ await delay2(HEALTH_POLL_INTERVAL_MS, options.signal);
4154
+ }
4155
+ }
4156
+ /**
4157
+ * Deletes the sandbox without starting it. One that is already gone counts as deleted; any other
4158
+ * failure throws, so cleanup can be retried, since a Daytona sandbox need not expire on its own.
4159
+ */
4160
+ async kill(sandboxId) {
4161
+ this.endpoints.delete(sandboxId);
4162
+ const { sandbox } = this.options;
4163
+ if (sandbox.provider === "modal") {
4164
+ await destroyProviderSandbox({
4165
+ provider: "modal",
4166
+ sandboxId,
4167
+ ...sandbox.environment ? { environment: sandbox.environment } : {}
4168
+ });
4169
+ return;
4170
+ }
4171
+ await destroyProviderSandbox({ provider: sandbox.provider, sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
4172
+ }
4173
+ /** File and command access to a sandbox, for staging inputs and reading results. */
4174
+ sandbox(sandboxId) {
4175
+ const { sandbox } = this.options;
4176
+ if (sandbox.provider === "modal") {
4177
+ return SandboxClient.connect({
4178
+ provider: "modal",
4179
+ sandboxId,
4180
+ ...sandbox.environment ? { environment: sandbox.environment } : {}
4181
+ });
4182
+ }
4183
+ if (sandbox.provider === "e2b") {
4184
+ return SandboxClient.connect({
4185
+ provider: "e2b",
4186
+ sandboxId,
4187
+ ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {},
4188
+ ...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
4189
+ });
4190
+ }
4191
+ return SandboxClient.connect({ provider: "daytona", sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
4192
+ }
4193
+ /**
4194
+ * Deletes this agent's Daytona snapshots or E2B templates except the newest `keep` and the
4195
+ * current one. Returns the names it deleted.
4196
+ */
4197
+ async gc(options = {}) {
4198
+ const keep = options.keep ?? 3;
4199
+ if (!Number.isInteger(keep) || keep < 0) throw new ConfigurationError("gc keep must be a non-negative integer.");
4200
+ const { sandbox } = this.options;
4201
+ if (sandbox.provider === "modal") return [];
4202
+ const ownName = new RegExp(`^${ARTIFACT_PREFIX}${this.name}-[0-9a-f]{16}$`, "u");
4203
+ const protectedNames = /* @__PURE__ */ new Set([this.artifactName, ...options.alsoKeep ?? []]);
4204
+ const artifacts = sandbox.provider === "daytona" ? await this.listDaytonaSnapshots(sandbox, ownName) : await this.listE2bTemplates(sandbox, ownName);
4205
+ 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));
4206
+ for (const artifact of stale) await artifact.delete();
4207
+ return stale.map((artifact) => artifact.name);
4208
+ }
4209
+ createSandbox(envs) {
4210
+ const { sandbox } = this.options;
4211
+ if (sandbox.provider === "modal") {
4212
+ const { provider: _provider, ...modal } = sandbox;
4213
+ return SandboxClient.create({ provider: "modal", ...modal, template: this.image, command: this.command, envs });
4214
+ }
4215
+ if (sandbox.provider === "daytona") {
4216
+ const { resources: _resources, ...daytona } = sandbox;
4217
+ return SandboxClient.create({ ...daytona, template: this.artifactName, envs });
4218
+ }
4219
+ const { cpuCount: _cpuCount, memoryMB: _memoryMB, registry: _registry, ...e2b } = sandbox;
4220
+ return SandboxClient.create({ ...e2b, template: this.artifactName, envs, allowPublicTraffic: false });
4221
+ }
4222
+ // An E2B template's start command runs once at build time, without each sandbox's environment.
4223
+ async startE2bRuntime(sandbox, sandboxId, envs) {
4224
+ const { Sandbox } = await import("e2b");
4225
+ const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
4226
+ const e2bSandbox = await Sandbox.connect(sandboxId, {
4227
+ ...apiKey ? { apiKey } : {},
4228
+ ...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
4229
+ });
4230
+ const command = await e2bSandbox.commands.run(this.command.map(shellQuote).join(" "), { background: true, envs, timeoutMs: 0 });
4231
+ await command.disconnect();
4232
+ }
4233
+ async waitForRuntime(sandboxId, signal) {
4234
+ const timeoutMs = this.options.startTimeoutMs ?? DEFAULT_START_TIMEOUT_MS;
4235
+ const deadline = Date.now() + timeoutMs;
4236
+ let lastError;
4237
+ while (Date.now() < deadline) {
4238
+ try {
4239
+ const health = await this.health(sandboxId, untilDeadline(deadline, signal));
4240
+ if (health.protocolVersion !== TURN_PROTOCOL_VERSION) {
4241
+ throw new DeploymentError(
4242
+ `Sandbox runtime speaks protocol ${health.protocolVersion}; this host speaks ${TURN_PROTOCOL_VERSION}.`
4243
+ );
4244
+ }
4245
+ return;
4246
+ } catch (error) {
4247
+ if (error instanceof DeploymentError || signal?.aborted) throw error;
4248
+ lastError = error;
4249
+ }
4250
+ await delay2(HEALTH_POLL_INTERVAL_MS, signal);
4251
+ }
4252
+ const message = lastError instanceof Error ? lastError.message : String(lastError);
4253
+ throw new DeploymentError(`Runtime in sandbox ${sandboxId} did not answer within ${timeoutMs}ms: ${message}`);
4254
+ }
4255
+ endpoint(sandboxId) {
4256
+ let endpoint = this.endpoints.get(sandboxId);
4257
+ if (!endpoint) {
4258
+ endpoint = this.sandbox(sandboxId).then((sandbox) => sandbox.getServerEndpoint(this.port));
4259
+ endpoint.catch(() => this.endpoints.delete(sandboxId));
4260
+ this.endpoints.set(sandboxId, endpoint);
4261
+ }
4262
+ return endpoint;
4263
+ }
4264
+ async request(sandboxId, method, path2, body, signal, options = {}) {
4265
+ for (let attempt = 0; ; attempt += 1) {
4266
+ const endpoint = await untilAborted(() => this.endpoint(sandboxId), signal);
4267
+ const url = new URL(`${endpoint.url}${path2}`);
4268
+ for (const [name, value] of Object.entries(endpoint.query)) url.searchParams.set(name, value);
4269
+ const timeout = options.stream ? void 0 : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
4270
+ const signals = [signal, timeout].filter((value) => value !== void 0);
4271
+ const response = await fetch(url, {
4272
+ method,
4273
+ headers: {
4274
+ ...endpoint.headers,
4275
+ ...body === void 0 ? {} : { "content-type": "application/json" },
4276
+ ...options.stream ? { accept: "text/event-stream" } : {}
4277
+ },
4278
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
4279
+ ...signals.length ? { signal: AbortSignal.any(signals) } : {}
4280
+ });
4281
+ if (response.status === 401 || response.status === 403) {
4282
+ await response.body?.cancel();
4283
+ this.endpoints.delete(sandboxId);
4284
+ if (attempt === 0) continue;
4285
+ throw new EndpointRejectedError(`Sandbox ${sandboxId} rejected its endpoint credentials (${response.status}).`);
4286
+ }
4287
+ return response;
4288
+ }
4289
+ }
4290
+ async prepareDaytonaSnapshot(sandbox, options) {
4291
+ const { Daytona, DaytonaNotFoundError } = await import("@daytona/sdk");
4292
+ const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
4293
+ const name = this.artifactName;
4294
+ const deadline = Date.now() + (this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS);
4295
+ const find = () => untilAborted(() => daytona.snapshot.get(name), options.signal).catch((error) => {
4296
+ if (error instanceof DaytonaNotFoundError) return void 0;
4297
+ throw error;
4298
+ });
4299
+ const isFailed = (found) => found.state === "error" || found.state === "build_failed";
4300
+ const isGoing = (found) => isFailed(found) || found.state === "removing";
4301
+ let snapshot = await find();
4302
+ let replaced;
4303
+ if (snapshot && snapshot.state !== "removing" && (isFailed(snapshot) || options.refresh)) {
4304
+ const old = snapshot;
4305
+ replaced = old;
4306
+ await untilAborted(() => daytona.snapshot.delete(old), options.signal).catch((error) => {
4307
+ if (!(error instanceof DaytonaNotFoundError)) throw error;
4308
+ });
4309
+ }
4310
+ while (snapshot && (isGoing(snapshot) || replaced !== void 0 && snapshot.id === replaced.id)) {
4311
+ await delay2(1e3, options.signal);
4312
+ snapshot = await find();
4313
+ }
4314
+ if (!snapshot) {
4315
+ try {
4316
+ snapshot = await untilAborted(() => daytona.snapshot.create(
4317
+ {
4318
+ name,
4319
+ image: this.image,
4320
+ entrypoint: this.command,
4321
+ ...sandbox.resources ? { resources: sandbox.resources } : {}
4322
+ },
4323
+ {
4324
+ timeout: Math.ceil((deadline - Date.now()) / 1e3),
4325
+ ...options.onLog ? { onLogs: options.onLog } : {}
4326
+ }
4327
+ ), options.signal);
4328
+ } catch (error) {
4329
+ if (options.signal.aborted) throw error;
4330
+ snapshot = await find();
4331
+ if (!snapshot) throw error;
4332
+ }
4333
+ }
4334
+ while (true) {
4335
+ if (snapshot.state === "active") return;
4336
+ if (snapshot.state === "inactive") {
4337
+ const inactive = snapshot;
4338
+ snapshot = await untilAborted(() => daytona.snapshot.activate(inactive), options.signal);
4339
+ continue;
4340
+ }
4341
+ if (isFailed(snapshot)) {
4342
+ throw new DeploymentError(`Daytona snapshot ${name} is ${snapshot.state}: ${snapshot.errorReason ?? "no reason given"}`);
4343
+ }
4344
+ await delay2(2e3, options.signal);
4345
+ snapshot = await find() ?? snapshot;
4346
+ }
4347
+ }
4348
+ async prepareE2bTemplate(sandbox, { signal, refresh, onLog }) {
4349
+ const { Template } = await import("e2b");
4350
+ const name = this.artifactName;
4351
+ const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
4352
+ const connection = { ...apiKey ? { apiKey } : {}, signal };
4353
+ const timeoutMs = this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS;
4354
+ const waitingGraceMs = Math.min(6e4, timeoutMs / 4);
4355
+ const pollMs = Math.min(2e3, waitingGraceMs / 4);
4356
+ let waitingSince;
4357
+ while (!refresh) {
4358
+ const { templates } = await this.e2bTemplates(sandbox, signal);
4359
+ const status = templates.find((template2) => [...template2.names ?? [], ...template2.aliases ?? []].includes(name))?.buildStatus;
4360
+ if (status === "ready") return;
4361
+ if (status === "waiting") {
4362
+ waitingSince ??= Date.now();
4363
+ if (Date.now() - waitingSince > waitingGraceMs) break;
4364
+ } else if (status !== "building") {
4365
+ break;
4366
+ }
4367
+ await delay2(pollMs, signal);
4368
+ }
4369
+ const template = Template().fromImage(
4370
+ this.image,
4371
+ ...sandbox.registry ? [sandbox.registry] : []
4372
+ );
4373
+ await Template.build(template, name, {
4374
+ ...connection,
4375
+ ...sandbox.cpuCount === void 0 ? {} : { cpuCount: sandbox.cpuCount },
4376
+ ...sandbox.memoryMB === void 0 ? {} : { memoryMB: sandbox.memoryMB },
4377
+ ...onLog ? { onBuildLogs: (entry) => onLog(entry.toString()) } : {}
4378
+ });
4379
+ }
4380
+ async listDaytonaSnapshots(sandbox, ownName) {
4381
+ const { Daytona } = await import("@daytona/sdk");
4382
+ const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
4383
+ const artifacts = [];
4384
+ for (let page = 1; ; page += 1) {
4385
+ const result = await daytona.snapshot.list({ page, limit: 100 });
4386
+ for (const snapshot of result.items) {
4387
+ if (!ownName.test(snapshot.name)) continue;
4388
+ artifacts.push({
4389
+ name: snapshot.name,
4390
+ createdAt: new Date(snapshot.createdAt).getTime(),
4391
+ delete: () => daytona.snapshot.delete(snapshot)
4392
+ });
4393
+ }
4394
+ if (page >= result.totalPages) return artifacts;
4395
+ }
4396
+ }
4397
+ async e2bTemplates(sandbox, signal) {
4398
+ const { ApiClient, ConnectionConfig } = await import("e2b");
4399
+ const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
4400
+ const client = new ApiClient(new ConnectionConfig(apiKey ? { apiKey } : {}));
4401
+ const { data, error } = await client.api.GET("/templates", signal ? { signal } : {});
4402
+ if (error || !data) throw new ExecutionError(`Listing E2B templates failed: ${JSON.stringify(error)}`);
4403
+ return { client, templates: data };
4404
+ }
4405
+ async listE2bTemplates(sandbox, ownName) {
4406
+ const { client, templates } = await this.e2bTemplates(sandbox);
4407
+ return templates.flatMap((template) => {
4408
+ const name = [...template.names ?? [], ...template.aliases ?? []].find((value) => ownName.test(value));
4409
+ if (!name) return [];
4410
+ return [{
4411
+ name,
4412
+ createdAt: new Date(template.createdAt).getTime(),
4413
+ delete: async () => {
4414
+ const result = await client.api.DELETE("/templates/{templateID}", {
4415
+ params: { path: { templateID: template.templateID } }
4416
+ });
4417
+ if (result.error) throw new ExecutionError(`Deleting E2B template ${name} failed: ${JSON.stringify(result.error)}`);
4418
+ }
4419
+ }];
4420
+ });
4421
+ }
4422
+ };
4423
+
4424
+ // src/braintrust.ts
4425
+ var API_KEY = "BRAINTRUST_API_KEY";
4426
+ var PROJECT_NAME = "BRAINTRUST_PROJECT_NAME";
4427
+ var FLUSH_TIMEOUT_MS = 1e4;
4428
+ var BRAINTRUST_PACKAGE = "braintrust";
4429
+ var BRAINTRUST_VERSIONS = ">=3.44.0 <4.0.0";
4430
+ var warn = (message) => console.warn(`neckbeard: ${message}`);
4431
+ var errorText = (error) => error instanceof Error ? error.message : String(error);
4432
+ function readBraintrustSettings(env, where) {
4433
+ const apiKey = env[API_KEY]?.trim();
4434
+ const projectName = env[PROJECT_NAME]?.trim();
4435
+ if (apiKey && projectName) return { apiKey, projectName };
4436
+ if (apiKey) warn(`Braintrust logging isn't configured ${where}: ${PROJECT_NAME} is not set.`);
4437
+ return void 0;
4438
+ }
4439
+ async function startBraintrust({ apiKey, projectName }) {
4440
+ const notTracing = "Braintrust tracing is off in the sandbox";
4441
+ let sdk;
4442
+ try {
4443
+ sdk = await import(
4444
+ /* webpackIgnore: true */
4445
+ BRAINTRUST_PACKAGE
4446
+ );
4447
+ } catch (error) {
4448
+ if (errorText(error).includes(`Cannot find package '${BRAINTRUST_PACKAGE}'`)) {
4449
+ warn(`${notTracing}: add ${BRAINTRUST_PACKAGE} ${BRAINTRUST_VERSIONS} to the agent's package's dependencies so the image has it.`);
4450
+ } else {
4451
+ warn(`${notTracing}: ${BRAINTRUST_PACKAGE} failed to load: ${errorText(error)}`);
4452
+ }
4453
+ return void 0;
4454
+ }
4455
+ if (typeof sdk.wrapPiCodingAgentSDK !== "function") {
4456
+ warn(`${notTracing}: its ${BRAINTRUST_PACKAGE} can't trace Pi; use ${BRAINTRUST_VERSIONS}.`);
4457
+ return void 0;
4458
+ }
4459
+ try {
4460
+ sdk.initLogger({ projectName, apiKey });
4461
+ } catch (error) {
4462
+ warn(`${notTracing}: ${errorText(error)}`);
4463
+ return void 0;
4464
+ }
4465
+ return {
4466
+ wrapPi: (pi) => sdk.wrapPiCodingAgentSDK(pi),
4467
+ async flush() {
4468
+ try {
4469
+ await withTimeout(sdk.flush(), FLUSH_TIMEOUT_MS, `not sent within ${FLUSH_TIMEOUT_MS / 1e3} seconds; it may arrive later`);
4470
+ } catch (error) {
4471
+ warn(`could not send the turn's Braintrust trace: ${errorText(error)}`);
4472
+ }
4473
+ }
4474
+ };
4475
+ }
4476
+
4477
+ // src/serve.ts
4478
+ var import_node_http = require("http");
4479
+ var HEARTBEAT_INTERVAL_MS = 15e3;
4480
+ var DEFAULT_ABORT_GRACE_MS = 1e4;
4481
+ var DEFAULT_PORT2 = 8080;
4482
+ function toPiJsonEvent(event) {
4483
+ if (!isRecord2(event) || event.type !== "message_update") return event;
4484
+ const { message, assistantMessageEvent } = event;
4485
+ if (!isRecord2(message) || message.role !== "assistant") {
4486
+ throw new Error("message_update message is not an assistant message");
4487
+ }
4488
+ if (!isRecord2(assistantMessageEvent) || typeof assistantMessageEvent.type !== "string") {
4489
+ throw new Error("message_update has no assistantMessageEvent");
4490
+ }
4491
+ const { partial, ...delta } = assistantMessageEvent;
4492
+ if (assistantMessageEvent.type === "toolcall_start") {
4493
+ const { contentIndex } = assistantMessageEvent;
4494
+ const content = isRecord2(partial) && Array.isArray(partial.content) ? partial.content : [];
4495
+ const toolCall = typeof contentIndex === "number" ? content[contentIndex] : void 0;
4496
+ if (!isRecord2(toolCall) || toolCall.type !== "toolCall" || typeof toolCall.id !== "string" || typeof toolCall.name !== "string") {
4497
+ throw new Error(`toolcall_start content at index ${String(contentIndex)} is not a tool call`);
4498
+ }
4499
+ return {
4500
+ type: "message_update",
4501
+ usage: message.usage,
4502
+ assistantMessageEvent: { ...delta, id: toolCall.id, toolName: toolCall.name }
4503
+ };
4504
+ }
4505
+ return { type: "message_update", usage: message.usage, assistantMessageEvent: delta };
4506
+ }
4507
+ var RequestError = class extends Error {
4508
+ constructor(status, message) {
4509
+ super(message);
4510
+ this.status = status;
4511
+ }
4512
+ };
4513
+ function sendJson(response, status, body) {
4514
+ response.writeHead(status, { "content-type": "application/json" });
4515
+ response.end(JSON.stringify(body));
4516
+ }
4517
+ async function readJsonBody(request) {
4518
+ const chunks = [];
4519
+ let size = 0;
4520
+ for await (const chunk of request) {
4521
+ size += chunk.byteLength;
4522
+ if (size > MAX_TURN_REQUEST_BYTES) throw new RequestError(413, "Request body is too large.");
4523
+ chunks.push(chunk);
4524
+ }
4525
+ try {
4526
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
4527
+ } catch {
4528
+ throw new RequestError(400, "Request body must be JSON.");
4529
+ }
4530
+ }
4531
+ function parseStartTurn(body) {
4532
+ if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
4533
+ const { turnId, message, env } = body;
4534
+ if (typeof turnId !== "string" || !turnId || turnId.length > MAX_TURN_ID_LENGTH) {
4535
+ throw new RequestError(400, `turnId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
4536
+ }
4537
+ if (typeof message !== "string" || !message.trim()) {
4538
+ throw new RequestError(400, "message must be a non-empty string.");
4539
+ }
4540
+ 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"))) {
4541
+ throw new RequestError(400, "env must map environment variable names to strings.");
4542
+ }
4543
+ return { turnId, message, ...env === void 0 ? {} : { env } };
4544
+ }
4545
+ function parseSteerTurn(body) {
4546
+ if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
4547
+ const { steerId, message } = body;
4548
+ if (typeof steerId !== "string" || !steerId || steerId.length > MAX_TURN_ID_LENGTH) {
4549
+ throw new RequestError(400, `steerId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
4550
+ }
4551
+ if (typeof message !== "string" || !message.trim()) {
4552
+ throw new RequestError(400, "message must be a non-empty string.");
4553
+ }
4554
+ return { steerId, message };
4555
+ }
4556
+ async function serve(options) {
4557
+ const toWireEvent = options.toWireEvent ?? toPiJsonEvent;
4558
+ let sessionPromise;
4559
+ let current;
4560
+ let previous;
4561
+ let currentSessionAbort;
4562
+ const findTurn = (turnId) => current?.id === turnId ? current : previous?.id === turnId ? previous : void 0;
4563
+ const append = (turn, record) => {
4564
+ const json = JSON.stringify({ seq: turn.records.length, ...record });
4565
+ turn.records.push(json);
4566
+ for (const wake of turn.waiters) wake();
4567
+ };
4568
+ const reclaimSteers = (turn) => {
4569
+ let left;
4570
+ try {
4571
+ left = turn.session?.clearQueue?.().steering.length ?? 0;
4572
+ } catch {
4573
+ left = turn.queuedSteers.length;
4574
+ sessionPromise = void 0;
4575
+ }
4576
+ const leftover = left > 0 ? turn.queuedSteers.slice(-left) : [];
4577
+ for (const steer of turn.queuedSteers) steer.state = leftover.includes(steer) ? "undelivered" : "delivered";
4578
+ turn.queuedSteers = [];
4579
+ turn.undeliveredSteers.push(...leftover);
4580
+ };
4581
+ const end = (turn, outcome, error) => {
4582
+ if (turn.ending) return turn.ending;
4583
+ turn.closed = true;
4584
+ turn.sessionReady();
4585
+ let written;
4586
+ turn.ending = new Promise((resolve2) => {
4587
+ written = resolve2;
4588
+ });
4589
+ reclaimSteers(turn);
4590
+ void (async () => {
4591
+ let timer;
4592
+ const graceMs = turn.stopBy === void 0 ? options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS : Math.max(0, turn.stopBy - Date.now());
4593
+ await Promise.race([
4594
+ turn.steering,
4595
+ new Promise((resolve2) => {
4596
+ timer = setTimeout(resolve2, graceMs);
4597
+ })
4598
+ ]);
4599
+ clearTimeout(timer);
4600
+ reclaimSteers(turn);
4601
+ const undeliveredSteerIds = turn.undeliveredSteers.filter((steer) => !steer.late).map((steer) => steer.id);
4602
+ append(turn, {
4603
+ type: "end",
4604
+ outcome,
4605
+ ...error === void 0 ? {} : { error },
4606
+ ...undeliveredSteerIds.length > 0 ? { undeliveredSteerIds } : {}
4607
+ });
4608
+ turn.ended = true;
4609
+ written();
4610
+ })();
4611
+ return turn.ending;
4612
+ };
4613
+ const acceptSteer = (turn, id, message) => {
4614
+ const steer = { id, state: "pending", late: false, settled: Promise.resolve() };
4615
+ steer.settled = turn.steering.then(async () => {
4616
+ const session = turn.session;
4617
+ if (turn.closed || !session?.steer || !session.clearQueue) {
4618
+ steer.state = "undelivered";
4619
+ return;
4620
+ }
4621
+ try {
4622
+ if (await session.steer(message) === "handled") {
4623
+ steer.state = "handled";
4624
+ return;
4625
+ }
4626
+ steer.state = "queued";
4627
+ turn.queuedSteers.push(steer);
4628
+ if (turn.closed) {
4629
+ reclaimSteers(turn);
4630
+ steer.late = turn.undeliveredSteers.includes(steer);
4631
+ }
4632
+ } catch (error) {
4633
+ steer.state = "failed";
4634
+ steer.error = error;
4635
+ turn.steers.delete(id);
4636
+ }
4637
+ });
4638
+ turn.steering = steer.settled;
4639
+ turn.steers.set(id, steer);
4640
+ return steer;
4641
+ };
4642
+ const endAfterGrace = (turn, outcome, error) => {
4643
+ if (turn.ending || turn.finishing || turn.forceEnd) return;
4644
+ const graceMs = options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS;
4645
+ turn.stopBy = Date.now() + graceMs;
4646
+ turn.forceEnd = setTimeout(() => void end(turn, outcome, error), graceMs);
4647
+ };
4648
+ const runTurn = async (turn, request) => {
4649
+ const previousEnv = /* @__PURE__ */ new Map();
4650
+ let unsubscribe;
4651
+ let timedOut = false;
4652
+ let session;
4653
+ const timeoutMessage = `Turn exceeded ${options.maxTurnDurationMs}ms.`;
4654
+ const timer = options.maxTurnDurationMs === void 0 ? void 0 : setTimeout(() => {
4655
+ timedOut = true;
4656
+ turn.closed = true;
4657
+ reclaimSteers(turn);
4658
+ if (session) void session.abort().catch(() => void 0);
4659
+ endAfterGrace(turn, "failed", timeoutMessage);
4660
+ }, options.maxTurnDurationMs);
4661
+ const finish = async (outcome, error) => {
4662
+ turn.finishing = true;
4663
+ turn.closed = true;
4664
+ if (timer) clearTimeout(timer);
4665
+ clearTimeout(turn.forceEnd);
4666
+ try {
4667
+ await session?.afterTurn?.();
4668
+ } catch {
4669
+ }
4670
+ await end(turn, outcome, error);
4671
+ };
4672
+ try {
4673
+ sessionPromise ??= options.createSession();
4674
+ try {
4675
+ session = await sessionPromise;
4676
+ } catch (error) {
4677
+ sessionPromise = void 0;
4678
+ throw error;
4679
+ }
4680
+ if (timedOut) {
4681
+ await end(turn, "failed", timeoutMessage);
4682
+ return;
4683
+ }
4684
+ const started = session;
4685
+ turn.session = session;
4686
+ for (const [name, value] of Object.entries(request.env ?? {})) {
4687
+ previousEnv.set(name, process.env[name]);
4688
+ process.env[name] = value;
4689
+ }
4690
+ unsubscribe = session.subscribe((event) => {
4691
+ if (turn.ending) return;
4692
+ try {
4693
+ append(turn, { type: "event", event: toWireEvent(event) });
4694
+ } catch (error) {
4695
+ void end(turn, "failed", `Could not convert an agent event: ${error instanceof Error ? error.message : String(error)}`);
4696
+ void started.abort().catch(() => void 0);
4697
+ }
4698
+ });
4699
+ currentSessionAbort = () => started.abort();
4700
+ turn.sessionReady();
4701
+ if (!turn.closed) await turn.steering;
4702
+ if (turn.ending) return;
4703
+ if (timedOut) {
4704
+ await end(turn, "failed", timeoutMessage);
4705
+ return;
4706
+ }
4707
+ if (turn.abortRequested) {
4708
+ await end(turn, "aborted");
4709
+ return;
4710
+ }
4711
+ await started.prompt(request.message);
4712
+ if (timedOut) await finish("failed", timeoutMessage);
4713
+ else await finish(turn.abortRequested ? "aborted" : "completed");
4714
+ } catch (error) {
4715
+ const message = error instanceof Error ? error.message : String(error);
4716
+ if (timedOut) await finish("failed", timeoutMessage);
4717
+ else await finish(turn.abortRequested ? "aborted" : "failed", turn.abortRequested ? void 0 : message);
4718
+ } finally {
4719
+ if (timer) clearTimeout(timer);
4720
+ clearTimeout(turn.forceEnd);
4721
+ turn.closed = true;
4722
+ turn.sessionReady();
4723
+ await turn.ending;
4724
+ unsubscribe?.();
4725
+ currentSessionAbort = void 0;
4726
+ await turn.steering;
4727
+ reclaimSteers(turn);
4728
+ for (const [name, value] of previousEnv) {
4729
+ if (value === void 0) delete process.env[name];
4730
+ else process.env[name] = value;
4731
+ }
4732
+ turn.settled = true;
4733
+ }
4734
+ };
4735
+ const busy = () => Boolean(current && !current.settled);
4736
+ const startTurn = async (request) => {
4737
+ const existing = findTurn(request.turnId);
4738
+ if (existing) return { status: 200, body: { turnId: existing.id, ended: existing.ended } };
4739
+ if (current && !current.settled) {
4740
+ return { status: 409, body: { error: "Another turn is running.", turnId: current.id } };
4741
+ }
4742
+ let sessionReady;
4743
+ const turn = {
4744
+ id: request.turnId,
4745
+ records: [],
4746
+ ended: false,
4747
+ settled: false,
4748
+ abortRequested: false,
4749
+ steers: /* @__PURE__ */ new Map(),
4750
+ queuedSteers: [],
4751
+ undeliveredSteers: [],
4752
+ steering: new Promise((resolve2) => {
4753
+ sessionReady = resolve2;
4754
+ }),
4755
+ sessionReady: () => sessionReady(),
4756
+ closed: false,
4757
+ finishing: false,
4758
+ waiters: /* @__PURE__ */ new Set()
4759
+ };
4760
+ previous = current;
4761
+ current = turn;
4762
+ void runTurn(turn, request);
4763
+ return { status: 202, body: { turnId: turn.id, ended: false } };
4764
+ };
4765
+ const streamTurn = async (turn, after, request, response) => {
4766
+ response.writeHead(200, {
4767
+ "content-type": "text/event-stream",
4768
+ "cache-control": "no-cache, no-transform",
4769
+ connection: "keep-alive",
4770
+ "x-accel-buffering": "no"
4771
+ });
4772
+ response.write(": connected\n\n");
4773
+ let closed = false;
4774
+ let wake;
4775
+ const onClose = () => {
4776
+ closed = true;
4777
+ wake?.();
4778
+ };
4779
+ request.on("close", onClose);
4780
+ response.on("close", onClose);
4781
+ const heartbeat = setInterval(() => {
4782
+ if (!closed) response.write(": ping\n\n");
4783
+ }, HEARTBEAT_INTERVAL_MS);
4784
+ let next = turn.ended ? Math.min(after + 1, turn.records.length - 1) : after + 1;
4785
+ try {
4786
+ while (!closed) {
4787
+ while (!closed && next < turn.records.length) {
4788
+ const ok = response.write(`id: ${next}
4789
+ data: ${turn.records[next]}
4790
+
4791
+ `);
4792
+ next += 1;
4793
+ if (!ok && !closed) {
4794
+ let onDrain;
4795
+ await new Promise((resolve2) => {
4796
+ wake = onDrain = resolve2;
4797
+ response.once("drain", resolve2);
4798
+ });
4799
+ if (onDrain) response.off("drain", onDrain);
4800
+ wake = void 0;
4801
+ }
4802
+ }
4803
+ if (closed || turn.ended && next >= turn.records.length) break;
4804
+ await new Promise((resolve2) => {
4805
+ wake = resolve2;
4806
+ turn.waiters.add(resolve2);
4807
+ });
4808
+ if (wake) turn.waiters.delete(wake);
4809
+ wake = void 0;
4810
+ }
4811
+ } finally {
4812
+ clearInterval(heartbeat);
4813
+ request.off("close", onClose);
4814
+ response.off("close", onClose);
4815
+ if (!closed) response.end();
4816
+ }
4817
+ };
4818
+ const server = (0, import_node_http.createServer)((request, response) => {
4819
+ void (async () => {
4820
+ const url = new URL(request.url ?? "/", "http://localhost");
4821
+ const turnPath = /^\/turns\/([^/]+)\/(events|abort|steer)$/u.exec(url.pathname);
4822
+ if (request.method === "GET" && url.pathname === "/health") {
4823
+ const health = {
4824
+ ok: true,
4825
+ protocolVersion: TURN_PROTOCOL_VERSION,
4826
+ busy: busy(),
4827
+ turnId: current?.id ?? null
4828
+ };
4829
+ return sendJson(response, 200, health);
4830
+ }
4831
+ if (request.method === "POST" && url.pathname === "/turns") {
4832
+ const { status, body } = await startTurn(parseStartTurn(await readJsonBody(request)));
4833
+ return sendJson(response, status, body);
4834
+ }
4835
+ if (turnPath) {
4836
+ const turn = findTurn(decodeURIComponent(turnPath[1]));
4837
+ if (!turn) return sendJson(response, 404, { error: "Unknown turn." });
4838
+ if (request.method === "GET" && turnPath[2] === "events") {
4839
+ const afterParam = url.searchParams.get("after");
4840
+ const after = afterParam === null ? -1 : Number(afterParam);
4841
+ if (!Number.isSafeInteger(after) || after < -1) {
4842
+ return sendJson(response, 400, { error: "after must be an integer of at least -1." });
4843
+ }
4844
+ return streamTurn(turn, after, request, response);
4845
+ }
4846
+ if (request.method === "POST" && turnPath[2] === "abort") {
4847
+ if (!turn.ending && !turn.finishing && !turn.abortRequested) {
4848
+ turn.abortRequested = true;
4849
+ turn.closed = true;
4850
+ reclaimSteers(turn);
4851
+ if (turn === current) void currentSessionAbort?.().catch(() => void 0);
4852
+ endAfterGrace(turn, "aborted");
4853
+ }
4854
+ return sendJson(response, 202, { turnId: turn.id, ended: turn.ended });
4855
+ }
4856
+ if (request.method === "POST" && turnPath[2] === "steer") {
4857
+ const { steerId, message } = parseSteerTurn(await readJsonBody(request));
4858
+ const known = turn.steers.get(steerId);
4859
+ if (!known && (turn !== current || turn.closed)) {
4860
+ return sendJson(response, 409, { error: "The turn is no longer running.", turnId: turn.id });
4861
+ }
4862
+ const steer = known ?? acceptSteer(turn, steerId, message);
4863
+ await steer.settled;
4864
+ if (steer.state === "failed") throw steer.error;
4865
+ if (steer.state === "undelivered" && !turn.closed) {
4866
+ return sendJson(response, 501, { error: "The session does not take steering messages." });
4867
+ }
4868
+ if (steer.late || steer.state === "undelivered") {
4869
+ return sendJson(response, 409, { error: "The turn is no longer running.", turnId: turn.id });
4870
+ }
4871
+ return sendJson(response, known ? 200 : 202, {
4872
+ turnId: turn.id,
4873
+ steerId,
4874
+ ...steer.state === "handled" ? { handled: true } : {}
4875
+ });
4876
+ }
4877
+ }
4878
+ sendJson(response, 404, { error: "Not found." });
4879
+ })().catch((error) => {
4880
+ if (response.headersSent) {
4881
+ response.destroy();
4882
+ return;
4883
+ }
4884
+ const status = error instanceof RequestError ? error.status : 500;
4885
+ sendJson(response, status, { error: error instanceof Error ? error.message : String(error) });
4886
+ });
4887
+ });
4888
+ const port = options.port ?? (Number(process.env.NECKBEARD_PORT) || DEFAULT_PORT2);
4889
+ await new Promise((resolve2, reject) => {
4890
+ server.once("error", reject);
4891
+ server.listen(port, options.host ?? "0.0.0.0", () => {
4892
+ server.off("error", reject);
4893
+ resolve2();
4894
+ });
4895
+ });
4896
+ return {
4897
+ port: server.address().port,
4898
+ close: () => new Promise((resolve2, reject) => {
4899
+ server.closeAllConnections();
4900
+ server.close((error) => error ? reject(error) : resolve2());
4901
+ })
4902
+ };
4903
+ }
4904
+
4905
+ // src/define.ts
4906
+ var SKILLS_DIR = "/app/.agents/skills";
4907
+ var IMAGE_TAG_ENV_VARS = [
4908
+ "NECKBEARD_IMAGE_TAG",
4909
+ "GITHUB_SHA",
4910
+ "CI_COMMIT_SHA",
4911
+ "BITBUCKET_COMMIT",
4912
+ "CODEBUILD_RESOLVED_SOURCE_VERSION",
4913
+ "BUILDKITE_COMMIT",
4914
+ "CIRCLE_SHA1",
4915
+ "CF_PAGES_COMMIT_SHA",
4916
+ "HEROKU_BUILD_COMMIT",
4917
+ "HEROKU_SLUG_COMMIT",
4918
+ "RAILWAY_GIT_COMMIT_SHA",
4919
+ "RENDER_GIT_COMMIT",
4920
+ "VERCEL_GIT_COMMIT_SHA",
4921
+ "SOURCE_VERSION",
4922
+ "GIT_COMMIT"
4923
+ ];
4924
+ function resolveImageTag(env = process.env) {
4925
+ for (const name of IMAGE_TAG_ENV_VARS) {
4926
+ const value = env[name]?.trim();
4927
+ if (value && value !== name) return value;
4928
+ }
4929
+ return void 0;
4930
+ }
4931
+ var PI_PACKAGE = "@earendil-works/pi-coding-agent";
4932
+ var definedAgentMarker = /* @__PURE__ */ Symbol.for("agent-neckbeard.DefinedAgent");
4933
+ var DefinedAgent = class {
4934
+ constructor(definition) {
4935
+ this.definition = definition;
4936
+ if (!definition || typeof definition !== "object") throw new ConfigurationError("Agent definition must be an object.");
4937
+ if (typeof definition.name !== "string" || !/^[a-z0-9]+(-[a-z0-9]+)*$/u.test(definition.name)) {
4938
+ throw new ConfigurationError("Agent name must be lowercase letters, digits, and single dashes.");
4939
+ }
4940
+ if (Boolean(definition.pi) === Boolean(definition.createSession)) {
4941
+ throw new ConfigurationError(`Agent ${definition.name} needs exactly one of pi and createSession.`);
4942
+ }
4943
+ if (!definition.image && !definition.registry) {
4944
+ throw new ConfigurationError(`Agent ${definition.name} needs a registry or an image.`);
4945
+ }
4946
+ }
4947
+ [definedAgentMarker] = true;
4948
+ client;
4949
+ braintrustChecked = false;
4950
+ get name() {
4951
+ return this.definition.name;
4952
+ }
4953
+ /** The image this host runs: `image`, else `<registry>/<name>:<tag>` with the tag `resolveImageTag()` finds. */
4954
+ imageRef(tag = resolveImageTag()) {
4955
+ const { image, registry, name } = this.definition;
4956
+ if (image) return image;
4957
+ if (!tag) {
4958
+ throw new ConfigurationError(
4959
+ `Set NECKBEARD_IMAGE_TAG to choose agent ${name}'s image, or deploy from a platform that names the commit, such as RENDER_GIT_COMMIT.`
4960
+ );
4961
+ }
4962
+ return `${registry.replace(/\/+$/u, "")}/${name}:${tag}`;
4963
+ }
4964
+ /** The `Agent` for an image, by default the one this host runs. */
4965
+ forImage(image = this.imageRef()) {
4966
+ const { definition } = this;
4967
+ const sandbox = typeof definition.sandbox === "function" ? definition.sandbox() : definition.sandbox;
4968
+ const envs = typeof definition.envs === "function" ? definition.envs() : definition.envs;
4969
+ return new Agent({
4970
+ name: definition.name,
4971
+ image,
4972
+ sandbox,
4973
+ ...envs ? { envs } : {},
4974
+ ...definition.command ? { command: definition.command } : {},
4975
+ ...definition.port === void 0 ? {} : { port: definition.port },
4976
+ ...definition.startTimeoutMs === void 0 ? {} : { startTimeoutMs: definition.startTimeoutMs },
4977
+ ...definition.prepareTimeoutMs === void 0 ? {} : { prepareTimeoutMs: definition.prepareTimeoutMs }
4978
+ });
4979
+ }
4980
+ get agent() {
4981
+ this.client ??= this.forImage();
4982
+ return this.client;
4983
+ }
4984
+ get artifactName() {
4985
+ return this.agent.artifactName;
4986
+ }
4987
+ prepare(options) {
4988
+ return this.agent.prepare(options);
4989
+ }
4990
+ start(options) {
4991
+ if (this.definition.pi && !this.braintrustChecked) {
4992
+ this.braintrustChecked = true;
4993
+ const envs = typeof this.definition.envs === "function" ? this.definition.envs() : this.definition.envs;
4994
+ readBraintrustSettings({ ...filterDefined(envs), ...filterDefined(options?.envs) }, `for agent ${this.name}'s sandboxes`);
4995
+ }
4996
+ return this.agent.start(options);
4997
+ }
4998
+ prompt(sandboxId, turn, options) {
4999
+ return this.agent.prompt(sandboxId, turn, options);
5000
+ }
5001
+ run(sandboxId, turn, options) {
5002
+ return this.agent.run(sandboxId, turn, options);
5003
+ }
5004
+ events(sandboxId, turnId, options) {
5005
+ return this.agent.events(sandboxId, turnId, options);
5006
+ }
5007
+ abort(sandboxId, turnId, signal) {
5008
+ return this.agent.abort(sandboxId, turnId, signal);
5009
+ }
5010
+ steer(sandboxId, turnId, steer, signal) {
5011
+ return this.agent.steer(sandboxId, turnId, steer, signal);
5012
+ }
5013
+ health(sandboxId, signal) {
5014
+ return this.agent.health(sandboxId, signal);
5015
+ }
5016
+ waitForIdle(sandboxId, options) {
5017
+ return this.agent.waitForIdle(sandboxId, options);
5018
+ }
5019
+ kill(sandboxId) {
5020
+ return this.agent.kill(sandboxId);
5021
+ }
5022
+ sandbox(sandboxId) {
5023
+ return this.agent.sandbox(sandboxId);
5024
+ }
5025
+ gc(options) {
5026
+ return this.agent.gc(options);
5027
+ }
5028
+ /** Where a persisted session's file is in a sandbox whose home is `homeDir`, as for copying it out and back. */
5029
+ sessionFilePath(homeDir, sessionId) {
5030
+ return import_node_path.default.posix.join(homeDir, "agent", ".pi", "sessions", `${sessionId}.jsonl`);
5031
+ }
5032
+ /** Serves the agent's session; the image's entry point, which `neckbeard build` generates, calls it. */
5033
+ serve(options = {}) {
5034
+ const { definition } = this;
5035
+ const { pi } = definition;
5036
+ return serve({
5037
+ createSession: pi ? () => createPiSession(pi) : definition.createSession,
5038
+ ...definition.maxTurnDurationMs === void 0 ? {} : { maxTurnDurationMs: definition.maxTurnDurationMs },
5039
+ ...definition.abortGraceMs === void 0 ? {} : { abortGraceMs: definition.abortGraceMs },
5040
+ ...options
5041
+ });
5042
+ }
5043
+ };
5044
+ function defineAgent(definition) {
5045
+ return new DefinedAgent(definition);
5046
+ }
5047
+ function isDefinedAgent(value) {
5048
+ return typeof value === "object" && value !== null && definedAgentMarker in value;
5049
+ }
5050
+ async function createPiSession(config) {
5051
+ const home = import_node_os.default.homedir();
5052
+ const cwd = import_node_path.default.resolve(home, config.cwd ?? "workspace");
5053
+ await (0, import_promises.mkdir)(cwd, { recursive: true });
5054
+ process.env.NECKBEARD_CWD = cwd;
5055
+ const agentDir = import_node_path.default.join(home, "agent", ".pi");
5056
+ const loaded = await import(
5057
+ /* webpackIgnore: true */
5058
+ PI_PACKAGE
5059
+ );
5060
+ const braintrustSettings = readBraintrustSettings(process.env, "in the sandbox");
5061
+ const braintrust = braintrustSettings && await startBraintrust(braintrustSettings);
5062
+ const pi = braintrust ? braintrust.wrapPi(loaded) : loaded;
5063
+ const modelRuntime = await pi.ModelRuntime.create({ modelsPath: null });
5064
+ const separator = config.model.indexOf("/");
5065
+ const model = separator > 0 ? modelRuntime.getModel(config.model.slice(0, separator), config.model.slice(separator + 1)) : void 0;
5066
+ if (!model) throw new ConfigurationError(`Pi has no model ${config.model}; name it as provider/model.`);
5067
+ const settingsManager = pi.SettingsManager.inMemory();
5068
+ const resourceLoader = new pi.DefaultResourceLoader({
5069
+ cwd,
5070
+ agentDir,
5071
+ settingsManager,
5072
+ additionalSkillPaths: [SKILLS_DIR],
5073
+ noSkills: true,
5074
+ noExtensions: true,
5075
+ noPromptTemplates: true,
5076
+ noContextFiles: true,
5077
+ systemPrompt: config.systemPrompt
5078
+ });
5079
+ await resourceLoader.reload();
5080
+ let sessionManager;
5081
+ if (config.persist) {
5082
+ const sessionId = process.env.NECKBEARD_SESSION_ID;
5083
+ if (!sessionId) throw new ConfigurationError("A persisted Pi session needs the sessionId passed to start().");
5084
+ const sessionFile = import_node_path.default.join(agentDir, "sessions", `${sessionId}.jsonl`);
5085
+ sessionManager = pi.SessionManager.open(sessionFile, import_node_path.default.dirname(sessionFile), cwd);
5086
+ } else {
5087
+ sessionManager = pi.SessionManager.inMemory(cwd);
5088
+ }
5089
+ const { session } = await pi.createAgentSession({
5090
+ cwd,
5091
+ agentDir,
5092
+ model,
5093
+ modelRuntime,
5094
+ resourceLoader,
5095
+ settingsManager,
5096
+ sessionManager,
5097
+ ...config.thinkingLevel ? { thinkingLevel: config.thinkingLevel } : {},
5098
+ ...config.tools ? { tools: config.tools } : {}
5099
+ });
5100
+ if (!braintrust) return session;
5101
+ return {
5102
+ subscribe: (listener) => session.subscribe(listener),
5103
+ prompt: (text) => session.prompt(text),
5104
+ abort: () => session.abort(),
5105
+ steer: (text) => session.steer(text),
5106
+ clearQueue: () => session.clearQueue(),
5107
+ afterTurn: () => braintrust.flush()
5108
+ };
5109
+ }
5110
+
3710
5111
  // src/providers/docker.ts
3711
5112
  var import_node_child_process = require("child_process");
3712
5113
  var import_node_net = require("net");
@@ -3949,18 +5350,18 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
3949
5350
  }
3950
5351
  return result;
3951
5352
  }
3952
- async makeDir(path) {
3953
- await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path]);
5353
+ async makeDir(path2) {
5354
+ await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path2]);
3954
5355
  }
3955
- async writeFile(path, content) {
5356
+ async writeFile(path2, content) {
3956
5357
  const input = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
3957
- await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path], input, DOCKER_FILE_TIMEOUT_MS);
5358
+ await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path2], input, DOCKER_FILE_TIMEOUT_MS);
3958
5359
  }
3959
- async readFile(path) {
3960
- return (await this.control("Docker file read", 'cat -- "$1"', [path], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
5360
+ async readFile(path2) {
5361
+ return (await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
3961
5362
  }
3962
- async readFileBytes(path) {
3963
- return new Uint8Array((await this.control("Docker file read", 'cat -- "$1"', [path], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout);
5363
+ async readFileBytes(path2) {
5364
+ return new Uint8Array((await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout);
3964
5365
  }
3965
5366
  async runCommand(command, options) {
3966
5367
  validateProviderCommand("Docker", command, options);
@@ -4009,8 +5410,8 @@ exec timeout --kill-after=1 ${deadlineSeconds} /bin/bash --noprofile --norc -c $
4009
5410
  };
4010
5411
 
4011
5412
  // src/index.ts
4012
- function readPackageJson(path) {
4013
- return JSON.parse((0, import_node_fs.readFileSync)(path, "utf8"));
5413
+ function readPackageJson(path2) {
5414
+ return JSON.parse((0, import_node_fs.readFileSync)(path2, "utf8"));
4014
5415
  }
4015
5416
  var getEsbuild = () => import("esbuild");
4016
5417
  var getE2b = () => import("e2b");
@@ -4040,9 +5441,11 @@ var NeckbeardError = class extends Error {
4040
5441
  }
4041
5442
  };
4042
5443
  var DeploymentError = class extends NeckbeardError {
4043
- constructor(message, cause) {
5444
+ /** A sandbox the failure left behind, for `kill()`. */
5445
+ constructor(message, cause, sandboxId) {
4044
5446
  super(message);
4045
5447
  this.cause = cause;
5448
+ this.sandboxId = sandboxId;
4046
5449
  this.name = "DeploymentError";
4047
5450
  }
4048
5451
  };
@@ -4066,6 +5469,12 @@ var RuntimeBusyError = class extends ExecutionError {
4066
5469
  this.name = "RuntimeBusyError";
4067
5470
  }
4068
5471
  };
5472
+ var TurnLostError = class extends ExecutionError {
5473
+ constructor(message) {
5474
+ super(message);
5475
+ this.name = "TurnLostError";
5476
+ }
5477
+ };
4069
5478
  var ConfigurationError = class extends NeckbeardError {
4070
5479
  constructor(message) {
4071
5480
  super(message);
@@ -4079,7 +5488,7 @@ function resolveAgentSourceFile(candidates, options = {}) {
4079
5488
  return sourceFile;
4080
5489
  }
4081
5490
  if (process.env[NECKBEARD_SANDBOX_RUNTIME_ENV] === "1") {
4082
- const sandboxSourceFile = options.sandboxSourceFile ?? (0, import_node_path.resolve)(process.cwd(), "agent.mjs");
5491
+ const sandboxSourceFile = options.sandboxSourceFile ?? (0, import_node_path2.resolve)(process.cwd(), "agent.mjs");
4083
5492
  if ((0, import_node_fs.existsSync)(sandboxSourceFile)) {
4084
5493
  return sandboxSourceFile;
4085
5494
  }
@@ -4201,7 +5610,7 @@ function appendIncludesToTraceAssets({
4201
5610
  if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
4202
5611
  continue;
4203
5612
  }
4204
- const traceDir = (0, import_node_path.dirname)((0, import_node_path.join)(outputPath, assetName));
5613
+ const traceDir = (0, import_node_path2.dirname)((0, import_node_path2.join)(outputPath, assetName));
4205
5614
  const nextSource = traceWithIncludedFiles(String(asset.source()), traceDir, includedFiles);
4206
5615
  if (rawSource && updateAsset) {
4207
5616
  updateAsset(assetName, new rawSource(nextSource));
@@ -4273,7 +5682,7 @@ function appendIncludesToTraceFiles(outputPath, appDir, sourceFiles, routeGlobs,
4273
5682
  function appendFilesToTrace(traceFile, includedFiles) {
4274
5683
  const nextSource = traceWithIncludedFiles(
4275
5684
  (0, import_node_fs.readFileSync)(traceFile, "utf8"),
4276
- (0, import_node_path.dirname)(traceFile),
5685
+ (0, import_node_path2.dirname)(traceFile),
4277
5686
  includedFiles
4278
5687
  );
4279
5688
  (0, import_node_fs.writeFileSync)(traceFile, nextSource);
@@ -4283,7 +5692,7 @@ function traceWithIncludedFiles(traceSource, traceDir, includedFiles) {
4283
5692
  const files = Array.isArray(trace.files) ? trace.files.filter((file) => typeof file === "string") : [];
4284
5693
  const nextFiles = new Set(files);
4285
5694
  for (const includedFile of includedFiles) {
4286
- nextFiles.add((0, import_node_path.relative)(traceDir, includedFile).replace(/\\/g, "/"));
5695
+ nextFiles.add((0, import_node_path2.relative)(traceDir, includedFile).replace(/\\/g, "/"));
4287
5696
  }
4288
5697
  return JSON.stringify({
4289
5698
  version: trace.version ?? 1,
@@ -4309,7 +5718,7 @@ function traceIncludeFilesForConfig(appDir, sourceFiles, traceSourceDependencies
4309
5718
  return mergeStringArray(sourceFiles, tracedFiles);
4310
5719
  }
4311
5720
  function toNextTraceIncludePath(appDir, file) {
4312
- const relativePath = (0, import_node_path.relative)(appDir, file).replace(/\\/g, "/");
5721
+ const relativePath = (0, import_node_path2.relative)(appDir, file).replace(/\\/g, "/");
4313
5722
  if (relativePath.startsWith("..")) {
4314
5723
  return relativePath;
4315
5724
  }
@@ -4318,14 +5727,14 @@ function toNextTraceIncludePath(appDir, file) {
4318
5727
  function expandTraceIncludePattern(appDir, sourceFile) {
4319
5728
  const normalized = sourceFile.replace(/\\/g, "/").replace(/^\.\//, "");
4320
5729
  if (normalized.endsWith("/**/*")) {
4321
- const dir = (0, import_node_path.resolve)(appDir, normalized.slice(0, -5));
5730
+ const dir = (0, import_node_path2.resolve)(appDir, normalized.slice(0, -5));
4322
5731
  return findFiles(dir);
4323
5732
  }
4324
5733
  if (normalized.endsWith("/*")) {
4325
- const dir = (0, import_node_path.resolve)(appDir, normalized.slice(0, -2));
5734
+ const dir = (0, import_node_path2.resolve)(appDir, normalized.slice(0, -2));
4326
5735
  return directFiles(dir);
4327
5736
  }
4328
- const file = (0, import_node_path.resolve)(appDir, normalized);
5737
+ const file = (0, import_node_path2.resolve)(appDir, normalized);
4329
5738
  return (0, import_node_fs.existsSync)(file) && (0, import_node_fs.statSync)(file).isFile() ? [file] : [];
4330
5739
  }
4331
5740
  function traceSourceDependencyFiles(appDir, sourceFiles) {
@@ -4371,12 +5780,12 @@ function traceSourceDependencyFiles(appDir, sourceFiles) {
4371
5780
  continue;
4372
5781
  }
4373
5782
  const resolvedImportPath = importRecord.external ? void 0 : resolveMetafileInput(appDir, importRecord.path);
4374
- const packageInfo = resolvedImportPath ? resolvePackageInfoFromResolvedPath(importPath, resolvedImportPath) : resolvePackageInfoSync(importPath, (0, import_node_path.dirname)(absoluteInput));
5783
+ const packageInfo = resolvedImportPath ? resolvePackageInfoFromResolvedPath(importPath, resolvedImportPath) : resolvePackageInfoSync(importPath, (0, import_node_path2.dirname)(absoluteInput));
4375
5784
  if (!packageInfo) {
4376
5785
  continue;
4377
5786
  }
4378
5787
  addFile(packageInfo.resolvedPath);
4379
- addFile((0, import_node_path.join)(packageInfo.root, "package.json"));
5788
+ addFile((0, import_node_path2.join)(packageInfo.root, "package.json"));
4380
5789
  }
4381
5790
  }
4382
5791
  return [...files];
@@ -4390,7 +5799,7 @@ function getEsbuildSync() {
4390
5799
  return packageRequire("esbuild");
4391
5800
  }
4392
5801
  function resolveMetafileInput(absWorkingDir, inputPath) {
4393
- return (0, import_node_path.resolve)(absWorkingDir, inputPath);
5802
+ return (0, import_node_path2.resolve)(absWorkingDir, inputPath);
4394
5803
  }
4395
5804
  function findTraceFiles(root) {
4396
5805
  return findFiles(root).filter((file) => file.endsWith(".nft.json"));
@@ -4408,7 +5817,7 @@ function findFiles(root) {
4408
5817
  }
4409
5818
  const files = [];
4410
5819
  for (const entry of (0, import_node_fs.readdirSync)(root)) {
4411
- files.push(...findFiles((0, import_node_path.join)(root, entry)));
5820
+ files.push(...findFiles((0, import_node_path2.join)(root, entry)));
4412
5821
  }
4413
5822
  return files;
4414
5823
  }
@@ -4416,10 +5825,10 @@ function directFiles(root) {
4416
5825
  if (!(0, import_node_fs.existsSync)(root) || !(0, import_node_fs.statSync)(root).isDirectory()) {
4417
5826
  return [];
4418
5827
  }
4419
- 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());
5828
+ 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());
4420
5829
  }
4421
5830
  function routePathFromTraceFile(outputPath, traceFile) {
4422
- const relativeTrace = (0, import_node_path.relative)(outputPath, traceFile).replace(/\\/g, "/");
5831
+ const relativeTrace = (0, import_node_path2.relative)(outputPath, traceFile).replace(/\\/g, "/");
4423
5832
  return routePathFromRelativeTrace(outputPath, relativeTrace);
4424
5833
  }
4425
5834
  function routePathFromTraceAsset(outputPath, assetName) {
@@ -4439,7 +5848,7 @@ function routePathFromRelativeTrace(outputPath, relativeTrace) {
4439
5848
  if (normalizedTrace.startsWith("pages/")) {
4440
5849
  return normalizeTraceRoute(normalizedTrace.slice("pages/".length));
4441
5850
  }
4442
- if ((0, import_node_path.basename)(outputPath) === "app" || (0, import_node_path.basename)(outputPath) === "pages") {
5851
+ if ((0, import_node_path2.basename)(outputPath) === "app" || (0, import_node_path2.basename)(outputPath) === "pages") {
4443
5852
  return normalizeTraceRoute(relativeTrace);
4444
5853
  }
4445
5854
  return void 0;
@@ -4549,7 +5958,7 @@ function normalizeLocalDirectoryDestination(destination, name) {
4549
5958
  throw new ConfigurationError(`${name}.destination must not contain null bytes.`);
4550
5959
  }
4551
5960
  const sandboxPath = destination.replace(/\\/g, "/");
4552
- if ((0, import_node_path.isAbsolute)(destination) || import_node_path.posix.isAbsolute(sandboxPath) || import_node_path.win32.isAbsolute(destination)) {
5961
+ if ((0, import_node_path2.isAbsolute)(destination) || import_node_path2.posix.isAbsolute(sandboxPath) || import_node_path2.win32.isAbsolute(destination)) {
4553
5962
  throw new ConfigurationError(
4554
5963
  `${name}.destination must be relative to the sandbox agent directory.`
4555
5964
  );
@@ -4559,7 +5968,7 @@ function normalizeLocalDirectoryDestination(destination, name) {
4559
5968
  `${name}.destination must not traverse outside the sandbox agent directory.`
4560
5969
  );
4561
5970
  }
4562
- const normalized = import_node_path.posix.normalize(sandboxPath);
5971
+ const normalized = import_node_path2.posix.normalize(sandboxPath);
4563
5972
  if (normalized === ".") {
4564
5973
  throw new ConfigurationError(`${name}.destination must not be ".".`);
4565
5974
  }
@@ -4758,10 +6167,10 @@ function requireEnv(name) {
4758
6167
  }
4759
6168
  return value;
4760
6169
  }
4761
- var require2 = (0, import_node_module2.createRequire)((0, import_node_path.join)(process.cwd(), "__agent_neckbeard__.cjs"));
6170
+ var require2 = (0, import_node_module2.createRequire)((0, import_node_path2.join)(process.cwd(), "__agent_neckbeard__.cjs"));
4762
6171
  var packageRequire = createPackageRequire();
4763
6172
  function createPackageRequire() {
4764
- const cwdPackageJsonPath = (0, import_node_path.join)(process.cwd(), "package.json");
6173
+ const cwdPackageJsonPath = (0, import_node_path2.join)(process.cwd(), "package.json");
4765
6174
  try {
4766
6175
  if ((0, import_node_fs.existsSync)(cwdPackageJsonPath) && readPackageJson(cwdPackageJsonPath).name === NECKBEARD_PACKAGE_NAME) {
4767
6176
  return (0, import_node_module2.createRequire)(cwdPackageJsonPath);
@@ -4774,12 +6183,12 @@ function createPackageRequire() {
4774
6183
  return require2;
4775
6184
  }
4776
6185
  }
4777
- function isBareModuleImport(path) {
6186
+ function isBareModuleImport(path2) {
4778
6187
  const excludes = [".", "/", "~", "file:", "data:"];
4779
- return !excludes.some((exclude) => path.startsWith(exclude));
6188
+ return !excludes.some((exclude) => path2.startsWith(exclude));
4780
6189
  }
4781
- function isBuiltinModule(path) {
4782
- return import_node_module2.builtinModules.includes(path.replace("node:", ""));
6190
+ function isBuiltinModule(path2) {
6191
+ return import_node_module2.builtinModules.includes(path2.replace("node:", ""));
4783
6192
  }
4784
6193
  function packageNameForImportPath(importPath) {
4785
6194
  if (importPath.startsWith("@")) {
@@ -4801,10 +6210,10 @@ function resolvePackageInfoSync(importPath, resolveDir) {
4801
6210
  try {
4802
6211
  const resolvedPath = require2.resolve(importPath, { paths: [resolveDir] });
4803
6212
  const packageName = packageNameForImportPath(importPath);
4804
- let root = (0, import_node_path.dirname)(resolvedPath);
6213
+ let root = (0, import_node_path2.dirname)(resolvedPath);
4805
6214
  let packageJsonPath = null;
4806
6215
  while (true) {
4807
- const candidate = (0, import_node_path.join)(root, "package.json");
6216
+ const candidate = (0, import_node_path2.join)(root, "package.json");
4808
6217
  if ((0, import_node_fs.existsSync)(candidate)) {
4809
6218
  const candidatePackageJson = readPackageJson(candidate);
4810
6219
  if (candidatePackageJson.name === packageName) {
@@ -4812,14 +6221,14 @@ function resolvePackageInfoSync(importPath, resolveDir) {
4812
6221
  break;
4813
6222
  }
4814
6223
  }
4815
- const parent = (0, import_node_path.dirname)(root);
6224
+ const parent = (0, import_node_path2.dirname)(root);
4816
6225
  if (parent === root) break;
4817
6226
  root = parent;
4818
6227
  }
4819
6228
  if (!packageJsonPath) return null;
4820
6229
  const packageJson = readPackageJson(packageJsonPath);
4821
6230
  if (!packageJson.name || !packageJson.version) return null;
4822
- root = (0, import_node_path.dirname)(packageJsonPath);
6231
+ root = (0, import_node_path2.dirname)(packageJsonPath);
4823
6232
  return {
4824
6233
  name: packageJson.name,
4825
6234
  version: packageJson.version,
@@ -4833,9 +6242,9 @@ function resolvePackageInfoSync(importPath, resolveDir) {
4833
6242
  }
4834
6243
  function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
4835
6244
  const packageName = packageNameForImportPath(importPath);
4836
- let root = (0, import_node_path.dirname)(resolvedPath);
6245
+ let root = (0, import_node_path2.dirname)(resolvedPath);
4837
6246
  while (true) {
4838
- const packageJsonPath = (0, import_node_path.join)(root, "package.json");
6247
+ const packageJsonPath = (0, import_node_path2.join)(root, "package.json");
4839
6248
  if ((0, import_node_fs.existsSync)(packageJsonPath)) {
4840
6249
  const packageJson = readPackageJson(packageJsonPath);
4841
6250
  if (packageJson.name === packageName) {
@@ -4849,7 +6258,7 @@ function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
4849
6258
  };
4850
6259
  }
4851
6260
  }
4852
- const parent = (0, import_node_path.dirname)(root);
6261
+ const parent = (0, import_node_path2.dirname)(root);
4853
6262
  if (parent === root) return null;
4854
6263
  root = parent;
4855
6264
  }
@@ -4864,7 +6273,7 @@ function hasNativeHints(info) {
4864
6273
  function shouldAutoExternalize(info) {
4865
6274
  if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
4866
6275
  if (hasNativeHints(info)) return true;
4867
- if ((0, import_node_fs.existsSync)((0, import_node_path.join)(info.root, "binding.gyp"))) return true;
6276
+ if ((0, import_node_fs.existsSync)((0, import_node_path2.join)(info.root, "binding.gyp"))) return true;
4868
6277
  return false;
4869
6278
  }
4870
6279
  function normalizeList(value) {
@@ -5055,6 +6464,24 @@ async function connectProviderSandboxHandle(options) {
5055
6464
  });
5056
6465
  return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
5057
6466
  }
6467
+ async function destroyProviderSandbox(options) {
6468
+ if (options.provider === "modal") {
6469
+ validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
6470
+ return ModalSandboxHandle.destroyById(options, (message) => new DeploymentError(message));
6471
+ }
6472
+ if (options.provider === "daytona") {
6473
+ const { Daytona, DaytonaNotFoundError } = await getDaytona();
6474
+ const daytona = new Daytona({ apiKey: providerApiKey("daytona", options.apiKey) });
6475
+ try {
6476
+ await (await daytona.get(options.sandboxId)).delete(Math.ceil(SANDBOX_COMMAND_TIMEOUT_MS2 / 1e3), true);
6477
+ } catch (error) {
6478
+ if (!(error instanceof DaytonaNotFoundError)) throw error;
6479
+ }
6480
+ return;
6481
+ }
6482
+ const { Sandbox } = await getE2b();
6483
+ await Sandbox.kill(options.sandboxId, { apiKey: providerApiKey("e2b", options.apiKey) });
6484
+ }
5058
6485
  var SandboxClient = class _SandboxClient {
5059
6486
  constructor(handle) {
5060
6487
  this.handle = handle;
@@ -5082,17 +6509,17 @@ var SandboxClient = class _SandboxClient {
5082
6509
  outputJson: this.handle.paths.outputJson
5083
6510
  };
5084
6511
  }
5085
- async makeDir(path) {
5086
- await this.handle.makeDir(path);
6512
+ async makeDir(path2) {
6513
+ await this.handle.makeDir(path2);
5087
6514
  }
5088
- async writeFile(path, content) {
5089
- await this.handle.writeFile(path, content);
6515
+ async writeFile(path2, content) {
6516
+ await this.handle.writeFile(path2, content);
5090
6517
  }
5091
- async readFile(path) {
5092
- return this.handle.readFile(path);
6518
+ async readFile(path2) {
6519
+ return this.handle.readFile(path2);
5093
6520
  }
5094
- async readFileBytes(path) {
5095
- return this.handle.readFileBytes(path);
6521
+ async readFileBytes(path2) {
6522
+ return this.handle.readFileBytes(path2);
5096
6523
  }
5097
6524
  async runCommand(command, options) {
5098
6525
  return this.handle.runCommand(command, options);
@@ -5158,6 +6585,22 @@ var SandboxClient = class _SandboxClient {
5158
6585
  }
5159
6586
  await this.handle.setTimeout(timeoutMs);
5160
6587
  }
6588
+ /**
6589
+ * Where to reach an HTTP server the sandbox runs on `port`, with the provider's auth: send
6590
+ * `headers` with every request and add `query` to every URL.
6591
+ */
6592
+ async getServerEndpoint(port) {
6593
+ if (!this.handle.getServerEndpoint) {
6594
+ throw new ConfigurationError(`Sandbox provider "${this.provider}" does not expose server ports.`);
6595
+ }
6596
+ const { url, trafficToken } = await this.handle.getServerEndpoint(port);
6597
+ const descriptor = { provider: this.provider, trafficToken };
6598
+ return {
6599
+ url: url.replace(/\/+$/u, ""),
6600
+ headers: trafficTokenHeaders(descriptor),
6601
+ query: this.provider === "daytona" && trafficToken ? { DAYTONA_SANDBOX_AUTH_KEY: trafficToken } : {}
6602
+ };
6603
+ }
5161
6604
  async kill() {
5162
6605
  await this.handle.destroy();
5163
6606
  }
@@ -5172,7 +6615,7 @@ function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
5172
6615
  if (rawPath.startsWith("webpack-internal:")) {
5173
6616
  const afterScheme = rawPath.replace(/^webpack-internal:\/+/, "");
5174
6617
  const afterLayer = afterScheme.replace(/^\([^)]+\)\//, "");
5175
- const resolved = (0, import_node_path.resolve)(cwd, afterLayer);
6618
+ const resolved = (0, import_node_path2.resolve)(cwd, afterLayer);
5176
6619
  return (0, import_node_fs.existsSync)(resolved) ? resolved : null;
5177
6620
  }
5178
6621
  return rawPath;
@@ -5222,7 +6665,7 @@ function resolveSourceFile(sourceFile) {
5222
6665
  if (!normalized) {
5223
6666
  throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
5224
6667
  }
5225
- const resolved = (0, import_node_path.resolve)(normalized);
6668
+ const resolved = (0, import_node_path2.resolve)(normalized);
5226
6669
  if (isFrameworkBuildOutputPath(resolved)) {
5227
6670
  throw frameworkBuildOutputError(resolved);
5228
6671
  }
@@ -5257,7 +6700,7 @@ function localPathStats(localPath, upload, isSourceRoot = false) {
5257
6700
  }
5258
6701
  }
5259
6702
  function readConfiguredLocalDirectory(upload) {
5260
- const rootPath = (0, import_node_path.resolve)(process.cwd(), upload.source);
6703
+ const rootPath = (0, import_node_path2.resolve)(process.cwd(), upload.source);
5261
6704
  const rootStats = localPathStats(rootPath, upload, true);
5262
6705
  if (!rootStats.isDirectory()) {
5263
6706
  throw new ConfigurationError(`${upload.name}.source must be a directory: ${rootPath}`);
@@ -5274,7 +6717,7 @@ function readConfiguredLocalDirectory(upload) {
5274
6717
  );
5275
6718
  }
5276
6719
  for (const entry of entries) {
5277
- const localPath = (0, import_node_path.join)(currentPath, entry);
6720
+ const localPath = (0, import_node_path2.join)(currentPath, entry);
5278
6721
  const stats = localPathStats(localPath, upload);
5279
6722
  if (stats.isDirectory()) {
5280
6723
  walk(localPath);
@@ -5285,8 +6728,8 @@ function readConfiguredLocalDirectory(upload) {
5285
6728
  `${upload.name} source tree contains an unsupported filesystem entry: ${localPath}`
5286
6729
  );
5287
6730
  }
5288
- const relativePath = (0, import_node_path.relative)(rootPath, localPath).split(import_node_path.sep).join("/");
5289
- const targetPath = import_node_path.posix.join(destination, relativePath);
6731
+ const relativePath = (0, import_node_path2.relative)(rootPath, localPath).split(import_node_path2.sep).join("/");
6732
+ const targetPath = import_node_path2.posix.join(destination, relativePath);
5290
6733
  let content;
5291
6734
  try {
5292
6735
  content = (0, import_node_fs.readFileSync)(localPath);
@@ -5336,7 +6779,7 @@ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
5336
6779
  }
5337
6780
  }
5338
6781
  for (const file of filesByTarget.values()) {
5339
- let parent = import_node_path.posix.dirname(file.targetPath);
6782
+ let parent = import_node_path2.posix.dirname(file.targetPath);
5340
6783
  while (parent !== ".") {
5341
6784
  const parentFile = filesByTarget.get(parent);
5342
6785
  if (parentFile) {
@@ -5345,7 +6788,7 @@ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
5345
6788
  );
5346
6789
  }
5347
6790
  requiredDirectories.add(parent);
5348
- parent = import_node_path.posix.dirname(parent);
6791
+ parent = import_node_path2.posix.dirname(parent);
5349
6792
  }
5350
6793
  }
5351
6794
  const directories = [...requiredDirectories].sort((left, right) => {
@@ -5357,7 +6800,7 @@ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
5357
6800
  );
5358
6801
  return { directories, files };
5359
6802
  }
5360
- var Agent = class {
6803
+ var LegacyBundledAgent = class {
5361
6804
  sandbox;
5362
6805
  provider;
5363
6806
  template;
@@ -5623,7 +7066,7 @@ var Agent = class {
5623
7066
  *
5624
7067
  * @example
5625
7068
  * ```typescript
5626
- * const agent = new Agent({ ... });
7069
+ * const agent = new LegacyBundledAgent({ ... });
5627
7070
  * const sandboxId = await agent.deploy();
5628
7071
  * console.log(`Deployed to sandbox: ${sandboxId}`);
5629
7072
  *
@@ -5678,7 +7121,7 @@ var require = __neckbeard_createRequire(import.meta.url);
5678
7121
  }));
5679
7122
  build.onLoad({ filter: /.*/, namespace: "agent-shim" }, () => ({
5680
7123
  contents: `
5681
- export class Agent {
7124
+ export class LegacyBundledAgent {
5682
7125
  constructor(config) {
5683
7126
  this.inputSchema = config.inputSchema;
5684
7127
  this.outputSchema = config.outputSchema;
@@ -5785,7 +7228,7 @@ var require = __neckbeard_createRequire(import.meta.url);
5785
7228
  }
5786
7229
  }
5787
7230
  if (localDirectoryUploads.directories.length > 0 || localDirectoryUploads.files.length > 0) {
5788
- const archivePath = import_node_path.posix.join(paths.agentDir, `.neckbeard-local-directories-${(0, import_node_crypto3.randomUUID)()}.tar.gz`);
7231
+ const archivePath = import_node_path2.posix.join(paths.agentDir, `.neckbeard-local-directories-${(0, import_node_crypto4.randomUUID)()}.tar.gz`);
5789
7232
  await sandbox.writeFile(archivePath, await createTarGz([
5790
7233
  ...localDirectoryUploads.directories.map((directory) => ({ path: directory })),
5791
7234
  ...localDirectoryUploads.files.map((file) => ({ path: file.targetPath, content: file.content }))
@@ -5966,18 +7409,18 @@ var require = __neckbeard_createRequire(import.meta.url);
5966
7409
  );
5967
7410
  }
5968
7411
  if (!options || typeof options !== "object") {
5969
- throw new ConfigurationError("Agent.createSession() options must be an object.");
7412
+ throw new ConfigurationError("LegacyBundledAgent.createSession() options must be an object.");
5970
7413
  }
5971
7414
  let optionsAreArray;
5972
7415
  try {
5973
7416
  optionsAreArray = Array.isArray(options);
5974
7417
  } catch {
5975
7418
  throw new ConfigurationError(
5976
- "Agent.createSession() options must have readable values."
7419
+ "LegacyBundledAgent.createSession() options must have readable values."
5977
7420
  );
5978
7421
  }
5979
7422
  if (optionsAreArray) {
5980
- throw new ConfigurationError("Agent.createSession() options must be an object.");
7423
+ throw new ConfigurationError("LegacyBundledAgent.createSession() options must be an object.");
5981
7424
  }
5982
7425
  let durability;
5983
7426
  let requestedSandboxId;
@@ -5988,22 +7431,22 @@ var require = __neckbeard_createRequire(import.meta.url);
5988
7431
  signal = options.signal;
5989
7432
  } catch {
5990
7433
  throw new ConfigurationError(
5991
- "Agent.createSession() options must have readable values."
7434
+ "LegacyBundledAgent.createSession() options must have readable values."
5992
7435
  );
5993
7436
  }
5994
7437
  if (durability !== void 0 && durability !== "attached") {
5995
7438
  throw new ConfigurationError(
5996
- "Agent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
7439
+ "LegacyBundledAgent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
5997
7440
  );
5998
7441
  }
5999
7442
  if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
6000
7443
  throw new ConfigurationError(
6001
- "Agent.createSession() sandboxId must be a non-empty string when provided."
7444
+ "LegacyBundledAgent.createSession() sandboxId must be a non-empty string when provided."
6002
7445
  );
6003
7446
  }
6004
7447
  if (signal !== void 0 && !isAbortSignal(signal)) {
6005
7448
  throw new ConfigurationError(
6006
- "Agent.createSession() signal must be an AbortSignal when provided."
7449
+ "LegacyBundledAgent.createSession() signal must be an AbortSignal when provided."
6007
7450
  );
6008
7451
  }
6009
7452
  const sandboxId = requestedSandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
@@ -6123,13 +7566,23 @@ var require = __neckbeard_createRequire(import.meta.url);
6123
7566
  Agent,
6124
7567
  ConfigurationError,
6125
7568
  DEFAULT_DEPENDENCIES,
7569
+ DefinedAgent,
6126
7570
  DeploymentError,
6127
7571
  ExecutionError,
7572
+ LegacyBundledAgent,
6128
7573
  NeckbeardError,
6129
7574
  RuntimeBusyError,
7575
+ SKILLS_DIR,
6130
7576
  SandboxClient,
7577
+ TURN_PROTOCOL_VERSION,
7578
+ TurnLostError,
6131
7579
  ValidationError,
7580
+ defineAgent,
7581
+ destroyProviderSandbox,
7582
+ getPiTurnResult,
7583
+ isDefinedAgent,
6132
7584
  normalizeStackFramePath,
6133
7585
  resolveAgentSourceFile,
7586
+ resolveImageTag,
6134
7587
  withNeckbeardNextConfig
6135
7588
  });