agent-neckbeard 1.1.29 → 1.1.30
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/CHANGELOG.md +7 -0
- package/README.md +25 -27
- package/dist/archil.d.ts +73 -0
- package/dist/archil.js +673 -0
- package/dist/build.cjs +129 -5315
- package/dist/build.d.cts +9 -5
- package/dist/build.d.ts +9 -5
- package/dist/build.js +4 -6
- package/dist/{chunk-BPXEIXPM.js → chunk-FHNQ5DNA.js} +3264 -564
- package/dist/{chunk-FSBTLBB5.js → chunk-I5GIWADK.js} +29 -7
- package/dist/chunk-I5NULOJP.js +129 -0
- package/dist/chunk-PKUGXECR.js +13 -0
- package/dist/chunk-QA4L7ZI2.js +72 -0
- package/dist/{chunk-KG6SJM74.js → chunk-VHBDBB3N.js} +8 -5
- package/dist/cli.cjs +124 -5309
- package/dist/cli.js +7 -8
- package/dist/define-gdmBe9RA.d.ts +227 -0
- package/dist/durable.d.ts +53 -0
- package/dist/durable.js +92 -0
- package/dist/index.cjs +720 -988
- package/dist/index.d.cts +139 -87
- package/dist/index.d.ts +139 -87
- package/dist/index.js +12 -11
- package/dist/inside.d.ts +15 -0
- package/dist/inside.js +530 -0
- package/dist/{invoke-client-P2CPBYTF.js → invoke-client-QB2NTZ3L.js} +1 -2
- package/dist/pi-watch-legacy.d.ts +4503 -0
- package/dist/serve.cjs +9 -439
- package/dist/serve.d.cts +14 -1
- package/dist/serve.d.ts +14 -1
- package/dist/serve.js +3 -5
- package/docs/AGENT.md +81 -77
- package/docs/DAYTONA.md +2 -0
- package/docs/DOCKER.md +0 -1
- package/docs/E2B.md +1 -1
- package/docs/LEGACY.md +1 -8
- package/docs/MODAL.md +1 -1
- package/package.json +57 -23
- package/types/pi-watch.d.cts +68 -0
- package/dist/chunk-33IXN6MM.js +0 -21
- package/dist/chunk-6P5I7ZCH.js +0 -2552
- package/dist/chunk-YFG4EKZM.js +0 -508
- package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +0 -77
- package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +0 -77
- package/dist/serve-Du2NCz9_.d.cts +0 -111
- package/dist/serve-Du2NCz9_.d.ts +0 -111
- package/dist/supervisor.cjs +0 -5731
- package/dist/supervisor.d.cts +0 -482
- package/dist/supervisor.d.ts +0 -482
- package/dist/supervisor.js +0 -3187
- package/docs/SUPERVISOR.md +0 -258
package/dist/index.cjs
CHANGED
|
@@ -89,9 +89,9 @@ var init_protocol = __esm({
|
|
|
89
89
|
});
|
|
90
90
|
|
|
91
91
|
// src/sse-framing.ts
|
|
92
|
-
async function* decodeSseStream(
|
|
92
|
+
async function* decodeSseStream(chunks2, options = {}) {
|
|
93
93
|
let buffer = "";
|
|
94
|
-
for await (const chunk of
|
|
94
|
+
for await (const chunk of chunks2) {
|
|
95
95
|
buffer += chunk;
|
|
96
96
|
let boundary = buffer.indexOf("\n\n");
|
|
97
97
|
while (boundary !== -1) {
|
|
@@ -106,6 +106,7 @@ async function* decodeSseStream(chunks) {
|
|
|
106
106
|
}
|
|
107
107
|
const tail = buffer.trim();
|
|
108
108
|
if (tail.length > 0) {
|
|
109
|
+
if (options.requireTerminator) throw new IncompleteSseFrameError("Stream ended during an SSE frame.");
|
|
109
110
|
let parsed;
|
|
110
111
|
try {
|
|
111
112
|
parsed = parseFrame(tail);
|
|
@@ -128,8 +129,8 @@ function parseFrame(raw) {
|
|
|
128
129
|
try {
|
|
129
130
|
return JSON.parse(dataLines.join("\n"));
|
|
130
131
|
} catch (error) {
|
|
131
|
-
const
|
|
132
|
-
throw new Error(`Malformed SSE data frame: ${
|
|
132
|
+
const message2 = error instanceof Error ? error.message : String(error);
|
|
133
|
+
throw new Error(`Malformed SSE data frame: ${message2}`);
|
|
133
134
|
}
|
|
134
135
|
}
|
|
135
136
|
var IncompleteSseFrameError;
|
|
@@ -185,20 +186,20 @@ function validateHarnessEvent(rawEvent, invocationId) {
|
|
|
185
186
|
);
|
|
186
187
|
}
|
|
187
188
|
}
|
|
188
|
-
async function* invokeServer(
|
|
189
|
+
async function* invokeServer(input2, options) {
|
|
189
190
|
const fetchImpl = options.fetch ?? fetch;
|
|
190
191
|
const invocationId = options.invocationId ?? createInvocationId();
|
|
191
192
|
const response = await fetchImpl(buildRequestUrl(options), {
|
|
192
193
|
method: "POST",
|
|
193
194
|
headers: buildRequestHeaders(options),
|
|
194
|
-
body: JSON.stringify({ invocationId, input }),
|
|
195
|
+
body: JSON.stringify({ invocationId, input: input2 }),
|
|
195
196
|
signal: options.signal
|
|
196
197
|
});
|
|
197
198
|
if (!response.ok) {
|
|
198
|
-
const
|
|
199
|
+
const text2 = await response.text().catch(() => "");
|
|
199
200
|
throw new InvokeHttpError(
|
|
200
201
|
response.status,
|
|
201
|
-
`Server returned ${response.status}${
|
|
202
|
+
`Server returned ${response.status}${text2 ? `: ${text2}` : ""}`
|
|
202
203
|
);
|
|
203
204
|
}
|
|
204
205
|
if (!response.body) {
|
|
@@ -206,7 +207,7 @@ async function* invokeServer(input, options) {
|
|
|
206
207
|
}
|
|
207
208
|
const reader = response.body.getReader();
|
|
208
209
|
const decoder = new TextDecoder();
|
|
209
|
-
async function*
|
|
210
|
+
async function* chunks2() {
|
|
210
211
|
try {
|
|
211
212
|
while (true) {
|
|
212
213
|
const { value, done } = await reader.read();
|
|
@@ -220,7 +221,7 @@ async function* invokeServer(input, options) {
|
|
|
220
221
|
}
|
|
221
222
|
}
|
|
222
223
|
}
|
|
223
|
-
for await (const rawEvent of decodeSseStream(
|
|
224
|
+
for await (const rawEvent of decodeSseStream(chunks2())) {
|
|
224
225
|
validateHarnessEvent(rawEvent, invocationId);
|
|
225
226
|
if (rawEvent.kind === "frame" && options.frameSchema) {
|
|
226
227
|
yield {
|
|
@@ -239,8 +240,8 @@ var init_invoke_client = __esm({
|
|
|
239
240
|
init_sse_framing();
|
|
240
241
|
init_protocol();
|
|
241
242
|
InvokeHttpError = class extends Error {
|
|
242
|
-
constructor(status,
|
|
243
|
-
super(
|
|
243
|
+
constructor(status, message2) {
|
|
244
|
+
super(message2);
|
|
244
245
|
this.status = status;
|
|
245
246
|
this.name = "InvokeHttpError";
|
|
246
247
|
}
|
|
@@ -255,19 +256,21 @@ __export(src_exports, {
|
|
|
255
256
|
ConfigurationError: () => ConfigurationError,
|
|
256
257
|
DEFAULT_DEPENDENCIES: () => DEFAULT_DEPENDENCIES,
|
|
257
258
|
DefinedAgent: () => DefinedAgent,
|
|
259
|
+
DefinedHostAgent: () => DefinedHostAgent,
|
|
258
260
|
DeploymentError: () => DeploymentError,
|
|
259
261
|
ExecutionError: () => ExecutionError,
|
|
260
262
|
LegacyBundledAgent: () => LegacyBundledAgent,
|
|
261
263
|
NeckbeardError: () => NeckbeardError,
|
|
264
|
+
RemoteAdmissionRejected: () => RemoteAdmissionRejected,
|
|
265
|
+
RemoteSubmissionNotFound: () => RemoteSubmissionNotFound,
|
|
262
266
|
RuntimeBusyError: () => RuntimeBusyError,
|
|
263
267
|
SKILLS_DIR: () => SKILLS_DIR,
|
|
264
268
|
SandboxClient: () => SandboxClient,
|
|
269
|
+
SandboxGoneError: () => SandboxGoneError,
|
|
265
270
|
TURN_PROTOCOL_VERSION: () => TURN_PROTOCOL_VERSION,
|
|
266
|
-
TurnLostError: () => TurnLostError,
|
|
267
271
|
ValidationError: () => ValidationError,
|
|
268
272
|
defineAgent: () => defineAgent,
|
|
269
273
|
destroyProviderSandbox: () => destroyProviderSandbox,
|
|
270
|
-
getPiTurnResult: () => getPiTurnResult,
|
|
271
274
|
isDefinedAgent: () => isDefinedAgent,
|
|
272
275
|
normalizeStackFramePath: () => normalizeStackFramePath,
|
|
273
276
|
resolveAgentSourceFile: () => resolveAgentSourceFile,
|
|
@@ -486,8 +489,8 @@ var AttachedAgentSessionImpl = class {
|
|
|
486
489
|
get closed() {
|
|
487
490
|
return this.isClosed;
|
|
488
491
|
}
|
|
489
|
-
prompt(
|
|
490
|
-
return this.runTurn(
|
|
492
|
+
prompt(input2) {
|
|
493
|
+
return this.runTurn(input2);
|
|
491
494
|
}
|
|
492
495
|
async stop(reason = "attached_session_stopped") {
|
|
493
496
|
await this.stopActiveTurn(reason);
|
|
@@ -495,7 +498,7 @@ var AttachedAgentSessionImpl = class {
|
|
|
495
498
|
close() {
|
|
496
499
|
return this.closeWithReason("attached_session_closed");
|
|
497
500
|
}
|
|
498
|
-
async *runTurn(
|
|
501
|
+
async *runTurn(input2) {
|
|
499
502
|
if (this.isClosed || this.lifetime.signal.aborted) {
|
|
500
503
|
throw this.configurationError("Attached session is closed.");
|
|
501
504
|
}
|
|
@@ -504,7 +507,7 @@ var AttachedAgentSessionImpl = class {
|
|
|
504
507
|
}
|
|
505
508
|
const controller = new AbortController();
|
|
506
509
|
const linked = linkAbortSignals([this.lifetime.signal, controller.signal]);
|
|
507
|
-
const iterator = this.runPrompt(
|
|
510
|
+
const iterator = this.runPrompt(input2, linked.signal);
|
|
508
511
|
const turn = {
|
|
509
512
|
controller,
|
|
510
513
|
iterator,
|
|
@@ -618,29 +621,29 @@ function paxPathRecord(path2) {
|
|
|
618
621
|
return import_node_buffer.Buffer.from(`${length}${body}`);
|
|
619
622
|
}
|
|
620
623
|
async function createTarGz(entries, mtime = Math.floor(Date.now() / 1e3)) {
|
|
621
|
-
const
|
|
622
|
-
for (const
|
|
623
|
-
const isDirectory =
|
|
624
|
-
const path2 = isDirectory ? `${
|
|
625
|
-
const size =
|
|
624
|
+
const chunks2 = [];
|
|
625
|
+
for (const entry2 of entries) {
|
|
626
|
+
const isDirectory = entry2.content === void 0;
|
|
627
|
+
const path2 = isDirectory ? `${entry2.path.replace(/\/+$/u, "")}/` : entry2.path;
|
|
628
|
+
const size = entry2.content?.byteLength ?? 0;
|
|
626
629
|
const type = isDirectory ? "5" : "0";
|
|
627
630
|
const mode = isDirectory ? 493 : 420;
|
|
628
631
|
const split = splitUstarPath(path2);
|
|
629
632
|
if (split) {
|
|
630
|
-
|
|
633
|
+
chunks2.push(header({ ...split, mode, size, mtime, type }));
|
|
631
634
|
} else {
|
|
632
635
|
const record = paxPathRecord(path2);
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
+
chunks2.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
|
|
637
|
+
chunks2.push(record, padding(record.byteLength));
|
|
638
|
+
chunks2.push(header({ name: path2.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
|
|
636
639
|
}
|
|
637
|
-
if (
|
|
638
|
-
|
|
639
|
-
|
|
640
|
+
if (entry2.content) {
|
|
641
|
+
chunks2.push(import_node_buffer.Buffer.from(entry2.content.buffer, entry2.content.byteOffset, entry2.content.byteLength));
|
|
642
|
+
chunks2.push(padding(size));
|
|
640
643
|
}
|
|
641
644
|
}
|
|
642
|
-
|
|
643
|
-
return gzipAsync(import_node_buffer.Buffer.concat(
|
|
645
|
+
chunks2.push(import_node_buffer.Buffer.alloc(BLOCK_SIZE * 2));
|
|
646
|
+
return gzipAsync(import_node_buffer.Buffer.concat(chunks2));
|
|
644
647
|
}
|
|
645
648
|
|
|
646
649
|
// src/providers/detached-process.ts
|
|
@@ -3049,7 +3052,7 @@ function validateProviderCommand(label, command, options) {
|
|
|
3049
3052
|
if (options.cwd !== void 0 && (typeof options.cwd !== "string" || !options.cwd.startsWith("/") || options.cwd.includes("\0")) || options.onStdout !== void 0 && typeof options.onStdout !== "function" || options.onStderr !== void 0 && typeof options.onStderr !== "function") {
|
|
3050
3053
|
throw new Error(`${label} command cwd must be absolute and output callbacks must be functions.`);
|
|
3051
3054
|
}
|
|
3052
|
-
if (options.envs !== void 0) validateProviderEnvs(label, options.envs, (
|
|
3055
|
+
if (options.envs !== void 0) validateProviderEnvs(label, options.envs, (message2) => new Error(message2));
|
|
3053
3056
|
}
|
|
3054
3057
|
|
|
3055
3058
|
// src/providers/daytona.ts
|
|
@@ -3242,11 +3245,21 @@ function settleOperation(operation, options = {}) {
|
|
|
3242
3245
|
);
|
|
3243
3246
|
});
|
|
3244
3247
|
}
|
|
3245
|
-
function
|
|
3248
|
+
function untilAborted(operation, signal) {
|
|
3249
|
+
if (signal?.aborted) return Promise.reject(abortError(signal));
|
|
3250
|
+
return settleOperation(operation, signal ? { abort: { signal, createError: () => abortError(signal) } } : {});
|
|
3251
|
+
}
|
|
3252
|
+
function abortError(signal) {
|
|
3253
|
+
if (signal.reason instanceof Error) return signal.reason;
|
|
3254
|
+
const error = new Error("Operation aborted.");
|
|
3255
|
+
error.name = "AbortError";
|
|
3256
|
+
return error;
|
|
3257
|
+
}
|
|
3258
|
+
function withTimeout(task, timeoutMs, message2) {
|
|
3246
3259
|
return settleOperation(() => task, {
|
|
3247
3260
|
timeout: {
|
|
3248
3261
|
timeoutMs,
|
|
3249
|
-
createError: () => new Error(
|
|
3262
|
+
createError: () => new Error(message2)
|
|
3250
3263
|
}
|
|
3251
3264
|
});
|
|
3252
3265
|
}
|
|
@@ -3466,7 +3479,7 @@ function getModalSdk() {
|
|
|
3466
3479
|
var MODAL_DEFAULT_TEMPLATE = "node:22-bookworm";
|
|
3467
3480
|
var MODAL_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
|
|
3468
3481
|
function parseModalAllowList(value) {
|
|
3469
|
-
return (value ?? "").split(",").map((
|
|
3482
|
+
return (value ?? "").split(",").map((entry2) => entry2.trim()).filter(Boolean);
|
|
3470
3483
|
}
|
|
3471
3484
|
function modalNetworkOptions(options) {
|
|
3472
3485
|
if (options.networkBlockAll) return { blockNetwork: true };
|
|
@@ -3497,7 +3510,7 @@ function validateModalOptions(options, mode, failure) {
|
|
|
3497
3510
|
throw failure("Modal networkBlockAll must be a boolean.");
|
|
3498
3511
|
}
|
|
3499
3512
|
for (const [key, value] of [["networkAllowList", networkAllowList], ["domainAllowList", domainAllowList]]) {
|
|
3500
|
-
if (value !== void 0 && (typeof value !== "string" || parseModalAllowList(value).some((
|
|
3513
|
+
if (value !== void 0 && (typeof value !== "string" || parseModalAllowList(value).some((entry2) => /[\s\0]/u.test(entry2)))) {
|
|
3501
3514
|
throw failure(`Modal ${key} must be a comma-separated string without whitespace or null bytes in entries.`);
|
|
3502
3515
|
}
|
|
3503
3516
|
}
|
|
@@ -3544,8 +3557,8 @@ async function sharedClient(credentials) {
|
|
|
3544
3557
|
return client;
|
|
3545
3558
|
}
|
|
3546
3559
|
var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
3547
|
-
constructor(
|
|
3548
|
-
this.id =
|
|
3560
|
+
constructor(id2, client, failure) {
|
|
3561
|
+
this.id = id2;
|
|
3549
3562
|
this.client = client;
|
|
3550
3563
|
this.detachedProcesses = new DetachedProcessController({
|
|
3551
3564
|
provider: "modal",
|
|
@@ -3585,7 +3598,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3585
3598
|
const network = modalNetworkOptions(options);
|
|
3586
3599
|
const template = options.template ?? MODAL_DEFAULT_TEMPLATE;
|
|
3587
3600
|
const registryImage = options.registrySecret === void 0 ? client.images.fromRegistry(template) : client.images.fromRegistry(template, await client.secrets.fromName(options.registrySecret));
|
|
3588
|
-
const
|
|
3601
|
+
const image2 = options.command ? registryImage : registryImage.dockerfileCommands([
|
|
3589
3602
|
"USER root",
|
|
3590
3603
|
"RUN apt-get update && apt-get install -y --no-install-recommends bash python3 util-linux coreutils sudo curl ca-certificates && rm -rf /var/lib/apt/lists/*",
|
|
3591
3604
|
// The runtime starts with a fixed PATH, so images with Node elsewhere (say nvm) need links.
|
|
@@ -3594,7 +3607,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3594
3607
|
...network.outboundDomainAllowlist ? ["RUN find /etc/apt -name '*.list' -o -name '*.sources' | xargs -r sed -i 's|http://|https://|g'"] : [],
|
|
3595
3608
|
"WORKDIR /root"
|
|
3596
3609
|
]);
|
|
3597
|
-
sandbox = await client.sandboxes.create(app,
|
|
3610
|
+
sandbox = await client.sandboxes.create(app, image2, {
|
|
3598
3611
|
...network,
|
|
3599
3612
|
...options.regions ? { regions: options.regions } : {},
|
|
3600
3613
|
timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
|
|
@@ -3602,7 +3615,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3602
3615
|
memoryMiB: options.memoryMiB,
|
|
3603
3616
|
...options.command ? { command: options.command } : { workdir: "/root" },
|
|
3604
3617
|
env: Object.fromEntries(Object.entries(options.envs ?? {}).filter(
|
|
3605
|
-
(
|
|
3618
|
+
(entry2) => entry2[1] !== void 0
|
|
3606
3619
|
))
|
|
3607
3620
|
// No tunnels: all HTTP access requires a port-scoped Connect Token.
|
|
3608
3621
|
});
|
|
@@ -3620,16 +3633,22 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3620
3633
|
});
|
|
3621
3634
|
await new _ModalSandboxHandle(options.sandboxId, client, failure).destroy();
|
|
3622
3635
|
}
|
|
3623
|
-
|
|
3636
|
+
/** With `gone`, a sandbox Modal reports finished or unknown throws that failure instead. */
|
|
3637
|
+
static async connect(options, failure, gone) {
|
|
3624
3638
|
const client = await sharedClient({
|
|
3625
3639
|
tokenId: options.tokenId,
|
|
3626
3640
|
tokenSecret: options.tokenSecret,
|
|
3627
3641
|
environment: options.environment
|
|
3628
3642
|
});
|
|
3629
3643
|
const handle = new _ModalSandboxHandle(options.sandboxId, client, failure);
|
|
3630
|
-
|
|
3631
|
-
|
|
3632
|
-
|
|
3644
|
+
try {
|
|
3645
|
+
await handle.use(async (sandbox) => {
|
|
3646
|
+
if (await sandbox.poll() !== null) throw (gone ?? failure)("Modal sandbox is no longer running.");
|
|
3647
|
+
});
|
|
3648
|
+
} catch (error) {
|
|
3649
|
+
if (gone && isModalNotFound(error)) throw gone(`Modal sandbox ${options.sandboxId} does not exist.`, error);
|
|
3650
|
+
throw error;
|
|
3651
|
+
}
|
|
3633
3652
|
return handle;
|
|
3634
3653
|
}
|
|
3635
3654
|
async use(operation, timeoutMs) {
|
|
@@ -3727,54 +3746,55 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3727
3746
|
});
|
|
3728
3747
|
}
|
|
3729
3748
|
async destroy() {
|
|
3730
|
-
const { NotFoundError } = getModalSdk();
|
|
3731
3749
|
try {
|
|
3732
3750
|
await this.use(async (sandbox) => {
|
|
3733
3751
|
await sandbox.terminate({ wait: true });
|
|
3734
3752
|
});
|
|
3735
3753
|
} catch (error) {
|
|
3736
|
-
|
|
3737
|
-
if (!(error instanceof NotFoundError) && !grpcNotFound) throw error;
|
|
3754
|
+
if (!isModalNotFound(error)) throw error;
|
|
3738
3755
|
}
|
|
3739
3756
|
}
|
|
3740
3757
|
};
|
|
3758
|
+
function isModalNotFound(error) {
|
|
3759
|
+
return error instanceof getModalSdk().NotFoundError || error instanceof Error && error.name === "ClientError" && Reflect.get(error, "code") === 5;
|
|
3760
|
+
}
|
|
3741
3761
|
|
|
3742
3762
|
// src/define.ts
|
|
3743
|
-
var import_promises = require("fs/promises");
|
|
3744
|
-
var import_node_os = __toESM(require("os"), 1);
|
|
3745
3763
|
var import_node_path = __toESM(require("path"), 1);
|
|
3746
3764
|
|
|
3747
|
-
// src/
|
|
3748
|
-
var
|
|
3749
|
-
|
|
3765
|
+
// src/image-tag.ts
|
|
3766
|
+
var IMAGE_TAG_ENV_VARS = [
|
|
3767
|
+
"NECKBEARD_IMAGE_TAG",
|
|
3768
|
+
"GITHUB_SHA",
|
|
3769
|
+
"CI_COMMIT_SHA",
|
|
3770
|
+
"BITBUCKET_COMMIT",
|
|
3771
|
+
"CODEBUILD_RESOLVED_SOURCE_VERSION",
|
|
3772
|
+
"BUILDKITE_COMMIT",
|
|
3773
|
+
"CIRCLE_SHA1",
|
|
3774
|
+
"CF_PAGES_COMMIT_SHA",
|
|
3775
|
+
"HEROKU_BUILD_COMMIT",
|
|
3776
|
+
"HEROKU_SLUG_COMMIT",
|
|
3777
|
+
"RAILWAY_GIT_COMMIT_SHA",
|
|
3778
|
+
"RENDER_GIT_COMMIT",
|
|
3779
|
+
"VERCEL_GIT_COMMIT_SHA",
|
|
3780
|
+
"SOURCE_VERSION",
|
|
3781
|
+
"GIT_COMMIT"
|
|
3782
|
+
];
|
|
3783
|
+
function resolveImageTag(env = process.env) {
|
|
3784
|
+
for (const name of IMAGE_TAG_ENV_VARS) {
|
|
3785
|
+
const value = env[name]?.trim();
|
|
3786
|
+
if (value && value !== name) return value;
|
|
3787
|
+
}
|
|
3788
|
+
return void 0;
|
|
3789
|
+
}
|
|
3750
3790
|
|
|
3751
3791
|
// src/turn-protocol.ts
|
|
3752
|
-
var TURN_PROTOCOL_VERSION =
|
|
3792
|
+
var TURN_PROTOCOL_VERSION = 6;
|
|
3793
|
+
var STARTUP_ENV_KEYS = "NECKBEARD_STARTUP_ENV_KEYS";
|
|
3753
3794
|
var MAX_TURN_REQUEST_BYTES = 4 * 1024 * 1024;
|
|
3754
|
-
var MAX_TURN_ID_LENGTH = 200;
|
|
3755
3795
|
function isRecord2(value) {
|
|
3756
3796
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3757
3797
|
}
|
|
3758
|
-
function parseTurnRecord(record) {
|
|
3759
|
-
if (!isRecord2(record)) throw new Error("Turn record must be an object.");
|
|
3760
|
-
const { seq } = record;
|
|
3761
|
-
if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0) {
|
|
3762
|
-
throw new Error("Turn record seq must be a non-negative integer.");
|
|
3763
|
-
}
|
|
3764
|
-
if (record.type === "event" && "event" in record) {
|
|
3765
|
-
return { seq, type: "event", event: record.event };
|
|
3766
|
-
}
|
|
3767
|
-
if (record.type === "end" && (record.outcome === "completed" || record.outcome === "aborted" || record.outcome === "failed") && (record.error === void 0 || typeof record.error === "string") && (record.undeliveredSteerIds === void 0 || Array.isArray(record.undeliveredSteerIds) && record.undeliveredSteerIds.every((id) => typeof id === "string"))) {
|
|
3768
|
-
return {
|
|
3769
|
-
seq,
|
|
3770
|
-
type: "end",
|
|
3771
|
-
outcome: record.outcome,
|
|
3772
|
-
...record.error === void 0 ? {} : { error: record.error },
|
|
3773
|
-
...record.undeliveredSteerIds === void 0 ? {} : { undeliveredSteerIds: record.undeliveredSteerIds }
|
|
3774
|
-
};
|
|
3775
|
-
}
|
|
3776
|
-
throw new Error("Turn record has an unknown shape.");
|
|
3777
|
-
}
|
|
3778
3798
|
function parseTurnHealth(value) {
|
|
3779
3799
|
if (!isRecord2(value)) throw new Error("Health response must be an object.");
|
|
3780
3800
|
const { ok, protocolVersion, busy, turnId } = value;
|
|
@@ -3783,55 +3803,360 @@ function parseTurnHealth(value) {
|
|
|
3783
3803
|
}
|
|
3784
3804
|
return { ok, protocolVersion, busy, turnId };
|
|
3785
3805
|
}
|
|
3786
|
-
|
|
3787
|
-
|
|
3788
|
-
|
|
3789
|
-
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3794
|
-
|
|
3795
|
-
|
|
3806
|
+
|
|
3807
|
+
// src/conversation-records.ts
|
|
3808
|
+
var string = (v) => typeof v === "string";
|
|
3809
|
+
var number = (v) => typeof v === "number" && Number.isFinite(v);
|
|
3810
|
+
var bool = (v) => typeof v === "boolean";
|
|
3811
|
+
var id = (v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0;
|
|
3812
|
+
var absent = (v) => v === void 0;
|
|
3813
|
+
var optional = (check) => (v) => v === void 0 || check(v);
|
|
3814
|
+
var array = (check) => (v) => Array.isArray(v) && v.every(check);
|
|
3815
|
+
var values = (check) => (v) => isRecord2(v) && Object.values(v).every(check);
|
|
3816
|
+
var oneOf = (...options) => (v) => typeof v === "string" && options.includes(v);
|
|
3817
|
+
var shape = (fields) => (v) => isRecord2(v) && Object.entries(fields).every(([key, check]) => check(v[key]));
|
|
3818
|
+
var input = shape({
|
|
3819
|
+
id,
|
|
3820
|
+
conversationId: id,
|
|
3821
|
+
requestId: optional(string),
|
|
3822
|
+
trace: optional(values(string)),
|
|
3823
|
+
notify: optional(shape({ taskId: id, key: string }))
|
|
3824
|
+
});
|
|
3825
|
+
function isInputRecord(v) {
|
|
3826
|
+
if (!isRecord2(v) || v.type !== "input" || !input(v)) return false;
|
|
3827
|
+
if (v.status === "unanswered") return optional(id)(v.entry) && absent(v.answer) && string(v.reason);
|
|
3828
|
+
if (v.reason !== void 0 || v.detail !== void 0) return false;
|
|
3829
|
+
switch (v.status) {
|
|
3830
|
+
case "queued":
|
|
3831
|
+
return absent(v.entry) && absent(v.answer);
|
|
3832
|
+
case "placed":
|
|
3833
|
+
return id(v.entry) && absent(v.answer);
|
|
3834
|
+
case "done":
|
|
3835
|
+
return id(v.entry) && id(v.answer);
|
|
3836
|
+
default:
|
|
3837
|
+
return false;
|
|
3838
|
+
}
|
|
3796
3839
|
}
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
|
|
3801
|
-
|
|
3802
|
-
|
|
3803
|
-
|
|
3804
|
-
|
|
3805
|
-
|
|
3840
|
+
var text = shape({ type: oneOf("text"), text: string, textSignature: optional(string) });
|
|
3841
|
+
var image = shape({ type: oneOf("image"), data: string, mimeType: string });
|
|
3842
|
+
var thinking = shape({ type: oneOf("thinking"), thinking: string, thinkingSignature: optional(string), redacted: optional(bool) });
|
|
3843
|
+
var toolCall = shape({
|
|
3844
|
+
type: oneOf("toolCall"),
|
|
3845
|
+
id: string,
|
|
3846
|
+
name: string,
|
|
3847
|
+
arguments: isRecord2,
|
|
3848
|
+
thoughtSignature: optional(string),
|
|
3849
|
+
namespace: optional(string),
|
|
3850
|
+
argumentsError: optional(string)
|
|
3851
|
+
});
|
|
3852
|
+
var tokens = { input: number, output: number, cacheRead: number, cacheWrite: number };
|
|
3853
|
+
var usage = shape({
|
|
3854
|
+
...tokens,
|
|
3855
|
+
totalTokens: number,
|
|
3856
|
+
cacheWrite1h: optional(number),
|
|
3857
|
+
reasoning: optional(number),
|
|
3858
|
+
cost: shape({ ...tokens, total: number, totalFromProvider: optional(bool) })
|
|
3859
|
+
});
|
|
3860
|
+
var diagnostic = shape({
|
|
3861
|
+
type: string,
|
|
3862
|
+
timestamp: number,
|
|
3863
|
+
details: optional(isRecord2),
|
|
3864
|
+
error: optional(shape({ name: optional(string), message: string, stack: optional(string), code: optional((v) => string(v) || number(v)) }))
|
|
3865
|
+
});
|
|
3866
|
+
var assistant = shape({
|
|
3867
|
+
api: string,
|
|
3868
|
+
provider: string,
|
|
3869
|
+
model: string,
|
|
3870
|
+
content: array((v) => text(v) || thinking(v) || toolCall(v)),
|
|
3871
|
+
usage,
|
|
3872
|
+
stopReason: oneOf("pending", "stop", "length", "toolUse", "error", "aborted", "deferred"),
|
|
3873
|
+
responseModel: optional(string),
|
|
3874
|
+
responseId: optional(string),
|
|
3875
|
+
providerThinkingLevel: optional(string),
|
|
3876
|
+
thinkingLevel: optional(oneOf("off", "minimal", "low", "medium", "high", "xhigh", "max")),
|
|
3877
|
+
diagnostics: optional(array(diagnostic)),
|
|
3878
|
+
errorMessage: optional(string),
|
|
3879
|
+
rawStopReason: optional(string),
|
|
3880
|
+
endTurn: optional(bool),
|
|
3881
|
+
durationMs: optional(number),
|
|
3882
|
+
deferred: optional(shape({ provider: string, modelId: string, api: string, id: string, expiresAt: optional(number), pollAfterMs: optional(number) }))
|
|
3883
|
+
});
|
|
3884
|
+
var constrainedSampling = (v) => v === false || isRecord2(v) && (v.type === "json_schema" && oneOf("prefer", "require")(v.strict) || v.type === "grammar" && isRecord2(v.variants) && optional(string)(v.variants.openai_lark) && optional(string)(v.variants.openai_regex));
|
|
3885
|
+
var system = shape({
|
|
3886
|
+
content: (v) => string(v) || array(text)(v),
|
|
3887
|
+
sections: optional(values((v) => v === null || string(v))),
|
|
3888
|
+
toolsAdded: optional(array(shape({ name: string, description: string, parameters: (v) => typeof v === "object" && v !== null, constrainedSampling: optional(constrainedSampling) }))),
|
|
3889
|
+
toolsRemoved: optional(array(shape({ name: string })))
|
|
3890
|
+
});
|
|
3891
|
+
var media = array((v) => text(v) || image(v));
|
|
3892
|
+
var toolResult = shape({
|
|
3893
|
+
toolCallId: string,
|
|
3894
|
+
toolName: string,
|
|
3895
|
+
content: media,
|
|
3896
|
+
isError: bool,
|
|
3897
|
+
usage: optional(usage),
|
|
3898
|
+
durationMs: optional(number),
|
|
3899
|
+
nestedCalls: optional(shape({ complete: bool, calls: array(shape({
|
|
3900
|
+
id: string,
|
|
3901
|
+
name: string,
|
|
3902
|
+
arguments: optional(isRecord2),
|
|
3903
|
+
argumentsBytes: optional(number),
|
|
3904
|
+
status: oneOf("ok", "error", "unfinished"),
|
|
3905
|
+
durationMs: optional(number),
|
|
3906
|
+
error: optional(string)
|
|
3907
|
+
})) }))
|
|
3908
|
+
});
|
|
3909
|
+
function message(v) {
|
|
3910
|
+
if (!isRecord2(v) || !number(v.timestamp)) return false;
|
|
3911
|
+
switch (v.role) {
|
|
3912
|
+
case "user":
|
|
3913
|
+
return string(v.content) || media(v.content);
|
|
3914
|
+
case "system":
|
|
3915
|
+
return system(v);
|
|
3916
|
+
case "assistant":
|
|
3917
|
+
return assistant(v);
|
|
3918
|
+
case "toolResult":
|
|
3919
|
+
return toolResult(v);
|
|
3920
|
+
default:
|
|
3921
|
+
return false;
|
|
3806
3922
|
}
|
|
3807
|
-
|
|
3808
|
-
|
|
3809
|
-
|
|
3923
|
+
}
|
|
3924
|
+
var messages = array(message);
|
|
3925
|
+
var edit = (v) => isRecord2(v) && id(v.target) && (v.action === "omit" && absent(v.messages) || v.action === "replace" && messages(v.messages));
|
|
3926
|
+
var entry = shape({ id, conversationId: id, kind: string, head: optional(id), byTaskId: optional(id), model: optional(messages), edits: optional(array(edit)) });
|
|
3927
|
+
function isEntryRecord(v) {
|
|
3928
|
+
return entry(v);
|
|
3929
|
+
}
|
|
3930
|
+
|
|
3931
|
+
// src/remote-conversation.ts
|
|
3932
|
+
init_sse_framing();
|
|
3933
|
+
async function* chunks(reader) {
|
|
3934
|
+
const decoder = new TextDecoder();
|
|
3935
|
+
for (; ; ) {
|
|
3936
|
+
const part = await reader.read();
|
|
3937
|
+
if (part.done) break;
|
|
3938
|
+
yield decoder.decode(part.value, { stream: true });
|
|
3810
3939
|
}
|
|
3811
|
-
|
|
3812
|
-
|
|
3940
|
+
yield decoder.decode();
|
|
3941
|
+
}
|
|
3942
|
+
var RemoteAdmissionRejected = class extends Error {
|
|
3943
|
+
};
|
|
3944
|
+
var RemoteSubmissionNotFound = class extends Error {
|
|
3945
|
+
};
|
|
3946
|
+
function remoteConversation(request) {
|
|
3947
|
+
async function send(path2, data, signal, stream = false) {
|
|
3948
|
+
const response = await request("/conversation/" + path2, data, signal, stream);
|
|
3949
|
+
if (!response.ok) {
|
|
3950
|
+
const body = await response.json();
|
|
3951
|
+
const message2 = isRecord2(body) && typeof body.error === "string" ? body.error : "Remote conversation request failed.";
|
|
3952
|
+
if (path2 === "submit" && isRecord2(body) && body.code === "request_rejected" && [400, 409].includes(response.status)) {
|
|
3953
|
+
const error = new RemoteAdmissionRejected(message2);
|
|
3954
|
+
if (typeof body.name === "string") error.name = body.name;
|
|
3955
|
+
throw error;
|
|
3956
|
+
}
|
|
3957
|
+
if (response.status === 404 && isRecord2(body) && body.code === "submission_missing")
|
|
3958
|
+
throw new RemoteSubmissionNotFound(message2);
|
|
3959
|
+
const err = new Error(message2);
|
|
3960
|
+
throw err;
|
|
3961
|
+
}
|
|
3962
|
+
return response;
|
|
3963
|
+
}
|
|
3964
|
+
async function rpc(path2, data, ctx) {
|
|
3965
|
+
for (; ; ) {
|
|
3966
|
+
const response = await send(path2, data, ctx.abortSignal);
|
|
3967
|
+
const result = await response.json();
|
|
3968
|
+
if (response.status !== 202) return result;
|
|
3969
|
+
if (path2 !== "wait" && path2 !== "idle" || !isRecord2(result) || result.pending !== true)
|
|
3970
|
+
throw new Error("Invalid pending response.");
|
|
3971
|
+
}
|
|
3972
|
+
}
|
|
3973
|
+
function handle(value) {
|
|
3974
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
|
|
3975
|
+
throw new Error("Invalid remote submission ID.");
|
|
3976
|
+
const id2 = value;
|
|
3977
|
+
async function record(op, ctx) {
|
|
3978
|
+
const data = await rpc(op, { id: id2 }, ctx);
|
|
3979
|
+
if (!isInputRecord(data) || data.id !== id2) throw new Error("Invalid remote input record.");
|
|
3980
|
+
return data;
|
|
3981
|
+
}
|
|
3813
3982
|
return {
|
|
3814
|
-
|
|
3815
|
-
|
|
3983
|
+
id: id2,
|
|
3984
|
+
status: (ctx) => record("status", ctx),
|
|
3985
|
+
async wait(ctx) {
|
|
3986
|
+
const r = await record("wait", ctx);
|
|
3987
|
+
if (r.status !== "done" && r.status !== "unanswered") throw new Error("Expected settled input.");
|
|
3988
|
+
return r;
|
|
3989
|
+
},
|
|
3990
|
+
async abort(ctx) {
|
|
3991
|
+
const result = await rpc("withdraw", { id: id2 }, ctx);
|
|
3992
|
+
if (result !== "already_placed" && result !== "aborted" && result !== "settled")
|
|
3993
|
+
throw new Error("Invalid withdrawal response.");
|
|
3994
|
+
return result;
|
|
3995
|
+
}
|
|
3816
3996
|
};
|
|
3817
3997
|
}
|
|
3818
|
-
return {
|
|
3998
|
+
return {
|
|
3999
|
+
submit: async (draft, ctx) => handle(await rpc("submit", { draft }, ctx)),
|
|
4000
|
+
async submissionByRequest(requestId, ctx) {
|
|
4001
|
+
const id2 = await rpc("lookup", { requestId }, ctx);
|
|
4002
|
+
return id2 === null ? void 0 : handle(id2);
|
|
4003
|
+
},
|
|
4004
|
+
async entry(id2, ctx) {
|
|
4005
|
+
const data = await rpc("entry", { id: id2 }, ctx);
|
|
4006
|
+
if (data === null) return void 0;
|
|
4007
|
+
if (!isEntryRecord(data) || data.id !== id2) throw new Error("Invalid remote entry.");
|
|
4008
|
+
return data;
|
|
4009
|
+
},
|
|
4010
|
+
async stopSubmission(id2, ctx) {
|
|
4011
|
+
await rpc("stop", { id: id2 }, ctx);
|
|
4012
|
+
},
|
|
4013
|
+
async abort(ctx, options) {
|
|
4014
|
+
await rpc("abort", options ?? {}, ctx);
|
|
4015
|
+
},
|
|
4016
|
+
async waitForIdle(ctx) {
|
|
4017
|
+
await rpc("idle", {}, ctx);
|
|
4018
|
+
},
|
|
4019
|
+
async watch(ctx, window) {
|
|
4020
|
+
const contextEntry = "@earendil-works/chord/context";
|
|
4021
|
+
const { withoutAbortSignal } = await import(
|
|
4022
|
+
/* webpackIgnore: true */
|
|
4023
|
+
contextEntry
|
|
4024
|
+
);
|
|
4025
|
+
const callbackContext = withoutAbortSignal(ctx);
|
|
4026
|
+
const controller = new AbortController();
|
|
4027
|
+
const signal = ctx.abortSignal ? AbortSignal.any([ctx.abortSignal, controller.signal]) : controller.signal;
|
|
4028
|
+
const res = await send("watch", { window }, signal, true);
|
|
4029
|
+
if (!res.body) throw new Error("Missing watch stream.");
|
|
4030
|
+
const reader = res.body.getReader();
|
|
4031
|
+
void reader.closed.catch((error) => controller.abort(error));
|
|
4032
|
+
const frames = decodeSseStream(chunks(reader), { requireTerminator: true });
|
|
4033
|
+
const opened = await (async () => {
|
|
4034
|
+
const first = await frames.next();
|
|
4035
|
+
if (first.done || first.value.seq !== 0 || !first.value.frame?.opened || !first.value.frame.value) {
|
|
4036
|
+
throw new Error("Missing initial watch value.");
|
|
4037
|
+
}
|
|
4038
|
+
return { id: first.value.frame.opened, value: first.value.frame.value };
|
|
4039
|
+
})().catch((error) => {
|
|
4040
|
+
controller.abort();
|
|
4041
|
+
throw error;
|
|
4042
|
+
});
|
|
4043
|
+
const id2 = opened.id;
|
|
4044
|
+
let value = opened.value;
|
|
4045
|
+
let listener;
|
|
4046
|
+
let start;
|
|
4047
|
+
const started = new Promise((resolve2) => {
|
|
4048
|
+
start = resolve2;
|
|
4049
|
+
});
|
|
4050
|
+
let stopping = false;
|
|
4051
|
+
let ended = false;
|
|
4052
|
+
function interruption() {
|
|
4053
|
+
return ctx.abortSignal?.aborted ? { kind: "aborted" } : { kind: "failed", error: signal.reason };
|
|
4054
|
+
}
|
|
4055
|
+
let onAbort;
|
|
4056
|
+
const interrupted = new Promise((resolve2) => {
|
|
4057
|
+
onAbort = () => {
|
|
4058
|
+
start();
|
|
4059
|
+
resolve2(interruption());
|
|
4060
|
+
};
|
|
4061
|
+
if (signal.aborted) onAbort();
|
|
4062
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
4063
|
+
});
|
|
4064
|
+
let callbacks = Promise.resolve();
|
|
4065
|
+
let pending = 0;
|
|
4066
|
+
let failListener;
|
|
4067
|
+
const listenerFailed = new Promise((resolve2) => {
|
|
4068
|
+
failListener = resolve2;
|
|
4069
|
+
});
|
|
4070
|
+
const delivery = (async () => {
|
|
4071
|
+
try {
|
|
4072
|
+
let seq = 1;
|
|
4073
|
+
for await (const { seq: next, frame, exception } of frames) {
|
|
4074
|
+
if (next !== seq++) throw new Error("Watch delivery interrupted.");
|
|
4075
|
+
if (exception) {
|
|
4076
|
+
if (typeof exception.name !== "string" || typeof exception.message !== "string")
|
|
4077
|
+
throw new Error("Invalid watch exception.");
|
|
4078
|
+
const error = Object.assign(new Error(exception.message), { name: exception.name });
|
|
4079
|
+
if (frame.end?.kind === "failed" || frame.end?.kind === "listener_error")
|
|
4080
|
+
frame.end = { ...frame.end, error };
|
|
4081
|
+
else if (frame.call?.kind === "failed") frame.call = { ...frame.call, error };
|
|
4082
|
+
else throw new Error("Unexpected watch exception.");
|
|
4083
|
+
}
|
|
4084
|
+
if (frame.end) {
|
|
4085
|
+
if (!["stopped", "ended", "aborted", "failed", "listener_error"].includes(frame.end.kind))
|
|
4086
|
+
throw new Error("Invalid watch end.");
|
|
4087
|
+
if (frame.end.kind === "stopped" && !stopping)
|
|
4088
|
+
throw new Error("Watch stopped without a local stop request.");
|
|
4089
|
+
if (frame.end.kind === "stopped" || frame.end.kind === "ended") await callbacks;
|
|
4090
|
+
return frame.end;
|
|
4091
|
+
}
|
|
4092
|
+
const call = frame.call;
|
|
4093
|
+
if (!call || call.kind !== "failed" && (call.kind !== "value" || !Array.isArray(call.ops)))
|
|
4094
|
+
throw new Error("Invalid remote watch call.");
|
|
4095
|
+
if (++pending > 256) throw new Error("Watch listener fell behind by more than 256 callbacks.");
|
|
4096
|
+
callbacks = callbacks.then(async () => {
|
|
4097
|
+
if (!listener) await started;
|
|
4098
|
+
pending--;
|
|
4099
|
+
if (signal.aborted || ended || !listener) return;
|
|
4100
|
+
if (call.kind === "value") value = call.value;
|
|
4101
|
+
try {
|
|
4102
|
+
await listener(call, callbackContext);
|
|
4103
|
+
} catch (error) {
|
|
4104
|
+
failListener({ kind: "listener_error", error: error instanceof Error ? error : new Error(String(error)) });
|
|
4105
|
+
}
|
|
4106
|
+
});
|
|
4107
|
+
}
|
|
4108
|
+
throw new Error("Watch disconnected before its terminal frame.");
|
|
4109
|
+
} catch (error) {
|
|
4110
|
+
return ctx.abortSignal?.aborted ? { kind: "aborted" } : { kind: "failed", error };
|
|
4111
|
+
}
|
|
4112
|
+
})();
|
|
4113
|
+
const closed = Promise.race([delivery, interrupted, listenerFailed]).finally(() => {
|
|
4114
|
+
ended = true;
|
|
4115
|
+
start();
|
|
4116
|
+
signal.removeEventListener("abort", onAbort);
|
|
4117
|
+
controller.abort();
|
|
4118
|
+
reader.releaseLock();
|
|
4119
|
+
});
|
|
4120
|
+
return {
|
|
4121
|
+
get value() {
|
|
4122
|
+
return value;
|
|
4123
|
+
},
|
|
4124
|
+
closed,
|
|
4125
|
+
start(next) {
|
|
4126
|
+
if (listener || stopping || ended) throw new Error("Watch already started or closed.");
|
|
4127
|
+
listener = next;
|
|
4128
|
+
start();
|
|
4129
|
+
},
|
|
4130
|
+
async stop() {
|
|
4131
|
+
if (!stopping && !ended) {
|
|
4132
|
+
stopping = true;
|
|
4133
|
+
start();
|
|
4134
|
+
try {
|
|
4135
|
+
await send("stop-watch", { id: id2 }, signal);
|
|
4136
|
+
} catch (error) {
|
|
4137
|
+
controller.abort(error);
|
|
4138
|
+
}
|
|
4139
|
+
}
|
|
4140
|
+
return closed;
|
|
4141
|
+
}
|
|
4142
|
+
};
|
|
4143
|
+
}
|
|
4144
|
+
};
|
|
3819
4145
|
}
|
|
3820
4146
|
|
|
3821
4147
|
// src/agent.ts
|
|
4148
|
+
var import_node_crypto3 = require("crypto");
|
|
3822
4149
|
var DEFAULT_COMMAND = ["node", "/app/agent.mjs"];
|
|
3823
4150
|
var DEFAULT_PORT = 8080;
|
|
3824
4151
|
var DEFAULT_START_TIMEOUT_MS = 12e4;
|
|
3825
4152
|
var DEFAULT_PREPARE_TIMEOUT_MS = 30 * 6e4;
|
|
3826
|
-
var DEFAULT_RECONNECT_TIMEOUT_MS = 12e4;
|
|
3827
4153
|
var HEALTH_POLL_INTERVAL_MS = 500;
|
|
3828
|
-
var RECONNECT_MIN_DELAY_MS = 250;
|
|
3829
|
-
var RECONNECT_MAX_DELAY_MS = 5e3;
|
|
3830
4154
|
var REQUEST_TIMEOUT_MS = 3e4;
|
|
3831
4155
|
var ARTIFACT_PREFIX = "nb-";
|
|
3832
|
-
|
|
3833
|
-
|
|
3834
|
-
|
|
4156
|
+
var RUNTIME_REJECTION_CODES = ["request_rejected", "submission_missing"];
|
|
4157
|
+
function filterDefined(env) {
|
|
4158
|
+
return Object.fromEntries(Object.entries(env ?? {}).filter(
|
|
4159
|
+
(entry2) => entry2[1] !== void 0
|
|
3835
4160
|
));
|
|
3836
4161
|
}
|
|
3837
4162
|
function delay2(ms, signal) {
|
|
@@ -3852,31 +4177,6 @@ function untilDeadline(deadline, signal) {
|
|
|
3852
4177
|
const timeout = AbortSignal.timeout(Math.max(0, deadline - Date.now()));
|
|
3853
4178
|
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
3854
4179
|
}
|
|
3855
|
-
function untilAborted(operation, signal) {
|
|
3856
|
-
if (signal?.aborted) return Promise.reject(abortError(signal));
|
|
3857
|
-
return settleOperation(operation, signal ? { abort: { signal, createError: () => abortError(signal) } } : {});
|
|
3858
|
-
}
|
|
3859
|
-
function abortError(signal) {
|
|
3860
|
-
if (signal.reason instanceof Error) return signal.reason;
|
|
3861
|
-
const error = new Error("Operation aborted.");
|
|
3862
|
-
error.name = "AbortError";
|
|
3863
|
-
return error;
|
|
3864
|
-
}
|
|
3865
|
-
async function* textChunks(body, onChunk) {
|
|
3866
|
-
const decoder = new TextDecoder();
|
|
3867
|
-
const reader = body.getReader();
|
|
3868
|
-
try {
|
|
3869
|
-
while (true) {
|
|
3870
|
-
const { done, value } = await reader.read();
|
|
3871
|
-
if (done) break;
|
|
3872
|
-
onChunk();
|
|
3873
|
-
yield decoder.decode(value, { stream: true });
|
|
3874
|
-
}
|
|
3875
|
-
} finally {
|
|
3876
|
-
await reader.cancel().catch(() => void 0);
|
|
3877
|
-
reader.releaseLock();
|
|
3878
|
-
}
|
|
3879
|
-
}
|
|
3880
4180
|
var EndpointRejectedError = class extends Error {
|
|
3881
4181
|
};
|
|
3882
4182
|
var Agent = class {
|
|
@@ -3953,27 +4253,45 @@ var Agent = class {
|
|
|
3953
4253
|
const preparing = this.preparing;
|
|
3954
4254
|
return untilAborted(() => preparing, options.signal);
|
|
3955
4255
|
}
|
|
3956
|
-
/**
|
|
4256
|
+
/** Launches a sandbox. To reconnect to one, call `attach()`. */
|
|
3957
4257
|
async start(options = {}) {
|
|
4258
|
+
if ("sandboxId" in options) throw new ConfigurationError("start() always launches a sandbox. Call attach(sandboxId) to reconnect to one.");
|
|
3958
4259
|
await this.prepare({ ...options.signal ? { signal: options.signal } : {} });
|
|
3959
|
-
const
|
|
3960
|
-
...filterDefined(this.options.
|
|
3961
|
-
...filterDefined(options.
|
|
4260
|
+
const startup = {
|
|
4261
|
+
...filterDefined(this.options.env),
|
|
4262
|
+
...filterDefined(options.env)
|
|
4263
|
+
};
|
|
4264
|
+
const env = {
|
|
4265
|
+
...startup,
|
|
4266
|
+
[STARTUP_ENV_KEYS]: JSON.stringify(Object.keys(startup)),
|
|
3962
4267
|
...options.sessionId === void 0 ? {} : { NECKBEARD_SESSION_ID: options.sessionId },
|
|
3963
4268
|
NECKBEARD_PORT: String(this.port)
|
|
3964
4269
|
};
|
|
3965
4270
|
if (options.signal?.aborted) throw abortError(options.signal);
|
|
3966
4271
|
let sandbox;
|
|
4272
|
+
const creating = this.createSandbox(env);
|
|
3967
4273
|
try {
|
|
3968
|
-
sandbox = await
|
|
4274
|
+
sandbox = await untilAborted(() => creating, options.signal);
|
|
3969
4275
|
} catch (error) {
|
|
4276
|
+
if (options.signal?.aborted) {
|
|
4277
|
+
creating.then(
|
|
4278
|
+
(late) => late.destroy().catch((cleanupError) => {
|
|
4279
|
+
console.warn(`neckbeard: sandbox ${late.id} was created after its start was cancelled, and deleting it failed (${String(cleanupError)}); kill() it.`);
|
|
4280
|
+
}),
|
|
4281
|
+
() => void 0
|
|
4282
|
+
);
|
|
4283
|
+
throw error;
|
|
4284
|
+
}
|
|
3970
4285
|
this.preparing = void 0;
|
|
3971
4286
|
throw error;
|
|
3972
4287
|
}
|
|
3973
4288
|
try {
|
|
3974
|
-
if (this.options.sandbox.provider === "e2b")
|
|
4289
|
+
if (this.options.sandbox.provider === "e2b") {
|
|
4290
|
+
const e2b = this.options.sandbox;
|
|
4291
|
+
await untilAborted(() => this.startE2bRuntime(e2b, sandbox.id, env), options.signal);
|
|
4292
|
+
}
|
|
3975
4293
|
await this.waitForRuntime(sandbox.id, options.signal);
|
|
3976
|
-
return sandbox.id;
|
|
4294
|
+
return this.handle(sandbox.id);
|
|
3977
4295
|
} catch (error) {
|
|
3978
4296
|
this.endpoints.delete(sandbox.id);
|
|
3979
4297
|
try {
|
|
@@ -3991,149 +4309,18 @@ var Agent = class {
|
|
|
3991
4309
|
}
|
|
3992
4310
|
}
|
|
3993
4311
|
/**
|
|
3994
|
-
*
|
|
3995
|
-
*
|
|
3996
|
-
*/
|
|
3997
|
-
async *prompt(sandboxId, turn, options = {}) {
|
|
3998
|
-
const response = await this.request(sandboxId, "POST", "/turns", turn, options.signal);
|
|
3999
|
-
if (response.status === 409) {
|
|
4000
|
-
const body = await response.json().catch(() => ({}));
|
|
4001
|
-
throw new RuntimeBusyError(`Sandbox ${sandboxId} is running another turn (${body.turnId ?? "unknown"}).`);
|
|
4002
|
-
}
|
|
4003
|
-
if (response.status !== 200 && response.status !== 202) {
|
|
4004
|
-
throw new ExecutionError(`Starting turn ${turn.turnId} failed with ${response.status}: ${await response.text()}`);
|
|
4005
|
-
}
|
|
4006
|
-
await response.body?.cancel();
|
|
4007
|
-
yield* this.events(sandboxId, turn.turnId, options);
|
|
4008
|
-
}
|
|
4009
|
-
/**
|
|
4010
|
-
* Runs a Pi turn to its end and returns its final assistant text, or null when it had none.
|
|
4011
|
-
* Throws `ExecutionError` when the turn did not complete or its model did not stop on its own.
|
|
4012
|
-
* Running a turn again with the same `turnId` replays its records from the start.
|
|
4013
|
-
*/
|
|
4014
|
-
async run(sandboxId, turn, options = {}) {
|
|
4015
|
-
const { onRecord, ...streamOptions } = options;
|
|
4016
|
-
const records = [];
|
|
4017
|
-
for await (const record of this.prompt(sandboxId, turn, streamOptions)) {
|
|
4018
|
-
records.push(record);
|
|
4019
|
-
await onRecord?.(record);
|
|
4020
|
-
}
|
|
4021
|
-
options.signal?.throwIfAborted();
|
|
4022
|
-
const result = getPiTurnResult(records);
|
|
4023
|
-
if (!result.completed) throw new ExecutionError(`Turn ${turn.turnId} did not finish: ${result.error}`);
|
|
4024
|
-
return result.text;
|
|
4025
|
-
}
|
|
4026
|
-
/**
|
|
4027
|
-
* Streams a turn's records after `options.after` until its `end` record, reconnecting when
|
|
4028
|
-
* the connection drops. Throws `TurnLostError` when the runtime no longer has the turn.
|
|
4312
|
+
* Reconnects to a running sandbox by its provider ID, including while it is busy. Never creates,
|
|
4313
|
+
* starts or kills a sandbox, and admits no input.
|
|
4029
4314
|
*/
|
|
4030
|
-
async
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
|
|
4035
|
-
while (true) {
|
|
4036
|
-
let lastError;
|
|
4037
|
-
const stalled = new AbortController();
|
|
4038
|
-
let watchdog;
|
|
4039
|
-
const armWatchdog = () => {
|
|
4040
|
-
clearTimeout(watchdog);
|
|
4041
|
-
const budget = failingSince === void 0 ? reconnectTimeoutMs : Math.max(0, failingSince + reconnectTimeoutMs - Date.now());
|
|
4042
|
-
watchdog = setTimeout(() => stalled.abort(new Error(`Turn stream sent nothing for ${budget}ms.`)), budget);
|
|
4043
|
-
};
|
|
4044
|
-
armWatchdog();
|
|
4045
|
-
try {
|
|
4046
|
-
const response = await this.request(
|
|
4047
|
-
sandboxId,
|
|
4048
|
-
"GET",
|
|
4049
|
-
`/turns/${encodeURIComponent(turnId)}/events?after=${last}`,
|
|
4050
|
-
void 0,
|
|
4051
|
-
options.signal ? AbortSignal.any([options.signal, stalled.signal]) : stalled.signal,
|
|
4052
|
-
{ stream: true }
|
|
4053
|
-
);
|
|
4054
|
-
if (response.status === 404) {
|
|
4055
|
-
await response.body?.cancel();
|
|
4056
|
-
throw new TurnLostError(`Sandbox ${sandboxId} has no turn ${turnId}.`);
|
|
4057
|
-
}
|
|
4058
|
-
if (!response.ok || !response.body) {
|
|
4059
|
-
await response.body?.cancel();
|
|
4060
|
-
throw new Error(`Turn stream returned ${response.status}.`);
|
|
4061
|
-
}
|
|
4062
|
-
try {
|
|
4063
|
-
const onChunk = () => {
|
|
4064
|
-
failingSince = void 0;
|
|
4065
|
-
armWatchdog();
|
|
4066
|
-
};
|
|
4067
|
-
for await (const frame of decodeSseStream(textChunks(response.body, onChunk))) {
|
|
4068
|
-
let record;
|
|
4069
|
-
try {
|
|
4070
|
-
record = parseTurnRecord(frame);
|
|
4071
|
-
} catch (error) {
|
|
4072
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
4073
|
-
throw new ExecutionError(`Sandbox ${sandboxId} sent an invalid record for turn ${turnId}: ${message}`);
|
|
4074
|
-
}
|
|
4075
|
-
if (record.seq <= last) {
|
|
4076
|
-
if (record.type === "end") return;
|
|
4077
|
-
continue;
|
|
4078
|
-
}
|
|
4079
|
-
last = record.seq;
|
|
4080
|
-
failingSince = void 0;
|
|
4081
|
-
attempt = 0;
|
|
4082
|
-
clearTimeout(watchdog);
|
|
4083
|
-
yield record;
|
|
4084
|
-
armWatchdog();
|
|
4085
|
-
if (record.type === "end") return;
|
|
4086
|
-
}
|
|
4087
|
-
} catch (error) {
|
|
4088
|
-
if (error instanceof Error && error.message.startsWith("Malformed SSE data frame")) {
|
|
4089
|
-
throw new ExecutionError(`Sandbox ${sandboxId} sent a malformed frame for turn ${turnId}: ${error.message}`);
|
|
4090
|
-
}
|
|
4091
|
-
if (!(error instanceof IncompleteSseFrameError)) throw error;
|
|
4092
|
-
}
|
|
4093
|
-
lastError = new Error("Turn stream ended before the turn did.");
|
|
4094
|
-
} catch (error) {
|
|
4095
|
-
if (error instanceof TurnLostError || error instanceof ExecutionError) throw error;
|
|
4096
|
-
if (options.signal?.aborted) throw abortError(options.signal);
|
|
4097
|
-
if (error instanceof EndpointRejectedError) this.endpoints.delete(sandboxId);
|
|
4098
|
-
lastError = stalled.signal.aborted ? stalled.signal.reason : error;
|
|
4099
|
-
} finally {
|
|
4100
|
-
clearTimeout(watchdog);
|
|
4101
|
-
}
|
|
4102
|
-
failingSince ??= Date.now();
|
|
4103
|
-
if (Date.now() - failingSince > reconnectTimeoutMs) {
|
|
4104
|
-
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
4105
|
-
throw new ExecutionError(`Lost the stream of turn ${turnId} for over ${reconnectTimeoutMs}ms: ${message}`);
|
|
4106
|
-
}
|
|
4107
|
-
attempt += 1;
|
|
4108
|
-
await delay2(Math.min(RECONNECT_MAX_DELAY_MS, RECONNECT_MIN_DELAY_MS * 2 ** (attempt - 1)), options.signal);
|
|
4109
|
-
}
|
|
4110
|
-
}
|
|
4111
|
-
/** Asks the runtime to stop the turn; its stream then ends with an `aborted` record. */
|
|
4112
|
-
async abort(sandboxId, turnId, signal) {
|
|
4113
|
-
const response = await this.request(sandboxId, "POST", `/turns/${encodeURIComponent(turnId)}/abort`, void 0, signal);
|
|
4114
|
-
await response.body?.cancel();
|
|
4115
|
-
if (response.status !== 202 && response.status !== 404) {
|
|
4116
|
-
throw new ExecutionError(`Aborting turn ${turnId} failed with ${response.status}.`);
|
|
4117
|
-
}
|
|
4315
|
+
async attach(sandboxId, options = {}) {
|
|
4316
|
+
if (typeof sandboxId !== "string" || !sandboxId.trim()) throw new ConfigurationError("attach() requires a nonempty sandboxId.");
|
|
4317
|
+
this.endpoints.delete(sandboxId);
|
|
4318
|
+
this.requireProtocol(await this.health(sandboxId, options.signal));
|
|
4319
|
+
return this.handle(sandboxId);
|
|
4118
4320
|
}
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
|
|
4122
|
-
* record's `undeliveredSteerIds`. Resolves to false when the turn can no longer take it, or the
|
|
4123
|
-
* runtime no longer has it, so the caller can send the message as a turn of its own. Throws when
|
|
4124
|
-
* queueing failed or the request did; calling again with the same `steerId` never queues it twice.
|
|
4125
|
-
*/
|
|
4126
|
-
async steer(sandboxId, turnId, steer, signal) {
|
|
4127
|
-
const response = await this.request(sandboxId, "POST", `/turns/${encodeURIComponent(turnId)}/steer`, steer, signal);
|
|
4128
|
-
if (response.status === 200 || response.status === 202) {
|
|
4129
|
-
await response.body?.cancel();
|
|
4130
|
-
return true;
|
|
4131
|
-
}
|
|
4132
|
-
if (response.status === 409 || response.status === 404) {
|
|
4133
|
-
await response.body?.cancel();
|
|
4134
|
-
return false;
|
|
4135
|
-
}
|
|
4136
|
-
throw new ExecutionError(`Steering turn ${turnId} failed with ${response.status}: ${await response.text()}`);
|
|
4321
|
+
handle(sandboxId) {
|
|
4322
|
+
const conversation = remoteConversation((path2, data, signal, stream) => this.request(sandboxId, "POST", path2, data, signal, { stream }));
|
|
4323
|
+
return { sandboxId, conversation };
|
|
4137
4324
|
}
|
|
4138
4325
|
async health(sandboxId, signal) {
|
|
4139
4326
|
const response = await this.request(sandboxId, "GET", "/health", void 0, signal);
|
|
@@ -4147,7 +4334,7 @@ var Agent = class {
|
|
|
4147
4334
|
try {
|
|
4148
4335
|
if (!(await this.health(sandboxId, untilDeadline(deadline, options.signal))).busy) return;
|
|
4149
4336
|
} catch (error) {
|
|
4150
|
-
if (options.signal?.aborted) throw error;
|
|
4337
|
+
if (options.signal?.aborted || error instanceof SandboxGoneError) throw error;
|
|
4151
4338
|
}
|
|
4152
4339
|
if (Date.now() > deadline) throw new RuntimeBusyError(`Sandbox ${sandboxId} did not become idle.`);
|
|
4153
4340
|
await delay2(HEALTH_POLL_INTERVAL_MS, options.signal);
|
|
@@ -4170,15 +4357,18 @@ var Agent = class {
|
|
|
4170
4357
|
}
|
|
4171
4358
|
await destroyProviderSandbox({ provider: sandbox.provider, sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
|
|
4172
4359
|
}
|
|
4173
|
-
/** File and command access to a sandbox, for staging inputs and reading results. */
|
|
4360
|
+
/** File and command access to a sandbox, for staging inputs and reading results. Starts a stopped Daytona sandbox and resumes a paused E2B one. */
|
|
4174
4361
|
sandbox(sandboxId) {
|
|
4362
|
+
return this.connect(sandboxId, true);
|
|
4363
|
+
}
|
|
4364
|
+
connect(sandboxId, wake) {
|
|
4175
4365
|
const { sandbox } = this.options;
|
|
4176
4366
|
if (sandbox.provider === "modal") {
|
|
4177
4367
|
return SandboxClient.connect({
|
|
4178
4368
|
provider: "modal",
|
|
4179
4369
|
sandboxId,
|
|
4180
4370
|
...sandbox.environment ? { environment: sandbox.environment } : {}
|
|
4181
|
-
});
|
|
4371
|
+
}, { wake });
|
|
4182
4372
|
}
|
|
4183
4373
|
if (sandbox.provider === "e2b") {
|
|
4184
4374
|
return SandboxClient.connect({
|
|
@@ -4186,9 +4376,9 @@ var Agent = class {
|
|
|
4186
4376
|
sandboxId,
|
|
4187
4377
|
...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {},
|
|
4188
4378
|
...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
|
|
4189
|
-
});
|
|
4379
|
+
}, { wake });
|
|
4190
4380
|
}
|
|
4191
|
-
return SandboxClient.connect({ provider: "daytona", sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
|
|
4381
|
+
return SandboxClient.connect({ provider: "daytona", sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} }, { wake });
|
|
4192
4382
|
}
|
|
4193
4383
|
/**
|
|
4194
4384
|
* Deletes this agent's Daytona snapshots or E2B templates except the newest `keep` and the
|
|
@@ -4206,30 +4396,35 @@ var Agent = class {
|
|
|
4206
4396
|
for (const artifact of stale) await artifact.delete();
|
|
4207
4397
|
return stale.map((artifact) => artifact.name);
|
|
4208
4398
|
}
|
|
4209
|
-
createSandbox(
|
|
4399
|
+
createSandbox(env) {
|
|
4210
4400
|
const { sandbox } = this.options;
|
|
4211
4401
|
if (sandbox.provider === "modal") {
|
|
4212
4402
|
const { provider: _provider, ...modal } = sandbox;
|
|
4213
|
-
return SandboxClient.create({ provider: "modal", ...modal, template: this.image, command: this.command, envs });
|
|
4403
|
+
return SandboxClient.create({ provider: "modal", ...modal, template: this.image, command: this.command, envs: env });
|
|
4214
4404
|
}
|
|
4215
4405
|
if (sandbox.provider === "daytona") {
|
|
4216
4406
|
const { resources: _resources, ...daytona } = sandbox;
|
|
4217
|
-
return SandboxClient.create({ ...daytona, template: this.artifactName, envs });
|
|
4407
|
+
return SandboxClient.create({ ...daytona, template: this.artifactName, envs: env });
|
|
4218
4408
|
}
|
|
4219
4409
|
const { cpuCount: _cpuCount, memoryMB: _memoryMB, registry: _registry, ...e2b } = sandbox;
|
|
4220
|
-
return SandboxClient.create({ ...e2b, template: this.artifactName, envs, allowPublicTraffic: false });
|
|
4410
|
+
return SandboxClient.create({ ...e2b, template: this.artifactName, envs: env, allowPublicTraffic: false });
|
|
4221
4411
|
}
|
|
4222
4412
|
// An E2B template's start command runs once at build time, without each sandbox's environment.
|
|
4223
|
-
async startE2bRuntime(sandbox, sandboxId,
|
|
4413
|
+
async startE2bRuntime(sandbox, sandboxId, env) {
|
|
4224
4414
|
const { Sandbox } = await import("e2b");
|
|
4225
4415
|
const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
|
|
4226
4416
|
const e2bSandbox = await Sandbox.connect(sandboxId, {
|
|
4227
4417
|
...apiKey ? { apiKey } : {},
|
|
4228
4418
|
...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
|
|
4229
4419
|
});
|
|
4230
|
-
const command = await e2bSandbox.commands.run(this.command.map(shellQuote).join(" "), { background: true, envs, timeoutMs: 0 });
|
|
4420
|
+
const command = await e2bSandbox.commands.run(this.command.map(shellQuote).join(" "), { background: true, envs: env, timeoutMs: 0 });
|
|
4231
4421
|
await command.disconnect();
|
|
4232
4422
|
}
|
|
4423
|
+
requireProtocol(health) {
|
|
4424
|
+
if (health.protocolVersion !== TURN_PROTOCOL_VERSION) {
|
|
4425
|
+
throw new DeploymentError(`Sandbox runtime speaks protocol ${health.protocolVersion}; this host speaks ${TURN_PROTOCOL_VERSION}.`);
|
|
4426
|
+
}
|
|
4427
|
+
}
|
|
4233
4428
|
async waitForRuntime(sandboxId, signal) {
|
|
4234
4429
|
const timeoutMs = this.options.startTimeoutMs ?? DEFAULT_START_TIMEOUT_MS;
|
|
4235
4430
|
const deadline = Date.now() + timeoutMs;
|
|
@@ -4237,11 +4432,7 @@ var Agent = class {
|
|
|
4237
4432
|
while (Date.now() < deadline) {
|
|
4238
4433
|
try {
|
|
4239
4434
|
const health = await this.health(sandboxId, untilDeadline(deadline, signal));
|
|
4240
|
-
|
|
4241
|
-
throw new DeploymentError(
|
|
4242
|
-
`Sandbox runtime speaks protocol ${health.protocolVersion}; this host speaks ${TURN_PROTOCOL_VERSION}.`
|
|
4243
|
-
);
|
|
4244
|
-
}
|
|
4435
|
+
this.requireProtocol(health);
|
|
4245
4436
|
return;
|
|
4246
4437
|
} catch (error) {
|
|
4247
4438
|
if (error instanceof DeploymentError || signal?.aborted) throw error;
|
|
@@ -4249,13 +4440,15 @@ var Agent = class {
|
|
|
4249
4440
|
}
|
|
4250
4441
|
await delay2(HEALTH_POLL_INTERVAL_MS, signal);
|
|
4251
4442
|
}
|
|
4252
|
-
const
|
|
4253
|
-
throw new DeploymentError(`Runtime in sandbox ${sandboxId} did not answer within ${timeoutMs}ms: ${
|
|
4443
|
+
const message2 = lastError instanceof Error ? lastError.message : String(lastError);
|
|
4444
|
+
throw new DeploymentError(`Runtime in sandbox ${sandboxId} did not answer within ${timeoutMs}ms: ${message2}`);
|
|
4254
4445
|
}
|
|
4446
|
+
// Runtime requests never start or resume a sandbox: its runtime would come back without the
|
|
4447
|
+
// turns it held in memory, and a repeated requestId would run again.
|
|
4255
4448
|
endpoint(sandboxId) {
|
|
4256
4449
|
let endpoint = this.endpoints.get(sandboxId);
|
|
4257
4450
|
if (!endpoint) {
|
|
4258
|
-
endpoint = this.
|
|
4451
|
+
endpoint = this.connect(sandboxId, false).then((sandbox) => sandbox.getServerEndpoint(this.port));
|
|
4259
4452
|
endpoint.catch(() => this.endpoints.delete(sandboxId));
|
|
4260
4453
|
this.endpoints.set(sandboxId, endpoint);
|
|
4261
4454
|
}
|
|
@@ -4263,21 +4456,37 @@ var Agent = class {
|
|
|
4263
4456
|
}
|
|
4264
4457
|
async request(sandboxId, method, path2, body, signal, options = {}) {
|
|
4265
4458
|
for (let attempt = 0; ; attempt += 1) {
|
|
4266
|
-
const endpoint = await
|
|
4459
|
+
const endpoint = await this.lookup(sandboxId, signal);
|
|
4267
4460
|
const url = new URL(`${endpoint.url}${path2}`);
|
|
4268
4461
|
for (const [name, value] of Object.entries(endpoint.query)) url.searchParams.set(name, value);
|
|
4269
4462
|
const timeout = options.stream ? void 0 : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
|
|
4270
4463
|
const signals = [signal, timeout].filter((value) => value !== void 0);
|
|
4271
|
-
|
|
4272
|
-
|
|
4273
|
-
|
|
4274
|
-
|
|
4275
|
-
|
|
4276
|
-
|
|
4277
|
-
|
|
4278
|
-
|
|
4279
|
-
|
|
4280
|
-
|
|
4464
|
+
let response;
|
|
4465
|
+
try {
|
|
4466
|
+
response = await fetch(url, {
|
|
4467
|
+
method,
|
|
4468
|
+
headers: {
|
|
4469
|
+
...endpoint.headers,
|
|
4470
|
+
...body === void 0 ? {} : { "content-type": "application/json" },
|
|
4471
|
+
...options.stream ? { accept: "text/event-stream" } : {}
|
|
4472
|
+
},
|
|
4473
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
4474
|
+
...signals.length ? { signal: AbortSignal.any(signals) } : {}
|
|
4475
|
+
});
|
|
4476
|
+
} catch (error) {
|
|
4477
|
+
if (!signal?.aborted) await this.throwIfGone(sandboxId, signal);
|
|
4478
|
+
throw error;
|
|
4479
|
+
}
|
|
4480
|
+
const rejection = response.ok ? void 0 : await response.clone().json().catch(() => void 0);
|
|
4481
|
+
const fromRuntime = typeof rejection === "object" && rejection !== null && RUNTIME_REJECTION_CODES.includes(Reflect.get(rejection, "code"));
|
|
4482
|
+
if (!response.ok && !fromRuntime && response.status !== 401 && response.status !== 403) {
|
|
4483
|
+
try {
|
|
4484
|
+
await this.throwIfGone(sandboxId, signal);
|
|
4485
|
+
} catch (error) {
|
|
4486
|
+
await response.body?.cancel();
|
|
4487
|
+
throw error;
|
|
4488
|
+
}
|
|
4489
|
+
}
|
|
4281
4490
|
if (response.status === 401 || response.status === 403) {
|
|
4282
4491
|
await response.body?.cancel();
|
|
4283
4492
|
this.endpoints.delete(sandboxId);
|
|
@@ -4287,6 +4496,31 @@ var Agent = class {
|
|
|
4287
4496
|
return response;
|
|
4288
4497
|
}
|
|
4289
4498
|
}
|
|
4499
|
+
// After a failed request, asks the provider whether the sandbox still runs, without waking it.
|
|
4500
|
+
// The request is not sent again, and any other answer leaves the original failure to the caller.
|
|
4501
|
+
// The caller's cancellation ends the wait, and a provider that does not answer within a request's
|
|
4502
|
+
// time is treated as unable to say.
|
|
4503
|
+
async throwIfGone(sandboxId, signal) {
|
|
4504
|
+
this.endpoints.delete(sandboxId);
|
|
4505
|
+
try {
|
|
4506
|
+
await this.lookup(sandboxId, signal);
|
|
4507
|
+
} catch (error) {
|
|
4508
|
+
if (error instanceof SandboxGoneError || signal?.aborted) throw error;
|
|
4509
|
+
}
|
|
4510
|
+
}
|
|
4511
|
+
// Callers share one provider lookup per sandbox, so each waits on it within its own signal and a
|
|
4512
|
+
// request's time. A lookup that outlasts that is dropped, so the next caller starts a new one.
|
|
4513
|
+
async lookup(sandboxId, signal) {
|
|
4514
|
+
const bound = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
|
|
4515
|
+
const pending = this.endpoint(sandboxId);
|
|
4516
|
+
try {
|
|
4517
|
+
return await untilAborted(() => pending, signal ? AbortSignal.any([signal, bound]) : bound);
|
|
4518
|
+
} catch (error) {
|
|
4519
|
+
if (signal?.aborted || !bound.aborted) throw error;
|
|
4520
|
+
if (this.endpoints.get(sandboxId) === pending) this.endpoints.delete(sandboxId);
|
|
4521
|
+
throw new ExecutionError(`The provider did not resolve sandbox ${sandboxId}'s endpoint within ${REQUEST_TIMEOUT_MS}ms.`);
|
|
4522
|
+
}
|
|
4523
|
+
}
|
|
4290
4524
|
async prepareDaytonaSnapshot(sandbox, options) {
|
|
4291
4525
|
const { Daytona, DaytonaNotFoundError } = await import("@daytona/sdk");
|
|
4292
4526
|
const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
|
|
@@ -4374,7 +4608,7 @@ var Agent = class {
|
|
|
4374
4608
|
...connection,
|
|
4375
4609
|
...sandbox.cpuCount === void 0 ? {} : { cpuCount: sandbox.cpuCount },
|
|
4376
4610
|
...sandbox.memoryMB === void 0 ? {} : { memoryMB: sandbox.memoryMB },
|
|
4377
|
-
...onLog ? { onBuildLogs: (
|
|
4611
|
+
...onLog ? { onBuildLogs: (entry2) => onLog(entry2.toString()) } : {}
|
|
4378
4612
|
});
|
|
4379
4613
|
}
|
|
4380
4614
|
async listDaytonaSnapshots(sandbox, ownName) {
|
|
@@ -4424,11 +4658,7 @@ var Agent = class {
|
|
|
4424
4658
|
// src/braintrust.ts
|
|
4425
4659
|
var API_KEY = "BRAINTRUST_API_KEY";
|
|
4426
4660
|
var PROJECT_NAME = "BRAINTRUST_PROJECT_NAME";
|
|
4427
|
-
var
|
|
4428
|
-
var BRAINTRUST_PACKAGE = "braintrust";
|
|
4429
|
-
var BRAINTRUST_VERSIONS = ">=3.44.0 <4.0.0";
|
|
4430
|
-
var warn = (message) => console.warn(`neckbeard: ${message}`);
|
|
4431
|
-
var errorText = (error) => error instanceof Error ? error.message : String(error);
|
|
4661
|
+
var warn = (message2) => console.warn(`neckbeard: ${message2}`);
|
|
4432
4662
|
function readBraintrustSettings(env, where) {
|
|
4433
4663
|
const apiKey = env[API_KEY]?.trim();
|
|
4434
4664
|
const projectName = env[PROJECT_NAME]?.trim();
|
|
@@ -4436,501 +4666,22 @@ function readBraintrustSettings(env, where) {
|
|
|
4436
4666
|
if (apiKey) warn(`Braintrust logging isn't configured ${where}: ${PROJECT_NAME} is not set.`);
|
|
4437
4667
|
return void 0;
|
|
4438
4668
|
}
|
|
4439
|
-
async function startBraintrust({ apiKey, projectName }) {
|
|
4440
|
-
const notTracing = "Braintrust tracing is off in the sandbox";
|
|
4441
|
-
let sdk;
|
|
4442
|
-
try {
|
|
4443
|
-
sdk = await import(
|
|
4444
|
-
/* webpackIgnore: true */
|
|
4445
|
-
BRAINTRUST_PACKAGE
|
|
4446
|
-
);
|
|
4447
|
-
} catch (error) {
|
|
4448
|
-
if (errorText(error).includes(`Cannot find package '${BRAINTRUST_PACKAGE}'`)) {
|
|
4449
|
-
warn(`${notTracing}: add ${BRAINTRUST_PACKAGE} ${BRAINTRUST_VERSIONS} to the agent's package's dependencies so the image has it.`);
|
|
4450
|
-
} else {
|
|
4451
|
-
warn(`${notTracing}: ${BRAINTRUST_PACKAGE} failed to load: ${errorText(error)}`);
|
|
4452
|
-
}
|
|
4453
|
-
return void 0;
|
|
4454
|
-
}
|
|
4455
|
-
if (typeof sdk.wrapPiCodingAgentSDK !== "function") {
|
|
4456
|
-
warn(`${notTracing}: its ${BRAINTRUST_PACKAGE} can't trace Pi; use ${BRAINTRUST_VERSIONS}.`);
|
|
4457
|
-
return void 0;
|
|
4458
|
-
}
|
|
4459
|
-
try {
|
|
4460
|
-
sdk.initLogger({ projectName, apiKey });
|
|
4461
|
-
} catch (error) {
|
|
4462
|
-
warn(`${notTracing}: ${errorText(error)}`);
|
|
4463
|
-
return void 0;
|
|
4464
|
-
}
|
|
4465
|
-
return {
|
|
4466
|
-
wrapPi: (pi) => sdk.wrapPiCodingAgentSDK(pi),
|
|
4467
|
-
async flush() {
|
|
4468
|
-
try {
|
|
4469
|
-
await withTimeout(sdk.flush(), FLUSH_TIMEOUT_MS, `not sent within ${FLUSH_TIMEOUT_MS / 1e3} seconds; it may arrive later`);
|
|
4470
|
-
} catch (error) {
|
|
4471
|
-
warn(`could not send the turn's Braintrust trace: ${errorText(error)}`);
|
|
4472
|
-
}
|
|
4473
|
-
}
|
|
4474
|
-
};
|
|
4475
|
-
}
|
|
4476
4669
|
|
|
4477
4670
|
// src/serve.ts
|
|
4478
|
-
var
|
|
4479
|
-
|
|
4480
|
-
|
|
4481
|
-
|
|
4482
|
-
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
if (!isRecord2(message) || message.role !== "assistant") {
|
|
4486
|
-
throw new Error("message_update message is not an assistant message");
|
|
4487
|
-
}
|
|
4488
|
-
if (!isRecord2(assistantMessageEvent) || typeof assistantMessageEvent.type !== "string") {
|
|
4489
|
-
throw new Error("message_update has no assistantMessageEvent");
|
|
4490
|
-
}
|
|
4491
|
-
const { partial, ...delta } = assistantMessageEvent;
|
|
4492
|
-
if (assistantMessageEvent.type === "toolcall_start") {
|
|
4493
|
-
const { contentIndex } = assistantMessageEvent;
|
|
4494
|
-
const content = isRecord2(partial) && Array.isArray(partial.content) ? partial.content : [];
|
|
4495
|
-
const toolCall = typeof contentIndex === "number" ? content[contentIndex] : void 0;
|
|
4496
|
-
if (!isRecord2(toolCall) || toolCall.type !== "toolCall" || typeof toolCall.id !== "string" || typeof toolCall.name !== "string") {
|
|
4497
|
-
throw new Error(`toolcall_start content at index ${String(contentIndex)} is not a tool call`);
|
|
4498
|
-
}
|
|
4499
|
-
return {
|
|
4500
|
-
type: "message_update",
|
|
4501
|
-
usage: message.usage,
|
|
4502
|
-
assistantMessageEvent: { ...delta, id: toolCall.id, toolName: toolCall.name }
|
|
4503
|
-
};
|
|
4504
|
-
}
|
|
4505
|
-
return { type: "message_update", usage: message.usage, assistantMessageEvent: delta };
|
|
4506
|
-
}
|
|
4507
|
-
var RequestError = class extends Error {
|
|
4508
|
-
constructor(status, message) {
|
|
4509
|
-
super(message);
|
|
4510
|
-
this.status = status;
|
|
4511
|
-
}
|
|
4512
|
-
};
|
|
4513
|
-
function sendJson(response, status, body) {
|
|
4514
|
-
response.writeHead(status, { "content-type": "application/json" });
|
|
4515
|
-
response.end(JSON.stringify(body));
|
|
4516
|
-
}
|
|
4517
|
-
async function readJsonBody(request) {
|
|
4518
|
-
const chunks = [];
|
|
4519
|
-
let size = 0;
|
|
4520
|
-
for await (const chunk of request) {
|
|
4521
|
-
size += chunk.byteLength;
|
|
4522
|
-
if (size > MAX_TURN_REQUEST_BYTES) throw new RequestError(413, "Request body is too large.");
|
|
4523
|
-
chunks.push(chunk);
|
|
4524
|
-
}
|
|
4525
|
-
try {
|
|
4526
|
-
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
4527
|
-
} catch {
|
|
4528
|
-
throw new RequestError(400, "Request body must be JSON.");
|
|
4529
|
-
}
|
|
4530
|
-
}
|
|
4531
|
-
function parseStartTurn(body) {
|
|
4532
|
-
if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
|
|
4533
|
-
const { turnId, message, env } = body;
|
|
4534
|
-
if (typeof turnId !== "string" || !turnId || turnId.length > MAX_TURN_ID_LENGTH) {
|
|
4535
|
-
throw new RequestError(400, `turnId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
|
|
4536
|
-
}
|
|
4537
|
-
if (typeof message !== "string" || !message.trim()) {
|
|
4538
|
-
throw new RequestError(400, "message must be a non-empty string.");
|
|
4539
|
-
}
|
|
4540
|
-
if (env !== void 0 && (!env || typeof env !== "object" || Array.isArray(env) || Object.entries(env).some(([name, value]) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || typeof value !== "string"))) {
|
|
4541
|
-
throw new RequestError(400, "env must map environment variable names to strings.");
|
|
4542
|
-
}
|
|
4543
|
-
return { turnId, message, ...env === void 0 ? {} : { env } };
|
|
4544
|
-
}
|
|
4545
|
-
function parseSteerTurn(body) {
|
|
4546
|
-
if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
|
|
4547
|
-
const { steerId, message } = body;
|
|
4548
|
-
if (typeof steerId !== "string" || !steerId || steerId.length > MAX_TURN_ID_LENGTH) {
|
|
4549
|
-
throw new RequestError(400, `steerId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
|
|
4550
|
-
}
|
|
4551
|
-
if (typeof message !== "string" || !message.trim()) {
|
|
4552
|
-
throw new RequestError(400, "message must be a non-empty string.");
|
|
4553
|
-
}
|
|
4554
|
-
return { steerId, message };
|
|
4555
|
-
}
|
|
4556
|
-
async function serve(options) {
|
|
4557
|
-
const toWireEvent = options.toWireEvent ?? toPiJsonEvent;
|
|
4558
|
-
let sessionPromise;
|
|
4559
|
-
let current;
|
|
4560
|
-
let previous;
|
|
4561
|
-
let currentSessionAbort;
|
|
4562
|
-
const findTurn = (turnId) => current?.id === turnId ? current : previous?.id === turnId ? previous : void 0;
|
|
4563
|
-
const append = (turn, record) => {
|
|
4564
|
-
const json = JSON.stringify({ seq: turn.records.length, ...record });
|
|
4565
|
-
turn.records.push(json);
|
|
4566
|
-
for (const wake of turn.waiters) wake();
|
|
4567
|
-
};
|
|
4568
|
-
const reclaimSteers = (turn) => {
|
|
4569
|
-
let left;
|
|
4570
|
-
try {
|
|
4571
|
-
left = turn.session?.clearQueue?.().steering.length ?? 0;
|
|
4572
|
-
} catch {
|
|
4573
|
-
left = turn.queuedSteers.length;
|
|
4574
|
-
sessionPromise = void 0;
|
|
4575
|
-
}
|
|
4576
|
-
const leftover = left > 0 ? turn.queuedSteers.slice(-left) : [];
|
|
4577
|
-
for (const steer of turn.queuedSteers) steer.state = leftover.includes(steer) ? "undelivered" : "delivered";
|
|
4578
|
-
turn.queuedSteers = [];
|
|
4579
|
-
turn.undeliveredSteers.push(...leftover);
|
|
4580
|
-
};
|
|
4581
|
-
const end = (turn, outcome, error) => {
|
|
4582
|
-
if (turn.ending) return turn.ending;
|
|
4583
|
-
turn.closed = true;
|
|
4584
|
-
turn.sessionReady();
|
|
4585
|
-
let written;
|
|
4586
|
-
turn.ending = new Promise((resolve2) => {
|
|
4587
|
-
written = resolve2;
|
|
4588
|
-
});
|
|
4589
|
-
reclaimSteers(turn);
|
|
4590
|
-
void (async () => {
|
|
4591
|
-
let timer;
|
|
4592
|
-
const graceMs = turn.stopBy === void 0 ? options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS : Math.max(0, turn.stopBy - Date.now());
|
|
4593
|
-
await Promise.race([
|
|
4594
|
-
turn.steering,
|
|
4595
|
-
new Promise((resolve2) => {
|
|
4596
|
-
timer = setTimeout(resolve2, graceMs);
|
|
4597
|
-
})
|
|
4598
|
-
]);
|
|
4599
|
-
clearTimeout(timer);
|
|
4600
|
-
reclaimSteers(turn);
|
|
4601
|
-
const undeliveredSteerIds = turn.undeliveredSteers.filter((steer) => !steer.late).map((steer) => steer.id);
|
|
4602
|
-
append(turn, {
|
|
4603
|
-
type: "end",
|
|
4604
|
-
outcome,
|
|
4605
|
-
...error === void 0 ? {} : { error },
|
|
4606
|
-
...undeliveredSteerIds.length > 0 ? { undeliveredSteerIds } : {}
|
|
4607
|
-
});
|
|
4608
|
-
turn.ended = true;
|
|
4609
|
-
written();
|
|
4610
|
-
})();
|
|
4611
|
-
return turn.ending;
|
|
4612
|
-
};
|
|
4613
|
-
const acceptSteer = (turn, id, message) => {
|
|
4614
|
-
const steer = { id, state: "pending", late: false, settled: Promise.resolve() };
|
|
4615
|
-
steer.settled = turn.steering.then(async () => {
|
|
4616
|
-
const session = turn.session;
|
|
4617
|
-
if (turn.closed || !session?.steer || !session.clearQueue) {
|
|
4618
|
-
steer.state = "undelivered";
|
|
4619
|
-
return;
|
|
4620
|
-
}
|
|
4621
|
-
try {
|
|
4622
|
-
if (await session.steer(message) === "handled") {
|
|
4623
|
-
steer.state = "handled";
|
|
4624
|
-
return;
|
|
4625
|
-
}
|
|
4626
|
-
steer.state = "queued";
|
|
4627
|
-
turn.queuedSteers.push(steer);
|
|
4628
|
-
if (turn.closed) {
|
|
4629
|
-
reclaimSteers(turn);
|
|
4630
|
-
steer.late = turn.undeliveredSteers.includes(steer);
|
|
4631
|
-
}
|
|
4632
|
-
} catch (error) {
|
|
4633
|
-
steer.state = "failed";
|
|
4634
|
-
steer.error = error;
|
|
4635
|
-
turn.steers.delete(id);
|
|
4636
|
-
}
|
|
4637
|
-
});
|
|
4638
|
-
turn.steering = steer.settled;
|
|
4639
|
-
turn.steers.set(id, steer);
|
|
4640
|
-
return steer;
|
|
4641
|
-
};
|
|
4642
|
-
const endAfterGrace = (turn, outcome, error) => {
|
|
4643
|
-
if (turn.ending || turn.finishing || turn.forceEnd) return;
|
|
4644
|
-
const graceMs = options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS;
|
|
4645
|
-
turn.stopBy = Date.now() + graceMs;
|
|
4646
|
-
turn.forceEnd = setTimeout(() => void end(turn, outcome, error), graceMs);
|
|
4647
|
-
};
|
|
4648
|
-
const runTurn = async (turn, request) => {
|
|
4649
|
-
const previousEnv = /* @__PURE__ */ new Map();
|
|
4650
|
-
let unsubscribe;
|
|
4651
|
-
let timedOut = false;
|
|
4652
|
-
let session;
|
|
4653
|
-
const timeoutMessage = `Turn exceeded ${options.maxTurnDurationMs}ms.`;
|
|
4654
|
-
const timer = options.maxTurnDurationMs === void 0 ? void 0 : setTimeout(() => {
|
|
4655
|
-
timedOut = true;
|
|
4656
|
-
turn.closed = true;
|
|
4657
|
-
reclaimSteers(turn);
|
|
4658
|
-
if (session) void session.abort().catch(() => void 0);
|
|
4659
|
-
endAfterGrace(turn, "failed", timeoutMessage);
|
|
4660
|
-
}, options.maxTurnDurationMs);
|
|
4661
|
-
const finish = async (outcome, error) => {
|
|
4662
|
-
turn.finishing = true;
|
|
4663
|
-
turn.closed = true;
|
|
4664
|
-
if (timer) clearTimeout(timer);
|
|
4665
|
-
clearTimeout(turn.forceEnd);
|
|
4666
|
-
try {
|
|
4667
|
-
await session?.afterTurn?.();
|
|
4668
|
-
} catch {
|
|
4669
|
-
}
|
|
4670
|
-
await end(turn, outcome, error);
|
|
4671
|
-
};
|
|
4672
|
-
try {
|
|
4673
|
-
sessionPromise ??= options.createSession();
|
|
4674
|
-
try {
|
|
4675
|
-
session = await sessionPromise;
|
|
4676
|
-
} catch (error) {
|
|
4677
|
-
sessionPromise = void 0;
|
|
4678
|
-
throw error;
|
|
4679
|
-
}
|
|
4680
|
-
if (timedOut) {
|
|
4681
|
-
await end(turn, "failed", timeoutMessage);
|
|
4682
|
-
return;
|
|
4683
|
-
}
|
|
4684
|
-
const started = session;
|
|
4685
|
-
turn.session = session;
|
|
4686
|
-
for (const [name, value] of Object.entries(request.env ?? {})) {
|
|
4687
|
-
previousEnv.set(name, process.env[name]);
|
|
4688
|
-
process.env[name] = value;
|
|
4689
|
-
}
|
|
4690
|
-
unsubscribe = session.subscribe((event) => {
|
|
4691
|
-
if (turn.ending) return;
|
|
4692
|
-
try {
|
|
4693
|
-
append(turn, { type: "event", event: toWireEvent(event) });
|
|
4694
|
-
} catch (error) {
|
|
4695
|
-
void end(turn, "failed", `Could not convert an agent event: ${error instanceof Error ? error.message : String(error)}`);
|
|
4696
|
-
void started.abort().catch(() => void 0);
|
|
4697
|
-
}
|
|
4698
|
-
});
|
|
4699
|
-
currentSessionAbort = () => started.abort();
|
|
4700
|
-
turn.sessionReady();
|
|
4701
|
-
if (!turn.closed) await turn.steering;
|
|
4702
|
-
if (turn.ending) return;
|
|
4703
|
-
if (timedOut) {
|
|
4704
|
-
await end(turn, "failed", timeoutMessage);
|
|
4705
|
-
return;
|
|
4706
|
-
}
|
|
4707
|
-
if (turn.abortRequested) {
|
|
4708
|
-
await end(turn, "aborted");
|
|
4709
|
-
return;
|
|
4710
|
-
}
|
|
4711
|
-
await started.prompt(request.message);
|
|
4712
|
-
if (timedOut) await finish("failed", timeoutMessage);
|
|
4713
|
-
else await finish(turn.abortRequested ? "aborted" : "completed");
|
|
4714
|
-
} catch (error) {
|
|
4715
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
4716
|
-
if (timedOut) await finish("failed", timeoutMessage);
|
|
4717
|
-
else await finish(turn.abortRequested ? "aborted" : "failed", turn.abortRequested ? void 0 : message);
|
|
4718
|
-
} finally {
|
|
4719
|
-
if (timer) clearTimeout(timer);
|
|
4720
|
-
clearTimeout(turn.forceEnd);
|
|
4721
|
-
turn.closed = true;
|
|
4722
|
-
turn.sessionReady();
|
|
4723
|
-
await turn.ending;
|
|
4724
|
-
unsubscribe?.();
|
|
4725
|
-
currentSessionAbort = void 0;
|
|
4726
|
-
await turn.steering;
|
|
4727
|
-
reclaimSteers(turn);
|
|
4728
|
-
for (const [name, value] of previousEnv) {
|
|
4729
|
-
if (value === void 0) delete process.env[name];
|
|
4730
|
-
else process.env[name] = value;
|
|
4731
|
-
}
|
|
4732
|
-
turn.settled = true;
|
|
4733
|
-
}
|
|
4734
|
-
};
|
|
4735
|
-
const busy = () => Boolean(current && !current.settled);
|
|
4736
|
-
const startTurn = async (request) => {
|
|
4737
|
-
const existing = findTurn(request.turnId);
|
|
4738
|
-
if (existing) return { status: 200, body: { turnId: existing.id, ended: existing.ended } };
|
|
4739
|
-
if (current && !current.settled) {
|
|
4740
|
-
return { status: 409, body: { error: "Another turn is running.", turnId: current.id } };
|
|
4741
|
-
}
|
|
4742
|
-
let sessionReady;
|
|
4743
|
-
const turn = {
|
|
4744
|
-
id: request.turnId,
|
|
4745
|
-
records: [],
|
|
4746
|
-
ended: false,
|
|
4747
|
-
settled: false,
|
|
4748
|
-
abortRequested: false,
|
|
4749
|
-
steers: /* @__PURE__ */ new Map(),
|
|
4750
|
-
queuedSteers: [],
|
|
4751
|
-
undeliveredSteers: [],
|
|
4752
|
-
steering: new Promise((resolve2) => {
|
|
4753
|
-
sessionReady = resolve2;
|
|
4754
|
-
}),
|
|
4755
|
-
sessionReady: () => sessionReady(),
|
|
4756
|
-
closed: false,
|
|
4757
|
-
finishing: false,
|
|
4758
|
-
waiters: /* @__PURE__ */ new Set()
|
|
4759
|
-
};
|
|
4760
|
-
previous = current;
|
|
4761
|
-
current = turn;
|
|
4762
|
-
void runTurn(turn, request);
|
|
4763
|
-
return { status: 202, body: { turnId: turn.id, ended: false } };
|
|
4764
|
-
};
|
|
4765
|
-
const streamTurn = async (turn, after, request, response) => {
|
|
4766
|
-
response.writeHead(200, {
|
|
4767
|
-
"content-type": "text/event-stream",
|
|
4768
|
-
"cache-control": "no-cache, no-transform",
|
|
4769
|
-
connection: "keep-alive",
|
|
4770
|
-
"x-accel-buffering": "no"
|
|
4771
|
-
});
|
|
4772
|
-
response.write(": connected\n\n");
|
|
4773
|
-
let closed = false;
|
|
4774
|
-
let wake;
|
|
4775
|
-
const onClose = () => {
|
|
4776
|
-
closed = true;
|
|
4777
|
-
wake?.();
|
|
4778
|
-
};
|
|
4779
|
-
request.on("close", onClose);
|
|
4780
|
-
response.on("close", onClose);
|
|
4781
|
-
const heartbeat = setInterval(() => {
|
|
4782
|
-
if (!closed) response.write(": ping\n\n");
|
|
4783
|
-
}, HEARTBEAT_INTERVAL_MS);
|
|
4784
|
-
let next = turn.ended ? Math.min(after + 1, turn.records.length - 1) : after + 1;
|
|
4785
|
-
try {
|
|
4786
|
-
while (!closed) {
|
|
4787
|
-
while (!closed && next < turn.records.length) {
|
|
4788
|
-
const ok = response.write(`id: ${next}
|
|
4789
|
-
data: ${turn.records[next]}
|
|
4790
|
-
|
|
4791
|
-
`);
|
|
4792
|
-
next += 1;
|
|
4793
|
-
if (!ok && !closed) {
|
|
4794
|
-
let onDrain;
|
|
4795
|
-
await new Promise((resolve2) => {
|
|
4796
|
-
wake = onDrain = resolve2;
|
|
4797
|
-
response.once("drain", resolve2);
|
|
4798
|
-
});
|
|
4799
|
-
if (onDrain) response.off("drain", onDrain);
|
|
4800
|
-
wake = void 0;
|
|
4801
|
-
}
|
|
4802
|
-
}
|
|
4803
|
-
if (closed || turn.ended && next >= turn.records.length) break;
|
|
4804
|
-
await new Promise((resolve2) => {
|
|
4805
|
-
wake = resolve2;
|
|
4806
|
-
turn.waiters.add(resolve2);
|
|
4807
|
-
});
|
|
4808
|
-
if (wake) turn.waiters.delete(wake);
|
|
4809
|
-
wake = void 0;
|
|
4810
|
-
}
|
|
4811
|
-
} finally {
|
|
4812
|
-
clearInterval(heartbeat);
|
|
4813
|
-
request.off("close", onClose);
|
|
4814
|
-
response.off("close", onClose);
|
|
4815
|
-
if (!closed) response.end();
|
|
4816
|
-
}
|
|
4817
|
-
};
|
|
4818
|
-
const server = (0, import_node_http.createServer)((request, response) => {
|
|
4819
|
-
void (async () => {
|
|
4820
|
-
const url = new URL(request.url ?? "/", "http://localhost");
|
|
4821
|
-
const turnPath = /^\/turns\/([^/]+)\/(events|abort|steer)$/u.exec(url.pathname);
|
|
4822
|
-
if (request.method === "GET" && url.pathname === "/health") {
|
|
4823
|
-
const health = {
|
|
4824
|
-
ok: true,
|
|
4825
|
-
protocolVersion: TURN_PROTOCOL_VERSION,
|
|
4826
|
-
busy: busy(),
|
|
4827
|
-
turnId: current?.id ?? null
|
|
4828
|
-
};
|
|
4829
|
-
return sendJson(response, 200, health);
|
|
4830
|
-
}
|
|
4831
|
-
if (request.method === "POST" && url.pathname === "/turns") {
|
|
4832
|
-
const { status, body } = await startTurn(parseStartTurn(await readJsonBody(request)));
|
|
4833
|
-
return sendJson(response, status, body);
|
|
4834
|
-
}
|
|
4835
|
-
if (turnPath) {
|
|
4836
|
-
const turn = findTurn(decodeURIComponent(turnPath[1]));
|
|
4837
|
-
if (!turn) return sendJson(response, 404, { error: "Unknown turn." });
|
|
4838
|
-
if (request.method === "GET" && turnPath[2] === "events") {
|
|
4839
|
-
const afterParam = url.searchParams.get("after");
|
|
4840
|
-
const after = afterParam === null ? -1 : Number(afterParam);
|
|
4841
|
-
if (!Number.isSafeInteger(after) || after < -1) {
|
|
4842
|
-
return sendJson(response, 400, { error: "after must be an integer of at least -1." });
|
|
4843
|
-
}
|
|
4844
|
-
return streamTurn(turn, after, request, response);
|
|
4845
|
-
}
|
|
4846
|
-
if (request.method === "POST" && turnPath[2] === "abort") {
|
|
4847
|
-
if (!turn.ending && !turn.finishing && !turn.abortRequested) {
|
|
4848
|
-
turn.abortRequested = true;
|
|
4849
|
-
turn.closed = true;
|
|
4850
|
-
reclaimSteers(turn);
|
|
4851
|
-
if (turn === current) void currentSessionAbort?.().catch(() => void 0);
|
|
4852
|
-
endAfterGrace(turn, "aborted");
|
|
4853
|
-
}
|
|
4854
|
-
return sendJson(response, 202, { turnId: turn.id, ended: turn.ended });
|
|
4855
|
-
}
|
|
4856
|
-
if (request.method === "POST" && turnPath[2] === "steer") {
|
|
4857
|
-
const { steerId, message } = parseSteerTurn(await readJsonBody(request));
|
|
4858
|
-
const known = turn.steers.get(steerId);
|
|
4859
|
-
if (!known && (turn !== current || turn.closed)) {
|
|
4860
|
-
return sendJson(response, 409, { error: "The turn is no longer running.", turnId: turn.id });
|
|
4861
|
-
}
|
|
4862
|
-
const steer = known ?? acceptSteer(turn, steerId, message);
|
|
4863
|
-
await steer.settled;
|
|
4864
|
-
if (steer.state === "failed") throw steer.error;
|
|
4865
|
-
if (steer.state === "undelivered" && !turn.closed) {
|
|
4866
|
-
return sendJson(response, 501, { error: "The session does not take steering messages." });
|
|
4867
|
-
}
|
|
4868
|
-
if (steer.late || steer.state === "undelivered") {
|
|
4869
|
-
return sendJson(response, 409, { error: "The turn is no longer running.", turnId: turn.id });
|
|
4870
|
-
}
|
|
4871
|
-
return sendJson(response, known ? 200 : 202, {
|
|
4872
|
-
turnId: turn.id,
|
|
4873
|
-
steerId,
|
|
4874
|
-
...steer.state === "handled" ? { handled: true } : {}
|
|
4875
|
-
});
|
|
4876
|
-
}
|
|
4877
|
-
}
|
|
4878
|
-
sendJson(response, 404, { error: "Not found." });
|
|
4879
|
-
})().catch((error) => {
|
|
4880
|
-
if (response.headersSent) {
|
|
4881
|
-
response.destroy();
|
|
4882
|
-
return;
|
|
4883
|
-
}
|
|
4884
|
-
const status = error instanceof RequestError ? error.status : 500;
|
|
4885
|
-
sendJson(response, status, { error: error instanceof Error ? error.message : String(error) });
|
|
4886
|
-
});
|
|
4887
|
-
});
|
|
4888
|
-
const port = options.port ?? (Number(process.env.NECKBEARD_PORT) || DEFAULT_PORT2);
|
|
4889
|
-
await new Promise((resolve2, reject) => {
|
|
4890
|
-
server.once("error", reject);
|
|
4891
|
-
server.listen(port, options.host ?? "0.0.0.0", () => {
|
|
4892
|
-
server.off("error", reject);
|
|
4893
|
-
resolve2();
|
|
4894
|
-
});
|
|
4895
|
-
});
|
|
4896
|
-
return {
|
|
4897
|
-
port: server.address().port,
|
|
4898
|
-
close: () => new Promise((resolve2, reject) => {
|
|
4899
|
-
server.closeAllConnections();
|
|
4900
|
-
server.close((error) => error ? reject(error) : resolve2());
|
|
4901
|
-
})
|
|
4902
|
-
};
|
|
4671
|
+
var insideEntry = "agent-neckbeard/inside";
|
|
4672
|
+
async function serve({ createSession, ...options }) {
|
|
4673
|
+
const inside = await import(
|
|
4674
|
+
/* webpackIgnore: true */
|
|
4675
|
+
insideEntry
|
|
4676
|
+
);
|
|
4677
|
+
return inside.serveConversation(createSession, options);
|
|
4903
4678
|
}
|
|
4904
4679
|
|
|
4905
4680
|
// src/define.ts
|
|
4906
4681
|
var SKILLS_DIR = "/app/.agents/skills";
|
|
4907
|
-
var
|
|
4908
|
-
"NECKBEARD_IMAGE_TAG",
|
|
4909
|
-
"GITHUB_SHA",
|
|
4910
|
-
"CI_COMMIT_SHA",
|
|
4911
|
-
"BITBUCKET_COMMIT",
|
|
4912
|
-
"CODEBUILD_RESOLVED_SOURCE_VERSION",
|
|
4913
|
-
"BUILDKITE_COMMIT",
|
|
4914
|
-
"CIRCLE_SHA1",
|
|
4915
|
-
"CF_PAGES_COMMIT_SHA",
|
|
4916
|
-
"HEROKU_BUILD_COMMIT",
|
|
4917
|
-
"HEROKU_SLUG_COMMIT",
|
|
4918
|
-
"RAILWAY_GIT_COMMIT_SHA",
|
|
4919
|
-
"RENDER_GIT_COMMIT",
|
|
4920
|
-
"VERCEL_GIT_COMMIT_SHA",
|
|
4921
|
-
"SOURCE_VERSION",
|
|
4922
|
-
"GIT_COMMIT"
|
|
4923
|
-
];
|
|
4924
|
-
function resolveImageTag(env = process.env) {
|
|
4925
|
-
for (const name of IMAGE_TAG_ENV_VARS) {
|
|
4926
|
-
const value = env[name]?.trim();
|
|
4927
|
-
if (value && value !== name) return value;
|
|
4928
|
-
}
|
|
4929
|
-
return void 0;
|
|
4930
|
-
}
|
|
4931
|
-
var PI_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
4682
|
+
var insideEntry2 = "agent-neckbeard/inside";
|
|
4932
4683
|
var definedAgentMarker = /* @__PURE__ */ Symbol.for("agent-neckbeard.DefinedAgent");
|
|
4933
|
-
var
|
|
4684
|
+
var AgentImage = class {
|
|
4934
4685
|
constructor(definition) {
|
|
4935
4686
|
this.definition = definition;
|
|
4936
4687
|
if (!definition || typeof definition !== "object") throw new ConfigurationError("Agent definition must be an object.");
|
|
@@ -4940,20 +4691,21 @@ var DefinedAgent = class {
|
|
|
4940
4691
|
if (Boolean(definition.pi) === Boolean(definition.createSession)) {
|
|
4941
4692
|
throw new ConfigurationError(`Agent ${definition.name} needs exactly one of pi and createSession.`);
|
|
4942
4693
|
}
|
|
4694
|
+
if (definition.createSession && definition.maxTurnDurationMs !== void 0) {
|
|
4695
|
+
throw new ConfigurationError("Set the custom session deadline in openInsideConversation(pi, models, maxTurnDurationMs).");
|
|
4696
|
+
}
|
|
4943
4697
|
if (!definition.image && !definition.registry) {
|
|
4944
4698
|
throw new ConfigurationError(`Agent ${definition.name} needs a registry or an image.`);
|
|
4945
4699
|
}
|
|
4946
4700
|
}
|
|
4947
4701
|
[definedAgentMarker] = true;
|
|
4948
|
-
client;
|
|
4949
|
-
braintrustChecked = false;
|
|
4950
4702
|
get name() {
|
|
4951
4703
|
return this.definition.name;
|
|
4952
4704
|
}
|
|
4953
4705
|
/** The image this host runs: `image`, else `<registry>/<name>:<tag>` with the tag `resolveImageTag()` finds. */
|
|
4954
4706
|
imageRef(tag = resolveImageTag()) {
|
|
4955
|
-
const { image, registry, name } = this.definition;
|
|
4956
|
-
if (
|
|
4707
|
+
const { image: image2, registry, name } = this.definition;
|
|
4708
|
+
if (image2) return image2;
|
|
4957
4709
|
if (!tag) {
|
|
4958
4710
|
throw new ConfigurationError(
|
|
4959
4711
|
`Set NECKBEARD_IMAGE_TAG to choose agent ${name}'s image, or deploy from a platform that names the commit, such as RENDER_GIT_COMMIT.`
|
|
@@ -4961,16 +4713,37 @@ var DefinedAgent = class {
|
|
|
4961
4713
|
}
|
|
4962
4714
|
return `${registry.replace(/\/+$/u, "")}/${name}:${tag}`;
|
|
4963
4715
|
}
|
|
4716
|
+
};
|
|
4717
|
+
var DefinedHostAgent = class extends AgentImage {
|
|
4718
|
+
constructor(definition) {
|
|
4719
|
+
super(definition);
|
|
4720
|
+
if (!definition.pi || definition.sandbox || definition.env) {
|
|
4721
|
+
throw new ConfigurationError("Harness-outside-sandbox mode requires pi and takes its storage and execution environment at startup.");
|
|
4722
|
+
}
|
|
4723
|
+
}
|
|
4724
|
+
async start(options, context) {
|
|
4725
|
+
const durableEntry = "agent-neckbeard/durable";
|
|
4726
|
+
const durable = await import(
|
|
4727
|
+
/* webpackIgnore: true */
|
|
4728
|
+
durableEntry
|
|
4729
|
+
);
|
|
4730
|
+
return durable.hostSession(this.definition, options, context);
|
|
4731
|
+
}
|
|
4732
|
+
};
|
|
4733
|
+
var DefinedAgent = class extends AgentImage {
|
|
4734
|
+
client;
|
|
4735
|
+
braintrustChecked = false;
|
|
4964
4736
|
/** The `Agent` for an image, by default the one this host runs. */
|
|
4965
|
-
forImage(
|
|
4737
|
+
forImage(image2 = this.imageRef()) {
|
|
4966
4738
|
const { definition } = this;
|
|
4967
4739
|
const sandbox = typeof definition.sandbox === "function" ? definition.sandbox() : definition.sandbox;
|
|
4968
|
-
|
|
4740
|
+
if (!sandbox) throw new ConfigurationError("An inside-sandbox agent needs a sandbox provider.");
|
|
4741
|
+
const env = typeof definition.env === "function" ? definition.env() : definition.env;
|
|
4969
4742
|
return new Agent({
|
|
4970
4743
|
name: definition.name,
|
|
4971
|
-
image,
|
|
4744
|
+
image: image2,
|
|
4972
4745
|
sandbox,
|
|
4973
|
-
...
|
|
4746
|
+
...env ? { env } : {},
|
|
4974
4747
|
...definition.command ? { command: definition.command } : {},
|
|
4975
4748
|
...definition.port === void 0 ? {} : { port: definition.port },
|
|
4976
4749
|
...definition.startTimeoutMs === void 0 ? {} : { startTimeoutMs: definition.startTimeoutMs },
|
|
@@ -4987,28 +4760,25 @@ var DefinedAgent = class {
|
|
|
4987
4760
|
prepare(options) {
|
|
4988
4761
|
return this.agent.prepare(options);
|
|
4989
4762
|
}
|
|
4990
|
-
start(options) {
|
|
4991
|
-
|
|
4763
|
+
async start(options) {
|
|
4764
|
+
const { pi } = this.definition;
|
|
4765
|
+
if (pi) {
|
|
4766
|
+
const sessionId = options?.sessionId;
|
|
4767
|
+
if (pi.persist && sessionId === void 0) throw new ConfigurationError(`Agent ${this.name} persists its session, so start() needs a sessionId.`);
|
|
4768
|
+
if (!pi.persist && sessionId !== void 0) throw new ConfigurationError(`Agent ${this.name} takes a sessionId only with pi.persist.`);
|
|
4769
|
+
if (sessionId !== void 0 && (typeof sessionId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(sessionId))) {
|
|
4770
|
+
throw new ConfigurationError("A sessionId may contain only letters, digits, underscores and dashes.");
|
|
4771
|
+
}
|
|
4772
|
+
}
|
|
4773
|
+
if (pi && !this.braintrustChecked) {
|
|
4992
4774
|
this.braintrustChecked = true;
|
|
4993
|
-
const
|
|
4994
|
-
readBraintrustSettings({ ...filterDefined(
|
|
4775
|
+
const env = typeof this.definition.env === "function" ? this.definition.env() : this.definition.env;
|
|
4776
|
+
readBraintrustSettings({ ...filterDefined(env), ...filterDefined(options?.env) }, `for agent ${this.name}'s sandboxes`);
|
|
4995
4777
|
}
|
|
4996
4778
|
return this.agent.start(options);
|
|
4997
4779
|
}
|
|
4998
|
-
|
|
4999
|
-
return this.agent.
|
|
5000
|
-
}
|
|
5001
|
-
run(sandboxId, turn, options) {
|
|
5002
|
-
return this.agent.run(sandboxId, turn, options);
|
|
5003
|
-
}
|
|
5004
|
-
events(sandboxId, turnId, options) {
|
|
5005
|
-
return this.agent.events(sandboxId, turnId, options);
|
|
5006
|
-
}
|
|
5007
|
-
abort(sandboxId, turnId, signal) {
|
|
5008
|
-
return this.agent.abort(sandboxId, turnId, signal);
|
|
5009
|
-
}
|
|
5010
|
-
steer(sandboxId, turnId, steer, signal) {
|
|
5011
|
-
return this.agent.steer(sandboxId, turnId, steer, signal);
|
|
4780
|
+
attach(sandboxId, options) {
|
|
4781
|
+
return this.agent.attach(sandboxId, options);
|
|
5012
4782
|
}
|
|
5013
4783
|
health(sandboxId, signal) {
|
|
5014
4784
|
return this.agent.health(sandboxId, signal);
|
|
@@ -5027,86 +4797,33 @@ var DefinedAgent = class {
|
|
|
5027
4797
|
}
|
|
5028
4798
|
/** Where a persisted session's file is in a sandbox whose home is `homeDir`, as for copying it out and back. */
|
|
5029
4799
|
sessionFilePath(homeDir, sessionId) {
|
|
5030
|
-
return import_node_path.default.posix.join(homeDir, "agent", ".pi", "sessions", `${sessionId}.
|
|
4800
|
+
return import_node_path.default.posix.join(homeDir, "agent", ".pi", "sessions", `${sessionId}.sqlite`);
|
|
5031
4801
|
}
|
|
5032
4802
|
/** Serves the agent's session; the image's entry point, which `neckbeard build` generates, calls it. */
|
|
5033
4803
|
serve(options = {}) {
|
|
5034
4804
|
const { definition } = this;
|
|
5035
4805
|
const { pi } = definition;
|
|
4806
|
+
if (options.createSession && definition.maxTurnDurationMs !== void 0) {
|
|
4807
|
+
throw new ConfigurationError("A custom serve factory must set its own deadline. Remove the definition-level maxTurnDurationMs.");
|
|
4808
|
+
}
|
|
5036
4809
|
return serve({
|
|
5037
|
-
createSession: pi ? () =>
|
|
5038
|
-
|
|
5039
|
-
|
|
4810
|
+
createSession: pi ? async () => (await import(
|
|
4811
|
+
/* webpackIgnore: true */
|
|
4812
|
+
insideEntry2
|
|
4813
|
+
)).openInsideConversation(pi, void 0, definition.maxTurnDurationMs) : definition.createSession,
|
|
5040
4814
|
...options
|
|
5041
4815
|
});
|
|
5042
4816
|
}
|
|
5043
4817
|
};
|
|
5044
4818
|
function defineAgent(definition) {
|
|
5045
|
-
|
|
4819
|
+
if (definition && "placement" in definition) throw new ConfigurationError("Set mode instead of placement.");
|
|
4820
|
+
if (definition?.mode === "harness-outside-sandbox") return new DefinedHostAgent(definition);
|
|
4821
|
+
if (definition?.mode === "harness-inside-sandbox") return new DefinedAgent(definition);
|
|
4822
|
+
throw new ConfigurationError("Set mode to harness-inside-sandbox or harness-outside-sandbox.");
|
|
5046
4823
|
}
|
|
5047
4824
|
function isDefinedAgent(value) {
|
|
5048
4825
|
return typeof value === "object" && value !== null && definedAgentMarker in value;
|
|
5049
4826
|
}
|
|
5050
|
-
async function createPiSession(config) {
|
|
5051
|
-
const home = import_node_os.default.homedir();
|
|
5052
|
-
const cwd = import_node_path.default.resolve(home, config.cwd ?? "workspace");
|
|
5053
|
-
await (0, import_promises.mkdir)(cwd, { recursive: true });
|
|
5054
|
-
process.env.NECKBEARD_CWD = cwd;
|
|
5055
|
-
const agentDir = import_node_path.default.join(home, "agent", ".pi");
|
|
5056
|
-
const loaded = await import(
|
|
5057
|
-
/* webpackIgnore: true */
|
|
5058
|
-
PI_PACKAGE
|
|
5059
|
-
);
|
|
5060
|
-
const braintrustSettings = readBraintrustSettings(process.env, "in the sandbox");
|
|
5061
|
-
const braintrust = braintrustSettings && await startBraintrust(braintrustSettings);
|
|
5062
|
-
const pi = braintrust ? braintrust.wrapPi(loaded) : loaded;
|
|
5063
|
-
const modelRuntime = await pi.ModelRuntime.create({ modelsPath: null });
|
|
5064
|
-
const separator = config.model.indexOf("/");
|
|
5065
|
-
const model = separator > 0 ? modelRuntime.getModel(config.model.slice(0, separator), config.model.slice(separator + 1)) : void 0;
|
|
5066
|
-
if (!model) throw new ConfigurationError(`Pi has no model ${config.model}; name it as provider/model.`);
|
|
5067
|
-
const settingsManager = pi.SettingsManager.inMemory();
|
|
5068
|
-
const resourceLoader = new pi.DefaultResourceLoader({
|
|
5069
|
-
cwd,
|
|
5070
|
-
agentDir,
|
|
5071
|
-
settingsManager,
|
|
5072
|
-
additionalSkillPaths: [SKILLS_DIR],
|
|
5073
|
-
noSkills: true,
|
|
5074
|
-
noExtensions: true,
|
|
5075
|
-
noPromptTemplates: true,
|
|
5076
|
-
noContextFiles: true,
|
|
5077
|
-
systemPrompt: config.systemPrompt
|
|
5078
|
-
});
|
|
5079
|
-
await resourceLoader.reload();
|
|
5080
|
-
let sessionManager;
|
|
5081
|
-
if (config.persist) {
|
|
5082
|
-
const sessionId = process.env.NECKBEARD_SESSION_ID;
|
|
5083
|
-
if (!sessionId) throw new ConfigurationError("A persisted Pi session needs the sessionId passed to start().");
|
|
5084
|
-
const sessionFile = import_node_path.default.join(agentDir, "sessions", `${sessionId}.jsonl`);
|
|
5085
|
-
sessionManager = pi.SessionManager.open(sessionFile, import_node_path.default.dirname(sessionFile), cwd);
|
|
5086
|
-
} else {
|
|
5087
|
-
sessionManager = pi.SessionManager.inMemory(cwd);
|
|
5088
|
-
}
|
|
5089
|
-
const { session } = await pi.createAgentSession({
|
|
5090
|
-
cwd,
|
|
5091
|
-
agentDir,
|
|
5092
|
-
model,
|
|
5093
|
-
modelRuntime,
|
|
5094
|
-
resourceLoader,
|
|
5095
|
-
settingsManager,
|
|
5096
|
-
sessionManager,
|
|
5097
|
-
...config.thinkingLevel ? { thinkingLevel: config.thinkingLevel } : {},
|
|
5098
|
-
...config.tools ? { tools: config.tools } : {}
|
|
5099
|
-
});
|
|
5100
|
-
if (!braintrust) return session;
|
|
5101
|
-
return {
|
|
5102
|
-
subscribe: (listener) => session.subscribe(listener),
|
|
5103
|
-
prompt: (text) => session.prompt(text),
|
|
5104
|
-
abort: () => session.abort(),
|
|
5105
|
-
steer: (text) => session.steer(text),
|
|
5106
|
-
clearQueue: () => session.clearQueue(),
|
|
5107
|
-
afterTurn: () => braintrust.flush()
|
|
5108
|
-
};
|
|
5109
|
-
}
|
|
5110
4827
|
|
|
5111
4828
|
// src/providers/docker.ts
|
|
5112
4829
|
var import_node_child_process = require("child_process");
|
|
@@ -5138,7 +4855,7 @@ function validateDockerOptions(options, mode, failure) {
|
|
|
5138
4855
|
}
|
|
5139
4856
|
}
|
|
5140
4857
|
function exportLines(envs) {
|
|
5141
|
-
return Object.entries(envs ?? {}).filter((
|
|
4858
|
+
return Object.entries(envs ?? {}).filter((entry2) => entry2[1] !== void 0).map(([name, value]) => `export ${name}=${shellQuote(value)}
|
|
5142
4859
|
`).join("");
|
|
5143
4860
|
}
|
|
5144
4861
|
var runDockerCli = (args, options) => new Promise((resolve2, reject) => {
|
|
@@ -5161,14 +4878,14 @@ var runDockerCli = (args, options) => new Promise((resolve2, reject) => {
|
|
|
5161
4878
|
child.stdout.on("data", (chunk) => {
|
|
5162
4879
|
stdout.push(chunk);
|
|
5163
4880
|
if (options.onStdout) {
|
|
5164
|
-
const
|
|
5165
|
-
if (
|
|
4881
|
+
const text2 = stdoutDecoder.write(chunk);
|
|
4882
|
+
if (text2) options.onStdout(text2);
|
|
5166
4883
|
}
|
|
5167
4884
|
});
|
|
5168
4885
|
child.stderr.on("data", (chunk) => {
|
|
5169
|
-
const
|
|
5170
|
-
stderr +=
|
|
5171
|
-
if (
|
|
4886
|
+
const text2 = stderrDecoder.write(chunk);
|
|
4887
|
+
stderr += text2;
|
|
4888
|
+
if (text2) options.onStderr?.(text2);
|
|
5172
4889
|
});
|
|
5173
4890
|
child.on("error", (error) => settle(() => reject(
|
|
5174
4891
|
Reflect.get(error, "code") === "ENOENT" ? new Error("The Docker provider requires the `docker` CLI on PATH.") : error
|
|
@@ -5243,8 +4960,8 @@ async function closeTunnels(containerId) {
|
|
|
5243
4960
|
}
|
|
5244
4961
|
}
|
|
5245
4962
|
var DockerSandboxHandle = class _DockerSandboxHandle {
|
|
5246
|
-
constructor(
|
|
5247
|
-
this.id =
|
|
4963
|
+
constructor(id2, managed, failure, cli = runDockerCli) {
|
|
4964
|
+
this.id = id2;
|
|
5248
4965
|
this.managed = managed;
|
|
5249
4966
|
this.failure = failure;
|
|
5250
4967
|
this.cli = cli;
|
|
@@ -5296,11 +5013,11 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
|
|
|
5296
5013
|
options.template ?? DOCKER_DEFAULT_TEMPLATE,
|
|
5297
5014
|
String(lifetimeSeconds)
|
|
5298
5015
|
], { timeoutMs: DOCKER_CREATE_TIMEOUT_MS });
|
|
5299
|
-
const
|
|
5300
|
-
if (created.exitCode !== 0 || !/^[a-f0-9]{12,64}$/u.test(
|
|
5016
|
+
const id2 = created.stdout.toString("utf8").trim().split("\n").pop() ?? "";
|
|
5017
|
+
if (created.exitCode !== 0 || !/^[a-f0-9]{12,64}$/u.test(id2)) {
|
|
5301
5018
|
throw failure(`Failed to create Docker sandbox: ${created.stderr.trim() || "no container ID returned."}`);
|
|
5302
5019
|
}
|
|
5303
|
-
const handle = new _DockerSandboxHandle(
|
|
5020
|
+
const handle = new _DockerSandboxHandle(id2, true, failure, cli);
|
|
5304
5021
|
try {
|
|
5305
5022
|
await handle.writeFile(DOCKER_ENV_FILE, exportLines(options.envs));
|
|
5306
5023
|
await handle.ensureTools();
|
|
@@ -5340,10 +5057,10 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
|
|
|
5340
5057
|
DOCKER_BOOTSTRAP_TIMEOUT_MS
|
|
5341
5058
|
);
|
|
5342
5059
|
}
|
|
5343
|
-
async control(label, script, args = [],
|
|
5060
|
+
async control(label, script, args = [], input2, timeoutMs = DOCKER_CONTROL_TIMEOUT_MS) {
|
|
5344
5061
|
const result = await this.cli(
|
|
5345
5062
|
["exec", "-i", "--user", "root", this.id, "/bin/sh", "-c", script, "sh", ...args],
|
|
5346
|
-
{ input, timeoutMs }
|
|
5063
|
+
{ input: input2, timeoutMs }
|
|
5347
5064
|
);
|
|
5348
5065
|
if (result.exitCode !== 0) {
|
|
5349
5066
|
throw this.failure(`${label} failed: ${result.stderr.trim() || `exit code ${result.exitCode}`}`);
|
|
@@ -5354,8 +5071,8 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
|
|
|
5354
5071
|
await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path2]);
|
|
5355
5072
|
}
|
|
5356
5073
|
async writeFile(path2, content) {
|
|
5357
|
-
const
|
|
5358
|
-
await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path2],
|
|
5074
|
+
const input2 = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
|
|
5075
|
+
await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path2], input2, DOCKER_FILE_TIMEOUT_MS);
|
|
5359
5076
|
}
|
|
5360
5077
|
async readFile(path2) {
|
|
5361
5078
|
return (await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
|
|
@@ -5435,49 +5152,49 @@ var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
|
|
|
5435
5152
|
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
5436
5153
|
var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
|
|
5437
5154
|
var NeckbeardError = class extends Error {
|
|
5438
|
-
constructor(
|
|
5439
|
-
super(
|
|
5155
|
+
constructor(message2) {
|
|
5156
|
+
super(message2);
|
|
5440
5157
|
this.name = "NeckbeardError";
|
|
5441
5158
|
}
|
|
5442
5159
|
};
|
|
5443
5160
|
var DeploymentError = class extends NeckbeardError {
|
|
5444
5161
|
/** A sandbox the failure left behind, for `kill()`. */
|
|
5445
|
-
constructor(
|
|
5446
|
-
super(
|
|
5162
|
+
constructor(message2, cause, sandboxId) {
|
|
5163
|
+
super(message2);
|
|
5447
5164
|
this.cause = cause;
|
|
5448
5165
|
this.sandboxId = sandboxId;
|
|
5449
5166
|
this.name = "DeploymentError";
|
|
5450
5167
|
}
|
|
5451
5168
|
};
|
|
5169
|
+
var SandboxGoneError = class extends DeploymentError {
|
|
5170
|
+
constructor(message2, cause) {
|
|
5171
|
+
super(message2, cause);
|
|
5172
|
+
this.name = "SandboxGoneError";
|
|
5173
|
+
}
|
|
5174
|
+
};
|
|
5452
5175
|
var ValidationError = class extends NeckbeardError {
|
|
5453
|
-
constructor(
|
|
5454
|
-
super(
|
|
5176
|
+
constructor(message2, cause) {
|
|
5177
|
+
super(message2);
|
|
5455
5178
|
this.cause = cause;
|
|
5456
5179
|
this.name = "ValidationError";
|
|
5457
5180
|
}
|
|
5458
5181
|
};
|
|
5459
5182
|
var ExecutionError = class extends NeckbeardError {
|
|
5460
|
-
constructor(
|
|
5461
|
-
super(
|
|
5183
|
+
constructor(message2, cause) {
|
|
5184
|
+
super(message2);
|
|
5462
5185
|
this.cause = cause;
|
|
5463
5186
|
this.name = "ExecutionError";
|
|
5464
5187
|
}
|
|
5465
5188
|
};
|
|
5466
5189
|
var RuntimeBusyError = class extends ExecutionError {
|
|
5467
|
-
constructor(
|
|
5468
|
-
super(
|
|
5190
|
+
constructor(message2) {
|
|
5191
|
+
super(message2);
|
|
5469
5192
|
this.name = "RuntimeBusyError";
|
|
5470
5193
|
}
|
|
5471
5194
|
};
|
|
5472
|
-
var TurnLostError = class extends ExecutionError {
|
|
5473
|
-
constructor(message) {
|
|
5474
|
-
super(message);
|
|
5475
|
-
this.name = "TurnLostError";
|
|
5476
|
-
}
|
|
5477
|
-
};
|
|
5478
5195
|
var ConfigurationError = class extends NeckbeardError {
|
|
5479
|
-
constructor(
|
|
5480
|
-
super(
|
|
5196
|
+
constructor(message2) {
|
|
5197
|
+
super(message2);
|
|
5481
5198
|
this.name = "ConfigurationError";
|
|
5482
5199
|
}
|
|
5483
5200
|
};
|
|
@@ -5768,10 +5485,10 @@ function traceSourceDependencyFiles(appDir, sourceFiles) {
|
|
|
5768
5485
|
files.add(file);
|
|
5769
5486
|
}
|
|
5770
5487
|
};
|
|
5771
|
-
for (const [inputPath,
|
|
5488
|
+
for (const [inputPath, input2] of Object.entries(metafile.inputs)) {
|
|
5772
5489
|
const absoluteInput = resolveMetafileInput(appDir, inputPath);
|
|
5773
5490
|
addFile(absoluteInput);
|
|
5774
|
-
for (const importRecord of
|
|
5491
|
+
for (const importRecord of input2.imports ?? []) {
|
|
5775
5492
|
const importPath = importRecord.original ?? importRecord.path;
|
|
5776
5493
|
if (!isBareModuleImport(importPath) || isBuiltinModule(importPath)) {
|
|
5777
5494
|
continue;
|
|
@@ -5816,8 +5533,8 @@ function findFiles(root) {
|
|
|
5816
5533
|
return [];
|
|
5817
5534
|
}
|
|
5818
5535
|
const files = [];
|
|
5819
|
-
for (const
|
|
5820
|
-
files.push(...findFiles((0, import_node_path2.join)(root,
|
|
5536
|
+
for (const entry2 of (0, import_node_fs.readdirSync)(root)) {
|
|
5537
|
+
files.push(...findFiles((0, import_node_path2.join)(root, entry2)));
|
|
5821
5538
|
}
|
|
5822
5539
|
return files;
|
|
5823
5540
|
}
|
|
@@ -5825,7 +5542,7 @@ function directFiles(root) {
|
|
|
5825
5542
|
if (!(0, import_node_fs.existsSync)(root) || !(0, import_node_fs.statSync)(root).isDirectory()) {
|
|
5826
5543
|
return [];
|
|
5827
5544
|
}
|
|
5828
|
-
return (0, import_node_fs.readdirSync)(root).map((
|
|
5545
|
+
return (0, import_node_fs.readdirSync)(root).map((entry2) => (0, import_node_path2.join)(root, entry2)).filter((file) => (0, import_node_fs.statSync)(file).isFile());
|
|
5829
5546
|
}
|
|
5830
5547
|
function routePathFromTraceFile(outputPath, traceFile) {
|
|
5831
5548
|
const relativeTrace = (0, import_node_path2.relative)(outputPath, traceFile).replace(/\\/g, "/");
|
|
@@ -5887,20 +5604,20 @@ function asRecord(value) {
|
|
|
5887
5604
|
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
5888
5605
|
}
|
|
5889
5606
|
function normalizeNonEmptyStrings(name, value) {
|
|
5890
|
-
const
|
|
5891
|
-
if (
|
|
5607
|
+
const values2 = Array.isArray(value) ? value : [value];
|
|
5608
|
+
if (values2.length === 0) {
|
|
5892
5609
|
throw new ConfigurationError(`${name} must contain at least one entry.`);
|
|
5893
5610
|
}
|
|
5894
|
-
for (const
|
|
5895
|
-
if (typeof
|
|
5611
|
+
for (const entry2 of values2) {
|
|
5612
|
+
if (typeof entry2 !== "string" || entry2.trim() === "") {
|
|
5896
5613
|
throw new ConfigurationError(`${name} entries must be non-empty strings.`);
|
|
5897
5614
|
}
|
|
5898
5615
|
}
|
|
5899
|
-
return
|
|
5616
|
+
return values2;
|
|
5900
5617
|
}
|
|
5901
|
-
function mergeStringArray(existing,
|
|
5618
|
+
function mergeStringArray(existing, values2) {
|
|
5902
5619
|
const current = Array.isArray(existing) ? existing.filter((value) => typeof value === "string") : [];
|
|
5903
|
-
return [.../* @__PURE__ */ new Set([...current, ...
|
|
5620
|
+
return [.../* @__PURE__ */ new Set([...current, ...values2])];
|
|
5904
5621
|
}
|
|
5905
5622
|
function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
|
|
5906
5623
|
const includes = { ...asRecord(existing) };
|
|
@@ -5979,12 +5696,12 @@ function validateLocalDirectoriesConfig(value) {
|
|
|
5979
5696
|
if (!Array.isArray(value)) {
|
|
5980
5697
|
throw new ConfigurationError("localDirectories must be an array when provided.");
|
|
5981
5698
|
}
|
|
5982
|
-
for (const [index,
|
|
5699
|
+
for (const [index, entry2] of value.entries()) {
|
|
5983
5700
|
const name = `localDirectories[${index}]`;
|
|
5984
|
-
if (!
|
|
5701
|
+
if (!entry2 || typeof entry2 !== "object" || Array.isArray(entry2)) {
|
|
5985
5702
|
throw new ConfigurationError(`${name} must be an object.`);
|
|
5986
5703
|
}
|
|
5987
|
-
const candidate =
|
|
5704
|
+
const candidate = entry2;
|
|
5988
5705
|
if (typeof candidate.source !== "string" || candidate.source.trim() === "") {
|
|
5989
5706
|
throw new ConfigurationError(`${name}.source must be a non-empty string.`);
|
|
5990
5707
|
}
|
|
@@ -6008,9 +5725,9 @@ function validateAgentConfig(config) {
|
|
|
6008
5725
|
throw new ConfigurationError('sandbox.provider must be "e2b", "daytona", "modal", or "docker".');
|
|
6009
5726
|
}
|
|
6010
5727
|
if (config.sandbox.provider === "modal") {
|
|
6011
|
-
validateModalOptions(config.sandbox, "agent", (
|
|
5728
|
+
validateModalOptions(config.sandbox, "agent", (message2) => new ConfigurationError(message2));
|
|
6012
5729
|
} else if (config.sandbox.provider === "docker") {
|
|
6013
|
-
validateDockerOptions(config.sandbox, "agent", (
|
|
5730
|
+
validateDockerOptions(config.sandbox, "agent", (message2) => new ConfigurationError(message2));
|
|
6014
5731
|
} else if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
|
|
6015
5732
|
throw new ConfigurationError("sandbox.template must be a non-empty string.");
|
|
6016
5733
|
}
|
|
@@ -6153,9 +5870,9 @@ async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HE
|
|
|
6153
5870
|
}
|
|
6154
5871
|
await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
|
|
6155
5872
|
}
|
|
6156
|
-
const
|
|
5873
|
+
const message2 = lastError instanceof Error ? lastError.message : String(lastError);
|
|
6157
5874
|
throw new DeploymentError(
|
|
6158
|
-
`Server did not become healthy at ${healthUrl} within ${timeoutMs}ms: ${
|
|
5875
|
+
`Server did not become healthy at ${healthUrl} within ${timeoutMs}ms: ${message2}`
|
|
6159
5876
|
);
|
|
6160
5877
|
}
|
|
6161
5878
|
function requireEnv(name) {
|
|
@@ -6359,7 +6076,7 @@ async function readServerFailureDiagnostics(sandbox, command, environment, signa
|
|
|
6359
6076
|
signal
|
|
6360
6077
|
);
|
|
6361
6078
|
const secrets = Object.entries(environment).filter(
|
|
6362
|
-
(
|
|
6079
|
+
(entry2) => Boolean(entry2[1]) && isConfiguredDiagnosticSecret(entry2[0], entry2[1])
|
|
6363
6080
|
).map(([, value]) => value);
|
|
6364
6081
|
secrets.sort((left, right) => right.length - left.length);
|
|
6365
6082
|
const stdout = redactServerFailureDiagnosticStream(captured.stdout, secrets);
|
|
@@ -6384,12 +6101,12 @@ function providerApiKey(provider, explicitApiKey) {
|
|
|
6384
6101
|
}
|
|
6385
6102
|
async function createProviderSandboxHandle(options) {
|
|
6386
6103
|
if (options.provider === "modal") {
|
|
6387
|
-
validateModalOptions(options, "create", (
|
|
6388
|
-
return ModalSandboxHandle.create(options, (
|
|
6104
|
+
validateModalOptions(options, "create", (message2) => new ConfigurationError(message2));
|
|
6105
|
+
return ModalSandboxHandle.create(options, (message2) => new DeploymentError(message2));
|
|
6389
6106
|
}
|
|
6390
6107
|
if (options.provider === "docker") {
|
|
6391
|
-
validateDockerOptions(options, "create", (
|
|
6392
|
-
return DockerSandboxHandle.create(options, (
|
|
6108
|
+
validateDockerOptions(options, "create", (message2) => new ConfigurationError(message2));
|
|
6109
|
+
return DockerSandboxHandle.create(options, (message2) => new DeploymentError(message2));
|
|
6393
6110
|
}
|
|
6394
6111
|
if (options.provider === "daytona") {
|
|
6395
6112
|
const apiKey2 = providerApiKey("daytona", options.apiKey);
|
|
@@ -6410,7 +6127,7 @@ async function createProviderSandboxHandle(options) {
|
|
|
6410
6127
|
try {
|
|
6411
6128
|
return await DaytonaSandboxHandle.create(
|
|
6412
6129
|
sandbox2,
|
|
6413
|
-
(
|
|
6130
|
+
(message2) => new DeploymentError(message2)
|
|
6414
6131
|
);
|
|
6415
6132
|
} catch (error) {
|
|
6416
6133
|
await sandbox2.delete(
|
|
@@ -6430,44 +6147,57 @@ async function createProviderSandboxHandle(options) {
|
|
|
6430
6147
|
network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
|
|
6431
6148
|
};
|
|
6432
6149
|
const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
|
|
6433
|
-
return new E2bSandboxHandle(sandbox, (
|
|
6150
|
+
return new E2bSandboxHandle(sandbox, (message2) => new DeploymentError(message2));
|
|
6434
6151
|
}
|
|
6435
|
-
async function connectProviderSandboxHandle(options) {
|
|
6152
|
+
async function connectProviderSandboxHandle(options, wake = true) {
|
|
6153
|
+
const gone = (message2, cause) => new SandboxGoneError(message2, cause instanceof Error ? cause : void 0);
|
|
6436
6154
|
if (options.provider === "modal") {
|
|
6437
|
-
validateModalOptions(options, "connect", (
|
|
6438
|
-
return ModalSandboxHandle.connect(options, (
|
|
6155
|
+
validateModalOptions(options, "connect", (message2) => new ConfigurationError(message2));
|
|
6156
|
+
return ModalSandboxHandle.connect(options, (message2) => new DeploymentError(message2), wake ? void 0 : gone);
|
|
6439
6157
|
}
|
|
6440
6158
|
if (options.provider === "docker") {
|
|
6441
|
-
validateDockerOptions(options, "connect", (
|
|
6442
|
-
return DockerSandboxHandle.connect(options, (
|
|
6159
|
+
validateDockerOptions(options, "connect", (message2) => new ConfigurationError(message2));
|
|
6160
|
+
return DockerSandboxHandle.connect(options, (message2) => new DeploymentError(message2));
|
|
6443
6161
|
}
|
|
6444
6162
|
if (options.provider === "daytona") {
|
|
6445
6163
|
const apiKey2 = providerApiKey("daytona", options.apiKey);
|
|
6446
|
-
const { Daytona } = await getDaytona();
|
|
6164
|
+
const { Daytona, DaytonaNotFoundError } = await getDaytona();
|
|
6447
6165
|
const daytona = new Daytona({ apiKey: apiKey2 });
|
|
6448
|
-
const sandbox2 = await daytona.get(options.sandboxId)
|
|
6166
|
+
const sandbox2 = await daytona.get(options.sandboxId).catch((error) => {
|
|
6167
|
+
if (!wake && error instanceof DaytonaNotFoundError) throw gone(`Daytona sandbox ${options.sandboxId} does not exist.`, error);
|
|
6168
|
+
throw error;
|
|
6169
|
+
});
|
|
6449
6170
|
if (sandbox2.state !== "started") {
|
|
6171
|
+
if (!wake) throw gone(`Daytona sandbox ${options.sandboxId} is ${sandbox2.state}, not started.`);
|
|
6450
6172
|
if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
|
|
6451
6173
|
await sandbox2.waitUntilStarted(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
|
|
6452
6174
|
} else {
|
|
6453
6175
|
await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
|
|
6454
6176
|
}
|
|
6455
6177
|
}
|
|
6456
|
-
return DaytonaSandboxHandle.create(sandbox2, (
|
|
6178
|
+
return DaytonaSandboxHandle.create(sandbox2, (message2) => new DeploymentError(message2));
|
|
6457
6179
|
}
|
|
6458
6180
|
const apiKey = providerApiKey("e2b", options.apiKey);
|
|
6459
|
-
const { Sandbox } = await getE2b();
|
|
6181
|
+
const { Sandbox, SandboxNotFoundError } = await getE2b();
|
|
6182
|
+
const absent2 = (error) => {
|
|
6183
|
+
if (!wake && error instanceof SandboxNotFoundError) throw gone(`E2B sandbox ${options.sandboxId} does not exist.`, error);
|
|
6184
|
+
throw error;
|
|
6185
|
+
};
|
|
6186
|
+
if (!wake) {
|
|
6187
|
+
const info = await Sandbox.getInfo(options.sandboxId, { apiKey, requestTimeoutMs: options.requestTimeoutMs }).catch(absent2);
|
|
6188
|
+
if (info.state !== "running") throw gone(`E2B sandbox ${options.sandboxId} is ${info.state}, not running.`);
|
|
6189
|
+
}
|
|
6460
6190
|
const sandbox = await Sandbox.connect(options.sandboxId, {
|
|
6461
6191
|
apiKey,
|
|
6462
6192
|
timeoutMs: options.timeoutMs,
|
|
6463
6193
|
requestTimeoutMs: options.requestTimeoutMs
|
|
6464
|
-
});
|
|
6465
|
-
return new E2bSandboxHandle(sandbox, (
|
|
6194
|
+
}).catch(absent2);
|
|
6195
|
+
return new E2bSandboxHandle(sandbox, (message2) => new DeploymentError(message2));
|
|
6466
6196
|
}
|
|
6467
6197
|
async function destroyProviderSandbox(options) {
|
|
6468
6198
|
if (options.provider === "modal") {
|
|
6469
|
-
validateModalOptions(options, "connect", (
|
|
6470
|
-
return ModalSandboxHandle.destroyById(options, (
|
|
6199
|
+
validateModalOptions(options, "connect", (message2) => new ConfigurationError(message2));
|
|
6200
|
+
return ModalSandboxHandle.destroyById(options, (message2) => new DeploymentError(message2));
|
|
6471
6201
|
}
|
|
6472
6202
|
if (options.provider === "daytona") {
|
|
6473
6203
|
const { Daytona, DaytonaNotFoundError } = await getDaytona();
|
|
@@ -6489,8 +6219,8 @@ var SandboxClient = class _SandboxClient {
|
|
|
6489
6219
|
static async create(options) {
|
|
6490
6220
|
return new _SandboxClient(await createProviderSandboxHandle(options));
|
|
6491
6221
|
}
|
|
6492
|
-
static async connect(options) {
|
|
6493
|
-
return new _SandboxClient(await connectProviderSandboxHandle(options));
|
|
6222
|
+
static async connect(options, mode = {}) {
|
|
6223
|
+
return new _SandboxClient(await connectProviderSandboxHandle(options, mode.wake ?? true));
|
|
6494
6224
|
}
|
|
6495
6225
|
get id() {
|
|
6496
6226
|
return this.handle.id;
|
|
@@ -6535,7 +6265,7 @@ var SandboxClient = class _SandboxClient {
|
|
|
6535
6265
|
}
|
|
6536
6266
|
const normalized = normalizeProviderSandboxDetachedCommandOptions(
|
|
6537
6267
|
options,
|
|
6538
|
-
(
|
|
6268
|
+
(message2) => new ConfigurationError(message2),
|
|
6539
6269
|
{ requireObject: true }
|
|
6540
6270
|
);
|
|
6541
6271
|
return this.handle.startDetachedCommand(command, normalized.options);
|
|
@@ -6716,8 +6446,8 @@ function readConfiguredLocalDirectory(upload) {
|
|
|
6716
6446
|
`${upload.name} could not read local directory: ${currentPath} (${errorMessage(error)})`
|
|
6717
6447
|
);
|
|
6718
6448
|
}
|
|
6719
|
-
for (const
|
|
6720
|
-
const localPath = (0, import_node_path2.join)(currentPath,
|
|
6449
|
+
for (const entry2 of entries) {
|
|
6450
|
+
const localPath = (0, import_node_path2.join)(currentPath, entry2);
|
|
6721
6451
|
const stats = localPathStats(localPath, upload);
|
|
6722
6452
|
if (stats.isDirectory()) {
|
|
6723
6453
|
walk(localPath);
|
|
@@ -6745,8 +6475,8 @@ function readConfiguredLocalDirectory(upload) {
|
|
|
6745
6475
|
return { rootPath, files };
|
|
6746
6476
|
}
|
|
6747
6477
|
function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
|
|
6748
|
-
const uploads = localDirectories.map((
|
|
6749
|
-
...
|
|
6478
|
+
const uploads = localDirectories.map((entry2, index) => ({
|
|
6479
|
+
...entry2,
|
|
6750
6480
|
name: `localDirectories[${index}]`,
|
|
6751
6481
|
rejectSymlinks: true,
|
|
6752
6482
|
preserveRootDirectory: false
|
|
@@ -6839,7 +6569,7 @@ var LegacyBundledAgent = class {
|
|
|
6839
6569
|
this._sourceFile = resolveSourceFile(config.sourceFile);
|
|
6840
6570
|
this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
|
|
6841
6571
|
this.files = config.files ?? [];
|
|
6842
|
-
this.localDirectories = (config.localDirectories ?? []).map((
|
|
6572
|
+
this.localDirectories = (config.localDirectories ?? []).map((entry2) => ({ ...entry2 }));
|
|
6843
6573
|
this.claudeDir = config.claudeDir;
|
|
6844
6574
|
this.envs = config.envs ?? {};
|
|
6845
6575
|
this.build = config.build ?? {};
|
|
@@ -7336,7 +7066,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
7336
7066
|
* const result = await agent.run({ prompt: 'Hello!' }, { sandboxId });
|
|
7337
7067
|
* ```
|
|
7338
7068
|
*/
|
|
7339
|
-
async run(
|
|
7069
|
+
async run(input2, options) {
|
|
7340
7070
|
const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
7341
7071
|
if (this.mode !== "run") {
|
|
7342
7072
|
return {
|
|
@@ -7351,7 +7081,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
7351
7081
|
const connection = await this.resolveRuntimeConnection(options?.sandboxId);
|
|
7352
7082
|
let validatedInput;
|
|
7353
7083
|
try {
|
|
7354
|
-
validatedInput = this.inputSchema.parse(
|
|
7084
|
+
validatedInput = this.inputSchema.parse(input2);
|
|
7355
7085
|
} catch (error) {
|
|
7356
7086
|
throw new ValidationError("Input validation failed.", asError(error));
|
|
7357
7087
|
}
|
|
@@ -7436,7 +7166,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
7436
7166
|
}
|
|
7437
7167
|
if (durability !== void 0 && durability !== "attached") {
|
|
7438
7168
|
throw new ConfigurationError(
|
|
7439
|
-
"LegacyBundledAgent.createSession() creates caller-owned attached sessions.
|
|
7169
|
+
"LegacyBundledAgent.createSession() creates caller-owned attached sessions. Durable sessions are no longer supported."
|
|
7440
7170
|
);
|
|
7441
7171
|
}
|
|
7442
7172
|
if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
|
|
@@ -7455,13 +7185,13 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
7455
7185
|
}
|
|
7456
7186
|
return createAttachedAgentSession({
|
|
7457
7187
|
sandboxId,
|
|
7458
|
-
runPrompt: (
|
|
7188
|
+
runPrompt: (input2, signal2) => this.streamSessionPrompt(input2, sandboxId, signal2),
|
|
7459
7189
|
...signal === void 0 ? {} : { externalSignal: signal },
|
|
7460
|
-
configurationError: (
|
|
7190
|
+
configurationError: (message2) => new ConfigurationError(message2),
|
|
7461
7191
|
abortError: abortSignalError
|
|
7462
7192
|
});
|
|
7463
7193
|
}
|
|
7464
|
-
async *streamSessionPrompt(
|
|
7194
|
+
async *streamSessionPrompt(input2, sandboxId, signal) {
|
|
7465
7195
|
const connection = await this.resolveRuntimeConnection(sandboxId, {
|
|
7466
7196
|
signal,
|
|
7467
7197
|
reuseMatchingCachedConnection: true
|
|
@@ -7469,7 +7199,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
7469
7199
|
const { invokeServer: invokeServer2, InvokeHttpError: InvokeHttpError2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
|
|
7470
7200
|
let validated;
|
|
7471
7201
|
try {
|
|
7472
|
-
validated = this.inputSchema.parse(
|
|
7202
|
+
validated = this.inputSchema.parse(input2);
|
|
7473
7203
|
} catch (error) {
|
|
7474
7204
|
throw new ValidationError("Input validation failed.", asError(error));
|
|
7475
7205
|
}
|
|
@@ -7549,13 +7279,13 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
7549
7279
|
* This compatibility wrapper creates one attached session, streams one turn,
|
|
7550
7280
|
* and closes the local handle afterward.
|
|
7551
7281
|
*/
|
|
7552
|
-
async *invoke(
|
|
7282
|
+
async *invoke(input2, options) {
|
|
7553
7283
|
const session = await this.createSession({
|
|
7554
7284
|
...options?.sandboxId === void 0 ? {} : { sandboxId: options.sandboxId },
|
|
7555
7285
|
...options?.signal === void 0 ? {} : { signal: options.signal }
|
|
7556
7286
|
});
|
|
7557
7287
|
try {
|
|
7558
|
-
yield* session.prompt(
|
|
7288
|
+
yield* session.prompt(input2);
|
|
7559
7289
|
} finally {
|
|
7560
7290
|
await session.close();
|
|
7561
7291
|
}
|
|
@@ -7567,19 +7297,21 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
7567
7297
|
ConfigurationError,
|
|
7568
7298
|
DEFAULT_DEPENDENCIES,
|
|
7569
7299
|
DefinedAgent,
|
|
7300
|
+
DefinedHostAgent,
|
|
7570
7301
|
DeploymentError,
|
|
7571
7302
|
ExecutionError,
|
|
7572
7303
|
LegacyBundledAgent,
|
|
7573
7304
|
NeckbeardError,
|
|
7305
|
+
RemoteAdmissionRejected,
|
|
7306
|
+
RemoteSubmissionNotFound,
|
|
7574
7307
|
RuntimeBusyError,
|
|
7575
7308
|
SKILLS_DIR,
|
|
7576
7309
|
SandboxClient,
|
|
7310
|
+
SandboxGoneError,
|
|
7577
7311
|
TURN_PROTOCOL_VERSION,
|
|
7578
|
-
TurnLostError,
|
|
7579
7312
|
ValidationError,
|
|
7580
7313
|
defineAgent,
|
|
7581
7314
|
destroyProviderSandbox,
|
|
7582
|
-
getPiTurnResult,
|
|
7583
7315
|
isDefinedAgent,
|
|
7584
7316
|
normalizeStackFramePath,
|
|
7585
7317
|
resolveAgentSourceFile,
|