agent-space-manager 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,188 @@
1
+ // D:\Software\Magpie\agent-space-manager\smart-tools.middleware.js
2
+ // Smart Middleware: Dynamic Intent-Based MCP Tool Gateway Middleware for Magpie
3
+ // Embedded as an On/Off Feature in Agent Space Manager.
4
+
5
+ import fs from "fs";
6
+ import path from "path";
7
+ import { fileURLToPath } from "url";
8
+ import { loadHubConfig } from "./manager.mjs";
9
+ import { startApiServer } from "./server.mjs";
10
+
11
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
+ const ERROR_LOG_PATH = path.join(__dirname, "error.log");
13
+ const LAST_ERROR_PATH = path.join(__dirname, "LAST_ERROR.json");
14
+ const STATUS_PATH = path.join(__dirname, "STATUS.md");
15
+
16
+ if (!process.env.ASM_NO_SERVER && process.env.NODE_ENV !== "test" && process.env.ASM_TEST !== "1") {
17
+ try {
18
+ startApiServer();
19
+ } catch {}
20
+ }
21
+
22
+ let cachedConfig = null;
23
+ let cachedConfigAt = 0;
24
+
25
+ function getCachedHubConfig() {
26
+ const now = Date.now();
27
+ if (!cachedConfig || now - cachedConfigAt > 2000) {
28
+ cachedConfig = loadHubConfig();
29
+ cachedConfigAt = now;
30
+ }
31
+ return cachedConfig;
32
+ }
33
+
34
+ function recordFailure(error, contextInfo = {}) {
35
+ const timestamp = new Date().toISOString();
36
+ const entry = {
37
+ timestamp,
38
+ message: String(error?.message || error),
39
+ stack: String(error?.stack || ""),
40
+ model: contextInfo.model || "unknown",
41
+ toolCount: contextInfo.toolCount || 0,
42
+ };
43
+
44
+ try {
45
+ fs.writeFileSync(LAST_ERROR_PATH, JSON.stringify(entry, null, 2), "utf8");
46
+ const logLine = `[${timestamp}] [ERROR] ${entry.message}\n${entry.stack}\n---\n`;
47
+ fs.appendFileSync(ERROR_LOG_PATH, logLine, "utf8");
48
+
49
+ const statusMd =
50
+ `# Smart Middleware Live Diagnostics\n\n` +
51
+ `**Last Failure Recorded:** ${timestamp}\n\n` +
52
+ `- **Error Message:** \`${entry.message}\`\n` +
53
+ `- **Model:** \`${entry.model}\`\n` +
54
+ `- **Initial Tools Count:** ${entry.toolCount}\n\n` +
55
+ `### Stack Trace\n\`\`\`text\n${entry.stack}\n\`\`\`\n\n` +
56
+ `*Log file location: \`${ERROR_LOG_PATH}\`*\n`;
57
+ fs.writeFileSync(STATUS_PATH, statusMd, "utf8");
58
+ } catch (err) {
59
+ console.error("Failed to record error diagnostics:", err);
60
+ }
61
+ }
62
+
63
+ const CORE_TOOL_REGEX = /^(read_file|write_file|edit_file|run_command|execute_command|bash|terminal|search_web|web_search|get_context|fetch)/i;
64
+
65
+ export function onRequest(body, ctx) {
66
+ if (!body) return;
67
+
68
+ const hubConfig = getCachedHubConfig();
69
+ const isEnabled = ctx?.options?.smartMiddlewareEnabled !== undefined
70
+ ? Boolean(ctx.options.smartMiddlewareEnabled)
71
+ : Boolean(hubConfig?.smartMiddleware?.enabled ?? true);
72
+
73
+ if (!isEnabled) {
74
+ if (ctx && typeof ctx.report === "function") {
75
+ ctx.report("bypassed", body?.tools?.length || 0);
76
+ }
77
+ return;
78
+ }
79
+
80
+ const initialToolCount = Array.isArray(body.tools) ? body.tools.length : 0;
81
+
82
+ if (ctx && typeof ctx.report === "function") {
83
+ ctx.report("ready", initialToolCount);
84
+ }
85
+
86
+ if (!Array.isArray(body.tools) || body.tools.length === 0) {
87
+ return;
88
+ }
89
+
90
+ try {
91
+ const maxSafeTools = (ctx?.options?.maxTools && Number.isInteger(ctx.options.maxTools))
92
+ ? ctx.options.maxTools
93
+ : (hubConfig?.smartMiddleware?.maxTools || 96);
94
+
95
+ const messages = Array.isArray(body.messages) ? body.messages : [];
96
+ const userMessages = messages.filter((m) => !m.role || m.role === "user");
97
+ const recentMsgs = (userMessages.length > 0 ? userMessages : messages).slice(-3);
98
+
99
+ let userText = "";
100
+ for (const msg of recentMsgs) {
101
+ if (typeof msg.content === "string") {
102
+ userText += " " + msg.content.toLowerCase();
103
+ } else if (Array.isArray(msg.content)) {
104
+ for (const part of msg.content) {
105
+ if (part && typeof part.text === "string") {
106
+ userText += " " + part.text.toLowerCase();
107
+ }
108
+ }
109
+ }
110
+ }
111
+
112
+ const coreTools = [];
113
+ const nonCoreTools = [];
114
+ for (const t of body.tools) {
115
+ const fn = t.function || t;
116
+ const name = String(fn.name || "");
117
+ if (CORE_TOOL_REGEX.test(name)) {
118
+ coreTools.push(t);
119
+ } else {
120
+ nonCoreTools.push(t);
121
+ }
122
+ }
123
+
124
+ const isPureChat = /^\s*(hi|hello|hey|yo|ping|thanks|thank you|what can you do|who are you)\s*[\.\?!]*$/i.test(userText.trim());
125
+ if (isPureChat && body.tools.length > 15) {
126
+ const chatTools = [...coreTools, ...nonCoreTools].slice(0, Math.min(15, maxSafeTools));
127
+ return { ...body, tools: chatTools };
128
+ }
129
+
130
+ const matchedTools = [...coreTools];
131
+ const fallbackTools = [];
132
+
133
+ for (const t of nonCoreTools) {
134
+ const fn = t.function || t;
135
+ const name = String(fn.name || "").toLowerCase();
136
+
137
+ const nameTokens = name.split(/[^a-z0-9]+/i).filter((tok) => tok.length > 2);
138
+ let isMatch = false;
139
+
140
+ for (const tok of nameTokens) {
141
+ if (userText.includes(tok)) {
142
+ isMatch = true;
143
+ break;
144
+ }
145
+ }
146
+
147
+ if (!isMatch) {
148
+ if (/(^|[_-])(re|reverse|binary|disasm|decompile|gdb|frida|rizin)([_-]|$)/i.test(name)) {
149
+ if (/(reverse|binary|disassembl|decompile|pe|elf|macho|dll|exe|instruction|register|gdb|frida|rizin|assembly|opcode|demangle|symbols)/i.test(userText)) {
150
+ isMatch = true;
151
+ }
152
+ } else if (name.includes("crawl") || name.includes("scrape") || name.includes("stagehand") || name.includes("crw")) {
153
+ if (/(scrape|crawl|website|browser|webpage|url|http|extract|html|dom|click|navigate|page)/i.test(userText)) {
154
+ isMatch = true;
155
+ }
156
+ } else if (name.includes("gemini") || name.includes("docs") || name.includes("knowledge")) {
157
+ if (/(doc|documentation|api|sdk|reference|search|lookup|guide|gemini)/i.test(userText)) {
158
+ isMatch = true;
159
+ }
160
+ } else if (name.includes("dart") || name.includes("flutter")) {
161
+ if (/(dart|flutter|pubspec|widget|stateful|stateless)/i.test(userText)) {
162
+ isMatch = true;
163
+ }
164
+ } else if (name.includes("bio") || name.includes("protein") || name.includes("chem") || name.includes("pdb") || name.includes("structure")) {
165
+ if (/(protein|amino|structure|alphafold|pdb|dna|rna|gene|sequence|molecular|chembl|biology)/i.test(userText)) {
166
+ isMatch = true;
167
+ }
168
+ }
169
+ }
170
+
171
+ if (isMatch) {
172
+ matchedTools.push(t);
173
+ } else {
174
+ fallbackTools.push(t);
175
+ }
176
+ }
177
+
178
+ const finalTools = [...matchedTools, ...fallbackTools].slice(0, maxSafeTools);
179
+ return { ...body, tools: finalTools };
180
+ } catch (err) {
181
+ recordFailure(err, { model: body.model, toolCount: initialToolCount });
182
+ return { ...body, tools: body.tools.slice(0, 96) };
183
+ }
184
+ }
185
+
186
+ export function onResponse(reply, ctx) {
187
+ // Pass-through
188
+ }