feat(agent): Pi in-app agent with tool router

New Pi tab. Talks to a typed tool router that maps natural-language
intent to real EA2 calls:

  navigate         go to mission / runs / studio / chat / hubs
  start_process    'run laptop procurement for store-204'
  send_chat        'tell Mariana that the quote is approved'
  create_process   opens the wizard
  list_processes   pulls published flow definitions for the tenant

This is the OSS-pluggable shape: today the router is rule-based and
fully wired to FlowMaster; swapping in an LLM provider for intent
parsing is a localised change in routeAgentInput().
This commit is contained in:
2026-06-14 12:41:13 +04:00
parent 333667366d
commit 47b1bf6998
4 changed files with 331 additions and 0 deletions
+164
View File
@@ -0,0 +1,164 @@
import { api } from "./api";
import { wizardApi } from "./wizardApi";
import { chatApi } from "./chatApi";
export interface ToolResult {
ok: boolean;
display: string;
action?: { kind: "navigate"; scene: string };
data?: any;
}
export interface ToolContext {
navigate: (scene: string) => void;
userEmail: string;
}
interface ToolDef {
name: string;
description: string;
matcher: RegExp;
run: (input: string, ctx: ToolContext) => Promise<ToolResult>;
}
const TOOLS: ToolDef[] = [
{
name: "navigate",
description: "Open a section of FlowMaster — mission, runs, studio, chat, settings, hubs",
matcher: /^(go to|open|show me|navigate to|take me to)\s+(.+)$/i,
async run(input, ctx) {
const m = input.match(/^(go to|open|show me|navigate to|take me to)\s+(.+)$/i);
const dest = m?.[2]?.toLowerCase().trim().replace(/[.!?]+$/, "") || "";
const map: Record<string, string> = {
mission: "mission",
"mission control": "mission",
runs: "history",
"run history": "history",
history: "history",
studio: "studio",
wizard: "studio",
chat: "chat",
settings: "settings",
home: "landing",
landing: "landing",
procurement: "hub-procurement",
"procurement hub": "hub-procurement",
hr: "hub-hr",
"hr hub": "hub-hr",
it: "hub-it",
"it hub": "hub-it",
attendance: "geo-attendance",
"geo attendance": "geo-attendance",
explainer: "explainer",
"what is flowmaster": "explainer",
};
const target = map[dest];
if (!target) return { ok: false, display: `I don't know where "${dest}" is. Try: mission, runs, studio, chat, procurement hub, HR hub, IT hub, attendance.` };
ctx.navigate(target);
return { ok: true, display: `Opened ${dest}.`, action: { kind: "navigate", scene: target } };
},
},
{
name: "start_process",
description: "Start a process instance",
matcher: /^(start|run|kick off|trigger)\s+(.+)$/i,
async run(input, _ctx) {
const m = input.match(/^(start|run|kick off|trigger)\s+(.+)$/i);
const phrase = m?.[2] || "";
const subjectMatch = phrase.match(/^(.*?)\s+(for|on|about)\s+(.+)$/i);
const processName = subjectMatch ? subjectMatch[1] : phrase;
const subject = subjectMatch ? subjectMatch[3] : undefined;
const procs = await fetch(`${api.config.baseUrl}/api/ea2/flow/processes?limit=200`, {
headers: { Authorization: `Bearer ${sessionStorage.getItem("fm.mc.token.v1")}` },
}).then((r) => r.json());
const items: any[] = procs?.items || [];
const norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
const target = norm(processName);
const match = items
.filter((it) => it.status === "published" && it.kind === "definition")
.find((it) => norm(it.display_name || "").includes(target) || norm(it.name || "").includes(target));
if (!match) return { ok: false, display: `Couldn't find a published process matching "${processName}". Try the Studio to create one.` };
try {
const res = await wizardApi.startInstance(match._key, subject);
return {
ok: true,
display: `Started ${match.display_name}${subject ? ` for ${subject}` : ""}. Transaction ${res.transaction_id?.slice(0, 8) || "ok"}.`,
data: res,
};
} catch (e: any) {
return { ok: false, display: `Start failed: ${e.message}` };
}
},
},
{
name: "send_chat",
description: "Send a chat message to a teammate",
matcher: /^(message|tell|text|ask)\s+(.+?)\s+(that|about|:)\s+(.+)$/i,
async run(input, ctx) {
const m = input.match(/^(message|tell|text|ask)\s+(.+?)\s+(that|about|:)\s+(.+)$/i);
if (!m) return { ok: false, display: "Try: message Mariana that the laptop quote is approved" };
const target = m[2].toLowerCase();
const body = m[4];
const directory: Record<string, string> = {
mariana: "ceo-head@flow-master.ai", ceo: "ceo-head@flow-master.ai",
aisha: "hr-head@flow-master.ai", hr: "hr-head@flow-master.ai",
rohan: "it-head@flow-master.ai", it: "it-head@flow-master.ai",
};
const recipient = Object.entries(directory).find(([k]) => target.includes(k))?.[1];
if (!recipient) return { ok: false, display: `I don't know who "${target}" is. Try Mariana, Aisha, or Rohan.` };
const threads = await chatApi.listThreads();
const existing = threads.find((t) => t.participants.includes(recipient) && t.participants.includes(ctx.userEmail));
const threadKey = existing?._key || (await chatApi.createThread(`${ctx.userEmail}${recipient}`, [ctx.userEmail, recipient]));
await chatApi.sendMessage(threadKey, body, ctx.userEmail);
return { ok: true, display: `Sent to ${recipient.split("@")[0]}: "${body}".` };
},
},
{
name: "create_process",
description: "Open the Process Creation Wizard to build a new process",
matcher: /^(create|new|design|build)\s+(a\s+)?(process|workflow|flow)/i,
async run(_input, ctx) {
ctx.navigate("studio");
return { ok: true, display: "Opened the Process Creation Wizard. Describe the process and I'll seed the structure.", action: { kind: "navigate", scene: "studio" } };
},
},
{
name: "list_processes",
description: "List published processes for this tenant",
matcher: /^(list|show|what)\s+(processes|workflows|flows)/i,
async run() {
const procs = await fetch(`${api.config.baseUrl}/api/ea2/flow/processes?limit=20`, {
headers: { Authorization: `Bearer ${sessionStorage.getItem("fm.mc.token.v1")}` },
}).then((r) => r.json());
const published = (procs?.items || []).filter((it: any) => it.status === "published" && it.kind === "definition").slice(0, 10);
if (!published.length) return { ok: true, display: "No published processes yet. Build one in the Studio." };
const lines = published.map((it: any) => `${it.display_name || it.name}`).join("\n");
return { ok: true, display: `Here's what's published:\n${lines}` };
},
},
];
export async function routeAgentInput(text: string, ctx: ToolContext): Promise<ToolResult> {
const trimmed = text.trim();
if (!trimmed) return { ok: false, display: "Tell me what to do." };
for (const tool of TOOLS) {
if (tool.matcher.test(trimmed)) {
try {
return await tool.run(trimmed, ctx);
} catch (e: any) {
return { ok: false, display: `${tool.name} failed: ${e.message || e}` };
}
}
}
return {
ok: false,
display:
"I can: navigate (e.g. 'open mission'), start a process ('run laptop procurement for store-204'), message a teammate ('tell Rohan that...'), list processes, or open the wizard ('create a new process').",
};
}
export function agentToolList(): { name: string; description: string }[] {
return TOOLS.map((t) => ({ name: t.name, description: t.description }));
}