Skip to content
13 changes: 7 additions & 6 deletions app/nullius/standard/pages/recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,10 +426,11 @@ def compile(recipe: dict, defs: Optional[Dict[str, List[dict]]] = None, *,
the run sends it as."""
d = defs or _all()
errors, notes = [], []
# each problem once; shown: the step already says it elsewhere, so only Review lists it; field: the input it is about
def add(step, message, shown=False, field=None):
# each problem once; shown: the step already says it elsewhere, so only Review lists it; field: the input it is about; unset: nothing is
# chosen yet, which the Model step does not say before its field is used
def add(step, message, shown=False, field=None, unset=False):
if not any(e["step"] == STEP[step] and e["message"] == message for e in errors):
errors.append({"step": STEP[step], "message": message, **({"shown": True} if shown else {}), **({"field": field} if field else {})})
errors.append({"step": STEP[step], "message": message, **({"shown": True} if shown else {}), **({"field": field} if field else {}), **({"unset": True} if unset else {})})
out = {"errors": errors, "notes": notes, "review": [], "jobs": [], "confirm": "", "script": "", "parts": [], "model": "",
"served_models": {}}
name = str(recipe.get("name") or "")
Expand Down Expand Up @@ -482,7 +483,7 @@ def add(step, message, shown=False, field=None):
orig = (b.get("setups") or {}).get("original") or {}
picked = str(recipe.get("model") or "").strip()
if not picked:
add("model", "Choose a model.")
add("model", "Choose a model.", unset=True)
continue
method = "model" if recipe.get("model_choice", "any") != "paper" and "model" in (b.get("setups") or {}) else "original"
if method == "original":
Expand Down Expand Up @@ -592,7 +593,7 @@ def add(step, message, shown=False, field=None):
add("model", f"{providers.label(provider)} does not serve what {b['label']}'s judge speaks: choose another provider.")
model = str(recipe.get("model") or "").strip()
if not _MODEL.match(model) and (needs_model or model):
add("model", "Choose a model or enter its ID.")
add("model", "Choose a model or enter its ID.", unset=not model)
if model_choice == "paper" and model in orig.get("models", []) and provider_ in orig.get("providers", {}):
model = orig["providers"][provider_] + (orig.get("served_as") or {}).get(model, model)
# each unit tried K times (the upstream's --num-trials: pass^k); the user simulator's and the judge's models
Expand Down Expand Up @@ -767,7 +768,7 @@ def called_of(p: dict) -> List[str]:
add("model", f"Served by pins {m} twice, with different providers: give its fields the same ones.")
by_model[m] = list(slugs)
# each field's model as the run sends it, for the builder to ask its providers under that name
out["served_models"] = {role: next((sent_of(p)[role] for p in sorted(picks, key=lambda q: q["control"]) if sent_of(p)[role]), None)
out["served_models"] = {role: next((sent_of(p)[role] for p in sorted(picks, key=lambda q: q["control"]) if _MODEL.match(sent_of(p)[role] or "")), None)
for role in roles}

def pinned(p: dict) -> Dict[str, List[str]]:
Expand Down
6 changes: 3 additions & 3 deletions app/static/builder/command-builder-core.js
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@
const RESERVED = ['agent','a','model','m','dataset','d','path','p','n-tasks','l','n-concurrent','n','max-retries','r','env','e','job-name','jobs-dir','o','agent-timeout-multiplier','include-task-name','i','ak','agent-kwarg','ek','environment-kwarg','verifier-kwarg','agent-env','ae'];
function validate(r) {
const errors = [], notes = [];
const add = (step, message, group) => errors.push({step, message, ...(group ? {group} : {})});
const add = (step, message, group, unset) => errors.push({step, message, ...(group ? {group} : {}), ...(unset ? {unset} : {})});
if (isStandard(r)) return {errors, notes}; // compiled and checked by the server, from its definition files
if (r.harness !== 'harbor') { add(STEP.runner, RUNNER_GONE); return {errors, notes}; }
const blocker = routeBlocker(r.benchmark);
Expand All @@ -533,9 +533,9 @@
const named = r.model.trim() || (benchmarkCallsModel(r) && r.agents.every(id => agentById(id, r)?.control) ? (r.userModel || '').trim() : '');
if (callsModel && r.model_choice === 'paper') {
const allowed = Object.values(paperModels(r).sent?.[r.provider] || {});
if (!allowed.includes(r.model)) add(STEP.model, 'Choose one of the paper models on this provider.');
if (!allowed.includes(r.model)) add(STEP.model, 'Choose one of the paper models on this provider.', '', !r.model);
}
if (callsModel && !named) add(STEP.model, benchmarkCallsModel(r) ? 'Enter a model for the agent and/or simulated user and evaluator.' : 'Enter a model.');
if (callsModel && !named) add(STEP.model, benchmarkCallsModel(r) ? 'Enter a model for the agent and/or simulated user and evaluator.' : 'Enter a model.', '', true);
if (callsModel && !PROVIDERS.includes(r.provider)) add(STEP.model, 'Choose a provider: OpenRouter, OpenAI, Anthropic or a custom provider.');
for (const [key,label] of [['keyEnv','API key source variable'],['urlEnv','Endpoint source variable']]) {
if (callsModel && (key !== 'urlEnv' || r[key]) && !/^[A-Z_][A-Z0-9_]*$/.test(r[key])) add(STEP.model, label + ' must be an environment variable name.');
Expand Down
5 changes: 0 additions & 5 deletions app/static/builder/command-builder.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 39 additions & 10 deletions app/static/builder/command-builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
// the model's providers (POST /new-run/endpoints), a pick or a slug typed and Enter joins the list under it, each
// removable. Empty: any provider. What a row shows is C.servedRow's; `compiled()` is the server's last compile and
// the key of the recipe it was made for (C.servedKey).
function servedRows({C, root, r, compiled, esc, button, providers}) {
// A role whose model is being typed has no row: `typing(role)`.
function servedRows({C, root, r, compiled, esc, button, providers, typing = () => false}) {
const NAME = {model: 'model', simulator: 'user simulator', judge: 'judge'};
// the model a Served by is for, as the step shows it: the field's, else the leaderboard's or the official one
const shown = (rec, role) => {
Expand Down Expand Up @@ -43,7 +44,7 @@
const rec = r();
root.querySelectorAll('input[data-served-by]').forEach(input => {
const role = input.dataset.servedBy, s = row(rec, role), list = root.querySelector(`[data-served-list="${role}"]`);
input.closest('.std-served').hidden = !C.servedRoles(rec).includes(role) || !s.visible;
input.closest('.std-served').hidden = !C.servedRoles(rec).includes(role) || !s.visible || typing(role);
Object.assign(input.dataset, {servedModel: s.model, servedPending: String(s.pending), chosen: s.chosen.join(',')});
input.placeholder = s.placeholder;
if (list && list.dataset.of !== JSON.stringify(s.chosen)) { list.dataset.of = JSON.stringify(s.chosen); list.innerHTML = chips(role, s.chosen); }
Expand Down Expand Up @@ -219,9 +220,10 @@
};
// The standard's recipe as the server compiles it from the definitions (POST
// /new-run/runner). Nothing typed here is a command; Run sends the choices.
let runnerOut = null, runnerKey = '', runnerTimer, runnerServed = null;
let runnerOut = null, runnerKey = '', runnerOutKey = '', runnerTimer, runnerServed = null;
// Served by's rows (servedRows above), given the models the server last named and what decided them (C.servedCompiled)
const {field: servedField, sync: syncServed, acceptCompile} = servedRows({C, root, r, esc, button, compiled: () => runnerServed, providers: window.NulliusServingProviders});
const {field: servedField, sync: syncServed, acceptCompile} = servedRows({C, root, r, esc, button, compiled: () => runnerServed, providers: window.NulliusServingProviders,
typing: role => !!root.querySelector(`[data-field="${role === 'model' ? role : role + '_model'}"][data-typing]`)});
// Switching runner keeps the recipe being edited, one per runner, for as long as the page is open: switching back finds it as it was.
const keptByRunner = {};
// Nullius's own mark for the standard; Harbor's for Harbor
Expand Down Expand Up @@ -876,7 +878,7 @@
runnerServed = accepted.served;
if (step === S.model) syncServed();
if (!accepted.current) return;
runnerOut = out;
runnerOut = out; runnerOutKey = key;
if (step === REVIEW) renderForm();
refreshPlan();
}, 120);
Expand Down Expand Up @@ -975,14 +977,40 @@
$('#nb-next').textContent=step===REVIEW?'Export recipe JSON':stepName(steps[nextShown(step,1)],nextShown(step,1))+' →';
placeThumb();
}
// The open step's errors. The Model step says none over a model being typed, nor before one is chosen or its field left.
let modelActed=false;
function localErrors() {
const rec=r(),el=document.activeElement,typing=root.contains(el)&&el.dataset.typing;
if(step===REVIEW)modelActed=true;
// nor the last check's while the next is on its way
const quiet=step===S.model&&(typing||C.isStandard(rec)&&runnerKey!==runnerOutKey);
$('#nb-localerrors').textContent=fieldErrors($('#nb-form'),quiet?[]:compiled.errors.filter(e=>e.step===step&&!e.shown&&!(e.unset&&!modelActed)),esc).map(e=>e.message).join(' ');
}
// A model picked, entered, or left in its field: the recipe takes it at once. What the page shows of it waits for a
// press to end, so a button pressed to leave the field does not move from under the pointer.
let pressing=false,afterPress=null;
document.addEventListener('pointerdown',()=>{pressing=true;},true);
for(const end of ['pointerup','pointercancel'])document.addEventListener(end,()=>{pressing=false;const show=afterPress;afterPress=null;if(show)setTimeout(show);},true);
function commitModel(el) {
if(document.activeElement===el&&!document.hasFocus())return; // the window lost the focus, not the field: still being typed
const rec=r(),key=el.dataset.field,value=el.value.trim(),changed=value!==(rec[key]||'');
modelActed=true;delete el.dataset.typing;
if(changed){
if(rec.modelFormat!=='provider-id'){for(const k of ['model','userModel','evalModel'])if(typeof rec[k]==='string')rec[k]=C.bareModel(rec[k]);rec.modelFormat='provider-id';}
C.setModelOf(rec,key,value);saveDraft(); // the field's pin goes with its model
}
const show=()=>{syncServed();refreshPlan();}; // asks nothing of a recipe already checked
if(pressing)afterPress=show;
else queueMicrotask(show);
}
function refreshPlan() {
const rec=r();
if(C.isStandard(rec)){
compileRunner();
const out=runnerOut||{errors:[],notes:[]};
compiled={errors:out.errors||[],notes:out.notes||[]};
}else{compiled=C.compile(rec);}
$('#nb-localerrors').textContent=fieldErrors($('#nb-form'),compiled.errors.filter(e=>e.step===step&&!e.shown),esc).map(e=>e.message).join(' ');
localErrors();
const errors=$('#nb-errors');
if(errors){
errors.hidden=!compiled.errors.length;
Expand Down Expand Up @@ -1172,7 +1200,7 @@
else if(b.id==='nb-next'){if(step===REVIEW){if(!compiled.errors.length)download(JSON.stringify(r(),null,2)+'\n',r().name+'.json','application/json');return;}step=nextShown(step,1);}
else if(b.id==='nb-back')step=nextShown(step,-1);
else if(b.id==='nb-save'){if(schema.local)openSave();return;}
else if(b.id==='nb-startover'){try{localStorage.removeItem(draftKey);}catch{}recipe=C.prefill({});savedId='';runnerOut=null;runnerKey='';step=S.benchmark;tab='select';status('Started over from the defaults.');}
else if(b.id==='nb-startover'){try{localStorage.removeItem(draftKey);}catch{}recipe=C.prefill({});savedId='';runnerOut=null;runnerKey='';modelActed=false;step=S.benchmark;tab='select';status('Started over from the defaults.');}
else if(b.id==='nb-save-cancel'){$('#nb-save-dialog').close();return;}
else if(b.id==='nb-saved-toggle'){renderSaved();$('#nb-saved').showModal();loadSaved();return;}
else if(b.id==='nb-saved-close'){$('#nb-saved').close();return;}
Expand All @@ -1191,7 +1219,7 @@
if(el.id==='nb-recipe-title'){updateSavePreview();return;}
if(d.servedBy!==undefined)return; // what is typed in a Served by filters its menu: a pick, or Enter, adds it (nb-pick)
if(d.stdUnsandboxed!==undefined)return; // a box's value is no tick: its change sets the recipe
if(d.providerModel && rec.modelFormat !== 'provider-id'){for(const key of ['model','userModel','evalModel'])if(typeof rec[key]==='string')rec[key]=C.bareModel(rec[key]);rec.modelFormat='provider-id';}
if(d.providerModel){d.typing='true';syncServed();localErrors();return;} // what is typed in a model field filters its list: a pick, Enter or leaving the field sets it
if(d.field){const p=d.field.startsWith('param:')?C.parameters().find(p=>p.key===d.field.slice(6)):null;
const value=el.type==='number'?(el.value===''?'':Number(el.value)):el.value;
if(p)rec.params[p.key]=p.type==='optional-boolean'?(value==='__default__'?null:value==='true'):value;
Expand All @@ -1200,7 +1228,6 @@
else if(!d.providerModel&&['model','userModel','evalModel'].includes(d.field)&&/^(openrouter|openai)\//.test(String(value))){rec.provider=C.providerOf(rec,value);rec[d.field]=C.bareModel(value);
renderForm();refreshPlan();const f=root.querySelector(`[data-field="${d.field}"]`);if(f){f.focus();f.setSelectionRange(f.value.length,f.value.length);}return;} // the provider the prefix named, and whether it is set
else if(d.field==='provider'){C.setChoice(rec,value);renderForm();refreshPlan();return;} // whether it is set in Settings, and the names a runner's models are sent as, follow the provider
else if(['model','simulator_model','judge_model'].includes(d.field)){C.setModelOf(rec,d.field,value);syncServed();} // the field's pin goes with its model; its Served by follows, in place
else rec[d.field]=value;
if(el.list?.id==='nb-paths')completeDirectory(el.value);
}else if(d.stdMinutes){const t=Object.assign({},rec.timeouts);if(el.value===''||!(Number(el.value)>0))delete t[d.stdMinutes];else t[d.stdMinutes]=Number(el.value);if(Object.keys(t).length)rec.timeouts=t;else delete rec.timeouts;refreshPlan();return;
Expand All @@ -1217,13 +1244,15 @@
// no cap, unsaid. It is said, and the field emptied, so that it shows what the recipe holds
root.addEventListener('focusout',event=>{
const el=event.target;
if(el.dataset.providerModel)commitModel(el); // a change undone by hand since the focus fires no change event
if(el.type==='number'&&(el.dataset.field||el.dataset.stdMinutes||el.dataset.benchOptSelect)&&el.validity&&el.validity.badInput){el.value='';window.nulliusNotify?.(`${el.getAttribute('aria-label')}: enter a number.`,{error:true,key:'bad-number'});}
});
// a provider picked in a Served by, or slugs typed there and Enter: they join its list, after the ones there
root.addEventListener('nb-pick',event=>{const role=event.target.dataset.servedBy;if(!role)return;C.addServed(r(),role,event.detail);syncServed();refreshPlan();});
root.addEventListener('change',async event=>{
const el=event.target,d=el.dataset;
if(d.custom?.endsWith(':type')){$('#nb-parameters').innerHTML=customRows(!['common','extra'].includes(tab)?tab:'');}
if(d.providerModel)commitModel(el);
else if(d.custom?.endsWith(':type')){$('#nb-parameters').innerHTML=customRows(!['common','extra'].includes(tab)?tab:'');}
else if(d.stdUnsandboxed!==undefined){r().unsandboxed=el.checked;refreshPlan();}
else if(d.stdVersion!==undefined){ // in place: only the card's count changes on this step, so nothing else is drawn again
C.setStandardBenchmark(r(),el.value);benchTasks();render(false,false);}
Expand Down
Loading