@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
@@ -0,0 +1,14 @@
1
+ import { Liquid } from "liquidjs";
2
+ export interface LiquidLimits {
3
+ /** Characters of template source. */
4
+ parse: number;
5
+ /** Bytes a render may allocate, as LiquidJS counts them. */
6
+ memory: number;
7
+ milliseconds: number;
8
+ }
9
+ /**
10
+ * The one Liquid engine for owner-written templates (reply rules, report templates): unknown variables and filters
11
+ * are errors, only own properties are read, and `include`, `render` and `layout` are refused, so a template cannot
12
+ * read a file.
13
+ */
14
+ export declare const safeLiquid: (limits: LiquidLimits) => Liquid;
@@ -0,0 +1,30 @@
1
+ import { Liquid, Tag } from "liquidjs";
2
+ /**
3
+ * The one Liquid engine for owner-written templates (reply rules, report templates): unknown variables and filters
4
+ * are errors, only own properties are read, and `include`, `render` and `layout` are refused, so a template cannot
5
+ * read a file.
6
+ */
7
+ export const safeLiquid = (limits) => {
8
+ const engine = new Liquid({
9
+ ownPropertyOnly: true,
10
+ strictVariables: true,
11
+ strictFilters: true,
12
+ lenientIf: false,
13
+ parseLimit: limits.parse,
14
+ renderLimit: limits.milliseconds,
15
+ memoryLimit: limits.memory,
16
+ preserveTimezones: true,
17
+ });
18
+ for (const name of ["include", "render", "layout"]) {
19
+ engine.registerTag(name, class extends Tag {
20
+ constructor(token, tokens, liquid) {
21
+ super(token, tokens, liquid);
22
+ throw new Error("templates cannot read files");
23
+ }
24
+ render() {
25
+ return "";
26
+ }
27
+ });
28
+ }
29
+ return engine;
30
+ };
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { Context, Liquid, Tag, } from "liquidjs";
2
+ import { Context, Tag, } from "liquidjs";
3
+ import { safeLiquid } from "../render/liquid.js";
3
4
  export const TEMPLATE_LIMITS = {
4
5
  parse: 32_768,
5
6
  renders: 2_000,
@@ -56,27 +57,7 @@ export const renderReplyTemplate = async (reply, input) => {
56
57
  .formatToParts(input.now)
57
58
  .map(({ type, value }) => [type, value]));
58
59
  const localTime = `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}${parts.timeZoneName?.replace("GMT", "") || "+00:00"}`;
59
- const engine = new Liquid({
60
- ownPropertyOnly: true,
61
- strictVariables: true,
62
- strictFilters: true,
63
- lenientIf: false,
64
- parseLimit: limits.parse,
65
- renderLimit: limits.milliseconds,
66
- memoryLimit: limits.memory,
67
- preserveTimezones: true,
68
- });
69
- for (const name of ["include", "render", "layout"]) {
70
- engine.registerTag(name, class extends Tag {
71
- constructor(token, tokens, liquid) {
72
- super(token, tokens, liquid);
73
- throw new Error("reply templates cannot read files");
74
- }
75
- render() {
76
- return "";
77
- }
78
- });
79
- }
60
+ const engine = safeLiquid({ parse: limits.parse, memory: limits.memory, milliseconds: limits.milliseconds });
80
61
  engine.registerTag("ai", class extends Tag {
81
62
  body = [];
82
63
  fallback = null;
@@ -56,9 +56,10 @@ export interface SkippedSource {
56
56
  }
57
57
  /**
58
58
  * The accounts of `kinds` the entries name, and each entry that names none of them with the reason. A search
59
- * fails only when nothing fits: `what` names the search in that error.
59
+ * fails only when nothing fits: `what` names the search in that error. `alsoFits` takes an account no kind names,
60
+ * such as one a records import wrote business data into.
60
61
  */
61
- export declare const fitting: (entries: readonly ListedEntry[], kinds: readonly Kind[], what: string, reasonOf?: (kind: Kind) => string) => {
62
+ export declare const fitting: (entries: readonly ListedEntry[], kinds: readonly Kind[], what: string, reasonOf?: (kind: Kind) => string, alsoFits?: (account: AccountKey) => boolean) => {
62
63
  accounts: AccountKey[];
63
64
  skipped: SkippedSource[];
64
65
  };
@@ -218,18 +218,19 @@ const READS = {
218
218
  };
219
219
  /**
220
220
  * The accounts of `kinds` the entries name, and each entry that names none of them with the reason. A search
221
- * fails only when nothing fits: `what` names the search in that error.
221
+ * fails only when nothing fits: `what` names the search in that error. `alsoFits` takes an account no kind names,
222
+ * such as one a records import wrote business data into.
222
223
  */
223
- export const fitting = (entries, kinds, what, reasonOf = (kind) => READS[kind]) => {
224
+ export const fitting = (entries, kinds, what, reasonOf = (kind) => READS[kind], alsoFits = () => false) => {
224
225
  const chosen = new Map();
225
226
  const skipped = [];
226
227
  for (const { entry, accounts } of entries) {
227
- const fits = accounts.filter((one) => kinds.some((kind) => listedHolds(one, kind)));
228
+ const fits = accounts.filter((one) => kinds.some((kind) => listedHolds(one, kind)) || alsoFits(one));
228
229
  for (const { provider, account } of fits)
229
230
  if (!chosen.has(keyOf({ provider, account })))
230
231
  chosen.set(keyOf({ provider, account }), { provider, account });
231
232
  const known = accounts.filter(({ kind }) => kind !== undefined);
232
- const unknown = accounts.filter(({ kind }) => kind === undefined);
233
+ const unknown = accounts.filter((one) => one.kind === undefined && !alsoFits(one));
233
234
  if (known.length)
234
235
  for (const { provider, account } of unknown)
235
236
  skipped.push({ source: `${provider}:${account}`, code: "not_found", reason: UNKNOWN_PROVIDER });
@@ -1,4 +1,4 @@
1
- import { isCliError } from "@wirecat/cli-base";
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
2
  import { parseLucene, walkQuery } from "@wirecat/cli-base/query";
3
3
  import { QUERY_FIELDS } from "./registry.js";
4
4
  import { MESSAGE_PARSING } from "./types.js";
@@ -92,6 +92,9 @@ const without = (text, leaves) => [...leaves]
92
92
  * search to report. `fields` are the names a list of its own (memories: `text`, `scope`) reads as fields.
93
93
  */
94
94
  export const plainQuery = (text, fields = SEARCH_FIELDS) => {
95
+ // `""`, a lone `?` or an emoji holds nothing the word index keeps, so it would find nothing and say nothing.
96
+ if (text.trim() && !/[\p{L}\p{N}*]/u.test(text))
97
+ throw new CliError("validation_error", `search needs a letter or a digit to look for; ${JSON.stringify(text)} has none`);
95
98
  let current = text;
96
99
  let whole = false;
97
100
  for (let tries = 0; tries <= 64; tries++) {
@@ -81,7 +81,8 @@ export function planQuestion(text, strict = false) {
81
81
  const bypass = strict ||
82
82
  !natural ||
83
83
  implicitTextTerms(cleaned).size === 0 ||
84
- textual.some((p) => p.operator !== "term" || p.field === "exact");
84
+ // A quoted single word is how `plainQuery` keeps `10:30` or `HH:MM` literal; it is no phrase the asker wrote.
85
+ textual.some((p) => !(p.operator === "term" || (p.operator === "phrase" && !/\s/u.test(p.value))) || p.field === "exact");
85
86
  if (bypass)
86
87
  return {
87
88
  changed: false,
@@ -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) => {
@@ -2,6 +2,7 @@ import type { LinkScorer } from "./types.js";
2
2
  /**
3
3
  * A person who wrote 5 or more messages in the window in one of the project's confirmed chats, or any in a dialog or a
4
4
  * group of 10 people or fewer, found by the sender's identity, never by the name a message shows. In a group of more
5
- * than 30 people writing there says less.
5
+ * than 30 people writing there says less. The reason names the chat and its size, and the evidence leads with the chat,
6
+ * so the owner can find and decide one group's senders together (`memo review list via:<chat>`).
6
7
  */
7
8
  export declare const chatSenders: LinkScorer;
@@ -6,14 +6,22 @@ const LARGE_GROUP = 30;
6
6
  const SMALL_CHAT = 10;
7
7
  const MIN_MESSAGES = 5;
8
8
  const READ_LIMIT = 2000;
9
+ const TITLE_WIDTH = 60;
10
+ const named = (title, chat) => {
11
+ const flat = (title ?? "").replace(/\s+/gu, " ").trim();
12
+ if (!flat)
13
+ return chat;
14
+ return `«${flat.length > TITLE_WIDTH ? `${flat.slice(0, TITLE_WIDTH - 1)}…` : flat}»`;
15
+ };
9
16
  /**
10
17
  * A person who wrote 5 or more messages in the window in one of the project's confirmed chats, or any in a dialog or a
11
18
  * group of 10 people or fewer, found by the sender's identity, never by the name a message shows. In a group of more
12
- * than 30 people writing there says less.
19
+ * than 30 people writing there says less. The reason names the chat and its size, and the evidence leads with the chat,
20
+ * so the owner can find and decide one group's senders together (`memo review list via:<chat>`).
13
21
  */
14
22
  export const chatSenders = {
15
23
  id: "chat-senders",
16
- version: 2,
24
+ version: 3,
17
25
  spreads: true,
18
26
  candidates: async ({ store, project, confirmed, sources, since, owner, signal }) => {
19
27
  if (!project)
@@ -37,6 +45,7 @@ export const chatSenders = {
37
45
  }
38
46
  const size = Math.max((await store.roster.members(key, reference.chat)).length, senders.size);
39
47
  const weight = size > LARGE_GROUP ? LARGE_GROUP_WEIGHT : WEIGHT;
48
+ const where = named(await store.chats.chatTitle(key, reference.chat), chat);
40
49
  for (const [id, { count, last }] of senders) {
41
50
  if (size > SMALL_CHAT && count < MIN_MESSAGES)
42
51
  continue;
@@ -48,8 +57,8 @@ export const chatSenders = {
48
57
  to: project.ref,
49
58
  kind: "member-of",
50
59
  weight,
51
- why: `${count} messages since ${since.slice(0, 10)} in a project chat (${chat})${size > LARGE_GROUP ? `, a group of ${size}` : ""}`,
52
- evidence: [formatReference({ ...reference, type: "message", message: last })],
60
+ why: `wrote ${count} message${count === 1 ? "" : "s"} in ${where} (${size} people) since ${since.slice(0, 10)}`,
61
+ evidence: [chat, formatReference({ ...reference, type: "message", message: last })],
53
62
  identity: contactRef(key.provider, id),
54
63
  });
55
64
  }
@@ -10,7 +10,7 @@ export interface LinkCandidate {
10
10
  kind: "member-of" | "related-to";
11
11
  /** 0..1. */
12
12
  weight: number;
13
- /** Ids and counts only, never message text. */
13
+ /** Ids, counts and at most a chat's title, never message text. */
14
14
  why: string;
15
15
  evidence: string[];
16
16
  /**
@@ -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");
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
+ error?: undefined;
17
18
  chatId: string;
18
19
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
19
20
  algorithm: string;
20
21
  fetchedAt: string | null;
21
22
  source: string;
22
- error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -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)}`, {
@@ -65,6 +65,7 @@ export const relationshipKind = (store) => {
65
65
  kinds: ["relationship"],
66
66
  ...(status === undefined ? {} : { status }),
67
67
  ...pushed(filter),
68
+ ...(filter.via === undefined ? {} : { evidence: filter.via }),
68
69
  });
69
70
  const links = (filter.status ?? "proposed") === "rejected" ? [] : await legacy();
70
71
  return kept([...stored.map(storedRow), ...links.map(linkRow)], filter);
@@ -60,7 +60,9 @@ export const emptyProposalRegistry = (store) => {
60
60
  throw new CliError("validation_error", "a proposal list takes a nonnegative offset");
61
61
  const asked = filter.kinds === undefined ? kinds : kinds.filter((kind) => filter.kinds?.includes(kind.kind));
62
62
  const wide = { ...filter, offset: 0, limit: filter.offset + filter.limit + 1 };
63
- const rows = (await Promise.all(asked.map(async (kind) => (await kind.list(wide)).map((row) => marked(kind, row))))).flat();
63
+ const rows = (await Promise.all(asked.map(async (kind) => (await kind.list(wide)).map((row) => marked(kind, row)))))
64
+ .flat()
65
+ .filter((row) => filter.via === undefined || row.evidence.includes(filter.via));
64
66
  rows.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id));
65
67
  const page = rows.slice(filter.offset, filter.offset + filter.limit + 1);
66
68
  return { items: page.slice(0, filter.limit), hasMore: page.length > filter.limit };
@@ -38,6 +38,8 @@ export interface ProposalFilter {
38
38
  bot: string;
39
39
  };
40
40
  status?: ProposalRow["status"] | "all";
41
+ /** A reference among the proposal's evidence, such as the chat a scan found a group's senders in. */
42
+ via?: string;
41
43
  limit: number;
42
44
  offset: number;
43
45
  }
@@ -0,0 +1,18 @@
1
+ import { type AccountKey, type MessageStore } from "../store/store.js";
2
+ import type { SearchAllItem } from "./search-all.js";
3
+ /** The account a hit of the owner's own invoice, product or wallet names: no import made it. */
4
+ export declare const OWN_BUSINESS: AccountKey;
5
+ export declare const BUSINESS_WORDS_ONLY: string;
6
+ export interface BusinessLane {
7
+ items: SearchAllItem[];
8
+ hasMore: boolean;
9
+ /** Every account read. */
10
+ read: AccountKey[];
11
+ }
12
+ /** The `business` lane: numbers and names folded in memory, each hit titled as its ref reads everywhere else. */
13
+ export declare const searchBusiness: (store: MessageStore, { words, anyWord, window, accounts, }: {
14
+ words: string[];
15
+ anyWord: boolean;
16
+ window: number;
17
+ accounts: AccountKey[] | undefined;
18
+ }) => Promise<BusinessLane>;
@@ -0,0 +1,38 @@
1
+ import { INTERNAL_NOTES } from "../domain/providers.js";
2
+ import { BUSINESS_FIND_MAX } from "../store/store.js";
3
+ /** The account a hit of the owner's own invoice, product or wallet names: no import made it. */
4
+ export const OWN_BUSINESS = { provider: "business", account: INTERNAL_NOTES };
5
+ export const BUSINESS_WORDS_ONLY = "invoices, payments, orders, contracts, subscriptions, products and wallets are found by the words of their " +
6
+ "numbers and names only";
7
+ /**
8
+ * A hit's account is its source record's. An imported row whose records all moved to other entities keeps its import
9
+ * provider with no account, so it is never taken for the owner's own.
10
+ */
11
+ const placeOf = ({ source, imported }) => source ?? (imported === undefined ? OWN_BUSINESS : { provider: imported, account: "" });
12
+ /** The `business` lane: numbers and names folded in memory, each hit titled as its ref reads everywhere else. */
13
+ export const searchBusiness = async (store, { words, anyWord, window, accounts, }) => {
14
+ const asked = Math.min(window + 1, BUSINESS_FIND_MAX);
15
+ const found = await store.business.find({
16
+ words,
17
+ anyWord,
18
+ limit: asked,
19
+ ...(accounts === undefined ? {} : { accounts }),
20
+ });
21
+ const page = found.slice(0, window);
22
+ const titles = await store.refs.summaries(page.map(({ ref }) => ref));
23
+ return {
24
+ items: page.map((hit) => ({
25
+ kind: hit.kind,
26
+ ref: hit.ref,
27
+ ...placeOf(hit),
28
+ title: titles.get(hit.ref)?.title ?? null,
29
+ timestamp: new Date(hit.updatedAt).toISOString(),
30
+ text: hit.text,
31
+ review: hit.review,
32
+ ...(hit.source === undefined ? {} : { sourceRecord: hit.source }),
33
+ foundBy: ["title"],
34
+ })),
35
+ hasMore: found.length > window || (asked < window + 1 && found.length === asked),
36
+ read: accounts ?? [...(await store.business.accounts()), OWN_BUSINESS],
37
+ };
38
+ };
@@ -3,7 +3,7 @@ import type { AccountKey, MessageStore } from "../store/store.js";
3
3
  import type { SearchFound, SearchQuery } from "./messages.js";
4
4
  import type { MeaningLane } from "./messages-discovery.js";
5
5
  import { type SearchAllFound, type SearchAllItem, type SearchAllMessenger, type SearchAllRequest, type Skipped } from "./search-all.js";
6
- export declare const RESOURCES_SEARCHED_WITH_MEETINGS: readonly ["messages", "mail", "notes", "events", "crm", "meetings"];
6
+ export declare const RESOURCES_SEARCHED_WITH_MEETINGS: readonly ["messages", "mail", "notes", "events", "crm", "business", "meetings"];
7
7
  export type ResourceWithMeetings = (typeof RESOURCES_SEARCHED_WITH_MEETINGS)[number];
8
8
  export interface MeetingSearchItem {
9
9
  kind: "meeting";
@@ -243,14 +243,18 @@ const holdingMeetings = async (store, named) => {
243
243
  }
244
244
  return holding.length ? holding : named;
245
245
  };
246
+ const keyOf = ({ provider, account }) => `${provider}\u0000${account}`;
246
247
  const searchAllOfSource = async (store, account, source, request, messenger, searchMessages, meaning) => {
247
248
  const only = request.only ?? RESOURCES_SEARCHED_WITH_MEETINGS;
248
249
  const entries = entriesOfList(source, await listContextOf(store, account, messenger.app));
249
- const { skipped } = fitting(entries, only, "search all", (kind) => `--only leaves ${kind} out`);
250
+ // Any provider's import may write business data, so its accounts are the ones that hold some, whatever their kind.
251
+ const imported = only.includes("business") ? new Set((await store.business.accounts()).map(keyOf)) : new Set();
252
+ const holdsBusiness = (one) => imported.has(keyOf(one));
253
+ const { skipped } = fitting(entries, only.filter((one) => one !== "business"), "search all", (kind) => `--only leaves ${kind} out`, holdsBusiness);
250
254
  const named = (resource) => [
251
255
  ...new Map(entries
252
256
  .flatMap(({ accounts }) => accounts)
253
- .filter((one) => listedHolds(one, resource))
257
+ .filter((one) => (resource === "business" ? holdsBusiness(one) : listedHolds(one, resource)))
254
258
  .map(({ provider, account }) => [`${provider}\u0000${account}`, { provider, account }])).values(),
255
259
  ];
256
260
  const meetings = await holdingMeetings(store, named("meetings"));
@@ -275,6 +279,7 @@ const searchAllOfSource = async (store, account, source, request, messenger, sea
275
279
  notes: named("notes"),
276
280
  events: named("events"),
277
281
  crm: named("crm"),
282
+ business: named("business"),
278
283
  },
279
284
  ...(meetings[0] ? { meetingAccount: meetings[0] } : {}),
280
285
  }, messenger, searchMessages, meaning);