@wirecat/cli-core 0.716.0 → 0.718.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 +84 -0
- package/dist/cli/account-rename.js +1 -1
- package/dist/cli/documents/index.d.ts +2 -0
- package/dist/cli/documents/index.js +2 -0
- package/dist/cli/documents/manifest/manifest.d.ts +82 -0
- package/dist/cli/documents/manifest/manifest.js +97 -0
- package/dist/cli/documents/manifest/source.d.ts +35 -0
- package/dist/cli/documents/manifest/source.js +257 -0
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/messenger/conversation-answers.d.ts +1 -1
- package/dist/cli/messenger/conversation-answers.js +4 -2
- package/dist/cli/messenger/conversations-command.js +13 -4
- package/dist/cli/service-api-manifest.d.ts +2 -0
- package/dist/cli/service-api-manifest.js +6 -6
- package/dist/cli/service-api.d.ts +5 -0
- package/dist/cli/service-api.js +2 -2
- package/dist/cli/token-session.js +1 -1
- package/dist/content/manifest/writer.js +5 -1
- package/dist/documents/model.d.ts +6 -0
- package/dist/entities/conversation-results.d.ts +5 -0
- package/dist/entities/conversation-results.js +6 -1
- package/dist/entities/index.d.ts +3 -0
- package/dist/errors/reasons.js +8 -1
- package/dist/manifest/index.d.ts +22 -3
- package/dist/manifest/index.js +13 -2
- package/dist/search/lucene/resolved.d.ts +2 -0
- package/dist/services/documents/plan.d.ts +2 -0
- package/dist/services/documents/plan.js +12 -0
- package/dist/services/embeddings-search.d.ts +9 -0
- package/dist/services/embeddings-search.js +189 -69
- package/dist/services/embeddings.d.ts +6 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/named-chat.d.ts +3 -3
- package/dist/services/named-chat.js +12 -3
- package/dist/store/conversations.d.ts +21 -0
- package/dist/store/conversations.js +13 -0
- package/dist/store/slow-queries.d.ts +7 -0
- package/dist/store/slow-queries.js +47 -0
- package/dist/store/sqlite/conversations.d.ts +21 -0
- package/dist/store/sqlite/conversations.js +50 -0
- package/dist/store/sqlite/lucene-fields.d.ts +2 -0
- package/dist/store/sqlite/lucene-fields.js +22 -0
- package/dist/store/sqlite/lucene.js +30 -42
- package/dist/store/sqlite/open.js +3 -0
- package/dist/store/sqlite/vector-index.d.ts +3 -1
- package/dist/store/sqlite/vector-index.js +5 -3
- package/dist/store/sqlite/vectors.js +20 -11
- package/dist/store/sqlite/word-rarity.d.ts +14 -0
- package/dist/store/sqlite/word-rarity.js +22 -0
- package/package.json +2 -2
- package/parity.json +5 -0
|
@@ -23,8 +23,21 @@ const OWN_BLOCK = 5;
|
|
|
23
23
|
* clear best must not lose to that.
|
|
24
24
|
*/
|
|
25
25
|
const PER_CHAT = 20;
|
|
26
|
+
/**
|
|
27
|
+
* A chat holding this many of the `ACROSS_CHATS` candidates is a big group: its 20th best sits right under its best, so
|
|
28
|
+
* nothing in it could lead. It is measured against this many instead.
|
|
29
|
+
*/
|
|
30
|
+
const BIG_CHAT = 100;
|
|
26
31
|
/** Messages the word search reads: one long thread can hold many of them. */
|
|
27
32
|
const WORD_HITS = 200;
|
|
33
|
+
/** Messages of a hit shown with it, and how much of each: enough to tell the answer, not the whole chunk. */
|
|
34
|
+
const SHOWN_LINES = 3;
|
|
35
|
+
const SHOWN_CHARS = 200;
|
|
36
|
+
const SHOWN_HEAD = 80;
|
|
37
|
+
/** Messages of a chunk read to pick the shown ones: a chunk is ~1,200 characters. */
|
|
38
|
+
const CHUNK_READ = 60;
|
|
39
|
+
/** Replies from outside a hit's chunk read per hit; the best one is shown with its lines. */
|
|
40
|
+
const REPLIES_READ = 60;
|
|
28
41
|
/** Reciprocal rank fusion's usual constant (phase 5 E9). */
|
|
29
42
|
const RRF_K = 60;
|
|
30
43
|
export const embeddingsSearch = (deps) => {
|
|
@@ -53,6 +66,7 @@ export const embeddingsSearch = (deps) => {
|
|
|
53
66
|
}, deps.messenger);
|
|
54
67
|
const { items } = await store.queries.matchQuery({
|
|
55
68
|
...lexical.execution,
|
|
69
|
+
rareWordsFirst: true,
|
|
56
70
|
...(prepared.selectedChat ? {} : { perChat: PER_CHAT }),
|
|
57
71
|
...(prepared.selectedChat ? { chat: prepared.selectedChat } : {}),
|
|
58
72
|
...(conversations === undefined ? {} : { conversationIds: conversations }),
|
|
@@ -141,11 +155,13 @@ export const embeddingsSearch = (deps) => {
|
|
|
141
155
|
});
|
|
142
156
|
return { hits, outside, sources, respellings };
|
|
143
157
|
};
|
|
144
|
-
const search = async (query, { chat, model: choice, since, limit, filter, source, timezone, syncFirst, signal, refresh, timeLimitMs }) => {
|
|
158
|
+
const search = async (query, { chat, model: choice, since, limit, filter, source, timezone, syncFirst, signal, refresh, timeLimitMs, like }) => {
|
|
145
159
|
if (!query.trim())
|
|
146
160
|
searchError("query.invalid-syntax", { start: 0, end: query.length }, "give words to search for");
|
|
147
161
|
if (new TextEncoder().encode(query).length > QUERY_LIMITS.bytes)
|
|
148
162
|
searchError("query.too-large", { start: 0, end: query.length }, "query is longer than 8 KiB");
|
|
163
|
+
if (like !== undefined && new TextEncoder().encode(like).length > QUERY_LIMITS.bytes)
|
|
164
|
+
throw new CliError("validation_error", "--like is longer than 8 KiB: one sentence is enough");
|
|
149
165
|
const refreshed = await refreshSearch(deps, {
|
|
150
166
|
chat,
|
|
151
167
|
limit,
|
|
@@ -191,57 +207,65 @@ export const embeddingsSearch = (deps) => {
|
|
|
191
207
|
respellings: new Map(),
|
|
192
208
|
};
|
|
193
209
|
});
|
|
194
|
-
const
|
|
210
|
+
const texts = like?.trim() ? [query, like] : [query];
|
|
211
|
+
const meaning = texts.map(() => []);
|
|
195
212
|
const own = [];
|
|
196
213
|
const sources = words.sources;
|
|
197
214
|
if (target.installed && prepared.scopeAccounts.length && eligibility?.conversations.length !== 0) {
|
|
198
215
|
await withEmbedder(deps, target, choice, {}, async (embedder) => {
|
|
199
|
-
const
|
|
200
|
-
for (const
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
216
|
+
const vectors = await embedder.embed(texts, "query");
|
|
217
|
+
for (const [at, vector] of vectors.entries())
|
|
218
|
+
for (const one of prepared.scopeAccounts) {
|
|
219
|
+
const scope = scopeOf(one);
|
|
220
|
+
if (scope === null)
|
|
221
|
+
continue;
|
|
222
|
+
// One chat needs no share, and mail's threads are too many to share among.
|
|
223
|
+
const whole = "chatId" in scope || one.provider === MAIL;
|
|
224
|
+
const hits = await store.vectors.nearestConversations(one, {
|
|
225
|
+
...scope,
|
|
226
|
+
...(since === undefined ? {} : { since }),
|
|
227
|
+
model: target.key,
|
|
228
|
+
limit: whole ? Math.max(limit, CANDIDATES) : Math.max(limit, ACROSS_CHATS),
|
|
229
|
+
query: vector,
|
|
230
|
+
...(eligibility ? { conversations: eligibility.conversations } : {}),
|
|
231
|
+
});
|
|
232
|
+
// The made-up text only widens the text hits: pictures and the owner's block come from the query alone.
|
|
233
|
+
const images = at > 0
|
|
234
|
+
? []
|
|
235
|
+
: await store.vectors.nearestImages(one, {
|
|
236
|
+
...scope,
|
|
237
|
+
...(since === undefined ? {} : { since }),
|
|
238
|
+
model: target.key,
|
|
239
|
+
limit: Math.max(limit, CANDIDATES),
|
|
240
|
+
query: vector,
|
|
241
|
+
});
|
|
242
|
+
const found = [
|
|
243
|
+
...hits,
|
|
244
|
+
...images.filter((hit) => !eligibility || eligibility.conversations.includes(hit.summary.id)),
|
|
245
|
+
].sort((a, b) => b.score - a.score);
|
|
246
|
+
const mine = at > 0
|
|
247
|
+
? []
|
|
248
|
+
: await store.vectors.nearestConversations(one, {
|
|
249
|
+
...scope,
|
|
250
|
+
...(since === undefined ? {} : { since }),
|
|
251
|
+
model: target.key,
|
|
252
|
+
limit: OWN_BLOCK,
|
|
253
|
+
query: vector,
|
|
254
|
+
fromOwner: true,
|
|
255
|
+
...(eligibility ? { conversations: eligibility.conversations } : {}),
|
|
256
|
+
});
|
|
257
|
+
for (const hit of found)
|
|
258
|
+
sources.set(hit.summary.id, one);
|
|
259
|
+
for (const hit of mine) {
|
|
260
|
+
sources.set(hit.summary.id, one);
|
|
261
|
+
own.push(hit);
|
|
262
|
+
}
|
|
263
|
+
meaning[at]?.push(...(whole ? found.map((hit) => ({ hit, lead: hit.score })) : shared(found, limit)));
|
|
239
264
|
}
|
|
240
|
-
meaning.push(...(whole ? found.map((hit) => ({ hit, lead: hit.score })) : shared(found, limit)));
|
|
241
|
-
}
|
|
242
265
|
});
|
|
243
266
|
}
|
|
244
|
-
|
|
267
|
+
for (const list of meaning)
|
|
268
|
+
list.sort((a, b) => b.lead - a.lead);
|
|
245
269
|
const scoped = [];
|
|
246
270
|
const elsewhere = [];
|
|
247
271
|
for (const one of prepared.scopeAccounts) {
|
|
@@ -276,23 +300,54 @@ export const embeddingsSearch = (deps) => {
|
|
|
276
300
|
locator: formatLocator({ ...source, chat: hit.summary.chatId, message: hit.chunk.firstMessageId }),
|
|
277
301
|
};
|
|
278
302
|
};
|
|
279
|
-
const hits = fused(meaning.map(({ hit }) => hit), words.hits, meaningFloor(target.key))
|
|
303
|
+
const hits = fused(meaning.map((list) => list.map(({ hit }) => hit)), words.hits, meaningFloor(target.key))
|
|
280
304
|
.slice(0, limit)
|
|
281
305
|
.map(located);
|
|
282
306
|
const shown = new Set(hits.map((hit) => hit.summary.id));
|
|
283
|
-
const
|
|
284
|
-
.filter(
|
|
307
|
+
const ownOf = (keep) => own
|
|
308
|
+
.filter(keep)
|
|
285
309
|
.sort((a, b) => b.score - a.score)
|
|
286
310
|
.slice(0, OWN_BLOCK)
|
|
287
311
|
.map((hit) => located({ ...hit, by: ["meaning"] }));
|
|
312
|
+
const ownHits = ownOf((hit) => !shown.has(hit.summary.id));
|
|
313
|
+
const ownSpare = ownOf((hit) => shown.has(hit.summary.id));
|
|
314
|
+
// The query's own words count twice: the made-up answer's words would otherwise pick its lines over the answer's.
|
|
315
|
+
const asked = wordStems(query);
|
|
316
|
+
const stems = [...asked, ...wordStems(texts.join(" "))];
|
|
317
|
+
// The answer to a chunk's question is often a reply sent later, which chunking put in another chunk.
|
|
318
|
+
const replies = (async () => {
|
|
319
|
+
const found = new Map();
|
|
320
|
+
const bySource = new Map();
|
|
321
|
+
for (const hit of [...hits, ...ownHits, ...ownSpare]) {
|
|
322
|
+
const source = hit.source ?? account;
|
|
323
|
+
const group = bySource.get(JSON.stringify(source)) ?? { source, hits: [] };
|
|
324
|
+
group.hits.push(hit);
|
|
325
|
+
bySource.set(JSON.stringify(source), group);
|
|
326
|
+
}
|
|
327
|
+
for (const { source, hits: group } of bySource.values()) {
|
|
328
|
+
const read = await store.conversations.chunkReplies(source, group.map(({ summary, chunk }) => ({ conversationId: summary.id, ...chunk })), REPLIES_READ);
|
|
329
|
+
for (const [index, hit] of group.entries())
|
|
330
|
+
found.set(hit, read[index] ?? []);
|
|
331
|
+
}
|
|
332
|
+
return found;
|
|
333
|
+
})();
|
|
334
|
+
const withLines = async (hit, ownFirst) => {
|
|
335
|
+
const read = await store.conversations.chunkMessages(hit.source ?? account, hit.summary.id, hit.chunk, CHUNK_READ);
|
|
336
|
+
const lines = [
|
|
337
|
+
...shownLines(read, stems, ownFirst, asked),
|
|
338
|
+
...shownLines((await replies).get(hit) ?? [], stems, false, [], 1),
|
|
339
|
+
];
|
|
340
|
+
return lines.length ? { ...hit, lines } : hit;
|
|
341
|
+
};
|
|
288
342
|
return {
|
|
289
343
|
accounts: prepared.scopeAccounts,
|
|
290
344
|
model: target.id,
|
|
291
345
|
meaning: target.installed ? "searched" : "unavailable",
|
|
292
346
|
...(wordsOutOfTime ? { words: "out-of-time" } : {}),
|
|
293
347
|
...(words.respellings.size ? { respelled: Object.fromEntries(words.respellings) } : {}),
|
|
294
|
-
hits,
|
|
295
|
-
...(ownHits.length ? { own: ownHits } : {}),
|
|
348
|
+
hits: await Promise.all(hits.map((hit) => withLines(hit, false))),
|
|
349
|
+
...(ownHits.length ? { own: await Promise.all(ownHits.map((hit) => withLines(hit, true))) } : {}),
|
|
350
|
+
...(ownSpare.length ? { ownSpare: await Promise.all(ownSpare.map((hit) => withLines(hit, true))) } : {}),
|
|
296
351
|
readiness,
|
|
297
352
|
...(locallyRefreshed ? { prepared: locallyRefreshed } : {}),
|
|
298
353
|
...(refreshed
|
|
@@ -304,7 +359,7 @@ export const embeddingsSearch = (deps) => {
|
|
|
304
359
|
return {
|
|
305
360
|
/** Over every chat, a query that names someone by a name their private chat uses has that chat's hits first. */
|
|
306
361
|
search: async (query, options) => {
|
|
307
|
-
const found = await search(query, options);
|
|
362
|
+
const { ownSpare, ...found } = await search(query, options);
|
|
308
363
|
if (options.chat !== undefined || options.filter !== undefined || found.accounts?.length !== 1)
|
|
309
364
|
return found;
|
|
310
365
|
const named = await namedChat(await deps.store(), await deps.account(), deps.messenger, found.accounts, queryWords(query)).catch((error) => {
|
|
@@ -319,10 +374,18 @@ export const embeddingsSearch = (deps) => {
|
|
|
319
374
|
const { syncFirst: _, refresh: __, ...plain } = options;
|
|
320
375
|
const inside = await search(rest || query, { ...plain, chat: named.chatId });
|
|
321
376
|
const shown = new Set(inside.hits.map(({ summary }) => summary.id));
|
|
377
|
+
const hits = [...inside.hits, ...found.hits.filter(({ summary }) => !shown.has(summary.id))].slice(0, options.limit);
|
|
378
|
+
const kept = new Set(hits.map(({ summary }) => summary.id));
|
|
379
|
+
// The chat's hits push some of the list out; the owner's chunks of what left belong back in the block.
|
|
380
|
+
const own = [...(found.own ?? []), ...(ownSpare ?? []).filter(({ summary }) => !kept.has(summary.id))]
|
|
381
|
+
.sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
|
|
382
|
+
.slice(0, OWN_BLOCK);
|
|
383
|
+
const { own: _shown, ...plainFound } = found;
|
|
322
384
|
return {
|
|
323
|
-
...
|
|
385
|
+
...plainFound,
|
|
386
|
+
...(own.length ? { own } : {}),
|
|
324
387
|
named: { word: named.word, chatId: named.chatId, title: named.title },
|
|
325
|
-
hits
|
|
388
|
+
hits,
|
|
326
389
|
};
|
|
327
390
|
},
|
|
328
391
|
related: async (chat, message, { model: choice, limit }) => {
|
|
@@ -364,31 +427,47 @@ export const embeddingsSearch = (deps) => {
|
|
|
364
427
|
* 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
|
|
365
428
|
* last, in a chat with fewer).
|
|
366
429
|
*/
|
|
367
|
-
const shared = (hits, limit) => {
|
|
430
|
+
export const shared = (hits, limit) => {
|
|
368
431
|
const chats = new Map();
|
|
369
432
|
for (const hit of hits)
|
|
370
433
|
chats.set(hit.summary.chatId, [...(chats.get(hit.summary.chatId) ?? []), hit]);
|
|
371
434
|
return [...chats.values()].flatMap((own) => {
|
|
372
|
-
const
|
|
373
|
-
|
|
435
|
+
const share = own.length >= BIG_CHAT ? BIG_CHAT : PER_CHAT;
|
|
436
|
+
const level = own[Math.min(share, own.length) - 1]?.score ?? 0;
|
|
437
|
+
// A big group's entries past the usual share would push private dialogs down, so they come after every chat's.
|
|
438
|
+
return own
|
|
439
|
+
.slice(0, Math.max(limit, share))
|
|
440
|
+
.map((hit, at) => ({ hit, lead: share > PER_CHAT && at >= PER_CHAT ? hit.score - 10 : hit.score - level }));
|
|
374
441
|
});
|
|
375
442
|
};
|
|
376
|
-
/**
|
|
443
|
+
/**
|
|
444
|
+
* Reciprocal rank fusion of the meaning lists (the query's, and `like`'s when given) and the word list: each
|
|
445
|
+
* conversation scores 1 / (k + rank) in every list it is in, and keeps the chunk and cosine of the first list that
|
|
446
|
+
* has it, so a score shown is the query's wherever the query found it.
|
|
447
|
+
*/
|
|
377
448
|
const fused = (meaning, words, minimumCosine) => {
|
|
378
449
|
const merged = new Map();
|
|
379
|
-
meaning
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
summary
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
450
|
+
for (const list of meaning)
|
|
451
|
+
list
|
|
452
|
+
.filter(({ score }) => score > minimumCosine)
|
|
453
|
+
.forEach(({ summary, chunk, score, stale, matchedIn }, index) => {
|
|
454
|
+
const key = matchedIn ? `${summary.id}#${chunk.firstMessageId}` : summary.id;
|
|
455
|
+
const share = 1 / (RRF_K + index + 1);
|
|
456
|
+
const held = merged.get(key);
|
|
457
|
+
if (!held) {
|
|
458
|
+
merged.set(key, {
|
|
459
|
+
summary,
|
|
460
|
+
chunk,
|
|
461
|
+
score,
|
|
462
|
+
by: ["meaning"],
|
|
463
|
+
stale,
|
|
464
|
+
...(matchedIn ? { matchedIn } : {}),
|
|
465
|
+
fused: share,
|
|
466
|
+
});
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
held.fused += share;
|
|
390
470
|
});
|
|
391
|
-
});
|
|
392
471
|
words.forEach(({ summary, chunk }, index) => {
|
|
393
472
|
const share = 1 / (RRF_K + index + 1);
|
|
394
473
|
const held = merged.get(summary.id);
|
|
@@ -403,6 +482,47 @@ const fused = (meaning, words, minimumCosine) => {
|
|
|
403
482
|
.sort((a, b) => b.fused - a.fused || (b.score ?? -2) - (a.score ?? -2))
|
|
404
483
|
.map(({ fused: _, ...hit }) => hit);
|
|
405
484
|
};
|
|
485
|
+
/** Each word's first five letters, lowercased: enough to match its other forms in Russian and English. */
|
|
486
|
+
const wordStems = (text) => [...new Set(queryWords(text).map((word) => word.slice(0, 5)))];
|
|
487
|
+
/**
|
|
488
|
+
* The messages that share most of `stems`, at most `count`, oldest first, each cut by `cutAround`. With
|
|
489
|
+
* `ownFirst` the owner's own messages come first: the owner block is there for them.
|
|
490
|
+
*/
|
|
491
|
+
const shownLines = (read, stems, ownFirst, asked, count = SHOWN_LINES) => {
|
|
492
|
+
const scored = read.map(({ text, ...line }, at) => {
|
|
493
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
494
|
+
const lower = flat.toLowerCase();
|
|
495
|
+
const found = stems.filter((stem) => lower.includes(stem));
|
|
496
|
+
const first = found.reduce((least, stem) => Math.min(least, lower.indexOf(stem)), Number.POSITIVE_INFINITY);
|
|
497
|
+
return { ...line, flat, at, score: found.length + (ownFirst && line.outgoing ? 100 : 0), first };
|
|
498
|
+
});
|
|
499
|
+
const picked = [...scored].sort((a, b) => b.score - a.score || a.at - b.at).slice(0, count);
|
|
500
|
+
// A question is answered by the message after it, which rarely repeats the question's words.
|
|
501
|
+
const matches = (flat) => asked.filter((stem) => flat.toLowerCase().includes(stem)).length;
|
|
502
|
+
const asking = scored.reduce((best, line) => (matches(line.flat) > (best ? matches(best.flat) : 0) ? line : best), undefined);
|
|
503
|
+
const reply = asking && scored[asking.at + 1];
|
|
504
|
+
if (reply && !picked.includes(reply))
|
|
505
|
+
picked.push(reply);
|
|
506
|
+
return picked
|
|
507
|
+
.sort((a, b) => a.at - b.at)
|
|
508
|
+
.map(({ sender, flat, outgoing, first }) => {
|
|
509
|
+
const who = outgoing ? `${sender ?? "you"}${sender ? " (you)" : ""}: ` : sender ? `${sender}: ` : "";
|
|
510
|
+
return `${who}${cutAround(flat, first)}`;
|
|
511
|
+
});
|
|
512
|
+
};
|
|
513
|
+
/**
|
|
514
|
+
* A message's start says what it is about, so it stays: whole up to `SHOWN_CHARS`, else its head, and, when the
|
|
515
|
+
* match lies past it, the head and the part around the match. Centring on the match alone cut away the answer.
|
|
516
|
+
*/
|
|
517
|
+
const cutAround = (flat, first) => {
|
|
518
|
+
if (flat.length <= SHOWN_CHARS)
|
|
519
|
+
return flat;
|
|
520
|
+
if (!Number.isFinite(first) || first < SHOWN_CHARS - 25)
|
|
521
|
+
return `${flat.slice(0, SHOWN_CHARS)}…`;
|
|
522
|
+
const tail = SHOWN_CHARS - SHOWN_HEAD;
|
|
523
|
+
const from = Math.min(first - 30, flat.length - tail);
|
|
524
|
+
return `${flat.slice(0, SHOWN_HEAD)}…${flat.slice(from, from + tail)}${from + tail < flat.length ? "…" : ""}`;
|
|
525
|
+
};
|
|
406
526
|
/** The chats in readiness by how a meaning search with these vectors could see them, and the word matches outside any. */
|
|
407
527
|
const searchReadiness = (chats, meaning, outside) => {
|
|
408
528
|
const built = new Set(chats.filter(({ state }) => state !== "not-built").map(({ chat }) => chat));
|
|
@@ -68,6 +68,8 @@ export interface EmbeddingsService {
|
|
|
68
68
|
refresh?: RefreshOptions;
|
|
69
69
|
/** The word half's budget, from an explicit `--timeout`; the default limit otherwise. */
|
|
70
70
|
timeLimitMs?: number;
|
|
71
|
+
/** A made-up text like the answer, such as a reply to the query: searched by meaning too, its list fused with the query's. */
|
|
72
|
+
like?: string;
|
|
71
73
|
}): Promise<FoundConversations>;
|
|
72
74
|
/**
|
|
73
75
|
* The conversations of every built chat nearest in meaning to the one `message` is in, best first, never that
|
|
@@ -150,6 +152,8 @@ export interface FoundConversations {
|
|
|
150
152
|
hits: FoundConversation[];
|
|
151
153
|
/** The owner's own conversations nearest in meaning that `hits` left out. */
|
|
152
154
|
own?: FoundConversation[];
|
|
155
|
+
/** Owner chunks `own` left out because `hits` showed their conversation: the named-chat step may drop those. */
|
|
156
|
+
ownSpare?: FoundConversation[];
|
|
153
157
|
readiness: SearchReadiness;
|
|
154
158
|
/** Kept for callers of 0.141.0 and before; `readiness.wordsOnly` says more. */
|
|
155
159
|
embeddedOnlyElsewhere: Id[];
|
|
@@ -217,5 +221,7 @@ export interface FoundConversation {
|
|
|
217
221
|
by: ("meaning" | "words")[];
|
|
218
222
|
/** The chunk's text changed after it was embedded: the score is for what it said then (NEED-550 B). */
|
|
219
223
|
stale: boolean;
|
|
224
|
+
/** The chunk's messages that share most words with the query, as "sender: text", so a reader need not open it. */
|
|
225
|
+
lines?: string[];
|
|
220
226
|
}
|
|
221
227
|
export declare const embeddingsService: (deps: ServiceDeps) => EmbeddingsService;
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
-
error?: undefined;
|
|
18
17
|
chatId: string;
|
|
19
18
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
20
19
|
algorithm: string;
|
|
21
20
|
fetchedAt: string | null;
|
|
22
21
|
source: string;
|
|
22
|
+
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
|
@@ -9,9 +9,9 @@ export interface NamedChat {
|
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
11
|
* The private chat a query names by a word the two people there write as a name («Петька, привет»), learned from the
|
|
12
|
-
* messages: the one private chat holding most of the word's uses, at least twice as many as any other private chat
|
|
13
|
-
* where it is capitalised nearly every time. An ordinary word («счёт») is spread over
|
|
14
|
-
* lower case, so it names none.
|
|
12
|
+
* messages: the one private chat holding most of the word's uses, at least twice as many as any other private chat
|
|
13
|
+
* and `NAMED_SHARE` of them all, where it is capitalised nearly every time. An ordinary word («счёт») is spread over
|
|
14
|
+
* many chats and written in lower case, so it names none.
|
|
15
15
|
*/
|
|
16
16
|
export declare const namedChat: (store: MessageStore, account: AccountKey, messenger: Saved, accounts: AccountKey[] | undefined, words: string[]) => Promise<NamedChat | undefined>;
|
|
17
17
|
/** The query's words, lower case, without the ones nearly every message holds (unless it holds nothing else). */
|
|
@@ -8,11 +8,17 @@ const LEAST_USES = 3;
|
|
|
8
8
|
const SAMPLE = 50;
|
|
9
9
|
/** The share of those uses written with a capital letter that makes the word a name there. */
|
|
10
10
|
const CAPITALISED = 0.8;
|
|
11
|
+
/**
|
|
12
|
+
* The least share of the word's uses across every chat, groups too, that its private chat must hold. A place or a
|
|
13
|
+
* brand is capitalised too, but spread over many chats: a few uses in one dialog must not make it a name there. The
|
|
14
|
+
* count takes every word sharing the stem, so a real name's share reads low; under 1% is a word spread over chats.
|
|
15
|
+
*/
|
|
16
|
+
const NAMED_SHARE = 0.05;
|
|
11
17
|
/**
|
|
12
18
|
* The private chat a query names by a word the two people there write as a name («Петька, привет»), learned from the
|
|
13
|
-
* messages: the one private chat holding most of the word's uses, at least twice as many as any other private chat
|
|
14
|
-
* where it is capitalised nearly every time. An ordinary word («счёт») is spread over
|
|
15
|
-
* lower case, so it names none.
|
|
19
|
+
* messages: the one private chat holding most of the word's uses, at least twice as many as any other private chat
|
|
20
|
+
* and `NAMED_SHARE` of them all, where it is capitalised nearly every time. An ordinary word («счёт») is spread over
|
|
21
|
+
* many chats and written in lower case, so it names none.
|
|
16
22
|
*/
|
|
17
23
|
export const namedChat = async (store, account, messenger, accounts, words) => {
|
|
18
24
|
for (const word of words) {
|
|
@@ -22,6 +28,7 @@ export const namedChat = async (store, account, messenger, accounts, words) => {
|
|
|
22
28
|
// Quoted, a word is its forms without the longer words it begins: a name, not every word starting like it.
|
|
23
29
|
{ text: `"${word}"`, ...(accounts ? { accounts } : {}), limit: SAMPLE }, messenger);
|
|
24
30
|
const groups = (await store.queries.countQuery(execution, "chat")).sort((a, b) => b.count - a.count);
|
|
31
|
+
const total = groups.reduce((sum, { count }) => sum + count, 0);
|
|
25
32
|
const dialogs = [];
|
|
26
33
|
for (const group of groups) {
|
|
27
34
|
if (dialogs.length === 2)
|
|
@@ -34,6 +41,8 @@ export const namedChat = async (store, account, messenger, accounts, words) => {
|
|
|
34
41
|
const [best, next] = dialogs;
|
|
35
42
|
if (!best || best.count < LEAST_USES || (next && next.count * 2 > best.count))
|
|
36
43
|
continue;
|
|
44
|
+
if (best.count < total * NAMED_SHARE)
|
|
45
|
+
continue;
|
|
37
46
|
const { items } = await store.queries.matchQuery({
|
|
38
47
|
...execution,
|
|
39
48
|
chat: { account: best.source, chatId: best.chatId },
|
|
@@ -37,6 +37,27 @@ export interface ConversationsStore {
|
|
|
37
37
|
chatId: Id;
|
|
38
38
|
messageId: Id;
|
|
39
39
|
}[]): Promise<(ConversationSummary | undefined)[]>;
|
|
40
|
+
/** A found chunk's messages, oldest first, from `first` to `last` inside the conversation; none when not the account's. */
|
|
41
|
+
chunkMessages(key: AccountKey, conversationId: string, chunk: {
|
|
42
|
+
firstMessageId: Id;
|
|
43
|
+
lastMessageId: Id;
|
|
44
|
+
}, limit: number): Promise<{
|
|
45
|
+
id: Id;
|
|
46
|
+
sender: string | null;
|
|
47
|
+
text: string;
|
|
48
|
+
outgoing: boolean;
|
|
49
|
+
}[]>;
|
|
50
|
+
/** Per chunk, in the same order: replies to its messages that sit outside it, oldest first, at most `limit` each. */
|
|
51
|
+
chunkReplies(key: AccountKey, chunks: {
|
|
52
|
+
conversationId: string;
|
|
53
|
+
firstMessageId: Id;
|
|
54
|
+
lastMessageId: Id;
|
|
55
|
+
}[], limit: number): Promise<{
|
|
56
|
+
id: Id;
|
|
57
|
+
sender: string | null;
|
|
58
|
+
text: string;
|
|
59
|
+
outgoing: boolean;
|
|
60
|
+
}[][]>;
|
|
40
61
|
/** Every link a message has, the messenger's first. */
|
|
41
62
|
links(key: AccountKey, chatId: Id, messageId: Id, options?: {
|
|
42
63
|
limit: number;
|
|
@@ -51,6 +51,19 @@ export const conversationsStoreOver = (context) => {
|
|
|
51
51
|
const found = conversationQueries.summariesOf(context, accountPk, pks.filter((pk) => pk !== undefined));
|
|
52
52
|
return pks.map((pk) => (pk === undefined ? undefined : found.get(pk)));
|
|
53
53
|
},
|
|
54
|
+
chunkMessages: async (key, conversationId, { firstMessageId, lastMessageId }, limit) => {
|
|
55
|
+
const accountPk = findAccountPk(key);
|
|
56
|
+
const pk = Number(conversationId);
|
|
57
|
+
return accountPk === undefined || !Number.isSafeInteger(pk)
|
|
58
|
+
? []
|
|
59
|
+
: conversationQueries.chunkMessagesOf(context, accountPk, pk, firstMessageId, lastMessageId, limit);
|
|
60
|
+
},
|
|
61
|
+
chunkReplies: async (key, chunks, limit) => {
|
|
62
|
+
const accountPk = findAccountPk(key);
|
|
63
|
+
return accountPk === undefined
|
|
64
|
+
? chunks.map(() => [])
|
|
65
|
+
: conversationQueries.chunkRepliesOf(context, accountPk, chunks, limit);
|
|
66
|
+
},
|
|
54
67
|
links: async (key, chatId, messageId, options) => {
|
|
55
68
|
const chatKey = chatKeyOf(key, chatId);
|
|
56
69
|
return chatKey === undefined ? [] : conversationQueries.linksOf(context, chatKey, messageId, options?.limit);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** A statement's shape without its values: a query may hold the owner's words, so only the shape is printed. */
|
|
2
|
+
export declare const queryShape: (sql: string) => string;
|
|
3
|
+
/**
|
|
4
|
+
* With `WIRECAT_SQL_SLOW_MS` set, every statement slower than that many milliseconds prints its time, rows and shape
|
|
5
|
+
* to stderr. A cold search once read 1.5 GB through one query that looked cheap on an empty store; this names it.
|
|
6
|
+
*/
|
|
7
|
+
export declare const timeQueries: <C extends object>(client: C, methods: readonly string[]) => C;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** A statement's shape without its values: a query may hold the owner's words, so only the shape is printed. */
|
|
2
|
+
export const queryShape = (sql) => sql
|
|
3
|
+
.replace(/'(?:[^']|'')*'/g, "?")
|
|
4
|
+
.replace(/\b\d+(?:\.\d+)?\b/g, "?")
|
|
5
|
+
.replace(/\s+/g, " ")
|
|
6
|
+
.trim()
|
|
7
|
+
.slice(0, 400);
|
|
8
|
+
const rowsOf = (result) => Array.isArray(result)
|
|
9
|
+
? result.length
|
|
10
|
+
: result && typeof result === "object" && "changes" in result
|
|
11
|
+
? Number(result.changes)
|
|
12
|
+
: result === undefined || result === null
|
|
13
|
+
? 0
|
|
14
|
+
: 1;
|
|
15
|
+
/**
|
|
16
|
+
* With `WIRECAT_SQL_SLOW_MS` set, every statement slower than that many milliseconds prints its time, rows and shape
|
|
17
|
+
* to stderr. A cold search once read 1.5 GB through one query that looked cheap on an empty store; this names it.
|
|
18
|
+
*/
|
|
19
|
+
export const timeQueries = (client, methods) => {
|
|
20
|
+
const threshold = Number(process.env.WIRECAT_SQL_SLOW_MS);
|
|
21
|
+
if (!process.env.WIRECAT_SQL_SLOW_MS || !Number.isFinite(threshold))
|
|
22
|
+
return client;
|
|
23
|
+
const target = client;
|
|
24
|
+
for (const name of methods) {
|
|
25
|
+
const prepare = target[name];
|
|
26
|
+
if (typeof prepare !== "function")
|
|
27
|
+
continue;
|
|
28
|
+
target[name] = (sql, ...rest) => {
|
|
29
|
+
const statement = prepare.call(client, sql, ...rest);
|
|
30
|
+
if (typeof sql !== "string")
|
|
31
|
+
return statement;
|
|
32
|
+
for (const method of ["run", "all", "get"]) {
|
|
33
|
+
const original = statement[method];
|
|
34
|
+
statement[method] = (...parameters) => {
|
|
35
|
+
const started = performance.now();
|
|
36
|
+
const result = original.apply(statement, parameters);
|
|
37
|
+
const took = performance.now() - started;
|
|
38
|
+
if (took >= threshold)
|
|
39
|
+
process.stderr.write(`sql ${took.toFixed(0)} ms, ${rowsOf(result)} rows: ${queryShape(sql)}\n`);
|
|
40
|
+
return result;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
return statement;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
return client;
|
|
47
|
+
};
|
|
@@ -69,6 +69,27 @@ export declare const conversation: (context: StoreContext, accountKey: number, i
|
|
|
69
69
|
messages: Message[];
|
|
70
70
|
} | undefined;
|
|
71
71
|
export declare const conversationOf: ({ orm }: StoreContext, chatKey: number, messageId: Id) => string | undefined;
|
|
72
|
+
/** A found chunk's messages, oldest first: from `first` to `last` (external ids) inside one of the account's conversations. */
|
|
73
|
+
export declare const chunkMessagesOf: ({ orm }: StoreContext, accountPk: number, conversationPk: number, first: Id, last: Id, limit: number) => {
|
|
74
|
+
id: Id;
|
|
75
|
+
sender: string | null;
|
|
76
|
+
text: string;
|
|
77
|
+
outgoing: boolean;
|
|
78
|
+
}[];
|
|
79
|
+
/**
|
|
80
|
+
* Per chunk, in the same order: replies (the messenger's own reply links) to its messages that are not in it, oldest
|
|
81
|
+
* first. One query serves a whole page: one per hit added up to two seconds to a search.
|
|
82
|
+
*/
|
|
83
|
+
export declare const chunkRepliesOf: ({ orm }: StoreContext, accountPk: number, chunks: {
|
|
84
|
+
conversationId: string;
|
|
85
|
+
firstMessageId: Id;
|
|
86
|
+
lastMessageId: Id;
|
|
87
|
+
}[], limit: number) => {
|
|
88
|
+
id: Id;
|
|
89
|
+
sender: string | null;
|
|
90
|
+
text: string;
|
|
91
|
+
outgoing: boolean;
|
|
92
|
+
}[][];
|
|
72
93
|
/** Every link a message has, the messenger's first, then the strongest. */
|
|
73
94
|
export declare const linksOf: ({ orm }: StoreContext, chatKey: number, messageId: Id, limit?: number) => StoredLink[];
|
|
74
95
|
/** Candidates only: the caller checks which parent each child chooses, using the same link reader. */
|
|
@@ -383,6 +383,56 @@ export const conversationOf = ({ orm }, chatKey, messageId) => {
|
|
|
383
383
|
.get();
|
|
384
384
|
return found ? String(found.pk) : undefined;
|
|
385
385
|
};
|
|
386
|
+
/** A found chunk's messages, oldest first: from `first` to `last` (external ids) inside one of the account's conversations. */
|
|
387
|
+
export const chunkMessagesOf = ({ orm }, accountPk, conversationPk, first, last, limit) => orm
|
|
388
|
+
.all(sql `SELECT m.external_id AS id, m.sender_name AS sender, m.text, m.outgoing
|
|
389
|
+
FROM conversations c
|
|
390
|
+
JOIN chats ch ON ch.id = c.chat_id AND ch.account_id = ${accountPk}
|
|
391
|
+
JOIN messages f ON f.chat_id = c.chat_id AND f.external_id = ${first}
|
|
392
|
+
JOIN messages l ON l.chat_id = c.chat_id AND l.external_id = ${last}
|
|
393
|
+
JOIN conversation_messages cm ON cm.conversation_id = c.id
|
|
394
|
+
JOIN messages m ON m.id = cm.message_id
|
|
395
|
+
WHERE c.id = ${conversationPk} AND m.deleted_at IS NULL AND m.text != ''
|
|
396
|
+
AND (m.sent_at, m.id) >= (f.sent_at, f.id) AND (m.sent_at, m.id) <= (l.sent_at, l.id)
|
|
397
|
+
ORDER BY m.sent_at, m.id LIMIT ${limit}`)
|
|
398
|
+
.map(({ outgoing, ...line }) => ({ ...line, outgoing: Boolean(outgoing) }));
|
|
399
|
+
/**
|
|
400
|
+
* Per chunk, in the same order: replies (the messenger's own reply links) to its messages that are not in it, oldest
|
|
401
|
+
* first. One query serves a whole page: one per hit added up to two seconds to a search.
|
|
402
|
+
*/
|
|
403
|
+
export const chunkRepliesOf = ({ orm }, accountPk, chunks, limit) => {
|
|
404
|
+
const found = chunks.map(() => []);
|
|
405
|
+
const wanted = chunks.map(({ conversationId, firstMessageId, lastMessageId }) => ({
|
|
406
|
+
c: Number(conversationId),
|
|
407
|
+
f: firstMessageId,
|
|
408
|
+
l: lastMessageId,
|
|
409
|
+
}));
|
|
410
|
+
if (!wanted.length)
|
|
411
|
+
return found;
|
|
412
|
+
const rows = orm.all(sql `WITH want(n, conv, first, last) AS (SELECT key, json_extract(value, '$.c'), json_extract(value, '$.f'),
|
|
413
|
+
json_extract(value, '$.l') FROM json_each(${JSON.stringify(wanted)})),
|
|
414
|
+
inside(n, id) AS MATERIALIZED (SELECT w.n, m.id
|
|
415
|
+
FROM want w
|
|
416
|
+
JOIN conversations c ON c.id = w.conv
|
|
417
|
+
JOIN chats ch ON ch.id = c.chat_id AND ch.account_id = ${accountPk}
|
|
418
|
+
JOIN messages f ON f.chat_id = c.chat_id AND f.external_id = w.first
|
|
419
|
+
JOIN messages l ON l.chat_id = c.chat_id AND l.external_id = w.last
|
|
420
|
+
JOIN conversation_messages cm ON cm.conversation_id = c.id
|
|
421
|
+
JOIN messages m ON m.id = cm.message_id
|
|
422
|
+
WHERE (m.sent_at, m.id) >= (f.sent_at, f.id) AND (m.sent_at, m.id) <= (l.sent_at, l.id))
|
|
423
|
+
SELECT DISTINCT i.n, r.external_id AS id, r.sender_name AS sender, r.text, r.outgoing, r.sent_at, r.id AS pk
|
|
424
|
+
FROM inside i
|
|
425
|
+
JOIN message_links k ON k.parent_id = i.id AND k.kind = 'reply' AND k.stale_at IS NULL
|
|
426
|
+
JOIN messages r ON r.id = k.message_id
|
|
427
|
+
WHERE r.deleted_at IS NULL AND r.text != '' AND NOT EXISTS (SELECT 1 FROM inside o WHERE o.n = i.n AND o.id = r.id)
|
|
428
|
+
ORDER BY i.n, r.sent_at, r.id`);
|
|
429
|
+
for (const { n, id, sender, text, outgoing } of rows) {
|
|
430
|
+
const list = found[n];
|
|
431
|
+
if (list && list.length < limit)
|
|
432
|
+
list.push({ id, sender, text, outgoing: Boolean(outgoing) });
|
|
433
|
+
}
|
|
434
|
+
return found;
|
|
435
|
+
};
|
|
386
436
|
const staleLink = (chatKey) => sql `(${messageLinks.staleAt} IS NOT NULL
|
|
387
437
|
OR EXISTS (SELECT 1 FROM message_revisions r WHERE r.message_id IN (${messageLinks.messageId}, ${messageLinks.parentId})
|
|
388
438
|
AND r.created_at >= ${messageLinks.createdAt})
|