Files
stack/packages/business/src/instance-settings.mjs
T
jason.woltje c216f47dbb plugins, cli, bus, business, webui: harness, model and thinking from the instance vars, a fallback route, and a harness plug-in kind (row 65, #1558)
Adds the harness plug-in kind (interface 1). packages/plugins/harness/pi
and claude-code hold what core branched on: the adapter, thinking levels,
preflight, version probe, sandbox mounts, builtins line, typed tool names,
gate timeout, bundle files, adapter env, turn end and session-files path.
Core reaches a module only through the loader.

A session's route is the instance's harness, model and thinking vars, or
the three fallback. vars; a missing one refuses no-route, and the system
file's execution keys are never read for a session. The launcher checks
the primary route, then the fallback: harness-off, harness-refused,
thinking-unsupported, then preflight. A failed preflight falls back when
a fallback is set, and any refusal of the fallback names the primary's
failure too. Account checks run
only when the route's module counts an account. The manifest records
route, routeReason and harnessVersion, replacing piVersion and
claudeVersion. pi gets --thinking, Claude Code --effort, both from
MOSAIC_THINKING.

The business file refuses a partial fallback. routes and routes.set are
human-only bus verbs outside ORGANIZATION_KEYS; checkRoutes is shared by
routes.set, instances.set and limits.set and checks only changed routes.
The chief of staff changes an instance's model, and the assistant's whole
vars (Q169), through limits.set, so its route write runs the same checks.
A model outside launch.models refuses unknown-model, primary or fallback,
and routes.set passes that code through.
A new run binds only on a switched-on harness module name and records
its transcript path, which the usage reader uses. Settings gains a
Routing table with six selects per instance and loses the Role models
fieldset; it posts changed rows to /api/routes. webui/src/bus.mjs is
unchanged.

Until Jason's `mosaic plugins set` adds "harness": ["claude-code"], a new
launch refuses harness-off.
2026-10-19 11:27:19 -05:00

160 lines
8.7 KiB
JavaScript

// Row 165 (#1662, Q171): the human adds a role instance and changes an existing one's definition,
// vars and launch membership. It is human-only: the broker's instances and instances.set verbs
// reach it, and neither is in ORGANIZATION_KEYS, so the chief of staff's tool can't (sage-0918).
// holder, credentials and tracker stay hand edits, and there is no delete. Every write goes
// through the organization writer, which logs the actor and the old and new values.
import { existsSync, readdirSync } from "node:fs";
import { organizationWriter, OrganizationError } from "./organization.mjs";
import { validateBusinessDocument, businessFilePath } from "./business.mjs";
import { checkRoutes } from "./launch-settings.mjs";
import { loadProject, projectFilePath } from "./project.mjs";
import { resolveInstance } from "./resolve.mjs";
import { loadRole } from "./role.mjs";
import { isPlainObject, canonicalJson } from "./util.mjs";
import { END_PROTECTED, ID_PATTERN } from "./vocabulary.mjs";
const SET_KEYS = ["revision", "instance", "op", "definition", "vars", "launch"];
const id = value => typeof value === "string" && ID_PATTERN.test(value);
// A definition this writer can give an instance: version 2, not END_PROTECTED, and declaring no
// credential. An instance of one that declares credentials needs credentials and a tracker bot,
// which stay out of this row (sage-0918); the refusal names that, so a later row lifts it alone.
function definitionFor(rolesDir, name) {
if (END_PROTECTED.includes(name)) throw new OrganizationError("organization-definition-refused");
const definition = loadRole(rolesDir, name);
if (definition.roleVersion !== 2) throw new OrganizationError("invalid-request", `role definition ${name} is version 1`);
if (definition.credentials.length > 0) {
throw new OrganizationError("organization-credentials-out-of-scope",
`${name} declares ${definition.credentials.map(c => c.service).join(" and ")} credentials; binding them is a hand edit`);
}
return definition;
}
// levels(name): the thinking levels harness module `name` applies, or null (launch-settings.mjs
// checkRoutes, row 65).
export function instanceSettings({ dir, rolesDir, system, levels = () => null }) {
const writer = organizationWriter({ dir, rolesDir });
// The definitions in rolesDir and whether add and set accept each one.
function definitions() {
const out = {};
for (const file of readdirSync(rolesDir).filter(f => f.endsWith(".json")).sort()) {
const name = file.slice(0, -5);
let definition;
try {
definition = loadRole(rolesDir, name);
} catch (e) {
if (e.name === "BusinessError") continue;
throw e;
}
if (definition.roleVersion !== 2) continue;
const services = definition.credentials.map(c => c.service);
out[name] = { services, accepted: !END_PROTECTED.includes(name) && services.length === 0 };
}
return out;
}
function read(business) {
const { document, revision } = writer.read(business);
validateBusinessDocument(document, businessFilePath(business, dir), { rolesDir });
const launch = document.launch ?? null;
const instances = Object.fromEntries(Object.entries(document.roles).map(([name, entry]) => [name, {
definition: entry.definition,
vars: entry.vars ?? {},
launched: launch ? launch.instances.includes(name) : false,
launcher: launch ? launch.by === name : false,
protected: END_PROTECTED.includes(entry.definition),
}]));
return { business, revision, launch: launch !== null, instances, definitions: definitions() };
}
// args: { revision, instance, op: "add" | "change", definition?, vars?, launch?: boolean }.
// add needs definition; change needs at least one of definition, vars and launch. vars replaces
// the instance's vars whole. The answer's restart is true when the running bus must restart
// before the change counts: the broker holds the roles it loaded at start (broker.mjs bindLaunch).
function set(business, args, actor) {
if (!isPlainObject(args) || Object.keys(args).some(key => !SET_KEYS.includes(key))) {
throw new OrganizationError("invalid-request");
}
if (typeof args.revision !== "string" || !/^[a-f0-9]{64}$/.test(args.revision)) {
throw new OrganizationError("invalid-request");
}
const { instance, op } = args;
if (!id(instance) || (op !== "add" && op !== "change")) throw new OrganizationError("invalid-request");
// The broker refuses a business whose roles name human or tester (broker.mjs, the load check),
// so an instance under either name would stop the bus at its next start (row 165 r2, Dewey F1).
if (instance === "human" || instance === "tester") {
throw new OrganizationError("invalid-request", `${instance} names the bus's own sessions, never a role instance`);
}
if (Object.hasOwn(args, "definition") && !id(args.definition)) throw new OrganizationError("invalid-request");
if (Object.hasOwn(args, "vars") && !isPlainObject(args.vars)) throw new OrganizationError("invalid-request");
if (Object.hasOwn(args, "launch") && typeof args.launch !== "boolean") throw new OrganizationError("invalid-request");
const old = writer.read(business).document;
const next = structuredClone(old);
const exists = Object.hasOwn(next.roles, instance);
let redefined = false;
if (op === "add") {
if (!Object.hasOwn(args, "definition")) throw new OrganizationError("invalid-request");
if (exists) throw new OrganizationError("organization-instance-exists");
definitionFor(rolesDir, args.definition);
next.roles[instance] = { definition: args.definition, ...(Object.hasOwn(args, "vars") ? { vars: structuredClone(args.vars) } : {}) };
redefined = true;
} else {
if (!["definition", "vars", "launch"].some(key => Object.hasOwn(args, key))) throw new OrganizationError("invalid-request");
if (!exists) throw new OrganizationError("organization-unknown-instance");
const entry = next.roles[instance];
// An assistant's settings change only through limits.set's assistants key (row 155), so
// nothing here touches a protected instance, its vars and launch membership included.
if (END_PROTECTED.includes(entry.definition)) throw new OrganizationError("organization-definition-refused");
if (Object.hasOwn(args, "definition") && args.definition !== entry.definition) {
definitionFor(rolesDir, args.definition);
// The old definition's credentials would bind to the new one's authority.
if (loadRole(rolesDir, entry.definition).credentials.length > 0) {
throw new OrganizationError("organization-credentials-out-of-scope",
`${instance} holds ${entry.definition} credentials; moving them to another definition is a hand edit`);
}
entry.definition = args.definition;
redefined = true;
}
if (Object.hasOwn(args, "vars")) entry.vars = structuredClone(args.vars);
}
if (Object.hasOwn(args, "launch")) {
if (!next.launch) throw new OrganizationError("organization-launch-not-configured");
const listed = next.launch.instances;
if (!args.launch) next.launch.instances = listed.filter(name => name !== instance);
else if (!listed.includes(instance)) listed.push(instance);
}
if (canonicalJson(next) === canonicalJson(old)) throw new OrganizationError("organization-no-change");
// The checks mosaic business validate runs, before the writer publishes anything, then the
// route checks every write of the route vars runs (row 65). A file that no longer validates
// has every route checked.
const proposed = validateBusinessDocument(next, businessFilePath(business, dir), { rolesDir });
let before = null;
try {
before = validateBusinessDocument(old, businessFilePath(business, dir), { rolesDir });
} catch (e) {
if (e.name !== "BusinessError") throw e;
}
checkRoutes({ proposed, old: before, levels });
for (const [project, entry] of Object.entries(proposed.projects)) {
if (!existsSync(projectFilePath(entry.root))) continue;
const loaded = loadProject(entry.root);
if (loaded.id !== project) throw new OrganizationError("organization-project-mismatch");
for (const name of Object.keys(proposed.roles)) {
try {
resolveInstance({ system, business: proposed, project: loaded, instance: name });
} catch (e) {
if (e.name === "BusinessError") throw new OrganizationError("organization-unresolvable-instance", e.message);
throw e;
}
}
}
const receipt = writer.write(business, next, { revision: args.revision, actor });
return { ...read(business), transaction: receipt.transaction, restart: redefined };
}
return { writer, read, set };
}