@wirecat/cli-core 0.608.0 → 0.610.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 (108) hide show
  1. package/CHANGELOG.md +124 -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 +23 -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/search-left-out.d.ts +1 -0
  26. package/dist/cli/search-left-out.js +2 -0
  27. package/dist/cli/store-settings.js +39 -3
  28. package/dist/crm/cli/csv.d.ts +18 -5
  29. package/dist/crm/cli/csv.js +30 -19
  30. package/dist/crm/cli/index.d.ts +1 -0
  31. package/dist/crm/cli/index.js +1 -0
  32. package/dist/domain/business.d.ts +3 -0
  33. package/dist/domain/business.js +2 -0
  34. package/dist/embeddings/models.d.ts +185 -5
  35. package/dist/embeddings/models.js +119 -5
  36. package/dist/entities/hit.d.ts +13 -2
  37. package/dist/entities/hit.js +10 -2
  38. package/dist/entities/index.d.ts +31 -1
  39. package/dist/entities/index.js +2 -1
  40. package/dist/entities/model.d.ts +42 -1
  41. package/dist/entities/model.js +20 -1
  42. package/dist/errors/reasons.js +4 -0
  43. package/dist/render/liquid.d.ts +14 -0
  44. package/dist/render/liquid.js +30 -0
  45. package/dist/replies/template.js +3 -22
  46. package/dist/search/account-list.d.ts +3 -2
  47. package/dist/search/account-list.js +5 -4
  48. package/dist/search/lucene/plain.js +4 -1
  49. package/dist/search/question-plan.js +2 -1
  50. package/dist/sends/permissions.js +4 -0
  51. package/dist/services/embeddings-maintenance.d.ts +1 -1
  52. package/dist/services/embeddings-maintenance.js +6 -6
  53. package/dist/services/index.d.ts +2 -0
  54. package/dist/services/index.js +2 -0
  55. package/dist/services/link-scorers/chat-senders.d.ts +2 -1
  56. package/dist/services/link-scorers/chat-senders.js +13 -4
  57. package/dist/services/link-scorers/types.d.ts +1 -1
  58. package/dist/services/meeting-model.d.ts +1 -1
  59. package/dist/services/meeting-model.js +4 -4
  60. package/dist/services/messages-meaning.js +25 -4
  61. package/dist/services/metadata.d.ts +1 -1
  62. package/dist/services/model-downloads.js +1 -1
  63. package/dist/services/notes-search.d.ts +1 -1
  64. package/dist/services/notes-search.js +2 -2
  65. package/dist/services/proposals/kinds/relationship.js +1 -0
  66. package/dist/services/proposals/registry.js +3 -1
  67. package/dist/services/proposals/types.d.ts +2 -0
  68. package/dist/services/search-all-business.d.ts +18 -0
  69. package/dist/services/search-all-business.js +38 -0
  70. package/dist/services/search-all-meetings.d.ts +1 -1
  71. package/dist/services/search-all-meetings.js +7 -2
  72. package/dist/services/search-all.d.ts +12 -6
  73. package/dist/services/search-all.js +48 -12
  74. package/dist/services/text-model-choice.d.ts +50 -0
  75. package/dist/services/text-model-choice.js +151 -0
  76. package/dist/store/exports.d.ts +3 -0
  77. package/dist/store/exports.js +3 -0
  78. package/dist/store/index.d.ts +5 -1
  79. package/dist/store/index.js +3 -0
  80. package/dist/store/sqlite/business-search.d.ts +44 -0
  81. package/dist/store/sqlite/business-search.js +141 -0
  82. package/dist/store/sqlite/finance.d.ts +12 -0
  83. package/dist/store/sqlite/finance.js +38 -2
  84. package/dist/store/sqlite/involvement-queue.d.ts +2 -7
  85. package/dist/store/sqlite/involvement-queue.js +11 -14
  86. package/dist/store/sqlite/money-lines.d.ts +12 -1
  87. package/dist/store/sqlite/money-lines.js +50 -4
  88. package/dist/store/sqlite/orders.js +5 -25
  89. package/dist/store/sqlite/owner-languages.d.ts +13 -0
  90. package/dist/store/sqlite/owner-languages.js +49 -0
  91. package/dist/store/sqlite/proposed-actions.d.ts +2 -0
  92. package/dist/store/sqlite/proposed-actions.js +4 -3
  93. package/dist/store/sqlite/records.d.ts +21 -0
  94. package/dist/store/sqlite/records.js +74 -13
  95. package/dist/store/sqlite/ref-summaries.d.ts +3 -1
  96. package/dist/store/sqlite/ref-summaries.js +4 -1
  97. package/dist/store/sqlite/reported-relations.d.ts +1 -0
  98. package/dist/store/sqlite/reported-relations.js +5 -1
  99. package/dist/store/sqlite/vectors.d.ts +2 -0
  100. package/dist/store/sqlite/vectors.js +5 -0
  101. package/dist/store/store.d.ts +2 -0
  102. package/dist/store/store.js +4 -4
  103. package/dist/store/vectors.d.ts +2 -0
  104. package/dist/store/vectors.js +1 -0
  105. package/dist/terminal/prompt.d.ts +4 -0
  106. package/dist/terminal/prompt.js +21 -2
  107. package/package.json +2 -2
  108. package/parity.json +13 -0
@@ -3,16 +3,16 @@ import { type HitFile } from "../domain/attachments.js";
3
3
  import type { DealKind } from "../domain/deals.js";
4
4
  import { type MailFields } from "../domain/models.js";
5
5
  import type { MessengerTraits } from "../ports/traits.js";
6
- import type { AccountKey, MessageStore } from "../store/store.js";
6
+ import type { AccountKey, BusinessKind, BusinessSource, MessageStore } from "../store/store.js";
7
7
  import type { SearchFound, SearchQuery } from "./messages.js";
8
8
  import { type MeaningLane, type MeaningSkipped } from "./messages-discovery.js";
9
9
  import type { SearchCoverage } from "./messages-search.js";
10
10
  import type { Backend, ServerOptions, ServerSearched } from "./server-search.js";
11
- export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm"];
11
+ export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm", "business"];
12
12
  export type SearchedResource = (typeof RESOURCES_SEARCHED)[number];
13
13
  export interface SearchAllItem {
14
- kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead";
15
- /** `msg:…` for a message or a mail, `note:…` for a note, `event:…` for a calendar event, `deal:…`, `lead:…`. */
14
+ kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead" | BusinessKind;
15
+ /** `msg:…` for a message or a mail, `note:…`, `event:…`, `deal:…`, `lead:…`, or a business ref: `invoice:…`. */
16
16
  ref: string;
17
17
  provider: string;
18
18
  /** The account it was found in; a note's folder id, or `internal` for a note written in memo. */
@@ -36,6 +36,10 @@ export interface SearchAllItem {
36
36
  attachments?: HitFile[];
37
37
  /** Which search found it: words, meaning or both. */
38
38
  foundBy: ("title" | "words" | "meaning")[];
39
+ /** A business hit's: whether the owner confirmed it, or it waits for him. */
40
+ review?: "proposed" | "confirmed";
41
+ /** A business hit's source record, when an import made it. */
42
+ sourceRecord?: BusinessSource;
39
43
  }
40
44
  /** One account a search read, by the kind it was read for: the shape memo's `search all` answers too. */
41
45
  export interface SearchedAccount {
@@ -95,6 +99,8 @@ export interface SearchAllFound {
95
99
  server?: ServerSearched;
96
100
  /** What the store held of the chats the messages were searched in; absent when messages were not searched. */
97
101
  coverage?: SearchCoverage;
102
+ /** When nothing was found by all the words: the words that alone find nothing in `searched` either. */
103
+ unmatched?: string[];
98
104
  }
99
105
  export interface SearchAllRequest {
100
106
  text: string;
@@ -125,14 +131,14 @@ export type SearchAllMessenger = Partial<Pick<MessengerTraits, "savedChatId" | "
125
131
  * What a deal or a lead is found by: words or phrases of its title, all of them, or any with OR. Anything else is
126
132
  * refused, so `search all` skips deals with the reason instead of matching a field they do not have.
127
133
  */
128
- export declare const titleWords: (text: string) => {
134
+ export declare const titleWords: (text: string, refused?: string) => {
129
135
  words: string[];
130
136
  anyWord: boolean;
131
137
  };
132
138
  /** The accounts of every CRM the store holds copies of. */
133
139
  export declare const crmAccounts: (store: MessageStore) => Promise<AccountKey[]>;
134
140
  /**
135
- * `search all`: messages, mail, notes, calendar events and CRM deals and leads from the local store — messages also from the messenger's
141
+ * `search all`: messages, mail, notes, calendar events, CRM deals and leads, and business data from the local store — messages also from the messenger's
136
142
  * server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
137
143
  * resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
138
144
  */
@@ -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";
@@ -14,7 +14,8 @@ import { excerpt } from "./excerpt.js";
14
14
  import { MAX_SEARCH_OFFSET, searchStore } from "./messages-archive-search.js";
15
15
  import { nearEligible } from "./messages-discovery.js";
16
16
  import { notesScopeOf, RRF_K, searchNotes } from "./notes-search.js";
17
- export const RESOURCES_SEARCHED = ["messages", "mail", "notes", "events", "crm"];
17
+ import { BUSINESS_WORDS_ONLY, searchBusiness } from "./search-all-business.js";
18
+ export const RESOURCES_SEARCHED = ["messages", "mail", "notes", "events", "crm", "business"];
18
19
  const refusal = (error, text) => {
19
20
  const { reason, span } = (error.details ?? {});
20
21
  const why = typeof reason === "string" ? reason : undefined;
@@ -43,7 +44,7 @@ const filtersBeside = (text) => {
43
44
  * What a deal or a lead is found by: words or phrases of its title, all of them, or any with OR. Anything else is
44
45
  * refused, so `search all` skips deals with the reason instead of matching a field they do not have.
45
46
  */
46
- export const titleWords = (text) => {
47
+ export const titleWords = (text, refused = "deals and leads are found by the words of their title only") => {
47
48
  const { root } = parseLucene(text, SEARCH_QUERY);
48
49
  const clauses = root.kind === "boolean" ? root.clauses : [{ node: root, occur: "must" }];
49
50
  const words = clauses.map(({ node, occur }) => occur !== "must_not" &&
@@ -53,14 +54,27 @@ export const titleWords = (text) => {
53
54
  ? // A title holds "invoice", not the question mark of "invoice?".
54
55
  node.value.replace(/\?+$/u, "") || node.value
55
56
  : (() => {
56
- throw new CliError("validation_error", "deals and leads are found by the words of their title only");
57
+ throw new CliError("validation_error", refused);
57
58
  })());
58
59
  return { words, anyWord: clauses.length > 1 && clauses.every(({ occur }) => occur === "should") };
59
60
  };
61
+ /** The single words of an all-words query, when it has two to eight of them; none for OR, fields or phrases. */
62
+ const strictWords = (text) => {
63
+ try {
64
+ const { words, anyWord } = titleWords(text);
65
+ const unique = [...new Set(words)];
66
+ return anyWord || unique.length < 2 || unique.length > 8 || unique.some((word) => /\s/u.test(word)) ? [] : unique;
67
+ }
68
+ catch (error) {
69
+ if (error instanceof CliError)
70
+ return [];
71
+ throw error;
72
+ }
73
+ };
60
74
  /** The accounts of every CRM the store holds copies of. */
61
75
  export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
62
76
  /**
63
- * `search all`: messages, mail, notes, calendar events and CRM deals and leads from the local store — messages also from the messenger's
77
+ * `search all`: messages, mail, notes, calendar events, CRM deals and leads, and business data from the local store — messages also from the messenger's
64
78
  * server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
65
79
  * resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
66
80
  */
@@ -153,7 +167,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
153
167
  ? {
154
168
  skipped: {
155
169
  reason: "the query uses NOT, or a filter under OR or in a group, which meaning cannot follow",
156
- model: DEFAULT_TEXT_MODEL,
170
+ model: chosenTextModel(request.env).id,
157
171
  },
158
172
  }
159
173
  : await meaning(request.text, read, embedders);
@@ -287,6 +301,19 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
287
301
  for (const { provider, account } of read)
288
302
  accounts.push({ resource, provider, account });
289
303
  }
304
+ else if (resource === "business") {
305
+ const { words, anyWord } = titleWords(request.text, BUSINESS_WORDS_ONLY);
306
+ const found = await searchBusiness(store, {
307
+ words,
308
+ anyWord: anyWord || discover,
309
+ window,
310
+ accounts: request.scope?.business,
311
+ });
312
+ hasMore ||= found.hasMore;
313
+ lists.push(found.items);
314
+ for (const { provider, account } of found.read)
315
+ accounts.push({ resource, provider, account });
316
+ }
290
317
  else
291
318
  lists.push(await messagesOf(resource));
292
319
  searched.push(resource);
@@ -303,6 +330,14 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
303
330
  }
304
331
  const ordered = oneList(lists, cosines);
305
332
  const more = hasMore || ordered.length > window;
333
+ const { backend: _backend, server: _server, ...local } = asked;
334
+ const unmatched = [];
335
+ if (!ordered.length && !offset && !discover)
336
+ for (const word of strictWords(request.text)) {
337
+ const alone = await searchAll(store, account, { ...local, text: word, limit: 1, only: searched });
338
+ if (!alone.items.length)
339
+ unmatched.push(word);
340
+ }
306
341
  return {
307
342
  query: asked.text,
308
343
  items: ordered.slice(offset, window),
@@ -317,14 +352,14 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
317
352
  ...(by.mail === undefined ? {} : { mail: by.mail }),
318
353
  ...(server === undefined ? {} : { server }),
319
354
  ...(coverage === undefined ? {} : { coverage }),
355
+ ...(unmatched.length ? { unmatched } : {}),
320
356
  };
321
357
  };
322
358
  /**
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.
359
+ * Every source's hits as one list: each source's best hit first, then every other hit by cosine, then by its rank in
360
+ * its source. Taking turns by rank (MEMO-37) gave each of two sources half of a ten-hit page however weak its hits;
361
+ * one model scores every source, so cosine compares across them (IDEA-249). A hit meaning did not find comes after
362
+ * those it did.
328
363
  */
329
364
  const oneList = (lists, cosines) => {
330
365
  const place = new Map();
@@ -335,7 +370,8 @@ const oneList = (lists, cosines) => {
335
370
  place.set(item.ref, { item, rank });
336
371
  });
337
372
  const cosine = (ref) => cosines.get(ref) ?? Number.NEGATIVE_INFINITY;
373
+ const head = (rank) => Math.min(rank, 1);
338
374
  return [...place.values()]
339
- .sort((a, b) => a.rank - b.rank || cosine(b.item.ref) - cosine(a.item.ref))
375
+ .sort((a, b) => head(a.rank) - head(b.rank) || cosine(b.item.ref) - cosine(a.item.ref) || a.rank - b.rank)
340
376
  .map(({ item }) => item);
341
377
  };
@@ -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
+ };
@@ -1,3 +1,4 @@
1
+ export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
1
2
  export type { CounterField, CounterObservations, CounterState } from "../domain/counters.js";
2
3
  export type { RetentionOptions } from "../domain/retention.js";
3
4
  export type { AccountAccounts, AccountsStore } from "./accounts.js";
@@ -17,6 +18,7 @@ export { accountGroupsOf } from "./sqlite/account-groups.js";
17
18
  export type { AdminStoreRequest, AdminStoreResult } from "./sqlite/admin-statistics.js";
18
19
  export { type AttachmentTextEntry, type AttachmentView, attachmentColumns, type FileAttachment, resetAttachmentWords, type TextOrigin, } from "./sqlite/attachment-texts.js";
19
20
  export { pendingNormalization } from "./sqlite/backfill.js";
21
+ export { BUSINESS_FIND_MAX, type BusinessHit, type BusinessSearch, type BusinessSearchStore, type BusinessSource, } from "./sqlite/business-search.js";
20
22
  export type { ChatRekey, ChatRekeys } from "./sqlite/chat-rekey.js";
21
23
  export { CHAT_COLUMNS, TRACKED_CHAT_COLUMNS, titlePart } from "./sqlite/chats.js";
22
24
  export { storeClients } from "./sqlite/clients.js";
@@ -36,6 +38,7 @@ export { MENTION_QUERY, MENTION_STATUSES, type MentionDecision, type MentionStat
36
38
  export { drainNoteIndex, noteIndexState, resetNoteIndex } from "./sqlite/note-index.js";
37
39
  export type { Link as ThingLink } from "./sqlite/notes.js";
38
40
  export { openSqlite } from "./sqlite/open.js";
41
+ export { DEFAULT_OWNER_LANGUAGES, ownerLanguages, parseOwnerLanguages, savedOwnerLanguages, saveOwnerLanguages, } from "./sqlite/owner-languages.js";
39
42
  export type { PersonPreparationRead, PreparationFact, PreparationNote, PreparationTask, } from "./sqlite/person-preparation.js";
40
43
  export { savedPhoneCountries, saveStorePhoneCountries } from "./sqlite/phone-countries.js";
41
44
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
@@ -1,7 +1,9 @@
1
+ export { BUSINESS_KINDS } from "../domain/business.js";
1
2
  export { registerProvider } from "./providers.js";
2
3
  export { accountGroupsOf } from "./sqlite/account-groups.js";
3
4
  export { attachmentColumns, resetAttachmentWords, } from "./sqlite/attachment-texts.js";
4
5
  export { pendingNormalization } from "./sqlite/backfill.js";
6
+ export { BUSINESS_FIND_MAX, } from "./sqlite/business-search.js";
5
7
  export { CHAT_COLUMNS, TRACKED_CHAT_COLUMNS, titlePart } from "./sqlite/chats.js";
6
8
  export { storeClients } from "./sqlite/clients.js";
7
9
  export { CHAT_LIST_KEY, fetchedKey, historyStartKey, } from "./sqlite/completeness.js";
@@ -15,6 +17,7 @@ export { OTHER_SOURCES } from "./sqlite/mention-sources.js";
15
17
  export { MENTION_QUERY, MENTION_STATUSES, } from "./sqlite/mentions.js";
16
18
  export { drainNoteIndex, noteIndexState, resetNoteIndex } from "./sqlite/note-index.js";
17
19
  export { openSqlite } from "./sqlite/open.js";
20
+ export { DEFAULT_OWNER_LANGUAGES, ownerLanguages, parseOwnerLanguages, savedOwnerLanguages, saveOwnerLanguages, } from "./sqlite/owner-languages.js";
18
21
  export { savedPhoneCountries, saveStorePhoneCountries } from "./sqlite/phone-countries.js";
19
22
  export { queryFilter } from "./sqlite/query-filter.js";
20
23
  export { AGENDA_COLUMNS } from "./sqlite/reads.js";
@@ -1,4 +1,5 @@
1
1
  export type { ContextEvidenceItem, ContextEvidencePage, ContextEvidenceReader, ContextEvidenceRequest, ContextEvidenceSender, ContextSource, } from "../context/evidence.js";
2
+ export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
2
3
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
3
4
  export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js";
4
5
  export type { TagConsolidationApplyOptions, TagConsolidationOptions, TagConsolidationPreview, TagConsolidationReceipt, TagConsolidationStore, } from "../domain/tag-consolidation.js";
@@ -38,6 +39,8 @@ export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
38
39
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
39
40
  export type { BotUpdate, BotUpdateStore } from "./sqlite/bot-updates.js";
40
41
  export type { Contract, ContractFields, ContractFilter, ContractInput, ContractsStore, ContractUpdate, } from "./sqlite/business-contracts.js";
42
+ export type { BusinessHit, BusinessSearch, BusinessSearchStore, BusinessSource } from "./sqlite/business-search.js";
43
+ export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
41
44
  export type { CatalogActor, CatalogEntry, CatalogInput, CatalogQuery, CatalogStore } from "./sqlite/catalog.js";
42
45
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
43
46
  export type { ChatMetadata } from "./sqlite/chats.js";
@@ -68,10 +71,11 @@ export type { NoteIndexState } from "./sqlite/note-index.js";
68
71
  export { type NearestNote, NOTE_FIELDS, type NoteChunkToEmbed, type NoteHit, type NoteQuery, type NoteSearch, } from "./sqlite/note-search.js";
69
72
  export type { FileNoteInput, Link, LinkInput, LinkListFilter, Note, NoteFolder, NotesStore, NoteTag, } from "./sqlite/notes.js";
70
73
  export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
74
+ export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
71
75
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
72
76
  export type { Product, ProductFilter, ProductInput, ProductsStore, ProductUpdate } from "./sqlite/products.js";
73
77
  export { assertGenericAction, PROPOSAL_STATUSES, type ProposalInput, type ProposedAction, type ProposedActionsStore, proposerOfAction, } from "./sqlite/proposed-actions.js";
74
- export { type FlaggedRecord, type MappedRecord, type MatchRun, type RecordKey, type RecordStore, type RecordsRun, type RunItem, type RunOptions, type SourceRecord, type SourceRecordRelation, type Unmatched, waitingPointer, } from "./sqlite/records.js";
78
+ export { type FlaggedRecord, type IncomingRelation, type MappedRecord, type MatchRun, type RecordKey, type RecordStore, type RecordsRun, type RunItem, type RunOptions, type SourceRecord, type SourceRecordRelation, type Unmatched, waitingPointer, } from "./sqlite/records.js";
75
79
  export type { RelationFilter, RelationList, RelationListItem } from "./sqlite/relation-list.js";
76
80
  export type { LinkDecision, RelationUpdate } from "./sqlite/relation-proposals.js";
77
81
  export type { RelationReads } from "./sqlite/relation-reads.js";
@@ -1,3 +1,4 @@
1
+ export { BUSINESS_KINDS } from "../domain/business.js";
1
2
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
2
3
  export { createTagRedirectIndex } from "../domain/tag-redirects.js";
3
4
  export { note } from "../entities/note.js";
@@ -25,6 +26,7 @@ export { SOURCE_REVIEW_CAUSES, SOURCE_REVIEW_KIND, } from "./source-review.js";
25
26
  export { ADDED_KINDS, addedSourceKeyOf, } from "./sqlite/added-sources.js";
26
27
  export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
27
28
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
29
+ export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
28
30
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
29
31
  export { crmIdentityId } from "./sqlite/crm.js";
30
32
  export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
@@ -32,6 +34,7 @@ export { EVENT_FIELDS, } from "./sqlite/event-search.js";
32
34
  export { IMPORTED_DOCUMENT_QUERY } from "./sqlite/imported-documents.js";
33
35
  export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js";
34
36
  export { NOTE_FIELDS, } from "./sqlite/note-search.js";
37
+ export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
35
38
  export { assertGenericAction, PROPOSAL_STATUSES, proposerOfAction, } from "./sqlite/proposed-actions.js";
36
39
  export { waitingPointer, } from "./sqlite/records.js";
37
40
  export { fillSearchIndex, resetSearchIndex, searchIndexState, } from "./sqlite/search-index.js";
@@ -0,0 +1,44 @@
1
+ import { type BusinessKind } from "../../domain/business.js";
2
+ import type { AccountKey } from "../types.js";
3
+ import type { StoreContext } from "./open.js";
4
+ /** The most rows one `find` answers: a `search all` page read as deep as its offset allows, and one more. */
5
+ export declare const BUSINESS_FIND_MAX = 2001;
6
+ export interface BusinessSearch {
7
+ /** Words of a number or a name, each matched at the start of a word in any letter case; a word may be a phrase. */
8
+ words: string[];
9
+ /** A row holding any of the words matches, those holding more first; otherwise every word is needed. */
10
+ anyWord?: boolean;
11
+ /** Only what imports of these accounts made; absent, every import's and the owner's own. */
12
+ accounts?: AccountKey[];
13
+ /** 1–`BUSINESS_FIND_MAX`, 100 by default. */
14
+ limit?: number;
15
+ }
16
+ /** The source record an import made the entity from. */
17
+ export interface BusinessSource {
18
+ provider: string;
19
+ account: string;
20
+ externalId: string;
21
+ }
22
+ export interface BusinessHit {
23
+ kind: BusinessKind;
24
+ ref: string;
25
+ /** A product's or a wallet's has no review and reads `confirmed`; rejected rows are never found. */
26
+ review: "proposed" | "confirmed";
27
+ /** The import provider of a row an import made; absent for the owner's or an agent's. */
28
+ imported?: string;
29
+ /** The one record that names the row's account: the oldest live one, else the oldest deleted one. */
30
+ source?: BusinessSource;
31
+ /** The numbers and names it was found by, one line. */
32
+ text: string;
33
+ /** Epoch ms. */
34
+ updatedAt: number;
35
+ }
36
+ /** Invoices, payments, orders, contracts, subscriptions, products and wallets, found by their numbers and names. */
37
+ export interface BusinessSearchStore {
38
+ find(search: BusinessSearch): Promise<BusinessHit[]>;
39
+ /** Every account with a live record of a row the lane reads. */
40
+ accounts(): Promise<AccountKey[]>;
41
+ }
42
+ /** "get" finds "Get well" and "INV-get", never "Widget": a word is matched where a word starts. */
43
+ export declare const startsAWord: (folded: string, word: string) => boolean;
44
+ export declare const businessSearchOver: ({ database }: StoreContext) => BusinessSearchStore;