@team-antioch/sc2-set-finder 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TeamAntioch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,73 @@
1
- # Temporary Holding Version
1
+ # @team-antioch/sc2-set-finder
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ask for a StarCraft II cinematic set in plain words ("the bridge of a small starship", "a jungle clearing at night", "a hall of sleeping warriors in stasis pods") and see the sets that fit, best first. A set is one of the pre-built locations Blizzard's campaign cutscenes are filmed in: a cluster of scenery in a Cutscene Editor file, with its own cameras. Each card shows pictures of the set, what it looks like, what it could stand in for, its size and camera count, and the Cutscene Editor file it is in.
4
+
5
+ It's a local page that narrows each ask with a keyword search and a local embeddings model over the sets' **looks**, then (optionally) ranks the candidates with Jev, TypeSafe AI's System One model.
6
+
7
+ This project is not affiliated with or endorsed by Blizzard Entertainment. StarCraft II and its assets are Blizzard's. No game data ships here. The looks (`data/set-looks.json` in `@team-antioch/sc2-asset-catalog`) are our own words and measurements of 77 sets made only from Blizzard's files, and the pictures are linked by URL from the [sc2-mapping-reference](https://github.com/TeamAntioch/sc2-mapping-reference) gallery ([ADR 0005](https://github.com/TeamAntioch/sc2-asset-catalog/blob/main/docs/adr/0005-cinematic-sets-ship-our-looks-and-link-their-pictures.md)).
8
+
9
+ ## Install and start
10
+
11
+ You need [Node.js](https://nodejs.org/) 22.18 or later, on Windows, macOS or Linux. No StarCraft II install is needed to search.
12
+
13
+ ```sh
14
+ npx @team-antioch/sc2-set-finder --open
15
+ ```
16
+
17
+ On Windows, type `npx.cmd` in place of `npx`, and install the [Microsoft Visual C++ Redistributable](https://learn.microsoft.com/cpp/windows/latest-supported-vc-redist) first if the machine doesn't have it: the embeddings model needs it. The page is at `http://127.0.0.1:4636/`. It listens on your own machine only. Ctrl-C stops it.
18
+
19
+ The first start downloads the embeddings model (gte-small, about 34 MB) into your cache folder, unless the Doodad or Music Finder already has, and embeds every card. Later starts take a second or so and need no connection, except to Jev and for the pictures.
20
+
21
+ Options:
22
+
23
+ - `--port <n>`: another port (`0` for any free one).
24
+ - `--budget <dollars>`: the session's spend cap on Jev, $1.00 by default.
25
+ - `--tick-log <folder>`: logs every tick to `<folder>/ticks.jsonl`, for the test asks.
26
+ - `--open`: opens the page in your browser.
27
+
28
+ `login` asks for your TypeSafe key and saves it in your config folder (the same key file the other finders use), and `logout` deletes it. Or set `TYPESAFE_API_KEY`. With no key every ask is narrowed only. What a ranked ask costs and how the cap works are in the [repo's README](https://github.com/TeamAntioch/sc2-asset-catalog#ranking-with-jev). The Set Finder sends Jev the ask, your tags and each candidate's card text (its name, kind, look, facets, uses and size), never pictures. An ask is cut to the best 24 sets, about 13,000 tokens by our estimate, so it costs about $0.0005.
29
+
30
+ ## Using the page
31
+
32
+ 1. **Browse.** With nothing asked, the page shows every set by name.
33
+ 2. **Ask** for the place your scene is in. Cards come from the narrowing as you type; on Enter, or after the pause set on the page, Jev puts them in order.
34
+ 3. **Pick kinds** with the chips: room, exterior, space, props (loose objects with no room around them), effects (only particles, holograms or light) and unclear. With none picked every kind is shown.
35
+ 4. **Open a set's page** from its card: its look in full, each chosen picture beside the same view filmed in game, its plan and overview, what is wrong with its pictures and the files it is in.
36
+ 5. **Tick** a card to put it in the tray. **Copy** gives the set's id, name and the Cutscene Editor files it is in, which is where the Editor finds it.
37
+
38
+ **Reading a card.** The pictures are Blender renders of the set's pieces where its file puts them, roof cut away, and frames of the same views filmed in the game, where one came out. The look was written by an agent from those pictures. Its confidence says how much the pictures showed, and a set's page lists the problems it saw. Sizes are in cells, measured from the pieces.
39
+
40
+ ## For a host: sc2-adjutant
41
+
42
+ These are for sc2-adjutant, and may change.
43
+
44
+ The package's main export has what a host needs: `setCards` to make the cards, `startSetFinder` to serve the page with them, `openSetFinder` for a finder with no page whose `find` narrows and ranks one ask, and `setAnswer`, the shape a found set is handed on in.
45
+
46
+ A host lays its own sets over the published ones as a **layer**: its looks (the catalog's `SetLook` shape) and where its pictures are, either a gallery address laid out as sc2-mapping-reference's `public/sets` or a folder on the machine laid out the same way (`<folder>/<set id>/card/1.jpg`, `card/1-game.jpg`, `plan.jpg`, `overview.jpg`). A set whose id is already there replaces it. The page serves a folder's pictures itself, at `/pictures/<id>/<file>`, and only those names; an answer gives each such picture's `path` too.
47
+
48
+ ```js
49
+ import { readSetLooks } from "@team-antioch/sc2-asset-catalog/catalog/set-looks.js";
50
+ import { localEmbedder } from "@team-antioch/sc2-finder-kit/embedder.js";
51
+ import { spendCap } from "@team-antioch/sc2-finder-kit/spend-cap.js";
52
+ import { openRanker, openSetFinder, setAnswer, setCards, setVectorCacheFile, startSetFinder } from "@team-antioch/sc2-set-finder";
53
+
54
+ const extra = [{ looks: myLooks, pictures: { dir: "/path/to/set-views" }, source: "my campaign" }];
55
+
56
+ // The page:
57
+ const running = await startSetFinder({ extra, port: 0 });
58
+
59
+ // Or a finder with no page, for a tool:
60
+ const embedder = await localEmbedder();
61
+ const jev = openRanker();
62
+ const finder = await openSetFinder({ cards: setCards(readSetLooks(), { extra }), embedder, cacheFile: setVectorCacheFile(embedder.model), ranker: jev.ranker, off: jev.off, cap: spendCap(1) });
63
+ const found = await finder.find("a cramped ship corridor");
64
+ const answers = found.sets.slice(0, 5).map((set) => setAnswer(set.card, set));
65
+ ```
66
+
67
+ An answer has the set's id, name, kind, look, facets, what it could stand in for, its places (`rooms`), confidence, source, size, camera count, files, its pictures (each with `url`, `thumbnail`, `path` for a folder's, and `inGame` where it has a frame filmed in game) and its plan and overview, and Jev's `level` (0 to 3) when the ask was ranked. `startSetFinder` also takes `trayActions`, a `ranker`, a `tickLog` function and `status`, as the Music Finder's start does, and gives back the `finder` its page asks, whose `find` spends under the page's cap.
68
+
69
+ ## Testing it
70
+
71
+ `npm run test-set-asks` in the repo runs the narrowing on `test-set-asks.json` (places to set a scene, each with the sets it should find) with the real model, and reports the hit rate, how many expected sets are in the first three and how fast. With a key it has Jev rank each ask too, which costs about a cent in all; `--no-rank` makes no calls.
72
+
73
+ Not affiliated with or endorsed by Blizzard Entertainment. MIT License; the looks it reads are CC BY 4.0.
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../dist/cli/set-finder.js";
3
+
4
+ // A failed start exits once its message is written: the model's download, still under way, would
5
+ // otherwise hold the terminal until it finished. Lines already sent to stdout are written first.
6
+ main().catch((error) => {
7
+ process.stdout.write("", () => process.stderr.write(`${error instanceof Error ? error.message : error}\n`, () => process.exit(1)));
8
+ });
@@ -0,0 +1,31 @@
1
+ import type { SetKind } from "@team-antioch/sc2-asset-catalog/catalog/set-looks.js";
2
+ import type { SetCard, SetCardPicture } from "./cards.ts";
3
+ import type { FoundSet } from "./finder.ts";
4
+ export type SetAnswer = {
5
+ readonly id: string;
6
+ readonly name: string;
7
+ readonly kind: SetKind;
8
+ readonly look: string;
9
+ readonly facets: readonly string[];
10
+ readonly standsInFor: readonly string[];
11
+ readonly rooms?: readonly string[];
12
+ readonly confidence: "high" | "medium" | "low";
13
+ /** What the set is from, as its card says. */
14
+ readonly source: string;
15
+ /** Cells: x, y and height. */
16
+ readonly size: readonly [number, number, number];
17
+ readonly cameras: number;
18
+ /** The Cutscene Editor files it is in, as paths in the game's data. */
19
+ readonly files: readonly string[];
20
+ /** Its chosen pictures, the whole place first, each with the same view filmed in game where there is one. */
21
+ readonly pictures: readonly SetCardPicture[];
22
+ /** Its plan and overview. */
23
+ readonly views: readonly SetCardPicture[];
24
+ /** Jev's grade, 0 to 3, when the ask was ranked. */
25
+ readonly level?: number;
26
+ /** Its places in the keyword search and among the nearest cards, 1 first, where it was in them. */
27
+ readonly keyword?: number;
28
+ readonly embeddings?: number;
29
+ };
30
+ /** A card as an answer, with what the ask found of it. */
31
+ export declare function setAnswer(card: SetCard, found?: Pick<FoundSet, "level" | "keyword" | "embeddings">): SetAnswer;
package/dist/answer.js ADDED
@@ -0,0 +1,26 @@
1
+ // A found set as a caller with no page takes it: sc2-adjutant's find_sets tool, the site's search.
2
+ // Everything its card shows, its pictures with their addresses (and files, for a layer whose
3
+ // pictures are on this machine), and Jev's grade when the ask was ranked.
4
+ /** A card as an answer, with what the ask found of it. */
5
+ export function setAnswer(card, found) {
6
+ const { look } = card;
7
+ return {
8
+ id: card.id,
9
+ name: card.name,
10
+ kind: look.kind,
11
+ look: look.look,
12
+ facets: look.facets,
13
+ standsInFor: look.standsInFor,
14
+ ...(look.rooms?.length ? { rooms: look.rooms } : {}),
15
+ confidence: look.confidence,
16
+ source: card.source,
17
+ size: look.size,
18
+ cameras: look.cameras,
19
+ files: look.files,
20
+ pictures: card.pictures,
21
+ views: card.views,
22
+ ...(found?.level !== undefined ? { level: found.level } : {}),
23
+ ...(found?.keyword !== undefined ? { keyword: found.keyword } : {}),
24
+ ...(found?.embeddings !== undefined ? { embeddings: found.embeddings } : {}),
25
+ };
26
+ }
@@ -0,0 +1,15 @@
1
+ import { escapeHtml } from "@team-antioch/sc2-asset-catalog/catalog/doodad-card-html.js";
2
+ import type { SetCard } from "./cards.ts";
3
+ export { escapeHtml };
4
+ /** A set's page on this Finder. */
5
+ export declare const setPageHref: (id: string) => string;
6
+ /** A set's size and camera count, as its card says them. */
7
+ export declare function sizeLine(card: SetCard): string;
8
+ /** The pictures a card shows: its chosen ones, else its plan and overview; then each one's frame filmed in game. */
9
+ export declare function cardPictures(card: SetCard): {
10
+ readonly url: string;
11
+ readonly thumbnail: string;
12
+ readonly shows: string;
13
+ }[];
14
+ /** A card's markup, with its tick box and an empty level. */
15
+ export declare function cardHtml(card: SetCard): string;
@@ -0,0 +1,37 @@
1
+ // A set's card on the Finder's page: its first picture large, the rest and their frames filmed in
2
+ // game in a strip below (a click swaps one into the large place), then its name, kind, source, size,
3
+ // camera count, the look, its facets and what it could stand in for. A card is plain markup the
4
+ // page's script reads; the level is filled in on the page when the ranker answers. Pictures are
5
+ // loaded by their address: the gallery's, or the page's own /pictures route for a layer's folder.
6
+ import { escapeHtml } from "@team-antioch/sc2-asset-catalog/catalog/doodad-card-html.js";
7
+ export { escapeHtml };
8
+ /** A set's page on this Finder. */
9
+ export const setPageHref = (id) => `/set/${encodeURIComponent(id)}`;
10
+ /** A set's size and camera count, as its card says them. */
11
+ export function sizeLine(card) {
12
+ const [x, y, z] = card.look.size.map(Math.round);
13
+ return `${x} × ${y} cells, ${z} high · ${card.look.cameras} camera${card.look.cameras === 1 ? "" : "s"}`;
14
+ }
15
+ /** The pictures a card shows: its chosen ones, else its plan and overview; then each one's frame filmed in game. */
16
+ export function cardPictures(card) {
17
+ const chosen = card.pictures.length ? card.pictures : card.views;
18
+ return [...chosen.map(({ url, thumbnail, shows }) => ({ url, thumbnail, shows })), ...chosen.flatMap(({ inGame, shows }) => (inGame ? [{ ...inGame, shows: `in game: ${shows}` }] : []))];
19
+ }
20
+ /** A card's markup, with its tick box and an empty level. */
21
+ export function cardHtml(card) {
22
+ const { look } = card;
23
+ const [first, ...rest] = cardPictures(card);
24
+ const href = setPageHref(card.id);
25
+ const image = (picture, large) => `<img loading="lazy" src="${escapeHtml(large ? picture.url : picture.thumbnail)}" data-large="${escapeHtml(picture.url)}" alt="${escapeHtml(picture.shows)}" title="${escapeHtml(picture.shows)}">`;
26
+ return [
27
+ first ? `<a class="first" href="${href}" target="_blank" rel="noopener">${image(first, true)}</a>` : "",
28
+ rest.length ? `<div class="strip">${rest.map((picture) => image(picture, false)).join("")}</div>` : "",
29
+ `<div class="body">`,
30
+ `<header><label><input type="checkbox" class="tick" aria-label="Tick ${escapeHtml(card.id)}"> <span class="name">${escapeHtml(card.name)}</span></label> <a class="open" href="${href}" target="_blank" rel="noopener">its page</a></header>`,
31
+ `<p class="facts"><span class="level"></span><span class="badge kind">${escapeHtml(look.kind)}</span><span>${escapeHtml(card.source)}</span><span>${escapeHtml(sizeLine(card))}</span>${look.confidence === "high" ? "" : `<span class="badge quiet">look: ${escapeHtml(look.confidence)} confidence</span>`}</p>`,
32
+ `<p class="look">${escapeHtml(look.look)}</p>`,
33
+ `<p class="facets">${look.facets.map((facet) => `<span>${escapeHtml(facet)}</span>`).join("")}</p>`,
34
+ look.standsInFor.length ? `<p class="uses">Could stand in for: ${escapeHtml(look.standsInFor.join("; "))}</p>` : "",
35
+ `</div>`,
36
+ ].join("");
37
+ }
@@ -0,0 +1,64 @@
1
+ import { type SetLook } from "@team-antioch/sc2-asset-catalog/catalog/set-looks.js";
2
+ import type { FinderCard } from "@team-antioch/sc2-finder-kit/card.js";
3
+ /** Where a picture is: the address the page loads, its small copy's, and its file on this machine when a layer's pictures are in a folder. */
4
+ export type PictureAt = {
5
+ readonly url: string;
6
+ readonly thumbnail: string;
7
+ readonly path?: string;
8
+ };
9
+ /** One of a card's pictures, what it shows, and the same view filmed in game where there is one. */
10
+ export type SetCardPicture = PictureAt & {
11
+ readonly file: string;
12
+ readonly shows: string;
13
+ readonly inGame?: PictureAt;
14
+ };
15
+ export type SetCard = FinderCard & {
16
+ readonly look: SetLook;
17
+ /** What the set is from, as its card says: "Blizzard campaign" for the published sets, a layer's own words for its sets. */
18
+ readonly source: string;
19
+ /** The look's chosen pictures, the whole place first. */
20
+ readonly pictures: readonly SetCardPicture[];
21
+ /** The plan and the overview every set has. */
22
+ readonly views: readonly SetCardPicture[];
23
+ /** The folder a layer's pictures are in, laid out as the gallery is (`<id>/card/1.jpg`): the page serves them from it. */
24
+ readonly pictureDir?: string;
25
+ };
26
+ /** What the published sets' cards say they are from. */
27
+ export declare const PUBLISHED_SOURCE = "Blizzard campaign";
28
+ /**
29
+ * For sc2-adjutant, may change: sets of a host's own, laid over the published ones. A set with an
30
+ * id the published sets (or an earlier layer) have replaces it. Its pictures are named as the
31
+ * gallery names them (`card/1.jpg`, `card/1-game.jpg`, `plan.jpg`, `overview.jpg`), under
32
+ * `base` (an address) or `dir` (a folder, `<dir>/<set id>/card/1.jpg`).
33
+ */
34
+ export type SetLayer = {
35
+ readonly looks: ReadonlyMap<string, SetLook> | Readonly<Record<string, SetLook>>;
36
+ readonly pictures: {
37
+ readonly base: string;
38
+ } | {
39
+ readonly dir: string;
40
+ };
41
+ /** What its cards say they are from. */
42
+ readonly source: string;
43
+ };
44
+ export type SetCardsOptions = {
45
+ /** The gallery the published sets' pictures are linked from (sc2-mapping-reference on GitHub by default), such as the site's own. */
46
+ readonly base?: string;
47
+ /** For sc2-adjutant, may change: more sets, laid over the published ones in order. */
48
+ readonly extra?: readonly SetLayer[];
49
+ };
50
+ /**
51
+ * A card's text and what the embeddings model reads of it, made together. The text is a name line
52
+ * (the name and kind), then the look, its facets, what it could stand in for, the places in it and
53
+ * its size, a line each. The embedded text is the same with the name line cut to the kind.
54
+ */
55
+ export declare function cardTexts(look: SetLook): {
56
+ readonly text: string;
57
+ readonly embedText: string;
58
+ };
59
+ /** A card's text: its name line, then what its look says (see cardTexts). */
60
+ export declare const cardText: (look: SetLook) => string;
61
+ /** One set's card, its pictures placed as its layer says. */
62
+ export declare function setCard(id: string, look: SetLook, layer: Pick<SetLayer, "pictures" | "source">): SetCard;
63
+ /** The cards of the published sets (or `looks`), with each `extra` layer laid over them, by name. */
64
+ export declare function setCards(looks?: ReadonlyMap<string, SetLook>, { base, extra }?: SetCardsOptions): SetCard[];
package/dist/cards.js ADDED
@@ -0,0 +1,71 @@
1
+ // The Set Finder's cards (docs/adr/0005): one per cinematic set, from its look, with each picture's
2
+ // address. A card's text is what the keyword search reads and Jev judges; the embeddings model
3
+ // reads it without the name line, since a set's name ("zSMBriefing_Korhal02 set") is a file's
4
+ // label, not a description, and drowns the meaning in the vector as the music ids' words did.
5
+ //
6
+ // The published sets' pictures are in the sc2-mapping-reference gallery, linked by URL. A host
7
+ // (sc2-adjutant) lays its own sets over them as more layers, each with its looks and where its
8
+ // pictures are: another gallery's address, or a folder on this machine that the page serves.
9
+ import path from "node:path";
10
+ import { readSetLooks, SET_GALLERY_URL, setPictureUrl } from "@team-antioch/sc2-asset-catalog/catalog/set-looks.js";
11
+ /** What the published sets' cards say they are from. */
12
+ export const PUBLISHED_SOURCE = "Blizzard campaign";
13
+ const sizeText = ([x, y, z]) => `${Math.round(x)} by ${Math.round(y)} cells, ${Math.round(z)} high`;
14
+ /**
15
+ * A card's text and what the embeddings model reads of it, made together. The text is a name line
16
+ * (the name and kind), then the look, its facets, what it could stand in for, the places in it and
17
+ * its size, a line each. The embedded text is the same with the name line cut to the kind.
18
+ */
19
+ export function cardTexts(look) {
20
+ const lines = [
21
+ look.look,
22
+ `Facets: ${look.facets.join(", ")}`,
23
+ ...(look.standsInFor.length ? [`Could stand in for: ${look.standsInFor.join("; ")}`] : []),
24
+ ...(look.rooms?.length ? [`Places in it: ${look.rooms.join(" ")}`] : []),
25
+ `Size: ${sizeText(look.size)}`,
26
+ ];
27
+ return { text: [`${look.name} (${look.kind})`, ...lines].join("\n"), embedText: [`A ${look.kind} set`, ...lines].join("\n") };
28
+ }
29
+ /** A card's text: its name line, then what its look says (see cardTexts). */
30
+ export const cardText = (look) => cardTexts(look).text;
31
+ /** The views every set has, with what they show. */
32
+ const VIEWS = [
33
+ { file: "plan.jpg", shows: "plan, roof cut away" },
34
+ { file: "overview.jpg", shows: "overview from the south-east, roof cut away" },
35
+ ];
36
+ /** How a layer names a picture's place: the gallery's address, or the page's own route to a folder's file. */
37
+ function placer(id, pictures) {
38
+ if ("base" in pictures)
39
+ return (file, inGame) => ({ url: setPictureUrl(id, file, { inGame, base: pictures.base }), thumbnail: setPictureUrl(id, file, { inGame, thumbnail: true, base: pictures.base }) });
40
+ // A folder has no thumbnails of its own: the page loads the picture itself.
41
+ return (file, inGame) => {
42
+ const name = inGame ? file.replace(/\.jpg$/, "-game.jpg") : file;
43
+ const url = `/pictures/${encodeURIComponent(id)}/${name}`;
44
+ return { url, thumbnail: url, path: path.join(pictures.dir, id, name) };
45
+ };
46
+ }
47
+ /** One set's card, its pictures placed as its layer says. */
48
+ export function setCard(id, look, layer) {
49
+ const at = placer(id, layer.pictures);
50
+ const { text, embedText } = cardTexts(look);
51
+ return {
52
+ id,
53
+ name: look.name,
54
+ text,
55
+ embedText,
56
+ look,
57
+ source: layer.source,
58
+ pictures: look.pictures.map(({ file, shows, inGame }) => ({ file, shows, ...at(file, false), ...(inGame ? { inGame: at(file, true) } : {}) })),
59
+ views: VIEWS.map(({ file, shows }) => ({ file, shows, ...at(file, false) })),
60
+ ...("dir" in layer.pictures ? { pictureDir: layer.pictures.dir } : {}),
61
+ };
62
+ }
63
+ const entries = (looks) => (looks instanceof Map ? [...looks] : Object.entries(looks));
64
+ /** The cards of the published sets (or `looks`), with each `extra` layer laid over them, by name. */
65
+ export function setCards(looks = readSetLooks(), { base = SET_GALLERY_URL, extra = [] } = {}) {
66
+ const byId = new Map();
67
+ for (const layer of [{ looks, pictures: { base }, source: PUBLISHED_SOURCE }, ...extra])
68
+ for (const [id, look] of entries(layer.looks))
69
+ byId.set(id, setCard(id, look, layer));
70
+ return [...byId.values()].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
71
+ }
@@ -0,0 +1,43 @@
1
+ import { type RunningSetFinder } from "../start.ts";
2
+ export declare const USAGE = "Usage: sc2-set-finder [--port n] [--budget dollars] [--tick-log <folder>] [--open]\n sc2-set-finder login | logout";
3
+ export type FinderArgs = {
4
+ readonly port: number;
5
+ readonly budget?: number;
6
+ readonly tickLog?: string;
7
+ readonly open: boolean;
8
+ readonly help?: true;
9
+ readonly login?: true;
10
+ readonly logout?: true;
11
+ };
12
+ /** The CLI's options, for parseArgs: sc2-adjutant's wrapper adds its own to these. */
13
+ export declare const FINDER_ARG_OPTIONS: {
14
+ readonly port: {
15
+ readonly type: "string";
16
+ };
17
+ readonly budget: {
18
+ readonly type: "string";
19
+ };
20
+ readonly "tick-log": {
21
+ readonly type: "string";
22
+ };
23
+ readonly open: {
24
+ readonly type: "boolean";
25
+ };
26
+ readonly help: {
27
+ readonly type: "boolean";
28
+ };
29
+ };
30
+ /** The options from parsed values, `--tick-log` resolved from `cwd`. */
31
+ export declare function finderArgs(values: {
32
+ readonly port?: string | undefined;
33
+ readonly budget?: string | undefined;
34
+ readonly "tick-log"?: string | undefined;
35
+ readonly open?: boolean | undefined;
36
+ readonly help?: boolean | undefined;
37
+ }, cwd: string, usage?: string): FinderArgs;
38
+ /** The CLI's options and command: none, `login` or `logout`. */
39
+ export declare function parseFinderArgs(args: readonly string[], cwd: string): FinderArgs;
40
+ /** Says what started, opens the page if asked, and stops on Ctrl-C. */
41
+ export declare function announce(running: RunningSetFinder, { open, budget }: Pick<FinderArgs, "open" | "budget">, started: number): void;
42
+ /** Runs the CLI with its arguments: bin/sc2-set-finder.js calls this. */
43
+ export declare function main(argv?: readonly string[]): Promise<void>;
@@ -0,0 +1,96 @@
1
+ // The Set Finder's CLI, `sc2-set-finder`, with the public defaults: the published sets, their
2
+ // pictures linked from the sc2-mapping-reference gallery, Jev when TYPESAFE_API_KEY or the key file
3
+ // holds a key (else the narrowing's order), a spend cap of $1.00 a session unless --budget sets
4
+ // another, and a tick log only in a folder --tick-log names. It starts the Finder (start.ts) and
5
+ // prints the page's address. The process listens on 127.0.0.1 only. `login` saves the TypeSafe key
6
+ // to the key file and `logout` deletes it (login.ts).
7
+ //
8
+ // sc2-set-finder [--port n] [--budget dollars] [--tick-log <folder>] [--open]
9
+ // sc2-set-finder login | logout
10
+ import { execFile } from "node:child_process";
11
+ import path from "node:path";
12
+ import { parseArgs } from "node:util";
13
+ import { keySourceText } from "@team-antioch/sc2-finder-kit/credentials.js";
14
+ import { isMainModule } from "@team-antioch/sc2-finder-kit/is-main.js";
15
+ import { DEFAULT_BUDGET, dollars } from "@team-antioch/sc2-finder-kit/spend-cap.js";
16
+ import { login, logout } from "../login.js";
17
+ import { SET_FINDER_PORT } from "../server.js";
18
+ import { startSetFinder } from "../start.js";
19
+ export const USAGE = "Usage: sc2-set-finder [--port n] [--budget dollars] [--tick-log <folder>] [--open]\n sc2-set-finder login | logout";
20
+ /** The CLI's options, for parseArgs: sc2-adjutant's wrapper adds its own to these. */
21
+ export const FINDER_ARG_OPTIONS = { port: { type: "string" }, budget: { type: "string" }, "tick-log": { type: "string" }, open: { type: "boolean" }, help: { type: "boolean" } };
22
+ /** The options from parsed values, `--tick-log` resolved from `cwd`. */
23
+ export function finderArgs(values, cwd, usage = USAGE) {
24
+ // Number("") is 0 and Number(" ") too: an empty value is no number.
25
+ if (values.port !== undefined && !values.port.trim())
26
+ throw new Error(`--port takes a port number\n${usage}`);
27
+ if (values.budget !== undefined && !values.budget.trim())
28
+ throw new Error(`--budget takes US dollars, 0 or more\n${usage}`);
29
+ const port = Number(values.port ?? SET_FINDER_PORT);
30
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
31
+ throw new Error(`--port takes a port number\n${usage}`);
32
+ const budget = values.budget === undefined ? undefined : Number(values.budget);
33
+ if (budget !== undefined && !(budget >= 0))
34
+ throw new Error(`--budget takes US dollars, 0 or more\n${usage}`);
35
+ if (values["tick-log"] !== undefined && !values["tick-log"].trim())
36
+ throw new Error(`--tick-log takes a folder\n${usage}`);
37
+ return {
38
+ port,
39
+ ...(budget !== undefined ? { budget } : {}),
40
+ ...(values["tick-log"] !== undefined ? { tickLog: path.resolve(cwd, values["tick-log"]) } : {}),
41
+ open: values.open === true,
42
+ ...(values.help ? { help: true } : {}),
43
+ };
44
+ }
45
+ const COMMANDS = ["login", "logout"];
46
+ /** The CLI's options and command: none, `login` or `logout`. */
47
+ export function parseFinderArgs(args, cwd) {
48
+ const { values, positionals } = parseArgs({ args: [...args], options: FINDER_ARG_OPTIONS, allowPositionals: true });
49
+ const [command, ...rest] = positionals;
50
+ if ((command !== undefined && !COMMANDS.includes(command)) || rest.length)
51
+ throw new Error(USAGE);
52
+ return { ...finderArgs(values, cwd), ...(command ? { [command]: true } : {}) };
53
+ }
54
+ /** Says what started, opens the page if asked, and stops on Ctrl-C. */
55
+ export function announce(running, { open, budget }, started) {
56
+ console.log(`${running.cards} cards, ${running.embeddedOnOpen} embedded now; ready in ${Math.round(performance.now() - started)} ms`);
57
+ const key = running.keySource ? `, with ${keySourceText(running.keySource)}` : "";
58
+ console.log(running.off ? `Not ranking: ${running.off}` : `Ranking with Jev${key}, up to ${dollars(budget ?? DEFAULT_BUDGET)} this session`);
59
+ console.log(`The Set Finder is at ${running.url} (Ctrl-C stops it)`);
60
+ if (open)
61
+ execFile(process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open", [running.url]);
62
+ const stop = async () => {
63
+ await running.close();
64
+ if (running.spend)
65
+ console.log(`Estimated spend this run: $${running.spend.toFixed(4)}; payloads in ${running.payloadLog}`);
66
+ process.exit(0);
67
+ };
68
+ process.once("SIGINT", () => void stop());
69
+ process.once("SIGTERM", () => void stop());
70
+ }
71
+ /** Runs the CLI with its arguments: bin/sc2-set-finder.js calls this. */
72
+ export async function main(argv = process.argv.slice(2)) {
73
+ const args = parseFinderArgs(argv, process.env.INIT_CWD ?? process.cwd());
74
+ if (args.help)
75
+ return void console.log(USAGE);
76
+ if (args.login)
77
+ return void (process.exitCode = await login());
78
+ if (args.logout)
79
+ return logout();
80
+ const started = performance.now();
81
+ const running = await startSetFinder({
82
+ port: args.port,
83
+ ...(args.budget !== undefined ? { budget: args.budget } : {}),
84
+ ...(args.tickLog ? { tickLog: args.tickLog } : {}),
85
+ log: (line) => console.log(line),
86
+ });
87
+ if (args.tickLog)
88
+ console.log(`Ticks are logged to ${args.tickLog}`);
89
+ announce(running, args, started);
90
+ }
91
+ // Run as a file in a checkout (node src/cli/set-finder.ts); the package's bin calls main.
92
+ if (isMainModule(import.meta.url)) {
93
+ main().catch((error) => {
94
+ process.stdout.write("", () => process.stderr.write(`${error instanceof Error ? error.message : error}\n`, () => process.exit(1)));
95
+ });
96
+ }
@@ -0,0 +1,11 @@
1
+ import { type OpenedRanker as KitOpenedRanker } from "@team-antioch/sc2-finder-kit/credentials.js";
2
+ import type { PayloadLog } from "@team-antioch/sc2-finder-kit/ranker.js";
3
+ import type { SetCard } from "./cards.ts";
4
+ export { type KeySource, jevApiKey, jevKey, keySourceText } from "@team-antioch/sc2-finder-kit/credentials.js";
5
+ export declare const NO_JEV_KEY: string;
6
+ export type OpenedRanker = KitOpenedRanker<SetCard>;
7
+ /** Jev with its key and the sets' wording, else off: with no key, or (Jev being optional) a key file that can't be read. */
8
+ export declare const openRanker: ({ env, log }?: {
9
+ readonly env?: Readonly<Record<string, string | undefined>>;
10
+ readonly log?: PayloadLog;
11
+ }) => OpenedRanker;
@@ -0,0 +1,11 @@
1
+ // The ranker's credential (docs/adr/0001, 0002), held by the Finder's process alone: the kit's, for
2
+ // this finder: Jev's key from TYPESAFE_API_KEY in the environment, else the key file
3
+ // `sc2-set-finder login` saved (the one every finder's `login` saves), on every platform. With no
4
+ // key, Jev is off, with a message saying how to give it one, and asks are narrowed only.
5
+ import { noJevKey, openRanker as kitOpenRanker } from "@team-antioch/sc2-finder-kit/credentials.js";
6
+ import { PACKAGE_NAME } from "./package-name.js";
7
+ import { JEV_WORDING } from "./wording.js";
8
+ export { jevApiKey, jevKey, keySourceText } from "@team-antioch/sc2-finder-kit/credentials.js";
9
+ export const NO_JEV_KEY = noJevKey(PACKAGE_NAME);
10
+ /** Jev with its key and the sets' wording, else off: with no key, or (Jev being optional) a key file that can't be read. */
11
+ export const openRanker = ({ env, log } = {}) => kitOpenRanker({ ...(env ? { env } : {}), ...(log ? { log } : {}), wording: JEV_WORDING, command: PACKAGE_NAME });
@@ -0,0 +1,70 @@
1
+ import { type Finder as KitFinder } from "@team-antioch/sc2-finder-kit/finder.js";
2
+ import type { Embedder } from "@team-antioch/sc2-finder-kit/embedder.js";
3
+ import type { LanguageDetector } from "@team-antioch/sc2-finder-kit/language-detector.js";
4
+ import type { Narrowed, RankBudget } from "@team-antioch/sc2-finder-kit/narrow.js";
5
+ import { type Ranker } from "@team-antioch/sc2-finder-kit/ranker.js";
6
+ import type { SpendCap } from "@team-antioch/sc2-finder-kit/spend-cap.js";
7
+ import type { Translator } from "@team-antioch/sc2-finder-kit/translator.js";
8
+ import type { SetCard } from "./cards.ts";
9
+ import { type Tag } from "./narrow.ts";
10
+ /** What the kit's finder reads: the cards, made once. */
11
+ export type SetSources = {
12
+ readonly cards: readonly SetCard[];
13
+ };
14
+ /** How many of the merged candidates an ask keeps for the ranker and the page. */
15
+ export declare const SET_LIMIT = 24;
16
+ /** What Jev takes in one request, counted for the sets' cards (docs/adr/0002); 24 cards are far below it. */
17
+ export declare const SET_RANK_BUDGET: RankBudget<SetCard>;
18
+ /** The sets' vectors in their own file, so the other finders, which share the cache folder, and this one don't replace each other's. */
19
+ export declare const setVectorCacheFile: (model: string, cacheDir?: string) => string;
20
+ /** A set an ask found: its places in the two searches, and Jev's grade from 0 (doesn't fit) to 3 (reads as exactly this) when it was ranked. */
21
+ export type FoundSet = Narrowed<SetCard> & {
22
+ readonly level?: number;
23
+ };
24
+ export type FoundSets = {
25
+ readonly ask: string;
26
+ /** Best first: by Jev's grade when ranked, else in the narrowing's order. */
27
+ readonly sets: readonly FoundSet[];
28
+ readonly ranked: boolean;
29
+ /** Why there is no ranking. */
30
+ readonly notRanked?: string;
31
+ /** US dollars this ask cost, estimated. */
32
+ readonly cost: number;
33
+ /** Milliseconds: the narrowing, and Jev's call. */
34
+ readonly timings: {
35
+ readonly narrow: number;
36
+ readonly rank?: number;
37
+ };
38
+ };
39
+ export type FindOptions = {
40
+ /** False for the narrowing alone. */
41
+ readonly rank?: boolean;
42
+ /** Pinned tags filter (`kind: room`); the rest raise, and go to Jev as context. */
43
+ readonly tags?: readonly Tag[];
44
+ /** How many candidates to narrow to and rank (24 by default). */
45
+ readonly limit?: number;
46
+ readonly signal?: AbortSignal;
47
+ };
48
+ export type SetFinderOptions = {
49
+ readonly cards: readonly SetCard[];
50
+ readonly embedder: Embedder;
51
+ /** Where the cards' vectors are kept between starts (see setVectorCacheFile). */
52
+ readonly cacheFile: string;
53
+ /** Jev, for `find`: none, or why it is off, and `find` gives the narrowing's order. */
54
+ readonly ranker?: Ranker<SetCard> | undefined;
55
+ readonly off?: string | undefined;
56
+ /** The session's spend cap, for `find`. */
57
+ readonly cap?: SpendCap | undefined;
58
+ /** Turns an ask in another language into English before it is searched; none by default (the kit's translator.js). */
59
+ readonly translator?: Translator;
60
+ readonly languageDetector?: LanguageDetector;
61
+ /** For tests: another rank budget than Jev's. */
62
+ readonly rankBudget?: RankBudget<SetCard>;
63
+ };
64
+ export type SetFinder = KitFinder<SetCard, SetSources> & {
65
+ /** Why `find` doesn't rank, when there is no ranker. */
66
+ readonly rankerOff: string | undefined;
67
+ find(ask: string, options?: FindOptions): Promise<FoundSets>;
68
+ };
69
+ export declare const NOT_RANKED = "rank: false asked for the narrowing alone";
70
+ export declare function openSetFinder({ cards, embedder, cacheFile, ranker, off, cap, translator, languageDetector, rankBudget }: SetFinderOptions): Promise<SetFinder>;