@loomwork/plugin-conversation-sse 0.0.0-stage → 0.1.1
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/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +39 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/server.d.ts +106 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +669 -0
- package/dist/server.js.map +1 -0
- package/dist/sse.d.ts +29 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +107 -0
- package/dist/sse.js.map +1 -0
- package/package.json +61 -3
- package/src/index.ts +7 -0
- package/src/server.ts +806 -0
- package/src/sse.ts +106 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,806 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import * as http from "node:http";
|
|
3
|
+
import type { AddressInfo } from "node:net";
|
|
4
|
+
import { unwrapTainted } from "@loomwork/classify";
|
|
5
|
+
import {
|
|
6
|
+
type ConversationHub,
|
|
7
|
+
ConversationNotFoundError,
|
|
8
|
+
type Conversations,
|
|
9
|
+
InvalidCursorError,
|
|
10
|
+
InvalidTurnError,
|
|
11
|
+
ParticipantLimitError,
|
|
12
|
+
QueueFullError,
|
|
13
|
+
SubscriberLimitError,
|
|
14
|
+
followConversation,
|
|
15
|
+
isValidConversationId,
|
|
16
|
+
parseCursor,
|
|
17
|
+
parseIdentity,
|
|
18
|
+
} from "@loomwork/conversation";
|
|
19
|
+
import { BadRequestError, exposeError } from "@loomwork/core";
|
|
20
|
+
import type { PrincipalChain } from "@loomwork/effect-runtime";
|
|
21
|
+
import type { EventStore } from "@loomwork/event-runtime";
|
|
22
|
+
import { type ReasoningReader, readReasoningBounded } from "@loomwork/llm";
|
|
23
|
+
import {
|
|
24
|
+
ExecutionDeniedError,
|
|
25
|
+
InboxClosedError,
|
|
26
|
+
InboxFullError,
|
|
27
|
+
InboxMessageRefusedError,
|
|
28
|
+
} from "@loomwork/workflow-runtime";
|
|
29
|
+
import { SseSink, frame } from "./sse";
|
|
30
|
+
|
|
31
|
+
// ── The end-user gateway of a conversation (ADR 0122 D6, D10) ───────────────────────────────────────
|
|
32
|
+
//
|
|
33
|
+
// POST /conversations start one (the SERVER mints the id)
|
|
34
|
+
// GET /conversations/:id status
|
|
35
|
+
// POST /conversations/:id/turns send a turn { text, messageId?, editOf? }
|
|
36
|
+
// POST /conversations/:id/close close it
|
|
37
|
+
// GET /conversations/:id/history a bounded page ?limit&cursor&direction
|
|
38
|
+
// GET /conversations/:id/events the SSE stream Last-Event-ID | ?cursor
|
|
39
|
+
// GET /conversations/:id/reasoning?cursor= a reply's durable model reasoning (opt-in, ADR 0133 D6)
|
|
40
|
+
// shared mode:
|
|
41
|
+
// GET /conversations/:id/participants the participant set (owner / manager)
|
|
42
|
+
// POST /conversations/:id/participants { actor, tenant?, onBehalfOf? } add
|
|
43
|
+
// POST /conversations/:id/participants/remove { actor, tenant?, onBehalfOf? } remove
|
|
44
|
+
//
|
|
45
|
+
// SECURITY MODEL. Fail closed at every step, and say nothing a caller was not entitled to.
|
|
46
|
+
// * AUTHENTICATION: every route needs `authenticate(req)` to return a principal with an `actor`;
|
|
47
|
+
// the server REFUSES TO BE CREATED without it unless `insecure: true` (never under strict), and
|
|
48
|
+
// refuses a runtime with no fail-closed execution authorizer unless `allowNoRuntimeAuthz`.
|
|
49
|
+
// * AUTHORIZATION is `@loomwork/conversation`'s, per conversation: OWNER-ONLY by default (the identity that
|
|
50
|
+
// started it), or the explicit participant set of a shared conversation. There is no second ACL here.
|
|
51
|
+
// * EXISTENCE IS HIDDEN: a conversation the caller may not touch and one that does not exist both
|
|
52
|
+
// answer 404 `{"error":"not found"}`, on every route including the stream.
|
|
53
|
+
// * ISOLATION: a stream is keyed by one conversation id; the live hub and the log reader are both
|
|
54
|
+
// keyed by it, and a cursor is a position INSIDE that conversation's chain. Shared mode filters
|
|
55
|
+
// every entry, the stream's deltas and the partial reply PER VIEWER.
|
|
56
|
+
// * REASONING (ADR 0133 D6) is OFF by default, live and durable. When on, it goes to the turn's ASKER and the
|
|
57
|
+
// conversation's OWNER ONLY (in shared mode never to any other participant), over its own SSE event types
|
|
58
|
+
// (`reasoning`, `reasoning-partial`) and its own endpoint; a caller who may not have it gets the same 404
|
|
59
|
+
// as a missing conversation. It is model-derived text restating what the asker's turn saw: it is
|
|
60
|
+
// unwrapped from its untrusted wrapper HERE, at the transport edge, and nowhere earlier.
|
|
61
|
+
// * LOOPBACK by default; a loopback `Host` allowlist protects an unauthenticated server from DNS
|
|
62
|
+
// rebinding. CSRF/CORS: a request carrying an `Origin` must name one of `allowedOrigins` (the
|
|
63
|
+
// `Host` header is never trusted to prove same-origin), POST bodies must be `application/json`.
|
|
64
|
+
// * LIMITS: connections (total, per principal), live subscribers per conversation (the hub's),
|
|
65
|
+
// request body and timeouts, a POST rate limit per principal, per-connection pending bytes (a slow
|
|
66
|
+
// reader is closed), stream lifetime. A connection is re-authenticated periodically; a revoked token
|
|
67
|
+
// or a removed participant ends the stream.
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* ADR 0133 D6 - bounds on one `/reasoning` response. The turn's steps are selected before any blob is
|
|
71
|
+
* fetched, and a reply that still exceeds either cap returns its FIRST parts (log order) with
|
|
72
|
+
* `truncated: true`. 256 parts covers a long tool loop (a part per model call, a few per call); 1 MiB
|
|
73
|
+
* of readable text is far past a normal turn and bounds what one request can make the server read.
|
|
74
|
+
*/
|
|
75
|
+
export const REASONING_RESPONSE_MAX_PARTS = 256;
|
|
76
|
+
export const REASONING_RESPONSE_MAX_BYTES = 1024 * 1024;
|
|
77
|
+
|
|
78
|
+
export interface ConversationSseOptions {
|
|
79
|
+
conversations: Conversations;
|
|
80
|
+
/** Where live deltas come from (the same hub the model effect's `onDelta` feeds). */
|
|
81
|
+
hub: ConversationHub;
|
|
82
|
+
/** The store the conversations' runtime appends to: its subscription wakes the stream. */
|
|
83
|
+
eventStore: EventStore;
|
|
84
|
+
port?: number;
|
|
85
|
+
/** Interface to bind. Default `"127.0.0.1"` (loopback only). */
|
|
86
|
+
host?: string;
|
|
87
|
+
/**
|
|
88
|
+
* Authenticate AND identify the caller from connection facts (a verified bearer token, an mTLS
|
|
89
|
+
* peer): return its principal (`actor` required) or `undefined` to refuse (401). Never derive it
|
|
90
|
+
* from the body or the URL.
|
|
91
|
+
*/
|
|
92
|
+
authenticate?: (
|
|
93
|
+
req: http.IncomingMessage
|
|
94
|
+
) => PrincipalChain | undefined | Promise<PrincipalChain | undefined>;
|
|
95
|
+
/** Explicit opt-out of authentication: any caller that can reach the socket converses. Warned; refused under `strict`. */
|
|
96
|
+
insecure?: boolean;
|
|
97
|
+
/** Fail closed on a principal-less caller. DEFAULTS from the runtime (`requiresPrincipal`), as the A2A server does. */
|
|
98
|
+
strict?: boolean;
|
|
99
|
+
/**
|
|
100
|
+
* Serve a runtime that has no fail-closed execution authorizer (`security.strict` / `executionAuthz:
|
|
101
|
+
* { requirePrincipal: true }`). Refused by default: this server is an edge, and an edge in front of a
|
|
102
|
+
* runtime that admits anonymous calls is a hole the application would have to remember.
|
|
103
|
+
*/
|
|
104
|
+
allowNoRuntimeAuthz?: boolean;
|
|
105
|
+
warn?: (message: string) => void;
|
|
106
|
+
/**
|
|
107
|
+
* Browser origins allowed to call this server, matched exactly. A request with an `Origin` that is
|
|
108
|
+
* not listed is refused: `Host` is attacker-influenced and never proves same-origin. Default none.
|
|
109
|
+
*/
|
|
110
|
+
allowedOrigins?: readonly string[];
|
|
111
|
+
/** Send `access-control-allow-credentials: true` to the listed origins (cookies / `EventSource` `withCredentials`). Default false. */
|
|
112
|
+
allowCredentials?: boolean;
|
|
113
|
+
/**
|
|
114
|
+
* `Host` header values accepted (hostname, port ignored). Default: the loopback names when `insecure`
|
|
115
|
+
* (DNS-rebinding protection for an unauthenticated server); unchecked otherwise.
|
|
116
|
+
*/
|
|
117
|
+
allowedHosts?: readonly string[];
|
|
118
|
+
/** Path prefix. Default `/conversations`. */
|
|
119
|
+
basePath?: string;
|
|
120
|
+
/** Concurrent streams, all callers. Default 256. */
|
|
121
|
+
maxConnections?: number;
|
|
122
|
+
/** Concurrent streams per principal (tenant + actor). Default 8. */
|
|
123
|
+
maxConnectionsPerPrincipal?: number;
|
|
124
|
+
/** Bytes a slow client may leave unread before its stream is closed. Default 1 MiB. */
|
|
125
|
+
maxPendingBytes?: number;
|
|
126
|
+
/** Request body cap, bytes. Default 64 KiB. */
|
|
127
|
+
maxBodyBytes?: number;
|
|
128
|
+
/** Comment heartbeat period, ms. Default 15 000. */
|
|
129
|
+
heartbeatMs?: number;
|
|
130
|
+
/** A stream is ended (the client reconnects with Last-Event-ID) after this long, ms. Default 15 min. */
|
|
131
|
+
maxStreamMs?: number;
|
|
132
|
+
/** How often an open stream re-authenticates and re-authorizes, ms. Default 30 000. */
|
|
133
|
+
reauthMs?: number;
|
|
134
|
+
/** Safety-net poll of the log when no notification arrives, ms. Default 2 000. */
|
|
135
|
+
pollMs?: number;
|
|
136
|
+
/** POSTs (start, turns, close, participants) one principal may make per window. Default 120 per minute. */
|
|
137
|
+
rateLimit?: { max?: number; windowMs?: number };
|
|
138
|
+
/** The clock the rate limit reads (tests). Default `Date.now`. */
|
|
139
|
+
now?: () => number;
|
|
140
|
+
/** Time a client may take to send its request, ms (slowloris). Default 30 000. */
|
|
141
|
+
requestTimeoutMs?: number;
|
|
142
|
+
/** Time a client may take to send its headers, ms. Default 15 000. */
|
|
143
|
+
headersTimeoutMs?: number;
|
|
144
|
+
/** Open sockets the server accepts at all (`http.Server.maxConnections`). Default 4096. */
|
|
145
|
+
maxSockets?: number;
|
|
146
|
+
/**
|
|
147
|
+
* ADR 0133 D6 - serve the model's reasoning. OFF by default. `true` (or `{ live: true }`) streams the
|
|
148
|
+
* `reasoning` / `reasoning-partial` SSE events; `{ store }` also serves a reply's durable reasoning at
|
|
149
|
+
* `GET <base>/:id/reasoning?cursor=<the reply's history cursor>` (the `ReasoningStore` the model effect
|
|
150
|
+
* captured into). In SHARED mode only the turn's asker and the conversation's owner receive any of it.
|
|
151
|
+
*/
|
|
152
|
+
reasoning?: boolean | { live?: boolean; store?: ReasoningReader };
|
|
153
|
+
/** Real error behind a 500, with the `errorId` the caller was given. */
|
|
154
|
+
onError?: (errorId: string, err: unknown) => void;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export interface ConversationSseServer {
|
|
158
|
+
start(): Promise<void>;
|
|
159
|
+
stop(): Promise<void>;
|
|
160
|
+
readonly url: string;
|
|
161
|
+
/** Open streams right now. */
|
|
162
|
+
readonly connections: number;
|
|
163
|
+
/** The underlying `http.Server` (timeouts and limits are set on it; exposed for operators and tests). */
|
|
164
|
+
readonly http: http.Server;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const principalKey = (p: PrincipalChain | undefined): string =>
|
|
168
|
+
p === undefined
|
|
169
|
+
? "anonymous"
|
|
170
|
+
: JSON.stringify([p.tenant ?? null, p.actor ?? null, p.onBehalfOf ?? null]);
|
|
171
|
+
|
|
172
|
+
const hasActor = (p: PrincipalChain): boolean =>
|
|
173
|
+
typeof p.actor === "string" && p.actor.trim().length > 0;
|
|
174
|
+
|
|
175
|
+
class HttpError extends Error {
|
|
176
|
+
constructor(
|
|
177
|
+
readonly status: number,
|
|
178
|
+
readonly body: Record<string, unknown>,
|
|
179
|
+
readonly headers: Record<string, string> = {}
|
|
180
|
+
) {
|
|
181
|
+
super(String(body.error));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const NOT_FOUND = new HttpError(404, { error: "not found" });
|
|
186
|
+
const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]", "::1"];
|
|
187
|
+
|
|
188
|
+
function sendJson(
|
|
189
|
+
res: http.ServerResponse,
|
|
190
|
+
status: number,
|
|
191
|
+
body: unknown,
|
|
192
|
+
headers: Record<string, string> = {}
|
|
193
|
+
): void {
|
|
194
|
+
if (res.headersSent) return;
|
|
195
|
+
res.writeHead(status, {
|
|
196
|
+
"content-type": "application/json; charset=utf-8",
|
|
197
|
+
"cache-control": "no-store",
|
|
198
|
+
"x-content-type-options": "nosniff",
|
|
199
|
+
...headers,
|
|
200
|
+
});
|
|
201
|
+
res.end(JSON.stringify(body));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function readJson(req: http.IncomingMessage, max: number): Promise<unknown> {
|
|
205
|
+
return new Promise((resolve, reject) => {
|
|
206
|
+
const type = (req.headers["content-type"] ?? "").split(";")[0]?.trim().toLowerCase();
|
|
207
|
+
if (type !== "application/json") {
|
|
208
|
+
reject(new HttpError(415, { error: "content-type must be application/json" }));
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const chunks: Uint8Array[] = [];
|
|
212
|
+
let size = 0;
|
|
213
|
+
req.on("data", (c: Uint8Array) => {
|
|
214
|
+
size += c.length;
|
|
215
|
+
if (size > max) {
|
|
216
|
+
// Answer first (a destroyed socket would turn the 413 into a connection reset), then drop
|
|
217
|
+
// the rest of the upload: the response handler closes the connection once it is written.
|
|
218
|
+
chunks.length = 0;
|
|
219
|
+
reject(new HttpError(413, { error: `body exceeds ${max} bytes` }, { connection: "close" }));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (size <= max) chunks.push(c);
|
|
223
|
+
});
|
|
224
|
+
req.on("end", () => {
|
|
225
|
+
try {
|
|
226
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown);
|
|
227
|
+
} catch {
|
|
228
|
+
reject(new BadRequestError("request body is not valid JSON"));
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
req.on("error", reject);
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function createConversationSseServer(
|
|
236
|
+
options: ConversationSseOptions
|
|
237
|
+
): ConversationSseServer {
|
|
238
|
+
const { conversations, hub } = options;
|
|
239
|
+
const host = options.host ?? "127.0.0.1";
|
|
240
|
+
const base = (options.basePath ?? "/conversations").replace(/\/+$/, "");
|
|
241
|
+
const warn = options.warn ?? ((m: string) => console.warn(m));
|
|
242
|
+
const maxConnections = options.maxConnections ?? 256;
|
|
243
|
+
const maxPerPrincipal = options.maxConnectionsPerPrincipal ?? 8;
|
|
244
|
+
const maxPending = options.maxPendingBytes ?? 1024 * 1024;
|
|
245
|
+
const maxBody = options.maxBodyBytes ?? 64 * 1024;
|
|
246
|
+
const heartbeatMs = options.heartbeatMs ?? 15_000;
|
|
247
|
+
const maxStreamMs = options.maxStreamMs ?? 15 * 60_000;
|
|
248
|
+
const reauthMs = options.reauthMs ?? 30_000;
|
|
249
|
+
const allowed = new Set(options.allowedOrigins ?? []);
|
|
250
|
+
const strict = options.strict ?? conversations.requiresPrincipal;
|
|
251
|
+
const rateMax = options.rateLimit?.max ?? 120;
|
|
252
|
+
const rateWindow = options.rateLimit?.windowMs ?? 60_000;
|
|
253
|
+
const now = options.now ?? Date.now;
|
|
254
|
+
const reasoningOpt = options.reasoning === true ? { live: true } : options.reasoning || undefined;
|
|
255
|
+
const liveReasoning = reasoningOpt?.live === true;
|
|
256
|
+
const reasoningStore = reasoningOpt?.store;
|
|
257
|
+
|
|
258
|
+
if (options.authenticate === undefined) {
|
|
259
|
+
if (options.insecure !== true) {
|
|
260
|
+
throw new Error(
|
|
261
|
+
"createConversationSseServer: refusing to create an unauthenticated server. Supply `authenticate`, or pass `insecure: true` to opt out explicitly."
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
if (strict) {
|
|
265
|
+
throw new Error(
|
|
266
|
+
"createConversationSseServer: `insecure: true` is refused under strict — authenticate callers."
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
warn(
|
|
270
|
+
`[loom] WARNING: conversation gateway is running with insecure: true — NO authentication; any caller that can reach ${host} can converse.`
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
if (
|
|
274
|
+
!conversations.requiresPrincipal &&
|
|
275
|
+
options.allowNoRuntimeAuthz !== true &&
|
|
276
|
+
options.insecure !== true
|
|
277
|
+
) {
|
|
278
|
+
throw new Error(
|
|
279
|
+
"createConversationSseServer: the runtime has no fail-closed execution authorizer (executionAuthorizer + executionAuthz.requirePrincipal, i.e. security.strict). Wire one, or pass `allowNoRuntimeAuthz: true` to accept an edge in front of an open runtime."
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
const hostAllow = new Set(
|
|
283
|
+
(options.allowedHosts ?? (options.insecure === true ? LOOPBACK_HOSTS : [])).map((h) =>
|
|
284
|
+
h.toLowerCase()
|
|
285
|
+
)
|
|
286
|
+
);
|
|
287
|
+
|
|
288
|
+
let resolvedUrl = `http://${host.includes(":") ? `[${host}]` : host}:${options.port ?? 0}`;
|
|
289
|
+
const open = new Set<{ close: () => void }>();
|
|
290
|
+
const perPrincipal = new Map<string, number>();
|
|
291
|
+
const rate = new Map<string, { windowStart: number; n: number }>();
|
|
292
|
+
|
|
293
|
+
/** One window counter per principal for the POSTs; the map is bounded (expired entries are swept). */
|
|
294
|
+
function takeRate(key: string): void {
|
|
295
|
+
const t = now();
|
|
296
|
+
if (rate.size > 10_000) {
|
|
297
|
+
for (const [k, v] of rate) if (t - v.windowStart >= rateWindow) rate.delete(k);
|
|
298
|
+
}
|
|
299
|
+
const cur = rate.get(key);
|
|
300
|
+
if (cur === undefined || t - cur.windowStart >= rateWindow) {
|
|
301
|
+
rate.set(key, { windowStart: t, n: 1 });
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
cur.n++;
|
|
305
|
+
if (cur.n > rateMax) {
|
|
306
|
+
throw new HttpError(
|
|
307
|
+
429,
|
|
308
|
+
{ error: "too many requests" },
|
|
309
|
+
{
|
|
310
|
+
"retry-after": String(
|
|
311
|
+
Math.max(1, Math.ceil((rateWindow - (t - cur.windowStart)) / 1000))
|
|
312
|
+
),
|
|
313
|
+
}
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function identify(req: http.IncomingMessage): Promise<PrincipalChain | undefined> {
|
|
319
|
+
if (options.authenticate === undefined) return undefined; // insecure
|
|
320
|
+
const p = await options.authenticate(req);
|
|
321
|
+
if (p === undefined || !hasActor(p)) throw new HttpError(401, { error: "unauthorized" });
|
|
322
|
+
return p;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** DNS rebinding: an unauthenticated loopback server must not answer a request addressed to some other name. */
|
|
326
|
+
function checkHost(req: http.IncomingMessage): void {
|
|
327
|
+
if (hostAllow.size === 0) return;
|
|
328
|
+
const raw = (req.headers.host ?? "").toLowerCase();
|
|
329
|
+
const name = raw.startsWith("[")
|
|
330
|
+
? raw.slice(0, raw.indexOf("]") + 1)
|
|
331
|
+
: (raw.split(":")[0] ?? "");
|
|
332
|
+
if (!hostAllow.has(name)) throw new HttpError(421, { error: "misdirected request" });
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** The allowed browser origin of this request, or a refusal. `Host` is never consulted. */
|
|
336
|
+
function checkOrigin(req: http.IncomingMessage): string | undefined {
|
|
337
|
+
const origin = req.headers.origin;
|
|
338
|
+
if (origin === undefined) return undefined; // not a browser cross-origin request
|
|
339
|
+
if (!allowed.has(origin)) throw new HttpError(403, { error: "origin not allowed" });
|
|
340
|
+
return origin;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** CORS headers for an allowed origin: ride EVERY response, errors included (a browser cannot read a 4xx without them). */
|
|
344
|
+
const corsHeaders = (origin: string | undefined): Record<string, string> =>
|
|
345
|
+
origin === undefined
|
|
346
|
+
? {}
|
|
347
|
+
: {
|
|
348
|
+
"access-control-allow-origin": origin,
|
|
349
|
+
vary: "Origin",
|
|
350
|
+
...(options.allowCredentials === true && { "access-control-allow-credentials": "true" }),
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
const mapError = (err: unknown, notFoundOnDeny: boolean): HttpError => {
|
|
354
|
+
if (err instanceof HttpError) return err;
|
|
355
|
+
if (err instanceof ConversationNotFoundError) return NOT_FOUND;
|
|
356
|
+
if (err instanceof ExecutionDeniedError) {
|
|
357
|
+
return notFoundOnDeny ? NOT_FOUND : new HttpError(403, { error: "forbidden" });
|
|
358
|
+
}
|
|
359
|
+
if (
|
|
360
|
+
err instanceof InvalidTurnError ||
|
|
361
|
+
err instanceof InvalidCursorError ||
|
|
362
|
+
err instanceof BadRequestError ||
|
|
363
|
+
err instanceof InboxMessageRefusedError ||
|
|
364
|
+
err instanceof ParticipantLimitError
|
|
365
|
+
) {
|
|
366
|
+
return new HttpError(400, { error: err.message });
|
|
367
|
+
}
|
|
368
|
+
if (err instanceof InboxClosedError)
|
|
369
|
+
return new HttpError(409, { error: "conversation is closed" });
|
|
370
|
+
if (
|
|
371
|
+
err instanceof InboxFullError ||
|
|
372
|
+
err instanceof SubscriberLimitError ||
|
|
373
|
+
err instanceof QueueFullError
|
|
374
|
+
) {
|
|
375
|
+
return new HttpError(429, { error: "too many requests" }, { "retry-after": "1" });
|
|
376
|
+
}
|
|
377
|
+
const exposed = exposeError(err, randomUUID);
|
|
378
|
+
if (exposed.internal !== undefined) {
|
|
379
|
+
options.onError?.(exposed.body.errorId as string, exposed.internal);
|
|
380
|
+
}
|
|
381
|
+
return new HttpError(exposed.status, exposed.body);
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
async function events(
|
|
385
|
+
req: http.IncomingMessage,
|
|
386
|
+
res: http.ServerResponse,
|
|
387
|
+
id: string,
|
|
388
|
+
principal: PrincipalChain | undefined,
|
|
389
|
+
url: URL,
|
|
390
|
+
cors: Record<string, string>
|
|
391
|
+
): Promise<void> {
|
|
392
|
+
const callOpts = principal !== undefined ? { principal } : {};
|
|
393
|
+
// The client may hang up while we authorize. Remember it from the first instant: a `close` that
|
|
394
|
+
// fires before the listener below exists would otherwise never be seen, and the slot would be held
|
|
395
|
+
// for the whole stream lifetime.
|
|
396
|
+
let gone = false;
|
|
397
|
+
const onGone = (): void => {
|
|
398
|
+
gone = true;
|
|
399
|
+
};
|
|
400
|
+
req.once("close", onGone);
|
|
401
|
+
res.once("close", onGone);
|
|
402
|
+
const dropped = (): boolean => gone || req.destroyed || res.destroyed || res.writableEnded;
|
|
403
|
+
// AUTHORIZE FIRST: nothing below (not even a limit that would answer 429) may reveal that a
|
|
404
|
+
// conversation exists to a caller who may not read it. `status` is that gate and the first frame.
|
|
405
|
+
const status = await conversations.status(id, callOpts);
|
|
406
|
+
if (dropped()) return;
|
|
407
|
+
const resume =
|
|
408
|
+
(req.headers["last-event-id"] as string | undefined) ??
|
|
409
|
+
url.searchParams.get("cursor") ??
|
|
410
|
+
undefined;
|
|
411
|
+
if (resume !== undefined && parseCursor(resume) === undefined) throw new InvalidCursorError();
|
|
412
|
+
|
|
413
|
+
const key = principalKey(principal);
|
|
414
|
+
if (open.size >= maxConnections || (perPrincipal.get(key) ?? 0) >= maxPerPrincipal) {
|
|
415
|
+
throw new HttpError(429, { error: "too many streams" }, { "retry-after": "5" });
|
|
416
|
+
}
|
|
417
|
+
const viewer = conversations.viewerKey(principal);
|
|
418
|
+
const ctl = new AbortController();
|
|
419
|
+
// Live subscription (a limit here is still an HTTP answer), then the catch-up snapshot of the
|
|
420
|
+
// in-progress reply taken in the same tick, so no delta falls between them.
|
|
421
|
+
const sink = new SseSink(res, maxPending, () => end());
|
|
422
|
+
const deltaFrame = (turn: number, text: string) => frame("delta", { turn, text });
|
|
423
|
+
// SHARED: a live delta streams to the ASKER alone. Whether the answer is restricted is only known when
|
|
424
|
+
// the turn ends (the tools it used), so until then nobody else may see its tokens; they get the
|
|
425
|
+
// durable entry (or a bare placeholder) on completion.
|
|
426
|
+
const mine = (asker: string | undefined): boolean => asker === undefined || asker === viewer;
|
|
427
|
+
// REASONING is stricter than a delta: in shared mode it needs the OWNER, or a KNOWN asker that is this
|
|
428
|
+
// viewer (an event with no asker is never served to anyone else), in owner mode the stream is already the owner's alone.
|
|
429
|
+
const reasoningFrame = (turn: number, text: string) => frame("reasoning", { turn, text });
|
|
430
|
+
// The conversation's OWNER also receives every turn's reasoning (owner ruling 2026-10-20).
|
|
431
|
+
const viewerIsOwner =
|
|
432
|
+
liveReasoning && conversations.mode === "shared"
|
|
433
|
+
? await conversations.isOwner(id, principal)
|
|
434
|
+
: false;
|
|
435
|
+
if (dropped()) return;
|
|
436
|
+
const askerOnly = (asker: string | undefined): boolean =>
|
|
437
|
+
liveReasoning &&
|
|
438
|
+
(conversations.mode !== "shared" ||
|
|
439
|
+
viewerIsOwner ||
|
|
440
|
+
(asker !== undefined && asker === viewer));
|
|
441
|
+
const unsubscribe = hub.subscribe(id, (ev) => {
|
|
442
|
+
if (ev.type === "reasoning") {
|
|
443
|
+
if (askerOnly(ev.asker)) sink.delta(ev.turn, ev.text, reasoningFrame, "reasoning");
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
if (!mine(ev.asker)) return;
|
|
447
|
+
if (ev.type === "delta") sink.delta(ev.turn, ev.text, deltaFrame);
|
|
448
|
+
else sink.send(frame("reset", { turn: ev.turn }));
|
|
449
|
+
});
|
|
450
|
+
const partial = hub.partialOf(id);
|
|
451
|
+
const reasoningPartial = liveReasoning ? hub.reasoningPartialOf(id) : undefined;
|
|
452
|
+
|
|
453
|
+
perPrincipal.set(key, (perPrincipal.get(key) ?? 0) + 1);
|
|
454
|
+
const handle = { close: () => end() };
|
|
455
|
+
open.add(handle);
|
|
456
|
+
let ended = false;
|
|
457
|
+
const timers: NodeJS.Timeout[] = [];
|
|
458
|
+
function end(): void {
|
|
459
|
+
if (ended) return;
|
|
460
|
+
ended = true;
|
|
461
|
+
sink.close();
|
|
462
|
+
ctl.abort();
|
|
463
|
+
for (const t of timers) clearInterval(t);
|
|
464
|
+
unsubscribe();
|
|
465
|
+
open.delete(handle);
|
|
466
|
+
const n = (perPrincipal.get(key) ?? 1) - 1;
|
|
467
|
+
if (n <= 0) perPrincipal.delete(key);
|
|
468
|
+
else perPrincipal.set(key, n);
|
|
469
|
+
res.end();
|
|
470
|
+
}
|
|
471
|
+
// A hang-up that raced the setup above is acted on now, and one that comes later by the listeners.
|
|
472
|
+
req.once("close", end);
|
|
473
|
+
res.once("close", end);
|
|
474
|
+
res.on("error", end);
|
|
475
|
+
if (dropped()) {
|
|
476
|
+
end();
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
res.writeHead(200, {
|
|
481
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
482
|
+
"cache-control": "no-cache, no-transform",
|
|
483
|
+
connection: "keep-alive",
|
|
484
|
+
"x-accel-buffering": "no",
|
|
485
|
+
"x-content-type-options": "nosniff",
|
|
486
|
+
...cors,
|
|
487
|
+
});
|
|
488
|
+
res.flushHeaders();
|
|
489
|
+
sink.send("retry: 3000\n\n");
|
|
490
|
+
sink.send(frame("status", status));
|
|
491
|
+
if (partial !== undefined && mine(partial.asker)) {
|
|
492
|
+
sink.send(frame("partial", { turn: partial.turn, text: partial.text }));
|
|
493
|
+
}
|
|
494
|
+
if (reasoningPartial !== undefined && askerOnly(reasoningPartial.asker)) {
|
|
495
|
+
sink.send(
|
|
496
|
+
frame("reasoning-partial", { turn: reasoningPartial.turn, text: reasoningPartial.text })
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
timers.push(setInterval(() => sink.send(": ping\n\n"), heartbeatMs).unref());
|
|
501
|
+
timers.push(
|
|
502
|
+
setInterval(() => {
|
|
503
|
+
void (async () => {
|
|
504
|
+
try {
|
|
505
|
+
const again = await identify(req);
|
|
506
|
+
if (principalKey(again) !== key) throw new Error("principal changed");
|
|
507
|
+
await conversations.authorizeRead(id, callOpts);
|
|
508
|
+
} catch {
|
|
509
|
+
sink.send(frame("error", { error: "unauthorized" }));
|
|
510
|
+
end();
|
|
511
|
+
}
|
|
512
|
+
})();
|
|
513
|
+
}, reauthMs).unref()
|
|
514
|
+
);
|
|
515
|
+
const lifetime = setTimeout(() => {
|
|
516
|
+
sink.send(frame("reconnect", {}));
|
|
517
|
+
end();
|
|
518
|
+
}, maxStreamMs);
|
|
519
|
+
lifetime.unref();
|
|
520
|
+
timers.push(lifetime as unknown as NodeJS.Timeout);
|
|
521
|
+
|
|
522
|
+
try {
|
|
523
|
+
for await (const item of followConversation(
|
|
524
|
+
{ reader: conversations.reader, eventStore: options.eventStore },
|
|
525
|
+
id,
|
|
526
|
+
{
|
|
527
|
+
...(resume !== undefined && { cursor: resume }),
|
|
528
|
+
signal: ctl.signal,
|
|
529
|
+
...(options.pollMs !== undefined && { pollMs: options.pollMs }),
|
|
530
|
+
}
|
|
531
|
+
)) {
|
|
532
|
+
// Membership is judged for EVERY delivered message, not only at the periodic re-authorization: a
|
|
533
|
+
// participant removed a moment ago must not be handed the next entry in the interval.
|
|
534
|
+
if (!(await conversations.isParticipant(id, principal))) {
|
|
535
|
+
sink.send(frame("error", { error: "unauthorized" }));
|
|
536
|
+
break;
|
|
537
|
+
}
|
|
538
|
+
if (item.type === "message") {
|
|
539
|
+
// The per-viewer filter: a restricted entry reaches this viewer as a bare placeholder.
|
|
540
|
+
const [entry] = await conversations.filterEntries([item.entry], principal);
|
|
541
|
+
if (entry !== undefined) sink.send(frame("message", entry, item.entry.cursor));
|
|
542
|
+
} else {
|
|
543
|
+
sink.send(frame("closed", {}));
|
|
544
|
+
break;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
} catch (err) {
|
|
548
|
+
if (!ended) {
|
|
549
|
+
const e = mapError(err, true);
|
|
550
|
+
sink.send(frame("error", e.body));
|
|
551
|
+
}
|
|
552
|
+
} finally {
|
|
553
|
+
end();
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const identityBody = (body: unknown) => {
|
|
558
|
+
const identity = parseIdentity(body);
|
|
559
|
+
if (identity === undefined) throw new BadRequestError("`actor` must be a non-empty string");
|
|
560
|
+
return identity;
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
async function route(
|
|
564
|
+
req: http.IncomingMessage,
|
|
565
|
+
res: http.ServerResponse,
|
|
566
|
+
corsRef: { cors: Record<string, string> }
|
|
567
|
+
): Promise<void> {
|
|
568
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
569
|
+
const method = req.method ?? "GET";
|
|
570
|
+
if (url.pathname !== base && !url.pathname.startsWith(`${base}/`)) throw NOT_FOUND;
|
|
571
|
+
checkHost(req);
|
|
572
|
+
const corsOrigin = checkOrigin(req);
|
|
573
|
+
corsRef.cors = corsHeaders(corsOrigin);
|
|
574
|
+
const cors = corsRef.cors;
|
|
575
|
+
if (method === "OPTIONS") {
|
|
576
|
+
// A preflight carries no credentials: answer it for allowed origins only.
|
|
577
|
+
if (corsOrigin === undefined) throw NOT_FOUND;
|
|
578
|
+
res.writeHead(204, {
|
|
579
|
+
...cors,
|
|
580
|
+
"access-control-allow-methods": "GET, POST, OPTIONS",
|
|
581
|
+
"access-control-allow-headers": "authorization, content-type, last-event-id",
|
|
582
|
+
"access-control-max-age": "600",
|
|
583
|
+
});
|
|
584
|
+
res.end();
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
const principal = await identify(req);
|
|
588
|
+
if (principal === undefined && strict) throw new HttpError(401, { error: "unauthorized" });
|
|
589
|
+
const call = principal !== undefined ? { principal } : {};
|
|
590
|
+
if (method === "POST") takeRate(principalKey(principal));
|
|
591
|
+
const rest = url.pathname
|
|
592
|
+
.slice(base.length)
|
|
593
|
+
.split("/")
|
|
594
|
+
.filter((s) => s !== "");
|
|
595
|
+
const decode = (s: string): string => {
|
|
596
|
+
try {
|
|
597
|
+
return decodeURIComponent(s);
|
|
598
|
+
} catch {
|
|
599
|
+
throw NOT_FOUND;
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
|
|
603
|
+
if (rest.length === 0) {
|
|
604
|
+
if (method !== "POST") {
|
|
605
|
+
throw new HttpError(405, { error: "method not allowed" }, { allow: "POST" });
|
|
606
|
+
}
|
|
607
|
+
await readJson(req, maxBody); // no fields are honoured: the server mints the id
|
|
608
|
+
try {
|
|
609
|
+
const { conversationId } = await conversations.start(call);
|
|
610
|
+
sendJson(res, 201, { conversationId }, cors);
|
|
611
|
+
} catch (err) {
|
|
612
|
+
throw mapError(err, false);
|
|
613
|
+
}
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
const id = decode(rest[0] as string);
|
|
618
|
+
if (!isValidConversationId(id)) throw NOT_FOUND;
|
|
619
|
+
const action = rest[1];
|
|
620
|
+
try {
|
|
621
|
+
if (rest.length === 1 && method === "GET") {
|
|
622
|
+
sendJson(res, 200, await conversations.status(id, call), cors);
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
if (rest.length === 2 && action === "turns" && method === "POST") {
|
|
626
|
+
const body = (await readJson(req, maxBody)) as {
|
|
627
|
+
text?: unknown;
|
|
628
|
+
messageId?: unknown;
|
|
629
|
+
editOf?: unknown;
|
|
630
|
+
} | null;
|
|
631
|
+
if (typeof body?.text !== "string") throw new BadRequestError("`text` must be a string");
|
|
632
|
+
if (
|
|
633
|
+
body.messageId !== undefined &&
|
|
634
|
+
(typeof body.messageId !== "string" ||
|
|
635
|
+
body.messageId.length === 0 ||
|
|
636
|
+
body.messageId.length > 200)
|
|
637
|
+
) {
|
|
638
|
+
throw new BadRequestError(
|
|
639
|
+
"`messageId` must be a non-empty string of at most 200 characters"
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
if (
|
|
643
|
+
body.editOf !== undefined &&
|
|
644
|
+
(typeof body.editOf !== "number" || !Number.isSafeInteger(body.editOf) || body.editOf < 1)
|
|
645
|
+
) {
|
|
646
|
+
throw new BadRequestError(
|
|
647
|
+
"`editOf` must be a positive integer (the ord of an earlier turn)"
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
const sent = await conversations.sendTurn(id, body.text, {
|
|
651
|
+
...call,
|
|
652
|
+
...(typeof body.editOf === "number" && { editOf: body.editOf }),
|
|
653
|
+
...(typeof body.messageId === "string" && { messageId: body.messageId }),
|
|
654
|
+
});
|
|
655
|
+
sendJson(res, 202, { messageId: sent.messageId, inboxSeq: sent.inboxSeq }, cors);
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
if (rest.length === 2 && action === "close" && method === "POST") {
|
|
659
|
+
await readJson(req, maxBody);
|
|
660
|
+
const sent = await conversations.close(id, call);
|
|
661
|
+
sendJson(res, 202, { messageId: sent.messageId }, cors);
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
if (action === "participants") {
|
|
665
|
+
if (rest.length === 2 && method === "GET") {
|
|
666
|
+
sendJson(res, 200, { participants: await conversations.participants(id, call) }, cors);
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
if (rest.length === 2 && method === "POST") {
|
|
670
|
+
await conversations.addParticipant(id, identityBody(await readJson(req, maxBody)), call);
|
|
671
|
+
sendJson(res, 202, { ok: true }, cors);
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
if (rest.length === 3 && rest[2] === "remove" && method === "POST") {
|
|
675
|
+
await conversations.removeParticipant(
|
|
676
|
+
id,
|
|
677
|
+
identityBody(await readJson(req, maxBody)),
|
|
678
|
+
call
|
|
679
|
+
);
|
|
680
|
+
sendJson(res, 202, { ok: true }, cors);
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
if (rest.length === 2 && action === "history" && method === "GET") {
|
|
685
|
+
const limit = url.searchParams.get("limit");
|
|
686
|
+
const cursor = url.searchParams.get("cursor");
|
|
687
|
+
const direction = url.searchParams.get("direction");
|
|
688
|
+
if (direction !== null && direction !== "forward" && direction !== "backward") {
|
|
689
|
+
throw new BadRequestError("`direction` must be forward or backward");
|
|
690
|
+
}
|
|
691
|
+
const n = limit === null ? undefined : Number(limit);
|
|
692
|
+
if (n !== undefined && (!Number.isInteger(n) || n < 1)) {
|
|
693
|
+
throw new BadRequestError("`limit` must be a positive integer");
|
|
694
|
+
}
|
|
695
|
+
// A read stops when its client does: a hung-up request must not keep walking the log.
|
|
696
|
+
const gone = new AbortController();
|
|
697
|
+
res.once("close", () => gone.abort());
|
|
698
|
+
const page = await conversations.history(id, {
|
|
699
|
+
...call,
|
|
700
|
+
signal: gone.signal,
|
|
701
|
+
...(n !== undefined && { limit: n }),
|
|
702
|
+
...(cursor !== null && { cursor }),
|
|
703
|
+
...(direction !== null && { direction }),
|
|
704
|
+
});
|
|
705
|
+
sendJson(res, 200, page, cors);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
if (rest.length === 2 && action === "reasoning" && method === "GET") {
|
|
709
|
+
// Disabled unless the host gave a store: indistinguishable from a route that does not exist.
|
|
710
|
+
if (reasoningStore === undefined) throw NOT_FOUND;
|
|
711
|
+
const cursor = url.searchParams.get("cursor");
|
|
712
|
+
if (cursor === null)
|
|
713
|
+
throw new BadRequestError("`cursor` (the reply's history cursor) is required");
|
|
714
|
+
// The audience decision is the conversation's: the asker or the owner in shared mode, the owner otherwise.
|
|
715
|
+
const target = await conversations.reasoningTarget(id, cursor, call);
|
|
716
|
+
const { steps, truncated } = await readReasoningBounded(
|
|
717
|
+
options.eventStore,
|
|
718
|
+
reasoningStore,
|
|
719
|
+
{
|
|
720
|
+
executionId: target.executionId,
|
|
721
|
+
...(target.stepPrefix !== undefined && { stepPrefix: target.stepPrefix }),
|
|
722
|
+
},
|
|
723
|
+
{ maxParts: REASONING_RESPONSE_MAX_PARTS, maxBytes: REASONING_RESPONSE_MAX_BYTES }
|
|
724
|
+
);
|
|
725
|
+
sendJson(
|
|
726
|
+
res,
|
|
727
|
+
200,
|
|
728
|
+
{
|
|
729
|
+
steps: steps.map((s) => ({
|
|
730
|
+
stepId: s.stepId,
|
|
731
|
+
...(s.recordedAttempt !== undefined && { recordedAttempt: s.recordedAttempt }),
|
|
732
|
+
attempts: s.attempts.map((a) => ({
|
|
733
|
+
attempt: a.attempt,
|
|
734
|
+
provider: a.provider,
|
|
735
|
+
...(a.model !== undefined && { model: a.model }),
|
|
736
|
+
recorded: a.recorded,
|
|
737
|
+
parts: a.parts.map((p) => ({
|
|
738
|
+
kind: p.kind,
|
|
739
|
+
status: p.status,
|
|
740
|
+
// The transport edge: the one place the untrusted wrapper comes off.
|
|
741
|
+
...(p.text !== undefined && { text: unwrapTainted(p.text) }),
|
|
742
|
+
})),
|
|
743
|
+
})),
|
|
744
|
+
})),
|
|
745
|
+
...(truncated && { truncated: true }),
|
|
746
|
+
},
|
|
747
|
+
cors
|
|
748
|
+
);
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
if (rest.length === 2 && action === "events" && method === "GET") {
|
|
752
|
+
await events(req, res, id, principal, url, cors);
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
} catch (err) {
|
|
756
|
+
throw mapError(err, true);
|
|
757
|
+
}
|
|
758
|
+
throw NOT_FOUND;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
const server = http.createServer((req, res) => {
|
|
762
|
+
const corsRef: { cors: Record<string, string> } = { cors: {} };
|
|
763
|
+
void route(req, res, corsRef).catch((err: unknown) => {
|
|
764
|
+
const e = mapError(err, true);
|
|
765
|
+
if (res.headersSent) {
|
|
766
|
+
res.end();
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
if (e.status === 413) res.once("finish", () => req.destroy());
|
|
770
|
+
sendJson(res, e.status, e.body, { ...corsRef.cors, ...e.headers });
|
|
771
|
+
});
|
|
772
|
+
});
|
|
773
|
+
server.requestTimeout = options.requestTimeoutMs ?? 30_000;
|
|
774
|
+
server.headersTimeout = options.headersTimeoutMs ?? 15_000;
|
|
775
|
+
server.maxConnections = options.maxSockets ?? 4096;
|
|
776
|
+
|
|
777
|
+
return {
|
|
778
|
+
get url() {
|
|
779
|
+
return resolvedUrl;
|
|
780
|
+
},
|
|
781
|
+
get connections() {
|
|
782
|
+
return open.size;
|
|
783
|
+
},
|
|
784
|
+
http: server,
|
|
785
|
+
start(): Promise<void> {
|
|
786
|
+
return new Promise((resolve, reject) => {
|
|
787
|
+
server.once("error", reject);
|
|
788
|
+
server.listen(options.port ?? 0, host, () => {
|
|
789
|
+
const addr = server.address() as AddressInfo | null;
|
|
790
|
+
if (addr !== null && typeof addr === "object") {
|
|
791
|
+
resolvedUrl = `http://${host.includes(":") ? `[${host}]` : host}:${addr.port}`;
|
|
792
|
+
}
|
|
793
|
+
resolve();
|
|
794
|
+
});
|
|
795
|
+
});
|
|
796
|
+
},
|
|
797
|
+
stop(): Promise<void> {
|
|
798
|
+
if (!server.listening) return Promise.resolve();
|
|
799
|
+
for (const c of [...open]) c.close();
|
|
800
|
+
server.closeAllConnections();
|
|
801
|
+
return new Promise((resolve, reject) => {
|
|
802
|
+
server.close((err?: Error) => (err !== undefined ? reject(err) : resolve()));
|
|
803
|
+
});
|
|
804
|
+
},
|
|
805
|
+
};
|
|
806
|
+
}
|