feat(model-proxy): Ride all puts the owner's existing organizations on the instance model proxy, and a cliproxy preset starts a new one on the owner's models (#1873, lane ride-default)

A cliproxy organization preset offers a model from the owner's catalogue and says in plain words
why it can't be used: no proxy, no riding bus answered, or no catalogue model is available. The
organization service passes an optional model to a preset's overlay; other presets ignore it.

Ride all, an instance-owner action on the Model proxy page, adds cliproxy to each organization
through that organization's own plugins.set. It skips and names an organization whose change log
shows cliproxy removed, whose bus is down, or whose bus has no proxy client. Proxy admin status
names it as the next step. A fixture organization is listed as using stand-in models; one more
confirmed click moves a stopped one to the owner's models through the organization service's
existing whole-document update at the revision read.

A fenced proxy then refuses each riding organization's launches with proxy-uncertain, a direct
anthropic route included.
This commit is contained in:
jason.woltje committed 2026-11-19 13:13:05 -06:00
1 parent 196505e6ef
commit 8200ea238c
14 files changed
+868 -22

No files matched your search

+72 -2
View File
@@ -5,6 +5,7 @@
import { homedir } from 'node:os';
import { fetchPinned } from './fetch.mjs';
import { PIN } from './common.mjs';
import { localRide } from './ride.mjs';
import { releaseState, initState, fenceState, initLockStatus, clearInitLock, appendReceipt, recentReceipts, createUnitControl, FILE_LABELS } from './admin.mjs';
export const proxyCode = (error, fallback) => (/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : fallback);
@@ -13,7 +14,12 @@ const failure = code => Object.assign(new Error(code), { code });
// `buses()` proves the init-lock condition "bus stopped" ({stopped, running:[label]}).
// `orgs()` lists the organizations this proxy serves: [{id, catalogue}]. `unit` and `fetch` are
// (and `pin`) seams for tests; the defaults run the real proxy-service.sh, systemctl and pinned fetch.
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], now = () => new Date(), env = process.env, pin = PIN }) {
// #1873 ride-default: `riders()` lists the owner's active organizations for Ride all, read locally:
// [{id, fixture, cliproxy, changes, call}] where `changes` is the text of the organization's change
// log and `call(verb, args)` reaches its bus as the owner. `ownerModels()` answers
// {proxy, riding, models} from the riding buses' catalogues. `move(id, models, principal)` moves a
// stopped fixture organization to the owner's models through the organization service.
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], riders = async () => [], ownerModels = async () => ({ proxy: false, riding: false, models: [] }), move = null, now = () => new Date(), env = process.env, pin = PIN }) {
const port = () => { try { return initState(configDir, dataRoot).settings?.port ?? null; } catch { return null; } };
const control = unit ?? createUnitControl({ instance, unitDir, port, env });
let job = { state: 'idle', step: null, receipt: null, error: null };
@@ -30,6 +36,28 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
async function unitStatus() {
try { return await control.status(); } catch (error) { return { unit: control.unit, installed: false, active: 'unknown', healthy: false, error: proxyCode(error, 'proxy-unit-failed') }; }
}
// Ride all, one organization: the local rules first, then the organization's bus, which must
// answer and must hold the proxy client. The bus decides the write (plugins.set) as it would
// for the owner on the Settings page. The answer names a reason, never bus or upstream text.
async function rideOne(rider) {
const id = rider.id, local = localRide(rider);
if (local === 'fixture') {
let running = true; try { await rider.call('plugins'); } catch { running = false; }
return { id, outcome: 'fixture', running };
}
if (local !== 'ready') return { id, outcome: local === 'already' ? 'already' : 'skipped', reason: local };
let current;
try { current = await rider.call('plugins'); } catch { return { id, outcome: 'skipped', reason: 'bus-down' }; }
try { await rider.call('proxy.accounts'); } catch (error) { return { id, outcome: 'skipped', reason: error?.code === 'not-configured' ? 'no-proxy-client' : 'proxy-check-failed' }; }
const providers = Array.isArray(current?.plugins?.['model-provider']) ? current.plugins['model-provider'] : [];
if (providers.includes('cliproxy')) return { id, outcome: 'already' };
try { await rider.call('plugins.set', { revision: current.revision, plugins: { 'model-provider': [...providers, 'cliproxy'] } }); }
catch (error) { return { id, outcome: 'failed', reason: /^[a-z][a-z-]{0,63}$/.test(error?.code ?? '') ? error.code : 'failed' }; }
return { id, outcome: 'added' };
}
async function rideSummary() {
try { return (await riders()).map(r => ({ id: r.id, state: localRide(r) })); } catch { return null; }
}
function nextSteps({ release, init, unitState, fence, lock }) {
if (!release.fetched || release.problem) return ['fetch'];
if (lock.present) return lock.clearable ? ['init-lock-clear'] : ['init-lock-wait'];
@@ -54,6 +82,10 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
const lock = init.lock ? initLockStatus({ configDir, dataRoot, buses: await buses() }) : { present: false, clearable: false, blockers: [] };
let organizations = null;
try { organizations = await orgs(); } catch { organizations = null; }
const ride = await rideSummary();
const next = nextSteps({ release, init, unitState, fence, lock });
// Ride all comes after the proxy runs with no fence, while an organization can still ride.
if (next[0] === 'accounts' && ride?.some(r => r.state === 'ready' || r.state === 'fixture')) next.push('ride-all');
return {
release: { version: release.version, panelVersion: release.panelVersion, fetched: release.fetched, verified: release.verified, problem: release.problem },
init: {
@@ -71,7 +103,8 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
// Ruling 8: the system config holds one proxy per instance; an organization's own proxy
// needs a config format that does not exist yet.
ownProxy: { available: false, state: 'not built', reason: 'This instance has one shared proxy. A separate proxy per organization is not built yet.' },
next: nextSteps({ release, init, unitState, fence, lock }),
ride,
next,
};
},
// Runs in the background; the page polls status for its step and receipt.
@@ -133,6 +166,43 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
return { cleared: result.cleared === true, receipt: receipt({ op: 'fence.clear', cleared: result.cleared === true, evidence: result.evidence ?? null }) };
});
},
// Ride all: adds cliproxy to each organization that can take it, and names every one it skips.
// Fixture organizations are listed, not changed: moving one spends real tokens, so it is a
// separate confirmed action (rideMove).
async rideAll() {
return exclusive('ride-all', async () => {
const list = await riders();
const results = [];
for (const rider of list) results.push(await rideOne(rider));
const added = results.filter(r => r.outcome === 'added').map(r => r.id);
const skipped = results.filter(r => r.outcome === 'skipped' || r.outcome === 'failed').map(r => ({ id: r.id, reason: r.reason }));
const fixtures = results.filter(r => r.outcome === 'fixture').map(r => ({ id: r.id, running: r.running }));
const already = results.filter(r => r.outcome === 'already').map(r => r.id);
return { added, already, skipped, fixtures, receipt: receipt({ op: 'ride-all', added, skipped, fixtures: fixtures.map(f => f.id) }) };
});
},
// Moves one stopped fixture organization to the owner's models. Its bus is refused at start
// beside a real proxy, so the organization service writes its document (the same whole-document
// update the organization's admin page uses); the owner starts its bus afterwards.
async rideMove({ org, principal } = {}) {
return exclusive('ride-move', async () => {
const rider = (await riders()).find(r => r.id === org);
if (!rider) return { org, moved: false, reason: 'unknown' };
const local = localRide(rider);
if (local !== 'fixture') return { org, moved: false, reason: local };
let running = true; try { await rider.call('plugins'); } catch { running = false; }
if (running) return { org, moved: false, reason: 'bus-running' };
if (typeof move !== 'function') return { org, moved: false, reason: 'not-available' };
const owner = await ownerModels();
if (owner?.proxy !== true) return { org, moved: false, reason: 'no-proxy' };
if (owner.riding !== true) return { org, moved: false, reason: 'no-riding-bus' };
let result;
try { result = await move(org, owner.models, principal); }
catch (error) { result = { moved: false, reason: /^[a-z][a-z-]{0,63}$/.test(error?.code ?? '') ? error.code : 'failed' }; }
if (!result?.moved) return { org, moved: false, reason: result?.reason ?? 'failed' };
return { org, moved: true, model: result.model, receipt: receipt({ op: 'ride-move', org, model: result.model }) };
});
},
async initLockClear() {
return exclusive('init-lock-clear', async () => ({ receipt: clearInitLock({ configDir, dataRoot, buses: await buses(), now }) }));
},
+115
View File
@@ -0,0 +1,115 @@
// #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);
// True when the organization's change log shows a committed write that removed cliproxy from
// its model providers: the owner took it off on purpose, so Ride all leaves it off. A log that
// cannot be read answers null, and the caller skips the organization as unreadable.
export function cliproxyRemoved(text) {
if (typeof text !== 'string') return null;
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) {
const [before, after] = change?.path === 'plugins.model-provider' ? [change.old, change.new]
: change?.path === 'plugins' ? [change.old?.['model-provider'], change.new?.['model-provider']] : [null, null];
if (has(before, 'cliproxy') && !has(after, 'cliproxy')) return true;
}
}
return false;
} catch { return null; }
}
// 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.
export function localRide({ fixture, cliproxy, changes }) {
if (typeof fixture !== 'boolean' || typeof cliproxy !== 'boolean') return 'unreadable';
const removed = cliproxyRemoved(changes);
if (removed === null) return 'unreadable';
if (removed) return 'removed';
if (fixture) return 'fixture';
if (cliproxy) return 'already';
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;
for (const m of catalogue.models) if (m?.module === 'cliproxy' && typeof m.key === 'string' && !models.has(m.key)) 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 };
}
@@ -0,0 +1,134 @@
// #1873 ride-default slice 1: once Ride all adds the model proxy to an organization, a fenced
// proxy refuses each of that organization's launches with proxy-uncertain, a direct anthropic
// route included. A real organization bus bound to the instance's proxy, a loopback stand-in for
// the proxy's management API (made-up key, kept in this test's memory), and the real Ride all.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { startBroker } from '../../bus/src/runtime.mjs';
import { busOrganization } from '../../bus/src/organization-context.mjs';
import { createProxyLock } from '../../bus/src/proxy-lock.mjs';
import { Registry } from '../../seat/src/session.mjs';
import { loadBusiness } from '../../organization/src/organization-config.mjs';
import { resolveInstance } from '../../organization/src/resolve.mjs';
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
import { createProxyAdmin } from '../src/admin-control.mjs';
const MANAGE = 'ride-fence-manage';
async function ridingBus(t) {
const root = fs.mkdtempSync(join(tmpdir(), 'ride-fence-')), configDir = join(root, 'config');
fs.mkdirSync(join(configDir, 'secrets'), { recursive: true, mode: 0o700 });
fs.mkdirSync(join(root, 'proxy'), { mode: 0o700 });
let keys = ['msk-ride-fence-sentinel'];
const server = http.createServer(async (req, res) => {
const chunks = []; for await (const c of req) chunks.push(c);
if (req.headers.authorization !== `Bearer ${MANAGE}`) { res.writeHead(401); res.end('{}'); return; }
if (req.url === '/v8/management/config/access/api-keys') {
if (req.method === 'PUT') keys = JSON.parse(Buffer.concat(chunks));
res.end(JSON.stringify(req.method === 'GET' ? keys : { status: 'ok' })); return;
}
if (req.url.startsWith('/v8/management/credentials')) { res.end(JSON.stringify({ files: [], observed_at: '2026-11-19T00:00:00Z' })); return; }
if (req.url.startsWith('/v8/management/config/api-keys/')) { res.end('[]'); return; }
res.writeHead(404); res.end('{}');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const port = server.address().port;
const rolesDir = rolesCopy(root), system = systemFor(root), doc = businessDoc(root, 'demo');
// A direct anthropic route and no model provider: before Ride all, no launch asks the proxy.
doc.plugins = { ...doc.plugins, harness: ['pi'] };
doc.launch.models['claude-opus-5-5'] = { provider: 'anthropic', model: 'claude-opus-5-5' };
doc.roles.coder.vars = { ...doc.roles.coder.vars, harness: 'pi', model: 'claude-opus-5-5', thinking: 'low' };
writeJson(join(configDir, 'businesses', 'demo.json'), doc);
fs.writeFileSync(join(configDir, 'secrets', 'proxy-management.key'), MANAGE, { mode: 0o600 });
const business = loadBusiness('demo', { dir: configDir, rolesDir }), resolved = {};
for (const instance of Object.keys(business.roles)) resolved[instance] = resolveInstance({ system, business, instance });
fs.mkdirSync(join(root, 'data'), { mode: 0o700 }); new Registry(join(root, 'data'));
const bus = await startBroker({ dataRoot: join(root, 'data'), businesses: { demo: busOrganization(business, resolved) },
organization: { dir: configDir, rolesDir, system }, proxy: { port, binary: '/fixture-unused' },
org: { id: 'demo' }, instanceDataRoot: root, instanceConfigDir: configDir });
t.after(async () => { await bus.close(); server.closeAllConnections(); await new Promise(r => server.close(r)); fs.rmSync(root, { recursive: true, force: true }); });
const human = bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
const call = async (verb, args = {}) => bus.broker.request(human, { verb, args });
const lock = createProxyLock({ stateDir: join(root, 'proxy'), identity: `${configDir}:${port}` });
const admission = async () => {
const current = JSON.parse(fs.readFileSync(join(configDir, 'businesses', 'demo.json'), 'utf8'));
const revision = (await call('plugins')).revision, entry = current.launch.models['claude-opus-5-5'];
return bus.modelAdmission({ business: 'demo', instance: 'coder', modelKey: 'claude-opus-5-5', harness: 'pi', revision, entry,
provider: entry.provider, model: entry.model, account: null, route: 'primary', transport: null });
};
return { root, configDir, bus, call, lock, admission, doc: () => JSON.parse(fs.readFileSync(join(configDir, 'businesses', 'demo.json'), 'utf8')) };
}
test('a fenced proxy refuses each riding organization\'s launches with proxy-uncertain, direct anthropic included', async t => {
const b = await ridingBus(t);
const dir = fs.mkdtempSync(join(tmpdir(), 'ride-fence-admin-')); t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const admin = createProxyAdmin({ dataRoot: dir, configDir: dir, unit: { status: async () => ({}) }, buses: async () => [], fetch: async () => ({}),
riders: async () => [{ id: 'demo', fixture: false, cliproxy: false, changes: '', call: b.call }] });
const ride = await admin.rideAll();
assert.deepEqual(ride.added, ['demo'], JSON.stringify(ride));
assert.deepEqual(b.doc().plugins['model-provider'], ['cliproxy']);
assert.equal(b.doc().launch.models['claude-opus-5-5'].module, undefined, 'the direct anthropic route stays as it was');
await b.lock.run(async () => b.lock.fence({ org: 'demo', op: 'ride-fence-test' }));
assert.deepEqual(await b.admission(), { allow: false, code: 'proxy-uncertain' });
assert.deepEqual((await admin.rideAll()).already, ['demo'], 'a second Ride all leaves a riding organization alone');
});
// The launcher half: on an instance with a model proxy, a direct anthropic route never asks the
// bus's admission until the organization lists a model provider. After Ride all it does, so the
// fenced answer above refuses the launch before any run exists.
test('after Ride all the launcher asks admission for a direct anthropic route and a fenced answer refuses the launch', async t => {
const { readFileSync } = fs;
const { createLauncher } = await import('../../cli/src/launcher.mjs');
const { initializeControl } = await import('../../processing-control/src/state.mjs');
const { fakeHarnesses, fixture, tmp, withoutHostCredentials } = await import('../../cli/tests/helpers.mjs');
// Ride all writes the organization's providers through its bus's plugins.set; this stand-in bus
// applies that write to the organization file the launcher reads.
const ride = async file => {
const dir = fs.mkdtempSync(join(tmpdir(), 'ride-fence-admin-')); t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const call = async (verb, args = {}) => {
const doc = JSON.parse(readFileSync(file, 'utf8'));
if (verb === 'plugins') return { revision: 'r1', plugins: doc.plugins };
if (verb === 'proxy.accounts') return { accounts: [] };
if (verb === 'plugins.set') { assert.equal(args.revision, 'r1'); doc.plugins = { ...doc.plugins, ...args.plugins }; fs.writeFileSync(file, JSON.stringify(doc)); return { revision: 'r2' }; }
throw Object.assign(Error('unexpected verb'), { code: 'invalid-request' });
};
const admin = createProxyAdmin({ dataRoot: dir, configDir: dir, unit: { status: async () => ({}) }, buses: async () => [], fetch: async () => ({}),
riders: async () => [{ id: 'acme', fixture: false, cliproxy: false, changes: '', call }] });
assert.deepEqual((await admin.rideAll()).added, ['acme']);
};
const launchOf = async riding => {
const root = tmp(t);
const f = fixture(root, 'acme', doc => {
doc.plugins = { ...doc.plugins, harness: ['pi'] };
doc.launch.models['claude-opus-5-5'] = { provider: 'anthropic', model: 'claude-opus-5-5' };
doc.roles.coder.vars = { harness: 'pi', model: 'claude-opus-5-5', thinking: 'low' };
return doc;
});
if (riding) await ride(join(root, 'config', 'businesses', 'acme.json'));
initializeControl(f.dataRoot); withoutHostCredentials(f.env, { piKey: true });
const ops = [];
const host = { business: 'acme', beforeClose: () => {}, op: async x => {
ops.push(x.op);
if (x.op === 'identity') return { business: 'acme', role: 'pm' };
if (x.op === 'mayLaunch') return { allow: true };
if (x.op === 'modelAdmission') return { allow: false, code: 'proxy-uncertain' };
if (x.op === 'authorizeLaunch') throw Object.assign(Error('fixture authorization stop'), { code: 'fixture-policy' });
return {};
} };
const makeLoader = await fakeHarnesses(t, { pi: null }, write => write('model-provider', 'cliproxy', `export * from ${JSON.stringify(new URL('../../plugins/model-provider/cliproxy/index.mjs', import.meta.url).href)};`));
const system = { ...JSON.parse(readFileSync(f.config, 'utf8')), proxy: { port: 1, binary: '/fixture-unused' } };
const launcher = createLauncher({ host, system, env: f.env, makeLoader, bwrap: '/usr/bin/true', log: () => {} });
return { answer: await launcher.fromSession('fixture-cap', 'coder'), ops };
};
const before = await launchOf(false);
assert.equal(before.ops.includes('modelAdmission'), false, JSON.stringify(before));
assert.equal(before.ops.includes('mayLaunch'), true, 'the before launch reached the limit checks');
assert.notDeepEqual(before.answer, { ok: false, error: 'proxy-uncertain' });
const after = await launchOf(true);
assert.equal(after.ops.includes('modelAdmission'), true, JSON.stringify(after));
assert.deepEqual(after.answer, { ok: false, error: 'proxy-uncertain' });
});
+269
View File
@@ -0,0 +1,269 @@
// #1873 ride-default slice 1: Ride all adds the instance's model proxy (cliproxy) to the owner's
// organizations, skips and names the ones it must not change, and lists fixture organizations,
// which move to the owner's models only by a separate confirmed action.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createHash } from 'node:crypto';
import { createProxyAdmin } from '../src/admin-control.mjs';
import { initFiles, receiptFile } from '../src/admin.mjs';
import { PIN } from '../src/common.mjs';
import { cliproxyRemoved, localRide, pickModel, fixtureMove, moveFixtureOrg, readRider, ownerModelsFrom } from '../src/ride.mjs';
import * as orgService from '../../organization/src/org-service.mjs';
import { orgUsesFixture } from '../../cli/src/dev-fixture.mjs';
const stopped = async () => ({ stopped: true, running: [] });
const row = (over = {}) => ({ key: 'claude-claude-opus-5-5', module: 'cliproxy', upstream: 'claude', provider: 'anthropic', model: 'claude-opus-5-5', label: 'Claude Opus 5.5', available: true, reason: null, harnesses: ['claude-code', 'pi'], ...over });
const glm = row({ key: 'zai-glm-5-3', upstream: 'zai', provider: 'zai', model: 'glm-5.3', label: 'GLM 5.3', harnesses: ['pi'] });
const committed = changes => JSON.stringify({ state: 'committed', changes }) + '\n';
const busError = code => Object.assign(new Error('bus text that must not leak'), { code });
// A fake organization bus: `plugins` answers the providers and revision; `proxy.accounts` answers
// or throws; `plugins.set` records the write.
function bus({ providers = ['fixture'], down = false, client = true, accounts = null, set = null } = {}) {
const calls = [];
const call = async (verb, args) => {
calls.push([verb, args]);
if (down) throw busError('no-bus-host');
if (verb === 'plugins') return { business: 'x', revision: 'rev-1', plugins: { 'model-provider': providers }, available: {} };
if (verb === 'proxy.accounts') { if (accounts) throw accounts; if (!client) throw busError('not-configured'); return { accounts: [] }; }
if (verb === 'plugins.set') { if (set) throw set; providers = args.plugins['model-provider']; return { revision: 'rev-2' }; }
throw new Error(`unexpected ${verb}`);
};
return { call, calls };
}
function admin(t, { riders, ownerModels, move, unitState } = {}) {
const root = fs.mkdtempSync(join(tmpdir(), 'rd-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
const state = unitState ?? { installed: false, active: 'inactive', healthy: false };
const unit = { unit: 'mosaic-proxy-zz.service', status: async () => ({ unit: 'mosaic-proxy-zz.service', ...state }) };
const sha = text => createHash('sha256').update(text).digest('hex');
const pin = { ...PIN, archive: { ...PIN.archive, sha256: sha('a') }, binary: { sha256: sha('b') }, panel: { ...PIN.panel, sha256: sha('p') } };
const a = createProxyAdmin({ dataRoot, configDir, unit, buses: stopped, fetch: async () => ({}), now: () => new Date(0), pin,
...(riders ? { riders } : {}), ...(ownerModels ? { ownerModels } : {}), ...(move !== undefined ? { move } : {}) });
return { admin: a, configDir, dataRoot, pin, state };
}
const receipts = dataRoot => { try { return fs.readFileSync(receiptFile(dataRoot), 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse); } catch { return []; } };
test('a change log shows cliproxy removed only when a committed write took it off', () => {
assert.equal(cliproxyRemoved(''), false);
assert.equal(cliproxyRemoved(committed([{ path: 'plugins.model-provider', old: ['fixture'], new: ['fixture', 'cliproxy'] }])), false);
assert.equal(cliproxyRemoved(committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }])), true);
assert.equal(cliproxyRemoved(committed([{ path: 'plugins', old: { 'model-provider': ['cliproxy'] }, new: { 'model-provider': ['fixture'] } }])), true);
assert.equal(cliproxyRemoved(JSON.stringify({ state: 'staged', changes: [{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }] }) + '\n'), false, 'a write that did not commit removed nothing');
assert.equal(cliproxyRemoved(committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }, { path: 'plugins.model-provider', old: [], new: ['cliproxy'] }]) ), true, 'a removal stays a removal once seen');
assert.equal(cliproxyRemoved('{not json\n'), null);
assert.equal(cliproxyRemoved(null), null);
});
test('the local rule names unreadable, removed, fixture, already and ready in that order', () => {
const removed = committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }]);
assert.equal(localRide({ fixture: undefined, cliproxy: false, changes: '' }), 'unreadable');
assert.equal(localRide({ fixture: false, cliproxy: undefined, changes: '' }), 'unreadable');
assert.equal(localRide({ fixture: false, cliproxy: false, changes: null }), 'unreadable');
assert.equal(localRide({ fixture: true, cliproxy: false, changes: removed }), 'removed');
assert.equal(localRide({ fixture: true, cliproxy: false, changes: '' }), 'fixture');
assert.equal(localRide({ fixture: false, cliproxy: true, changes: '' }), 'already');
assert.equal(localRide({ fixture: false, cliproxy: false, changes: '' }), 'ready');
});
test('the owner model is a usable catalogue row that serves every harness, claude first', () => {
assert.equal(pickModel([glm, row()]).key, 'claude-claude-opus-5-5');
assert.equal(pickModel([glm]).key, 'zai-glm-5-3');
assert.equal(pickModel([glm, row()], ['claude-code']).key, 'claude-claude-opus-5-5');
assert.equal(pickModel([glm], ['claude-code']), null);
assert.equal(pickModel([row({ available: false }), row({ reason: 'unverified' }), row({ module: 'fixture' })]), null, 'a model the catalogue does not offer is never picked');
assert.equal(pickModel(null), null);
});
test('ride all adds cliproxy through plugins.set and skips and names each organization it must not change', async t => {
const ready = bus({ providers: [] }), noClient = bus({ providers: [], client: false }), down = bus({ down: true }), checkFails = bus({ providers: [], accounts: busError('proxy-down') });
const refused = bus({ providers: [], set: busError('revision-conflict') }), alreadyBus = bus({ providers: ['cliproxy'] }), removedBus = bus({ providers: [] }), fixtureBus = bus({ down: true });
const unreadable = bus({ providers: [] }), raced = bus({ providers: ['cliproxy'] });
const riders = async () => [
{ id: 'ready', fixture: false, cliproxy: false, changes: '', call: ready.call },
{ id: 'removed', fixture: false, cliproxy: false, changes: committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }]), call: removedBus.call },
{ id: 'down', fixture: false, cliproxy: false, changes: '', call: down.call },
{ id: 'noclient', fixture: false, cliproxy: false, changes: '', call: noClient.call },
{ id: 'checkfails', fixture: false, cliproxy: false, changes: '', call: checkFails.call },
{ id: 'refused', fixture: false, cliproxy: false, changes: '', call: refused.call },
{ id: 'already', fixture: false, cliproxy: true, changes: '', call: alreadyBus.call },
{ id: 'raced', fixture: false, cliproxy: false, changes: '', call: raced.call },
{ id: 'unreadable', fixture: undefined, cliproxy: undefined, changes: '', call: unreadable.call },
{ id: 'stand-in', fixture: true, cliproxy: false, changes: '', call: fixtureBus.call },
];
const { admin: a, dataRoot } = admin(t, { riders });
const result = await a.rideAll();
assert.deepEqual(result.added, ['ready']);
assert.deepEqual(result.already, ['already', 'raced']);
assert.deepEqual(result.skipped, [
{ id: 'removed', reason: 'removed' }, { id: 'down', reason: 'bus-down' }, { id: 'noclient', reason: 'no-proxy-client' },
{ id: 'checkfails', reason: 'proxy-check-failed' }, { id: 'refused', reason: 'revision-conflict' }, { id: 'unreadable', reason: 'unreadable' },
]);
assert.deepEqual(result.fixtures, [{ id: 'stand-in', running: false }]);
assert.deepEqual(ready.calls.find(([v]) => v === 'plugins.set'), ['plugins.set', { revision: 'rev-1', plugins: { 'model-provider': ['cliproxy'] } }]);
for (const [name, b] of Object.entries({ removedBus, down, noClient, checkFails, alreadyBus, raced, unreadable, fixtureBus }))
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false, `${name} gets no write`);
assert.equal(JSON.stringify(result).includes('must not leak'), false);
const last = receipts(dataRoot).at(-1);
assert.equal(last.op, 'ride-all'); assert.deepEqual(last.added, ['ready']); assert.deepEqual(last.fixtures, ['stand-in']);
});
test('ride all keeps the providers an organization already has', async t => {
const b = bus({ providers: ['openai'] });
const { admin: a } = admin(t, { riders: async () => [{ id: 'o', fixture: false, cliproxy: false, changes: '', call: b.call }] });
assert.deepEqual((await a.rideAll()).added, ['o']);
assert.deepEqual(b.calls.find(([v]) => v === 'plugins.set')[1].plugins, { 'model-provider': ['openai', 'cliproxy'] });
});
test('status names ride all after accounts while an organization can still ride', async t => {
let list = [{ id: 'o', fixture: false, cliproxy: false, changes: '', call: bus().call }];
const f = admin(t, { riders: async () => list, unitState: { installed: true, active: 'active', healthy: true, pid: 3 } });
const binDir = join(f.dataRoot, 'opt', 'cliproxyapi', PIN.version);
fs.mkdirSync(join(binDir, 'static'), { recursive: true });
fs.writeFileSync(join(binDir, 'cli-proxy-api'), 'b'); fs.writeFileSync(join(binDir, 'static', 'management.html'), 'p');
const files = initFiles(f.configDir, f.dataRoot);
fs.mkdirSync(join(f.configDir, 'secrets'), { mode: 0o700 }); fs.writeFileSync(files.key, 'fixture', { mode: 0o600 });
fs.mkdirSync(files.proxyDir, { mode: 0o700 });
fs.writeFileSync(files.settings, JSON.stringify({ binary: join(binDir, 'cli-proxy-api'), port: 18432 }), { mode: 0o600 });
let status = await f.admin.status();
assert.deepEqual(status.next, ['accounts', 'ride-all']);
assert.deepEqual(status.ride, [{ id: 'o', state: 'ready' }]);
list = [{ id: 'o', fixture: true, cliproxy: false, changes: '', call: bus().call }];
assert.deepEqual((await f.admin.status()).next, ['accounts', 'ride-all'], 'a fixture organization can still be moved');
list = [{ id: 'o', fixture: false, cliproxy: true, changes: '', call: bus().call }];
status = await f.admin.status();
assert.deepEqual(status.next, ['accounts']);
list = [{ id: 'o', fixture: false, cliproxy: false, changes: committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }]), call: bus().call }];
assert.deepEqual((await f.admin.status()).next, ['accounts'], 'a removed organization is not a reason to ride');
f.state.healthy = false;
list = [{ id: 'o', fixture: false, cliproxy: false, changes: '', call: bus().call }];
assert.deepEqual((await f.admin.status()).next, ['unit-restart'], 'never before the proxy answers');
});
test('a fixture organization moves only when stopped, with a proxy, a riding bus and a move seam', async t => {
const owner = { proxy: true, riding: true, models: [row()] };
const moves = [];
const move = async (id, models, principal) => { moves.push({ id, models, principal }); return { moved: true, model: models[0].key }; };
let stoppedBus = bus({ down: true }), runningBus = bus();
const riders = async () => [
{ id: 'stand-in', fixture: true, cliproxy: false, changes: '', call: stoppedBus.call },
{ id: 'live', fixture: true, cliproxy: false, changes: '', call: runningBus.call },
{ id: 'real', fixture: false, cliproxy: false, changes: '', call: stoppedBus.call },
];
let ownerNow = owner;
const f = admin(t, { riders, ownerModels: async () => ownerNow, move });
const principal = { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' };
assert.deepEqual(await f.admin.rideMove({ org: 'nope', principal }), { org: 'nope', moved: false, reason: 'unknown' });
assert.deepEqual(await f.admin.rideMove({ org: 'real', principal }), { org: 'real', moved: false, reason: 'ready' });
assert.deepEqual(await f.admin.rideMove({ org: 'live', principal }), { org: 'live', moved: false, reason: 'bus-running' });
ownerNow = { ...owner, proxy: false };
assert.deepEqual(await f.admin.rideMove({ org: 'stand-in', principal }), { org: 'stand-in', moved: false, reason: 'no-proxy' });
ownerNow = { ...owner, riding: false };
assert.deepEqual(await f.admin.rideMove({ org: 'stand-in', principal }), { org: 'stand-in', moved: false, reason: 'no-riding-bus' });
assert.equal(moves.length, 0);
ownerNow = owner;
const done = await f.admin.rideMove({ org: 'stand-in', principal });
assert.equal(done.moved, true); assert.equal(done.model, 'claude-claude-opus-5-5');
assert.deepEqual(moves, [{ id: 'stand-in', models: [row()], principal }]);
const last = receipts(f.dataRoot).at(-1);
assert.deepEqual({ op: last.op, org: last.org, model: last.model }, { op: 'ride-move', org: 'stand-in', model: 'claude-claude-opus-5-5' });
const none = admin(t, { riders, ownerModels: async () => owner, move: null });
assert.deepEqual(await none.admin.rideMove({ org: 'stand-in', principal }), { org: 'stand-in', moved: false, reason: 'not-available' });
const throws = admin(t, { riders, ownerModels: async () => owner, move: async () => { throw Object.assign(new Error('raw text'), { code: 'revision-conflict' }); } });
assert.deepEqual(await throws.admin.rideMove({ org: 'stand-in', principal }), { org: 'stand-in', moved: false, reason: 'revision-conflict' });
});
test('the fixture move rewrites the model provider, the model entry and every role that used it', async () => {
const doc = await orgService.templateRender('alpha', { fixture: 'local' });
Object.assign(doc.roles.assistant.vars, { 'fallback.harness': 'pi', 'fallback.model': 'fixture-deterministic', 'fallback.thinking': 'off' });
doc.projects.work.agents = { helper: { definition: 'coder', vars: { harness: 'pi', model: 'fixture-deterministic', thinking: 'off' } } };
assert.deepEqual(await orgService.validateOrg(doc), { ok: true, errors: [] });
assert.equal(orgUsesFixture(doc), true);
const { doc: next, model } = fixtureMove(doc, [glm, row()]);
assert.equal(model.key, 'claude-claude-opus-5-5', 'the fixture assistant runs pi; of the models that serve pi, claude comes first');
assert.equal(orgUsesFixture(next), false);
assert.deepEqual(next.plugins['model-provider'], ['cliproxy']);
assert.deepEqual(next.launch.models, { 'claude-claude-opus-5-5': { provider: 'anthropic', model: 'claude-opus-5-5', module: 'cliproxy', upstream: 'claude' } });
assert.equal(next.roles.assistant.vars.model, 'claude-claude-opus-5-5');
assert.equal(next.roles.assistant.vars['fallback.model'], 'claude-claude-opus-5-5');
assert.equal(next.roles.assistant.vars.harness, 'pi', 'the harness is left as it was');
assert.equal(next.projects.work.agents.helper.vars.model, 'claude-claude-opus-5-5', 'a project\'s own agent moves too');
assert.deepEqual(await orgService.validateOrg(next), { ok: true, errors: [] });
const zai = fixtureMove(doc, [glm]);
assert.equal(zai.model.key, 'zai-glm-5-3');
assert.deepEqual(zai.doc.launch.models, { 'zai-glm-5-3': { provider: 'zai', model: 'glm-5.3', module: 'cliproxy', upstream: 'zai' } });
assert.deepEqual(await orgService.validateOrg(zai.doc), { ok: true, errors: [] });
assert.equal(doc.plugins['model-provider'][0], 'fixture', 'the input is not changed');
assert.deepEqual(fixtureMove(doc, [row({ harnesses: ['claude-code'] })]), { reason: 'no-model' }, 'a model that cannot serve the harness is not used');
assert.deepEqual(fixtureMove(doc, [row({ available: false, harnesses: ['pi'] })]), { reason: 'no-model' }, 'a model the catalogue does not offer is not used');
});
test('the fixture move writes through the organization service as the owner, and only at the revision read', async () => {
const root = fs.mkdtempSync(join(tmpdir(), 'rd-svc-'));
try {
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
const ctx = { configDir, dataRoot, instance: 'test', principal: { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' } };
await orgService.createOrg(ctx, 'alpha', await orgService.templateRender('alpha', { fixture: 'local' }));
const stranger = { ...ctx, principal: { provider: 'sso', iss: 'https://idp.invalid', sub: 'someone' } };
await assert.rejects(moveFixtureOrg({ service: orgService, ctx: stranger, id: 'alpha', models: [row()] }));
assert.equal(orgUsesFixture((await orgService.showOrg(ctx, 'alpha')).doc), true, 'a stranger moved nothing');
assert.deepEqual(await moveFixtureOrg({ service: orgService, ctx, id: 'alpha', models: [row({ harnesses: ['claude-code'] })] }), { moved: false, reason: 'no-model' });
// A moved document the service does not accept is not written.
const refusing = { ...orgService, validateOrg: async () => ({ ok: false, errors: [{ path: '$', message: 'no' }] }) };
assert.deepEqual(await moveFixtureOrg({ service: refusing, ctx, id: 'alpha', models: [row()] }), { moved: false, reason: 'invalid' });
assert.equal(orgUsesFixture((await orgService.showOrg(ctx, 'alpha')).doc), true, 'an invalid move wrote nothing');
// A write between the read and the update loses: the service refuses the stale revision.
const racing = { ...orgService, validateOrg: async d => { const now = await orgService.showOrg(ctx, 'alpha'); await orgService.updateOrg(ctx, 'alpha', now.doc, { ifRevision: now.revision }); return orgService.validateOrg(d); } };
await assert.rejects(moveFixtureOrg({ service: racing, ctx, id: 'alpha', models: [row()] }), { code: 'revision-conflict' });
assert.equal(orgUsesFixture((await orgService.showOrg(ctx, 'alpha')).doc), true);
assert.deepEqual(await moveFixtureOrg({ service: orgService, ctx, id: 'alpha', models: [row()] }), { moved: true, model: 'claude-claude-opus-5-5' });
const after = (await orgService.showOrg(ctx, 'alpha')).doc;
assert.equal(orgUsesFixture(after), false);
assert.deepEqual(after.plugins['model-provider'], ['cliproxy']);
assert.equal(after.roles.assistant.vars.model, 'claude-claude-opus-5-5');
assert.deepEqual(after.launch.models['claude-claude-opus-5-5'], { provider: 'anthropic', model: 'claude-opus-5-5', module: 'cliproxy', upstream: 'claude' });
} finally { fs.rmSync(root, { recursive: true, force: true }); }
});
test('an organization is read from its file and change log; a missing log is empty and any other failure unreadable', () => {
const enoent = () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); };
const eacces = () => { throw Object.assign(new Error('denied'), { code: 'EACCES' }); };
const doc = providers => ({ plugins: { 'model-provider': providers } });
assert.deepEqual(readRider({ id: 'a', read: () => doc(['cliproxy']), readLog: () => 'log', isFixture: () => false }), { id: 'a', fixture: false, cliproxy: true, changes: 'log' });
assert.deepEqual(readRider({ id: 'b', read: () => doc(['fixture']), readLog: enoent, isFixture: () => true }), { id: 'b', fixture: true, cliproxy: false, changes: '' });
assert.deepEqual(readRider({ id: 'c', read: () => ({}), readLog: eacces, isFixture: () => false }), { id: 'c', fixture: false, cliproxy: false, changes: null });
const unread = readRider({ id: 'd', read: () => { throw new Error('bad json'); }, readLog: () => '', isFixture: () => true });
assert.deepEqual(unread, { id: 'd', fixture: undefined, cliproxy: undefined, changes: '' });
assert.equal(localRide(unread), 'unreadable');
assert.equal(localRide(readRider({ id: 'c', read: () => ({}), readLog: eacces, isFixture: () => false })), 'unreadable');
// The real fixture test decides the fixture field.
assert.equal(readRider({ id: 'e', read: () => doc(['fixture']), readLog: () => '', isFixture: orgUsesFixture }).fixture, true);
});
test('the owner models come only from riding buses that answer a ready catalogue, cliproxy rows once each', async () => {
const asked = [];
const rider = (id, cliproxy, answer) => ({ id, cliproxy, call: async verb => { asked.push([id, verb]); if (answer instanceof Error) throw answer; return answer; } });
const ready = models => ({ catalogue: { status: 'ready', models } });
assert.deepEqual(await ownerModelsFrom({ proxy: false, riders: [rider('a', true, ready([row()]))] }), { proxy: false, riding: false, models: [] });
assert.deepEqual(asked, [], 'no proxy asks no bus');
const fixtureRow = row({ key: 'fixture-deterministic', module: 'fixture' });
const answer = await ownerModelsFrom({ proxy: true, riders: [
rider('a', true, ready([row(), fixtureRow])), rider('b', true, ready([row({ label: 'later copy' }), glm])), rider('c', false, ready([row({ key: 'not-riding' })])),
rider('d', true, { catalogue: { status: 'unavailable', models: [row({ key: 'fenced' })] } }), rider('e', true, busError('no-bus-host')),
] });
assert.deepEqual(answer, { proxy: true, riding: true, models: [row(), glm] });
assert.deepEqual(asked.map(([id]) => id).sort(), ['a', 'b', 'd', 'e'], 'only organizations that list cliproxy are asked');
assert.deepEqual(await ownerModelsFrom({ proxy: true, riders: [rider('d', true, { catalogue: { status: 'unavailable', models: [] } }), rider('e', true, busError('no-bus-host'))] }), { proxy: true, riding: false, models: [] });
// A hung bus does not hold the others back: they are asked together.
let release; const hung = { id: 'h', cliproxy: true, call: () => new Promise(r => { release = r; }) };
const pending = ownerModelsFrom({ proxy: true, riders: [hung, rider('a', true, ready([row()]))] });
await new Promise(r => setImmediate(r));
assert.equal(asked.filter(([id]) => id === 'a').length, 2, 'the second bus was asked while the first hung');
release(null); assert.deepEqual((await pending).models, [row()]);
});
+8 -4
View File
@@ -83,15 +83,18 @@ async function discoverPresets() {
}
return presets;
}
export async function orgPresets({ env = process.env } = {}) {
// `owner` (#1873 ride-default) is what the Console read from the owner's model proxy:
// {proxy, riding, models}. A preset that does not use it ignores it.
export async function orgPresets({ env = process.env, owner } = {}) {
const presets = await discoverPresets();
return Promise.all([...presets.values()].map(async p => {
const availability = await p.available({ env });
const availability = await p.available({ env, owner });
if (!availability || typeof availability.ok !== 'boolean' || (!availability.ok && (typeof availability.reason !== 'string' || !availability.reason))) fail('org-invalid', 'invalid preset availability');
return { name: p.name, label: p.label, description: p.description, thinking: structuredClone(p.thinking), available: availability.ok ? { ok: true } : { ok: false, reason: availability.reason } };
}));
}
export async function templateRender(id, { fixture, preset, thinking } = {}) {
// `model` (#1873 ride-default) is one row of the owner's catalogue, for a preset that routes to it.
export async function templateRender(id, { fixture, preset, thinking, model } = {}) {
if (fixture !== undefined && fixture !== 'local') fail('org-invalid', 'unknown fixture');
if (fixture !== undefined && preset !== undefined) fail('org-invalid', 'choose fixture or preset');
if (fixture === 'local') preset = 'fixture';
@@ -105,7 +108,8 @@ export async function templateRender(id, { fixture, preset, thinking } = {}) {
if (!p) fail('org-invalid', 'unknown preset');
const level = thinking === undefined ? p.thinking.default : thinking;
if (!p.thinking.levels.includes(level)) fail('org-invalid', 'unknown thinking level');
const overlay = await p.overlay({ thinking: level });
let overlay;
try { overlay = await p.overlay({ thinking: level, model }); } catch (e) { fail('org-invalid', e?.code === 'org-invalid' && typeof e.message === 'string' ? e.message : 'invalid preset overlay'); }
if (!overlay || typeof overlay !== 'object' || !overlay.plugins || !overlay.launch || !overlay.assistantVars) fail('org-invalid', 'invalid preset overlay');
doc.plugins = structuredClone(overlay.plugins); doc.launch = structuredClone(overlay.launch);
doc.roles.assistant.vars = structuredClone(overlay.assistantVars);
@@ -30,3 +30,45 @@ test('unknown presets and thinking levels refuse', async () => {
await assert.rejects(templateRender('alpha', { preset: 'claude-code', thinking: 'off' }), /thinking/);
await assert.rejects(templateRender('alpha', { thinking: 'low' }), /thinking/);
});
// #1873 ride-default slice 1: the cliproxy preset routes a new organization to a model the
// owner's catalogue lists, and says plainly why it is unavailable.
const row = (over = {}) => ({ key: 'claude-claude-opus-5-5', module: 'cliproxy', upstream: 'claude', provider: 'anthropic', model: 'claude-opus-5-5',
label: 'claude / claude-opus-5-5', available: true, reason: null, harnesses: ['claude-code', 'pi'], ...over });
const cliproxyOf = async owner => (await service.orgPresets({ env: { PATH: '/usr/bin:/bin' }, owner })).find(p => p.name === 'cliproxy');
test('the cliproxy preset is discovered and names each reason it is unavailable', async () => {
const none = await cliproxyOf(undefined);
assert.equal(none.available.ok, false); assert.match(none.available.reason, /Set up the model proxy first/);
assert.match((await cliproxyOf({ proxy: false, riding: true, models: [row()] })).available.reason, /Set up the model proxy first/);
assert.match((await cliproxyOf({ proxy: true, riding: false, models: [row()] })).available.reason, /No organization uses the model proxy yet/);
assert.match((await cliproxyOf({ proxy: true, riding: true, models: [] })).available.reason, /lists no model you can use/);
for (const bad of [row({ available: false }), row({ reason: 'unverified' }), row({ module: 'fixture' }), row({ harnesses: [] })])
assert.match((await cliproxyOf({ proxy: true, riding: true, models: [bad] })).available.reason, /lists no model you can use/);
const ok = await cliproxyOf({ proxy: true, riding: true, models: [row()] });
assert.deepEqual(ok.available, { ok: true });
assert.deepEqual(ok.thinking, { levels: ['low', 'medium', 'high', 'xhigh', 'max'], default: 'low' });
});
test('the cliproxy overlay routes to the catalogue model it is given and validates', async () => {
const doc = await templateRender('alpha', { preset: 'cliproxy', model: row() });
assert.deepEqual(doc.plugins['model-provider'], ['cliproxy']);
assert.deepEqual(doc.launch.models, { 'claude-claude-opus-5-5': { provider: 'anthropic', model: 'claude-opus-5-5', module: 'cliproxy', upstream: 'claude' } });
assert.deepEqual(doc.roles.assistant.vars, { harness: 'claude-code', model: 'claude-claude-opus-5-5', thinking: 'low' });
assert.equal(doc.vars, undefined);
assert.deepEqual(await validateOrg(doc), { ok: true, errors: [] });
const glm = await templateRender('alpha', { preset: 'cliproxy', thinking: 'high', model: row({ key: 'zai-glm-5-3', upstream: 'zai', provider: 'zai', model: 'glm-5.3', harnesses: ['pi'] }) });
assert.deepEqual(glm.roles.assistant.vars, { harness: 'pi', model: 'zai-glm-5-3', thinking: 'high' });
assert.deepEqual(glm.plugins.harness, ['pi']);
assert.deepEqual(await validateOrg(glm), { ok: true, errors: [] });
await assert.rejects(templateRender('alpha', { preset: 'cliproxy' }), /lists no such model/);
await assert.rejects(templateRender('alpha', { preset: 'cliproxy', model: row({ available: false }) }), /lists no such model/);
});
test('existing presets ignore the new model and owner inputs', async () => {
assert.deepEqual(await templateRender('alpha', { preset: 'fixture', model: row() }), await templateRender('alpha', { preset: 'fixture' }));
assert.deepEqual(await templateRender('alpha', { preset: 'claude-code', model: row() }), await templateRender('alpha', { preset: 'claude-code' }));
const presets = await service.orgPresets({ env: { PATH: '/usr/bin:/bin' }, owner: { proxy: true, riding: true, models: [row()] } });
assert.equal(presets.find(p => p.name === 'fixture').available.ok, true);
assert.equal(presets.find(p => p.name === 'claude-code').available.ok, false);
});
@@ -76,3 +76,32 @@ export function route({ selection, harness }) {
if (typeof selection.model !== 'string' || !MODEL.test(selection.model)) return { code: 'model-provider-unavailable' };
return { provider: selection.provider ?? upstream, model: selection.model, upstream, ...ROUTES[upstream] };
}
// #1873 ride-default slice 1: a new organization that uses the owner's models through the
// instance's model proxy. The Console reads the owner's catalogue from a riding bus and passes
// it as `owner`; this module never reaches the proxy itself.
const THINKING = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
export const usableModel = m => !!m && m.module === 'cliproxy' && m.available === true && m.reason === null
&& typeof m.key === 'string' && /^[a-z][a-z0-9-]{0,63}$/.test(m.key) && typeof m.upstream === 'string' && Object.hasOwn(ROUTES, m.upstream)
&& typeof m.provider === 'string' && typeof m.model === 'string' && MODEL.test(m.model)
&& Array.isArray(m.harnesses) && (m.harnesses.includes('claude-code') || m.harnesses.includes('pi'));
export function orgPresets() {
return [{ name: 'cliproxy', label: 'Your models through the model proxy',
description: 'Uses a model your model proxy lists. Each reply spends your own account.',
thinking: { levels: [...THINKING], default: 'low' },
available: ({ owner } = {}) => {
if (!owner || owner.proxy !== true) return { ok: false, reason: 'Set up the model proxy first, on the Model proxy page.' };
if (owner.riding !== true) return { ok: false, reason: 'No organization uses the model proxy yet, or none answered. Use Ride all on the Model proxy page.' };
if (!Array.isArray(owner.models) || !owner.models.some(usableModel)) return { ok: false, reason: 'The model proxy lists no model you can use. Sign in to an account on the Model proxy page.' };
return { ok: true };
},
overlay: ({ thinking, model }) => {
if (!usableModel(model)) throw Object.assign(Error('the model proxy lists no such model'), { code: 'org-invalid' });
const harness = model.harnesses.includes('claude-code') ? 'claude-code' : 'pi';
return {
plugins: { channel: ['cli', 'webui'], harness: [harness], 'model-provider': ['cliproxy'] },
launch: { by: 'chief', instances: ['assistant'], models: { [model.key]: { provider: model.provider, model: model.model, module: 'cliproxy', upstream: model.upstream } } },
assistantVars: { harness, model: model.key, thinking },
};
} }];
}
+31 -1
View File
@@ -19,6 +19,9 @@ import { loadSystem, socketPath, orgPaths, REPO, rolesDir } from '../../cli/src/
import { busStatus as orgBusStatus, busRevive as orgBusRevive } from '../../cli/src/org-bus.mjs';
import { listOrgs, resolveOrg } from '../../organization/src/org-registry.mjs';
import { showOrg } from '../../organization/src/org-service.mjs';
import * as orgService from '../../organization/src/org-service.mjs';
import { orgUsesFixture } from '../../cli/src/dev-fixture.mjs';
import { moveFixtureOrg, ownerModelsFrom, readRider } from '../../model-proxy/src/ride.mjs';
import { configDir } from '../../organization/src/organization-config.mjs';
import { loadRootAgents } from '../../organization/src/agent-levels.mjs';
import { organizationWriter } from '../../organization/src/organization.mjs';
@@ -218,6 +221,28 @@ try {
const agentLevels = organizations ? { loadRoot: () => loadRootAgents(configDir(), { rolesDir: rolesDir() }), rolesDir: rolesDir(), ctx: { configDir: configDir(), dataRoot: system.dataRoot, instance } } : null;
// #1873: proxy setup for the instance owner (dev local owner, or the root owner under --sso).
// Instance-wide: one pinned release, one proxy.json, one unit. Each organization uses it (shared).
// #1873 ride-default: each active organization as Ride all reads it, from its file and change log
// (read only) and, through `call`, from its bus as the owner. A file that cannot be read gives
// undefined fields, which Ride all names as unreadable.
const rideRiders = async () => {
const writer = organizationWriter({ dir: configDir(), rolesDir: rolesDir() });
const local = id => readRider({ id, read: () => writer.read(id).document, readLog: () => readFileSync(writer.logFile(id), 'utf8'), isFixture: orgUsesFixture });
const down = async () => { throw Object.assign(new Error('the bus is not reachable'), { code: 'no-bus-host' }); };
if (!organizations) return ownerCall && options.business ? [{ ...local(options.business), call: ownerCall }] : [];
const out = [];
for (const org of await listOrgs({ configDir: configDir(), dataRoot: system.dataRoot, instance })) {
if (org.state !== 'active') continue;
let call = down; try { const paths = orgPaths(org.root); call = busCaller({ dataRoot: org.root, socket: paths.socket, business: org.id, timeoutMs: 5000 }); } catch {}
out.push({ ...local(org.id), call });
}
return out;
};
// The owner's models (ride.mjs ownerModelsFrom): the proxy is set up when proxy.json names a port.
const ownerModels = system && (devOwner || ssoOn) ? async () => {
let proxy = false;
try { proxy = Number.isInteger(loadProxy(configDir(), system.dataRoot)?.port); } catch {}
return ownerModelsFrom({ proxy, riders: proxy ? await rideRiders() : [] });
} : null;
const proxyAdmin = system && (devOwner || ssoOn) ? createProxyAdmin({
dataRoot: system.dataRoot, configDir: configDir(), instance, unitDir: options.proxyUnitDir ?? null,
buses: () => busesStopped({ dataRoot: system.dataRoot, configDir: configDir() }),
@@ -232,6 +257,11 @@ try {
}
return out;
},
riders: rideRiders,
ownerModels,
// A stopped fixture organization moves through the organization service's whole-file update, the
// write `POST /api/orgs/ID/admin` makes, as the signed-in owner. The owner starts its bus after.
move: (id, models, principal) => moveFixtureOrg({ service: orgService, ctx: { configDir: configDir(), dataRoot: system.dataRoot, instance, principal }, id, models }),
}) : null;
// #1873 triage-host: the instance owner's Triage session, hosted by the Console in no organization.
// Nothing starts here; the owner's first message starts it.
@@ -303,7 +333,7 @@ try {
},
})] : [];
try {
server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, triage, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, routes: [...agentLevelRoutes, ...triageRoutes], preselect: options.business ?? null });
server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, triage, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, ownerModels, routes: [...agentLevelRoutes, ...triageRoutes], preselect: options.business ?? null });
} catch (err) { sso?.close(); throw err; }
if (testerSocket) {
const call = busCaller({ dataRoot: system.dataRoot, socket: socketPath(system.dataRoot), business: options.business ?? null, cli: TESTER_CLI });
+21 -6
View File
@@ -27,6 +27,7 @@
// handler returns false for them.
import { open } from 'node:fs/promises';
import { pickModel, usableModel } from '../../model-proxy/src/ride.mjs';
import { lstatSync } from 'node:fs';
import { checkProject, initProject, projectRepo, recordContext } from '../../project/src/index.mjs';
import { refuseInsideAgent } from '../../cli/src/transport.mjs';
@@ -285,9 +286,10 @@ function refusal(res, error, { step, id, unknownOk = false }) {
// Default service wiring: the real C1/C2/C3 modules, loaded on first use.
// A missing module (a branch without S1 yet) answers not-configured.
async function load(spec) { try { return await import(spec); } catch (e) { if (e?.code === 'ERR_MODULE_NOT_FOUND') return null; throw e; } }
export function defaultOrgAdmin(env = process.env) {
export function defaultOrgAdmin(env = process.env, { ownerModels = null } = {}) {
let system = null;
return createOrgAdmin({
ownerModels,
service: () => load('../../organization/src/org-service.mjs'),
registry: () => load('../../organization/src/org-registry.mjs'),
bus: () => load('../../cli/src/org-bus.mjs'),
@@ -308,10 +310,14 @@ export function defaultOrgAdmin(env = process.env) {
// `service`, `registry` and `bus` are module objects or functions returning
// them (or null when absent). `context()` gives { configDir, dataRoot, instance }.
export function createOrgAdmin({ service, registry = null, bus = null, context }) {
// `ownerModels()` (#1873 ride-default) answers {proxy, riding, models} from the owner's model
// proxy, read through the riding buses; without it the cliproxy preset reads unavailable.
export function createOrgAdmin({ service, registry = null, bus = null, context, ownerModels = null }) {
const get = async x => (typeof x === 'function' ? x() : x);
return { service: () => get(service), registry: () => get(registry), bus: () => get(bus), context: () => get(context) };
const owner = async () => { if (typeof ownerModels !== 'function') return { proxy: false, riding: false, models: [] }; try { return await ownerModels(); } catch { return { proxy: false, riding: false, models: [] }; } };
return { service: () => get(service), registry: () => get(registry), bus: () => get(bus), context: () => get(context), ownerModels: owner };
}
const ownerOf = admin => (typeof admin.ownerModels === 'function' ? admin.ownerModels() : { proxy: false, riding: false, models: [] });
// The handler. Returns true when it answered. `owner` is the signed-in owner
// session (provider, iss, sub) or null; `send` says --send is on; `origin` is
@@ -413,17 +419,26 @@ async function route(req, res, { path, search, org, admin, principal, write, log
if (path === '/api/org-presets' && !write) {
if (new URLSearchParams(search).size) return json(res, 422, { error: 'invalid', message: 'unexpected query parameter' });
const service = await need(admin, 'service', res, 'presets'); if (!service) return;
try { return json(res, 200, { presets: await service.orgPresets() }); }
try { return json(res, 200, { presets: await service.orgPresets({ owner: await ownerOf(admin) }) }); }
catch (e) { return refusal(res, e, { step: 'presets' }); }
}
if (path === '/api/org-template' && !write) {
const params = new URLSearchParams(search);
for (const [key] of params) if (!['id', 'preset', 'thinking'].includes(key) || params.getAll(key).length !== 1) return json(res, 422, { error: 'invalid', message: 'invalid template query' });
for (const [key] of params) if (!['id', 'preset', 'thinking', 'model'].includes(key) || params.getAll(key).length !== 1) return json(res, 422, { error: 'invalid', message: 'invalid template query' });
if (params.has('model') && params.get('preset') !== 'cliproxy') return json(res, 422, { error: 'invalid', message: 'model applies to the cliproxy preset only' });
const id = params.has('id') ? params.get('id') : 'new-org';
if (!ID.test(id)) return json(res, 422, { error: 'invalid', errors: [{ path: '$.id', field: 'id', message: 'invalid organization id' }] });
const service = await need(admin, 'service', res, 'template'); if (!service) return;
// #1873 ride-default: the cliproxy preset routes to a model the owner's catalogue lists. A named
// model must be one of them; otherwise the Console picks one (claude first).
let model;
if (params.get('preset') === 'cliproxy') {
const owner = await ownerOf(admin), models = Array.isArray(owner?.models) ? owner.models : [];
model = params.has('model') ? models.find(m => usableModel(m) && m.key === params.get('model')) : (owner?.proxy === true && owner?.riding === true ? pickModel(models) : null);
if (!model) return json(res, 422, { error: 'invalid', step: 'template', errors: [{ path: '$.model', field: 'model', message: params.has('model') ? 'the model proxy lists no such model' : 'the model proxy lists no model you can use' }] });
}
let doc;
try { doc = await service.templateRender(id, params.has('preset') || params.has('thinking') ? { ...(params.has('preset') ? { preset: params.get('preset') } : {}), ...(params.has('thinking') ? { thinking: params.get('thinking') } : {}) } : { fixture: 'local' }); } catch (e) { return refusal(res, e, { step: 'template' }); }
try { doc = await service.templateRender(id, params.has('preset') || params.has('thinking') ? { ...(params.has('preset') ? { preset: params.get('preset') } : {}), ...(params.has('thinking') ? { thinking: params.get('thinking') } : {}), ...(model ? { model } : {}) } : { fixture: 'local' }); } catch (e) { return refusal(res, e, { step: 'template' }); }
const shown = forBrowser(doc);
return json(res, 200, { id, doc: shown.doc, held: shown.held, verb: verbFor('create', id) });
}
+9 -1
View File
@@ -28,6 +28,9 @@ const ROUTES = Object.freeze({
'/api/proxy/admin/unit/restart': ['POST', []],
'/api/proxy/admin/fence/clear': ['POST', []],
'/api/proxy/admin/init-lock/clear': ['POST', []],
// #1873 ride-default: Ride all, and the confirmed move of one stopped fixture organization.
'/api/proxy/admin/ride-all': ['POST', []],
'/api/proxy/admin/ride-move': ['POST', ['org']],
});
export const PROXY_ADMIN_PATHS = Object.freeze(Object.keys(ROUTES));
const INIT_KEYS = ['generate', 'key', 'confirm', 'port', 'rotateGraceMinutes', 'firstOutputSeconds'];
@@ -46,7 +49,8 @@ const STATUS = { 'human-required': 403, 'proxy-key-transport': 403, 'not-configu
// `owner` is true only for the instance owner's session (the dev local owner, or the root owner
// signed in under --sso). `call` is the owner's transport to the selected bus, or null.
export async function proxyAdminHTTP(req, res, { path, admin, call, named, tester, granted, owner, send, origin, user, log }) {
// `principal` is that session's {provider, iss, sub}; the organization service checks it again.
export async function proxyAdminHTTP(req, res, { path, admin, call, named, tester, granted, owner, send, origin, user, principal = null, log }) {
const route = ROUTES[path];
const done = (status, value) => {
// Path, method and status only: never a body, key, evidence or exception text.
@@ -105,6 +109,10 @@ export async function proxyAdminHTTP(req, res, { path, admin, call, named, teste
if (!call) return refuse('not-configured');
return done(200, await admin.fenceClear(call));
case '/api/proxy/admin/init-lock/clear': return done(200, await admin.initLockClear());
case '/api/proxy/admin/ride-all': return done(200, await admin.rideAll());
case '/api/proxy/admin/ride-move':
if (typeof args.org !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(args.org)) return refuse('invalid-request');
return done(200, await admin.rideMove({ org: args.org, principal }));
}
} catch (error) {
const code = ['human-required', 'not-configured', 'invalid-request'].includes(error?.code) ? error.code : proxyCode(error, 'outcome-unknown');
+71 -2
View File
@@ -528,6 +528,9 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
+ '<div class="proxy-setup-buttons"><button type="button" data-unit="install" data-setup-write disabled>Install</button><button type="button" data-unit="start" data-setup-write disabled>Start</button><button type="button" data-unit="restart" data-setup-write disabled>Restart</button><button type="button" data-unit="stop" data-setup-write disabled>Stop</button><button type="button" id="proxy-setup-render">Show unit file</button></div>'
+ '<pre id="proxy-setup-unit-file" hidden></pre></div>'
+ '<div class="proxy-setup-orgs"><h3>Organizations</h3><div class="table-wrap" tabindex="0" role="region" aria-label="Organizations using the proxy"><table><thead><tr><th>Organization</th><th>Proxy</th><th>Catalogue</th><th>Models</th></tr></thead><tbody id="proxy-setup-orgs"></tbody></table></div>'
+ '<div id="proxy-ride" class="proxy-ride" hidden><h3>Use your models in every organization</h3><p id="proxy-ride-text"></p>'
+ '<button type="button" id="proxy-ride-go" class="btn">Ride all</button><p id="proxy-ride-message" role="status" aria-live="polite"></p>'
+ '<ul id="proxy-ride-skips" class="proxy-ride-list"></ul><ul id="proxy-ride-fixtures" class="proxy-ride-list"></ul></div>'
+ '<p id="proxy-setup-own" class="muted"></p></div>'
+ '<div class="proxy-setup-receipts"><h3>Receipts</h3><ol id="proxy-setup-receipts"><li class="muted">No setup actions on this page yet.</li></ol></div></section>\n';
const markup = setupMarkup + '<button id="proxy-refresh" type="button">Refresh</button><p id="proxy-message" role="status" aria-live="polite">Reading accounts…</p>\n<p id="proxy-readonly" class="muted" hidden>This Console is read-only. Sign-in and account changes are unavailable.</p>\n<section class="panel" aria-labelledby="proxy-accounts-title"><h2 id="proxy-accounts-title">Accounts</h2>\n<p>Higher priority is used first. Account names are stable identifiers; credential values are never displayed.</p>\n<div class="table-wrap" tabindex="0" role="region" aria-label="Accounts"><table><thead><tr><th>Account</th><th>Provider</th><th>Status</th><th>Priority</th><th>Models</th></tr></thead><tbody id="proxy-accounts"></tbody></table></div></section>\n<section class="panel" aria-labelledby="proxy-signin-title"><h2 id="proxy-signin-title">Sign in to an account</h2>\n<form id="proxy-login-start"><fieldset data-write disabled><legend>Subscription account</legend><label>Provider <select name="provider"><option value="claude">Claude</option><option value="codex">Codex</option></select></label><button type="submit">Start sign-in</button></fieldset></form>\n<p id="proxy-login-message" role="status" aria-live="polite"></p>\n<p><a id="proxy-authorize" target="_blank" rel="noopener noreferrer" hidden>Open account sign-in in a new tab</a></p>\n<form id="proxy-login-submit"><fieldset data-write disabled><legend>Finish sign-in</legend><p>If the sign-in tab does not return, copy its full address and paste it here.</p><label>Callback address <input name="redirect_url" type="url" autocomplete="off" spellcheck="false" maxlength="8192" required></label><button type="submit">Submit address</button><button id="proxy-login-cancel" type="button">Cancel sign-in</button></fieldset></form></section>\n<section class="panel" aria-labelledby="proxy-apikey-title"><h2 id="proxy-apikey-title">Add an API key</h2>\n<form id="proxy-apikey"><fieldset data-write disabled><legend>z.ai</legend><label>API key <input name="key" type="password" autocomplete="off" spellcheck="false" maxlength="4096" required></label><p>The key is sent once and cleared from this field. It will never be shown again.</p><button type="submit">Add key</button></fieldset><p id="proxy-apikey-message" role="status"></p></form></section>\n<section class="panel" aria-labelledby="proxy-keys-title"><h2 id="proxy-keys-title">Client keys</h2><p>Only key IDs are shown. Hire and fire manage agent keys.</p>\n<div class="table-wrap" tabindex="0" role="region" aria-label="Client keys"><table><thead><tr><th>Key ID</th><th>Managed by</th><th>Agent</th><th>Issued</th><th>State</th></tr></thead><tbody id="proxy-keys"></tbody></table></div></section>\n';
@@ -732,13 +735,14 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
'unit-start': ['Start the proxy service', `Next: start ${state.unit.unit}.`, () => unitAction('start')],
'unit-restart': ['Restart the proxy service', state.fence.set ? (fence => fence.invalid || !fence.time ? 'A key write had an uncertain outcome, so key writes are fenced. The fence file has no readable time, so a restart from this page cannot be proven against it: restart the proxy service, confirm it answers, then run mosaic proxy fence clear --proxy-restarted.' : 'A key write had an uncertain outcome, so key writes are fenced. Restart the proxy; after this page confirms the new process, clear the fence.')(state.fence) : 'The service is running but does not answer on its port. Restart it.', () => unitAction('restart')],
'fence-clear': ['Clear the fence', 'The proxy was restarted from this page and the new process answers on its port. Clear the fence with that evidence.', clearFence],
accounts: ['Add an account', 'The proxy is running. Sign in to an account or add an API key below.', () => $('proxy-signin-title')?.scrollIntoView({ block: 'start' })],
accounts: ['Add an account', state.next?.includes('ride-all') ? 'The proxy is running. Sign in to an account or add an API key below. Then use Ride all under Organizations.' : 'The proxy is running. Sign in to an account or add an API key below.', () => $('proxy-signin-title')?.scrollIntoView({ block: 'start' })],
'ride-all': ['Ride all', 'Next: let your organizations use your models. See Ride all under Organizations.', () => $('proxy-ride')?.scrollIntoView({ block: 'start' })],
};
const [label, text, action] = steps[next] ?? ['Check again', 'Status read.', load];
const p = document.createElement('p'); p.textContent = text;
const button = document.createElement('button'); button.type = 'button'; button.className = 'btn primary'; button.id = 'proxy-setup-go'; button.dataset.next = next ?? '';
button.textContent = state.busy ? 'Working…' : label;
const write = !['init-lock-wait', 'init-repair', 'accounts', 'init'].includes(next);
const write = !['init-lock-wait', 'init-repair', 'accounts', 'init', 'ride-all'].includes(next);
button.disabled = Boolean(state.busy) || (write && !sendOk);
button.addEventListener('click', () => { if (!button.disabled) action(); });
box.replaceChildren(p, button);
@@ -754,8 +758,73 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
if (!Array.isArray(state.organizations)) orgs.replaceChildren(Object.assign(document.createElement('tr'), { innerHTML: '<td colspan="4">Organizations could not be read.</td>' }));
else if (!state.organizations.length) orgs.replaceChildren(Object.assign(document.createElement('tr'), { innerHTML: '<td colspan="4">No organizations.</td>' }));
else orgs.replaceChildren(...state.organizations.map(org => { const tr = document.createElement('tr'); tr.append(cell(org.id), cell(org.proxy === 'shared' ? 'Shared (this instance)' : org.proxy), cell(org.catalogue?.status ?? org.error ?? 'unknown'), cell(Number.isInteger(org.catalogue?.models) ? String(org.catalogue.models) : '—')); return tr; }));
paintRide();
$('proxy-setup-own').textContent = state.ownProxy?.available ? 'An organization can run its own proxy.' : `Own proxy per organization: ${state.ownProxy?.state ?? 'not built'}. ${state.ownProxy?.reason ?? ''}`;
}
// #1873 ride-default: Ride all and the fixture move. The server decides each organization again;
// this code only words the answer. Every write asks first, in plain words, what changes.
const RIDE_REASONS = {
removed: 'Its owner took the model proxy off. Ride all leaves it off.',
'bus-down': 'Its bus is not running. Start it, then ride again.',
'no-proxy-client': 'Its bus started before the proxy was set up. Restart its bus, then ride again.',
'proxy-check-failed': 'Its bus could not check the proxy. Check the proxy, then ride again.',
unreadable: 'Its organization file or change log could not be read.',
failed: 'Its bus refused the change.',
'bus-running': 'Its bus is running. Stop its bus first, then move it.',
'no-proxy': 'Set up the model proxy first.',
'no-riding-bus': 'No organization uses the proxy yet, so no model list was read. Ride all first.',
'no-model': 'The proxy lists no model for the harness its agents use.',
invalid: 'The moved organization file did not pass its check. Nothing was written.',
'revision-conflict': 'The organization changed while it was being moved. Try again.',
'org-forbidden': 'Only the instance owner can move it.',
unknown: 'It is not an active organization.',
'not-available': 'Moving is not available on this Console.',
fixture: 'It uses stand-in models.',
};
const rideReason = code => RIDE_REASONS[code] ?? `Its bus refused the change (${code}).`;
let rideResult = null;
const li = text => { const el = document.createElement('li'); el.textContent = text; return el; };
function paintRide() {
const box = $('proxy-ride'), ride = Array.isArray(state.ride) ? state.ride : null;
box.hidden = !ride || !state.init?.initialized;
if (box.hidden) return;
const ready = ride.filter(r => r.state === 'ready').length, fixtures = ride.filter(r => r.state === 'fixture');
$('proxy-ride-text').textContent = 'Ride all adds this proxy to each organization that does not use it yet. '
+ 'Admission gets stricter there: every launch route is checked, direct Anthropic routes too, and while the proxy is down or fenced every launch in that organization is refused. '
+ (ready ? `${ready} ${ready === 1 ? 'organization can' : 'organizations can'} ride now.` : 'No organization is waiting to ride.');
const go = $('proxy-ride-go'); go.disabled = !sendOk || Boolean(state.busy) || !ready;
const skips = (rideResult?.skipped ?? ride.filter(r => !['ready', 'already', 'fixture'].includes(r.state)).map(r => ({ id: r.id, reason: r.state })));
$('proxy-ride-skips').replaceChildren(...skips.map(s => li(`Skipped ${s.id}: ${rideReason(s.reason)}`)));
const listed = rideResult?.fixtures ?? fixtures.map(f => ({ id: f.id }));
$('proxy-ride-fixtures').replaceChildren(...listed.map(f => {
const item = li(`${f.id} uses stand-in models, can be moved to the owner's models.${f.running ? ' Its bus is running: stop it first.' : ''} `);
const move = document.createElement('button'); move.type = 'button'; move.className = 'btn'; move.textContent = `Move ${f.id}`;
move.dataset.rideMove = f.id; move.disabled = !sendOk || Boolean(state.busy);
move.addEventListener('click', () => { if (!move.disabled) rideMove(f.id); });
item.append(move); return item;
}));
}
const rideSay = (text, kind) => receipt('proxy-ride-message', text, kind);
const rideAll = () => {
if (!window.confirm('Ride all adds this model proxy to each organization that can take it. Admission gets stricter there: every launch route is checked, direct Anthropic routes too, and while the proxy is down or fenced every launch in that organization is refused. Continue?')) return;
return act('ride-all', async () => {
const result = await admin('ride-all', {}); addReceipt(result.receipt); rideResult = result;
const parts = [`Added to ${result.added.length}`, `already using it ${result.already.length}`, `skipped ${result.skipped.length}`];
if (result.fixtures.length) parts.push(`stand-in models ${result.fixtures.length}`);
rideSay(parts.join(', ') + '.', result.skipped.length ? 'error' : 'success'); say('Ride all finished.', 'success');
});
};
const rideMove = id => {
if (!window.confirm(`Move ${id} to your models? Its stand-in models are replaced by a model your proxy lists. After this, its agents spend real tokens on your account. Its bus stays stopped: start it when you are ready.`)) return;
return act('ride-move', async () => {
const result = await admin('ride-move', { org: id });
if (!result.moved) { rideSay(`${id} was not moved. ${rideReason(result.reason)}`, 'error'); return; }
addReceipt(result.receipt);
if (rideResult) rideResult = { ...rideResult, fixtures: rideResult.fixtures.filter(f => f.id !== id) };
rideSay(`${id} now uses ${result.model}. Start its bus when you are ready. It spends real tokens from now on.`, 'success');
});
};
$('proxy-ride-go').addEventListener('click', () => { if (!$('proxy-ride-go').disabled) rideAll(); });
function paint() {
paintState(); paintNext(); paintControls(); paintReceipts();
// An initialized proxy keeps the init form folded after a reload too.
+4 -3
View File
@@ -812,7 +812,7 @@ async function libraryStatusRead(res, read, search) {
// `log` takes one line per send attempt that got past sign-in; never the body. `fieldsFile` is for
// tests; the field table is otherwise the committed packages/tasks/fields.json.
// `agentWrite` (row 194, D7) is `(verb, args) => Promise` for the Agents section's verbs and instance.request.
export async function startServer({ host = '127.0.0.1', port = 7330, board = DEFAULT_BOARD, timeout = 20000, bus = null, reads = null, preview = null, sso = null, tester = false, testerSocket = null, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, proxyAdmin = null, triage = null, processing = null, decisionWrite = null, requestRead = null, requestWrite = null, userOptions = null, federation = null, organizations = null, preselect = null, routes = [], orgAdmin = null, devAllowHosts = [], log = line => console.log(line), fieldsFile = undefined, restart = null, trail = null, boot = randomUUID(), workspaceTimeoutMs = undefined, agentLevels = null } = {}) {
export async function startServer({ host = '127.0.0.1', port = 7330, board = DEFAULT_BOARD, timeout = 20000, bus = null, reads = null, preview = null, sso = null, tester = false, testerSocket = null, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, proxyAdmin = null, triage = null, processing = null, decisionWrite = null, requestRead = null, requestWrite = null, userOptions = null, federation = null, organizations = null, preselect = null, routes = [], orgAdmin = null, ownerModels = null, devAllowHosts = [], log = line => console.log(line), fieldsFile = undefined, restart = null, trail = null, boot = randomUUID(), workspaceTimeoutMs = undefined, agentLevels = null } = {}) {
// org-lan-bind: the dev owner on the LAN is an explicit opt-in. `devAllowHosts` names the Host
// names (without a port) a remote browser may use; only the dev owner takes them, and only with
// them may it bind a non-loopback IPv4 address. SSO, preview and tester listeners stay loopback.
@@ -842,7 +842,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
const registered = routeTable();
for (const registerRoutes of routes) registerRoutes(registered);
registered.add('GET', '/api/themes', (req, res) => themesHTTP(req, res, { log }), { publicRead: true });
const adminRoute = (req, res, context) => orgAdminHTTP(req, res, { ...context, admin: orgAdmin ??= defaultOrgAdmin(), log, trail });
const adminRoute = (req, res, context) => orgAdminHTTP(req, res, { ...context, admin: orgAdmin ??= defaultOrgAdmin(process.env, { ownerModels }), log, trail });
for (const path of ['/api/org-template', '/api/org-presets', '/api/org-validate', '/api/org-admin', /^\/api\/orgs\/[^/]+\/(?:admin|setup|repo|delete|archive|restore|restart|stop)(?:\/(?:queue|bus|project\/[^/]+|records\/[^/]+))?$/]) {
for (const method of ['GET', 'POST']) registered.add(method, path, adminRoute);
}
@@ -1048,7 +1048,8 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
// the selected bus; only the instance owner's own session reaches them, never an org owner.
if (path.startsWith('/api/proxy/admin/')) return proxyAdminHTTP(req, res, { path, admin: proxyAdmin, call: proxyCall, named, tester, granted,
owner: !tester && !granted && named && sso !== null && currentSession?.rootOwner === true, send: owner.send !== null,
origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user, log });
origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user,
principal: currentSession ? { provider: currentSession.provider, iss: currentSession.iss, sub: currentSession.sub } : null, log });
if (path.startsWith('/api/proxy/')) return proxyHTTP(req, res, { path, call: proxyCall, named, tester, granted,
send, origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user, log });
}
+30
View File
@@ -1074,3 +1074,33 @@ test('stop: an archived organization, or a Console whose bus control has no stop
assert.equal(c.calls.filter(x => ['busStop', 'busRestart'].includes(x[0])).length, 0);
assert.deepEqual(tr.lines(), []);
});
// #1873 ride-default slice 1: the cliproxy preset reads the owner's catalogue through the
// `ownerModels` seam and routes a new organization only to a model that catalogue lists.
test('the cliproxy preset uses the owner\'s catalogue and refuses a model it does not list', async t => {
const service = await import('../../organization/src/org-service.mjs');
const row = (over = {}) => ({ key: 'claude-claude-opus-5-5', module: 'cliproxy', upstream: 'claude', provider: 'anthropic', model: 'claude-opus-5-5', label: 'claude / claude-opus-5-5', available: true, reason: null, harnesses: ['claude-code', 'pi'], ...over });
let owner = { proxy: true, riding: true, models: [row({ key: 'zai-glm-5-3', upstream: 'zai', provider: 'zai', model: 'glm-5.3', harnesses: ['pi'] }), row(), row({ key: 'claude-claude-haiku-5-5', model: 'claude-haiku-5-5', available: false, reason: 'no-account' })] };
const admin = createOrgAdmin({ service, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }), ownerModels: async () => owner });
const c = await console_(t, { orgAdmin: admin });
const presetOf = async () => (await c.call('GET', '/api/org-presets')).body.presets.find(p => p.name === 'cliproxy');
assert.deepEqual((await presetOf()).available, { ok: true });
const picked = await c.call('GET', '/api/org-template?id=alpha&preset=cliproxy');
assert.equal(picked.status, 200, picked.raw);
assert.deepEqual(Object.keys(picked.body.doc.launch.models), ['claude-claude-opus-5-5'], 'claude comes first');
assert.equal(picked.body.doc.roles.assistant.vars.model, 'claude-claude-opus-5-5');
const named = await c.call('GET', '/api/org-template?id=alpha&preset=cliproxy&model=zai-glm-5-3');
assert.equal(named.status, 200, named.raw);
assert.deepEqual(named.body.doc.roles.assistant.vars, { harness: 'pi', model: 'zai-glm-5-3', thinking: 'low' });
for (const model of ['claude-claude-haiku-5-5', 'gpt-x', 'not%20a%20key']) {
const r = await c.call('GET', `/api/org-template?id=alpha&preset=cliproxy&model=${model}`);
assert.equal(r.status, 422, model); assert.equal(r.body.errors[0].path, '$.model', model);
}
assert.equal((await c.call('GET', '/api/org-template?id=alpha&preset=fixture&model=claude-claude-opus-5-5')).status, 422, 'model is for the cliproxy preset only');
owner = { ...owner, riding: false };
assert.match((await presetOf()).available.reason, /No organization uses the model proxy yet/);
const none = await c.call('GET', '/api/org-template?id=alpha&preset=cliproxy');
assert.equal(none.status, 422); assert.equal(none.body.errors[0].path, '$.model');
owner = null; admin.ownerModels = createOrgAdmin({ service, context: async () => ({}), ownerModels: async () => { throw new Error('bus down'); } }).ownerModels;
assert.match((await presetOf()).available.reason, /Set up the model proxy first/, 'a failing catalogue read is no proxy');
});
+33 -3
View File
@@ -18,6 +18,8 @@ const ROUTES = [
['status', 'GET'], ['unit/render', 'GET'], ['fetch', 'POST', {}], ['init', 'POST', { generate: true }],
['unit/install', 'POST', {}], ['unit/start', 'POST', {}], ['unit/stop', 'POST', {}], ['unit/restart', 'POST', {}],
['fence/clear', 'POST', {}], ['init-lock/clear', 'POST', {}],
// #1873 ride-default: Ride all, and the move of one stopped fixture organization.
['ride-all', 'POST', {}], ['ride-move', 'POST', { org: 'stand-in' }],
];
function fakeAdmin() {
@@ -26,7 +28,8 @@ function fakeAdmin() {
return {
calls,
unit: 'mosaic-proxy.service',
status: note('status'), render: note('render'), unitAction: note('unitAction'), initLockClear: note('initLockClear'),
status: note('status'), render: note('render'), unitAction: note('unitAction'), initLockClear: note('initLockClear'), rideAll: note('rideAll'),
rideMove: async args => { calls.push(['rideMove', args]); return { org: args.org, moved: false, reason: 'bus-running' }; },
fetchStart: () => { calls.push(['fetchStart']); return { state: 'running' }; },
init: async (call, args) => { calls.push(['init', args]); await call('proxy.init', args); return { settings: { port: 18432 }, receipt: { op: 'init' } }; },
fenceClear: async call => { calls.push(['fenceClear']); return call('proxy.fence.clear', { evidence: {} }); },
@@ -51,7 +54,7 @@ async function devServer(t, options = {}) {
}
const hit = (f, route, extra = {}) => send(f.port, `/api/proxy/admin/${route[0]}`, { method: route[1], headers: { ...f.headers(), ...extra }, body: route[2] });
test('the route table is exactly the brief: status, render, fetch, init, four unit verbs, fence clear, lock clear', () => {
test('the route table is exactly the brief: status, render, fetch, init, four unit verbs, fence clear, lock clear, ride all, ride move', () => {
assert.deepEqual(PROXY_ADMIN_PATHS, ROUTES.map(([p]) => `/api/proxy/admin/${p}`));
});
@@ -61,7 +64,7 @@ test('the dev local owner reaches every route; init and fence clear go to the bu
const r = await hit(f, route);
assert.equal(r.status, route[0] === 'fetch' ? 202 : 200, route[0]);
}
assert.deepEqual(f.admin.calls.map(c => c[0]), ['status', 'render', 'fetchStart', 'init', 'unitAction', 'unitAction', 'unitAction', 'unitAction', 'fenceClear', 'initLockClear']);
assert.deepEqual(f.admin.calls.map(c => c[0]), ['status', 'render', 'fetchStart', 'init', 'unitAction', 'unitAction', 'unitAction', 'unitAction', 'fenceClear', 'initLockClear', 'rideAll', 'rideMove']);
assert.deepEqual(f.admin.calls.filter(c => c[0] === 'unitAction').map(c => c[1]), ['install', 'start', 'stop', 'restart']);
assert.deepEqual(f.busCalls.map(c => c[0]), ['proxy.init', 'proxy.fence.clear']);
assert.deepEqual(f.busCalls[0][1], { generate: true });
@@ -203,3 +206,30 @@ test('an organization whose bus does not answer shows no model count, not a made
assert.deepEqual(await orgCatalogue(async () => ({ catalogue: { status: 'enabled', models: [{ id: 'a' }, { id: 'b' }] } })), { status: 'enabled', models: 2 });
assert.deepEqual(await orgCatalogue(async () => ({ catalogue: { status: 'enabled', models: [] } })), { status: 'enabled', models: 0 });
});
test('ride move takes one organization id and passes the signed-in owner as the principal', async t => {
const f = await devServer(t);
for (const body of [{}, { org: '' }, { org: '../x' }, { org: 'A' }, { org: 7 }, { org: 'x', extra: 1 }])
assert.deepEqual((await hit(f, ['ride-move', 'POST', body])).json, { error: 'invalid-request' }, JSON.stringify(body));
assert.deepEqual((await hit(f, ['ride-all', 'POST', { org: 'x' }])).json, { error: 'invalid-request' }, 'ride all takes no arguments');
assert.deepEqual(f.admin.calls, []);
const r = await hit(f, ['ride-move', 'POST', { org: 'stand-in' }]);
assert.deepEqual(r.json, { org: 'stand-in', moved: false, reason: 'bus-running' });
assert.deepEqual(f.admin.calls, [['rideMove', { org: 'stand-in', principal: { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' } }]]);
f.admin.rideAll = async () => { throw Object.assign(new Error(`${SENTINEL} busy`), { code: 'proxy-admin-busy' }); };
const busy = await hit(f, ['ride-all', 'POST', {}]);
assert.deepEqual(busy.json, { error: 'proxy-admin-busy' });
assert.equal(busy.text.includes(SENTINEL), false);
});
test('a signed-in member who is not the instance owner gets human-required for ride all and ride move', async t => {
const organizations = { list: async () => [], resolve: async id => (id === 'x' ? { busHealthy: true } : null) };
const member = await devServer(t, { organizations, sso: { ...createDevOwner(), session: () => ({ name: 'Bob', provider: 'local-dev', iss: 'local-dev', sub: 'bob', rootOwner: false, instanceRole: 'member' }) } });
for (const route of ROUTES.filter(([p]) => p.startsWith('ride-'))) {
const inOrg = await send(member.port, `/api/orgs/x/proxy/admin/${route[0]}`, { method: route[1], headers: member.headers(), body: route[2] });
assert.equal(inOrg.status, 403, route[0]); assert.deepEqual(inOrg.json, { error: 'human-required' }, route[0]);
const plain = await hit(member, route);
assert.equal(plain.status >= 400 && plain.status < 500, true, `${route[0]} outside an organization is refused`);
}
assert.deepEqual(member.admin.calls, []);
});