lantern-harness 0.1.23 → 0.1.25
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 +51 -0
- package/builtin/session/bash-session.mjs +91 -0
- package/builtin/session/lh-bash.mjs +67 -1
- package/builtin/session/lh-web.mjs +103 -52
- package/builtin/session/mcp-client.mjs +290 -0
- package/builtin/session/pwsh-session.mjs +90 -0
- package/builtin/session/session-runs.mjs +6 -1
- package/builtin/session/tool-run-policy.mjs +32 -0
- package/builtin/session/web-fetch-policy.mjs +79 -0
- package/cli/acp-server.mjs +19 -9
- package/cli/agent-policy.mjs +60 -0
- package/cli/headless.mjs +30 -6
- package/cli/jsonrpc-server.mjs +9 -3
- package/cli/lantern.mjs +40 -5
- package/cli/server.mjs +2 -0
- package/dist/500.html +4 -4
- package/dist/_astro/Base.COYvzmy5.css +1 -0
- package/dist/_astro/{Base.astro_astro_type_script_index_0_lang.CWRCetQl.js → Base.astro_astro_type_script_index_0_lang.Cb6ggViJ.js} +1 -1
- package/dist/_astro/{CaseExecBoard.Dnb8oP5i.js → CaseExecBoard.cl2Od7av.js} +1 -1
- package/dist/_astro/{CaseGenerateApp.ci_JowEk.js → CaseGenerateApp.nE3RR7bV.js} +5 -5
- package/dist/_astro/CasesLibrary.e3vlOqSQ.js +21 -0
- package/dist/_astro/ChatApp.CECImcJo.js +226 -0
- package/dist/_astro/ConfirmDialog.D5qXeML0.js +1 -0
- package/dist/_astro/{DashboardBoard.D-zHXRds.js → DashboardBoard.CmxqpmzI.js} +2 -2
- package/dist/_astro/{DocsFileBrowser.BM3nH4VD.js → DocsFileBrowser.BdpWp8zQ.js} +1 -1
- package/dist/_astro/DocsPager.D55FTK9d.js +1 -0
- package/dist/_astro/{KnowledgeLibrary.D9KnqXzr.js → KnowledgeLibrary.DKci9jN8.js} +1 -1
- package/dist/_astro/MultiSelectDropdown.BHxW9XLR.js +1 -0
- package/dist/_astro/NamePromptDialog.Csfnh5eM.js +1 -0
- package/dist/_astro/{NavLibraries.RH3Sinuh.js → NavLibraries.BybmHnXn.js} +1 -1
- package/dist/_astro/PluginsPage.B6dsHB44.js +1 -0
- package/dist/_astro/{PluginsPage.DBRfSxtq.js → PluginsPage.D5LXPMns.js} +2 -2
- package/dist/_astro/{PmBugsBoard.BnnaNP1y.js → PmBugsBoard.B6w50MHD.js} +1 -1
- package/dist/_astro/{PmIterationsBoard.phiyhQVA.js → PmIterationsBoard.Dk7JheCU.js} +1 -1
- package/dist/_astro/{PmProjectDetail.C8kRX5lu.js → PmProjectDetail.O44fnczN.js} +1 -1
- package/dist/_astro/{PmProjectsBoard.CFApEGPo.js → PmProjectsBoard.qgj9HAj8.js} +1 -1
- package/dist/_astro/PmRequirementsBoard.BKY3h4CQ.js +1 -0
- package/dist/_astro/{PmRequirementsBoard.DR9egcgA.js → PmRequirementsBoard.DTL_RFxq.js} +1 -1
- package/dist/_astro/{PmShared.BrBicDMN.js → PmShared.Bwphj4KH.js} +1 -1
- package/dist/_astro/{PromptsLibrary.sz6MivVn.js → PromptsLibrary.Dv5OABdK.js} +1 -1
- package/dist/_astro/{ReportsPage.CYZtpeiv.js → ReportsPage.B7MOskzc.js} +1 -1
- package/dist/_astro/ReqAnalysisBoard.nUp89z1s.js +39 -0
- package/dist/_astro/{RequirementsLibrary.R4dNZa9y.js → RequirementsLibrary._OviMClB.js} +1 -1
- package/dist/_astro/SearchableSelect.D3ODywC4.js +1 -0
- package/dist/_astro/SettingsDialog.D3f4EOwl.js +1 -0
- package/dist/_astro/SlideOverDrawer.CpQu7VMQ.js +1 -0
- package/dist/_astro/SpaceSwitcher.DQOG363O.js +7 -0
- package/dist/_astro/{TasksBoard.D0HwS5hd.js → TasksBoard.rwdPWLAh.js} +1 -1
- package/dist/_astro/{TemplatesLibrary.CVv5Ef30.js → TemplatesLibrary.CEVQPDDz.js} +1 -1
- package/dist/_astro/{TestStatsBoard._qNcNorG.js → TestStatsBoard.CO4JMh4N.js} +1 -1
- package/dist/_astro/{TodosBoard.CF5wbJy7.js → TodosBoard.CrZMl6Ei.js} +1 -1
- package/dist/_astro/UiAutoBoard.BRMCH1zB.js +9 -0
- package/dist/_astro/{app-config.CF1xVPmo.js → app-config.DAIyT--R.js} +1 -1
- package/dist/_astro/app-version.BPkgRlbu.js +1 -0
- package/dist/_astro/bash-tools.D4DBYc9k.js +27 -0
- package/dist/_astro/case-fields.Dqkws1iX.js +1 -0
- package/dist/_astro/case-gen-run.Byxy6M5X.js +22 -0
- package/dist/_astro/case-review.DlCarphW.js +3 -0
- package/dist/_astro/{case-types.DS1EQ5yP.js → case-types.B6MLX3iE.js} +1 -1
- package/dist/_astro/{hydrate-cache.CmC22o_H.js → hydrate-cache.C0F0L04c.js} +1 -1
- package/dist/_astro/i18n.ele1lM9e.js +7 -0
- package/dist/_astro/{llm.BuR7z55C.js → llm.DyweO-KK.js} +1 -1
- package/dist/_astro/open-docs-in-session.D608wzlx.js +1 -0
- package/dist/_astro/{plugins.CVM1IaoC.js → plugins.Di6uuouN.js} +1 -1
- package/dist/_astro/req-analysis.CIZ_cIJQ.js +23 -0
- package/dist/_astro/settings.DbhUT6Ao.js +2 -0
- package/dist/_astro/{spaces-client.DnS6MgGy.js → spaces-client.OuJPy3GP.js} +1 -1
- package/dist/_astro/{story-review.BbdIf5zg.js → story-review.BvgXBApZ.js} +6 -3
- package/dist/_astro/{view-prefs.D1snIG5o.js → view-prefs.DkS1ldnh.js} +1 -1
- package/dist/case-exec/index.html +5 -5
- package/dist/cases/generate/index.html +5 -5
- package/dist/cases/library/index.html +5 -5
- package/dist/dashboard/index.html +5 -5
- package/dist/docs/changelog/index.html +52 -5
- package/dist/docs/install/index.html +48 -4
- package/dist/docs/manual/index.html +40 -33
- package/dist/knowledge/index.html +5 -5
- package/dist/plugins/index.html +5 -5
- package/dist/pm/bugs/index.html +5 -5
- package/dist/pm/iterations/index.html +5 -5
- package/dist/pm/projects/detail/index.html +5 -5
- package/dist/pm/projects/index.html +5 -5
- package/dist/pm/requirements/index.html +5 -5
- package/dist/prompts/index.html +5 -5
- package/dist/reports/index.html +5 -5
- package/dist/requirement-analysis/index.html +5 -5
- package/dist/requirements/index.html +5 -5
- package/dist/tasks/index.html +5 -5
- package/dist/templates/index.html +5 -5
- package/dist/test-automation/index.html +5 -5
- package/dist/test-stats/index.html +5 -5
- package/dist/todos/index.html +5 -5
- package/dist/workbench/index.html +5 -5
- package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +9 -7
- package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +14 -2
- package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +23 -0
- package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +35 -27
- package/lh-plugins/case-review-prompt.mjs +12 -106
- package/lh-plugins/lh-case-review.mjs +118 -34
- package/lh-plugins/lh-mcp.mjs +79 -0
- package/lh-plugins/lh-reports.mjs +11 -29
- package/lh-plugins/lh-req-analysis.mjs +59 -6
- package/lh-plugins/req-analysis-prompt.mjs +34 -44
- package/lh-plugins/story-review-prompt.mjs +8 -52
- package/lh-plugins/uiauto-prompt.mjs +9 -65
- package/package.json +3 -1
- package/dist/_astro/Base.GThhapKd.css +0 -1
- package/dist/_astro/CasesLibrary.CDjuLV_E.js +0 -21
- package/dist/_astro/ChatApp.Td2xCiQG.js +0 -216
- package/dist/_astro/ConfirmDialog.CsMwWevK.js +0 -1
- package/dist/_astro/DocsPager.B9VhI6E3.js +0 -1
- package/dist/_astro/NamePromptDialog.CS1pTTVl.js +0 -1
- package/dist/_astro/PluginsPage.DMDyUktn.js +0 -1
- package/dist/_astro/PmRequirementsBoard.B-AI9iZX.js +0 -1
- package/dist/_astro/ReqAnalysisBoard.CazI9SU-.js +0 -29
- package/dist/_astro/SearchableSelect.Cbb8jMnP.js +0 -1
- package/dist/_astro/SettingsDialog.Bs1I8b27.js +0 -1
- package/dist/_astro/SlideOverDrawer.DMWJPD_W.js +0 -1
- package/dist/_astro/SpaceSwitcher.Dw9LjKiJ.js +0 -7
- package/dist/_astro/UiAutoBoard.B-7mL3ez.js +0 -9
- package/dist/_astro/app-version.yT2l6J8H.js +0 -1
- package/dist/_astro/bash-tools.CPS0ZiKi.js +0 -25
- package/dist/_astro/case-fields.h0roo2br.js +0 -1
- package/dist/_astro/case-gen-run.D8DGX0mr.js +0 -19
- package/dist/_astro/case-review.C1hQRbQ2.js +0 -3
- package/dist/_astro/i18n.CjqQGCAI.js +0 -7
- package/dist/_astro/open-docs-in-session.Cj0J2-XT.js +0 -1
- package/dist/_astro/req-analysis.dhgy4p2f.js +0 -14
- package/dist/_astro/settings.B1yetppp.js +0 -2
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP 真客户端(stdio / Streamable HTTP):读空间 mcp.json,暴露 tools/list · tools/call。
|
|
3
|
+
*/
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
7
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
8
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
9
|
+
import { getDataRoot } from './space-context.mjs';
|
|
10
|
+
import { LOCAL_REL } from './space-layout.mjs';
|
|
11
|
+
|
|
12
|
+
const NAME_RE = /^[a-zA-Z0-9_-]+$/;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {string} raw
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
export function sanitizeMcpSegment(raw) {
|
|
19
|
+
return (
|
|
20
|
+
String(raw || '')
|
|
21
|
+
.trim()
|
|
22
|
+
.replace(/[^a-zA-Z0-9_-]+/g, '_')
|
|
23
|
+
.replace(/^_+|_+$/g, '')
|
|
24
|
+
.slice(0, 64) || 'x'
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {string} server
|
|
30
|
+
* @param {string} tool
|
|
31
|
+
*/
|
|
32
|
+
export function mcpToolName(server, tool) {
|
|
33
|
+
return `mcp__${sanitizeMcpSegment(server)}__${sanitizeMcpSegment(tool)}`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {string} name
|
|
38
|
+
* @returns {{ server: string, tool: string } | null}
|
|
39
|
+
*/
|
|
40
|
+
export function parseMcpToolName(name) {
|
|
41
|
+
const m = String(name || '').match(/^mcp__([a-zA-Z0-9_-]+)__(.+)$/);
|
|
42
|
+
if (!m) return null;
|
|
43
|
+
return { server: m[1], tool: m[2] };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {string} root
|
|
48
|
+
*/
|
|
49
|
+
export function mcpConfigPath(root) {
|
|
50
|
+
return path.join(root, LOCAL_REL, 'mcp.json');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {unknown} raw
|
|
55
|
+
* @returns {{ name: string, transport: string, command?: string, args?: string[], env?: Record<string,string>, url?: string, headers?: Record<string,string> }[]}
|
|
56
|
+
*/
|
|
57
|
+
export function normalizeMcpServers(raw) {
|
|
58
|
+
const list = Array.isArray(raw?.servers) ? raw.servers : Array.isArray(raw) ? raw : [];
|
|
59
|
+
/** @type {typeof list} */
|
|
60
|
+
const out = [];
|
|
61
|
+
const seen = new Set();
|
|
62
|
+
for (const item of list) {
|
|
63
|
+
if (!item || typeof item !== 'object') continue;
|
|
64
|
+
const name = sanitizeMcpSegment(item.name);
|
|
65
|
+
if (!NAME_RE.test(name) || seen.has(name)) continue;
|
|
66
|
+
const transport = String(item.transport || (item.url ? 'http' : 'stdio'))
|
|
67
|
+
.trim()
|
|
68
|
+
.toLowerCase();
|
|
69
|
+
if (transport === 'stdio') {
|
|
70
|
+
const command = String(item.command || '').trim();
|
|
71
|
+
if (!command) continue;
|
|
72
|
+
seen.add(name);
|
|
73
|
+
out.push({
|
|
74
|
+
name,
|
|
75
|
+
transport: 'stdio',
|
|
76
|
+
command,
|
|
77
|
+
args: Array.isArray(item.args) ? item.args.map((a) => String(a)) : [],
|
|
78
|
+
env:
|
|
79
|
+
item.env && typeof item.env === 'object'
|
|
80
|
+
? Object.fromEntries(Object.entries(item.env).filter(([, v]) => typeof v === 'string'))
|
|
81
|
+
: undefined,
|
|
82
|
+
});
|
|
83
|
+
} else if (transport === 'http' || transport === 'streamable-http' || transport === 'sse') {
|
|
84
|
+
const url = String(item.url || '').trim();
|
|
85
|
+
if (!url) continue;
|
|
86
|
+
seen.add(name);
|
|
87
|
+
out.push({
|
|
88
|
+
name,
|
|
89
|
+
transport: 'http',
|
|
90
|
+
url,
|
|
91
|
+
headers:
|
|
92
|
+
item.headers && typeof item.headers === 'object'
|
|
93
|
+
? Object.fromEntries(
|
|
94
|
+
Object.entries(item.headers).filter(([, v]) => typeof v === 'string'),
|
|
95
|
+
)
|
|
96
|
+
: undefined,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function loadMcpConfig(root = getDataRoot()) {
|
|
104
|
+
const p = mcpConfigPath(root);
|
|
105
|
+
if (!fs.existsSync(p)) return { path: p, servers: [] };
|
|
106
|
+
try {
|
|
107
|
+
const raw = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
108
|
+
return { path: p, servers: normalizeMcpServers(raw) };
|
|
109
|
+
} catch (e) {
|
|
110
|
+
return {
|
|
111
|
+
path: p,
|
|
112
|
+
servers: [],
|
|
113
|
+
error: e instanceof Error ? e.message : String(e),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** @type {Map<string, { client: import('@modelcontextprotocol/sdk/client/index.js').Client, conf: object, root: string }>} */
|
|
119
|
+
const pool = new Map();
|
|
120
|
+
/** @type {Map<string, { server: string, remoteName: string }>} */
|
|
121
|
+
const toolIndex = new Map();
|
|
122
|
+
let poolRoot = '';
|
|
123
|
+
|
|
124
|
+
function poolKey(root, name) {
|
|
125
|
+
return `${root}::${name}`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function closeAllMcpClients() {
|
|
129
|
+
for (const [k, entry] of pool) {
|
|
130
|
+
try {
|
|
131
|
+
await entry.client.close();
|
|
132
|
+
} catch {
|
|
133
|
+
// ignore
|
|
134
|
+
}
|
|
135
|
+
pool.delete(k);
|
|
136
|
+
}
|
|
137
|
+
toolIndex.clear();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @param {object} conf
|
|
142
|
+
* @param {string} root
|
|
143
|
+
*/
|
|
144
|
+
async function connectServer(conf, root) {
|
|
145
|
+
const client = new Client({ name: 'lantern-harness', version: '0.1' });
|
|
146
|
+
if (conf.transport === 'stdio') {
|
|
147
|
+
const transport = new StdioClientTransport({
|
|
148
|
+
command: conf.command,
|
|
149
|
+
args: conf.args || [],
|
|
150
|
+
env: conf.env,
|
|
151
|
+
stderr: 'pipe',
|
|
152
|
+
cwd: root,
|
|
153
|
+
});
|
|
154
|
+
await client.connect(transport);
|
|
155
|
+
} else {
|
|
156
|
+
const headers = conf.headers || {};
|
|
157
|
+
const transport = new StreamableHTTPClientTransport(new URL(conf.url), {
|
|
158
|
+
requestInit: { headers },
|
|
159
|
+
});
|
|
160
|
+
await client.connect(transport);
|
|
161
|
+
}
|
|
162
|
+
return client;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* @param {string} [root]
|
|
167
|
+
*/
|
|
168
|
+
export async function ensureMcpClients(root = getDataRoot()) {
|
|
169
|
+
if (poolRoot && poolRoot !== root) {
|
|
170
|
+
await closeAllMcpClients();
|
|
171
|
+
}
|
|
172
|
+
poolRoot = root;
|
|
173
|
+
const { servers, error } = loadMcpConfig(root);
|
|
174
|
+
const wanted = new Set(servers.map((s) => s.name));
|
|
175
|
+
for (const key of [...pool.keys()]) {
|
|
176
|
+
const name = key.slice(root.length + 2);
|
|
177
|
+
if (!wanted.has(name)) {
|
|
178
|
+
try {
|
|
179
|
+
await pool.get(key)?.client.close();
|
|
180
|
+
} catch {
|
|
181
|
+
// ignore
|
|
182
|
+
}
|
|
183
|
+
pool.delete(key);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const errors = [];
|
|
187
|
+
if (error) errors.push(error);
|
|
188
|
+
for (const conf of servers) {
|
|
189
|
+
const key = poolKey(root, conf.name);
|
|
190
|
+
if (pool.has(key)) continue;
|
|
191
|
+
try {
|
|
192
|
+
const client = await connectServer(conf, root);
|
|
193
|
+
pool.set(key, { client, conf, root });
|
|
194
|
+
} catch (e) {
|
|
195
|
+
errors.push(`${conf.name}: ${e instanceof Error ? e.message : String(e)}`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return { servers, connected: [...pool.keys()].map((k) => k.slice(root.length + 2)), errors };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* @param {string} [root]
|
|
203
|
+
*/
|
|
204
|
+
export async function listMcpTools(root = getDataRoot()) {
|
|
205
|
+
await ensureMcpClients(root);
|
|
206
|
+
/** @type {Array<{ name: string, description?: string, inputSchema?: object, server: string, remoteName: string }>} */
|
|
207
|
+
const tools = [];
|
|
208
|
+
const errors = [];
|
|
209
|
+
for (const key of [...toolIndex.keys()]) {
|
|
210
|
+
if (key.startsWith('mcp__')) toolIndex.delete(key);
|
|
211
|
+
}
|
|
212
|
+
for (const [key, entry] of pool) {
|
|
213
|
+
if (entry.root !== root) continue;
|
|
214
|
+
try {
|
|
215
|
+
const listed = await entry.client.listTools();
|
|
216
|
+
for (const t of listed.tools || []) {
|
|
217
|
+
const remoteName = String(t.name || '').trim();
|
|
218
|
+
if (!remoteName) continue;
|
|
219
|
+
const name = mcpToolName(entry.conf.name, remoteName);
|
|
220
|
+
toolIndex.set(name, { server: entry.conf.name, remoteName });
|
|
221
|
+
tools.push({
|
|
222
|
+
name,
|
|
223
|
+
description: t.description || `MCP ${entry.conf.name}/${remoteName}`,
|
|
224
|
+
inputSchema: t.inputSchema || { type: 'object', properties: {} },
|
|
225
|
+
server: entry.conf.name,
|
|
226
|
+
remoteName,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
} catch (e) {
|
|
230
|
+
errors.push(`${entry.conf.name}: ${e instanceof Error ? e.message : String(e)}`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return {
|
|
234
|
+
ok: true,
|
|
235
|
+
tools,
|
|
236
|
+
errors,
|
|
237
|
+
connected: [...pool.keys()]
|
|
238
|
+
.filter((k) => k.startsWith(`${root}::`))
|
|
239
|
+
.map((k) => k.slice(root.length + 2)),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* @param {string} toolName mcp__server__tool
|
|
245
|
+
* @param {unknown} args
|
|
246
|
+
* @param {string} [root]
|
|
247
|
+
*/
|
|
248
|
+
export async function callMcpTool(toolName, args, root = getDataRoot()) {
|
|
249
|
+
const name = String(toolName || '');
|
|
250
|
+
await ensureMcpClients(root);
|
|
251
|
+
if (!toolIndex.has(name)) {
|
|
252
|
+
await listMcpTools(root);
|
|
253
|
+
}
|
|
254
|
+
let resolved = toolIndex.get(name);
|
|
255
|
+
if (!resolved) {
|
|
256
|
+
const parsed = parseMcpToolName(name);
|
|
257
|
+
if (!parsed) return { ok: false, error: 'not an mcp tool name' };
|
|
258
|
+
resolved = { server: parsed.server, remoteName: parsed.tool };
|
|
259
|
+
}
|
|
260
|
+
const key = poolKey(root, resolved.server);
|
|
261
|
+
const entry = pool.get(key);
|
|
262
|
+
if (!entry) return { ok: false, error: `mcp server not connected: ${resolved.server}` };
|
|
263
|
+
try {
|
|
264
|
+
const result = await entry.client.callTool({
|
|
265
|
+
name: resolved.remoteName,
|
|
266
|
+
arguments: args && typeof args === 'object' ? args : {},
|
|
267
|
+
});
|
|
268
|
+
const texts = [];
|
|
269
|
+
const content = Array.isArray(result?.content) ? result.content : [];
|
|
270
|
+
for (const c of content) {
|
|
271
|
+
if (c?.type === 'text' && typeof c.text === 'string') texts.push(c.text);
|
|
272
|
+
else if (c) texts.push(JSON.stringify(c));
|
|
273
|
+
}
|
|
274
|
+
const text = texts.join('\n') || JSON.stringify(result ?? {}, null, 2);
|
|
275
|
+
return {
|
|
276
|
+
ok: result?.isError ? false : true,
|
|
277
|
+
text: text.slice(0, 80_000),
|
|
278
|
+
isError: Boolean(result?.isError),
|
|
279
|
+
};
|
|
280
|
+
} catch (e) {
|
|
281
|
+
return { ok: false, error: e instanceof Error ? e.message : String(e) };
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** 测试用 */
|
|
286
|
+
export function resetMcpPoolForTests() {
|
|
287
|
+
pool.clear();
|
|
288
|
+
toolIndex.clear();
|
|
289
|
+
poolRoot = '';
|
|
290
|
+
}
|
|
@@ -346,6 +346,96 @@ export function readPwshSession(sessionId, offset = 0) {
|
|
|
346
346
|
};
|
|
347
347
|
}
|
|
348
348
|
|
|
349
|
+
const ALLOWED_SIGNALS = new Set(['SIGINT', 'SIGTERM', 'SIGTSTP', 'SIGHUP']);
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* @param {{ sessionId: string, data?: string, text?: string, submit?: boolean }} opts
|
|
353
|
+
*/
|
|
354
|
+
export function writePwshSession(opts) {
|
|
355
|
+
const id = String(opts.sessionId || '').trim();
|
|
356
|
+
const session = sessions.get(id);
|
|
357
|
+
if (!session) return { ok: false, error: 'session not found' };
|
|
358
|
+
if (session.status !== 'running') {
|
|
359
|
+
return {
|
|
360
|
+
ok: false,
|
|
361
|
+
error: `session not running (${session.status})`,
|
|
362
|
+
session: publicSession(session),
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
let payload = String(opts.data ?? opts.text ?? '');
|
|
366
|
+
if (opts.submit !== false && !payload.endsWith('\n')) payload += '\n';
|
|
367
|
+
if (!payload) return { ok: false, error: 'data is required' };
|
|
368
|
+
try {
|
|
369
|
+
if (session.backend === 'pty' && session.pty) {
|
|
370
|
+
session.pty.write(payload);
|
|
371
|
+
} else if (session.child?.stdin) {
|
|
372
|
+
session.child.stdin.write(payload);
|
|
373
|
+
} else {
|
|
374
|
+
return { ok: false, error: 'session has no writable stdin' };
|
|
375
|
+
}
|
|
376
|
+
} catch (e) {
|
|
377
|
+
return { ok: false, error: e instanceof Error ? e.message : String(e) };
|
|
378
|
+
}
|
|
379
|
+
session.lastActiveAt = Date.now();
|
|
380
|
+
return {
|
|
381
|
+
ok: true,
|
|
382
|
+
sessionId: session.id,
|
|
383
|
+
backend: session.backend,
|
|
384
|
+
bytes: Buffer.byteLength(payload, 'utf8'),
|
|
385
|
+
session: publicSession(session),
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* @param {{ sessionId: string, signal?: string }} opts
|
|
391
|
+
*/
|
|
392
|
+
export function signalPwshSession(opts) {
|
|
393
|
+
const id = String(opts.sessionId || '').trim();
|
|
394
|
+
const signal = String(opts.signal || 'SIGINT')
|
|
395
|
+
.trim()
|
|
396
|
+
.toUpperCase();
|
|
397
|
+
if (!ALLOWED_SIGNALS.has(signal)) {
|
|
398
|
+
return {
|
|
399
|
+
ok: false,
|
|
400
|
+
error: `unsupported signal (allowed: ${[...ALLOWED_SIGNALS].join(', ')})`,
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
const session = sessions.get(id);
|
|
404
|
+
if (!session) return { ok: false, error: 'session not found' };
|
|
405
|
+
if (session.status !== 'running') {
|
|
406
|
+
return {
|
|
407
|
+
ok: false,
|
|
408
|
+
error: `session not running (${session.status})`,
|
|
409
|
+
session: publicSession(session),
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
try {
|
|
413
|
+
if (session.backend === 'pty' && session.pty) {
|
|
414
|
+
if (typeof session.pty.kill === 'function') {
|
|
415
|
+
session.pty.kill(signal);
|
|
416
|
+
} else if (session.pty.pid) {
|
|
417
|
+
process.kill(session.pty.pid, signal);
|
|
418
|
+
} else {
|
|
419
|
+
return { ok: false, error: 'pty has no kill' };
|
|
420
|
+
}
|
|
421
|
+
} else if (session.child) {
|
|
422
|
+
session.child.kill(signal);
|
|
423
|
+
} else {
|
|
424
|
+
return { ok: false, error: 'session has no process' };
|
|
425
|
+
}
|
|
426
|
+
} catch (e) {
|
|
427
|
+
return { ok: false, error: e instanceof Error ? e.message : String(e) };
|
|
428
|
+
}
|
|
429
|
+
session.lastActiveAt = Date.now();
|
|
430
|
+
return {
|
|
431
|
+
ok: true,
|
|
432
|
+
sessionId: session.id,
|
|
433
|
+
signal,
|
|
434
|
+
backend: session.backend,
|
|
435
|
+
session: publicSession(session),
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
|
|
349
439
|
export function closePwshSession(sessionId) {
|
|
350
440
|
return closeSessionInternal(String(sessionId || '').trim());
|
|
351
441
|
}
|
|
@@ -12,6 +12,7 @@ import path from 'node:path';
|
|
|
12
12
|
|
|
13
13
|
import { getDataRoot } from './space-context.mjs';
|
|
14
14
|
import { LOCAL_REL } from './space-layout.mjs';
|
|
15
|
+
import { defaultTimeoutMs, withToolTimeout } from './tool-run-policy.mjs';
|
|
15
16
|
|
|
16
17
|
const PREFIX = '/__tb_sessions/runs';
|
|
17
18
|
|
|
@@ -877,7 +878,11 @@ async function execToolCalls(run, calls, content, reasoning, apiMessages, origin
|
|
|
877
878
|
applyChunk(run, { type: 'tool', name, status: 'running', args });
|
|
878
879
|
let out;
|
|
879
880
|
try {
|
|
880
|
-
out = await
|
|
881
|
+
out = await withToolTimeout(
|
|
882
|
+
runToolLoopback(origin, name, args, ctx),
|
|
883
|
+
defaultTimeoutMs(name),
|
|
884
|
+
name || 'tool',
|
|
885
|
+
);
|
|
881
886
|
} catch (toolErr) {
|
|
882
887
|
const aborted =
|
|
883
888
|
(toolErr instanceof DOMException && toolErr.name === 'AbortError') ||
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 与 src/lib/tool-run-policy.ts 语义对齐(服务端 session-runs 用)。
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export function defaultTimeoutMs(toolName) {
|
|
6
|
+
const n = String(toolName || '');
|
|
7
|
+
if (n === 'bash' || n === 'pwsh' || n.endsWith('_session_exec')) return 120_000;
|
|
8
|
+
if (n.startsWith('bash_session_') || n.startsWith('pwsh_session_')) return 30_000;
|
|
9
|
+
if (n === 'web_fetch') return 35_000;
|
|
10
|
+
if (n === 'web_search') return 30_000;
|
|
11
|
+
if (n.startsWith('mcp__')) return 60_000;
|
|
12
|
+
if (n.startsWith('fs_') || n.startsWith('kb_') || n.startsWith('memory_')) return 30_000;
|
|
13
|
+
if (n.startsWith('subagent_') || n === 'spawn_subagent' || n === 'fork_subagent') return 300_000;
|
|
14
|
+
return 60_000;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function withToolTimeout(promise, timeoutMs, label = 'tool') {
|
|
18
|
+
const ms = Math.max(1_000, Math.min(600_000, Number(timeoutMs) || 60_000));
|
|
19
|
+
let timer;
|
|
20
|
+
try {
|
|
21
|
+
return await Promise.race([
|
|
22
|
+
promise,
|
|
23
|
+
new Promise((_, reject) => {
|
|
24
|
+
timer = setTimeout(() => {
|
|
25
|
+
reject(new Error(`${label} timed out after ${ms}ms`));
|
|
26
|
+
}, ms);
|
|
27
|
+
}),
|
|
28
|
+
]);
|
|
29
|
+
} finally {
|
|
30
|
+
if (timer) clearTimeout(timer);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* web_fetch 私网 / 回环目的地判定(供 lh-web 与单测共用)。
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @param {string} hostname
|
|
7
|
+
* @returns {boolean}
|
|
8
|
+
*/
|
|
9
|
+
export function isPrivateHostname(hostname) {
|
|
10
|
+
const h = String(hostname || '')
|
|
11
|
+
.toLowerCase()
|
|
12
|
+
.replace(/^\[|\]$/g, '');
|
|
13
|
+
if (!h) return true;
|
|
14
|
+
if (h === 'localhost' || h.endsWith('.localhost')) return true;
|
|
15
|
+
if (h.endsWith('.local') || h.endsWith('.internal')) return true;
|
|
16
|
+
if (h === '0.0.0.0' || h === '::' || h === '::1') return true;
|
|
17
|
+
if (isPrivateIp(h)) return true;
|
|
18
|
+
// IPv4-mapped IPv6
|
|
19
|
+
const v4mapped = h.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
|
|
20
|
+
if (v4mapped && isPrivateIp(v4mapped[1])) return true;
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {string} ip
|
|
26
|
+
* @returns {boolean}
|
|
27
|
+
*/
|
|
28
|
+
export function isPrivateIp(ip) {
|
|
29
|
+
const s = String(ip || '')
|
|
30
|
+
.toLowerCase()
|
|
31
|
+
.replace(/^\[|\]$/g, '');
|
|
32
|
+
if (!s) return true;
|
|
33
|
+
if (s === '::1' || s === '::' || s === '0.0.0.0') return true;
|
|
34
|
+
|
|
35
|
+
// IPv4
|
|
36
|
+
if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(s)) {
|
|
37
|
+
const parts = s.split('.').map((x) => Number(x));
|
|
38
|
+
if (parts.some((n) => !Number.isFinite(n) || n < 0 || n > 255)) return true;
|
|
39
|
+
const [a, b] = parts;
|
|
40
|
+
if (a === 10) return true;
|
|
41
|
+
if (a === 127) return true;
|
|
42
|
+
if (a === 0) return true;
|
|
43
|
+
if (a === 169 && b === 254) return true;
|
|
44
|
+
if (a === 192 && b === 168) return true;
|
|
45
|
+
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
46
|
+
if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// IPv6 ULA fc00::/7, link-local fe80::/10
|
|
51
|
+
if (s.includes(':')) {
|
|
52
|
+
if (s.startsWith('fc') || s.startsWith('fd')) return true;
|
|
53
|
+
if (/^fe[89ab]/i.test(s)) return true;
|
|
54
|
+
if (s === '::1') return true;
|
|
55
|
+
const v4m = s.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
|
|
56
|
+
if (v4m) return isPrivateIp(v4m[1]);
|
|
57
|
+
}
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* @param {string} hostname
|
|
63
|
+
* @param {boolean} allowPrivate
|
|
64
|
+
* @returns {boolean} true = 应拦截
|
|
65
|
+
*/
|
|
66
|
+
export function shouldBlockHost(hostname, allowPrivate = false) {
|
|
67
|
+
if (allowPrivate) return false;
|
|
68
|
+
return isPrivateHostname(hostname);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @param {string} ip
|
|
73
|
+
* @param {boolean} allowPrivate
|
|
74
|
+
* @returns {boolean}
|
|
75
|
+
*/
|
|
76
|
+
export function shouldBlockIp(ip, allowPrivate = false) {
|
|
77
|
+
if (allowPrivate) return false;
|
|
78
|
+
return isPrivateIp(ip);
|
|
79
|
+
}
|
package/cli/acp-server.mjs
CHANGED
|
@@ -17,10 +17,18 @@ import fs from 'node:fs';
|
|
|
17
17
|
import path from 'node:path';
|
|
18
18
|
import { fileURLToPath } from 'node:url';
|
|
19
19
|
|
|
20
|
+
import { parseToolProfile } from './agent-policy.mjs';
|
|
20
21
|
import { headlessAsk, loadHeadlessSettings } from './headless.mjs';
|
|
21
22
|
|
|
22
23
|
const PROTOCOL_VERSION = 1;
|
|
23
24
|
|
|
25
|
+
/** @param {unknown} raw @param {string} fallback */
|
|
26
|
+
function resolveToolsParam(raw, fallback = 'none') {
|
|
27
|
+
if (raw === undefined || raw === null) return fallback;
|
|
28
|
+
if (typeof raw === 'boolean') return raw ? 'fs-readonly' : 'none';
|
|
29
|
+
return parseToolProfile(raw, fallback);
|
|
30
|
+
}
|
|
31
|
+
|
|
24
32
|
/** 与 package.json 保持同源,避免发版时漏改 */
|
|
25
33
|
const SERVER_VERSION = (() => {
|
|
26
34
|
try {
|
|
@@ -52,13 +60,14 @@ function uid() {
|
|
|
52
60
|
}
|
|
53
61
|
|
|
54
62
|
/**
|
|
55
|
-
* @param {{ dataRoot: string, tools?: boolean, workspace?: string }} opts
|
|
63
|
+
* @param {{ dataRoot: string, tools?: boolean | string, workspace?: string, access?: string }} opts
|
|
56
64
|
*/
|
|
57
65
|
export async function runAcpServer(opts) {
|
|
58
66
|
const settings = loadHeadlessSettings(opts.dataRoot);
|
|
59
|
-
const toolsDefault = opts.tools
|
|
67
|
+
const toolsDefault = resolveToolsParam(opts.tools, 'none');
|
|
60
68
|
const workspaceDefault = opts.workspace || settings.dataRoot;
|
|
61
|
-
|
|
69
|
+
const accessDefault = opts.access || settings.access;
|
|
70
|
+
/** @type {Map<string, { id: string, messages: Array<{ role: string, content: string }>, createdAt: number, toolProfile: string }>} */
|
|
62
71
|
const sessions = new Map();
|
|
63
72
|
let shuttingDown = false;
|
|
64
73
|
|
|
@@ -113,14 +122,14 @@ export async function runAcpServer(opts) {
|
|
|
113
122
|
typeof params.system === 'string' && params.system.trim()
|
|
114
123
|
? params.system.trim()
|
|
115
124
|
: '你是 Lantern Harness headless 助手,简洁回答。';
|
|
116
|
-
const
|
|
125
|
+
const toolProfile = resolveToolsParam(params.tools, toolsDefault);
|
|
117
126
|
sessions.set(sid, {
|
|
118
127
|
id: sid,
|
|
119
128
|
messages: [{ role: 'system', content: system }],
|
|
120
129
|
createdAt: Date.now(),
|
|
121
|
-
|
|
130
|
+
toolProfile,
|
|
122
131
|
});
|
|
123
|
-
ok(id, { sessionId: sid, tools });
|
|
132
|
+
ok(id, { sessionId: sid, tools: toolProfile });
|
|
124
133
|
continue;
|
|
125
134
|
}
|
|
126
135
|
|
|
@@ -136,7 +145,7 @@ export async function runAcpServer(opts) {
|
|
|
136
145
|
continue;
|
|
137
146
|
}
|
|
138
147
|
const sess = sessions.get(sessionId);
|
|
139
|
-
const
|
|
148
|
+
const toolProfile = resolveToolsParam(params.tools, sess.toolProfile);
|
|
140
149
|
sess.messages.push({ role: 'user', content: prompt });
|
|
141
150
|
|
|
142
151
|
const history = sess.messages
|
|
@@ -151,7 +160,8 @@ export async function runAcpServer(opts) {
|
|
|
151
160
|
const toolEvents = [];
|
|
152
161
|
const text = await headlessAsk(settings, prompt, {
|
|
153
162
|
system,
|
|
154
|
-
|
|
163
|
+
toolProfile,
|
|
164
|
+
access: typeof params.access === 'string' ? params.access : accessDefault,
|
|
155
165
|
workspace: workspaceDefault,
|
|
156
166
|
onTool: (ev) => {
|
|
157
167
|
toolEvents.push(ev);
|
|
@@ -173,7 +183,7 @@ export async function runAcpServer(opts) {
|
|
|
173
183
|
stopReason: 'end_turn',
|
|
174
184
|
text,
|
|
175
185
|
model: settings.model,
|
|
176
|
-
tools:
|
|
186
|
+
tools: toolProfile,
|
|
177
187
|
toolCalls: toolEvents.filter((e) => e.status === 'done').map((e) => e.name),
|
|
178
188
|
});
|
|
179
189
|
continue;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent 策略解析(与 src/lib/agent-policy.ts 语义对齐)。
|
|
3
|
+
* CLI / headless 用本文件,避免运行时依赖 TS 编译。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const ACCESS = new Set(['readonly', 'readwrite', 'full']);
|
|
7
|
+
const TOOLS = new Set(['none', 'fs-readonly', 'fs']);
|
|
8
|
+
|
|
9
|
+
export function parseAccessLevel(raw, fallback = 'readonly') {
|
|
10
|
+
const v = String(raw ?? '')
|
|
11
|
+
.trim()
|
|
12
|
+
.toLowerCase();
|
|
13
|
+
if (ACCESS.has(v)) return v;
|
|
14
|
+
return fallback;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function parseToolProfile(raw, fallback = 'none') {
|
|
18
|
+
const v = String(raw ?? '')
|
|
19
|
+
.trim()
|
|
20
|
+
.toLowerCase()
|
|
21
|
+
.replace(/_/g, '-');
|
|
22
|
+
if (v === 'readonly' || v === 'fs-ro') return 'fs-readonly';
|
|
23
|
+
if (v === 'true' || v === '1' || v === 'yes') return 'fs-readonly';
|
|
24
|
+
if (v === 'false' || v === '0' || v === 'no' || v === 'off') return 'none';
|
|
25
|
+
if (TOOLS.has(v)) return v;
|
|
26
|
+
return fallback;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {{
|
|
31
|
+
* configAccess?: unknown,
|
|
32
|
+
* cliAccess?: unknown,
|
|
33
|
+
* cliToolProfile?: unknown,
|
|
34
|
+
* workspace?: unknown,
|
|
35
|
+
* defaultAccess?: string,
|
|
36
|
+
* defaultToolProfile?: string,
|
|
37
|
+
* }} input
|
|
38
|
+
*/
|
|
39
|
+
export function resolveAgentPolicy(input = {}) {
|
|
40
|
+
const defaultAccess = input.defaultAccess || 'readonly';
|
|
41
|
+
const access = parseAccessLevel(
|
|
42
|
+
input.cliAccess !== undefined && String(input.cliAccess).trim() !== ''
|
|
43
|
+
? input.cliAccess
|
|
44
|
+
: input.configAccess,
|
|
45
|
+
defaultAccess,
|
|
46
|
+
);
|
|
47
|
+
let toolProfile = parseToolProfile(input.cliToolProfile, input.defaultToolProfile || 'none');
|
|
48
|
+
if (access === 'readonly' && toolProfile === 'fs') {
|
|
49
|
+
toolProfile = 'fs-readonly';
|
|
50
|
+
}
|
|
51
|
+
const workspace = String(input.workspace ?? '').trim();
|
|
52
|
+
return { access, workspace, toolProfile };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 从空间 app.config / defaults 读出 access 字段(若有) */
|
|
56
|
+
export function readSpaceAccess(localConfig, defaultsConfig) {
|
|
57
|
+
const local = localConfig && typeof localConfig === 'object' ? localConfig : {};
|
|
58
|
+
const defaults = defaultsConfig && typeof defaultsConfig === 'object' ? defaultsConfig : {};
|
|
59
|
+
return local.access ?? defaults.access ?? local.general?.access ?? defaults.general?.access;
|
|
60
|
+
}
|