@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
@@ -0,0 +1,121 @@
1
+ import type { FileStat } from "../files.ts";
2
+ import type { Document, Filter, StoreSettings } from "../types.ts";
3
+ export type Engine = {
4
+ /** "memory", "files", ... for stats and error messages. */
5
+ readonly kind: string;
6
+ /**
7
+ * Writes the settings of a new store and returns them. On an existing
8
+ * store, writes nothing and returns what is there. Atomic across
9
+ * processes: two programs creating the same store get the same result.
10
+ * Rejects a store written by another version of the engine's schema.
11
+ */
12
+ initialize(defaults: StoreSettings): Promise<StoreSettings>;
13
+ getSettings(): Promise<StoreSettings>;
14
+ /** Merges `patch` into the settings. */
15
+ setSettings(patch: Partial<StoreSettings>): Promise<void>;
16
+ /** In the order asked, once each; unknown ids are left out. */
17
+ getDocsById(ids: string[]): Promise<StoredDocument[]>;
18
+ /**
19
+ * The windows of each of `ids` that the store holds, with their vectors,
20
+ * in the order asked, once each; unknown ids are left out. A held document
21
+ * without windows is listed with an empty list. With getDocsById, this is
22
+ * enough to copy a store into another engine through `write`.
23
+ */
24
+ getWindows(ids: string[]): Promise<DocumentWindows[]>;
25
+ /** Documents in the store, for stats().documents. */
26
+ getDocumentCount(): Promise<number>;
27
+ /** Files addFiles has loaded, for stats().files. A file can give many documents, or none. */
28
+ getFileCount(): Promise<number>;
29
+ /** The files among `paths` that the store tracks, with the stamp it recorded. */
30
+ statFiles(paths: string[]): Promise<FileStat[]>;
31
+ /** Size of the store as kept: a database file, a table, a directory. */
32
+ getSizeBytes(): Promise<number>;
33
+ write(batch: WriteBatch): Promise<void>;
34
+ /**
35
+ * Documents matching any of `terms`, best first, after `filter`. The
36
+ * engine tokenizes and scores its own way.
37
+ */
38
+ keywordSearch(terms: string[], filter: Filter | undefined, limit: number): Promise<ScoredDocument[]>;
39
+ /** The filtered documents, newest first, for an empty query. */
40
+ getNewest(filter: Filter | undefined, limit: number): Promise<StoredDocument[]>;
41
+ /**
42
+ * Each document's best window by dot product with `query`, best first,
43
+ * after `filter`. An exact scan or an index; the caller cannot tell.
44
+ */
45
+ embeddingsSearch(query: Float32Array, filter: Filter | undefined, limit: number): Promise<WindowHit[]>;
46
+ /** Throws when the engine's own invariants do not hold. For tests. */
47
+ check(): Promise<void>;
48
+ close(): Promise<void>;
49
+ };
50
+ export type { StoreSettings };
51
+ /** A Document as the engine keeps it. */
52
+ export type StoredDocument = Document & {
53
+ /** The file it came from, for addFiles. Absent for add. */
54
+ sourcePath?: string;
55
+ };
56
+ /** `score` is the engine's own; higher is better, comparable within one call. */
57
+ export type ScoredDocument = {
58
+ document: StoredDocument;
59
+ score: number;
60
+ };
61
+ /** One window of a document: its index within the document and its offsets in `text`. */
62
+ export type Window = {
63
+ n: number;
64
+ start: number;
65
+ end: number;
66
+ };
67
+ export type WindowHit = ScoredDocument & {
68
+ window: Window;
69
+ };
70
+ /** A window with its unit-length vector, as written. */
71
+ export type WindowWrite = Window & {
72
+ vector: Float32Array;
73
+ };
74
+ /** A document's windows as the store holds them, from getWindows. */
75
+ export type DocumentWindows = {
76
+ id: string;
77
+ windows: WindowWrite[];
78
+ };
79
+ export type DocumentWrite = {
80
+ document: StoredDocument;
81
+ /**
82
+ * The document's windows after the write. A list replaces what it has;
83
+ * "keep" leaves them, which is right when its title and text did not
84
+ * change. The caller must say which: the engine cannot tell a changed
85
+ * text from an unchanged one. "keep" on a document the store does not
86
+ * hold rejects; a new document without vectors gets [].
87
+ */
88
+ windows: WindowWrite[] | "keep";
89
+ };
90
+ /** One atomic write, and one statement: the engine does exactly the kind named. */
91
+ export type WriteBatch =
92
+ /** Insert or replace by id. */
93
+ {
94
+ kind: "upsert";
95
+ documents: DocumentWrite[];
96
+ }
97
+ /**
98
+ * In this order: record these files, upsert their documents, and delete
99
+ * each file's documents that are not among them. The order is required:
100
+ * a document references its file, so the file's row must exist first.
101
+ */
102
+ | {
103
+ kind: "replaceFiles";
104
+ files: FileStat[];
105
+ documents: DocumentWrite[];
106
+ }
107
+ /** Delete these documents and their windows. */
108
+ | {
109
+ kind: "remove";
110
+ ids: string[];
111
+ }
112
+ /** Delete every tracked file not in this list, with its documents. */
113
+ | {
114
+ kind: "keepOnlyFiles";
115
+ paths: string[];
116
+ }
117
+ /** Clear these files' stamps, so the next load reads them again. */
118
+ | {
119
+ kind: "forgetFileStamps";
120
+ paths: string[];
121
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,75 @@
1
+ import type { Document } from "./types.ts";
2
+ /** Bytes read from the start of a file to decide whether it is text. */
3
+ export declare const NUL_PROBE_BYTES = 8192;
4
+ /** A file on disk, as addFiles sees it. `mtime` is `stat.mtimeMs`, not truncated. */
5
+ export type FileStat = {
6
+ path: string;
7
+ mtime: number;
8
+ size: number;
9
+ };
10
+ /** Which matched files to read again. */
11
+ export type FilePlan = {
12
+ total: number;
13
+ changed: FileStat[];
14
+ skipped: number;
15
+ };
16
+ /** What reading a file found: text, binary data, or an error from the file system. */
17
+ export type FileKind = "text" | "nonText" | "unreadable";
18
+ /** One file after reading: its documents, or none when it is binary or unreadable. */
19
+ export type ParsedFile = {
20
+ file: FileStat;
21
+ kind: FileKind;
22
+ documents: Document[];
23
+ };
24
+ /** The matched paths that are regular files, and those that could not be stat'ed, such as dangling symlinks. */
25
+ export type StatResult = {
26
+ files: FileStat[];
27
+ unreadable: string[];
28
+ };
29
+ export type Parse = (path: string, text: string) => Document[];
30
+ /** Replaces a leading `~` or `~/` with the home directory. `~user` is left alone. */
31
+ export declare function expandHome(p: string): string;
32
+ /** An absolute path: `~` expanded, then resolved against the current directory. */
33
+ export declare function resolveUserPath(p: string): string;
34
+ /**
35
+ * A real path, written as a pattern that `expandGlobs` matches to that path
36
+ * and nothing else: a folder named `notes [2024]` matches itself, not
37
+ * `notes 2`. Escape the path the caller holds, then add pattern parts after
38
+ * it, such as `${escapeGlob(folder)}/**\/*.md`.
39
+ *
40
+ * `fs.glob` has no escape character: it reads a backslash as a path
41
+ * separator. So each special character becomes a class of one, `[*]`. Two
42
+ * things cannot be written that way, and throw: a backslash, and a pair of
43
+ * braces with a comma between them, which `fs.glob` expands even inside a
44
+ * class.
45
+ *
46
+ * @throws when the path holds a backslash, or a pair of braces with a comma
47
+ * between them. No glob matches such a path alone, so a caller that takes
48
+ * paths from a person must catch this.
49
+ */
50
+ export declare function escapeGlob(p: string): string;
51
+ /**
52
+ * The absolute paths of the entries matching any glob, sorted and without
53
+ * duplicates. Patterns resolve against the current directory. `fs.glob`
54
+ * skips dotfiles and dot directories, and does not descend into symlinked
55
+ * directories. A symlinked file matches under the link's own path.
56
+ */
57
+ export declare function expandGlobs(globs: string[]): Promise<string[]>;
58
+ /**
59
+ * Stats every path, following symlinks, and keeps regular files only. A path
60
+ * the file system refuses, such as a dangling symlink, is counted as
61
+ * unreadable instead of failing the whole load.
62
+ */
63
+ export declare function statFiles(paths: string[]): Promise<StatResult>;
64
+ /** A file is unchanged when the store knows it with the same mtime and size. `force` reads every file again. */
65
+ export declare function planFileChanges(files: FileStat[], known: FileStat[], force: boolean): FilePlan;
66
+ /** One document per file: id is the path, title the file name, createdAt the mtime. */
67
+ export declare function defaultParse(file: FileStat, text: string): Document[];
68
+ /**
69
+ * Reads a file and turns it into documents. A NUL byte in the first
70
+ * NUL_PROBE_BYTES marks binary data, and the rest is never read. A file the
71
+ * file system refuses, such as one without read permission, is unreadable.
72
+ * A custom parser's documents get `meta.path` unless they set it, and an
73
+ * error from the parser rejects.
74
+ */
75
+ export declare function readAndParse(file: FileStat, parse: Parse | undefined): Promise<ParsedFile>;
package/dist/files.js ADDED
@@ -0,0 +1,190 @@
1
+ // Paths, globs and files for addFiles. planFileChanges and defaultParse are
2
+ // pure; the rest read the file system.
3
+ import { glob, open, readFile, stat } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ /** Bytes read from the start of a file to decide whether it is text. */
7
+ export const NUL_PROBE_BYTES = 8192;
8
+ /** Replaces a leading `~` or `~/` with the home directory. `~user` is left alone. */
9
+ export function expandHome(p) {
10
+ if (p === "~") {
11
+ return os.homedir();
12
+ }
13
+ if (p.startsWith("~/")) {
14
+ return path.join(os.homedir(), p.slice(2));
15
+ }
16
+ return p;
17
+ }
18
+ /** An absolute path: `~` expanded, then resolved against the current directory. */
19
+ export function resolveUserPath(p) {
20
+ return path.resolve(expandHome(p));
21
+ }
22
+ /**
23
+ * The characters that mean something in a pattern `expandGlobs` reads. `(`
24
+ * and `)` cover the extglobs `@(…)`, `+(…)`, `!(…)`, `*(…)` and `?(…)`, so
25
+ * `!`, `+` and `@` need nothing of their own.
26
+ */
27
+ const GLOB_SPECIAL = /[*?[\]{}()]/g;
28
+ /**
29
+ * Whether a `{` and the `}` that closes it have a comma between them, at
30
+ * their own depth. Node's glob expands such a pair before it reads anything
31
+ * else. `{y}/a,b/{z}` has none: its comma is outside both pairs. `a{b{c},d}`
32
+ * has one: the outer pair.
33
+ */
34
+ function hasBraceOptions(p) {
35
+ // One entry per brace still open: whether a comma has been seen inside it.
36
+ const open = [];
37
+ for (const character of p) {
38
+ if (character === "{") {
39
+ open.push(false);
40
+ }
41
+ else if (character === "," && open.length > 0) {
42
+ open[open.length - 1] = true;
43
+ }
44
+ else if (character === "}" && open.pop() === true) {
45
+ return true;
46
+ }
47
+ }
48
+ return false;
49
+ }
50
+ /**
51
+ * A real path, written as a pattern that `expandGlobs` matches to that path
52
+ * and nothing else: a folder named `notes [2024]` matches itself, not
53
+ * `notes 2`. Escape the path the caller holds, then add pattern parts after
54
+ * it, such as `${escapeGlob(folder)}/**\/*.md`.
55
+ *
56
+ * `fs.glob` has no escape character: it reads a backslash as a path
57
+ * separator. So each special character becomes a class of one, `[*]`. Two
58
+ * things cannot be written that way, and throw: a backslash, and a pair of
59
+ * braces with a comma between them, which `fs.glob` expands even inside a
60
+ * class.
61
+ *
62
+ * @throws when the path holds a backslash, or a pair of braces with a comma
63
+ * between them. No glob matches such a path alone, so a caller that takes
64
+ * paths from a person must catch this.
65
+ */
66
+ export function escapeGlob(p) {
67
+ if (p.includes("\\")) {
68
+ throw new Error(`${p} holds a backslash, which a glob reads as a path separator, so no glob matches it`);
69
+ }
70
+ if (hasBraceOptions(p)) {
71
+ throw new Error(`${p} holds braces with a comma between them, which a glob always expands, so no glob matches it alone`);
72
+ }
73
+ return p.replace(GLOB_SPECIAL, (character) => `[${character}]`);
74
+ }
75
+ /**
76
+ * The absolute paths of the entries matching any glob, sorted and without
77
+ * duplicates. Patterns resolve against the current directory. `fs.glob`
78
+ * skips dotfiles and dot directories, and does not descend into symlinked
79
+ * directories. A symlinked file matches under the link's own path.
80
+ */
81
+ export async function expandGlobs(globs) {
82
+ const found = new Set();
83
+ for (const pattern of globs) {
84
+ for await (const entry of glob(expandHome(pattern))) {
85
+ found.add(path.resolve(entry));
86
+ }
87
+ }
88
+ return [...found].sort();
89
+ }
90
+ /**
91
+ * Stats every path, following symlinks, and keeps regular files only. A path
92
+ * the file system refuses, such as a dangling symlink, is counted as
93
+ * unreadable instead of failing the whole load.
94
+ */
95
+ export async function statFiles(paths) {
96
+ const entries = await Promise.all(paths.map(async (p) => {
97
+ try {
98
+ return { path: p, stats: await stat(p) };
99
+ }
100
+ catch (error) {
101
+ rethrowUnlessFileSystemError(error);
102
+ return { path: p, stats: undefined };
103
+ }
104
+ }));
105
+ const files = entries.flatMap((entry) => entry.stats?.isFile() ? [{ path: entry.path, mtime: entry.stats.mtimeMs, size: entry.stats.size }] : []);
106
+ const unreadable = entries.filter((entry) => entry.stats === undefined).map((entry) => entry.path);
107
+ return { files, unreadable };
108
+ }
109
+ /** Errors from the file system carry a code such as ENOENT or EACCES. Anything else is a bug and is rethrown. */
110
+ function rethrowUnlessFileSystemError(error) {
111
+ const code = error?.code;
112
+ if (typeof code !== "string") {
113
+ throw error;
114
+ }
115
+ }
116
+ /** A file is unchanged when the store knows it with the same mtime and size. `force` reads every file again. */
117
+ export function planFileChanges(files, known, force) {
118
+ const knownByPath = Object.fromEntries(known.map((file) => [file.path, file]));
119
+ const isUnchanged = (file) => {
120
+ const previous = Object.hasOwn(knownByPath, file.path) ? knownByPath[file.path] : undefined;
121
+ return !force && previous?.mtime === file.mtime && previous.size === file.size;
122
+ };
123
+ const changed = files.filter((file) => !isUnchanged(file));
124
+ return { total: files.length, changed, skipped: files.length - changed.length };
125
+ }
126
+ /** One document per file: id is the path, title the file name, createdAt the mtime. */
127
+ export function defaultParse(file, text) {
128
+ return [
129
+ {
130
+ id: file.path,
131
+ title: path.basename(file.path),
132
+ text,
133
+ createdAt: new Date(file.mtime),
134
+ meta: { path: file.path },
135
+ },
136
+ ];
137
+ }
138
+ /**
139
+ * Reads a file and turns it into documents. A NUL byte in the first
140
+ * NUL_PROBE_BYTES marks binary data, and the rest is never read. A file the
141
+ * file system refuses, such as one without read permission, is unreadable.
142
+ * A custom parser's documents get `meta.path` unless they set it, and an
143
+ * error from the parser rejects.
144
+ */
145
+ export async function readAndParse(file, parse) {
146
+ const read = await readText(file.path);
147
+ if (read.kind !== "text") {
148
+ return { file, kind: read.kind, documents: [] };
149
+ }
150
+ if (parse === undefined) {
151
+ return { file, kind: "text", documents: defaultParse(file, read.text) };
152
+ }
153
+ const documents = callParser(parse, file.path, read.text);
154
+ return {
155
+ file,
156
+ kind: "text",
157
+ documents: documents.map((doc) => ({ ...doc, meta: { path: file.path, ...doc.meta } })),
158
+ };
159
+ }
160
+ async function readText(filePath) {
161
+ try {
162
+ if (await startsWithBinary(filePath)) {
163
+ return { kind: "nonText" };
164
+ }
165
+ return { kind: "text", text: await readFile(filePath, "utf8") };
166
+ }
167
+ catch (error) {
168
+ rethrowUnlessFileSystemError(error);
169
+ return { kind: "unreadable" };
170
+ }
171
+ }
172
+ function callParser(parse, filePath, text) {
173
+ try {
174
+ return parse(filePath, text);
175
+ }
176
+ catch (error) {
177
+ throw new Error(`parse failed for ${filePath}: ${error.message}`, { cause: error });
178
+ }
179
+ }
180
+ async function startsWithBinary(filePath) {
181
+ const handle = await open(filePath, "r");
182
+ try {
183
+ const probe = Buffer.alloc(NUL_PROBE_BYTES);
184
+ const { bytesRead } = await handle.read(probe, 0, NUL_PROBE_BYTES, 0);
185
+ return probe.subarray(0, bytesRead).includes(0);
186
+ }
187
+ finally {
188
+ await handle.close();
189
+ }
190
+ }
@@ -0,0 +1,3 @@
1
+ import type { Filter } from "./types.ts";
2
+ /** Rejects a filter with an unknown key, a mixed object or a value the store cannot compare. */
3
+ export declare function validateFilter(filter: Filter): void;
package/dist/filter.js ADDED
@@ -0,0 +1,80 @@
1
+ const COMBINATOR_KEYS = ["and", "or", "not"];
2
+ const CONDITION_KEYS = ["date", "meta", "ids", "lengthChars"];
3
+ const DATE_KEYS = ["after", "before"];
4
+ const LENGTH_KEYS = ["min", "max"];
5
+ /** Rejects a filter with an unknown key, a mixed object or a value the store cannot compare. */
6
+ export function validateFilter(filter) {
7
+ assertObject(filter, "a filter");
8
+ const keys = Object.keys(filter);
9
+ for (const key of keys) {
10
+ if (!COMBINATOR_KEYS.includes(key) && !CONDITION_KEYS.includes(key)) {
11
+ throw new Error(`unknown filter key "${key}"; expected and, or, not, date, meta, ids or lengthChars`);
12
+ }
13
+ }
14
+ if (keys.some((key) => COMBINATOR_KEYS.includes(key)) && keys.length > 1) {
15
+ throw new Error(`filter mixes ${keys.join(", ")}; and, or and not each need an object of their own`);
16
+ }
17
+ if ("and" in filter || "or" in filter) {
18
+ const children = "and" in filter ? filter.and : filter.or;
19
+ if (!Array.isArray(children)) {
20
+ throw new Error(`"${keys[0]}" must be a list of filters`);
21
+ }
22
+ children.forEach(validateFilter);
23
+ return;
24
+ }
25
+ if ("not" in filter) {
26
+ validateFilter(filter.not);
27
+ return;
28
+ }
29
+ validateCondition(filter);
30
+ }
31
+ /** The entries whose value is not undefined; `{ before: undefined }` means the same as leaving `before` out. */
32
+ function definedEntries(object) {
33
+ return Object.entries(object).filter(([, value]) => value !== undefined);
34
+ }
35
+ function validateCondition(condition) {
36
+ if (condition.date !== undefined) {
37
+ assertKeys(condition.date, DATE_KEYS, "date");
38
+ for (const [key, value] of definedEntries(condition.date)) {
39
+ if (!(value instanceof Date) || Number.isNaN(value.getTime())) {
40
+ throw new Error(`date.${key} must be a valid Date`);
41
+ }
42
+ }
43
+ }
44
+ if (condition.lengthChars !== undefined) {
45
+ assertKeys(condition.lengthChars, LENGTH_KEYS, "lengthChars");
46
+ for (const [key, value] of definedEntries(condition.lengthChars)) {
47
+ if (!Number.isFinite(value)) {
48
+ throw new Error(`lengthChars.${key} must be a number`);
49
+ }
50
+ }
51
+ }
52
+ if (condition.ids !== undefined && !(Array.isArray(condition.ids) && condition.ids.every((id) => typeof id === "string"))) {
53
+ throw new Error("ids must be a list of strings");
54
+ }
55
+ if (condition.meta !== undefined) {
56
+ assertObject(condition.meta, "meta");
57
+ definedEntries(condition.meta).forEach(([key, value]) => validateMetaEntry(key, value));
58
+ }
59
+ }
60
+ function validateMetaEntry(key, value) {
61
+ if (Array.isArray(value) || (typeof value === "object" && value !== null)) {
62
+ throw new Error(`meta filter on "${key}": arrays and objects are not supported yet; "contains" filters come later`);
63
+ }
64
+ const comparable = value === null || ["string", "boolean"].includes(typeof value) || Number.isFinite(value);
65
+ if (!comparable) {
66
+ throw new Error(`meta filter on "${key}": the value must be a string, number, boolean or null`);
67
+ }
68
+ }
69
+ function assertObject(value, what) {
70
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
71
+ throw new Error(`${what} must be an object`);
72
+ }
73
+ }
74
+ function assertKeys(value, allowed, what) {
75
+ assertObject(value, what);
76
+ const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
77
+ if (unknown.length > 0) {
78
+ throw new Error(`unknown key "${unknown[0]}" in ${what}; expected ${allowed.join(" or ")}`);
79
+ }
80
+ }
@@ -0,0 +1,24 @@
1
+ /** The constant in reciprocal rank fusion: each document scores weight / (RRF_K + rank). The bench's value. */
2
+ export declare const RRF_K = 60;
3
+ export type FusionWeights = {
4
+ keyword: number;
5
+ embedding: number;
6
+ };
7
+ /** The default weights, chosen in the embeddings ticket's step 3 and 4. Not a public option. */
8
+ export declare const FUSION_WEIGHTS: FusionWeights;
9
+ /** One ranked list, best first, with its weight. */
10
+ export type RankedList = {
11
+ ids: string[];
12
+ weight: number;
13
+ };
14
+ export type Fused = {
15
+ id: string;
16
+ score: number;
17
+ };
18
+ /**
19
+ * Weighted reciprocal rank fusion: each document scores weight / (RRF_K + rank)
20
+ * in each list it is in, rank starting at 1, and the scores add. Best first;
21
+ * equal scores order by id in code point order, so the result is the same on
22
+ * every run and for every engine.
23
+ */
24
+ export declare function fuse(lists: RankedList[]): Fused[];
package/dist/fusion.js ADDED
@@ -0,0 +1,26 @@
1
+ // Combining the keyword list and the embedding list by reciprocal rank.
2
+ import { compareCodePoints } from "./ids.js";
3
+ /** The constant in reciprocal rank fusion: each document scores weight / (RRF_K + rank). The bench's value. */
4
+ export const RRF_K = 60;
5
+ /** The default weights, chosen in the embeddings ticket's step 3 and 4. Not a public option. */
6
+ export const FUSION_WEIGHTS = { keyword: 1, embedding: 1 };
7
+ /**
8
+ * Weighted reciprocal rank fusion: each document scores weight / (RRF_K + rank)
9
+ * in each list it is in, rank starting at 1, and the scores add. Best first;
10
+ * equal scores order by id in code point order, so the result is the same on
11
+ * every run and for every engine.
12
+ */
13
+ export function fuse(lists) {
14
+ const scores = Object.create(null);
15
+ for (const { ids, weight } of lists) {
16
+ if (weight === 0) {
17
+ continue;
18
+ }
19
+ ids.forEach((id, rank) => {
20
+ scores[id] = (scores[id] ?? 0) + weight / (RRF_K + rank + 1);
21
+ });
22
+ }
23
+ return Object.entries(scores)
24
+ .map(([id, score]) => ({ id, score }))
25
+ .sort((a, b) => b.score - a.score || compareCodePoints(a.id, b.id));
26
+ }
package/dist/ids.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Negative when `a` sorts before `b` in code point order, 0 when equal. */
2
+ export declare function compareCodePoints(a: string, b: string): number;
package/dist/ids.js ADDED
@@ -0,0 +1,19 @@
1
+ // The order ids sort in: code point order, the order a byte-wise comparison
2
+ // of UTF-8 gives. JavaScript's `<` on strings compares UTF-16 code units
3
+ // and puts U+FF01 after U+1F600; code point order puts it before.
4
+ /** Negative when `a` sorts before `b` in code point order, 0 when equal. */
5
+ export function compareCodePoints(a, b) {
6
+ const left = a[Symbol.iterator]();
7
+ const right = b[Symbol.iterator]();
8
+ for (;;) {
9
+ const leftChar = left.next();
10
+ const rightChar = right.next();
11
+ if (leftChar.done || rightChar.done) {
12
+ return Number(!leftChar.done) - Number(!rightChar.done);
13
+ }
14
+ const diff = leftChar.value.codePointAt(0) - rightChar.value.codePointAt(0);
15
+ if (diff !== 0) {
16
+ return diff;
17
+ }
18
+ }
19
+ }
@@ -0,0 +1,4 @@
1
+ export { Memento } from "./memento.ts";
2
+ export { escapeGlob } from "./files.ts";
3
+ export { isLocalModel } from "./local.ts";
4
+ export type * from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { Memento } from "./memento.js";
2
+ export { escapeGlob } from "./files.js";
3
+ export { isLocalModel } from "./local.js";
@@ -0,0 +1,36 @@
1
+ import type { Engine } from "./engine/types.ts";
2
+ import type { Models } from "./types.ts";
3
+ /**
4
+ * The providers that run a model on this machine, as Agency names them: the
5
+ * MLX server behind `agency local serve`, and llama.cpp inside the process.
6
+ * Agency keeps the same list as `LOCAL_PROVIDERS` but does not export it.
7
+ * Ollama is left out on purpose: it is a server, and it can run on another
8
+ * machine as easily as on this one. `notLocalBecause` also checks where the
9
+ * MLX server is.
10
+ */
11
+ export declare const LOCAL_PROVIDERS: string[];
12
+ export type ModelRole = keyof Models;
13
+ /**
14
+ * Why a "provider:model" name does not run on this machine, or undefined
15
+ * when it does.
16
+ *
17
+ * Agency sends an `mlx` call to `client.baseUrl.mlx` from the agency.json the
18
+ * node was compiled with, then to `MLX_BASE_URL`, then to
19
+ * http://127.0.0.1:8080/v1. Memento's agency.json sets no `baseUrl.mlx`, and
20
+ * test/local.test.ts checks that the compiled node has none, so only
21
+ * `MLX_BASE_URL` is read here.
22
+ */
23
+ export declare function notLocalBecause(name: string): string | undefined;
24
+ /** Whether a "provider:model" name runs on this machine. */
25
+ export declare function isLocalModel(name: string): boolean;
26
+ /**
27
+ * Rejects when a local-only store would use a model that is not local: one
28
+ * this open names, or the embedding model that made the store's vectors. A
29
+ * hosted model that made the vectors has already been sent the store's text,
30
+ * so the store cannot become local without a rebuild. Only that model's
31
+ * provider is checked, because `MLX_BASE_URL` now says nothing about where
32
+ * the vectors were made.
33
+ */
34
+ export declare function checkLocalModels(given: Models, recordedEmbedding: string | undefined): void;
35
+ /** Rejects a model call when the store is local-only now and the model is not local. Runs before every model call. */
36
+ export declare function checkModelCall(engine: Engine, role: ModelRole, name: string): Promise<void>;
package/dist/local.js ADDED
@@ -0,0 +1,75 @@
1
+ // The `local` guard. A store opened with `local: true`, or one that was
2
+ // opened that way before, calls only models that run on this machine.
3
+ // docs/dev/package.md, under "Local models only", has the rules.
4
+ import { splitModelName } from "./embed.js";
5
+ /**
6
+ * The providers that run a model on this machine, as Agency names them: the
7
+ * MLX server behind `agency local serve`, and llama.cpp inside the process.
8
+ * Agency keeps the same list as `LOCAL_PROVIDERS` but does not export it.
9
+ * Ollama is left out on purpose: it is a server, and it can run on another
10
+ * machine as easily as on this one. `notLocalBecause` also checks where the
11
+ * MLX server is.
12
+ */
13
+ export const LOCAL_PROVIDERS = ["mlx", "llama-cpp"];
14
+ /** The hosts that name this machine. `URL` keeps the brackets around an IPv6 host. */
15
+ const THIS_MACHINE = ["localhost", "127.0.0.1", "[::1]"];
16
+ /**
17
+ * Why a "provider:model" name does not run on this machine, or undefined
18
+ * when it does.
19
+ *
20
+ * Agency sends an `mlx` call to `client.baseUrl.mlx` from the agency.json the
21
+ * node was compiled with, then to `MLX_BASE_URL`, then to
22
+ * http://127.0.0.1:8080/v1. Memento's agency.json sets no `baseUrl.mlx`, and
23
+ * test/local.test.ts checks that the compiled node has none, so only
24
+ * `MLX_BASE_URL` is read here.
25
+ */
26
+ export function notLocalBecause(name) {
27
+ const { provider } = splitModelName(name);
28
+ if (!LOCAL_PROVIDERS.includes(provider)) {
29
+ return `the local providers are ${LOCAL_PROVIDERS.join(", ")}`;
30
+ }
31
+ const mlxUrl = process.env.MLX_BASE_URL ?? "";
32
+ if (provider === "mlx" && mlxUrl !== "" && !isThisMachine(mlxUrl)) {
33
+ return `MLX_BASE_URL is ${mlxUrl}, which is not this machine`;
34
+ }
35
+ return undefined;
36
+ }
37
+ function isThisMachine(url) {
38
+ const host = URL.parse(url)?.hostname;
39
+ return host !== undefined && THIS_MACHINE.includes(host);
40
+ }
41
+ /** Whether a "provider:model" name runs on this machine. */
42
+ export function isLocalModel(name) {
43
+ return notLocalBecause(name) === undefined;
44
+ }
45
+ /**
46
+ * Rejects when a local-only store would use a model that is not local: one
47
+ * this open names, or the embedding model that made the store's vectors. A
48
+ * hosted model that made the vectors has already been sent the store's text,
49
+ * so the store cannot become local without a rebuild. Only that model's
50
+ * provider is checked, because `MLX_BASE_URL` now says nothing about where
51
+ * the vectors were made.
52
+ */
53
+ export function checkLocalModels(given, recordedEmbedding) {
54
+ for (const role of ["embedding", "chat"]) {
55
+ const name = given[role];
56
+ if (name !== undefined) {
57
+ checkLocalModel(role, name);
58
+ }
59
+ }
60
+ if (recordedEmbedding !== undefined && !LOCAL_PROVIDERS.includes(splitModelName(recordedEmbedding).provider)) {
61
+ throw new Error(`store is local-only but its vectors were made by embedding model ${recordedEmbedding}, which is not local; rebuild it with a local model`);
62
+ }
63
+ }
64
+ /** Rejects a model call when the store is local-only now and the model is not local. Runs before every model call. */
65
+ export async function checkModelCall(engine, role, name) {
66
+ if ((await engine.getSettings()).local) {
67
+ checkLocalModel(role, name);
68
+ }
69
+ }
70
+ function checkLocalModel(role, name) {
71
+ const reason = notLocalBecause(name);
72
+ if (reason !== undefined) {
73
+ throw new Error(`store is local-only; ${role} model ${name} is not local: ${reason}`);
74
+ }
75
+ }