@jini-ai/chat 0.7.3-next.1 → 0.7.3-next.3

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 (220) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +49 -0
  3. package/dist/core/accepted-input.d.ts +1 -1
  4. package/dist/core/ag-ui/event-projection.d.ts +14 -69
  5. package/dist/core/ag-ui/event-projection.js +58 -133
  6. package/dist/core/ag-ui/event-reduction.d.ts +12 -2
  7. package/dist/core/ag-ui/event-reduction.js +35 -10
  8. package/dist/core/ag-ui/resume.d.ts +110 -0
  9. package/dist/core/ag-ui/resume.js +200 -0
  10. package/dist/core/ag-ui/run-input.d.ts +23 -0
  11. package/dist/core/ag-ui/run-input.js +45 -0
  12. package/dist/core/ag-ui/server.d.ts +69 -0
  13. package/dist/core/ag-ui/server.js +71 -0
  14. package/dist/core/agent-plugin-chat-state.js +13 -11
  15. package/dist/core/assistant-client/ag-ui-approval-relay.d.ts +113 -0
  16. package/dist/core/assistant-client/ag-ui-approval-relay.js +287 -0
  17. package/dist/core/assistant-client/ag-ui-fetch-agent.d.ts +25 -10
  18. package/dist/core/assistant-client/ag-ui-fetch-agent.js +25 -6
  19. package/dist/core/assistant-client/ag-ui-transport.d.ts +86 -3
  20. package/dist/core/assistant-client/ag-ui-transport.js +310 -80
  21. package/dist/core/assistant-client/browser-durable-subscription.d.ts +25 -0
  22. package/dist/core/assistant-client/browser-durable-subscription.js +78 -0
  23. package/dist/core/assistant-client/durable-run-subscription.js +141 -130
  24. package/dist/core/assistant-client/entry.d.ts +2 -1
  25. package/dist/core/assistant-client/entry.js +1 -0
  26. package/dist/core/assistant-client/transport-prompt.d.ts +94 -0
  27. package/dist/core/assistant-client/transport-prompt.js +180 -0
  28. package/dist/core/assistant-client/transport-run.d.ts +49 -0
  29. package/dist/core/assistant-client/transport-run.js +432 -0
  30. package/dist/core/assistant-client/transport-stream.d.ts +73 -0
  31. package/dist/core/assistant-client/transport-stream.js +128 -0
  32. package/dist/core/assistant-client/transport.d.ts +1 -1
  33. package/dist/core/assistant-client/transport.js +129 -835
  34. package/dist/core/assistant-content.d.ts +1 -17
  35. package/dist/core/assistant-content.js +16 -0
  36. package/dist/core/assistant-tool-metadata.d.ts +103 -0
  37. package/dist/core/assistant-tool-metadata.js +56 -0
  38. package/dist/core/checkpoint-interval.d.ts +1 -1
  39. package/dist/core/compact-events.d.ts +1 -1
  40. package/dist/core/durable-projection.d.ts +1 -1
  41. package/dist/core/durable-runs/continuation.d.ts +1 -1
  42. package/dist/core/durable-runs/ledger-contracts.d.ts +4 -1
  43. package/dist/core/durable-runs/ports.d.ts +2 -1
  44. package/dist/core/durable-runs/run-contracts.d.ts +1 -1
  45. package/dist/core/durable-runs/run-finalizer.d.ts +145 -0
  46. package/dist/core/durable-runs/run-finalizer.js +171 -0
  47. package/dist/core/events.d.ts +4 -82
  48. package/dist/core/events.js +2 -1
  49. package/dist/core/index.d.ts +4 -1
  50. package/dist/core/index.js +2 -1
  51. package/dist/core/messages.d.ts +1 -1
  52. package/dist/core/persistence/index.d.ts +1 -1
  53. package/dist/core/persistence/index.js +1 -1
  54. package/dist/core/question-form/normalize.d.ts +9 -3
  55. package/dist/core/question-form/normalize.js +20 -20
  56. package/dist/core/question-form/scan.js +15 -19
  57. package/dist/core/run-activity.d.ts +1 -1
  58. package/dist/core/run-events/entry.d.ts +11 -63
  59. package/dist/core/run-events/entry.js +12 -7
  60. package/dist/core/todos.d.ts +1 -1
  61. package/dist/core/todos.js +8 -0
  62. package/dist/core/tool-call-detail.d.ts +8 -1
  63. package/dist/core/tool-call-detail.js +35 -12
  64. package/dist/core/tool-events.d.ts +1 -1
  65. package/dist/core/tool-output.js +2 -6
  66. package/dist/core/tools.d.ts +2 -1
  67. package/dist/core/transport.d.ts +1 -1
  68. package/dist/core/turn-usage.d.ts +1 -1
  69. package/dist/core/util/parser.js +70 -69
  70. package/dist/embed-widget/browser/embed-send-bridge.d.ts +44 -0
  71. package/dist/embed-widget/browser/embed-send-bridge.js +60 -0
  72. package/dist/embed-widget/browser/frontend-invocation-handler.d.ts +39 -0
  73. package/dist/embed-widget/browser/frontend-invocation-handler.js +151 -0
  74. package/dist/embed-widget/browser/frontend-session-bridge.d.ts +28 -0
  75. package/dist/embed-widget/browser/frontend-session-bridge.js +201 -257
  76. package/dist/embed-widget/browser/lazy-loader.js +16 -12
  77. package/dist/embed-widget/browser/session-store.d.ts +19 -1
  78. package/dist/embed-widget/browser/session-store.js +48 -17
  79. package/dist/embed-widget/transports/fetch-sse.d.ts +1 -1
  80. package/dist/embed-widget/vanilla/index.js +131 -67
  81. package/dist/embed-widget/vanilla/state.js +53 -38
  82. package/dist/react/admin-execution/ai-agent-presentation.d.ts +35 -0
  83. package/dist/react/admin-execution/ai-agent-presentation.js +39 -0
  84. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.d.ts +22 -0
  85. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.js +25 -0
  86. package/dist/react/chat-cleanup/ChatCleanupPanel.d.ts +15 -0
  87. package/dist/react/chat-cleanup/ChatCleanupPanel.js +17 -0
  88. package/dist/react/chat-cleanup/chat-cleanup.hooks.d.ts +168 -0
  89. package/dist/react/chat-cleanup/chat-cleanup.hooks.js +83 -0
  90. package/dist/react/components/ChatCleanupDialog.d.ts +38 -0
  91. package/dist/react/components/ChatCleanupDialog.js +12 -0
  92. package/dist/react/components/ConversationList.d.ts +14 -5
  93. package/dist/react/components/ConversationList.hooks.d.ts +1 -0
  94. package/dist/react/components/ConversationList.hooks.js +4 -2
  95. package/dist/react/components/ConversationList.js +41 -5
  96. package/dist/react/components/Icon.d.ts +1 -1
  97. package/dist/react/components/Icon.js +2 -0
  98. package/dist/react/components/Markdown.js +6 -6
  99. package/dist/react/components/MarkdownLink.d.ts +25 -0
  100. package/dist/react/components/MarkdownLink.js +17 -0
  101. package/dist/react/components/MessageList.hooks.d.ts +4 -0
  102. package/dist/react/components/MessageList.hooks.js +16 -2
  103. package/dist/react/components/MessageList.js +14 -7
  104. package/dist/react/components/MessageList.rules.d.ts +5 -0
  105. package/dist/react/components/MessageList.rules.js +4 -0
  106. package/dist/react/components/RoutedA2uiSurfaceCard.d.ts +80 -0
  107. package/dist/react/components/RoutedA2uiSurfaceCard.js +15 -0
  108. package/dist/react/components/ToolCard.d.ts +4 -2
  109. package/dist/react/components/ToolCard.js +46 -4
  110. package/dist/react/components/ToolCard.rules.d.ts +5 -2
  111. package/dist/react/components/ToolCard.rules.js +12 -5
  112. package/dist/react/components/mcp-ui-question-input.d.ts +1 -1
  113. package/dist/react/components/mcp-ui-surface-state.d.ts +3 -1
  114. package/dist/react/components/mcp-ui-surface-state.js +2 -2
  115. package/dist/react/components/own-link.d.ts +26 -0
  116. package/dist/react/components/own-link.js +36 -0
  117. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.d.ts +7 -0
  118. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.js +26 -0
  119. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.d.ts +12 -0
  120. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.js +60 -0
  121. package/dist/react/features/bridged-chat/index.d.ts +8 -0
  122. package/dist/react/features/bridged-chat/index.js +7 -0
  123. package/dist/react/features/bridged-chat/types.d.ts +49 -0
  124. package/dist/react/features/bridged-chat/types.js +2 -0
  125. package/dist/react/features/chat-pane/components/RuntimeDropUp.js +1 -1
  126. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.d.ts +6 -0
  127. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.js +101 -59
  128. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.d.ts +3 -0
  129. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.js +26 -16
  130. package/dist/react/features/chat-pane/model-options.d.ts +3 -1
  131. package/dist/react/features/chat-pane/model-options.js +3 -3
  132. package/dist/react/features/chat-pane/rules.js +4 -3
  133. package/dist/react/features/chat-pane/styles.d.ts +1 -1
  134. package/dist/react/features/chat-pane/styles.js +43 -11
  135. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.d.ts +10 -0
  136. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.js +19 -0
  137. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.d.ts +12 -0
  138. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.js +21 -0
  139. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.d.ts +13 -0
  140. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.js +9 -0
  141. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.d.ts +12 -0
  142. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.js +12 -0
  143. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.d.ts +7 -0
  144. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.js +43 -0
  145. package/dist/react/features/conversation-chat-pane/index.d.ts +9 -0
  146. package/dist/react/features/conversation-chat-pane/index.js +8 -0
  147. package/dist/react/features/conversation-chat-pane/rules.d.ts +25 -0
  148. package/dist/react/features/conversation-chat-pane/rules.js +29 -0
  149. package/dist/react/features/conversation-chat-pane/types.d.ts +139 -0
  150. package/dist/react/features/conversation-chat-pane/types.js +2 -0
  151. package/dist/react/features/conversations/conversation-controller.d.ts +16 -0
  152. package/dist/react/features/conversations/conversation-controller.js +280 -0
  153. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.d.ts +15 -0
  154. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.js +33 -0
  155. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.d.ts +16 -0
  156. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.js +36 -0
  157. package/dist/react/features/conversations/index.d.ts +9 -0
  158. package/dist/react/features/conversations/index.js +8 -0
  159. package/dist/react/features/conversations/types.d.ts +120 -0
  160. package/dist/react/features/conversations/types.js +2 -0
  161. package/dist/react/features/voice-input/space-hold-rules.d.ts +65 -0
  162. package/dist/react/features/voice-input/space-hold-rules.js +48 -0
  163. package/dist/react/hooks/testing/fake-transport.d.ts +1 -1
  164. package/dist/react/hooks/useAnsweredCards.d.ts +2 -1
  165. package/dist/react/hooks/useConversation.js +5 -2
  166. package/dist/react/hooks/useExtEventGroups.d.ts +1 -1
  167. package/dist/react/hooks/useRunActivity.d.ts +2 -1
  168. package/dist/react/hooks/useRunStream.d.ts +1 -1
  169. package/dist/react/hooks/useRunStream.js +1 -1
  170. package/dist/react/hooks/useSurfaceRecovery.js +3 -1
  171. package/dist/react/hooks/useToolTimeline.d.ts +2 -1
  172. package/dist/react/index.d.ts +5 -2
  173. package/dist/react/index.js +4 -2
  174. package/dist/react/message-blocks.d.ts +1 -48
  175. package/dist/react/message-blocks.js +47 -0
  176. package/dist/react/styles/chat-settings.css +14 -14
  177. package/dist/server/chat-cleanup-routes.d.ts +56 -0
  178. package/dist/server/chat-cleanup-routes.js +56 -0
  179. package/dist/server/durable-runs/recover.js +193 -171
  180. package/dist/server/run-finalizer/entry.js +133 -110
  181. package/dist/store/legacy/sqlite/conversations.js +29 -17
  182. package/dist/store/pglite/index.d.ts +1 -0
  183. package/dist/store/pglite/index.js +1 -0
  184. package/dist/store/ports.d.ts +12 -0
  185. package/dist/store/postgres/index.d.ts +1 -0
  186. package/dist/store/postgres/index.js +1 -0
  187. package/dist/store/runtime/attempt-base-retention.d.ts +57 -0
  188. package/dist/store/runtime/attempt-base-retention.js +103 -0
  189. package/dist/store/runtime/chat-maintenance.d.ts +16 -0
  190. package/dist/store/runtime/chat-maintenance.js +19 -0
  191. package/dist/store/runtime/chat-principal.d.ts +63 -0
  192. package/dist/store/runtime/chat-principal.js +39 -0
  193. package/dist/store/runtime/checkpoint-delta.d.ts +1 -1
  194. package/dist/store/runtime/durable-run-queries.d.ts +124 -0
  195. package/dist/store/runtime/durable-run-queries.js +122 -0
  196. package/dist/store/runtime/durable-run-store.d.ts +1 -1
  197. package/dist/store/runtime/durable-run-store.js +291 -343
  198. package/dist/store/runtime/entry.d.ts +3 -0
  199. package/dist/store/runtime/entry.js +3 -0
  200. package/dist/store/runtime/events-json.d.ts +1 -1
  201. package/dist/store/runtime/lazy-run-ledger.d.ts +19 -0
  202. package/dist/store/runtime/lazy-run-ledger.js +28 -0
  203. package/dist/store/runtime/run-ledger.d.ts +4 -1
  204. package/dist/store/runtime/run-ledger.js +256 -204
  205. package/dist/store/sql/bulk-deletion.d.ts +36 -0
  206. package/dist/store/sql/bulk-deletion.js +103 -0
  207. package/dist/store/sql/store-queries.d.ts +170 -0
  208. package/dist/store/sql/store-queries.js +212 -0
  209. package/dist/store/sql/store-rows.d.ts +106 -0
  210. package/dist/store/sql/store-rows.js +116 -0
  211. package/dist/store/sql/store-writes.d.ts +46 -0
  212. package/dist/store/sql/store-writes.js +161 -0
  213. package/dist/store/sql/store.d.ts +3 -16
  214. package/dist/store/sql/store.js +58 -428
  215. package/dist/store/sql/tables.d.ts +1 -0
  216. package/dist/store/sqlite/index.d.ts +1 -0
  217. package/dist/store/sqlite/index.js +1 -0
  218. package/dist/store/sqlite/schema.d.ts +1 -1
  219. package/dist/store/sqlite/schema.js +5 -1
  220. package/package.json +174 -23
@@ -1,61 +1,10 @@
1
- import { sqliteReadVersion } from './read-version.js';
2
- import { withFolderReceipt, foldersFromReceipts } from '../../core/accepted-input.js';
3
- const MESSAGE_POSITION = 'm.position';
4
- const CONVERSATION_UPDATED_AT = 'c.updated_at';
5
- /** One SQL query body upstreamed from the existing host adapter; no resource/schema ownership. */
6
- // Legacy project/conversation CRUD trusts access to a local database file; this owner-bound store
7
- // serves shared databases instead. Choose by trust model: borrowing a handle must not grant access
8
- // to every tenant, and this adapter neither chooses that handle's file nor owns its lifetime.
9
- /**
10
- * Every read/write uses the authenticated (scope_id, owner_kind, owner_id) tuple; store construction
11
- * must not turn a shared database into access to other owners' conversations. Append reads and
12
- * assigns position in one transaction under the conversation lock: PostgreSQL READ COMMITTED alone
13
- * cannot serialize two appends as SQLite BEGIN IMMEDIATE does. The unique conversation/position
14
- * constraint remains the backstop, and nested appends join the host's existing transaction.
15
- */
16
- import { sql } from 'kysely';
17
- import { isUniqueViolation } from '@jini-ai/core/contracts/storage';
1
+ import { foldersFromReceipts } from '../../core/accepted-input.js';
18
2
  import { redactUserMessage } from '../../core/user-text-redaction.js';
19
3
  import { MID_RUN_USER_MESSAGE_EVENT_NAME } from '../../core/turn-usage.js';
20
- import { ChatStoreError } from '../errors.js';
21
- import { copyScope, atStoreBoundary, runChatQuery } from './boundary.js';
22
- import { pageLimit, decodeCursor, encodeCursor } from './cursor.js';
23
- /** UTF-8 byte ordinal ordering, identical on SQLite BINARY and PostgreSQL C collation. */
24
- function ordinalId(dialect, column) {
25
- return dialect === 'sqlite' ? sql `${sql.ref(column)} collate BINARY` : sql `${sql.ref(column)} collate "C"`;
26
- }
27
- /** The lock every position-assigning append to one conversation takes. */
28
- function conversationLockKey(conversationId) {
29
- return `chat-conversation:${conversationId}`;
30
- }
31
- function toConversation(row) {
32
- return {
33
- id: row.id,
34
- title: row.title,
35
- titleSource: row.title_source,
36
- // COUNT(*) never yields null; Number() also maps a driver's string/bigint count.
37
- messageCount: Number(row.message_count),
38
- createdAt: Number(row.created_at),
39
- updatedAt: Number(row.updated_at),
40
- ...(row.expires_at === null ? {} : { expiresAt: Number(row.expires_at) }),
41
- };
42
- }
43
- /**
44
- * A malformed JSON column yields `undefined` rather than throwing: one half-written `events_json`
45
- * must not make the whole conversation unreadable (same rule as Jini's store).
46
- */
47
- function safeParse(value) {
48
- try {
49
- return JSON.parse(value);
50
- }
51
- catch {
52
- return undefined;
53
- }
54
- }
55
- /** A NULL (or empty) JSON column is absent; anything else goes through {@link safeParse}. */
56
- function parseJsonColumn(value) {
57
- return value ? safeParse(value) : undefined;
58
- }
4
+ import { copyScope, atStoreBoundary, chatKernelTables, runChatQuery } from './boundary.js';
5
+ import { parseJsonColumn } from './store-rows.js';
6
+ import { getConversation, historyList, historyRead, listConversations, listMessages, messageById, messageRowsWithValidity, messagesVersion, pageConversations, pageMessages, } from './store-queries.js';
7
+ import { createConversation, deleteConversation, renameConversation, touchConversation, updateConversation, writeMessage } from './store-writes.js';
59
8
  /** Project only existing ai_* fields: resumable and lastRunEventId belong to run state. */
60
9
  // Both fields disappear on a transcript round trip today. Adding columns alone would let the
61
10
  // browser persist claims about a run it does not own. First associate the run with its conversation
@@ -83,8 +32,8 @@ function agentFields(row) {
83
32
  }
84
33
  /** Unparseable or absent JSON columns are omitted rather than failing the read. */
85
34
  function jsonFields(row) {
86
- const events = parseJsonColumn(row.events_json);
87
- const attachments = parseJsonColumn(row.attachments_json);
35
+ const events = parseJsonColumn({ value: row.events_json });
36
+ const attachments = parseJsonColumn({ value: row.attachments_json });
88
37
  const folders = foldersFromReceipts({ events });
89
38
  return {
90
39
  ...(events === undefined ? {} : { events }),
@@ -101,6 +50,13 @@ function rawMessageMetadata({ row }, _optional = {}) {
101
50
  delete message.events;
102
51
  return message;
103
52
  }
53
+ /** Empty run columns are omitted. */
54
+ function runFields(row) {
55
+ return {
56
+ ...(row.run_id ? { runId: row.run_id } : {}),
57
+ ...(row.run_status ? { runStatus: row.run_status } : {}),
58
+ };
59
+ }
104
60
  /** Keep malformed-column tolerance without reserializing event trees. SQLite validates in SQL;
105
61
  * PostgreSQL 14 lacks a safe built-in JSON try-cast, so validate and discard one row's parsed value.
106
62
  * @complexity O(row JSON size) time; PG14 temporarily allocates one event tree, SQLite none. */
@@ -140,42 +96,6 @@ async function* messageJsonChunks({ rows }, { orderMessages = messages => messag
140
96
  }
141
97
  yield ']}';
142
98
  }
143
- /** Receipt-bearing user rows retain their public metadata while large assistant histories stay
144
- * outside recovery/acceptance projections. Both dialects evaluate the same CASE expression. */
145
- function messageEventsColumn({ includeEvents }, _options = {}) {
146
- if (includeEvents === 'user')
147
- return sql `case when m.role = 'user' then m.events_json else null end`;
148
- return includeEvents ? sql `m.events_json` : sql `null`;
149
- }
150
- /** Empty run columns are omitted. */
151
- function runFields(row) {
152
- return {
153
- ...(row.run_id ? { runId: row.run_id } : {}),
154
- ...(row.run_status ? { runStatus: row.run_status } : {}),
155
- };
156
- }
157
- /** Reject an unbounded or malformed history read before any query runs. */
158
- function assertHistoryReadBounds({ limit, fromPosition }) {
159
- if (!Number.isInteger(limit) || limit < 1 || limit > 100)
160
- throw new ChatStoreError({ code: 'invalid-input' });
161
- if (fromPosition !== undefined && (!Number.isSafeInteger(fromPosition) || fromPosition < 0)) {
162
- throw new ChatStoreError({ code: 'invalid-input' });
163
- }
164
- }
165
- /** Project one history row; `events` is present (possibly undefined) only when tool events were asked for. */
166
- function toHistoryMessage(row, { includeToolEvents }) {
167
- return { id: row.id, role: row.role, content: row.content,
168
- position: Number(row.position), createdAt: Number(row.created_at),
169
- ...(includeToolEvents ? { events: parseJsonColumn(row.events_json) } : {}), };
170
- }
171
- /** @throws {ChatStoreError} `invalid-input` for an out-of-range limit or an over-long/non-string query. */
172
- function assertHistoryListInputs({ limit, query }, _optional = {}) {
173
- if (!Number.isInteger(limit) || limit < 1 || limit > 50)
174
- throw new ChatStoreError({ code: 'invalid-input' });
175
- if (query !== undefined && (typeof query !== 'string' || query.length > 200)) {
176
- throw new ChatStoreError({ code: 'invalid-input' });
177
- }
178
- }
179
99
  /**
180
100
  * Returns a {@link ChatHistoryStore} that can only ever see `scope`'s own conversations.
181
101
  *
@@ -188,334 +108,55 @@ function assertHistoryListInputs({ limit, query }, _optional = {}) {
188
108
  * messages and embedded events in SQL; `messages` is O(messages in the conversation).
189
109
  */
190
110
  export function createSqlChatStore({ kernel, scope: inputScope, clock }, redactionOptions = {}) {
191
- const scope = copyScope({ scope: inputScope });
192
- const { scopeId, ownerKind, ownerId } = scope;
193
111
  // The single subset boundary: DB must contain both required table definitions. Extra host tables
194
112
  // stay on the exact borrowed kernel; its transaction context is never projected or recreated.
195
- const run = (body) => runChatQuery({ kernel: kernel, body: body });
196
- // Count embedded user messages in SQL: list/get still return summaries, never whole transcripts.
197
- // Writers store `JSON.stringify` output (no whitespace, as appendedEventsJson also relies on), so
198
- // each mid-run event holds this exact text once; text inside a JSON string has escaped quotes and
199
- // cannot match, and invalid JSON stays readable (it counts what it holds, never throws). Plain
200
- // length/replace run on SQLite and PostgreSQL 14+, unlike `IS JSON` (PostgreSQL 16+).
201
- const needle = `"name":"${MID_RUN_USER_MESSAGE_EVENT_NAME}"`;
202
- const midRunCount = sql `((length(coalesce(m.events_json, '')) - length(replace(coalesce(m.events_json, ''), ${sql.lit(needle)}, ''))) / ${sql.lit(needle.length)})`;
203
- /** This scope's conversations, projected as {@link ConversationRow}s with their message count. */
204
- function ownedConversations(db) {
205
- return db
206
- .selectFrom("ai_chats as c")
207
- .select((eb) => [
208
- "c.id",
209
- "c.title",
210
- "c.title_source",
211
- "c.created_at",
212
- CONVERSATION_UPDATED_AT,
213
- "c.expires_at",
214
- eb
215
- .selectFrom("ai_chat_messages as m")
216
- .select(sql `coalesce(sum(1 + case when m.role = 'assistant' then ${midRunCount} else 0 end), 0)`.as("n"))
217
- .whereRef("m.conversation_id", "=", "c.id")
218
- .as("message_count"),
219
- ])
220
- .where("c.scope_id", "=", scopeId)
221
- .where("c.owner_kind", "=", ownerKind)
222
- .where("c.owner_id", "=", ownerId);
223
- }
224
- /** One owner-filtered indexed lookup; missing and foreign IDs both return null. */
225
- async function get({ id }, _optional = {}) {
226
- const row = await run((db) => ownedConversations(db).where("c.id", "=", id).executeTakeFirst());
227
- return row ? toConversation(row) : null;
228
- }
229
- /** One scoped projection for all message reads, including the row returned by an upsert. */
230
- function ownedMessages(db, conversationId, { includeEvents = true } = {}) {
231
- return db
232
- .selectFrom("ai_chat_messages as m")
233
- .innerJoin("ai_chats as c", "c.id", "m.conversation_id")
234
- .select([
235
- "m.id",
236
- "m.role",
237
- "m.content",
238
- "m.agent_id",
239
- "m.agent_name",
240
- "m.attachments_json",
241
- "m.run_id",
242
- "m.run_status",
243
- "m.created_at",
244
- "m.started_at",
245
- "m.ended_at",
246
- ])
247
- .select(messageEventsColumn({ includeEvents }).as('events_json'))
248
- .where("m.conversation_id", "=", conversationId)
249
- .where("c.scope_id", "=", scopeId)
250
- .where("c.owner_kind", "=", ownerKind)
251
- .where("c.owner_id", "=", ownerId);
252
- }
253
- /** Read owned messages in persisted position order; foreign IDs produce no rows. */
254
- async function messages({ conversationId }, { includeEvents = true } = {}) {
255
- const rows = await run(db => ownedMessages(db, conversationId, { includeEvents }).orderBy(MESSAGE_POSITION).execute());
256
- return rows.map(toMessage);
257
- }
258
- /** Writes and projects one message inside the borrowed transaction; null for absent/foreign IDs. */
259
- function writeMessage(conversationId, message) {
260
- const m = withFolderReceipt({ message });
261
- return kernel.transaction(async () => {
262
- await kernel.lockKey(conversationLockKey(conversationId));
263
- const owned = await run((db) => db
264
- .selectFrom("ai_chats")
265
- .select("id")
266
- .where("id", "=", conversationId)
267
- .where("scope_id", "=", scopeId)
268
- .where("owner_kind", "=", ownerKind)
269
- .where("owner_id", "=", ownerId)
270
- .executeTakeFirst());
271
- if (!owned)
272
- return null;
273
- const existing = await run((db) => db
274
- .selectFrom("ai_chat_messages")
275
- .select("position")
276
- .where("id", "=", m.id)
277
- .where("conversation_id", "=", conversationId)
278
- .executeTakeFirst());
279
- const position = existing ? Number(existing.position) : await nextPosition(conversationId);
280
- // The conflict target is `id`, the GLOBAL key: the `where` keeps an id that already lives in
281
- // another conversation from updating THAT row (the contract's "colliding id to its OWN chat" case).
282
- await run((db) => db
283
- .insertInto("ai_chat_messages")
284
- .values({
285
- id: m.id,
286
- conversation_id: conversationId,
287
- role: m.role,
288
- content: m.content,
289
- agent_id: m.agentId ?? null,
290
- agent_name: m.agentName ?? null,
291
- events_json: m.events ? JSON.stringify(m.events) : null,
292
- attachments_json: m.attachments ? JSON.stringify(m.attachments) : null,
293
- run_id: m.runId ?? null,
294
- run_status: m.runStatus ?? null,
295
- position,
296
- created_at: m.createdAt ?? clock.nowMs(),
297
- started_at: m.startedAt ?? null,
298
- ended_at: m.endedAt ?? null,
299
- })
300
- .onConflict(updateOwnedMessageConflict)
301
- .execute());
302
- // A new message is activity: the list orders by `updated_at`.
303
- await run((db) => db.updateTable("ai_chats").set({ updated_at: clock.nowMs() }).where("id", "=", conversationId).execute());
304
- // Re-read only the written row, while still in the same transaction and conversation lock.
305
- const saved = await run(db => ownedMessages(db, conversationId).where('m.id', '=', m.id).executeTakeFirst());
306
- return saved ? toMessage(saved) : null;
307
- });
308
- }
309
- async function nextPosition(conversationId) {
310
- const row = await run((db) => db
311
- .selectFrom("ai_chat_messages")
312
- .select((eb) => eb.fn.max("position").as("max"))
313
- .where("conversation_id", "=", conversationId)
314
- .executeTakeFirst());
315
- return row?.max === null || row?.max === undefined ? 0 : Number(row.max) + 1;
316
- }
317
- const store = {
113
+ const ctx = {
114
+ kernel: chatKernelTables({ kernel }, {}),
115
+ run: body => runChatQuery({ kernel: kernel, body: body }),
116
+ scope: copyScope({ scope: inputScope }),
117
+ clock,
118
+ toMessage,
119
+ };
120
+ return wrapAtStoreBoundary(createRawChatStore({ ctx, redactionOptions }));
121
+ }
122
+ /** The raw store: every method delegates to a query/write function; errors are not yet translated. */
123
+ function createRawChatStore({ ctx, redactionOptions }) {
124
+ return {
318
125
  history: {
319
- /** Literal search uses two scoped projections, not a transcript fetch per conversation.
320
- * A continuation is bound to this owner and orders by activity descending, then ID ascending.
321
- * @throws {ChatStoreError} For invalid inputs or a cursor belonging to another scope.
322
- * @complexity The database scans owned content for search; at most limit+1 rows are returned.
323
- */
324
- async list(_required, { query, limit = 20, cursor } = {}) {
325
- assertHistoryListInputs({ limit, query });
326
- const anchor = decodeCursor({ cursor: cursor ?? undefined, kind: 'conversations', scope, conversation: null });
327
- const id = ordinalId(kernel.dialect, 'c.id');
328
- const rows = await run(db => {
329
- let statement = ownedConversations(db).select(eb => eb.selectFrom('ai_chat_messages as first')
330
- .select('first.content').whereRef('first.conversation_id', '=', 'c.id').where('first.role', '=', 'user')
331
- .orderBy('first.position').limit(1).as('first_user_line'));
332
- if (query?.trim()) {
333
- // Escape LIKE wildcards: user search is literal text, never an SQL/FTS expression.
334
- const pattern = '%' + query.trim().toLowerCase().replace(/[!%_]/g, char => '!' + char) + '%';
335
- statement = statement.where(eb => eb.or([
336
- sql `lower(c.title) like ${pattern} escape '!'`,
337
- eb.exists(eb.selectFrom('ai_chat_messages as found').select('found.id')
338
- .whereRef('found.conversation_id', '=', 'c.id')
339
- .where(sql `lower(found.content) like ${pattern} escape '!'`)),
340
- ]));
341
- }
342
- if (anchor)
343
- statement = statement.where(eb => eb.or([
344
- eb(CONVERSATION_UPDATED_AT, '<', anchor[0]),
345
- eb.and([eb(CONVERSATION_UPDATED_AT, '=', anchor[0]), eb(id, '>', anchor[1])]),
346
- ]));
347
- return statement.orderBy(CONVERSATION_UPDATED_AT, 'desc').orderBy(id, 'asc').limit(limit + 1).execute();
348
- });
349
- const items = rows.slice(0, limit).map(row => ({ ...toConversation(row), firstUserLine: row.first_user_line ?? '' }));
350
- const last = items.at(-1);
351
- const nextCursor = rows.length > limit && last
352
- ? encodeCursor({ kind: 'conversations', scope, conversation: null, anchor: [last.updatedAt, last.id] })
353
- : null;
354
- return { items, nextCursor };
355
- },
356
- /** No attachment column is read. O(limit) rows; default tail is reversed into position order. */
357
- async read({ chatId }, { fromPosition, limit = 50, includeToolEvents = false } = {}) {
358
- assertHistoryReadBounds({ limit, fromPosition });
359
- const rows = await run(db => {
360
- let statement = ownedMessages(db, chatId).clearSelect().select([
361
- 'm.id', 'm.role', 'm.content', MESSAGE_POSITION, 'm.created_at',
362
- ]);
363
- if (fromPosition !== undefined)
364
- statement = statement.where(MESSAGE_POSITION, '>=', fromPosition);
365
- return statement.select(includeToolEvents ? sql `m.events_json`.as('events_json') : sql `null`.as('events_json'))
366
- .orderBy(MESSAGE_POSITION, fromPosition === undefined ? 'desc' : 'asc').limit(limit + 1).execute();
367
- });
368
- const page = rows.slice(0, limit);
369
- if (fromPosition === undefined)
370
- page.reverse();
371
- return { messages: page.map(row => toHistoryMessage(row, { includeToolEvents })), hasMore: rows.length > limit };
372
- },
373
- },
374
- async list() {
375
- const rows = await run((db) => ownedConversations(db).orderBy(CONVERSATION_UPDATED_AT, "desc").execute());
376
- return rows.map((row) => toConversation(row));
377
- },
378
- get,
379
- async create(input, _optional = {}) {
380
- const ts = clock.nowMs();
381
- try {
382
- await run((db) => db
383
- .insertInto("ai_chats")
384
- .values({
385
- id: input.id,
386
- scope_id: scopeId,
387
- owner_kind: ownerKind,
388
- owner_id: ownerId,
389
- title: input.title ?? null,
390
- title_source: input.titleSource ?? "fallback",
391
- created_at: ts,
392
- updated_at: ts,
393
- expires_at: input.expiresAt ?? null,
394
- })
395
- .execute());
396
- }
397
- catch (cause) {
398
- if (isUniqueViolation({ err: cause }))
399
- throw new ChatStoreError({ code: 'conflict' }, { cause });
400
- throw cause;
401
- }
402
- const created = await get({ id: input.id });
403
- // Unreachable: the insert used this exact scope. Asserted so a future change to either
404
- // statement fails loudly instead of returning a malformed conversation.
405
- if (!created)
406
- throw new Error(`ai_chats: created conversation ${input.id} was not readable in its own scope`);
407
- return created;
408
- },
409
- async rename({ id, title }, { source = "manual" } = {}) {
410
- // A generated title never overwrites a typed one: in the WHERE clause, so a concurrent
411
- // rename cannot slip between a read and this write.
412
- await run((db) => db
413
- .updateTable("ai_chats")
414
- .set({ title, title_source: source, updated_at: clock.nowMs() })
415
- .where("id", "=", id)
416
- .where("scope_id", "=", scopeId)
417
- .where("owner_kind", "=", ownerKind)
418
- .where("owner_id", "=", ownerId)
419
- .$if(source === "generated", (qb) => qb.where("title_source", "<>", "manual"))
420
- .execute());
421
- return get({ id });
422
- },
423
- async touch({ id }, options = {}) {
424
- const ts = clock.nowMs();
425
- await run((db) => db
426
- .updateTable("ai_chats")
427
- .set(options?.expiresAt === undefined ? { updated_at: ts } : { updated_at: ts, expires_at: options.expiresAt })
428
- .where("id", "=", id)
429
- .where("scope_id", "=", scopeId)
430
- .where("owner_kind", "=", ownerKind)
431
- .where("owner_id", "=", ownerId)
432
- .execute());
433
- },
434
- async delete({ id }, _optional = {}) {
435
- // Messages, agent sessions and tool approvals go with it through `ON DELETE CASCADE`.
436
- await run((db) => db
437
- .deleteFrom("ai_chats")
438
- .where("id", "=", id)
439
- .where("scope_id", "=", scopeId)
440
- .where("owner_kind", "=", ownerKind)
441
- .where("owner_id", "=", ownerId)
442
- .execute());
443
- },
444
- messages,
445
- /** One indexed, owner-scoped row; browser save fences do not need the conversation's history. */
446
- async message({ conversationId, messageId }, _optional = {}) {
447
- const row = await run(db => ownedMessages(db, conversationId).where('m.id', '=', messageId).executeTakeFirst());
448
- return row ? toMessage(row) : null;
449
- },
450
- /** SQLite's connection/external-commit counters avoid reading message rows at all. PG uses
451
- * MVCC versions from only this conversation's indexed metadata, never large event columns.
452
- * @complexity O(1) SQLite; O(n) PG message metadata for n messages; O(1) returned bytes.
453
- */
454
- async messagesVersion({ conversationId }, _optional = {}) {
455
- const row = await run(db => db.selectFrom('ai_chats as c').select(eb => {
456
- const version = kernel.dialect === 'sqlite' ? sqliteReadVersion({ kernel })
457
- : sql `md5(coalesce(${eb.selectFrom('ai_chat_messages as m')
458
- .select(sql `string_agg(m.id || ':' || cast(m.xmin as text), ',' order by m.position)`.as('versions'))
459
- .whereRef('m.conversation_id', '=', 'c.id')}, ''))`;
460
- return version.as('version');
461
- })
462
- .where('c.id', '=', conversationId).where('c.scope_id', '=', scopeId)
463
- .where('c.owner_kind', '=', ownerKind).where('c.owner_id', '=', ownerId).executeTakeFirst());
464
- return row?.version ?? null;
126
+ list: (_required, options = {}) => historyList({ ctx, options }),
127
+ read: ({ chatId }, options = {}) => historyRead({ ctx, chatId, options }),
465
128
  },
129
+ list: () => listConversations({ ctx }),
130
+ get: ({ id }, _optional = {}) => getConversation({ ctx, id }),
131
+ create: (input, _optional = {}) => createConversation({ ctx, input }),
132
+ rename: ({ id, title }, { source = "manual" } = {}) => renameConversation({ ctx, id, title, source }),
133
+ setPinned: ({ id, pinned }, _optional = {}) => updateConversation({ ctx, id, pinned, source: "manual" }),
134
+ updateConversation: ({ id, title, pinned }, { source = "manual" } = {}) => updateConversation({ ctx, id, ...(title === undefined ? {} : { title }), ...(pinned === undefined ? {} : { pinned }), source }),
135
+ touch: ({ id }, options = {}) => touchConversation({ ctx, id, options }),
136
+ delete: ({ id }, _optional = {}) => deleteConversation({ ctx, id }),
137
+ messages: ({ conversationId }, { includeEvents = true } = {}) => listMessages({ ctx, conversationId }, { includeEvents }),
138
+ message: ({ conversationId, messageId }, _optional = {}) => messageById({ ctx, conversationId, messageId }),
139
+ messagesVersion: ({ conversationId }, _optional = {}) => messagesVersion({ ctx, conversationId }),
466
140
  async messagesJson({ conversationId }, optional = {}) {
467
- const valid = kernel.dialect === 'sqlite' ? sql `json_valid(m.events_json)` : sql `null`;
468
- const rows = await run(db => ownedMessages(db, conversationId).select(valid.as('events_json_valid')).orderBy(MESSAGE_POSITION).execute());
469
- return messageJsonChunks({ rows }, optional);
470
- },
471
- async appendMessage({ conversationId, message }, _optional = {}) {
472
- const prepared = redactUserMessage({ message }, { ...(redactionOptions.redactUserText ? { redactUserText: redactionOptions.redactUserText } : {}) });
473
- const saved = await writeMessage(conversationId, prepared.message);
474
- if (!saved || !prepared.secretRedacted)
475
- return saved;
476
- const signal = { secretRedacted: true, count: prepared.count };
477
- redactionOptions.onSecretRedacted?.(signal);
478
- return { ...saved, secretRedaction: signal };
479
- },
480
- async pageConversations(_required, options = {}) {
481
- const limit = pageLimit({ options: options });
482
- const anchor = decodeCursor({ cursor: options?.cursor, kind: 'conversations', scope: scope, conversation: null });
483
- const id = ordinalId(kernel.dialect, 'c.id');
484
- const rows = await run(db => {
485
- let query = ownedConversations(db);
486
- if (anchor)
487
- query = query.where(eb => eb.or([
488
- eb(CONVERSATION_UPDATED_AT, '<', anchor[0]),
489
- eb.and([eb(CONVERSATION_UPDATED_AT, '=', anchor[0]), eb(id, '>', anchor[1])]),
490
- ]));
491
- return query.orderBy(CONVERSATION_UPDATED_AT, 'desc').orderBy(id, 'asc').limit(limit + 1).execute();
492
- });
493
- const items = rows.slice(0, limit).map(row => toConversation(row));
494
- const last = items.at(-1);
495
- return { items, ...(rows.length > limit && last ? {
496
- nextCursor: encodeCursor({ kind: 'conversations', scope: scope, conversation: null, anchor: [last.updatedAt, last.id] }),
497
- } : {}) };
498
- },
499
- async pageMessages(input, options = {}) {
500
- const limit = pageLimit({ options: options });
501
- const anchor = decodeCursor({ cursor: options?.cursor, kind: 'messages', scope: scope, conversation: input.conversationId });
502
- const id = ordinalId(kernel.dialect, 'm.id');
503
- // One join, at most limit+1 rows, including the ownership check; no parent pre-read.
504
- const rows = await run(db => {
505
- let query = ownedMessages(db, input.conversationId).select(MESSAGE_POSITION);
506
- if (anchor)
507
- query = query.where(eb => eb.or([
508
- eb(MESSAGE_POSITION, '>', anchor[0]),
509
- eb.and([eb(MESSAGE_POSITION, '=', anchor[0]), eb(id, '>', anchor[1])]),
510
- ]));
511
- return query.orderBy(MESSAGE_POSITION, 'asc').orderBy(id, 'asc').limit(limit + 1).execute();
512
- });
513
- const page = rows.slice(0, limit), last = page.at(-1);
514
- return { items: page.map(toMessage), ...(rows.length > limit && last ? {
515
- nextCursor: encodeCursor({ kind: 'messages', scope: scope, conversation: input.conversationId, anchor: [Number(last.position), last.id] }),
516
- } : {}) };
141
+ return messageJsonChunks({ rows: await messageRowsWithValidity({ ctx, conversationId }) }, optional);
517
142
  },
143
+ appendMessage: ({ conversationId, message }, _optional = {}) => appendRedacted({ ctx, redactionOptions, conversationId, message }),
144
+ pageConversations: (_required, options = {}) => pageConversations({ ctx, options }),
145
+ pageMessages: (input, options = {}) => pageMessages({ ctx, input, options }),
518
146
  };
147
+ }
148
+ /** Redact the user text first, write once, then report (never log) that a secret was removed. */
149
+ async function appendRedacted({ ctx, redactionOptions, conversationId, message }) {
150
+ const prepared = redactUserMessage({ message }, { ...(redactionOptions.redactUserText ? { redactUserText: redactionOptions.redactUserText } : {}) });
151
+ const saved = await writeMessage({ ctx, conversationId, message: prepared.message });
152
+ if (!saved || !prepared.secretRedacted)
153
+ return saved;
154
+ const signal = { secretRedacted: true, count: prepared.count };
155
+ redactionOptions.onSecretRedacted?.(signal);
156
+ return { ...saved, secretRedaction: signal };
157
+ }
158
+ /** Wrap every operation so a driver failure surfaces as a structured {@link ChatStoreError}. */
159
+ function wrapAtStoreBoundary(store) {
519
160
  return {
520
161
  history: {
521
162
  list: (required, optional = {}) => atStoreBoundary({ operation: () => store.history.list(required, optional) }),
@@ -525,6 +166,8 @@ export function createSqlChatStore({ kernel, scope: inputScope, clock }, redacti
525
166
  get: (required, optional = {}) => atStoreBoundary({ operation: () => store.get(required, optional) }),
526
167
  create: (required, optional = {}) => atStoreBoundary({ operation: () => store.create(required, optional) }),
527
168
  rename: (required, optional = {}) => atStoreBoundary({ operation: () => store.rename(required, optional) }),
169
+ setPinned: (required, optional = {}) => atStoreBoundary({ operation: () => store.setPinned(required, optional) }),
170
+ updateConversation: (required, optional = {}) => atStoreBoundary({ operation: () => store.updateConversation(required, optional) }),
528
171
  touch: (required, optional = {}) => atStoreBoundary({ operation: () => store.touch(required, optional) }),
529
172
  delete: (required, optional = {}) => atStoreBoundary({ operation: () => store.delete(required, optional) }),
530
173
  messages: (required, optional = {}) => atStoreBoundary({ operation: () => store.messages(required, optional) }),
@@ -536,17 +179,4 @@ export function createSqlChatStore({ kernel, scope: inputScope, clock }, redacti
536
179
  pageMessages: (required, optional = {}) => atStoreBoundary({ operation: () => store.pageMessages(required, optional) }),
537
180
  };
538
181
  }
539
- function updateOwnedMessageConflict(oc) {
540
- return oc.column("id")
541
- .doUpdateSet((eb) => ({
542
- content: eb.ref("excluded.content"),
543
- events_json: eb.ref("excluded.events_json"),
544
- attachments_json: eb.ref("excluded.attachments_json"),
545
- run_id: eb.ref("excluded.run_id"),
546
- run_status: eb.ref("excluded.run_status"),
547
- started_at: eb.ref("excluded.started_at"),
548
- ended_at: eb.ref("excluded.ended_at"),
549
- }))
550
- .where((eb) => eb("ai_chat_messages.conversation_id", "=", eb.ref("excluded.conversation_id")));
551
- }
552
182
  //# sourceMappingURL=store.js.map
@@ -10,6 +10,7 @@ export type AiChatsTable = {
10
10
  created_at: number;
11
11
  updated_at: number;
12
12
  expires_at: number | null;
13
+ pinned_at: Generated<number | null>;
13
14
  };
14
15
  export type AiChatMessagesTable = {
15
16
  id: string;
@@ -33,4 +33,5 @@ export declare function createChatHistoryStore({ db, scope, clock }: {
33
33
  export declare function createChatHistoryMaintenance({ db }: {
34
34
  db: SqliteConnectionSource;
35
35
  }): ChatHistoryMaintenance;
36
+ export { createChatBulkDeletion } from '../sql/bulk-deletion.js';
36
37
  //# sourceMappingURL=index.d.ts.map
@@ -26,4 +26,5 @@ export function createChatHistoryStore({ db, scope, clock }, optional = {}) {
26
26
  export function createChatHistoryMaintenance({ db }) {
27
27
  return createSqliteChatMaintenance({ kernel: sqliteKernel({ source: db }) });
28
28
  }
29
+ export { createChatBulkDeletion } from '../sql/bulk-deletion.js';
29
30
  //# sourceMappingURL=index.js.map
@@ -30,7 +30,7 @@ import type { SqliteClient } from '@jini-ai/core/contracts/storage';
30
30
  * `expires_at IS NOT NULL`, so authenticated history is out of its reach by construction, not
31
31
  * by a predicate that could drift.
32
32
  */
33
- export declare const CHAT_HISTORY_DDL = "\nCREATE TABLE IF NOT EXISTS ai_chats (\n id TEXT PRIMARY KEY,\n scope_id TEXT NOT NULL,\n owner_kind TEXT NOT NULL CHECK (owner_kind IN ('user','guest')),\n owner_id TEXT NOT NULL,\n title TEXT,\n title_source TEXT NOT NULL DEFAULT 'fallback'\n CHECK (title_source IN ('fallback','generated','manual')),\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n expires_at INTEGER\n);\n\nCREATE INDEX IF NOT EXISTS idx_ai_chats_owner\n ON ai_chats(scope_id, owner_kind, owner_id, updated_at DESC);\n\nCREATE INDEX IF NOT EXISTS idx_ai_chats_expiry\n ON ai_chats(expires_at) WHERE expires_at IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS ai_chat_messages (\n id TEXT PRIMARY KEY,\n conversation_id TEXT NOT NULL REFERENCES ai_chats(id) ON DELETE CASCADE,\n role TEXT NOT NULL CHECK (role IN ('user','assistant')),\n content TEXT NOT NULL,\n agent_id TEXT,\n agent_name TEXT,\n events_json TEXT,\n attachments_json TEXT,\n run_id TEXT,\n run_status TEXT,\n position INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n ended_at INTEGER,\n UNIQUE (conversation_id, position)\n);\n\nCREATE INDEX IF NOT EXISTS idx_ai_chat_messages_order\n ON ai_chat_messages(conversation_id, position);\n\n-- Idle probes read only this covering index, never the overflowing event rows.\nCREATE INDEX IF NOT EXISTS idx_ai_chat_messages_active\n ON ai_chat_messages(role, run_status, id) WHERE run_status IN ('queued', 'running');\n";
33
+ export declare const CHAT_HISTORY_DDL = "\nCREATE TABLE IF NOT EXISTS ai_chats (\n id TEXT PRIMARY KEY,\n scope_id TEXT NOT NULL,\n owner_kind TEXT NOT NULL CHECK (owner_kind IN ('user','guest')),\n owner_id TEXT NOT NULL,\n title TEXT,\n title_source TEXT NOT NULL DEFAULT 'fallback'\n CHECK (title_source IN ('fallback','generated','manual')),\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n expires_at INTEGER,\n pinned_at INTEGER\n);\n\nCREATE INDEX IF NOT EXISTS idx_ai_chats_owner\n ON ai_chats(scope_id, owner_kind, owner_id, updated_at DESC);\n\nCREATE INDEX IF NOT EXISTS idx_ai_chats_owner_cleanup\n ON ai_chats(scope_id, owner_kind, owner_id, pinned_at, updated_at);\n\nCREATE INDEX IF NOT EXISTS idx_ai_chats_expiry\n ON ai_chats(expires_at) WHERE expires_at IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS ai_chat_messages (\n id TEXT PRIMARY KEY,\n conversation_id TEXT NOT NULL REFERENCES ai_chats(id) ON DELETE CASCADE,\n role TEXT NOT NULL CHECK (role IN ('user','assistant')),\n content TEXT NOT NULL,\n agent_id TEXT,\n agent_name TEXT,\n events_json TEXT,\n attachments_json TEXT,\n run_id TEXT,\n run_status TEXT,\n position INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n ended_at INTEGER,\n UNIQUE (conversation_id, position)\n);\n\nCREATE INDEX IF NOT EXISTS idx_ai_chat_messages_order\n ON ai_chat_messages(conversation_id, position);\n\n-- Idle probes read only this covering index, never the overflowing event rows.\nCREATE INDEX IF NOT EXISTS idx_ai_chat_messages_active\n ON ai_chat_messages(role, run_status, id) WHERE run_status IN ('queued', 'running');\n";
34
34
  /**
35
35
  * Creates the chat-history tables in the given database if they are absent.
36
36
  *
@@ -32,12 +32,16 @@ CREATE TABLE IF NOT EXISTS ai_chats (
32
32
  CHECK (title_source IN ('fallback','generated','manual')),
33
33
  created_at INTEGER NOT NULL,
34
34
  updated_at INTEGER NOT NULL,
35
- expires_at INTEGER
35
+ expires_at INTEGER,
36
+ pinned_at INTEGER
36
37
  );
37
38
 
38
39
  CREATE INDEX IF NOT EXISTS idx_ai_chats_owner
39
40
  ON ai_chats(scope_id, owner_kind, owner_id, updated_at DESC);
40
41
 
42
+ CREATE INDEX IF NOT EXISTS idx_ai_chats_owner_cleanup
43
+ ON ai_chats(scope_id, owner_kind, owner_id, pinned_at, updated_at);
44
+
41
45
  CREATE INDEX IF NOT EXISTS idx_ai_chats_expiry
42
46
  ON ai_chats(expires_at) WHERE expires_at IS NOT NULL;
43
47