dal-code 1.0.0 → 1.0.7

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.
Files changed (166) hide show
  1. package/CHANGELOG.md +67 -1
  2. package/dist/core/auth-guidance.d.ts +1 -0
  3. package/dist/core/auth-guidance.d.ts.map +1 -1
  4. package/dist/core/auth-guidance.js +6 -0
  5. package/dist/core/auth-guidance.js.map +1 -1
  6. package/dist/core/compaction/compaction.d.ts.map +1 -1
  7. package/dist/core/compaction/compaction.js +4 -7
  8. package/dist/core/compaction/compaction.js.map +1 -1
  9. package/dist/core/extensions/index.d.ts +1 -1
  10. package/dist/core/extensions/index.d.ts.map +1 -1
  11. package/dist/core/extensions/index.js.map +1 -1
  12. package/dist/core/extensions/loader.d.ts.map +1 -1
  13. package/dist/core/extensions/loader.js +13 -1
  14. package/dist/core/extensions/loader.js.map +1 -1
  15. package/dist/core/extensions/runner.d.ts.map +1 -1
  16. package/dist/core/extensions/runner.js +47 -48
  17. package/dist/core/extensions/runner.js.map +1 -1
  18. package/dist/core/extensions/types.d.ts +46 -43
  19. package/dist/core/extensions/types.d.ts.map +1 -1
  20. package/dist/core/extensions/types.js.map +1 -1
  21. package/dist/core/keybindings.d.ts +10 -0
  22. package/dist/core/keybindings.d.ts.map +1 -1
  23. package/dist/core/keybindings.js +13 -0
  24. package/dist/core/keybindings.js.map +1 -1
  25. package/dist/core/tools/bash.d.ts +3 -1
  26. package/dist/core/tools/bash.d.ts.map +1 -1
  27. package/dist/core/tools/bash.js +61 -8
  28. package/dist/core/tools/bash.js.map +1 -1
  29. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  30. package/dist/core/tools/renderers/bash.js +43 -6
  31. package/dist/core/tools/renderers/bash.js.map +1 -1
  32. package/dist/dal/builtins.d.ts.map +1 -1
  33. package/dist/dal/builtins.js +1 -0
  34. package/dist/dal/builtins.js.map +1 -1
  35. package/dist/index.d.ts +1 -1
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/main.d.ts.map +1 -1
  39. package/dist/main.js +6 -0
  40. package/dist/main.js.map +1 -1
  41. package/dist/modes/interactive/components/assistant-message.d.ts +12 -0
  42. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  43. package/dist/modes/interactive/components/assistant-message.js +22 -1
  44. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  45. package/dist/modes/interactive/components/footer.d.ts +2 -0
  46. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  47. package/dist/modes/interactive/components/footer.js +24 -7
  48. package/dist/modes/interactive/components/footer.js.map +1 -1
  49. package/dist/modes/interactive/components/tool-execution.d.ts +39 -2
  50. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  51. package/dist/modes/interactive/components/tool-execution.js +200 -29
  52. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  53. package/dist/modes/interactive/interactive-mode.d.ts +35 -0
  54. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  55. package/dist/modes/interactive/interactive-mode.js +177 -23
  56. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  57. package/dist/modes/interactive/theme/dark.json +1 -1
  58. package/dist/modes/interactive/theme/light.json +1 -1
  59. package/dist/modes/interactive/tui-renderer.d.ts.map +1 -1
  60. package/dist/modes/interactive/tui-renderer.js +2 -2
  61. package/dist/modes/interactive/tui-renderer.js.map +1 -1
  62. package/dist/node_modules/@dalcode/dal-bridge/package.json +3 -3
  63. package/dist/node_modules/@dalcode/dal-gateway/package.json +3 -3
  64. package/dist/node_modules/@dalcode/dal-guard/package.json +5 -5
  65. package/dist/node_modules/@dalcode/dal-halo/package.json +2 -2
  66. package/dist/node_modules/@dalcode/dal-lang/package.json +4 -4
  67. package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
  68. package/dist/node_modules/@dalcode/dal-mcp/package.json +9 -6
  69. package/dist/node_modules/@dalcode/dal-mcp/src/add-wizard.ts +142 -0
  70. package/dist/node_modules/@dalcode/dal-mcp/src/command-parser.ts +218 -0
  71. package/dist/node_modules/@dalcode/dal-mcp/src/config-edit.ts +99 -0
  72. package/dist/node_modules/@dalcode/dal-mcp/src/index.ts +161 -18
  73. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.ts +8 -3
  74. package/dist/node_modules/@dalcode/dal-office/LICENSE +21 -0
  75. package/dist/node_modules/@dalcode/dal-office/package.json +37 -0
  76. package/dist/node_modules/@dalcode/dal-office/src/extract/csv.ts +84 -0
  77. package/dist/node_modules/@dalcode/dal-office/src/extract/index.ts +111 -0
  78. package/dist/node_modules/@dalcode/dal-office/src/extract/ooxml.ts +109 -0
  79. package/dist/node_modules/@dalcode/dal-office/src/extract/pdf.ts +43 -0
  80. package/dist/node_modules/@dalcode/dal-office/src/index.ts +43 -0
  81. package/dist/node_modules/@dalcode/dal-office/src/paths.ts +107 -0
  82. package/dist/node_modules/@dalcode/dal-office/src/render/chart.ts +111 -0
  83. package/dist/node_modules/@dalcode/dal-office/src/render/docx.ts +155 -0
  84. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.ts +386 -0
  85. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.ts +99 -0
  86. package/dist/node_modules/@dalcode/dal-office/src/scenes.ts +197 -0
  87. package/dist/node_modules/@dalcode/dal-office/src/scratchpad.ts +49 -0
  88. package/dist/node_modules/@dalcode/dal-office/src/themes.ts +240 -0
  89. package/dist/node_modules/@dalcode/dal-office/src/tools/chart-generate.ts +122 -0
  90. package/dist/node_modules/@dalcode/dal-office/src/tools/doc-generate.ts +123 -0
  91. package/dist/node_modules/@dalcode/dal-office/src/tools/drawio-generate.ts +99 -0
  92. package/dist/node_modules/@dalcode/dal-office/src/tools/md-generate.ts +76 -0
  93. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.ts +106 -0
  94. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-plan.ts +91 -0
  95. package/dist/node_modules/@dalcode/dal-office/src/tools/read-file.ts +71 -0
  96. package/dist/node_modules/@dalcode/dal-office/src/tools/shared.ts +54 -0
  97. package/dist/node_modules/@dalcode/dal-office/src/tools/sheet-generate.ts +101 -0
  98. package/dist/node_modules/@dalcode/dal-office/src/truncate.ts +27 -0
  99. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.d.ts.map +1 -1
  100. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +233 -1
  101. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js.map +1 -1
  102. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  103. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.ts +322 -1
  104. package/dist/node_modules/@dalcode/dal-skills/package.json +4 -4
  105. package/dist/node_modules/@dalcode/dal-skills/src/discover.ts +101 -0
  106. package/dist/node_modules/@dalcode/dal-skills/src/index.ts +71 -9
  107. package/dist/node_modules/@dalcode/dal-skills/src/install.ts +140 -0
  108. package/dist/node_modules/@dalcode/dal-skills/src/manage.ts +446 -0
  109. package/dist/node_modules/@dalcode/dal-skills/src/packages.ts +39 -1
  110. package/dist/node_modules/@dalcode/dal-subagent/package.json +6 -6
  111. package/dist/node_modules/@dalcode/dal-subagent/src/index.ts +46 -4
  112. package/dist/node_modules/@dalcode/dal-telemetry/package.json +3 -3
  113. package/dist/node_modules/@dalcode/deepailab/package.json +4 -4
  114. package/dist/node_modules/@dalcode/deepailab/src/index.ts +7 -1
  115. package/dist/node_modules/@dalcode/deepailab/src/model-defaults.ts +42 -6
  116. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  117. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  118. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  119. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  120. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  121. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/kimi-coding.json +1 -1
  122. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  123. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  124. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  125. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  126. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
  127. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
  128. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  129. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  130. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  131. package/dist/node_modules/@earendil-works/pi-client/package.json +2 -2
  132. package/dist/node_modules/@earendil-works/pi-protocol/package.json +1 -1
  133. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  134. package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.d.ts.map +1 -1
  135. package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +3 -1
  136. package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.js.map +1 -1
  137. package/dist/node_modules/@earendil-works/pi-tui/dist/components/input.d.ts.map +1 -1
  138. package/dist/node_modules/@earendil-works/pi-tui/dist/components/input.js +3 -1
  139. package/dist/node_modules/@earendil-works/pi-tui/dist/components/input.js.map +1 -1
  140. package/dist/node_modules/@earendil-works/pi-tui/dist/fuzzy.d.ts.map +1 -1
  141. package/dist/node_modules/@earendil-works/pi-tui/dist/fuzzy.js +23 -22
  142. package/dist/node_modules/@earendil-works/pi-tui/dist/fuzzy.js.map +1 -1
  143. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts +4 -3
  144. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts.map +1 -1
  145. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +4 -2
  146. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js.map +1 -1
  147. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  148. package/dist/utils/changelog.d.ts +37 -4
  149. package/dist/utils/changelog.d.ts.map +1 -1
  150. package/dist/utils/changelog.js +80 -17
  151. package/dist/utils/changelog.js.map +1 -1
  152. package/dist/utils/clipboard.d.ts.map +1 -1
  153. package/dist/utils/clipboard.js +13 -1
  154. package/dist/utils/clipboard.js.map +1 -1
  155. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  156. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  157. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  158. package/examples/extensions/gondolin/package-lock.json +2 -2
  159. package/examples/extensions/gondolin/package.json +1 -1
  160. package/examples/extensions/sandbox/package-lock.json +2 -2
  161. package/examples/extensions/sandbox/package.json +1 -1
  162. package/examples/extensions/with-deps/package-lock.json +2 -2
  163. package/examples/extensions/with-deps/package.json +1 -1
  164. package/examples/plugins/pi-example-plugin/package.json +1 -1
  165. package/npm-shrinkwrap.json +1511 -25
  166. package/package.json +8 -2
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Editing MCP config files on disk — the write side of config.ts.
3
+ *
4
+ * Both scopes share the `{ "mcpServers": { ... } }` JSON shape: user
5
+ * (`~/.dal/agent/mcp.json`) and project (`<cwd>/.dal/mcp.json`). Writes only
6
+ * touch the named entry and preserve every other key in the file; a file that
7
+ * fails to parse is never rewritten, so one bad comma cannot nuke a hand-edited
8
+ * config. Writes go through a temp file + rename (two concurrent sessions
9
+ * interleaving plain writes would produce truncated JSON, same argument as
10
+ * dal-telemetry's writeState).
11
+ */
12
+
13
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import { t } from "@dalcode/dal-pi-kit";
16
+ import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
17
+ import type { McpServerConfig } from "./types.ts";
18
+
19
+ export type McpConfigScope = "user" | "project";
20
+
21
+ export function mcpConfigPath(scope: McpConfigScope, cwd: string): string {
22
+ return scope === "user" ? join(getAgentDir(), "mcp.json") : join(cwd, CONFIG_DIR_NAME, "mcp.json");
23
+ }
24
+
25
+ interface McpConfigFile {
26
+ mcpServers?: Record<string, unknown>;
27
+ [key: string]: unknown;
28
+ }
29
+
30
+ function isStringKeyedRecord(value: unknown): value is Record<string, unknown> {
31
+ return typeof value === "object" && value !== null && !Array.isArray(value);
32
+ }
33
+
34
+ /** JSON.parse rejects a leading BOM, which Windows editors like to add. */
35
+ function stripBom(text: string): string {
36
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
37
+ }
38
+
39
+ function readConfigFile(path: string): { file: McpConfigFile; existed: boolean } {
40
+ if (!existsSync(path)) return { file: {}, existed: false };
41
+ let parsed: unknown;
42
+ try {
43
+ parsed = JSON.parse(stripBom(readFileSync(path, "utf8")));
44
+ } catch (error) {
45
+ const reason = error instanceof Error ? error.message : String(error);
46
+ throw new Error(`${path}: ${t("JSON 解析失败,拒绝修改以避免覆盖现有配置。")}${reason}`);
47
+ }
48
+ if (!isStringKeyedRecord(parsed)) throw new Error(`${path}: ${t("顶层不是 JSON 对象,拒绝修改。")}`);
49
+ return { file: parsed as McpConfigFile, existed: true };
50
+ }
51
+
52
+ function writeConfigFile(path: string, file: McpConfigFile): void {
53
+ mkdirSync(dirname(path), { recursive: true });
54
+ const temp = `${path}.${process.pid}.tmp`;
55
+ writeFileSync(temp, `${JSON.stringify(file, null, 2)}\n`, "utf-8");
56
+ renameSync(temp, path);
57
+ }
58
+
59
+ /**
60
+ * Adds (or replaces — callers gate on "already exists" first) one server entry.
61
+ * Throws when the name already exists, mirroring `claude mcp add`: changing a
62
+ * server is remove-then-add, never a silent overwrite.
63
+ */
64
+ export function addMcpServerEntry(
65
+ scope: McpConfigScope,
66
+ cwd: string,
67
+ name: string,
68
+ config: McpServerConfig,
69
+ ): { path: string; created: boolean } {
70
+ const path = mcpConfigPath(scope, cwd);
71
+ const { file, existed } = readConfigFile(path);
72
+ if (file.mcpServers === undefined) file.mcpServers = {};
73
+ const servers = file.mcpServers;
74
+ if (!isStringKeyedRecord(servers)) {
75
+ throw new Error(`${path}: ${t('"mcpServers" 不是对象,拒绝修改。')}`);
76
+ }
77
+ if (name in servers) {
78
+ throw new Error(`${t("该名称已存在于 ")}${path}${t(":")}${name}${t("。先 /mcp remove,或直接编辑该文件。")}`);
79
+ }
80
+ servers[name] = config;
81
+ writeConfigFile(path, file);
82
+ return { path, created: !existed };
83
+ }
84
+
85
+ /** Deletes one entry; a missing file or missing name is a no-op, not an error. */
86
+ export function removeMcpServerEntry(
87
+ scope: McpConfigScope,
88
+ cwd: string,
89
+ name: string,
90
+ ): { path: string; removed: boolean } {
91
+ const path = mcpConfigPath(scope, cwd);
92
+ if (!existsSync(path)) return { path, removed: false };
93
+ const { file } = readConfigFile(path);
94
+ const servers = file.mcpServers;
95
+ if (!isStringKeyedRecord(servers) || !(name in servers)) return { path, removed: false };
96
+ delete servers[name];
97
+ writeConfigFile(path, file);
98
+ return { path, removed: true };
99
+ }
@@ -19,7 +19,17 @@ import { t } from "@dalcode/dal-pi-kit";
19
19
  import { defaultConfig } from "@dalcode/deepailab/oidc";
20
20
  import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
21
21
  import { fetchAccountMcpServers } from "./account-layer.ts";
22
+ import { runAddWizard } from "./add-wizard.ts";
23
+ import {
24
+ ADD_USAGE,
25
+ parseAddArgs,
26
+ parseRemoveArgs,
27
+ REMOVE_USAGE,
28
+ tokenizeCommandArgs,
29
+ UsageError,
30
+ } from "./command-parser.ts";
22
31
  import { loadMcpServerConfigs, takeMcpConfigProblems } from "./config.ts";
32
+ import { addMcpServerEntry, type McpConfigScope, removeMcpServerEntry } from "./config-edit.ts";
23
33
  import { McpHttpClient } from "./http-client.ts";
24
34
  import { type McpStatusItem, rememberMcpSessionId, reportMcpStatus } from "./report.ts";
25
35
  import { McpStdioClient } from "./stdio-client.ts";
@@ -194,22 +204,34 @@ function statusLabel(status: McpServerStatus): string {
194
204
  return t("已断开");
195
205
  }
196
206
 
207
+ function configCommandLine(config: McpServerConfig): string {
208
+ return isHttpMcpConfig(config) ? config.url : [config.command, ...(config.args ?? [])].join(" ");
209
+ }
210
+
211
+ /** Expanded view: one block per server — status, transport, command line, tool names, last error. */
197
212
  function mcpList(ctx: ExtensionContext): void {
198
213
  const states = getMcpServerStates();
199
214
  if (states.length === 0) {
200
215
  ctx.ui.notify(t("未配置 MCP 服务器。在 .dal/mcp.json 或 ~/.dal/agent/mcp.json 中添加。"), "info");
201
216
  return;
202
217
  }
203
- const lines = states.map((state) => {
204
- const suffix =
218
+ const blocks = states.map((state) => {
219
+ const source = isHttpMcpConfig(state.config) ? "http" : "stdio";
220
+ const meta =
205
221
  state.status === "connected"
206
- ? `${t("(")}${state.tools.length}${t(" 个工具)")}`
207
- : state.lastError
208
- ? ` — ${state.lastError}`
209
- : "";
210
- return `${state.name}: ${statusLabel(state.status)}${suffix}`;
222
+ ? `${t("(")}${source}${t(",")}${state.tools.length}${t(" 个工具)")}`
223
+ : `${t("(")}${source}${t(")")}`;
224
+ const lines = [
225
+ `${state.name} — ${statusLabel(state.status)}${meta}`,
226
+ ` ${t("命令:")}${configCommandLine(state.config)}`,
227
+ ];
228
+ if (state.tools.length > 0) {
229
+ lines.push(` ${t("工具:")}${state.tools.map((tool) => tool.name).join(", ")}`);
230
+ }
231
+ if (state.lastError) lines.push(` ${t("最近错误:")}${state.lastError}`);
232
+ return lines.join("\n");
211
233
  });
212
- ctx.ui.notify(lines.join("\n"), "info");
234
+ ctx.ui.notify(`${t("MCP 服务器(")}${states.length}${t("):")}\n\n${blocks.join("\n\n")}`, "info");
213
235
  }
214
236
 
215
237
  function mcpStatus(serverName: string, ctx: ExtensionContext): void {
@@ -223,12 +245,9 @@ function mcpStatus(serverName: string, ctx: ExtensionContext): void {
223
245
  return;
224
246
  }
225
247
  const toolNames = state.tools.map((tool) => tool.name).join(", ") || t("(无)");
226
- const commandLine = isHttpMcpConfig(state.config)
227
- ? state.config.url
228
- : [state.config.command, ...(state.config.args ?? [])].join(" ");
229
248
  const parts = [
230
249
  `${state.name} — ${statusLabel(state.status)}`,
231
- `${t("命令:")}${commandLine}`,
250
+ `${t("命令:")}${configCommandLine(state.config)}`,
232
251
  `${t("工具:")}${toolNames}`,
233
252
  ];
234
253
  if (state.lastError) parts.push(`${t("最近错误:")}${state.lastError}`);
@@ -255,6 +274,101 @@ async function mcpReconnect(pi: ExtensionAPI, serverName: string, ctx: Extension
255
274
  }
256
275
  }
257
276
 
277
+ /**
278
+ * Persists the entry, then connects immediately so its tools are usable in
279
+ * this session. A connect failure still keeps the saved config: the entry
280
+ * shows up as 连接失败 in /mcp list, and /mcp reconnect picks it up.
281
+ */
282
+ async function applyAdd(
283
+ pi: ExtensionAPI,
284
+ name: string,
285
+ scope: McpConfigScope,
286
+ config: McpServerConfig,
287
+ ctx: ExtensionContext,
288
+ ): Promise<void> {
289
+ if (scope === "project" && !ctx.isProjectTrusted()) {
290
+ ctx.ui.notify(t("项目未受信任,无法写入项目级 .dal/mcp.json。先运行 /trust 保存信任决策,再重试。"), "warning");
291
+ return;
292
+ }
293
+ let path: string;
294
+ try {
295
+ ({ path } = addMcpServerEntry(scope, ctx.cwd, name, config));
296
+ } catch (error) {
297
+ ctx.ui.notify(errorMessage(error), "error");
298
+ return;
299
+ }
300
+ try {
301
+ const state = await connectServer(pi, name, config, ctx.cwd);
302
+ ctx.ui.notify(
303
+ `${t("已添加 MCP 服务器:")}${name}${t("(")}${scope}${t(",")}${state.tools.length}${t(" 个工具)")}`,
304
+ "info",
305
+ );
306
+ } catch (error) {
307
+ ctx.ui.notify(`${t("已保存到 ")}${path}${t(",但连接失败:")}${errorMessage(error)}`, "warning");
308
+ }
309
+ }
310
+
311
+ async function mcpAdd(pi: ExtensionAPI, tokens: string[], ctx: ExtensionContext): Promise<void> {
312
+ if (tokens.length === 0) {
313
+ if (!ctx.hasUI) {
314
+ ctx.ui.notify(`${ADD_USAGE}`, "info");
315
+ return;
316
+ }
317
+ const spec = await runAddWizard(ctx.ui, ctx.cwd);
318
+ if (!spec) return;
319
+ await applyAdd(pi, spec.name, spec.scope, spec.config, ctx);
320
+ return;
321
+ }
322
+ try {
323
+ const spec = parseAddArgs(tokens);
324
+ await applyAdd(pi, spec.name, spec.scope, spec.config, ctx);
325
+ } catch (error) {
326
+ if (error instanceof UsageError) ctx.ui.notify(error.message, "info");
327
+ else ctx.ui.notify(`${t("添加失败:")}${errorMessage(error)}`, "error");
328
+ }
329
+ }
330
+
331
+ function mcpRemove(tokens: string[], ctx: ExtensionContext): void {
332
+ let spec: ReturnType<typeof parseRemoveArgs>;
333
+ try {
334
+ spec = parseRemoveArgs(tokens);
335
+ } catch (error) {
336
+ if (error instanceof UsageError) ctx.ui.notify(error.message, "info");
337
+ else ctx.ui.notify(errorMessage(error), "error");
338
+ return;
339
+ }
340
+ // Highest priority first: removing "the" server means removing the entry
341
+ // that actually wins the config merge. `--scope` pins it.
342
+ const order: McpConfigScope[] = spec.scope ? [spec.scope] : ["project", "user"];
343
+ try {
344
+ for (const scope of order) {
345
+ if (scope === "project" && !ctx.isProjectTrusted()) continue;
346
+ const { path, removed } = removeMcpServerEntry(scope, ctx.cwd, spec.name);
347
+ if (!removed) continue;
348
+ const state = registry.get(spec.name);
349
+ if (state) {
350
+ state.client?.disconnect();
351
+ registry.delete(spec.name);
352
+ pushMcpStatus();
353
+ }
354
+ ctx.ui.notify(
355
+ `${t("已从 ")}${path}${t(" 移除 MCP 服务器:")}${spec.name}${
356
+ state ? t("。连接已断开,其工具将在重启会话后消失。") : ""
357
+ }`,
358
+ "info",
359
+ );
360
+ return;
361
+ }
362
+ } catch (error) {
363
+ ctx.ui.notify(errorMessage(error), "error");
364
+ return;
365
+ }
366
+ ctx.ui.notify(
367
+ `${t("未找到本地配置条目:")}${spec.name}${t("。账号下发的服务器不可删除,可在用户级 mcp.json 写入 disabled: true 屏蔽。")}`,
368
+ "warning",
369
+ );
370
+ }
371
+
258
372
  /**
259
373
  * hasUI, not `ui`. A headless run still gets a real `ui` object whose notify
260
374
  * does nothing, so a truthiness check would drop the message in `dal -p` — the
@@ -309,24 +423,53 @@ export default function (pi: ExtensionAPI) {
309
423
  });
310
424
 
311
425
  pi.registerCommand("mcp", {
312
- description: t("查看/管理 MCP 服务器连接(list | status <server> | reconnect <server>)"),
426
+ description: t("查看/管理 MCP 服务器连接(list | add | remove | status <server> | reconnect <server>)"),
427
+ getArgumentCompletions: (prefix: string) => {
428
+ const trimmed = prefix.trimStart();
429
+ const spaceIndex = trimmed.indexOf(" ");
430
+ if (spaceIndex === -1) {
431
+ const subcommands = ["list", "add", "remove", "status", "reconnect"];
432
+ return subcommands
433
+ .filter((sub) => sub.startsWith(trimmed))
434
+ .map((sub) => ({ value: `${sub} `, label: sub }));
435
+ }
436
+ const sub = trimmed.slice(0, spaceIndex);
437
+ const rest = trimmed.slice(spaceIndex + 1);
438
+ if ((sub === "status" || sub === "reconnect" || sub === "remove") && !rest.includes(" ")) {
439
+ return getMcpServerStates()
440
+ .filter((state) => state.name.startsWith(rest))
441
+ .map((state) => ({ value: `${sub} ${state.name}`, label: state.name }));
442
+ }
443
+ return null;
444
+ },
313
445
  handler: async (args: string, ctx: ExtensionContext) => {
314
- const [sub, ...rest] = args.trim().split(/\s+/).filter(Boolean);
315
- const target = rest.join(" ");
446
+ const tokens = tokenizeCommandArgs(args);
447
+ const sub = tokens.shift();
448
+ const rest = tokens.join(" ");
316
449
  switch (sub) {
317
450
  case undefined:
318
451
  case "":
319
452
  case "list":
320
453
  mcpList(ctx);
321
454
  return;
455
+ case "add":
456
+ await mcpAdd(pi, tokens, ctx);
457
+ return;
458
+ case "remove":
459
+ case "rm":
460
+ mcpRemove(tokens, ctx);
461
+ return;
322
462
  case "status":
323
- mcpStatus(target, ctx);
463
+ mcpStatus(rest, ctx);
324
464
  return;
325
465
  case "reconnect":
326
- await mcpReconnect(pi, target, ctx);
466
+ await mcpReconnect(pi, rest, ctx);
327
467
  return;
328
468
  default:
329
- ctx.ui.notify(t("用法:/mcp list | /mcp status <server> | /mcp reconnect <server>"), "info");
469
+ ctx.ui.notify(
470
+ `${t("用法:/mcp list | /mcp add | /mcp remove <name> | /mcp status <server> | /mcp reconnect <server>")}\n${ADD_USAGE}\n${REMOVE_USAGE}`,
471
+ "info",
472
+ );
330
473
  }
331
474
  },
332
475
  });
@@ -7,7 +7,8 @@
7
7
  * transport, no resources/prompts/sampling — YAGNI beyond tool calls.
8
8
  */
9
9
 
10
- import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
10
+ import type { ChildProcessWithoutNullStreams } from "node:child_process";
11
+ import crossSpawn from "cross-spawn";
11
12
  import type { McpClient, McpStdioServerConfig, McpTool, McpToolCallResult } from "./types.ts";
12
13
 
13
14
  export type { McpStdioServerConfig, McpTool, McpToolCallResult } from "./types.ts";
@@ -48,11 +49,15 @@ export class McpStdioClient implements McpClient {
48
49
  }
49
50
 
50
51
  async connect(): Promise<void> {
51
- const child = spawn(this.config.command, this.config.args ?? [], {
52
+ // cross-spawn, not node's spawn: on Windows npx/npm/pnpm are .cmd shims
53
+ // and Node ≥18.20 refuses to spawn those without a shell (ENOENT/EINVAL),
54
+ // which took down every npx-based server including the chrome-devtools
55
+ // default. Same fix dal-lsp's client already carries.
56
+ const child = crossSpawn(this.config.command, this.config.args ?? [], {
52
57
  cwd: this.config.cwd,
53
58
  env: { ...process.env, ...this.config.env },
54
59
  stdio: ["pipe", "pipe", "pipe"],
55
- });
60
+ }) as ChildProcessWithoutNullStreams;
56
61
  this.child = child;
57
62
  // Don't let the MCP server child process keep the host CLI's event
58
63
  // loop alive — a one-shot `-p` run must be able to exit once its
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Mario Zechner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@dalcode/dal-office",
3
+ "version": "1.0.7",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "exports": {
8
+ ".": "./src/index.ts",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "pi": {
15
+ "extensions": [
16
+ "./src/index.ts"
17
+ ]
18
+ },
19
+ "dependencies": {
20
+ "@dalcode/dal-pi-kit": "1.0.7",
21
+ "docx": "9.7.1",
22
+ "echarts": "6.1.0",
23
+ "exceljs": "4.4.0",
24
+ "jszip": "3.10.2",
25
+ "pdfjs-dist": "6.3.289",
26
+ "pptxgenjs": "4.0.1",
27
+ "typebox": "1.3.7"
28
+ },
29
+ "peerDependencies": {
30
+ "@earendil-works/pi-coding-agent": "^1.0.0"
31
+ },
32
+ "peerDependenciesMeta": {
33
+ "@earendil-works/pi-coding-agent": {
34
+ "optional": false
35
+ }
36
+ }
37
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Minimal CSV/TSV reader for office_read_file.
3
+ *
4
+ * Handles quoted fields with doubled-quote escapes; output is re-emitted as
5
+ * aligned TSV so the model sees columns without parsing the original dialect.
6
+ */
7
+
8
+ export function detectDelimiter(text: string): string {
9
+ const firstLine = text.split(/\r?\n/, 1)[0] ?? "";
10
+ const tabs = (firstLine.match(/\t/g) ?? []).length;
11
+ const commas = (firstLine.match(/,/g) ?? []).length;
12
+ return tabs > commas ? "\t" : ",";
13
+ }
14
+
15
+ /** Parses delimited text into rows (quoted fields supported). */
16
+ export function parseDelimited(text: string, delimiter: string): string[][] {
17
+ const rows: string[][] = [];
18
+ let row: string[] = [];
19
+ let field = "";
20
+ let inQuotes = false;
21
+
22
+ const pushField = (): void => {
23
+ row.push(field);
24
+ field = "";
25
+ };
26
+ const pushRow = (): void => {
27
+ pushField();
28
+ rows.push(row);
29
+ row = [];
30
+ };
31
+
32
+ for (let index = 0; index < text.length; index++) {
33
+ const char = text[index];
34
+ if (inQuotes) {
35
+ if (char === '"') {
36
+ if (text[index + 1] === '"') {
37
+ field += '"';
38
+ index++;
39
+ } else {
40
+ inQuotes = false;
41
+ }
42
+ } else {
43
+ field += char;
44
+ }
45
+ continue;
46
+ }
47
+ if (char === '"') {
48
+ inQuotes = true;
49
+ } else if (char === delimiter) {
50
+ pushField();
51
+ } else if (char === "\n") {
52
+ pushRow();
53
+ } else if (char === "\r") {
54
+ // skip; \n handles the row break
55
+ } else {
56
+ field += char;
57
+ }
58
+ }
59
+ if (field.length > 0 || row.length > 0) {
60
+ pushRow();
61
+ }
62
+ return rows.filter((r) => r.some((cell) => cell.trim().length > 0));
63
+ }
64
+
65
+ /** Formats rows as width-aligned plain text (columns capped at 28 chars). */
66
+ export function formatAligned(rows: string[][]): string {
67
+ const width = Math.max(...rows.map((row) => row.length));
68
+ const colWidths: number[] = [];
69
+ for (let col = 0; col < width; col++) {
70
+ let max = 0;
71
+ for (const row of rows) {
72
+ max = Math.max(max, (row[col] ?? "").length);
73
+ }
74
+ colWidths.push(Math.min(Math.max(max, 4), 28));
75
+ }
76
+ return rows
77
+ .map((row) =>
78
+ row
79
+ .map((cell, col) => (cell ?? "").slice(0, 28).padEnd(colWidths[col]))
80
+ .join(" ")
81
+ .trimEnd(),
82
+ )
83
+ .join("\n");
84
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * office_read_file dispatcher: routes a file path to the right text extractor.
3
+ *
4
+ * Supported: .docx / .pptx / .xlsx / .pdf / .csv / .tsv / plain text
5
+ * (.txt, .md and any other text-ish extension). Anything else is rejected
6
+ * with the supported list so the model can correct course.
7
+ */
8
+
9
+ import { readFile } from "node:fs/promises";
10
+ import { extname } from "node:path";
11
+ import { t } from "@dalcode/dal-pi-kit";
12
+ import ExcelJS from "exceljs";
13
+ import { detectDelimiter, formatAligned, parseDelimited } from "./csv.ts";
14
+ import { extractDocx, extractPptx } from "./ooxml.ts";
15
+ import { extractPdf } from "./pdf.ts";
16
+
17
+ export interface OfficeTextExtraction {
18
+ parser: string;
19
+ meta: string;
20
+ text: string;
21
+ }
22
+
23
+ const OFFICE_EXTENSIONS = [".docx", ".pptx", ".xlsx", ".pdf", ".csv", ".tsv"] as const;
24
+
25
+ function unsupportedType(extension: string): Error {
26
+ const supported = `${t("支持的格式:")}${OFFICE_EXTENSIONS.join(" / ")}${t(",以及 .txt/.md 等纯文本")}`;
27
+ return new Error(`${t("暂不支持的文件类型:")}${extension}。${supported}`);
28
+ }
29
+
30
+ function isCellValueObject(value: unknown): value is Record<string, unknown> {
31
+ return typeof value === "object" && value !== null;
32
+ }
33
+
34
+ /** Normalizes an exceljs cell value (string/number/formula/rich text/date) to plain text. */
35
+ export function cellToText(value: unknown): string {
36
+ if (value === null || value === undefined) return "";
37
+ if (typeof value === "string") return value;
38
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
39
+ if (value instanceof Date) return value.toISOString();
40
+ if (isCellValueObject(value)) {
41
+ if (Array.isArray(value.richText)) {
42
+ return value.richText.map((part) => cellToText((part as { text?: unknown }).text)).join("");
43
+ }
44
+ if ("result" in value) return cellToText(value.result);
45
+ if ("text" in value) return cellToText(value.text);
46
+ if ("error" in value) return "";
47
+ }
48
+ return String(value);
49
+ }
50
+
51
+ /** xlsx: every worksheet flattened to aligned text with sheet separators. */
52
+ async function extractXlsx(buffer: Buffer): Promise<OfficeTextExtraction> {
53
+ const workbook = new ExcelJS.Workbook();
54
+ await workbook.xlsx.load(buffer as unknown as ArrayBuffer);
55
+ const chunks: string[] = [];
56
+ let rowCount = 0;
57
+ workbook.eachSheet((sheet) => {
58
+ chunks.push(`=== ${sheet.name} ===`);
59
+ sheet.eachRow((row) => {
60
+ const cells: string[] = [];
61
+ row.eachCell({ includeEmpty: false }, (cell) => {
62
+ cells.push(cellToText(cell.value));
63
+ });
64
+ if (cells.some((cell) => cell.trim().length > 0)) {
65
+ rowCount++;
66
+ chunks.push(cells.join("\t"));
67
+ }
68
+ });
69
+ });
70
+ return { parser: "xlsx", meta: `${workbook.worksheets.length} sheets / ${rowCount} rows`, text: chunks.join("\n") };
71
+ }
72
+
73
+ export async function extractOfficeText(filePath: string): Promise<OfficeTextExtraction> {
74
+ const extension = extname(filePath).toLowerCase();
75
+ switch (extension) {
76
+ case ".docx": {
77
+ const { text, meta } = await extractDocx(await readFile(filePath));
78
+ return { parser: "docx", meta, text };
79
+ }
80
+ case ".pptx": {
81
+ const { text, meta } = await extractPptx(await readFile(filePath));
82
+ return { parser: "pptx", meta, text };
83
+ }
84
+ case ".xlsx":
85
+ return extractXlsx(await readFile(filePath));
86
+ case ".pdf": {
87
+ const { text, meta } = await extractPdf(await readFile(filePath));
88
+ return { parser: "pdf", meta, text };
89
+ }
90
+ case ".csv":
91
+ case ".tsv": {
92
+ const raw = await readFile(filePath, "utf8");
93
+ const rows = parseDelimited(raw, detectDelimiter(raw));
94
+ return {
95
+ parser: extension.slice(1),
96
+ meta: `${rows.length} rows`,
97
+ text: formatAligned(rows),
98
+ };
99
+ }
100
+ case ".txt":
101
+ case ".md":
102
+ case ".markdown":
103
+ case ".text":
104
+ case ".log": {
105
+ const text = await readFile(filePath, "utf8");
106
+ return { parser: "text", meta: `${text.length} chars`, text };
107
+ }
108
+ default:
109
+ throw unsupportedType(extension || filePath);
110
+ }
111
+ }