@jini-ai/chat 0.7.3-next.2 → 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.
- package/README.md +49 -0
- package/dist/core/accepted-input.d.ts +1 -1
- package/dist/core/ag-ui/event-projection.d.ts +14 -69
- package/dist/core/ag-ui/event-projection.js +58 -133
- package/dist/core/ag-ui/event-reduction.d.ts +12 -2
- package/dist/core/ag-ui/event-reduction.js +35 -10
- package/dist/core/ag-ui/resume.d.ts +110 -0
- package/dist/core/ag-ui/resume.js +200 -0
- package/dist/core/ag-ui/run-input.d.ts +23 -0
- package/dist/core/ag-ui/run-input.js +45 -0
- package/dist/core/ag-ui/server.d.ts +69 -0
- package/dist/core/ag-ui/server.js +71 -0
- package/dist/core/agent-plugin-chat-state.js +13 -11
- package/dist/core/assistant-client/ag-ui-approval-relay.d.ts +113 -0
- package/dist/core/assistant-client/ag-ui-approval-relay.js +287 -0
- package/dist/core/assistant-client/ag-ui-fetch-agent.d.ts +25 -10
- package/dist/core/assistant-client/ag-ui-fetch-agent.js +25 -6
- package/dist/core/assistant-client/ag-ui-transport.d.ts +86 -3
- package/dist/core/assistant-client/ag-ui-transport.js +310 -80
- package/dist/core/assistant-client/browser-durable-subscription.d.ts +25 -0
- package/dist/core/assistant-client/browser-durable-subscription.js +78 -0
- package/dist/core/assistant-client/durable-run-subscription.js +141 -130
- package/dist/core/assistant-client/entry.d.ts +2 -1
- package/dist/core/assistant-client/entry.js +1 -0
- package/dist/core/assistant-client/transport-prompt.d.ts +94 -0
- package/dist/core/assistant-client/transport-prompt.js +180 -0
- package/dist/core/assistant-client/transport-run.d.ts +49 -0
- package/dist/core/assistant-client/transport-run.js +432 -0
- package/dist/core/assistant-client/transport-stream.d.ts +73 -0
- package/dist/core/assistant-client/transport-stream.js +128 -0
- package/dist/core/assistant-client/transport.d.ts +1 -1
- package/dist/core/assistant-client/transport.js +129 -835
- package/dist/core/assistant-content.d.ts +1 -17
- package/dist/core/assistant-content.js +16 -0
- package/dist/core/assistant-tool-metadata.d.ts +103 -0
- package/dist/core/assistant-tool-metadata.js +56 -0
- package/dist/core/checkpoint-interval.d.ts +1 -1
- package/dist/core/compact-events.d.ts +1 -1
- package/dist/core/durable-projection.d.ts +1 -1
- package/dist/core/durable-runs/continuation.d.ts +1 -1
- package/dist/core/durable-runs/ledger-contracts.d.ts +4 -1
- package/dist/core/durable-runs/ports.d.ts +2 -1
- package/dist/core/durable-runs/run-contracts.d.ts +1 -1
- package/dist/core/durable-runs/run-finalizer.d.ts +145 -0
- package/dist/core/durable-runs/run-finalizer.js +171 -0
- package/dist/core/events.d.ts +4 -82
- package/dist/core/events.js +2 -1
- package/dist/core/index.d.ts +4 -1
- package/dist/core/index.js +2 -1
- package/dist/core/messages.d.ts +1 -1
- package/dist/core/persistence/index.d.ts +1 -1
- package/dist/core/persistence/index.js +1 -1
- package/dist/core/question-form/normalize.d.ts +9 -3
- package/dist/core/question-form/normalize.js +20 -20
- package/dist/core/question-form/scan.js +15 -19
- package/dist/core/run-activity.d.ts +1 -1
- package/dist/core/run-events/entry.d.ts +11 -63
- package/dist/core/run-events/entry.js +12 -7
- package/dist/core/todos.d.ts +1 -1
- package/dist/core/todos.js +8 -0
- package/dist/core/tool-call-detail.d.ts +8 -1
- package/dist/core/tool-call-detail.js +35 -12
- package/dist/core/tool-events.d.ts +1 -1
- package/dist/core/tool-output.js +2 -6
- package/dist/core/tools.d.ts +2 -1
- package/dist/core/transport.d.ts +1 -1
- package/dist/core/turn-usage.d.ts +1 -1
- package/dist/core/util/parser.js +70 -69
- package/dist/embed-widget/browser/embed-send-bridge.d.ts +44 -0
- package/dist/embed-widget/browser/embed-send-bridge.js +60 -0
- package/dist/embed-widget/browser/frontend-invocation-handler.d.ts +39 -0
- package/dist/embed-widget/browser/frontend-invocation-handler.js +151 -0
- package/dist/embed-widget/browser/frontend-session-bridge.d.ts +28 -0
- package/dist/embed-widget/browser/frontend-session-bridge.js +201 -257
- package/dist/embed-widget/browser/lazy-loader.js +16 -12
- package/dist/embed-widget/browser/session-store.d.ts +19 -1
- package/dist/embed-widget/browser/session-store.js +48 -17
- package/dist/embed-widget/transports/fetch-sse.d.ts +1 -1
- package/dist/embed-widget/vanilla/index.js +131 -67
- package/dist/embed-widget/vanilla/state.js +53 -38
- package/dist/react/admin-execution/ai-agent-presentation.d.ts +35 -0
- package/dist/react/admin-execution/ai-agent-presentation.js +39 -0
- package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.d.ts +22 -0
- package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.js +25 -0
- package/dist/react/chat-cleanup/ChatCleanupPanel.d.ts +15 -0
- package/dist/react/chat-cleanup/ChatCleanupPanel.js +17 -0
- package/dist/react/chat-cleanup/chat-cleanup.hooks.d.ts +168 -0
- package/dist/react/chat-cleanup/chat-cleanup.hooks.js +83 -0
- package/dist/react/components/ChatCleanupDialog.d.ts +38 -0
- package/dist/react/components/ChatCleanupDialog.js +12 -0
- package/dist/react/components/ConversationList.d.ts +14 -5
- package/dist/react/components/ConversationList.hooks.d.ts +1 -0
- package/dist/react/components/ConversationList.hooks.js +4 -2
- package/dist/react/components/ConversationList.js +41 -5
- package/dist/react/components/Icon.d.ts +1 -1
- package/dist/react/components/Icon.js +2 -0
- package/dist/react/components/Markdown.js +6 -6
- package/dist/react/components/MarkdownLink.d.ts +25 -0
- package/dist/react/components/MarkdownLink.js +17 -0
- package/dist/react/components/RoutedA2uiSurfaceCard.d.ts +80 -0
- package/dist/react/components/RoutedA2uiSurfaceCard.js +15 -0
- package/dist/react/components/ToolCard.d.ts +4 -2
- package/dist/react/components/ToolCard.js +46 -4
- package/dist/react/components/ToolCard.rules.d.ts +5 -2
- package/dist/react/components/ToolCard.rules.js +12 -5
- package/dist/react/components/mcp-ui-question-input.d.ts +1 -1
- package/dist/react/components/mcp-ui-surface-state.d.ts +3 -1
- package/dist/react/components/mcp-ui-surface-state.js +2 -2
- package/dist/react/components/own-link.d.ts +26 -0
- package/dist/react/components/own-link.js +36 -0
- package/dist/react/features/bridged-chat/create-staged-attachment-uploader.d.ts +7 -0
- package/dist/react/features/bridged-chat/create-staged-attachment-uploader.js +26 -0
- package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.d.ts +12 -0
- package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.js +60 -0
- package/dist/react/features/bridged-chat/index.d.ts +8 -0
- package/dist/react/features/bridged-chat/index.js +7 -0
- package/dist/react/features/bridged-chat/types.d.ts +49 -0
- package/dist/react/features/bridged-chat/types.js +2 -0
- package/dist/react/features/chat-pane/components/RuntimeDropUp.js +1 -1
- package/dist/react/features/chat-pane/create-daemon-attachment-uploader.d.ts +6 -0
- package/dist/react/features/chat-pane/create-daemon-attachment-uploader.js +101 -59
- package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.d.ts +3 -0
- package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.js +26 -16
- package/dist/react/features/chat-pane/model-options.d.ts +3 -1
- package/dist/react/features/chat-pane/model-options.js +3 -3
- package/dist/react/features/chat-pane/rules.js +4 -3
- package/dist/react/features/chat-pane/styles.d.ts +1 -1
- package/dist/react/features/chat-pane/styles.js +16 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.d.ts +10 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.js +19 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.d.ts +12 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.js +21 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.d.ts +13 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.js +9 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.d.ts +12 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.js +12 -0
- package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.d.ts +7 -0
- package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.js +43 -0
- package/dist/react/features/conversation-chat-pane/index.d.ts +9 -0
- package/dist/react/features/conversation-chat-pane/index.js +8 -0
- package/dist/react/features/conversation-chat-pane/rules.d.ts +25 -0
- package/dist/react/features/conversation-chat-pane/rules.js +29 -0
- package/dist/react/features/conversation-chat-pane/types.d.ts +139 -0
- package/dist/react/features/conversation-chat-pane/types.js +2 -0
- package/dist/react/features/conversations/conversation-controller.d.ts +16 -0
- package/dist/react/features/conversations/conversation-controller.js +280 -0
- package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.d.ts +15 -0
- package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.js +33 -0
- package/dist/react/features/conversations/hooks/useStoredConversations.hooks.d.ts +16 -0
- package/dist/react/features/conversations/hooks/useStoredConversations.hooks.js +36 -0
- package/dist/react/features/conversations/index.d.ts +9 -0
- package/dist/react/features/conversations/index.js +8 -0
- package/dist/react/features/conversations/types.d.ts +120 -0
- package/dist/react/features/conversations/types.js +2 -0
- package/dist/react/features/voice-input/space-hold-rules.d.ts +65 -0
- package/dist/react/features/voice-input/space-hold-rules.js +48 -0
- package/dist/react/hooks/testing/fake-transport.d.ts +1 -1
- package/dist/react/hooks/useAnsweredCards.d.ts +2 -1
- package/dist/react/hooks/useConversation.js +5 -2
- package/dist/react/hooks/useExtEventGroups.d.ts +1 -1
- package/dist/react/hooks/useRunActivity.d.ts +2 -1
- package/dist/react/hooks/useRunStream.d.ts +1 -1
- package/dist/react/hooks/useRunStream.js +1 -1
- package/dist/react/hooks/useSurfaceRecovery.js +3 -1
- package/dist/react/hooks/useToolTimeline.d.ts +2 -1
- package/dist/react/index.d.ts +5 -2
- package/dist/react/index.js +4 -2
- package/dist/react/message-blocks.d.ts +1 -48
- package/dist/react/message-blocks.js +47 -0
- package/dist/react/styles/chat-settings.css +14 -14
- package/dist/server/chat-cleanup-routes.d.ts +56 -0
- package/dist/server/chat-cleanup-routes.js +56 -0
- package/dist/server/durable-runs/recover.js +193 -171
- package/dist/server/run-finalizer/entry.js +133 -110
- package/dist/store/legacy/sqlite/conversations.js +29 -17
- package/dist/store/pglite/index.d.ts +1 -0
- package/dist/store/pglite/index.js +1 -0
- package/dist/store/ports.d.ts +12 -0
- package/dist/store/postgres/index.d.ts +1 -0
- package/dist/store/postgres/index.js +1 -0
- package/dist/store/runtime/attempt-base-retention.d.ts +57 -0
- package/dist/store/runtime/attempt-base-retention.js +103 -0
- package/dist/store/runtime/chat-maintenance.d.ts +16 -0
- package/dist/store/runtime/chat-maintenance.js +19 -0
- package/dist/store/runtime/chat-principal.d.ts +63 -0
- package/dist/store/runtime/chat-principal.js +39 -0
- package/dist/store/runtime/checkpoint-delta.d.ts +1 -1
- package/dist/store/runtime/durable-run-queries.d.ts +124 -0
- package/dist/store/runtime/durable-run-queries.js +122 -0
- package/dist/store/runtime/durable-run-store.d.ts +1 -1
- package/dist/store/runtime/durable-run-store.js +291 -343
- package/dist/store/runtime/entry.d.ts +3 -0
- package/dist/store/runtime/entry.js +3 -0
- package/dist/store/runtime/events-json.d.ts +1 -1
- package/dist/store/runtime/lazy-run-ledger.d.ts +19 -0
- package/dist/store/runtime/lazy-run-ledger.js +28 -0
- package/dist/store/runtime/run-ledger.d.ts +4 -1
- package/dist/store/runtime/run-ledger.js +256 -204
- package/dist/store/sql/bulk-deletion.d.ts +36 -0
- package/dist/store/sql/bulk-deletion.js +103 -0
- package/dist/store/sql/store-queries.d.ts +170 -0
- package/dist/store/sql/store-queries.js +212 -0
- package/dist/store/sql/store-rows.d.ts +106 -0
- package/dist/store/sql/store-rows.js +116 -0
- package/dist/store/sql/store-writes.d.ts +46 -0
- package/dist/store/sql/store-writes.js +161 -0
- package/dist/store/sql/store.d.ts +3 -16
- package/dist/store/sql/store.js +58 -428
- package/dist/store/sql/tables.d.ts +1 -0
- package/dist/store/sqlite/index.d.ts +1 -0
- package/dist/store/sqlite/index.js +1 -0
- package/dist/store/sqlite/schema.d.ts +1 -1
- package/dist/store/sqlite/schema.js +5 -1
- package/package.json +171 -20
|
@@ -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 {
|
|
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
|
-
/**
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
return
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
//
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
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
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
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
|
-
|
|
324
|
-
|
|
325
|
-
|
|
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
|
|
409
|
-
return (
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
});
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
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
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
});
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
return
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
await
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
});
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
})
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
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
|