agent-space-manager 1.0.1 → 1.0.2
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.
- package/CHANGELOG.md +20 -1
- package/README.md +1 -1
- package/README.zh-CN.md +2 -2
- package/package.json +1 -1
- package/page/app.js +17 -7
- package/page/index.html +2 -2
- package/smart-tools.middleware.js +285 -19
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
9
|
+
## [1.0.2] - 2026-11-14
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
- **Smart Middleware Dynamic Intent Layer (`shared/middleware-intents.json`)**: Layered runtime intent keyword engine (`smart-tools.middleware.js`) enabling users and agents to register custom intent keywords and tool patterns without altering core middleware code.
|
|
13
|
+
- **Initial Run Auto-Seeding (`autoSeedMiddlewareIntents`)**: Scans existing installed plugins/tools in Components Storage on initial run and seeds the personal intent layer automatically.
|
|
14
|
+
- **Uninstallation Intent Trimming (`trimMiddlewareIntent`)**: Concurrently trims and prunes uninstalled plugin tool patterns and intent keywords from `shared/middleware-intents.json` upon component removal.
|
|
15
|
+
- **Copy Prompt V1.5 (`page/app.js`, `page/index.html`)**: Bumped Copy Prompt to V1.5 with dynamic Smart Middleware intent lifecycle directives and updated persistent agent rule invariants.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
9
19
|
## [1.0.1] - 2026-11-12
|
|
10
20
|
|
|
11
21
|
### Changed
|
|
@@ -34,7 +44,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
|
34
44
|
|
|
35
45
|
This section tracks all revisions to the standardized instructions copied via the **Copy Prompt** button in the Agent Space Manager dashboard.
|
|
36
46
|
|
|
37
|
-
## [V1.
|
|
47
|
+
## [V1.5] - 2026-11-14
|
|
48
|
+
|
|
49
|
+
### Features & Invariants
|
|
50
|
+
- **Dynamic Smart Middleware Intent Lifecycle (`shared/middleware-intents.json`)**: Added Rule Invariant 8 directing AI agents to register or update intent keywords and tool patterns whenever installing or modifying MCP tools in Components Storage.
|
|
51
|
+
- **Initial Run Seeding**: Mandated that the copy prompt and Smart Middleware automatically scan existing installed plugins/tools in `<Components Storage Path>/plugins/` on initial run and seed the initial `shared/middleware-intents.json` personal layer.
|
|
52
|
+
- **Uninstallation Intent Trimming**: Mandated that when a user requests uninstalling or removing a plugin via the copy prompt, the agent concurrently trims and deletes its corresponding intent entries from `shared/middleware-intents.json` so no stale tool mappings remain.
|
|
53
|
+
- **Layered Upstream Engine Protection**: Allows Smart Middleware to dynamically prioritize newly installed tools based on user prompt context while preserving origin updates for the core middleware engine.
|
|
54
|
+
- **Dashboard UI Update**: Updated the Storage & Upstream Rules tile button to display `Copy Prompt (V1.5)`.
|
|
55
|
+
|
|
56
|
+
## [V1.4] - 2026-11-12
|
|
38
57
|
|
|
39
58
|
### Features & Invariants
|
|
40
59
|
- **Version Identifier**: Added explicit version tag `[Components Storage Specification & Upstream Rules Prompt V1.0]` at the header of the copied prompt text.
|
package/README.md
CHANGED
|
@@ -61,7 +61,7 @@ Agent Space Manager includes **13 built-in Agent Profiles** (`agents.mjs` & `ada
|
|
|
61
61
|
|
|
62
62
|
### 6. Centralized Weekly Upstream Checking & Storage Rules Prompt
|
|
63
63
|
- **Centralized Monday Update Check**: Checks upstream repository links for all stored components once per week on Monday startup (`/api/central-update-check`), and automatically prunes legacy decentralized update scripts (`update_checker.mjs`, `update_check_state.json`).
|
|
64
|
-
- **Copy Prompt (`V1.
|
|
64
|
+
- **Copy Prompt (`V1.5`)**: One-click button in the **Storage & Upstream Rules** tile that copies standardized instructions for your AI agent to enforce the Hub layout, record mandatory `upstream` URLs, perform complete plugin removal cleanup (including trimming Smart Middleware intents), save manifests in strict UTF-8 without BOM, respect one-time rearrangement stability, preserve the `shared/` cross-agent IPC/handoff directory, and maintain dynamic Smart Middleware intent keywords in `shared/middleware-intents.json` (auto-seeded on initial run from existing components).
|
|
65
65
|
|
|
66
66
|
### 7. Smart Middleware Tool Gateway & OmniRoute Integration
|
|
67
67
|
- **Dynamic Intent-Based Tool Filtering (`smart-tools.middleware.js`)**:
|
package/README.zh-CN.md
CHANGED
|
@@ -59,9 +59,9 @@ Agent Space Manager 是一个集中式控制平面,旨在**在同一个文件
|
|
|
59
59
|
- **SHA-256 存储快照指纹**:对 Components Storage 目录计算确定性规范快照(`getComponentsStorageSnapshot`)。
|
|
60
60
|
- **外部变更自动重连**:启动时若检测到存储目录中存在外部新增、修改或删除,系统将自动重新同步已配置的 Agent,并在顶部展示可关闭的 **Auto-reconnected Connected Agents** 提示横幅。
|
|
61
61
|
|
|
62
|
-
### 6. 集中式每周上游更新检查与规范提示词 (`Copy Prompt V1.
|
|
62
|
+
### 6. 集中式每周上游更新检查与规范提示词 (`Copy Prompt V1.5`)
|
|
63
63
|
- **集中式每周一更新检查**:每周一启动 Magpie 时集中检查所有已安装组件的上游仓库更新(`/api/central-update-check`),并自动清理分散的本地更新脚本(`update_checker.mjs`、`update_check_state.json`)。
|
|
64
|
-
- **一键复制规范提示词 (`Copy Prompt (V1.
|
|
64
|
+
- **一键复制规范提示词 (`Copy Prompt (V1.5)`)**:在 **Storage & Upstream Rules** 磁贴中一键复制标准化指令,引导你的 AI 助手严格遵守 Hub 目录规范、记录 `upstream` 上游链接、执行完整的插件卸载清理(同步裁剪智能中间件无用意图)、使用无 BOM 的 UTF-8 编码、保持一次性目录整理稳定性、保护 `shared/` 跨 Agent 通信目录,并在 `shared/middleware-intents.json` 中自动生成初始意图并在组件变动时动态增删。
|
|
65
65
|
|
|
66
66
|
### 7. 智能中间件工具网关与 OmniRoute 集成
|
|
67
67
|
- **基于意图的动态工具过滤 (`smart-tools.middleware.js`)**:
|
package/package.json
CHANGED
package/page/app.js
CHANGED
|
@@ -3248,7 +3248,7 @@
|
|
|
3248
3248
|
}
|
|
3249
3249
|
|
|
3250
3250
|
// Standardize Storage Structure Prompt Copy Button (with version display)
|
|
3251
|
-
const STORAGE_PROMPT_VERSION = "V1.
|
|
3251
|
+
const STORAGE_PROMPT_VERSION = "V1.5";
|
|
3252
3252
|
const btnCopyPrompt = $("btnCopyStoragePrompt");
|
|
3253
3253
|
if (btnCopyPrompt) {
|
|
3254
3254
|
const originalText = `Copy Prompt (${STORAGE_PROMPT_VERSION})`;
|
|
@@ -3260,7 +3260,7 @@
|
|
|
3260
3260
|
|
|
3261
3261
|
const promptText = `[Components Storage Specification & Upstream Rules Prompt ${STORAGE_PROMPT_VERSION}]
|
|
3262
3262
|
|
|
3263
|
-
Please organize and force our Components Storage file structure to strictly adhere to the standard plugin specification, record mandatory upstream source links, eliminate decentralized component updaters, ensure complete plugin uninstallation cleanup, enforce UTF-8 without BOM encoding, respect one-time rearrangement stability, define universal shared folder specifications, and install a persistent agent rule:
|
|
3263
|
+
Please organize and force our Components Storage file structure to strictly adhere to the standard plugin specification, record mandatory upstream source links, eliminate decentralized component updaters, ensure complete plugin uninstallation cleanup, enforce UTF-8 without BOM encoding, respect one-time rearrangement stability, define universal shared folder specifications, maintain dynamic Smart Middleware intent rules, and install a persistent agent rule:
|
|
3264
3264
|
|
|
3265
3265
|
${targetPathHeader}1. Directory Structure Specification:
|
|
3266
3266
|
Components Storage root (e.g. \`<Components Storage Path>\`) contains plugins, optional standalone skills, hub configuration, and a shared cross-agent communication/data directory:
|
|
@@ -3283,6 +3283,7 @@ Components Storage root (e.g. \`<Components Storage Path>\`) contains plugins, o
|
|
|
3283
3283
|
│ ├── handoff/ # Cross-agent delegation and task handoff inboxes
|
|
3284
3284
|
│ │ └── <agent-id>/ # Target agent inbox queue
|
|
3285
3285
|
│ ├── _upstream_backups/ # Pre-update backups and component snapshots
|
|
3286
|
+
│ ├── middleware-intents.json # Dynamic user & agent Smart Middleware intent keyword registry
|
|
3286
3287
|
│ └── <shared-tool-dirs>/ # Shared runtime states, engines, caches, or browser automation; subfolders are named after their joining skills (e.g. stagehand-fastcrw joining stagehand and fastcrw, omniroute)
|
|
3287
3288
|
├── skills/ # Standalone or migrated skills
|
|
3288
3289
|
├── hub-config.json # Hub configuration
|
|
@@ -3296,6 +3297,7 @@ The shared directory serves as the centralized cross-agent IPC, discovery, and s
|
|
|
3296
3297
|
- agent-connectors.json: Global discovery registry tracking connected agent profiles, capability flags, root config paths, and communication bridges.
|
|
3297
3298
|
- handoff/: Inter-agent handoff queues. Enables asynchronous task delegation and context packet transfers between agents across different IDEs.
|
|
3298
3299
|
- _upstream_backups/: Centralized safety backups created prior to weekly upstream component updates or synchronization runs.
|
|
3300
|
+
- middleware-intents.json: Dynamic intent keyword registry for Smart Middleware. Maps tool patterns (e.g. docker, database, git) to user intent keywords so Smart Middleware dynamically surfaces domain tools without exceeding LLM context limits.
|
|
3299
3301
|
- Shared Tooling & State Subfolder Naming: Shared runtime caches, browser automation tools, and routing engines accessible universally across all connected agents without redundant duplication. Any subfolder created in shared/ for collaborating skills MUST be named after the joining skills (e.g. \`stagehand-fastcrw\` representing the joint operation of \`stagehand\` and \`fastcrw\`).
|
|
3300
3302
|
- Invariant: Never treat the shared/ directory or its internal files as loose components, and never delete or clear user-managed handoffs or shared configs during plugin cleanup.
|
|
3301
3303
|
|
|
@@ -3316,7 +3318,8 @@ When the user asks to remove, delete, or uninstall a plugin:
|
|
|
3316
3318
|
* Associated rules in rules/ and any bridged rule files or managed rule sections.
|
|
3317
3319
|
* Associated MCP server definitions in mcp_config.json and their bridged entries.
|
|
3318
3320
|
* Associated hooks in hooks.json and their bridged hook entries.
|
|
3319
|
-
|
|
3321
|
+
* Associated Smart Middleware intent entries in <Components Storage Path>/shared/middleware-intents.json: trim and remove the plugin's registered intent keywords and tool patterns so no dead or stale intent entries remain for uninstalled tools.
|
|
3322
|
+
- Ensure no orphaned components, dangling junctions/symlinks, ghost configuration entries, or leftover intent keywords associated with the removed plugin remain.
|
|
3320
3323
|
|
|
3321
3324
|
5. Centralized Weekly Update Checking (No Decentralized Scripts):
|
|
3322
3325
|
- Remove and DO NOT create individual, local, or decentralized update scripts (such as update_checker.mjs or update_check_state.json) inside component folders.
|
|
@@ -3332,18 +3335,25 @@ When the user asks to remove, delete, or uninstall a plugin:
|
|
|
3332
3335
|
- If the rearrangement of the file structure in Components Storage Path has already been executed once using this prompt, STOP rearranging or moving existing directory/file structures on subsequent runs unless the user explicitly requests a rearrangement.
|
|
3333
3336
|
- Preserve already-organized components in their current locations to prevent directory churn and broken path references.
|
|
3334
3337
|
|
|
3335
|
-
8.
|
|
3338
|
+
8. Dynamic Smart Middleware Intent Lifecycle & Initial Run Seeding (shared/middleware-intents.json):
|
|
3339
|
+
- Initial Run Seeding: On the first initial run of this instruction prompt, or whenever <Components Storage Path>/shared/middleware-intents.json is missing or does not yet include all currently installed components, inspect all existing plugins in plugins/ (and their plugin.json, mcp_config.json, and skill definitions), identify their tool names and capabilities, and generate the initial shared/middleware-intents.json personal layer mapping each existing tool to relevant intent keywords and tool patterns.
|
|
3340
|
+
- Component Addendum: Whenever adding or installing new components with tools, register or update their intent keywords and tool patterns in <Components Storage Path>/shared/middleware-intents.json (e.g. {"<category>": {"toolPatterns": ["..."], "intentKeywords": ["..."]}}).
|
|
3341
|
+
- Component Removal & Trimming: Whenever removing or uninstalling any plugin/component, trim and delete its corresponding intent entries from shared/middleware-intents.json so no stale or orphaned tool mappings remain.
|
|
3342
|
+
- Rationale: Keeps the Smart Middleware dynamic, clean, and user-personalized while keeping the core middleware engine fully updatable from upstream origin.
|
|
3343
|
+
|
|
3344
|
+
9. Mandatory Persistent Agent Rule:
|
|
3336
3345
|
Install and persist a dedicated rule in your agent's rule system (e.g. .agents/rules/components-storage-upstream-rule.md or .cursor/rules/components-storage-upstream-rule.mdc) that is ALWAYS TRIGGERED whenever an addendum, creation, modification, edit, or removal of any component in the Components Storage Path (${storagePath || "Components Storage Path"}):
|
|
3337
3346
|
- Rule Trigger: Addendum, creation, edit, or removal of any component in Components Storage Path.
|
|
3338
3347
|
- Rule Invariant 1: Ensure strict compliance with the plugin directory and shared/ directory structures above, and disambiguate any coincidental duplicate component names by appending -1, -2, etc. sequentially.
|
|
3339
3348
|
- Rule Invariant 2: Always add and preserve the upstream link in the component's manifest or frontmatter.
|
|
3340
|
-
- Rule Invariant 3: Complete removal cleanup — when removing a plugin, all components related to that plugin (skills, agents, rules, MCP servers, hooks) must
|
|
3349
|
+
- Rule Invariant 3: Complete removal cleanup — when removing a plugin, all components related to that plugin (skills, agents, rules, MCP servers, hooks) AND its entries in shared/middleware-intents.json must be cleanly removed and trimmed with no orphaned leftovers.
|
|
3341
3350
|
- Rule Invariant 4: Never introduce decentralized or component-level update scripts; all update checking is handled centrally by the Agent Space Manager plugin on Monday startup.
|
|
3342
3351
|
- Rule Invariant 5: Never write files with a UTF-8 BOM header; always enforce UTF-8 No BOM encoding.
|
|
3343
3352
|
- Rule Invariant 6: One-Time Rearrangement Stability — if file rearrangement was already performed once, never rearrange or move existing structure again on subsequent prompt runs unless explicitly requested by the user.
|
|
3344
|
-
- Rule Invariant 7: Universal Shared Directory Preservation & Naming — preserve <Components Storage Path>/shared (agent-connectors.json, handoff/, _upstream_backups
|
|
3353
|
+
- Rule Invariant 7: Universal Shared Directory Preservation & Naming — preserve <Components Storage Path>/shared (agent-connectors.json, handoff/, _upstream_backups/, middleware-intents.json) as the designated cross-agent communication and data hub; never treat it as an orphaned or removable plugin; any subfolders in shared/ must be named after their joining skills (e.g. stagehand-fastcrw joining stagehand and fastcrw).
|
|
3354
|
+
- Rule Invariant 8: Dynamic Smart Middleware Intent Lifecycle & Seeding — (a) on initial run, seed shared/middleware-intents.json based on all currently existing plugins and tools in Components Storage; (b) when adding new components with tools, register their intent keywords and tool patterns in shared/middleware-intents.json; (c) when removing components, trim and prune their intent entries from shared/middleware-intents.json so the personal layer remains trimmed and accurate.
|
|
3345
3355
|
|
|
3346
|
-
Please inspect ${storagePath || "Components Storage Path"}, clean up non-conforming or loose files, ensure all component manifests and frontmatters contain their upstream links, ensure all JSON files are valid UTF-8 without BOM, purge any decentralized update checking scripts, ensure removal rules cover all related components, preserve the shared/ cross-agent folder, respect one-time rearrangement stability if already arranged, and persist the rule into your agent's rules.`;
|
|
3356
|
+
Please inspect ${storagePath || "Components Storage Path"}, clean up non-conforming or loose files, ensure all component manifests and frontmatters contain their upstream links, ensure all JSON files are valid UTF-8 without BOM, purge any decentralized update checking scripts, ensure removal rules cover all related components and trim middleware intents, preserve the shared/ cross-agent folder, seed or update tool intent keywords in shared/middleware-intents.json based on existing installed components, respect one-time rearrangement stability if already arranged, and persist the rule into your agent's rules.`;
|
|
3347
3357
|
|
|
3348
3358
|
let copied = false;
|
|
3349
3359
|
if (navigator.clipboard && navigator.clipboard.writeText) {
|
package/page/index.html
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
<div>
|
|
18
18
|
<div class="title-row">
|
|
19
19
|
<h1>Agent Space Manager</h1>
|
|
20
|
-
<span class="plugin-version-badge" id="pluginVersionBadge">V1.0.
|
|
20
|
+
<span class="plugin-version-badge" id="pluginVersionBadge">V1.0.2</span>
|
|
21
21
|
</div>
|
|
22
22
|
<p class="subtitle" id="main-subtitle">Universal Multi-IDE & Project Skill Orchestrator</p>
|
|
23
23
|
</div>
|
|
@@ -132,7 +132,7 @@
|
|
|
132
132
|
<div class="prompt-desc">
|
|
133
133
|
Ask your AI agent to enforce standard layouts, record upstream links, and install rules for component addendum/edits.
|
|
134
134
|
</div>
|
|
135
|
-
<button type="button" class="btn-copy-prompt" id="btnCopyStoragePrompt" title="Copy prompt for your AI agent to standardize Components Storage file structure, enforce upstream links, clean up plugins, enforce UTF-8 No BOM encoding, respect one-time rearrangement stability, preserve shared cross-agent communication folders, and install rules">Copy Prompt (V1.
|
|
135
|
+
<button type="button" class="btn-copy-prompt" id="btnCopyStoragePrompt" title="Copy prompt for your AI agent to standardize Components Storage file structure, enforce upstream links, clean up plugins, enforce UTF-8 No BOM encoding, respect one-time rearrangement stability, preserve shared cross-agent communication folders, maintain dynamic Smart Middleware intent rules, and install rules">Copy Prompt (V1.5)</button>
|
|
136
136
|
</div>
|
|
137
137
|
|
|
138
138
|
<!-- Tile 4: Gateway Tool Optimization (Adjustable Cap with "Default" button) -->
|
|
@@ -62,6 +62,279 @@ function recordFailure(error, contextInfo = {}) {
|
|
|
62
62
|
|
|
63
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
64
|
|
|
65
|
+
function escapeRegex(str) {
|
|
66
|
+
return String(str).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export const BUILTIN_INTENT_RULES = [
|
|
70
|
+
{
|
|
71
|
+
id: "reverse_engineering",
|
|
72
|
+
toolPattern: /(^|[_-])(re|reverse|binary|disasm|decompile|gdb|frida|rizin)([_-]|$)/i,
|
|
73
|
+
intentPattern: /(reverse|binary|disassembl|decompile|pe|elf|macho|dll|exe|instruction|register|gdb|frida|rizin|assembly|opcode|demangle|symbols)/i,
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
id: "web_scraping",
|
|
77
|
+
toolPattern: /(crawl|scrape|stagehand|crw)/i,
|
|
78
|
+
intentPattern: /(scrape|crawl|website|browser|webpage|url|http|extract|html|dom|click|navigate|page)/i,
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
id: "gemini_docs",
|
|
82
|
+
toolPattern: /(gemini|docs|knowledge)/i,
|
|
83
|
+
intentPattern: /(doc|documentation|api|sdk|reference|search|lookup|guide|gemini)/i,
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
id: "dart_flutter",
|
|
87
|
+
toolPattern: /(dart|flutter)/i,
|
|
88
|
+
intentPattern: /(dart|flutter|pubspec|widget|stateful|stateless)/i,
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
id: "bio_chem",
|
|
92
|
+
toolPattern: /(bio|protein|chem|pdb|structure)/i,
|
|
93
|
+
intentPattern: /(protein|amino|structure|alphafold|pdb|dna|rna|gene|sequence|molecular|chembl|biology)/i,
|
|
94
|
+
},
|
|
95
|
+
];
|
|
96
|
+
|
|
97
|
+
export function compileCustomIntentRules(raw) {
|
|
98
|
+
if (!raw) return [];
|
|
99
|
+
const rules = [];
|
|
100
|
+
|
|
101
|
+
const entries = Array.isArray(raw)
|
|
102
|
+
? raw
|
|
103
|
+
: typeof raw === "object"
|
|
104
|
+
? Object.entries(raw).map(([key, val]) => ({ id: key, ...(val || {}) }))
|
|
105
|
+
: [];
|
|
106
|
+
|
|
107
|
+
for (const item of entries) {
|
|
108
|
+
if (!item || typeof item !== "object") continue;
|
|
109
|
+
|
|
110
|
+
let toolRegex = null;
|
|
111
|
+
const rawTools = item.toolPattern || item.toolPatterns || item.tools || item.tool;
|
|
112
|
+
if (rawTools instanceof RegExp) {
|
|
113
|
+
toolRegex = rawTools;
|
|
114
|
+
} else if (Array.isArray(rawTools) && rawTools.length > 0) {
|
|
115
|
+
const parts = rawTools.map((t) => (typeof t === "string" ? escapeRegex(t.trim()) : "")).filter(Boolean);
|
|
116
|
+
if (parts.length > 0) {
|
|
117
|
+
toolRegex = new RegExp(`(${parts.join("|")})`, "i");
|
|
118
|
+
}
|
|
119
|
+
} else if (typeof rawTools === "string" && rawTools.trim()) {
|
|
120
|
+
const trimmed = rawTools.trim();
|
|
121
|
+
toolRegex = /[\^$|*+?]/.test(trimmed)
|
|
122
|
+
? new RegExp(trimmed, "i")
|
|
123
|
+
: new RegExp(escapeRegex(trimmed), "i");
|
|
124
|
+
} else if (item.id && typeof item.id === "string") {
|
|
125
|
+
toolRegex = new RegExp(escapeRegex(item.id.trim()), "i");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
let intentRegex = null;
|
|
129
|
+
const rawIntents = item.intentPattern || item.intentKeywords || item.keywords || item.intents;
|
|
130
|
+
if (rawIntents instanceof RegExp) {
|
|
131
|
+
intentRegex = rawIntents;
|
|
132
|
+
} else if (Array.isArray(rawIntents) && rawIntents.length > 0) {
|
|
133
|
+
const parts = rawIntents.map((k) => (typeof k === "string" ? escapeRegex(k.trim()) : "")).filter(Boolean);
|
|
134
|
+
if (parts.length > 0) {
|
|
135
|
+
toolRegex = toolRegex || new RegExp(`(${parts.join("|")})`, "i");
|
|
136
|
+
intentRegex = new RegExp(`(${parts.join("|")})`, "i");
|
|
137
|
+
}
|
|
138
|
+
} else if (typeof rawIntents === "string" && rawIntents.trim()) {
|
|
139
|
+
const trimmed = rawIntents.trim();
|
|
140
|
+
intentRegex = /[\^$|*+?]/.test(trimmed)
|
|
141
|
+
? new RegExp(trimmed, "i")
|
|
142
|
+
: new RegExp(escapeRegex(trimmed), "i");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (toolRegex && intentRegex) {
|
|
146
|
+
rules.push({
|
|
147
|
+
id: item.id || "custom",
|
|
148
|
+
toolPattern: toolRegex,
|
|
149
|
+
intentPattern: intentRegex,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return rules;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function autoSeedMiddlewareIntents(hubRoot) {
|
|
158
|
+
if (!hubRoot || !fs.existsSync(hubRoot)) return {};
|
|
159
|
+
const sharedDir = path.join(hubRoot, "shared");
|
|
160
|
+
const intentsPath = path.join(sharedDir, "middleware-intents.json");
|
|
161
|
+
if (fs.existsSync(intentsPath)) {
|
|
162
|
+
try {
|
|
163
|
+
const content = fs.readFileSync(intentsPath, "utf8").trim();
|
|
164
|
+
if (content) return JSON.parse(content);
|
|
165
|
+
} catch {}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const pluginsDir = path.join(hubRoot, "plugins");
|
|
169
|
+
if (!fs.existsSync(pluginsDir)) return {};
|
|
170
|
+
|
|
171
|
+
const intents = {};
|
|
172
|
+
try {
|
|
173
|
+
const entries = fs.readdirSync(pluginsDir);
|
|
174
|
+
for (const ent of entries) {
|
|
175
|
+
const pluginDir = path.join(pluginsDir, ent);
|
|
176
|
+
try {
|
|
177
|
+
const st = fs.statSync(pluginDir);
|
|
178
|
+
if (!st.isDirectory()) continue;
|
|
179
|
+
} catch {
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const pluginJsonPath = path.join(pluginDir, "plugin.json");
|
|
184
|
+
const mcpJsonPath = path.join(pluginDir, "mcp_config.json");
|
|
185
|
+
const toolPatterns = [ent.toLowerCase()];
|
|
186
|
+
const intentKeywords = new Set([ent.toLowerCase()]);
|
|
187
|
+
|
|
188
|
+
if (fs.existsSync(pluginJsonPath)) {
|
|
189
|
+
try {
|
|
190
|
+
const pj = JSON.parse(fs.readFileSync(pluginJsonPath, "utf8"));
|
|
191
|
+
if (pj.name) {
|
|
192
|
+
pj.name.split(/[^a-z0-9]+/i).filter((t) => t.length > 2).forEach((t) => intentKeywords.add(t.toLowerCase()));
|
|
193
|
+
}
|
|
194
|
+
if (pj.description) {
|
|
195
|
+
pj.description.split(/[^a-z0-9]+/i).filter((t) => t.length > 3).slice(0, 10).forEach((t) => intentKeywords.add(t.toLowerCase()));
|
|
196
|
+
}
|
|
197
|
+
if (pj.middleware?.intents) {
|
|
198
|
+
pj.middleware.intents.forEach((i) => intentKeywords.add(String(i).toLowerCase()));
|
|
199
|
+
}
|
|
200
|
+
} catch {}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (fs.existsSync(mcpJsonPath)) {
|
|
204
|
+
try {
|
|
205
|
+
const mcp = JSON.parse(fs.readFileSync(mcpJsonPath, "utf8"));
|
|
206
|
+
const servers = mcp.mcpServers || mcp.servers || {};
|
|
207
|
+
for (const sName of Object.keys(servers)) {
|
|
208
|
+
toolPatterns.push(sName.toLowerCase());
|
|
209
|
+
sName.split(/[^a-z0-9]+/i).filter((t) => t.length > 2).forEach((t) => intentKeywords.add(t.toLowerCase()));
|
|
210
|
+
}
|
|
211
|
+
} catch {}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const skillsDir = path.join(pluginDir, "skills");
|
|
215
|
+
if (fs.existsSync(skillsDir)) {
|
|
216
|
+
try {
|
|
217
|
+
for (const sEnt of fs.readdirSync(skillsDir)) {
|
|
218
|
+
toolPatterns.push(sEnt.toLowerCase());
|
|
219
|
+
sEnt.split(/[^a-z0-9]+/i).filter((t) => t.length > 2).forEach((t) => intentKeywords.add(t.toLowerCase()));
|
|
220
|
+
}
|
|
221
|
+
} catch {}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
intents[ent.toLowerCase()] = {
|
|
225
|
+
toolPatterns: Array.from(new Set(toolPatterns)),
|
|
226
|
+
intentKeywords: Array.from(intentKeywords),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (Object.keys(intents).length > 0) {
|
|
231
|
+
if (!fs.existsSync(sharedDir)) fs.mkdirSync(sharedDir, { recursive: true });
|
|
232
|
+
fs.writeFileSync(intentsPath, JSON.stringify(intents, null, 2), "utf8");
|
|
233
|
+
}
|
|
234
|
+
} catch (err) {
|
|
235
|
+
console.warn("Failed to auto-seed middleware intents:", err);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return intents;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export function trimMiddlewareIntent(hubRoot, pluginId) {
|
|
242
|
+
if (!hubRoot || !pluginId) return false;
|
|
243
|
+
const intentsPath = path.join(hubRoot, "shared", "middleware-intents.json");
|
|
244
|
+
if (!fs.existsSync(intentsPath)) return false;
|
|
245
|
+
|
|
246
|
+
try {
|
|
247
|
+
const content = fs.readFileSync(intentsPath, "utf8").trim();
|
|
248
|
+
if (!content) return false;
|
|
249
|
+
const data = JSON.parse(content);
|
|
250
|
+
const targetKey = String(pluginId).toLowerCase();
|
|
251
|
+
let changed = false;
|
|
252
|
+
|
|
253
|
+
if (data[targetKey]) {
|
|
254
|
+
delete data[targetKey];
|
|
255
|
+
changed = true;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
for (const [k, v] of Object.entries(data)) {
|
|
259
|
+
if (k.toLowerCase() === targetKey) {
|
|
260
|
+
delete data[k];
|
|
261
|
+
changed = true;
|
|
262
|
+
} else if (v && Array.isArray(v.toolPatterns)) {
|
|
263
|
+
const filtered = v.toolPatterns.filter((p) => String(p).toLowerCase() !== targetKey);
|
|
264
|
+
if (filtered.length !== v.toolPatterns.length) {
|
|
265
|
+
if (filtered.length === 0) {
|
|
266
|
+
delete data[k];
|
|
267
|
+
} else {
|
|
268
|
+
v.toolPatterns = filtered;
|
|
269
|
+
}
|
|
270
|
+
changed = true;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (changed) {
|
|
276
|
+
fs.writeFileSync(intentsPath, JSON.stringify(data, null, 2), "utf8");
|
|
277
|
+
return true;
|
|
278
|
+
}
|
|
279
|
+
} catch {}
|
|
280
|
+
return false;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
let cachedUserIntents = [];
|
|
284
|
+
let cachedUserIntentsAt = 0;
|
|
285
|
+
let lastIntentsFile = null;
|
|
286
|
+
let lastIntentsMtime = 0;
|
|
287
|
+
|
|
288
|
+
export function getCachedUserIntents(hubConfig) {
|
|
289
|
+
const now = Date.now();
|
|
290
|
+
const hubRoot = hubConfig?.hubRoot;
|
|
291
|
+
const intentsPath = hubRoot ? path.join(hubRoot, "shared", "middleware-intents.json") : null;
|
|
292
|
+
|
|
293
|
+
if (now - cachedUserIntentsAt < 2000 && lastIntentsFile === intentsPath) {
|
|
294
|
+
return cachedUserIntents;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
cachedUserIntentsAt = now;
|
|
298
|
+
lastIntentsFile = intentsPath;
|
|
299
|
+
|
|
300
|
+
if (!intentsPath || !fs.existsSync(intentsPath)) {
|
|
301
|
+
if (hubRoot && fs.existsSync(path.join(hubRoot, "plugins"))) {
|
|
302
|
+
const seeded = autoSeedMiddlewareIntents(hubRoot);
|
|
303
|
+
if (Object.keys(seeded).length > 0) {
|
|
304
|
+
cachedUserIntents = compileCustomIntentRules(seeded);
|
|
305
|
+
return cachedUserIntents;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
if (hubConfig?.smartMiddleware?.customIntents) {
|
|
309
|
+
cachedUserIntents = compileCustomIntentRules(hubConfig.smartMiddleware.customIntents);
|
|
310
|
+
return cachedUserIntents;
|
|
311
|
+
}
|
|
312
|
+
cachedUserIntents = [];
|
|
313
|
+
return cachedUserIntents;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
try {
|
|
317
|
+
const stat = fs.statSync(intentsPath);
|
|
318
|
+
if (stat.mtimeMs === lastIntentsMtime && cachedUserIntents.length > 0) {
|
|
319
|
+
return cachedUserIntents;
|
|
320
|
+
}
|
|
321
|
+
lastIntentsMtime = stat.mtimeMs;
|
|
322
|
+
|
|
323
|
+
const content = fs.readFileSync(intentsPath, "utf8").trim();
|
|
324
|
+
if (!content) {
|
|
325
|
+
cachedUserIntents = [];
|
|
326
|
+
return cachedUserIntents;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const parsed = JSON.parse(content);
|
|
330
|
+
cachedUserIntents = compileCustomIntentRules(parsed);
|
|
331
|
+
} catch {
|
|
332
|
+
if (!cachedUserIntents) cachedUserIntents = [];
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return cachedUserIntents;
|
|
336
|
+
}
|
|
337
|
+
|
|
65
338
|
export function onRequest(body, ctx) {
|
|
66
339
|
if (!body) return;
|
|
67
340
|
|
|
@@ -127,6 +400,12 @@ export function onRequest(body, ctx) {
|
|
|
127
400
|
return { ...body, tools: chatTools };
|
|
128
401
|
}
|
|
129
402
|
|
|
403
|
+
const optionIntents = ctx?.options?.customIntents
|
|
404
|
+
? compileCustomIntentRules(ctx.options.customIntents)
|
|
405
|
+
: [];
|
|
406
|
+
const userIntents = [...getCachedUserIntents(hubConfig), ...optionIntents];
|
|
407
|
+
const allIntentRules = [...BUILTIN_INTENT_RULES, ...userIntents];
|
|
408
|
+
|
|
130
409
|
const matchedTools = [...coreTools];
|
|
131
410
|
const fallbackTools = [];
|
|
132
411
|
|
|
@@ -145,25 +424,12 @@ export function onRequest(body, ctx) {
|
|
|
145
424
|
}
|
|
146
425
|
|
|
147
426
|
if (!isMatch) {
|
|
148
|
-
|
|
149
|
-
if (
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
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;
|
|
427
|
+
for (const rule of allIntentRules) {
|
|
428
|
+
if (rule.toolPattern && rule.intentPattern) {
|
|
429
|
+
if (rule.toolPattern.test(name) && rule.intentPattern.test(userText)) {
|
|
430
|
+
isMatch = true;
|
|
431
|
+
break;
|
|
432
|
+
}
|
|
167
433
|
}
|
|
168
434
|
}
|
|
169
435
|
}
|