A role whose title holds one of the agent's phrases as whole words is gated with the phrase as its reason, a favourite's too. The agent form has a Leave out titles line under Where. function = sales could not do it, since the classifier files Solutions Engineer and pre-sales under sales. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
831 lines
34 KiB
JavaScript
831 lines
34 KiB
JavaScript
/* The Search agents page: what Best match on the Roles tab is measured
|
||
* against, one agent at a time.
|
||
*
|
||
* Every agent from `/api/agents` is a card, newest first: its name, its
|
||
* switch, its prompts, its gates in words, its weights, and a link to the
|
||
* Roles tab in its order. The prompts are the body, since fit is measured
|
||
* against the one a role fits best; the weights only share out the terms.
|
||
* The form edits the prompts as rows, and the gates as a Where block, a
|
||
* short list of lines a role passes by matching any one of, over a row per
|
||
* remaining rule under Advanced; a gate Where cannot say lands in a row, so
|
||
* a load and a save lose nothing. Edit turns a card
|
||
* into the form from the page's `<template>`, in place, and New agent puts a
|
||
* blank card on top in the same state. One card edits at a time, so the
|
||
* form's ids stay unique. Votes, liked companies and scores are the agent's,
|
||
* so a delete takes them with it, and the confirm says so.
|
||
*
|
||
* The fetch terms are chips of free text, as the towns are: words that
|
||
* narrow what big boards read with the wide reach send (app/jobs/reach.py).
|
||
* The card says them in a line of their own, or that boards send every role.
|
||
*
|
||
* Every request goes through `api()` from app.js, so a failure is one toast
|
||
* carrying the server's own sentence.
|
||
*/
|
||
(function () {
|
||
"use strict";
|
||
|
||
const { api, count } = window;
|
||
const $ = (sel, root = document) => root.querySelector(sel);
|
||
|
||
const DEFAULT_WEIGHTS = { fit: 0.6, recency: 0.2, affinity: 0.2, taste: 0.2 };
|
||
// What the model reads after a pull, per agent: the best `extract_top`
|
||
// roles scoring at least `extract_min` get their gate columns filled, the
|
||
// best `summarise_top` at `summarise_min` or more a summary.
|
||
const DEFAULT_LIMITS = { extract_top: 500, extract_min: 0.55, summarise_top: 30, summarise_min: 0.65 };
|
||
const NEW = "new";
|
||
// Europe as the starter agents in config.example.yaml spell it: the EEA,
|
||
// the UK and Switzerland, and EU for a role open anywhere in Europe.
|
||
const EUROPE = ["AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR",
|
||
"HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE",
|
||
"IS", "LI", "NO", "GB", "CH", "EU"];
|
||
const FIELDS = ["place", "country", "remote", "seniority", "function", "salary_min",
|
||
"currency", "permit", "languages", "company", "title"];
|
||
const MODES = [["require", "must"], ["any", "one of"], ["prefer", "prefer"], ["exclude", "not"]];
|
||
const HYBRID_WEIGHT = 0.05;
|
||
|
||
/** @type {object[]} every agent, as the server lists them */
|
||
let agents = [];
|
||
/** @type {Object<string, boolean>} whether extract and summarise run, from
|
||
* `/api/stages`; empty when that did not answer, and then a card says
|
||
* nothing about them */
|
||
let stageOn = {};
|
||
/** @type {number | "new" | null} the card in edit mode: an agent's id, NEW
|
||
* for the blank one on top, null for none */
|
||
let editing = null;
|
||
/** @type {HTMLElement | null} that card, kept across renders so a switch
|
||
* flipped on another card does not wipe what is being typed */
|
||
let editor = null;
|
||
/** @type {Map<number, HTMLElement>} each card's status line, kept across
|
||
* renders for the same reason: a "Scoring…" outlives the card it is on */
|
||
const statuses = new Map();
|
||
|
||
function newestFirst(rows) {
|
||
return [...rows].sort((a, b) => b.id - a.id);
|
||
}
|
||
|
||
// What the Roles tab and the company list use when no agent is picked: the
|
||
// enabled one with the lowest id, else the lowest id (`Store.default_agent`).
|
||
function defaultAgent() {
|
||
const byId = [...agents].sort((a, b) => a.id - b.id);
|
||
return byId.find((a) => a.enabled) || byId[0] || null;
|
||
}
|
||
|
||
function el(tag, className, text) {
|
||
const node = document.createElement(tag);
|
||
if (className) node.className = className;
|
||
if (text !== undefined) node.textContent = text;
|
||
return node;
|
||
}
|
||
|
||
function link(href, text) {
|
||
const a = el("a", "", text);
|
||
a.href = href;
|
||
return a;
|
||
}
|
||
|
||
function linky(text) {
|
||
const button = el("button", "linky", text);
|
||
button.type = "button";
|
||
return button;
|
||
}
|
||
|
||
let regionNames = null;
|
||
try {
|
||
regionNames = new Intl.DisplayNames(["en"], { type: "region" });
|
||
} catch (err) {
|
||
regionNames = null;
|
||
}
|
||
|
||
// A country code in words, the code itself where the browser has no name.
|
||
function countryName(code) {
|
||
if (code === "EU") return "anywhere in Europe";
|
||
try {
|
||
return (regionNames && regionNames.of(code)) || code;
|
||
} catch (err) {
|
||
return code;
|
||
}
|
||
}
|
||
|
||
// The countries Where offers, by name: Europe's, without EU, which is not
|
||
// a country but "open anywhere in Europe" and is said by Remote.
|
||
const COUNTRIES = EUROPE.filter((c) => c !== "EU")
|
||
.map((c) => [c, countryName(c)])
|
||
.sort((a, b) => a[1].localeCompare(b[1]));
|
||
|
||
// "a, b or c": the values of one line.
|
||
function orList(items) {
|
||
return items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} or ${items[items.length - 1]}`;
|
||
}
|
||
|
||
// A town without its accents, lower case: "Malmo" is "Malmö" spelt for a
|
||
// board that writes ASCII, one town with two spellings.
|
||
function fold(text) {
|
||
return String(text).normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
|
||
}
|
||
|
||
// The towns, one spelling each: the first of those that fold alike.
|
||
function towns(values) {
|
||
const seen = new Set();
|
||
return values.map(String).filter((v) => !seen.has(fold(v)) && seen.add(fold(v)));
|
||
}
|
||
|
||
// Until the backend returns `prompts`: an intent is one prompt named after its agent.
|
||
function promptsOf(row) {
|
||
if (row.prompts) return row.prompts;
|
||
const intent = (row.intent || "").trim();
|
||
return intent ? [{ name: row.name, text: row.intent }] : [];
|
||
}
|
||
|
||
function statusOf(id) {
|
||
if (!statuses.has(id)) {
|
||
const line = el("p", "count agent-status");
|
||
line.setAttribute("role", "status");
|
||
statuses.set(id, line);
|
||
}
|
||
return statuses.get(id);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- a card
|
||
|
||
// A switch with its state in words: a bare checkbox did not say what it
|
||
// switched. Switching one on scores it, since the pulls it sat out left it
|
||
// with no scores or stale ones.
|
||
function onSwitch(row) {
|
||
const label = el("label", "switch");
|
||
label.title = "On: scored with every pull and offered in the order menu on Roles.";
|
||
const box = el("input");
|
||
box.type = "checkbox";
|
||
box.setAttribute("role", "switch");
|
||
box.checked = Boolean(row.enabled);
|
||
box.setAttribute("aria-label", row.name);
|
||
const track = el("span", "switch-track");
|
||
track.setAttribute("aria-hidden", "true");
|
||
label.append(box, track, el("span", "switch-label", row.enabled ? "On" : "Off"));
|
||
box.addEventListener("change", async () => {
|
||
box.disabled = true;
|
||
try {
|
||
const saved = await api("/api/agents", {
|
||
method: "POST", body: Object.assign({}, row, { enabled: box.checked }),
|
||
});
|
||
Object.assign(row, saved);
|
||
} catch (err) {
|
||
box.checked = !box.checked;
|
||
box.disabled = false;
|
||
return;
|
||
}
|
||
render();
|
||
if (row.enabled) rescore(statusOf(row.id), row, "Switched on");
|
||
else statusOf(row.id).textContent = "Off: not scored, and not offered on Roles.";
|
||
});
|
||
return label;
|
||
}
|
||
|
||
function weightsLine(row) {
|
||
const w = Object.assign({}, DEFAULT_WEIGHTS, row.weights);
|
||
return `fit ${w.fit} · newness ${w.recency} · companies ${w.affinity} · liked ${w.taste}`;
|
||
}
|
||
|
||
// One gate as a phrase: "in Denmark or Sweden", "remote", "with seniority
|
||
// senior, staff". Europe, whole, is one word rather than 33 countries.
|
||
function phrase(gate) {
|
||
const values = gate.values.map(String);
|
||
if (gate.field === "country") {
|
||
const europe = EUROPE.every((c) => values.includes(c));
|
||
const rest = values.filter((v) => !(europe && EUROPE.includes(v))).map(countryName);
|
||
return `in ${orList(europe ? ["Europe", ...rest] : rest)}`;
|
||
}
|
||
if (gate.field === "place") return `in ${orList(towns(values))}`;
|
||
if (gate.field === "remote") return orList(values);
|
||
if (gate.field === "company") return `at ${orList(values)}`;
|
||
if (gate.field === "salary_min") return `paying at least ${values[0]}`;
|
||
return `with ${gate.field.replace("_", " ")} ${values.join(", ")}`;
|
||
}
|
||
|
||
// The Where block in words, one sentence of the lines a role may match,
|
||
// with the one-of rows among them since they are the same group: "Keeps
|
||
// roles anywhere in Denmark, in Malmö, Lund or Helsingborg, or remote within
|
||
// Europe, and leaves out the rest." The lines add up, which the first
|
||
// wording ("Roles in ...") left the owner to guess.
|
||
function whereSentence(where, others) {
|
||
const parts = [];
|
||
if (where.countries) parts.push(`anywhere ${phrase(where.countries)}`);
|
||
if (where.places) parts.push(phrase(where.places));
|
||
if (where.remote) parts.push(where.europe ? "remote within Europe" : "remote");
|
||
parts.push(...others.map(phrase));
|
||
if (!parts.length) return "";
|
||
const list = parts.length < 2 ? parts[0] : `${parts.slice(0, -1).join(", ")}, or ${parts[parts.length - 1]}`;
|
||
return `Keeps roles ${list}, and leaves out the rest.`;
|
||
}
|
||
|
||
// The gates in words: where a role may be, then what it must meet, then
|
||
// what lifts it. "Keeps roles anywhere in Denmark, or remote within Europe,
|
||
// and leaves out the rest. Only roles with seniority senior. Prefers
|
||
// hybrid."
|
||
function rulesLine(gates) {
|
||
const { where, rest } = distribute(gates);
|
||
const of = (mode) => rest.filter((g) => g.mode === mode);
|
||
const must = of("require").map(phrase);
|
||
const prefer = of("prefer").map((g) => phrase(g).replace(/^with /, ""));
|
||
if (where.hybrid) prefer.unshift("hybrid");
|
||
const not = of("exclude").map(phrase);
|
||
const sentences = [];
|
||
const any = whereSentence(where, of("any"));
|
||
if (any) sentences.push(any);
|
||
if (must.length) sentences.push(`Only roles ${must.join(" and ")}.`);
|
||
if (prefer.length) sentences.push(`Prefers ${prefer.join("; ")}.`);
|
||
if (where.titles) sentences.push(`Leaves out titles with ${orList(where.titles.values.map((t) => `“${t}”`))}.`);
|
||
if (not.length) sentences.push(`Leaves out roles ${not.join(" or ")}.`);
|
||
return sentences.join(" ");
|
||
}
|
||
|
||
// What the model reads after a pull, one clause per stage. A stage that is
|
||
// off says so, with a link to its switch under Runs: the numbers are only
|
||
// what it would read once it is on.
|
||
function limitsLine(row) {
|
||
const l = Object.assign({}, DEFAULT_LIMITS, row.limits);
|
||
const p = el("p", "agent-limits");
|
||
const clauses = [
|
||
["extract", `reads ${l.extract_top} at ${l.extract_min}`, `${l.extract_top} at ${l.extract_min}`],
|
||
["summarise", `summarises ${l.summarise_top} at ${l.summarise_min}`, `${l.summarise_top} at ${l.summarise_min}`],
|
||
];
|
||
clauses.forEach(([name, on, would], i) => {
|
||
if (i) p.append(" · ");
|
||
if (stageOn[name] === false) {
|
||
const off = link("/settings/sources#stages", `${name} is off`);
|
||
off.title = "Switch it on under Runs, What the model reads.";
|
||
p.append(off, ` (${would})`);
|
||
} else {
|
||
p.append(on);
|
||
}
|
||
});
|
||
return p;
|
||
}
|
||
|
||
function card(row, fallback) {
|
||
const div = el("article", "agent-card");
|
||
if (!row.enabled) div.dataset.off = "true";
|
||
|
||
const head = el("div", "agent-card-head");
|
||
head.appendChild(el("h2", "agent-name", row.name));
|
||
if (fallback) {
|
||
const badge = el("span", "badge", "default");
|
||
badge.title = "What Roles and the company list use when no agent is picked.";
|
||
head.appendChild(badge);
|
||
}
|
||
head.appendChild(onSwitch(row));
|
||
div.appendChild(head);
|
||
|
||
const prompts = promptsOf(row).filter((p) => p.text.trim());
|
||
if (!prompts.length) {
|
||
div.appendChild(el("p", "agent-intent empty", "Nothing described yet, so fit has nothing to measure against. Edit says what this agent looks for."));
|
||
}
|
||
for (const prompt of prompts) {
|
||
// A lone prompt named after its agent, as a migrated intent is, says its name once.
|
||
if (prompts.length > 1 || prompt.name !== row.name) {
|
||
div.appendChild(el("h3", "agent-prompt-name", prompt.name));
|
||
}
|
||
div.appendChild(el("p", "agent-intent", prompt.text.trim()));
|
||
}
|
||
const rules = rulesLine(row.gates || []);
|
||
if (rules) div.appendChild(el("p", "agent-rules", rules));
|
||
div.appendChild(el("p", "agent-weights", weightsLine(row)));
|
||
div.appendChild(limitsLine(row));
|
||
div.appendChild(termsLine(row));
|
||
|
||
const actions = el("div", "agent-card-actions");
|
||
const edit = el("button", "secondary", "Edit");
|
||
edit.type = "button";
|
||
edit.addEventListener("click", () => open(row));
|
||
actions.appendChild(edit);
|
||
// An agent that is off is not in the order menu, so Roles would open in
|
||
// another agent's order: the link is only there while this one is on.
|
||
if (row.enabled) actions.appendChild(link(`/?agent=${row.id}`, "Open Roles as this agent →"));
|
||
const remove = el("button", "linky", "Delete");
|
||
remove.type = "button";
|
||
remove.addEventListener("click", () => removeAgent(row));
|
||
actions.appendChild(remove);
|
||
div.appendChild(actions);
|
||
div.appendChild(statusOf(row.id));
|
||
return div;
|
||
}
|
||
|
||
// ---------------------------------------------------------------- the form
|
||
|
||
// Tell the form something changed that no field typed: a chip or a row
|
||
// added or removed. It marks the form dirty and redraws the gates view.
|
||
function changed(node) {
|
||
node.dispatchEvent(new Event("input", { bubbles: true }));
|
||
}
|
||
|
||
// A list of values as chips, the rail's tags with news's filter pills' ×,
|
||
// then `entry`, the control that adds to it. `label` is a value in words.
|
||
// `group` puts values that are one thing on one chip, whose × drops them
|
||
// all. `drawn` runs after each redraw, for an entry that lists what is left.
|
||
function chipList(values, entry, { label = String, group = (v) => v, drawn = () => {} } = {}) {
|
||
const list = values.map(String);
|
||
const box = el("div", "chips");
|
||
|
||
function chip(value) {
|
||
const same = list.filter((v) => group(v) === group(value));
|
||
const text = label(value);
|
||
const button = el("button", "tag", `${text} `);
|
||
button.type = "button";
|
||
button.title = same.length > 1 ? `Also matches ${same.slice(1).join(", ")}` : value;
|
||
button.setAttribute("aria-label", `Remove ${text}`);
|
||
const x = el("span", "", "×");
|
||
x.setAttribute("aria-hidden", "true");
|
||
button.appendChild(x);
|
||
button.addEventListener("click", () => {
|
||
list.splice(0, list.length, ...list.filter((v) => group(v) !== group(value)));
|
||
draw();
|
||
changed(box);
|
||
entry.focus();
|
||
});
|
||
return button;
|
||
}
|
||
|
||
function draw() {
|
||
const firsts = list.filter((v, i) => list.findIndex((w) => group(w) === group(v)) === i);
|
||
box.replaceChildren(...firsts.map(chip), entry);
|
||
drawn(list);
|
||
}
|
||
|
||
function add(more) {
|
||
const before = list.length;
|
||
for (const value of more) if (!list.includes(value)) list.push(value);
|
||
draw();
|
||
if (list.length !== before) changed(box);
|
||
}
|
||
|
||
draw();
|
||
return { node: box, list, add };
|
||
}
|
||
|
||
// Countries as chips by name, added from a select of Europe's by name;
|
||
// the select leaves out the ones already chips.
|
||
function countryInput(values) {
|
||
const pick = el("select");
|
||
pick.setAttribute("aria-label", "Add a country");
|
||
const offer = (list) => {
|
||
const blank = el("option", "", "Add a country");
|
||
blank.value = "";
|
||
const left = COUNTRIES.filter(([code]) => !list.includes(code)).map(([code, name]) => {
|
||
const option = el("option", "", name);
|
||
option.value = code;
|
||
return option;
|
||
});
|
||
pick.replaceChildren(blank, ...left);
|
||
pick.value = "";
|
||
};
|
||
const chips = chipList(values, pick, { label: countryName, drawn: offer });
|
||
pick.addEventListener("change", () => { if (pick.value) chips.add([pick.value]); });
|
||
return { node: chips.node, values: () => [...chips.list] };
|
||
}
|
||
|
||
// Words as chips of free text, added on Enter or a comma, and one chip for
|
||
// the spellings that fold alike. What is typed but not added yet counts, so
|
||
// Save does not drop it. Towns and fetch terms both.
|
||
function wordInput(values, prompt) {
|
||
const input = el("input");
|
||
input.type = "text";
|
||
input.spellcheck = false;
|
||
input.placeholder = prompt;
|
||
input.setAttribute("aria-label", prompt);
|
||
const split = (text) => text.split(",").map((v) => v.trim()).filter(Boolean);
|
||
const chips = chipList(values, input, { group: fold });
|
||
const take = () => {
|
||
const typed = split(input.value);
|
||
input.value = "";
|
||
chips.add(typed);
|
||
};
|
||
input.addEventListener("keydown", (event) => {
|
||
if (event.key !== "Enter" && event.key !== ",") return;
|
||
event.preventDefault();
|
||
take();
|
||
});
|
||
input.addEventListener("blur", take);
|
||
return {
|
||
node: chips.node,
|
||
values: () => [...chips.list, ...split(input.value).filter((v) => !chips.list.includes(v))],
|
||
};
|
||
}
|
||
|
||
// The fetch terms on a card: the words, or that big boards send every role.
|
||
function termsLine(row) {
|
||
const terms = row.fetch_terms || [];
|
||
return el("p", "agent-terms", terms.length
|
||
? `Big boards read across Europe send only roles matching ${orList(terms.map((t) => `“${t}”`))}.`
|
||
: "Big boards send every role: no fetch terms.");
|
||
}
|
||
|
||
// A prompt as a row: its name and Remove on a line, its text under them.
|
||
function promptRow(prompt, remove) {
|
||
const row = el("div", "prompt-row");
|
||
const name = el("input");
|
||
name.type = "text";
|
||
name.placeholder = "AI and data leadership";
|
||
name.value = prompt.name;
|
||
name.setAttribute("aria-label", "Prompt name");
|
||
const text = el("textarea");
|
||
text.rows = 5;
|
||
text.placeholder = "VP, Head or Director of Data and AI. Owns the data platform and the ML teams, sets the roadmap with the business, in a product company.";
|
||
text.value = prompt.text;
|
||
text.setAttribute("aria-label", "What this prompt looks for");
|
||
const drop = linky("Remove");
|
||
drop.addEventListener("click", () => remove(row));
|
||
row.append(name, drop, text);
|
||
return { node: row, read: () => ({ name: name.value.trim(), text: text.value }) };
|
||
}
|
||
|
||
function select(options, value, label) {
|
||
const box = el("select");
|
||
for (const [key, text] of options) {
|
||
const option = el("option", "", text);
|
||
option.value = key;
|
||
box.appendChild(option);
|
||
}
|
||
box.value = value;
|
||
box.setAttribute("aria-label", label);
|
||
return box;
|
||
}
|
||
|
||
// A gate as a row: field, mode, values, the weight while it is prefer, and
|
||
// Remove. Values untouched since the load are sent as they came, so a
|
||
// value with a comma in it survives a save.
|
||
function ruleRow(gate, remove) {
|
||
const row = el("div", "rule-row");
|
||
const field = select(FIELDS.map((f) => [f, f.replace("_", " ")]), gate.field, "Field");
|
||
const mode = select(MODES, gate.mode, "Mode");
|
||
const values = el("input");
|
||
values.type = "text";
|
||
values.required = true;
|
||
values.spellcheck = false;
|
||
values.placeholder = "senior, staff";
|
||
values.value = gate.values.join(", ");
|
||
values.setAttribute("aria-label", "Values, separated by commas");
|
||
const loaded = values.value;
|
||
const weight = el("input");
|
||
weight.type = "number";
|
||
weight.min = "0";
|
||
weight.step = "0.05";
|
||
weight.value = gate.mode === "prefer" && gate.weight !== undefined ? gate.weight : HYBRID_WEIGHT;
|
||
weight.setAttribute("aria-label", "Weight");
|
||
weight.title = "What a role that meets it gains.";
|
||
// A must or one-of gate carries a weight nobody reads; kept as it came.
|
||
const kept = gate.mode === "prefer" ? undefined : gate.weight;
|
||
const drop = linky("Remove");
|
||
drop.addEventListener("click", () => remove(row));
|
||
const shown = () => { weight.hidden = mode.value !== "prefer"; };
|
||
mode.addEventListener("change", shown);
|
||
shown();
|
||
row.append(field, mode, values, weight, drop);
|
||
|
||
function read() {
|
||
const parts = values.value === loaded
|
||
? gate.values
|
||
: values.value.split(",").map((v) => v.trim()).filter(Boolean)
|
||
.map((v) => (field.value === "salary_min" ? Number(v) : v));
|
||
const out = { field: field.value, values: parts, mode: mode.value };
|
||
if (mode.value === "prefer") out.weight = Number(weight.value);
|
||
else if (kept !== undefined && kept !== 1) out.weight = kept;
|
||
return out;
|
||
}
|
||
return { node: row, read };
|
||
}
|
||
|
||
// Share out an agent's gates between the Where block and Other rules. Each
|
||
// Where line takes the first gate it can say whole; the rest are rows. A
|
||
// must or one-of gate with a weight other than the default stays a row,
|
||
// since Where would drop it. Remote within Europe is a must on country
|
||
// that is Europe and the countries line exactly, and only with Remote
|
||
// ticked; any other must on country is a row, and Remote reads anywhere.
|
||
function distribute(gates) {
|
||
const where = { countries: null, places: null, remote: null, europe: null, hybrid: null, titles: null };
|
||
const rest = [];
|
||
const musts = [];
|
||
const plain = (g) => g.weight === undefined || g.weight === 1;
|
||
const only = (g, value) => g.values.length === 1 && g.values[0] === value;
|
||
for (const g of gates) {
|
||
let slot = null;
|
||
if (g.field === "country" && g.mode === "require" && plain(g)) {
|
||
musts.push(g);
|
||
continue;
|
||
}
|
||
if (g.field === "country" && g.mode === "any" && plain(g)) slot = "countries";
|
||
else if (g.field === "remote" && g.mode === "any" && plain(g) && only(g, "remote")) slot = "remote";
|
||
else if (g.field === "place" && g.mode === "any" && plain(g)) slot = "places";
|
||
else if (g.field === "remote" && g.mode === "prefer" && only(g, "hybrid")) slot = "hybrid";
|
||
else if (g.field === "title" && g.mode === "exclude" && plain(g)) slot = "titles";
|
||
if (slot && !where[slot]) where[slot] = g;
|
||
else rest.push(g);
|
||
}
|
||
const within = new Set(europeWith(where.countries ? where.countries.values : []));
|
||
for (const g of musts) {
|
||
const same = g.values.length === within.size && g.values.every((v) => within.has(v));
|
||
if (where.remote && !where.europe && same) where.europe = g;
|
||
else rest.push(g);
|
||
}
|
||
return { where, rest };
|
||
}
|
||
|
||
// What Remote within Europe sends: Europe, and the countries line too,
|
||
// since the must holds for every role, not only the remote ones.
|
||
function europeWith(countries) {
|
||
return [...EUROPE, ...countries.filter((c) => !EUROPE.includes(c))];
|
||
}
|
||
|
||
function form(row) {
|
||
const div = el("article", "agent-card editing");
|
||
const f = $("#agent-form-template").content.querySelector("form").cloneNode(true);
|
||
const weights = Object.assign({}, DEFAULT_WEIGHTS, row ? row.weights : {});
|
||
const limits = Object.assign({}, DEFAULT_LIMITS, row ? row.limits : {});
|
||
$("#agent-form-title", f).textContent = row ? `Edit ${row.name}` : "New agent";
|
||
$("#a-name", f).value = row ? row.name : "";
|
||
|
||
// A new agent, or one with none, starts with one empty prompt.
|
||
const prompts = [];
|
||
const dropPrompt = (node) => {
|
||
prompts.splice(prompts.findIndex((p) => p.node === node), 1);
|
||
node.remove();
|
||
changed(f);
|
||
};
|
||
const addPrompt = (prompt) => {
|
||
const entry = promptRow(prompt, dropPrompt);
|
||
prompts.push(entry);
|
||
$("#a-prompts", f).appendChild(entry.node);
|
||
return entry;
|
||
};
|
||
const loaded = row ? promptsOf(row) : [];
|
||
(loaded.length ? loaded : [{ name: "", text: "" }]).forEach(addPrompt);
|
||
$("#a-add-prompt", f).addEventListener("click", () => {
|
||
$("input", addPrompt({ name: "", text: "" }).node).focus();
|
||
changed(f);
|
||
});
|
||
|
||
const { where, rest } = distribute(row ? row.gates : []);
|
||
const countries = countryInput(where.countries ? where.countries.values : []);
|
||
const places = wordInput(where.places ? where.places.values : [], "Add a town");
|
||
const titles = wordInput(where.titles ? where.titles.values : [], "account executive");
|
||
const terms = wordInput(row ? row.fetch_terms || [] : [], "machine learning, data science");
|
||
$("#a-titles", f).replaceWith(titles.node);
|
||
$("#a-terms", f).replaceWith(terms.node);
|
||
$("#a-countries", f).replaceWith(countries.node);
|
||
$("#a-towns", f).replaceWith(places.node);
|
||
const remote = $("#a-remote", f);
|
||
const scope = $("#a-remote-scope", f);
|
||
remote.checked = Boolean(where.remote);
|
||
// Anywhere when a must on country is a row, so ticking Remote does not
|
||
// stack a second one on it; else Europe, the usual answer.
|
||
const mustRow = rest.some((g) => g.field === "country" && g.mode === "require");
|
||
scope.value = where.europe || !(where.remote || mustRow) ? "europe" : "anywhere";
|
||
const offerScope = () => { scope.disabled = !remote.checked; };
|
||
offerScope();
|
||
// The hybrid weight shows only when it is not the default; either way it
|
||
// is sent back as it came.
|
||
const hybridWeight = where.hybrid && where.hybrid.weight !== undefined ? where.hybrid.weight : HYBRID_WEIGHT;
|
||
$("#a-hybrid", f).checked = Boolean(where.hybrid);
|
||
$("#a-hybrid-weight", f).value = hybridWeight;
|
||
$("#a-hybrid-weight-line", f).hidden = hybridWeight === HYBRID_WEIGHT;
|
||
$("details.advanced", f).open = rest.length > 0;
|
||
|
||
const rules = [];
|
||
const dropRule = (node) => {
|
||
rules.splice(rules.findIndex((r) => r.node === node), 1);
|
||
node.remove();
|
||
changed(f);
|
||
};
|
||
const addRule = (gate) => {
|
||
const entry = ruleRow(gate, dropRule);
|
||
rules.push(entry);
|
||
$("#a-rules", f).appendChild(entry.node);
|
||
return entry;
|
||
};
|
||
rest.forEach(addRule);
|
||
$("#a-add-rule", f).addEventListener("click", () => {
|
||
$("select", addRule({ field: "seniority", values: [], mode: "prefer", weight: HYBRID_WEIGHT }).node).focus();
|
||
changed(f);
|
||
});
|
||
|
||
// The gates the Where block says, in the order the starter agents have
|
||
// them: the must on country, the lines, then hybrid; and the titles left
|
||
// out, the block under it.
|
||
function whereGates() {
|
||
const out = [];
|
||
const within = countries.values();
|
||
const towns = places.values();
|
||
if (remote.checked && scope.value === "europe") {
|
||
out.push({ field: "country", values: europeWith(within), mode: "require" });
|
||
}
|
||
if (within.length) out.push({ field: "country", values: within, mode: "any" });
|
||
if (remote.checked) out.push({ field: "remote", values: ["remote"], mode: "any" });
|
||
if (towns.length) out.push({ field: "place", values: towns, mode: "any" });
|
||
if ($("#a-hybrid", f).checked) {
|
||
out.push({ field: "remote", values: ["hybrid"], mode: "prefer", weight: Number($("#a-hybrid-weight", f).value) });
|
||
}
|
||
const left = titles.values();
|
||
if (left.length) out.push({ field: "title", values: left, mode: "exclude" });
|
||
return out;
|
||
}
|
||
// The gates Save sends: the Where block's, then the rows. The sentence
|
||
// under Where says them all, as the card will, rows included.
|
||
const gates = () => whereGates().concat(rules.map((r) => r.read()));
|
||
const view = () => {
|
||
offerScope();
|
||
$("#a-gates", f).value = JSON.stringify(gates(), null, 2);
|
||
$("#a-where-sum", f).textContent = rulesLine(gates()) || "Keeps roles anywhere.";
|
||
};
|
||
view();
|
||
|
||
$("#a-fit", f).value = weights.fit;
|
||
$("#a-recency", f).value = weights.recency;
|
||
$("#a-affinity", f).value = weights.affinity;
|
||
$("#a-taste", f).value = weights.taste;
|
||
$("#a-extract-top", f).value = limits.extract_top;
|
||
$("#a-extract-min", f).value = limits.extract_min;
|
||
$("#a-summarise-top", f).value = limits.summarise_top;
|
||
$("#a-summarise-min", f).value = limits.summarise_min;
|
||
$("#a-delete", f).hidden = !row;
|
||
f.addEventListener("input", () => { f.dataset.dirty = "true"; view(); });
|
||
f.addEventListener("change", view);
|
||
f.addEventListener("submit", (event) => save(event, row, () => prompts.map((p) => p.read()), gates, terms.values));
|
||
$("#a-cancel", f).addEventListener("click", () => { close(); render(); });
|
||
$("#a-delete", f).addEventListener("click", () => row && removeAgent(row));
|
||
div.appendChild(f);
|
||
if (row) div.appendChild(statusOf(row.id));
|
||
return div;
|
||
}
|
||
|
||
// Put the open form away, asking first if it holds changes. False when the
|
||
// answer was to keep them.
|
||
function close() {
|
||
const f = editor && $("form", editor);
|
||
if (f && f.dataset.dirty && !window.confirm("Discard the changes to this agent?")) {
|
||
return false;
|
||
}
|
||
editing = null;
|
||
editor = null;
|
||
return true;
|
||
}
|
||
|
||
// Edit `row` in its own card, or a new agent in a blank card on top.
|
||
function open(row) {
|
||
const target = row ? row.id : NEW;
|
||
if (editing !== target) {
|
||
if (!close()) return;
|
||
editing = target;
|
||
editor = form(row);
|
||
render();
|
||
}
|
||
editor.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
||
$("#a-name", editor).focus({ preventScroll: true });
|
||
}
|
||
|
||
function render() {
|
||
const cards = [];
|
||
if (editing === NEW) cards.push(editor);
|
||
const fallback = defaultAgent();
|
||
for (const row of newestFirst(agents)) {
|
||
cards.push(editing === row.id ? editor : card(row, agents.length > 1 && row === fallback));
|
||
}
|
||
$("#agents-list").replaceChildren(...cards);
|
||
$("#agents-count").textContent = agents.length
|
||
? count(agents.length, "search agent")
|
||
: "No search agents yet. New agent describes one.";
|
||
}
|
||
|
||
// `readPrompts`, `readGates` and `readTerms` are the form's rows and chips
|
||
// as the API takes them.
|
||
// A prompt with neither name nor text is an empty row, left out.
|
||
async function save(event, row, readPrompts, readGates, readTerms) {
|
||
event.preventDefault();
|
||
const f = event.target;
|
||
const prompts = readPrompts().filter((p) => p.name || p.text.trim());
|
||
if (prompts.some((p) => !p.name)) {
|
||
window.toast.error("Every prompt needs a name.");
|
||
return;
|
||
}
|
||
const gates = readGates();
|
||
const body = {
|
||
name: $("#a-name", f).value.trim(),
|
||
prompts,
|
||
gates,
|
||
weights: {
|
||
fit: Number($("#a-fit", f).value),
|
||
recency: Number($("#a-recency", f).value),
|
||
affinity: Number($("#a-affinity", f).value),
|
||
taste: Number($("#a-taste", f).value),
|
||
},
|
||
limits: {
|
||
extract_top: Number($("#a-extract-top", f).value),
|
||
extract_min: Number($("#a-extract-min", f).value),
|
||
summarise_top: Number($("#a-summarise-top", f).value),
|
||
summarise_min: Number($("#a-summarise-min", f).value),
|
||
},
|
||
fetch_terms: readTerms(),
|
||
// Saving an agent means it is wanted, so a new one starts on; the
|
||
// card's switch is where an existing one is switched.
|
||
enabled: row ? row.enabled : true,
|
||
};
|
||
if (row) body.id = row.id;
|
||
const button = $("button[type=submit]", f);
|
||
button.disabled = true;
|
||
let saved;
|
||
try {
|
||
saved = await api("/api/agents", { method: "POST", body });
|
||
await load();
|
||
} catch (err) {
|
||
button.disabled = false;
|
||
return;
|
||
}
|
||
// The newest is first, so a new agent's card stays where its form was.
|
||
editing = null;
|
||
editor = null;
|
||
render();
|
||
const agent = agents.find((a) => a.id === saved.id) || saved;
|
||
await rescore(statusOf(agent.id), agent, "Saved");
|
||
}
|
||
|
||
async function removeAgent(row) {
|
||
if (!window.confirm(`Delete ${row.name}? Its votes and liked companies go with it.`)) {
|
||
return;
|
||
}
|
||
try {
|
||
await api(`/api/agents/${row.id}`, { method: "DELETE" });
|
||
} catch (err) {
|
||
return;
|
||
}
|
||
agents = agents.filter((a) => a.id !== row.id);
|
||
statuses.delete(row.id);
|
||
if (editing === row.id) {
|
||
editing = null;
|
||
editor = null;
|
||
}
|
||
render();
|
||
}
|
||
|
||
// Ask for a `score` and wait for the job the server answers with, so
|
||
// "scored" means the Roles tab already orders by what was saved. While a
|
||
// score is running that is a follow-up queued after it, since the running
|
||
// one read the agent before the save. `said` is what happened first.
|
||
async function rescore(status, agent, said) {
|
||
const runs = () => link("/settings/sources#runs", "follow it under Runs");
|
||
status.replaceChildren(`${said}. Scoring every open role; `, runs(), ".");
|
||
let job;
|
||
try {
|
||
job = await api("/api/score", { method: "POST" });
|
||
} catch (err) {
|
||
status.textContent = `${said}, but scoring did not start.`;
|
||
return;
|
||
}
|
||
for (let i = 0; i < 300; i += 1) {
|
||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||
let snapshot;
|
||
try {
|
||
snapshot = await api("/api/jobs");
|
||
} catch (err) {
|
||
return;
|
||
}
|
||
const busy = [...snapshot.running, ...snapshot.queued].some((j) => j.id === job.id);
|
||
if (busy) continue;
|
||
const done = snapshot.recent.find((j) => j.id === job.id);
|
||
if (done && done.state !== "done") {
|
||
status.textContent = `${said}. Scoring ${done.state}.`;
|
||
if (done.error) window.toast.error(`Scoring ${done.state}: ${done.error}`);
|
||
return;
|
||
}
|
||
status.replaceChildren(`${said} and scored. `,
|
||
link(`/?agent=${agent.id}`, `Open Roles as ${agent.name} →`));
|
||
return;
|
||
}
|
||
status.replaceChildren(`${said}. Scoring is still running; `, runs(), ".");
|
||
}
|
||
|
||
// -------------------------------------------------------------------- init
|
||
|
||
async function load() {
|
||
agents = await api("/api/agents");
|
||
// A card is only worded by it, so a failure leaves the cards as they were.
|
||
try {
|
||
stageOn = Object.fromEntries((await api("/api/stages")).map((s) => [s.name, s.on]));
|
||
} catch (err) {
|
||
stageOn = {};
|
||
}
|
||
}
|
||
|
||
document.addEventListener("DOMContentLoaded", async () => {
|
||
if (!$("#agents-list")) return;
|
||
$("#a-new").addEventListener("click", () => open(null));
|
||
try {
|
||
await load();
|
||
} catch (err) {
|
||
return;
|
||
}
|
||
// With none yet, the page is the form for the first one.
|
||
if (!agents.length) {
|
||
editing = NEW;
|
||
editor = form(null);
|
||
}
|
||
render();
|
||
});
|
||
})();
|