agent-neckbeard 1.1.3 → 1.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +479 -9
- package/dist/index.d.cts +94 -11
- package/dist/index.d.ts +94 -11
- package/dist/index.js +375 -9
- package/dist/invoke-client-Y3NPRFEE.js +88 -0
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -3,7 +3,171 @@ import { fileURLToPath } from "url";
|
|
|
3
3
|
import { existsSync, readdirSync, readFileSync, statSync } from "fs";
|
|
4
4
|
import { dirname, join, relative, resolve } from "path";
|
|
5
5
|
import { builtinModules, createRequire } from "module";
|
|
6
|
-
import {
|
|
6
|
+
import { randomBytes } from "crypto";
|
|
7
|
+
|
|
8
|
+
// src/server-code.ts
|
|
9
|
+
function buildServerCode(options) {
|
|
10
|
+
const sandboxContextLiteral = JSON.stringify(options.sandboxContext);
|
|
11
|
+
const defaultPort = options.port;
|
|
12
|
+
const maxDurationMs = options.maxDurationSeconds * 1e3;
|
|
13
|
+
return `
|
|
14
|
+
import { createServer } from 'node:http';
|
|
15
|
+
|
|
16
|
+
const DEFAULT_PORT = ${defaultPort};
|
|
17
|
+
const MAX_DURATION_MS = ${maxDurationMs};
|
|
18
|
+
const SANDBOX_CONTEXT = ${sandboxContextLiteral};
|
|
19
|
+
|
|
20
|
+
const PORT = Number(process.env.NECKBEARD_SERVER_PORT) || DEFAULT_PORT;
|
|
21
|
+
const TOKEN = process.env.NECKBEARD_SERVER_TOKEN;
|
|
22
|
+
if (!TOKEN) {
|
|
23
|
+
console.error('[neckbeard-server] NECKBEARD_SERVER_TOKEN env is required');
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const mod = await import('./agent.mjs');
|
|
28
|
+
const agent =
|
|
29
|
+
(mod.default && mod.default._server ? mod.default : null) ||
|
|
30
|
+
Object.values(mod).find((v) => v && typeof v === 'object' && v._server);
|
|
31
|
+
if (!agent || !agent._server) {
|
|
32
|
+
console.error('[neckbeard-server] No server-mode agent found in agent.mjs (expected export with a _server property)');
|
|
33
|
+
process.exit(1);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function sendSseFrame(res, frame) {
|
|
37
|
+
res.write(\`data: \${JSON.stringify(frame)}\\n\\n\`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function sendJson(res, status, body) {
|
|
41
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
42
|
+
res.end(JSON.stringify(body));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function readRequestBody(req) {
|
|
46
|
+
const chunks = [];
|
|
47
|
+
for await (const chunk of req) {
|
|
48
|
+
chunks.push(chunk);
|
|
49
|
+
}
|
|
50
|
+
return Buffer.concat(chunks).toString('utf-8');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isAuthorized(req) {
|
|
54
|
+
const header = req.headers['authorization'];
|
|
55
|
+
return header === \`Bearer \${TOKEN}\`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const server = createServer(async (req, res) => {
|
|
59
|
+
try {
|
|
60
|
+
if (req.url === '/health' && req.method === 'GET') {
|
|
61
|
+
return sendJson(res, 200, { ok: true });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (!isAuthorized(req)) {
|
|
65
|
+
return sendJson(res, 401, { error: 'unauthorized' });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (req.url === '/invoke' && req.method === 'POST') {
|
|
69
|
+
const rawBody = await readRequestBody(req);
|
|
70
|
+
let parsedBody;
|
|
71
|
+
try {
|
|
72
|
+
parsedBody = JSON.parse(rawBody);
|
|
73
|
+
} catch (err) {
|
|
74
|
+
return sendJson(res, 400, { error: 'invalid JSON body' });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
let validatedInput;
|
|
78
|
+
try {
|
|
79
|
+
validatedInput = agent.inputSchema.parse(parsedBody);
|
|
80
|
+
} catch (err) {
|
|
81
|
+
return sendJson(res, 400, {
|
|
82
|
+
error: 'input validation failed: ' + (err && err.message ? err.message : String(err)),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
res.writeHead(200, {
|
|
87
|
+
'content-type': 'text/event-stream',
|
|
88
|
+
'cache-control': 'no-cache, no-transform',
|
|
89
|
+
connection: 'keep-alive',
|
|
90
|
+
'x-accel-buffering': 'no',
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const controller = new AbortController();
|
|
94
|
+
req.on('close', () => controller.abort());
|
|
95
|
+
const timeout = setTimeout(() => controller.abort(), MAX_DURATION_MS);
|
|
96
|
+
|
|
97
|
+
const emit = async (frame) => {
|
|
98
|
+
if (!res.writableEnded) {
|
|
99
|
+
sendSseFrame(res, frame);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const ctx = {
|
|
104
|
+
executionId: \`exec_\${Date.now()}_\${Math.random().toString(36).slice(2, 8)}\`,
|
|
105
|
+
signal: controller.signal,
|
|
106
|
+
env: process.env,
|
|
107
|
+
sandbox: SANDBOX_CONTEXT,
|
|
108
|
+
logger: {
|
|
109
|
+
debug: (msg, ...args) => console.log('[DEBUG]', msg, ...args),
|
|
110
|
+
info: (msg, ...args) => console.log('[INFO]', msg, ...args),
|
|
111
|
+
warn: (msg, ...args) => console.warn('[WARN]', msg, ...args),
|
|
112
|
+
error: (msg, ...args) => console.error('[ERROR]', msg, ...args),
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
try {
|
|
117
|
+
await agent._server.handler({
|
|
118
|
+
input: validatedInput,
|
|
119
|
+
ctx,
|
|
120
|
+
signal: controller.signal,
|
|
121
|
+
emit,
|
|
122
|
+
});
|
|
123
|
+
} catch (err) {
|
|
124
|
+
try {
|
|
125
|
+
sendSseFrame(res, {
|
|
126
|
+
type: 'error',
|
|
127
|
+
error: err && err.message ? err.message : String(err),
|
|
128
|
+
});
|
|
129
|
+
} catch {
|
|
130
|
+
// response may already be closed
|
|
131
|
+
}
|
|
132
|
+
} finally {
|
|
133
|
+
clearTimeout(timeout);
|
|
134
|
+
if (!res.writableEnded) {
|
|
135
|
+
res.end();
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return sendJson(res, 404, { error: 'not found' });
|
|
142
|
+
} catch (err) {
|
|
143
|
+
console.error('[neckbeard-server] unexpected error', err);
|
|
144
|
+
if (!res.headersSent) {
|
|
145
|
+
sendJson(res, 500, { error: 'internal error' });
|
|
146
|
+
} else if (!res.writableEnded) {
|
|
147
|
+
res.end();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
server.listen(PORT, '0.0.0.0', () => {
|
|
153
|
+
console.log(\`[neckbeard-server] listening on port \${PORT}\`);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
function shutdown() {
|
|
157
|
+
console.log('[neckbeard-server] shutting down');
|
|
158
|
+
server.close(() => process.exit(0));
|
|
159
|
+
setTimeout(() => process.exit(0), 5000).unref();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
process.on('SIGTERM', shutdown);
|
|
163
|
+
process.on('SIGINT', shutdown);
|
|
164
|
+
`;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// src/index.ts
|
|
168
|
+
function readPackageJson(path) {
|
|
169
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
170
|
+
}
|
|
7
171
|
var getEsbuild = () => import("esbuild");
|
|
8
172
|
var getE2b = () => import("e2b");
|
|
9
173
|
var getDaytona = () => import("@daytona/sdk");
|
|
@@ -15,6 +179,9 @@ var NODE_TARGET = "node20";
|
|
|
15
179
|
var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
|
|
16
180
|
var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
|
|
17
181
|
var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
|
|
182
|
+
var DEFAULT_SERVER_PORT = 3e3;
|
|
183
|
+
var SERVER_HEALTH_TIMEOUT_MS = 12e4;
|
|
184
|
+
var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
|
|
18
185
|
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
19
186
|
var E2B_SANDBOX_HOME = "/home/user";
|
|
20
187
|
var NeckbeardError = class extends Error {
|
|
@@ -51,6 +218,36 @@ var ConfigurationError = class extends NeckbeardError {
|
|
|
51
218
|
}
|
|
52
219
|
};
|
|
53
220
|
var DEFAULT_DEPENDENCIES = {};
|
|
221
|
+
function isServerAgentConfig(config) {
|
|
222
|
+
return "server" in config && config.server !== void 0;
|
|
223
|
+
}
|
|
224
|
+
function generateAuthToken() {
|
|
225
|
+
return randomBytes(32).toString("hex");
|
|
226
|
+
}
|
|
227
|
+
async function waitForServerHealthy(healthUrl, authToken, previewToken) {
|
|
228
|
+
const deadline = Date.now() + SERVER_HEALTH_TIMEOUT_MS;
|
|
229
|
+
let lastError;
|
|
230
|
+
const urlWithToken = previewToken ? `${healthUrl}${healthUrl.includes("?") ? "&" : "?"}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(previewToken)}` : healthUrl;
|
|
231
|
+
while (Date.now() < deadline) {
|
|
232
|
+
try {
|
|
233
|
+
const response = await fetch(urlWithToken, {
|
|
234
|
+
headers: { authorization: `Bearer ${authToken}` }
|
|
235
|
+
});
|
|
236
|
+
if (response.ok) {
|
|
237
|
+
await response.text().catch(() => void 0);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
lastError = new Error(`health check returned ${response.status}`);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
lastError = error;
|
|
243
|
+
}
|
|
244
|
+
await new Promise((resolve2) => setTimeout(resolve2, SERVER_HEALTH_POLL_INTERVAL_MS));
|
|
245
|
+
}
|
|
246
|
+
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
247
|
+
throw new DeploymentError(
|
|
248
|
+
`Server did not become healthy at ${healthUrl} within ${SERVER_HEALTH_TIMEOUT_MS}ms: ${message}`
|
|
249
|
+
);
|
|
250
|
+
}
|
|
54
251
|
function requireEnv(name) {
|
|
55
252
|
const value = process.env[name];
|
|
56
253
|
if (!value) {
|
|
@@ -90,7 +287,7 @@ async function resolvePackageInfo(importPath, resolveDir) {
|
|
|
90
287
|
while (true) {
|
|
91
288
|
const candidate = join(root, "package.json");
|
|
92
289
|
if (existsSync(candidate)) {
|
|
93
|
-
const candidatePackageJson =
|
|
290
|
+
const candidatePackageJson = readPackageJson(candidate);
|
|
94
291
|
if (candidatePackageJson.name === packageName) {
|
|
95
292
|
packageJsonPath = candidate;
|
|
96
293
|
break;
|
|
@@ -101,7 +298,7 @@ async function resolvePackageInfo(importPath, resolveDir) {
|
|
|
101
298
|
root = parent;
|
|
102
299
|
}
|
|
103
300
|
if (!packageJsonPath) return null;
|
|
104
|
-
const packageJson =
|
|
301
|
+
const packageJson = readPackageJson(packageJsonPath);
|
|
105
302
|
if (!packageJson.name || !packageJson.version) return null;
|
|
106
303
|
root = dirname(packageJsonPath);
|
|
107
304
|
return {
|
|
@@ -267,6 +464,34 @@ async function createDaytonaHandle(sandbox) {
|
|
|
267
464
|
stderr: ""
|
|
268
465
|
};
|
|
269
466
|
},
|
|
467
|
+
startDetachedCommand: async (cmd, options) => {
|
|
468
|
+
const sessionId = `neckbeard-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
469
|
+
await sandbox.process.createSession(sessionId);
|
|
470
|
+
const envPrefix = options.envs ? Object.entries(options.envs).map(([k, v]) => `${k}=${shellEscape(v)}`).join(" ") + " " : "";
|
|
471
|
+
const cwdPrefix = options.cwd ? `cd ${shellEscape(options.cwd)} && ` : "";
|
|
472
|
+
const result = await sandbox.process.executeSessionCommand(sessionId, {
|
|
473
|
+
command: `${cwdPrefix}${envPrefix}${cmd}`,
|
|
474
|
+
runAsync: true
|
|
475
|
+
});
|
|
476
|
+
return { sessionId, commandId: result.cmdId };
|
|
477
|
+
},
|
|
478
|
+
readSessionLogs: async (sessionId, commandId) => {
|
|
479
|
+
try {
|
|
480
|
+
const logs = await sandbox.process.getSessionCommandLogs(sessionId, commandId);
|
|
481
|
+
return {
|
|
482
|
+
stdout: logs.stdout ?? logs.output ?? "",
|
|
483
|
+
stderr: logs.stderr ?? ""
|
|
484
|
+
};
|
|
485
|
+
} catch {
|
|
486
|
+
return { stdout: "", stderr: "" };
|
|
487
|
+
}
|
|
488
|
+
},
|
|
489
|
+
stopSession: async (sessionId) => {
|
|
490
|
+
await sandbox.process.deleteSession(sessionId);
|
|
491
|
+
},
|
|
492
|
+
getPreviewLink: async (port) => {
|
|
493
|
+
return sandbox.getPreviewLink(port);
|
|
494
|
+
},
|
|
270
495
|
destroy: () => sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS))
|
|
271
496
|
};
|
|
272
497
|
}
|
|
@@ -327,15 +552,23 @@ var Agent = class {
|
|
|
327
552
|
provider;
|
|
328
553
|
template;
|
|
329
554
|
inputSchema;
|
|
555
|
+
/** Only populated for one-shot agents; undefined for server-mode. */
|
|
330
556
|
outputSchema;
|
|
557
|
+
/** Only populated for server-mode agents; undefined for one-shot. */
|
|
558
|
+
frameSchema;
|
|
559
|
+
mode;
|
|
331
560
|
maxDuration;
|
|
332
561
|
dependencies;
|
|
333
562
|
files;
|
|
334
563
|
claudeDir;
|
|
335
564
|
envs;
|
|
336
565
|
build;
|
|
337
|
-
/** @internal Used by the sandbox runner
|
|
566
|
+
/** @internal Used by the sandbox runner for one-shot agents. */
|
|
338
567
|
_run;
|
|
568
|
+
/** @internal Used by the in-sandbox HTTP server for server-mode agents. */
|
|
569
|
+
_server;
|
|
570
|
+
/** @internal Runtime state populated by deploy() for server-mode agents. */
|
|
571
|
+
_serverRuntime;
|
|
339
572
|
_sourceFile;
|
|
340
573
|
_sandboxId;
|
|
341
574
|
constructor(config) {
|
|
@@ -343,15 +576,22 @@ var Agent = class {
|
|
|
343
576
|
this.provider = config.sandbox.provider;
|
|
344
577
|
this.template = config.sandbox.template;
|
|
345
578
|
this.inputSchema = config.inputSchema;
|
|
346
|
-
this.outputSchema = config.outputSchema;
|
|
347
579
|
this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
|
|
348
|
-
this._run = config.run;
|
|
349
580
|
this._sourceFile = getCallerFile();
|
|
350
581
|
this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
|
|
351
582
|
this.files = config.files ?? [];
|
|
352
583
|
this.claudeDir = config.claudeDir;
|
|
353
584
|
this.envs = config.envs ?? {};
|
|
354
585
|
this.build = config.build ?? {};
|
|
586
|
+
if (isServerAgentConfig(config)) {
|
|
587
|
+
this.mode = "server";
|
|
588
|
+
this._server = config.server;
|
|
589
|
+
this.frameSchema = config.server.frameSchema;
|
|
590
|
+
} else {
|
|
591
|
+
this.mode = "one-shot";
|
|
592
|
+
this._run = config.run;
|
|
593
|
+
this.outputSchema = config.outputSchema;
|
|
594
|
+
}
|
|
355
595
|
}
|
|
356
596
|
get sandboxId() {
|
|
357
597
|
return this._sandboxId;
|
|
@@ -520,7 +760,16 @@ try {
|
|
|
520
760
|
* ```
|
|
521
761
|
*/
|
|
522
762
|
async deploy(options) {
|
|
523
|
-
if (!options?.fresh && this._sandboxId) return this._sandboxId;
|
|
763
|
+
if (!options?.fresh && this._sandboxId && this.mode === "one-shot") return this._sandboxId;
|
|
764
|
+
if (!options?.fresh && this._sandboxId && this._serverRuntime) {
|
|
765
|
+
return {
|
|
766
|
+
mode: "server",
|
|
767
|
+
sandboxId: this._sandboxId,
|
|
768
|
+
serverUrl: this._serverRuntime.serverUrl,
|
|
769
|
+
authToken: this._serverRuntime.authToken,
|
|
770
|
+
previewToken: this._serverRuntime.previewToken
|
|
771
|
+
};
|
|
772
|
+
}
|
|
524
773
|
const esbuild = await getEsbuild();
|
|
525
774
|
const externalPatterns = Array.from(
|
|
526
775
|
/* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
|
|
@@ -563,6 +812,10 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
563
812
|
this.outputSchema = config.outputSchema;
|
|
564
813
|
this.maxDuration = config.maxDuration ?? 300;
|
|
565
814
|
this._run = config.run;
|
|
815
|
+
if (config.server) {
|
|
816
|
+
this._server = config.server;
|
|
817
|
+
this.frameSchema = config.server.frameSchema;
|
|
818
|
+
}
|
|
566
819
|
}
|
|
567
820
|
}
|
|
568
821
|
`,
|
|
@@ -665,7 +918,25 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
665
918
|
}
|
|
666
919
|
}
|
|
667
920
|
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
668
|
-
|
|
921
|
+
if (this.mode === "one-shot") {
|
|
922
|
+
await sandbox.writeFile(paths.runnerModule, runnerCode);
|
|
923
|
+
} else if (this._server) {
|
|
924
|
+
const port = this._server.port ?? DEFAULT_SERVER_PORT;
|
|
925
|
+
const serverCode = buildServerCode({
|
|
926
|
+
port,
|
|
927
|
+
sandboxContext: {
|
|
928
|
+
provider: paths.provider,
|
|
929
|
+
homeDir: paths.homeDir,
|
|
930
|
+
workDir: paths.workDir,
|
|
931
|
+
agentDir: paths.agentDir,
|
|
932
|
+
ioDir: paths.ioDir,
|
|
933
|
+
inputJson: paths.inputJson,
|
|
934
|
+
outputJson: paths.outputJson
|
|
935
|
+
},
|
|
936
|
+
maxDurationSeconds: this.maxDuration
|
|
937
|
+
});
|
|
938
|
+
await sandbox.writeFile(`${paths.agentDir}/server.mjs`, serverCode);
|
|
939
|
+
}
|
|
669
940
|
if (collectedExternals.size > 0) {
|
|
670
941
|
const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
|
|
671
942
|
const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
|
|
@@ -692,6 +963,55 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
692
963
|
throw new DeploymentError(details);
|
|
693
964
|
}
|
|
694
965
|
}
|
|
966
|
+
if (this.mode === "server") {
|
|
967
|
+
if (!sandbox.startDetachedCommand || !sandbox.getPreviewLink) {
|
|
968
|
+
throw new DeploymentError(
|
|
969
|
+
"Server-mode agents require a sandbox provider that supports detached sessions and preview URLs (currently Daytona only)."
|
|
970
|
+
);
|
|
971
|
+
}
|
|
972
|
+
const port = this._server?.port ?? DEFAULT_SERVER_PORT;
|
|
973
|
+
const authToken = generateAuthToken();
|
|
974
|
+
const { sessionId, commandId } = await sandbox.startDetachedCommand("node server.mjs", {
|
|
975
|
+
cwd: paths.agentDir,
|
|
976
|
+
envs: {
|
|
977
|
+
...this.sandboxEnv,
|
|
978
|
+
NECKBEARD_SERVER_PORT: String(port),
|
|
979
|
+
NECKBEARD_SERVER_TOKEN: authToken
|
|
980
|
+
}
|
|
981
|
+
});
|
|
982
|
+
const { url: previewUrl, token: previewToken } = await sandbox.getPreviewLink(port);
|
|
983
|
+
const serverUrl = `${previewUrl.replace(/\/$/, "")}/invoke`;
|
|
984
|
+
const healthUrl = `${previewUrl.replace(/\/$/, "")}/health`;
|
|
985
|
+
try {
|
|
986
|
+
await waitForServerHealthy(healthUrl, authToken, previewToken);
|
|
987
|
+
} catch (err) {
|
|
988
|
+
const baseMessage = err instanceof Error ? err.message : String(err);
|
|
989
|
+
let logs = "";
|
|
990
|
+
if (commandId && sandbox.readSessionLogs) {
|
|
991
|
+
const captured = await sandbox.readSessionLogs(sessionId, commandId);
|
|
992
|
+
const parts = [];
|
|
993
|
+
if (captured.stdout.trim()) parts.push(`stdout:
|
|
994
|
+
${captured.stdout}`);
|
|
995
|
+
if (captured.stderr.trim()) parts.push(`stderr:
|
|
996
|
+
${captured.stderr}`);
|
|
997
|
+
if (parts.length > 0) {
|
|
998
|
+
logs = `
|
|
999
|
+
--- server logs ---
|
|
1000
|
+
${parts.join("\n\n")}`;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
1004
|
+
}
|
|
1005
|
+
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
1006
|
+
this._serverRuntime = { sessionId, serverUrl, authToken, previewToken };
|
|
1007
|
+
return {
|
|
1008
|
+
mode: "server",
|
|
1009
|
+
sandboxId: sandbox.id,
|
|
1010
|
+
serverUrl,
|
|
1011
|
+
authToken,
|
|
1012
|
+
previewToken
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
695
1015
|
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
696
1016
|
return sandbox.id;
|
|
697
1017
|
}
|
|
@@ -719,6 +1039,15 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
719
1039
|
*/
|
|
720
1040
|
async run(input, options) {
|
|
721
1041
|
const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1042
|
+
if (this.mode === "server") {
|
|
1043
|
+
return {
|
|
1044
|
+
ok: false,
|
|
1045
|
+
executionId,
|
|
1046
|
+
error: new ExecutionError(
|
|
1047
|
+
"run() is not available on server-mode agents. Use agent.invoke() instead."
|
|
1048
|
+
)
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
722
1051
|
const sandboxId = options?.sandboxId ?? this._sandboxId;
|
|
723
1052
|
if (!sandboxId) {
|
|
724
1053
|
return {
|
|
@@ -780,11 +1109,48 @@ Stdout: ${capturedStdout}` : ""
|
|
|
780
1109
|
err.stack = output.error.stack;
|
|
781
1110
|
return { ok: false, executionId, error: err };
|
|
782
1111
|
}
|
|
783
|
-
|
|
1112
|
+
const validated = this.outputSchema ? this.outputSchema.parse(output.output) : output.output;
|
|
1113
|
+
return { ok: true, executionId, output: validated };
|
|
784
1114
|
} catch (err) {
|
|
785
1115
|
return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
|
|
786
1116
|
}
|
|
787
1117
|
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Invoke a server-mode agent. Streams the agent's emitted frames back as an
|
|
1120
|
+
* async iterator as the handler runs. Only valid for agents constructed with
|
|
1121
|
+
* `server: {...}` config; one-shot agents should use `run()` instead.
|
|
1122
|
+
*
|
|
1123
|
+
* Requires the agent to be deployed via `deploy()` (returns `serverUrl` and
|
|
1124
|
+
* `authToken`) — callers must persist those values and pass them on each
|
|
1125
|
+
* invocation. Deploy is not yet implemented for server mode; this method
|
|
1126
|
+
* currently throws `ConfigurationError` if `serverUrl` is not supplied.
|
|
1127
|
+
*/
|
|
1128
|
+
async *invoke(input, options) {
|
|
1129
|
+
if (this.mode !== "server") {
|
|
1130
|
+
throw new ConfigurationError(
|
|
1131
|
+
"invoke() is only available on server-mode agents. Use agent.run() for one-shot agents."
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
const serverUrl = options?.serverUrl ?? this._serverRuntime?.serverUrl;
|
|
1135
|
+
const authToken = options?.authToken ?? this._serverRuntime?.authToken;
|
|
1136
|
+
const previewToken = options?.previewToken ?? this._serverRuntime?.previewToken;
|
|
1137
|
+
if (!serverUrl || !authToken) {
|
|
1138
|
+
throw new ConfigurationError(
|
|
1139
|
+
"Agent not deployed in server mode. Call agent.deploy() first and pass the returned serverUrl and authToken to invoke()."
|
|
1140
|
+
);
|
|
1141
|
+
}
|
|
1142
|
+
const urlWithPreviewToken = previewToken ? `${serverUrl}${serverUrl.includes("?") ? "&" : "?"}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(previewToken)}` : serverUrl;
|
|
1143
|
+
const { invokeServer } = await import("./invoke-client-Y3NPRFEE.js");
|
|
1144
|
+
const validated = this.inputSchema.parse(input);
|
|
1145
|
+
for await (const frame of invokeServer(validated, {
|
|
1146
|
+
serverUrl: urlWithPreviewToken,
|
|
1147
|
+
authToken,
|
|
1148
|
+
frameSchema: this.frameSchema,
|
|
1149
|
+
signal: options?.signal
|
|
1150
|
+
})) {
|
|
1151
|
+
yield frame;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
788
1154
|
};
|
|
789
1155
|
export {
|
|
790
1156
|
Agent,
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// src/sse-framing.ts
|
|
2
|
+
async function* decodeSseStream(chunks) {
|
|
3
|
+
let buffer = "";
|
|
4
|
+
for await (const chunk of chunks) {
|
|
5
|
+
buffer += chunk;
|
|
6
|
+
let boundary = buffer.indexOf("\n\n");
|
|
7
|
+
while (boundary !== -1) {
|
|
8
|
+
const rawFrame = buffer.slice(0, boundary);
|
|
9
|
+
buffer = buffer.slice(boundary + 2);
|
|
10
|
+
const parsed = parseFrame(rawFrame);
|
|
11
|
+
if (parsed !== void 0) {
|
|
12
|
+
yield parsed;
|
|
13
|
+
}
|
|
14
|
+
boundary = buffer.indexOf("\n\n");
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const tail = buffer.trim();
|
|
18
|
+
if (tail.length > 0) {
|
|
19
|
+
const parsed = parseFrame(tail);
|
|
20
|
+
if (parsed !== void 0) {
|
|
21
|
+
yield parsed;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function parseFrame(raw) {
|
|
26
|
+
const dataLines = [];
|
|
27
|
+
for (const line of raw.split("\n")) {
|
|
28
|
+
if (line.startsWith("data:")) {
|
|
29
|
+
dataLines.push(line.slice("data:".length).replace(/^ /, ""));
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (dataLines.length === 0) return void 0;
|
|
33
|
+
try {
|
|
34
|
+
return JSON.parse(dataLines.join("\n"));
|
|
35
|
+
} catch {
|
|
36
|
+
return void 0;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/invoke-client.ts
|
|
41
|
+
async function* invokeServer(input, options) {
|
|
42
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
43
|
+
const response = await fetchImpl(options.serverUrl, {
|
|
44
|
+
method: "POST",
|
|
45
|
+
headers: {
|
|
46
|
+
"content-type": "application/json",
|
|
47
|
+
accept: "text/event-stream",
|
|
48
|
+
authorization: `Bearer ${options.authToken}`
|
|
49
|
+
},
|
|
50
|
+
body: JSON.stringify(input),
|
|
51
|
+
signal: options.signal
|
|
52
|
+
});
|
|
53
|
+
if (!response.ok) {
|
|
54
|
+
const text = await response.text().catch(() => "");
|
|
55
|
+
throw new Error(
|
|
56
|
+
`Server returned ${response.status}${text ? `: ${text}` : ""}`
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
if (!response.body) {
|
|
60
|
+
throw new Error("Server response had no body");
|
|
61
|
+
}
|
|
62
|
+
const reader = response.body.getReader();
|
|
63
|
+
const decoder = new TextDecoder();
|
|
64
|
+
async function* chunks() {
|
|
65
|
+
try {
|
|
66
|
+
while (true) {
|
|
67
|
+
const { value, done } = await reader.read();
|
|
68
|
+
if (done) return;
|
|
69
|
+
yield decoder.decode(value, { stream: true });
|
|
70
|
+
}
|
|
71
|
+
} finally {
|
|
72
|
+
try {
|
|
73
|
+
reader.releaseLock();
|
|
74
|
+
} catch {
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
for await (const rawFrame of decodeSseStream(chunks())) {
|
|
79
|
+
if (options.frameSchema) {
|
|
80
|
+
yield options.frameSchema.parse(rawFrame);
|
|
81
|
+
} else {
|
|
82
|
+
yield rawFrame;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export {
|
|
87
|
+
invokeServer
|
|
88
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-neckbeard",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.5",
|
|
4
4
|
"description": "Deploy AI agents to E2B and Daytona sandboxes",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -33,14 +33,14 @@
|
|
|
33
33
|
"test:e2e": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.e2e.config.mjs --runInBand",
|
|
34
34
|
"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
35
|
"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 --testPathPattern=cjs-build",
|
|
36
37
|
"typecheck": "tsc --noEmit -p tsconfig.test.json",
|
|
37
38
|
"prepare": "npm run build"
|
|
38
39
|
},
|
|
39
40
|
"dependencies": {
|
|
40
41
|
"@daytona/sdk": "^0.164.0",
|
|
41
42
|
"e2b": "^2.2.0",
|
|
42
|
-
"esbuild": "^0.24.0"
|
|
43
|
-
"pkg-types": "^2.3.0"
|
|
43
|
+
"esbuild": "^0.24.0"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
46
|
"zod": "^3.0.0 || ^4.0.0"
|