@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
@@ -76,6 +76,8 @@ export interface ChecksOptions {
76
76
  /** 默认在 PATH 里找(由调用方给,见 index.ts 的 shell@1);测试用 */
77
77
  which?: (bin: string) => string | null;
78
78
  id?: string;
79
+ /** 写文件的工具把路径放在输入的哪个字段(工具的 meta.writes);不写文件的工具返回 undefined */
80
+ writes(tool: string): string | undefined;
79
81
  }
80
82
 
81
83
  export interface Checks {
@@ -89,7 +91,6 @@ export interface Checks {
89
91
  reset(): void;
90
92
  }
91
93
 
92
- export const WRITE_TOOLS = new Set(["write_file", "edit_file", "multi_edit"]);
93
94
  const DEFAULT_TIMEOUT_MS = 120_000;
94
95
  /** 附给模型的文字上限 */
95
96
  const MAX_REPORT_CHARS = 6000;
@@ -341,8 +342,9 @@ export function checks(opts: ChecksOptions): Checks {
341
342
  const ids: string[] = [];
342
343
  const files: string[] = [];
343
344
  for (const b of reply.content) {
344
- if (b.kind !== "tool_use" || !WRITE_TOOLS.has(b.name) || !ok.has(b.id)) continue;
345
- const p = (b.input as { path?: unknown } | null)?.path;
345
+ const field = b.kind === "tool_use" && ok.has(b.id) ? opts.writes(b.name) : undefined;
346
+ if (field === undefined || b.kind !== "tool_use") continue;
347
+ const p = (b.input as Record<string, unknown> | null)?.[field];
346
348
  if (typeof p !== "string") continue;
347
349
  ids.push(b.id);
348
350
  // 和 root 一样解析符号链接、短文件名,否则判断不出文件在不在某个目录里
@@ -402,15 +404,16 @@ export function checks(opts: ChecksOptions): Checks {
402
404
  return self;
403
405
  }
404
406
 
405
- /** 会话里成功改过的文件(/checks 显示用):所有写入调用里结果不是错误的 */
406
- export function changedFiles(messages: readonly Message[], cwd: string): string[] {
407
+ /** 会话里成功改过的文件(/checks 显示用):所有写入调用里结果不是错误的;writes 同 ChecksOptions.writes */
408
+ export function changedFiles(messages: readonly Message[], cwd: string, writes: (tool: string) => string | undefined): string[] {
407
409
  const ok = new Set(messages.flatMap((m) => (m.role === "user" ? m.content.flatMap((b) => (b.kind === "tool_result" && !b.isError ? [b.toolUseId] : [])) : [])));
408
410
  const files: string[] = [];
409
411
  for (const m of messages) {
410
412
  if (m.role !== "assistant") continue;
411
413
  for (const b of m.content) {
412
- if (b.kind !== "tool_use" || !WRITE_TOOLS.has(b.name) || !ok.has(b.id)) continue;
413
- const p = (b.input as { path?: unknown } | null)?.path;
414
+ const field = b.kind === "tool_use" && ok.has(b.id) ? writes(b.name) : undefined;
415
+ if (field === undefined || b.kind !== "tool_use") continue;
416
+ const p = (b.input as Record<string, unknown> | null)?.[field];
414
417
  if (typeof p !== "string") continue;
415
418
  const full = canonical(path.resolve(cwd, p));
416
419
  if (!files.some((f) => sameFile(f, full))) files.push(full);
@@ -5,15 +5,15 @@
5
5
  // 自己刚引入的错误并改掉;轮次结束后才检查就得再发起一轮(session.send),等于替用户多说一句话。
6
6
  //
7
7
  // 检查会执行仓库里的代码(node_modules 里的 tsc、.jade/checks.json 里的命令),每条命令第一次运行前请用户确认,
8
- // 记在 $JADE_HOME/trust.jsonl(和旧 jade 同一个文件、同一种记录,旧 jade 里确认过的不用再确认)。
8
+ // 确认记在核心的 trust@1($JADE_HOME/state/confirmed.json)。
9
9
  // yolo 模式不问;不能提问时不运行没确认过的命令。
10
10
 
11
11
  import { createHash } from "node:crypto";
12
12
  import path from "node:path";
13
- import { definePlugin, type SessionContext, type UI } from "@uncarved/jade-api";
13
+ import { definePlugin, type SessionContext, type Text, type Trust, type UI } from "@uncarved/jade-api";
14
14
  import type { Approval, Commands, EventRenderer, Renderers, Shell } from "@uncarved/jade-api/services";
15
15
  import { changedFiles, checks, type Check, type Checks } from "./checks.ts";
16
- import { bold, dim, display, realPath, repoRoot, TrustFile, yellow } from "./project.ts";
16
+ import { bold, dim, display, lines as joinLines, realPath, repoRoot, warn, withLegacyTrust } from "./project.ts";
17
17
 
18
18
  /** 确认记录:同一个目录里的同一条命令只问一次。和旧 jade 的算法相同 */
19
19
  const checkHash = (c: Check) => createHash("sha256").update(`jade-check\0${c.cwd}\0${c.command}`).digest("hex");
@@ -34,9 +34,9 @@ export const checksRenderers: EventRenderer[] = [
34
34
  const bad = d.summary.filter((s) => s.problems > 0 || s.others || s.failed);
35
35
  const lines = d.report ? d.report.split("\n").slice(1) : [];
36
36
  const details = lines.length
37
- ? [...lines.slice(0, MAX_DETAIL_LINES), ...(lines.length > MAX_DETAIL_LINES ? [dim(`… ${lines.length - MAX_DETAIL_LINES} more lines`)] : [])].join("\n")
37
+ ? joinLines([...lines.slice(0, MAX_DETAIL_LINES), ...(lines.length > MAX_DETAIL_LINES ? [dim(`… ${lines.length - MAX_DETAIL_LINES} more lines`)] : [])])
38
38
  : undefined;
39
- const withDetails = (line: string) => (details ? { line, details } : { line });
39
+ const withDetails = (line: Text) => (details ? { line, details } : { line });
40
40
  if (bad.length === 0) return withDetails(dim(`✓ checks passed: ${d.summary.map((s) => s.name).join(", ")}`));
41
41
  const what = bad.map((s) =>
42
42
  s.failed
@@ -45,7 +45,7 @@ export const checksRenderers: EventRenderer[] = [
45
45
  .filter(Boolean)
46
46
  .join(", ")}`,
47
47
  );
48
- return withDetails(yellow(`⚠ checks: ${what.join("; ")}`));
48
+ return withDetails(warn(`⚠ checks: ${what.join("; ")}`));
49
49
  },
50
50
  },
51
51
  ];
@@ -53,7 +53,7 @@ export const checksRenderers: EventRenderer[] = [
53
53
  export default definePlugin({
54
54
  process(ctx) {
55
55
  const off = ctx.config.enabled === false || process.env.JADE_CHECKS === "off";
56
- const trust = new TrustFile(path.join(ctx.home, "trust.jsonl"));
56
+ const trust = withLegacyTrust(ctx.require<Trust>("trust@1"), ctx.home);
57
57
  const renderers = ctx.service<Renderers>("renderers@1");
58
58
  if (renderers) for (const r of checksRenderers) renderers.event(r);
59
59
 
@@ -75,15 +75,15 @@ export default definePlugin({
75
75
  if (arg === "on") checks.reset();
76
76
  return `checks: ${arg}`;
77
77
  }
78
- if (arg) return yellow("usage: /checks [on|off]");
79
- const files = changedFiles(session.state.messages, realPath(ctx.cwd));
78
+ if (arg) return warn("usage: /checks [on|off]");
79
+ const files = changedFiles(session.state.messages, realPath(ctx.cwd), (t) => session.tool(t)?.meta?.writes);
80
80
  const found = await checks.resolve(files);
81
- const lines = [`Edit-time checks are ${checks.enabled ? "on" : "off"} in this session.`];
81
+ const lines: Text[] = [`Edit-time checks are ${checks.enabled ? "on" : "off"} in this session.`];
82
82
  if (found.length > 0) {
83
83
  lines.push("For the files changed in this session:");
84
84
  for (const check of found) {
85
85
  const pending = (await trust.has(checkHash(check))) ? "" : ", not confirmed yet";
86
- lines.push(` ${bold(check.name)} ${dim(`in ${display(ctx.cwd, check.cwd) || "."}${pending}`)}\n ${dim(check.command)}`);
86
+ lines.push([" ", bold(check.name), " ", dim(`in ${display(ctx.cwd, check.cwd) || "."}${pending}`), "\n ", dim(check.command)]);
87
87
  }
88
88
  } else lines.push(dim(files.length ? "No checks apply to the files changed in this session." : "No files changed in this session yet."));
89
89
  lines.push(
@@ -92,7 +92,7 @@ export default definePlugin({
92
92
  `Add your own in .jade/checks.json or ${path.join(ctx.home, "checks.json")}; JADE_CHECKS=off turns them off.`,
93
93
  ),
94
94
  );
95
- return lines.join("\n");
95
+ return joinLines(lines);
96
96
  },
97
97
  });
98
98
 
@@ -139,7 +139,7 @@ export default definePlugin({
139
139
  return turn;
140
140
  };
141
141
  const cwd = realPath(s.cwd);
142
- const c = checks({ cwd, root: realPath(repoRoot(cwd)), home: s.home, run: shell.run, which: (bin) => shell.which(bin) ?? null, approve });
142
+ const c = checks({ cwd, root: realPath(repoRoot(cwd)), home: s.home, run: shell.run, which: (bin) => shell.which(bin) ?? null, approve, writes: (t) => s.session.tool(t)?.meta?.writes });
143
143
  const id = s.session.id;
144
144
  bySession.set(id, c);
145
145
  await s.effect(() => () => {
@@ -3,7 +3,7 @@
3
3
  "version": "0.3.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "requires": ["shell@1"],
6
+ "requires": ["shell@1", "trust@1"],
7
7
  "optional": ["ui@1", "approval@1", "renderers@1", "commands@1"],
8
8
  "config": {
9
9
  "enabled": {
@@ -1,7 +1,8 @@
1
1
  // 仓库目录、确认记录、显示用的小工具。插件之间不共享代码(只能共享类型),jade/mcp、jade/skills 各有一份。
2
2
 
3
+ import type { Span, Text, TextStyle, Trust } from "@uncarved/jade-api";
3
4
  import { existsSync, realpathSync } from "node:fs";
4
- import { appendFile, mkdir, readFile } from "node:fs/promises";
5
+ import { readFile } from "node:fs/promises";
5
6
  import path from "node:path";
6
7
 
7
8
  export function realPath(p: string): string {
@@ -30,52 +31,50 @@ export function display(cwd: string, full: string): string {
30
31
  return shown.split(path.sep).join("/");
31
32
  }
32
33
 
33
- /**
34
- * 用户确认过的东西(检查命令),每行一条 { hash, path, at }。
35
- * 和旧 jade 的 $JADE_HOME/trust.jsonl 同一个文件、同一种格式,旧 jade 里确认过的不用再确认
36
- */
37
- export class TrustFile {
38
- readonly file: string;
39
- #known = new Set<string>();
34
+ export const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
40
35
 
41
- constructor(file: string) {
42
- this.file = file;
43
- }
36
+ // 带语义样式的文字(jade-api 的 Text):插件只说这段是次要的、成功、警告……,怎么画由前端决定
37
+ const styled = (style: TextStyle) => (text: string): Span => ({ text, style });
38
+ export const dim = styled("dim");
39
+ export const bold = styled("bold");
40
+ export const ok = styled("ok");
41
+ export const warn = styled("warn");
42
+ export const error = styled("error");
43
+ /** 几行接成一段,行之间换行 */
44
+ export const lines = (rows: readonly Text[]): Text => rows.flatMap((r, i) => (i ? ["\n", r] : [r]));
44
45
 
45
- async has(hash: string): Promise<boolean> {
46
- if (this.#known.has(hash)) return true;
46
+ /**
47
+ * 0.3.1 及以前,本插件自己把确认记在 $JADE_HOME/trust.jsonl(每行 { hash, path, at })。升级后照认,不用再确认一遍:
48
+ * trust@1 里没有时查这份旧文件,查到了顺手记进 trust@1。这是本插件自己的旧数据,核心不认识它
49
+ */
50
+ export function withLegacyTrust(trust: Trust, home: string): Trust {
51
+ let legacy: Promise<Map<string, string>> | undefined;
52
+ const read = async () => {
53
+ const hashes = new Map<string, string>();
47
54
  let text = "";
48
55
  try {
49
- text = await readFile(this.file, "utf8");
56
+ text = await readFile(path.join(home, "trust.jsonl"), "utf8");
50
57
  } catch {
51
- return false;
58
+ return hashes;
52
59
  }
53
60
  for (const line of text.split("\n")) {
54
61
  try {
55
- if ((JSON.parse(line) as { hash?: unknown }).hash === hash) {
56
- this.#known.add(hash);
57
- return true;
58
- }
62
+ const r = JSON.parse(line) as { hash?: unknown; path?: unknown };
63
+ if (typeof r.hash === "string") hashes.set(r.hash, typeof r.path === "string" ? r.path : "");
59
64
  } catch {
60
- // 写到一半的行
65
+ // 空行、写到一半的行
61
66
  }
62
67
  }
63
- return false;
64
- }
65
-
66
- async add(hash: string, where: string): Promise<void> {
67
- await mkdir(path.dirname(this.file), { recursive: true });
68
- await appendFile(this.file, `${JSON.stringify({ hash, path: where, at: new Date().toISOString() })}\n`);
69
- this.#known.add(hash);
70
- }
68
+ return hashes;
69
+ };
70
+ return {
71
+ has: async (hash) => {
72
+ if (await trust.has(hash)) return true;
73
+ const where = (await (legacy ??= read())).get(hash);
74
+ if (where === undefined) return false;
75
+ await trust.add(hash, where).catch(() => {});
76
+ return true;
77
+ },
78
+ add: (hash, where) => trust.add(hash, where),
79
+ };
71
80
  }
72
-
73
- export const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
74
-
75
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
76
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
77
- const paint = (open: string, close: string) => (s: string) =>
78
- colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
79
- export const dim = paint("2", "22");
80
- export const yellow = paint("33", "39");
81
- export const bold = paint("1", "22");
@@ -6,6 +6,8 @@ import type { CommandEntry, Commands } from "@uncarved/jade-api/services";
6
6
 
7
7
  const NAME = /^[a-z0-9][a-z0-9_-]*$/i;
8
8
  const registry = new Map<string, CommandEntry>();
9
+ /** 简写字符 → 命令名(小写) */
10
+ const prefixes = new Map<string, string>();
9
11
 
10
12
  export default definePlugin({
11
13
  process(ctx) {
@@ -14,20 +16,42 @@ export default definePlugin({
14
16
  if (typeof command?.name !== "string" || !NAME.test(command.name)) throw new Error(`invalid command name ${JSON.stringify(command?.name)}`);
15
17
  if (typeof command.run !== "function") throw new Error(`command /${command.name} has no run function`);
16
18
  const key = command.name.toLowerCase();
19
+ // 重名时先注册的留下,后来的这一条跳过并报告:抛错会让调用方整个激活失败,连它别的功能一起没了
17
20
  const taken = registry.get(key);
18
- if (taken) throw new Error(`command /${command.name} is already registered by ${taken.plugin}`);
19
- const entry: CommandEntry = { command, plugin: caller.plugin };
21
+ if (taken) {
22
+ ctx.report(`/${command.name} from ${caller.plugin} was skipped: ${taken.plugin} already registered it`);
23
+ return () => {};
24
+ }
25
+ if (command.prefix !== undefined && (typeof command.prefix !== "string" || [...command.prefix].length !== 1 || /[\p{L}\p{N}\s/]/u.test(command.prefix))) {
26
+ throw new Error(`command /${command.name}: prefix must be one character that is not a letter, digit, space or "/"`);
27
+ }
28
+ let entry: CommandEntry = { command, plugin: caller.plugin };
29
+ let prefix = command.prefix;
30
+ const owner = prefix === undefined ? undefined : prefixes.get(prefix);
31
+ if (prefix !== undefined && owner !== undefined) {
32
+ // 简写被占了:命令照常注册,只是没有简写
33
+ ctx.report(`the ${prefix} shortcut for /${command.name} from ${caller.plugin} was skipped: /${owner} already uses it`);
34
+ const { prefix: _, prefixHint: __, ...rest } = command;
35
+ entry = { command: rest as typeof command, plugin: caller.plugin };
36
+ prefix = undefined;
37
+ }
20
38
  registry.set(key, entry);
39
+ if (prefix !== undefined) prefixes.set(prefix, key);
21
40
  const revoke = () => {
22
41
  if (registry.get(key) === entry) registry.delete(key);
42
+ if (prefix !== undefined && prefixes.get(prefix) === key) prefixes.delete(prefix);
23
43
  };
24
44
  caller.onDispose(revoke);
25
45
  return revoke;
26
46
  },
27
47
  get: (name) => registry.get(name.toLowerCase()),
48
+ byPrefix: (prefix) => {
49
+ const name = prefixes.get(prefix);
50
+ return name === undefined ? undefined : registry.get(name);
51
+ },
28
52
  list: () =>
29
53
  [...registry.values()]
30
- .map(({ command: c, plugin }) => ({ name: c.name, ...(c.args ? { args: c.args } : {}), ...(c.description ? { description: c.description } : {}), ...(c.instant ? { instant: true } : {}), plugin }))
54
+ .map(({ command: c, plugin }) => ({ name: c.name, ...(c.args ? { args: c.args } : {}), ...(c.description ? { description: c.description } : {}), ...(c.instant ? { instant: true } : {}), ...(c.prefix ? { prefix: c.prefix } : {}), ...(c.prefixHint ? { prefixHint: c.prefixHint } : {}), plugin }))
31
55
  .sort((a, b) => a.name.localeCompare(b.name)),
32
56
  }));
33
57
  },
@@ -32,6 +32,8 @@ export interface CompactorOptions {
32
32
  /** 压缩后保留最近大约这么多 token 的原始消息,默认阈值的 30% */
33
33
  keepTokens?: number;
34
34
  id?: string;
35
+ /** 写文件的工具把路径放在输入的哪个字段(工具的 meta.writes);摘要后面列出改过的文件用 */
36
+ writes(tool: string): string | undefined;
35
37
  }
36
38
 
37
39
  export interface Compactor {
@@ -41,6 +43,8 @@ export interface Compactor {
41
43
  observe(e: LogEvent): void;
42
44
  /** 下一次请求前无论是否超过阈值都总结一次;focus 是用户要总结特别留意的事(/compact 后面写的) */
43
45
  request(focus?: string): void;
46
+ /** 最近一次 project 给出的投影有多少 token:和判断要不要压缩用的是同一个数(能用真实用量就用);还没投影过时 undefined */
47
+ projected(): number | undefined;
44
48
  }
45
49
 
46
50
  const SUMMARY_SYSTEM =
@@ -129,6 +133,7 @@ export function compactor(opts: CompactorOptions): Compactor {
129
133
  /** 最近一次投影:它对应的消息条数和压缩状态;收到回复后补上真实用量 */
130
134
  let last: { length: number; state: string; tokens?: number } | undefined;
131
135
  let pending: { length: number; state: string } | undefined;
136
+ let projected: number | undefined;
132
137
 
133
138
  const view = (messages: Message[], c: CompactState | undefined): Message[] => {
134
139
  if (!c) return messages;
@@ -169,6 +174,8 @@ export function compactor(opts: CompactorOptions): Compactor {
169
174
  const keep = opts.keepTokens ?? Math.floor(threshold * 0.3);
170
175
  const done = (out: Message[], c = prev) => {
171
176
  pending = { length: messages.length, state: JSON.stringify(c ?? null) };
177
+ // 没有清理、没有压缩时就是上面量出来的那个数;变了的(少见)重新估
178
+ projected = out === current ? tokens : estimateTokens(out);
172
179
  return out;
173
180
  };
174
181
  const current = view(messages, prev);
@@ -222,7 +229,7 @@ export function compactor(opts: CompactorOptions): Compactor {
222
229
  const todos = latestTodos(messages.slice(cut)) ? undefined : latestTodos(messages.slice(0, cut));
223
230
  if (todos?.length) summary += `\n\nTodo list at the time of compaction:\n${renderTodos(todos)}`;
224
231
  // 用户的原话和改过的文件也原样带上:只靠总结,压缩几轮后要求和约束容易走样
225
- summary += appendix(messages.slice(0, cut));
232
+ summary += appendix(messages.slice(0, cut), opts.writes);
226
233
 
227
234
  // 保留部分里已经清理过的输出继续保持清理,否则投影反而变大
228
235
  const next: CompactState = { upTo: cut, summary, ...(prev?.trimUpTo && prev.trimUpTo > cut ? { trimUpTo: prev.trimUpTo } : {}) };
@@ -243,6 +250,7 @@ export function compactor(opts: CompactorOptions): Compactor {
243
250
  forced = true;
244
251
  focus = what;
245
252
  },
253
+ projected: () => projected,
246
254
  };
247
255
  }
248
256
 
@@ -288,13 +296,12 @@ function renderTodos(todos: Todo[]): string {
288
296
  return todos.map((t) => `${MARK[t.status] ?? "[ ]"} ${t.content}`).join("\n");
289
297
  }
290
298
 
291
- const WRITE_TOOLS = new Set(["write_file", "edit_file", "multi_edit"]);
292
299
  /** 摘要后面附的用户原话的总长度上限 */
293
300
  const MAX_USER_CHARS = 6000;
294
301
  const MAX_USER_MESSAGE_CHARS = 1500;
295
302
 
296
303
  /** 被压缩部分里用户的原话(第一条和最近的几条)和成功修改过的文件 */
297
- function appendix(messages: Message[]): string {
304
+ function appendix(messages: Message[], writes: (tool: string) => string | undefined): string {
298
305
  const said: string[] = [];
299
306
  const ok = new Set<string>();
300
307
  const files: string[] = [];
@@ -305,8 +312,9 @@ function appendix(messages: Message[]): string {
305
312
  const text = m.content.flatMap((b) => (b.kind === "text" && b.origin.by === "user" ? [b.text.trim()] : [])).join("\n");
306
313
  if (text) said.push(text.length > MAX_USER_MESSAGE_CHARS ? `${text.slice(0, MAX_USER_MESSAGE_CHARS)}…` : text);
307
314
  for (const b of m.content) {
308
- if (b.kind !== "tool_use" || !WRITE_TOOLS.has(b.name) || !ok.has(b.id)) continue;
309
- const p = (b.input as { path?: unknown } | null)?.path;
315
+ const field = b.kind === "tool_use" && ok.has(b.id) ? writes(b.name) : undefined;
316
+ if (field === undefined || b.kind !== "tool_use") continue;
317
+ const p = (b.input as Record<string, unknown> | null)?.[field];
310
318
  if (typeof p === "string" && !files.includes(p)) files.push(p);
311
319
  }
312
320
  }
@@ -58,12 +58,24 @@ export default definePlugin({
58
58
  },
59
59
 
60
60
  session(ctx) {
61
+ // 子会话(子 Agent)不压缩:它活不长,上下文由开它的插件管(jade/task 接近窗口时让它写报告、只放最近的工具输出)
62
+ if (ctx.session.parent) return;
61
63
  const models = ctx.require<Models>("models@1");
62
64
  const configured = parseTokens(ctx.config.thresholdTokens);
63
65
  const keepTokens = parseTokens(ctx.config.keepTokens);
64
66
  const threshold = thresholdFor(ctx.config, models);
65
- const c = compactor({ complete: (req, o) => models.complete(req, o), threshold, keepTokens, id: ctx.plugin });
67
+ const c = compactor({ complete: (req, o) => models.complete(req, o), threshold, keepTokens, id: ctx.plugin, writes: (t) => ctx.session.tool(t)?.meta?.writes });
66
68
  const id = ctx.session.id;
69
+ /** 状态栏上的一段:多少 token 时自动压缩,投影离它不远(85%)时变黄 */
70
+ const show = (projected?: number) => {
71
+ const at = threshold();
72
+ if (!at) return ctx.status?.(undefined);
73
+ ctx.status?.({ text: `compacts at ${tokens(at)}`, ...(projected !== undefined && projected >= at * 0.85 ? { tone: "warn" as const } : {}) });
74
+ };
75
+ show();
76
+ // 换了模型,窗口和阈值跟着变
77
+ const offModel = models.subscribe?.(() => show());
78
+ if (offModel) void ctx.effect(() => offModel);
67
79
 
68
80
  ctx.kernel.hook({
69
81
  kind: "transform",
@@ -71,13 +83,15 @@ export default definePlugin({
71
83
  // 排在其他改投影的插件(例如 jade/mentions 附上引用的文件)之后:估算的是最终的投影
72
84
  order: 100,
73
85
  timeoutMs: SUMMARY_TIMEOUT_MS,
74
- fn: (messages, hook) => {
86
+ fn: async (messages, hook) => {
75
87
  const focus = requested.get(id);
76
88
  if (focus !== undefined) {
77
89
  requested.delete(id);
78
90
  c.request(focus || undefined);
79
91
  }
80
- return c.project(messages, hook);
92
+ const out = await c.project(messages, hook);
93
+ show(c.projected());
94
+ return out;
81
95
  },
82
96
  });
83
97
 
@@ -110,3 +124,6 @@ export default definePlugin({
110
124
  },
111
125
  });
112
126
 
127
+ /** 状态栏上的 token 数:12.3k、160k、1.2M */
128
+ const tokens = (n: number) =>
129
+ n >= 1_000_000 ? `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}M` : n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n);
@@ -1,17 +1,16 @@
1
- // 显示用的小工具:截断和 ANSI 颜色。插件之间不共享代码(只能共享类型),所以这里也有一份(同 jade/fs 的 style.ts)。
1
+ // 显示用的小工具:截断,和带语义样式的文字(jade-api 的 Text)。插件只说这段是次要的、成功、警告……,
2
+ // 怎么画由前端决定(终端界面画成颜色,-p 只取文字)。插件之间不共享代码(只能共享类型),所以每个插件有一份。
3
+
4
+ import type { Span, Text, TextStyle } from "@uncarved/jade-api";
2
5
 
3
6
  export const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
4
7
 
5
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
6
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
7
- /**
8
- * 每种样式用自己的关闭码,不用 \x1b[0m 全部重置:外面套着别的样式时,后面的文字仍保持外层样式。
9
- * 里面出现同一个关闭码(例如 dim 里套 bold,两者都用 22 关闭)时紧接着重新打开外层的样式
10
- */
11
- const paint = (open: string, close: string) => (s: string) =>
12
- colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
13
- export const dim = paint("2", "22");
14
- export const red = paint("31", "39");
15
- export const green = paint("32", "39");
16
- export const yellow = paint("33", "39");
17
- export const bold = paint("1", "22");
8
+ const styled = (style: TextStyle) => (text: string): Span => ({ text, style });
9
+ export const dim = styled("dim");
10
+ export const bold = styled("bold");
11
+ export const ok = styled("ok");
12
+ export const warn = styled("warn");
13
+ export const error = styled("error");
14
+
15
+ /** 几行接成一段,行之间换行 */
16
+ export const lines = (rows: readonly Text[]): Text => rows.flatMap((r, i) => (i ? ["\n", r] : [r]));
@@ -0,0 +1,35 @@
1
+ // jade/completions:输入框补全的注册表(completions@1)。前端在输入框里遇到触发字符时查这里取候选;
2
+ // 候选是什么、发送时拿它做什么归登记的插件(例如 jade/mentions 的 @ 文件)。只登记,不知道谁在用。
3
+
4
+ import { definePlugin } from "@uncarved/jade-api";
5
+ import type { Completion, Completions } from "@uncarved/jade-api/services";
6
+
7
+ const registry = new Map<string, { completion: Completion; plugin: string }>();
8
+
9
+ export default definePlugin({
10
+ process(ctx) {
11
+ ctx.provide("completions@1", (caller): Completions => ({
12
+ register(completion) {
13
+ const trigger = completion?.trigger;
14
+ if (typeof trigger !== "string" || [...trigger].length !== 1 || /[\p{L}\p{N}\s/]/u.test(trigger)) {
15
+ throw new Error(`invalid completion trigger ${JSON.stringify(trigger)}: use one character that is not a letter, digit, space or "/"`);
16
+ }
17
+ if (typeof completion.candidates !== "function") throw new Error(`completion ${trigger} has no candidates function`);
18
+ // 重名时先登记的留下,后来的跳过并报告(同 commands@1)
19
+ const taken = registry.get(trigger);
20
+ if (taken) {
21
+ ctx.report(`completion ${trigger} from ${caller.plugin} was skipped: ${taken.plugin} already registered it`);
22
+ return () => {};
23
+ }
24
+ const entry = { completion, plugin: caller.plugin };
25
+ registry.set(trigger, entry);
26
+ const revoke = () => {
27
+ if (registry.get(trigger) === entry) registry.delete(trigger);
28
+ };
29
+ caller.onDispose(revoke);
30
+ return revoke;
31
+ },
32
+ list: () => [...registry.values()],
33
+ }));
34
+ },
35
+ });
@@ -0,0 +1,7 @@
1
+ {
2
+ "id": "jade/completions",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.ts",
6
+ "provides": ["completions@1"]
7
+ }
@@ -0,0 +1,46 @@
1
+ // jade/copy:/copy 把最后一条回复(模型写的原文,没有折行和排版)放进剪贴板;/copy code 只放它的最后一个代码块。
2
+ // 原来写在 jade/tui 里;回复从当前会话的状态里取,剪贴板经 ui@1.copy,所以任何有剪贴板的前端都能用。
3
+
4
+ import type { Block } from "uncarved";
5
+ import { definePlugin, type Span, type TextStyle } from "@uncarved/jade-api";
6
+ import type { Commands } from "@uncarved/jade-api/services";
7
+
8
+ const styled = (style: TextStyle) => (text: string): Span => ({ text, style });
9
+ const dim = styled("dim");
10
+ const error = styled("error");
11
+
12
+ /** 最近一条有正文的助手消息的正文 */
13
+ export function lastReply(messages: readonly { role: string; content: readonly Block[] }[]): string | undefined {
14
+ for (let i = messages.length - 1; i >= 0; i--) {
15
+ const m = messages[i]!;
16
+ if (m.role !== "assistant") continue;
17
+ const text = m.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim();
18
+ if (text) return text;
19
+ }
20
+ return undefined;
21
+ }
22
+
23
+ /** Markdown 里最后一个围栏代码块的内容 */
24
+ export function lastCodeBlock(markdown: string): string | undefined {
25
+ const blocks = [...markdown.matchAll(/^ {0,3}(`{3,}|~{3,})[^\n]*\n([\s\S]*?)^ {0,3}\1[`~]*[ \t]*$/gm)];
26
+ return blocks.at(-1)?.[2]?.replace(/\n$/, "");
27
+ }
28
+
29
+ export default definePlugin({
30
+ process(ctx) {
31
+ ctx.require<Commands>("commands@1").register({
32
+ name: "copy",
33
+ args: "[code]",
34
+ description: "copy the last reply to the clipboard as it was written (code: only its last code block)",
35
+ instant: true,
36
+ run(args, c) {
37
+ const code = args.trim() === "code";
38
+ const reply = lastReply(c.sessions.current?.state.messages ?? []);
39
+ const text = code ? reply && lastCodeBlock(reply) : reply;
40
+ if (!text) return dim(code ? "The last reply has no code block." : "There is no reply to copy yet.");
41
+ if (!c.ui.copy?.(text)) return error("[error] this front end cannot copy to the clipboard");
42
+ return dim(`[copied ${[...text].length} characters]`);
43
+ },
44
+ });
45
+ },
46
+ });
@@ -0,0 +1,7 @@
1
+ {
2
+ "id": "jade/copy",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.ts",
6
+ "requires": ["commands@1"]
7
+ }
@@ -66,10 +66,16 @@ export default definePlugin({
66
66
  };
67
67
  // 键被别的插件占了不算这个插件坏了:只是没有这个键,换一个就行
68
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`;
69
+ const keys = ctx.require<Keys>("keys@1");
70
+ const taken = keys.get(binding.key)?.plugin;
71
+ const fix = `set {"jade/editor": {"key": "ctrl+<letter>"}} in config.json to use another key`;
72
+ if (taken) noKey = `${binding.key} is already used by ${taken}; ${fix}`;
73
+ else {
74
+ try {
75
+ keys.register(binding);
76
+ } catch (e) {
77
+ noKey = `${e instanceof Error ? e.message : String(e)}; ${fix}`;
78
+ }
73
79
  }
74
80
  },
75
81
 
@@ -3,7 +3,8 @@
3
3
  // 先去掉相同的开头和结尾,只对中间部分求最长公共子序列;中间部分太大时(整个文件重写)
4
4
  // 不再逐行比较,整段显示为删除加新增,避免占用大量内存和时间。
5
5
 
6
- import { dim, green, red } from "./style.ts";
6
+ import type { Text } from "@uncarved/jade-api";
7
+ import { added as plus, dim, lines as joinLines, removed as minus } from "./style.ts";
7
8
 
8
9
  export type DiffLine = { kind: " " | "-" | "+"; text: string; /** 旧文件里的行号(删除、相同) */ old?: number; /** 新文件里的行号(新增、相同) */ new?: number };
9
10
 
@@ -110,11 +111,11 @@ export function diffStats(lines: DiffLine[]): DiffStats {
110
111
  * 显示用:每行前面是行号(新增行用新文件的行号,其余用旧文件的),段与段之间用 ⋯ 分开。
111
112
  * 超过 maxLines 行时截断
112
113
  */
113
- export function renderDiff(before: string, after: string, maxLines = 60, lines = diffLines(before, after)): string {
114
+ export function renderDiff(before: string, after: string, maxLines = 60, lines = diffLines(before, after)): Text {
114
115
  const parts = hunks(lines);
115
116
  if (parts.length === 0) return dim(" (no changes)");
116
117
  const width = String(lines.reduce((w, l) => Math.max(w, l.old ?? 0, l.new ?? 0), 0)).length;
117
- const out: string[] = [];
118
+ const out: Text[] = [];
118
119
  let shown = 0;
119
120
  let total = 0;
120
121
  for (const h of parts) total += h.length;
@@ -124,12 +125,12 @@ export function renderDiff(before: string, after: string, maxLines = 60, lines =
124
125
  if (shown >= maxLines) break;
125
126
  const no = String((l.kind === "+" ? l.new : l.old) ?? "").padStart(width);
126
127
  const text = `${no} ${l.kind} ${l.text}`;
127
- out.push(l.kind === "+" ? green(text) : l.kind === "-" ? red(text) : dim(text));
128
+ out.push(l.kind === "+" ? plus(text) : l.kind === "-" ? minus(text) : dim(text));
128
129
  shown++;
129
130
  }
130
131
  }
131
132
  if (total > shown) out.push(dim(` … ${total - shown} more lines`));
132
133
  const { added, removed } = diffStats(lines);
133
- out.push(dim(` ${green(`+${added}`)} ${red(`-${removed}`)}`));
134
- return out.join("\n");
134
+ out.push([" ", plus(`+${added}`), " ", minus(`-${removed}`)]);
135
+ return joinLines(out);
135
136
  }