@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,135 @@
1
+ // jade/cost:按配置的单价把会话的 token 用量换算成钱,显示在状态栏上;/cost 列出每个模型用了多少。
2
+ //
3
+ // 单价不内置(价格会变,兼容服务上的模型名也各不相同),写在 $JADE_HOME/config.json,单位是每百万 token(下面的数字只是示例):
4
+ //
5
+ // { "jade/cost": { "prices": { "claude-opus": { "input": 15, "output": 75, "cacheRead": 1.5, "cacheWrite": 18.75 } } } }
6
+ //
7
+ // 键是模型名或它的前缀(最长的前缀算数);cacheRead、cacheWrite 不写时按 input 算。没有配置单价的模型只计 token,不计钱。
8
+ // 用量来自日志:模型的每次回复,以及插件自己发的请求(压缩的总结、auto 模式的审查、子 Agent),后者不知道用的是哪个模型,
9
+ // 按会话当前的模型算。状态栏的合计每轮结束时记进 derived,恢复会话后接着算;/cost 每次从整份日志重算。
10
+ import { definePlugin } from "@uncarved/jade-api";
11
+ const KEY = "jade/cost/usage";
12
+ /** 插件自己发的请求没有记模型名时记在这个名字下,算钱时按当前模型 */
13
+ const UNKNOWN = "";
14
+ /** 配置里的 prices;写错的条目忽略 */
15
+ export function parsePrices(value) {
16
+ const out = {};
17
+ if (!value || typeof value !== "object" || Array.isArray(value))
18
+ return out;
19
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
20
+ for (const [model, raw] of Object.entries(value)) {
21
+ const p = (raw ?? {});
22
+ const input = num(p.input);
23
+ const output = num(p.output);
24
+ if (input === undefined || output === undefined)
25
+ continue;
26
+ const cacheRead = num(p.cacheRead);
27
+ const cacheWrite = num(p.cacheWrite);
28
+ out[model] = { input, output, ...(cacheRead !== undefined ? { cacheRead } : {}), ...(cacheWrite !== undefined ? { cacheWrite } : {}) };
29
+ }
30
+ return out;
31
+ }
32
+ /** 模型的单价:名字完全相同的,否则最长的前缀 */
33
+ export function priceOf(prices, model) {
34
+ let best;
35
+ for (const key of Object.keys(prices))
36
+ if (model.startsWith(key) && (best === undefined || key.length > best.length))
37
+ best = key;
38
+ return best === undefined ? undefined : prices[best];
39
+ }
40
+ /** 一份用量按单价是多少钱。inputTokens 含缓存命中和写入的部分(Usage 的约定) */
41
+ export function costOf(u, p) {
42
+ const plain = Math.max(0, u.inputTokens - u.cacheReadTokens - u.cacheWriteTokens);
43
+ return (plain * p.input + u.cacheReadTokens * (p.cacheRead ?? p.input) + u.cacheWriteTokens * (p.cacheWrite ?? p.input) + u.outputTokens * p.output) / 1_000_000;
44
+ }
45
+ /** 一个事件带来的用量和它的模型;不带用量的事件 undefined */
46
+ function usageIn(e) {
47
+ const usage = e.data?.usage;
48
+ if (!usage || typeof usage !== "object")
49
+ return undefined;
50
+ if (e.type === "model.responded")
51
+ return { model: e.origin.by === "model" ? e.origin.model : UNKNOWN, usage };
52
+ return e.origin.by === "plugin" ? { model: UNKNOWN, usage } : undefined;
53
+ }
54
+ function add(totals, model, u) {
55
+ const t = (totals[model] ??= { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 });
56
+ for (const k of Object.keys(t)) {
57
+ const v = u[k];
58
+ if (typeof v === "number" && Number.isFinite(v))
59
+ t[k] += v;
60
+ }
61
+ }
62
+ /** 合计的钱;一个有单价的模型都没有时 undefined */
63
+ function total(totals, prices, current) {
64
+ let sum;
65
+ for (const [model, u] of Object.entries(totals)) {
66
+ const p = priceOf(prices, model === UNKNOWN ? (current ?? "") : model);
67
+ if (p)
68
+ sum = (sum ?? 0) + costOf(u, p);
69
+ }
70
+ return sum;
71
+ }
72
+ const money = (n) => `$${n < 0.01 && n > 0 ? n.toFixed(4) : n.toFixed(2)}`;
73
+ const tokens = (n) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(2)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
74
+ export default definePlugin({
75
+ process(ctx) {
76
+ const prices = parsePrices(ctx.config.prices);
77
+ ctx.service("commands@1")?.register({
78
+ name: "cost",
79
+ description: "show this session's token usage per model, and what it cost at the configured prices",
80
+ instant: true,
81
+ async run(_args, { sessions }) {
82
+ const s = sessions.current;
83
+ if (!s)
84
+ return "No session is open.";
85
+ const totals = {};
86
+ for (const e of await s.history()) {
87
+ const u = usageIn(e);
88
+ if (u)
89
+ add(totals, u.model, u.usage);
90
+ }
91
+ const current = ctx.service("models@1")?.current()?.model;
92
+ const rows = Object.entries(totals).map(([model, u]) => {
93
+ const p = priceOf(prices, model === UNKNOWN ? (current ?? "") : model);
94
+ const cached = u.cacheReadTokens ? `, ${tokens(u.cacheReadTokens)} from cache` : "";
95
+ return `${model === UNKNOWN ? "plugin requests (compaction, review, sub-agents)" : model}: ${tokens(u.inputTokens)} in${cached}, ${tokens(u.outputTokens)} out${p ? ` · ${money(costOf(u, p))}` : ""}`;
96
+ });
97
+ if (rows.length === 0)
98
+ return "No model usage in this session yet.";
99
+ const sum = total(totals, prices, current);
100
+ const hint = `No price is configured for ${sum === undefined ? "these models" : "some of these models"}: add {"jade/cost": {"prices": {"<model name or prefix>": {"input": <$ per million tokens>, "output": <$>}}}} to ${ctx.home}/config.json`;
101
+ const unpriced = Object.keys(totals).some((m) => !priceOf(prices, m === UNKNOWN ? (current ?? "") : m));
102
+ return [...rows, ...(sum !== undefined ? [`Total: ${money(sum)}`] : []), ...(unpriced ? [hint] : [])].join("\n");
103
+ },
104
+ });
105
+ },
106
+ session(ctx) {
107
+ const prices = parsePrices(ctx.config.prices);
108
+ // 没有配置单价、或者前端没有状态栏:不用算
109
+ if (Object.keys(prices).length === 0 || !ctx.status)
110
+ return;
111
+ const models = ctx.service("models@1");
112
+ let totals;
113
+ const show = () => {
114
+ const sum = total(totals ?? {}, prices, models?.current()?.model);
115
+ ctx.status?.(sum === undefined ? undefined : money(sum));
116
+ };
117
+ ctx.kernel.hook({
118
+ kind: "observe",
119
+ point: "event",
120
+ fn: async (e, hook) => {
121
+ // 恢复的会话:从上次记下的合计接着算
122
+ totals ??= structuredClone(hook.derived[KEY] ?? {});
123
+ const u = usageIn(e);
124
+ if (u) {
125
+ add(totals, u.model, u.usage);
126
+ show();
127
+ }
128
+ else if (e.type === "turn.ended") {
129
+ show();
130
+ await hook.record(KEY, totals);
131
+ }
132
+ },
133
+ });
134
+ },
135
+ });
@@ -0,0 +1,16 @@
1
+ {
2
+ "id": "jade/cost",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.js",
6
+ "optional": [
7
+ "commands@1",
8
+ "models@1"
9
+ ],
10
+ "config": {
11
+ "prices": {
12
+ "default": {},
13
+ "description": "prices in $ per million tokens, by model name or name prefix: { \"<model>\": { \"input\": 3, \"output\": 15, \"cacheRead\": 0.3, \"cacheWrite\": 3.75 } }; models without a price are counted in tokens only"
14
+ }
15
+ }
16
+ }
@@ -0,0 +1,86 @@
1
+ // jade/custom-commands:把 Markdown 文件变成斜杠命令。常用的提示词写一次,之后 /名字 [参数] 就能发出去。
2
+ //
3
+ // 文件放在 $JADE_HOME/commands/<名字>.md(用户层)或 <工作目录>/.jade/commands/<名字>.md(项目层,随仓库分发)。
4
+ // 文件内容就是要发给模型的消息;$ARGUMENTS 换成命令后面的文字,没有这个占位符时参数接在最后。
5
+ // 开头可以有一段 frontmatter,description 显示在命令菜单里:
6
+ //
7
+ // ---
8
+ // description: review the staged changes
9
+ // ---
10
+ // Review the staged changes ($ARGUMENTS) ...
11
+ //
12
+ // 命令在启动时登记(新加的文件重启后生效),内容每次执行时重新读(改了马上生效)。
13
+ // 同名时用户层的优先;名字被别的插件的命令占用时不登记,告诉用户一次。
14
+ import { readdir, readFile } from "node:fs/promises";
15
+ import path from "node:path";
16
+ import { definePlugin } from "@uncarved/jade-api";
17
+ const MAX_DESCRIPTION = 80;
18
+ /** 拆出 frontmatter 里的 description 和正文 */
19
+ export function parseCommand(text) {
20
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
21
+ if (!m)
22
+ return { body: text.trim() };
23
+ const description = /^description:\s*(.+?)\s*$/m.exec(m[1])?.[1]?.replace(/^(["'])(.*)\1$/, "$2");
24
+ return { ...(description ? { description } : {}), body: text.slice(m[0].length).trim() };
25
+ }
26
+ /** 把参数放进正文:有 $ARGUMENTS 就替换,没有就接在最后 */
27
+ export function fill(body, args) {
28
+ const given = args.trim();
29
+ if (body.includes("$ARGUMENTS"))
30
+ return body.replaceAll("$ARGUMENTS", given);
31
+ return given ? `${body}\n\n${given}` : body;
32
+ }
33
+ async function markdownFiles(dir) {
34
+ try {
35
+ return (await readdir(dir)).filter((n) => n.toLowerCase().endsWith(".md")).sort();
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ }
41
+ export default definePlugin({
42
+ async process(ctx) {
43
+ const commands = ctx.require("commands@1");
44
+ const skipped = [];
45
+ const seen = new Set();
46
+ for (const [dir, layer] of [
47
+ [path.join(ctx.home, "commands"), "user"],
48
+ [path.join(ctx.cwd, ".jade", "commands"), "project"],
49
+ ]) {
50
+ for (const file of await markdownFiles(dir)) {
51
+ const name = file.slice(0, -3);
52
+ // 用户层的已经登记了同名的:项目层的不盖过它
53
+ if (seen.has(name.toLowerCase()))
54
+ continue;
55
+ const full = path.join(dir, file);
56
+ let description;
57
+ try {
58
+ description = parseCommand(await readFile(full, "utf8")).description;
59
+ }
60
+ catch {
61
+ continue;
62
+ }
63
+ const about = (description ?? `send ${layer === "user" ? full : path.join(".jade", "commands", file)}`).replace(/\s+/g, " ");
64
+ try {
65
+ commands.register({
66
+ name,
67
+ args: "[arguments]",
68
+ description: `${about.length > MAX_DESCRIPTION ? `${about.slice(0, MAX_DESCRIPTION)}…` : about} (${layer} command)`,
69
+ async run(args) {
70
+ const { body } = parseCommand(await readFile(full, "utf8"));
71
+ if (!body)
72
+ return `${full} is empty.`;
73
+ return { prompt: fill(body, args) };
74
+ },
75
+ });
76
+ seen.add(name.toLowerCase());
77
+ }
78
+ catch (e) {
79
+ skipped.push(`/${name} (${e instanceof Error ? e.message : String(e)})`);
80
+ }
81
+ }
82
+ }
83
+ if (skipped.length > 0)
84
+ ctx.service("ui@1")?.notify(`jade/custom-commands: not registered: ${skipped.join("; ")}`, "warning");
85
+ },
86
+ });
@@ -0,0 +1,12 @@
1
+ {
2
+ "id": "jade/custom-commands",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.js",
6
+ "requires": [
7
+ "commands@1"
8
+ ],
9
+ "optional": [
10
+ "ui@1"
11
+ ]
12
+ }
@@ -0,0 +1,89 @@
1
+ // jade/editor:Ctrl+G 把输入框里的文字交给 $EDITOR 编辑,存盘退出后换回输入框。
2
+ //
3
+ // 终端编辑器(vim、nano)要独占终端:经 ui@1 的 suspend 让前端把终端让出来,编辑器退出后前端重新接管。
4
+ // 图形编辑器("code --wait")不需要终端,但走同一条路也没有坏处。前端不提供 suspend 或没有输入框时做不了,提示一句。
5
+ import { spawn } from "node:child_process";
6
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { definePlugin } from "@uncarved/jade-api";
10
+ const DEFAULT_KEY = "ctrl+g";
11
+ /** 用哪个编辑器:配置的 editor,否则 $VISUAL、$EDITOR,都没有时 vi(Windows 上是 notepad) */
12
+ export function editorCommand(configured, env = process.env) {
13
+ if (typeof configured === "string" && configured.trim())
14
+ return configured.trim();
15
+ return env.VISUAL?.trim() || env.EDITOR?.trim() || (process.platform === "win32" ? "notepad" : "vi");
16
+ }
17
+ /** 经 shell 启动编辑器(命令里可以带参数,例如 "code --wait"),等它退出;返回退出码 */
18
+ function run(command, file) {
19
+ return new Promise((resolve, reject) => {
20
+ const child = spawn(`${command} "${file}"`, { stdio: "inherit", shell: true });
21
+ child.on("error", reject);
22
+ child.on("exit", (code) => resolve(code));
23
+ });
24
+ }
25
+ /** 正在显示的会话的输入框:会话级的 ctx 才有,按键是进程级注册的 */
26
+ let input;
27
+ /** 编辑器开着的时候再按一次不再开一个 */
28
+ let editing = false;
29
+ /** 按键没注册上的原因(被别的插件占了、配置写错了):第一个会话打开时告诉用户一次 */
30
+ let noKey;
31
+ export default definePlugin({
32
+ process(ctx) {
33
+ const key = typeof ctx.config.key === "string" && ctx.config.key ? ctx.config.key : DEFAULT_KEY;
34
+ const binding = {
35
+ key,
36
+ description: "edit the input in $EDITOR",
37
+ async run() {
38
+ const ui = ctx.service("ui@1");
39
+ const draft = input;
40
+ if (!ui?.suspend || !draft)
41
+ return ui?.notify("this front end cannot hand the terminal to an editor", "warning");
42
+ if (editing)
43
+ return;
44
+ editing = true;
45
+ const command = editorCommand(ctx.config.editor);
46
+ const dir = await mkdtemp(path.join(os.tmpdir(), "jade-edit-"));
47
+ // .md:编辑器按 Markdown 高亮,消息多半就是 Markdown
48
+ const file = path.join(dir, "message.md");
49
+ try {
50
+ await writeFile(file, draft.text());
51
+ const code = await ui.suspend(() => run(command, file));
52
+ if (code !== 0)
53
+ return ui.notify(`${command} exited with code ${code}; the input was left as it was`, "warning");
54
+ // 编辑器存盘时加的最后一个换行不算
55
+ draft.set((await readFile(file, "utf8")).replace(/\r?\n$/, ""));
56
+ }
57
+ catch (e) {
58
+ ui.notify(`could not edit the input with ${command}: ${e instanceof Error ? e.message : String(e)}`, "error");
59
+ }
60
+ finally {
61
+ editing = false;
62
+ await rm(dir, { recursive: true, force: true }).catch(() => { });
63
+ }
64
+ },
65
+ };
66
+ // 键被别的插件占了不算这个插件坏了:只是没有这个键,换一个就行
67
+ noKey = undefined;
68
+ try {
69
+ ctx.require("keys@1").register(binding);
70
+ }
71
+ catch (e) {
72
+ noKey = `${e instanceof Error ? e.message : String(e)}; set {"jade/editor": {"key": "ctrl+<letter>"}} in config.json to use another key`;
73
+ }
74
+ },
75
+ async session(ctx) {
76
+ if (noKey) {
77
+ ctx.service("ui@1")?.notify(`jade/editor: ${noKey}`, "warning");
78
+ noKey = undefined;
79
+ }
80
+ const draft = ctx.input;
81
+ if (!draft)
82
+ return;
83
+ input = draft;
84
+ await ctx.effect(() => () => {
85
+ if (input === draft)
86
+ input = undefined;
87
+ });
88
+ },
89
+ });
@@ -0,0 +1,21 @@
1
+ {
2
+ "id": "jade/editor",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.js",
6
+ "requires": [
7
+ "keys@1"
8
+ ],
9
+ "optional": [
10
+ "ui@1"
11
+ ],
12
+ "config": {
13
+ "key": {
14
+ "default": "ctrl+g",
15
+ "description": "the key that opens the editor: ctrl+<letter> or alt+<letter or digit>"
16
+ },
17
+ "editor": {
18
+ "description": "the editor command ctrl+g opens the input in, for example \"vim\" or \"code --wait\"; default: $VISUAL, then $EDITOR, then vi (notepad on Windows)"
19
+ }
20
+ }
21
+ }
@@ -146,8 +146,12 @@ export function fsTools(cwd, opts = {}) {
146
146
  if (buf.subarray(0, 8000).includes(0)) {
147
147
  return { content: `${display(cwd, full)} is a binary file (${buf.length} bytes) and cannot be shown as text`, isError: true };
148
148
  }
149
- const text = buf.toString("utf8");
150
- remember(full, info, opts.responses?.calls ?? -1, ctx?.toolUseId);
149
+ // 不是 UTF-8 的文件(多半是 GBK)照样给模型看,但不算读过:改它会把原来的字节写坏
150
+ const strict = utf8(buf);
151
+ const text = strict ?? legacyText(buf);
152
+ const note = strict === undefined ? `\n(${notUtf8(display(cwd, full))})` : "";
153
+ if (strict !== undefined)
154
+ remember(full, info, opts.responses?.calls ?? -1, ctx?.toolUseId);
151
155
  if (text.length === 0)
152
156
  return { content: "(empty file)" };
153
157
  const lines = text.split(/\r?\n/);
@@ -170,9 +174,9 @@ export function fsTools(cwd, opts = {}) {
170
174
  const body = out.join("\n");
171
175
  const end = start + out.length - 1;
172
176
  if (out.length < slice.length) {
173
- return { content: `${body}\n(output capped at about ${MAX_READ_CHARS} characters: showing lines ${start}-${end} of ${lines.length}; continue with offset ${end + 1})` };
177
+ return { content: `${body}\n(output capped at about ${MAX_READ_CHARS} characters: showing lines ${start}-${end} of ${lines.length}; continue with offset ${end + 1})${note}` };
174
178
  }
175
- return { content: end < lines.length ? `${body}\n(showing lines ${start}-${end} of ${lines.length})` : body };
179
+ return { content: (end < lines.length ? `${body}\n(showing lines ${start}-${end} of ${lines.length})` : body) + note };
176
180
  },
177
181
  };
178
182
  const writeFileTool = {
@@ -196,7 +200,9 @@ export function fsTools(cwd, opts = {}) {
196
200
  if (info?.isDirectory())
197
201
  return { content: `${display(cwd, full)} is a directory`, isError: true };
198
202
  // 同样内容重复写入(崩溃后重跑)不算覆盖别人的修改
199
- const before = info ? await readFile(full, "utf8") : null;
203
+ const before = info ? utf8(await readFile(full)) ?? undefined : null;
204
+ if (before === undefined)
205
+ return { content: notUtf8(display(cwd, full)), isError: true };
200
206
  // read_file 不显示换行风格和 BOM:覆盖已有文件时沿用原来的,否则整个文件每一行都算改了
201
207
  const content = before === null ? given : keepStyle(before, given);
202
208
  const problem = info && before !== null && before !== content ? staleness(full, info) : undefined;
@@ -218,7 +224,9 @@ export function fsTools(cwd, opts = {}) {
218
224
  if (!info) {
219
225
  return { content: seen.has(full) ? `${shown} no longer exists` : `${shown} does not exist; use write_file to create it`, isError: true };
220
226
  }
221
- const text = await readFile(full, "utf8");
227
+ const text = utf8(await readFile(full));
228
+ if (text === undefined)
229
+ return { content: notUtf8(shown), isError: true };
222
230
  const problem = staleness(full, info);
223
231
  if (problem)
224
232
  return { content: problem, isError: true };
@@ -353,6 +361,26 @@ export function applyEditsToText(text, edits, shown) {
353
361
  }
354
362
  return { text: next };
355
363
  }
364
+ /** 按 UTF-8 解码(BOM 留着);不是合法的 UTF-8 时 undefined */
365
+ export function utf8(buf) {
366
+ try {
367
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buf);
368
+ }
369
+ catch {
370
+ return undefined;
371
+ }
372
+ }
373
+ /** 不是 UTF-8 的文本只用来显示:按 GB18030(含 GBK)解码,运行时不支持时按 UTF-8 解码、坏的字节显示成 U+FFFD */
374
+ function legacyText(buf) {
375
+ try {
376
+ return new TextDecoder("gb18030").decode(buf);
377
+ }
378
+ catch {
379
+ return buf.toString("utf8");
380
+ }
381
+ }
382
+ const notUtf8 = (shown) => `${shown} is not valid UTF-8 (read_file shows it decoded as GB18030). write_file and edit_file only handle UTF-8 and would corrupt it, so they refuse it: ` +
383
+ "change it with a command that keeps its encoding, or ask the user before converting it to UTF-8.";
356
384
  /** text 里多数换行是 CRLF 时返回 "\r\n",多数是 LF 时返回 "\n",一样多或没有换行时返回 fallback */
357
385
  function eolOf(text, fallback) {
358
386
  const crlf = text.split("\r\n").length - 1;
@@ -21,7 +21,8 @@ export function grepTool(cwd, opts = {}) {
21
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
22
  `output_mode: "content" (default) returns "file:line:text" for matches and "file-line-text" for context lines, at most ${MAX_MATCHES} matches; ` +
23
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.`,
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.",
25
26
  inputSchema: {
26
27
  type: "object",
27
28
  properties: {
@@ -29,8 +30,13 @@ export function grepTool(cwd, opts = {}) {
29
30
  path: { type: "string" },
30
31
  include: { type: "string" },
31
32
  ignore_case: { type: "boolean" },
32
- output_mode: { type: "string", enum: ["content", "files", "count"] },
33
+ // files_with_matches 是 ripgrep / Claude Code 的叫法,很多模型会这样传,当作 files
34
+ output_mode: { type: "string", enum: ["content", "files", "count", "files_with_matches"] },
33
35
  context: { type: "integer" },
36
+ // head_limit、glob 也是 ripgrep / Claude Code 的叫法;不接受的话模型要多花一轮去掉它们重发。
37
+ // 有的模型把数字写成字符串("30"),也接受
38
+ head_limit: { type: ["integer", "string"] },
39
+ glob: { type: "string" },
34
40
  },
35
41
  required: ["pattern"],
36
42
  additionalProperties: false,
@@ -39,7 +45,8 @@ export function grepTool(cwd, opts = {}) {
39
45
  concurrency: "safe",
40
46
  idempotent: true,
41
47
  async execute(input, { signal }) {
42
- const { pattern, path: p = ".", include, ignore_case = false, output_mode = "content", context = 0 } = input;
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;
43
50
  let re;
44
51
  try {
45
52
  re = new RegExp(pattern, ignore_case ? "i" : "");
@@ -53,8 +60,8 @@ export function grepTool(cwd, opts = {}) {
53
60
  pattern,
54
61
  ignoreCase: ignore_case,
55
62
  include,
56
- context: output_mode === "content" ? Math.min(Math.max(context, 0), MAX_CONTEXT) : 0,
57
- mode: output_mode,
63
+ context: mode === "content" ? Math.min(Math.max(context, 0), MAX_CONTEXT) : 0,
64
+ mode,
58
65
  signal,
59
66
  };
60
67
  let found;
@@ -66,7 +73,11 @@ export function grepTool(cwd, opts = {}) {
66
73
  found = result;
67
74
  }
68
75
  found ??= await jsGrep(search);
69
- return { content: format(cwd, found, 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") };
70
81
  },
71
82
  };
72
83
  }
@@ -1,5 +1,5 @@
1
1
  // jade/fs:文件工具 read_file、write_file、edit_file、multi_edit、list_dir、glob、grep。
2
- import { definePlugin } from "../../dist/api.js";
2
+ import { definePlugin } from "@uncarved/jade-api";
3
3
  import { fsTools, SeenFiles } from "./fs.js";
4
4
  import { fsRenderers } from "./renderers.js";
5
5
  export default definePlugin({
@@ -25,14 +25,14 @@ export default definePlugin({
25
25
  });
26
26
  for (const tool of fsTools(ctx.cwd, { responses, seen }))
27
27
  ctx.kernel.tool(tool);
28
- // 子 Agent(jade/task)的只读工具:另一套实例,子 Agent 读过的文件不算主会话读过
29
- // jade/task 被隔离时它的服务已失效:子 Agent 没有文件工具,文件工具本身照常
28
+ // 嵌套 Agent(例如 jade/task 的子 Agent)的只读工具:另一套实例,它读过的文件不算主会话读过
29
+ // jade/tools 被隔离时它的服务已失效:嵌套 Agent 没有文件工具,文件工具本身照常
30
30
  try {
31
- const task = ctx.service("task@1");
32
- if (task)
31
+ const shared = ctx.service("tools@1");
32
+ if (shared)
33
33
  for (const tool of fsTools(ctx.cwd))
34
34
  if (tool.effect === "read")
35
- task.tool(tool);
35
+ shared.register(tool);
36
36
  }
37
37
  catch { }
38
38
  },
@@ -5,6 +5,6 @@
5
5
  "entry": "./index.js",
6
6
  "optional": [
7
7
  "renderers@1",
8
- "task@1"
8
+ "tools@1"
9
9
  ]
10
10
  }