Files
canvas-frontend/src/lib/agentTools.ts
T
shad 15ab8ededa feat(agent): LLM proxy integration shape (Pi-AI compatible)
src/lib/llmClient.ts: browser POSTs to /internal/canvas-llm/chat with
{messages, max_tokens}. Mirrors the normalized request shape used by
earendil-works/pi's @earendil-works/pi-ai. Returns:
 - ok:true with content+provider when configured and successful
 - ok:false, configured:false when proxy 404/503/unreachable
 - ok:false, configured:true when provider returned an error

routeAgentInput now falls back to the LLM with a system prompt that
includes the user identity, tool catalogue, and the top-3 vault recall
hits when no deterministic tool matches. When the proxy is not
configured the deterministic vault-hint reply is used (no regression
in the demo tier).
2026-06-14 14:55:34 +04:00

234 lines
10 KiB
TypeScript

import { api } from "./api";
import { wizardApi } from "./wizardApi";
import { chatApi } from "./chatApi";
import { curatedPublishedFlows, fetchStartableFlows } from "./flowCuration";
import { agentMemory, type Memory } from "./agentMemory";
import { llmClient, type LlmMessage } from "./llmClient";
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 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<string, any>();
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<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(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<string, any>();
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}` };
},
},
{
name: "remember",
description: "Stash a note in your per-tenant memory vault",
matcher: /^(remember|note|save)\s+(that\s+)?(.+)$/i,
async run(input, ctx) {
const m = input.match(/^(remember|note|save)\s+(that\s+)?(.+)$/i);
const content = m?.[3]?.trim() || "";
if (!content) return { ok: false, display: "Tell me what to remember." };
const key = await agentMemory.remember(ctx.userEmail, content, ["user-said"]);
return key
? { ok: true, display: `Got it — I'll remember: "${content}".` }
: { ok: false, display: "Couldn't save that to your vault. Try again." };
},
},
{
name: "recall",
description: "Pull related notes from your memory vault",
matcher: /^(recall|remind me|what do you know|what did i say)\s*(about|of|on)?\s*(.*)$/i,
async run(input, ctx) {
const m = input.match(/^(recall|remind me|what do you know|what did i say)\s*(about|of|on)?\s*(.*)$/i);
const query = m?.[3]?.trim() || "";
const memories = await agentMemory.recall(ctx.userEmail, query, 5);
if (!memories.length) return { ok: true, display: query ? `Nothing in your vault about "${query}" yet.` : "Your vault is empty." };
const lines = memories.map((mem) => `• ${mem.content}`).join("\n");
return { ok: true, display: `From your vault${query ? ` about "${query}"` : ""}:\n${lines}` };
},
},
];
async function llmFallback(trimmed: string, ctx: ToolContext, hints: Memory[]): Promise<ToolResult | null> {
const memBlock = hints.length ? `\nYour vault has related notes:\n${hints.map((h) => `- ${h.content}`).join("\n")}` : "";
const system: LlmMessage = {
role: "system",
content:
`You are the FlowMaster Command Assistant inside canvas.flow-master.ai for ${ctx.userEmail}. ` +
`Speak briefly (3 sentences max). You can refer to these tools by name when suggesting actions: ${TOOLS.map((t) => t.name).join(", ")}. ` +
`If the user asks something operational, recommend a specific tool. ${memBlock}`,
};
const user: LlmMessage = { role: "user", content: trimmed };
const reply = await llmClient.chat({ messages: [system, user], max_tokens: 320 });
if (reply.ok) return { ok: true, display: reply.content };
return null;
}
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." };
agentMemory.remember(ctx.userEmail, trimmed, ["turn"]).catch(() => {});
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}` };
}
}
}
let hints: Memory[] = [];
try { hints = await agentMemory.recall(ctx.userEmail, trimmed, 3); } catch { /* ignore */ }
const llmReply = await llmFallback(trimmed, ctx, hints);
if (llmReply) return llmReply;
if (hints.length > 0) {
const lines = hints.map((h) => `• ${h.content}`).join("\n");
return {
ok: true,
display: `I don't have a command that matches that yet, but your vault has related notes:\n${lines}\n\nTry: 'open mission', 'list processes', 'remember that ...', 'recall about ...', 'create a new process'.`,
};
}
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 }));
}