Files

968 lines
40 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* The Search agents page: what the order What I'm looking for 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 prompt closeness is
* measured against the one a role is closest to; the weights only share out the terms.
* The form edits the prompts as rows, and the fetch gate in four parts, in the
* ADR's order: the world (the scope select), the location (a short list of
* lines a role passes by matching any one of: countries, towns, remote), the
* role exclusion (the titles to leave out) and the role fetch (the fetch
* terms), and nothing else: seniority, pay and the like are filters on Roles.
* A gate is a field, values and a mode (must, one of, not), with no weight.
* A stored gate the four parts cannot say, which only the config or the API
* writes, is named in a note under the fetch gate and sent back as it came,
* so a load and a save lose nothing. After the fetch gate come the analytics
* filter (the best N by prompt closeness and the best M by CV closeness, each
* with a minimum level), the want feed score weights (prompt closeness,
* newness, company like, job like), the CV match weights and the size of
* summarise. 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 a big board
* (300 roles or more) whose host takes a query must match before it sends a
* role (app/jobs/reach.py). The card says them in a line of their own, or that
* boards send every role.
*
* The CV fieldset holds what the judge stage reads a role against: the CV as
* text (typed, or read from a .md/.txt file by the browser), the languages it
* states as rows of a code and a level, and the two soft texts, what the
* person likes and what they do not like (the work, the workplace,
* situations), which the judge reads for the career score.
* Every save sends the CV, languages and the two texts, and the card's switch
* re-posts the row as the server gave it, so neither drops them.
*
* 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, remoteHelpers: rh } = window;
const $ = (sel, root = document) => root.querySelector(sel);
const DEFAULT_WEIGHTS = { fit: 0.6, recency: 0.2, affinity: 0.2, taste: 0.2,
cv_skills: 30, cv_experience: 25, cv_career: 30 };
// What the models read after a pull, per agent (`app.models.Limits`): the
// analytics filter is the best `cut_fit_top` roles by prompt closeness at
// `cut_fit_min` or more, then the best `cut_cv_top` by CV closeness at
// `cut_cv_min` or more that the first list leaves out, and every role liked
// or saved: the cut. Fetch text, extract and judge read the cut; summarise
// reads the top `summarise_top` of each feed order, want and match, and the
// roles liked or saved.
const DEFAULT_LIMITS = { cut_fit_top: 500, cut_fit_min: 0.6, cut_cv_top: 150, cut_cv_min: 0.6,
summarise_top: 30 };
// The levels of a language, the order of the server's ladder, and how big a
// CV file the browser reads into the box.
const LEVELS = ["basic", "conversational", "professional", "fluent", "native"];
const MAX_CV_BYTES = 1_000_000;
const NEW = "new";
// Europe as the starter agents spell it (static/remote.js).
const EUROPE = rh.EUROPE;
// A gate's mode in the words of the note on the gates the form keeps.
const MODES = { require: "must", any: "one of", exclude: "not" };
/** @type {object[]} every agent, as the server lists them */
let agents = [];
/** @type {Object<string, boolean>} whether extract, summarise, judge and
* fetch_text 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;
}
let languageNames = null;
try {
languageNames = new Intl.DisplayNames(["en"], { type: "language" });
} catch (err) {
languageNames = 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 picked in the remote line.
const COUNTRIES = EUROPE.filter((c) => c !== "EU")
.map((c) => [c, countryName(c)])
.sort((a, b) => a[1].localeCompare(b[1]));
/** @type {Map<string, string>} the words of the `remote_from` values, by
* value, as `/api/places/labels` says them; a card and a chip fall back to
* `rh.fallbackLabel` until they are in */
const placeNames = new Map();
const placeLabel = (value) => placeNames.get(value) || rh.fallbackLabel(value, countryName);
// The labels of the `remote_from` tokens in `gates` that are not known yet.
// A failure is toasted by `api()` and leaves the fallbacks.
async function nameRemote(gates) {
const missing = [...new Set(gates.filter((g) => g.field === "remote_from")
.flatMap((g) => g.values.map(String)))]
.filter((v) => v !== rh.ANYWHERE && !placeNames.has(v));
if (!missing.length) return;
const p = new URLSearchParams();
missing.forEach((t) => p.append("tokens", t));
try {
for (const { token, label } of await api(`/api/places/labels?${p}`)) placeNames.set(token, label);
} catch (err) {
// the fallbacks stand
}
}
// "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 `prompt closeness ${w.fit} · newness ${w.recency} · company like ${w.affinity} · job like ${w.taste}`
+ ` · CV match: skills ${w.cv_skills}, experience ${w.cv_experience}, career ${w.cv_career}`;
}
// 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 === "remote_from") return rh.remoteSentence(values, placeLabel);
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 region in words: "Within Europe", "Within Denmark or
// Sweden", "Everywhere".
function scopeWords(scope) {
if (scope.kind === "everywhere") return "Everywhere";
if (scope.kind === "europe") return "Within Europe";
return `Within ${phrase({ field: "country", values: scope.values }).replace(/^in /, "")}`;
}
// The region and place in words, one sentence led by the region, then the lines a
// role may match, with any other one-of gates among them since they are the
// same group: "Within Europe: keeps roles anywhere in Denmark, in Malmö, Lund or
// Helsingborg, or remote, 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.mode === "scope") parts.push("remote");
if (where.remote.mode === "from" && where.remote.values.length) {
parts.push(rh.remoteSentence(where.remote.values, placeLabel));
}
parts.push(...others.map(phrase));
if (!parts.length) return where.scope.kind === "everywhere" ? "" : `${scopeWords(where.scope)}: keeps every role.`;
const list = parts.length < 2 ? parts[0] : `${parts.slice(0, -1).join(", ")}, or ${parts[parts.length - 1]}`;
return `${scopeWords(where.scope)}: keeps roles ${list}, and leaves out the rest.`;
}
// The gates in words: the region and the places a role may be, then what
// it must meet, then what is left out. "Within Europe: keeps roles anywhere
// in Denmark, or remote, and leaves out the rest. Only roles with seniority
// senior. Leaves out titles with “sales”."
function rulesLine(gates) {
const { where, rest } = rh.distribute(gates);
const of = (mode) => rest.filter((g) => g.mode === mode);
const must = of("require").map(phrase);
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 (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 models read after a pull: the analytics filter's cut, then the
// stages that read it, then summarise's own size. 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. The stage names are those of `/api/stages`.
function limitsLine(row) {
const l = Object.assign({}, DEFAULT_LIMITS, row.limits);
const p = el("p", "agent-limits");
const lists = [];
if (l.cut_fit_top) lists.push(`the best ${l.cut_fit_top} by prompt closeness at ${l.cut_fit_min} or more`);
if (l.cut_cv_top) lists.push(`the best ${l.cut_cv_top} by CV closeness at ${l.cut_cv_min} or more`);
const cut = lists.length ? `${lists.join(", then ")}, and liked and saved roles` : "liked and saved roles only";
p.append(`Analytics filter: ${cut}.`);
const off = (name, would) => {
const a = link("/settings/sources#stages", `${name} is off`);
a.title = "Switch it on under Runs.";
p.append(" · ", a, ` (${would})`);
};
const reads = [["fetch_text", "fetch text"], ["extract", "extract"], ["judge", "judge"]];
const on = reads.filter(([key]) => stageOn[key] !== false).map(([, name]) => name);
if (on.length) {
const said = on.length < 2 ? on[0] : `${on.slice(0, -1).join(", ")} and ${on[on.length - 1]}`;
p.append(` ${said[0].toUpperCase()}${said.slice(1)} ${on.length > 1 ? "read" : "reads"} it`);
}
for (const [key, name] of reads) if (stageOn[key] === false) off(name, "reads the cut");
const summarised = `the top ${l.summarise_top} of each feed order and liked and saved roles`;
if (stageOn.summarise === false) off("summarise", `summarises ${summarised}`);
else p.append(` · summarises ${summarised}`);
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 prompt closeness 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));
div.appendChild(cvLine(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' sentence.
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] };
}
// "Only when open to someone in": the values of a `remote_from` gate as
// chips, picked from the place suggestions that a remote hire can live in:
// countries and regions. `values()` are the gate's values (`country:DK`),
// the chips say them in words.
function remoteInput(values, onChange) {
const root = el("div");
root.id = "a-remote-from";
const chips = window.chipInput(root, {
suggest: async (q) => {
const rows = await api(`/api/suggest/places?${new URLSearchParams({ q })}`);
const picks = [];
for (const s of rows) {
const value = rh.fromSuggestion(s);
if (value !== null) picks.push({ value, label: s.label, hint: s.kind });
}
return picks;
},
onChange: (items) => {
items.forEach((i) => placeNames.set(i.value, i.label));
onChange();
},
placeholder: "Add a country or a region", label: "Remote, open to someone in",
});
chips.set(values.map((v) => ({ value: v, label: placeLabel(v) })));
return { node: root, values: () => chips.values().map((i) => i.value) };
}
// 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
? `Boards of 300 or more roles whose host takes a query send only roles matching ${orList(terms.map((t) => `“${t}”`))}.`
: "Big boards send every role: no fetch terms.");
}
// The CV on a card: whether the judge has one to read roles against, and
// the languages it states, as "da fluent, en native", and whether the
// likes and dislikes are written.
function cvLine(row) {
const langs = row.cv_languages || [];
const said = langs.length ? `Languages: ${langs.map((l) => `${l.language} ${l.level}`).join(", ")}.` : "No languages stated.";
const has = Boolean((row.cv_text || "").trim());
const soft = `Likes ${(row.like_text || "").trim() ? "set" : "not set"}, dislikes ${(row.avoid_text || "").trim() ? "set" : "not set"}.`;
return el("p", "agent-terms", `${has ? "CV set." : "No CV, so roles are not judged against one."} ${said} ${soft}`);
}
// 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 language as a row: a code, a level, Remove. The code is two letters,
// which the server turns into the language; its name is the row's title
// where the browser knows it.
function languageRow(language, remove) {
const row = el("div", "rule-row");
const code = el("input");
code.type = "text";
code.maxLength = 2;
code.spellcheck = false;
code.placeholder = "en";
code.value = language.language;
code.setAttribute("aria-label", "Language code");
const level = select(LEVELS.map((l) => [l, l]), language.level, "Level");
const named = () => {
try {
code.title = (languageNames && languageNames.of(code.value.trim().toLowerCase())) || "";
} catch (err) {
code.title = "";
}
};
code.addEventListener("input", named);
named();
const drop = linky("Remove");
drop.addEventListener("click", () => remove(row));
row.append(code, level, drop);
return { node: row, read: () => ({ language: code.value.trim().toLowerCase(), level: level.value }) };
}
// The gates the fetch gate's four parts say, in the order the starter
// agents have them: the world, the location lines and the titles left out,
// then `kept`, the stored gates the parts cannot say, as they came. `parts`
// holds what the form reads: `scope` (europe, countries, everywhere) and
// its `scoped` countries, the `within` countries, the `towns`, `remote`
// (none, scope, from) and its `from` areas, and the `titles`.
function formGates(parts, kept = []) {
const out = [];
const { scope, scoped, within, towns: lines, remote, from, titles } = parts;
if (scope === "europe") out.push({ field: "country", values: rh.europeWith(within), mode: "require" });
if (scope === "countries" && scoped.length) out.push({ field: "country", values: scoped, mode: "require" });
if (within.length) out.push({ field: "country", values: within, mode: "any" });
if (remote === "scope") out.push({ field: "remote", values: ["remote"], mode: "any" });
if (remote === "from" && from.length) out.push({ field: "remote_from", values: from, mode: "any" });
if (lines.length) out.push({ field: "place", values: lines, mode: "any" });
if (titles.length) out.push({ field: "title", values: titles, mode: "exclude" });
return out.concat(kept);
}
// The note on the gates the form keeps: "The form cannot edit these rules,
// and Save keeps them as stored: must: with seniority senior; not: at Acme."
function keptNote(kept) {
if (!kept.length) return "";
const said = kept.map((g) => `${MODES[g.mode] || g.mode}: ${phrase(g)}`).join("; ");
return `The form cannot edit ${kept.length > 1 ? "these rules" : "this rule"}, and Save keeps `
+ `${kept.length > 1 ? "them" : "it"} as stored: ${said}.`;
}
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);
});
// The CV: its text, the file that can fill it, the languages as rows and
// the two soft texts. All four are always sent, so what is cleared here
// is cleared in the store.
const cvText = $("#a-cv-text", f);
cvText.value = row ? row.cv_text || "" : "";
$("#a-like-text", f).value = row ? row.like_text || "" : "";
$("#a-avoid-text", f).value = row ? row.avoid_text || "" : "";
const languages = [];
const dropLanguage = (node) => {
languages.splice(languages.findIndex((l) => l.node === node), 1);
node.remove();
changed(f);
};
const addLanguage = (language) => {
const entry = languageRow(language, dropLanguage);
languages.push(entry);
$("#a-cv-languages", f).appendChild(entry.node);
return entry;
};
(row ? row.cv_languages || [] : []).forEach(addLanguage);
$("#a-add-language", f).addEventListener("click", () => {
$("input", addLanguage({ language: "", level: "professional" }).node).focus();
changed(f);
});
$("#a-cv-file", f).addEventListener("change", (event) => readCvFile(event.target, cvText, f));
$("#a-suggest-languages", f).addEventListener("click", async (event) => {
const button = event.currentTarget;
if (!cvText.value.trim()) {
window.toast.error("Paste a CV first.");
return;
}
button.disabled = true;
try {
const { languages: found } = await api("/api/agents/cv-languages", {
method: "POST", body: { cv_text: cvText.value },
});
languages.splice(0).forEach((l) => l.node.remove());
found.forEach(addLanguage);
changed(f);
if (!found.length) window.toast.info("The CV states no language.");
} catch (err) {
// `api()` toasted the server's sentence; the rows stay as they were.
} finally {
button.disabled = false;
}
});
const { where, rest } = rh.distribute(row ? row.gates : []);
const scope = $("#a-scope", f);
scope.value = where.scope.kind;
const scoped = countryInput(where.scope.values);
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-scope-countries", f).replaceWith(scoped.node);
$("#a-countries", f).replaceWith(countries.node);
$("#a-towns", f).replaceWith(places.node);
const remoteMode = $("#a-remote", f);
remoteMode.value = where.remote.mode;
const remoteFrom = remoteInput(where.remote.mode === "from" ? where.remote.values : [], () => changed(f));
$("#a-remote-from", f).replaceWith(remoteFrom.node);
// Only the pick that is on shows its chips.
const offer = () => {
scoped.node.hidden = scope.value !== "countries";
remoteFrom.node.hidden = remoteMode.value !== "from";
};
offer();
const kept = $("#a-kept", f);
kept.textContent = keptNote(rest);
kept.hidden = !rest.length;
// The gates Save sends: the four parts', then the kept ones. The sentence
// under them says them all, as the card will, the kept ones included.
const gates = () => formGates({
scope: scope.value, scoped: scoped.values(), within: countries.values(), towns: places.values(),
remote: remoteMode.value, from: remoteFrom.values(), titles: titles.values(),
}, rest);
const view = () => {
offer();
$("#a-where-sum", f).textContent = rulesLine(gates()) || "Passes every role.";
};
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-cv-skills", f).value = weights.cv_skills;
$("#a-cv-experience", f).value = weights.cv_experience;
$("#a-cv-career", f).value = weights.cv_career;
$("#a-cut-fit-top", f).value = limits.cut_fit_top;
$("#a-cut-fit-min", f).value = limits.cut_fit_min;
$("#a-cut-cv-top", f).value = limits.cut_cv_top;
$("#a-cut-cv-min", f).value = limits.cut_cv_min;
$("#a-summarise-top", f).value = limits.summarise_top;
$("#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: () => prompts.map((p) => p.read()),
gates,
terms: terms.values,
languages: () => languages.map((l) => l.read()),
}));
$("#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.";
}
// Read a .md or .txt file into the CV box, replacing what is there. The file
// stays in the browser; Save sends the text like any typed one.
function readCvFile(input, box, f) {
const file = input.files && input.files[0];
input.value = "";
if (!file) return;
if (file.size > MAX_CV_BYTES) {
window.toast.error(`${file.name} is over 1 MB, too big for a CV. Paste the part that matters.`);
return;
}
const reader = new FileReader();
reader.onload = () => {
box.value = String(reader.result || "");
changed(f);
};
reader.onerror = () => window.toast.error(`Could not read ${file.name}.`);
reader.readAsText(file);
}
// `read` holds the form's rows and chips as the API takes them: `prompts`,
// `gates`, `terms` and `languages`.
// A prompt with neither name nor text is an empty row, left out, as is a
// language row with no code.
async function save(event, row, read) {
event.preventDefault();
const f = event.target;
const prompts = read.prompts().filter((p) => p.name || p.text.trim());
if (prompts.some((p) => !p.name)) {
window.toast.error("Every prompt needs a name.");
return;
}
const cvLanguages = read.languages().filter((l) => l.language);
if (cvLanguages.some((l) => !/^[a-z]{2}$/.test(l.language))) {
window.toast.error("A language is a two-letter code such as en or da.");
return;
}
const gates = read.gates();
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),
cv_skills: Number($("#a-cv-skills", f).value),
cv_experience: Number($("#a-cv-experience", f).value),
cv_career: Number($("#a-cv-career", f).value),
},
limits: {
cut_fit_top: Number($("#a-cut-fit-top", f).value),
cut_fit_min: Number($("#a-cut-fit-min", f).value),
cut_cv_top: Number($("#a-cut-cv-top", f).value),
cut_cv_min: Number($("#a-cut-cv-min", f).value),
summarise_top: Number($("#a-summarise-top", f).value),
},
fetch_terms: read.terms(),
cv_text: $("#a-cv-text", f).value,
cv_languages: cvLanguages,
like_text: $("#a-like-text", f).value,
avoid_text: $("#a-avoid-text", f).value,
// 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");
await nameRemote(agents.flatMap((a) => a.gates || []));
// 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 = {};
}
}
// For tests/js/agents.test.mjs: what Save sends and how it is said.
window.agentGates = { formGates, keptNote, rulesLine };
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();
});
})();