@wirecat/cli-core 0.686.0 → 0.688.0
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 +114 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/account-remove.js +21 -3
- package/dist/cli/documents/testing/source-contract.js +18 -9
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/envelope.js +2 -3
- package/dist/cli/meeting-batch.js +5 -1
- package/dist/cli/meeting-passage-text.d.ts +1 -1
- package/dist/cli/meeting-passage-text.js +3 -5
- package/dist/cli/messenger/conversations-command.js +4 -0
- package/dist/cli/messenger/messages-search-command.js +6 -1
- package/dist/cli/messenger/search-answers.js +2 -0
- package/dist/cli/messenger/store-maintenance-command.js +3 -2
- package/dist/cli/search-left-out.d.ts +3 -0
- package/dist/cli/search-left-out.js +12 -0
- package/dist/cli/store-settings.js +23 -4
- package/dist/cli/untrusted-marks.d.ts +2 -0
- package/dist/cli/untrusted-marks.js +6 -0
- package/dist/crm/cli/files.d.ts +68 -0
- package/dist/crm/cli/files.js +616 -0
- package/dist/crm/cli/index.d.ts +1 -0
- package/dist/crm/cli/index.js +3 -0
- package/dist/crm/cli/search-all.js +3 -2
- package/dist/crm/file-fetch.d.ts +15 -0
- package/dist/crm/file-fetch.js +61 -0
- package/dist/crm/files.d.ts +16 -0
- package/dist/crm/files.js +56 -0
- package/dist/crm/foreign-contacts.d.ts +16 -4
- package/dist/crm/foreign-contacts.js +8 -4
- package/dist/crm/index.d.ts +3 -1
- package/dist/crm/index.js +3 -0
- package/dist/crm/source.d.ts +37 -0
- package/dist/crm/source.js +2 -1
- package/dist/crm/testing/files-contract.d.ts +17 -0
- package/dist/crm/testing/files-contract.js +142 -0
- package/dist/crm/testing/index.d.ts +2 -1
- package/dist/crm/testing/index.js +2 -1
- package/dist/crm/testing/source.d.ts +36 -1
- package/dist/crm/testing/source.js +55 -1
- package/dist/crm/values.d.ts +2 -1
- package/dist/crm/values.js +4 -2
- package/dist/entities/hit.d.ts +3 -3
- package/dist/entities/hit.js +14 -3
- package/dist/entities/index.d.ts +1 -1
- package/dist/errors/reasons.js +12 -1
- package/dist/files/safe-name.d.ts +2 -1
- package/dist/files/safe-name.js +21 -3
- package/dist/meetings/cli/index.d.ts +1 -1
- package/dist/meetings/cli/index.js +10 -6
- package/dist/meetings/mcp/index.d.ts +15 -15
- package/dist/meetings/mcp/passage.d.ts +6 -2
- package/dist/meetings/mcp/passage.js +7 -3
- package/dist/meetings/read-through.d.ts +2 -0
- package/dist/meetings/read-through.js +7 -2
- package/dist/meetings/source.d.ts +2 -2
- package/dist/oauth/storage.js +21 -4
- package/dist/search/lucene/resolved.d.ts +2 -0
- package/dist/search/respell.d.ts +10 -0
- package/dist/search/respell.js +63 -0
- package/dist/search/stem.d.ts +16 -3
- package/dist/search/stem.js +32 -4
- package/dist/services/documents/plan.js +26 -5
- package/dist/services/documents/sync.js +4 -1
- package/dist/services/embeddings-search.js +190 -140
- package/dist/services/embeddings.d.ts +8 -0
- package/dist/services/messages-archive-search.js +55 -3
- package/dist/services/messages-search.d.ts +2 -1
- package/dist/services/messages-search.js +19 -7
- package/dist/services/messages.d.ts +8 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/named-chat.d.ts +20 -0
- package/dist/services/named-chat.js +63 -0
- package/dist/services/search-all.d.ts +7 -2
- package/dist/services/search-all.js +35 -1
- package/dist/store/accounts.d.ts +2 -1
- package/dist/store/exports.d.ts +2 -1
- package/dist/store/exports.js +2 -1
- package/dist/store/recover.js +2 -0
- package/dist/store/search-index.d.ts +2 -0
- package/dist/store/search-index.js +1 -0
- package/dist/store/sqlite/account-purge.js +1 -0
- package/dist/store/sqlite/crm-files.d.ts +70 -0
- package/dist/store/sqlite/crm-files.js +174 -0
- package/dist/store/sqlite/crm-settings.d.ts +42 -1
- package/dist/store/sqlite/crm-settings.js +46 -2
- package/dist/store/sqlite/lucene-fields.d.ts +2 -0
- package/dist/store/sqlite/lucene-fields.js +6 -2
- package/dist/store/sqlite/lucene.js +13 -7
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +17 -0
- package/dist/store/sqlite/schema.d.ts +329 -0
- package/dist/store/sqlite/schema.js +28 -0
- package/dist/store/sqlite/stems.d.ts +2 -0
- package/dist/store/sqlite/stems.js +5 -0
- package/dist/store/store.d.ts +3 -0
- package/dist/store/store.js +5 -0
- package/package.json +2 -2
package/dist/search/stem.d.ts
CHANGED
|
@@ -20,6 +20,8 @@ export declare const DEFAULT_STEMMERS_VERSION = 2;
|
|
|
20
20
|
* Between the stem sequences of one text when several Latin stemmers give different ones, so a phrase
|
|
21
21
|
* never matches across two sequences. Letters and digits, so `unicode61` keeps it as one token.
|
|
22
22
|
*/
|
|
23
|
+
/** The fewest letters a searched word has for the longer words it begins to count too: `рост` finds `ростовщик`. */
|
|
24
|
+
export declare const START_LETTERS = 4;
|
|
23
25
|
export declare const STEM_SEPARATOR = "0stemsep0";
|
|
24
26
|
/** Clear-all rather than LRU: the 1M benchmark corpus holds 523k distinct words, and a Map stays cheap below this. */
|
|
25
27
|
export declare const STEM_CACHE_LIMIT = 200000;
|
|
@@ -40,8 +42,13 @@ export type Stemmer = {
|
|
|
40
42
|
indexText(text: string): string;
|
|
41
43
|
/** An FTS5 expression for a text as phrases of stems, one per sequence; `undefined` when no word stems. */
|
|
42
44
|
phrases(text: string): string | undefined;
|
|
43
|
-
/**
|
|
44
|
-
|
|
45
|
+
/**
|
|
46
|
+
* Each word of a text with its stem and the stemmer its script chose — what a search answer shows. With `query`, the
|
|
47
|
+
* stem `phrases` searches, which keeps a word whole where its stem would be another word.
|
|
48
|
+
*/
|
|
49
|
+
explain(text: string, options?: {
|
|
50
|
+
query?: boolean;
|
|
51
|
+
}): {
|
|
45
52
|
word: string;
|
|
46
53
|
stem: string;
|
|
47
54
|
stemmer: CyrillicStemmer | LatinStemmer;
|
|
@@ -53,6 +60,12 @@ export type Stemmer = {
|
|
|
53
60
|
* (`Москвa` with a Latin `a`) are usually homoglyph spoofing or code, and `covid19` is a name, not a word form.
|
|
54
61
|
* Ukrainian and other Cyrillic languages go through the Russian stemmer — there is no language detection.
|
|
55
62
|
*/
|
|
56
|
-
|
|
63
|
+
/**
|
|
64
|
+
* Whether Snowball cuts a word to a stem so short that it may be another word's: «домен» → «дом», the stem of «дом»
|
|
65
|
+
* and «дома». The search keeps such a word whole when the stems show it is a stem itself («доменов» → «домен»).
|
|
66
|
+
*/
|
|
67
|
+
export declare const cutsDeep: (stemmer: Stemmer, token: string) => boolean;
|
|
68
|
+
export declare const createStemmer: (stemmers?: Stemmers, { cacheLimit, whole }?: {
|
|
57
69
|
cacheLimit?: number;
|
|
70
|
+
whole?: ReadonlySet<string>;
|
|
58
71
|
}) => Stemmer;
|
package/dist/search/stem.js
CHANGED
|
@@ -18,6 +18,8 @@ export const DEFAULT_STEMMERS_VERSION = 2;
|
|
|
18
18
|
* Between the stem sequences of one text when several Latin stemmers give different ones, so a phrase
|
|
19
19
|
* never matches across two sequences. Letters and digits, so `unicode61` keeps it as one token.
|
|
20
20
|
*/
|
|
21
|
+
/** The fewest letters a searched word has for the longer words it begins to count too: `рост` finds `ростовщик`. */
|
|
22
|
+
export const START_LETTERS = 4;
|
|
21
23
|
export const STEM_SEPARATOR = "0stemsep0";
|
|
22
24
|
/** Clear-all rather than LRU: the 1M benchmark corpus holds 523k distinct words, and a Map stays cheap below this. */
|
|
23
25
|
export const STEM_CACHE_LIMIT = 200_000;
|
|
@@ -66,7 +68,16 @@ const snowball = {
|
|
|
66
68
|
* (`Москвa` with a Latin `a`) are usually homoglyph spoofing or code, and `covid19` is a name, not a word form.
|
|
67
69
|
* Ukrainian and other Cyrillic languages go through the Russian stemmer — there is no language detection.
|
|
68
70
|
*/
|
|
69
|
-
|
|
71
|
+
/**
|
|
72
|
+
* Whether Snowball cuts a word to a stem so short that it may be another word's: «домен» → «дом», the stem of «дом»
|
|
73
|
+
* and «дома». The search keeps such a word whole when the stems show it is a stem itself («доменов» → «домен»).
|
|
74
|
+
*/
|
|
75
|
+
export const cutsDeep = (stemmer, token) => {
|
|
76
|
+
const word = [...normalize(token.normalize("NFC").toLowerCase().replace(MARKS, ""))];
|
|
77
|
+
const stem = [...stemmer.stemToken(token)];
|
|
78
|
+
return stem.length < 4 && word.length - stem.length >= 2;
|
|
79
|
+
};
|
|
80
|
+
export const createStemmer = (stemmers = DEFAULT_STEMMERS, { cacheLimit = STEM_CACHE_LIMIT, whole = new Set() } = {}) => {
|
|
70
81
|
const valid = parseStemmers(stemmers);
|
|
71
82
|
const cyrillic = snowball[valid.cyrillic]();
|
|
72
83
|
const latinNames = valid.latin.split(",");
|
|
@@ -92,6 +103,23 @@ export const createStemmer = (stemmers = DEFAULT_STEMMERS, { cacheLimit = STEM_C
|
|
|
92
103
|
return stem;
|
|
93
104
|
};
|
|
94
105
|
const stemToken = (token) => stemOf(token, 0);
|
|
106
|
+
const queryStemOf = (token, variant) => {
|
|
107
|
+
const word = normalize(token.normalize("NFC").toLowerCase().replace(MARKS, ""));
|
|
108
|
+
return whole.has(word) ? word : stemOf(token, variant);
|
|
109
|
+
};
|
|
110
|
+
const querySequences = (text) => {
|
|
111
|
+
const seen = new Set();
|
|
112
|
+
return latins.flatMap((_, variant) => {
|
|
113
|
+
const sequence = tokensOf(text)
|
|
114
|
+
.map((token) => queryStemOf(token, variant))
|
|
115
|
+
.filter(Boolean);
|
|
116
|
+
const key = sequence.join(" ");
|
|
117
|
+
if (seen.has(key))
|
|
118
|
+
return [];
|
|
119
|
+
seen.add(key);
|
|
120
|
+
return [sequence];
|
|
121
|
+
});
|
|
122
|
+
};
|
|
95
123
|
const tokensOf = (text) => text.normalize("NFC").toLowerCase().match(TOKEN) ?? [];
|
|
96
124
|
const stemSequences = (text) => {
|
|
97
125
|
const tokens = tokensOf(text);
|
|
@@ -116,12 +144,12 @@ export const createStemmer = (stemmers = DEFAULT_STEMMERS, { cacheLimit = STEM_C
|
|
|
116
144
|
.filter(Boolean)
|
|
117
145
|
.join(` ${STEM_SEPARATOR} `),
|
|
118
146
|
phrases: (text) => {
|
|
119
|
-
const phrases =
|
|
147
|
+
const phrases = querySequences(text)
|
|
120
148
|
.filter((sequence) => sequence.length > 0)
|
|
121
149
|
.map((sequence) => `"${sequence.join(" ").replaceAll('"', '""')}"`);
|
|
122
150
|
return phrases.length ? phrases.join(" OR ") : undefined;
|
|
123
151
|
},
|
|
124
|
-
explain: (text) => tokensOf(text).flatMap((word) => {
|
|
152
|
+
explain: (text, { query = false } = {}) => tokensOf(text).flatMap((word) => {
|
|
125
153
|
const bare = word.replace(MARKS, "");
|
|
126
154
|
const script = CYRILLIC.test(bare) ? "cyrillic" : LATIN.test(bare) ? "latin" : "none";
|
|
127
155
|
const variants = script === "latin"
|
|
@@ -129,7 +157,7 @@ export const createStemmer = (stemmers = DEFAULT_STEMMERS, { cacheLimit = STEM_C
|
|
|
129
157
|
: [{ name: script === "cyrillic" ? valid.cyrillic : "none", variant: 0 }];
|
|
130
158
|
const seen = new Set();
|
|
131
159
|
return variants.flatMap(({ name, variant }) => {
|
|
132
|
-
const stem = stemOf(word, variant);
|
|
160
|
+
const stem = query ? queryStemOf(word, variant) : stemOf(word, variant);
|
|
133
161
|
if (!stem || seen.has(stem))
|
|
134
162
|
return [];
|
|
135
163
|
seen.add(stem);
|
|
@@ -78,7 +78,16 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
78
78
|
const walked = (id) => !initial && state.folders[id] !== undefined && !state.folders[id]?.trashed;
|
|
79
79
|
let walk = resumed;
|
|
80
80
|
let cursor = state.cursor ?? "";
|
|
81
|
+
// Each read takes a request from the budget, the start token and a root's own metadata as much as a listing: a run
|
|
82
|
+
// that left them out would reach its deadline with no margin.
|
|
83
|
+
const charge = () => {
|
|
84
|
+
const taken = options.signal?.aborted ? "cancelled" : budget?.take();
|
|
85
|
+
return taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
|
|
86
|
+
};
|
|
81
87
|
if (!walk && initial) {
|
|
88
|
+
const before = charge();
|
|
89
|
+
if (before)
|
|
90
|
+
return { walk: { folders_left: roots.length, entries: 0, listed: 0, stopped: before } };
|
|
82
91
|
const start = await source.startToken();
|
|
83
92
|
walk = {
|
|
84
93
|
scope,
|
|
@@ -91,6 +100,11 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
91
100
|
};
|
|
92
101
|
}
|
|
93
102
|
else if (!walk) {
|
|
103
|
+
// The roots' metadata below stays free: a run stopped between them and the changes would read the same page again
|
|
104
|
+
// in every call.
|
|
105
|
+
const before = charge();
|
|
106
|
+
if (before)
|
|
107
|
+
return { walk: { folders_left: 0, entries: 0, listed: 0, stopped: before } };
|
|
94
108
|
const page = await source.changes(cursor);
|
|
95
109
|
const latest = new Map(page.items.map((change) => [change.id, change]));
|
|
96
110
|
const entering = [];
|
|
@@ -195,11 +209,18 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
195
209
|
stopped = taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
|
|
196
210
|
if (stopped)
|
|
197
211
|
break;
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
container(
|
|
212
|
+
if (!step.folder) {
|
|
213
|
+
const root = await source.metadata(step.id);
|
|
214
|
+
if (!isFolder(root) || root.trashed)
|
|
215
|
+
throw new CliError("validation_error", "configured root is not an accessible folder");
|
|
216
|
+
container(root);
|
|
217
|
+
// Kept on the step, so a call stopped before the listing does not read the root again.
|
|
218
|
+
step.folder = root;
|
|
219
|
+
stopped = charge();
|
|
220
|
+
if (stopped)
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
const folder = step.folder;
|
|
203
224
|
let children;
|
|
204
225
|
let more;
|
|
205
226
|
try {
|
|
@@ -221,7 +221,10 @@ export const syncDocuments = async (options) => {
|
|
|
221
221
|
const safe = errorOf(error);
|
|
222
222
|
if (safe.code === "cancelled")
|
|
223
223
|
throw safe;
|
|
224
|
-
|
|
224
|
+
// A file the sign-in may not read is skipped as a gone one is: retried on every sync, it would hold the pass,
|
|
225
|
+
// and the change cursor with it, for good.
|
|
226
|
+
if (job.kind === "save" &&
|
|
227
|
+
(safe.code === "not_found" || safe.code === "permission_error" || safe.code === "validation_error")) {
|
|
225
228
|
const skipped = {
|
|
226
229
|
id: job.id,
|
|
227
230
|
reason: safe.message,
|
|
@@ -3,16 +3,24 @@ import { formatLocator, parseLocator } from "../domain/locator.js";
|
|
|
3
3
|
import { meaningFloor } from "../embeddings/models.js";
|
|
4
4
|
import { fuseRanked } from "../search/fusion.js";
|
|
5
5
|
import { isQueryLimit, QUERY_LIMITS, searchError } from "../search/lucene/types.js";
|
|
6
|
-
import {
|
|
7
|
-
import { normalize } from "../store/normalize.js";
|
|
6
|
+
import { respelled } from "../search/respell.js";
|
|
8
7
|
import { threadConversation } from "../store/store.js";
|
|
9
8
|
import { embeddingsMaintenance, embeddingTarget, isStale, notBuiltError, readinessOf, shaped, withEmbedder, } from "./embeddings-maintenance.js";
|
|
10
9
|
import { storedChatId } from "./message-resolution.js";
|
|
11
10
|
import { prepareLucene } from "./messages-search.js";
|
|
11
|
+
import { namedChat, queryWords, without } from "./named-chat.js";
|
|
12
12
|
import { MAIL } from "./search-kind.js";
|
|
13
13
|
import { refreshSearch } from "./search-refresh.js";
|
|
14
14
|
/** How deep each list is read before the two are merged. */
|
|
15
15
|
const CANDIDATES = 50;
|
|
16
|
+
/** Conversations the meaning half reads across chats before it gives each chat its share. */
|
|
17
|
+
const ACROSS_CHATS = 500;
|
|
18
|
+
/**
|
|
19
|
+
* What one chat brings to each list when several are searched, so a large chat cannot fill them. Its meaning hits
|
|
20
|
+
* count by how far they lead its 20th best: a large chat holds some text near any question, and a small chat's
|
|
21
|
+
* clear best must not lose to that.
|
|
22
|
+
*/
|
|
23
|
+
const PER_CHAT = 20;
|
|
16
24
|
/** Messages the word search reads: one long thread can hold many of them. */
|
|
17
25
|
const WORD_HITS = 200;
|
|
18
26
|
/** Reciprocal rank fusion's usual constant (phase 5 E9). */
|
|
@@ -22,26 +30,28 @@ export const embeddingsSearch = (deps) => {
|
|
|
22
30
|
/**
|
|
23
31
|
* The conversations holding messages that share a word with the query, best message first. Every word
|
|
24
32
|
* is one side of an OR, so a sentence ranks what shares any of it, and nothing in it is read as a filter.
|
|
25
|
-
* Only whole words and their beginnings count
|
|
26
|
-
*
|
|
33
|
+
* Only whole words and their beginnings count, except for a word no message holds at all: that one is read as
|
|
34
|
+
* the words it may stand for (`respelled`), its Latin spelling and the nearest spellings the store holds.
|
|
27
35
|
*/
|
|
28
36
|
const byWords = async (query, prepared, conversations, since, timeLimitMs) => {
|
|
29
|
-
const
|
|
30
|
-
// `что*` OR `какие*` reads most of a large store and runs out of time before the words that matter count.
|
|
31
|
-
const content = all.filter((word) => !STOP_WORDS.has(normalize(word)));
|
|
32
|
-
const words = content.length ? content : all;
|
|
37
|
+
const words = queryWords(query);
|
|
33
38
|
const outside = new Map();
|
|
34
39
|
if (!words.length || !prepared.scopeAccounts.length)
|
|
35
|
-
return { hits: [], outside, sources: new Map() };
|
|
40
|
+
return { hits: [], outside, sources: new Map(), respellings: new Map() };
|
|
36
41
|
const store = await deps.store();
|
|
42
|
+
const respellings = await respelled(store.searchIndex, words);
|
|
37
43
|
const lexical = await prepareLucene(store, await deps.account(), {
|
|
38
|
-
text: words
|
|
44
|
+
text: words
|
|
45
|
+
.flatMap((word) => [word, ...(respellings.get(word) ?? [])])
|
|
46
|
+
.map((word) => (word.length >= 3 ? `${word}*` : `"${word}"`))
|
|
47
|
+
.join(" OR "),
|
|
39
48
|
accounts: prepared.scopeAccounts,
|
|
40
49
|
limit: WORD_HITS,
|
|
41
50
|
...(timeLimitMs === undefined ? {} : { timeLimitMs }),
|
|
42
51
|
}, deps.messenger);
|
|
43
52
|
const { items } = await store.queries.matchQuery({
|
|
44
53
|
...lexical.execution,
|
|
54
|
+
...(prepared.selectedChat ? {} : { perChat: PER_CHAT }),
|
|
45
55
|
...(prepared.selectedChat ? { chat: prepared.selectedChat } : {}),
|
|
46
56
|
...(conversations === undefined ? {} : { conversationIds: conversations }),
|
|
47
57
|
...(since === undefined ? {} : { conversationSince: Date.parse(since) }),
|
|
@@ -127,140 +137,167 @@ export const embeddingsSearch = (deps) => {
|
|
|
127
137
|
seen.add(summary.id);
|
|
128
138
|
return [{ summary, chunk }];
|
|
129
139
|
});
|
|
130
|
-
return { hits, outside, sources };
|
|
140
|
+
return { hits, outside, sources, respellings };
|
|
131
141
|
};
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
142
|
+
const search = async (query, { chat, model: choice, since, limit, filter, source, timezone, syncFirst, signal, refresh, timeLimitMs }) => {
|
|
143
|
+
if (!query.trim())
|
|
144
|
+
searchError("query.invalid-syntax", { start: 0, end: query.length }, "give words to search for");
|
|
145
|
+
if (new TextEncoder().encode(query).length > QUERY_LIMITS.bytes)
|
|
146
|
+
searchError("query.too-large", { start: 0, end: query.length }, "query is longer than 8 KiB");
|
|
147
|
+
const refreshed = await refreshSearch(deps, {
|
|
148
|
+
chat,
|
|
149
|
+
limit,
|
|
150
|
+
syncFirst,
|
|
151
|
+
signal,
|
|
152
|
+
text: filter,
|
|
153
|
+
source,
|
|
154
|
+
timezone,
|
|
155
|
+
});
|
|
156
|
+
const locallyRefreshed = refresh
|
|
157
|
+
? await embeddingsMaintenance(deps).refresh({ ...refresh, messages: false })
|
|
158
|
+
: undefined;
|
|
159
|
+
const store = await deps.store();
|
|
160
|
+
const account = await deps.account();
|
|
161
|
+
const target = embeddingTarget(deps, choice);
|
|
162
|
+
const stop = Date.now() + 200;
|
|
163
|
+
await store.searchIndex.fillSearchIndex({ until: () => Date.now() >= stop });
|
|
164
|
+
await store.searchIndex.fillStems({ until: () => Date.now() >= stop });
|
|
165
|
+
const prepared = await prepareLucene(store, account, {
|
|
166
|
+
...(filter === undefined ? {} : { text: filter }),
|
|
167
|
+
...(source === undefined ? {} : { source }),
|
|
168
|
+
...(chat === undefined ? {} : { chat }),
|
|
169
|
+
...(timezone === undefined ? {} : { timezone }),
|
|
170
|
+
limit,
|
|
171
|
+
}, deps.messenger);
|
|
172
|
+
const eligibility = filter === undefined ? undefined : await store.queries.conversationEligibility(prepared.execution);
|
|
173
|
+
const selected = prepared.selectedChat;
|
|
174
|
+
const scopeOf = (one) => selected
|
|
175
|
+
? selected.account.provider === one.provider && selected.account.account === one.account
|
|
176
|
+
? { chatId: selected.chatId }
|
|
177
|
+
: null
|
|
178
|
+
: {};
|
|
179
|
+
// Out of time in words still leaves the meaning half, the one a sentence needs most.
|
|
180
|
+
let wordsOutOfTime = false;
|
|
181
|
+
const words = await byWords(query, prepared, eligibility?.conversations, since, timeLimitMs).catch((error) => {
|
|
182
|
+
if (!isQueryLimit(error))
|
|
183
|
+
throw error;
|
|
184
|
+
wordsOutOfTime = true;
|
|
185
|
+
return {
|
|
186
|
+
hits: [],
|
|
187
|
+
outside: new Map(),
|
|
188
|
+
sources: new Map(),
|
|
189
|
+
respellings: new Map(),
|
|
190
|
+
};
|
|
191
|
+
});
|
|
192
|
+
const meaning = [];
|
|
193
|
+
const sources = words.sources;
|
|
194
|
+
if (target.installed && prepared.scopeAccounts.length && eligibility?.conversations.length !== 0) {
|
|
195
|
+
await withEmbedder(deps, target, choice, {}, async (embedder) => {
|
|
196
|
+
const [vector] = await embedder.embed([query], "query");
|
|
197
|
+
for (const one of prepared.scopeAccounts) {
|
|
198
|
+
const scope = scopeOf(one);
|
|
199
|
+
if (scope === null)
|
|
200
|
+
continue;
|
|
201
|
+
// One chat needs no share, and mail's threads are too many to share among.
|
|
202
|
+
const whole = "chatId" in scope || one.provider === MAIL;
|
|
203
|
+
const hits = await store.vectors.nearestConversations(one, {
|
|
204
|
+
...scope,
|
|
205
|
+
...(since === undefined ? {} : { since }),
|
|
206
|
+
model: target.key,
|
|
207
|
+
limit: whole ? Math.max(limit, CANDIDATES) : Math.max(limit, ACROSS_CHATS),
|
|
208
|
+
query: vector,
|
|
209
|
+
...(eligibility ? { conversations: eligibility.conversations } : {}),
|
|
210
|
+
});
|
|
211
|
+
const images = await store.vectors.nearestImages(one, {
|
|
212
|
+
...scope,
|
|
213
|
+
...(since === undefined ? {} : { since }),
|
|
214
|
+
model: target.key,
|
|
215
|
+
limit: Math.max(limit, CANDIDATES),
|
|
216
|
+
query: vector,
|
|
217
|
+
});
|
|
218
|
+
const found = [
|
|
219
|
+
...hits,
|
|
220
|
+
...images.filter((hit) => !eligibility || eligibility.conversations.includes(hit.summary.id)),
|
|
221
|
+
].sort((a, b) => b.score - a.score);
|
|
222
|
+
for (const hit of found)
|
|
223
|
+
sources.set(hit.summary.id, one);
|
|
224
|
+
meaning.push(...(whole ? found.map((hit) => ({ hit, lead: hit.score })) : shared(found, limit)));
|
|
225
|
+
}
|
|
146
226
|
});
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
227
|
+
}
|
|
228
|
+
meaning.sort((a, b) => b.lead - a.lead);
|
|
229
|
+
const scoped = [];
|
|
230
|
+
const elsewhere = [];
|
|
231
|
+
for (const one of prepared.scopeAccounts) {
|
|
232
|
+
const scope = scopeOf(one);
|
|
233
|
+
if (scope === null)
|
|
234
|
+
continue;
|
|
235
|
+
const eligibleChats = eligibility?.chats
|
|
236
|
+
.filter(({ account }) => account.provider === one.provider && account.account === one.account)
|
|
237
|
+
.map(({ chat }) => chat);
|
|
238
|
+
const rows = eligibleChats === undefined
|
|
239
|
+
? await store.vectors.readiness(one, { ...scope, model: target.key, searchableOnly: true })
|
|
240
|
+
: (await Promise.all(eligibleChats.map((chatId) => store.vectors.readiness(one, { chatId, model: target.key })))).flat();
|
|
241
|
+
const readiness = searchReadiness(rows.map(shaped), target.installed, words.outside.get(JSON.stringify(one))?.chats ?? new Set());
|
|
242
|
+
scoped.push({ source: one, readiness });
|
|
243
|
+
const other = await store.vectors.embeddedOnlyElsewhere(one, { ...scope, model: target.key });
|
|
244
|
+
elsewhere.push(...other
|
|
245
|
+
.filter((id) => eligibleChats === undefined || eligibleChats.includes(id))
|
|
246
|
+
.map((id) => prepared.scopeAccounts.length > 1 ? [one.provider, one.account, id].map(encodeURIComponent).join("/") : id));
|
|
247
|
+
}
|
|
248
|
+
const readiness = { searchedByMeaning: [], wordsOnly: [], partial: [], stale: [], notBuilt: [] };
|
|
249
|
+
for (const key of ["searchedByMeaning", "wordsOnly", "partial", "stale", "notBuilt"])
|
|
250
|
+
readiness[key] = [
|
|
251
|
+
...new Set(scoped.flatMap(({ source, readiness }) => readiness[key].map((id) => scoped.length > 1 ? [source.provider, source.account, id].map(encodeURIComponent).join("/") : id))),
|
|
252
|
+
].sort();
|
|
253
|
+
if (scoped.length > 1)
|
|
254
|
+
readiness.scopes = scoped;
|
|
255
|
+
return {
|
|
256
|
+
accounts: prepared.scopeAccounts,
|
|
257
|
+
model: target.id,
|
|
258
|
+
meaning: target.installed ? "searched" : "unavailable",
|
|
259
|
+
...(wordsOutOfTime ? { words: "out-of-time" } : {}),
|
|
260
|
+
...(words.respellings.size ? { respelled: Object.fromEntries(words.respellings) } : {}),
|
|
261
|
+
hits: fused(meaning.map(({ hit }) => hit), words.hits, meaningFloor(target.key))
|
|
262
|
+
.slice(0, limit)
|
|
263
|
+
.map((hit) => {
|
|
264
|
+
const source = sources.get(hit.summary.id);
|
|
265
|
+
return {
|
|
266
|
+
...hit,
|
|
267
|
+
source,
|
|
268
|
+
locator: formatLocator({ ...source, chat: hit.summary.chatId, message: hit.chunk.firstMessageId }),
|
|
269
|
+
};
|
|
270
|
+
}),
|
|
271
|
+
readiness,
|
|
272
|
+
...(locallyRefreshed ? { prepared: locallyRefreshed } : {}),
|
|
273
|
+
...(refreshed
|
|
274
|
+
? { refreshed, coverage: { state: refreshed.complete ? "partial" : "stale" } }
|
|
275
|
+
: {}),
|
|
276
|
+
embeddedOnlyElsewhere: elsewhere,
|
|
277
|
+
};
|
|
278
|
+
};
|
|
279
|
+
return {
|
|
280
|
+
/** Over every chat, a query that names someone by a name their private chat uses has that chat's hits first. */
|
|
281
|
+
search: async (query, options) => {
|
|
282
|
+
const found = await search(query, options);
|
|
283
|
+
if (options.chat !== undefined || options.filter !== undefined || found.accounts?.length !== 1)
|
|
284
|
+
return found;
|
|
285
|
+
const named = await namedChat(await deps.store(), await deps.account(), deps.messenger, found.accounts, queryWords(query)).catch((error) => {
|
|
286
|
+
if (isQueryLimit(error))
|
|
287
|
+
return undefined;
|
|
288
|
+
throw error;
|
|
177
289
|
});
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
if (scope === null)
|
|
186
|
-
continue;
|
|
187
|
-
const hits = await store.vectors.nearestConversations(one, {
|
|
188
|
-
...scope,
|
|
189
|
-
...(since === undefined ? {} : { since }),
|
|
190
|
-
model: target.key,
|
|
191
|
-
limit: Math.max(limit, CANDIDATES),
|
|
192
|
-
query: vector,
|
|
193
|
-
...(eligibility ? { conversations: eligibility.conversations } : {}),
|
|
194
|
-
});
|
|
195
|
-
for (const hit of hits)
|
|
196
|
-
sources.set(hit.summary.id, one);
|
|
197
|
-
meaning.push(...hits);
|
|
198
|
-
const images = await store.vectors.nearestImages(one, {
|
|
199
|
-
...scope,
|
|
200
|
-
...(since === undefined ? {} : { since }),
|
|
201
|
-
model: target.key,
|
|
202
|
-
limit: Math.max(limit, CANDIDATES),
|
|
203
|
-
query: vector,
|
|
204
|
-
});
|
|
205
|
-
for (const hit of images) {
|
|
206
|
-
if (eligibility && !eligibility.conversations.includes(hit.summary.id))
|
|
207
|
-
continue;
|
|
208
|
-
sources.set(hit.summary.id, one);
|
|
209
|
-
meaning.push(hit);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
meaning.sort((a, b) => b.score - a.score);
|
|
215
|
-
const scoped = [];
|
|
216
|
-
const elsewhere = [];
|
|
217
|
-
for (const one of prepared.scopeAccounts) {
|
|
218
|
-
const scope = scopeOf(one);
|
|
219
|
-
if (scope === null)
|
|
220
|
-
continue;
|
|
221
|
-
const eligibleChats = eligibility?.chats
|
|
222
|
-
.filter(({ account }) => account.provider === one.provider && account.account === one.account)
|
|
223
|
-
.map(({ chat }) => chat);
|
|
224
|
-
const rows = eligibleChats === undefined
|
|
225
|
-
? await store.vectors.readiness(one, { ...scope, model: target.key, searchableOnly: true })
|
|
226
|
-
: (await Promise.all(eligibleChats.map((chatId) => store.vectors.readiness(one, { chatId, model: target.key })))).flat();
|
|
227
|
-
const readiness = searchReadiness(rows.map(shaped), target.installed, words.outside.get(JSON.stringify(one))?.chats ?? new Set());
|
|
228
|
-
scoped.push({ source: one, readiness });
|
|
229
|
-
const other = await store.vectors.embeddedOnlyElsewhere(one, { ...scope, model: target.key });
|
|
230
|
-
elsewhere.push(...other
|
|
231
|
-
.filter((id) => eligibleChats === undefined || eligibleChats.includes(id))
|
|
232
|
-
.map((id) => prepared.scopeAccounts.length > 1
|
|
233
|
-
? [one.provider, one.account, id].map(encodeURIComponent).join("/")
|
|
234
|
-
: id));
|
|
235
|
-
}
|
|
236
|
-
const readiness = { searchedByMeaning: [], wordsOnly: [], partial: [], stale: [], notBuilt: [] };
|
|
237
|
-
for (const key of ["searchedByMeaning", "wordsOnly", "partial", "stale", "notBuilt"])
|
|
238
|
-
readiness[key] = [
|
|
239
|
-
...new Set(scoped.flatMap(({ source, readiness }) => readiness[key].map((id) => scoped.length > 1 ? [source.provider, source.account, id].map(encodeURIComponent).join("/") : id))),
|
|
240
|
-
].sort();
|
|
241
|
-
if (scoped.length > 1)
|
|
242
|
-
readiness.scopes = scoped;
|
|
290
|
+
if (!named)
|
|
291
|
+
return found;
|
|
292
|
+
// Inside the chat the name is in every other message, so it would only add noise there.
|
|
293
|
+
const rest = without(query, named.word);
|
|
294
|
+
const { syncFirst: _, refresh: __, ...plain } = options;
|
|
295
|
+
const inside = await search(rest || query, { ...plain, chat: named.chatId });
|
|
296
|
+
const shown = new Set(inside.hits.map(({ summary }) => summary.id));
|
|
243
297
|
return {
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
...(wordsOutOfTime ? { words: "out-of-time" } : {}),
|
|
248
|
-
hits: fused(meaning, words.hits, meaningFloor(target.key))
|
|
249
|
-
.slice(0, limit)
|
|
250
|
-
.map((hit) => {
|
|
251
|
-
const source = sources.get(hit.summary.id);
|
|
252
|
-
return {
|
|
253
|
-
...hit,
|
|
254
|
-
source,
|
|
255
|
-
locator: formatLocator({ ...source, chat: hit.summary.chatId, message: hit.chunk.firstMessageId }),
|
|
256
|
-
};
|
|
257
|
-
}),
|
|
258
|
-
readiness,
|
|
259
|
-
...(locallyRefreshed ? { prepared: locallyRefreshed } : {}),
|
|
260
|
-
...(refreshed
|
|
261
|
-
? { refreshed, coverage: { state: refreshed.complete ? "partial" : "stale" } }
|
|
262
|
-
: {}),
|
|
263
|
-
embeddedOnlyElsewhere: elsewhere,
|
|
298
|
+
...found,
|
|
299
|
+
named: { word: named.word, chatId: named.chatId, title: named.title },
|
|
300
|
+
hits: [...inside.hits, ...found.hits.filter(({ summary }) => !shown.has(summary.id))].slice(0, options.limit),
|
|
264
301
|
};
|
|
265
302
|
},
|
|
266
303
|
related: async (chat, message, { model: choice, limit }) => {
|
|
@@ -298,6 +335,19 @@ export const embeddingsSearch = (deps) => {
|
|
|
298
335
|
},
|
|
299
336
|
};
|
|
300
337
|
};
|
|
338
|
+
/**
|
|
339
|
+
* Each chat's best hits, as many as the page holds, with each one's lead over the chat's `PER_CHAT`th best (or its
|
|
340
|
+
* last, in a chat with fewer).
|
|
341
|
+
*/
|
|
342
|
+
const shared = (hits, limit) => {
|
|
343
|
+
const chats = new Map();
|
|
344
|
+
for (const hit of hits)
|
|
345
|
+
chats.set(hit.summary.chatId, [...(chats.get(hit.summary.chatId) ?? []), hit]);
|
|
346
|
+
return [...chats.values()].flatMap((own) => {
|
|
347
|
+
const level = own[Math.min(PER_CHAT, own.length) - 1]?.score ?? 0;
|
|
348
|
+
return own.slice(0, Math.max(limit, PER_CHAT)).map((hit) => ({ hit, lead: hit.score - level }));
|
|
349
|
+
});
|
|
350
|
+
};
|
|
301
351
|
/** Reciprocal rank fusion of the two lists: each conversation scores 1 / (k + rank) in every list it is in. */
|
|
302
352
|
const fused = (meaning, words, minimumCosine) => {
|
|
303
353
|
const merged = new Map();
|
|
@@ -139,6 +139,14 @@ export interface FoundConversations {
|
|
|
139
139
|
meaning: "searched" | "unavailable";
|
|
140
140
|
/** `out-of-time`: the word half hit its time limit, so the hits are by meaning alone. */
|
|
141
141
|
words?: "out-of-time";
|
|
142
|
+
/** Words no message holds, each with the words searched in its place: its Latin spelling and near spellings. */
|
|
143
|
+
respelled?: Record<string, string[]>;
|
|
144
|
+
/** The private chat a word of the query names, whose hits come first. */
|
|
145
|
+
named?: {
|
|
146
|
+
word: string;
|
|
147
|
+
chatId: Id;
|
|
148
|
+
title: string | null;
|
|
149
|
+
};
|
|
142
150
|
hits: FoundConversation[];
|
|
143
151
|
readiness: SearchReadiness;
|
|
144
152
|
/** Kept for callers of 0.141.0 and before; `readiness.wordsOnly` says more. */
|