agent-neckbeard 1.1.4 → 1.1.6
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 +502 -6
- package/dist/index.d.cts +107 -10
- package/dist/index.d.ts +107 -10
- package/dist/index.js +398 -6
- package/dist/invoke-client-Y3NPRFEE.js +88 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -3,6 +3,168 @@ 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
|
|
6
168
|
function readPackageJson(path) {
|
|
7
169
|
return JSON.parse(readFileSync(path, "utf8"));
|
|
8
170
|
}
|
|
@@ -17,6 +179,9 @@ var NODE_TARGET = "node20";
|
|
|
17
179
|
var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
|
|
18
180
|
var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
|
|
19
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;
|
|
20
185
|
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
21
186
|
var E2B_SANDBOX_HOME = "/home/user";
|
|
22
187
|
var NeckbeardError = class extends Error {
|
|
@@ -53,6 +218,36 @@ var ConfigurationError = class extends NeckbeardError {
|
|
|
53
218
|
}
|
|
54
219
|
};
|
|
55
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
|
+
}
|
|
56
251
|
function requireEnv(name) {
|
|
57
252
|
const value = process.env[name];
|
|
58
253
|
if (!value) {
|
|
@@ -269,6 +464,34 @@ async function createDaytonaHandle(sandbox) {
|
|
|
269
464
|
stderr: ""
|
|
270
465
|
};
|
|
271
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
|
+
},
|
|
272
495
|
destroy: () => sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS))
|
|
273
496
|
};
|
|
274
497
|
}
|
|
@@ -329,15 +552,23 @@ var Agent = class {
|
|
|
329
552
|
provider;
|
|
330
553
|
template;
|
|
331
554
|
inputSchema;
|
|
555
|
+
/** Only populated for one-shot agents; undefined for server-mode. */
|
|
332
556
|
outputSchema;
|
|
557
|
+
/** Only populated for server-mode agents; undefined for one-shot. */
|
|
558
|
+
frameSchema;
|
|
559
|
+
mode;
|
|
333
560
|
maxDuration;
|
|
334
561
|
dependencies;
|
|
335
562
|
files;
|
|
336
563
|
claudeDir;
|
|
337
564
|
envs;
|
|
338
565
|
build;
|
|
339
|
-
/** @internal Used by the sandbox runner
|
|
566
|
+
/** @internal Used by the sandbox runner for one-shot agents. */
|
|
340
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;
|
|
341
572
|
_sourceFile;
|
|
342
573
|
_sandboxId;
|
|
343
574
|
constructor(config) {
|
|
@@ -345,15 +576,22 @@ var Agent = class {
|
|
|
345
576
|
this.provider = config.sandbox.provider;
|
|
346
577
|
this.template = config.sandbox.template;
|
|
347
578
|
this.inputSchema = config.inputSchema;
|
|
348
|
-
this.outputSchema = config.outputSchema;
|
|
349
579
|
this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
|
|
350
|
-
this._run = config.run;
|
|
351
580
|
this._sourceFile = getCallerFile();
|
|
352
581
|
this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
|
|
353
582
|
this.files = config.files ?? [];
|
|
354
583
|
this.claudeDir = config.claudeDir;
|
|
355
584
|
this.envs = config.envs ?? {};
|
|
356
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
|
+
}
|
|
357
595
|
}
|
|
358
596
|
get sandboxId() {
|
|
359
597
|
return this._sandboxId;
|
|
@@ -521,8 +759,45 @@ try {
|
|
|
521
759
|
* await agent.kill(id);
|
|
522
760
|
* ```
|
|
523
761
|
*/
|
|
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
|
+
*/
|
|
524
767
|
async deploy(options) {
|
|
525
|
-
if (
|
|
768
|
+
if (this.mode !== "one-shot") {
|
|
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;
|
|
789
|
+
}
|
|
790
|
+
async _deploy(options) {
|
|
791
|
+
if (!options?.fresh && this._sandboxId && this.mode === "one-shot") return this._sandboxId;
|
|
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
|
+
}
|
|
526
801
|
const esbuild = await getEsbuild();
|
|
527
802
|
const externalPatterns = Array.from(
|
|
528
803
|
/* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
|
|
@@ -565,6 +840,10 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
565
840
|
this.outputSchema = config.outputSchema;
|
|
566
841
|
this.maxDuration = config.maxDuration ?? 300;
|
|
567
842
|
this._run = config.run;
|
|
843
|
+
if (config.server) {
|
|
844
|
+
this._server = config.server;
|
|
845
|
+
this.frameSchema = config.server.frameSchema;
|
|
846
|
+
}
|
|
568
847
|
}
|
|
569
848
|
}
|
|
570
849
|
`,
|
|
@@ -667,7 +946,25 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
667
946
|
}
|
|
668
947
|
}
|
|
669
948
|
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
670
|
-
|
|
949
|
+
if (this.mode === "one-shot") {
|
|
950
|
+
await sandbox.writeFile(paths.runnerModule, runnerCode);
|
|
951
|
+
} else if (this._server) {
|
|
952
|
+
const port = this._server.port ?? DEFAULT_SERVER_PORT;
|
|
953
|
+
const serverCode = buildServerCode({
|
|
954
|
+
port,
|
|
955
|
+
sandboxContext: {
|
|
956
|
+
provider: paths.provider,
|
|
957
|
+
homeDir: paths.homeDir,
|
|
958
|
+
workDir: paths.workDir,
|
|
959
|
+
agentDir: paths.agentDir,
|
|
960
|
+
ioDir: paths.ioDir,
|
|
961
|
+
inputJson: paths.inputJson,
|
|
962
|
+
outputJson: paths.outputJson
|
|
963
|
+
},
|
|
964
|
+
maxDurationSeconds: this.maxDuration
|
|
965
|
+
});
|
|
966
|
+
await sandbox.writeFile(`${paths.agentDir}/server.mjs`, serverCode);
|
|
967
|
+
}
|
|
671
968
|
if (collectedExternals.size > 0) {
|
|
672
969
|
const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
|
|
673
970
|
const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
|
|
@@ -694,6 +991,55 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
694
991
|
throw new DeploymentError(details);
|
|
695
992
|
}
|
|
696
993
|
}
|
|
994
|
+
if (this.mode === "server") {
|
|
995
|
+
if (!sandbox.startDetachedCommand || !sandbox.getPreviewLink) {
|
|
996
|
+
throw new DeploymentError(
|
|
997
|
+
"Server-mode agents require a sandbox provider that supports detached sessions and preview URLs (currently Daytona only)."
|
|
998
|
+
);
|
|
999
|
+
}
|
|
1000
|
+
const port = this._server?.port ?? DEFAULT_SERVER_PORT;
|
|
1001
|
+
const authToken = generateAuthToken();
|
|
1002
|
+
const { sessionId, commandId } = await sandbox.startDetachedCommand("node server.mjs", {
|
|
1003
|
+
cwd: paths.agentDir,
|
|
1004
|
+
envs: {
|
|
1005
|
+
...this.sandboxEnv,
|
|
1006
|
+
NECKBEARD_SERVER_PORT: String(port),
|
|
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:
|
|
1022
|
+
${captured.stdout}`);
|
|
1023
|
+
if (captured.stderr.trim()) parts.push(`stderr:
|
|
1024
|
+
${captured.stderr}`);
|
|
1025
|
+
if (parts.length > 0) {
|
|
1026
|
+
logs = `
|
|
1027
|
+
--- server logs ---
|
|
1028
|
+
${parts.join("\n\n")}`;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
1032
|
+
}
|
|
1033
|
+
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
1034
|
+
this._serverRuntime = { sessionId, serverUrl, authToken, previewToken };
|
|
1035
|
+
return {
|
|
1036
|
+
mode: "server",
|
|
1037
|
+
sandboxId: sandbox.id,
|
|
1038
|
+
serverUrl,
|
|
1039
|
+
authToken,
|
|
1040
|
+
previewToken
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
697
1043
|
if (!options?.fresh) this._sandboxId = sandbox.id;
|
|
698
1044
|
return sandbox.id;
|
|
699
1045
|
}
|
|
@@ -721,6 +1067,15 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
721
1067
|
*/
|
|
722
1068
|
async run(input, options) {
|
|
723
1069
|
const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1070
|
+
if (this.mode === "server") {
|
|
1071
|
+
return {
|
|
1072
|
+
ok: false,
|
|
1073
|
+
executionId,
|
|
1074
|
+
error: new ExecutionError(
|
|
1075
|
+
"run() is not available on server-mode agents. Use agent.invoke() instead."
|
|
1076
|
+
)
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
724
1079
|
const sandboxId = options?.sandboxId ?? this._sandboxId;
|
|
725
1080
|
if (!sandboxId) {
|
|
726
1081
|
return {
|
|
@@ -782,11 +1137,48 @@ Stdout: ${capturedStdout}` : ""
|
|
|
782
1137
|
err.stack = output.error.stack;
|
|
783
1138
|
return { ok: false, executionId, error: err };
|
|
784
1139
|
}
|
|
785
|
-
|
|
1140
|
+
const validated = this.outputSchema ? this.outputSchema.parse(output.output) : output.output;
|
|
1141
|
+
return { ok: true, executionId, output: validated };
|
|
786
1142
|
} catch (err) {
|
|
787
1143
|
return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
|
|
788
1144
|
}
|
|
789
1145
|
}
|
|
1146
|
+
/**
|
|
1147
|
+
* Invoke a server-mode agent. Streams the agent's emitted frames back as an
|
|
1148
|
+
* async iterator as the handler runs. Only valid for agents constructed with
|
|
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.
|
|
1155
|
+
*/
|
|
1156
|
+
async *invoke(input, options) {
|
|
1157
|
+
if (this.mode !== "server") {
|
|
1158
|
+
throw new ConfigurationError(
|
|
1159
|
+
"invoke() is only available on server-mode agents. Use agent.run() for one-shot agents."
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
const serverUrl = options?.serverUrl ?? this._serverRuntime?.serverUrl;
|
|
1163
|
+
const authToken = options?.authToken ?? this._serverRuntime?.authToken;
|
|
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");
|
|
1172
|
+
const validated = this.inputSchema.parse(input);
|
|
1173
|
+
for await (const frame of invokeServer(validated, {
|
|
1174
|
+
serverUrl: urlWithPreviewToken,
|
|
1175
|
+
authToken,
|
|
1176
|
+
frameSchema: this.frameSchema,
|
|
1177
|
+
signal: options?.signal
|
|
1178
|
+
})) {
|
|
1179
|
+
yield frame;
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
790
1182
|
};
|
|
791
1183
|
export {
|
|
792
1184
|
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
|
+
};
|