Files
jobboard/app/static/agents.js
T

997 lines
41 KiB
JavaScript
Raw 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 Agent 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 fetch gate in three parts: the
* region (the scope select), the place (a short list of lines a role passes by
* matching any one of: countries, towns, remote) and the role (the fetch terms
* and the titles to leave out), over a row per remaining rule under Advanced;
* a gate the three parts cannot say lands in a row, so a load and a save lose
* nothing. A gate is a field, values and a mode (must, one of, not), with no
* weight. After it come the feed order (the four weights of the final score and
* the CV match weights), the cut (the best N by fit and the best M by CV
* closeness, each with a minimum level) 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. The must-have text
* is no longer on the form: a save leaves `must_text` out, so the stored one
* is kept (it is set through the API, and still caps career at 39 in code
* when the judge reports one broken).
* 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
// cut is the best `cut_fit_top` roles by fit 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. Fetch text, extract
// and judge read the cut; summarise reads the top `summarise_top` of the
// feed 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: 50 };
// 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;
const FIELDS = ["place", "country", "remote", "remote_from", "seniority", "function", "salary_min",
"currency", "permit", "languages", "company", "title"];
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 `fit ${w.fit} · newness ${w.recency} · companies ${w.affinity} · liked ${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 the one-of rows 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 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 fit at ${l.cut_fit_min} or more`);
if (l.cut_cv_top) lists.push(`the best ${l.cut_cv_top} by closeness to the CV 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(`The cut: ${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 the feed 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 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));
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 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] };
}
// "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, after the rule rows: 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 }) };
}
// A gate as a row: field, mode, values 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 drop = linky("Remove");
drop.addEventListener("click", () => remove(row));
row.append(field, mode, values, 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));
return { field: field.value, values: parts, mode: mode.value };
}
return { node: row, read };
}
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();
$("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: "require" }).node).focus();
changed(f);
});
// The gates the fetch gate's three parts say, in the order the starter
// agents have them: the region, the place lines, and the titles left out.
function whereGates() {
const out = [];
const within = countries.values();
const towns = places.values();
const from = remoteFrom.values();
if (scope.value === "europe") out.push({ field: "country", values: rh.europeWith(within), mode: "require" });
if (scope.value === "countries" && scoped.values().length) {
out.push({ field: "country", values: scoped.values(), mode: "require" });
}
if (within.length) out.push({ field: "country", values: within, mode: "any" });
if (remoteMode.value === "scope") out.push({ field: "remote", values: ["remote"], mode: "any" });
if (remoteMode.value === "from" && from.length) out.push({ field: "remote_from", values: from, mode: "any" });
if (towns.length) out.push({ field: "place", values: towns, mode: "any" });
const left = titles.values();
if (left.length) out.push({ field: "title", values: left, mode: "exclude" });
return out;
}
// The gates Save sends: the fetch gate's, then the rows. The sentence
// under it says them all, as the card will, rows included.
const gates = () => whereGates().concat(rules.map((r) => r.read()));
const view = () => {
offer();
$("#a-gates", f).value = JSON.stringify(gates(), null, 2);
$("#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 = {};
}
}
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();
});
})();