@jini-ai/chat 0.3.11 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +152 -6
  3. package/dist/core/ag-ui/entry.d.ts +53 -0
  4. package/dist/core/ag-ui/entry.js +135 -0
  5. package/dist/core/agentic/chat-capabilities.d.ts +1 -1
  6. package/dist/core/agentic/index.d.ts +1 -1
  7. package/dist/core/agentic/index.js +1 -1
  8. package/dist/core/assistant-content.d.ts +6 -2
  9. package/dist/core/assistant-content.js +2 -2
  10. package/dist/core/compact-events.d.ts +3 -1
  11. package/dist/core/compact-events.js +1 -1
  12. package/dist/core/events.d.ts +1 -1
  13. package/dist/core/events.js +1 -1
  14. package/dist/core/index.d.ts +3 -3
  15. package/dist/core/index.js +3 -3
  16. package/dist/core/messages.d.ts +4 -2
  17. package/dist/core/messages.js +2 -2
  18. package/dist/core/partial-json.d.ts +6 -2
  19. package/dist/core/partial-json.js +3 -3
  20. package/dist/core/persistence/index.d.ts +1 -1
  21. package/dist/core/persistence/index.js +1 -1
  22. package/dist/core/persistence/ports.d.ts +2 -123
  23. package/dist/core/persistence/title.d.ts +3 -1
  24. package/dist/core/persistence/title.js +1 -1
  25. package/dist/core/question-form/format.d.ts +16 -7
  26. package/dist/core/question-form/format.js +3 -3
  27. package/dist/core/question-form/normalize.d.ts +7 -2
  28. package/dist/core/question-form/normalize.js +5 -5
  29. package/dist/core/question-form/scan.d.ts +18 -6
  30. package/dist/core/question-form/scan.js +14 -14
  31. package/dist/core/run-activity.d.ts +16 -4
  32. package/dist/core/run-activity.js +11 -11
  33. package/dist/core/run-events/entry.d.ts +121 -0
  34. package/dist/core/run-events/entry.js +290 -0
  35. package/dist/core/todos.d.ts +20 -8
  36. package/dist/core/todos.js +11 -11
  37. package/dist/core/tool-events.d.ts +3 -1
  38. package/dist/core/tool-events.js +1 -1
  39. package/dist/core/tool-output.d.ts +3 -1
  40. package/dist/core/tool-output.js +1 -1
  41. package/dist/core/tools.d.ts +14 -3
  42. package/dist/core/tools.js +3 -3
  43. package/dist/core/transcript.d.ts +13 -5
  44. package/dist/core/transcript.js +5 -5
  45. package/dist/core/util/manifest.d.ts +9 -3
  46. package/dist/core/util/manifest.js +3 -3
  47. package/dist/core/util/markdown-context.d.ts +11 -3
  48. package/dist/core/util/markdown-context.js +3 -3
  49. package/dist/core/util/markup-attributes.d.ts +3 -1
  50. package/dist/core/util/markup-attributes.js +1 -1
  51. package/dist/core/util/parser.d.ts +9 -5
  52. package/dist/core/util/parser.js +13 -13
  53. package/dist/core/util/recover.d.ts +6 -2
  54. package/dist/core/util/recover.js +6 -6
  55. package/dist/core/util/strip.d.ts +19 -5
  56. package/dist/core/util/strip.js +17 -17
  57. package/dist/core/util/validate.d.ts +3 -1
  58. package/dist/core/util/validate.js +1 -1
  59. package/dist/embed-widget/browser/page-actions.d.ts +121 -0
  60. package/dist/embed-widget/browser/page-actions.js +113 -0
  61. package/dist/embed-widget/browser/session-store.d.ts +44 -0
  62. package/dist/embed-widget/browser/session-store.js +103 -0
  63. package/dist/embed-widget/react/embed.d.ts +45 -0
  64. package/dist/embed-widget/react/embed.js +87 -0
  65. package/dist/embed-widget/react/header.d.ts +21 -0
  66. package/dist/embed-widget/react/header.js +18 -0
  67. package/dist/embed-widget/transports/fetch-sse.d.ts +75 -0
  68. package/dist/embed-widget/transports/fetch-sse.js +175 -0
  69. package/dist/react/agent-bridge/frontend-session-bridge.d.ts +15 -3
  70. package/dist/react/agent-bridge/frontend-session-bridge.js +13 -6
  71. package/dist/react/artifact-types.d.ts +3 -3
  72. package/dist/react/artifact-types.js +3 -3
  73. package/dist/react/components/A2uiSurfaceCard.js +34 -13
  74. package/dist/react/components/AttachmentPreviewModal.hooks.d.ts +7 -2
  75. package/dist/react/components/AttachmentPreviewModal.hooks.js +5 -5
  76. package/dist/react/components/AttachmentPreviewModal.js +2 -2
  77. package/dist/react/components/AttachmentTray.d.ts +3 -1
  78. package/dist/react/components/AttachmentTray.js +2 -2
  79. package/dist/react/components/ChatFab.js +1 -1
  80. package/dist/react/components/Composer.js +9 -9
  81. package/dist/react/components/ConversationList.js +1 -1
  82. package/dist/react/components/McpUiSurfaceCard.d.ts +4 -2
  83. package/dist/react/components/McpUiSurfaceCard.js +5 -5
  84. package/dist/react/components/MessageList.js +1 -1
  85. package/dist/react/components/MessageRow.js +9 -9
  86. package/dist/react/components/QuestionForm.js +5 -5
  87. package/dist/react/components/ToolCard.js +9 -9
  88. package/dist/react/components/composer-discovery.d.ts +29 -8
  89. package/dist/react/components/composer-discovery.js +10 -10
  90. package/dist/react/ext-event-renderer-registry.d.ts +15 -5
  91. package/dist/react/ext-event-renderer-registry.js +4 -4
  92. package/dist/react/features/chat-pane/components/AgentRuntimePicker.d.ts +3 -1
  93. package/dist/react/features/chat-pane/components/AgentRuntimePicker.js +3 -3
  94. package/dist/react/features/chat-pane/components/ChatPane.js +43 -43
  95. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.d.ts +4 -1
  96. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.js +5 -35
  97. package/dist/react/features/chat-pane/create-mcp-ui-tool-caller.d.ts +5 -2
  98. package/dist/react/features/chat-pane/create-mcp-ui-tool-caller.js +1 -1
  99. package/dist/react/features/chat-pane/hooks/useAgentRuntimePicker.hooks.d.ts +38 -10
  100. package/dist/react/features/chat-pane/hooks/useAgentRuntimePicker.hooks.js +15 -15
  101. package/dist/react/features/chat-pane/hooks/useChatPane.hooks.js +31 -31
  102. package/dist/react/features/chat-pane/hooks/useChatPaneAgentControl.hooks.d.ts +3 -1
  103. package/dist/react/features/chat-pane/hooks/useChatPaneAgentControl.hooks.js +3 -3
  104. package/dist/react/features/chat-pane/hooks/useChatPaneComposerPlaceholder.hooks.d.ts +4 -1
  105. package/dist/react/features/chat-pane/hooks/useChatPaneComposerPlaceholder.hooks.js +1 -1
  106. package/dist/react/features/chat-pane/hooks/useChatPaneRuntimeInventory.hooks.js +30 -30
  107. package/dist/react/features/chat-pane/hooks/useChatPaneWorkingDirectory.hooks.js +57 -57
  108. package/dist/react/features/chat-pane/rules.d.ts +13 -4
  109. package/dist/react/features/chat-pane/rules.js +5 -5
  110. package/dist/react/features/chat-pane/types.d.ts +1 -1
  111. package/dist/react/hooks/attachment-preview-cache.d.ts +7 -2
  112. package/dist/react/hooks/attachment-preview-cache.js +2 -2
  113. package/dist/react/hooks/composer-draft-cache.d.ts +17 -5
  114. package/dist/react/hooks/composer-draft-cache.js +6 -6
  115. package/dist/react/hooks/useArtifactStream.d.ts +5 -1
  116. package/dist/react/hooks/useArtifactStream.js +3 -3
  117. package/dist/react/hooks/useChatFabDrag.d.ts +9 -4
  118. package/dist/react/hooks/useChatFabDrag.js +4 -4
  119. package/dist/react/hooks/useComposer.js +8 -8
  120. package/dist/react/hooks/useConversation.js +56 -4
  121. package/dist/react/hooks/useExtEventGroups.d.ts +5 -1
  122. package/dist/react/hooks/useExtEventGroups.js +1 -1
  123. package/dist/react/hooks/useLatestOperation.d.ts +8 -3
  124. package/dist/react/hooks/useLatestOperation.js +4 -4
  125. package/dist/react/hooks/usePinnedTodos.d.ts +3 -1
  126. package/dist/react/hooks/usePinnedTodos.js +3 -3
  127. package/dist/react/hooks/useQuestionForms.d.ts +7 -2
  128. package/dist/react/hooks/useQuestionForms.js +7 -7
  129. package/dist/react/hooks/useRunActivity.d.ts +6 -1
  130. package/dist/react/hooks/useRunActivity.js +3 -3
  131. package/dist/react/hooks/useRunStream.d.ts +3 -1
  132. package/dist/react/hooks/useRunStream.js +1 -1
  133. package/dist/react/hooks/useToolTimeline.d.ts +3 -1
  134. package/dist/react/hooks/useToolTimeline.js +3 -3
  135. package/dist/react/index.d.ts +4 -4
  136. package/dist/react/index.js +6 -6
  137. package/dist/react/message-blocks.d.ts +10 -4
  138. package/dist/react/message-blocks.js +2 -2
  139. package/dist/react/styles/reference.css +3 -3
  140. package/dist/react/tool-renderer-registry.d.ts +8 -3
  141. package/dist/react/tool-renderer-registry.js +3 -3
  142. package/dist/react/util/defined-props.d.ts +3 -1
  143. package/dist/react/util/defined-props.js +1 -1
  144. package/dist/server/run-finalizer/entry.d.ts +47 -0
  145. package/dist/server/run-finalizer/entry.js +156 -0
  146. package/dist/server/run-finalizer/ports.d.ts +52 -0
  147. package/dist/store/contracts/index.d.ts +5 -0
  148. package/dist/store/contracts/index.js +5 -0
  149. package/dist/store/errors.d.ts +12 -0
  150. package/dist/store/errors.js +18 -0
  151. package/dist/store/index.d.ts +4 -0
  152. package/dist/store/index.js +2 -0
  153. package/dist/store/legacy/index.d.ts +3 -0
  154. package/dist/store/legacy/index.js +2 -0
  155. package/dist/store/legacy/sqlite/conversations.d.ts +129 -0
  156. package/dist/store/legacy/sqlite/conversations.js +274 -0
  157. package/dist/store/legacy/sqlite/index.d.ts +6 -0
  158. package/dist/store/legacy/sqlite/index.js +5 -0
  159. package/dist/store/legacy/sqlite/messages.d.ts +156 -0
  160. package/dist/store/legacy/sqlite/messages.js +246 -0
  161. package/dist/store/legacy/sqlite/schema.d.ts +3 -0
  162. package/dist/store/legacy/sqlite/schema.js +40 -0
  163. package/dist/store/pglite/index.d.ts +21 -0
  164. package/dist/store/pglite/index.js +17 -0
  165. package/dist/store/ports.d.ts +121 -0
  166. package/dist/store/ports.js +2 -0
  167. package/dist/store/postgres/index.d.ts +21 -0
  168. package/dist/store/postgres/index.js +17 -0
  169. package/dist/store/sql/boundary.d.ts +28 -0
  170. package/dist/store/sql/boundary.js +32 -0
  171. package/dist/store/sql/cursor.d.ts +24 -0
  172. package/dist/store/sql/cursor.js +49 -0
  173. package/dist/store/sql/maintenance.d.ts +9 -0
  174. package/dist/store/sql/maintenance.js +16 -0
  175. package/dist/store/sql/store.d.ts +22 -0
  176. package/dist/store/sql/store.js +340 -0
  177. package/dist/store/sql/tables.d.ts +34 -0
  178. package/dist/store/sql/tables.js +2 -0
  179. package/dist/store/sqlite/index.d.ts +36 -0
  180. package/dist/store/sqlite/index.js +29 -0
  181. package/dist/store/sqlite/schema.d.ts +49 -0
  182. package/dist/store/sqlite/schema.js +80 -0
  183. package/package.json +211 -14
  184. package/dist/react/features/model-picker/components/CredentialStatusBadge.d.ts +0 -7
  185. package/dist/react/features/model-picker/components/CredentialStatusBadge.js +0 -20
  186. package/dist/react/features/model-picker/components/ModelPicker.d.ts +0 -9
  187. package/dist/react/features/model-picker/components/ModelPicker.js +0 -34
  188. package/dist/react/features/model-picker/constants.d.ts +0 -6
  189. package/dist/react/features/model-picker/constants.js +0 -9
  190. package/dist/react/features/model-picker/dependencies.d.ts +0 -11
  191. package/dist/react/features/model-picker/dependencies.js +0 -10
  192. package/dist/react/features/model-picker/hooks/useModelPicker.hooks.d.ts +0 -27
  193. package/dist/react/features/model-picker/hooks/useModelPicker.hooks.js +0 -62
  194. package/dist/react/features/model-picker/index.d.ts +0 -32
  195. package/dist/react/features/model-picker/index.js +0 -29
  196. package/dist/react/features/model-picker/ports.d.ts +0 -11
  197. package/dist/react/features/model-picker/rules.d.ts +0 -26
  198. package/dist/react/features/model-picker/rules.js +0 -84
  199. package/dist/react/features/model-picker/types.d.ts +0 -38
  200. package/dist/react/features/model-picker/types.js +0 -2
  201. package/dist/react/poc-mcp-ui-official/PocMcpUiCard.d.ts +0 -9
  202. package/dist/react/poc-mcp-ui-official/PocMcpUiCard.js +0 -29
  203. package/dist/react/poc-mcp-ui-official/create-poc-resource.d.ts +0 -30
  204. package/dist/react/poc-mcp-ui-official/create-poc-resource.js +0 -44
  205. /package/dist/{react/features/model-picker → server/run-finalizer}/ports.js +0 -0
@@ -0,0 +1,156 @@
1
+ import { isTerminalRunStatus } from '../../core/messages.js';
2
+ import { readSseFrames, runContentFromEvents, runEventsForSave, runInterruptedNotice, translateRunFrame } from '../../core/run-events/entry.js';
3
+ /** Follow replayable run streams and save through atomic host ledger operations.
4
+ * The host retains authorization, owner scope, kernel transactions, boot reconciliation, HTTP
5
+ * credentials and excluded run-ID prefixes. Replay starts at zero; error-before-success and
6
+ * reconnect exhaustion must not falsely settle a run. Checkpoints are throttled with a trailing
7
+ * write, and checkpoint/settle atomically reject other runs or terminal rows: first terminal wins.
8
+ * Frame vocabulary, paragraph boundaries and compaction are shared with the run-event reducer.
9
+ * Non-success bodies are cancelled and progress scheduling stops at completion. Real database
10
+ * restart/race coverage remains a host responsibility; this factory never opens storage. */
11
+ export function createAssistantRunFinalizer(args, options = {}) {
12
+ const { daemon, scheduler } = args;
13
+ const now = () => args.clock.nowMs();
14
+ const reconnectDelayMs = options.reconnectDelayMs ?? 2_000;
15
+ const maxReconnects = options.maxReconnects ?? 30;
16
+ const checkpointIntervalMs = options.checkpointIntervalMs ?? 1_000;
17
+ // Diagnostics must not change run/checkpoint behavior, even when the host callback throws.
18
+ function reportError(input) {
19
+ try {
20
+ args.onError(input);
21
+ }
22
+ catch { /* The host owns reporting failures. */ }
23
+ }
24
+ const active = new Map();
25
+ async function settle(watch, status, events) {
26
+ watch.terminal = true;
27
+ if (watch.trailing)
28
+ scheduler.cancel({ handle: watch.trailing.handle });
29
+ watch.trailing = undefined;
30
+ await args.ledger.settle({
31
+ conversationId: watch.conversationId,
32
+ messageId: watch.messageId,
33
+ runId: watch.runId,
34
+ status,
35
+ content: runContentFromEvents({ events }),
36
+ events: runEventsForSave({ events }),
37
+ endedAt: now(),
38
+ });
39
+ }
40
+ function settleInterrupted(watch) {
41
+ return settle(watch, "canceled", [...watch.events, runInterruptedNotice({ notice: args.notices.interrupted })]);
42
+ }
43
+ // Coalesce one pending write and one trailing timer. Never block frame consumption on storage.
44
+ // Growth-only checkpointing avoids shrinking a saved answer during replay from event zero.
45
+ async function checkpoint(watch) {
46
+ if (watch.terminal || watch.checkpointPending)
47
+ return;
48
+ if (watch.events.length <= watch.checkpointedEvents)
49
+ return;
50
+ const wait = checkpointIntervalMs - (now() - watch.checkpointedAt);
51
+ if (wait > 0) {
52
+ if (!watch.trailing) {
53
+ watch.trailing = { handle: scheduler.schedule({ task: () => {
54
+ watch.trailing = undefined;
55
+ void checkpoint(watch);
56
+ }, delayMs: wait }) };
57
+ }
58
+ return;
59
+ }
60
+ if (watch.trailing)
61
+ scheduler.cancel({ handle: watch.trailing.handle });
62
+ watch.trailing = undefined;
63
+ watch.checkpointedEvents = watch.events.length;
64
+ watch.checkpointedAt = now();
65
+ watch.checkpointPending = true;
66
+ await args.ledger
67
+ .checkpoint({
68
+ conversationId: watch.conversationId,
69
+ messageId: watch.messageId,
70
+ runId: watch.runId,
71
+ content: runContentFromEvents({ events: watch.events }),
72
+ events: runEventsForSave({ events: watch.events }),
73
+ })
74
+ .catch((error) => reportError({ operation: "checkpoint", runId: watch.runId, error }))
75
+ .finally(() => {
76
+ watch.checkpointPending = false;
77
+ void checkpoint(watch);
78
+ });
79
+ }
80
+ async function readStream(watch) {
81
+ const response = await daemon.openEvents({ runId: watch.runId, principalId: watch.principalId });
82
+ if (response.status === 404 || !response.ok || !response.body) {
83
+ await response.body?.cancel().catch(() => undefined);
84
+ return response.status === 404 ? { kind: "gone" } : { kind: "dropped" };
85
+ }
86
+ // Each connection replays the complete history, rather than appending duplicate deltas.
87
+ watch.events = [];
88
+ watch.failed = false;
89
+ for await (const frame of readSseFrames({ body: response.body })) {
90
+ const outcome = translateRunFrame({ kind: frame.event, raw: frame.data, notices: args.notices });
91
+ watch.events.push(...outcome.events);
92
+ if (outcome.error)
93
+ watch.failed = true;
94
+ if (outcome.terminal) {
95
+ watch.terminal = true;
96
+ return { kind: "ended", status: watch.failed && outcome.terminal === "succeeded" ? "failed" : outcome.terminal };
97
+ }
98
+ void checkpoint(watch);
99
+ }
100
+ return { kind: "dropped" };
101
+ }
102
+ async function follow(watch) {
103
+ for (let attempt = 0; attempt <= maxReconnects; attempt += 1) {
104
+ const result = await readStream(watch).catch(() => ({ kind: "dropped" }));
105
+ if (result.kind === "ended")
106
+ return settle(watch, result.status, watch.events);
107
+ if (result.kind === "gone")
108
+ return settleInterrupted(watch);
109
+ if ((await daemon.runStatus({ runId: watch.runId, principalId: watch.principalId })) === 404)
110
+ return settleInterrupted(watch);
111
+ await scheduler.sleep({ delayMs: reconnectDelayMs });
112
+ }
113
+ // Exhaustion alone is not evidence of a terminal run; the host can reattach or repair at boot.
114
+ }
115
+ return {
116
+ watch({ principalId, conversationId, message }) {
117
+ const runId = message.runId;
118
+ if (message.role !== "assistant" || !runId || !args.runIdClassifier.isDaemonRunId({ runId }))
119
+ return;
120
+ if (message.runStatus === undefined || isTerminalRunStatus({ status: message.runStatus }))
121
+ return;
122
+ if (active.has(runId))
123
+ return;
124
+ const watch = {
125
+ principalId,
126
+ conversationId,
127
+ messageId: message.id,
128
+ runId,
129
+ events: [],
130
+ failed: false,
131
+ checkpointedEvents: 0,
132
+ checkpointedAt: Number.NEGATIVE_INFINITY,
133
+ checkpointPending: false,
134
+ terminal: false,
135
+ };
136
+ const done = follow(watch)
137
+ .catch((error) => {
138
+ reportError({ operation: "watch", runId, error });
139
+ })
140
+ .finally(() => {
141
+ watch.terminal = true;
142
+ if (watch.trailing)
143
+ scheduler.cancel({ handle: watch.trailing.handle });
144
+ watch.trailing = undefined;
145
+ active.delete(runId);
146
+ });
147
+ active.set(runId, { watch, done });
148
+ },
149
+ async idle(_args) {
150
+ while (active.size > 0)
151
+ await Promise.all([...active.values()].map((entry) => entry.done));
152
+ },
153
+ activeCount: (_args) => active.size,
154
+ };
155
+ }
156
+ //# sourceMappingURL=entry.js.map
@@ -0,0 +1,52 @@
1
+ import type { AgentEvent } from '../../core/events.js';
2
+ import type { ChatRunStatus } from '../../core/messages.js';
3
+ /** Exactly which run owns the row; the host binds authorization and storage scope. */
4
+ export interface RunRef {
5
+ readonly conversationId: string;
6
+ readonly messageId: string;
7
+ readonly runId: string;
8
+ }
9
+ export interface RunProgress extends RunRef {
10
+ readonly content: string;
11
+ readonly events: readonly AgentEvent[];
12
+ }
13
+ export interface RunSettlement extends RunProgress {
14
+ readonly status: Extract<ChatRunStatus, 'succeeded' | 'failed' | 'canceled'>;
15
+ readonly endedAt: number;
16
+ }
17
+ /** Storage contract only. Both methods must atomically reject a different run or terminal row.
18
+ * First terminal write wins; a late checkpoint cannot reopen or replace that row. */
19
+ export interface RunLedger {
20
+ checkpoint(args: RunProgress): Promise<boolean>;
21
+ settle(args: RunSettlement): Promise<boolean>;
22
+ }
23
+ /** Host adapter owns URL, auth, headers and transport timeout policy. Events replay from zero. */
24
+ export interface RunDaemonClient {
25
+ openEvents(args: {
26
+ runId: string;
27
+ principalId: string;
28
+ }): Promise<Response>;
29
+ runStatus(args: {
30
+ runId: string;
31
+ principalId: string;
32
+ }): Promise<number | null>;
33
+ }
34
+ /** Scheduling returns an opaque handle; a host Node adapter can unref its timer here. */
35
+ export interface Scheduler {
36
+ schedule(args: {
37
+ task: () => void;
38
+ delayMs: number;
39
+ }): unknown;
40
+ cancel(args: {
41
+ handle: unknown;
42
+ }): void;
43
+ sleep(args: {
44
+ delayMs: number;
45
+ }): Promise<void>;
46
+ }
47
+ export interface RunIdClassifier {
48
+ isDaemonRunId(args: {
49
+ runId: string;
50
+ }): boolean;
51
+ }
52
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1,5 @@
1
+ /** Closed metadata directory for the public neutral entry. Its full source closure is
2
+ * verified by store/__tests__/import-isolation.test.ts and the packed Node consumer.
3
+ */
4
+ export * from '@jini-ai/chat/store';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ /** Closed metadata directory for the public neutral entry. Its full source closure is
2
+ * verified by store/__tests__/import-isolation.test.ts and the packed Node consumer.
3
+ */
4
+ export * from '@jini-ai/chat/store';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ import type { ChatStoreErrorCode } from './ports.js';
2
+ /** Stable public errors; messages never expose owner IDs, cursors or driver details.
3
+ * @example new ChatStoreError({ code: 'conflict' }, { cause: originalError })
4
+ */
5
+ export declare class ChatStoreError extends Error {
6
+ readonly name: "ChatStoreError";
7
+ readonly code: ChatStoreErrorCode;
8
+ constructor({ code }: {
9
+ code: ChatStoreErrorCode;
10
+ }, options?: ErrorOptions);
11
+ }
12
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1,18 @@
1
+ const MESSAGES = {
2
+ 'invalid-input': 'Invalid chat store input.',
3
+ 'invalid-cursor': 'Invalid chat page cursor.',
4
+ conflict: 'Chat store conflict.',
5
+ unavailable: 'Chat store unavailable.',
6
+ };
7
+ /** Stable public errors; messages never expose owner IDs, cursors or driver details.
8
+ * @example new ChatStoreError({ code: 'conflict' }, { cause: originalError })
9
+ */
10
+ export class ChatStoreError extends Error {
11
+ name = 'ChatStoreError';
12
+ code;
13
+ constructor({ code }, options) {
14
+ super(MESSAGES[code], options);
15
+ this.code = code;
16
+ }
17
+ }
18
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,4 @@
1
+ /** Neutral store contracts and errors. SQL adapters are explicit child entries. */
2
+ export type * from './ports.js';
3
+ export { ChatStoreError } from './errors.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,2 @@
1
+ export { ChatStoreError } from './errors.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,3 @@
1
+ /** Legacy local project conversations, distinct from tenant-scoped ai_* history. */
2
+ export type ChatSessionMode = 'design' | 'chat' | 'plan';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,129 @@
1
+ /**
2
+ * @module db/conversations/conversations
3
+ * Owns conversation CRUD and list/get queries with per-conversation run summaries and
4
+ * total run-duration aggregation. Imports only the core/ kernel (types + rows helper).
5
+ */
6
+ import type { SqliteDb } from '@jini-ai/db/sqlite';
7
+ import type { DbRow } from '@jini-ai/db/core';
8
+ import type { ChatSessionMode } from '../index.js';
9
+ /**
10
+ * Returns all conversations for a project, newest first, each enriched with message count,
11
+ * the latest assistant run summary, and total accumulated run duration across all terminal runs.
12
+ * @param db Open SQLite database handle.
13
+ * @param projectId The project whose conversations to list.
14
+ */
15
+ export declare function listConversations({ db, projectId }: {
16
+ db: SqliteDb;
17
+ projectId: string;
18
+ }): {
19
+ latestRun: {
20
+ durationMs?: number;
21
+ endedAt?: number | undefined;
22
+ startedAt?: number | undefined;
23
+ status: string;
24
+ } | undefined;
25
+ totalDurationMs?: number;
26
+ id: any;
27
+ projectId: any;
28
+ title: any;
29
+ sessionMode: ChatSessionMode;
30
+ messageCount: number;
31
+ createdAt: number;
32
+ updatedAt: number;
33
+ }[];
34
+ /**
35
+ * Fetches a single conversation by id with its latest run summary and total run duration.
36
+ * Returns null when no matching conversation exists.
37
+ * @param db Open SQLite database handle.
38
+ * @param id Conversation id.
39
+ */
40
+ export declare function getConversation({ db, id }: {
41
+ db: SqliteDb;
42
+ id: string;
43
+ }): {
44
+ totalDurationMs?: number;
45
+ latestRun: {
46
+ durationMs?: number;
47
+ endedAt?: number | undefined;
48
+ startedAt?: number | undefined;
49
+ status: string;
50
+ } | undefined;
51
+ id: any;
52
+ projectId: any;
53
+ title: any;
54
+ sessionMode: ChatSessionMode;
55
+ messageCount: number;
56
+ createdAt: number;
57
+ updatedAt: number;
58
+ } | null;
59
+ /**
60
+ * Coerces an arbitrary database value to a valid ChatSessionMode, defaulting to 'design'.
61
+ * Upholds the invariant that no conversation ever carries an unknown session mode.
62
+ * @param value Raw value read from the session_mode column.
63
+ * @returns A valid ChatSessionMode: 'chat', 'plan', or 'design'.
64
+ */
65
+ export declare function normalizeConversationSessionMode({ value }: {
66
+ value: unknown;
67
+ }): ChatSessionMode;
68
+ /**
69
+ * Inserts a new conversation row and returns the full conversation record (including run summary).
70
+ * Normalizes sessionMode before persisting so the stored value is always a valid ChatSessionMode.
71
+ * @param db Open SQLite database handle.
72
+ * @param c Conversation fields to insert.
73
+ */
74
+ export declare function insertConversation({ db, c }: {
75
+ db: SqliteDb;
76
+ c: DbRow;
77
+ }): {
78
+ totalDurationMs?: number;
79
+ latestRun: {
80
+ durationMs?: number;
81
+ endedAt?: number | undefined;
82
+ startedAt?: number | undefined;
83
+ status: string;
84
+ } | undefined;
85
+ id: any;
86
+ projectId: any;
87
+ title: any;
88
+ sessionMode: ChatSessionMode;
89
+ messageCount: number;
90
+ createdAt: number;
91
+ updatedAt: number;
92
+ } | null;
93
+ /**
94
+ * Applies a partial patch to an existing conversation, merging with the current record.
95
+ * Returns null when the conversation does not exist; otherwise returns the updated record.
96
+ * @param db Open SQLite database handle.
97
+ * @param id Conversation id to update.
98
+ * @param patch Fields to overwrite; sessionMode and updatedAt are normalized before persisting.
99
+ */
100
+ export declare function updateConversation({ db, id, patch }: {
101
+ db: SqliteDb;
102
+ id: string;
103
+ patch: DbRow;
104
+ }): {
105
+ totalDurationMs?: number;
106
+ latestRun: {
107
+ durationMs?: number;
108
+ endedAt?: number | undefined;
109
+ startedAt?: number | undefined;
110
+ status: string;
111
+ } | undefined;
112
+ id: any;
113
+ projectId: any;
114
+ title: any;
115
+ sessionMode: ChatSessionMode;
116
+ messageCount: number;
117
+ createdAt: number;
118
+ updatedAt: number;
119
+ } | null;
120
+ /**
121
+ * Removes a conversation row by id. Cascading deletes on messages are handled by the schema.
122
+ * @param db Open SQLite database handle.
123
+ * @param id Conversation id to delete.
124
+ */
125
+ export declare function deleteConversation({ db, id }: {
126
+ db: SqliteDb;
127
+ id: string;
128
+ }): void;
129
+ //# sourceMappingURL=conversations.d.ts.map
@@ -0,0 +1,274 @@
1
+ import { rows } from '@jini-ai/db/core';
2
+ /**
3
+ * Returns all conversations for a project, newest first, each enriched with message count,
4
+ * the latest assistant run summary, and total accumulated run duration across all terminal runs.
5
+ * @param db Open SQLite database handle.
6
+ * @param projectId The project whose conversations to list.
7
+ */
8
+ export function listConversations({ db, projectId }) {
9
+ return rows(db
10
+ .prepare(`WITH project_conversations AS (
11
+ SELECT id, project_id AS projectId, title, session_mode AS sessionMode,
12
+ created_at AS createdAt, updated_at AS updatedAt
13
+ FROM conversations
14
+ WHERE project_id = ?
15
+ ),
16
+ latest_runs AS (
17
+ SELECT conversation_id AS conversationId,
18
+ run_status AS latestRunStatus,
19
+ started_at AS latestRunStartedAt,
20
+ ended_at AS latestRunEndedAt,
21
+ events_json AS latestRunEventsJson
22
+ FROM (
23
+ SELECT m.conversation_id,
24
+ m.run_status,
25
+ m.started_at,
26
+ m.ended_at,
27
+ m.events_json,
28
+ ROW_NUMBER() OVER (
29
+ PARTITION BY m.conversation_id
30
+ ORDER BY m.position DESC
31
+ ) AS rn
32
+ FROM messages m
33
+ JOIN project_conversations c ON c.id = m.conversation_id
34
+ WHERE m.role = 'assistant'
35
+ AND m.run_status IS NOT NULL
36
+ )
37
+ WHERE rn = 1
38
+ ),
39
+ message_counts AS (
40
+ SELECT m.conversation_id AS conversationId,
41
+ COUNT(*) AS messageCount
42
+ FROM messages m
43
+ JOIN project_conversations c ON c.id = m.conversation_id
44
+ GROUP BY m.conversation_id
45
+ ),
46
+ total_run_durations AS (
47
+ SELECT m.conversation_id AS conversationId,
48
+ SUM(${terminalRunDurationSql('m')}) AS totalDurationMs
49
+ FROM messages m
50
+ JOIN project_conversations c ON c.id = m.conversation_id
51
+ WHERE m.role = 'assistant'
52
+ AND m.run_status IN ('succeeded', 'failed', 'canceled')
53
+ GROUP BY m.conversation_id
54
+ )
55
+ SELECT c.id, c.projectId, c.title, c.sessionMode, c.createdAt, c.updatedAt,
56
+ COALESCE(mc.messageCount, 0) AS messageCount,
57
+ lr.latestRunStatus, lr.latestRunStartedAt,
58
+ lr.latestRunEndedAt, lr.latestRunEventsJson,
59
+ trd.totalDurationMs
60
+ FROM project_conversations c
61
+ LEFT JOIN latest_runs lr ON lr.conversationId = c.id
62
+ LEFT JOIN message_counts mc ON mc.conversationId = c.id
63
+ LEFT JOIN total_run_durations trd ON trd.conversationId = c.id
64
+ ORDER BY c.updatedAt DESC`)
65
+ .all(projectId)).map(normalizeConversation);
66
+ }
67
+ /**
68
+ * Fetches a single conversation by id with its latest run summary and total run duration.
69
+ * Returns null when no matching conversation exists.
70
+ * @param db Open SQLite database handle.
71
+ * @param id Conversation id.
72
+ */
73
+ export function getConversation({ db, id }) {
74
+ const r = db
75
+ .prepare(`SELECT id, project_id AS projectId, title, session_mode AS sessionMode,
76
+ created_at AS createdAt, updated_at AS updatedAt,
77
+ (SELECT COUNT(*) FROM messages WHERE conversation_id = conversations.id) AS messageCount
78
+ FROM conversations WHERE id = ?`)
79
+ .get(id);
80
+ if (!r)
81
+ return null;
82
+ return {
83
+ ...normalizeConversation(r),
84
+ latestRun: latestConversationRunSummary(db, r.id) ?? undefined,
85
+ ...numberProperty('totalDurationMs', totalConversationRunDurationMs(db, r.id)),
86
+ };
87
+ }
88
+ /** @internal Shapes a raw SQLite row into the canonical conversation object, including run summary. */
89
+ function normalizeConversation(r) {
90
+ const latestRun = conversationRunSummaryFromRow({
91
+ runStatus: r.latestRunStatus,
92
+ startedAt: r.latestRunStartedAt,
93
+ endedAt: r.latestRunEndedAt,
94
+ eventsJson: r.latestRunEventsJson,
95
+ });
96
+ return {
97
+ id: r.id,
98
+ projectId: r.projectId,
99
+ title: r.title ?? null,
100
+ sessionMode: normalizeConversationSessionMode({ value: r.sessionMode }),
101
+ messageCount: Number(r.messageCount),
102
+ createdAt: Number(r.createdAt),
103
+ updatedAt: Number(r.updatedAt),
104
+ ...numberProperty('totalDurationMs', r.totalDurationMs),
105
+ latestRun: latestRun ?? undefined,
106
+ };
107
+ }
108
+ /**
109
+ * Coerces an arbitrary database value to a valid ChatSessionMode, defaulting to 'design'.
110
+ * Upholds the invariant that no conversation ever carries an unknown session mode.
111
+ * @param value Raw value read from the session_mode column.
112
+ * @returns A valid ChatSessionMode: 'chat', 'plan', or 'design'.
113
+ */
114
+ export function normalizeConversationSessionMode({ value }) {
115
+ return value === 'chat' || value === 'plan' ? value : 'design';
116
+ }
117
+ /**
118
+ * @internal Produces a single-key object `{ [key]: number }` only when value is a finite number,
119
+ * omitting the key entirely otherwise. Generic over `key` (rather than plain `string`) so the
120
+ * spread of its return type into a caller's object literal carries a real, statically-known
121
+ * optional property instead of collapsing to an index signature the compiler then can't see
122
+ * through at the call site.
123
+ */
124
+ function numberProperty(key, value) {
125
+ const n = value == null ? undefined : Number(value);
126
+ return typeof n === 'number' && Number.isFinite(n)
127
+ ? { [key]: n }
128
+ : {};
129
+ }
130
+ /** @internal Queries the most recent assistant run summary for a conversation (used by getConversation's per-row fetch path). */
131
+ function latestConversationRunSummary(db, conversationId) {
132
+ const row = db
133
+ .prepare(`SELECT run_status AS runStatus,
134
+ started_at AS startedAt,
135
+ ended_at AS endedAt,
136
+ events_json AS eventsJson
137
+ FROM messages
138
+ WHERE conversation_id = ?
139
+ AND role = 'assistant'
140
+ AND run_status IS NOT NULL
141
+ ORDER BY position DESC
142
+ LIMIT 1`)
143
+ .get(conversationId);
144
+ return conversationRunSummaryFromRow(row);
145
+ }
146
+ /** @internal Sums terminal-run duration across all succeeded/failed/canceled assistant messages in a conversation. */
147
+ function totalConversationRunDurationMs(db, conversationId) {
148
+ const row = db
149
+ .prepare(`SELECT SUM(${terminalRunDurationSql()}) AS totalDurationMs
150
+ FROM messages
151
+ WHERE conversation_id = ?
152
+ AND role = 'assistant'
153
+ AND run_status IN ('succeeded', 'failed', 'canceled')`)
154
+ .get(conversationId);
155
+ return row?.totalDurationMs == null ? undefined : Number(row.totalDurationMs);
156
+ }
157
+ /** @internal Emits the SQL CASE expression that resolves a terminal run's duration: wall-clock diff when both timestamps exist, otherwise the latest usage event's durationMs. */
158
+ function terminalRunDurationSql(alias) {
159
+ const p = alias ? `${alias}.` : '';
160
+ return `CASE
161
+ WHEN ${p}started_at IS NOT NULL AND ${p}ended_at IS NOT NULL THEN
162
+ CASE
163
+ WHEN CAST(${p}ended_at AS INTEGER) >= CAST(${p}started_at AS INTEGER)
164
+ THEN CAST(${p}ended_at AS INTEGER) - CAST(${p}started_at AS INTEGER)
165
+ ELSE 0
166
+ END
167
+ ELSE (
168
+ SELECT CASE
169
+ WHEN json_extract(usage_event.value, '$.durationMs') >= 0
170
+ THEN json_extract(usage_event.value, '$.durationMs')
171
+ ELSE 0
172
+ END
173
+ FROM json_each(
174
+ CASE
175
+ WHEN json_valid(${p}events_json) AND json_type(${p}events_json) = 'array'
176
+ THEN ${p}events_json
177
+ ELSE '[]'
178
+ END
179
+ ) AS usage_event
180
+ WHERE usage_event.type = 'object'
181
+ AND json_extract(usage_event.value, '$.kind') = 'usage'
182
+ AND json_type(usage_event.value, '$.durationMs') IN ('integer', 'real')
183
+ ORDER BY CAST(usage_event.key AS INTEGER) DESC
184
+ LIMIT 1
185
+ )
186
+ END`;
187
+ }
188
+ /** @internal Converts a raw message row (runStatus/startedAt/endedAt/eventsJson) into a run summary object, or null when no run status is present. */
189
+ function conversationRunSummaryFromRow(row) {
190
+ if (!row || typeof row.runStatus !== 'string')
191
+ return null;
192
+ const startedAt = row.startedAt == null ? undefined : Number(row.startedAt);
193
+ const endedAt = row.endedAt == null ? undefined : Number(row.endedAt);
194
+ const usageDurationMs = latestUsageDurationMs(row.eventsJson);
195
+ const durationMs = Number.isFinite(startedAt) && Number.isFinite(endedAt)
196
+ ? Math.max(0, endedAt - startedAt)
197
+ : usageDurationMs;
198
+ return {
199
+ status: row.runStatus,
200
+ ...(Number.isFinite(startedAt) ? { startedAt } : {}),
201
+ ...(Number.isFinite(endedAt) ? { endedAt } : {}),
202
+ ...(typeof durationMs === 'number' && Number.isFinite(durationMs)
203
+ ? { durationMs }
204
+ : {}),
205
+ };
206
+ }
207
+ /** @internal Parses events_json to find the most recent usage event's durationMs; returns undefined when events_json is absent or malformed. */
208
+ function latestUsageDurationMs(eventsJson) {
209
+ if (typeof eventsJson !== 'string' || eventsJson.length === 0)
210
+ return undefined;
211
+ try {
212
+ const events = JSON.parse(eventsJson);
213
+ if (!Array.isArray(events))
214
+ return undefined;
215
+ for (let i = events.length - 1; i >= 0; i -= 1) {
216
+ const event = events[i];
217
+ if (event &&
218
+ typeof event === 'object' &&
219
+ event.kind === 'usage' &&
220
+ typeof event.durationMs === 'number' &&
221
+ Number.isFinite(event.durationMs)) {
222
+ return Math.max(0, event.durationMs);
223
+ }
224
+ }
225
+ }
226
+ catch {
227
+ return undefined;
228
+ }
229
+ return undefined;
230
+ }
231
+ /**
232
+ * Inserts a new conversation row and returns the full conversation record (including run summary).
233
+ * Normalizes sessionMode before persisting so the stored value is always a valid ChatSessionMode.
234
+ * @param db Open SQLite database handle.
235
+ * @param c Conversation fields to insert.
236
+ */
237
+ export function insertConversation({ db, c }) {
238
+ db.prepare(`INSERT INTO conversations
239
+ (id, project_id, title, session_mode, created_at, updated_at)
240
+ VALUES (?, ?, ?, ?, ?, ?)`).run(c.id, c.projectId, c.title ?? null, normalizeConversationSessionMode({ value: c.sessionMode }), c.createdAt, c.updatedAt);
241
+ return getConversation({ db: db, id: c.id });
242
+ }
243
+ /**
244
+ * Applies a partial patch to an existing conversation, merging with the current record.
245
+ * Returns null when the conversation does not exist; otherwise returns the updated record.
246
+ * @param db Open SQLite database handle.
247
+ * @param id Conversation id to update.
248
+ * @param patch Fields to overwrite; sessionMode and updatedAt are normalized before persisting.
249
+ */
250
+ export function updateConversation({ db, id, patch }) {
251
+ const existing = getConversation({ db: db, id: id });
252
+ if (!existing)
253
+ return null;
254
+ const merged = {
255
+ ...existing,
256
+ ...patch,
257
+ sessionMode: Object.prototype.hasOwnProperty.call(patch, 'sessionMode')
258
+ ? normalizeConversationSessionMode({ value: patch.sessionMode })
259
+ : existing.sessionMode,
260
+ updatedAt: typeof patch.updatedAt === 'number' ? patch.updatedAt : Date.now(),
261
+ };
262
+ db.prepare(`UPDATE conversations
263
+ SET title = ?, session_mode = ?, updated_at = ? WHERE id = ?`).run(merged.title ?? null, merged.sessionMode, merged.updatedAt, id);
264
+ return getConversation({ db: db, id: id });
265
+ }
266
+ /**
267
+ * Removes a conversation row by id. Cascading deletes on messages are handled by the schema.
268
+ * @param db Open SQLite database handle.
269
+ * @param id Conversation id to delete.
270
+ */
271
+ export function deleteConversation({ db, id }) {
272
+ db.prepare(`DELETE FROM conversations WHERE id = ?`).run(id);
273
+ }
274
+ //# sourceMappingURL=conversations.js.map