167 lines
9.7 KiB
JavaScript
167 lines
9.7 KiB
JavaScript
// #1873 ride-default slice 1: the rules for "Ride all", which adds the instance's model proxy
|
|
// (the cliproxy model provider) to the owner's existing organizations. Pure functions: the
|
|
// Console wiring (webui cli.mjs) reads each organization and its bus, and admin-control runs them.
|
|
import { usableModel } from '../../plugins/model-provider/cliproxy/index.mjs';
|
|
|
|
export { usableModel };
|
|
const has = (list, name) => Array.isArray(list) && list.includes(name);
|
|
|
|
// The model providers one change-log change shows before and after, by the change's path: the
|
|
// list itself, the plugins object, or the whole document. Any other path shows none.
|
|
function providersOf(change) {
|
|
const at = value => change?.path === 'plugins.model-provider' ? value
|
|
: change?.path === 'plugins' ? value?.['model-provider']
|
|
: change?.path === '' ? value?.plugins?.['model-provider'] : undefined;
|
|
return [at(change?.old), at(change?.new)];
|
|
}
|
|
const touchesProviders = path => path === '' || path === 'plugins' || path === 'plugins.model-provider';
|
|
|
|
// What the organization's change log shows of cliproxy, from its committed writes: `removed` when
|
|
// a write took it off, `seen` when any write shows it on the organization before or after, or wrote
|
|
// the providers without logging their values (a paths-only entry). A log that cannot be read
|
|
// answers null, and the caller skips the organization as unreadable.
|
|
export function cliproxyHistory(text) {
|
|
if (typeof text !== 'string') return null;
|
|
let removed = false, seen = false;
|
|
try {
|
|
for (const line of text.split('\n')) {
|
|
if (!line.trim()) continue;
|
|
const event = JSON.parse(line);
|
|
if (event?.state !== 'committed' || !Array.isArray(event.changes)) continue;
|
|
for (const change of event.changes) {
|
|
if (!touchesProviders(change?.path)) continue;
|
|
if (!Object.hasOwn(change, 'old') && !Object.hasOwn(change, 'new')) { seen = true; continue; }
|
|
const [before, after] = providersOf(change);
|
|
if (has(before, 'cliproxy') && !has(after, 'cliproxy')) removed = true;
|
|
if (has(before, 'cliproxy') || has(after, 'cliproxy')) seen = true;
|
|
}
|
|
}
|
|
return { removed, seen };
|
|
} catch { return null; }
|
|
}
|
|
export function cliproxyRemoved(text) { const h = cliproxyHistory(text); return h === null ? null : h.removed; }
|
|
|
|
// The organizations the proxy's own receipts (proxy-admin.jsonl) show cliproxy was or may have
|
|
// been on: each ride-all receipt's added list, each ride-move's org, each ride-removed's org (the
|
|
// organization admin page writes one before it saves a document without cliproxy), and each
|
|
// ride-intent's org (Ride all writes one before each plugins.set) unless a later ride-not-added for
|
|
// that organization shows the bus did not take it. Any line that does not parse, and any ride
|
|
// record of the wrong shape, answers null: the caller then skips every organization without
|
|
// cliproxy as unreadable. Text that is not a string answers null too.
|
|
const RIDE_ORG = new Set(['ride-move', 'ride-removed', 'ride-intent', 'ride-not-added']);
|
|
export function riddenOrgs(text) {
|
|
if (typeof text !== 'string') return null;
|
|
const ids = new Set(), pending = new Set();
|
|
for (const line of text.split('\n')) {
|
|
if (!line.trim()) continue;
|
|
let r; try { r = JSON.parse(line); } catch { return null; }
|
|
if (!r || typeof r !== 'object' || Array.isArray(r)) return null;
|
|
if (r.op === 'ride-all') {
|
|
if (!Array.isArray(r.added) || !r.added.every(id => typeof id === 'string')) return null;
|
|
for (const id of r.added) ids.add(id);
|
|
} else if (RIDE_ORG.has(r.op)) {
|
|
if (typeof r.org !== 'string') return null;
|
|
if (r.op === 'ride-intent') pending.add(r.org);
|
|
else if (r.op === 'ride-not-added') pending.delete(r.org);
|
|
else ids.add(r.org);
|
|
}
|
|
}
|
|
for (const id of pending) ids.add(id);
|
|
return ids;
|
|
}
|
|
|
|
// The local part of the decision, with no bus call: what Ride all does with one organization
|
|
// before it asks the organization's bus anything. An organization that uses cliproxy now (and is
|
|
// not a fixture organization) is already riding, whatever its history. One without cliproxy now
|
|
// that had it, or may have had it, is removed: its change log or the proxy's receipts show it
|
|
// (`ridden` is true from the receipts, null when they cannot be read).
|
|
export function localRide({ fixture, cliproxy, changes, ridden = false }) {
|
|
if (typeof fixture !== 'boolean' || typeof cliproxy !== 'boolean') return 'unreadable';
|
|
if (cliproxy && !fixture) return 'already';
|
|
const history = cliproxyHistory(changes);
|
|
if (history === null || (ridden === null && !cliproxy)) return 'unreadable';
|
|
if (history.removed || (!cliproxy && (ridden === true || history.seen))) return 'removed';
|
|
if (fixture) return 'fixture';
|
|
return 'ready';
|
|
}
|
|
|
|
// One organization as Ride all reads it, without its bus: `read()` gives its document and
|
|
// `readLog()` the text of its change log. A document that cannot be read leaves `fixture` and
|
|
// `cliproxy` undefined, a log that does not exist yet is empty, and any other log failure is null;
|
|
// localRide names either as unreadable. `isFixture(doc)` is the CLI's own fixture test.
|
|
export function readRider({ id, read, readLog, isFixture }) {
|
|
let doc = null, changes = null;
|
|
try { doc = read(); } catch {}
|
|
try { changes = readLog(); } catch (e) { changes = e?.code === 'ENOENT' ? '' : null; }
|
|
const ok = !!doc && typeof doc === 'object';
|
|
return { id, fixture: ok ? isFixture(doc) === true : undefined,
|
|
cliproxy: ok ? (Array.isArray(doc.plugins?.['model-provider']) ? doc.plugins['model-provider'] : []).includes('cliproxy') : undefined, changes };
|
|
}
|
|
|
|
// The owner's models: `proxy` is true when the instance's proxy.json names a port. Each organization
|
|
// that lists cliproxy is asked for its routes at once, so a hung bus costs one timeout, not one each.
|
|
// It rides when its bus answers a ready catalogue; the models are the cliproxy rows those
|
|
// catalogues list, once each.
|
|
export async function ownerModelsFrom({ proxy, riders }) {
|
|
if (proxy !== true) return { proxy: false, riding: false, models: [] };
|
|
const catalogues = await Promise.all((Array.isArray(riders) ? riders : []).filter(r => r?.cliproxy === true)
|
|
.map(async r => { try { return (await r.call('routes'))?.catalogue; } catch { return null; } }));
|
|
const models = new Map(); let riding = false;
|
|
for (const catalogue of catalogues) {
|
|
if (catalogue?.status !== 'ready' || !Array.isArray(catalogue.models)) continue;
|
|
riding = true;
|
|
// A key two buses list keeps the first usable row: one bus's stale row does not hide the model.
|
|
for (const m of catalogue.models) {
|
|
if (m?.module !== 'cliproxy' || typeof m.key !== 'string') continue;
|
|
if (!models.has(m.key) || (!usableModel(models.get(m.key)) && usableModel(m))) models.set(m.key, m);
|
|
}
|
|
}
|
|
return { proxy: true, riding, models: [...models.values()] };
|
|
}
|
|
|
|
// The owner's model for an organization: the first usable catalogue model from claude, else
|
|
// the first usable one, that serves every harness in `harnesses`.
|
|
export function pickModel(models, harnesses = []) {
|
|
const fits = (Array.isArray(models) ? models : []).filter(m => usableModel(m) && harnesses.every(h => m.harnesses.includes(h)));
|
|
return fits.find(m => m.upstream === 'claude') ?? fits[0] ?? null;
|
|
}
|
|
|
|
// A fixture organization moved to the owner's models: the fixture model provider becomes
|
|
// cliproxy, each fixture model entry goes, and every role that used one uses the owner's model.
|
|
// Answers { doc, model } or { reason } when no catalogue model serves the roles' harnesses.
|
|
export function fixtureMove(doc, models) {
|
|
const next = structuredClone(doc);
|
|
const fixtureKeys = Object.entries(next.launch?.models ?? {}).filter(([, m]) => m?.module === 'fixture').map(([key]) => key);
|
|
const uses = [];
|
|
const visit = vars => {
|
|
if (!vars || typeof vars !== 'object') return;
|
|
for (const prefix of ['', 'fallback.']) if (fixtureKeys.includes(vars[prefix + 'model'])) uses.push({ vars, prefix });
|
|
};
|
|
// A model is an agent-layer var: an organization's roles and each project's own agents carry one.
|
|
for (const role of Object.values(next.roles ?? {})) visit(role?.vars);
|
|
for (const project of Object.values(next.projects ?? {})) for (const agent of Object.values(project?.agents ?? {})) visit(agent?.vars);
|
|
const harnesses = [...new Set(uses.map(({ vars, prefix }) => vars[prefix + 'harness']).filter(h => typeof h === 'string'))];
|
|
const model = pickModel(models, harnesses);
|
|
if (!model) return { reason: 'no-model' };
|
|
for (const key of fixtureKeys) delete next.launch.models[key];
|
|
next.launch = next.launch ?? {}; next.launch.models = next.launch.models ?? {};
|
|
next.launch.models[model.key] = { provider: model.provider, model: model.model, module: 'cliproxy', upstream: model.upstream };
|
|
for (const { vars, prefix } of uses) vars[prefix + 'model'] = model.key;
|
|
const providers = (next.plugins?.['model-provider'] ?? []).filter(n => n !== 'fixture');
|
|
next.plugins = { ...(next.plugins ?? {}), 'model-provider': providers.includes('cliproxy') ? providers : [...providers, 'cliproxy'] };
|
|
return { doc: next, model };
|
|
}
|
|
|
|
// The move itself, through the organization service's existing whole-document update: read,
|
|
// change, validate, then write only if the revision read is still current. Owner-only twice:
|
|
// the Console route admits only the instance owner, and the service checks `ctx.principal`.
|
|
export async function moveFixtureOrg({ service, ctx, id, models }) {
|
|
const shown = await service.showOrg(ctx, id);
|
|
const moved = fixtureMove(shown.doc, models);
|
|
if (moved.reason) return { moved: false, reason: moved.reason };
|
|
const checked = await service.validateOrg(moved.doc);
|
|
if (!checked?.ok) return { moved: false, reason: 'invalid' };
|
|
await service.updateOrg(ctx, id, moved.doc, { ifRevision: shown.revision });
|
|
return { moved: true, model: moved.model.key };
|
|
}
|