@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
@@ -0,0 +1,63 @@
1
+ import type { ChatHistoryStore } from "../ports.js";
2
+ /**
3
+ * @file Who a chat history belongs to — the principal a host hands its owner-scoped store factory,
4
+ * and the two owner-derived values every host binding needs: the hashed guest owner id and the
5
+ * per-principal retention deadline.
6
+ *
7
+ * Guest sessions are keyed by a hash of their cookie, never the cookie itself — see
8
+ * {@link hashSessionKey}. The host binds a principal onto a store scope (`scopeId` = workspace,
9
+ * `ownerKind` = principal kind, `ownerId` = user id or hashed session key).
10
+ */
11
+ /** How long a visitor's chat history survives without activity. */
12
+ export declare const GUEST_CHAT_TTL_MS: number;
13
+ /**
14
+ * Hashes a visitor's session key for storage.
15
+ *
16
+ * The cookie is a bearer credential: anyone holding it can read that visitor's transcripts. Stored
17
+ * raw, a database dump, a stray log line, or a backup handed to a contractor becomes a set of live
18
+ * session tokens. Hashed, the same leak yields values that cannot be replayed against the site.
19
+ *
20
+ * Plain SHA-256 rather than a password KDF, deliberately: the input is a high-entropy random token
21
+ * we generate, not a user-chosen secret, so there is nothing for a slow hash to protect against —
22
+ * and this runs on every request to the public assistant, where a deliberately slow hash would be
23
+ * a self-inflicted denial of service.
24
+ */
25
+ export declare function hashSessionKey({ sessionKey }: {
26
+ sessionKey: string;
27
+ }, _optional?: {}): string;
28
+ /** An authenticated staff member. History is retained until explicitly deleted. */
29
+ export interface AdminChatPrincipal {
30
+ readonly kind: "user";
31
+ readonly workspaceId: string;
32
+ readonly userId: string;
33
+ }
34
+ /** An anonymous site visitor, identified only by the opaque token in their cookie. */
35
+ export interface GuestChatPrincipal {
36
+ readonly kind: "guest";
37
+ readonly workspaceId: string;
38
+ /** The RAW cookie value. It is hashed here and never stored or logged in this form. */
39
+ readonly sessionKey: string;
40
+ }
41
+ export type ChatPrincipal = AdminChatPrincipal | GuestChatPrincipal;
42
+ /**
43
+ * What routes are handed instead of a database.
44
+ *
45
+ * Injected through the host's route dependencies so a handler's only path to chat history runs
46
+ * through a principal. The raw database handle is closed over at composition time and never
47
+ * reaches a route, which is what makes the unscoped query unwritable rather than merely discouraged.
48
+ */
49
+ export type ChatStoreFactory = (principal: ChatPrincipal) => ChatHistoryStore;
50
+ /**
51
+ * When a new conversation for this principal should expire, or `undefined` for never.
52
+ *
53
+ * Admin history has no TTL: it is work product, and an assistant that quietly forgets what an
54
+ * administrator did two days ago is worse than useless during an incident review. Guest history
55
+ * expires because it is personal data belonging to someone who never created an account, and
56
+ * keeping it indefinitely is a liability with no matching benefit.
57
+ */
58
+ export declare function chatExpiryFor({ principal }: {
59
+ principal: ChatPrincipal;
60
+ }, { now }?: {
61
+ now?: number;
62
+ }): number | undefined;
63
+ //# sourceMappingURL=chat-principal.d.ts.map
@@ -0,0 +1,39 @@
1
+ import { createHash } from "node:crypto";
2
+ /**
3
+ * @file Who a chat history belongs to — the principal a host hands its owner-scoped store factory,
4
+ * and the two owner-derived values every host binding needs: the hashed guest owner id and the
5
+ * per-principal retention deadline.
6
+ *
7
+ * Guest sessions are keyed by a hash of their cookie, never the cookie itself — see
8
+ * {@link hashSessionKey}. The host binds a principal onto a store scope (`scopeId` = workspace,
9
+ * `ownerKind` = principal kind, `ownerId` = user id or hashed session key).
10
+ */
11
+ /** How long a visitor's chat history survives without activity. */
12
+ export const GUEST_CHAT_TTL_MS = 2 * 24 * 60 * 60 * 1000;
13
+ /**
14
+ * Hashes a visitor's session key for storage.
15
+ *
16
+ * The cookie is a bearer credential: anyone holding it can read that visitor's transcripts. Stored
17
+ * raw, a database dump, a stray log line, or a backup handed to a contractor becomes a set of live
18
+ * session tokens. Hashed, the same leak yields values that cannot be replayed against the site.
19
+ *
20
+ * Plain SHA-256 rather than a password KDF, deliberately: the input is a high-entropy random token
21
+ * we generate, not a user-chosen secret, so there is nothing for a slow hash to protect against —
22
+ * and this runs on every request to the public assistant, where a deliberately slow hash would be
23
+ * a self-inflicted denial of service.
24
+ */
25
+ export function hashSessionKey({ sessionKey }, _optional = {}) {
26
+ return createHash("sha256").update(sessionKey).digest("hex");
27
+ }
28
+ /**
29
+ * When a new conversation for this principal should expire, or `undefined` for never.
30
+ *
31
+ * Admin history has no TTL: it is work product, and an assistant that quietly forgets what an
32
+ * administrator did two days ago is worse than useless during an incident review. Guest history
33
+ * expires because it is personal data belonging to someone who never created an account, and
34
+ * keeping it indefinitely is a liability with no matching benefit.
35
+ */
36
+ export function chatExpiryFor({ principal }, { now = Date.now() } = {}) {
37
+ return principal.kind === "guest" ? now + GUEST_CHAT_TTL_MS : undefined;
38
+ }
39
+ //# sourceMappingURL=chat-principal.js.map
@@ -1,5 +1,5 @@
1
- import type { AgentEvent } from "../../core/index.js";
2
1
  import type { CheckpointState, RunProgress } from "../../core/durable-runs/ledger-contracts.js";
2
+ import type { AgentEvent } from "@jini-ai/core/contracts/site/chat-core";
3
3
  /** A delta may append events or replace the final coalesced text event. Every earlier event
4
4
  * must match; replay reordering, thinking replacement and tool identity deduplication fall back.
5
5
  * @complexity O(prefix bytes + new suffix bytes) time; O(new suffix bytes) temporary space. */
@@ -0,0 +1,124 @@
1
+ import { type Insertable, type Selectable, type Updateable } from "kysely";
2
+ import type { AgentEvent } from "@jini-ai/core/contracts/site/chat-core";
3
+ import type { ChatMessage } from "../../core/index.js";
4
+ import type { RunIdPolicy, DurableRunHead } from "../../core/durable-runs/ports.js";
5
+ import type { ChatDatabase, ChatKernel } from "./kernel.js";
6
+ /**
7
+ * @file The durable run store's SQL: every query and single-statement write it issues, each taking
8
+ * the kernel explicitly. Nothing here opens a transaction or decides anything; the store owns both,
9
+ * so each of its transactions still reads as one body.
10
+ */
11
+ export type RunKernel = ChatKernel<ChatDatabase>;
12
+ export type RunRow = Selectable<ChatDatabase["ai_chat_messages"]> & {
13
+ owner_id: string;
14
+ owner_kind: string;
15
+ scope_id: string;
16
+ };
17
+ /** Where a run read finds its message row: by its id, or by the attempt id it currently holds. */
18
+ export type RunMatch = {
19
+ column: "ai_chat_messages.id" | "ai_chat_messages.run_id";
20
+ value: string;
21
+ };
22
+ /** `events`: parse the run's own saved events. `transcript`: also read every message of its conversation. */
23
+ export type ReadOptions = {
24
+ events?: boolean;
25
+ transcript?: boolean;
26
+ includeTranscriptEvents?: boolean;
27
+ };
28
+ export type Metadata = ChatDatabase["assistant_run_attempts"] | undefined;
29
+ type AttemptTable = ChatDatabase["assistant_run_attempts"];
30
+ /** The run's own message row, with its events only when asked: never another message's. */
31
+ export declare function selectRunRow({ kernel, match }: {
32
+ kernel: RunKernel;
33
+ match: RunMatch;
34
+ }, { events }?: ReadOptions): Promise<RunRow | undefined>;
35
+ /** The attempt metadata of one message, when it has any. */
36
+ export declare function selectAttempt({ kernel, messageId }: {
37
+ kernel: RunKernel;
38
+ messageId: string;
39
+ }): Promise<Metadata>;
40
+ /** The conversation a message belongs to. */
41
+ export declare function selectBinding({ kernel, messageId }: {
42
+ kernel: RunKernel;
43
+ messageId: string;
44
+ }): Promise<{
45
+ conversation_id: string;
46
+ } | undefined>;
47
+ /** Unlocked probe: the message and conversation an attempt id currently names. */
48
+ export declare function probeRun({ kernel, runId }: {
49
+ kernel: RunKernel;
50
+ runId: string;
51
+ }): Promise<{
52
+ id: string;
53
+ conversation_id: string;
54
+ } | undefined>;
55
+ /** Whether another answer in the conversation still holds its single run slot. */
56
+ export declare function slotOccupied({ kernel, conversationId }: {
57
+ kernel: RunKernel;
58
+ conversationId: string;
59
+ }): Promise<boolean>;
60
+ /** Conversation projection: callers can omit assistant event payloads; legacy heads need only content. */
61
+ export declare function conversationTranscript({ kernel, isDaemonRunId, row }: {
62
+ kernel: RunKernel;
63
+ isDaemonRunId: RunIdPolicy;
64
+ row: RunRow;
65
+ }, { includeEvents }?: {
66
+ includeEvents?: boolean | "user";
67
+ }): Promise<ChatMessage[]>;
68
+ /** Read only one owned projection, without a run lock or accepted-request reconstruction.
69
+ * Native database versions follow checkpoint growth, replacements, attempts and settlement. SQL omits
70
+ * content/events on a hit; only changed rows cross into JS as raw JSON, never parsed events.
71
+ * @complexity One indexed row read; O(1) unchanged payload and JS space; changed payload is O(current message bytes).
72
+ */
73
+ export declare function pollProjection({ kernel, messageId, principalId, workspaceId }: {
74
+ kernel: RunKernel;
75
+ messageId: string;
76
+ principalId: string;
77
+ workspaceId: string;
78
+ }, { cursor }?: {
79
+ cursor?: string;
80
+ }): Promise<{
81
+ cursor: string;
82
+ conversationId?: never;
83
+ messageJson?: never;
84
+ } | {
85
+ cursor: string;
86
+ conversationId: string;
87
+ messageJson: string;
88
+ } | null>;
89
+ /** First acceptance of a run: its attempt row. */
90
+ export declare function insertAttempt({ kernel, values }: {
91
+ kernel: RunKernel;
92
+ values: Insertable<AttemptTable>;
93
+ }): Promise<void>;
94
+ export declare function writeAttemptMetadata({ kernel, values, updates }: {
95
+ kernel: RunKernel;
96
+ values: Insertable<AttemptTable>;
97
+ updates: Updateable<AttemptTable>;
98
+ }): Promise<void>;
99
+ /** CAS of the attempt id and projection; false when the row no longer holds the old attempt id as active. */
100
+ export declare function casAdvanceProjection({ kernel, run, nextRunId, content, projection }: {
101
+ kernel: RunKernel;
102
+ run: DurableRunHead;
103
+ nextRunId: string;
104
+ content: string;
105
+ projection: readonly AgentEvent[];
106
+ }): Promise<boolean>;
107
+ export declare function saveAgentSession({ kernel, run, sessionId }: {
108
+ kernel: RunKernel;
109
+ run: DurableRunHead;
110
+ sessionId: string;
111
+ }): Promise<void>;
112
+ /** Drop the conversation's locator, then the attempt's own record of the same session. */
113
+ export declare function deleteSession({ kernel, run, sessionId }: {
114
+ kernel: RunKernel;
115
+ run: DurableRunHead;
116
+ sessionId: string;
117
+ }): Promise<void>;
118
+ export declare function writeToolEvent({ kernel, run, event }: {
119
+ kernel: RunKernel;
120
+ run: DurableRunHead;
121
+ event: AgentEvent;
122
+ }): Promise<void>;
123
+ export {};
124
+ //# sourceMappingURL=durable-run-queries.d.ts.map
@@ -0,0 +1,122 @@
1
+ import { sql } from "kysely";
2
+ import { sqliteReadVersion } from "../sql/read-version.js";
3
+ import { toMessage, validatedEventsJson } from "../sql/store.js";
4
+ import { createChatHistoryStore } from "./chat-history-store.js";
5
+ import { appendedEventsJson } from "./events-json.js";
6
+ /** The run's own message row, with its events only when asked: never another message's. */
7
+ export async function selectRunRow({ kernel, match }, { events = false } = {}) {
8
+ const eventsColumn = events ? sql `${sql.ref("ai_chat_messages.events_json")}` : sql `null`;
9
+ return kernel.run((db) => db.selectFrom("ai_chat_messages")
10
+ .innerJoin("ai_chats", "ai_chats.id", "ai_chat_messages.conversation_id")
11
+ .select(["ai_chat_messages.id", "conversation_id", "role", "content", "agent_id", "agent_name", "attachments_json",
12
+ "run_id", "run_status", "position", "ai_chat_messages.created_at", "started_at", "ended_at", "owner_kind", "owner_id", "scope_id"])
13
+ .select(eventsColumn.as("events_json"))
14
+ .where(match.column, "=", match.value).where("role", "=", "assistant").executeTakeFirst());
15
+ }
16
+ /** The attempt metadata of one message, when it has any. */
17
+ export async function selectAttempt({ kernel, messageId }) {
18
+ return kernel.run((db) => db.selectFrom("assistant_run_attempts").selectAll().where("message_id", "=", messageId).executeTakeFirst());
19
+ }
20
+ /** The conversation a message belongs to. */
21
+ export async function selectBinding({ kernel, messageId }) {
22
+ return kernel.run((db) => db.selectFrom("ai_chat_messages").select("conversation_id")
23
+ .where("id", "=", messageId).executeTakeFirst());
24
+ }
25
+ /** Unlocked probe: the message and conversation an attempt id currently names. */
26
+ export async function probeRun({ kernel, runId }) {
27
+ return kernel.run((db) => db.selectFrom("ai_chat_messages").select(["id", "conversation_id"])
28
+ .where("run_id", "=", runId).where("role", "=", "assistant").executeTakeFirst());
29
+ }
30
+ /** Whether another answer in the conversation still holds its single run slot. */
31
+ export async function slotOccupied({ kernel, conversationId }) {
32
+ const occupied = await kernel.run((db) => db.selectFrom("ai_chat_messages").select("id")
33
+ .where("conversation_id", "=", conversationId).where("role", "=", "assistant")
34
+ .where("run_status", "in", ["queued", "running"]).executeTakeFirst());
35
+ return occupied !== undefined;
36
+ }
37
+ /** Conversation projection: callers can omit assistant event payloads; legacy heads need only content. */
38
+ export async function conversationTranscript({ kernel, isDaemonRunId, row }, { includeEvents = true } = {}) {
39
+ const history = createChatHistoryStore({ kernel, isDaemonRunId, scope: { scopeId: row.scope_id, ownerKind: row.owner_kind, ownerId: row.owner_id } }, {});
40
+ return history.messages({ conversationId: row.conversation_id }, { includeEvents });
41
+ }
42
+ /** Read only one owned projection, without a run lock or accepted-request reconstruction.
43
+ * Native database versions follow checkpoint growth, replacements, attempts and settlement. SQL omits
44
+ * content/events on a hit; only changed rows cross into JS as raw JSON, never parsed events.
45
+ * @complexity One indexed row read; O(1) unchanged payload and JS space; changed payload is O(current message bytes).
46
+ */
47
+ export async function pollProjection({ kernel, messageId, principalId, workspaceId }, { cursor } = {}) {
48
+ // SQLite has no per-row version: combine this connection's writes with the external-commit
49
+ // generation. Unrelated writes may invalidate the cursor, but equal-length rewrites cannot
50
+ // hide. PostgreSQL supplies the row's own MVCC version. Neither reads the event column.
51
+ const version = kernel.dialect === 'sqlite'
52
+ ? sqliteReadVersion({ kernel })
53
+ : sql `cast(ai_chat_messages.xmin as text)`;
54
+ const changed = sql `${version} <> ${cursor ?? ''}`;
55
+ // Run writers persist compact JSON arrays on both engines. SQLite also tolerates malformed
56
+ // legacy rows through its native validator; PG14 has no safe try-cast (do not parse in JS).
57
+ const valid = kernel.dialect === 'sqlite' ? sql `json_valid(events_json)` : sql `1`;
58
+ const row = await kernel.run(db => db.selectFrom('ai_chat_messages')
59
+ .innerJoin('ai_chats', 'ai_chats.id', 'ai_chat_messages.conversation_id')
60
+ .select(['ai_chat_messages.id', 'conversation_id', 'role'])
61
+ .select([
62
+ sql `case when ${changed} then run_id else null end`.as('run_id'),
63
+ sql `case when ${changed} then run_status else null end`.as('run_status'),
64
+ sql `case when ${changed} then agent_id else null end`.as('agent_id'),
65
+ sql `case when ${changed} then agent_name else null end`.as('agent_name'),
66
+ sql `case when ${changed} then attachments_json else null end`.as('attachments_json'),
67
+ sql `case when ${changed} then ai_chat_messages.created_at else 0 end`.as('created_at'),
68
+ sql `case when ${changed} then started_at else null end`.as('started_at'),
69
+ sql `case when ${changed} then ended_at else null end`.as('ended_at')
70
+ ])
71
+ .select([version.as('cursor'),
72
+ sql `case when ${changed} then content else '' end`.as('content'),
73
+ sql `case when ${changed} then events_json else null end`.as('events_json'),
74
+ sql `case when ${changed} then ${valid} else null end`.as('events_json_valid')])
75
+ .where('ai_chat_messages.id', '=', messageId).where('role', '=', 'assistant')
76
+ .where('owner_kind', '=', 'user').where('owner_id', '=', principalId).where('scope_id', '=', workspaceId)
77
+ .executeTakeFirst());
78
+ if (!row)
79
+ return null;
80
+ if (row.cursor === cursor)
81
+ return { cursor: row.cursor };
82
+ const metadata = JSON.stringify(toMessage({ ...row, events_json: null }));
83
+ const events = validatedEventsJson({ row });
84
+ const messageJson = events === undefined ? metadata : metadata.slice(0, -1) + ',"events":' + events + '}';
85
+ return { cursor: row.cursor, conversationId: row.conversation_id, messageJson };
86
+ }
87
+ /** First acceptance of a run: its attempt row. */
88
+ export async function insertAttempt({ kernel, values }) {
89
+ await kernel.run((db) => db.insertInto("assistant_run_attempts").values(values).execute());
90
+ }
91
+ export async function writeAttemptMetadata({ kernel, values, updates }) {
92
+ await kernel.run(db => db.insertInto("assistant_run_attempts").values(values)
93
+ .onConflict(oc => oc.column("message_id").doUpdateSet(updates)).execute());
94
+ }
95
+ /** CAS of the attempt id and projection; false when the row no longer holds the old attempt id as active. */
96
+ export async function casAdvanceProjection({ kernel, run, nextRunId, content, projection }) {
97
+ const result = await kernel.run((db) => db.updateTable("ai_chat_messages")
98
+ .set({ run_id: nextRunId, run_status: "queued", content, events_json: JSON.stringify(projection) })
99
+ .where("id", "=", run.messageId).where("run_id", "=", run.runId)
100
+ .where("run_status", "in", ["queued", "running"]).executeTakeFirst());
101
+ return Number(result.numUpdatedRows) !== 0;
102
+ }
103
+ export async function saveAgentSession({ kernel, run, sessionId }) {
104
+ await kernel.run((db) => db.insertInto("assistant_agent_sessions").values({ conversation_id: run.conversationId,
105
+ agent_id: run.request.agentId ?? "claude", session_id: sessionId, updated_at: Date.now() })
106
+ .onConflict((oc) => oc.columns(["conversation_id", "agent_id"]).doUpdateSet({ session_id: sessionId, updated_at: Date.now() })).execute());
107
+ }
108
+ /** Drop the conversation's locator, then the attempt's own record of the same session. */
109
+ export async function deleteSession({ kernel, run, sessionId }) {
110
+ await kernel.run((db) => db.deleteFrom("assistant_agent_sessions").where("conversation_id", "=", run.conversationId)
111
+ .where("agent_id", "=", run.request.agentId ?? "claude").where("session_id", "=", sessionId).execute());
112
+ await kernel.run((db) => db.updateTable("assistant_run_attempts").set({ session_id: null, session_confirmed: 0 })
113
+ .where("message_id", "=", run.messageId).where("session_id", "=", sessionId).execute());
114
+ }
115
+ export async function writeToolEvent({ kernel, run, event }) {
116
+ await kernel.run((db) => db.updateTable("ai_chat_messages").set({ events_json: appendedEventsJson({ event }) })
117
+ .where("id", "=", run.messageId).where("run_id", "=", run.runId).where("run_status", "in", ["queued", "running"]).execute());
118
+ await kernel.run((db) => db.updateTable("assistant_run_attempts")
119
+ .set({ recovery_count: 0, recovery_deadline: null, recovery_elapsed_ms: 0, last_progress_at: Date.now() })
120
+ .where("message_id", "=", run.messageId).execute());
121
+ }
122
+ //# sourceMappingURL=durable-run-queries.js.map
@@ -1,7 +1,7 @@
1
1
  import type { RunIdPolicy } from "../../core/durable-runs/ports.js";
2
- import { type AgentEvent } from "../../core/index.js";
3
2
  import type { ChatKernel, ChatDatabase } from "./kernel.js";
4
3
  import type { DurableRunHead, DurableRunStore } from "../../core/durable-runs/ports.js";
4
+ import type { AgentEvent } from "@jini-ai/core/contracts/site/chat-core";
5
5
  export declare const RUN_SLOT_BUSY = "Another answer in this chat is still running. This turn is queued in your browser.";
6
6
  export declare class RunSlotBusyError extends Error {
7
7
  constructor();