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
+5
View File
@@ -9,6 +9,7 @@ import Settings from "./scenes/Settings";
import Login from "./scenes/Login"; import Login from "./scenes/Login";
import SsoCallback from "./scenes/SsoCallback"; import SsoCallback from "./scenes/SsoCallback";
import Chat from "./scenes/Chat"; import Chat from "./scenes/Chat";
import Agent from "./scenes/Agent";
import CommandBar from "./components/CommandBar"; import CommandBar from "./components/CommandBar";
import Toaster from "./components/Toaster"; import Toaster from "./components/Toaster";
import Console from "./components/Console"; import Console from "./components/Console";
@@ -75,6 +76,9 @@ export default function App() {
<button role="tab" aria-selected={scene === "chat"} className={`tab${scene === "chat" ? " tab-sel" : ""}`} onClick={() => setScene("chat")}> <button role="tab" aria-selected={scene === "chat"} className={`tab${scene === "chat" ? " tab-sel" : ""}`} onClick={() => setScene("chat")}>
<Bot size={13} /> Chat <Bot size={13} /> Chat
</button> </button>
<button role="tab" aria-selected={scene === "agent"} className={`tab${scene === "agent" ? " tab-sel" : ""}`} onClick={() => setScene("agent")}>
<Bot size={13} /> Pi
</button>
<button role="tab" aria-selected={scene === "settings"} className={`tab${scene === "settings" ? " tab-sel" : ""}`} onClick={() => setScene("settings")}> <button role="tab" aria-selected={scene === "settings"} className={`tab${scene === "settings" ? " tab-sel" : ""}`} onClick={() => setScene("settings")}>
<Cog size={13} /> Settings <Cog size={13} /> Settings
</button> </button>
@@ -154,6 +158,7 @@ export default function App() {
{scene === "history" && <RunHistory />} {scene === "history" && <RunHistory />}
{scene === "studio" && <Wizard />} {scene === "studio" && <Wizard />}
{scene === "chat" && <Chat />} {scene === "chat" && <Chat />}
{scene === "agent" && <Agent />}
{scene === "settings" && <Settings />} {scene === "settings" && <Settings />}
</div> </div>
+39
View File
@@ -1898,3 +1898,42 @@ select.studio-input { background: var(--bp-paper); }
.chat-scene { grid-template-columns: 1fr; height: auto; } .chat-scene { grid-template-columns: 1fr; height: auto; }
.chat-sidebar { max-height: 240px; } .chat-sidebar { max-height: 240px; }
} }
.agent-scene {
display: grid;
grid-template-columns: 280px 1fr;
gap: 16px;
padding: 16px;
height: calc(100vh - 60px);
background: var(--bp-paper);
}
.agent-sidebar {
border: 1px solid var(--bp-navy);
background: var(--bp-paper);
display: flex; flex-direction: column; overflow: hidden;
}
.agent-side-head { padding: 12px; border-bottom: 1px solid var(--bp-navy); }
.agent-tool-list { padding: 12px; overflow-y: auto; display: flex; flex-direction: column; gap: 10px; }
.agent-tool-label { font-family: var(--bp-mono); font-size: 10px; letter-spacing: 0.08em; color: var(--bp-muted); margin-bottom: 4px; }
.agent-tool-row { display: flex; gap: 8px; align-items: flex-start; }
.agent-tool-name { font-size: 11px; font-weight: 700; color: var(--bp-navy); text-transform: uppercase; letter-spacing: 0.04em; }
.agent-tool-desc { font-size: 10px; color: var(--bp-muted); line-height: 1.4; }
.agent-main { border: 1px solid var(--bp-navy); background: var(--bp-paper); display: flex; flex-direction: column; overflow: hidden; }
.agent-messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; }
.agent-turn { padding: 10px 12px; border: 1px solid var(--bp-navy); max-width: 80%; }
.agent-turn-user { align-self: flex-end; background: color-mix(in srgb, var(--bp-amber) 20%, var(--bp-paper)); }
.agent-turn-agent { align-self: flex-start; background: var(--bp-paper); }
.agent-turn-err { border-color: #c25555; }
.agent-turn-thinking { font-style: italic; color: var(--bp-muted); }
.agent-turn-author { font-family: var(--bp-mono); font-size: 10px; color: var(--bp-muted); margin-bottom: 4px; }
.agent-turn-body { font-size: 12px; color: var(--bp-navy); white-space: pre-wrap; line-height: 1.4; }
.agent-suggestions { padding: 0 16px 12px; display: flex; flex-wrap: wrap; gap: 6px; }
.agent-suggestion { padding: 6px 10px; background: var(--bp-paper); border: 1px solid var(--bp-navy); color: var(--bp-navy); font-family: var(--bp-mono); font-size: 10px; cursor: pointer; }
.agent-suggestion:hover { background: color-mix(in srgb, var(--bp-amber) 20%, var(--bp-paper)); }
.agent-composer { padding: 12px; border-top: 1px solid var(--bp-navy); display: flex; gap: 8px; align-items: flex-end; }
.agent-composer textarea { flex: 1; padding: 8px; resize: none; background: var(--bp-paper); border: 1px solid var(--bp-navy); color: var(--bp-navy); font-family: var(--bp-mono); font-size: 12px; }
@media (max-width: 700px) {
.agent-scene { grid-template-columns: 1fr; height: auto; }
.agent-sidebar { max-height: 240px; }
}
+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 }));
}
+123
View File
@@ -0,0 +1,123 @@
import { useEffect, useRef, useState } from "react";
import { useApp } from "../state/store";
import { routeAgentInput, agentToolList, type ToolResult } from "../lib/agentTools";
import { Bot, Branch } from "../components/icons";
interface Turn {
id: string;
role: "user" | "agent";
text: string;
ok?: boolean;
}
const SUGGESTIONS = [
"Open mission control",
"List processes",
"Run procurement to pay for store-204",
"Tell Rohan that the laptop quote is approved",
"Create a new process",
"Open the IT hub",
];
export default function Agent() {
const userEmail = useApp((s) => s.userEmail);
const setScene = useApp((s) => s.setScene as (s: string) => void);
const [turns, setTurns] = useState<Turn[]>([
{
id: "welcome",
role: "agent",
ok: true,
text:
`Hi ${userEmail.split("@")[0]}. I'm Pi — your FlowMaster co-pilot. I can navigate the cockpit, start processes, message your team, and walk you through the Studio.`,
},
]);
const [draft, setDraft] = useState("");
const [working, setWorking] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
setTimeout(() => scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" }), 50);
}, [turns]);
const submit = async (text: string) => {
const t = text.trim();
if (!t || working) return;
const userTurn: Turn = { id: `u-${Date.now()}`, role: "user", text: t };
setTurns((prev) => [...prev, userTurn]);
setDraft("");
setWorking(true);
try {
const res: ToolResult = await routeAgentInput(t, {
navigate: (s) => setScene(s),
userEmail,
});
setTurns((prev) => [...prev, { id: `a-${Date.now()}`, role: "agent", text: res.display, ok: res.ok }]);
} catch (e: any) {
setTurns((prev) => [...prev, { id: `a-${Date.now()}`, role: "agent", text: `Error: ${e.message}`, ok: false }]);
} finally {
setWorking(false);
}
};
return (
<div className="agent-scene">
<aside className="agent-sidebar">
<header className="agent-side-head">
<div className="mc-hero-eyebrow"><Bot size={12} /> Pi FlowMaster Agent</div>
<h2 className="mc-hero-title">Talk to your cockpit</h2>
</header>
<div className="agent-tool-list">
<div className="agent-tool-label">CAPABILITIES</div>
{agentToolList().map((t) => (
<div key={t.name} className="agent-tool-row">
<Branch size={11} />
<div>
<div className="agent-tool-name">{t.name.replace(/_/g, " ")}</div>
<div className="agent-tool-desc">{t.description}</div>
</div>
</div>
))}
</div>
</aside>
<section className="agent-main">
<div className="agent-messages" ref={scrollRef}>
{turns.map((t) => (
<div key={t.id} className={`agent-turn agent-turn-${t.role}${t.ok === false ? " agent-turn-err" : ""}`}>
<div className="agent-turn-author">{t.role === "user" ? userEmail.split("@")[0] : "Pi"}</div>
<div className="agent-turn-body">{t.text}</div>
</div>
))}
{working && <div className="agent-turn agent-turn-agent agent-turn-thinking">Pi is thinking</div>}
</div>
{turns.length <= 1 && (
<div className="agent-suggestions">
{SUGGESTIONS.map((s) => (
<button key={s} className="agent-suggestion" onClick={() => submit(s)}>{s}</button>
))}
</div>
)}
<footer className="agent-composer">
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
submit(draft);
}
}}
placeholder="Ask Pi to navigate, start a process, or message a teammate. Enter to send."
rows={2}
disabled={working}
/>
<button className="btn btn-primary" onClick={() => submit(draft)} disabled={!draft.trim() || working}>
{working ? "…" : "Send"}
</button>
</footer>
</section>
</div>
);
}