Files
tiny-worlds/server/providers.mjs
T

119 lines
4.7 KiB
JavaScript
Raw Normal View History

// server/providers.mjs -- the provider entities.
//
// A provider is a first-class thing (developer, 2026-11-18): a user-named
// slug, a baseUrl, optional auth, and the op's default model spec for
// it -- {model, effort}, never params (those are per-turn, the <mind>
// verb's alone). state/config.json is the truth, written only by the
// server; the SPA is the surface, zero hand edits. No legacy shapes
// are read: the config is born in this shape, and shape changes come
// with one-time migrations, not permanent tolerance (the no-legacy
// rule, developer, 2026-11-18).
//
// The built-in singleton: opencode/free -- the anonymous, keyless
// fallback, the harness thesis in one entry (playable with zero
// secrets). It never carries auth: if it starts answering 401, that
// is upstream breakage to show as an error, never a prompt to fix.
// It is always available: removable only while another provider
// exists, auto-added (with its discovery) whenever the provider list
// is empty -- the self-heal rule, broadly: an error that can be
// mechanically fixed to a reasonable degree without requiring human
// input gets fixed.
/** @typedef {import('./shapes.mjs').ProviderCfg} ProviderCfg */
/** @typedef {import('./shapes.mjs').DeployCfg} DeployCfg */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { makeProvider } from './provider.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const CONFIG_PATH = path.join(ROOT, 'state', 'config.json');
/** The singleton: fixed slug, fixed base, structurally authless. */
export const OF_SLUG = 'opencode/free';
export const OF_BASE = 'https://opencode.ai/inference/openai/v1';
/** A slug: lowercase letters, digits, dashes; at most one slash
* (the singleton's own two-segment shape is the precedent). */
export const SLUG_RE = /^[a-z0-9][a-z0-9-]*(?:\/[a-z0-9][a-z0-9-]*)?$/;
/** @param {string} slug @returns {boolean} */
export function validSlug(slug) {
return SLUG_RE.test(slug) && slug.length <= 64;
}
/** @param {string} baseUrl @returns {boolean} */
export function validBaseUrl(baseUrl) {
try {
const u = new URL(baseUrl);
return u.protocol === 'https:' || u.protocol === 'http:';
} catch {
return false;
}
}
// --- the config file --------------------------------------------------------
/** @returns {DeployCfg} */
export function readConfig() {
try {
const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
if (cfg && Array.isArray(cfg.providers)) return cfg;
} catch { /* absent or unreadable -- the empty state is legal */ }
return { providers: [] };
}
/** @param {DeployCfg} cfg */
export function writeConfig(cfg) {
fs.mkdirSync(path.dirname(CONFIG_PATH), { recursive: true });
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2) + '\n');
}
/** @param {DeployCfg} cfg @param {string} slug @returns {?ProviderCfg} */
export function findProvider(cfg, slug) {
return cfg.providers.find((p) => p.slug === slug) ?? null;
}
/** The base-to-slug map -- what the routing errors and any
* base-keyed lookup read. */
/** @param {DeployCfg} cfg @returns {Map<string, string>} */
export function slugMap(cfg) {
return new Map(cfg.providers.map((p) => [p.baseUrl.replace(/\/+$/, ''), p.slug]));
}
/** Apply a mutated config: persist it and rebuild the context's
* clients. Every mutation goes through here -- the file and the map
* can never disagree.
* @param {import('./shapes.mjs').Ctx} ctx @param {DeployCfg} cfg @returns {DeployCfg} */
export function applyConfig(ctx, cfg) {
writeConfig(cfg);
ctx.providerCfg = cfg;
ctx.providers = new Map(cfg.providers.map((p) => [p.slug, makeProvider(p)]));
return cfg;
}
// --- the singleton ----------------------------------------------------------
/** Add the opencode/free singleton. Idempotent: returns null when it
* is already present (the add modal disables the choice, this is
* the backstop).
* @param {DeployCfg} cfg @returns {?ProviderCfg} */
export function addBuiltin(cfg) {
if (findProvider(cfg, OF_SLUG)) return null;
/** @type {ProviderCfg} */
const p = { slug: OF_SLUG, baseUrl: OF_BASE, default: null };
cfg.providers.push(p);
return p;
}
/** The removal guard (developer, 2026-11-18): the singleton goes only when
* a custom provider stands in its place -- the empty list is an
* error state, and the fallback is what keeps it unreachable.
* @param {DeployCfg} cfg @param {string} slug @returns {string} an error message, or '' when removable */
export function removalGuard(cfg, slug) {
if (slug !== OF_SLUG) return '';
if (cfg.providers.length > 1) return '';
return 'opencode/free is the anonymous fallback -- it is removable only while another provider is configured';
}