@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.
- package/CHANGELOG.md +10 -0
- 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/MessageList.hooks.d.ts +4 -0
- package/dist/react/components/MessageList.hooks.js +16 -2
- package/dist/react/components/MessageList.js +14 -7
- package/dist/react/components/MessageList.rules.d.ts +5 -0
- package/dist/react/components/MessageList.rules.js +4 -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 +43 -11
- 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 +174 -23
|
@@ -5,4 +5,7 @@ export * from "./run-guarded-chat-store.js";
|
|
|
5
5
|
export type { ChatKernel, ChatDatabase } from "./kernel.js";
|
|
6
6
|
export * from "./chat-expiry-sweep.js";
|
|
7
7
|
export * from "./history-tools.js";
|
|
8
|
+
export * from "./chat-principal.js";
|
|
9
|
+
export * from "./chat-maintenance.js";
|
|
10
|
+
export * from "./lazy-run-ledger.js";
|
|
8
11
|
//# sourceMappingURL=entry.d.ts.map
|
|
@@ -4,4 +4,7 @@ export * from "./chat-history-store.js";
|
|
|
4
4
|
export * from "./run-guarded-chat-store.js";
|
|
5
5
|
export * from "./chat-expiry-sweep.js";
|
|
6
6
|
export * from "./history-tools.js";
|
|
7
|
+
export * from "./chat-principal.js";
|
|
8
|
+
export * from "./chat-maintenance.js";
|
|
9
|
+
export * from "./lazy-run-ledger.js";
|
|
7
10
|
//# sourceMappingURL=entry.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AgentEvent } from "
|
|
1
|
+
import type { AgentEvent } from "@jini-ai/core/contracts/site/chat-core";
|
|
2
2
|
/** Replace a compact array's suffix without transferring the stored prefix to JS.
|
|
3
3
|
* SQL length/substr count characters on SQLite and PostgreSQL, including non-BMP text.
|
|
4
4
|
* @complexity One SQL string splice; only the new suffix crosses the kernel boundary. */
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ChatRunLedger } from '../../core/durable-runs/ledger-contracts.js';
|
|
2
|
+
/**
|
|
3
|
+
* A {@link ChatRunLedger} over a database the host opens only on first real use (a test
|
|
4
|
+
* composition root whose routes may never touch chat history should not pay for a database).
|
|
5
|
+
* The host owns opening and memoizing the kernel; building a ledger per call must be cheap
|
|
6
|
+
* (one kernel per connection), which keeps the database lazy.
|
|
7
|
+
* @param peek The already-open kernel, or undefined when nothing has opened it yet.
|
|
8
|
+
* @param open Opens (once) and returns the kernel; every writing or durable call goes through it.
|
|
9
|
+
* @param ledgerFor Builds the host's ledger (including any host wrappers) over one kernel.
|
|
10
|
+
* @complexity O(1) per call beyond the delegated ledger operation.
|
|
11
|
+
*/
|
|
12
|
+
export declare function createLazyChatRunLedger<K>({ peek, open, ledgerFor }: {
|
|
13
|
+
peek: () => K | undefined;
|
|
14
|
+
open: () => K;
|
|
15
|
+
ledgerFor: (required: {
|
|
16
|
+
kernel: K;
|
|
17
|
+
}) => ChatRunLedger;
|
|
18
|
+
}, _optional?: {}): ChatRunLedger;
|
|
19
|
+
//# sourceMappingURL=lazy-run-ledger.d.ts.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A {@link ChatRunLedger} over a database the host opens only on first real use (a test
|
|
3
|
+
* composition root whose routes may never touch chat history should not pay for a database).
|
|
4
|
+
* The host owns opening and memoizing the kernel; building a ledger per call must be cheap
|
|
5
|
+
* (one kernel per connection), which keeps the database lazy.
|
|
6
|
+
* @param peek The already-open kernel, or undefined when nothing has opened it yet.
|
|
7
|
+
* @param open Opens (once) and returns the kernel; every writing or durable call goes through it.
|
|
8
|
+
* @param ledgerFor Builds the host's ledger (including any host wrappers) over one kernel.
|
|
9
|
+
* @complexity O(1) per call beyond the delegated ledger operation.
|
|
10
|
+
*/
|
|
11
|
+
export function createLazyChatRunLedger({ peek, open, ledgerFor }, _optional = {}) {
|
|
12
|
+
const opened = () => ledgerFor({ kernel: open() });
|
|
13
|
+
return {
|
|
14
|
+
hasActiveRuns: async () => { const kernel = peek(); return kernel !== undefined ? ledgerFor({ kernel }).hasActiveRuns({}, {}) : false; },
|
|
15
|
+
// Mirrors the opened ledger's optional store exactly; a getter cannot be an absent property
|
|
16
|
+
// under exactOptionalPropertyTypes, so `undefined` passes through as the host ledger has it.
|
|
17
|
+
get durable() { return opened().durable; },
|
|
18
|
+
unlessSettled: (required, optional) => opened().unlessSettled(required, optional),
|
|
19
|
+
settle: (settlement, optional) => opened().settle(settlement, optional),
|
|
20
|
+
checkpoint: (progress, optional) => opened().checkpoint(progress, optional),
|
|
21
|
+
// A database nobody has opened yet holds no stuck rows, so boot-time reconcile does not open it.
|
|
22
|
+
reconcileInterrupted: async (required, optional) => {
|
|
23
|
+
const kernel = peek();
|
|
24
|
+
return kernel !== undefined ? ledgerFor({ kernel }).reconcileInterrupted(required, optional) : 0;
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=lazy-run-ledger.js.map
|
|
@@ -3,16 +3,19 @@ import type { RunIdPolicy } from "../../core/durable-runs/ports.js";
|
|
|
3
3
|
export type * from "../../core/durable-runs/ledger-contracts.js";
|
|
4
4
|
import type { ChatRunLedger } from "../../core/durable-runs/ledger-contracts.js";
|
|
5
5
|
export { runLockKey } from "../../core/durable-runs/run-lock.js";
|
|
6
|
+
type LedgerLog = (code: string, detail?: Record<string, never>) => void;
|
|
6
7
|
/**
|
|
7
8
|
* @param store the chat kernel, or the open `chat.db` handle `createChatStoreFactory` also wraps.
|
|
8
9
|
* @param now Injectable epoch-millisecond clock for progress stamps and the default cancel time.
|
|
10
|
+
* @param log Code-only sink for a failed recovery admission; never receives error text.
|
|
9
11
|
* @complexity indexed guards; checkpoints cost O(delta bytes) plus a SQLite scalar receipt read,
|
|
10
12
|
* or O(saved + incoming bytes) on fallback. Reconcile costs O(stuck rows + their event bytes).
|
|
11
13
|
*/
|
|
12
14
|
export declare function createChatRunLedger<DB extends ChatDatabase>({ kernel: hostKernel, isDaemonRunId }: {
|
|
13
15
|
kernel: ChatKernel<DB>;
|
|
14
16
|
isDaemonRunId: RunIdPolicy;
|
|
15
|
-
}, { now }?: {
|
|
17
|
+
}, { now, log }?: {
|
|
16
18
|
now?: () => number;
|
|
19
|
+
log?: LedgerLog;
|
|
17
20
|
}): ChatRunLedger;
|
|
18
21
|
//# sourceMappingURL=run-ledger.d.ts.map
|
|
@@ -94,231 +94,283 @@ function keepToolCheckpoints(saved, incoming) {
|
|
|
94
94
|
// serialized input. The shared ID rule owns identity; JSON equality does not.
|
|
95
95
|
return dedupeToolUsesById({ events: [...incoming, ...saved.filter((event) => { const id = toolKey({ event }); return id !== "" && !seen.has(id); })] });
|
|
96
96
|
}
|
|
97
|
-
/**
|
|
98
|
-
|
|
99
|
-
* @param now Injectable epoch-millisecond clock for progress stamps and the default cancel time.
|
|
100
|
-
* @complexity indexed guards; checkpoints cost O(delta bytes) plus a SQLite scalar receipt read,
|
|
101
|
-
* or O(saved + incoming bytes) on fallback. Reconcile costs O(stuck rows + their event bytes).
|
|
102
|
-
*/
|
|
103
|
-
export function createChatRunLedger({ kernel: hostKernel, isDaemonRunId }, { now = () => Date.now() } = {}) {
|
|
104
|
-
const kernel = chatKernelTables({ kernel: hostKernel }, {});
|
|
97
|
+
/** The kernel, the clock, the code-only logger and the dialect-specific version expressions every ledger operation shares. */
|
|
98
|
+
function ledgerContext({ kernel, now, log }) {
|
|
105
99
|
const version = kernel.dialect === 'sqlite' ? sqliteReadVersion({ kernel }) : sql `cast(ai_chat_messages.xmin as text)`;
|
|
106
100
|
const returnedVersion = kernel.dialect === 'sqlite' ? sql `null` : version;
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
101
|
+
return { kernel, now, log, version, returnedVersion };
|
|
102
|
+
}
|
|
103
|
+
async function isSettled({ kernel, run }) {
|
|
104
|
+
const row = await kernel.run((db) => db
|
|
105
|
+
.selectFrom("ai_chat_messages")
|
|
106
|
+
.select("run_status")
|
|
107
|
+
.where("id", "=", run.messageId)
|
|
108
|
+
.where("conversation_id", "=", run.conversationId)
|
|
109
|
+
.where("run_id", "=", run.runId)
|
|
110
|
+
.executeTakeFirst());
|
|
111
|
+
return isTerminal(row?.run_status);
|
|
112
|
+
}
|
|
113
|
+
/** Progress earns a fresh recovery budget. Replayed prefixes/dividers cannot keep a failing
|
|
114
|
+
* attempt alive forever. Kept separate so full and delta writes use exactly the same reset. */
|
|
115
|
+
async function recordProgress({ ctx, progress }, _options = {}) {
|
|
116
|
+
await ctx.kernel.run((db) => db.updateTable("assistant_run_attempts")
|
|
117
|
+
.set({ recovery_count: 0, recovery_deadline: null, recovery_elapsed_ms: 0, last_progress_at: ctx.now() })
|
|
118
|
+
.where("message_id", "=", progress.messageId).execute());
|
|
119
|
+
}
|
|
120
|
+
/** One guarded delta UPDATE, no saved-column read or parse. A miss is deliberately indistinguishable
|
|
121
|
+
* from an ineligible delta: both must consult the authoritative checkpoint path under this lock. */
|
|
122
|
+
async function writeDelta({ ctx, progress, optional }, _options = {}) {
|
|
123
|
+
const { previous, expected } = optional;
|
|
124
|
+
if (!previous || expected !== previous.length)
|
|
125
|
+
return false;
|
|
126
|
+
const delta = checkpointDelta({ previous, progress });
|
|
127
|
+
if (!delta)
|
|
128
|
+
return false;
|
|
129
|
+
const result = await ctx.kernel.run((db) => db.updateTable("ai_chat_messages")
|
|
130
|
+
.set({ content: progress.content, events_json: spliceEventsJson(delta),
|
|
131
|
+
run_status: sql `case when run_status = 'queued' then 'running' else run_status end` })
|
|
132
|
+
.where(activeRunPredicate({ run: progress }))
|
|
133
|
+
.where(sql `${ctx.version} = ${previous.version}`)
|
|
134
|
+
.where(sql `length(events_json) = ${expected}`)
|
|
135
|
+
// BYOK/AG-UI browser upserts can replace a queued/running projection at the same length.
|
|
136
|
+
// Durable tool appends grow the length; recovery replacements also change run_id.
|
|
137
|
+
.where(sql `substr(events_json, length(events_json) - length(cast(${previous.tail} as text)) + 1) = ${previous.tail}`)
|
|
138
|
+
.where(sql `length(content) = ${previous.contentLength}`)
|
|
139
|
+
.returning([sql `length(events_json)`.as("length"), sql `length(content)`.as("contentLength"), ctx.returnedVersion.as("version")])
|
|
140
|
+
.executeTakeFirst());
|
|
141
|
+
if (!result)
|
|
142
|
+
return false;
|
|
143
|
+
if (delta.grown)
|
|
144
|
+
await recordProgress({ ctx, progress });
|
|
145
|
+
await notifyPersisted({ ctx, progress, optional, length: Number(result.length), contentLength: Number(result.contentLength), nativeVersion: result.version, exact: true });
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
/** A saved-only barrier invalidates the receipt. SQLite samples its connection/external-commit
|
|
149
|
+
* generation after ALL writes, while still under the transaction lock. Never capture a later
|
|
150
|
+
* writer's version beside this projection. PG returns the updated row's own MVCC version.
|
|
151
|
+
* @complexity O(1) scalar SQLite read per requested receipt; no payload query or PG extra read.
|
|
152
|
+
*/
|
|
153
|
+
async function notifyPersisted({ ctx, progress, optional, length, contentLength, nativeVersion, exact }, _options = {}) {
|
|
154
|
+
if (!optional.onPersisted)
|
|
155
|
+
return;
|
|
156
|
+
if (!exact) {
|
|
157
|
+
optional.onPersisted(undefined);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
// `run` keeps this read on the open transaction, under the write lock.
|
|
161
|
+
const receiptVersion = ctx.kernel.dialect === 'sqlite' ? (await ctx.kernel.run((db) => sql `select ${ctx.version} as version`.execute(db))).rows[0].version : nativeVersion;
|
|
162
|
+
optional.onPersisted(checkpointState({ progress, length, contentLength, version: receiptVersion }));
|
|
163
|
+
}
|
|
164
|
+
/** The saved columns a full checkpoint compares against, with their SQL lengths and native version. */
|
|
165
|
+
async function selectCheckpointRow({ ctx, progress }) {
|
|
166
|
+
return ctx.kernel.run((db) => db.selectFrom("ai_chat_messages")
|
|
167
|
+
.select(["content", "events_json", "run_status", sql `length(events_json)`.as("length"), sql `length(content)`.as("contentLength"), ctx.returnedVersion.as("version")])
|
|
168
|
+
.where(activeRunPredicate({ run: progress })).executeTakeFirst());
|
|
169
|
+
}
|
|
170
|
+
/** Full merge fallback, including identical-checkpoint write elision. One parse/stringify only. */
|
|
171
|
+
async function writeFullCheckpoint({ ctx, progress, optional }, _options = {}) {
|
|
172
|
+
const current = await selectCheckpointRow({ ctx, progress });
|
|
173
|
+
if (!current || progress.content.length < current.content.length)
|
|
174
|
+
return false;
|
|
175
|
+
const plan = planCheckpoint({ current, progress });
|
|
176
|
+
// Identical content/events are not progress; accepting without rewriting leaves both the
|
|
177
|
+
// multi-MB column and recovery budget exactly as the guarded UPDATE would have.
|
|
178
|
+
// Under this lock the row was just matched by the update's own predicate, so the update
|
|
179
|
+
// would match (true); returning true without writing preserves that contract.
|
|
180
|
+
if (plan.unchanged) {
|
|
181
|
+
await notifyPersisted({ ctx, progress, optional, length: Number(current.length), contentLength: Number(current.contentLength), nativeVersion: current.version, exact: plan.exact });
|
|
182
|
+
return true;
|
|
116
183
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
184
|
+
const result = await ctx.kernel.run((db) => db.updateTable("ai_chat_messages")
|
|
185
|
+
.set({ content: progress.content, events_json: plan.eventsJson, run_status: plan.runStatus })
|
|
186
|
+
.where(activeRunPredicate({ run: progress }))
|
|
187
|
+
.returning([sql `length(events_json)`.as("length"), sql `length(content)`.as("contentLength"), ctx.returnedVersion.as("version")]).executeTakeFirst());
|
|
188
|
+
if (!result)
|
|
189
|
+
return false;
|
|
190
|
+
if (plan.grown)
|
|
191
|
+
await recordProgress({ ctx, progress });
|
|
192
|
+
await notifyPersisted({ ctx, progress, optional, length: Number(result.length), contentLength: Number(result.contentLength), nativeVersion: result.version, exact: plan.exact });
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
async function checkpointRun({ ctx, progress, optional }) {
|
|
196
|
+
let persisted = false;
|
|
197
|
+
let receipt;
|
|
198
|
+
// Publish the watch receipt only after COMMIT. A rollback must not advance its CAS base.
|
|
199
|
+
const transactionOptions = optional.onPersisted
|
|
200
|
+
? { ...optional, onPersisted: (value) => { persisted = true; receipt = value; } } : optional;
|
|
201
|
+
const written = await ctx.kernel.transaction(async () => {
|
|
202
|
+
await ctx.kernel.lockKey(runLockKey(progress));
|
|
203
|
+
if (await writeDelta({ ctx, progress, optional: transactionOptions }))
|
|
204
|
+
return true;
|
|
205
|
+
return writeFullCheckpoint({ ctx, progress, optional: transactionOptions });
|
|
206
|
+
});
|
|
207
|
+
if (persisted)
|
|
208
|
+
optional.onPersisted?.(receipt);
|
|
209
|
+
return written;
|
|
210
|
+
}
|
|
211
|
+
/** One bounded existence read, across owners and engines. Stale active rows conservatively
|
|
212
|
+
* keep the host awake; recovery belongs to the serving boot, never an idle probe.
|
|
213
|
+
* @complexity O(log n) covering-index lookup for n messages; O(1) returned space, no payload reads.
|
|
214
|
+
*/
|
|
215
|
+
async function anyActiveRun({ kernel }) {
|
|
216
|
+
const row = await kernel.run(db => db.selectFrom("ai_chat_messages").select("id")
|
|
217
|
+
.where("role", "=", "assistant")
|
|
218
|
+
// Keep the fixed literal predicate identical to the partial index. Parameterized IN
|
|
219
|
+
// cannot establish SQLite's partial-index implication at plan time.
|
|
220
|
+
.where(sql `run_status in ('queued', 'running')`)
|
|
221
|
+
.limit(1).executeTakeFirst());
|
|
222
|
+
return row !== undefined;
|
|
223
|
+
}
|
|
224
|
+
/** The content and events a settlement writes: the longer text wins, saved tool barriers survive. */
|
|
225
|
+
function settledProjection({ saved, settlement }, _optional = {}) {
|
|
226
|
+
const content = settlement.content.length >= saved.content.length ? settlement.content : saved.content;
|
|
227
|
+
let events = keepToolCheckpoints(readEvents(saved.events_json), settlement.events);
|
|
228
|
+
if (content !== settlement.content) {
|
|
229
|
+
events = retainSavedEvents(readEvents(saved.events_json), settlement.events);
|
|
230
|
+
if (!events.some((event) => event.kind === "text"))
|
|
231
|
+
events.unshift({ kind: "text", text: saved.content });
|
|
123
232
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
233
|
+
return { content, events };
|
|
234
|
+
}
|
|
235
|
+
/** The terminal write of a settlement; false when the guarded update matched no row. */
|
|
236
|
+
async function writeTerminal({ kernel, settlement, projection }) {
|
|
237
|
+
const result = await kernel.run((db) => db
|
|
238
|
+
.updateTable("ai_chat_messages")
|
|
239
|
+
.set({
|
|
240
|
+
content: projection.content,
|
|
241
|
+
events_json: JSON.stringify(projection.events),
|
|
242
|
+
run_status: settlement.status,
|
|
243
|
+
ended_at: settlement.endedAt,
|
|
244
|
+
})
|
|
245
|
+
.where(activeRunPredicate({ run: settlement }))
|
|
246
|
+
.executeTakeFirst());
|
|
247
|
+
return Number(result.numUpdatedRows) !== 0;
|
|
248
|
+
}
|
|
249
|
+
async function touchChat({ kernel, conversationId, at }) {
|
|
250
|
+
await kernel.run((db) => db
|
|
251
|
+
.updateTable("ai_chats")
|
|
252
|
+
.set({ updated_at: at })
|
|
253
|
+
.where("id", "=", conversationId)
|
|
254
|
+
.execute());
|
|
255
|
+
}
|
|
256
|
+
async function settleRun({ kernel, settlement }) {
|
|
257
|
+
return kernel.transaction(async () => {
|
|
258
|
+
await kernel.lockKey(runLockKey(settlement));
|
|
259
|
+
const saved = await kernel.run((db) => db.selectFrom("ai_chat_messages").select(["content", "events_json"])
|
|
260
|
+
.where(activeRunPredicate({ run: settlement })).executeTakeFirst());
|
|
261
|
+
if (!saved)
|
|
132
262
|
return false;
|
|
133
|
-
|
|
134
|
-
.set({ content: progress.content, events_json: spliceEventsJson(delta),
|
|
135
|
-
run_status: sql `case when run_status = 'queued' then 'running' else run_status end` })
|
|
136
|
-
.where(activeRunPredicate({ run: progress }))
|
|
137
|
-
.where(sql `${version} = ${previous.version}`)
|
|
138
|
-
.where(sql `length(events_json) = ${expected}`)
|
|
139
|
-
// BYOK/AG-UI browser upserts can replace a queued/running projection at the same length.
|
|
140
|
-
// Durable tool appends grow the length; recovery replacements also change run_id.
|
|
141
|
-
.where(sql `substr(events_json, length(events_json) - length(cast(${previous.tail} as text)) + 1) = ${previous.tail}`)
|
|
142
|
-
.where(sql `length(content) = ${previous.contentLength}`)
|
|
143
|
-
.returning([sql `length(events_json)`.as("length"), sql `length(content)`.as("contentLength"), returnedVersion.as("version")])
|
|
144
|
-
.executeTakeFirst());
|
|
145
|
-
if (!result)
|
|
263
|
+
if (!await writeTerminal({ kernel, settlement, projection: settledProjection({ saved, settlement }) }))
|
|
146
264
|
return false;
|
|
147
|
-
|
|
148
|
-
await recordProgress({ progress });
|
|
149
|
-
await notifyPersisted({ progress, optional, length: Number(result.length), contentLength: Number(result.contentLength), nativeVersion: result.version, exact: true });
|
|
265
|
+
await touchChat({ kernel, conversationId: settlement.conversationId, at: settlement.endedAt });
|
|
150
266
|
return true;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
.
|
|
172
|
-
|
|
173
|
-
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
async function selectStuckRuns({ kernel }) {
|
|
270
|
+
return kernel.run((db) => db
|
|
271
|
+
.selectFrom("ai_chat_messages")
|
|
272
|
+
.innerJoin("ai_chats", "ai_chats.id", "ai_chat_messages.conversation_id")
|
|
273
|
+
.select(["ai_chat_messages.id", "conversation_id", "run_id", "run_status", "content", "events_json", "owner_kind", "owner_id"])
|
|
274
|
+
.where("ai_chat_messages.role", "=", "assistant")
|
|
275
|
+
.where("ai_chat_messages.run_status", "in", ["queued", "running"])
|
|
276
|
+
.orderBy("ai_chat_messages.id")
|
|
277
|
+
.execute());
|
|
278
|
+
}
|
|
279
|
+
/** The persisted owner and run stub the recovery port decides on. */
|
|
280
|
+
function interruptedTurn({ row }, _optional = {}) {
|
|
281
|
+
return {
|
|
282
|
+
principalId: row.owner_kind === "user" ? row.owner_id : null,
|
|
283
|
+
conversationId: row.conversation_id,
|
|
284
|
+
message: {
|
|
285
|
+
id: row.id, role: "assistant", content: row.content, events: readEvents(row.events_json),
|
|
286
|
+
...(row.run_id ? { runId: row.run_id } : {}),
|
|
287
|
+
runStatus: row.run_status,
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/** The row of exactly this stuck run, still not terminal. */
|
|
292
|
+
function stuckRowPredicate({ row }, _optional = {}) {
|
|
293
|
+
return (eb) => eb.and([
|
|
294
|
+
eb("id", "=", row.id), eb("conversation_id", "=", row.conversation_id), eb("role", "=", "assistant"),
|
|
295
|
+
row.run_id === null ? eb("run_id", "is", null) : eb("run_id", "=", row.run_id),
|
|
296
|
+
notTerminal(eb),
|
|
297
|
+
]);
|
|
298
|
+
}
|
|
299
|
+
/** A legacy stub without an attempt id, or a host without durable recovery, cannot ever
|
|
300
|
+
* be adopted. Preserve the latest checkpoint under the same lock as settle: discovery's
|
|
301
|
+
* snapshot may be old, and acceptance/recovery may have replaced its run id meanwhile. */
|
|
302
|
+
async function cancelStuckRun({ ctx, row, required }) {
|
|
303
|
+
const { kernel } = ctx;
|
|
304
|
+
return kernel.transaction(async () => {
|
|
305
|
+
await kernel.lockKey(runLockKey({ conversationId: row.conversation_id, messageId: row.id, runId: row.run_id ?? "" }));
|
|
306
|
+
const matches = stuckRowPredicate({ row });
|
|
307
|
+
const current = await kernel.run((db) => db.selectFrom("ai_chat_messages").select("events_json")
|
|
308
|
+
.where(matches).executeTakeFirst());
|
|
309
|
+
if (!current)
|
|
174
310
|
return false;
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
// multi-MB column and recovery budget exactly as the guarded UPDATE would have.
|
|
178
|
-
// Under this lock the row was just matched by the update's own predicate, so the update
|
|
179
|
-
// would match (true); returning true without writing preserves that contract.
|
|
180
|
-
if (plan.unchanged) {
|
|
181
|
-
await notifyPersisted({ progress, optional, length: Number(current.length), contentLength: Number(current.contentLength), nativeVersion: current.version, exact: plan.exact });
|
|
182
|
-
return true;
|
|
183
|
-
}
|
|
311
|
+
const endedAt = required.now ?? ctx.now();
|
|
312
|
+
const events = [...readEvents(current.events_json), { kind: "status", label: "Stopped. Saved work is above." }];
|
|
184
313
|
const result = await kernel.run((db) => db.updateTable("ai_chat_messages")
|
|
185
|
-
.set({
|
|
186
|
-
.where(
|
|
187
|
-
|
|
188
|
-
if (!result)
|
|
314
|
+
.set({ run_status: "canceled", ended_at: endedAt, events_json: JSON.stringify(events) })
|
|
315
|
+
.where(matches).executeTakeFirst());
|
|
316
|
+
if (Number(result.numUpdatedRows) === 0)
|
|
189
317
|
return false;
|
|
190
|
-
|
|
191
|
-
await recordProgress({ progress });
|
|
192
|
-
await notifyPersisted({ progress, optional, length: Number(result.length), contentLength: Number(result.contentLength), nativeVersion: result.version, exact: plan.exact });
|
|
318
|
+
await touchChat({ kernel, conversationId: row.conversation_id, at: endedAt });
|
|
193
319
|
return true;
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* The host may own a class of turns whose lifecycle must not race generic boot repair (a
|
|
324
|
+
* routine run is recorded Interrupted, never re-run). Admission runs outside any write
|
|
325
|
+
* transaction and fails closed: a throwing port leaves the turn alone, and the log carries
|
|
326
|
+
* only a code, never the error text, which could echo prompt or context.
|
|
327
|
+
*/
|
|
328
|
+
async function admitSafely({ ctx, turn, optional }) {
|
|
329
|
+
try {
|
|
330
|
+
return await optional.admit?.({ turn }, {}) ?? 'recover';
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
ctx.log('CHAT_RUN_RECOVERY_ADMISSION_FAILED');
|
|
334
|
+
return 'leave-owned';
|
|
194
335
|
}
|
|
336
|
+
}
|
|
337
|
+
async function reconcileStuckRuns({ ctx, required, optional }) {
|
|
338
|
+
const stuck = await selectStuckRuns({ kernel: ctx.kernel });
|
|
339
|
+
let count = 0;
|
|
340
|
+
for (const row of stuck) {
|
|
341
|
+
const turn = interruptedTurn({ row });
|
|
342
|
+
if ((await admitSafely({ ctx, turn, optional })) === 'leave-owned')
|
|
343
|
+
continue;
|
|
344
|
+
const dispatched = await optional.recover?.(turn);
|
|
345
|
+
if (dispatched || await cancelStuckRun({ ctx, row, required }))
|
|
346
|
+
count += 1;
|
|
347
|
+
}
|
|
348
|
+
return count;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* @param store the chat kernel, or the open `chat.db` handle `createChatStoreFactory` also wraps.
|
|
352
|
+
* @param now Injectable epoch-millisecond clock for progress stamps and the default cancel time.
|
|
353
|
+
* @param log Code-only sink for a failed recovery admission; never receives error text.
|
|
354
|
+
* @complexity indexed guards; checkpoints cost O(delta bytes) plus a SQLite scalar receipt read,
|
|
355
|
+
* or O(saved + incoming bytes) on fallback. Reconcile costs O(stuck rows + their event bytes).
|
|
356
|
+
*/
|
|
357
|
+
export function createChatRunLedger({ kernel: hostKernel, isDaemonRunId }, { now = () => Date.now(), log = (code) => console.error(code) } = {}) {
|
|
358
|
+
const kernel = chatKernelTables({ kernel: hostKernel }, {});
|
|
359
|
+
const ctx = ledgerContext({ kernel, now, log });
|
|
195
360
|
return {
|
|
196
361
|
durable: createDurableRunStore({ kernel, isDaemonRunId }, {}),
|
|
197
|
-
|
|
198
|
-
* keep the host awake; recovery belongs to the serving boot, never an idle probe.
|
|
199
|
-
* @complexity O(log n) covering-index lookup for n messages; O(1) returned space, no payload reads.
|
|
200
|
-
*/
|
|
201
|
-
async hasActiveRuns(_required = {}, _optional = {}) {
|
|
202
|
-
const row = await kernel.run(db => db.selectFrom("ai_chat_messages").select("id")
|
|
203
|
-
.where("role", "=", "assistant")
|
|
204
|
-
// Keep the fixed literal predicate identical to the partial index. Parameterized IN
|
|
205
|
-
// cannot establish SQLite's partial-index implication at plan time.
|
|
206
|
-
.where(sql `run_status in ('queued', 'running')`)
|
|
207
|
-
.limit(1).executeTakeFirst());
|
|
208
|
-
return row !== undefined;
|
|
209
|
-
},
|
|
362
|
+
hasActiveRuns: (_required = {}, _optional = {}) => anyActiveRun({ kernel }),
|
|
210
363
|
unlessSettled({ run, write }, _optional = {}) {
|
|
211
364
|
return kernel.transaction(async () => {
|
|
212
365
|
await kernel.lockKey(runLockKey(run));
|
|
213
|
-
if (await isSettled(run))
|
|
366
|
+
if (await isSettled({ kernel, run }))
|
|
214
367
|
return { written: false };
|
|
215
368
|
return { written: true, value: await write() };
|
|
216
369
|
});
|
|
217
370
|
},
|
|
218
|
-
settle(settlement, _optional = {}) {
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
const saved = await kernel.run((db) => db.selectFrom("ai_chat_messages").select(["content", "events_json"])
|
|
222
|
-
.where(activeRunPredicate({ run: settlement })).executeTakeFirst());
|
|
223
|
-
if (!saved)
|
|
224
|
-
return false;
|
|
225
|
-
const content = settlement.content.length >= saved.content.length ? settlement.content : saved.content;
|
|
226
|
-
let events = keepToolCheckpoints(readEvents(saved.events_json), settlement.events);
|
|
227
|
-
if (content !== settlement.content) {
|
|
228
|
-
events = retainSavedEvents(readEvents(saved.events_json), settlement.events);
|
|
229
|
-
if (!events.some((event) => event.kind === "text"))
|
|
230
|
-
events.unshift({ kind: "text", text: saved.content });
|
|
231
|
-
}
|
|
232
|
-
const result = await kernel.run((db) => db
|
|
233
|
-
.updateTable("ai_chat_messages")
|
|
234
|
-
.set({
|
|
235
|
-
content,
|
|
236
|
-
events_json: JSON.stringify(events),
|
|
237
|
-
run_status: settlement.status,
|
|
238
|
-
ended_at: settlement.endedAt,
|
|
239
|
-
})
|
|
240
|
-
.where(activeRunPredicate({ run: settlement }))
|
|
241
|
-
.executeTakeFirst());
|
|
242
|
-
if (Number(result.numUpdatedRows) === 0)
|
|
243
|
-
return false;
|
|
244
|
-
await kernel.run((db) => db
|
|
245
|
-
.updateTable("ai_chats")
|
|
246
|
-
.set({ updated_at: settlement.endedAt })
|
|
247
|
-
.where("id", "=", settlement.conversationId)
|
|
248
|
-
.execute());
|
|
249
|
-
return true;
|
|
250
|
-
});
|
|
251
|
-
},
|
|
252
|
-
async checkpoint(progress, optional = {}) {
|
|
253
|
-
let persisted = false;
|
|
254
|
-
let receipt;
|
|
255
|
-
// Publish the watch receipt only after COMMIT. A rollback must not advance its CAS base.
|
|
256
|
-
const transactionOptions = optional.onPersisted
|
|
257
|
-
? { ...optional, onPersisted: (value) => { persisted = true; receipt = value; } } : optional;
|
|
258
|
-
const written = await kernel.transaction(async () => {
|
|
259
|
-
await kernel.lockKey(runLockKey(progress));
|
|
260
|
-
if (await writeDelta({ progress, optional: transactionOptions }))
|
|
261
|
-
return true;
|
|
262
|
-
return writeFullCheckpoint({ progress, optional: transactionOptions });
|
|
263
|
-
});
|
|
264
|
-
if (persisted)
|
|
265
|
-
optional.onPersisted?.(receipt);
|
|
266
|
-
return written;
|
|
267
|
-
},
|
|
268
|
-
async reconcileInterrupted(required = {}, optional = {}) {
|
|
269
|
-
const stuck = await kernel.run((db) => db
|
|
270
|
-
.selectFrom("ai_chat_messages")
|
|
271
|
-
.innerJoin("ai_chats", "ai_chats.id", "ai_chat_messages.conversation_id")
|
|
272
|
-
.select(["ai_chat_messages.id", "conversation_id", "run_id", "run_status", "content", "events_json", "owner_kind", "owner_id"])
|
|
273
|
-
.where("ai_chat_messages.role", "=", "assistant")
|
|
274
|
-
.where("ai_chat_messages.run_status", "in", ["queued", "running"])
|
|
275
|
-
.orderBy("ai_chat_messages.id")
|
|
276
|
-
.execute());
|
|
277
|
-
let count = 0;
|
|
278
|
-
for (const row of stuck) {
|
|
279
|
-
const dispatched = await optional.recover?.({
|
|
280
|
-
principalId: row.owner_kind === "user" ? row.owner_id : null,
|
|
281
|
-
conversationId: row.conversation_id,
|
|
282
|
-
message: {
|
|
283
|
-
id: row.id, role: "assistant", content: row.content, events: readEvents(row.events_json),
|
|
284
|
-
...(row.run_id ? { runId: row.run_id } : {}),
|
|
285
|
-
runStatus: row.run_status,
|
|
286
|
-
},
|
|
287
|
-
});
|
|
288
|
-
if (dispatched) {
|
|
289
|
-
count += 1;
|
|
290
|
-
continue;
|
|
291
|
-
}
|
|
292
|
-
// A legacy stub without an attempt id, or a host without durable recovery, cannot ever
|
|
293
|
-
// be adopted. Preserve the latest checkpoint under the same lock as settle: discovery's
|
|
294
|
-
// snapshot may be old, and acceptance/recovery may have replaced its run id meanwhile.
|
|
295
|
-
const canceled = await kernel.transaction(async () => {
|
|
296
|
-
await kernel.lockKey(runLockKey({ conversationId: row.conversation_id, messageId: row.id, runId: row.run_id ?? "" }));
|
|
297
|
-
const matches = (eb) => eb.and([
|
|
298
|
-
eb("id", "=", row.id), eb("conversation_id", "=", row.conversation_id), eb("role", "=", "assistant"),
|
|
299
|
-
row.run_id === null ? eb("run_id", "is", null) : eb("run_id", "=", row.run_id),
|
|
300
|
-
notTerminal(eb),
|
|
301
|
-
]);
|
|
302
|
-
const current = await kernel.run((db) => db.selectFrom("ai_chat_messages").select("events_json")
|
|
303
|
-
.where(matches).executeTakeFirst());
|
|
304
|
-
if (!current)
|
|
305
|
-
return false;
|
|
306
|
-
const endedAt = required.now ?? now();
|
|
307
|
-
const events = [...readEvents(current.events_json), { kind: "status", label: "Stopped. Saved work is above." }];
|
|
308
|
-
const result = await kernel.run((db) => db.updateTable("ai_chat_messages")
|
|
309
|
-
.set({ run_status: "canceled", ended_at: endedAt, events_json: JSON.stringify(events) })
|
|
310
|
-
.where(matches).executeTakeFirst());
|
|
311
|
-
if (Number(result.numUpdatedRows) === 0)
|
|
312
|
-
return false;
|
|
313
|
-
await kernel.run((db) => db.updateTable("ai_chats").set({ updated_at: endedAt })
|
|
314
|
-
.where("id", "=", row.conversation_id).execute());
|
|
315
|
-
return true;
|
|
316
|
-
});
|
|
317
|
-
if (canceled)
|
|
318
|
-
count += 1;
|
|
319
|
-
}
|
|
320
|
-
return count;
|
|
321
|
-
},
|
|
371
|
+
settle: (settlement, _optional = {}) => settleRun({ kernel, settlement }),
|
|
372
|
+
checkpoint: (progress, optional = {}) => checkpointRun({ ctx, progress, optional }),
|
|
373
|
+
reconcileInterrupted: (required = {}, optional = {}) => reconcileStuckRuns({ ctx, required, optional }),
|
|
322
374
|
};
|
|
323
375
|
}
|
|
324
376
|
function activeRunPredicate({ run }) {
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { ChatKernel } from '../runtime/kernel.js';
|
|
2
|
+
import type { ChatOwnerScope } from '../ports.js';
|
|
3
|
+
export declare function createChatBulkDeletion({ kernel, scope: inputScope, now, openConversations }: {
|
|
4
|
+
kernel: ChatKernel;
|
|
5
|
+
scope: ChatOwnerScope;
|
|
6
|
+
now: () => number;
|
|
7
|
+
openConversations: () => Promise<ReadonlySet<string> | undefined>;
|
|
8
|
+
}, { previewLimit }?: {
|
|
9
|
+
previewLimit?: number | undefined;
|
|
10
|
+
}): {
|
|
11
|
+
preview({ before }: {
|
|
12
|
+
before: number;
|
|
13
|
+
}, _optional?: {}): Promise<{
|
|
14
|
+
ids: string[];
|
|
15
|
+
count: number;
|
|
16
|
+
bytes: number;
|
|
17
|
+
before: number;
|
|
18
|
+
kept: {
|
|
19
|
+
id: string;
|
|
20
|
+
title: string | null;
|
|
21
|
+
reason: string;
|
|
22
|
+
}[];
|
|
23
|
+
}>;
|
|
24
|
+
apply({ ids, before }: {
|
|
25
|
+
ids: readonly string[];
|
|
26
|
+
before?: number;
|
|
27
|
+
}, _optional?: {}): Promise<{
|
|
28
|
+
deleted: string[];
|
|
29
|
+
kept: {
|
|
30
|
+
id: string;
|
|
31
|
+
title: string | null;
|
|
32
|
+
reason: string;
|
|
33
|
+
}[];
|
|
34
|
+
}>;
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=bulk-deletion.d.ts.map
|