agent-neckbeard 1.1.27 → 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 +11 -0
- package/README.md +53 -461
- 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 +1444 -146
- package/dist/index.d.cts +312 -6
- package/dist/index.d.ts +312 -6
- package/dist/index.js +36 -3397
- 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 +14 -12
- package/docs/SUPERVISOR.md +2 -2
- package/package.json +43 -3
- package/dist/chunk-6GCQOKYI.js +0 -48
|
@@ -1,48 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
|
+
decodeSseStream,
|
|
2
3
|
isHarnessEvent
|
|
3
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-KG6SJM74.js";
|
|
4
5
|
import "./chunk-33IXN6MM.js";
|
|
5
6
|
|
|
6
|
-
// src/sse-framing.ts
|
|
7
|
-
async function* decodeSseStream(chunks) {
|
|
8
|
-
let buffer = "";
|
|
9
|
-
for await (const chunk of chunks) {
|
|
10
|
-
buffer += chunk;
|
|
11
|
-
let boundary = buffer.indexOf("\n\n");
|
|
12
|
-
while (boundary !== -1) {
|
|
13
|
-
const rawFrame = buffer.slice(0, boundary);
|
|
14
|
-
buffer = buffer.slice(boundary + 2);
|
|
15
|
-
const parsed = parseFrame(rawFrame);
|
|
16
|
-
if (parsed !== void 0) {
|
|
17
|
-
yield parsed;
|
|
18
|
-
}
|
|
19
|
-
boundary = buffer.indexOf("\n\n");
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
const tail = buffer.trim();
|
|
23
|
-
if (tail.length > 0) {
|
|
24
|
-
const parsed = parseFrame(tail);
|
|
25
|
-
if (parsed !== void 0) {
|
|
26
|
-
yield parsed;
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
function parseFrame(raw) {
|
|
31
|
-
const dataLines = [];
|
|
32
|
-
for (const line of raw.split("\n")) {
|
|
33
|
-
if (line.startsWith("data:")) {
|
|
34
|
-
dataLines.push(line.slice("data:".length).replace(/^ /, ""));
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
if (dataLines.length === 0) return void 0;
|
|
38
|
-
try {
|
|
39
|
-
return JSON.parse(dataLines.join("\n"));
|
|
40
|
-
} catch (error) {
|
|
41
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
42
|
-
throw new Error(`Malformed SSE data frame: ${message}`);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
7
|
// src/invoke-client.ts
|
|
47
8
|
var InvokeHttpError = class extends Error {
|
|
48
9
|
constructor(status, message) {
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire contract between `Agent` on the host and `serve()` in the sandbox. See docs/AGENT.md.
|
|
3
|
+
*/
|
|
4
|
+
declare const TURN_PROTOCOL_VERSION = 2;
|
|
5
|
+
/** One record of a turn's stream. `seq` starts at 0 and increases by one per record. */
|
|
6
|
+
type TurnRecord<TEvent = unknown> = {
|
|
7
|
+
seq: number;
|
|
8
|
+
type: 'event';
|
|
9
|
+
event: TEvent;
|
|
10
|
+
} | {
|
|
11
|
+
seq: number;
|
|
12
|
+
type: 'end';
|
|
13
|
+
outcome: TurnOutcome;
|
|
14
|
+
error?: string;
|
|
15
|
+
};
|
|
16
|
+
type TurnOutcome = 'completed' | 'aborted' | 'failed';
|
|
17
|
+
interface StartTurnRequest {
|
|
18
|
+
/** Caller-chosen, stable per turn, so a retried start never runs the turn twice. */
|
|
19
|
+
turnId: string;
|
|
20
|
+
message: string;
|
|
21
|
+
/** Set in the agent's `process.env` for this turn only, then restored. */
|
|
22
|
+
env?: Record<string, string>;
|
|
23
|
+
}
|
|
24
|
+
interface TurnHealth {
|
|
25
|
+
ok: true;
|
|
26
|
+
protocolVersion: number;
|
|
27
|
+
busy: boolean;
|
|
28
|
+
turnId: string | null;
|
|
29
|
+
}
|
|
30
|
+
type PiTurnResult = {
|
|
31
|
+
completed: true;
|
|
32
|
+
text: string | null;
|
|
33
|
+
} | {
|
|
34
|
+
completed: false;
|
|
35
|
+
error: string;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* How a turn of a Pi session ended, from its records: completed when they include its `end`
|
|
39
|
+
* record, the turn ended normally, and its last assistant message stopped on its own, with that
|
|
40
|
+
* message's text. Records without an `end` record have not shown how the turn ended.
|
|
41
|
+
*/
|
|
42
|
+
declare function getPiTurnResult(records: readonly TurnRecord[]): PiTurnResult;
|
|
43
|
+
|
|
44
|
+
/** The parts of a Pi `AgentSession` the bridge drives. */
|
|
45
|
+
interface ServedSession {
|
|
46
|
+
subscribe(listener: (event: unknown) => void): () => void;
|
|
47
|
+
prompt(text: string): Promise<void>;
|
|
48
|
+
abort(): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Runs once each turn's outcome is known: outside its deadline, so it can't fail the turn, and
|
|
51
|
+
* before its end record, so a host that deletes the sandbox at the end loses nothing, as when
|
|
52
|
+
* sending the turn's trace. An abort that arrives meanwhile changes nothing. Keep it bounded; it
|
|
53
|
+
* delays the end record. Its errors are ignored.
|
|
54
|
+
*/
|
|
55
|
+
afterTurn?(): Promise<void>;
|
|
56
|
+
}
|
|
57
|
+
interface ServeOptions {
|
|
58
|
+
/** Creates the agent's session before its first turn; the session is reused for every later turn. */
|
|
59
|
+
createSession(): Promise<ServedSession>;
|
|
60
|
+
/** Converts a session event for the wire. Defaults to Pi's JSON event form. */
|
|
61
|
+
toWireEvent?: (event: unknown) => unknown;
|
|
62
|
+
/** Defaults to `NECKBEARD_PORT`, then 8080. */
|
|
63
|
+
port?: number;
|
|
64
|
+
host?: string;
|
|
65
|
+
/** Aborts a turn that runs longer, ending it `failed`. */
|
|
66
|
+
maxTurnDurationMs?: number;
|
|
67
|
+
/**
|
|
68
|
+
* How long an aborted or timed-out turn may take to stop before its end record is written anyway,
|
|
69
|
+
* since Pi waits for a running tool. The runtime stays busy until the prompt returns. Defaults to 10 seconds.
|
|
70
|
+
*/
|
|
71
|
+
abortGraceMs?: number;
|
|
72
|
+
}
|
|
73
|
+
interface ServeHandle {
|
|
74
|
+
port: number;
|
|
75
|
+
close(): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Pi's JSON event form, which its JSON and RPC modes write: `message_update` drops the
|
|
79
|
+
* cumulative `partial` message, which the deltas rebuild, and keeps the usage.
|
|
80
|
+
*/
|
|
81
|
+
declare function toPiJsonEvent(event: unknown): unknown;
|
|
82
|
+
/**
|
|
83
|
+
* Serves a Pi session over HTTP for `Agent` on the host. Run it as the sandbox image's main
|
|
84
|
+
* process. One turn runs at a time, a turn keeps running when its stream disconnects, and a
|
|
85
|
+
* stream resumes from any `seq` of the current or previous turn.
|
|
86
|
+
*/
|
|
87
|
+
declare function serve(options: ServeOptions): Promise<ServeHandle>;
|
|
88
|
+
|
|
89
|
+
export { type PiTurnResult as P, type StartTurnRequest as S, type TurnRecord as T, type TurnHealth as a, type ServedSession as b, type ServeHandle as c, TURN_PROTOCOL_VERSION as d, type TurnOutcome as e, type ServeOptions as f, getPiTurnResult as g, serve as s, toPiJsonEvent as t };
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire contract between `Agent` on the host and `serve()` in the sandbox. See docs/AGENT.md.
|
|
3
|
+
*/
|
|
4
|
+
declare const TURN_PROTOCOL_VERSION = 2;
|
|
5
|
+
/** One record of a turn's stream. `seq` starts at 0 and increases by one per record. */
|
|
6
|
+
type TurnRecord<TEvent = unknown> = {
|
|
7
|
+
seq: number;
|
|
8
|
+
type: 'event';
|
|
9
|
+
event: TEvent;
|
|
10
|
+
} | {
|
|
11
|
+
seq: number;
|
|
12
|
+
type: 'end';
|
|
13
|
+
outcome: TurnOutcome;
|
|
14
|
+
error?: string;
|
|
15
|
+
};
|
|
16
|
+
type TurnOutcome = 'completed' | 'aborted' | 'failed';
|
|
17
|
+
interface StartTurnRequest {
|
|
18
|
+
/** Caller-chosen, stable per turn, so a retried start never runs the turn twice. */
|
|
19
|
+
turnId: string;
|
|
20
|
+
message: string;
|
|
21
|
+
/** Set in the agent's `process.env` for this turn only, then restored. */
|
|
22
|
+
env?: Record<string, string>;
|
|
23
|
+
}
|
|
24
|
+
interface TurnHealth {
|
|
25
|
+
ok: true;
|
|
26
|
+
protocolVersion: number;
|
|
27
|
+
busy: boolean;
|
|
28
|
+
turnId: string | null;
|
|
29
|
+
}
|
|
30
|
+
type PiTurnResult = {
|
|
31
|
+
completed: true;
|
|
32
|
+
text: string | null;
|
|
33
|
+
} | {
|
|
34
|
+
completed: false;
|
|
35
|
+
error: string;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* How a turn of a Pi session ended, from its records: completed when they include its `end`
|
|
39
|
+
* record, the turn ended normally, and its last assistant message stopped on its own, with that
|
|
40
|
+
* message's text. Records without an `end` record have not shown how the turn ended.
|
|
41
|
+
*/
|
|
42
|
+
declare function getPiTurnResult(records: readonly TurnRecord[]): PiTurnResult;
|
|
43
|
+
|
|
44
|
+
/** The parts of a Pi `AgentSession` the bridge drives. */
|
|
45
|
+
interface ServedSession {
|
|
46
|
+
subscribe(listener: (event: unknown) => void): () => void;
|
|
47
|
+
prompt(text: string): Promise<void>;
|
|
48
|
+
abort(): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Runs once each turn's outcome is known: outside its deadline, so it can't fail the turn, and
|
|
51
|
+
* before its end record, so a host that deletes the sandbox at the end loses nothing, as when
|
|
52
|
+
* sending the turn's trace. An abort that arrives meanwhile changes nothing. Keep it bounded; it
|
|
53
|
+
* delays the end record. Its errors are ignored.
|
|
54
|
+
*/
|
|
55
|
+
afterTurn?(): Promise<void>;
|
|
56
|
+
}
|
|
57
|
+
interface ServeOptions {
|
|
58
|
+
/** Creates the agent's session before its first turn; the session is reused for every later turn. */
|
|
59
|
+
createSession(): Promise<ServedSession>;
|
|
60
|
+
/** Converts a session event for the wire. Defaults to Pi's JSON event form. */
|
|
61
|
+
toWireEvent?: (event: unknown) => unknown;
|
|
62
|
+
/** Defaults to `NECKBEARD_PORT`, then 8080. */
|
|
63
|
+
port?: number;
|
|
64
|
+
host?: string;
|
|
65
|
+
/** Aborts a turn that runs longer, ending it `failed`. */
|
|
66
|
+
maxTurnDurationMs?: number;
|
|
67
|
+
/**
|
|
68
|
+
* How long an aborted or timed-out turn may take to stop before its end record is written anyway,
|
|
69
|
+
* since Pi waits for a running tool. The runtime stays busy until the prompt returns. Defaults to 10 seconds.
|
|
70
|
+
*/
|
|
71
|
+
abortGraceMs?: number;
|
|
72
|
+
}
|
|
73
|
+
interface ServeHandle {
|
|
74
|
+
port: number;
|
|
75
|
+
close(): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Pi's JSON event form, which its JSON and RPC modes write: `message_update` drops the
|
|
79
|
+
* cumulative `partial` message, which the deltas rebuild, and keeps the usage.
|
|
80
|
+
*/
|
|
81
|
+
declare function toPiJsonEvent(event: unknown): unknown;
|
|
82
|
+
/**
|
|
83
|
+
* Serves a Pi session over HTTP for `Agent` on the host. Run it as the sandbox image's main
|
|
84
|
+
* process. One turn runs at a time, a turn keeps running when its stream disconnects, and a
|
|
85
|
+
* stream resumes from any `seq` of the current or previous turn.
|
|
86
|
+
*/
|
|
87
|
+
declare function serve(options: ServeOptions): Promise<ServeHandle>;
|
|
88
|
+
|
|
89
|
+
export { type PiTurnResult as P, type StartTurnRequest as S, type TurnRecord as T, type TurnHealth as a, type ServedSession as b, type ServeHandle as c, TURN_PROTOCOL_VERSION as d, type TurnOutcome as e, type ServeOptions as f, getPiTurnResult as g, serve as s, toPiJsonEvent as t };
|
package/dist/serve.cjs
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/serve.ts
|
|
21
|
+
var serve_exports = {};
|
|
22
|
+
__export(serve_exports, {
|
|
23
|
+
serve: () => serve,
|
|
24
|
+
toPiJsonEvent: () => toPiJsonEvent
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(serve_exports);
|
|
27
|
+
var import_node_http = require("http");
|
|
28
|
+
|
|
29
|
+
// src/turn-protocol.ts
|
|
30
|
+
var TURN_PROTOCOL_VERSION = 2;
|
|
31
|
+
var MAX_TURN_REQUEST_BYTES = 4 * 1024 * 1024;
|
|
32
|
+
var MAX_TURN_ID_LENGTH = 200;
|
|
33
|
+
function isRecord(value) {
|
|
34
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/serve.ts
|
|
38
|
+
var HEARTBEAT_INTERVAL_MS = 15e3;
|
|
39
|
+
var DEFAULT_ABORT_GRACE_MS = 1e4;
|
|
40
|
+
var DEFAULT_PORT = 8080;
|
|
41
|
+
function toPiJsonEvent(event) {
|
|
42
|
+
if (!isRecord(event) || event.type !== "message_update") return event;
|
|
43
|
+
const { message, assistantMessageEvent } = event;
|
|
44
|
+
if (!isRecord(message) || message.role !== "assistant") {
|
|
45
|
+
throw new Error("message_update message is not an assistant message");
|
|
46
|
+
}
|
|
47
|
+
if (!isRecord(assistantMessageEvent) || typeof assistantMessageEvent.type !== "string") {
|
|
48
|
+
throw new Error("message_update has no assistantMessageEvent");
|
|
49
|
+
}
|
|
50
|
+
const { partial, ...delta } = assistantMessageEvent;
|
|
51
|
+
if (assistantMessageEvent.type === "toolcall_start") {
|
|
52
|
+
const { contentIndex } = assistantMessageEvent;
|
|
53
|
+
const content = isRecord(partial) && Array.isArray(partial.content) ? partial.content : [];
|
|
54
|
+
const toolCall = typeof contentIndex === "number" ? content[contentIndex] : void 0;
|
|
55
|
+
if (!isRecord(toolCall) || toolCall.type !== "toolCall" || typeof toolCall.id !== "string" || typeof toolCall.name !== "string") {
|
|
56
|
+
throw new Error(`toolcall_start content at index ${String(contentIndex)} is not a tool call`);
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
type: "message_update",
|
|
60
|
+
usage: message.usage,
|
|
61
|
+
assistantMessageEvent: { ...delta, id: toolCall.id, toolName: toolCall.name }
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
return { type: "message_update", usage: message.usage, assistantMessageEvent: delta };
|
|
65
|
+
}
|
|
66
|
+
var RequestError = class extends Error {
|
|
67
|
+
constructor(status, message) {
|
|
68
|
+
super(message);
|
|
69
|
+
this.status = status;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
function sendJson(response, status, body) {
|
|
73
|
+
response.writeHead(status, { "content-type": "application/json" });
|
|
74
|
+
response.end(JSON.stringify(body));
|
|
75
|
+
}
|
|
76
|
+
async function readJsonBody(request) {
|
|
77
|
+
const chunks = [];
|
|
78
|
+
let size = 0;
|
|
79
|
+
for await (const chunk of request) {
|
|
80
|
+
size += chunk.byteLength;
|
|
81
|
+
if (size > MAX_TURN_REQUEST_BYTES) throw new RequestError(413, "Request body is too large.");
|
|
82
|
+
chunks.push(chunk);
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
86
|
+
} catch {
|
|
87
|
+
throw new RequestError(400, "Request body must be JSON.");
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function parseStartTurn(body) {
|
|
91
|
+
if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
|
|
92
|
+
const { turnId, message, env } = body;
|
|
93
|
+
if (typeof turnId !== "string" || !turnId || turnId.length > MAX_TURN_ID_LENGTH) {
|
|
94
|
+
throw new RequestError(400, `turnId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
|
|
95
|
+
}
|
|
96
|
+
if (typeof message !== "string" || !message.trim()) {
|
|
97
|
+
throw new RequestError(400, "message must be a non-empty string.");
|
|
98
|
+
}
|
|
99
|
+
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"))) {
|
|
100
|
+
throw new RequestError(400, "env must map environment variable names to strings.");
|
|
101
|
+
}
|
|
102
|
+
return { turnId, message, ...env === void 0 ? {} : { env } };
|
|
103
|
+
}
|
|
104
|
+
async function serve(options) {
|
|
105
|
+
const toWireEvent = options.toWireEvent ?? toPiJsonEvent;
|
|
106
|
+
let sessionPromise;
|
|
107
|
+
let current;
|
|
108
|
+
let previous;
|
|
109
|
+
let currentSessionAbort;
|
|
110
|
+
const findTurn = (turnId) => current?.id === turnId ? current : previous?.id === turnId ? previous : void 0;
|
|
111
|
+
const append = (turn, record) => {
|
|
112
|
+
const json = JSON.stringify({ seq: turn.records.length, ...record });
|
|
113
|
+
turn.records.push(json);
|
|
114
|
+
for (const wake of turn.waiters) wake();
|
|
115
|
+
};
|
|
116
|
+
const end = (turn, outcome, error) => {
|
|
117
|
+
if (turn.ended) return;
|
|
118
|
+
append(turn, { type: "end", outcome, ...error === void 0 ? {} : { error } });
|
|
119
|
+
turn.ended = true;
|
|
120
|
+
};
|
|
121
|
+
const endAfterGrace = (turn, outcome, error) => {
|
|
122
|
+
if (turn.ended || turn.finishing || turn.forceEnd) return;
|
|
123
|
+
turn.forceEnd = setTimeout(() => end(turn, outcome, error), options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS);
|
|
124
|
+
};
|
|
125
|
+
const runTurn = async (turn, request) => {
|
|
126
|
+
const previousEnv = /* @__PURE__ */ new Map();
|
|
127
|
+
let unsubscribe;
|
|
128
|
+
let timedOut = false;
|
|
129
|
+
let session;
|
|
130
|
+
const timeoutMessage = `Turn exceeded ${options.maxTurnDurationMs}ms.`;
|
|
131
|
+
const timer = options.maxTurnDurationMs === void 0 ? void 0 : setTimeout(() => {
|
|
132
|
+
timedOut = true;
|
|
133
|
+
if (session) void session.abort().catch(() => void 0);
|
|
134
|
+
endAfterGrace(turn, "failed", timeoutMessage);
|
|
135
|
+
}, options.maxTurnDurationMs);
|
|
136
|
+
const finish = async (outcome, error) => {
|
|
137
|
+
turn.finishing = true;
|
|
138
|
+
if (timer) clearTimeout(timer);
|
|
139
|
+
clearTimeout(turn.forceEnd);
|
|
140
|
+
try {
|
|
141
|
+
await session?.afterTurn?.();
|
|
142
|
+
} catch {
|
|
143
|
+
}
|
|
144
|
+
end(turn, outcome, error);
|
|
145
|
+
};
|
|
146
|
+
try {
|
|
147
|
+
sessionPromise ??= options.createSession();
|
|
148
|
+
try {
|
|
149
|
+
session = await sessionPromise;
|
|
150
|
+
} catch (error) {
|
|
151
|
+
sessionPromise = void 0;
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
if (timedOut) {
|
|
155
|
+
end(turn, "failed", timeoutMessage);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const started = session;
|
|
159
|
+
for (const [name, value] of Object.entries(request.env ?? {})) {
|
|
160
|
+
previousEnv.set(name, process.env[name]);
|
|
161
|
+
process.env[name] = value;
|
|
162
|
+
}
|
|
163
|
+
unsubscribe = session.subscribe((event) => {
|
|
164
|
+
if (turn.ended) return;
|
|
165
|
+
try {
|
|
166
|
+
append(turn, { type: "event", event: toWireEvent(event) });
|
|
167
|
+
} catch (error) {
|
|
168
|
+
end(turn, "failed", `Could not convert an agent event: ${error instanceof Error ? error.message : String(error)}`);
|
|
169
|
+
void started.abort().catch(() => void 0);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
currentSessionAbort = () => started.abort();
|
|
173
|
+
if (turn.abortRequested) {
|
|
174
|
+
end(turn, "aborted");
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
await started.prompt(request.message);
|
|
178
|
+
if (timedOut) await finish("failed", timeoutMessage);
|
|
179
|
+
else await finish(turn.abortRequested ? "aborted" : "completed");
|
|
180
|
+
} catch (error) {
|
|
181
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
182
|
+
if (timedOut) await finish("failed", timeoutMessage);
|
|
183
|
+
else await finish(turn.abortRequested ? "aborted" : "failed", turn.abortRequested ? void 0 : message);
|
|
184
|
+
} finally {
|
|
185
|
+
if (timer) clearTimeout(timer);
|
|
186
|
+
clearTimeout(turn.forceEnd);
|
|
187
|
+
unsubscribe?.();
|
|
188
|
+
currentSessionAbort = void 0;
|
|
189
|
+
for (const [name, value] of previousEnv) {
|
|
190
|
+
if (value === void 0) delete process.env[name];
|
|
191
|
+
else process.env[name] = value;
|
|
192
|
+
}
|
|
193
|
+
turn.settled = true;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
const busy = () => Boolean(current && !current.settled);
|
|
197
|
+
const startTurn = async (request) => {
|
|
198
|
+
const existing = findTurn(request.turnId);
|
|
199
|
+
if (existing) return { status: 200, body: { turnId: existing.id, ended: existing.ended } };
|
|
200
|
+
if (current && !current.settled) {
|
|
201
|
+
return { status: 409, body: { error: "Another turn is running.", turnId: current.id } };
|
|
202
|
+
}
|
|
203
|
+
const turn = {
|
|
204
|
+
id: request.turnId,
|
|
205
|
+
records: [],
|
|
206
|
+
ended: false,
|
|
207
|
+
settled: false,
|
|
208
|
+
abortRequested: false,
|
|
209
|
+
finishing: false,
|
|
210
|
+
waiters: /* @__PURE__ */ new Set()
|
|
211
|
+
};
|
|
212
|
+
previous = current;
|
|
213
|
+
current = turn;
|
|
214
|
+
void runTurn(turn, request);
|
|
215
|
+
return { status: 202, body: { turnId: turn.id, ended: false } };
|
|
216
|
+
};
|
|
217
|
+
const streamTurn = async (turn, after, request, response) => {
|
|
218
|
+
response.writeHead(200, {
|
|
219
|
+
"content-type": "text/event-stream",
|
|
220
|
+
"cache-control": "no-cache, no-transform",
|
|
221
|
+
connection: "keep-alive",
|
|
222
|
+
"x-accel-buffering": "no"
|
|
223
|
+
});
|
|
224
|
+
response.write(": connected\n\n");
|
|
225
|
+
let closed = false;
|
|
226
|
+
let wake;
|
|
227
|
+
const onClose = () => {
|
|
228
|
+
closed = true;
|
|
229
|
+
wake?.();
|
|
230
|
+
};
|
|
231
|
+
request.on("close", onClose);
|
|
232
|
+
response.on("close", onClose);
|
|
233
|
+
const heartbeat = setInterval(() => {
|
|
234
|
+
if (!closed) response.write(": ping\n\n");
|
|
235
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
236
|
+
let next = turn.ended ? Math.min(after + 1, turn.records.length - 1) : after + 1;
|
|
237
|
+
try {
|
|
238
|
+
while (!closed) {
|
|
239
|
+
while (!closed && next < turn.records.length) {
|
|
240
|
+
const ok = response.write(`id: ${next}
|
|
241
|
+
data: ${turn.records[next]}
|
|
242
|
+
|
|
243
|
+
`);
|
|
244
|
+
next += 1;
|
|
245
|
+
if (!ok && !closed) {
|
|
246
|
+
let onDrain;
|
|
247
|
+
await new Promise((resolve) => {
|
|
248
|
+
wake = onDrain = resolve;
|
|
249
|
+
response.once("drain", resolve);
|
|
250
|
+
});
|
|
251
|
+
if (onDrain) response.off("drain", onDrain);
|
|
252
|
+
wake = void 0;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (closed || turn.ended && next >= turn.records.length) break;
|
|
256
|
+
await new Promise((resolve) => {
|
|
257
|
+
wake = resolve;
|
|
258
|
+
turn.waiters.add(resolve);
|
|
259
|
+
});
|
|
260
|
+
if (wake) turn.waiters.delete(wake);
|
|
261
|
+
wake = void 0;
|
|
262
|
+
}
|
|
263
|
+
} finally {
|
|
264
|
+
clearInterval(heartbeat);
|
|
265
|
+
request.off("close", onClose);
|
|
266
|
+
response.off("close", onClose);
|
|
267
|
+
if (!closed) response.end();
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
const server = (0, import_node_http.createServer)((request, response) => {
|
|
271
|
+
void (async () => {
|
|
272
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
273
|
+
const turnPath = /^\/turns\/([^/]+)\/(events|abort)$/u.exec(url.pathname);
|
|
274
|
+
if (request.method === "GET" && url.pathname === "/health") {
|
|
275
|
+
const health = {
|
|
276
|
+
ok: true,
|
|
277
|
+
protocolVersion: TURN_PROTOCOL_VERSION,
|
|
278
|
+
busy: busy(),
|
|
279
|
+
turnId: current?.id ?? null
|
|
280
|
+
};
|
|
281
|
+
return sendJson(response, 200, health);
|
|
282
|
+
}
|
|
283
|
+
if (request.method === "POST" && url.pathname === "/turns") {
|
|
284
|
+
const { status, body } = await startTurn(parseStartTurn(await readJsonBody(request)));
|
|
285
|
+
return sendJson(response, status, body);
|
|
286
|
+
}
|
|
287
|
+
if (turnPath) {
|
|
288
|
+
const turn = findTurn(decodeURIComponent(turnPath[1]));
|
|
289
|
+
if (!turn) return sendJson(response, 404, { error: "Unknown turn." });
|
|
290
|
+
if (request.method === "GET" && turnPath[2] === "events") {
|
|
291
|
+
const afterParam = url.searchParams.get("after");
|
|
292
|
+
const after = afterParam === null ? -1 : Number(afterParam);
|
|
293
|
+
if (!Number.isSafeInteger(after) || after < -1) {
|
|
294
|
+
return sendJson(response, 400, { error: "after must be an integer of at least -1." });
|
|
295
|
+
}
|
|
296
|
+
return streamTurn(turn, after, request, response);
|
|
297
|
+
}
|
|
298
|
+
if (request.method === "POST" && turnPath[2] === "abort") {
|
|
299
|
+
if (!turn.ended && !turn.finishing && !turn.abortRequested) {
|
|
300
|
+
turn.abortRequested = true;
|
|
301
|
+
if (turn === current) void currentSessionAbort?.().catch(() => void 0);
|
|
302
|
+
endAfterGrace(turn, "aborted");
|
|
303
|
+
}
|
|
304
|
+
return sendJson(response, 202, { turnId: turn.id, ended: turn.ended });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
sendJson(response, 404, { error: "Not found." });
|
|
308
|
+
})().catch((error) => {
|
|
309
|
+
if (response.headersSent) {
|
|
310
|
+
response.destroy();
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
const status = error instanceof RequestError ? error.status : 500;
|
|
314
|
+
sendJson(response, status, { error: error instanceof Error ? error.message : String(error) });
|
|
315
|
+
});
|
|
316
|
+
});
|
|
317
|
+
const port = options.port ?? (Number(process.env.NECKBEARD_PORT) || DEFAULT_PORT);
|
|
318
|
+
await new Promise((resolve, reject) => {
|
|
319
|
+
server.once("error", reject);
|
|
320
|
+
server.listen(port, options.host ?? "0.0.0.0", () => {
|
|
321
|
+
server.off("error", reject);
|
|
322
|
+
resolve();
|
|
323
|
+
});
|
|
324
|
+
});
|
|
325
|
+
return {
|
|
326
|
+
port: server.address().port,
|
|
327
|
+
close: () => new Promise((resolve, reject) => {
|
|
328
|
+
server.closeAllConnections();
|
|
329
|
+
server.close((error) => error ? reject(error) : resolve());
|
|
330
|
+
})
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
334
|
+
0 && (module.exports = {
|
|
335
|
+
serve,
|
|
336
|
+
toPiJsonEvent
|
|
337
|
+
});
|
package/dist/serve.d.cts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { c as ServeHandle, f as ServeOptions, b as ServedSession, e as TurnOutcome, T as TurnRecord, s as serve, t as toPiJsonEvent } from './serve-Dan1HQKN.cjs';
|
package/dist/serve.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { c as ServeHandle, f as ServeOptions, b as ServedSession, e as TurnOutcome, T as TurnRecord, s as serve, t as toPiJsonEvent } from './serve-Dan1HQKN.js';
|