feat(model-proxy): Ride all puts the owner's organizations on the instance model proxy, and a cliproxy preset starts a new one on the owner's models (#1873) #1999
No files matched your search
@@ -5,6 +5,7 @@ import { listOrgs, orgLock, resolveOrg } from '../../organization/src/org-regist
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { templateRender, validateOrg, createOrg, showOrg, updateOrg, queueInit, queueShow, projectRepoInit, projectRepoShow, projectRepoSet, deleteOrg, archiveOrg, restoreOrg } from '../../organization/src/org-service.mjs';
|
||||
import { installedStarterPacks } from '../../plugins/src/starter-pack.mjs';
|
||||
import { appendReceipt } from '../../model-proxy/src/admin.mjs';
|
||||
import { DEV_OWNER, devOwnerInstance } from './dev-local-owner.mjs';
|
||||
import { loadSystem, orgPaths, rolesDir } from './config.mjs';
|
||||
import { CliError } from './errors.mjs';
|
||||
@@ -173,6 +174,18 @@ async function templateCommand(args, io, deps) {
|
||||
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
const busStartVerb = id => `mosaic bus start ${id} --dev-local-owner --detach`;
|
||||
// #1873 ride-default: `mosaic org update` that takes cliproxy off an organization records the removal
|
||||
// in the instance's proxy receipts first, where Ride all reads it, as the Console's admin save does.
|
||||
// A record that cannot be written refuses the update and writes nothing. A stale revision records
|
||||
// nothing and is left to updateOrg's own refusal.
|
||||
const providerList = doc => (Array.isArray(doc?.plugins?.['model-provider']) ? doc.plugins['model-provider'] : []);
|
||||
export async function orgUpdate(ctx, id, doc, { ifRevision, record = org => appendReceipt(ctx.dataRoot, { time: new Date().toISOString(), op: 'ride-removed', org }) } = {}) {
|
||||
const shown = await showOrg(ctx, id);
|
||||
if (shown.revision === ifRevision && providerList(shown.doc).includes('cliproxy') && !providerList(doc).includes('cliproxy')) {
|
||||
try { await record(id); } catch { throw new CliError('the removal of the model proxy could not be recorded, so nothing was saved', 3); }
|
||||
}
|
||||
return updateOrg(ctx, id, doc, { ifRevision });
|
||||
}
|
||||
export async function orgCommand(args, io, deps = {}) {
|
||||
try {
|
||||
// #1873 T1: the definitions verbs take their own options.
|
||||
@@ -195,7 +208,7 @@ export async function orgCommand(args, io, deps = {}) {
|
||||
const instance = devOwnerInstance(io.env); const system = deps.system ?? loadSystem({ env: io.env, instance }); const ctx = { configDir: configDir(io.env), dataRoot: system.dataRoot, instance, principal: DEV_OWNER };
|
||||
if (words[0] === 'lock' && ['show', 'clear'].includes(words[1]) && words.length === 3) { allowed([], []); result = await orgLock(ctx, words[2], { clear: words[1] === 'clear' }); }
|
||||
else if (words[0] === 'create' && words.length === 2) { allowed([], ['--from']); result = await createOrg(ctx, words[1], await document(need('--from'))); }
|
||||
else if (words[0] === 'update' && words.length === 2) { allowed([], ['--from', '--if-revision']); const r = need('--if-revision'); if (!/^[1-9][0-9]*$/.test(r)) throw new CliError('invalid revision', 4); result = await updateOrg(ctx, words[1], await document(need('--from')), { ifRevision: Number(r) }); }
|
||||
else if (words[0] === 'update' && words.length === 2) { allowed([], ['--from', '--if-revision']); const r = need('--if-revision'); if (!/^[1-9][0-9]*$/.test(r)) throw new CliError('invalid revision', 4); result = await orgUpdate(ctx, words[1], await document(need('--from')), { ifRevision: Number(r) }); }
|
||||
else if (words[0] === 'archive' && words.length === 2) result = await archiveOrg(ctx, words[1], { ...lifecycle, busStop: busStopForDelete, copyRemote: await (deps.copyRemoteFor ?? copyRemoteFor)(ctx) });
|
||||
else if (words[0] === 'restore' && words.length === 2) {
|
||||
const startBus = !p.flags.has('--no-bus');
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// #1873 ride-default, re-check 3 P1-1: `mosaic org update` that takes cliproxy off an organization
|
||||
// records the removal in the instance's proxy receipts before it writes, as the Console's admin save
|
||||
// does, so Ride all leaves the organization off.
|
||||
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 { orgUpdate } from '../src/org.mjs';
|
||||
import * as orgService from '../../organization/src/org-service.mjs';
|
||||
import { createProxyAdmin } from '../../model-proxy/src/admin-control.mjs';
|
||||
import { receiptFile } from '../../model-proxy/src/admin.mjs';
|
||||
|
||||
const owner = { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' };
|
||||
function scratch(t) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'org-upd-'));
|
||||
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 });
|
||||
return { configDir, dataRoot, instance: 'test', principal: owner };
|
||||
}
|
||||
const receipts = dataRoot => { try { return fs.readFileSync(receiptFile(dataRoot), 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse); } catch { return []; } };
|
||||
const withProviders = (doc, list) => ({ ...doc, plugins: { ...(doc.plugins ?? {}), 'model-provider': list } });
|
||||
async function cliproxyOrg(ctx, id) {
|
||||
const doc = withProviders(await orgService.templateRender(id), ['cliproxy']);
|
||||
await orgService.createOrg(ctx, id, doc);
|
||||
return orgService.showOrg(ctx, id);
|
||||
}
|
||||
|
||||
test('the reviewer probe: an organization taken off cliproxy by mosaic org update is skipped by Ride all as removed', async t => {
|
||||
const ctx = scratch(t);
|
||||
const shown = await cliproxyOrg(ctx, 'cli');
|
||||
await orgUpdate(ctx, 'cli', withProviders(shown.doc, []), { ifRevision: shown.revision });
|
||||
assert.deepEqual((await orgService.showOrg(ctx, 'cli')).doc.plugins['model-provider'], []);
|
||||
assert.deepEqual(receipts(ctx.dataRoot).map(r => [r.op, r.org]), [['ride-removed', 'cli']]);
|
||||
const writes = [];
|
||||
const call = async verb => {
|
||||
if (verb === 'plugins') return { revision: 'r', plugins: { 'model-provider': [] } };
|
||||
if (verb === 'proxy.accounts') return { accounts: [] };
|
||||
if (verb === 'plugins.set') { writes.push('cli'); return { revision: 'r2' }; }
|
||||
throw new Error(`unexpected ${verb}`);
|
||||
};
|
||||
const proxy = createProxyAdmin({ dataRoot: ctx.dataRoot, configDir: ctx.configDir, unit: { unit: 'u', status: async () => ({}) }, buses: async () => ({ stopped: true, running: [] }), fetch: async () => ({}),
|
||||
riders: async () => [{ id: 'cli', fixture: false, cliproxy: false, changes: '', call }] });
|
||||
const r = await proxy.rideAll();
|
||||
assert.deepEqual(r.added, []); assert.deepEqual(r.skipped, [{ id: 'cli', reason: 'removed' }]);
|
||||
assert.deepEqual(writes, []);
|
||||
});
|
||||
|
||||
test('mosaic org update records only a removal of cliproxy, and saves nothing when the record cannot be written', async t => {
|
||||
const ctx = scratch(t);
|
||||
const recorded = [];
|
||||
const record = async id => { recorded.push(id); };
|
||||
// Keeping cliproxy, or an organization that never had it, records nothing.
|
||||
let shown = await cliproxyOrg(ctx, 'keep');
|
||||
await orgUpdate(ctx, 'keep', { ...shown.doc }, { ifRevision: shown.revision, record });
|
||||
const plain = await orgService.templateRender('plain');
|
||||
await orgService.createOrg(ctx, 'plain', withProviders(plain, []));
|
||||
shown = await orgService.showOrg(ctx, 'plain');
|
||||
await orgUpdate(ctx, 'plain', { ...shown.doc }, { ifRevision: shown.revision, record });
|
||||
assert.deepEqual(recorded, []);
|
||||
// A stale revision records nothing and is refused by the service.
|
||||
shown = await cliproxyOrg(ctx, 'stale');
|
||||
await assert.rejects(orgUpdate(ctx, 'stale', withProviders(shown.doc, []), { ifRevision: shown.revision + 1, record }), { code: 'revision-conflict' });
|
||||
assert.deepEqual(recorded, []);
|
||||
// A record that fails refuses the update: the organization keeps cliproxy, at the same revision.
|
||||
await assert.rejects(orgUpdate(ctx, 'stale', withProviders(shown.doc, []), { ifRevision: shown.revision, record: async () => { throw Object.assign(new Error('disk full at /x/proxy-admin.jsonl'), { code: 'ENOSPC' }); } }),
|
||||
err => err.exitCode === 3 && err.message === 'the removal of the model proxy could not be recorded, so nothing was saved');
|
||||
const after = await orgService.showOrg(ctx, 'stale');
|
||||
assert.deepEqual(after.doc.plugins['model-provider'], ['cliproxy']); assert.equal(after.revision, shown.revision);
|
||||
// The removal itself records once, before the write.
|
||||
await orgUpdate(ctx, 'stale', withProviders(shown.doc, []), { ifRevision: shown.revision, record: async id => { recorded.push(id); assert.deepEqual((await orgService.showOrg(ctx, 'stale')).doc.plugins['model-provider'], ['cliproxy'], 'recorded before the write'); } });
|
||||
assert.deepEqual(recorded, ['stale']);
|
||||
});
|
||||
|
||||
test('the mosaic org update command records the removal in the instance\'s own proxy receipts', async t => {
|
||||
const { spawnSync } = await import('node:child_process');
|
||||
const { resolve } = await import('node:path');
|
||||
const repo = resolve(import.meta.dirname, '../../..');
|
||||
const home = fs.mkdtempSync(join(tmpdir(), 'org-upd-cli-'));
|
||||
t.after(() => fs.rmSync(home, { recursive: true, force: true }));
|
||||
const env = { ...process.env, HOME: home, MOSAIC_CONFIG: join(home, '.config/mosaic-orgupd/config.json') };
|
||||
const run = (cmd, ...args) => { const r = spawnSync(join(repo, cmd), args, { cwd: repo, env, encoding: 'utf8' }); assert.equal(r.status, 0, r.stderr); return r.stdout; };
|
||||
run('scripts/bootstrap.sh', '--instance', 'orgupd');
|
||||
const on = join(home, 'on.json'), off = join(home, 'off.json');
|
||||
const doc = withProviders(await orgService.templateRender('cliw'), ['cliproxy']);
|
||||
fs.writeFileSync(on, JSON.stringify(doc)); fs.writeFileSync(off, JSON.stringify(withProviders(doc, [])));
|
||||
run('scripts/mosaic', 'org', 'create', 'cliw', '--from', on);
|
||||
const { revision } = JSON.parse(run('scripts/mosaic', 'org', 'show', 'cliw', '--json'));
|
||||
run('scripts/mosaic', 'org', 'update', 'cliw', '--from', off, '--if-revision', String(revision));
|
||||
assert.deepEqual(JSON.parse(run('scripts/mosaic', 'org', 'show', 'cliw', '--json')).doc.plugins['model-provider'], []);
|
||||
assert.deepEqual(receipts(join(home, '.mosaic-orgupd')).map(r => [r.op, r.org]), [['ride-removed', 'cliw']]);
|
||||
});
|
||||
@@ -2,10 +2,12 @@
|
||||
// `mosaic proxy status|unit|init-lock|fence clear --restart`. Host actions run here; init and
|
||||
// the fence clear go to the bus, which decides them. Results and receipts carry labels, key IDs
|
||||
// and process ids only: never a key, token, absolute path or upstream text.
|
||||
import fs from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { fetchPinned } from './fetch.mjs';
|
||||
import { PIN } from './common.mjs';
|
||||
import { releaseState, initState, fenceState, initLockStatus, clearInitLock, appendReceipt, recentReceipts, createUnitControl, FILE_LABELS } from './admin.mjs';
|
||||
import { localRide, riddenOrgs } from './ride.mjs';
|
||||
import { releaseState, initState, fenceState, initLockStatus, clearInitLock, appendReceipt, recentReceipts, receiptsText, createUnitControl, FILE_LABELS } from './admin.mjs';
|
||||
|
||||
export const proxyCode = (error, fallback) => (/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : fallback);
|
||||
const failure = code => Object.assign(new Error(code), { code });
|
||||
@@ -13,7 +15,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, status}] where `changes` is the text of the organization's
|
||||
// change log, `call(verb, args)` reaches its bus as the owner and `status()` is its bus status. `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 +37,54 @@ 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') }; }
|
||||
}
|
||||
// The organizations this proxy's own receipts show cliproxy was or may have been on (riddenOrgs).
|
||||
// No receipt file yet is none; a file that fails receiptsText's check, or holds a line that does
|
||||
// not parse, is null, and localRide skips every organization without cliproxy as unreadable.
|
||||
function ridden() {
|
||||
const ids = riddenOrgs(receiptsText(dataRoot));
|
||||
return id => (ids === null ? null : ids.has(id));
|
||||
}
|
||||
const decide = (rider, wasRidden) => localRide({ ...rider, ridden: wasRidden(rider.id) });
|
||||
// Stopped is the organization admin page's test (org-admin bus stop): a bus status with no
|
||||
// process id. A status that cannot be read, or a rider with no status, is not stopped.
|
||||
async function stopped(rider) {
|
||||
if (typeof rider.status !== 'function') return false;
|
||||
try { return !Number.isSafeInteger((await rider.status())?.pid); } catch { return false; }
|
||||
}
|
||||
const failCode = error => (/^[a-z][a-z-]{0,63}$/.test(error?.code ?? '') ? error.code : '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.
|
||||
// A ride-intent receipt is on disk before plugins.set is sent; with no receipt there is no write.
|
||||
// When plugins.set fails and the bus then shows no cliproxy, a ride-not-added receipt clears that
|
||||
// intent. Any other failure leaves it: the add may have happened.
|
||||
async function rideOne(rider, wasRidden) {
|
||||
const id = rider.id, local = decide(rider, wasRidden);
|
||||
if (local === 'fixture') return { id, outcome: 'fixture', running: !(await stopped(rider)) };
|
||||
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' };
|
||||
// The receipts are read again here: a removal saved while this run worked on earlier
|
||||
// organizations is on file now, and the decision above came from the run's first read.
|
||||
const now = ridden()(id);
|
||||
if (now !== false) return { id, outcome: 'skipped', reason: now === null ? 'unreadable' : 'removed' };
|
||||
try { receipt({ op: 'ride-intent', org: id }); } catch { return { id, outcome: 'skipped', reason: 'not-recorded' }; }
|
||||
try { await rider.call('plugins.set', { revision: current.revision, plugins: { 'model-provider': [...providers, 'cliproxy'] } }); }
|
||||
catch (error) {
|
||||
try {
|
||||
const after = await rider.call('plugins');
|
||||
if (Array.isArray(after?.plugins?.['model-provider']) && !after.plugins['model-provider'].includes('cliproxy')) receipt({ op: 'ride-not-added', org: id });
|
||||
} catch { /* unknown outcome: the intent stands */ }
|
||||
return { id, outcome: 'failed', reason: failCode(error) };
|
||||
}
|
||||
return { id, outcome: 'added' };
|
||||
}
|
||||
async function rideSummary() {
|
||||
try { const wasRidden = ridden(); return (await riders()).map(r => ({ id: r.id, state: decide(r, wasRidden) })); } 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 +109,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 +130,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 +193,52 @@ 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(), wasRidden = ridden();
|
||||
const results = [];
|
||||
for (const rider of list) results.push(await rideOne(rider, wasRidden));
|
||||
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);
|
||||
// Each add already left its ride-intent receipt, so a summary that cannot be written still
|
||||
// answers what happened, with no receipt.
|
||||
let summary = null;
|
||||
try { summary = receipt({ op: 'ride-all', added, skipped, fixtures: fixtures.map(f => f.id) }); } catch { summary = null; }
|
||||
return { added, already, skipped, fixtures, receipt: summary };
|
||||
});
|
||||
},
|
||||
// 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 = decide(rider, ridden());
|
||||
if (local !== 'fixture') return { org, moved: false, reason: local };
|
||||
if (!(await stopped(rider))) 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: failCode(error) }; }
|
||||
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 }) };
|
||||
});
|
||||
},
|
||||
// The organization admin page calls this before it saves a document that drops cliproxy from
|
||||
// the model providers, and saves nothing when it throws. Ride all then leaves that organization off.
|
||||
rideRemoved(org) {
|
||||
if (typeof org !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(org)) throw failure('proxy-org-invalid');
|
||||
return receipt({ op: 'ride-removed', org });
|
||||
},
|
||||
async initLockClear() {
|
||||
return exclusive('init-lock-clear', async () => ({ receipt: clearInitLock({ configDir, dataRoot, buses: await buses(), now }) }));
|
||||
},
|
||||
|
||||
@@ -107,6 +107,26 @@ export function appendReceipt(dataRoot, record) {
|
||||
return record;
|
||||
}
|
||||
|
||||
// A file's text, read the way fenceState checks the fence file: opened without following a symlink
|
||||
// (and without blocking on a FIFO), a regular file the Console's own user owns, with none of the
|
||||
// `mask` permission bits. A missing file throws its ENOENT; any other failure throws
|
||||
// proxy-file-refused. `uid` is a test seam.
|
||||
export function ownedText(file, { mask = 0o077, uid = process.getuid() } = {}) {
|
||||
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
||||
try {
|
||||
const stat = fs.fstatSync(fd);
|
||||
if (!stat.isFile() || stat.uid !== uid || (stat.mode & mask)) throw Object.assign(new Error('proxy-file-refused'), { code: 'proxy-file-refused' });
|
||||
return fs.readFileSync(fd, 'utf8');
|
||||
} finally { fs.closeSync(fd); }
|
||||
}
|
||||
|
||||
// The whole receipt file's text for Ride all, which decides from it (ownedText, no group or other
|
||||
// bits). No file yet answers ''; anything else that fails answers null, and the caller treats every
|
||||
// organization without cliproxy as unreadable.
|
||||
export function receiptsText(dataRoot, { uid = process.getuid() } = {}) {
|
||||
try { return ownedText(receiptFile(dataRoot), { uid }); } catch (error) { return error?.code === 'ENOENT' ? '' : null; }
|
||||
}
|
||||
|
||||
// The last few receipts, oldest first, for the page after a reload. Reads only the file's tail and
|
||||
// skips a line that does not parse (a torn last write). Receipts never hold a key or a body.
|
||||
export function recentReceipts(dataRoot, limit = 10) {
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
// #1873 ride-default slice 1: the rules for "Ride all", which adds the instance's model proxy
|
||||
// (the cliproxy model provider) to the owner's existing organizations. Pure functions: the
|
||||
// Console wiring (webui cli.mjs) reads each organization and its bus, and admin-control runs them.
|
||||
import { usableModel } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
|
||||
export { usableModel };
|
||||
const has = (list, name) => Array.isArray(list) && list.includes(name);
|
||||
|
||||
// The model providers one change-log change shows before and after, by the change's path: the
|
||||
// list itself, the plugins object, or the whole document. Any other path shows none.
|
||||
function providersOf(change) {
|
||||
const at = value => change?.path === 'plugins.model-provider' ? value
|
||||
: change?.path === 'plugins' ? value?.['model-provider']
|
||||
: change?.path === '' ? value?.plugins?.['model-provider'] : undefined;
|
||||
return [at(change?.old), at(change?.new)];
|
||||
}
|
||||
const touchesProviders = path => path === '' || path === 'plugins' || path === 'plugins.model-provider';
|
||||
|
||||
// What the organization's change log shows of cliproxy, from its committed writes: `removed` when
|
||||
// a write took it off, `seen` when any write shows it on the organization before or after, or wrote
|
||||
// the providers without logging their values (a paths-only entry). A log that cannot be read
|
||||
// answers null, and the caller skips the organization as unreadable.
|
||||
export function cliproxyHistory(text) {
|
||||
if (typeof text !== 'string') return null;
|
||||
let removed = false, seen = false;
|
||||
try {
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line.trim()) continue;
|
||||
const event = JSON.parse(line);
|
||||
if (event?.state !== 'committed' || !Array.isArray(event.changes)) continue;
|
||||
for (const change of event.changes) {
|
||||
if (!touchesProviders(change?.path)) continue;
|
||||
if (!Object.hasOwn(change, 'old') && !Object.hasOwn(change, 'new')) { seen = true; continue; }
|
||||
const [before, after] = providersOf(change);
|
||||
if (has(before, 'cliproxy') && !has(after, 'cliproxy')) removed = true;
|
||||
if (has(before, 'cliproxy') || has(after, 'cliproxy')) seen = true;
|
||||
}
|
||||
}
|
||||
return { removed, seen };
|
||||
} catch { return null; }
|
||||
}
|
||||
export function cliproxyRemoved(text) { const h = cliproxyHistory(text); return h === null ? null : h.removed; }
|
||||
|
||||
// The organizations the proxy's own receipts (proxy-admin.jsonl) show cliproxy was or may have
|
||||
// been on: each ride-all receipt's added list, each ride-move's org, each ride-removed's org (the
|
||||
// organization admin page writes one before it saves a document without cliproxy), and each
|
||||
// ride-intent's org (Ride all writes one before each plugins.set) unless a later ride-not-added for
|
||||
// that organization shows the bus did not take it. Any line that does not parse, and any ride
|
||||
// record of the wrong shape, answers null: the caller then skips every organization without
|
||||
// cliproxy as unreadable. Text that is not a string answers null too.
|
||||
const RIDE_ORG = new Set(['ride-move', 'ride-removed', 'ride-intent', 'ride-not-added']);
|
||||
export function riddenOrgs(text) {
|
||||
if (typeof text !== 'string') return null;
|
||||
const ids = new Set(), pending = new Set();
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line.trim()) continue;
|
||||
let r; try { r = JSON.parse(line); } catch { return null; }
|
||||
if (!r || typeof r !== 'object' || Array.isArray(r)) return null;
|
||||
if (r.op === 'ride-all') {
|
||||
if (!Array.isArray(r.added) || !r.added.every(id => typeof id === 'string')) return null;
|
||||
for (const id of r.added) ids.add(id);
|
||||
} else if (RIDE_ORG.has(r.op)) {
|
||||
if (typeof r.org !== 'string') return null;
|
||||
if (r.op === 'ride-intent') pending.add(r.org);
|
||||
else if (r.op === 'ride-not-added') pending.delete(r.org);
|
||||
else ids.add(r.org);
|
||||
}
|
||||
}
|
||||
for (const id of pending) ids.add(id);
|
||||
return ids;
|
||||
}
|
||||
|
||||
// The local part of the decision, with no bus call: what Ride all does with one organization
|
||||
// before it asks the organization's bus anything. An organization that uses cliproxy now (and is
|
||||
// not a fixture organization) is already riding, whatever its history. One without cliproxy now
|
||||
// that had it, or may have had it, is removed: its change log or the proxy's receipts show it
|
||||
// (`ridden` is true from the receipts, null when they cannot be read).
|
||||
export function localRide({ fixture, cliproxy, changes, ridden = false }) {
|
||||
if (typeof fixture !== 'boolean' || typeof cliproxy !== 'boolean') return 'unreadable';
|
||||
if (cliproxy && !fixture) return 'already';
|
||||
const history = cliproxyHistory(changes);
|
||||
if (history === null || (ridden === null && !cliproxy)) return 'unreadable';
|
||||
if (history.removed || (!cliproxy && (ridden === true || history.seen))) return 'removed';
|
||||
if (fixture) return 'fixture';
|
||||
return 'ready';
|
||||
}
|
||||
|
||||
// One organization as Ride all reads it, without its bus: `read()` gives its document and
|
||||
// `readLog()` the text of its change log. A document that cannot be read leaves `fixture` and
|
||||
// `cliproxy` undefined, a log that does not exist yet is empty, and any other log failure is null;
|
||||
// localRide names either as unreadable. `isFixture(doc)` is the CLI's own fixture test.
|
||||
export function readRider({ id, read, readLog, isFixture }) {
|
||||
let doc = null, changes = null;
|
||||
try { doc = read(); } catch {}
|
||||
try { changes = readLog(); } catch (e) { changes = e?.code === 'ENOENT' ? '' : null; }
|
||||
const ok = !!doc && typeof doc === 'object';
|
||||
return { id, fixture: ok ? isFixture(doc) === true : undefined,
|
||||
cliproxy: ok ? (Array.isArray(doc.plugins?.['model-provider']) ? doc.plugins['model-provider'] : []).includes('cliproxy') : undefined, changes };
|
||||
}
|
||||
|
||||
// The owner's models: `proxy` is true when the instance's proxy.json names a port. Each organization
|
||||
// that lists cliproxy is asked for its routes at once, so a hung bus costs one timeout, not one each.
|
||||
// It rides when its bus answers a ready catalogue; the models are the cliproxy rows those
|
||||
// catalogues list, once each.
|
||||
export async function ownerModelsFrom({ proxy, riders }) {
|
||||
if (proxy !== true) return { proxy: false, riding: false, models: [] };
|
||||
const catalogues = await Promise.all((Array.isArray(riders) ? riders : []).filter(r => r?.cliproxy === true)
|
||||
.map(async r => { try { return (await r.call('routes'))?.catalogue; } catch { return null; } }));
|
||||
const models = new Map(); let riding = false;
|
||||
for (const catalogue of catalogues) {
|
||||
if (catalogue?.status !== 'ready' || !Array.isArray(catalogue.models)) continue;
|
||||
riding = true;
|
||||
// A key two buses list keeps the first usable row: one bus's stale row does not hide the model.
|
||||
for (const m of catalogue.models) {
|
||||
if (m?.module !== 'cliproxy' || typeof m.key !== 'string') continue;
|
||||
if (!models.has(m.key) || (!usableModel(models.get(m.key)) && usableModel(m))) models.set(m.key, m);
|
||||
}
|
||||
}
|
||||
return { proxy: true, riding, models: [...models.values()] };
|
||||
}
|
||||
|
||||
// The owner's model for an organization: the first usable catalogue model from claude, else
|
||||
// the first usable one, that serves every harness in `harnesses`.
|
||||
export function pickModel(models, harnesses = []) {
|
||||
const fits = (Array.isArray(models) ? models : []).filter(m => usableModel(m) && harnesses.every(h => m.harnesses.includes(h)));
|
||||
return fits.find(m => m.upstream === 'claude') ?? fits[0] ?? null;
|
||||
}
|
||||
|
||||
// A fixture organization moved to the owner's models: the fixture model provider becomes
|
||||
// cliproxy, each fixture model entry goes, and every role that used one uses the owner's model.
|
||||
// Answers { doc, model } or { reason } when no catalogue model serves the roles' harnesses.
|
||||
export function fixtureMove(doc, models) {
|
||||
const next = structuredClone(doc);
|
||||
const fixtureKeys = Object.entries(next.launch?.models ?? {}).filter(([, m]) => m?.module === 'fixture').map(([key]) => key);
|
||||
const uses = [];
|
||||
const visit = vars => {
|
||||
if (!vars || typeof vars !== 'object') return;
|
||||
for (const prefix of ['', 'fallback.']) if (fixtureKeys.includes(vars[prefix + 'model'])) uses.push({ vars, prefix });
|
||||
};
|
||||
// A model is an agent-layer var: an organization's roles and each project's own agents carry one.
|
||||
for (const role of Object.values(next.roles ?? {})) visit(role?.vars);
|
||||
for (const project of Object.values(next.projects ?? {})) for (const agent of Object.values(project?.agents ?? {})) visit(agent?.vars);
|
||||
const harnesses = [...new Set(uses.map(({ vars, prefix }) => vars[prefix + 'harness']).filter(h => typeof h === 'string'))];
|
||||
const model = pickModel(models, harnesses);
|
||||
if (!model) return { reason: 'no-model' };
|
||||
for (const key of fixtureKeys) delete next.launch.models[key];
|
||||
next.launch = next.launch ?? {}; next.launch.models = next.launch.models ?? {};
|
||||
next.launch.models[model.key] = { provider: model.provider, model: model.model, module: 'cliproxy', upstream: model.upstream };
|
||||
for (const { vars, prefix } of uses) vars[prefix + 'model'] = model.key;
|
||||
const providers = (next.plugins?.['model-provider'] ?? []).filter(n => n !== 'fixture');
|
||||
next.plugins = { ...(next.plugins ?? {}), 'model-provider': providers.includes('cliproxy') ? providers : [...providers, 'cliproxy'] };
|
||||
return { doc: next, model };
|
||||
}
|
||||
|
||||
// The move itself, through the organization service's existing whole-document update: read,
|
||||
// change, validate, then write only if the revision read is still current. Owner-only twice:
|
||||
// the Console route admits only the instance owner, and the service checks `ctx.principal`.
|
||||
export async function moveFixtureOrg({ service, ctx, id, models }) {
|
||||
const shown = await service.showOrg(ctx, id);
|
||||
const moved = fixtureMove(shown.doc, models);
|
||||
if (moved.reason) return { moved: false, reason: moved.reason };
|
||||
const checked = await service.validateOrg(moved.doc);
|
||||
if (!checked?.ok) return { moved: false, reason: 'invalid' };
|
||||
await service.updateOrg(ctx, id, moved.doc, { ifRevision: shown.revision });
|
||||
return { moved: true, model: moved.model.key };
|
||||
}
|
||||
@@ -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: (b.doc().plugins['model-provider'] ?? []).includes('cliproxy'), 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' });
|
||||
});
|
||||
@@ -0,0 +1,504 @@
|
||||
// #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, appendReceipt, receiptsText, ownedText } from '../src/admin.mjs';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { PIN } from '../src/common.mjs';
|
||||
import { cliproxyRemoved, localRide, riddenOrgs, 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');
|
||||
// Review round: an organization that uses cliproxy now is already riding, whatever its history.
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: removed }), 'already', 'removed once and added back');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: null }), 'already');
|
||||
assert.equal(localRide({ fixture: true, cliproxy: true, changes: '' }), 'fixture');
|
||||
// The proxy's receipts show it put cliproxy on the organization, and it lacks cliproxy now.
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: '', ridden: true }), 'removed');
|
||||
assert.equal(localRide({ fixture: true, cliproxy: false, changes: '', ridden: true }), 'removed');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: '', ridden: true }), 'already');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: '', ridden: null }), 'unreadable');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: '', ridden: null }), 'already');
|
||||
});
|
||||
|
||||
test('the proxy receipts name each organization ride all added, tried to add, moved or saw removed', () => {
|
||||
const lines = records => records.map(r => JSON.stringify(r)).join('\n') + '\n';
|
||||
const text = lines([{ op: 'ride-all', added: ['a', 'b'], skipped: [{ id: 'c', reason: 'bus-down' }], fixtures: ['d'] }, { op: 'ride-move', org: 'e', model: 'm' },
|
||||
{ op: 'fetch', added: ['f'] }, { op: 'ride-intent', org: 'g' }, { op: 'ride-removed', org: 'h' }]);
|
||||
assert.deepEqual([...riddenOrgs(text)].sort(), ['a', 'b', 'e', 'g', 'h']);
|
||||
assert.deepEqual([...riddenOrgs('')], []);
|
||||
assert.equal(riddenOrgs(null), null);
|
||||
// Round 3 (P2a): a line that does not parse, or a ride record of the wrong shape, fails closed.
|
||||
assert.equal(riddenOrgs(text + '{torn'), null, 'a torn line');
|
||||
assert.equal(riddenOrgs(lines([{ op: 'ride-all', added: [7] }])), null);
|
||||
assert.equal(riddenOrgs(lines([{ op: 'ride-all', added: 'a' }])), null);
|
||||
assert.equal(riddenOrgs(lines([{ op: 'ride-intent' }])), null);
|
||||
assert.equal(riddenOrgs(lines([{ op: 'ride-removed', org: 3 }])), null);
|
||||
assert.equal(riddenOrgs('7\n'), null, 'a line that is not a record');
|
||||
// Round 3 (P2b): an intent the bus then showed was not applied is cleared, and only that intent.
|
||||
assert.deepEqual([...riddenOrgs(lines([{ op: 'ride-intent', org: 'g' }, { op: 'ride-not-added', org: 'g' }]))], []);
|
||||
assert.deepEqual([...riddenOrgs(lines([{ op: 'ride-all', added: ['g'] }, { op: 'ride-intent', org: 'g' }, { op: 'ride-not-added', org: 'g' }]))], ['g'], 'an earlier add stays');
|
||||
assert.deepEqual([...riddenOrgs(lines([{ op: 'ride-removed', org: 'g' }, { op: 'ride-intent', org: 'g' }, { op: 'ride-not-added', org: 'g' }]))], ['g'], 'an earlier removal stays');
|
||||
assert.deepEqual([...riddenOrgs(lines([{ op: 'ride-not-added', org: 'g' }, { op: 'ride-intent', org: 'g' }]))], ['g'], 'a later intent stands');
|
||||
});
|
||||
|
||||
test('a change log that shows cliproxy on the organization at any time, or a write to its providers it cannot read, counts as removed once cliproxy is gone', () => {
|
||||
// Round 3 (P1 case b): added on the Settings page, then removed on the admin page, which writes no log entry.
|
||||
const added = committed([{ path: 'plugins.model-provider', old: [], new: ['cliproxy'] }]);
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: added }), 'removed');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: added }), 'already');
|
||||
assert.equal(localRide({ fixture: true, cliproxy: true, changes: added }), 'fixture', 'a fixture organization that lists cliproxy is still listed to move');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: committed([{ path: 'plugins', old: null, new: { 'model-provider': ['cliproxy'] } }]) }), 'removed');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: committed([{ path: '', old: null, new: { plugins: { 'model-provider': ['cliproxy'] } } }]) }), 'removed');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: committed([{ path: 'plugins.model-provider', oldPresent: true, newPresent: true }]) }), 'removed', 'a paths-only write to the providers');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: committed([{ path: 'roles.chief.vars', oldPresent: true, newPresent: true }]) }), 'ready', 'a paths-only write elsewhere');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: committed([{ path: 'plugins.model-provider', old: ['fixture'], new: ['openai'] }]) }), 'ready');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: JSON.stringify({ state: 'aborted', changes: [{ path: 'plugins.model-provider', old: [], new: ['cliproxy'] }] }) + '\n' }), 'ready', 'a write that did not commit');
|
||||
});
|
||||
|
||||
test('the reviewer probe: an organization created from the cliproxy preset and saved without it on its admin page is skipped as removed', async t => {
|
||||
// P1 case a. Nothing in the change log: the preset made it, the admin page took it off. The
|
||||
// admin page leaves a ride-removed receipt (proxy admin rideRemoved) before it saves.
|
||||
const b = bus({ providers: [] });
|
||||
const { admin: a, dataRoot } = admin(t, { riders: async () => [{ id: 'p', fixture: false, cliproxy: false, changes: '', call: b.call }] });
|
||||
assert.equal(a.rideRemoved('p').op, 'ride-removed');
|
||||
const r = await a.rideAll();
|
||||
assert.deepEqual(r.added, []); assert.deepEqual(r.skipped, [{ id: 'p', reason: 'removed' }]);
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
assert.deepEqual(receipts(dataRoot).filter(x => x.op === 'ride-removed').map(x => x.org), ['p']);
|
||||
assert.throws(() => a.rideRemoved('../x'), /proxy-org-invalid|invalid/);
|
||||
});
|
||||
|
||||
test('the reviewer probe: an organization added on the Settings page and removed on its admin page is skipped as removed', async t => {
|
||||
// P1 case b, with no ride-removed receipt at all: the change log's add is enough.
|
||||
const b = bus({ providers: [] });
|
||||
const log = committed([{ path: 'plugins.model-provider', old: [], new: ['cliproxy'] }]);
|
||||
const { admin: a } = admin(t, { riders: async () => [{ id: 's', fixture: false, cliproxy: false, changes: log, call: b.call }] });
|
||||
const r = await a.rideAll();
|
||||
assert.deepEqual(r.added, []); assert.deepEqual(r.skipped, [{ id: 's', reason: 'removed' }]);
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
});
|
||||
|
||||
test('each add leaves its intent receipt before plugins.set, and an add whose outcome is unknown stays recorded', async t => {
|
||||
// P2b. The bus reads the receipts at the moment of the write.
|
||||
let seen = null, dataRootOf = null;
|
||||
const order = [];
|
||||
const watching = id => { const b = bus({ providers: [] }); const call = async (verb, args) => { if (verb === 'plugins.set') { order.push(id); seen = receipts(dataRootOf()).map(r => `${r.op}:${r.org ?? ''}`); } return b.call(verb, args); }; return { ...b, call }; };
|
||||
const one = watching('one'), two = watching('two');
|
||||
const f = admin(t, { riders: async () => [{ id: 'one', fixture: false, cliproxy: false, changes: '', call: one.call }, { id: 'two', fixture: false, cliproxy: false, changes: '', call: two.call }] });
|
||||
dataRootOf = () => f.dataRoot;
|
||||
await f.admin.rideAll();
|
||||
assert.deepEqual(order, ['one', 'two']);
|
||||
assert.deepEqual(seen, ['ride-intent:one', 'ride-intent:two'], 'the first add is on record before the second starts');
|
||||
// Probe C: plugins.set commits, then the call times out. The bus shows cliproxy, so the intent stands.
|
||||
let providers = [];
|
||||
const timeout = { calls: [], call: async (verb, args) => {
|
||||
if (verb === 'plugins') return { revision: 'r1', plugins: { 'model-provider': providers } };
|
||||
if (verb === 'proxy.accounts') return { accounts: [] };
|
||||
if (verb === 'plugins.set') { providers = args.plugins['model-provider']; throw busError('timeout'); }
|
||||
} };
|
||||
let cp = false;
|
||||
const c = admin(t, { riders: async () => [{ id: 't', fixture: false, cliproxy: cp, changes: '', call: timeout.call }] });
|
||||
const first = await c.admin.rideAll();
|
||||
assert.deepEqual(first.skipped, [{ id: 't', reason: 'timeout' }]);
|
||||
assert.deepEqual(receipts(c.dataRoot).filter(r => r.org === 't').map(r => r.op), ['ride-intent']);
|
||||
providers = []; // the owner took it off
|
||||
assert.deepEqual((await c.admin.rideAll()).skipped, [{ id: 't', reason: 'removed' }]);
|
||||
// A refusal the bus shows was not applied clears the intent, so the organization can ride later.
|
||||
const refusedBus = bus({ providers: [], set: busError('revision-conflict') });
|
||||
const d = admin(t, { riders: async () => [{ id: 'q', fixture: false, cliproxy: false, changes: '', call: refusedBus.call }] });
|
||||
assert.deepEqual((await d.admin.rideAll()).skipped, [{ id: 'q', reason: 'revision-conflict' }]);
|
||||
assert.deepEqual(receipts(d.dataRoot).filter(r => r.org === 'q').map(r => r.op), ['ride-intent', 'ride-not-added']);
|
||||
assert.deepEqual((await d.admin.status()).ride, [{ id: 'q', state: 'ready' }]);
|
||||
// A bus that does not answer the re-read leaves the intent: the add may have happened.
|
||||
let gone = false;
|
||||
const lost = { call: async (verb, args) => { if (gone) throw busError('no-bus-host'); if (verb === 'plugins') return { revision: 'r1', plugins: { 'model-provider': [] } }; if (verb === 'proxy.accounts') return { accounts: [] }; if (verb === 'plugins.set') { gone = true; throw busError('timeout'); } } };
|
||||
const e = admin(t, { riders: async () => [{ id: 'l', fixture: false, cliproxy: false, changes: '', call: lost.call }] });
|
||||
await e.admin.rideAll();
|
||||
assert.deepEqual(receipts(e.dataRoot).filter(r => r.org === 'l').map(r => r.op), ['ride-intent']);
|
||||
});
|
||||
|
||||
test('a removal saved while Ride all works on earlier organizations is read before the later add', async t => {
|
||||
// Re-check 3, P3-1: the run's first read of the receipts showed nothing for 'late'. While the run
|
||||
// reads 'first', the owner takes cliproxy off 'late' on its admin page (a ride-removed receipt).
|
||||
let a = null;
|
||||
const first = bus({ providers: [] }), late = bus({ providers: [] });
|
||||
const firstCall = async (verb, args) => { if (verb === 'plugins') a.rideRemoved('late'); return first.call(verb, args); };
|
||||
const f = admin(t, { riders: async () => [{ id: 'first', fixture: false, cliproxy: false, changes: '', call: firstCall }, { id: 'late', fixture: false, cliproxy: false, changes: '', call: late.call }] });
|
||||
a = f.admin;
|
||||
const r = await a.rideAll();
|
||||
assert.deepEqual(r.added, ['first']); assert.deepEqual(r.skipped, [{ id: 'late', reason: 'removed' }]);
|
||||
assert.equal(late.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
assert.deepEqual(receipts(f.dataRoot).filter(x => x.org === 'late').map(x => x.op), ['ride-removed']);
|
||||
// Receipts that turn unreadable during the run skip the later add as unreadable.
|
||||
const g1 = bus({ providers: [] }), g2 = bus({ providers: [] });
|
||||
let g = null;
|
||||
const tear = async (verb, args) => { if (verb === 'plugins') { appendReceipt(g.dataRoot, { op: 'fetch' }); fs.appendFileSync(receiptFile(g.dataRoot), '{torn\n'); } return g1.call(verb, args); };
|
||||
g = admin(t, { riders: async () => [{ id: 'one', fixture: false, cliproxy: false, changes: '', call: tear }, { id: 'two', fixture: false, cliproxy: false, changes: '', call: g2.call }] });
|
||||
const s = await g.admin.rideAll();
|
||||
assert.deepEqual(s.skipped, [{ id: 'one', reason: 'unreadable' }, { id: 'two', reason: 'unreadable' }]);
|
||||
assert.equal(g2.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
});
|
||||
|
||||
test('an intent receipt that cannot be written stops that add before plugins.set', async t => {
|
||||
const b = bus({ providers: [] });
|
||||
const f = admin(t, { riders: async () => [{ id: 'w', fixture: false, cliproxy: false, changes: '', call: b.call }] });
|
||||
appendReceipt(f.dataRoot, { op: 'fetch' });
|
||||
fs.chmodSync(receiptFile(f.dataRoot), 0o400); // readable by its owner only, not writable
|
||||
const r = await f.admin.rideAll();
|
||||
assert.deepEqual(r.skipped, [{ id: 'w', reason: 'not-recorded' }]);
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
});
|
||||
|
||||
test('receipts that are torn, a symlink, not the owner\'s or open to others are unreadable, and every organization without cliproxy is skipped', async t => {
|
||||
// P2a and P3 (probes D and E).
|
||||
const b = bus({ providers: [] });
|
||||
const f = admin(t, { riders: async () => [{ id: 'z', fixture: false, cliproxy: false, changes: '', call: b.call }, { id: 'y', fixture: false, cliproxy: true, changes: '', call: b.call }] });
|
||||
const file = receiptFile(f.dataRoot);
|
||||
appendReceipt(f.dataRoot, { op: 'fetch' });
|
||||
fs.appendFileSync(file, '{"op":"ride-all","added":["z"]');
|
||||
let r = await f.admin.rideAll();
|
||||
assert.deepEqual(r.skipped, [{ id: 'z', reason: 'unreadable' }], 'torn'); assert.deepEqual(r.already, ['y']);
|
||||
fs.rmSync(file); fs.writeFileSync(join(f.dataRoot, 'state', 'empty'), '', { mode: 0o600 });
|
||||
fs.symlinkSync(join(f.dataRoot, 'state', 'empty'), file);
|
||||
assert.deepEqual((await f.admin.rideAll()).skipped, [{ id: 'z', reason: 'unreadable' }], 'symlink');
|
||||
assert.equal(fs.lstatSync(file).isSymbolicLink(), true);
|
||||
fs.rmSync(file); fs.writeFileSync(file, '', { mode: 0o600 }); fs.chmodSync(file, 0o640);
|
||||
assert.deepEqual((await f.admin.rideAll()).skipped, [{ id: 'z', reason: 'unreadable' }], 'group-readable');
|
||||
fs.rmSync(file); fs.mkdirSync(file);
|
||||
assert.deepEqual((await f.admin.rideAll()).skipped, [{ id: 'z', reason: 'unreadable' }], 'not a file');
|
||||
fs.rmSync(file, { recursive: true });
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
assert.deepEqual((await f.admin.rideAll()).added, ['z'], 'no receipt file is no history');
|
||||
});
|
||||
|
||||
test('the receipts are read only when the Console\'s own user owns them', t => {
|
||||
const f = admin(t);
|
||||
appendReceipt(f.dataRoot, { op: 'ride-removed', org: 'p' });
|
||||
assert.match(receiptsText(f.dataRoot), /"ride-removed"/);
|
||||
assert.equal(receiptsText(f.dataRoot, { uid: process.getuid() + 1 }), null, 'another user\'s file');
|
||||
});
|
||||
|
||||
test('a FIFO in place of the receipts is unreadable and never blocks the read', t => {
|
||||
const f = admin(t);
|
||||
fs.mkdirSync(join(f.dataRoot, 'state'), { mode: 0o700 });
|
||||
execFileSync('mkfifo', ['-m', '600', receiptFile(f.dataRoot)]);
|
||||
assert.equal(receiptsText(f.dataRoot), null);
|
||||
});
|
||||
|
||||
test('the change log read takes the writer\'s rule: group readable is fine, group writable, a symlink or a missing file is not', t => {
|
||||
const dir = fs.mkdtempSync(join(tmpdir(), 'rdo-')); t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
const file = join(dir, 'changes.jsonl'); fs.writeFileSync(file, 'x\n', { mode: 0o600 }); fs.chmodSync(file, 0o640);
|
||||
assert.equal(ownedText(file, { mask: 0o022 }), 'x\n');
|
||||
fs.chmodSync(file, 0o660);
|
||||
assert.throws(() => ownedText(file, { mask: 0o022 }), { code: 'proxy-file-refused' });
|
||||
fs.chmodSync(file, 0o600); fs.symlinkSync(file, join(dir, 'link'));
|
||||
assert.throws(() => ownedText(join(dir, 'link'), { mask: 0o022 }), { code: 'ELOOP' });
|
||||
assert.throws(() => ownedText(join(dir, 'gone'), { mask: 0o022 }), { code: 'ENOENT' });
|
||||
// readRider, as the Console wires it: a refused log is unreadable, a missing one is empty.
|
||||
const doc = { plugins: { 'model-provider': [] } };
|
||||
fs.chmodSync(file, 0o660);
|
||||
assert.equal(readRider({ id: 'a', read: () => doc, readLog: () => ownedText(file, { mask: 0o022 }), isFixture: () => false }).changes, null);
|
||||
assert.equal(readRider({ id: 'a', read: () => doc, readLog: () => ownedText(join(dir, 'gone'), { mask: 0o022 }), isFixture: () => false }).changes, '');
|
||||
});
|
||||
|
||||
test('a fixture organization that uses cliproxy now, with a removal in its log, is removed, not movable', () => {
|
||||
const log = committed([{ path: 'plugins.model-provider', old: ['fixture', 'cliproxy'], new: ['fixture'] }]) + committed([{ path: 'plugins.model-provider', old: ['fixture'], new: ['fixture', 'cliproxy'] }]);
|
||||
assert.equal(localRide({ fixture: true, cliproxy: true, changes: log }), 'removed');
|
||||
assert.equal(localRide({ fixture: true, cliproxy: true, changes: '' }), 'fixture');
|
||||
});
|
||||
|
||||
test('an organization ride all once added and its owner then saved without cliproxy is skipped as removed', async t => {
|
||||
// The organization's file as the Console reads it. The organization admin page saves a whole
|
||||
// document and writes no change-log entry, so the log stays empty after the owner's removal.
|
||||
let cliproxy = false;
|
||||
const b = bus({ providers: [] });
|
||||
const { admin: a, dataRoot } = admin(t, { riders: async () => [{ id: 'a', fixture: false, cliproxy, changes: '', call: b.call }] });
|
||||
assert.deepEqual((await a.rideAll()).added, ['a']);
|
||||
cliproxy = true;
|
||||
assert.deepEqual((await a.rideAll()).already, ['a']);
|
||||
cliproxy = false; // the owner saved the organization without cliproxy on its admin page
|
||||
const second = await a.rideAll();
|
||||
assert.deepEqual(second.skipped, [{ id: 'a', reason: 'removed' }], JSON.stringify(second));
|
||||
assert.equal(b.calls.filter(([verb]) => verb === 'plugins.set').length, 1, 'no second write');
|
||||
assert.deepEqual((await a.status()).ride, [{ id: 'a', state: 'removed' }]);
|
||||
// A fixture organization the proxy once moved, and its owner then put back on stand-in models, is not moved again.
|
||||
const moved = { id: 'f', fixture: true, cliproxy: false, changes: '', call: bus({ down: true }).call };
|
||||
const m = admin(t, { riders: async () => [moved], ownerModels: async () => ({ proxy: true, riding: true, models: [row()] }), move: async () => ({ moved: true, model: row().key }) });
|
||||
appendReceipt(m.dataRoot, { op: 'ride-move', org: 'f', model: row().key });
|
||||
assert.deepEqual(await m.admin.rideMove({ org: 'f' }), { org: 'f', moved: false, reason: 'removed' });
|
||||
// Receipts that cannot be read name every organization without cliproxy unreadable.
|
||||
fs.chmodSync(receiptFile(dataRoot), 0o200);
|
||||
assert.deepEqual((await a.rideAll()).skipped, [{ id: 'a', reason: 'unreadable' }]);
|
||||
});
|
||||
|
||||
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, status: async () => ({ pid: null }) },
|
||||
];
|
||||
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();
|
||||
// Round 3 (P2c): stopped is the organization admin page's test, a bus status with no process id.
|
||||
const stopped = async () => ({ healthy: false, pid: null }), running = async () => ({ healthy: true, pid: 4242 });
|
||||
const riders = async () => [
|
||||
{ id: 'stand-in', fixture: true, cliproxy: false, changes: '', call: stoppedBus.call, status: stopped },
|
||||
{ id: 'live', fixture: true, cliproxy: false, changes: '', call: runningBus.call, status: running },
|
||||
{ id: 'busy', fixture: true, cliproxy: false, changes: '', call: stoppedBus.call, status: async () => ({ healthy: false, pid: 4343 }) },
|
||||
{ id: 'unproven', fixture: true, cliproxy: false, changes: '', call: stoppedBus.call, status: async () => { throw busError('stale-host'); } },
|
||||
{ id: 'no-status', fixture: true, cliproxy: false, changes: '', call: stoppedBus.call },
|
||||
{ id: 'real', fixture: false, cliproxy: false, changes: '', call: stoppedBus.call, status: stopped },
|
||||
];
|
||||
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' });
|
||||
// A slow or busy bus that does not answer, a status that cannot be read, or no status at all is running.
|
||||
for (const org of ['busy', 'unproven', 'no-status']) assert.deepEqual(await f.admin.rideMove({ org, principal }), { org, moved: false, reason: 'bus-running' }, org);
|
||||
const listed = await f.admin.rideAll();
|
||||
assert.deepEqual(listed.fixtures, [{ id: 'stand-in', running: false }, { id: 'live', running: true }, { id: 'busy', running: true }, { id: 'unproven', running: true }, { id: 'no-status', running: true }]);
|
||||
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()]);
|
||||
// Review round: a key one bus lists as unavailable and another as usable keeps the usable row.
|
||||
const stale = row({ available: false, reason: 'proxy-down', label: 'stale' });
|
||||
assert.deepEqual((await ownerModelsFrom({ proxy: true, riders: [rider('s', true, ready([stale])), rider('a', true, ready([row()]))] })).models, [row()]);
|
||||
assert.deepEqual((await ownerModelsFrom({ proxy: true, riders: [rider('a', true, ready([row()])), rider('s', true, ready([stale]))] })).models, [row()]);
|
||||
});
|
||||
@@ -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 },
|
||||
};
|
||||
} }];
|
||||
}
|
||||
@@ -19,6 +19,10 @@ 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 { ownedText } from '../../model-proxy/src/admin.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 +222,31 @@ 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. The change log is read with the writer's
|
||||
// own check (no symlink, a regular file this user owns, not group or world writable).
|
||||
const rideRiders = async () => {
|
||||
const writer = organizationWriter({ dir: configDir(), rolesDir: rolesDir() });
|
||||
const local = id => readRider({ id, read: () => writer.read(id).document, readLog: () => ownedText(writer.logFile(id), { mask: 0o022 }), isFixture: orgUsesFixture });
|
||||
const down = async () => { throw Object.assign(new Error('the bus is not reachable'), { code: 'no-bus-host' }); };
|
||||
// The single-business Console has no bus status here: its organization never reads as stopped.
|
||||
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 {}
|
||||
// The organization admin page's stopped test reads this bus status (its process id).
|
||||
out.push({ ...local(org.id), call, status: () => orgBusStatus({ configDir: configDir(), dataRoot: system.dataRoot, instance }, org.id) });
|
||||
}
|
||||
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 +261,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 +337,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, rideRemoved: proxyAdmin ? id => proxyAdmin.rideRemoved(id) : null, 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 });
|
||||
|
||||
@@ -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,33 +286,53 @@ 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, rideRemoved = null } = {}) {
|
||||
let system = null;
|
||||
// The same context `mosaic org` builds (packages/cli/src/org.mjs): the named
|
||||
// instance from MOSAIC_CONFIG, its data root and its config directory.
|
||||
const context = async () => {
|
||||
if (!system) {
|
||||
const { loadSystem } = await import('../../cli/src/config.mjs');
|
||||
const { configDir } = await import('../../organization/src/organization-config.mjs');
|
||||
const { devOwnerInstance } = await import('../../cli/src/dev-local-owner.mjs');
|
||||
let instance; try { instance = devOwnerInstance(env); } catch { return null; }
|
||||
system = { configDir: configDir(env), dataRoot: loadSystem({ env, instance }).dataRoot, instance };
|
||||
}
|
||||
return system;
|
||||
};
|
||||
return createOrgAdmin({
|
||||
ownerModels, rideRemoved: rideRemoved ?? removalRecorder(context),
|
||||
service: () => load('../../organization/src/org-service.mjs'),
|
||||
registry: () => load('../../organization/src/org-registry.mjs'),
|
||||
bus: () => load('../../cli/src/org-bus.mjs'),
|
||||
// The same context `mosaic org` builds (packages/cli/src/org.mjs): the named
|
||||
// instance from MOSAIC_CONFIG, its data root and its config directory.
|
||||
context: async () => {
|
||||
if (!system) {
|
||||
const { loadSystem } = await import('../../cli/src/config.mjs');
|
||||
const { configDir } = await import('../../organization/src/organization-config.mjs');
|
||||
const { devOwnerInstance } = await import('../../cli/src/dev-local-owner.mjs');
|
||||
let instance; try { instance = devOwnerInstance(env); } catch { return null; }
|
||||
system = { configDir: configDir(env), dataRoot: loadSystem({ env, instance }).dataRoot, instance };
|
||||
}
|
||||
return system;
|
||||
},
|
||||
context,
|
||||
});
|
||||
}
|
||||
|
||||
// A Console without the proxy setup page still records a removal of cliproxy, in the instance's
|
||||
// proxy receipts (model-proxy admin.mjs appendReceipt), where Ride all reads it. `context()` gives
|
||||
// the instance's data root; with none, the record and the save are refused.
|
||||
export function removalRecorder(context) {
|
||||
return async id => {
|
||||
const ctx = await context(), proxy = await load('../../model-proxy/src/admin.mjs');
|
||||
if (!ctx?.dataRoot || !proxy) throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
|
||||
return proxy.appendReceipt(ctx.dataRoot, { time: new Date().toISOString(), op: 'ride-removed', org: id });
|
||||
};
|
||||
}
|
||||
|
||||
// `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.
|
||||
// `rideRemoved(id)` records in the proxy's receipts that a save took cliproxy off the organization,
|
||||
// so Ride all leaves it off; without it such a save is refused.
|
||||
export function createOrgAdmin({ service, registry = null, bus = null, context, ownerModels = null, rideRemoved = 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, rideRemoved };
|
||||
}
|
||||
const providersOf = doc => (Array.isArray(doc?.plugins?.['model-provider']) ? doc.plugins['model-provider'] : []);
|
||||
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 +434,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) });
|
||||
}
|
||||
@@ -509,6 +539,12 @@ async function route(req, res, { path, search, org, admin, principal, write, log
|
||||
const doc = toCanonical(id, body.doc, shown.doc);
|
||||
const checked = await service.validateOrg(doc);
|
||||
if (!checked.ok) return json(res, 422, { error: 'invalid', step: 'update', errors: withField(checked.errors ?? []) });
|
||||
// #1873 ride-default: a save that takes cliproxy off leaves a proxy receipt first, so Ride all
|
||||
// does not put it back. No record, no save.
|
||||
if (providersOf(shown.doc).includes('cliproxy') && !providersOf(doc).includes('cliproxy')) {
|
||||
if (typeof admin.rideRemoved !== 'function') return json(res, 503, { error: 'not-configured', step: 'update', message: 'this Console cannot record that the model proxy was taken off, so nothing was saved' });
|
||||
try { await admin.rideRemoved(id); } catch { return json(res, 500, { error: 'internal', step: 'update', message: 'the removal of the model proxy could not be recorded, so nothing was saved' }); }
|
||||
}
|
||||
let receipt;
|
||||
try { receipt = await service.updateOrg(ctx, id, doc, { ifRevision: body.ifRevision }); } catch (e) { return refusal(res, e, { step: 'update', id, unknownOk: true }); }
|
||||
return json(res, 200, { outcome: 'done', step: 'update', receipt: forReceipt(ctx, receipt), verb: verbFor('update', id, { revision: body.ifRevision }) });
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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,74 @@ 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: 'The model proxy was on it, or Ride all may have added it, and it is off now. Ride all leaves it off. Add it on its Settings page to use it.',
|
||||
'not-recorded': 'The proxy could not record the change first, so it was not made.',
|
||||
'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, its change log or the proxy\'s receipts could not be read. A damaged line in the proxy\'s receipts must be repaired by hand before Ride all adds again.',
|
||||
failed: 'Its bus refused the change.',
|
||||
'bus-running': 'Its bus is running, or its state could not be read. Stop or recover its bus, 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': 'Moving organizations is not available on this Console yet. It works on a local development Console.',
|
||||
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] ?? `The change was refused (${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.
|
||||
@@ -776,7 +846,9 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
async function act(label, action) {
|
||||
if (!sendOk || state?.busy) return;
|
||||
state = { ...state, busy: label }; paintNext(); paintControls(); say('Working…');
|
||||
try { await action(); } catch (error) { say(error.message, 'error'); } finally { if (state) state = { ...state, busy: null }; await load(); }
|
||||
// A load still waiting on accounts makes the load below return at once, so the answer is
|
||||
// painted here first from the state already read.
|
||||
try { await action(); } catch (error) { say(error.message, 'error'); } finally { if (state) { state = { ...state, busy: null }; paint(); } await load(); }
|
||||
}
|
||||
const fetchRelease = () => act('fetch', async () => { await admin('fetch', {}); seenFetch = null; say('Fetch started.'); });
|
||||
const clearLock = () => act('init-lock-clear', async () => { const result = await admin('init-lock/clear', {}); addReceipt(result.receipt); say('Stale init lock cleared.', 'success'); });
|
||||
|
||||
@@ -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, rideRemoved = 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, rideRemoved }), 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 });
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { createOrgAdmin, orgAdminHTTP, browserProblems, pathFromMessage, toCanonical, forBrowser, plainMessage } from '../src/org-admin.mjs';
|
||||
import { createOrgAdmin, defaultOrgAdmin, removalRecorder, orgAdminHTTP, browserProblems, pathFromMessage, toCanonical, forBrowser, plainMessage } from '../src/org-admin.mjs';
|
||||
import { actionTrail } from '../src/action-trail.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
@@ -1074,3 +1074,145 @@ 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');
|
||||
});
|
||||
|
||||
// #1873 ride-default round 3 (P1): a save on the admin page that drops cliproxy from the model
|
||||
// providers leaves a ride-removed record first, so the next Ride all leaves the organization off.
|
||||
test('a save that takes cliproxy off records the removal before it writes, and saves nothing when it cannot', async t => {
|
||||
const removed = [];
|
||||
let fail = null;
|
||||
const f = fakes();
|
||||
const admin = createOrgAdmin({ service: f.service, registry: await f.admin.registry(), bus: null, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }), rideRemoved: async id => { if (fail) throw fail; removed.push(id); } });
|
||||
const c = await console_(t, { orgAdmin: admin });
|
||||
const d = { call: c.call, orgs: f.orgs, calls: f.calls };
|
||||
await d.call('POST', '/api/orgs', { id: 'acme', doc: browserDoc('acme') });
|
||||
d.orgs.get('acme').doc.plugins = { 'model-provider': ['cliproxy', 'openai'] };
|
||||
const save = async providers => {
|
||||
const shown = await d.call('GET', '/api/orgs/acme/admin');
|
||||
const doc = shown.body.doc; doc.plugins = { 'model-provider': providers };
|
||||
return d.call('POST', '/api/orgs/acme/admin', { doc, ifRevision: shown.body.revision });
|
||||
};
|
||||
// Keeping cliproxy records nothing.
|
||||
let r = await save(['cliproxy']);
|
||||
assert.equal(r.status, 200, r.raw); assert.deepEqual(removed, []);
|
||||
// The hook fails: nothing is saved.
|
||||
fail = new Error('disk full /data/state/proxy-admin.jsonl');
|
||||
r = await save(['openai']);
|
||||
assert.equal(r.status, 500, r.raw); assert.equal(r.body.error, 'internal');
|
||||
assert.doesNotMatch(r.raw, /proxy-admin\.jsonl|disk full/);
|
||||
assert.deepEqual(d.orgs.get('acme').doc.plugins['model-provider'], ['cliproxy']);
|
||||
fail = null;
|
||||
const updates = d.calls.filter(x => x[0] === 'updateOrg').length;
|
||||
r = await save(['openai']);
|
||||
assert.equal(r.status, 200, r.raw); assert.deepEqual(removed, ['acme']);
|
||||
assert.equal(d.calls.filter(x => x[0] === 'updateOrg').length, updates + 1);
|
||||
assert.deepEqual(d.orgs.get('acme').doc.plugins['model-provider'], ['openai']);
|
||||
// A Console wired without the record refuses that save.
|
||||
const plain = await console_(t);
|
||||
await plain.call('POST', '/api/orgs', { id: 'acme', doc: browserDoc('acme') });
|
||||
plain.orgs.get('acme').doc.plugins = { 'model-provider': ['cliproxy'] };
|
||||
const shown = await plain.call('GET', '/api/orgs/acme/admin');
|
||||
const doc = shown.body.doc; doc.plugins = { 'model-provider': [] };
|
||||
r = await plain.call('POST', '/api/orgs/acme/admin', { doc, ifRevision: shown.body.revision });
|
||||
assert.equal(r.status, 503, r.raw); assert.equal(r.body.error, 'not-configured');
|
||||
assert.deepEqual(plain.orgs.get('acme').doc.plugins['model-provider'], ['cliproxy']);
|
||||
assert.equal(plain.calls.some(x => x[0] === 'updateOrg'), false);
|
||||
});
|
||||
|
||||
// The reviewer's two P1 probes end to end: the real organization service, the admin page route,
|
||||
// the real proxy admin and its receipts, and the organization file and change log as Ride all reads them.
|
||||
test('against the real C2 service: an organization saved without cliproxy on its admin page is skipped by Ride all as removed', async t => {
|
||||
const service = await import('../../organization/src/org-service.mjs');
|
||||
const registry = await import('../../organization/src/org-registry.mjs');
|
||||
const { organizationWriter } = await import('../../organization/src/organization.mjs');
|
||||
const { createProxyAdmin } = await import('../../model-proxy/src/admin-control.mjs');
|
||||
const { readRider } = await import('../../model-proxy/src/ride.mjs');
|
||||
const { orgUsesFixture } = await import('../../cli/src/dev-fixture.mjs');
|
||||
const { mkdtempSync, mkdirSync, readFileSync, rmSync } = await import('node:fs');
|
||||
const { join, resolve, dirname } = await import('node:path'); const { tmpdir } = await import('node:os'); const { fileURLToPath } = await import('node:url');
|
||||
const root = mkdtempSync(join(tmpdir(), 'oar')); const configDir = join(root, 'config'), dataRoot = join(root, 'data');
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
mkdirSync(configDir, { mode: 0o700 }); mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const rolesDir = resolve(dirname(fileURLToPath(import.meta.url)), '../../../roles');
|
||||
const writes = [];
|
||||
const busFor = id => async (verb, args) => {
|
||||
if (verb === 'plugins') return { revision: 'r', plugins: { 'model-provider': organizationWriter({ dir: configDir, rolesDir }).read(id).document.plugins?.['model-provider'] ?? [] } };
|
||||
if (verb === 'proxy.accounts') return { accounts: [] };
|
||||
if (verb === 'plugins.set') { writes.push(id); return { revision: 'r2' }; }
|
||||
throw new Error(`unexpected ${verb}`);
|
||||
};
|
||||
const riders = async () => ['made', 'settings'].map(id => {
|
||||
const writer = organizationWriter({ dir: configDir, rolesDir });
|
||||
return { ...readRider({ id, read: () => writer.read(id).document, readLog: () => readFileSync(writer.logFile(id), 'utf8'), isFixture: orgUsesFixture }), call: busFor(id) };
|
||||
});
|
||||
const proxy = createProxyAdmin({ dataRoot, configDir, unit: { unit: 'u', status: async () => ({}) }, buses: async () => ({ stopped: true, running: [] }), fetch: async () => ({}), riders });
|
||||
const admin = createOrgAdmin({ service, registry, bus: null, context: async () => ({ configDir, dataRoot, instance: 'test' }), rideRemoved: id => proxy.rideRemoved(id) });
|
||||
const c = await console_(t, { orgAdmin: admin });
|
||||
const tpl = (await c.call('GET', '/api/org-template?id=made')).body.doc;
|
||||
// Probe a: made on cliproxy (as the preset makes it), then saved without it on the admin page.
|
||||
const made = await c.call('POST', '/api/orgs', { id: 'made', doc: { ...tpl, plugins: { 'model-provider': ['cliproxy'] } } });
|
||||
assert.equal(made.status, 201, made.raw);
|
||||
// Probe b: cliproxy added through the organization writer (as the Settings page's bus plugins.set writes it, with a change-log entry), then removed on the admin page.
|
||||
const tpl2 = (await c.call('GET', '/api/org-template?id=settings')).body.doc;
|
||||
assert.equal((await c.call('POST', '/api/orgs', { id: 'settings', doc: tpl2 })).status, 201);
|
||||
const writer = organizationWriter({ dir: configDir, rolesDir });
|
||||
const current = writer.read('settings');
|
||||
writer.write('settings', { ...current.document, plugins: { ...(current.document.plugins ?? {}), 'model-provider': ['cliproxy'] } }, { revision: current.revision, actor: current.document.human });
|
||||
assert.match(readFileSync(writer.logFile('settings'), 'utf8'), /cliproxy/);
|
||||
for (const id of ['made', 'settings']) {
|
||||
const shown = await c.call('GET', `/api/orgs/${id}/admin`);
|
||||
assert.deepEqual(shown.body.doc.plugins['model-provider'], ['cliproxy'], id);
|
||||
const doc = shown.body.doc; doc.plugins = { 'model-provider': [] };
|
||||
const r = await c.call('POST', `/api/orgs/${id}/admin`, { doc, ifRevision: shown.body.revision });
|
||||
assert.equal(r.status, 200, r.raw);
|
||||
}
|
||||
const result = await proxy.rideAll();
|
||||
assert.deepEqual(result.added, []);
|
||||
assert.deepEqual(result.skipped, [{ id: 'made', reason: 'removed' }, { id: 'settings', reason: 'removed' }]);
|
||||
assert.deepEqual(writes, [], 'Ride all put cliproxy back on neither');
|
||||
});
|
||||
|
||||
test('a Console without the proxy setup page records the removal in the instance\'s proxy receipts, and refuses with no data root', async t => {
|
||||
const { riddenOrgs } = await import('../../model-proxy/src/ride.mjs');
|
||||
const { receiptsText } = await import('../../model-proxy/src/admin.mjs');
|
||||
const dataRoot = mkdtempSync(join(tmpdir(), 'oarr')); t.after(() => rmSync(dataRoot, { recursive: true, force: true }));
|
||||
const record = await removalRecorder(async () => ({ dataRoot }))('acme');
|
||||
assert.equal(record.op, 'ride-removed'); assert.equal(record.org, 'acme');
|
||||
assert.deepEqual([...riddenOrgs(receiptsText(dataRoot))], ['acme']);
|
||||
await assert.rejects(removalRecorder(async () => null)('acme'), /not-configured/);
|
||||
});
|
||||
|
||||
test('the default Console wiring always has a removal recorder, and keeps the one it is given', () => {
|
||||
assert.equal(typeof defaultOrgAdmin({}).rideRemoved, 'function');
|
||||
const given = async () => ({ op: 'ride-removed' });
|
||||
assert.equal(defaultOrgAdmin({}, { rideRemoved: given }).rideRemoved, given);
|
||||
});
|
||||
@@ -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, []);
|
||||
});
|
||||
@@ -144,3 +144,67 @@ test('after a reload the receipts come from status, and an initialized proxy fol
|
||||
await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/unit/install")');
|
||||
await wait('document.querySelector("#proxy-setup-init-box").open===false');
|
||||
});
|
||||
|
||||
// #1873 ride-default: the Ride all box. The confirm names the stricter admission, the answer's
|
||||
// skips and stand-in organizations are painted even while an earlier load still waits on the
|
||||
// accounts read, and the move confirm says the organization spends real tokens after it.
|
||||
test('Ride all confirms the stricter admission, paints skips and stand-in organizations while a load waits, and the move warns of real tokens', { timeout: 90000 }, async t => {
|
||||
const running = { ...fenced, fence: { set: false }, restart: null, next: ['ride-all'],
|
||||
ride: [{ id: 'north', state: 'ready' }, { id: 'south', state: 'ready' }, { id: 'west', state: 'fixture' }] };
|
||||
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(running),
|
||||
'POST /api/proxy/admin/ride-all': { body: { added: ['south'], already: [], skipped: [], fixtures: [{ id: 'west' }], receipt: { op: 'ride.all', time: T } } },
|
||||
'POST /api/proxy/admin/ride-move': { body: { moved: false, reason: 'bus-running' } } } });
|
||||
// The first accounts and keys reads answer not-configured; every later pair never answers, so a load stays in flight.
|
||||
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `(() => { const inner = window.fetch; let n = 0; window.__confirms = [];
|
||||
window.confirm = text => { window.__confirms.push(text); return true; };
|
||||
window.fetch = (input, init) => { const url = String(typeof input === 'string' ? input : input.url);
|
||||
if (url.includes('/api/proxy/accounts') && n++ > 0) return new Promise(() => {});
|
||||
if (url.includes('/api/proxy/keys') && n > 1) return new Promise(() => {});
|
||||
return inner(input, init); }; })();` });
|
||||
await b.navigate(f.base + '/#/settings/model-proxy');
|
||||
await wait('document.querySelector("#proxy-ride")?.hidden===false && document.querySelector("#proxy-setup-go")?.dataset.next==="ride-all"');
|
||||
assert.match(await b.evaluate('document.querySelector("#proxy-ride-text").textContent'), /every launch route is checked, direct Anthropic routes too.*2 organizations can ride now/);
|
||||
assert.match(await b.evaluate('document.querySelector("#proxy-ride-fixtures li").textContent'), /^west uses stand-in models, can be moved to the owner's models\./);
|
||||
// The first Ride all's own reload paints, then waits on the accounts read for good.
|
||||
await b.evaluate('document.querySelector("#proxy-ride-go").click()');
|
||||
await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/ride-all")');
|
||||
assert.match(await b.evaluate('window.__confirms[0]'), /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/);
|
||||
await wait('document.querySelector("#proxy-ride-message").textContent.includes("Added to 1")');
|
||||
await wait('document.querySelector("#proxy-ride-go").disabled===false');
|
||||
// The second answer lands while that load is still in flight.
|
||||
await b.evaluate(`window.__scenario['POST /api/proxy/admin/ride-all'] = { body: ${JSON.stringify({ added: [], already: ['south'], skipped: [{ id: 'north', reason: 'no-proxy-client' }], fixtures: [{ id: 'west', running: true }], receipt: { op: 'ride.all', time: T } })} }`);
|
||||
await b.evaluate('document.querySelector("#proxy-ride-go").click()');
|
||||
await wait('window.__writes.filter(w=>w.path==="/api/proxy/admin/ride-all").length===2');
|
||||
await wait('document.querySelector("#proxy-ride-message").textContent.includes("skipped 1")');
|
||||
await wait('document.querySelectorAll("#proxy-ride-skips li").length===1');
|
||||
assert.equal(await b.evaluate('document.querySelector("#proxy-ride-skips li").textContent'), 'Skipped north: Its bus started before the proxy was set up. Restart its bus, then ride again.');
|
||||
assert.match(await b.evaluate('document.querySelector("#proxy-ride-fixtures li").textContent'), /Its bus is running: stop it first\./);
|
||||
assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").disabled'), false, 'the box is not left busy');
|
||||
await b.evaluate('document.querySelector("[data-ride-move=west]").click()');
|
||||
await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/ride-move")');
|
||||
assert.match(await b.evaluate('window.__confirms[2]'), /^Move west to your models\?.*its agents spend real tokens on your account/);
|
||||
assert.deepEqual(JSON.parse(await b.evaluate('window.__writes.find(w=>w.path==="/api/proxy/admin/ride-move").body')), { org: 'west' });
|
||||
// Re-check 3 (P3-2): a running bus and a bus whose state cannot be read get the same refusal, in words that fit both.
|
||||
await wait(`document.querySelector("#proxy-ride-message").textContent===${JSON.stringify('west was not moved. Its bus is running, or its state could not be read. Stop or recover its bus, then move it.')}`);
|
||||
// Round 3 (P3): an SSO Console's org-forbidden in plain words, and the neutral fallback for a code the page does not know.
|
||||
for (const [n, reason, text] of [[2, 'org-forbidden', 'west was not moved. Moving organizations is not available on this Console yet. It works on a local development Console.'],
|
||||
[3, 'frobnicated', 'west was not moved. The change was refused (frobnicated).']]) {
|
||||
await b.evaluate(`window.__scenario['POST /api/proxy/admin/ride-move'] = { body: ${JSON.stringify({ moved: false, reason })} }`);
|
||||
await wait('document.querySelector("[data-ride-move=west]")?.disabled===false');
|
||||
await b.evaluate('document.querySelector("[data-ride-move=west]").click()');
|
||||
await wait(`window.__writes.filter(w=>w.path==="/api/proxy/admin/ride-move").length===${n}`);
|
||||
await wait(`document.querySelector("#proxy-ride-message").textContent===${JSON.stringify(text)}`);
|
||||
}
|
||||
// Round 3: an organization the proxy was or may have been on, and an add the receipt could not record first.
|
||||
await b.evaluate(`window.__scenario['POST /api/proxy/admin/ride-all'] = { body: ${JSON.stringify({ added: [], already: [], skipped: [{ id: 'north', reason: 'removed' }, { id: 'south', reason: 'not-recorded' }, { id: 'east', reason: 'unreadable' }], fixtures: [], receipt: { op: 'ride.all', time: T } })} }`);
|
||||
await wait('document.querySelector("#proxy-ride-go").disabled===false');
|
||||
await b.evaluate('document.querySelector("#proxy-ride-go").click()');
|
||||
await wait('window.__writes.filter(w=>w.path==="/api/proxy/admin/ride-all").length===3');
|
||||
await wait('document.querySelectorAll("#proxy-ride-skips li").length===3');
|
||||
assert.deepEqual(JSON.parse(await b.evaluate('JSON.stringify([...document.querySelectorAll("#proxy-ride-skips li")].map(li=>li.textContent))')), [
|
||||
'Skipped north: The model proxy was on it, or Ride all may have added it, and it is off now. Ride all leaves it off. Add it on its Settings page to use it.',
|
||||
'Skipped south: The proxy could not record the change first, so it was not made.',
|
||||
// Re-check 3 (P3-3): a damaged receipts line stops every add until someone repairs it.
|
||||
'Skipped east: Its organization file, its change log or the proxy\'s receipts could not be read. A damaged line in the proxy\'s receipts must be repaired by hand before Ride all adds again.']);
|
||||
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
|
||||
});
|
||||
Reference in new issue
Block a user