@uncarved/jade 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/README.md +65 -2
  2. package/assets/logo.svg +1 -0
  3. package/bin/jade.js +4 -0
  4. package/dist/api.d.ts +5 -250
  5. package/dist/api.js +5 -7
  6. package/dist/api.js.map +1 -1
  7. package/dist/fetch.d.ts +8 -0
  8. package/dist/fetch.js +19 -17
  9. package/dist/fetch.js.map +1 -1
  10. package/dist/host.d.ts +12 -1
  11. package/dist/host.js +49 -1
  12. package/dist/host.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/main.js +26 -4
  17. package/dist/main.js.map +1 -1
  18. package/dist/remote.js +4 -0
  19. package/dist/remote.js.map +1 -1
  20. package/dist/session.d.ts +2 -0
  21. package/dist/session.js +133 -13
  22. package/dist/session.js.map +1 -1
  23. package/dist/source.d.ts +2 -10
  24. package/dist/source.js.map +1 -1
  25. package/dist/update.d.ts +8 -20
  26. package/dist/update.js +12 -1
  27. package/dist/update.js.map +1 -1
  28. package/package.json +4 -2
  29. package/plugins/approval/index.ts +236 -85
  30. package/plugins/approval/plugin.json +1 -1
  31. package/plugins/approval/policy.ts +36 -17
  32. package/plugins/approval/review.ts +1 -1
  33. package/plugins/ask/index.ts +2 -2
  34. package/plugins/budget/index.ts +1 -1
  35. package/plugins/checks/checks.ts +3 -2
  36. package/plugins/checks/index.ts +2 -5
  37. package/plugins/commands/index.ts +2 -44
  38. package/plugins/compact/compact.ts +8 -3
  39. package/plugins/compact/index.ts +13 -16
  40. package/plugins/continue/index.ts +1 -1
  41. package/plugins/cost/index.ts +143 -0
  42. package/plugins/cost/plugin.json +13 -0
  43. package/plugins/custom-commands/index.ts +85 -0
  44. package/plugins/custom-commands/plugin.json +8 -0
  45. package/plugins/editor/index.ts +88 -0
  46. package/plugins/editor/plugin.json +17 -0
  47. package/plugins/fs/fs.ts +33 -6
  48. package/plugins/fs/grep.ts +19 -7
  49. package/plugins/fs/index.ts +6 -7
  50. package/plugins/fs/plugin.json +1 -1
  51. package/plugins/fs/renderers.ts +1 -1
  52. package/plugins/hooks/index.ts +152 -0
  53. package/plugins/hooks/plugin.json +14 -0
  54. package/plugins/keys/index.ts +2 -18
  55. package/plugins/mcp/index.ts +43 -15
  56. package/plugins/mcp/install.ts +139 -0
  57. package/plugins/mcp/mcp.ts +2 -1
  58. package/plugins/mcp/plugin.json +1 -1
  59. package/plugins/mcp/project.ts +37 -1
  60. package/plugins/memory/index.ts +4 -9
  61. package/plugins/memory/plugin.json +1 -1
  62. package/plugins/mentions/index.ts +2 -2
  63. package/plugins/models/configure.ts +258 -150
  64. package/plugins/models/context.ts +2 -2
  65. package/plugins/models/index.ts +39 -45
  66. package/plugins/models/plugin.json +1 -1
  67. package/plugins/models/provider.ts +34 -5
  68. package/plugins/models/saved.ts +8 -4
  69. package/plugins/modes/index.ts +2 -17
  70. package/plugins/plugins/index.ts +2 -2
  71. package/plugins/print/index.ts +36 -6
  72. package/plugins/print/plugin.json +1 -0
  73. package/plugins/prompts/index.ts +22 -14
  74. package/plugins/{memory → prompts}/notes.ts +21 -9
  75. package/plugins/prompts/plugin.json +8 -2
  76. package/plugins/prompts/prompts.ts +5 -4
  77. package/plugins/renderers/index.ts +2 -43
  78. package/plugins/repeats/index.ts +32 -2
  79. package/plugins/schedule/index.ts +2 -2
  80. package/plugins/scratch/index.ts +2 -3
  81. package/plugins/screenshot/browser.ts +221 -0
  82. package/plugins/screenshot/index.ts +29 -15
  83. package/plugins/screenshot/plugin.json +1 -1
  84. package/plugins/screenshot/tool.ts +27 -51
  85. package/plugins/sessions/index.ts +2 -17
  86. package/plugins/shell/index.ts +115 -7
  87. package/plugins/shell/plugin.json +3 -1
  88. package/plugins/shell/renderers.ts +1 -1
  89. package/plugins/shell/service.ts +2 -13
  90. package/plugins/shell/shell.ts +119 -47
  91. package/plugins/skills/index.ts +172 -37
  92. package/plugins/skills/install.ts +212 -0
  93. package/plugins/skills/plugin.json +3 -2
  94. package/plugins/skills/project.ts +38 -1
  95. package/plugins/skills/skills.ts +28 -9
  96. package/plugins/steer/index.ts +142 -0
  97. package/plugins/steer/plugin.json +8 -0
  98. package/plugins/suggest/index.ts +16 -11
  99. package/plugins/suggest/plugin.json +1 -1
  100. package/plugins/task/index.ts +18 -57
  101. package/plugins/task/plugin.json +9 -3
  102. package/plugins/task/subagent.ts +25 -7
  103. package/plugins/todo/index.ts +2 -2
  104. package/plugins/tools/index.ts +50 -0
  105. package/plugins/tools/plugin.json +7 -0
  106. package/plugins/tui/editor.ts +10 -2
  107. package/plugins/tui/frontend.ts +129 -23
  108. package/plugins/tui/index.ts +3 -8
  109. package/plugins/tui/markdown.ts +51 -6
  110. package/plugins/tui/mascot.ts +506 -0
  111. package/plugins/tui/plugin.json +2 -2
  112. package/plugins/tui/screen.ts +6 -0
  113. package/plugins/tui/transcript.ts +17 -2
  114. package/plugins/tui/tui.ts +344 -97
  115. package/plugins/undo/checkpoint.ts +2 -2
  116. package/plugins/undo/index.ts +84 -26
  117. package/plugins/undo/plugin.json +8 -2
  118. package/plugins/undo/snapshot.ts +129 -0
  119. package/plugins/update/index.ts +11 -15
  120. package/plugins/update/plugin.json +2 -1
  121. package/plugins/web/index.ts +8 -11
  122. package/plugins/web/plugin.json +1 -1
  123. package/plugins/web/renderers.ts +1 -1
  124. package/plugins-dist/approval/index.js +221 -51
  125. package/plugins-dist/approval/plugin.json +1 -1
  126. package/plugins-dist/approval/policy.js +30 -15
  127. package/plugins-dist/ask/index.js +1 -1
  128. package/plugins-dist/budget/index.js +1 -1
  129. package/plugins-dist/checks/checks.js +2 -1
  130. package/plugins-dist/checks/index.js +1 -1
  131. package/plugins-dist/commands/index.js +1 -1
  132. package/plugins-dist/compact/compact.js +6 -1
  133. package/plugins-dist/compact/index.js +12 -8
  134. package/plugins-dist/continue/index.js +1 -1
  135. package/plugins-dist/cost/index.js +135 -0
  136. package/plugins-dist/cost/plugin.json +16 -0
  137. package/plugins-dist/custom-commands/index.js +86 -0
  138. package/plugins-dist/custom-commands/plugin.json +12 -0
  139. package/plugins-dist/editor/index.js +89 -0
  140. package/plugins-dist/editor/plugin.json +21 -0
  141. package/plugins-dist/fs/fs.js +34 -6
  142. package/plugins-dist/fs/grep.js +17 -6
  143. package/plugins-dist/fs/index.js +6 -6
  144. package/plugins-dist/fs/plugin.json +1 -1
  145. package/plugins-dist/hooks/index.js +145 -0
  146. package/plugins-dist/hooks/plugin.json +19 -0
  147. package/plugins-dist/keys/index.js +1 -1
  148. package/plugins-dist/mcp/index.js +45 -13
  149. package/plugins-dist/mcp/install.js +160 -0
  150. package/plugins-dist/mcp/mcp.js +2 -1
  151. package/plugins-dist/mcp/plugin.json +2 -1
  152. package/plugins-dist/mcp/project.js +42 -1
  153. package/plugins-dist/memory/index.js +3 -5
  154. package/plugins-dist/memory/plugin.json +1 -1
  155. package/plugins-dist/mentions/index.js +1 -1
  156. package/plugins-dist/models/configure.js +252 -151
  157. package/plugins-dist/models/context.js +2 -2
  158. package/plugins-dist/models/index.js +41 -17
  159. package/plugins-dist/models/plugin.json +1 -1
  160. package/plugins-dist/models/provider.js +17 -3
  161. package/plugins-dist/models/saved.js +9 -4
  162. package/plugins-dist/modes/index.js +1 -1
  163. package/plugins-dist/plugins/index.js +1 -1
  164. package/plugins-dist/print/index.js +37 -3
  165. package/plugins-dist/print/plugin.json +3 -0
  166. package/plugins-dist/prompts/index.js +22 -3
  167. package/plugins-dist/{memory → prompts}/notes.js +10 -7
  168. package/plugins-dist/prompts/plugin.json +8 -2
  169. package/plugins-dist/prompts/prompts.js +5 -4
  170. package/plugins-dist/renderers/index.js +1 -1
  171. package/plugins-dist/repeats/index.js +28 -2
  172. package/plugins-dist/schedule/index.js +1 -1
  173. package/plugins-dist/scratch/index.js +1 -1
  174. package/plugins-dist/screenshot/browser.js +187 -0
  175. package/plugins-dist/screenshot/index.js +28 -13
  176. package/plugins-dist/screenshot/plugin.json +1 -1
  177. package/plugins-dist/screenshot/tool.js +27 -49
  178. package/plugins-dist/sessions/index.js +1 -1
  179. package/plugins-dist/shell/index.js +119 -4
  180. package/plugins-dist/shell/plugin.json +3 -1
  181. package/plugins-dist/shell/shell.js +106 -36
  182. package/plugins-dist/skills/index.js +184 -35
  183. package/plugins-dist/skills/install.js +178 -0
  184. package/plugins-dist/skills/plugin.json +6 -2
  185. package/plugins-dist/skills/project.js +43 -1
  186. package/plugins-dist/skills/skills.js +27 -10
  187. package/plugins-dist/steer/index.js +135 -0
  188. package/plugins-dist/steer/plugin.json +12 -0
  189. package/plugins-dist/suggest/index.js +15 -9
  190. package/plugins-dist/suggest/plugin.json +1 -1
  191. package/plugins-dist/task/index.js +17 -46
  192. package/plugins-dist/task/plugin.json +11 -5
  193. package/plugins-dist/task/subagent.js +21 -6
  194. package/plugins-dist/todo/index.js +1 -1
  195. package/plugins-dist/tools/index.js +49 -0
  196. package/plugins-dist/tools/plugin.json +9 -0
  197. package/plugins-dist/tui/editor.js +7 -2
  198. package/plugins-dist/tui/frontend.js +134 -15
  199. package/plugins-dist/tui/index.js +2 -1
  200. package/plugins-dist/tui/markdown.js +48 -6
  201. package/plugins-dist/tui/mascot.js +441 -0
  202. package/plugins-dist/tui/plugin.json +3 -2
  203. package/plugins-dist/tui/screen.js +2 -0
  204. package/plugins-dist/tui/transcript.js +16 -1
  205. package/plugins-dist/tui/tui.js +320 -88
  206. package/plugins-dist/tui/vendor.js +1388 -1088
  207. package/plugins-dist/undo/checkpoint.js +1 -1
  208. package/plugins-dist/undo/index.js +91 -24
  209. package/plugins-dist/undo/plugin.json +10 -3
  210. package/plugins-dist/undo/snapshot.js +111 -0
  211. package/plugins-dist/update/index.js +9 -10
  212. package/plugins-dist/update/plugin.json +4 -1
  213. package/plugins-dist/web/index.js +7 -7
  214. package/plugins-dist/web/plugin.json +1 -1
  215. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  216. package/sdk/python/jade_plugin.py +8 -0
  217. package/src/api.ts +7 -262
  218. package/src/fetch.ts +18 -16
  219. package/src/host.ts +49 -1
  220. package/src/index.ts +1 -1
  221. package/src/main.ts +23 -5
  222. package/src/remote.ts +2 -0
  223. package/src/session.ts +134 -15
  224. package/src/source.ts +2 -11
  225. package/src/update.ts +16 -10
  226. package/plugins/undo/notes.ts +0 -43
  227. package/plugins-dist/undo/notes.js +0 -36
@@ -0,0 +1,145 @@
1
+ // jade/hooks:不写插件,在配置里写几条 shell 命令,就能在工具调用前后、一轮结束时做点事。
2
+ //
3
+ // $JADE_HOME/config.json(项目层的配置设不了这一项:克隆的仓库不能让你的机器跑命令):
4
+ //
5
+ // { "jade/hooks": { "hooks": [
6
+ // { "on": "before", "tool": "bash", "command": "python ~/.jade/guard.py" },
7
+ // { "on": "after", "tool": "edit_file", "command": "bunx prettier --write \"$JADE_TOOL_PATH\"" },
8
+ // { "on": "turn", "command": "powershell -c \"New-BurntToastNotification -Text 'jade is done'\"" }
9
+ // ] } }
10
+ //
11
+ // - before:工具执行前(审批的关卡里)运行。退出码不是 0 时这次调用被拒绝,命令的输出作为理由告诉模型;是 0 时不表态。
12
+ // - after:工具成功执行后运行。退出码不是 0 时把输出留给模型看(下一次请求时附上),不改工具的结果。
13
+ // - turn:一轮结束后运行,结果不影响会话。
14
+ // tool 是工具名,不写或写 "*" 表示所有工具。命令经 shell@1 在工作目录里运行(和 bash 工具同一个 shell),环境变量:
15
+ // JADE_TOOL(工具名)、JADE_TOOL_INPUT(参数的 JSON 文件的路径)、JADE_TOOL_PATH(参数里有 path 时)。
16
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
17
+ import os from "node:os";
18
+ import path from "node:path";
19
+ import { definePlugin } from "@uncarved/jade-api";
20
+ const DEFAULT_TIMEOUT_SECONDS = 60;
21
+ const MAX_TIMEOUT_SECONDS = 600;
22
+ const MAX_OUTPUT_CHARS = 4000;
23
+ /** 检查配置里的 hooks;写错的条目说明原因,其余的照用 */
24
+ export function parseHooks(value) {
25
+ if (value === undefined)
26
+ return { hooks: [], problems: [] };
27
+ if (!Array.isArray(value))
28
+ return { hooks: [], problems: ["hooks must be a list"] };
29
+ const hooks = [];
30
+ const problems = [];
31
+ for (const [i, raw] of value.entries()) {
32
+ const h = (raw ?? {});
33
+ const where = `hooks[${i}]`;
34
+ if (h.on !== "before" && h.on !== "after" && h.on !== "turn")
35
+ problems.push(`${where}: "on" must be "before", "after" or "turn"`);
36
+ else if (typeof h.command !== "string" || !h.command.trim())
37
+ problems.push(`${where}: "command" must be a shell command`);
38
+ else if (h.tool !== undefined && typeof h.tool !== "string")
39
+ problems.push(`${where}: "tool" must be a tool name`);
40
+ else if (h.timeoutSeconds !== undefined && !(typeof h.timeoutSeconds === "number" && h.timeoutSeconds > 0 && h.timeoutSeconds <= MAX_TIMEOUT_SECONDS)) {
41
+ problems.push(`${where}: "timeoutSeconds" must be a number up to ${MAX_TIMEOUT_SECONDS}`);
42
+ }
43
+ else {
44
+ hooks.push({
45
+ on: h.on,
46
+ command: h.command,
47
+ timeoutMs: (h.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000,
48
+ ...(typeof h.tool === "string" && h.tool !== "*" ? { tool: h.tool } : {}),
49
+ });
50
+ }
51
+ }
52
+ return { hooks, problems };
53
+ }
54
+ /** 单引号括起来,给 POSIX shell 用 */
55
+ const quote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
56
+ const clip = (s) => (s.length > MAX_OUTPUT_CHARS ? `${s.slice(0, MAX_OUTPUT_CHARS)}\n… (${s.length - MAX_OUTPUT_CHARS} more characters)` : s);
57
+ let warned = false;
58
+ export default definePlugin({
59
+ session(ctx) {
60
+ const { hooks, problems } = parseHooks(ctx.config.hooks);
61
+ const ui = () => ctx.service("ui@1");
62
+ if (problems.length > 0 && !warned) {
63
+ warned = true;
64
+ ui()?.notify(`jade/hooks: ${problems.join("; ")}`, "warning");
65
+ }
66
+ if (hooks.length === 0)
67
+ return;
68
+ const shell = ctx.require("shell@1");
69
+ const sessionId = ctx.session.id;
70
+ /** 运行一条 hook;call 给了就把工具名和参数经环境变量交给它 */
71
+ const run = async (hook, call, signal) => {
72
+ let dir;
73
+ try {
74
+ let exports = "";
75
+ if (call) {
76
+ dir = await mkdtemp(path.join(os.tmpdir(), "jade-hook-"));
77
+ const file = path.join(dir, "input.json");
78
+ await writeFile(file, JSON.stringify(call.input ?? null));
79
+ const p = call.input?.path;
80
+ // 路径用正斜杠:Git Bash 里反斜杠是转义符
81
+ const vars = { JADE_TOOL: call.name, JADE_TOOL_INPUT: file.split(path.sep).join("/"), ...(typeof p === "string" ? { JADE_TOOL_PATH: p.split(path.sep).join("/") } : {}) };
82
+ exports = `export ${Object.entries(vars).map(([k, v]) => `${k}=${quote(v)}`).join(" ")}; `;
83
+ }
84
+ const r = await shell.run(exports + hook.command, { cwd: ctx.cwd, timeoutMs: hook.timeoutMs, ...(signal ? { signal } : {}) });
85
+ return { ok: r.code === 0, output: r.timedOut ? `timed out after ${hook.timeoutMs / 1000}s` : clip(r.output.trim()) };
86
+ }
87
+ finally {
88
+ if (dir)
89
+ await rm(dir, { recursive: true, force: true }).catch(() => { });
90
+ }
91
+ };
92
+ const matching = (on, tool) => hooks.filter((h) => h.on === on && (h.tool === undefined || h.tool === tool));
93
+ if (hooks.some((h) => h.on === "before")) {
94
+ ctx.kernel.hook({
95
+ kind: "gate",
96
+ point: "tool.gate",
97
+ timeoutMs: MAX_TIMEOUT_SECONDS * 1000,
98
+ fn: async (call, hook) => {
99
+ for (const h of matching("before", call.name)) {
100
+ const r = await run(h, call, hook.signal);
101
+ if (!r.ok)
102
+ return { decision: "deny", reason: `A hook the user configured (${h.command}) refused this ${call.name} call${r.output ? `:\n${r.output}` : "."}` };
103
+ }
104
+ return { decision: "abstain" };
105
+ },
106
+ });
107
+ }
108
+ if (hooks.some((h) => h.on === "after")) {
109
+ ctx.kernel.hook({
110
+ kind: "transform",
111
+ point: "tool.after",
112
+ timeoutMs: MAX_TIMEOUT_SECONDS * 1000,
113
+ // 出错时只是这条 hook 没跑,不影响工具的结果
114
+ optional: true,
115
+ fn: async (out) => {
116
+ if (out.isError)
117
+ return undefined;
118
+ for (const h of matching("after", out.call.name)) {
119
+ const r = await run(h, out.call);
120
+ if (r.ok)
121
+ continue;
122
+ const text = `The user's hook after ${out.call.name} (${h.command}) failed${r.output ? `:\n${r.output}` : "."}`;
123
+ ui()?.notify(text, "warning");
124
+ ctx.service("prompts@1")?.note(sessionId, text);
125
+ }
126
+ return undefined;
127
+ },
128
+ });
129
+ }
130
+ if (hooks.some((h) => h.on === "turn")) {
131
+ ctx.kernel.hook({
132
+ kind: "observe",
133
+ point: "event",
134
+ fn: (e) => {
135
+ if (e.type !== "turn.ended")
136
+ return;
137
+ // 不等它:一轮结束不该被用户的命令拖住
138
+ for (const h of matching("turn")) {
139
+ void run(h, undefined, ctx.signal).then((r) => void (r.ok || ui()?.notify(`jade/hooks: ${h.command} failed${r.output ? `: ${r.output}` : ""}`, "warning")), () => { });
140
+ }
141
+ },
142
+ });
143
+ }
144
+ },
145
+ });
@@ -0,0 +1,19 @@
1
+ {
2
+ "id": "jade/hooks",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.js",
6
+ "requires": [
7
+ "shell@1"
8
+ ],
9
+ "optional": [
10
+ "ui@1",
11
+ "prompts@1"
12
+ ],
13
+ "config": {
14
+ "hooks": {
15
+ "default": [],
16
+ "description": "shell commands to run around tool calls: a list of { \"on\": \"before\" | \"after\" | \"turn\", \"tool\": \"<name>\" (optional), \"command\": \"...\", \"timeoutSeconds\": 60 }. A failing \"before\" command denies the call; a failing \"after\" command is reported to the agent; \"turn\" runs when a turn ends"
17
+ }
18
+ }
19
+ }
@@ -1,5 +1,5 @@
1
1
  // jade/keys:快捷键的注册表。前端在输入框有焦点时按下自己不用的键,查这里找到插件的处理函数。
2
- import { definePlugin } from "../../dist/api.js";
2
+ import { definePlugin } from "@uncarved/jade-api";
3
3
  /** "ctrl+<字母>"、"alt+<字母或数字>" 或 "shift+tab" */
4
4
  export const KEY_SPEC = /^(ctrl\+[a-z]|alt\+[a-z0-9]|shift\+tab)$/;
5
5
  /**
@@ -1,13 +1,15 @@
1
- // jade/mcp:配置的 MCP 服务的工具交给模型(声明只读的也经 task@1 交给子 Agent);/mcp 查看状态、重连。
1
+ // jade/mcp:配置的 MCP 服务的工具交给模型(声明只读的也经 tools@1 交给嵌套 Agent);/mcp 查看状态、重连,
2
+ // /mcp add、/mcp remove 改配置文件(见 install.ts;终端里是 jade mcp add|remove)。
2
3
  //
3
4
  // 服务是进程级的资源:第一个会话打开时读配置、确认项目层的服务、连接,之后各会话共用;进程退出时(进程作用域关闭)全部关掉。
4
5
  // 一个会话里的工具列表不变(否则提示缓存失效):第一个会话最多等 STARTUP_WAIT_MS,没连上的在后台接着连,
5
6
  // 它们的工具从下一个会话(/clear)开始提供。不能交互时(-p)只有这一个会话,照常等到每个服务连上或超时。
6
7
  // 服务进程退出后,下一次调用它的工具时重新连接一次。
7
8
  import path from "node:path";
8
- import { definePlugin } from "../../dist/api.js";
9
+ import { definePlugin } from "@uncarved/jade-api";
9
10
  import { describeServer, loadMcpConfig, McpClient, mcpTools, mcpTrustHash } from "./mcp.js";
10
- import { bold, clip, dim, display, green, realPath, red, repoRoot, TrustFile, yellow } from "./project.js";
11
+ import { manageMcp, manageUsage } from "./install.js";
12
+ import { bold, clip, dim, display, estimateTokens, green, realPath, red, repoRoot, splitArgs, TrustFile, yellow } from "./project.js";
11
13
  const ID = "jade/mcp";
12
14
  /** 第一个会话最多等 MCP 服务连接这么久(能交互时),没连上的在后台接着连 */
13
15
  const STARTUP_WAIT_MS = 5000;
@@ -117,6 +119,11 @@ function instructions(clients) {
117
119
 
118
120
  ${c.instructions}`);
119
121
  }
122
+ /** 一个服务每次请求都带着的大约多少 token:发给模型的工具定义,加上它的使用说明。没连上时为 0 */
123
+ function serverTokens(c) {
124
+ const tools = mcpTools([c]).reduce((n, t) => n + estimateTokens(JSON.stringify({ name: t.name, description: t.description, input_schema: t.inputSchema })), 0);
125
+ return tools + instructions([c]).reduce((n, text) => n + estimateTokens(text), 0);
126
+ }
120
127
  /** 当前进程的服务;process() 里创建,session() 里用 */
121
128
  let current;
122
129
  export default definePlugin({
@@ -127,13 +134,28 @@ export default definePlugin({
127
134
  await ctx.effect(() => () => servers.close());
128
135
  ctx.service("commands@1")?.register({
129
136
  name: "mcp",
130
- args: "[reconnect <name>]",
131
- description: "MCP servers: status and tools",
137
+ args: "[reconnect <name> | add <name> … | remove <name>] [--project]",
138
+ description: "MCP servers: status and tools; add or remove one",
132
139
  instant: true,
133
140
  async run(args) {
141
+ let words;
142
+ try {
143
+ words = splitArgs(args);
144
+ }
145
+ catch (e) {
146
+ return red(errorText(e));
147
+ }
148
+ // 只改配置文件,不用先连接
149
+ if (words[0] === "add" || words[0] === "remove" || words[0] === "rm") {
150
+ try {
151
+ return await manageMcp(words, { home: ctx.home, cwd: ctx.cwd, cmd: "/mcp" });
152
+ }
153
+ catch (e) {
154
+ return red(errorText(e));
155
+ }
156
+ }
134
157
  await servers.start();
135
158
  const clients = servers.clients;
136
- const words = args.trim().split(/\s+/).filter(Boolean);
137
159
  if (words[0] === "reconnect") {
138
160
  const c = clients.find((x) => x.name === words[1]);
139
161
  if (!c)
@@ -148,15 +170,18 @@ export default definePlugin({
148
170
  }
149
171
  }
150
172
  if (words.length > 0)
151
- return red("usage: /mcp [reconnect <name>]");
173
+ return red(`usage: /mcp [reconnect <name>]\n${manageUsage("/mcp")}`);
152
174
  if (clients.length === 0) {
153
- return dim(`(no MCP servers) configure them in ${display(ctx.cwd, path.join(ctx.home, "mcp.json"))}, .mcp.json or .jade/mcp.json`);
175
+ return dim(`(no MCP servers) add one with /mcp add, or configure them in ${display(ctx.cwd, path.join(ctx.home, "mcp.json"))}, .mcp.json or .jade/mcp.json`);
154
176
  }
155
177
  const lines = [];
178
+ let total = 0;
156
179
  for (const c of clients) {
157
180
  const state = c.status === "connected" ? green("connected") : c.status === "failed" ? red("failed") : yellow(c.status);
158
181
  const info = c.serverInfo?.name ? ` · ${c.serverInfo.name}${c.serverInfo.version ? ` ${c.serverInfo.version}` : ""}` : "";
159
- lines.push(`${bold(c.name)} ${state} ${dim(`${c.entry.layer} · ${display(ctx.cwd, c.entry.file)} · ${describeServer(c.entry.config)}${info}`)}`);
182
+ const tokens = serverTokens(c);
183
+ total += tokens;
184
+ lines.push(`${bold(c.name)} ${state} ${dim(`${c.entry.layer} · ${display(ctx.cwd, c.entry.file)} · ${describeServer(c.entry.config)}${info}${tokens ? ` · ≈${tokens} tokens` : ""}`)}`);
160
185
  if (c.error)
161
186
  lines.push(red(` ${c.error}`));
162
187
  if (c.tools.length)
@@ -164,9 +189,16 @@ export default definePlugin({
164
189
  if (c.status === "failed" && c.stderr.length)
165
190
  lines.push(dim(c.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
166
191
  }
192
+ if (total)
193
+ lines.push(dim(`≈${total} tokens in every request (tool definitions and server instructions); remove or disable servers you do not use to save them`));
167
194
  return lines.join("\n");
168
195
  },
169
196
  });
197
+ // 终端里加、删服务:jade mcp add|remove …(cli@1,核心提供)。查看状态要连接服务,只在 /mcp 里有
198
+ ctx.service("cli@1")?.register({
199
+ name: "mcp",
200
+ run: (argv) => manageMcp(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "jade mcp" }),
201
+ });
170
202
  },
171
203
  async session(ctx) {
172
204
  const servers = current;
@@ -175,11 +207,11 @@ export default definePlugin({
175
207
  await servers.start();
176
208
  for (const tool of mcpTools(servers.clients))
177
209
  ctx.kernel.tool(tool);
178
- // 子 Agent(jade/task)只拿声明了只读(readOnlyHint)的工具:另一套实例,和 jade/fs 一样
179
- const task = ctx.service("task@1");
180
- if (task)
210
+ // 嵌套 Agent(例如 jade/task 的子 Agent)只拿声明了只读(readOnlyHint)的工具:另一套实例,和 jade/fs 一样
211
+ const shared = ctx.service("tools@1");
212
+ if (shared)
181
213
  for (const tool of mcpTools(servers.clients, { readOnly: true }))
182
- task.tool(tool);
214
+ shared.register(tool);
183
215
  const prompts = ctx.service("prompts@1");
184
216
  for (const text of instructions(servers.clients))
185
217
  prompts?.add({ text, untrusted: true });
@@ -0,0 +1,160 @@
1
+ // /mcp add|remove(终端里是 jade mcp add|remove):往配置文件里加一个 MCP 服务或删掉它,不用手改 JSON。
2
+ //
3
+ // 不加 --project 写 $JADE_HOME/mcp.json,加了写 <工作目录>/.jade/mcp.json;文件里其他的内容原样保留。
4
+ // 这里只写配置,不启动服务:进程里的服务只在第一个会话打开时连接,新加的重启 jade 后生效。
5
+ // 项目层的服务照旧在第一次启动前请用户确认:命令不顺带记下确认。这个命令也有命令行的写法(jade mcp add),
6
+ // 模型能经 shell 跑它;如果加了就算确认,模型就能绕过确认。
7
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
8
+ import path from "node:path";
9
+ import { checkConfig, describeServer } from "./mcp.js";
10
+ import { display } from "./project.js";
11
+ /** cmd 是 "/mcp" 或 "jade mcp" */
12
+ export const manageUsage = (cmd) => `usage: ${cmd} add <name> [--project] [--env KEY=VALUE]… [--force] [--] <command> [args…]
13
+ ${cmd} add <name> --url <url> [--project] [--header "Name: value"]… [--force]
14
+ ${cmd} remove <name> [--project]
15
+
16
+ --project write <cwd>/.jade/mcp.json instead of $JADE_HOME/mcp.json
17
+ --env an environment variable for a stdio server; values may use \${VAR}
18
+ --header an HTTP header for a --url server; values may use \${VAR}
19
+ --force replace a server with the same name
20
+ Everything after <command> is passed to it unchanged, e.g. ${cmd} add fs npx -y @modelcontextprotocol/server-filesystem .`;
21
+ /** 不加 --project 写 $JADE_HOME/mcp.json,加了写 <工作目录>/.jade/mcp.json */
22
+ export const mcpConfigFile = (home, cwd, project) => (project ? path.join(cwd, ".jade", "mcp.json") : path.join(home, "mcp.json"));
23
+ /** add / remove,参数已经切好;返回给用户看的结果,用法错误或失败时抛错。cmd 用在提示里 */
24
+ export async function manageMcp(argv, env) {
25
+ const usage = manageUsage(env.cmd);
26
+ const [sub, ...tail] = argv;
27
+ if (sub === "-h" || sub === "--help")
28
+ return usage;
29
+ if (sub === "add") {
30
+ const { name, project, force, config } = parseAdd(tail, usage);
31
+ const file = mcpConfigFile(env.home, env.cwd, project);
32
+ await edit(file, (servers) => {
33
+ if (servers[name] !== undefined && !force)
34
+ throw new Error(`${display(env.cwd, file)} already has an MCP server named ${name}; add --force to replace it`);
35
+ servers[name] = config;
36
+ });
37
+ return [
38
+ `added MCP server ${name} to ${display(env.cwd, file)}: ${describeServer(config)}`,
39
+ `restart jade to start it${project ? "; jade asks you to confirm it the first time" : ""}`,
40
+ ].join("\n");
41
+ }
42
+ if (sub === "remove" || sub === "rm") {
43
+ const project = tail.includes("--project");
44
+ const rest = tail.filter((a) => a !== "--project");
45
+ if (rest.length !== 1 || rest[0].startsWith("-"))
46
+ throw new Error(usage);
47
+ const name = rest[0];
48
+ const file = mcpConfigFile(env.home, env.cwd, project);
49
+ await edit(file, (servers) => {
50
+ if (servers[name] === undefined)
51
+ throw new Error(`${display(env.cwd, file)} has no MCP server named ${name}`);
52
+ delete servers[name];
53
+ });
54
+ return `removed MCP server ${name} from ${display(env.cwd, file)}; restart jade to stop it`;
55
+ }
56
+ throw new Error(usage);
57
+ }
58
+ function parseAdd(tail, usage) {
59
+ let name;
60
+ let project = false;
61
+ let force = false;
62
+ let url;
63
+ const envVars = {};
64
+ const headers = {};
65
+ let command;
66
+ for (let i = 0; i < tail.length; i++) {
67
+ const a = tail[i];
68
+ const value = () => {
69
+ const v = tail[++i];
70
+ if (v === undefined)
71
+ throw new Error(`${a} needs a value\n${usage}`);
72
+ return v;
73
+ };
74
+ if (a === "--") {
75
+ command = tail.slice(i + 1);
76
+ break;
77
+ }
78
+ else if (a === "--project")
79
+ project = true;
80
+ else if (a === "--force" || a === "-f")
81
+ force = true;
82
+ else if (a === "--url")
83
+ url = value();
84
+ else if (a === "--env" || a === "-e") {
85
+ const v = value();
86
+ const eq = v.indexOf("=");
87
+ if (eq <= 0)
88
+ throw new Error(`--env needs KEY=VALUE, got ${JSON.stringify(v)}`);
89
+ envVars[v.slice(0, eq)] = v.slice(eq + 1);
90
+ }
91
+ else if (a === "--header" || a === "-H") {
92
+ const v = value();
93
+ const colon = v.indexOf(":");
94
+ if (colon <= 0)
95
+ throw new Error(`--header needs "Name: value", got ${JSON.stringify(v)}`);
96
+ headers[v.slice(0, colon).trim()] = v.slice(colon + 1).trim();
97
+ }
98
+ else if (a.startsWith("-"))
99
+ throw new Error(`unknown option ${a}\n${usage}`);
100
+ else if (name === undefined)
101
+ name = a;
102
+ else {
103
+ // 名字之后第一个不是选项的参数是服务的命令,后面的都原样交给它(npx -y … 里的 -y 不是 jade 的选项)
104
+ command = tail.slice(i);
105
+ break;
106
+ }
107
+ }
108
+ if (name === undefined)
109
+ throw new Error(usage);
110
+ if (url !== undefined && command?.length)
111
+ throw new Error(`give either --url or a command, not both\n${usage}`);
112
+ if (url === undefined && !command?.length)
113
+ throw new Error(`give a command or --url\n${usage}`);
114
+ let config;
115
+ if (url !== undefined) {
116
+ // 含 ${VAR} 的地址要到读配置时才知道展开后是什么,那时再检查
117
+ if (!/^https?:\/\//.test(url) && !url.includes("${"))
118
+ throw new Error(`--url must start with http:// or https://`);
119
+ if (Object.keys(envVars).length)
120
+ throw new Error("--env is for servers started with a command; a --url server takes --header");
121
+ config = { type: "http", url, ...(Object.keys(headers).length ? { headers } : {}) };
122
+ }
123
+ else {
124
+ if (Object.keys(headers).length)
125
+ throw new Error("--header is for --url servers; a command takes --env");
126
+ const [cmd, ...args] = command;
127
+ config = { command: cmd, ...(args.length ? { args } : {}), ...(Object.keys(envVars).length ? { env: envVars } : {}) };
128
+ }
129
+ const problem = checkConfig(name, config);
130
+ if (problem)
131
+ throw new Error(`MCP server ${JSON.stringify(name)}: ${problem}`);
132
+ return { name, project, force, config };
133
+ }
134
+ /** 读配置文件、改 mcpServers、写回;文件坏了时报错,不覆盖 */
135
+ async function edit(file, change) {
136
+ let json = {};
137
+ let text;
138
+ try {
139
+ text = await readFile(file, "utf8");
140
+ }
141
+ catch {
142
+ // 还没有这个文件
143
+ }
144
+ if (text !== undefined && text.trim()) {
145
+ try {
146
+ json = JSON.parse(text);
147
+ }
148
+ catch (e) {
149
+ throw new Error(`${file}: ${e instanceof Error ? e.message : String(e)}; fix it by hand first`);
150
+ }
151
+ if (typeof json !== "object" || json === null || Array.isArray(json))
152
+ throw new Error(`${file}: expected { "mcpServers": { ... } }; fix it by hand first`);
153
+ }
154
+ const servers = (json.mcpServers ??= {});
155
+ if (typeof servers !== "object" || servers === null || Array.isArray(servers))
156
+ throw new Error(`${file}: "mcpServers" is not an object; fix it by hand first`);
157
+ change(servers);
158
+ await mkdir(path.dirname(file), { recursive: true });
159
+ await writeFile(file, JSON.stringify(json, null, 2) + "\n");
160
+ }
@@ -90,7 +90,8 @@ export async function loadMcpConfig(opts) {
90
90
  return { servers: [...out.values()], warnings };
91
91
  }
92
92
  const SERVER_NAME = /^[A-Za-z0-9_.-]+$/;
93
- function checkConfig(name, raw) {
93
+ /** 一条服务配置的问题;没问题时为 undefined。/mcp add 写入前也用它检查 */
94
+ export function checkConfig(name, raw) {
94
95
  if (!SERVER_NAME.test(name))
95
96
  return "the name may only contain letters, digits, '.', '_' and '-'";
96
97
  if (typeof raw !== "object" || raw === null || Array.isArray(raw))
@@ -7,6 +7,7 @@
7
7
  "ui@1",
8
8
  "commands@1",
9
9
  "prompts@1",
10
- "task@1"
10
+ "tools@1",
11
+ "cli@1"
11
12
  ]
12
13
  }
@@ -1,4 +1,4 @@
1
- // 仓库目录、确认记录、显示用的小工具。插件之间不共享代码(只能共享类型),jade/skills、jade/checks 各有一份。
1
+ // 仓库目录、确认记录、显示用的小工具、斜杠命令参数的切分、token 估算。插件之间不共享代码(只能共享类型),jade/skills、jade/checks 各有一份。
2
2
  import { existsSync, realpathSync } from "node:fs";
3
3
  import { appendFile, mkdir, readFile } from "node:fs/promises";
4
4
  import path from "node:path";
@@ -88,3 +88,44 @@ export const red = paint("31", "39");
88
88
  export const green = paint("32", "39");
89
89
  export const yellow = paint("33", "39");
90
90
  export const bold = paint("1", "22");
91
+ /** 斜杠命令的参数按空白切开;"…" 或 '…' 里的空白不切(不处理反斜杠,Windows 路径照写) */
92
+ export function splitArgs(text) {
93
+ const out = [];
94
+ let cur = "";
95
+ let started = false;
96
+ let quote;
97
+ for (const ch of text) {
98
+ if (quote) {
99
+ if (ch === quote)
100
+ quote = undefined;
101
+ else
102
+ cur += ch;
103
+ }
104
+ else if (ch === '"' || ch === "'") {
105
+ quote = ch;
106
+ started = true;
107
+ }
108
+ else if (/\s/.test(ch)) {
109
+ if (started)
110
+ out.push(cur);
111
+ cur = "";
112
+ started = false;
113
+ }
114
+ else {
115
+ cur += ch;
116
+ started = true;
117
+ }
118
+ }
119
+ if (quote)
120
+ throw new Error(`unclosed ${quote}`);
121
+ if (started)
122
+ out.push(cur);
123
+ return out;
124
+ }
125
+ /** 中日韩文字和全角符号:大约一个字一个 token(和 jade/compact 的估算一致) */
126
+ const WIDE = /[ -鿿가-힯豈-﫿＀-￯]/g;
127
+ /** 粗略估算一段文字发给模型时占多少 token:英文和代码约 4 个字符 1 个,中日韩文字每字约 1 个 */
128
+ export function estimateTokens(text) {
129
+ const wide = text.match(WIDE)?.length ?? 0;
130
+ return Math.ceil((text.length - wide) / 4 + wide);
131
+ }
@@ -1,11 +1,9 @@
1
1
  // jade/memory:跨会话的记忆(见 memory.ts)。memory 工具给模型增删,/memory 给用户查看和管理,
2
2
  // 会话开始时经 prompts@1 把记忆放进系统提示词(会话中途的改动下一个会话才进提示词,这样提示缓存不失效;
3
3
  // 用户在 /memory 里改了,下一次请求时附一条说明告诉模型)。
4
- import { definePlugin } from "../../dist/api.js";
4
+ import { definePlugin } from "@uncarved/jade-api";
5
5
  import { Memory, MEMORY_SCOPES, memoryTool, projectRoot } from "./memory.js";
6
- import { Notes } from "./notes.js";
7
6
  import { clip, dim, green, red } from "./style.js";
8
- const notes = new Notes();
9
7
  const args = (input) => (input ?? {});
10
8
  export default definePlugin({
11
9
  process(ctx) {
@@ -29,8 +27,9 @@ export default definePlugin({
29
27
  async run(input, { ui, sessions, signal }) {
30
28
  const note = (text) => {
31
29
  const id = sessions.current?.id;
30
+ // 用到的时候再取:可选服务在 process() 开头不一定已经有了
32
31
  if (id)
33
- notes.add(id, text);
32
+ ctx.service("prompts@1")?.note(id, text);
34
33
  };
35
34
  let text = input.trim();
36
35
  if (!text) {
@@ -85,7 +84,6 @@ export default definePlugin({
85
84
  async session(ctx) {
86
85
  const memory = new Memory(ctx.home, projectRoot(ctx.cwd));
87
86
  ctx.kernel.tool(memoryTool(memory));
88
- ctx.kernel.hook(notes.hook(ctx.session.id, ctx.plugin, ctx.plugin));
89
87
  const text = await memory.prompt();
90
88
  // 段落随会话作用域撤销
91
89
  if (text)
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "jade/memory",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.js",
6
6
  "optional": [
@@ -6,7 +6,7 @@
6
6
  // 每条消息的附件单独记一个 key(attachedKey):derived.recorded 是整值替换,记成一张表的话,
7
7
  // 每次有新的 @ 都要把之前附过的全部内容再写一遍,日志按平方增长。
8
8
  // 输入框里 @ 的补全不在这里,在 jade/tui。
9
- import { definePlugin } from "../../dist/api.js";
9
+ import { definePlugin } from "@uncarved/jade-api";
10
10
  import { attachMentions } from "./attach.js";
11
11
  import { clip, dim, yellow } from "./style.js";
12
12
  /** 附在第 i 条消息后面的内容记在这个 key 下 */