agent-neckbeard 1.1.27 → 1.1.29
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 +16 -0
- package/README.md +53 -461
- package/dist/build.cjs +5715 -0
- package/dist/build.d.cts +80 -0
- package/dist/build.d.ts +80 -0
- package/dist/build.js +17 -0
- package/dist/chunk-BPXEIXPM.js +4363 -0
- package/dist/chunk-FSBTLBB5.js +346 -0
- package/dist/chunk-KG6SJM74.js +97 -0
- package/dist/chunk-YFG4EKZM.js +508 -0
- package/dist/cli.cjs +5761 -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 +1599 -146
- package/dist/index.d.cts +321 -6
- package/dist/index.d.ts +321 -6
- package/dist/index.js +36 -3397
- package/dist/{invoke-client-YKWOTQWG.js → invoke-client-P2CPBYTF.js} +2 -41
- package/dist/serve-Du2NCz9_.d.cts +111 -0
- package/dist/serve-Du2NCz9_.d.ts +111 -0
- package/dist/serve.cjs +467 -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 +205 -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 +14 -12
- package/docs/SUPERVISOR.md +2 -2
- package/package.json +43 -3
- package/dist/chunk-6GCQOKYI.js +0 -48
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
// src/serve.ts
|
|
2
|
+
import { createServer } from "http";
|
|
3
|
+
|
|
4
|
+
// src/turn-protocol.ts
|
|
5
|
+
var TURN_PROTOCOL_VERSION = 3;
|
|
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") && (record.undeliveredSteerIds === void 0 || Array.isArray(record.undeliveredSteerIds) && record.undeliveredSteerIds.every((id) => typeof id === "string"))) {
|
|
21
|
+
return {
|
|
22
|
+
seq,
|
|
23
|
+
type: "end",
|
|
24
|
+
outcome: record.outcome,
|
|
25
|
+
...record.error === void 0 ? {} : { error: record.error },
|
|
26
|
+
...record.undeliveredSteerIds === void 0 ? {} : { undeliveredSteerIds: record.undeliveredSteerIds }
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
throw new Error("Turn record has an unknown shape.");
|
|
30
|
+
}
|
|
31
|
+
function parseTurnHealth(value) {
|
|
32
|
+
if (!isRecord(value)) throw new Error("Health response must be an object.");
|
|
33
|
+
const { ok, protocolVersion, busy, turnId } = value;
|
|
34
|
+
if (ok !== true || typeof protocolVersion !== "number" || typeof busy !== "boolean" || turnId !== null && typeof turnId !== "string") {
|
|
35
|
+
throw new Error("Health response is not { ok: true, protocolVersion, busy, turnId }.");
|
|
36
|
+
}
|
|
37
|
+
return { ok, protocolVersion, busy, turnId };
|
|
38
|
+
}
|
|
39
|
+
function readAssistantMessageEnd(event) {
|
|
40
|
+
if (!isRecord(event) || event.type !== "message_end" || !isRecord(event.message)) return void 0;
|
|
41
|
+
const { role, content, stopReason, errorMessage } = event.message;
|
|
42
|
+
if (role !== "assistant") return void 0;
|
|
43
|
+
const text = (Array.isArray(content) ? content : []).flatMap((block) => isRecord(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n").trim();
|
|
44
|
+
return {
|
|
45
|
+
text,
|
|
46
|
+
stopReason: typeof stopReason === "string" ? stopReason : void 0,
|
|
47
|
+
errorMessage: typeof errorMessage === "string" ? errorMessage : void 0
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function getPiTurnResult(records) {
|
|
51
|
+
let end;
|
|
52
|
+
let message;
|
|
53
|
+
for (const record of records) {
|
|
54
|
+
if (record.type === "end") {
|
|
55
|
+
end = record;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
message = readAssistantMessageEnd(record.event) ?? message;
|
|
59
|
+
}
|
|
60
|
+
if (!end) return { completed: false, error: "The agent turn has not ended." };
|
|
61
|
+
if (end.outcome !== "completed") {
|
|
62
|
+
return { completed: false, error: end.error ?? `The agent turn was ${end.outcome}.` };
|
|
63
|
+
}
|
|
64
|
+
if (!message) return { completed: false, error: "The agent did not reply." };
|
|
65
|
+
if (message.stopReason !== "stop") {
|
|
66
|
+
return {
|
|
67
|
+
completed: false,
|
|
68
|
+
error: message.errorMessage?.trim() || `The agent stopped with ${message.stopReason ?? "no reason"}.`
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return { completed: true, text: message.text || null };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/serve.ts
|
|
75
|
+
var HEARTBEAT_INTERVAL_MS = 15e3;
|
|
76
|
+
var DEFAULT_ABORT_GRACE_MS = 1e4;
|
|
77
|
+
var DEFAULT_PORT = 8080;
|
|
78
|
+
function toPiJsonEvent(event) {
|
|
79
|
+
if (!isRecord(event) || event.type !== "message_update") return event;
|
|
80
|
+
const { message, assistantMessageEvent } = event;
|
|
81
|
+
if (!isRecord(message) || message.role !== "assistant") {
|
|
82
|
+
throw new Error("message_update message is not an assistant message");
|
|
83
|
+
}
|
|
84
|
+
if (!isRecord(assistantMessageEvent) || typeof assistantMessageEvent.type !== "string") {
|
|
85
|
+
throw new Error("message_update has no assistantMessageEvent");
|
|
86
|
+
}
|
|
87
|
+
const { partial, ...delta } = assistantMessageEvent;
|
|
88
|
+
if (assistantMessageEvent.type === "toolcall_start") {
|
|
89
|
+
const { contentIndex } = assistantMessageEvent;
|
|
90
|
+
const content = isRecord(partial) && Array.isArray(partial.content) ? partial.content : [];
|
|
91
|
+
const toolCall = typeof contentIndex === "number" ? content[contentIndex] : void 0;
|
|
92
|
+
if (!isRecord(toolCall) || toolCall.type !== "toolCall" || typeof toolCall.id !== "string" || typeof toolCall.name !== "string") {
|
|
93
|
+
throw new Error(`toolcall_start content at index ${String(contentIndex)} is not a tool call`);
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
type: "message_update",
|
|
97
|
+
usage: message.usage,
|
|
98
|
+
assistantMessageEvent: { ...delta, id: toolCall.id, toolName: toolCall.name }
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
return { type: "message_update", usage: message.usage, assistantMessageEvent: delta };
|
|
102
|
+
}
|
|
103
|
+
var RequestError = class extends Error {
|
|
104
|
+
constructor(status, message) {
|
|
105
|
+
super(message);
|
|
106
|
+
this.status = status;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
function sendJson(response, status, body) {
|
|
110
|
+
response.writeHead(status, { "content-type": "application/json" });
|
|
111
|
+
response.end(JSON.stringify(body));
|
|
112
|
+
}
|
|
113
|
+
async function readJsonBody(request) {
|
|
114
|
+
const chunks = [];
|
|
115
|
+
let size = 0;
|
|
116
|
+
for await (const chunk of request) {
|
|
117
|
+
size += chunk.byteLength;
|
|
118
|
+
if (size > MAX_TURN_REQUEST_BYTES) throw new RequestError(413, "Request body is too large.");
|
|
119
|
+
chunks.push(chunk);
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
123
|
+
} catch {
|
|
124
|
+
throw new RequestError(400, "Request body must be JSON.");
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function parseStartTurn(body) {
|
|
128
|
+
if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
|
|
129
|
+
const { turnId, message, env } = body;
|
|
130
|
+
if (typeof turnId !== "string" || !turnId || turnId.length > MAX_TURN_ID_LENGTH) {
|
|
131
|
+
throw new RequestError(400, `turnId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
|
|
132
|
+
}
|
|
133
|
+
if (typeof message !== "string" || !message.trim()) {
|
|
134
|
+
throw new RequestError(400, "message must be a non-empty string.");
|
|
135
|
+
}
|
|
136
|
+
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"))) {
|
|
137
|
+
throw new RequestError(400, "env must map environment variable names to strings.");
|
|
138
|
+
}
|
|
139
|
+
return { turnId, message, ...env === void 0 ? {} : { env } };
|
|
140
|
+
}
|
|
141
|
+
function parseSteerTurn(body) {
|
|
142
|
+
if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
|
|
143
|
+
const { steerId, message } = body;
|
|
144
|
+
if (typeof steerId !== "string" || !steerId || steerId.length > MAX_TURN_ID_LENGTH) {
|
|
145
|
+
throw new RequestError(400, `steerId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
|
|
146
|
+
}
|
|
147
|
+
if (typeof message !== "string" || !message.trim()) {
|
|
148
|
+
throw new RequestError(400, "message must be a non-empty string.");
|
|
149
|
+
}
|
|
150
|
+
return { steerId, message };
|
|
151
|
+
}
|
|
152
|
+
async function serve(options) {
|
|
153
|
+
const toWireEvent = options.toWireEvent ?? toPiJsonEvent;
|
|
154
|
+
let sessionPromise;
|
|
155
|
+
let current;
|
|
156
|
+
let previous;
|
|
157
|
+
let currentSessionAbort;
|
|
158
|
+
const findTurn = (turnId) => current?.id === turnId ? current : previous?.id === turnId ? previous : void 0;
|
|
159
|
+
const append = (turn, record) => {
|
|
160
|
+
const json = JSON.stringify({ seq: turn.records.length, ...record });
|
|
161
|
+
turn.records.push(json);
|
|
162
|
+
for (const wake of turn.waiters) wake();
|
|
163
|
+
};
|
|
164
|
+
const reclaimSteers = (turn) => {
|
|
165
|
+
let left;
|
|
166
|
+
try {
|
|
167
|
+
left = turn.session?.clearQueue?.().steering.length ?? 0;
|
|
168
|
+
} catch {
|
|
169
|
+
left = turn.queuedSteers.length;
|
|
170
|
+
sessionPromise = void 0;
|
|
171
|
+
}
|
|
172
|
+
const leftover = left > 0 ? turn.queuedSteers.slice(-left) : [];
|
|
173
|
+
for (const steer of turn.queuedSteers) steer.state = leftover.includes(steer) ? "undelivered" : "delivered";
|
|
174
|
+
turn.queuedSteers = [];
|
|
175
|
+
turn.undeliveredSteers.push(...leftover);
|
|
176
|
+
};
|
|
177
|
+
const end = (turn, outcome, error) => {
|
|
178
|
+
if (turn.ending) return turn.ending;
|
|
179
|
+
turn.closed = true;
|
|
180
|
+
turn.sessionReady();
|
|
181
|
+
let written;
|
|
182
|
+
turn.ending = new Promise((resolve) => {
|
|
183
|
+
written = resolve;
|
|
184
|
+
});
|
|
185
|
+
reclaimSteers(turn);
|
|
186
|
+
void (async () => {
|
|
187
|
+
let timer;
|
|
188
|
+
const graceMs = turn.stopBy === void 0 ? options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS : Math.max(0, turn.stopBy - Date.now());
|
|
189
|
+
await Promise.race([
|
|
190
|
+
turn.steering,
|
|
191
|
+
new Promise((resolve) => {
|
|
192
|
+
timer = setTimeout(resolve, graceMs);
|
|
193
|
+
})
|
|
194
|
+
]);
|
|
195
|
+
clearTimeout(timer);
|
|
196
|
+
reclaimSteers(turn);
|
|
197
|
+
const undeliveredSteerIds = turn.undeliveredSteers.filter((steer) => !steer.late).map((steer) => steer.id);
|
|
198
|
+
append(turn, {
|
|
199
|
+
type: "end",
|
|
200
|
+
outcome,
|
|
201
|
+
...error === void 0 ? {} : { error },
|
|
202
|
+
...undeliveredSteerIds.length > 0 ? { undeliveredSteerIds } : {}
|
|
203
|
+
});
|
|
204
|
+
turn.ended = true;
|
|
205
|
+
written();
|
|
206
|
+
})();
|
|
207
|
+
return turn.ending;
|
|
208
|
+
};
|
|
209
|
+
const acceptSteer = (turn, id, message) => {
|
|
210
|
+
const steer = { id, state: "pending", late: false, settled: Promise.resolve() };
|
|
211
|
+
steer.settled = turn.steering.then(async () => {
|
|
212
|
+
const session = turn.session;
|
|
213
|
+
if (turn.closed || !session?.steer || !session.clearQueue) {
|
|
214
|
+
steer.state = "undelivered";
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
if (await session.steer(message) === "handled") {
|
|
219
|
+
steer.state = "handled";
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
steer.state = "queued";
|
|
223
|
+
turn.queuedSteers.push(steer);
|
|
224
|
+
if (turn.closed) {
|
|
225
|
+
reclaimSteers(turn);
|
|
226
|
+
steer.late = turn.undeliveredSteers.includes(steer);
|
|
227
|
+
}
|
|
228
|
+
} catch (error) {
|
|
229
|
+
steer.state = "failed";
|
|
230
|
+
steer.error = error;
|
|
231
|
+
turn.steers.delete(id);
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
turn.steering = steer.settled;
|
|
235
|
+
turn.steers.set(id, steer);
|
|
236
|
+
return steer;
|
|
237
|
+
};
|
|
238
|
+
const endAfterGrace = (turn, outcome, error) => {
|
|
239
|
+
if (turn.ending || turn.finishing || turn.forceEnd) return;
|
|
240
|
+
const graceMs = options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS;
|
|
241
|
+
turn.stopBy = Date.now() + graceMs;
|
|
242
|
+
turn.forceEnd = setTimeout(() => void end(turn, outcome, error), graceMs);
|
|
243
|
+
};
|
|
244
|
+
const runTurn = async (turn, request) => {
|
|
245
|
+
const previousEnv = /* @__PURE__ */ new Map();
|
|
246
|
+
let unsubscribe;
|
|
247
|
+
let timedOut = false;
|
|
248
|
+
let session;
|
|
249
|
+
const timeoutMessage = `Turn exceeded ${options.maxTurnDurationMs}ms.`;
|
|
250
|
+
const timer = options.maxTurnDurationMs === void 0 ? void 0 : setTimeout(() => {
|
|
251
|
+
timedOut = true;
|
|
252
|
+
turn.closed = true;
|
|
253
|
+
reclaimSteers(turn);
|
|
254
|
+
if (session) void session.abort().catch(() => void 0);
|
|
255
|
+
endAfterGrace(turn, "failed", timeoutMessage);
|
|
256
|
+
}, options.maxTurnDurationMs);
|
|
257
|
+
const finish = async (outcome, error) => {
|
|
258
|
+
turn.finishing = true;
|
|
259
|
+
turn.closed = true;
|
|
260
|
+
if (timer) clearTimeout(timer);
|
|
261
|
+
clearTimeout(turn.forceEnd);
|
|
262
|
+
try {
|
|
263
|
+
await session?.afterTurn?.();
|
|
264
|
+
} catch {
|
|
265
|
+
}
|
|
266
|
+
await end(turn, outcome, error);
|
|
267
|
+
};
|
|
268
|
+
try {
|
|
269
|
+
sessionPromise ??= options.createSession();
|
|
270
|
+
try {
|
|
271
|
+
session = await sessionPromise;
|
|
272
|
+
} catch (error) {
|
|
273
|
+
sessionPromise = void 0;
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
if (timedOut) {
|
|
277
|
+
await end(turn, "failed", timeoutMessage);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
const started = session;
|
|
281
|
+
turn.session = session;
|
|
282
|
+
for (const [name, value] of Object.entries(request.env ?? {})) {
|
|
283
|
+
previousEnv.set(name, process.env[name]);
|
|
284
|
+
process.env[name] = value;
|
|
285
|
+
}
|
|
286
|
+
unsubscribe = session.subscribe((event) => {
|
|
287
|
+
if (turn.ending) return;
|
|
288
|
+
try {
|
|
289
|
+
append(turn, { type: "event", event: toWireEvent(event) });
|
|
290
|
+
} catch (error) {
|
|
291
|
+
void end(turn, "failed", `Could not convert an agent event: ${error instanceof Error ? error.message : String(error)}`);
|
|
292
|
+
void started.abort().catch(() => void 0);
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
currentSessionAbort = () => started.abort();
|
|
296
|
+
turn.sessionReady();
|
|
297
|
+
if (!turn.closed) await turn.steering;
|
|
298
|
+
if (turn.ending) return;
|
|
299
|
+
if (timedOut) {
|
|
300
|
+
await end(turn, "failed", timeoutMessage);
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
if (turn.abortRequested) {
|
|
304
|
+
await end(turn, "aborted");
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
await started.prompt(request.message);
|
|
308
|
+
if (timedOut) await finish("failed", timeoutMessage);
|
|
309
|
+
else await finish(turn.abortRequested ? "aborted" : "completed");
|
|
310
|
+
} catch (error) {
|
|
311
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
312
|
+
if (timedOut) await finish("failed", timeoutMessage);
|
|
313
|
+
else await finish(turn.abortRequested ? "aborted" : "failed", turn.abortRequested ? void 0 : message);
|
|
314
|
+
} finally {
|
|
315
|
+
if (timer) clearTimeout(timer);
|
|
316
|
+
clearTimeout(turn.forceEnd);
|
|
317
|
+
turn.closed = true;
|
|
318
|
+
turn.sessionReady();
|
|
319
|
+
await turn.ending;
|
|
320
|
+
unsubscribe?.();
|
|
321
|
+
currentSessionAbort = void 0;
|
|
322
|
+
await turn.steering;
|
|
323
|
+
reclaimSteers(turn);
|
|
324
|
+
for (const [name, value] of previousEnv) {
|
|
325
|
+
if (value === void 0) delete process.env[name];
|
|
326
|
+
else process.env[name] = value;
|
|
327
|
+
}
|
|
328
|
+
turn.settled = true;
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
const busy = () => Boolean(current && !current.settled);
|
|
332
|
+
const startTurn = async (request) => {
|
|
333
|
+
const existing = findTurn(request.turnId);
|
|
334
|
+
if (existing) return { status: 200, body: { turnId: existing.id, ended: existing.ended } };
|
|
335
|
+
if (current && !current.settled) {
|
|
336
|
+
return { status: 409, body: { error: "Another turn is running.", turnId: current.id } };
|
|
337
|
+
}
|
|
338
|
+
let sessionReady;
|
|
339
|
+
const turn = {
|
|
340
|
+
id: request.turnId,
|
|
341
|
+
records: [],
|
|
342
|
+
ended: false,
|
|
343
|
+
settled: false,
|
|
344
|
+
abortRequested: false,
|
|
345
|
+
steers: /* @__PURE__ */ new Map(),
|
|
346
|
+
queuedSteers: [],
|
|
347
|
+
undeliveredSteers: [],
|
|
348
|
+
steering: new Promise((resolve) => {
|
|
349
|
+
sessionReady = resolve;
|
|
350
|
+
}),
|
|
351
|
+
sessionReady: () => sessionReady(),
|
|
352
|
+
closed: false,
|
|
353
|
+
finishing: false,
|
|
354
|
+
waiters: /* @__PURE__ */ new Set()
|
|
355
|
+
};
|
|
356
|
+
previous = current;
|
|
357
|
+
current = turn;
|
|
358
|
+
void runTurn(turn, request);
|
|
359
|
+
return { status: 202, body: { turnId: turn.id, ended: false } };
|
|
360
|
+
};
|
|
361
|
+
const streamTurn = async (turn, after, request, response) => {
|
|
362
|
+
response.writeHead(200, {
|
|
363
|
+
"content-type": "text/event-stream",
|
|
364
|
+
"cache-control": "no-cache, no-transform",
|
|
365
|
+
connection: "keep-alive",
|
|
366
|
+
"x-accel-buffering": "no"
|
|
367
|
+
});
|
|
368
|
+
response.write(": connected\n\n");
|
|
369
|
+
let closed = false;
|
|
370
|
+
let wake;
|
|
371
|
+
const onClose = () => {
|
|
372
|
+
closed = true;
|
|
373
|
+
wake?.();
|
|
374
|
+
};
|
|
375
|
+
request.on("close", onClose);
|
|
376
|
+
response.on("close", onClose);
|
|
377
|
+
const heartbeat = setInterval(() => {
|
|
378
|
+
if (!closed) response.write(": ping\n\n");
|
|
379
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
380
|
+
let next = turn.ended ? Math.min(after + 1, turn.records.length - 1) : after + 1;
|
|
381
|
+
try {
|
|
382
|
+
while (!closed) {
|
|
383
|
+
while (!closed && next < turn.records.length) {
|
|
384
|
+
const ok = response.write(`id: ${next}
|
|
385
|
+
data: ${turn.records[next]}
|
|
386
|
+
|
|
387
|
+
`);
|
|
388
|
+
next += 1;
|
|
389
|
+
if (!ok && !closed) {
|
|
390
|
+
let onDrain;
|
|
391
|
+
await new Promise((resolve) => {
|
|
392
|
+
wake = onDrain = resolve;
|
|
393
|
+
response.once("drain", resolve);
|
|
394
|
+
});
|
|
395
|
+
if (onDrain) response.off("drain", onDrain);
|
|
396
|
+
wake = void 0;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if (closed || turn.ended && next >= turn.records.length) break;
|
|
400
|
+
await new Promise((resolve) => {
|
|
401
|
+
wake = resolve;
|
|
402
|
+
turn.waiters.add(resolve);
|
|
403
|
+
});
|
|
404
|
+
if (wake) turn.waiters.delete(wake);
|
|
405
|
+
wake = void 0;
|
|
406
|
+
}
|
|
407
|
+
} finally {
|
|
408
|
+
clearInterval(heartbeat);
|
|
409
|
+
request.off("close", onClose);
|
|
410
|
+
response.off("close", onClose);
|
|
411
|
+
if (!closed) response.end();
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
const server = createServer((request, response) => {
|
|
415
|
+
void (async () => {
|
|
416
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
417
|
+
const turnPath = /^\/turns\/([^/]+)\/(events|abort|steer)$/u.exec(url.pathname);
|
|
418
|
+
if (request.method === "GET" && url.pathname === "/health") {
|
|
419
|
+
const health = {
|
|
420
|
+
ok: true,
|
|
421
|
+
protocolVersion: TURN_PROTOCOL_VERSION,
|
|
422
|
+
busy: busy(),
|
|
423
|
+
turnId: current?.id ?? null
|
|
424
|
+
};
|
|
425
|
+
return sendJson(response, 200, health);
|
|
426
|
+
}
|
|
427
|
+
if (request.method === "POST" && url.pathname === "/turns") {
|
|
428
|
+
const { status, body } = await startTurn(parseStartTurn(await readJsonBody(request)));
|
|
429
|
+
return sendJson(response, status, body);
|
|
430
|
+
}
|
|
431
|
+
if (turnPath) {
|
|
432
|
+
const turn = findTurn(decodeURIComponent(turnPath[1]));
|
|
433
|
+
if (!turn) return sendJson(response, 404, { error: "Unknown turn." });
|
|
434
|
+
if (request.method === "GET" && turnPath[2] === "events") {
|
|
435
|
+
const afterParam = url.searchParams.get("after");
|
|
436
|
+
const after = afterParam === null ? -1 : Number(afterParam);
|
|
437
|
+
if (!Number.isSafeInteger(after) || after < -1) {
|
|
438
|
+
return sendJson(response, 400, { error: "after must be an integer of at least -1." });
|
|
439
|
+
}
|
|
440
|
+
return streamTurn(turn, after, request, response);
|
|
441
|
+
}
|
|
442
|
+
if (request.method === "POST" && turnPath[2] === "abort") {
|
|
443
|
+
if (!turn.ending && !turn.finishing && !turn.abortRequested) {
|
|
444
|
+
turn.abortRequested = true;
|
|
445
|
+
turn.closed = true;
|
|
446
|
+
reclaimSteers(turn);
|
|
447
|
+
if (turn === current) void currentSessionAbort?.().catch(() => void 0);
|
|
448
|
+
endAfterGrace(turn, "aborted");
|
|
449
|
+
}
|
|
450
|
+
return sendJson(response, 202, { turnId: turn.id, ended: turn.ended });
|
|
451
|
+
}
|
|
452
|
+
if (request.method === "POST" && turnPath[2] === "steer") {
|
|
453
|
+
const { steerId, message } = parseSteerTurn(await readJsonBody(request));
|
|
454
|
+
const known = turn.steers.get(steerId);
|
|
455
|
+
if (!known && (turn !== current || turn.closed)) {
|
|
456
|
+
return sendJson(response, 409, { error: "The turn is no longer running.", turnId: turn.id });
|
|
457
|
+
}
|
|
458
|
+
const steer = known ?? acceptSteer(turn, steerId, message);
|
|
459
|
+
await steer.settled;
|
|
460
|
+
if (steer.state === "failed") throw steer.error;
|
|
461
|
+
if (steer.state === "undelivered" && !turn.closed) {
|
|
462
|
+
return sendJson(response, 501, { error: "The session does not take steering messages." });
|
|
463
|
+
}
|
|
464
|
+
if (steer.late || steer.state === "undelivered") {
|
|
465
|
+
return sendJson(response, 409, { error: "The turn is no longer running.", turnId: turn.id });
|
|
466
|
+
}
|
|
467
|
+
return sendJson(response, known ? 200 : 202, {
|
|
468
|
+
turnId: turn.id,
|
|
469
|
+
steerId,
|
|
470
|
+
...steer.state === "handled" ? { handled: true } : {}
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
sendJson(response, 404, { error: "Not found." });
|
|
475
|
+
})().catch((error) => {
|
|
476
|
+
if (response.headersSent) {
|
|
477
|
+
response.destroy();
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
const status = error instanceof RequestError ? error.status : 500;
|
|
481
|
+
sendJson(response, status, { error: error instanceof Error ? error.message : String(error) });
|
|
482
|
+
});
|
|
483
|
+
});
|
|
484
|
+
const port = options.port ?? (Number(process.env.NECKBEARD_PORT) || DEFAULT_PORT);
|
|
485
|
+
await new Promise((resolve, reject) => {
|
|
486
|
+
server.once("error", reject);
|
|
487
|
+
server.listen(port, options.host ?? "0.0.0.0", () => {
|
|
488
|
+
server.off("error", reject);
|
|
489
|
+
resolve();
|
|
490
|
+
});
|
|
491
|
+
});
|
|
492
|
+
return {
|
|
493
|
+
port: server.address().port,
|
|
494
|
+
close: () => new Promise((resolve, reject) => {
|
|
495
|
+
server.closeAllConnections();
|
|
496
|
+
server.close((error) => error ? reject(error) : resolve());
|
|
497
|
+
})
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
export {
|
|
502
|
+
TURN_PROTOCOL_VERSION,
|
|
503
|
+
parseTurnRecord,
|
|
504
|
+
parseTurnHealth,
|
|
505
|
+
getPiTurnResult,
|
|
506
|
+
toPiJsonEvent,
|
|
507
|
+
serve
|
|
508
|
+
};
|