agent-neckbeard 1.1.7 → 1.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +114 -53
- package/dist/index.cjs +360 -475
- package/dist/index.d.cts +49 -75
- package/dist/index.d.ts +49 -75
- package/dist/index.js +310 -465
- package/dist/{invoke-client-Y3NPRFEE.js → invoke-client-WYMFPR3F.js} +45 -11
- package/dist/runtime/server.js +163 -0
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -3,168 +3,6 @@ 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 { 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
6
|
function readPackageJson(path) {
|
|
169
7
|
return JSON.parse(readFileSync(path, "utf8"));
|
|
170
8
|
}
|
|
@@ -181,6 +19,7 @@ var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
|
|
|
181
19
|
var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
|
|
182
20
|
var DEFAULT_SERVER_PORT = 3e3;
|
|
183
21
|
var SERVER_HEALTH_TIMEOUT_MS = 12e4;
|
|
22
|
+
var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
|
|
184
23
|
var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
|
|
185
24
|
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
186
25
|
var E2B_SANDBOX_HOME = "/home/user";
|
|
@@ -221,17 +60,30 @@ var DEFAULT_DEPENDENCIES = {};
|
|
|
221
60
|
function isServerAgentConfig(config) {
|
|
222
61
|
return "server" in config && config.server !== void 0;
|
|
223
62
|
}
|
|
224
|
-
function
|
|
225
|
-
return
|
|
63
|
+
function getTrafficToken(descriptor) {
|
|
64
|
+
return descriptor.trafficToken;
|
|
65
|
+
}
|
|
66
|
+
function appendTrafficTokenToUrl(url, descriptor) {
|
|
67
|
+
const token = getTrafficToken(descriptor);
|
|
68
|
+
if (descriptor.provider !== "daytona" || !token) return url;
|
|
69
|
+
const separator = url.includes("?") ? "&" : "?";
|
|
70
|
+
return `${url}${separator}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(token)}`;
|
|
71
|
+
}
|
|
72
|
+
function trafficTokenHeaders(descriptor) {
|
|
73
|
+
const token = getTrafficToken(descriptor);
|
|
74
|
+
if (descriptor.provider === "e2b" && token) {
|
|
75
|
+
return { "e2b-traffic-access-token": token };
|
|
76
|
+
}
|
|
77
|
+
return {};
|
|
226
78
|
}
|
|
227
|
-
async function waitForServerHealthy(healthUrl,
|
|
228
|
-
const deadline = Date.now() +
|
|
79
|
+
async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HEALTH_TIMEOUT_MS) {
|
|
80
|
+
const deadline = Date.now() + timeoutMs;
|
|
229
81
|
let lastError;
|
|
230
|
-
const urlWithToken =
|
|
82
|
+
const urlWithToken = appendTrafficTokenToUrl(healthUrl, descriptor);
|
|
231
83
|
while (Date.now() < deadline) {
|
|
232
84
|
try {
|
|
233
85
|
const response = await fetch(urlWithToken, {
|
|
234
|
-
headers:
|
|
86
|
+
headers: trafficTokenHeaders(descriptor)
|
|
235
87
|
});
|
|
236
88
|
if (response.ok) {
|
|
237
89
|
await response.text().catch(() => void 0);
|
|
@@ -245,7 +97,7 @@ async function waitForServerHealthy(healthUrl, authToken, previewToken) {
|
|
|
245
97
|
}
|
|
246
98
|
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
247
99
|
throw new DeploymentError(
|
|
248
|
-
`Server did not become healthy at ${healthUrl} within ${
|
|
100
|
+
`Server did not become healthy at ${healthUrl} within ${timeoutMs}ms: ${message}`
|
|
249
101
|
);
|
|
250
102
|
}
|
|
251
103
|
function requireEnv(name) {
|
|
@@ -374,7 +226,8 @@ function createSandboxPaths(provider, homeDir, workDir) {
|
|
|
374
226
|
inputJson: `${ioDir}/input.json`,
|
|
375
227
|
outputJson: `${ioDir}/output.json`,
|
|
376
228
|
agentModule: `${agentDir}/agent.mjs`,
|
|
377
|
-
|
|
229
|
+
serverModule: `${agentDir}/server.mjs`,
|
|
230
|
+
serverConfig: `${agentDir}/server-config.json`,
|
|
378
231
|
claudeDir: `${agentDir}/.claude`,
|
|
379
232
|
packageJson: `${agentDir}/package.json`
|
|
380
233
|
};
|
|
@@ -432,6 +285,34 @@ function createE2bHandle(sandbox) {
|
|
|
432
285
|
const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
|
|
433
286
|
return runE2bCommand(sandbox, command, options);
|
|
434
287
|
},
|
|
288
|
+
startDetachedCommand: async (cmd, options) => {
|
|
289
|
+
const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
|
|
290
|
+
const handle = await sandbox.commands.run(command, {
|
|
291
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS,
|
|
292
|
+
envs: options.envs,
|
|
293
|
+
background: true
|
|
294
|
+
});
|
|
295
|
+
return { sessionId: `e2b:${handle.pid}`, commandId: String(handle.pid) };
|
|
296
|
+
},
|
|
297
|
+
readSessionLogs: async (_sessionId, commandId) => {
|
|
298
|
+
if (!sandbox.commands.connect) return { stdout: "", stderr: "" };
|
|
299
|
+
try {
|
|
300
|
+
const handle = await sandbox.commands.connect(Number(commandId));
|
|
301
|
+
return { stdout: handle.stdout ?? "", stderr: handle.stderr ?? "" };
|
|
302
|
+
} catch {
|
|
303
|
+
return { stdout: "", stderr: "" };
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
stopSession: async (sessionId) => {
|
|
307
|
+
const pid = Number(sessionId.replace(/^e2b:/, ""));
|
|
308
|
+
if (Number.isFinite(pid)) {
|
|
309
|
+
await sandbox.commands.kill?.(pid);
|
|
310
|
+
}
|
|
311
|
+
},
|
|
312
|
+
getServerEndpoint: async (port) => ({
|
|
313
|
+
url: `https://${sandbox.getHost(port)}`,
|
|
314
|
+
trafficToken: sandbox.trafficAccessToken
|
|
315
|
+
}),
|
|
435
316
|
destroy: () => sandbox.kill()
|
|
436
317
|
};
|
|
437
318
|
}
|
|
@@ -489,8 +370,9 @@ async function createDaytonaHandle(sandbox) {
|
|
|
489
370
|
stopSession: async (sessionId) => {
|
|
490
371
|
await sandbox.process.deleteSession(sessionId);
|
|
491
372
|
},
|
|
492
|
-
|
|
493
|
-
|
|
373
|
+
getServerEndpoint: async (port) => {
|
|
374
|
+
const preview = await sandbox.getPreviewLink(port);
|
|
375
|
+
return { url: preview.url, trafficToken: preview.token };
|
|
494
376
|
},
|
|
495
377
|
destroy: () => sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS))
|
|
496
378
|
};
|
|
@@ -547,14 +429,40 @@ function readDirectoryRecursively(dirPath) {
|
|
|
547
429
|
walkDir(dirPath);
|
|
548
430
|
return files;
|
|
549
431
|
}
|
|
432
|
+
function getRuntimeServerEntryPoint() {
|
|
433
|
+
const currentFile = getCurrentModuleFile();
|
|
434
|
+
const currentDir = currentFile ? dirname(currentFile) : process.cwd();
|
|
435
|
+
const candidates = [
|
|
436
|
+
join(currentDir, "runtime/server.ts"),
|
|
437
|
+
join(currentDir, "runtime/server.js"),
|
|
438
|
+
join(currentDir, "runtime/server.mjs")
|
|
439
|
+
];
|
|
440
|
+
const entry = candidates.find((candidate) => existsSync(candidate));
|
|
441
|
+
if (!entry) {
|
|
442
|
+
throw new DeploymentError(
|
|
443
|
+
`Could not find neckbeard runtime server entry. Tried: ${candidates.join(", ")}`
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
return entry;
|
|
447
|
+
}
|
|
448
|
+
function getCurrentModuleFile() {
|
|
449
|
+
const stack = new Error().stack?.split("\n") ?? [];
|
|
450
|
+
for (const line of stack.slice(1)) {
|
|
451
|
+
const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
|
|
452
|
+
if (!match) continue;
|
|
453
|
+
const normalized = normalizeStackFramePath(match[1]);
|
|
454
|
+
if (normalized && existsSync(normalized)) return normalized;
|
|
455
|
+
}
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
550
458
|
var Agent = class {
|
|
551
459
|
sandbox;
|
|
552
460
|
provider;
|
|
553
461
|
template;
|
|
554
462
|
inputSchema;
|
|
555
|
-
/** Only populated for
|
|
463
|
+
/** Only populated for run-output agents; undefined for streaming agents. */
|
|
556
464
|
outputSchema;
|
|
557
|
-
/** Only populated for
|
|
465
|
+
/** Only populated for streaming agents; undefined for run-output agents. */
|
|
558
466
|
frameSchema;
|
|
559
467
|
mode;
|
|
560
468
|
maxDuration;
|
|
@@ -563,14 +471,14 @@ var Agent = class {
|
|
|
563
471
|
claudeDir;
|
|
564
472
|
envs;
|
|
565
473
|
build;
|
|
566
|
-
/** @internal Used by the sandbox
|
|
474
|
+
/** @internal Used by the in-sandbox server for run-output agents. */
|
|
567
475
|
_run;
|
|
568
|
-
/** @internal Used by the in-sandbox
|
|
476
|
+
/** @internal Used by the in-sandbox server for streaming agents. */
|
|
569
477
|
_server;
|
|
570
|
-
/** @internal Runtime state populated by deploy()
|
|
478
|
+
/** @internal Runtime state populated by deploy(). */
|
|
571
479
|
_serverRuntime;
|
|
572
|
-
_sourceFile;
|
|
573
480
|
_sandboxId;
|
|
481
|
+
_sourceFile;
|
|
574
482
|
constructor(config) {
|
|
575
483
|
this.sandbox = config.sandbox;
|
|
576
484
|
this.provider = config.sandbox.provider;
|
|
@@ -584,17 +492,17 @@ var Agent = class {
|
|
|
584
492
|
this.envs = config.envs ?? {};
|
|
585
493
|
this.build = config.build ?? {};
|
|
586
494
|
if (isServerAgentConfig(config)) {
|
|
587
|
-
this.mode = "
|
|
495
|
+
this.mode = "stream";
|
|
588
496
|
this._server = config.server;
|
|
589
497
|
this.frameSchema = config.server.frameSchema;
|
|
590
498
|
} else {
|
|
591
|
-
this.mode = "
|
|
499
|
+
this.mode = "run";
|
|
592
500
|
this._run = config.run;
|
|
593
501
|
this.outputSchema = config.outputSchema;
|
|
594
502
|
}
|
|
595
503
|
}
|
|
596
504
|
get sandboxId() {
|
|
597
|
-
return this._sandboxId;
|
|
505
|
+
return this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
598
506
|
}
|
|
599
507
|
get sandboxEnv() {
|
|
600
508
|
return filterDefinedEnvs(this.envs);
|
|
@@ -616,7 +524,11 @@ var Agent = class {
|
|
|
616
524
|
}
|
|
617
525
|
const apiKey = requireEnv("E2B_API_KEY");
|
|
618
526
|
const { Sandbox } = await getE2b();
|
|
619
|
-
const sandbox = await Sandbox.create(this.template, {
|
|
527
|
+
const sandbox = await Sandbox.create(this.template, {
|
|
528
|
+
apiKey,
|
|
529
|
+
envs: this.sandboxEnv,
|
|
530
|
+
network: { allowPublicTraffic: false }
|
|
531
|
+
});
|
|
620
532
|
return createE2bHandle(sandbox);
|
|
621
533
|
}
|
|
622
534
|
async connectSandboxHandle(sandboxId) {
|
|
@@ -639,80 +551,97 @@ var Agent = class {
|
|
|
639
551
|
const sandbox = await Sandbox.connect(sandboxId, { apiKey });
|
|
640
552
|
return createE2bHandle(sandbox);
|
|
641
553
|
}
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
554
|
+
async readRuntimeServerConfig(sandbox) {
|
|
555
|
+
try {
|
|
556
|
+
return JSON.parse(await sandbox.readFile(sandbox.paths.serverConfig));
|
|
557
|
+
} catch {
|
|
558
|
+
return void 0;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
async createRuntimeConnection(sandbox, port) {
|
|
562
|
+
if (!sandbox.getServerEndpoint) {
|
|
563
|
+
throw new DeploymentError(
|
|
564
|
+
"Persistent agents require a sandbox provider that supports public port endpoints."
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
const endpoint = await sandbox.getServerEndpoint(port);
|
|
568
|
+
const baseServerUrl = endpoint.url.replace(/\/$/, "");
|
|
569
|
+
return {
|
|
570
|
+
provider: this.provider,
|
|
571
|
+
sandboxId: sandbox.id,
|
|
572
|
+
serverUrl: `${baseServerUrl}/invoke`,
|
|
573
|
+
trafficToken: endpoint.trafficToken
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
healthUrlFor(connection) {
|
|
577
|
+
const url = new URL(connection.serverUrl);
|
|
578
|
+
url.pathname = url.pathname.replace(/\/invoke$/, "/health");
|
|
579
|
+
url.search = "";
|
|
580
|
+
return url.toString();
|
|
581
|
+
}
|
|
582
|
+
async startRuntimeServer(sandbox) {
|
|
583
|
+
if (!sandbox.startDetachedCommand) {
|
|
584
|
+
throw new DeploymentError(
|
|
585
|
+
"Persistent agents require a sandbox provider that supports background commands."
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
return sandbox.startDetachedCommand("node server.mjs", {
|
|
589
|
+
cwd: sandbox.paths.agentDir,
|
|
590
|
+
envs: this.sandboxEnv
|
|
651
591
|
});
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
try {
|
|
674
|
-
|
|
675
|
-
} catch (
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
const
|
|
681
|
-
if (
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
};
|
|
698
|
-
|
|
699
|
-
try {
|
|
700
|
-
const validated = agent.inputSchema.parse(input);
|
|
701
|
-
const output = await agent._run(validated, ctx);
|
|
702
|
-
const validatedOutput = agent.outputSchema.parse(output);
|
|
703
|
-
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: true, output: validatedOutput }));
|
|
704
|
-
} catch (error) {
|
|
705
|
-
writeFileSync(OUTPUT_FILE, JSON.stringify({ success: false, error: { message: error.message, stack: error.stack } }));
|
|
706
|
-
}
|
|
707
|
-
`;
|
|
592
|
+
}
|
|
593
|
+
async resolveRuntimeConnection(sandboxId) {
|
|
594
|
+
const targetId = sandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
595
|
+
if (!targetId) {
|
|
596
|
+
throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
|
|
597
|
+
}
|
|
598
|
+
if (!sandboxId && this._serverRuntime?.connection.sandboxId === targetId) {
|
|
599
|
+
return this._serverRuntime.connection;
|
|
600
|
+
}
|
|
601
|
+
const sandbox = await this.connectSandboxHandle(targetId);
|
|
602
|
+
const serverConfig = await this.readRuntimeServerConfig(sandbox);
|
|
603
|
+
const port = serverConfig?.port ?? this._server?.port ?? DEFAULT_SERVER_PORT;
|
|
604
|
+
const connection = await this.createRuntimeConnection(sandbox, port);
|
|
605
|
+
const healthUrl = this.healthUrlFor(connection);
|
|
606
|
+
try {
|
|
607
|
+
await waitForServerHealthy(healthUrl, connection, SERVER_RECONNECT_HEALTH_TIMEOUT_MS);
|
|
608
|
+
this._serverRuntime = { connection };
|
|
609
|
+
this._sandboxId = targetId;
|
|
610
|
+
return connection;
|
|
611
|
+
} catch {
|
|
612
|
+
const { sessionId, commandId } = await this.startRuntimeServer(sandbox);
|
|
613
|
+
try {
|
|
614
|
+
await waitForServerHealthy(healthUrl, connection);
|
|
615
|
+
} catch (error) {
|
|
616
|
+
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
617
|
+
let logs = "";
|
|
618
|
+
if (commandId && sandbox.readSessionLogs) {
|
|
619
|
+
const captured = await sandbox.readSessionLogs(sessionId, commandId);
|
|
620
|
+
const parts = [];
|
|
621
|
+
if (captured.stdout.trim()) parts.push(`stdout:
|
|
622
|
+
${captured.stdout}`);
|
|
623
|
+
if (captured.stderr.trim()) parts.push(`stderr:
|
|
624
|
+
${captured.stderr}`);
|
|
625
|
+
if (parts.length > 0) {
|
|
626
|
+
logs = `
|
|
627
|
+
--- server logs ---
|
|
628
|
+
${parts.join("\n\n")}`;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
632
|
+
}
|
|
633
|
+
this._serverRuntime = { sessionId, commandId, connection };
|
|
634
|
+
this._sandboxId = targetId;
|
|
635
|
+
return connection;
|
|
636
|
+
}
|
|
708
637
|
}
|
|
709
638
|
/**
|
|
710
|
-
* Kills the current sandbox and resets the cached
|
|
639
|
+
* Kills the current sandbox and resets the cached runtime.
|
|
711
640
|
*
|
|
712
641
|
* Use this to clean up sandbox resources after a run, especially when
|
|
713
642
|
* running multiple evaluations that each need their own sandbox.
|
|
714
643
|
*
|
|
715
|
-
* @param
|
|
644
|
+
* @param target - Optional sandbox ID to kill. Defaults to the cached sandbox.
|
|
716
645
|
*
|
|
717
646
|
* @example
|
|
718
647
|
* ```typescript
|
|
@@ -721,29 +650,36 @@ try {
|
|
|
721
650
|
* await agent.kill(sandboxId);
|
|
722
651
|
* ```
|
|
723
652
|
*/
|
|
724
|
-
async kill(
|
|
725
|
-
const targetId = sandboxId ?? this._sandboxId;
|
|
653
|
+
async kill(target) {
|
|
654
|
+
const targetId = target ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
726
655
|
if (!targetId) return;
|
|
727
656
|
try {
|
|
728
657
|
const sandbox = await this.connectSandboxHandle(targetId);
|
|
658
|
+
if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.sessionId && sandbox.stopSession) {
|
|
659
|
+
await sandbox.stopSession(this._serverRuntime.sessionId).catch(() => void 0);
|
|
660
|
+
}
|
|
729
661
|
await sandbox.destroy();
|
|
730
662
|
} catch {
|
|
731
663
|
}
|
|
732
664
|
if (targetId === this._sandboxId) {
|
|
733
665
|
this._sandboxId = void 0;
|
|
734
666
|
}
|
|
667
|
+
if (targetId === this._serverRuntime?.connection.sandboxId) {
|
|
668
|
+
this._serverRuntime = void 0;
|
|
669
|
+
}
|
|
735
670
|
}
|
|
736
671
|
/**
|
|
737
672
|
* Deploys the agent to a sandbox provider.
|
|
738
673
|
*
|
|
739
674
|
* This method bundles the agent code using esbuild, creates a new sandbox,
|
|
740
675
|
* installs any specified OS dependencies, downloads configured files, and
|
|
741
|
-
* uploads the agent code
|
|
676
|
+
* uploads the agent and runtime server code, then starts a long-running HTTP
|
|
677
|
+
* server inside the sandbox.
|
|
742
678
|
*
|
|
743
679
|
* @param options.fresh - When true, always creates a new sandbox without caching.
|
|
744
680
|
* Useful for concurrent evaluations where each run needs its own sandbox.
|
|
745
681
|
* The returned sandbox ID won't be stored on the instance.
|
|
746
|
-
* @returns The sandbox ID
|
|
682
|
+
* @returns The sandbox ID. Persist this ID when another host process should reuse the sandbox.
|
|
747
683
|
* @throws {ConfigurationError} If the selected provider credentials are not set
|
|
748
684
|
* @throws {DeploymentError} If sandbox creation, dependency installation, or file upload fails
|
|
749
685
|
*
|
|
@@ -754,50 +690,16 @@ try {
|
|
|
754
690
|
* console.log(`Deployed to sandbox: ${sandboxId}`);
|
|
755
691
|
*
|
|
756
692
|
* // For concurrent evals: each call gets its own sandbox
|
|
757
|
-
* const
|
|
758
|
-
* const result = await agent.run(input, { sandboxId
|
|
759
|
-
* await agent.kill(
|
|
693
|
+
* const sandboxId = await agent.deploy({ fresh: true });
|
|
694
|
+
* const result = await agent.run(input, { sandboxId });
|
|
695
|
+
* await agent.kill(sandboxId);
|
|
760
696
|
* ```
|
|
761
697
|
*/
|
|
762
|
-
/**
|
|
763
|
-
* Deploy a one-shot agent. Throws if called on a server-mode agent; use
|
|
764
|
-
* `deployServer()` for those. Returns the sandbox id so callers can pass it
|
|
765
|
-
* to `run(input, { sandboxId })`.
|
|
766
|
-
*/
|
|
767
698
|
async deploy(options) {
|
|
768
|
-
|
|
769
|
-
throw new ConfigurationError(
|
|
770
|
-
"deploy() is only available on one-shot agents. Use agent.deployServer() for server-mode agents."
|
|
771
|
-
);
|
|
772
|
-
}
|
|
773
|
-
const result = await this._deploy(options);
|
|
774
|
-
return result;
|
|
775
|
-
}
|
|
776
|
-
/**
|
|
777
|
-
* Deploy a server-mode agent. Throws if called on a one-shot agent; use
|
|
778
|
-
* `deploy()` for those. Returns the sandbox id, public server URL, bearer
|
|
779
|
-
* token, and Daytona preview token that `invoke()` needs to stream.
|
|
780
|
-
*/
|
|
781
|
-
async deployServer(options) {
|
|
782
|
-
if (this.mode !== "server") {
|
|
783
|
-
throw new ConfigurationError(
|
|
784
|
-
"deployServer() is only available on server-mode agents. Use agent.deploy() for one-shot agents."
|
|
785
|
-
);
|
|
786
|
-
}
|
|
787
|
-
const result = await this._deploy(options);
|
|
788
|
-
return result;
|
|
699
|
+
return this._deploy(options);
|
|
789
700
|
}
|
|
790
701
|
async _deploy(options) {
|
|
791
|
-
if (!options?.fresh && this.
|
|
792
|
-
if (!options?.fresh && this._sandboxId && this._serverRuntime) {
|
|
793
|
-
return {
|
|
794
|
-
mode: "server",
|
|
795
|
-
sandboxId: this._sandboxId,
|
|
796
|
-
serverUrl: this._serverRuntime.serverUrl,
|
|
797
|
-
authToken: this._serverRuntime.authToken,
|
|
798
|
-
previewToken: this._serverRuntime.previewToken
|
|
799
|
-
};
|
|
800
|
-
}
|
|
702
|
+
if (!options?.fresh && this._serverRuntime) return this._serverRuntime.connection.sandboxId;
|
|
801
703
|
const esbuild = await getEsbuild();
|
|
802
704
|
const externalPatterns = Array.from(
|
|
803
705
|
/* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
|
|
@@ -815,7 +717,7 @@ try {
|
|
|
815
717
|
minify: true,
|
|
816
718
|
keepNames: true,
|
|
817
719
|
treeShaking: false,
|
|
818
|
-
// Preserve exports for the
|
|
720
|
+
// Preserve exports for the runtime server to import
|
|
819
721
|
banner: {
|
|
820
722
|
js: `import { fileURLToPath as __neckbeard_fileURLToPath } from 'node:url';
|
|
821
723
|
import { dirname as __neckbeard_dirname } from 'node:path';
|
|
@@ -870,9 +772,18 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
870
772
|
}
|
|
871
773
|
}]
|
|
872
774
|
});
|
|
775
|
+
const serverResult = await esbuild.build({
|
|
776
|
+
entryPoints: [getRuntimeServerEntryPoint()],
|
|
777
|
+
bundle: true,
|
|
778
|
+
platform: "node",
|
|
779
|
+
target: NODE_TARGET,
|
|
780
|
+
format: "esm",
|
|
781
|
+
write: false,
|
|
782
|
+
minify: false,
|
|
783
|
+
external: ["./agent.mjs"]
|
|
784
|
+
});
|
|
873
785
|
const sandbox = await this.createSandboxHandle();
|
|
874
786
|
const { paths } = sandbox;
|
|
875
|
-
const runnerCode = this.buildRunnerCode(paths);
|
|
876
787
|
await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
|
|
877
788
|
timeoutMs: QUICK_COMMAND_TIMEOUT_MS
|
|
878
789
|
});
|
|
@@ -946,114 +857,86 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
946
857
|
}
|
|
947
858
|
}
|
|
948
859
|
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
maxDurationSeconds: this.maxDuration
|
|
965
|
-
});
|
|
966
|
-
await sandbox.writeFile(`${paths.agentDir}/server.mjs`, serverCode);
|
|
967
|
-
}
|
|
860
|
+
await sandbox.writeFile(paths.serverModule, serverResult.outputFiles[0].text);
|
|
861
|
+
const serverConfig = {
|
|
862
|
+
port: this._server?.port ?? DEFAULT_SERVER_PORT,
|
|
863
|
+
maxDurationMs: this.maxDuration * 1e3,
|
|
864
|
+
sandboxContext: {
|
|
865
|
+
provider: paths.provider,
|
|
866
|
+
homeDir: paths.homeDir,
|
|
867
|
+
workDir: paths.workDir,
|
|
868
|
+
agentDir: paths.agentDir,
|
|
869
|
+
ioDir: paths.ioDir,
|
|
870
|
+
inputJson: paths.inputJson,
|
|
871
|
+
outputJson: paths.outputJson
|
|
872
|
+
}
|
|
873
|
+
};
|
|
874
|
+
await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
|
|
968
875
|
if (collectedExternals.size > 0) {
|
|
969
876
|
const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
|
|
970
877
|
const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
|
|
971
|
-
if (Object.keys(dependencies).length
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
].filter(Boolean).join("\n");
|
|
991
|
-
throw new DeploymentError(details);
|
|
878
|
+
if (Object.keys(dependencies).length > 0) {
|
|
879
|
+
const pkgJson = JSON.stringify({
|
|
880
|
+
name: "agent-sandbox",
|
|
881
|
+
type: "module",
|
|
882
|
+
dependencies
|
|
883
|
+
});
|
|
884
|
+
await sandbox.writeFile(paths.packageJson, pkgJson);
|
|
885
|
+
const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
|
|
886
|
+
cwd: paths.agentDir,
|
|
887
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
|
|
888
|
+
});
|
|
889
|
+
if (installResult.exitCode !== 0) {
|
|
890
|
+
const details = [
|
|
891
|
+
`Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
|
|
892
|
+
installResult.stderr ? `stderr: ${installResult.stderr}` : "",
|
|
893
|
+
installResult.stdout ? `stdout: ${installResult.stdout}` : ""
|
|
894
|
+
].filter(Boolean).join("\n");
|
|
895
|
+
throw new DeploymentError(details);
|
|
896
|
+
}
|
|
992
897
|
}
|
|
993
898
|
}
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
const
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
NECKBEARD_SERVER_TOKEN: authToken
|
|
1008
|
-
}
|
|
1009
|
-
});
|
|
1010
|
-
const { url: previewUrl, token: previewToken } = await sandbox.getPreviewLink(port);
|
|
1011
|
-
const serverUrl = `${previewUrl.replace(/\/$/, "")}/invoke`;
|
|
1012
|
-
const healthUrl = `${previewUrl.replace(/\/$/, "")}/health`;
|
|
1013
|
-
try {
|
|
1014
|
-
await waitForServerHealthy(healthUrl, authToken, previewToken);
|
|
1015
|
-
} catch (err) {
|
|
1016
|
-
const baseMessage = err instanceof Error ? err.message : String(err);
|
|
1017
|
-
let logs = "";
|
|
1018
|
-
if (commandId && sandbox.readSessionLogs) {
|
|
1019
|
-
const captured = await sandbox.readSessionLogs(sessionId, commandId);
|
|
1020
|
-
const parts = [];
|
|
1021
|
-
if (captured.stdout.trim()) parts.push(`stdout:
|
|
899
|
+
const port = serverConfig.port;
|
|
900
|
+
const { sessionId, commandId } = await this.startRuntimeServer(sandbox);
|
|
901
|
+
const connection = await this.createRuntimeConnection(sandbox, port);
|
|
902
|
+
const healthUrl = this.healthUrlFor(connection);
|
|
903
|
+
try {
|
|
904
|
+
await waitForServerHealthy(healthUrl, connection);
|
|
905
|
+
} catch (err) {
|
|
906
|
+
const baseMessage = err instanceof Error ? err.message : String(err);
|
|
907
|
+
let logs = "";
|
|
908
|
+
if (commandId && sandbox.readSessionLogs) {
|
|
909
|
+
const captured = await sandbox.readSessionLogs(sessionId, commandId);
|
|
910
|
+
const parts = [];
|
|
911
|
+
if (captured.stdout.trim()) parts.push(`stdout:
|
|
1022
912
|
${captured.stdout}`);
|
|
1023
|
-
|
|
913
|
+
if (captured.stderr.trim()) parts.push(`stderr:
|
|
1024
914
|
${captured.stderr}`);
|
|
1025
|
-
|
|
1026
|
-
|
|
915
|
+
if (parts.length > 0) {
|
|
916
|
+
logs = `
|
|
1027
917
|
--- server logs ---
|
|
1028
918
|
${parts.join("\n\n")}`;
|
|
1029
|
-
}
|
|
1030
919
|
}
|
|
1031
|
-
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
1032
920
|
}
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
serverUrl,
|
|
1039
|
-
authToken,
|
|
1040
|
-
previewToken
|
|
1041
|
-
};
|
|
921
|
+
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
922
|
+
}
|
|
923
|
+
if (!options?.fresh) {
|
|
924
|
+
this._sandboxId = sandbox.id;
|
|
925
|
+
this._serverRuntime = { sessionId, commandId, connection };
|
|
1042
926
|
}
|
|
1043
|
-
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
1044
927
|
return sandbox.id;
|
|
1045
928
|
}
|
|
1046
929
|
/**
|
|
1047
930
|
* Executes the agent with the given input.
|
|
1048
931
|
*
|
|
1049
|
-
* The agent must be deployed before calling this method, or a
|
|
1050
|
-
* be provided in the options. Input is validated against the input
|
|
1051
|
-
* then
|
|
1052
|
-
*
|
|
932
|
+
* The agent must be deployed before calling this method, or a sandbox ID
|
|
933
|
+
* must be provided in the options. Input is validated against the input
|
|
934
|
+
* schema, then POSTed to the in-sandbox server. Output is validated against
|
|
935
|
+
* the output schema before being returned.
|
|
1053
936
|
*
|
|
1054
937
|
* @param input - The input data for the agent, must conform to inputSchema
|
|
1055
938
|
* @param options - Optional configuration for this run
|
|
1056
|
-
* @param options.sandboxId - Sandbox ID to use, overrides the
|
|
939
|
+
* @param options.sandboxId - Sandbox ID to use, overrides the cached sandbox
|
|
1057
940
|
* @returns A result object indicating success or failure with output or error
|
|
1058
941
|
*
|
|
1059
942
|
* @example
|
|
@@ -1061,122 +944,84 @@ ${parts.join("\n\n")}`;
|
|
|
1061
944
|
* // Using deployed sandbox
|
|
1062
945
|
* const result = await agent.run({ prompt: 'Hello, world!' });
|
|
1063
946
|
*
|
|
1064
|
-
* //
|
|
1065
|
-
* const result = await agent.run({ prompt: 'Hello!' }, { sandboxId
|
|
947
|
+
* // Reconnecting from another process
|
|
948
|
+
* const result = await agent.run({ prompt: 'Hello!' }, { sandboxId });
|
|
1066
949
|
* ```
|
|
1067
950
|
*/
|
|
1068
951
|
async run(input, options) {
|
|
1069
952
|
const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1070
|
-
if (this.mode
|
|
953
|
+
if (this.mode !== "run") {
|
|
1071
954
|
return {
|
|
1072
955
|
ok: false,
|
|
1073
956
|
executionId,
|
|
1074
957
|
error: new ExecutionError(
|
|
1075
|
-
"run() is
|
|
958
|
+
"run() is only available on agents configured with a run handler. Use agent.invoke() for streaming agents."
|
|
1076
959
|
)
|
|
1077
960
|
};
|
|
1078
961
|
}
|
|
1079
|
-
const sandboxId = options?.sandboxId ?? this._sandboxId;
|
|
1080
|
-
if (!sandboxId) {
|
|
1081
|
-
return {
|
|
1082
|
-
ok: false,
|
|
1083
|
-
executionId,
|
|
1084
|
-
error: new ExecutionError("Agent not deployed. Call agent.deploy() first or pass sandboxId to run().")
|
|
1085
|
-
};
|
|
1086
|
-
}
|
|
1087
962
|
try {
|
|
963
|
+
const connection = await this.resolveRuntimeConnection(options?.sandboxId);
|
|
1088
964
|
const validatedInput = this.inputSchema.parse(input);
|
|
1089
|
-
const
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
965
|
+
const { invokeServer } = await import("./invoke-client-WYMFPR3F.js");
|
|
966
|
+
let output;
|
|
967
|
+
let sawOutput = false;
|
|
968
|
+
for await (const event of invokeServer(validatedInput, {
|
|
969
|
+
serverUrl: connection.serverUrl,
|
|
970
|
+
provider: connection.provider,
|
|
971
|
+
trafficToken: getTrafficToken(connection),
|
|
972
|
+
invocationId: executionId,
|
|
973
|
+
signal: AbortSignal.timeout(this.maxDuration * 1e3 + 5e3)
|
|
974
|
+
})) {
|
|
975
|
+
if (event.kind === "error") {
|
|
976
|
+
const err = new ExecutionError(event.error.message);
|
|
977
|
+
err.stack = event.error.stack;
|
|
978
|
+
return { ok: false, executionId, error: err };
|
|
1103
979
|
}
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
try {
|
|
1108
|
-
const resultJson = await sandbox.readFile(paths.outputJson);
|
|
1109
|
-
const parsed = JSON.parse(resultJson);
|
|
1110
|
-
if (!parsed.success && parsed.error) {
|
|
1111
|
-
resultError = `
|
|
1112
|
-
Result: ${parsed.error.message}`;
|
|
1113
|
-
if (parsed.error.stack) resultError += `
|
|
1114
|
-
Stack: ${parsed.error.stack}`;
|
|
1115
|
-
}
|
|
1116
|
-
} catch {
|
|
980
|
+
if (event.kind === "output") {
|
|
981
|
+
output = event.output;
|
|
982
|
+
sawOutput = true;
|
|
1117
983
|
}
|
|
1118
|
-
const errorDetails = [
|
|
1119
|
-
`Agent failed with exit code ${result.exitCode}`,
|
|
1120
|
-
result.stderr ? `Stderr: ${result.stderr}` : "",
|
|
1121
|
-
capturedStderr ? `Captured stderr: ${capturedStderr}` : "",
|
|
1122
|
-
capturedStdout ? `Stdout: ${capturedStdout}` : "",
|
|
1123
|
-
resultError
|
|
1124
|
-
].filter(Boolean).join("\n");
|
|
1125
|
-
return { ok: false, executionId, error: new ExecutionError(errorDetails) };
|
|
1126
984
|
}
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
capturedStdout ? `
|
|
1134
|
-
Stdout: ${capturedStdout}` : ""
|
|
1135
|
-
].filter(Boolean).join("");
|
|
1136
|
-
const err = new ExecutionError(errorDetails);
|
|
1137
|
-
err.stack = output.error.stack;
|
|
1138
|
-
return { ok: false, executionId, error: err };
|
|
985
|
+
if (!sawOutput) {
|
|
986
|
+
return {
|
|
987
|
+
ok: false,
|
|
988
|
+
executionId,
|
|
989
|
+
error: new ExecutionError("Agent server completed without returning output.")
|
|
990
|
+
};
|
|
1139
991
|
}
|
|
1140
|
-
const validated = this.outputSchema ? this.outputSchema.parse(output
|
|
992
|
+
const validated = this.outputSchema ? this.outputSchema.parse(output) : output;
|
|
1141
993
|
return { ok: true, executionId, output: validated };
|
|
1142
994
|
} catch (err) {
|
|
1143
995
|
return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
|
|
1144
996
|
}
|
|
1145
997
|
}
|
|
1146
998
|
/**
|
|
1147
|
-
* Invoke a
|
|
1148
|
-
*
|
|
1149
|
-
* `server: {...}` config; one-shot agents should use `run()` instead.
|
|
1150
|
-
*
|
|
1151
|
-
* Requires the agent to be deployed via `deploy()` (returns `serverUrl` and
|
|
1152
|
-
* `authToken`) — callers must persist those values and pass them on each
|
|
1153
|
-
* invocation. Deploy is not yet implemented for server mode; this method
|
|
1154
|
-
* currently throws `ConfigurationError` if `serverUrl` is not supplied.
|
|
999
|
+
* Invoke a streaming agent. Streams user frames emitted by the in-sandbox
|
|
1000
|
+
* handler as an async iterator.
|
|
1155
1001
|
*/
|
|
1156
1002
|
async *invoke(input, options) {
|
|
1157
|
-
if (this.mode !== "
|
|
1003
|
+
if (this.mode !== "stream") {
|
|
1158
1004
|
throw new ConfigurationError(
|
|
1159
|
-
"invoke() is only available on server
|
|
1005
|
+
"invoke() is only available on agents configured with server.handler. Use agent.run() for run-output agents."
|
|
1160
1006
|
);
|
|
1161
1007
|
}
|
|
1162
|
-
const
|
|
1163
|
-
const
|
|
1164
|
-
const previewToken = options?.previewToken ?? this._serverRuntime?.previewToken;
|
|
1165
|
-
if (!serverUrl || !authToken) {
|
|
1166
|
-
throw new ConfigurationError(
|
|
1167
|
-
"Agent not deployed in server mode. Call agent.deploy() first and pass the returned serverUrl and authToken to invoke()."
|
|
1168
|
-
);
|
|
1169
|
-
}
|
|
1170
|
-
const urlWithPreviewToken = previewToken ? `${serverUrl}${serverUrl.includes("?") ? "&" : "?"}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(previewToken)}` : serverUrl;
|
|
1171
|
-
const { invokeServer } = await import("./invoke-client-Y3NPRFEE.js");
|
|
1008
|
+
const connection = await this.resolveRuntimeConnection(options?.sandboxId);
|
|
1009
|
+
const { invokeServer } = await import("./invoke-client-WYMFPR3F.js");
|
|
1172
1010
|
const validated = this.inputSchema.parse(input);
|
|
1173
1011
|
for await (const frame of invokeServer(validated, {
|
|
1174
|
-
serverUrl:
|
|
1175
|
-
|
|
1012
|
+
serverUrl: connection.serverUrl,
|
|
1013
|
+
provider: connection.provider,
|
|
1014
|
+
trafficToken: getTrafficToken(connection),
|
|
1176
1015
|
frameSchema: this.frameSchema,
|
|
1177
1016
|
signal: options?.signal
|
|
1178
1017
|
})) {
|
|
1179
|
-
|
|
1018
|
+
if (frame.kind === "frame") {
|
|
1019
|
+
yield frame.data;
|
|
1020
|
+
} else if (frame.kind === "error") {
|
|
1021
|
+
const err = new ExecutionError(frame.error.message);
|
|
1022
|
+
err.stack = frame.error.stack;
|
|
1023
|
+
throw err;
|
|
1024
|
+
}
|
|
1180
1025
|
}
|
|
1181
1026
|
}
|
|
1182
1027
|
};
|