agent-neckbeard 1.1.6 → 1.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -74,21 +74,54 @@ var init_sse_framing = __esm({
74
74
  }
75
75
  });
76
76
 
77
+ // src/runtime/protocol.ts
78
+ function isHarnessEvent(value) {
79
+ if (!value || typeof value !== "object") return false;
80
+ const candidate = value;
81
+ return typeof candidate.kind === "string" && typeof candidate.invocationId === "string" && ["started", "frame", "output", "done", "error"].includes(candidate.kind);
82
+ }
83
+ var init_protocol = __esm({
84
+ "src/runtime/protocol.ts"() {
85
+ "use strict";
86
+ }
87
+ });
88
+
77
89
  // src/invoke-client.ts
78
90
  var invoke_client_exports = {};
79
91
  __export(invoke_client_exports, {
80
92
  invokeServer: () => invokeServer
81
93
  });
94
+ function createInvocationId() {
95
+ return `invoke_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
96
+ }
97
+ function appendDaytonaTrafficToken(url, token) {
98
+ if (!token) return url;
99
+ const separator = url.includes("?") ? "&" : "?";
100
+ return `${url}${separator}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(token)}`;
101
+ }
102
+ function buildRequestUrl(options) {
103
+ if (options.provider === "daytona") {
104
+ return appendDaytonaTrafficToken(options.serverUrl, options.trafficToken);
105
+ }
106
+ return options.serverUrl;
107
+ }
108
+ function buildRequestHeaders(options) {
109
+ const headers = {
110
+ "content-type": "application/json",
111
+ accept: "text/event-stream"
112
+ };
113
+ if (options.provider === "e2b" && options.trafficToken) {
114
+ headers["e2b-traffic-access-token"] = options.trafficToken;
115
+ }
116
+ return headers;
117
+ }
82
118
  async function* invokeServer(input, options) {
83
119
  const fetchImpl = options.fetch ?? fetch;
84
- const response = await fetchImpl(options.serverUrl, {
120
+ const invocationId = options.invocationId ?? createInvocationId();
121
+ const response = await fetchImpl(buildRequestUrl(options), {
85
122
  method: "POST",
86
- headers: {
87
- "content-type": "application/json",
88
- accept: "text/event-stream",
89
- authorization: `Bearer ${options.authToken}`
90
- },
91
- body: JSON.stringify(input),
123
+ headers: buildRequestHeaders(options),
124
+ body: JSON.stringify({ invocationId, input }),
92
125
  signal: options.signal
93
126
  });
94
127
  if (!response.ok) {
@@ -116,11 +149,17 @@ async function* invokeServer(input, options) {
116
149
  }
117
150
  }
118
151
  }
119
- for await (const rawFrame of decodeSseStream(chunks())) {
120
- if (options.frameSchema) {
121
- yield options.frameSchema.parse(rawFrame);
152
+ for await (const rawEvent of decodeSseStream(chunks())) {
153
+ if (!isHarnessEvent(rawEvent)) {
154
+ throw new Error("Server returned an invalid harness event");
155
+ }
156
+ if (rawEvent.kind === "frame" && options.frameSchema) {
157
+ yield {
158
+ ...rawEvent,
159
+ data: options.frameSchema.parse(rawEvent.data)
160
+ };
122
161
  } else {
123
- yield rawFrame;
162
+ yield rawEvent;
124
163
  }
125
164
  }
126
165
  }
@@ -128,6 +167,7 @@ var init_invoke_client = __esm({
128
167
  "src/invoke-client.ts"() {
129
168
  "use strict";
130
169
  init_sse_framing();
170
+ init_protocol();
131
171
  }
132
172
  });
133
173
 
@@ -148,168 +188,6 @@ var import_node_url = require("url");
148
188
  var import_node_fs = require("fs");
149
189
  var import_node_path = require("path");
150
190
  var import_node_module = require("module");
151
- var import_node_crypto = require("crypto");
152
-
153
- // src/server-code.ts
154
- function buildServerCode(options) {
155
- const sandboxContextLiteral = JSON.stringify(options.sandboxContext);
156
- const defaultPort = options.port;
157
- const maxDurationMs = options.maxDurationSeconds * 1e3;
158
- return `
159
- import { createServer } from 'node:http';
160
-
161
- const DEFAULT_PORT = ${defaultPort};
162
- const MAX_DURATION_MS = ${maxDurationMs};
163
- const SANDBOX_CONTEXT = ${sandboxContextLiteral};
164
-
165
- const PORT = Number(process.env.NECKBEARD_SERVER_PORT) || DEFAULT_PORT;
166
- const TOKEN = process.env.NECKBEARD_SERVER_TOKEN;
167
- if (!TOKEN) {
168
- console.error('[neckbeard-server] NECKBEARD_SERVER_TOKEN env is required');
169
- process.exit(1);
170
- }
171
-
172
- const mod = await import('./agent.mjs');
173
- const agent =
174
- (mod.default && mod.default._server ? mod.default : null) ||
175
- Object.values(mod).find((v) => v && typeof v === 'object' && v._server);
176
- if (!agent || !agent._server) {
177
- console.error('[neckbeard-server] No server-mode agent found in agent.mjs (expected export with a _server property)');
178
- process.exit(1);
179
- }
180
-
181
- function sendSseFrame(res, frame) {
182
- res.write(\`data: \${JSON.stringify(frame)}\\n\\n\`);
183
- }
184
-
185
- function sendJson(res, status, body) {
186
- res.writeHead(status, { 'content-type': 'application/json' });
187
- res.end(JSON.stringify(body));
188
- }
189
-
190
- async function readRequestBody(req) {
191
- const chunks = [];
192
- for await (const chunk of req) {
193
- chunks.push(chunk);
194
- }
195
- return Buffer.concat(chunks).toString('utf-8');
196
- }
197
-
198
- function isAuthorized(req) {
199
- const header = req.headers['authorization'];
200
- return header === \`Bearer \${TOKEN}\`;
201
- }
202
-
203
- const server = createServer(async (req, res) => {
204
- try {
205
- if (req.url === '/health' && req.method === 'GET') {
206
- return sendJson(res, 200, { ok: true });
207
- }
208
-
209
- if (!isAuthorized(req)) {
210
- return sendJson(res, 401, { error: 'unauthorized' });
211
- }
212
-
213
- if (req.url === '/invoke' && req.method === 'POST') {
214
- const rawBody = await readRequestBody(req);
215
- let parsedBody;
216
- try {
217
- parsedBody = JSON.parse(rawBody);
218
- } catch (err) {
219
- return sendJson(res, 400, { error: 'invalid JSON body' });
220
- }
221
-
222
- let validatedInput;
223
- try {
224
- validatedInput = agent.inputSchema.parse(parsedBody);
225
- } catch (err) {
226
- return sendJson(res, 400, {
227
- error: 'input validation failed: ' + (err && err.message ? err.message : String(err)),
228
- });
229
- }
230
-
231
- res.writeHead(200, {
232
- 'content-type': 'text/event-stream',
233
- 'cache-control': 'no-cache, no-transform',
234
- connection: 'keep-alive',
235
- 'x-accel-buffering': 'no',
236
- });
237
-
238
- const controller = new AbortController();
239
- req.on('close', () => controller.abort());
240
- const timeout = setTimeout(() => controller.abort(), MAX_DURATION_MS);
241
-
242
- const emit = async (frame) => {
243
- if (!res.writableEnded) {
244
- sendSseFrame(res, frame);
245
- }
246
- };
247
-
248
- const ctx = {
249
- executionId: \`exec_\${Date.now()}_\${Math.random().toString(36).slice(2, 8)}\`,
250
- signal: controller.signal,
251
- env: process.env,
252
- sandbox: SANDBOX_CONTEXT,
253
- logger: {
254
- debug: (msg, ...args) => console.log('[DEBUG]', msg, ...args),
255
- info: (msg, ...args) => console.log('[INFO]', msg, ...args),
256
- warn: (msg, ...args) => console.warn('[WARN]', msg, ...args),
257
- error: (msg, ...args) => console.error('[ERROR]', msg, ...args),
258
- },
259
- };
260
-
261
- try {
262
- await agent._server.handler({
263
- input: validatedInput,
264
- ctx,
265
- signal: controller.signal,
266
- emit,
267
- });
268
- } catch (err) {
269
- try {
270
- sendSseFrame(res, {
271
- type: 'error',
272
- error: err && err.message ? err.message : String(err),
273
- });
274
- } catch {
275
- // response may already be closed
276
- }
277
- } finally {
278
- clearTimeout(timeout);
279
- if (!res.writableEnded) {
280
- res.end();
281
- }
282
- }
283
- return;
284
- }
285
-
286
- return sendJson(res, 404, { error: 'not found' });
287
- } catch (err) {
288
- console.error('[neckbeard-server] unexpected error', err);
289
- if (!res.headersSent) {
290
- sendJson(res, 500, { error: 'internal error' });
291
- } else if (!res.writableEnded) {
292
- res.end();
293
- }
294
- }
295
- });
296
-
297
- server.listen(PORT, '0.0.0.0', () => {
298
- console.log(\`[neckbeard-server] listening on port \${PORT}\`);
299
- });
300
-
301
- function shutdown() {
302
- console.log('[neckbeard-server] shutting down');
303
- server.close(() => process.exit(0));
304
- setTimeout(() => process.exit(0), 5000).unref();
305
- }
306
-
307
- process.on('SIGTERM', shutdown);
308
- process.on('SIGINT', shutdown);
309
- `;
310
- }
311
-
312
- // src/index.ts
313
191
  function readPackageJson(path) {
314
192
  return JSON.parse((0, import_node_fs.readFileSync)(path, "utf8"));
315
193
  }
@@ -326,6 +204,7 @@ var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
326
204
  var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
327
205
  var DEFAULT_SERVER_PORT = 3e3;
328
206
  var SERVER_HEALTH_TIMEOUT_MS = 12e4;
207
+ var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
329
208
  var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
330
209
  var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
331
210
  var E2B_SANDBOX_HOME = "/home/user";
@@ -366,17 +245,30 @@ var DEFAULT_DEPENDENCIES = {};
366
245
  function isServerAgentConfig(config) {
367
246
  return "server" in config && config.server !== void 0;
368
247
  }
369
- function generateAuthToken() {
370
- return (0, import_node_crypto.randomBytes)(32).toString("hex");
248
+ function getTrafficToken(descriptor) {
249
+ return descriptor.trafficToken;
250
+ }
251
+ function appendTrafficTokenToUrl(url, descriptor) {
252
+ const token = getTrafficToken(descriptor);
253
+ if (descriptor.provider !== "daytona" || !token) return url;
254
+ const separator = url.includes("?") ? "&" : "?";
255
+ return `${url}${separator}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(token)}`;
256
+ }
257
+ function trafficTokenHeaders(descriptor) {
258
+ const token = getTrafficToken(descriptor);
259
+ if (descriptor.provider === "e2b" && token) {
260
+ return { "e2b-traffic-access-token": token };
261
+ }
262
+ return {};
371
263
  }
372
- async function waitForServerHealthy(healthUrl, authToken, previewToken) {
373
- const deadline = Date.now() + SERVER_HEALTH_TIMEOUT_MS;
264
+ async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HEALTH_TIMEOUT_MS) {
265
+ const deadline = Date.now() + timeoutMs;
374
266
  let lastError;
375
- const urlWithToken = previewToken ? `${healthUrl}${healthUrl.includes("?") ? "&" : "?"}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(previewToken)}` : healthUrl;
267
+ const urlWithToken = appendTrafficTokenToUrl(healthUrl, descriptor);
376
268
  while (Date.now() < deadline) {
377
269
  try {
378
270
  const response = await fetch(urlWithToken, {
379
- headers: { authorization: `Bearer ${authToken}` }
271
+ headers: trafficTokenHeaders(descriptor)
380
272
  });
381
273
  if (response.ok) {
382
274
  await response.text().catch(() => void 0);
@@ -390,7 +282,7 @@ async function waitForServerHealthy(healthUrl, authToken, previewToken) {
390
282
  }
391
283
  const message = lastError instanceof Error ? lastError.message : String(lastError);
392
284
  throw new DeploymentError(
393
- `Server did not become healthy at ${healthUrl} within ${SERVER_HEALTH_TIMEOUT_MS}ms: ${message}`
285
+ `Server did not become healthy at ${healthUrl} within ${timeoutMs}ms: ${message}`
394
286
  );
395
287
  }
396
288
  function requireEnv(name) {
@@ -519,7 +411,8 @@ function createSandboxPaths(provider, homeDir, workDir) {
519
411
  inputJson: `${ioDir}/input.json`,
520
412
  outputJson: `${ioDir}/output.json`,
521
413
  agentModule: `${agentDir}/agent.mjs`,
522
- runnerModule: `${agentDir}/runner.mjs`,
414
+ serverModule: `${agentDir}/server.mjs`,
415
+ serverConfig: `${agentDir}/server-config.json`,
523
416
  claudeDir: `${agentDir}/.claude`,
524
417
  packageJson: `${agentDir}/package.json`
525
418
  };
@@ -577,6 +470,34 @@ function createE2bHandle(sandbox) {
577
470
  const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
578
471
  return runE2bCommand(sandbox, command, options);
579
472
  },
473
+ startDetachedCommand: async (cmd, options) => {
474
+ const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
475
+ const handle = await sandbox.commands.run(command, {
476
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS,
477
+ envs: options.envs,
478
+ background: true
479
+ });
480
+ return { sessionId: `e2b:${handle.pid}`, commandId: String(handle.pid) };
481
+ },
482
+ readSessionLogs: async (_sessionId, commandId) => {
483
+ if (!sandbox.commands.connect) return { stdout: "", stderr: "" };
484
+ try {
485
+ const handle = await sandbox.commands.connect(Number(commandId));
486
+ return { stdout: handle.stdout ?? "", stderr: handle.stderr ?? "" };
487
+ } catch {
488
+ return { stdout: "", stderr: "" };
489
+ }
490
+ },
491
+ stopSession: async (sessionId) => {
492
+ const pid = Number(sessionId.replace(/^e2b:/, ""));
493
+ if (Number.isFinite(pid)) {
494
+ await sandbox.commands.kill?.(pid);
495
+ }
496
+ },
497
+ getServerEndpoint: async (port) => ({
498
+ url: `https://${sandbox.getHost(port)}`,
499
+ trafficToken: sandbox.trafficAccessToken
500
+ }),
580
501
  destroy: () => sandbox.kill()
581
502
  };
582
503
  }
@@ -634,8 +555,9 @@ async function createDaytonaHandle(sandbox) {
634
555
  stopSession: async (sessionId) => {
635
556
  await sandbox.process.deleteSession(sessionId);
636
557
  },
637
- getPreviewLink: async (port) => {
638
- return sandbox.getPreviewLink(port);
558
+ getServerEndpoint: async (port) => {
559
+ const preview = await sandbox.getPreviewLink(port);
560
+ return { url: preview.url, trafficToken: preview.token };
639
561
  },
640
562
  destroy: () => sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS))
641
563
  };
@@ -692,14 +614,40 @@ function readDirectoryRecursively(dirPath) {
692
614
  walkDir(dirPath);
693
615
  return files;
694
616
  }
617
+ function getRuntimeServerEntryPoint() {
618
+ const currentFile = getCurrentModuleFile();
619
+ const currentDir = currentFile ? (0, import_node_path.dirname)(currentFile) : process.cwd();
620
+ const candidates = [
621
+ (0, import_node_path.join)(currentDir, "runtime/server.ts"),
622
+ (0, import_node_path.join)(currentDir, "runtime/server.js"),
623
+ (0, import_node_path.join)(currentDir, "runtime/server.mjs")
624
+ ];
625
+ const entry = candidates.find((candidate) => (0, import_node_fs.existsSync)(candidate));
626
+ if (!entry) {
627
+ throw new DeploymentError(
628
+ `Could not find neckbeard runtime server entry. Tried: ${candidates.join(", ")}`
629
+ );
630
+ }
631
+ return entry;
632
+ }
633
+ function getCurrentModuleFile() {
634
+ const stack = new Error().stack?.split("\n") ?? [];
635
+ for (const line of stack.slice(1)) {
636
+ const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
637
+ if (!match) continue;
638
+ const normalized = normalizeStackFramePath(match[1]);
639
+ if (normalized && (0, import_node_fs.existsSync)(normalized)) return normalized;
640
+ }
641
+ return null;
642
+ }
695
643
  var Agent = class {
696
644
  sandbox;
697
645
  provider;
698
646
  template;
699
647
  inputSchema;
700
- /** Only populated for one-shot agents; undefined for server-mode. */
648
+ /** Only populated for run-output agents; undefined for streaming agents. */
701
649
  outputSchema;
702
- /** Only populated for server-mode agents; undefined for one-shot. */
650
+ /** Only populated for streaming agents; undefined for run-output agents. */
703
651
  frameSchema;
704
652
  mode;
705
653
  maxDuration;
@@ -708,14 +656,14 @@ var Agent = class {
708
656
  claudeDir;
709
657
  envs;
710
658
  build;
711
- /** @internal Used by the sandbox runner for one-shot agents. */
659
+ /** @internal Used by the in-sandbox server for run-output agents. */
712
660
  _run;
713
- /** @internal Used by the in-sandbox HTTP server for server-mode agents. */
661
+ /** @internal Used by the in-sandbox server for streaming agents. */
714
662
  _server;
715
- /** @internal Runtime state populated by deploy() for server-mode agents. */
663
+ /** @internal Runtime state populated by deploy(). */
716
664
  _serverRuntime;
717
- _sourceFile;
718
665
  _sandboxId;
666
+ _sourceFile;
719
667
  constructor(config) {
720
668
  this.sandbox = config.sandbox;
721
669
  this.provider = config.sandbox.provider;
@@ -729,17 +677,17 @@ var Agent = class {
729
677
  this.envs = config.envs ?? {};
730
678
  this.build = config.build ?? {};
731
679
  if (isServerAgentConfig(config)) {
732
- this.mode = "server";
680
+ this.mode = "stream";
733
681
  this._server = config.server;
734
682
  this.frameSchema = config.server.frameSchema;
735
683
  } else {
736
- this.mode = "one-shot";
684
+ this.mode = "run";
737
685
  this._run = config.run;
738
686
  this.outputSchema = config.outputSchema;
739
687
  }
740
688
  }
741
689
  get sandboxId() {
742
- return this._sandboxId;
690
+ return this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
743
691
  }
744
692
  get sandboxEnv() {
745
693
  return filterDefinedEnvs(this.envs);
@@ -761,7 +709,11 @@ var Agent = class {
761
709
  }
762
710
  const apiKey = requireEnv("E2B_API_KEY");
763
711
  const { Sandbox } = await getE2b();
764
- const sandbox = await Sandbox.create(this.template, { apiKey });
712
+ const sandbox = await Sandbox.create(this.template, {
713
+ apiKey,
714
+ envs: this.sandboxEnv,
715
+ network: { allowPublicTraffic: false }
716
+ });
765
717
  return createE2bHandle(sandbox);
766
718
  }
767
719
  async connectSandboxHandle(sandboxId) {
@@ -784,80 +736,97 @@ var Agent = class {
784
736
  const sandbox = await Sandbox.connect(sandboxId, { apiKey });
785
737
  return createE2bHandle(sandbox);
786
738
  }
787
- buildRunnerCode(paths) {
788
- const sandboxContext = JSON.stringify({
789
- provider: paths.provider,
790
- homeDir: paths.homeDir,
791
- workDir: paths.workDir,
792
- agentDir: paths.agentDir,
793
- ioDir: paths.ioDir,
794
- inputJson: paths.inputJson,
795
- outputJson: paths.outputJson
739
+ async readRuntimeServerConfig(sandbox) {
740
+ try {
741
+ return JSON.parse(await sandbox.readFile(sandbox.paths.serverConfig));
742
+ } catch {
743
+ return void 0;
744
+ }
745
+ }
746
+ async createRuntimeConnection(sandbox, port) {
747
+ if (!sandbox.getServerEndpoint) {
748
+ throw new DeploymentError(
749
+ "Persistent agents require a sandbox provider that supports public port endpoints."
750
+ );
751
+ }
752
+ const endpoint = await sandbox.getServerEndpoint(port);
753
+ const baseServerUrl = endpoint.url.replace(/\/$/, "");
754
+ return {
755
+ provider: this.provider,
756
+ sandboxId: sandbox.id,
757
+ serverUrl: `${baseServerUrl}/invoke`,
758
+ trafficToken: endpoint.trafficToken
759
+ };
760
+ }
761
+ healthUrlFor(connection) {
762
+ const url = new URL(connection.serverUrl);
763
+ url.pathname = url.pathname.replace(/\/invoke$/, "/health");
764
+ url.search = "";
765
+ return url.toString();
766
+ }
767
+ async startRuntimeServer(sandbox) {
768
+ if (!sandbox.startDetachedCommand) {
769
+ throw new DeploymentError(
770
+ "Persistent agents require a sandbox provider that supports background commands."
771
+ );
772
+ }
773
+ return sandbox.startDetachedCommand("node server.mjs", {
774
+ cwd: sandbox.paths.agentDir,
775
+ envs: this.sandboxEnv
796
776
  });
797
- return `
798
- import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
799
-
800
- const SANDBOX_CONTEXT = ${sandboxContext};
801
- const IO_DIR = SANDBOX_CONTEXT.ioDir;
802
- const INPUT_FILE = SANDBOX_CONTEXT.inputJson;
803
- const OUTPUT_FILE = SANDBOX_CONTEXT.outputJson;
804
-
805
- mkdirSync(IO_DIR, { recursive: true });
806
-
807
- let input, executionId;
808
- try {
809
- const taskData = JSON.parse(readFileSync(INPUT_FILE, 'utf-8'));
810
- input = taskData.input;
811
- executionId = taskData.executionId;
812
- } catch (parseError) {
813
- writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'Task parse failed: ' + parseError.message, stack: parseError.stack } }));
814
- process.exit(0);
815
- }
816
-
817
- let mod;
818
- try {
819
- mod = await import('./agent.mjs');
820
- } catch (importError) {
821
- writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'Import failed: ' + importError.message, stack: importError.stack } }));
822
- process.exit(0);
823
- }
824
-
825
- const agent = mod.default || Object.values(mod).find(v => v instanceof Object && v._run);
826
- if (!agent) {
827
- writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: 'No agent found in module. Exports: ' + Object.keys(mod).join(', ') } }));
828
- process.exit(0);
829
- }
830
-
831
- const ctx = {
832
- executionId,
833
- signal: AbortSignal.timeout(${this.maxDuration * 1e3}),
834
- env: process.env,
835
- sandbox: SANDBOX_CONTEXT,
836
- logger: {
837
- debug: (msg, ...args) => console.log('[DEBUG]', msg, ...args),
838
- info: (msg, ...args) => console.log('[INFO]', msg, ...args),
839
- warn: (msg, ...args) => console.warn('[WARN]', msg, ...args),
840
- error: (msg, ...args) => console.error('[ERROR]', msg, ...args),
841
- },
842
- };
843
-
844
- try {
845
- const validated = agent.inputSchema.parse(input);
846
- const output = await agent._run(validated, ctx);
847
- const validatedOutput = agent.outputSchema.parse(output);
848
- writeFileSync(OUTPUT_FILE, JSON.stringify({ success: true, output: validatedOutput }));
849
- } catch (error) {
850
- writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: error.message, stack: error.stack } }));
851
- }
852
- `;
777
+ }
778
+ async resolveRuntimeConnection(sandboxId) {
779
+ const targetId = sandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
780
+ if (!targetId) {
781
+ throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
782
+ }
783
+ if (!sandboxId && this._serverRuntime?.connection.sandboxId === targetId) {
784
+ return this._serverRuntime.connection;
785
+ }
786
+ const sandbox = await this.connectSandboxHandle(targetId);
787
+ const serverConfig = await this.readRuntimeServerConfig(sandbox);
788
+ const port = serverConfig?.port ?? this._server?.port ?? DEFAULT_SERVER_PORT;
789
+ const connection = await this.createRuntimeConnection(sandbox, port);
790
+ const healthUrl = this.healthUrlFor(connection);
791
+ try {
792
+ await waitForServerHealthy(healthUrl, connection, SERVER_RECONNECT_HEALTH_TIMEOUT_MS);
793
+ this._serverRuntime = { connection };
794
+ this._sandboxId = targetId;
795
+ return connection;
796
+ } catch {
797
+ const { sessionId, commandId } = await this.startRuntimeServer(sandbox);
798
+ try {
799
+ await waitForServerHealthy(healthUrl, connection);
800
+ } catch (error) {
801
+ const baseMessage = error instanceof Error ? error.message : String(error);
802
+ let logs = "";
803
+ if (commandId && sandbox.readSessionLogs) {
804
+ const captured = await sandbox.readSessionLogs(sessionId, commandId);
805
+ const parts = [];
806
+ if (captured.stdout.trim()) parts.push(`stdout:
807
+ ${captured.stdout}`);
808
+ if (captured.stderr.trim()) parts.push(`stderr:
809
+ ${captured.stderr}`);
810
+ if (parts.length > 0) {
811
+ logs = `
812
+ --- server logs ---
813
+ ${parts.join("\n\n")}`;
814
+ }
815
+ }
816
+ throw new DeploymentError(`${baseMessage}${logs}`);
817
+ }
818
+ this._serverRuntime = { sessionId, commandId, connection };
819
+ this._sandboxId = targetId;
820
+ return connection;
821
+ }
853
822
  }
854
823
  /**
855
- * Kills the current sandbox and resets the cached sandbox ID.
824
+ * Kills the current sandbox and resets the cached runtime.
856
825
  *
857
826
  * Use this to clean up sandbox resources after a run, especially when
858
827
  * running multiple evaluations that each need their own sandbox.
859
828
  *
860
- * @param sandboxId - Optional sandbox ID to kill. Defaults to the cached sandbox.
829
+ * @param target - Optional sandbox ID to kill. Defaults to the cached sandbox.
861
830
  *
862
831
  * @example
863
832
  * ```typescript
@@ -866,29 +835,36 @@ try {
866
835
  * await agent.kill(sandboxId);
867
836
  * ```
868
837
  */
869
- async kill(sandboxId) {
870
- const targetId = sandboxId ?? this._sandboxId;
838
+ async kill(target) {
839
+ const targetId = target ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
871
840
  if (!targetId) return;
872
841
  try {
873
842
  const sandbox = await this.connectSandboxHandle(targetId);
843
+ if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.sessionId && sandbox.stopSession) {
844
+ await sandbox.stopSession(this._serverRuntime.sessionId).catch(() => void 0);
845
+ }
874
846
  await sandbox.destroy();
875
847
  } catch {
876
848
  }
877
849
  if (targetId === this._sandboxId) {
878
850
  this._sandboxId = void 0;
879
851
  }
852
+ if (targetId === this._serverRuntime?.connection.sandboxId) {
853
+ this._serverRuntime = void 0;
854
+ }
880
855
  }
881
856
  /**
882
857
  * Deploys the agent to a sandbox provider.
883
858
  *
884
859
  * This method bundles the agent code using esbuild, creates a new sandbox,
885
860
  * installs any specified OS dependencies, downloads configured files, and
886
- * uploads the agent code to the sandbox.
861
+ * uploads the agent and runtime server code, then starts a long-running HTTP
862
+ * server inside the sandbox.
887
863
  *
888
864
  * @param options.fresh - When true, always creates a new sandbox without caching.
889
865
  * Useful for concurrent evaluations where each run needs its own sandbox.
890
866
  * The returned sandbox ID won't be stored on the instance.
891
- * @returns The sandbox ID, which can be used to reconnect via `run(input, { sandboxId })`
867
+ * @returns The sandbox ID. Persist this ID when another host process should reuse the sandbox.
892
868
  * @throws {ConfigurationError} If the selected provider credentials are not set
893
869
  * @throws {DeploymentError} If sandbox creation, dependency installation, or file upload fails
894
870
  *
@@ -899,50 +875,16 @@ try {
899
875
  * console.log(`Deployed to sandbox: ${sandboxId}`);
900
876
  *
901
877
  * // For concurrent evals: each call gets its own sandbox
902
- * const id = await agent.deploy({ fresh: true });
903
- * const result = await agent.run(input, { sandboxId: id });
904
- * await agent.kill(id);
878
+ * const sandboxId = await agent.deploy({ fresh: true });
879
+ * const result = await agent.run(input, { sandboxId });
880
+ * await agent.kill(sandboxId);
905
881
  * ```
906
882
  */
907
- /**
908
- * Deploy a one-shot agent. Throws if called on a server-mode agent; use
909
- * `deployServer()` for those. Returns the sandbox id so callers can pass it
910
- * to `run(input, { sandboxId })`.
911
- */
912
883
  async deploy(options) {
913
- if (this.mode !== "one-shot") {
914
- throw new ConfigurationError(
915
- "deploy() is only available on one-shot agents. Use agent.deployServer() for server-mode agents."
916
- );
917
- }
918
- const result = await this._deploy(options);
919
- return result;
920
- }
921
- /**
922
- * Deploy a server-mode agent. Throws if called on a one-shot agent; use
923
- * `deploy()` for those. Returns the sandbox id, public server URL, bearer
924
- * token, and Daytona preview token that `invoke()` needs to stream.
925
- */
926
- async deployServer(options) {
927
- if (this.mode !== "server") {
928
- throw new ConfigurationError(
929
- "deployServer() is only available on server-mode agents. Use agent.deploy() for one-shot agents."
930
- );
931
- }
932
- const result = await this._deploy(options);
933
- return result;
884
+ return this._deploy(options);
934
885
  }
935
886
  async _deploy(options) {
936
- if (!options?.fresh && this._sandboxId && this.mode === "one-shot") return this._sandboxId;
937
- if (!options?.fresh && this._sandboxId && this._serverRuntime) {
938
- return {
939
- mode: "server",
940
- sandboxId: this._sandboxId,
941
- serverUrl: this._serverRuntime.serverUrl,
942
- authToken: this._serverRuntime.authToken,
943
- previewToken: this._serverRuntime.previewToken
944
- };
945
- }
887
+ if (!options?.fresh && this._serverRuntime) return this._serverRuntime.connection.sandboxId;
946
888
  const esbuild = await getEsbuild();
947
889
  const externalPatterns = Array.from(
948
890
  /* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
@@ -960,7 +902,7 @@ try {
960
902
  minify: true,
961
903
  keepNames: true,
962
904
  treeShaking: false,
963
- // Preserve exports for the sandbox runner to import
905
+ // Preserve exports for the runtime server to import
964
906
  banner: {
965
907
  js: `import { fileURLToPath as __neckbeard_fileURLToPath } from 'node:url';
966
908
  import { dirname as __neckbeard_dirname } from 'node:path';
@@ -1015,9 +957,18 @@ var require = __neckbeard_createRequire(import.meta.url);
1015
957
  }
1016
958
  }]
1017
959
  });
960
+ const serverResult = await esbuild.build({
961
+ entryPoints: [getRuntimeServerEntryPoint()],
962
+ bundle: true,
963
+ platform: "node",
964
+ target: NODE_TARGET,
965
+ format: "esm",
966
+ write: false,
967
+ minify: false,
968
+ external: ["./agent.mjs"]
969
+ });
1018
970
  const sandbox = await this.createSandboxHandle();
1019
971
  const { paths } = sandbox;
1020
- const runnerCode = this.buildRunnerCode(paths);
1021
972
  await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
1022
973
  timeoutMs: QUICK_COMMAND_TIMEOUT_MS
1023
974
  });
@@ -1091,114 +1042,86 @@ var require = __neckbeard_createRequire(import.meta.url);
1091
1042
  }
1092
1043
  }
1093
1044
  await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
1094
- if (this.mode === "one-shot") {
1095
- await sandbox.writeFile(paths.runnerModule, runnerCode);
1096
- } else if (this._server) {
1097
- const port = this._server.port ?? DEFAULT_SERVER_PORT;
1098
- const serverCode = buildServerCode({
1099
- port,
1100
- sandboxContext: {
1101
- provider: paths.provider,
1102
- homeDir: paths.homeDir,
1103
- workDir: paths.workDir,
1104
- agentDir: paths.agentDir,
1105
- ioDir: paths.ioDir,
1106
- inputJson: paths.inputJson,
1107
- outputJson: paths.outputJson
1108
- },
1109
- maxDurationSeconds: this.maxDuration
1110
- });
1111
- await sandbox.writeFile(`${paths.agentDir}/server.mjs`, serverCode);
1112
- }
1045
+ await sandbox.writeFile(paths.serverModule, serverResult.outputFiles[0].text);
1046
+ const serverConfig = {
1047
+ port: this._server?.port ?? DEFAULT_SERVER_PORT,
1048
+ maxDurationMs: this.maxDuration * 1e3,
1049
+ sandboxContext: {
1050
+ provider: paths.provider,
1051
+ homeDir: paths.homeDir,
1052
+ workDir: paths.workDir,
1053
+ agentDir: paths.agentDir,
1054
+ ioDir: paths.ioDir,
1055
+ inputJson: paths.inputJson,
1056
+ outputJson: paths.outputJson
1057
+ }
1058
+ };
1059
+ await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
1113
1060
  if (collectedExternals.size > 0) {
1114
1061
  const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
1115
1062
  const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
1116
- if (Object.keys(dependencies).length === 0) {
1117
- if (!options?.fresh) this._sandboxId = sandbox.id;
1118
- return sandbox.id;
1119
- }
1120
- const pkgJson = JSON.stringify({
1121
- name: "agent-sandbox",
1122
- type: "module",
1123
- dependencies
1124
- });
1125
- await sandbox.writeFile(paths.packageJson, pkgJson);
1126
- const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
1127
- cwd: paths.agentDir,
1128
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
1129
- });
1130
- if (installResult.exitCode !== 0) {
1131
- const details = [
1132
- `Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
1133
- installResult.stderr ? `stderr: ${installResult.stderr}` : "",
1134
- installResult.stdout ? `stdout: ${installResult.stdout}` : ""
1135
- ].filter(Boolean).join("\n");
1136
- throw new DeploymentError(details);
1063
+ if (Object.keys(dependencies).length > 0) {
1064
+ const pkgJson = JSON.stringify({
1065
+ name: "agent-sandbox",
1066
+ type: "module",
1067
+ dependencies
1068
+ });
1069
+ await sandbox.writeFile(paths.packageJson, pkgJson);
1070
+ const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
1071
+ cwd: paths.agentDir,
1072
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
1073
+ });
1074
+ if (installResult.exitCode !== 0) {
1075
+ const details = [
1076
+ `Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
1077
+ installResult.stderr ? `stderr: ${installResult.stderr}` : "",
1078
+ installResult.stdout ? `stdout: ${installResult.stdout}` : ""
1079
+ ].filter(Boolean).join("\n");
1080
+ throw new DeploymentError(details);
1081
+ }
1137
1082
  }
1138
1083
  }
1139
- if (this.mode === "server") {
1140
- if (!sandbox.startDetachedCommand || !sandbox.getPreviewLink) {
1141
- throw new DeploymentError(
1142
- "Server-mode agents require a sandbox provider that supports detached sessions and preview URLs (currently Daytona only)."
1143
- );
1144
- }
1145
- const port = this._server?.port ?? DEFAULT_SERVER_PORT;
1146
- const authToken = generateAuthToken();
1147
- const { sessionId, commandId } = await sandbox.startDetachedCommand("node server.mjs", {
1148
- cwd: paths.agentDir,
1149
- envs: {
1150
- ...this.sandboxEnv,
1151
- NECKBEARD_SERVER_PORT: String(port),
1152
- NECKBEARD_SERVER_TOKEN: authToken
1153
- }
1154
- });
1155
- const { url: previewUrl, token: previewToken } = await sandbox.getPreviewLink(port);
1156
- const serverUrl = `${previewUrl.replace(/\/$/, "")}/invoke`;
1157
- const healthUrl = `${previewUrl.replace(/\/$/, "")}/health`;
1158
- try {
1159
- await waitForServerHealthy(healthUrl, authToken, previewToken);
1160
- } catch (err) {
1161
- const baseMessage = err instanceof Error ? err.message : String(err);
1162
- let logs = "";
1163
- if (commandId && sandbox.readSessionLogs) {
1164
- const captured = await sandbox.readSessionLogs(sessionId, commandId);
1165
- const parts = [];
1166
- if (captured.stdout.trim()) parts.push(`stdout:
1084
+ const port = serverConfig.port;
1085
+ const { sessionId, commandId } = await this.startRuntimeServer(sandbox);
1086
+ const connection = await this.createRuntimeConnection(sandbox, port);
1087
+ const healthUrl = this.healthUrlFor(connection);
1088
+ try {
1089
+ await waitForServerHealthy(healthUrl, connection);
1090
+ } catch (err) {
1091
+ const baseMessage = err instanceof Error ? err.message : String(err);
1092
+ let logs = "";
1093
+ if (commandId && sandbox.readSessionLogs) {
1094
+ const captured = await sandbox.readSessionLogs(sessionId, commandId);
1095
+ const parts = [];
1096
+ if (captured.stdout.trim()) parts.push(`stdout:
1167
1097
  ${captured.stdout}`);
1168
- if (captured.stderr.trim()) parts.push(`stderr:
1098
+ if (captured.stderr.trim()) parts.push(`stderr:
1169
1099
  ${captured.stderr}`);
1170
- if (parts.length > 0) {
1171
- logs = `
1100
+ if (parts.length > 0) {
1101
+ logs = `
1172
1102
  --- server logs ---
1173
1103
  ${parts.join("\n\n")}`;
1174
- }
1175
1104
  }
1176
- throw new DeploymentError(`${baseMessage}${logs}`);
1177
1105
  }
1178
- if (!options?.fresh) this._sandboxId = sandbox.id;
1179
- this._serverRuntime = { sessionId, serverUrl, authToken, previewToken };
1180
- return {
1181
- mode: "server",
1182
- sandboxId: sandbox.id,
1183
- serverUrl,
1184
- authToken,
1185
- previewToken
1186
- };
1106
+ throw new DeploymentError(`${baseMessage}${logs}`);
1107
+ }
1108
+ if (!options?.fresh) {
1109
+ this._sandboxId = sandbox.id;
1110
+ this._serverRuntime = { sessionId, commandId, connection };
1187
1111
  }
1188
- if (!options?.fresh) this._sandboxId = sandbox.id;
1189
1112
  return sandbox.id;
1190
1113
  }
1191
1114
  /**
1192
1115
  * Executes the agent with the given input.
1193
1116
  *
1194
- * The agent must be deployed before calling this method, or a sandboxId must
1195
- * be provided in the options. Input is validated against the input schema,
1196
- * then the agent runs in the sandbox with the validated input. Output is
1197
- * validated against the output schema before being returned.
1117
+ * The agent must be deployed before calling this method, or a sandbox ID
1118
+ * must be provided in the options. Input is validated against the input
1119
+ * schema, then POSTed to the in-sandbox server. Output is validated against
1120
+ * the output schema before being returned.
1198
1121
  *
1199
1122
  * @param input - The input data for the agent, must conform to inputSchema
1200
1123
  * @param options - Optional configuration for this run
1201
- * @param options.sandboxId - Sandbox ID to use, overrides the deployed sandbox
1124
+ * @param options.sandboxId - Sandbox ID to use, overrides the cached sandbox
1202
1125
  * @returns A result object indicating success or failure with output or error
1203
1126
  *
1204
1127
  * @example
@@ -1206,122 +1129,84 @@ ${parts.join("\n\n")}`;
1206
1129
  * // Using deployed sandbox
1207
1130
  * const result = await agent.run({ prompt: 'Hello, world!' });
1208
1131
  *
1209
- * // Using explicit sandboxId (for reconnecting)
1210
- * const result = await agent.run({ prompt: 'Hello!' }, { sandboxId: 'sbx_...' });
1132
+ * // Reconnecting from another process
1133
+ * const result = await agent.run({ prompt: 'Hello!' }, { sandboxId });
1211
1134
  * ```
1212
1135
  */
1213
1136
  async run(input, options) {
1214
1137
  const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1215
- if (this.mode === "server") {
1138
+ if (this.mode !== "run") {
1216
1139
  return {
1217
1140
  ok: false,
1218
1141
  executionId,
1219
1142
  error: new ExecutionError(
1220
- "run() is not available on server-mode agents. Use agent.invoke() instead."
1143
+ "run() is only available on agents configured with a run handler. Use agent.invoke() for streaming agents."
1221
1144
  )
1222
1145
  };
1223
1146
  }
1224
- const sandboxId = options?.sandboxId ?? this._sandboxId;
1225
- if (!sandboxId) {
1226
- return {
1227
- ok: false,
1228
- executionId,
1229
- error: new ExecutionError("Agent not deployed. Call agent.deploy() first or pass sandboxId to run().")
1230
- };
1231
- }
1232
1147
  try {
1148
+ const connection = await this.resolveRuntimeConnection(options?.sandboxId);
1233
1149
  const validatedInput = this.inputSchema.parse(input);
1234
- const sandbox = await this.connectSandboxHandle(sandboxId);
1235
- const { paths } = sandbox;
1236
- await sandbox.writeFile(paths.inputJson, JSON.stringify({ input: validatedInput, executionId }));
1237
- let capturedStdout = "";
1238
- let capturedStderr = "";
1239
- const result = await sandbox.runCommand("node runner.mjs", {
1240
- cwd: paths.agentDir,
1241
- timeoutMs: this.maxDuration * 1e3,
1242
- envs: this.sandboxEnv,
1243
- onStdout: (data) => {
1244
- capturedStdout += data;
1245
- },
1246
- onStderr: (data) => {
1247
- capturedStderr += data;
1150
+ const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
1151
+ let output;
1152
+ let sawOutput = false;
1153
+ for await (const event of invokeServer2(validatedInput, {
1154
+ serverUrl: connection.serverUrl,
1155
+ provider: connection.provider,
1156
+ trafficToken: getTrafficToken(connection),
1157
+ invocationId: executionId,
1158
+ signal: AbortSignal.timeout(this.maxDuration * 1e3 + 5e3)
1159
+ })) {
1160
+ if (event.kind === "error") {
1161
+ const err = new ExecutionError(event.error.message);
1162
+ err.stack = event.error.stack;
1163
+ return { ok: false, executionId, error: err };
1248
1164
  }
1249
- });
1250
- if (result.exitCode !== 0) {
1251
- let resultError = "";
1252
- try {
1253
- const resultJson = await sandbox.readFile(paths.outputJson);
1254
- const parsed = JSON.parse(resultJson);
1255
- if (!parsed.success && parsed.error) {
1256
- resultError = `
1257
- Result: ${parsed.error.message}`;
1258
- if (parsed.error.stack) resultError += `
1259
- Stack: ${parsed.error.stack}`;
1260
- }
1261
- } catch {
1165
+ if (event.kind === "output") {
1166
+ output = event.output;
1167
+ sawOutput = true;
1262
1168
  }
1263
- const errorDetails = [
1264
- `Agent failed with exit code ${result.exitCode}`,
1265
- result.stderr ? `Stderr: ${result.stderr}` : "",
1266
- capturedStderr ? `Captured stderr: ${capturedStderr}` : "",
1267
- capturedStdout ? `Stdout: ${capturedStdout}` : "",
1268
- resultError
1269
- ].filter(Boolean).join("\n");
1270
- return { ok: false, executionId, error: new ExecutionError(errorDetails) };
1271
1169
  }
1272
- const output = JSON.parse(await sandbox.readFile(paths.outputJson));
1273
- if (!output.success) {
1274
- const errorDetails = [
1275
- output.error.message,
1276
- capturedStderr ? `
1277
- Captured stderr: ${capturedStderr}` : "",
1278
- capturedStdout ? `
1279
- Stdout: ${capturedStdout}` : ""
1280
- ].filter(Boolean).join("");
1281
- const err = new ExecutionError(errorDetails);
1282
- err.stack = output.error.stack;
1283
- return { ok: false, executionId, error: err };
1170
+ if (!sawOutput) {
1171
+ return {
1172
+ ok: false,
1173
+ executionId,
1174
+ error: new ExecutionError("Agent server completed without returning output.")
1175
+ };
1284
1176
  }
1285
- const validated = this.outputSchema ? this.outputSchema.parse(output.output) : output.output;
1177
+ const validated = this.outputSchema ? this.outputSchema.parse(output) : output;
1286
1178
  return { ok: true, executionId, output: validated };
1287
1179
  } catch (err) {
1288
1180
  return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
1289
1181
  }
1290
1182
  }
1291
1183
  /**
1292
- * Invoke a server-mode agent. Streams the agent's emitted frames back as an
1293
- * async iterator as the handler runs. Only valid for agents constructed with
1294
- * `server: {...}` config; one-shot agents should use `run()` instead.
1295
- *
1296
- * Requires the agent to be deployed via `deploy()` (returns `serverUrl` and
1297
- * `authToken`) — callers must persist those values and pass them on each
1298
- * invocation. Deploy is not yet implemented for server mode; this method
1299
- * currently throws `ConfigurationError` if `serverUrl` is not supplied.
1184
+ * Invoke a streaming agent. Streams user frames emitted by the in-sandbox
1185
+ * handler as an async iterator.
1300
1186
  */
1301
1187
  async *invoke(input, options) {
1302
- if (this.mode !== "server") {
1303
- throw new ConfigurationError(
1304
- "invoke() is only available on server-mode agents. Use agent.run() for one-shot agents."
1305
- );
1306
- }
1307
- const serverUrl = options?.serverUrl ?? this._serverRuntime?.serverUrl;
1308
- const authToken = options?.authToken ?? this._serverRuntime?.authToken;
1309
- const previewToken = options?.previewToken ?? this._serverRuntime?.previewToken;
1310
- if (!serverUrl || !authToken) {
1188
+ if (this.mode !== "stream") {
1311
1189
  throw new ConfigurationError(
1312
- "Agent not deployed in server mode. Call agent.deploy() first and pass the returned serverUrl and authToken to invoke()."
1190
+ "invoke() is only available on agents configured with server.handler. Use agent.run() for run-output agents."
1313
1191
  );
1314
1192
  }
1315
- const urlWithPreviewToken = previewToken ? `${serverUrl}${serverUrl.includes("?") ? "&" : "?"}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(previewToken)}` : serverUrl;
1193
+ const connection = await this.resolveRuntimeConnection(options?.sandboxId);
1316
1194
  const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
1317
1195
  const validated = this.inputSchema.parse(input);
1318
1196
  for await (const frame of invokeServer2(validated, {
1319
- serverUrl: urlWithPreviewToken,
1320
- authToken,
1197
+ serverUrl: connection.serverUrl,
1198
+ provider: connection.provider,
1199
+ trafficToken: getTrafficToken(connection),
1321
1200
  frameSchema: this.frameSchema,
1322
1201
  signal: options?.signal
1323
1202
  })) {
1324
- yield frame;
1203
+ if (frame.kind === "frame") {
1204
+ yield frame.data;
1205
+ } else if (frame.kind === "error") {
1206
+ const err = new ExecutionError(frame.error.message);
1207
+ err.stack = frame.error.stack;
1208
+ throw err;
1209
+ }
1325
1210
  }
1326
1211
  }
1327
1212
  };