src / tools_27-10.txt
src / tools_27-10.txt
import { tool, Tool } from "@lmstudio/sdk";
import { z } from "zod";
import { executeFileTool } from "./tools/fileTools";
import { executeMemoryTool } from "./tools/memoryTools";
import { executeSystemTool } from "./tools/systemTools";
import { executeWebTool } from "./tools/webTools";
import { executeExcelTool } from "./tools/excelTools";
// ============================================================
// SERVER REGISTRY — 3 Cognitive Arms
// ============================================================
const SERVERS = {
core: "http://127.0.0.1:6075",
code: "http://127.0.0.1:6041",
terminal: "http://127.0.0.1:6090",
} as const;
type ServerName = keyof typeof SERVERS;
// ============================================================
// TOOL ALIASES
// ============================================================
const TOOL_ALIASES: Record<string, string> = {
runTerminal: "exec",
systemInfo: "health",
getNow: "getTime",
getCurrentTime: "getTime",
getCurrentDate: "getDate",
deleteFile: "moveToTrash",
listFolder: "listFiles",
runCode: "runPythonScript",
terminal: "exec",
semanticMemory: "semanticSearch",
};
// ============================================================
// FALLBACK CATALOG
// ============================================================
const FALLBACK_TOOL_CATALOG = [
{ name: "getTime", description: "Get current system time and date." },
{ name: "getDate", description: "Get current date and day of week." },
{ name: "readFile", description: "Read full content of a target file." },
{ name: "writeFile", description: "Create or overwrite a file with content." },
{ name: "appendToFile", description: "Append text to an existing file." },
{ name: "listFiles", description: "List direct files and folders in a directory." },
{ name: "searchFiles", description: "Search for files by name or content." },
{ name: "eagleEye", description: "Perform deep structural analysis on a file." },
{ name: "runPythonScript", description: "Execute a Python script and return output." },
{ name: "saveSession", description: "Save a session to persistent memory." },
{ name: "semanticSearch", description: "Semantic search in memory." },
{ name: "searchWeb", description: "Search the web in real time." },
{ name: "fetchArticle", description: "Fetch and save a web article." },
{ name: "exec", description: "Execute a shell command." },
{ name: "health", description: "Get system info." },
];
type ToolCatalogEntry = {
name: string;
description?: string;
parameters?: Record<string, string>;
server?: ServerName;
};
// ============================================================
// TOOL CATALOG CACHE
// ============================================================
let toolCatalogCache: ToolCatalogEntry[] | null = null;
let toolCatalogCacheTime = 0;
const TOOL_CATALOG_TTL_MS = 60 * 1000;
let cachedCatalogText: string | null = null;
// ============================================================
// LOAD CATALOG
// ============================================================
async function loadToolCatalog(forceRefresh = false): Promise<ToolCatalogEntry[]> {
const now = Date.now();
if (!forceRefresh && toolCatalogCache && (now - toolCatalogCacheTime) < TOOL_CATALOG_TTL_MS) {
return toolCatalogCache;
}
const fetchServer = async (serverName: ServerName, url: string): Promise<ToolCatalogEntry[]> => {
try {
const response = await fetch(`${url}/tools`, { signal: AbortSignal.timeout(1500) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json() as {
descriptions?: Record<string, { description?: string; parameters?: Record<string, string> }>;
};
return Object.entries(data.descriptions || {}).map(([name, details]) => ({
name,
description: details.description,
parameters: details.parameters,
server: serverName,
}));
} catch (err) {
console.warn(`[loadToolCatalog] Server '${serverName}' unreachable:`, (err as Error).message);
return [];
}
};
const results = await Promise.all(
Object.entries(SERVERS).map(([name, url]) => fetchServer(name as ServerName, url))
);
const catalog = results.flat();
if (catalog.length === 0) {
console.warn("[loadToolCatalog] All servers down — using FALLBACK_TOOL_CATALOG");
toolCatalogCache = FALLBACK_TOOL_CATALOG;
toolCatalogCacheTime = Date.now();
return FALLBACK_TOOL_CATALOG;
}
toolCatalogCache = catalog;
toolCatalogCacheTime = Date.now();
console.info(`[loadToolCatalog] Loaded ${catalog.length} tools from ${Object.keys(SERVERS).length} servers (cached)`);
return catalog;
}
// ============================================================
// GET TOOL CATALOG TEXT — for dynamic_prompt.md injection
// ============================================================
export async function getToolCatalogText(): Promise<string> {
if (cachedCatalogText !== null) return cachedCatalogText;
try {
await loadToolCatalog(true);
} catch {
console.warn("[getToolCatalogText] catalog load failed");
}
const catalog = toolCatalogCache || FALLBACK_TOOL_CATALOG;
const grouped: Record<string, ToolCatalogEntry[]> = { core: [], code: [], terminal: [] };
for (const entry of catalog) {
const server = entry.server || "core";
if (!grouped[server]) grouped[server] = [];
grouped[server].push(entry);
}
const headers: Record<string, string> = {
core: "### Core Tools (6075)",
code: "### Code Tools (6041)",
terminal: "### Terminal Tools (6090)",
};
const lines: string[] = ["## Tool Catalog"];
for (const [server, tools] of Object.entries(grouped)) {
if (tools.length === 0) continue;
lines.push(headers[server] || `### ${server}`);
for (const t of tools) {
const params = Object.entries(t.parameters || {})
.map(([k, v]) => `${k}: ${v}`)
.join(", ");
lines.push(`- ${t.name}${params ? `(${params})` : ""}: ${t.description || "No description"}`);
}
lines.push("");
}
cachedCatalogText = lines.join("\n");
return cachedCatalogText;
}
// ============================================================
// SERVER FOR TOOL
// ============================================================
let cachedToolToServer: Map<string, ServerName> | null = null;
function getServerForTool(toolName: string): ServerName | null {
if (!cachedToolToServer) return null;
return cachedToolToServer.get(toolName) || null;
}
// ============================================================
// EXECUTE VIA SERVER
// ============================================================
async function executeViaServer(toolName: string, params: any): Promise<any | null> {
const serverName = getServerForTool(toolName);
if (!serverName) return null;
const serverUrl = SERVERS[serverName];
try {
const response = await fetch(`${serverUrl}/tool/${encodeURIComponent(toolName)}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params || {}),
signal: AbortSignal.timeout(5000),
});
if (!response.ok) return null;
const data = await response.json() as any;
if (data.status === "success" || data.success) {
return {
success: true,
...data,
howl: data.howl || wolfHowl(toolName),
source: `server_${serverName}`,
};
}
} catch (err) {
console.warn(`[executeViaServer] '${serverName}' failed for '${toolName}':`, (err as Error).message);
}
return null;
}
// ============================================================
// EXECUTE TOOL
// ============================================================
export async function executeTool(rawToolName: string, args: any = {}): Promise<any> {
const toolName = TOOL_ALIASES[rawToolName] || rawToolName;
const serverResult = await executeViaServer(toolName, args);
if (serverResult) return serverResult;
let result = null;
result = await executeFileTool(toolName, args);
if (result) return result;
result = await executeMemoryTool(toolName, args);
if (result) return result;
result = await executeSystemTool(toolName, args);
if (result) return result;
result = await executeWebTool(toolName, args);
if (result) return result;
result = await executeExcelTool(toolName, args);
if (result) return result;
return { error: `Tool '${toolName}' has no executor registered.` };
}
// ============================================================
// WOLF HOWL
// ============================================================
export function wolfHowl(toolName: string): string {
const howls: Record<string, string> = {
readFile: "IO Engine: Reading file contents...",
writeFile: "IO Engine: Writing data to disk...",
appendToFile: "IO Engine: Appending to file...",
searchFiles: "IO Engine: Searching directory tree...",
eagleEye: "Analyzer: Deep inspection of file structure...",
listFiles: "IO Engine: Listing directory...",
listDirectoryStructure: "IO Engine: Mapping directory tree...",
semanticSearch: "Vector Engine: Retrieving embeddings...",
saveSession: "Memory Engine: Persisting session state...",
getMemory: "Memory Engine: Searching semantic history...",
markAwareness: "Cognitive Core: Recording insight...",
recallAwareness: "Cognitive Core: Recalling insights...",
searchWeb: "Web Engine: Performing live search...",
fetchArticle: "Web Engine: Scraping article text...",
runPythonScript: "Runtime: Executing Python script...",
readConsciousness: "Identity Core: Reading consciousness...",
appendToDynamicPrompt: "Identity Core: Updating dynamic prompt...",
getTime: "System Clock: Fetching timestamp...",
readFileLines: "Code Reader: Extracting line range...",
getFileOutline: "Code Analyzer: Building structure outline...",
searchInFile: "Code Reader: Searching within file...",
readFileWindow: "Code Reader: Reading context window...",
replaceLines: "Code Editor: Replacing line range...",
insertAtLine: "Code Editor: Inserting content...",
deleteLines: "Code Editor: Deleting lines...",
replaceInFile: "Code Editor: Find and replace...",
replaceBlock: "Code Editor: Replacing tagged block...",
findSymbols: "Code Analyzer: Extracting symbols...",
findReferences: "Code Analyzer: Finding references...",
getDependencies: "Code Analyzer: Mapping dependencies...",
codeStats: "Code Analyzer: Computing statistics...",
exec: "Terminal: Executing shell command...",
health: "Terminal: Gathering system info...",
history: "Terminal: Fetching command history...",
download: "Terminal: Downloading file...",
listPorts: "Terminal: Scanning listening ports...",
killProcess: "Terminal: Terminating process...",
which: "Terminal: Locating executable...",
env: "Terminal: Snapshotting environment...",
};
return howls[toolName] || `Executor: Invoking ${toolName}...`;
}
// ============================================================
// TOOLS PROVIDER — UI list only
// ============================================================
export async function toolsProvider(): Promise<any[]> {
return (await loadToolCatalog()).map(({ name, description, server }) => ({
name,
description,
server,
}));
}
// ============================================================
// TOOL EXECUTION CONTEXT
// ============================================================
export interface ToolExecutionContext {
onToolStart?: (callId: string, name: string, args: any) => void;
onToolResult?: (callId: string, name: string, result: any, howl: string, elapsedMs: number) => void;
}
// ============================================================
// CREATE SDK TOOLS — SHORT description
// ============================================================
export async function createSDKTools(context?: ToolExecutionContext): Promise<Tool[]> {
const catalog = await loadToolCatalog();
cachedToolToServer = new Map();
for (const entry of catalog) {
if (entry.server) cachedToolToServer.set(entry.name, entry.server);
}
return [tool({
name: "callTool",
description: "Execute one tool by exact name. Tool catalog is in the system prompt (dynamic_prompt.md). Pass arguments as JSON object.",
parameters: {
name: z.string().describe("Exact tool name"),
arguments: z.record(z.string(), z.unknown()).optional().describe("Arguments as JSON object"),
},
implementation: async ({ name, arguments: args = {} }) => {
const callId = `call_${name}_${Date.now()}`;
context?.onToolStart?.(callId, name, args);
const start = Date.now();
try {
const result = await executeTool(name, args);
const elapsed = Date.now() - start;
context?.onToolResult?.(callId, name, result, result?.howl || wolfHowl(name), elapsed);
return typeof result === "object" ? JSON.stringify(result, null, 2) : String(result);
} catch (err: any) {
const elapsed = Date.now() - start;
const errMsg = err?.message || String(err);
context?.onToolResult?.(callId, name, { error: errMsg }, "Error in tool execution", elapsed);
return `Error executing ${name}: ${errMsg}`;
}
},
})];
}
// ============================================================
// EXTRACT TOOLS FROM TEXT
// ============================================================
export interface ExtractedToolCall {
name: string;
arguments: any;
fullMatch?: string;
source?: string;
}
export function extractAllToolsFromText(text: string): ExtractedToolCall[] {
if (!text) return [];
const tools: ExtractedToolCall[] = [];
let match: RegExpExecArray | null;
const normalize = (n: string) => TOOL_ALIASES[n] || n;
const bidoRegex = /to=functions\.([a-zA-Z0-9_]+)\s+<\|channel\|>commentary\s+json<\|message\|>(\{[\s\S]*?\})<\|call\|>/gi;
while ((match = bidoRegex.exec(text)) !== null) {
try {
tools.push({ name: normalize(match[1]), arguments: JSON.parse(match[2]), fullMatch: match[0], source: "Commentary" });
} catch {}
}
const bidoConstrainRegex = /to=functions\.([a-zA-Z0-9_]+)\s+<\|constrain\|>json<\|message\|>(\{[\s\S]*?\})/gi;
while ((match = bidoConstrainRegex.exec(text)) !== null) {
try {
tools.push({ name: normalize(match[1]), arguments: JSON.parse(match[2]), fullMatch: match[0], source: "Constrained" });
} catch {}
}
const xmlRegex = /<execute_tool\s+name=["']([^"']+)["'](?:\s+params=['"]([^'"]*)['"])?/gi;
while ((match = xmlRegex.exec(text)) !== null) {
try {
let params = {};
if (match[2]) params = JSON.parse(match[2].replace(/'/g, '"'));
tools.push({ name: normalize(match[1]), arguments: params, fullMatch: match[0], source: "XML" });
} catch {}
}
const r1Regex = /<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/gi;
while ((match = r1Regex.exec(text)) !== null) {
try {
const parsed = JSON.parse(match[1]);
if (parsed.name || parsed.tool) {
const rawName = parsed.name || parsed.tool;
tools.push({ name: normalize(rawName), arguments: parsed.arguments || parsed.params || {}, fullMatch: match[0], source: "Standard" });
}
} catch {}
}
const explicitJsonRegex = /\{\s*"tool"\s*:\s*"([a-zA-Z0-9_-]+)"\s*,\s*"params"\s*:\s*(\{[^}]*\})\s*\}/gi;
while ((match = explicitJsonRegex.exec(text)) !== null) {
try {
tools.push({ name: normalize(match[1]), arguments: JSON.parse(match[2]), fullMatch: match[0], source: "Explicit" });
} catch {}
}
const standardJsonRegex = /\{\s*"name"\s*:\s*"([a-zA-Z0-9_-]+)"\s*,\s*"arguments"\s*:\s*(\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\})\s*\}/gi;
while ((match = standardJsonRegex.exec(text)) !== null) {
try {
if (!match[0].includes('<tool_call>')) {
tools.push({ name: normalize(match[1]), arguments: JSON.parse(match[2]), fullMatch: match[0], source: "StandardJSON" });
}
} catch {}
}
const hamadaRegex = /@tool:([a-zA-Z0-9_]+)\((.*?)\)/gi;
while ((match = hamadaRegex.exec(text)) !== null) {
try {
let argsObj: any = {};
const inner = match[2].trim();
if (inner.startsWith('{') && inner.endsWith('}')) {
argsObj = JSON.parse(inner);
} else if (inner) {
const parts = inner.split(',').map(s => s.trim().replace(/^['"]|['"]$/g, ''));
if (parts.length === 1) argsObj = { path: parts[0], query: parts[0], command: parts[0] };
else argsObj = { arg1: parts[0], arg2: parts[1] };
}
tools.push({ name: normalize(match[1]), arguments: argsObj, fullMatch: match[0], source: "Lightweight" });
} catch {}
}
const unique: ExtractedToolCall[] = [];
const seen = new Set<string>();
for (const t of tools) {
const key = `${t.name}|${JSON.stringify(t.arguments)}`;
if (!seen.has(key)) {
seen.add(key);
unique.push(t);
}
}
return unique;
}import { tool, Tool } from "@lmstudio/sdk";
import { z } from "zod";
import { executeFileTool } from "./tools/fileTools";
import { executeMemoryTool } from "./tools/memoryTools";
import { executeSystemTool } from "./tools/systemTools";
import { executeWebTool } from "./tools/webTools";
import { executeExcelTool } from "./tools/excelTools";
// ============================================================
// SERVER REGISTRY — 3 Cognitive Arms
// ============================================================
const SERVERS = {
core: "http://127.0.0.1:6075",
code: "http://127.0.0.1:6041",
terminal: "http://127.0.0.1:6090",
} as const;
type ServerName = keyof typeof SERVERS;
// ============================================================
// TOOL ALIASES
// ============================================================
const TOOL_ALIASES: Record<string, string> = {
runTerminal: "exec",
systemInfo: "health",
getNow: "getTime",
getCurrentTime: "getTime",
getCurrentDate: "getDate",
deleteFile: "moveToTrash",
listFolder: "listFiles",
runCode: "runPythonScript",
terminal: "exec",
semanticMemory: "semanticSearch",
};
// ============================================================
// FALLBACK CATALOG
// ============================================================
const FALLBACK_TOOL_CATALOG = [
{ name: "getTime", description: "Get current system time and date." },
{ name: "getDate", description: "Get current date and day of week." },
{ name: "readFile", description: "Read full content of a target file." },
{ name: "writeFile", description: "Create or overwrite a file with content." },
{ name: "appendToFile", description: "Append text to an existing file." },
{ name: "listFiles", description: "List direct files and folders in a directory." },
{ name: "searchFiles", description: "Search for files by name or content." },
{ name: "eagleEye", description: "Perform deep structural analysis on a file." },
{ name: "runPythonScript", description: "Execute a Python script and return output." },
{ name: "saveSession", description: "Save a session to persistent memory." },
{ name: "semanticSearch", description: "Semantic search in memory." },
{ name: "searchWeb", description: "Search the web in real time." },
{ name: "fetchArticle", description: "Fetch and save a web article." },
{ name: "exec", description: "Execute a shell command." },
{ name: "health", description: "Get system info." },
];
type ToolCatalogEntry = {
name: string;
description?: string;
parameters?: Record<string, string>;
server?: ServerName;
};
// ============================================================
// TOOL CATALOG CACHE
// ============================================================
let toolCatalogCache: ToolCatalogEntry[] | null = null;
let toolCatalogCacheTime = 0;
const TOOL_CATALOG_TTL_MS = 60 * 1000;
let cachedCatalogText: string | null = null;
// ============================================================
// LOAD CATALOG
// ============================================================
async function loadToolCatalog(forceRefresh = false): Promise<ToolCatalogEntry[]> {
const now = Date.now();
if (!forceRefresh && toolCatalogCache && (now - toolCatalogCacheTime) < TOOL_CATALOG_TTL_MS) {
return toolCatalogCache;
}
const fetchServer = async (serverName: ServerName, url: string): Promise<ToolCatalogEntry[]> => {
try {
const response = await fetch(`${url}/tools`, { signal: AbortSignal.timeout(1500) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json() as {
descriptions?: Record<string, { description?: string; parameters?: Record<string, string> }>;
};
return Object.entries(data.descriptions || {}).map(([name, details]) => ({
name,
description: details.description,
parameters: details.parameters,
server: serverName,
}));
} catch (err) {
console.warn(`[loadToolCatalog] Server '${serverName}' unreachable:`, (err as Error).message);
return [];
}
};
const results = await Promise.all(
Object.entries(SERVERS).map(([name, url]) => fetchServer(name as ServerName, url))
);
const catalog = results.flat();
if (catalog.length === 0) {
console.warn("[loadToolCatalog] All servers down — using FALLBACK_TOOL_CATALOG");
toolCatalogCache = FALLBACK_TOOL_CATALOG;
toolCatalogCacheTime = Date.now();
return FALLBACK_TOOL_CATALOG;
}
toolCatalogCache = catalog;
toolCatalogCacheTime = Date.now();
console.info(`[loadToolCatalog] Loaded ${catalog.length} tools from ${Object.keys(SERVERS).length} servers (cached)`);
return catalog;
}
// ============================================================
// GET TOOL CATALOG TEXT — for dynamic_prompt.md injection
// ============================================================
export async function getToolCatalogText(): Promise<string> {
if (cachedCatalogText !== null) return cachedCatalogText;
try {
await loadToolCatalog(true);
} catch {
console.warn("[getToolCatalogText] catalog load failed");
}
const catalog = toolCatalogCache || FALLBACK_TOOL_CATALOG;
const grouped: Record<string, ToolCatalogEntry[]> = { core: [], code: [], terminal: [] };
for (const entry of catalog) {
const server = entry.server || "core";
if (!grouped[server]) grouped[server] = [];
grouped[server].push(entry);
}
const headers: Record<string, string> = {
core: "### Core Tools (6075)",
code: "### Code Tools (6041)",
terminal: "### Terminal Tools (6090)",
};
const lines: string[] = ["## Tool Catalog"];
for (const [server, tools] of Object.entries(grouped)) {
if (tools.length === 0) continue;
lines.push(headers[server] || `### ${server}`);
for (const t of tools) {
const params = Object.entries(t.parameters || {})
.map(([k, v]) => `${k}: ${v}`)
.join(", ");
lines.push(`- ${t.name}${params ? `(${params})` : ""}: ${t.description || "No description"}`);
}
lines.push("");
}
cachedCatalogText = lines.join("\n");
return cachedCatalogText;
}
// ============================================================
// SERVER FOR TOOL
// ============================================================
let cachedToolToServer: Map<string, ServerName> | null = null;
function getServerForTool(toolName: string): ServerName | null {
if (!cachedToolToServer) return null;
return cachedToolToServer.get(toolName) || null;
}
// ============================================================
// EXECUTE VIA SERVER
// ============================================================
async function executeViaServer(toolName: string, params: any): Promise<any | null> {
const serverName = getServerForTool(toolName);
if (!serverName) return null;
const serverUrl = SERVERS[serverName];
try {
const response = await fetch(`${serverUrl}/tool/${encodeURIComponent(toolName)}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params || {}),
signal: AbortSignal.timeout(5000),
});
if (!response.ok) return null;
const data = await response.json() as any;
if (data.status === "success" || data.success) {
return {
success: true,
...data,
howl: data.howl || wolfHowl(toolName),
source: `server_${serverName}`,
};
}
} catch (err) {
console.warn(`[executeViaServer] '${serverName}' failed for '${toolName}':`, (err as Error).message);
}
return null;
}
// ============================================================
// EXECUTE TOOL
// ============================================================
export async function executeTool(rawToolName: string, args: any = {}): Promise<any> {
const toolName = TOOL_ALIASES[rawToolName] || rawToolName;
const serverResult = await executeViaServer(toolName, args);
if (serverResult) return serverResult;
let result = null;
result = await executeFileTool(toolName, args);
if (result) return result;
result = await executeMemoryTool(toolName, args);
if (result) return result;
result = await executeSystemTool(toolName, args);
if (result) return result;
result = await executeWebTool(toolName, args);
if (result) return result;
result = await executeExcelTool(toolName, args);
if (result) return result;
return { error: `Tool '${toolName}' has no executor registered.` };
}
// ============================================================
// WOLF HOWL
// ============================================================
export function wolfHowl(toolName: string): string {
const howls: Record<string, string> = {
readFile: "IO Engine: Reading file contents...",
writeFile: "IO Engine: Writing data to disk...",
appendToFile: "IO Engine: Appending to file...",
searchFiles: "IO Engine: Searching directory tree...",
eagleEye: "Analyzer: Deep inspection of file structure...",
listFiles: "IO Engine: Listing directory...",
listDirectoryStructure: "IO Engine: Mapping directory tree...",
semanticSearch: "Vector Engine: Retrieving embeddings...",
saveSession: "Memory Engine: Persisting session state...",
getMemory: "Memory Engine: Searching semantic history...",
markAwareness: "Cognitive Core: Recording insight...",
recallAwareness: "Cognitive Core: Recalling insights...",
searchWeb: "Web Engine: Performing live search...",
fetchArticle: "Web Engine: Scraping article text...",
runPythonScript: "Runtime: Executing Python script...",
readConsciousness: "Identity Core: Reading consciousness...",
appendToDynamicPrompt: "Identity Core: Updating dynamic prompt...",
getTime: "System Clock: Fetching timestamp...",
readFileLines: "Code Reader: Extracting line range...",
getFileOutline: "Code Analyzer: Building structure outline...",
searchInFile: "Code Reader: Searching within file...",
readFileWindow: "Code Reader: Reading context window...",
replaceLines: "Code Editor: Replacing line range...",
insertAtLine: "Code Editor: Inserting content...",
deleteLines: "Code Editor: Deleting lines...",
replaceInFile: "Code Editor: Find and replace...",
replaceBlock: "Code Editor: Replacing tagged block...",
findSymbols: "Code Analyzer: Extracting symbols...",
findReferences: "Code Analyzer: Finding references...",
getDependencies: "Code Analyzer: Mapping dependencies...",
codeStats: "Code Analyzer: Computing statistics...",
exec: "Terminal: Executing shell command...",
health: "Terminal: Gathering system info...",
history: "Terminal: Fetching command history...",
download: "Terminal: Downloading file...",
listPorts: "Terminal: Scanning listening ports...",
killProcess: "Terminal: Terminating process...",
which: "Terminal: Locating executable...",
env: "Terminal: Snapshotting environment...",
};
return howls[toolName] || `Executor: Invoking ${toolName}...`;
}
// ============================================================
// TOOLS PROVIDER — UI list only
// ============================================================
export async function toolsProvider(): Promise<any[]> {
return (await loadToolCatalog()).map(({ name, description, server }) => ({
name,
description,
server,
}));
}
// ============================================================
// TOOL EXECUTION CONTEXT
// ============================================================
export interface ToolExecutionContext {
onToolStart?: (callId: string, name: string, args: any) => void;
onToolResult?: (callId: string, name: string, result: any, howl: string, elapsedMs: number) => void;
}
// ============================================================
// CREATE SDK TOOLS — SHORT description
// ============================================================
export async function createSDKTools(context?: ToolExecutionContext): Promise<Tool[]> {
const catalog = await loadToolCatalog();
cachedToolToServer = new Map();
for (const entry of catalog) {
if (entry.server) cachedToolToServer.set(entry.name, entry.server);
}
return [tool({
name: "callTool",
description: "Execute one tool by exact name. Tool catalog is in the system prompt (dynamic_prompt.md). Pass arguments as JSON object.",
parameters: {
name: z.string().describe("Exact tool name"),
arguments: z.record(z.string(), z.unknown()).optional().describe("Arguments as JSON object"),
},
implementation: async ({ name, arguments: args = {} }) => {
const callId = `call_${name}_${Date.now()}`;
context?.onToolStart?.(callId, name, args);
const start = Date.now();
try {
const result = await executeTool(name, args);
const elapsed = Date.now() - start;
context?.onToolResult?.(callId, name, result, result?.howl || wolfHowl(name), elapsed);
return typeof result === "object" ? JSON.stringify(result, null, 2) : String(result);
} catch (err: any) {
const elapsed = Date.now() - start;
const errMsg = err?.message || String(err);
context?.onToolResult?.(callId, name, { error: errMsg }, "Error in tool execution", elapsed);
return `Error executing ${name}: ${errMsg}`;
}
},
})];
}
// ============================================================
// EXTRACT TOOLS FROM TEXT
// ============================================================
export interface ExtractedToolCall {
name: string;
arguments: any;
fullMatch?: string;
source?: string;
}
export function extractAllToolsFromText(text: string): ExtractedToolCall[] {
if (!text) return [];
const tools: ExtractedToolCall[] = [];
let match: RegExpExecArray | null;
const normalize = (n: string) => TOOL_ALIASES[n] || n;
const bidoRegex = /to=functions\.([a-zA-Z0-9_]+)\s+<\|channel\|>commentary\s+json<\|message\|>(\{[\s\S]*?\})<\|call\|>/gi;
while ((match = bidoRegex.exec(text)) !== null) {
try {
tools.push({ name: normalize(match[1]), arguments: JSON.parse(match[2]), fullMatch: match[0], source: "Commentary" });
} catch {}
}
const bidoConstrainRegex = /to=functions\.([a-zA-Z0-9_]+)\s+<\|constrain\|>json<\|message\|>(\{[\s\S]*?\})/gi;
while ((match = bidoConstrainRegex.exec(text)) !== null) {
try {
tools.push({ name: normalize(match[1]), arguments: JSON.parse(match[2]), fullMatch: match[0], source: "Constrained" });
} catch {}
}
const xmlRegex = /<execute_tool\s+name=["']([^"']+)["'](?:\s+params=['"]([^'"]*)['"])?/gi;
while ((match = xmlRegex.exec(text)) !== null) {
try {
let params = {};
if (match[2]) params = JSON.parse(match[2].replace(/'/g, '"'));
tools.push({ name: normalize(match[1]), arguments: params, fullMatch: match[0], source: "XML" });
} catch {}
}
const r1Regex = /<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/gi;
while ((match = r1Regex.exec(text)) !== null) {
try {
const parsed = JSON.parse(match[1]);
if (parsed.name || parsed.tool) {
const rawName = parsed.name || parsed.tool;
tools.push({ name: normalize(rawName), arguments: parsed.arguments || parsed.params || {}, fullMatch: match[0], source: "Standard" });
}
} catch {}
}
const explicitJsonRegex = /\{\s*"tool"\s*:\s*"([a-zA-Z0-9_-]+)"\s*,\s*"params"\s*:\s*(\{[^}]*\})\s*\}/gi;
while ((match = explicitJsonRegex.exec(text)) !== null) {
try {
tools.push({ name: normalize(match[1]), arguments: JSON.parse(match[2]), fullMatch: match[0], source: "Explicit" });
} catch {}
}
const standardJsonRegex = /\{\s*"name"\s*:\s*"([a-zA-Z0-9_-]+)"\s*,\s*"arguments"\s*:\s*(\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\})\s*\}/gi;
while ((match = standardJsonRegex.exec(text)) !== null) {
try {
if (!match[0].includes('<tool_call>')) {
tools.push({ name: normalize(match[1]), arguments: JSON.parse(match[2]), fullMatch: match[0], source: "StandardJSON" });
}
} catch {}
}
const hamadaRegex = /@tool:([a-zA-Z0-9_]+)\((.*?)\)/gi;
while ((match = hamadaRegex.exec(text)) !== null) {
try {
let argsObj: any = {};
const inner = match[2].trim();
if (inner.startsWith('{') && inner.endsWith('}')) {
argsObj = JSON.parse(inner);
} else if (inner) {
const parts = inner.split(',').map(s => s.trim().replace(/^['"]|['"]$/g, ''));
if (parts.length === 1) argsObj = { path: parts[0], query: parts[0], command: parts[0] };
else argsObj = { arg1: parts[0], arg2: parts[1] };
}
tools.push({ name: normalize(match[1]), arguments: argsObj, fullMatch: match[0], source: "Lightweight" });
} catch {}
}
const unique: ExtractedToolCall[] = [];
const seen = new Set<string>();
for (const t of tools) {
const key = `${t.name}|${JSON.stringify(t.arguments)}`;
if (!seen.has(key)) {
seen.add(key);
unique.push(t);
}
}
return unique;
}