@wirecat/cli-core 0.608.0 → 0.609.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.
Files changed (68) hide show
  1. package/CHANGELOG.md +67 -1
  2. package/dist/background/deliver.d.ts +12 -1
  3. package/dist/background/deliver.js +38 -5
  4. package/dist/background/report/render.d.ts +61 -0
  5. package/dist/background/report/render.js +208 -0
  6. package/dist/background/report/schema.d.ts +66 -0
  7. package/dist/background/report/schema.js +191 -0
  8. package/dist/background/report/templates/morning-digest.email.en.liquid +79 -0
  9. package/dist/background/report/templates/morning-digest.email.ru.liquid +79 -0
  10. package/dist/background/report/templates/morning-digest.telegram.en.liquid +77 -0
  11. package/dist/background/report/templates/morning-digest.telegram.ru.liquid +77 -0
  12. package/dist/background/report/templates/morning-digest.text.en.liquid +76 -0
  13. package/dist/background/report/templates/morning-digest.text.ru.liquid +76 -0
  14. package/dist/background/report/view.d.ts +88 -0
  15. package/dist/background/report/view.js +152 -0
  16. package/dist/background/schedules.d.ts +6 -1
  17. package/dist/background/schedules.js +24 -7
  18. package/dist/cli/embedding-choice.d.ts +4 -1
  19. package/dist/cli/embedding-choice.js +6 -3
  20. package/dist/cli/messenger/models-command.js +46 -18
  21. package/dist/cli/messenger/search-answers.js +11 -2
  22. package/dist/cli/model-catalogue-command.d.ts +33 -0
  23. package/dist/cli/model-catalogue-command.js +110 -21
  24. package/dist/cli/schedule/schedule-command.js +18 -0
  25. package/dist/cli/store-settings.js +39 -3
  26. package/dist/crm/cli/csv.d.ts +18 -5
  27. package/dist/crm/cli/csv.js +30 -19
  28. package/dist/crm/cli/index.d.ts +1 -0
  29. package/dist/crm/cli/index.js +1 -0
  30. package/dist/embeddings/models.d.ts +185 -5
  31. package/dist/embeddings/models.js +119 -5
  32. package/dist/entities/index.d.ts +24 -0
  33. package/dist/entities/index.js +2 -1
  34. package/dist/entities/model.d.ts +42 -1
  35. package/dist/entities/model.js +20 -1
  36. package/dist/render/liquid.d.ts +14 -0
  37. package/dist/render/liquid.js +30 -0
  38. package/dist/replies/template.js +3 -22
  39. package/dist/search/lucene/plain.js +4 -1
  40. package/dist/search/question-plan.js +2 -1
  41. package/dist/sends/permissions.js +4 -0
  42. package/dist/services/embeddings-maintenance.d.ts +1 -1
  43. package/dist/services/embeddings-maintenance.js +6 -6
  44. package/dist/services/index.d.ts +2 -0
  45. package/dist/services/index.js +2 -0
  46. package/dist/services/meeting-model.d.ts +1 -1
  47. package/dist/services/meeting-model.js +4 -4
  48. package/dist/services/messages-meaning.js +25 -4
  49. package/dist/services/model-downloads.js +1 -1
  50. package/dist/services/notes-search.d.ts +1 -1
  51. package/dist/services/notes-search.js +2 -2
  52. package/dist/services/search-all.d.ts +2 -0
  53. package/dist/services/search-all.js +30 -8
  54. package/dist/services/text-model-choice.d.ts +50 -0
  55. package/dist/services/text-model-choice.js +151 -0
  56. package/dist/store/exports.d.ts +1 -0
  57. package/dist/store/exports.js +1 -0
  58. package/dist/store/index.d.ts +1 -0
  59. package/dist/store/index.js +1 -0
  60. package/dist/store/sqlite/owner-languages.d.ts +13 -0
  61. package/dist/store/sqlite/owner-languages.js +49 -0
  62. package/dist/store/sqlite/reported-relations.js +5 -1
  63. package/dist/store/sqlite/vectors.d.ts +2 -0
  64. package/dist/store/sqlite/vectors.js +5 -0
  65. package/dist/store/vectors.d.ts +2 -0
  66. package/dist/store/vectors.js +1 -0
  67. package/package.json +2 -2
  68. package/parity.json +13 -0
@@ -31,6 +31,10 @@ export const DEFAULT_PERMISSIONS = {
31
31
  "server.stop": "ask",
32
32
  "server.restart": "ask",
33
33
  "models.download": "ask",
34
+ // NEED-2357.f: many MCP clients (ChatGPT) cannot answer a question, and a switch deletes nothing; kept as a key so a
35
+ // profile can still deny it.
36
+ "models.set": "allow",
37
+ "models.add": "ask",
34
38
  "images.models.download": "ask",
35
39
  "schedule.run": "ask",
36
40
  "schedule.exec": "ask",
@@ -34,7 +34,7 @@ export declare const embeddingTarget: (deps: ModelDeps, choice?: ModelChoice) =>
34
34
  id: string;
35
35
  key: string;
36
36
  dims: number;
37
- speed: number;
37
+ speed: number | null;
38
38
  price: undefined;
39
39
  installed: boolean;
40
40
  perBatch: number;
@@ -2,7 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { CHUNK_CHARS, chunkHash, chunkTextOf } from "../conversations/chunks.js";
3
3
  import { RULES_VERSION } from "../conversations/link.js";
4
4
  import { defaultThreads, isTextModelInstalled, openEmbedder, textModelsDirectory, } from "../embeddings/embed.js";
5
- import { DEFAULT_TEXT_MODEL, textModel, vectorModelKey } from "../embeddings/models.js";
5
+ import { chosenTextModel, textModel, vectorModelKey } from "../embeddings/models.js";
6
6
  import { remoteKey } from "../embeddings/remote.js";
7
7
  import { CONTEXT_MESSAGES, CONTEXT_MINUTES } from "../images/context/index.js";
8
8
  import { registeredImageProviders } from "../images/registry.js";
@@ -22,7 +22,7 @@ const CHARS_PER_TOKEN_AT_LEAST = 3;
22
22
  /** The download is the error's `next` step, named only by a CLI that has `models` (`failureSteps`). */
23
23
  const notDownloaded = (id) => new CliError("not_found", `${id} is not downloaded on this machine`, { reason: "model.not-downloaded", model: id });
24
24
  export const notBuiltError = (deps, chatId) => new CliError("not_found", `chat ${chatId} has no conversations yet — \`${typedCommand(deps.messenger.app.command, `conversations links rebuild --chat ${chatId}`)}\``);
25
- export const embeddingTarget = (deps, choice = DEFAULT_TEXT_MODEL) => {
25
+ export const embeddingTarget = (deps, choice = chosenTextModel(deps.env).id) => {
26
26
  if (typeof choice !== "string") {
27
27
  const { remote, apiKey, concurrency = 4 } = choice;
28
28
  return {
@@ -36,13 +36,13 @@ export const embeddingTarget = (deps, choice = DEFAULT_TEXT_MODEL) => {
36
36
  open: async () => (await import("../embeddings/remote.js")).openRemote(remote, apiKey, { concurrency }),
37
37
  };
38
38
  }
39
- const model = textModel(choice);
39
+ const model = textModel(choice, deps.env);
40
40
  const directory = textModelsDirectory(deps.env);
41
41
  return {
42
42
  id: model.id,
43
43
  key: vectorModelKey(model),
44
44
  dims: model.dims,
45
- speed: model.chunksPerSecond,
45
+ speed: model.chunksPerSecond ?? null,
46
46
  price: undefined,
47
47
  installed: isTextModelInstalled(model, directory),
48
48
  perBatch: PER_SESSION,
@@ -256,7 +256,7 @@ export const embeddingsMaintenance = (deps) => {
256
256
  return { model: target.id, chats };
257
257
  return { model: target.id, chats, unbuiltGroups: (await store.vectors.unbuiltGroups(account)).length };
258
258
  },
259
- refresh: async ({ chat, model: choice = DEFAULT_TEXT_MODEL, build = true, embed = true, maxChats = REFRESH_BOUNDS.maxChats, maxChunks = REFRESH_BOUNDS.maxChunks, threads, progress, maxMessages, check, messages = true, }) => {
259
+ refresh: async ({ chat, model: choice = chosenTextModel(deps.env).id, build = true, embed = true, maxChats = REFRESH_BOUNDS.maxChats, maxChunks = REFRESH_BOUNDS.maxChunks, threads, progress, maxMessages, check, messages = true, }) => {
260
260
  check?.();
261
261
  const store = await deps.store();
262
262
  const account = await deps.account();
@@ -288,7 +288,7 @@ export const embeddingsMaintenance = (deps) => {
288
288
  }
289
289
  }
290
290
  const embedded = [];
291
- const wantsMessages = embed && messages && target.installed && choice === DEFAULT_TEXT_MODEL;
291
+ const wantsMessages = embed && messages && target.installed && choice === chosenTextModel(deps.env).id;
292
292
  const toEmbed = wantsMessages ? await messagesToEmbed(chatId, target.key, maxChunks, check) : undefined;
293
293
  let messagesEmbedded = 0;
294
294
  if (embed && target.installed) {
@@ -55,6 +55,7 @@ import { type SearchesService } from "./searches.js";
55
55
  import { type TagsService } from "./tags.js";
56
56
  import { type TasksService } from "./tasks.js";
57
57
  import { type TopicsService } from "./topics.js";
58
+ export { chosenTextModel, DEFAULT_TEXT_MODEL, type TextModel, textModel, textModels, textModelsFile, vectorModelKey, } from "../embeddings/models.js";
58
59
  export type { MeetingProjectCandidateInput, MeetingProjectCandidateMatch, MeetingProjectCandidateOptions, MeetingProjectCandidateReader, MeetingProjectCandidates, } from "../meetings/index.js";
59
60
  export type { AccountService } from "./account.js";
60
61
  export { accountService } from "./account.js";
@@ -112,6 +113,7 @@ export type { TagsAdded, TagsRemoved, TagsService, TagTargetInput, TagTargetView
112
113
  export { tagsService } from "./tags.js";
113
114
  export type { ClosedTask, TaskCard, TaskItem, TaskList, TaskListRequest, TasksService, TaskView, } from "./tasks.js";
114
115
  export { closedStateOf, taskStateOf, tasksService, taskTypeOf, taskView } from "./tasks.js";
116
+ export { addCustomTextModel, type TextModelSwitch, useTextModel } from "./text-model-choice.js";
115
117
  export { type TopicsService, topicsService } from "./topics.js";
116
118
  export interface Services {
117
119
  metadata: ReturnType<typeof metadataService>;
@@ -46,6 +46,7 @@ import { searchesService } from "./searches.js";
46
46
  import { tagsService } from "./tags.js";
47
47
  import { tasksService } from "./tasks.js";
48
48
  import { topicsService } from "./topics.js";
49
+ export { chosenTextModel, DEFAULT_TEXT_MODEL, textModel, textModels, textModelsFile, vectorModelKey, } from "../embeddings/models.js";
49
50
  export { accountService } from "./account.js";
50
51
  export { adminService } from "./admin.js";
51
52
  export { archiveService } from "./archive.js";
@@ -79,6 +80,7 @@ export { searchRecordOf } from "./search-record.js";
79
80
  export { savedSearchItem, searchesService } from "./searches.js";
80
81
  export { tagsService } from "./tags.js";
81
82
  export { closedStateOf, taskStateOf, tasksService, taskTypeOf, taskView } from "./tasks.js";
83
+ export { addCustomTextModel, useTextModel } from "./text-model-choice.js";
82
84
  export { topicsService } from "./topics.js";
83
85
  /** The shared services, with the messenger's `services` override applied — commands and MCP tools alike. */
84
86
  export const servicesFor = (deps) => {
@@ -21,7 +21,7 @@ export interface MeetingEmbedderOptions {
21
21
  maxResponseBytes?: number;
22
22
  }
23
23
  /** Validates a descriptor without reading keys or model files or opening a model. */
24
- export declare const meetingEmbeddingModel: (choice: ModelChoice) => MeetingEmbeddingModel;
24
+ export declare const meetingEmbeddingModel: (choice: ModelChoice, env?: NodeJS.ProcessEnv) => MeetingEmbeddingModel;
25
25
  export declare const createMeetingRemoteModel: (input: Parameters<typeof remoteModel>[0]) => RemoteModel;
26
26
  /** Explicit opening only; installed local models and the existing remote engine are reused. */
27
27
  export declare const openMeetingEmbedder: (choice: ModelChoice, options?: MeetingEmbedderOptions) => Promise<MeetingEmbedder>;
@@ -29,9 +29,9 @@ const validatedRemote = (remote) => {
29
29
  return result;
30
30
  };
31
31
  /** Validates a descriptor without reading keys or model files or opening a model. */
32
- export const meetingEmbeddingModel = (choice) => {
32
+ export const meetingEmbeddingModel = (choice, env) => {
33
33
  if (typeof choice === "string") {
34
- const model = textModel(choice);
34
+ const model = textModel(choice, env);
35
35
  return { key: vectorModelKey(model), dims: model.dims, kind: "local", model: model.id };
36
36
  }
37
37
  if (!choice || typeof choice !== "object" || !choice.remote)
@@ -105,7 +105,7 @@ const boundedResponse = async (response, maxBytes, signal) => {
105
105
  };
106
106
  /** Explicit opening only; installed local models and the existing remote engine are reused. */
107
107
  export const openMeetingEmbedder = async (choice, options = {}) => {
108
- const descriptor = meetingEmbeddingModel(choice);
108
+ const descriptor = meetingEmbeddingModel(choice, options.env);
109
109
  const { signal } = options;
110
110
  cancelled(signal);
111
111
  const maxInputBytes = integer(options.maxInputBytes ?? 1024 * 1024, "input byte budget", 16 * 1024 * 1024);
@@ -115,7 +115,7 @@ export const openMeetingEmbedder = async (choice, options = {}) => {
115
115
  let engine;
116
116
  let remoteFailure;
117
117
  if (typeof choice === "string") {
118
- const model = textModel(choice);
118
+ const model = textModel(choice, options.env);
119
119
  const directory = options.directory ?? textModelsDirectory(options.env);
120
120
  if (!isTextModelInstalled(model, directory))
121
121
  throw new CliError("configuration_error", "The explicit local embedding model is not installed");
@@ -1,13 +1,34 @@
1
- import { DEFAULT_TEXT_MODEL } from "../embeddings/models.js";
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { parseLucene } from "@wirecat/cli-base/query";
3
+ import { chosenTextModel } from "../embeddings/models.js";
4
+ import { meaningWords } from "../search/lucene/meaning-parts.js";
5
+ import { validateFields } from "../search/lucene/registry.js";
6
+ import { SEARCH_QUERY } from "../search/lucene/types.js";
7
+ import { questionLookup, questionText } from "../search/question-plan.js";
2
8
  import { embeddingTarget, withEmbedder } from "./embeddings-maintenance.js";
3
9
  import { MEANING_DEPTH } from "./messages-discovery.js";
4
10
  import { plainWords } from "./pictures.js";
11
+ // The text notes embed: `search all` compares cosines across sources, so all must embed one text (IDEA-249).
12
+ const meaningText = (question) => {
13
+ try {
14
+ const text = questionLookup(question) === undefined ? question : questionText(question);
15
+ const root = validateFields(parseLucene(text, { ...SEARCH_QUERY, defaultField: "text" })).root;
16
+ // `content:invoice` or `budg*` leave notes nothing to embed; mail keeps its words then.
17
+ return meaningWords(root) || plainWords(question);
18
+ }
19
+ catch (error) {
20
+ if (error instanceof CliError)
21
+ return plainWords(question);
22
+ throw error;
23
+ }
24
+ };
5
25
  /**
6
26
  * Discovery's meaning half: the default local model over each message's own vector. It runs only when the model is
7
27
  * on disk and vectors exist — never a download, never a remote model — and any failure leaves the words alone.
8
28
  */
9
29
  export const meaningLane = (deps) => async (question, accounts, shared, within) => {
10
- const target = embeddingTarget(deps, DEFAULT_TEXT_MODEL);
30
+ const model = chosenTextModel(deps.env).id;
31
+ const target = embeddingTarget(deps, model);
11
32
  const skipped = (reason, step) => ({
12
33
  skipped: { reason, model: target.id, ...(step ? { step } : {}) },
13
34
  });
@@ -30,7 +51,7 @@ export const meaningLane = (deps) => async (question, accounts, shared, within)
30
51
  }
31
52
  if (ready.length === 0 && mail.size === 0)
32
53
  return skipped("no message has a vector yet", "conversations.rebuild");
33
- const words = plainWords(question);
54
+ const words = meaningText(question);
34
55
  try {
35
56
  const ranked = [];
36
57
  if (words) {
@@ -62,7 +83,7 @@ export const meaningLane = (deps) => async (question, accounts, shared, within)
62
83
  if (shared && !deps.embedders)
63
84
  await lookUp(await shared.get(target.key, () => target.open()));
64
85
  else
65
- await withEmbedder(deps, target, DEFAULT_TEXT_MODEL, {}, lookUp);
86
+ await withEmbedder(deps, target, model, {}, lookUp);
66
87
  }
67
88
  if (ranked.length === 0 && without.length === accounts.length)
68
89
  return skipped("no message has a vector yet", "conversations.rebuild");
@@ -22,7 +22,7 @@ const nativeRuntime = async ({ env, progress = () => { } }) => {
22
22
  * loaded once on a word. Nothing is downloaded when it is already there; it is still loaded.
23
23
  */
24
24
  export const downloadTextModel = async (id, { env, progress = () => { }, bytes, acceptTerms = false }) => {
25
- const model = textModel(id);
25
+ const model = textModel(id, env);
26
26
  if (model.terms && !acceptTerms) {
27
27
  throw new CliError("validation_error", `${model.id} comes under the ${model.licence} (${model.terms}): read them, then run this again with --accept-terms`);
28
28
  }
@@ -41,7 +41,7 @@ export declare const searchNotesQuery: (store: MessageStore, request: NotesSearc
41
41
  hasMore: boolean;
42
42
  }>;
43
43
  export interface NotesEmbedOptions {
44
- /** A local text model by id; e5-small, as conversations use, when absent. */
44
+ /** A local text model by id; the one `models use` chose, as conversations use, when absent. */
45
45
  model?: string;
46
46
  /** How many chunks this run embeds at most; the next run continues. */
47
47
  maxChunks?: number;
@@ -3,7 +3,7 @@ import { dateRange, parseLucene, timezoneOf } from "@wirecat/cli-base/query";
3
3
  import { INTERNAL_NOTES } from "../domain/providers.js";
4
4
  import { normalizeTag } from "../domain/tags.js";
5
5
  import { defaultThreads, isTextModelInstalled, openEmbedder, textModelsDirectory, } from "../embeddings/embed.js";
6
- import { DEFAULT_TEXT_MODEL, meaningFloor, textModel, vectorModelKey } from "../embeddings/models.js";
6
+ import { chosenTextModel, meaningFloor, textModel, vectorModelKey } from "../embeddings/models.js";
7
7
  import { DEFAULT_IMAGE_MODEL, imageModel } from "../images/picture/models.js";
8
8
  import { entriesOfList, fitting } from "../search/account-list.js";
9
9
  import { fieldsOfQuery as fieldsOf, meaningWords } from "../search/lucene/meaning-parts.js";
@@ -72,7 +72,7 @@ const downloadHint = (model, command) => command === undefined
72
72
  ? `install it with a WireCat CLI that has \`models download\` (tg, max or wa); they share the model folder`
73
73
  : `\`${command} models download ${model}\``;
74
74
  export const localModel = (choice, env, command) => {
75
- const model = textModel(choice ?? DEFAULT_TEXT_MODEL);
75
+ const model = textModel(choice ?? chosenTextModel(env).id, env);
76
76
  const directory = textModelsDirectory(env);
77
77
  if (!isTextModelInstalled(model, directory))
78
78
  throw new CliError("not_found", `${model.id} is not downloaded — ${downloadHint(model.id, command)}`, {
@@ -95,6 +95,8 @@ export interface SearchAllFound {
95
95
  server?: ServerSearched;
96
96
  /** What the store held of the chats the messages were searched in; absent when messages were not searched. */
97
97
  coverage?: SearchCoverage;
98
+ /** When nothing was found by all the words: the words that alone find nothing in `searched` either. */
99
+ unmatched?: string[];
98
100
  }
99
101
  export interface SearchAllRequest {
100
102
  text: string;
@@ -5,7 +5,7 @@ import { parseLocator } from "../domain/locator.js";
5
5
  import { senderIsMe } from "../domain/models.js";
6
6
  import { holdsKind, INTERNAL_NOTES } from "../domain/providers.js";
7
7
  import { runEmbedders } from "../embeddings/embed.js";
8
- import { DEFAULT_TEXT_MODEL } from "../embeddings/models.js";
8
+ import { chosenTextModel } from "../embeddings/models.js";
9
9
  import { plainQuery } from "../search/lucene/plain.js";
10
10
  import { MESSAGE_PARSING, SEARCH_QUERY } from "../search/lucene/types.js";
11
11
  import { planQuestion, questionLookup } from "../search/question-plan.js";
@@ -57,6 +57,19 @@ export const titleWords = (text) => {
57
57
  })());
58
58
  return { words, anyWord: clauses.length > 1 && clauses.every(({ occur }) => occur === "should") };
59
59
  };
60
+ /** The single words of an all-words query, when it has two to eight of them; none for OR, fields or phrases. */
61
+ const strictWords = (text) => {
62
+ try {
63
+ const { words, anyWord } = titleWords(text);
64
+ const unique = [...new Set(words)];
65
+ return anyWord || unique.length < 2 || unique.length > 8 || unique.some((word) => /\s/u.test(word)) ? [] : unique;
66
+ }
67
+ catch (error) {
68
+ if (error instanceof CliError)
69
+ return [];
70
+ throw error;
71
+ }
72
+ };
60
73
  /** The accounts of every CRM the store holds copies of. */
61
74
  export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
62
75
  /**
@@ -153,7 +166,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
153
166
  ? {
154
167
  skipped: {
155
168
  reason: "the query uses NOT, or a filter under OR or in a group, which meaning cannot follow",
156
- model: DEFAULT_TEXT_MODEL,
169
+ model: chosenTextModel(request.env).id,
157
170
  },
158
171
  }
159
172
  : await meaning(request.text, read, embedders);
@@ -303,6 +316,14 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
303
316
  }
304
317
  const ordered = oneList(lists, cosines);
305
318
  const more = hasMore || ordered.length > window;
319
+ const { backend: _backend, server: _server, ...local } = asked;
320
+ const unmatched = [];
321
+ if (!ordered.length && !offset && !discover)
322
+ for (const word of strictWords(request.text)) {
323
+ const alone = await searchAll(store, account, { ...local, text: word, limit: 1, only: searched });
324
+ if (!alone.items.length)
325
+ unmatched.push(word);
326
+ }
306
327
  return {
307
328
  query: asked.text,
308
329
  items: ordered.slice(offset, window),
@@ -317,14 +338,14 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
317
338
  ...(by.mail === undefined ? {} : { mail: by.mail }),
318
339
  ...(server === undefined ? {} : { server }),
319
340
  ...(coverage === undefined ? {} : { coverage }),
341
+ ...(unmatched.length ? { unmatched } : {}),
320
342
  };
321
343
  };
322
344
  /**
323
- * Every source's hits as one list: by the rank each has in its own source, then by cosine. Rank alone gave every
324
- * source's hit at one rank the same score, so the sources took turns and the order among them was the order they were
325
- * read in (MEMO-37). One model scores every source, so cosine compares across them; a hit meaning did not find comes
326
- * after those it did at the same rank. Each source's own order is kept, so recall at any depth past the number of
327
- * sources does not change.
345
+ * Every source's hits as one list: each source's best hit first, then every other hit by cosine, then by its rank in
346
+ * its source. Taking turns by rank (MEMO-37) gave each of two sources half of a ten-hit page however weak its hits;
347
+ * one model scores every source, so cosine compares across them (IDEA-249). A hit meaning did not find comes after
348
+ * those it did.
328
349
  */
329
350
  const oneList = (lists, cosines) => {
330
351
  const place = new Map();
@@ -335,7 +356,8 @@ const oneList = (lists, cosines) => {
335
356
  place.set(item.ref, { item, rank });
336
357
  });
337
358
  const cosine = (ref) => cosines.get(ref) ?? Number.NEGATIVE_INFINITY;
359
+ const head = (rank) => Math.min(rank, 1);
338
360
  return [...place.values()]
339
- .sort((a, b) => a.rank - b.rank || cosine(b.item.ref) - cosine(a.item.ref))
361
+ .sort((a, b) => head(a.rank) - head(b.rank) || cosine(b.item.ref) - cosine(a.item.ref) || a.rank - b.rank)
340
362
  .map(({ item }) => item);
341
363
  };
@@ -0,0 +1,50 @@
1
+ import * as v from "valibot";
2
+ import { type TextModel } from "../embeddings/models.js";
3
+ import type { Fetch } from "../speech/install.js";
4
+ export interface TextModelSwitch {
5
+ model: TextModel;
6
+ previous: string;
7
+ /** Chunk texts the previous model has vectors for and this one has not: what the next syncs embed. */
8
+ toEmbed: number | null;
9
+ /** Embedding time alone at the model's measured speed, done a part per sync; `null` when the speed or the count is unknown. */
10
+ estimateSeconds: number | null;
11
+ }
12
+ /**
13
+ * Makes `id` the model every embed and every search by meaning uses, in every WireCat CLI. Vectors are kept per
14
+ * model, so nothing is deleted or re-embedded here: the next syncs embed what the new model lacks, and search by
15
+ * meaning reads only the new model's vectors, finding by words what it has not reached yet.
16
+ */
17
+ export declare const useTextModel: (id: string, { env, command }: {
18
+ env: NodeJS.ProcessEnv;
19
+ command: string;
20
+ }) => Promise<TextModelSwitch>;
21
+ /** What `models add --payload` takes: where the model is and how to run it; the files' sizes and hashes are looked up. */
22
+ export declare const CustomModelRequest: v.StrictObjectSchema<{
23
+ /** A Hugging Face repository, `owner/name`. */
24
+ readonly repository: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "is not a Hugging Face repository, owner/name">]>;
25
+ /** A branch, tag or commit; pinned to the commit it names now. */
26
+ readonly revision: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 200, undefined>]>, undefined>;
27
+ readonly onnx: v.StringSchema<undefined>;
28
+ readonly externalData: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
29
+ readonly dims: v.NumberSchema<undefined>;
30
+ readonly pooling: v.PicklistSchema<["mean", "sentence_embedding"], undefined>;
31
+ readonly prefix: v.StrictObjectSchema<{
32
+ readonly query: v.StringSchema<undefined>;
33
+ readonly passage: v.StringSchema<undefined>;
34
+ }, undefined>;
35
+ readonly maxTokens: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
36
+ readonly title: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
37
+ readonly languages: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
38
+ readonly licence: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
39
+ readonly chunksPerSecond: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
40
+ }, undefined>;
41
+ export type CustomModelRequest = v.InferOutput<typeof CustomModelRequest>;
42
+ /**
43
+ * A model from a Hugging Face repository, pinned to one commit with each file's size and sha256, as the built-in
44
+ * ones are, and kept in the shared settings file beside the choice. It is checked again on `models download`,
45
+ * which also embeds a word to see the vector has `dims` numbers. Adding an id again replaces its definition.
46
+ */
47
+ export declare const addCustomTextModel: (id: string, payload: unknown, { env, fetch: get }: {
48
+ env: NodeJS.ProcessEnv;
49
+ fetch?: Fetch;
50
+ }) => Promise<TextModel>;
@@ -0,0 +1,151 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { CliError } from "@wirecat/cli-base";
4
+ import * as v from "valibot";
5
+ import { isTextModelInstalled, textModelsDirectory } from "../embeddings/embed.js";
6
+ import { CustomTextModelShape, chosenTextModel, readTextModelsSection, textModel, textModels, vectorModelKey, writeTextModelsSection, } from "../embeddings/models.js";
7
+ import { storePath } from "../store/path.js";
8
+ import { openStore } from "../store/store.js";
9
+ /**
10
+ * Makes `id` the model every embed and every search by meaning uses, in every WireCat CLI. Vectors are kept per
11
+ * model, so nothing is deleted or re-embedded here: the next syncs embed what the new model lacks, and search by
12
+ * meaning reads only the new model's vectors, finding by words what it has not reached yet.
13
+ */
14
+ export const useTextModel = async (id, { env, command }) => {
15
+ const model = textModel(id, env);
16
+ if (!isTextModelInstalled(model, textModelsDirectory(env)))
17
+ throw new CliError("not_found", `${model.id} is not downloaded — \`${command} models download ${model.id}${model.terms ? " --accept-terms" : ""}\` first`, { reason: "model.not-downloaded", model: model.id });
18
+ const previous = chosenTextModel(env).id;
19
+ const before = textModels(env).find((one) => one.id === previous);
20
+ const toEmbed = previous === model.id ? 0 : before ? await missingVectors(before, model, env) : null;
21
+ writeTextModelsSection({ ...readTextModelsSection(env), use: model.id }, env);
22
+ return {
23
+ model,
24
+ previous,
25
+ toEmbed,
26
+ estimateSeconds: toEmbed === null || model.chunksPerSecond === undefined ? null : Math.ceil(toEmbed / model.chunksPerSecond),
27
+ };
28
+ };
29
+ const missingVectors = async (from, to, env) => {
30
+ if (!existsSync(storePath(env)))
31
+ return null;
32
+ // Only an estimate: a store that is busy, damaged or older than this build must not stop the switch.
33
+ try {
34
+ const store = await openStore({ env });
35
+ try {
36
+ const counts = await store.vectors.vectorCounts([vectorModelKey(from), vectorModelKey(to)]);
37
+ return Math.max(0, (counts.get(vectorModelKey(from)) ?? 0) - (counts.get(vectorModelKey(to)) ?? 0));
38
+ }
39
+ finally {
40
+ await store.close();
41
+ }
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ };
47
+ /** What `models add --payload` takes: where the model is and how to run it; the files' sizes and hashes are looked up. */
48
+ export const CustomModelRequest = v.strictObject({
49
+ /** A Hugging Face repository, `owner/name`. */
50
+ repository: v.pipe(v.string(), v.regex(/^[\w.-]+\/[\w.-]+$/, "is not a Hugging Face repository, owner/name")),
51
+ /** A branch, tag or commit; pinned to the commit it names now. */
52
+ revision: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200))),
53
+ onnx: v.string(),
54
+ externalData: v.optional(v.string()),
55
+ dims: v.number(),
56
+ pooling: v.picklist(["mean", "sentence_embedding"]),
57
+ prefix: v.strictObject({ query: v.string(), passage: v.string() }),
58
+ maxTokens: v.optional(v.number()),
59
+ title: v.optional(v.string()),
60
+ languages: v.optional(v.string()),
61
+ licence: v.optional(v.string()),
62
+ chunksPerSecond: v.optional(v.number()),
63
+ });
64
+ const invalid = (what, issues) => {
65
+ const at = v.getDotPath(issues[0]);
66
+ return new CliError("validation_error", `${what}${at ? ` ${at}` : ""} ${issues[0].message}`);
67
+ };
68
+ const HUB = "https://huggingface.co";
69
+ /** Larger files are stored through LFS, whose listing gives their sha256; a small one is fetched and hashed here. */
70
+ const SMALL_FILE_MOST = 20_000_000;
71
+ const hubJson = async (get, url) => {
72
+ const response = await get(url);
73
+ if (!response.ok) {
74
+ await response.body?.cancel();
75
+ throw new CliError(response.status === 404 || response.status === 401 ? "not_found" : "network_error", `Hugging Face answered HTTP ${response.status} for ${url}`);
76
+ }
77
+ return response.json();
78
+ };
79
+ const Revision = v.object({ sha: v.pipe(v.string(), v.regex(/^[0-9a-f]{40}$/)), cardData: v.optional(v.unknown()) });
80
+ const Tree = v.array(v.object({
81
+ path: v.string(),
82
+ type: v.optional(v.string()),
83
+ size: v.optional(v.number()),
84
+ lfs: v.optional(v.object({ oid: v.string(), size: v.optional(v.number()) })),
85
+ }));
86
+ /**
87
+ * A model from a Hugging Face repository, pinned to one commit with each file's size and sha256, as the built-in
88
+ * ones are, and kept in the shared settings file beside the choice. It is checked again on `models download`,
89
+ * which also embeds a word to see the vector has `dims` numbers. Adding an id again replaces its definition.
90
+ */
91
+ export const addCustomTextModel = async (id, payload, { env, fetch: get = fetch }) => {
92
+ const given = v.safeParse(CustomModelRequest, payload);
93
+ if (!given.success)
94
+ throw invalid("--payload", given.issues);
95
+ const request = given.output;
96
+ const revision = v.safeParse(Revision, await hubJson(get, `${HUB}/api/models/${request.repository}/revision/${encodeURIComponent(request.revision ?? "main")}`));
97
+ if (!revision.success)
98
+ throw new CliError("invalid_response", "Hugging Face gave no commit for that revision");
99
+ const commit = revision.output.sha;
100
+ const names = [
101
+ ...new Set([request.onnx, request.externalData, "tokenizer.json", "tokenizer_config.json"].filter(Boolean)),
102
+ ];
103
+ const folders = [...new Set(names.map((name) => name.split("/").slice(0, -1).join("/")))];
104
+ const listed = new Map();
105
+ for (const folder of folders) {
106
+ const tree = v.safeParse(Tree, await hubJson(get, `${HUB}/api/models/${request.repository}/tree/${commit}${folder ? `/${folder}` : ""}`));
107
+ if (!tree.success)
108
+ throw new CliError("invalid_response", "Hugging Face gave an unreadable file list");
109
+ for (const entry of tree.output)
110
+ listed.set(entry.path, entry);
111
+ }
112
+ const url = (name) => `${HUB}/${request.repository}/resolve/${commit}/${name}`;
113
+ const files = [];
114
+ for (const name of names) {
115
+ const entry = listed.get(name);
116
+ if (!entry)
117
+ throw new CliError("not_found", `${request.repository} has no ${name} at ${commit.slice(0, 12)}`);
118
+ if (entry.lfs) {
119
+ files.push({ name, url: url(name), sha256: entry.lfs.oid, bytes: entry.lfs.size ?? entry.size ?? 0 });
120
+ continue;
121
+ }
122
+ if ((entry.size ?? 0) > SMALL_FILE_MOST)
123
+ throw new CliError("invalid_response", `${name} is large and not in LFS, so it has no sha256 to pin`);
124
+ const response = await get(url(name));
125
+ if (!response.ok)
126
+ throw new CliError("network_error", `${name} could not be downloaded: HTTP ${response.status}`);
127
+ const bytes = Buffer.from(await response.arrayBuffer());
128
+ files.push({ name, url: url(name), sha256: createHash("sha256").update(bytes).digest("hex"), bytes: bytes.length });
129
+ }
130
+ const card = revision.output.cardData;
131
+ const checked = v.safeParse(CustomTextModelShape, {
132
+ id,
133
+ title: request.title ?? `${request.repository} (${request.onnx})`,
134
+ languages: request.languages ?? "as the model card says",
135
+ licence: request.licence ??
136
+ (typeof card?.license === "string" ? card.license : `unknown — read ${HUB}/${request.repository}`),
137
+ dims: request.dims,
138
+ maxTokens: request.maxTokens ?? 512,
139
+ ...(request.chunksPerSecond === undefined ? {} : { chunksPerSecond: request.chunksPerSecond }),
140
+ pooling: request.pooling,
141
+ prefix: request.prefix,
142
+ onnx: request.onnx,
143
+ ...(request.externalData ? { externalData: request.externalData } : {}),
144
+ files,
145
+ });
146
+ if (!checked.success)
147
+ throw invalid("the model", checked.issues);
148
+ const section = readTextModelsSection(env);
149
+ writeTextModelsSection({ ...section, custom: [...(section.custom ?? []).filter((one) => one.id !== id), checked.output] }, env);
150
+ return { ...checked.output, custom: true };
151
+ };
@@ -36,6 +36,7 @@ export { MENTION_QUERY, MENTION_STATUSES, type MentionDecision, type MentionStat
36
36
  export { drainNoteIndex, noteIndexState, resetNoteIndex } from "./sqlite/note-index.js";
37
37
  export type { Link as ThingLink } from "./sqlite/notes.js";
38
38
  export { openSqlite } from "./sqlite/open.js";
39
+ export { DEFAULT_OWNER_LANGUAGES, ownerLanguages, parseOwnerLanguages, savedOwnerLanguages, saveOwnerLanguages, } from "./sqlite/owner-languages.js";
39
40
  export type { PersonPreparationRead, PreparationFact, PreparationNote, PreparationTask, } from "./sqlite/person-preparation.js";
40
41
  export { savedPhoneCountries, saveStorePhoneCountries } from "./sqlite/phone-countries.js";
41
42
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
@@ -15,6 +15,7 @@ export { OTHER_SOURCES } from "./sqlite/mention-sources.js";
15
15
  export { MENTION_QUERY, MENTION_STATUSES, } from "./sqlite/mentions.js";
16
16
  export { drainNoteIndex, noteIndexState, resetNoteIndex } from "./sqlite/note-index.js";
17
17
  export { openSqlite } from "./sqlite/open.js";
18
+ export { DEFAULT_OWNER_LANGUAGES, ownerLanguages, parseOwnerLanguages, savedOwnerLanguages, saveOwnerLanguages, } from "./sqlite/owner-languages.js";
18
19
  export { savedPhoneCountries, saveStorePhoneCountries } from "./sqlite/phone-countries.js";
19
20
  export { queryFilter } from "./sqlite/query-filter.js";
20
21
  export { AGENDA_COLUMNS } from "./sqlite/reads.js";
@@ -68,6 +68,7 @@ export type { NoteIndexState } from "./sqlite/note-index.js";
68
68
  export { type NearestNote, NOTE_FIELDS, type NoteChunkToEmbed, type NoteHit, type NoteQuery, type NoteSearch, } from "./sqlite/note-search.js";
69
69
  export type { FileNoteInput, Link, LinkInput, LinkListFilter, Note, NoteFolder, NotesStore, NoteTag, } from "./sqlite/notes.js";
70
70
  export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
71
+ export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
71
72
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
72
73
  export type { Product, ProductFilter, ProductInput, ProductsStore, ProductUpdate } from "./sqlite/products.js";
73
74
  export { assertGenericAction, PROPOSAL_STATUSES, type ProposalInput, type ProposedAction, type ProposedActionsStore, proposerOfAction, } from "./sqlite/proposed-actions.js";
@@ -32,6 +32,7 @@ export { EVENT_FIELDS, } from "./sqlite/event-search.js";
32
32
  export { IMPORTED_DOCUMENT_QUERY } from "./sqlite/imported-documents.js";
33
33
  export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js";
34
34
  export { NOTE_FIELDS, } from "./sqlite/note-search.js";
35
+ export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
35
36
  export { assertGenericAction, PROPOSAL_STATUSES, proposerOfAction, } from "./sqlite/proposed-actions.js";
36
37
  export { waitingPointer, } from "./sqlite/records.js";
37
38
  export { fillSearchIndex, resetSearchIndex, searchIndexState, } from "./sqlite/search-index.js";
@@ -0,0 +1,13 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ /** Unset, the owner reads Russian, the same default as `AppIdentity.locale`, not the system's language. */
3
+ export declare const DEFAULT_OWNER_LANGUAGES: readonly string[];
4
+ /** `ru, EN,ru` → `["ru", "en"]`: ISO 639-1 codes in the owner's order, each once. */
5
+ export declare const parseOwnerLanguages: (value: string) => string[];
6
+ /** What `config set owner_languages` saved; `undefined` while the default applies, or when a newer tool saved one. */
7
+ export declare const savedOwnerLanguages: (database: CacheDatabase) => string[] | undefined;
8
+ /**
9
+ * The languages the owner reads, primary first: everything written for him is in the first; a title quoted in a
10
+ * later one stays untranslated.
11
+ */
12
+ export declare const ownerLanguages: (database: CacheDatabase) => readonly string[];
13
+ export declare const saveOwnerLanguages: (database: CacheDatabase, languages: readonly string[] | undefined, now: number) => void;