@yitom/acp-client 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -0
- package/dist/auth/auth-method-order.d.ts +9 -0
- package/dist/auth/connect-auth-decision.d.ts +18 -0
- package/dist/auth/connect-auth-gate.d.ts +35 -0
- package/dist/client/acp-client.d.ts +110 -0
- package/dist/client/acp-fs.d.ts +15 -0
- package/dist/client/acp-paths.d.ts +8 -0
- package/dist/client/acp-proxy-service.d.ts +14 -0
- package/dist/client/acp-terminal.d.ts +36 -0
- package/dist/client/client-handlers.d.ts +27 -0
- package/dist/client/sdk-client.d.ts +32 -0
- package/dist/client/session-open.d.ts +39 -0
- package/dist/contracts/index.d.ts +277 -0
- package/dist/index.cjs +3279 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.js +3242 -0
- package/dist/mcp/inkdown-mcp-rpc.d.ts +14 -0
- package/dist/mcp/inkdown-mcp-toc-tools.d.ts +3 -0
- package/dist/mcp/inkdown-mcp-tools.d.ts +31 -0
- package/dist/process/process-manager.d.ts +59 -0
- package/dist/runtimes/agy/index.d.ts +19 -0
- package/dist/runtimes/claude/index.d.ts +13 -0
- package/dist/runtimes/codex/codex-auth-preflight.d.ts +10 -0
- package/dist/runtimes/codex/codex-provider-home.d.ts +20 -0
- package/dist/runtimes/codex/codex-provider.d.ts +13 -0
- package/dist/runtimes/codex/index.d.ts +16 -0
- package/dist/runtimes/copilot/index.d.ts +14 -0
- package/dist/runtimes/cursor/index.d.ts +66 -0
- package/dist/runtimes/deepseek/index.d.ts +34 -0
- package/dist/runtimes/gemini/index.d.ts +13 -0
- package/dist/runtimes/index.d.ts +54 -0
- package/dist/runtimes/opencode/index.d.ts +28 -0
- package/dist/session/agent-registry.d.ts +4 -0
- package/dist/session/config-options.d.ts +17 -0
- package/dist/session/session-capabilities.d.ts +10 -0
- package/dist/transport/terminal-output-buffer.d.ts +11 -0
- package/docs/adding-an-agent.md +121 -0
- package/docs/api-reference.md +104 -0
- package/docs/getting-started.md +164 -0
- package/docs/tauri-integration.md +107 -0
- package/package.json +44 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3242 @@
|
|
|
1
|
+
// src/contracts/index.ts
|
|
2
|
+
function isCancelled(error) {
|
|
3
|
+
return error.code === "CANCELLED";
|
|
4
|
+
}
|
|
5
|
+
function isAppError(value) {
|
|
6
|
+
return value !== null && typeof value === "object" && "code" in value && "message" in value && typeof value.message === "string";
|
|
7
|
+
}
|
|
8
|
+
function toAppError(error, fallbackMessage) {
|
|
9
|
+
if (error && typeof error === "object" && "code" in error && "message" in error) {
|
|
10
|
+
return error;
|
|
11
|
+
}
|
|
12
|
+
const message = error instanceof Error ? error.message : fallbackMessage;
|
|
13
|
+
const code = error instanceof Error && "code" in error && error.code === "ENOENT" ? "FILE_NOT_FOUND" : "UNKNOWN";
|
|
14
|
+
return { code, message };
|
|
15
|
+
}
|
|
16
|
+
function ok(value) {
|
|
17
|
+
return { ok: true, value };
|
|
18
|
+
}
|
|
19
|
+
function err(error) {
|
|
20
|
+
return { ok: false, error };
|
|
21
|
+
}
|
|
22
|
+
function isOk(result) {
|
|
23
|
+
return result.ok;
|
|
24
|
+
}
|
|
25
|
+
function isErr(result) {
|
|
26
|
+
return !result.ok;
|
|
27
|
+
}
|
|
28
|
+
var INKDOWN_SETTLE_COMPLETE_KIND = "inkdown_settle_complete";
|
|
29
|
+
var INKDOWN_VIRTUAL_DIR = ".inkdown/agent";
|
|
30
|
+
var INKDOWN_VIRTUAL_RESOURCES = [
|
|
31
|
+
"focused.json",
|
|
32
|
+
"toc.json",
|
|
33
|
+
"chapter.txt",
|
|
34
|
+
"viewport.txt"
|
|
35
|
+
];
|
|
36
|
+
function toPosix(input) {
|
|
37
|
+
return input.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
38
|
+
}
|
|
39
|
+
function stripWorkspacePrefix(path, workspaceRoot) {
|
|
40
|
+
const root = toPosix(workspaceRoot);
|
|
41
|
+
if (!root)
|
|
42
|
+
return path;
|
|
43
|
+
if (path === root)
|
|
44
|
+
return "";
|
|
45
|
+
if (path.toLowerCase().startsWith(`${root.toLowerCase()}/`)) {
|
|
46
|
+
return path.slice(root.length + 1);
|
|
47
|
+
}
|
|
48
|
+
return path;
|
|
49
|
+
}
|
|
50
|
+
function isVirtualResource(value) {
|
|
51
|
+
return INKDOWN_VIRTUAL_RESOURCES.includes(value);
|
|
52
|
+
}
|
|
53
|
+
function parseInkdownVirtualPath(filePath, workspaceRoot) {
|
|
54
|
+
const relative = stripWorkspacePrefix(toPosix(filePath.trim()), workspaceRoot).replace(/^\.\//, "");
|
|
55
|
+
if (!relative.startsWith(`${INKDOWN_VIRTUAL_DIR}/`))
|
|
56
|
+
return null;
|
|
57
|
+
const resource = relative.slice(INKDOWN_VIRTUAL_DIR.length + 1);
|
|
58
|
+
return isVirtualResource(resource) ? resource : null;
|
|
59
|
+
}
|
|
60
|
+
function isInkdownVirtualDirPath(filePath, workspaceRoot) {
|
|
61
|
+
const relative = stripWorkspacePrefix(toPosix(filePath.trim()), workspaceRoot).replace(/^\.\//, "");
|
|
62
|
+
return relative === INKDOWN_VIRTUAL_DIR || relative.startsWith(`${INKDOWN_VIRTUAL_DIR}/`);
|
|
63
|
+
}
|
|
64
|
+
var CODEX_ACP_NPM_PACKAGE = "@agentclientprotocol/codex-acp";
|
|
65
|
+
var CLAUDE_ACP_NPM_PACKAGE = "@agentclientprotocol/claude-agent-acp";
|
|
66
|
+
var DEEPSEEK_DSH_NPM_PACKAGE = "@deepseek-ai/dsh";
|
|
67
|
+
var AGY_ACP_NPM_PACKAGE = "@yitom/agy-acp-map";
|
|
68
|
+
var LEGACY_ZED_CODEX_ACP_NPM_PACKAGE = "@zed-industries/codex-acp";
|
|
69
|
+
var DEFAULT_ACP_RUNTIME_ID = "codex-acp";
|
|
70
|
+
function isWindowsPlatform() {
|
|
71
|
+
const proc = globalThis.process;
|
|
72
|
+
return proc?.platform === "win32";
|
|
73
|
+
}
|
|
74
|
+
var BUILTIN_ACP_RUNTIMES = [
|
|
75
|
+
{
|
|
76
|
+
id: "codex-acp",
|
|
77
|
+
name: "ChatGPT",
|
|
78
|
+
description: "通过 bunx 启动官方 @agentclientprotocol/codex-acp;可复用本机 ~/.codex(ChatGPT / API Key)",
|
|
79
|
+
authHint: "复用本机 ~/.codex 登录(auth.json 或 OPENAI_API_KEY / CODEX_API_KEY);未登录按下方 Agent 认证方式完成登录",
|
|
80
|
+
command: "bunx",
|
|
81
|
+
args: ["-y", `${CODEX_ACP_NPM_PACKAGE}@latest`],
|
|
82
|
+
requiredEnvKeys: ["OPENAI_API_KEY", "CODEX_API_KEY"]
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
id: "claude",
|
|
86
|
+
name: "Claude",
|
|
87
|
+
description: "通过 bunx 启动官方 @agentclientprotocol/claude-agent-acp;可复用本机 Claude Code 登录态(~/.claude.json)或 ANTHROPIC_API_KEY",
|
|
88
|
+
authHint: "复用本机 Claude Code 登录(~/.claude.json / ~/.claude/.credentials.json 或 ANTHROPIC_API_KEY);未登录先跑 claude login",
|
|
89
|
+
command: "bunx",
|
|
90
|
+
args: ["-y", `${CLAUDE_ACP_NPM_PACKAGE}@latest`],
|
|
91
|
+
requiredEnvKeys: ["ANTHROPIC_API_KEY"]
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
id: "gemini",
|
|
95
|
+
name: "Gemini",
|
|
96
|
+
description: "启动本机 Gemini CLI(--acp);复用 Gemini CLI 登录态(~/.gemini/)",
|
|
97
|
+
authHint: "复用本机 Gemini CLI 登录(~/.gemini/oauth_creds.json 或 GEMINI_API_KEY / GOOGLE_API_KEY);未登录先在本机终端跑 gemini 完成登录",
|
|
98
|
+
command: isWindowsPlatform() ? "gemini.cmd" : "gemini",
|
|
99
|
+
args: ["--acp"],
|
|
100
|
+
requiredEnvKeys: []
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
id: "copilot",
|
|
104
|
+
name: "Copilot",
|
|
105
|
+
description: "启动本机 Copilot CLI(--acp --stdio);复用 Copilot CLI 的 GitHub 登录态",
|
|
106
|
+
authHint: "复用本机 Copilot CLI 的 GitHub 登录(~/.copilot/config.json 或 COPILOT_GITHUB_TOKEN / GH_TOKEN / GITHUB_TOKEN);未登录先跑 copilot login",
|
|
107
|
+
command: isWindowsPlatform() ? "copilot.cmd" : "copilot",
|
|
108
|
+
args: ["--acp", "--stdio"],
|
|
109
|
+
requiredEnvKeys: []
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
id: "opencode",
|
|
113
|
+
name: "OpenCode",
|
|
114
|
+
description: "启动本机 opencode(acp);复用 `opencode auth login` 写入 auth.json(~/.local/share/opencode/auth.json)的各 provider 凭证",
|
|
115
|
+
authHint: "已登录(%LOCALAPPDATA%\\opencode\\auth.json 或 ~/.local/share/opencode/auth.json)则直接连接;否则先跑 opencode auth login",
|
|
116
|
+
command: isWindowsPlatform() ? "opencode.exe" : "opencode",
|
|
117
|
+
args: ["acp"],
|
|
118
|
+
requiredEnvKeys: []
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
id: "cursor-cli",
|
|
122
|
+
name: "Cursor",
|
|
123
|
+
description: "启动 Cursor 官方 CLI(agent acp);复用本机 Cursor 登录态(未登录可运行 `agent login`)。安装路径探测(%LOCALAPPDATA%\\cursor-agent / ~/.local/bin/agent)见主进程 cursor 适配器",
|
|
124
|
+
authHint: "复用本机 Cursor 登录态(或 CURSOR_API_KEY / CURSOR_AUTH_TOKEN);未登录先跑 agent login",
|
|
125
|
+
command: isWindowsPlatform() ? "agent.cmd" : "agent",
|
|
126
|
+
args: ["acp"],
|
|
127
|
+
requiredEnvKeys: []
|
|
128
|
+
},
|
|
129
|
+
{
|
|
130
|
+
id: "deepseek",
|
|
131
|
+
name: "DeepSeek",
|
|
132
|
+
description: "通过 bunx 启动 @deepseek-ai/dsh(--profile acp);无 ACP 登录,靠 harness 自身凭证(DEEPSEEK_API_KEY / harness 配置);模型经 session 到达,无需额外动作",
|
|
133
|
+
authHint: "无 ACP 登录,靠 harness 自身凭证(DEEPSEEK_API_KEY / harness 配置);未配置先导出 DEEPSEEK_API_KEY;模型经 session 到达,无需额外动作;若官方最新 dsh 存在坏依赖(如 rc.3 缺失),可设 DSH_PACKAGE pin 旧版",
|
|
134
|
+
command: "bunx",
|
|
135
|
+
args: ["-y", `${DEEPSEEK_DSH_NPM_PACKAGE}@latest`, "--profile", "acp"],
|
|
136
|
+
requiredEnvKeys: ["DEEPSEEK_API_KEY"]
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
id: "agy",
|
|
140
|
+
name: "agy",
|
|
141
|
+
description: "经 bunx 直调官方桥 JS 入口(免安装,跨平台;版本跟随 bunx 解析)",
|
|
142
|
+
authHint: "复用 Antigravity CLI 本地登录态;未登录先在本机终端完成 agy 登录后再连接",
|
|
143
|
+
command: "bunx",
|
|
144
|
+
args: ["-y", `${AGY_ACP_NPM_PACKAGE}@latest`],
|
|
145
|
+
requiredEnvKeys: []
|
|
146
|
+
}
|
|
147
|
+
];
|
|
148
|
+
function findBuiltinAcpRuntime(id) {
|
|
149
|
+
return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
|
|
150
|
+
}
|
|
151
|
+
// src/client/acp-client.ts
|
|
152
|
+
import {
|
|
153
|
+
methods as methods2
|
|
154
|
+
} from "@agentclientprotocol/sdk";
|
|
155
|
+
|
|
156
|
+
// src/runtimes/codex/index.ts
|
|
157
|
+
import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
|
|
158
|
+
import { join as join4 } from "node:path";
|
|
159
|
+
|
|
160
|
+
// src/runtimes/codex/codex-provider-home.ts
|
|
161
|
+
var INKDOWN_PROVIDER_ID = "inkdown-custom";
|
|
162
|
+
var INKDOWN_PROVIDER_API_KEY_ENV = "INKDOWN_PROVIDER_API_KEY";
|
|
163
|
+
function tomlEscape(value) {
|
|
164
|
+
return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
|
|
165
|
+
}
|
|
166
|
+
function buildCustomProviderConfigToml(config) {
|
|
167
|
+
const name = config.name?.trim() || "自定义 API";
|
|
168
|
+
const wireApi = config.wireApi === "responses" ? "responses" : "chat";
|
|
169
|
+
return [
|
|
170
|
+
`model_provider = "${INKDOWN_PROVIDER_ID}"`,
|
|
171
|
+
`model = "${tomlEscape(config.model.trim())}"`,
|
|
172
|
+
"",
|
|
173
|
+
`[model_providers.${INKDOWN_PROVIDER_ID}]`,
|
|
174
|
+
`name = "${tomlEscape(name)}"`,
|
|
175
|
+
`base_url = "${tomlEscape(config.baseUrl.trim())}"`,
|
|
176
|
+
`env_key = "${INKDOWN_PROVIDER_API_KEY_ENV}"`,
|
|
177
|
+
`wire_api = "${wireApi}"`,
|
|
178
|
+
""
|
|
179
|
+
].join(`
|
|
180
|
+
`);
|
|
181
|
+
}
|
|
182
|
+
function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
|
|
183
|
+
return {
|
|
184
|
+
CODEX_HOME: codexHome,
|
|
185
|
+
[INKDOWN_PROVIDER_API_KEY_ENV]: apiKey
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// src/runtimes/codex/codex-auth-preflight.ts
|
|
190
|
+
import { existsSync } from "node:fs";
|
|
191
|
+
import { homedir } from "node:os";
|
|
192
|
+
import { join } from "node:path";
|
|
193
|
+
function emptyAcpAuthPreflight() {
|
|
194
|
+
return {
|
|
195
|
+
codexHome: "",
|
|
196
|
+
hasCodexHome: false,
|
|
197
|
+
hasAuthFile: false,
|
|
198
|
+
hasApiKeyEnv: false,
|
|
199
|
+
looksLoggedIn: false
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function isCodexPreflightRuntime(runtimeId) {
|
|
203
|
+
return !runtimeId || runtimeId === "codex-acp";
|
|
204
|
+
}
|
|
205
|
+
function resolveCodexHome() {
|
|
206
|
+
const fromEnv = process.env.CODEX_HOME?.trim();
|
|
207
|
+
if (fromEnv)
|
|
208
|
+
return fromEnv;
|
|
209
|
+
return join(homedir(), ".codex");
|
|
210
|
+
}
|
|
211
|
+
function probeCodexAuth() {
|
|
212
|
+
const codexHome = resolveCodexHome();
|
|
213
|
+
const hasCodexHome = existsSync(codexHome);
|
|
214
|
+
const hasAuthFile = existsSync(join(codexHome, "auth.json"));
|
|
215
|
+
const hasApiKeyEnv = Boolean(process.env.CODEX_API_KEY?.trim() || process.env.OPENAI_API_KEY?.trim());
|
|
216
|
+
return {
|
|
217
|
+
codexHome,
|
|
218
|
+
hasCodexHome,
|
|
219
|
+
hasAuthFile,
|
|
220
|
+
hasApiKeyEnv,
|
|
221
|
+
looksLoggedIn: hasAuthFile || hasApiKeyEnv
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// src/runtimes/codex/codex-provider.ts
|
|
226
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
227
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
228
|
+
import { join as join3 } from "node:path";
|
|
229
|
+
|
|
230
|
+
// src/client/acp-paths.ts
|
|
231
|
+
import { homedir as homedir2 } from "node:os";
|
|
232
|
+
import { join as join2 } from "node:path";
|
|
233
|
+
function getDefaultAgentDataDir() {
|
|
234
|
+
if (process.env.INKDOWN_DATA_DIR) {
|
|
235
|
+
return process.env.INKDOWN_DATA_DIR;
|
|
236
|
+
}
|
|
237
|
+
if (process.env.ACP_DATA_DIR) {
|
|
238
|
+
return process.env.ACP_DATA_DIR;
|
|
239
|
+
}
|
|
240
|
+
if (process.platform === "win32") {
|
|
241
|
+
return process.env.LOCALAPPDATA || process.env.APPDATA || join2(homedir2(), "AppData", "Local", "inkdown");
|
|
242
|
+
}
|
|
243
|
+
if (process.platform === "darwin") {
|
|
244
|
+
return join2(homedir2(), "Library", "Application Support", "inkdown");
|
|
245
|
+
}
|
|
246
|
+
return process.env.XDG_DATA_HOME || join2(homedir2(), ".local", "share", "inkdown");
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// src/runtimes/codex/codex-provider.ts
|
|
250
|
+
function providerFilePath(dir) {
|
|
251
|
+
return join3(dir, "agent", "provider.json");
|
|
252
|
+
}
|
|
253
|
+
function providerHomePath(dir) {
|
|
254
|
+
return join3(dir, "agent", "codex-home");
|
|
255
|
+
}
|
|
256
|
+
function toStatus(stored) {
|
|
257
|
+
if (!stored)
|
|
258
|
+
return { configured: false, hasApiKey: false };
|
|
259
|
+
return {
|
|
260
|
+
configured: true,
|
|
261
|
+
name: stored.name,
|
|
262
|
+
baseUrl: stored.baseUrl,
|
|
263
|
+
model: stored.model,
|
|
264
|
+
wireApi: stored.wireApi,
|
|
265
|
+
hasApiKey: Boolean(stored.apiKey)
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
function validate(payload) {
|
|
269
|
+
const base = payload.baseUrl.trim();
|
|
270
|
+
if (!/^https?:\/\/.+/.test(base))
|
|
271
|
+
return "Base URL 必须是 http(s) 地址";
|
|
272
|
+
if (!payload.model.trim())
|
|
273
|
+
return "模型 id 不能为空";
|
|
274
|
+
if ((payload.name ?? "").trim().length > 40)
|
|
275
|
+
return "名称过长(至多 40 字)";
|
|
276
|
+
return null;
|
|
277
|
+
}
|
|
278
|
+
async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
|
|
279
|
+
const file = providerFilePath(dir);
|
|
280
|
+
if (!existsSync2(file))
|
|
281
|
+
return null;
|
|
282
|
+
try {
|
|
283
|
+
const raw = JSON.parse(await readFile(file, "utf8"));
|
|
284
|
+
if (typeof raw.baseUrl !== "string" || typeof raw.model !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
return {
|
|
288
|
+
name: typeof raw.name === "string" ? raw.name : undefined,
|
|
289
|
+
baseUrl: raw.baseUrl,
|
|
290
|
+
model: raw.model,
|
|
291
|
+
apiKey: raw.apiKey,
|
|
292
|
+
wireApi: raw.wireApi === "responses" ? "responses" : "chat"
|
|
293
|
+
};
|
|
294
|
+
} catch {
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
async function getAcpProviderStatus(dir = getDefaultAgentDataDir()) {
|
|
299
|
+
return toStatus(await readStoredAcpProvider(dir));
|
|
300
|
+
}
|
|
301
|
+
async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
|
|
302
|
+
const invalid = validate(payload);
|
|
303
|
+
if (invalid)
|
|
304
|
+
return err({ code: "INVALID_ARGUMENT", message: invalid });
|
|
305
|
+
const file = providerFilePath(dir);
|
|
306
|
+
const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
|
|
307
|
+
if (!apiKey)
|
|
308
|
+
return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
|
|
309
|
+
await mkdir(join3(dir, "agent"), { recursive: true });
|
|
310
|
+
const stored = {
|
|
311
|
+
name: payload.name?.trim() || undefined,
|
|
312
|
+
baseUrl: payload.baseUrl.trim(),
|
|
313
|
+
model: payload.model.trim(),
|
|
314
|
+
apiKey,
|
|
315
|
+
wireApi: payload.wireApi === "responses" ? "responses" : "chat"
|
|
316
|
+
};
|
|
317
|
+
await writeFile(file, JSON.stringify(stored, null, 2), "utf8");
|
|
318
|
+
return ok(toStatus(stored));
|
|
319
|
+
}
|
|
320
|
+
async function clearAcpProvider(dir = getDefaultAgentDataDir()) {
|
|
321
|
+
await rm(providerFilePath(dir), { force: true });
|
|
322
|
+
return ok(undefined);
|
|
323
|
+
}
|
|
324
|
+
function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
|
|
325
|
+
return providerHomePath(dir);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// src/runtimes/codex/index.ts
|
|
329
|
+
async function provisionCustomProviderCodexHome(provider, codexHome) {
|
|
330
|
+
try {
|
|
331
|
+
await mkdir2(codexHome, { recursive: true });
|
|
332
|
+
await writeFile2(join4(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
|
|
333
|
+
return true;
|
|
334
|
+
} catch (error) {
|
|
335
|
+
console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
|
|
336
|
+
return false;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
var codexAdapter = {
|
|
340
|
+
id: "codex-acp",
|
|
341
|
+
probeAuth: () => {
|
|
342
|
+
return probeCodexAuth();
|
|
343
|
+
},
|
|
344
|
+
getCustomProvider: async () => {
|
|
345
|
+
const provider = await readStoredAcpProvider();
|
|
346
|
+
const codexHome = getAcpProviderCodexHome();
|
|
347
|
+
const isCustom = provider !== null && await provisionCustomProviderCodexHome(provider, codexHome);
|
|
348
|
+
const customEnv = isCustom && provider ? buildCustomProviderSpawnEnv(provider, provider.apiKey, codexHome) : {};
|
|
349
|
+
return {
|
|
350
|
+
provider,
|
|
351
|
+
customEnv,
|
|
352
|
+
isCustom
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
// src/runtimes/claude/index.ts
|
|
358
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
359
|
+
import { homedir as homedir3 } from "node:os";
|
|
360
|
+
import { join as join5 } from "node:path";
|
|
361
|
+
function resolveClaudeHome() {
|
|
362
|
+
const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
363
|
+
if (fromEnv)
|
|
364
|
+
return fromEnv;
|
|
365
|
+
return join5(homedir3(), ".claude");
|
|
366
|
+
}
|
|
367
|
+
function probeClaudeAuth() {
|
|
368
|
+
const claudeHome = resolveClaudeHome();
|
|
369
|
+
const hasCodexHome = existsSync3(claudeHome);
|
|
370
|
+
const hasAuthFile = existsSync3(join5(homedir3(), ".claude.json")) || existsSync3(join5(claudeHome, ".credentials.json"));
|
|
371
|
+
const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
|
|
372
|
+
return {
|
|
373
|
+
codexHome: claudeHome,
|
|
374
|
+
hasCodexHome,
|
|
375
|
+
hasAuthFile,
|
|
376
|
+
hasApiKeyEnv,
|
|
377
|
+
looksLoggedIn: hasAuthFile || hasApiKeyEnv
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
var claudeAdapter = {
|
|
381
|
+
id: "claude",
|
|
382
|
+
probeAuth: () => probeClaudeAuth(),
|
|
383
|
+
orderAuthMethods: (methods) => methods,
|
|
384
|
+
canSkipInteractiveAuth: () => false
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
// src/runtimes/gemini/index.ts
|
|
388
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
389
|
+
import { homedir as homedir4 } from "node:os";
|
|
390
|
+
import { join as join6 } from "node:path";
|
|
391
|
+
function resolveGeminiHome() {
|
|
392
|
+
return join6(homedir4(), ".gemini");
|
|
393
|
+
}
|
|
394
|
+
function probeGeminiAuth() {
|
|
395
|
+
const geminiHome = resolveGeminiHome();
|
|
396
|
+
const hasCodexHome = existsSync4(geminiHome);
|
|
397
|
+
const hasAuthFile = existsSync4(join6(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
|
|
398
|
+
const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
|
|
399
|
+
return {
|
|
400
|
+
codexHome: geminiHome,
|
|
401
|
+
hasCodexHome,
|
|
402
|
+
hasAuthFile,
|
|
403
|
+
hasApiKeyEnv,
|
|
404
|
+
looksLoggedIn: hasAuthFile || hasApiKeyEnv
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
var geminiAdapter = {
|
|
408
|
+
id: "gemini",
|
|
409
|
+
probeAuth: () => probeGeminiAuth(),
|
|
410
|
+
orderAuthMethods: (methods) => methods,
|
|
411
|
+
canSkipInteractiveAuth: () => false
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
// src/runtimes/copilot/index.ts
|
|
415
|
+
import { existsSync as existsSync5, readFileSync } from "node:fs";
|
|
416
|
+
import { homedir as homedir5 } from "node:os";
|
|
417
|
+
import { join as join7 } from "node:path";
|
|
418
|
+
function resolveCopilotHome() {
|
|
419
|
+
const fromEnv = process.env.COPILOT_HOME?.trim();
|
|
420
|
+
if (fromEnv)
|
|
421
|
+
return fromEnv;
|
|
422
|
+
return join7(homedir5(), ".copilot");
|
|
423
|
+
}
|
|
424
|
+
function hasCopilotLogin(home) {
|
|
425
|
+
try {
|
|
426
|
+
const raw = readFileSync(join7(home, "config.json"), "utf8");
|
|
427
|
+
const parsed = JSON.parse(raw);
|
|
428
|
+
return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
|
|
429
|
+
} catch {
|
|
430
|
+
return false;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
function probeCopilotAuth() {
|
|
434
|
+
const copilotHome = resolveCopilotHome();
|
|
435
|
+
const hasCodexHome = existsSync5(copilotHome);
|
|
436
|
+
const hasAuthFile = hasCopilotLogin(copilotHome);
|
|
437
|
+
const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
|
|
438
|
+
return {
|
|
439
|
+
codexHome: copilotHome,
|
|
440
|
+
hasCodexHome,
|
|
441
|
+
hasAuthFile,
|
|
442
|
+
hasApiKeyEnv,
|
|
443
|
+
looksLoggedIn: hasAuthFile || hasApiKeyEnv
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
var copilotAdapter = {
|
|
447
|
+
id: "copilot",
|
|
448
|
+
probeAuth: () => probeCopilotAuth(),
|
|
449
|
+
orderAuthMethods: (methods) => methods,
|
|
450
|
+
canSkipInteractiveAuth: () => false
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
// src/runtimes/opencode/index.ts
|
|
454
|
+
import { existsSync as existsSync6, readFileSync as readFileSync2 } from "node:fs";
|
|
455
|
+
import { homedir as homedir6 } from "node:os";
|
|
456
|
+
import { dirname, join as join8 } from "node:path";
|
|
457
|
+
function pickEnv(env, key) {
|
|
458
|
+
return env?.[key]?.trim() ?? "";
|
|
459
|
+
}
|
|
460
|
+
function resolveOpencodeAuthCandidates(overrides) {
|
|
461
|
+
const platform = overrides?.platform ?? process.platform;
|
|
462
|
+
const env = overrides?.env ?? process.env;
|
|
463
|
+
const home = overrides?.home ?? homedir6();
|
|
464
|
+
const seen = new Set;
|
|
465
|
+
const out = [];
|
|
466
|
+
const push = (p) => {
|
|
467
|
+
if (!p || seen.has(p))
|
|
468
|
+
return;
|
|
469
|
+
seen.add(p);
|
|
470
|
+
out.push(p);
|
|
471
|
+
};
|
|
472
|
+
const xdg = pickEnv(env, "XDG_DATA_HOME");
|
|
473
|
+
if (xdg)
|
|
474
|
+
push(join8(xdg, "opencode", "auth.json"));
|
|
475
|
+
if (platform === "win32") {
|
|
476
|
+
const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? join8(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
|
|
477
|
+
if (localAppData)
|
|
478
|
+
push(join8(localAppData, "opencode", "auth.json"));
|
|
479
|
+
const userProfile = pickEnv(env, "USERPROFILE") || home;
|
|
480
|
+
if (userProfile)
|
|
481
|
+
push(join8(userProfile, ".local", "share", "opencode", "auth.json"));
|
|
482
|
+
} else if (home) {
|
|
483
|
+
push(join8(home, ".local", "share", "opencode", "auth.json"));
|
|
484
|
+
}
|
|
485
|
+
return out;
|
|
486
|
+
}
|
|
487
|
+
function resolveOpencodeAuthFile() {
|
|
488
|
+
return resolveOpencodeAuthCandidates()[0] ?? join8(homedir6(), ".local", "share", "opencode", "auth.json");
|
|
489
|
+
}
|
|
490
|
+
function isValidOpencodeAuthFile(authFile) {
|
|
491
|
+
try {
|
|
492
|
+
if (!authFile || !existsSync6(authFile))
|
|
493
|
+
return false;
|
|
494
|
+
const raw = readFileSync2(authFile, "utf8").trim();
|
|
495
|
+
if (!raw)
|
|
496
|
+
return false;
|
|
497
|
+
const parsed = JSON.parse(raw);
|
|
498
|
+
if (!parsed || typeof parsed !== "object")
|
|
499
|
+
return false;
|
|
500
|
+
return Object.keys(parsed).length > 0;
|
|
501
|
+
} catch {
|
|
502
|
+
return false;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
function probeOpencodeAuth(overrides) {
|
|
506
|
+
const candidates = resolveOpencodeAuthCandidates(overrides);
|
|
507
|
+
let firstExisting = null;
|
|
508
|
+
let validFile = null;
|
|
509
|
+
for (const candidate of candidates) {
|
|
510
|
+
let exists = false;
|
|
511
|
+
try {
|
|
512
|
+
exists = existsSync6(candidate);
|
|
513
|
+
} catch {
|
|
514
|
+
exists = false;
|
|
515
|
+
}
|
|
516
|
+
if (!exists)
|
|
517
|
+
continue;
|
|
518
|
+
firstExisting ??= candidate;
|
|
519
|
+
if (validFile)
|
|
520
|
+
continue;
|
|
521
|
+
if (isValidOpencodeAuthFile(candidate))
|
|
522
|
+
validFile = candidate;
|
|
523
|
+
}
|
|
524
|
+
const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
|
|
525
|
+
const authDir = dirname(authFile);
|
|
526
|
+
let hasCodexHome = false;
|
|
527
|
+
try {
|
|
528
|
+
hasCodexHome = existsSync6(authDir);
|
|
529
|
+
} catch {
|
|
530
|
+
hasCodexHome = false;
|
|
531
|
+
}
|
|
532
|
+
const hasAuthFile = firstExisting !== null;
|
|
533
|
+
return {
|
|
534
|
+
codexHome: authDir,
|
|
535
|
+
hasCodexHome,
|
|
536
|
+
hasAuthFile,
|
|
537
|
+
hasApiKeyEnv: false,
|
|
538
|
+
looksLoggedIn: validFile !== null
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
var opencodeAdapter = {
|
|
542
|
+
id: "opencode",
|
|
543
|
+
probeAuth: () => probeOpencodeAuth(),
|
|
544
|
+
orderAuthMethods: (methods) => methods,
|
|
545
|
+
canSkipInteractiveAuth: () => false,
|
|
546
|
+
tryDirectSessionFirst: true
|
|
547
|
+
};
|
|
548
|
+
|
|
549
|
+
// src/runtimes/cursor/index.ts
|
|
550
|
+
import { spawnSync } from "node:child_process";
|
|
551
|
+
import { existsSync as existsSync7, readFileSync as readFileSync3 } from "node:fs";
|
|
552
|
+
import { homedir as homedir7 } from "node:os";
|
|
553
|
+
import { delimiter, dirname as dirname2, join as join9 } from "node:path";
|
|
554
|
+
function cursorLocalAppData(env) {
|
|
555
|
+
const local = env.LOCALAPPDATA?.trim();
|
|
556
|
+
if (local)
|
|
557
|
+
return local;
|
|
558
|
+
const profile = env.USERPROFILE?.trim();
|
|
559
|
+
return profile ? join9(profile, "AppData", "Local") : "";
|
|
560
|
+
}
|
|
561
|
+
function isOnPath(command, env, platform) {
|
|
562
|
+
const pathValue = env.PATH ?? env.Path ?? "";
|
|
563
|
+
if (!pathValue.trim())
|
|
564
|
+
return false;
|
|
565
|
+
const sep = platform === "win32" ? ";" : delimiter;
|
|
566
|
+
for (const dir of pathValue.split(sep)) {
|
|
567
|
+
const trimmed = dir.trim().replace(/^"|"$/g, "");
|
|
568
|
+
if (!trimmed)
|
|
569
|
+
continue;
|
|
570
|
+
try {
|
|
571
|
+
if (existsSync7(join9(trimmed, command)))
|
|
572
|
+
return true;
|
|
573
|
+
} catch {}
|
|
574
|
+
}
|
|
575
|
+
return false;
|
|
576
|
+
}
|
|
577
|
+
function resolveDirectCursorCommand(platform, env, home) {
|
|
578
|
+
if (platform === "win32") {
|
|
579
|
+
const localAppData = cursorLocalAppData(env);
|
|
580
|
+
return localAppData ? join9(localAppData, "cursor-agent", "agent.cmd") : "";
|
|
581
|
+
}
|
|
582
|
+
return home ? join9(home, ".local", "bin", "agent") : "";
|
|
583
|
+
}
|
|
584
|
+
function resolveCursorCommand(overrides) {
|
|
585
|
+
const args = ["acp"];
|
|
586
|
+
const platform = overrides?.platform ?? process.platform;
|
|
587
|
+
const env = overrides?.env ?? process.env;
|
|
588
|
+
const home = overrides?.home ?? homedir7();
|
|
589
|
+
if (platform === "win32") {
|
|
590
|
+
const directCmd = resolveDirectCursorCommand(platform, env, home);
|
|
591
|
+
if (directCmd && existsSync7(directCmd)) {
|
|
592
|
+
return { command: directCmd, args };
|
|
593
|
+
}
|
|
594
|
+
return { command: "agent.cmd", args };
|
|
595
|
+
}
|
|
596
|
+
const directBin = resolveDirectCursorCommand(platform, env, home);
|
|
597
|
+
if (directBin && existsSync7(directBin)) {
|
|
598
|
+
return { command: directBin, args };
|
|
599
|
+
}
|
|
600
|
+
return { command: "agent", args };
|
|
601
|
+
}
|
|
602
|
+
function resolveCursorSpawnCommand(overrides) {
|
|
603
|
+
const args = ["acp"];
|
|
604
|
+
const platform = overrides?.platform ?? process.platform;
|
|
605
|
+
const env = overrides?.env ?? process.env;
|
|
606
|
+
const home = overrides?.home ?? homedir7();
|
|
607
|
+
const binary = platform === "win32" ? "agent.cmd" : "agent";
|
|
608
|
+
const direct = resolveDirectCursorCommand(platform, env, home);
|
|
609
|
+
try {
|
|
610
|
+
if (direct && existsSync7(direct))
|
|
611
|
+
return { command: direct, args };
|
|
612
|
+
} catch {}
|
|
613
|
+
if (isOnPath(binary, env, platform))
|
|
614
|
+
return { command: binary, args };
|
|
615
|
+
return null;
|
|
616
|
+
}
|
|
617
|
+
function buildCursorMissingCliMessage(overrides) {
|
|
618
|
+
const platform = overrides?.platform ?? process.platform;
|
|
619
|
+
if (platform === "win32") {
|
|
620
|
+
return "Cursor CLI 未安装:请在终端执行 irm https://cursor.com/install?win32=true | iex 后重试(已安装请确认 agent.cmd 在 PATH,或 %LOCALAPPDATA%\\cursor-agent\\agent.cmd 存在)";
|
|
621
|
+
}
|
|
622
|
+
return "Cursor CLI 未安装:请在终端执行 curl https://cursor.com/install -fsS | bash 后重试(已安装请确认 agent 在 PATH,或 ~/.local/bin/agent 存在)";
|
|
623
|
+
}
|
|
624
|
+
function pickEnv2(env, key) {
|
|
625
|
+
return env?.[key]?.trim() ?? "";
|
|
626
|
+
}
|
|
627
|
+
function cursorRoamingAppData(env, home) {
|
|
628
|
+
const roaming = pickEnv2(env, "APPDATA");
|
|
629
|
+
if (roaming)
|
|
630
|
+
return roaming;
|
|
631
|
+
const profile = pickEnv2(env, "USERPROFILE") || home;
|
|
632
|
+
return profile ? join9(profile, "AppData", "Roaming") : "";
|
|
633
|
+
}
|
|
634
|
+
function resolveCursorAuthCandidates(overrides) {
|
|
635
|
+
const platform = overrides?.platform ?? process.platform;
|
|
636
|
+
const env = overrides?.env ?? process.env;
|
|
637
|
+
const home = overrides?.home ?? homedir7();
|
|
638
|
+
const seen = new Set;
|
|
639
|
+
const out = [];
|
|
640
|
+
const push = (p) => {
|
|
641
|
+
if (!p || seen.has(p))
|
|
642
|
+
return;
|
|
643
|
+
seen.add(p);
|
|
644
|
+
out.push(p);
|
|
645
|
+
};
|
|
646
|
+
const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
|
|
647
|
+
if (xdg)
|
|
648
|
+
push(join9(xdg, "cursor", "auth.json"));
|
|
649
|
+
if (platform === "win32") {
|
|
650
|
+
const profile = pickEnv2(env, "USERPROFILE") || home;
|
|
651
|
+
if (profile)
|
|
652
|
+
push(join9(profile, ".config", "cursor", "auth.json"));
|
|
653
|
+
const roaming = cursorRoamingAppData(env, home);
|
|
654
|
+
if (roaming)
|
|
655
|
+
push(join9(roaming, "Cursor", "User", "globalStorage", "storage.json"));
|
|
656
|
+
} else if (home) {
|
|
657
|
+
push(join9(home, ".config", "cursor", "auth.json"));
|
|
658
|
+
}
|
|
659
|
+
return out;
|
|
660
|
+
}
|
|
661
|
+
function isStorageHintPath(authFile) {
|
|
662
|
+
return authFile.replace(/\\/g, "/").endsWith("/globalStorage/storage.json");
|
|
663
|
+
}
|
|
664
|
+
function isValidCursorAuthFile(authFile) {
|
|
665
|
+
try {
|
|
666
|
+
if (!authFile || isStorageHintPath(authFile))
|
|
667
|
+
return false;
|
|
668
|
+
if (!existsSync7(authFile))
|
|
669
|
+
return false;
|
|
670
|
+
const raw = readFileSync3(authFile, "utf8").trim();
|
|
671
|
+
if (!raw)
|
|
672
|
+
return false;
|
|
673
|
+
const parsed = JSON.parse(raw);
|
|
674
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
675
|
+
return false;
|
|
676
|
+
const row = parsed;
|
|
677
|
+
const access = typeof row.accessToken === "string" ? row.accessToken.trim() : "";
|
|
678
|
+
const refresh = typeof row.refreshToken === "string" ? row.refreshToken.trim() : "";
|
|
679
|
+
return Boolean(access || refresh);
|
|
680
|
+
} catch {
|
|
681
|
+
return false;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
function isHintCursorStorageFile(authFile) {
|
|
685
|
+
try {
|
|
686
|
+
if (!authFile || !isStorageHintPath(authFile))
|
|
687
|
+
return false;
|
|
688
|
+
if (!existsSync7(authFile))
|
|
689
|
+
return false;
|
|
690
|
+
const raw = readFileSync3(authFile, "utf8").trim();
|
|
691
|
+
if (!raw)
|
|
692
|
+
return false;
|
|
693
|
+
const parsed = JSON.parse(raw);
|
|
694
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
695
|
+
return false;
|
|
696
|
+
return Object.keys(parsed).length > 0;
|
|
697
|
+
} catch {
|
|
698
|
+
return false;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
function isValidCursorCandidate(authFile) {
|
|
702
|
+
return isStorageHintPath(authFile) ? isHintCursorStorageFile(authFile) : isValidCursorAuthFile(authFile);
|
|
703
|
+
}
|
|
704
|
+
function probeCursorAuth(overrides) {
|
|
705
|
+
const env = overrides?.env ?? process.env;
|
|
706
|
+
const home = overrides?.home ?? homedir7();
|
|
707
|
+
const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
|
|
708
|
+
const candidates = resolveCursorAuthCandidates(overrides);
|
|
709
|
+
let firstExisting = null;
|
|
710
|
+
let validFile = null;
|
|
711
|
+
for (const candidate of candidates) {
|
|
712
|
+
let exists = false;
|
|
713
|
+
try {
|
|
714
|
+
exists = existsSync7(candidate);
|
|
715
|
+
} catch {
|
|
716
|
+
exists = false;
|
|
717
|
+
}
|
|
718
|
+
if (!exists)
|
|
719
|
+
continue;
|
|
720
|
+
firstExisting ??= candidate;
|
|
721
|
+
if (validFile)
|
|
722
|
+
continue;
|
|
723
|
+
if (isValidCursorCandidate(candidate))
|
|
724
|
+
validFile = candidate;
|
|
725
|
+
}
|
|
726
|
+
const fallback = home ? join9(home, ".config", "cursor", "auth.json") : "";
|
|
727
|
+
const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
|
|
728
|
+
const authDir = authFile ? dirname2(authFile) : "";
|
|
729
|
+
let hasCodexHome = false;
|
|
730
|
+
try {
|
|
731
|
+
hasCodexHome = authDir ? existsSync7(authDir) : false;
|
|
732
|
+
} catch {
|
|
733
|
+
hasCodexHome = false;
|
|
734
|
+
}
|
|
735
|
+
return {
|
|
736
|
+
codexHome: authDir,
|
|
737
|
+
hasCodexHome,
|
|
738
|
+
hasAuthFile: firstExisting !== null,
|
|
739
|
+
hasApiKeyEnv,
|
|
740
|
+
looksLoggedIn: validFile !== null || hasApiKeyEnv
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
var cursorAdapter = {
|
|
744
|
+
id: "cursor-cli",
|
|
745
|
+
probeAuth: () => probeCursorAuth(),
|
|
746
|
+
resolveSpawnCommand: () => resolveCursorSpawnCommand(),
|
|
747
|
+
orderAuthMethods: (methods) => methods,
|
|
748
|
+
canSkipInteractiveAuth: () => false,
|
|
749
|
+
tryDirectSessionFirst: true
|
|
750
|
+
};
|
|
751
|
+
function parseCursorCatalogOutput(output) {
|
|
752
|
+
if (typeof output !== "string")
|
|
753
|
+
return [];
|
|
754
|
+
const out = [];
|
|
755
|
+
for (const line of output.split(/\r?\n/)) {
|
|
756
|
+
let trimmed = line.trim();
|
|
757
|
+
if (!trimmed)
|
|
758
|
+
continue;
|
|
759
|
+
if (trimmed.startsWith("*")) {
|
|
760
|
+
trimmed = trimmed.slice(1).trim();
|
|
761
|
+
if (!trimmed)
|
|
762
|
+
continue;
|
|
763
|
+
}
|
|
764
|
+
const first = trimmed.split(/\s+/)[0]?.trim() ?? "";
|
|
765
|
+
if (!first)
|
|
766
|
+
continue;
|
|
767
|
+
out.push(first);
|
|
768
|
+
}
|
|
769
|
+
return out;
|
|
770
|
+
}
|
|
771
|
+
var cachedCursorCatalogIds;
|
|
772
|
+
function clearCursorCatalogCache() {
|
|
773
|
+
cachedCursorCatalogIds = undefined;
|
|
774
|
+
}
|
|
775
|
+
function getCursorCatalogIds(execFile, overrides) {
|
|
776
|
+
if (cachedCursorCatalogIds !== undefined)
|
|
777
|
+
return cachedCursorCatalogIds;
|
|
778
|
+
let command = execFile?.trim() || "";
|
|
779
|
+
if (!command) {
|
|
780
|
+
let resolved = null;
|
|
781
|
+
try {
|
|
782
|
+
resolved = resolveCursorSpawnCommand(overrides);
|
|
783
|
+
} catch {
|
|
784
|
+
resolved = null;
|
|
785
|
+
}
|
|
786
|
+
if (!resolved?.command) {
|
|
787
|
+
cachedCursorCatalogIds = null;
|
|
788
|
+
return null;
|
|
789
|
+
}
|
|
790
|
+
command = resolved.command;
|
|
791
|
+
}
|
|
792
|
+
try {
|
|
793
|
+
const shell = command.toLowerCase().endsWith(".cmd");
|
|
794
|
+
const result = spawnSync(command, ["--list-models"], {
|
|
795
|
+
encoding: "utf8",
|
|
796
|
+
timeout: 6000,
|
|
797
|
+
windowsHide: true,
|
|
798
|
+
shell
|
|
799
|
+
});
|
|
800
|
+
if (result.error || result.status !== 0) {
|
|
801
|
+
cachedCursorCatalogIds = null;
|
|
802
|
+
return null;
|
|
803
|
+
}
|
|
804
|
+
const ids = parseCursorCatalogOutput(result.stdout);
|
|
805
|
+
if (ids.length === 0) {
|
|
806
|
+
cachedCursorCatalogIds = null;
|
|
807
|
+
return null;
|
|
808
|
+
}
|
|
809
|
+
cachedCursorCatalogIds = ids;
|
|
810
|
+
return ids;
|
|
811
|
+
} catch {
|
|
812
|
+
cachedCursorCatalogIds = null;
|
|
813
|
+
return null;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// src/runtimes/deepseek/index.ts
|
|
818
|
+
function buildDeepseekMissingKeyMessage() {
|
|
819
|
+
return "未检测到 DEEPSEEK_API_KEY:请先在终端导出该变量(或完成 harness 自身登录)后再连接";
|
|
820
|
+
}
|
|
821
|
+
function resolveDeepseekSpawnBlocker(env) {
|
|
822
|
+
const source = env ?? process.env;
|
|
823
|
+
if (source.DEEPSEEK_API_KEY?.trim())
|
|
824
|
+
return null;
|
|
825
|
+
return buildDeepseekMissingKeyMessage();
|
|
826
|
+
}
|
|
827
|
+
function resolveDeepseekPackage(env) {
|
|
828
|
+
const source = env ?? process.env;
|
|
829
|
+
const raw = source.DSH_PACKAGE?.trim();
|
|
830
|
+
if (!raw)
|
|
831
|
+
return DEEPSEEK_DSH_NPM_PACKAGE;
|
|
832
|
+
if (/[\s;&|$()`"'\\<>*?~#!]/.test(raw)) {
|
|
833
|
+
if (true) {
|
|
834
|
+
console.warn(`[acp:deepseek] 非法 DSH_PACKAGE 回落缺省: ${raw}`);
|
|
835
|
+
}
|
|
836
|
+
return DEEPSEEK_DSH_NPM_PACKAGE;
|
|
837
|
+
}
|
|
838
|
+
return raw;
|
|
839
|
+
}
|
|
840
|
+
function resolveDeepseekSpawnCommand(env) {
|
|
841
|
+
const pkg = resolveDeepseekPackage(env);
|
|
842
|
+
const spec = pkg === DEEPSEEK_DSH_NPM_PACKAGE ? `${pkg}@latest` : pkg;
|
|
843
|
+
return { command: "bunx", args: ["-y", spec, "--profile", "acp"] };
|
|
844
|
+
}
|
|
845
|
+
function probeDeepseekAuth() {
|
|
846
|
+
const hasApiKeyEnv = Boolean(process.env.DEEPSEEK_API_KEY?.trim());
|
|
847
|
+
return {
|
|
848
|
+
codexHome: "",
|
|
849
|
+
hasCodexHome: false,
|
|
850
|
+
hasAuthFile: false,
|
|
851
|
+
hasApiKeyEnv,
|
|
852
|
+
looksLoggedIn: hasApiKeyEnv
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
var deepseekAdapter = {
|
|
856
|
+
id: "deepseek",
|
|
857
|
+
probeAuth: () => probeDeepseekAuth(),
|
|
858
|
+
resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
|
|
859
|
+
resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
|
|
860
|
+
orderAuthMethods: (methods) => methods,
|
|
861
|
+
canSkipInteractiveAuth: () => false
|
|
862
|
+
};
|
|
863
|
+
|
|
864
|
+
// src/runtimes/agy/index.ts
|
|
865
|
+
function probeAgyAuth() {
|
|
866
|
+
return {
|
|
867
|
+
codexHome: "",
|
|
868
|
+
hasCodexHome: false,
|
|
869
|
+
hasAuthFile: false,
|
|
870
|
+
hasApiKeyEnv: false,
|
|
871
|
+
looksLoggedIn: false
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
var agyAdapter = {
|
|
875
|
+
id: "agy",
|
|
876
|
+
probeAuth: () => probeAgyAuth(),
|
|
877
|
+
orderAuthMethods: (methods) => methods,
|
|
878
|
+
canSkipInteractiveAuth: () => false,
|
|
879
|
+
tryDirectSessionFirst: true
|
|
880
|
+
};
|
|
881
|
+
|
|
882
|
+
// src/runtimes/index.ts
|
|
883
|
+
function getAcpRuntimeAdapter(runtimeId) {
|
|
884
|
+
if (runtimeId === DEFAULT_ACP_RUNTIME_ID) {
|
|
885
|
+
return codexAdapter;
|
|
886
|
+
}
|
|
887
|
+
switch (runtimeId) {
|
|
888
|
+
case claudeAdapter.id:
|
|
889
|
+
return claudeAdapter;
|
|
890
|
+
case geminiAdapter.id:
|
|
891
|
+
return geminiAdapter;
|
|
892
|
+
case copilotAdapter.id:
|
|
893
|
+
return copilotAdapter;
|
|
894
|
+
case opencodeAdapter.id:
|
|
895
|
+
return opencodeAdapter;
|
|
896
|
+
case cursorAdapter.id:
|
|
897
|
+
case "cursor":
|
|
898
|
+
return cursorAdapter;
|
|
899
|
+
case deepseekAdapter.id:
|
|
900
|
+
return deepseekAdapter;
|
|
901
|
+
case agyAdapter.id:
|
|
902
|
+
return agyAdapter;
|
|
903
|
+
default:
|
|
904
|
+
return {
|
|
905
|
+
id: runtimeId,
|
|
906
|
+
probeAuth: emptyAcpAuthPreflight
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// src/process/process-manager.ts
|
|
912
|
+
import { spawn, spawnSync as spawnSync2 } from "node:child_process";
|
|
913
|
+
var active = new Map;
|
|
914
|
+
var ACP_EARLY_EXIT_WINDOW_MS = 3000;
|
|
915
|
+
var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
|
|
916
|
+
function isSpawnedAcpProcessAlive(handle) {
|
|
917
|
+
const child = handle.child;
|
|
918
|
+
return !child.killed && child.exitCode === null && child.signalCode === null;
|
|
919
|
+
}
|
|
920
|
+
function killProcessTree(pid) {
|
|
921
|
+
if (process.platform !== "win32")
|
|
922
|
+
return;
|
|
923
|
+
try {
|
|
924
|
+
spawnSync2("taskkill", ["/F", "/T", "/PID", String(pid)], {
|
|
925
|
+
windowsHide: true,
|
|
926
|
+
timeout: 8000
|
|
927
|
+
});
|
|
928
|
+
} catch {}
|
|
929
|
+
}
|
|
930
|
+
function resolveCommand(runtime) {
|
|
931
|
+
if (process.platform === "win32") {
|
|
932
|
+
const cmd = runtime.command.toLowerCase();
|
|
933
|
+
if (/\.exe$/i.test(cmd) || cmd === "bun" || cmd === "node") {
|
|
934
|
+
return { file: runtime.command, shell: false };
|
|
935
|
+
}
|
|
936
|
+
return { file: runtime.command, shell: true };
|
|
937
|
+
}
|
|
938
|
+
return { file: runtime.command, shell: false };
|
|
939
|
+
}
|
|
940
|
+
function spawnAcpProcess(options) {
|
|
941
|
+
if (!options.runtime?.id || !options.runtime.command || !Array.isArray(options.runtime.args)) {
|
|
942
|
+
throw new Error(`ACP 运行时模板缺失 command/args: ${options.runtime?.id ?? "(empty)"}`);
|
|
943
|
+
}
|
|
944
|
+
const existing = active.get(options.runtime.id);
|
|
945
|
+
if (existing) {
|
|
946
|
+
existing.kill();
|
|
947
|
+
}
|
|
948
|
+
const { file, shell } = resolveCommand(options.runtime);
|
|
949
|
+
const env = {
|
|
950
|
+
...process.env,
|
|
951
|
+
...options.env
|
|
952
|
+
};
|
|
953
|
+
for (const key of options.envRemove ?? []) {
|
|
954
|
+
delete env[key];
|
|
955
|
+
}
|
|
956
|
+
for (const key of Object.keys(env)) {
|
|
957
|
+
if (key.startsWith("_PYI") || key.startsWith("_MEI")) {
|
|
958
|
+
delete env[key];
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
const forceNoBrowser = process.env.INKDOWN_ACP_NO_BROWSER === "1" || process.env.CI === "true" || process.env.CI === "1";
|
|
962
|
+
if (forceNoBrowser) {
|
|
963
|
+
env.NO_BROWSER = "1";
|
|
964
|
+
} else {
|
|
965
|
+
delete env.NO_BROWSER;
|
|
966
|
+
}
|
|
967
|
+
const child = spawn(file, options.runtime.args, {
|
|
968
|
+
cwd: options.cwd,
|
|
969
|
+
env,
|
|
970
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
971
|
+
shell,
|
|
972
|
+
windowsHide: true
|
|
973
|
+
});
|
|
974
|
+
let stderrBuffer = "";
|
|
975
|
+
const stderrTail = [];
|
|
976
|
+
const pushStderrTailLine = (line) => {
|
|
977
|
+
if (!line.trim())
|
|
978
|
+
return;
|
|
979
|
+
stderrTail.push(line);
|
|
980
|
+
if (stderrTail.length > ACP_EARLY_EXIT_STDERR_TAIL_LINES) {
|
|
981
|
+
stderrTail.splice(0, stderrTail.length - ACP_EARLY_EXIT_STDERR_TAIL_LINES);
|
|
982
|
+
}
|
|
983
|
+
};
|
|
984
|
+
child.stderr.setEncoding("utf8");
|
|
985
|
+
child.stderr.on("data", (chunk) => {
|
|
986
|
+
stderrBuffer += chunk;
|
|
987
|
+
while (true) {
|
|
988
|
+
const idx = stderrBuffer.indexOf(`
|
|
989
|
+
`);
|
|
990
|
+
if (idx < 0)
|
|
991
|
+
break;
|
|
992
|
+
const line = stderrBuffer.slice(0, idx).replace(/\r$/, "");
|
|
993
|
+
stderrBuffer = stderrBuffer.slice(idx + 1);
|
|
994
|
+
if (line.trim()) {
|
|
995
|
+
pushStderrTailLine(line);
|
|
996
|
+
if (true) {
|
|
997
|
+
console.error(`[acp:${options.runtime.id}]`, line);
|
|
998
|
+
}
|
|
999
|
+
options.onStderrLine?.(line);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
});
|
|
1003
|
+
const handle = {
|
|
1004
|
+
runtimeId: options.runtime.id,
|
|
1005
|
+
child,
|
|
1006
|
+
spawnedAt: Date.now(),
|
|
1007
|
+
stderrTail,
|
|
1008
|
+
kill: () => {
|
|
1009
|
+
if (isSpawnedAcpProcessAlive(handle)) {
|
|
1010
|
+
try {
|
|
1011
|
+
child.stdin.end();
|
|
1012
|
+
} catch {}
|
|
1013
|
+
if (typeof child.pid === "number") {
|
|
1014
|
+
killProcessTree(child.pid);
|
|
1015
|
+
}
|
|
1016
|
+
if (!child.killed) {
|
|
1017
|
+
try {
|
|
1018
|
+
child.kill();
|
|
1019
|
+
} catch {}
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
active.delete(options.runtime.id);
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
child.on("exit", (code, signal) => {
|
|
1026
|
+
const rest = stderrBuffer.trim();
|
|
1027
|
+
if (rest)
|
|
1028
|
+
pushStderrTailLine(rest);
|
|
1029
|
+
stderrBuffer = "";
|
|
1030
|
+
active.delete(options.runtime.id);
|
|
1031
|
+
options.onExit?.(code, signal);
|
|
1032
|
+
});
|
|
1033
|
+
active.set(options.runtime.id, handle);
|
|
1034
|
+
return handle;
|
|
1035
|
+
}
|
|
1036
|
+
function getAcpEarlyExitStderrDetail(handle, _now = Date.now()) {
|
|
1037
|
+
if (!handle)
|
|
1038
|
+
return null;
|
|
1039
|
+
const tail = (handle.stderrTail ?? []).filter((line) => line.trim()).slice(-ACP_EARLY_EXIT_STDERR_TAIL_LINES);
|
|
1040
|
+
if (tail.length === 0)
|
|
1041
|
+
return null;
|
|
1042
|
+
return tail.join(`
|
|
1043
|
+
`);
|
|
1044
|
+
}
|
|
1045
|
+
function withAcpEarlyExitDetail(message, detail) {
|
|
1046
|
+
if (!detail)
|
|
1047
|
+
return message;
|
|
1048
|
+
if (message.includes(detail))
|
|
1049
|
+
return message;
|
|
1050
|
+
return `${message}
|
|
1051
|
+
|
|
1052
|
+
子进程早退 stderr 尾部:
|
|
1053
|
+
${detail}`;
|
|
1054
|
+
}
|
|
1055
|
+
function disposeAllAcpProcesses() {
|
|
1056
|
+
for (const handle of [...active.values()]) {
|
|
1057
|
+
handle.kill();
|
|
1058
|
+
}
|
|
1059
|
+
active.clear();
|
|
1060
|
+
}
|
|
1061
|
+
function getActiveAcpProcess(runtimeId) {
|
|
1062
|
+
return active.get(runtimeId);
|
|
1063
|
+
}
|
|
1064
|
+
function listLiveAcpRuntimeIds() {
|
|
1065
|
+
const ids = [];
|
|
1066
|
+
for (const [runtimeId, handle] of active) {
|
|
1067
|
+
if (isSpawnedAcpProcessAlive(handle))
|
|
1068
|
+
ids.push(runtimeId);
|
|
1069
|
+
}
|
|
1070
|
+
return ids.sort();
|
|
1071
|
+
}
|
|
1072
|
+
function getLiveAcpProcess(runtimeId) {
|
|
1073
|
+
const handle = active.get(runtimeId);
|
|
1074
|
+
if (!handle)
|
|
1075
|
+
return;
|
|
1076
|
+
if (!isSpawnedAcpProcessAlive(handle)) {
|
|
1077
|
+
active.delete(runtimeId);
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
return handle;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
// src/client/sdk-client.ts
|
|
1084
|
+
import { PassThrough, Readable, Writable } from "node:stream";
|
|
1085
|
+
import {
|
|
1086
|
+
client as createSdkClientApp,
|
|
1087
|
+
ndJsonStream
|
|
1088
|
+
} from "@agentclientprotocol/sdk";
|
|
1089
|
+
var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
|
|
1090
|
+
function createSdkStreamHandle(child) {
|
|
1091
|
+
const stdoutBridge = new PassThrough;
|
|
1092
|
+
const stdinBridge = new PassThrough;
|
|
1093
|
+
child.stdout.pipe(stdoutBridge);
|
|
1094
|
+
stdinBridge.pipe(child.stdin, { end: false });
|
|
1095
|
+
const output = Writable.toWeb(stdinBridge);
|
|
1096
|
+
const input = Readable.toWeb(stdoutBridge);
|
|
1097
|
+
const stream = ndJsonStream(output, input);
|
|
1098
|
+
let disposed = false;
|
|
1099
|
+
return {
|
|
1100
|
+
stream,
|
|
1101
|
+
dispose: () => {
|
|
1102
|
+
if (disposed)
|
|
1103
|
+
return;
|
|
1104
|
+
disposed = true;
|
|
1105
|
+
try {
|
|
1106
|
+
child.stdout.unpipe(stdoutBridge);
|
|
1107
|
+
} catch {}
|
|
1108
|
+
try {
|
|
1109
|
+
stdinBridge.unpipe(child.stdin);
|
|
1110
|
+
} catch {}
|
|
1111
|
+
try {
|
|
1112
|
+
stdoutBridge.destroy();
|
|
1113
|
+
} catch {}
|
|
1114
|
+
try {
|
|
1115
|
+
stdinBridge.destroy();
|
|
1116
|
+
} catch {}
|
|
1117
|
+
}
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
function connectSdkClient(child, configure, runtimeId) {
|
|
1121
|
+
if (runtimeId && true) {
|
|
1122
|
+
console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
|
|
1123
|
+
}
|
|
1124
|
+
const app = createSdkClientApp({ name: "inkdown" });
|
|
1125
|
+
configure(app);
|
|
1126
|
+
const streamHandle = createSdkStreamHandle(child);
|
|
1127
|
+
const connection = app.connect(streamHandle.stream);
|
|
1128
|
+
return { app, connection, streamHandle };
|
|
1129
|
+
}
|
|
1130
|
+
async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
|
|
1131
|
+
const controller = new AbortController;
|
|
1132
|
+
let timer;
|
|
1133
|
+
try {
|
|
1134
|
+
const pending = agent.request(method, params, {
|
|
1135
|
+
cancellationSignal: controller.signal
|
|
1136
|
+
});
|
|
1137
|
+
const timeout = new Promise((_, reject) => {
|
|
1138
|
+
timer = setTimeout(() => {
|
|
1139
|
+
controller.abort();
|
|
1140
|
+
reject(new Error(`请求超时: ${method}`));
|
|
1141
|
+
}, timeoutMs);
|
|
1142
|
+
timer.unref?.();
|
|
1143
|
+
});
|
|
1144
|
+
return await Promise.race([pending, timeout]);
|
|
1145
|
+
} finally {
|
|
1146
|
+
if (timer !== undefined)
|
|
1147
|
+
clearTimeout(timer);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
// src/client/client-handlers.ts
|
|
1152
|
+
import { methods, RequestError } from "@agentclientprotocol/sdk";
|
|
1153
|
+
|
|
1154
|
+
// src/client/acp-fs.ts
|
|
1155
|
+
import { access, readFile as readFile2, writeFile as writeFile3 } from "node:fs/promises";
|
|
1156
|
+
import { dirname as dirname3, extname, resolve, sep } from "node:path";
|
|
1157
|
+
import { mkdir as mkdir3 } from "node:fs/promises";
|
|
1158
|
+
var MAX_READ_BYTES = 2 * 1024 * 1024;
|
|
1159
|
+
var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
|
|
1160
|
+
function isBinaryDocumentPath(filePath) {
|
|
1161
|
+
return BINARY_DOCUMENT_EXTENSIONS.has(extname(filePath).toLowerCase());
|
|
1162
|
+
}
|
|
1163
|
+
function assertPathInsideWorkspace(filePath, workspaceRoot) {
|
|
1164
|
+
const root = resolve(workspaceRoot);
|
|
1165
|
+
const target = resolve(filePath);
|
|
1166
|
+
const rootWithSep = root.endsWith(sep) ? root : root + sep;
|
|
1167
|
+
if (target !== root && !target.startsWith(rootWithSep)) {
|
|
1168
|
+
throw new Error(`路径不在工作区内: ${filePath}`);
|
|
1169
|
+
}
|
|
1170
|
+
return target;
|
|
1171
|
+
}
|
|
1172
|
+
async function acpReadTextFile(params) {
|
|
1173
|
+
if (isBinaryDocumentPath(params.path)) {
|
|
1174
|
+
throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
|
|
1175
|
+
}
|
|
1176
|
+
const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
|
|
1177
|
+
await access(abs);
|
|
1178
|
+
let content = await readFile2(abs, "utf-8");
|
|
1179
|
+
if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
|
|
1180
|
+
content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
|
|
1181
|
+
content += `
|
|
1182
|
+
|
|
1183
|
+
…[截断:文件过大]…`;
|
|
1184
|
+
}
|
|
1185
|
+
if (typeof params.line === "number" && params.line > 0) {
|
|
1186
|
+
const lines = content.split(`
|
|
1187
|
+
`);
|
|
1188
|
+
const start = params.line - 1;
|
|
1189
|
+
const limit = typeof params.limit === "number" && params.limit > 0 ? params.limit : lines.length;
|
|
1190
|
+
content = lines.slice(start, start + limit).join(`
|
|
1191
|
+
`);
|
|
1192
|
+
}
|
|
1193
|
+
return { content };
|
|
1194
|
+
}
|
|
1195
|
+
async function acpWriteTextFile(params) {
|
|
1196
|
+
const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
|
|
1197
|
+
await mkdir3(dirname3(abs), { recursive: true });
|
|
1198
|
+
await writeFile3(abs, params.content, "utf-8");
|
|
1199
|
+
return {};
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
// src/client/client-handlers.ts
|
|
1203
|
+
function toInvalidParams(message) {
|
|
1204
|
+
return RequestError.invalidParams(undefined, message);
|
|
1205
|
+
}
|
|
1206
|
+
function toServerError(error, fallback) {
|
|
1207
|
+
return new RequestError(-32000, error instanceof Error ? error.message : fallback);
|
|
1208
|
+
}
|
|
1209
|
+
function registerAcpClientHandlers(app, deps) {
|
|
1210
|
+
app.onRequest(methods.client.session.requestPermission, async (ctx) => {
|
|
1211
|
+
const params = ctx.params;
|
|
1212
|
+
const toolCall = params.toolCall;
|
|
1213
|
+
const toolHint = toolCall && typeof toolCall === "object" ? {
|
|
1214
|
+
id: typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : undefined,
|
|
1215
|
+
title: typeof toolCall.title === "string" ? toolCall.title : undefined,
|
|
1216
|
+
kind: typeof toolCall.kind === "string" ? toolCall.kind : undefined
|
|
1217
|
+
} : undefined;
|
|
1218
|
+
console.info("[acp] ← Agent request", {
|
|
1219
|
+
requestId: ctx.requestId,
|
|
1220
|
+
method: "session/request_permission",
|
|
1221
|
+
toolCall: toolHint,
|
|
1222
|
+
optionCount: Array.isArray(params.options) ? params.options.length : undefined
|
|
1223
|
+
});
|
|
1224
|
+
try {
|
|
1225
|
+
const outcome = await deps.onPermission({
|
|
1226
|
+
sessionId: typeof params.sessionId === "string" ? params.sessionId : undefined,
|
|
1227
|
+
params
|
|
1228
|
+
});
|
|
1229
|
+
return { outcome };
|
|
1230
|
+
} catch (error) {
|
|
1231
|
+
console.error("[acp] request_permission 失败", error);
|
|
1232
|
+
return { outcome: { outcome: "cancelled" } };
|
|
1233
|
+
}
|
|
1234
|
+
});
|
|
1235
|
+
app.onRequest(methods.client.fs.readTextFile, async (ctx) => {
|
|
1236
|
+
const workspaceRoot = deps.getWorkspaceRoot();
|
|
1237
|
+
const filePath = ctx.params.path;
|
|
1238
|
+
if (!workspaceRoot || !filePath) {
|
|
1239
|
+
throw toInvalidParams("fs/read_text_file 需要 path 与已连接工作区");
|
|
1240
|
+
}
|
|
1241
|
+
const virtualResource = parseInkdownVirtualPath(filePath, workspaceRoot);
|
|
1242
|
+
if (virtualResource) {
|
|
1243
|
+
try {
|
|
1244
|
+
const content = await deps.readSnapshot(virtualResource);
|
|
1245
|
+
console.info("[acp] fs/read_text_file 虚拟快照 ok", {
|
|
1246
|
+
resource: virtualResource,
|
|
1247
|
+
chars: content.length
|
|
1248
|
+
});
|
|
1249
|
+
return { content };
|
|
1250
|
+
} catch (error) {
|
|
1251
|
+
throw toServerError(error, "读取 Inkdown 快照失败");
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
if (isInkdownVirtualDirPath(filePath, workspaceRoot)) {
|
|
1255
|
+
throw toInvalidParams(`Inkdown 虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
|
|
1256
|
+
}
|
|
1257
|
+
try {
|
|
1258
|
+
const result = await acpReadTextFile({
|
|
1259
|
+
path: filePath,
|
|
1260
|
+
workspaceRoot,
|
|
1261
|
+
line: ctx.params.line ?? undefined,
|
|
1262
|
+
limit: ctx.params.limit ?? undefined
|
|
1263
|
+
});
|
|
1264
|
+
console.info("[acp] fs/read_text_file ok", { path: filePath });
|
|
1265
|
+
return result;
|
|
1266
|
+
} catch (error) {
|
|
1267
|
+
throw toServerError(error, "读取文件失败");
|
|
1268
|
+
}
|
|
1269
|
+
});
|
|
1270
|
+
app.onRequest(methods.client.fs.writeTextFile, async (ctx) => {
|
|
1271
|
+
const workspaceRoot = deps.getWorkspaceRoot();
|
|
1272
|
+
const filePath = ctx.params.path;
|
|
1273
|
+
const content = ctx.params.content;
|
|
1274
|
+
if (!workspaceRoot || !filePath || typeof content !== "string") {
|
|
1275
|
+
throw toInvalidParams("fs/write_text_file 需要 path、content 与已连接工作区");
|
|
1276
|
+
}
|
|
1277
|
+
try {
|
|
1278
|
+
console.info("[acp] fs/write_text_file(无内嵌审批,依赖 Agent 是否先 request_permission)", {
|
|
1279
|
+
path: filePath,
|
|
1280
|
+
bytes: content.length
|
|
1281
|
+
});
|
|
1282
|
+
return await acpWriteTextFile({ path: filePath, content, workspaceRoot });
|
|
1283
|
+
} catch (error) {
|
|
1284
|
+
throw toServerError(error, "写入文件失败");
|
|
1285
|
+
}
|
|
1286
|
+
});
|
|
1287
|
+
app.onRequest(methods.client.terminal.create, async (ctx) => {
|
|
1288
|
+
const workspaceRoot = deps.getWorkspaceRoot();
|
|
1289
|
+
const sessionId = ctx.params.sessionId;
|
|
1290
|
+
const command = ctx.params.command;
|
|
1291
|
+
if (!workspaceRoot || !sessionId || !command) {
|
|
1292
|
+
throw toInvalidParams("terminal/create 需要 sessionId、command 与已连接工作区");
|
|
1293
|
+
}
|
|
1294
|
+
try {
|
|
1295
|
+
return deps.terminals.create({
|
|
1296
|
+
sessionId,
|
|
1297
|
+
command,
|
|
1298
|
+
args: ctx.params.args ?? undefined,
|
|
1299
|
+
env: ctx.params.env ?? undefined,
|
|
1300
|
+
cwd: ctx.params.cwd ?? undefined,
|
|
1301
|
+
outputByteLimit: ctx.params.outputByteLimit ?? undefined,
|
|
1302
|
+
workspaceRoot
|
|
1303
|
+
});
|
|
1304
|
+
} catch (error) {
|
|
1305
|
+
throw toServerError(error, "创建终端失败");
|
|
1306
|
+
}
|
|
1307
|
+
});
|
|
1308
|
+
app.onRequest(methods.client.terminal.output, async (ctx) => {
|
|
1309
|
+
const terminalId = ctx.params.terminalId;
|
|
1310
|
+
if (!terminalId) {
|
|
1311
|
+
throw toInvalidParams("terminal/output 需要 terminalId");
|
|
1312
|
+
}
|
|
1313
|
+
try {
|
|
1314
|
+
return deps.terminals.getOutput(terminalId);
|
|
1315
|
+
} catch (error) {
|
|
1316
|
+
throw toServerError(error, "读取终端输出失败");
|
|
1317
|
+
}
|
|
1318
|
+
});
|
|
1319
|
+
app.onRequest(methods.client.terminal.waitForExit, async (ctx) => {
|
|
1320
|
+
const terminalId = ctx.params.terminalId;
|
|
1321
|
+
if (!terminalId) {
|
|
1322
|
+
throw toInvalidParams("terminal/wait_for_exit 需要 terminalId");
|
|
1323
|
+
}
|
|
1324
|
+
try {
|
|
1325
|
+
return await deps.terminals.waitForExit(terminalId);
|
|
1326
|
+
} catch (error) {
|
|
1327
|
+
throw toServerError(error, "等待终端退出失败");
|
|
1328
|
+
}
|
|
1329
|
+
});
|
|
1330
|
+
app.onRequest(methods.client.terminal.kill, async (ctx) => {
|
|
1331
|
+
const terminalId = ctx.params.terminalId;
|
|
1332
|
+
if (!terminalId) {
|
|
1333
|
+
throw toInvalidParams("terminal/kill 需要 terminalId");
|
|
1334
|
+
}
|
|
1335
|
+
try {
|
|
1336
|
+
return deps.terminals.kill(terminalId);
|
|
1337
|
+
} catch (error) {
|
|
1338
|
+
throw toServerError(error, "终止终端失败");
|
|
1339
|
+
}
|
|
1340
|
+
});
|
|
1341
|
+
app.onRequest(methods.client.terminal.release, async (ctx) => {
|
|
1342
|
+
const terminalId = ctx.params.terminalId;
|
|
1343
|
+
if (!terminalId) {
|
|
1344
|
+
throw toInvalidParams("terminal/release 需要 terminalId");
|
|
1345
|
+
}
|
|
1346
|
+
try {
|
|
1347
|
+
return deps.terminals.release(terminalId);
|
|
1348
|
+
} catch (error) {
|
|
1349
|
+
throw toServerError(error, "释放终端失败");
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
app.onNotification(methods.client.session.update, async (ctx) => {
|
|
1353
|
+
deps.onSessionUpdate({
|
|
1354
|
+
sessionId: ctx.params.sessionId,
|
|
1355
|
+
update: ctx.params.update
|
|
1356
|
+
});
|
|
1357
|
+
});
|
|
1358
|
+
}
|
|
1359
|
+
function permissionOptionId(option) {
|
|
1360
|
+
if (typeof option.optionId === "string")
|
|
1361
|
+
return option.optionId;
|
|
1362
|
+
if (typeof option.id === "string")
|
|
1363
|
+
return option.id;
|
|
1364
|
+
return null;
|
|
1365
|
+
}
|
|
1366
|
+
function pickAllowOptionId(params) {
|
|
1367
|
+
const options = params.options;
|
|
1368
|
+
if (!Array.isArray(options))
|
|
1369
|
+
return null;
|
|
1370
|
+
for (const item of options) {
|
|
1371
|
+
if (!item || typeof item !== "object")
|
|
1372
|
+
continue;
|
|
1373
|
+
const option = item;
|
|
1374
|
+
const id = permissionOptionId(option);
|
|
1375
|
+
const kind = typeof option.kind === "string" ? option.kind : "";
|
|
1376
|
+
if (id && (kind.includes("allow") || kind === "allow_once" || kind === "allow_always")) {
|
|
1377
|
+
return id;
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
for (const item of options) {
|
|
1381
|
+
if (!item || typeof item !== "object")
|
|
1382
|
+
continue;
|
|
1383
|
+
const id = permissionOptionId(item);
|
|
1384
|
+
if (id)
|
|
1385
|
+
return id;
|
|
1386
|
+
}
|
|
1387
|
+
return null;
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
// src/client/session-open.ts
|
|
1391
|
+
import { RequestError as RequestError2 } from "@agentclientprotocol/sdk";
|
|
1392
|
+
|
|
1393
|
+
// src/session/config-options.ts
|
|
1394
|
+
function coerceOptionValue(raw) {
|
|
1395
|
+
if (typeof raw === "string")
|
|
1396
|
+
return raw || null;
|
|
1397
|
+
if (typeof raw === "number" && Number.isFinite(raw))
|
|
1398
|
+
return String(raw);
|
|
1399
|
+
if (typeof raw === "boolean")
|
|
1400
|
+
return String(raw);
|
|
1401
|
+
return null;
|
|
1402
|
+
}
|
|
1403
|
+
function coerceCurrentValue(raw) {
|
|
1404
|
+
if (typeof raw === "string")
|
|
1405
|
+
return raw;
|
|
1406
|
+
if (typeof raw === "boolean")
|
|
1407
|
+
return raw;
|
|
1408
|
+
if (typeof raw === "number" && Number.isFinite(raw))
|
|
1409
|
+
return String(raw);
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
function parseAcpConfigOptions(raw) {
|
|
1413
|
+
if (!Array.isArray(raw))
|
|
1414
|
+
return [];
|
|
1415
|
+
const options = [];
|
|
1416
|
+
for (const item of raw) {
|
|
1417
|
+
if (!item || typeof item !== "object")
|
|
1418
|
+
continue;
|
|
1419
|
+
const row = item;
|
|
1420
|
+
const configId = typeof row.configId === "string" ? row.configId : typeof row.id === "string" ? row.id : null;
|
|
1421
|
+
if (!configId)
|
|
1422
|
+
continue;
|
|
1423
|
+
const name = typeof row.name === "string" ? row.name : configId;
|
|
1424
|
+
const type = typeof row.type === "string" ? row.type : "select";
|
|
1425
|
+
const values = [];
|
|
1426
|
+
if (Array.isArray(row.options)) {
|
|
1427
|
+
for (const opt of row.options) {
|
|
1428
|
+
if (!opt || typeof opt !== "object")
|
|
1429
|
+
continue;
|
|
1430
|
+
const o = opt;
|
|
1431
|
+
const value = coerceOptionValue(o.value) ?? coerceOptionValue(o.id);
|
|
1432
|
+
if (!value)
|
|
1433
|
+
continue;
|
|
1434
|
+
values.push({
|
|
1435
|
+
value,
|
|
1436
|
+
name: typeof o.name === "string" ? o.name : String(value),
|
|
1437
|
+
description: typeof o.description === "string" ? o.description : undefined
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
options.push({
|
|
1442
|
+
configId,
|
|
1443
|
+
name,
|
|
1444
|
+
description: typeof row.description === "string" ? row.description : undefined,
|
|
1445
|
+
category: typeof row.category === "string" ? row.category : undefined,
|
|
1446
|
+
type,
|
|
1447
|
+
currentValue: coerceCurrentValue(row.currentValue),
|
|
1448
|
+
options: values.length > 0 ? values : undefined
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
return options;
|
|
1452
|
+
}
|
|
1453
|
+
function findModelConfigOption(options) {
|
|
1454
|
+
return options.find((o) => o.category === "model") ?? options.find((o) => o.configId === "model" || o.configId.includes("model"));
|
|
1455
|
+
}
|
|
1456
|
+
function coerceTopLevelModelEntry(raw) {
|
|
1457
|
+
if (typeof raw === "string") {
|
|
1458
|
+
const trimmed = raw.trim();
|
|
1459
|
+
if (!trimmed)
|
|
1460
|
+
return null;
|
|
1461
|
+
return { value: trimmed, name: trimmed };
|
|
1462
|
+
}
|
|
1463
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
1464
|
+
return null;
|
|
1465
|
+
const row = raw;
|
|
1466
|
+
const valueRaw = row.value ?? row.id;
|
|
1467
|
+
const value = coerceOptionValue(valueRaw);
|
|
1468
|
+
if (!value)
|
|
1469
|
+
return null;
|
|
1470
|
+
const name = typeof row.name === "string" && row.name.trim() ? row.name : value;
|
|
1471
|
+
return { value, name };
|
|
1472
|
+
}
|
|
1473
|
+
function coerceTopLevelModelList(raw) {
|
|
1474
|
+
if (!Array.isArray(raw))
|
|
1475
|
+
return [];
|
|
1476
|
+
const out = [];
|
|
1477
|
+
for (const item of raw) {
|
|
1478
|
+
const coerced = coerceTopLevelModelEntry(item);
|
|
1479
|
+
if (coerced)
|
|
1480
|
+
out.push(coerced);
|
|
1481
|
+
}
|
|
1482
|
+
return out;
|
|
1483
|
+
}
|
|
1484
|
+
function synthesizeModelOptionFromTopLevelModels(models, response) {
|
|
1485
|
+
let list = [];
|
|
1486
|
+
let currentValue;
|
|
1487
|
+
if (Array.isArray(models)) {
|
|
1488
|
+
list = coerceTopLevelModelList(models);
|
|
1489
|
+
} else if (models && typeof models === "object" && !Array.isArray(models)) {
|
|
1490
|
+
const row = models;
|
|
1491
|
+
list = coerceTopLevelModelList(row.availableModels);
|
|
1492
|
+
const currentRaw = row.currentModelId ?? response?.currentModelId;
|
|
1493
|
+
if (typeof currentRaw === "string" && currentRaw.trim())
|
|
1494
|
+
currentValue = currentRaw;
|
|
1495
|
+
} else {
|
|
1496
|
+
return null;
|
|
1497
|
+
}
|
|
1498
|
+
if (list.length === 0)
|
|
1499
|
+
return null;
|
|
1500
|
+
if (!currentValue && response && typeof response.currentModelId === "string") {
|
|
1501
|
+
const trimmed = response.currentModelId.trim();
|
|
1502
|
+
if (trimmed)
|
|
1503
|
+
currentValue = trimmed;
|
|
1504
|
+
}
|
|
1505
|
+
return {
|
|
1506
|
+
configId: "model",
|
|
1507
|
+
name: "Model",
|
|
1508
|
+
category: "model",
|
|
1509
|
+
type: "select",
|
|
1510
|
+
...currentValue ? { currentValue } : {},
|
|
1511
|
+
options: list.map((item) => ({ value: item.value, name: item.name }))
|
|
1512
|
+
};
|
|
1513
|
+
}
|
|
1514
|
+
function mergeTopLevelModelsIntoConfigOptions(configOptionsRaw, response) {
|
|
1515
|
+
const parsed = parseAcpConfigOptions(configOptionsRaw);
|
|
1516
|
+
if (findModelConfigOption(parsed))
|
|
1517
|
+
return configOptionsRaw;
|
|
1518
|
+
const models = response?.models;
|
|
1519
|
+
if (models === undefined)
|
|
1520
|
+
return configOptionsRaw;
|
|
1521
|
+
const synthesized = synthesizeModelOptionFromTopLevelModels(models, response ?? undefined);
|
|
1522
|
+
if (!synthesized)
|
|
1523
|
+
return configOptionsRaw;
|
|
1524
|
+
const base = Array.isArray(configOptionsRaw) ? [...configOptionsRaw] : [];
|
|
1525
|
+
base.push({
|
|
1526
|
+
configId: synthesized.configId,
|
|
1527
|
+
name: synthesized.name,
|
|
1528
|
+
category: synthesized.category,
|
|
1529
|
+
type: synthesized.type,
|
|
1530
|
+
...synthesized.currentValue !== undefined ? { currentValue: synthesized.currentValue } : {},
|
|
1531
|
+
options: synthesized.options?.map((o) => ({ value: o.value, name: o.name }))
|
|
1532
|
+
});
|
|
1533
|
+
return base;
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
// src/client/session-open.ts
|
|
1537
|
+
function errorMessage(error) {
|
|
1538
|
+
return error instanceof Error ? error.message : String(error);
|
|
1539
|
+
}
|
|
1540
|
+
function isTransientAcpTransportError(error) {
|
|
1541
|
+
if (error instanceof RequestError2) {
|
|
1542
|
+
if (error.code === -32800 || error.code === -32601 || error.code === -32602)
|
|
1543
|
+
return false;
|
|
1544
|
+
let detail = "";
|
|
1545
|
+
try {
|
|
1546
|
+
detail = error.data === undefined ? "" : JSON.stringify(error.data);
|
|
1547
|
+
} catch {
|
|
1548
|
+
detail = String(error.data);
|
|
1549
|
+
}
|
|
1550
|
+
return /超时|timeout|timed out|temporar|busy|unavailable|closed|abort|econnreset|epipe/i.test(`${error.message} ${detail}`);
|
|
1551
|
+
}
|
|
1552
|
+
const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
1553
|
+
return /ACP connection closed|connection closed|closed|abort|超时|timeout|timed out|econnreset|epipe|stdio|stream/i.test(message);
|
|
1554
|
+
}
|
|
1555
|
+
async function restoreOrCreateAcpSession(input) {
|
|
1556
|
+
const resumeId = input.resumeSessionId?.trim() || null;
|
|
1557
|
+
const restoreAttempts = [];
|
|
1558
|
+
const delayMs = input.retryDelayMs ?? 250;
|
|
1559
|
+
const log = input.log ?? ((level, message, data) => {
|
|
1560
|
+
if (level === "info" && false)
|
|
1561
|
+
;
|
|
1562
|
+
const line = `[acp] ${message}`;
|
|
1563
|
+
if (level === "warn")
|
|
1564
|
+
console.warn(line, data ?? "");
|
|
1565
|
+
else
|
|
1566
|
+
console.info(line, data ?? "");
|
|
1567
|
+
});
|
|
1568
|
+
const tryRestoreMethod = async (method, rpcMethod) => {
|
|
1569
|
+
const maxTries = 2;
|
|
1570
|
+
let lastError = "";
|
|
1571
|
+
for (let tryIndex = 1;tryIndex <= maxTries; tryIndex++) {
|
|
1572
|
+
log("info", "session restore attempt", {
|
|
1573
|
+
method: rpcMethod,
|
|
1574
|
+
sessionId: resumeId,
|
|
1575
|
+
try: tryIndex,
|
|
1576
|
+
maxTries
|
|
1577
|
+
});
|
|
1578
|
+
try {
|
|
1579
|
+
const result = await input.request(rpcMethod, {
|
|
1580
|
+
sessionId: resumeId,
|
|
1581
|
+
cwd: input.cwd,
|
|
1582
|
+
mcpServers: input.mcpServers ?? []
|
|
1583
|
+
});
|
|
1584
|
+
restoreAttempts.push({ method, ok: true, tries: tryIndex });
|
|
1585
|
+
log("info", "session restore ok", { method: rpcMethod, sessionId: resumeId });
|
|
1586
|
+
return result;
|
|
1587
|
+
} catch (error) {
|
|
1588
|
+
lastError = errorMessage(error);
|
|
1589
|
+
log("warn", "session restore failed", {
|
|
1590
|
+
method: rpcMethod,
|
|
1591
|
+
sessionId: resumeId,
|
|
1592
|
+
try: tryIndex,
|
|
1593
|
+
error: lastError
|
|
1594
|
+
});
|
|
1595
|
+
const canRetry = tryIndex < maxTries && isTransientAcpTransportError(error);
|
|
1596
|
+
if (!canRetry) {
|
|
1597
|
+
restoreAttempts.push({ method, ok: false, tries: tryIndex, error: lastError });
|
|
1598
|
+
return null;
|
|
1599
|
+
}
|
|
1600
|
+
if (delayMs > 0)
|
|
1601
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
restoreAttempts.push({ method, ok: false, tries: maxTries, error: lastError });
|
|
1605
|
+
return null;
|
|
1606
|
+
};
|
|
1607
|
+
log("info", "openSession", {
|
|
1608
|
+
resumeId,
|
|
1609
|
+
resumeSupported: input.resumeSupported,
|
|
1610
|
+
loadSupported: input.loadSupported
|
|
1611
|
+
});
|
|
1612
|
+
const requestSessionNew = async () => {
|
|
1613
|
+
const baseParams = {
|
|
1614
|
+
cwd: input.cwd,
|
|
1615
|
+
mcpServers: input.mcpServers ?? []
|
|
1616
|
+
};
|
|
1617
|
+
try {
|
|
1618
|
+
return await input.request("session/new", baseParams);
|
|
1619
|
+
} catch (firstError) {
|
|
1620
|
+
if ((input.mcpServers ?? []).length === 0)
|
|
1621
|
+
throw firstError;
|
|
1622
|
+
log("warn", "session/new failed, retry without mcpServers", {
|
|
1623
|
+
error: errorMessage(firstError)
|
|
1624
|
+
});
|
|
1625
|
+
try {
|
|
1626
|
+
return await input.request("session/new", {
|
|
1627
|
+
cwd: input.cwd,
|
|
1628
|
+
mcpServers: []
|
|
1629
|
+
});
|
|
1630
|
+
} catch {
|
|
1631
|
+
throw firstError;
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
};
|
|
1635
|
+
const withModelsFallback = (result) => mergeTopLevelModelsIntoConfigOptions(result.configOptions, result);
|
|
1636
|
+
if (resumeId && input.resumeSupported) {
|
|
1637
|
+
const resumed = await tryRestoreMethod("resume", "session/resume");
|
|
1638
|
+
if (resumed) {
|
|
1639
|
+
const id = typeof resumed.sessionId === "string" ? resumed.sessionId : resumeId;
|
|
1640
|
+
return {
|
|
1641
|
+
sessionId: id,
|
|
1642
|
+
configOptions: withModelsFallback(resumed),
|
|
1643
|
+
restoreMethod: "resume",
|
|
1644
|
+
sessionRestored: true,
|
|
1645
|
+
requestedSessionId: resumeId,
|
|
1646
|
+
restoreAttempts
|
|
1647
|
+
};
|
|
1648
|
+
}
|
|
1649
|
+
} else if (resumeId && !input.resumeSupported) {
|
|
1650
|
+
log("info", "skip session/resume:Agent 未声明 resume 能力");
|
|
1651
|
+
}
|
|
1652
|
+
if (resumeId && input.loadSupported) {
|
|
1653
|
+
input.onSuppressUpdates?.(true);
|
|
1654
|
+
try {
|
|
1655
|
+
const loaded = await tryRestoreMethod("load", "session/load");
|
|
1656
|
+
if (loaded) {
|
|
1657
|
+
const id = typeof loaded.sessionId === "string" ? loaded.sessionId : resumeId;
|
|
1658
|
+
return {
|
|
1659
|
+
sessionId: id,
|
|
1660
|
+
configOptions: withModelsFallback(loaded),
|
|
1661
|
+
restoreMethod: "load",
|
|
1662
|
+
sessionRestored: true,
|
|
1663
|
+
requestedSessionId: resumeId,
|
|
1664
|
+
restoreAttempts
|
|
1665
|
+
};
|
|
1666
|
+
}
|
|
1667
|
+
} finally {
|
|
1668
|
+
input.onSuppressUpdates?.(false);
|
|
1669
|
+
}
|
|
1670
|
+
} else if (resumeId && !input.loadSupported) {
|
|
1671
|
+
log("info", "skip session/load:Agent 未声明 loadSession 能力");
|
|
1672
|
+
}
|
|
1673
|
+
log("info", "falling back to session/new", { resumeId, restoreAttempts });
|
|
1674
|
+
const sessionResult = await requestSessionNew();
|
|
1675
|
+
const newSessionId = typeof sessionResult.sessionId === "string" ? sessionResult.sessionId : null;
|
|
1676
|
+
if (!newSessionId) {
|
|
1677
|
+
throw new Error("session/new 未返回 sessionId");
|
|
1678
|
+
}
|
|
1679
|
+
return {
|
|
1680
|
+
sessionId: newSessionId,
|
|
1681
|
+
configOptions: withModelsFallback(sessionResult),
|
|
1682
|
+
restoreMethod: "new",
|
|
1683
|
+
sessionRestored: false,
|
|
1684
|
+
requestedSessionId: resumeId ?? undefined,
|
|
1685
|
+
restoreAttempts
|
|
1686
|
+
};
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
// src/client/acp-terminal.ts
|
|
1690
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1691
|
+
import { randomUUID } from "node:crypto";
|
|
1692
|
+
|
|
1693
|
+
// src/transport/terminal-output-buffer.ts
|
|
1694
|
+
function truncateOutputFromStart(text, byteLimit) {
|
|
1695
|
+
if (byteLimit <= 0)
|
|
1696
|
+
return { text: "", truncated: text.length > 0 };
|
|
1697
|
+
if (Buffer.byteLength(text, "utf8") <= byteLimit) {
|
|
1698
|
+
return { text, truncated: false };
|
|
1699
|
+
}
|
|
1700
|
+
let lo = 0;
|
|
1701
|
+
let hi = text.length;
|
|
1702
|
+
while (lo < hi) {
|
|
1703
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
1704
|
+
if (Buffer.byteLength(text.slice(mid), "utf8") <= byteLimit)
|
|
1705
|
+
hi = mid;
|
|
1706
|
+
else
|
|
1707
|
+
lo = mid + 1;
|
|
1708
|
+
}
|
|
1709
|
+
return { text: text.slice(lo), truncated: true };
|
|
1710
|
+
}
|
|
1711
|
+
function appendTerminalOutput(current, chunk, byteLimit) {
|
|
1712
|
+
const { text, truncated } = truncateOutputFromStart(current + chunk, byteLimit);
|
|
1713
|
+
return { output: text, truncated };
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
// src/client/acp-terminal.ts
|
|
1717
|
+
var DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
|
|
1718
|
+
function resolveCwd(cwd, workspaceRoot) {
|
|
1719
|
+
if (!cwd?.trim())
|
|
1720
|
+
return assertPathInsideWorkspace(workspaceRoot, workspaceRoot);
|
|
1721
|
+
return assertPathInsideWorkspace(cwd, workspaceRoot);
|
|
1722
|
+
}
|
|
1723
|
+
function buildEnv(extra) {
|
|
1724
|
+
const env = { ...process.env };
|
|
1725
|
+
if (!extra)
|
|
1726
|
+
return env;
|
|
1727
|
+
for (const row of extra) {
|
|
1728
|
+
if (!row.name)
|
|
1729
|
+
continue;
|
|
1730
|
+
env[row.name] = row.value;
|
|
1731
|
+
}
|
|
1732
|
+
return env;
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
class AcpTerminalManager {
|
|
1736
|
+
terminals = new Map;
|
|
1737
|
+
create(params) {
|
|
1738
|
+
const command = params.command?.trim();
|
|
1739
|
+
if (!command)
|
|
1740
|
+
throw new Error("terminal/create 需要 command");
|
|
1741
|
+
const cwd = resolveCwd(params.cwd, params.workspaceRoot);
|
|
1742
|
+
const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : DEFAULT_OUTPUT_BYTE_LIMIT;
|
|
1743
|
+
const child = spawn2(command, params.args ?? [], {
|
|
1744
|
+
cwd,
|
|
1745
|
+
env: buildEnv(params.env),
|
|
1746
|
+
windowsHide: true,
|
|
1747
|
+
shell: false,
|
|
1748
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1749
|
+
});
|
|
1750
|
+
const id = `term_${randomUUID().replace(/-/g, "").slice(0, 12)}`;
|
|
1751
|
+
const record = {
|
|
1752
|
+
id,
|
|
1753
|
+
sessionId: params.sessionId,
|
|
1754
|
+
child,
|
|
1755
|
+
output: "",
|
|
1756
|
+
truncated: false,
|
|
1757
|
+
outputByteLimit,
|
|
1758
|
+
exitCode: null,
|
|
1759
|
+
signal: null,
|
|
1760
|
+
exited: false,
|
|
1761
|
+
waiters: []
|
|
1762
|
+
};
|
|
1763
|
+
const onChunk = (buf) => {
|
|
1764
|
+
const chunk = buf.toString("utf8");
|
|
1765
|
+
const next = appendTerminalOutput(record.output, chunk, record.outputByteLimit);
|
|
1766
|
+
record.output = next.output;
|
|
1767
|
+
if (next.truncated)
|
|
1768
|
+
record.truncated = true;
|
|
1769
|
+
};
|
|
1770
|
+
child.stdout?.on("data", onChunk);
|
|
1771
|
+
child.stderr?.on("data", onChunk);
|
|
1772
|
+
child.on("error", (error) => {
|
|
1773
|
+
const msg = `
|
|
1774
|
+
[spawn error] ${error.message}
|
|
1775
|
+
`;
|
|
1776
|
+
const next = appendTerminalOutput(record.output, msg, record.outputByteLimit);
|
|
1777
|
+
record.output = next.output;
|
|
1778
|
+
if (next.truncated)
|
|
1779
|
+
record.truncated = true;
|
|
1780
|
+
this.markExited(record, null, null);
|
|
1781
|
+
});
|
|
1782
|
+
child.on("close", (code, signal) => {
|
|
1783
|
+
this.markExited(record, code, signal);
|
|
1784
|
+
});
|
|
1785
|
+
this.terminals.set(id, record);
|
|
1786
|
+
return { terminalId: id };
|
|
1787
|
+
}
|
|
1788
|
+
getOutput(terminalId) {
|
|
1789
|
+
const record = this.require(terminalId);
|
|
1790
|
+
const snapshot = {
|
|
1791
|
+
output: record.output,
|
|
1792
|
+
truncated: record.truncated
|
|
1793
|
+
};
|
|
1794
|
+
if (record.exited) {
|
|
1795
|
+
snapshot.exitStatus = {
|
|
1796
|
+
exitCode: record.exitCode,
|
|
1797
|
+
signal: record.signal
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
return snapshot;
|
|
1801
|
+
}
|
|
1802
|
+
waitForExit(terminalId) {
|
|
1803
|
+
const record = this.require(terminalId);
|
|
1804
|
+
if (record.exited) {
|
|
1805
|
+
return Promise.resolve({ exitCode: record.exitCode, signal: record.signal });
|
|
1806
|
+
}
|
|
1807
|
+
return new Promise((resolve) => {
|
|
1808
|
+
record.waiters.push(resolve);
|
|
1809
|
+
});
|
|
1810
|
+
}
|
|
1811
|
+
kill(terminalId) {
|
|
1812
|
+
const record = this.require(terminalId);
|
|
1813
|
+
if (!record.exited) {
|
|
1814
|
+
this.forceKill(record.child);
|
|
1815
|
+
}
|
|
1816
|
+
return {};
|
|
1817
|
+
}
|
|
1818
|
+
release(terminalId) {
|
|
1819
|
+
const record = this.terminals.get(terminalId);
|
|
1820
|
+
if (!record)
|
|
1821
|
+
return {};
|
|
1822
|
+
if (!record.exited) {
|
|
1823
|
+
this.forceKill(record.child);
|
|
1824
|
+
}
|
|
1825
|
+
this.terminals.delete(terminalId);
|
|
1826
|
+
return {};
|
|
1827
|
+
}
|
|
1828
|
+
releaseAll() {
|
|
1829
|
+
for (const id of [...this.terminals.keys()]) {
|
|
1830
|
+
this.release(id);
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
forceKill(child) {
|
|
1834
|
+
const pid = child.pid;
|
|
1835
|
+
if (!pid)
|
|
1836
|
+
return;
|
|
1837
|
+
if (process.platform === "win32") {
|
|
1838
|
+
try {
|
|
1839
|
+
spawn2("taskkill", ["/pid", String(pid), "/T", "/F"], {
|
|
1840
|
+
windowsHide: true,
|
|
1841
|
+
stdio: "ignore"
|
|
1842
|
+
});
|
|
1843
|
+
} catch {
|
|
1844
|
+
try {
|
|
1845
|
+
child.kill();
|
|
1846
|
+
} catch {}
|
|
1847
|
+
}
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
try {
|
|
1851
|
+
child.kill("SIGKILL");
|
|
1852
|
+
} catch {}
|
|
1853
|
+
}
|
|
1854
|
+
require(terminalId) {
|
|
1855
|
+
const record = this.terminals.get(terminalId);
|
|
1856
|
+
if (!record)
|
|
1857
|
+
throw new Error(`未知 terminalId: ${terminalId}`);
|
|
1858
|
+
return record;
|
|
1859
|
+
}
|
|
1860
|
+
markExited(record, code, signal) {
|
|
1861
|
+
if (record.exited)
|
|
1862
|
+
return;
|
|
1863
|
+
record.exited = true;
|
|
1864
|
+
record.exitCode = code;
|
|
1865
|
+
record.signal = signal;
|
|
1866
|
+
const status = { exitCode: code, signal };
|
|
1867
|
+
for (const waiter of record.waiters)
|
|
1868
|
+
waiter(status);
|
|
1869
|
+
record.waiters = [];
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
// src/client/acp-proxy-service.ts
|
|
1874
|
+
import { mkdir as mkdir4, readFile as readFile3, writeFile as writeFile4 } from "node:fs/promises";
|
|
1875
|
+
import { existsSync as existsSync8 } from "node:fs";
|
|
1876
|
+
import { join as join10 } from "node:path";
|
|
1877
|
+
var DEFAULT_ACP_PROXY_SETTINGS = {
|
|
1878
|
+
enabled: false,
|
|
1879
|
+
host: "127.0.0.1",
|
|
1880
|
+
port: 7897
|
|
1881
|
+
};
|
|
1882
|
+
var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
|
|
1883
|
+
var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
|
|
1884
|
+
function proxyFilePath(dir) {
|
|
1885
|
+
return join10(dir, "agent", "proxy.json");
|
|
1886
|
+
}
|
|
1887
|
+
function validate2(settings) {
|
|
1888
|
+
if (!settings.host.trim())
|
|
1889
|
+
return "代理主机不能为空";
|
|
1890
|
+
if (!Number.isInteger(settings.port) || settings.port < 1 || settings.port > 65535) {
|
|
1891
|
+
return "代理端口必须是 1-65535 的整数";
|
|
1892
|
+
}
|
|
1893
|
+
return null;
|
|
1894
|
+
}
|
|
1895
|
+
async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
|
|
1896
|
+
const file = proxyFilePath(dir);
|
|
1897
|
+
if (!existsSync8(file))
|
|
1898
|
+
return { ...DEFAULT_ACP_PROXY_SETTINGS };
|
|
1899
|
+
try {
|
|
1900
|
+
const raw = JSON.parse(await readFile3(file, "utf8"));
|
|
1901
|
+
return {
|
|
1902
|
+
enabled: raw.enabled === true,
|
|
1903
|
+
host: typeof raw.host === "string" && raw.host.trim() ? raw.host : DEFAULT_ACP_PROXY_SETTINGS.host,
|
|
1904
|
+
port: typeof raw.port === "number" && Number.isInteger(raw.port) && raw.port >= 1 && raw.port <= 65535 ? raw.port : DEFAULT_ACP_PROXY_SETTINGS.port
|
|
1905
|
+
};
|
|
1906
|
+
} catch {
|
|
1907
|
+
return { ...DEFAULT_ACP_PROXY_SETTINGS };
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
|
|
1911
|
+
const invalid = validate2(payload);
|
|
1912
|
+
if (invalid)
|
|
1913
|
+
return err({ code: "INVALID_ARGUMENT", message: invalid });
|
|
1914
|
+
const stored = {
|
|
1915
|
+
enabled: payload.enabled === true,
|
|
1916
|
+
host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
|
|
1917
|
+
port: payload.port
|
|
1918
|
+
};
|
|
1919
|
+
await mkdir4(join10(dir, "agent"), { recursive: true });
|
|
1920
|
+
await writeFile4(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
|
|
1921
|
+
return ok(stored);
|
|
1922
|
+
}
|
|
1923
|
+
function buildAcpProxySpawnEnv(settings) {
|
|
1924
|
+
if (!settings.enabled) {
|
|
1925
|
+
return {
|
|
1926
|
+
env: {},
|
|
1927
|
+
envRemove: [...PROXY_ENV_KEYS, ...LOWERCASE_PROXY_ENV_KEYS]
|
|
1928
|
+
};
|
|
1929
|
+
}
|
|
1930
|
+
const url = `http://${settings.host.trim()}:${settings.port}`;
|
|
1931
|
+
return {
|
|
1932
|
+
env: {
|
|
1933
|
+
HTTP_PROXY: url,
|
|
1934
|
+
HTTPS_PROXY: url,
|
|
1935
|
+
ALL_PROXY: url,
|
|
1936
|
+
NO_PROXY: "localhost,127.0.0.1"
|
|
1937
|
+
},
|
|
1938
|
+
envRemove: [...LOWERCASE_PROXY_ENV_KEYS]
|
|
1939
|
+
};
|
|
1940
|
+
}
|
|
1941
|
+
|
|
1942
|
+
// src/session/session-capabilities.ts
|
|
1943
|
+
function parseLoadSessionSupported(caps) {
|
|
1944
|
+
return caps.loadSession === true;
|
|
1945
|
+
}
|
|
1946
|
+
function parseResumeSessionSupported(caps) {
|
|
1947
|
+
const sessionCaps = caps.sessionCapabilities && typeof caps.sessionCapabilities === "object" ? caps.sessionCapabilities : null;
|
|
1948
|
+
if (!sessionCaps)
|
|
1949
|
+
return false;
|
|
1950
|
+
const resume = sessionCaps.resume;
|
|
1951
|
+
if (resume === true)
|
|
1952
|
+
return true;
|
|
1953
|
+
if (resume && typeof resume === "object")
|
|
1954
|
+
return true;
|
|
1955
|
+
return false;
|
|
1956
|
+
}
|
|
1957
|
+
function parseMcpHttpSupported(caps) {
|
|
1958
|
+
const mcpCaps = caps.mcpCapabilities && typeof caps.mcpCapabilities === "object" ? caps.mcpCapabilities : null;
|
|
1959
|
+
return mcpCaps?.http === true;
|
|
1960
|
+
}
|
|
1961
|
+
function parsePromptCapabilities(caps) {
|
|
1962
|
+
const raw = caps.promptCapabilities && typeof caps.promptCapabilities === "object" ? caps.promptCapabilities : null;
|
|
1963
|
+
if (!raw)
|
|
1964
|
+
return {};
|
|
1965
|
+
return {
|
|
1966
|
+
image: raw.image === true,
|
|
1967
|
+
audio: raw.audio === true,
|
|
1968
|
+
embeddedContext: raw.embeddedContext === true
|
|
1969
|
+
};
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
// src/client/acp-client.ts
|
|
1973
|
+
class AcpSessionHandle {
|
|
1974
|
+
sessionId;
|
|
1975
|
+
client;
|
|
1976
|
+
restoreMethod;
|
|
1977
|
+
configOptions;
|
|
1978
|
+
constructor(sessionId, client, restoreMethod, configOptions) {
|
|
1979
|
+
this.sessionId = sessionId;
|
|
1980
|
+
this.client = client;
|
|
1981
|
+
this.restoreMethod = restoreMethod;
|
|
1982
|
+
this.configOptions = configOptions;
|
|
1983
|
+
}
|
|
1984
|
+
async prompt(promptText, options) {
|
|
1985
|
+
return this.client.promptSession(this.sessionId, promptText, options);
|
|
1986
|
+
}
|
|
1987
|
+
async setConfigOption(configId, value) {
|
|
1988
|
+
return this.client.setSessionConfigOption(this.sessionId, configId, value);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1992
|
+
class AcpClient {
|
|
1993
|
+
status = "disconnected";
|
|
1994
|
+
runtimeInfo;
|
|
1995
|
+
adapter;
|
|
1996
|
+
workspaceRoot;
|
|
1997
|
+
clientInfo;
|
|
1998
|
+
dataDir;
|
|
1999
|
+
callbacks;
|
|
2000
|
+
terminals = new AcpTerminalManager;
|
|
2001
|
+
processHandle = null;
|
|
2002
|
+
sdkApp = null;
|
|
2003
|
+
sdkConnection = null;
|
|
2004
|
+
streamHandle = null;
|
|
2005
|
+
initResponse = null;
|
|
2006
|
+
constructor(options) {
|
|
2007
|
+
this.workspaceRoot = options.workspaceRoot;
|
|
2008
|
+
this.clientInfo = {
|
|
2009
|
+
name: options.clientInfo?.name ?? "inkdown",
|
|
2010
|
+
version: options.clientInfo?.version ?? "0.1.0"
|
|
2011
|
+
};
|
|
2012
|
+
this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
|
|
2013
|
+
this.callbacks = options.callbacks ?? {};
|
|
2014
|
+
const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
|
|
2015
|
+
this.adapter = getAcpRuntimeAdapter(runtimeId);
|
|
2016
|
+
if (typeof options.runtime === "object" && options.runtime !== null) {
|
|
2017
|
+
this.runtimeInfo = options.runtime;
|
|
2018
|
+
} else {
|
|
2019
|
+
const found = findBuiltinAcpRuntime(runtimeId);
|
|
2020
|
+
if (!found) {
|
|
2021
|
+
throw new Error(`未知或未注册的 ACP 运行时模板: ${runtimeId}`);
|
|
2022
|
+
}
|
|
2023
|
+
this.runtimeInfo = found;
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
get currentStatus() {
|
|
2027
|
+
return this.status;
|
|
2028
|
+
}
|
|
2029
|
+
get isConnected() {
|
|
2030
|
+
return this.status === "connected" && Boolean(this.sdkConnection?.agent);
|
|
2031
|
+
}
|
|
2032
|
+
get agent() {
|
|
2033
|
+
return this.sdkConnection?.agent ?? null;
|
|
2034
|
+
}
|
|
2035
|
+
async connect() {
|
|
2036
|
+
try {
|
|
2037
|
+
this.setStatus("connecting");
|
|
2038
|
+
const blocker = this.adapter.resolveSpawnBlocker?.();
|
|
2039
|
+
if (blocker) {
|
|
2040
|
+
this.setStatus("error", blocker);
|
|
2041
|
+
return err({ code: "ACP_SPAWN_ERROR", message: blocker });
|
|
2042
|
+
}
|
|
2043
|
+
let effectiveRuntime = { ...this.runtimeInfo };
|
|
2044
|
+
if (this.adapter.resolveSpawnCommand) {
|
|
2045
|
+
const resolved = this.adapter.resolveSpawnCommand();
|
|
2046
|
+
if (!resolved) {
|
|
2047
|
+
const message = `运行时 CLI 未安装: ${this.runtimeInfo.id}`;
|
|
2048
|
+
this.setStatus("error", message);
|
|
2049
|
+
return err({ code: "ACP_SPAWN_ERROR", message });
|
|
2050
|
+
}
|
|
2051
|
+
effectiveRuntime.command = resolved.command;
|
|
2052
|
+
effectiveRuntime.args = resolved.args;
|
|
2053
|
+
}
|
|
2054
|
+
const storedProxy = await readAcpProxySettings(this.dataDir);
|
|
2055
|
+
const proxyEnv = buildAcpProxySpawnEnv(storedProxy);
|
|
2056
|
+
const spawnEnv = this.adapter.getSpawnEnv?.(storedProxy) ?? proxyEnv;
|
|
2057
|
+
await this.adapter.beforeSpawn?.();
|
|
2058
|
+
const processHandle = spawnAcpProcess({
|
|
2059
|
+
runtime: effectiveRuntime,
|
|
2060
|
+
cwd: this.workspaceRoot,
|
|
2061
|
+
env: spawnEnv.env,
|
|
2062
|
+
envRemove: spawnEnv.envRemove,
|
|
2063
|
+
onStderrLine: (line) => {
|
|
2064
|
+
this.callbacks.onStderrLine?.(line);
|
|
2065
|
+
},
|
|
2066
|
+
onExit: (code, signal) => {
|
|
2067
|
+
this.callbacks.onLog?.("warn", `Agent 进程已退出 (code: ${code}, signal: ${signal})`);
|
|
2068
|
+
if (this.status === "connected" || this.status === "connecting") {
|
|
2069
|
+
this.disconnect("Agent 进程异常终止");
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
});
|
|
2073
|
+
this.processHandle = processHandle;
|
|
2074
|
+
const handlerDeps = {
|
|
2075
|
+
getWorkspaceRoot: () => this.workspaceRoot,
|
|
2076
|
+
terminals: this.terminals,
|
|
2077
|
+
readSnapshot: async (resource) => {
|
|
2078
|
+
if (!this.callbacks.readSnapshot) {
|
|
2079
|
+
throw new Error(`当前宿主未实现 readSnapshot 回调: ${resource}`);
|
|
2080
|
+
}
|
|
2081
|
+
return this.callbacks.readSnapshot(resource);
|
|
2082
|
+
},
|
|
2083
|
+
onPermission: async (payload) => {
|
|
2084
|
+
if (this.callbacks.onPermissionRequest) {
|
|
2085
|
+
return this.callbacks.onPermissionRequest({
|
|
2086
|
+
sessionId: payload.sessionId,
|
|
2087
|
+
toolCall: payload.params?.toolCall,
|
|
2088
|
+
params: payload.params
|
|
2089
|
+
});
|
|
2090
|
+
}
|
|
2091
|
+
return { outcome: "cancelled" };
|
|
2092
|
+
},
|
|
2093
|
+
onSessionUpdate: (params) => {
|
|
2094
|
+
this.callbacks.onSessionUpdate?.(params);
|
|
2095
|
+
}
|
|
2096
|
+
};
|
|
2097
|
+
const { app, connection, streamHandle } = connectSdkClient(processHandle.child, (clientApp) => {
|
|
2098
|
+
registerAcpClientHandlers(clientApp, handlerDeps);
|
|
2099
|
+
}, this.runtimeInfo.id);
|
|
2100
|
+
this.sdkApp = app;
|
|
2101
|
+
this.sdkConnection = connection;
|
|
2102
|
+
this.streamHandle = streamHandle;
|
|
2103
|
+
const initResp = await sdkRequest(connection.agent, methods2.agent.initialize, {
|
|
2104
|
+
protocolVersion: 1,
|
|
2105
|
+
clientInfo: this.clientInfo,
|
|
2106
|
+
clientCapabilities: {
|
|
2107
|
+
fs: { readTextFile: true, writeTextFile: true },
|
|
2108
|
+
terminal: true,
|
|
2109
|
+
session: {
|
|
2110
|
+
configOptions: { boolean: {} }
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
});
|
|
2114
|
+
this.initResponse = initResp;
|
|
2115
|
+
this.setStatus("connected");
|
|
2116
|
+
return ok({ status: "connected", init: initResp });
|
|
2117
|
+
} catch (e) {
|
|
2118
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
2119
|
+
this.setStatus("error", message);
|
|
2120
|
+
await this.disconnect(message);
|
|
2121
|
+
return err({ code: "ACP_PROTOCOL_ERROR", message });
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
async createSession(options) {
|
|
2125
|
+
if (!this.sdkConnection?.agent) {
|
|
2126
|
+
return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
|
|
2127
|
+
}
|
|
2128
|
+
const agent = this.sdkConnection.agent;
|
|
2129
|
+
const init = this.initResponse;
|
|
2130
|
+
const resumeSupported = Boolean(init && parseResumeSessionSupported(init.agentCapabilities));
|
|
2131
|
+
const loadSupported = Boolean(init && parseLoadSessionSupported(init.agentCapabilities));
|
|
2132
|
+
try {
|
|
2133
|
+
const openResult = await restoreOrCreateAcpSession({
|
|
2134
|
+
request: async (method, params) => {
|
|
2135
|
+
return sdkRequest(agent, method, params);
|
|
2136
|
+
},
|
|
2137
|
+
cwd: this.workspaceRoot,
|
|
2138
|
+
resumeSessionId: options?.resumeSessionId ?? null,
|
|
2139
|
+
resumeSupported,
|
|
2140
|
+
loadSupported,
|
|
2141
|
+
mcpServers: options?.mcpServers ?? [],
|
|
2142
|
+
log: (level, msg, meta) => {
|
|
2143
|
+
this.callbacks.onLog?.(level, msg, meta);
|
|
2144
|
+
}
|
|
2145
|
+
});
|
|
2146
|
+
const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions);
|
|
2147
|
+
return ok(handle);
|
|
2148
|
+
} catch (e) {
|
|
2149
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
2150
|
+
return err({ code: "ACP_PROTOCOL_ERROR", message });
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
async promptSession(sessionId, promptText, options) {
|
|
2154
|
+
if (!this.sdkConnection?.agent) {
|
|
2155
|
+
return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
|
|
2156
|
+
}
|
|
2157
|
+
try {
|
|
2158
|
+
const response = await sdkRequest(this.sdkConnection.agent, methods2.agent.session.prompt, {
|
|
2159
|
+
sessionId,
|
|
2160
|
+
prompt: [{ type: "text", text: promptText }]
|
|
2161
|
+
}, options?.timeoutMs);
|
|
2162
|
+
return ok(response);
|
|
2163
|
+
} catch (e) {
|
|
2164
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
2165
|
+
return err({ code: "ACP_PROTOCOL_ERROR", message });
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
async setSessionConfigOption(sessionId, configId, value) {
|
|
2169
|
+
if (!this.sdkConnection?.agent) {
|
|
2170
|
+
return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
|
|
2171
|
+
}
|
|
2172
|
+
try {
|
|
2173
|
+
const response = await sdkRequest(this.sdkConnection.agent, methods2.agent.session.setConfigOption, {
|
|
2174
|
+
sessionId,
|
|
2175
|
+
configId,
|
|
2176
|
+
value
|
|
2177
|
+
});
|
|
2178
|
+
return ok(response);
|
|
2179
|
+
} catch (e) {
|
|
2180
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
2181
|
+
return err({ code: "ACP_PROTOCOL_ERROR", message });
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
async disconnect(reason) {
|
|
2185
|
+
this.setStatus("disconnected", reason);
|
|
2186
|
+
try {
|
|
2187
|
+
this.streamHandle?.dispose();
|
|
2188
|
+
this.sdkConnection?.close();
|
|
2189
|
+
} catch {} finally {
|
|
2190
|
+
this.sdkConnection = null;
|
|
2191
|
+
this.streamHandle = null;
|
|
2192
|
+
this.sdkApp = null;
|
|
2193
|
+
this.initResponse = null;
|
|
2194
|
+
}
|
|
2195
|
+
if (this.processHandle && isSpawnedAcpProcessAlive(this.processHandle)) {
|
|
2196
|
+
try {
|
|
2197
|
+
this.processHandle.kill();
|
|
2198
|
+
} catch {}
|
|
2199
|
+
this.processHandle = null;
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
setStatus(status, detail) {
|
|
2203
|
+
this.status = status;
|
|
2204
|
+
this.callbacks.onStatusChange?.(status, detail);
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
// src/auth/auth-method-order.ts
|
|
2208
|
+
function methodKey(method) {
|
|
2209
|
+
return `${method.id} ${method.type ?? ""} ${method.name ?? ""}`.toLowerCase();
|
|
2210
|
+
}
|
|
2211
|
+
function isChatGptMethod(method) {
|
|
2212
|
+
return /chatgpt|openai|google|oauth|subscription|login/.test(methodKey(method));
|
|
2213
|
+
}
|
|
2214
|
+
function isApiKeyMethod(method) {
|
|
2215
|
+
return /api[_-]?key|token|env/.test(methodKey(method));
|
|
2216
|
+
}
|
|
2217
|
+
function orderSilentAuthMethodIds(methods, preflight) {
|
|
2218
|
+
if (methods.length === 0)
|
|
2219
|
+
return [];
|
|
2220
|
+
const score = (method) => {
|
|
2221
|
+
const id = method.id.toLowerCase();
|
|
2222
|
+
if (id === "oauth-personal")
|
|
2223
|
+
return 0;
|
|
2224
|
+
if (id === "oauth-business")
|
|
2225
|
+
return 2;
|
|
2226
|
+
if (id === "gemini-api-key")
|
|
2227
|
+
return preflight.hasApiKeyEnv ? 1 : 4;
|
|
2228
|
+
const chatgpt = isChatGptMethod(method);
|
|
2229
|
+
const apiKey = isApiKeyMethod(method);
|
|
2230
|
+
if (preflight.hasAuthFile && chatgpt)
|
|
2231
|
+
return 0;
|
|
2232
|
+
if (preflight.hasApiKeyEnv && apiKey)
|
|
2233
|
+
return 1;
|
|
2234
|
+
if (preflight.hasAuthFile && apiKey)
|
|
2235
|
+
return 8;
|
|
2236
|
+
if (preflight.hasApiKeyEnv && chatgpt)
|
|
2237
|
+
return 8;
|
|
2238
|
+
if (chatgpt)
|
|
2239
|
+
return 3;
|
|
2240
|
+
if (apiKey)
|
|
2241
|
+
return 4;
|
|
2242
|
+
return 5;
|
|
2243
|
+
};
|
|
2244
|
+
return [...methods].sort((a, b) => score(a) - score(b) || a.id.localeCompare(b.id)).map((m) => m.id);
|
|
2245
|
+
}
|
|
2246
|
+
function shouldPromptAuthWizard(methods, preflight) {
|
|
2247
|
+
return methods.length > 0 && !preflight.looksLoggedIn;
|
|
2248
|
+
}
|
|
2249
|
+
// src/auth/connect-auth-decision.ts
|
|
2250
|
+
function decideConnectAuth(methods, preflight) {
|
|
2251
|
+
if (methods.length === 0)
|
|
2252
|
+
return { action: "skip_auth" };
|
|
2253
|
+
const orderedIds = orderSilentAuthMethodIds(methods, preflight);
|
|
2254
|
+
const ordered = orderedIds.map((id) => methods.find((m) => m.id === id)).filter((m) => Boolean(m));
|
|
2255
|
+
if (shouldPromptAuthWizard(methods, preflight)) {
|
|
2256
|
+
return { action: "needs_auth", methods: ordered.length > 0 ? ordered : methods };
|
|
2257
|
+
}
|
|
2258
|
+
return { action: "silent", methodIds: orderedIds };
|
|
2259
|
+
}
|
|
2260
|
+
// src/auth/connect-auth-gate.ts
|
|
2261
|
+
async function runConnectAuthGate(authMethods, preflight, deps) {
|
|
2262
|
+
const decision = decideConnectAuth(authMethods, preflight);
|
|
2263
|
+
if (decision.action === "skip_auth") {
|
|
2264
|
+
return { outcome: "skip_auth" };
|
|
2265
|
+
}
|
|
2266
|
+
if (decision.action === "needs_auth") {
|
|
2267
|
+
if (deps.tryDirectSessionFirst && deps.tryOpenSessionWithoutAuth) {
|
|
2268
|
+
try {
|
|
2269
|
+
if (await deps.tryOpenSessionWithoutAuth()) {
|
|
2270
|
+
return { outcome: "session_without_auth" };
|
|
2271
|
+
}
|
|
2272
|
+
} catch {}
|
|
2273
|
+
return { outcome: "needs_auth", methods: decision.methods };
|
|
2274
|
+
}
|
|
2275
|
+
return { outcome: "needs_auth", methods: decision.methods };
|
|
2276
|
+
}
|
|
2277
|
+
if (deps.preferDirectSession && preflight.looksLoggedIn && deps.tryOpenSessionWithoutAuth) {
|
|
2278
|
+
try {
|
|
2279
|
+
if (await deps.tryOpenSessionWithoutAuth()) {
|
|
2280
|
+
return { outcome: "session_without_auth" };
|
|
2281
|
+
}
|
|
2282
|
+
} catch {
|
|
2283
|
+
return { outcome: "needs_auth", methods: authMethods };
|
|
2284
|
+
}
|
|
2285
|
+
return { outcome: "needs_auth", methods: authMethods };
|
|
2286
|
+
}
|
|
2287
|
+
for (const methodId of decision.methodIds) {
|
|
2288
|
+
try {
|
|
2289
|
+
await deps.authenticate(methodId);
|
|
2290
|
+
return { outcome: "authenticated", methodId };
|
|
2291
|
+
} catch {}
|
|
2292
|
+
}
|
|
2293
|
+
if (deps.tryOpenSessionWithoutAuth) {
|
|
2294
|
+
try {
|
|
2295
|
+
if (await deps.tryOpenSessionWithoutAuth()) {
|
|
2296
|
+
return { outcome: "session_without_auth" };
|
|
2297
|
+
}
|
|
2298
|
+
} catch {}
|
|
2299
|
+
}
|
|
2300
|
+
return { outcome: "needs_auth", methods: authMethods };
|
|
2301
|
+
}
|
|
2302
|
+
// src/session/agent-registry.ts
|
|
2303
|
+
function listAcpRuntimes() {
|
|
2304
|
+
return [...BUILTIN_ACP_RUNTIMES];
|
|
2305
|
+
}
|
|
2306
|
+
function getAcpRuntime(id) {
|
|
2307
|
+
return findBuiltinAcpRuntime(id);
|
|
2308
|
+
}
|
|
2309
|
+
function getDefaultAcpRuntime() {
|
|
2310
|
+
const runtime = findBuiltinAcpRuntime(DEFAULT_ACP_RUNTIME_ID);
|
|
2311
|
+
if (!runtime) {
|
|
2312
|
+
throw new Error(`缺少默认 ACP 运行时: ${DEFAULT_ACP_RUNTIME_ID}`);
|
|
2313
|
+
}
|
|
2314
|
+
return runtime;
|
|
2315
|
+
}
|
|
2316
|
+
// src/mcp/inkdown-mcp-tools.ts
|
|
2317
|
+
var READER_FORMATS = "EPUB/PDF/MOBI/AZW3 与在线文档(web URL,阅读模式抓取的正文)";
|
|
2318
|
+
var READ_SCOPE_ENUM = ["toc", "viewport", "current", "chapter", "search"];
|
|
2319
|
+
var MARK_LIST_FILTER_ENUM = ["all", "highlights", "bookmarks"];
|
|
2320
|
+
var INKDOWN_MCP_TOOLS = [
|
|
2321
|
+
{
|
|
2322
|
+
name: "inkdown_read",
|
|
2323
|
+
annotations: {
|
|
2324
|
+
title: "Read Inkdown document",
|
|
2325
|
+
readOnlyHint: true,
|
|
2326
|
+
destructiveHint: false,
|
|
2327
|
+
idempotentHint: true,
|
|
2328
|
+
openWorldHint: false
|
|
2329
|
+
},
|
|
2330
|
+
description: `读取当前打开的 ${READER_FORMATS} 内容(不含用户选区;选区用 inkdown_get_selection)。` + "scope 含义:toc=目录结构;viewport=当前视口约一屏(优先于整章);current=当前章/页全文;" + "chapter=指定 TOC 章/页(需 flatIndex 或 title,不跳转);search=全书关键词检索(需 query)。" + "正文 escalation:viewport → current → chapter;结构用 toc;「哪里提到 X」用 search;" + "「这页/这章」不要直接用 current,先看线程里是否已有内容。" + "scope=search 的 JSON 含 source=memory|index,以及 preciseTotal=false" + `(精确 corpus total 只用 inkdown_inspect_content)。
|
|
2331
|
+
` + "已入库 PDF(罗盘索引已建):所有读取只读索引;缺页返回 error(不是空成功)——" + `告知用户,不要重试指望 OCR 补上,也不要凭记忆编造该页内容;请用户重建索引。
|
|
2332
|
+
` + "未入库扫描/混合 PDF:search / inspect_content 会报错而不整书 OCR;" + `viewport/current/chapter 可按需单页 OCR(首次 10–30 秒,缓存后即时)。
|
|
2333
|
+
` + "正文前缀【PDF 第 N/M 页】标识真实读到的页——永远信任该页头," + "不要用其他页或记忆的内容替代;OCR 失败返回 error,提示用户「识别本页」或重建索引。",
|
|
2334
|
+
inputSchema: {
|
|
2335
|
+
type: "object",
|
|
2336
|
+
properties: {
|
|
2337
|
+
scope: {
|
|
2338
|
+
type: "string",
|
|
2339
|
+
enum: READ_SCOPE_ENUM,
|
|
2340
|
+
description: "读取范围"
|
|
2341
|
+
},
|
|
2342
|
+
flatIndex: {
|
|
2343
|
+
type: "number",
|
|
2344
|
+
description: "scope=chapter 时:目录 flatIndex(与 toc.entries[].index 一致)"
|
|
2345
|
+
},
|
|
2346
|
+
title: {
|
|
2347
|
+
type: "string",
|
|
2348
|
+
description: "scope=chapter 时:章节标题(可与 flatIndex 二选一,支持包含匹配)"
|
|
2349
|
+
},
|
|
2350
|
+
query: {
|
|
2351
|
+
type: "string",
|
|
2352
|
+
description: "scope=search 时:检索关键词(取自原文用词)"
|
|
2353
|
+
}
|
|
2354
|
+
},
|
|
2355
|
+
required: ["scope"],
|
|
2356
|
+
additionalProperties: false
|
|
2357
|
+
}
|
|
2358
|
+
},
|
|
2359
|
+
{
|
|
2360
|
+
name: "inkdown_inspect_content",
|
|
2361
|
+
annotations: {
|
|
2362
|
+
title: "Inspect indexed content",
|
|
2363
|
+
readOnlyHint: true,
|
|
2364
|
+
destructiveHint: false,
|
|
2365
|
+
idempotentHint: true,
|
|
2366
|
+
openWorldHint: false
|
|
2367
|
+
},
|
|
2368
|
+
description: "块级取证:按字面关键词返回至多 10 条内容证据(原文、命中位置 start/end/middle/multiple、精确总数与截断标记)。" + "覆盖:当前打开且已入库的 PDF(book-index:PDF 页码、章节标题、block id)、" + "当前 md(editor-buffer:行号,有文件夹时兼 workspace-file 相对路径)、" + "当前 EPUB/MOBI(ebook-section:章节标题定位)。" + "专供审计残留命中(如清洗后是否还有「王道计」、命中是正文还是水印碎片);章节级阅读仍用 inkdown_read。" + "只读,不建库、不 OCR;已入库 PDF 仅读罗盘索引,缺索引直接报错(不要重试指望 OCR),未入库或参数错误也会报错。",
|
|
2369
|
+
inputSchema: {
|
|
2370
|
+
type: "object",
|
|
2371
|
+
properties: {
|
|
2372
|
+
query: {
|
|
2373
|
+
type: "string",
|
|
2374
|
+
description: "字面检索词,至少 3 个字符"
|
|
2375
|
+
},
|
|
2376
|
+
limit: {
|
|
2377
|
+
type: "number",
|
|
2378
|
+
description: "展示条数 1–10,默认 10(只截断展示,不影响总数)",
|
|
2379
|
+
minimum: 1,
|
|
2380
|
+
maximum: 10
|
|
2381
|
+
}
|
|
2382
|
+
},
|
|
2383
|
+
required: ["query"],
|
|
2384
|
+
additionalProperties: false
|
|
2385
|
+
}
|
|
2386
|
+
},
|
|
2387
|
+
{
|
|
2388
|
+
name: "inkdown_get_selection",
|
|
2389
|
+
annotations: {
|
|
2390
|
+
title: "Get current selection",
|
|
2391
|
+
readOnlyHint: true,
|
|
2392
|
+
destructiveHint: false,
|
|
2393
|
+
idempotentHint: true,
|
|
2394
|
+
openWorldHint: false
|
|
2395
|
+
},
|
|
2396
|
+
description: "获取用户当前选中的文本(高频独立工具)。若选区较短(≤30 字),仅向前后各补约 30 字作为 excerpt。" + "仅当 turn-context 出现 hasSelection=true(本轮新划选)时几乎必调;无此标记时不要调。" + "用户划选即优先分析该段;选区通知只生效一轮;无选区时会报错。",
|
|
2397
|
+
inputSchema: {
|
|
2398
|
+
type: "object",
|
|
2399
|
+
properties: {},
|
|
2400
|
+
additionalProperties: false
|
|
2401
|
+
}
|
|
2402
|
+
},
|
|
2403
|
+
{
|
|
2404
|
+
name: "inkdown_list_marks",
|
|
2405
|
+
annotations: {
|
|
2406
|
+
title: "List reading marks",
|
|
2407
|
+
readOnlyHint: true,
|
|
2408
|
+
destructiveHint: false,
|
|
2409
|
+
idempotentHint: true,
|
|
2410
|
+
openWorldHint: false
|
|
2411
|
+
},
|
|
2412
|
+
description: "列出当前打开文档的阅读标记。filter=all(默认)=书签+高亮+批注;highlights=仅划重点(高亮与带摘录批注,含 passages);" + "bookmarks=仅书签。用于 EPUB/PDF/MOBI/在线文档。",
|
|
2413
|
+
inputSchema: {
|
|
2414
|
+
type: "object",
|
|
2415
|
+
properties: {
|
|
2416
|
+
filter: {
|
|
2417
|
+
type: "string",
|
|
2418
|
+
enum: MARK_LIST_FILTER_ENUM,
|
|
2419
|
+
description: "all | highlights | bookmarks;默认 all"
|
|
2420
|
+
}
|
|
2421
|
+
},
|
|
2422
|
+
additionalProperties: false
|
|
2423
|
+
}
|
|
2424
|
+
},
|
|
2425
|
+
{
|
|
2426
|
+
name: "inkdown_suggest_chapters",
|
|
2427
|
+
annotations: {
|
|
2428
|
+
title: "Suggest chapters to mark",
|
|
2429
|
+
readOnlyHint: false,
|
|
2430
|
+
destructiveHint: false,
|
|
2431
|
+
idempotentHint: false,
|
|
2432
|
+
openWorldHint: false
|
|
2433
|
+
},
|
|
2434
|
+
description: "提交章级划重点建议供用户点选(不写 marks、不调 propose_mark)。" + "先 inkdown_read(scope=toc);再提交 2~5 章,每章含 flatIndex、title、reason。" + "用户点选一章后,再 read(scope=chapter) + inkdown_propose_mark(marks),单批≤10。" + "禁止:跳过用户点选、整书范围内提建议、一次批量超限。",
|
|
2435
|
+
inputSchema: {
|
|
2436
|
+
type: "object",
|
|
2437
|
+
properties: {
|
|
2438
|
+
chapters: {
|
|
2439
|
+
type: "array",
|
|
2440
|
+
description: "建议划重点的章节(2~5 条为宜)",
|
|
2441
|
+
minItems: 1,
|
|
2442
|
+
maxItems: 5,
|
|
2443
|
+
items: {
|
|
2444
|
+
type: "object",
|
|
2445
|
+
properties: {
|
|
2446
|
+
flatIndex: { type: "number", description: "与 toc.entries[].index 一致" },
|
|
2447
|
+
title: { type: "string", description: "章节标题" },
|
|
2448
|
+
reason: { type: "string", description: "一句推荐理由" }
|
|
2449
|
+
},
|
|
2450
|
+
required: ["flatIndex", "title", "reason"],
|
|
2451
|
+
additionalProperties: false
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
},
|
|
2455
|
+
required: ["chapters"],
|
|
2456
|
+
additionalProperties: false
|
|
2457
|
+
}
|
|
2458
|
+
},
|
|
2459
|
+
{
|
|
2460
|
+
name: "inkdown_create_bookmark",
|
|
2461
|
+
annotations: {
|
|
2462
|
+
title: "Create bookmark",
|
|
2463
|
+
readOnlyHint: false,
|
|
2464
|
+
destructiveHint: false,
|
|
2465
|
+
idempotentHint: false,
|
|
2466
|
+
openWorldHint: false
|
|
2467
|
+
},
|
|
2468
|
+
description: "在当前阅读位置创建书签(不跳转)。用户明确要求「加个书签」时调用;仅 EPUB/PDF/MOBI。",
|
|
2469
|
+
inputSchema: {
|
|
2470
|
+
type: "object",
|
|
2471
|
+
properties: {},
|
|
2472
|
+
additionalProperties: false
|
|
2473
|
+
}
|
|
2474
|
+
},
|
|
2475
|
+
{
|
|
2476
|
+
name: "inkdown_propose_mark",
|
|
2477
|
+
annotations: {
|
|
2478
|
+
title: "Propose highlight or note",
|
|
2479
|
+
readOnlyHint: false,
|
|
2480
|
+
destructiveHint: false,
|
|
2481
|
+
idempotentHint: false,
|
|
2482
|
+
openWorldHint: false
|
|
2483
|
+
},
|
|
2484
|
+
description: "唯一标记提议工具(高亮 / 批注 / 批量,不入库;用户「采用」后才写入)。" + "单条:excerpt(原句或口述关键词)+ 可选 note(空=仅高亮)+ 可选 kind=highlight|note|auto + 可选 flatIndex。" + "有 fresh 选区时也可只传 note(用当前选区定位)。" + "批量:marks 数组(每项同单条字段,单批≤10,客户端截断超出部分)。" + "客户端读正文并模糊匹配原句;建议先 inkdown_read(scope=viewport) 或 scope=chapter。" + "仅在用户明确要求保存高亮/批注时调用;不要未经提示发明标记,也不要整书到处提议。",
|
|
2485
|
+
inputSchema: {
|
|
2486
|
+
type: "object",
|
|
2487
|
+
properties: {
|
|
2488
|
+
excerpt: {
|
|
2489
|
+
type: "string",
|
|
2490
|
+
description: "单条:要高亮/批注的原文或口述片段"
|
|
2491
|
+
},
|
|
2492
|
+
note: {
|
|
2493
|
+
type: "string",
|
|
2494
|
+
description: "批注正文;省略或空字符串则仅高亮"
|
|
2495
|
+
},
|
|
2496
|
+
kind: {
|
|
2497
|
+
type: "string",
|
|
2498
|
+
enum: ["highlight", "note", "auto"],
|
|
2499
|
+
description: "highlight=仅高亮;note=批注;auto=由 note 是否为空推断(默认)"
|
|
2500
|
+
},
|
|
2501
|
+
flatIndex: {
|
|
2502
|
+
type: "number",
|
|
2503
|
+
description: "可选:目录 flatIndex"
|
|
2504
|
+
},
|
|
2505
|
+
marks: {
|
|
2506
|
+
type: "array",
|
|
2507
|
+
description: "批量提议(≤10);与 excerpt 二选一,优先 marks",
|
|
2508
|
+
items: {
|
|
2509
|
+
type: "object",
|
|
2510
|
+
properties: {
|
|
2511
|
+
excerpt: { type: "string" },
|
|
2512
|
+
note: { type: "string" },
|
|
2513
|
+
kind: { type: "string", enum: ["highlight", "note", "auto"] },
|
|
2514
|
+
flatIndex: { type: "number" }
|
|
2515
|
+
},
|
|
2516
|
+
required: ["excerpt"],
|
|
2517
|
+
additionalProperties: false
|
|
2518
|
+
},
|
|
2519
|
+
maxItems: 10
|
|
2520
|
+
}
|
|
2521
|
+
},
|
|
2522
|
+
additionalProperties: false
|
|
2523
|
+
}
|
|
2524
|
+
},
|
|
2525
|
+
{
|
|
2526
|
+
name: "inkdown_generate_diagram",
|
|
2527
|
+
annotations: {
|
|
2528
|
+
title: "Generate visualization diagram",
|
|
2529
|
+
readOnlyHint: true,
|
|
2530
|
+
destructiveHint: false,
|
|
2531
|
+
idempotentHint: true,
|
|
2532
|
+
openWorldHint: false
|
|
2533
|
+
},
|
|
2534
|
+
description: "生成 Mermaid 可视化图解(时序图、流程图、状态机、实体关系网络或章节思维导图)。" + "当读者询问复杂交互时序(如握手协议流程)、概念实体网络、算法状态机或全章宏观导图时调用。" + "客户端将渲染悬浮卡片并支持双向高亮与「钉入正文」。" + "mermaidCode 仅提供图表纯语法,不要包含 ```mermaid 围栏标记。",
|
|
2535
|
+
inputSchema: {
|
|
2536
|
+
type: "object",
|
|
2537
|
+
properties: {
|
|
2538
|
+
diagramType: {
|
|
2539
|
+
type: "string",
|
|
2540
|
+
enum: ["sequence", "flowchart", "mindmap", "stateDiagram", "classDiagram", "erDiagram"],
|
|
2541
|
+
description: "图表类型:sequence=时序交互;flowchart=流程决策;mindmap=思维导图;stateDiagram=状态机;classDiagram=类关系;erDiagram=实体网络"
|
|
2542
|
+
},
|
|
2543
|
+
title: {
|
|
2544
|
+
type: "string",
|
|
2545
|
+
description: "图表标题(如:ACP 握手与能力协商时序图)"
|
|
2546
|
+
},
|
|
2547
|
+
mermaidCode: {
|
|
2548
|
+
type: "string",
|
|
2549
|
+
description: "标准 Mermaid 语法图表代码(不要加 ``` 围栏)"
|
|
2550
|
+
},
|
|
2551
|
+
anchorExcerpt: {
|
|
2552
|
+
type: "string",
|
|
2553
|
+
description: "可选:该图表所对应的正文关键原文片段(用于点击穿透高亮)"
|
|
2554
|
+
},
|
|
2555
|
+
summary: {
|
|
2556
|
+
type: "string",
|
|
2557
|
+
description: "可选:该图表的核心要点解读(1–2 句话)"
|
|
2558
|
+
},
|
|
2559
|
+
visualSteps: {
|
|
2560
|
+
type: "array",
|
|
2561
|
+
description: "可选:结构化交互式卡片步骤流(提供更现代、可展开参数、可点击正文穿透高亮的卡片视觉)",
|
|
2562
|
+
items: {
|
|
2563
|
+
type: "object",
|
|
2564
|
+
properties: {
|
|
2565
|
+
from: { type: "string", description: "发起方角色(如:client, agent, user, server)" },
|
|
2566
|
+
to: { type: "string", description: "接收方角色(如:agent, client, database)" },
|
|
2567
|
+
action: { type: "string", description: "动作或方法名(如:1. initialize)" },
|
|
2568
|
+
desc: { type: "string", description: "该步骤的关键说明" },
|
|
2569
|
+
payload: { type: "string", description: "可选:该步骤传输的代码或 JSON 参数详情" },
|
|
2570
|
+
anchorExcerpt: {
|
|
2571
|
+
type: "string",
|
|
2572
|
+
description: "可选:该步骤对应的正文片段(用于点击穿透高亮)"
|
|
2573
|
+
}
|
|
2574
|
+
},
|
|
2575
|
+
required: ["from", "to", "action"],
|
|
2576
|
+
additionalProperties: false
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
},
|
|
2580
|
+
required: ["diagramType", "title", "mermaidCode"],
|
|
2581
|
+
additionalProperties: false
|
|
2582
|
+
}
|
|
2583
|
+
},
|
|
2584
|
+
{
|
|
2585
|
+
name: "inkdown_cross_reference",
|
|
2586
|
+
annotations: {
|
|
2587
|
+
title: "Cross reference entity tracker",
|
|
2588
|
+
readOnlyHint: true,
|
|
2589
|
+
destructiveHint: false,
|
|
2590
|
+
idempotentHint: true,
|
|
2591
|
+
openWorldHint: false
|
|
2592
|
+
},
|
|
2593
|
+
description: "全书跨章节实体/概念流转脉络追踪。检索关键技术变量、哲学概念或历史人物在本书各章节的提及分布与上下文证据链。" + "返回按章节组织的证据列表,用于梳理脉络或进行跨章比对。",
|
|
2594
|
+
inputSchema: {
|
|
2595
|
+
type: "object",
|
|
2596
|
+
properties: {
|
|
2597
|
+
entityName: {
|
|
2598
|
+
type: "string",
|
|
2599
|
+
description: "追踪的目标实体或概念名称(至少 2 字符,取自原文)"
|
|
2600
|
+
},
|
|
2601
|
+
maxPerChapter: {
|
|
2602
|
+
type: "number",
|
|
2603
|
+
description: "每章最多展示的引用片段数(1–5,默认 3)",
|
|
2604
|
+
minimum: 1,
|
|
2605
|
+
maximum: 5
|
|
2606
|
+
}
|
|
2607
|
+
},
|
|
2608
|
+
required: ["entityName"],
|
|
2609
|
+
additionalProperties: false
|
|
2610
|
+
}
|
|
2611
|
+
}
|
|
2612
|
+
];
|
|
2613
|
+
function parseReadScope(value) {
|
|
2614
|
+
if (typeof value !== "string")
|
|
2615
|
+
return null;
|
|
2616
|
+
return READ_SCOPE_ENUM.includes(value) ? value : null;
|
|
2617
|
+
}
|
|
2618
|
+
function parseMarkListFilter(value) {
|
|
2619
|
+
if (value === "highlights" || value === "bookmarks")
|
|
2620
|
+
return value;
|
|
2621
|
+
return "all";
|
|
2622
|
+
}
|
|
2623
|
+
async function callInkdownRead(context, scope, args) {
|
|
2624
|
+
switch (scope) {
|
|
2625
|
+
case "toc": {
|
|
2626
|
+
const text = await context.readSnapshot("toc.json");
|
|
2627
|
+
return { content: [{ type: "text", text }] };
|
|
2628
|
+
}
|
|
2629
|
+
case "viewport": {
|
|
2630
|
+
const text = await context.readSnapshot("viewport.txt");
|
|
2631
|
+
return { content: [{ type: "text", text }] };
|
|
2632
|
+
}
|
|
2633
|
+
case "current": {
|
|
2634
|
+
const text = await context.readSnapshot("chapter.txt");
|
|
2635
|
+
return { content: [{ type: "text", text }] };
|
|
2636
|
+
}
|
|
2637
|
+
case "chapter": {
|
|
2638
|
+
const flatIndex = args?.flatIndex;
|
|
2639
|
+
const title = args?.title;
|
|
2640
|
+
if ((typeof flatIndex !== "number" || !Number.isFinite(flatIndex)) && (typeof title !== "string" || !title.trim())) {
|
|
2641
|
+
return {
|
|
2642
|
+
content: [
|
|
2643
|
+
{
|
|
2644
|
+
type: "text",
|
|
2645
|
+
text: "inkdown_read(scope=chapter) 需要 flatIndex 或 title 之一"
|
|
2646
|
+
}
|
|
2647
|
+
],
|
|
2648
|
+
isError: true
|
|
2649
|
+
};
|
|
2650
|
+
}
|
|
2651
|
+
const text = await context.readSnapshot("chapter", {
|
|
2652
|
+
...typeof flatIndex === "number" ? { flatIndex } : {},
|
|
2653
|
+
...typeof title === "string" ? { title } : {}
|
|
2654
|
+
});
|
|
2655
|
+
return { content: [{ type: "text", text }] };
|
|
2656
|
+
}
|
|
2657
|
+
case "search": {
|
|
2658
|
+
const query = args?.query;
|
|
2659
|
+
if (typeof query !== "string" || !query.trim()) {
|
|
2660
|
+
return {
|
|
2661
|
+
content: [
|
|
2662
|
+
{ type: "text", text: "inkdown_read(scope=search) 需要非空的 query 参数" }
|
|
2663
|
+
],
|
|
2664
|
+
isError: true
|
|
2665
|
+
};
|
|
2666
|
+
}
|
|
2667
|
+
const text = await context.readSnapshot("search", { query });
|
|
2668
|
+
return { content: [{ type: "text", text }] };
|
|
2669
|
+
}
|
|
2670
|
+
}
|
|
2671
|
+
}
|
|
2672
|
+
async function callInkdownMcpTool(name, context, args) {
|
|
2673
|
+
switch (name) {
|
|
2674
|
+
case "inkdown_read": {
|
|
2675
|
+
const scope = parseReadScope(args?.scope);
|
|
2676
|
+
if (!scope) {
|
|
2677
|
+
return {
|
|
2678
|
+
content: [
|
|
2679
|
+
{
|
|
2680
|
+
type: "text",
|
|
2681
|
+
text: "inkdown_read 需要 scope: toc | viewport | current | chapter | search"
|
|
2682
|
+
}
|
|
2683
|
+
],
|
|
2684
|
+
isError: true
|
|
2685
|
+
};
|
|
2686
|
+
}
|
|
2687
|
+
return callInkdownRead(context, scope, args);
|
|
2688
|
+
}
|
|
2689
|
+
case "inkdown_get_toc":
|
|
2690
|
+
return callInkdownRead(context, "toc", args);
|
|
2691
|
+
case "inkdown_get_viewport":
|
|
2692
|
+
return callInkdownRead(context, "viewport", args);
|
|
2693
|
+
case "inkdown_get_current_text":
|
|
2694
|
+
return callInkdownRead(context, "current", args);
|
|
2695
|
+
case "inkdown_get_chapter":
|
|
2696
|
+
return callInkdownRead(context, "chapter", args);
|
|
2697
|
+
case "inkdown_search":
|
|
2698
|
+
return callInkdownRead(context, "search", args);
|
|
2699
|
+
case "inkdown_inspect_content": {
|
|
2700
|
+
const query = args?.query;
|
|
2701
|
+
if (typeof query !== "string" || !query.trim()) {
|
|
2702
|
+
return {
|
|
2703
|
+
content: [{ type: "text", text: "inkdown_inspect_content 需要非空的 query 参数" }],
|
|
2704
|
+
isError: true
|
|
2705
|
+
};
|
|
2706
|
+
}
|
|
2707
|
+
const limit = args?.limit;
|
|
2708
|
+
if (limit !== undefined && (typeof limit !== "number" || !Number.isFinite(limit))) {
|
|
2709
|
+
return {
|
|
2710
|
+
content: [{ type: "text", text: "inkdown_inspect_content 的 limit 须为数字(1–10)" }],
|
|
2711
|
+
isError: true
|
|
2712
|
+
};
|
|
2713
|
+
}
|
|
2714
|
+
const text = await context.readSnapshot("content-audit", {
|
|
2715
|
+
query,
|
|
2716
|
+
...limit === undefined ? {} : { limit }
|
|
2717
|
+
});
|
|
2718
|
+
return { content: [{ type: "text", text }] };
|
|
2719
|
+
}
|
|
2720
|
+
case "inkdown_get_selection": {
|
|
2721
|
+
const text = await context.readSnapshot("selection");
|
|
2722
|
+
return { content: [{ type: "text", text }] };
|
|
2723
|
+
}
|
|
2724
|
+
case "inkdown_list_marks": {
|
|
2725
|
+
const filter = parseMarkListFilter(args?.filter);
|
|
2726
|
+
const text = await context.readSnapshot("marks", { filter });
|
|
2727
|
+
return { content: [{ type: "text", text }] };
|
|
2728
|
+
}
|
|
2729
|
+
case "inkdown_list_highlights": {
|
|
2730
|
+
const text = await context.readSnapshot("marks", { filter: "highlights" });
|
|
2731
|
+
return { content: [{ type: "text", text }] };
|
|
2732
|
+
}
|
|
2733
|
+
case "inkdown_create_bookmark": {
|
|
2734
|
+
const text = await context.readSnapshot("create-bookmark");
|
|
2735
|
+
return { content: [{ type: "text", text }] };
|
|
2736
|
+
}
|
|
2737
|
+
case "inkdown_create_note":
|
|
2738
|
+
case "inkdown_propose_note": {
|
|
2739
|
+
const note = typeof args?.note === "string" ? args.note : "";
|
|
2740
|
+
const text = await context.readSnapshot("propose-mark", { note });
|
|
2741
|
+
return { content: [{ type: "text", text }] };
|
|
2742
|
+
}
|
|
2743
|
+
case "inkdown_suggest_chapters": {
|
|
2744
|
+
const chapters = args?.chapters;
|
|
2745
|
+
if (!Array.isArray(chapters) || chapters.length === 0) {
|
|
2746
|
+
return {
|
|
2747
|
+
content: [{ type: "text", text: "inkdown_suggest_chapters 需要非空 chapters 数组" }],
|
|
2748
|
+
isError: true
|
|
2749
|
+
};
|
|
2750
|
+
}
|
|
2751
|
+
const text = await context.readSnapshot("suggest-chapters", { chapters });
|
|
2752
|
+
return { content: [{ type: "text", text }] };
|
|
2753
|
+
}
|
|
2754
|
+
case "inkdown_propose_mark": {
|
|
2755
|
+
const marks = args?.marks;
|
|
2756
|
+
const excerpt = args?.excerpt;
|
|
2757
|
+
const noteOnly = typeof args?.note === "string" && args.note.trim();
|
|
2758
|
+
if ((!Array.isArray(marks) || marks.length === 0) && (typeof excerpt !== "string" || !excerpt.trim()) && !noteOnly) {
|
|
2759
|
+
return {
|
|
2760
|
+
content: [
|
|
2761
|
+
{
|
|
2762
|
+
type: "text",
|
|
2763
|
+
text: "inkdown_propose_mark 需要 excerpt、marks 之一,或有选区时仅传 note"
|
|
2764
|
+
}
|
|
2765
|
+
],
|
|
2766
|
+
isError: true
|
|
2767
|
+
};
|
|
2768
|
+
}
|
|
2769
|
+
const note = typeof args?.note === "string" ? args.note : "";
|
|
2770
|
+
const flatIndex = args?.flatIndex;
|
|
2771
|
+
const kind = args?.kind;
|
|
2772
|
+
const text = await context.readSnapshot("propose-mark", {
|
|
2773
|
+
...typeof excerpt === "string" ? { excerpt } : {},
|
|
2774
|
+
note,
|
|
2775
|
+
kind: kind === "highlight" || kind === "note" || kind === "auto" ? kind : undefined,
|
|
2776
|
+
...typeof flatIndex === "number" && Number.isFinite(flatIndex) ? { flatIndex } : {},
|
|
2777
|
+
...Array.isArray(marks) ? { marks } : {}
|
|
2778
|
+
});
|
|
2779
|
+
return { content: [{ type: "text", text }] };
|
|
2780
|
+
}
|
|
2781
|
+
case "inkdown_generate_diagram": {
|
|
2782
|
+
const diagramType = args?.diagramType;
|
|
2783
|
+
const title = args?.title;
|
|
2784
|
+
const mermaidCode = args?.mermaidCode;
|
|
2785
|
+
const anchorExcerpt = typeof args?.anchorExcerpt === "string" ? args.anchorExcerpt.trim() : undefined;
|
|
2786
|
+
const summary = typeof args?.summary === "string" ? args.summary.trim() : undefined;
|
|
2787
|
+
const validTypes = [
|
|
2788
|
+
"sequence",
|
|
2789
|
+
"flowchart",
|
|
2790
|
+
"mindmap",
|
|
2791
|
+
"stateDiagram",
|
|
2792
|
+
"classDiagram",
|
|
2793
|
+
"erDiagram"
|
|
2794
|
+
];
|
|
2795
|
+
if (typeof diagramType !== "string" || !validTypes.includes(diagramType)) {
|
|
2796
|
+
return {
|
|
2797
|
+
content: [
|
|
2798
|
+
{
|
|
2799
|
+
type: "text",
|
|
2800
|
+
text: `inkdown_generate_diagram 需要有效的 diagramType: ${validTypes.join(", ")}`
|
|
2801
|
+
}
|
|
2802
|
+
],
|
|
2803
|
+
isError: true
|
|
2804
|
+
};
|
|
2805
|
+
}
|
|
2806
|
+
if (typeof title !== "string" || !title.trim()) {
|
|
2807
|
+
return {
|
|
2808
|
+
content: [
|
|
2809
|
+
{
|
|
2810
|
+
type: "text",
|
|
2811
|
+
text: "inkdown_generate_diagram 需要非空的 title 参数"
|
|
2812
|
+
}
|
|
2813
|
+
],
|
|
2814
|
+
isError: true
|
|
2815
|
+
};
|
|
2816
|
+
}
|
|
2817
|
+
if (typeof mermaidCode !== "string" || !mermaidCode.trim()) {
|
|
2818
|
+
return {
|
|
2819
|
+
content: [
|
|
2820
|
+
{
|
|
2821
|
+
type: "text",
|
|
2822
|
+
text: "inkdown_generate_diagram 需要非空的 mermaidCode 参数"
|
|
2823
|
+
}
|
|
2824
|
+
],
|
|
2825
|
+
isError: true
|
|
2826
|
+
};
|
|
2827
|
+
}
|
|
2828
|
+
const cleanedCode = mermaidCode.replace(/^```(?:mermaid)?[\r\n]*/i, "").replace(/^mermaid[\r\n]+/i, "").replace(/[\r\n]*```\s*$/i, "").trim();
|
|
2829
|
+
const visualSteps = Array.isArray(args?.visualSteps) ? args.visualSteps : undefined;
|
|
2830
|
+
const payload = {
|
|
2831
|
+
diagramId: `diag-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
|
|
2832
|
+
diagramType,
|
|
2833
|
+
title: title.trim(),
|
|
2834
|
+
mermaidCode: cleanedCode,
|
|
2835
|
+
...anchorExcerpt ? { anchorExcerpt } : {},
|
|
2836
|
+
...summary ? { summary } : {},
|
|
2837
|
+
...visualSteps ? { visualSteps } : {}
|
|
2838
|
+
};
|
|
2839
|
+
return {
|
|
2840
|
+
content: [
|
|
2841
|
+
{
|
|
2842
|
+
type: "text",
|
|
2843
|
+
text: JSON.stringify(payload, null, 2)
|
|
2844
|
+
}
|
|
2845
|
+
]
|
|
2846
|
+
};
|
|
2847
|
+
}
|
|
2848
|
+
case "inkdown_cross_reference": {
|
|
2849
|
+
const entityName = args?.entityName;
|
|
2850
|
+
if (typeof entityName !== "string" || entityName.trim().length < 2) {
|
|
2851
|
+
return {
|
|
2852
|
+
content: [
|
|
2853
|
+
{
|
|
2854
|
+
type: "text",
|
|
2855
|
+
text: "inkdown_cross_reference 需要至少 2 个字符的 entityName 参数"
|
|
2856
|
+
}
|
|
2857
|
+
],
|
|
2858
|
+
isError: true
|
|
2859
|
+
};
|
|
2860
|
+
}
|
|
2861
|
+
const rawText = await context.readSnapshot("search", { query: entityName.trim() });
|
|
2862
|
+
try {
|
|
2863
|
+
const parsed = JSON.parse(rawText);
|
|
2864
|
+
const maxPerChapter = typeof args?.maxPerChapter === "number" && args.maxPerChapter >= 1 && args.maxPerChapter <= 5 ? Math.floor(args.maxPerChapter) : 3;
|
|
2865
|
+
const hits = Array.isArray(parsed.hits) ? parsed.hits : [];
|
|
2866
|
+
const chapterMap = new Map;
|
|
2867
|
+
for (const hit of hits) {
|
|
2868
|
+
const key = hit.flatIndex != null ? hit.flatIndex : hit.title ?? "未知章节";
|
|
2869
|
+
const hitCount = typeof hit.count === "number" && hit.count > 0 ? hit.count : 1;
|
|
2870
|
+
const snippet = hit.snippet?.trim() || "";
|
|
2871
|
+
const existing = chapterMap.get(key);
|
|
2872
|
+
if (!existing) {
|
|
2873
|
+
chapterMap.set(key, {
|
|
2874
|
+
chapter: hit.title ?? "未知章节",
|
|
2875
|
+
...hit.flatIndex != null ? { flatIndex: hit.flatIndex } : {},
|
|
2876
|
+
occurrences: hitCount,
|
|
2877
|
+
excerpt: snippet,
|
|
2878
|
+
excerpts: snippet ? [snippet] : []
|
|
2879
|
+
});
|
|
2880
|
+
} else {
|
|
2881
|
+
existing.occurrences += hitCount;
|
|
2882
|
+
if (snippet && existing.excerpts.length < maxPerChapter && !existing.excerpts.includes(snippet)) {
|
|
2883
|
+
existing.excerpts.push(snippet);
|
|
2884
|
+
}
|
|
2885
|
+
if (!existing.excerpt && snippet) {
|
|
2886
|
+
existing.excerpt = snippet;
|
|
2887
|
+
}
|
|
2888
|
+
}
|
|
2889
|
+
}
|
|
2890
|
+
const chapterDistribution = Array.from(chapterMap.values()).slice(0, 15);
|
|
2891
|
+
const totalOccurrences = typeof parsed.totalMatches === "number" ? parsed.totalMatches : chapterDistribution.reduce((acc, c) => acc + c.occurrences, 0);
|
|
2892
|
+
const result = {
|
|
2893
|
+
entity: entityName.trim(),
|
|
2894
|
+
totalOccurrences,
|
|
2895
|
+
chapterDistribution
|
|
2896
|
+
};
|
|
2897
|
+
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
2898
|
+
} catch {
|
|
2899
|
+
return { content: [{ type: "text", text: rawText }] };
|
|
2900
|
+
}
|
|
2901
|
+
}
|
|
2902
|
+
default:
|
|
2903
|
+
return {
|
|
2904
|
+
content: [{ type: "text", text: `未知工具: ${name}` }],
|
|
2905
|
+
isError: true
|
|
2906
|
+
};
|
|
2907
|
+
}
|
|
2908
|
+
}
|
|
2909
|
+
// src/mcp/inkdown-mcp-toc-tools.ts
|
|
2910
|
+
var FINGERPRINT_PROP = {
|
|
2911
|
+
fingerprint: {
|
|
2912
|
+
type: "string",
|
|
2913
|
+
description: "目标书指纹(取自任务提示,照抄)"
|
|
2914
|
+
}
|
|
2915
|
+
};
|
|
2916
|
+
var TOC_ENTRY_SCHEMA = {
|
|
2917
|
+
type: "object",
|
|
2918
|
+
properties: {
|
|
2919
|
+
title: { type: "string", description: "章节标题" },
|
|
2920
|
+
printedPage: { type: "number", description: "印在纸上的页码" },
|
|
2921
|
+
level: { type: "number", description: "章/部=1,节=2,小节=3" }
|
|
2922
|
+
},
|
|
2923
|
+
required: ["title", "printedPage"],
|
|
2924
|
+
additionalProperties: false
|
|
2925
|
+
};
|
|
2926
|
+
var INKDOWN_TOC_MCP_TOOLS = [
|
|
2927
|
+
{
|
|
2928
|
+
name: "toc_list_draft",
|
|
2929
|
+
annotations: {
|
|
2930
|
+
title: "List TOC draft",
|
|
2931
|
+
readOnlyHint: true,
|
|
2932
|
+
destructiveHint: false,
|
|
2933
|
+
idempotentHint: true,
|
|
2934
|
+
openWorldHint: false
|
|
2935
|
+
},
|
|
2936
|
+
description: "查看当前目录草稿(条目、指纹)。写入后调用来自查。",
|
|
2937
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false }
|
|
2938
|
+
},
|
|
2939
|
+
{
|
|
2940
|
+
name: "toc_replace_all",
|
|
2941
|
+
annotations: {
|
|
2942
|
+
title: "Replace TOC draft",
|
|
2943
|
+
readOnlyHint: false,
|
|
2944
|
+
destructiveHint: true,
|
|
2945
|
+
idempotentHint: true,
|
|
2946
|
+
openWorldHint: false
|
|
2947
|
+
},
|
|
2948
|
+
description: "整单写入目录草稿(首选,一次写完整个目录,只需确认一次)。" + "level:章/部=1,节=2,小节=3;水印碎片会被自动丢弃并计数。" + "缺页码的节父项会自动跟随后继(限连续3个),缺页码的章行会被丢弃:" + "章页码必须明确给出,不要留空。",
|
|
2949
|
+
inputSchema: {
|
|
2950
|
+
type: "object",
|
|
2951
|
+
properties: {
|
|
2952
|
+
...FINGERPRINT_PROP,
|
|
2953
|
+
entries: {
|
|
2954
|
+
type: "array",
|
|
2955
|
+
description: "完整目录条目",
|
|
2956
|
+
items: TOC_ENTRY_SCHEMA
|
|
2957
|
+
}
|
|
2958
|
+
},
|
|
2959
|
+
required: ["fingerprint", "entries"],
|
|
2960
|
+
additionalProperties: false
|
|
2961
|
+
}
|
|
2962
|
+
},
|
|
2963
|
+
{
|
|
2964
|
+
name: "toc_upsert_entry",
|
|
2965
|
+
annotations: {
|
|
2966
|
+
title: "Update TOC entry",
|
|
2967
|
+
readOnlyHint: false,
|
|
2968
|
+
destructiveHint: false,
|
|
2969
|
+
idempotentHint: true,
|
|
2970
|
+
openWorldHint: false
|
|
2971
|
+
},
|
|
2972
|
+
description: "新增或按标题更新一条目录(小修补用,大改走 toc_replace_all)。",
|
|
2973
|
+
inputSchema: {
|
|
2974
|
+
type: "object",
|
|
2975
|
+
properties: {
|
|
2976
|
+
...FINGERPRINT_PROP,
|
|
2977
|
+
entry: TOC_ENTRY_SCHEMA
|
|
2978
|
+
},
|
|
2979
|
+
required: ["fingerprint", "entry"],
|
|
2980
|
+
additionalProperties: false
|
|
2981
|
+
}
|
|
2982
|
+
},
|
|
2983
|
+
{
|
|
2984
|
+
name: "toc_delete_entry",
|
|
2985
|
+
annotations: {
|
|
2986
|
+
title: "Delete TOC entry",
|
|
2987
|
+
readOnlyHint: false,
|
|
2988
|
+
destructiveHint: true,
|
|
2989
|
+
idempotentHint: true,
|
|
2990
|
+
openWorldHint: false
|
|
2991
|
+
},
|
|
2992
|
+
description: "按序号(从 0 起)或标题删一条目录。",
|
|
2993
|
+
inputSchema: {
|
|
2994
|
+
type: "object",
|
|
2995
|
+
properties: {
|
|
2996
|
+
...FINGERPRINT_PROP,
|
|
2997
|
+
index: { type: "number", description: "草稿序号,与 title 二选一" },
|
|
2998
|
+
title: { type: "string", description: "条目标题,与 index 二选一" }
|
|
2999
|
+
},
|
|
3000
|
+
additionalProperties: false
|
|
3001
|
+
}
|
|
3002
|
+
}
|
|
3003
|
+
];
|
|
3004
|
+
function invalidFingerprint() {
|
|
3005
|
+
return {
|
|
3006
|
+
content: [{ type: "text", text: "缺少 fingerprint(取自任务提示,照抄)" }],
|
|
3007
|
+
isError: true
|
|
3008
|
+
};
|
|
3009
|
+
}
|
|
3010
|
+
function fingerprintOf(args) {
|
|
3011
|
+
const fingerprint = args?.fingerprint;
|
|
3012
|
+
return typeof fingerprint === "string" && fingerprint.trim() ? fingerprint.trim() : null;
|
|
3013
|
+
}
|
|
3014
|
+
function fingerprintTail(args) {
|
|
3015
|
+
const fingerprint = args?.fingerprint;
|
|
3016
|
+
if (typeof fingerprint !== "string" || !fingerprint)
|
|
3017
|
+
return "-";
|
|
3018
|
+
return fingerprint.length > 24 ? `…${fingerprint.slice(-24)}` : fingerprint;
|
|
3019
|
+
}
|
|
3020
|
+
async function callInkdownTocTool(name, context, args) {
|
|
3021
|
+
const startedAt = Date.now();
|
|
3022
|
+
try {
|
|
3023
|
+
return await callInkdownTocToolInner(name, context, args);
|
|
3024
|
+
} finally {
|
|
3025
|
+
console.info(`[toc-mcp] tool=${name} fp=${fingerprintTail(args)} elapsedMs=${Date.now() - startedAt}`);
|
|
3026
|
+
}
|
|
3027
|
+
}
|
|
3028
|
+
async function callInkdownTocToolInner(name, context, args) {
|
|
3029
|
+
switch (name) {
|
|
3030
|
+
case "toc_list_draft": {
|
|
3031
|
+
const text = await context.readSnapshot("toc-draft-read");
|
|
3032
|
+
return { content: [{ type: "text", text }] };
|
|
3033
|
+
}
|
|
3034
|
+
case "toc_replace_all":
|
|
3035
|
+
case "toc_upsert_entry":
|
|
3036
|
+
case "toc_delete_entry": {
|
|
3037
|
+
const fingerprint = fingerprintOf(args);
|
|
3038
|
+
if (!fingerprint)
|
|
3039
|
+
return invalidFingerprint();
|
|
3040
|
+
const op = name === "toc_replace_all" ? "replace" : name === "toc_upsert_entry" ? "upsert" : "delete";
|
|
3041
|
+
const text = await context.readSnapshot("toc-draft-write", {
|
|
3042
|
+
op,
|
|
3043
|
+
fingerprint,
|
|
3044
|
+
entries: args?.entries,
|
|
3045
|
+
entry: args?.entry,
|
|
3046
|
+
...typeof args?.title === "string" ? { title: args.title } : {},
|
|
3047
|
+
...typeof args?.index === "number" ? { index: args.index } : {}
|
|
3048
|
+
});
|
|
3049
|
+
return { content: [{ type: "text", text }] };
|
|
3050
|
+
}
|
|
3051
|
+
default:
|
|
3052
|
+
return {
|
|
3053
|
+
content: [{ type: "text", text: `未知目录工具: ${name}` }],
|
|
3054
|
+
isError: true
|
|
3055
|
+
};
|
|
3056
|
+
}
|
|
3057
|
+
}
|
|
3058
|
+
// src/mcp/inkdown-mcp-rpc.ts
|
|
3059
|
+
var FALLBACK_PROTOCOL_VERSION = "2025-06-18";
|
|
3060
|
+
function result(id, value) {
|
|
3061
|
+
return { jsonrpc: "2.0", id, result: value };
|
|
3062
|
+
}
|
|
3063
|
+
function rpcError(id, code, message) {
|
|
3064
|
+
return { jsonrpc: "2.0", id, error: { code, message } };
|
|
3065
|
+
}
|
|
3066
|
+
function isNotification(message) {
|
|
3067
|
+
return message.id === undefined || message.id === null;
|
|
3068
|
+
}
|
|
3069
|
+
async function handleInkdownMcpRpc(message, context, tools = INKDOWN_MCP_TOOLS, call = callInkdownMcpTool) {
|
|
3070
|
+
const method = message.method;
|
|
3071
|
+
if (!method) {
|
|
3072
|
+
return isNotification(message) ? null : rpcError(message.id, -32600, "缺少 method");
|
|
3073
|
+
}
|
|
3074
|
+
if (isNotification(message))
|
|
3075
|
+
return null;
|
|
3076
|
+
switch (method) {
|
|
3077
|
+
case "initialize": {
|
|
3078
|
+
const requested = message.params?.protocolVersion;
|
|
3079
|
+
return result(message.id, {
|
|
3080
|
+
protocolVersion: typeof requested === "string" ? requested : FALLBACK_PROTOCOL_VERSION,
|
|
3081
|
+
capabilities: { tools: { listChanged: false } },
|
|
3082
|
+
serverInfo: { name: "inkdown", version: "1" }
|
|
3083
|
+
});
|
|
3084
|
+
}
|
|
3085
|
+
case "ping":
|
|
3086
|
+
return result(message.id, {});
|
|
3087
|
+
case "tools/list":
|
|
3088
|
+
return result(message.id, { tools });
|
|
3089
|
+
case "tools/call": {
|
|
3090
|
+
const name = message.params?.name;
|
|
3091
|
+
if (typeof name !== "string") {
|
|
3092
|
+
return rpcError(message.id, -32602, "tools/call 需要 name");
|
|
3093
|
+
}
|
|
3094
|
+
const rawArgs = message.params?.arguments;
|
|
3095
|
+
const args = rawArgs && typeof rawArgs === "object" && !Array.isArray(rawArgs) ? rawArgs : undefined;
|
|
3096
|
+
try {
|
|
3097
|
+
return result(message.id, await call(name, context, args));
|
|
3098
|
+
} catch (error) {
|
|
3099
|
+
const messageText = error instanceof Error ? error.message : "工具执行失败";
|
|
3100
|
+
console.warn("[acp-mcp] tools/call 失败", {
|
|
3101
|
+
name,
|
|
3102
|
+
message: messageText,
|
|
3103
|
+
stack: error instanceof Error ? error.stack : undefined
|
|
3104
|
+
});
|
|
3105
|
+
return result(message.id, {
|
|
3106
|
+
content: [
|
|
3107
|
+
{
|
|
3108
|
+
type: "text",
|
|
3109
|
+
text: messageText
|
|
3110
|
+
}
|
|
3111
|
+
],
|
|
3112
|
+
isError: true
|
|
3113
|
+
});
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
default:
|
|
3117
|
+
return rpcError(message.id, -32601, `未实现的方法: ${method}`);
|
|
3118
|
+
}
|
|
3119
|
+
}
|
|
3120
|
+
export {
|
|
3121
|
+
ACP_EARLY_EXIT_STDERR_TAIL_LINES,
|
|
3122
|
+
ACP_EARLY_EXIT_WINDOW_MS,
|
|
3123
|
+
ACP_SDK_REQUEST_TIMEOUT_MS,
|
|
3124
|
+
AGY_ACP_NPM_PACKAGE,
|
|
3125
|
+
AcpClient,
|
|
3126
|
+
AcpSessionHandle,
|
|
3127
|
+
AcpTerminalManager,
|
|
3128
|
+
BUILTIN_ACP_RUNTIMES,
|
|
3129
|
+
CLAUDE_ACP_NPM_PACKAGE,
|
|
3130
|
+
CODEX_ACP_NPM_PACKAGE,
|
|
3131
|
+
DEEPSEEK_DSH_NPM_PACKAGE,
|
|
3132
|
+
DEFAULT_ACP_PROXY_SETTINGS,
|
|
3133
|
+
DEFAULT_ACP_RUNTIME_ID,
|
|
3134
|
+
INKDOWN_MCP_TOOLS,
|
|
3135
|
+
INKDOWN_PROVIDER_API_KEY_ENV,
|
|
3136
|
+
INKDOWN_PROVIDER_ID,
|
|
3137
|
+
INKDOWN_SETTLE_COMPLETE_KIND,
|
|
3138
|
+
INKDOWN_TOC_MCP_TOOLS,
|
|
3139
|
+
INKDOWN_VIRTUAL_DIR,
|
|
3140
|
+
INKDOWN_VIRTUAL_RESOURCES,
|
|
3141
|
+
LEGACY_ZED_CODEX_ACP_NPM_PACKAGE,
|
|
3142
|
+
acpReadTextFile,
|
|
3143
|
+
acpWriteTextFile,
|
|
3144
|
+
agyAdapter,
|
|
3145
|
+
appendTerminalOutput,
|
|
3146
|
+
assertPathInsideWorkspace,
|
|
3147
|
+
buildAcpProxySpawnEnv,
|
|
3148
|
+
buildCursorMissingCliMessage,
|
|
3149
|
+
buildCustomProviderConfigToml,
|
|
3150
|
+
buildCustomProviderSpawnEnv,
|
|
3151
|
+
buildDeepseekMissingKeyMessage,
|
|
3152
|
+
callInkdownMcpTool,
|
|
3153
|
+
callInkdownTocTool,
|
|
3154
|
+
claudeAdapter,
|
|
3155
|
+
clearAcpProvider,
|
|
3156
|
+
clearCursorCatalogCache,
|
|
3157
|
+
codexAdapter,
|
|
3158
|
+
connectSdkClient,
|
|
3159
|
+
copilotAdapter,
|
|
3160
|
+
createSdkStreamHandle,
|
|
3161
|
+
cursorAdapter,
|
|
3162
|
+
decideConnectAuth,
|
|
3163
|
+
deepseekAdapter,
|
|
3164
|
+
disposeAllAcpProcesses,
|
|
3165
|
+
emptyAcpAuthPreflight,
|
|
3166
|
+
err,
|
|
3167
|
+
findBuiltinAcpRuntime,
|
|
3168
|
+
findModelConfigOption,
|
|
3169
|
+
geminiAdapter,
|
|
3170
|
+
getAcpEarlyExitStderrDetail,
|
|
3171
|
+
getAcpProviderCodexHome,
|
|
3172
|
+
getAcpProviderStatus,
|
|
3173
|
+
getAcpRuntime,
|
|
3174
|
+
getAcpRuntimeAdapter,
|
|
3175
|
+
getActiveAcpProcess,
|
|
3176
|
+
getCursorCatalogIds,
|
|
3177
|
+
getDefaultAcpRuntime,
|
|
3178
|
+
getDefaultAgentDataDir,
|
|
3179
|
+
getLiveAcpProcess,
|
|
3180
|
+
handleInkdownMcpRpc,
|
|
3181
|
+
isAppError,
|
|
3182
|
+
isBinaryDocumentPath,
|
|
3183
|
+
isCancelled,
|
|
3184
|
+
isCodexPreflightRuntime,
|
|
3185
|
+
isErr,
|
|
3186
|
+
isHintCursorStorageFile,
|
|
3187
|
+
isInkdownVirtualDirPath,
|
|
3188
|
+
isOk,
|
|
3189
|
+
isSpawnedAcpProcessAlive,
|
|
3190
|
+
isTransientAcpTransportError,
|
|
3191
|
+
isValidCursorAuthFile,
|
|
3192
|
+
isValidOpencodeAuthFile,
|
|
3193
|
+
listAcpRuntimes,
|
|
3194
|
+
listLiveAcpRuntimeIds,
|
|
3195
|
+
mergeTopLevelModelsIntoConfigOptions,
|
|
3196
|
+
ok,
|
|
3197
|
+
opencodeAdapter,
|
|
3198
|
+
orderSilentAuthMethodIds,
|
|
3199
|
+
parseAcpConfigOptions,
|
|
3200
|
+
parseCursorCatalogOutput,
|
|
3201
|
+
parseInkdownVirtualPath,
|
|
3202
|
+
parseLoadSessionSupported,
|
|
3203
|
+
parseMcpHttpSupported,
|
|
3204
|
+
parsePromptCapabilities,
|
|
3205
|
+
parseResumeSessionSupported,
|
|
3206
|
+
pickAllowOptionId,
|
|
3207
|
+
probeAgyAuth,
|
|
3208
|
+
probeClaudeAuth,
|
|
3209
|
+
probeCodexAuth,
|
|
3210
|
+
probeCopilotAuth,
|
|
3211
|
+
probeCursorAuth,
|
|
3212
|
+
probeDeepseekAuth,
|
|
3213
|
+
probeGeminiAuth,
|
|
3214
|
+
probeOpencodeAuth,
|
|
3215
|
+
provisionCustomProviderCodexHome,
|
|
3216
|
+
readAcpProxySettings,
|
|
3217
|
+
readStoredAcpProvider,
|
|
3218
|
+
registerAcpClientHandlers,
|
|
3219
|
+
resolveClaudeHome,
|
|
3220
|
+
resolveCodexHome,
|
|
3221
|
+
resolveCopilotHome,
|
|
3222
|
+
resolveCursorAuthCandidates,
|
|
3223
|
+
resolveCursorCommand,
|
|
3224
|
+
resolveCursorSpawnCommand,
|
|
3225
|
+
resolveDeepseekPackage,
|
|
3226
|
+
resolveDeepseekSpawnBlocker,
|
|
3227
|
+
resolveDeepseekSpawnCommand,
|
|
3228
|
+
resolveGeminiHome,
|
|
3229
|
+
resolveOpencodeAuthCandidates,
|
|
3230
|
+
resolveOpencodeAuthFile,
|
|
3231
|
+
restoreOrCreateAcpSession,
|
|
3232
|
+
runConnectAuthGate,
|
|
3233
|
+
saveAcpProvider,
|
|
3234
|
+
saveAcpProxySettings,
|
|
3235
|
+
sdkRequest,
|
|
3236
|
+
shouldPromptAuthWizard,
|
|
3237
|
+
spawnAcpProcess,
|
|
3238
|
+
synthesizeModelOptionFromTopLevelModels,
|
|
3239
|
+
toAppError,
|
|
3240
|
+
truncateOutputFromStart,
|
|
3241
|
+
withAcpEarlyExitDetail
|
|
3242
|
+
};
|