agent-neckbeard 1.1.8 → 1.1.10

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/README.md CHANGED
@@ -46,7 +46,7 @@ const sandboxId = await agent.deploy();
46
46
  const result = await agent.run({ topic: 'TypeScript generics' }, { sandboxId });
47
47
  ```
48
48
 
49
- `deploy()` bundles your agent, uploads `agent.mjs` and a TypeScript runtime server to the sandbox, starts `node server.mjs`, waits for `/health`, and returns the sandbox ID.
49
+ `deploy()` bundles your agent, uploads `agent.mjs` and the embedded runtime server to the sandbox, starts `node server.mjs`, waits for `/health`, and returns the sandbox ID.
50
50
 
51
51
  `run()` validates input locally, POSTs it to the sandbox server, reads SSE harness events, validates the final output, and returns the existing `{ ok, executionId, output | error }` result shape.
52
52
 
package/dist/index.cjs CHANGED
@@ -188,6 +188,11 @@ var import_node_url = require("url");
188
188
  var import_node_fs = require("fs");
189
189
  var import_node_path = require("path");
190
190
  var import_node_module = require("module");
191
+
192
+ // src/runtime/server-source.generated.ts
193
+ var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n }\n return { message: String(error) };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction sendSseFrame(res, event) {\n res.write(`data: ${JSON.stringify(event)}\n\n`);\n}\nasync function readRequestBody(req) {\n const chunks = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, { ok: true });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n const rawBody = await readRequestBody(req);\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const emitHarnessEvent = (event) => {\n if (!res.writableEnded) {\n sendSseFrame(res, event);\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => emitHarnessEvent({ kind: "frame", invocationId, data })\n });\n } else if (agent._run) {\n const output = await agent._run(validatedInput, ctx);\n emitHarnessEvent({ kind: "output", invocationId, output });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
194
+
195
+ // src/index.ts
191
196
  function readPackageJson(path) {
192
197
  return JSON.parse((0, import_node_fs.readFileSync)(path, "utf8"));
193
198
  }
@@ -473,7 +478,7 @@ function createE2bHandle(sandbox) {
473
478
  startDetachedCommand: async (cmd, options) => {
474
479
  const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
475
480
  const handle = await sandbox.commands.run(command, {
476
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS,
481
+ timeoutMs: 0,
477
482
  envs: options.envs,
478
483
  background: true
479
484
  });
@@ -614,32 +619,6 @@ function readDirectoryRecursively(dirPath) {
614
619
  walkDir(dirPath);
615
620
  return files;
616
621
  }
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
- }
643
622
  var Agent = class {
644
623
  sandbox;
645
624
  provider;
@@ -957,16 +936,6 @@ var require = __neckbeard_createRequire(import.meta.url);
957
936
  }
958
937
  }]
959
938
  });
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
- });
970
939
  const sandbox = await this.createSandboxHandle();
971
940
  const { paths } = sandbox;
972
941
  await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
@@ -1042,7 +1011,7 @@ var require = __neckbeard_createRequire(import.meta.url);
1042
1011
  }
1043
1012
  }
1044
1013
  await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
1045
- await sandbox.writeFile(paths.serverModule, serverResult.outputFiles[0].text);
1014
+ await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
1046
1015
  const serverConfig = {
1047
1016
  port: this._server?.port ?? DEFAULT_SERVER_PORT,
1048
1017
  maxDurationMs: this.maxDuration * 1e3,
package/dist/index.js CHANGED
@@ -3,6 +3,11 @@ import { fileURLToPath } from "url";
3
3
  import { existsSync, readdirSync, readFileSync, statSync } from "fs";
4
4
  import { dirname, join, relative, resolve } from "path";
5
5
  import { builtinModules, createRequire } from "module";
6
+
7
+ // src/runtime/server-source.generated.ts
8
+ var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n }\n return { message: String(error) };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction sendSseFrame(res, event) {\n res.write(`data: ${JSON.stringify(event)}\n\n`);\n}\nasync function readRequestBody(req) {\n const chunks = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, { ok: true });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n const rawBody = await readRequestBody(req);\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const emitHarnessEvent = (event) => {\n if (!res.writableEnded) {\n sendSseFrame(res, event);\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => emitHarnessEvent({ kind: "frame", invocationId, data })\n });\n } else if (agent._run) {\n const output = await agent._run(validatedInput, ctx);\n emitHarnessEvent({ kind: "output", invocationId, output });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
9
+
10
+ // src/index.ts
6
11
  function readPackageJson(path) {
7
12
  return JSON.parse(readFileSync(path, "utf8"));
8
13
  }
@@ -288,7 +293,7 @@ function createE2bHandle(sandbox) {
288
293
  startDetachedCommand: async (cmd, options) => {
289
294
  const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
290
295
  const handle = await sandbox.commands.run(command, {
291
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS,
296
+ timeoutMs: 0,
292
297
  envs: options.envs,
293
298
  background: true
294
299
  });
@@ -429,32 +434,6 @@ function readDirectoryRecursively(dirPath) {
429
434
  walkDir(dirPath);
430
435
  return files;
431
436
  }
432
- function getRuntimeServerEntryPoint() {
433
- const currentFile = getCurrentModuleFile();
434
- const currentDir = currentFile ? dirname(currentFile) : process.cwd();
435
- const candidates = [
436
- join(currentDir, "runtime/server.ts"),
437
- join(currentDir, "runtime/server.js"),
438
- join(currentDir, "runtime/server.mjs")
439
- ];
440
- const entry = candidates.find((candidate) => existsSync(candidate));
441
- if (!entry) {
442
- throw new DeploymentError(
443
- `Could not find neckbeard runtime server entry. Tried: ${candidates.join(", ")}`
444
- );
445
- }
446
- return entry;
447
- }
448
- function getCurrentModuleFile() {
449
- const stack = new Error().stack?.split("\n") ?? [];
450
- for (const line of stack.slice(1)) {
451
- const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
452
- if (!match) continue;
453
- const normalized = normalizeStackFramePath(match[1]);
454
- if (normalized && existsSync(normalized)) return normalized;
455
- }
456
- return null;
457
- }
458
437
  var Agent = class {
459
438
  sandbox;
460
439
  provider;
@@ -772,16 +751,6 @@ var require = __neckbeard_createRequire(import.meta.url);
772
751
  }
773
752
  }]
774
753
  });
775
- const serverResult = await esbuild.build({
776
- entryPoints: [getRuntimeServerEntryPoint()],
777
- bundle: true,
778
- platform: "node",
779
- target: NODE_TARGET,
780
- format: "esm",
781
- write: false,
782
- minify: false,
783
- external: ["./agent.mjs"]
784
- });
785
754
  const sandbox = await this.createSandboxHandle();
786
755
  const { paths } = sandbox;
787
756
  await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
@@ -857,7 +826,7 @@ var require = __neckbeard_createRequire(import.meta.url);
857
826
  }
858
827
  }
859
828
  await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
860
- await sandbox.writeFile(paths.serverModule, serverResult.outputFiles[0].text);
829
+ await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
861
830
  const serverConfig = {
862
831
  port: this._server?.port ?? DEFAULT_SERVER_PORT,
863
832
  maxDurationMs: this.maxDuration * 1e3,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-neckbeard",
3
- "version": "1.1.8",
3
+ "version": "1.1.10",
4
4
  "description": "Deploy AI agents to E2B and Daytona sandboxes",
5
5
  "type": "module",
6
6
  "exports": {
@@ -26,7 +26,7 @@
26
26
  "node": ">=20.0.0"
27
27
  },
28
28
  "scripts": {
29
- "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
29
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && node scripts/generate-runtime-server-source.mjs && tsup",
30
30
  "dev": "tsup --watch",
31
31
  "test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.config.mjs",
32
32
  "test:watch": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.config.mjs --watch",
@@ -1,163 +0,0 @@
1
- // src/runtime/server.ts
2
- import { createServer } from "http";
3
- import { readFileSync } from "fs";
4
- import { fileURLToPath } from "url";
5
- import { dirname, join } from "path";
6
- var CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");
7
- var CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
8
- function createLogger() {
9
- return {
10
- debug: (message, ...args) => console.log("[DEBUG]", message, ...args),
11
- info: (message, ...args) => console.log("[INFO]", message, ...args),
12
- warn: (message, ...args) => console.warn("[WARN]", message, ...args),
13
- error: (message, ...args) => console.error("[ERROR]", message, ...args)
14
- };
15
- }
16
- function serializeError(error) {
17
- if (error instanceof Error) {
18
- return {
19
- name: error.name,
20
- message: error.message,
21
- stack: error.stack
22
- };
23
- }
24
- return { message: String(error) };
25
- }
26
- function sendJson(res, status, body) {
27
- res.writeHead(status, { "content-type": "application/json" });
28
- res.end(JSON.stringify(body));
29
- }
30
- function sendSseFrame(res, event) {
31
- res.write(`data: ${JSON.stringify(event)}
32
-
33
- `);
34
- }
35
- async function readRequestBody(req) {
36
- const chunks = [];
37
- for await (const chunk of req) {
38
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
39
- }
40
- return Buffer.concat(chunks).toString("utf-8");
41
- }
42
- async function loadAgent() {
43
- const mod = await import(new URL("./agent.mjs", import.meta.url).href);
44
- const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(
45
- (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)
46
- );
47
- if (!agent || typeof agent !== "object") {
48
- throw new Error(
49
- `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`
50
- );
51
- }
52
- return agent;
53
- }
54
- async function main() {
55
- const agent = await loadAgent();
56
- const server = createServer(async (req, res) => {
57
- try {
58
- const url = new URL(req.url ?? "/", "http://localhost");
59
- if (url.pathname === "/health" && req.method === "GET") {
60
- return sendJson(res, 200, { ok: true });
61
- }
62
- if (url.pathname === "/shutdown" && req.method === "POST") {
63
- sendJson(res, 200, { ok: true });
64
- setTimeout(() => shutdown(), 10).unref();
65
- return;
66
- }
67
- if (url.pathname === "/invoke" && req.method === "POST") {
68
- const rawBody = await readRequestBody(req);
69
- let requestBody;
70
- try {
71
- requestBody = JSON.parse(rawBody);
72
- } catch {
73
- return sendJson(res, 400, { error: "invalid JSON body" });
74
- }
75
- if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {
76
- return sendJson(res, 400, { error: "invalid invoke request" });
77
- }
78
- let validatedInput;
79
- try {
80
- validatedInput = agent.inputSchema.parse(requestBody.input);
81
- } catch (error) {
82
- return sendJson(res, 400, {
83
- error: `input validation failed: ${serializeError(error).message}`
84
- });
85
- }
86
- res.writeHead(200, {
87
- "content-type": "text/event-stream",
88
- "cache-control": "no-cache, no-transform",
89
- connection: "keep-alive",
90
- "x-accel-buffering": "no"
91
- });
92
- const controller = new AbortController();
93
- req.on("aborted", () => controller.abort());
94
- res.on("close", () => {
95
- if (!res.writableEnded) {
96
- controller.abort();
97
- }
98
- });
99
- const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);
100
- const invocationId = requestBody.invocationId;
101
- const emitHarnessEvent = (event) => {
102
- if (!res.writableEnded) {
103
- sendSseFrame(res, event);
104
- }
105
- };
106
- const ctx = {
107
- executionId: invocationId,
108
- signal: controller.signal,
109
- env: process.env,
110
- sandbox: CONFIG.sandboxContext,
111
- logger: createLogger()
112
- };
113
- try {
114
- emitHarnessEvent({ kind: "started", invocationId });
115
- if (agent._server) {
116
- await agent._server.handler({
117
- input: validatedInput,
118
- ctx,
119
- signal: controller.signal,
120
- emit: async (data) => emitHarnessEvent({ kind: "frame", invocationId, data })
121
- });
122
- } else if (agent._run) {
123
- const output = await agent._run(validatedInput, ctx);
124
- emitHarnessEvent({ kind: "output", invocationId, output });
125
- } else {
126
- throw new Error("Agent has neither a run handler nor a server handler.");
127
- }
128
- emitHarnessEvent({ kind: "done", invocationId });
129
- } catch (error) {
130
- emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });
131
- } finally {
132
- clearTimeout(timeout);
133
- if (!res.writableEnded) {
134
- res.end();
135
- }
136
- }
137
- return;
138
- }
139
- return sendJson(res, 404, { error: "not found" });
140
- } catch (error) {
141
- console.error("[neckbeard-server] unexpected error", error);
142
- if (!res.headersSent) {
143
- sendJson(res, 500, { error: "internal error" });
144
- } else if (!res.writableEnded) {
145
- res.end();
146
- }
147
- }
148
- });
149
- function shutdown() {
150
- console.log("[neckbeard-server] shutting down");
151
- server.close(() => process.exit(0));
152
- setTimeout(() => process.exit(0), 5e3).unref();
153
- }
154
- server.listen(CONFIG.port, "0.0.0.0", () => {
155
- console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);
156
- });
157
- process.on("SIGTERM", shutdown);
158
- process.on("SIGINT", shutdown);
159
- }
160
- main().catch((error) => {
161
- console.error("[neckbeard-server] failed to start", error);
162
- process.exit(1);
163
- });