@jini-ai/chat 0.7.3-next.2 → 0.7.3-next.4

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 (216) hide show
  1. package/README.md +49 -0
  2. package/dist/core/accepted-input.d.ts +1 -1
  3. package/dist/core/ag-ui/event-projection.d.ts +14 -69
  4. package/dist/core/ag-ui/event-projection.js +58 -133
  5. package/dist/core/ag-ui/event-reduction.d.ts +12 -2
  6. package/dist/core/ag-ui/event-reduction.js +35 -10
  7. package/dist/core/ag-ui/resume.d.ts +110 -0
  8. package/dist/core/ag-ui/resume.js +200 -0
  9. package/dist/core/ag-ui/run-input.d.ts +23 -0
  10. package/dist/core/ag-ui/run-input.js +45 -0
  11. package/dist/core/ag-ui/server.d.ts +69 -0
  12. package/dist/core/ag-ui/server.js +71 -0
  13. package/dist/core/agent-plugin-chat-state.js +13 -11
  14. package/dist/core/assistant-client/ag-ui-approval-relay.d.ts +113 -0
  15. package/dist/core/assistant-client/ag-ui-approval-relay.js +287 -0
  16. package/dist/core/assistant-client/ag-ui-fetch-agent.d.ts +25 -10
  17. package/dist/core/assistant-client/ag-ui-fetch-agent.js +25 -6
  18. package/dist/core/assistant-client/ag-ui-transport.d.ts +86 -3
  19. package/dist/core/assistant-client/ag-ui-transport.js +310 -80
  20. package/dist/core/assistant-client/browser-durable-subscription.d.ts +25 -0
  21. package/dist/core/assistant-client/browser-durable-subscription.js +78 -0
  22. package/dist/core/assistant-client/durable-run-subscription.js +141 -130
  23. package/dist/core/assistant-client/entry.d.ts +2 -1
  24. package/dist/core/assistant-client/entry.js +1 -0
  25. package/dist/core/assistant-client/transport-prompt.d.ts +94 -0
  26. package/dist/core/assistant-client/transport-prompt.js +180 -0
  27. package/dist/core/assistant-client/transport-run.d.ts +49 -0
  28. package/dist/core/assistant-client/transport-run.js +432 -0
  29. package/dist/core/assistant-client/transport-stream.d.ts +73 -0
  30. package/dist/core/assistant-client/transport-stream.js +128 -0
  31. package/dist/core/assistant-client/transport.d.ts +1 -1
  32. package/dist/core/assistant-client/transport.js +129 -835
  33. package/dist/core/assistant-content.d.ts +1 -17
  34. package/dist/core/assistant-content.js +16 -0
  35. package/dist/core/assistant-tool-metadata.d.ts +103 -0
  36. package/dist/core/assistant-tool-metadata.js +56 -0
  37. package/dist/core/checkpoint-interval.d.ts +1 -1
  38. package/dist/core/compact-events.d.ts +1 -1
  39. package/dist/core/durable-projection.d.ts +1 -1
  40. package/dist/core/durable-runs/continuation.d.ts +1 -1
  41. package/dist/core/durable-runs/ledger-contracts.d.ts +4 -1
  42. package/dist/core/durable-runs/ports.d.ts +2 -1
  43. package/dist/core/durable-runs/run-contracts.d.ts +1 -1
  44. package/dist/core/durable-runs/run-finalizer.d.ts +145 -0
  45. package/dist/core/durable-runs/run-finalizer.js +171 -0
  46. package/dist/core/events.d.ts +4 -82
  47. package/dist/core/events.js +2 -1
  48. package/dist/core/index.d.ts +4 -1
  49. package/dist/core/index.js +2 -1
  50. package/dist/core/messages.d.ts +1 -1
  51. package/dist/core/persistence/index.d.ts +1 -1
  52. package/dist/core/persistence/index.js +1 -1
  53. package/dist/core/question-form/normalize.d.ts +9 -3
  54. package/dist/core/question-form/normalize.js +20 -20
  55. package/dist/core/question-form/scan.js +15 -19
  56. package/dist/core/run-activity.d.ts +1 -1
  57. package/dist/core/run-events/entry.d.ts +11 -63
  58. package/dist/core/run-events/entry.js +12 -7
  59. package/dist/core/todos.d.ts +1 -1
  60. package/dist/core/todos.js +8 -0
  61. package/dist/core/tool-call-detail.d.ts +8 -1
  62. package/dist/core/tool-call-detail.js +35 -12
  63. package/dist/core/tool-events.d.ts +1 -1
  64. package/dist/core/tool-output.js +2 -6
  65. package/dist/core/tools.d.ts +2 -1
  66. package/dist/core/transport.d.ts +1 -1
  67. package/dist/core/turn-usage.d.ts +1 -1
  68. package/dist/core/util/parser.js +70 -69
  69. package/dist/embed-widget/browser/embed-send-bridge.d.ts +44 -0
  70. package/dist/embed-widget/browser/embed-send-bridge.js +60 -0
  71. package/dist/embed-widget/browser/frontend-invocation-handler.d.ts +39 -0
  72. package/dist/embed-widget/browser/frontend-invocation-handler.js +151 -0
  73. package/dist/embed-widget/browser/frontend-session-bridge.d.ts +28 -0
  74. package/dist/embed-widget/browser/frontend-session-bridge.js +201 -257
  75. package/dist/embed-widget/browser/lazy-loader.js +16 -12
  76. package/dist/embed-widget/browser/session-store.d.ts +19 -1
  77. package/dist/embed-widget/browser/session-store.js +48 -17
  78. package/dist/embed-widget/transports/fetch-sse.d.ts +1 -1
  79. package/dist/embed-widget/vanilla/index.js +131 -67
  80. package/dist/embed-widget/vanilla/state.js +53 -38
  81. package/dist/react/admin-execution/ai-agent-presentation.d.ts +35 -0
  82. package/dist/react/admin-execution/ai-agent-presentation.js +39 -0
  83. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.d.ts +22 -0
  84. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.js +25 -0
  85. package/dist/react/chat-cleanup/ChatCleanupPanel.d.ts +32 -0
  86. package/dist/react/chat-cleanup/ChatCleanupPanel.js +34 -0
  87. package/dist/react/chat-cleanup/chat-cleanup.hooks.d.ts +174 -0
  88. package/dist/react/chat-cleanup/chat-cleanup.hooks.js +83 -0
  89. package/dist/react/components/ChatCleanupDialog.d.ts +38 -0
  90. package/dist/react/components/ChatCleanupDialog.js +15 -0
  91. package/dist/react/components/ChatSettingsDialog.d.ts +3 -0
  92. package/dist/react/components/ChatSettingsDialog.js +3 -3
  93. package/dist/react/components/ConversationList.d.ts +19 -5
  94. package/dist/react/components/ConversationList.hooks.d.ts +1 -0
  95. package/dist/react/components/ConversationList.hooks.js +4 -2
  96. package/dist/react/components/ConversationList.js +66 -9
  97. package/dist/react/components/Icon.d.ts +1 -1
  98. package/dist/react/components/Icon.js +7 -0
  99. package/dist/react/components/Markdown.js +6 -6
  100. package/dist/react/components/MarkdownLink.d.ts +25 -0
  101. package/dist/react/components/MarkdownLink.js +17 -0
  102. package/dist/react/components/RoutedA2uiSurfaceCard.d.ts +80 -0
  103. package/dist/react/components/RoutedA2uiSurfaceCard.js +15 -0
  104. package/dist/react/components/ToolCard.d.ts +4 -2
  105. package/dist/react/components/ToolCard.js +46 -4
  106. package/dist/react/components/ToolCard.rules.d.ts +5 -2
  107. package/dist/react/components/ToolCard.rules.js +12 -5
  108. package/dist/react/components/mcp-ui-question-input.d.ts +1 -1
  109. package/dist/react/components/mcp-ui-surface-state.d.ts +3 -1
  110. package/dist/react/components/mcp-ui-surface-state.js +2 -2
  111. package/dist/react/components/own-link.d.ts +26 -0
  112. package/dist/react/components/own-link.js +36 -0
  113. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.d.ts +7 -0
  114. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.js +26 -0
  115. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.d.ts +12 -0
  116. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.js +60 -0
  117. package/dist/react/features/bridged-chat/index.d.ts +8 -0
  118. package/dist/react/features/bridged-chat/index.js +7 -0
  119. package/dist/react/features/bridged-chat/types.d.ts +49 -0
  120. package/dist/react/features/bridged-chat/types.js +2 -0
  121. package/dist/react/features/chat-pane/components/RuntimeDropUp.js +1 -1
  122. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.d.ts +6 -0
  123. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.js +101 -59
  124. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.d.ts +3 -0
  125. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.js +26 -16
  126. package/dist/react/features/chat-pane/model-options.d.ts +3 -1
  127. package/dist/react/features/chat-pane/model-options.js +3 -3
  128. package/dist/react/features/chat-pane/rules.js +4 -3
  129. package/dist/react/features/chat-pane/styles.d.ts +1 -1
  130. package/dist/react/features/chat-pane/styles.js +16 -0
  131. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.d.ts +10 -0
  132. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.js +19 -0
  133. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.d.ts +12 -0
  134. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.js +21 -0
  135. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.d.ts +13 -0
  136. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.js +9 -0
  137. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.d.ts +12 -0
  138. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.js +12 -0
  139. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.d.ts +7 -0
  140. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.js +43 -0
  141. package/dist/react/features/conversation-chat-pane/index.d.ts +9 -0
  142. package/dist/react/features/conversation-chat-pane/index.js +8 -0
  143. package/dist/react/features/conversation-chat-pane/rules.d.ts +25 -0
  144. package/dist/react/features/conversation-chat-pane/rules.js +29 -0
  145. package/dist/react/features/conversation-chat-pane/types.d.ts +139 -0
  146. package/dist/react/features/conversation-chat-pane/types.js +2 -0
  147. package/dist/react/features/conversations/conversation-controller.d.ts +16 -0
  148. package/dist/react/features/conversations/conversation-controller.js +280 -0
  149. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.d.ts +15 -0
  150. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.js +33 -0
  151. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.d.ts +16 -0
  152. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.js +36 -0
  153. package/dist/react/features/conversations/index.d.ts +9 -0
  154. package/dist/react/features/conversations/index.js +8 -0
  155. package/dist/react/features/conversations/types.d.ts +120 -0
  156. package/dist/react/features/conversations/types.js +2 -0
  157. package/dist/react/features/voice-input/space-hold-rules.d.ts +65 -0
  158. package/dist/react/features/voice-input/space-hold-rules.js +48 -0
  159. package/dist/react/hooks/testing/fake-transport.d.ts +1 -1
  160. package/dist/react/hooks/useAnsweredCards.d.ts +2 -1
  161. package/dist/react/hooks/useConversation.js +5 -2
  162. package/dist/react/hooks/useExtEventGroups.d.ts +1 -1
  163. package/dist/react/hooks/useRunActivity.d.ts +2 -1
  164. package/dist/react/hooks/useRunStream.d.ts +1 -1
  165. package/dist/react/hooks/useRunStream.js +1 -1
  166. package/dist/react/hooks/useSurfaceRecovery.js +3 -1
  167. package/dist/react/hooks/useToolTimeline.d.ts +2 -1
  168. package/dist/react/index.d.ts +5 -2
  169. package/dist/react/index.js +4 -2
  170. package/dist/react/message-blocks.d.ts +1 -48
  171. package/dist/react/message-blocks.js +47 -0
  172. package/dist/react/styles/chat-settings.css +42 -14
  173. package/dist/server/chat-cleanup-routes.d.ts +56 -0
  174. package/dist/server/chat-cleanup-routes.js +56 -0
  175. package/dist/server/durable-runs/recover.js +193 -171
  176. package/dist/server/run-finalizer/entry.js +133 -110
  177. package/dist/store/legacy/sqlite/conversations.js +29 -17
  178. package/dist/store/pglite/index.d.ts +1 -0
  179. package/dist/store/pglite/index.js +1 -0
  180. package/dist/store/ports.d.ts +12 -0
  181. package/dist/store/postgres/index.d.ts +1 -0
  182. package/dist/store/postgres/index.js +1 -0
  183. package/dist/store/runtime/attempt-base-retention.d.ts +57 -0
  184. package/dist/store/runtime/attempt-base-retention.js +103 -0
  185. package/dist/store/runtime/chat-maintenance.d.ts +16 -0
  186. package/dist/store/runtime/chat-maintenance.js +19 -0
  187. package/dist/store/runtime/chat-principal.d.ts +63 -0
  188. package/dist/store/runtime/chat-principal.js +39 -0
  189. package/dist/store/runtime/checkpoint-delta.d.ts +1 -1
  190. package/dist/store/runtime/durable-run-queries.d.ts +124 -0
  191. package/dist/store/runtime/durable-run-queries.js +122 -0
  192. package/dist/store/runtime/durable-run-store.d.ts +1 -1
  193. package/dist/store/runtime/durable-run-store.js +291 -343
  194. package/dist/store/runtime/entry.d.ts +3 -0
  195. package/dist/store/runtime/entry.js +3 -0
  196. package/dist/store/runtime/events-json.d.ts +1 -1
  197. package/dist/store/runtime/lazy-run-ledger.d.ts +19 -0
  198. package/dist/store/runtime/lazy-run-ledger.js +28 -0
  199. package/dist/store/runtime/run-ledger.d.ts +4 -1
  200. package/dist/store/runtime/run-ledger.js +256 -204
  201. package/dist/store/sql/bulk-deletion.d.ts +36 -0
  202. package/dist/store/sql/bulk-deletion.js +103 -0
  203. package/dist/store/sql/store-queries.d.ts +170 -0
  204. package/dist/store/sql/store-queries.js +212 -0
  205. package/dist/store/sql/store-rows.d.ts +106 -0
  206. package/dist/store/sql/store-rows.js +116 -0
  207. package/dist/store/sql/store-writes.d.ts +46 -0
  208. package/dist/store/sql/store-writes.js +161 -0
  209. package/dist/store/sql/store.d.ts +3 -16
  210. package/dist/store/sql/store.js +58 -428
  211. package/dist/store/sql/tables.d.ts +1 -0
  212. package/dist/store/sqlite/index.d.ts +1 -0
  213. package/dist/store/sqlite/index.js +1 -0
  214. package/dist/store/sqlite/schema.d.ts +1 -1
  215. package/dist/store/sqlite/schema.js +5 -1
  216. package/package.json +171 -20
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Pure row shapes, encoders and decoders for the owner-bound SQL chat store. Nothing here touches
3
+ * a kernel, a transaction or a clock: the transactional writers in `store-writes.ts` and the query
4
+ * builders in `store-queries.ts` import these, so encoding can change without moving a write
5
+ * across a transaction boundary.
6
+ */
7
+ import { sql } from 'kysely';
8
+ import { ChatStoreError } from '../errors.js';
9
+ export const MESSAGE_POSITION = 'm.position';
10
+ export const CONVERSATION_UPDATED_AT = 'c.updated_at';
11
+ /** UTF-8 byte ordinal ordering, identical on SQLite BINARY and PostgreSQL C collation. */
12
+ export function ordinalId({ dialect, column }, _optional = {}) {
13
+ return dialect === 'sqlite' ? sql `${sql.ref(column)} collate BINARY` : sql `${sql.ref(column)} collate "C"`;
14
+ }
15
+ /** The lock every position-assigning append to one conversation takes. */
16
+ export function conversationLockKey({ conversationId }, _optional = {}) {
17
+ return `chat-conversation:${conversationId}`;
18
+ }
19
+ export function toConversation(row) {
20
+ return {
21
+ id: row.id,
22
+ title: row.title,
23
+ titleSource: row.title_source,
24
+ ...(row.pinned_at === null ? {} : { pinned: true }),
25
+ // COUNT(*) never yields null; Number() also maps a driver's string/bigint count.
26
+ messageCount: Number(row.message_count),
27
+ createdAt: Number(row.created_at),
28
+ updatedAt: Number(row.updated_at),
29
+ ...(row.expires_at === null ? {} : { expiresAt: Number(row.expires_at) }),
30
+ };
31
+ }
32
+ /**
33
+ * A malformed JSON column yields `undefined` rather than throwing: one half-written `events_json`
34
+ * must not make the whole conversation unreadable (same rule as Jini's store).
35
+ */
36
+ function safeParse(value) {
37
+ try {
38
+ return JSON.parse(value);
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ /** A NULL (or empty) JSON column is absent; anything else goes through {@link safeParse}. */
45
+ export function parseJsonColumn({ value }, _optional = {}) {
46
+ return value ? safeParse(value) : undefined;
47
+ }
48
+ /** Serialize an optional JSON column: an absent or empty value is stored as SQL NULL. */
49
+ function encodeJsonColumn(value) {
50
+ return value ? JSON.stringify(value) : null;
51
+ }
52
+ /**
53
+ * The `ai_chat_messages` insert values for one message at a fixed position. `now` is only called
54
+ * when the message carries no `createdAt`, so a counting clock sees exactly the reads it always did.
55
+ */
56
+ export function encodeMessageRow({ message: m, conversationId, position, now }, _optional = {}) {
57
+ return {
58
+ id: m.id,
59
+ conversation_id: conversationId,
60
+ role: m.role,
61
+ content: m.content,
62
+ agent_id: m.agentId ?? null,
63
+ agent_name: m.agentName ?? null,
64
+ events_json: encodeJsonColumn(m.events),
65
+ attachments_json: encodeJsonColumn(m.attachments),
66
+ run_id: m.runId ?? null,
67
+ run_status: m.runStatus ?? null,
68
+ position,
69
+ created_at: m.createdAt ?? now(),
70
+ started_at: m.startedAt ?? null,
71
+ ended_at: m.endedAt ?? null,
72
+ };
73
+ }
74
+ /** Receipt-bearing user rows retain their public metadata while large assistant histories stay
75
+ * outside recovery/acceptance projections. Both dialects evaluate the same CASE expression. */
76
+ export function messageEventsColumn({ includeEvents }, _options = {}) {
77
+ if (includeEvents === 'user')
78
+ return sql `case when m.role = 'user' then m.events_json else null end`;
79
+ return includeEvents ? sql `m.events_json` : sql `null`;
80
+ }
81
+ /** Reject an unbounded or malformed history read before any query runs. */
82
+ export function assertHistoryReadBounds({ limit, fromPosition }) {
83
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
84
+ throw new ChatStoreError({ code: 'invalid-input' });
85
+ if (fromPosition !== undefined && (!Number.isSafeInteger(fromPosition) || fromPosition < 0)) {
86
+ throw new ChatStoreError({ code: 'invalid-input' });
87
+ }
88
+ }
89
+ /** Project one history row; `events` is present (possibly undefined) only when tool events were asked for. */
90
+ export function toHistoryMessage(row, { includeToolEvents }) {
91
+ return { id: row.id, role: row.role, content: row.content,
92
+ position: Number(row.position), createdAt: Number(row.created_at),
93
+ ...(includeToolEvents ? { events: parseJsonColumn({ value: row.events_json }) } : {}), };
94
+ }
95
+ /** @throws {ChatStoreError} `invalid-input` for an out-of-range limit or an over-long/non-string query. */
96
+ export function assertHistoryListInputs({ limit, query }, _optional = {}) {
97
+ if (!Number.isInteger(limit) || limit < 1 || limit > 50)
98
+ throw new ChatStoreError({ code: 'invalid-input' });
99
+ if (query !== undefined && (typeof query !== 'string' || query.length > 200)) {
100
+ throw new ChatStoreError({ code: 'invalid-input' });
101
+ }
102
+ }
103
+ export function updateOwnedMessageConflict(oc) {
104
+ return oc.column("id")
105
+ .doUpdateSet((eb) => ({
106
+ content: eb.ref("excluded.content"),
107
+ events_json: eb.ref("excluded.events_json"),
108
+ attachments_json: eb.ref("excluded.attachments_json"),
109
+ run_id: eb.ref("excluded.run_id"),
110
+ run_status: eb.ref("excluded.run_status"),
111
+ started_at: eb.ref("excluded.started_at"),
112
+ ended_at: eb.ref("excluded.ended_at"),
113
+ }))
114
+ .where((eb) => eb("ai_chat_messages.conversation_id", "=", eb.ref("excluded.conversation_id")));
115
+ }
116
+ //# sourceMappingURL=store-rows.js.map
@@ -0,0 +1,46 @@
1
+ import type { ChatMessage } from '../../core/messages.js';
2
+ import type { ChatConversation, ChatTitleSource, CreateChatConversationInput } from '../ports.js';
3
+ import { type SqlStoreContext } from './store-queries.js';
4
+ /** Insert one conversation for this scope; a duplicate ID is a `conflict`, any other failure propagates. */
5
+ export declare function createConversation({ ctx, input }: {
6
+ ctx: SqlStoreContext;
7
+ input: CreateChatConversationInput;
8
+ }): Promise<ChatConversation>;
9
+ /** Rename an owned conversation, then return its fresh projection (null when absent or foreign). */
10
+ export declare function renameConversation({ ctx, id, title, source }: {
11
+ ctx: SqlStoreContext;
12
+ id: string;
13
+ title: string;
14
+ source: ChatTitleSource;
15
+ }): Promise<ChatConversation | null>;
16
+ /**
17
+ * Rename and/or pin an owned conversation under its chat-slot lock, in one transaction, then
18
+ * return its fresh projection (null when absent or foreign).
19
+ */
20
+ export declare function updateConversation({ ctx, id, title, pinned, source }: {
21
+ ctx: SqlStoreContext;
22
+ id: string;
23
+ title?: string;
24
+ pinned?: boolean;
25
+ source: ChatTitleSource;
26
+ }): Promise<ChatConversation | null>;
27
+ /** Bump an owned conversation's activity time, optionally replacing its expiry. */
28
+ export declare function touchConversation({ ctx, id, options }: {
29
+ ctx: SqlStoreContext;
30
+ id: string;
31
+ options: {
32
+ readonly expiresAt?: number;
33
+ };
34
+ }): Promise<void>;
35
+ /** Delete an owned conversation; unknown and foreign IDs are no-ops. */
36
+ export declare function deleteConversation({ ctx, id }: {
37
+ ctx: SqlStoreContext;
38
+ id: string;
39
+ }): Promise<void>;
40
+ /** Writes and projects one message inside the borrowed transaction; null for absent/foreign IDs. */
41
+ export declare function writeMessage({ ctx, conversationId, message }: {
42
+ ctx: SqlStoreContext;
43
+ conversationId: string;
44
+ message: ChatMessage;
45
+ }): Promise<ChatMessage | null>;
46
+ //# sourceMappingURL=store-writes.d.ts.map
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Write-side statements of the owner-bound SQL chat store. Every statement runs through the
3
+ * injected {@link SqlStoreContext}. `writeMessage` owns exactly one kernel transaction; its
4
+ * steps are separate functions only so each stays small, they never open a transaction of their own.
5
+ */
6
+ import { isUniqueViolation } from '@jini-ai/core/contracts/storage';
7
+ import { withFolderReceipt } from '../../core/accepted-input.js';
8
+ import { ChatStoreError } from '../errors.js';
9
+ import { conversationLockKey, encodeMessageRow, updateOwnedMessageConflict } from './store-rows.js';
10
+ import { getConversation, ownedMessages } from './store-queries.js';
11
+ /** Insert one conversation for this scope; a duplicate ID is a `conflict`, any other failure propagates. */
12
+ export async function createConversation({ ctx, input }) {
13
+ const { scopeId, ownerKind, ownerId } = ctx.scope;
14
+ const ts = ctx.clock.nowMs();
15
+ try {
16
+ await ctx.run((db) => db
17
+ .insertInto("ai_chats")
18
+ .values({
19
+ id: input.id,
20
+ scope_id: scopeId,
21
+ owner_kind: ownerKind,
22
+ owner_id: ownerId,
23
+ title: input.title ?? null,
24
+ title_source: input.titleSource ?? "fallback",
25
+ created_at: ts,
26
+ updated_at: ts,
27
+ expires_at: input.expiresAt ?? null,
28
+ })
29
+ .execute());
30
+ }
31
+ catch (cause) {
32
+ if (isUniqueViolation({ err: cause }))
33
+ throw new ChatStoreError({ code: 'conflict' }, { cause });
34
+ throw cause;
35
+ }
36
+ const created = await getConversation({ ctx, id: input.id });
37
+ // Unreachable: the insert used this exact scope. Asserted so a future change to either
38
+ // statement fails loudly instead of returning a malformed conversation.
39
+ if (!created)
40
+ throw new Error(`ai_chats: created conversation ${input.id} was not readable in its own scope`);
41
+ return created;
42
+ }
43
+ /** Rename an owned conversation, then return its fresh projection (null when absent or foreign). */
44
+ export async function renameConversation({ ctx, id, title, source }) {
45
+ const { scopeId, ownerKind, ownerId } = ctx.scope;
46
+ // A generated title never overwrites a typed one: in the WHERE clause, so a concurrent
47
+ // rename cannot slip between a read and this write.
48
+ await ctx.run((db) => db
49
+ .updateTable("ai_chats")
50
+ .set({ title, title_source: source, updated_at: ctx.clock.nowMs() })
51
+ .where("id", "=", id)
52
+ .where("scope_id", "=", scopeId)
53
+ .where("owner_kind", "=", ownerKind)
54
+ .where("owner_id", "=", ownerId)
55
+ .$if(source === "generated", (qb) => qb.where("title_source", "<>", "manual"))
56
+ .execute());
57
+ return getConversation({ ctx, id });
58
+ }
59
+ /**
60
+ * Rename and/or pin an owned conversation under its chat-slot lock, in one transaction, then
61
+ * return its fresh projection (null when absent or foreign).
62
+ */
63
+ export async function updateConversation({ ctx, id, title, pinned, source }) {
64
+ const { scopeId, ownerKind, ownerId } = ctx.scope;
65
+ return ctx.kernel.transaction(async () => {
66
+ await ctx.kernel.lockKey(`chat-slot:${id}`);
67
+ if (title !== undefined)
68
+ await renameConversation({ ctx, id, title, source });
69
+ if (pinned !== undefined)
70
+ await ctx.run(db => db.updateTable("ai_chats")
71
+ .set({ pinned_at: pinned ? ctx.clock.nowMs() : null })
72
+ .where("id", "=", id).where("scope_id", "=", scopeId)
73
+ .where("owner_kind", "=", ownerKind).where("owner_id", "=", ownerId).execute());
74
+ return getConversation({ ctx, id });
75
+ });
76
+ }
77
+ /** Bump an owned conversation's activity time, optionally replacing its expiry. */
78
+ export async function touchConversation({ ctx, id, options }) {
79
+ const { scopeId, ownerKind, ownerId } = ctx.scope;
80
+ const ts = ctx.clock.nowMs();
81
+ await ctx.run((db) => db
82
+ .updateTable("ai_chats")
83
+ .set(options?.expiresAt === undefined ? { updated_at: ts } : { updated_at: ts, expires_at: options.expiresAt })
84
+ .where("id", "=", id)
85
+ .where("scope_id", "=", scopeId)
86
+ .where("owner_kind", "=", ownerKind)
87
+ .where("owner_id", "=", ownerId)
88
+ .execute());
89
+ }
90
+ /** Delete an owned conversation; unknown and foreign IDs are no-ops. */
91
+ export async function deleteConversation({ ctx, id }) {
92
+ const { scopeId, ownerKind, ownerId } = ctx.scope;
93
+ // Messages, agent sessions and tool approvals go with it through `ON DELETE CASCADE`.
94
+ await ctx.run((db) => db
95
+ .deleteFrom("ai_chats")
96
+ .where("id", "=", id)
97
+ .where("scope_id", "=", scopeId)
98
+ .where("owner_kind", "=", ownerKind)
99
+ .where("owner_id", "=", ownerId)
100
+ .execute());
101
+ }
102
+ /** Whether this scope owns `conversationId`; a foreign ID is indistinguishable from a missing one. */
103
+ async function ownsConversation({ ctx, conversationId }) {
104
+ const { scopeId, ownerKind, ownerId } = ctx.scope;
105
+ const owned = await ctx.run((db) => db
106
+ .selectFrom("ai_chats")
107
+ .select("id")
108
+ .where("id", "=", conversationId)
109
+ .where("scope_id", "=", scopeId)
110
+ .where("owner_kind", "=", ownerKind)
111
+ .where("owner_id", "=", ownerId)
112
+ .executeTakeFirst());
113
+ return Boolean(owned);
114
+ }
115
+ async function nextPosition({ ctx, conversationId }) {
116
+ const row = await ctx.run((db) => db
117
+ .selectFrom("ai_chat_messages")
118
+ .select((eb) => eb.fn.max("position").as("max"))
119
+ .where("conversation_id", "=", conversationId)
120
+ .executeTakeFirst());
121
+ return row?.max === null || row?.max === undefined ? 0 : Number(row.max) + 1;
122
+ }
123
+ /** A rewritten message keeps its stored position; a new one is appended after the current maximum. */
124
+ async function messagePosition({ ctx, conversationId, messageId }) {
125
+ const existing = await ctx.run((db) => db
126
+ .selectFrom("ai_chat_messages")
127
+ .select("position")
128
+ .where("id", "=", messageId)
129
+ .where("conversation_id", "=", conversationId)
130
+ .executeTakeFirst());
131
+ return existing ? Number(existing.position) : nextPosition({ ctx, conversationId });
132
+ }
133
+ /** Insert-or-update the encoded message row. */
134
+ async function upsertMessageRow({ ctx, conversationId, message, position }) {
135
+ const values = encodeMessageRow({ message, conversationId, position, now: () => ctx.clock.nowMs() });
136
+ // The conflict target is `id`, the GLOBAL key: the `where` keeps an id that already lives in
137
+ // another conversation from updating THAT row (the contract's "colliding id to its OWN chat" case).
138
+ await ctx.run((db) => db.insertInto("ai_chat_messages").values(values).onConflict(updateOwnedMessageConflict).execute());
139
+ }
140
+ /** Every step of one message write, in order, on the ambient transaction and under the conversation lock. */
141
+ async function writeMessageSteps({ ctx, conversationId, message }) {
142
+ await ctx.kernel.lockKey(conversationLockKey({ conversationId }));
143
+ if (!(await ownsConversation({ ctx, conversationId })))
144
+ return null;
145
+ const position = await messagePosition({ ctx, conversationId, messageId: message.id });
146
+ await upsertMessageRow({ ctx, conversationId, message, position });
147
+ // A new message is activity: the list orders by `updated_at`.
148
+ await ctx.run((db) => db.updateTable("ai_chats").set({ updated_at: ctx.clock.nowMs() }).where("id", "=", conversationId).execute());
149
+ // Re-read only the written row, while still in the same transaction and conversation lock.
150
+ const saved = await ctx.run(db => ownedMessages({ ctx, db, conversationId }).where('m.id', '=', message.id).executeTakeFirst());
151
+ return saved ?? null;
152
+ }
153
+ /** Writes and projects one message inside the borrowed transaction; null for absent/foreign IDs. */
154
+ export function writeMessage({ ctx, conversationId, message }) {
155
+ const m = withFolderReceipt({ message });
156
+ return ctx.kernel.transaction(async () => {
157
+ const saved = await writeMessageSteps({ ctx, conversationId, message: m });
158
+ return saved ? ctx.toMessage(saved) : null;
159
+ });
160
+ }
161
+ //# sourceMappingURL=store-writes.js.map
@@ -6,27 +6,14 @@
6
6
  * cannot serialize two appends as SQLite BEGIN IMMEDIATE does. The unique conversation/position
7
7
  * constraint remains the backstop, and nested appends join the host's existing transaction.
8
8
  */
9
- import { type Kysely } from 'kysely';
9
+ import type { Kysely } from 'kysely';
10
10
  import type { Clock } from '@jini-ai/core/primitives';
11
- import { type StorageKernel } from '@jini-ai/core/contracts/storage';
11
+ import type { StorageKernel } from '@jini-ai/core/contracts/storage';
12
12
  import { type UserTextRedactionOptions } from '../../core/user-text-redaction.js';
13
13
  import type { ChatMessage } from '../../core/messages.js';
14
14
  import type { ChatStore, ChatOwnerScope } from '../ports.js';
15
15
  import type { ChatDatabase } from './tables.js';
16
- interface MessageRow {
17
- id: string;
18
- role: string;
19
- content: string;
20
- agent_id: string | null;
21
- agent_name: string | null;
22
- events_json: string | null;
23
- attachments_json: string | null;
24
- run_id: string | null;
25
- run_status: string | null;
26
- created_at: number;
27
- started_at: number | null;
28
- ended_at: number | null;
29
- }
16
+ import { type MessageRow } from './store-rows.js';
30
17
  /** Project only existing ai_* fields: resumable and lastRunEventId belong to run state. */
31
18
  export declare function toMessage(row: MessageRow): ChatMessage;
32
19
  type RawMessageRow = MessageRow & {