@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.
- package/README.md +7 -0
- package/dist/domain.d.ts +10 -0
- package/dist/domain.d.ts.map +1 -0
- package/dist/errors.d.ts +20 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/events.d.ts +59 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/hash.d.ts +47 -0
- package/dist/hash.d.ts.map +1 -0
- package/dist/http/client.d.ts +21 -0
- package/dist/http/client.d.ts.map +1 -0
- package/dist/http/client.js +367 -0
- package/dist/http/config.d.ts +5 -0
- package/dist/http/config.d.ts.map +1 -0
- package/dist/http/index.d.ts +6 -0
- package/dist/http/index.d.ts.map +1 -0
- package/dist/http/index.js +1084 -0
- package/dist/http/routes.d.ts +15 -0
- package/dist/http/routes.d.ts.map +1 -0
- package/dist/http/routes.js +645 -0
- package/dist/http/server.d.ts +19 -0
- package/dist/http/server.d.ts.map +1 -0
- package/dist/http/server.js +973 -0
- package/dist/http/service.d.ts +34 -0
- package/dist/http/service.d.ts.map +1 -0
- package/dist/http/service.js +501 -0
- package/dist/ids.d.ts +8 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +453 -0
- package/dist/lineage.d.ts +5 -0
- package/dist/lineage.d.ts.map +1 -0
- package/dist/persistence/core/index.d.ts +2 -0
- package/dist/persistence/core/index.d.ts.map +1 -0
- package/dist/persistence/core/persistence/base-persistence.d.ts +12 -0
- package/dist/persistence/core/persistence/base-persistence.d.ts.map +1 -0
- package/dist/persistence/core/persistence/helpers.d.ts +30 -0
- package/dist/persistence/core/persistence/helpers.d.ts.map +1 -0
- package/dist/persistence/core/persistence/index.d.ts +6 -0
- package/dist/persistence/core/persistence/index.d.ts.map +1 -0
- package/dist/persistence/core/persistence/index.js +1276 -0
- package/dist/persistence/core/persistence/memory-persistence.d.ts +55 -0
- package/dist/persistence/core/persistence/memory-persistence.d.ts.map +1 -0
- package/dist/persistence/core/persistence/signed-persistence.d.ts +18 -0
- package/dist/persistence/core/persistence/signed-persistence.d.ts.map +1 -0
- package/dist/persistence/core/persistence/types.d.ts +210 -0
- package/dist/persistence/core/persistence/types.d.ts.map +1 -0
- package/dist/persistence/sqlite/index.d.ts +3 -0
- package/dist/persistence/sqlite/index.d.ts.map +1 -0
- package/dist/persistence/sqlite/index.js +1544 -0
- package/dist/persistence/sqlite/persistence/persistence.d.ts +49 -0
- package/dist/persistence/sqlite/persistence/persistence.d.ts.map +1 -0
- package/dist/persistence/sqlite/persistence/schema.d.ts +4 -0
- package/dist/persistence/sqlite/persistence/schema.d.ts.map +1 -0
- package/dist/persistence/sqlite/persistence/streaming.d.ts +27 -0
- package/dist/persistence/sqlite/persistence/streaming.d.ts.map +1 -0
- package/dist/persistence/testing/index.d.ts +2 -0
- package/dist/persistence/testing/index.d.ts.map +1 -0
- package/dist/persistence/testing/index.js +689 -0
- package/dist/persistence/testing/persistence/contract.d.ts +3 -0
- package/dist/persistence/testing/persistence/contract.d.ts.map +1 -0
- package/dist/persistence/turso-serverless/index.d.ts +10 -0
- package/dist/persistence/turso-serverless/index.d.ts.map +1 -0
- package/dist/persistence/turso-serverless/index.js +1812 -0
- package/dist/persistence/turso-serverless/persistence/local-sqlite.d.ts +5 -0
- package/dist/persistence/turso-serverless/persistence/local-sqlite.d.ts.map +1 -0
- package/dist/persistence/turso-serverless/persistence/persistence.d.ts +49 -0
- package/dist/persistence/turso-serverless/persistence/persistence.d.ts.map +1 -0
- package/dist/persistence/turso-serverless/persistence/schema.d.ts +4 -0
- package/dist/persistence/turso-serverless/persistence/schema.d.ts.map +1 -0
- package/dist/persistence/turso-serverless/persistence/sql.d.ts +20 -0
- package/dist/persistence/turso-serverless/persistence/sql.d.ts.map +1 -0
- package/dist/persistence/turso-serverless/persistence/sql.js +53 -0
- package/dist/persistence/turso-serverless/persistence/streaming.d.ts +27 -0
- package/dist/persistence/turso-serverless/persistence/streaming.d.ts.map +1 -0
- package/dist/service.d.ts +49 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/stream.d.ts +32 -0
- package/dist/stream.d.ts.map +1 -0
- package/dist/types.d.ts +201 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/validation.d.ts +4 -0
- package/dist/validation.d.ts.map +1 -0
- package/package.json +104 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { ChatEvent, ChatPersistence } from "../domain.js";
|
|
2
|
+
import { ChatNotFoundError } from "../domain.js";
|
|
3
|
+
import { type ChatService } from "../service.js";
|
|
4
|
+
export type ChatHttpRuntime = {
|
|
5
|
+
service: ChatService;
|
|
6
|
+
subscribeToThread(threadId: string, send: (event: ChatEvent) => void): () => void;
|
|
7
|
+
close(): void;
|
|
8
|
+
};
|
|
9
|
+
export type CreateChatHttpRuntimeOptions = {
|
|
10
|
+
persistence: ChatPersistence;
|
|
11
|
+
onEvent?: (event: ChatEvent) => void;
|
|
12
|
+
};
|
|
13
|
+
export type ChatStorageConfig = {
|
|
14
|
+
kind: "local-sqlite";
|
|
15
|
+
dbPath: string;
|
|
16
|
+
} | {
|
|
17
|
+
kind: "turso";
|
|
18
|
+
url: string;
|
|
19
|
+
authToken: string;
|
|
20
|
+
} | {
|
|
21
|
+
kind: "custom";
|
|
22
|
+
persistence: ChatPersistence;
|
|
23
|
+
close?: () => void;
|
|
24
|
+
};
|
|
25
|
+
export type ChatStorage = {
|
|
26
|
+
persistence: ChatPersistence;
|
|
27
|
+
close(): void;
|
|
28
|
+
};
|
|
29
|
+
/** Build a ChatService + in-process thread event fanout from host-provided persistence. */
|
|
30
|
+
export declare function createChatHttpRuntime(options: CreateChatHttpRuntimeOptions): ChatHttpRuntime;
|
|
31
|
+
/** Open host-selected storage and return persistence + cleanup. */
|
|
32
|
+
export declare function createChatStorage(config: ChatStorageConfig): Promise<ChatStorage>;
|
|
33
|
+
export declare function isChatNotFound(error: unknown): error is ChatNotFoundError;
|
|
34
|
+
//# sourceMappingURL=service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/http/service.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,KAAK,WAAW,EAAqB,MAAM,eAAe,CAAC;AAEpE,MAAM,MAAM,eAAe,GAAG;IAC5B,OAAO,EAAE,WAAW,CAAC;IACrB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IAClF,KAAK,IAAI,IAAI,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG;IACzC,WAAW,EAAE,eAAe,CAAC;IAC7B,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC;CACtC,CAAC;AAEF,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACxC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACjD;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,WAAW,EAAE,eAAe,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,IAAI,CAAA;CAAE,CAAC;AAEzE,MAAM,MAAM,WAAW,GAAG;IACxB,WAAW,EAAE,eAAe,CAAC;IAC7B,KAAK,IAAI,IAAI,CAAC;CACf,CAAC;AAEF,2FAA2F;AAC3F,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,eAAe,CA0B5F;AAED,mEAAmE;AACnE,wBAAsB,iBAAiB,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,WAAW,CAAC,CA+BvF;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,iBAAiB,CAEzE"}
|
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// src/http/service.ts
|
|
5
|
+
import {
|
|
6
|
+
closeLocalSqliteDatabase,
|
|
7
|
+
createLocalSqliteDatabase,
|
|
8
|
+
createTursoChatPersistence,
|
|
9
|
+
createTursoDatabase,
|
|
10
|
+
ensureChatSchema
|
|
11
|
+
} from "@khoralabs/chat/turso-serverless";
|
|
12
|
+
|
|
13
|
+
// src/errors.ts
|
|
14
|
+
class ChatError extends Error {
|
|
15
|
+
code;
|
|
16
|
+
constructor(code, message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "ChatError";
|
|
19
|
+
this.code = code;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
class ChatNotFoundError extends ChatError {
|
|
24
|
+
resource;
|
|
25
|
+
resourceId;
|
|
26
|
+
constructor(resource, resourceId) {
|
|
27
|
+
super("not_found", `${resource} not found: ${resourceId}`);
|
|
28
|
+
this.name = "ChatNotFoundError";
|
|
29
|
+
this.resource = resource;
|
|
30
|
+
this.resourceId = resourceId;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
class ChatConflictError extends ChatError {
|
|
35
|
+
reason;
|
|
36
|
+
constructor(reason, message) {
|
|
37
|
+
super("conflict", message);
|
|
38
|
+
this.name = "ChatConflictError";
|
|
39
|
+
this.reason = reason;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
class ChatValidationError extends ChatError {
|
|
44
|
+
constructor(message) {
|
|
45
|
+
super("validation", message);
|
|
46
|
+
this.name = "ChatValidationError";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
class ChatPermissionError extends ChatError {
|
|
51
|
+
constructor(message) {
|
|
52
|
+
super("permission_denied", message);
|
|
53
|
+
this.name = "ChatPermissionError";
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
// src/hash.ts
|
|
57
|
+
function sha256Hex(input) {
|
|
58
|
+
const hasher = new Bun.CryptoHasher("sha256");
|
|
59
|
+
hasher.update(input);
|
|
60
|
+
return hasher.digest("hex");
|
|
61
|
+
}
|
|
62
|
+
function stableStringify(value) {
|
|
63
|
+
if (value === undefined) {
|
|
64
|
+
return "null";
|
|
65
|
+
}
|
|
66
|
+
if (value === null || typeof value !== "object") {
|
|
67
|
+
return JSON.stringify(value);
|
|
68
|
+
}
|
|
69
|
+
if (Array.isArray(value)) {
|
|
70
|
+
return `[${value.map((item) => stableStringify(item)).join(",")}]`;
|
|
71
|
+
}
|
|
72
|
+
const record = value;
|
|
73
|
+
const keys = Object.keys(record).sort();
|
|
74
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
|
|
75
|
+
}
|
|
76
|
+
function canonicalPostVersionPayload(input) {
|
|
77
|
+
return stableStringify({
|
|
78
|
+
postId: input.postId,
|
|
79
|
+
versionId: input.versionId,
|
|
80
|
+
threadId: input.threadId,
|
|
81
|
+
author: input.author,
|
|
82
|
+
role: input.role,
|
|
83
|
+
parts: input.parts,
|
|
84
|
+
metadata: input.metadata ?? null,
|
|
85
|
+
mentions: input.mentions ?? null,
|
|
86
|
+
model: input.model ?? null,
|
|
87
|
+
usage: input.usage ?? null,
|
|
88
|
+
parentVersionId: input.parentVersionId ?? null,
|
|
89
|
+
previousPostVersionId: input.previousPostVersionId ?? null
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function computeContentHash(payload) {
|
|
93
|
+
return sha256Hex(canonicalPostVersionPayload(payload));
|
|
94
|
+
}
|
|
95
|
+
function computeLineageHash(input) {
|
|
96
|
+
return sha256Hex(stableStringify({
|
|
97
|
+
previousLineageHash: input.previousLineageHash,
|
|
98
|
+
contentHash: input.contentHash,
|
|
99
|
+
postId: input.postId,
|
|
100
|
+
versionId: input.versionId
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
function canonicalAclEventPayload(input) {
|
|
104
|
+
return stableStringify({
|
|
105
|
+
type: input.type,
|
|
106
|
+
targetType: input.targetType,
|
|
107
|
+
targetId: input.targetId,
|
|
108
|
+
scope: input.scope ?? null,
|
|
109
|
+
role: input.role ?? null,
|
|
110
|
+
actor: input.actor,
|
|
111
|
+
previousAclEventId: input.previousAclEventId ?? null
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
function computeAclEventContentHash(payload) {
|
|
115
|
+
return sha256Hex(canonicalAclEventPayload(payload));
|
|
116
|
+
}
|
|
117
|
+
function signedPayloadBytes(payload) {
|
|
118
|
+
return new TextEncoder().encode(payload);
|
|
119
|
+
}
|
|
120
|
+
function canonicalSignedPostVersionPayload(input) {
|
|
121
|
+
return stableStringify({
|
|
122
|
+
contentHash: input.contentHash,
|
|
123
|
+
lineageHash: input.lineageHash,
|
|
124
|
+
payload: JSON.parse(canonicalPostVersionPayload(input))
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
function canonicalSignedAclEventPayload(input) {
|
|
128
|
+
return stableStringify({
|
|
129
|
+
contentHash: input.contentHash,
|
|
130
|
+
payload: JSON.parse(canonicalAclEventPayload(input.payload))
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
async function maybeSignPayload(payload, signer, sign) {
|
|
134
|
+
return sign(signedPayloadBytes(payload), signer);
|
|
135
|
+
}
|
|
136
|
+
// src/ids.ts
|
|
137
|
+
function createId() {
|
|
138
|
+
return crypto.randomUUID();
|
|
139
|
+
}
|
|
140
|
+
function scopeKey(scope) {
|
|
141
|
+
return `${scope.type}:${scope.id}`;
|
|
142
|
+
}
|
|
143
|
+
function scopeRefFromKey(key) {
|
|
144
|
+
const separatorIndex = key.indexOf(":");
|
|
145
|
+
if (separatorIndex === -1) {
|
|
146
|
+
throw new Error(`Invalid scope key: ${key}`);
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
type: key.slice(0, separatorIndex),
|
|
150
|
+
id: key.slice(separatorIndex + 1)
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
// src/lineage.ts
|
|
154
|
+
function walkLineageFromHead(headVersionId, versionsById) {
|
|
155
|
+
const lineage = [];
|
|
156
|
+
let currentId = headVersionId;
|
|
157
|
+
const seenPostIds = new Set;
|
|
158
|
+
while (currentId) {
|
|
159
|
+
const version = versionsById.get(currentId);
|
|
160
|
+
if (!version)
|
|
161
|
+
break;
|
|
162
|
+
if (!seenPostIds.has(version.postId)) {
|
|
163
|
+
lineage.push(version);
|
|
164
|
+
seenPostIds.add(version.postId);
|
|
165
|
+
}
|
|
166
|
+
currentId = version.previousPostVersionId;
|
|
167
|
+
}
|
|
168
|
+
return lineage.reverse();
|
|
169
|
+
}
|
|
170
|
+
function lineageBetween(headVersionId, ancestorVersionId, versionsById) {
|
|
171
|
+
const lineage = walkLineageFromHead(headVersionId, versionsById);
|
|
172
|
+
const startIndex = lineage.findIndex((version) => version.id === ancestorVersionId);
|
|
173
|
+
if (startIndex === -1)
|
|
174
|
+
return null;
|
|
175
|
+
return lineage.slice(startIndex);
|
|
176
|
+
}
|
|
177
|
+
function postFromVersion(version, index, deletedAtMs) {
|
|
178
|
+
return {
|
|
179
|
+
...version,
|
|
180
|
+
id: version.postId,
|
|
181
|
+
status: "complete",
|
|
182
|
+
versionId: version.id,
|
|
183
|
+
previousVersionId: version.parentVersionId ?? null,
|
|
184
|
+
index,
|
|
185
|
+
updatedAtMs: version.parentVersionId ? version.createdAtMs : null,
|
|
186
|
+
deletedAtMs: deletedAtMs ?? null
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
// src/stream.ts
|
|
190
|
+
function rebuildStreamCacheFromEvents(events) {
|
|
191
|
+
const sorted = [...events].sort((a, b) => a.revision - b.revision);
|
|
192
|
+
let message = null;
|
|
193
|
+
let mentions;
|
|
194
|
+
let model;
|
|
195
|
+
let usage;
|
|
196
|
+
let revision = 0;
|
|
197
|
+
for (const event of sorted) {
|
|
198
|
+
if (event.eventType === "stream.started") {
|
|
199
|
+
if (!event.message) {
|
|
200
|
+
throw new Error(`stream.started event ${event.id} missing message`);
|
|
201
|
+
}
|
|
202
|
+
message = event.message;
|
|
203
|
+
mentions = event.mentions;
|
|
204
|
+
model = event.model;
|
|
205
|
+
usage = event.usage;
|
|
206
|
+
revision = event.revision;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (event.eventType === "stream.delta") {
|
|
210
|
+
if (!event.message) {
|
|
211
|
+
throw new Error(`stream.delta event ${event.id} missing message`);
|
|
212
|
+
}
|
|
213
|
+
message = event.message;
|
|
214
|
+
if (event.mentions !== undefined)
|
|
215
|
+
mentions = event.mentions;
|
|
216
|
+
if (event.model !== undefined)
|
|
217
|
+
model = event.model;
|
|
218
|
+
if (event.usage !== undefined)
|
|
219
|
+
usage = event.usage;
|
|
220
|
+
revision = event.revision;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
if (event.eventType === "stream.completed" || event.eventType === "stream.aborted") {
|
|
224
|
+
revision = event.revision;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (!message) {
|
|
228
|
+
throw new Error("stream events did not produce a message");
|
|
229
|
+
}
|
|
230
|
+
return { message, mentions, model, usage, revision };
|
|
231
|
+
}
|
|
232
|
+
function streamingPostFromCache(input) {
|
|
233
|
+
return {
|
|
234
|
+
...input.message,
|
|
235
|
+
id: input.postId,
|
|
236
|
+
status: "streaming",
|
|
237
|
+
threadId: input.threadId,
|
|
238
|
+
author: input.author,
|
|
239
|
+
mentions: input.mentions,
|
|
240
|
+
model: input.model,
|
|
241
|
+
usage: input.usage,
|
|
242
|
+
index: input.index,
|
|
243
|
+
streamRevision: input.streamRevision,
|
|
244
|
+
createdAtMs: input.createdAtMs,
|
|
245
|
+
updatedAtMs: input.updatedAtMs ?? null,
|
|
246
|
+
deletedAtMs: input.deletedAtMs ?? null
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
function mergeThreadPostsForList(lineagePosts, activePosts) {
|
|
250
|
+
const byIndex = new Map;
|
|
251
|
+
for (const item of lineagePosts) {
|
|
252
|
+
byIndex.set(item.index, item.post);
|
|
253
|
+
}
|
|
254
|
+
for (const post of activePosts) {
|
|
255
|
+
if (post.status === "streaming" || post.status === "aborted") {
|
|
256
|
+
byIndex.set(post.index, post);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return [...byIndex.entries()].sort(([a], [b]) => a - b).map(([, post]) => post);
|
|
260
|
+
}
|
|
261
|
+
// src/validation.ts
|
|
262
|
+
function assertThreadRoot(root) {
|
|
263
|
+
if (root.type === "channel") {
|
|
264
|
+
if (!root.channelId.trim()) {
|
|
265
|
+
throw new ChatValidationError("channel root requires channelId");
|
|
266
|
+
}
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (!root.postId.trim()) {
|
|
270
|
+
throw new ChatValidationError("post root requires postId");
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
function assertNonEmptyString(value, label) {
|
|
274
|
+
if (!value.trim()) {
|
|
275
|
+
throw new ChatValidationError(`${label} is required`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
// src/service.ts
|
|
279
|
+
function createChatService(persistence, options = {}) {
|
|
280
|
+
const emit = (event) => {
|
|
281
|
+
options.onEvent?.(event);
|
|
282
|
+
};
|
|
283
|
+
async function requireChannel(id) {
|
|
284
|
+
const channel = await persistence.getChannel(id);
|
|
285
|
+
if (!channel)
|
|
286
|
+
throw new ChatNotFoundError("channel", id);
|
|
287
|
+
return channel;
|
|
288
|
+
}
|
|
289
|
+
async function requireThread(id) {
|
|
290
|
+
const thread = await persistence.getThread(id);
|
|
291
|
+
if (!thread)
|
|
292
|
+
throw new ChatNotFoundError("thread", id);
|
|
293
|
+
return thread;
|
|
294
|
+
}
|
|
295
|
+
async function requirePost(id) {
|
|
296
|
+
const post = await persistence.getPost(id);
|
|
297
|
+
if (!post)
|
|
298
|
+
throw new ChatNotFoundError("post", id);
|
|
299
|
+
return post;
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
async createChannel(input) {
|
|
303
|
+
const channel = await persistence.createChannel({
|
|
304
|
+
...input,
|
|
305
|
+
id: input.id ?? options.generateId?.() ?? createId()
|
|
306
|
+
});
|
|
307
|
+
emit({ type: "channel.created", channel });
|
|
308
|
+
return channel;
|
|
309
|
+
},
|
|
310
|
+
async createThread(input) {
|
|
311
|
+
const thread = await persistence.createThread({
|
|
312
|
+
...input,
|
|
313
|
+
id: input.id ?? options.generateId?.() ?? createId()
|
|
314
|
+
});
|
|
315
|
+
emit({ type: "thread.created", thread });
|
|
316
|
+
return thread;
|
|
317
|
+
},
|
|
318
|
+
getChannel: requireChannel,
|
|
319
|
+
getThread: requireThread,
|
|
320
|
+
getPost: requirePost,
|
|
321
|
+
listThreads: (input) => persistence.listThreads(input),
|
|
322
|
+
listPosts: (input) => persistence.listPosts(input),
|
|
323
|
+
getThreadTip: (threadId) => persistence.getThreadTip(threadId),
|
|
324
|
+
async appendPost(input) {
|
|
325
|
+
const result = await persistence.appendPost(input);
|
|
326
|
+
if (!result.ok) {
|
|
327
|
+
throw new ChatConflictError("head_conflict", `head conflict: expected ${input.expectedHeadPostVersionId ?? "null"}, current ${result.currentHead.headPostVersionId}`);
|
|
328
|
+
}
|
|
329
|
+
emit({
|
|
330
|
+
type: "post.appended",
|
|
331
|
+
threadId: input.threadId,
|
|
332
|
+
post: result.post
|
|
333
|
+
});
|
|
334
|
+
return { post: result.post, head: result.head };
|
|
335
|
+
},
|
|
336
|
+
async editPost(input) {
|
|
337
|
+
const result = await persistence.editPost(input);
|
|
338
|
+
if (!result.ok) {
|
|
339
|
+
throw new ChatConflictError("head_conflict", `head conflict during edit: current ${result.currentHead.headPostVersionId}`);
|
|
340
|
+
}
|
|
341
|
+
emit({
|
|
342
|
+
type: "post.updated",
|
|
343
|
+
threadId: result.post.threadId,
|
|
344
|
+
post: result.post
|
|
345
|
+
});
|
|
346
|
+
return { post: result.post, head: result.head };
|
|
347
|
+
},
|
|
348
|
+
async deletePost(input) {
|
|
349
|
+
const post = await persistence.deletePost(input);
|
|
350
|
+
emit({
|
|
351
|
+
type: "post.deleted",
|
|
352
|
+
threadId: post.threadId,
|
|
353
|
+
postId: post.id,
|
|
354
|
+
deletedAtMs: post.deletedAtMs ?? Date.now()
|
|
355
|
+
});
|
|
356
|
+
return post;
|
|
357
|
+
},
|
|
358
|
+
addChannelMember: (input) => persistence.addChannelMember(input),
|
|
359
|
+
removeChannelMember: (input) => persistence.removeChannelMember(input),
|
|
360
|
+
async addThreadParticipant(input) {
|
|
361
|
+
const event = await persistence.addThreadParticipant(input);
|
|
362
|
+
emit({
|
|
363
|
+
type: "participant.added",
|
|
364
|
+
threadId: input.threadId,
|
|
365
|
+
scope: input.scope,
|
|
366
|
+
role: input.role
|
|
367
|
+
});
|
|
368
|
+
return event;
|
|
369
|
+
},
|
|
370
|
+
removeThreadParticipant: (input) => persistence.removeThreadParticipant(input),
|
|
371
|
+
createThreadHead: (input) => persistence.createThreadHead(input),
|
|
372
|
+
listChannelMembers: (channelId) => persistence.listChannelMembers(channelId),
|
|
373
|
+
listThreadParticipants: (threadId) => persistence.listThreadParticipants(threadId),
|
|
374
|
+
async startStreamedPost(input) {
|
|
375
|
+
const result = await persistence.startStreamedPost(input);
|
|
376
|
+
emit({
|
|
377
|
+
type: "post.stream.started",
|
|
378
|
+
threadId: input.threadId,
|
|
379
|
+
post: result.post,
|
|
380
|
+
revision: result.revision
|
|
381
|
+
});
|
|
382
|
+
return result;
|
|
383
|
+
},
|
|
384
|
+
async applyPostDelta(input) {
|
|
385
|
+
const record = await persistence.getPost(input.postId);
|
|
386
|
+
if (!record)
|
|
387
|
+
throw new ChatNotFoundError("post", input.postId);
|
|
388
|
+
const result = await persistence.applyPostDelta(input);
|
|
389
|
+
emit({
|
|
390
|
+
type: "post.stream.delta",
|
|
391
|
+
threadId: record.threadId,
|
|
392
|
+
post: result.post,
|
|
393
|
+
revision: result.revision
|
|
394
|
+
});
|
|
395
|
+
return result;
|
|
396
|
+
},
|
|
397
|
+
async completeStreamedPost(input) {
|
|
398
|
+
const record = await persistence.getPost(input.postId);
|
|
399
|
+
if (!record)
|
|
400
|
+
throw new ChatNotFoundError("post", input.postId);
|
|
401
|
+
const streamRevision = record.status === "streaming" ? record.streamRevision : input.expectedRevision;
|
|
402
|
+
const result = await persistence.completeStreamedPost(input);
|
|
403
|
+
if (!result.ok) {
|
|
404
|
+
throw new ChatConflictError("head_conflict", `head conflict during stream completion: current ${result.currentHead.headPostVersionId}`);
|
|
405
|
+
}
|
|
406
|
+
emit({
|
|
407
|
+
type: "post.stream.completed",
|
|
408
|
+
threadId: record.threadId,
|
|
409
|
+
post: result.post,
|
|
410
|
+
head: result.head,
|
|
411
|
+
revision: typeof streamRevision === "number" ? streamRevision + 1 : 0
|
|
412
|
+
});
|
|
413
|
+
return { post: result.post, head: result.head };
|
|
414
|
+
},
|
|
415
|
+
async abortStreamedPost(input) {
|
|
416
|
+
const record = await persistence.getPost(input.postId);
|
|
417
|
+
if (!record)
|
|
418
|
+
throw new ChatNotFoundError("post", input.postId);
|
|
419
|
+
const result = await persistence.abortStreamedPost(input);
|
|
420
|
+
emit({
|
|
421
|
+
type: "post.stream.aborted",
|
|
422
|
+
threadId: record.threadId,
|
|
423
|
+
postId: input.postId,
|
|
424
|
+
revision: result.post.streamRevision,
|
|
425
|
+
deletedAtMs: result.post.deletedAtMs ?? Date.now()
|
|
426
|
+
});
|
|
427
|
+
return result.post;
|
|
428
|
+
},
|
|
429
|
+
setPostVersionSignature(versionId, signature) {
|
|
430
|
+
return persistence.setPostVersionSignature(versionId, signature);
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// src/http/service.ts
|
|
436
|
+
function createChatHttpRuntime(options) {
|
|
437
|
+
const subscribers = new Map;
|
|
438
|
+
const service = createChatService(options.persistence, {
|
|
439
|
+
onEvent(event) {
|
|
440
|
+
options.onEvent?.(event);
|
|
441
|
+
if (!("threadId" in event))
|
|
442
|
+
return;
|
|
443
|
+
for (const send of subscribers.get(event.threadId) ?? [])
|
|
444
|
+
send(event);
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
return {
|
|
448
|
+
service,
|
|
449
|
+
subscribeToThread(threadId, send) {
|
|
450
|
+
const set = subscribers.get(threadId) ?? new Set;
|
|
451
|
+
set.add(send);
|
|
452
|
+
subscribers.set(threadId, set);
|
|
453
|
+
return () => {
|
|
454
|
+
set.delete(send);
|
|
455
|
+
if (set.size === 0)
|
|
456
|
+
subscribers.delete(threadId);
|
|
457
|
+
};
|
|
458
|
+
},
|
|
459
|
+
close() {
|
|
460
|
+
subscribers.clear();
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
async function createChatStorage(config) {
|
|
465
|
+
if (config.kind === "custom") {
|
|
466
|
+
return {
|
|
467
|
+
persistence: config.persistence,
|
|
468
|
+
close() {
|
|
469
|
+
config.close?.();
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
if (config.kind === "turso") {
|
|
474
|
+
const db2 = createTursoDatabase({
|
|
475
|
+
url: config.url,
|
|
476
|
+
authToken: config.authToken
|
|
477
|
+
});
|
|
478
|
+
await ensureChatSchema(db2);
|
|
479
|
+
return {
|
|
480
|
+
persistence: createTursoChatPersistence(db2),
|
|
481
|
+
close() {
|
|
482
|
+
closeLocalSqliteDatabase(db2);
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
const db = createLocalSqliteDatabase(config.dbPath);
|
|
487
|
+
return {
|
|
488
|
+
persistence: createTursoChatPersistence(db),
|
|
489
|
+
close() {
|
|
490
|
+
closeLocalSqliteDatabase(db);
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
function isChatNotFound(error) {
|
|
495
|
+
return error instanceof ChatNotFoundError;
|
|
496
|
+
}
|
|
497
|
+
export {
|
|
498
|
+
isChatNotFound,
|
|
499
|
+
createChatStorage,
|
|
500
|
+
createChatHttpRuntime
|
|
501
|
+
};
|
package/dist/ids.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ScopeRef } from "./types.js";
|
|
2
|
+
export declare function createId(): string;
|
|
3
|
+
export declare function scopeKey(scope: {
|
|
4
|
+
type: string;
|
|
5
|
+
id: string;
|
|
6
|
+
}): string;
|
|
7
|
+
export declare function scopeRefFromKey(key: string): ScopeRef;
|
|
8
|
+
//# sourceMappingURL=ids.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ids.d.ts","sourceRoot":"","sources":["../src/ids.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,wBAAgB,QAAQ,IAAI,MAAM,CAEjC;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAEpE;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,QAAQ,CASrD"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC"}
|