@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
|
@@ -4,6 +4,130 @@ import { readSseFrames, runContentFromEvents, runEventsForSave, runInterruptedNo
|
|
|
4
4
|
function endStatus({ failed, terminal }, _optional = {}) {
|
|
5
5
|
return failed && terminal === "succeeded" ? "failed" : terminal;
|
|
6
6
|
}
|
|
7
|
+
/** Pure: the one atomic ledger write that ends a watched run. */
|
|
8
|
+
function settlementOf({ watch, status, events, endedAt }, _optional = {}) {
|
|
9
|
+
return {
|
|
10
|
+
conversationId: watch.conversationId,
|
|
11
|
+
messageId: watch.messageId,
|
|
12
|
+
runId: watch.runId,
|
|
13
|
+
status,
|
|
14
|
+
content: runContentFromEvents({ events }),
|
|
15
|
+
events: runEventsForSave({ events }),
|
|
16
|
+
endedAt,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/** Pure: the growth-only progress write for a watched run's events so far. */
|
|
20
|
+
function progressOf({ watch }, _optional = {}) {
|
|
21
|
+
return {
|
|
22
|
+
conversationId: watch.conversationId,
|
|
23
|
+
messageId: watch.messageId,
|
|
24
|
+
runId: watch.runId,
|
|
25
|
+
content: runContentFromEvents({ events: watch.events }),
|
|
26
|
+
events: runEventsForSave({ events: watch.events }),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** Pure eligibility: only a non-terminal assistant message held by a daemon run is followed. */
|
|
30
|
+
function isWatchable({ message, runIdClassifier }, _optional = {}) {
|
|
31
|
+
const runId = message.runId;
|
|
32
|
+
if (message.role !== "assistant" || !runId || !runIdClassifier.isDaemonRunId({ runId }))
|
|
33
|
+
return false;
|
|
34
|
+
return message.runStatus !== undefined && !isTerminalRunStatus({ status: message.runStatus });
|
|
35
|
+
}
|
|
36
|
+
function newWatch({ principalId, conversationId, message, runId }, _optional = {}) {
|
|
37
|
+
return {
|
|
38
|
+
principalId,
|
|
39
|
+
conversationId,
|
|
40
|
+
messageId: message.id,
|
|
41
|
+
runId,
|
|
42
|
+
events: [],
|
|
43
|
+
failed: false,
|
|
44
|
+
checkpointedEvents: 0,
|
|
45
|
+
checkpointedAt: Number.NEGATIVE_INFINITY,
|
|
46
|
+
checkpointPending: false,
|
|
47
|
+
terminal: false,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** The connection's event body, or why it cannot be followed. Non-success bodies are cancelled. */
|
|
51
|
+
async function openStream({ daemon, watch }, _optional = {}) {
|
|
52
|
+
const response = await daemon.openEvents({ runId: watch.runId, principalId: watch.principalId });
|
|
53
|
+
if (response.ok && response.body)
|
|
54
|
+
return { kind: "open", body: response.body };
|
|
55
|
+
await response.body?.cancel().catch(() => undefined);
|
|
56
|
+
return response.status === 404 ? { kind: "gone" } : { kind: "dropped" };
|
|
57
|
+
}
|
|
58
|
+
async function consumeFrames({ watch, body, notices, onFrame }, _optional = {}) {
|
|
59
|
+
// Each connection replays the complete history, rather than appending duplicate deltas.
|
|
60
|
+
watch.events = [];
|
|
61
|
+
watch.failed = false;
|
|
62
|
+
const carry = {};
|
|
63
|
+
for await (const frame of readSseFrames({ body })) {
|
|
64
|
+
const outcome = translateRunFrame({ kind: frame.event, raw: frame.data, notices }, { carry });
|
|
65
|
+
watch.events.push(...outcome.events);
|
|
66
|
+
if (outcome.error)
|
|
67
|
+
watch.failed = true;
|
|
68
|
+
if (outcome.terminal) {
|
|
69
|
+
watch.terminal = true;
|
|
70
|
+
return { kind: "ended", status: endStatus({ failed: watch.failed, terminal: outcome.terminal }) };
|
|
71
|
+
}
|
|
72
|
+
onFrame();
|
|
73
|
+
}
|
|
74
|
+
return { kind: "dropped" };
|
|
75
|
+
}
|
|
76
|
+
async function readWatchStream({ daemon, watch, notices, onFrame }, _optional = {}) {
|
|
77
|
+
const opened = await openStream({ daemon, watch });
|
|
78
|
+
return opened.kind === "open" ? consumeFrames({ watch, body: opened.body, notices, onFrame }) : opened;
|
|
79
|
+
}
|
|
80
|
+
function clearTrailingTimer({ watch, scheduler }, _optional = {}) {
|
|
81
|
+
if (watch.trailing)
|
|
82
|
+
scheduler.cancel({ handle: watch.trailing.handle });
|
|
83
|
+
watch.trailing = undefined;
|
|
84
|
+
}
|
|
85
|
+
function scheduleTrailing({ watch, wait, deps }, _optional = {}) {
|
|
86
|
+
if (watch.trailing)
|
|
87
|
+
return;
|
|
88
|
+
watch.trailing = { handle: deps.scheduler.schedule({ task: () => {
|
|
89
|
+
watch.trailing = undefined;
|
|
90
|
+
void checkpointWatch({ watch, deps });
|
|
91
|
+
}, delayMs: wait }) };
|
|
92
|
+
}
|
|
93
|
+
// Coalesce one pending write and one trailing timer. Never block frame consumption on storage.
|
|
94
|
+
// Growth-only checkpointing avoids shrinking a saved answer during replay from event zero.
|
|
95
|
+
async function checkpointWatch({ watch, deps }, _optional = {}) {
|
|
96
|
+
if (watch.terminal || watch.checkpointPending)
|
|
97
|
+
return;
|
|
98
|
+
if (watch.events.length <= watch.checkpointedEvents)
|
|
99
|
+
return;
|
|
100
|
+
const wait = deps.intervalMs - (deps.now() - watch.checkpointedAt);
|
|
101
|
+
if (wait > 0) {
|
|
102
|
+
scheduleTrailing({ watch, wait, deps });
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
clearTrailingTimer({ watch, scheduler: deps.scheduler });
|
|
106
|
+
watch.checkpointedEvents = watch.events.length;
|
|
107
|
+
watch.checkpointedAt = deps.now();
|
|
108
|
+
watch.checkpointPending = true;
|
|
109
|
+
await deps.ledger
|
|
110
|
+
.checkpoint(progressOf({ watch }))
|
|
111
|
+
.catch((error) => deps.report({ operation: "checkpoint", runId: watch.runId, error }))
|
|
112
|
+
.finally(() => {
|
|
113
|
+
watch.checkpointPending = false;
|
|
114
|
+
void checkpointWatch({ watch, deps });
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
async function followWatch({ watch, readStream, settle, settleInterrupted, daemon, scheduler, maxReconnects, reconnectDelayMs }) {
|
|
118
|
+
for (let attempt = 0; attempt <= maxReconnects; attempt += 1) {
|
|
119
|
+
const result = await readStream(watch).catch(() => ({ kind: "dropped" }));
|
|
120
|
+
if (result.kind === "ended")
|
|
121
|
+
return settle(watch, result.status, watch.events);
|
|
122
|
+
if (result.kind === "gone")
|
|
123
|
+
return settleInterrupted(watch);
|
|
124
|
+
if ((await daemon.runStatus({ runId: watch.runId, principalId: watch.principalId })) === 404)
|
|
125
|
+
return settleInterrupted(watch);
|
|
126
|
+
await scheduler.sleep({ delayMs: reconnectDelayMs });
|
|
127
|
+
}
|
|
128
|
+
// Exhaustion alone is not evidence of a terminal run; the host can reattach or repair at boot.
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
7
131
|
/** Follow replayable run streams and save through atomic host ledger operations.
|
|
8
132
|
* The host retains authorization, owner scope, kernel transactions, boot reconciliation, HTTP
|
|
9
133
|
* credentials and excluded run-ID prefixes. Replay starts at zero; error-before-success and
|
|
@@ -26,128 +150,27 @@ export function createAssistantRunFinalizer(args, options = {}) {
|
|
|
26
150
|
catch { /* The host owns reporting failures. */ }
|
|
27
151
|
}
|
|
28
152
|
const active = new Map();
|
|
29
|
-
|
|
30
|
-
if (watch.trailing)
|
|
31
|
-
scheduler.cancel({ handle: watch.trailing.handle });
|
|
32
|
-
watch.trailing = undefined;
|
|
33
|
-
}
|
|
153
|
+
const clearTrailing = (watch) => clearTrailingTimer({ watch, scheduler });
|
|
34
154
|
async function settle(watch, status, events) {
|
|
35
155
|
watch.terminal = true;
|
|
36
156
|
clearTrailing(watch);
|
|
37
|
-
await args.ledger.settle({
|
|
38
|
-
conversationId: watch.conversationId,
|
|
39
|
-
messageId: watch.messageId,
|
|
40
|
-
runId: watch.runId,
|
|
41
|
-
status,
|
|
42
|
-
content: runContentFromEvents({ events }),
|
|
43
|
-
events: runEventsForSave({ events }),
|
|
44
|
-
endedAt: now(),
|
|
45
|
-
});
|
|
157
|
+
await args.ledger.settle(settlementOf({ watch, status, events, endedAt: now() }));
|
|
46
158
|
}
|
|
47
159
|
function settleInterrupted(watch) {
|
|
48
160
|
return settle(watch, "canceled", [...watch.events, runInterruptedNotice({ notice: args.notices.interrupted })]);
|
|
49
161
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
if (watch.terminal || watch.checkpointPending)
|
|
54
|
-
return;
|
|
55
|
-
if (watch.events.length <= watch.checkpointedEvents)
|
|
56
|
-
return;
|
|
57
|
-
const wait = checkpointIntervalMs - (now() - watch.checkpointedAt);
|
|
58
|
-
if (wait > 0) {
|
|
59
|
-
if (!watch.trailing) {
|
|
60
|
-
watch.trailing = { handle: scheduler.schedule({ task: () => {
|
|
61
|
-
watch.trailing = undefined;
|
|
62
|
-
void checkpoint(watch);
|
|
63
|
-
}, delayMs: wait }) };
|
|
64
|
-
}
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
clearTrailing(watch);
|
|
68
|
-
watch.checkpointedEvents = watch.events.length;
|
|
69
|
-
watch.checkpointedAt = now();
|
|
70
|
-
watch.checkpointPending = true;
|
|
71
|
-
await args.ledger
|
|
72
|
-
.checkpoint({
|
|
73
|
-
conversationId: watch.conversationId,
|
|
74
|
-
messageId: watch.messageId,
|
|
75
|
-
runId: watch.runId,
|
|
76
|
-
content: runContentFromEvents({ events: watch.events }),
|
|
77
|
-
events: runEventsForSave({ events: watch.events }),
|
|
78
|
-
})
|
|
79
|
-
.catch((error) => reportError({ operation: "checkpoint", runId: watch.runId, error }))
|
|
80
|
-
.finally(() => {
|
|
81
|
-
watch.checkpointPending = false;
|
|
82
|
-
void checkpoint(watch);
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
/** The connection's event body, or why it cannot be followed. Non-success bodies are cancelled. */
|
|
86
|
-
async function openStream(watch) {
|
|
87
|
-
const response = await daemon.openEvents({ runId: watch.runId, principalId: watch.principalId });
|
|
88
|
-
if (response.ok && response.body)
|
|
89
|
-
return { kind: "open", body: response.body };
|
|
90
|
-
await response.body?.cancel().catch(() => undefined);
|
|
91
|
-
return response.status === 404 ? { kind: "gone" } : { kind: "dropped" };
|
|
92
|
-
}
|
|
93
|
-
async function consumeFrames(watch, body) {
|
|
94
|
-
// Each connection replays the complete history, rather than appending duplicate deltas.
|
|
95
|
-
watch.events = [];
|
|
96
|
-
watch.failed = false;
|
|
97
|
-
const carry = {};
|
|
98
|
-
for await (const frame of readSseFrames({ body })) {
|
|
99
|
-
const outcome = translateRunFrame({ kind: frame.event, raw: frame.data, notices: args.notices }, { carry });
|
|
100
|
-
watch.events.push(...outcome.events);
|
|
101
|
-
if (outcome.error)
|
|
102
|
-
watch.failed = true;
|
|
103
|
-
if (outcome.terminal) {
|
|
104
|
-
watch.terminal = true;
|
|
105
|
-
return { kind: "ended", status: endStatus({ failed: watch.failed, terminal: outcome.terminal }) };
|
|
106
|
-
}
|
|
107
|
-
void checkpoint(watch);
|
|
108
|
-
}
|
|
109
|
-
return { kind: "dropped" };
|
|
110
|
-
}
|
|
111
|
-
async function readStream(watch) {
|
|
112
|
-
const opened = await openStream(watch);
|
|
113
|
-
return opened.kind === "open" ? consumeFrames(watch, opened.body) : opened;
|
|
114
|
-
}
|
|
115
|
-
async function follow(watch) {
|
|
116
|
-
for (let attempt = 0; attempt <= maxReconnects; attempt += 1) {
|
|
117
|
-
const result = await readStream(watch).catch(() => ({ kind: "dropped" }));
|
|
118
|
-
if (result.kind === "ended")
|
|
119
|
-
return settle(watch, result.status, watch.events);
|
|
120
|
-
if (result.kind === "gone")
|
|
121
|
-
return settleInterrupted(watch);
|
|
122
|
-
if ((await daemon.runStatus({ runId: watch.runId, principalId: watch.principalId })) === 404)
|
|
123
|
-
return settleInterrupted(watch);
|
|
124
|
-
await scheduler.sleep({ delayMs: reconnectDelayMs });
|
|
125
|
-
}
|
|
126
|
-
// Exhaustion alone is not evidence of a terminal run; the host can reattach or repair at boot.
|
|
127
|
-
return undefined;
|
|
128
|
-
}
|
|
162
|
+
const checkpointDeps = { ledger: args.ledger, scheduler, now, intervalMs: checkpointIntervalMs, report: reportError };
|
|
163
|
+
const checkpoint = (watch) => checkpointWatch({ watch, deps: checkpointDeps });
|
|
164
|
+
const readStream = (watch) => readWatchStream({ daemon, watch, notices: args.notices, onFrame: () => { void checkpoint(watch); } });
|
|
129
165
|
return {
|
|
130
166
|
watch({ principalId, conversationId, message }) {
|
|
131
|
-
|
|
132
|
-
if (message.role !== "assistant" || !runId || !args.runIdClassifier.isDaemonRunId({ runId }))
|
|
133
|
-
return;
|
|
134
|
-
if (message.runStatus === undefined || isTerminalRunStatus({ status: message.runStatus }))
|
|
167
|
+
if (!isWatchable({ message, runIdClassifier: args.runIdClassifier }))
|
|
135
168
|
return;
|
|
169
|
+
const runId = message.runId;
|
|
136
170
|
if (active.has(runId))
|
|
137
171
|
return;
|
|
138
|
-
const watch = {
|
|
139
|
-
|
|
140
|
-
conversationId,
|
|
141
|
-
messageId: message.id,
|
|
142
|
-
runId,
|
|
143
|
-
events: [],
|
|
144
|
-
failed: false,
|
|
145
|
-
checkpointedEvents: 0,
|
|
146
|
-
checkpointedAt: Number.NEGATIVE_INFINITY,
|
|
147
|
-
checkpointPending: false,
|
|
148
|
-
terminal: false,
|
|
149
|
-
};
|
|
150
|
-
const done = follow(watch)
|
|
172
|
+
const watch = newWatch({ principalId, conversationId, message, runId });
|
|
173
|
+
const done = followWatch({ watch, readStream, settle, settleInterrupted, daemon, scheduler, maxReconnects, reconnectDelayMs })
|
|
151
174
|
.catch((error) => {
|
|
152
175
|
reportError({ operation: "watch", runId, error });
|
|
153
176
|
})
|
|
@@ -1,17 +1,15 @@
|
|
|
1
1
|
import { rows } from '@jini-ai/core/contracts/storage';
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
* run summary, and total accumulated run duration across all terminal runs.
|
|
6
|
-
*/
|
|
7
|
-
function conversationSummarySql(filterColumn) {
|
|
8
|
-
return `WITH selected_conversations AS (
|
|
2
|
+
/** @internal CTE selecting the conversations that match `filterColumn = ?`; every other CTE joins back to it. */
|
|
3
|
+
function selectedConversationsCte(filterColumn) {
|
|
4
|
+
return `selected_conversations AS (
|
|
9
5
|
SELECT id, project_id AS projectId, title, session_mode AS sessionMode,
|
|
10
6
|
created_at AS createdAt, updated_at AS updatedAt
|
|
11
7
|
FROM conversations
|
|
12
8
|
WHERE ${filterColumn} = ?
|
|
13
|
-
)
|
|
14
|
-
|
|
9
|
+
)`;
|
|
10
|
+
}
|
|
11
|
+
/** @internal CTE holding each selected conversation's most recent assistant message that carries a run status. */
|
|
12
|
+
const LATEST_RUNS_CTE = `latest_runs AS (
|
|
15
13
|
SELECT conversation_id AS conversationId,
|
|
16
14
|
run_status AS latestRunStatus,
|
|
17
15
|
started_at AS latestRunStartedAt,
|
|
@@ -33,15 +31,18 @@ function conversationSummarySql(filterColumn) {
|
|
|
33
31
|
AND m.run_status IS NOT NULL
|
|
34
32
|
)
|
|
35
33
|
WHERE rn = 1
|
|
36
|
-
)
|
|
37
|
-
|
|
34
|
+
)`;
|
|
35
|
+
/** @internal CTE counting every message of each selected conversation. */
|
|
36
|
+
const MESSAGE_COUNTS_CTE = `message_counts AS (
|
|
38
37
|
SELECT m.conversation_id AS conversationId,
|
|
39
38
|
COUNT(*) AS messageCount
|
|
40
39
|
FROM messages m
|
|
41
40
|
JOIN selected_conversations c ON c.id = m.conversation_id
|
|
42
41
|
GROUP BY m.conversation_id
|
|
43
|
-
)
|
|
44
|
-
|
|
42
|
+
)`;
|
|
43
|
+
/** @internal CTE summing the duration of each selected conversation's terminal assistant runs. */
|
|
44
|
+
function totalRunDurationsCte() {
|
|
45
|
+
return `total_run_durations AS (
|
|
45
46
|
SELECT m.conversation_id AS conversationId,
|
|
46
47
|
SUM(${TERMINAL_RUN_DURATION_SQL}) AS totalDurationMs
|
|
47
48
|
FROM messages m
|
|
@@ -49,8 +50,10 @@ function conversationSummarySql(filterColumn) {
|
|
|
49
50
|
WHERE m.role = 'assistant'
|
|
50
51
|
AND m.run_status IN ('succeeded', 'failed', 'canceled')
|
|
51
52
|
GROUP BY m.conversation_id
|
|
52
|
-
)
|
|
53
|
-
|
|
53
|
+
)`;
|
|
54
|
+
}
|
|
55
|
+
/** @internal Final projection joining the selected conversations to the three summary CTEs. */
|
|
56
|
+
const SUMMARY_SELECT = `SELECT c.id, c.projectId, c.title, c.sessionMode, c.createdAt, c.updatedAt,
|
|
54
57
|
COALESCE(mc.messageCount, 0) AS messageCount,
|
|
55
58
|
lr.latestRunStatus, lr.latestRunStartedAt,
|
|
56
59
|
lr.latestRunEndedAt, lr.latestRunEventsJson,
|
|
@@ -59,6 +62,14 @@ function conversationSummarySql(filterColumn) {
|
|
|
59
62
|
LEFT JOIN latest_runs lr ON lr.conversationId = c.id
|
|
60
63
|
LEFT JOIN message_counts mc ON mc.conversationId = c.id
|
|
61
64
|
LEFT JOIN total_run_durations trd ON trd.conversationId = c.id`;
|
|
65
|
+
/**
|
|
66
|
+
* @internal Builds the summary query shared by `listConversations` and `getConversation`: every
|
|
67
|
+
* conversation matching `filterColumn = ?`, each enriched with message count, the latest assistant
|
|
68
|
+
* run summary, and total accumulated run duration across all terminal runs.
|
|
69
|
+
*/
|
|
70
|
+
function conversationSummarySql(filterColumn) {
|
|
71
|
+
const ctes = [selectedConversationsCte(filterColumn), LATEST_RUNS_CTE, MESSAGE_COUNTS_CTE, totalRunDurationsCte()];
|
|
72
|
+
return `WITH ${ctes.join(',\n ')}\n ${SUMMARY_SELECT}`;
|
|
62
73
|
}
|
|
63
74
|
/**
|
|
64
75
|
* Returns all conversations for a project, newest first, each enriched with message count,
|
|
@@ -67,9 +78,10 @@ function conversationSummarySql(filterColumn) {
|
|
|
67
78
|
* @param projectId The project whose conversations to list.
|
|
68
79
|
*/
|
|
69
80
|
export function listConversations({ db, projectId }) {
|
|
70
|
-
|
|
81
|
+
const value = db
|
|
71
82
|
.prepare(`${conversationSummarySql('project_id')}\n ORDER BY c.updatedAt DESC`)
|
|
72
|
-
.all(projectId)
|
|
83
|
+
.all(projectId);
|
|
84
|
+
return rows({ value }).map(normalizeConversation);
|
|
73
85
|
}
|
|
74
86
|
/**
|
|
75
87
|
* Fetches a single conversation by id with its latest run summary and total run duration.
|
|
@@ -19,4 +19,5 @@ export declare function createPgliteChatStore<DB extends ChatDatabase>(required:
|
|
|
19
19
|
export declare function createPgliteChatMaintenance<DB extends ChatDatabase>(required: {
|
|
20
20
|
kernel: StorageKernel<Kysely<DB>, DB>;
|
|
21
21
|
}): ChatHistoryMaintenance;
|
|
22
|
+
export { createChatBulkDeletion } from '../sql/bulk-deletion.js';
|
|
22
23
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -14,4 +14,5 @@ export function createPgliteChatMaintenance(required) {
|
|
|
14
14
|
validateKernel({ kernel: required.kernel, transports: ['pglite', 'pglite-socket'], dialect: 'postgres' });
|
|
15
15
|
return createSqlChatMaintenance(required);
|
|
16
16
|
}
|
|
17
|
+
export { createChatBulkDeletion } from '../sql/bulk-deletion.js';
|
|
17
18
|
//# sourceMappingURL=index.js.map
|
package/dist/store/ports.d.ts
CHANGED
|
@@ -18,6 +18,7 @@ export interface ChatConversation {
|
|
|
18
18
|
readonly updatedAt: number;
|
|
19
19
|
/** Epoch milliseconds; absence means retained until explicitly deleted. */
|
|
20
20
|
readonly expiresAt?: number;
|
|
21
|
+
readonly pinned?: boolean;
|
|
21
22
|
}
|
|
22
23
|
export interface CreateChatConversationInput {
|
|
23
24
|
readonly id: string;
|
|
@@ -80,6 +81,17 @@ export interface ChatStore {
|
|
|
80
81
|
}, optional?: {
|
|
81
82
|
readonly source?: ChatTitleSource;
|
|
82
83
|
}): Promise<ChatConversation | null>;
|
|
84
|
+
setPinned(required: {
|
|
85
|
+
readonly id: string;
|
|
86
|
+
readonly pinned: boolean;
|
|
87
|
+
}, optional?: Record<string, never>): Promise<ChatConversation | null>;
|
|
88
|
+
updateConversation(required: {
|
|
89
|
+
readonly id: string;
|
|
90
|
+
readonly title?: string;
|
|
91
|
+
readonly pinned?: boolean;
|
|
92
|
+
}, optional?: {
|
|
93
|
+
readonly source?: ChatTitleSource;
|
|
94
|
+
}): Promise<ChatConversation | null>;
|
|
83
95
|
touch(required: {
|
|
84
96
|
readonly id: string;
|
|
85
97
|
}, optional?: {
|
|
@@ -19,4 +19,5 @@ export declare function createPostgresChatStore<DB extends ChatDatabase>(require
|
|
|
19
19
|
export declare function createPostgresChatMaintenance<DB extends ChatDatabase>(required: {
|
|
20
20
|
kernel: StorageKernel<Kysely<DB>, DB>;
|
|
21
21
|
}): ChatHistoryMaintenance;
|
|
22
|
+
export { createChatBulkDeletion } from '../sql/bulk-deletion.js';
|
|
22
23
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -14,4 +14,5 @@ export function createPostgresChatMaintenance(required) {
|
|
|
14
14
|
validateKernel({ kernel: required.kernel, transports: ['node-postgres'], dialect: 'postgres' });
|
|
15
15
|
return createSqlChatMaintenance(required);
|
|
16
16
|
}
|
|
17
|
+
export { createChatBulkDeletion } from '../sql/bulk-deletion.js';
|
|
17
18
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { ChatDatabase, ChatKernel } from "./kernel.js";
|
|
2
|
+
/**
|
|
3
|
+
* @file Retention policy `attempt-base` (kind `derived`): clears `assistant_run_attempts.attempt_base_json`
|
|
4
|
+
* of finished runs whose recovery deadline passed long ago.
|
|
5
|
+
*
|
|
6
|
+
* The attempt base is a working copy, not a receipt. It holds the saved events an attempt started
|
|
7
|
+
* from so a live stream can be seeded and a retry can tell old diagnostics from new ones. The
|
|
8
|
+
* message's own `events_json` stays the durable record of what happened and is never touched here;
|
|
9
|
+
* once the run is finished nothing can resume it (`advance` only moves `queued`/`running` runs), so
|
|
10
|
+
* the copy has no reader left. That last claim is only as good as the reader proof in
|
|
11
|
+
* `__tests__/attempt-base-readers.test.ts`, which is why the policy cleans nothing unless the host
|
|
12
|
+
* hands back exactly the list of readers that file proves.
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* Every in-engine reader of an attempt base that `attempt-base-readers.test.ts` drives with a
|
|
16
|
+
* finished, past-deadline attempt and shows to behave identically with `'[]'`. Host-side readers
|
|
17
|
+
* (for example a host's run watcher) are not listed: they cannot be proven from this package, and a
|
|
18
|
+
* host that has its own readers must not claim this list until it proves them too.
|
|
19
|
+
*/
|
|
20
|
+
export declare const ATTEMPT_BASE_READERS: readonly ["chat/core/durable-runs/ports.ts#DurableRunHead.attemptBase", "chat/store/runtime/kernel.ts#assistant_run_attempts.attempt_base_json", "chat/store/runtime/durable-run-store.ts#sessionFields", "chat/store/runtime/durable-run-store.ts#metadataForRun", "chat/store/runtime/durable-run-store.ts#accept", "chat/store/runtime/durable-run-store.ts#advance", "chat/store/runtime/durable-run-store.ts#guardTool.hasUnknownToolCall", "chat/server/durable-runs/recover.ts#attemptDiagnostics", "chat/server/durable-runs/recover.ts#attach", "chat/store/sql/store.ts#messages", "chat/store/sql/store.ts#messagesVersion"];
|
|
21
|
+
export interface AttemptBaseReaderProof {
|
|
22
|
+
readonly verifiedReaders: readonly string[];
|
|
23
|
+
}
|
|
24
|
+
export interface AttemptBaseTrimPolicy {
|
|
25
|
+
readonly id: "attempt-base";
|
|
26
|
+
readonly kind: "derived";
|
|
27
|
+
/** `report-only` until the host's reader proof matches {@link ATTEMPT_BASE_READERS} exactly. */
|
|
28
|
+
readonly mode: "report-only" | "trim";
|
|
29
|
+
measure(): Promise<{
|
|
30
|
+
readonly bytes: number | null;
|
|
31
|
+
readonly items: number;
|
|
32
|
+
}>;
|
|
33
|
+
sweep(input: {
|
|
34
|
+
readonly now: number;
|
|
35
|
+
readonly signal?: AbortSignal;
|
|
36
|
+
}): Promise<{
|
|
37
|
+
readonly freedBytes: number | null;
|
|
38
|
+
readonly removed: number;
|
|
39
|
+
}>;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Builds the `attempt-base` policy. Measuring always works; sweeping writes only after the reader
|
|
43
|
+
* proof matches, and then clears at most `limit` bases per call in one statement.
|
|
44
|
+
*
|
|
45
|
+
* @param required.now clock for `measure()`; `sweep()` uses the pass time it is given.
|
|
46
|
+
* @param optional.minPastDeadlineMs how long after its recovery deadline a base stays (default 7 days).
|
|
47
|
+
* @throws Error when `limit` is not a positive whole number.
|
|
48
|
+
*/
|
|
49
|
+
export declare function createAttemptBaseTrimPolicy<DB extends ChatDatabase>({ kernel: hostKernel, now, readerProof }: {
|
|
50
|
+
kernel: ChatKernel<DB>;
|
|
51
|
+
now: () => number;
|
|
52
|
+
readerProof: AttemptBaseReaderProof;
|
|
53
|
+
}, { minPastDeadlineMs, limit }?: {
|
|
54
|
+
minPastDeadlineMs?: number;
|
|
55
|
+
limit?: number;
|
|
56
|
+
}): AttemptBaseTrimPolicy;
|
|
57
|
+
//# sourceMappingURL=attempt-base-retention.d.ts.map
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { CHAT_RUN_STATUSES, isTerminalRunStatus } from "../../core/messages.js";
|
|
3
|
+
import { chatKernelTables } from "../sql/boundary.js";
|
|
4
|
+
/**
|
|
5
|
+
* @file Retention policy `attempt-base` (kind `derived`): clears `assistant_run_attempts.attempt_base_json`
|
|
6
|
+
* of finished runs whose recovery deadline passed long ago.
|
|
7
|
+
*
|
|
8
|
+
* The attempt base is a working copy, not a receipt. It holds the saved events an attempt started
|
|
9
|
+
* from so a live stream can be seeded and a retry can tell old diagnostics from new ones. The
|
|
10
|
+
* message's own `events_json` stays the durable record of what happened and is never touched here;
|
|
11
|
+
* once the run is finished nothing can resume it (`advance` only moves `queued`/`running` runs), so
|
|
12
|
+
* the copy has no reader left. That last claim is only as good as the reader proof in
|
|
13
|
+
* `__tests__/attempt-base-readers.test.ts`, which is why the policy cleans nothing unless the host
|
|
14
|
+
* hands back exactly the list of readers that file proves.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Every in-engine reader of an attempt base that `attempt-base-readers.test.ts` drives with a
|
|
18
|
+
* finished, past-deadline attempt and shows to behave identically with `'[]'`. Host-side readers
|
|
19
|
+
* (for example a host's run watcher) are not listed: they cannot be proven from this package, and a
|
|
20
|
+
* host that has its own readers must not claim this list until it proves them too.
|
|
21
|
+
*/
|
|
22
|
+
export const ATTEMPT_BASE_READERS = Object.freeze([
|
|
23
|
+
"chat/core/durable-runs/ports.ts#DurableRunHead.attemptBase",
|
|
24
|
+
"chat/store/runtime/kernel.ts#assistant_run_attempts.attempt_base_json",
|
|
25
|
+
"chat/store/runtime/durable-run-store.ts#sessionFields",
|
|
26
|
+
"chat/store/runtime/durable-run-store.ts#metadataForRun",
|
|
27
|
+
"chat/store/runtime/durable-run-store.ts#accept",
|
|
28
|
+
"chat/store/runtime/durable-run-store.ts#advance",
|
|
29
|
+
"chat/store/runtime/durable-run-store.ts#guardTool.hasUnknownToolCall",
|
|
30
|
+
"chat/server/durable-runs/recover.ts#attemptDiagnostics",
|
|
31
|
+
"chat/server/durable-runs/recover.ts#attach",
|
|
32
|
+
"chat/store/sql/store.ts#messages",
|
|
33
|
+
"chat/store/sql/store.ts#messagesVersion",
|
|
34
|
+
]);
|
|
35
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
36
|
+
const EMPTY_BASE = "[]";
|
|
37
|
+
const TERMINAL_STATUSES = CHAT_RUN_STATUSES.filter((status) => isTerminalRunStatus({ status }));
|
|
38
|
+
/** Exact set equality: a missing reader is unproven, and an extra one names a reader this package never proved. */
|
|
39
|
+
function proofMatches({ readerProof }) {
|
|
40
|
+
const claimed = new Set(readerProof.verifiedReaders);
|
|
41
|
+
return claimed.size === ATTEMPT_BASE_READERS.length && readerProof.verifiedReaders.length === claimed.size
|
|
42
|
+
&& ATTEMPT_BASE_READERS.every((reader) => claimed.has(reader));
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Builds the `attempt-base` policy. Measuring always works; sweeping writes only after the reader
|
|
46
|
+
* proof matches, and then clears at most `limit` bases per call in one statement.
|
|
47
|
+
*
|
|
48
|
+
* @param required.now clock for `measure()`; `sweep()` uses the pass time it is given.
|
|
49
|
+
* @param optional.minPastDeadlineMs how long after its recovery deadline a base stays (default 7 days).
|
|
50
|
+
* @throws Error when `limit` is not a positive whole number.
|
|
51
|
+
*/
|
|
52
|
+
export function createAttemptBaseTrimPolicy({ kernel: hostKernel, now, readerProof }, { minPastDeadlineMs = 7 * DAY_MS, limit = 500 } = {}) {
|
|
53
|
+
if (!Number.isInteger(limit) || limit < 1)
|
|
54
|
+
throw new Error(`The attempt base cleanup limit must be a positive whole number, not ${limit}.`);
|
|
55
|
+
const kernel = chatKernelTables({ kernel: hostKernel }, {});
|
|
56
|
+
const mode = proofMatches({ readerProof }) ? "trim" : "report-only";
|
|
57
|
+
/** Finished, belongs to its message's run, still holds a base, and its non-null deadline is old enough. */
|
|
58
|
+
function eligible(eb, { at }) {
|
|
59
|
+
return eb.and([
|
|
60
|
+
eb("assistant_run_attempts.attempt_base_json", "<>", EMPTY_BASE),
|
|
61
|
+
// A null deadline means recovery is paused or never started; unknown age keeps the data.
|
|
62
|
+
eb("assistant_run_attempts.recovery_deadline", "is not", null),
|
|
63
|
+
eb("assistant_run_attempts.recovery_deadline", "<=", at - minPastDeadlineMs),
|
|
64
|
+
eb.exists(eb.selectFrom("ai_chat_messages as m").select(sql.lit(1).as("one"))
|
|
65
|
+
.whereRef("m.id", "=", "assistant_run_attempts.message_id")
|
|
66
|
+
.where("m.run_id", "is not", null)
|
|
67
|
+
.where("m.run_status", "in", TERMINAL_STATUSES)),
|
|
68
|
+
]);
|
|
69
|
+
}
|
|
70
|
+
async function measure() {
|
|
71
|
+
const row = await kernel.run((db) => db.selectFrom("assistant_run_attempts")
|
|
72
|
+
.select((eb) => [eb.fn.countAll().as("items"),
|
|
73
|
+
eb.fn.sum(eb.fn("length", ["assistant_run_attempts.attempt_base_json"])).as("chars")])
|
|
74
|
+
.where((eb) => eligible(eb, { at: now() })).executeTakeFirst());
|
|
75
|
+
return { bytes: Number(row?.chars ?? 0), items: Number(row?.items ?? 0) };
|
|
76
|
+
}
|
|
77
|
+
async function sweep({ now: at, signal }) {
|
|
78
|
+
if (signal?.aborted)
|
|
79
|
+
throw new Error("The attempt base cleanup was stopped before it changed anything.", { cause: signal.reason });
|
|
80
|
+
if (mode === "report-only")
|
|
81
|
+
return { freedBytes: 0, removed: 0 };
|
|
82
|
+
// One statement re-checks every predicate as it writes, so a run that is still recoverable can
|
|
83
|
+
// never be cleared by a stale read, and finished runs cannot become active again. Only the
|
|
84
|
+
// attempt row changes: no field served by the messages response (or under messagesVersion)
|
|
85
|
+
// depends on it, which `messages response bytes identical before and after trim` proves, so no
|
|
86
|
+
// version bump is needed. `events_json` is never named here.
|
|
87
|
+
return kernel.transaction(async () => {
|
|
88
|
+
const chosen = await kernel.run((db) => db.selectFrom("assistant_run_attempts")
|
|
89
|
+
.select((eb) => ["assistant_run_attempts.message_id", eb.fn("length", ["assistant_run_attempts.attempt_base_json"]).as("chars")])
|
|
90
|
+
.where((eb) => eligible(eb, { at })).limit(limit).execute());
|
|
91
|
+
if (chosen.length === 0)
|
|
92
|
+
return { freedBytes: 0, removed: 0 };
|
|
93
|
+
const result = await kernel.run((db) => db.updateTable("assistant_run_attempts").set({ attempt_base_json: EMPTY_BASE })
|
|
94
|
+
.where("message_id", "in", chosen.map((row) => row.message_id))
|
|
95
|
+
.where((eb) => eligible(eb, { at })).executeTakeFirst());
|
|
96
|
+
const removed = Number(result.numUpdatedRows);
|
|
97
|
+
const freed = chosen.reduce((sum, row) => sum + Number(row.chars) - EMPTY_BASE.length, 0);
|
|
98
|
+
return { freedBytes: removed === chosen.length ? freed : null, removed };
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return { id: "attempt-base", kind: "derived", mode, measure, sweep };
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=attempt-base-retention.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { StorageKernel } from '@jini-ai/core/contracts/storage';
|
|
2
|
+
import type { Kysely } from 'kysely';
|
|
3
|
+
import type { ChatDatabase } from '../sql/tables.js';
|
|
4
|
+
import type { ChatHistoryMaintenance } from '../ports.js';
|
|
5
|
+
/**
|
|
6
|
+
* Privileged expiry maintenance for whichever dialect the host's borrowed chat kernel uses,
|
|
7
|
+
* selected by its transport. Maintenance authority stays at composition time: hand the result to
|
|
8
|
+
* `sweepExpiredChats`/`startChatExpirySweep`, never to an owner-scoped store, so no request
|
|
9
|
+
* handler can sweep other owners. The selected adapter still validates the dialect.
|
|
10
|
+
* @throws ChatStoreError invalid-input when the kernel's dialect does not match its transport.
|
|
11
|
+
* @complexity O(1); no I/O at construction.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createChatMaintenanceForKernel<DB extends ChatDatabase>({ kernel }: {
|
|
14
|
+
kernel: StorageKernel<Kysely<DB>, DB>;
|
|
15
|
+
}, _optional?: {}): ChatHistoryMaintenance;
|
|
16
|
+
//# sourceMappingURL=chat-maintenance.d.ts.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { createSqliteChatMaintenance } from '../sqlite/index.js';
|
|
2
|
+
import { createPgliteChatMaintenance } from '../pglite/index.js';
|
|
3
|
+
import { createPostgresChatMaintenance } from '../postgres/index.js';
|
|
4
|
+
/**
|
|
5
|
+
* Privileged expiry maintenance for whichever dialect the host's borrowed chat kernel uses,
|
|
6
|
+
* selected by its transport. Maintenance authority stays at composition time: hand the result to
|
|
7
|
+
* `sweepExpiredChats`/`startChatExpirySweep`, never to an owner-scoped store, so no request
|
|
8
|
+
* handler can sweep other owners. The selected adapter still validates the dialect.
|
|
9
|
+
* @throws ChatStoreError invalid-input when the kernel's dialect does not match its transport.
|
|
10
|
+
* @complexity O(1); no I/O at construction.
|
|
11
|
+
*/
|
|
12
|
+
export function createChatMaintenanceForKernel({ kernel }, _optional = {}) {
|
|
13
|
+
if (kernel.transport === 'better-sqlite3')
|
|
14
|
+
return createSqliteChatMaintenance({ kernel });
|
|
15
|
+
if (kernel.transport === 'pglite' || kernel.transport === 'pglite-socket')
|
|
16
|
+
return createPgliteChatMaintenance({ kernel });
|
|
17
|
+
return createPostgresChatMaintenance({ kernel });
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=chat-maintenance.js.map
|