@team-antioch/sc2-doodad-finder 0.1.2 → 0.3.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.
- package/dist/asker.d.ts +1 -89
- package/dist/asker.js +2 -214
- package/dist/cache-dir.d.ts +1 -4
- package/dist/cache-dir.js +2 -17
- package/dist/cards.d.ts +2 -9
- package/dist/cli/is-main.d.ts +1 -6
- package/dist/cli/is-main.js +2 -17
- package/dist/credentials.d.ts +7 -25
- package/dist/credentials.js +9 -30
- package/dist/embedder.d.ts +1 -39
- package/dist/embedder.js +2 -94
- package/dist/embedding-index.d.ts +1 -25
- package/dist/embedding-index.js +2 -126
- package/dist/finder.d.ts +5 -56
- package/dist/finder.js +20 -141
- package/dist/jev-ranker.d.ts +7 -15
- package/dist/jev-ranker.js +6 -72
- package/dist/key-file.d.ts +1 -13
- package/dist/key-file.js +2 -62
- package/dist/login.d.ts +4 -31
- package/dist/login.js +4 -136
- package/dist/narrow.d.ts +9 -35
- package/dist/narrow.js +8 -51
- package/dist/payload-log.d.ts +1 -5
- package/dist/payload-log.js +2 -12
- package/dist/ranker.d.ts +4 -80
- package/dist/ranker.js +3 -40
- package/dist/server.d.ts +6 -150
- package/dist/server.js +31 -552
- package/dist/settings.d.ts +1 -7
- package/dist/settings.js +2 -20
- package/dist/spend-cap.d.ts +1 -14
- package/dist/spend-cap.js +2 -22
- package/dist/start.d.ts +1 -1
- package/dist/start.js +13 -39
- package/dist/tags.d.ts +2 -14
- package/dist/test-asks.d.ts +1 -46
- package/dist/test-asks.js +2 -81
- package/dist/tray.d.ts +4 -17
- package/dist/tray.js +6 -11
- package/dist/wording.d.ts +7 -0
- package/dist/wording.js +2 -0
- package/package.json +4 -5
package/dist/embedding-index.js
CHANGED
|
@@ -1,126 +1,2 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
// tied to one model, and are only a copy of committed text: deleting the file costs a cold start.
|
|
4
|
-
//
|
|
5
|
-
// The file is a 4-byte header length, a JSON header ({ model, dimensions, hashes }), then each
|
|
6
|
-
// hash's vector as float32s, in the header's order.
|
|
7
|
-
import { createHash } from "node:crypto";
|
|
8
|
-
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
9
|
-
import path from "node:path";
|
|
10
|
-
const textHash = (text) => createHash("sha256").update(text).digest("base64url").slice(0, 22);
|
|
11
|
-
async function readCache(file, model) {
|
|
12
|
-
let bytes;
|
|
13
|
-
try {
|
|
14
|
-
bytes = await readFile(file);
|
|
15
|
-
}
|
|
16
|
-
catch {
|
|
17
|
-
return new Map();
|
|
18
|
-
}
|
|
19
|
-
try {
|
|
20
|
-
const length = bytes.readUInt32LE(0);
|
|
21
|
-
const header = JSON.parse(bytes.subarray(4, 4 + length).toString("utf8"));
|
|
22
|
-
if (header.model !== model)
|
|
23
|
-
return new Map();
|
|
24
|
-
const start = 4 + length;
|
|
25
|
-
// A file cut short, or of another layout, is no cache.
|
|
26
|
-
if (!(header.dimensions > 0) || !Array.isArray(header.hashes) || bytes.length !== start + header.hashes.length * header.dimensions * 4)
|
|
27
|
-
return new Map();
|
|
28
|
-
// A copy, aligned for Float32Array whatever the header's length.
|
|
29
|
-
const floats = new Float32Array(bytes.buffer.slice(bytes.byteOffset + start, bytes.byteOffset + start + header.hashes.length * header.dimensions * 4));
|
|
30
|
-
return new Map(header.hashes.map((hash, i) => [hash, floats.subarray(i * header.dimensions, (i + 1) * header.dimensions)]));
|
|
31
|
-
}
|
|
32
|
-
catch {
|
|
33
|
-
// Nor is one whose header doesn't read.
|
|
34
|
-
return new Map();
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
async function writeCache(file, model, vectors) {
|
|
38
|
-
const hashes = [...vectors.keys()];
|
|
39
|
-
const dimensions = vectors.values().next().value?.length ?? 0;
|
|
40
|
-
const header = Buffer.from(JSON.stringify({ model, dimensions, hashes }), "utf8");
|
|
41
|
-
const length = Buffer.alloc(4);
|
|
42
|
-
length.writeUInt32LE(header.length);
|
|
43
|
-
const floats = new Float32Array(hashes.length * dimensions);
|
|
44
|
-
hashes.forEach((hash, i) => floats.set(vectors.get(hash), i * dimensions));
|
|
45
|
-
await mkdir(path.dirname(file), { recursive: true });
|
|
46
|
-
const partial = `${file}.partial`;
|
|
47
|
-
await writeFile(partial, Buffer.concat([length, header, Buffer.from(floats.buffer)]));
|
|
48
|
-
await rename(partial, file);
|
|
49
|
-
}
|
|
50
|
-
export class EmbeddingIndex {
|
|
51
|
-
/** By card text's hash: every vector the cache holds that a card still uses. */
|
|
52
|
-
#vectors;
|
|
53
|
-
/** The last update's cards' nearest. */
|
|
54
|
-
#nearest = () => [];
|
|
55
|
-
#embedder;
|
|
56
|
-
#file;
|
|
57
|
-
constructor(embedder, file, vectors) {
|
|
58
|
-
this.#embedder = embedder;
|
|
59
|
-
this.#file = file;
|
|
60
|
-
this.#vectors = vectors;
|
|
61
|
-
}
|
|
62
|
-
/** The index over the cache file's vectors for the embedder's model; none until the first update. */
|
|
63
|
-
static async open(embedder, file) {
|
|
64
|
-
return new EmbeddingIndex(embedder, file, await readCache(file, embedder.model));
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* Takes these cards as the whole set: embeds the ones whose text it has no vector for, forgets the
|
|
68
|
-
* rest, and saves the cache when it changed. Gives these cards' own nearest, which later updates
|
|
69
|
-
* leave as it is, so a caller can swap it in with the cards it was made for.
|
|
70
|
-
*/
|
|
71
|
-
async update(cards) {
|
|
72
|
-
const hashes = cards.map((card) => textHash(card.text));
|
|
73
|
-
const missing = new Map();
|
|
74
|
-
hashes.forEach((hash, i) => {
|
|
75
|
-
if (!this.#vectors.has(hash))
|
|
76
|
-
missing.set(hash, cards[i].text);
|
|
77
|
-
});
|
|
78
|
-
const vectors = new Map();
|
|
79
|
-
if (missing.size) {
|
|
80
|
-
const embedded = await this.#embedder.embed([...missing.values()], "passage");
|
|
81
|
-
[...missing.keys()].forEach((hash, i) => vectors.set(hash, embedded[i]));
|
|
82
|
-
}
|
|
83
|
-
for (const hash of hashes)
|
|
84
|
-
vectors.set(hash, vectors.get(hash) ?? this.#vectors.get(hash));
|
|
85
|
-
const forgot = this.#vectors.size !== vectors.size || [...this.#vectors.keys()].some((hash) => !vectors.has(hash));
|
|
86
|
-
const dimensions = vectors.values().next().value?.length ?? 0;
|
|
87
|
-
const matrix = new Float32Array(cards.length * dimensions);
|
|
88
|
-
hashes.forEach((hash, i) => matrix.set(vectors.get(hash), i * dimensions));
|
|
89
|
-
const nearest = nearestOver(cards.map((card) => card.id), matrix, dimensions);
|
|
90
|
-
this.#vectors = vectors;
|
|
91
|
-
this.#nearest = nearest;
|
|
92
|
-
if (missing.size || forgot)
|
|
93
|
-
await writeCache(this.#file, this.#embedder.model, vectors);
|
|
94
|
-
// Counted in cards, not texts: cards that share a text share its one vector.
|
|
95
|
-
return { embedded: hashes.filter((hash) => missing.has(hash)).length, nearest };
|
|
96
|
-
}
|
|
97
|
-
/** The last update's cards most like a unit vector (see Nearest). */
|
|
98
|
-
nearest(query, k, keep) {
|
|
99
|
-
return this.#nearest(query, k, keep);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
/** Nearest over some cards' ids and their vectors, a row each of `matrix`. */
|
|
103
|
-
function nearestOver(ids, matrix, dimensions) {
|
|
104
|
-
return (query, k, keep) => {
|
|
105
|
-
const best = [];
|
|
106
|
-
for (let row = 0; row < ids.length; row++) {
|
|
107
|
-
const id = ids[row];
|
|
108
|
-
let similarity = 0;
|
|
109
|
-
const offset = row * dimensions;
|
|
110
|
-
for (let d = 0; d < dimensions; d++)
|
|
111
|
-
similarity += matrix[offset + d] * query[d];
|
|
112
|
-
if (best.length === k && similarity <= best[k - 1].similarity)
|
|
113
|
-
continue;
|
|
114
|
-
if (keep && !keep(id))
|
|
115
|
-
continue;
|
|
116
|
-
// Kept sorted by insertion: k is about 100, the cards a few thousand.
|
|
117
|
-
let at = best.length;
|
|
118
|
-
while (at > 0 && best[at - 1].similarity < similarity)
|
|
119
|
-
at--;
|
|
120
|
-
best.splice(at, 0, { id, similarity });
|
|
121
|
-
if (best.length > k)
|
|
122
|
-
best.pop();
|
|
123
|
-
}
|
|
124
|
-
return best;
|
|
125
|
-
};
|
|
126
|
-
}
|
|
1
|
+
// Moved to @team-antioch/sc2-finder-kit; kept here so deep imports of this package still resolve.
|
|
2
|
+
export * from "@team-antioch/sc2-finder-kit/embedding-index.js";
|
package/dist/finder.d.ts
CHANGED
|
@@ -1,58 +1,7 @@
|
|
|
1
1
|
import { type DoodadSearchSources } from "@team-antioch/sc2-asset-catalog/catalog/doodad-search.js";
|
|
2
|
+
import { type Finder as KitFinder, type FinderOptions as KitFinderOptions } from "@team-antioch/sc2-finder-kit/finder.js";
|
|
2
3
|
import { type CandidateCard } from "./cards.ts";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
export declare const
|
|
7
|
-
/** About a hundred from each search, as docs/adr/0001 has it. */
|
|
8
|
-
export declare const KEYWORD_RESULTS = 100;
|
|
9
|
-
export declare const NEAREST_RESULTS = 100;
|
|
10
|
-
/** The nearest cards the embeddings search puts the provided ones first among: its matches. */
|
|
11
|
-
export declare const NEAREST_MATCHES: number;
|
|
12
|
-
export type FinderOptions = {
|
|
13
|
-
/** Reads the sources afresh: on opening, and after each watched change. */
|
|
14
|
-
readonly load: () => Promise<DoodadSearchSources>;
|
|
15
|
-
readonly embedder: Embedder;
|
|
16
|
-
/** The vector cache file. */
|
|
17
|
-
readonly cacheFile: string;
|
|
18
|
-
/** Files and folders whose changes write the cards again; a folder is watched with everything in it. */
|
|
19
|
-
readonly watch?: readonly string[];
|
|
20
|
-
/** Called after each reload a watched change set off, with how many cards it embedded; or with the error it met. */
|
|
21
|
-
readonly onReload?: (result: {
|
|
22
|
-
readonly embedded: number;
|
|
23
|
-
}) => void;
|
|
24
|
-
readonly onError?: (error: unknown) => void;
|
|
25
|
-
};
|
|
26
|
-
export type NarrowOptions = {
|
|
27
|
-
readonly tags?: readonly Tag[];
|
|
28
|
-
/** A map's dependencies: the doodads they provide are marked, and each search takes them first among its matches. */
|
|
29
|
-
readonly dependencies?: readonly string[] | undefined;
|
|
30
|
-
/** At most this many (200 by default). */
|
|
31
|
-
readonly limit?: number;
|
|
32
|
-
};
|
|
33
|
-
export type Narrowing = {
|
|
34
|
-
readonly candidates: readonly Narrowed[];
|
|
35
|
-
/** Milliseconds: the keyword search, embedding the ask, the nearest cards, the merge, and all of it. */
|
|
36
|
-
readonly timings: {
|
|
37
|
-
readonly keyword: number;
|
|
38
|
-
readonly embed: number;
|
|
39
|
-
readonly nearest: number;
|
|
40
|
-
readonly merge: number;
|
|
41
|
-
readonly total: number;
|
|
42
|
-
};
|
|
43
|
-
};
|
|
44
|
-
export type Finder = {
|
|
45
|
-
narrow(ask: string, options?: NarrowOptions): Promise<Narrowing>;
|
|
46
|
-
/** Reads the sources and writes the cards again, embedding the changed ones. */
|
|
47
|
-
reload(): Promise<{
|
|
48
|
-
readonly embedded: number;
|
|
49
|
-
}>;
|
|
50
|
-
/** Every card, by id. */
|
|
51
|
-
readonly cards: ReadonlyMap<string, CandidateCard>;
|
|
52
|
-
/** The sources as last read: for looking up a card's picture. */
|
|
53
|
-
readonly sources: DoodadSearchSources;
|
|
54
|
-
/** How many cards opening embedded: none on a warm start. */
|
|
55
|
-
readonly embeddedOnOpen: number;
|
|
56
|
-
close(): void;
|
|
57
|
-
};
|
|
58
|
-
export declare function openFinder(options: FinderOptions): Promise<Finder>;
|
|
4
|
+
export { KEYWORD_RESULTS, NEAREST_MATCHES, NEAREST_RESULTS, type NarrowOptions, type Narrowing, vectorCacheFile } from "@team-antioch/sc2-finder-kit/finder.js";
|
|
5
|
+
export type FinderOptions = Pick<KitFinderOptions<CandidateCard, DoodadSearchSources>, "load" | "embedder" | "translator" | "languageDetector" | "cacheFile" | "watch" | "onReload" | "onError">;
|
|
6
|
+
export type Finder = KitFinder<CandidateCard, DoodadSearchSources>;
|
|
7
|
+
export declare const openFinder: (options: FinderOptions) => Promise<Finder>;
|
package/dist/finder.js
CHANGED
|
@@ -1,144 +1,23 @@
|
|
|
1
|
-
// The Doodad Finder's narrowing over its sources (docs/adr/0001), as its process keeps it: the
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// changes (the catalog's files, and any others the sources name).
|
|
5
|
-
import { watch } from "node:fs";
|
|
6
|
-
import { stat } from "node:fs/promises";
|
|
7
|
-
import path from "node:path";
|
|
1
|
+
// The Doodad Finder's narrowing over its sources (docs/adr/0001), as its process keeps it: the kit's
|
|
2
|
+
// finder (@team-antioch/sc2-finder-kit/finder.js) with the doodads' cards, keyword search, tags and
|
|
3
|
+
// dependencies.
|
|
8
4
|
import { providesDependency } from "@team-antioch/sc2-asset-catalog/catalog/doodad-dependencies.js";
|
|
9
|
-
import { catalogCacheDir } from "@team-antioch/sc2-asset-catalog/catalog/catalog-dirs.js";
|
|
10
5
|
import { matchDoodads } from "@team-antioch/sc2-asset-catalog/catalog/doodad-search.js";
|
|
6
|
+
import { openFinder as kitOpenFinder } from "@team-antioch/sc2-finder-kit/finder.js";
|
|
7
|
+
import { jevRankBudget } from "@team-antioch/sc2-finder-kit/jev-ranker.js";
|
|
11
8
|
import { candidateCards } from "./cards.js";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
export const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const isFolder = await stat(target).then((found) => found.isDirectory(), () => false);
|
|
28
|
-
const folder = isFolder ? target : path.dirname(target);
|
|
29
|
-
const name = path.basename(target);
|
|
30
|
-
try {
|
|
31
|
-
const watcher = watch(folder, { recursive: isFolder, persistent: false }, (_event, file) => (isFolder || file === null || file === name ? changed() : undefined));
|
|
32
|
-
// A watched folder deleted or shut off (the cache folder is safe to delete) stops its watch, not the process.
|
|
33
|
-
watcher.on("error", (error) => {
|
|
34
|
-
watcher.close();
|
|
35
|
-
onError(error);
|
|
36
|
-
});
|
|
37
|
-
watchers.push(watcher);
|
|
38
|
-
}
|
|
39
|
-
catch {
|
|
40
|
-
// A folder that isn't there (one the sources name before it exists) has nothing to watch.
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return watchers;
|
|
44
|
-
}
|
|
45
|
-
export async function openFinder(options) {
|
|
46
|
-
const index = await EmbeddingIndex.open(options.embedder, options.cacheFile);
|
|
47
|
-
/** The sources and their cards, embedded: swapped whole, with the cards' own nearest, so an ask under way when they change never mixes old and new. */
|
|
48
|
-
const read = async () => {
|
|
49
|
-
const sources = await options.load();
|
|
50
|
-
const cards = candidateCards(sources);
|
|
51
|
-
const { embedded, nearest } = await index.update(cards);
|
|
52
|
-
return { sources, cards, byId: new Map(cards.map((card) => [card.id, card])), nearest, embedded };
|
|
53
|
-
};
|
|
54
|
-
const first = await read();
|
|
55
|
-
let loaded = first;
|
|
56
|
-
const embeddedOnOpen = first.embedded;
|
|
57
|
-
// Cards marked for a map's dependencies, kept for the last ones asked for.
|
|
58
|
-
let marked;
|
|
59
|
-
const cardsFor = (of, dependencies) => {
|
|
60
|
-
if (dependencies === undefined)
|
|
61
|
-
return of.byId;
|
|
62
|
-
const key = JSON.stringify(dependencies);
|
|
63
|
-
if (marked?.key !== key || marked.of !== of) {
|
|
64
|
-
const provides = (card) => card.dependency === undefined || providesDependency(dependencies, card.dependency);
|
|
65
|
-
marked = { key, of, cards: new Map([...of.byId].map(([id, card]) => [id, { ...card, provided: provides(card) }])) };
|
|
66
|
-
}
|
|
67
|
-
return marked.cards;
|
|
68
|
-
};
|
|
69
|
-
// One reload at a time; a change during one runs another after it.
|
|
70
|
-
let running;
|
|
71
|
-
let again = false;
|
|
72
|
-
const reload = async () => {
|
|
73
|
-
if (running) {
|
|
74
|
-
again = true;
|
|
75
|
-
return running;
|
|
76
|
-
}
|
|
77
|
-
running = (async () => {
|
|
78
|
-
let embedded = 0;
|
|
79
|
-
do {
|
|
80
|
-
again = false;
|
|
81
|
-
const next = await read();
|
|
82
|
-
embedded += next.embedded;
|
|
83
|
-
loaded = next;
|
|
84
|
-
} while (again);
|
|
85
|
-
return { embedded };
|
|
86
|
-
})();
|
|
87
|
-
try {
|
|
88
|
-
return await running;
|
|
89
|
-
}
|
|
90
|
-
finally {
|
|
91
|
-
running = undefined;
|
|
92
|
-
}
|
|
93
|
-
};
|
|
94
|
-
let timer;
|
|
95
|
-
const changed = () => {
|
|
96
|
-
clearTimeout(timer);
|
|
97
|
-
timer = setTimeout(() => {
|
|
98
|
-
reload().then((result) => options.onReload?.(result), (error) => options.onError?.(error));
|
|
99
|
-
}, SETTLE_MS);
|
|
100
|
-
};
|
|
101
|
-
const watchers = await watchPaths(options.watch ?? [], changed, (error) => options.onError?.(error));
|
|
102
|
-
return {
|
|
103
|
-
get cards() {
|
|
104
|
-
return loaded.byId;
|
|
105
|
-
},
|
|
106
|
-
get sources() {
|
|
107
|
-
return loaded.sources;
|
|
108
|
-
},
|
|
109
|
-
embeddedOnOpen,
|
|
110
|
-
reload,
|
|
111
|
-
close() {
|
|
112
|
-
clearTimeout(timer);
|
|
113
|
-
for (const watcher of watchers)
|
|
114
|
-
watcher.close();
|
|
115
|
-
},
|
|
116
|
-
async narrow(ask, { tags = [], dependencies, limit } = {}) {
|
|
117
|
-
const started = performance.now();
|
|
118
|
-
const now = loaded;
|
|
119
|
-
const cards = cardsFor(now, dependencies);
|
|
120
|
-
const pinned = tags.filter((tag) => tag.pinned);
|
|
121
|
-
const keeps = (id) => mergeKeeps(cards, id, pinned);
|
|
122
|
-
const words = askWords(ask);
|
|
123
|
-
// Pinned tags the search can't take filter before the cut; then the map's provided matches first.
|
|
124
|
-
const matches = words.length ? matchDoodads({ words, ...pinnedFacets(tags) }, now.sources) : [];
|
|
125
|
-
const keyword = providedFirst(pinned.length ? matches.filter(({ id }) => keeps(id)) : matches, cards, KEYWORD_RESULTS);
|
|
126
|
-
const keywordDone = performance.now();
|
|
127
|
-
const [vector] = ask.trim() ? await options.embedder.embed([ask], "query") : [];
|
|
128
|
-
const embedDone = performance.now();
|
|
129
|
-
const nearest = vector ? providedFirst(now.nearest(vector, NEAREST_MATCHES, pinned.length ? keeps : undefined), cards, NEAREST_RESULTS) : [];
|
|
130
|
-
const nearestDone = performance.now();
|
|
131
|
-
const candidates = mergeNarrowing(keyword, nearest, cards, { tags, ...(limit !== undefined ? { limit } : {}) });
|
|
132
|
-
const done = performance.now();
|
|
133
|
-
return {
|
|
134
|
-
candidates,
|
|
135
|
-
timings: { keyword: keywordDone - started, embed: embedDone - keywordDone, nearest: nearestDone - embedDone, merge: done - nearestDone, total: done - started },
|
|
136
|
-
};
|
|
137
|
-
},
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
/** Whether every pinned tag matches a card, as the merge keeps it, so the nearest hundred are all ones it keeps. */
|
|
141
|
-
const mergeKeeps = (cards, id, pinned) => {
|
|
142
|
-
const card = cards.get(id);
|
|
143
|
-
return card !== undefined && pinned.every((tag) => tagMatches(card, tag));
|
|
144
|
-
};
|
|
9
|
+
import { askWords, pinnedFacets, tagMatches } from "./narrow.js";
|
|
10
|
+
import { JEV_WORDING } from "./wording.js";
|
|
11
|
+
export { KEYWORD_RESULTS, NEAREST_MATCHES, NEAREST_RESULTS, vectorCacheFile } from "@team-antioch/sc2-finder-kit/finder.js";
|
|
12
|
+
export const openFinder = (options) => kitOpenFinder({
|
|
13
|
+
...options,
|
|
14
|
+
cards: (sources) => candidateCards(sources),
|
|
15
|
+
keyword: (sources, ask, tags) => {
|
|
16
|
+
const words = askWords(ask);
|
|
17
|
+
return words.length ? matchDoodads({ words, ...pinnedFacets(tags) }, sources) : [];
|
|
18
|
+
},
|
|
19
|
+
tagMatches,
|
|
20
|
+
// Jev refuses a request over its token limit (the kit's jev-ranker.ts); the doodads' cards are short enough that a default 200 never reaches it (tests/finder.test.ts).
|
|
21
|
+
rankBudget: jevRankBudget(JEV_WORDING),
|
|
22
|
+
provides: (dependencies, card) => card.dependency === undefined || providesDependency(dependencies, card.dependency),
|
|
23
|
+
});
|
package/dist/jev-ranker.d.ts
CHANGED
|
@@ -1,16 +1,8 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
export
|
|
6
|
-
export type JevOptions = {
|
|
7
|
-
readonly apiKey: string;
|
|
8
|
-
readonly log?: PayloadLog;
|
|
9
|
-
/** For tests: answers in place of the API. */
|
|
10
|
-
readonly fetch?: Fetch;
|
|
11
|
-
/** Milliseconds per attempt (10 s by default). */
|
|
12
|
-
readonly timeout?: number;
|
|
13
|
-
};
|
|
1
|
+
import { type JevOptions as KitJevOptions } from "@team-antioch/sc2-finder-kit/jev-ranker.js";
|
|
2
|
+
import type { SystemOneRequest } from "@typesafe-ai/sdk";
|
|
3
|
+
import type { RankRequest, Ranker } from "./ranker.ts";
|
|
4
|
+
export { JEV_INPUT_PRICE, JEV_MODEL } from "@team-antioch/sc2-finder-kit/jev-ranker.js";
|
|
5
|
+
export type JevOptions = Omit<KitJevOptions, "wording">;
|
|
14
6
|
/** The request for one ask: what is sent and logged. Question i is about candidate i. */
|
|
15
|
-
export declare
|
|
16
|
-
export declare
|
|
7
|
+
export declare const jevRequest: (request: RankRequest) => SystemOneRequest;
|
|
8
|
+
export declare const jevRanker: (options: JevOptions) => Ranker;
|
package/dist/jev-ranker.js
CHANGED
|
@@ -1,73 +1,7 @@
|
|
|
1
|
-
// The Jev ranker (docs/adr/0001)
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import { score, TypeSafeClient } from "@typesafe-ai/sdk";
|
|
6
|
-
import { RankerError, tagText } from "./ranker.js";
|
|
7
|
-
import { ABOUT, JEV_QUESTION, LEVELS } from "./wording.js";
|
|
8
|
-
export const JEV_MODEL = "jev-latest";
|
|
9
|
-
/** US dollars per input token; output is free. */
|
|
10
|
-
export const JEV_INPUT_PRICE = 0.042 / 1e6;
|
|
1
|
+
// The Jev ranker (docs/adr/0001) for doodads: the kit's, with this finder's wording (wording.ts).
|
|
2
|
+
import { jevRanker as kitJevRanker, jevRequest as kitJevRequest } from "@team-antioch/sc2-finder-kit/jev-ranker.js";
|
|
3
|
+
import { JEV_WORDING } from "./wording.js";
|
|
4
|
+
export { JEV_INPUT_PRICE, JEV_MODEL } from "@team-antioch/sc2-finder-kit/jev-ranker.js";
|
|
11
5
|
/** The request for one ask: what is sent and logged. Question i is about candidate i. */
|
|
12
|
-
export
|
|
13
|
-
|
|
14
|
-
if (object)
|
|
15
|
-
state.object = object;
|
|
16
|
-
if (tags?.length)
|
|
17
|
-
state.tags = tags.map(tagText);
|
|
18
|
-
const questions = Object.fromEntries(candidates.map((card, i) => [`c${i}`, score({ question: JEV_QUESTION, doodad: card.text }, LEVELS)]));
|
|
19
|
-
return { model: JEV_MODEL, state, questions };
|
|
20
|
-
}
|
|
21
|
-
export function jevRanker(options) {
|
|
22
|
-
const client = new TypeSafeClient({ apiKey: options.apiKey, logLevel: "off", ...(options.fetch ? { fetch: options.fetch } : {}), ...(options.timeout ? { timeout: options.timeout } : {}) });
|
|
23
|
-
return {
|
|
24
|
-
name: "jev",
|
|
25
|
-
async rank(request, { signal } = {}) {
|
|
26
|
-
const started = performance.now();
|
|
27
|
-
const payload = jevRequest(request);
|
|
28
|
-
const sent = performance.now();
|
|
29
|
-
const at = new Date().toISOString();
|
|
30
|
-
let result;
|
|
31
|
-
try {
|
|
32
|
-
result = await client.systemOne(payload, signal ? { signal } : {});
|
|
33
|
-
}
|
|
34
|
-
catch (error) {
|
|
35
|
-
// The key never goes further than the client: not into the log, the terminal or the page.
|
|
36
|
-
const hide = (text) => (options.apiKey ? text.split(options.apiKey).join("[the key]") : text);
|
|
37
|
-
options.log?.({ ranker: "jev", at, ms: performance.now() - sent, request: payload, error: hide(String(error)) });
|
|
38
|
-
// The SDK's error is kept as a copy with the key hidden: its name, message and status.
|
|
39
|
-
// Its network code too (ENOTFOUND, say), from its own cause, so an outage still reads as one.
|
|
40
|
-
const failure = error;
|
|
41
|
-
const code = failure.cause?.code;
|
|
42
|
-
const cause = Object.assign(new Error(hide(failure.message)), {
|
|
43
|
-
name: failure.name,
|
|
44
|
-
...(failure.status !== undefined ? { status: failure.status } : {}),
|
|
45
|
-
...(typeof code === "string" ? { code } : {}),
|
|
46
|
-
});
|
|
47
|
-
throw new RankerError("jev", `the request failed: ${cause.message}`, { cause });
|
|
48
|
-
}
|
|
49
|
-
const answered = performance.now();
|
|
50
|
-
options.log?.({ ranker: "jev", at, ms: answered - sent, request: payload, response: result });
|
|
51
|
-
const logged = performance.now() - answered; // the log write is not part of the ranker's time
|
|
52
|
-
const input = result.usage.input_tokens ?? 0;
|
|
53
|
-
const cost = input * JEV_INPUT_PRICE;
|
|
54
|
-
const grades = new Map();
|
|
55
|
-
request.candidates.forEach((card, i) => {
|
|
56
|
-
const answer = result.answers[`c${i}`];
|
|
57
|
-
// Answered, so paid for: the error carries the cost for the spend cap.
|
|
58
|
-
if (answer?.type !== "score" || !Number.isFinite(answer.score))
|
|
59
|
-
throw new RankerError("jev", `no score for ${card.id}`, { cost });
|
|
60
|
-
const given = answer.probabilities;
|
|
61
|
-
grades.set(card.id, given ? { level: answer.score, probabilities: LEVELS.map((_, level) => given[level] ?? 0) } : { level: answer.score });
|
|
62
|
-
});
|
|
63
|
-
return {
|
|
64
|
-
ranker: "jev",
|
|
65
|
-
model: result.model,
|
|
66
|
-
grades,
|
|
67
|
-
timings: { request: answered - sent, total: performance.now() - started - logged },
|
|
68
|
-
usage: { input, output: result.usage.output_tokens ?? 0 },
|
|
69
|
-
cost,
|
|
70
|
-
};
|
|
71
|
-
},
|
|
72
|
-
};
|
|
73
|
-
}
|
|
6
|
+
export const jevRequest = (request) => kitJevRequest(request, JEV_WORDING);
|
|
7
|
+
export const jevRanker = (options) => kitJevRanker({ ...options, wording: JEV_WORDING });
|
package/dist/key-file.d.ts
CHANGED
|
@@ -1,13 +1 @@
|
|
|
1
|
-
|
|
2
|
-
/** The platform, environment and home folder the config folder is worked out from, as for the cache folder. */
|
|
3
|
-
export type ConfigPlatform = CachePlatform;
|
|
4
|
-
/** This user's config folder (the catalog's, which `setup-renderer` also writes to): where the key file is kept. */
|
|
5
|
-
export declare const configDir: (on?: ConfigPlatform) => string;
|
|
6
|
-
/** The key file in the config folder. */
|
|
7
|
-
export declare const keyFile: (on?: ConfigPlatform) => string;
|
|
8
|
-
/** The saved key, trimmed, or none when there is no file or it is blank. */
|
|
9
|
-
export declare function readKeyFile(on?: ConfigPlatform): string | undefined;
|
|
10
|
-
/** Saves the key whole: to a new file beside the key file, readable by its owner alone, then over it. */
|
|
11
|
-
export declare function saveKeyFile(key: string, on?: ConfigPlatform): Promise<void>;
|
|
12
|
-
/** Deletes the key file: true when there was one. */
|
|
13
|
-
export declare function removeKeyFile(on?: ConfigPlatform): Promise<boolean>;
|
|
1
|
+
export * from "@team-antioch/sc2-finder-kit/key-file.js";
|
package/dist/key-file.js
CHANGED
|
@@ -1,62 +1,2 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
// ~/.config/sc2-asset-catalog) on macOS and Linux, or SC2_ASSET_CATALOG_CONFIG on any of them. Unlike
|
|
4
|
-
// the cache folder, it holds something that is not a copy of anything else. On POSIX the file is
|
|
5
|
-
// 0600, in a 0700 folder (a folder SC2_ASSET_CATALOG_CONFIG names is left as it is unless the save
|
|
6
|
-
// creates it). No OS credential manager is used.
|
|
7
|
-
import { randomBytes } from "node:crypto";
|
|
8
|
-
import { readFileSync } from "node:fs";
|
|
9
|
-
import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
10
|
-
import path from "node:path";
|
|
11
|
-
import { catalogConfigDir } from "@team-antioch/sc2-asset-catalog/catalog/catalog-dirs.js";
|
|
12
|
-
/** This user's config folder (the catalog's, which `setup-renderer` also writes to): where the key file is kept. */
|
|
13
|
-
export const configDir = (on = {}) => catalogConfigDir(on);
|
|
14
|
-
/** The key file in the config folder. */
|
|
15
|
-
export const keyFile = (on = {}) => ((on.platform ?? process.platform) === "win32" ? path.win32 : path.posix).join(configDir(on), "typesafe-key");
|
|
16
|
-
/** The saved key, trimmed, or none when there is no file or it is blank. */
|
|
17
|
-
export function readKeyFile(on = {}) {
|
|
18
|
-
let text;
|
|
19
|
-
try {
|
|
20
|
-
text = readFileSync(keyFile(on), "utf8");
|
|
21
|
-
}
|
|
22
|
-
catch (error) {
|
|
23
|
-
if (error.code === "ENOENT")
|
|
24
|
-
return undefined;
|
|
25
|
-
throw error;
|
|
26
|
-
}
|
|
27
|
-
return text.trim() || undefined;
|
|
28
|
-
}
|
|
29
|
-
/** Saves the key whole: to a new file beside the key file, readable by its owner alone, then over it. */
|
|
30
|
-
export async function saveKeyFile(key, on = {}) {
|
|
31
|
-
const file = keyFile(on);
|
|
32
|
-
const dir = path.dirname(file);
|
|
33
|
-
const posix = (on.platform ?? process.platform) !== "win32";
|
|
34
|
-
const created = await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
35
|
-
// The default folder is ours, so it is tightened; a folder SC2_ASSET_CATALOG_CONFIG names is the
|
|
36
|
-
// user's, so only the file is.
|
|
37
|
-
if (posix && (created !== undefined || !(on.env ?? process.env).SC2_ASSET_CATALOG_CONFIG))
|
|
38
|
-
await chmod(dir, 0o700);
|
|
39
|
-
const partial = `${file}.${randomBytes(6).toString("hex")}.partial`;
|
|
40
|
-
try {
|
|
41
|
-
await writeFile(partial, `${key}\n`, { mode: 0o600, flag: "wx" });
|
|
42
|
-
if (posix)
|
|
43
|
-
await chmod(partial, 0o600);
|
|
44
|
-
await rename(partial, file);
|
|
45
|
-
}
|
|
46
|
-
catch (error) {
|
|
47
|
-
await rm(partial, { force: true });
|
|
48
|
-
throw error;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
/** Deletes the key file: true when there was one. */
|
|
52
|
-
export async function removeKeyFile(on = {}) {
|
|
53
|
-
try {
|
|
54
|
-
await rm(keyFile(on));
|
|
55
|
-
return true;
|
|
56
|
-
}
|
|
57
|
-
catch (error) {
|
|
58
|
-
if (error.code === "ENOENT")
|
|
59
|
-
return false;
|
|
60
|
-
throw error;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
1
|
+
// Moved to @team-antioch/sc2-finder-kit; kept here so deep imports of this package still resolve.
|
|
2
|
+
export * from "@team-antioch/sc2-finder-kit/key-file.js";
|
package/dist/login.d.ts
CHANGED
|
@@ -1,32 +1,5 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
|
|
3
|
-
export type
|
|
4
|
-
readonly ok: true;
|
|
5
|
-
} | {
|
|
6
|
-
readonly ok: false;
|
|
7
|
-
readonly refused: boolean;
|
|
8
|
-
readonly reason: string;
|
|
9
|
-
};
|
|
10
|
-
export type KeyCheck = (key: string) => Promise<KeyCheckResult>;
|
|
11
|
-
/** Checks a key by listing the account's models (GET /v1/models): no Jev request, no tokens. */
|
|
12
|
-
export declare function typesafeKeyCheck({ fetch }?: {
|
|
13
|
-
readonly fetch?: typeof globalThis.fetch;
|
|
14
|
-
}): KeyCheck;
|
|
15
|
-
/** A terminal's input: raw mode turns its echo off. */
|
|
16
|
-
type TerminalInput = NodeJS.ReadableStream & {
|
|
17
|
-
readonly isTTY?: boolean;
|
|
18
|
-
setRawMode?(raw: boolean): unknown;
|
|
19
|
-
};
|
|
20
|
-
export type LoginOptions = ConfigPlatform & {
|
|
21
|
-
/** Where the key is read from (stdin by default). */
|
|
22
|
-
readonly input?: TerminalInput;
|
|
23
|
-
/** Where the prompt and messages go (stdout by default). */
|
|
24
|
-
readonly output?: NodeJS.WritableStream;
|
|
25
|
-
/** How the key is checked (with TypeSafe by default). */
|
|
26
|
-
readonly check?: KeyCheck;
|
|
27
|
-
};
|
|
1
|
+
import { type LoginOptions as KitLoginOptions } from "@team-antioch/sc2-finder-kit/login.js";
|
|
2
|
+
export { logout, type KeyCheck, type KeyCheckResult, typesafeKeyCheck } from "@team-antioch/sc2-finder-kit/login.js";
|
|
3
|
+
export type LoginOptions = Omit<KitLoginOptions, "command">;
|
|
28
4
|
/** Asks for the key, checks it and saves it. Returns the exit code: 0 saved, 1 not, 130 cancelled. */
|
|
29
|
-
export declare
|
|
30
|
-
/** Deletes the key file and says whether there was one. */
|
|
31
|
-
export declare function logout(options?: Pick<LoginOptions, "output" | keyof ConfigPlatform>): Promise<void>;
|
|
32
|
-
export {};
|
|
5
|
+
export declare const login: (options?: LoginOptions) => Promise<number>;
|