Multiplayer agent harness for work.
Let admins enforce decision rules from chat (#2336)
Joshua France8d3f330864f6
diff --git a/src/api/routes/decisions-resource.ts b/src/api/routes/decisions-resource.tsindex c7afab718..fb82a3d0a 100644--- a/src/api/routes/decisions-resource.ts+++ b/src/api/routes/decisions-resource.ts@@ -10,7 +10,7 @@ export const decisionsResource: AdminResource = {kind: "custom",target: "org",label:- "Decision providers and rules. Send { provider }, { removeProvider: id }, { rule } or { removeRule: id }. A provider names a wire protocol (chat-completions, decisions or systemone); leave baseUrl unset to use the model gateway, or set baseUrl plus an org service credential. A rule asks a classifier a question at a hook and applies the chosen option's action. Rule mode is off, observe or enforce. Agents can save off or observe rules; only an admin enforces a rule or changes an enforced rule or its provider.",+ "Decision providers and rules. Send { provider }, { removeProvider: id }, { rule } or { removeRule: id }. A provider names a wire protocol (chat-completions, decisions or systemone); leave baseUrl unset to use the model gateway, or set baseUrl plus an org service credential. A rule asks a classifier a question at a hook and applies the chosen option's action. Rule mode is off, observe or enforce.",readKey: "decisions",get: async (deps, scope) =>deps.decisions && {@@ -25,14 +25,14 @@ export const decisionsResource: AdminResource = {const store = ctx.deps.decisions;if (!store) return { error: "not available on this deployment", status: 404 };const body = (ctx.body ?? {}) as Record<string, unknown>;- const by = { actorId: actor.id, agent: !!ctx.capability };+ const by = { actorId: actor.id };let change: [string, string];try {if (typeof body.removeProvider === "string") {- await store.removeProvider(body.removeProvider, by);+ await store.removeProvider(body.removeProvider);change = ["decision.provider.remove", body.removeProvider];} else if (typeof body.removeRule === "string") {- await store.removeRule(body.removeRule, by);+ await store.removeRule(body.removeRule);change = ["decision.rule.remove", body.removeRule];} else if (body.provider !== undefined) {const parsed = parseDecisionProvider(body.provider);diff --git a/src/decisions/store.ts b/src/decisions/store.tsindex 499e0ce7f..989f4db24 100644--- a/src/decisions/store.ts+++ b/src/decisions/store.ts@@ -4,16 +4,15 @@ import { checkRuleSet, type DecisionHook, type DecisionProvider, type DecisionRuinterface DecisionWriter {actorId: string;- agent: boolean;}export interface DecisionStore {providers(ids?: readonly string[]): Promise<DecisionProvider[]>;rules(hook?: DecisionHook): Promise<DecisionRule[]>;saveProvider(provider: DecisionProvider, by: DecisionWriter): Promise<void>;- removeProvider(id: string, by: DecisionWriter): Promise<void>;+ removeProvider(id: string): Promise<void>;saveRule(rule: DecisionRule, by: DecisionWriter): Promise<void>;- removeRule(id: string, by: DecisionWriter): Promise<void>;+ removeRule(id: string): Promise<void>;}const SCHEMA = [@@ -54,19 +53,14 @@ const RULES = "SELECT * FROM decision_rules";const CACHE_MS = 10_000;const MAX_STORED_RULES = 100;const MAX_PROVIDERS = 20;-const ENFORCED_RULE = "SELECT 1 FROM decision_rules WHERE rule_id = $1 AND mode = 'enforce'";-const ENFORCED_PROVIDER = "SELECT 1 FROM decision_rules WHERE provider_id = $1 AND mode = 'enforce'";-const AGENT_LIMIT =- "agents can't enforce decision rules or change enforced rules and their providers; an admin does that from the dashboard";export function createPostgresDecisionStore(connectionString: string): DecisionStore {const { q, pool } = createPgPool(connectionString, "decisions/0001", SCHEMA);const active = new Map<DecisionHook, { at: number; rules: Promise<DecisionRule[]> }>();let known: { at: number; providers: Promise<DecisionProvider[]> } | undefined;- const write = async (by: DecisionWriter, guard: string, id: string, fn: (db: PoolClient) => Promise<unknown>) => {+ const write = async (fn: (db: PoolClient) => Promise<unknown>) => {await withPgTransaction(await pool(), async (db) => {await db.query("LOCK TABLE decision_rules IN SHARE ROW EXCLUSIVE MODE");- if (by.agent && (await db.query(guard, [id])).rows.length) throw new Error(AGENT_LIMIT);await fn(db);});active.clear();@@ -98,7 +92,7 @@ export function createPostgresDecisionStore(connectionString: string): DecisionSreturn rules;},saveProvider: (p, by) =>- write(by, ENFORCED_PROVIDER, p.id, async (db) => {+ write(async (db) => {const { rows } = await db.query("SELECT count(*)::int AS n FROM decision_providers WHERE provider_id <> $1", [p.id,]);@@ -111,11 +105,9 @@ export function createPostgresDecisionStore(connectionString: string): DecisionS[p.id, p.protocol, p.baseUrl ?? null, p.credential ?? null, by.actorId, Date.now()],);}),- async removeProvider(id, by) {+ async removeProvider(id) {try {- await write(by, ENFORCED_PROVIDER, id, (db) =>- db.query("DELETE FROM decision_providers WHERE provider_id = $1", [id]),- );+ await write((db) => db.query("DELETE FROM decision_providers WHERE provider_id = $1", [id]));} catch (error) {if ((error as { code?: string }).code === "23503")throw new Error(`decision provider ${id} is still used by a rule`, { cause: error });@@ -123,8 +115,7 @@ export function createPostgresDecisionStore(connectionString: string): DecisionS}},saveRule: (rule, by) =>- write(by, ENFORCED_RULE, rule.id, async (db) => {- if (by.agent && rule.mode === "enforce") throw new Error(AGENT_LIMIT);+ write(async (db) => {const { rows } = await db.query("SELECT count(*)::int AS n FROM decision_rules WHERE rule_id <> $1", [rule.id]);if (rows[0].n >= MAX_STORED_RULES)throw new Error(`at most ${MAX_STORED_RULES} decision rules; remove one first`);@@ -151,7 +142,6 @@ export function createPostgresDecisionStore(connectionString: string): DecisionS],);}),- removeRule: (id, by) =>- write(by, ENFORCED_RULE, id, (db) => db.query("DELETE FROM decision_rules WHERE rule_id = $1", [id])),+ removeRule: (id) => write((db) => db.query("DELETE FROM decision_rules WHERE rule_id = $1", [id])),};}diff --git a/test/decision-rules.test.ts b/test/decision-rules.test.tsindex e55395124..0314db85c 100644--- a/test/decision-rules.test.ts+++ b/test/decision-rules.test.ts@@ -335,7 +335,7 @@ test("most_confident hook points follow the likeliest enforced verdict and errorassert.equal(failing.decisive?.action, "continue", "a failed classifier falls back to its onError option");});-test("the decisions resource checks the model catalog and marks agent writes", async () => {+test("the decisions resource checks the model catalog and lets an admin's agent enforce", async () => {const { ADMIN_RESOURCE_BY_ID } = await import("../src/api/routes/admin-resources.ts");const { selectableBaseModels } = await import("../src/model/pi-models.ts");const saved: DecisionRule[] = [];@@ -344,7 +344,8 @@ test("the decisions resource checks the model catalog and marks agent writes", arules: async () => saved,saveProvider: async () => {},removeProvider: async () => {},- saveRule: async (r: DecisionRule, by: { agent: boolean }) => void saved.push({ ...r, id: `${r.id}:${by.agent}` }),+ saveRule: async (r: DecisionRule, by: { actorId: string }) =>+ void saved.push({ ...r, id: `${r.id}:${by.actorId}` }),removeRule: async () => {},};const modelId = selectableBaseModels()[0]!.id;@@ -362,13 +363,13 @@ test("the decisions resource checks the model catalog and marks agent writes", a"org:default-org",);assert.match(err(await apply({ rule: route() })), /m-deep is not in this deployment's model catalog/);- assert.deepEqual(await apply({ rule: { ...rule, mode: "observe" } }, { actorId: "[email protected]" }), { ok: true });- assert.deepEqual(await apply({ rule }), { ok: true });+ assert.deepEqual(await apply({ rule }, { actorId: "[email protected]" }), { ok: true });+ assert.deepEqual(await apply({ rule: { ...rule, mode: "observe" } }), { ok: true });assert.deepEqual(saved.map((r) => [r.id, r.mode]),[- ["router:true", "observe"],- ["router:false", "enforce"],+ ["router:[email protected]", "enforce"],+ ["router:[email protected]", "observe"],],);});diff --git a/test/postgres-decisions.test.ts b/test/postgres-decisions.test.tsindex 7274287ea..c211d1753 100644--- a/test/postgres-decisions.test.ts+++ b/test/postgres-decisions.test.ts@@ -30,8 +30,7 @@ const rule = (id: string, over: Partial<DecisionRule> = {}): DecisionRule => ({test("pg decisions: providers and rules are rows; hooks load active rules only", { skip }, async () => {const store = createPostgresDecisionStore(URL!);- const a = { actorId: "[email protected]", agent: false };- const agent = { actorId: "[email protected]", agent: true };+ const a = { actorId: "[email protected]" };await store.saveProvider({ id: "gw", protocol: "chat-completions" }, a);await store.saveProvider({ id: "oa", protocol: "decisions", baseUrl: "https://dec.example", credential: "dec" }, a);assert.deepEqual(await store.providers(), [@@ -49,23 +48,17 @@ test("pg decisions: providers and rules are rows; hooks load active rules only",assert.deepEqual(await store.rules("turn_start"), [rule("router"), rule("shadow", { mode: "observe" })]);await assert.rejects(store.saveRule(rule("second"), a), /allows one enforcing rule/);- await assert.rejects(store.removeProvider("gw", a), /still used by a rule/);+ await assert.rejects(store.removeProvider("gw"), /still used by a rule/);await store.saveRule(rule("router", { question: "Changed?" }), a);assert.equal((await store.rules("turn_start")).find((r) => r.id === "router")?.question, "Changed?");- await assert.rejects(store.saveRule(rule("router", { mode: "observe" }), agent), /admin does that/);- await assert.rejects(store.removeRule("router", agent), /admin does that/);- await assert.rejects(store.saveProvider({ id: "gw", protocol: "systemone" }, agent), /admin does that/);- await assert.rejects(store.saveRule(rule("mine"), agent), /admin does that/);- await store.saveRule(rule("mine", { mode: "observe" }), agent);- await store.removeRule("mine", agent);assert.deepEqual(await store.providers(["oa"]), [{ id: "oa", protocol: "decisions", baseUrl: "https://dec.example", credential: "dec" },]);- for (const r of await store.rules()) await store.removeRule(r.id, a);- await store.removeProvider("gw", a);+ for (const r of await store.rules()) await store.removeRule(r.id);+ await store.removeProvider("gw");assert.deepEqual((await store.providers()).map((p) => p.id),["oa"],