@uncarved/jade 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/dist/api.d.ts +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/host.d.ts +2 -0
  4. package/dist/host.js +39 -5
  5. package/dist/host.js.map +1 -1
  6. package/dist/remote.js +5 -0
  7. package/dist/remote.js.map +1 -1
  8. package/dist/session.d.ts +7 -0
  9. package/dist/session.js +482 -27
  10. package/dist/session.js.map +1 -1
  11. package/package.json +4 -4
  12. package/plugins/approval/index.ts +36 -14
  13. package/plugins/approval/policy.ts +15 -10
  14. package/plugins/approval/review.ts +9 -5
  15. package/plugins/checks/checks.ts +10 -7
  16. package/plugins/checks/index.ts +13 -13
  17. package/plugins/checks/plugin.json +1 -1
  18. package/plugins/checks/project.ts +37 -38
  19. package/plugins/commands/index.ts +27 -3
  20. package/plugins/compact/compact.ts +13 -5
  21. package/plugins/compact/index.ts +20 -3
  22. package/plugins/compact/style.ts +13 -14
  23. package/plugins/completions/index.ts +35 -0
  24. package/plugins/completions/plugin.json +7 -0
  25. package/plugins/copy/index.ts +46 -0
  26. package/plugins/copy/plugin.json +7 -0
  27. package/plugins/editor/index.ts +10 -4
  28. package/plugins/fs/diff.ts +7 -6
  29. package/plugins/fs/fs.ts +8 -4
  30. package/plugins/fs/grep.ts +42 -9
  31. package/plugins/fs/index.ts +2 -7
  32. package/plugins/fs/plugin.json +1 -1
  33. package/plugins/fs/renderers.ts +16 -15
  34. package/plugins/fs/style.ts +16 -15
  35. package/plugins/hooks/index.ts +3 -2
  36. package/plugins/keys/index.ts +5 -1
  37. package/plugins/mcp/index.ts +197 -78
  38. package/plugins/mcp/install.ts +5 -3
  39. package/plugins/mcp/mcp.ts +163 -11
  40. package/plugins/mcp/plugin.json +2 -1
  41. package/plugins/mcp/project.ts +47 -50
  42. package/plugins/memory/index.ts +4 -4
  43. package/plugins/memory/style.ts +13 -14
  44. package/plugins/mentions/candidates.ts +67 -0
  45. package/plugins/mentions/index.ts +12 -5
  46. package/plugins/mentions/plugin.json +1 -1
  47. package/plugins/mentions/style.ts +13 -14
  48. package/plugins/models/configure.ts +10 -9
  49. package/plugins/models/index.ts +27 -1
  50. package/plugins/modes/index.ts +13 -2
  51. package/plugins/print/index.ts +7 -4
  52. package/plugins/prompts/index.ts +0 -0
  53. package/plugins/renderers/index.ts +10 -5
  54. package/plugins/repeats/index.ts +8 -8
  55. package/plugins/schedule/index.ts +2 -0
  56. package/plugins/screenshot/browser.ts +10 -0
  57. package/plugins/sessions/index.ts +48 -2
  58. package/plugins/shell/index.ts +20 -25
  59. package/plugins/shell/plugin.json +1 -2
  60. package/plugins/shell/renderers.ts +9 -7
  61. package/plugins/shell/shell.ts +3 -1
  62. package/plugins/skills/index.ts +28 -19
  63. package/plugins/skills/project.ts +12 -7
  64. package/plugins/steer/index.ts +5 -4
  65. package/plugins/task/index.ts +80 -50
  66. package/plugins/task/plugin.json +6 -2
  67. package/plugins/task/style.ts +13 -14
  68. package/plugins/task/subagent.ts +67 -184
  69. package/plugins/todo/index.ts +39 -9
  70. package/plugins/tools/index.ts +9 -2
  71. package/plugins/tui/frontend.ts +139 -89
  72. package/plugins/tui/index.ts +2 -3
  73. package/plugins/tui/mentions.ts +11 -80
  74. package/plugins/tui/plugin.json +1 -1
  75. package/plugins/tui/screen.ts +55 -5
  76. package/plugins/tui/transcript.ts +17 -7
  77. package/plugins/tui/tui.ts +337 -101
  78. package/plugins/tui/vendor.ts +1 -1
  79. package/plugins/undo/checkpoint.ts +5 -3
  80. package/plugins/undo/index.ts +43 -14
  81. package/plugins/undo/style.ts +13 -14
  82. package/plugins/web/index.ts +7 -18
  83. package/plugins/web/plugin.json +1 -1
  84. package/plugins-dist/approval/index.js +363 -418
  85. package/plugins-dist/approval/policy.js +391 -508
  86. package/plugins-dist/approval/review.js +132 -158
  87. package/plugins-dist/approval/schema.js +50 -55
  88. package/plugins-dist/ask/index.js +115 -129
  89. package/plugins-dist/budget/index.js +27 -31
  90. package/plugins-dist/checks/checks.js +293 -329
  91. package/plugins-dist/checks/index.js +119 -139
  92. package/plugins-dist/checks/plugin.json +2 -1
  93. package/plugins-dist/checks/project.js +57 -65
  94. package/plugins-dist/commands/index.js +47 -29
  95. package/plugins-dist/compact/compact.js +233 -249
  96. package/plugins-dist/compact/index.js +98 -95
  97. package/plugins-dist/compact/style.js +9 -14
  98. package/plugins-dist/completions/index.js +30 -0
  99. package/plugins-dist/completions/plugin.json +9 -0
  100. package/plugins-dist/continue/index.js +40 -52
  101. package/plugins-dist/copy/index.js +40 -0
  102. package/plugins-dist/copy/plugin.json +9 -0
  103. package/plugins-dist/cost/index.js +98 -115
  104. package/plugins-dist/custom-commands/index.js +55 -72
  105. package/plugins-dist/editor/index.js +64 -72
  106. package/plugins-dist/fs/diff.js +111 -124
  107. package/plugins-dist/fs/fs.js +426 -469
  108. package/plugins-dist/fs/grep.js +262 -253
  109. package/plugins-dist/fs/index.js +20 -34
  110. package/plugins-dist/fs/plugin.json +1 -2
  111. package/plugins-dist/fs/renderers.js +100 -112
  112. package/plugins-dist/fs/style.js +11 -15
  113. package/plugins-dist/fs/sys.js +31 -43
  114. package/plugins-dist/hooks/index.js +107 -127
  115. package/plugins-dist/keys/index.js +27 -31
  116. package/plugins-dist/mcp/index.js +271 -199
  117. package/plugins-dist/mcp/install.js +123 -137
  118. package/plugins-dist/mcp/mcp.js +638 -577
  119. package/plugins-dist/mcp/plugin.json +3 -1
  120. package/plugins-dist/mcp/project.js +98 -115
  121. package/plugins-dist/memory/index.js +83 -88
  122. package/plugins-dist/memory/memory.js +111 -128
  123. package/plugins-dist/memory/style.js +9 -14
  124. package/plugins-dist/mentions/attach.js +91 -99
  125. package/plugins-dist/mentions/candidates.js +49 -0
  126. package/plugins-dist/mentions/index.js +71 -81
  127. package/plugins-dist/mentions/plugin.json +2 -1
  128. package/plugins-dist/mentions/style.js +9 -14
  129. package/plugins-dist/models/config.js +29 -43
  130. package/plugins-dist/models/configure.js +392 -473
  131. package/plugins-dist/models/context.js +14 -22
  132. package/plugins-dist/models/index.js +182 -189
  133. package/plugins-dist/models/provider.js +243 -307
  134. package/plugins-dist/models/saved.js +59 -71
  135. package/plugins-dist/modes/index.js +138 -165
  136. package/plugins-dist/plugins/index.js +34 -34
  137. package/plugins-dist/print/index.js +192 -175
  138. package/plugins-dist/prompts/index.js +81 -89
  139. package/plugins-dist/prompts/notes.js +31 -37
  140. package/plugins-dist/prompts/prompts.js +155 -193
  141. package/plugins-dist/prompts/results.js +40 -53
  142. package/plugins-dist/prompts/sys.js +39 -50
  143. package/plugins-dist/renderers/index.js +32 -32
  144. package/plugins-dist/repeats/index.js +131 -174
  145. package/plugins-dist/schedule/cron.js +49 -56
  146. package/plugins-dist/schedule/index.js +229 -247
  147. package/plugins-dist/schedule/store.js +93 -109
  148. package/plugins-dist/scratch/index.js +12 -18
  149. package/plugins-dist/screenshot/browser.js +136 -154
  150. package/plugins-dist/screenshot/index.js +37 -46
  151. package/plugins-dist/screenshot/sys.js +53 -65
  152. package/plugins-dist/screenshot/tool.js +98 -126
  153. package/plugins-dist/sessions/index.js +149 -117
  154. package/plugins-dist/shell/index.js +115 -135
  155. package/plugins-dist/shell/plugin.json +1 -2
  156. package/plugins-dist/shell/renderers.js +28 -33
  157. package/plugins-dist/shell/service.js +17 -23
  158. package/plugins-dist/shell/shell.js +307 -362
  159. package/plugins-dist/shell/sys.js +64 -79
  160. package/plugins-dist/skills/index.js +193 -211
  161. package/plugins-dist/skills/install.js +122 -149
  162. package/plugins-dist/skills/project.js +65 -73
  163. package/plugins-dist/skills/skills.js +135 -171
  164. package/plugins-dist/steer/index.js +108 -125
  165. package/plugins-dist/suggest/index.js +235 -259
  166. package/plugins-dist/task/index.js +130 -117
  167. package/plugins-dist/task/plugin.json +5 -2
  168. package/plugins-dist/task/style.js +9 -14
  169. package/plugins-dist/task/subagent.js +156 -279
  170. package/plugins-dist/todo/index.js +79 -63
  171. package/plugins-dist/tools/index.js +36 -42
  172. package/plugins-dist/tui/editor.js +145 -160
  173. package/plugins-dist/tui/frontend.js +639 -678
  174. package/plugins-dist/tui/history.js +34 -37
  175. package/plugins-dist/tui/index.js +16 -18
  176. package/plugins-dist/tui/markdown.js +203 -247
  177. package/plugins-dist/tui/mascot.js +266 -355
  178. package/plugins-dist/tui/mentions.js +67 -144
  179. package/plugins-dist/tui/plugin.json +1 -2
  180. package/plugins-dist/tui/render.js +35 -45
  181. package/plugins-dist/tui/screen.js +197 -180
  182. package/plugins-dist/tui/transcript.js +436 -468
  183. package/plugins-dist/tui/tui.js +1554 -1656
  184. package/plugins-dist/undo/checkpoint.js +95 -118
  185. package/plugins-dist/undo/index.js +185 -192
  186. package/plugins-dist/undo/snapshot.js +83 -99
  187. package/plugins-dist/undo/style.js +9 -14
  188. package/plugins-dist/update/index.js +26 -28
  189. package/plugins-dist/web/env.js +55 -68
  190. package/plugins-dist/web/index.js +80 -110
  191. package/plugins-dist/web/plugin.json +1 -2
  192. package/plugins-dist/web/renderers.js +4 -5
  193. package/plugins-dist/web/web.js +514 -593
  194. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  195. package/sdk/python/jade_plugin.py +9 -2
  196. package/src/api.ts +1 -1
  197. package/src/host.ts +39 -4
  198. package/src/remote.ts +6 -1
  199. package/src/session.ts +489 -34
@@ -1,8 +1,3 @@
1
- // grep 工具:有 ripgrep 时用它(快、并行、自己处理 .gitignore 和二进制文件),没有时用 JS 逐个文件搜索。
2
- // 两条路径产生同样的中间结果(按文件分组的命中行和上下文行),再统一格式化,所以输出格式一致。
3
- //
4
- // ripgrep 的正则语法和 JavaScript 不完全相同(例如不支持环视)。ripgrep 报正则语法错误时改用 JS 搜索,
5
- // 所以模型按 JavaScript 语法写的正则总能用。
6
1
  import { readFile, stat } from "node:fs/promises";
7
2
  import path from "node:path";
8
3
  import { display, listFiles, statOrUndefined } from "./fs.js";
@@ -10,271 +5,285 @@ import { globMatcher, spawn, text } from "./sys.js";
10
5
  const MAX_MATCHES = 200;
11
6
  const MAX_FILES = 500;
12
7
  const MAX_CONTEXT = 10;
13
- const MAX_FILE_BYTES = 1_000_000;
8
+ const MAX_FILE_BYTES = 1e6;
14
9
  const MAX_LINE_CHARS = 300;
15
10
  export function grepTool(cwd, opts = {}) {
16
- /** 第一次找不到 ripgrep 之后不再尝试 */
17
- let rg = opts.rg === undefined ? "rg" : opts.rg;
18
- return {
19
- name: "grep",
20
- description: "Search file contents with a regular expression (JavaScript syntax). Searches path (a file or directory, default: the working directory), " +
21
- `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. ` +
22
- `output_mode: "content" (default) returns "file:line:text" for matches and "file-line-text" for context lines, at most ${MAX_MATCHES} matches; ` +
23
- `"files" returns only the paths of matching files; "count" returns "file:count". ` +
24
- `context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode. ` +
25
- "head_limit keeps only the first that many lines of the output.",
26
- inputSchema: {
27
- type: "object",
28
- properties: {
29
- pattern: { type: "string" },
30
- path: { type: "string" },
31
- include: { type: "string" },
32
- ignore_case: { type: "boolean" },
33
- // files_with_matches 是 ripgrep / Claude Code 的叫法,很多模型会这样传,当作 files
34
- output_mode: { type: "string", enum: ["content", "files", "count", "files_with_matches"] },
35
- context: { type: "integer" },
36
- // head_limit、glob 也是 ripgrep / Claude Code 的叫法;不接受的话模型要多花一轮去掉它们重发。
37
- // 有的模型把数字写成字符串("30"),也接受
38
- head_limit: { type: ["integer", "string"] },
39
- glob: { type: "string" },
40
- },
41
- required: ["pattern"],
42
- additionalProperties: false,
43
- },
44
- effect: "read",
45
- concurrency: "safe",
46
- idempotent: true,
47
- async execute(input, { signal }) {
48
- const { pattern, path: p = ".", glob, include = glob, ignore_case = false, output_mode = "content", context = 0, head_limit } = input;
49
- const mode = output_mode === "files_with_matches" ? "files" : output_mode;
50
- let re;
51
- try {
52
- re = new RegExp(pattern, ignore_case ? "i" : "");
53
- }
54
- catch (err) {
55
- return { content: `invalid regular expression: ${err.message}`, isError: true };
56
- }
57
- const search = {
58
- root: path.resolve(cwd, p),
59
- re,
60
- pattern,
61
- ignoreCase: ignore_case,
62
- include,
63
- context: mode === "content" ? Math.min(Math.max(context, 0), MAX_CONTEXT) : 0,
64
- mode,
65
- signal,
66
- };
67
- let found;
68
- if (rg) {
69
- const result = await ripgrep(rg, search);
70
- if (result === "missing")
71
- rg = null;
72
- else
73
- found = result;
74
- }
75
- found ??= await jsGrep(search);
76
- const lines = format(cwd, found, search).split("\n");
77
- const limit = Number(head_limit);
78
- if (limit > 0 && lines.length > limit)
79
- lines.splice(limit, Infinity, `(showing the first ${limit} of ${lines.length} lines)`);
80
- return { content: lines.join("\n") };
81
- },
82
- };
11
+ let rg = opts.rg === undefined ? "rg" : opts.rg;
12
+ return {
13
+ name: "grep",
14
+ description: "Search file contents with a regular expression (JavaScript syntax). Searches path (a file or directory, default: the working directory), " + `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. ` + `output_mode: "content" (default) returns "file:line:text" for matches and "file-line-text" for context lines, at most ${MAX_MATCHES} matches; ` + `"files" returns only the paths of matching files; "count" returns "file:count". ` + `context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode. ` + "head_limit keeps only the first that many lines of the output.",
15
+ inputSchema: {
16
+ type: "object",
17
+ properties: {
18
+ pattern: { type: "string" },
19
+ path: { type: "string" },
20
+ include: { type: "string" },
21
+ ignore_case: { type: "boolean" },
22
+ output_mode: { type: "string", enum: ["content", "files", "count", "files_with_matches"] },
23
+ context: { type: "integer" },
24
+ head_limit: { type: ["integer", "string"] },
25
+ glob: { type: "string" }
26
+ },
27
+ required: ["pattern"],
28
+ additionalProperties: false
29
+ },
30
+ effect: "read",
31
+ concurrency: "safe",
32
+ idempotent: true,
33
+ async execute(input, { signal }) {
34
+ const { pattern, path: p = ".", glob, include = glob, ignore_case = false, output_mode = "content", context = 0, head_limit } = input;
35
+ const mode = output_mode === "files_with_matches" ? "files" : output_mode;
36
+ let re;
37
+ try {
38
+ re = new RegExp(pattern, ignore_case ? "i" : "");
39
+ } catch (err) {
40
+ return { content: `invalid regular expression: ${err.message}`, isError: true };
41
+ }
42
+ const search = {
43
+ root: path.resolve(cwd, p),
44
+ re,
45
+ pattern,
46
+ ignoreCase: ignore_case,
47
+ include,
48
+ context: mode === "content" ? Math.min(Math.max(context, 0), MAX_CONTEXT) : 0,
49
+ mode,
50
+ signal
51
+ };
52
+ let found;
53
+ if (rg) {
54
+ const result = await ripgrep(rg, search);
55
+ if (result === "missing")
56
+ rg = null;
57
+ else
58
+ found = result;
59
+ }
60
+ found ??= await jsGrep(search);
61
+ const lines = format(cwd, found, search).split(`
62
+ `);
63
+ const limit = Number(head_limit);
64
+ if (limit > 0 && lines.length > limit)
65
+ lines.splice(limit, 1 / 0, `(showing the first ${limit} of ${lines.length} lines)`);
66
+ return { content: lines.join(`
67
+ `) };
68
+ }
69
+ };
83
70
  }
84
71
  function format(cwd, { files, truncated }, s) {
85
- if (files.length === 0)
86
- return "No matches";
87
- const shown = (f) => display(cwd, f.file);
88
- if (s.mode === "files") {
89
- const out = files.slice(0, MAX_FILES).map(shown);
90
- if (files.length > MAX_FILES || truncated)
91
- out.push(`(stopped after ${MAX_FILES} files; narrow the search)`);
92
- return out.join("\n");
93
- }
94
- if (s.mode === "count") {
95
- const out = files.slice(0, MAX_FILES).map((f) => `${shown(f)}:${f.count}`);
96
- if (files.length > MAX_FILES || truncated)
97
- out.push(`(stopped after ${MAX_FILES} files; narrow the search)`);
98
- return out.join("\n");
99
- }
100
- const out = [];
101
- let matches = 0;
102
- for (const f of files) {
103
- const name = shown(f);
104
- let prev;
105
- for (const l of f.lines) {
106
- if (l.match && matches >= MAX_MATCHES) {
107
- truncated = true;
108
- break;
109
- }
110
- if (s.context > 0 && prev !== undefined && l.n > prev + 1)
111
- out.push("--");
112
- if (s.context > 0 && prev === undefined && out.length > 0)
113
- out.push("--");
114
- const text = l.text.length > MAX_LINE_CHARS ? l.text.slice(0, MAX_LINE_CHARS) + "…" : l.text;
115
- out.push(`${name}${l.match ? ":" : "-"}${l.n}${l.match ? ":" : "-"}${text}`);
116
- if (l.match)
117
- matches++;
118
- prev = l.n;
119
- }
120
- if (matches >= MAX_MATCHES && truncated)
121
- break;
72
+ if (files.length === 0)
73
+ return "No matches";
74
+ const shown = (f) => display(cwd, f.file);
75
+ if (s.mode === "files") {
76
+ const out = files.slice(0, MAX_FILES).map(shown);
77
+ if (files.length > MAX_FILES || truncated)
78
+ out.push(`(stopped after ${MAX_FILES} files; narrow the search)`);
79
+ return out.join(`
80
+ `);
81
+ }
82
+ if (s.mode === "count") {
83
+ const out = files.slice(0, MAX_FILES).map((f) => `${shown(f)}:${f.count}`);
84
+ if (files.length > MAX_FILES || truncated)
85
+ out.push(`(stopped after ${MAX_FILES} files; narrow the search)`);
86
+ return out.join(`
87
+ `);
88
+ }
89
+ const out = [];
90
+ let matches = 0;
91
+ for (const f of files) {
92
+ const name = shown(f);
93
+ let prev;
94
+ for (const l of f.lines) {
95
+ if (l.match && matches >= MAX_MATCHES) {
96
+ truncated = true;
97
+ break;
98
+ }
99
+ if (s.context > 0 && prev !== undefined && l.n > prev + 1)
100
+ out.push("--");
101
+ if (s.context > 0 && prev === undefined && out.length > 0)
102
+ out.push("--");
103
+ const text = l.text.length > MAX_LINE_CHARS ? l.text.slice(0, MAX_LINE_CHARS) + "…" : l.text;
104
+ out.push(`${name}${l.match ? ":" : "-"}${l.n}${l.match ? ":" : "-"}${text}`);
105
+ if (l.match)
106
+ matches++;
107
+ prev = l.n;
122
108
  }
123
- // 末尾可能是最后一个命中之后多出来的上下文行,保留也无妨
124
- if (truncated)
125
- out.push(`(stopped after ${MAX_MATCHES} matches; narrow the search)`);
126
- return out.join("\n");
109
+ if (matches >= MAX_MATCHES && truncated)
110
+ break;
111
+ }
112
+ if (truncated)
113
+ out.push(`(stopped after ${MAX_MATCHES} matches; narrow the search)`);
114
+ return out.join(`
115
+ `);
127
116
  }
128
- /** 达到这个数量就够用了,不用再搜下去 */
129
117
  const enough = (s, files, matches) => s.mode === "content" ? matches > MAX_MATCHES : files.length > MAX_FILES;
130
- // ---------- ripgrep ----------
131
- /** ripgrep 不存在时返回 "missing";正则语法 ripgrep 不支持时返回 undefined,由调用方改用 JS 搜索 */
132
118
  async function ripgrep(rg, s) {
133
- const args = ["--json", "--sort", "path", "--hidden", "--glob", "!.git", "--glob", "!node_modules", "--max-filesize", `${MAX_FILE_BYTES}`];
134
- if (s.ignoreCase)
135
- args.push("--ignore-case");
136
- if (s.context > 0)
137
- args.push("--context", String(s.context));
138
- if (s.include)
139
- args.push("--glob", s.include);
140
- args.push("--regexp", s.pattern, "--", s.root);
141
- let proc;
142
- try {
143
- proc = await spawn([rg, ...args]);
144
- }
145
- catch {
146
- return "missing";
147
- }
148
- const kill = () => proc.kill();
149
- s.signal.addEventListener("abort", kill, { once: true });
150
- const files = [];
151
- let matches = 0;
152
- let stopped = false;
153
- try {
154
- const stderr = text(proc.stderr);
155
- const decoder = new TextDecoder();
156
- let buf = "";
157
- const handle = (line) => {
158
- if (!line)
159
- return;
160
- const ev = JSON.parse(line);
161
- if (ev.type !== "match" && ev.type !== "context")
162
- return;
163
- const file = ev.data.path?.text;
164
- const text = ev.data.lines?.text;
165
- // 不是合法 UTF-8 的路径或内容(ripgrep 给的是 bytes),跳过
166
- if (file === undefined || text === undefined || ev.data.line_number === undefined)
167
- return;
168
- const full = path.resolve(file);
169
- let hits = files.at(-1);
170
- if (hits?.file !== full) {
171
- hits = { file: full, count: 0, lines: [] };
172
- files.push(hits);
173
- }
174
- const match = ev.type === "match";
175
- if (match) {
176
- hits.count++;
177
- matches++;
178
- }
179
- if (s.mode === "content")
180
- hits.lines.push({ n: ev.data.line_number, text: text.replace(/\r?\n$/, ""), match });
181
- };
182
- for await (const chunk of proc.stdout) {
183
- buf += decoder.decode(chunk, { stream: true });
184
- let nl;
185
- while ((nl = buf.indexOf("\n")) >= 0) {
186
- handle(buf.slice(0, nl));
187
- buf = buf.slice(nl + 1);
188
- }
189
- // count 模式要数完每个文件,只有文件数超了才停
190
- if (enough(s, files, matches)) {
191
- stopped = true;
192
- proc.kill();
193
- break;
194
- }
119
+ const first = await ripgrepOnce(rg, s, false);
120
+ return typeof first === "object" && first.truncated ? ripgrepOnce(rg, s, true) : first;
121
+ }
122
+ async function ripgrepOnce(rg, s, sorted) {
123
+ const args = [...sorted ? ["--sort", "path"] : [], "--hidden", "--glob", "!.git", "--glob", "!node_modules", "--max-filesize", `${MAX_FILE_BYTES}`];
124
+ if (s.mode === "content")
125
+ args.push("--json");
126
+ else if (s.mode === "files")
127
+ args.push("--files-with-matches", "--null");
128
+ else
129
+ args.push("--count", "--with-filename", "--null");
130
+ if (s.ignoreCase)
131
+ args.push("--ignore-case");
132
+ if (s.context > 0)
133
+ args.push("--context", String(s.context));
134
+ if (s.include)
135
+ args.push("--glob", s.include);
136
+ args.push("--regexp", s.pattern, "--", s.root);
137
+ let proc;
138
+ try {
139
+ proc = await spawn([rg, ...args]);
140
+ } catch {
141
+ return "missing";
142
+ }
143
+ const kill = () => proc.kill();
144
+ s.signal.addEventListener("abort", kill, { once: true });
145
+ const files = [];
146
+ let matches = 0;
147
+ let stopped = false;
148
+ try {
149
+ const stderr = text(proc.stderr);
150
+ const decoder = new TextDecoder;
151
+ let buf = "";
152
+ const handle = (line) => {
153
+ if (!line)
154
+ return;
155
+ const ev = JSON.parse(line);
156
+ if (ev.type !== "match" && ev.type !== "context")
157
+ return;
158
+ const file = ev.data.path?.text;
159
+ const text = ev.data.lines?.text;
160
+ if (file === undefined || text === undefined || ev.data.line_number === undefined)
161
+ return;
162
+ const full = path.resolve(file);
163
+ let hits = files.at(-1);
164
+ if (hits?.file !== full) {
165
+ hits = { file: full, count: 0, lines: [] };
166
+ files.push(hits);
167
+ }
168
+ const match = ev.type === "match";
169
+ if (match) {
170
+ hits.count++;
171
+ matches++;
172
+ }
173
+ hits.lines.push({ n: ev.data.line_number, text: text.replace(/\r?\n$/, ""), match });
174
+ };
175
+ const add = (file, count) => {
176
+ if (!file.includes("�"))
177
+ files.push({ file: path.resolve(file), count, lines: [] });
178
+ };
179
+ const drain = () => {
180
+ for (;; ) {
181
+ const end = buf.indexOf(s.mode === "content" ? `
182
+ ` : "\x00");
183
+ if (end < 0)
184
+ return;
185
+ let next = end + 1;
186
+ if (s.mode === "content")
187
+ handle(buf.slice(0, end));
188
+ else if (s.mode === "files")
189
+ add(buf.slice(0, end), 1);
190
+ else {
191
+ const nl = buf.indexOf(`
192
+ `, end);
193
+ if (nl < 0)
194
+ return;
195
+ add(buf.slice(0, end), Number(buf.slice(end + 1, nl)));
196
+ next = nl + 1;
195
197
  }
196
- if (!stopped)
197
- handle(buf);
198
- const [code, err] = await Promise.all([proc.exited, stderr]);
199
- s.signal.throwIfAborted();
200
- // 1:没有命中;2:出错,但部分文件出错(例如没有权限)时其余结果仍然有效
201
- if (!stopped && code === 2 && /regex parse error|error parsing regex|look-?around|backreference/i.test(err))
202
- return undefined;
203
- return { files, truncated: stopped };
204
- }
205
- finally {
206
- s.signal.removeEventListener("abort", kill);
198
+ buf = buf.slice(next);
199
+ }
200
+ };
201
+ for await (const chunk of proc.stdout) {
202
+ buf += decoder.decode(chunk, { stream: true });
203
+ drain();
204
+ if (enough(s, files, matches)) {
205
+ stopped = true;
206
+ proc.kill();
207
+ break;
208
+ }
207
209
  }
210
+ if (!stopped && s.mode === "content")
211
+ handle(buf);
212
+ const [code, err] = await Promise.all([proc.exited, stderr]);
213
+ s.signal.throwIfAborted();
214
+ if (!stopped && code === 2 && /regex parse error|error parsing regex|look-?around|backreference/i.test(err))
215
+ return;
216
+ files.sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
217
+ return { files, truncated: stopped };
218
+ } finally {
219
+ s.signal.removeEventListener("abort", kill);
220
+ }
208
221
  }
209
- // ---------- JS ----------
210
- /** 同时读几个文件。逐个等 stat、readFile 时,几万个文件的仓库要好几秒(多数时间花在等 IO 上) */
211
222
  const READ_AHEAD = 16;
212
- /** 读出可以搜的文本;不存在(git 列出的文件可能已在工作区删除)、太大、二进制的返回 undefined */
213
223
  async function readSearchable(file) {
214
- const info = await statOrUndefined(file);
215
- if (!info?.isFile() || info.size > MAX_FILE_BYTES)
216
- return undefined;
217
- const buf = await readFile(file).catch(() => undefined);
218
- return buf && !buf.includes(0) ? buf : undefined;
224
+ const info = await statOrUndefined(file);
225
+ if (!info?.isFile() || info.size > MAX_FILE_BYTES)
226
+ return;
227
+ const buf = await readFile(file).catch(() => {
228
+ return;
229
+ });
230
+ return buf && !buf.includes(0) ? buf : undefined;
219
231
  }
220
- /** 按 items 的顺序产出 fn 的结果,最多 n 个同时进行;调用方提前停止时,已经开始的读取随它结束 */
221
232
  async function* ordered(items, n, fn) {
222
- const pending = [];
223
- for await (const item of items) {
224
- const result = fn(item);
225
- // 先挂上处理,免得提前停止时没人等的 Promise 报 unhandled rejection
226
- result.catch(() => { });
227
- pending.push({ item, result });
228
- if (pending.length >= n) {
229
- const head = pending.shift();
230
- yield [head.item, await head.result];
231
- }
233
+ const pending = [];
234
+ for await (const item of items) {
235
+ const result = fn(item);
236
+ result.catch(() => {});
237
+ pending.push({ item, result });
238
+ if (pending.length >= n) {
239
+ const head = pending.shift();
240
+ yield [head.item, await head.result];
232
241
  }
233
- for (const p of pending)
234
- yield [p.item, await p.result];
242
+ }
243
+ for (const p of pending)
244
+ yield [p.item, await p.result];
235
245
  }
236
246
  async function jsGrep(s) {
237
- // 和 ripgrep 的 --glob 一致:不含 / 的模式("*.ts")匹配任意深度的文件名
238
- const filter = s.include ? globMatcher(s.include.includes("/") ? s.include : `**/${s.include}`) : undefined;
239
- const files = [];
240
- let matches = 0;
241
- const single = (await stat(s.root)).isFile();
242
- const candidates = single ? [s.root] : await listFiles(s.root, s.signal);
243
- const sorted = Array.isArray(candidates) ? [...candidates].sort() : candidates;
244
- const wanted = async function* () {
245
- for await (const file of sorted) {
246
- if (filter && !single && !filter(path.relative(s.root, file).split(path.sep).join("/")))
247
- continue;
248
- yield file;
249
- }
250
- };
251
- for await (const [file, buf] of ordered(wanted(), READ_AHEAD, readSearchable)) {
252
- s.signal.throwIfAborted();
253
- if (!buf)
254
- continue;
255
- const all = buf.toString("utf8").split(/\r?\n/);
256
- if (all.at(-1) === "")
257
- all.pop();
258
- const hits = { file, count: 0, lines: [] };
259
- let last = -1;
260
- for (const [i, text] of all.entries()) {
261
- if (!s.re.test(text))
262
- continue;
263
- hits.count++;
264
- matches++;
265
- if (s.mode !== "content")
266
- continue;
267
- for (let j = Math.max(i - s.context, last + 1); j <= Math.min(i + s.context, all.length - 1); j++) {
268
- hits.lines.push({ n: j + 1, text: all[j], match: j === i || s.re.test(all[j]) });
269
- last = j;
270
- }
271
- if (matches > MAX_MATCHES)
272
- break;
273
- }
274
- if (hits.count > 0)
275
- files.push(hits);
276
- if (enough(s, files, matches))
277
- return { files, truncated: true };
247
+ const filter = s.include ? globMatcher(s.include.includes("/") ? s.include : `**/${s.include}`) : undefined;
248
+ const files = [];
249
+ let matches = 0;
250
+ const single = (await stat(s.root)).isFile();
251
+ const candidates = single ? [s.root] : await listFiles(s.root, s.signal);
252
+ const sorted = Array.isArray(candidates) ? [...candidates].sort() : candidates;
253
+ const wanted = async function* () {
254
+ for await (const file of sorted) {
255
+ if (filter && !single && !filter(path.relative(s.root, file).split(path.sep).join("/")))
256
+ continue;
257
+ yield file;
258
+ }
259
+ };
260
+ for await (const [file, buf] of ordered(wanted(), READ_AHEAD, readSearchable)) {
261
+ s.signal.throwIfAborted();
262
+ if (!buf)
263
+ continue;
264
+ const all = buf.toString("utf8").split(/\r?\n/);
265
+ if (all.at(-1) === "")
266
+ all.pop();
267
+ const hits = { file, count: 0, lines: [] };
268
+ let last = -1;
269
+ for (const [i, text] of all.entries()) {
270
+ if (!s.re.test(text))
271
+ continue;
272
+ hits.count++;
273
+ matches++;
274
+ if (s.mode !== "content")
275
+ continue;
276
+ for (let j = Math.max(i - s.context, last + 1);j <= Math.min(i + s.context, all.length - 1); j++) {
277
+ hits.lines.push({ n: j + 1, text: all[j], match: j === i || s.re.test(all[j]) });
278
+ last = j;
279
+ }
280
+ if (matches > MAX_MATCHES)
281
+ break;
278
282
  }
279
- return { files, truncated: false };
283
+ if (hits.count > 0)
284
+ files.push(hits);
285
+ if (enough(s, files, matches))
286
+ return { files, truncated: true };
287
+ }
288
+ return { files, truncated: false };
280
289
  }
@@ -1,39 +1,25 @@
1
- // jade/fs:文件工具 read_file、write_file、edit_file、multi_edit、list_dir、glob、grep。
2
1
  import { definePlugin } from "@uncarved/jade-api";
3
2
  import { fsTools, SeenFiles } from "./fs.js";
4
3
  import { fsRenderers } from "./renderers.js";
5
4
  export default definePlugin({
6
- process(ctx) {
7
- // 显示方式和会话无关,登记一次留到进程结束;没有 renderers@1(例如 print)时用前端的默认显示
8
- const renderers = ctx.service("renderers@1");
9
- if (renderers)
10
- for (const r of fsRenderers(ctx.cwd))
11
- renderers.tool(r);
12
- },
13
- session(ctx) {
14
- // 数模型调用的次数:同一次回复里先读后改的,改的内容是看到读取结果之前写好的。
15
- // 同时按最终发给模型的消息让被压缩(jade/compact 总结或清理)掉的读取失效:那些文件要重新读才能改
16
- const responses = { calls: 0 };
17
- const seen = new SeenFiles();
18
- ctx.kernel.hook({
19
- kind: "transform",
20
- point: "model.before",
21
- fn: (request) => {
22
- responses.calls++;
23
- seen.prune(request.messages);
24
- },
25
- });
26
- for (const tool of fsTools(ctx.cwd, { responses, seen }))
27
- ctx.kernel.tool(tool);
28
- // 嵌套 Agent(例如 jade/task 的子 Agent)的只读工具:另一套实例,它读过的文件不算主会话读过
29
- // jade/tools 被隔离时它的服务已失效:嵌套 Agent 没有文件工具,文件工具本身照常
30
- try {
31
- const shared = ctx.service("tools@1");
32
- if (shared)
33
- for (const tool of fsTools(ctx.cwd))
34
- if (tool.effect === "read")
35
- shared.register(tool);
36
- }
37
- catch { }
38
- },
5
+ process(ctx) {
6
+ const renderers = ctx.service("renderers@1");
7
+ if (renderers)
8
+ for (const r of fsRenderers(ctx.cwd))
9
+ renderers.tool(r);
10
+ },
11
+ session(ctx) {
12
+ const responses = { calls: 0 };
13
+ const seen = new SeenFiles;
14
+ ctx.kernel.hook({
15
+ kind: "transform",
16
+ point: "model.before",
17
+ fn: (request) => {
18
+ responses.calls++;
19
+ seen.prune(request.messages);
20
+ }
21
+ });
22
+ for (const tool of fsTools(ctx.cwd, { responses, seen }))
23
+ ctx.kernel.tool(tool);
24
+ }
39
25
  });
@@ -4,7 +4,6 @@
4
4
  "api": "^1",
5
5
  "entry": "./index.js",
6
6
  "optional": [
7
- "renderers@1",
8
- "tools@1"
7
+ "renderers@1"
9
8
  ]
10
9
  }