the provider round and the provider-flow round, plus the template and box packages
the provider round (2026-11-18, batteries-included): providers are first-class entities, the config is server-written state (state/config.json), and a fresh clone boots playable -- the opencode/free singleton auto-added and discovered on the empty list, playable with zero secrets. Every request resolves a full spec {provider, model, effort}: no unset effort, the per-run params layer retired, the mind verb the only sampling source. The registry is per-provider sections (state/models.json), refine caches adjudications under the double spec tuple (state/refine-cache.json), run picks are invalidatable (a removed provider or drifted model blocks the run with the note naming what died), and the housekeeper inherits the player spec's provider default (#16 closed). The no-legacy pass died the same day it shipped: bootImport deleted (server.json is bind + contwin), the registry's v1/v2 in-memory migrations deleted (models.json rewritten on disk into the per-provider shape), bare-string model picks deleted (Chloe's run.json migrated to spec objects, shape-preserving), the clerk's create model arg deleted, apiKeyEnv and the contextWindow alias gone. The live arc proven from a bare boot: invite minted, o/f auto-added, a custom provider with a bogus key (the recognizable 401), the auth fixed (13 models), the default pair selected, and a real glm-5.3 turn through the full path. Two live findings: opencode.ai serves 89 models keyless but 401s an empty Bearer header (the auth header rides only when a key exists), and the failure log line rides stderr.
the provider-flow round (2026-11-19, GM-designed): discovery IS the probe. The add takes only the endpoint -- {slug, baseUrl} or {builtin: true}, an apiKey in the body 400s (the auth route is the only key path) -- and a working keyless listing never sees a key field. A 401/403 stands the provider broken: the entity carries a probe record (outcome ok/auth/error, detail, at), the card opens the ask, and only the explicit acts move the record -- add, key, remove-key, discover; usage errors are transient and the op's to fix, nothing in the runtime flips provider state. The auth route is probe-then-save: the candidate key checks on reception, saves only on success -- a still-refused key never reaches the config, the previous state returns, the ask repeats. Every other discovery failure refuses the add outright with rollback: an endpoint that cannot answer is not a provider, nothing stands (the old code let it stand on any failure). The remove-key control (custom providers, armed) clears and re-probes: a provider gone public lands working keyless, a locked one re-opens the ask -- which is the key-replacement path. o/f never asks in any state: its auth failures are upstream breakage to show, not a prompt. The universal retry rule: NO automatic retries anywhere -- every inference call is user-initiated (the send, the housekeeping run, the refine) and every act has its manual retry; the curator's one auto-retry (the 2026-11-17 hiccup lesson) is deleted, the machine-label fallback the designed outcome. And failures never cache (GM: a failure is the absence of a measurement, not a measurement) -- the adjudication cache skips inference:false entries, the receipt line says "never cached, retried at every refine", and a transient battery error can never pin a false verdict; gev's 400s cost one cheap probe per refine and self-heal the day the backend learns tools. En-route fix the smoke earned: the create route validated body.spec AFTER the clerk built the run dir -- a refused spec left an orphan run (restart-check's exact count caught the sixth run); the spec validates first now, nothing lands on refusal.
the sheet's transport at the lint: the record is the only channel, the tag is view machinery composed by renderView, never authored by anyone -- the authored gate names the tag in any content (hers would never apply and primes the guarded emission; GM prose rides the view and story raw, the GM-side strips do not know it), names a sheet record on her turn, and checks object-ness on GM-turn records and boundary state notes both kinds; her emitted sheet in a carried tail stays legitimate history (the log keeps guard-conflicted emissions verbatim, and a stop can move one into the slidwin). The carryover editor teaches its own format now: a per-file hint between the editor and the save bar (one JSON object per line; status and agenda ride her turns; the sheet rides yours as the "sheet" field, never as a tag; the sigils and $VARS expand at start on the authored opening only).
the packages: template (the base for new packages -- the mood-indexed voice examples, the settings comment convention, non-playable as-is) and box (the sheet's first consumer: an incremental-game economy as ERP, GP and BP as two currencies with the room pushing her to fund her own punishments; the opening turn third-person per the typography ruling, ending on the display that needs a second read; the amnesiac rings empty by design; the erased name reading "(redacted)" after sigil expansion). The review found and fixed: both carryovers were pretty-printed JSON with duplicate keys -- unstartable under every per-line reader, flattened to true JSONL; the box's opening sheet rode her authored prose -- dead on every surface (the scan reads GM-turn records only, the strips eat it) and priming the exact emission the guard conflicts -- moved to the GM turn's sheet record, the override's shape; the gm.md "take of leave" typo fixed in all three packages.
the lint's rule 4 scoped to the substrate (GM, 2026-11-19): a banned word in a package's prose is fine -- the packages are the fiction and their words are the story's; README and the root prompts stay patrolled, and the box's "Or windows" is an architectural plural in a padded cell.
verified: typecheck green both programs; smoke ALL PASS (+27 the provider-flow battery: apiKey-on-add 400, the dead-endpoint refusal with config rollback, the auth-standing card with its probe record, probe-then-save both ways, the remove-key round trip, the o/f guards, the failures-never-cache proof over mock-fail -- verdict with the marker, absent from the cache file, re-probed fresh while the passing three serve from cache, not selectable, no orphan run; +8 the sheet-transport lint battery); restart + reminder checks green; a browser pass driving the whole add-flow machine on a mock+debug server (the hidden key field opening on the 401, the key landing through the auth route, the remove-key round trip re-opening the ask, the dead add refusing with the banner and no card, zero console errors beyond the expected 401/500 resource lines); check-repo clean with the box's windows. detention stays untracked WIP, untouched.
This commit is contained in:
+391
-116
@@ -26,12 +26,13 @@ import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { makeProvider } from './provider.mjs';
|
||||
import * as providers from './providers.mjs';
|
||||
import { clerkRaw, clerkRawJson, clerkJson, clerk } from './clerk.mjs';
|
||||
import * as bundle from './bundle.mjs';
|
||||
import * as session from './session.mjs';
|
||||
import * as housekeeping from './housekeeping.mjs';
|
||||
import { effectiveContents } from './variants.mjs';
|
||||
import { gmTurn, answerAsk, openingCall, HttpError, resolveParams } from './loop.mjs';
|
||||
import { gmTurn, answerAsk, openingCall, HttpError, specFromMeta, gateSpec } from './loop.mjs';
|
||||
import * as users from './users.mjs';
|
||||
import { forkRun } from './fork.mjs';
|
||||
import * as discovery from './discovery.mjs';
|
||||
@@ -40,20 +41,66 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const MOCK = process.argv.includes('--mock');
|
||||
const DEBUG = process.argv.includes('--debug'); // identity bypass: everyone is the superuser
|
||||
|
||||
const CONFIG_PATH = path.join(ROOT, 'server.json');
|
||||
if (!fs.existsSync(CONFIG_PATH)) {
|
||||
console.error('no server.json -- copy server.example.json and set your key in it (or via apiKeyEnv)');
|
||||
process.exit(1);
|
||||
// server.json is the static, non-secret remainder: bind and contwin.
|
||||
// Optional (GM, 2026-11-18) -- the provider entities live in
|
||||
// state/config.json (server-written, SPA-managed). Nothing here gates
|
||||
// the boot: a fresh deployment with no config at all comes up
|
||||
// serving, mints the superuser invite, and shows the global
|
||||
// no-providers banner -- every consumer of providers treats "none"
|
||||
// as a loud 409, never a crash.
|
||||
/** @type {import('./shapes.mjs').ServerCfg} */
|
||||
let cfg = {};
|
||||
const SERVER_JSON = path.join(ROOT, 'server.json');
|
||||
if (fs.existsSync(SERVER_JSON)) {
|
||||
try {
|
||||
cfg = JSON.parse(fs.readFileSync(SERVER_JSON, 'utf8'));
|
||||
} catch {
|
||||
console.error('server.json does not parse -- fix it or remove it (the provider entities live in state/config.json)');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
const cfg = /** @type {import('./shapes.mjs').ServerCfg} */ (JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')));
|
||||
if (cfg.contextWindow && !cfg.contwin) console.warn('config: contextWindow was renamed to contwin - the meter stays null until fixed');
|
||||
const provider = makeProvider(cfg.endpoint ?? {});
|
||||
let providerCfg = providers.readConfig();
|
||||
// the self-heal rule (GM, 2026-11-18), stated broadly: an error that
|
||||
// can be mechanically fixed to a reasonable degree without requiring
|
||||
// human input gets fixed. The empty provider list is one: the
|
||||
// anonymous fallback is added and discovered, as a background job --
|
||||
// boot never blocks on the network, and a failure leaves the empty
|
||||
// state plus the admin block's banner, whose fix path is the same
|
||||
// add act. The mock world seeds its two synthetic providers instead
|
||||
// (offline, the same code path).
|
||||
/** @type {string[]} */
|
||||
const autoAdded = [];
|
||||
if (!providerCfg.providers.length) {
|
||||
if (MOCK) {
|
||||
providerCfg.providers.push(
|
||||
{ slug: 'mock-a', baseUrl: 'mock://a', default: null },
|
||||
{ slug: 'mock-b', baseUrl: 'mock://b', default: null },
|
||||
);
|
||||
autoAdded.push('mock-a', 'mock-b');
|
||||
} else {
|
||||
const p = providers.addBuiltin(providerCfg);
|
||||
if (p) autoAdded.push(p.slug);
|
||||
}
|
||||
providers.writeConfig(providerCfg);
|
||||
}
|
||||
const providersMap = new Map(providerCfg.providers.map((p) => [p.slug, makeProvider(p)]));
|
||||
// locks/enqueue are attached just below; the cast is the two-step that
|
||||
// lets the literal precede them
|
||||
const ctxBase = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
|
||||
const ctxBase = { mock: MOCK, cfg, providerCfg, providers: providersMap, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
|
||||
/** @type {Ctx} */
|
||||
const ctx = /** @type {Ctx} */ (ctxBase);
|
||||
|
||||
// the auto-added providers discover in the background -- no LLM
|
||||
// calls, one GET each, zero cost; a dead network shows as the probe
|
||||
// record on the card (o/f's auth failure reads as upstream breakage,
|
||||
// never a prompt) plus the banner, whose fix path is the same add act
|
||||
for (const slug of autoAdded) {
|
||||
console.log(`fresh deployment -- auto-added '${slug}', discovering`);
|
||||
void runProbe(slug)
|
||||
.then((s) => console.log(`auto-discovery of '${slug}': ${s.models.length} models scraped`))
|
||||
.catch((e) => console.error(`auto-discovery of '${slug}' failed: ${String(e.message ?? e).split('\n')[0]} -- the admin block's add act retries it`));
|
||||
}
|
||||
|
||||
// --- the per-run activity lock ---------------------------------------------------
|
||||
//
|
||||
// Serializes every async mutation span (turn, ask, start, the
|
||||
@@ -314,48 +361,293 @@ route('GET', '/api', async () => ({
|
||||
sessions: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, session: s.n, pendingAsk: !!s.pendingAsk })),
|
||||
}));
|
||||
|
||||
// --- models: the registry, and the op's discovery acts -------------------------
|
||||
// --- models and providers: the registry, the op's provider acts ----------------
|
||||
//
|
||||
// The registry (state/models.json) is the truth of selectable
|
||||
// models. Fresh deployments have none: model use is disabled until
|
||||
// the op discovers. Discover scrapes the provider surface -- API
|
||||
// metadata only, zero inference; refine runs the deterministic
|
||||
// battery and the curator pass (it sends real traffic and may cost
|
||||
// real money). Both are the superuser's.
|
||||
// The registry (state/models.json, per-provider sections) is the
|
||||
// truth of selectable models. The provider entities (state/
|
||||
// config.json) are the op's: add and remove from the SPA, discover
|
||||
// and refine per provider. Both surfaces below are the superuser's
|
||||
// except GET /api/models (the model box reads it, any signed-in
|
||||
// user).
|
||||
|
||||
/** The effective deployment default per role: the op's server.json
|
||||
* pick wins, else the registry's discovered default. */
|
||||
/** @returns {{ player?: ?string, housekeeper?: ?string }} */
|
||||
function effectiveDefaults() {
|
||||
/** The per-provider payload the model box and the admin block read. */
|
||||
/** @typedef {import('./shapes.mjs').JobState} JobState */
|
||||
/** @returns {{ providers: { slug: string, phase: 'none'|'preliminary'|'refined', discovered: ?string, refined: ?string, curator: ?string, recommendation: ?{ model: string, effort: string }, default: ?{ model: string, effort: string }, models: import('./shapes.mjs').RegistryModel[], job: ?JobState, probe: ?{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string }, hasKey: boolean }[] }} */
|
||||
function modelsPayload() {
|
||||
const reg = discovery.registry();
|
||||
return {
|
||||
player: ctx.cfg.models?.player ?? reg?.defaults.player ?? undefined,
|
||||
housekeeper: ctx.cfg.models?.housekeeper ?? reg?.defaults.housekeeper ?? undefined,
|
||||
providers: ctx.providerCfg.providers.map((p) => {
|
||||
const section = reg?.providers[p.slug] ?? null;
|
||||
return {
|
||||
slug: p.slug,
|
||||
phase: section?.phase ?? 'none',
|
||||
discovered: section?.discovered ?? null,
|
||||
refined: section?.refined ?? null,
|
||||
curator: section?.curator ?? null,
|
||||
recommendation: section?.recommendation ?? null,
|
||||
default: p.default ?? null,
|
||||
models: section?.models ?? [],
|
||||
job: discovery.jobState(ctx, p.slug),
|
||||
probe: p.probe ?? null,
|
||||
hasKey: !!p.apiKey,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
route('GET', '/api/models', async () => {
|
||||
const reg = discovery.registry();
|
||||
route('GET', '/api/models', async () => modelsPayload());
|
||||
|
||||
/** The providers' default specs: the create flow's pre-select, and
|
||||
* what a pick-less housekeeper inherits. */
|
||||
/** @returns {{ slug: string, default: ?{ model: string, effort: string } }[]} */
|
||||
function providerDefaults() {
|
||||
return ctx.providerCfg.providers.map((p) => ({ slug: p.slug, default: p.default ?? null }));
|
||||
}
|
||||
|
||||
/** The run's per-role spec health, read-only: the invalidation
|
||||
* surface the table renders as a note before any send refuses. An
|
||||
* unset housekeeper is not an error -- it inherits the player
|
||||
* spec's provider default (the same resolution the pass runs). */
|
||||
/** @param {string} runId @returns {{ player: RoleHealth, housekeeper: RoleHealth }} */
|
||||
function roleHealth(runId) {
|
||||
/** @typedef {{ spec: ?{ provider: string, model: string, effort: string }, ok: boolean, note: ?string, inherited: boolean }} RoleHealth */
|
||||
/** @param {'player'|'housekeeper'} role @returns {RoleHealth} */
|
||||
const health = (role) => {
|
||||
const meta = bundle.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
||||
try {
|
||||
const spec = specFromMeta(meta.models?.[role] ?? null, role);
|
||||
if (spec) {
|
||||
gateSpec(ctx, spec, role);
|
||||
return { spec, ok: true, note: null, inherited: false };
|
||||
}
|
||||
if (role === 'player') {
|
||||
return { spec: null, ok: false, note: 'no player model set for this run -- pick one in the model box', inherited: false };
|
||||
}
|
||||
// the housekeeper inherits: the player spec's provider's default
|
||||
const player = specFromMeta(meta.models?.player ?? null, 'player');
|
||||
const def = player ? ctx.providerCfg.providers.find((p) => p.slug === player.provider)?.default ?? null : null;
|
||||
if (def) {
|
||||
const inherited = { provider: /** @type {{ provider: string }} */ (player).provider, model: def.model, effort: def.effort };
|
||||
gateSpec(ctx, inherited, 'housekeeper');
|
||||
return { spec: inherited, ok: true, note: null, inherited: true };
|
||||
}
|
||||
return { spec: null, ok: false, note: 'no housekeeper pick, and no provider default to inherit', inherited: false };
|
||||
} catch (e) {
|
||||
return { spec: null, ok: false, note: String(/** @type {Error} */ (e).message ?? e), inherited: false };
|
||||
}
|
||||
};
|
||||
return { player: health('player'), housekeeper: health('housekeeper') };
|
||||
}
|
||||
|
||||
// the op's config detail: slugs, bases, key presence (the key itself
|
||||
// never leaves the server), defaults -- what the admin block edits
|
||||
route('GET', '/api/providers', async ({ user }) => {
|
||||
requireSuperuser(user);
|
||||
return {
|
||||
phase: reg?.phase ?? 'none',
|
||||
discovered: reg?.discovered ?? null,
|
||||
refined: reg?.refined ?? null,
|
||||
curator: reg?.curator ?? null,
|
||||
defaults: effectiveDefaults(),
|
||||
models: reg?.models ?? [],
|
||||
job: discovery.jobState(ctx),
|
||||
providers: ctx.providerCfg.providers.map((p) => ({
|
||||
slug: p.slug,
|
||||
baseUrl: p.baseUrl,
|
||||
hasKey: !!p.apiKey,
|
||||
default: p.default ?? null,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
route('POST', '/api/models/discover', async ({ user }) => {
|
||||
// the probe (GM, 2026-11-19): discovery IS the health check -- every
|
||||
// path that scrapes a provider records the outcome on the entity, so
|
||||
// the card reads the last probe, never a stored machine. 401/403 is
|
||||
// the ask (custom providers only -- an auth failure on o/f is
|
||||
// upstream breakage, shown as the error it is); everything else is
|
||||
// the error named. No runtime path probes: usage errors are transient
|
||||
// and the op's to fix eventually (a failed turn already landed its
|
||||
// req event, and the invalidation surface only answers removal).
|
||||
/** @param {string} slug @param {{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string }} probe */
|
||||
function setProbe(slug, probe) {
|
||||
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
|
||||
const p = cfgMut.providers.find((x) => x.slug === slug);
|
||||
if (!p) return; // removed mid-probe -- the record goes with the entity
|
||||
p.probe = probe;
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
}
|
||||
/** @param {string} slug @returns {Promise<import('./discovery.mjs').RegistrySection>} */
|
||||
async function runProbe(slug) {
|
||||
try {
|
||||
const section = await discovery.discover(ctx, slug);
|
||||
setProbe(slug, { outcome: 'ok', detail: `${section.models.length} models scraped`, at: new Date().toISOString() });
|
||||
return section;
|
||||
} catch (e) {
|
||||
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
||||
setProbe(slug, {
|
||||
outcome: err.status === 401 || err.status === 403 ? 'auth' : 'error',
|
||||
detail: String(err.message ?? e).split('\n')[0].slice(0, 200),
|
||||
at: new Date().toISOString(),
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// add a provider (GM, 2026-11-19): {builtin: true} or {slug,
|
||||
// baseUrl} -- never a key (the auth route is the only key path).
|
||||
// Discovery is the probe: an auth refusal (401/403) leaves the
|
||||
// provider standing broken -- the SPA asks for the key, checked on
|
||||
// reception; every other failure refuses the add outright, because an
|
||||
// endpoint that cannot answer is not a provider -- nothing stands.
|
||||
route('POST', '/api/providers', async ({ body, user }) => {
|
||||
requireSuperuser(user);
|
||||
const reg = await discovery.discover(ctx);
|
||||
return { ok: true, phase: reg.phase, models: reg.models.length };
|
||||
if (body.apiKey !== undefined && body.apiKey !== null) {
|
||||
throw new HttpError(400, 'apiKey does not ride the add -- send the endpoint alone; a 401/403 opens the key path');
|
||||
}
|
||||
const cfgMut = { providers: [...ctx.providerCfg.providers] };
|
||||
/** @type {import('./shapes.mjs').ProviderCfg} */ let p;
|
||||
if (body.builtin === true) {
|
||||
const added = providers.addBuiltin(cfgMut);
|
||||
if (!added) throw new HttpError(409, 'opencode/free is already on the provider list');
|
||||
p = added; // addBuiltin pushed it
|
||||
} else {
|
||||
const slug = String(body.slug ?? '').trim();
|
||||
const baseUrl = String(body.baseUrl ?? '').trim().replace(/\/+$/, '');
|
||||
if (!providers.validSlug(slug)) throw new HttpError(400, 'slug must be lowercase letters, digits, dashes (one slash allowed), e.g. my-shop');
|
||||
if (providers.findProvider(cfgMut, slug)) throw new HttpError(409, `a provider named '${slug}' already exists`);
|
||||
if (!providers.validBaseUrl(baseUrl)) throw new HttpError(400, 'baseUrl must be a valid http(s) URL');
|
||||
p = { slug, baseUrl, default: null };
|
||||
cfgMut.providers.push(p);
|
||||
}
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
let section;
|
||||
try {
|
||||
section = await runProbe(p.slug);
|
||||
} catch (e) {
|
||||
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
||||
if (err.status === 401 || err.status === 403) {
|
||||
// the add stands (the op keys it or removes it); the failure
|
||||
// carries its status for the SPA's password branch
|
||||
throw new HttpError(err.status, `provider '${p.slug}' added, but the listing was refused: ${err.message} -- send the API key`);
|
||||
}
|
||||
// every other failure refuses the add: roll back, nothing stands
|
||||
providers.applyConfig(ctx, { providers: ctx.providerCfg.providers.filter((x) => x.slug !== p.slug) });
|
||||
throw err;
|
||||
}
|
||||
return { ok: true, provider: p.slug, models: section.models.length };
|
||||
});
|
||||
|
||||
route('POST', '/api/models/refine', async ({ user }) => {
|
||||
// set or replace a custom provider's key (the o/f singleton never
|
||||
// takes one -- its purpose is to be the anonymous fallback; a 401
|
||||
// from it is upstream breakage, not a prompt). Probe-then-save (GM,
|
||||
// 2026-11-19): the candidate key is checked on reception -- a key
|
||||
// that still meets the refusal is never saved, the previous state
|
||||
// returns, and the ask stays open for the next attempt.
|
||||
route('POST', '/api/providers/:slug/auth', async ({ params, body, user }) => {
|
||||
requireSuperuser(user);
|
||||
return discovery.refine(ctx, user);
|
||||
const p = providers.findProvider(ctx.providerCfg, params.slug);
|
||||
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
|
||||
if (p.slug === providers.OF_SLUG) throw new HttpError(403, 'opencode/free never takes an API key -- it is the anonymous fallback');
|
||||
if (typeof body.apiKey !== 'string' || !body.apiKey.trim()) throw new HttpError(400, 'apiKey (a non-empty string) is required');
|
||||
const prev = ctx.providerCfg;
|
||||
const prevEntity = /** @type {import('./shapes.mjs').ProviderCfg} */ (prev.providers.find((x) => x.slug === p.slug));
|
||||
const cfgMut = { providers: prev.providers.map((x) => ({ ...x })) };
|
||||
const target = /** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug));
|
||||
target.apiKey = body.apiKey.trim();
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
try {
|
||||
const section = await runProbe(p.slug);
|
||||
return { ok: true, provider: p.slug, models: section.models.length };
|
||||
} catch (e) {
|
||||
// the failed candidate never saves: the previous state returns,
|
||||
// and this attempt's probe record rides back with it (the card
|
||||
// shows the last attempt, whatever it was)
|
||||
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
||||
const candidate = ctx.providerCfg.providers.find((x) => x.slug === p.slug);
|
||||
if (candidate?.probe) prevEntity.probe = candidate.probe;
|
||||
providers.applyConfig(ctx, prev);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// remove a custom provider's key (GM, 2026-11-19): the op's control
|
||||
// for a provider that went public -- or the first half of a key
|
||||
// replacement, the second half being the ask, which re-opens when
|
||||
// the keyless probe meets the 401 again. The removal stands whatever
|
||||
// the probe says: it is the op's deliberate act, not an add; the
|
||||
// probe outcome rides the response and the card.
|
||||
route('DELETE', '/api/providers/:slug/auth', async ({ params, user }) => {
|
||||
requireSuperuser(user);
|
||||
const p = providers.findProvider(ctx.providerCfg, params.slug);
|
||||
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
|
||||
if (p.slug === providers.OF_SLUG) throw new HttpError(403, 'opencode/free never takes an API key -- it is the anonymous fallback');
|
||||
if (!p.apiKey) throw new HttpError(404, `provider '${p.slug}' has no key to remove`);
|
||||
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
|
||||
const target = /** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug));
|
||||
delete target.apiKey;
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
try {
|
||||
const section = await runProbe(p.slug);
|
||||
return { ok: true, provider: p.slug, models: section.models.length };
|
||||
} catch (e) {
|
||||
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
||||
return {
|
||||
ok: true,
|
||||
provider: p.slug,
|
||||
probe: err.status === 401 || err.status === 403 ? 'auth' : 'error',
|
||||
detail: String(err.message ?? e).split('\n')[0].slice(0, 200),
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// remove a provider: the section and the adjudication cache entries
|
||||
// go with it; the runs that rode it invalidate at their next send
|
||||
// (the GM's table carries the note)
|
||||
route('DELETE', '/api/providers/:slug', async ({ params, user }) => {
|
||||
requireSuperuser(user);
|
||||
const slug = params.slug;
|
||||
const guard = providers.removalGuard(ctx.providerCfg, slug);
|
||||
if (guard) throw new HttpError(409, guard);
|
||||
const cfgMut = { providers: ctx.providerCfg.providers.filter((p) => p.slug !== slug) };
|
||||
if (cfgMut.providers.length === ctx.providerCfg.providers.length) {
|
||||
throw new HttpError(404, `no such provider: ${slug}`);
|
||||
}
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
discovery.deleteSection(slug);
|
||||
discovery.purgeCache(slug);
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
// re-run one provider's discovery: the scrape, the section reset to
|
||||
// preliminary (a refined section loses its battery -- the button
|
||||
// says so in the UI), and the probe record updated -- this manual
|
||||
// act is one of the only things that moves it
|
||||
route('POST', '/api/providers/:slug/discover', async ({ params, user }) => {
|
||||
requireSuperuser(user);
|
||||
const section = await runProbe(params.slug);
|
||||
return { ok: true, provider: params.slug, phase: section.phase, models: section.models.length };
|
||||
});
|
||||
|
||||
// the selection: the provider's default {model, effort} -- also the
|
||||
// refine curator. Validated against the provider's own registry.
|
||||
route('POST', '/api/providers/:slug/default', async ({ params, body, user }) => {
|
||||
requireSuperuser(user);
|
||||
const p = providers.findProvider(ctx.providerCfg, params.slug);
|
||||
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
|
||||
const model = String(body.model ?? '').trim();
|
||||
const effort = String(body.effort ?? '').trim();
|
||||
if (!model) throw new HttpError(400, 'model (an id from this provider\'s registry) is required');
|
||||
if (!discovery.EFFORT_LEVELS.includes(effort)) {
|
||||
throw new HttpError(400, `effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
|
||||
}
|
||||
const m = discovery.findModel(p.slug, model);
|
||||
if (!m) throw new HttpError(400, `model '${model}' is not in '${p.slug}'s registry -- run its discovery first`);
|
||||
if (m.inference === false) throw new HttpError(400, `model '${model}' failed the inference battery -- it is not selectable`);
|
||||
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
|
||||
/** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug)).default = { model, effort };
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
return { ok: true, provider: p.slug, default: { model, effort } };
|
||||
});
|
||||
|
||||
// refine one provider: the battery + the curator pass (the op's
|
||||
// selected default is the curator). Real traffic, real cost; the job
|
||||
// meters itself.
|
||||
route('POST', '/api/providers/:slug/refine', async ({ params, user }) => {
|
||||
requireSuperuser(user);
|
||||
return discovery.refine(ctx, params.slug, user);
|
||||
});
|
||||
|
||||
route('GET', '/api/packages', async () => {
|
||||
@@ -414,7 +706,8 @@ route('GET', '/api/runs', async () => {
|
||||
|
||||
// create: the pc's name is required (unique per package); the
|
||||
// package display name defaults to the package's own. The id is
|
||||
// anonymous, generated by the clerk.
|
||||
// anonymous, generated by the clerk. body.spec (the player pick, a
|
||||
// full {provider, model, effort}) lands in run.json after the copy.
|
||||
route('POST', '/api/runs', async ({ body, user }) => {
|
||||
const pkg = String(body.package ?? '').trim();
|
||||
const pc = String(body.pc ?? '').trim();
|
||||
@@ -422,9 +715,30 @@ route('POST', '/api/runs', async ({ body, user }) => {
|
||||
if (!pc) throw new HttpError(400, 'pc is required -- the main character\'s name, distinct per package');
|
||||
const name = body.name === undefined ? undefined : String(body.name);
|
||||
requireUser(user);
|
||||
const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
|
||||
// the spec validates before anything lands: a refused create leaves
|
||||
// no orphan run dir behind (the failures-never-cache smoke found
|
||||
// the old order -- create first, validate after)
|
||||
if (body.spec !== undefined) {
|
||||
const spec = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (body.spec);
|
||||
if (typeof spec.provider !== 'string' || typeof spec.model !== 'string' || typeof spec.effort !== 'string') {
|
||||
throw new HttpError(400, 'spec must be { provider, model, effort } -- see GET /api/models');
|
||||
}
|
||||
if (!discovery.EFFORT_LEVELS.includes(spec.effort)) {
|
||||
throw new HttpError(400, `spec.effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
|
||||
}
|
||||
if (!discovery.usable(spec.provider, spec.model)) {
|
||||
throw new HttpError(400, `spec model '${spec.model}' is not usable on '${spec.provider}' (not discovered, or failed the battery)`);
|
||||
}
|
||||
}
|
||||
const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []));
|
||||
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
|
||||
const run = JSON.parse(r.out);
|
||||
if (body.spec !== undefined) {
|
||||
const spec = /** @type {{ provider: string, model: string, effort: string }} */ (body.spec);
|
||||
const meta = bundle.runMeta(run.id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
||||
meta.models = { ...(meta.models ?? {}), player: { provider: spec.provider, model: spec.model, effort: spec.effort } };
|
||||
fs.writeFileSync(path.join(bundle.runDir(run.id), 'run.json'), JSON.stringify(meta, null, 2) + '\n');
|
||||
}
|
||||
return { run, dir: `runs/${run.id}` };
|
||||
});
|
||||
|
||||
@@ -457,12 +771,12 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
|
||||
owner,
|
||||
ownerName: owner == null ? null : userName(owner),
|
||||
models: meta?.models ?? {},
|
||||
params: meta?.params ?? {},
|
||||
modelDefaults: effectiveDefaults(),
|
||||
// the deployment layer of the knobs (server.json params): the
|
||||
// only default an unset knob can honestly resolve to -- the
|
||||
// provider's own serving defaults are unknown and stay unstated
|
||||
paramDefaults: cfg.params ?? {},
|
||||
// the invalidation surface: each resolved spec's health, so the
|
||||
// table can carry the note before a send ever 409s
|
||||
modelState: roleHealth(id),
|
||||
// the providers' default specs -- the create flow's pre-select,
|
||||
// and the fallback a pick-less role would inherit
|
||||
providerDefaults: providerDefaults(),
|
||||
},
|
||||
display: bundle.runDisplay(id),
|
||||
open: !!s,
|
||||
@@ -599,80 +913,44 @@ route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => {
|
||||
return { ok: true, vars: settings.vars };
|
||||
});
|
||||
|
||||
// the run's models and sampling knobs: per-run overrides of the
|
||||
// deployment defaults (server.json, else the registry's discovered
|
||||
// pick), selected from the registry (GET /api/models). Owner-only,
|
||||
// changeable at any time -- every call resolves fresh, so a
|
||||
// mid-session switch simply takes the next turn. null clears a role
|
||||
// back to its deployment default; a null knob clears the knob (for
|
||||
// reasoning_effort, clearing means the registry's measured default
|
||||
// rides again).
|
||||
const KNOBS = ['temperature', 'top_p', 'top_k', 'repetition_penalty', 'max_tokens', 'reasoning_effort'];
|
||||
// the run's model picks: full specs, selected from the registry (GET
|
||||
// /api/models). Owner-only, changeable at any time -- every call
|
||||
// resolves fresh, so a mid-session switch simply takes the next
|
||||
// turn. null clears a role back to its inheritance (the player to
|
||||
// nothing, the housekeeper to the player provider's default).
|
||||
route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
|
||||
const id = params.id;
|
||||
bundle.requireRun(id);
|
||||
requireOwner(user, id);
|
||||
for (const k of Object.keys(body)) {
|
||||
if (k !== 'player' && k !== 'housekeeper' && k !== 'params') throw new HttpError(400, `unknown field: ${k} -- player, housekeeper, params`);
|
||||
if (k !== 'player' && k !== 'housekeeper') throw new HttpError(400, `unknown field: ${k} -- player, housekeeper`);
|
||||
}
|
||||
const meta = bundle.runMeta(id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
||||
const reg = discovery.registry();
|
||||
const models = meta.models ?? {};
|
||||
const models = { ...(meta.models ?? {}) };
|
||||
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
|
||||
if (body[role] === undefined) continue;
|
||||
if (body[role] === null) { delete models[role]; continue; }
|
||||
const m = String(body[role]).trim();
|
||||
if (!m) throw new HttpError(400, `${role}: a model name, or null to fall back to the deployment default`);
|
||||
if (!discovery.usable(reg, m)) {
|
||||
throw new HttpError(400, `${role}: '${m}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ' -- the op has not run discovery yet'}`);
|
||||
const spec = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (body[role]);
|
||||
if (typeof spec !== 'object' || spec === null || Array.isArray(spec)
|
||||
|| typeof spec.provider !== 'string' || typeof spec.model !== 'string' || typeof spec.effort !== 'string') {
|
||||
throw new HttpError(400, `${role}: a full spec { provider, model, effort }, or null to clear -- see GET /api/models`);
|
||||
}
|
||||
models[role] = m;
|
||||
if (!ctx.providerCfg.providers.some((p) => p.slug === spec.provider)) {
|
||||
throw new HttpError(400, `${role}: no provider named '${spec.provider}' is configured`);
|
||||
}
|
||||
if (!discovery.EFFORT_LEVELS.includes(spec.effort)) {
|
||||
throw new HttpError(400, `${role}.effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
|
||||
}
|
||||
if (!discovery.usable(spec.provider, spec.model)) {
|
||||
throw new HttpError(400, `${role}: '${spec.model}' is not usable on '${spec.provider}' (not in its registry, or failed the battery)`);
|
||||
}
|
||||
models[role] = { provider: spec.provider, model: spec.model, effort: spec.effort };
|
||||
}
|
||||
if (Object.keys(models).length) meta.models = models;
|
||||
else delete meta.models;
|
||||
|
||||
if (body.params !== undefined) {
|
||||
if (typeof body.params !== 'object' || body.params === null || Array.isArray(body.params)) {
|
||||
throw new HttpError(400, 'params (an object of player/housekeeper knob objects) is required');
|
||||
}
|
||||
for (const role of Object.keys(body.params)) {
|
||||
if (role !== 'player' && role !== 'housekeeper') throw new HttpError(400, `unknown params role: ${role}`);
|
||||
const knobs = body.params[role];
|
||||
if (typeof knobs !== 'object' || knobs === null || Array.isArray(knobs)) {
|
||||
throw new HttpError(400, `params.${role} must be an object of knobs`);
|
||||
}
|
||||
for (const [k, v] of Object.entries(knobs)) {
|
||||
if (!KNOBS.includes(k)) throw new HttpError(400, `unknown knob: ${k} -- ${KNOBS.join(', ')}`);
|
||||
if (k === 'reasoning_effort') {
|
||||
// the enum knob: one of the ladder's levels, or null to
|
||||
// clear back to the measured default
|
||||
if (v !== null && !discovery.EFFORT_LEVELS.includes(String(v))) {
|
||||
throw new HttpError(400, `params.${role}.reasoning_effort must be one of ${discovery.EFFORT_LEVELS.join(', ')} -- or null to ride the model's measured default`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (v !== null && !Number.isFinite(v)) throw new HttpError(400, `params.${role}.${k} must be a number, or null to clear`);
|
||||
}
|
||||
}
|
||||
const rp = meta.params ?? {};
|
||||
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
|
||||
const knobs = body.params[role];
|
||||
if (knobs === undefined) continue;
|
||||
const cur = { ...(rp[role] ?? {}) };
|
||||
for (const [k, v] of Object.entries(knobs)) {
|
||||
if (v === null) delete cur[/** @type {keyof import('./shapes.mjs').RoleParams} */ (k)];
|
||||
else if (k === 'reasoning_effort') cur[/** @type {'reasoning_effort'} */ (k)] = String(v);
|
||||
else cur[/** @type {'temperature'|'top_p'|'top_k'|'repetition_penalty'|'max_tokens'} */ (k)] = Number(v);
|
||||
}
|
||||
if (Object.keys(cur).length) rp[role] = cur;
|
||||
else delete rp[role];
|
||||
}
|
||||
if (Object.keys(rp).length) meta.params = rp;
|
||||
else delete meta.params;
|
||||
}
|
||||
|
||||
fs.writeFileSync(path.join(bundle.runDir(id), 'run.json'), JSON.stringify(meta, null, 2) + '\n');
|
||||
return { ok: true, models: meta.models ?? {}, params: meta.params ?? {}, defaults: effectiveDefaults(), paramDefaults: cfg.params ?? {} };
|
||||
return { ok: true, models: meta.models ?? {}, modelState: roleHealth(id) };
|
||||
});
|
||||
|
||||
// the GM's notepad: the run's gm.md -- the owner's alone (#28's
|
||||
@@ -985,29 +1263,24 @@ route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
|
||||
|
||||
// the turn meter's read (GM, 2026-11-17): the live progress record
|
||||
// the streaming callback feeds, plus the scale the bar guesstimates
|
||||
// against -- the only true budget is max_tokens when the knobs set
|
||||
// one (reasoning counts inside it), else the session's own history:
|
||||
// her longest past turn in characters (thinking and prose both, the
|
||||
// units the meter counts). No history and no budget means no scale:
|
||||
// the client falls back to the chunk-driven animation. Owner-only
|
||||
// machinery; a plain read, never queued.
|
||||
// against -- the session's own history: her longest past turn in
|
||||
// characters (thinking and prose both, the units the meter counts).
|
||||
// No history means no scale: the client falls back to the
|
||||
// chunk-driven animation. (The old max_tokens budget layer is gone
|
||||
// with the per-run params: no surface sets one anymore -- GM,
|
||||
// 2026-11-18.) Owner-only machinery; a plain read, never queued.
|
||||
route('GET', '/api/runs/:id/progress', async ({ params, user }) => {
|
||||
requireOwner(user, params.id);
|
||||
const s = ctx.sessions.get(params.id);
|
||||
if (!s) return { inFlight: false, scale: null };
|
||||
// the max_tokens layer mirrors the loop's own resolution (the mind
|
||||
// rides over the run and deployment params); ~4 chars a token is
|
||||
// the meter's rough exchange rate -- a meter, not a ledger
|
||||
const eff = { ...resolveParams(ctx, params.id, 'player'), ...(s.mind ?? {}) };
|
||||
const budget = typeof eff.max_tokens === 'number' ? eff.max_tokens * 4 : null;
|
||||
let high = 0;
|
||||
for (const e of s.lines) {
|
||||
if (e.t !== 'msg' || e.m.role !== 'assistant') continue;
|
||||
const chars = (e.m.reasoning_content ?? '').length + (e.m.content ?? '').length;
|
||||
if (chars > high) high = chars;
|
||||
}
|
||||
const scale = budget ?? (high > 0 ? high : null);
|
||||
const scaleKind = budget ? 'budget' : (high > 0 ? 'history' : null);
|
||||
const scale = high > 0 ? high : null;
|
||||
const scaleKind = high > 0 ? 'history' : null;
|
||||
if (!s.progress) return { inFlight: false, scale, scaleKind };
|
||||
return { inFlight: true, ...s.progress, scale, scaleKind };
|
||||
});
|
||||
@@ -1187,5 +1460,7 @@ const server = http.createServer(async (req, res) => {
|
||||
const [cfgHost, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':');
|
||||
const host = DEBUG ? '127.0.0.1' : cfgHost;
|
||||
server.listen(Number(port ?? 7350), host, () => {
|
||||
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : (effectiveDefaults().player ?? 'no default model')} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`);
|
||||
const providerCount = ctx.providerCfg.providers.length;
|
||||
const discovered = Object.keys(discovery.registry()?.providers ?? {}).length;
|
||||
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : `${providerCount} provider(s), ${discovered} discovered`} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user