@khoralabs/chat 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.
Files changed (85) hide show
  1. package/README.md +7 -0
  2. package/dist/domain.d.ts +10 -0
  3. package/dist/domain.d.ts.map +1 -0
  4. package/dist/errors.d.ts +20 -0
  5. package/dist/errors.d.ts.map +1 -0
  6. package/dist/events.d.ts +59 -0
  7. package/dist/events.d.ts.map +1 -0
  8. package/dist/hash.d.ts +47 -0
  9. package/dist/hash.d.ts.map +1 -0
  10. package/dist/http/client.d.ts +21 -0
  11. package/dist/http/client.d.ts.map +1 -0
  12. package/dist/http/client.js +367 -0
  13. package/dist/http/config.d.ts +5 -0
  14. package/dist/http/config.d.ts.map +1 -0
  15. package/dist/http/index.d.ts +6 -0
  16. package/dist/http/index.d.ts.map +1 -0
  17. package/dist/http/index.js +1084 -0
  18. package/dist/http/routes.d.ts +15 -0
  19. package/dist/http/routes.d.ts.map +1 -0
  20. package/dist/http/routes.js +645 -0
  21. package/dist/http/server.d.ts +19 -0
  22. package/dist/http/server.d.ts.map +1 -0
  23. package/dist/http/server.js +973 -0
  24. package/dist/http/service.d.ts +34 -0
  25. package/dist/http/service.d.ts.map +1 -0
  26. package/dist/http/service.js +501 -0
  27. package/dist/ids.d.ts +8 -0
  28. package/dist/ids.d.ts.map +1 -0
  29. package/dist/index.d.ts +3 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +453 -0
  32. package/dist/lineage.d.ts +5 -0
  33. package/dist/lineage.d.ts.map +1 -0
  34. package/dist/persistence/core/index.d.ts +2 -0
  35. package/dist/persistence/core/index.d.ts.map +1 -0
  36. package/dist/persistence/core/persistence/base-persistence.d.ts +12 -0
  37. package/dist/persistence/core/persistence/base-persistence.d.ts.map +1 -0
  38. package/dist/persistence/core/persistence/helpers.d.ts +30 -0
  39. package/dist/persistence/core/persistence/helpers.d.ts.map +1 -0
  40. package/dist/persistence/core/persistence/index.d.ts +6 -0
  41. package/dist/persistence/core/persistence/index.d.ts.map +1 -0
  42. package/dist/persistence/core/persistence/index.js +1276 -0
  43. package/dist/persistence/core/persistence/memory-persistence.d.ts +55 -0
  44. package/dist/persistence/core/persistence/memory-persistence.d.ts.map +1 -0
  45. package/dist/persistence/core/persistence/signed-persistence.d.ts +18 -0
  46. package/dist/persistence/core/persistence/signed-persistence.d.ts.map +1 -0
  47. package/dist/persistence/core/persistence/types.d.ts +210 -0
  48. package/dist/persistence/core/persistence/types.d.ts.map +1 -0
  49. package/dist/persistence/sqlite/index.d.ts +3 -0
  50. package/dist/persistence/sqlite/index.d.ts.map +1 -0
  51. package/dist/persistence/sqlite/index.js +1544 -0
  52. package/dist/persistence/sqlite/persistence/persistence.d.ts +49 -0
  53. package/dist/persistence/sqlite/persistence/persistence.d.ts.map +1 -0
  54. package/dist/persistence/sqlite/persistence/schema.d.ts +4 -0
  55. package/dist/persistence/sqlite/persistence/schema.d.ts.map +1 -0
  56. package/dist/persistence/sqlite/persistence/streaming.d.ts +27 -0
  57. package/dist/persistence/sqlite/persistence/streaming.d.ts.map +1 -0
  58. package/dist/persistence/testing/index.d.ts +2 -0
  59. package/dist/persistence/testing/index.d.ts.map +1 -0
  60. package/dist/persistence/testing/index.js +689 -0
  61. package/dist/persistence/testing/persistence/contract.d.ts +3 -0
  62. package/dist/persistence/testing/persistence/contract.d.ts.map +1 -0
  63. package/dist/persistence/turso-serverless/index.d.ts +10 -0
  64. package/dist/persistence/turso-serverless/index.d.ts.map +1 -0
  65. package/dist/persistence/turso-serverless/index.js +1812 -0
  66. package/dist/persistence/turso-serverless/persistence/local-sqlite.d.ts +5 -0
  67. package/dist/persistence/turso-serverless/persistence/local-sqlite.d.ts.map +1 -0
  68. package/dist/persistence/turso-serverless/persistence/persistence.d.ts +49 -0
  69. package/dist/persistence/turso-serverless/persistence/persistence.d.ts.map +1 -0
  70. package/dist/persistence/turso-serverless/persistence/schema.d.ts +4 -0
  71. package/dist/persistence/turso-serverless/persistence/schema.d.ts.map +1 -0
  72. package/dist/persistence/turso-serverless/persistence/sql.d.ts +20 -0
  73. package/dist/persistence/turso-serverless/persistence/sql.d.ts.map +1 -0
  74. package/dist/persistence/turso-serverless/persistence/sql.js +53 -0
  75. package/dist/persistence/turso-serverless/persistence/streaming.d.ts +27 -0
  76. package/dist/persistence/turso-serverless/persistence/streaming.d.ts.map +1 -0
  77. package/dist/service.d.ts +49 -0
  78. package/dist/service.d.ts.map +1 -0
  79. package/dist/stream.d.ts +32 -0
  80. package/dist/stream.d.ts.map +1 -0
  81. package/dist/types.d.ts +201 -0
  82. package/dist/types.d.ts.map +1 -0
  83. package/dist/validation.d.ts +4 -0
  84. package/dist/validation.d.ts.map +1 -0
  85. package/package.json +104 -0
@@ -0,0 +1,973 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
4
+ // src/errors.ts
5
+ class ChatError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.name = "ChatError";
10
+ this.code = code;
11
+ }
12
+ }
13
+
14
+ class ChatNotFoundError extends ChatError {
15
+ resource;
16
+ resourceId;
17
+ constructor(resource, resourceId) {
18
+ super("not_found", `${resource} not found: ${resourceId}`);
19
+ this.name = "ChatNotFoundError";
20
+ this.resource = resource;
21
+ this.resourceId = resourceId;
22
+ }
23
+ }
24
+
25
+ class ChatConflictError extends ChatError {
26
+ reason;
27
+ constructor(reason, message) {
28
+ super("conflict", message);
29
+ this.name = "ChatConflictError";
30
+ this.reason = reason;
31
+ }
32
+ }
33
+
34
+ class ChatValidationError extends ChatError {
35
+ constructor(message) {
36
+ super("validation", message);
37
+ this.name = "ChatValidationError";
38
+ }
39
+ }
40
+
41
+ class ChatPermissionError extends ChatError {
42
+ constructor(message) {
43
+ super("permission_denied", message);
44
+ this.name = "ChatPermissionError";
45
+ }
46
+ }
47
+ // src/hash.ts
48
+ function sha256Hex(input) {
49
+ const hasher = new Bun.CryptoHasher("sha256");
50
+ hasher.update(input);
51
+ return hasher.digest("hex");
52
+ }
53
+ function stableStringify(value) {
54
+ if (value === undefined) {
55
+ return "null";
56
+ }
57
+ if (value === null || typeof value !== "object") {
58
+ return JSON.stringify(value);
59
+ }
60
+ if (Array.isArray(value)) {
61
+ return `[${value.map((item) => stableStringify(item)).join(",")}]`;
62
+ }
63
+ const record = value;
64
+ const keys = Object.keys(record).sort();
65
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
66
+ }
67
+ function canonicalPostVersionPayload(input) {
68
+ return stableStringify({
69
+ postId: input.postId,
70
+ versionId: input.versionId,
71
+ threadId: input.threadId,
72
+ author: input.author,
73
+ role: input.role,
74
+ parts: input.parts,
75
+ metadata: input.metadata ?? null,
76
+ mentions: input.mentions ?? null,
77
+ model: input.model ?? null,
78
+ usage: input.usage ?? null,
79
+ parentVersionId: input.parentVersionId ?? null,
80
+ previousPostVersionId: input.previousPostVersionId ?? null
81
+ });
82
+ }
83
+ function computeContentHash(payload) {
84
+ return sha256Hex(canonicalPostVersionPayload(payload));
85
+ }
86
+ function computeLineageHash(input) {
87
+ return sha256Hex(stableStringify({
88
+ previousLineageHash: input.previousLineageHash,
89
+ contentHash: input.contentHash,
90
+ postId: input.postId,
91
+ versionId: input.versionId
92
+ }));
93
+ }
94
+ function canonicalAclEventPayload(input) {
95
+ return stableStringify({
96
+ type: input.type,
97
+ targetType: input.targetType,
98
+ targetId: input.targetId,
99
+ scope: input.scope ?? null,
100
+ role: input.role ?? null,
101
+ actor: input.actor,
102
+ previousAclEventId: input.previousAclEventId ?? null
103
+ });
104
+ }
105
+ function computeAclEventContentHash(payload) {
106
+ return sha256Hex(canonicalAclEventPayload(payload));
107
+ }
108
+ function signedPayloadBytes(payload) {
109
+ return new TextEncoder().encode(payload);
110
+ }
111
+ function canonicalSignedPostVersionPayload(input) {
112
+ return stableStringify({
113
+ contentHash: input.contentHash,
114
+ lineageHash: input.lineageHash,
115
+ payload: JSON.parse(canonicalPostVersionPayload(input))
116
+ });
117
+ }
118
+ function canonicalSignedAclEventPayload(input) {
119
+ return stableStringify({
120
+ contentHash: input.contentHash,
121
+ payload: JSON.parse(canonicalAclEventPayload(input.payload))
122
+ });
123
+ }
124
+ async function maybeSignPayload(payload, signer, sign) {
125
+ return sign(signedPayloadBytes(payload), signer);
126
+ }
127
+ // src/ids.ts
128
+ function createId() {
129
+ return crypto.randomUUID();
130
+ }
131
+ function scopeKey(scope) {
132
+ return `${scope.type}:${scope.id}`;
133
+ }
134
+ function scopeRefFromKey(key) {
135
+ const separatorIndex = key.indexOf(":");
136
+ if (separatorIndex === -1) {
137
+ throw new Error(`Invalid scope key: ${key}`);
138
+ }
139
+ return {
140
+ type: key.slice(0, separatorIndex),
141
+ id: key.slice(separatorIndex + 1)
142
+ };
143
+ }
144
+ // src/lineage.ts
145
+ function walkLineageFromHead(headVersionId, versionsById) {
146
+ const lineage = [];
147
+ let currentId = headVersionId;
148
+ const seenPostIds = new Set;
149
+ while (currentId) {
150
+ const version = versionsById.get(currentId);
151
+ if (!version)
152
+ break;
153
+ if (!seenPostIds.has(version.postId)) {
154
+ lineage.push(version);
155
+ seenPostIds.add(version.postId);
156
+ }
157
+ currentId = version.previousPostVersionId;
158
+ }
159
+ return lineage.reverse();
160
+ }
161
+ function lineageBetween(headVersionId, ancestorVersionId, versionsById) {
162
+ const lineage = walkLineageFromHead(headVersionId, versionsById);
163
+ const startIndex = lineage.findIndex((version) => version.id === ancestorVersionId);
164
+ if (startIndex === -1)
165
+ return null;
166
+ return lineage.slice(startIndex);
167
+ }
168
+ function postFromVersion(version, index, deletedAtMs) {
169
+ return {
170
+ ...version,
171
+ id: version.postId,
172
+ status: "complete",
173
+ versionId: version.id,
174
+ previousVersionId: version.parentVersionId ?? null,
175
+ index,
176
+ updatedAtMs: version.parentVersionId ? version.createdAtMs : null,
177
+ deletedAtMs: deletedAtMs ?? null
178
+ };
179
+ }
180
+ // src/stream.ts
181
+ function rebuildStreamCacheFromEvents(events) {
182
+ const sorted = [...events].sort((a, b) => a.revision - b.revision);
183
+ let message = null;
184
+ let mentions;
185
+ let model;
186
+ let usage;
187
+ let revision = 0;
188
+ for (const event of sorted) {
189
+ if (event.eventType === "stream.started") {
190
+ if (!event.message) {
191
+ throw new Error(`stream.started event ${event.id} missing message`);
192
+ }
193
+ message = event.message;
194
+ mentions = event.mentions;
195
+ model = event.model;
196
+ usage = event.usage;
197
+ revision = event.revision;
198
+ continue;
199
+ }
200
+ if (event.eventType === "stream.delta") {
201
+ if (!event.message) {
202
+ throw new Error(`stream.delta event ${event.id} missing message`);
203
+ }
204
+ message = event.message;
205
+ if (event.mentions !== undefined)
206
+ mentions = event.mentions;
207
+ if (event.model !== undefined)
208
+ model = event.model;
209
+ if (event.usage !== undefined)
210
+ usage = event.usage;
211
+ revision = event.revision;
212
+ continue;
213
+ }
214
+ if (event.eventType === "stream.completed" || event.eventType === "stream.aborted") {
215
+ revision = event.revision;
216
+ }
217
+ }
218
+ if (!message) {
219
+ throw new Error("stream events did not produce a message");
220
+ }
221
+ return { message, mentions, model, usage, revision };
222
+ }
223
+ function streamingPostFromCache(input) {
224
+ return {
225
+ ...input.message,
226
+ id: input.postId,
227
+ status: "streaming",
228
+ threadId: input.threadId,
229
+ author: input.author,
230
+ mentions: input.mentions,
231
+ model: input.model,
232
+ usage: input.usage,
233
+ index: input.index,
234
+ streamRevision: input.streamRevision,
235
+ createdAtMs: input.createdAtMs,
236
+ updatedAtMs: input.updatedAtMs ?? null,
237
+ deletedAtMs: input.deletedAtMs ?? null
238
+ };
239
+ }
240
+ function mergeThreadPostsForList(lineagePosts, activePosts) {
241
+ const byIndex = new Map;
242
+ for (const item of lineagePosts) {
243
+ byIndex.set(item.index, item.post);
244
+ }
245
+ for (const post of activePosts) {
246
+ if (post.status === "streaming" || post.status === "aborted") {
247
+ byIndex.set(post.index, post);
248
+ }
249
+ }
250
+ return [...byIndex.entries()].sort(([a], [b]) => a - b).map(([, post]) => post);
251
+ }
252
+ // src/validation.ts
253
+ function assertThreadRoot(root) {
254
+ if (root.type === "channel") {
255
+ if (!root.channelId.trim()) {
256
+ throw new ChatValidationError("channel root requires channelId");
257
+ }
258
+ return;
259
+ }
260
+ if (!root.postId.trim()) {
261
+ throw new ChatValidationError("post root requires postId");
262
+ }
263
+ }
264
+ function assertNonEmptyString(value, label) {
265
+ if (!value.trim()) {
266
+ throw new ChatValidationError(`${label} is required`);
267
+ }
268
+ }
269
+ // src/http/routes.ts
270
+ function json(value, init) {
271
+ return Response.json(value, init);
272
+ }
273
+ function extractBearerToken(req) {
274
+ const auth = req.headers.get("authorization")?.trim() ?? "";
275
+ const match = /^Bearer\s+(.+)$/i.exec(auth);
276
+ const headerToken = match?.[1]?.trim() ?? "";
277
+ if (headerToken.length > 0)
278
+ return headerToken;
279
+ const url = new URL(req.url);
280
+ return url.searchParams.get("token")?.trim() ?? "";
281
+ }
282
+ function requireInternalToken(req, expected) {
283
+ const token = extractBearerToken(req);
284
+ if (token.length === 0 || token !== expected) {
285
+ return json({ error: "Unauthorized" }, { status: 401 });
286
+ }
287
+ return null;
288
+ }
289
+ function createTokenAuthorizer(token) {
290
+ return (req) => requireInternalToken(req, token);
291
+ }
292
+ async function readJson(req) {
293
+ try {
294
+ return await req.json();
295
+ } catch {
296
+ return null;
297
+ }
298
+ }
299
+ function stringField(body, key) {
300
+ const value = body[key];
301
+ return typeof value === "string" && value.length > 0 ? value : null;
302
+ }
303
+ function errorResponse(error) {
304
+ if (error instanceof ChatNotFoundError) {
305
+ return json({ error: error.message }, { status: 404 });
306
+ }
307
+ const message = error instanceof Error ? error.message : String(error);
308
+ return json({ error: message }, { status: 500 });
309
+ }
310
+ function resolveAuthorize(options) {
311
+ if (options.authorize !== undefined)
312
+ return options.authorize;
313
+ if (options.token !== undefined && options.token.length > 0) {
314
+ return createTokenAuthorizer(options.token);
315
+ }
316
+ throw new Error("createChatRoutes requires token or authorize");
317
+ }
318
+ function createChatRoutes(chat, tokenOrOptions) {
319
+ const options = typeof tokenOrOptions === "string" ? { token: tokenOrOptions } : tokenOrOptions;
320
+ const authorized = resolveAuthorize(options);
321
+ return {
322
+ "GET /health": async () => json({ ok: true }),
323
+ "POST /channels/get": async (req) => {
324
+ const error = await authorized(req);
325
+ if (error !== null)
326
+ return error;
327
+ const body = await readJson(req);
328
+ const channelId = body === null ? null : stringField(body, "channelId");
329
+ if (channelId === null)
330
+ return json({ error: "channelId is required" }, { status: 400 });
331
+ try {
332
+ return json(await chat.getChannel(channelId));
333
+ } catch (err) {
334
+ return errorResponse(err);
335
+ }
336
+ },
337
+ "POST /channels/create": async (req) => {
338
+ const error = await authorized(req);
339
+ if (error !== null)
340
+ return error;
341
+ const body = await readJson(req);
342
+ const id = body === null ? null : stringField(body, "id");
343
+ if (id === null)
344
+ return json({ error: "id is required" }, { status: 400 });
345
+ try {
346
+ return json(await chat.createChannel({
347
+ id,
348
+ metadata: body?.metadata
349
+ }));
350
+ } catch (err) {
351
+ return errorResponse(err);
352
+ }
353
+ },
354
+ "POST /threads/get": async (req) => {
355
+ const error = await authorized(req);
356
+ if (error !== null)
357
+ return error;
358
+ const body = await readJson(req);
359
+ const threadId = body === null ? null : stringField(body, "threadId");
360
+ if (threadId === null)
361
+ return json({ error: "threadId is required" }, { status: 400 });
362
+ try {
363
+ return json(await chat.getThread(threadId));
364
+ } catch (err) {
365
+ return errorResponse(err);
366
+ }
367
+ },
368
+ "POST /threads/create": async (req) => {
369
+ const error = await authorized(req);
370
+ if (error !== null)
371
+ return error;
372
+ const body = await readJson(req);
373
+ if (body?.id === undefined || body.root === undefined) {
374
+ return json({ error: "id and root are required" }, { status: 400 });
375
+ }
376
+ try {
377
+ return json(await chat.createThread({
378
+ id: body.id,
379
+ root: body.root,
380
+ metadata: body.metadata
381
+ }));
382
+ } catch (err) {
383
+ return errorResponse(err);
384
+ }
385
+ },
386
+ "POST /threads/list": async (req) => {
387
+ const error = await authorized(req);
388
+ if (error !== null)
389
+ return error;
390
+ const body = await readJson(req);
391
+ if (body?.channelId === undefined) {
392
+ return json({ error: "channelId is required" }, { status: 400 });
393
+ }
394
+ try {
395
+ return json(await chat.listThreads({
396
+ channelId: body.channelId,
397
+ participant: body.participant,
398
+ limit: body.limit,
399
+ cursor: body.cursor
400
+ }));
401
+ } catch (err) {
402
+ return errorResponse(err);
403
+ }
404
+ },
405
+ "POST /threads/list-posts": async (req) => {
406
+ const error = await authorized(req);
407
+ if (error !== null)
408
+ return error;
409
+ const body = await readJson(req);
410
+ if (body?.threadId === undefined) {
411
+ return json({ error: "threadId is required" }, { status: 400 });
412
+ }
413
+ try {
414
+ return json(await chat.listPosts({ threadId: body.threadId, limit: body.limit, cursor: body.cursor }));
415
+ } catch (err) {
416
+ return errorResponse(err);
417
+ }
418
+ },
419
+ "POST /threads/tip": async (req) => {
420
+ const error = await authorized(req);
421
+ if (error !== null)
422
+ return error;
423
+ const body = await readJson(req);
424
+ const threadId = body === null ? null : stringField(body, "threadId");
425
+ if (threadId === null)
426
+ return json({ error: "threadId is required" }, { status: 400 });
427
+ try {
428
+ return json({ tip: await chat.getThreadTip(threadId) });
429
+ } catch (err) {
430
+ return errorResponse(err);
431
+ }
432
+ },
433
+ "POST /threads/list-participants": async (req) => {
434
+ const error = await authorized(req);
435
+ if (error !== null)
436
+ return error;
437
+ const body = await readJson(req);
438
+ const threadId = body === null ? null : stringField(body, "threadId");
439
+ if (threadId === null)
440
+ return json({ error: "threadId is required" }, { status: 400 });
441
+ try {
442
+ return json({ participants: await chat.listThreadParticipants(threadId) });
443
+ } catch (err) {
444
+ return errorResponse(err);
445
+ }
446
+ },
447
+ "POST /threads/add-participant": async (req) => {
448
+ const error = await authorized(req);
449
+ if (error !== null)
450
+ return error;
451
+ const body = await readJson(req);
452
+ if (body?.threadId === undefined || body.scope === undefined || body.actor === undefined) {
453
+ return json({ error: "threadId, scope, and actor are required" }, { status: 400 });
454
+ }
455
+ try {
456
+ return json(await chat.addThreadParticipant({
457
+ threadId: body.threadId,
458
+ scope: body.scope,
459
+ role: body.role ?? "participant",
460
+ actor: body.actor
461
+ }));
462
+ } catch (err) {
463
+ return errorResponse(err);
464
+ }
465
+ },
466
+ "POST /threads/append-post": async (req) => {
467
+ const error = await authorized(req);
468
+ if (error !== null)
469
+ return error;
470
+ const body = await readJson(req);
471
+ if (body?.threadId === undefined || body.author === undefined || body.message === undefined) {
472
+ return json({ error: "threadId, author, and message are required" }, { status: 400 });
473
+ }
474
+ try {
475
+ return json(await chat.appendPost({
476
+ threadId: body.threadId,
477
+ author: body.author,
478
+ message: body.message,
479
+ expectedHeadPostVersionId: body.expectedHeadPostVersionId,
480
+ versionId: body.versionId,
481
+ createdAtMs: body.createdAtMs,
482
+ signature: body.signature
483
+ }));
484
+ } catch (err) {
485
+ return errorResponse(err);
486
+ }
487
+ },
488
+ "POST /posts/set-signature": async (req) => {
489
+ const error = await authorized(req);
490
+ if (error !== null)
491
+ return error;
492
+ const body = await readJson(req);
493
+ if (body?.versionId === undefined || body.signature === undefined) {
494
+ return json({ error: "versionId and signature are required" }, { status: 400 });
495
+ }
496
+ try {
497
+ await chat.setPostVersionSignature(body.versionId, body.signature);
498
+ return json({ ok: true });
499
+ } catch (err) {
500
+ return errorResponse(err);
501
+ }
502
+ },
503
+ "POST /internal/chat/streamed-posts": async (req) => {
504
+ const error = await authorized(req);
505
+ if (error !== null)
506
+ return error;
507
+ const body = await readJson(req);
508
+ if (body?.author === undefined || body.message === undefined || body.threadId === undefined) {
509
+ return json({ error: "threadId, author, and message are required" }, { status: 400 });
510
+ }
511
+ try {
512
+ return json(await chat.startStreamedPost({
513
+ threadId: body.threadId,
514
+ author: body.author,
515
+ idempotencyKey: body.idempotencyKey,
516
+ message: body.message
517
+ }));
518
+ } catch (err) {
519
+ return errorResponse(err);
520
+ }
521
+ },
522
+ "POST /internal/chat/posts/:postId/deltas": async (req) => {
523
+ const error = await authorized(req);
524
+ if (error !== null)
525
+ return error;
526
+ const url = new URL(req.url);
527
+ const postId = url.pathname.split("/").at(-2);
528
+ if (postId === undefined)
529
+ return json({ error: "postId is required" }, { status: 400 });
530
+ const body = await readJson(req);
531
+ if (body?.message === undefined) {
532
+ return json({ error: "message is required" }, { status: 400 });
533
+ }
534
+ try {
535
+ return json(await chat.applyPostDelta({
536
+ postId,
537
+ expectedRevision: body.expectedRevision,
538
+ message: body.message,
539
+ model: body.model,
540
+ usage: body.usage
541
+ }));
542
+ } catch (err) {
543
+ return errorResponse(err);
544
+ }
545
+ },
546
+ "POST /internal/chat/posts/:postId/complete": async (req) => {
547
+ const error = await authorized(req);
548
+ if (error !== null)
549
+ return error;
550
+ const url = new URL(req.url);
551
+ const postId = url.pathname.split("/").at(-2);
552
+ if (postId === undefined)
553
+ return json({ error: "postId is required" }, { status: 400 });
554
+ const body = await readJson(req);
555
+ try {
556
+ return json(await chat.completeStreamedPost({
557
+ postId,
558
+ expectedRevision: body?.expectedRevision,
559
+ idempotencyKey: body?.idempotencyKey
560
+ }));
561
+ } catch (err) {
562
+ return errorResponse(err);
563
+ }
564
+ },
565
+ "POST /internal/chat/posts/:postId/abort": async (req) => {
566
+ const error = await authorized(req);
567
+ if (error !== null)
568
+ return error;
569
+ const url = new URL(req.url);
570
+ const postId = url.pathname.split("/").at(-2);
571
+ if (postId === undefined)
572
+ return json({ error: "postId is required" }, { status: 400 });
573
+ try {
574
+ const post = await chat.abortStreamedPost({ postId });
575
+ return json({ post });
576
+ } catch (err) {
577
+ return errorResponse(err);
578
+ }
579
+ }
580
+ };
581
+ }
582
+ function createChatRoutesWithParams(chat, tokenOrOptions) {
583
+ const options = typeof tokenOrOptions === "string" ? { token: tokenOrOptions } : tokenOrOptions;
584
+ const base = createChatRoutes(chat, options);
585
+ const authorized = resolveAuthorize(options);
586
+ return {
587
+ ...base,
588
+ "POST /internal/chat/threads/:threadId/streamed-posts": async (req) => {
589
+ const error = await authorized(req);
590
+ if (error !== null)
591
+ return error;
592
+ const url = new URL(req.url);
593
+ const parts = url.pathname.split("/");
594
+ const threadIdx = parts.indexOf("threads");
595
+ const threadId = threadIdx >= 0 ? decodeURIComponent(parts[threadIdx + 1] ?? "") : undefined;
596
+ const body = await readJson(req);
597
+ if (threadId === undefined || threadId.length === 0 || body?.author === undefined || body.message === undefined) {
598
+ return json({ error: "threadId, author, and message are required" }, { status: 400 });
599
+ }
600
+ try {
601
+ return json(await chat.startStreamedPost({
602
+ threadId,
603
+ author: body.author,
604
+ idempotencyKey: body.idempotencyKey,
605
+ message: body.message
606
+ }));
607
+ } catch (err) {
608
+ return errorResponse(err);
609
+ }
610
+ }
611
+ };
612
+ }
613
+ async function dispatchChatRoute(routes, req) {
614
+ const url = new URL(req.url);
615
+ const paramPaths = [
616
+ "POST /internal/chat/threads/:threadId/streamed-posts",
617
+ "POST /internal/chat/posts/:postId/deltas",
618
+ "POST /internal/chat/posts/:postId/complete",
619
+ "POST /internal/chat/posts/:postId/abort"
620
+ ];
621
+ for (const pattern of paramPaths) {
622
+ const [method, pathPattern] = pattern.split(" ");
623
+ if (req.method !== method || pathPattern === undefined)
624
+ continue;
625
+ const regex = new RegExp(`^${pathPattern.replace(/:[^/]+/g, "[^/]+")}$`);
626
+ if (regex.test(url.pathname)) {
627
+ const handler2 = routes[pattern];
628
+ if (handler2 !== undefined)
629
+ return handler2(req);
630
+ }
631
+ }
632
+ const key = `${req.method} ${url.pathname}`;
633
+ const handler = routes[key];
634
+ if (handler === undefined)
635
+ return json({ error: "Not found" }, { status: 404 });
636
+ return handler(req);
637
+ }
638
+
639
+ // src/http/service.ts
640
+ import {
641
+ closeLocalSqliteDatabase,
642
+ createLocalSqliteDatabase,
643
+ createTursoChatPersistence,
644
+ createTursoDatabase,
645
+ ensureChatSchema
646
+ } from "@khoralabs/chat/turso-serverless";
647
+
648
+ // src/service.ts
649
+ function createChatService(persistence, options = {}) {
650
+ const emit = (event) => {
651
+ options.onEvent?.(event);
652
+ };
653
+ async function requireChannel(id) {
654
+ const channel = await persistence.getChannel(id);
655
+ if (!channel)
656
+ throw new ChatNotFoundError("channel", id);
657
+ return channel;
658
+ }
659
+ async function requireThread(id) {
660
+ const thread = await persistence.getThread(id);
661
+ if (!thread)
662
+ throw new ChatNotFoundError("thread", id);
663
+ return thread;
664
+ }
665
+ async function requirePost(id) {
666
+ const post = await persistence.getPost(id);
667
+ if (!post)
668
+ throw new ChatNotFoundError("post", id);
669
+ return post;
670
+ }
671
+ return {
672
+ async createChannel(input) {
673
+ const channel = await persistence.createChannel({
674
+ ...input,
675
+ id: input.id ?? options.generateId?.() ?? createId()
676
+ });
677
+ emit({ type: "channel.created", channel });
678
+ return channel;
679
+ },
680
+ async createThread(input) {
681
+ const thread = await persistence.createThread({
682
+ ...input,
683
+ id: input.id ?? options.generateId?.() ?? createId()
684
+ });
685
+ emit({ type: "thread.created", thread });
686
+ return thread;
687
+ },
688
+ getChannel: requireChannel,
689
+ getThread: requireThread,
690
+ getPost: requirePost,
691
+ listThreads: (input) => persistence.listThreads(input),
692
+ listPosts: (input) => persistence.listPosts(input),
693
+ getThreadTip: (threadId) => persistence.getThreadTip(threadId),
694
+ async appendPost(input) {
695
+ const result = await persistence.appendPost(input);
696
+ if (!result.ok) {
697
+ throw new ChatConflictError("head_conflict", `head conflict: expected ${input.expectedHeadPostVersionId ?? "null"}, current ${result.currentHead.headPostVersionId}`);
698
+ }
699
+ emit({
700
+ type: "post.appended",
701
+ threadId: input.threadId,
702
+ post: result.post
703
+ });
704
+ return { post: result.post, head: result.head };
705
+ },
706
+ async editPost(input) {
707
+ const result = await persistence.editPost(input);
708
+ if (!result.ok) {
709
+ throw new ChatConflictError("head_conflict", `head conflict during edit: current ${result.currentHead.headPostVersionId}`);
710
+ }
711
+ emit({
712
+ type: "post.updated",
713
+ threadId: result.post.threadId,
714
+ post: result.post
715
+ });
716
+ return { post: result.post, head: result.head };
717
+ },
718
+ async deletePost(input) {
719
+ const post = await persistence.deletePost(input);
720
+ emit({
721
+ type: "post.deleted",
722
+ threadId: post.threadId,
723
+ postId: post.id,
724
+ deletedAtMs: post.deletedAtMs ?? Date.now()
725
+ });
726
+ return post;
727
+ },
728
+ addChannelMember: (input) => persistence.addChannelMember(input),
729
+ removeChannelMember: (input) => persistence.removeChannelMember(input),
730
+ async addThreadParticipant(input) {
731
+ const event = await persistence.addThreadParticipant(input);
732
+ emit({
733
+ type: "participant.added",
734
+ threadId: input.threadId,
735
+ scope: input.scope,
736
+ role: input.role
737
+ });
738
+ return event;
739
+ },
740
+ removeThreadParticipant: (input) => persistence.removeThreadParticipant(input),
741
+ createThreadHead: (input) => persistence.createThreadHead(input),
742
+ listChannelMembers: (channelId) => persistence.listChannelMembers(channelId),
743
+ listThreadParticipants: (threadId) => persistence.listThreadParticipants(threadId),
744
+ async startStreamedPost(input) {
745
+ const result = await persistence.startStreamedPost(input);
746
+ emit({
747
+ type: "post.stream.started",
748
+ threadId: input.threadId,
749
+ post: result.post,
750
+ revision: result.revision
751
+ });
752
+ return result;
753
+ },
754
+ async applyPostDelta(input) {
755
+ const record = await persistence.getPost(input.postId);
756
+ if (!record)
757
+ throw new ChatNotFoundError("post", input.postId);
758
+ const result = await persistence.applyPostDelta(input);
759
+ emit({
760
+ type: "post.stream.delta",
761
+ threadId: record.threadId,
762
+ post: result.post,
763
+ revision: result.revision
764
+ });
765
+ return result;
766
+ },
767
+ async completeStreamedPost(input) {
768
+ const record = await persistence.getPost(input.postId);
769
+ if (!record)
770
+ throw new ChatNotFoundError("post", input.postId);
771
+ const streamRevision = record.status === "streaming" ? record.streamRevision : input.expectedRevision;
772
+ const result = await persistence.completeStreamedPost(input);
773
+ if (!result.ok) {
774
+ throw new ChatConflictError("head_conflict", `head conflict during stream completion: current ${result.currentHead.headPostVersionId}`);
775
+ }
776
+ emit({
777
+ type: "post.stream.completed",
778
+ threadId: record.threadId,
779
+ post: result.post,
780
+ head: result.head,
781
+ revision: typeof streamRevision === "number" ? streamRevision + 1 : 0
782
+ });
783
+ return { post: result.post, head: result.head };
784
+ },
785
+ async abortStreamedPost(input) {
786
+ const record = await persistence.getPost(input.postId);
787
+ if (!record)
788
+ throw new ChatNotFoundError("post", input.postId);
789
+ const result = await persistence.abortStreamedPost(input);
790
+ emit({
791
+ type: "post.stream.aborted",
792
+ threadId: record.threadId,
793
+ postId: input.postId,
794
+ revision: result.post.streamRevision,
795
+ deletedAtMs: result.post.deletedAtMs ?? Date.now()
796
+ });
797
+ return result.post;
798
+ },
799
+ setPostVersionSignature(versionId, signature) {
800
+ return persistence.setPostVersionSignature(versionId, signature);
801
+ }
802
+ };
803
+ }
804
+
805
+ // src/http/service.ts
806
+ function createChatHttpRuntime(options) {
807
+ const subscribers = new Map;
808
+ const service = createChatService(options.persistence, {
809
+ onEvent(event) {
810
+ options.onEvent?.(event);
811
+ if (!("threadId" in event))
812
+ return;
813
+ for (const send of subscribers.get(event.threadId) ?? [])
814
+ send(event);
815
+ }
816
+ });
817
+ return {
818
+ service,
819
+ subscribeToThread(threadId, send) {
820
+ const set = subscribers.get(threadId) ?? new Set;
821
+ set.add(send);
822
+ subscribers.set(threadId, set);
823
+ return () => {
824
+ set.delete(send);
825
+ if (set.size === 0)
826
+ subscribers.delete(threadId);
827
+ };
828
+ },
829
+ close() {
830
+ subscribers.clear();
831
+ }
832
+ };
833
+ }
834
+ async function createChatStorage(config) {
835
+ if (config.kind === "custom") {
836
+ return {
837
+ persistence: config.persistence,
838
+ close() {
839
+ config.close?.();
840
+ }
841
+ };
842
+ }
843
+ if (config.kind === "turso") {
844
+ const db2 = createTursoDatabase({
845
+ url: config.url,
846
+ authToken: config.authToken
847
+ });
848
+ await ensureChatSchema(db2);
849
+ return {
850
+ persistence: createTursoChatPersistence(db2),
851
+ close() {
852
+ closeLocalSqliteDatabase(db2);
853
+ }
854
+ };
855
+ }
856
+ const db = createLocalSqliteDatabase(config.dbPath);
857
+ return {
858
+ persistence: createTursoChatPersistence(db),
859
+ close() {
860
+ closeLocalSqliteDatabase(db);
861
+ }
862
+ };
863
+ }
864
+ function isChatNotFound(error) {
865
+ return error instanceof ChatNotFoundError;
866
+ }
867
+
868
+ // src/http/server.ts
869
+ import { serve } from "bun";
870
+
871
+ // src/http/config.ts
872
+ import path from "node:path";
873
+ function resolveChatDataDir() {
874
+ const raw = process.env.CHAT_DATA_DIR?.trim();
875
+ if (raw !== undefined && raw.length > 0)
876
+ return raw;
877
+ return path.join(process.cwd(), "data");
878
+ }
879
+ function resolveChatDbPath() {
880
+ const raw = process.env.CHAT_DB_PATH?.trim();
881
+ if (raw !== undefined && raw.length > 0)
882
+ return raw;
883
+ return path.join(resolveChatDataDir(), "chat.db");
884
+ }
885
+ function chatInternalToken() {
886
+ const value = process.env.CHAT_INTERNAL_TOKEN?.trim();
887
+ if (value === undefined || value.length === 0) {
888
+ throw new Error("CHAT_INTERNAL_TOKEN must be set");
889
+ }
890
+ return value;
891
+ }
892
+ function chatHttpPort() {
893
+ return Number(process.env.PORT?.trim() || "3002");
894
+ }
895
+
896
+ // src/http/server.ts
897
+ async function startChatHttpServer(opts) {
898
+ const storage = await createChatStorage(opts.storage);
899
+ const runtime = createChatHttpRuntime({
900
+ persistence: storage.persistence,
901
+ onEvent: opts.onEvent
902
+ });
903
+ const routes = createChatRoutesWithParams(runtime.service, opts.token);
904
+ const token = opts.token;
905
+ const server = serve({
906
+ port: opts.port ?? 0,
907
+ fetch(req, bunServer) {
908
+ const url = new URL(req.url);
909
+ if (req.method === "GET" && url.pathname === "/health") {
910
+ return Response.json({ ok: true });
911
+ }
912
+ if (url.pathname.startsWith("/ws/threads/")) {
913
+ const authError = requireInternalToken(req, token);
914
+ if (authError !== null)
915
+ return authError;
916
+ const threadId = decodeURIComponent(url.pathname.slice("/ws/threads/".length));
917
+ if (threadId.length === 0) {
918
+ return Response.json({ error: "threadId is required" }, { status: 400 });
919
+ }
920
+ const upgraded = bunServer.upgrade(req, { data: { threadId } });
921
+ if (upgraded)
922
+ return;
923
+ return new Response("WebSocket upgrade failed", { status: 500 });
924
+ }
925
+ return dispatchChatRoute(routes, req);
926
+ },
927
+ websocket: {
928
+ open(ws) {
929
+ ws.data.unsubscribe = runtime.subscribeToThread(ws.data.threadId, (event) => {
930
+ ws.send(JSON.stringify(event));
931
+ });
932
+ },
933
+ message() {},
934
+ close(ws) {
935
+ ws.data.unsubscribe?.();
936
+ }
937
+ }
938
+ });
939
+ const port = server.port ?? opts.port ?? 0;
940
+ return {
941
+ port,
942
+ baseUrl: `http://127.0.0.1:${port}`,
943
+ token,
944
+ service: runtime.service,
945
+ stop() {
946
+ server.stop(true);
947
+ runtime.close();
948
+ storage.close();
949
+ }
950
+ };
951
+ }
952
+ function storageConfigFromEnv() {
953
+ const tursoUrl = process.env.TURSO_DATABASE_URL?.trim();
954
+ if (tursoUrl !== undefined && tursoUrl.length > 0) {
955
+ const authToken = process.env.TURSO_AUTH_TOKEN?.trim();
956
+ if (authToken === undefined || authToken.length === 0) {
957
+ throw new Error("TURSO_AUTH_TOKEN must be set when TURSO_DATABASE_URL is set");
958
+ }
959
+ return { kind: "turso", url: tursoUrl, authToken };
960
+ }
961
+ return { kind: "local-sqlite", dbPath: resolveChatDbPath() };
962
+ }
963
+ if (__require.main == __require.module) {
964
+ const handle = await startChatHttpServer({
965
+ storage: storageConfigFromEnv(),
966
+ token: chatInternalToken(),
967
+ port: chatHttpPort()
968
+ });
969
+ console.log(`chat-http listening on ${handle.port}`);
970
+ }
971
+ export {
972
+ startChatHttpServer
973
+ };