@uncarved/jade 0.0.0-stage → 0.1.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 (164) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +187 -2
  3. package/bin/jade.js +20 -0
  4. package/dist/commands.d.ts +30 -0
  5. package/dist/commands.js +106 -0
  6. package/dist/commands.js.map +1 -0
  7. package/dist/config.d.ts +34 -0
  8. package/dist/config.js +130 -0
  9. package/dist/config.js.map +1 -0
  10. package/dist/context.d.ts +17 -0
  11. package/dist/context.js +53 -0
  12. package/dist/context.js.map +1 -0
  13. package/dist/distro.d.ts +93 -0
  14. package/dist/distro.js +277 -0
  15. package/dist/distro.js.map +1 -0
  16. package/dist/history.d.ts +10 -0
  17. package/dist/history.js +47 -0
  18. package/dist/history.js.map +1 -0
  19. package/dist/index.d.ts +26 -0
  20. package/dist/index.js +27 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/main.d.ts +2 -0
  23. package/dist/main.js +1124 -0
  24. package/dist/main.js.map +1 -0
  25. package/dist/mcp.d.ts +114 -0
  26. package/dist/mcp.js +640 -0
  27. package/dist/mcp.js.map +1 -0
  28. package/dist/memory.d.ts +19 -0
  29. package/dist/memory.js +129 -0
  30. package/dist/memory.js.map +1 -0
  31. package/dist/mentions.d.ts +35 -0
  32. package/dist/mentions.js +130 -0
  33. package/dist/mentions.js.map +1 -0
  34. package/dist/plugin-cli.d.ts +16 -0
  35. package/dist/plugin-cli.js +251 -0
  36. package/dist/plugin-cli.js.map +1 -0
  37. package/dist/plugins/budget.d.ts +9 -0
  38. package/dist/plugins/budget.js +30 -0
  39. package/dist/plugins/budget.js.map +1 -0
  40. package/dist/plugins/builtins.d.ts +10 -0
  41. package/dist/plugins/builtins.js +22 -0
  42. package/dist/plugins/builtins.js.map +1 -0
  43. package/dist/plugins/checks.d.ts +70 -0
  44. package/dist/plugins/checks.js +335 -0
  45. package/dist/plugins/checks.js.map +1 -0
  46. package/dist/plugins/compact.d.ts +26 -0
  47. package/dist/plugins/compact.js +216 -0
  48. package/dist/plugins/compact.js.map +1 -0
  49. package/dist/plugins/core.d.ts +42 -0
  50. package/dist/plugins/core.js +190 -0
  51. package/dist/plugins/core.js.map +1 -0
  52. package/dist/plugins/install.d.ts +68 -0
  53. package/dist/plugins/install.js +377 -0
  54. package/dist/plugins/install.js.map +1 -0
  55. package/dist/plugins/loader.d.ts +182 -0
  56. package/dist/plugins/loader.js +253 -0
  57. package/dist/plugins/loader.js.map +1 -0
  58. package/dist/plugins/policy.d.ts +64 -0
  59. package/dist/plugins/policy.js +269 -0
  60. package/dist/plugins/policy.js.map +1 -0
  61. package/dist/plugins/prompts.d.ts +28 -0
  62. package/dist/plugins/prompts.js +169 -0
  63. package/dist/plugins/prompts.js.map +1 -0
  64. package/dist/plugins/repeats.d.ts +9 -0
  65. package/dist/plugins/repeats.js +55 -0
  66. package/dist/plugins/repeats.js.map +1 -0
  67. package/dist/plugins/schema.d.ts +2 -0
  68. package/dist/plugins/schema.js +64 -0
  69. package/dist/plugins/schema.js.map +1 -0
  70. package/dist/provider.d.ts +52 -0
  71. package/dist/provider.js +187 -0
  72. package/dist/provider.js.map +1 -0
  73. package/dist/sessions.d.ts +13 -0
  74. package/dist/sessions.js +40 -0
  75. package/dist/sessions.js.map +1 -0
  76. package/dist/skills.d.ts +37 -0
  77. package/dist/skills.js +179 -0
  78. package/dist/skills.js.map +1 -0
  79. package/dist/sys.d.ts +44 -0
  80. package/dist/sys.js +115 -0
  81. package/dist/sys.js.map +1 -0
  82. package/dist/tools/checkpoint.d.ts +43 -0
  83. package/dist/tools/checkpoint.js +144 -0
  84. package/dist/tools/checkpoint.js.map +1 -0
  85. package/dist/tools/fs.d.ts +35 -0
  86. package/dist/tools/fs.js +417 -0
  87. package/dist/tools/fs.js.map +1 -0
  88. package/dist/tools/grep.d.ts +6 -0
  89. package/dist/tools/grep.js +243 -0
  90. package/dist/tools/grep.js.map +1 -0
  91. package/dist/tools/shell.d.ts +49 -0
  92. package/dist/tools/shell.js +295 -0
  93. package/dist/tools/shell.js.map +1 -0
  94. package/dist/tools/task.d.ts +31 -0
  95. package/dist/tools/task.js +86 -0
  96. package/dist/tools/task.js.map +1 -0
  97. package/dist/tools/todo.d.ts +10 -0
  98. package/dist/tools/todo.js +55 -0
  99. package/dist/tools/todo.js.map +1 -0
  100. package/dist/tools/web.d.ts +23 -0
  101. package/dist/tools/web.js +426 -0
  102. package/dist/tools/web.js.map +1 -0
  103. package/dist/ui/configure.d.ts +20 -0
  104. package/dist/ui/configure.js +285 -0
  105. package/dist/ui/configure.js.map +1 -0
  106. package/dist/ui/diff.d.ts +20 -0
  107. package/dist/ui/diff.js +142 -0
  108. package/dist/ui/diff.js.map +1 -0
  109. package/dist/ui/editor.d.ts +33 -0
  110. package/dist/ui/editor.js +128 -0
  111. package/dist/ui/editor.js.map +1 -0
  112. package/dist/ui/render.d.ts +13 -0
  113. package/dist/ui/render.js +84 -0
  114. package/dist/ui/render.js.map +1 -0
  115. package/dist/ui/screen.d.ts +90 -0
  116. package/dist/ui/screen.js +105 -0
  117. package/dist/ui/screen.js.map +1 -0
  118. package/dist/ui/transcript.d.ts +33 -0
  119. package/dist/ui/transcript.js +336 -0
  120. package/dist/ui/transcript.js.map +1 -0
  121. package/dist/ui/tui.d.ts +28 -0
  122. package/dist/ui/tui.js +884 -0
  123. package/dist/ui/tui.js.map +1 -0
  124. package/package.json +59 -4
  125. package/src/commands.ts +120 -0
  126. package/src/config.ts +146 -0
  127. package/src/context.ts +64 -0
  128. package/src/distro.ts +358 -0
  129. package/src/history.ts +55 -0
  130. package/src/index.ts +26 -0
  131. package/src/main.ts +1180 -0
  132. package/src/mcp.ts +693 -0
  133. package/src/memory.ts +135 -0
  134. package/src/mentions.ts +135 -0
  135. package/src/plugin-cli.ts +239 -0
  136. package/src/plugins/budget.ts +37 -0
  137. package/src/plugins/builtins.ts +31 -0
  138. package/src/plugins/checks.ts +390 -0
  139. package/src/plugins/compact.ts +257 -0
  140. package/src/plugins/core.ts +217 -0
  141. package/src/plugins/install.ts +429 -0
  142. package/src/plugins/loader.ts +386 -0
  143. package/src/plugins/policy.ts +304 -0
  144. package/src/plugins/prompts.ts +200 -0
  145. package/src/plugins/repeats.ts +62 -0
  146. package/src/plugins/schema.ts +67 -0
  147. package/src/provider.ts +208 -0
  148. package/src/sessions.ts +48 -0
  149. package/src/skills.ts +197 -0
  150. package/src/sys.ts +133 -0
  151. package/src/tools/checkpoint.ts +164 -0
  152. package/src/tools/fs.ts +432 -0
  153. package/src/tools/grep.ts +268 -0
  154. package/src/tools/shell.ts +339 -0
  155. package/src/tools/task.ts +105 -0
  156. package/src/tools/todo.ts +67 -0
  157. package/src/tools/web.ts +451 -0
  158. package/src/ui/configure.ts +310 -0
  159. package/src/ui/diff.ts +136 -0
  160. package/src/ui/editor.ts +136 -0
  161. package/src/ui/render.ts +74 -0
  162. package/src/ui/screen.ts +164 -0
  163. package/src/ui/transcript.ts +345 -0
  164. package/src/ui/tui.tsx +1374 -0
package/dist/main.js ADDED
@@ -0,0 +1,1124 @@
1
+ #!/usr/bin/env -S bun --no-env-file
2
+ // jade:基于 uncarved 内核的编程 Agent 命令行宿主。
3
+ //
4
+ // 宿主负责内核不管的事:配置目录、会话索引、项目层插件的确认、审批界面、渲染、中断。
5
+ // 不读当前目录的 .env(见 config.ts):模型配置放在 $JADE_HOME/.env。
6
+ // 交互运行时用终端界面(ui/tui.tsx),-p 和非交互运行时逐行输出(ui/screen.ts)。
7
+ import { readdir, stat } from "node:fs/promises";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { createHash } from "node:crypto";
11
+ import { JsonlLogStore, JsonlTrustStore } from "@uncarved/store-jsonl";
12
+ import { readAll, Runtime, UntrustedPlugin, } from "uncarved";
13
+ import { realpathSync } from "node:fs";
14
+ import { expandCommand, loadCommands } from "./commands.js";
15
+ import { discoverPlugins, inspectPlugin, loadPlugin } from "./plugins/loader.js";
16
+ import { readPluginSettings } from "./plugins/install.js";
17
+ import { PLUGIN_HELP, pluginCli, UsageError } from "./plugin-cli.js";
18
+ import { describeServer, loadMcpConfig, McpClient, mcpTrustHash } from "./mcp.js";
19
+ import { loadSkills } from "./skills.js";
20
+ import { hasProvider, loadEnvFile, parseTokens } from "./config.js";
21
+ import { createJade } from "./distro.js";
22
+ import { describeRule, MODES, POLICY_KEY } from "./plugins/policy.js";
23
+ import { compactThreshold, contextWindowFromEnv, contextWindowInfo, isContextOverflow } from "./context.js";
24
+ import { InputHistory } from "./history.js";
25
+ import { attachMentions, mentionCandidates } from "./mentions.js";
26
+ import { repoRoot } from "./plugins/prompts.js";
27
+ import { providerFromEnv, providerInfo, switchable, withRetry } from "./provider.js";
28
+ import { SessionIndex } from "./sessions.js";
29
+ import { lastTurnChanges, UNDO_KEY } from "./tools/checkpoint.js";
30
+ import { display } from "./tools/fs.js";
31
+ import { bold, dim, green, plainScreen, red, yellow } from "./ui/screen.js";
32
+ import { configurator } from "./ui/configure.js";
33
+ import { clip, preview, shortPath, summarize } from "./ui/render.js";
34
+ import { transcript } from "./ui/transcript.js";
35
+ import { run, VERSION } from "./sys.js";
36
+ const HELP = `Usage: jade [options] [prompt]
37
+ jade plugin <list|add|update|remove|enable|disable> (jade plugin --help)
38
+
39
+ -p, --print <prompt> run one prompt and exit
40
+ -c, --continue continue the most recent session in this directory
41
+ -r, --resume [id] resume a session by id, or pick one from a list
42
+ -m, --mode <mode> permission mode: ${MODES.join(" | ")} (default ask)
43
+ --cwd <dir> working directory (default: current directory)
44
+ -v, --version
45
+ -h, --help
46
+
47
+ Type / in the session for commands; /model configures the model.
48
+ Model settings are read from $JADE_HOME/.env, and data lives in $JADE_HOME (default ~/.jade).
49
+ Instructions are read from AGENTS.md (or CLAUDE.md) in $JADE_HOME and from the repository root down to the working directory.`;
50
+ /** 会话里的命令:/help、输入 / 时的菜单都从这里取 */
51
+ const COMMANDS = [
52
+ { name: "help", about: "list the commands and keys" },
53
+ { name: "model", args: "[name]", about: "switch between saved models, or add one and configure its provider, API key and output limit" },
54
+ { name: "mode", args: `[${MODES.join("|")}]`, about: "show or change the permission mode" },
55
+ { name: "clear", about: "start a new session (the current one stays resumable)" },
56
+ { name: "undo", about: "restore every file the agent changed in its last turn (run again to go further back)" },
57
+ { name: "retry", about: "request the model again after a failed request, without sending another message" },
58
+ { name: "usage", about: "token usage of this session, including sub-agents and compaction" },
59
+ { name: "resume", args: "[id]", about: "pick a recent session in this directory and switch to it" },
60
+ { name: "rules", about: `"always allow" rules of this session` },
61
+ { name: "plugins", about: "built-in and installed plugins: their tools, hooks and commands" },
62
+ { name: "hooks", about: "execution order of every extension point" },
63
+ { name: "exit", about: "quit (the session stays resumable)" },
64
+ ];
65
+ /** 运行中也立即执行的命令(不碰运行时,或者只读) */
66
+ const INSTANT = new Set(["help", "model", "usage", "rules", "hooks", "plugins", "exit", "quit"]);
67
+ /** 内置插件提供的命令(/memory 在 jade/memory 里,等等):名字保留给它们,自定义命令不能占用 */
68
+ const BUILTIN_PLUGIN_COMMANDS = ["memory", "checks", "mcp", "skills", "compact"];
69
+ const KEYS = `Keys: enter send · \\ or alt+enter new line · ↑↓ history · @ reference a file · esc interrupt · shift+tab cycle ask/auto-edit/plan · ctrl+c twice to exit
70
+ mouse wheel or PgUp/PgDn scroll the conversation · ctrl+home/ctrl+end jump to the top/bottom · shift+drag selects text
71
+ While jade is working you can keep typing: messages are queued and sent when the current turn ends.`;
72
+ /** 回复被输出上限截断后,自动让模型接着做的次数(每条用户消息) */
73
+ const MAX_CONTINUES = 3;
74
+ const CONTINUE_NOTE = "Your previous reply was cut off because it reached the output token limit. Continue from where you stopped. " +
75
+ "If you were writing a large file or edit, split it into several smaller write_file/edit_file calls.";
76
+ // ---------- 参数 ----------
77
+ const argv = process.argv.slice(2);
78
+ if (argv[0] === "plugin" || argv[0] === "plugins") {
79
+ const home = process.env.JADE_HOME ?? path.join(os.homedir(), ".jade");
80
+ const here = process.cwd();
81
+ try {
82
+ const root = realPath(await repoRoot(here));
83
+ process.exit(await pluginCli(argv.slice(1), { home, cwd: here, root, trust: new JsonlTrustStore(path.join(home, "trust.jsonl")) }));
84
+ }
85
+ catch (err) {
86
+ console.error(`jade plugin: ${err instanceof Error ? err.message : String(err)}${err instanceof UsageError ? `\n\n${PLUGIN_HELP}` : ""}`);
87
+ process.exit(err instanceof UsageError ? 2 : 1);
88
+ }
89
+ }
90
+ const opts = { prompt: [] };
91
+ for (let i = 0; i < argv.length; i++) {
92
+ const a = argv[i];
93
+ const value = () => {
94
+ const v = argv[++i];
95
+ if (v === undefined)
96
+ fail(`${a} needs a value`);
97
+ return v;
98
+ };
99
+ if (a === "-h" || a === "--help") {
100
+ console.log(HELP);
101
+ process.exit(0);
102
+ }
103
+ else if (a === "-v" || a === "--version") {
104
+ console.log(VERSION);
105
+ process.exit(0);
106
+ }
107
+ else if (a === "-p" || a === "--print")
108
+ opts.print = value();
109
+ else if (a === "-c" || a === "--continue")
110
+ opts.cont = true;
111
+ // 不带 id 时从列表里选
112
+ else if (a === "-r" || a === "--resume")
113
+ opts.resume = argv[i + 1] === undefined || argv[i + 1].startsWith("-") ? "" : argv[++i];
114
+ else if (a === "-m" || a === "--mode") {
115
+ const m = value();
116
+ if (!MODES.includes(m))
117
+ fail(`unknown mode ${m}`);
118
+ opts.mode = m;
119
+ }
120
+ else if (a === "--cwd")
121
+ opts.cwd = value();
122
+ else if (a.startsWith("-"))
123
+ fail(`unknown option ${a}`);
124
+ else
125
+ opts.prompt.push(a);
126
+ }
127
+ function fail(msg) {
128
+ console.error(`jade: ${msg}\n\n${HELP}`);
129
+ process.exit(2);
130
+ }
131
+ /** 解析符号链接和 Windows 短文件名,和 git 给出的仓库根目录可以比较 */
132
+ function realPath(p) {
133
+ try {
134
+ return realpathSync.native(p);
135
+ }
136
+ catch {
137
+ return path.resolve(p);
138
+ }
139
+ }
140
+ const errorText = (err) => (err instanceof Error ? err.message : String(err));
141
+ async function gitBranch(dir) {
142
+ try {
143
+ const { code, stdout } = await run(["git", "rev-parse", "--abbrev-ref", "HEAD"], { cwd: dir });
144
+ return code === 0 ? stdout.trim() : undefined;
145
+ }
146
+ catch {
147
+ return undefined;
148
+ }
149
+ }
150
+ // ---------- 配置与界面 ----------
151
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
152
+ if (!(await stat(cwd).catch(() => undefined))?.isDirectory())
153
+ fail(`${cwd} is not a directory`);
154
+ const home = process.env.JADE_HOME ?? path.join(os.homedir(), ".jade");
155
+ const envFile = path.join(home, ".env");
156
+ await loadEnvFile(envFile);
157
+ const tui = Boolean(process.stdin.isTTY && process.stdout.isTTY) && opts.print === undefined;
158
+ if (!hasProvider() && !tui) {
159
+ console.error(`jade: no model is configured.\n\n` +
160
+ `Run jade in a terminal and use /model, or put one of these in ${envFile} (or set them in the shell):\n` +
161
+ ` OPENAI_COMPAT_BASE_URL=… OPENAI_COMPAT_API_KEY=… OPENAI_COMPAT_MODEL=… (any /chat/completions service)\n` +
162
+ ` OPENAI_API_KEY=… [OPENAI_BASE_URL=… OPENAI_MODEL=…] (OpenAI Responses API)\n` +
163
+ ` ANTHROPIC_API_KEY=… [ANTHROPIC_MODEL=…] (Claude)`);
164
+ process.exit(2);
165
+ }
166
+ // 写错时直接报错:NaN 会让"是否超过阈值"永远为假,每次请求都压缩
167
+ let compactTokens;
168
+ try {
169
+ compactTokens = process.env.JADE_COMPACT_TOKENS ? parseTokens("JADE_COMPACT_TOKENS", process.env.JADE_COMPACT_TOKENS) : undefined;
170
+ }
171
+ catch (err) {
172
+ fail(errorText(err));
173
+ }
174
+ /** 模型的上下文窗口:JADE_CONTEXT_WINDOW,/model 改配置后更新 */
175
+ let contextWindow = 0;
176
+ try {
177
+ contextWindow = contextWindowFromEnv();
178
+ }
179
+ catch (err) {
180
+ fail(errorText(err));
181
+ }
182
+ /** 压缩阈值:JADE_COMPACT_TOKENS,否则由上下文窗口推出 */
183
+ const compactAt = () => compactTokens ?? compactThreshold(contextWindow);
184
+ const modelLabel = () => (hasProvider() ? providerInfo().model || "(no model)" : "(no model)");
185
+ // 界面在启动过程中就已经可以输入;启动完成前提交的内容先存着,完成后再处理
186
+ let ready = false;
187
+ const early = [];
188
+ const inputs = new InputHistory(path.join(home, "history.jsonl"), cwd);
189
+ /** $JADE_HOME/plugins.json 里停用的插件(目录名或 id)和内置插件(id) */
190
+ const disabledPlugins = new Set((await readPluginSettings(home)).disabled);
191
+ const repo = realPath(await repoRoot(cwd));
192
+ /** 第三方插件目录;停用的不加载,也不读它们带的内容 */
193
+ const foundPlugins = (await discoverPlugins({ home, root: repo, cwd: realPath(cwd) })).filter((f) => !disabledPlugins.has(f.name));
194
+ /** 不执行代码就能读到的插件信息(带的 skills、命令、MCP 配置);读不了的插件在 loadPlugins 里报告 */
195
+ const pluginInfos = new Map();
196
+ for (const f of foundPlugins) {
197
+ const info = await inspectPlugin(f.dir).catch(() => undefined);
198
+ if (info)
199
+ pluginInfos.set(f.dir, info);
200
+ }
201
+ const bundled = (pick) => foundPlugins.flatMap((f) => (pluginInfos.get(f.dir) ? pick(pluginInfos.get(f.dir).bundle).map((dir) => ({ plugin: f.name, dir, layer: f.layer })) : []));
202
+ /** 自定义命令($JADE_HOME/commands、.jade/commands、插件带的 commands/);和内置命令同名的不生效 */
203
+ const builtinNames = new Set([...COMMANDS.map((c) => c.name), ...BUILTIN_PLUGIN_COMMANDS, "quit", "sessions"]);
204
+ const customLoaded = await loadCommands({ home, root: repo, cwd: realPath(cwd), plugins: bundled((b) => b.commands) });
205
+ const shadowed = customLoaded.filter((c) => builtinNames.has(c.name));
206
+ const customs = new Map(customLoaded.filter((c) => !builtinNames.has(c.name)).map((c) => [c.name, c]));
207
+ const ALL_COMMANDS = [
208
+ ...COMMANDS,
209
+ ...[...customs.values()].map((c) => ({ name: c.name, args: c.args, about: `${c.description} (${c.plugin ? `plugin ${c.plugin}` : c.layer})` })),
210
+ ];
211
+ // 终端界面依赖 ink 和 react,加载要几百毫秒,只在真的用到时才导入
212
+ const screen = tui
213
+ ? (await import("./ui/tui.js")).tuiScreen({
214
+ status: { cwd: shortPath(cwd), branch: await gitBranch(cwd), model: modelLabel(), mode: opts.mode ?? "ask" },
215
+ version: VERSION,
216
+ commands: ALL_COMMANDS,
217
+ history: await inputs.load(),
218
+ handlers: {
219
+ submit: (text) => {
220
+ inputs.add(text).catch(() => { });
221
+ if (ready)
222
+ onSubmit(text);
223
+ else
224
+ early.push(text);
225
+ },
226
+ interrupt: () => ready && interrupt(),
227
+ exit: () => (ready ? void quit() : process.exit(130)),
228
+ files: () => mentionCandidates(cwd),
229
+ cycleMode: () => ready && cycleMode(),
230
+ },
231
+ })
232
+ : plainScreen({ interactive: Boolean(process.stdin.isTTY) });
233
+ /** 压缩、子 Agent 和主循环共用;/model 改配置后换掉里面的实现 */
234
+ const provider = switchable({
235
+ id: "unconfigured",
236
+ complete: () => Promise.reject(new Error("no model is configured; use /model")),
237
+ });
238
+ /** /model 的交互:改配置后换掉 provider、更新上下文窗口和状态栏 */
239
+ const configure = configurator({
240
+ screen,
241
+ envFile,
242
+ modelsFile: path.join(home, "models.json"),
243
+ apply: async () => {
244
+ provider.set(retrying(await providerFromEnv()));
245
+ contextWindow = contextWindowFromEnv();
246
+ },
247
+ contextWindow: () => contextWindow,
248
+ onApplied: () => screen.status({ model: modelLabel() }),
249
+ });
250
+ if (!hasProvider()) {
251
+ screen.log(bold("Welcome to jade.") + " No model is configured yet; let's set one up.");
252
+ if (!(await configure.provider())) {
253
+ await screen.close();
254
+ process.exit(2);
255
+ }
256
+ }
257
+ else {
258
+ try {
259
+ provider.set(retrying(await providerFromEnv()));
260
+ }
261
+ catch (err) {
262
+ await screen.close();
263
+ fail(errorText(err));
264
+ }
265
+ }
266
+ function retrying(inner) {
267
+ return withRetry(inner, {
268
+ onRetry: ({ attempt, delayMs, error }) => screen.log(yellow(`[retry ${attempt} in ${Math.round(delayMs / 1000)}s: ${error.message}]`)),
269
+ });
270
+ }
271
+ const store = new JsonlLogStore(path.join(home, "sessions"));
272
+ const trust = new JsonlTrustStore(path.join(home, "trust.jsonl"));
273
+ const index = new SessionIndex(path.join(home, "index.jsonl"));
274
+ /** 正在结束进程外插件:这时它们退出是预期的,不提示 */
275
+ let pluginsClosing = false;
276
+ const pluginSources = await loadPlugins();
277
+ const skillsLoaded = await loadSkills({ home, root: repo, cwd: realPath(cwd), plugins: bundled((b) => b.skills) });
278
+ for (const w of skillsLoaded.warnings)
279
+ screen.log(yellow(`[warning] ${w}`));
280
+ const skills = skillsLoaded.skills;
281
+ const mcpClients = await connectMcp();
282
+ /** 每个会话用一套新的插件实例:插件里有按会话记的状态(例如压缩、重复调用的计数) */
283
+ const makeJade = (mode) => createJade({
284
+ cwd,
285
+ home,
286
+ store,
287
+ provider,
288
+ mode,
289
+ extensions: pluginSources,
290
+ disabled: disabledPlugins,
291
+ mcp: mcpClients,
292
+ skills,
293
+ compactTokens: compactAt,
294
+ approveSubagent,
295
+ sharedRules: () => [...settings().rules, ...pendingRules],
296
+ approveCheck: process.env.JADE_CHECKS === "off" ? undefined : approveCheck,
297
+ checkConfirmed: (c) => trust.has(checkHash(c)),
298
+ checksUnavailable: process.env.JADE_CHECKS === "off" ? "Edit-time checks are turned off by JADE_CHECKS=off." : undefined,
299
+ });
300
+ let jade = await makeJade(opts.mode);
301
+ for (const w of jade.warnings)
302
+ screen.log(yellow(`[warning] ${w}`));
303
+ for (const c of shadowed)
304
+ screen.log(yellow(`[warning] custom command ${display(cwd, c.file)} is ignored: /${c.name} is a built-in command`));
305
+ // 插件的命令加进菜单(名字在各个会话的实例之间不变)。内置命令和 .jade/commands 里的同名命令优先
306
+ // skill 也可以当命令用:/<skill 名> [要做的事]。内置命令和自定义命令优先
307
+ const skillCommands = new Map();
308
+ for (const sk of skills) {
309
+ const name = sk.name.toLowerCase();
310
+ if (builtinNames.has(name) || customs.has(name))
311
+ continue;
312
+ skillCommands.set(name, sk);
313
+ ALL_COMMANDS.push({ name: sk.name, args: "[task]", about: `${clip(sk.description.replace(/\s+/g, " "), 80)} (skill)` });
314
+ }
315
+ // 内置插件的命令排在宿主命令后面;第三方插件的命令排在最后
316
+ const builtinPluginCommands = [];
317
+ for (const [name, { plugin, command: c, builtin }] of jade.commands) {
318
+ if (builtin) {
319
+ builtinPluginCommands.push({ name: c.name, args: c.args, about: c.description ?? "" });
320
+ continue;
321
+ }
322
+ if (builtinNames.has(name) || customs.has(name) || skillCommands.has(name)) {
323
+ const what = builtinNames.has(name) ? "a built-in command" : customs.has(name) ? "a custom command" : "a skill";
324
+ screen.log(yellow(`[warning] command /${c.name} of plugin ${plugin} is ignored: ${what} has that name`));
325
+ continue;
326
+ }
327
+ ALL_COMMANDS.push({ name: c.name, args: c.args, about: `${c.description ?? ""} (plugin ${plugin})`.trim() });
328
+ }
329
+ ALL_COMMANDS.splice(COMMANDS.length, 0, ...builtinPluginCommands);
330
+ /**
331
+ * 第三方插件:$JADE_HOME/plugins/<name>/(用户层)和 .jade/plugins/<name>/(项目层)。
332
+ * 项目层的首次加载及内容变化后要用户确认(7.1)。加载失败的跳过并提示,不影响启动
333
+ */
334
+ async function loadPlugins() {
335
+ const out = [];
336
+ for (const f of foundPlugins) {
337
+ try {
338
+ const unsupported = pluginInfos.get(f.dir)?.bundle.unsupported ?? [];
339
+ if (unsupported.length)
340
+ screen.log(dim(`[note] plugin ${f.name}: jade does not support its ${unsupported.join(" and ")} yet; they are ignored`));
341
+ out.push(await loadPlugin(f, {
342
+ trust,
343
+ confirm: async ({ path: p, hash, files, command }) => (await screen.select(`Project plugin ${display(cwd, p)} is new or changed. Load and run it?`, [
344
+ { label: "No", value: false },
345
+ { label: "Yes, load it", value: true },
346
+ ], {
347
+ body: dim(`${command ? `runs: ${command}\n` : ""}sha256 ${hash.slice(0, 12)}, ${files.length} files:\n${files.map((f) => ` ${f}`).join("\n")}`),
348
+ })) ?? false,
349
+ onExit: (p, { code, signal }) => {
350
+ if (!pluginsClosing)
351
+ screen.log(yellow(`[warning] plugin ${p.name} exited (${signal ?? `code ${code}`}); its hooks fail until jade restarts. /plugins shows its stderr`));
352
+ },
353
+ }));
354
+ }
355
+ catch (err) {
356
+ const hint = f.layer === "project" && !tui && err instanceof UntrustedPlugin ? " (run jade interactively in this directory once to confirm it)" : "";
357
+ screen.log(yellow(`[skipped] plugin ${display(cwd, f.dir)}: ${errorText(err)}${hint}`));
358
+ }
359
+ }
360
+ return out;
361
+ }
362
+ /** 结束进程外插件的进程 */
363
+ async function closePlugins() {
364
+ pluginsClosing = true;
365
+ await Promise.all([...pluginSources.map((p) => p.close?.().catch(() => { })), ...mcpClients.map((c) => c.close().catch(() => { }))]);
366
+ }
367
+ /**
368
+ * 连接 mcp.json 里配置的 MCP 服务。项目层(随仓库分发)的服务第一次启动前要用户确认,按配置内容记在 trust.jsonl;
369
+ * 连不上的跳过并提示,不影响启动。所有服务并发连接
370
+ */
371
+ async function connectMcp() {
372
+ const plugins = foundPlugins.flatMap((f) => {
373
+ const mcp = pluginInfos.get(f.dir)?.bundle.mcp;
374
+ return mcp ? [{ plugin: f.name, dir: f.dir, layer: f.layer, file: mcp.file, servers: mcp.servers }] : [];
375
+ });
376
+ const { servers, warnings } = await loadMcpConfig({ home, root: repo, cwd: realPath(cwd), plugins });
377
+ for (const w of warnings)
378
+ screen.log(yellow(`[warning] ${w}`));
379
+ const clients = [];
380
+ for (const entry of servers) {
381
+ if (entry.config.disabled)
382
+ continue;
383
+ if (entry.layer === "project") {
384
+ const hash = mcpTrustHash(repo, entry);
385
+ if (!(await trust.has(hash))) {
386
+ const ok = tui
387
+ ? ((await screen.select(`MCP server "${entry.name}" from ${display(cwd, entry.file)} is new or changed. Start it?`, [
388
+ { label: "No", value: false },
389
+ { label: "Yes, start it", value: true },
390
+ ], { body: dim(`${entry.config.command !== undefined ? "runs" : "connects to"}: ${describeServer(entry.config)}`) })) ?? false)
391
+ : false;
392
+ if (!ok) {
393
+ screen.log(yellow(`[skipped] MCP server ${entry.name}: not confirmed${tui ? "" : " (run jade interactively in this directory once to confirm it)"}`));
394
+ continue;
395
+ }
396
+ await trust.add({ hash, path: entry.file, at: new Date().toISOString() });
397
+ }
398
+ }
399
+ clients.push(new McpClient(entry, {
400
+ cwd,
401
+ onDisconnect: (c, why) => {
402
+ if (!pluginsClosing)
403
+ screen.log(yellow(`[warning] MCP server ${c.name} disconnected: ${why}. jade reconnects on its next tool call; /mcp shows details`));
404
+ },
405
+ }));
406
+ }
407
+ if (clients.length === 0)
408
+ return clients;
409
+ screen.busy(`Connecting to ${clients.length} MCP server${clients.length > 1 ? "s" : ""}`);
410
+ await Promise.all(clients.map((c) => c.connect().catch((err) => screen.log(yellow(`[warning] MCP server ${c.name} is unavailable: ${errorText(err)}`)))));
411
+ screen.busy(undefined);
412
+ return clients;
413
+ }
414
+ let resumeId = opts.resume;
415
+ if (resumeId === "") {
416
+ if (!tui) {
417
+ await screen.close();
418
+ fail("--resume without an id needs a terminal to pick from; pass the id");
419
+ }
420
+ resumeId = await pickSession();
421
+ }
422
+ else if (resumeId)
423
+ resumeId = await findSession(resumeId);
424
+ if (opts.cont) {
425
+ resumeId = (await index.list(cwd))[0]?.id;
426
+ if (!resumeId) {
427
+ await screen.close();
428
+ fail(`no session to continue in ${cwd}`);
429
+ }
430
+ }
431
+ // /clear 换成新的运行时和会话
432
+ let rt = resumeId
433
+ ? await Runtime.resume({ store, provider, plugins: jade.plugins, sessionId: resumeId })
434
+ : await Runtime.create({ store, provider, plugins: jade.plugins });
435
+ let sessionId = rt.state.sessionId;
436
+ // 权限设置记在日志里(derived),关卡从那里读,恢复会话后仍然有效
437
+ const settings = () => jade.policy.settings(rt.state.derived);
438
+ const saveSettings = async (next) => {
439
+ await rt.record(POLICY_KEY, next);
440
+ screen.status({ mode: next.mode });
441
+ };
442
+ // ---------- 渲染 ----------
443
+ const view = transcript({ screen, cwd, store, contextWindow: () => contextWindow, compactAt: () => compactAt(), canRetry: () => canRetry() });
444
+ rt.subscribe(view.onNotice);
445
+ const percent = (part, whole) => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "—");
446
+ /** 问用户是否允许一个调用;选了"总是允许"时交给 remember 记下规则 */
447
+ async function ask(c, who, remember) {
448
+ const head = `${c.name}(${summarize(cwd, c.name, c.input)})`;
449
+ if (!screen.interactive) {
450
+ screen.log(red(`✗ ${who}${head} denied: not running interactively`));
451
+ return { approved: false, reason: "The user is not available to approve this action." };
452
+ }
453
+ const rule = jade.policy.ruleFor(c);
454
+ const always = rule.command !== undefined ? "this exact command" : describeRule(rule);
455
+ const answer = await screen.select(`Allow ${who}${head}?`, [
456
+ { label: "Yes", value: "yes" },
457
+ { label: `Yes, and always allow ${always} in this session`, value: "always" },
458
+ { label: "No, and tell jade what to do instead", value: "no" },
459
+ ], { body: await preview(c, cwd) });
460
+ if (answer === "always")
461
+ await remember(rule);
462
+ const approved = answer === "yes" || answer === "always";
463
+ const reason = approved
464
+ ? undefined
465
+ : (answer === "no" ? await screen.input("What should jade do instead? (optional)") : undefined) || "The user rejected this action.";
466
+ // 主 Agent 的调用的结果之后接在这一行后面
467
+ screen.log(approved ? green(`✓ ${who}${head}`) : red(`✗ ${who}${head}`) + dim(reason ? ` — ${clip(reason, 200)}` : ""), { id: c.toolUseId });
468
+ return { approved, reason };
469
+ }
470
+ async function approvePending() {
471
+ while (rt.state.phase === "awaiting") {
472
+ for (const c of rt.state.batch.filter((x) => x.decision === "ask")) {
473
+ const answer = await ask(c, "", async (rule) => {
474
+ const s = settings();
475
+ await saveSettings({ ...s, rules: [...s.rules, rule] });
476
+ });
477
+ await rt.send({ kind: "approval", toolUseId: c.toolUseId, ...answer });
478
+ }
479
+ }
480
+ }
481
+ /**
482
+ * 子 Agent 审批时选了"总是允许"的规则:主会话这时正在执行 task 工具,日志写不进去,
483
+ * 先在这里生效(sharedRules),这一轮结束后再记进日志
484
+ */
485
+ const pendingRules = [];
486
+ /** 并行的子 Agent 一次只问一个 */
487
+ let subagentAsking = Promise.resolve();
488
+ function approveSubagent(...[c, signal]) {
489
+ const turn = subagentAsking.then(() => {
490
+ signal.throwIfAborted();
491
+ // 中断时不再等用户回答;对话框由用户自己关掉
492
+ return abortable(ask(c, "sub-agent ", (rule) => void pendingRules.push(rule)), signal);
493
+ });
494
+ subagentAsking = turn.catch(() => { });
495
+ return turn;
496
+ }
497
+ /** 编辑后检查的确认记录:同一个目录里的同一条命令只问一次,记在 trust.jsonl */
498
+ const checkHash = (c) => createHash("sha256").update(`jade-check\0${c.cwd}\0${c.command}`).digest("hex");
499
+ /**
500
+ * 编辑后检查的命令第一次运行前问用户:它会执行仓库里的代码(node_modules 里的 tsc、配置里的命令)。
501
+ * yolo 模式不问;不能交互时不运行
502
+ */
503
+ async function approveCheck(c, signal) {
504
+ const hash = checkHash(c);
505
+ if (await trust.has(hash))
506
+ return true;
507
+ if (settings().mode === "yolo")
508
+ return true;
509
+ if (!screen.interactive)
510
+ return false;
511
+ const run = subagentAsking.then(() => {
512
+ signal.throwIfAborted();
513
+ return abortable(screen.select(`Run ${c.name} after the agent edits files, and show it the problems found?`, [
514
+ { label: "Yes, in this project from now on", value: true },
515
+ { label: "No, not in this session", value: false },
516
+ ], { body: `${c.command}\n${dim(`in ${display(cwd, c.cwd) || "."}${c.source === "config" ? " (from checks.json)" : " (detected)"}`)}` }), signal);
517
+ });
518
+ subagentAsking = run.catch(() => { });
519
+ const ok = (await run) ?? false;
520
+ if (ok)
521
+ await trust.add({ hash, path: c.cwd, at: new Date().toISOString() });
522
+ else
523
+ screen.log(dim(`[${c.name} will not run in this session; /checks on to ask again]`));
524
+ return ok;
525
+ }
526
+ /** /checks:开关本会话的编辑后检查;不带参数时列出对本会话改过的文件会运行的检查 */
527
+ /** /<skill> 发给模型的消息:让它先加载这个 skill */
528
+ function skillMessage(name, args) {
529
+ return `Use the "${name}" skill${args.trim() ? ` for this: ${args.trim()}` : "."}`;
530
+ }
531
+ /** 正在执行的插件命令;esc 中断它 */
532
+ let commandAbort;
533
+ /** 执行插件的斜杠命令,返回要发给模型的提示词(没有就是 undefined) */
534
+ async function pluginCommand(name, args) {
535
+ const found = jade.commands.get(name.toLowerCase());
536
+ if (!found) {
537
+ screen.log(red(`unknown command /${name}; type / to see the commands`));
538
+ return undefined;
539
+ }
540
+ const ac = new AbortController();
541
+ commandAbort = ac;
542
+ try {
543
+ const result = await abortable(Promise.resolve(found.command.run(args, {
544
+ sessionId,
545
+ cwd,
546
+ signal: ac.signal,
547
+ derived: structuredClone(rt.state.derived),
548
+ ui: {
549
+ interactive: screen.interactive,
550
+ log: (text) => screen.log(text),
551
+ select: (title, choices, o) => screen.select(title, choices, o),
552
+ input: (title, o) => screen.input(title, o),
553
+ },
554
+ note: (text) => void notes.push(text),
555
+ })), ac.signal);
556
+ if (typeof result === "string") {
557
+ if (result)
558
+ screen.log(result);
559
+ return undefined;
560
+ }
561
+ if (result && typeof result === "object" && typeof result.prompt === "string") {
562
+ // instant 的命令在模型工作时也会执行,不能再发一条消息
563
+ if (found.command.instant) {
564
+ screen.log(red(`[error] /${found.command.name} (plugin ${found.plugin}) is instant, so it cannot send a prompt`));
565
+ return undefined;
566
+ }
567
+ return result.prompt.trim() ? result.prompt : undefined;
568
+ }
569
+ return undefined;
570
+ }
571
+ catch (err) {
572
+ screen.log(red(`[error] /${found.command.name} (plugin ${found.plugin}): ${errorText(err)}`));
573
+ return undefined;
574
+ }
575
+ finally {
576
+ if (commandAbort === ac)
577
+ commandAbort = undefined;
578
+ }
579
+ }
580
+ /** /plugins:内置插件的状态,每个第三方插件的来源、工具、hook、命令和带的内容;跳过的插件在启动时已经提示过 */
581
+ function showPlugins() {
582
+ const width = Math.max(...jade.builtins.map((b) => b.id.length)) + 2;
583
+ const lines = [bold("Built-in") + dim(" (jade plugin disable <id> turns one off)")];
584
+ for (const b of jade.builtins) {
585
+ const state = b.state === "replaced" ? yellow(` replaced by ${b.by}`) : b.state === "disabled" ? yellow(" disabled") : "";
586
+ lines.push(` ${b.id.padEnd(width)}${dim(b.about)}${state}`);
587
+ }
588
+ const contentOnly = pluginSources.filter((p) => p.kind === "content");
589
+ lines.push("", bold("Installed") + dim(" (jade plugin add <git URL | npm package | directory>)"));
590
+ if (jade.extensions.length === 0 && contentOnly.length === 0) {
591
+ lines.push(dim(` (none) put plugins in ${display(cwd, path.join(home, "plugins"))}/<name>/ or .jade/plugins/<name>/`));
592
+ }
593
+ const carried = (b) => [b.skills.length ? "skills" : "", b.commands.length ? "commands" : "", b.mcp ? "MCP servers" : ""].filter(Boolean).join(", ");
594
+ for (const { source, plugin } of jade.extensions) {
595
+ const exit = source.process?.exited;
596
+ const state = source.kind === "process" ? (exit ? red(` exited (${exit.signal ?? `code ${exit.code}`})`) : green(" running")) : "";
597
+ lines.push(`${bold(plugin.id)} ${plugin.version} ${dim(`${source.layer} · ${display(cwd, source.dir)} · ${source.kind === "process" ? `runs ${source.entry}` : source.entry}`)}${state}`);
598
+ const tools = (plugin.tools ?? []).map((t) => `${t.name} (${t.effect})`);
599
+ const hooks = [...new Set((plugin.hooks ?? []).map((h) => `${h.kind}:${h.point}`))];
600
+ const cmds = (plugin.commands ?? []).map((c) => `/${c.name}`);
601
+ if (tools.length)
602
+ lines.push(` tools ${tools.join(", ")}`);
603
+ if (hooks.length)
604
+ lines.push(` hooks ${hooks.join(", ")}`);
605
+ if (cmds.length)
606
+ lines.push(` commands ${cmds.join(", ")}`);
607
+ if (plugin.replaces?.length)
608
+ lines.push(` replaces ${plugin.replaces.join(", ")}`);
609
+ if (carried(source.info.bundle))
610
+ lines.push(` carries ${carried(source.info.bundle)}`);
611
+ if (exit && source.process.stderr.length)
612
+ lines.push(dim(source.process.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
613
+ }
614
+ for (const p of contentOnly) {
615
+ lines.push(`${bold(p.info.name ?? p.name)}${p.info.version ? ` ${p.info.version}` : ""} ${dim(`${p.layer} · ${display(cwd, p.dir)}`)}`);
616
+ lines.push(` carries ${carried(p.info.bundle)}`);
617
+ }
618
+ screen.log(lines.join("\n"));
619
+ }
620
+ async function savePendingRules() {
621
+ if (pendingRules.length === 0)
622
+ return;
623
+ const s = settings();
624
+ await saveSettings({ ...s, rules: [...s.rules, ...pendingRules.splice(0)] });
625
+ }
626
+ function abortable(p, signal) {
627
+ return new Promise((resolve, reject) => {
628
+ const stop = () => reject(signal.reason);
629
+ signal.addEventListener("abort", stop, { once: true });
630
+ p.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
631
+ });
632
+ }
633
+ // ---------- 运行 ----------
634
+ /** 正在执行一轮对话(或一个需要独占运行时的命令) */
635
+ let running = false;
636
+ /** running 期间那段工作;退出时等它收尾 */
637
+ let work;
638
+ /** 独占运行时执行 fn;同一时间只有一个 */
639
+ async function occupy(fn) {
640
+ running = true;
641
+ work = fn();
642
+ try {
643
+ await work;
644
+ }
645
+ finally {
646
+ running = false;
647
+ work = undefined;
648
+ screen.busy(undefined);
649
+ }
650
+ }
651
+ function interrupt() {
652
+ if (!running)
653
+ return;
654
+ commandAbort?.abort(new Error("interrupted by user"));
655
+ rt.abort("interrupted by user");
656
+ screen.busy("Interrupting");
657
+ }
658
+ /** 离开会话但保留它:写入 session.detached,插件的收尾写入完成后再退出(4.2) */
659
+ async function leave() {
660
+ jade.shutdown();
661
+ try {
662
+ await rt.detach();
663
+ }
664
+ catch (err) {
665
+ screen.log(red(`[error] ${errorText(err)}`));
666
+ }
667
+ }
668
+ /** 关掉界面后再提示怎么恢复:终端界面退出备用屏幕后,里面的内容就看不到了 */
669
+ async function closeScreen() {
670
+ await screen.close();
671
+ if (rt.state.messages.length > 0)
672
+ console.log(dim(`Resume with: jade --resume ${sessionId}`));
673
+ }
674
+ let quitting = false;
675
+ async function quit(code = 0) {
676
+ if (quitting)
677
+ return;
678
+ quitting = true;
679
+ if (running)
680
+ rt.abort("exiting");
681
+ // 中断后等这一轮收尾,再写 session.detached;pump 看到 quitting 就不再取排队的输入
682
+ await work?.catch(() => { });
683
+ await leave();
684
+ await closePlugins();
685
+ await closeScreen();
686
+ process.exit(code);
687
+ }
688
+ /**
689
+ * 换成另一个会话:/clear 开始新会话,/resume 恢复 id 指定的会话。当前会话保持可恢复;
690
+ * 新会话用一套新的插件和运行时,权限模式沿用(恢复的会话用它日志里的设置)。
691
+ * 恢复失败时留在当前会话
692
+ */
693
+ async function switchSession(id) {
694
+ const mode = settings().mode;
695
+ const next = await makeJade(mode);
696
+ let nextRt;
697
+ try {
698
+ nextRt = id
699
+ ? await Runtime.resume({ store, provider, plugins: next.plugins, sessionId: id })
700
+ : await Runtime.create({ store, provider, plugins: next.plugins });
701
+ }
702
+ catch (err) {
703
+ next.shutdown();
704
+ return screen.log(red(`[error] could not resume ${id}: ${errorText(err)}`));
705
+ }
706
+ await leave();
707
+ const old = sessionId;
708
+ jade = next;
709
+ rt = nextRt;
710
+ rt.subscribe(view.onNotice);
711
+ sessionId = rt.state.sessionId;
712
+ view.reset();
713
+ notes.length = 0;
714
+ announcedMode = undefined;
715
+ pendingRules.length = 0;
716
+ screen.clear();
717
+ screen.status({ session: sessionId, mode: settings().mode, context: undefined, cache: undefined, spent: undefined });
718
+ if (!id)
719
+ return screen.log(dim(`Started a new session. The previous one can be resumed with /resume or: jade --resume ${old}`));
720
+ if (!(await resumeSession())) {
721
+ screen.log(dim("Starting a new session instead."));
722
+ await switchSession();
723
+ }
724
+ }
725
+ /** 从这个目录最近的会话里选一个;取消或没有时返回 undefined */
726
+ async function pickSession(current) {
727
+ const all = (await index.list(cwd)).filter((s) => s.id !== current).slice(0, 50);
728
+ if (all.length === 0) {
729
+ screen.log(dim(`No other sessions in ${shortPath(cwd)}.`));
730
+ return undefined;
731
+ }
732
+ return screen.select("Resume which session?", all.map((s) => ({ label: s.title || "(untitled)", value: s.id, hint: `${ago(s.at)} · ${s.id}` })));
733
+ }
734
+ /** 这个目录的会话里 id 等于 arg 或以它开头的唯一一个;都不是时原样返回,交给 Runtime.resume 去找 */
735
+ async function findSession(arg) {
736
+ const hits = (await index.list(cwd)).filter((s) => s.id.startsWith(arg));
737
+ return hits.find((s) => s.id === arg)?.id ?? (hits.length === 1 ? hits[0].id : arg);
738
+ }
739
+ /** 显示用的相对时间 */
740
+ function ago(iso) {
741
+ const s = (Date.now() - Date.parse(iso)) / 1000;
742
+ if (!Number.isFinite(s))
743
+ return iso;
744
+ if (s < 60)
745
+ return "just now";
746
+ if (s < 3600)
747
+ return `${Math.floor(s / 60)} min ago`;
748
+ if (s < 86400)
749
+ return `${Math.floor(s / 3600)} h ago`;
750
+ if (s < 86400 * 7)
751
+ return `${Math.floor(s / 86400)} d ago`;
752
+ return iso.slice(0, 10);
753
+ }
754
+ process.on("SIGINT", () => (running ? interrupt() : void quit(130)));
755
+ /** guarded 里最近一次抛出的错误;每次 guarded 开始时清掉 */
756
+ let lastThrown;
757
+ async function guarded(fn) {
758
+ view.turnFailed = false;
759
+ view.lastError = undefined;
760
+ lastThrown = undefined;
761
+ try {
762
+ await fn();
763
+ await approvePending();
764
+ }
765
+ catch (err) {
766
+ lastThrown = errorText(err);
767
+ if (!view.turnFailed)
768
+ screen.log(red(`[error] ${errorText(err)}`));
769
+ }
770
+ finally {
771
+ screen.endStream();
772
+ }
773
+ }
774
+ /** 宿主替用户告诉模型的事(例如 /undo),随下一条消息发出 */
775
+ const notes = [];
776
+ /** 最近一次告诉模型的权限模式;进入、离开计划模式时要随下一条消息告诉它 */
777
+ let announcedMode;
778
+ const PLAN_ON = "The session is now in plan mode. Investigate with read-only tools (and the task tool for broad searches); do not try to modify files " +
779
+ "or run commands that change anything, such calls are denied. When you understand the task, reply with a concise, concrete plan: " +
780
+ "the files to change and how, in order, any open questions, and how you will verify the result. Then stop and wait for the user's approval.";
781
+ const PLAN_OFF = "The session has left plan mode; you can now change files and run commands (subject to the user's approval settings).";
782
+ function announceMode() {
783
+ const mode = settings().mode;
784
+ if (mode === "plan" && announcedMode !== "plan")
785
+ notes.push(PLAN_ON);
786
+ else if (mode !== "plan" && announcedMode === "plan")
787
+ notes.push(PLAN_OFF);
788
+ announcedMode = mode;
789
+ }
790
+ /** Shift+Tab:ask → auto-edit → plan → ask;yolo、readonly 也回到 ask。运行中不切换(日志正在写) */
791
+ const CYCLE = ["ask", "auto-edit", "plan"];
792
+ function cycleMode() {
793
+ if (running)
794
+ return screen.log(dim("[the mode can be changed when jade is idle, or queue /mode <mode>]"));
795
+ const i = CYCLE.indexOf(settings().mode);
796
+ const next = CYCLE[(i + 1) % CYCLE.length];
797
+ saveSettings({ ...settings(), mode: next }).catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
798
+ }
799
+ /**
800
+ * 计划模式下模型给出计划、这一轮正常结束后,问用户是否按计划执行。
801
+ * 用户已经排了别的输入、或者不能交互时不问
802
+ */
803
+ async function offerPlan() {
804
+ if (settings().mode !== "plan" || view.lastEnd !== "end" || !screen.interactive || queue.length > 0)
805
+ return;
806
+ const last = rt.state.messages.at(-1);
807
+ if (last?.role !== "assistant" || !last.content.some((b) => b.kind === "text" && b.text.trim()))
808
+ return;
809
+ const choice = await screen.select("Execute this plan?", [
810
+ { label: "Yes, and auto-accept edits", value: "auto-edit", hint: "mode auto-edit" },
811
+ { label: "Yes, and ask before each edit", value: "ask", hint: "mode ask" },
812
+ { label: "No, keep planning", value: "plan", hint: "type what to change" },
813
+ ]);
814
+ if (!choice || choice === "plan")
815
+ return;
816
+ await saveSettings({ ...settings(), mode: choice });
817
+ screen.log(dim(`mode: ${choice}`));
818
+ await say("The plan is approved. Implement it now.");
819
+ }
820
+ const hostNote = (text) => ({ kind: "text", text: `[Note from jade] ${text}`, origin: { by: "host" }, trust: "trusted" });
821
+ /** 本进程里已经记进会话索引的会话:每个会话每次运行只记一次,索引不随消息数增长 */
822
+ const indexed = new Set();
823
+ async function say(text) {
824
+ if (!indexed.has(sessionId)) {
825
+ indexed.add(sessionId);
826
+ await index.add({ id: sessionId, cwd, title: clip(text.replace(/\s+/g, " "), 80), at: new Date().toISOString() });
827
+ }
828
+ announceMode();
829
+ const content = notes.splice(0).map(hostNote);
830
+ content.push({ kind: "text", text, origin: { by: "user" }, trust: "trusted" });
831
+ // @ 引用的文件和目录:内容随消息发出,模型不用再读一遍
832
+ const refs = await attachMentions(text, { cwd, tools: jade.tools, sessionId, signal: AbortSignal.timeout(30_000) });
833
+ for (const f of refs.failed)
834
+ screen.log(yellow(`[@${f.path} not attached: ${clip(f.reason, 200)}]`));
835
+ if (refs.attached.length)
836
+ screen.log(dim(`[attached ${refs.attached.map((p) => `@${p}`).join(", ")}]`));
837
+ content.push(...refs.blocks);
838
+ await drive({ kind: "message", content });
839
+ await offerPlan();
840
+ }
841
+ /** 上一轮在模型回复之前就失败了:最后一条消息还没有回复 */
842
+ const canRetry = () => rt.state.phase === "idle" && rt.state.messages.at(-1)?.role === "user";
843
+ async function retry() {
844
+ if (!canRetry())
845
+ return screen.log(dim("Nothing to retry: the last message already has a reply."));
846
+ await drive({ kind: "retry" });
847
+ }
848
+ async function drive(input) {
849
+ // 计时从这次输入开始,不接着上一条排队消息的
850
+ screen.busy(undefined);
851
+ screen.busy("Working");
852
+ view.lastEnd = undefined;
853
+ await guarded(() => rt.send(input));
854
+ // 请求超出了上下文窗口(窗口估大了,或者一次读进来太多):压缩后重试一次
855
+ if (isContextOverflow(view.lastError ?? lastThrown) && canRetry()) {
856
+ screen.log(yellow("[the request exceeded the model's context window; compacting the history and retrying]") +
857
+ (contextWindowInfo().source === "env" ? "" : dim(`\n[jade assumed a ${contextWindow}-token window; set the real one with /model → context window]`)));
858
+ jade.compact?.request();
859
+ await guarded(() => rt.send({ kind: "retry" }));
860
+ }
861
+ // 回复被输出上限截断:让模型接着做,而不是把半截任务丢给用户
862
+ for (let i = 0; i < MAX_CONTINUES && view.lastEnd === "max_tokens"; i++) {
863
+ screen.log(dim(`[asking the model to continue (${i + 1}/${MAX_CONTINUES})]`));
864
+ view.lastEnd = undefined;
865
+ await guarded(() => rt.send({ kind: "message", content: [hostNote(CONTINUE_NOTE)] }));
866
+ }
867
+ await savePendingRules().catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
868
+ }
869
+ /** 撤销最近一轮里还没撤销的全部文件修改:同一个文件改过几次的,恢复到这一轮改它之前的样子 */
870
+ async function undo() {
871
+ const undone = new Set(rt.state.derived[UNDO_KEY]?.undone ?? []);
872
+ const cps = lastTurnChanges(rt.state.messages, await jade.checkpoints.list(sessionId), undone);
873
+ if (cps.length === 0)
874
+ return screen.log(dim("Nothing to undo."));
875
+ /** 文件 → 这一轮最早的快照(恢复成它的 before);cps 是最新的在前 */
876
+ const files = new Map();
877
+ for (const cp of cps)
878
+ files.set(cp.path, cp);
879
+ // 只有最新一次写入之后的内容能和文件现在的样子比较
880
+ const latest = new Map();
881
+ for (const cp of cps)
882
+ if (!latest.has(cp.path))
883
+ latest.set(cp.path, cp);
884
+ const changed = [];
885
+ for (const cp of latest.values())
886
+ if (!(await jade.checkpoints.unchangedSince(cp)))
887
+ changed.push(display(cwd, cp.path));
888
+ const list = [...files.values()].map((cp) => ` ${cp.before === null ? "delete " : "restore"} ${display(cwd, cp.path)}`).join("\n");
889
+ if (files.size > 1 || changed.length > 0) {
890
+ const ok = await screen.select(changed.length > 0
891
+ ? `${changed.join(", ")} changed since the agent wrote ${changed.length > 1 ? "them" : "it"}. Undo anyway and discard those changes too?`
892
+ : `Undo the agent's last turn of changes (${files.size} files)?`, [
893
+ { label: "No", value: false },
894
+ { label: changed.length > 0 ? "Yes, undo anyway" : "Yes, undo", value: true },
895
+ ], { body: list });
896
+ if (!ok)
897
+ return;
898
+ }
899
+ for (const cp of cps)
900
+ await jade.checkpoints.restore(cp);
901
+ await rt.record(UNDO_KEY, { undone: [...undone, ...cps.map((c) => c.toolUseId)] });
902
+ const what = [...files.values()].map((cp) => cp.before === null ? `deleted ${display(cwd, cp.path)} (you had created it)` : `restored ${display(cwd, cp.path)} to its content before your changes`);
903
+ notes.push(`The user undid your changes from your last turn: ${what.join("; ")}. Read these files again before changing them.`);
904
+ screen.log(green(`Undid ${cps.length} change${cps.length > 1 ? "s" : ""} from the last turn:`) + "\n" + dim(list));
905
+ }
906
+ /** 恢复的会话里已有的内容:终端界面里重新显示对话,逐行输出时只统计用量 */
907
+ async function replayHistory() {
908
+ await view.replay(await readAll(store, sessionId), tui);
909
+ }
910
+ /** 恢复会话:先显示之前的对话,处理插件变化(4.6),再继续日志里没做完的工作。插件变化后不能继续时返回 false */
911
+ async function resumeSession() {
912
+ await replayHistory();
913
+ const held = rt.state.held;
914
+ if (held) {
915
+ screen.log(yellow(`Plugins changed since this session was last used: ${held.plugins.map((p) => `${p.id}@${p.version}`).join(", ")}`));
916
+ if (held.resolution === "abort") {
917
+ screen.log(red("A plugin requires this session to stop. Restore the previous plugins to continue."));
918
+ return false;
919
+ }
920
+ const ok = (await screen.select("Continue with the new plugins? Pending tool calls will be re-checked.", [
921
+ { label: "Yes, continue", value: true },
922
+ { label: "No", value: false },
923
+ ])) ?? false;
924
+ await guarded(() => rt.send({ kind: "plugins", approved: ok }));
925
+ if (!ok)
926
+ return false;
927
+ }
928
+ await guarded(() => rt.recover());
929
+ // 命令行明确给了 --mode 时覆盖日志里的设置
930
+ if (opts.mode && opts.mode !== settings().mode)
931
+ await saveSettings({ ...settings(), mode: opts.mode });
932
+ screen.log(dim(`Resumed ${sessionId} (${rt.state.messages.length} messages, mode ${settings().mode})`));
933
+ return true;
934
+ }
935
+ /** /memory:不带参数时列出记忆,可以删掉一条或新加一条;带参数时记下这段话 */
936
+ // ---------- 命令 ----------
937
+ const commandWidth = () => Math.max(...ALL_COMMANDS.map((c) => `/${c.name}${c.args ? ` ${c.args}` : ""}`.length)) + 2;
938
+ /** 执行命令;返回 false 表示退出 */
939
+ async function command(input) {
940
+ const [cmd, ...rest] = input.slice(1).split(/\s+/);
941
+ switch (cmd) {
942
+ case "help":
943
+ screen.log(ALL_COMMANDS.map((c) => `${`/${c.name}${c.args ? ` ${c.args}` : ""}`.padEnd(commandWidth())}${dim(c.about)}`).join("\n"));
944
+ screen.log(dim(KEYS));
945
+ break;
946
+ case "model":
947
+ await configure.model(rest[0]);
948
+ break;
949
+ case "mode": {
950
+ let m = rest[0];
951
+ if (!m) {
952
+ m = await screen.select("Permission mode", MODES.map((x) => ({ label: x, value: x, hint: x === settings().mode ? "current" : MODE_HINTS[x] })));
953
+ if (!m)
954
+ break;
955
+ }
956
+ if (!MODES.includes(m))
957
+ screen.log(red(`unknown mode ${m}`));
958
+ else
959
+ await saveSettings({ ...settings(), mode: m });
960
+ screen.log(`mode: ${settings().mode}`);
961
+ break;
962
+ }
963
+ case "undo":
964
+ await undo();
965
+ break;
966
+ case "retry":
967
+ await retry();
968
+ break;
969
+ case "clear":
970
+ await switchSession();
971
+ break;
972
+ case "resume":
973
+ case "sessions": {
974
+ const id = rest[0] ? await findSession(rest[0]) : await pickSession(sessionId);
975
+ if (!id)
976
+ break;
977
+ if (id === sessionId)
978
+ screen.log(dim("That is the current session."));
979
+ else
980
+ await switchSession(id);
981
+ break;
982
+ }
983
+ case "hooks":
984
+ for (const p of ["context.project", "context.build", "model.before", "model.after", "tool.before", "tool.gate", "tool.after", "turn.continue", "event", "session.start", "session.end"]) {
985
+ screen.log(`${p.padEnd(16)} ${rt.hookOrder(p).join(" → ") || dim("(none)")}`);
986
+ }
987
+ break;
988
+ case "plugins":
989
+ showPlugins();
990
+ break;
991
+ case "rules":
992
+ screen.log(settings().rules.length ? settings().rules.map(describeRule).join("\n") : dim("(none)"));
993
+ break;
994
+ case "usage":
995
+ screen.log(`input ${view.usage.inputTokens} output ${view.usage.outputTokens} cache read ${view.usage.cacheReadTokens} cache write ${view.usage.cacheWriteTokens} ` +
996
+ `cache hit ${percent(view.usage.cacheReadTokens, view.usage.inputTokens)}`);
997
+ screen.log(dim(`context window ${contextWindow} (${{ env: "JADE_CONTEXT_WINDOW", model: `known for ${modelLabel()}`, default: "default for unknown models" }[contextWindowInfo().source]}), ` +
998
+ `compacts at ${compactAt()}${compactTokens !== undefined ? " (JADE_COMPACT_TOKENS)" : ""}`));
999
+ break;
1000
+ case "exit":
1001
+ case "quit":
1002
+ return false;
1003
+ default: {
1004
+ const custom = customs.get(cmd.toLowerCase());
1005
+ const skill = skillCommands.get(cmd.toLowerCase());
1006
+ if (!custom && skill) {
1007
+ await say(skillMessage(skill.name, input.slice(1).replace(/^\S+\s*/, "")));
1008
+ break;
1009
+ }
1010
+ if (!custom) {
1011
+ const text = await pluginCommand(cmd, input.slice(1).replace(/^\S+\s*/, ""));
1012
+ if (text !== undefined)
1013
+ await say(text);
1014
+ break;
1015
+ }
1016
+ const text = expandCommand(custom, input.slice(1).replace(/^\S+\s*/, ""));
1017
+ if (!text.trim()) {
1018
+ screen.log(red(`/${custom.name} is empty (${display(cwd, custom.file)})`));
1019
+ break;
1020
+ }
1021
+ await say(text);
1022
+ }
1023
+ }
1024
+ return true;
1025
+ }
1026
+ const MODE_HINTS = {
1027
+ ask: "ask before edits and commands",
1028
+ "auto-edit": "edit files without asking; ask before commands",
1029
+ yolo: "never ask",
1030
+ readonly: "read only, no edits or commands",
1031
+ plan: "research read-only and propose a plan; edits start after you approve it",
1032
+ };
1033
+ // ---------- 输入 ----------
1034
+ /** 等待执行的输入:运行中提交的消息和需要独占运行时的命令排在这里,按顺序执行 */
1035
+ const queue = [];
1036
+ const echo = view.echo;
1037
+ function onSubmit(text) {
1038
+ const name = text.startsWith("/") ? text.slice(1).split(/\s+/)[0] : undefined;
1039
+ if (name !== undefined && (INSTANT.has(name) || instantPlugin(name))) {
1040
+ // 只读命令和 /model 不碰运行时状态,运行中也直接执行
1041
+ echo(text);
1042
+ if (name === "exit" || name === "quit")
1043
+ return void quit();
1044
+ return void command(text).catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
1045
+ }
1046
+ queue.push(text);
1047
+ if (running)
1048
+ screen.queued(queue);
1049
+ void pump();
1050
+ }
1051
+ /** 解析到的是插件命令(不是同名的自定义命令或 skill),而且它声明了 instant */
1052
+ function instantPlugin(name) {
1053
+ const n = name.toLowerCase();
1054
+ const found = jade.commands.get(n);
1055
+ if (!found?.command.instant)
1056
+ return false;
1057
+ if (found.builtin)
1058
+ return true;
1059
+ return !builtinNames.has(n) && !customs.has(n) && !skillCommands.has(n);
1060
+ }
1061
+ async function pump() {
1062
+ if (running)
1063
+ return;
1064
+ let exit = false;
1065
+ await occupy(async () => {
1066
+ while (queue.length > 0 && !quitting) {
1067
+ const text = queue.shift();
1068
+ screen.queued(queue);
1069
+ echo(text);
1070
+ if (text.startsWith("/")) {
1071
+ try {
1072
+ if (!(await command(text))) {
1073
+ exit = true;
1074
+ return;
1075
+ }
1076
+ }
1077
+ catch (err) {
1078
+ screen.log(red(`[error] ${errorText(err)}`));
1079
+ }
1080
+ }
1081
+ else
1082
+ await say(text);
1083
+ }
1084
+ });
1085
+ if (exit)
1086
+ await quit();
1087
+ }
1088
+ // ---------- 开始 ----------
1089
+ if (resumeId) {
1090
+ let ok = false;
1091
+ await occupy(async () => void (ok = await resumeSession()));
1092
+ if (!ok) {
1093
+ await screen.close();
1094
+ process.exit(1);
1095
+ }
1096
+ }
1097
+ else if (tui)
1098
+ screen.log(dim("Type / for commands, /model to configure the model, esc to interrupt."));
1099
+ else
1100
+ screen.log(dim(`jade · ${shortPath(cwd)} · ${modelLabel()} · mode ${settings().mode} · session ${sessionId}`));
1101
+ screen.status({ mode: settings().mode, session: sessionId });
1102
+ const first = opts.print ?? (opts.prompt.length > 0 ? opts.prompt.join(" ") : undefined);
1103
+ if (tui) {
1104
+ // 之后由输入框驱动:onSubmit → pump
1105
+ ready = true;
1106
+ for (const text of [...(first ? [first] : []), ...early.splice(0)])
1107
+ onSubmit(text);
1108
+ }
1109
+ else {
1110
+ // -p 也能用自定义命令和插件的命令(内置命令需要交互,不在这里处理)
1111
+ const name = first?.startsWith("/") ? first.slice(1).split(/\s+/)[0].toLowerCase() : undefined;
1112
+ const args = first?.slice(1).replace(/^\S+\s*/, "") ?? "";
1113
+ const custom = name !== undefined ? customs.get(name) : undefined;
1114
+ await occupy(async () => {
1115
+ const skill = name !== undefined && !custom ? skillCommands.get(name) : undefined;
1116
+ const text = custom ? expandCommand(custom, args) : skill ? skillMessage(skill.name, args) : name !== undefined && !builtinNames.has(name) && jade.commands.has(name) ? await pluginCommand(name, args) : first;
1117
+ if (text)
1118
+ await say(text);
1119
+ });
1120
+ await leave();
1121
+ await closePlugins();
1122
+ await closeScreen();
1123
+ }
1124
+ //# sourceMappingURL=main.js.map