@agency-lang/memento 0.0.0-stage → 0.1.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 (64) hide show
  1. package/README.md +64 -2
  2. package/dist/agency/embed.d.ts +22 -0
  3. package/dist/agency/embed.js +458 -0
  4. package/dist/agencyApi.d.ts +98 -0
  5. package/dist/agencyApi.js +237 -0
  6. package/dist/embed.d.ts +45 -0
  7. package/dist/embed.js +77 -0
  8. package/dist/engine/files/engine.d.ts +85 -0
  9. package/dist/engine/files/engine.js +284 -0
  10. package/dist/engine/files/lock.d.ts +18 -0
  11. package/dist/engine/files/lock.js +247 -0
  12. package/dist/engine/files/manifest.d.ts +43 -0
  13. package/dist/engine/files/manifest.js +111 -0
  14. package/dist/engine/files/safe-delete.d.ts +19 -0
  15. package/dist/engine/files/safe-delete.js +79 -0
  16. package/dist/engine/files/segments.d.ts +17 -0
  17. package/dist/engine/files/segments.js +128 -0
  18. package/dist/engine/memory/engine.d.ts +27 -0
  19. package/dist/engine/memory/engine.js +87 -0
  20. package/dist/engine/open.d.ts +7 -0
  21. package/dist/engine/open.js +28 -0
  22. package/dist/engine/shared/filter.d.ts +7 -0
  23. package/dist/engine/shared/filter.js +72 -0
  24. package/dist/engine/shared/keyword.d.ts +27 -0
  25. package/dist/engine/shared/keyword.js +92 -0
  26. package/dist/engine/shared/settings.d.ts +5 -0
  27. package/dist/engine/shared/settings.js +9 -0
  28. package/dist/engine/shared/state.d.ts +58 -0
  29. package/dist/engine/shared/state.js +275 -0
  30. package/dist/engine/shared/tokens.d.ts +15 -0
  31. package/dist/engine/shared/tokens.js +23 -0
  32. package/dist/engine/shared/vectors.d.ts +36 -0
  33. package/dist/engine/shared/vectors.js +70 -0
  34. package/dist/engine/types.d.ts +121 -0
  35. package/dist/engine/types.js +1 -0
  36. package/dist/files.d.ts +75 -0
  37. package/dist/files.js +190 -0
  38. package/dist/filter.d.ts +3 -0
  39. package/dist/filter.js +80 -0
  40. package/dist/fusion.d.ts +24 -0
  41. package/dist/fusion.js +26 -0
  42. package/dist/ids.d.ts +2 -0
  43. package/dist/ids.js +19 -0
  44. package/dist/index.d.ts +4 -0
  45. package/dist/index.js +3 -0
  46. package/dist/local.d.ts +36 -0
  47. package/dist/local.js +75 -0
  48. package/dist/memento.d.ts +151 -0
  49. package/dist/memento.js +470 -0
  50. package/dist/query.d.ts +50 -0
  51. package/dist/query.js +138 -0
  52. package/dist/rows.d.ts +17 -0
  53. package/dist/rows.js +90 -0
  54. package/dist/stem.d.ts +2 -0
  55. package/dist/stem.js +121 -0
  56. package/dist/types.d.ts +246 -0
  57. package/dist/types.js +3 -0
  58. package/dist/vectors.d.ts +2 -0
  59. package/dist/vectors.js +10 -0
  60. package/dist/windows.d.ts +44 -0
  61. package/dist/windows.js +77 -0
  62. package/index.agency +268 -0
  63. package/index.js +1803 -0
  64. package/package.json +55 -4
package/dist/query.js ADDED
@@ -0,0 +1,138 @@
1
+ // The words of a question, and the excerpt of a document to show for them.
2
+ // Nothing here knows an engine; each engine turns the words into its own query.
3
+ import { stem } from "./stem.js";
4
+ const STOP = new Set("a an and are as at be by for from has have in is it its of on or that the to was were will with this which who whom what when where why how do does did not no can could should would may might shall if then than there their they them".split(" "));
5
+ /**
6
+ * Words of letters, digits and combining marks. The same rule for questions
7
+ * and for excerpt text. unicode61 splits some words that this keeps whole,
8
+ * such as Arabic with harakat; queryWords sends a folded form for those.
9
+ */
10
+ const WORD = /[\p{L}\p{N}\p{M}]+/gu;
11
+ /** Questions keep at most this many distinct words, each sent in up to two forms. */
12
+ const MAX_QUERY_TERMS = 64;
13
+ /** Shorter words are dropped from questions. */
14
+ const MIN_TERM_LENGTH = 2;
15
+ /** How long an excerpt is, before widening to whitespace. */
16
+ export const EXCERPT_CHARS = 300;
17
+ /** How far an excerpt may widen at each end to reach whitespace. */
18
+ export const WIDEN_CHARS = 40;
19
+ /**
20
+ * Lowercases a word and removes every combining mark, then recomposes what is
21
+ * left, so Hangul stays in syllables. It folds more than unicode61 does, which
22
+ * keeps accents on non-Latin letters and on letters with two accents. Folds
23
+ * one word at a time, so offsets in the original text stay valid.
24
+ */
25
+ export function foldWord(word) {
26
+ return word.normalize("NFD").replace(/\p{M}/gu, "").normalize("NFC").toLowerCase();
27
+ }
28
+ /**
29
+ * The distinct content words of a question, in order, each in two forms: the
30
+ * word lowercased, and the word folded by foldWord. An engine's tokenizer
31
+ * folds the first form the way it indexed the documents, which finds "Сергей"
32
+ * and "Nguyễn" as written. The folded form finds the same word written without its marks,
33
+ * such as "שלום" for "שָׁלוֹם". The stop list and MIN_TERM_LENGTH check the
34
+ * folded form, so "thé" is dropped like "the".
35
+ */
36
+ export function queryWords(text, maxTerms = MAX_QUERY_TERMS) {
37
+ const words = new Set();
38
+ const forms = new Set();
39
+ for (const word of text.match(WORD) ?? []) {
40
+ const folded = foldWord(word);
41
+ if (folded.length < MIN_TERM_LENGTH || STOP.has(folded)) {
42
+ continue;
43
+ }
44
+ words.add(folded);
45
+ forms.add(word.toLowerCase());
46
+ forms.add(folded);
47
+ if (words.size >= maxTerms) {
48
+ break;
49
+ }
50
+ }
51
+ return [...forms];
52
+ }
53
+ /**
54
+ * Every word of a text as its stem, with where it starts: the word by WORD,
55
+ * folded by foldWord, stemmed by stem. The keyword index and the excerpt both
56
+ * use this, so what the index matched is what the excerpt highlights.
57
+ */
58
+ export function stemsOf(text) {
59
+ // A word of combining marks alone, such as a variation selector after an emoji, folds to nothing and is not a word.
60
+ return [...text.matchAll(WORD)]
61
+ .map((match) => ({ stem: stem(foldWord(match[0])), start: match.index }))
62
+ .filter((match) => match.stem !== "");
63
+ }
64
+ /**
65
+ * The window of `text` holding the most distinct query terms, matched by
66
+ * Porter stem, the way the keyword index matched them. Ties go to the earliest window.
67
+ * Undefined when no word in the text matches, so the caller can show
68
+ * another part of the document.
69
+ */
70
+ export function excerpt(text, terms) {
71
+ const matches = findMatches(text, terms);
72
+ if (matches.length === 0) {
73
+ return undefined;
74
+ }
75
+ return excerptAt(text, bestWindowStart(matches));
76
+ }
77
+ /** The excerpt of EXCERPT_CHARS starting at `from`, widened to whitespace at each end. */
78
+ export function excerptAt(text, from) {
79
+ // The end comes from the window's own start, so widening the start never pushes a counted match out.
80
+ const start = widenStart(text, from);
81
+ const end = widenEnd(text, Math.min(text.length, from + EXCERPT_CHARS));
82
+ return { excerpt: text.slice(start, end), position: { start, end, line: lineOf(text, start) } };
83
+ }
84
+ function findMatches(text, terms) {
85
+ const stems = new Set(terms.map((term) => stem(foldWord(term))));
86
+ return stemsOf(text).filter((match) => stems.has(match.stem));
87
+ }
88
+ /**
89
+ * Slides a window of EXCERPT_CHARS over the matches in one pass. Starting at
90
+ * 0 or at a match covers every best window, since a window can move right to
91
+ * its first match without losing one. Ties go to the earliest window.
92
+ */
93
+ export function bestWindowStart(matches) {
94
+ // A null prototype, so a stem such as "constructor" starts at zero.
95
+ const counts = Object.create(null);
96
+ let distinct = 0;
97
+ let left = 0;
98
+ let right = 0;
99
+ let best = { from: 0, count: -1 };
100
+ for (const from of [0, ...matches.map((m) => m.start)]) {
101
+ while (right < matches.length && matches[right].start < from + EXCERPT_CHARS) {
102
+ const added = matches[right].stem;
103
+ counts[added] = (counts[added] ?? 0) + 1;
104
+ distinct += counts[added] === 1 ? 1 : 0;
105
+ right++;
106
+ }
107
+ while (left < right && matches[left].start < from) {
108
+ const removed = matches[left].stem;
109
+ counts[removed] = counts[removed] - 1;
110
+ distinct -= counts[removed] === 0 ? 1 : 0;
111
+ left++;
112
+ }
113
+ if (distinct > best.count) {
114
+ best = { from, count: distinct };
115
+ }
116
+ }
117
+ return best.from;
118
+ }
119
+ function widenStart(text, start) {
120
+ const limit = Math.max(0, start - WIDEN_CHARS);
121
+ let widened = start;
122
+ while (widened > limit && !/\s/.test(text[widened - 1])) {
123
+ widened--;
124
+ }
125
+ return widened;
126
+ }
127
+ function widenEnd(text, end) {
128
+ const limit = Math.min(text.length, end + WIDEN_CHARS);
129
+ let widened = end;
130
+ while (widened < limit && !/\s/.test(text[widened])) {
131
+ widened++;
132
+ }
133
+ return widened;
134
+ }
135
+ /** 1-based line of an offset; `\r\n` counts as one line break. */
136
+ function lineOf(text, offset) {
137
+ return (text.slice(0, offset).match(/\r\n|\r|\n/g) ?? []).length + 1;
138
+ }
package/dist/rows.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import type { StoredDocument } from "./engine/types.ts";
2
+ import type { Excerpt } from "./query.ts";
3
+ import type { Document, Hit } from "./types.ts";
4
+ /**
5
+ * The document as stored: batch meta under its own, and the file it came
6
+ * from. The title and text are made well-formed first, replacing a lone
7
+ * surrogate with U+FFFD, so that what is compared against the stored
8
+ * document and cut into windows is what every store holds, and a document
9
+ * with a lone surrogate is not embedded again on every add.
10
+ */
11
+ export declare function documentToStored(doc: Document, batchMeta?: Record<string, unknown>, sourcePath?: string): StoredDocument;
12
+ /** The public document: everything but where it came from. */
13
+ export declare function storedToDocument(stored: StoredDocument): Document;
14
+ /** A hit from a stored document, its score, and the excerpt the caller chose to show. */
15
+ export declare function toHit(stored: StoredDocument, score: number, shown: Excerpt): Hit;
16
+ /** Rejects documents the store cannot hold, naming the first bad one by its index. */
17
+ export declare function validateDocuments(documents: Document[], batchMeta?: Record<string, unknown>): void;
package/dist/rows.js ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The document as stored: batch meta under its own, and the file it came
3
+ * from. The title and text are made well-formed first, replacing a lone
4
+ * surrogate with U+FFFD, so that what is compared against the stored
5
+ * document and cut into windows is what every store holds, and a document
6
+ * with a lone surrogate is not embedded again on every add.
7
+ */
8
+ export function documentToStored(doc, batchMeta = {}, sourcePath) {
9
+ const stored = { ...doc, title: doc.title.toWellFormed(), text: doc.text.toWellFormed(), meta: { ...batchMeta, ...doc.meta } };
10
+ if (sourcePath !== undefined) {
11
+ stored.sourcePath = sourcePath;
12
+ }
13
+ return stored;
14
+ }
15
+ /** The public document: everything but where it came from. */
16
+ export function storedToDocument(stored) {
17
+ const { sourcePath, ...doc } = stored;
18
+ return doc;
19
+ }
20
+ /** A hit from a stored document, its score, and the excerpt the caller chose to show. */
21
+ export function toHit(stored, score, shown) {
22
+ return { document: storedToDocument(stored), score, ...shown };
23
+ }
24
+ /** Rejects documents the store cannot hold, naming the first bad one by its index. */
25
+ export function validateDocuments(documents, batchMeta) {
26
+ if (batchMeta !== undefined) {
27
+ assertPlainJson(batchMeta, "the batch meta");
28
+ }
29
+ documents.forEach((doc, index) => {
30
+ if (doc.id === "") {
31
+ throw new Error(`document ${index}: id is empty`);
32
+ }
33
+ // A lone surrogate would be stored as U+FFFD, so two different ids could land on one document.
34
+ if (!doc.id.isWellFormed()) {
35
+ throw new Error(`document ${index}: id is not well-formed UTF-16`);
36
+ }
37
+ if (doc.createdAt !== undefined && Number.isNaN(doc.createdAt.getTime())) {
38
+ throw new Error(`document ${index} ("${doc.id}"): createdAt is an invalid Date`);
39
+ }
40
+ if (doc.meta !== undefined) {
41
+ assertPlainJson(doc.meta, `document ${index} ("${doc.id}"): meta`);
42
+ }
43
+ });
44
+ }
45
+ /**
46
+ * Meta must be plain JSON: strings, finite numbers, booleans, null, arrays,
47
+ * and objects whose prototype is Object.prototype or null, as parsed JSON
48
+ * and rows from a database driver can be. A Date, undefined, NaN, bigint or an
49
+ * object that refers back to itself is rejected, naming the key that holds
50
+ * it. `parents` holds the objects above `value`, to find such cycles.
51
+ *
52
+ * Three things JSON changes without an error pass this check: a hole in an
53
+ * array is stored as null, an extra property on an array is dropped, and a
54
+ * symbol key is dropped.
55
+ */
56
+ function assertPlainJson(value, where, parents = []) {
57
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
58
+ return;
59
+ }
60
+ if (typeof value === "number" && Number.isFinite(value)) {
61
+ return;
62
+ }
63
+ if (typeof value === "object" && parents.includes(value)) {
64
+ throw new Error(`${where} refers back to itself`);
65
+ }
66
+ if (Array.isArray(value)) {
67
+ value.forEach((item, i) => assertPlainJson(item, `${where}[${i}]`, [...parents, value]));
68
+ return;
69
+ }
70
+ if (isPlainObject(value)) {
71
+ for (const [key, item] of Object.entries(value)) {
72
+ assertPlainJson(item, `${where}.${key}`, [...parents, value]);
73
+ }
74
+ return;
75
+ }
76
+ throw new Error(`${where} must be plain JSON: a string, finite number, boolean, null, array or plain object; got ${describe(value)}`);
77
+ }
78
+ function isPlainObject(value) {
79
+ if (typeof value !== "object" || value === null) {
80
+ return false;
81
+ }
82
+ const prototype = Object.getPrototypeOf(value);
83
+ return prototype === Object.prototype || prototype === null;
84
+ }
85
+ function describe(value) {
86
+ if (typeof value === "object" && value !== null) {
87
+ return value.constructor?.name ?? "object";
88
+ }
89
+ return typeof value === "number" ? String(value) : typeof value;
90
+ }
package/dist/stem.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** The Porter stem of one lowercase word. */
2
+ export declare function stem(word: string): string;
package/dist/stem.js ADDED
@@ -0,0 +1,121 @@
1
+ // The Porter stemmer, as published by Martin Porter, with two common
2
+ // departures: "bli" becomes "ble" and "logi" becomes "log". The keyword index
3
+ // and the excerpt both stem with it, so what the index matched is what the
4
+ // excerpt highlights. Public domain algorithm.
5
+ /** Words shorter than this are not stemmed. */
6
+ const MIN_STEM_LENGTH = 3;
7
+ /** Longer tokens pass through unstemmed. */
8
+ const MAX_STEM_LENGTH = 64;
9
+ const STEP2 = {
10
+ ational: "ate",
11
+ tional: "tion",
12
+ enci: "ence",
13
+ anci: "ance",
14
+ izer: "ize",
15
+ bli: "ble",
16
+ alli: "al",
17
+ entli: "ent",
18
+ eli: "e",
19
+ ousli: "ous",
20
+ ization: "ize",
21
+ ation: "ate",
22
+ ator: "ate",
23
+ alism: "al",
24
+ iveness: "ive",
25
+ fulness: "ful",
26
+ ousness: "ous",
27
+ aliti: "al",
28
+ iviti: "ive",
29
+ biliti: "ble",
30
+ logi: "log",
31
+ };
32
+ const STEP3 = {
33
+ icate: "ic",
34
+ ative: "",
35
+ alize: "al",
36
+ iciti: "ic",
37
+ ical: "ic",
38
+ ful: "",
39
+ ness: "",
40
+ };
41
+ const CONSONANT = "[^aeiou]";
42
+ const VOWEL = "[aeiouy]";
43
+ const CONSONANTS = `${CONSONANT}[^aeiouy]*`;
44
+ const VOWELS = `${VOWEL}[aeiou]*`;
45
+ /** measure > 0 */
46
+ const M_GT_0 = new RegExp(`^(${CONSONANTS})?${VOWELS}${CONSONANTS}`);
47
+ /** measure == 1 */
48
+ const M_EQ_1 = new RegExp(`^(${CONSONANTS})?${VOWELS}${CONSONANTS}(${VOWELS})?$`);
49
+ /** measure > 1 */
50
+ const M_GT_1 = new RegExp(`^(${CONSONANTS})?${VOWELS}${CONSONANTS}${VOWELS}${CONSONANTS}`);
51
+ /** the stem contains a vowel */
52
+ const HAS_VOWEL = new RegExp(`^(${CONSONANTS})?${VOWEL}`);
53
+ /** ends consonant-vowel-consonant, where the last is not w, x or y */
54
+ const ENDS_CVC = new RegExp(`^${CONSONANTS}${VOWEL}[^aeiouwxy]$`);
55
+ const DOUBLE_CONSONANT = /([^aeiouylsz])\1$/;
56
+ /** The Porter stem of one lowercase word. */
57
+ export function stem(word) {
58
+ if (word.length < MIN_STEM_LENGTH || word.length > MAX_STEM_LENGTH) {
59
+ return word;
60
+ }
61
+ // A leading y is a consonant; upper-casing it keeps the vowel patterns off it.
62
+ const leadingY = word.startsWith("y");
63
+ const steps = [step1a, step1b, step1c, step2, step3, step4, step5];
64
+ const stemmed = steps.reduce((w, step) => step(w), leadingY ? "Y" + word.slice(1) : word);
65
+ return leadingY ? "y" + stemmed.slice(1) : stemmed;
66
+ }
67
+ function step1a(w) {
68
+ const sses = /^(.+?)(ss|i)es$/.exec(w);
69
+ if (sses) {
70
+ return sses[1] + sses[2];
71
+ }
72
+ const plural = /^(.+?)([^s])s$/.exec(w);
73
+ return plural ? plural[1] + plural[2] : w;
74
+ }
75
+ function step1b(w) {
76
+ const eed = /^(.+?)eed$/.exec(w);
77
+ if (eed) {
78
+ return M_GT_0.test(eed[1]) ? w.slice(0, -1) : w;
79
+ }
80
+ const edIng = /^(.+?)(ed|ing)$/.exec(w);
81
+ if (!edIng || !HAS_VOWEL.test(edIng[1])) {
82
+ return w;
83
+ }
84
+ const base = edIng[1];
85
+ if (/(at|bl|iz)$/.test(base)) {
86
+ return base + "e";
87
+ }
88
+ if (DOUBLE_CONSONANT.test(base)) {
89
+ return base.slice(0, -1);
90
+ }
91
+ return ENDS_CVC.test(base) ? base + "e" : base;
92
+ }
93
+ function step1c(w) {
94
+ const y = /^(.+?)y$/.exec(w);
95
+ return y && HAS_VOWEL.test(y[1]) ? y[1] + "i" : w;
96
+ }
97
+ function step2(w) {
98
+ const match = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/.exec(w);
99
+ return match && M_GT_0.test(match[1]) ? match[1] + STEP2[match[2]] : w;
100
+ }
101
+ function step3(w) {
102
+ const match = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/.exec(w);
103
+ return match && M_GT_0.test(match[1]) ? match[1] + STEP3[match[2]] : w;
104
+ }
105
+ function step4(w) {
106
+ const suffix = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/.exec(w);
107
+ if (suffix) {
108
+ return M_GT_1.test(suffix[1]) ? suffix[1] : w;
109
+ }
110
+ const ion = /^(.+?)(s|t)(ion)$/.exec(w);
111
+ if (ion) {
112
+ const base = ion[1] + ion[2];
113
+ return M_GT_1.test(base) ? base : w;
114
+ }
115
+ return w;
116
+ }
117
+ function step5(w) {
118
+ const e = /^(.+?)e$/.exec(w);
119
+ const withoutE = e && (M_GT_1.test(e[1]) || (M_EQ_1.test(e[1]) && !ENDS_CVC.test(e[1]))) ? e[1] : w;
120
+ return /ll$/.test(withoutE) && M_GT_1.test(withoutE) ? withoutE.slice(0, -1) : withoutE;
121
+ }
@@ -0,0 +1,246 @@
1
+ /** One piece of text in the store: a code section, an email, a note, a page. */
2
+ export type Document = {
3
+ /** Stable and unique within the store. Adding a document with an existing id replaces it. */
4
+ id: string;
5
+ title: string;
6
+ /** A lone surrogate is stored as U+FFFD, and `get` returns it that way. */
7
+ text: string;
8
+ createdAt?: Date;
9
+ /**
10
+ * Anything worth filtering on later: sender, path, year, document type, tags.
11
+ * Must be plain JSON: strings, numbers, booleans, null, arrays and objects of those.
12
+ * `get` returns `{}` for a document added without meta.
13
+ */
14
+ meta?: Record<string, unknown>;
15
+ };
16
+ /**
17
+ * Where the store lives. A store holds everything: the documents, the keyword
18
+ * index, the embeddings and the model-written questions.
19
+ *
20
+ * - "memory": everything in RAM. Fastest; gone when the process exits, so every
21
+ * open starts with an empty store and documents must be added again.
22
+ * - "files": everything on disk under `path`. Loading is slow once; opening
23
+ * again is instant.
24
+ */
25
+ export type Storage = MemoryStorage | FileStorage;
26
+ export type MemoryStorage = {
27
+ type: "memory";
28
+ };
29
+ export type FileStorage = {
30
+ type: "files";
31
+ /**
32
+ * A directory. Created if it does not exist. A leading `~` or `~/` means the
33
+ * home directory; a relative path resolves against the current directory.
34
+ */
35
+ path: string;
36
+ };
37
+ /**
38
+ * Which models an open uses. Each is "provider:model", e.g.
39
+ * "openai:text-embedding-3-small", "openrouter:z-ai/glm-5.3-flash" or
40
+ * "llama-cpp:~/models/qwen3.gguf". The name splits at its first colon, so a
41
+ * model name may hold one, as in "ollama:qwen3:8b". Memento calls the model
42
+ * through Agency, which reads the provider's API key from the environment.
43
+ */
44
+ export type Models = {
45
+ /**
46
+ * Turns text into vectors for meaning-based search. Used at load time and at
47
+ * question time. A store remembers it, and opening the store with a
48
+ * different embedding model rejects. A store that already holds documents
49
+ * without vectors rejects any embedding model: rebuild it.
50
+ */
51
+ embedding?: string;
52
+ /**
53
+ * Lists the topics a question needs, writes the answer, and writes
54
+ * questions per document when `enrich` is on. The store does not record
55
+ * it, so each open names the chat model it wants.
56
+ */
57
+ chat?: string;
58
+ };
59
+ /** The models a store records: the embedding model that made its vectors. */
60
+ export type StoreModels = Pick<Models, "embedding">;
61
+ /** What a store records about itself. `Memento.settings` reads it without opening the store. */
62
+ export type StoreSettings = {
63
+ models: StoreModels;
64
+ /** Whether the store was opened with `local: true`, which it remembers. */
65
+ local: boolean;
66
+ };
67
+ export type OpenOptions = {
68
+ models?: Models;
69
+ /**
70
+ * When true, every model must run on this machine: its provider must be
71
+ * `mlx` or `llama-cpp`, and an `mlx` model's server must be on this
72
+ * machine. Opening with any other model rejects, and so does opening a
73
+ * store whose vectors were made by one. Set it for email, notes and
74
+ * health data. A files store remembers it: once opened with
75
+ * `local: true`, it stays local, and every later open and every model
76
+ * call is checked even when the open left `local` out.
77
+ */
78
+ local?: boolean;
79
+ };
80
+ export type AddOptions = {
81
+ /** Attached to every document in this batch, e.g. { source: "gmail", year: 2024 }. A document's own meta wins on a clash. */
82
+ meta?: Record<string, unknown>;
83
+ /**
84
+ * Have the chat model write the questions each document answers and index
85
+ * them too. One model call per document: about $0.30 per 1,000 documents
86
+ * with GLM, minutes per 1,000 with a local model. Bought +2.8 points on
87
+ * stpaul. Default false.
88
+ */
89
+ enrich?: boolean;
90
+ /**
91
+ * Called as the load goes on; useful for a long load. `add` counts
92
+ * documents and `addFiles` counts files, skipped files included. The last
93
+ * call is `(total, total)`.
94
+ */
95
+ onProgress?: (done: number, total: number) => void;
96
+ };
97
+ export type AddFilesOptions = AddOptions & {
98
+ /** How to turn one file into documents. Default: one document per file, title from the file name, createdAt from mtime. */
99
+ parse?: (path: string, text: string) => Document[];
100
+ /**
101
+ * Remove the documents of every file the store tracks that does not match
102
+ * this call's globs. Default false: a deleted file's documents stay until
103
+ * `remove` or a call with `prune: true`. Rejects, removing nothing, when
104
+ * the globs match no files, so a typo cannot empty the store.
105
+ */
106
+ prune?: boolean;
107
+ /** Re-index every matching file, changed or not. Use it after changing `parse`. Default false. */
108
+ force?: boolean;
109
+ };
110
+ /** What `addFiles` did. */
111
+ export type AddFilesResult = {
112
+ /** Files that matched the globs. */
113
+ files: number;
114
+ /** Files unchanged since the last load, so not read again. */
115
+ skipped: number;
116
+ /** Files skipped because they hold binary data. */
117
+ nonText: number;
118
+ /**
119
+ * Files skipped because the file system refused them, such as a dangling
120
+ * symlink or a file without read permission. They are tried again on the
121
+ * next call, and any documents they gave before stay in the store.
122
+ */
123
+ unreadable: number;
124
+ /** Documents written by this call. */
125
+ documents: number;
126
+ };
127
+ /**
128
+ * Narrows a search before ranking. A filter is either one condition, or
129
+ * and / or / not over other filters, nested as deep as needed:
130
+ *
131
+ * { and: [{ date: { after: y2009, before: y2011 } },
132
+ * { or: [{ meta: { sender: "uchicago.edu" } }, { meta: { list: "cpp-class" } }] }] }
133
+ *
134
+ * `not` matches everything the inner filter does not, including documents
135
+ * that lack the field. An unknown key rejects.
136
+ */
137
+ export type Filter = Condition | {
138
+ and: Filter[];
139
+ } | {
140
+ or: Filter[];
141
+ } | {
142
+ not: Filter;
143
+ };
144
+ /** Every field given must hold. */
145
+ export type Condition = {
146
+ /** A document without `createdAt` never matches a date condition. */
147
+ date?: DateRange;
148
+ /**
149
+ * Each key must equal the document's meta value, e.g. { sender: "uchicago.edu" }.
150
+ * Values are strings, numbers, booleans or null. Booleans compare as 1 and 0,
151
+ * so `{ flag: true }` also matches a stored 1. `null` means the key is
152
+ * missing or null. Arrays and objects are not supported yet.
153
+ */
154
+ meta?: Record<string, unknown>;
155
+ /** Only these document ids. An empty list matches nothing. */
156
+ ids?: string[];
157
+ lengthChars?: LengthRange;
158
+ };
159
+ export type DateRange = {
160
+ /** Only documents on or after this moment. */
161
+ after?: Date;
162
+ /**
163
+ * Only documents on or before this moment. `new Date("2011-01-01")` is
164
+ * midnight UTC on that day, and a document at exactly that moment matches.
165
+ */
166
+ before?: Date;
167
+ };
168
+ /** Bounds on `text.length`, both inclusive. A range with `min > max` matches nothing. */
169
+ export type LengthRange = {
170
+ min?: number;
171
+ max?: number;
172
+ };
173
+ export type SearchOptions = {
174
+ filter?: Filter;
175
+ /**
176
+ * How many documents to return. Default 20. With a blank query and a
177
+ * filter, `search` returns the filtered documents newest first.
178
+ */
179
+ limit?: number;
180
+ /**
181
+ * Search by meaning as well as by keyword. When unset, Memento searches
182
+ * by meaning if the store has an embedding model. Passing `true` on a
183
+ * store without one rejects, as does passing it on a store opened without
184
+ * its embedding model. Keyword search alone is fast, but found 51% of the
185
+ * right documents on stpaul against 63% for both together.
186
+ */
187
+ useEmbeddings?: boolean;
188
+ /**
189
+ * Let the chat model list the separate topics the question needs and search
190
+ * each. The best method on stpaul (+7 points) but several seconds per
191
+ * question. When unset, `ask` uses it and `search` does not. Passing
192
+ * `true` on a store without a chat model rejects. `ask` always uses the chat model to write
193
+ * the answer, whatever this says.
194
+ */
195
+ useLLM?: boolean;
196
+ };
197
+ export type AskOptions = SearchOptions & {
198
+ /** How many documents the answer is written from. Default 8. */
199
+ numRefDocuments?: number;
200
+ };
201
+ /** Where an excerpt sits in `document.text`. */
202
+ export type Position = {
203
+ /** Character offsets, end exclusive. */
204
+ start: number;
205
+ end: number;
206
+ /** 1-based line of `start`. */
207
+ line?: number;
208
+ };
209
+ export type Hit = {
210
+ document: Document;
211
+ /** Higher is more relevant. Comparable within one search, not across searches. */
212
+ score: number;
213
+ /** The part of the document that matched, for display. */
214
+ excerpt: string;
215
+ /** Where the excerpt sits in `document.text`. Absent when the search method does not know where it matched. */
216
+ position?: Position;
217
+ };
218
+ export type Answer = {
219
+ /** Plain words, citing hits as [1], [2], ... in the order of `sources`. */
220
+ text: string;
221
+ sources: Hit[];
222
+ /** What the store did: the searches it ran, timings, the model calls. For debugging, not for display. */
223
+ trace: Record<string, unknown>;
224
+ };
225
+ export type Stats = {
226
+ documents: number;
227
+ /** How many files `addFiles` has loaded into the store. */
228
+ files: number;
229
+ /**
230
+ * Size of the store as kept. For a files store, the bytes of its segment
231
+ * files on disk; for a memory store, an estimate of what it holds.
232
+ */
233
+ bytes: number;
234
+ models: StoreModels;
235
+ /** How many documents have model-written questions. */
236
+ enriched: number;
237
+ /** Model usage since this connection opened. Not stored: a new open starts at zero. */
238
+ spent: Spent;
239
+ };
240
+ /** What one connection has spent on models. The store does not know what other connections paid. */
241
+ export type Spent = {
242
+ embeddingCalls: number;
243
+ embeddingTokens: number;
244
+ /** In US dollars, as the provider reported it through Agency. */
245
+ cost: number;
246
+ };
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ // The public types of Memento: a local store you load documents into, then
2
+ // ask questions of in plain words.
3
+ export {};
@@ -0,0 +1,2 @@
1
+ /** The vector scaled to length 1. A vector of zeros has no direction and rejects, as does an empty one. */
2
+ export declare function toUnitVector(values: number[]): Float32Array;
@@ -0,0 +1,10 @@
1
+ // Scaling a model's vector to unit length, so a search is a dot product.
2
+ // Encoding and the scan are the engine's.
3
+ /** The vector scaled to length 1. A vector of zeros has no direction and rejects, as does an empty one. */
4
+ export function toUnitVector(values) {
5
+ const length = Math.sqrt(values.reduce((sum, x) => sum + x * x, 0));
6
+ if (values.length === 0 || length === 0) {
7
+ throw new Error("the model returned a vector of zeros");
8
+ }
9
+ return new Float32Array(values.map((x) => x / length));
10
+ }
@@ -0,0 +1,44 @@
1
+ import type { Window } from "./engine/types.ts";
2
+ import { type Excerpt } from "./query.ts";
3
+ /** The most characters of text in one window. */
4
+ export declare const WINDOW_CHARS = 2000;
5
+ /** How many characters consecutive windows share. */
6
+ export declare const WINDOW_OVERLAP = 200;
7
+ /** A window ends at the last newline or sentence end after this share of its length, when there is one. */
8
+ export declare const WINDOW_CUT_FROM = 0.6;
9
+ /** The most characters of the title that go on top of a window. The text is bounded; the title is not. */
10
+ export declare const WINDOW_TITLE_CHARS = 300;
11
+ /** A window with the text the model sees: the title on top of the window's slice of the text. */
12
+ export type TextWindow = Window & {
13
+ text: string;
14
+ };
15
+ type Range = {
16
+ start: number;
17
+ end: number;
18
+ };
19
+ /** A document with no title and no text after trimming gets no windows; the model rejects an empty input. */
20
+ export declare function isBlank(doc: {
21
+ title: string;
22
+ text: string;
23
+ }): boolean;
24
+ /**
25
+ * A window whose text is blank is dropped, because the model rejects a blank
26
+ * input: a window that falls inside a run of whitespace, under a blank
27
+ * title. At least one window stays, because the document is not blank. The
28
+ * rest are numbered without it.
29
+ */
30
+ export declare function windowsOf(doc: {
31
+ title: string;
32
+ text: string;
33
+ }): TextWindow[];
34
+ /**
35
+ * Cuts a text into overlapping ranges of at most `maxChars`, each ending at
36
+ * the last newline or sentence end in its final part when there is one. A
37
+ * text that fits is one range; an empty text is one empty range.
38
+ */
39
+ export declare function splitText(text: string, maxChars: number, overlap: number): Range[];
40
+ /** The excerpt to show when no query word matched: the start of the document's best window. */
41
+ export declare function windowExcerpt(text: string, window: Window): Excerpt;
42
+ /** The window that is the whole text, for a document found by keyword alone. */
43
+ export declare function wholeText(text: string): Window;
44
+ export {};