agent-neckbeard 1.1.4 → 1.1.6

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
@@ -5,6 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
8
11
  var __export = (target, all) => {
9
12
  for (var name in all)
10
13
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -27,6 +30,107 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
30
  ));
28
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
32
 
33
+ // src/sse-framing.ts
34
+ async function* decodeSseStream(chunks) {
35
+ let buffer = "";
36
+ for await (const chunk of chunks) {
37
+ buffer += chunk;
38
+ let boundary = buffer.indexOf("\n\n");
39
+ while (boundary !== -1) {
40
+ const rawFrame = buffer.slice(0, boundary);
41
+ buffer = buffer.slice(boundary + 2);
42
+ const parsed = parseFrame(rawFrame);
43
+ if (parsed !== void 0) {
44
+ yield parsed;
45
+ }
46
+ boundary = buffer.indexOf("\n\n");
47
+ }
48
+ }
49
+ const tail = buffer.trim();
50
+ if (tail.length > 0) {
51
+ const parsed = parseFrame(tail);
52
+ if (parsed !== void 0) {
53
+ yield parsed;
54
+ }
55
+ }
56
+ }
57
+ function parseFrame(raw) {
58
+ const dataLines = [];
59
+ for (const line of raw.split("\n")) {
60
+ if (line.startsWith("data:")) {
61
+ dataLines.push(line.slice("data:".length).replace(/^ /, ""));
62
+ }
63
+ }
64
+ if (dataLines.length === 0) return void 0;
65
+ try {
66
+ return JSON.parse(dataLines.join("\n"));
67
+ } catch {
68
+ return void 0;
69
+ }
70
+ }
71
+ var init_sse_framing = __esm({
72
+ "src/sse-framing.ts"() {
73
+ "use strict";
74
+ }
75
+ });
76
+
77
+ // src/invoke-client.ts
78
+ var invoke_client_exports = {};
79
+ __export(invoke_client_exports, {
80
+ invokeServer: () => invokeServer
81
+ });
82
+ async function* invokeServer(input, options) {
83
+ const fetchImpl = options.fetch ?? fetch;
84
+ const response = await fetchImpl(options.serverUrl, {
85
+ 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),
92
+ signal: options.signal
93
+ });
94
+ if (!response.ok) {
95
+ const text = await response.text().catch(() => "");
96
+ throw new Error(
97
+ `Server returned ${response.status}${text ? `: ${text}` : ""}`
98
+ );
99
+ }
100
+ if (!response.body) {
101
+ throw new Error("Server response had no body");
102
+ }
103
+ const reader = response.body.getReader();
104
+ const decoder = new TextDecoder();
105
+ async function* chunks() {
106
+ try {
107
+ while (true) {
108
+ const { value, done } = await reader.read();
109
+ if (done) return;
110
+ yield decoder.decode(value, { stream: true });
111
+ }
112
+ } finally {
113
+ try {
114
+ reader.releaseLock();
115
+ } catch {
116
+ }
117
+ }
118
+ }
119
+ for await (const rawFrame of decodeSseStream(chunks())) {
120
+ if (options.frameSchema) {
121
+ yield options.frameSchema.parse(rawFrame);
122
+ } else {
123
+ yield rawFrame;
124
+ }
125
+ }
126
+ }
127
+ var init_invoke_client = __esm({
128
+ "src/invoke-client.ts"() {
129
+ "use strict";
130
+ init_sse_framing();
131
+ }
132
+ });
133
+
30
134
  // src/index.ts
31
135
  var index_exports = {};
32
136
  __export(index_exports, {
@@ -44,6 +148,168 @@ var import_node_url = require("url");
44
148
  var import_node_fs = require("fs");
45
149
  var import_node_path = require("path");
46
150
  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
47
313
  function readPackageJson(path) {
48
314
  return JSON.parse((0, import_node_fs.readFileSync)(path, "utf8"));
49
315
  }
@@ -58,6 +324,9 @@ var NODE_TARGET = "node20";
58
324
  var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
59
325
  var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
60
326
  var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
327
+ var DEFAULT_SERVER_PORT = 3e3;
328
+ var SERVER_HEALTH_TIMEOUT_MS = 12e4;
329
+ var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
61
330
  var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
62
331
  var E2B_SANDBOX_HOME = "/home/user";
63
332
  var NeckbeardError = class extends Error {
@@ -94,6 +363,36 @@ var ConfigurationError = class extends NeckbeardError {
94
363
  }
95
364
  };
96
365
  var DEFAULT_DEPENDENCIES = {};
366
+ function isServerAgentConfig(config) {
367
+ return "server" in config && config.server !== void 0;
368
+ }
369
+ function generateAuthToken() {
370
+ return (0, import_node_crypto.randomBytes)(32).toString("hex");
371
+ }
372
+ async function waitForServerHealthy(healthUrl, authToken, previewToken) {
373
+ const deadline = Date.now() + SERVER_HEALTH_TIMEOUT_MS;
374
+ let lastError;
375
+ const urlWithToken = previewToken ? `${healthUrl}${healthUrl.includes("?") ? "&" : "?"}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(previewToken)}` : healthUrl;
376
+ while (Date.now() < deadline) {
377
+ try {
378
+ const response = await fetch(urlWithToken, {
379
+ headers: { authorization: `Bearer ${authToken}` }
380
+ });
381
+ if (response.ok) {
382
+ await response.text().catch(() => void 0);
383
+ return;
384
+ }
385
+ lastError = new Error(`health check returned ${response.status}`);
386
+ } catch (error) {
387
+ lastError = error;
388
+ }
389
+ await new Promise((resolve2) => setTimeout(resolve2, SERVER_HEALTH_POLL_INTERVAL_MS));
390
+ }
391
+ const message = lastError instanceof Error ? lastError.message : String(lastError);
392
+ throw new DeploymentError(
393
+ `Server did not become healthy at ${healthUrl} within ${SERVER_HEALTH_TIMEOUT_MS}ms: ${message}`
394
+ );
395
+ }
97
396
  function requireEnv(name) {
98
397
  const value = process.env[name];
99
398
  if (!value) {
@@ -310,6 +609,34 @@ async function createDaytonaHandle(sandbox) {
310
609
  stderr: ""
311
610
  };
312
611
  },
612
+ startDetachedCommand: async (cmd, options) => {
613
+ const sessionId = `neckbeard-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
614
+ await sandbox.process.createSession(sessionId);
615
+ const envPrefix = options.envs ? Object.entries(options.envs).map(([k, v]) => `${k}=${shellEscape(v)}`).join(" ") + " " : "";
616
+ const cwdPrefix = options.cwd ? `cd ${shellEscape(options.cwd)} && ` : "";
617
+ const result = await sandbox.process.executeSessionCommand(sessionId, {
618
+ command: `${cwdPrefix}${envPrefix}${cmd}`,
619
+ runAsync: true
620
+ });
621
+ return { sessionId, commandId: result.cmdId };
622
+ },
623
+ readSessionLogs: async (sessionId, commandId) => {
624
+ try {
625
+ const logs = await sandbox.process.getSessionCommandLogs(sessionId, commandId);
626
+ return {
627
+ stdout: logs.stdout ?? logs.output ?? "",
628
+ stderr: logs.stderr ?? ""
629
+ };
630
+ } catch {
631
+ return { stdout: "", stderr: "" };
632
+ }
633
+ },
634
+ stopSession: async (sessionId) => {
635
+ await sandbox.process.deleteSession(sessionId);
636
+ },
637
+ getPreviewLink: async (port) => {
638
+ return sandbox.getPreviewLink(port);
639
+ },
313
640
  destroy: () => sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS))
314
641
  };
315
642
  }
@@ -370,15 +697,23 @@ var Agent = class {
370
697
  provider;
371
698
  template;
372
699
  inputSchema;
700
+ /** Only populated for one-shot agents; undefined for server-mode. */
373
701
  outputSchema;
702
+ /** Only populated for server-mode agents; undefined for one-shot. */
703
+ frameSchema;
704
+ mode;
374
705
  maxDuration;
375
706
  dependencies;
376
707
  files;
377
708
  claudeDir;
378
709
  envs;
379
710
  build;
380
- /** @internal Used by the sandbox runner - must be public for bundled code access */
711
+ /** @internal Used by the sandbox runner for one-shot agents. */
381
712
  _run;
713
+ /** @internal Used by the in-sandbox HTTP server for server-mode agents. */
714
+ _server;
715
+ /** @internal Runtime state populated by deploy() for server-mode agents. */
716
+ _serverRuntime;
382
717
  _sourceFile;
383
718
  _sandboxId;
384
719
  constructor(config) {
@@ -386,15 +721,22 @@ var Agent = class {
386
721
  this.provider = config.sandbox.provider;
387
722
  this.template = config.sandbox.template;
388
723
  this.inputSchema = config.inputSchema;
389
- this.outputSchema = config.outputSchema;
390
724
  this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
391
- this._run = config.run;
392
725
  this._sourceFile = getCallerFile();
393
726
  this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
394
727
  this.files = config.files ?? [];
395
728
  this.claudeDir = config.claudeDir;
396
729
  this.envs = config.envs ?? {};
397
730
  this.build = config.build ?? {};
731
+ if (isServerAgentConfig(config)) {
732
+ this.mode = "server";
733
+ this._server = config.server;
734
+ this.frameSchema = config.server.frameSchema;
735
+ } else {
736
+ this.mode = "one-shot";
737
+ this._run = config.run;
738
+ this.outputSchema = config.outputSchema;
739
+ }
398
740
  }
399
741
  get sandboxId() {
400
742
  return this._sandboxId;
@@ -562,8 +904,45 @@ try {
562
904
  * await agent.kill(id);
563
905
  * ```
564
906
  */
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
+ */
565
912
  async deploy(options) {
566
- if (!options?.fresh && this._sandboxId) return this._sandboxId;
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;
934
+ }
935
+ 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
+ }
567
946
  const esbuild = await getEsbuild();
568
947
  const externalPatterns = Array.from(
569
948
  /* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
@@ -606,6 +985,10 @@ var require = __neckbeard_createRequire(import.meta.url);
606
985
  this.outputSchema = config.outputSchema;
607
986
  this.maxDuration = config.maxDuration ?? 300;
608
987
  this._run = config.run;
988
+ if (config.server) {
989
+ this._server = config.server;
990
+ this.frameSchema = config.server.frameSchema;
991
+ }
609
992
  }
610
993
  }
611
994
  `,
@@ -708,7 +1091,25 @@ var require = __neckbeard_createRequire(import.meta.url);
708
1091
  }
709
1092
  }
710
1093
  await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
711
- await sandbox.writeFile(paths.runnerModule, runnerCode);
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
+ }
712
1113
  if (collectedExternals.size > 0) {
713
1114
  const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
714
1115
  const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
@@ -735,6 +1136,55 @@ var require = __neckbeard_createRequire(import.meta.url);
735
1136
  throw new DeploymentError(details);
736
1137
  }
737
1138
  }
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:
1167
+ ${captured.stdout}`);
1168
+ if (captured.stderr.trim()) parts.push(`stderr:
1169
+ ${captured.stderr}`);
1170
+ if (parts.length > 0) {
1171
+ logs = `
1172
+ --- server logs ---
1173
+ ${parts.join("\n\n")}`;
1174
+ }
1175
+ }
1176
+ throw new DeploymentError(`${baseMessage}${logs}`);
1177
+ }
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
+ };
1187
+ }
738
1188
  if (!options?.fresh) this._sandboxId = sandbox.id;
739
1189
  return sandbox.id;
740
1190
  }
@@ -762,6 +1212,15 @@ var require = __neckbeard_createRequire(import.meta.url);
762
1212
  */
763
1213
  async run(input, options) {
764
1214
  const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1215
+ if (this.mode === "server") {
1216
+ return {
1217
+ ok: false,
1218
+ executionId,
1219
+ error: new ExecutionError(
1220
+ "run() is not available on server-mode agents. Use agent.invoke() instead."
1221
+ )
1222
+ };
1223
+ }
765
1224
  const sandboxId = options?.sandboxId ?? this._sandboxId;
766
1225
  if (!sandboxId) {
767
1226
  return {
@@ -823,11 +1282,48 @@ Stdout: ${capturedStdout}` : ""
823
1282
  err.stack = output.error.stack;
824
1283
  return { ok: false, executionId, error: err };
825
1284
  }
826
- return { ok: true, executionId, output: this.outputSchema.parse(output.output) };
1285
+ const validated = this.outputSchema ? this.outputSchema.parse(output.output) : output.output;
1286
+ return { ok: true, executionId, output: validated };
827
1287
  } catch (err) {
828
1288
  return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
829
1289
  }
830
1290
  }
1291
+ /**
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.
1300
+ */
1301
+ 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) {
1311
+ throw new ConfigurationError(
1312
+ "Agent not deployed in server mode. Call agent.deploy() first and pass the returned serverUrl and authToken to invoke()."
1313
+ );
1314
+ }
1315
+ const urlWithPreviewToken = previewToken ? `${serverUrl}${serverUrl.includes("?") ? "&" : "?"}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(previewToken)}` : serverUrl;
1316
+ const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
1317
+ const validated = this.inputSchema.parse(input);
1318
+ for await (const frame of invokeServer2(validated, {
1319
+ serverUrl: urlWithPreviewToken,
1320
+ authToken,
1321
+ frameSchema: this.frameSchema,
1322
+ signal: options?.signal
1323
+ })) {
1324
+ yield frame;
1325
+ }
1326
+ }
831
1327
  };
832
1328
  // Annotate the CommonJS export names for ESM import in node:
833
1329
  0 && (module.exports = {