@loomwork/plugin-conversation-sse 0.0.0-stage → 0.1.0

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