agent-neckbeard 1.1.10 → 1.1.12
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 +43 -8
- package/dist/chunk-AM2J5KBI.js +50 -0
- package/dist/index.cjs +557 -38
- package/dist/index.d.cts +66 -30
- package/dist/index.d.ts +66 -30
- package/dist/index.js +495 -24
- package/dist/{invoke-client-WYMFPR3F.js → invoke-client-XEH6FVRH.js} +18 -12
- package/package.json +9 -2
package/dist/index.js
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
|
+
import {
|
|
2
|
+
RUNTIME_PROTOCOL_VERSION
|
|
3
|
+
} from "./chunk-AM2J5KBI.js";
|
|
4
|
+
|
|
1
5
|
// src/index.ts
|
|
2
6
|
import { fileURLToPath } from "url";
|
|
3
|
-
import { existsSync, readdirSync, readFileSync, statSync } from "fs";
|
|
4
|
-
import { dirname, join, relative, resolve } from "path";
|
|
7
|
+
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "fs";
|
|
8
|
+
import { basename, 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) {
|
|
@@ -20,6 +24,8 @@ var QUICK_COMMAND_TIMEOUT_MS = 3e4;
|
|
|
20
24
|
var DAYTONA_CREATE_TIMEOUT_SEC = 120;
|
|
21
25
|
var NODE_TARGET = "node20";
|
|
22
26
|
var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
|
|
27
|
+
var NECKBEARD_PACKAGE_NAME = "agent-neckbeard";
|
|
28
|
+
var NECKBEARD_SANDBOX_RUNTIME_ENV = "AGENT_NECKBEARD_SANDBOX_RUNTIME";
|
|
23
29
|
var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
|
|
24
30
|
var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
|
|
25
31
|
var DEFAULT_SERVER_PORT = 3e3;
|
|
@@ -61,10 +67,412 @@ var ConfigurationError = class extends NeckbeardError {
|
|
|
61
67
|
this.name = "ConfigurationError";
|
|
62
68
|
}
|
|
63
69
|
};
|
|
70
|
+
function resolveAgentSourceFile(candidates, options = {}) {
|
|
71
|
+
const normalizedCandidates = normalizeNonEmptyStrings("candidates", candidates);
|
|
72
|
+
const sourceFile = normalizedCandidates.find((candidate) => existsSync(candidate));
|
|
73
|
+
if (sourceFile) {
|
|
74
|
+
return sourceFile;
|
|
75
|
+
}
|
|
76
|
+
if (process.env[NECKBEARD_SANDBOX_RUNTIME_ENV] === "1") {
|
|
77
|
+
const sandboxSourceFile = options.sandboxSourceFile ?? resolve(process.cwd(), "agent.mjs");
|
|
78
|
+
if (existsSync(sandboxSourceFile)) {
|
|
79
|
+
return sandboxSourceFile;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
throw new ConfigurationError(
|
|
83
|
+
options.errorMessage ?? `Could not resolve agent source file. Checked: ${candidates.join(", ")}`
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
function withNeckbeardNextConfig(nextConfig, options) {
|
|
87
|
+
const sourceFiles = normalizeNonEmptyStrings("sourceFiles", options.sourceFiles);
|
|
88
|
+
const routeGlobs = normalizeNonEmptyStrings("routeGlob", options.routeGlob ?? "/*");
|
|
89
|
+
const experimental = asRecord(nextConfig.experimental);
|
|
90
|
+
const useLegacyExperimental = options.legacyExperimental ?? ("serverComponentsExternalPackages" in experimental || "outputFileTracingIncludes" in experimental || "outputFileTracingRoot" in experimental);
|
|
91
|
+
if (useLegacyExperimental) {
|
|
92
|
+
const nextExperimental = {
|
|
93
|
+
...experimental,
|
|
94
|
+
serverComponentsExternalPackages: mergeStringArray(
|
|
95
|
+
experimental.serverComponentsExternalPackages,
|
|
96
|
+
[NECKBEARD_PACKAGE_NAME]
|
|
97
|
+
),
|
|
98
|
+
outputFileTracingIncludes: mergeTracingIncludes(
|
|
99
|
+
experimental.outputFileTracingIncludes,
|
|
100
|
+
routeGlobs,
|
|
101
|
+
sourceFiles
|
|
102
|
+
)
|
|
103
|
+
};
|
|
104
|
+
if (options.outputFileTracingRoot !== void 0) {
|
|
105
|
+
nextExperimental.outputFileTracingRoot = options.outputFileTracingRoot;
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
...nextConfig,
|
|
109
|
+
experimental: nextExperimental,
|
|
110
|
+
webpack: withNextTraceIncludeWebpack(nextConfig.webpack, sourceFiles, routeGlobs)
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const result = {
|
|
114
|
+
...nextConfig,
|
|
115
|
+
serverExternalPackages: mergeStringArray(nextConfig.serverExternalPackages, [
|
|
116
|
+
NECKBEARD_PACKAGE_NAME
|
|
117
|
+
]),
|
|
118
|
+
outputFileTracingIncludes: mergeTracingIncludes(
|
|
119
|
+
nextConfig.outputFileTracingIncludes,
|
|
120
|
+
routeGlobs,
|
|
121
|
+
sourceFiles
|
|
122
|
+
)
|
|
123
|
+
};
|
|
124
|
+
if (options.outputFileTracingRoot !== void 0) {
|
|
125
|
+
result.outputFileTracingRoot = options.outputFileTracingRoot;
|
|
126
|
+
}
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
var NextTraceIncludePlugin = class {
|
|
130
|
+
constructor(appDir, sourceFiles, routeGlobs) {
|
|
131
|
+
this.appDir = appDir;
|
|
132
|
+
this.sourceFiles = sourceFiles;
|
|
133
|
+
this.routeGlobs = routeGlobs;
|
|
134
|
+
}
|
|
135
|
+
apply(compiler) {
|
|
136
|
+
const compilationHook = compiler.hooks?.compilation;
|
|
137
|
+
if (typeof compilationHook?.tap === "function") {
|
|
138
|
+
compilationHook.tap("NeckbeardNextTraceIncludePlugin", (compilation) => {
|
|
139
|
+
const processAssets = compilation.hooks?.processAssets;
|
|
140
|
+
if (typeof processAssets?.tap !== "function") {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
processAssets.tap({
|
|
144
|
+
name: "NeckbeardNextTraceIncludePlugin",
|
|
145
|
+
stage: compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_REPORT ?? 5e3
|
|
146
|
+
}, (assets) => {
|
|
147
|
+
appendIncludesToTraceAssets({
|
|
148
|
+
appDir: this.appDir,
|
|
149
|
+
assets,
|
|
150
|
+
outputPath: compilation.outputOptions?.path ?? compiler.outputPath ?? "",
|
|
151
|
+
rawSource: compiler.webpack?.sources?.RawSource,
|
|
152
|
+
routeGlobs: this.routeGlobs,
|
|
153
|
+
sourceFiles: this.sourceFiles,
|
|
154
|
+
updateAsset: compilation.updateAsset?.bind(compilation)
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
const afterEmit = compiler.hooks?.afterEmit;
|
|
160
|
+
const done = compiler.hooks?.done;
|
|
161
|
+
if (typeof afterEmit?.tap !== "function" && typeof done?.tap !== "function") {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (!compiler.outputPath) {
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const appendIncludes = () => {
|
|
168
|
+
appendIncludesToTraceFiles(
|
|
169
|
+
compiler.outputPath ?? "",
|
|
170
|
+
this.appDir,
|
|
171
|
+
this.sourceFiles,
|
|
172
|
+
this.routeGlobs
|
|
173
|
+
);
|
|
174
|
+
};
|
|
175
|
+
if (typeof afterEmit?.tap === "function") {
|
|
176
|
+
afterEmit.tap("NeckbeardNextTraceIncludePlugin", appendIncludes);
|
|
177
|
+
}
|
|
178
|
+
if (typeof done?.tap === "function") {
|
|
179
|
+
done.tap("NeckbeardNextTraceIncludePlugin", appendIncludes);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
function appendIncludesToTraceAssets({
|
|
184
|
+
appDir,
|
|
185
|
+
assets,
|
|
186
|
+
outputPath,
|
|
187
|
+
rawSource,
|
|
188
|
+
routeGlobs,
|
|
189
|
+
sourceFiles,
|
|
190
|
+
updateAsset
|
|
191
|
+
}) {
|
|
192
|
+
const includedFiles = expandTraceIncludeFiles(appDir, sourceFiles);
|
|
193
|
+
if (includedFiles.length === 0) {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
for (const [assetName, asset] of Object.entries(assets)) {
|
|
197
|
+
if (!assetName.endsWith(".nft.json")) {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const routePath = routePathFromTraceAsset(outputPath, assetName);
|
|
201
|
+
if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
const traceDir = dirname(join(outputPath, assetName));
|
|
205
|
+
const nextSource = traceWithIncludedFiles(String(asset.source()), traceDir, includedFiles);
|
|
206
|
+
if (rawSource && updateAsset) {
|
|
207
|
+
updateAsset(assetName, new rawSource(nextSource));
|
|
208
|
+
} else {
|
|
209
|
+
assets[assetName] = {
|
|
210
|
+
source: () => nextSource,
|
|
211
|
+
size: () => Buffer.byteLength(nextSource)
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function withNextTraceIncludeWebpack(originalWebpack, sourceFiles, routeGlobs) {
|
|
217
|
+
return (config, context) => {
|
|
218
|
+
const nextConfig = originalWebpack ? originalWebpack(config, context) : config;
|
|
219
|
+
if (!context.isServer || context.dev) {
|
|
220
|
+
return nextConfig;
|
|
221
|
+
}
|
|
222
|
+
nextConfig.externals = withNeckbeardExternal(nextConfig.externals);
|
|
223
|
+
nextConfig.plugins = [
|
|
224
|
+
...Array.isArray(nextConfig.plugins) ? nextConfig.plugins : [],
|
|
225
|
+
new NextTraceIncludePlugin(context.dir ?? process.cwd(), sourceFiles, routeGlobs)
|
|
226
|
+
];
|
|
227
|
+
return nextConfig;
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
function withNeckbeardExternal(externals) {
|
|
231
|
+
return [
|
|
232
|
+
neckbeardExternal,
|
|
233
|
+
...Array.isArray(externals) ? externals : externals ? [externals] : []
|
|
234
|
+
];
|
|
235
|
+
}
|
|
236
|
+
function neckbeardExternal(contextOrRequest, requestOrCallback) {
|
|
237
|
+
const legacyCallback = arguments[2];
|
|
238
|
+
const request = typeof requestOrCallback === "string" ? requestOrCallback : typeof contextOrRequest === "string" ? contextOrRequest : contextOrRequest.request;
|
|
239
|
+
const callback = typeof requestOrCallback === "function" ? requestOrCallback : legacyCallback;
|
|
240
|
+
if (request === NECKBEARD_PACKAGE_NAME) {
|
|
241
|
+
const result = `commonjs ${NECKBEARD_PACKAGE_NAME}`;
|
|
242
|
+
if (callback) {
|
|
243
|
+
callback(null, result);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
return result;
|
|
247
|
+
}
|
|
248
|
+
if (callback) {
|
|
249
|
+
callback();
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
function appendIncludesToTraceFiles(outputPath, appDir, sourceFiles, routeGlobs) {
|
|
253
|
+
if (!outputPath || !existsSync(outputPath)) {
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const includedFiles = expandTraceIncludeFiles(appDir, sourceFiles);
|
|
257
|
+
if (includedFiles.length === 0) {
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
for (const traceFile of findTraceFiles(outputPath)) {
|
|
261
|
+
const routePath = routePathFromTraceFile(outputPath, traceFile);
|
|
262
|
+
if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
appendFilesToTrace(traceFile, includedFiles);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function appendFilesToTrace(traceFile, includedFiles) {
|
|
269
|
+
const nextSource = traceWithIncludedFiles(
|
|
270
|
+
readFileSync(traceFile, "utf8"),
|
|
271
|
+
dirname(traceFile),
|
|
272
|
+
includedFiles
|
|
273
|
+
);
|
|
274
|
+
writeFileSync(traceFile, nextSource);
|
|
275
|
+
}
|
|
276
|
+
function traceWithIncludedFiles(traceSource, traceDir, includedFiles) {
|
|
277
|
+
const trace = JSON.parse(traceSource);
|
|
278
|
+
const files = Array.isArray(trace.files) ? trace.files.filter((file) => typeof file === "string") : [];
|
|
279
|
+
const nextFiles = new Set(files);
|
|
280
|
+
for (const includedFile of includedFiles) {
|
|
281
|
+
nextFiles.add(relative(traceDir, includedFile).replace(/\\/g, "/"));
|
|
282
|
+
}
|
|
283
|
+
return JSON.stringify({
|
|
284
|
+
version: trace.version ?? 1,
|
|
285
|
+
files: [...nextFiles]
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
function expandTraceIncludeFiles(appDir, sourceFiles) {
|
|
289
|
+
const files = /* @__PURE__ */ new Set();
|
|
290
|
+
for (const sourceFile of sourceFiles) {
|
|
291
|
+
for (const file of expandTraceIncludePattern(appDir, sourceFile)) {
|
|
292
|
+
files.add(file);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return [...files];
|
|
296
|
+
}
|
|
297
|
+
function expandTraceIncludePattern(appDir, sourceFile) {
|
|
298
|
+
const normalized = sourceFile.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
299
|
+
if (normalized.endsWith("/**/*")) {
|
|
300
|
+
const dir = resolve(appDir, normalized.slice(0, -5));
|
|
301
|
+
return findFiles(dir);
|
|
302
|
+
}
|
|
303
|
+
if (normalized.endsWith("/*")) {
|
|
304
|
+
const dir = resolve(appDir, normalized.slice(0, -2));
|
|
305
|
+
return directFiles(dir);
|
|
306
|
+
}
|
|
307
|
+
const file = resolve(appDir, normalized);
|
|
308
|
+
return existsSync(file) && statSync(file).isFile() ? [file] : [];
|
|
309
|
+
}
|
|
310
|
+
function findTraceFiles(root) {
|
|
311
|
+
return findFiles(root).filter((file) => file.endsWith(".nft.json"));
|
|
312
|
+
}
|
|
313
|
+
function findFiles(root) {
|
|
314
|
+
if (!existsSync(root)) {
|
|
315
|
+
return [];
|
|
316
|
+
}
|
|
317
|
+
const stat = statSync(root);
|
|
318
|
+
if (stat.isFile()) {
|
|
319
|
+
return [root];
|
|
320
|
+
}
|
|
321
|
+
if (!stat.isDirectory()) {
|
|
322
|
+
return [];
|
|
323
|
+
}
|
|
324
|
+
const files = [];
|
|
325
|
+
for (const entry of readdirSync(root)) {
|
|
326
|
+
files.push(...findFiles(join(root, entry)));
|
|
327
|
+
}
|
|
328
|
+
return files;
|
|
329
|
+
}
|
|
330
|
+
function directFiles(root) {
|
|
331
|
+
if (!existsSync(root) || !statSync(root).isDirectory()) {
|
|
332
|
+
return [];
|
|
333
|
+
}
|
|
334
|
+
return readdirSync(root).map((entry) => join(root, entry)).filter((file) => statSync(file).isFile());
|
|
335
|
+
}
|
|
336
|
+
function routePathFromTraceFile(outputPath, traceFile) {
|
|
337
|
+
const relativeTrace = relative(outputPath, traceFile).replace(/\\/g, "/");
|
|
338
|
+
return routePathFromRelativeTrace(outputPath, relativeTrace);
|
|
339
|
+
}
|
|
340
|
+
function routePathFromTraceAsset(outputPath, assetName) {
|
|
341
|
+
return routePathFromRelativeTrace(outputPath, assetName.replace(/\\/g, "/"));
|
|
342
|
+
}
|
|
343
|
+
function routePathFromRelativeTrace(outputPath, relativeTrace) {
|
|
344
|
+
const normalizedTrace = relativeTrace.replace(/^(\.\.\/)+/, "");
|
|
345
|
+
if (relativeTrace.startsWith("app/")) {
|
|
346
|
+
return normalizeTraceRoute(relativeTrace.slice("app/".length));
|
|
347
|
+
}
|
|
348
|
+
if (relativeTrace.startsWith("pages/")) {
|
|
349
|
+
return normalizeTraceRoute(relativeTrace.slice("pages/".length));
|
|
350
|
+
}
|
|
351
|
+
if (normalizedTrace.startsWith("app/")) {
|
|
352
|
+
return normalizeTraceRoute(normalizedTrace.slice("app/".length));
|
|
353
|
+
}
|
|
354
|
+
if (normalizedTrace.startsWith("pages/")) {
|
|
355
|
+
return normalizeTraceRoute(normalizedTrace.slice("pages/".length));
|
|
356
|
+
}
|
|
357
|
+
if (basename(outputPath) === "app" || basename(outputPath) === "pages") {
|
|
358
|
+
return normalizeTraceRoute(relativeTrace);
|
|
359
|
+
}
|
|
360
|
+
return void 0;
|
|
361
|
+
}
|
|
362
|
+
function normalizeTraceRoute(relativeTrace) {
|
|
363
|
+
const withoutTraceSuffix = relativeTrace.replace(/\.js\.nft\.json$/, "");
|
|
364
|
+
const route = withoutTraceSuffix.replace(/\/route$/, "").replace(/\/page$/, "").replace(/\/index$/, "");
|
|
365
|
+
return `/${route}`;
|
|
366
|
+
}
|
|
367
|
+
function routeGlobMatches(routeGlob, routePath) {
|
|
368
|
+
if (routeGlob === "/*") {
|
|
369
|
+
return true;
|
|
370
|
+
}
|
|
371
|
+
return routeGlobToRegExp(routeGlob).test(routePath);
|
|
372
|
+
}
|
|
373
|
+
function routeGlobToRegExp(glob) {
|
|
374
|
+
let pattern = "";
|
|
375
|
+
for (let index = 0; index < glob.length; index += 1) {
|
|
376
|
+
const char = glob[index];
|
|
377
|
+
const nextChar = glob[index + 1];
|
|
378
|
+
if (char === "*" && nextChar === "*") {
|
|
379
|
+
pattern += ".*";
|
|
380
|
+
index += 1;
|
|
381
|
+
} else if (char === "*") {
|
|
382
|
+
pattern += "[^/]*";
|
|
383
|
+
} else {
|
|
384
|
+
pattern += escapeRegExp(char);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return new RegExp(`^${pattern}$`);
|
|
388
|
+
}
|
|
389
|
+
function escapeRegExp(value) {
|
|
390
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
391
|
+
}
|
|
392
|
+
function asRecord(value) {
|
|
393
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
394
|
+
}
|
|
395
|
+
function normalizeNonEmptyStrings(name, value) {
|
|
396
|
+
const values = Array.isArray(value) ? value : [value];
|
|
397
|
+
if (values.length === 0) {
|
|
398
|
+
throw new ConfigurationError(`${name} must contain at least one entry.`);
|
|
399
|
+
}
|
|
400
|
+
for (const entry of values) {
|
|
401
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
402
|
+
throw new ConfigurationError(`${name} entries must be non-empty strings.`);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
return values;
|
|
406
|
+
}
|
|
407
|
+
function mergeStringArray(existing, values) {
|
|
408
|
+
const current = Array.isArray(existing) ? existing.filter((value) => typeof value === "string") : [];
|
|
409
|
+
return [.../* @__PURE__ */ new Set([...current, ...values])];
|
|
410
|
+
}
|
|
411
|
+
function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
|
|
412
|
+
const includes = { ...asRecord(existing) };
|
|
413
|
+
for (const routeGlob of routeGlobs) {
|
|
414
|
+
includes[routeGlob] = mergeStringArray(includes[routeGlob], sourceFiles);
|
|
415
|
+
}
|
|
416
|
+
return includes;
|
|
417
|
+
}
|
|
64
418
|
var DEFAULT_DEPENDENCIES = {};
|
|
65
419
|
function isServerAgentConfig(config) {
|
|
66
420
|
return "server" in config && config.server !== void 0;
|
|
67
421
|
}
|
|
422
|
+
function isSchemaLike(value) {
|
|
423
|
+
return Boolean(
|
|
424
|
+
value && typeof value === "object" && typeof value.parse === "function"
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
function requireSchemaLike(name, value) {
|
|
428
|
+
if (!isSchemaLike(value)) {
|
|
429
|
+
throw new ConfigurationError(`${name} must be an object with a parse(value) function.`);
|
|
430
|
+
}
|
|
431
|
+
return value;
|
|
432
|
+
}
|
|
433
|
+
function validateAgentConfig(config) {
|
|
434
|
+
if (!config || typeof config !== "object") {
|
|
435
|
+
throw new ConfigurationError("Agent config must be an object.");
|
|
436
|
+
}
|
|
437
|
+
if (!config.sandbox || typeof config.sandbox !== "object") {
|
|
438
|
+
throw new ConfigurationError("Agent config requires sandbox settings.");
|
|
439
|
+
}
|
|
440
|
+
if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona") {
|
|
441
|
+
throw new ConfigurationError('sandbox.provider must be "e2b" or "daytona".');
|
|
442
|
+
}
|
|
443
|
+
if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
|
|
444
|
+
throw new ConfigurationError("sandbox.template must be a non-empty string.");
|
|
445
|
+
}
|
|
446
|
+
requireSchemaLike("inputSchema", config.inputSchema);
|
|
447
|
+
if (config.maxDuration !== void 0 && (!Number.isFinite(config.maxDuration) || config.maxDuration <= 0)) {
|
|
448
|
+
throw new ConfigurationError("maxDuration must be a positive finite number of seconds.");
|
|
449
|
+
}
|
|
450
|
+
if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
|
|
451
|
+
throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
|
|
452
|
+
}
|
|
453
|
+
if (isServerAgentConfig(config)) {
|
|
454
|
+
if ("run" in config && typeof config.run === "function") {
|
|
455
|
+
throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
|
|
456
|
+
}
|
|
457
|
+
if (!config.server || typeof config.server !== "object") {
|
|
458
|
+
throw new ConfigurationError("server must be an object.");
|
|
459
|
+
}
|
|
460
|
+
if (config.server.port !== void 0) {
|
|
461
|
+
if (!Number.isInteger(config.server.port) || config.server.port < 1 || config.server.port > 65535) {
|
|
462
|
+
throw new ConfigurationError("server.port must be an integer between 1 and 65535.");
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
requireSchemaLike("server.frameSchema", config.server.frameSchema);
|
|
466
|
+
if (typeof config.server.handler !== "function") {
|
|
467
|
+
throw new ConfigurationError("server.handler must be a function.");
|
|
468
|
+
}
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
if (typeof config.run !== "function") {
|
|
472
|
+
throw new ConfigurationError("run must be a function for run-output agents.");
|
|
473
|
+
}
|
|
474
|
+
requireSchemaLike("outputSchema", config.outputSchema);
|
|
475
|
+
}
|
|
68
476
|
function getTrafficToken(descriptor) {
|
|
69
477
|
return descriptor.trafficToken;
|
|
70
478
|
}
|
|
@@ -240,6 +648,9 @@ function createSandboxPaths(provider, homeDir, workDir) {
|
|
|
240
648
|
function timeoutMsToSeconds(timeoutMs) {
|
|
241
649
|
return Math.max(1, Math.ceil(timeoutMs / 1e3));
|
|
242
650
|
}
|
|
651
|
+
function asError(error) {
|
|
652
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
653
|
+
}
|
|
243
654
|
async function resolveDaytonaPaths(sandbox) {
|
|
244
655
|
const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
|
|
245
656
|
const homeDir = await sandbox.getUserHomeDir() ?? workDir;
|
|
@@ -409,6 +820,36 @@ function getCallerFile() {
|
|
|
409
820
|
}
|
|
410
821
|
throw new Error("Could not determine source file");
|
|
411
822
|
}
|
|
823
|
+
function isFrameworkBuildOutputPath(file) {
|
|
824
|
+
const normalized = file.replace(/\\/g, "/");
|
|
825
|
+
return normalized.includes("/.next/server/chunks/") || normalized.includes("/.next/server/app/") || normalized.includes("/.next/server/pages/");
|
|
826
|
+
}
|
|
827
|
+
function frameworkBuildOutputError(file) {
|
|
828
|
+
return new ConfigurationError(
|
|
829
|
+
`Agent source resolved to framework build output (${file}). Set sourceFile to the original agent module so deploy() bundles your agent source instead of a framework chunk.`
|
|
830
|
+
);
|
|
831
|
+
}
|
|
832
|
+
function resolveSourceFile(sourceFile) {
|
|
833
|
+
if (!sourceFile) {
|
|
834
|
+
const inferred = getCallerFile();
|
|
835
|
+
if (isFrameworkBuildOutputPath(inferred)) {
|
|
836
|
+
throw frameworkBuildOutputError(inferred);
|
|
837
|
+
}
|
|
838
|
+
return inferred;
|
|
839
|
+
}
|
|
840
|
+
const normalized = normalizeStackFramePath(sourceFile);
|
|
841
|
+
if (!normalized) {
|
|
842
|
+
throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
|
|
843
|
+
}
|
|
844
|
+
const resolved = resolve(normalized);
|
|
845
|
+
if (isFrameworkBuildOutputPath(resolved)) {
|
|
846
|
+
throw frameworkBuildOutputError(resolved);
|
|
847
|
+
}
|
|
848
|
+
if (!existsSync(resolved)) {
|
|
849
|
+
throw new ConfigurationError(`sourceFile does not exist: ${resolved}`);
|
|
850
|
+
}
|
|
851
|
+
return resolved;
|
|
852
|
+
}
|
|
412
853
|
function readDirectoryRecursively(dirPath) {
|
|
413
854
|
const files = [];
|
|
414
855
|
function walkDir(currentPath) {
|
|
@@ -459,12 +900,13 @@ var Agent = class {
|
|
|
459
900
|
_sandboxId;
|
|
460
901
|
_sourceFile;
|
|
461
902
|
constructor(config) {
|
|
903
|
+
validateAgentConfig(config);
|
|
462
904
|
this.sandbox = config.sandbox;
|
|
463
905
|
this.provider = config.sandbox.provider;
|
|
464
906
|
this.template = config.sandbox.template;
|
|
465
907
|
this.inputSchema = config.inputSchema;
|
|
466
908
|
this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
|
|
467
|
-
this._sourceFile =
|
|
909
|
+
this._sourceFile = resolveSourceFile(config.sourceFile);
|
|
468
910
|
this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
|
|
469
911
|
this.files = config.files ?? [];
|
|
470
912
|
this.claudeDir = config.claudeDir;
|
|
@@ -484,7 +926,10 @@ var Agent = class {
|
|
|
484
926
|
return this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
485
927
|
}
|
|
486
928
|
get sandboxEnv() {
|
|
487
|
-
return
|
|
929
|
+
return {
|
|
930
|
+
...filterDefinedEnvs(this.envs),
|
|
931
|
+
[NECKBEARD_SANDBOX_RUNTIME_ENV]: "1"
|
|
932
|
+
};
|
|
488
933
|
}
|
|
489
934
|
async createSandboxHandle() {
|
|
490
935
|
if (this.provider === "daytona") {
|
|
@@ -727,6 +1172,9 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
727
1172
|
}
|
|
728
1173
|
}
|
|
729
1174
|
}
|
|
1175
|
+
export function resolveAgentSourceFile(_candidates, options = {}) {
|
|
1176
|
+
return options.sandboxSourceFile ?? process.cwd() + '/agent.mjs';
|
|
1177
|
+
}
|
|
730
1178
|
`,
|
|
731
1179
|
loader: "js"
|
|
732
1180
|
}));
|
|
@@ -828,6 +1276,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
828
1276
|
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
829
1277
|
await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
|
|
830
1278
|
const serverConfig = {
|
|
1279
|
+
protocolVersion: RUNTIME_PROTOCOL_VERSION,
|
|
831
1280
|
port: this._server?.port ?? DEFAULT_SERVER_PORT,
|
|
832
1281
|
maxDurationMs: this.maxDuration * 1e3,
|
|
833
1282
|
sandboxContext: {
|
|
@@ -930,8 +1379,13 @@ ${parts.join("\n\n")}`;
|
|
|
930
1379
|
}
|
|
931
1380
|
try {
|
|
932
1381
|
const connection = await this.resolveRuntimeConnection(options?.sandboxId);
|
|
933
|
-
|
|
934
|
-
|
|
1382
|
+
let validatedInput;
|
|
1383
|
+
try {
|
|
1384
|
+
validatedInput = this.inputSchema.parse(input);
|
|
1385
|
+
} catch (error) {
|
|
1386
|
+
throw new ValidationError("Input validation failed.", asError(error));
|
|
1387
|
+
}
|
|
1388
|
+
const { invokeServer } = await import("./invoke-client-XEH6FVRH.js");
|
|
935
1389
|
let output;
|
|
936
1390
|
let sawOutput = false;
|
|
937
1391
|
for await (const event of invokeServer(validatedInput, {
|
|
@@ -958,7 +1412,12 @@ ${parts.join("\n\n")}`;
|
|
|
958
1412
|
error: new ExecutionError("Agent server completed without returning output.")
|
|
959
1413
|
};
|
|
960
1414
|
}
|
|
961
|
-
|
|
1415
|
+
let validated;
|
|
1416
|
+
try {
|
|
1417
|
+
validated = this.outputSchema ? this.outputSchema.parse(output) : output;
|
|
1418
|
+
} catch (error) {
|
|
1419
|
+
throw new ValidationError("Output validation failed.", asError(error));
|
|
1420
|
+
}
|
|
962
1421
|
return { ok: true, executionId, output: validated };
|
|
963
1422
|
} catch (err) {
|
|
964
1423
|
return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
|
|
@@ -975,22 +1434,32 @@ ${parts.join("\n\n")}`;
|
|
|
975
1434
|
);
|
|
976
1435
|
}
|
|
977
1436
|
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
|
-
|
|
1437
|
+
const { invokeServer } = await import("./invoke-client-XEH6FVRH.js");
|
|
1438
|
+
let validated;
|
|
1439
|
+
try {
|
|
1440
|
+
validated = this.inputSchema.parse(input);
|
|
1441
|
+
} catch (error) {
|
|
1442
|
+
throw new ValidationError("Input validation failed.", asError(error));
|
|
1443
|
+
}
|
|
1444
|
+
try {
|
|
1445
|
+
for await (const frame of invokeServer(validated, {
|
|
1446
|
+
serverUrl: connection.serverUrl,
|
|
1447
|
+
provider: connection.provider,
|
|
1448
|
+
trafficToken: getTrafficToken(connection),
|
|
1449
|
+
frameSchema: this.frameSchema,
|
|
1450
|
+
signal: options?.signal
|
|
1451
|
+
})) {
|
|
1452
|
+
if (frame.kind === "frame") {
|
|
1453
|
+
yield frame.data;
|
|
1454
|
+
} else if (frame.kind === "error") {
|
|
1455
|
+
const err = new ExecutionError(frame.error.message);
|
|
1456
|
+
err.stack = frame.error.stack;
|
|
1457
|
+
throw err;
|
|
1458
|
+
}
|
|
993
1459
|
}
|
|
1460
|
+
} catch (error) {
|
|
1461
|
+
if (error instanceof ExecutionError) throw error;
|
|
1462
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
994
1463
|
}
|
|
995
1464
|
}
|
|
996
1465
|
};
|
|
@@ -1002,5 +1471,7 @@ export {
|
|
|
1002
1471
|
ExecutionError,
|
|
1003
1472
|
NeckbeardError,
|
|
1004
1473
|
ValidationError,
|
|
1005
|
-
normalizeStackFramePath
|
|
1474
|
+
normalizeStackFramePath,
|
|
1475
|
+
resolveAgentSourceFile,
|
|
1476
|
+
withNeckbeardNextConfig
|
|
1006
1477
|
};
|