import { api } from "./api"; import { wizardApi } from "./wizardApi"; import { chatApi } from "./chatApi"; import { curatedPublishedFlows, fetchStartableFlows } from "./flowCuration"; 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; } 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 = { 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 token = sessionStorage.getItem("fm.mc.token.v1") || ""; const procs = await fetch(`${api.config.baseUrl}/api/ea2/flow/processes?limit=500`, { headers: { Authorization: `Bearer ${token}` }, }).then((r) => r.json()); const fromList = curatedPublishedFlows((procs?.items || []) as any[]); const directHits = await fetchStartableFlows(api.config.baseUrl, token); const items = (() => { const m = new Map(); for (const it of [...directHits, ...fromList]) m.set(it._key, it); return Array.from(m.values()); })(); const norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim(); const target = norm(processName); const match = items.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}` : ""}.`, 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 = { 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(ctx.userEmail); 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 token = sessionStorage.getItem("fm.mc.token.v1") || ""; const procs = await fetch(`${api.config.baseUrl}/api/ea2/flow/processes?limit=500`, { headers: { Authorization: `Bearer ${token}` }, }) .then((r) => r.json()) .catch(() => ({ items: [] })); const fromList = curatedPublishedFlows((procs?.items || []) as any[]); const directHits = await fetchStartableFlows(api.config.baseUrl, token); const merged = new Map(); for (const it of [...directHits, ...fromList]) merged.set(it._key, it); const published = Array.from(merged.values()).slice(0, 10); if (!published.length) return { ok: true, display: "No published processes yet. Open the Studio to design one." }; const lines = published.map((it) => `• ${it.display_name}`).join("\n"); return { ok: true, display: `Here's what's published:\n${lines}` }; }, }, ]; export async function routeAgentInput(text: string, ctx: ToolContext): Promise { 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 })); }