agent-neckbeard 1.1.28 → 1.1.30

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +28 -30
  3. package/dist/archil.d.ts +73 -0
  4. package/dist/archil.js +673 -0
  5. package/dist/build.cjs +129 -5160
  6. package/dist/build.d.cts +9 -5
  7. package/dist/build.d.ts +9 -5
  8. package/dist/build.js +4 -6
  9. package/dist/{chunk-JF5YPOBY.js → chunk-FHNQ5DNA.js} +3235 -511
  10. package/dist/{chunk-M7XNBKG4.js → chunk-I5GIWADK.js} +29 -7
  11. package/dist/chunk-I5NULOJP.js +129 -0
  12. package/dist/chunk-PKUGXECR.js +13 -0
  13. package/dist/chunk-QA4L7ZI2.js +72 -0
  14. package/dist/{chunk-KG6SJM74.js → chunk-VHBDBB3N.js} +8 -5
  15. package/dist/cli.cjs +124 -5154
  16. package/dist/cli.js +7 -8
  17. package/dist/define-gdmBe9RA.d.ts +227 -0
  18. package/dist/durable.d.ts +53 -0
  19. package/dist/durable.js +92 -0
  20. package/dist/index.cjs +720 -833
  21. package/dist/index.d.cts +139 -78
  22. package/dist/index.d.ts +139 -78
  23. package/dist/index.js +12 -11
  24. package/dist/inside.d.ts +15 -0
  25. package/dist/inside.js +530 -0
  26. package/dist/{invoke-client-P2CPBYTF.js → invoke-client-QB2NTZ3L.js} +1 -2
  27. package/dist/pi-watch-legacy.d.ts +4503 -0
  28. package/dist/serve.cjs +9 -309
  29. package/dist/serve.d.cts +14 -1
  30. package/dist/serve.d.ts +14 -1
  31. package/dist/serve.js +3 -5
  32. package/docs/AGENT.md +95 -59
  33. package/docs/DAYTONA.md +2 -0
  34. package/docs/DOCKER.md +0 -1
  35. package/docs/E2B.md +1 -1
  36. package/docs/LEGACY.md +1 -8
  37. package/docs/MODAL.md +1 -1
  38. package/package.json +57 -23
  39. package/types/pi-watch.d.cts +68 -0
  40. package/dist/chunk-33IXN6MM.js +0 -21
  41. package/dist/chunk-6P5I7ZCH.js +0 -2552
  42. package/dist/chunk-M3FISP7J.js +0 -377
  43. package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +0 -77
  44. package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +0 -77
  45. package/dist/serve-Dan1HQKN.d.cts +0 -89
  46. package/dist/serve-Dan1HQKN.d.ts +0 -89
  47. package/dist/supervisor.cjs +0 -5731
  48. package/dist/supervisor.d.cts +0 -482
  49. package/dist/supervisor.d.ts +0 -482
  50. package/dist/supervisor.js +0 -3187
  51. package/docs/SUPERVISOR.md +0 -258
package/dist/index.cjs CHANGED
@@ -89,9 +89,9 @@ var init_protocol = __esm({
89
89
  });
90
90
 
91
91
  // src/sse-framing.ts
92
- async function* decodeSseStream(chunks) {
92
+ async function* decodeSseStream(chunks2, options = {}) {
93
93
  let buffer = "";
94
- for await (const chunk of chunks) {
94
+ for await (const chunk of chunks2) {
95
95
  buffer += chunk;
96
96
  let boundary = buffer.indexOf("\n\n");
97
97
  while (boundary !== -1) {
@@ -106,6 +106,7 @@ async function* decodeSseStream(chunks) {
106
106
  }
107
107
  const tail = buffer.trim();
108
108
  if (tail.length > 0) {
109
+ if (options.requireTerminator) throw new IncompleteSseFrameError("Stream ended during an SSE frame.");
109
110
  let parsed;
110
111
  try {
111
112
  parsed = parseFrame(tail);
@@ -128,8 +129,8 @@ function parseFrame(raw) {
128
129
  try {
129
130
  return JSON.parse(dataLines.join("\n"));
130
131
  } catch (error) {
131
- const message = error instanceof Error ? error.message : String(error);
132
- throw new Error(`Malformed SSE data frame: ${message}`);
132
+ const message2 = error instanceof Error ? error.message : String(error);
133
+ throw new Error(`Malformed SSE data frame: ${message2}`);
133
134
  }
134
135
  }
135
136
  var IncompleteSseFrameError;
@@ -185,20 +186,20 @@ function validateHarnessEvent(rawEvent, invocationId) {
185
186
  );
186
187
  }
187
188
  }
188
- async function* invokeServer(input, options) {
189
+ async function* invokeServer(input2, options) {
189
190
  const fetchImpl = options.fetch ?? fetch;
190
191
  const invocationId = options.invocationId ?? createInvocationId();
191
192
  const response = await fetchImpl(buildRequestUrl(options), {
192
193
  method: "POST",
193
194
  headers: buildRequestHeaders(options),
194
- body: JSON.stringify({ invocationId, input }),
195
+ body: JSON.stringify({ invocationId, input: input2 }),
195
196
  signal: options.signal
196
197
  });
197
198
  if (!response.ok) {
198
- const text = await response.text().catch(() => "");
199
+ const text2 = await response.text().catch(() => "");
199
200
  throw new InvokeHttpError(
200
201
  response.status,
201
- `Server returned ${response.status}${text ? `: ${text}` : ""}`
202
+ `Server returned ${response.status}${text2 ? `: ${text2}` : ""}`
202
203
  );
203
204
  }
204
205
  if (!response.body) {
@@ -206,7 +207,7 @@ async function* invokeServer(input, options) {
206
207
  }
207
208
  const reader = response.body.getReader();
208
209
  const decoder = new TextDecoder();
209
- async function* chunks() {
210
+ async function* chunks2() {
210
211
  try {
211
212
  while (true) {
212
213
  const { value, done } = await reader.read();
@@ -220,7 +221,7 @@ async function* invokeServer(input, options) {
220
221
  }
221
222
  }
222
223
  }
223
- for await (const rawEvent of decodeSseStream(chunks())) {
224
+ for await (const rawEvent of decodeSseStream(chunks2())) {
224
225
  validateHarnessEvent(rawEvent, invocationId);
225
226
  if (rawEvent.kind === "frame" && options.frameSchema) {
226
227
  yield {
@@ -239,8 +240,8 @@ var init_invoke_client = __esm({
239
240
  init_sse_framing();
240
241
  init_protocol();
241
242
  InvokeHttpError = class extends Error {
242
- constructor(status, message) {
243
- super(message);
243
+ constructor(status, message2) {
244
+ super(message2);
244
245
  this.status = status;
245
246
  this.name = "InvokeHttpError";
246
247
  }
@@ -255,19 +256,21 @@ __export(src_exports, {
255
256
  ConfigurationError: () => ConfigurationError,
256
257
  DEFAULT_DEPENDENCIES: () => DEFAULT_DEPENDENCIES,
257
258
  DefinedAgent: () => DefinedAgent,
259
+ DefinedHostAgent: () => DefinedHostAgent,
258
260
  DeploymentError: () => DeploymentError,
259
261
  ExecutionError: () => ExecutionError,
260
262
  LegacyBundledAgent: () => LegacyBundledAgent,
261
263
  NeckbeardError: () => NeckbeardError,
264
+ RemoteAdmissionRejected: () => RemoteAdmissionRejected,
265
+ RemoteSubmissionNotFound: () => RemoteSubmissionNotFound,
262
266
  RuntimeBusyError: () => RuntimeBusyError,
263
267
  SKILLS_DIR: () => SKILLS_DIR,
264
268
  SandboxClient: () => SandboxClient,
269
+ SandboxGoneError: () => SandboxGoneError,
265
270
  TURN_PROTOCOL_VERSION: () => TURN_PROTOCOL_VERSION,
266
- TurnLostError: () => TurnLostError,
267
271
  ValidationError: () => ValidationError,
268
272
  defineAgent: () => defineAgent,
269
273
  destroyProviderSandbox: () => destroyProviderSandbox,
270
- getPiTurnResult: () => getPiTurnResult,
271
274
  isDefinedAgent: () => isDefinedAgent,
272
275
  normalizeStackFramePath: () => normalizeStackFramePath,
273
276
  resolveAgentSourceFile: () => resolveAgentSourceFile,
@@ -486,8 +489,8 @@ var AttachedAgentSessionImpl = class {
486
489
  get closed() {
487
490
  return this.isClosed;
488
491
  }
489
- prompt(input) {
490
- return this.runTurn(input);
492
+ prompt(input2) {
493
+ return this.runTurn(input2);
491
494
  }
492
495
  async stop(reason = "attached_session_stopped") {
493
496
  await this.stopActiveTurn(reason);
@@ -495,7 +498,7 @@ var AttachedAgentSessionImpl = class {
495
498
  close() {
496
499
  return this.closeWithReason("attached_session_closed");
497
500
  }
498
- async *runTurn(input) {
501
+ async *runTurn(input2) {
499
502
  if (this.isClosed || this.lifetime.signal.aborted) {
500
503
  throw this.configurationError("Attached session is closed.");
501
504
  }
@@ -504,7 +507,7 @@ var AttachedAgentSessionImpl = class {
504
507
  }
505
508
  const controller = new AbortController();
506
509
  const linked = linkAbortSignals([this.lifetime.signal, controller.signal]);
507
- const iterator = this.runPrompt(input, linked.signal);
510
+ const iterator = this.runPrompt(input2, linked.signal);
508
511
  const turn = {
509
512
  controller,
510
513
  iterator,
@@ -618,29 +621,29 @@ function paxPathRecord(path2) {
618
621
  return import_node_buffer.Buffer.from(`${length}${body}`);
619
622
  }
620
623
  async function createTarGz(entries, mtime = Math.floor(Date.now() / 1e3)) {
621
- const chunks = [];
622
- for (const entry of entries) {
623
- const isDirectory = entry.content === void 0;
624
- const path2 = isDirectory ? `${entry.path.replace(/\/+$/u, "")}/` : entry.path;
625
- const size = entry.content?.byteLength ?? 0;
624
+ const chunks2 = [];
625
+ for (const entry2 of entries) {
626
+ const isDirectory = entry2.content === void 0;
627
+ const path2 = isDirectory ? `${entry2.path.replace(/\/+$/u, "")}/` : entry2.path;
628
+ const size = entry2.content?.byteLength ?? 0;
626
629
  const type = isDirectory ? "5" : "0";
627
630
  const mode = isDirectory ? 493 : 420;
628
631
  const split = splitUstarPath(path2);
629
632
  if (split) {
630
- chunks.push(header({ ...split, mode, size, mtime, type }));
633
+ chunks2.push(header({ ...split, mode, size, mtime, type }));
631
634
  } else {
632
635
  const record = paxPathRecord(path2);
633
- chunks.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
634
- chunks.push(record, padding(record.byteLength));
635
- chunks.push(header({ name: path2.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
636
+ chunks2.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
637
+ chunks2.push(record, padding(record.byteLength));
638
+ chunks2.push(header({ name: path2.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
636
639
  }
637
- if (entry.content) {
638
- chunks.push(import_node_buffer.Buffer.from(entry.content.buffer, entry.content.byteOffset, entry.content.byteLength));
639
- chunks.push(padding(size));
640
+ if (entry2.content) {
641
+ chunks2.push(import_node_buffer.Buffer.from(entry2.content.buffer, entry2.content.byteOffset, entry2.content.byteLength));
642
+ chunks2.push(padding(size));
640
643
  }
641
644
  }
642
- chunks.push(import_node_buffer.Buffer.alloc(BLOCK_SIZE * 2));
643
- return gzipAsync(import_node_buffer.Buffer.concat(chunks));
645
+ chunks2.push(import_node_buffer.Buffer.alloc(BLOCK_SIZE * 2));
646
+ return gzipAsync(import_node_buffer.Buffer.concat(chunks2));
644
647
  }
645
648
 
646
649
  // src/providers/detached-process.ts
@@ -3049,7 +3052,7 @@ function validateProviderCommand(label, command, options) {
3049
3052
  if (options.cwd !== void 0 && (typeof options.cwd !== "string" || !options.cwd.startsWith("/") || options.cwd.includes("\0")) || options.onStdout !== void 0 && typeof options.onStdout !== "function" || options.onStderr !== void 0 && typeof options.onStderr !== "function") {
3050
3053
  throw new Error(`${label} command cwd must be absolute and output callbacks must be functions.`);
3051
3054
  }
3052
- if (options.envs !== void 0) validateProviderEnvs(label, options.envs, (message) => new Error(message));
3055
+ if (options.envs !== void 0) validateProviderEnvs(label, options.envs, (message2) => new Error(message2));
3053
3056
  }
3054
3057
 
3055
3058
  // src/providers/daytona.ts
@@ -3242,11 +3245,21 @@ function settleOperation(operation, options = {}) {
3242
3245
  );
3243
3246
  });
3244
3247
  }
3245
- function withTimeout(task, timeoutMs, message) {
3248
+ function untilAborted(operation, signal) {
3249
+ if (signal?.aborted) return Promise.reject(abortError(signal));
3250
+ return settleOperation(operation, signal ? { abort: { signal, createError: () => abortError(signal) } } : {});
3251
+ }
3252
+ function abortError(signal) {
3253
+ if (signal.reason instanceof Error) return signal.reason;
3254
+ const error = new Error("Operation aborted.");
3255
+ error.name = "AbortError";
3256
+ return error;
3257
+ }
3258
+ function withTimeout(task, timeoutMs, message2) {
3246
3259
  return settleOperation(() => task, {
3247
3260
  timeout: {
3248
3261
  timeoutMs,
3249
- createError: () => new Error(message)
3262
+ createError: () => new Error(message2)
3250
3263
  }
3251
3264
  });
3252
3265
  }
@@ -3466,7 +3479,7 @@ function getModalSdk() {
3466
3479
  var MODAL_DEFAULT_TEMPLATE = "node:22-bookworm";
3467
3480
  var MODAL_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
3468
3481
  function parseModalAllowList(value) {
3469
- return (value ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
3482
+ return (value ?? "").split(",").map((entry2) => entry2.trim()).filter(Boolean);
3470
3483
  }
3471
3484
  function modalNetworkOptions(options) {
3472
3485
  if (options.networkBlockAll) return { blockNetwork: true };
@@ -3497,7 +3510,7 @@ function validateModalOptions(options, mode, failure) {
3497
3510
  throw failure("Modal networkBlockAll must be a boolean.");
3498
3511
  }
3499
3512
  for (const [key, value] of [["networkAllowList", networkAllowList], ["domainAllowList", domainAllowList]]) {
3500
- if (value !== void 0 && (typeof value !== "string" || parseModalAllowList(value).some((entry) => /[\s\0]/u.test(entry)))) {
3513
+ if (value !== void 0 && (typeof value !== "string" || parseModalAllowList(value).some((entry2) => /[\s\0]/u.test(entry2)))) {
3501
3514
  throw failure(`Modal ${key} must be a comma-separated string without whitespace or null bytes in entries.`);
3502
3515
  }
3503
3516
  }
@@ -3544,8 +3557,8 @@ async function sharedClient(credentials) {
3544
3557
  return client;
3545
3558
  }
3546
3559
  var ModalSandboxHandle = class _ModalSandboxHandle {
3547
- constructor(id, client, failure) {
3548
- this.id = id;
3560
+ constructor(id2, client, failure) {
3561
+ this.id = id2;
3549
3562
  this.client = client;
3550
3563
  this.detachedProcesses = new DetachedProcessController({
3551
3564
  provider: "modal",
@@ -3585,7 +3598,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3585
3598
  const network = modalNetworkOptions(options);
3586
3599
  const template = options.template ?? MODAL_DEFAULT_TEMPLATE;
3587
3600
  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([
3601
+ const image2 = options.command ? registryImage : registryImage.dockerfileCommands([
3589
3602
  "USER root",
3590
3603
  "RUN apt-get update && apt-get install -y --no-install-recommends bash python3 util-linux coreutils sudo curl ca-certificates && rm -rf /var/lib/apt/lists/*",
3591
3604
  // The runtime starts with a fixed PATH, so images with Node elsewhere (say nvm) need links.
@@ -3594,7 +3607,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3594
3607
  ...network.outboundDomainAllowlist ? ["RUN find /etc/apt -name '*.list' -o -name '*.sources' | xargs -r sed -i 's|http://|https://|g'"] : [],
3595
3608
  "WORKDIR /root"
3596
3609
  ]);
3597
- sandbox = await client.sandboxes.create(app, image, {
3610
+ sandbox = await client.sandboxes.create(app, image2, {
3598
3611
  ...network,
3599
3612
  ...options.regions ? { regions: options.regions } : {},
3600
3613
  timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
@@ -3602,7 +3615,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3602
3615
  memoryMiB: options.memoryMiB,
3603
3616
  ...options.command ? { command: options.command } : { workdir: "/root" },
3604
3617
  env: Object.fromEntries(Object.entries(options.envs ?? {}).filter(
3605
- (entry) => entry[1] !== void 0
3618
+ (entry2) => entry2[1] !== void 0
3606
3619
  ))
3607
3620
  // No tunnels: all HTTP access requires a port-scoped Connect Token.
3608
3621
  });
@@ -3620,16 +3633,22 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3620
3633
  });
3621
3634
  await new _ModalSandboxHandle(options.sandboxId, client, failure).destroy();
3622
3635
  }
3623
- static async connect(options, failure) {
3636
+ /** With `gone`, a sandbox Modal reports finished or unknown throws that failure instead. */
3637
+ static async connect(options, failure, gone) {
3624
3638
  const client = await sharedClient({
3625
3639
  tokenId: options.tokenId,
3626
3640
  tokenSecret: options.tokenSecret,
3627
3641
  environment: options.environment
3628
3642
  });
3629
3643
  const handle = new _ModalSandboxHandle(options.sandboxId, client, failure);
3630
- await handle.use(async (sandbox) => {
3631
- if (await sandbox.poll() !== null) throw failure("Modal sandbox is no longer running.");
3632
- });
3644
+ try {
3645
+ await handle.use(async (sandbox) => {
3646
+ if (await sandbox.poll() !== null) throw (gone ?? failure)("Modal sandbox is no longer running.");
3647
+ });
3648
+ } catch (error) {
3649
+ if (gone && isModalNotFound(error)) throw gone(`Modal sandbox ${options.sandboxId} does not exist.`, error);
3650
+ throw error;
3651
+ }
3633
3652
  return handle;
3634
3653
  }
3635
3654
  async use(operation, timeoutMs) {
@@ -3727,53 +3746,55 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
3727
3746
  });
3728
3747
  }
3729
3748
  async destroy() {
3730
- const { NotFoundError } = getModalSdk();
3731
3749
  try {
3732
3750
  await this.use(async (sandbox) => {
3733
3751
  await sandbox.terminate({ wait: true });
3734
3752
  });
3735
3753
  } catch (error) {
3736
- const grpcNotFound = error instanceof Error && error.name === "ClientError" && Reflect.get(error, "code") === 5;
3737
- if (!(error instanceof NotFoundError) && !grpcNotFound) throw error;
3754
+ if (!isModalNotFound(error)) throw error;
3738
3755
  }
3739
3756
  }
3740
3757
  };
3758
+ function isModalNotFound(error) {
3759
+ return error instanceof getModalSdk().NotFoundError || error instanceof Error && error.name === "ClientError" && Reflect.get(error, "code") === 5;
3760
+ }
3741
3761
 
3742
3762
  // src/define.ts
3743
- var import_promises = require("fs/promises");
3744
- var import_node_os = __toESM(require("os"), 1);
3745
3763
  var import_node_path = __toESM(require("path"), 1);
3746
3764
 
3747
- // src/agent.ts
3748
- var import_node_crypto3 = require("crypto");
3749
- init_sse_framing();
3765
+ // src/image-tag.ts
3766
+ var IMAGE_TAG_ENV_VARS = [
3767
+ "NECKBEARD_IMAGE_TAG",
3768
+ "GITHUB_SHA",
3769
+ "CI_COMMIT_SHA",
3770
+ "BITBUCKET_COMMIT",
3771
+ "CODEBUILD_RESOLVED_SOURCE_VERSION",
3772
+ "BUILDKITE_COMMIT",
3773
+ "CIRCLE_SHA1",
3774
+ "CF_PAGES_COMMIT_SHA",
3775
+ "HEROKU_BUILD_COMMIT",
3776
+ "HEROKU_SLUG_COMMIT",
3777
+ "RAILWAY_GIT_COMMIT_SHA",
3778
+ "RENDER_GIT_COMMIT",
3779
+ "VERCEL_GIT_COMMIT_SHA",
3780
+ "SOURCE_VERSION",
3781
+ "GIT_COMMIT"
3782
+ ];
3783
+ function resolveImageTag(env = process.env) {
3784
+ for (const name of IMAGE_TAG_ENV_VARS) {
3785
+ const value = env[name]?.trim();
3786
+ if (value && value !== name) return value;
3787
+ }
3788
+ return void 0;
3789
+ }
3750
3790
 
3751
3791
  // src/turn-protocol.ts
3752
- var TURN_PROTOCOL_VERSION = 2;
3792
+ var TURN_PROTOCOL_VERSION = 6;
3793
+ var STARTUP_ENV_KEYS = "NECKBEARD_STARTUP_ENV_KEYS";
3753
3794
  var MAX_TURN_REQUEST_BYTES = 4 * 1024 * 1024;
3754
- var MAX_TURN_ID_LENGTH = 200;
3755
3795
  function isRecord2(value) {
3756
3796
  return typeof value === "object" && value !== null && !Array.isArray(value);
3757
3797
  }
3758
- function parseTurnRecord(record) {
3759
- if (!isRecord2(record)) throw new Error("Turn record must be an object.");
3760
- const { seq } = record;
3761
- if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0) {
3762
- throw new Error("Turn record seq must be a non-negative integer.");
3763
- }
3764
- if (record.type === "event" && "event" in record) {
3765
- return { seq, type: "event", event: record.event };
3766
- }
3767
- if (record.type === "end" && (record.outcome === "completed" || record.outcome === "aborted" || record.outcome === "failed") && (record.error === void 0 || typeof record.error === "string")) {
3768
- return {
3769
- seq,
3770
- type: "end",
3771
- outcome: record.outcome,
3772
- ...record.error === void 0 ? {} : { error: record.error }
3773
- };
3774
- }
3775
- throw new Error("Turn record has an unknown shape.");
3776
- }
3777
3798
  function parseTurnHealth(value) {
3778
3799
  if (!isRecord2(value)) throw new Error("Health response must be an object.");
3779
3800
  const { ok, protocolVersion, busy, turnId } = value;
@@ -3782,55 +3803,360 @@ function parseTurnHealth(value) {
3782
3803
  }
3783
3804
  return { ok, protocolVersion, busy, turnId };
3784
3805
  }
3785
- function readAssistantMessageEnd(event) {
3786
- if (!isRecord2(event) || event.type !== "message_end" || !isRecord2(event.message)) return void 0;
3787
- const { role, content, stopReason, errorMessage: errorMessage2 } = event.message;
3788
- if (role !== "assistant") return void 0;
3789
- const text = (Array.isArray(content) ? content : []).flatMap((block) => isRecord2(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n").trim();
3790
- return {
3791
- text,
3792
- stopReason: typeof stopReason === "string" ? stopReason : void 0,
3793
- errorMessage: typeof errorMessage2 === "string" ? errorMessage2 : void 0
3794
- };
3806
+
3807
+ // src/conversation-records.ts
3808
+ var string = (v) => typeof v === "string";
3809
+ var number = (v) => typeof v === "number" && Number.isFinite(v);
3810
+ var bool = (v) => typeof v === "boolean";
3811
+ var id = (v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0;
3812
+ var absent = (v) => v === void 0;
3813
+ var optional = (check) => (v) => v === void 0 || check(v);
3814
+ var array = (check) => (v) => Array.isArray(v) && v.every(check);
3815
+ var values = (check) => (v) => isRecord2(v) && Object.values(v).every(check);
3816
+ var oneOf = (...options) => (v) => typeof v === "string" && options.includes(v);
3817
+ var shape = (fields) => (v) => isRecord2(v) && Object.entries(fields).every(([key, check]) => check(v[key]));
3818
+ var input = shape({
3819
+ id,
3820
+ conversationId: id,
3821
+ requestId: optional(string),
3822
+ trace: optional(values(string)),
3823
+ notify: optional(shape({ taskId: id, key: string }))
3824
+ });
3825
+ function isInputRecord(v) {
3826
+ if (!isRecord2(v) || v.type !== "input" || !input(v)) return false;
3827
+ if (v.status === "unanswered") return optional(id)(v.entry) && absent(v.answer) && string(v.reason);
3828
+ if (v.reason !== void 0 || v.detail !== void 0) return false;
3829
+ switch (v.status) {
3830
+ case "queued":
3831
+ return absent(v.entry) && absent(v.answer);
3832
+ case "placed":
3833
+ return id(v.entry) && absent(v.answer);
3834
+ case "done":
3835
+ return id(v.entry) && id(v.answer);
3836
+ default:
3837
+ return false;
3838
+ }
3795
3839
  }
3796
- function getPiTurnResult(records) {
3797
- let end;
3798
- let message;
3799
- for (const record of records) {
3800
- if (record.type === "end") {
3801
- end = record;
3802
- continue;
3803
- }
3804
- message = readAssistantMessageEnd(record.event) ?? message;
3840
+ var text = shape({ type: oneOf("text"), text: string, textSignature: optional(string) });
3841
+ var image = shape({ type: oneOf("image"), data: string, mimeType: string });
3842
+ var thinking = shape({ type: oneOf("thinking"), thinking: string, thinkingSignature: optional(string), redacted: optional(bool) });
3843
+ var toolCall = shape({
3844
+ type: oneOf("toolCall"),
3845
+ id: string,
3846
+ name: string,
3847
+ arguments: isRecord2,
3848
+ thoughtSignature: optional(string),
3849
+ namespace: optional(string),
3850
+ argumentsError: optional(string)
3851
+ });
3852
+ var tokens = { input: number, output: number, cacheRead: number, cacheWrite: number };
3853
+ var usage = shape({
3854
+ ...tokens,
3855
+ totalTokens: number,
3856
+ cacheWrite1h: optional(number),
3857
+ reasoning: optional(number),
3858
+ cost: shape({ ...tokens, total: number, totalFromProvider: optional(bool) })
3859
+ });
3860
+ var diagnostic = shape({
3861
+ type: string,
3862
+ timestamp: number,
3863
+ details: optional(isRecord2),
3864
+ error: optional(shape({ name: optional(string), message: string, stack: optional(string), code: optional((v) => string(v) || number(v)) }))
3865
+ });
3866
+ var assistant = shape({
3867
+ api: string,
3868
+ provider: string,
3869
+ model: string,
3870
+ content: array((v) => text(v) || thinking(v) || toolCall(v)),
3871
+ usage,
3872
+ stopReason: oneOf("pending", "stop", "length", "toolUse", "error", "aborted", "deferred"),
3873
+ responseModel: optional(string),
3874
+ responseId: optional(string),
3875
+ providerThinkingLevel: optional(string),
3876
+ thinkingLevel: optional(oneOf("off", "minimal", "low", "medium", "high", "xhigh", "max")),
3877
+ diagnostics: optional(array(diagnostic)),
3878
+ errorMessage: optional(string),
3879
+ rawStopReason: optional(string),
3880
+ endTurn: optional(bool),
3881
+ durationMs: optional(number),
3882
+ deferred: optional(shape({ provider: string, modelId: string, api: string, id: string, expiresAt: optional(number), pollAfterMs: optional(number) }))
3883
+ });
3884
+ var constrainedSampling = (v) => v === false || isRecord2(v) && (v.type === "json_schema" && oneOf("prefer", "require")(v.strict) || v.type === "grammar" && isRecord2(v.variants) && optional(string)(v.variants.openai_lark) && optional(string)(v.variants.openai_regex));
3885
+ var system = shape({
3886
+ content: (v) => string(v) || array(text)(v),
3887
+ sections: optional(values((v) => v === null || string(v))),
3888
+ toolsAdded: optional(array(shape({ name: string, description: string, parameters: (v) => typeof v === "object" && v !== null, constrainedSampling: optional(constrainedSampling) }))),
3889
+ toolsRemoved: optional(array(shape({ name: string })))
3890
+ });
3891
+ var media = array((v) => text(v) || image(v));
3892
+ var toolResult = shape({
3893
+ toolCallId: string,
3894
+ toolName: string,
3895
+ content: media,
3896
+ isError: bool,
3897
+ usage: optional(usage),
3898
+ durationMs: optional(number),
3899
+ nestedCalls: optional(shape({ complete: bool, calls: array(shape({
3900
+ id: string,
3901
+ name: string,
3902
+ arguments: optional(isRecord2),
3903
+ argumentsBytes: optional(number),
3904
+ status: oneOf("ok", "error", "unfinished"),
3905
+ durationMs: optional(number),
3906
+ error: optional(string)
3907
+ })) }))
3908
+ });
3909
+ function message(v) {
3910
+ if (!isRecord2(v) || !number(v.timestamp)) return false;
3911
+ switch (v.role) {
3912
+ case "user":
3913
+ return string(v.content) || media(v.content);
3914
+ case "system":
3915
+ return system(v);
3916
+ case "assistant":
3917
+ return assistant(v);
3918
+ case "toolResult":
3919
+ return toolResult(v);
3920
+ default:
3921
+ return false;
3805
3922
  }
3806
- if (!end) return { completed: false, error: "The agent turn has not ended." };
3807
- if (end.outcome !== "completed") {
3808
- return { completed: false, error: end.error ?? `The agent turn was ${end.outcome}.` };
3923
+ }
3924
+ var messages = array(message);
3925
+ var edit = (v) => isRecord2(v) && id(v.target) && (v.action === "omit" && absent(v.messages) || v.action === "replace" && messages(v.messages));
3926
+ var entry = shape({ id, conversationId: id, kind: string, head: optional(id), byTaskId: optional(id), model: optional(messages), edits: optional(array(edit)) });
3927
+ function isEntryRecord(v) {
3928
+ return entry(v);
3929
+ }
3930
+
3931
+ // src/remote-conversation.ts
3932
+ init_sse_framing();
3933
+ async function* chunks(reader) {
3934
+ const decoder = new TextDecoder();
3935
+ for (; ; ) {
3936
+ const part = await reader.read();
3937
+ if (part.done) break;
3938
+ yield decoder.decode(part.value, { stream: true });
3809
3939
  }
3810
- if (!message) return { completed: false, error: "The agent did not reply." };
3811
- if (message.stopReason !== "stop") {
3940
+ yield decoder.decode();
3941
+ }
3942
+ var RemoteAdmissionRejected = class extends Error {
3943
+ };
3944
+ var RemoteSubmissionNotFound = class extends Error {
3945
+ };
3946
+ function remoteConversation(request) {
3947
+ async function send(path2, data, signal, stream = false) {
3948
+ const response = await request("/conversation/" + path2, data, signal, stream);
3949
+ if (!response.ok) {
3950
+ const body = await response.json();
3951
+ const message2 = isRecord2(body) && typeof body.error === "string" ? body.error : "Remote conversation request failed.";
3952
+ if (path2 === "submit" && isRecord2(body) && body.code === "request_rejected" && [400, 409].includes(response.status)) {
3953
+ const error = new RemoteAdmissionRejected(message2);
3954
+ if (typeof body.name === "string") error.name = body.name;
3955
+ throw error;
3956
+ }
3957
+ if (response.status === 404 && isRecord2(body) && body.code === "submission_missing")
3958
+ throw new RemoteSubmissionNotFound(message2);
3959
+ const err = new Error(message2);
3960
+ throw err;
3961
+ }
3962
+ return response;
3963
+ }
3964
+ async function rpc(path2, data, ctx) {
3965
+ for (; ; ) {
3966
+ const response = await send(path2, data, ctx.abortSignal);
3967
+ const result = await response.json();
3968
+ if (response.status !== 202) return result;
3969
+ if (path2 !== "wait" && path2 !== "idle" || !isRecord2(result) || result.pending !== true)
3970
+ throw new Error("Invalid pending response.");
3971
+ }
3972
+ }
3973
+ function handle(value) {
3974
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
3975
+ throw new Error("Invalid remote submission ID.");
3976
+ const id2 = value;
3977
+ async function record(op, ctx) {
3978
+ const data = await rpc(op, { id: id2 }, ctx);
3979
+ if (!isInputRecord(data) || data.id !== id2) throw new Error("Invalid remote input record.");
3980
+ return data;
3981
+ }
3812
3982
  return {
3813
- completed: false,
3814
- error: message.errorMessage?.trim() || `The agent stopped with ${message.stopReason ?? "no reason"}.`
3983
+ id: id2,
3984
+ status: (ctx) => record("status", ctx),
3985
+ async wait(ctx) {
3986
+ const r = await record("wait", ctx);
3987
+ if (r.status !== "done" && r.status !== "unanswered") throw new Error("Expected settled input.");
3988
+ return r;
3989
+ },
3990
+ async abort(ctx) {
3991
+ const result = await rpc("withdraw", { id: id2 }, ctx);
3992
+ if (result !== "already_placed" && result !== "aborted" && result !== "settled")
3993
+ throw new Error("Invalid withdrawal response.");
3994
+ return result;
3995
+ }
3815
3996
  };
3816
3997
  }
3817
- return { completed: true, text: message.text || null };
3998
+ return {
3999
+ submit: async (draft, ctx) => handle(await rpc("submit", { draft }, ctx)),
4000
+ async submissionByRequest(requestId, ctx) {
4001
+ const id2 = await rpc("lookup", { requestId }, ctx);
4002
+ return id2 === null ? void 0 : handle(id2);
4003
+ },
4004
+ async entry(id2, ctx) {
4005
+ const data = await rpc("entry", { id: id2 }, ctx);
4006
+ if (data === null) return void 0;
4007
+ if (!isEntryRecord(data) || data.id !== id2) throw new Error("Invalid remote entry.");
4008
+ return data;
4009
+ },
4010
+ async stopSubmission(id2, ctx) {
4011
+ await rpc("stop", { id: id2 }, ctx);
4012
+ },
4013
+ async abort(ctx, options) {
4014
+ await rpc("abort", options ?? {}, ctx);
4015
+ },
4016
+ async waitForIdle(ctx) {
4017
+ await rpc("idle", {}, ctx);
4018
+ },
4019
+ async watch(ctx, window) {
4020
+ const contextEntry = "@earendil-works/chord/context";
4021
+ const { withoutAbortSignal } = await import(
4022
+ /* webpackIgnore: true */
4023
+ contextEntry
4024
+ );
4025
+ const callbackContext = withoutAbortSignal(ctx);
4026
+ const controller = new AbortController();
4027
+ const signal = ctx.abortSignal ? AbortSignal.any([ctx.abortSignal, controller.signal]) : controller.signal;
4028
+ const res = await send("watch", { window }, signal, true);
4029
+ if (!res.body) throw new Error("Missing watch stream.");
4030
+ const reader = res.body.getReader();
4031
+ void reader.closed.catch((error) => controller.abort(error));
4032
+ const frames = decodeSseStream(chunks(reader), { requireTerminator: true });
4033
+ const opened = await (async () => {
4034
+ const first = await frames.next();
4035
+ if (first.done || first.value.seq !== 0 || !first.value.frame?.opened || !first.value.frame.value) {
4036
+ throw new Error("Missing initial watch value.");
4037
+ }
4038
+ return { id: first.value.frame.opened, value: first.value.frame.value };
4039
+ })().catch((error) => {
4040
+ controller.abort();
4041
+ throw error;
4042
+ });
4043
+ const id2 = opened.id;
4044
+ let value = opened.value;
4045
+ let listener;
4046
+ let start;
4047
+ const started = new Promise((resolve2) => {
4048
+ start = resolve2;
4049
+ });
4050
+ let stopping = false;
4051
+ let ended = false;
4052
+ function interruption() {
4053
+ return ctx.abortSignal?.aborted ? { kind: "aborted" } : { kind: "failed", error: signal.reason };
4054
+ }
4055
+ let onAbort;
4056
+ const interrupted = new Promise((resolve2) => {
4057
+ onAbort = () => {
4058
+ start();
4059
+ resolve2(interruption());
4060
+ };
4061
+ if (signal.aborted) onAbort();
4062
+ else signal.addEventListener("abort", onAbort, { once: true });
4063
+ });
4064
+ let callbacks = Promise.resolve();
4065
+ let pending = 0;
4066
+ let failListener;
4067
+ const listenerFailed = new Promise((resolve2) => {
4068
+ failListener = resolve2;
4069
+ });
4070
+ const delivery = (async () => {
4071
+ try {
4072
+ let seq = 1;
4073
+ for await (const { seq: next, frame, exception } of frames) {
4074
+ if (next !== seq++) throw new Error("Watch delivery interrupted.");
4075
+ if (exception) {
4076
+ if (typeof exception.name !== "string" || typeof exception.message !== "string")
4077
+ throw new Error("Invalid watch exception.");
4078
+ const error = Object.assign(new Error(exception.message), { name: exception.name });
4079
+ if (frame.end?.kind === "failed" || frame.end?.kind === "listener_error")
4080
+ frame.end = { ...frame.end, error };
4081
+ else if (frame.call?.kind === "failed") frame.call = { ...frame.call, error };
4082
+ else throw new Error("Unexpected watch exception.");
4083
+ }
4084
+ if (frame.end) {
4085
+ if (!["stopped", "ended", "aborted", "failed", "listener_error"].includes(frame.end.kind))
4086
+ throw new Error("Invalid watch end.");
4087
+ if (frame.end.kind === "stopped" && !stopping)
4088
+ throw new Error("Watch stopped without a local stop request.");
4089
+ if (frame.end.kind === "stopped" || frame.end.kind === "ended") await callbacks;
4090
+ return frame.end;
4091
+ }
4092
+ const call = frame.call;
4093
+ if (!call || call.kind !== "failed" && (call.kind !== "value" || !Array.isArray(call.ops)))
4094
+ throw new Error("Invalid remote watch call.");
4095
+ if (++pending > 256) throw new Error("Watch listener fell behind by more than 256 callbacks.");
4096
+ callbacks = callbacks.then(async () => {
4097
+ if (!listener) await started;
4098
+ pending--;
4099
+ if (signal.aborted || ended || !listener) return;
4100
+ if (call.kind === "value") value = call.value;
4101
+ try {
4102
+ await listener(call, callbackContext);
4103
+ } catch (error) {
4104
+ failListener({ kind: "listener_error", error: error instanceof Error ? error : new Error(String(error)) });
4105
+ }
4106
+ });
4107
+ }
4108
+ throw new Error("Watch disconnected before its terminal frame.");
4109
+ } catch (error) {
4110
+ return ctx.abortSignal?.aborted ? { kind: "aborted" } : { kind: "failed", error };
4111
+ }
4112
+ })();
4113
+ const closed = Promise.race([delivery, interrupted, listenerFailed]).finally(() => {
4114
+ ended = true;
4115
+ start();
4116
+ signal.removeEventListener("abort", onAbort);
4117
+ controller.abort();
4118
+ reader.releaseLock();
4119
+ });
4120
+ return {
4121
+ get value() {
4122
+ return value;
4123
+ },
4124
+ closed,
4125
+ start(next) {
4126
+ if (listener || stopping || ended) throw new Error("Watch already started or closed.");
4127
+ listener = next;
4128
+ start();
4129
+ },
4130
+ async stop() {
4131
+ if (!stopping && !ended) {
4132
+ stopping = true;
4133
+ start();
4134
+ try {
4135
+ await send("stop-watch", { id: id2 }, signal);
4136
+ } catch (error) {
4137
+ controller.abort(error);
4138
+ }
4139
+ }
4140
+ return closed;
4141
+ }
4142
+ };
4143
+ }
4144
+ };
3818
4145
  }
3819
4146
 
3820
4147
  // src/agent.ts
4148
+ var import_node_crypto3 = require("crypto");
3821
4149
  var DEFAULT_COMMAND = ["node", "/app/agent.mjs"];
3822
4150
  var DEFAULT_PORT = 8080;
3823
4151
  var DEFAULT_START_TIMEOUT_MS = 12e4;
3824
4152
  var DEFAULT_PREPARE_TIMEOUT_MS = 30 * 6e4;
3825
- var DEFAULT_RECONNECT_TIMEOUT_MS = 12e4;
3826
4153
  var HEALTH_POLL_INTERVAL_MS = 500;
3827
- var RECONNECT_MIN_DELAY_MS = 250;
3828
- var RECONNECT_MAX_DELAY_MS = 5e3;
3829
4154
  var REQUEST_TIMEOUT_MS = 3e4;
3830
4155
  var ARTIFACT_PREFIX = "nb-";
3831
- function filterDefined(envs) {
3832
- return Object.fromEntries(Object.entries(envs ?? {}).filter(
3833
- (entry) => entry[1] !== void 0
4156
+ var RUNTIME_REJECTION_CODES = ["request_rejected", "submission_missing"];
4157
+ function filterDefined(env) {
4158
+ return Object.fromEntries(Object.entries(env ?? {}).filter(
4159
+ (entry2) => entry2[1] !== void 0
3834
4160
  ));
3835
4161
  }
3836
4162
  function delay2(ms, signal) {
@@ -3851,31 +4177,6 @@ function untilDeadline(deadline, signal) {
3851
4177
  const timeout = AbortSignal.timeout(Math.max(0, deadline - Date.now()));
3852
4178
  return signal ? AbortSignal.any([signal, timeout]) : timeout;
3853
4179
  }
3854
- function untilAborted(operation, signal) {
3855
- if (signal?.aborted) return Promise.reject(abortError(signal));
3856
- return settleOperation(operation, signal ? { abort: { signal, createError: () => abortError(signal) } } : {});
3857
- }
3858
- function abortError(signal) {
3859
- if (signal.reason instanceof Error) return signal.reason;
3860
- const error = new Error("Operation aborted.");
3861
- error.name = "AbortError";
3862
- return error;
3863
- }
3864
- async function* textChunks(body, onChunk) {
3865
- const decoder = new TextDecoder();
3866
- const reader = body.getReader();
3867
- try {
3868
- while (true) {
3869
- const { done, value } = await reader.read();
3870
- if (done) break;
3871
- onChunk();
3872
- yield decoder.decode(value, { stream: true });
3873
- }
3874
- } finally {
3875
- await reader.cancel().catch(() => void 0);
3876
- reader.releaseLock();
3877
- }
3878
- }
3879
4180
  var EndpointRejectedError = class extends Error {
3880
4181
  };
3881
4182
  var Agent = class {
@@ -3952,27 +4253,45 @@ var Agent = class {
3952
4253
  const preparing = this.preparing;
3953
4254
  return untilAborted(() => preparing, options.signal);
3954
4255
  }
3955
- /** Starts a sandbox from the image and waits for its runtime. Returns the sandbox ID. */
4256
+ /** Launches a sandbox. To reconnect to one, call `attach()`. */
3956
4257
  async start(options = {}) {
4258
+ if ("sandboxId" in options) throw new ConfigurationError("start() always launches a sandbox. Call attach(sandboxId) to reconnect to one.");
3957
4259
  await this.prepare({ ...options.signal ? { signal: options.signal } : {} });
3958
- const envs = {
3959
- ...filterDefined(this.options.envs),
3960
- ...filterDefined(options.envs),
4260
+ const startup = {
4261
+ ...filterDefined(this.options.env),
4262
+ ...filterDefined(options.env)
4263
+ };
4264
+ const env = {
4265
+ ...startup,
4266
+ [STARTUP_ENV_KEYS]: JSON.stringify(Object.keys(startup)),
3961
4267
  ...options.sessionId === void 0 ? {} : { NECKBEARD_SESSION_ID: options.sessionId },
3962
4268
  NECKBEARD_PORT: String(this.port)
3963
4269
  };
3964
4270
  if (options.signal?.aborted) throw abortError(options.signal);
3965
4271
  let sandbox;
4272
+ const creating = this.createSandbox(env);
3966
4273
  try {
3967
- sandbox = await this.createSandbox(envs);
4274
+ sandbox = await untilAborted(() => creating, options.signal);
3968
4275
  } catch (error) {
4276
+ if (options.signal?.aborted) {
4277
+ creating.then(
4278
+ (late) => late.destroy().catch((cleanupError) => {
4279
+ console.warn(`neckbeard: sandbox ${late.id} was created after its start was cancelled, and deleting it failed (${String(cleanupError)}); kill() it.`);
4280
+ }),
4281
+ () => void 0
4282
+ );
4283
+ throw error;
4284
+ }
3969
4285
  this.preparing = void 0;
3970
4286
  throw error;
3971
4287
  }
3972
4288
  try {
3973
- if (this.options.sandbox.provider === "e2b") await this.startE2bRuntime(this.options.sandbox, sandbox.id, envs);
4289
+ if (this.options.sandbox.provider === "e2b") {
4290
+ const e2b = this.options.sandbox;
4291
+ await untilAborted(() => this.startE2bRuntime(e2b, sandbox.id, env), options.signal);
4292
+ }
3974
4293
  await this.waitForRuntime(sandbox.id, options.signal);
3975
- return sandbox.id;
4294
+ return this.handle(sandbox.id);
3976
4295
  } catch (error) {
3977
4296
  this.endpoints.delete(sandbox.id);
3978
4297
  try {
@@ -3990,130 +4309,18 @@ var Agent = class {
3990
4309
  }
3991
4310
  }
3992
4311
  /**
3993
- * Starts a turn and streams its records until its `end` record. Starting a turn whose
3994
- * `turnId` the runtime already has resumes it instead of running it again.
3995
- */
3996
- async *prompt(sandboxId, turn, options = {}) {
3997
- const response = await this.request(sandboxId, "POST", "/turns", turn, options.signal);
3998
- if (response.status === 409) {
3999
- const body = await response.json().catch(() => ({}));
4000
- throw new RuntimeBusyError(`Sandbox ${sandboxId} is running another turn (${body.turnId ?? "unknown"}).`);
4001
- }
4002
- if (response.status !== 200 && response.status !== 202) {
4003
- throw new ExecutionError(`Starting turn ${turn.turnId} failed with ${response.status}: ${await response.text()}`);
4004
- }
4005
- await response.body?.cancel();
4006
- yield* this.events(sandboxId, turn.turnId, options);
4007
- }
4008
- /**
4009
- * Runs a Pi turn to its end and returns its final assistant text, or null when it had none.
4010
- * Throws `ExecutionError` when the turn did not complete or its model did not stop on its own.
4011
- * Running a turn again with the same `turnId` replays its records from the start.
4312
+ * Reconnects to a running sandbox by its provider ID, including while it is busy. Never creates,
4313
+ * starts or kills a sandbox, and admits no input.
4012
4314
  */
4013
- async run(sandboxId, turn, options = {}) {
4014
- const { onRecord, ...streamOptions } = options;
4015
- const records = [];
4016
- for await (const record of this.prompt(sandboxId, turn, streamOptions)) {
4017
- records.push(record);
4018
- await onRecord?.(record);
4019
- }
4020
- options.signal?.throwIfAborted();
4021
- const result = getPiTurnResult(records);
4022
- if (!result.completed) throw new ExecutionError(`Turn ${turn.turnId} did not finish: ${result.error}`);
4023
- return result.text;
4024
- }
4025
- /**
4026
- * Streams a turn's records after `options.after` until its `end` record, reconnecting when
4027
- * the connection drops. Throws `TurnLostError` when the runtime no longer has the turn.
4028
- */
4029
- async *events(sandboxId, turnId, options = {}) {
4030
- let last = options.after ?? -1;
4031
- const reconnectTimeoutMs = options.reconnectTimeoutMs ?? DEFAULT_RECONNECT_TIMEOUT_MS;
4032
- let failingSince;
4033
- let attempt = 0;
4034
- while (true) {
4035
- let lastError;
4036
- const stalled = new AbortController();
4037
- let watchdog;
4038
- const armWatchdog = () => {
4039
- clearTimeout(watchdog);
4040
- const budget = failingSince === void 0 ? reconnectTimeoutMs : Math.max(0, failingSince + reconnectTimeoutMs - Date.now());
4041
- watchdog = setTimeout(() => stalled.abort(new Error(`Turn stream sent nothing for ${budget}ms.`)), budget);
4042
- };
4043
- armWatchdog();
4044
- try {
4045
- const response = await this.request(
4046
- sandboxId,
4047
- "GET",
4048
- `/turns/${encodeURIComponent(turnId)}/events?after=${last}`,
4049
- void 0,
4050
- options.signal ? AbortSignal.any([options.signal, stalled.signal]) : stalled.signal,
4051
- { stream: true }
4052
- );
4053
- if (response.status === 404) {
4054
- await response.body?.cancel();
4055
- throw new TurnLostError(`Sandbox ${sandboxId} has no turn ${turnId}.`);
4056
- }
4057
- if (!response.ok || !response.body) {
4058
- await response.body?.cancel();
4059
- throw new Error(`Turn stream returned ${response.status}.`);
4060
- }
4061
- try {
4062
- const onChunk = () => {
4063
- failingSince = void 0;
4064
- armWatchdog();
4065
- };
4066
- for await (const frame of decodeSseStream(textChunks(response.body, onChunk))) {
4067
- let record;
4068
- try {
4069
- record = parseTurnRecord(frame);
4070
- } catch (error) {
4071
- const message = error instanceof Error ? error.message : String(error);
4072
- throw new ExecutionError(`Sandbox ${sandboxId} sent an invalid record for turn ${turnId}: ${message}`);
4073
- }
4074
- if (record.seq <= last) {
4075
- if (record.type === "end") return;
4076
- continue;
4077
- }
4078
- last = record.seq;
4079
- failingSince = void 0;
4080
- attempt = 0;
4081
- clearTimeout(watchdog);
4082
- yield record;
4083
- armWatchdog();
4084
- if (record.type === "end") return;
4085
- }
4086
- } catch (error) {
4087
- if (error instanceof Error && error.message.startsWith("Malformed SSE data frame")) {
4088
- throw new ExecutionError(`Sandbox ${sandboxId} sent a malformed frame for turn ${turnId}: ${error.message}`);
4089
- }
4090
- if (!(error instanceof IncompleteSseFrameError)) throw error;
4091
- }
4092
- lastError = new Error("Turn stream ended before the turn did.");
4093
- } catch (error) {
4094
- if (error instanceof TurnLostError || error instanceof ExecutionError) throw error;
4095
- if (options.signal?.aborted) throw abortError(options.signal);
4096
- if (error instanceof EndpointRejectedError) this.endpoints.delete(sandboxId);
4097
- lastError = stalled.signal.aborted ? stalled.signal.reason : error;
4098
- } finally {
4099
- clearTimeout(watchdog);
4100
- }
4101
- failingSince ??= Date.now();
4102
- if (Date.now() - failingSince > reconnectTimeoutMs) {
4103
- const message = lastError instanceof Error ? lastError.message : String(lastError);
4104
- throw new ExecutionError(`Lost the stream of turn ${turnId} for over ${reconnectTimeoutMs}ms: ${message}`);
4105
- }
4106
- attempt += 1;
4107
- await delay2(Math.min(RECONNECT_MAX_DELAY_MS, RECONNECT_MIN_DELAY_MS * 2 ** (attempt - 1)), options.signal);
4108
- }
4315
+ async attach(sandboxId, options = {}) {
4316
+ if (typeof sandboxId !== "string" || !sandboxId.trim()) throw new ConfigurationError("attach() requires a nonempty sandboxId.");
4317
+ this.endpoints.delete(sandboxId);
4318
+ this.requireProtocol(await this.health(sandboxId, options.signal));
4319
+ return this.handle(sandboxId);
4109
4320
  }
4110
- /** Asks the runtime to stop the turn; its stream then ends with an `aborted` record. */
4111
- async abort(sandboxId, turnId, signal) {
4112
- const response = await this.request(sandboxId, "POST", `/turns/${encodeURIComponent(turnId)}/abort`, void 0, signal);
4113
- await response.body?.cancel();
4114
- if (response.status !== 202 && response.status !== 404) {
4115
- throw new ExecutionError(`Aborting turn ${turnId} failed with ${response.status}.`);
4116
- }
4321
+ handle(sandboxId) {
4322
+ const conversation = remoteConversation((path2, data, signal, stream) => this.request(sandboxId, "POST", path2, data, signal, { stream }));
4323
+ return { sandboxId, conversation };
4117
4324
  }
4118
4325
  async health(sandboxId, signal) {
4119
4326
  const response = await this.request(sandboxId, "GET", "/health", void 0, signal);
@@ -4127,7 +4334,7 @@ var Agent = class {
4127
4334
  try {
4128
4335
  if (!(await this.health(sandboxId, untilDeadline(deadline, options.signal))).busy) return;
4129
4336
  } catch (error) {
4130
- if (options.signal?.aborted) throw error;
4337
+ if (options.signal?.aborted || error instanceof SandboxGoneError) throw error;
4131
4338
  }
4132
4339
  if (Date.now() > deadline) throw new RuntimeBusyError(`Sandbox ${sandboxId} did not become idle.`);
4133
4340
  await delay2(HEALTH_POLL_INTERVAL_MS, options.signal);
@@ -4150,15 +4357,18 @@ var Agent = class {
4150
4357
  }
4151
4358
  await destroyProviderSandbox({ provider: sandbox.provider, sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
4152
4359
  }
4153
- /** File and command access to a sandbox, for staging inputs and reading results. */
4360
+ /** File and command access to a sandbox, for staging inputs and reading results. Starts a stopped Daytona sandbox and resumes a paused E2B one. */
4154
4361
  sandbox(sandboxId) {
4362
+ return this.connect(sandboxId, true);
4363
+ }
4364
+ connect(sandboxId, wake) {
4155
4365
  const { sandbox } = this.options;
4156
4366
  if (sandbox.provider === "modal") {
4157
4367
  return SandboxClient.connect({
4158
4368
  provider: "modal",
4159
4369
  sandboxId,
4160
4370
  ...sandbox.environment ? { environment: sandbox.environment } : {}
4161
- });
4371
+ }, { wake });
4162
4372
  }
4163
4373
  if (sandbox.provider === "e2b") {
4164
4374
  return SandboxClient.connect({
@@ -4166,9 +4376,9 @@ var Agent = class {
4166
4376
  sandboxId,
4167
4377
  ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {},
4168
4378
  ...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
4169
- });
4379
+ }, { wake });
4170
4380
  }
4171
- return SandboxClient.connect({ provider: "daytona", sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
4381
+ return SandboxClient.connect({ provider: "daytona", sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} }, { wake });
4172
4382
  }
4173
4383
  /**
4174
4384
  * Deletes this agent's Daytona snapshots or E2B templates except the newest `keep` and the
@@ -4186,30 +4396,35 @@ var Agent = class {
4186
4396
  for (const artifact of stale) await artifact.delete();
4187
4397
  return stale.map((artifact) => artifact.name);
4188
4398
  }
4189
- createSandbox(envs) {
4399
+ createSandbox(env) {
4190
4400
  const { sandbox } = this.options;
4191
4401
  if (sandbox.provider === "modal") {
4192
4402
  const { provider: _provider, ...modal } = sandbox;
4193
- return SandboxClient.create({ provider: "modal", ...modal, template: this.image, command: this.command, envs });
4403
+ return SandboxClient.create({ provider: "modal", ...modal, template: this.image, command: this.command, envs: env });
4194
4404
  }
4195
4405
  if (sandbox.provider === "daytona") {
4196
4406
  const { resources: _resources, ...daytona } = sandbox;
4197
- return SandboxClient.create({ ...daytona, template: this.artifactName, envs });
4407
+ return SandboxClient.create({ ...daytona, template: this.artifactName, envs: env });
4198
4408
  }
4199
4409
  const { cpuCount: _cpuCount, memoryMB: _memoryMB, registry: _registry, ...e2b } = sandbox;
4200
- return SandboxClient.create({ ...e2b, template: this.artifactName, envs, allowPublicTraffic: false });
4410
+ return SandboxClient.create({ ...e2b, template: this.artifactName, envs: env, allowPublicTraffic: false });
4201
4411
  }
4202
4412
  // An E2B template's start command runs once at build time, without each sandbox's environment.
4203
- async startE2bRuntime(sandbox, sandboxId, envs) {
4413
+ async startE2bRuntime(sandbox, sandboxId, env) {
4204
4414
  const { Sandbox } = await import("e2b");
4205
4415
  const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
4206
4416
  const e2bSandbox = await Sandbox.connect(sandboxId, {
4207
4417
  ...apiKey ? { apiKey } : {},
4208
4418
  ...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
4209
4419
  });
4210
- const command = await e2bSandbox.commands.run(this.command.map(shellQuote).join(" "), { background: true, envs, timeoutMs: 0 });
4420
+ const command = await e2bSandbox.commands.run(this.command.map(shellQuote).join(" "), { background: true, envs: env, timeoutMs: 0 });
4211
4421
  await command.disconnect();
4212
4422
  }
4423
+ requireProtocol(health) {
4424
+ if (health.protocolVersion !== TURN_PROTOCOL_VERSION) {
4425
+ throw new DeploymentError(`Sandbox runtime speaks protocol ${health.protocolVersion}; this host speaks ${TURN_PROTOCOL_VERSION}.`);
4426
+ }
4427
+ }
4213
4428
  async waitForRuntime(sandboxId, signal) {
4214
4429
  const timeoutMs = this.options.startTimeoutMs ?? DEFAULT_START_TIMEOUT_MS;
4215
4430
  const deadline = Date.now() + timeoutMs;
@@ -4217,11 +4432,7 @@ var Agent = class {
4217
4432
  while (Date.now() < deadline) {
4218
4433
  try {
4219
4434
  const health = await this.health(sandboxId, untilDeadline(deadline, signal));
4220
- if (health.protocolVersion !== TURN_PROTOCOL_VERSION) {
4221
- throw new DeploymentError(
4222
- `Sandbox runtime speaks protocol ${health.protocolVersion}; this host speaks ${TURN_PROTOCOL_VERSION}.`
4223
- );
4224
- }
4435
+ this.requireProtocol(health);
4225
4436
  return;
4226
4437
  } catch (error) {
4227
4438
  if (error instanceof DeploymentError || signal?.aborted) throw error;
@@ -4229,13 +4440,15 @@ var Agent = class {
4229
4440
  }
4230
4441
  await delay2(HEALTH_POLL_INTERVAL_MS, signal);
4231
4442
  }
4232
- const message = lastError instanceof Error ? lastError.message : String(lastError);
4233
- throw new DeploymentError(`Runtime in sandbox ${sandboxId} did not answer within ${timeoutMs}ms: ${message}`);
4443
+ const message2 = lastError instanceof Error ? lastError.message : String(lastError);
4444
+ throw new DeploymentError(`Runtime in sandbox ${sandboxId} did not answer within ${timeoutMs}ms: ${message2}`);
4234
4445
  }
4446
+ // Runtime requests never start or resume a sandbox: its runtime would come back without the
4447
+ // turns it held in memory, and a repeated requestId would run again.
4235
4448
  endpoint(sandboxId) {
4236
4449
  let endpoint = this.endpoints.get(sandboxId);
4237
4450
  if (!endpoint) {
4238
- endpoint = this.sandbox(sandboxId).then((sandbox) => sandbox.getServerEndpoint(this.port));
4451
+ endpoint = this.connect(sandboxId, false).then((sandbox) => sandbox.getServerEndpoint(this.port));
4239
4452
  endpoint.catch(() => this.endpoints.delete(sandboxId));
4240
4453
  this.endpoints.set(sandboxId, endpoint);
4241
4454
  }
@@ -4243,21 +4456,37 @@ var Agent = class {
4243
4456
  }
4244
4457
  async request(sandboxId, method, path2, body, signal, options = {}) {
4245
4458
  for (let attempt = 0; ; attempt += 1) {
4246
- const endpoint = await untilAborted(() => this.endpoint(sandboxId), signal);
4459
+ const endpoint = await this.lookup(sandboxId, signal);
4247
4460
  const url = new URL(`${endpoint.url}${path2}`);
4248
4461
  for (const [name, value] of Object.entries(endpoint.query)) url.searchParams.set(name, value);
4249
4462
  const timeout = options.stream ? void 0 : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
4250
4463
  const signals = [signal, timeout].filter((value) => value !== void 0);
4251
- const response = await fetch(url, {
4252
- method,
4253
- headers: {
4254
- ...endpoint.headers,
4255
- ...body === void 0 ? {} : { "content-type": "application/json" },
4256
- ...options.stream ? { accept: "text/event-stream" } : {}
4257
- },
4258
- ...body === void 0 ? {} : { body: JSON.stringify(body) },
4259
- ...signals.length ? { signal: AbortSignal.any(signals) } : {}
4260
- });
4464
+ let response;
4465
+ try {
4466
+ response = await fetch(url, {
4467
+ method,
4468
+ headers: {
4469
+ ...endpoint.headers,
4470
+ ...body === void 0 ? {} : { "content-type": "application/json" },
4471
+ ...options.stream ? { accept: "text/event-stream" } : {}
4472
+ },
4473
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
4474
+ ...signals.length ? { signal: AbortSignal.any(signals) } : {}
4475
+ });
4476
+ } catch (error) {
4477
+ if (!signal?.aborted) await this.throwIfGone(sandboxId, signal);
4478
+ throw error;
4479
+ }
4480
+ const rejection = response.ok ? void 0 : await response.clone().json().catch(() => void 0);
4481
+ const fromRuntime = typeof rejection === "object" && rejection !== null && RUNTIME_REJECTION_CODES.includes(Reflect.get(rejection, "code"));
4482
+ if (!response.ok && !fromRuntime && response.status !== 401 && response.status !== 403) {
4483
+ try {
4484
+ await this.throwIfGone(sandboxId, signal);
4485
+ } catch (error) {
4486
+ await response.body?.cancel();
4487
+ throw error;
4488
+ }
4489
+ }
4261
4490
  if (response.status === 401 || response.status === 403) {
4262
4491
  await response.body?.cancel();
4263
4492
  this.endpoints.delete(sandboxId);
@@ -4267,6 +4496,31 @@ var Agent = class {
4267
4496
  return response;
4268
4497
  }
4269
4498
  }
4499
+ // After a failed request, asks the provider whether the sandbox still runs, without waking it.
4500
+ // The request is not sent again, and any other answer leaves the original failure to the caller.
4501
+ // The caller's cancellation ends the wait, and a provider that does not answer within a request's
4502
+ // time is treated as unable to say.
4503
+ async throwIfGone(sandboxId, signal) {
4504
+ this.endpoints.delete(sandboxId);
4505
+ try {
4506
+ await this.lookup(sandboxId, signal);
4507
+ } catch (error) {
4508
+ if (error instanceof SandboxGoneError || signal?.aborted) throw error;
4509
+ }
4510
+ }
4511
+ // Callers share one provider lookup per sandbox, so each waits on it within its own signal and a
4512
+ // request's time. A lookup that outlasts that is dropped, so the next caller starts a new one.
4513
+ async lookup(sandboxId, signal) {
4514
+ const bound = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
4515
+ const pending = this.endpoint(sandboxId);
4516
+ try {
4517
+ return await untilAborted(() => pending, signal ? AbortSignal.any([signal, bound]) : bound);
4518
+ } catch (error) {
4519
+ if (signal?.aborted || !bound.aborted) throw error;
4520
+ if (this.endpoints.get(sandboxId) === pending) this.endpoints.delete(sandboxId);
4521
+ throw new ExecutionError(`The provider did not resolve sandbox ${sandboxId}'s endpoint within ${REQUEST_TIMEOUT_MS}ms.`);
4522
+ }
4523
+ }
4270
4524
  async prepareDaytonaSnapshot(sandbox, options) {
4271
4525
  const { Daytona, DaytonaNotFoundError } = await import("@daytona/sdk");
4272
4526
  const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
@@ -4354,7 +4608,7 @@ var Agent = class {
4354
4608
  ...connection,
4355
4609
  ...sandbox.cpuCount === void 0 ? {} : { cpuCount: sandbox.cpuCount },
4356
4610
  ...sandbox.memoryMB === void 0 ? {} : { memoryMB: sandbox.memoryMB },
4357
- ...onLog ? { onBuildLogs: (entry) => onLog(entry.toString()) } : {}
4611
+ ...onLog ? { onBuildLogs: (entry2) => onLog(entry2.toString()) } : {}
4358
4612
  });
4359
4613
  }
4360
4614
  async listDaytonaSnapshots(sandbox, ownName) {
@@ -4404,11 +4658,7 @@ var Agent = class {
4404
4658
  // src/braintrust.ts
4405
4659
  var API_KEY = "BRAINTRUST_API_KEY";
4406
4660
  var PROJECT_NAME = "BRAINTRUST_PROJECT_NAME";
4407
- var FLUSH_TIMEOUT_MS = 1e4;
4408
- var BRAINTRUST_PACKAGE = "braintrust";
4409
- var BRAINTRUST_VERSIONS = ">=3.44.0 <4.0.0";
4410
- var warn = (message) => console.warn(`neckbeard: ${message}`);
4411
- var errorText = (error) => error instanceof Error ? error.message : String(error);
4661
+ var warn = (message2) => console.warn(`neckbeard: ${message2}`);
4412
4662
  function readBraintrustSettings(env, where) {
4413
4663
  const apiKey = env[API_KEY]?.trim();
4414
4664
  const projectName = env[PROJECT_NAME]?.trim();
@@ -4416,371 +4666,22 @@ function readBraintrustSettings(env, where) {
4416
4666
  if (apiKey) warn(`Braintrust logging isn't configured ${where}: ${PROJECT_NAME} is not set.`);
4417
4667
  return void 0;
4418
4668
  }
4419
- async function startBraintrust({ apiKey, projectName }) {
4420
- const notTracing = "Braintrust tracing is off in the sandbox";
4421
- let sdk;
4422
- try {
4423
- sdk = await import(
4424
- /* webpackIgnore: true */
4425
- BRAINTRUST_PACKAGE
4426
- );
4427
- } catch (error) {
4428
- if (errorText(error).includes(`Cannot find package '${BRAINTRUST_PACKAGE}'`)) {
4429
- warn(`${notTracing}: add ${BRAINTRUST_PACKAGE} ${BRAINTRUST_VERSIONS} to the agent's package's dependencies so the image has it.`);
4430
- } else {
4431
- warn(`${notTracing}: ${BRAINTRUST_PACKAGE} failed to load: ${errorText(error)}`);
4432
- }
4433
- return void 0;
4434
- }
4435
- if (typeof sdk.wrapPiCodingAgentSDK !== "function") {
4436
- warn(`${notTracing}: its ${BRAINTRUST_PACKAGE} can't trace Pi; use ${BRAINTRUST_VERSIONS}.`);
4437
- return void 0;
4438
- }
4439
- try {
4440
- sdk.initLogger({ projectName, apiKey });
4441
- } catch (error) {
4442
- warn(`${notTracing}: ${errorText(error)}`);
4443
- return void 0;
4444
- }
4445
- return {
4446
- wrapPi: (pi) => sdk.wrapPiCodingAgentSDK(pi),
4447
- async flush() {
4448
- try {
4449
- await withTimeout(sdk.flush(), FLUSH_TIMEOUT_MS, `not sent within ${FLUSH_TIMEOUT_MS / 1e3} seconds; it may arrive later`);
4450
- } catch (error) {
4451
- warn(`could not send the turn's Braintrust trace: ${errorText(error)}`);
4452
- }
4453
- }
4454
- };
4455
- }
4456
4669
 
4457
4670
  // src/serve.ts
4458
- var import_node_http = require("http");
4459
- var HEARTBEAT_INTERVAL_MS = 15e3;
4460
- var DEFAULT_ABORT_GRACE_MS = 1e4;
4461
- var DEFAULT_PORT2 = 8080;
4462
- function toPiJsonEvent(event) {
4463
- if (!isRecord2(event) || event.type !== "message_update") return event;
4464
- const { message, assistantMessageEvent } = event;
4465
- if (!isRecord2(message) || message.role !== "assistant") {
4466
- throw new Error("message_update message is not an assistant message");
4467
- }
4468
- if (!isRecord2(assistantMessageEvent) || typeof assistantMessageEvent.type !== "string") {
4469
- throw new Error("message_update has no assistantMessageEvent");
4470
- }
4471
- const { partial, ...delta } = assistantMessageEvent;
4472
- if (assistantMessageEvent.type === "toolcall_start") {
4473
- const { contentIndex } = assistantMessageEvent;
4474
- const content = isRecord2(partial) && Array.isArray(partial.content) ? partial.content : [];
4475
- const toolCall = typeof contentIndex === "number" ? content[contentIndex] : void 0;
4476
- if (!isRecord2(toolCall) || toolCall.type !== "toolCall" || typeof toolCall.id !== "string" || typeof toolCall.name !== "string") {
4477
- throw new Error(`toolcall_start content at index ${String(contentIndex)} is not a tool call`);
4478
- }
4479
- return {
4480
- type: "message_update",
4481
- usage: message.usage,
4482
- assistantMessageEvent: { ...delta, id: toolCall.id, toolName: toolCall.name }
4483
- };
4484
- }
4485
- return { type: "message_update", usage: message.usage, assistantMessageEvent: delta };
4486
- }
4487
- var RequestError = class extends Error {
4488
- constructor(status, message) {
4489
- super(message);
4490
- this.status = status;
4491
- }
4492
- };
4493
- function sendJson(response, status, body) {
4494
- response.writeHead(status, { "content-type": "application/json" });
4495
- response.end(JSON.stringify(body));
4496
- }
4497
- async function readJsonBody(request) {
4498
- const chunks = [];
4499
- let size = 0;
4500
- for await (const chunk of request) {
4501
- size += chunk.byteLength;
4502
- if (size > MAX_TURN_REQUEST_BYTES) throw new RequestError(413, "Request body is too large.");
4503
- chunks.push(chunk);
4504
- }
4505
- try {
4506
- return JSON.parse(Buffer.concat(chunks).toString("utf8"));
4507
- } catch {
4508
- throw new RequestError(400, "Request body must be JSON.");
4509
- }
4510
- }
4511
- function parseStartTurn(body) {
4512
- if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
4513
- const { turnId, message, env } = body;
4514
- if (typeof turnId !== "string" || !turnId || turnId.length > MAX_TURN_ID_LENGTH) {
4515
- throw new RequestError(400, `turnId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
4516
- }
4517
- if (typeof message !== "string" || !message.trim()) {
4518
- throw new RequestError(400, "message must be a non-empty string.");
4519
- }
4520
- if (env !== void 0 && (!env || typeof env !== "object" || Array.isArray(env) || Object.entries(env).some(([name, value]) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || typeof value !== "string"))) {
4521
- throw new RequestError(400, "env must map environment variable names to strings.");
4522
- }
4523
- return { turnId, message, ...env === void 0 ? {} : { env } };
4524
- }
4525
- async function serve(options) {
4526
- const toWireEvent = options.toWireEvent ?? toPiJsonEvent;
4527
- let sessionPromise;
4528
- let current;
4529
- let previous;
4530
- let currentSessionAbort;
4531
- const findTurn = (turnId) => current?.id === turnId ? current : previous?.id === turnId ? previous : void 0;
4532
- const append = (turn, record) => {
4533
- const json = JSON.stringify({ seq: turn.records.length, ...record });
4534
- turn.records.push(json);
4535
- for (const wake of turn.waiters) wake();
4536
- };
4537
- const end = (turn, outcome, error) => {
4538
- if (turn.ended) return;
4539
- append(turn, { type: "end", outcome, ...error === void 0 ? {} : { error } });
4540
- turn.ended = true;
4541
- };
4542
- const endAfterGrace = (turn, outcome, error) => {
4543
- if (turn.ended || turn.finishing || turn.forceEnd) return;
4544
- turn.forceEnd = setTimeout(() => end(turn, outcome, error), options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS);
4545
- };
4546
- const runTurn = async (turn, request) => {
4547
- const previousEnv = /* @__PURE__ */ new Map();
4548
- let unsubscribe;
4549
- let timedOut = false;
4550
- let session;
4551
- const timeoutMessage = `Turn exceeded ${options.maxTurnDurationMs}ms.`;
4552
- const timer = options.maxTurnDurationMs === void 0 ? void 0 : setTimeout(() => {
4553
- timedOut = true;
4554
- if (session) void session.abort().catch(() => void 0);
4555
- endAfterGrace(turn, "failed", timeoutMessage);
4556
- }, options.maxTurnDurationMs);
4557
- const finish = async (outcome, error) => {
4558
- turn.finishing = true;
4559
- if (timer) clearTimeout(timer);
4560
- clearTimeout(turn.forceEnd);
4561
- try {
4562
- await session?.afterTurn?.();
4563
- } catch {
4564
- }
4565
- end(turn, outcome, error);
4566
- };
4567
- try {
4568
- sessionPromise ??= options.createSession();
4569
- try {
4570
- session = await sessionPromise;
4571
- } catch (error) {
4572
- sessionPromise = void 0;
4573
- throw error;
4574
- }
4575
- if (timedOut) {
4576
- end(turn, "failed", timeoutMessage);
4577
- return;
4578
- }
4579
- const started = session;
4580
- for (const [name, value] of Object.entries(request.env ?? {})) {
4581
- previousEnv.set(name, process.env[name]);
4582
- process.env[name] = value;
4583
- }
4584
- unsubscribe = session.subscribe((event) => {
4585
- if (turn.ended) return;
4586
- try {
4587
- append(turn, { type: "event", event: toWireEvent(event) });
4588
- } catch (error) {
4589
- end(turn, "failed", `Could not convert an agent event: ${error instanceof Error ? error.message : String(error)}`);
4590
- void started.abort().catch(() => void 0);
4591
- }
4592
- });
4593
- currentSessionAbort = () => started.abort();
4594
- if (turn.abortRequested) {
4595
- end(turn, "aborted");
4596
- return;
4597
- }
4598
- await started.prompt(request.message);
4599
- if (timedOut) await finish("failed", timeoutMessage);
4600
- else await finish(turn.abortRequested ? "aborted" : "completed");
4601
- } catch (error) {
4602
- const message = error instanceof Error ? error.message : String(error);
4603
- if (timedOut) await finish("failed", timeoutMessage);
4604
- else await finish(turn.abortRequested ? "aborted" : "failed", turn.abortRequested ? void 0 : message);
4605
- } finally {
4606
- if (timer) clearTimeout(timer);
4607
- clearTimeout(turn.forceEnd);
4608
- unsubscribe?.();
4609
- currentSessionAbort = void 0;
4610
- for (const [name, value] of previousEnv) {
4611
- if (value === void 0) delete process.env[name];
4612
- else process.env[name] = value;
4613
- }
4614
- turn.settled = true;
4615
- }
4616
- };
4617
- const busy = () => Boolean(current && !current.settled);
4618
- const startTurn = async (request) => {
4619
- const existing = findTurn(request.turnId);
4620
- if (existing) return { status: 200, body: { turnId: existing.id, ended: existing.ended } };
4621
- if (current && !current.settled) {
4622
- return { status: 409, body: { error: "Another turn is running.", turnId: current.id } };
4623
- }
4624
- const turn = {
4625
- id: request.turnId,
4626
- records: [],
4627
- ended: false,
4628
- settled: false,
4629
- abortRequested: false,
4630
- finishing: false,
4631
- waiters: /* @__PURE__ */ new Set()
4632
- };
4633
- previous = current;
4634
- current = turn;
4635
- void runTurn(turn, request);
4636
- return { status: 202, body: { turnId: turn.id, ended: false } };
4637
- };
4638
- const streamTurn = async (turn, after, request, response) => {
4639
- response.writeHead(200, {
4640
- "content-type": "text/event-stream",
4641
- "cache-control": "no-cache, no-transform",
4642
- connection: "keep-alive",
4643
- "x-accel-buffering": "no"
4644
- });
4645
- response.write(": connected\n\n");
4646
- let closed = false;
4647
- let wake;
4648
- const onClose = () => {
4649
- closed = true;
4650
- wake?.();
4651
- };
4652
- request.on("close", onClose);
4653
- response.on("close", onClose);
4654
- const heartbeat = setInterval(() => {
4655
- if (!closed) response.write(": ping\n\n");
4656
- }, HEARTBEAT_INTERVAL_MS);
4657
- let next = turn.ended ? Math.min(after + 1, turn.records.length - 1) : after + 1;
4658
- try {
4659
- while (!closed) {
4660
- while (!closed && next < turn.records.length) {
4661
- const ok = response.write(`id: ${next}
4662
- data: ${turn.records[next]}
4663
-
4664
- `);
4665
- next += 1;
4666
- if (!ok && !closed) {
4667
- let onDrain;
4668
- await new Promise((resolve2) => {
4669
- wake = onDrain = resolve2;
4670
- response.once("drain", resolve2);
4671
- });
4672
- if (onDrain) response.off("drain", onDrain);
4673
- wake = void 0;
4674
- }
4675
- }
4676
- if (closed || turn.ended && next >= turn.records.length) break;
4677
- await new Promise((resolve2) => {
4678
- wake = resolve2;
4679
- turn.waiters.add(resolve2);
4680
- });
4681
- if (wake) turn.waiters.delete(wake);
4682
- wake = void 0;
4683
- }
4684
- } finally {
4685
- clearInterval(heartbeat);
4686
- request.off("close", onClose);
4687
- response.off("close", onClose);
4688
- if (!closed) response.end();
4689
- }
4690
- };
4691
- const server = (0, import_node_http.createServer)((request, response) => {
4692
- void (async () => {
4693
- const url = new URL(request.url ?? "/", "http://localhost");
4694
- const turnPath = /^\/turns\/([^/]+)\/(events|abort)$/u.exec(url.pathname);
4695
- if (request.method === "GET" && url.pathname === "/health") {
4696
- const health = {
4697
- ok: true,
4698
- protocolVersion: TURN_PROTOCOL_VERSION,
4699
- busy: busy(),
4700
- turnId: current?.id ?? null
4701
- };
4702
- return sendJson(response, 200, health);
4703
- }
4704
- if (request.method === "POST" && url.pathname === "/turns") {
4705
- const { status, body } = await startTurn(parseStartTurn(await readJsonBody(request)));
4706
- return sendJson(response, status, body);
4707
- }
4708
- if (turnPath) {
4709
- const turn = findTurn(decodeURIComponent(turnPath[1]));
4710
- if (!turn) return sendJson(response, 404, { error: "Unknown turn." });
4711
- if (request.method === "GET" && turnPath[2] === "events") {
4712
- const afterParam = url.searchParams.get("after");
4713
- const after = afterParam === null ? -1 : Number(afterParam);
4714
- if (!Number.isSafeInteger(after) || after < -1) {
4715
- return sendJson(response, 400, { error: "after must be an integer of at least -1." });
4716
- }
4717
- return streamTurn(turn, after, request, response);
4718
- }
4719
- if (request.method === "POST" && turnPath[2] === "abort") {
4720
- if (!turn.ended && !turn.finishing && !turn.abortRequested) {
4721
- turn.abortRequested = true;
4722
- if (turn === current) void currentSessionAbort?.().catch(() => void 0);
4723
- endAfterGrace(turn, "aborted");
4724
- }
4725
- return sendJson(response, 202, { turnId: turn.id, ended: turn.ended });
4726
- }
4727
- }
4728
- sendJson(response, 404, { error: "Not found." });
4729
- })().catch((error) => {
4730
- if (response.headersSent) {
4731
- response.destroy();
4732
- return;
4733
- }
4734
- const status = error instanceof RequestError ? error.status : 500;
4735
- sendJson(response, status, { error: error instanceof Error ? error.message : String(error) });
4736
- });
4737
- });
4738
- const port = options.port ?? (Number(process.env.NECKBEARD_PORT) || DEFAULT_PORT2);
4739
- await new Promise((resolve2, reject) => {
4740
- server.once("error", reject);
4741
- server.listen(port, options.host ?? "0.0.0.0", () => {
4742
- server.off("error", reject);
4743
- resolve2();
4744
- });
4745
- });
4746
- return {
4747
- port: server.address().port,
4748
- close: () => new Promise((resolve2, reject) => {
4749
- server.closeAllConnections();
4750
- server.close((error) => error ? reject(error) : resolve2());
4751
- })
4752
- };
4671
+ var insideEntry = "agent-neckbeard/inside";
4672
+ async function serve({ createSession, ...options }) {
4673
+ const inside = await import(
4674
+ /* webpackIgnore: true */
4675
+ insideEntry
4676
+ );
4677
+ return inside.serveConversation(createSession, options);
4753
4678
  }
4754
4679
 
4755
4680
  // src/define.ts
4756
4681
  var SKILLS_DIR = "/app/.agents/skills";
4757
- var IMAGE_TAG_ENV_VARS = [
4758
- "NECKBEARD_IMAGE_TAG",
4759
- "GITHUB_SHA",
4760
- "CI_COMMIT_SHA",
4761
- "BITBUCKET_COMMIT",
4762
- "CODEBUILD_RESOLVED_SOURCE_VERSION",
4763
- "BUILDKITE_COMMIT",
4764
- "CIRCLE_SHA1",
4765
- "CF_PAGES_COMMIT_SHA",
4766
- "HEROKU_BUILD_COMMIT",
4767
- "HEROKU_SLUG_COMMIT",
4768
- "RAILWAY_GIT_COMMIT_SHA",
4769
- "RENDER_GIT_COMMIT",
4770
- "VERCEL_GIT_COMMIT_SHA",
4771
- "SOURCE_VERSION",
4772
- "GIT_COMMIT"
4773
- ];
4774
- function resolveImageTag(env = process.env) {
4775
- for (const name of IMAGE_TAG_ENV_VARS) {
4776
- const value = env[name]?.trim();
4777
- if (value && value !== name) return value;
4778
- }
4779
- return void 0;
4780
- }
4781
- var PI_PACKAGE = "@earendil-works/pi-coding-agent";
4682
+ var insideEntry2 = "agent-neckbeard/inside";
4782
4683
  var definedAgentMarker = /* @__PURE__ */ Symbol.for("agent-neckbeard.DefinedAgent");
4783
- var DefinedAgent = class {
4684
+ var AgentImage = class {
4784
4685
  constructor(definition) {
4785
4686
  this.definition = definition;
4786
4687
  if (!definition || typeof definition !== "object") throw new ConfigurationError("Agent definition must be an object.");
@@ -4790,20 +4691,21 @@ var DefinedAgent = class {
4790
4691
  if (Boolean(definition.pi) === Boolean(definition.createSession)) {
4791
4692
  throw new ConfigurationError(`Agent ${definition.name} needs exactly one of pi and createSession.`);
4792
4693
  }
4694
+ if (definition.createSession && definition.maxTurnDurationMs !== void 0) {
4695
+ throw new ConfigurationError("Set the custom session deadline in openInsideConversation(pi, models, maxTurnDurationMs).");
4696
+ }
4793
4697
  if (!definition.image && !definition.registry) {
4794
4698
  throw new ConfigurationError(`Agent ${definition.name} needs a registry or an image.`);
4795
4699
  }
4796
4700
  }
4797
4701
  [definedAgentMarker] = true;
4798
- client;
4799
- braintrustChecked = false;
4800
4702
  get name() {
4801
4703
  return this.definition.name;
4802
4704
  }
4803
4705
  /** The image this host runs: `image`, else `<registry>/<name>:<tag>` with the tag `resolveImageTag()` finds. */
4804
4706
  imageRef(tag = resolveImageTag()) {
4805
- const { image, registry, name } = this.definition;
4806
- if (image) return image;
4707
+ const { image: image2, registry, name } = this.definition;
4708
+ if (image2) return image2;
4807
4709
  if (!tag) {
4808
4710
  throw new ConfigurationError(
4809
4711
  `Set NECKBEARD_IMAGE_TAG to choose agent ${name}'s image, or deploy from a platform that names the commit, such as RENDER_GIT_COMMIT.`
@@ -4811,16 +4713,37 @@ var DefinedAgent = class {
4811
4713
  }
4812
4714
  return `${registry.replace(/\/+$/u, "")}/${name}:${tag}`;
4813
4715
  }
4716
+ };
4717
+ var DefinedHostAgent = class extends AgentImage {
4718
+ constructor(definition) {
4719
+ super(definition);
4720
+ if (!definition.pi || definition.sandbox || definition.env) {
4721
+ throw new ConfigurationError("Harness-outside-sandbox mode requires pi and takes its storage and execution environment at startup.");
4722
+ }
4723
+ }
4724
+ async start(options, context) {
4725
+ const durableEntry = "agent-neckbeard/durable";
4726
+ const durable = await import(
4727
+ /* webpackIgnore: true */
4728
+ durableEntry
4729
+ );
4730
+ return durable.hostSession(this.definition, options, context);
4731
+ }
4732
+ };
4733
+ var DefinedAgent = class extends AgentImage {
4734
+ client;
4735
+ braintrustChecked = false;
4814
4736
  /** The `Agent` for an image, by default the one this host runs. */
4815
- forImage(image = this.imageRef()) {
4737
+ forImage(image2 = this.imageRef()) {
4816
4738
  const { definition } = this;
4817
4739
  const sandbox = typeof definition.sandbox === "function" ? definition.sandbox() : definition.sandbox;
4818
- const envs = typeof definition.envs === "function" ? definition.envs() : definition.envs;
4740
+ if (!sandbox) throw new ConfigurationError("An inside-sandbox agent needs a sandbox provider.");
4741
+ const env = typeof definition.env === "function" ? definition.env() : definition.env;
4819
4742
  return new Agent({
4820
4743
  name: definition.name,
4821
- image,
4744
+ image: image2,
4822
4745
  sandbox,
4823
- ...envs ? { envs } : {},
4746
+ ...env ? { env } : {},
4824
4747
  ...definition.command ? { command: definition.command } : {},
4825
4748
  ...definition.port === void 0 ? {} : { port: definition.port },
4826
4749
  ...definition.startTimeoutMs === void 0 ? {} : { startTimeoutMs: definition.startTimeoutMs },
@@ -4837,25 +4760,25 @@ var DefinedAgent = class {
4837
4760
  prepare(options) {
4838
4761
  return this.agent.prepare(options);
4839
4762
  }
4840
- start(options) {
4841
- if (this.definition.pi && !this.braintrustChecked) {
4763
+ async start(options) {
4764
+ const { pi } = this.definition;
4765
+ if (pi) {
4766
+ const sessionId = options?.sessionId;
4767
+ if (pi.persist && sessionId === void 0) throw new ConfigurationError(`Agent ${this.name} persists its session, so start() needs a sessionId.`);
4768
+ if (!pi.persist && sessionId !== void 0) throw new ConfigurationError(`Agent ${this.name} takes a sessionId only with pi.persist.`);
4769
+ if (sessionId !== void 0 && (typeof sessionId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(sessionId))) {
4770
+ throw new ConfigurationError("A sessionId may contain only letters, digits, underscores and dashes.");
4771
+ }
4772
+ }
4773
+ if (pi && !this.braintrustChecked) {
4842
4774
  this.braintrustChecked = true;
4843
- const envs = typeof this.definition.envs === "function" ? this.definition.envs() : this.definition.envs;
4844
- readBraintrustSettings({ ...filterDefined(envs), ...filterDefined(options?.envs) }, `for agent ${this.name}'s sandboxes`);
4775
+ const env = typeof this.definition.env === "function" ? this.definition.env() : this.definition.env;
4776
+ readBraintrustSettings({ ...filterDefined(env), ...filterDefined(options?.env) }, `for agent ${this.name}'s sandboxes`);
4845
4777
  }
4846
4778
  return this.agent.start(options);
4847
4779
  }
4848
- prompt(sandboxId, turn, options) {
4849
- return this.agent.prompt(sandboxId, turn, options);
4850
- }
4851
- run(sandboxId, turn, options) {
4852
- return this.agent.run(sandboxId, turn, options);
4853
- }
4854
- events(sandboxId, turnId, options) {
4855
- return this.agent.events(sandboxId, turnId, options);
4856
- }
4857
- abort(sandboxId, turnId, signal) {
4858
- return this.agent.abort(sandboxId, turnId, signal);
4780
+ attach(sandboxId, options) {
4781
+ return this.agent.attach(sandboxId, options);
4859
4782
  }
4860
4783
  health(sandboxId, signal) {
4861
4784
  return this.agent.health(sandboxId, signal);
@@ -4874,84 +4797,33 @@ var DefinedAgent = class {
4874
4797
  }
4875
4798
  /** Where a persisted session's file is in a sandbox whose home is `homeDir`, as for copying it out and back. */
4876
4799
  sessionFilePath(homeDir, sessionId) {
4877
- return import_node_path.default.posix.join(homeDir, "agent", ".pi", "sessions", `${sessionId}.jsonl`);
4800
+ return import_node_path.default.posix.join(homeDir, "agent", ".pi", "sessions", `${sessionId}.sqlite`);
4878
4801
  }
4879
4802
  /** Serves the agent's session; the image's entry point, which `neckbeard build` generates, calls it. */
4880
4803
  serve(options = {}) {
4881
4804
  const { definition } = this;
4882
4805
  const { pi } = definition;
4806
+ if (options.createSession && definition.maxTurnDurationMs !== void 0) {
4807
+ throw new ConfigurationError("A custom serve factory must set its own deadline. Remove the definition-level maxTurnDurationMs.");
4808
+ }
4883
4809
  return serve({
4884
- createSession: pi ? () => createPiSession(pi) : definition.createSession,
4885
- ...definition.maxTurnDurationMs === void 0 ? {} : { maxTurnDurationMs: definition.maxTurnDurationMs },
4886
- ...definition.abortGraceMs === void 0 ? {} : { abortGraceMs: definition.abortGraceMs },
4810
+ createSession: pi ? async () => (await import(
4811
+ /* webpackIgnore: true */
4812
+ insideEntry2
4813
+ )).openInsideConversation(pi, void 0, definition.maxTurnDurationMs) : definition.createSession,
4887
4814
  ...options
4888
4815
  });
4889
4816
  }
4890
4817
  };
4891
4818
  function defineAgent(definition) {
4892
- return new DefinedAgent(definition);
4819
+ if (definition && "placement" in definition) throw new ConfigurationError("Set mode instead of placement.");
4820
+ if (definition?.mode === "harness-outside-sandbox") return new DefinedHostAgent(definition);
4821
+ if (definition?.mode === "harness-inside-sandbox") return new DefinedAgent(definition);
4822
+ throw new ConfigurationError("Set mode to harness-inside-sandbox or harness-outside-sandbox.");
4893
4823
  }
4894
4824
  function isDefinedAgent(value) {
4895
4825
  return typeof value === "object" && value !== null && definedAgentMarker in value;
4896
4826
  }
4897
- async function createPiSession(config) {
4898
- const home = import_node_os.default.homedir();
4899
- const cwd = import_node_path.default.resolve(home, config.cwd ?? "workspace");
4900
- await (0, import_promises.mkdir)(cwd, { recursive: true });
4901
- process.env.NECKBEARD_CWD = cwd;
4902
- const agentDir = import_node_path.default.join(home, "agent", ".pi");
4903
- const loaded = await import(
4904
- /* webpackIgnore: true */
4905
- PI_PACKAGE
4906
- );
4907
- const braintrustSettings = readBraintrustSettings(process.env, "in the sandbox");
4908
- const braintrust = braintrustSettings && await startBraintrust(braintrustSettings);
4909
- const pi = braintrust ? braintrust.wrapPi(loaded) : loaded;
4910
- const modelRuntime = await pi.ModelRuntime.create({ modelsPath: null });
4911
- const separator = config.model.indexOf("/");
4912
- const model = separator > 0 ? modelRuntime.getModel(config.model.slice(0, separator), config.model.slice(separator + 1)) : void 0;
4913
- if (!model) throw new ConfigurationError(`Pi has no model ${config.model}; name it as provider/model.`);
4914
- const settingsManager = pi.SettingsManager.inMemory();
4915
- const resourceLoader = new pi.DefaultResourceLoader({
4916
- cwd,
4917
- agentDir,
4918
- settingsManager,
4919
- additionalSkillPaths: [SKILLS_DIR],
4920
- noSkills: true,
4921
- noExtensions: true,
4922
- noPromptTemplates: true,
4923
- noContextFiles: true,
4924
- systemPrompt: config.systemPrompt
4925
- });
4926
- await resourceLoader.reload();
4927
- let sessionManager;
4928
- if (config.persist) {
4929
- const sessionId = process.env.NECKBEARD_SESSION_ID;
4930
- if (!sessionId) throw new ConfigurationError("A persisted Pi session needs the sessionId passed to start().");
4931
- const sessionFile = import_node_path.default.join(agentDir, "sessions", `${sessionId}.jsonl`);
4932
- sessionManager = pi.SessionManager.open(sessionFile, import_node_path.default.dirname(sessionFile), cwd);
4933
- } else {
4934
- sessionManager = pi.SessionManager.inMemory(cwd);
4935
- }
4936
- const { session } = await pi.createAgentSession({
4937
- cwd,
4938
- agentDir,
4939
- model,
4940
- modelRuntime,
4941
- resourceLoader,
4942
- settingsManager,
4943
- sessionManager,
4944
- ...config.thinkingLevel ? { thinkingLevel: config.thinkingLevel } : {},
4945
- ...config.tools ? { tools: config.tools } : {}
4946
- });
4947
- if (!braintrust) return session;
4948
- return {
4949
- subscribe: (listener) => session.subscribe(listener),
4950
- prompt: (text) => session.prompt(text),
4951
- abort: () => session.abort(),
4952
- afterTurn: () => braintrust.flush()
4953
- };
4954
- }
4955
4827
 
4956
4828
  // src/providers/docker.ts
4957
4829
  var import_node_child_process = require("child_process");
@@ -4983,7 +4855,7 @@ function validateDockerOptions(options, mode, failure) {
4983
4855
  }
4984
4856
  }
4985
4857
  function exportLines(envs) {
4986
- return Object.entries(envs ?? {}).filter((entry) => entry[1] !== void 0).map(([name, value]) => `export ${name}=${shellQuote(value)}
4858
+ return Object.entries(envs ?? {}).filter((entry2) => entry2[1] !== void 0).map(([name, value]) => `export ${name}=${shellQuote(value)}
4987
4859
  `).join("");
4988
4860
  }
4989
4861
  var runDockerCli = (args, options) => new Promise((resolve2, reject) => {
@@ -5006,14 +4878,14 @@ var runDockerCli = (args, options) => new Promise((resolve2, reject) => {
5006
4878
  child.stdout.on("data", (chunk) => {
5007
4879
  stdout.push(chunk);
5008
4880
  if (options.onStdout) {
5009
- const text = stdoutDecoder.write(chunk);
5010
- if (text) options.onStdout(text);
4881
+ const text2 = stdoutDecoder.write(chunk);
4882
+ if (text2) options.onStdout(text2);
5011
4883
  }
5012
4884
  });
5013
4885
  child.stderr.on("data", (chunk) => {
5014
- const text = stderrDecoder.write(chunk);
5015
- stderr += text;
5016
- if (text) options.onStderr?.(text);
4886
+ const text2 = stderrDecoder.write(chunk);
4887
+ stderr += text2;
4888
+ if (text2) options.onStderr?.(text2);
5017
4889
  });
5018
4890
  child.on("error", (error) => settle(() => reject(
5019
4891
  Reflect.get(error, "code") === "ENOENT" ? new Error("The Docker provider requires the `docker` CLI on PATH.") : error
@@ -5088,8 +4960,8 @@ async function closeTunnels(containerId) {
5088
4960
  }
5089
4961
  }
5090
4962
  var DockerSandboxHandle = class _DockerSandboxHandle {
5091
- constructor(id, managed, failure, cli = runDockerCli) {
5092
- this.id = id;
4963
+ constructor(id2, managed, failure, cli = runDockerCli) {
4964
+ this.id = id2;
5093
4965
  this.managed = managed;
5094
4966
  this.failure = failure;
5095
4967
  this.cli = cli;
@@ -5141,11 +5013,11 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
5141
5013
  options.template ?? DOCKER_DEFAULT_TEMPLATE,
5142
5014
  String(lifetimeSeconds)
5143
5015
  ], { timeoutMs: DOCKER_CREATE_TIMEOUT_MS });
5144
- const id = created.stdout.toString("utf8").trim().split("\n").pop() ?? "";
5145
- if (created.exitCode !== 0 || !/^[a-f0-9]{12,64}$/u.test(id)) {
5016
+ const id2 = created.stdout.toString("utf8").trim().split("\n").pop() ?? "";
5017
+ if (created.exitCode !== 0 || !/^[a-f0-9]{12,64}$/u.test(id2)) {
5146
5018
  throw failure(`Failed to create Docker sandbox: ${created.stderr.trim() || "no container ID returned."}`);
5147
5019
  }
5148
- const handle = new _DockerSandboxHandle(id, true, failure, cli);
5020
+ const handle = new _DockerSandboxHandle(id2, true, failure, cli);
5149
5021
  try {
5150
5022
  await handle.writeFile(DOCKER_ENV_FILE, exportLines(options.envs));
5151
5023
  await handle.ensureTools();
@@ -5185,10 +5057,10 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
5185
5057
  DOCKER_BOOTSTRAP_TIMEOUT_MS
5186
5058
  );
5187
5059
  }
5188
- async control(label, script, args = [], input, timeoutMs = DOCKER_CONTROL_TIMEOUT_MS) {
5060
+ async control(label, script, args = [], input2, timeoutMs = DOCKER_CONTROL_TIMEOUT_MS) {
5189
5061
  const result = await this.cli(
5190
5062
  ["exec", "-i", "--user", "root", this.id, "/bin/sh", "-c", script, "sh", ...args],
5191
- { input, timeoutMs }
5063
+ { input: input2, timeoutMs }
5192
5064
  );
5193
5065
  if (result.exitCode !== 0) {
5194
5066
  throw this.failure(`${label} failed: ${result.stderr.trim() || `exit code ${result.exitCode}`}`);
@@ -5199,8 +5071,8 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
5199
5071
  await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path2]);
5200
5072
  }
5201
5073
  async writeFile(path2, content) {
5202
- const input = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
5203
- await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path2], input, DOCKER_FILE_TIMEOUT_MS);
5074
+ const input2 = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
5075
+ await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path2], input2, DOCKER_FILE_TIMEOUT_MS);
5204
5076
  }
5205
5077
  async readFile(path2) {
5206
5078
  return (await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
@@ -5280,49 +5152,49 @@ var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
5280
5152
  var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
5281
5153
  var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
5282
5154
  var NeckbeardError = class extends Error {
5283
- constructor(message) {
5284
- super(message);
5155
+ constructor(message2) {
5156
+ super(message2);
5285
5157
  this.name = "NeckbeardError";
5286
5158
  }
5287
5159
  };
5288
5160
  var DeploymentError = class extends NeckbeardError {
5289
5161
  /** A sandbox the failure left behind, for `kill()`. */
5290
- constructor(message, cause, sandboxId) {
5291
- super(message);
5162
+ constructor(message2, cause, sandboxId) {
5163
+ super(message2);
5292
5164
  this.cause = cause;
5293
5165
  this.sandboxId = sandboxId;
5294
5166
  this.name = "DeploymentError";
5295
5167
  }
5296
5168
  };
5169
+ var SandboxGoneError = class extends DeploymentError {
5170
+ constructor(message2, cause) {
5171
+ super(message2, cause);
5172
+ this.name = "SandboxGoneError";
5173
+ }
5174
+ };
5297
5175
  var ValidationError = class extends NeckbeardError {
5298
- constructor(message, cause) {
5299
- super(message);
5176
+ constructor(message2, cause) {
5177
+ super(message2);
5300
5178
  this.cause = cause;
5301
5179
  this.name = "ValidationError";
5302
5180
  }
5303
5181
  };
5304
5182
  var ExecutionError = class extends NeckbeardError {
5305
- constructor(message, cause) {
5306
- super(message);
5183
+ constructor(message2, cause) {
5184
+ super(message2);
5307
5185
  this.cause = cause;
5308
5186
  this.name = "ExecutionError";
5309
5187
  }
5310
5188
  };
5311
5189
  var RuntimeBusyError = class extends ExecutionError {
5312
- constructor(message) {
5313
- super(message);
5190
+ constructor(message2) {
5191
+ super(message2);
5314
5192
  this.name = "RuntimeBusyError";
5315
5193
  }
5316
5194
  };
5317
- var TurnLostError = class extends ExecutionError {
5318
- constructor(message) {
5319
- super(message);
5320
- this.name = "TurnLostError";
5321
- }
5322
- };
5323
5195
  var ConfigurationError = class extends NeckbeardError {
5324
- constructor(message) {
5325
- super(message);
5196
+ constructor(message2) {
5197
+ super(message2);
5326
5198
  this.name = "ConfigurationError";
5327
5199
  }
5328
5200
  };
@@ -5613,10 +5485,10 @@ function traceSourceDependencyFiles(appDir, sourceFiles) {
5613
5485
  files.add(file);
5614
5486
  }
5615
5487
  };
5616
- for (const [inputPath, input] of Object.entries(metafile.inputs)) {
5488
+ for (const [inputPath, input2] of Object.entries(metafile.inputs)) {
5617
5489
  const absoluteInput = resolveMetafileInput(appDir, inputPath);
5618
5490
  addFile(absoluteInput);
5619
- for (const importRecord of input.imports ?? []) {
5491
+ for (const importRecord of input2.imports ?? []) {
5620
5492
  const importPath = importRecord.original ?? importRecord.path;
5621
5493
  if (!isBareModuleImport(importPath) || isBuiltinModule(importPath)) {
5622
5494
  continue;
@@ -5661,8 +5533,8 @@ function findFiles(root) {
5661
5533
  return [];
5662
5534
  }
5663
5535
  const files = [];
5664
- for (const entry of (0, import_node_fs.readdirSync)(root)) {
5665
- files.push(...findFiles((0, import_node_path2.join)(root, entry)));
5536
+ for (const entry2 of (0, import_node_fs.readdirSync)(root)) {
5537
+ files.push(...findFiles((0, import_node_path2.join)(root, entry2)));
5666
5538
  }
5667
5539
  return files;
5668
5540
  }
@@ -5670,7 +5542,7 @@ function directFiles(root) {
5670
5542
  if (!(0, import_node_fs.existsSync)(root) || !(0, import_node_fs.statSync)(root).isDirectory()) {
5671
5543
  return [];
5672
5544
  }
5673
- return (0, import_node_fs.readdirSync)(root).map((entry) => (0, import_node_path2.join)(root, entry)).filter((file) => (0, import_node_fs.statSync)(file).isFile());
5545
+ return (0, import_node_fs.readdirSync)(root).map((entry2) => (0, import_node_path2.join)(root, entry2)).filter((file) => (0, import_node_fs.statSync)(file).isFile());
5674
5546
  }
5675
5547
  function routePathFromTraceFile(outputPath, traceFile) {
5676
5548
  const relativeTrace = (0, import_node_path2.relative)(outputPath, traceFile).replace(/\\/g, "/");
@@ -5732,20 +5604,20 @@ function asRecord(value) {
5732
5604
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
5733
5605
  }
5734
5606
  function normalizeNonEmptyStrings(name, value) {
5735
- const values = Array.isArray(value) ? value : [value];
5736
- if (values.length === 0) {
5607
+ const values2 = Array.isArray(value) ? value : [value];
5608
+ if (values2.length === 0) {
5737
5609
  throw new ConfigurationError(`${name} must contain at least one entry.`);
5738
5610
  }
5739
- for (const entry of values) {
5740
- if (typeof entry !== "string" || entry.trim() === "") {
5611
+ for (const entry2 of values2) {
5612
+ if (typeof entry2 !== "string" || entry2.trim() === "") {
5741
5613
  throw new ConfigurationError(`${name} entries must be non-empty strings.`);
5742
5614
  }
5743
5615
  }
5744
- return values;
5616
+ return values2;
5745
5617
  }
5746
- function mergeStringArray(existing, values) {
5618
+ function mergeStringArray(existing, values2) {
5747
5619
  const current = Array.isArray(existing) ? existing.filter((value) => typeof value === "string") : [];
5748
- return [.../* @__PURE__ */ new Set([...current, ...values])];
5620
+ return [.../* @__PURE__ */ new Set([...current, ...values2])];
5749
5621
  }
5750
5622
  function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
5751
5623
  const includes = { ...asRecord(existing) };
@@ -5824,12 +5696,12 @@ function validateLocalDirectoriesConfig(value) {
5824
5696
  if (!Array.isArray(value)) {
5825
5697
  throw new ConfigurationError("localDirectories must be an array when provided.");
5826
5698
  }
5827
- for (const [index, entry] of value.entries()) {
5699
+ for (const [index, entry2] of value.entries()) {
5828
5700
  const name = `localDirectories[${index}]`;
5829
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
5701
+ if (!entry2 || typeof entry2 !== "object" || Array.isArray(entry2)) {
5830
5702
  throw new ConfigurationError(`${name} must be an object.`);
5831
5703
  }
5832
- const candidate = entry;
5704
+ const candidate = entry2;
5833
5705
  if (typeof candidate.source !== "string" || candidate.source.trim() === "") {
5834
5706
  throw new ConfigurationError(`${name}.source must be a non-empty string.`);
5835
5707
  }
@@ -5853,9 +5725,9 @@ function validateAgentConfig(config) {
5853
5725
  throw new ConfigurationError('sandbox.provider must be "e2b", "daytona", "modal", or "docker".');
5854
5726
  }
5855
5727
  if (config.sandbox.provider === "modal") {
5856
- validateModalOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
5728
+ validateModalOptions(config.sandbox, "agent", (message2) => new ConfigurationError(message2));
5857
5729
  } else if (config.sandbox.provider === "docker") {
5858
- validateDockerOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
5730
+ validateDockerOptions(config.sandbox, "agent", (message2) => new ConfigurationError(message2));
5859
5731
  } else if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
5860
5732
  throw new ConfigurationError("sandbox.template must be a non-empty string.");
5861
5733
  }
@@ -5998,9 +5870,9 @@ async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HE
5998
5870
  }
5999
5871
  await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
6000
5872
  }
6001
- const message = lastError instanceof Error ? lastError.message : String(lastError);
5873
+ const message2 = lastError instanceof Error ? lastError.message : String(lastError);
6002
5874
  throw new DeploymentError(
6003
- `Server did not become healthy at ${healthUrl} within ${timeoutMs}ms: ${message}`
5875
+ `Server did not become healthy at ${healthUrl} within ${timeoutMs}ms: ${message2}`
6004
5876
  );
6005
5877
  }
6006
5878
  function requireEnv(name) {
@@ -6204,7 +6076,7 @@ async function readServerFailureDiagnostics(sandbox, command, environment, signa
6204
6076
  signal
6205
6077
  );
6206
6078
  const secrets = Object.entries(environment).filter(
6207
- (entry) => Boolean(entry[1]) && isConfiguredDiagnosticSecret(entry[0], entry[1])
6079
+ (entry2) => Boolean(entry2[1]) && isConfiguredDiagnosticSecret(entry2[0], entry2[1])
6208
6080
  ).map(([, value]) => value);
6209
6081
  secrets.sort((left, right) => right.length - left.length);
6210
6082
  const stdout = redactServerFailureDiagnosticStream(captured.stdout, secrets);
@@ -6229,12 +6101,12 @@ function providerApiKey(provider, explicitApiKey) {
6229
6101
  }
6230
6102
  async function createProviderSandboxHandle(options) {
6231
6103
  if (options.provider === "modal") {
6232
- validateModalOptions(options, "create", (message) => new ConfigurationError(message));
6233
- return ModalSandboxHandle.create(options, (message) => new DeploymentError(message));
6104
+ validateModalOptions(options, "create", (message2) => new ConfigurationError(message2));
6105
+ return ModalSandboxHandle.create(options, (message2) => new DeploymentError(message2));
6234
6106
  }
6235
6107
  if (options.provider === "docker") {
6236
- validateDockerOptions(options, "create", (message) => new ConfigurationError(message));
6237
- return DockerSandboxHandle.create(options, (message) => new DeploymentError(message));
6108
+ validateDockerOptions(options, "create", (message2) => new ConfigurationError(message2));
6109
+ return DockerSandboxHandle.create(options, (message2) => new DeploymentError(message2));
6238
6110
  }
6239
6111
  if (options.provider === "daytona") {
6240
6112
  const apiKey2 = providerApiKey("daytona", options.apiKey);
@@ -6255,7 +6127,7 @@ async function createProviderSandboxHandle(options) {
6255
6127
  try {
6256
6128
  return await DaytonaSandboxHandle.create(
6257
6129
  sandbox2,
6258
- (message) => new DeploymentError(message)
6130
+ (message2) => new DeploymentError(message2)
6259
6131
  );
6260
6132
  } catch (error) {
6261
6133
  await sandbox2.delete(
@@ -6275,44 +6147,57 @@ async function createProviderSandboxHandle(options) {
6275
6147
  network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
6276
6148
  };
6277
6149
  const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
6278
- return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
6150
+ return new E2bSandboxHandle(sandbox, (message2) => new DeploymentError(message2));
6279
6151
  }
6280
- async function connectProviderSandboxHandle(options) {
6152
+ async function connectProviderSandboxHandle(options, wake = true) {
6153
+ const gone = (message2, cause) => new SandboxGoneError(message2, cause instanceof Error ? cause : void 0);
6281
6154
  if (options.provider === "modal") {
6282
- validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
6283
- return ModalSandboxHandle.connect(options, (message) => new DeploymentError(message));
6155
+ validateModalOptions(options, "connect", (message2) => new ConfigurationError(message2));
6156
+ return ModalSandboxHandle.connect(options, (message2) => new DeploymentError(message2), wake ? void 0 : gone);
6284
6157
  }
6285
6158
  if (options.provider === "docker") {
6286
- validateDockerOptions(options, "connect", (message) => new ConfigurationError(message));
6287
- return DockerSandboxHandle.connect(options, (message) => new DeploymentError(message));
6159
+ validateDockerOptions(options, "connect", (message2) => new ConfigurationError(message2));
6160
+ return DockerSandboxHandle.connect(options, (message2) => new DeploymentError(message2));
6288
6161
  }
6289
6162
  if (options.provider === "daytona") {
6290
6163
  const apiKey2 = providerApiKey("daytona", options.apiKey);
6291
- const { Daytona } = await getDaytona();
6164
+ const { Daytona, DaytonaNotFoundError } = await getDaytona();
6292
6165
  const daytona = new Daytona({ apiKey: apiKey2 });
6293
- const sandbox2 = await daytona.get(options.sandboxId);
6166
+ const sandbox2 = await daytona.get(options.sandboxId).catch((error) => {
6167
+ if (!wake && error instanceof DaytonaNotFoundError) throw gone(`Daytona sandbox ${options.sandboxId} does not exist.`, error);
6168
+ throw error;
6169
+ });
6294
6170
  if (sandbox2.state !== "started") {
6171
+ if (!wake) throw gone(`Daytona sandbox ${options.sandboxId} is ${sandbox2.state}, not started.`);
6295
6172
  if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
6296
6173
  await sandbox2.waitUntilStarted(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
6297
6174
  } else {
6298
6175
  await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
6299
6176
  }
6300
6177
  }
6301
- return DaytonaSandboxHandle.create(sandbox2, (message) => new DeploymentError(message));
6178
+ return DaytonaSandboxHandle.create(sandbox2, (message2) => new DeploymentError(message2));
6302
6179
  }
6303
6180
  const apiKey = providerApiKey("e2b", options.apiKey);
6304
- const { Sandbox } = await getE2b();
6181
+ const { Sandbox, SandboxNotFoundError } = await getE2b();
6182
+ const absent2 = (error) => {
6183
+ if (!wake && error instanceof SandboxNotFoundError) throw gone(`E2B sandbox ${options.sandboxId} does not exist.`, error);
6184
+ throw error;
6185
+ };
6186
+ if (!wake) {
6187
+ const info = await Sandbox.getInfo(options.sandboxId, { apiKey, requestTimeoutMs: options.requestTimeoutMs }).catch(absent2);
6188
+ if (info.state !== "running") throw gone(`E2B sandbox ${options.sandboxId} is ${info.state}, not running.`);
6189
+ }
6305
6190
  const sandbox = await Sandbox.connect(options.sandboxId, {
6306
6191
  apiKey,
6307
6192
  timeoutMs: options.timeoutMs,
6308
6193
  requestTimeoutMs: options.requestTimeoutMs
6309
- });
6310
- return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
6194
+ }).catch(absent2);
6195
+ return new E2bSandboxHandle(sandbox, (message2) => new DeploymentError(message2));
6311
6196
  }
6312
6197
  async function destroyProviderSandbox(options) {
6313
6198
  if (options.provider === "modal") {
6314
- validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
6315
- return ModalSandboxHandle.destroyById(options, (message) => new DeploymentError(message));
6199
+ validateModalOptions(options, "connect", (message2) => new ConfigurationError(message2));
6200
+ return ModalSandboxHandle.destroyById(options, (message2) => new DeploymentError(message2));
6316
6201
  }
6317
6202
  if (options.provider === "daytona") {
6318
6203
  const { Daytona, DaytonaNotFoundError } = await getDaytona();
@@ -6334,8 +6219,8 @@ var SandboxClient = class _SandboxClient {
6334
6219
  static async create(options) {
6335
6220
  return new _SandboxClient(await createProviderSandboxHandle(options));
6336
6221
  }
6337
- static async connect(options) {
6338
- return new _SandboxClient(await connectProviderSandboxHandle(options));
6222
+ static async connect(options, mode = {}) {
6223
+ return new _SandboxClient(await connectProviderSandboxHandle(options, mode.wake ?? true));
6339
6224
  }
6340
6225
  get id() {
6341
6226
  return this.handle.id;
@@ -6380,7 +6265,7 @@ var SandboxClient = class _SandboxClient {
6380
6265
  }
6381
6266
  const normalized = normalizeProviderSandboxDetachedCommandOptions(
6382
6267
  options,
6383
- (message) => new ConfigurationError(message),
6268
+ (message2) => new ConfigurationError(message2),
6384
6269
  { requireObject: true }
6385
6270
  );
6386
6271
  return this.handle.startDetachedCommand(command, normalized.options);
@@ -6561,8 +6446,8 @@ function readConfiguredLocalDirectory(upload) {
6561
6446
  `${upload.name} could not read local directory: ${currentPath} (${errorMessage(error)})`
6562
6447
  );
6563
6448
  }
6564
- for (const entry of entries) {
6565
- const localPath = (0, import_node_path2.join)(currentPath, entry);
6449
+ for (const entry2 of entries) {
6450
+ const localPath = (0, import_node_path2.join)(currentPath, entry2);
6566
6451
  const stats = localPathStats(localPath, upload);
6567
6452
  if (stats.isDirectory()) {
6568
6453
  walk(localPath);
@@ -6590,8 +6475,8 @@ function readConfiguredLocalDirectory(upload) {
6590
6475
  return { rootPath, files };
6591
6476
  }
6592
6477
  function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
6593
- const uploads = localDirectories.map((entry, index) => ({
6594
- ...entry,
6478
+ const uploads = localDirectories.map((entry2, index) => ({
6479
+ ...entry2,
6595
6480
  name: `localDirectories[${index}]`,
6596
6481
  rejectSymlinks: true,
6597
6482
  preserveRootDirectory: false
@@ -6684,7 +6569,7 @@ var LegacyBundledAgent = class {
6684
6569
  this._sourceFile = resolveSourceFile(config.sourceFile);
6685
6570
  this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
6686
6571
  this.files = config.files ?? [];
6687
- this.localDirectories = (config.localDirectories ?? []).map((entry) => ({ ...entry }));
6572
+ this.localDirectories = (config.localDirectories ?? []).map((entry2) => ({ ...entry2 }));
6688
6573
  this.claudeDir = config.claudeDir;
6689
6574
  this.envs = config.envs ?? {};
6690
6575
  this.build = config.build ?? {};
@@ -7181,7 +7066,7 @@ var require = __neckbeard_createRequire(import.meta.url);
7181
7066
  * const result = await agent.run({ prompt: 'Hello!' }, { sandboxId });
7182
7067
  * ```
7183
7068
  */
7184
- async run(input, options) {
7069
+ async run(input2, options) {
7185
7070
  const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
7186
7071
  if (this.mode !== "run") {
7187
7072
  return {
@@ -7196,7 +7081,7 @@ var require = __neckbeard_createRequire(import.meta.url);
7196
7081
  const connection = await this.resolveRuntimeConnection(options?.sandboxId);
7197
7082
  let validatedInput;
7198
7083
  try {
7199
- validatedInput = this.inputSchema.parse(input);
7084
+ validatedInput = this.inputSchema.parse(input2);
7200
7085
  } catch (error) {
7201
7086
  throw new ValidationError("Input validation failed.", asError(error));
7202
7087
  }
@@ -7281,7 +7166,7 @@ var require = __neckbeard_createRequire(import.meta.url);
7281
7166
  }
7282
7167
  if (durability !== void 0 && durability !== "attached") {
7283
7168
  throw new ConfigurationError(
7284
- "LegacyBundledAgent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
7169
+ "LegacyBundledAgent.createSession() creates caller-owned attached sessions. Durable sessions are no longer supported."
7285
7170
  );
7286
7171
  }
7287
7172
  if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
@@ -7300,13 +7185,13 @@ var require = __neckbeard_createRequire(import.meta.url);
7300
7185
  }
7301
7186
  return createAttachedAgentSession({
7302
7187
  sandboxId,
7303
- runPrompt: (input, signal2) => this.streamSessionPrompt(input, sandboxId, signal2),
7188
+ runPrompt: (input2, signal2) => this.streamSessionPrompt(input2, sandboxId, signal2),
7304
7189
  ...signal === void 0 ? {} : { externalSignal: signal },
7305
- configurationError: (message) => new ConfigurationError(message),
7190
+ configurationError: (message2) => new ConfigurationError(message2),
7306
7191
  abortError: abortSignalError
7307
7192
  });
7308
7193
  }
7309
- async *streamSessionPrompt(input, sandboxId, signal) {
7194
+ async *streamSessionPrompt(input2, sandboxId, signal) {
7310
7195
  const connection = await this.resolveRuntimeConnection(sandboxId, {
7311
7196
  signal,
7312
7197
  reuseMatchingCachedConnection: true
@@ -7314,7 +7199,7 @@ var require = __neckbeard_createRequire(import.meta.url);
7314
7199
  const { invokeServer: invokeServer2, InvokeHttpError: InvokeHttpError2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
7315
7200
  let validated;
7316
7201
  try {
7317
- validated = this.inputSchema.parse(input);
7202
+ validated = this.inputSchema.parse(input2);
7318
7203
  } catch (error) {
7319
7204
  throw new ValidationError("Input validation failed.", asError(error));
7320
7205
  }
@@ -7394,13 +7279,13 @@ var require = __neckbeard_createRequire(import.meta.url);
7394
7279
  * This compatibility wrapper creates one attached session, streams one turn,
7395
7280
  * and closes the local handle afterward.
7396
7281
  */
7397
- async *invoke(input, options) {
7282
+ async *invoke(input2, options) {
7398
7283
  const session = await this.createSession({
7399
7284
  ...options?.sandboxId === void 0 ? {} : { sandboxId: options.sandboxId },
7400
7285
  ...options?.signal === void 0 ? {} : { signal: options.signal }
7401
7286
  });
7402
7287
  try {
7403
- yield* session.prompt(input);
7288
+ yield* session.prompt(input2);
7404
7289
  } finally {
7405
7290
  await session.close();
7406
7291
  }
@@ -7412,19 +7297,21 @@ var require = __neckbeard_createRequire(import.meta.url);
7412
7297
  ConfigurationError,
7413
7298
  DEFAULT_DEPENDENCIES,
7414
7299
  DefinedAgent,
7300
+ DefinedHostAgent,
7415
7301
  DeploymentError,
7416
7302
  ExecutionError,
7417
7303
  LegacyBundledAgent,
7418
7304
  NeckbeardError,
7305
+ RemoteAdmissionRejected,
7306
+ RemoteSubmissionNotFound,
7419
7307
  RuntimeBusyError,
7420
7308
  SKILLS_DIR,
7421
7309
  SandboxClient,
7310
+ SandboxGoneError,
7422
7311
  TURN_PROTOCOL_VERSION,
7423
- TurnLostError,
7424
7312
  ValidationError,
7425
7313
  defineAgent,
7426
7314
  destroyProviderSandbox,
7427
- getPiTurnResult,
7428
7315
  isDefinedAgent,
7429
7316
  normalizeStackFramePath,
7430
7317
  resolveAgentSourceFile,