mirror of
https://github.com/baserow/baserow.git
synced 2026-12-06 09:18:47 +00:00
* feat(agent): let triggered runs ask a person A trigger-started reply gets a built-in ask_person tool when the trigger's may_ask_person is on (default). The call is held like an ask-first call: the run pauses, counts as going for the overlap rule, and resumes with the answer of someone who may approve tool calls, or is told nobody will answer when the question is dismissed. Unattended replies are told that nobody reads them and whether they may ask; follow-ups keep the outside-data instruction. Later replies replay each decided question and its answer as plain turns in their history. * feat(agent): answer an agent's question in the conversation A held ask_person call shows as its own card with an answer field, Send answer and Dismiss, kept out of the approval card's batch actions. Only people without the approve permission see it read-only. The trigger card gets a switch to let the agent ask a person, and approval wording now covers questions too. * test(agent): cover asking a person end to end and record it in ADR 014 * refactor(agent): build the question tool like web fetch and tell it from actions The question tool is a plain Pydantic AI tool in agent/tools.py that the reply runner wraps in a FunctionToolset, like web fetch. A held call is a question only when it has no tool key, so an action saved as ask_person before the name was reserved keeps its normal approval. History prefetches only the decided questions, and the pending approvals menu links to the conversation only for a pending question. * test(agent): cover Ask first in a triggered run end to end With changes set to not ask first, a triggered run creates a database without waiting; turned back on, the same run waits for approval and finishes once approved. * test(agent): open the Triggers section in the ask-a-person spec The section was renamed on develop. * fix(agent): keep web search off next to the question tool on older Gemini Gemini before 3 refuses web search next to function tools. The question tool now counts as one, so a triggered run that may ask a person no longer sends both, gets a 400 and records a failed search on every run. * fix(agent): keep the ask-a-person switch of a license-locked trigger read-only The API refuses the change like the trigger's other locked settings, and the card makes the section inert and the switch read-only, like the overlap rule. * fix(agent): reserve the web_fetch action name An action named web_fetch on an agent with web fetch on gave two tools with the same name, so every reply failed when its toolsets were built. * refactor(agent): drop the special case for an action named ask_person Agents are behind a flag with no production users, so the name is simply reserved like the other built-in tools: a held ask_person call is always a question, on the backend and in the conversation. * fix(agent): answer a waiting question after asking is turned off ask_person now defers its call, and the resumed run gets the answer, or the dismissal note, as the call's result. Turning the trigger's switch off only stops new questions, instead of telling the agent that an answered question is no longer allowed while the card shows it as answered. * fix(agent): decide calls held with a question from the pending approvals menu The question shows as its link row to the conversation, and the other held calls stay in a card below it, so they can still be approved or rejected from the menu.
238 lines
7.3 KiB
JavaScript
238 lines
7.3 KiB
JavaScript
/** Answers Kuma's model requests like OpenAI's chat completions API, from fixed scripts. */
|
|
|
|
import http from "node:http";
|
|
|
|
const PORT = Number(process.env.PORT ?? 8080);
|
|
const WORD_DELAY_MS = Number(process.env.WORD_DELAY_MS ?? 300);
|
|
const MODEL = "kuma-e2e";
|
|
// Creates the database <name> with a "Tasks" table, then answers "word1 ... word<n>".
|
|
const SCRIPT = /kuma-e2e db=(\S+) words=(\d+)/;
|
|
// Next to SCRIPT, asks for sample rows and answers them once a GET of <url> returns.
|
|
const ROWS_HOLD = /rows-hold=(\S+)/;
|
|
// Also the chat's title, which Kuma asks for without tools.
|
|
const UNSCRIPTED_ANSWER = "E2E chat";
|
|
const MODEL_CHECK_TOOL = "baserow_model_compatibility_test";
|
|
// Asks "Which customer is this about?", then answers "Done for <answer>.".
|
|
const ASK_PERSON_SCRIPT = "E2E ask a person";
|
|
const ASK_PERSON_TOOL = "ask_person";
|
|
const NOBODY_TO_ASK_ANSWER = "Nobody to ask.";
|
|
const BUILDERS_RESULT = /"(created|reused)_builders"/;
|
|
const TABLES_RESULT = /"(created|reused)_tables"/;
|
|
const USAGE = { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 };
|
|
|
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
|
|
function textOf(message) {
|
|
if (typeof message.content === "string") return message.content;
|
|
return (message.content ?? []).map((part) => part.text ?? "").join("");
|
|
}
|
|
|
|
/** What a person wrote, also when a shared conversation wraps it with its sender. */
|
|
function promptOf(message) {
|
|
const text = textOf(message);
|
|
try {
|
|
const wrapped = JSON.parse(text);
|
|
if (typeof wrapped?.message === "string") return wrapped.message;
|
|
} catch {
|
|
// Plain text, as in a private conversation.
|
|
}
|
|
return text;
|
|
}
|
|
|
|
function toolCall(name, args) {
|
|
return {
|
|
id: `call_${name}`,
|
|
type: "function",
|
|
function: { name, arguments: JSON.stringify(args) },
|
|
};
|
|
}
|
|
|
|
/** Says when `ask_person` isn't offered, so a test can tell it was left out. */
|
|
function askPersonAnswer(messages, tools) {
|
|
if (!tools.includes(ASK_PERSON_TOOL)) return { text: NOBODY_TO_ASK_ANSWER };
|
|
const result = messages.at(-1);
|
|
if (result?.role === "tool") return { text: `Done for ${textOf(result)}.` };
|
|
return {
|
|
toolCall: toolCall(ASK_PERSON_TOOL, {
|
|
question: "Which customer is this about?",
|
|
}),
|
|
};
|
|
}
|
|
|
|
/** The next answer: `{ toolCall }`, `{ text }`, or `{ words }` streamed one by one. */
|
|
function nextAnswer(body) {
|
|
const messages = body.messages ?? [];
|
|
const tools = (body.tools ?? []).map((tool) => tool.function?.name);
|
|
if (tools.includes(MODEL_CHECK_TOOL)) {
|
|
return messages.at(-1)?.role === "tool"
|
|
? { text: "OK" }
|
|
: { toolCall: toolCall(MODEL_CHECK_TOOL, { value: "e2e" }) };
|
|
}
|
|
const lastUser = messages.findLast((message) => message.role === "user");
|
|
const prompt = lastUser ? promptOf(lastUser) : "";
|
|
if (prompt.includes(ASK_PERSON_SCRIPT)) {
|
|
return askPersonAnswer(messages, tools);
|
|
}
|
|
if (
|
|
prompt === "Create a support database." &&
|
|
tools.includes("create_database")
|
|
) {
|
|
const result = messages.at(-1);
|
|
if (result?.role === "tool") {
|
|
return {
|
|
text: textOf(result).includes("created_database")
|
|
? "The support database is ready."
|
|
: "I could not create the support database.",
|
|
};
|
|
}
|
|
return { toolCall: toolCall("create_database", { name: "Support" }) };
|
|
}
|
|
const script = prompt.match(SCRIPT);
|
|
const rowsHold = prompt.match(ROWS_HOLD);
|
|
if (rowsHold && !script) {
|
|
// Only the sample rows' prompt carries the hold without the script.
|
|
return { text: "No sample rows.", holdUrl: rowsHold[1] };
|
|
}
|
|
if (tools.length === 0 || !script) {
|
|
return { text: UNSCRIPTED_ANSWER };
|
|
}
|
|
const [, databaseName, wordCount] = script;
|
|
const results = messages
|
|
.slice(messages.lastIndexOf(lastUser))
|
|
.filter((message) => message.role === "tool")
|
|
.map(textOf);
|
|
const builders = results.find((result) => BUILDERS_RESULT.test(result));
|
|
if (!builders) {
|
|
return {
|
|
toolCall: toolCall("create_database", {
|
|
name: databaseName,
|
|
thought: "Create the database",
|
|
}),
|
|
};
|
|
}
|
|
if (!results.some((result) => TABLES_RESULT.test(result))) {
|
|
return {
|
|
toolCall: toolCall("create_tables", {
|
|
database_id: Number(builders.match(/"id":\s*(\d+)/)[1]),
|
|
tables: [{ name: "Tasks", primary_field_name: "Name", fields: [] }],
|
|
// Sample rows cost a sub-agent call, which only a held scenario needs.
|
|
add_sample_rows: rowsHold ? `kuma-e2e ${rowsHold[0]}` : false,
|
|
thought: "Add the Tasks table",
|
|
}),
|
|
};
|
|
}
|
|
return {
|
|
words: Array.from(
|
|
{ length: Number(wordCount) },
|
|
(_, index) => `word${index + 1}`
|
|
),
|
|
};
|
|
}
|
|
|
|
/** Waits until the barrier releases the hold at `url`; a failed hold answers at once. */
|
|
async function hold(url) {
|
|
try {
|
|
await fetch(url);
|
|
} catch (error) {
|
|
console.error(`kuma model stub: the hold at ${url} failed: ${error}`);
|
|
}
|
|
}
|
|
|
|
function chunk(delta, finishReason = null) {
|
|
return {
|
|
id: "chatcmpl-e2e",
|
|
object: "chat.completion.chunk",
|
|
created: Math.floor(Date.now() / 1000),
|
|
model: MODEL,
|
|
choices: [{ index: 0, delta, finish_reason: finishReason }],
|
|
};
|
|
}
|
|
|
|
async function stream(res, answer) {
|
|
res.writeHead(200, {
|
|
"Content-Type": "text/event-stream",
|
|
"Cache-Control": "no-cache",
|
|
});
|
|
const send = (data) => res.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
if (answer.toolCall) {
|
|
send(
|
|
chunk({
|
|
role: "assistant",
|
|
tool_calls: [{ index: 0, ...answer.toolCall }],
|
|
})
|
|
);
|
|
send(chunk({}, "tool_calls"));
|
|
} else {
|
|
const parts = answer.words ?? [answer.text];
|
|
for (const [index, part] of parts.entries()) {
|
|
if (res.destroyed) return;
|
|
send(
|
|
chunk({ role: "assistant", content: index === 0 ? part : ` ${part}` })
|
|
);
|
|
if (answer.words) await sleep(WORD_DELAY_MS);
|
|
}
|
|
send(chunk({}, "stop"));
|
|
}
|
|
send({ ...chunk({}), choices: [], usage: USAGE });
|
|
res.end("data: [DONE]\n\n");
|
|
}
|
|
|
|
function respond(res, answer) {
|
|
const message = answer.toolCall
|
|
? { role: "assistant", content: null, tool_calls: [answer.toolCall] }
|
|
: {
|
|
role: "assistant",
|
|
content: answer.words ? answer.words.join(" ") : answer.text,
|
|
};
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
res.end(
|
|
JSON.stringify({
|
|
id: "chatcmpl-e2e",
|
|
object: "chat.completion",
|
|
created: Math.floor(Date.now() / 1000),
|
|
model: MODEL,
|
|
choices: [
|
|
{
|
|
index: 0,
|
|
message,
|
|
finish_reason: answer.toolCall ? "tool_calls" : "stop",
|
|
},
|
|
],
|
|
usage: USAGE,
|
|
})
|
|
);
|
|
}
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
// A run that stops closes its stream early; that must not crash the stub.
|
|
res.on("error", () => {});
|
|
if (req.method !== "POST" || !req.url.endsWith("/chat/completions")) {
|
|
res.writeHead(404, { "Content-Type": "application/json" });
|
|
res.end(JSON.stringify({ error: { message: `No stub for ${req.url}` } }));
|
|
return;
|
|
}
|
|
let raw = "";
|
|
for await (const piece of req) raw += piece;
|
|
let body;
|
|
try {
|
|
body = JSON.parse(raw);
|
|
} catch {
|
|
res.writeHead(400);
|
|
res.end();
|
|
return;
|
|
}
|
|
const answer = nextAnswer(body);
|
|
if (answer.holdUrl) {
|
|
await hold(answer.holdUrl);
|
|
}
|
|
if (body.stream) {
|
|
await stream(res, answer);
|
|
} else {
|
|
respond(res, answer);
|
|
}
|
|
});
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`kuma model stub listening on ${PORT}`);
|
|
});
|