Name: Explicata, and EX_ for the environment variables
Infinispand becomes Explicata (Latin, "things unfolded") wherever the name shows: the page title, README, package, prompts, seed title, Wikipedia User-Agent and startup line. Every IE_* variable becomes EX_*. The browser's IndexedDB name and the ie: storage keys stay, so settings and replicas already stored are found; the migration fixtures keep the old seed title. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014yB6q6Kn9JiRmGKzPQMh7o
This commit is contained in:
1 parent
e6d71e84de
commit
60d26908d6
51 files changed
+256
-252
No files matched your search
+1
-1
@@ -72,7 +72,7 @@ export class Bundle {
|
||||
this.nodeIndex.watch(store.main);
|
||||
const getLinker = () => (this.linker ??= new Linker({ doc: main, wiki: shared.wiki, embedder: shared.embed, index: this.nodeIndex }));
|
||||
this.pending = new PendingStore(join(store.dir, "links", "pending.json"));
|
||||
// The link reviewer asks the configured model (no tools, structured verdicts); IE_REVIEW_CALLS caps a background job's calls.
|
||||
// The link reviewer asks the configured model (no tools, structured verdicts); EX_REVIEW_CALLS caps a background job's calls.
|
||||
this.reviewer = new Reviewer({ llm: shared.llm, wiki: shared.wiki, pending: this.pending, snap: () => store.main.snap() });
|
||||
this.jobs = new Jobs({
|
||||
snap: () => store.main.snap(),
|
||||
|
||||
+10
-10
@@ -4,15 +4,15 @@
|
||||
*
|
||||
* Node text never leaves the machine: the model runs in a worker thread of this process
|
||||
* (transformers.js on onnxruntime-node, server/embedWorker.mjs). It is loaded on first use; its
|
||||
* files are downloaded once from the Hugging Face hub into <IE_DATA>/models/. If that fails
|
||||
* files are downloaded once from the Hugging Face hub into <EX_DATA>/models/. If that fails
|
||||
* (offline, no native runtime), embed() returns null and callers fall back to text search.
|
||||
*
|
||||
* embedder.embed(texts) Float32Array[] (unit length) or null
|
||||
* new VectorIndex(file).upsert() re-embeds only entries whose text hash changed
|
||||
* index.search / textSearch / hybrid cosine top-k, BM25, and the two fused
|
||||
*
|
||||
* IE_EMBED_MODEL picks the model (default Xenova/bge-small-en-v1.5, MIT, 384 dimensions);
|
||||
* IE_EMBED=off turns embeddings off, IE_EMBED=fake uses hashed words (the tests).
|
||||
* EX_EMBED_MODEL picks the model (default Xenova/bge-small-en-v1.5, MIT, 384 dimensions);
|
||||
* EX_EMBED=off turns embeddings off, EX_EMBED=fake uses hashed words (the tests).
|
||||
*/
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
@@ -46,15 +46,15 @@ export type Loader = (spec: ModelSpec, cacheDir: string) => Promise<EmbedFn>;
|
||||
/**
|
||||
* The model with transformers.js, in a worker thread: loading it and every batch run off the main
|
||||
* thread, so the server keeps answering while a library is being embedded. A few threads are
|
||||
* nearly as fast as all of them and leave the machine usable (IE_EMBED_THREADS, default 4);
|
||||
* IE_EMBED_OFFLINE=1 reads only files downloaded before.
|
||||
* nearly as fast as all of them and leave the machine usable (EX_EMBED_THREADS, default 4);
|
||||
* EX_EMBED_OFFLINE=1 reads only files downloaded before.
|
||||
*/
|
||||
const workerLoader: Loader = (spec, cacheDir) =>
|
||||
new Promise((resolveLoad, rejectLoad) => {
|
||||
// execArgv: [] keeps a TypeScript loader (tsx) out of the worker, which is plain JavaScript.
|
||||
const worker = new Worker(new URL("./embedWorker.mjs", import.meta.url), {
|
||||
execArgv: [],
|
||||
workerData: { id: spec.id, pooling: spec.pooling, cacheDir, offline: process.env.IE_EMBED_OFFLINE === "1", threads: Number(process.env.IE_EMBED_THREADS) || 4 },
|
||||
workerData: { id: spec.id, pooling: spec.pooling, cacheDir, offline: process.env.EX_EMBED_OFFLINE === "1", threads: Number(process.env.EX_EMBED_THREADS) || 4 },
|
||||
});
|
||||
// The worker must not keep a script alive that is otherwise done.
|
||||
worker.unref();
|
||||
@@ -90,7 +90,7 @@ const workerLoader: Loader = (spec, cacheDir) =>
|
||||
});
|
||||
|
||||
/**
|
||||
* A stand-in model for tests and offline runs (IE_EMBED=fake): a bag of hashed words, normalised,
|
||||
* A stand-in model for tests and offline runs (EX_EMBED=fake): a bag of hashed words, normalised,
|
||||
* so texts sharing words are near each other. It needs no download and separates nothing subtle.
|
||||
*/
|
||||
export function fakeVector(text: string, dim = 384): Float32Array {
|
||||
@@ -176,10 +176,10 @@ export class Embedder {
|
||||
}
|
||||
|
||||
let shared: Embedder | null = null;
|
||||
/** The server's embedder, configured from IE_DATA, IE_EMBED_MODEL and IE_EMBED. */
|
||||
/** The server's embedder, configured from EX_DATA, EX_EMBED_MODEL and EX_EMBED. */
|
||||
export function embedder(): Embedder {
|
||||
const mode = process.env.IE_EMBED;
|
||||
shared ??= new Embedder({ model: mode === "fake" ? "fake" : process.env.IE_EMBED_MODEL, off: mode === "off", loader: mode === "fake" ? fakeLoader : workerLoader });
|
||||
const mode = process.env.EX_EMBED;
|
||||
shared ??= new Embedder({ model: mode === "fake" ? "fake" : process.env.EX_EMBED_MODEL, off: mode === "off", loader: mode === "fake" ? fakeLoader : workerLoader });
|
||||
return shared;
|
||||
}
|
||||
|
||||
|
||||
+24
-24
@@ -33,13 +33,13 @@ import { JOB_CALLS } from "./links/review";
|
||||
|
||||
const PORT = Number(process.env.PORT ?? 4747);
|
||||
// Host names the dev server answers to besides localhost. Tailscale names are allowed so that
|
||||
// `tailscale serve` works; IE_HOSTS adds more (comma-separated; a leading dot matches subdomains).
|
||||
const ALLOWED_HOSTS = [".ts.net", ...(process.env.IE_HOSTS ?? "").split(",").map((h) => h.trim()).filter(Boolean)];
|
||||
// `tailscale serve` works; EX_HOSTS adds more (comma-separated; a leading dot matches subdomains).
|
||||
const ALLOWED_HOSTS = [".ts.net", ...(process.env.EX_HOSTS ?? "").split(",").map((h) => h.trim()).filter(Boolean)];
|
||||
const DATA = dataDir();
|
||||
const PROD = process.env.IE_PROD === "1";
|
||||
const MODEL = process.env.IE_MODEL ?? "claude-opus-5-5";
|
||||
const USER = process.env.IE_USER ?? userInfo().username;
|
||||
const LIBRARY = resolve(process.env.IE_LIBRARY ?? join(root, "library"));
|
||||
const PROD = process.env.EX_PROD === "1";
|
||||
const MODEL = process.env.EX_MODEL ?? "claude-opus-5-5";
|
||||
const USER = process.env.EX_USER ?? userInfo().username;
|
||||
const LIBRARY = resolve(process.env.EX_LIBRARY ?? join(root, "library"));
|
||||
|
||||
// ---- model ----
|
||||
|
||||
@@ -52,11 +52,11 @@ if (process.env.ANTHROPIC_API_KEY?.startsWith("sk-ant-oat")) {
|
||||
console.log("ANTHROPIC_API_KEY holds a subscription token; using it as CLAUDE_CODE_OAUTH_TOKEN instead.");
|
||||
}
|
||||
const apiKey = Boolean(process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN);
|
||||
const wanted = process.env.IE_LLM ?? (apiKey ? "claude" : process.env.CLAUDE_CODE_OAUTH_TOKEN ? "subscription" : "off");
|
||||
const wanted = process.env.EX_LLM ?? (apiKey ? "claude" : process.env.CLAUDE_CODE_OAUTH_TOKEN ? "subscription" : "off");
|
||||
const llm: LLM | null =
|
||||
wanted === "claude" ? claudeLLM(MODEL)
|
||||
: wanted === "subscription" ? subscriptionLLM(MODEL)
|
||||
: wanted === "mock" ? withMockUsage(mockLLM({ delay: Number(process.env.IE_MOCK_DELAY ?? 12) }))
|
||||
: wanted === "mock" ? withMockUsage(mockLLM({ delay: Number(process.env.EX_MOCK_DELAY ?? 12) }))
|
||||
: null;
|
||||
|
||||
// Usage: every provider reports into one tracker (server/usage.ts), served at GET /api/usage.
|
||||
@@ -71,27 +71,27 @@ if (wanted === "subscription") {
|
||||
|
||||
// ---- web research for the editor agent ----
|
||||
|
||||
// IE_WEB=off takes web search and fetch away from the agent entirely; IE_WEB_SEARCHES and
|
||||
// IE_WEB_FETCHES cap each run (default 5 and 5). The browser asks for research; this decides.
|
||||
// EX_WEB=off takes web search and fetch away from the agent entirely; EX_WEB_SEARCHES and
|
||||
// EX_WEB_FETCHES cap each run (default 5 and 5). The browser asks for research; this decides.
|
||||
const web = webConfig(process.env, Boolean(llm));
|
||||
if (process.env.IE_WEB && !web.on && web.why) console.warn(`web research is off: ${web.why}.`);
|
||||
if (process.env.EX_WEB && !web.on && web.why) console.warn(`web research is off: ${web.why}.`);
|
||||
|
||||
// ---- Wikipedia ----
|
||||
|
||||
// IE_WIKI picks where /api/wiki/* gets its answers: the real Wikipedia (live), the fixtures in
|
||||
// EX_WIKI picks where /api/wiki/* gets its answers: the real Wikipedia (live), the fixtures in
|
||||
// server/wikiMock.ts (mock: tests and offline work, no network at all), or nowhere (off). An
|
||||
// unrecognised value is treated as off, so a typo never sends requests nobody asked for.
|
||||
type WikiMode = "live" | "mock" | "off";
|
||||
const wikiWanted = process.env.IE_WIKI ?? "live";
|
||||
const wikiWanted = process.env.EX_WIKI ?? "live";
|
||||
const wikiMode: WikiMode = wikiWanted === "live" || wikiWanted === "mock" ? wikiWanted : "off";
|
||||
if (wikiMode !== wikiWanted) console.warn(`IE_WIKI=${wikiWanted} is not live, mock or off; Wikipedia is off.`);
|
||||
if (wikiMode !== wikiWanted) console.warn(`EX_WIKI=${wikiWanted} is not live, mock or off; Wikipedia is off.`);
|
||||
// The mock keeps nothing on disk and never holds itself offline, so one test's "offline" title
|
||||
// does not leak into the next.
|
||||
const mockWiki = wikiMode === "mock" ? new WikiClient({ lang: process.env.IE_WIKI_LANG, fetch: makeMockWikiFetch(undefined, Number(process.env.IE_WIKI_MOCK_BULK_MS) || 0), spacingMs: 0, persist: false, offlineHoldMs: 0 }) : null;
|
||||
const mockWiki = wikiMode === "mock" ? new WikiClient({ lang: process.env.EX_WIKI_LANG, fetch: makeMockWikiFetch(undefined, Number(process.env.EX_WIKI_MOCK_BULK_MS) || 0), spacingMs: 0, persist: false, offlineHoldMs: 0 }) : null;
|
||||
const wikiClient = () => (wikiMode === "off" ? null : (mockWiki ?? wiki()));
|
||||
const handleWiki = wikiMode === "off" ? wikiOff : wikiRoutes(() => wikiClient()!);
|
||||
/** What the UI may know: the mode, the language, and whether a contact is set (never the contact). */
|
||||
const wikiState = { mode: wikiMode, lang: wikiLang(process.env.IE_WIKI_LANG), contact: validContact(process.env.IE_WIKI_CONTACT) !== null };
|
||||
const wikiState = { mode: wikiMode, lang: wikiLang(process.env.EX_WIKI_LANG), contact: validContact(process.env.EX_WIKI_CONTACT) !== null };
|
||||
|
||||
/** A short reason for a failed model call, whichever provider made it. */
|
||||
const explain = (err: unknown) => (err instanceof SubscriptionError ? { status: err.status, message: err.message } : describeError(err));
|
||||
@@ -104,7 +104,7 @@ const started = performance.now();
|
||||
// migration (npm run migrate) has a dry run and verifies what it writes.
|
||||
const held = lockHolder(DATA);
|
||||
if (held) {
|
||||
console.error(`Another server (pid ${held.pid}${held.port ? `, port ${held.port}` : ""}) has ${DATA} open; stop it first, or set IE_DATA to another directory.`);
|
||||
console.error(`Another server (pid ${held.pid}${held.port ? `, port ${held.port}` : ""}) has ${DATA} open; stop it first, or set EX_DATA to another directory.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const libraries = new Libraries(DATA);
|
||||
@@ -125,20 +125,20 @@ const startMs = Math.round(performance.now() - started);
|
||||
// ---- each library's link discovery, notices and routes (server/bundle.ts) ----
|
||||
|
||||
// The embedding model is loaded on first use, in a worker thread shared by every library;
|
||||
// IE_EMBED=off turns it off, and scanning then matches by text alone.
|
||||
const embed = process.env.IE_EMBED === "off" ? null : embedder();
|
||||
// EX_EMBED=off turns it off, and scanning then matches by text alone.
|
||||
const embed = process.env.EX_EMBED === "off" ? null : embedder();
|
||||
const shared: Shared = {
|
||||
llm: () => llm,
|
||||
wiki: wikiClient,
|
||||
embed,
|
||||
reviewCalls: Math.max(1, Number(process.env.IE_REVIEW_CALLS) || JOB_CALLS),
|
||||
reviewCalls: Math.max(1, Number(process.env.EX_REVIEW_CALLS) || JOB_CALLS),
|
||||
user: USER,
|
||||
state: () => ({
|
||||
user: USER,
|
||||
llm: llm?.kind ?? "off",
|
||||
model: llm?.model ?? null,
|
||||
wiki: wikiState,
|
||||
embed: embed ? (process.env.IE_EMBED === "fake" ? "fake" : "on") : "off",
|
||||
embed: embed ? (process.env.EX_EMBED === "fake" ? "fake" : "on") : "off",
|
||||
web: { on: web.on, searches: web.searches, fetches: web.fetches },
|
||||
libraries: libraries.list(),
|
||||
}),
|
||||
@@ -295,8 +295,8 @@ const CSP = [
|
||||
].join("; ");
|
||||
|
||||
function serveStatic(res: ServerResponse, path: string) {
|
||||
// IE_DIST: another build to serve (the browser tests build one per port, so runs side by side do not collide).
|
||||
const dist = resolve(root, process.env.IE_DIST ?? "dist");
|
||||
// EX_DIST: another build to serve (the browser tests build one per port, so runs side by side do not collide).
|
||||
const dist = resolve(root, process.env.EX_DIST ?? "dist");
|
||||
let file = resolve(dist, "." + path);
|
||||
if (!file.startsWith(dist) || !existsSync(file) || path === "/") file = join(dist, "index.html");
|
||||
res.writeHead(200, {
|
||||
@@ -334,7 +334,7 @@ createServer(async (req, res) => {
|
||||
serveStatic(res, path);
|
||||
}
|
||||
}).listen(PORT, "127.0.0.1", () => {
|
||||
console.log(`Infinispand http://localhost:${PORT} model: ${llm ? `${llm.kind}${llm.model ? `: ${llm.model}` : ""}` : "off (set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN to generate)"} data: ${DATA}`);
|
||||
console.log(`Explicata http://localhost:${PORT} model: ${llm ? `${llm.kind}${llm.model ? `: ${llm.model}` : ""}` : "off (set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN to generate)"} data: ${DATA}`);
|
||||
for (const l of libraries.list()) console.log(`library “${l.title}” (/l/${l.id}): ${libraries.get(l.id)!.titles().length} top-level sections, ${l.nodes} nodes`);
|
||||
console.log(`${libraries.stores.size} librar${libraries.stores.size === 1 ? "y" : "ies"} opened in ${startMs} ms`);
|
||||
console.log(`web research: ${web.on ? `on (at most ${web.searches} searches and ${web.fetches} pages read per request)` : `off${web.why ? ` (${web.why})` : ""}`}`);
|
||||
|
||||
@@ -32,7 +32,7 @@ export interface JobState {
|
||||
finishedAt?: number;
|
||||
/** Seconds left, estimated from the requests still to make and the client's spacing. */
|
||||
etaSec: number | null;
|
||||
/** The client is spacing requests for want of a contact (IE_WIKI_CONTACT). */
|
||||
/** The client is spacing requests for want of a contact (EX_WIKI_CONTACT). */
|
||||
slow: boolean;
|
||||
message?: string;
|
||||
/** The reviewer's part, for a job started with review: verdicts so far, calls made of those allowed, and why it stopped early if it did. */
|
||||
@@ -55,7 +55,7 @@ export class Jobs {
|
||||
pending: PendingStore;
|
||||
announce: (state: JobState) => void;
|
||||
reviewer?: Reviewer;
|
||||
/** Calls a job's review may make (IE_REVIEW_CALLS). */
|
||||
/** Calls a job's review may make (EX_REVIEW_CALLS). */
|
||||
reviewCalls?: number;
|
||||
},
|
||||
) {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Suggestions and what was decided about them. Derived data, so they live on the server under
|
||||
* <IE_DATA>/libraries/<id>/links/pending.json, one file per library, and never in the library.
|
||||
* <EX_DATA>/libraries/<id>/links/pending.json, one file per library, and never in the library.
|
||||
*
|
||||
* A scan replaces what was pending for its node, but what was decided is kept: the model
|
||||
* reviewer's verdict (link or not, and why), a person's decision, and when an approved link was
|
||||
|
||||
@@ -22,7 +22,7 @@ import type { Suggestion } from "./scan";
|
||||
/** Proposals per call. */
|
||||
export const BATCH = 60;
|
||||
|
||||
/** Calls a background job may make, unless IE_REVIEW_CALLS says otherwise. */
|
||||
/** Calls a background job may make, unless EX_REVIEW_CALLS says otherwise. */
|
||||
export const JOB_CALLS = 50;
|
||||
/** Calls the scan after one edit may make. */
|
||||
export const SCAN_CALLS = 2;
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
* or POST { node, text, title, ancestors }
|
||||
* POST /api/links/jobs { scope: "node" | "library", node?, review? } → the job's state (node: a node's id, scanned with
|
||||
* everything under it; on the library root, the whole library); it runs in the background
|
||||
* (with review, the model reviewer judges what it finds, within IE_REVIEW_CALLS calls)
|
||||
* (with review, the model reviewer judges what it finds, within EX_REVIEW_CALLS calls)
|
||||
* GET /api/links/jobs → { job } (the current or last one)
|
||||
* DELETE /api/links/jobs → cancel the running job
|
||||
* GET /api/links/status → embeddings, the node index, the pending count, the job
|
||||
|
||||
@@ -177,7 +177,7 @@ export const TUNING: Tuning = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Per-model adjustments. The test model (IE_EMBED=fake: hashed words) gives a 7-word description
|
||||
* Per-model adjustments. The test model (EX_EMBED=fake: hashed words) gives a 7-word description
|
||||
* and a paragraph a cosine of 0.1–0.3 when they share a word and 0 when they share none.
|
||||
*/
|
||||
const PROFILES: Record<string, Partial<Tuning>> = {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* From the single-library layout to the libraries layout (libraries.ts), once, when asked:
|
||||
*
|
||||
* npm run migrate migrate IE_DATA (or .data)
|
||||
* npm run migrate migrate EX_DATA (or .data)
|
||||
* npm run migrate -- --check a dry run: build, verify and report, writing nothing
|
||||
* npm run migrate -- [--check] DIR another data directory
|
||||
*
|
||||
@@ -402,7 +402,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolvePath(process.arg
|
||||
const unknown = args.filter((a) => a.startsWith("-") && a !== "--check");
|
||||
const dirs = args.filter((a) => !a.startsWith("-"));
|
||||
if (unknown.length || dirs.length > 1) {
|
||||
console.error("usage: npm run migrate [-- [--check] [DATA_DIR]] (DATA_DIR defaults to IE_DATA, else .data)");
|
||||
console.error("usage: npm run migrate [-- [--check] [DATA_DIR]] (DATA_DIR defaults to EX_DATA, else .data)");
|
||||
process.exit(2);
|
||||
}
|
||||
const r = migrateLibraries(dirs[0] ?? dataDir(), { check });
|
||||
|
||||
@@ -73,7 +73,7 @@ const INHERITED = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_EFFORT|CLAUDE_CODE_(ENTRYPOINT
|
||||
* OAuth token inside Claude Code, so neither is ever passed on.
|
||||
*/
|
||||
function childEnv(): Record<string, string | undefined> {
|
||||
const env: Record<string, string | undefined> = { ...process.env, CLAUDE_AGENT_SDK_CLIENT_APP: "infinispand/1.0.0" };
|
||||
const env: Record<string, string | undefined> = { ...process.env, CLAUDE_AGENT_SDK_CLIENT_APP: "explicata/1.0.0" };
|
||||
for (const k of Object.keys(env)) if (k === "ANTHROPIC_API_KEY" || k === "ANTHROPIC_AUTH_TOKEN" || INHERITED.test(k)) delete env[k];
|
||||
return env;
|
||||
}
|
||||
|
||||
+2
-2
@@ -7,8 +7,8 @@ import { fileURLToPath } from "node:url";
|
||||
/** The checkout's root directory. */
|
||||
export const ROOT = resolve(fileURLToPath(new URL(".", import.meta.url)), "..");
|
||||
|
||||
/** Where the library and everything derived from it are kept: IE_DATA, or .data in the checkout. */
|
||||
export const dataDir = () => resolve(process.env.IE_DATA ?? join(ROOT, ".data"));
|
||||
/** Where the library and everything derived from it are kept: EX_DATA, or .data in the checkout. */
|
||||
export const dataDir = () => resolve(process.env.EX_DATA ?? join(ROOT, ".data"));
|
||||
|
||||
/** A failure with the HTTP status it should be answered with. */
|
||||
export class HttpError extends Error {
|
||||
|
||||
+9
-9
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* Web research on the server: whether it is on (IE_WEB), the per-run caps (IE_WEB_SEARCHES,
|
||||
* IE_WEB_FETCHES), and the Messages API's web tools as the API-key route declares them.
|
||||
* Web research on the server: whether it is on (EX_WEB), the per-run caps (EX_WEB_SEARCHES,
|
||||
* EX_WEB_FETCHES), and the Messages API's web tools as the API-key route declares them.
|
||||
*
|
||||
* The browser asks for research on an agent turn; what it gets is decided here. With IE_WEB=off a
|
||||
* The browser asks for research on an agent turn; what it gets is decided here. With EX_WEB=off a
|
||||
* turn never carries web tools, whatever the browser asked, and the caps the browser sends are
|
||||
* replaced by the server's.
|
||||
*/
|
||||
@@ -23,14 +23,14 @@ const count = (v: string | undefined, d: number) => {
|
||||
return v !== undefined && v !== "" && Number.isInteger(n) && n >= 0 && n <= 50 ? n : d;
|
||||
};
|
||||
|
||||
/** IE_WEB is on or off (default on, when there is a model at all); anything else is off, said once. */
|
||||
/** EX_WEB is on or off (default on, when there is a model at all); anything else is off, said once. */
|
||||
export function webConfig(env: Record<string, string | undefined>, hasModel: boolean): WebConfig {
|
||||
const caps = { searches: count(env.IE_WEB_SEARCHES, DEFAULT_LIMITS.searches), fetches: count(env.IE_WEB_FETCHES, DEFAULT_LIMITS.fetches) };
|
||||
const wanted = env.IE_WEB ?? "on";
|
||||
const caps = { searches: count(env.EX_WEB_SEARCHES, DEFAULT_LIMITS.searches), fetches: count(env.EX_WEB_FETCHES, DEFAULT_LIMITS.fetches) };
|
||||
const wanted = env.EX_WEB ?? "on";
|
||||
if (!hasModel) return { on: false, ...caps, why: "no model is configured" };
|
||||
if (wanted === "off") return { on: false, ...caps, why: "IE_WEB=off" };
|
||||
if (wanted !== "on") return { on: false, ...caps, why: `IE_WEB=${wanted} is not on or off` };
|
||||
if (caps.searches === 0 && caps.fetches === 0) return { on: false, ...caps, why: "IE_WEB_SEARCHES and IE_WEB_FETCHES are both 0" };
|
||||
if (wanted === "off") return { on: false, ...caps, why: "EX_WEB=off" };
|
||||
if (wanted !== "on") return { on: false, ...caps, why: `EX_WEB=${wanted} is not on or off` };
|
||||
if (caps.searches === 0 && caps.fetches === 0) return { on: false, ...caps, why: "EX_WEB_SEARCHES and EX_WEB_FETCHES are both 0" };
|
||||
return { on: true, ...caps };
|
||||
}
|
||||
|
||||
|
||||
+6
-6
@@ -15,7 +15,7 @@
|
||||
*
|
||||
* Every request goes through one serial queue with a minimum spacing, priority for interactive
|
||||
* calls, Retry-After / 429 / 503 / maxlag handling, and a descriptive User-Agent. Results are
|
||||
* cached on disk under <IE_DATA>/wiki-cache/, so scanning the same text twice costs nothing.
|
||||
* cached on disk under <EX_DATA>/wiki-cache/, so scanning the same text twice costs nothing.
|
||||
* Nothing here throws into a caller: failures come back as { ok: false, reason }.
|
||||
*
|
||||
* Only the candidate phrase or the search query itself is ever sent, never surrounding text.
|
||||
@@ -207,7 +207,7 @@ export function validContact(contact: string | undefined): string | null {
|
||||
|
||||
/** The User-Agent: generic by default; never the owner's name, host or paths unless they supply a contact. */
|
||||
export function userAgent(contact: string | null): string {
|
||||
return contact ? `Infinispand/0.1 (${contact})` : "Infinispand/0.1 (personal knowledge tool)";
|
||||
return contact ? `Explicata/0.1 (${contact})` : "Explicata/0.1 (personal knowledge tool)";
|
||||
}
|
||||
|
||||
interface WikiOptions {
|
||||
@@ -930,12 +930,12 @@ export class WikiClient {
|
||||
const MODIFIED = "Adapted: references, navigation boxes, infoboxes, edit links and images removed.";
|
||||
|
||||
let shared: WikiClient | null = null;
|
||||
/** The server's client, configured from IE_DATA, IE_WIKI_LANG and IE_WIKI_CONTACT. */
|
||||
/** The server's client, configured from EX_DATA, EX_WIKI_LANG and EX_WIKI_CONTACT. */
|
||||
export function wiki(): WikiClient {
|
||||
if (!shared) {
|
||||
shared = new WikiClient({ lang: process.env.IE_WIKI_LANG, contact: process.env.IE_WIKI_CONTACT });
|
||||
if (process.env.IE_WIKI_CONTACT && !shared.contact) {
|
||||
console.warn("IE_WIKI_CONTACT is not an email address, an http(s) URL or User:Name; sending the generic User-Agent.");
|
||||
shared = new WikiClient({ lang: process.env.EX_WIKI_LANG, contact: process.env.EX_WIKI_CONTACT });
|
||||
if (process.env.EX_WIKI_CONTACT && !shared.contact) {
|
||||
console.warn("EX_WIKI_CONTACT is not an email address, an http(s) URL or User:Name; sending the generic User-Agent.");
|
||||
}
|
||||
process.once("exit", () => shared?.flush());
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* A stand-in Wikipedia for tests and offline work (IE_WIKI=mock). `mockWikiFetch` answers every
|
||||
* A stand-in Wikipedia for tests and offline work (EX_WIKI=mock). `mockWikiFetch` answers every
|
||||
* URL server/wiki.ts builds, in the shapes the real APIs return (docs/wikipedia.md §2), from a
|
||||
* few short articles written for the purpose. The HTML imitates action=parse output, junk
|
||||
* included (reference markers, infoboxes, navboxes, hatnotes, TemplateStyles), so the real
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* Answers: 200 { ok: true, ... }; 400 bad input; 404 { ok: false, reason: "missing" };
|
||||
* 503 { ok: false, reason, retryAfter } when Wikipedia is unreachable or asked us to wait.
|
||||
* A request the browser abandons (a superseded keystroke) is dropped from the queue unsent.
|
||||
* With IE_WIKI=off the server wires in wikiOff instead: every route answers 503 reason "off".
|
||||
* With EX_WIKI=off the server wires in wikiOff instead: every route answers 503 reason "off".
|
||||
*/
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { HttpError, abortOnClose, sendJson as send } from "./util";
|
||||
@@ -125,9 +125,9 @@ export function wikiRoutes(client: () => WikiClient) {
|
||||
};
|
||||
}
|
||||
|
||||
/** IE_WIKI=off: the routes exist, so the UI can tell "turned off" from "unreachable", but none works. */
|
||||
/** EX_WIKI=off: the routes exist, so the UI can tell "turned off" from "unreachable", but none works. */
|
||||
export async function wikiOff(_req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
|
||||
if (!url.pathname.startsWith("/api/wiki/")) return false;
|
||||
send(res, 503, { ok: false, reason: "off", message: "Wikipedia is turned off on this server (IE_WIKI=off)." });
|
||||
send(res, 503, { ok: false, reason: "off", message: "Wikipedia is turned off on this server (EX_WIKI=off)." });
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user