agent-neckbeard 1.1.26 → 1.1.28
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 +18 -0
- package/README.md +53 -459
- package/dist/build.cjs +5560 -0
- package/dist/build.d.cts +80 -0
- package/dist/build.d.ts +80 -0
- package/dist/build.js +17 -0
- package/dist/chunk-JF5YPOBY.js +4339 -0
- package/dist/chunk-KG6SJM74.js +97 -0
- package/dist/chunk-M3FISP7J.js +377 -0
- package/dist/chunk-M7XNBKG4.js +346 -0
- package/dist/cli.cjs +5606 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +75 -0
- package/dist/index.cjs +1572 -149
- package/dist/index.d.cts +338 -6
- package/dist/index.d.ts +338 -6
- package/dist/index.js +36 -3272
- package/dist/{invoke-client-YKWOTQWG.js → invoke-client-P2CPBYTF.js} +2 -41
- package/dist/serve-Dan1HQKN.d.cts +89 -0
- package/dist/serve-Dan1HQKN.d.ts +89 -0
- package/dist/serve.cjs +337 -0
- package/dist/serve.d.cts +1 -0
- package/dist/serve.d.ts +1 -0
- package/dist/serve.js +8 -0
- package/docs/AGENT.md +173 -0
- package/docs/DAYTONA.md +56 -0
- package/docs/DOCKER.md +7 -7
- package/docs/E2B.md +11 -0
- package/docs/LEGACY.md +335 -0
- package/docs/MODAL.md +29 -13
- package/docs/SUPERVISOR.md +2 -2
- package/package.json +43 -3
- package/dist/chunk-6GCQOKYI.js +0 -48
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isSerializedError
|
|
3
|
+
} from "./chunk-33IXN6MM.js";
|
|
4
|
+
|
|
5
|
+
// src/runtime/protocol.ts
|
|
6
|
+
var RUNTIME_PROTOCOL_VERSION = 1;
|
|
7
|
+
var RUNTIME_ABORT_GRACE_MS = 1e4;
|
|
8
|
+
function isHarnessEvent(value) {
|
|
9
|
+
if (!value || typeof value !== "object") return false;
|
|
10
|
+
const candidate = value;
|
|
11
|
+
if (typeof candidate.kind !== "string") return false;
|
|
12
|
+
if (typeof candidate.invocationId !== "string") return false;
|
|
13
|
+
if (!hasValidMetadata(candidate)) return false;
|
|
14
|
+
switch (candidate.kind) {
|
|
15
|
+
case "started":
|
|
16
|
+
case "done":
|
|
17
|
+
return true;
|
|
18
|
+
case "frame":
|
|
19
|
+
return Object.hasOwn(candidate, "data");
|
|
20
|
+
case "output":
|
|
21
|
+
return Object.hasOwn(candidate, "output");
|
|
22
|
+
case "error":
|
|
23
|
+
return isSerializedError(candidate.error);
|
|
24
|
+
default:
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function hasValidMetadata(candidate) {
|
|
29
|
+
if (candidate.protocolVersion !== void 0 && candidate.protocolVersion !== RUNTIME_PROTOCOL_VERSION) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
if (candidate.sequence !== void 0 && typeof candidate.sequence !== "number") {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
if (candidate.timestamp !== void 0 && typeof candidate.timestamp !== "string") {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
if (candidate.elapsedMs !== void 0 && typeof candidate.elapsedMs !== "number") {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// src/sse-framing.ts
|
|
45
|
+
var IncompleteSseFrameError = class extends Error {
|
|
46
|
+
};
|
|
47
|
+
async function* decodeSseStream(chunks) {
|
|
48
|
+
let buffer = "";
|
|
49
|
+
for await (const chunk of chunks) {
|
|
50
|
+
buffer += chunk;
|
|
51
|
+
let boundary = buffer.indexOf("\n\n");
|
|
52
|
+
while (boundary !== -1) {
|
|
53
|
+
const rawFrame = buffer.slice(0, boundary);
|
|
54
|
+
buffer = buffer.slice(boundary + 2);
|
|
55
|
+
const parsed = parseFrame(rawFrame);
|
|
56
|
+
if (parsed !== void 0) {
|
|
57
|
+
yield parsed;
|
|
58
|
+
}
|
|
59
|
+
boundary = buffer.indexOf("\n\n");
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const tail = buffer.trim();
|
|
63
|
+
if (tail.length > 0) {
|
|
64
|
+
let parsed;
|
|
65
|
+
try {
|
|
66
|
+
parsed = parseFrame(tail);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
throw new IncompleteSseFrameError(`Incomplete SSE data frame: ${error instanceof Error ? error.message : String(error)}`);
|
|
69
|
+
}
|
|
70
|
+
if (parsed !== void 0) {
|
|
71
|
+
yield parsed;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function parseFrame(raw) {
|
|
76
|
+
const dataLines = [];
|
|
77
|
+
for (const line of raw.split("\n")) {
|
|
78
|
+
if (line.startsWith("data:")) {
|
|
79
|
+
dataLines.push(line.slice("data:".length).replace(/^ /, ""));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (dataLines.length === 0) return void 0;
|
|
83
|
+
try {
|
|
84
|
+
return JSON.parse(dataLines.join("\n"));
|
|
85
|
+
} catch (error) {
|
|
86
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
87
|
+
throw new Error(`Malformed SSE data frame: ${message}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export {
|
|
92
|
+
RUNTIME_PROTOCOL_VERSION,
|
|
93
|
+
RUNTIME_ABORT_GRACE_MS,
|
|
94
|
+
isHarnessEvent,
|
|
95
|
+
IncompleteSseFrameError,
|
|
96
|
+
decodeSseStream
|
|
97
|
+
};
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
// src/serve.ts
|
|
2
|
+
import { createServer } from "http";
|
|
3
|
+
|
|
4
|
+
// src/turn-protocol.ts
|
|
5
|
+
var TURN_PROTOCOL_VERSION = 2;
|
|
6
|
+
var MAX_TURN_REQUEST_BYTES = 4 * 1024 * 1024;
|
|
7
|
+
var MAX_TURN_ID_LENGTH = 200;
|
|
8
|
+
function isRecord(value) {
|
|
9
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10
|
+
}
|
|
11
|
+
function parseTurnRecord(record) {
|
|
12
|
+
if (!isRecord(record)) throw new Error("Turn record must be an object.");
|
|
13
|
+
const { seq } = record;
|
|
14
|
+
if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0) {
|
|
15
|
+
throw new Error("Turn record seq must be a non-negative integer.");
|
|
16
|
+
}
|
|
17
|
+
if (record.type === "event" && "event" in record) {
|
|
18
|
+
return { seq, type: "event", event: record.event };
|
|
19
|
+
}
|
|
20
|
+
if (record.type === "end" && (record.outcome === "completed" || record.outcome === "aborted" || record.outcome === "failed") && (record.error === void 0 || typeof record.error === "string")) {
|
|
21
|
+
return {
|
|
22
|
+
seq,
|
|
23
|
+
type: "end",
|
|
24
|
+
outcome: record.outcome,
|
|
25
|
+
...record.error === void 0 ? {} : { error: record.error }
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
throw new Error("Turn record has an unknown shape.");
|
|
29
|
+
}
|
|
30
|
+
function parseTurnHealth(value) {
|
|
31
|
+
if (!isRecord(value)) throw new Error("Health response must be an object.");
|
|
32
|
+
const { ok, protocolVersion, busy, turnId } = value;
|
|
33
|
+
if (ok !== true || typeof protocolVersion !== "number" || typeof busy !== "boolean" || turnId !== null && typeof turnId !== "string") {
|
|
34
|
+
throw new Error("Health response is not { ok: true, protocolVersion, busy, turnId }.");
|
|
35
|
+
}
|
|
36
|
+
return { ok, protocolVersion, busy, turnId };
|
|
37
|
+
}
|
|
38
|
+
function readAssistantMessageEnd(event) {
|
|
39
|
+
if (!isRecord(event) || event.type !== "message_end" || !isRecord(event.message)) return void 0;
|
|
40
|
+
const { role, content, stopReason, errorMessage } = event.message;
|
|
41
|
+
if (role !== "assistant") return void 0;
|
|
42
|
+
const text = (Array.isArray(content) ? content : []).flatMap((block) => isRecord(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n").trim();
|
|
43
|
+
return {
|
|
44
|
+
text,
|
|
45
|
+
stopReason: typeof stopReason === "string" ? stopReason : void 0,
|
|
46
|
+
errorMessage: typeof errorMessage === "string" ? errorMessage : void 0
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function getPiTurnResult(records) {
|
|
50
|
+
let end;
|
|
51
|
+
let message;
|
|
52
|
+
for (const record of records) {
|
|
53
|
+
if (record.type === "end") {
|
|
54
|
+
end = record;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
message = readAssistantMessageEnd(record.event) ?? message;
|
|
58
|
+
}
|
|
59
|
+
if (!end) return { completed: false, error: "The agent turn has not ended." };
|
|
60
|
+
if (end.outcome !== "completed") {
|
|
61
|
+
return { completed: false, error: end.error ?? `The agent turn was ${end.outcome}.` };
|
|
62
|
+
}
|
|
63
|
+
if (!message) return { completed: false, error: "The agent did not reply." };
|
|
64
|
+
if (message.stopReason !== "stop") {
|
|
65
|
+
return {
|
|
66
|
+
completed: false,
|
|
67
|
+
error: message.errorMessage?.trim() || `The agent stopped with ${message.stopReason ?? "no reason"}.`
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
return { completed: true, text: message.text || null };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/serve.ts
|
|
74
|
+
var HEARTBEAT_INTERVAL_MS = 15e3;
|
|
75
|
+
var DEFAULT_ABORT_GRACE_MS = 1e4;
|
|
76
|
+
var DEFAULT_PORT = 8080;
|
|
77
|
+
function toPiJsonEvent(event) {
|
|
78
|
+
if (!isRecord(event) || event.type !== "message_update") return event;
|
|
79
|
+
const { message, assistantMessageEvent } = event;
|
|
80
|
+
if (!isRecord(message) || message.role !== "assistant") {
|
|
81
|
+
throw new Error("message_update message is not an assistant message");
|
|
82
|
+
}
|
|
83
|
+
if (!isRecord(assistantMessageEvent) || typeof assistantMessageEvent.type !== "string") {
|
|
84
|
+
throw new Error("message_update has no assistantMessageEvent");
|
|
85
|
+
}
|
|
86
|
+
const { partial, ...delta } = assistantMessageEvent;
|
|
87
|
+
if (assistantMessageEvent.type === "toolcall_start") {
|
|
88
|
+
const { contentIndex } = assistantMessageEvent;
|
|
89
|
+
const content = isRecord(partial) && Array.isArray(partial.content) ? partial.content : [];
|
|
90
|
+
const toolCall = typeof contentIndex === "number" ? content[contentIndex] : void 0;
|
|
91
|
+
if (!isRecord(toolCall) || toolCall.type !== "toolCall" || typeof toolCall.id !== "string" || typeof toolCall.name !== "string") {
|
|
92
|
+
throw new Error(`toolcall_start content at index ${String(contentIndex)} is not a tool call`);
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
type: "message_update",
|
|
96
|
+
usage: message.usage,
|
|
97
|
+
assistantMessageEvent: { ...delta, id: toolCall.id, toolName: toolCall.name }
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
return { type: "message_update", usage: message.usage, assistantMessageEvent: delta };
|
|
101
|
+
}
|
|
102
|
+
var RequestError = class extends Error {
|
|
103
|
+
constructor(status, message) {
|
|
104
|
+
super(message);
|
|
105
|
+
this.status = status;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
function sendJson(response, status, body) {
|
|
109
|
+
response.writeHead(status, { "content-type": "application/json" });
|
|
110
|
+
response.end(JSON.stringify(body));
|
|
111
|
+
}
|
|
112
|
+
async function readJsonBody(request) {
|
|
113
|
+
const chunks = [];
|
|
114
|
+
let size = 0;
|
|
115
|
+
for await (const chunk of request) {
|
|
116
|
+
size += chunk.byteLength;
|
|
117
|
+
if (size > MAX_TURN_REQUEST_BYTES) throw new RequestError(413, "Request body is too large.");
|
|
118
|
+
chunks.push(chunk);
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
122
|
+
} catch {
|
|
123
|
+
throw new RequestError(400, "Request body must be JSON.");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function parseStartTurn(body) {
|
|
127
|
+
if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
|
|
128
|
+
const { turnId, message, env } = body;
|
|
129
|
+
if (typeof turnId !== "string" || !turnId || turnId.length > MAX_TURN_ID_LENGTH) {
|
|
130
|
+
throw new RequestError(400, `turnId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
|
|
131
|
+
}
|
|
132
|
+
if (typeof message !== "string" || !message.trim()) {
|
|
133
|
+
throw new RequestError(400, "message must be a non-empty string.");
|
|
134
|
+
}
|
|
135
|
+
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"))) {
|
|
136
|
+
throw new RequestError(400, "env must map environment variable names to strings.");
|
|
137
|
+
}
|
|
138
|
+
return { turnId, message, ...env === void 0 ? {} : { env } };
|
|
139
|
+
}
|
|
140
|
+
async function serve(options) {
|
|
141
|
+
const toWireEvent = options.toWireEvent ?? toPiJsonEvent;
|
|
142
|
+
let sessionPromise;
|
|
143
|
+
let current;
|
|
144
|
+
let previous;
|
|
145
|
+
let currentSessionAbort;
|
|
146
|
+
const findTurn = (turnId) => current?.id === turnId ? current : previous?.id === turnId ? previous : void 0;
|
|
147
|
+
const append = (turn, record) => {
|
|
148
|
+
const json = JSON.stringify({ seq: turn.records.length, ...record });
|
|
149
|
+
turn.records.push(json);
|
|
150
|
+
for (const wake of turn.waiters) wake();
|
|
151
|
+
};
|
|
152
|
+
const end = (turn, outcome, error) => {
|
|
153
|
+
if (turn.ended) return;
|
|
154
|
+
append(turn, { type: "end", outcome, ...error === void 0 ? {} : { error } });
|
|
155
|
+
turn.ended = true;
|
|
156
|
+
};
|
|
157
|
+
const endAfterGrace = (turn, outcome, error) => {
|
|
158
|
+
if (turn.ended || turn.finishing || turn.forceEnd) return;
|
|
159
|
+
turn.forceEnd = setTimeout(() => end(turn, outcome, error), options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS);
|
|
160
|
+
};
|
|
161
|
+
const runTurn = async (turn, request) => {
|
|
162
|
+
const previousEnv = /* @__PURE__ */ new Map();
|
|
163
|
+
let unsubscribe;
|
|
164
|
+
let timedOut = false;
|
|
165
|
+
let session;
|
|
166
|
+
const timeoutMessage = `Turn exceeded ${options.maxTurnDurationMs}ms.`;
|
|
167
|
+
const timer = options.maxTurnDurationMs === void 0 ? void 0 : setTimeout(() => {
|
|
168
|
+
timedOut = true;
|
|
169
|
+
if (session) void session.abort().catch(() => void 0);
|
|
170
|
+
endAfterGrace(turn, "failed", timeoutMessage);
|
|
171
|
+
}, options.maxTurnDurationMs);
|
|
172
|
+
const finish = async (outcome, error) => {
|
|
173
|
+
turn.finishing = true;
|
|
174
|
+
if (timer) clearTimeout(timer);
|
|
175
|
+
clearTimeout(turn.forceEnd);
|
|
176
|
+
try {
|
|
177
|
+
await session?.afterTurn?.();
|
|
178
|
+
} catch {
|
|
179
|
+
}
|
|
180
|
+
end(turn, outcome, error);
|
|
181
|
+
};
|
|
182
|
+
try {
|
|
183
|
+
sessionPromise ??= options.createSession();
|
|
184
|
+
try {
|
|
185
|
+
session = await sessionPromise;
|
|
186
|
+
} catch (error) {
|
|
187
|
+
sessionPromise = void 0;
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
if (timedOut) {
|
|
191
|
+
end(turn, "failed", timeoutMessage);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
const started = session;
|
|
195
|
+
for (const [name, value] of Object.entries(request.env ?? {})) {
|
|
196
|
+
previousEnv.set(name, process.env[name]);
|
|
197
|
+
process.env[name] = value;
|
|
198
|
+
}
|
|
199
|
+
unsubscribe = session.subscribe((event) => {
|
|
200
|
+
if (turn.ended) return;
|
|
201
|
+
try {
|
|
202
|
+
append(turn, { type: "event", event: toWireEvent(event) });
|
|
203
|
+
} catch (error) {
|
|
204
|
+
end(turn, "failed", `Could not convert an agent event: ${error instanceof Error ? error.message : String(error)}`);
|
|
205
|
+
void started.abort().catch(() => void 0);
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
currentSessionAbort = () => started.abort();
|
|
209
|
+
if (turn.abortRequested) {
|
|
210
|
+
end(turn, "aborted");
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
await started.prompt(request.message);
|
|
214
|
+
if (timedOut) await finish("failed", timeoutMessage);
|
|
215
|
+
else await finish(turn.abortRequested ? "aborted" : "completed");
|
|
216
|
+
} catch (error) {
|
|
217
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
218
|
+
if (timedOut) await finish("failed", timeoutMessage);
|
|
219
|
+
else await finish(turn.abortRequested ? "aborted" : "failed", turn.abortRequested ? void 0 : message);
|
|
220
|
+
} finally {
|
|
221
|
+
if (timer) clearTimeout(timer);
|
|
222
|
+
clearTimeout(turn.forceEnd);
|
|
223
|
+
unsubscribe?.();
|
|
224
|
+
currentSessionAbort = void 0;
|
|
225
|
+
for (const [name, value] of previousEnv) {
|
|
226
|
+
if (value === void 0) delete process.env[name];
|
|
227
|
+
else process.env[name] = value;
|
|
228
|
+
}
|
|
229
|
+
turn.settled = true;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
const busy = () => Boolean(current && !current.settled);
|
|
233
|
+
const startTurn = async (request) => {
|
|
234
|
+
const existing = findTurn(request.turnId);
|
|
235
|
+
if (existing) return { status: 200, body: { turnId: existing.id, ended: existing.ended } };
|
|
236
|
+
if (current && !current.settled) {
|
|
237
|
+
return { status: 409, body: { error: "Another turn is running.", turnId: current.id } };
|
|
238
|
+
}
|
|
239
|
+
const turn = {
|
|
240
|
+
id: request.turnId,
|
|
241
|
+
records: [],
|
|
242
|
+
ended: false,
|
|
243
|
+
settled: false,
|
|
244
|
+
abortRequested: false,
|
|
245
|
+
finishing: false,
|
|
246
|
+
waiters: /* @__PURE__ */ new Set()
|
|
247
|
+
};
|
|
248
|
+
previous = current;
|
|
249
|
+
current = turn;
|
|
250
|
+
void runTurn(turn, request);
|
|
251
|
+
return { status: 202, body: { turnId: turn.id, ended: false } };
|
|
252
|
+
};
|
|
253
|
+
const streamTurn = async (turn, after, request, response) => {
|
|
254
|
+
response.writeHead(200, {
|
|
255
|
+
"content-type": "text/event-stream",
|
|
256
|
+
"cache-control": "no-cache, no-transform",
|
|
257
|
+
connection: "keep-alive",
|
|
258
|
+
"x-accel-buffering": "no"
|
|
259
|
+
});
|
|
260
|
+
response.write(": connected\n\n");
|
|
261
|
+
let closed = false;
|
|
262
|
+
let wake;
|
|
263
|
+
const onClose = () => {
|
|
264
|
+
closed = true;
|
|
265
|
+
wake?.();
|
|
266
|
+
};
|
|
267
|
+
request.on("close", onClose);
|
|
268
|
+
response.on("close", onClose);
|
|
269
|
+
const heartbeat = setInterval(() => {
|
|
270
|
+
if (!closed) response.write(": ping\n\n");
|
|
271
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
272
|
+
let next = turn.ended ? Math.min(after + 1, turn.records.length - 1) : after + 1;
|
|
273
|
+
try {
|
|
274
|
+
while (!closed) {
|
|
275
|
+
while (!closed && next < turn.records.length) {
|
|
276
|
+
const ok = response.write(`id: ${next}
|
|
277
|
+
data: ${turn.records[next]}
|
|
278
|
+
|
|
279
|
+
`);
|
|
280
|
+
next += 1;
|
|
281
|
+
if (!ok && !closed) {
|
|
282
|
+
let onDrain;
|
|
283
|
+
await new Promise((resolve) => {
|
|
284
|
+
wake = onDrain = resolve;
|
|
285
|
+
response.once("drain", resolve);
|
|
286
|
+
});
|
|
287
|
+
if (onDrain) response.off("drain", onDrain);
|
|
288
|
+
wake = void 0;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
if (closed || turn.ended && next >= turn.records.length) break;
|
|
292
|
+
await new Promise((resolve) => {
|
|
293
|
+
wake = resolve;
|
|
294
|
+
turn.waiters.add(resolve);
|
|
295
|
+
});
|
|
296
|
+
if (wake) turn.waiters.delete(wake);
|
|
297
|
+
wake = void 0;
|
|
298
|
+
}
|
|
299
|
+
} finally {
|
|
300
|
+
clearInterval(heartbeat);
|
|
301
|
+
request.off("close", onClose);
|
|
302
|
+
response.off("close", onClose);
|
|
303
|
+
if (!closed) response.end();
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
const server = createServer((request, response) => {
|
|
307
|
+
void (async () => {
|
|
308
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
309
|
+
const turnPath = /^\/turns\/([^/]+)\/(events|abort)$/u.exec(url.pathname);
|
|
310
|
+
if (request.method === "GET" && url.pathname === "/health") {
|
|
311
|
+
const health = {
|
|
312
|
+
ok: true,
|
|
313
|
+
protocolVersion: TURN_PROTOCOL_VERSION,
|
|
314
|
+
busy: busy(),
|
|
315
|
+
turnId: current?.id ?? null
|
|
316
|
+
};
|
|
317
|
+
return sendJson(response, 200, health);
|
|
318
|
+
}
|
|
319
|
+
if (request.method === "POST" && url.pathname === "/turns") {
|
|
320
|
+
const { status, body } = await startTurn(parseStartTurn(await readJsonBody(request)));
|
|
321
|
+
return sendJson(response, status, body);
|
|
322
|
+
}
|
|
323
|
+
if (turnPath) {
|
|
324
|
+
const turn = findTurn(decodeURIComponent(turnPath[1]));
|
|
325
|
+
if (!turn) return sendJson(response, 404, { error: "Unknown turn." });
|
|
326
|
+
if (request.method === "GET" && turnPath[2] === "events") {
|
|
327
|
+
const afterParam = url.searchParams.get("after");
|
|
328
|
+
const after = afterParam === null ? -1 : Number(afterParam);
|
|
329
|
+
if (!Number.isSafeInteger(after) || after < -1) {
|
|
330
|
+
return sendJson(response, 400, { error: "after must be an integer of at least -1." });
|
|
331
|
+
}
|
|
332
|
+
return streamTurn(turn, after, request, response);
|
|
333
|
+
}
|
|
334
|
+
if (request.method === "POST" && turnPath[2] === "abort") {
|
|
335
|
+
if (!turn.ended && !turn.finishing && !turn.abortRequested) {
|
|
336
|
+
turn.abortRequested = true;
|
|
337
|
+
if (turn === current) void currentSessionAbort?.().catch(() => void 0);
|
|
338
|
+
endAfterGrace(turn, "aborted");
|
|
339
|
+
}
|
|
340
|
+
return sendJson(response, 202, { turnId: turn.id, ended: turn.ended });
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
sendJson(response, 404, { error: "Not found." });
|
|
344
|
+
})().catch((error) => {
|
|
345
|
+
if (response.headersSent) {
|
|
346
|
+
response.destroy();
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const status = error instanceof RequestError ? error.status : 500;
|
|
350
|
+
sendJson(response, status, { error: error instanceof Error ? error.message : String(error) });
|
|
351
|
+
});
|
|
352
|
+
});
|
|
353
|
+
const port = options.port ?? (Number(process.env.NECKBEARD_PORT) || DEFAULT_PORT);
|
|
354
|
+
await new Promise((resolve, reject) => {
|
|
355
|
+
server.once("error", reject);
|
|
356
|
+
server.listen(port, options.host ?? "0.0.0.0", () => {
|
|
357
|
+
server.off("error", reject);
|
|
358
|
+
resolve();
|
|
359
|
+
});
|
|
360
|
+
});
|
|
361
|
+
return {
|
|
362
|
+
port: server.address().port,
|
|
363
|
+
close: () => new Promise((resolve, reject) => {
|
|
364
|
+
server.closeAllConnections();
|
|
365
|
+
server.close((error) => error ? reject(error) : resolve());
|
|
366
|
+
})
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export {
|
|
371
|
+
TURN_PROTOCOL_VERSION,
|
|
372
|
+
parseTurnRecord,
|
|
373
|
+
parseTurnHealth,
|
|
374
|
+
getPiTurnResult,
|
|
375
|
+
toPiJsonEvent,
|
|
376
|
+
serve
|
|
377
|
+
};
|