@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
@@ -1,50 +1,8 @@
1
1
  // jade/commands:斜杠命令的注册表。只登记,不执行:前端解析输入、带着自己的上下文调用 run。
2
2
  // 每个调用方一个实例,调用方关闭(停用、被隔离、换会话时的会话作用域)时它注册的命令自动撤销。
3
3
 
4
- import { definePlugin, type SessionManager, type UI } from "../../src/api.ts";
5
-
6
- export interface Command {
7
- /** 不带斜杠,字母、数字、- 和 _ */
8
- name: string;
9
- description?: string;
10
- /** 参数提示,例如 "<file>" */
11
- args?: string;
12
- /**
13
- * 不碰会话(只查看、只改插件自己的设置)的命令设为 true:模型工作时也立即执行,不排队。
14
- * 这种命令返回 { prompt } 无效
15
- */
16
- instant?: boolean;
17
- /** 字符串:显示给用户;{ prompt }:作为用户消息发给模型;不返回:什么也不做 */
18
- run(args: string, ctx: CommandContext): CommandResult | Promise<CommandResult>;
19
- }
20
-
21
- export type CommandResult = string | { prompt: string } | void | undefined;
22
-
23
- /** 前端执行命令时给的上下文 */
24
- export interface CommandContext {
25
- /** 用户中断(esc)或退出时中止 */
26
- signal: AbortSignal;
27
- ui: UI;
28
- /** 当前会话、新建、恢复(/clear、/resume 用它) */
29
- sessions: SessionManager;
30
- /** 在对话里显示一段文字,可以带 ANSI 颜色 */
31
- print(text: string): void;
32
- }
33
-
34
- export interface CommandEntry {
35
- command: Command;
36
- /** 注册它的插件 */
37
- plugin: string;
38
- }
39
-
40
- export interface Commands {
41
- /** 注册一条命令,返回撤销函数。名字已被占用时抛错 */
42
- register(command: Command): () => void;
43
- /** 按名字找(不分大小写) */
44
- get(name: string): CommandEntry | undefined;
45
- /** 全部命令,按名字排序 */
46
- list(): { name: string; args?: string; description?: string; instant?: boolean; plugin: string }[];
47
- }
4
+ import { definePlugin } from "@uncarved/jade-api";
5
+ import type { CommandEntry, Commands } from "@uncarved/jade-api/services";
48
6
 
49
7
  const NAME = /^[a-z0-9][a-z0-9_-]*$/i;
50
8
  const registry = new Map<string, CommandEntry>();
@@ -39,8 +39,8 @@ export interface Compactor {
39
39
  project(messages: Message[], ctx: HookContext): Promise<Message[]>;
40
40
  /** event 的 observe:记下真实用量 */
41
41
  observe(e: LogEvent): void;
42
- /** 下一次请求前无论是否超过阈值都总结一次 */
43
- request(): void;
42
+ /** 下一次请求前无论是否超过阈值都总结一次;focus 是用户要总结特别留意的事(/compact 后面写的) */
43
+ request(focus?: string): void;
44
44
  }
45
45
 
46
46
  const SUMMARY_SYSTEM =
@@ -125,6 +125,7 @@ const total = (u: Usage | undefined) => (u?.inputTokens === undefined ? undefine
125
125
  export function compactor(opts: CompactorOptions): Compactor {
126
126
  const id = opts.id ?? "jade/compact";
127
127
  let forced = false;
128
+ let focus: string | undefined;
128
129
  /** 最近一次投影:它对应的消息条数和压缩状态;收到回复后补上真实用量 */
129
130
  let last: { length: number; state: string; tokens?: number } | undefined;
130
131
  let pending: { length: number; state: string } | undefined;
@@ -189,6 +190,8 @@ export function compactor(opts: CompactorOptions): Compactor {
189
190
  }
190
191
  }
191
192
  forced = false;
193
+ const asked = focus;
194
+ focus = undefined;
192
195
 
193
196
  const res = await opts.complete(
194
197
  {
@@ -205,6 +208,7 @@ export function compactor(opts: CompactorOptions): Compactor {
205
208
  origin: { by: "plugin", id },
206
209
  trust: "untrusted",
207
210
  },
211
+ ...(asked ? [{ kind: "text" as const, text: `The user asked that the summary pay particular attention to: ${asked}`, origin: { by: "plugin" as const, id }, trust: "trusted" as const }] : []),
208
212
  ],
209
213
  },
210
214
  ],
@@ -235,8 +239,9 @@ export function compactor(opts: CompactorOptions): Compactor {
235
239
  last = { ...pending, tokens: total((e as LogEvent<"model.responded">).data.usage) };
236
240
  pending = undefined;
237
241
  },
238
- request() {
242
+ request(what) {
239
243
  forced = true;
244
+ focus = what;
240
245
  },
241
246
  };
242
247
  }
@@ -2,10 +2,8 @@
2
2
  // 请求因为超出上下文窗口失败时,压缩后用 { kind: "retry" } 重试一次(session.afterTurn,设计 4.3)。
3
3
 
4
4
  import type { LogEvent } from "uncarved";
5
- import { definePlugin, type UI } from "../../src/api.ts";
6
- import type { Commands } from "../commands/index.ts";
7
- import type { Models } from "../models/index.ts";
8
- import type { Renderers } from "../renderers/index.ts";
5
+ import { definePlugin, type UI } from "@uncarved/jade-api";
6
+ import type { Commands, Compact, Models, Renderers } from "@uncarved/jade-api/services";
9
7
  import { compactor, compactThreshold, isContextOverflow, parseTokens } from "./compact.ts";
10
8
  import { dim } from "./style.ts";
11
9
 
@@ -16,12 +14,6 @@ const ANTHROPIC_REPLY_TOKENS = 64_000;
16
14
  /** 总结要调用模型,比 hook 默认的 30 秒长 */
17
15
  const SUMMARY_TIMEOUT_MS = 300_000;
18
16
 
19
- /** compact@1 */
20
- export interface Compact {
21
- /** 历史超过这么多 token 时自动压缩(界面显示用) */
22
- threshold(): number;
23
- }
24
-
25
17
  /** 自动压缩的阈值:配置的 thresholdTokens,否则按当前模型的上下文窗口算 */
26
18
  function thresholdFor(config: Record<string, unknown>, models: Models): () => number {
27
19
  const configured = parseTokens(config.thresholdTokens);
@@ -34,8 +26,8 @@ function thresholdFor(config: Record<string, unknown>, models: Models): () => nu
34
26
  };
35
27
  }
36
28
 
37
- /** /compact 请求过的会话:下一次投影时无论是否超过阈值都总结一次 */
38
- const requested = new Set<string>();
29
+ /** /compact 请求过的会话:下一次投影时无论是否超过阈值都总结一次。值是命令后面写的、要总结特别留意的事 */
30
+ const requested = new Map<string, string>();
39
31
 
40
32
  export default definePlugin({
41
33
  process(ctx) {
@@ -43,11 +35,12 @@ export default definePlugin({
43
35
  const commands = ctx.service<Commands>("commands@1");
44
36
  commands?.register({
45
37
  name: "compact",
46
- description: "compact the history before the next request",
47
- run(_args, c) {
38
+ args: "[what to keep]",
39
+ description: "compact the history before the next request; text after the command tells the summary what to pay attention to",
40
+ run(args, c) {
48
41
  const s = c.sessions.current;
49
42
  if (!s) return "No session is open.";
50
- requested.add(s.id);
43
+ requested.set(s.id, args.trim());
51
44
  return dim("History will be compacted before the next request.");
52
45
  },
53
46
  });
@@ -79,7 +72,11 @@ export default definePlugin({
79
72
  order: 100,
80
73
  timeoutMs: SUMMARY_TIMEOUT_MS,
81
74
  fn: (messages, hook) => {
82
- if (requested.delete(id)) c.request();
75
+ const focus = requested.get(id);
76
+ if (focus !== undefined) {
77
+ requested.delete(id);
78
+ c.request(focus || undefined);
79
+ }
83
80
  return c.project(messages, hook);
84
81
  },
85
82
  });
@@ -6,7 +6,7 @@
6
6
  // 旧 jade 的"上下文溢出后压缩重试"不在这里:不压缩就重试只会再溢出一次,整件事归 jade/compact。
7
7
 
8
8
  import type { Block, UserInput } from "uncarved";
9
- import { definePlugin, type UI } from "../../src/api.ts";
9
+ import { definePlugin, type UI } from "@uncarved/jade-api";
10
10
 
11
11
  export const DEFAULT_CONTINUES = 3;
12
12
  export const CONTINUE_NOTE =
@@ -0,0 +1,143 @@
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
+
11
+ import type { LogEvent, Usage } from "uncarved";
12
+ import { definePlugin } from "@uncarved/jade-api";
13
+ import type { Commands, Models } from "@uncarved/jade-api/services";
14
+
15
+ export interface Price {
16
+ input: number;
17
+ output: number;
18
+ cacheRead?: number;
19
+ cacheWrite?: number;
20
+ }
21
+ type Totals = Record<string, Required<Usage>>;
22
+
23
+ const KEY = "jade/cost/usage";
24
+ /** 插件自己发的请求没有记模型名时记在这个名字下,算钱时按当前模型 */
25
+ const UNKNOWN = "";
26
+
27
+ /** 配置里的 prices;写错的条目忽略 */
28
+ export function parsePrices(value: unknown): Record<string, Price> {
29
+ const out: Record<string, Price> = {};
30
+ if (!value || typeof value !== "object" || Array.isArray(value)) return out;
31
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
32
+ for (const [model, raw] of Object.entries(value)) {
33
+ const p = (raw ?? {}) as Record<string, unknown>;
34
+ const input = num(p.input);
35
+ const output = num(p.output);
36
+ if (input === undefined || output === undefined) continue;
37
+ const cacheRead = num(p.cacheRead);
38
+ const cacheWrite = num(p.cacheWrite);
39
+ out[model] = { input, output, ...(cacheRead !== undefined ? { cacheRead } : {}), ...(cacheWrite !== undefined ? { cacheWrite } : {}) };
40
+ }
41
+ return out;
42
+ }
43
+
44
+ /** 模型的单价:名字完全相同的,否则最长的前缀 */
45
+ export function priceOf(prices: Record<string, Price>, model: string): Price | undefined {
46
+ let best: string | undefined;
47
+ for (const key of Object.keys(prices)) if (model.startsWith(key) && (best === undefined || key.length > best.length)) best = key;
48
+ return best === undefined ? undefined : prices[best];
49
+ }
50
+
51
+ /** 一份用量按单价是多少钱。inputTokens 含缓存命中和写入的部分(Usage 的约定) */
52
+ export function costOf(u: Required<Usage>, p: Price): number {
53
+ const plain = Math.max(0, u.inputTokens - u.cacheReadTokens - u.cacheWriteTokens);
54
+ return (plain * p.input + u.cacheReadTokens * (p.cacheRead ?? p.input) + u.cacheWriteTokens * (p.cacheWrite ?? p.input) + u.outputTokens * p.output) / 1_000_000;
55
+ }
56
+
57
+ /** 一个事件带来的用量和它的模型;不带用量的事件 undefined */
58
+ function usageIn(e: LogEvent): { model: string; usage: Usage } | undefined {
59
+ const usage = (e.data as { usage?: Usage } | null)?.usage;
60
+ if (!usage || typeof usage !== "object") return undefined;
61
+ if (e.type === "model.responded") return { model: e.origin.by === "model" ? e.origin.model : UNKNOWN, usage };
62
+ return e.origin.by === "plugin" ? { model: UNKNOWN, usage } : undefined;
63
+ }
64
+
65
+ function add(totals: Totals, model: string, u: Usage): void {
66
+ const t = (totals[model] ??= { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 });
67
+ for (const k of Object.keys(t) as (keyof Usage)[]) {
68
+ const v = u[k];
69
+ if (typeof v === "number" && Number.isFinite(v)) t[k] += v;
70
+ }
71
+ }
72
+
73
+ /** 合计的钱;一个有单价的模型都没有时 undefined */
74
+ function total(totals: Totals, prices: Record<string, Price>, current: string | undefined): number | undefined {
75
+ let sum: number | undefined;
76
+ for (const [model, u] of Object.entries(totals)) {
77
+ const p = priceOf(prices, model === UNKNOWN ? (current ?? "") : model);
78
+ if (p) sum = (sum ?? 0) + costOf(u, p);
79
+ }
80
+ return sum;
81
+ }
82
+
83
+ const money = (n: number) => `$${n < 0.01 && n > 0 ? n.toFixed(4) : n.toFixed(2)}`;
84
+ const tokens = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(2)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
85
+
86
+ export default definePlugin({
87
+ process(ctx) {
88
+ const prices = parsePrices(ctx.config.prices);
89
+ ctx.service<Commands>("commands@1")?.register({
90
+ name: "cost",
91
+ description: "show this session's token usage per model, and what it cost at the configured prices",
92
+ instant: true,
93
+ async run(_args, { sessions }) {
94
+ const s = sessions.current;
95
+ if (!s) return "No session is open.";
96
+ const totals: Totals = {};
97
+ for (const e of await s.history()) {
98
+ const u = usageIn(e);
99
+ if (u) add(totals, u.model, u.usage);
100
+ }
101
+ const current = ctx.service<Models>("models@1")?.current()?.model;
102
+ const rows = Object.entries(totals).map(([model, u]) => {
103
+ const p = priceOf(prices, model === UNKNOWN ? (current ?? "") : model);
104
+ const cached = u.cacheReadTokens ? `, ${tokens(u.cacheReadTokens)} from cache` : "";
105
+ return `${model === UNKNOWN ? "plugin requests (compaction, review, sub-agents)" : model}: ${tokens(u.inputTokens)} in${cached}, ${tokens(u.outputTokens)} out${p ? ` · ${money(costOf(u, p))}` : ""}`;
106
+ });
107
+ if (rows.length === 0) return "No model usage in this session yet.";
108
+ const sum = total(totals, prices, current);
109
+ 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`;
110
+ const unpriced = Object.keys(totals).some((m) => !priceOf(prices, m === UNKNOWN ? (current ?? "") : m));
111
+ return [...rows, ...(sum !== undefined ? [`Total: ${money(sum)}`] : []), ...(unpriced ? [hint] : [])].join("\n");
112
+ },
113
+ });
114
+ },
115
+
116
+ session(ctx) {
117
+ const prices = parsePrices(ctx.config.prices);
118
+ // 没有配置单价、或者前端没有状态栏:不用算
119
+ if (Object.keys(prices).length === 0 || !ctx.status) return;
120
+ const models = ctx.service<Models>("models@1");
121
+ let totals: Totals | undefined;
122
+ const show = () => {
123
+ const sum = total(totals ?? {}, prices, models?.current()?.model);
124
+ ctx.status?.(sum === undefined ? undefined : money(sum));
125
+ };
126
+ ctx.kernel.hook({
127
+ kind: "observe",
128
+ point: "event",
129
+ fn: async (e, hook) => {
130
+ // 恢复的会话:从上次记下的合计接着算
131
+ totals ??= structuredClone((hook.derived[KEY] as Totals | undefined) ?? {});
132
+ const u = usageIn(e);
133
+ if (u) {
134
+ add(totals, u.model, u.usage);
135
+ show();
136
+ } else if (e.type === "turn.ended") {
137
+ show();
138
+ await hook.record(KEY, totals);
139
+ }
140
+ },
141
+ });
142
+ },
143
+ });
@@ -0,0 +1,13 @@
1
+ {
2
+ "id": "jade/cost",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.ts",
6
+ "optional": ["commands@1", "models@1"],
7
+ "config": {
8
+ "prices": {
9
+ "default": {},
10
+ "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"
11
+ }
12
+ }
13
+ }
@@ -0,0 +1,85 @@
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
+
15
+ import { readdir, readFile } from "node:fs/promises";
16
+ import path from "node:path";
17
+ import { definePlugin, type UI } from "@uncarved/jade-api";
18
+ import type { Commands } from "@uncarved/jade-api/services";
19
+
20
+ const MAX_DESCRIPTION = 80;
21
+
22
+ /** 拆出 frontmatter 里的 description 和正文 */
23
+ export function parseCommand(text: string): { description?: string; body: string } {
24
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
25
+ if (!m) return { body: text.trim() };
26
+ const description = /^description:\s*(.+?)\s*$/m.exec(m[1]!)?.[1]?.replace(/^(["'])(.*)\1$/, "$2");
27
+ return { ...(description ? { description } : {}), body: text.slice(m[0].length).trim() };
28
+ }
29
+
30
+ /** 把参数放进正文:有 $ARGUMENTS 就替换,没有就接在最后 */
31
+ export function fill(body: string, args: string): string {
32
+ const given = args.trim();
33
+ if (body.includes("$ARGUMENTS")) return body.replaceAll("$ARGUMENTS", given);
34
+ return given ? `${body}\n\n${given}` : body;
35
+ }
36
+
37
+ async function markdownFiles(dir: string): Promise<string[]> {
38
+ try {
39
+ return (await readdir(dir)).filter((n) => n.toLowerCase().endsWith(".md")).sort();
40
+ } catch {
41
+ return [];
42
+ }
43
+ }
44
+
45
+ export default definePlugin({
46
+ async process(ctx) {
47
+ const commands = ctx.require<Commands>("commands@1");
48
+ const skipped: string[] = [];
49
+ const seen = new Set<string>();
50
+ for (const [dir, layer] of [
51
+ [path.join(ctx.home, "commands"), "user"],
52
+ [path.join(ctx.cwd, ".jade", "commands"), "project"],
53
+ ] as const) {
54
+ for (const file of await markdownFiles(dir)) {
55
+ const name = file.slice(0, -3);
56
+ // 用户层的已经登记了同名的:项目层的不盖过它
57
+ if (seen.has(name.toLowerCase())) continue;
58
+ const full = path.join(dir, file);
59
+ let description: string | undefined;
60
+ try {
61
+ description = parseCommand(await readFile(full, "utf8")).description;
62
+ } catch {
63
+ continue;
64
+ }
65
+ const about = (description ?? `send ${layer === "user" ? full : path.join(".jade", "commands", file)}`).replace(/\s+/g, " ");
66
+ try {
67
+ commands.register({
68
+ name,
69
+ args: "[arguments]",
70
+ description: `${about.length > MAX_DESCRIPTION ? `${about.slice(0, MAX_DESCRIPTION)}…` : about} (${layer} command)`,
71
+ async run(args) {
72
+ const { body } = parseCommand(await readFile(full, "utf8"));
73
+ if (!body) return `${full} is empty.`;
74
+ return { prompt: fill(body, args) };
75
+ },
76
+ });
77
+ seen.add(name.toLowerCase());
78
+ } catch (e) {
79
+ skipped.push(`/${name} (${e instanceof Error ? e.message : String(e)})`);
80
+ }
81
+ }
82
+ }
83
+ if (skipped.length > 0) ctx.service<UI>("ui@1")?.notify(`jade/custom-commands: not registered: ${skipped.join("; ")}`, "warning");
84
+ },
85
+ });
@@ -0,0 +1,8 @@
1
+ {
2
+ "id": "jade/custom-commands",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.ts",
6
+ "requires": ["commands@1"],
7
+ "optional": ["ui@1"]
8
+ }
@@ -0,0 +1,88 @@
1
+ // jade/editor:Ctrl+G 把输入框里的文字交给 $EDITOR 编辑,存盘退出后换回输入框。
2
+ //
3
+ // 终端编辑器(vim、nano)要独占终端:经 ui@1 的 suspend 让前端把终端让出来,编辑器退出后前端重新接管。
4
+ // 图形编辑器("code --wait")不需要终端,但走同一条路也没有坏处。前端不提供 suspend 或没有输入框时做不了,提示一句。
5
+
6
+ import { spawn } from "node:child_process";
7
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { definePlugin, type Draft, type UI } from "@uncarved/jade-api";
11
+ import type { Key, Keys } from "@uncarved/jade-api/services";
12
+
13
+ const DEFAULT_KEY = "ctrl+g";
14
+
15
+ /** 用哪个编辑器:配置的 editor,否则 $VISUAL、$EDITOR,都没有时 vi(Windows 上是 notepad) */
16
+ export function editorCommand(configured: unknown, env: Record<string, string | undefined> = process.env): string {
17
+ if (typeof configured === "string" && configured.trim()) return configured.trim();
18
+ return env.VISUAL?.trim() || env.EDITOR?.trim() || (process.platform === "win32" ? "notepad" : "vi");
19
+ }
20
+
21
+ /** 经 shell 启动编辑器(命令里可以带参数,例如 "code --wait"),等它退出;返回退出码 */
22
+ function run(command: string, file: string): Promise<number | null> {
23
+ return new Promise((resolve, reject) => {
24
+ const child = spawn(`${command} "${file}"`, { stdio: "inherit", shell: true });
25
+ child.on("error", reject);
26
+ child.on("exit", (code) => resolve(code));
27
+ });
28
+ }
29
+
30
+ /** 正在显示的会话的输入框:会话级的 ctx 才有,按键是进程级注册的 */
31
+ let input: Draft | undefined;
32
+ /** 编辑器开着的时候再按一次不再开一个 */
33
+ let editing = false;
34
+ /** 按键没注册上的原因(被别的插件占了、配置写错了):第一个会话打开时告诉用户一次 */
35
+ let noKey: string | undefined;
36
+
37
+ export default definePlugin({
38
+ process(ctx) {
39
+ const key = typeof ctx.config.key === "string" && ctx.config.key ? ctx.config.key : DEFAULT_KEY;
40
+ const binding: Key = {
41
+ key,
42
+ description: "edit the input in $EDITOR",
43
+ async run() {
44
+ const ui = ctx.service<UI>("ui@1");
45
+ const draft = input;
46
+ if (!ui?.suspend || !draft) return ui?.notify("this front end cannot hand the terminal to an editor", "warning");
47
+ if (editing) return;
48
+ editing = true;
49
+ const command = editorCommand(ctx.config.editor);
50
+ const dir = await mkdtemp(path.join(os.tmpdir(), "jade-edit-"));
51
+ // .md:编辑器按 Markdown 高亮,消息多半就是 Markdown
52
+ const file = path.join(dir, "message.md");
53
+ try {
54
+ await writeFile(file, draft.text());
55
+ const code = await ui.suspend(() => run(command, file));
56
+ if (code !== 0) return ui.notify(`${command} exited with code ${code}; the input was left as it was`, "warning");
57
+ // 编辑器存盘时加的最后一个换行不算
58
+ draft.set((await readFile(file, "utf8")).replace(/\r?\n$/, ""));
59
+ } catch (e) {
60
+ ui.notify(`could not edit the input with ${command}: ${e instanceof Error ? e.message : String(e)}`, "error");
61
+ } finally {
62
+ editing = false;
63
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
64
+ }
65
+ },
66
+ };
67
+ // 键被别的插件占了不算这个插件坏了:只是没有这个键,换一个就行
68
+ noKey = undefined;
69
+ try {
70
+ ctx.require<Keys>("keys@1").register(binding);
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
+
76
+ async session(ctx) {
77
+ if (noKey) {
78
+ ctx.service<UI>("ui@1")?.notify(`jade/editor: ${noKey}`, "warning");
79
+ noKey = undefined;
80
+ }
81
+ const draft = ctx.input;
82
+ if (!draft) return;
83
+ input = draft;
84
+ await ctx.effect(() => () => {
85
+ if (input === draft) input = undefined;
86
+ });
87
+ },
88
+ });
@@ -0,0 +1,17 @@
1
+ {
2
+ "id": "jade/editor",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.ts",
6
+ "requires": ["keys@1"],
7
+ "optional": ["ui@1"],
8
+ "config": {
9
+ "key": {
10
+ "default": "ctrl+g",
11
+ "description": "the key that opens the editor: ctrl+<letter> or alt+<letter or digit>"
12
+ },
13
+ "editor": {
14
+ "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)"
15
+ }
16
+ }
17
+ }
package/plugins/fs/fs.ts CHANGED
@@ -172,8 +172,11 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
172
172
  if (buf.subarray(0, 8000).includes(0)) {
173
173
  return { content: `${display(cwd, full)} is a binary file (${buf.length} bytes) and cannot be shown as text`, isError: true };
174
174
  }
175
- const text = buf.toString("utf8");
176
- remember(full, info, opts.responses?.calls ?? -1, ctx?.toolUseId);
175
+ // 不是 UTF-8 的文件(多半是 GBK)照样给模型看,但不算读过:改它会把原来的字节写坏
176
+ const strict = utf8(buf);
177
+ const text = strict ?? legacyText(buf);
178
+ const note = strict === undefined ? `\n(${notUtf8(display(cwd, full))})` : "";
179
+ if (strict !== undefined) remember(full, info, opts.responses?.calls ?? -1, ctx?.toolUseId);
177
180
  if (text.length === 0) return { content: "(empty file)" };
178
181
  const lines = text.split(/\r?\n/);
179
182
  if (lines.at(-1) === "") lines.pop();
@@ -192,9 +195,9 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
192
195
  const body = out.join("\n");
193
196
  const end = start + out.length - 1;
194
197
  if (out.length < slice.length) {
195
- return { content: `${body}\n(output capped at about ${MAX_READ_CHARS} characters: showing lines ${start}-${end} of ${lines.length}; continue with offset ${end + 1})` };
198
+ 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}` };
196
199
  }
197
- return { content: end < lines.length ? `${body}\n(showing lines ${start}-${end} of ${lines.length})` : body };
200
+ return { content: (end < lines.length ? `${body}\n(showing lines ${start}-${end} of ${lines.length})` : body) + note };
198
201
  },
199
202
  };
200
203
 
@@ -219,7 +222,8 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
219
222
  const info = await statOrUndefined(full);
220
223
  if (info?.isDirectory()) return { content: `${display(cwd, full)} is a directory`, isError: true };
221
224
  // 同样内容重复写入(崩溃后重跑)不算覆盖别人的修改
222
- const before = info ? await readFile(full, "utf8") : null;
225
+ const before = info ? utf8(await readFile(full)) ?? undefined : null;
226
+ if (before === undefined) return { content: notUtf8(display(cwd, full)), isError: true };
223
227
  // read_file 不显示换行风格和 BOM:覆盖已有文件时沿用原来的,否则整个文件每一行都算改了
224
228
  const content = before === null ? given : keepStyle(before, given);
225
229
  const problem = info && before !== null && before !== content ? staleness(full, info) : undefined;
@@ -241,7 +245,8 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
241
245
  if (!info) {
242
246
  return { content: seen.has(full) ? `${shown} no longer exists` : `${shown} does not exist; use write_file to create it`, isError: true };
243
247
  }
244
- const text = await readFile(full, "utf8");
248
+ const text = utf8(await readFile(full));
249
+ if (text === undefined) return { content: notUtf8(shown), isError: true };
245
250
  const problem = staleness(full, info);
246
251
  if (problem) return { content: problem, isError: true };
247
252
  let next = text;
@@ -386,6 +391,28 @@ export function applyEditsToText(text: string, edits: Edit[], shown: string): st
386
391
  return { text: next };
387
392
  }
388
393
 
394
+ /** 按 UTF-8 解码(BOM 留着);不是合法的 UTF-8 时 undefined */
395
+ export function utf8(buf: Uint8Array): string | undefined {
396
+ try {
397
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buf);
398
+ } catch {
399
+ return undefined;
400
+ }
401
+ }
402
+
403
+ /** 不是 UTF-8 的文本只用来显示:按 GB18030(含 GBK)解码,运行时不支持时按 UTF-8 解码、坏的字节显示成 U+FFFD */
404
+ function legacyText(buf: Buffer): string {
405
+ try {
406
+ return new TextDecoder("gb18030").decode(buf);
407
+ } catch {
408
+ return buf.toString("utf8");
409
+ }
410
+ }
411
+
412
+ const notUtf8 = (shown: string) =>
413
+ `${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: ` +
414
+ "change it with a command that keeps its encoding, or ask the user before converting it to UTF-8.";
415
+
389
416
  /** text 里多数换行是 CRLF 时返回 "\r\n",多数是 LF 时返回 "\n",一样多或没有换行时返回 fallback */
390
417
  function eolOf(text: string, fallback: string): string {
391
418
  const crlf = text.split("\r\n").length - 1;