@wirecat/cli-core 0.610.0 → 0.612.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 (47) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/calendar/mcp/index.d.ts +12 -12
  3. package/dist/cli/enrichment-consents-command.d.ts +19 -0
  4. package/dist/cli/enrichment-consents-command.js +110 -0
  5. package/dist/cli/model-catalogue-command.d.ts +8 -0
  6. package/dist/cli/model-catalogue-command.js +4 -1
  7. package/dist/embeddings/keys.d.ts +2 -0
  8. package/dist/embeddings/keys.js +2 -0
  9. package/dist/errors/reasons.js +1 -0
  10. package/dist/models/anthropic.js +6 -0
  11. package/dist/models/index.d.ts +1 -1
  12. package/dist/models/openai.js +8 -1
  13. package/dist/models/types.d.ts +7 -0
  14. package/dist/services/enrichment-setting.d.ts +50 -0
  15. package/dist/services/enrichment-setting.js +84 -0
  16. package/dist/services/enrichment.d.ts +111 -0
  17. package/dist/services/enrichment.js +240 -0
  18. package/dist/services/index.d.ts +2 -0
  19. package/dist/services/index.js +2 -0
  20. package/dist/services/metadata.d.ts +1 -1
  21. package/dist/services/notes-search.d.ts +15 -1
  22. package/dist/services/notes-search.js +38 -2
  23. package/dist/services/search-all.js +8 -6
  24. package/dist/store/exports.d.ts +1 -0
  25. package/dist/store/exports.js +1 -0
  26. package/dist/store/sqlite/email-index.d.ts +2 -2
  27. package/dist/store/sqlite/email-index.js +6 -4
  28. package/dist/store/sqlite/emails.js +5 -0
  29. package/dist/store/sqlite/enrichments.d.ts +60 -0
  30. package/dist/store/sqlite/enrichments.js +113 -0
  31. package/dist/store/sqlite/entity-types.d.ts +1 -0
  32. package/dist/store/sqlite/entity-types.js +1 -0
  33. package/dist/store/sqlite/index-text.d.ts +2 -0
  34. package/dist/store/sqlite/index-text.js +2 -0
  35. package/dist/store/sqlite/mail-nearest.js +1 -1
  36. package/dist/store/sqlite/manifest.js +2 -0
  37. package/dist/store/sqlite/migrations.generated.js +14 -0
  38. package/dist/store/sqlite/note-index.d.ts +1 -2
  39. package/dist/store/sqlite/note-index.js +25 -4
  40. package/dist/store/sqlite/note-search.js +8 -1
  41. package/dist/store/sqlite/schema/enrichments.d.ts +137 -0
  42. package/dist/store/sqlite/schema/enrichments.js +12 -0
  43. package/dist/store/sqlite/schema.d.ts +1 -0
  44. package/dist/store/sqlite/schema.js +1 -0
  45. package/dist/store/store.d.ts +3 -0
  46. package/dist/store/store.js +5 -0
  47. package/package.json +4 -4
@@ -0,0 +1,111 @@
1
+ import { type KeyringStore } from "@wirecat/cli-base";
2
+ import { type ModelAdapter, type ModelUsage } from "../models/index.js";
3
+ import type { AppIdentity } from "../ports/app.js";
4
+ import type { EnrichmentNarrowing, EnrichmentStore } from "../store/store.js";
5
+ import { type EnrichmentSetting, estimateEnrichment } from "./enrichment-setting.js";
6
+ /** One sync's share, as embedding is bounded per run; the next sync goes on where it stopped. */
7
+ export declare const ENRICH_PER_RUN = 600;
8
+ /** The reply's rows by index; a reply that is not this JSON fails the whole batch. */
9
+ export declare const parseEnrichmentReply: (text: string) => Map<number, string>;
10
+ export interface EnrichOptions {
11
+ env: NodeJS.ProcessEnv;
12
+ /** The tool whose keyring entry holds the provider key; without it only the environment's key is read. */
13
+ app?: AppIdentity;
14
+ keyring?: KeyringStore;
15
+ maxRecords?: number;
16
+ concurrency?: number;
17
+ narrow?: EnrichmentNarrowing;
18
+ /** Tests inject these; nothing in the suite reaches a provider. */
19
+ adapters?: Readonly<Record<string, ModelAdapter>>;
20
+ fetch?: typeof fetch;
21
+ key?: (provider: string) => string | undefined;
22
+ signal?: AbortSignal;
23
+ }
24
+ export type EnrichRun = {
25
+ status: "off";
26
+ } | {
27
+ status: "done" | "stopped";
28
+ provider: string;
29
+ model: string;
30
+ /** Records the model answered for, with or without facts. */
31
+ enriched: number;
32
+ failed: number;
33
+ /** Records still without an enrichment of their current text, in the types this run read. */
34
+ left: number;
35
+ usage: ModelUsage;
36
+ cost_usd: number | null;
37
+ /** Why a stopped run stopped, with no provider body or key in it. */
38
+ reason?: string;
39
+ };
40
+ export type KeySource = "keyring" | "file" | "env" | "given";
41
+ export declare const keyVariable: (provider: string) => string;
42
+ /**
43
+ * Sends records with no enrichment of their current text to the provider the owner consented to, in batches, and
44
+ * keeps what it writes; the next index drain puts it beside each record. Off, it sends nothing and reads no key.
45
+ */
46
+ export declare const enrichRecords: (store: {
47
+ enrichment?: EnrichmentStore | undefined;
48
+ }, options: EnrichOptions) => Promise<EnrichRun>;
49
+ export interface EnrichmentTarget {
50
+ provider: string;
51
+ model: string;
52
+ endpoint: string;
53
+ endpoint_host: string;
54
+ /** Whether a key for this provider is found, and where; never the key. */
55
+ key: {
56
+ present: boolean;
57
+ source: KeySource | null;
58
+ env_var: string;
59
+ };
60
+ price_known: boolean;
61
+ }
62
+ export interface EnrichmentState {
63
+ on: boolean;
64
+ /** The setting in force; `null` while off. */
65
+ provider: string | null;
66
+ model: string | null;
67
+ endpoint: string | null;
68
+ consented_at: string | null;
69
+ /**
70
+ * What the estimate and the consent are about: the setting in force, else the one `set` proposes, else the
71
+ * default offer. A window shows its price while enrichment is off.
72
+ */
73
+ target: EnrichmentTarget;
74
+ records: number;
75
+ enriched: number;
76
+ pending: number;
77
+ estimate: ReturnType<typeof estimateEnrichment>;
78
+ /** Records one sync enriches of notes and documents, and as many of mail. */
79
+ per_sync: number;
80
+ /** Syncs to enrich what is pending now. */
81
+ syncs_needed: number;
82
+ /** Every record added or changed later is sent too, at the next sync. */
83
+ sends_new_records: true;
84
+ offered: readonly {
85
+ provider: string;
86
+ model: string;
87
+ default: boolean;
88
+ usd_per_million: {
89
+ input: number;
90
+ output: number;
91
+ };
92
+ }[];
93
+ /** What the measurement on synthetic data found; the consent text quotes it. */
94
+ measured: typeof MEASURED;
95
+ }
96
+ /** cli-testing write-time-enrichment, 10,444 synthetic records, memo with e5-small, gpt-4o-mini, 2026-11-08. */
97
+ export declare const MEASURED: {
98
+ readonly reworded_at_10: {
99
+ readonly off: 0.62;
100
+ readonly on: 0.79;
101
+ };
102
+ readonly own_words_first: {
103
+ readonly off: 0.54;
104
+ readonly on: 0.48;
105
+ };
106
+ readonly source: "https://github.com/WireCatLabs/cli-testing/pull/322";
107
+ };
108
+ /** The setting and how far the store is enriched: what a window shows beside the switch. */
109
+ export declare const enrichmentState: (store: {
110
+ enrichment?: EnrichmentStore | undefined;
111
+ }, env: NodeJS.ProcessEnv, estimateFor?: Pick<EnrichmentSetting, "provider" | "model" | "base_url">, keys?: Pick<EnrichOptions, "app" | "keyring">) => Promise<EnrichmentState>;
@@ -0,0 +1,240 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import * as v from "valibot";
3
+ import { embeddingKeys, endpointKeyName } from "../embeddings/keys.js";
4
+ import { modelGateway } from "../models/index.js";
5
+ import { costOf, DEFAULT_OFFER, enrichmentEndpoint, enrichmentPrice, estimateEnrichment, offeredModels, readEnrichmentSetting, } from "./enrichment-setting.js";
6
+ /** One sync's share, as embedding is bounded per run; the next sync goes on where it stopped. */
7
+ export const ENRICH_PER_RUN = 600;
8
+ const BATCH = 20;
9
+ const CONCURRENCY = 4;
10
+ /** A long document is enriched by its start: the cost stays bounded, and its own chunks carry the rest. */
11
+ const MAX_INPUT_CHARS = 4_000;
12
+ const MAX_FACTS = 5;
13
+ const MAX_QUESTIONS = 3;
14
+ const MAX_LINE = 400;
15
+ /** After this many failed batches in one run the provider is not answering; the rest wait for the next sync. */
16
+ const MAX_FAILED_BATCHES = 3;
17
+ const SYSTEM = `For each record, write what a memory system would store about it.
18
+
19
+ For each record:
20
+ - facts: one to three standalone sentences, each stating exactly one fact. Name people, projects and things in
21
+ full, leave no pronoun unresolved, and turn relative dates into absolute ones using the record's date. Keep
22
+ amounts, dates and times exactly. Say whether the fact is confirmed, only proposed, rejected or cancelled.
23
+ Small talk with no fact gets an empty list.
24
+ - questions: two questions a person might ask whose answer is in this record, in everyday words that differ
25
+ from the record's own words (synonyms, plainer terms). Empty for small talk.
26
+
27
+ Write in the record's own language. Reply with JSON only: {"records": [{"i": <index>, "facts": [...], "questions": [...]}]}, one entry per record.`;
28
+ const line = v.pipe(v.unknown(), v.transform((value) => (typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, MAX_LINE) : "")));
29
+ const Reply = v.object({
30
+ records: v.array(v.object({
31
+ i: v.pipe(v.number(), v.integer(), v.minValue(0)),
32
+ facts: v.optional(v.array(line), []),
33
+ questions: v.optional(v.array(line), []),
34
+ })),
35
+ });
36
+ /** The reply's rows by index; a reply that is not this JSON fails the whole batch. */
37
+ export const parseEnrichmentReply = (text) => {
38
+ const start = text.indexOf("{");
39
+ const end = text.lastIndexOf("}");
40
+ if (start < 0 || end < start)
41
+ throw new CliError("invalid_response", "the enrichment reply holds no JSON object");
42
+ let parsed;
43
+ try {
44
+ parsed = JSON.parse(text.slice(start, end + 1));
45
+ }
46
+ catch {
47
+ throw new CliError("invalid_response", "the enrichment reply is not valid JSON");
48
+ }
49
+ const checked = v.safeParse(Reply, parsed);
50
+ if (!checked.success)
51
+ throw new CliError("invalid_response", "the enrichment reply does not have the asked shape");
52
+ return new Map(checked.output.records.map((row) => [
53
+ row.i,
54
+ [...row.facts.slice(0, MAX_FACTS), ...row.questions.slice(0, MAX_QUESTIONS)].filter(Boolean).join("\n"),
55
+ ]));
56
+ };
57
+ const recordsData = (batch) => JSON.stringify(batch.map((record, i) => ({
58
+ i,
59
+ date: record.at === null ? null : new Date(record.at).toISOString().slice(0, 10),
60
+ kind: record.type === "email" ? "mail" : "note",
61
+ text: record.text.slice(0, MAX_INPUT_CHARS),
62
+ })));
63
+ /** The provider's key and where it came from; it never leaves this process. */
64
+ const keyLookup = (options, setting) => {
65
+ if (options.key) {
66
+ const key = options.key(setting.provider);
67
+ return key === undefined ? undefined : { key, source: "given" };
68
+ }
69
+ const name = setting.base_url === undefined ? setting.provider : endpointKeyName(setting.base_url);
70
+ if (options.app) {
71
+ const keys = embeddingKeys(options.app, options.env, options.keyring);
72
+ // The tool's `embeddings:<provider>` entry or the environment, then an entry named after the provider alone.
73
+ const stored = keys.read(name);
74
+ if (stored)
75
+ return {
76
+ key: stored.key,
77
+ source: stored.source === "file" ? "file" : stored.source === "keyring" ? "keyring" : "env",
78
+ };
79
+ const plain = setting.base_url === undefined ? keys.readPlain(setting.provider) : undefined;
80
+ return plain === undefined ? undefined : { key: plain, source: "keyring" };
81
+ }
82
+ const key = setting.base_url === undefined ? options.env[keyVariable(setting.provider)]?.trim() : undefined;
83
+ return key ? { key, source: "env" } : undefined;
84
+ };
85
+ export const keyVariable = (provider) => `${provider.toUpperCase()}_API_KEY`;
86
+ /**
87
+ * Sends records with no enrichment of their current text to the provider the owner consented to, in batches, and
88
+ * keeps what it writes; the next index drain puts it beside each record. Off, it sends nothing and reads no key.
89
+ */
90
+ export const enrichRecords = async (store, options) => {
91
+ const setting = readEnrichmentSetting(options.env);
92
+ if (!setting || !store.enrichment)
93
+ return { status: "off" };
94
+ const enrichment = store.enrichment;
95
+ const baseUrl = enrichmentEndpoint(setting);
96
+ const target = { provider: setting.provider, model: setting.model, baseUrl };
97
+ const apiKey = keyLookup(options, setting)?.key;
98
+ const maxRecords = options.maxRecords ?? ENRICH_PER_RUN;
99
+ // Without a key the public API answers 401 only after the records' text has left; a custom server may need none.
100
+ if (apiKey === undefined && setting.base_url === undefined)
101
+ return {
102
+ status: "stopped",
103
+ provider: setting.provider,
104
+ model: setting.model,
105
+ enriched: 0,
106
+ failed: 0,
107
+ left: (await enrichment.pending(Number.MAX_SAFE_INTEGER, options.narrow)).length,
108
+ usage: { input: 0, output: 0 },
109
+ cost_usd: 0,
110
+ reason: `no ${setting.provider} key: set ${setting.provider.toUpperCase()}_API_KEY, or the tool's own key; nothing was sent`,
111
+ };
112
+ const gateway = modelGateway({
113
+ resolve: () => target,
114
+ // The setting exists only with the owner's yes for this provider and endpoint; the endpoint is checked again.
115
+ consent: (_request, chosen) => chosen.provider === setting.provider && chosen.baseUrl === baseUrl,
116
+ key: () => apiKey,
117
+ ...(options.adapters ? { adapters: options.adapters } : {}),
118
+ ...(options.fetch ? { fetch: options.fetch } : {}),
119
+ ...(options.signal ? { signal: options.signal } : {}),
120
+ });
121
+ const queue = await enrichment.pending(maxRecords, options.narrow);
122
+ const batches = [];
123
+ for (let start = 0; start < queue.length; start += BATCH)
124
+ batches.push(queue.slice(start, start + BATCH));
125
+ const usage = { input: 0, output: 0 };
126
+ let enriched = 0;
127
+ let failed = 0;
128
+ let failedBatches = 0;
129
+ let reason;
130
+ const ask = async (batch) => {
131
+ const answer = await gateway.complete({
132
+ purpose: "enrichment",
133
+ system: SYSTEM,
134
+ prompt: "Enrich each record of the data.",
135
+ data: recordsData(batch),
136
+ // The facts must keep names, amounts and dates exactly, which the default no-copy policy forbids.
137
+ allowSourceQuotes: true,
138
+ maxTokens: 8_192,
139
+ ...(setting.provider === "openai" && setting.base_url === undefined
140
+ ? { options: { response_format: { type: "json_object" }, temperature: 0 } }
141
+ : {}),
142
+ });
143
+ const rows = parseEnrichmentReply(answer.text);
144
+ const used = answer.usage ?? { input: answer.tokens, output: 0 };
145
+ usage.input += used.input;
146
+ usage.output += used.output;
147
+ const answered = batch.flatMap((record, i) => {
148
+ const text = rows.get(i);
149
+ return text === undefined
150
+ ? []
151
+ : [
152
+ {
153
+ type: record.type,
154
+ id: record.id,
155
+ hash: record.hash,
156
+ provider: setting.provider,
157
+ model: setting.model,
158
+ text,
159
+ tokens: Math.round(answer.tokens / batch.length),
160
+ },
161
+ ];
162
+ });
163
+ await enrichment.save(answered);
164
+ enriched += answered.length;
165
+ failed += batch.length - answered.length;
166
+ };
167
+ let next = 0;
168
+ const worker = async () => {
169
+ while (reason === undefined && next < batches.length) {
170
+ const batch = batches[next++];
171
+ try {
172
+ await ask(batch);
173
+ }
174
+ catch (error) {
175
+ failed += batch.length;
176
+ const code = error instanceof CliError ? error.code : "invalid_response";
177
+ if (code !== "invalid_response" || ++failedBatches >= MAX_FAILED_BATCHES)
178
+ reason = error instanceof CliError ? error.message : "the enrichment provider failed";
179
+ }
180
+ }
181
+ };
182
+ await Promise.all(Array.from({ length: Math.min(options.concurrency ?? CONCURRENCY, batches.length) }, () => worker()));
183
+ const left = (await enrichment.pending(Number.MAX_SAFE_INTEGER, options.narrow)).length;
184
+ return {
185
+ status: reason === undefined ? "done" : "stopped",
186
+ provider: setting.provider,
187
+ model: setting.model,
188
+ enriched,
189
+ failed,
190
+ left,
191
+ usage,
192
+ cost_usd: costOf(usage, setting),
193
+ ...(reason === undefined ? {} : { reason }),
194
+ };
195
+ };
196
+ /** cli-testing write-time-enrichment, 10,444 synthetic records, memo with e5-small, gpt-4o-mini, 2026-11-08. */
197
+ export const MEASURED = {
198
+ reworded_at_10: { off: 0.62, on: 0.79 },
199
+ own_words_first: { off: 0.54, on: 0.48 },
200
+ source: "https://github.com/WireCatLabs/cli-testing/pull/322",
201
+ };
202
+ /** The setting and how far the store is enriched: what a window shows beside the switch. */
203
+ export const enrichmentState = async (store, env, estimateFor, keys = {}) => {
204
+ const setting = readEnrichmentSetting(env);
205
+ const counts = (await store.enrichment?.counts()) ?? {
206
+ records: 0,
207
+ enriched: 0,
208
+ pendingChars: 0,
209
+ pendingByType: { document: 0, note: 0, email: 0 },
210
+ };
211
+ const pending = counts.records - counts.enriched;
212
+ const chosen = estimateFor ?? setting ?? DEFAULT_OFFER;
213
+ const endpoint = enrichmentEndpoint(chosen);
214
+ const found = keyLookup({ env, ...keys }, chosen);
215
+ const notes = counts.pendingByType.document + counts.pendingByType.note;
216
+ return {
217
+ on: setting !== undefined,
218
+ provider: setting?.provider ?? null,
219
+ model: setting?.model ?? null,
220
+ endpoint: setting ? enrichmentEndpoint(setting) : null,
221
+ consented_at: setting?.consented_at ?? null,
222
+ target: {
223
+ provider: chosen.provider,
224
+ model: chosen.model,
225
+ endpoint,
226
+ endpoint_host: new URL(endpoint).host,
227
+ key: { present: found !== undefined, source: found?.source ?? null, env_var: keyVariable(chosen.provider) },
228
+ price_known: enrichmentPrice(chosen.provider, chosen.model, chosen.base_url) !== undefined,
229
+ },
230
+ records: counts.records,
231
+ enriched: counts.enriched,
232
+ pending,
233
+ estimate: estimateEnrichment(pending, counts.pendingChars, chosen),
234
+ per_sync: ENRICH_PER_RUN,
235
+ syncs_needed: Math.ceil(Math.max(notes, counts.pendingByType.email) / ENRICH_PER_RUN),
236
+ sends_new_records: true,
237
+ offered: offeredModels(),
238
+ measured: MEASURED,
239
+ };
240
+ };
@@ -73,6 +73,8 @@ export type { ServiceDeps, ServiceMessenger } from "./deps.js";
73
73
  export { accountStore, crossAccount, OFFLINE, onlineDeps, storedDeps, storeOnlyDeps } from "./deps.js";
74
74
  export type { Embedded, EmbeddingsService, EmbedStatus, FoundConversation } from "./embeddings.js";
75
75
  export { embeddingsService } from "./embeddings.js";
76
+ export { ENRICH_PER_RUN, type EnrichmentState, type EnrichOptions, type EnrichRun, enrichmentState, enrichRecords, } from "./enrichment.js";
77
+ export { type EnrichmentSetting, estimateEnrichment, readEnrichmentSetting, writeEnrichmentSetting, } from "./enrichment-setting.js";
76
78
  export type { EvidenceKind, EvidenceMessage, EvidencePacket, EvidencePacketInput, EvidenceSource } from "./evidence.js";
77
79
  export { prepareEvidencePacket } from "./evidence.js";
78
80
  export type { EvidenceReadQuery, StoredEvidencePacket } from "./evidence-read.js";
@@ -55,6 +55,8 @@ export { chatsService, EVENTS_DAYS } from "./chats.js";
55
55
  export { BATCH_SIZE, conversationsService } from "./conversations.js";
56
56
  export { accountStore, crossAccount, OFFLINE, onlineDeps, storedDeps, storeOnlyDeps } from "./deps.js";
57
57
  export { embeddingsService } from "./embeddings.js";
58
+ export { ENRICH_PER_RUN, enrichmentState, enrichRecords, } from "./enrichment.js";
59
+ export { estimateEnrichment, readEnrichmentSetting, writeEnrichmentSetting, } from "./enrichment-setting.js";
58
60
  export { prepareEvidencePacket } from "./evidence.js";
59
61
  export { readEvidencePacket } from "./evidence-read.js";
60
62
  export { foldersService } from "./folders.js";
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -1,3 +1,4 @@
1
+ import { type KeyringStore } from "@wirecat/cli-base";
1
2
  import { type QueryNode } from "@wirecat/cli-base/query";
2
3
  import { type Embedder, type WarmEmbedders } from "../embeddings/embed.js";
3
4
  import { type TextModel } from "../embeddings/models.js";
@@ -9,6 +10,7 @@ import { type Stemmer } from "../search/stem.js";
9
10
  import { type SearchTotal } from "../search/total.js";
10
11
  import type { Link, NearestNote, Note, NoteHit } from "../store/index.js";
11
12
  import type { AccountKey, MessageStore } from "../store/store.js";
13
+ import { type EnrichOptions, type EnrichRun } from "./enrichment.js";
12
14
  export interface NotesSearchRequest {
13
15
  text: string;
14
16
  limit: number;
@@ -47,12 +49,24 @@ export interface NotesEmbedOptions {
47
49
  maxChunks?: number;
48
50
  env?: NodeJS.ProcessEnv;
49
51
  threads?: number;
52
+ /** Whose keyring entry holds the enrichment provider's key; without it only the environment's key is read. */
53
+ app?: AppIdentity;
54
+ keyring?: KeyringStore;
55
+ /** Tests give a fake model here; nothing in the suite reaches a provider. */
56
+ enrichWith?: Pick<EnrichOptions, "adapters" | "fetch" | "key">;
50
57
  }
51
58
  export interface NotesEmbedded {
52
59
  model: string;
53
60
  embedded: number;
54
- /** Chunks still without a vector, when `maxChunks` stopped the run. */
61
+ /** Chunks still without a vector, when `maxChunks` stopped the run, or records still to enrich. */
55
62
  left: boolean;
63
+ /** What the owner's enrichment did first; absent when it is off. */
64
+ enrichment?: Exclude<EnrichRun, {
65
+ status: "off";
66
+ }> | {
67
+ status: "failed";
68
+ reason: string;
69
+ };
56
70
  }
57
71
  export declare const localModel: (choice: string | undefined, env: NodeJS.ProcessEnv | undefined, command: string | undefined) => {
58
72
  model: TextModel;
@@ -16,6 +16,7 @@ import { createStemmer, DEFAULT_STEMMERS } from "../search/stem.js";
16
16
  import { TOTAL_CAP, totalOf } from "../search/total.js";
17
17
  import { openPictureEmbedderFor } from "./document-pictures.js";
18
18
  import { documentSource } from "./document-source.js";
19
+ import { enrichRecords } from "./enrichment.js";
19
20
  import { plainQueryWords, titleQuery, titleTiers } from "./notes-title-tier.js";
20
21
  import { PICTURE_FLOOR, plainWords } from "./pictures.js";
21
22
  import { listContextOf } from "./search-kind.js";
@@ -120,11 +121,46 @@ const embedChunks = async (store, source, { model: choice, maxChunks = Number.PO
120
121
  return { model: model.id, embedded, left };
121
122
  });
122
123
  };
123
- export const embedNotes = (store, options = {}) => embedChunks(store, store.notes, options);
124
+ /**
125
+ * With enrichment on, the records of these types are enriched before their chunks are embedded, so the same run
126
+ * embeds the new text. A failed enrichment never fails the embed; it is reported and the next run tries again.
127
+ */
128
+ const enrichedFirst = async (store, types, options, embed) => {
129
+ let enrichment;
130
+ try {
131
+ const run = await enrichRecords(store, {
132
+ env: options.env ?? process.env,
133
+ narrow: { types },
134
+ ...(options.app ? { app: options.app } : {}),
135
+ ...(options.keyring ? { keyring: options.keyring } : {}),
136
+ ...options.enrichWith,
137
+ });
138
+ if (run.status !== "off")
139
+ enrichment = run;
140
+ }
141
+ catch (error) {
142
+ enrichment = { status: "failed", reason: error instanceof Error ? error.message : "enrichment failed" };
143
+ }
144
+ let embedded;
145
+ try {
146
+ embedded = await embed();
147
+ }
148
+ catch (error) {
149
+ // A missing model must not hide what was already sent and paid for.
150
+ if (enrichment && error instanceof CliError)
151
+ throw new CliError(error.code, error.message, { ...error.details, enrichment });
152
+ throw error;
153
+ }
154
+ if (!enrichment)
155
+ return embedded;
156
+ const more = enrichment.status !== "failed" && enrichment.left > 0 && enrichment.enriched > 0;
157
+ return { ...embedded, left: embedded.left || more, enrichment };
158
+ };
159
+ export const embedNotes = (store, options = {}) => enrichedFirst(store, ["document", "note"], options, () => embedChunks(store, store.notes, options));
124
160
  /** Embeds calendar events' pieces as notes' are embedded; the occurrences of a series share one vector. */
125
161
  export const embedEvents = (store, options = {}) => embedChunks(store, store.calendar, options);
126
162
  /** Embeds mail's chunks as notes' are embedded: same model and key, so search by meaning reads both. */
127
- export const embedMail = (store, options = {}) => embedChunks(store, store.mail, options);
163
+ export const embedMail = (store, options = {}) => enrichedFirst(store, ["email"], options, () => embedChunks(store, store.mail, options));
128
164
  /** Notes nearest in meaning to the query, best first; only notes already embedded can be found. */
129
165
  export const nearestNotes = async (store, query, options) => {
130
166
  const { key, vector, floor } = await queryVector(store, query, options);
@@ -358,20 +358,22 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
358
358
  /**
359
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
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.
361
+ * one model scores every source, so cosine compares across them (IDEA-249). A hit only words found takes the cosine of
362
+ * the hit above it in its source: its source ranked it there, and with none it would follow every hit meaning found.
363
363
  */
364
364
  const oneList = (lists, cosines) => {
365
365
  const place = new Map();
366
- for (const list of lists)
366
+ for (const list of lists) {
367
+ let above = Number.NEGATIVE_INFINITY;
367
368
  list.forEach((item, rank) => {
369
+ above = cosines.get(item.ref) ?? above;
368
370
  const held = place.get(item.ref);
369
371
  if (!held || rank < held.rank)
370
- place.set(item.ref, { item, rank });
372
+ place.set(item.ref, { item, rank, cosine: above });
371
373
  });
372
- const cosine = (ref) => cosines.get(ref) ?? Number.NEGATIVE_INFINITY;
374
+ }
373
375
  const head = (rank) => Math.min(rank, 1);
374
376
  return [...place.values()]
375
- .sort((a, b) => head(a.rank) - head(b.rank) || cosine(b.item.ref) - cosine(a.item.ref) || a.rank - b.rank)
377
+ .sort((a, b) => head(a.rank) - head(b.rank) || b.cosine - a.cosine || a.rank - b.rank)
376
378
  .map(({ item }) => item);
377
379
  };
@@ -28,6 +28,7 @@ export type { CounterTarget } from "./sqlite/counters.js";
28
28
  export { crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting } from "./sqlite/crm-settings.js";
29
29
  export { type EmailMarks, MAIL_AGENDA_COLUMNS, type MarkedEmail, type NewestEmail, type ThreadActivity, } from "./sqlite/email-activity.js";
30
30
  export { messageOfEmail, threadConversation } from "./sqlite/emails.js";
31
+ export { ENRICHMENT_SUBJECTS, type EnrichmentCandidate, type EnrichmentCounts, type EnrichmentNarrowing, type EnrichmentStore, type EnrichmentSubject, type SavedEnrichment, } from "./sqlite/enrichments.js";
31
32
  export { orphanPointers } from "./sqlite/entity-types.js";
32
33
  export { involvementStoreOver } from "./sqlite/involvements.js";
33
34
  export type { MeetingContextReadCapabilities, MeetingReadCapabilities, TranscriptContextInput, TranscriptContextPage, } from "./sqlite/meeting-reads.js";
@@ -11,6 +11,7 @@ export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
11
11
  export { crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting } from "./sqlite/crm-settings.js";
12
12
  export { MAIL_AGENDA_COLUMNS, } from "./sqlite/email-activity.js";
13
13
  export { messageOfEmail, threadConversation } from "./sqlite/emails.js";
14
+ export { ENRICHMENT_SUBJECTS, } from "./sqlite/enrichments.js";
14
15
  export { orphanPointers } from "./sqlite/entity-types.js";
15
16
  export { involvementStoreOver } from "./sqlite/involvements.js";
16
17
  export { OTHER_SOURCES } from "./sqlite/mention-sources.js";
@@ -3,10 +3,10 @@ import type { Stemmer, Stemmers } from "../../search/stem.js";
3
3
  import type { CacheDatabase } from "../driver.js";
4
4
  export declare const titleOf: (subject: string | null) => string | null;
5
5
  /**
6
- * Every piece of mail: a stretch of a thread, or of one email's attachment. A thread piece holds no email of its
6
+ * Every piece of mail: a stretch of a thread, one email's attachment, or the text a model wrote about one email. A thread piece holds no email of its
7
7
  * own; `threadPieces` cuts the thread again to find which emails it spans.
8
8
  */
9
- export declare const MAIL_PIECES = "(SELECT k.id, k.content_hash, k.chunkable_type AS type, k.chunkable_id AS owner, k.position,\n k.start_offset, k.end_offset, k.account_id, k.occurred_at, a.attachable_id AS email_id,\n CASE k.chunkable_type WHEN 'email_thread' THEN k.chunkable_id\n ELSE (SELECT email_thread_id FROM emails WHERE id = a.attachable_id) END AS thread_id\n FROM chunks k LEFT JOIN attachments a ON k.chunkable_type = 'attachment' AND a.id = k.chunkable_id\n AND a.attachable_type = 'email'\n WHERE k.chunkable_type = 'email_thread' OR a.id IS NOT NULL) p";
9
+ export declare const MAIL_PIECES = "(SELECT k.id, k.content_hash, k.chunkable_type AS type, k.chunkable_id AS owner, k.position,\n k.start_offset, k.end_offset, k.account_id, k.occurred_at,\n CASE k.chunkable_type WHEN 'email_enrichment' THEN k.chunkable_id ELSE a.attachable_id END AS email_id,\n CASE k.chunkable_type WHEN 'email_thread' THEN k.chunkable_id\n ELSE (SELECT email_thread_id FROM emails\n WHERE id = CASE k.chunkable_type WHEN 'email_enrichment' THEN k.chunkable_id ELSE a.attachable_id END) END AS thread_id\n FROM chunks k LEFT JOIN attachments a ON k.chunkable_type = 'attachment' AND a.id = k.chunkable_id\n AND a.attachable_type = 'email'\n WHERE k.chunkable_type IN ('email_thread', 'email_enrichment') OR a.id IS NOT NULL) p";
10
10
  /**
11
11
  * A thread's pieces, email by email: a piece never spans two emails, so a hit names the email that holds it
12
12
  * (bench/mail-quality). A new reply adds its own pieces; every earlier one keeps its hash and so its vector.
@@ -6,16 +6,18 @@ import { write } from "./transaction.js";
6
6
  import { dropUnusedVectors } from "./vector-index.js";
7
7
  export const titleOf = (subject) => subject?.replace(/^\s*((re|fwd?|aw|wg)\s*:\s*)+/i, "").trim() || null;
8
8
  /**
9
- * Every piece of mail: a stretch of a thread, or of one email's attachment. A thread piece holds no email of its
9
+ * Every piece of mail: a stretch of a thread, one email's attachment, or the text a model wrote about one email. A thread piece holds no email of its
10
10
  * own; `threadPieces` cuts the thread again to find which emails it spans.
11
11
  */
12
12
  export const MAIL_PIECES = `(SELECT k.id, k.content_hash, k.chunkable_type AS type, k.chunkable_id AS owner, k.position,
13
- k.start_offset, k.end_offset, k.account_id, k.occurred_at, a.attachable_id AS email_id,
13
+ k.start_offset, k.end_offset, k.account_id, k.occurred_at,
14
+ CASE k.chunkable_type WHEN 'email_enrichment' THEN k.chunkable_id ELSE a.attachable_id END AS email_id,
14
15
  CASE k.chunkable_type WHEN 'email_thread' THEN k.chunkable_id
15
- ELSE (SELECT email_thread_id FROM emails WHERE id = a.attachable_id) END AS thread_id
16
+ ELSE (SELECT email_thread_id FROM emails
17
+ WHERE id = CASE k.chunkable_type WHEN 'email_enrichment' THEN k.chunkable_id ELSE a.attachable_id END) END AS thread_id
16
18
  FROM chunks k LEFT JOIN attachments a ON k.chunkable_type = 'attachment' AND a.id = k.chunkable_id
17
19
  AND a.attachable_type = 'email'
18
- WHERE k.chunkable_type = 'email_thread' OR a.id IS NOT NULL) p`;
20
+ WHERE k.chunkable_type IN ('email_thread', 'email_enrichment') OR a.id IS NOT NULL) p`;
19
21
  /** A thread's live emails, oldest first, each as what it adds: its subject, then its own text. */
20
22
  const threadText = (database, threadId) => {
21
23
  const rows = database
@@ -5,6 +5,7 @@ import { mailActivity, threadEmailIds } from "./email-activity.js";
5
5
  import { chunkAttachments, drainEmailIndex, dropAttachmentChunks, MAIL_PIECES, queueThreads, threadPieces, titleOf, } from "./email-index.js";
6
6
  import { backfillSentAt, folderEmails, forgetLocations, locate, partialMail, setLocations, storedWhole, } from "./email-locations.js";
7
7
  import { markEmailsDeleted, markEmailsRestored, recountEmailThread as recount, setEmailFlags } from "./email-state.js";
8
+ import { EMAIL_ENRICHMENT, enrichmentText } from "./enrichments.js";
8
9
  import { bool, flag, fromJson, int, page, str, toJson } from "./events.js";
9
10
  import { folded } from "./folded.js";
10
11
  import { ensurePerson } from "./identities.js";
@@ -586,6 +587,10 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
586
587
  const piece = threads.get(owner)?.[Number(row.position)];
587
588
  return piece && piece.hash === row.hash ? [{ hash: piece.hash, text: piece.text }] : [];
588
589
  }
590
+ if (type === EMAIL_ENRICHMENT) {
591
+ const text = enrichmentText(database, type, owner);
592
+ return text === undefined ? [] : [{ hash: String(row.hash), text }];
593
+ }
589
594
  const text = str(file.get(owner)?.text);
590
595
  return text == null ? [] : [{ hash: String(row.hash), text: text.slice(Number(row.start), Number(row.end)) }];
591
596
  });
@@ -0,0 +1,60 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import type { StoreContext } from "./open.js";
3
+ export type EnrichmentSubject = "document" | "note" | "email";
4
+ export declare const ENRICHMENT_SUBJECTS: readonly EnrichmentSubject[];
5
+ /**
6
+ * A note's or document's enrichment chunk sits at this position under the record's own chunks, so a hit by meaning
7
+ * still names the record. Its offsets are 0: its text is the enrichment's, never a stretch of the record's.
8
+ */
9
+ export declare const ENRICHMENT_POSITION = 1000000;
10
+ /** An email's enrichment chunk: thread pieces are cut again by position, so a reserved position there would break. */
11
+ export declare const EMAIL_ENRICHMENT = "email_enrichment";
12
+ export interface EnrichmentCandidate {
13
+ type: EnrichmentSubject;
14
+ id: number;
15
+ /** The record's indexed text, title first: what the hash covers. */
16
+ text: string;
17
+ at: number | null;
18
+ hash: string;
19
+ }
20
+ export interface SavedEnrichment {
21
+ type: EnrichmentSubject;
22
+ id: number;
23
+ hash: string;
24
+ provider: string;
25
+ model: string;
26
+ text: string;
27
+ tokens: number;
28
+ }
29
+ export interface EnrichmentNarrowing {
30
+ types?: readonly EnrichmentSubject[];
31
+ only?: readonly {
32
+ type: EnrichmentSubject;
33
+ id: number;
34
+ }[];
35
+ }
36
+ export interface EnrichmentCounts {
37
+ /** Live records search reads: documents, notes and emails. */
38
+ records: number;
39
+ /** Of those, the ones whose current text has an enrichment. */
40
+ enriched: number;
41
+ /** Characters of the records still to enrich, for a cost estimate. */
42
+ pendingChars: number;
43
+ pendingByType: Record<EnrichmentSubject, number>;
44
+ }
45
+ export interface EnrichmentStore {
46
+ /** Up to `limit` live records with no enrichment of their current text, by type then id; `only` narrows them. */
47
+ pending(limit: number, narrow?: EnrichmentNarrowing): Promise<EnrichmentCandidate[]>;
48
+ counts(): Promise<EnrichmentCounts>;
49
+ /** Keeps each text and queues its record, so the next index drain adds it to the record's stems and chunks. */
50
+ save(rows: readonly SavedEnrichment[]): Promise<void>;
51
+ /** Deletes every enrichment and queues its record: the drain then indexes the record's own text alone. */
52
+ clear(): Promise<number>;
53
+ }
54
+ /** The hash an enrichment is kept under: of the text the corpus indexes, so an edit makes it stale. */
55
+ export declare const enrichmentHash: (title: string | null, body: string) => string;
56
+ /** The record's enrichment text when it was written for its current text; a stale one is never indexed. */
57
+ export declare const currentEnrichment: (database: CacheDatabase, type: string, id: number, indexed: string) => string | undefined;
58
+ /** An enrichment's text by its chunk's owner, for the embed pass. */
59
+ export declare const enrichmentText: (database: CacheDatabase, type: string, id: number) => string | undefined;
60
+ export declare const enrichmentsOver: ({ database, now }: StoreContext) => EnrichmentStore;