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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +49 -0
  3. package/dist/core/accepted-input.d.ts +1 -1
  4. package/dist/core/ag-ui/event-projection.d.ts +14 -69
  5. package/dist/core/ag-ui/event-projection.js +58 -133
  6. package/dist/core/ag-ui/event-reduction.d.ts +12 -2
  7. package/dist/core/ag-ui/event-reduction.js +35 -10
  8. package/dist/core/ag-ui/resume.d.ts +110 -0
  9. package/dist/core/ag-ui/resume.js +200 -0
  10. package/dist/core/ag-ui/run-input.d.ts +23 -0
  11. package/dist/core/ag-ui/run-input.js +45 -0
  12. package/dist/core/ag-ui/server.d.ts +69 -0
  13. package/dist/core/ag-ui/server.js +71 -0
  14. package/dist/core/agent-plugin-chat-state.js +13 -11
  15. package/dist/core/assistant-client/ag-ui-approval-relay.d.ts +113 -0
  16. package/dist/core/assistant-client/ag-ui-approval-relay.js +287 -0
  17. package/dist/core/assistant-client/ag-ui-fetch-agent.d.ts +25 -10
  18. package/dist/core/assistant-client/ag-ui-fetch-agent.js +25 -6
  19. package/dist/core/assistant-client/ag-ui-transport.d.ts +86 -3
  20. package/dist/core/assistant-client/ag-ui-transport.js +310 -80
  21. package/dist/core/assistant-client/browser-durable-subscription.d.ts +25 -0
  22. package/dist/core/assistant-client/browser-durable-subscription.js +78 -0
  23. package/dist/core/assistant-client/durable-run-subscription.js +141 -130
  24. package/dist/core/assistant-client/entry.d.ts +2 -1
  25. package/dist/core/assistant-client/entry.js +1 -0
  26. package/dist/core/assistant-client/transport-prompt.d.ts +94 -0
  27. package/dist/core/assistant-client/transport-prompt.js +180 -0
  28. package/dist/core/assistant-client/transport-run.d.ts +49 -0
  29. package/dist/core/assistant-client/transport-run.js +432 -0
  30. package/dist/core/assistant-client/transport-stream.d.ts +73 -0
  31. package/dist/core/assistant-client/transport-stream.js +128 -0
  32. package/dist/core/assistant-client/transport.d.ts +1 -1
  33. package/dist/core/assistant-client/transport.js +129 -835
  34. package/dist/core/assistant-content.d.ts +1 -17
  35. package/dist/core/assistant-content.js +16 -0
  36. package/dist/core/assistant-tool-metadata.d.ts +103 -0
  37. package/dist/core/assistant-tool-metadata.js +56 -0
  38. package/dist/core/checkpoint-interval.d.ts +1 -1
  39. package/dist/core/compact-events.d.ts +1 -1
  40. package/dist/core/durable-projection.d.ts +1 -1
  41. package/dist/core/durable-runs/continuation.d.ts +1 -1
  42. package/dist/core/durable-runs/ledger-contracts.d.ts +4 -1
  43. package/dist/core/durable-runs/ports.d.ts +2 -1
  44. package/dist/core/durable-runs/run-contracts.d.ts +1 -1
  45. package/dist/core/durable-runs/run-finalizer.d.ts +145 -0
  46. package/dist/core/durable-runs/run-finalizer.js +171 -0
  47. package/dist/core/events.d.ts +4 -82
  48. package/dist/core/events.js +2 -1
  49. package/dist/core/index.d.ts +4 -1
  50. package/dist/core/index.js +2 -1
  51. package/dist/core/messages.d.ts +1 -1
  52. package/dist/core/persistence/index.d.ts +1 -1
  53. package/dist/core/persistence/index.js +1 -1
  54. package/dist/core/question-form/normalize.d.ts +9 -3
  55. package/dist/core/question-form/normalize.js +20 -20
  56. package/dist/core/question-form/scan.js +15 -19
  57. package/dist/core/run-activity.d.ts +1 -1
  58. package/dist/core/run-events/entry.d.ts +11 -63
  59. package/dist/core/run-events/entry.js +12 -7
  60. package/dist/core/todos.d.ts +1 -1
  61. package/dist/core/todos.js +8 -0
  62. package/dist/core/tool-call-detail.d.ts +8 -1
  63. package/dist/core/tool-call-detail.js +35 -12
  64. package/dist/core/tool-events.d.ts +1 -1
  65. package/dist/core/tool-output.js +2 -6
  66. package/dist/core/tools.d.ts +2 -1
  67. package/dist/core/transport.d.ts +1 -1
  68. package/dist/core/turn-usage.d.ts +1 -1
  69. package/dist/core/util/parser.js +70 -69
  70. package/dist/embed-widget/browser/embed-send-bridge.d.ts +44 -0
  71. package/dist/embed-widget/browser/embed-send-bridge.js +60 -0
  72. package/dist/embed-widget/browser/frontend-invocation-handler.d.ts +39 -0
  73. package/dist/embed-widget/browser/frontend-invocation-handler.js +151 -0
  74. package/dist/embed-widget/browser/frontend-session-bridge.d.ts +28 -0
  75. package/dist/embed-widget/browser/frontend-session-bridge.js +201 -257
  76. package/dist/embed-widget/browser/lazy-loader.js +16 -12
  77. package/dist/embed-widget/browser/session-store.d.ts +19 -1
  78. package/dist/embed-widget/browser/session-store.js +48 -17
  79. package/dist/embed-widget/transports/fetch-sse.d.ts +1 -1
  80. package/dist/embed-widget/vanilla/index.js +131 -67
  81. package/dist/embed-widget/vanilla/state.js +53 -38
  82. package/dist/react/admin-execution/ai-agent-presentation.d.ts +35 -0
  83. package/dist/react/admin-execution/ai-agent-presentation.js +39 -0
  84. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.d.ts +22 -0
  85. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.js +25 -0
  86. package/dist/react/chat-cleanup/ChatCleanupPanel.d.ts +15 -0
  87. package/dist/react/chat-cleanup/ChatCleanupPanel.js +17 -0
  88. package/dist/react/chat-cleanup/chat-cleanup.hooks.d.ts +168 -0
  89. package/dist/react/chat-cleanup/chat-cleanup.hooks.js +83 -0
  90. package/dist/react/components/ChatCleanupDialog.d.ts +38 -0
  91. package/dist/react/components/ChatCleanupDialog.js +12 -0
  92. package/dist/react/components/ConversationList.d.ts +14 -5
  93. package/dist/react/components/ConversationList.hooks.d.ts +1 -0
  94. package/dist/react/components/ConversationList.hooks.js +4 -2
  95. package/dist/react/components/ConversationList.js +41 -5
  96. package/dist/react/components/Icon.d.ts +1 -1
  97. package/dist/react/components/Icon.js +2 -0
  98. package/dist/react/components/Markdown.js +6 -6
  99. package/dist/react/components/MarkdownLink.d.ts +25 -0
  100. package/dist/react/components/MarkdownLink.js +17 -0
  101. package/dist/react/components/MessageList.hooks.d.ts +4 -0
  102. package/dist/react/components/MessageList.hooks.js +16 -2
  103. package/dist/react/components/MessageList.js +14 -7
  104. package/dist/react/components/MessageList.rules.d.ts +5 -0
  105. package/dist/react/components/MessageList.rules.js +4 -0
  106. package/dist/react/components/RoutedA2uiSurfaceCard.d.ts +80 -0
  107. package/dist/react/components/RoutedA2uiSurfaceCard.js +15 -0
  108. package/dist/react/components/ToolCard.d.ts +4 -2
  109. package/dist/react/components/ToolCard.js +46 -4
  110. package/dist/react/components/ToolCard.rules.d.ts +5 -2
  111. package/dist/react/components/ToolCard.rules.js +12 -5
  112. package/dist/react/components/mcp-ui-question-input.d.ts +1 -1
  113. package/dist/react/components/mcp-ui-surface-state.d.ts +3 -1
  114. package/dist/react/components/mcp-ui-surface-state.js +2 -2
  115. package/dist/react/components/own-link.d.ts +26 -0
  116. package/dist/react/components/own-link.js +36 -0
  117. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.d.ts +7 -0
  118. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.js +26 -0
  119. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.d.ts +12 -0
  120. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.js +60 -0
  121. package/dist/react/features/bridged-chat/index.d.ts +8 -0
  122. package/dist/react/features/bridged-chat/index.js +7 -0
  123. package/dist/react/features/bridged-chat/types.d.ts +49 -0
  124. package/dist/react/features/bridged-chat/types.js +2 -0
  125. package/dist/react/features/chat-pane/components/RuntimeDropUp.js +1 -1
  126. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.d.ts +6 -0
  127. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.js +101 -59
  128. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.d.ts +3 -0
  129. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.js +26 -16
  130. package/dist/react/features/chat-pane/model-options.d.ts +3 -1
  131. package/dist/react/features/chat-pane/model-options.js +3 -3
  132. package/dist/react/features/chat-pane/rules.js +4 -3
  133. package/dist/react/features/chat-pane/styles.d.ts +1 -1
  134. package/dist/react/features/chat-pane/styles.js +43 -11
  135. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.d.ts +10 -0
  136. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.js +19 -0
  137. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.d.ts +12 -0
  138. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.js +21 -0
  139. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.d.ts +13 -0
  140. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.js +9 -0
  141. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.d.ts +12 -0
  142. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.js +12 -0
  143. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.d.ts +7 -0
  144. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.js +43 -0
  145. package/dist/react/features/conversation-chat-pane/index.d.ts +9 -0
  146. package/dist/react/features/conversation-chat-pane/index.js +8 -0
  147. package/dist/react/features/conversation-chat-pane/rules.d.ts +25 -0
  148. package/dist/react/features/conversation-chat-pane/rules.js +29 -0
  149. package/dist/react/features/conversation-chat-pane/types.d.ts +139 -0
  150. package/dist/react/features/conversation-chat-pane/types.js +2 -0
  151. package/dist/react/features/conversations/conversation-controller.d.ts +16 -0
  152. package/dist/react/features/conversations/conversation-controller.js +280 -0
  153. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.d.ts +15 -0
  154. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.js +33 -0
  155. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.d.ts +16 -0
  156. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.js +36 -0
  157. package/dist/react/features/conversations/index.d.ts +9 -0
  158. package/dist/react/features/conversations/index.js +8 -0
  159. package/dist/react/features/conversations/types.d.ts +120 -0
  160. package/dist/react/features/conversations/types.js +2 -0
  161. package/dist/react/features/voice-input/space-hold-rules.d.ts +65 -0
  162. package/dist/react/features/voice-input/space-hold-rules.js +48 -0
  163. package/dist/react/hooks/testing/fake-transport.d.ts +1 -1
  164. package/dist/react/hooks/useAnsweredCards.d.ts +2 -1
  165. package/dist/react/hooks/useConversation.js +5 -2
  166. package/dist/react/hooks/useExtEventGroups.d.ts +1 -1
  167. package/dist/react/hooks/useRunActivity.d.ts +2 -1
  168. package/dist/react/hooks/useRunStream.d.ts +1 -1
  169. package/dist/react/hooks/useRunStream.js +1 -1
  170. package/dist/react/hooks/useSurfaceRecovery.js +3 -1
  171. package/dist/react/hooks/useToolTimeline.d.ts +2 -1
  172. package/dist/react/index.d.ts +5 -2
  173. package/dist/react/index.js +4 -2
  174. package/dist/react/message-blocks.d.ts +1 -48
  175. package/dist/react/message-blocks.js +47 -0
  176. package/dist/react/styles/chat-settings.css +14 -14
  177. package/dist/server/chat-cleanup-routes.d.ts +56 -0
  178. package/dist/server/chat-cleanup-routes.js +56 -0
  179. package/dist/server/durable-runs/recover.js +193 -171
  180. package/dist/server/run-finalizer/entry.js +133 -110
  181. package/dist/store/legacy/sqlite/conversations.js +29 -17
  182. package/dist/store/pglite/index.d.ts +1 -0
  183. package/dist/store/pglite/index.js +1 -0
  184. package/dist/store/ports.d.ts +12 -0
  185. package/dist/store/postgres/index.d.ts +1 -0
  186. package/dist/store/postgres/index.js +1 -0
  187. package/dist/store/runtime/attempt-base-retention.d.ts +57 -0
  188. package/dist/store/runtime/attempt-base-retention.js +103 -0
  189. package/dist/store/runtime/chat-maintenance.d.ts +16 -0
  190. package/dist/store/runtime/chat-maintenance.js +19 -0
  191. package/dist/store/runtime/chat-principal.d.ts +63 -0
  192. package/dist/store/runtime/chat-principal.js +39 -0
  193. package/dist/store/runtime/checkpoint-delta.d.ts +1 -1
  194. package/dist/store/runtime/durable-run-queries.d.ts +124 -0
  195. package/dist/store/runtime/durable-run-queries.js +122 -0
  196. package/dist/store/runtime/durable-run-store.d.ts +1 -1
  197. package/dist/store/runtime/durable-run-store.js +291 -343
  198. package/dist/store/runtime/entry.d.ts +3 -0
  199. package/dist/store/runtime/entry.js +3 -0
  200. package/dist/store/runtime/events-json.d.ts +1 -1
  201. package/dist/store/runtime/lazy-run-ledger.d.ts +19 -0
  202. package/dist/store/runtime/lazy-run-ledger.js +28 -0
  203. package/dist/store/runtime/run-ledger.d.ts +4 -1
  204. package/dist/store/runtime/run-ledger.js +256 -204
  205. package/dist/store/sql/bulk-deletion.d.ts +36 -0
  206. package/dist/store/sql/bulk-deletion.js +103 -0
  207. package/dist/store/sql/store-queries.d.ts +170 -0
  208. package/dist/store/sql/store-queries.js +212 -0
  209. package/dist/store/sql/store-rows.d.ts +106 -0
  210. package/dist/store/sql/store-rows.js +116 -0
  211. package/dist/store/sql/store-writes.d.ts +46 -0
  212. package/dist/store/sql/store-writes.js +161 -0
  213. package/dist/store/sql/store.d.ts +3 -16
  214. package/dist/store/sql/store.js +58 -428
  215. package/dist/store/sql/tables.d.ts +1 -0
  216. package/dist/store/sqlite/index.d.ts +1 -0
  217. package/dist/store/sqlite/index.js +1 -0
  218. package/dist/store/sqlite/schema.d.ts +1 -1
  219. package/dist/store/sqlite/schema.js +5 -1
  220. package/package.json +174 -23
@@ -1,16 +1,14 @@
1
- import { sqliteReadVersion } from '../sql/read-version.js';
2
1
  import { acceptedInputEvent, acceptedInputUserEvent } from "../../core/accepted-input.js";
3
2
  import { redactUserMessage, redactUserText } from "../../core/user-text-redaction.js";
4
3
  import { recoveredRunEvents } from "../../core/index.js";
4
+ import { casAdvanceProjection, conversationTranscript, deleteSession, insertAttempt, pollProjection, probeRun, saveAgentSession, selectAttempt, selectBinding, selectRunRow, slotOccupied, writeAttemptMetadata, writeToolEvent, } from "./durable-run-queries.js";
5
5
  import { chatKernelTables } from "../sql/boundary.js";
6
- import { sql } from "kysely";
7
6
  import { hasUnknownToolCall, CONTINUATION_DIVIDER } from "../../core/durable-runs/continuation.js";
8
7
  import { RECOVERY_WINDOW_MS } from "../../core/durable-runs/policies.js";
9
8
  import { createChatHistoryStore } from "./chat-history-store.js";
10
9
  import { runLockKey } from "../../core/durable-runs/run-lock.js";
11
10
  import { runContentFromEvents } from "../../core/run-events/entry.js";
12
- import { appendedEventsJson } from "./events-json.js";
13
- import { toMessage, validatedEventsJson } from "../sql/store.js";
11
+ import { toMessage } from "../sql/store.js";
14
12
  export const RUN_SLOT_BUSY = "Another answer in this chat is still running. This turn is queued in your browser.";
15
13
  export class RunSlotBusyError extends Error {
16
14
  constructor() { super(RUN_SLOT_BUSY); }
@@ -169,348 +167,298 @@ function continuationEvents({ current, incoming }, _optional = {}) {
169
167
  function sameOwner({ run, required }, _optional = {}) {
170
168
  return run.principalId === required.principalId && run.conversationId === required.conversationId;
171
169
  }
172
- /** Same kernel and message lock as checkpoint/settle. Claim changes run_id before any spawn;
173
- * old attempts cannot write projections or dispatch tools after that transaction commits. */
174
- export function createDurableRunStore({ kernel: hostKernel, isDaemonRunId }, _optional = {}) {
175
- const kernel = chatKernelTables({ kernel: hostKernel }, {});
176
- /** The run's own message row, with its events only when asked: never another message's. */
177
- async function runRow({ match }, { events = false } = {}) {
178
- const eventsColumn = events ? sql `${sql.ref("ai_chat_messages.events_json")}` : sql `null`;
179
- return kernel.run((db) => db.selectFrom("ai_chat_messages")
180
- .innerJoin("ai_chats", "ai_chats.id", "ai_chat_messages.conversation_id")
181
- .select(["ai_chat_messages.id", "conversation_id", "role", "content", "agent_id", "agent_name", "attachments_json",
182
- "run_id", "run_status", "position", "ai_chat_messages.created_at", "started_at", "ended_at", "owner_kind", "owner_id", "scope_id"])
183
- .select(eventsColumn.as("events_json"))
184
- .where(match.column, "=", match.value).where("role", "=", "assistant").executeTakeFirst());
185
- }
186
- /** Conversation projection: callers can omit assistant event payloads; legacy heads need only content. */
187
- async function conversationTranscript({ row }, { includeEvents = true } = {}) {
188
- const history = createChatHistoryStore({ kernel, isDaemonRunId, scope: { scopeId: row.scope_id, ownerKind: row.owner_kind, ownerId: row.owner_id } }, {});
189
- return history.messages({ conversationId: row.conversation_id }, { includeEvents });
190
- }
191
- /** Legacy accepted requests and recovery reconstruction consume prior text only. */
192
- async function readTranscript({ row, metadata }, options = {}) {
193
- if (!options.transcript && metadata)
194
- return [];
195
- const includeEvents = transcriptEventProjection(options);
196
- return conversationTranscript({ row }, { includeEvents });
197
- }
198
- /** Accepted user receipts split queued inputs and hold folder references. Keep that small
199
- * public metadata even when recovery omits prior assistant event payloads. */
200
- function transcriptEventProjection(options) {
201
- if (options.includeTranscriptEvents === false && options.transcript)
202
- return 'user';
203
- return options.includeTranscriptEvents ?? options.transcript === true;
204
- }
205
- function currentMessage({ row, transcript }, options = {}) {
206
- return options.transcript && options.includeTranscriptEvents !== false
207
- ? transcript.find(item => item.id === row.id) : toMessage(row);
208
- }
209
- /** One run's head, plus its transcript when that was read (`[]` otherwise). */
210
- async function readRun({ match }, options = {}) {
211
- const row = await runRow({ match }, options);
212
- if (!row || !row.run_id)
213
- return null;
214
- const messageId = row.id;
215
- const metadata = await kernel.run((db) => db.selectFrom("assistant_run_attempts").selectAll().where("message_id", "=", messageId).executeTakeFirst());
216
- // A legacy row's accepted request is derived from its transcript, so only it reads one here.
217
- const transcript = await readTranscript({ row, metadata }, options);
218
- const message = currentMessage({ row, transcript }, options);
219
- if (!message)
220
- return null; // Deletion may have cascaded between the two reads.
221
- return { head: runHead({ row, runId: row.run_id, metadata, message, transcript }, { isDaemonRunId }),
222
- transcript: transcript.map(item => item.id === messageId ? message : item) };
223
- }
224
- /** Locked read of one message; `transcript` decides whether it is a whole run or only its head. */
225
- async function lockedRead({ messageId, conversationId }, options = {}) {
226
- return kernel.transaction(async () => {
227
- // Message, attempt metadata and transcript must describe the same generation. A CAS in
228
- // the gap between independent reads must never pair a new projection with an old session.
229
- await kernel.lockKey(runLockKey({ messageId, conversationId, runId: "" }));
230
- return readRun({ match: { column: "ai_chat_messages.id", value: messageId } }, options);
231
- });
232
- }
233
- async function load({ messageId }, { includeTranscriptEvents = true } = {}) {
234
- const binding = await kernel.run((db) => db.selectFrom("ai_chat_messages").select("conversation_id")
235
- .where("id", "=", messageId).executeTakeFirst());
236
- if (!binding)
237
- return null;
238
- // Full reads take the message from the transcript. Lean reads select its own events once,
239
- // omitting prior assistant payloads while retaining accepted user receipts.
240
- const read = await lockedRead({ messageId, conversationId: binding.conversation_id }, { transcript: true, includeTranscriptEvents, events: !includeTranscriptEvents });
241
- return read && { ...read.head, transcript: read.transcript };
242
- }
243
- /** Single-message read; message identity survives continuation while run_id changes.
244
- * Legacy request reconstruction needs only transcript content, never its old event columns. */
245
- async function head({ messageId }, { events = true } = {}) {
246
- const binding = await kernel.run((db) => db.selectFrom("ai_chat_messages").select("conversation_id")
247
- .where("id", "=", messageId).executeTakeFirst());
248
- if (!binding)
249
- return null;
250
- return (await lockedRead({ messageId, conversationId: binding.conversation_id }, { events }))?.head ?? null;
251
- }
252
- /** Read only one owned projection, without a run lock or accepted-request reconstruction.
253
- * Native database versions follow checkpoint growth, replacements, attempts and settlement. SQL omits
254
- * content/events on a hit; only changed rows cross into JS as raw JSON, never parsed events.
255
- * @complexity One indexed row read; O(1) unchanged payload and JS space; changed payload is O(current message bytes).
256
- */
257
- async function poll({ messageId, principalId, workspaceId }, { cursor } = {}) {
258
- // SQLite has no per-row version: combine this connection's writes with the external-commit
259
- // generation. Unrelated writes may invalidate the cursor, but equal-length rewrites cannot
260
- // hide. PostgreSQL supplies the row's own MVCC version. Neither reads the event column.
261
- const version = kernel.dialect === 'sqlite'
262
- ? sqliteReadVersion({ kernel })
263
- : sql `cast(ai_chat_messages.xmin as text)`;
264
- const changed = sql `${version} <> ${cursor ?? ''}`;
265
- // Run writers persist compact JSON arrays on both engines. SQLite also tolerates malformed
266
- // legacy rows through its native validator; PG14 has no safe try-cast (do not parse in JS).
267
- const valid = kernel.dialect === 'sqlite' ? sql `json_valid(events_json)` : sql `1`;
268
- const row = await kernel.run(db => db.selectFrom('ai_chat_messages')
269
- .innerJoin('ai_chats', 'ai_chats.id', 'ai_chat_messages.conversation_id')
270
- .select(['ai_chat_messages.id', 'conversation_id', 'role'])
271
- .select([
272
- sql `case when ${changed} then run_id else null end`.as('run_id'),
273
- sql `case when ${changed} then run_status else null end`.as('run_status'),
274
- sql `case when ${changed} then agent_id else null end`.as('agent_id'),
275
- sql `case when ${changed} then agent_name else null end`.as('agent_name'),
276
- sql `case when ${changed} then attachments_json else null end`.as('attachments_json'),
277
- sql `case when ${changed} then ai_chat_messages.created_at else 0 end`.as('created_at'),
278
- sql `case when ${changed} then started_at else null end`.as('started_at'),
279
- sql `case when ${changed} then ended_at else null end`.as('ended_at')
280
- ])
281
- .select([version.as('cursor'),
282
- sql `case when ${changed} then content else '' end`.as('content'),
283
- sql `case when ${changed} then events_json else null end`.as('events_json'),
284
- sql `case when ${changed} then ${valid} else null end`.as('events_json_valid')])
285
- .where('ai_chat_messages.id', '=', messageId).where('role', '=', 'assistant')
286
- .where('owner_kind', '=', 'user').where('owner_id', '=', principalId).where('scope_id', '=', workspaceId)
287
- .executeTakeFirst());
288
- if (!row)
289
- return null;
290
- if (row.cursor === cursor)
291
- return { cursor: row.cursor };
292
- const metadata = JSON.stringify(toMessage({ ...row, events_json: null }));
293
- const events = validatedEventsJson({ row });
294
- const messageJson = events === undefined ? metadata : metadata.slice(0, -1) + ',"events":' + events + '}';
295
- return { cursor: row.cursor, conversationId: row.conversation_id, messageJson };
296
- }
297
- /** Unlocked probe: the message and conversation an attempt id currently names. */
298
- async function probeRun({ runId }, _options = {}) {
299
- return kernel.run((db) => db.selectFrom("ai_chat_messages").select(["id", "conversation_id"])
300
- .where("run_id", "=", runId).where("role", "=", "assistant").executeTakeFirst());
301
- }
302
- async function find({ runId, principalId }, _options = {}) {
303
- const row = await probeRun({ runId });
304
- if (!row)
170
+ /** The conversation locator and attempt fields one captured session writes. */
171
+ function capturedSessionFields({ sessionId, child, confirmed }, _optional = {}) {
172
+ return { session_id: sessionId, session_confirmed: confirmed ? 1 : 0, ...(child ? { child_pid: child.pid, child_started_at: child.startedAt } : {}) };
173
+ }
174
+ /** The attempt row a first acceptance stores; the request is masked before it is serialized. */
175
+ function acceptedAttemptRow({ required }, _optional = {}) {
176
+ return {
177
+ message_id: required.messageId, engine: "daemon", accepted_json: JSON.stringify(maskedRequest({ request: required.request }, {})),
178
+ recovery_count: 0, recovery_deadline: null, last_progress_at: required.now, cancel_reason: null,
179
+ recovery_elapsed_ms: 0, attempt_started_at: required.now,
180
+ session_id: null, session_confirmed: 0, child_pid: null, child_started_at: null, attempt_base_json: "[]",
181
+ };
182
+ }
183
+ /** Only a current, uncanceled attempt may move to its continuation. */
184
+ function mayAdvance({ current, run }, _optional = {}) {
185
+ return !current.cancelReason && current.runId === run.runId;
186
+ }
187
+ /** The attempt row a continuation stores: one more recovery, a window if none is open, and no session. */
188
+ function advancedAttempt({ run, current, now, projection }, _optional = {}) {
189
+ const recoveryCount = current.recoveryCount + 1;
190
+ const recoveryDeadline = current.recoveryDeadline ?? now + RECOVERY_WINDOW_MS;
191
+ const reset = { session_id: null, session_confirmed: 0, child_pid: null, child_started_at: null, attempt_base_json: JSON.stringify(projection) };
192
+ return {
193
+ values: { message_id: run.messageId, engine: run.engine, accepted_json: JSON.stringify(run.request),
194
+ recovery_count: recoveryCount, recovery_deadline: recoveryDeadline, recovery_elapsed_ms: 0, attempt_started_at: now,
195
+ last_progress_at: current.lastProgressAt, cancel_reason: null, ...reset },
196
+ updates: { recovery_count: recoveryCount, recovery_deadline: recoveryDeadline, attempt_started_at: now, ...reset },
197
+ };
198
+ }
199
+ /** Whether a tool call may run now. The unknown-call check covers the attempt base and the canonical projection. */
200
+ function toolGuardVerdict({ run, required }, _optional = {}) {
201
+ if (!run || !attemptCanExecute({ run }, {}))
202
+ return "stale";
203
+ const events = run.message.events ?? [];
204
+ const canonical = events.filter((event) => event.kind !== "tool_use" || event.name === required.toolId);
205
+ if (hasUnknownToolCall({ ...required, events: run.attemptBase }, {}) || hasUnknownToolCall({ ...required, events: canonical }, {}))
206
+ return "unknown";
207
+ return "allowed";
208
+ }
209
+ /** The recovery window opened or paused by `active`, from the saved deadline and elapsed budget. */
210
+ function nextRecoveryClock({ row, now, active }, _optional = {}) {
211
+ let deadline = row.recovery_deadline;
212
+ let elapsed = row.recovery_elapsed_ms;
213
+ if (active && deadline === null)
214
+ deadline = now + Math.max(0, RECOVERY_WINDOW_MS - elapsed);
215
+ if (!active && deadline !== null) {
216
+ elapsed = Math.max(0, RECOVERY_WINDOW_MS - (deadline - now));
217
+ deadline = null;
218
+ }
219
+ return { recovery_deadline: deadline, recovery_elapsed_ms: elapsed };
220
+ }
221
+ /** The terminal row a stop writes when it beats acceptance. */
222
+ function stopTombstone({ required }, _optional = {}) {
223
+ return { id: required.messageId, role: "assistant", content: "",
224
+ events: [{ kind: "status", label: "Stopped." }], runId: required.runId, runStatus: "canceled", createdAt: required.now, endedAt: required.now };
225
+ }
226
+ /** Accepted user receipts split queued inputs and hold folder references. Keep that small
227
+ * public metadata even when recovery omits prior assistant event payloads. */
228
+ function transcriptEventProjection(options) {
229
+ if (options.includeTranscriptEvents === false && options.transcript)
230
+ return 'user';
231
+ return options.includeTranscriptEvents ?? options.transcript === true;
232
+ }
233
+ function currentMessage({ row, transcript }, options = {}) {
234
+ return options.transcript && options.includeTranscriptEvents !== false
235
+ ? transcript.find(item => item.id === row.id) : toMessage(row);
236
+ }
237
+ /** Legacy accepted requests and recovery reconstruction consume prior text only. */
238
+ async function readTranscript({ deps, row, metadata }, options = {}) {
239
+ if (!options.transcript && metadata)
240
+ return [];
241
+ const includeEvents = transcriptEventProjection(options);
242
+ return conversationTranscript({ ...deps, row }, { includeEvents });
243
+ }
244
+ /** One run's head, plus its transcript when that was read (`[]` otherwise). */
245
+ async function readRun({ deps, match }, options = {}) {
246
+ const row = await selectRunRow({ kernel: deps.kernel, match }, options);
247
+ if (!row || !row.run_id)
248
+ return null;
249
+ const messageId = row.id;
250
+ const metadata = await selectAttempt({ kernel: deps.kernel, messageId });
251
+ // A legacy row's accepted request is derived from its transcript, so only it reads one here.
252
+ const transcript = await readTranscript({ deps, row, metadata }, options);
253
+ const message = currentMessage({ row, transcript }, options);
254
+ if (!message)
255
+ return null; // Deletion may have cascaded between the two reads.
256
+ return { head: runHead({ row, runId: row.run_id, metadata, message, transcript }, { isDaemonRunId: deps.isDaemonRunId }),
257
+ transcript: transcript.map(item => item.id === messageId ? message : item) };
258
+ }
259
+ /** Locked read of one message; `transcript` decides whether it is a whole run or only its head. */
260
+ async function lockedRead({ deps, messageId, conversationId }, options = {}) {
261
+ return deps.kernel.transaction(async () => {
262
+ // Message, attempt metadata and transcript must describe the same generation. A CAS in
263
+ // the gap between independent reads must never pair a new projection with an old session.
264
+ await deps.kernel.lockKey(runLockKey({ messageId, conversationId, runId: "" }));
265
+ return readRun({ deps, match: { column: "ai_chat_messages.id", value: messageId } }, options);
266
+ });
267
+ }
268
+ /** Probe without the run lock, take it, then read: a run deleted or advanced in the gap reads as gone.
269
+ * One read under the lock serves the whole operation; the unlocked probe only names the lock.
270
+ * @returns The run as of the lock, or null when the attempt id is unknown or no longer current. */
271
+ async function lockedRun({ deps, runId }, options = {}) {
272
+ const probe = await probeRun({ kernel: deps.kernel, runId });
273
+ if (!probe)
274
+ return null;
275
+ await deps.kernel.lockKey(runLockKey({ messageId: probe.id, conversationId: probe.conversation_id, runId }));
276
+ return (await readRun({ deps, match: { column: "ai_chat_messages.run_id", value: runId } }, options))?.head ?? null;
277
+ }
278
+ async function loadRun({ deps, messageId }, { includeTranscriptEvents = true } = {}) {
279
+ const binding = await selectBinding({ kernel: deps.kernel, messageId });
280
+ if (!binding)
281
+ return null;
282
+ // Full reads take the message from the transcript. Lean reads select its own events once,
283
+ // omitting prior assistant payloads while retaining accepted user receipts.
284
+ const read = await lockedRead({ deps, messageId, conversationId: binding.conversation_id }, { transcript: true, includeTranscriptEvents, events: !includeTranscriptEvents });
285
+ return read && { ...read.head, transcript: read.transcript };
286
+ }
287
+ /** Single-message read; message identity survives continuation while run_id changes.
288
+ * Legacy request reconstruction needs only transcript content, never its old event columns. */
289
+ async function headRun({ deps, messageId }, { events = true } = {}) {
290
+ const binding = await selectBinding({ kernel: deps.kernel, messageId });
291
+ if (!binding)
292
+ return null;
293
+ return (await lockedRead({ deps, messageId, conversationId: binding.conversation_id }, { events }))?.head ?? null;
294
+ }
295
+ async function findRun({ deps, runId, principalId }) {
296
+ const row = await probeRun({ kernel: deps.kernel, runId });
297
+ if (!row)
298
+ return null;
299
+ const run = (await lockedRead({ deps, messageId: row.id, conversationId: row.conversation_id }, { events: true }))?.head ?? null;
300
+ return principalId !== undefined && run?.principalId !== principalId ? null : run;
301
+ }
302
+ /** Slot and run locks, then the owner-scoped conversation; null when the caller does not own it. */
303
+ async function lockOwnedConversation({ deps, required }, _options = {}) {
304
+ const { kernel, isDaemonRunId } = deps;
305
+ await kernel.lockKey(`chat-slot:${required.conversationId}`);
306
+ await kernel.lockKey(runLockKey(required));
307
+ const history = createChatHistoryStore({ kernel, isDaemonRunId, scope: { scopeId: required.workspaceId, ownerKind: "user", ownerId: required.principalId } }, {});
308
+ return await history.get({ id: required.conversationId }) ? history : null;
309
+ }
310
+ async function appendAcceptedQuestion({ history, required, userMessage }, _options = {}) {
311
+ if (userMessage.id === required.messageId)
312
+ throw new Error("User and assistant messages must have different IDs");
313
+ // A pending/failed browser PUT must never let the assistant take the first position.
314
+ // Nested appends join this transaction and retain the conversation lock through both
315
+ // writes, so either arrival order of the idempotent PUT yields user then assistant.
316
+ const saved = await history.appendMessage({ conversationId: required.conversationId, message: userMessage });
317
+ if (!saved || saved.role !== "user")
318
+ throw new Error("Accepted user message could not be persisted");
319
+ }
320
+ /** @returns false when the answer id collides and no question was written. */
321
+ async function appendQueuedAnswer({ history, required, hasQuestion }, _options = {}) {
322
+ const message = { id: required.messageId, role: "assistant", content: "", events: [],
323
+ runId: required.runId, runStatus: "queued", createdAt: required.now, startedAt: required.now,
324
+ ...(required.request.agentId ? { agentId: required.request.agentId } : {}) };
325
+ const savedMessage = await history.appendMessage({ conversationId: required.conversationId, message });
326
+ if (savedMessage?.role === "assistant")
327
+ return true;
328
+ // Returning null here would commit the question alone after an ID collision.
329
+ if (hasQuestion)
330
+ throw new Error("Accepted assistant message could not be persisted");
331
+ return false;
332
+ }
333
+ async function acceptRun({ deps, required }) {
334
+ return deps.kernel.transaction(async () => {
335
+ const history = await lockOwnedConversation({ deps, required });
336
+ if (!history)
305
337
  return null;
306
- const run = (await lockedRead({ messageId: row.id, conversationId: row.conversation_id }, { events: true }))?.head ?? null;
307
- return principalId !== undefined && run?.principalId !== principalId ? null : run;
308
- }
309
- /** Slot and run locks, then the owner-scoped conversation; null when the caller does not own it. */
310
- async function lockOwnedConversation({ required }, _options = {}) {
311
- await kernel.lockKey(`chat-slot:${required.conversationId}`);
312
- await kernel.lockKey(runLockKey(required));
313
- const history = createChatHistoryStore({ kernel, isDaemonRunId, scope: { scopeId: required.workspaceId, ownerKind: "user", ownerId: required.principalId } }, {});
314
- return await history.get({ id: required.conversationId }) ? history : null;
315
- }
316
- async function assertSlotFree({ conversationId }, _options = {}) {
317
- const occupied = await kernel.run((db) => db.selectFrom("ai_chat_messages").select("id")
318
- .where("conversation_id", "=", conversationId).where("role", "=", "assistant")
319
- .where("run_status", "in", ["queued", "running"]).executeTakeFirst());
320
- if (occupied)
338
+ const existing = await loadRun({ deps, messageId: required.messageId }, { includeTranscriptEvents: false });
339
+ if (existing)
340
+ return sameOwner({ run: existing, required }) ? existing : null;
341
+ if (await slotOccupied({ kernel: deps.kernel, conversationId: required.conversationId }))
321
342
  throw new RunSlotBusyError();
322
- }
323
- async function appendAcceptedQuestion({ history, required, userMessage }, _options = {}) {
324
- if (userMessage.id === required.messageId)
325
- throw new Error("User and assistant messages must have different IDs");
326
- // A pending/failed browser PUT must never let the assistant take the first position.
327
- // Nested appends join this transaction and retain the conversation lock through both
328
- // writes, so either arrival order of the idempotent PUT yields user then assistant.
329
- const saved = await history.appendMessage({ conversationId: required.conversationId, message: userMessage });
330
- if (!saved || saved.role !== "user")
331
- throw new Error("Accepted user message could not be persisted");
332
- }
333
- /** @returns false when the answer id collides and no question was written. */
334
- async function appendQueuedAnswer({ history, required, hasQuestion }, _options = {}) {
335
- const message = { id: required.messageId, role: "assistant", content: "", events: [],
336
- runId: required.runId, runStatus: "queued", createdAt: required.now, startedAt: required.now,
337
- ...(required.request.agentId ? { agentId: required.request.agentId } : {}) };
338
- const savedMessage = await history.appendMessage({ conversationId: required.conversationId, message });
339
- if (savedMessage?.role === "assistant")
340
- return true;
341
- // Returning null here would commit the question alone after an ID collision.
342
- if (hasQuestion)
343
- throw new Error("Accepted assistant message could not be persisted");
344
- return false;
345
- }
346
- async function accept(required, _options = {}) {
347
- return kernel.transaction(async () => {
348
- const history = await lockOwnedConversation({ required });
349
- if (!history)
350
- return null;
351
- const existing = await load({ messageId: required.messageId }, { includeTranscriptEvents: false });
352
- if (existing)
353
- return sameOwner({ run: existing, required }) ? existing : null;
354
- await assertSlotFree({ conversationId: required.conversationId });
355
- const userMessage = acceptedUserMessage({ request: required.request, now: required.now }, {});
356
- if (userMessage)
357
- await appendAcceptedQuestion({ history, required, userMessage });
358
- if (!await appendQueuedAnswer({ history, required, hasQuestion: userMessage !== null }))
359
- return null;
360
- await kernel.run((db) => db.insertInto("assistant_run_attempts").values({
361
- message_id: required.messageId, engine: "daemon", accepted_json: JSON.stringify(maskedRequest({ request: required.request }, {})),
362
- recovery_count: 0, recovery_deadline: null, last_progress_at: required.now, cancel_reason: null,
363
- recovery_elapsed_ms: 0, attempt_started_at: required.now,
364
- session_id: null, session_confirmed: 0, child_pid: null, child_started_at: null, attempt_base_json: "[]",
365
- }).execute());
366
- return load({ messageId: required.messageId }, { includeTranscriptEvents: false });
367
- });
368
- }
369
- async function writeAttemptMetadata({ values, updates }) {
370
- await kernel.run(db => db.insertInto("assistant_run_attempts").values(values)
371
- .onConflict(oc => oc.column("message_id").doUpdateSet(updates)).execute());
372
- }
373
- async function advance({ run, nextRunId, now, events }, _options = {}) {
374
- return kernel.transaction(async () => {
375
- await kernel.lockKey(runLockKey(run));
376
- // The projection rebase needs this run's events, never the rest of its conversation.
377
- const current = (await lockedRead(run, { events: true }))?.head;
378
- if (!current || current.cancelReason || current.runId !== run.runId)
379
- return false;
380
- const projection = continuationEvents({ current, incoming: events }, {});
381
- const result = await kernel.run((db) => db.updateTable("ai_chat_messages")
382
- .set({ run_id: nextRunId, run_status: "queued", content: runContentFromEvents({ events: projection }), events_json: JSON.stringify(projection) })
383
- .where("id", "=", run.messageId).where("run_id", "=", run.runId)
384
- .where("run_status", "in", ["queued", "running"]).executeTakeFirst());
385
- if (Number(result.numUpdatedRows) === 0)
386
- return false;
387
- await writeAttemptMetadata({ values: {
388
- message_id: run.messageId, engine: run.engine, accepted_json: JSON.stringify(run.request),
389
- recovery_count: current.recoveryCount + 1, recovery_deadline: current.recoveryDeadline ?? now + RECOVERY_WINDOW_MS,
390
- recovery_elapsed_ms: 0, attempt_started_at: now,
391
- last_progress_at: current.lastProgressAt, cancel_reason: null, session_id: null,
392
- session_confirmed: 0, child_pid: null, child_started_at: null, attempt_base_json: JSON.stringify(projection),
393
- }, updates: {
394
- recovery_count: current.recoveryCount + 1, recovery_deadline: current.recoveryDeadline ?? now + RECOVERY_WINDOW_MS,
395
- attempt_started_at: now,
396
- session_id: null, session_confirmed: 0, child_pid: null, child_started_at: null, attempt_base_json: JSON.stringify(projection),
397
- } });
398
- return true;
399
- });
400
- }
401
- /** Probe without the run lock, take it, then read: a run deleted or advanced in the gap reads as gone.
402
- * One read under the lock serves the whole operation; the unlocked probe only names the lock.
403
- * @returns The run as of the lock, or null when the attempt id is unknown or no longer current. */
404
- async function lockedRun({ runId }, options = {}) {
405
- const probe = await probeRun({ runId });
406
- if (!probe)
343
+ const userMessage = acceptedUserMessage({ request: required.request, now: required.now }, {});
344
+ if (userMessage)
345
+ await appendAcceptedQuestion({ history, required, userMessage });
346
+ if (!await appendQueuedAnswer({ history, required, hasQuestion: userMessage !== null }))
407
347
  return null;
408
- await kernel.lockKey(runLockKey({ messageId: probe.id, conversationId: probe.conversation_id, runId }));
409
- return (await readRun({ match: { column: "ai_chat_messages.run_id", value: runId } }, options))?.head ?? null;
410
- }
411
- async function cancel({ runId, reason }, _options = {}) {
412
- await kernel.transaction(async () => {
413
- const run = await lockedRun({ runId });
414
- if (!run)
415
- return;
416
- await writeAttemptMetadata({ values: { ...metadataForRun({ run }, {}), cancel_reason: reason }, updates: { cancel_reason: reason } });
417
- });
418
- }
419
- async function cancelPending(required, _options = {}) {
420
- return kernel.transaction(async () => {
421
- const history = await lockOwnedConversation({ required });
422
- if (!history)
348
+ await insertAttempt({ kernel: deps.kernel, values: acceptedAttemptRow({ required }) });
349
+ return loadRun({ deps, messageId: required.messageId }, { includeTranscriptEvents: false });
350
+ });
351
+ }
352
+ async function advanceRun({ deps, args: { run, nextRunId, now, events } }) {
353
+ const { kernel } = deps;
354
+ return kernel.transaction(async () => {
355
+ await kernel.lockKey(runLockKey(run));
356
+ // The projection rebase needs this run's events, never the rest of its conversation.
357
+ const current = (await lockedRead({ deps, ...run }, { events: true }))?.head;
358
+ if (!current || !mayAdvance({ current, run }))
359
+ return false;
360
+ const projection = continuationEvents({ current, incoming: events }, {});
361
+ const content = runContentFromEvents({ events: projection });
362
+ if (!await casAdvanceProjection({ kernel, run, nextRunId, content, projection }))
363
+ return false;
364
+ await writeAttemptMetadata({ kernel, ...advancedAttempt({ run, current, now, projection }) });
365
+ return true;
366
+ });
367
+ }
368
+ async function cancelRun({ deps, runId, reason }) {
369
+ await deps.kernel.transaction(async () => {
370
+ const run = await lockedRun({ deps, runId });
371
+ if (!run)
372
+ return;
373
+ await writeAttemptMetadata({ kernel: deps.kernel, values: { ...metadataForRun({ run }, {}), cancel_reason: reason }, updates: { cancel_reason: reason } });
374
+ });
375
+ }
376
+ async function cancelPendingRun({ deps, required }) {
377
+ return deps.kernel.transaction(async () => {
378
+ const history = await lockOwnedConversation({ deps, required });
379
+ if (!history)
380
+ return null;
381
+ const existing = await loadRun({ deps, messageId: required.messageId }, { includeTranscriptEvents: false });
382
+ if (existing) {
383
+ if (!sameOwner({ run: existing, required }))
423
384
  return null;
424
- const existing = await load({ messageId: required.messageId }, { includeTranscriptEvents: false });
425
- if (existing) {
426
- if (!sameOwner({ run: existing, required }))
427
- return null;
428
- await cancel({ runId: existing.runId, reason: "user-stop" }, {});
429
- return load({ messageId: existing.messageId }, { includeTranscriptEvents: false });
430
- }
431
- // Stop may beat acceptance or its response. A terminal tombstone for the same logical
432
- // identity makes any later duplicate acceptance a no-op, without reserving the chat slot.
433
- await history.appendMessage({ conversationId: required.conversationId, message: { id: required.messageId, role: "assistant", content: "",
434
- events: [{ kind: "status", label: "Stopped." }], runId: required.runId, runStatus: "canceled", createdAt: required.now, endedAt: required.now } });
435
- return load({ messageId: required.messageId }, { includeTranscriptEvents: false });
436
- });
437
- }
438
- async function saveAgentSession({ run, sessionId }) {
439
- await kernel.run((db) => db.insertInto("assistant_agent_sessions").values({ conversation_id: run.conversationId,
440
- agent_id: run.request.agentId ?? "claude", session_id: sessionId, updated_at: Date.now() })
441
- .onConflict((oc) => oc.columns(["conversation_id", "agent_id"]).doUpdateSet({ session_id: sessionId, updated_at: Date.now() })).execute());
442
- }
443
- async function captureSession({ runId, sessionId, child, confirmed = true }, _options = {}) {
444
- return kernel.transaction(async () => {
445
- const run = await lockedRun({ runId });
446
- if (!run || !attemptCanExecute({ run }, {}))
447
- return false;
448
- const fields = { session_id: sessionId, session_confirmed: confirmed ? 1 : 0, ...(child ? { child_pid: child.pid, child_started_at: child.startedAt } : {}) };
449
- await writeAttemptMetadata({ values: { ...metadataForRun({ run }, {}), ...fields }, updates: fields });
450
- // Session and generation share the same lock/transaction; an old callback cannot write
451
- // the conversation's locator in the gap between a successful guard and a later CAS.
452
- await saveAgentSession({ run, sessionId });
453
- return true;
454
- });
455
- }
456
- async function clearSession({ runId, sessionId }, _options = {}) {
457
- await kernel.transaction(async () => {
458
- const run = await lockedRun({ runId });
459
- if (!run)
460
- return;
461
- await kernel.run((db) => db.deleteFrom("assistant_agent_sessions").where("conversation_id", "=", run.conversationId)
462
- .where("agent_id", "=", run.request.agentId ?? "claude").where("session_id", "=", sessionId).execute());
463
- await kernel.run((db) => db.updateTable("assistant_run_attempts").set({ session_id: null, session_confirmed: 0 })
464
- .where("message_id", "=", run.messageId).where("session_id", "=", sessionId).execute());
465
- });
466
- }
467
- async function guardTool(required, _options = {}) {
468
- return kernel.transaction(async () => {
469
- // The unknown-call check needs this run's saved events (one row), never other messages'.
470
- const run = await lockedRun({ runId: required.runId }, { events: true });
471
- if (!run || !attemptCanExecute({ run }, {}))
472
- return "stale";
473
- const events = run.message.events ?? [];
474
- const canonical = events.filter((event) => event.kind !== "tool_use" || event.name === required.toolId);
475
- if (hasUnknownToolCall({ ...required, events: run.attemptBase }, {}) || hasUnknownToolCall({ ...required, events: canonical }, {}))
476
- return "unknown";
477
- if (required.toolUseId)
478
- await writeToolEvent(run, { kind: "tool_use", id: required.toolUseId, name: required.toolId, input: required.input });
479
- return "allowed";
480
- });
481
- }
482
- async function writeToolEvent(run, event) {
483
- await kernel.run((db) => db.updateTable("ai_chat_messages").set({ events_json: appendedEventsJson({ event }) })
484
- .where("id", "=", run.messageId).where("run_id", "=", run.runId).where("run_status", "in", ["queued", "running"]).execute());
485
- await kernel.run((db) => db.updateTable("assistant_run_attempts")
486
- .set({ recovery_count: 0, recovery_deadline: null, recovery_elapsed_ms: 0, last_progress_at: Date.now() })
487
- .where("message_id", "=", run.messageId).execute());
488
- }
489
- async function completeTool({ runId, toolUseId, content }, _options = {}) {
490
- await kernel.transaction(async () => {
491
- const run = await lockedRun({ runId });
492
- if (run)
493
- await writeToolEvent(run, { kind: "tool_result", toolUseId, content, isError: false });
494
- });
495
- }
496
- async function recoveryClock({ runId, now, active }, _options = {}) {
497
- await kernel.transaction(async () => {
498
- const run = await lockedRun({ runId });
499
- if (!run)
500
- return;
501
- const row = await kernel.run((db) => db.selectFrom("assistant_run_attempts").selectAll().where("message_id", "=", run.messageId).executeTakeFirst())
502
- ?? metadataForRun({ run }, {});
503
- let deadline = row.recovery_deadline;
504
- let elapsed = row.recovery_elapsed_ms;
505
- if (active && deadline === null)
506
- deadline = now + Math.max(0, RECOVERY_WINDOW_MS - elapsed);
507
- if (!active && deadline !== null) {
508
- elapsed = Math.max(0, RECOVERY_WINDOW_MS - (deadline - now));
509
- deadline = null;
510
- }
511
- await writeAttemptMetadata({ values: { ...row, recovery_deadline: deadline, recovery_elapsed_ms: elapsed }, updates: { recovery_deadline: deadline, recovery_elapsed_ms: elapsed } });
512
- });
513
- }
514
- return { load, head, poll, find, accept, advance, cancel, cancelPending, captureSession, clearSession, guardTool, completeTool, recoveryClock };
385
+ await cancelRun({ deps, runId: existing.runId, reason: "user-stop" });
386
+ return loadRun({ deps, messageId: existing.messageId }, { includeTranscriptEvents: false });
387
+ }
388
+ // Stop may beat acceptance or its response. A terminal tombstone for the same logical
389
+ // identity makes any later duplicate acceptance a no-op, without reserving the chat slot.
390
+ await history.appendMessage({ conversationId: required.conversationId, message: stopTombstone({ required }) });
391
+ return loadRun({ deps, messageId: required.messageId }, { includeTranscriptEvents: false });
392
+ });
393
+ }
394
+ async function captureRunSession({ deps, args: { runId, sessionId, child, confirmed = true } }) {
395
+ const { kernel } = deps;
396
+ return kernel.transaction(async () => {
397
+ const run = await lockedRun({ deps, runId });
398
+ if (!run || !attemptCanExecute({ run }, {}))
399
+ return false;
400
+ const fields = capturedSessionFields({ sessionId, child, confirmed });
401
+ await writeAttemptMetadata({ kernel, values: { ...metadataForRun({ run }, {}), ...fields }, updates: fields });
402
+ // Session and generation share the same lock/transaction; an old callback cannot write
403
+ // the conversation's locator in the gap between a successful guard and a later CAS.
404
+ await saveAgentSession({ kernel, run, sessionId });
405
+ return true;
406
+ });
407
+ }
408
+ async function clearRunSession({ deps, runId, sessionId }) {
409
+ await deps.kernel.transaction(async () => {
410
+ const run = await lockedRun({ deps, runId });
411
+ if (run)
412
+ await deleteSession({ kernel: deps.kernel, run, sessionId });
413
+ });
414
+ }
415
+ async function guardRunTool({ deps, required }) {
416
+ return deps.kernel.transaction(async () => {
417
+ // The unknown-call check needs this run's saved events (one row), never other messages'.
418
+ const run = await lockedRun({ deps, runId: required.runId }, { events: true });
419
+ const verdict = toolGuardVerdict({ run, required });
420
+ if (verdict === "allowed" && run && required.toolUseId) {
421
+ await writeToolEvent({ kernel: deps.kernel, run, event: { kind: "tool_use", id: required.toolUseId, name: required.toolId, input: required.input } });
422
+ }
423
+ return verdict;
424
+ });
425
+ }
426
+ async function completeRunTool({ deps, args: { runId, toolUseId, content } }) {
427
+ await deps.kernel.transaction(async () => {
428
+ const run = await lockedRun({ deps, runId });
429
+ if (run)
430
+ await writeToolEvent({ kernel: deps.kernel, run, event: { kind: "tool_result", toolUseId, content, isError: false } });
431
+ });
432
+ }
433
+ async function runRecoveryClock({ deps, args: { runId, now, active } }) {
434
+ const { kernel } = deps;
435
+ await kernel.transaction(async () => {
436
+ const run = await lockedRun({ deps, runId });
437
+ if (!run)
438
+ return;
439
+ const row = await selectAttempt({ kernel, messageId: run.messageId }) ?? metadataForRun({ run }, {});
440
+ const clock = nextRecoveryClock({ row, now, active });
441
+ await writeAttemptMetadata({ kernel, values: { ...row, ...clock }, updates: clock });
442
+ });
443
+ }
444
+ /** Same kernel and message lock as checkpoint/settle. Claim changes run_id before any spawn;
445
+ * old attempts cannot write projections or dispatch tools after that transaction commits. */
446
+ export function createDurableRunStore({ kernel: hostKernel, isDaemonRunId }, _optional = {}) {
447
+ const deps = { kernel: chatKernelTables({ kernel: hostKernel }, {}), isDaemonRunId };
448
+ return {
449
+ load: ({ messageId }, options) => loadRun({ deps, messageId }, options),
450
+ head: ({ messageId }, options) => headRun({ deps, messageId }, options),
451
+ poll: (required, options) => pollProjection({ kernel: deps.kernel, ...required }, options),
452
+ find: (required) => findRun({ deps, ...required }),
453
+ accept: (required) => acceptRun({ deps, required }),
454
+ advance: (args) => advanceRun({ deps, args }),
455
+ cancel: (required) => cancelRun({ deps, ...required }),
456
+ cancelPending: (required) => cancelPendingRun({ deps, required }),
457
+ captureSession: (args) => captureRunSession({ deps, args }),
458
+ clearSession: (required) => clearRunSession({ deps, ...required }),
459
+ guardTool: (required) => guardRunTool({ deps, required }),
460
+ completeTool: (args) => completeRunTool({ deps, args }),
461
+ recoveryClock: (args) => runRecoveryClock({ deps, args }),
462
+ };
515
463
  }
516
464
  //# sourceMappingURL=durable-run-store.js.map