agent-neckbeard 1.1.4 → 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 +474 -6
- package/dist/index.d.cts +94 -11
- package/dist/index.d.ts +94 -11
- package/dist/index.js +370 -6
- package/dist/invoke-client-Y3NPRFEE.js +88 -0
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -5,6 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
|
5
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
6
|
var __getProtoOf = Object.getPrototypeOf;
|
|
7
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __esm = (fn, res) => function __init() {
|
|
9
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
10
|
+
};
|
|
8
11
|
var __export = (target, all) => {
|
|
9
12
|
for (var name in all)
|
|
10
13
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -27,6 +30,107 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
27
30
|
));
|
|
28
31
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
32
|
|
|
33
|
+
// src/sse-framing.ts
|
|
34
|
+
async function* decodeSseStream(chunks) {
|
|
35
|
+
let buffer = "";
|
|
36
|
+
for await (const chunk of chunks) {
|
|
37
|
+
buffer += chunk;
|
|
38
|
+
let boundary = buffer.indexOf("\n\n");
|
|
39
|
+
while (boundary !== -1) {
|
|
40
|
+
const rawFrame = buffer.slice(0, boundary);
|
|
41
|
+
buffer = buffer.slice(boundary + 2);
|
|
42
|
+
const parsed = parseFrame(rawFrame);
|
|
43
|
+
if (parsed !== void 0) {
|
|
44
|
+
yield parsed;
|
|
45
|
+
}
|
|
46
|
+
boundary = buffer.indexOf("\n\n");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const tail = buffer.trim();
|
|
50
|
+
if (tail.length > 0) {
|
|
51
|
+
const parsed = parseFrame(tail);
|
|
52
|
+
if (parsed !== void 0) {
|
|
53
|
+
yield parsed;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function parseFrame(raw) {
|
|
58
|
+
const dataLines = [];
|
|
59
|
+
for (const line of raw.split("\n")) {
|
|
60
|
+
if (line.startsWith("data:")) {
|
|
61
|
+
dataLines.push(line.slice("data:".length).replace(/^ /, ""));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (dataLines.length === 0) return void 0;
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(dataLines.join("\n"));
|
|
67
|
+
} catch {
|
|
68
|
+
return void 0;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
var init_sse_framing = __esm({
|
|
72
|
+
"src/sse-framing.ts"() {
|
|
73
|
+
"use strict";
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// src/invoke-client.ts
|
|
78
|
+
var invoke_client_exports = {};
|
|
79
|
+
__export(invoke_client_exports, {
|
|
80
|
+
invokeServer: () => invokeServer
|
|
81
|
+
});
|
|
82
|
+
async function* invokeServer(input, options) {
|
|
83
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
84
|
+
const response = await fetchImpl(options.serverUrl, {
|
|
85
|
+
method: "POST",
|
|
86
|
+
headers: {
|
|
87
|
+
"content-type": "application/json",
|
|
88
|
+
accept: "text/event-stream",
|
|
89
|
+
authorization: `Bearer ${options.authToken}`
|
|
90
|
+
},
|
|
91
|
+
body: JSON.stringify(input),
|
|
92
|
+
signal: options.signal
|
|
93
|
+
});
|
|
94
|
+
if (!response.ok) {
|
|
95
|
+
const text = await response.text().catch(() => "");
|
|
96
|
+
throw new Error(
|
|
97
|
+
`Server returned ${response.status}${text ? `: ${text}` : ""}`
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
if (!response.body) {
|
|
101
|
+
throw new Error("Server response had no body");
|
|
102
|
+
}
|
|
103
|
+
const reader = response.body.getReader();
|
|
104
|
+
const decoder = new TextDecoder();
|
|
105
|
+
async function* chunks() {
|
|
106
|
+
try {
|
|
107
|
+
while (true) {
|
|
108
|
+
const { value, done } = await reader.read();
|
|
109
|
+
if (done) return;
|
|
110
|
+
yield decoder.decode(value, { stream: true });
|
|
111
|
+
}
|
|
112
|
+
} finally {
|
|
113
|
+
try {
|
|
114
|
+
reader.releaseLock();
|
|
115
|
+
} catch {
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
for await (const rawFrame of decodeSseStream(chunks())) {
|
|
120
|
+
if (options.frameSchema) {
|
|
121
|
+
yield options.frameSchema.parse(rawFrame);
|
|
122
|
+
} else {
|
|
123
|
+
yield rawFrame;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
var init_invoke_client = __esm({
|
|
128
|
+
"src/invoke-client.ts"() {
|
|
129
|
+
"use strict";
|
|
130
|
+
init_sse_framing();
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
|
|
30
134
|
// src/index.ts
|
|
31
135
|
var index_exports = {};
|
|
32
136
|
__export(index_exports, {
|
|
@@ -44,6 +148,168 @@ var import_node_url = require("url");
|
|
|
44
148
|
var import_node_fs = require("fs");
|
|
45
149
|
var import_node_path = require("path");
|
|
46
150
|
var import_node_module = require("module");
|
|
151
|
+
var import_node_crypto = require("crypto");
|
|
152
|
+
|
|
153
|
+
// src/server-code.ts
|
|
154
|
+
function buildServerCode(options) {
|
|
155
|
+
const sandboxContextLiteral = JSON.stringify(options.sandboxContext);
|
|
156
|
+
const defaultPort = options.port;
|
|
157
|
+
const maxDurationMs = options.maxDurationSeconds * 1e3;
|
|
158
|
+
return `
|
|
159
|
+
import { createServer } from 'node:http';
|
|
160
|
+
|
|
161
|
+
const DEFAULT_PORT = ${defaultPort};
|
|
162
|
+
const MAX_DURATION_MS = ${maxDurationMs};
|
|
163
|
+
const SANDBOX_CONTEXT = ${sandboxContextLiteral};
|
|
164
|
+
|
|
165
|
+
const PORT = Number(process.env.NECKBEARD_SERVER_PORT) || DEFAULT_PORT;
|
|
166
|
+
const TOKEN = process.env.NECKBEARD_SERVER_TOKEN;
|
|
167
|
+
if (!TOKEN) {
|
|
168
|
+
console.error('[neckbeard-server] NECKBEARD_SERVER_TOKEN env is required');
|
|
169
|
+
process.exit(1);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const mod = await import('./agent.mjs');
|
|
173
|
+
const agent =
|
|
174
|
+
(mod.default && mod.default._server ? mod.default : null) ||
|
|
175
|
+
Object.values(mod).find((v) => v && typeof v === 'object' && v._server);
|
|
176
|
+
if (!agent || !agent._server) {
|
|
177
|
+
console.error('[neckbeard-server] No server-mode agent found in agent.mjs (expected export with a _server property)');
|
|
178
|
+
process.exit(1);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function sendSseFrame(res, frame) {
|
|
182
|
+
res.write(\`data: \${JSON.stringify(frame)}\\n\\n\`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function sendJson(res, status, body) {
|
|
186
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
187
|
+
res.end(JSON.stringify(body));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function readRequestBody(req) {
|
|
191
|
+
const chunks = [];
|
|
192
|
+
for await (const chunk of req) {
|
|
193
|
+
chunks.push(chunk);
|
|
194
|
+
}
|
|
195
|
+
return Buffer.concat(chunks).toString('utf-8');
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function isAuthorized(req) {
|
|
199
|
+
const header = req.headers['authorization'];
|
|
200
|
+
return header === \`Bearer \${TOKEN}\`;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const server = createServer(async (req, res) => {
|
|
204
|
+
try {
|
|
205
|
+
if (req.url === '/health' && req.method === 'GET') {
|
|
206
|
+
return sendJson(res, 200, { ok: true });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (!isAuthorized(req)) {
|
|
210
|
+
return sendJson(res, 401, { error: 'unauthorized' });
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (req.url === '/invoke' && req.method === 'POST') {
|
|
214
|
+
const rawBody = await readRequestBody(req);
|
|
215
|
+
let parsedBody;
|
|
216
|
+
try {
|
|
217
|
+
parsedBody = JSON.parse(rawBody);
|
|
218
|
+
} catch (err) {
|
|
219
|
+
return sendJson(res, 400, { error: 'invalid JSON body' });
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
let validatedInput;
|
|
223
|
+
try {
|
|
224
|
+
validatedInput = agent.inputSchema.parse(parsedBody);
|
|
225
|
+
} catch (err) {
|
|
226
|
+
return sendJson(res, 400, {
|
|
227
|
+
error: 'input validation failed: ' + (err && err.message ? err.message : String(err)),
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
res.writeHead(200, {
|
|
232
|
+
'content-type': 'text/event-stream',
|
|
233
|
+
'cache-control': 'no-cache, no-transform',
|
|
234
|
+
connection: 'keep-alive',
|
|
235
|
+
'x-accel-buffering': 'no',
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
const controller = new AbortController();
|
|
239
|
+
req.on('close', () => controller.abort());
|
|
240
|
+
const timeout = setTimeout(() => controller.abort(), MAX_DURATION_MS);
|
|
241
|
+
|
|
242
|
+
const emit = async (frame) => {
|
|
243
|
+
if (!res.writableEnded) {
|
|
244
|
+
sendSseFrame(res, frame);
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const ctx = {
|
|
249
|
+
executionId: \`exec_\${Date.now()}_\${Math.random().toString(36).slice(2, 8)}\`,
|
|
250
|
+
signal: controller.signal,
|
|
251
|
+
env: process.env,
|
|
252
|
+
sandbox: SANDBOX_CONTEXT,
|
|
253
|
+
logger: {
|
|
254
|
+
debug: (msg, ...args) => console.log('[DEBUG]', msg, ...args),
|
|
255
|
+
info: (msg, ...args) => console.log('[INFO]', msg, ...args),
|
|
256
|
+
warn: (msg, ...args) => console.warn('[WARN]', msg, ...args),
|
|
257
|
+
error: (msg, ...args) => console.error('[ERROR]', msg, ...args),
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
try {
|
|
262
|
+
await agent._server.handler({
|
|
263
|
+
input: validatedInput,
|
|
264
|
+
ctx,
|
|
265
|
+
signal: controller.signal,
|
|
266
|
+
emit,
|
|
267
|
+
});
|
|
268
|
+
} catch (err) {
|
|
269
|
+
try {
|
|
270
|
+
sendSseFrame(res, {
|
|
271
|
+
type: 'error',
|
|
272
|
+
error: err && err.message ? err.message : String(err),
|
|
273
|
+
});
|
|
274
|
+
} catch {
|
|
275
|
+
// response may already be closed
|
|
276
|
+
}
|
|
277
|
+
} finally {
|
|
278
|
+
clearTimeout(timeout);
|
|
279
|
+
if (!res.writableEnded) {
|
|
280
|
+
res.end();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return sendJson(res, 404, { error: 'not found' });
|
|
287
|
+
} catch (err) {
|
|
288
|
+
console.error('[neckbeard-server] unexpected error', err);
|
|
289
|
+
if (!res.headersSent) {
|
|
290
|
+
sendJson(res, 500, { error: 'internal error' });
|
|
291
|
+
} else if (!res.writableEnded) {
|
|
292
|
+
res.end();
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
server.listen(PORT, '0.0.0.0', () => {
|
|
298
|
+
console.log(\`[neckbeard-server] listening on port \${PORT}\`);
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
function shutdown() {
|
|
302
|
+
console.log('[neckbeard-server] shutting down');
|
|
303
|
+
server.close(() => process.exit(0));
|
|
304
|
+
setTimeout(() => process.exit(0), 5000).unref();
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
process.on('SIGTERM', shutdown);
|
|
308
|
+
process.on('SIGINT', shutdown);
|
|
309
|
+
`;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// src/index.ts
|
|
47
313
|
function readPackageJson(path) {
|
|
48
314
|
return JSON.parse((0, import_node_fs.readFileSync)(path, "utf8"));
|
|
49
315
|
}
|
|
@@ -58,6 +324,9 @@ var NODE_TARGET = "node20";
|
|
|
58
324
|
var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
|
|
59
325
|
var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
|
|
60
326
|
var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
|
|
327
|
+
var DEFAULT_SERVER_PORT = 3e3;
|
|
328
|
+
var SERVER_HEALTH_TIMEOUT_MS = 12e4;
|
|
329
|
+
var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
|
|
61
330
|
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
62
331
|
var E2B_SANDBOX_HOME = "/home/user";
|
|
63
332
|
var NeckbeardError = class extends Error {
|
|
@@ -94,6 +363,36 @@ var ConfigurationError = class extends NeckbeardError {
|
|
|
94
363
|
}
|
|
95
364
|
};
|
|
96
365
|
var DEFAULT_DEPENDENCIES = {};
|
|
366
|
+
function isServerAgentConfig(config) {
|
|
367
|
+
return "server" in config && config.server !== void 0;
|
|
368
|
+
}
|
|
369
|
+
function generateAuthToken() {
|
|
370
|
+
return (0, import_node_crypto.randomBytes)(32).toString("hex");
|
|
371
|
+
}
|
|
372
|
+
async function waitForServerHealthy(healthUrl, authToken, previewToken) {
|
|
373
|
+
const deadline = Date.now() + SERVER_HEALTH_TIMEOUT_MS;
|
|
374
|
+
let lastError;
|
|
375
|
+
const urlWithToken = previewToken ? `${healthUrl}${healthUrl.includes("?") ? "&" : "?"}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(previewToken)}` : healthUrl;
|
|
376
|
+
while (Date.now() < deadline) {
|
|
377
|
+
try {
|
|
378
|
+
const response = await fetch(urlWithToken, {
|
|
379
|
+
headers: { authorization: `Bearer ${authToken}` }
|
|
380
|
+
});
|
|
381
|
+
if (response.ok) {
|
|
382
|
+
await response.text().catch(() => void 0);
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
lastError = new Error(`health check returned ${response.status}`);
|
|
386
|
+
} catch (error) {
|
|
387
|
+
lastError = error;
|
|
388
|
+
}
|
|
389
|
+
await new Promise((resolve2) => setTimeout(resolve2, SERVER_HEALTH_POLL_INTERVAL_MS));
|
|
390
|
+
}
|
|
391
|
+
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
392
|
+
throw new DeploymentError(
|
|
393
|
+
`Server did not become healthy at ${healthUrl} within ${SERVER_HEALTH_TIMEOUT_MS}ms: ${message}`
|
|
394
|
+
);
|
|
395
|
+
}
|
|
97
396
|
function requireEnv(name) {
|
|
98
397
|
const value = process.env[name];
|
|
99
398
|
if (!value) {
|
|
@@ -310,6 +609,34 @@ async function createDaytonaHandle(sandbox) {
|
|
|
310
609
|
stderr: ""
|
|
311
610
|
};
|
|
312
611
|
},
|
|
612
|
+
startDetachedCommand: async (cmd, options) => {
|
|
613
|
+
const sessionId = `neckbeard-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
614
|
+
await sandbox.process.createSession(sessionId);
|
|
615
|
+
const envPrefix = options.envs ? Object.entries(options.envs).map(([k, v]) => `${k}=${shellEscape(v)}`).join(" ") + " " : "";
|
|
616
|
+
const cwdPrefix = options.cwd ? `cd ${shellEscape(options.cwd)} && ` : "";
|
|
617
|
+
const result = await sandbox.process.executeSessionCommand(sessionId, {
|
|
618
|
+
command: `${cwdPrefix}${envPrefix}${cmd}`,
|
|
619
|
+
runAsync: true
|
|
620
|
+
});
|
|
621
|
+
return { sessionId, commandId: result.cmdId };
|
|
622
|
+
},
|
|
623
|
+
readSessionLogs: async (sessionId, commandId) => {
|
|
624
|
+
try {
|
|
625
|
+
const logs = await sandbox.process.getSessionCommandLogs(sessionId, commandId);
|
|
626
|
+
return {
|
|
627
|
+
stdout: logs.stdout ?? logs.output ?? "",
|
|
628
|
+
stderr: logs.stderr ?? ""
|
|
629
|
+
};
|
|
630
|
+
} catch {
|
|
631
|
+
return { stdout: "", stderr: "" };
|
|
632
|
+
}
|
|
633
|
+
},
|
|
634
|
+
stopSession: async (sessionId) => {
|
|
635
|
+
await sandbox.process.deleteSession(sessionId);
|
|
636
|
+
},
|
|
637
|
+
getPreviewLink: async (port) => {
|
|
638
|
+
return sandbox.getPreviewLink(port);
|
|
639
|
+
},
|
|
313
640
|
destroy: () => sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS))
|
|
314
641
|
};
|
|
315
642
|
}
|
|
@@ -370,15 +697,23 @@ var Agent = class {
|
|
|
370
697
|
provider;
|
|
371
698
|
template;
|
|
372
699
|
inputSchema;
|
|
700
|
+
/** Only populated for one-shot agents; undefined for server-mode. */
|
|
373
701
|
outputSchema;
|
|
702
|
+
/** Only populated for server-mode agents; undefined for one-shot. */
|
|
703
|
+
frameSchema;
|
|
704
|
+
mode;
|
|
374
705
|
maxDuration;
|
|
375
706
|
dependencies;
|
|
376
707
|
files;
|
|
377
708
|
claudeDir;
|
|
378
709
|
envs;
|
|
379
710
|
build;
|
|
380
|
-
/** @internal Used by the sandbox runner
|
|
711
|
+
/** @internal Used by the sandbox runner for one-shot agents. */
|
|
381
712
|
_run;
|
|
713
|
+
/** @internal Used by the in-sandbox HTTP server for server-mode agents. */
|
|
714
|
+
_server;
|
|
715
|
+
/** @internal Runtime state populated by deploy() for server-mode agents. */
|
|
716
|
+
_serverRuntime;
|
|
382
717
|
_sourceFile;
|
|
383
718
|
_sandboxId;
|
|
384
719
|
constructor(config) {
|
|
@@ -386,15 +721,22 @@ var Agent = class {
|
|
|
386
721
|
this.provider = config.sandbox.provider;
|
|
387
722
|
this.template = config.sandbox.template;
|
|
388
723
|
this.inputSchema = config.inputSchema;
|
|
389
|
-
this.outputSchema = config.outputSchema;
|
|
390
724
|
this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
|
|
391
|
-
this._run = config.run;
|
|
392
725
|
this._sourceFile = getCallerFile();
|
|
393
726
|
this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
|
|
394
727
|
this.files = config.files ?? [];
|
|
395
728
|
this.claudeDir = config.claudeDir;
|
|
396
729
|
this.envs = config.envs ?? {};
|
|
397
730
|
this.build = config.build ?? {};
|
|
731
|
+
if (isServerAgentConfig(config)) {
|
|
732
|
+
this.mode = "server";
|
|
733
|
+
this._server = config.server;
|
|
734
|
+
this.frameSchema = config.server.frameSchema;
|
|
735
|
+
} else {
|
|
736
|
+
this.mode = "one-shot";
|
|
737
|
+
this._run = config.run;
|
|
738
|
+
this.outputSchema = config.outputSchema;
|
|
739
|
+
}
|
|
398
740
|
}
|
|
399
741
|
get sandboxId() {
|
|
400
742
|
return this._sandboxId;
|
|
@@ -563,7 +905,16 @@ try {
|
|
|
563
905
|
* ```
|
|
564
906
|
*/
|
|
565
907
|
async deploy(options) {
|
|
566
|
-
if (!options?.fresh && this._sandboxId) return this._sandboxId;
|
|
908
|
+
if (!options?.fresh && this._sandboxId && this.mode === "one-shot") return this._sandboxId;
|
|
909
|
+
if (!options?.fresh && this._sandboxId && this._serverRuntime) {
|
|
910
|
+
return {
|
|
911
|
+
mode: "server",
|
|
912
|
+
sandboxId: this._sandboxId,
|
|
913
|
+
serverUrl: this._serverRuntime.serverUrl,
|
|
914
|
+
authToken: this._serverRuntime.authToken,
|
|
915
|
+
previewToken: this._serverRuntime.previewToken
|
|
916
|
+
};
|
|
917
|
+
}
|
|
567
918
|
const esbuild = await getEsbuild();
|
|
568
919
|
const externalPatterns = Array.from(
|
|
569
920
|
/* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
|
|
@@ -606,6 +957,10 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
606
957
|
this.outputSchema = config.outputSchema;
|
|
607
958
|
this.maxDuration = config.maxDuration ?? 300;
|
|
608
959
|
this._run = config.run;
|
|
960
|
+
if (config.server) {
|
|
961
|
+
this._server = config.server;
|
|
962
|
+
this.frameSchema = config.server.frameSchema;
|
|
963
|
+
}
|
|
609
964
|
}
|
|
610
965
|
}
|
|
611
966
|
`,
|
|
@@ -708,7 +1063,25 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
708
1063
|
}
|
|
709
1064
|
}
|
|
710
1065
|
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
711
|
-
|
|
1066
|
+
if (this.mode === "one-shot") {
|
|
1067
|
+
await sandbox.writeFile(paths.runnerModule, runnerCode);
|
|
1068
|
+
} else if (this._server) {
|
|
1069
|
+
const port = this._server.port ?? DEFAULT_SERVER_PORT;
|
|
1070
|
+
const serverCode = buildServerCode({
|
|
1071
|
+
port,
|
|
1072
|
+
sandboxContext: {
|
|
1073
|
+
provider: paths.provider,
|
|
1074
|
+
homeDir: paths.homeDir,
|
|
1075
|
+
workDir: paths.workDir,
|
|
1076
|
+
agentDir: paths.agentDir,
|
|
1077
|
+
ioDir: paths.ioDir,
|
|
1078
|
+
inputJson: paths.inputJson,
|
|
1079
|
+
outputJson: paths.outputJson
|
|
1080
|
+
},
|
|
1081
|
+
maxDurationSeconds: this.maxDuration
|
|
1082
|
+
});
|
|
1083
|
+
await sandbox.writeFile(`${paths.agentDir}/server.mjs`, serverCode);
|
|
1084
|
+
}
|
|
712
1085
|
if (collectedExternals.size > 0) {
|
|
713
1086
|
const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
|
|
714
1087
|
const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
|
|
@@ -735,6 +1108,55 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
735
1108
|
throw new DeploymentError(details);
|
|
736
1109
|
}
|
|
737
1110
|
}
|
|
1111
|
+
if (this.mode === "server") {
|
|
1112
|
+
if (!sandbox.startDetachedCommand || !sandbox.getPreviewLink) {
|
|
1113
|
+
throw new DeploymentError(
|
|
1114
|
+
"Server-mode agents require a sandbox provider that supports detached sessions and preview URLs (currently Daytona only)."
|
|
1115
|
+
);
|
|
1116
|
+
}
|
|
1117
|
+
const port = this._server?.port ?? DEFAULT_SERVER_PORT;
|
|
1118
|
+
const authToken = generateAuthToken();
|
|
1119
|
+
const { sessionId, commandId } = await sandbox.startDetachedCommand("node server.mjs", {
|
|
1120
|
+
cwd: paths.agentDir,
|
|
1121
|
+
envs: {
|
|
1122
|
+
...this.sandboxEnv,
|
|
1123
|
+
NECKBEARD_SERVER_PORT: String(port),
|
|
1124
|
+
NECKBEARD_SERVER_TOKEN: authToken
|
|
1125
|
+
}
|
|
1126
|
+
});
|
|
1127
|
+
const { url: previewUrl, token: previewToken } = await sandbox.getPreviewLink(port);
|
|
1128
|
+
const serverUrl = `${previewUrl.replace(/\/$/, "")}/invoke`;
|
|
1129
|
+
const healthUrl = `${previewUrl.replace(/\/$/, "")}/health`;
|
|
1130
|
+
try {
|
|
1131
|
+
await waitForServerHealthy(healthUrl, authToken, previewToken);
|
|
1132
|
+
} catch (err) {
|
|
1133
|
+
const baseMessage = err instanceof Error ? err.message : String(err);
|
|
1134
|
+
let logs = "";
|
|
1135
|
+
if (commandId && sandbox.readSessionLogs) {
|
|
1136
|
+
const captured = await sandbox.readSessionLogs(sessionId, commandId);
|
|
1137
|
+
const parts = [];
|
|
1138
|
+
if (captured.stdout.trim()) parts.push(`stdout:
|
|
1139
|
+
${captured.stdout}`);
|
|
1140
|
+
if (captured.stderr.trim()) parts.push(`stderr:
|
|
1141
|
+
${captured.stderr}`);
|
|
1142
|
+
if (parts.length > 0) {
|
|
1143
|
+
logs = `
|
|
1144
|
+
--- server logs ---
|
|
1145
|
+
${parts.join("\n\n")}`;
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
1149
|
+
}
|
|
1150
|
+
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
1151
|
+
this._serverRuntime = { sessionId, serverUrl, authToken, previewToken };
|
|
1152
|
+
return {
|
|
1153
|
+
mode: "server",
|
|
1154
|
+
sandboxId: sandbox.id,
|
|
1155
|
+
serverUrl,
|
|
1156
|
+
authToken,
|
|
1157
|
+
previewToken
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
738
1160
|
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
739
1161
|
return sandbox.id;
|
|
740
1162
|
}
|
|
@@ -762,6 +1184,15 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
762
1184
|
*/
|
|
763
1185
|
async run(input, options) {
|
|
764
1186
|
const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1187
|
+
if (this.mode === "server") {
|
|
1188
|
+
return {
|
|
1189
|
+
ok: false,
|
|
1190
|
+
executionId,
|
|
1191
|
+
error: new ExecutionError(
|
|
1192
|
+
"run() is not available on server-mode agents. Use agent.invoke() instead."
|
|
1193
|
+
)
|
|
1194
|
+
};
|
|
1195
|
+
}
|
|
765
1196
|
const sandboxId = options?.sandboxId ?? this._sandboxId;
|
|
766
1197
|
if (!sandboxId) {
|
|
767
1198
|
return {
|
|
@@ -823,11 +1254,48 @@ Stdout: ${capturedStdout}` : ""
|
|
|
823
1254
|
err.stack = output.error.stack;
|
|
824
1255
|
return { ok: false, executionId, error: err };
|
|
825
1256
|
}
|
|
826
|
-
|
|
1257
|
+
const validated = this.outputSchema ? this.outputSchema.parse(output.output) : output.output;
|
|
1258
|
+
return { ok: true, executionId, output: validated };
|
|
827
1259
|
} catch (err) {
|
|
828
1260
|
return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
|
|
829
1261
|
}
|
|
830
1262
|
}
|
|
1263
|
+
/**
|
|
1264
|
+
* Invoke a server-mode agent. Streams the agent's emitted frames back as an
|
|
1265
|
+
* async iterator as the handler runs. Only valid for agents constructed with
|
|
1266
|
+
* `server: {...}` config; one-shot agents should use `run()` instead.
|
|
1267
|
+
*
|
|
1268
|
+
* Requires the agent to be deployed via `deploy()` (returns `serverUrl` and
|
|
1269
|
+
* `authToken`) — callers must persist those values and pass them on each
|
|
1270
|
+
* invocation. Deploy is not yet implemented for server mode; this method
|
|
1271
|
+
* currently throws `ConfigurationError` if `serverUrl` is not supplied.
|
|
1272
|
+
*/
|
|
1273
|
+
async *invoke(input, options) {
|
|
1274
|
+
if (this.mode !== "server") {
|
|
1275
|
+
throw new ConfigurationError(
|
|
1276
|
+
"invoke() is only available on server-mode agents. Use agent.run() for one-shot agents."
|
|
1277
|
+
);
|
|
1278
|
+
}
|
|
1279
|
+
const serverUrl = options?.serverUrl ?? this._serverRuntime?.serverUrl;
|
|
1280
|
+
const authToken = options?.authToken ?? this._serverRuntime?.authToken;
|
|
1281
|
+
const previewToken = options?.previewToken ?? this._serverRuntime?.previewToken;
|
|
1282
|
+
if (!serverUrl || !authToken) {
|
|
1283
|
+
throw new ConfigurationError(
|
|
1284
|
+
"Agent not deployed in server mode. Call agent.deploy() first and pass the returned serverUrl and authToken to invoke()."
|
|
1285
|
+
);
|
|
1286
|
+
}
|
|
1287
|
+
const urlWithPreviewToken = previewToken ? `${serverUrl}${serverUrl.includes("?") ? "&" : "?"}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(previewToken)}` : serverUrl;
|
|
1288
|
+
const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
|
|
1289
|
+
const validated = this.inputSchema.parse(input);
|
|
1290
|
+
for await (const frame of invokeServer2(validated, {
|
|
1291
|
+
serverUrl: urlWithPreviewToken,
|
|
1292
|
+
authToken,
|
|
1293
|
+
frameSchema: this.frameSchema,
|
|
1294
|
+
signal: options?.signal
|
|
1295
|
+
})) {
|
|
1296
|
+
yield frame;
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
831
1299
|
};
|
|
832
1300
|
// Annotate the CommonJS export names for ESM import in node:
|
|
833
1301
|
0 && (module.exports = {
|