@mordn/chat-widget 0.8.1 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,204 @@
1
+ // src/server/stores/hosted/index.ts
2
+ import "server-only";
3
+
4
+ // src/server/stores/hosted/store.ts
5
+ import "server-only";
6
+
7
+ // src/server/chat-store.ts
8
+ var ConversationOwnershipError = class extends Error {
9
+ constructor(conversationId) {
10
+ super(`Conversation ${conversationId} is not owned by the current user`);
11
+ this.conversationId = conversationId;
12
+ this.name = "ConversationOwnershipError";
13
+ }
14
+ };
15
+
16
+ // src/server/stores/hosted/store.ts
17
+ var DEFAULT_BASE_URL = "https://api.mordn.dev";
18
+ function normaliseConversation(raw) {
19
+ return {
20
+ id: raw.id,
21
+ title: raw.title,
22
+ metadata: raw.metadata ?? null,
23
+ createdAt: new Date(raw.created_at ?? raw.createdAt),
24
+ updatedAt: new Date(raw.updated_at ?? raw.updatedAt),
25
+ messageCount: raw.message_count ?? raw.messageCount
26
+ };
27
+ }
28
+ function normaliseMessage(raw) {
29
+ return {
30
+ id: raw.id,
31
+ role: raw.role,
32
+ parts: raw.parts ?? [],
33
+ text: raw.content ?? raw.text ?? "",
34
+ model: raw.model ?? void 0,
35
+ createdAt: new Date(raw.created_at ?? raw.createdAt)
36
+ };
37
+ }
38
+ var HostedChatStore = class {
39
+ constructor(userId, apiKey, baseUrl, fetchImpl) {
40
+ this.userId = userId;
41
+ this.apiKey = apiKey;
42
+ this.base = baseUrl.replace(/\/$/, "");
43
+ this.doFetch = fetchImpl;
44
+ }
45
+ headers(json = false) {
46
+ const h = {
47
+ Authorization: `Bearer ${this.apiKey}`,
48
+ "X-Chat-User": this.userId
49
+ };
50
+ if (json) h["Content-Type"] = "application/json";
51
+ return h;
52
+ }
53
+ async req(path, init) {
54
+ return this.doFetch(`${this.base}/v1${path}`, init);
55
+ }
56
+ async listConversations() {
57
+ const res = await this.req("/conversations", { headers: this.headers() });
58
+ if (!res.ok) return [];
59
+ const data = await res.json();
60
+ return (data.conversations ?? []).map(normaliseConversation);
61
+ }
62
+ async getConversation(id) {
63
+ const res = await this.req(`/conversations/${encodeURIComponent(id)}`, { headers: this.headers() });
64
+ if (res.status === 404) return null;
65
+ if (!res.ok) return null;
66
+ const data = await res.json();
67
+ return data.conversation ? normaliseConversation(data.conversation) : null;
68
+ }
69
+ async ensureConversation(id) {
70
+ const res = await this.req(`/conversations/${encodeURIComponent(id)}/turns`, {
71
+ method: "POST",
72
+ headers: this.headers(true),
73
+ body: JSON.stringify({ messages: [] })
74
+ });
75
+ if (res.status === 403) throw new ConversationOwnershipError(id);
76
+ const conv = await this.getConversation(id);
77
+ if (conv) return conv;
78
+ const now = /* @__PURE__ */ new Date();
79
+ return { id, title: "New Chat", metadata: {}, createdAt: now, updatedAt: now };
80
+ }
81
+ async renameConversation(id, title) {
82
+ await this.req(`/conversations/${encodeURIComponent(id)}`, {
83
+ method: "PATCH",
84
+ headers: this.headers(true),
85
+ body: JSON.stringify({ title })
86
+ });
87
+ }
88
+ async deleteConversation(id) {
89
+ const res = await this.req(`/conversations/${encodeURIComponent(id)}`, {
90
+ method: "DELETE",
91
+ headers: this.headers()
92
+ });
93
+ return res.status === 204;
94
+ }
95
+ async listMessages(conversationId, _opts) {
96
+ const res = await this.req(`/conversations/${encodeURIComponent(conversationId)}`, { headers: this.headers() });
97
+ if (!res.ok) return [];
98
+ const data = await res.json();
99
+ return (data.messages ?? []).map(normaliseMessage);
100
+ }
101
+ async saveTurn(input) {
102
+ const res = await this.req(`/conversations/${encodeURIComponent(input.conversationId)}/turns`, {
103
+ method: "POST",
104
+ headers: this.headers(true),
105
+ body: JSON.stringify({ messages: input.messages, model: input.model })
106
+ });
107
+ if (res.status === 403) throw new ConversationOwnershipError(input.conversationId);
108
+ if (!res.ok) {
109
+ throw new Error(`[chat-widget] hosted saveTurn failed: ${res.status} ${await res.text().catch(() => "")}`);
110
+ }
111
+ }
112
+ };
113
+ var HostedStorageAdapter = class {
114
+ constructor(userId, apiKey, baseUrl, fetchImpl) {
115
+ this.userId = userId;
116
+ this.apiKey = apiKey;
117
+ this.base = baseUrl.replace(/\/$/, "");
118
+ this.doFetch = fetchImpl;
119
+ }
120
+ async upload(input) {
121
+ const form = new FormData();
122
+ const buf = input.data instanceof Uint8Array ? input.data.buffer.slice(input.data.byteOffset, input.data.byteOffset + input.data.byteLength) : input.data;
123
+ form.append("file", new Blob([buf], { type: input.mediaType }), input.filename);
124
+ if (input.conversationId) form.append("conversationId", input.conversationId);
125
+ const res = await this.doFetch(`${this.base}/v1/uploads`, {
126
+ method: "POST",
127
+ headers: { Authorization: `Bearer ${this.apiKey}`, "X-Chat-User": this.userId },
128
+ body: form
129
+ });
130
+ if (!res.ok) throw new Error(`[chat-widget] hosted upload failed: ${res.status}`);
131
+ const r = await res.json();
132
+ return r;
133
+ }
134
+ async resign(storagePath) {
135
+ const res = await this.doFetch(`${this.base}/v1/uploads/resign`, {
136
+ method: "POST",
137
+ headers: { Authorization: `Bearer ${this.apiKey}`, "X-Chat-User": this.userId, "Content-Type": "application/json" },
138
+ body: JSON.stringify({ storagePath })
139
+ });
140
+ if (!res.ok) return null;
141
+ const r = await res.json();
142
+ return r.url ?? null;
143
+ }
144
+ async remove(storagePath) {
145
+ await this.doFetch(`${this.base}/v1/uploads`, {
146
+ method: "DELETE",
147
+ headers: { Authorization: `Bearer ${this.apiKey}`, "X-Chat-User": this.userId, "Content-Type": "application/json" },
148
+ body: JSON.stringify({ storagePath })
149
+ }).catch(() => {
150
+ });
151
+ }
152
+ };
153
+ function createHostedChatStore(options) {
154
+ if (!options.apiKey) throw new Error("[chat-widget] createHostedChatStore requires an apiKey");
155
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
156
+ const fetchImpl = options.fetch ?? fetch;
157
+ return (userId) => new HostedChatStore(userId, options.apiKey, baseUrl, fetchImpl);
158
+ }
159
+ function createHostedStorage(options) {
160
+ if (!options.apiKey) throw new Error("[chat-widget] createHostedStorage requires an apiKey");
161
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
162
+ const fetchImpl = options.fetch ?? fetch;
163
+ return (userId) => new HostedStorageAdapter(userId, options.apiKey, baseUrl, fetchImpl);
164
+ }
165
+ function createHostedConfig(options) {
166
+ if (!options.apiKey) throw new Error("[chat-widget] createHostedConfig requires an apiKey");
167
+ const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
168
+ const fetchImpl = options.fetch ?? fetch;
169
+ const apiKey = options.apiKey;
170
+ const CONFIG_TTL_MS = 6e4;
171
+ let cached = null;
172
+ return async (ctx) => {
173
+ const now = Date.now();
174
+ if (cached && now - cached.at < CONFIG_TTL_MS) return cached.value;
175
+ try {
176
+ const res = await fetchImpl(`${baseUrl}/v1/config`, {
177
+ method: "GET",
178
+ headers: { Authorization: `Bearer ${apiKey}`, "X-Chat-User": ctx.userId }
179
+ });
180
+ if (!res.ok) {
181
+ cached = { value: null, at: now };
182
+ return null;
183
+ }
184
+ const raw = await res.json();
185
+ const value = {
186
+ model: raw.model ?? null,
187
+ systemPrompt: raw.systemPrompt ?? null,
188
+ greeting: raw.greeting ?? null,
189
+ appearance: raw.appearance ?? null
190
+ };
191
+ cached = { value, at: now };
192
+ return value;
193
+ } catch {
194
+ cached = { value: null, at: now };
195
+ return null;
196
+ }
197
+ };
198
+ }
199
+ export {
200
+ createHostedChatStore,
201
+ createHostedConfig,
202
+ createHostedStorage
203
+ };
204
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/server/stores/hosted/index.ts","../../../src/server/stores/hosted/store.ts","../../../src/server/chat-store.ts"],"sourcesContent":["/**\n * Hosted store/storage clients — public entry.\n *\n * import { createHostedChatStore, createHostedStorage } from '@mordn/chat-widget/server/hosted';\n * createChatHandler({\n * getUserId,\n * model,\n * store: createHostedChatStore({ apiKey: process.env.MORDN_CHAT_KEY }),\n * storage: createHostedStorage({ apiKey: process.env.MORDN_CHAT_KEY }),\n * });\n *\n * No DATABASE_URL, no bucket, no migrations — the hosted @mordn/chat-api service\n * owns all of that. The only secret you hold is the tenant API key.\n */\nimport 'server-only';\n\nexport { createHostedChatStore, createHostedStorage, createHostedConfig, type HostedOptions } from './store';\n","/**\n * Hosted ChatStore + StorageAdapter — thin HTTP clients over the @mordn/chat-api\n * service. Same interfaces as the Drizzle/Supabase defaults, so switching a\n * consumer from BYO to hosted is a one-line change:\n *\n * store: createHostedChatStore({ apiKey: process.env.MORDN_CHAT_KEY })\n * storage: createHostedStorage({ apiKey: process.env.MORDN_CHAT_KEY })\n *\n * Identity: the `apiKey` authenticates the TENANT (the customer/app). The\n * per-request `userId` the handler binds is sent as `X-Chat-User` — the end\n * user, derived from the consumer's verified session (same trust model as\n * getUserId). The hosted service enforces both axes; this client never decides\n * authorization, it only carries identity.\n */\n\nimport 'server-only';\nimport {\n ConversationOwnershipError,\n type ChatStore,\n} from '../../chat-store';\nimport type { StorageAdapter, UploadInput, UploadResult } from '../../storage-adapter';\nimport type { ChatRequestContext, HostedAgentConfig } from '../../handler-types';\nimport type {\n ListMessagesOptions,\n SaveTurnInput,\n StoredConversation,\n StoredMessage,\n} from '../../types';\n\nconst DEFAULT_BASE_URL = 'https://api.mordn.dev';\n\nexport interface HostedOptions {\n /** Tenant API key (mck_live_… / mck_test_…). Required. Never sent to the client. */\n apiKey: string;\n /** API base URL. Defaults to the hosted service; override for self-host/local. */\n baseUrl?: string;\n /** Optional fetch override (testing). */\n fetch?: typeof fetch;\n}\n\nfunction normaliseConversation(raw: any): StoredConversation {\n return {\n id: raw.id,\n title: raw.title,\n metadata: raw.metadata ?? null,\n createdAt: new Date(raw.created_at ?? raw.createdAt),\n updatedAt: new Date(raw.updated_at ?? raw.updatedAt),\n messageCount: raw.message_count ?? raw.messageCount,\n };\n}\n\nfunction normaliseMessage(raw: any): StoredMessage {\n return {\n id: raw.id,\n role: raw.role,\n parts: raw.parts ?? [],\n text: raw.content ?? raw.text ?? '',\n model: raw.model ?? undefined,\n createdAt: new Date(raw.created_at ?? raw.createdAt),\n };\n}\n\nclass HostedChatStore implements ChatStore {\n private readonly base: string;\n private readonly doFetch: typeof fetch;\n\n constructor(\n public readonly userId: string,\n private readonly apiKey: string,\n baseUrl: string,\n fetchImpl: typeof fetch,\n ) {\n this.base = baseUrl.replace(/\\/$/, '');\n this.doFetch = fetchImpl;\n }\n\n private headers(json = false): Record<string, string> {\n const h: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Chat-User': this.userId,\n };\n if (json) h['Content-Type'] = 'application/json';\n return h;\n }\n\n private async req(path: string, init?: RequestInit): Promise<Response> {\n return this.doFetch(`${this.base}/v1${path}`, init);\n }\n\n async listConversations(): Promise<StoredConversation[]> {\n const res = await this.req('/conversations', { headers: this.headers() });\n if (!res.ok) return [];\n const data = (await res.json()) as { conversations?: any[] };\n return (data.conversations ?? []).map(normaliseConversation);\n }\n\n async getConversation(id: string): Promise<StoredConversation | null> {\n const res = await this.req(`/conversations/${encodeURIComponent(id)}`, { headers: this.headers() });\n if (res.status === 404) return null;\n if (!res.ok) return null;\n const data = (await res.json()) as { conversation?: any };\n return data.conversation ? normaliseConversation(data.conversation) : null;\n }\n\n async ensureConversation(id: string): Promise<StoredConversation> {\n // The hosted API creates-or-rejects inside POST /turns (it calls\n // ensureConversation server-side). With no messages this is a cheap upsert;\n // a 403 means the conversation belongs to another user → ownership error.\n const res = await this.req(`/conversations/${encodeURIComponent(id)}/turns`, {\n method: 'POST',\n headers: this.headers(true),\n body: JSON.stringify({ messages: [] }),\n });\n if (res.status === 403) throw new ConversationOwnershipError(id);\n // Read it back so the contract (returns the row) holds.\n const conv = await this.getConversation(id);\n if (conv) return conv;\n // Brand-new conversation with no messages yet: synthesise the row shape.\n const now = new Date();\n return { id, title: 'New Chat', metadata: {}, createdAt: now, updatedAt: now };\n }\n\n async renameConversation(id: string, title: string): Promise<void> {\n await this.req(`/conversations/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n headers: this.headers(true),\n body: JSON.stringify({ title }),\n });\n }\n\n async deleteConversation(id: string): Promise<boolean> {\n const res = await this.req(`/conversations/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n headers: this.headers(),\n });\n return res.status === 204;\n }\n\n async listMessages(conversationId: string, _opts?: ListMessagesOptions): Promise<StoredMessage[]> {\n const res = await this.req(`/conversations/${encodeURIComponent(conversationId)}`, { headers: this.headers() });\n if (!res.ok) return [];\n const data = (await res.json()) as { messages?: any[] };\n return (data.messages ?? []).map(normaliseMessage);\n }\n\n async saveTurn(input: SaveTurnInput): Promise<void> {\n const res = await this.req(`/conversations/${encodeURIComponent(input.conversationId)}/turns`, {\n method: 'POST',\n headers: this.headers(true),\n body: JSON.stringify({ messages: input.messages, model: input.model }),\n });\n if (res.status === 403) throw new ConversationOwnershipError(input.conversationId);\n if (!res.ok) {\n throw new Error(`[chat-widget] hosted saveTurn failed: ${res.status} ${await res.text().catch(() => '')}`);\n }\n }\n}\n\nclass HostedStorageAdapter implements StorageAdapter {\n private readonly base: string;\n private readonly doFetch: typeof fetch;\n\n constructor(\n public readonly userId: string,\n private readonly apiKey: string,\n baseUrl: string,\n fetchImpl: typeof fetch,\n ) {\n this.base = baseUrl.replace(/\\/$/, '');\n this.doFetch = fetchImpl;\n }\n\n async upload(input: UploadInput): Promise<UploadResult> {\n const form = new FormData();\n // Normalise to an ArrayBuffer for Blob (TS's BlobPart doesn't accept a\n // Uint8Array<ArrayBufferLike> directly under all lib configs).\n const buf: ArrayBuffer =\n input.data instanceof Uint8Array\n ? (input.data.buffer.slice(input.data.byteOffset, input.data.byteOffset + input.data.byteLength) as ArrayBuffer)\n : input.data;\n form.append('file', new Blob([buf], { type: input.mediaType }), input.filename);\n if (input.conversationId) form.append('conversationId', input.conversationId);\n const res = await this.doFetch(`${this.base}/v1/uploads`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${this.apiKey}`, 'X-Chat-User': this.userId },\n body: form,\n });\n if (!res.ok) throw new Error(`[chat-widget] hosted upload failed: ${res.status}`);\n const r = (await res.json()) as UploadResult;\n return r;\n }\n\n async resign(storagePath: string): Promise<string | null> {\n // The hosted history read re-signs server-side, so a separate resign call\n // is rarely needed; expose it for parity. Returns null on any failure.\n const res = await this.doFetch(`${this.base}/v1/uploads/resign`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${this.apiKey}`, 'X-Chat-User': this.userId, 'Content-Type': 'application/json' },\n body: JSON.stringify({ storagePath }),\n });\n if (!res.ok) return null;\n const r = (await res.json()) as { url?: string };\n return r.url ?? null;\n }\n\n async remove(storagePath: string): Promise<void> {\n await this.doFetch(`${this.base}/v1/uploads`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${this.apiKey}`, 'X-Chat-User': this.userId, 'Content-Type': 'application/json' },\n body: JSON.stringify({ storagePath }),\n }).catch(() => {});\n }\n}\n\n/**\n * Create a `ChatStoreFactory` backed by the hosted @mordn/chat-api service.\n * Pass to `createChatHandler({ store: createHostedChatStore({ apiKey }) })`.\n */\nexport function createHostedChatStore(options: HostedOptions) {\n if (!options.apiKey) throw new Error('[chat-widget] createHostedChatStore requires an apiKey');\n const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n const fetchImpl = options.fetch ?? fetch;\n return (userId: string): ChatStore => new HostedChatStore(userId, options.apiKey, baseUrl, fetchImpl);\n}\n\n/**\n * Create a `StorageAdapterFactory` backed by the hosted service.\n */\nexport function createHostedStorage(options: HostedOptions) {\n if (!options.apiKey) throw new Error('[chat-widget] createHostedStorage requires an apiKey');\n const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n const fetchImpl = options.fetch ?? fetch;\n return (userId: string): StorageAdapter => new HostedStorageAdapter(userId, options.apiKey, baseUrl, fetchImpl);\n}\n\n/**\n * Create a `getHostedConfig` fetcher backed by the hosted service's\n * `GET /v1/config`. Pass to\n * `createChatHandler({ getHostedConfig: createHostedConfig({ apiKey }) })`.\n *\n * The agent is resolved server-side from the apiKey, so this returns THIS key's\n * agent config. Results are cached in-process per apiKey for a short TTL so it\n * isn't refetched every turn. Returns null on any failure → the handler falls\n * through to code/defaults (a control-plane hiccup never breaks a turn).\n */\nexport function createHostedConfig(options: HostedOptions) {\n if (!options.apiKey) throw new Error('[chat-widget] createHostedConfig requires an apiKey');\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '');\n const fetchImpl = options.fetch ?? fetch;\n const apiKey = options.apiKey;\n const CONFIG_TTL_MS = 60_000;\n\n let cached: { value: HostedAgentConfig | null; at: number } | null = null;\n\n return async (ctx: ChatRequestContext): Promise<HostedAgentConfig | null> => {\n const now = Date.now();\n if (cached && now - cached.at < CONFIG_TTL_MS) return cached.value;\n\n try {\n const res = await fetchImpl(`${baseUrl}/v1/config`, {\n method: 'GET',\n headers: { Authorization: `Bearer ${apiKey}`, 'X-Chat-User': ctx.userId },\n });\n if (!res.ok) {\n cached = { value: null, at: now };\n return null;\n }\n const raw = (await res.json()) as HostedAgentConfig;\n const value: HostedAgentConfig = {\n model: raw.model ?? null,\n systemPrompt: raw.systemPrompt ?? null,\n greeting: raw.greeting ?? null,\n appearance: raw.appearance ?? null,\n };\n cached = { value, at: now };\n return value;\n } catch {\n cached = { value: null, at: now };\n return null;\n }\n };\n}\n","/**\n * ChatStore — the persistence contract for chat conversations and messages.\n *\n * This is one of the two pluggable backends of the widget (the other is\n * `StorageAdapter` for attachments). The package ships a Drizzle/Postgres\n * implementation as the default; a hosted backend or a BYO store (Prisma,\n * raw SQL, DynamoDB, a test double) is simply another implementation of this\n * same interface.\n *\n * ──────────────────────────────────────────────────────────────────────────\n * The security model is in the shape of this API, not in its callers.\n * ──────────────────────────────────────────────────────────────────────────\n *\n * A `ChatStore` is *bound to one verified user* at construction time (see\n * `ChatStoreFactory`). None of its methods accept a `userId`. This is\n * deliberate and it is the core defence against the IDOR class of bug:\n *\n * - You cannot ask the store for \"conversation X belonging to user Y\",\n * because there is no parameter through which a foreign `userId` could\n * enter. The only user the store will ever read or write is the one it\n * was constructed with.\n *\n * - Every method is therefore *implicitly scoped*. `listConversations()`\n * returns only the bound user's conversations. `getConversation(id)`\n * returns `null` — not someone else's row — when `id` exists but belongs\n * to a different user. `saveTurn(...)` refuses (throws\n * `ConversationOwnershipError`) if `conversationId` exists under another\n * user.\n *\n * The route layer's job shrinks to: authenticate the request, derive the\n * real `userId` from the *server* session, construct a store bound to it,\n * and call methods. There is no per-route ownership check to forget, because\n * the store cannot be made to cross users.\n *\n * Implementations MUST uphold the contract documented on each method. The\n * Drizzle default does; if you write your own, these invariants are the\n * security boundary — treat them as load-bearing, not advisory.\n */\n\nimport type {\n ListMessagesOptions,\n SaveTurnInput,\n StoredConversation,\n StoredMessage,\n} from './types';\n\n/**\n * Thrown by mutating methods when the target conversation exists but is owned\n * by a different user than the one this store is bound to. Callers should map\n * this to an HTTP 403. (Read methods don't throw — they return `null`/`[]` —\n * so that probing for existence can't distinguish \"not found\" from\n * \"forbidden\", which would itself leak information.)\n */\nexport class ConversationOwnershipError extends Error {\n constructor(public readonly conversationId: string) {\n super(`Conversation ${conversationId} is not owned by the current user`);\n this.name = 'ConversationOwnershipError';\n }\n}\n\nexport interface ChatStore {\n /**\n * The user this store instance is bound to. Read-only; set at construction.\n * Exposed so the router can stamp it onto storage paths, logs, etc. — never\n * as something a caller can change.\n */\n readonly userId: string;\n\n // ── Conversations ──────────────────────────────────────────────────────\n\n /**\n * List the bound user's conversations, most-recently-updated first.\n * Returns `messageCount` on each row for the history list. Returns `[]`\n * (never throws) when the user has none.\n */\n listConversations(): Promise<StoredConversation[]>;\n\n /**\n * Fetch a single conversation by id, scoped to the bound user.\n *\n * Returns `null` when the conversation does not exist OR exists but belongs\n * to another user — the two cases are intentionally indistinguishable to\n * the caller (and thus to an attacker). Never returns another user's row.\n */\n getConversation(id: string): Promise<StoredConversation | null>;\n\n /**\n * Ensure a conversation row exists for `id`, owned by the bound user.\n *\n * - If no row exists for `id`: creates it, owned by the bound user, and\n * returns it.\n * - If a row exists and is owned by the bound user: returns it unchanged\n * (idempotent — safe to call at the top of every request).\n * - If a row exists but is owned by a *different* user: throws\n * `ConversationOwnershipError` and writes nothing.\n *\n * This is the single chokepoint that makes \"write into someone else's\n * conversation\" impossible: the router calls it before persisting any\n * message, so a forged conversation id is rejected before any data lands.\n */\n ensureConversation(id: string, init?: { title?: string }): Promise<StoredConversation>;\n\n /**\n * Rename a conversation owned by the bound user. No-op (does not throw) if\n * the conversation doesn't exist or isn't owned by the user — renaming is\n * not security-sensitive and silent failure is friendlier here.\n */\n renameConversation(id: string, title: string): Promise<void>;\n\n /**\n * Delete a conversation (and cascade its messages + attachment rows) owned\n * by the bound user. No-op if it doesn't exist or isn't owned by the user.\n * Returns `true` if a row was actually deleted, `false` otherwise — lets\n * the route return 404 vs 200 honestly without a separate existence check.\n *\n * Note: this deletes message *rows*. Purging the underlying attachment\n * blobs from storage is the router's job (it has the `StorageAdapter`),\n * driven off the attachments this method returns having referenced.\n */\n deleteConversation(id: string): Promise<boolean>;\n\n // ── Messages ───────────────────────────────────────────────────────────\n\n /**\n * Load messages for a conversation, scoped to the bound user, newest-first\n * internally but returned in chronological order (oldest → newest) ready to\n * render. Returns `[]` if the conversation doesn't exist or isn't owned by\n * the user — same non-distinguishing contract as `getConversation`.\n *\n * Honours `ListMessagesOptions` for pagination. Implementations MUST clamp\n * `limit` to a ceiling (default ceiling: 100) so a hostile client can't\n * request an unbounded page.\n */\n listMessages(conversationId: string, opts?: ListMessagesOptions): Promise<StoredMessage[]>;\n\n /**\n * Persist the final messages of a completed turn.\n *\n * Contract:\n * - MUST verify the conversation is owned by the bound user first; throws\n * `ConversationOwnershipError` otherwise (defence in depth — the router\n * already called `ensureConversation`, but `saveTurn` must not trust\n * that).\n * - MUST be idempotent on message id: a message whose id already exists is\n * skipped, not duplicated. (The AI SDK delivers stable ids; replays and\n * retries re-deliver them.)\n * - MUST persist each message's full `parts` array as the source of truth,\n * plus a denormalised text projection for previews.\n * - MUST bump the conversation's `updatedAt`.\n *\n * Errors other than ownership (e.g. a transient DB failure) propagate so\n * the router can log them loudly — a silently-dropped assistant turn is\n * exactly the bug we're trying to design out.\n */\n saveTurn(input: SaveTurnInput): Promise<void>;\n}\n\n/**\n * Constructs a `ChatStore` bound to a specific, already-verified user.\n *\n * The router calls this *after* it has authenticated the request and derived\n * `userId` from the server session — never from anything client-supplied.\n * Passing a client-controlled value here would reintroduce the very IDOR the\n * bound-store design exists to prevent, so implementations should treat\n * `userId` as a trusted server secret, not as request input.\n *\n * Construction is intended to be cheap (the underlying DB pool/connection is\n * shared across instances) so a fresh store per request is the norm.\n */\nexport type ChatStoreFactory = (userId: string) => ChatStore;\n"],"mappings":";AAcA,OAAO;;;ACCP,OAAO;;;ACsCA,IAAM,6BAAN,cAAyC,MAAM;AAAA,EACpD,YAA4B,gBAAwB;AAClD,UAAM,gBAAgB,cAAc,mCAAmC;AAD7C;AAE1B,SAAK,OAAO;AAAA,EACd;AACF;;;AD7BA,IAAM,mBAAmB;AAWzB,SAAS,sBAAsB,KAA8B;AAC3D,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,OAAO,IAAI;AAAA,IACX,UAAU,IAAI,YAAY;AAAA,IAC1B,WAAW,IAAI,KAAK,IAAI,cAAc,IAAI,SAAS;AAAA,IACnD,WAAW,IAAI,KAAK,IAAI,cAAc,IAAI,SAAS;AAAA,IACnD,cAAc,IAAI,iBAAiB,IAAI;AAAA,EACzC;AACF;AAEA,SAAS,iBAAiB,KAAyB;AACjD,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,MAAM,IAAI;AAAA,IACV,OAAO,IAAI,SAAS,CAAC;AAAA,IACrB,MAAM,IAAI,WAAW,IAAI,QAAQ;AAAA,IACjC,OAAO,IAAI,SAAS;AAAA,IACpB,WAAW,IAAI,KAAK,IAAI,cAAc,IAAI,SAAS;AAAA,EACrD;AACF;AAEA,IAAM,kBAAN,MAA2C;AAAA,EAIzC,YACkB,QACC,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OAAO,QAA+D;AAC3E,UAAM,MAAM,KAAK,IAAI;AACrB,QAAI,UAAU,MAAM,OAAO,KAAK,cAAe,QAAO,OAAO;AAE7D,QAAI;AACF,YAAM,MAAM,MAAM,UAAU,GAAG,OAAO,cAAc;AAAA,QAClD,QAAQ;AAAA,QACR,SAAS,EAAE,eAAe,UAAU,MAAM,IAAI,eAAe,IAAI,OAAO;AAAA,MAC1E,CAAC;AACD,UAAI,CAAC,IAAI,IAAI;AACX,iBAAS,EAAE,OAAO,MAAM,IAAI,IAAI;AAChC,eAAO;AAAA,MACT;AACA,YAAM,MAAO,MAAM,IAAI,KAAK;AAC5B,YAAM,QAA2B;AAAA,QAC/B,OAAO,IAAI,SAAS;AAAA,QACpB,cAAc,IAAI,gBAAgB;AAAA,QAClC,UAAU,IAAI,YAAY;AAAA,QAC1B,YAAY,IAAI,cAAc;AAAA,MAChC;AACA,eAAS,EAAE,OAAO,IAAI,IAAI;AAC1B,aAAO;AAAA,IACT,QAAQ;AACN,eAAS,EAAE,OAAO,MAAM,IAAI,IAAI;AAChC,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -1,182 +1,8 @@
1
- import { C as ChatStoreFactory } from '../chat-store-DERCPwhl.mjs';
2
- export { d as ChatStore, e as ConversationOwnershipError, L as ListMessagesOptions, c as SaveTurnInput, S as StoredAttachment, a as StoredConversation, b as StoredMessage } from '../chat-store-DERCPwhl.mjs';
3
- import { a as StorageAdapterFactory } from '../storage-adapter-DD8uqiAP.mjs';
4
- export { S as StorageAdapter, U as UploadInput, b as UploadResult } from '../storage-adapter-DD8uqiAP.mjs';
5
- import { LanguageModel, ToolSet, ModelMessage, UIMessage, StopCondition } from 'ai';
6
-
7
- /**
8
- * Public configuration surface for `createChatHandler`.
9
- *
10
- * This is the API a host app touches to mount the chat backend. The design
11
- * follows one rule, derived from auditing a real power-user integration
12
- * (Jarvis): take away the shared, dangerous-to-get-wrong plumbing; keep every
13
- * point of genuine per-app variation as an injection point or a hook.
14
- *
15
- * Three tiers of override, from "you must" to "you rarely will":
16
- *
17
- * REQUIRED injections — no safe default exists:
18
- * • getUserId (identity; the security boundary)
19
- *
20
- * OPTIONAL injections — a default exists, swap to take control:
21
- * • model (which LLM)
22
- * • buildTools (your tools, incl. per-request resources)
23
- * • store (persistence; hosted default)
24
- * • storage (attachments; hosted default)
25
- *
26
- * HOOKS — the loop runs fine without them; override one seam at a time:
27
- * • buildSystemPrompt, transformMessages, onChatFinish, onError,
28
- * stopWhen, upload
29
- *
30
- * Everything NOT in this file — ownership checks, idempotency, pagination,
31
- * re-signing, socket teardown, save-on-finish — is owned by the handler and
32
- * is intentionally not configurable, because getting it wrong is a security
33
- * or correctness bug, not a preference.
34
- */
35
-
36
- /**
37
- * Everything a per-request hook/injection needs to know about the current
38
- * request, assembled by the handler AFTER authentication. Passed to
39
- * `buildTools`, `model` (when a function), `buildSystemPrompt`, and
40
- * `transformMessages`.
41
- *
42
- * Note `userId` is the server-verified identity — the same value the store
43
- * and storage are bound to. Hooks can trust it.
44
- */
45
- interface ChatRequestContext {
46
- /** Server-verified user id. Never client-supplied. */
47
- userId: string;
48
- /** The conversation this request targets. */
49
- conversationId: string;
50
- /** The raw request, for hooks that need headers/cookies (e.g. an org id). */
51
- request: Request;
52
- }
53
- /**
54
- * What `buildTools` returns. The `cleanup` callback is the critical piece the
55
- * naive "just return a ToolSet" design misses: tools backed by a per-request
56
- * resource (an MCP client holding a socket, a DB transaction, a temp scope)
57
- * MUST be torn down after the stream finishes — exactly once, whether the
58
- * stream completed, errored, or the client aborted. The handler guarantees
59
- * that single, correctly-timed call so the host app never leaks sockets.
60
- */
61
- interface BuiltTools {
62
- tools: ToolSet;
63
- /**
64
- * Called exactly once when the request is fully done (success, error, or
65
- * abort), after the response stream has settled. Optional — omit when your
66
- * tools hold no per-request resource.
67
- */
68
- cleanup?: () => void | Promise<void>;
69
- }
70
- /**
71
- * Server-side upload policy. Enforced by the handler's upload route BEFORE
72
- * any bytes touch storage, so an oversized or disallowed file is rejected
73
- * with a clean 4xx instead of a framework body-parse failure. The widget's
74
- * client-side `accept`/`maxBytes` should mirror these, but the SERVER is the
75
- * source of truth — the client checks are UX, these checks are the boundary.
76
- */
77
- interface UploadPolicy {
78
- /**
79
- * Allowed MIME types. An exact-match allow-list (not a prefix match) so
80
- * `image/svg+xml` can be excluded while `image/png` is allowed. Defaults to
81
- * a conservative image+pdf set that current vision models accept natively.
82
- */
83
- allowedMediaTypes?: string[];
84
- /** Per-file size cap in bytes. Defaults to 5 MB. */
85
- maxBytes?: number;
86
- }
87
- interface CreateChatHandlerOptions {
88
- /**
89
- * Derive the authenticated user's id from the SERVER session — a verified
90
- * cookie/JWT, Clerk `auth()`, NextAuth `getServerSession()`,
91
- * `supabase.auth.getUser()`, etc. Return `null` for an unauthenticated
92
- * request; the handler responds 401.
93
- *
94
- * SECURITY: never read the id from the request body, query string, or a
95
- * header the browser controls (e.g. `X-User-Id`). Those are forgeable and
96
- * doing so reintroduces the IDOR this whole design exists to prevent. The
97
- * handler passes you the `Request` so you can read *verified* cookies — not
98
- * so you can read a client-asserted id.
99
- */
100
- getUserId: (request: Request) => Promise<string | null> | string | null;
101
- /**
102
- * The model to stream from. Either a fixed `LanguageModel` or a function of
103
- * the request context (for per-user/per-org model selection). Defaults to a
104
- * sensible current model when omitted.
105
- */
106
- model?: LanguageModel | ((ctx: ChatRequestContext) => LanguageModel | Promise<LanguageModel>);
107
- /**
108
- * Build the tool set for this request. Async and context-aware so tools can
109
- * close over the user and open per-request resources (e.g. an MCP client).
110
- * Return `{ tools, cleanup }`; the handler calls `cleanup` exactly once when
111
- * the request settles. Omit for a chat with no tools.
112
- */
113
- buildTools?: (ctx: ChatRequestContext) => Promise<BuiltTools> | BuiltTools;
114
- /**
115
- * Persistence backend. Omit to use the hosted/default store. Provide a
116
- * factory to bring your own DB. The factory is called per request with the
117
- * server-verified `userId`; the handler never constructs a store with a
118
- * client-supplied id.
119
- */
120
- store?: ChatStoreFactory;
121
- /**
122
- * Attachment storage backend. Omit to use the hosted/default adapter.
123
- * Provide a factory for BYO storage (S3/R2/own bucket). Same per-request,
124
- * verified-userId construction as `store`.
125
- */
126
- storage?: StorageAdapterFactory;
127
- /**
128
- * Produce the system prompt for this request. Receives the context so it
129
- * can personalise (e.g. bake in the user's name). Defaults to a generic
130
- * assistant prompt.
131
- */
132
- buildSystemPrompt?: (ctx: ChatRequestContext) => string | Promise<string>;
133
- /**
134
- * Last-chance transform of the model-ready messages before they're sent to
135
- * the model — after the handler has applied its own sliding-window prune.
136
- * Use for provider-specific rewrites (e.g. image file-parts → image-parts)
137
- * or extra capping. Defaults to identity.
138
- */
139
- transformMessages?: (messages: ModelMessage[], ctx: ChatRequestContext) => ModelMessage[] | Promise<ModelMessage[]>;
140
- /**
141
- * Called after the assistant turn has been persisted. For telemetry/usage
142
- * logging. NOT where you save messages — the handler already did that. Any
143
- * error thrown here is logged and swallowed; it never fails the response
144
- * (the user already has their answer).
145
- */
146
- onChatFinish?: (info: {
147
- ctx: ChatRequestContext;
148
- messages: UIMessage[];
149
- usage?: unknown;
150
- providerMetadata?: unknown;
151
- }) => void | Promise<void>;
152
- /**
153
- * Map a stream error to the user-facing string the widget shows. Lets you
154
- * downgrade benign post-finish teardown noise and localise messages.
155
- * Defaults to a generic message + server-side error log.
156
- */
157
- onError?: (error: unknown) => string;
158
- /**
159
- * When the model may chain tool calls, how long to let it run before it
160
- * must answer. Defaults to a bounded step count so a misbehaving tool loop
161
- * can't run forever. Pass any AI SDK `StopCondition`.
162
- */
163
- stopWhen?: StopCondition<ToolSet>;
164
- /** Server-side upload policy (types + size). See `UploadPolicy`. */
165
- upload?: UploadPolicy;
166
- /**
167
- * How many of the most-recent messages to send to the model (sliding
168
- * window). Defaults to 30. The handler always prunes; this tunes the
169
- * window. Older messages stay in the store and in the UI — only the model
170
- * payload is windowed.
171
- */
172
- maxHistoryMessages?: number;
173
- /**
174
- * Defensive per-message character cap applied during pruning so a single
175
- * giant pasted blob can't dominate the context window. Defaults to 4000.
176
- * Set to `0` to disable.
177
- */
178
- maxMessageChars?: number;
179
- }
1
+ export { C as ChatStore, d as ChatStoreFactory, e as ConversationOwnershipError, L as ListMessagesOptions, c as SaveTurnInput, S as StoredAttachment, a as StoredConversation, b as StoredMessage } from '../chat-store-Dq1Zy_qV.mjs';
2
+ export { S as StorageAdapter, a as StorageAdapterFactory, U as UploadInput, b as UploadResult } from '../storage-adapter-DD8uqiAP.mjs';
3
+ import { C as CreateChatHandlerOptions } from '../handler-types-CCSjDZZ9.mjs';
4
+ export { B as BuiltTools, a as ChatRequestContext, H as HostedAgentConfig, U as UploadPolicy } from '../handler-types-CCSjDZZ9.mjs';
5
+ import 'ai';
180
6
 
181
7
  /**
182
8
  * createChatHandler — the request router and the "OWN loop".
@@ -214,4 +40,4 @@ declare function createChatHandler(options: CreateChatHandlerOptions): {
214
40
  DELETE: (request: Request) => Promise<Response>;
215
41
  };
216
42
 
217
- export { type BuiltTools, type ChatRequestContext, ChatStoreFactory, type CreateChatHandlerOptions, StorageAdapterFactory, type UploadPolicy, createChatHandler };
43
+ export { CreateChatHandlerOptions, createChatHandler };
@@ -1,182 +1,8 @@
1
- import { C as ChatStoreFactory } from '../chat-store-DERCPwhl.js';
2
- export { d as ChatStore, e as ConversationOwnershipError, L as ListMessagesOptions, c as SaveTurnInput, S as StoredAttachment, a as StoredConversation, b as StoredMessage } from '../chat-store-DERCPwhl.js';
3
- import { a as StorageAdapterFactory } from '../storage-adapter-DD8uqiAP.js';
4
- export { S as StorageAdapter, U as UploadInput, b as UploadResult } from '../storage-adapter-DD8uqiAP.js';
5
- import { LanguageModel, ToolSet, ModelMessage, UIMessage, StopCondition } from 'ai';
6
-
7
- /**
8
- * Public configuration surface for `createChatHandler`.
9
- *
10
- * This is the API a host app touches to mount the chat backend. The design
11
- * follows one rule, derived from auditing a real power-user integration
12
- * (Jarvis): take away the shared, dangerous-to-get-wrong plumbing; keep every
13
- * point of genuine per-app variation as an injection point or a hook.
14
- *
15
- * Three tiers of override, from "you must" to "you rarely will":
16
- *
17
- * REQUIRED injections — no safe default exists:
18
- * • getUserId (identity; the security boundary)
19
- *
20
- * OPTIONAL injections — a default exists, swap to take control:
21
- * • model (which LLM)
22
- * • buildTools (your tools, incl. per-request resources)
23
- * • store (persistence; hosted default)
24
- * • storage (attachments; hosted default)
25
- *
26
- * HOOKS — the loop runs fine without them; override one seam at a time:
27
- * • buildSystemPrompt, transformMessages, onChatFinish, onError,
28
- * stopWhen, upload
29
- *
30
- * Everything NOT in this file — ownership checks, idempotency, pagination,
31
- * re-signing, socket teardown, save-on-finish — is owned by the handler and
32
- * is intentionally not configurable, because getting it wrong is a security
33
- * or correctness bug, not a preference.
34
- */
35
-
36
- /**
37
- * Everything a per-request hook/injection needs to know about the current
38
- * request, assembled by the handler AFTER authentication. Passed to
39
- * `buildTools`, `model` (when a function), `buildSystemPrompt`, and
40
- * `transformMessages`.
41
- *
42
- * Note `userId` is the server-verified identity — the same value the store
43
- * and storage are bound to. Hooks can trust it.
44
- */
45
- interface ChatRequestContext {
46
- /** Server-verified user id. Never client-supplied. */
47
- userId: string;
48
- /** The conversation this request targets. */
49
- conversationId: string;
50
- /** The raw request, for hooks that need headers/cookies (e.g. an org id). */
51
- request: Request;
52
- }
53
- /**
54
- * What `buildTools` returns. The `cleanup` callback is the critical piece the
55
- * naive "just return a ToolSet" design misses: tools backed by a per-request
56
- * resource (an MCP client holding a socket, a DB transaction, a temp scope)
57
- * MUST be torn down after the stream finishes — exactly once, whether the
58
- * stream completed, errored, or the client aborted. The handler guarantees
59
- * that single, correctly-timed call so the host app never leaks sockets.
60
- */
61
- interface BuiltTools {
62
- tools: ToolSet;
63
- /**
64
- * Called exactly once when the request is fully done (success, error, or
65
- * abort), after the response stream has settled. Optional — omit when your
66
- * tools hold no per-request resource.
67
- */
68
- cleanup?: () => void | Promise<void>;
69
- }
70
- /**
71
- * Server-side upload policy. Enforced by the handler's upload route BEFORE
72
- * any bytes touch storage, so an oversized or disallowed file is rejected
73
- * with a clean 4xx instead of a framework body-parse failure. The widget's
74
- * client-side `accept`/`maxBytes` should mirror these, but the SERVER is the
75
- * source of truth — the client checks are UX, these checks are the boundary.
76
- */
77
- interface UploadPolicy {
78
- /**
79
- * Allowed MIME types. An exact-match allow-list (not a prefix match) so
80
- * `image/svg+xml` can be excluded while `image/png` is allowed. Defaults to
81
- * a conservative image+pdf set that current vision models accept natively.
82
- */
83
- allowedMediaTypes?: string[];
84
- /** Per-file size cap in bytes. Defaults to 5 MB. */
85
- maxBytes?: number;
86
- }
87
- interface CreateChatHandlerOptions {
88
- /**
89
- * Derive the authenticated user's id from the SERVER session — a verified
90
- * cookie/JWT, Clerk `auth()`, NextAuth `getServerSession()`,
91
- * `supabase.auth.getUser()`, etc. Return `null` for an unauthenticated
92
- * request; the handler responds 401.
93
- *
94
- * SECURITY: never read the id from the request body, query string, or a
95
- * header the browser controls (e.g. `X-User-Id`). Those are forgeable and
96
- * doing so reintroduces the IDOR this whole design exists to prevent. The
97
- * handler passes you the `Request` so you can read *verified* cookies — not
98
- * so you can read a client-asserted id.
99
- */
100
- getUserId: (request: Request) => Promise<string | null> | string | null;
101
- /**
102
- * The model to stream from. Either a fixed `LanguageModel` or a function of
103
- * the request context (for per-user/per-org model selection). Defaults to a
104
- * sensible current model when omitted.
105
- */
106
- model?: LanguageModel | ((ctx: ChatRequestContext) => LanguageModel | Promise<LanguageModel>);
107
- /**
108
- * Build the tool set for this request. Async and context-aware so tools can
109
- * close over the user and open per-request resources (e.g. an MCP client).
110
- * Return `{ tools, cleanup }`; the handler calls `cleanup` exactly once when
111
- * the request settles. Omit for a chat with no tools.
112
- */
113
- buildTools?: (ctx: ChatRequestContext) => Promise<BuiltTools> | BuiltTools;
114
- /**
115
- * Persistence backend. Omit to use the hosted/default store. Provide a
116
- * factory to bring your own DB. The factory is called per request with the
117
- * server-verified `userId`; the handler never constructs a store with a
118
- * client-supplied id.
119
- */
120
- store?: ChatStoreFactory;
121
- /**
122
- * Attachment storage backend. Omit to use the hosted/default adapter.
123
- * Provide a factory for BYO storage (S3/R2/own bucket). Same per-request,
124
- * verified-userId construction as `store`.
125
- */
126
- storage?: StorageAdapterFactory;
127
- /**
128
- * Produce the system prompt for this request. Receives the context so it
129
- * can personalise (e.g. bake in the user's name). Defaults to a generic
130
- * assistant prompt.
131
- */
132
- buildSystemPrompt?: (ctx: ChatRequestContext) => string | Promise<string>;
133
- /**
134
- * Last-chance transform of the model-ready messages before they're sent to
135
- * the model — after the handler has applied its own sliding-window prune.
136
- * Use for provider-specific rewrites (e.g. image file-parts → image-parts)
137
- * or extra capping. Defaults to identity.
138
- */
139
- transformMessages?: (messages: ModelMessage[], ctx: ChatRequestContext) => ModelMessage[] | Promise<ModelMessage[]>;
140
- /**
141
- * Called after the assistant turn has been persisted. For telemetry/usage
142
- * logging. NOT where you save messages — the handler already did that. Any
143
- * error thrown here is logged and swallowed; it never fails the response
144
- * (the user already has their answer).
145
- */
146
- onChatFinish?: (info: {
147
- ctx: ChatRequestContext;
148
- messages: UIMessage[];
149
- usage?: unknown;
150
- providerMetadata?: unknown;
151
- }) => void | Promise<void>;
152
- /**
153
- * Map a stream error to the user-facing string the widget shows. Lets you
154
- * downgrade benign post-finish teardown noise and localise messages.
155
- * Defaults to a generic message + server-side error log.
156
- */
157
- onError?: (error: unknown) => string;
158
- /**
159
- * When the model may chain tool calls, how long to let it run before it
160
- * must answer. Defaults to a bounded step count so a misbehaving tool loop
161
- * can't run forever. Pass any AI SDK `StopCondition`.
162
- */
163
- stopWhen?: StopCondition<ToolSet>;
164
- /** Server-side upload policy (types + size). See `UploadPolicy`. */
165
- upload?: UploadPolicy;
166
- /**
167
- * How many of the most-recent messages to send to the model (sliding
168
- * window). Defaults to 30. The handler always prunes; this tunes the
169
- * window. Older messages stay in the store and in the UI — only the model
170
- * payload is windowed.
171
- */
172
- maxHistoryMessages?: number;
173
- /**
174
- * Defensive per-message character cap applied during pruning so a single
175
- * giant pasted blob can't dominate the context window. Defaults to 4000.
176
- * Set to `0` to disable.
177
- */
178
- maxMessageChars?: number;
179
- }
1
+ export { C as ChatStore, d as ChatStoreFactory, e as ConversationOwnershipError, L as ListMessagesOptions, c as SaveTurnInput, S as StoredAttachment, a as StoredConversation, b as StoredMessage } from '../chat-store-Dq1Zy_qV.js';
2
+ export { S as StorageAdapter, a as StorageAdapterFactory, U as UploadInput, b as UploadResult } from '../storage-adapter-DD8uqiAP.js';
3
+ import { C as CreateChatHandlerOptions } from '../handler-types-Bil94kTX.js';
4
+ export { B as BuiltTools, a as ChatRequestContext, H as HostedAgentConfig, U as UploadPolicy } from '../handler-types-Bil94kTX.js';
5
+ import 'ai';
180
6
 
181
7
  /**
182
8
  * createChatHandler — the request router and the "OWN loop".
@@ -214,4 +40,4 @@ declare function createChatHandler(options: CreateChatHandlerOptions): {
214
40
  DELETE: (request: Request) => Promise<Response>;
215
41
  };
216
42
 
217
- export { type BuiltTools, type ChatRequestContext, ChatStoreFactory, type CreateChatHandlerOptions, StorageAdapterFactory, type UploadPolicy, createChatHandler };
43
+ export { CreateChatHandlerOptions, createChatHandler };