@uncarved/jade 0.3.1 → 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 (199) hide show
  1. package/dist/api.d.ts +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/host.d.ts +2 -0
  4. package/dist/host.js +39 -5
  5. package/dist/host.js.map +1 -1
  6. package/dist/remote.js +5 -0
  7. package/dist/remote.js.map +1 -1
  8. package/dist/session.d.ts +7 -0
  9. package/dist/session.js +482 -27
  10. package/dist/session.js.map +1 -1
  11. package/package.json +4 -4
  12. package/plugins/approval/index.ts +36 -14
  13. package/plugins/approval/policy.ts +15 -10
  14. package/plugins/approval/review.ts +9 -5
  15. package/plugins/checks/checks.ts +10 -7
  16. package/plugins/checks/index.ts +13 -13
  17. package/plugins/checks/plugin.json +1 -1
  18. package/plugins/checks/project.ts +37 -38
  19. package/plugins/commands/index.ts +27 -3
  20. package/plugins/compact/compact.ts +13 -5
  21. package/plugins/compact/index.ts +20 -3
  22. package/plugins/compact/style.ts +13 -14
  23. package/plugins/completions/index.ts +35 -0
  24. package/plugins/completions/plugin.json +7 -0
  25. package/plugins/copy/index.ts +46 -0
  26. package/plugins/copy/plugin.json +7 -0
  27. package/plugins/editor/index.ts +10 -4
  28. package/plugins/fs/diff.ts +7 -6
  29. package/plugins/fs/fs.ts +8 -4
  30. package/plugins/fs/grep.ts +42 -9
  31. package/plugins/fs/index.ts +2 -7
  32. package/plugins/fs/plugin.json +1 -1
  33. package/plugins/fs/renderers.ts +16 -15
  34. package/plugins/fs/style.ts +16 -15
  35. package/plugins/hooks/index.ts +3 -2
  36. package/plugins/keys/index.ts +5 -1
  37. package/plugins/mcp/index.ts +197 -78
  38. package/plugins/mcp/install.ts +5 -3
  39. package/plugins/mcp/mcp.ts +163 -11
  40. package/plugins/mcp/plugin.json +2 -1
  41. package/plugins/mcp/project.ts +47 -50
  42. package/plugins/memory/index.ts +4 -4
  43. package/plugins/memory/style.ts +13 -14
  44. package/plugins/mentions/candidates.ts +67 -0
  45. package/plugins/mentions/index.ts +12 -5
  46. package/plugins/mentions/plugin.json +1 -1
  47. package/plugins/mentions/style.ts +13 -14
  48. package/plugins/models/configure.ts +10 -9
  49. package/plugins/models/index.ts +27 -1
  50. package/plugins/modes/index.ts +13 -2
  51. package/plugins/print/index.ts +7 -4
  52. package/plugins/prompts/index.ts +0 -0
  53. package/plugins/renderers/index.ts +10 -5
  54. package/plugins/repeats/index.ts +8 -8
  55. package/plugins/schedule/index.ts +2 -0
  56. package/plugins/screenshot/browser.ts +10 -0
  57. package/plugins/sessions/index.ts +48 -2
  58. package/plugins/shell/index.ts +20 -25
  59. package/plugins/shell/plugin.json +1 -2
  60. package/plugins/shell/renderers.ts +9 -7
  61. package/plugins/shell/shell.ts +3 -1
  62. package/plugins/skills/index.ts +28 -19
  63. package/plugins/skills/project.ts +12 -7
  64. package/plugins/steer/index.ts +5 -4
  65. package/plugins/task/index.ts +80 -50
  66. package/plugins/task/plugin.json +6 -2
  67. package/plugins/task/style.ts +13 -14
  68. package/plugins/task/subagent.ts +67 -184
  69. package/plugins/todo/index.ts +39 -9
  70. package/plugins/tools/index.ts +9 -2
  71. package/plugins/tui/frontend.ts +139 -89
  72. package/plugins/tui/index.ts +2 -3
  73. package/plugins/tui/mentions.ts +11 -80
  74. package/plugins/tui/plugin.json +1 -1
  75. package/plugins/tui/screen.ts +55 -5
  76. package/plugins/tui/transcript.ts +17 -7
  77. package/plugins/tui/tui.ts +337 -101
  78. package/plugins/tui/vendor.ts +1 -1
  79. package/plugins/undo/checkpoint.ts +5 -3
  80. package/plugins/undo/index.ts +43 -14
  81. package/plugins/undo/style.ts +13 -14
  82. package/plugins/web/index.ts +7 -18
  83. package/plugins/web/plugin.json +1 -1
  84. package/plugins-dist/approval/index.js +363 -418
  85. package/plugins-dist/approval/policy.js +391 -508
  86. package/plugins-dist/approval/review.js +132 -158
  87. package/plugins-dist/approval/schema.js +50 -55
  88. package/plugins-dist/ask/index.js +115 -129
  89. package/plugins-dist/budget/index.js +27 -31
  90. package/plugins-dist/checks/checks.js +293 -329
  91. package/plugins-dist/checks/index.js +119 -139
  92. package/plugins-dist/checks/plugin.json +2 -1
  93. package/plugins-dist/checks/project.js +57 -65
  94. package/plugins-dist/commands/index.js +47 -29
  95. package/plugins-dist/compact/compact.js +233 -249
  96. package/plugins-dist/compact/index.js +98 -95
  97. package/plugins-dist/compact/style.js +9 -14
  98. package/plugins-dist/completions/index.js +30 -0
  99. package/plugins-dist/completions/plugin.json +9 -0
  100. package/plugins-dist/continue/index.js +40 -52
  101. package/plugins-dist/copy/index.js +40 -0
  102. package/plugins-dist/copy/plugin.json +9 -0
  103. package/plugins-dist/cost/index.js +98 -115
  104. package/plugins-dist/custom-commands/index.js +55 -72
  105. package/plugins-dist/editor/index.js +64 -72
  106. package/plugins-dist/fs/diff.js +111 -124
  107. package/plugins-dist/fs/fs.js +426 -469
  108. package/plugins-dist/fs/grep.js +262 -253
  109. package/plugins-dist/fs/index.js +20 -34
  110. package/plugins-dist/fs/plugin.json +1 -2
  111. package/plugins-dist/fs/renderers.js +100 -112
  112. package/plugins-dist/fs/style.js +11 -15
  113. package/plugins-dist/fs/sys.js +31 -43
  114. package/plugins-dist/hooks/index.js +107 -127
  115. package/plugins-dist/keys/index.js +27 -31
  116. package/plugins-dist/mcp/index.js +271 -199
  117. package/plugins-dist/mcp/install.js +123 -137
  118. package/plugins-dist/mcp/mcp.js +638 -577
  119. package/plugins-dist/mcp/plugin.json +3 -1
  120. package/plugins-dist/mcp/project.js +98 -115
  121. package/plugins-dist/memory/index.js +83 -88
  122. package/plugins-dist/memory/memory.js +111 -128
  123. package/plugins-dist/memory/style.js +9 -14
  124. package/plugins-dist/mentions/attach.js +91 -99
  125. package/plugins-dist/mentions/candidates.js +49 -0
  126. package/plugins-dist/mentions/index.js +71 -81
  127. package/plugins-dist/mentions/plugin.json +2 -1
  128. package/plugins-dist/mentions/style.js +9 -14
  129. package/plugins-dist/models/config.js +29 -43
  130. package/plugins-dist/models/configure.js +392 -473
  131. package/plugins-dist/models/context.js +14 -22
  132. package/plugins-dist/models/index.js +182 -189
  133. package/plugins-dist/models/provider.js +243 -307
  134. package/plugins-dist/models/saved.js +59 -71
  135. package/plugins-dist/modes/index.js +138 -165
  136. package/plugins-dist/plugins/index.js +34 -34
  137. package/plugins-dist/print/index.js +192 -175
  138. package/plugins-dist/prompts/index.js +81 -89
  139. package/plugins-dist/prompts/notes.js +31 -37
  140. package/plugins-dist/prompts/prompts.js +155 -193
  141. package/plugins-dist/prompts/results.js +40 -53
  142. package/plugins-dist/prompts/sys.js +39 -50
  143. package/plugins-dist/renderers/index.js +32 -32
  144. package/plugins-dist/repeats/index.js +131 -174
  145. package/plugins-dist/schedule/cron.js +49 -56
  146. package/plugins-dist/schedule/index.js +229 -247
  147. package/plugins-dist/schedule/store.js +93 -109
  148. package/plugins-dist/scratch/index.js +12 -18
  149. package/plugins-dist/screenshot/browser.js +136 -154
  150. package/plugins-dist/screenshot/index.js +37 -46
  151. package/plugins-dist/screenshot/sys.js +53 -65
  152. package/plugins-dist/screenshot/tool.js +98 -126
  153. package/plugins-dist/sessions/index.js +149 -117
  154. package/plugins-dist/shell/index.js +115 -135
  155. package/plugins-dist/shell/plugin.json +1 -2
  156. package/plugins-dist/shell/renderers.js +28 -33
  157. package/plugins-dist/shell/service.js +17 -23
  158. package/plugins-dist/shell/shell.js +307 -362
  159. package/plugins-dist/shell/sys.js +64 -79
  160. package/plugins-dist/skills/index.js +193 -211
  161. package/plugins-dist/skills/install.js +122 -149
  162. package/plugins-dist/skills/project.js +65 -73
  163. package/plugins-dist/skills/skills.js +135 -171
  164. package/plugins-dist/steer/index.js +108 -125
  165. package/plugins-dist/suggest/index.js +235 -259
  166. package/plugins-dist/task/index.js +130 -117
  167. package/plugins-dist/task/plugin.json +5 -2
  168. package/plugins-dist/task/style.js +9 -14
  169. package/plugins-dist/task/subagent.js +156 -279
  170. package/plugins-dist/todo/index.js +79 -63
  171. package/plugins-dist/tools/index.js +36 -42
  172. package/plugins-dist/tui/editor.js +145 -160
  173. package/plugins-dist/tui/frontend.js +639 -678
  174. package/plugins-dist/tui/history.js +34 -37
  175. package/plugins-dist/tui/index.js +16 -18
  176. package/plugins-dist/tui/markdown.js +203 -247
  177. package/plugins-dist/tui/mascot.js +266 -355
  178. package/plugins-dist/tui/mentions.js +67 -144
  179. package/plugins-dist/tui/plugin.json +1 -2
  180. package/plugins-dist/tui/render.js +35 -45
  181. package/plugins-dist/tui/screen.js +197 -180
  182. package/plugins-dist/tui/transcript.js +436 -468
  183. package/plugins-dist/tui/tui.js +1554 -1656
  184. package/plugins-dist/undo/checkpoint.js +95 -118
  185. package/plugins-dist/undo/index.js +185 -192
  186. package/plugins-dist/undo/snapshot.js +83 -99
  187. package/plugins-dist/undo/style.js +9 -14
  188. package/plugins-dist/update/index.js +26 -28
  189. package/plugins-dist/web/env.js +55 -68
  190. package/plugins-dist/web/index.js +80 -110
  191. package/plugins-dist/web/plugin.json +1 -2
  192. package/plugins-dist/web/renderers.js +4 -5
  193. package/plugins-dist/web/web.js +514 -593
  194. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  195. package/sdk/python/jade_plugin.py +9 -2
  196. package/src/api.ts +1 -1
  197. package/src/host.ts +39 -4
  198. package/src/remote.ts +6 -1
  199. package/src/session.ts +489 -34
@@ -1,5 +1,4 @@
1
- // jade/print:jade -p "<prompt>" 跑一轮就退出。模型的回复写到 stdout,工具调用和提示写到 stderr。
2
- // 不能向用户提问:ui@1 的 select 总是返回 undefined,要审批的调用由审批插件拒绝。
1
+ import { stripVTControlCharacters } from "node:util";
3
2
  import { definePlugin } from "@uncarved/jade-api";
4
3
  const USAGE = `usage: jade -p <prompt> [--resume <session id> | --continue] [--json]
5
4
  echo <prompt> | jade -p
@@ -13,194 +12,212 @@ Runs one prompt and exits. The reply goes to stdout; tool calls and notices go t
13
12
  {"session", "result" (the final reply), "reason" (why the turn ended), "error"?, "usage"}
14
13
  Exit code: 0 when the turn ends normally, 1 on an error, 130 when interrupted.
15
14
  jade's own commands (plugins, update, --safe): jade help`;
16
- const ui = {
17
- interactive: false,
18
- notify(message, level = "info") {
19
- process.stderr.write(`${level === "info" ? "" : `[${level}] `}${message}\n`);
20
- },
21
- select: async () => undefined,
22
- input: async () => undefined,
15
+ export const ui = {
16
+ interactive: false,
17
+ notify(message, level = "info") {
18
+ process.stderr.write(`${level === "info" ? "" : `[${level}] `}${stripVTControlCharacters(String(message))}
19
+ `);
20
+ },
21
+ select: async () => {
22
+ return;
23
+ },
24
+ input: async () => {
25
+ return;
26
+ }
23
27
  };
24
- /** --continue 用:process() 里记下的工作目录和会话索引(jade/sessions 的 sessions@1,用到的时候取) */
25
28
  let here;
26
29
  const frontend = {
27
- async run({ argv, sessions }) {
28
- const args = parse(argv);
29
- if (typeof args === "string") {
30
- process.stderr.write(`${args}\n\n${USAGE}\n`);
31
- return 2;
32
- }
33
- if (args.help) {
34
- process.stdout.write(`${USAGE}\n`);
35
- return 0;
36
- }
37
- // 有 prompt 参数时只在写了 "-" 时读 stdin:脚本启动 jade -p 时 stdin 常是没人关的管道,默认去读会一直等下去
38
- const piped = args.stdin || (args.prompt === undefined && !process.stdin.isTTY) ? (await readStdin()).trim() : "";
39
- const prompt = [args.prompt, piped].filter(Boolean).join("\n\n");
40
- if (!prompt) {
41
- process.stderr.write(`no prompt given\n\n${USAGE}\n`);
42
- return 2;
43
- }
44
- if (args.cont) {
45
- const latest = (await here?.index()?.list(here.cwd))?.[0]?.id;
46
- if (!latest) {
47
- process.stderr.write("jade: there is no earlier session in this directory to continue\n");
48
- return 2;
49
- }
50
- args.resume = latest;
51
- }
52
- let session;
53
- try {
54
- session = await sessions.open(args.resume ? { resume: args.resume } : {});
55
- }
56
- catch (e) {
57
- // 例如 --resume 的会话不存在:只说原因,不带插件名的包装
58
- process.stderr.write(`jade: ${args.resume ? `could not resume ${args.resume}` : "could not start a session"}: ${errorText(e)}\n`);
59
- return args.resume ? 2 : 1;
60
- }
61
- let ended;
62
- let midLine = false;
63
- /** --json:回复不边写边打印,最后一次回复的正文和用量合计在结束时一起输出 */
64
- let result = "";
65
- const used = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
66
- const out = (text) => {
67
- if (args.json)
68
- return;
69
- process.stdout.write(text);
70
- midLine = !text.endsWith("\n");
71
- };
72
- /** 这次模型调用推送过文字增量;没推送的(不流式的服务),回复到了再一次写出 */
73
- let streamed = false;
74
- const unsubscribe = session.subscribe((n) => {
75
- if (n.type === "delta" && n.delta.kind === "text") {
76
- streamed = true;
77
- out(n.delta.text);
78
- }
79
- if (n.type !== "event")
80
- return;
81
- const e = n.event;
82
- if (e.type === "model.responded") {
83
- const { content, usage } = e.data;
84
- const text = content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n");
85
- if (text)
86
- result = text;
87
- for (const k of Object.keys(used))
88
- used[k] += usage?.[k] ?? 0;
89
- if (!streamed)
90
- for (const b of content)
91
- if (b.kind === "text")
92
- out(b.text);
93
- streamed = false;
94
- if (midLine)
95
- out("\n");
96
- for (const b of content)
97
- if (b.kind === "tool_use")
98
- process.stderr.write(`· ${b.name} ${summary(b.input)}\n`);
99
- }
100
- if (e.type === "tool.decided") {
101
- const d = e.data;
102
- if (d.decision === "deny")
103
- process.stderr.write(` denied${d.reason ? `: ${d.reason}` : ""}\n`);
104
- }
105
- if (e.type === "tool.completed") {
106
- const d = e.data;
107
- if (d.isError)
108
- process.stderr.write(` failed: ${firstLine(d.content)}\n`);
109
- }
110
- if (e.type === "turn.ended")
111
- ended = e.data;
112
- });
113
- const interrupt = () => session.abort(new Error("interrupted"));
114
- process.once("SIGINT", interrupt);
115
- let failure;
116
- try {
117
- if (args.resume)
118
- await session.recover();
119
- await session.send({ kind: "message", content: [{ kind: "text", text: prompt, origin: { by: "user" }, trust: "trusted" }] });
120
- await session.idle();
121
- }
122
- catch (e) {
123
- failure = e;
124
- }
125
- finally {
126
- process.off("SIGINT", interrupt);
127
- unsubscribe();
30
+ async run({ argv, sessions }) {
31
+ const args = parse(argv);
32
+ if (typeof args === "string") {
33
+ process.stderr.write(`${args}
34
+
35
+ ${USAGE}
36
+ `);
37
+ return 2;
38
+ }
39
+ if (args.help) {
40
+ process.stdout.write(`${USAGE}
41
+ `);
42
+ return 0;
43
+ }
44
+ const piped = args.stdin || args.prompt === undefined && !process.stdin.isTTY ? (await readStdin()).trim() : "";
45
+ const prompt = [args.prompt, piped].filter(Boolean).join(`
46
+
47
+ `);
48
+ if (!prompt) {
49
+ process.stderr.write(`no prompt given
50
+
51
+ ${USAGE}
52
+ `);
53
+ return 2;
54
+ }
55
+ if (args.cont) {
56
+ const latest = (await here?.index()?.list(here.cwd))?.[0]?.id;
57
+ if (!latest) {
58
+ process.stderr.write(`jade: there is no earlier session in this directory to continue
59
+ `);
60
+ return 2;
61
+ }
62
+ args.resume = latest;
63
+ }
64
+ let session;
65
+ try {
66
+ session = await sessions.open(args.resume ? { resume: args.resume } : {});
67
+ } catch (e) {
68
+ process.stderr.write(`jade: ${args.resume ? `could not resume ${args.resume}` : "could not start a session"}: ${errorText(e)}
69
+ `);
70
+ return args.resume ? 2 : 1;
71
+ }
72
+ let ended;
73
+ let midLine = false;
74
+ let result = "";
75
+ const used = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
76
+ const out = (text) => {
77
+ if (args.json)
78
+ return;
79
+ process.stdout.write(text);
80
+ midLine = !text.endsWith(`
81
+ `);
82
+ };
83
+ let streamed = false;
84
+ const unsubscribe = session.subscribe((n) => {
85
+ if (n.type === "delta" && n.delta.kind === "text") {
86
+ streamed = true;
87
+ out(n.delta.text);
88
+ }
89
+ if (n.type !== "event")
90
+ return;
91
+ const e = n.event;
92
+ if (e.type === "model.responded") {
93
+ const { content, usage } = e.data;
94
+ const text = content.flatMap((b) => b.kind === "text" ? [b.text] : []).join(`
95
+ `);
96
+ if (text)
97
+ result = text;
98
+ for (const k of Object.keys(used))
99
+ used[k] += usage?.[k] ?? 0;
100
+ if (!streamed) {
101
+ for (const b of content)
102
+ if (b.kind === "text")
103
+ out(b.text);
128
104
  }
105
+ streamed = false;
129
106
  if (midLine)
130
- out("\n");
131
- process.stderr.write(`session ${session.id}\n`);
132
- const end = ended;
133
- if (args.json) {
134
- const error = failure !== undefined ? errorText(failure) : end?.error;
135
- process.stdout.write(`${JSON.stringify({ session: session.id, result, reason: end?.reason ?? "error", ...(error ? { error } : {}), usage: used })}\n`);
136
- }
137
- if (end?.reason === "aborted")
138
- return 130;
139
- if (failure !== undefined || end?.reason === "error") {
140
- process.stderr.write(`error: ${failure !== undefined ? errorText(failure) : (end?.error ?? "the turn failed")}\n`);
141
- return 1;
142
- }
143
- return 0;
144
- },
107
+ out(`
108
+ `);
109
+ for (const b of content)
110
+ if (b.kind === "tool_use")
111
+ process.stderr.write(`· ${b.name} ${summary(b.input)}
112
+ `);
113
+ }
114
+ if (e.type === "tool.decided") {
115
+ const d = e.data;
116
+ if (d.decision === "deny")
117
+ process.stderr.write(` denied${d.reason ? `: ${stripVTControlCharacters(d.reason)}` : ""}
118
+ `);
119
+ }
120
+ if (e.type === "tool.completed") {
121
+ const d = e.data;
122
+ if (d.isError)
123
+ process.stderr.write(` failed: ${stripVTControlCharacters(firstLine(d.content))}
124
+ `);
125
+ }
126
+ if (e.type === "turn.ended")
127
+ ended = e.data;
128
+ });
129
+ const interrupt = () => session.abort(new Error("interrupted"));
130
+ process.once("SIGINT", interrupt);
131
+ let failure;
132
+ try {
133
+ if (args.resume)
134
+ await session.recover();
135
+ await session.send({ kind: "message", content: [{ kind: "text", text: prompt, origin: { by: "user" }, trust: "trusted" }] });
136
+ await session.idle();
137
+ } catch (e) {
138
+ failure = e;
139
+ } finally {
140
+ process.off("SIGINT", interrupt);
141
+ unsubscribe();
142
+ }
143
+ if (midLine)
144
+ out(`
145
+ `);
146
+ process.stderr.write(`session ${session.id}
147
+ `);
148
+ const end = ended;
149
+ if (args.json) {
150
+ const error = failure !== undefined ? errorText(failure) : end?.error;
151
+ process.stdout.write(`${JSON.stringify({ session: session.id, result, reason: end?.reason ?? "error", ...error ? { error } : {}, usage: used })}
152
+ `);
153
+ }
154
+ if (end?.reason === "aborted")
155
+ return 130;
156
+ if (failure !== undefined || end?.reason === "error") {
157
+ process.stderr.write(`error: ${failure !== undefined ? errorText(failure) : end?.error ?? "the turn failed"}
158
+ `);
159
+ return 1;
160
+ }
161
+ return 0;
162
+ }
145
163
  };
146
164
  export default definePlugin({
147
- process(ctx) {
148
- here = { cwd: ctx.cwd, index: () => ctx.service("sessions@1") };
149
- ctx.provide("ui@1", ui);
150
- ctx.provide("frontend@1", frontend);
151
- },
165
+ process(ctx) {
166
+ here = { cwd: ctx.cwd, index: () => ctx.service("sessions@1") };
167
+ ctx.provide("ui@1", ui);
168
+ ctx.provide("frontend@1", frontend);
169
+ }
152
170
  });
153
171
  function parse(argv) {
154
- const out = {};
155
- const words = [];
156
- for (let i = 0; i < argv.length; i++) {
157
- const a = argv[i];
158
- if (a === "-p" || a === "--print")
159
- continue;
160
- if (a === "-h" || a === "--help")
161
- out.help = true;
162
- else if (a === "-")
163
- out.stdin = true;
164
- else if (a === "-c" || a === "--continue")
165
- out.cont = true;
166
- else if (a === "--json")
167
- out.json = true;
168
- else if (a === "--resume") {
169
- const id = argv[++i];
170
- if (!id)
171
- return "--resume needs a session id";
172
- out.resume = id;
173
- }
174
- else if (a.startsWith("-"))
175
- return `unknown option ${a}`;
176
- else
177
- words.push(a);
178
- }
179
- if (out.cont && out.resume)
180
- return "--continue and --resume both pick the session; use one of them";
181
- if (words.length > 0)
182
- out.prompt = words.join(" ");
183
- return out;
172
+ const out = {};
173
+ const words = [];
174
+ for (let i = 0;i < argv.length; i++) {
175
+ const a = argv[i];
176
+ if (a === "-p" || a === "--print")
177
+ continue;
178
+ if (a === "-h" || a === "--help")
179
+ out.help = true;
180
+ else if (a === "-")
181
+ out.stdin = true;
182
+ else if (a === "-c" || a === "--continue")
183
+ out.cont = true;
184
+ else if (a === "--json")
185
+ out.json = true;
186
+ else if (a === "--resume") {
187
+ const id = argv[++i];
188
+ if (!id)
189
+ return "--resume needs a session id";
190
+ out.resume = id;
191
+ } else if (a.startsWith("-"))
192
+ return `unknown option ${a}`;
193
+ else
194
+ words.push(a);
195
+ }
196
+ if (out.cont && out.resume)
197
+ return "--continue and --resume both pick the session; use one of them";
198
+ if (words.length > 0)
199
+ out.prompt = words.join(" ");
200
+ return out;
184
201
  }
185
202
  async function readStdin() {
186
- const chunks = [];
187
- for await (const c of process.stdin)
188
- chunks.push(c);
189
- return Buffer.concat(chunks).toString("utf8");
203
+ const chunks = [];
204
+ for await (const c of process.stdin)
205
+ chunks.push(c);
206
+ return Buffer.concat(chunks).toString("utf8");
190
207
  }
191
- /** 工具参数的一行摘要:常见的 path、command、pattern,其余是截断的 JSON */
192
208
  function summary(input) {
193
- const i = input;
194
- const s = typeof i?.command === "string" ? i.command : typeof i?.path === "string" ? i.path : typeof i?.pattern === "string" ? i.pattern : JSON.stringify(input);
195
- const line = (s ?? "").split("\n")[0];
196
- return line.length > 120 ? `${line.slice(0, 120)}…` : line;
209
+ const i = input;
210
+ const s = typeof i?.command === "string" ? i.command : typeof i?.path === "string" ? i.path : typeof i?.pattern === "string" ? i.pattern : JSON.stringify(input);
211
+ const line = (s ?? "").split(`
212
+ `)[0];
213
+ return line.length > 120 ? `${line.slice(0, 120)}…` : line;
197
214
  }
198
- /** 经过膜的错误包成了 PluginError,带着插件名;用户要看的是原因 */
199
215
  function errorText(e) {
200
- const cause = e instanceof Error && e.cause instanceof Error ? e.cause : e;
201
- return cause instanceof Error ? cause.message : String(cause);
216
+ const cause = e instanceof Error && e.cause instanceof Error ? e.cause : e;
217
+ return cause instanceof Error ? cause.message : String(cause);
202
218
  }
203
219
  function firstLine(content) {
204
- const text = content.find((b) => b.kind === "text");
205
- return text && "text" in text ? text.text.split("\n")[0] : "(no message)";
220
+ const text = content.find((b) => b.kind === "text");
221
+ return text && "text" in text ? text.text.split(`
222
+ `)[0] : "(no message)";
206
223
  }
@@ -1,6 +1,3 @@
1
- // jade/prompts:在 context.build 里生成系统提示词。其他插件经 prompts@1 往里加段落。
2
- // 也负责内核不写的、给模型看的说明:内容为空的错误工具结果在投影里补一句原因(results.ts);
3
- // 其他插件经 prompts@1 的 note 给模型留一句说明(notes.ts)。
4
1
  import os from "node:os";
5
2
  import path from "node:path";
6
3
  import { definePlugin } from "@uncarved/jade-api";
@@ -8,97 +5,92 @@ import { Notes } from "./notes.js";
8
5
  import { allInstructions, environment, mainPrompt, realPath } from "./prompts.js";
9
6
  import { explainEmptyResults, whyEmpty } from "./results.js";
10
7
  const ID = "jade/prompts";
11
- /** 其他插件加的段落。模块每个进程只加载一次,进程级和会话级共用 */
12
8
  const sections = [];
13
- /** 打开着的会话 → 它读到的指令文件(prompts@1.instructions) */
14
- const loaded = new Map();
15
- /** 其他插件留给模型的说明 */
16
- const notes = new Notes();
9
+ const loaded = new Map;
10
+ const notes = new Notes;
17
11
  function segment(text, trust = "trusted", stability = "stable", by = ID, source) {
18
- return { text, stability, origin: { by: "plugin", id: by, ...(source ? { source } : {}) }, trust };
12
+ return { text, stability, origin: { by: "plugin", id: by, ...source ? { source } : {} }, trust };
19
13
  }
20
- /** 工作目录里的显示成相对路径,外面的显示绝对路径 */
21
14
  function display(cwd, full) {
22
- const rel = path.relative(cwd, full);
23
- const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
24
- return shown.split(path.sep).join("/");
15
+ const rel = path.relative(cwd, full);
16
+ const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
17
+ return shown.split(path.sep).join("/");
25
18
  }
26
19
  export default definePlugin({
27
- process(ctx) {
28
- ctx.provide("prompts@1", (caller) => ({
29
- add({ text, stable = true, untrusted = false }) {
30
- if (typeof text !== "string" || !text)
31
- throw new Error("prompts.add: text must be a non-empty string");
32
- const s = { plugin: caller.plugin, text, stable, trusted: caller.layer !== "project" && untrusted !== true };
33
- sections.push(s);
34
- const remove = () => {
35
- const i = sections.indexOf(s);
36
- if (i !== -1)
37
- sections.splice(i, 1);
38
- };
39
- caller.onDispose(remove);
40
- return remove;
41
- },
42
- note(session, text) {
43
- if (typeof session !== "string" || !session)
44
- throw new Error("prompts.note: session must be a session id");
45
- if (typeof text !== "string" || !text)
46
- throw new Error("prompts.note: text must be a non-empty string");
47
- notes.add(session, { plugin: caller.plugin, text, trusted: caller.layer !== "project" });
48
- },
49
- instructions: (session) => (loaded.get(session) ?? []).map((i) => ({ ...i, source: { ...i.source } })),
50
- }));
51
- },
52
- async session(ctx) {
53
- const models = ctx.service("models@1");
54
- const [env, instructions] = await Promise.all([environment(ctx.cwd), allInstructions(ctx.home, ctx.cwd, ctx.config.claudeInstructions === false ? null : os.homedir())]);
55
- loaded.set(ctx.session.id, instructions.map(({ text, trust, source }) => ({ text, trust, source })));
56
- await ctx.effect(() => () => void loaded.delete(ctx.session.id));
57
- const fixed = [segment(env), ...instructions.map((i) => segment(i.text, i.trust, "stable", ID, i.source))];
58
- // 告诉用户读了哪些指令文件,否则看不出它们生效了
59
- if (instructions.length > 0)
60
- ctx.service("ui@1")?.notify(`loaded instructions: ${instructions.map((i) => display(realPath(ctx.cwd), i.file)).join(", ")}`);
61
- // 内容为空的错误工具结果补上说明(results.ts)。原因记在 derived 里;同一批里可能有几个,
62
- // observe 并发执行、拿到的 derived 快照可能是旧的,所以在这里累积,每次记完整的一份。
63
- // 运行时不等 observe:紧接着的模型调用投影时记录可能还没落盘,所以投影也看这份累积的。
64
- // observe 在事件写入时就(以微任务)开始执行,早于之后的投影;下一轮之前记录一定已落盘,恢复会话时从 derived 读,
65
- // 所以投影只取决于日志,每次相同
66
- const reasonsKey = `${ID}/empty-results`;
67
- let reasons;
68
- ctx.kernel.hook({
69
- kind: "observe",
70
- point: "event",
71
- fn: async (e, hook) => {
72
- const found = whyEmpty(e);
73
- if (!found)
74
- return;
75
- reasons ??= { ...(hook.derived[reasonsKey] ?? {}) };
76
- reasons[found.toolUseId] = found.why;
77
- await hook.record(reasonsKey, { ...reasons });
78
- },
20
+ process(ctx) {
21
+ ctx.provide("prompts@1", (caller) => ({
22
+ add({ text, stable = true, untrusted = false }) {
23
+ if (typeof text !== "string" || !text)
24
+ throw new Error("prompts.add: text must be a non-empty string");
25
+ const s = { plugin: caller.plugin, text, stable, trusted: caller.layer !== "project" && untrusted !== true };
26
+ sections.push(s);
27
+ const remove = () => {
28
+ const i = sections.indexOf(s);
29
+ if (i !== -1)
30
+ sections.splice(i, 1);
31
+ };
32
+ caller.onDispose(remove);
33
+ return remove;
34
+ },
35
+ note(session, text) {
36
+ if (typeof session !== "string" || !session)
37
+ throw new Error("prompts.note: session must be a session id");
38
+ if (typeof text !== "string" || !text)
39
+ throw new Error("prompts.note: text must be a non-empty string");
40
+ notes.add(session, { plugin: caller.plugin, text, trusted: caller.layer !== "project" });
41
+ },
42
+ instructions: (session) => (loaded.get(session) ?? []).map((i) => ({ ...i, source: { ...i.source } }))
43
+ }));
44
+ },
45
+ async session(ctx) {
46
+ const models = ctx.service("models@1");
47
+ const [env, instructions] = await Promise.all([environment(ctx.cwd), allInstructions(ctx.home, ctx.cwd, ctx.config.claudeInstructions === false ? null : os.homedir())]);
48
+ loaded.set(ctx.session.id, instructions.map(({ text, trust, source }) => ({ text, trust, source })));
49
+ await ctx.effect(() => () => void loaded.delete(ctx.session.id));
50
+ const fixed = [segment(env), ...instructions.map((i) => segment(i.text, i.trust, "stable", ID, i.source))];
51
+ const child = ctx.session.parent !== undefined;
52
+ if (instructions.length > 0 && !child)
53
+ ctx.service("ui@1")?.notify(`loaded instructions: ${instructions.map((i) => display(realPath(ctx.cwd), i.file)).join(", ")}`);
54
+ const reasonsKey = `${ID}/empty-results`;
55
+ let reasons;
56
+ ctx.kernel.hook({
57
+ kind: "observe",
58
+ point: "event",
59
+ fn: async (e, hook) => {
60
+ const found = whyEmpty(e);
61
+ if (!found)
62
+ return;
63
+ reasons ??= { ...hook.derived[reasonsKey] ?? {} };
64
+ reasons[found.toolUseId] = found.why;
65
+ await hook.record(reasonsKey, { ...reasons });
66
+ }
67
+ });
68
+ ctx.kernel.hook({
69
+ kind: "transform",
70
+ point: "context.project",
71
+ optional: true,
72
+ fn: (messages, hook) => explainEmptyResults(messages, { ...hook.derived[reasonsKey], ...reasons }, ID)
73
+ });
74
+ ctx.kernel.hook(notes.hook(ctx.session.id, `${ID}/notes`));
75
+ await ctx.effect(() => () => notes.drop(ctx.session.id));
76
+ ctx.kernel.hook({
77
+ kind: "transform",
78
+ point: "context.build",
79
+ fn: (req) => {
80
+ const main = child ? [] : [segment(mainPrompt(new Set(req.tools.map((t) => t.name))))];
81
+ const model = models?.current();
82
+ const modelLine = model?.model ? [segment(`Jade is configured to use the model "${model.model}" via ${model.via}. If the user asks which model you are, answer with this rather than guessing from your training.`)] : [];
83
+ const once = new Set;
84
+ const unique = sections.filter((s) => {
85
+ const key = `${s.plugin}\x00${s.trusted}\x00${s.text}`;
86
+ if (once.has(key))
87
+ return false;
88
+ once.add(key);
89
+ return true;
79
90
  });
80
- ctx.kernel.hook({
81
- kind: "transform",
82
- point: "context.project",
83
- // 出错时跳过(不补说明),不让这一轮失败
84
- optional: true,
85
- fn: (messages, hook) => explainEmptyResults(messages, { ...hook.derived[reasonsKey], ...reasons }, ID),
86
- });
87
- ctx.kernel.hook(notes.hook(ctx.session.id, `${ID}/notes`));
88
- await ctx.effect(() => () => notes.drop(ctx.session.id));
89
- ctx.kernel.hook({
90
- kind: "transform",
91
- point: "context.build",
92
- fn: (req) => {
93
- const main = segment(mainPrompt(new Set(req.tools.map((t) => t.name))));
94
- const model = models?.current();
95
- // 说成"配置的模型":服务商的别名、路由背后实际回复的可能是别的模型
96
- const modelLine = model?.model
97
- ? [segment(`Jade is configured to use the model "${model.model}" via ${model.via}. If the user asks which model you are, answer with this rather than guessing from your training.`)]
98
- : [];
99
- const extra = [...sections.filter((s) => s.stable), ...sections.filter((s) => !s.stable)].map((s) => segment(s.text, s.trusted ? "trusted" : "untrusted", s.stable ? "stable" : "volatile", s.plugin));
100
- return { ...req, system: [main, ...fixed, ...modelLine, ...extra, ...req.system] };
101
- },
102
- });
103
- },
91
+ const extra = [...unique.filter((s) => s.stable), ...unique.filter((s) => !s.stable)].map((s) => segment(s.text, s.trusted ? "trusted" : "untrusted", s.stable ? "stable" : "volatile", s.plugin));
92
+ return { ...req, system: [...main, ...fixed, ...modelLine, ...extra, ...req.system] };
93
+ }
94
+ });
95
+ }
104
96
  });