@uncarved/jade 0.3.1 → 0.4.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 (206) 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 +490 -29
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +36 -14
  14. package/plugins/approval/policy.ts +15 -10
  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 +42 -9
  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 +47 -12
  50. package/plugins/models/index.ts +27 -1
  51. package/plugins/models/provider.ts +24 -0
  52. package/plugins/models/saved.ts +1 -1
  53. package/plugins/modes/index.ts +13 -2
  54. package/plugins/print/index.ts +7 -4
  55. package/plugins/prompts/index.ts +0 -0
  56. package/plugins/renderers/index.ts +10 -5
  57. package/plugins/repeats/index.ts +8 -8
  58. package/plugins/schedule/index.ts +5 -1
  59. package/plugins/screenshot/browser.ts +10 -0
  60. package/plugins/sessions/index.ts +48 -2
  61. package/plugins/shell/index.ts +27 -28
  62. package/plugins/shell/plugin.json +1 -1
  63. package/plugins/shell/renderers.ts +9 -7
  64. package/plugins/shell/shell.ts +3 -1
  65. package/plugins/skills/index.ts +28 -19
  66. package/plugins/skills/project.ts +12 -7
  67. package/plugins/steer/index.ts +5 -4
  68. package/plugins/task/index.ts +80 -50
  69. package/plugins/task/plugin.json +6 -2
  70. package/plugins/task/style.ts +13 -14
  71. package/plugins/task/subagent.ts +67 -184
  72. package/plugins/todo/index.ts +39 -9
  73. package/plugins/tools/index.ts +9 -2
  74. package/plugins/tui/frontend.ts +139 -89
  75. package/plugins/tui/index.ts +2 -3
  76. package/plugins/tui/mentions.ts +11 -80
  77. package/plugins/tui/plugin.json +1 -1
  78. package/plugins/tui/screen.ts +55 -5
  79. package/plugins/tui/transcript.ts +17 -7
  80. package/plugins/tui/tui.ts +337 -101
  81. package/plugins/tui/vendor.ts +1 -1
  82. package/plugins/undo/checkpoint.ts +8 -4
  83. package/plugins/undo/index.ts +170 -31
  84. package/plugins/undo/plugin.json +1 -0
  85. package/plugins/undo/snapshot.ts +87 -14
  86. package/plugins/undo/style.ts +13 -14
  87. package/plugins/web/index.ts +7 -18
  88. package/plugins/web/plugin.json +1 -1
  89. package/plugins-dist/approval/index.js +363 -418
  90. package/plugins-dist/approval/policy.js +391 -508
  91. package/plugins-dist/approval/review.js +132 -158
  92. package/plugins-dist/approval/schema.js +50 -55
  93. package/plugins-dist/ask/index.js +115 -129
  94. package/plugins-dist/budget/index.js +27 -31
  95. package/plugins-dist/checks/checks.js +293 -329
  96. package/plugins-dist/checks/index.js +119 -139
  97. package/plugins-dist/checks/plugin.json +2 -1
  98. package/plugins-dist/checks/project.js +57 -65
  99. package/plugins-dist/commands/index.js +47 -29
  100. package/plugins-dist/compact/compact.js +233 -249
  101. package/plugins-dist/compact/index.js +98 -95
  102. package/plugins-dist/compact/style.js +9 -14
  103. package/plugins-dist/completions/index.js +30 -0
  104. package/plugins-dist/completions/plugin.json +9 -0
  105. package/plugins-dist/continue/index.js +40 -52
  106. package/plugins-dist/copy/index.js +40 -0
  107. package/plugins-dist/copy/plugin.json +9 -0
  108. package/plugins-dist/cost/index.js +98 -115
  109. package/plugins-dist/custom-commands/index.js +55 -72
  110. package/plugins-dist/editor/index.js +64 -72
  111. package/plugins-dist/fs/diff.js +111 -124
  112. package/plugins-dist/fs/fs.js +426 -469
  113. package/plugins-dist/fs/grep.js +262 -253
  114. package/plugins-dist/fs/index.js +20 -34
  115. package/plugins-dist/fs/plugin.json +1 -2
  116. package/plugins-dist/fs/renderers.js +100 -112
  117. package/plugins-dist/fs/style.js +11 -15
  118. package/plugins-dist/fs/sys.js +31 -43
  119. package/plugins-dist/hooks/index.js +107 -127
  120. package/plugins-dist/keys/index.js +27 -31
  121. package/plugins-dist/mcp/index.js +271 -199
  122. package/plugins-dist/mcp/install.js +123 -137
  123. package/plugins-dist/mcp/mcp.js +638 -577
  124. package/plugins-dist/mcp/plugin.json +3 -1
  125. package/plugins-dist/mcp/project.js +98 -115
  126. package/plugins-dist/memory/index.js +83 -88
  127. package/plugins-dist/memory/memory.js +111 -128
  128. package/plugins-dist/memory/style.js +9 -14
  129. package/plugins-dist/mentions/attach.js +91 -99
  130. package/plugins-dist/mentions/candidates.js +49 -0
  131. package/plugins-dist/mentions/index.js +71 -81
  132. package/plugins-dist/mentions/plugin.json +2 -1
  133. package/plugins-dist/mentions/style.js +9 -14
  134. package/plugins-dist/models/config.js +29 -43
  135. package/plugins-dist/models/configure.js +421 -474
  136. package/plugins-dist/models/context.js +14 -22
  137. package/plugins-dist/models/index.js +182 -189
  138. package/plugins-dist/models/provider.js +263 -307
  139. package/plugins-dist/models/saved.js +60 -72
  140. package/plugins-dist/modes/index.js +138 -165
  141. package/plugins-dist/plugins/index.js +34 -34
  142. package/plugins-dist/print/index.js +192 -175
  143. package/plugins-dist/prompts/index.js +86 -89
  144. package/plugins-dist/prompts/notes.js +31 -37
  145. package/plugins-dist/prompts/prompts.js +155 -193
  146. package/plugins-dist/prompts/results.js +40 -53
  147. package/plugins-dist/prompts/sys.js +39 -50
  148. package/plugins-dist/renderers/index.js +32 -32
  149. package/plugins-dist/repeats/index.js +131 -174
  150. package/plugins-dist/schedule/cron.js +49 -56
  151. package/plugins-dist/schedule/index.js +230 -247
  152. package/plugins-dist/schedule/store.js +93 -109
  153. package/plugins-dist/scratch/index.js +12 -18
  154. package/plugins-dist/screenshot/browser.js +136 -154
  155. package/plugins-dist/screenshot/index.js +37 -46
  156. package/plugins-dist/screenshot/sys.js +53 -65
  157. package/plugins-dist/screenshot/tool.js +98 -126
  158. package/plugins-dist/sessions/index.js +149 -117
  159. package/plugins-dist/shell/index.js +117 -135
  160. package/plugins-dist/shell/plugin.json +1 -1
  161. package/plugins-dist/shell/renderers.js +28 -33
  162. package/plugins-dist/shell/service.js +17 -23
  163. package/plugins-dist/shell/shell.js +307 -362
  164. package/plugins-dist/shell/sys.js +64 -79
  165. package/plugins-dist/skills/index.js +193 -211
  166. package/plugins-dist/skills/install.js +122 -149
  167. package/plugins-dist/skills/project.js +65 -73
  168. package/plugins-dist/skills/skills.js +135 -171
  169. package/plugins-dist/steer/index.js +108 -125
  170. package/plugins-dist/suggest/index.js +235 -259
  171. package/plugins-dist/task/index.js +130 -117
  172. package/plugins-dist/task/plugin.json +5 -2
  173. package/plugins-dist/task/style.js +9 -14
  174. package/plugins-dist/task/subagent.js +156 -279
  175. package/plugins-dist/todo/index.js +79 -63
  176. package/plugins-dist/tools/index.js +36 -42
  177. package/plugins-dist/tui/editor.js +145 -160
  178. package/plugins-dist/tui/frontend.js +639 -678
  179. package/plugins-dist/tui/history.js +34 -37
  180. package/plugins-dist/tui/index.js +16 -18
  181. package/plugins-dist/tui/markdown.js +203 -247
  182. package/plugins-dist/tui/mascot.js +266 -355
  183. package/plugins-dist/tui/mentions.js +67 -144
  184. package/plugins-dist/tui/plugin.json +1 -2
  185. package/plugins-dist/tui/render.js +35 -45
  186. package/plugins-dist/tui/screen.js +197 -180
  187. package/plugins-dist/tui/transcript.js +436 -468
  188. package/plugins-dist/tui/tui.js +1554 -1656
  189. package/plugins-dist/tui/vendor.js +1088 -1388
  190. package/plugins-dist/undo/checkpoint.js +97 -118
  191. package/plugins-dist/undo/index.js +281 -192
  192. package/plugins-dist/undo/plugin.json +3 -0
  193. package/plugins-dist/undo/snapshot.js +134 -99
  194. package/plugins-dist/undo/style.js +9 -14
  195. package/plugins-dist/update/index.js +26 -28
  196. package/plugins-dist/web/env.js +55 -68
  197. package/plugins-dist/web/index.js +80 -110
  198. package/plugins-dist/web/plugin.json +1 -2
  199. package/plugins-dist/web/renderers.js +4 -5
  200. package/plugins-dist/web/web.js +514 -593
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +9 -2
  203. package/src/api.ts +1 -1
  204. package/src/host.ts +39 -4
  205. package/src/remote.ts +6 -1
  206. package/src/session.ts +496 -36
@@ -1,288 +1,264 @@
1
- // jade/suggest:每一轮正常结束后,预测用户下一条想发的消息,灰色显示在输入框里,Tab 或 → 接受。默认关着(enabled)。
2
- //
3
- // 模型经 models@1:配置 model 是 /model 保存过的模型名或当前服务上的模型名,不设时用会话的模型。
4
- // /suggest 在 TUI 里开关、选模型,马上生效,记在 $JADE_HOME/state/suggest.json,盖过 config.json 里的 enabled 和 model。
5
- // 对话从 context.project(每次请求模型前的消息)和 model.after(这一轮最后的回复)取,轮次结束从 turn.ended 事件知道。
6
- // 从旧 jade 的 examples/plugins/suggest 移植;提示词、对话的整理和截取、回复的清理参考 dsh-ghost-prompt。
7
1
  import { randomBytes } from "node:crypto";
8
2
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
9
3
  import path from "node:path";
10
4
  import { definePlugin } from "@uncarved/jade-api";
11
5
  export const SYSTEM = [
12
- "You predict the next message the USER will type to an AI coding assistant.",
13
- "You are given the recent conversation. Write the single message the user is most likely to send next, exactly as they would type it.",
14
- "Rules:",
15
- '- Write from the user\'s point of view, addressed to the assistant (e.g. "run the tests", "commit this", "yes, go ahead").',
16
- "- Match the language and tone the user has been writing in. If the user writes Chinese, answer in Chinese.",
17
- "- Keep it short: one sentence, at most about 20 words or 40 CJK characters.",
18
- "- Prefer the obvious next step: answering a question the assistant just asked, approving a proposed plan, verifying or continuing the work.",
19
- "- The user gives instructions; write an instruction or a short answer, not a question.",
20
- '- Never summarize or describe the work that was done (wrong: "the Title weights are fixed now"). That is the assistant\'s job, not the user\'s.',
21
- '- Never speak as the assistant: no offers or plans like "want me to...", "I will...", "需要我…吗", "我会…". When the assistant offered something, the user accepts or declines it (assistant: "I can commit this if you want" -> user: "commit it").',
22
- "- Never repeat a request the user already made, and never invent facts, file names or numbers not in the conversation.",
23
- "- If no next message is reasonably predictable, output exactly: NONE",
24
- 'Output only the message text on one line. No quotes, no prefix like "User:", no explanation, no Markdown.',
25
- ].join("\n");
26
- /** 送给预测模型的最近对话(字符),从最新的往前取 */
6
+ "You predict the next message the USER will type to an AI coding assistant.",
7
+ "You are given the recent conversation. Write the single message the user is most likely to send next, exactly as they would type it.",
8
+ "Rules:",
9
+ `- Write from the user's point of view, addressed to the assistant (e.g. "run the tests", "commit this", "yes, go ahead").`,
10
+ "- Match the language and tone the user has been writing in. If the user writes Chinese, answer in Chinese.",
11
+ "- Keep it short: one sentence, at most about 20 words or 40 CJK characters.",
12
+ "- Prefer the obvious next step: answering a question the assistant just asked, approving a proposed plan, verifying or continuing the work.",
13
+ "- The user gives instructions; write an instruction or a short answer, not a question.",
14
+ `- Never summarize or describe the work that was done (wrong: "the Title weights are fixed now"). That is the assistant's job, not the user's.`,
15
+ '- Never speak as the assistant: no offers or plans like "want me to...", "I will...", "需要我…吗", "我会…". When the assistant offered something, the user accepts or declines it (assistant: "I can commit this if you want" -> user: "commit it").',
16
+ "- Never repeat a request the user already made, and never invent facts, file names or numbers not in the conversation.",
17
+ "- If no next message is reasonably predictable, output exactly: NONE",
18
+ 'Output only the message text on one line. No quotes, no prefix like "User:", no explanation, no Markdown.'
19
+ ].join(`
20
+ `);
27
21
  const MAX_CONTEXT_CHARS = 8000;
28
- /** 每条消息最多这么多字,超出时留头尾 */
29
22
  const PER_MESSAGE_CHARS = 2400;
30
- /** 一次预测的时限 */
31
- const TIMEOUT_MS = 30_000;
32
- /** 太长的消息留头和尾,中间最不要紧 */
23
+ const TIMEOUT_MS = 30000;
33
24
  function clip(text, max) {
34
- if (text.length <= max)
35
- return text;
36
- const half = Math.floor((max - 5) / 2);
37
- return `${text.slice(0, half)}\n…\n${text.slice(-half)}`;
25
+ if (text.length <= max)
26
+ return text;
27
+ const half = Math.floor((max - 5) / 2);
28
+ return `${text.slice(0, half)}
29
+ …
30
+ ${text.slice(-half)}`;
38
31
  }
39
- /** 一条消息里给预测模型看的文字:用户消息只取用户自己打的字(工具结果、插件附的说明不算),回复里的工具调用只留名字 */
40
32
  function textOf(m) {
41
- const parts = [];
42
- for (const b of m.content) {
43
- if (b.kind === "text" && b.text.trim() && (m.role === "assistant" || b.origin.by === "user"))
44
- parts.push(b.text.trim());
45
- else if (b.kind === "tool_use" && m.role === "assistant")
46
- parts.push(`[called tool: ${b.name}]`);
47
- }
48
- return parts.join("\n");
33
+ const parts = [];
34
+ for (const b of m.content) {
35
+ if (b.kind === "text" && b.text.trim() && (m.role === "assistant" || b.origin.by === "user"))
36
+ parts.push(b.text.trim());
37
+ else if (b.kind === "tool_use" && m.role === "assistant")
38
+ parts.push(`[called tool: ${b.name}]`);
39
+ }
40
+ return parts.join(`
41
+ `);
49
42
  }
50
- /** 整理成用户、助手交替的对话:没有文字的消息去掉,相邻同一方的合并(一轮里助手的几步并成一条) */
51
43
  export function transcriptOf(messages) {
52
- const out = [];
53
- for (const m of messages) {
54
- const text = textOf(m);
55
- if (!text)
56
- continue;
57
- const last = out.at(-1);
58
- if (last?.role === m.role)
59
- last.text += `\n${text}`;
60
- else
61
- out.push({ role: m.role, text });
62
- }
63
- return out;
44
+ const out = [];
45
+ for (const m of messages) {
46
+ const text = textOf(m);
47
+ if (!text)
48
+ continue;
49
+ const last = out.at(-1);
50
+ if (last?.role === m.role)
51
+ last.text += `
52
+ ${text}`;
53
+ else
54
+ out.push({ role: m.role, text });
55
+ }
56
+ return out;
64
57
  }
65
- const frameLine = (e) => `<${e.role}>\n${clip(e.text, PER_MESSAGE_CHARS)}\n</${e.role}>`;
66
- /** 从最新的往前放,放不下就停;最后一条总是放进去 */
58
+ const frameLine = (e) => `<${e.role}>
59
+ ${clip(e.text, PER_MESSAGE_CHARS)}
60
+ </${e.role}>`;
67
61
  export function frame(transcript, budget = MAX_CONTEXT_CHARS) {
68
- const lines = [];
69
- let used = 0;
70
- for (let i = transcript.length - 1; i >= 0; i--) {
71
- const line = frameLine(transcript[i]);
72
- if (lines.length > 0 && used + line.length > budget)
73
- break;
74
- lines.unshift(line);
75
- used += line.length;
76
- }
77
- return ["Recent conversation, oldest first:", "", lines.join("\n\n"), "", "Predict the user's next message."].join("\n");
62
+ const lines = [];
63
+ let used = 0;
64
+ for (let i = transcript.length - 1;i >= 0; i--) {
65
+ const line = frameLine(transcript[i]);
66
+ if (lines.length > 0 && used + line.length > budget)
67
+ break;
68
+ lines.unshift(line);
69
+ used += line.length;
70
+ }
71
+ return ["Recent conversation, oldest first:", "", lines.join(`
72
+
73
+ `), "", "Predict the user's next message."].join(`
74
+ `);
78
75
  }
79
76
  const LEADING_PREFIX = /^(?:user|用户)\s*[::]\s*/i;
80
77
  const LEADING_QUOTES = /^["'“”‘’`「『]+/;
81
78
  const TRAILING_QUOTES = /["'“”‘’`」』]+$/;
82
- /** 模型回复的第一行整理成建议:去掉 "User:" 前缀和包着的引号;NONE、空或问句的时候 undefined */
83
79
  export function tidy(reply) {
84
- let line = reply.trimStart().split(/\r?\n/)[0].trim().replace(LEADING_PREFIX, "");
85
- if (LEADING_QUOTES.test(line))
86
- line = line.replace(LEADING_QUOTES, "").replace(TRAILING_QUOTES, "").trim();
87
- // 问句多半是模型把助手的"要不要我…?"当成了用户的话,猜中用户真要问什么的少,不显示
88
- if (!line || /^none\.?$/i.test(line) || /[??]$/.test(line))
89
- return undefined;
90
- return line.length > 300 ? `${line.slice(0, 299)}…` : line;
80
+ let line = reply.trimStart().split(/\r?\n/)[0].trim().replace(LEADING_PREFIX, "");
81
+ if (LEADING_QUOTES.test(line))
82
+ line = line.replace(LEADING_QUOTES, "").replace(TRAILING_QUOTES, "").trim();
83
+ if (!line || /^none\.?$/i.test(line) || /[??]$/.test(line))
84
+ return;
85
+ return line.length > 300 ? `${line.slice(0, 299)}…` : line;
91
86
  }
92
- /** process() 里读好、/suggest 改的设置,session() 里每次预测时读 */
93
87
  let settings = { enabled: false, model: undefined };
94
- /** 设置改了时通知每个会话(关掉时去掉已经显示的建议) */
95
- const changed = new Set();
96
- /** state/suggest.json 里 /suggest 记下的设置;没有、读不了或格式不对的键不算 */
88
+ const changed = new Set;
97
89
  async function readState(file) {
98
- try {
99
- const data = JSON.parse(await readFile(file, "utf8"));
100
- return {
101
- ...(typeof data.enabled === "boolean" ? { enabled: data.enabled } : {}),
102
- // 空字符串表示用会话的模型
103
- ...(typeof data.model === "string" ? { model: data.model.trim() || undefined } : {}),
104
- };
105
- }
106
- catch {
107
- return {};
108
- }
90
+ try {
91
+ const data = JSON.parse(await readFile(file, "utf8"));
92
+ return {
93
+ ...typeof data.enabled === "boolean" ? { enabled: data.enabled } : {},
94
+ ...typeof data.model === "string" ? { model: data.model.trim() || undefined } : {}
95
+ };
96
+ } catch {
97
+ return {};
98
+ }
109
99
  }
110
100
  async function writeState(file, s) {
111
- await mkdir(path.dirname(file), { recursive: true });
112
- const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
113
- await writeFile(tmp, `${JSON.stringify({ enabled: s.enabled, model: s.model ?? "" }, null, 2)}\n`);
114
- await rename(tmp, file);
101
+ await mkdir(path.dirname(file), { recursive: true });
102
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
103
+ await writeFile(tmp, `${JSON.stringify({ enabled: s.enabled, model: s.model ?? "" }, null, 2)}
104
+ `);
105
+ await rename(tmp, file);
115
106
  }
116
107
  export default definePlugin({
117
- async process(ctx) {
118
- const file = path.join(ctx.home, "state", "suggest.json");
119
- const raw = ctx.config.model;
120
- if (raw !== undefined && typeof raw !== "string")
121
- ctx.service("ui@1")?.notify(`jade/suggest: model must be a model name, got ${JSON.stringify(raw)}; using the session's model`, "warning");
122
- settings = {
123
- enabled: ctx.config.enabled === true,
124
- model: typeof raw === "string" && raw.trim() ? raw.trim() : undefined,
125
- ...(await readState(file)),
126
- };
127
- const models = ctx.require("models@1");
128
- const describe = () => `suggestions are ${settings.enabled ? "on" : "off"}, predicted by ${settings.model ? `the model ${settings.model}` : "the session's model"}`;
129
- const update = async (next) => {
130
- settings = { ...settings, ...next };
131
- for (const fn of changed)
132
- fn();
133
- await writeState(file, settings);
134
- return `${describe()}.`;
135
- };
136
- ctx.service("commands@1")?.register({
137
- name: "suggest",
138
- args: "[on|off|model [name]]",
139
- description: "predict your next message after each turn (one more model request per turn), and which model predicts",
140
- // 只改插件自己的设置
141
- instant: true,
142
- async run(args, c) {
143
- const [sub = "", ...rest] = args.trim().split(/\s+/);
144
- if (sub === "on" || sub === "off")
145
- return update({ enabled: sub === "on" });
146
- if (sub === "model") {
147
- // 能选的:/model 保存过的,加上当前服务提供的(不用先在 /model 里保存)
148
- const [saved, listed] = await Promise.all([models.saved?.() ?? [], models.list().catch(() => [])]);
149
- const names = [...new Set([...saved, ...listed])];
150
- let name = rest.join(" ");
151
- if (!name) {
152
- const SESSION = "\0session";
153
- const picked = await c.ui.select({
154
- title: "Which model predicts your next message?",
155
- options: [
156
- { label: "The session's model", value: SESSION },
157
- ...names.map((m) => ({ label: m, value: m, ...(m === settings.model ? { hint: "current" } : saved.includes(m) ? { hint: "saved" } : {}) })),
158
- ],
159
- }, c.signal);
160
- if (picked === undefined)
161
- return;
162
- name = picked === SESSION ? undefined : picked;
163
- }
164
- else if (models.saved && !names.includes(name)) {
165
- return `${name} is not a model saved by /model or offered by the current service. ${names.length ? `Available: ${names.join(", ")}.` : "Add one with /model first."}`;
166
- }
167
- return update({ model: name });
168
- }
169
- if (sub)
170
- return "usage: /suggest [on|off|model [name]]";
171
- return `${describe()}. /suggest on|off turns them on or off; /suggest model picks the model.`;
172
- },
173
- });
174
- },
175
- session(ctx) {
176
- const input = ctx.input;
177
- // 没有输入框的前端(-p)用不上
178
- if (!input)
179
- return;
180
- const models = ctx.require("models@1");
181
- /** 最近一次发给模型的消息,加上这一轮最后的回复 */
182
- let messages = [];
183
- let reply;
184
- /** 正在进行的预测:新的一次请求开始、会话结束时中止 */
185
- let pending;
186
- ctx.signal.addEventListener("abort", () => pending?.abort());
187
- // /suggest off:停下正在进行的预测,去掉已经显示的建议
188
- const onChange = () => {
189
- if (settings.enabled)
190
- return;
191
- pending?.abort();
192
- input.hint(undefined);
193
- };
194
- changed.add(onChange);
195
- ctx.signal.addEventListener("abort", () => changed.delete(onChange));
196
- /** 上一次提示过的错误:同样的错误每轮都提示太吵,成功一次后清掉 */
197
- let warned;
198
- const warn = (e) => {
199
- const message = e instanceof Error ? e.message : String(e);
200
- if (message === warned)
201
- return;
202
- warned = message;
203
- ctx.service("ui@1")?.notify(`jade/suggest: prediction failed (${settings.model ? `model ${settings.model}` : "the session's model"}): ${message}`, "warning");
204
- };
205
- async function predict() {
206
- if (!settings.enabled)
207
- return;
208
- const { model } = settings;
209
- const transcript = transcriptOf([...messages, ...(reply ? [reply] : [])]);
210
- // 用户还没说过话,或者最后不是助手的回复:没有可回答的
211
- if (!transcript.some((e) => e.role === "user") || transcript.at(-1)?.role !== "assistant")
212
- return;
213
- pending?.abort();
214
- const mine = (pending = new AbortController());
215
- // 第一行完整了就停:建议只要一行,后面的都会丢掉
216
- const firstLine = new AbortController();
217
- let streamed = "";
218
- const onDelta = (d) => {
219
- if (d.kind === "reset")
220
- streamed = "";
221
- else if (d.kind === "text")
222
- streamed += d.text;
223
- if (/\S[^\n]*\n/.test(streamed))
224
- firstLine.abort();
225
- };
226
- const origin = { by: "plugin", id: ctx.plugin };
227
- const request = {
228
- system: [{ text: SYSTEM, stability: "stable", origin, trust: "trusted" }],
229
- messages: [{ role: "user", content: [{ kind: "text", text: frame(transcript), origin, trust: "trusted" }] }],
230
- tools: [],
231
- };
232
- let text;
233
- const timeout = AbortSignal.timeout(TIMEOUT_MS);
234
- try {
235
- const res = await models.complete(request, {
236
- signal: AbortSignal.any([mine.signal, firstLine.signal, timeout]),
237
- onDelta,
238
- ...(model ? { model } : {}),
239
- });
240
- text = res.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("");
241
- }
242
- catch (e) {
243
- // 第一行完整后自己停下的,用已经收到的
244
- if (firstLine.signal.aborted && !mine.signal.aborted)
245
- text = streamed;
246
- else {
247
- // 超时、被中止不打扰用户;模型出错(配置不对之类)说一次,否则开着却什么都不显示,看不出为什么
248
- if (!mine.signal.aborted && !timeout.aborted && !ctx.signal.aborted)
249
- warn(e);
250
- return;
251
- }
252
- }
253
- warned = undefined;
254
- const hint = tidy(text);
255
- if (hint && !mine.signal.aborted)
256
- input.hint(hint);
108
+ async process(ctx) {
109
+ const file = path.join(ctx.home, "state", "suggest.json");
110
+ const raw = ctx.config.model;
111
+ if (raw !== undefined && typeof raw !== "string")
112
+ ctx.service("ui@1")?.notify(`jade/suggest: model must be a model name, got ${JSON.stringify(raw)}; using the session's model`, "warning");
113
+ settings = {
114
+ enabled: ctx.config.enabled === true,
115
+ model: typeof raw === "string" && raw.trim() ? raw.trim() : undefined,
116
+ ...await readState(file)
117
+ };
118
+ const models = ctx.require("models@1");
119
+ const describe = () => `suggestions are ${settings.enabled ? "on" : "off"}, predicted by ${settings.model ? `the model ${settings.model}` : "the session's model"}`;
120
+ const update = async (next) => {
121
+ settings = { ...settings, ...next };
122
+ for (const fn of changed)
123
+ fn();
124
+ await writeState(file, settings);
125
+ return `${describe()}.`;
126
+ };
127
+ ctx.service("commands@1")?.register({
128
+ name: "suggest",
129
+ args: "[on|off|model [name]]",
130
+ description: "predict your next message after each turn (one more model request per turn), and which model predicts",
131
+ instant: true,
132
+ async run(args, c) {
133
+ const [sub = "", ...rest] = args.trim().split(/\s+/);
134
+ if (sub === "on" || sub === "off")
135
+ return update({ enabled: sub === "on" });
136
+ if (sub === "model") {
137
+ const [saved, listed] = await Promise.all([models.saved?.() ?? [], models.list().catch(() => [])]);
138
+ const names = [...new Set([...saved, ...listed])];
139
+ let name = rest.join(" ");
140
+ if (!name) {
141
+ const SESSION = "\x00session";
142
+ const picked = await c.ui.select({
143
+ title: "Which model predicts your next message?",
144
+ options: [
145
+ { label: "The session's model", value: SESSION },
146
+ ...names.map((m) => ({ label: m, value: m, ...m === settings.model ? { hint: "current" } : saved.includes(m) ? { hint: "saved" } : {} }))
147
+ ]
148
+ }, c.signal);
149
+ if (picked === undefined)
150
+ return;
151
+ name = picked === SESSION ? undefined : picked;
152
+ } else if (models.saved && !names.includes(name)) {
153
+ return `${name} is not a model saved by /model or offered by the current service. ${names.length ? `Available: ${names.join(", ")}.` : "Add one with /model first."}`;
154
+ }
155
+ return update({ model: name });
257
156
  }
258
- ctx.kernel.hook({
259
- // 每次请求模型前:记下这次发出的消息,不改它们。新的请求说明新的一轮(或下一步)开始了,之前的建议作废
260
- kind: "transform",
261
- point: "context.project",
262
- optional: true,
263
- fn: (msgs) => {
264
- messages = msgs;
265
- reply = undefined;
266
- pending?.abort();
267
- input.hint(undefined);
268
- return undefined;
269
- },
270
- });
271
- ctx.kernel.hook({
272
- kind: "observe",
273
- point: "model.after",
274
- fn: (res) => {
275
- reply = { role: "assistant", content: res.content };
276
- },
277
- });
278
- ctx.kernel.hook({
279
- // 这一轮正常结束(不是中断、出错或被截断)时预测。不 await:hook 有时限,预测在后台进行
280
- kind: "observe",
281
- point: "event",
282
- fn: (e) => {
283
- if (e.type === "turn.ended" && e.data.reason === "end")
284
- void predict();
285
- },
157
+ if (sub)
158
+ return "usage: /suggest [on|off|model [name]]";
159
+ return `${describe()}. /suggest on|off turns them on or off; /suggest model picks the model.`;
160
+ }
161
+ });
162
+ },
163
+ session(ctx) {
164
+ const input = ctx.input;
165
+ if (!input)
166
+ return;
167
+ const models = ctx.require("models@1");
168
+ let messages = [];
169
+ let reply;
170
+ let pending;
171
+ ctx.signal.addEventListener("abort", () => pending?.abort());
172
+ const onChange = () => {
173
+ if (settings.enabled)
174
+ return;
175
+ pending?.abort();
176
+ input.hint(undefined);
177
+ };
178
+ changed.add(onChange);
179
+ ctx.signal.addEventListener("abort", () => changed.delete(onChange));
180
+ let warned;
181
+ const warn = (e) => {
182
+ const message = e instanceof Error ? e.message : String(e);
183
+ if (message === warned)
184
+ return;
185
+ warned = message;
186
+ ctx.service("ui@1")?.notify(`jade/suggest: prediction failed (${settings.model ? `model ${settings.model}` : "the session's model"}): ${message}`, "warning");
187
+ };
188
+ async function predict() {
189
+ if (!settings.enabled)
190
+ return;
191
+ const { model } = settings;
192
+ const transcript = transcriptOf([...messages, ...reply ? [reply] : []]);
193
+ if (!transcript.some((e) => e.role === "user") || transcript.at(-1)?.role !== "assistant")
194
+ return;
195
+ pending?.abort();
196
+ const mine = pending = new AbortController;
197
+ const firstLine = new AbortController;
198
+ let streamed = "";
199
+ const onDelta = (d) => {
200
+ if (d.kind === "reset")
201
+ streamed = "";
202
+ else if (d.kind === "text")
203
+ streamed += d.text;
204
+ if (/\S[^\n]*\n/.test(streamed))
205
+ firstLine.abort();
206
+ };
207
+ const origin = { by: "plugin", id: ctx.plugin };
208
+ const request = {
209
+ system: [{ text: SYSTEM, stability: "stable", origin, trust: "trusted" }],
210
+ messages: [{ role: "user", content: [{ kind: "text", text: frame(transcript), origin, trust: "trusted" }] }],
211
+ tools: []
212
+ };
213
+ let text;
214
+ const timeout = AbortSignal.timeout(TIMEOUT_MS);
215
+ try {
216
+ const res = await models.complete(request, {
217
+ signal: AbortSignal.any([mine.signal, firstLine.signal, timeout]),
218
+ onDelta,
219
+ ...model ? { model } : {}
286
220
  });
287
- },
221
+ text = res.content.flatMap((b) => b.kind === "text" ? [b.text] : []).join("");
222
+ } catch (e) {
223
+ if (firstLine.signal.aborted && !mine.signal.aborted)
224
+ text = streamed;
225
+ else {
226
+ if (!mine.signal.aborted && !timeout.aborted && !ctx.signal.aborted)
227
+ warn(e);
228
+ return;
229
+ }
230
+ }
231
+ warned = undefined;
232
+ const hint = tidy(text);
233
+ if (hint && !mine.signal.aborted)
234
+ input.hint(hint);
235
+ }
236
+ ctx.kernel.hook({
237
+ kind: "transform",
238
+ point: "context.project",
239
+ optional: true,
240
+ fn: (msgs) => {
241
+ messages = msgs;
242
+ reply = undefined;
243
+ pending?.abort();
244
+ input.hint(undefined);
245
+ return;
246
+ }
247
+ });
248
+ ctx.kernel.hook({
249
+ kind: "observe",
250
+ point: "model.after",
251
+ fn: (res) => {
252
+ reply = { role: "assistant", content: res.content };
253
+ }
254
+ });
255
+ ctx.kernel.hook({
256
+ kind: "observe",
257
+ point: "event",
258
+ fn: (e) => {
259
+ if (e.type === "turn.ended" && e.data.reason === "end")
260
+ predict();
261
+ }
262
+ });
263
+ }
288
264
  });