@nathan-adk/dsh-rea-lazy 1.1.2 → 2.0.1

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/README.md CHANGED
@@ -1,56 +1,35 @@
1
- # @nathan-adk/dsh-rea-lazy
1
+ # @nathan-adk/dsh-rea-lazy v2.0.0
2
2
 
3
- REA 在 DeepSeek Harness(DSH)里的**按需启动配置层** —— DSH 侧专用。让 REA 的 263 个工具保持可搜索,但 `rea` 进程平时不运行、不烧后台 token。
3
+ 自包含的 REA 按需能力层 —— **DeepSeek Harness 专用,单包即可,无需第三方 capability-catalog**。
4
4
 
5
- ## 工作原理(v1.1.0 起自动探测)
5
+ ## 核心(全部自研,不依赖第三方)
6
+ - **紧凑索引**:263 个 REA 工具不进系统提示词,只留约 1.8KB 的族索引(族名+数量+代表名)。对比全量 670KB schema,省 token 显著。
7
+ - **3 个元工具**:`capability_search` / `capability_describe` / `capability_call`。schema 只在 describe 时按需进上下文。
8
+ - **磁盘缓存**:工具清单缓存到 `$DSH_HOME/capability-catalog/mcp-rea.json`,缓存命中时**不启动 REA**。
9
+ - **按需 spawn**:只有真正 `capability_call` 时才连接 REA;空闲 5 分钟自动断开。零后台进程、零后台 token。
10
+ - **每日更新检查**:每 24 小时用 HTTP 元数据查询 npm 上 `rea-agents` 的最新版本(不启动 REA、不耗 token、不进上下文),发现新版本写标记并提示。工具清单的真正刷新由用户主动触发(`ctx.reaRefresh()`),保持"无需求不启动"。
6
11
 
7
- 插件激活时自动探测本机 REA,按以下优先级:
8
-
9
- 1. 环境变量 `REA_COMMAND` —— 手动指定完整命令(最高优先级)
10
- 2. PATH 上的 `rea` 命令(标准 `npm install -g rea-agents` 安装)
11
- 3. 本机 `rea-agents/scripts/rea.mjs`(用当前 Node 运行时启动)
12
-
13
- 探测到后把 REA 注册到 `@kirkchinese/dsh-capability-catalog`,配置:
14
- - `catalogTtlMs`: 10 年 —— 目录缓存一旦生成就永不因陈旧而重新发现
15
- - `idleDisconnectMs`: 5 分钟 —— 调用完空闲即断开
16
- - `enabled: true` —— 工具留在目录里可搜索
17
-
18
- **没有硬编码路径,任何电脑都能用。** 目录缓存由首次发现自动生成(会短暂启动一次 rea),之后不再自动启动。
19
-
20
- ## 沿用了哪些上游项目
21
-
22
- 本包是薄配置层,不改、不重新分发上游:
23
-
24
- - [REA](https://github.com/morluto/rea) 的 `rea mcp` 标准输入输出接口(使用者自行安装 `rea-agents`)
25
- - [`@kirkchinese/dsh-capability-catalog`](https://github.com/kirkchinese/dsh-capability-catalog) 的懒加载能力目录(search / describe / call)
26
- - [`@kirkchinese/dsh-rea`](https://github.com/kirkchinese/dsh-capability-catalog) 整理的 14 个能力族与工具匹配规则(内联在引导插件中,源自其 MIT 授权的 `families.yml`)
27
-
28
- 上游项目均按其各自 MIT 许可授权,版权归各自作者。
29
-
30
- ## 对 REA 的影响 / 删除声明
31
-
32
- - 不修改 REA 仓库、npm 包或运行时文件
33
- - 不自动常驻:缓存命中后 `rea mcp` 只在真正 `capability_call` 工具时启动,空闲 5 分钟断开
34
- - 缓存写在 DSH 数据目录(`$DSH_HOME/capability-catalog`),不碰 REA 安装目录
35
- - 卸载本包只是移除这一行插件配置,可逆、无残留
36
-
37
- **如果本包对 REA 或你的环境造成任何影响,或希望我们停止发布/删除相关内容,可直接联系 GitHub: Nathan-ADK,我们会立即配合处理或下架。**
12
+ ## 与上游 REA 的关系
13
+ 沿用 REA(https://github.com/morluto/rea)的 `rea mcp` 标准接口与 14 个能力族规则(源自上游 MIT families.yml)。不修改、不重新分发 REA。若造成影响可联系 GitHub: Nathan-ADK 删除/下架。
38
14
 
39
15
  ## 安装
40
-
41
- 前置:先装能力目录 `@kirkchinese/dsh-capability-catalog`(本包依赖它的服务)。REA 可装可不装到 PATH —— 本包会自动探测;若探测不到,设 `REA_COMMAND` 即可。
42
-
43
16
  ```sh
44
- dsh plugin add @nathan-adk/dsh-capability-catalog
45
17
  dsh plugin add @nathan-adk/dsh-rea-lazy
46
- # 可选:REA_COMMAND="node /path/to/rea.mjs mcp"
18
+ # 可选:REA_COMMAND="node /path/to/rea.mjs mcp" 环境变量覆盖自动探测
19
+ ```
20
+ 自动探测顺序:REA_COMMAND → PATH 上的 rea → 本机 rea-agents/scripts/rea.mjs。
21
+
22
+ ## 配置
23
+ ```yaml
24
+ - id: dsh-rea-lazy
25
+ name: '@nathan-adk/dsh-rea-lazy'
26
+ config:
27
+ idleDisconnectMs: 300000
28
+ checkIntervalMs: 86400000 # 0 = 关闭每日检查
47
29
  ```
48
30
 
49
- ## 排障
50
-
51
- - 目录里看不到 REA 工具 → 确认能力目录已装;若自动探测失败,设 `REA_COMMAND` 后重启 DSH。
52
- - 首次使用会短暂启动一次 rea 建立目录缓存(属预期);此后不再自动启动。
31
+ ## 升级说明(从 v1.x)
32
+ v1.x 依赖第三方 `@kirkchinese/dsh-capability-catalog`;v2.0.0 已内置核心,请先移除第三方包再装本版,避免两套元工具冲突。
53
33
 
54
34
  ## 许可
55
-
56
- MIT —— 仅覆盖本配置层;上游 REA 与能力目录归各自作者所有。
35
+ MIT —— 仅覆盖本包;REA 与相关上游归各自作者所有。
package/cordis.patch.yml CHANGED
@@ -1,8 +1,9 @@
1
- # REA on-demand config layer for DeepSeek Harness (DSH-only).
2
- # Inserts the bootstrap plugin row; the plugin autodetects the local REA command
3
- # and registers it with @kirkchinese/dsh-capability-catalog. No local paths are
4
- # hardcoded. REA_COMMAND env overrides detection when needed.
1
+ # dsh-rea-lazy v2.0.0 — self-contained on-demand REA capability layer.
2
+ # Inserts our own plugin (no third-party capability-catalog needed).
3
+ # REA_COMMAND env / $DSH_HOME/.env overrides detection; otherwise PATH / local rea.mjs.
5
4
  - insert:
6
5
  - id: dsh-rea-lazy
7
6
  name: '@nathan-adk/dsh-rea-lazy'
8
- config: {}
7
+ config:
8
+ idleDisconnectMs: 300000
9
+ checkIntervalMs: 86400000
@@ -0,0 +1,92 @@
1
+ 'use strict';
2
+ /**
3
+ * Family assignment: curated glob rules first, then a name-derived heuristic.
4
+ * Reimplemented in-house from the published algorithm description (subject-word
5
+ * frequency clustering): verbs and generic words are ignored; a tool joins the
6
+ * family of its most widely shared subject word, small groups fold into misc.
7
+ */
8
+ const VERBS = new Set(('add analyze annotate apply batch build call capture check close collect compare correlate create current decode decompile delete demangle describe discover evaluate execute export extract fetch find get goto identify import inspect install instrument list load next observe open prev project pull push query read reconcile record recover remove resolve resume run search send set start stop trace uninstall unload unset update upload verify write').split(' '));
9
+ const GENERIC = new Set(('to with of and session status command console client target targets file files data info the a').split(' '));
10
+
11
+ function globToRegExp(glob) {
12
+ const e = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
13
+ return new RegExp('^' + e + '$', 'u');
14
+ }
15
+ function words(name) {
16
+ return String(name).split(/[_\-.:]+|(?<=[a-z0-9])(?=[A-Z])/u).map(w => w.toLowerCase()).filter(Boolean);
17
+ }
18
+ function subjectWords(name) {
19
+ const s = words(name).filter(w => !VERBS.has(w) && !GENERIC.has(w));
20
+ return s.length ? s : [words(name)[0] || 'misc'];
21
+ }
22
+
23
+ /** Assign every tool name to a family: curated rules win, heuristic fills the rest. */
24
+ function assignFamilies(names, rules, minSize = 3) {
25
+ const family = new Map();
26
+ const compiled = (rules || []).map(r => ({ r, p: (r.match || []).map(globToRegExp) }));
27
+ const unassigned = [];
28
+ for (const name of names) {
29
+ const hit = compiled.find(({ p }) => p.some(re => re.test(name)));
30
+ if (hit) family.set(name, hit.r.name);
31
+ else unassigned.push(name);
32
+ }
33
+ const subjects = new Map(unassigned.map(n => [n, subjectWords(n)]));
34
+ const freq = new Map();
35
+ for (const ws of subjects.values()) for (const w of new Set(ws)) freq.set(w, (freq.get(w) || 0) + 1);
36
+ for (const name of unassigned) {
37
+ let best, bestCount = 0;
38
+ for (const w of subjects.get(name) || []) {
39
+ const c = freq.get(w) || 0;
40
+ if (c > bestCount) { best = w; bestCount = c; }
41
+ }
42
+ family.set(name, best !== undefined && (bestCount >= minSize || unassigned.length < minSize) ? best : 'misc');
43
+ }
44
+ if (unassigned.length >= minSize) {
45
+ const sizes = new Map();
46
+ for (const n of unassigned) sizes.set(family.get(n), (sizes.get(family.get(n)) || 0) + 1);
47
+ for (const n of unassigned) if ((sizes.get(family.get(n)) || 0) < minSize) family.set(n, 'misc');
48
+ }
49
+ return family;
50
+ }
51
+
52
+ function summarizeFamilies(tools, families) {
53
+ const fam = new Map();
54
+ for (const rule of families || []) fam.set(rule.name, { name: rule.name, description: rule.description || '', count: 0, examples: [] });
55
+ for (const t of tools) {
56
+ const f = t.family || 'misc';
57
+ if (!fam.has(f)) fam.set(f, { name: f, description: '', count: 0, examples: [] });
58
+ const g = fam.get(f); g.count++;
59
+ if (g.examples.length < 4) g.examples.push(t.name);
60
+ }
61
+ return [...fam.values()].filter(f => f.count > 0).sort((a, b) => b.count - a.count);
62
+ }
63
+
64
+ function search(tools, query, limit = 8) {
65
+ const q = String(query || '').toLowerCase().trim();
66
+ if (!q) return [];
67
+ const scored = [];
68
+ for (const t of tools) {
69
+ const name = (t.name || '').toLowerCase();
70
+ const desc = (t.description || '').toLowerCase();
71
+ let score = 0;
72
+ if (name === q) score = 100;
73
+ else if (name.includes(q)) score = 60;
74
+ else if (q.split(/\s+/).some(w => name.includes(w))) score = 30;
75
+ else if (desc.includes(q)) score = 10;
76
+ if (score) scored.push({ t, score });
77
+ }
78
+ scored.sort((a, b) => b.score - a.score);
79
+ return scored.slice(0, limit).map(x => x.t);
80
+ }
81
+
82
+ function renderIndex(tools, families) {
83
+ const fams = summarizeFamilies(tools, families);
84
+ const lines = ['## REA capability catalog', '',
85
+ 'REA tools are NOT declared as native tools; their schemas are not in context.',
86
+ 'Find one with `capability_search`, read exact parameters with `capability_describe`, then run it with `capability_call`.',
87
+ 'When a task matches a family below, search before concluding no tool exists.', ''];
88
+ for (const f of fams) lines.push(`- ${f.name} (${f.count}): ${f.examples.join(', ')}${f.count > f.examples.length ? ', …' : ''}`);
89
+ return lines.join('\n');
90
+ }
91
+
92
+ module.exports = { assignFamilies, summarizeFamilies, search, renderIndex, globToRegExp };
@@ -0,0 +1,152 @@
1
+ 'use strict';
2
+ // Curated REA capability families (from upstream MIT families.yml, via dsh-rea).
3
+ module.exports = [
4
+ {
5
+ "name": "session",
6
+ "description": "open/close a target, provider binding, readiness and navigation context",
7
+ "match": [
8
+ "open_binary",
9
+ "close_binary",
10
+ "binary_session",
11
+ "binary_overview",
12
+ "get_navigation_context",
13
+ "list_documents",
14
+ "current_document",
15
+ "list_architectures"
16
+ ]
17
+ },
18
+ {
19
+ "name": "native-code",
20
+ "description": "functions, pseudocode, assembly, call graph and references in native binaries",
21
+ "match": [
22
+ "procedure_*",
23
+ "list_procedures",
24
+ "search_procedures",
25
+ "analyze_function",
26
+ "inspect_native_*",
27
+ "get_call_graph",
28
+ "trace_native_values",
29
+ "compare_functions"
30
+ ]
31
+ },
32
+ {
33
+ "name": "native-navigation",
34
+ "description": "addresses, bytes, strings, names, segments, comments and bookmarks",
35
+ "match": [
36
+ "*address*",
37
+ "read_bytes",
38
+ "search_bytes",
39
+ "list_strings",
40
+ "list_names",
41
+ "list_segments",
42
+ "*comment*",
43
+ "*bookmark*"
44
+ ]
45
+ },
46
+ {
47
+ "name": "native-formats",
48
+ "description": "Mach-O, PE, ELF, signatures, Go/Rust/Swift/ObjC metadata",
49
+ "match": [
50
+ "inspect_macho",
51
+ "inspect_pe_resources",
52
+ "inspect_binary_layout",
53
+ "inspect_signature",
54
+ "inspect_go_binary",
55
+ "inspect_rust_binary",
56
+ "*swift*",
57
+ "get_objc_*"
58
+ ]
59
+ },
60
+ {
61
+ "name": "javascript-electron",
62
+ "description": "JS/Electron apps, bundles, source maps, IPC and runtime tracing",
63
+ "match": [
64
+ "*javascript*",
65
+ "analyze_web_bundle",
66
+ "recover_javascript_sources",
67
+ "*electron*",
68
+ "trace_feature"
69
+ ]
70
+ },
71
+ {
72
+ "name": "web-browser",
73
+ "description": "live pages, network captures, screenshots and WebMCP",
74
+ "match": [
75
+ "*web*",
76
+ "capture_browser_scenario",
77
+ "list_browser_targets"
78
+ ]
79
+ },
80
+ {
81
+ "name": "android",
82
+ "description": "APKs, classes, methods, resources and app graphs",
83
+ "match": [
84
+ "*android*",
85
+ "inspect_apktool_client",
86
+ "*jeb*"
87
+ ]
88
+ },
89
+ {
90
+ "name": "adb-device",
91
+ "description": "attached Android devices over adb",
92
+ "match": [
93
+ "*adb*"
94
+ ]
95
+ },
96
+ {
97
+ "name": "managed-dotnet",
98
+ "description": ".NET assemblies, members, native boundaries and reconstruction",
99
+ "match": [
100
+ "*managed*"
101
+ ]
102
+ },
103
+ {
104
+ "name": "apple-bundles",
105
+ "description": "plists, keyed archives, asset catalogs, Interface Builder",
106
+ "match": [
107
+ "inspect_plist",
108
+ "inspect_keyed_archive",
109
+ "inspect_asset_catalog",
110
+ "decode_interface_builder"
111
+ ]
112
+ },
113
+ {
114
+ "name": "artifacts",
115
+ "description": "archives, packages, firmware, SQLite and file-level comparisons",
116
+ "match": [
117
+ "inspect_artifact",
118
+ "extract_artifact",
119
+ "compare_artifacts",
120
+ "inspect_firmware_regions"
121
+ ]
122
+ },
123
+ {
124
+ "name": "runtime-debug",
125
+ "description": "Frida, GDB and rizin debugging, process and native UI capture",
126
+ "match": [
127
+ "*frida*",
128
+ "*gdb*",
129
+ "*rizin_debug*",
130
+ "capture_process_scenario",
131
+ "observe_native_*"
132
+ ]
133
+ },
134
+ {
135
+ "name": "captures-signals",
136
+ "description": "pcap/pcapng packets and recorded logic signals",
137
+ "match": [
138
+ "*pcap*",
139
+ "*packet*",
140
+ "*signal*"
141
+ ]
142
+ },
143
+ {
144
+ "name": "evidence",
145
+ "description": "evidence bundles, residual unknowns and reconstruction verification",
146
+ "match": [
147
+ "*evidence*",
148
+ "*unknown*",
149
+ "*reconstruction*"
150
+ ]
151
+ }
152
+ ];
@@ -0,0 +1,148 @@
1
+ 'use strict';
2
+ /**
3
+ * Minimal stdio MCP source: on-disk catalog cache + on-demand connection.
4
+ * - start(): load cached tool list; spawn only when cache is missing/stale.
5
+ * - ensureClient(): connect on a REAL tool call; idle timer disconnects.
6
+ * No network / no token cost at startup when the cache key matches.
7
+ */
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const crypto = require('crypto');
11
+
12
+ function cacheKey(config) {
13
+ const identity = {
14
+ transport: 'stdio', command: config.command, args: config.args,
15
+ env: Object.entries(config.env || {}).sort(),
16
+ cwd: config.cwd, url: config.url, headers: Object.keys(config.headers || {}).sort(),
17
+ };
18
+ return crypto.createHash('sha256').update(JSON.stringify(identity)).digest('hex');
19
+ }
20
+
21
+ class McpSource {
22
+ constructor(config, cachePath) {
23
+ this.config = config;
24
+ this.cachePath = cachePath;
25
+ this.name = config.name || 'rea';
26
+ this.client = null;
27
+ this.connecting = null;
28
+ this.catalog = null;
29
+ this.inFlight = 0;
30
+ this.idleTimer = null;
31
+ this.disposed = false;
32
+ }
33
+ get configuredEnabled() { return this.config.enabled !== false; }
34
+ get connected() { return !!this.client; }
35
+ get toolCount() { return this.catalog ? this.catalog.tools.length : 0; }
36
+
37
+ async start() {
38
+ try {
39
+ const c = JSON.parse(fs.readFileSync(this.cachePath, 'utf8'));
40
+ if (c.version === 1 && c.key === cacheKey(this.config) && Array.isArray(c.tools)) {
41
+ this.catalog = c; // cache hit: NO spawn
42
+ return;
43
+ }
44
+ } catch (_) {}
45
+ // cache missing/mismatch: do a one-time discovery (spawn) to build the catalog
46
+ await this.discover(false).catch(() => {});
47
+ }
48
+
49
+ _loadMcp() {
50
+ // Resolve the MCP client from our own deps first, then from the DSH host
51
+ // node_modules tree (plugins may live outside that tree).
52
+ if (!this._mcp) {
53
+ try { this._mcp = { StdioClientTransport: require('@modelcontextprotocol/client/stdio').StdioClientTransport, Client: require('@modelcontextprotocol/client').Client }; }
54
+ catch (_) {
55
+ const { createRequire } = require('module');
56
+ const { homedir } = require('os');
57
+ const path = require('path');
58
+ const candidates = [
59
+ path.join(__dirname, '../../node_modules/@modelcontextprotocol/client'),
60
+ path.join(__dirname, '../../../node_modules/@modelcontextprotocol/client'),
61
+ path.join(__dirname, '../../../e-drive-plugin-host/node_modules/@modelcontextprotocol/client'),
62
+ path.join(homedir(), '.dsh', 'profiles', 'desktop', 'node_modules', '@modelcontextprotocol', 'client'),
63
+ ];
64
+ for (const c of candidates) {
65
+ try { const r = createRequire(c + '/x.js'); this._mcp = { StdioClientTransport: r('@modelcontextprotocol/client/stdio').StdioClientTransport, Client: r('@modelcontextprotocol/client').Client }; break } catch (_) {}
66
+ }
67
+ }
68
+ }
69
+ if (!this._mcp) throw new Error('dsh-rea-lazy: @modelcontextprotocol/client not found');
70
+ return this._mcp;
71
+ }
72
+
73
+ async _transport() {
74
+ const { StdioClientTransport, Client } = this._loadMcp();
75
+ const transport = new StdioClientTransport({
76
+ command: this.config.command,
77
+ args: this.config.args || [],
78
+ env: { ...process.env, ...(this.config.env || {}) },
79
+ stderr: 'ignore',
80
+ });
81
+ const client = new Client({ name: 'dsh-rea-lazy', version: '2.0.0' });
82
+ await client.connect(transport);
83
+ return client;
84
+ }
85
+
86
+ async discover(keepAlive) {
87
+ const client = await this._transport();
88
+ try {
89
+ const tools = [];
90
+ let cursor;
91
+ do {
92
+ const page = await client.listTools(cursor ? { cursor } : {});
93
+ tools.push(...(page.tools || []));
94
+ cursor = page.nextCursor;
95
+ } while (cursor);
96
+ this.catalog = { version: 1, key: cacheKey(this.config), fetchedAt: Date.now(), tools };
97
+ fs.mkdirSync(path.dirname(this.cachePath), { recursive: true });
98
+ const tmp = this.cachePath + '.' + process.pid + '.tmp';
99
+ fs.writeFileSync(tmp, JSON.stringify(this.catalog), { mode: 0o600 });
100
+ fs.renameSync(tmp, this.cachePath);
101
+ } finally {
102
+ if (!keepAlive) await this.disconnect();
103
+ }
104
+ }
105
+
106
+ async ensureClient() {
107
+ this._clearIdle();
108
+ if (this.client) return this.client;
109
+ if (!this.connecting) {
110
+ this.connecting = this._transport().then(c => {
111
+ this.client = c;
112
+ return c;
113
+ }).finally(() => { this.connecting = null; });
114
+ }
115
+ return this.connecting;
116
+ }
117
+
118
+ async call(name, args) {
119
+ const client = await this.ensureClient();
120
+ this.inFlight++;
121
+ try {
122
+ const r = await client.callTool({ name, arguments: args });
123
+ const content = Array.isArray(r.content) ? r.content : [];
124
+ return { content, isError: r.isError === true };
125
+ } finally {
126
+ this.inFlight--;
127
+ this._scheduleIdle();
128
+ }
129
+ }
130
+
131
+ _clearIdle() { if (this.idleTimer) { clearTimeout(this.idleTimer); this.idleTimer = null; } }
132
+ _scheduleIdle() {
133
+ this._clearIdle();
134
+ const ms = this.config.idleDisconnectMs || 300000;
135
+ if (this.inFlight === 0 && this.client) {
136
+ this.idleTimer = setTimeout(() => { this.disconnect().catch(() => {}); }, ms);
137
+ this.idleTimer.unref && this.idleTimer.unref();
138
+ }
139
+ }
140
+ async disconnect() {
141
+ this._clearIdle();
142
+ const c = this.client; this.client = null;
143
+ if (c) { try { await c.close(); } catch (_) {} }
144
+ }
145
+ async dispose() { this.disposed = true; await this.disconnect(); }
146
+ }
147
+
148
+ module.exports = { McpSource, cacheKey };
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+ /** Register the three lazy catalog meta-tools (plain tool objects for ctx.tools.register). */
3
+ function createTools({ source, families, limits = {} }) {
4
+ const { search } = require('./catalog');
5
+ const tools = () => (source.catalog && source.catalog.tools) || [];
6
+ const find = (id) => tools().find(t => t.name === id || `mcp:rea/${t.name}` === id);
7
+ const brief = (t) => `- mcp:rea/${t.name} [${t.family || 'misc'}, params ${(JSON.stringify(t.inputSchema||{}).length)} B] ${String(t.description || '').slice(0, 110)}`;
8
+ const textRender = (_a, v) => ({ text: v.text });
9
+ const OUT = { schema: { type:'object', properties:{ text:{type:'string'} }, required:['text'], additionalProperties:false }, render: textRender };
10
+
11
+ const searchTool = {
12
+ name: 'capability_search',
13
+ description: 'Search the REA capability catalog by keywords or family. Returns ids with one-line summaries; read exact parameters with capability_describe before calling.',
14
+ parameters: { type:'object', properties:{
15
+ query:{type:'string',description:'Keywords or a short description of the task'},
16
+ family:{type:'string',description:'Restrict to one family'},
17
+ limit:{type:'integer',minimum:1,maximum:limits.maxSearch||60,description:'Maximum results'},
18
+ }, required:['query'], additionalProperties:false },
19
+ output: OUT,
20
+ execute: async ({ query, family, limit }) => {
21
+ let list = tools();
22
+ if (family) list = list.filter(t => (t.family||'misc') === family);
23
+ const hits = search(list, query, Math.min(limit||8, limits.maxSearch||60));
24
+ return { text: hits.length ? hits.map(brief).join('\n') : 'No capability matched.' };
25
+ },
26
+ };
27
+ const describeTool = {
28
+ name: 'capability_describe',
29
+ description: 'Read the exact JSON Schema of one REA capability (loaded into context only on demand).',
30
+ parameters: { type:'object', properties:{ id:{type:'string',description:'Capability id, e.g. mcp:rea/list_procedures'} }, required:['id'], additionalProperties:false },
31
+ output: OUT,
32
+ execute: async ({ id }) => {
33
+ const t = find(id);
34
+ if (!t) return { text:`Unknown capability: ${id}` };
35
+ return { text:`mcp:rea/${t.name}\n${t.description||''}\n\nParameters (exact JSON Schema):\n${JSON.stringify(t.inputSchema||{},null,2)}` };
36
+ },
37
+ };
38
+ const callTool = {
39
+ name: 'capability_call',
40
+ description: 'Call one REA capability. The REA process starts on demand and disconnects when idle.',
41
+ parameters: { type:'object', properties:{
42
+ id:{type:'string',description:'Capability id'},
43
+ arguments:{type:'object',additionalProperties:true,description:'Tool arguments (read them with capability_describe first)'},
44
+ }, required:['id'], additionalProperties:false },
45
+ output: OUT,
46
+ execute: async ({ id, arguments: args }) => {
47
+ const t = find(id);
48
+ if (!t) return { text:`Unknown capability: ${id}` };
49
+ const r = await source.call(t.name, args||{});
50
+ const out = r.content.map(c => c.text || (c.structuredContent ? JSON.stringify(c.structuredContent) : '')).join('\n');
51
+ return { text: out.slice(0, limits.callMaxChars||120000) || '(no output)' };
52
+ },
53
+ };
54
+ return [searchTool, describeTool, callTool];
55
+ }
56
+ module.exports = { createTools };
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+ /**
3
+ * Daily update check for REA tooling.
4
+ * Pure HTTP metadata check against the npm registry: no REA spawn, no token
5
+ * cost, no context injection. Writes a marker file only when a new upstream
6
+ * version is seen. Tool-list refresh remains user-triggered (via refresh()).
7
+ */
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const https = require('https');
11
+
12
+ function checkRegistry(pkg) {
13
+ return new Promise((resolve) => {
14
+ const req = https.get({ host: 'registry.npmjs.org', path: '/' + encodeURIComponent(pkg), headers: { 'User-Agent': 'dsh-rea-lazy' }, timeout: 8000 }, (res) => {
15
+ let d = ''; res.on('data', c => d += c);
16
+ res.on('end', () => { try { const j = JSON.parse(d); resolve(j['dist-tags'] && j['dist-tags'].latest || null); } catch (_) { resolve(null); } });
17
+ });
18
+ req.on('error', () => resolve(null));
19
+ req.on('timeout', () => { req.destroy(); resolve(null); });
20
+ });
21
+ }
22
+
23
+ function createUpdater({ cacheDir, markerPath, intervalMs = 86400000, logger }) {
24
+ let timer = null;
25
+ let lastVersion = null;
26
+ try { const m = JSON.parse(fs.readFileSync(markerPath, 'utf8')); lastVersion = m.lastVersion || null; } catch (_) {}
27
+ async function check() {
28
+ const latest = await checkRegistry('rea-agents');
29
+ if (!latest || latest === lastVersion) return;
30
+ lastVersion = latest;
31
+ try {
32
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true });
33
+ fs.writeFileSync(markerPath, JSON.stringify({ lastVersion: latest, checkedAt: new Date().toISOString() }), 'utf8');
34
+ } catch (_) {}
35
+ try { logger && logger.info && logger.info(`[dsh-rea-lazy] upstream rea-agents ${latest} available; tool catalog can be refreshed on demand`); } catch (_) {}
36
+ }
37
+ function start() {
38
+ if (intervalMs <= 0) return;
39
+ check().catch(() => {});
40
+ timer = setInterval(() => check().catch(() => {}), intervalMs);
41
+ if (timer.unref) timer.unref();
42
+ }
43
+ function stop() { if (timer) { clearInterval(timer); timer = null; } }
44
+ return { start, stop, check };
45
+ }
46
+
47
+ module.exports = { createUpdater };
package/lib/index.js CHANGED
@@ -1,226 +1,30 @@
1
1
  'use strict';
2
2
  /**
3
- * dsh-rea-lazy bootstrap (zero dependency).
4
- * Detects a usable REA command at activation time and registers it with the
5
- * capability catalog. No local paths are hardcoded: resolution order is
6
- * REA_COMMAND env > "rea" on PATH > bundled rea-agents via process.execPath
7
- * The server is configured with a 10-year catalog TTL and idle disconnect, so
8
- * once the tool catalog is cached, rea mcp never starts in the background.
3
+ * dsh-rea-lazy v2.0.0 — self-contained on-demand REA capability layer.
4
+ * Includes its own compact-index + search/describe/call meta-tools,
5
+ * on-disk catalog cache and on-demand spawn. No third-party catalog required.
9
6
  */
10
7
  const fs = require('fs');
11
8
  const path = require('path');
9
+ const os = require('os');
12
10
  const { spawnSync } = require('child_process');
13
-
14
- const FAMILIES = [
15
- {
16
- "name": "session",
17
- "description": "open/close a target, provider binding, readiness and navigation context",
18
- "match": [
19
- "open_binary",
20
- "close_binary",
21
- "binary_session",
22
- "binary_overview",
23
- "get_navigation_context",
24
- "list_documents",
25
- "current_document",
26
- "list_architectures"
27
- ]
28
- },
29
- {
30
- "name": "native-code",
31
- "description": "functions, pseudocode, assembly, call graph and references in native binaries (Hopper/Ghidra/IDA)",
32
- "match": [
33
- "procedure_*",
34
- "list_procedures",
35
- "search_procedures",
36
- "current_procedure",
37
- "resolve_containing_procedure",
38
- "analyze_function",
39
- "batch_decompile",
40
- "read_function_instructions",
41
- "get_call_graph",
42
- "build_call_path",
43
- "trace_call_path",
44
- "xrefs",
45
- "find_xrefs_to_name",
46
- "resolve_native_call_targets",
47
- "trace_native_values",
48
- "compare_functions",
49
- "inspect_native_*",
50
- "inspect_address_context"
51
- ]
52
- },
53
- {
54
- "name": "native-navigation",
55
- "description": "addresses, bytes, strings, names, segments, comments and bookmarks",
56
- "match": [
57
- "*address*",
58
- "goto_address",
59
- "next_address",
60
- "prev_address",
61
- "read_bytes",
62
- "search_bytes",
63
- "list_strings",
64
- "search_strings",
65
- "list_names",
66
- "list_segments",
67
- "*comment*",
68
- "*bookmark*",
69
- "annotate_native_function"
70
- ]
71
- },
72
- {
73
- "name": "native-formats",
74
- "description": "Mach-O, PE, ELF layout, signatures, Go/Rust/Swift/ObjC metadata, objdump and rizin",
75
- "match": [
76
- "inspect_macho",
77
- "inspect_pe_resources",
78
- "inspect_binary_layout",
79
- "inspect_signature",
80
- "inspect_go_binary",
81
- "inspect_rust_binary",
82
- "*swift*",
83
- "get_objc_*",
84
- "inspect_native_dispatch_metadata",
85
- "inspect_with_objdump",
86
- "execute_rizin_command",
87
- "cutter_command",
88
- "list_cutter_sessions",
89
- "trace_dylib_resolution",
90
- "inspect_dart_aot",
91
- "identify_flutter_build",
92
- "inspect_wasm_artifact",
93
- "compare_wasm_interfaces",
94
- "inspect_evm_interface"
95
- ]
96
- },
97
- {
98
- "name": "javascript-electron",
99
- "description": "JavaScript/Electron apps, bundles, source maps, IPC and runtime tracing",
100
- "match": [
101
- "*javascript*",
102
- "analyze_web_bundle",
103
- "recover_javascript_sources",
104
- "compare_source_to_bundle",
105
- "compare_bundles",
106
- "*electron*",
107
- "trace_application_feature",
108
- "trace_feature",
109
- "compare_application_versions"
110
- ]
111
- },
112
- {
113
- "name": "web-browser",
114
- "description": "live pages through a Chrome-family browser, network captures, screenshots and WebMCP",
115
- "match": [
116
- "*web*",
117
- "capture_browser_scenario",
118
- "list_browser_targets"
119
- ]
120
- },
121
- {
122
- "name": "android",
123
- "description": "APKs, classes, methods, resources (JADX, Apktool, JEB) and app graphs",
124
- "match": [
125
- "*android*",
126
- "inspect_apktool_client",
127
- "*jeb*"
128
- ]
129
- },
130
- {
131
- "name": "adb-device",
132
- "description": "attached Android devices over adb: packages, files, logs, screens and app control",
133
- "match": [
134
- "*adb*"
135
- ]
136
- },
137
- {
138
- "name": "managed-dotnet",
139
- "description": ".NET assemblies, members, native boundaries and reconstruction",
140
- "match": [
141
- "*managed*"
142
- ]
143
- },
144
- {
145
- "name": "apple-bundles",
146
- "description": "plists, keyed archives, asset catalogs, Interface Builder and Apple/Harmony app graphs",
147
- "match": [
148
- "inspect_plist",
149
- "inspect_keyed_archive",
150
- "inspect_asset_catalog",
151
- "decode_interface_builder",
152
- "project_apple_application_graph",
153
- "project_harmony_application_graph"
154
- ]
155
- },
156
- {
157
- "name": "artifacts",
158
- "description": "archives, packages, firmware, SQLite and file-level comparisons",
159
- "match": [
160
- "inspect_artifact",
161
- "extract_artifact",
162
- "compare_artifacts",
163
- "inspect_firmware_regions",
164
- "extract_firmware",
165
- "inspect_sqlite_database",
166
- "inspect_analysis_view"
167
- ]
168
- },
169
- {
170
- "name": "runtime-debug",
171
- "description": "Frida, GDB and rizin debugging, process and native UI capture, recorded crashes",
172
- "match": [
173
- "*frida*",
174
- "*gdb*",
175
- "*rizin_debug*",
176
- "capture_process_scenario",
177
- "compare_process_captures",
178
- "observe_native_*",
179
- "capture_native_ui_scenario",
180
- "trace_native_ui_action",
181
- "inspect_recorded_crash",
182
- "correlate_static_and_runtime",
183
- "find_changed_behavior"
184
- ]
185
- },
186
- {
187
- "name": "captures-signals",
188
- "description": "pcap/pcapng packets and recorded logic signals",
189
- "match": [
190
- "*pcap*",
191
- "*packet*",
192
- "*signal*"
193
- ]
194
- },
195
- {
196
- "name": "evidence",
197
- "description": "evidence bundles, residual unknowns and reconstruction verification",
198
- "match": [
199
- "*evidence*",
200
- "*unknown*",
201
- "*reconstruction*"
202
- ]
203
- }
204
- ];
11
+ const { McpSource, cacheKey } = require('./core/mcp-source');
12
+ const { renderIndex, assignFamilies } = require('./core/catalog');
13
+ const { createTools } = require('./core/tools');
14
+ const { createUpdater } = require('./core/updater');
205
15
 
206
16
  function which(name) {
207
17
  try {
208
18
  const cmd = process.platform === 'win32' ? 'where' : 'which';
209
19
  const r = spawnSync(cmd, [name], { encoding: 'utf8', timeout: 3000 });
210
- if (r.status === 0 && r.stdout) {
211
- const line = String(r.stdout).split(/\r?\n/).find(Boolean);
212
- if (line) return line.trim();
213
- }
20
+ if (r.status === 0 && r.stdout) return String(r.stdout).split(/\r?\n/).find(Boolean).trim();
214
21
  } catch (_) {}
215
22
  return null;
216
23
  }
217
-
218
24
  function readEnvFile() {
219
- // DSH injects $DSH_HOME/.env into the process at launch; read it here too so
220
- // detection also works in plain Node / tests. No hardcoded paths.
221
25
  try {
222
- const home = process.env.DSH_HOME || require('path').join(require('os').homedir(), '.dsh');
223
- const f = require('path').join(home, '.env');
26
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
27
+ const f = path.join(home, '.env');
224
28
  if (!fs.existsSync(f)) return {};
225
29
  const out = {};
226
30
  for (const line of fs.readFileSync(f, 'utf8').split(/\r?\n/)) {
@@ -230,58 +34,83 @@ function readEnvFile() {
230
34
  return out;
231
35
  } catch (_) { return {}; }
232
36
  }
233
-
234
37
  function findRea() {
235
- // 1) explicit override (process env first, then DSH .env)
236
38
  const envCmd = process.env.REA_COMMAND || readEnvFile().REA_COMMAND;
237
39
  if (envCmd && envCmd.trim()) {
238
- const parts = envCmd.trim().split(/\s+/);
239
- return { command: parts[0], args: parts.slice(1) };
40
+ const p = envCmd.trim().split(/\s+/);
41
+ return { command: p[0], args: p.slice(1) };
240
42
  }
241
- // 2) on PATH
242
43
  const onPath = which('rea');
243
44
  if (onPath) return { command: onPath, args: ['mcp'] };
244
- // 3) rea-agents installed near this package / in the DSH profile
245
45
  const roots = [
246
46
  path.join(__dirname, '..', 'node_modules', 'rea-agents'),
247
47
  path.join(process.cwd(), 'node_modules', 'rea-agents'),
48
+ path.resolve(__dirname, '../../../node_modules/rea-agents'),
248
49
  ];
249
50
  for (const root of roots) {
250
51
  const entry = path.join(root, 'scripts', 'rea.mjs');
251
- if (fs.existsSync(entry)) {
252
- return { command: process.execPath, args: [entry, 'mcp'] };
253
- }
52
+ if (fs.existsSync(entry)) return { command: process.execPath, args: [entry, 'mcp'] };
254
53
  }
255
54
  return null;
256
55
  }
257
56
 
57
+ const FAMILIES = require('./core/families');
58
+
258
59
  async function apply(ctx, config = {}) {
259
60
  const found = findRea();
260
61
  if (!found) {
261
- ctx.logger?.warn('[dsh-rea-lazy] no REA executable found; set REA_COMMAND to enable');
62
+ (ctx.logger && ctx.logger.warn) && ctx.logger.warn('[dsh-rea-lazy] no REA found; set REA_COMMAND');
262
63
  return;
263
64
  }
65
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
66
+ const cacheDir = config.cacheDir || process.env.REA_CACHE_DIR || path.join(home, 'capability-catalog');
67
+ const cachePath = path.join(cacheDir, 'mcp-rea.json');
264
68
  const server = {
265
- name: 'rea',
266
- title: 'REA reverse engineering (on-demand)',
267
- description: '263 REA tools via the lazy capability catalog; the rea process starts only on an actual tool call.',
268
- enabled: true,
269
- transport: 'stdio',
270
- command: found.command,
271
- args: found.args,
272
- // McpServerSchema defaults: cacheKey() calls Object.entries(config.env)
273
- // and Object.keys(config.headers) directly, so these must never be undefined.
274
- env: {},
275
- headers: {},
276
- catalogTtlMs: 315360000000,
277
- idleDisconnectMs: 300000,
278
- callTimeoutMs: 600000,
279
- discoveryTimeoutMs: 60000,
280
- families: FAMILIES,
281
- ...config,
69
+ name: 'rea', command: found.command, args: found.args, env: config.env || {},
70
+ headers: config.headers || {}, idleDisconnectMs: config.idleDisconnectMs || 300000,
282
71
  };
283
- const remove = await ctx.capabilityCatalogServers.addMcpServer(server);
284
- ctx.effect(() => () => { try { remove && remove(); } catch (_) {} }, 'dsh-rea-lazy.server');
72
+ const source = new McpSource(server, cachePath);
73
+ await source.start(); // cache hit = no spawn; miss = one discovery
74
+ // Enrich cached tools with families (curated rules + in-house heuristic) so the
75
+ // compact index shows the full family set (curated + derived, ~24 families).
76
+ if (source.catalog && Array.isArray(source.catalog.tools)) {
77
+ const fm = assignFamilies(source.catalog.tools.map(t => t.name), FAMILIES);
78
+ for (const t of source.catalog.tools) if (!t.family) t.family = fm.get(t.name) || 'misc';
79
+ }
80
+ ctx.effect(() => () => source.dispose(), 'dsh-rea-lazy.source');
81
+
82
+ // register three meta-tools
83
+ if (ctx.tools && ctx.tools.register) {
84
+ for (const t of createTools({ source, families: FAMILIES, ctx, limits: config.limits })) {
85
+ try { ctx.tools.register(t); } catch (_) {}
86
+ }
87
+ }
88
+ // inject compact index into system prompt (section API, like the reference catalog)
89
+ if (ctx.systemPrompt && ctx.systemPrompt.section) {
90
+ try {
91
+ ctx.systemPrompt.section({
92
+ name: 'dsh-rea-lazy',
93
+ order: 40,
94
+ interpolate: false,
95
+ text: () => renderIndex(source.catalog ? source.catalog.tools : [], FAMILIES),
96
+ });
97
+ } catch (_) {}
98
+ }
99
+
100
+ // daily upstream check (no spawn, no token)
101
+ const updater = createUpdater({
102
+ cacheDir, markerPath: path.join(cacheDir, 'update-marker.json'),
103
+ intervalMs: config.checkIntervalMs === undefined ? 86400000 : config.checkIntervalMs,
104
+ logger: ctx.logger,
105
+ });
106
+ updater.start();
107
+ ctx.effect(() => () => updater.stop(), 'dsh-rea-lazy.updater');
108
+
109
+ // FIX: DSH forbids assigning undeclared ctx properties; declare via provide.
110
+ // Placed after all tool/prompt registration so an early failure cannot leave a half-loaded plugin.
111
+ if (ctx.provide) {
112
+ ctx.provide('reaRefresh', async () => { await source.discover(true); return source.toolCount; });
113
+ }
285
114
  }
286
115
 
287
- module.exports = { name: 'dsh-rea-lazy', inject: ['capabilityCatalogServers'], apply, findRea };
116
+ module.exports = { name: 'dsh-rea-lazy', inject: ['tools', 'systemPrompt'], apply, findRea, cacheKey };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nathan-adk/dsh-rea-lazy",
3
- "version": "1.1.2",
4
- "description": "On-demand REA for DeepSeek Harness: auto-detects the local REA executable and registers it as a lazy capability, so 263 REA tools stay searchable while rea mcp never runs in the background. DSH-only.",
3
+ "version": "2.0.1",
4
+ "description": "Self-contained on-demand REA capability layer for DeepSeek Harness: built-in compact index + search/describe/call meta-tools + on-disk cache + on-demand spawn + daily upstream check. No third-party catalog required.",
5
5
  "keywords": [
6
6
  "deepseek-harness",
7
7
  "dsh",
@@ -28,9 +28,6 @@
28
28
  "patch": "./cordis.patch.yml"
29
29
  }
30
30
  },
31
- "peerDependencies": {
32
- "@kirkchinese/dsh-capability-catalog": "^0.2.2"
33
- },
34
31
  "repository": {
35
32
  "type": "git",
36
33
  "url": "git+https://github.com/Nathan-ADK/dsh-rea-lazy.git"
@@ -39,5 +36,8 @@
39
36
  "engines": {
40
37
  "node": ">=18"
41
38
  },
42
- "main": "lib/index.js"
39
+ "main": "lib/index.js",
40
+ "dependencies": {
41
+ "@modelcontextprotocol/client": "2.2.0"
42
+ }
43
43
  }