feat: run each loop phase on its own strength (Thrifty, Balanced, Best)

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-04 19:23:52 -08:00
1 parent e963513a8a
commit 81d14c8e78
41 files changed
+3290 -81

No files matched your search

+7 -4
View File
@@ -104,8 +104,9 @@
"kind": "template",
"command": "opencode",
"prompt": "Use the plan2code skill",
"args": ["--prompt", "{prompt}"],
"bypassArgs": ["--auto"]
"args": ["{model}", "--prompt", "{prompt}"],
"bypassArgs": ["--auto"],
"modelArgs": ["--model", "{model}"]
},
{
"id": "gemini",
@@ -113,8 +114,9 @@
"kind": "template",
"command": "gemini",
"prompt": "Use the plan2code skill",
"args": ["{prompt}"],
"args": ["{model}", "{prompt}"],
"bypassArgs": ["--approval-mode=yolo"],
"modelArgs": ["--model", "{model}"],
"note": "For unpaid tier and Google One accounts Gemini CLI was replaced by Antigravity CLI on June 18, 2026; whether gemini still runs depends on the account."
},
{
@@ -123,7 +125,8 @@
"kind": "template",
"command": "pi",
"prompt": "/skill:plan2code",
"args": ["{prompt}"]
"args": ["{model}", "{prompt}"],
"modelArgs": ["--model", "{model}"]
}
]
}
+58 -2
View File
@@ -1,5 +1,5 @@
{
"_note": "Curated model menu for the plan2code launcher. Maintained by the Plan2Code authors; every install overwrites this file. Users add models in User Preferences (kept in ~/.plan2code/models.json). Devin entries are explicit ids at Low, Medium and High effort only, verified against `devin models list`. Codex has no curated entries yet (its docs name none to verify): the launcher skips the model question for it. Pass --model <name> to choose one.",
"_note": "Curated model menu for the plan2code launcher. Maintained by the Plan2Code authors; every install overwrites this file. Users add models in User Preferences (kept in ~/.plan2code/models.json). Devin entries are explicit ids at Low, Medium and High effort only, verified against `devin models list`. Codex entries are the models its docs name as current. The strengths key maps the loop's Thrifty, Balanced and Best to a model (and effort) per agent; users override it in User Preferences. Pass --model <name> to choose any other.",
"claude": [
{
"id": "default",
@@ -138,7 +138,63 @@
{
"id": "gpt-6-astra-high",
"label": "GPT-6 Astra High Thinking"
},
{
"id": "gpt-5-6-sol-low",
"label": "GPT-5.6 Sol Low Thinking"
},
{
"id": "gpt-5-6-sol-medium",
"label": "GPT-5.6 Sol Medium Thinking"
},
{
"id": "gpt-5-6-sol-high",
"label": "GPT-5.6 Sol High Thinking"
}
],
"codex": []
"codex": [
{
"id": "gpt-6-astra",
"label": "GPT-6 Astra"
},
{
"id": "gpt-6.1-sol",
"label": "GPT-6.1 Sol"
},
{
"id": "gpt-6.1-terra",
"label": "GPT-6.1 Terra"
},
{
"id": "gpt-6-luna",
"label": "GPT-6 Luna"
}
],
"strengths": {
"claude": {
"thrifty": {
"model": "sonnet",
"effort": "low"
},
"balanced": {
"model": "sonnet",
"effort": "medium"
},
"best": {
"model": "opus",
"effort": "medium"
}
},
"devin": {
"thrifty": {
"model": "swe-2-medium"
},
"balanced": {
"model": "swe-2-high"
},
"best": {
"model": "claude-opus-5-5-medium"
}
}
}
}
+17 -4
View File
@@ -48,10 +48,11 @@ import {
workspaceForAgent,
writeWorkspaceCursor,
} from "./workspace.mjs";
import { readPrHosts, resetSubagentCursor } from "./settings.mjs";
import { readPrHosts, resetSubagentCursor, subagentStoreEntry } from "./settings.mjs";
import { resetPointers } from "./pointers.mjs";
import { WORKFLOWS, isWorkflow } from "./public/skills.js";
import { startsClean } from "./public/hops.js";
import { STRENGTH_ORDER } from "./strengths.mjs";
import { snapshot } from "./git-repo.mjs";
import { announcePage, currentSession, inAppSignal } from "./in-app.mjs";
import { findAgent } from "./agent-lookup.mjs";
@@ -107,6 +108,14 @@ const EMBED_API = 1;
// The only workflows a loop drives (open --loop).
const LOOP_WORKFLOWS = ["implement", "implement-review"];
// What the loop locks a session with: `driving`, and, when the app started this
// phase on a strength, its word (PLAN2CODE_LOOP_STRENGTH), which the server's
// Subagents sync reads so the phase's helpers follow it.
function loopLock() {
const strength = process.env.PLAN2CODE_LOOP_STRENGTH;
return STRENGTH_ORDER.includes(strength) ? { driving: true, strength } : { driving: true };
}
export async function cmdOpen() {
trace("open: start");
// A workflow the console does not know is refused first, before the pointer,
@@ -256,7 +265,7 @@ export async function cmdOpen() {
// without it (Fix it by hand, from a stop screen) is an ordinary,
// unlocked session. `loopExpect` goes with the lock: the app restamps it
// on its next look, so a stale setup never judges a new run.
if (loopMode) s.loop = { driving: true };
if (loopMode) s.loop = loopLock();
else {
delete s.loop;
delete s.loopExpect;
@@ -288,7 +297,7 @@ export async function cmdOpen() {
// Only a freshly opened dashboard plays Planny's wake-up.
if (args.workflow === "dashboard") state.wake = true;
// Locked from the first frame, before the state is first written.
if (loopMode) state.loop = { driving: true };
if (loopMode) state.loop = loopLock();
// The setup session's hand-over data (forCli + the token /handover
// checks), created with the state so the first write already has it.
if (args.workflow === "setup") {
@@ -450,7 +459,11 @@ export async function cmdOpen() {
// A standing instruction the new agent is owed, as a `reply` holding only
// its lines; no key when nothing is owed.
const subagentsOwed = () => {
awaitSubagentSync(dir, state.workflow);
// In a loop the setting must carry this phase's strength, or the stored one
// when the phase has none, before the first block is built: a resume leaves
// the earlier phase's strength in the setting until the server syncs.
const expected = loopMode ? (state.loop && state.loop.strength) || subagentStoreEntry(worktree, state.workflow).strength : undefined;
awaitSubagentSync(dir, state.workflow, expected);
const [out, cursor] = withSubagents(dir, { reply: "" });
return [cursor ? out : {}, cursor];
};
+4 -2
View File
@@ -553,12 +553,14 @@ export function advanceWorkspace(dir, changes) {
// an older server, which never writes one: a short look, not the full wait.
const SUBAGENT_SYNC_WAIT_MS = 1500;
const SUBAGENT_SYNC_MISSING_MS = 250;
export function awaitSubagentSync(dir, workflow) {
export function awaitSubagentSync(dir, workflow, strength) {
if (!offered(workflow)) return;
const start = Date.now();
for (;;) {
const setting = readSubagentSetting(dir);
if (setting && setting.workflow === workflow) return;
// A loop phase's strength rides on the session's state: the setting must
// carry it before the first block is built, or the agent hears the stored one.
if (setting && setting.workflow === workflow && (!strength || setting.strength === strength)) return;
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
if (Date.now() - start >= budget) return;
sleepSync(25);
+83 -5
View File
@@ -1,5 +1,6 @@
// Plan2Code Web Console - the Implementation Loop's setup, remembered per project.
import fs from "node:fs";
import path from "node:path";
import { ensureDir, HOME_DIR, readJson, withStateLock, writeJsonAtomic } from "./files.mjs";
@@ -22,6 +23,9 @@ const AFTER_LAST = ["offer-finalize", "run-finalize"];
const NOTIFY_KINDS = ["query", "discord", "slack", "teams", "google-chat", "json"];
// The kinds where the person names the parameter or field that holds the message.
const NAMED_KINDS = ["query", "json"];
const STRENGTH_WORDS = ["thrifty", "balanced", "best"];
// A spec folder directly under specs/, no leading dot (the route's own rule).
const SPEC_KEY = /^specs\/[^/\\.][^/\\]*$/;
export const LOOP_DEFAULTS = Object.freeze({
review: true,
@@ -36,6 +40,8 @@ export const LOOP_DEFAULTS = Object.freeze({
notifyKind: "query",
notifyUrl: "",
notifyParam: "message",
phaseStrength: false,
strengths: Object.freeze({}),
});
/** An http or https address in printable ASCII, with a host and no user name or password (the app's `valid_url`). */
@@ -78,9 +84,72 @@ export function loopSetupProblems(entry) {
if (typeof entry.notifyParam !== "string" || (entry.notifyUrl && NAMED_KINDS.includes(entry.notifyKind) && !/^[A-Za-z0-9._~-]{1,64}$/.test(entry.notifyParam))) {
problems.push('"notifyParam" must be 1 to 64 letters, digits, or - _ . ~');
}
if (typeof entry.phaseStrength !== "boolean") problems.push('"phaseStrength" must be true or false');
problems.push(...strengthsProblems(entry.strengths));
return problems;
}
/** Problems with the per-spec phase picks; empty when they are good. */
function strengthsProblems(strengths) {
if (strengths === null || typeof strengths !== "object" || Array.isArray(strengths)) return ['"strengths" must be an object'];
const problems = [];
for (const [key, picks] of Object.entries(strengths)) {
if (!SPEC_KEY.test(key)) {
problems.push(`"strengths" key "${key}" must be a folder directly under specs/`);
continue;
}
if (!Array.isArray(picks) || picks.length > 100) {
problems.push(`"strengths.${key}" must list at most 100 phase picks`);
continue;
}
const seen = new Set();
for (const pick of picks) {
const ok = pick && typeof pick === "object" && !Array.isArray(pick);
if (!ok || !Number.isInteger(pick.n) || pick.n < 1) {
problems.push(`"strengths.${key}" picks need a phase number "n" (a positive whole number)`);
} else if (seen.has(pick.n)) {
problems.push(`"strengths.${key}" has Phase ${pick.n} twice`);
} else {
seen.add(pick.n);
}
if (!ok) continue;
if (typeof pick.name !== "string" || pick.name.length > 200) problems.push(`"strengths.${key}" pick names must be text of at most 200 characters`);
if (!STRENGTH_WORDS.includes(pick.strength)) problems.push(`"strengths.${key}" picks need a strength of ${STRENGTH_WORDS.join(", ")}`);
}
}
return problems;
}
/**
* Drop picks that no longer mean anything (FR-12, FR-13): a spec key whose folder
* is gone from the project, and, for a spec whose phases can be read, picks whose
* number and name match no phase left. `phasesFor(spec)` returns the phases left
* as [{ n, name }], or null when the overview cannot be read (its picks stay).
* Returns a fresh object; the input is never changed.
*/
export function pruneStrengths(project, strengths, phasesFor) {
const out = {};
for (const [spec, picks] of Object.entries(strengths && typeof strengths === "object" ? strengths : {})) {
if (!SPEC_KEY.test(spec) || !Array.isArray(picks)) continue;
let isDir = false;
try {
isDir = fs.statSync(path.join(project, spec)).isDirectory();
} catch {
/* gone */
}
if (!isDir) continue;
let left = null;
try {
left = typeof phasesFor === "function" ? phasesFor(spec) : null;
} catch {
left = null;
}
const kept = Array.isArray(left) ? picks.filter((p) => left.some((l) => l.n === p.n && l.name === p.name)) : picks;
if (kept.length) out[spec] = kept.map((p) => ({ ...p }));
}
return out;
}
function readStore() {
const saved = readJson(LOOP_SETUP_FILE, null);
const ok = saved && saved.schema === 1 && saved.projects && typeof saved.projects === "object" && !Array.isArray(saved.projects);
@@ -94,14 +163,22 @@ function readStore() {
* file reads as empty. An entry saved before `fixMode` existed fixed by level,
* so it keeps doing that rather than taking the newer default.
*/
export function readLoopSetup(project) {
export function readLoopSetup(project, phasesFor) {
const saved = readStore().projects[foldKey(project)];
if (saved && typeof saved === "object") return { ...LOOP_DEFAULTS, fix: [...LOOP_DEFAULTS.fix], fixMode: "levels", ...saved, remembered: true };
return { ...LOOP_DEFAULTS, fix: [...LOOP_DEFAULTS.fix], remembered: false };
const base = { ...LOOP_DEFAULTS, fix: [...LOOP_DEFAULTS.fix], strengths: {} };
if (saved && typeof saved === "object") {
const setup = { ...base, fixMode: "levels", ...saved, remembered: true };
// Deep-copied and pruned like `fix`: the caller may change it freely.
const strengths = saved.strengths && typeof saved.strengths === "object" && !Array.isArray(saved.strengths) ? saved.strengths : {};
setup.strengths = pruneStrengths(project, strengths, phasesFor);
if (typeof setup.phaseStrength !== "boolean") setup.phaseStrength = false;
return setup;
}
return { ...base, remembered: false };
}
/** Validate and save this project's setup; throws an Error listing the problems. */
export function saveLoopSetup(project, entry) {
export function saveLoopSetup(project, entry, phasesFor) {
const problems = loopSetupProblems(entry);
if (problems.length) {
const err = new Error(`the loop setup is not valid: ${problems.join("; ")}`);
@@ -115,9 +192,10 @@ export function saveLoopSetup(project, entry) {
const store = readStore();
// Only the known fields are kept, in the defaults' order.
const known = Object.fromEntries(Object.keys(LOOP_DEFAULTS).map((key) => [key, entry[key]]));
known.strengths = pruneStrengths(project, known.strengths, phasesFor);
store.projects[foldKey(project)] = { ...known, saved: new Date().toISOString() };
writeJsonAtomic(LOOP_SETUP_FILE, { schema: 1, projects: store.projects });
return readLoopSetup(project);
return readLoopSetup(project, phasesFor);
},
LOOP_SETUP_LOCK,
);
+2 -2
View File
@@ -1075,7 +1075,7 @@ export function isOpen(item) {
const LOOP_LEVELS = ["critical", "warning", "suggestion"];
const LOOP_REASONS = ["tests", "findings", "blocked", "conflict", "other"];
const LOOP_CAN = ["resume", "fix", "finalize", "dashboard"];
const LOOP_CAN = ["resume", "ask", "fix", "finalize", "dashboard"];
const TASK_ID = /^\d+\.\d+$/;
// A one-line path that stays inside the project: not absolute, no `..` step.
@@ -1298,7 +1298,7 @@ export function loopEndProblems(e, state) {
}
// Loop mode adds four optional keys that a blank state does not hold (absent,
// not null): `loop: { driving: true }` (set by `open --loop`), `loopExpect`
// not null): `loop: { driving: true, strength? }` (set by `open --loop`), `loopExpect`
// (the app's judging criteria), `loopOutcome` (the skill's report) and
// `loopEnd` (the app's ending).
export function blankState({ sid, workflow, title, project, specDir }) {
+16
View File
@@ -36,6 +36,8 @@
<link rel="modulepreload" href="/screens/agents/agents-list-editor.js" />
<link rel="modulepreload" href="/screens/agents/agents-summary.js" />
<link rel="modulepreload" href="/screens/agents/agents-form.js" />
<link rel="modulepreload" href="/screens/agents/agents-strengths.js" />
<link rel="modulepreload" href="/strengths.js" />
<link rel="modulepreload" href="/screens/cleanup.js" />
<link rel="modulepreload" href="/screens/help-dialog.js" />
<link rel="modulepreload" href="/screens/workspace.js" />
@@ -2251,6 +2253,15 @@
wait on a prompt nobody sees, so Start stays grayed out.
</li>
</ul>
<h4>Strength per phase</h4>
<p>
Turn on <strong>Set strength per phase</strong> in the setup to run each
phase on <strong>Thrifty</strong>, <strong>Balanced</strong>, <strong>Best</strong>
or <strong>Match my session</strong>. A phase you leave untouched runs on
the launch model. The one retry after a crash or a quiet agent (when retry
is on) goes one step up (Match my session stays on the launch model),
and the phase's helpers follow.
</p>
<h4>What is locked while it runs</h4>
<p>
Answers, sign-offs, launches, Workspace, Helpers and
@@ -3305,6 +3316,11 @@
opens one agent's form, and <strong>Add agent</strong> a blank one.
</p>
<ul>
<li>
<strong>Strengths in the loop</strong>: under Models, map Thrifty,
Balanced and Best to one of the agent's own models. The Implementation
Loop's per-phase strength reads them. Untouched rows stay as shipped.
</li>
<li>
<strong>Models</strong>: each built-in agent (Claude, Devin, Codex)
shows the models that come with Plan2Code, which every update
+82 -7
View File
@@ -15,6 +15,7 @@ import { hooks } from "../state.js";
import {
MODEL_CLIS,
emptyLists,
emptyStrengths,
newAgent,
normalizeAgent,
cliOf,
@@ -91,7 +92,16 @@ export function mountAgentsView(container, opts = {}) {
$,
// The last server reply for each list. Unknown keys on an agent ride along
// untouched; builtins and templates only feed the setup pick list.
saved: { agents: [], user: emptyLists(), shipped: emptyLists(), builtins: [], templates: [] },
saved: { agents: [], user: emptyLists(), shipped: emptyLists(), builtins: [], templates: [], strengths: emptyStrengths() },
// The person's own strength rows per form key, once the fold changed them
// (agents-strengths.js); a form with no entry has not touched its fold.
strengthDrafts: new Map(),
strengthsOpen: false,
// The open fold's redraw, set by the fold itself.
strengthsRefresh: null,
// Whether GET /models answered: without it the page holds none of the
// person's models or strengths, so the fold stays away and no save sends them.
modelsLoaded: false,
// At most one per form being edited: "cli:<cli>" for a built-in's own models,
// "agent:<id>" for an added agent, "agent:new" for one being added.
drafts: new Map(),
@@ -148,15 +158,20 @@ export function mountAgentsView(container, opts = {}) {
}
function edited() {
if (ctx.openKey) renderDirty(ctx, ctx.openKey);
if (ctx.openKey) {
// A model added or removed changes what the strengths fold may pick.
if (ctx.strengthsRefresh) ctx.strengthsRefresh();
renderDirty(ctx, ctx.openKey);
}
}
// Leaving a form for another row drops its draft, as closing it always did:
// a dirty one asks first (the dialog's Save / Discard / Keep editing).
async function leaveForm() {
if (!ctx.openKey) return true;
if (isDirty(ctx.saved, ctx.drafts, ctx.openKey) && !(await confirmUnsaved())) return false;
if (isDirty(ctx.saved, ctx.drafts, ctx.openKey, ctx.strengthDrafts) && !(await confirmUnsaved())) return false;
ctx.drafts.delete(ctx.openKey);
ctx.strengthDrafts.delete(ctx.openKey);
ctx.openKey = null;
return true;
}
@@ -183,6 +198,7 @@ export function mountAgentsView(container, opts = {}) {
ctx.formError = null;
ctx.formReplace = null;
ctx.confirming = false;
ctx.strengthsOpen = false;
ctx.argsOpen = key === "agent:new";
// A built-in's only section is its models: folded it would show nothing.
ctx.modelsOpen = key.startsWith("cli:");
@@ -198,7 +214,10 @@ export function mountAgentsView(container, opts = {}) {
// one just deleted).
function closeForm() {
const left = ctx.openKey;
if (ctx.openKey) ctx.drafts.delete(ctx.openKey);
if (ctx.openKey) {
ctx.drafts.delete(ctx.openKey);
ctx.strengthDrafts.delete(ctx.openKey);
}
ctx.openKey = null;
ctx.formError = null;
ctx.formReplace = null;
@@ -286,6 +305,7 @@ export function mountAgentsView(container, opts = {}) {
// Fresh from what was just saved: the form redraws on a clean draft.
function savedAs(key) {
ctx.drafts.delete(ctx.openKey);
ctx.strengthDrafts.delete(ctx.openKey);
ctx.openKey = key;
ctx.drafts.set(key, structuredClone(savedEntry(ctx.saved, key)));
ctx.formError = null;
@@ -294,15 +314,35 @@ export function mountAgentsView(container, opts = {}) {
drawForm(ctx);
}
// The strengths mapping to send for `owner` (a built-in's cli or an added
// agent's id): every other agent's saved rows that still name a known agent
// (a deleted agent's rows drop out here), plus the owner's own rows. Those are
// the form's draft when its fold changed, else what is saved, keeping only
// rows whose model is still in `modelIds`.
function strengthsToSend(owner, key, modelIds) {
const known = new Set([...MODEL_CLIS, ...ctx.saved.agents.map((a) => a.id)]);
const out = {};
for (const [id, rows] of Object.entries(ctx.saved.strengths.user)) if (id !== owner && known.has(id)) out[id] = rows;
const mine = ctx.strengthDrafts.has(key) ? ctx.strengthDrafts.get(key) : ctx.saved.strengths.user[owner] || {};
const kept = Object.fromEntries(Object.entries(mine).filter(([, row]) => row && modelIds.includes(row.model)));
if (Object.keys(kept).length) out[owner] = kept;
return out;
}
async function saveModelsFor(cli) {
const sent = ctx.drafts.get("cli:" + cli).filter((m) => m.id);
const key = "cli:" + cli;
const sent = ctx.drafts.get(key).filter((m) => m.id);
try {
const { res, body } = await postJson("/models", { models: { ...ctx.saved.user, [cli]: sent } });
const modelIds = [...ctx.saved.shipped[cli], ...sent].map((m) => m.id);
const payload = { models: { ...ctx.saved.user, [cli]: sent } };
if (ctx.modelsLoaded) payload.strengths = strengthsToSend(cli, key, modelIds);
const { res, body } = await postJson("/models", payload);
if (!res.ok) {
formMark({ ok: false, error: body.error || "Could not save." });
return false;
}
ctx.saved.user[cli] = (body.user && body.user[cli]) || sent;
if (ctx.modelsLoaded) ctx.saved.strengths.user = body.strengths || {};
} catch {
formMark({ ok: false, error: "Could not save." });
return false;
@@ -343,6 +383,32 @@ export function mountAgentsView(container, opts = {}) {
return false;
}
const id = ctx.saved.agents[at].id;
// The fold's rows ride a second save into models.json, under the id the
// agent has now (a new agent only gets one from the first).
const modelIds = draft.models.map((m) => m.id).filter(Boolean);
const savedRows = ctx.saved.strengths.user[id] || {};
const stale = Object.values(savedRows).some((row) => row && !modelIds.includes(row.model));
if (ctx.modelsLoaded && (ctx.strengthDrafts.has(key) || stale)) {
// The agent itself is saved by now: on a failure the form moves to its
// saved id, keeps the fold's unsaved rows and says what did not land.
const strengthsFailed = (message) => {
const mine = ctx.strengthDrafts.get(key);
ctx.found.delete(key);
ctx.found.delete("agent:" + id);
savedAs("agent:" + id);
if (mine !== undefined) ctx.strengthDrafts.set("agent:" + id, mine);
drawForm(ctx);
formMark({ ok: false, error: message });
return false;
};
try {
const { res, body } = await postJson("/models", { models: ctx.saved.user, strengths: strengthsToSend(id, key, modelIds) });
if (!res.ok) return strengthsFailed(body.error || "Saved, but the strengths could not be.");
ctx.saved.strengths.user = body.strengths || {};
} catch {
return strengthsFailed("Saved, but the strengths could not be.");
}
}
ctx.found.delete(key);
ctx.found.delete("agent:" + id);
savedAs("agent:" + id);
@@ -379,7 +445,7 @@ export function mountAgentsView(container, opts = {}) {
// An open form whose draft differs from what is saved.
function hasUnsaved() {
return ctx.openKey !== null && isDirty(ctx.saved, ctx.drafts, ctx.openKey);
return ctx.openKey !== null && isDirty(ctx.saved, ctx.drafts, ctx.openKey, ctx.strengthDrafts);
}
// What the unsaved prompt calls the open form.
@@ -395,6 +461,7 @@ export function mountAgentsView(container, opts = {}) {
if (!ctx.openKey) return;
if (ctx.openKey === "agent:new") return closeForm();
ctx.drafts.set(ctx.openKey, structuredClone(savedEntry(ctx.saved, ctx.openKey)));
ctx.strengthDrafts.delete(ctx.openKey);
ctx.formError = null;
ctx.formReplace = null;
ctx.confirming = false;
@@ -414,6 +481,7 @@ export function mountAgentsView(container, opts = {}) {
const seq = ++loadSeq;
ctx.openKey = null;
ctx.drafts.clear();
ctx.strengthDrafts.clear();
ctx.found.clear();
ctx.formError = null;
ctx.formReplace = null;
@@ -437,7 +505,14 @@ export function mountAgentsView(container, opts = {}) {
}
ctx.saved.user = emptyLists();
ctx.saved.shipped = emptyLists();
ctx.saved.strengths = emptyStrengths();
ctx.modelsLoaded = Boolean(models);
if (models) {
// A failed or missing strengths answer reads as nothing mapped.
for (const part of ["shipped", "user"]) {
const rows = models.strengths && models.strengths[part];
if (rows && typeof rows === "object" && !Array.isArray(rows)) ctx.saved.strengths[part] = rows;
}
for (const cli of MODEL_CLIS) {
if (Array.isArray(models.user?.[cli])) ctx.saved.user[cli] = models.user[cli];
if (Array.isArray(models.shipped?.[cli])) ctx.saved.shipped[cli] = models.shipped[cli];
@@ -11,6 +11,22 @@ export const MODEL_CLIS = ["claude", "devin", "codex"];
// What the table calls each built-in, and the command it runs (the launcher's CLIS ids).
export const BUILT_IN = { claude: "Claude", devin: "Devin", codex: "Codex" };
// The built-ins that take an effort beside the model (agents.rs has_effort).
export const HAS_EFFORT = ["claude", "codex"];
// The loop's strength mapping as the page keeps it: the shipped rows and the
// person's own, each { <agent id>: { thrifty?, balanced?, best? } }.
export function emptyStrengths() {
return { shipped: {}, user: {} };
}
// The agent a form's strengths belong to: a built-in's cli, an added agent's id.
// An agent not yet saved has no id, so nothing of anyone else's can be its rows.
export function strengthOwner(key) {
if (key === "agent:new") return null;
return key.startsWith("cli:") ? cliOf(key) : agentId(key);
}
export function emptyLists() {
return Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
}
@@ -44,8 +60,15 @@ export function canonical(value) {
);
}
export function isDirty(saved, drafts, key) {
return drafts.has(key) && canonical(drafts.get(key)) !== canonical(savedEntry(saved, key));
// `strengthDrafts` holds, per form key, the person's own strength rows once the
// fold changed them; absent means the fold was left alone.
export function isDirty(saved, drafts, key, strengthDrafts) {
if (!drafts.has(key)) return false;
if (canonical(drafts.get(key)) !== canonical(savedEntry(saved, key))) return true;
const rows = strengthDrafts && strengthDrafts.get(key);
if (rows === undefined) return false;
const was = (saved.strengths && saved.strengths.user[strengthOwner(key)]) || {};
return canonical(rows) !== canonical(was);
}
export function nameOf(saved, drafts, key) {
@@ -10,7 +10,8 @@
import { el } from "../../render.js";
import { listEditor } from "./agents-list-editor.js";
import { BUILT_IN, cliOf, savedEntry, isDirty } from "./agents-data.js";
import { BUILT_IN, HAS_EFFORT, cliOf, savedEntry, isDirty } from "./agents-data.js";
import { strengthsFold } from "./agents-strengths.js";
function agentField(label, field, child) {
const wrap = el("div", "agent-field");
@@ -89,7 +90,11 @@ function builtInFields(ctx, cli, draft) {
"models",
listEditor({ list: draft, kind: "models", field: "models", optionalName: false, addLabel: "Add a model", onChange: ctx.edited })
);
return [fold(ctx, "modelsOpen", "Models", "agent-fold", [note, comes, yours])];
const models = () => [...ctx.saved.shipped[cli], ...draft];
return [
fold(ctx, "modelsOpen", "Models", "agent-fold", [note, comes, yours]),
...(ctx.modelsLoaded ? [strengthsFold(ctx, cli, draft, { models, hasEffort: HAS_EFFORT.includes(cli) })] : []),
];
}
function addedFields(ctx, draft) {
@@ -112,6 +117,9 @@ function addedFields(ctx, draft) {
command,
agentField("Start prompt", "prompt", agentInput(ctx, draft, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
models,
...(ctx.modelsLoaded
? [strengthsFold(ctx, ctx.openKey === "agent:new" ? "" : savedEntry(ctx.saved, ctx.openKey).id, draft, { models: () => draft.models, hasEffort: false })]
: []),
args,
];
}
@@ -165,7 +173,7 @@ function formFoot(ctx, key) {
export function renderDirty(ctx, key) {
const foot = ctx.$("form").querySelector(".prefs-agents-foot");
if (!foot || key !== ctx.openKey) return;
const dirty = isDirty(ctx.saved, ctx.drafts, key);
const dirty = isDirty(ctx.saved, ctx.drafts, key, ctx.strengthDrafts);
for (const sel of [".prefs-agents-save", ".prefs-agents-discard", ".prefs-unsaved-badge"]) foot.querySelector(sel).hidden = !dirty;
}
@@ -0,0 +1,140 @@
// Plan2Code Web Console - the "Strengths in the loop" fold of an agent's form.
//
// Maps the loop's three words (Thrifty, Balanced, Best) to one of the agent's
// own models, and to an effort where the agent takes one. Choices are
// select-only from the agent's Models list. An untouched row follows what
// ships; only a row the person changed is kept in the form's strength draft
// (ctx.strengthDrafts, by form key), which the form's Save sends. The rule that
// reads a row is resolveStrengths, the same module the server uses.
import { el } from "../../render.js";
import { STRENGTH_ORDER, resolveStrengths } from "../../strengths.js";
import { canonical, strengthOwner } from "./agents-data.js";
const WORDS = { thrifty: "Thrifty", balanced: "Balanced", best: "Best" };
const EFFORTS = ["low", "medium", "high"];
function option(value, text) {
const o = el("option", null, text);
o.value = value;
return o;
}
/**
* The fold for the open form. `models` is the agent's Models list ({ id, label }
* rows) or a function returning it, read at every redraw so a model added in the
* same form shows up. `hasEffort` adds the effort select.
*/
export function strengthsFold(ctx, agentId, draft, { models, hasEffort }) {
const key = ctx.openKey;
const owner = agentId || strengthOwner(key);
const shipped = (ctx.saved.strengths.shipped && ctx.saved.strengths.shipped[owner]) || {};
const modelList = () => {
const rows = typeof models === "function" ? models() : models;
const seen = new Set();
return (rows || []).filter((m) => m && m.id && !seen.has(m.id) && seen.add(m.id));
};
// The person's own rows: the draft once changed, else what is saved.
const userRows = () => {
const rows = ctx.strengthDrafts.has(key) ? ctx.strengthDrafts.get(key) : ctx.saved.strengths.user && ctx.saved.strengths.user[owner];
return rows && typeof rows === "object" ? rows : {};
};
const details = el("details", "agent-fold prefs-agents-strengths");
details.open = ctx.strengthsOpen;
details.addEventListener("toggle", () => (ctx.strengthsOpen = details.open));
details.appendChild(el("summary", null, "Strengths in the loop"));
const body = el("div", "strength-body");
details.appendChild(body);
function setRow(word, row) {
const next = { ...userRows() };
if (row) next[word] = row;
else delete next[word];
ctx.strengthDrafts.set(key, next);
ctx.edited();
}
function draw() {
const active = document.activeElement;
const back = active && body.contains(active) ? { word: active.closest("[data-word]")?.dataset.word, field: active.dataset.field } : null;
body.replaceChildren();
const list = modelList();
if (!list.length) {
body.appendChild(el("p", "help strength-empty", "Add a model under Models first"));
return;
}
const base = { shipped, models: list.map((m) => m.id), hasEffort };
const user = userRows();
const resolved = resolveStrengths({ ...base, user });
const dflt = resolveStrengths({ ...base, user: {} });
for (const word of STRENGTH_ORDER) {
const row = el("div", "strength-row");
row.dataset.word = word;
row.appendChild(el("span", "strength-word", WORDS[word]));
const model = el("select");
model.dataset.field = "model";
model.setAttribute("aria-label", `${WORDS[word]} model`);
// Nothing ships for this word: "not mapped" is a real choice. With a default,
// clearing a row is Reset's job.
if (!dflt[word]) model.appendChild(option("", "not mapped"));
for (const m of list) model.appendChild(option(m.id, m.label && m.label !== m.id ? `${m.label} (${m.id})` : m.id));
model.value = resolved[word] ? resolved[word].model : "";
model.addEventListener("change", () => {
if (!model.value) return setRow(word, null);
const next = { model: model.value };
if (hasEffort && resolved[word] && resolved[word].effort) next.effort = resolved[word].effort;
setRow(word, canonical(next) === canonical(dflt[word]) ? null : next);
});
row.appendChild(model);
if (hasEffort) {
const effort = el("select");
effort.dataset.field = "effort";
effort.setAttribute("aria-label", `${WORDS[word]} effort`);
effort.disabled = !resolved[word];
effort.appendChild(option("", "no effort"));
for (const e of EFFORTS) effort.appendChild(option(e, e));
effort.value = (resolved[word] && resolved[word].effort) || "";
effort.addEventListener("change", () => {
const next = { model: resolved[word].model };
if (effort.value) next.effort = effort.value;
setRow(word, canonical(next) === canonical(dflt[word]) ? null : next);
});
row.appendChild(effort);
}
if (Object.prototype.hasOwnProperty.call(user, word)) {
const reset = el("button", "btn small ghost strength-reset", "Reset");
reset.type = "button";
reset.dataset.field = "reset";
reset.setAttribute("aria-label", `Reset ${WORDS[word]}`);
reset.addEventListener("click", () => setRow(word, null));
row.appendChild(reset);
} else if (resolved[word]) {
row.appendChild(el("span", "help strength-default", "default"));
}
body.appendChild(row);
}
const offered = STRENGTH_ORDER.filter((w) => resolved[w]).map((w) => WORDS[w]);
body.appendChild(
el(
"p",
"help strength-offer",
offered.length ? `The loop will offer: ${offered.join(", ")}` : "The loop will not offer a strength for this agent until one is mapped."
)
);
if (back) {
// A Reset that was pressed is gone with its row's change: the model select takes the focus.
const row = body.querySelector(`[data-word="${back.word}"]`);
(row?.querySelector(`[data-field="${back.field}"]`) || row?.querySelector('[data-field="model"]'))?.focus();
}
}
ctx.strengthsRefresh = draw;
draw();
return details;
}
+184 -7
View File
@@ -29,6 +29,13 @@ const AFTER_LAST = [
["run-finalize", "Run Finalize automatically", "Finalize starts by itself once every phase is built."],
];
const STRENGTH_WORDS = [
["thrifty", "Thrifty"],
["balanced", "Balanced"],
["best", "Best"],
];
const MATCH_SESSION = "Match my session";
const DEFAULT_NOTIFY_PARAM = "message";
// What the setup can send a notification to. `name` is the label for the field
// the person names, on the kinds that have one.
@@ -57,7 +64,7 @@ export async function openLoopSetup(spec) {
const dir = spec.dir;
page.loopStart = null;
page.loopNotifyTest = null;
page.loopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false };
page.loopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false, resolvedFor: undefined };
tellApp("loop-facts");
redraw();
const mine = page.loopSetup;
@@ -80,7 +87,7 @@ export async function openLoopSetup(spec) {
redraw();
return;
}
const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, ...setup } = answer;
const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, picks, resolved, ...setup } = answer;
mine.form = {
review: setup.review !== false,
fixMode: setup.fixMode === "levels" ? "levels" : "smart",
@@ -94,18 +101,86 @@ export async function openLoopSetup(spec) {
notifyKind: NOTIFY_KINDS.some((k) => k.id === setup.notifyKind) ? setup.notifyKind : "query",
notifyUrl: typeof setup.notifyUrl === "string" ? setup.notifyUrl : "",
notifyParam: setup.notifyParam || DEFAULT_NOTIFY_PARAM,
phaseStrength: setup.phaseStrength === true,
// Every spec's picks, as saved; only this spec's key is changed here.
strengths: setup.strengths && typeof setup.strengths === "object" && !Array.isArray(setup.strengths) ? structuredClone(setup.strengths) : {},
};
if (Array.isArray(picks)) mine.form.strengths[dir] = structuredClone(picks);
// A first visit with nothing typed starts from the project's own check.
if (!remembered && !mine.form.quickCheck && suggestedQuickCheck) mine.form.quickCheck = suggestedQuickCheck;
mine.facts = {
spec: dir,
phasesLeft: Array.isArray(phasesLeft) ? phasesLeft : [],
branch: typeof branch === "string" ? branch : "",
pending: Number.isInteger(pending) ? pending : null,
// The loop agent's strengths: undefined until the app has named the agent
// and the console has answered, then null (no such agent) or { word: { model, effort? } }.
resolved: undefined,
};
mine.loaded = true;
redraw();
}
const loopAgent = () => (page.loopFacts && typeof page.loopFacts.agent === "string" ? page.loopFacts.agent : "");
/**
* Read the loop agent's strengths once the app has said which agent it is. The
* setup and the app answer in either order, so every draw asks (cheaply) whether
* the agent changed since the last read.
*/
function ensureResolved(s) {
if (!page.loopFacts || s.resolvedFor === loopAgent()) return;
const agent = loopAgent();
s.resolvedFor = agent;
if (!agent) {
s.facts.resolved = null;
return;
}
fetch("/loop-setup?spec=" + encodeURIComponent(s.spec) + "&agent=" + encodeURIComponent(agent), { cache: "no-store" })
.then((res) => (res.ok ? res.json() : null))
.catch(() => null)
.then((answer) => {
if (page.loopSetup !== s || s.resolvedFor !== agent) return;
s.facts.resolved = answer && answer.resolved && typeof answer.resolved === "object" ? answer.resolved : null;
redraw();
});
}
const hasMapping = (resolved) => Boolean(resolved) && Object.keys(resolved).length > 0;
/** This spec's saved word for a phase, or "" for Match my session. */
function pickOf(form, spec, phase) {
const list = form.strengths && form.strengths[spec];
const hit = Array.isArray(list) ? list.find((p) => p.n === phase.n && p.name === phase.name) : null;
return hit ? hit.strength : "";
}
function setPick(form, spec, phase, word) {
const rest = (form.strengths[spec] || []).filter((p) => p.n !== phase.n);
if (word) rest.push({ n: phase.n, name: phase.name, strength: word });
rest.sort((a, b) => a.n - b.n);
form.strengths[spec] = rest;
}
/** The phases left whose saved pick is not mapped for the loop's agent. */
function unmappedPicks(form, facts, spec) {
const resolved = facts.resolved;
return facts.phasesLeft.filter((p) => {
const word = pickOf(form, spec, p);
return word && !(resolved && resolved[word]);
});
}
/** "sonnet, low": what a pick becomes. Match my session shows the launch choice. */
export function pickModelText(resolved, word, appFacts) {
if (!word) {
if (!appFacts) return "";
return [appFacts.model || "default model", appFacts.effort].filter(Boolean).join(", ");
}
const row = resolved && resolved[word];
return row ? [row.model, row.effort].filter(Boolean).join(", ") : "";
}
function close() {
page.loopSetup = null;
page.loopStart = null;
@@ -125,6 +200,13 @@ export function startBlock(form, facts, appFacts) {
if (appFacts.permissionMode === "checked") return "The loop needs permission checks off. Start a New Session with checks off first.";
if (appFacts.promptSupport === false) return "This agent cannot be started with a first prompt.";
if (!facts.phasesLeft.length) return "Nothing left to build in this spec.";
// A saved pick the agent no longer maps holds Start until it is changed (FR-14).
// An agent with nothing mapped grays the section instead, and its picks do not count.
if (form.phaseStrength && facts.resolved === undefined) return "Asking the app...";
if (form.phaseStrength && hasMapping(facts.resolved)) {
const bad = unmappedPicks(form, facts, facts.spec);
if (bad.length) return `Pick a new strength for ${bad.map((p) => `Phase ${p.n}`).join(", ")}: not mapped for this agent.`;
}
return "";
}
@@ -256,8 +338,91 @@ export function renderLoopSetup(main) {
main.appendChild(pane);
}
/** A plain select: [value, text, disabled?] options, the chosen value, a change handler. */
function select(id, label, options, value, onChange) {
const box = el("select", "loop-select");
box.id = id;
box.setAttribute("aria-label", label);
for (const [v, text, disabled] of options) {
const o = el("option", null, text);
o.value = v;
o.disabled = Boolean(disabled);
box.appendChild(o);
}
box.value = value;
box.addEventListener("change", () => onChange(box.value));
return box;
}
/** The "Strength per phase" field: the toggle, Set all to, and one row per phase left. */
function strengthField(s, redo) {
const f = s.form;
const resolved = s.facts.resolved;
const box = field("Strength per phase");
const mapped = hasMapping(resolved);
const loading = resolved === undefined;
const off = !loading && !mapped;
const sw = toggle("loop-phase-strength", "Set strength per phase", f.phaseStrength && !off, (v) => ((f.phaseStrength = v), redo()));
if (off) {
sw.classList.add("is-gray");
sw.querySelector("input").disabled = true;
}
box.appendChild(sw);
if (off) {
const line = el("p", "loop-hint loop-strength-none");
line.append("This agent has no strengths mapped yet. ");
const link = el("button", "linky", "Map them in Agents & models");
link.type = "button";
link.addEventListener("click", () => hooks.openPrefs("agents"));
line.appendChild(link);
box.appendChild(line);
return box;
}
if (loading) {
box.appendChild(el("p", "loop-hint", "Asking the app which agent this loop uses..."));
return box;
}
if (!f.phaseStrength) return box;
// An unmapped word stays in the list, grayed, so a saved one is seen and changed.
const options = [
["", MATCH_SESSION],
...STRENGTH_WORDS.map(([word, label]) => [word, resolved[word] ? label : label + " (not mapped)", !resolved[word]]),
];
const all = el("div", "loop-strength-all");
all.appendChild(el("label", "loop-strength-label", "Set all to"));
all.firstChild.htmlFor = "loop-strength-all";
const everyone = select("loop-strength-all", "Set all phases to", [["-", "Choose..."], ...options.map(([v, t, d]) => [v === "" ? "match" : v, t, d])], "-", (v) => {
if (v === "-") return;
for (const p of s.facts.phasesLeft) setPick(f, s.spec, p, v === "match" ? "" : v);
redraw();
});
all.appendChild(everyone);
box.appendChild(all);
const rows = el("div", "loop-strength-rows");
for (const p of s.facts.phasesLeft) {
const word = pickOf(f, s.spec, p);
const row = el("div", "loop-strength-row");
row.dataset.phase = String(p.n);
row.appendChild(el("span", "loop-strength-phase", `Phase ${p.n}: ${p.name}`));
row.appendChild(
select(`loop-strength-${p.n}`, `Phase ${p.n} strength`, options, word, (v) => {
setPick(f, s.spec, p, v);
s.problems = [];
redraw();
})
);
row.appendChild(el("span", "loop-strength-model", pickModelText(resolved, word, page.loopFacts)));
rows.appendChild(row);
}
box.appendChild(rows);
return box;
}
function drawBody(pane, s) {
const f = s.form;
ensureResolved(s);
const redo = () => {
s.problems = [];
redraw();
@@ -287,6 +452,8 @@ function drawBody(pane, s) {
// The fields (FR-2, FR-4).
const form = el("div", "loop-form");
form.appendChild(strengthField(s, redo));
const review = field("Review");
review.appendChild(toggle("loop-review", "Review each phase with a fresh agent before it counts", f.review, (v) => ((f.review = v), redo())));
form.appendChild(review);
@@ -503,9 +670,19 @@ function gitButton() {
return b;
}
/** The form as the console saves it. */
function setupBody(f) {
return { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM };
/** The form as the console saves it (exported for the page tests). */
export function setupBody(f, s) {
const body = { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM };
// Only this spec's key changes: its rows that are not Match my session. With the
// toggle off, or an agent with nothing mapped, the saved picks stay as they are
// but the loop is told nothing about strengths (NFR-3).
const strengths = structuredClone(f.strengths || {});
const mine = (strengths[s.spec] || []).filter((p) => p.strength);
if (mine.length) strengths[s.spec] = mine;
else delete strengths[s.spec];
body.strengths = strengths;
body.phaseStrength = f.phaseStrength && hasMapping(s.facts.resolved);
return body;
}
/**
@@ -519,7 +696,7 @@ async function sendTest(s) {
s.problems = [];
page.loopNotifyTest = { waiting: true };
redraw();
const { status, body: answer } = await postJson("/loop-setup", setupBody(f));
const { status, body: answer } = await postJson("/loop-setup", setupBody(f, s));
if (page.loopSetup !== s) return;
if (status !== 200 || !answer || answer.ok !== true) {
page.loopNotifyTest = null;
@@ -537,7 +714,7 @@ async function startLoop(s) {
page.loopStart = null;
s.starting = true;
redraw();
const { status, body: answer } = await postJson("/loop-setup", setupBody(f));
const { status, body: answer } = await postJson("/loop-setup", setupBody(f, s));
if (page.loopSetup !== s) return;
if (status !== 200 || !answer || answer.ok !== true) {
s.starting = false;
+45
View File
@@ -0,0 +1,45 @@
// The loop's strength rule, shared by the page and the server (strengths.mjs re-exports it).
// Turns Thrifty, Balanced and Best into a model (and effort) for one agent. Pure functions, no file reads: the caller passes the
// shipped and user mappings (the `strengths` key of models.json) and the
// agent's Models list. Held to scripts/fixtures/strength-cases.json; the Rust
// twin is `resolve_strengths` / `next_strength` in
// plan2code-app/src-tauri/src/models.rs, held to the same file.
export const STRENGTH_ORDER = ["thrifty", "balanced", "best"];
const EFFORTS = ["low", "medium", "high"];
// One row as the resolver keeps it, or null when the row is not usable: the
// model must be a string in `models`; an effort survives only when the agent
// takes one and it is low, medium or high.
function validRow(row, models, hasEffort) {
if (!row || typeof row !== "object" || Array.isArray(row)) return null;
if (typeof row.model !== "string" || !models.includes(row.model)) return null;
const out = { model: row.model };
if (hasEffort && EFFORTS.includes(row.effort)) out.effort = row.effort;
return out;
}
/**
* { thrifty?, balanced?, best? } for one agent: per word the user's row if it is
* valid, else the shipped row if it is valid. A word with neither is left out
* (unmapped).
*/
export function resolveStrengths({ shipped, user, models, hasEffort } = {}) {
const list = Array.isArray(models) ? models : [];
const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
const resolved = {};
for (const word of STRENGTH_ORDER) {
const row = validRow(obj(user)[word], list, !!hasEffort) || validRow(obj(shipped)[word], list, !!hasEffort);
if (row) resolved[word] = row;
}
return resolved;
}
/** The first mapped word after `word` in STRENGTH_ORDER, else null. */
export function nextStrength(resolved, word) {
const at = STRENGTH_ORDER.indexOf(word);
if (at < 0) return null;
const have = resolved && typeof resolved === "object" ? resolved : {};
for (const next of STRENGTH_ORDER.slice(at + 1)) if (have[next]) return next;
return null;
}
+10
View File
@@ -155,3 +155,13 @@
.split { grid-template-columns: 1fr; }
.split-list { border-right: 0; border-bottom: 1px solid var(--rule); max-height: 260px; overflow: auto; }
}
/* ------------------------------------------------- strengths in the loop */
.strength-body { display: grid; gap: 6px; }
.strength-row { display: grid; grid-template-columns: 5.5em minmax(0, 1fr) auto; gap: 6px; align-items: center; }
.strength-row:has(select + select) { grid-template-columns: 5.5em minmax(0, 1fr) minmax(0, 8em) auto; }
.strength-row select { min-width: 0; }
.strength-word { font-size: 0.9em; }
.strength-default { margin: 0; font-size: 0.8em; color: var(--ink-3); }
.strength-empty, .strength-offer { margin: 0; }
@@ -629,6 +629,15 @@
.loop-radios { display: grid; gap: 6px; }
.loop-radio-body { display: grid; gap: 1px; }
.loop-radio-detail { font-size: 12.5px; color: var(--ink-3); }
.loop-switch.is-gray { opacity: 0.55; cursor: default; }
.loop-strength-none .linky { font-size: inherit; }
.loop-strength-all { display: flex; align-items: center; gap: 10px; margin-top: 4px; font-size: 13px; color: var(--ink-2); }
.loop-strength-rows { display: grid; gap: 6px; }
.loop-strength-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(150px, 190px) minmax(70px, 120px); align-items: center; gap: 10px; font-size: 13.5px; }
.loop-strength-phase { overflow-wrap: anywhere; color: var(--ink); }
.loop-strength-model { font-size: 12.5px; color: var(--ink-3); overflow-wrap: anywhere; }
.loop-select { font: inherit; font-size: 13.5px; padding: 5px 8px; color: var(--ink); background: var(--panel-2); border: 1px solid var(--rule); border-radius: 6px; max-width: 100%; }
@media (max-width: 560px) { .loop-strength-row { grid-template-columns: 1fr 1fr; } .loop-strength-phase { grid-column: 1 / -1; } }
.loop-ticks { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-left: 4px; }
.loop-text { font: inherit; font-size: 14px; padding: 6px 10px; color: var(--ink); background: var(--panel-2); border: 1px solid var(--rule); border-radius: 6px; max-width: 520px; width: 100%; }
.loop-text.loop-narrow { width: 90px; }
+144 -16
View File
@@ -35,6 +35,7 @@ import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs";
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
import { specKey } from "./workspace.mjs";
import { readLoopSetup, saveLoopSetup } from "./loop-setup.mjs";
import { resolveStrengths } from "./strengths.mjs";
import { MARKERS, phaseChecklist } from "./spec-files.mjs";
import {
PR_HOST_KINDS,
@@ -612,6 +613,79 @@ function cleanModels(input) {
return { models };
}
// The loop's strength words and the efforts a mapping may carry (strengths.mjs).
const STRENGTH_WORDS = ["thrifty", "balanced", "best"];
const STRENGTH_EFFORTS = ["low", "medium", "high"];
// Agent ids a strengths mapping may name: the shipped built-ins plus the ids of
// the person's own added agents.
function strengthAgentIds() {
const ids = new Set(modelClis());
try {
const raw = fs.existsSync(USER_AGENTS_FILE) ? readText(USER_AGENTS_FILE) : undefined;
for (const a of normalizeAgents(raw).agents) if (a && typeof a.id === "string" && a.id) ids.add(a.id);
} catch {
// A broken agents file adds no ids; the built-ins still map.
}
return ids;
}
/**
* The user's strengths mapping: { <agent id>: { thrifty|balanced|best: { model, effort? } } }.
* Returns { strengths } or { error } naming the field. Only known agent ids, the three
* words, a model matching MODEL_ID and an effort of low, medium or high survive; an
* agent left with no row is dropped.
*/
function cleanStrengths(input) {
if (input == null) return { strengths: {} };
if (typeof input !== "object" || Array.isArray(input)) return { error: "strengths must be an object" };
const known = strengthAgentIds();
const strengths = {};
for (const [agent, rows] of Object.entries(input)) {
if (!known.has(agent)) return { error: `strengths.${agent}: not a known agent` };
if (!rows || typeof rows !== "object" || Array.isArray(rows)) return { error: `strengths.${agent} must be an object` };
const out = {};
for (const [word, row] of Object.entries(rows)) {
if (!STRENGTH_WORDS.includes(word)) return { error: `strengths.${agent}.${word}: not a strength (thrifty, balanced or best)` };
if (!row || typeof row !== "object" || Array.isArray(row)) return { error: `strengths.${agent}.${word} must be an object` };
const model = typeof row.model === "string" ? row.model.trim() : "";
if (!MODEL_ID.test(model)) return { error: `strengths.${agent}.${word}.model: "${model}" is not a valid model id` };
const entry = { model };
if (row.effort != null && row.effort !== "") {
if (!STRENGTH_EFFORTS.includes(row.effort)) return { error: `strengths.${agent}.${word}.effort: must be low, medium or high` };
entry.effort = row.effort;
}
out[word] = entry;
}
if (Object.keys(out).length) strengths[agent] = out;
}
return { strengths };
}
// Strengths from a models file that was read from disk. Tolerant, unlike a POST body:
// an agent that is no longer known (a deleted custom agent) or whose rows are bad is
// skipped on its own, so it never hides or wipes the other agents' mapping.
function savedStrengths(file) {
const saved = file && file.strengths;
if (!saved || typeof saved !== "object" || Array.isArray(saved)) return {};
const out = {};
for (const [agent, rows] of Object.entries(saved)) {
if (!rows || typeof rows !== "object" || Array.isArray(rows)) continue;
// Row by row, like the app: a bad row is dropped, a bad effort is dropped and
// its row stays, and the agent keeps every other row.
const kept = {};
for (const [word, row] of Object.entries(rows)) {
let one = cleanStrengths({ [agent]: { [word]: row } });
if (!one.strengths && row && typeof row === "object" && !Array.isArray(row) && row.effort != null) {
one = cleanStrengths({ [agent]: { [word]: { model: row.model } } });
}
if (one.strengths && one.strengths[agent]) Object.assign(kept, one.strengths[agent]);
}
if (Object.keys(kept).length) out[agent] = kept;
}
return out;
}
function shippedModels() {
const file = readJson(SHIPPED_MODELS_FILE, null) || {};
const out = {};
@@ -625,7 +699,12 @@ function shippedModels() {
function modelsGet(req, res) {
const saved = readJson(USER_MODELS_FILE, null) || {};
const { models } = cleanModels(saved);
return json(res, 200, { shipped: shippedModels(), user: models || Object.fromEntries(modelClis().map((cli) => [cli, []])) });
const shippedFile = readJson(SHIPPED_MODELS_FILE, null) || {};
return json(res, 200, {
shipped: shippedModels(),
user: models || Object.fromEntries(modelClis().map((cli) => [cli, []])),
strengths: { shipped: savedStrengths(shippedFile), user: savedStrengths(saved) },
});
}
function modelsPost(req, res) {
@@ -633,13 +712,22 @@ function modelsPost(req, res) {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
// A body without strengths keeps the mapping already saved, so saving a Models list never wipes it.
let strengths;
if (body && body.strengths !== undefined) {
const cleaned = cleanStrengths(body.strengths);
if (cleaned.error) return json(res, 400, { error: cleaned.error });
strengths = cleaned.strengths;
} else {
strengths = savedStrengths(readJson(USER_MODELS_FILE, null));
}
try {
ensureDir(path.dirname(USER_MODELS_FILE));
writeJsonAtomic(USER_MODELS_FILE, models);
writeJsonAtomic(USER_MODELS_FILE, Object.keys(strengths).length ? { ...models, strengths } : models);
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, { ok: true, user: models });
return json(res, 200, { ok: true, user: models, strengths });
});
}
@@ -1492,22 +1580,60 @@ const loopProject = (ctx) => (ctx.readState() || {}).project || ctx.project || c
// `?spec=specs/<name>` adds the setup screen's read-only facts (FR-3): the
// phases not yet marked done, the branch and the count of uncommitted files.
// The server reads the project here and never writes it.
// The phases of `spec` not yet done, as [{ n, name }]; null when its overview.md
// cannot be read (the store then keeps that spec's picks as they are).
function phasesLeftOf(project, spec) {
try {
const overview = fs.readFileSync(path.join(project, spec, "overview.md"), "utf8");
// Done as specs.mjs reads it ([x], [X], [?]), the same rule the app's Start uses.
return phaseChecklist(overview)
.filter((p) => !["complete", "assumed"].includes(MARKERS[p.marker]))
.map((p) => ({ n: p.number, name: p.name }));
} catch {
return null;
}
}
// Agents that take an effort beside the model (the Preferences page's HAS_EFFORT).
const EFFORT_AGENTS = ["claude", "codex"];
/**
* The loop agent's resolved strengths ({ thrifty?, balanced?, best? }, each { model, effort? })
* for `?agent=<id>`: a built-in's Models list is what ships plus what the person added; an
* added agent's is its own. null when the id is neither.
*/
function resolvedStrengthsFor(agentId) {
if (typeof agentId !== "string" || !agentId) return null;
const shippedFile = readJson(SHIPPED_MODELS_FILE, null) || {};
const savedFile = readJson(USER_MODELS_FILE, null) || {};
let models;
let hasEffort = false;
if (modelClis().includes(agentId)) {
const user = cleanModels(savedFile).models || {};
models = [...(shippedModels()[agentId] || []), ...(user[agentId] || [])].map((m) => m.id);
hasEffort = EFFORT_AGENTS.includes(agentId);
} else {
const raw = fs.existsSync(USER_AGENTS_FILE) ? readText(USER_AGENTS_FILE) : undefined;
let found = null;
try {
found = normalizeAgents(raw).agents.find((a) => a && a.id === agentId) || null;
} catch {
found = null;
}
if (!found) return null;
models = (Array.isArray(found.models) ? found.models : []).map((m) => m.id);
}
const owned = (file) => savedStrengths(file)[agentId] || {};
return resolveStrengths({ shipped: owned(shippedFile), user: owned(savedFile), models, hasEffort });
}
function loopSetupGet(req, res, ctx, url) {
const answer = readLoopSetup(loopProject(ctx));
const answer = readLoopSetup(loopProject(ctx), (s) => phasesLeftOf(loopProject(ctx), s));
const spec = url && url.searchParams.get("spec");
if (spec === null || spec === undefined) return json(res, 200, answer);
if (!/^specs\/[^/\\]+$/.test(spec) || /^specs\/\./.test(spec)) return json(res, 400, { error: "spec must be a folder directly under specs/" });
const state = ctx.readState() || {};
let phasesLeft = [];
try {
const overview = fs.readFileSync(path.join(loopProject(ctx), spec, "overview.md"), "utf8");
// Done as specs.mjs reads it ([x], [X], [?]), the same rule the app's Start uses.
phasesLeft = phaseChecklist(overview)
.filter((p) => !["complete", "assumed"].includes(MARKERS[p.marker]))
.map((p) => ({ n: p.number, name: p.name }));
} catch {
/* no overview.md: nothing to build */
}
const phasesLeft = phasesLeftOf(loopProject(ctx), spec) || [];
const pending = state.scan && Number.isInteger(state.scan.pending) ? state.scan.pending : null;
// What to prefill an empty quick check with: the project's own build, then
// lint, script. Text only; nothing here runs it.
@@ -1519,7 +1645,9 @@ function loopSetupGet(req, res, ctx, url) {
} catch {
/* no package.json, or not JSON: no suggestion */
}
return json(res, 200, { ...answer, phasesLeft, branch: state.branch || "", pending, suggestedQuickCheck });
const agent = url.searchParams.get("agent");
const picks = Array.isArray(answer.strengths[spec]) ? answer.strengths[spec] : [];
return json(res, 200, { ...answer, phasesLeft, branch: state.branch || "", pending, suggestedQuickCheck, picks, resolved: resolvedStrengthsFor(agent) });
}
function loopSetupPost(req, res, ctx) {
@@ -1527,7 +1655,7 @@ function loopSetupPost(req, res, ctx) {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { ok: false, problems: ["the setup must be a JSON object"] });
try {
return json(res, 200, { ok: true, setup: saveLoopSetup(loopProject(ctx), body) });
return json(res, 200, { ok: true, setup: saveLoopSetup(loopProject(ctx), body, (s) => phasesLeftOf(loopProject(ctx), s)) });
} catch (e) {
if (Array.isArray(e.problems)) return json(res, 400, { ok: false, problems: e.problems });
return json(res, 500, { error: String(e.message) });
+7 -2
View File
@@ -2,7 +2,7 @@
import path from "node:path";
import { cleanSetting, defaultSetting, DEFAULT_STRENGTH, offered } from "./public/subagents.js";
import { cleanSetting, defaultSetting, DEFAULT_STRENGTH, offered, STRENGTHS } from "./public/subagents.js";
import { ensureDir, fileStamp, HOME_DIR, readJson, readJsonLines, withStateLock, writeJsonAtomic } from "./files.mjs";
import { foldKey } from "./workspace.mjs";
@@ -174,7 +174,12 @@ export function serverSubagents(ctx) {
function sync(state) {
if (!state || typeof state.workflow !== "string") return;
const { workflow } = state;
const { on, instruction, max, strength } = offered(workflow) ? subagentStoreEntry(ctx.worktree(), workflow) : defaultSetting(workflow);
const stored = offered(workflow) ? subagentStoreEntry(ctx.worktree(), workflow) : defaultSetting(workflow);
// A loop phase on a strength runs its helpers at that strength, for this
// session only: the stored setting is read, never written (FR-16).
const loopStrength = state.loop && state.loop.strength;
const { on, instruction, max } = stored;
const strength = STRENGTHS.includes(loopStrength) ? loopStrength : stored.strength;
const target = { workflow, on, instruction, max, strength };
const current = readSubagentSetting(dir);
if (current && sameSetting(current, target)) return;
+5
View File
@@ -34,6 +34,7 @@ export const SERVABLE = new Set([
"sound.js",
"looks.js",
"selectors.js",
"strengths.js",
"app.css",
"render.js",
"palette.js",
@@ -75,6 +76,7 @@ export const SERVABLE = new Set([
"screens/agents/agents-list-editor.js",
"screens/agents/agents-summary.js",
"screens/agents/agents-form.js",
"screens/agents/agents-strengths.js",
"screens/prefs-dialog.js",
"screens/cleanup.js",
"screens/help-dialog.js",
@@ -110,6 +112,8 @@ export const SERVABLE = new Set([
"activities/bumper-draw.js",
"activities/rapids.js",
"activities/rapids-draw.js",
"activities/flock.js",
"activities/flock-draw.js",
"activities/fuse.js",
"activities/fuse-draw.js",
"activities/hop.js",
@@ -232,6 +236,7 @@ export const SERVABLE = new Set([
"activities/stack-sfx.js",
"activities/bumper-sfx.js",
"activities/rapids-sfx.js",
"activities/flock-sfx.js",
"activities/fuse-sfx.js",
"activities/hop-sfx.js",
"activities/bounce-sfx.js",
+3
View File
@@ -0,0 +1,3 @@
// The server-side name for the strength rule. The code lives in public/strengths.js
// so the Preferences page imports the very same module; see that file's header.
export { STRENGTH_ORDER, nextStrength, resolveStrengths } from "./public/strengths.js";