agent-neckbeard 1.1.10 → 1.1.11
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/LICENSE +21 -0
- package/README.md +23 -8
- package/dist/chunk-AM2J5KBI.js +50 -0
- package/dist/index.cjs +176 -35
- package/dist/index.d.cts +9 -30
- package/dist/index.d.ts +9 -30
- package/dist/index.js +115 -20
- package/dist/{invoke-client-WYMFPR3F.js → invoke-client-XEH6FVRH.js} +18 -12
- package/package.json +8 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zacwellmer
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -6,6 +6,8 @@ Neckbeard deploys your agent code into an E2B or Daytona sandbox and runs it beh
|
|
|
6
6
|
|
|
7
7
|
The intent is simple: your production process should not run the agent. The sandbox runs the agent, keeps its filesystem/process state, and exposes a private `/invoke` endpoint that neckbeard calls for each turn.
|
|
8
8
|
|
|
9
|
+
This is designed to work from short-lived request handlers and long-running workers, including Vercel Functions, Hatchet workers, and Trigger.dev tasks. See `docs/CONSUMER_ENVIRONMENTS.md` before changing lifecycle, timeout, streaming, or cleanup behavior for those environments.
|
|
10
|
+
|
|
9
11
|
## What This Does
|
|
10
12
|
|
|
11
13
|
You write an agent:
|
|
@@ -50,6 +52,15 @@ const result = await agent.run({ topic: 'TypeScript generics' }, { sandboxId });
|
|
|
50
52
|
|
|
51
53
|
`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
54
|
|
|
55
|
+
By default, the package infers the file to bundle from the `new Agent(...)` call stack. In frameworks that bundle server code before runtime, set `sourceFile` to the real agent module so `deploy()` does not rebundle a framework output chunk:
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
new Agent({
|
|
59
|
+
sourceFile: path.resolve(process.cwd(), 'packages/my-agent/src/agent.ts'),
|
|
60
|
+
// ...
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
53
64
|
## Setup
|
|
54
65
|
|
|
55
66
|
```bash
|
|
@@ -152,13 +163,6 @@ new Agent({
|
|
|
152
163
|
template: string,
|
|
153
164
|
},
|
|
154
165
|
inputSchema: ZodSchema,
|
|
155
|
-
outputSchema?: ZodSchema,
|
|
156
|
-
run?: (input, ctx) => Promise<output>,
|
|
157
|
-
server?: {
|
|
158
|
-
port?: number,
|
|
159
|
-
frameSchema: ZodSchema,
|
|
160
|
-
handler: ({ input, ctx, signal, emit }) => Promise<void>,
|
|
161
|
-
},
|
|
162
166
|
maxDuration?: number,
|
|
163
167
|
dependencies?: {
|
|
164
168
|
apt?: string[],
|
|
@@ -167,6 +171,15 @@ new Agent({
|
|
|
167
171
|
files?: [{ url, path }],
|
|
168
172
|
claudeDir?: string,
|
|
169
173
|
envs?: Record<string, string | undefined>,
|
|
174
|
+
// Run-output agents require:
|
|
175
|
+
outputSchema: ZodSchema,
|
|
176
|
+
run: (input, ctx) => Promise<output>,
|
|
177
|
+
// Streaming agents require this instead of outputSchema/run:
|
|
178
|
+
server: {
|
|
179
|
+
port?: number,
|
|
180
|
+
frameSchema: ZodSchema,
|
|
181
|
+
handler: ({ input, ctx, signal, emit }) => Promise<void>,
|
|
182
|
+
},
|
|
170
183
|
});
|
|
171
184
|
```
|
|
172
185
|
|
|
@@ -209,9 +222,11 @@ try {
|
|
|
209
222
|
## Testing
|
|
210
223
|
|
|
211
224
|
```bash
|
|
212
|
-
npm
|
|
225
|
+
npm run check
|
|
213
226
|
```
|
|
214
227
|
|
|
228
|
+
The local check runs typecheck, repository lint checks, formatting hygiene checks, unit tests, generated runtime verification, CJS build verification, and package dry-run validation.
|
|
229
|
+
|
|
215
230
|
Jest drives both the fast local suite and the live smoke suites. Each live suite automatically skips when its provider key is not set:
|
|
216
231
|
|
|
217
232
|
```bash
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// src/runtime/protocol.ts
|
|
2
|
+
var RUNTIME_PROTOCOL_VERSION = 1;
|
|
3
|
+
function isHarnessEvent(value) {
|
|
4
|
+
if (!value || typeof value !== "object") return false;
|
|
5
|
+
const candidate = value;
|
|
6
|
+
if (typeof candidate.kind !== "string") return false;
|
|
7
|
+
if (typeof candidate.invocationId !== "string") return false;
|
|
8
|
+
if (!hasValidMetadata(candidate)) return false;
|
|
9
|
+
switch (candidate.kind) {
|
|
10
|
+
case "started":
|
|
11
|
+
case "done":
|
|
12
|
+
return true;
|
|
13
|
+
case "frame":
|
|
14
|
+
return Object.hasOwn(candidate, "data");
|
|
15
|
+
case "output":
|
|
16
|
+
return Object.hasOwn(candidate, "output");
|
|
17
|
+
case "error":
|
|
18
|
+
return isSerializedError(candidate.error);
|
|
19
|
+
default:
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function hasValidMetadata(candidate) {
|
|
24
|
+
if (candidate.protocolVersion !== void 0 && candidate.protocolVersion !== RUNTIME_PROTOCOL_VERSION) {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
if (candidate.sequence !== void 0 && typeof candidate.sequence !== "number") {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
if (candidate.timestamp !== void 0 && typeof candidate.timestamp !== "string") {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
if (candidate.elapsedMs !== void 0 && typeof candidate.elapsedMs !== "number") {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
function isSerializedError(value) {
|
|
39
|
+
if (!value || typeof value !== "object") return false;
|
|
40
|
+
const candidate = value;
|
|
41
|
+
if (typeof candidate.message !== "string") return false;
|
|
42
|
+
if (candidate.name !== void 0 && typeof candidate.name !== "string") return false;
|
|
43
|
+
if (candidate.stack !== void 0 && typeof candidate.stack !== "string") return false;
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export {
|
|
48
|
+
RUNTIME_PROTOCOL_VERSION,
|
|
49
|
+
isHarnessEvent
|
|
50
|
+
};
|
package/dist/index.cjs
CHANGED
|
@@ -30,6 +30,58 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
30
30
|
));
|
|
31
31
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
32
|
|
|
33
|
+
// src/runtime/protocol.ts
|
|
34
|
+
function isHarnessEvent(value) {
|
|
35
|
+
if (!value || typeof value !== "object") return false;
|
|
36
|
+
const candidate = value;
|
|
37
|
+
if (typeof candidate.kind !== "string") return false;
|
|
38
|
+
if (typeof candidate.invocationId !== "string") return false;
|
|
39
|
+
if (!hasValidMetadata(candidate)) return false;
|
|
40
|
+
switch (candidate.kind) {
|
|
41
|
+
case "started":
|
|
42
|
+
case "done":
|
|
43
|
+
return true;
|
|
44
|
+
case "frame":
|
|
45
|
+
return Object.hasOwn(candidate, "data");
|
|
46
|
+
case "output":
|
|
47
|
+
return Object.hasOwn(candidate, "output");
|
|
48
|
+
case "error":
|
|
49
|
+
return isSerializedError(candidate.error);
|
|
50
|
+
default:
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function hasValidMetadata(candidate) {
|
|
55
|
+
if (candidate.protocolVersion !== void 0 && candidate.protocolVersion !== RUNTIME_PROTOCOL_VERSION) {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
if (candidate.sequence !== void 0 && typeof candidate.sequence !== "number") {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
if (candidate.timestamp !== void 0 && typeof candidate.timestamp !== "string") {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
if (candidate.elapsedMs !== void 0 && typeof candidate.elapsedMs !== "number") {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
function isSerializedError(value) {
|
|
70
|
+
if (!value || typeof value !== "object") return false;
|
|
71
|
+
const candidate = value;
|
|
72
|
+
if (typeof candidate.message !== "string") return false;
|
|
73
|
+
if (candidate.name !== void 0 && typeof candidate.name !== "string") return false;
|
|
74
|
+
if (candidate.stack !== void 0 && typeof candidate.stack !== "string") return false;
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
var RUNTIME_PROTOCOL_VERSION;
|
|
78
|
+
var init_protocol = __esm({
|
|
79
|
+
"src/runtime/protocol.ts"() {
|
|
80
|
+
"use strict";
|
|
81
|
+
RUNTIME_PROTOCOL_VERSION = 1;
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
33
85
|
// src/sse-framing.ts
|
|
34
86
|
async function* decodeSseStream(chunks) {
|
|
35
87
|
let buffer = "";
|
|
@@ -64,8 +116,9 @@ function parseFrame(raw) {
|
|
|
64
116
|
if (dataLines.length === 0) return void 0;
|
|
65
117
|
try {
|
|
66
118
|
return JSON.parse(dataLines.join("\n"));
|
|
67
|
-
} catch {
|
|
68
|
-
|
|
119
|
+
} catch (error) {
|
|
120
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
121
|
+
throw new Error(`Malformed SSE data frame: ${message}`);
|
|
69
122
|
}
|
|
70
123
|
}
|
|
71
124
|
var init_sse_framing = __esm({
|
|
@@ -74,18 +127,6 @@ var init_sse_framing = __esm({
|
|
|
74
127
|
}
|
|
75
128
|
});
|
|
76
129
|
|
|
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
|
-
|
|
89
130
|
// src/invoke-client.ts
|
|
90
131
|
var invoke_client_exports = {};
|
|
91
132
|
__export(invoke_client_exports, {
|
|
@@ -115,6 +156,16 @@ function buildRequestHeaders(options) {
|
|
|
115
156
|
}
|
|
116
157
|
return headers;
|
|
117
158
|
}
|
|
159
|
+
function validateHarnessEvent(rawEvent, invocationId) {
|
|
160
|
+
if (!isHarnessEvent(rawEvent)) {
|
|
161
|
+
throw new Error("Server returned an invalid harness event");
|
|
162
|
+
}
|
|
163
|
+
if (rawEvent.invocationId !== invocationId) {
|
|
164
|
+
throw new Error(
|
|
165
|
+
`Server returned event for invocation ${rawEvent.invocationId}; expected ${invocationId}`
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
118
169
|
async function* invokeServer(input, options) {
|
|
119
170
|
const fetchImpl = options.fetch ?? fetch;
|
|
120
171
|
const invocationId = options.invocationId ?? createInvocationId();
|
|
@@ -150,9 +201,7 @@ async function* invokeServer(input, options) {
|
|
|
150
201
|
}
|
|
151
202
|
}
|
|
152
203
|
for await (const rawEvent of decodeSseStream(chunks())) {
|
|
153
|
-
|
|
154
|
-
throw new Error("Server returned an invalid harness event");
|
|
155
|
-
}
|
|
204
|
+
validateHarnessEvent(rawEvent, invocationId);
|
|
156
205
|
if (rawEvent.kind === "frame" && options.frameSchema) {
|
|
157
206
|
yield {
|
|
158
207
|
...rawEvent,
|
|
@@ -188,9 +237,10 @@ var import_node_url = require("url");
|
|
|
188
237
|
var import_node_fs = require("fs");
|
|
189
238
|
var import_node_path = require("path");
|
|
190
239
|
var import_node_module = require("module");
|
|
240
|
+
init_protocol();
|
|
191
241
|
|
|
192
242
|
// 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}\
|
|
243
|
+
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";\nimport { once } from "node:events";\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\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}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(promise, signal, maxDurationMs) {\n if (signal.aborted) {\n throw createTimeoutError(maxDurationMs);\n }\n let cleanup = () => void 0;\n const abortPromise = new Promise((_, reject) => {\n const onAbort = () => reject(createTimeoutError(maxDurationMs));\n cleanup = () => signal.removeEventListener("abort", onAbort);\n signal.addEventListener("abort", onAbort, { once: true });\n });\n try {\n return await Promise.race([promise, abortPromise]);\n } finally {\n cleanup();\n }\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, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\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 let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\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 startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\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 await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await 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
244
|
|
|
195
245
|
// src/index.ts
|
|
196
246
|
function readPackageJson(path) {
|
|
@@ -250,6 +300,60 @@ var DEFAULT_DEPENDENCIES = {};
|
|
|
250
300
|
function isServerAgentConfig(config) {
|
|
251
301
|
return "server" in config && config.server !== void 0;
|
|
252
302
|
}
|
|
303
|
+
function isSchemaLike(value) {
|
|
304
|
+
return Boolean(
|
|
305
|
+
value && typeof value === "object" && typeof value.parse === "function"
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
function requireSchemaLike(name, value) {
|
|
309
|
+
if (!isSchemaLike(value)) {
|
|
310
|
+
throw new ConfigurationError(`${name} must be an object with a parse(value) function.`);
|
|
311
|
+
}
|
|
312
|
+
return value;
|
|
313
|
+
}
|
|
314
|
+
function validateAgentConfig(config) {
|
|
315
|
+
if (!config || typeof config !== "object") {
|
|
316
|
+
throw new ConfigurationError("Agent config must be an object.");
|
|
317
|
+
}
|
|
318
|
+
if (!config.sandbox || typeof config.sandbox !== "object") {
|
|
319
|
+
throw new ConfigurationError("Agent config requires sandbox settings.");
|
|
320
|
+
}
|
|
321
|
+
if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona") {
|
|
322
|
+
throw new ConfigurationError('sandbox.provider must be "e2b" or "daytona".');
|
|
323
|
+
}
|
|
324
|
+
if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
|
|
325
|
+
throw new ConfigurationError("sandbox.template must be a non-empty string.");
|
|
326
|
+
}
|
|
327
|
+
requireSchemaLike("inputSchema", config.inputSchema);
|
|
328
|
+
if (config.maxDuration !== void 0 && (!Number.isFinite(config.maxDuration) || config.maxDuration <= 0)) {
|
|
329
|
+
throw new ConfigurationError("maxDuration must be a positive finite number of seconds.");
|
|
330
|
+
}
|
|
331
|
+
if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
|
|
332
|
+
throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
|
|
333
|
+
}
|
|
334
|
+
if (isServerAgentConfig(config)) {
|
|
335
|
+
if ("run" in config && typeof config.run === "function") {
|
|
336
|
+
throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
|
|
337
|
+
}
|
|
338
|
+
if (!config.server || typeof config.server !== "object") {
|
|
339
|
+
throw new ConfigurationError("server must be an object.");
|
|
340
|
+
}
|
|
341
|
+
if (config.server.port !== void 0) {
|
|
342
|
+
if (!Number.isInteger(config.server.port) || config.server.port < 1 || config.server.port > 65535) {
|
|
343
|
+
throw new ConfigurationError("server.port must be an integer between 1 and 65535.");
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
requireSchemaLike("server.frameSchema", config.server.frameSchema);
|
|
347
|
+
if (typeof config.server.handler !== "function") {
|
|
348
|
+
throw new ConfigurationError("server.handler must be a function.");
|
|
349
|
+
}
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
if (typeof config.run !== "function") {
|
|
353
|
+
throw new ConfigurationError("run must be a function for run-output agents.");
|
|
354
|
+
}
|
|
355
|
+
requireSchemaLike("outputSchema", config.outputSchema);
|
|
356
|
+
}
|
|
253
357
|
function getTrafficToken(descriptor) {
|
|
254
358
|
return descriptor.trafficToken;
|
|
255
359
|
}
|
|
@@ -425,6 +529,9 @@ function createSandboxPaths(provider, homeDir, workDir) {
|
|
|
425
529
|
function timeoutMsToSeconds(timeoutMs) {
|
|
426
530
|
return Math.max(1, Math.ceil(timeoutMs / 1e3));
|
|
427
531
|
}
|
|
532
|
+
function asError(error) {
|
|
533
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
534
|
+
}
|
|
428
535
|
async function resolveDaytonaPaths(sandbox) {
|
|
429
536
|
const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
|
|
430
537
|
const homeDir = await sandbox.getUserHomeDir() ?? workDir;
|
|
@@ -594,6 +701,18 @@ function getCallerFile() {
|
|
|
594
701
|
}
|
|
595
702
|
throw new Error("Could not determine source file");
|
|
596
703
|
}
|
|
704
|
+
function resolveSourceFile(sourceFile) {
|
|
705
|
+
if (!sourceFile) return getCallerFile();
|
|
706
|
+
const normalized = normalizeStackFramePath(sourceFile);
|
|
707
|
+
if (!normalized) {
|
|
708
|
+
throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
|
|
709
|
+
}
|
|
710
|
+
const resolved = (0, import_node_path.resolve)(normalized);
|
|
711
|
+
if (!(0, import_node_fs.existsSync)(resolved)) {
|
|
712
|
+
throw new ConfigurationError(`sourceFile does not exist: ${resolved}`);
|
|
713
|
+
}
|
|
714
|
+
return resolved;
|
|
715
|
+
}
|
|
597
716
|
function readDirectoryRecursively(dirPath) {
|
|
598
717
|
const files = [];
|
|
599
718
|
function walkDir(currentPath) {
|
|
@@ -644,12 +763,13 @@ var Agent = class {
|
|
|
644
763
|
_sandboxId;
|
|
645
764
|
_sourceFile;
|
|
646
765
|
constructor(config) {
|
|
766
|
+
validateAgentConfig(config);
|
|
647
767
|
this.sandbox = config.sandbox;
|
|
648
768
|
this.provider = config.sandbox.provider;
|
|
649
769
|
this.template = config.sandbox.template;
|
|
650
770
|
this.inputSchema = config.inputSchema;
|
|
651
771
|
this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
|
|
652
|
-
this._sourceFile =
|
|
772
|
+
this._sourceFile = resolveSourceFile(config.sourceFile);
|
|
653
773
|
this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
|
|
654
774
|
this.files = config.files ?? [];
|
|
655
775
|
this.claudeDir = config.claudeDir;
|
|
@@ -1013,6 +1133,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
1013
1133
|
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
1014
1134
|
await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
|
|
1015
1135
|
const serverConfig = {
|
|
1136
|
+
protocolVersion: RUNTIME_PROTOCOL_VERSION,
|
|
1016
1137
|
port: this._server?.port ?? DEFAULT_SERVER_PORT,
|
|
1017
1138
|
maxDurationMs: this.maxDuration * 1e3,
|
|
1018
1139
|
sandboxContext: {
|
|
@@ -1115,7 +1236,12 @@ ${parts.join("\n\n")}`;
|
|
|
1115
1236
|
}
|
|
1116
1237
|
try {
|
|
1117
1238
|
const connection = await this.resolveRuntimeConnection(options?.sandboxId);
|
|
1118
|
-
|
|
1239
|
+
let validatedInput;
|
|
1240
|
+
try {
|
|
1241
|
+
validatedInput = this.inputSchema.parse(input);
|
|
1242
|
+
} catch (error) {
|
|
1243
|
+
throw new ValidationError("Input validation failed.", asError(error));
|
|
1244
|
+
}
|
|
1119
1245
|
const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
|
|
1120
1246
|
let output;
|
|
1121
1247
|
let sawOutput = false;
|
|
@@ -1143,7 +1269,12 @@ ${parts.join("\n\n")}`;
|
|
|
1143
1269
|
error: new ExecutionError("Agent server completed without returning output.")
|
|
1144
1270
|
};
|
|
1145
1271
|
}
|
|
1146
|
-
|
|
1272
|
+
let validated;
|
|
1273
|
+
try {
|
|
1274
|
+
validated = this.outputSchema ? this.outputSchema.parse(output) : output;
|
|
1275
|
+
} catch (error) {
|
|
1276
|
+
throw new ValidationError("Output validation failed.", asError(error));
|
|
1277
|
+
}
|
|
1147
1278
|
return { ok: true, executionId, output: validated };
|
|
1148
1279
|
} catch (err) {
|
|
1149
1280
|
return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
|
|
@@ -1161,21 +1292,31 @@ ${parts.join("\n\n")}`;
|
|
|
1161
1292
|
}
|
|
1162
1293
|
const connection = await this.resolveRuntimeConnection(options?.sandboxId);
|
|
1163
1294
|
const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1295
|
+
let validated;
|
|
1296
|
+
try {
|
|
1297
|
+
validated = this.inputSchema.parse(input);
|
|
1298
|
+
} catch (error) {
|
|
1299
|
+
throw new ValidationError("Input validation failed.", asError(error));
|
|
1300
|
+
}
|
|
1301
|
+
try {
|
|
1302
|
+
for await (const frame of invokeServer2(validated, {
|
|
1303
|
+
serverUrl: connection.serverUrl,
|
|
1304
|
+
provider: connection.provider,
|
|
1305
|
+
trafficToken: getTrafficToken(connection),
|
|
1306
|
+
frameSchema: this.frameSchema,
|
|
1307
|
+
signal: options?.signal
|
|
1308
|
+
})) {
|
|
1309
|
+
if (frame.kind === "frame") {
|
|
1310
|
+
yield frame.data;
|
|
1311
|
+
} else if (frame.kind === "error") {
|
|
1312
|
+
const err = new ExecutionError(frame.error.message);
|
|
1313
|
+
err.stack = frame.error.stack;
|
|
1314
|
+
throw err;
|
|
1315
|
+
}
|
|
1178
1316
|
}
|
|
1317
|
+
} catch (error) {
|
|
1318
|
+
if (error instanceof ExecutionError) throw error;
|
|
1319
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
1179
1320
|
}
|
|
1180
1321
|
}
|
|
1181
1322
|
};
|
package/dist/index.d.cts
CHANGED
|
@@ -107,6 +107,14 @@ interface AgentSharedConfig<TInput> {
|
|
|
107
107
|
sandbox: SandboxConfig;
|
|
108
108
|
inputSchema: SchemaLike<TInput>;
|
|
109
109
|
maxDuration?: number;
|
|
110
|
+
/**
|
|
111
|
+
* Local source file to bundle for deploy().
|
|
112
|
+
*
|
|
113
|
+
* By default this is inferred from the Agent constructor stack. Set this
|
|
114
|
+
* explicitly when a framework bundles server code before runtime, such as a
|
|
115
|
+
* Next.js route handler running from `.next/server/chunks/*.js`.
|
|
116
|
+
*/
|
|
117
|
+
sourceFile?: string;
|
|
110
118
|
/** OS-level dependencies to install in the sandbox. Defaults to Claude Code. Set to {} to skip. */
|
|
111
119
|
dependencies?: OsDependencies;
|
|
112
120
|
/**
|
|
@@ -214,25 +222,6 @@ type SandboxConfig = E2BSandboxConfig | DaytonaSandboxConfig;
|
|
|
214
222
|
* Mode is discriminated at runtime by the presence of `server` vs `run`.
|
|
215
223
|
*/
|
|
216
224
|
type AgentConfig<TInput, TOutput, TFrame = unknown> = RunAgentConfig<TInput, TOutput> | ServerAgentConfig<TInput, TFrame>;
|
|
217
|
-
interface RuntimeConnection {
|
|
218
|
-
sandboxId: string;
|
|
219
|
-
serverUrl: string;
|
|
220
|
-
provider: SandboxProvider;
|
|
221
|
-
trafficToken?: string;
|
|
222
|
-
}
|
|
223
|
-
/**
|
|
224
|
-
* Normalizes a path captured from a stack trace into a real on-disk file
|
|
225
|
-
* path. Handles plain paths, `file://` URLs, and `webpack-internal://` URLs
|
|
226
|
-
* emitted when user code runs inside a Next.js route handler or other
|
|
227
|
-
* webpack-bundled context.
|
|
228
|
-
*
|
|
229
|
-
* Returns null when the input is a `webpack-internal://` URL but the
|
|
230
|
-
* resolved disk path does not exist — callers should skip and keep walking
|
|
231
|
-
* the stack in that case.
|
|
232
|
-
*
|
|
233
|
-
* @internal Exported for testing.
|
|
234
|
-
*/
|
|
235
|
-
declare function normalizeStackFramePath(rawPath: string, cwd?: string): string | null;
|
|
236
225
|
type AgentMode = 'run' | 'stream';
|
|
237
226
|
declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
|
|
238
227
|
readonly sandbox: SandboxConfig;
|
|
@@ -250,16 +239,6 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
|
|
|
250
239
|
readonly claudeDir?: string;
|
|
251
240
|
readonly envs: Record<string, string | undefined>;
|
|
252
241
|
readonly build: BuildOptions;
|
|
253
|
-
/** @internal Used by the in-sandbox server for run-output agents. */
|
|
254
|
-
_run?: (input: TInput, ctx: AgentRunContext) => Promise<TOutput>;
|
|
255
|
-
/** @internal Used by the in-sandbox server for streaming agents. */
|
|
256
|
-
_server?: ServerAgentConfig<TInput, TFrame>['server'];
|
|
257
|
-
/** @internal Runtime state populated by deploy(). */
|
|
258
|
-
_serverRuntime?: {
|
|
259
|
-
sessionId?: string;
|
|
260
|
-
commandId?: string;
|
|
261
|
-
connection: RuntimeConnection;
|
|
262
|
-
};
|
|
263
242
|
private _sandboxId?;
|
|
264
243
|
private _sourceFile;
|
|
265
244
|
constructor(config: RunAgentConfig<TInput, TOutput>);
|
|
@@ -356,4 +335,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
|
|
|
356
335
|
}): AsyncGenerator<TFrame>;
|
|
357
336
|
}
|
|
358
337
|
|
|
359
|
-
export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, NeckbeardError, type OsDependencies, type RunAgentConfig, type SandboxConfig, type SandboxProvider, type ServerAgentConfig, ValidationError
|
|
338
|
+
export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, NeckbeardError, type OsDependencies, type RunAgentConfig, type SandboxConfig, type SandboxProvider, type ServerAgentConfig, ValidationError };
|
package/dist/index.d.ts
CHANGED
|
@@ -107,6 +107,14 @@ interface AgentSharedConfig<TInput> {
|
|
|
107
107
|
sandbox: SandboxConfig;
|
|
108
108
|
inputSchema: SchemaLike<TInput>;
|
|
109
109
|
maxDuration?: number;
|
|
110
|
+
/**
|
|
111
|
+
* Local source file to bundle for deploy().
|
|
112
|
+
*
|
|
113
|
+
* By default this is inferred from the Agent constructor stack. Set this
|
|
114
|
+
* explicitly when a framework bundles server code before runtime, such as a
|
|
115
|
+
* Next.js route handler running from `.next/server/chunks/*.js`.
|
|
116
|
+
*/
|
|
117
|
+
sourceFile?: string;
|
|
110
118
|
/** OS-level dependencies to install in the sandbox. Defaults to Claude Code. Set to {} to skip. */
|
|
111
119
|
dependencies?: OsDependencies;
|
|
112
120
|
/**
|
|
@@ -214,25 +222,6 @@ type SandboxConfig = E2BSandboxConfig | DaytonaSandboxConfig;
|
|
|
214
222
|
* Mode is discriminated at runtime by the presence of `server` vs `run`.
|
|
215
223
|
*/
|
|
216
224
|
type AgentConfig<TInput, TOutput, TFrame = unknown> = RunAgentConfig<TInput, TOutput> | ServerAgentConfig<TInput, TFrame>;
|
|
217
|
-
interface RuntimeConnection {
|
|
218
|
-
sandboxId: string;
|
|
219
|
-
serverUrl: string;
|
|
220
|
-
provider: SandboxProvider;
|
|
221
|
-
trafficToken?: string;
|
|
222
|
-
}
|
|
223
|
-
/**
|
|
224
|
-
* Normalizes a path captured from a stack trace into a real on-disk file
|
|
225
|
-
* path. Handles plain paths, `file://` URLs, and `webpack-internal://` URLs
|
|
226
|
-
* emitted when user code runs inside a Next.js route handler or other
|
|
227
|
-
* webpack-bundled context.
|
|
228
|
-
*
|
|
229
|
-
* Returns null when the input is a `webpack-internal://` URL but the
|
|
230
|
-
* resolved disk path does not exist — callers should skip and keep walking
|
|
231
|
-
* the stack in that case.
|
|
232
|
-
*
|
|
233
|
-
* @internal Exported for testing.
|
|
234
|
-
*/
|
|
235
|
-
declare function normalizeStackFramePath(rawPath: string, cwd?: string): string | null;
|
|
236
225
|
type AgentMode = 'run' | 'stream';
|
|
237
226
|
declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
|
|
238
227
|
readonly sandbox: SandboxConfig;
|
|
@@ -250,16 +239,6 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
|
|
|
250
239
|
readonly claudeDir?: string;
|
|
251
240
|
readonly envs: Record<string, string | undefined>;
|
|
252
241
|
readonly build: BuildOptions;
|
|
253
|
-
/** @internal Used by the in-sandbox server for run-output agents. */
|
|
254
|
-
_run?: (input: TInput, ctx: AgentRunContext) => Promise<TOutput>;
|
|
255
|
-
/** @internal Used by the in-sandbox server for streaming agents. */
|
|
256
|
-
_server?: ServerAgentConfig<TInput, TFrame>['server'];
|
|
257
|
-
/** @internal Runtime state populated by deploy(). */
|
|
258
|
-
_serverRuntime?: {
|
|
259
|
-
sessionId?: string;
|
|
260
|
-
commandId?: string;
|
|
261
|
-
connection: RuntimeConnection;
|
|
262
|
-
};
|
|
263
242
|
private _sandboxId?;
|
|
264
243
|
private _sourceFile;
|
|
265
244
|
constructor(config: RunAgentConfig<TInput, TOutput>);
|
|
@@ -356,4 +335,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
|
|
|
356
335
|
}): AsyncGenerator<TFrame>;
|
|
357
336
|
}
|
|
358
337
|
|
|
359
|
-
export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, NeckbeardError, type OsDependencies, type RunAgentConfig, type SandboxConfig, type SandboxProvider, type ServerAgentConfig, ValidationError
|
|
338
|
+
export { Agent, type AgentConfig, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type BuildOptions, ConfigurationError, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type E2BSandboxConfig, ExecutionError, type FileDownload, NeckbeardError, type OsDependencies, type RunAgentConfig, type SandboxConfig, type SandboxProvider, type ServerAgentConfig, ValidationError };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
RUNTIME_PROTOCOL_VERSION
|
|
3
|
+
} from "./chunk-AM2J5KBI.js";
|
|
4
|
+
|
|
1
5
|
// src/index.ts
|
|
2
6
|
import { fileURLToPath } from "url";
|
|
3
7
|
import { existsSync, readdirSync, readFileSync, statSync } from "fs";
|
|
@@ -5,7 +9,7 @@ import { dirname, join, relative, resolve } from "path";
|
|
|
5
9
|
import { builtinModules, createRequire } from "module";
|
|
6
10
|
|
|
7
11
|
// 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}\
|
|
12
|
+
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";\nimport { once } from "node:events";\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\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}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(promise, signal, maxDurationMs) {\n if (signal.aborted) {\n throw createTimeoutError(maxDurationMs);\n }\n let cleanup = () => void 0;\n const abortPromise = new Promise((_, reject) => {\n const onAbort = () => reject(createTimeoutError(maxDurationMs));\n cleanup = () => signal.removeEventListener("abort", onAbort);\n signal.addEventListener("abort", onAbort, { once: true });\n });\n try {\n return await Promise.race([promise, abortPromise]);\n } finally {\n cleanup();\n }\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, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\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 let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\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 startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\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 await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await 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
13
|
|
|
10
14
|
// src/index.ts
|
|
11
15
|
function readPackageJson(path) {
|
|
@@ -65,6 +69,60 @@ var DEFAULT_DEPENDENCIES = {};
|
|
|
65
69
|
function isServerAgentConfig(config) {
|
|
66
70
|
return "server" in config && config.server !== void 0;
|
|
67
71
|
}
|
|
72
|
+
function isSchemaLike(value) {
|
|
73
|
+
return Boolean(
|
|
74
|
+
value && typeof value === "object" && typeof value.parse === "function"
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
function requireSchemaLike(name, value) {
|
|
78
|
+
if (!isSchemaLike(value)) {
|
|
79
|
+
throw new ConfigurationError(`${name} must be an object with a parse(value) function.`);
|
|
80
|
+
}
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
function validateAgentConfig(config) {
|
|
84
|
+
if (!config || typeof config !== "object") {
|
|
85
|
+
throw new ConfigurationError("Agent config must be an object.");
|
|
86
|
+
}
|
|
87
|
+
if (!config.sandbox || typeof config.sandbox !== "object") {
|
|
88
|
+
throw new ConfigurationError("Agent config requires sandbox settings.");
|
|
89
|
+
}
|
|
90
|
+
if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona") {
|
|
91
|
+
throw new ConfigurationError('sandbox.provider must be "e2b" or "daytona".');
|
|
92
|
+
}
|
|
93
|
+
if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
|
|
94
|
+
throw new ConfigurationError("sandbox.template must be a non-empty string.");
|
|
95
|
+
}
|
|
96
|
+
requireSchemaLike("inputSchema", config.inputSchema);
|
|
97
|
+
if (config.maxDuration !== void 0 && (!Number.isFinite(config.maxDuration) || config.maxDuration <= 0)) {
|
|
98
|
+
throw new ConfigurationError("maxDuration must be a positive finite number of seconds.");
|
|
99
|
+
}
|
|
100
|
+
if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
|
|
101
|
+
throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
|
|
102
|
+
}
|
|
103
|
+
if (isServerAgentConfig(config)) {
|
|
104
|
+
if ("run" in config && typeof config.run === "function") {
|
|
105
|
+
throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
|
|
106
|
+
}
|
|
107
|
+
if (!config.server || typeof config.server !== "object") {
|
|
108
|
+
throw new ConfigurationError("server must be an object.");
|
|
109
|
+
}
|
|
110
|
+
if (config.server.port !== void 0) {
|
|
111
|
+
if (!Number.isInteger(config.server.port) || config.server.port < 1 || config.server.port > 65535) {
|
|
112
|
+
throw new ConfigurationError("server.port must be an integer between 1 and 65535.");
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
requireSchemaLike("server.frameSchema", config.server.frameSchema);
|
|
116
|
+
if (typeof config.server.handler !== "function") {
|
|
117
|
+
throw new ConfigurationError("server.handler must be a function.");
|
|
118
|
+
}
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (typeof config.run !== "function") {
|
|
122
|
+
throw new ConfigurationError("run must be a function for run-output agents.");
|
|
123
|
+
}
|
|
124
|
+
requireSchemaLike("outputSchema", config.outputSchema);
|
|
125
|
+
}
|
|
68
126
|
function getTrafficToken(descriptor) {
|
|
69
127
|
return descriptor.trafficToken;
|
|
70
128
|
}
|
|
@@ -240,6 +298,9 @@ function createSandboxPaths(provider, homeDir, workDir) {
|
|
|
240
298
|
function timeoutMsToSeconds(timeoutMs) {
|
|
241
299
|
return Math.max(1, Math.ceil(timeoutMs / 1e3));
|
|
242
300
|
}
|
|
301
|
+
function asError(error) {
|
|
302
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
303
|
+
}
|
|
243
304
|
async function resolveDaytonaPaths(sandbox) {
|
|
244
305
|
const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
|
|
245
306
|
const homeDir = await sandbox.getUserHomeDir() ?? workDir;
|
|
@@ -409,6 +470,18 @@ function getCallerFile() {
|
|
|
409
470
|
}
|
|
410
471
|
throw new Error("Could not determine source file");
|
|
411
472
|
}
|
|
473
|
+
function resolveSourceFile(sourceFile) {
|
|
474
|
+
if (!sourceFile) return getCallerFile();
|
|
475
|
+
const normalized = normalizeStackFramePath(sourceFile);
|
|
476
|
+
if (!normalized) {
|
|
477
|
+
throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
|
|
478
|
+
}
|
|
479
|
+
const resolved = resolve(normalized);
|
|
480
|
+
if (!existsSync(resolved)) {
|
|
481
|
+
throw new ConfigurationError(`sourceFile does not exist: ${resolved}`);
|
|
482
|
+
}
|
|
483
|
+
return resolved;
|
|
484
|
+
}
|
|
412
485
|
function readDirectoryRecursively(dirPath) {
|
|
413
486
|
const files = [];
|
|
414
487
|
function walkDir(currentPath) {
|
|
@@ -459,12 +532,13 @@ var Agent = class {
|
|
|
459
532
|
_sandboxId;
|
|
460
533
|
_sourceFile;
|
|
461
534
|
constructor(config) {
|
|
535
|
+
validateAgentConfig(config);
|
|
462
536
|
this.sandbox = config.sandbox;
|
|
463
537
|
this.provider = config.sandbox.provider;
|
|
464
538
|
this.template = config.sandbox.template;
|
|
465
539
|
this.inputSchema = config.inputSchema;
|
|
466
540
|
this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
|
|
467
|
-
this._sourceFile =
|
|
541
|
+
this._sourceFile = resolveSourceFile(config.sourceFile);
|
|
468
542
|
this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
|
|
469
543
|
this.files = config.files ?? [];
|
|
470
544
|
this.claudeDir = config.claudeDir;
|
|
@@ -828,6 +902,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
828
902
|
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
829
903
|
await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
|
|
830
904
|
const serverConfig = {
|
|
905
|
+
protocolVersion: RUNTIME_PROTOCOL_VERSION,
|
|
831
906
|
port: this._server?.port ?? DEFAULT_SERVER_PORT,
|
|
832
907
|
maxDurationMs: this.maxDuration * 1e3,
|
|
833
908
|
sandboxContext: {
|
|
@@ -930,8 +1005,13 @@ ${parts.join("\n\n")}`;
|
|
|
930
1005
|
}
|
|
931
1006
|
try {
|
|
932
1007
|
const connection = await this.resolveRuntimeConnection(options?.sandboxId);
|
|
933
|
-
|
|
934
|
-
|
|
1008
|
+
let validatedInput;
|
|
1009
|
+
try {
|
|
1010
|
+
validatedInput = this.inputSchema.parse(input);
|
|
1011
|
+
} catch (error) {
|
|
1012
|
+
throw new ValidationError("Input validation failed.", asError(error));
|
|
1013
|
+
}
|
|
1014
|
+
const { invokeServer } = await import("./invoke-client-XEH6FVRH.js");
|
|
935
1015
|
let output;
|
|
936
1016
|
let sawOutput = false;
|
|
937
1017
|
for await (const event of invokeServer(validatedInput, {
|
|
@@ -958,7 +1038,12 @@ ${parts.join("\n\n")}`;
|
|
|
958
1038
|
error: new ExecutionError("Agent server completed without returning output.")
|
|
959
1039
|
};
|
|
960
1040
|
}
|
|
961
|
-
|
|
1041
|
+
let validated;
|
|
1042
|
+
try {
|
|
1043
|
+
validated = this.outputSchema ? this.outputSchema.parse(output) : output;
|
|
1044
|
+
} catch (error) {
|
|
1045
|
+
throw new ValidationError("Output validation failed.", asError(error));
|
|
1046
|
+
}
|
|
962
1047
|
return { ok: true, executionId, output: validated };
|
|
963
1048
|
} catch (err) {
|
|
964
1049
|
return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
|
|
@@ -975,22 +1060,32 @@ ${parts.join("\n\n")}`;
|
|
|
975
1060
|
);
|
|
976
1061
|
}
|
|
977
1062
|
const connection = await this.resolveRuntimeConnection(options?.sandboxId);
|
|
978
|
-
const { invokeServer } = await import("./invoke-client-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
1063
|
+
const { invokeServer } = await import("./invoke-client-XEH6FVRH.js");
|
|
1064
|
+
let validated;
|
|
1065
|
+
try {
|
|
1066
|
+
validated = this.inputSchema.parse(input);
|
|
1067
|
+
} catch (error) {
|
|
1068
|
+
throw new ValidationError("Input validation failed.", asError(error));
|
|
1069
|
+
}
|
|
1070
|
+
try {
|
|
1071
|
+
for await (const frame of invokeServer(validated, {
|
|
1072
|
+
serverUrl: connection.serverUrl,
|
|
1073
|
+
provider: connection.provider,
|
|
1074
|
+
trafficToken: getTrafficToken(connection),
|
|
1075
|
+
frameSchema: this.frameSchema,
|
|
1076
|
+
signal: options?.signal
|
|
1077
|
+
})) {
|
|
1078
|
+
if (frame.kind === "frame") {
|
|
1079
|
+
yield frame.data;
|
|
1080
|
+
} else if (frame.kind === "error") {
|
|
1081
|
+
const err = new ExecutionError(frame.error.message);
|
|
1082
|
+
err.stack = frame.error.stack;
|
|
1083
|
+
throw err;
|
|
1084
|
+
}
|
|
993
1085
|
}
|
|
1086
|
+
} catch (error) {
|
|
1087
|
+
if (error instanceof ExecutionError) throw error;
|
|
1088
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
994
1089
|
}
|
|
995
1090
|
}
|
|
996
1091
|
};
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isHarnessEvent
|
|
3
|
+
} from "./chunk-AM2J5KBI.js";
|
|
4
|
+
|
|
1
5
|
// src/sse-framing.ts
|
|
2
6
|
async function* decodeSseStream(chunks) {
|
|
3
7
|
let buffer = "";
|
|
@@ -32,18 +36,12 @@ function parseFrame(raw) {
|
|
|
32
36
|
if (dataLines.length === 0) return void 0;
|
|
33
37
|
try {
|
|
34
38
|
return JSON.parse(dataLines.join("\n"));
|
|
35
|
-
} catch {
|
|
36
|
-
|
|
39
|
+
} catch (error) {
|
|
40
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
41
|
+
throw new Error(`Malformed SSE data frame: ${message}`);
|
|
37
42
|
}
|
|
38
43
|
}
|
|
39
44
|
|
|
40
|
-
// src/runtime/protocol.ts
|
|
41
|
-
function isHarnessEvent(value) {
|
|
42
|
-
if (!value || typeof value !== "object") return false;
|
|
43
|
-
const candidate = value;
|
|
44
|
-
return typeof candidate.kind === "string" && typeof candidate.invocationId === "string" && ["started", "frame", "output", "done", "error"].includes(candidate.kind);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
45
|
// src/invoke-client.ts
|
|
48
46
|
function createInvocationId() {
|
|
49
47
|
return `invoke_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
@@ -69,6 +67,16 @@ function buildRequestHeaders(options) {
|
|
|
69
67
|
}
|
|
70
68
|
return headers;
|
|
71
69
|
}
|
|
70
|
+
function validateHarnessEvent(rawEvent, invocationId) {
|
|
71
|
+
if (!isHarnessEvent(rawEvent)) {
|
|
72
|
+
throw new Error("Server returned an invalid harness event");
|
|
73
|
+
}
|
|
74
|
+
if (rawEvent.invocationId !== invocationId) {
|
|
75
|
+
throw new Error(
|
|
76
|
+
`Server returned event for invocation ${rawEvent.invocationId}; expected ${invocationId}`
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
72
80
|
async function* invokeServer(input, options) {
|
|
73
81
|
const fetchImpl = options.fetch ?? fetch;
|
|
74
82
|
const invocationId = options.invocationId ?? createInvocationId();
|
|
@@ -104,9 +112,7 @@ async function* invokeServer(input, options) {
|
|
|
104
112
|
}
|
|
105
113
|
}
|
|
106
114
|
for await (const rawEvent of decodeSseStream(chunks())) {
|
|
107
|
-
|
|
108
|
-
throw new Error("Server returned an invalid harness event");
|
|
109
|
-
}
|
|
115
|
+
validateHarnessEvent(rawEvent, invocationId);
|
|
110
116
|
if (rawEvent.kind === "frame" && options.frameSchema) {
|
|
111
117
|
yield {
|
|
112
118
|
...rawEvent,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-neckbeard",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.11",
|
|
4
4
|
"description": "Deploy AI agents to E2B and Daytona sandboxes",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -25,15 +25,21 @@
|
|
|
25
25
|
"engines": {
|
|
26
26
|
"node": ">=20.0.0"
|
|
27
27
|
},
|
|
28
|
+
"packageManager": "npm@10.9.4",
|
|
28
29
|
"scripts": {
|
|
29
30
|
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && node scripts/generate-runtime-server-source.mjs && tsup",
|
|
31
|
+
"check": "npm run typecheck && npm run lint && npm run format:check && npm test && npm run check:generated && npm run test:cjs && npm run pack:dry-run",
|
|
32
|
+
"check:generated": "node scripts/verify-runtime-server-source.mjs",
|
|
30
33
|
"dev": "tsup --watch",
|
|
34
|
+
"format:check": "node scripts/check-format.mjs",
|
|
35
|
+
"lint": "node scripts/repo-lint.mjs",
|
|
36
|
+
"pack:dry-run": "npm pack --dry-run",
|
|
31
37
|
"test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.config.mjs",
|
|
32
38
|
"test:watch": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.config.mjs --watch",
|
|
33
39
|
"test:e2e": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.e2e.config.mjs --runInBand",
|
|
34
40
|
"test:e2e:e2b": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.e2e.config.mjs --runInBand --testNamePattern=\"live E2B smoke tests\"",
|
|
35
41
|
"test:e2e:daytona": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.e2e.config.mjs --runInBand --testNamePattern=\"live Daytona smoke tests\"",
|
|
36
|
-
"test:cjs": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.config.mjs
|
|
42
|
+
"test:cjs": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.build.config.mjs",
|
|
37
43
|
"typecheck": "tsc --noEmit -p tsconfig.test.json",
|
|
38
44
|
"prepare": "npm run build"
|
|
39
45
|
},
|