@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
@@ -64,7 +64,8 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
64
64
  `optionally only files matching the glob include (e.g. "*.ts" matches at any depth; "src/**/*.ts" limits it to src). Skips files ignored by git, binary files and .git/node_modules. ` +
65
65
  `output_mode: "content" (default) returns "file:line:text" for matches and "file-line-text" for context lines, at most ${MAX_MATCHES} matches; ` +
66
66
  `"files" returns only the paths of matching files; "count" returns "file:count". ` +
67
- `context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode.`,
67
+ `context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode. ` +
68
+ "head_limit keeps only the first that many lines of the output.",
68
69
  inputSchema: {
69
70
  type: "object",
70
71
  properties: {
@@ -72,8 +73,13 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
72
73
  path: { type: "string" },
73
74
  include: { type: "string" },
74
75
  ignore_case: { type: "boolean" },
75
- output_mode: { type: "string", enum: ["content", "files", "count"] },
76
+ // files_with_matches 是 ripgrep / Claude Code 的叫法,很多模型会这样传,当作 files
77
+ output_mode: { type: "string", enum: ["content", "files", "count", "files_with_matches"] },
76
78
  context: { type: "integer" },
79
+ // head_limit、glob 也是 ripgrep / Claude Code 的叫法;不接受的话模型要多花一轮去掉它们重发。
80
+ // 有的模型把数字写成字符串("30"),也接受
81
+ head_limit: { type: ["integer", "string"] },
82
+ glob: { type: "string" },
77
83
  },
78
84
  required: ["pattern"],
79
85
  additionalProperties: false,
@@ -82,14 +88,17 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
82
88
  concurrency: "safe",
83
89
  idempotent: true,
84
90
  async execute(input, { signal }) {
85
- const { pattern, path: p = ".", include, ignore_case = false, output_mode = "content", context = 0 } = input as {
91
+ const { pattern, path: p = ".", glob, include = glob, ignore_case = false, output_mode = "content", context = 0, head_limit } = input as {
86
92
  pattern: string;
87
93
  path?: string;
88
94
  include?: string;
95
+ glob?: string;
96
+ head_limit?: number | string;
89
97
  ignore_case?: boolean;
90
- output_mode?: Mode;
98
+ output_mode?: Mode | "files_with_matches";
91
99
  context?: number;
92
100
  };
101
+ const mode: Mode = output_mode === "files_with_matches" ? "files" : output_mode;
93
102
  let re: RegExp;
94
103
  try {
95
104
  re = new RegExp(pattern, ignore_case ? "i" : "");
@@ -102,8 +111,8 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
102
111
  pattern,
103
112
  ignoreCase: ignore_case,
104
113
  include,
105
- context: output_mode === "content" ? Math.min(Math.max(context, 0), MAX_CONTEXT) : 0,
106
- mode: output_mode,
114
+ context: mode === "content" ? Math.min(Math.max(context, 0), MAX_CONTEXT) : 0,
115
+ mode,
107
116
  signal,
108
117
  };
109
118
  let found: Found | undefined;
@@ -113,7 +122,10 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
113
122
  else found = result;
114
123
  }
115
124
  found ??= await jsGrep(search);
116
- return { content: format(cwd, found, search) };
125
+ const lines = format(cwd, found, search).split("\n");
126
+ const limit = Number(head_limit);
127
+ if (limit > 0 && lines.length > limit) lines.splice(limit, Infinity, `(showing the first ${limit} of ${lines.length} lines)`);
128
+ return { content: lines.join("\n") };
117
129
  },
118
130
  };
119
131
  }
@@ -1,8 +1,7 @@
1
1
  // jade/fs:文件工具 read_file、write_file、edit_file、multi_edit、list_dir、glob、grep。
2
2
 
3
- import { definePlugin } from "../../src/api.ts";
4
- import type { Renderers } from "../renderers/index.ts";
5
- import type { Task } from "../task/index.ts";
3
+ import { definePlugin } from "@uncarved/jade-api";
4
+ import type { Renderers, Tools } from "@uncarved/jade-api/services";
6
5
  import { fsTools, SeenFiles } from "./fs.ts";
7
6
  import { fsRenderers } from "./renderers.ts";
8
7
 
@@ -27,11 +26,11 @@ export default definePlugin({
27
26
  },
28
27
  });
29
28
  for (const tool of fsTools(ctx.cwd, { responses, seen })) ctx.kernel.tool(tool);
30
- // 子 Agent(jade/task)的只读工具:另一套实例,子 Agent 读过的文件不算主会话读过
31
- // jade/task 被隔离时它的服务已失效:子 Agent 没有文件工具,文件工具本身照常
29
+ // 嵌套 Agent(例如 jade/task 的子 Agent)的只读工具:另一套实例,它读过的文件不算主会话读过
30
+ // jade/tools 被隔离时它的服务已失效:嵌套 Agent 没有文件工具,文件工具本身照常
32
31
  try {
33
- const task = ctx.service<Task>("task@1");
34
- if (task) for (const tool of fsTools(ctx.cwd)) if (tool.effect === "read") task.tool(tool);
32
+ const shared = ctx.service<Tools>("tools@1");
33
+ if (shared) for (const tool of fsTools(ctx.cwd)) if (tool.effect === "read") shared.register(tool);
35
34
  } catch {}
36
35
  },
37
36
  });
@@ -3,5 +3,5 @@
3
3
  "version": "0.2.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["renderers@1", "task@1"]
6
+ "optional": ["renderers@1", "tools@1"]
7
7
  }
@@ -6,7 +6,7 @@
6
6
  import { readFileSync } from "node:fs";
7
7
  import { readFile } from "node:fs/promises";
8
8
  import path from "node:path";
9
- import type { ToolRenderer } from "../renderers/index.ts";
9
+ import type { ToolRenderer } from "@uncarved/jade-api/services";
10
10
  import { diffLines, diffStats, renderDiff } from "./diff.ts";
11
11
  import { applyEditsToText, display, type Edit } from "./fs.ts";
12
12
  import { clip, dim, green, red, yellow } from "./style.ts";
@@ -0,0 +1,152 @@
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
+
17
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
18
+ import os from "node:os";
19
+ import path from "node:path";
20
+ import { definePlugin, type UI } from "@uncarved/jade-api";
21
+ import type { Prompts, Shell } from "@uncarved/jade-api/services";
22
+
23
+ export interface UserHook {
24
+ on: "before" | "after" | "turn";
25
+ /** 工具名;undefined 表示所有工具 */
26
+ tool?: string;
27
+ command: string;
28
+ timeoutMs: number;
29
+ }
30
+
31
+ const DEFAULT_TIMEOUT_SECONDS = 60;
32
+ const MAX_TIMEOUT_SECONDS = 600;
33
+ const MAX_OUTPUT_CHARS = 4000;
34
+
35
+ /** 检查配置里的 hooks;写错的条目说明原因,其余的照用 */
36
+ export function parseHooks(value: unknown): { hooks: UserHook[]; problems: string[] } {
37
+ if (value === undefined) return { hooks: [], problems: [] };
38
+ if (!Array.isArray(value)) return { hooks: [], problems: ["hooks must be a list"] };
39
+ const hooks: UserHook[] = [];
40
+ const problems: string[] = [];
41
+ for (const [i, raw] of value.entries()) {
42
+ const h = (raw ?? {}) as { on?: unknown; tool?: unknown; command?: unknown; timeoutSeconds?: unknown };
43
+ const where = `hooks[${i}]`;
44
+ if (h.on !== "before" && h.on !== "after" && h.on !== "turn") problems.push(`${where}: "on" must be "before", "after" or "turn"`);
45
+ else if (typeof h.command !== "string" || !h.command.trim()) problems.push(`${where}: "command" must be a shell command`);
46
+ else if (h.tool !== undefined && typeof h.tool !== "string") problems.push(`${where}: "tool" must be a tool name`);
47
+ else if (h.timeoutSeconds !== undefined && !(typeof h.timeoutSeconds === "number" && h.timeoutSeconds > 0 && h.timeoutSeconds <= MAX_TIMEOUT_SECONDS)) {
48
+ problems.push(`${where}: "timeoutSeconds" must be a number up to ${MAX_TIMEOUT_SECONDS}`);
49
+ } else {
50
+ hooks.push({
51
+ on: h.on,
52
+ command: h.command,
53
+ timeoutMs: ((h.timeoutSeconds as number | undefined) ?? DEFAULT_TIMEOUT_SECONDS) * 1000,
54
+ ...(typeof h.tool === "string" && h.tool !== "*" ? { tool: h.tool } : {}),
55
+ });
56
+ }
57
+ }
58
+ return { hooks, problems };
59
+ }
60
+
61
+ /** 单引号括起来,给 POSIX shell 用 */
62
+ const quote = (s: string) => `'${s.replaceAll("'", `'\\''`)}'`;
63
+ const clip = (s: string) => (s.length > MAX_OUTPUT_CHARS ? `${s.slice(0, MAX_OUTPUT_CHARS)}\n… (${s.length - MAX_OUTPUT_CHARS} more characters)` : s);
64
+
65
+ let warned = false;
66
+
67
+ export default definePlugin({
68
+ session(ctx) {
69
+ const { hooks, problems } = parseHooks(ctx.config.hooks);
70
+ const ui = () => ctx.service<UI>("ui@1");
71
+ if (problems.length > 0 && !warned) {
72
+ warned = true;
73
+ ui()?.notify(`jade/hooks: ${problems.join("; ")}`, "warning");
74
+ }
75
+ if (hooks.length === 0) return;
76
+ const shell = ctx.require<Shell>("shell@1");
77
+ const sessionId = ctx.session.id;
78
+
79
+ /** 运行一条 hook;call 给了就把工具名和参数经环境变量交给它 */
80
+ const run = async (hook: UserHook, call: { name: string; input: unknown } | undefined, signal?: AbortSignal) => {
81
+ let dir: string | undefined;
82
+ try {
83
+ let exports = "";
84
+ if (call) {
85
+ dir = await mkdtemp(path.join(os.tmpdir(), "jade-hook-"));
86
+ const file = path.join(dir, "input.json");
87
+ await writeFile(file, JSON.stringify(call.input ?? null));
88
+ const p = (call.input as { path?: unknown } | null)?.path;
89
+ // 路径用正斜杠:Git Bash 里反斜杠是转义符
90
+ 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("/") } : {}) };
91
+ exports = `export ${Object.entries(vars).map(([k, v]) => `${k}=${quote(v)}`).join(" ")}; `;
92
+ }
93
+ const r = await shell.run(exports + hook.command, { cwd: ctx.cwd, timeoutMs: hook.timeoutMs, ...(signal ? { signal } : {}) });
94
+ return { ok: r.code === 0, output: r.timedOut ? `timed out after ${hook.timeoutMs / 1000}s` : clip(r.output.trim()) };
95
+ } finally {
96
+ if (dir) await rm(dir, { recursive: true, force: true }).catch(() => {});
97
+ }
98
+ };
99
+ const matching = (on: UserHook["on"], tool?: string) => hooks.filter((h) => h.on === on && (h.tool === undefined || h.tool === tool));
100
+
101
+ if (hooks.some((h) => h.on === "before")) {
102
+ ctx.kernel.hook({
103
+ kind: "gate",
104
+ point: "tool.gate",
105
+ timeoutMs: MAX_TIMEOUT_SECONDS * 1000,
106
+ fn: async (call, hook) => {
107
+ for (const h of matching("before", call.name)) {
108
+ const r = await run(h, call, hook.signal);
109
+ if (!r.ok) return { decision: "deny", reason: `A hook the user configured (${h.command}) refused this ${call.name} call${r.output ? `:\n${r.output}` : "."}` };
110
+ }
111
+ return { decision: "abstain" };
112
+ },
113
+ });
114
+ }
115
+ if (hooks.some((h) => h.on === "after")) {
116
+ ctx.kernel.hook({
117
+ kind: "transform",
118
+ point: "tool.after",
119
+ timeoutMs: MAX_TIMEOUT_SECONDS * 1000,
120
+ // 出错时只是这条 hook 没跑,不影响工具的结果
121
+ optional: true,
122
+ fn: async (out) => {
123
+ if (out.isError) return undefined;
124
+ for (const h of matching("after", out.call.name)) {
125
+ const r = await run(h, out.call);
126
+ if (r.ok) continue;
127
+ const text = `The user's hook after ${out.call.name} (${h.command}) failed${r.output ? `:\n${r.output}` : "."}`;
128
+ ui()?.notify(text, "warning");
129
+ ctx.service<Prompts>("prompts@1")?.note(sessionId, text);
130
+ }
131
+ return undefined;
132
+ },
133
+ });
134
+ }
135
+ if (hooks.some((h) => h.on === "turn")) {
136
+ ctx.kernel.hook({
137
+ kind: "observe",
138
+ point: "event",
139
+ fn: (e) => {
140
+ if (e.type !== "turn.ended") return;
141
+ // 不等它:一轮结束不该被用户的命令拖住
142
+ for (const h of matching("turn")) {
143
+ void run(h, undefined, ctx.signal).then(
144
+ (r) => void (r.ok || ui()?.notify(`jade/hooks: ${h.command} failed${r.output ? `: ${r.output}` : ""}`, "warning")),
145
+ () => {},
146
+ );
147
+ }
148
+ },
149
+ });
150
+ }
151
+ },
152
+ });
@@ -0,0 +1,14 @@
1
+ {
2
+ "id": "jade/hooks",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.ts",
6
+ "requires": ["shell@1"],
7
+ "optional": ["ui@1", "prompts@1"],
8
+ "config": {
9
+ "hooks": {
10
+ "default": [],
11
+ "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"
12
+ }
13
+ }
14
+ }
@@ -1,6 +1,7 @@
1
1
  // jade/keys:快捷键的注册表。前端在输入框有焦点时按下自己不用的键,查这里找到插件的处理函数。
2
2
 
3
- import { definePlugin } from "../../src/api.ts";
3
+ import { definePlugin } from "@uncarved/jade-api";
4
+ import type { Key, Keys } from "@uncarved/jade-api/services";
4
5
 
5
6
  /** "ctrl+<字母>"、"alt+<字母或数字>" 或 "shift+tab" */
6
7
  export const KEY_SPEC = /^(ctrl\+[a-z]|alt\+[a-z0-9]|shift\+tab)$/;
@@ -10,23 +11,6 @@ export const KEY_SPEC = /^(ctrl\+[a-z]|alt\+[a-z0-9]|shift\+tab)$/;
10
11
  */
11
12
  export const RESERVED_KEYS: ReadonlySet<string> = new Set([..."acdehijklmoruw"].map((c) => `ctrl+${c}`).concat("alt+f", "alt+b"));
12
13
 
13
- export interface Key {
14
- /** 见 KEY_SPEC,不分大小写 */
15
- key: string;
16
- /** /help 里显示 */
17
- description?: string;
18
- /** 按下时调用;出错时前端显示警告。上一次还没执行完时再按,会再调用一次 */
19
- run(ctx: { key: string; signal: AbortSignal }): void | Promise<void>;
20
- }
21
-
22
- export interface Keys {
23
- /** 注册一个键,返回撤销函数。键不合法、是保留键或已被占用时抛错 */
24
- register(key: Key): () => void;
25
- /** 前端按下一个自己不用的键时查找;找到了由前端执行 run,出错时显示警告 */
26
- get(key: string): { key: Key; plugin: string } | undefined;
27
- list(): { key: string; description?: string; plugin: string }[];
28
- }
29
-
30
14
  const registry = new Map<string, { key: Key; plugin: string }>();
31
15
 
32
16
  export default definePlugin({
@@ -1,4 +1,5 @@
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,没连上的在后台接着连,
@@ -6,12 +7,11 @@
6
7
  // 服务进程退出后,下一次调用它的工具时重新连接一次。
7
8
 
8
9
  import path from "node:path";
9
- import { definePlugin, type ProcessContext, type UI } from "../../src/api.ts";
10
- import type { Commands } from "../commands/index.ts";
11
- import type { Prompts } from "../prompts/index.ts";
12
- import type { Task } from "../task/index.ts";
10
+ import { definePlugin, type Cli, type ProcessContext, type UI } from "@uncarved/jade-api";
11
+ import type { Commands, Prompts, Tools } from "@uncarved/jade-api/services";
13
12
  import { describeServer, loadMcpConfig, McpClient, mcpTools, mcpTrustHash } from "./mcp.ts";
14
- import { bold, clip, dim, display, green, realPath, red, repoRoot, TrustFile, yellow } from "./project.ts";
13
+ import { manageMcp, manageUsage } from "./install.ts";
14
+ import { bold, clip, dim, display, estimateTokens, green, realPath, red, repoRoot, splitArgs, TrustFile, yellow } from "./project.ts";
15
15
 
16
16
  const ID = "jade/mcp";
17
17
  /** 第一个会话最多等 MCP 服务连接这么久(能交互时),没连上的在后台接着连 */
@@ -130,6 +130,12 @@ function instructions(clients: McpClient[]): string[] {
130
130
  ${c.instructions}`);
131
131
  }
132
132
 
133
+ /** 一个服务每次请求都带着的大约多少 token:发给模型的工具定义,加上它的使用说明。没连上时为 0 */
134
+ function serverTokens(c: McpClient): number {
135
+ const tools = mcpTools([c]).reduce((n, t) => n + estimateTokens(JSON.stringify({ name: t.name, description: t.description, input_schema: t.inputSchema })), 0);
136
+ return tools + instructions([c]).reduce((n, text) => n + estimateTokens(text), 0);
137
+ }
138
+
133
139
  /** 当前进程的服务;process() 里创建,session() 里用 */
134
140
  let current: Servers | undefined;
135
141
 
@@ -142,13 +148,26 @@ export default definePlugin({
142
148
 
143
149
  ctx.service<Commands>("commands@1")?.register({
144
150
  name: "mcp",
145
- args: "[reconnect <name>]",
146
- description: "MCP servers: status and tools",
151
+ args: "[reconnect <name> | add <name> … | remove <name>] [--project]",
152
+ description: "MCP servers: status and tools; add or remove one",
147
153
  instant: true,
148
154
  async run(args) {
155
+ let words: string[];
156
+ try {
157
+ words = splitArgs(args);
158
+ } catch (e) {
159
+ return red(errorText(e));
160
+ }
161
+ // 只改配置文件,不用先连接
162
+ if (words[0] === "add" || words[0] === "remove" || words[0] === "rm") {
163
+ try {
164
+ return await manageMcp(words, { home: ctx.home, cwd: ctx.cwd, cmd: "/mcp" });
165
+ } catch (e) {
166
+ return red(errorText(e));
167
+ }
168
+ }
149
169
  await servers.start();
150
170
  const clients = servers.clients;
151
- const words = args.trim().split(/\s+/).filter(Boolean);
152
171
  if (words[0] === "reconnect") {
153
172
  const c = clients.find((x) => x.name === words[1]);
154
173
  if (!c) return red(`usage: /mcp reconnect <name>; servers: ${clients.map((x) => x.name).join(", ") || "(none)"}`);
@@ -160,22 +179,31 @@ export default definePlugin({
160
179
  return red(`${c.name}: ${errorText(err)}`);
161
180
  }
162
181
  }
163
- if (words.length > 0) return red("usage: /mcp [reconnect <name>]");
182
+ if (words.length > 0) return red(`usage: /mcp [reconnect <name>]\n${manageUsage("/mcp")}`);
164
183
  if (clients.length === 0) {
165
- return dim(`(no MCP servers) configure them in ${display(ctx.cwd, path.join(ctx.home, "mcp.json"))}, .mcp.json or .jade/mcp.json`);
184
+ 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`);
166
185
  }
167
186
  const lines: string[] = [];
187
+ let total = 0;
168
188
  for (const c of clients) {
169
189
  const state = c.status === "connected" ? green("connected") : c.status === "failed" ? red("failed") : yellow(c.status);
170
190
  const info = c.serverInfo?.name ? ` · ${c.serverInfo.name}${c.serverInfo.version ? ` ${c.serverInfo.version}` : ""}` : "";
171
- lines.push(`${bold(c.name)} ${state} ${dim(`${c.entry.layer} · ${display(ctx.cwd, c.entry.file)} · ${describeServer(c.entry.config)}${info}`)}`);
191
+ const tokens = serverTokens(c);
192
+ total += tokens;
193
+ lines.push(`${bold(c.name)} ${state} ${dim(`${c.entry.layer} · ${display(ctx.cwd, c.entry.file)} · ${describeServer(c.entry.config)}${info}${tokens ? ` · ≈${tokens} tokens` : ""}`)}`);
172
194
  if (c.error) lines.push(red(` ${c.error}`));
173
195
  if (c.tools.length) lines.push(` tools ${c.tools.map((t) => `${t.name}${t.annotations?.readOnlyHint ? dim(" (read)") : ""}`).join(", ")}`);
174
196
  if (c.status === "failed" && c.stderr.length) lines.push(dim(c.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
175
197
  }
198
+ if (total) lines.push(dim(`≈${total} tokens in every request (tool definitions and server instructions); remove or disable servers you do not use to save them`));
176
199
  return lines.join("\n");
177
200
  },
178
201
  });
202
+ // 终端里加、删服务:jade mcp add|remove …(cli@1,核心提供)。查看状态要连接服务,只在 /mcp 里有
203
+ ctx.service<Cli>("cli@1")?.register({
204
+ name: "mcp",
205
+ run: (argv) => manageMcp(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "jade mcp" }),
206
+ });
179
207
  },
180
208
 
181
209
  async session(ctx) {
@@ -183,9 +211,9 @@ export default definePlugin({
183
211
  if (!servers) return;
184
212
  await servers.start();
185
213
  for (const tool of mcpTools(servers.clients)) ctx.kernel.tool(tool);
186
- // 子 Agent(jade/task)只拿声明了只读(readOnlyHint)的工具:另一套实例,和 jade/fs 一样
187
- const task = ctx.service<Task>("task@1");
188
- if (task) for (const tool of mcpTools(servers.clients, { readOnly: true })) task.tool(tool);
214
+ // 嵌套 Agent(例如 jade/task 的子 Agent)只拿声明了只读(readOnlyHint)的工具:另一套实例,和 jade/fs 一样
215
+ const shared = ctx.service<Tools>("tools@1");
216
+ if (shared) for (const tool of mcpTools(servers.clients, { readOnly: true })) shared.register(tool);
189
217
  const prompts = ctx.service<Prompts>("prompts@1");
190
218
  for (const text of instructions(servers.clients)) prompts?.add({ text, untrusted: true });
191
219
  },
@@ -0,0 +1,139 @@
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
+
8
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
9
+ import path from "node:path";
10
+ import { checkConfig, describeServer, type McpServerConfig } from "./mcp.ts";
11
+ import { display } from "./project.ts";
12
+
13
+ /** cmd 是 "/mcp" 或 "jade mcp" */
14
+ export const manageUsage = (cmd: string) => `usage: ${cmd} add <name> [--project] [--env KEY=VALUE]… [--force] [--] <command> [args…]
15
+ ${cmd} add <name> --url <url> [--project] [--header "Name: value"]… [--force]
16
+ ${cmd} remove <name> [--project]
17
+
18
+ --project write <cwd>/.jade/mcp.json instead of $JADE_HOME/mcp.json
19
+ --env an environment variable for a stdio server; values may use \${VAR}
20
+ --header an HTTP header for a --url server; values may use \${VAR}
21
+ --force replace a server with the same name
22
+ Everything after <command> is passed to it unchanged, e.g. ${cmd} add fs npx -y @modelcontextprotocol/server-filesystem .`;
23
+
24
+ /** 不加 --project 写 $JADE_HOME/mcp.json,加了写 <工作目录>/.jade/mcp.json */
25
+ export const mcpConfigFile = (home: string, cwd: string, project: boolean) => (project ? path.join(cwd, ".jade", "mcp.json") : path.join(home, "mcp.json"));
26
+
27
+ /** add / remove,参数已经切好;返回给用户看的结果,用法错误或失败时抛错。cmd 用在提示里 */
28
+ export async function manageMcp(argv: readonly string[], env: { home: string; cwd: string; cmd: string }): Promise<string> {
29
+ const usage = manageUsage(env.cmd);
30
+ const [sub, ...tail] = argv;
31
+ if (sub === "-h" || sub === "--help") return usage;
32
+ if (sub === "add") {
33
+ const { name, project, force, config } = parseAdd(tail, usage);
34
+ const file = mcpConfigFile(env.home, env.cwd, project);
35
+ await edit(file, (servers) => {
36
+ if (servers[name] !== undefined && !force) throw new Error(`${display(env.cwd, file)} already has an MCP server named ${name}; add --force to replace it`);
37
+ servers[name] = config;
38
+ });
39
+ return [
40
+ `added MCP server ${name} to ${display(env.cwd, file)}: ${describeServer(config)}`,
41
+ `restart jade to start it${project ? "; jade asks you to confirm it the first time" : ""}`,
42
+ ].join("\n");
43
+ }
44
+ if (sub === "remove" || sub === "rm") {
45
+ const project = tail.includes("--project");
46
+ const rest = tail.filter((a) => a !== "--project");
47
+ if (rest.length !== 1 || rest[0]!.startsWith("-")) throw new Error(usage);
48
+ const name = rest[0]!;
49
+ const file = mcpConfigFile(env.home, env.cwd, project);
50
+ await edit(file, (servers) => {
51
+ if (servers[name] === undefined) 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
+
59
+ function parseAdd(tail: readonly string[], usage: string): { name: string; project: boolean; force: boolean; config: McpServerConfig } {
60
+ let name: string | undefined;
61
+ let project = false;
62
+ let force = false;
63
+ let url: string | undefined;
64
+ const envVars: Record<string, string> = {};
65
+ const headers: Record<string, string> = {};
66
+ let command: string[] | undefined;
67
+ for (let i = 0; i < tail.length; i++) {
68
+ const a = tail[i]!;
69
+ const value = () => {
70
+ const v = tail[++i];
71
+ if (v === undefined) 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
+ } else if (a === "--project") project = true;
78
+ else if (a === "--force" || a === "-f") force = true;
79
+ else if (a === "--url") url = value();
80
+ else if (a === "--env" || a === "-e") {
81
+ const v = value();
82
+ const eq = v.indexOf("=");
83
+ if (eq <= 0) throw new Error(`--env needs KEY=VALUE, got ${JSON.stringify(v)}`);
84
+ envVars[v.slice(0, eq)] = v.slice(eq + 1);
85
+ } else if (a === "--header" || a === "-H") {
86
+ const v = value();
87
+ const colon = v.indexOf(":");
88
+ if (colon <= 0) throw new Error(`--header needs "Name: value", got ${JSON.stringify(v)}`);
89
+ headers[v.slice(0, colon).trim()] = v.slice(colon + 1).trim();
90
+ } else if (a.startsWith("-")) throw new Error(`unknown option ${a}\n${usage}`);
91
+ else if (name === undefined) name = a;
92
+ else {
93
+ // 名字之后第一个不是选项的参数是服务的命令,后面的都原样交给它(npx -y … 里的 -y 不是 jade 的选项)
94
+ command = tail.slice(i);
95
+ break;
96
+ }
97
+ }
98
+ if (name === undefined) throw new Error(usage);
99
+ if (url !== undefined && command?.length) throw new Error(`give either --url or a command, not both\n${usage}`);
100
+ if (url === undefined && !command?.length) throw new Error(`give a command or --url\n${usage}`);
101
+ let config: McpServerConfig;
102
+ if (url !== undefined) {
103
+ // 含 ${VAR} 的地址要到读配置时才知道展开后是什么,那时再检查
104
+ if (!/^https?:\/\//.test(url) && !url.includes("${")) throw new Error(`--url must start with http:// or https://`);
105
+ if (Object.keys(envVars).length) throw new Error("--env is for servers started with a command; a --url server takes --header");
106
+ config = { type: "http", url, ...(Object.keys(headers).length ? { headers } : {}) };
107
+ } else {
108
+ if (Object.keys(headers).length) throw new Error("--header is for --url servers; a command takes --env");
109
+ const [cmd, ...args] = command!;
110
+ config = { command: cmd!, ...(args.length ? { args } : {}), ...(Object.keys(envVars).length ? { env: envVars } : {}) };
111
+ }
112
+ const problem = checkConfig(name, config);
113
+ if (problem) throw new Error(`MCP server ${JSON.stringify(name)}: ${problem}`);
114
+ return { name, project, force, config };
115
+ }
116
+
117
+ /** 读配置文件、改 mcpServers、写回;文件坏了时报错,不覆盖 */
118
+ async function edit(file: string, change: (servers: Record<string, unknown>) => void): Promise<void> {
119
+ let json: Record<string, unknown> = {};
120
+ let text: string | undefined;
121
+ try {
122
+ text = await readFile(file, "utf8");
123
+ } catch {
124
+ // 还没有这个文件
125
+ }
126
+ if (text !== undefined && text.trim()) {
127
+ try {
128
+ json = JSON.parse(text);
129
+ } catch (e) {
130
+ throw new Error(`${file}: ${e instanceof Error ? e.message : String(e)}; fix it by hand first`);
131
+ }
132
+ if (typeof json !== "object" || json === null || Array.isArray(json)) throw new Error(`${file}: expected { "mcpServers": { ... } }; fix it by hand first`);
133
+ }
134
+ const servers = (json.mcpServers ??= {}) as Record<string, unknown>;
135
+ if (typeof servers !== "object" || servers === null || Array.isArray(servers)) throw new Error(`${file}: "mcpServers" is not an object; fix it by hand first`);
136
+ change(servers);
137
+ await mkdir(path.dirname(file), { recursive: true });
138
+ await writeFile(file, JSON.stringify(json, null, 2) + "\n");
139
+ }
@@ -135,7 +135,8 @@ export async function loadMcpConfig(opts: {
135
135
 
136
136
  const SERVER_NAME = /^[A-Za-z0-9_.-]+$/;
137
137
 
138
- function checkConfig(name: string, raw: unknown): string | undefined {
138
+ /** 一条服务配置的问题;没问题时为 undefined。/mcp add 写入前也用它检查 */
139
+ export function checkConfig(name: string, raw: unknown): string | undefined {
139
140
  if (!SERVER_NAME.test(name)) return "the name may only contain letters, digits, '.', '_' and '-'";
140
141
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return "must be an object";
141
142
  const c = raw as McpServerConfig;
@@ -3,5 +3,5 @@
3
3
  "version": "0.2.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["ui@1", "commands@1", "prompts@1", "task@1"]
6
+ "optional": ["ui@1", "commands@1", "prompts@1", "tools@1", "cli@1"]
7
7
  }
@@ -1,4 +1,4 @@
1
- // 仓库目录、确认记录、显示用的小工具。插件之间不共享代码(只能共享类型),jade/skills、jade/checks 各有一份。
1
+ // 仓库目录、确认记录、显示用的小工具、斜杠命令参数的切分、token 估算。插件之间不共享代码(只能共享类型),jade/skills、jade/checks 各有一份。
2
2
 
3
3
  import { existsSync, realpathSync } from "node:fs";
4
4
  import { appendFile, mkdir, readFile } from "node:fs/promises";
@@ -91,3 +91,39 @@ export const red = paint("31", "39");
91
91
  export const green = paint("32", "39");
92
92
  export const yellow = paint("33", "39");
93
93
  export const bold = paint("1", "22");
94
+
95
+ /** 斜杠命令的参数按空白切开;"…" 或 '…' 里的空白不切(不处理反斜杠,Windows 路径照写) */
96
+ export function splitArgs(text: string): string[] {
97
+ const out: string[] = [];
98
+ let cur = "";
99
+ let started = false;
100
+ let quote: string | undefined;
101
+ for (const ch of text) {
102
+ if (quote) {
103
+ if (ch === quote) quote = undefined;
104
+ else cur += ch;
105
+ } else if (ch === '"' || ch === "'") {
106
+ quote = ch;
107
+ started = true;
108
+ } else if (/\s/.test(ch)) {
109
+ if (started) out.push(cur);
110
+ cur = "";
111
+ started = false;
112
+ } else {
113
+ cur += ch;
114
+ started = true;
115
+ }
116
+ }
117
+ if (quote) throw new Error(`unclosed ${quote}`);
118
+ if (started) out.push(cur);
119
+ return out;
120
+ }
121
+
122
+ /** 中日韩文字和全角符号:大约一个字一个 token(和 jade/compact 的估算一致) */
123
+ const WIDE = /[ -鿿가-힯豈-﫿＀-￯]/g;
124
+
125
+ /** 粗略估算一段文字发给模型时占多少 token:英文和代码约 4 个字符 1 个,中日韩文字每字约 1 个 */
126
+ export function estimateTokens(text: string): number {
127
+ const wide = text.match(WIDE)?.length ?? 0;
128
+ return Math.ceil((text.length - wide) / 4 + wide);
129
+ }