@wirecat/cli-core 0.611.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 +27 -1
  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/meetings/mcp/index.d.ts +15 -15
  11. package/dist/models/anthropic.js +6 -0
  12. package/dist/models/index.d.ts +1 -1
  13. package/dist/models/openai.js +8 -1
  14. package/dist/models/types.d.ts +7 -0
  15. package/dist/services/enrichment-setting.d.ts +50 -0
  16. package/dist/services/enrichment-setting.js +84 -0
  17. package/dist/services/enrichment.d.ts +111 -0
  18. package/dist/services/enrichment.js +240 -0
  19. package/dist/services/index.d.ts +2 -0
  20. package/dist/services/index.js +2 -0
  21. package/dist/services/metadata.d.ts +1 -1
  22. package/dist/services/notes-search.d.ts +15 -1
  23. package/dist/services/notes-search.js +38 -2
  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 +2 -2
@@ -0,0 +1,50 @@
1
+ import * as v from "valibot";
2
+ export declare const ENRICHMENT_PROVIDERS: readonly ["openai", "anthropic"];
3
+ export type EnrichmentProvider = (typeof ENRICHMENT_PROVIDERS)[number];
4
+ declare const Setting: v.StrictObjectSchema<{
5
+ readonly provider: v.PicklistSchema<readonly ["openai", "anthropic"], undefined>;
6
+ readonly model: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 200, undefined>]>;
7
+ readonly base_url: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "use an HTTP/S endpoint without credentials, query or fragment">]>, undefined>;
8
+ /** When the owner agreed that records go to this provider and endpoint; the setting exists only with it. */
9
+ readonly consented_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, undefined>]>;
10
+ }, undefined>;
11
+ export type EnrichmentSetting = v.InferOutput<typeof Setting>;
12
+ export declare const enrichmentSettingPath: (env: NodeJS.ProcessEnv) => string;
13
+ /** The owner's choice, or `undefined` when enrichment is off: no section means off. */
14
+ export declare const readEnrichmentSetting: (env: NodeJS.ProcessEnv) => EnrichmentSetting | undefined;
15
+ export declare const writeEnrichmentSetting: (env: NodeJS.ProcessEnv, setting: EnrichmentSetting | undefined) => void;
16
+ export declare const enrichmentEndpoint: (setting: Pick<EnrichmentSetting, "provider" | "base_url">) => string;
17
+ export declare const isEnrichmentProvider: (value: string) => value is EnrichmentProvider;
18
+ /** What `show` estimates while enrichment is off and nothing is proposed: the measured model. */
19
+ export declare const DEFAULT_OFFER: {
20
+ readonly provider: "openai";
21
+ readonly model: "gpt-4o-mini";
22
+ };
23
+ /** The provider and model pairs offered, each with its price; another model is allowed, with no price. */
24
+ export declare const offeredModels: () => {
25
+ provider: string;
26
+ model: string;
27
+ default: boolean;
28
+ usd_per_million: {
29
+ input: number;
30
+ output: number;
31
+ };
32
+ }[];
33
+ export declare const enrichmentPrice: (provider: string, model: string, baseUrl?: string) => {
34
+ input: number;
35
+ output: number;
36
+ source: string;
37
+ } | undefined;
38
+ export interface EnrichmentEstimate {
39
+ records: number;
40
+ input_tokens: number;
41
+ output_tokens: number;
42
+ /** `null` for a model or endpoint with no known price. */
43
+ usd: number | null;
44
+ }
45
+ export declare const estimateEnrichment: (records: number, chars: number, setting?: Pick<EnrichmentSetting, "provider" | "model" | "base_url">) => EnrichmentEstimate;
46
+ export declare const costOf: (usage: {
47
+ input: number;
48
+ output: number;
49
+ }, setting: Pick<EnrichmentSetting, "provider" | "model" | "base_url">) => number | null;
50
+ export {};
@@ -0,0 +1,84 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import * as v from "valibot";
3
+ import { endpoint } from "../models/endpoint.js";
4
+ import { storePath } from "../store/path.js";
5
+ import { readSharedSection, sharedConfigPath, writeSharedSection } from "../store/shared-config.js";
6
+ const SECTION = "enrichment";
7
+ export const ENRICHMENT_PROVIDERS = ["openai", "anthropic"];
8
+ const DEFAULT_BASE_URLS = {
9
+ openai: "https://api.openai.com/v1",
10
+ anthropic: "https://api.anthropic.com",
11
+ };
12
+ const Setting = v.strictObject({
13
+ provider: v.picklist(ENRICHMENT_PROVIDERS),
14
+ model: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(200)),
15
+ base_url: v.optional(v.pipe(v.string(), v.check((value) => endpoint(value), "use an HTTP/S endpoint without credentials, query or fragment"))),
16
+ /** When the owner agreed that records go to this provider and endpoint; the setting exists only with it. */
17
+ consented_at: v.pipe(v.string(), v.isoTimestamp()),
18
+ });
19
+ export const enrichmentSettingPath = (env) => sharedConfigPath(storePath(env), env);
20
+ /** The owner's choice, or `undefined` when enrichment is off: no section means off. */
21
+ export const readEnrichmentSetting = (env) => {
22
+ const path = enrichmentSettingPath(env);
23
+ const section = readSharedSection(path, SECTION);
24
+ if (section === undefined || section === null)
25
+ return undefined;
26
+ const checked = v.safeParse(Setting, section);
27
+ if (!checked.success)
28
+ throw new CliError("configuration_error", `${path}: enrichment.${v.getDotPath(checked.issues[0]) ?? "settings"} is invalid — ${checked.issues[0].message}`);
29
+ return checked.output;
30
+ };
31
+ export const writeEnrichmentSetting = (env, setting) => writeSharedSection(enrichmentSettingPath(env), SECTION, setting === undefined ? undefined : v.parse(Setting, setting));
32
+ export const enrichmentEndpoint = (setting) => setting.base_url ?? DEFAULT_BASE_URLS[setting.provider];
33
+ export const isEnrichmentProvider = (value) => ENRICHMENT_PROVIDERS.includes(value);
34
+ /** USD per token, from the providers' price pages on 2026-11-08; a model not listed gets no price. */
35
+ const PRICES = {
36
+ "openai/gpt-4o-mini": {
37
+ input: 0.15e-6,
38
+ output: 0.6e-6,
39
+ source: "https://developers.openai.com/api/docs/pricing",
40
+ },
41
+ "anthropic/claude-haiku-5-5": {
42
+ input: 0.1e-6,
43
+ output: 0.5e-6,
44
+ source: "https://platform.claude.com/docs/en/about-claude/pricing",
45
+ },
46
+ };
47
+ /** What `show` estimates while enrichment is off and nothing is proposed: the measured model. */
48
+ export const DEFAULT_OFFER = { provider: "openai", model: "gpt-4o-mini" };
49
+ /** The provider and model pairs offered, each with its price; another model is allowed, with no price. */
50
+ export const offeredModels = () => Object.entries(PRICES).map(([key, price]) => {
51
+ const [provider, model] = key.split("/");
52
+ return {
53
+ provider,
54
+ model,
55
+ default: provider === DEFAULT_OFFER.provider && model === DEFAULT_OFFER.model,
56
+ usd_per_million: {
57
+ input: Math.round(price.input * 1e8) / 100,
58
+ output: Math.round(price.output * 1e8) / 100,
59
+ },
60
+ };
61
+ });
62
+ export const enrichmentPrice = (provider, model, baseUrl) => baseUrl === undefined ? PRICES[`${provider}/${model}`] : undefined;
63
+ /**
64
+ * Per record, measured with this prompt and gpt-4o-mini on 1,048 synthetic records of about 100 characters, 20 to a
65
+ * request (cli-testing write-time-enrichment, 2026-11-08): 66 input tokens, 41 of them the prompt's share, and 65
66
+ * output tokens.
67
+ */
68
+ const OUTPUT_TOKENS_PER_RECORD = 70;
69
+ const PROMPT_TOKENS_PER_RECORD = 40;
70
+ export const estimateEnrichment = (records, chars, setting) => {
71
+ const input = Math.ceil(chars / 4) + records * PROMPT_TOKENS_PER_RECORD;
72
+ const output = records * OUTPUT_TOKENS_PER_RECORD;
73
+ const price = setting && enrichmentPrice(setting.provider, setting.model, setting.base_url);
74
+ return {
75
+ records,
76
+ input_tokens: input,
77
+ output_tokens: output,
78
+ usd: price ? Math.round((input * price.input + output * price.output) * 1_000_000) / 1_000_000 : null,
79
+ };
80
+ };
81
+ export const costOf = (usage, setting) => {
82
+ const price = enrichmentPrice(setting.provider, setting.model, setting.base_url);
83
+ return price ? Math.round((usage.input * price.input + usage.output * price.output) * 1_000_000) / 1_000_000 : null;
84
+ };
@@ -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);
@@ -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.