@uncarved/jade 0.3.0 → 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 (207) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +482 -27
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +49 -24
  14. package/plugins/approval/policy.ts +48 -25
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +55 -12
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +10 -9
  50. package/plugins/models/index.ts +31 -4
  51. package/plugins/models/provider.ts +12 -1
  52. package/plugins/modes/index.ts +13 -2
  53. package/plugins/print/index.ts +7 -4
  54. package/plugins/prompts/index.ts +0 -0
  55. package/plugins/renderers/index.ts +10 -5
  56. package/plugins/repeats/index.ts +39 -9
  57. package/plugins/schedule/index.ts +2 -0
  58. package/plugins/screenshot/browser.ts +231 -0
  59. package/plugins/screenshot/index.ts +3 -2
  60. package/plugins/screenshot/tool.ts +27 -51
  61. package/plugins/sessions/index.ts +48 -2
  62. package/plugins/shell/index.ts +75 -22
  63. package/plugins/shell/plugin.json +1 -2
  64. package/plugins/shell/renderers.ts +9 -7
  65. package/plugins/shell/shell.ts +93 -34
  66. package/plugins/skills/index.ts +28 -19
  67. package/plugins/skills/project.ts +12 -7
  68. package/plugins/steer/index.ts +5 -4
  69. package/plugins/task/index.ts +81 -81
  70. package/plugins/task/plugin.json +5 -2
  71. package/plugins/task/style.ts +13 -14
  72. package/plugins/task/subagent.ts +67 -184
  73. package/plugins/todo/index.ts +39 -9
  74. package/plugins/tools/index.ts +57 -0
  75. package/plugins/tools/plugin.json +7 -0
  76. package/plugins/tui/frontend.ts +161 -87
  77. package/plugins/tui/index.ts +2 -3
  78. package/plugins/tui/mascot.ts +8 -7
  79. package/plugins/tui/mentions.ts +11 -80
  80. package/plugins/tui/plugin.json +1 -1
  81. package/plugins/tui/screen.ts +55 -5
  82. package/plugins/tui/transcript.ts +17 -7
  83. package/plugins/tui/tui.ts +356 -104
  84. package/plugins/tui/vendor.ts +1 -1
  85. package/plugins/undo/checkpoint.ts +5 -3
  86. package/plugins/undo/index.ts +43 -14
  87. package/plugins/undo/style.ts +13 -14
  88. package/plugins/web/index.ts +7 -18
  89. package/plugins/web/plugin.json +1 -1
  90. package/plugins-dist/approval/index.js +363 -414
  91. package/plugins-dist/approval/policy.js +395 -497
  92. package/plugins-dist/approval/review.js +132 -158
  93. package/plugins-dist/approval/schema.js +50 -55
  94. package/plugins-dist/ask/index.js +115 -129
  95. package/plugins-dist/budget/index.js +27 -31
  96. package/plugins-dist/checks/checks.js +293 -329
  97. package/plugins-dist/checks/index.js +119 -139
  98. package/plugins-dist/checks/plugin.json +2 -1
  99. package/plugins-dist/checks/project.js +57 -65
  100. package/plugins-dist/commands/index.js +47 -29
  101. package/plugins-dist/compact/compact.js +233 -249
  102. package/plugins-dist/compact/index.js +98 -95
  103. package/plugins-dist/compact/style.js +9 -14
  104. package/plugins-dist/completions/index.js +30 -0
  105. package/plugins-dist/completions/plugin.json +9 -0
  106. package/plugins-dist/continue/index.js +40 -52
  107. package/plugins-dist/copy/index.js +40 -0
  108. package/plugins-dist/copy/plugin.json +9 -0
  109. package/plugins-dist/cost/index.js +98 -115
  110. package/plugins-dist/custom-commands/index.js +55 -72
  111. package/plugins-dist/editor/index.js +64 -72
  112. package/plugins-dist/fs/diff.js +111 -124
  113. package/plugins-dist/fs/fs.js +426 -469
  114. package/plugins-dist/fs/grep.js +262 -244
  115. package/plugins-dist/fs/index.js +20 -34
  116. package/plugins-dist/fs/plugin.json +1 -2
  117. package/plugins-dist/fs/renderers.js +100 -112
  118. package/plugins-dist/fs/style.js +11 -15
  119. package/plugins-dist/fs/sys.js +31 -43
  120. package/plugins-dist/hooks/index.js +107 -127
  121. package/plugins-dist/keys/index.js +27 -31
  122. package/plugins-dist/mcp/index.js +271 -199
  123. package/plugins-dist/mcp/install.js +123 -137
  124. package/plugins-dist/mcp/mcp.js +638 -577
  125. package/plugins-dist/mcp/plugin.json +3 -1
  126. package/plugins-dist/mcp/project.js +98 -115
  127. package/plugins-dist/memory/index.js +83 -88
  128. package/plugins-dist/memory/memory.js +111 -128
  129. package/plugins-dist/memory/style.js +9 -14
  130. package/plugins-dist/mentions/attach.js +91 -99
  131. package/plugins-dist/mentions/candidates.js +49 -0
  132. package/plugins-dist/mentions/index.js +71 -81
  133. package/plugins-dist/mentions/plugin.json +2 -1
  134. package/plugins-dist/mentions/style.js +9 -14
  135. package/plugins-dist/models/config.js +29 -43
  136. package/plugins-dist/models/configure.js +392 -473
  137. package/plugins-dist/models/context.js +14 -22
  138. package/plugins-dist/models/index.js +182 -188
  139. package/plugins-dist/models/provider.js +243 -295
  140. package/plugins-dist/models/saved.js +59 -71
  141. package/plugins-dist/modes/index.js +138 -165
  142. package/plugins-dist/plugins/index.js +34 -34
  143. package/plugins-dist/print/index.js +192 -175
  144. package/plugins-dist/prompts/index.js +81 -89
  145. package/plugins-dist/prompts/notes.js +31 -37
  146. package/plugins-dist/prompts/prompts.js +155 -193
  147. package/plugins-dist/prompts/results.js +40 -53
  148. package/plugins-dist/prompts/sys.js +39 -50
  149. package/plugins-dist/renderers/index.js +32 -32
  150. package/plugins-dist/repeats/index.js +134 -151
  151. package/plugins-dist/schedule/cron.js +49 -56
  152. package/plugins-dist/schedule/index.js +229 -247
  153. package/plugins-dist/schedule/store.js +93 -109
  154. package/plugins-dist/scratch/index.js +12 -18
  155. package/plugins-dist/screenshot/browser.js +169 -0
  156. package/plugins-dist/screenshot/index.js +37 -45
  157. package/plugins-dist/screenshot/sys.js +53 -65
  158. package/plugins-dist/screenshot/tool.js +101 -151
  159. package/plugins-dist/sessions/index.js +149 -117
  160. package/plugins-dist/shell/index.js +117 -74
  161. package/plugins-dist/shell/plugin.json +1 -2
  162. package/plugins-dist/shell/renderers.js +28 -33
  163. package/plugins-dist/shell/service.js +17 -23
  164. package/plugins-dist/shell/shell.js +317 -320
  165. package/plugins-dist/shell/sys.js +64 -79
  166. package/plugins-dist/skills/index.js +193 -211
  167. package/plugins-dist/skills/install.js +122 -149
  168. package/plugins-dist/skills/project.js +65 -73
  169. package/plugins-dist/skills/skills.js +135 -171
  170. package/plugins-dist/steer/index.js +108 -125
  171. package/plugins-dist/suggest/index.js +235 -259
  172. package/plugins-dist/task/index.js +130 -148
  173. package/plugins-dist/task/plugin.json +5 -4
  174. package/plugins-dist/task/style.js +9 -14
  175. package/plugins-dist/task/subagent.js +156 -279
  176. package/plugins-dist/todo/index.js +79 -63
  177. package/plugins-dist/tools/index.js +43 -0
  178. package/plugins-dist/tools/plugin.json +9 -0
  179. package/plugins-dist/tui/editor.js +145 -160
  180. package/plugins-dist/tui/frontend.js +641 -655
  181. package/plugins-dist/tui/history.js +34 -37
  182. package/plugins-dist/tui/index.js +16 -18
  183. package/plugins-dist/tui/markdown.js +203 -247
  184. package/plugins-dist/tui/mascot.js +266 -353
  185. package/plugins-dist/tui/mentions.js +67 -144
  186. package/plugins-dist/tui/plugin.json +1 -2
  187. package/plugins-dist/tui/render.js +35 -45
  188. package/plugins-dist/tui/screen.js +197 -180
  189. package/plugins-dist/tui/transcript.js +436 -468
  190. package/plugins-dist/tui/tui.js +1554 -1645
  191. package/plugins-dist/tui/vendor.js +1388 -1088
  192. package/plugins-dist/undo/checkpoint.js +95 -118
  193. package/plugins-dist/undo/index.js +185 -192
  194. package/plugins-dist/undo/snapshot.js +83 -99
  195. package/plugins-dist/undo/style.js +9 -14
  196. package/plugins-dist/update/index.js +26 -28
  197. package/plugins-dist/web/env.js +55 -68
  198. package/plugins-dist/web/index.js +80 -110
  199. package/plugins-dist/web/plugin.json +1 -2
  200. package/plugins-dist/web/renderers.js +4 -5
  201. package/plugins-dist/web/web.js +514 -593
  202. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  203. package/sdk/python/jade_plugin.py +9 -2
  204. package/src/api.ts +1 -1
  205. package/src/host.ts +39 -4
  206. package/src/remote.ts +6 -1
  207. package/src/session.ts +489 -34
@@ -1,135 +1,118 @@
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
1
  import { definePlugin } from "@uncarved/jade-api";
11
2
  const KEY = "jade/cost/usage";
12
- /** 插件自己发的请求没有记模型名时记在这个名字下,算钱时按当前模型 */
13
3
  const UNKNOWN = "";
14
- /** 配置里的 prices;写错的条目忽略 */
15
4
  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
- }
5
+ const out = {};
6
+ if (!value || typeof value !== "object" || Array.isArray(value))
30
7
  return out;
8
+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined;
9
+ for (const [model, raw] of Object.entries(value)) {
10
+ const p = raw ?? {};
11
+ const input = num(p.input);
12
+ const output = num(p.output);
13
+ if (input === undefined || output === undefined)
14
+ continue;
15
+ const cacheRead = num(p.cacheRead);
16
+ const cacheWrite = num(p.cacheWrite);
17
+ out[model] = { input, output, ...cacheRead !== undefined ? { cacheRead } : {}, ...cacheWrite !== undefined ? { cacheWrite } : {} };
18
+ }
19
+ return out;
31
20
  }
32
- /** 模型的单价:名字完全相同的,否则最长的前缀 */
33
21
  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];
22
+ let best;
23
+ for (const key of Object.keys(prices))
24
+ if (model.startsWith(key) && (best === undefined || key.length > best.length))
25
+ best = key;
26
+ return best === undefined ? undefined : prices[best];
39
27
  }
40
- /** 一份用量按单价是多少钱。inputTokens 含缓存命中和写入的部分(Usage 的约定) */
41
28
  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;
29
+ const plain = Math.max(0, u.inputTokens - u.cacheReadTokens - u.cacheWriteTokens);
30
+ return (plain * p.input + u.cacheReadTokens * (p.cacheRead ?? p.input) + u.cacheWriteTokens * (p.cacheWrite ?? p.input) + u.outputTokens * p.output) / 1e6;
44
31
  }
45
- /** 一个事件带来的用量和它的模型;不带用量的事件 undefined */
46
32
  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;
33
+ const usage = e.data?.usage;
34
+ if (!usage || typeof usage !== "object")
35
+ return;
36
+ if (e.type === "model.responded")
37
+ return { model: e.origin.by === "model" ? e.origin.model : UNKNOWN, usage };
38
+ return e.origin.by === "plugin" ? { model: UNKNOWN, usage } : undefined;
53
39
  }
54
40
  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
- }
41
+ const t = totals[model] ??= { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
42
+ for (const k of Object.keys(t)) {
43
+ const v = u[k];
44
+ if (typeof v === "number" && Number.isFinite(v))
45
+ t[k] += v;
46
+ }
61
47
  }
62
- /** 合计的钱;一个有单价的模型都没有时 undefined */
63
48
  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;
49
+ let sum;
50
+ for (const [model, u] of Object.entries(totals)) {
51
+ const p = priceOf(prices, model === UNKNOWN ? current ?? "" : model);
52
+ if (p)
53
+ sum = (sum ?? 0) + costOf(u, p);
54
+ }
55
+ return sum;
71
56
  }
72
57
  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));
58
+ const tokens = (n) => n >= 1e6 ? `${(n / 1e6).toFixed(2)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);
74
59
  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
- },
60
+ process(ctx) {
61
+ const prices = parsePrices(ctx.config.prices);
62
+ ctx.service("commands@1")?.register({
63
+ name: "cost",
64
+ description: "show this session's token usage per model, and what it cost at the configured prices",
65
+ instant: true,
66
+ async run(_args, { sessions }) {
67
+ const s = sessions.current;
68
+ if (!s)
69
+ return "No session is open.";
70
+ const totals = {};
71
+ for (const e of await s.history()) {
72
+ const u = usageIn(e);
73
+ if (u)
74
+ add(totals, u.model, u.usage);
75
+ }
76
+ const current = ctx.service("models@1")?.current()?.model;
77
+ const rows = Object.entries(totals).map(([model, u]) => {
78
+ const p = priceOf(prices, model === UNKNOWN ? current ?? "" : model);
79
+ const cached = u.cacheReadTokens ? `, ${tokens(u.cacheReadTokens)} from cache` : "";
80
+ return `${model === UNKNOWN ? "plugin requests (compaction, review, sub-agents)" : model}: ${tokens(u.inputTokens)} in${cached}, ${tokens(u.outputTokens)} out${p ? ` · ${money(costOf(u, p))}` : ""}`;
104
81
  });
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
- },
82
+ if (rows.length === 0)
83
+ return "No model usage in this session yet.";
84
+ const sum = total(totals, prices, current);
85
+ 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`;
86
+ const unpriced = Object.keys(totals).some((m) => !priceOf(prices, m === UNKNOWN ? current ?? "" : m));
87
+ return [...rows, ...sum !== undefined ? [`Total: ${money(sum)}`] : [], ...unpriced ? [hint] : []].join(`
88
+ `);
89
+ }
90
+ });
91
+ },
92
+ session(ctx) {
93
+ const prices = parsePrices(ctx.config.prices);
94
+ if (Object.keys(prices).length === 0 || !ctx.status)
95
+ return;
96
+ const models = ctx.service("models@1");
97
+ let totals;
98
+ const show = () => {
99
+ const sum = total(totals ?? {}, prices, models?.current()?.model);
100
+ ctx.status?.(sum === undefined ? undefined : money(sum));
101
+ };
102
+ ctx.kernel.hook({
103
+ kind: "observe",
104
+ point: "event",
105
+ fn: async (e, hook) => {
106
+ totals ??= structuredClone(hook.derived[KEY] ?? {});
107
+ const u = usageIn(e);
108
+ if (u) {
109
+ add(totals, u.model, u.usage);
110
+ show();
111
+ } else if (e.type === "turn.ended") {
112
+ show();
113
+ await hook.record(KEY, totals);
114
+ }
115
+ }
116
+ });
117
+ }
135
118
  });
@@ -1,86 +1,69 @@
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
1
  import { readdir, readFile } from "node:fs/promises";
15
2
  import path from "node:path";
16
3
  import { definePlugin } from "@uncarved/jade-api";
17
4
  const MAX_DESCRIPTION = 80;
18
- /** 拆出 frontmatter 里的 description 和正文 */
19
5
  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() };
6
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
7
+ if (!m)
8
+ return { body: text.trim() };
9
+ const description = /^description:\s*(.+?)\s*$/m.exec(m[1])?.[1]?.replace(/^(["'])(.*)\1$/, "$2");
10
+ return { ...description ? { description } : {}, body: text.slice(m[0].length).trim() };
25
11
  }
26
- /** 把参数放进正文:有 $ARGUMENTS 就替换,没有就接在最后 */
27
12
  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;
13
+ const given = args.trim();
14
+ if (body.includes("$ARGUMENTS"))
15
+ return body.replaceAll("$ARGUMENTS", given);
16
+ return given ? `${body}
17
+
18
+ ${given}` : body;
32
19
  }
33
20
  async function markdownFiles(dir) {
34
- try {
35
- return (await readdir(dir)).filter((n) => n.toLowerCase().endsWith(".md")).sort();
36
- }
37
- catch {
38
- return [];
39
- }
21
+ try {
22
+ return (await readdir(dir)).filter((n) => n.toLowerCase().endsWith(".md")).sort();
23
+ } catch {
24
+ return [];
25
+ }
40
26
  }
41
27
  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
- }
28
+ async process(ctx) {
29
+ const commands = ctx.require("commands@1");
30
+ const skipped = [];
31
+ const seen = new Set;
32
+ for (const [dir, layer] of [
33
+ [path.join(ctx.home, "commands"), "user"],
34
+ [path.join(ctx.cwd, ".jade", "commands"), "project"]
35
+ ]) {
36
+ for (const file of await markdownFiles(dir)) {
37
+ const name = file.slice(0, -3);
38
+ if (seen.has(name.toLowerCase()))
39
+ continue;
40
+ const full = path.join(dir, file);
41
+ let description;
42
+ try {
43
+ description = parseCommand(await readFile(full, "utf8")).description;
44
+ } catch {
45
+ continue;
46
+ }
47
+ const about = (description ?? `send ${layer === "user" ? full : path.join(".jade", "commands", file)}`).replace(/\s+/g, " ");
48
+ try {
49
+ commands.register({
50
+ name,
51
+ args: "[arguments]",
52
+ description: `${about.length > MAX_DESCRIPTION ? `${about.slice(0, MAX_DESCRIPTION)}…` : about} (${layer} command)`,
53
+ async run(args) {
54
+ const { body } = parseCommand(await readFile(full, "utf8"));
55
+ if (!body)
56
+ return `${full} is empty.`;
57
+ return { prompt: fill(body, args) };
81
58
  }
59
+ });
60
+ seen.add(name.toLowerCase());
61
+ } catch (e) {
62
+ skipped.push(`/${name} (${e instanceof Error ? e.message : String(e)})`);
82
63
  }
83
- if (skipped.length > 0)
84
- ctx.service("ui@1")?.notify(`jade/custom-commands: not registered: ${skipped.join("; ")}`, "warning");
85
- },
64
+ }
65
+ }
66
+ if (skipped.length > 0)
67
+ ctx.service("ui@1")?.notify(`jade/custom-commands: not registered: ${skipped.join("; ")}`, "warning");
68
+ }
86
69
  });
@@ -1,89 +1,81 @@
1
- // jade/editor:Ctrl+G 把输入框里的文字交给 $EDITOR 编辑,存盘退出后换回输入框。
2
- //
3
- // 终端编辑器(vim、nano)要独占终端:经 ui@1 的 suspend 让前端把终端让出来,编辑器退出后前端重新接管。
4
- // 图形编辑器("code --wait")不需要终端,但走同一条路也没有坏处。前端不提供 suspend 或没有输入框时做不了,提示一句。
5
1
  import { spawn } from "node:child_process";
6
2
  import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
7
3
  import os from "node:os";
8
4
  import path from "node:path";
9
5
  import { definePlugin } from "@uncarved/jade-api";
10
6
  const DEFAULT_KEY = "ctrl+g";
11
- /** 用哪个编辑器:配置的 editor,否则 $VISUAL、$EDITOR,都没有时 vi(Windows 上是 notepad) */
12
7
  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");
8
+ if (typeof configured === "string" && configured.trim())
9
+ return configured.trim();
10
+ return env.VISUAL?.trim() || env.EDITOR?.trim() || (process.platform === "win32" ? "notepad" : "vi");
16
11
  }
17
- /** 经 shell 启动编辑器(命令里可以带参数,例如 "code --wait"),等它退出;返回退出码 */
18
12
  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
- });
13
+ return new Promise((resolve, reject) => {
14
+ const child = spawn(`${command} "${file}"`, { stdio: "inherit", shell: true });
15
+ child.on("error", reject);
16
+ child.on("exit", (code) => resolve(code));
17
+ });
24
18
  }
25
- /** 正在显示的会话的输入框:会话级的 ctx 才有,按键是进程级注册的 */
26
19
  let input;
27
- /** 编辑器开着的时候再按一次不再开一个 */
28
20
  let editing = false;
29
- /** 按键没注册上的原因(被别的插件占了、配置写错了):第一个会话打开时告诉用户一次 */
30
21
  let noKey;
31
22
  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;
23
+ process(ctx) {
24
+ const key = typeof ctx.config.key === "string" && ctx.config.key ? ctx.config.key : DEFAULT_KEY;
25
+ const binding = {
26
+ key,
27
+ description: "edit the input in $EDITOR",
28
+ async run() {
29
+ const ui = ctx.service("ui@1");
30
+ const draft = input;
31
+ if (!ui?.suspend || !draft)
32
+ return ui?.notify("this front end cannot hand the terminal to an editor", "warning");
33
+ if (editing)
34
+ return;
35
+ editing = true;
36
+ const command = editorCommand(ctx.config.editor);
37
+ const dir = await mkdtemp(path.join(os.tmpdir(), "jade-edit-"));
38
+ const file = path.join(dir, "message.md");
68
39
  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`;
40
+ await writeFile(file, draft.text());
41
+ const code = await ui.suspend(() => run(command, file));
42
+ if (code !== 0)
43
+ return ui.notify(`${command} exited with code ${code}; the input was left as it was`, "warning");
44
+ draft.set((await readFile(file, "utf8")).replace(/\r?\n$/, ""));
45
+ } catch (e) {
46
+ ui.notify(`could not edit the input with ${command}: ${e instanceof Error ? e.message : String(e)}`, "error");
47
+ } finally {
48
+ editing = false;
49
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
73
50
  }
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
- },
51
+ }
52
+ };
53
+ noKey = undefined;
54
+ const keys = ctx.require("keys@1");
55
+ const taken = keys.get(binding.key)?.plugin;
56
+ const fix = `set {"jade/editor": {"key": "ctrl+<letter>"}} in config.json to use another key`;
57
+ if (taken)
58
+ noKey = `${binding.key} is already used by ${taken}; ${fix}`;
59
+ else {
60
+ try {
61
+ keys.register(binding);
62
+ } catch (e) {
63
+ noKey = `${e instanceof Error ? e.message : String(e)}; ${fix}`;
64
+ }
65
+ }
66
+ },
67
+ async session(ctx) {
68
+ if (noKey) {
69
+ ctx.service("ui@1")?.notify(`jade/editor: ${noKey}`, "warning");
70
+ noKey = undefined;
71
+ }
72
+ const draft = ctx.input;
73
+ if (!draft)
74
+ return;
75
+ input = draft;
76
+ await ctx.effect(() => () => {
77
+ if (input === draft)
78
+ input = undefined;
79
+ });
80
+ }
89
81
  });