@uncarved/jade 0.1.1 → 0.1.3

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 (154) hide show
  1. package/README.md +18 -6
  2. package/bin/jade.js +23 -0
  3. package/dist/commands.d.ts +20 -0
  4. package/dist/commands.js +20 -0
  5. package/dist/commands.js.map +1 -1
  6. package/dist/distro.d.ts +51 -7
  7. package/dist/distro.js +199 -48
  8. package/dist/distro.js.map +1 -1
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.js +3 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/main.js +479 -303
  13. package/dist/main.js.map +1 -1
  14. package/dist/mcp.js +1 -1
  15. package/dist/mcp.js.map +1 -1
  16. package/dist/plugin-cli.d.ts +1 -1
  17. package/dist/plugin-cli.js +79 -36
  18. package/dist/plugin-cli.js.map +1 -1
  19. package/dist/plugins/budget.d.ts +2 -2
  20. package/dist/plugins/budget.js +2 -2
  21. package/dist/plugins/budget.js.map +1 -1
  22. package/dist/plugins/builtins.js +6 -3
  23. package/dist/plugins/builtins.js.map +1 -1
  24. package/dist/plugins/checks.d.ts +2 -1
  25. package/dist/plugins/checks.js +25 -5
  26. package/dist/plugins/checks.js.map +1 -1
  27. package/dist/plugins/compact.js +45 -1
  28. package/dist/plugins/compact.js.map +1 -1
  29. package/dist/plugins/core.d.ts +5 -0
  30. package/dist/plugins/core.js +39 -0
  31. package/dist/plugins/core.js.map +1 -1
  32. package/dist/plugins/host.d.ts +52 -0
  33. package/dist/plugins/host.js +115 -0
  34. package/dist/plugins/host.js.map +1 -0
  35. package/dist/plugins/install.d.ts +1 -1
  36. package/dist/plugins/loader.d.ts +238 -10
  37. package/dist/plugins/loader.js +175 -21
  38. package/dist/plugins/loader.js.map +1 -1
  39. package/dist/plugins/policy.d.ts +23 -5
  40. package/dist/plugins/policy.js +63 -10
  41. package/dist/plugins/policy.js.map +1 -1
  42. package/dist/plugins/prompts.d.ts +14 -1
  43. package/dist/plugins/prompts.js +118 -16
  44. package/dist/plugins/prompts.js.map +1 -1
  45. package/dist/plugins/repeats.d.ts +7 -0
  46. package/dist/plugins/repeats.js +74 -13
  47. package/dist/plugins/repeats.js.map +1 -1
  48. package/dist/plugins/review.d.ts +18 -0
  49. package/dist/plugins/review.js +130 -0
  50. package/dist/plugins/review.js.map +1 -0
  51. package/dist/plugins/sessions.d.ts +7 -0
  52. package/dist/plugins/sessions.js +110 -0
  53. package/dist/plugins/sessions.js.map +1 -0
  54. package/dist/provider.d.ts +57 -3
  55. package/dist/provider.js +80 -10
  56. package/dist/provider.js.map +1 -1
  57. package/dist/session-lifecycle.d.ts +61 -0
  58. package/dist/session-lifecycle.js +167 -0
  59. package/dist/session-lifecycle.js.map +1 -0
  60. package/dist/session-scope.d.ts +53 -0
  61. package/dist/session-scope.js +116 -0
  62. package/dist/session-scope.js.map +1 -0
  63. package/dist/sessions.d.ts +6 -0
  64. package/dist/sessions.js +20 -0
  65. package/dist/sessions.js.map +1 -1
  66. package/dist/sys.d.ts +4 -1
  67. package/dist/sys.js +18 -1
  68. package/dist/sys.js.map +1 -1
  69. package/dist/tools/ask.d.ts +11 -0
  70. package/dist/tools/ask.js +62 -0
  71. package/dist/tools/ask.js.map +1 -0
  72. package/dist/tools/fs.d.ts +4 -0
  73. package/dist/tools/fs.js +53 -12
  74. package/dist/tools/fs.js.map +1 -1
  75. package/dist/tools/grep.js +3 -2
  76. package/dist/tools/grep.js.map +1 -1
  77. package/dist/tools/shell.js +5 -1
  78. package/dist/tools/shell.js.map +1 -1
  79. package/dist/tools/task.d.ts +10 -2
  80. package/dist/tools/task.js +40 -9
  81. package/dist/tools/task.js.map +1 -1
  82. package/dist/tools/web.d.ts +33 -3
  83. package/dist/tools/web.js +351 -143
  84. package/dist/tools/web.js.map +1 -1
  85. package/dist/ui/configure.js +144 -66
  86. package/dist/ui/configure.js.map +1 -1
  87. package/dist/ui/diff.d.ts +1 -1
  88. package/dist/ui/diff.js +1 -2
  89. package/dist/ui/diff.js.map +1 -1
  90. package/dist/ui/editor.d.ts +8 -0
  91. package/dist/ui/editor.js +50 -1
  92. package/dist/ui/editor.js.map +1 -1
  93. package/dist/ui/markdown.d.ts +22 -0
  94. package/dist/ui/markdown.js +242 -0
  95. package/dist/ui/markdown.js.map +1 -0
  96. package/dist/ui/render.d.ts +9 -8
  97. package/dist/ui/render.js +35 -62
  98. package/dist/ui/render.js.map +1 -1
  99. package/dist/ui/renderers.d.ts +8 -0
  100. package/dist/ui/renderers.js +169 -0
  101. package/dist/ui/renderers.js.map +1 -0
  102. package/dist/ui/screen.d.ts +25 -2
  103. package/dist/ui/screen.js +104 -12
  104. package/dist/ui/screen.js.map +1 -1
  105. package/dist/ui/transcript.d.ts +13 -0
  106. package/dist/ui/transcript.js +157 -31
  107. package/dist/ui/transcript.js.map +1 -1
  108. package/dist/ui/tui.d.ts +2 -0
  109. package/dist/ui/tui.js +383 -81
  110. package/dist/ui/tui.js.map +1 -1
  111. package/dist/update.d.ts +53 -0
  112. package/dist/update.js +255 -0
  113. package/dist/update.js.map +1 -0
  114. package/package.json +7 -6
  115. package/src/commands.ts +24 -0
  116. package/src/distro.ts +234 -52
  117. package/src/index.ts +3 -0
  118. package/src/main.ts +459 -300
  119. package/src/mcp.ts +1 -1
  120. package/src/plugin-cli.ts +73 -34
  121. package/src/plugins/budget.ts +4 -4
  122. package/src/plugins/builtins.ts +6 -3
  123. package/src/plugins/checks.ts +25 -6
  124. package/src/plugins/compact.ts +40 -1
  125. package/src/plugins/core.ts +40 -0
  126. package/src/plugins/host.ts +146 -0
  127. package/src/plugins/install.ts +1 -1
  128. package/src/plugins/loader.ts +379 -23
  129. package/src/plugins/policy.ts +70 -13
  130. package/src/plugins/prompts.ts +128 -16
  131. package/src/plugins/repeats.ts +75 -14
  132. package/src/plugins/review.ts +146 -0
  133. package/src/plugins/sessions.ts +109 -0
  134. package/src/provider.ts +117 -14
  135. package/src/session-lifecycle.ts +194 -0
  136. package/src/session-scope.ts +135 -0
  137. package/src/sessions.ts +17 -0
  138. package/src/sys.ts +18 -1
  139. package/src/tools/ask.ts +72 -0
  140. package/src/tools/fs.ts +53 -12
  141. package/src/tools/grep.ts +3 -2
  142. package/src/tools/shell.ts +5 -1
  143. package/src/tools/task.ts +56 -12
  144. package/src/tools/web.ts +370 -140
  145. package/src/ui/configure.ts +141 -67
  146. package/src/ui/diff.ts +1 -2
  147. package/src/ui/editor.ts +50 -1
  148. package/src/ui/markdown.ts +258 -0
  149. package/src/ui/render.ts +35 -48
  150. package/src/ui/renderers.ts +183 -0
  151. package/src/ui/screen.ts +113 -16
  152. package/src/ui/transcript.ts +164 -35
  153. package/src/ui/tui.tsx +424 -79
  154. package/src/update.ts +262 -0
package/src/main.ts CHANGED
@@ -5,54 +5,60 @@
5
5
  // 不读当前目录的 .env(见 config.ts):模型配置放在 $JADE_HOME/.env。
6
6
  // 交互运行时用终端界面(ui/tui.tsx),-p 和非交互运行时逐行输出(ui/screen.ts)。
7
7
 
8
- import { readdir, stat } from "node:fs/promises";
8
+ import { mkdtemp, readdir, stat } from "node:fs/promises";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
11
  import { createHash } from "node:crypto";
12
+ import { stripVTControlCharacters } from "node:util";
12
13
  import { JsonlLogStore, JsonlTrustStore } from "@uncarved/store-jsonl";
13
14
  import {
14
15
  readAll,
15
16
  Runtime,
16
17
  RuntimeBusy,
17
- UntrustedPlugin,
18
18
  type Block,
19
19
  type Plugin,
20
20
  type Provider,
21
21
  type UserInput,
22
22
  } from "uncarved";
23
23
  import { realpathSync } from "node:fs";
24
- import { expandCommand, loadCommands } from "./commands.ts";
25
- import { discoverPlugins, inspectPlugin, loadPlugin, type LoadedPlugin, type PluginBundle, type PluginInfo } from "./plugins/loader.ts";
24
+ import { expandCommand, loadCommands, pluginMenu } from "./commands.ts";
25
+ import { type PluginBundle, type SessionControl } from "./plugins/loader.ts";
26
+ import { openPluginHost } from "./plugins/host.ts";
26
27
  import { readPluginSettings } from "./plugins/install.ts";
27
28
  import { PLUGIN_HELP, pluginCli, UsageError } from "./plugin-cli.ts";
28
29
  import { describeServer, loadMcpConfig, McpClient, mcpTrustHash } from "./mcp.ts";
29
30
  import { loadSkills } from "./skills.ts";
30
- import { hasProvider, loadEnvFile, parseTokens } from "./config.ts";
31
+ import { hasProvider, loadEnvFile, parseTokens, updateEnvFile } from "./config.ts";
31
32
  import { createJade, type Jade } from "./distro.ts";
33
+ import { SessionScope } from "./session-scope.ts";
34
+ import { SessionLifecycle, type Current } from "./session-lifecycle.ts";
32
35
  import { describeRule, MODES, POLICY_KEY, type AllowRule, type Mode, type PolicySettings } from "./plugins/policy.ts";
33
36
  import { compactThreshold, contextWindowFromEnv, contextWindowInfo, isContextOverflow } from "./context.ts";
34
37
  import { InputHistory } from "./history.ts";
35
38
  import { attachMentions, mentionCandidates } from "./mentions.ts";
36
39
  import { repoRoot } from "./plugins/prompts.ts";
37
- import { isRateLimit, providerFromEnv, providerInfo, RateGate, rpmFromEnv, switchable, withRetry } from "./provider.ts";
38
- import { discardIfEmpty, SessionIndex } from "./sessions.ts";
39
- import { lastTurnChanges, UNDO_KEY, type Checkpoint, type UndoState } from "./tools/checkpoint.ts";
40
+ import { isBuiltinKind, isRateLimit, pluginProvider, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, switchable, withRetry } from "./provider.ts";
41
+ import { ago, discardIfEmpty, matchSession, SessionIndex } from "./sessions.ts";
40
42
  import { display } from "./tools/fs.ts";
41
43
  import type { ApproveSubagent, SubagentApproval } from "./tools/task.ts";
44
+ import type { Question } from "./tools/ask.ts";
42
45
  import type { Check } from "./plugins/checks.ts";
43
- import { bold, dim, green, plainScreen, red, yellow, type CommandInfo, type Screen } from "./ui/screen.ts";
46
+ import { bold, dim, green, plainScreen, red, safeScreen, yellow, type CommandInfo, type Screen } from "./ui/screen.ts";
44
47
  import { configurator } from "./ui/configure.ts";
45
- import { clip, preview, shortPath, summarize } from "./ui/render.ts";
48
+ import { reviewer } from "./plugins/review.ts";
49
+ import { clip, shortPath } from "./ui/render.ts";
46
50
  import { transcript } from "./ui/transcript.ts";
47
51
  import { run, VERSION } from "./sys.ts";
52
+ import { autoUpdate, autoUpdateEnabled, detectInstall, newerVersion, updateCli } from "./update.ts";
48
53
 
49
54
  const HELP = `Usage: jade [options] [prompt]
50
55
  jade plugin <list|add|update|remove|enable|disable> (jade plugin --help)
56
+ jade update [--check] upgrade jade to the latest version on npm
51
57
 
52
58
  -p, --print <prompt> run one prompt and exit
53
59
  -c, --continue continue the most recent session in this directory
54
60
  -r, --resume [id] resume a session by id, or pick one from a list
55
- -m, --mode <mode> permission mode: ${MODES.join(" | ")} (default ask)
61
+ -m, --mode <mode> permission mode for this run: ${MODES.join(" | ")} (default: the last mode you switched to, or ask)
56
62
  --cwd <dir> working directory (default: current directory)
57
63
  -v, --version
58
64
  -h, --help
@@ -66,25 +72,21 @@ const COMMANDS: CommandInfo[] = [
66
72
  { name: "help", about: "list the commands and keys" },
67
73
  { name: "model", args: "[name]", about: "switch between saved models, or add one and configure its provider, API key and output limit" },
68
74
  { name: "mode", args: `[${MODES.join("|")}]`, about: "show or change the permission mode" },
69
- { name: "clear", about: "start a new session (the current one stays resumable)" },
70
- { name: "undo", about: "restore every file the agent changed in its last turn (run again to go further back)" },
71
- { name: "retry", about: "request the model again after a failed request, without sending another message" },
72
- { name: "usage", about: "token usage of this session, including sub-agents and compaction" },
73
- { name: "resume", args: "[id]", about: "pick a recent session in this directory and switch to it" },
74
- { name: "rules", about: `"always allow" rules of this session` },
75
- { name: "plugins", about: "built-in and installed plugins: their tools, hooks and commands" },
76
- { name: "hooks", about: "execution order of every extension point" },
75
+ { name: "plugins", about: "built-in and installed plugins: their tools, hooks and commands, and the hook execution order" },
77
76
  { name: "exit", about: "quit (the session stays resumable)" },
78
77
  ];
79
78
  /** 运行中也立即执行的命令(不碰运行时,或者只读;/mode 运行中先记在 pendingMode) */
80
- const INSTANT = new Set(["help", "model", "mode", "usage", "rules", "hooks", "plugins", "exit", "quit"]);
79
+ const INSTANT = new Set(["help", "model", "mode", "plugins", "exit"]);
81
80
  /** 内置插件提供的命令(/memory 在 jade/memory 里,等等):名字保留给它们,自定义命令不能占用 */
82
- const BUILTIN_PLUGIN_COMMANDS = ["memory", "checks", "mcp", "skills", "compact"];
81
+ const BUILTIN_PLUGIN_COMMANDS = ["memory", "checks", "mcp", "skills", "compact", "clear", "resume", "retry", "undo", "search"];
83
82
 
84
- const KEYS = `Keys: enter send · \\ or alt+enter new line · ↑↓ history · @ reference a file · esc interrupt (twice to also clear queued messages) · shift+tab cycle ask/auto-edit/plan · ctrl+c twice to exit
85
- mouse wheel or PgUp/PgDn scroll the conversation · ctrl+home/ctrl+end jump to the top/bottom · shift+drag selects text
83
+ const KEYS = `Keys: enter send · \\ or alt+enter new line · ↑↓ history · @ reference a file · esc interrupt (twice to also clear queued messages) · shift+tab cycle ask/auto/plan · ctrl+c twice to exit
84
+ mouse wheel or PgUp/PgDn scroll the conversation · ctrl+home/ctrl+end jump to the top/bottom · click ▸ expands an item (ctrl+o the latest one) · click in the input moves the cursor · shift+drag selects text
86
85
  While jade is working you can keep typing: messages are queued and sent when the current turn ends.`;
87
86
 
87
+ /** 终端界面启动时最多等 MCP 服务连接这么久,没连上的在后台接着连 */
88
+ const MCP_STARTUP_WAIT_MS = 5000;
89
+
88
90
  /** 回复被输出上限截断后,自动让模型接着做的次数(每条用户消息) */
89
91
  const MAX_CONTINUES = 3;
90
92
  const CONTINUE_NOTE =
@@ -105,6 +107,7 @@ if (argv[0] === "plugin" || argv[0] === "plugins") {
105
107
  process.exit(err instanceof UsageError ? 2 : 1);
106
108
  }
107
109
  }
110
+ if (argv[0] === "update") process.exit(await updateCli(argv.slice(1)));
108
111
  const opts: { print?: string; cont?: boolean; resume?: string; mode?: Mode; cwd?: string; prompt: string[] } = { prompt: [] };
109
112
  for (let i = 0; i < argv.length; i++) {
110
113
  const a = argv[i]!;
@@ -165,14 +168,28 @@ const home = process.env.JADE_HOME ?? path.join(os.homedir(), ".jade");
165
168
  const envFile = path.join(home, ".env");
166
169
  await loadEnvFile(envFile);
167
170
 
171
+ /** 新会话的权限模式:-m 只管这一次;没给时用上次在会话里切换到的模式(JADE_MODE,见 rememberMode),都没有时是 ask */
172
+ const savedMode = process.env.JADE_MODE?.trim();
173
+ const badSavedMode = savedMode && !(MODES as readonly string[]).includes(savedMode) ? savedMode : undefined;
174
+ if (savedMode && !badSavedMode) opts.mode ??= savedMode as Mode;
175
+
168
176
  const tui = Boolean(process.stdin.isTTY && process.stdout.isTTY) && opts.print === undefined;
177
+ // 终端界面依赖 ink 和 react,加载要几百毫秒,只在真的用到时才导入;现在就开始加载,和下面读配置、跑 git 同时进行
178
+ const tuiModule = tui ? import("./ui/tui.tsx") : undefined;
179
+ const branchFound = tui ? gitBranch(cwd) : undefined;
180
+ // provider 要动态导入 SDK(一百多毫秒),和终端界面一起加载;出错时在下面创建界面之后再报。
181
+ // JADE_PROVIDER 选的是插件提供的服务时,等插件加载完再创建(pluginProviderPending)
182
+ const pluginProviderPending = hasProvider() && !isBuiltinKind(providerKind());
183
+ const providerEarly = hasProvider() && !pluginProviderPending ? providerFromEnv() : undefined;
184
+ providerEarly?.catch(() => {});
169
185
  if (!hasProvider() && !tui) {
170
186
  console.error(
171
187
  `jade: no model is configured.\n\n` +
172
188
  `Run jade in a terminal and use /model, or put one of these in ${envFile} (or set them in the shell):\n` +
173
189
  ` OPENAI_COMPAT_BASE_URL=… OPENAI_COMPAT_API_KEY=… OPENAI_COMPAT_MODEL=… (any /chat/completions service)\n` +
174
190
  ` OPENAI_API_KEY=… [OPENAI_BASE_URL=… OPENAI_MODEL=…] (OpenAI Responses API)\n` +
175
- ` ANTHROPIC_API_KEY=… [ANTHROPIC_MODEL=…] (Claude)`,
191
+ ` ANTHROPIC_API_KEY=… [ANTHROPIC_MODEL=…] (Claude)\n` +
192
+ ` JADE_PROVIDER=<kind> plus the settings that plugin documents (a model service from a plugin)`,
176
193
  );
177
194
  process.exit(2);
178
195
  }
@@ -202,22 +219,41 @@ const early: string[] = [];
202
219
 
203
220
  const inputs = new InputHistory(path.join(home, "history.jsonl"), cwd);
204
221
 
205
- /** $JADE_HOME/plugins.json 里停用的插件(目录名或 id)和内置插件(id) */
222
+ /** $JADE_HOME/plugins.json 里停用的插件和内置插件(id) */
206
223
  const disabledPlugins = new Set((await readPluginSettings(home)).disabled);
207
224
  const repo = realPath(await repoRoot(cwd));
208
- /** 第三方插件目录;停用的不加载,也不读它们带的内容 */
209
- const foundPlugins = (await discoverPlugins({ home, root: repo, cwd: realPath(cwd) })).filter((f) => !disabledPlugins.has(f.name));
210
- /** 不执行代码就能读到的插件信息(带的 skills、命令、MCP 配置);读不了的插件在 loadPlugins 里报告 */
211
- const pluginInfos = new Map<string, PluginInfo>();
212
- for (const f of foundPlugins) {
213
- const info = await inspectPlugin(f.dir).catch(() => undefined);
214
- if (info) pluginInfos.set(f.dir, info);
215
- }
216
- const bundled = (pick: (b: PluginBundle) => string[]) =>
217
- foundPlugins.flatMap((f) => (pluginInfos.get(f.dir) ? pick(pluginInfos.get(f.dir)!.bundle).map((dir) => ({ plugin: f.name, dir, layer: f.layer })) : []));
225
+ const trust = new JsonlTrustStore(path.join(home, "trust.jsonl"));
226
+ /**
227
+ * 第三方插件(进程级,见 plugins/host.ts):这里只读清单,不执行代码,停用的不加载,也不读它们带的内容。
228
+ * 加载(项目层的要确认)在界面起来之后
229
+ */
230
+ const plugins = await openPluginHost({
231
+ home,
232
+ root: repo,
233
+ cwd: realPath(cwd),
234
+ disabled: disabledPlugins,
235
+ trust,
236
+ confirm: async ({ path: p, hash, files, command }) =>
237
+ (await screen.select(
238
+ `Project plugin ${display(cwd, p)} is new or changed. Load and run it?`,
239
+ [
240
+ { label: "No", value: false },
241
+ { label: "Yes, load it", value: true },
242
+ ],
243
+ {
244
+ body: dim(`${command ? `runs: ${command}\n` : ""}sha256 ${hash.slice(0, 12)}, ${files.length} files:\n${files.map((f) => ` ${f}`).join("\n")}`),
245
+ },
246
+ )) ?? false,
247
+ report: (kind, text) => screen.log(kind === "note" ? dim(`[note] ${text}`) : yellow(`[${kind}] ${text}`)),
248
+ display: (dir) => display(cwd, dir),
249
+ untrustedHint: tui ? undefined : "(run jade interactively in this directory once to confirm it)",
250
+ });
251
+ const bundled = plugins.bundled;
218
252
 
219
253
  /** 自定义命令($JADE_HOME/commands、.jade/commands、插件带的 commands/);和内置命令同名的不生效 */
220
- const builtinNames = new Set([...COMMANDS.map((c) => c.name), ...BUILTIN_PLUGIN_COMMANDS, "quit", "sessions"]);
254
+ const builtinNames = new Set([...COMMANDS.map((c) => c.name), ...BUILTIN_PLUGIN_COMMANDS]);
255
+ /** 宿主自己处理的命令(/help、/model 等):插件的同名命令永远不生效 */
256
+ const hostNames = new Set(COMMANDS.map((c) => c.name));
221
257
  const customLoaded = await loadCommands({ home, root: repo, cwd: realPath(cwd), plugins: bundled((b) => b.commands) });
222
258
  const shadowed = customLoaded.filter((c) => builtinNames.has(c.name));
223
259
  const customs = new Map(customLoaded.filter((c) => !builtinNames.has(c.name)).map((c) => [c.name, c]));
@@ -226,10 +262,10 @@ const ALL_COMMANDS: CommandInfo[] = [
226
262
  ...[...customs.values()].map((c) => ({ name: c.name, args: c.args, about: `${c.description} (${c.plugin ? `plugin ${c.plugin}` : c.layer})` })),
227
263
  ];
228
264
 
229
- // 终端界面依赖 ink 和 react,加载要几百毫秒,只在真的用到时才导入
230
- const screen: Screen = tui
231
- ? (await import("./ui/tui.tsx")).tuiScreen({
232
- status: { cwd: shortPath(cwd), branch: await gitBranch(cwd), model: modelLabel(), mode: opts.mode ?? "ask" },
265
+ // 插件、工具输出和模型的文字都经过这里显示:只留颜色,去掉能搅乱终端的控制序列
266
+ const screen: Screen = safeScreen(tuiModule
267
+ ? (await tuiModule).tuiScreen({
268
+ status: { cwd: shortPath(cwd), branch: await branchFound, model: modelLabel(), mode: opts.mode ?? "ask" },
233
269
  version: VERSION,
234
270
  commands: ALL_COMMANDS,
235
271
  history: await inputs.load(),
@@ -243,9 +279,10 @@ const screen: Screen = tui
243
279
  exit: () => (ready ? void quit() : process.exit(130)),
244
280
  files: () => mentionCandidates(cwd),
245
281
  cycleMode: () => ready && cycleMode(),
282
+ key: (spec) => ready && pluginKey(spec),
246
283
  },
247
284
  })
248
- : plainScreen({ interactive: Boolean(process.stdin.isTTY) });
285
+ : plainScreen({ interactive: Boolean(process.stdin.isTTY) }));
249
286
 
250
287
  /** 压缩、子 Agent 和主循环共用;/model 改配置后换掉里面的实现 */
251
288
  const provider = switchable({
@@ -266,15 +303,10 @@ const configure = configurator({
266
303
  onApplied: () => screen.status({ model: modelLabel() }),
267
304
  });
268
305
 
269
- if (!hasProvider()) {
270
- screen.log(bold("Welcome to jade.") + " No model is configured yet; let's set one up.");
271
- if (!(await configure.provider())) {
272
- await screen.close();
273
- process.exit(2);
274
- }
275
- } else {
306
+ // 还没配置模型时,等插件加载完再问(见下面 registerProviders 之后):插件提供的服务也要列出来
307
+ if (providerEarly) {
276
308
  try {
277
- provider.set(retrying(await providerFromEnv()));
309
+ provider.set(retrying(await providerEarly));
278
310
  } catch (err) {
279
311
  await screen.close();
280
312
  fail(errorText(err));
@@ -305,10 +337,11 @@ function retrying(inner: Provider) {
305
337
  waiting = false;
306
338
  },
307
339
  onRetry: ({ attempt, retries, delayMs, error }) => {
308
- const why = isRateLimit(error) ? "rate limited" : clip(error.message.replace(/\s+/g, " "), 160);
309
- screen.log(yellow(`[${why} · retry ${attempt}/${retries} in ${seconds(delayMs)}]`));
340
+ const why = isRateLimit(error) ? "rate limited" : clip(error.message.replace(/\s+/g, " "), tui ? 60 : 160);
341
+ // 终端界面只在状态行显示,不在对话里每次重试刷一行;重试用完仍然失败时照常报错
342
+ if (!tui) screen.log(yellow(`[${why} · retry ${attempt}/${retries} in ${seconds(delayMs)}]`));
310
343
  waiting = true;
311
- screen.busy(`Waiting to retry (${attempt}/${retries}, ${seconds(delayMs)})`);
344
+ screen.busy(`Waiting to retry (${why} · ${attempt}/${retries}, ${seconds(delayMs)})`);
312
345
  },
313
346
  });
314
347
  }
@@ -316,44 +349,141 @@ function retrying(inner: Provider) {
316
349
  const seconds = (ms: number) => (ms >= 60_000 ? `${Math.floor(ms / 60_000)}m${Math.round((ms % 60_000) / 1000) ? `${Math.round((ms % 60_000) / 1000)}s` : ""}` : `${Math.max(1, Math.round(ms / 1000))}s`);
317
350
 
318
351
  const store = new JsonlLogStore(path.join(home, "sessions"));
319
- const trust = new JsonlTrustStore(path.join(home, "trust.jsonl"));
320
352
  const index = new SessionIndex(path.join(home, "index.jsonl"));
321
353
 
322
- /** 正在结束进程外插件:这时它们退出是预期的,不提示 */
354
+ /** 正在退出:这时 MCP 服务断开是预期的,不提示 */
323
355
  let pluginsClosing = false;
324
- const pluginSources = await loadPlugins();
325
- const skillsLoaded = await loadSkills({ home, root: repo, cwd: realPath(cwd), plugins: bundled((b) => b.skills) });
356
+ // 插件、skill、MCP 服务同时加载:MCP 服务启动可能要好几秒。确认对话框一个接一个:MCP 的排在插件的后面。
357
+ // 插件加载完就注册了它们导出的模型服务(不用创建插件实例),所以下面先配置好模型,再创建插件,工厂函数里也能用 ctx.complete
358
+ const pluginsLoading = plugins.load();
359
+ const mcpConnecting = connectMcp(pluginsLoading);
360
+ const skillsLoading = loadSkills({ home, root: repo, cwd: realPath(cwd), plugins: bundled((b) => b.skills) });
361
+ const pluginSources = await pluginsLoading;
362
+ const skillsLoaded = await skillsLoading;
326
363
  for (const w of skillsLoaded.warnings) screen.log(yellow(`[warning] ${w}`));
327
364
  const skills = skillsLoaded.skills;
328
- const mcpClients = await connectMcp();
365
+ const mcpClients = await mcpConnecting;
329
366
  /**
330
367
  * 运行中切换的权限模式:这一轮正占着日志,写不进去。关卡先按它判断(下一个工具调用就生效),
331
368
  * 这一轮结束后再记进日志(flushPendingMode)
332
369
  */
333
370
  let pendingMode: Mode | undefined;
334
- /** 每个会话用一套新的插件实例:插件里有按会话记的状态(例如压缩、重复调用的计数) */
335
- const makeJade = (mode?: Mode) =>
336
- createJade({
371
+ /** 当前配置的模型和服务,写进系统提示词,用户问起时模型照这个回答;/model 改了配置后下一次请求就是新的 */
372
+ function currentModel(): { name: string; via: string } | undefined {
373
+ if (!hasProvider()) return undefined;
374
+ const info = providerInfo();
375
+ let host: string | undefined;
376
+ try {
377
+ host = info.baseURL ? new URL(info.baseURL).host : undefined;
378
+ } catch {}
379
+ if (!isBuiltinKind(info.kind)) {
380
+ let via = `the ${info.kind} provider`;
381
+ try {
382
+ via = pluginProvider(info.kind)?.def.via?.(process.env) || via;
383
+ } catch {}
384
+ return { name: info.model, via };
385
+ }
386
+ const api = { anthropic: "the Anthropic API", openai: "the OpenAI Responses API", "openai-compat": "an OpenAI-compatible API" }[info.kind];
387
+ return { name: info.model, via: host ? `${api} at ${host}` : api };
388
+ }
389
+
390
+ // 模型放临时脚本、测试数据的目录,整个进程共用一个(换会话时提示词不变,不影响缓存)。
391
+ // 写成正斜杠:Windows 上 Git Bash、Python、Node 都认 C:/Users/...,而 /tmp 在它们之间不是同一个地方
392
+ const scratch = realpathSync.native(await mkdtemp(path.join(os.tmpdir(), "jade-"))).replaceAll("\\", "/");
393
+
394
+ /**
395
+ * 每个会话用一套新的插件实例(SessionScope):插件里有按会话记的状态(例如压缩、重复调用的计数)。
396
+ * 新的一套先在 preparing 里创建(工厂函数这时运行),换会话成功了才 activate;失败了直接 dispose,当前的一套不受影响。
397
+ * 插件的 ctx.status、ctx.input、ctx.send 只在 active 时生效,见 session-scope.ts
398
+ */
399
+ async function prepareScope(mode?: Mode): Promise<SessionScope> {
400
+ const next = new SessionScope({
401
+ showStatus: (plugins) => screen.status({ plugins }),
402
+ input: screen.draft && { text: () => screen.draft!.text(), insert: (t) => screen.draft!.insert(t), set: (t) => screen.draft!.set(t) },
403
+ send: screen.draft && pluginSend,
404
+ warn: (w) => warn([w]),
405
+ tidy: (t) => clip(stripVTControlCharacters(t).replace(/\s+/g, " ").trim(), 40),
406
+ });
407
+ next.attach(await createJade({
337
408
  cwd,
338
409
  home,
339
410
  store,
340
411
  provider,
341
412
  mode,
413
+ model: currentModel,
342
414
  extensions: pluginSources,
343
415
  disabled: disabledPlugins,
344
416
  mcp: mcpClients,
345
417
  skills,
346
418
  compactTokens: compactAt,
419
+ scratch,
347
420
  approveSubagent,
421
+ // 不能交互时(-p)没有人回答,不提供这个工具
422
+ askUser: screen.interactive ? askUser : undefined,
348
423
  sharedRules: (): AllowRule[] => [...settings().rules, ...pendingRules],
349
424
  pendingMode: () => pendingMode,
425
+ // auto 模式的审查用当前的模型;rt 换会话时跟着换,所以每次取
426
+ review: reviewer({ provider, cwd, scratch, messages: () => rt.state.messages }),
350
427
  approveCheck: process.env.JADE_CHECKS === "off" ? undefined : approveCheck,
351
428
  checkConfirmed: (c) => trust.has(checkHash(c)),
352
429
  checksUnavailable: process.env.JADE_CHECKS === "off" ? "Edit-time checks are turned off by JADE_CHECKS=off." : undefined,
353
- });
430
+ ...next.hooks,
431
+ }));
432
+ return next;
433
+ }
354
434
 
355
- let jade: Jade = await makeJade(opts.mode);
356
- for (const w of jade.warnings) screen.log(yellow(`[warning] ${w}`));
435
+ const warn = (list: string[]) => {
436
+ for (const w of list) screen.log(yellow(`[warning] ${w}`));
437
+ };
438
+ if (!hasProvider()) {
439
+ // 第一次运行:插件已经加载,/model 的服务列表里也有插件提供的
440
+ screen.log(bold("Welcome to jade.") + " No model is configured yet; let's set one up.");
441
+ if (!(await configure.provider())) {
442
+ await closePlugins();
443
+ await screen.close();
444
+ process.exit(2);
445
+ }
446
+ } else if (pluginProviderPending) {
447
+ try {
448
+ provider.set(retrying(await providerFromEnv()));
449
+ contextWindow = contextWindowFromEnv();
450
+ } catch (err) {
451
+ // 例如提供这个服务的插件被删掉、停用或者没加载成功:原因在上面插件的警告里
452
+ await providerUnavailable(errorText(err));
453
+ }
454
+ screen.status({ model: modelLabel() });
455
+ }
456
+ /** 会话的开始、离开、换会话、重新加载,见 session-lifecycle.ts */
457
+ const sessions = await SessionLifecycle.prepare<Mode>(
458
+ {
459
+ prepare: prepareScope,
460
+ open: (plugins, id) => (id ? Runtime.resume({ store, provider, plugins, sessionId: id }) : Runtime.create({ store, provider, plugins })),
461
+ discard: (id) => discardIfEmpty(store, id),
462
+ warn,
463
+ error: (err) => screen.log(red(`[error] ${errorText(err)}`)),
464
+ },
465
+ opts.mode,
466
+ );
467
+ /** 当前会话的插件作用域、插件实例、运行时和 id;换会话之后由 adopt 一起换 */
468
+ let scope = sessions.scope;
469
+ let jade: Jade = sessions.jade;
470
+ warn(jade.warnings);
471
+
472
+ /** 选的模型服务用不了:终端界面里直接进 /model 换一个服务,不然用户只能手改 .env;不能交互时报错退出 */
473
+ async function providerUnavailable(message: string): Promise<void> {
474
+ if (tui) {
475
+ screen.log(red(`[error] ${message}`));
476
+ screen.log("Choose another model with /model.");
477
+ if (await configure.provider()) return;
478
+ await closePlugins();
479
+ await screen.close();
480
+ process.exit(2);
481
+ }
482
+ await closePlugins();
483
+ await screen.close();
484
+ fail(message);
485
+ }
486
+ if (badSavedMode) screen.log(yellow(`[warning] JADE_MODE=${badSavedMode} is not a mode (${MODES.join(", ")}); starting in ${opts.mode ?? "ask"}`));
357
487
  for (const c of shadowed) screen.log(yellow(`[warning] custom command ${display(cwd, c.file)} is ignored: /${c.name} is a built-in command`));
358
488
  // 插件的命令加进菜单(名字在各个会话的实例之间不变)。内置命令和 .jade/commands 里的同名命令优先
359
489
  // skill 也可以当命令用:/<skill 名> [要做的事]。内置命令和自定义命令优先
@@ -364,84 +494,40 @@ for (const sk of skills) {
364
494
  skillCommands.set(name, sk);
365
495
  ALL_COMMANDS.push({ name: sk.name, args: "[task]", about: `${clip(sk.description.replace(/\s+/g, " "), 80)} (skill)` });
366
496
  }
367
- // 内置插件的命令排在宿主命令后面;第三方插件的命令排在最后
368
- const builtinPluginCommands: CommandInfo[] = [];
369
- for (const [name, { plugin, command: c, builtin }] of jade.commands) {
370
- if (builtin) {
371
- builtinPluginCommands.push({ name: c.name, args: c.args, about: c.description ?? "" });
372
- continue;
373
- }
374
- if (builtinNames.has(name) || customs.has(name) || skillCommands.has(name)) {
375
- const what = builtinNames.has(name) ? "a built-in command" : customs.has(name) ? "a custom command" : "a skill";
376
- screen.log(yellow(`[warning] command /${c.name} of plugin ${plugin} is ignored: ${what} has that name`));
377
- continue;
378
- }
379
- ALL_COMMANDS.push({ name: c.name, args: c.args, about: `${c.description ?? ""} (plugin ${plugin})`.trim() });
380
- }
381
- ALL_COMMANDS.splice(COMMANDS.length, 0, ...builtinPluginCommands);
497
+ // 内置插件的命令排在宿主命令后面;第三方插件的命令排在最后。同名时谁生效见 pluginMenu
498
+ const menu = pluginMenu(jade.commands, { host: hostNames, custom: customs, skill: skillCommands });
499
+ warn(menu.warnings);
500
+ ALL_COMMANDS.push(...menu.plugins);
501
+ ALL_COMMANDS.splice(COMMANDS.length, 0, ...menu.builtin);
382
502
 
383
- /**
384
- * 第三方插件:$JADE_HOME/plugins/<name>/(用户层)和 .jade/plugins/<name>/(项目层)。
385
- * 项目层的首次加载及内容变化后要用户确认(7.1)。加载失败的跳过并提示,不影响启动
386
- */
387
- async function loadPlugins(): Promise<LoadedPlugin[]> {
388
- const out: LoadedPlugin[] = [];
389
- for (const f of foundPlugins) {
390
- try {
391
- const unsupported = pluginInfos.get(f.dir)?.bundle.unsupported ?? [];
392
- if (unsupported.length) screen.log(dim(`[note] plugin ${f.name}: jade does not support its ${unsupported.join(" and ")} yet; they are ignored`));
393
- out.push(
394
- await loadPlugin(f, {
395
- trust,
396
- confirm: async ({ path: p, hash, files, command }) =>
397
- (await screen.select(
398
- `Project plugin ${display(cwd, p)} is new or changed. Load and run it?`,
399
- [
400
- { label: "No", value: false },
401
- { label: "Yes, load it", value: true },
402
- ],
403
- {
404
- body: dim(
405
- `${command ? `runs: ${command}\n` : ""}sha256 ${hash.slice(0, 12)}, ${files.length} files:\n${files.map((f) => ` ${f}`).join("\n")}`,
406
- ),
407
- },
408
- )) ?? false,
409
- onExit: (p, { code, signal }) => {
410
- if (!pluginsClosing) screen.log(yellow(`[warning] plugin ${p.name} exited (${signal ?? `code ${code}`}); its hooks fail until jade restarts. /plugins shows its stderr`));
411
- },
412
- }),
413
- );
414
- } catch (err) {
415
- const hint = f.layer === "project" && !tui && err instanceof UntrustedPlugin ? " (run jade interactively in this directory once to confirm it)" : "";
416
- screen.log(yellow(`[skipped] plugin ${display(cwd, f.dir)}: ${errorText(err)}${hint}`));
417
- }
418
- }
419
- return out;
420
- }
421
-
422
- /** 结束进程外插件的进程 */
503
+ /** 结束进程外插件的进程和 MCP 服务 */
423
504
  async function closePlugins() {
424
505
  pluginsClosing = true;
425
- await Promise.all([...pluginSources.map((p) => p.close?.().catch(() => {})), ...mcpClients.map((c) => c.close().catch(() => {}))]);
506
+ await Promise.all([plugins.close(), ...mcpClients.map((c) => c.close().catch(() => {}))]);
426
507
  }
427
508
 
428
509
  /**
429
510
  * 连接 mcp.json 里配置的 MCP 服务。项目层(随仓库分发)的服务第一次启动前要用户确认,按配置内容记在 trust.jsonl;
430
- * 连不上的跳过并提示,不影响启动。所有服务并发连接
511
+ * 连不上的跳过并提示,不影响启动。所有服务并发连接,不用确认的立即开始连。
512
+ * 启动时最多等 MCP_STARTUP_WAIT_MS:还没连上的在后台接着连,它们的工具从下一个会话(/clear)开始提供
513
+ * (一个会话里的工具列表不变,否则提示缓存失效)。
514
+ * dialogsAfter:在它完成之后才弹确认框,不和插件的确认框同时出现
431
515
  */
432
- async function connectMcp(): Promise<McpClient[]> {
433
- const plugins = foundPlugins.flatMap((f) => {
434
- const mcp = pluginInfos.get(f.dir)?.bundle.mcp;
435
- return mcp ? [{ plugin: f.name, dir: f.dir, layer: f.layer, file: mcp.file, servers: mcp.servers }] : [];
516
+ async function connectMcp(dialogsAfter: Promise<unknown>): Promise<McpClient[]> {
517
+ const carried = plugins.plugins.flatMap((f) => {
518
+ const mcp = f.info.bundle.mcp;
519
+ return mcp ? [{ plugin: f.id, dir: f.dir, layer: f.layer, file: mcp.file, servers: mcp.servers }] : [];
436
520
  });
437
- const { servers, warnings } = await loadMcpConfig({ home, root: repo, cwd: realPath(cwd), plugins });
521
+ const { servers, warnings } = await loadMcpConfig({ home, root: repo, cwd: realPath(cwd), plugins: carried });
438
522
  for (const w of warnings) screen.log(yellow(`[warning] ${w}`));
439
523
  const clients: McpClient[] = [];
524
+ const connecting: Promise<unknown>[] = [];
440
525
  for (const entry of servers) {
441
526
  if (entry.config.disabled) continue;
442
527
  if (entry.layer === "project") {
443
528
  const hash = mcpTrustHash(repo, entry);
444
529
  if (!(await trust.has(hash))) {
530
+ if (tui) await dialogsAfter.catch(() => {});
445
531
  const ok = tui
446
532
  ? ((await screen.select(
447
533
  `MCP server "${entry.name}" from ${display(cwd, entry.file)} is new or changed. Start it?`,
@@ -459,21 +545,31 @@ async function connectMcp(): Promise<McpClient[]> {
459
545
  await trust.add({ hash, path: entry.file, at: new Date().toISOString() });
460
546
  }
461
547
  }
462
- clients.push(
463
- new McpClient(entry, {
464
- cwd,
465
- onDisconnect: (c, why) => {
466
- if (!pluginsClosing) screen.log(yellow(`[warning] MCP server ${c.name} disconnected: ${why}. jade reconnects on its next tool call; /mcp shows details`));
467
- },
468
- }),
469
- );
548
+ const client = new McpClient(entry, {
549
+ cwd,
550
+ onDisconnect: (c, why) => {
551
+ if (!pluginsClosing) screen.log(yellow(`[warning] MCP server ${c.name} disconnected: ${why}. jade reconnects on its next tool call; /mcp shows details`));
552
+ },
553
+ });
554
+ clients.push(client);
555
+ connecting.push(client.connect().catch((err) => screen.log(yellow(`[warning] MCP server ${client.name} is unavailable: ${errorText(err)}`))));
470
556
  }
471
557
  if (clients.length === 0) return clients;
472
558
  screen.busy(`Connecting to ${clients.length} MCP server${clients.length > 1 ? "s" : ""}`);
473
- await Promise.all(
474
- clients.map((c) => c.connect().catch((err) => screen.log(yellow(`[warning] MCP server ${c.name} is unavailable: ${errorText(err)}`)))),
475
- );
559
+ const all = Promise.all(connecting);
560
+ // 不能交互时(-p)只运行这一次,没有"下一个会话",照常等到每个服务连上或超时
561
+ let timer: ReturnType<typeof setTimeout> | undefined;
562
+ if (tui) await Promise.race([all, new Promise<void>((resolve) => (timer = setTimeout(resolve, MCP_STARTUP_WAIT_MS)))]);
563
+ else await all;
564
+ clearTimeout(timer);
476
565
  screen.busy(undefined);
566
+ for (const c of clients.filter((x) => x.status === "connecting")) {
567
+ screen.log(dim(`[MCP server ${c.name} is still starting; its tools are available from the next session (/clear) once it is connected]`));
568
+ void c.connect().then(
569
+ () => screen.log(dim(`[MCP server ${c.name} connected; its tools are available from the next session (/clear)]`)),
570
+ () => {},
571
+ );
572
+ }
477
573
  return clients;
478
574
  }
479
575
 
@@ -484,7 +580,7 @@ if (resumeId === "") {
484
580
  fail("--resume without an id needs a terminal to pick from; pass the id");
485
581
  }
486
582
  resumeId = await pickSession();
487
- } else if (resumeId) resumeId = await findSession(resumeId);
583
+ } else if (resumeId) resumeId = matchSession(await index.list(cwd), resumeId);
488
584
  if (opts.cont) {
489
585
  resumeId = (await index.list(cwd))[0]?.id;
490
586
  if (!resumeId) {
@@ -494,21 +590,40 @@ if (opts.cont) {
494
590
  }
495
591
 
496
592
  // /clear 换成新的运行时和会话
497
- let rt = resumeId
498
- ? await Runtime.resume({ store, provider, plugins: jade.plugins, sessionId: resumeId })
499
- : await Runtime.create({ store, provider, plugins: jade.plugins });
500
- let sessionId = rt.state.sessionId;
593
+ let rt!: Runtime;
594
+ let sessionId!: string;
595
+ function adopt(c: Current) {
596
+ scope = c.scope;
597
+ jade = c.jade;
598
+ rt = c.rt;
599
+ sessionId = c.sessionId;
600
+ }
601
+ adopt(await sessions.begin(resumeId));
501
602
 
502
603
  // 权限设置记在日志里(derived),关卡从那里读,恢复会话后仍然有效
503
- const settings = (): PolicySettings => jade.policy.settings(rt.state.derived);
604
+ // 主会话不会是 readonly(只给子 Agent 用;旧会话里记的 readonly 由关卡换成 plan)
605
+ // 只取这一项:rt.state 每次都拷贝整段历史,而这里调用得很频繁(子 Agent 的每次关卡判断都会调用)
606
+ const settings = () => jade.policy.settings({ [POLICY_KEY]: rt.derived(POLICY_KEY) }) as PolicySettings & { mode: Mode };
504
607
  const saveSettings = async (next: PolicySettings) => {
505
608
  await rt.record(POLICY_KEY, next);
506
609
  pendingMode = undefined;
507
610
  screen.status({ mode: next.mode });
508
611
  };
509
612
 
613
+ /**
614
+ * 用户切换的模式记进 $JADE_HOME/.env 的 JADE_MODE,之后新开的会话默认用它(恢复的会话仍用它自己记下的模式)。
615
+ * yolo 不记:免得以后一打开就什么都不问;要默认 yolo 可以手动写 JADE_MODE=yolo 或用 -m yolo
616
+ */
617
+ async function rememberMode(mode: Mode) {
618
+ if (mode === "yolo" || process.env.JADE_MODE === mode) return;
619
+ await updateEnvFile(envFile, { JADE_MODE: mode }).catch((err) =>
620
+ screen.log(yellow(`[warning] could not remember the mode in ${envFile}: ${errorText(err)}`)),
621
+ );
622
+ }
623
+
510
624
  /** 换权限模式;运行时正在执行这一轮时先记在 pendingMode,关卡立即按它判断,这一轮结束后再写进日志 */
511
625
  async function setMode(mode: Mode) {
626
+ await rememberMode(mode);
512
627
  try {
513
628
  await saveSettings({ ...settings(), mode });
514
629
  } catch (err) {
@@ -530,24 +645,27 @@ async function flushPendingMode() {
530
645
 
531
646
  // ---------- 渲染 ----------
532
647
 
533
- const view = transcript({ screen, cwd, store, contextWindow: () => contextWindow, compactAt: () => compactAt(), canRetry: () => canRetry() });
648
+ const view = transcript({ screen, cwd, store, contextWindow: () => contextWindow, compactAt: () => compactAt(), canRetry: () => canRetry(), renderer: (tool) => jade.renderers.get(tool) });
534
649
  rt.subscribe(view.onNotice);
535
650
 
536
- const percent = (part: number, whole: number) => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "—");
537
-
538
651
  // ---------- 审批 ----------
539
652
 
540
- type Call = { toolUseId: string; name: string; input: unknown };
653
+ type Call = { toolUseId: string; name: string; input: unknown; reason?: string };
541
654
 
542
- /** 问用户是否允许一个调用;选了"总是允许"时交给 remember 记下规则 */
543
- async function ask(c: Call, who: string, remember: (rule: AllowRule) => Promise<void> | void): Promise<SubagentApproval> {
544
- const head = `${c.name}(${summarize(cwd, c.name, c.input)})`;
655
+ /**
656
+ * 问用户是否允许一个调用;选了"总是允许"时交给 remember 记下规则。
657
+ * signal 中止时(例如中断了子 Agent)关掉对话框并抛出
658
+ */
659
+ async function ask(c: Call, who: string, remember: (rule: AllowRule) => Promise<void> | void, signal?: AbortSignal): Promise<SubagentApproval> {
660
+ const head = `${c.name}(${view.summary(c.name, c.input)})`;
545
661
  if (!screen.interactive) {
546
662
  screen.log(red(`✗ ${who}${head} denied: not running interactively`));
547
663
  return { approved: false, reason: "The user is not available to approve this action." };
548
664
  }
549
665
  const rule = jade.policy.ruleFor(c);
550
666
  const always = rule.command !== undefined ? "this exact command" : describeRule(rule);
667
+ // 关卡给了理由的(例如 auto 模式下审查转给用户的),说明为什么要问
668
+ const body = (c.reason ? `${yellow(c.reason)}\n\n` : "") + (await view.preview(c));
551
669
  const answer = await screen.select(
552
670
  `Allow ${who}${head}?`,
553
671
  [
@@ -555,15 +673,20 @@ async function ask(c: Call, who: string, remember: (rule: AllowRule) => Promise<
555
673
  { label: `Yes, and always allow ${always} in this session`, value: "always" as const },
556
674
  { label: "No, and tell jade what to do instead", value: "no" as const },
557
675
  ],
558
- { body: await preview(c, cwd) },
676
+ { body, signal },
559
677
  );
678
+ signal?.throwIfAborted();
560
679
  if (answer === "always") await remember(rule);
561
680
  const approved = answer === "yes" || answer === "always";
562
- const reason = approved
563
- ? undefined
564
- : (answer === "no" ? await screen.input("What should jade do instead? (optional)") : undefined) || "The user rejected this action.";
681
+ const said = answer === "no" ? (await screen.input("What should jade do instead? (optional)", { signal }))?.trim() : undefined;
682
+ signal?.throwIfAborted();
683
+ // 带上"用户拒绝了"这层前提,否则模型可能把用户的话当成命令的输出
684
+ const reason = approved ? undefined : said ? `The user rejected this action and said: ${said}` : "The user rejected this action.";
565
685
  // 主 Agent 的调用的结果之后接在这一行后面
566
- screen.log(approved ? green(`✓ ${who}${head}`) : red(`✗ ${who}${head}`) + dim(reason ? ` — ${clip(reason, 200)}` : ""), { id: c.toolUseId });
686
+ screen.log((approved ? green(`✓ ${who}${head}`) : red(`✗ ${who}${head}`)) + dim(reason ? ` — ${clip(reason, 200)}` : ""), {
687
+ id: c.toolUseId,
688
+ details: view.details(c.name, c.input),
689
+ });
567
690
  return { approved, reason };
568
691
  }
569
692
 
@@ -590,15 +713,42 @@ let subagentAsking: Promise<unknown> = Promise.resolve();
590
713
  function approveSubagent(...[c, signal]: Parameters<ApproveSubagent>): Promise<SubagentApproval> {
591
714
  const turn = subagentAsking.then(() => {
592
715
  signal.throwIfAborted();
593
- // 中断时不再等用户回答;对话框由用户自己关掉
594
- return abortable(ask(c, "sub-agent ", (rule) => void pendingRules.push(rule)), signal);
716
+ // 中断时不再等用户回答,对话框和插件那边的请求一起关掉
717
+ return ask(c, "sub-agent ", (rule) => void pendingRules.push(rule), signal);
595
718
  });
596
719
  subagentAsking = turn.catch(() => {});
597
720
  return turn;
598
721
  }
599
722
 
723
+ /** ask_user:逐个问题让用户选一项,或者选"其他"自己输入;任何一个问题取消就算没有回答。signal 中止时关掉对话框并抛出 */
724
+ async function askUser(questions: Question[], signal: AbortSignal): Promise<string[] | undefined> {
725
+ if (!screen.interactive) return undefined;
726
+ const OTHER = -1;
727
+ // 和子 Agent 的审批轮流问,不同时弹两个对话框
728
+ const run = subagentAsking.then(async () => {
729
+ const answers: string[] = [];
730
+ for (const [i, q] of questions.entries()) {
731
+ const title = questions.length > 1 ? `${q.question} (${i + 1}/${questions.length})` : q.question;
732
+ const choice = await screen.select(
733
+ title,
734
+ [...q.options.map((o, k) => ({ label: o.label, value: k, hint: o.description })), { label: "Other (type your answer)", value: OTHER }],
735
+ { signal },
736
+ );
737
+ const answer = choice === undefined ? undefined : choice === OTHER ? (await screen.input(q.question, { signal }))?.trim() : q.options[choice]!.label;
738
+ signal.throwIfAborted();
739
+ if (!answer) return undefined;
740
+ answers.push(answer);
741
+ screen.log(dim(` ${q.question} → `) + answer);
742
+ }
743
+ return answers;
744
+ });
745
+ subagentAsking = run.catch(() => {});
746
+ return run;
747
+ }
748
+
600
749
  /** 编辑后检查的确认记录:同一个目录里的同一条命令只问一次,记在 trust.jsonl */
601
750
  const checkHash = (c: Check) => createHash("sha256").update(`jade-check\0${c.cwd}\0${c.command}`).digest("hex");
751
+ const confirmedChecks = new Set<string>();
602
752
 
603
753
  /**
604
754
  * 编辑后检查的命令第一次运行前问用户:它会执行仓库里的代码(node_modules 里的 tsc、配置里的命令)。
@@ -606,7 +756,12 @@ const checkHash = (c: Check) => createHash("sha256").update(`jade-check\0${c.cwd
606
756
  */
607
757
  async function approveCheck(c: Check, signal: AbortSignal): Promise<boolean> {
608
758
  const hash = checkHash(c);
609
- if (await trust.has(hash)) return true;
759
+ // 每批修改都会问一次:确认过的记在内存里,不用每次重读、解析整份 trust.jsonl
760
+ if (confirmedChecks.has(hash)) return true;
761
+ if (await trust.has(hash)) {
762
+ confirmedChecks.add(hash);
763
+ return true;
764
+ }
610
765
  if (settings().mode === "yolo") return true;
611
766
  if (!screen.interactive) return false;
612
767
  const run = subagentAsking.then(() => {
@@ -625,8 +780,10 @@ async function approveCheck(c: Check, signal: AbortSignal): Promise<boolean> {
625
780
  });
626
781
  subagentAsking = run.catch(() => {});
627
782
  const ok = (await run) ?? false;
628
- if (ok) await trust.add({ hash, path: c.cwd, at: new Date().toISOString() });
629
- else screen.log(dim(`[${c.name} will not run in this session; /checks on to ask again]`));
783
+ if (ok) {
784
+ await trust.add({ hash, path: c.cwd, at: new Date().toISOString() });
785
+ confirmedChecks.add(hash);
786
+ } else screen.log(dim(`[${c.name} will not run in this session; /checks on to ask again]`));
630
787
  return ok;
631
788
  }
632
789
 
@@ -636,8 +793,10 @@ function skillMessage(name: string, args: string): string {
636
793
  return `Use the "${name}" skill${args.trim() ? ` for this: ${args.trim()}` : "."}`;
637
794
  }
638
795
 
639
- /** 正在执行的插件命令;esc 中断它 */
640
- let commandAbort: AbortController | undefined;
796
+ /** 正在执行的插件命令;esc 中断它们。instant 的命令可以在另一个命令的模型回合里执行,所以可能同时有几个 */
797
+ const commandAborts = new Set<AbortController>();
798
+ /** 插件命令经 session 发起的换会话、重试:命令被 esc 中断后也要等它收尾,再处理下一条输入 */
799
+ let sessionWork: Promise<unknown> | undefined;
641
800
 
642
801
  /** 执行插件的斜杠命令,返回要发给模型的提示词(没有就是 undefined) */
643
802
  async function pluginCommand(name: string, args: string): Promise<string | undefined> {
@@ -647,7 +806,7 @@ async function pluginCommand(name: string, args: string): Promise<string | undef
647
806
  return undefined;
648
807
  }
649
808
  const ac = new AbortController();
650
- commandAbort = ac;
809
+ commandAborts.add(ac);
651
810
  try {
652
811
  const result = await abortable(
653
812
  Promise.resolve(
@@ -663,6 +822,8 @@ async function pluginCommand(name: string, args: string): Promise<string | undef
663
822
  input: (title, o) => screen.input(title, o),
664
823
  },
665
824
  note: (text) => void notes.push(text),
825
+ // instant 的命令在模型工作时执行,不能换会话、写日志
826
+ session: found.command.instant ? undefined : sessionControl(found.plugin),
666
827
  }),
667
828
  ),
668
829
  ac.signal,
@@ -681,13 +842,40 @@ async function pluginCommand(name: string, args: string): Promise<string | undef
681
842
  }
682
843
  return undefined;
683
844
  } catch (err) {
684
- screen.log(red(`[error] /${found.command.name} (plugin ${found.plugin}): ${errorText(err)}`));
845
+ // 用户按 esc 中断的不算出错
846
+ if (!ac.signal.aborted) screen.log(red(`[error] /${found.command.name} (plugin ${found.plugin}): ${errorText(err)}`));
685
847
  return undefined;
686
848
  } finally {
687
- if (commandAbort === ac) commandAbort = undefined;
849
+ // instant 的命令没有 session,不会发起 sessionWork;运行中的是别的命令发起的,不能替它等、替它清掉
850
+ if (!found.command.instant) {
851
+ await sessionWork?.catch(() => {});
852
+ sessionWork = undefined;
853
+ }
854
+ commandAborts.delete(ac);
688
855
  }
689
856
  }
690
857
 
858
+ /** 插件命令操作会话的接口;换会话后指向新的会话(rt、sessionId 每次现取) */
859
+ function sessionControl(plugin: string): SessionControl {
860
+ const track = <T>(p: Promise<T>): Promise<T> => ((sessionWork = p), p);
861
+ return {
862
+ messages: () => structuredClone(rt.state.messages),
863
+ record: async (key, value) => {
864
+ if (key !== plugin && !key.startsWith(`${plugin}/`)) throw new Error(`plugin ${plugin} can only record keys "${plugin}" or "${plugin}/…", not ${JSON.stringify(key)}`);
865
+ await rt.record(key, value);
866
+ },
867
+ list: async () => (await index.list(cwd)).map(({ id, title, at }) => ({ id, title, at })),
868
+ clear: () => track(switchSession()),
869
+ reload: () => track(reloadSession()),
870
+ resume: (id) => track(switchSession(id)),
871
+ retry: async () => {
872
+ if (!canRetry()) return false;
873
+ await track(drive({ kind: "retry" }));
874
+ return true;
875
+ },
876
+ };
877
+ }
878
+
691
879
  /** /plugins:内置插件的状态,每个第三方插件的来源、工具、hook、命令和带的内容;跳过的插件在启动时已经提示过 */
692
880
  function showPlugins() {
693
881
  const width = Math.max(...jade.builtins.map((b) => b.id.length)) + 2;
@@ -703,24 +891,29 @@ function showPlugins() {
703
891
  }
704
892
  const carried = (b: PluginBundle) =>
705
893
  [b.skills.length ? "skills" : "", b.commands.length ? "commands" : "", b.mcp ? "MCP servers" : ""].filter(Boolean).join(", ");
706
- for (const { source, plugin } of jade.extensions) {
894
+ for (const { source, plugin, commands, keys } of jade.extensions) {
707
895
  const exit = source.process?.exited;
708
896
  const state = source.kind === "process" ? (exit ? red(` exited (${exit.signal ?? `code ${exit.code}`})`) : green(" running")) : "";
709
897
  lines.push(`${bold(plugin.id)} ${plugin.version} ${dim(`${source.layer} · ${display(cwd, source.dir)} · ${source.kind === "process" ? `runs ${source.entry}` : source.entry}`)}${state}`);
710
898
  const tools = (plugin.tools ?? []).map((t) => `${t.name} (${t.effect})`);
711
899
  const hooks = [...new Set((plugin.hooks ?? []).map((h) => `${h.kind}:${h.point}`))];
712
- const cmds = (plugin.commands ?? []).map((c) => `/${c.name}`);
900
+ const cmds = commands.map((c) => `/${c.name}`);
713
901
  if (tools.length) lines.push(` tools ${tools.join(", ")}`);
714
902
  if (hooks.length) lines.push(` hooks ${hooks.join(", ")}`);
715
903
  if (cmds.length) lines.push(` commands ${cmds.join(", ")}`);
716
- if (plugin.replaces?.length) lines.push(` replaces ${plugin.replaces.join(", ")}`);
904
+ if (keys.length) lines.push(` keys ${keys.map((k) => k.key).join(", ")}`);
905
+ if (source.info.replaces?.length) lines.push(` replaces ${source.info.replaces.join(", ")}`);
717
906
  if (carried(source.info.bundle)) lines.push(` carries ${carried(source.info.bundle)}`);
718
907
  if (exit && source.process!.stderr.length) lines.push(dim(source.process!.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
719
908
  }
720
909
  for (const p of contentOnly) {
721
- lines.push(`${bold(p.info.name ?? p.name)}${p.info.version ? ` ${p.info.version}` : ""} ${dim(`${p.layer} · ${display(cwd, p.dir)}`)}`);
910
+ lines.push(`${bold(p.id)}${p.info.version ? ` ${p.info.version}` : ""} ${dim(`${p.layer} · ${display(cwd, p.dir)}`)}`);
722
911
  lines.push(` carries ${carried(p.info.bundle)}`);
723
912
  }
913
+ lines.push("", bold("Hook execution order"));
914
+ 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"]) {
915
+ lines.push(` ${p.padEnd(16)} ${rt.hookOrder(p).join(" → ") || dim("(none)")}`);
916
+ }
724
917
  screen.log(lines.join("\n"));
725
918
  }
726
919
 
@@ -730,9 +923,11 @@ async function savePendingRules() {
730
923
  await saveSettings({ ...s, rules: [...s.rules, ...pendingRules.splice(0)] });
731
924
  }
732
925
 
926
+ /** p 和 signal 谁先结束用谁:signal 中止时以它的 reason 拒绝 */
733
927
  function abortable<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
734
928
  return new Promise((resolve, reject) => {
735
929
  const stop = () => reject(signal.reason);
930
+ if (signal.aborted) return stop();
736
931
  signal.addEventListener("abort", stop, { once: true });
737
932
  p.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
738
933
  });
@@ -774,7 +969,7 @@ function interrupt() {
774
969
  const again = interruptPending || Date.now() - interruptedAt < SECOND_ESC_MS;
775
970
  interruptedAt = Date.now();
776
971
  interruptPending = true;
777
- commandAbort?.abort(new Error("interrupted by user"));
972
+ for (const ac of commandAborts) ac.abort(new Error("interrupted by user"));
778
973
  rt.abort("interrupted by user");
779
974
  screen.busy("Interrupting");
780
975
  if (queue.length === 0) return;
@@ -791,15 +986,8 @@ function interrupt() {
791
986
  * 离开会话但保留它:写入 session.detached,插件的收尾写入完成后再退出(4.2)。
792
987
  * 没收到过输入的会话没什么可恢复的,删掉它的日志;返回会话是否保留了下来
793
988
  */
794
- async function leave(): Promise<boolean> {
795
- jade.shutdown();
796
- try {
797
- await rt.detach();
798
- return !(await discardIfEmpty(store, sessionId));
799
- } catch (err) {
800
- screen.log(red(`[error] ${errorText(err)}`));
801
- return true;
802
- }
989
+ function leave(): Promise<boolean> {
990
+ return sessions.leave();
803
991
  }
804
992
 
805
993
  /** 关掉界面后再提示怎么恢复:终端界面退出备用屏幕后,里面的内容就看不到了 */
@@ -816,6 +1004,7 @@ async function quit(code = 0) {
816
1004
  // 中断后等这一轮收尾,再写 session.detached;pump 看到 quitting 就不再取排队的输入
817
1005
  await work?.catch(() => {});
818
1006
  await leave();
1007
+ await sessions.settled();
819
1008
  await closePlugins();
820
1009
  await closeScreen();
821
1010
  process.exit(code);
@@ -828,23 +1017,16 @@ async function quit(code = 0) {
828
1017
  */
829
1018
  async function switchSession(id?: string) {
830
1019
  await flushPendingMode();
831
- const mode = settings().mode;
832
- const next = await makeJade(mode);
833
- let nextRt: Runtime;
1020
+ let switched: { previous: string; kept: boolean };
834
1021
  try {
835
- nextRt = id
836
- ? await Runtime.resume({ store, provider, plugins: next.plugins, sessionId: id })
837
- : await Runtime.create({ store, provider, plugins: next.plugins });
1022
+ switched = await sessions.switchTo(id, settings().mode);
838
1023
  } catch (err) {
839
- next.shutdown();
840
- return screen.log(red(`[error] could not resume ${id}: ${errorText(err)}`));
1024
+ // 已经回滚:留在当前会话
1025
+ return screen.log(red(`[error] ${id ? `could not resume ${id}` : "could not start a new session"}: ${errorText(err)}`));
841
1026
  }
842
- const kept = await leave();
843
- const old = sessionId;
844
- jade = next;
845
- rt = nextRt;
1027
+ const { previous: old, kept } = switched;
1028
+ adopt(sessions.current);
846
1029
  rt.subscribe(view.onNotice);
847
- sessionId = rt.state.sessionId;
848
1030
  view.reset();
849
1031
  notes.length = 0;
850
1032
  announcedMode = undefined;
@@ -858,9 +1040,35 @@ async function switchSession(id?: string) {
858
1040
  }
859
1041
  }
860
1042
 
861
- /** 从这个目录最近的会话里选一个;取消或没有时返回 undefined */
862
- async function pickSession(current?: string): Promise<string | undefined> {
863
- const all = (await index.list(cwd)).filter((s) => s.id !== current).slice(0, 50);
1043
+ /**
1044
+ * 用新的插件实例继续当前会话:工具和系统提示词按现在的配置重新生成(例如 /search 改了搜索服务),对话内容不变。
1045
+ * 只在空闲时调用:插件命令的 session.reload(instant 命令没有 session)
1046
+ */
1047
+ async function reloadSession() {
1048
+ await flushPendingMode();
1049
+ let error: unknown;
1050
+ try {
1051
+ ({ error } = await sessions.reload(settings().mode));
1052
+ } catch (err) {
1053
+ // 没换成新的插件实例时(prepare 失败)当前会话照常;已经离开当前会话、新会话也开不了时,只能等用户再试
1054
+ if (!sessions.left) throw err;
1055
+ screen.log(red(`[error] could not reload the session or start a new one: ${errorText(err)}`));
1056
+ screen.log("Use /clear or /resume to continue.");
1057
+ return;
1058
+ }
1059
+ adopt(sessions.current);
1060
+ if (error !== undefined) {
1061
+ screen.log(red(`[error] could not reload the session: ${errorText(error)}; starting a new one`));
1062
+ view.reset();
1063
+ screen.status({ session: sessionId });
1064
+ }
1065
+ rt.subscribe(view.onNotice);
1066
+ await guarded(() => rt.recover());
1067
+ }
1068
+
1069
+ /** 从这个目录最近的会话里选一个(-r 不带 id 时);取消或没有时返回 undefined */
1070
+ async function pickSession(): Promise<string | undefined> {
1071
+ const all = (await index.list(cwd)).slice(0, 50);
864
1072
  if (all.length === 0) {
865
1073
  screen.log(dim(`No other sessions in ${shortPath(cwd)}.`));
866
1074
  return undefined;
@@ -871,23 +1079,6 @@ async function pickSession(current?: string): Promise<string | undefined> {
871
1079
  );
872
1080
  }
873
1081
 
874
- /** 这个目录的会话里 id 等于 arg 或以它开头的唯一一个;都不是时原样返回,交给 Runtime.resume 去找 */
875
- async function findSession(arg: string): Promise<string> {
876
- const hits = (await index.list(cwd)).filter((s) => s.id.startsWith(arg));
877
- return hits.find((s) => s.id === arg)?.id ?? (hits.length === 1 ? hits[0]!.id : arg);
878
- }
879
-
880
- /** 显示用的相对时间 */
881
- function ago(iso: string): string {
882
- const s = (Date.now() - Date.parse(iso)) / 1000;
883
- if (!Number.isFinite(s)) return iso;
884
- if (s < 60) return "just now";
885
- if (s < 3600) return `${Math.floor(s / 60)} min ago`;
886
- if (s < 86400) return `${Math.floor(s / 3600)} h ago`;
887
- if (s < 86400 * 7) return `${Math.floor(s / 86400)} d ago`;
888
- return iso.slice(0, 10);
889
- }
890
-
891
1082
  process.on("SIGINT", () => (running ? interrupt() : void quit(130)));
892
1083
 
893
1084
  /** guarded 里最近一次抛出的错误;每次 guarded 开始时清掉 */
@@ -926,10 +1117,10 @@ function announceMode() {
926
1117
  announcedMode = mode;
927
1118
  }
928
1119
 
929
- /** Shift+Tab:ask → auto-edit → plan → ask;yolo、readonly 也回到 ask。运行中也能切换,从下一个工具调用起生效 */
930
- const CYCLE: Mode[] = ["ask", "auto-edit", "plan"];
1120
+ /** Shift+Tab:ask → auto → plan → ask;yolo 也回到 ask。运行中也能切换,从下一个工具调用起生效 */
1121
+ const CYCLE: Mode[] = ["ask", "auto", "plan"];
931
1122
  function cycleMode() {
932
- const i = CYCLE.indexOf(settings().mode);
1123
+ const i = CYCLE.indexOf(settings().mode as Mode);
933
1124
  setMode(CYCLE[(i + 1) % CYCLE.length]!).catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
934
1125
  }
935
1126
 
@@ -943,11 +1134,12 @@ async function offerPlan() {
943
1134
  const last = rt.state.messages.at(-1);
944
1135
  if (last?.role !== "assistant" || !last.content.some((b) => b.kind === "text" && b.text.trim())) return;
945
1136
  const choice = await screen.select("Execute this plan?", [
946
- { label: "Yes, and auto-accept edits", value: "auto-edit" as const, hint: "mode auto-edit" },
1137
+ { label: "Yes, in auto mode", value: "auto" as const, hint: "edits and safe commands run without asking" },
947
1138
  { label: "Yes, and ask before each edit", value: "ask" as const, hint: "mode ask" },
948
1139
  { label: "No, keep planning", value: "plan" as const, hint: "type what to change" },
949
1140
  ]);
950
1141
  if (!choice || choice === "plan") return;
1142
+ await rememberMode(choice);
951
1143
  await saveSettings({ ...settings(), mode: choice });
952
1144
  screen.log(dim(`mode: ${choice}`));
953
1145
  await say("The plan is approved. Implement it now.");
@@ -974,15 +1166,36 @@ async function say(text: string) {
974
1166
  await offerPlan();
975
1167
  }
976
1168
 
977
- /** 上一轮在模型回复之前就失败了:最后一条消息还没有回复 */
978
- const canRetry = () => rt.state.phase === "idle" && rt.state.messages.at(-1)?.role === "user";
1169
+ /**
1170
+ * 插件的快捷键:找到了就在后台执行,返回 true。同一个键可以同时执行几次(例如按一下开始录音、再按一下结束);
1171
+ * signal 是当前作用域的,换会话、重新加载、退出时全部中止,卡住的插件积压的请求也就到此为止
1172
+ */
1173
+ function pluginKey(spec: string): boolean {
1174
+ const found = jade.keys.get(spec);
1175
+ if (!found) return false;
1176
+ const signal = scope.signal;
1177
+ Promise.resolve()
1178
+ .then(() => found.key.run({ key: spec, sessionId, signal }))
1179
+ .catch((err) => {
1180
+ if (!signal.aborted) screen.log(yellow(`[warning] plugin ${found.plugin}: ${spec} failed: ${errorText(err)}`));
1181
+ });
1182
+ return true;
1183
+ }
979
1184
 
980
- async function retry() {
981
- if (!canRetry()) return screen.log(dim("Nothing to retry: the last message already has a reply."));
982
- await drive({ kind: "retry" });
1185
+ /** 插件的 ctx.send:和用户在输入框里提交一样,先注明是哪个插件发的 */
1186
+ function pluginSend(plugin: string, text: string) {
1187
+ if (typeof text !== "string" || !text.trim()) return;
1188
+ screen.log(dim(`[plugin ${plugin} sent this for you]`));
1189
+ if (ready) onSubmit(text);
1190
+ else early.push(text);
983
1191
  }
984
1192
 
1193
+ /** 上一轮在模型回复之前就失败了:最后一条消息还没有回复 */
1194
+ const canRetry = () => rt.phase === "idle" && rt.state.messages.at(-1)?.role === "user";
1195
+
985
1196
  async function drive(input: UserInput) {
1197
+ // 重新加载失败后没有可用的会话(见 reloadSession)
1198
+ if (sessions.left) return screen.log(red("[error] there is no open session. Use /clear or /resume to continue."));
986
1199
  // 计时从这次输入开始,不接着上一条排队消息的
987
1200
  screen.busy(undefined);
988
1201
  screen.busy("Working");
@@ -1006,42 +1219,6 @@ async function drive(input: UserInput) {
1006
1219
  await savePendingRules().catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
1007
1220
  }
1008
1221
 
1009
- /** 撤销最近一轮里还没撤销的全部文件修改:同一个文件改过几次的,恢复到这一轮改它之前的样子 */
1010
- async function undo() {
1011
- const undone = new Set((rt.state.derived[UNDO_KEY] as UndoState | undefined)?.undone ?? []);
1012
- const cps = lastTurnChanges(rt.state.messages, await jade.checkpoints.list(sessionId), undone);
1013
- if (cps.length === 0) return screen.log(dim("Nothing to undo."));
1014
- /** 文件 → 这一轮最早的快照(恢复成它的 before);cps 是最新的在前 */
1015
- const files = new Map<string, Checkpoint>();
1016
- for (const cp of cps) files.set(cp.path, cp);
1017
- // 只有最新一次写入之后的内容能和文件现在的样子比较
1018
- const latest = new Map<string, Checkpoint>();
1019
- for (const cp of cps) if (!latest.has(cp.path)) latest.set(cp.path, cp);
1020
- const changed: string[] = [];
1021
- for (const cp of latest.values()) if (!(await jade.checkpoints.unchangedSince(cp))) changed.push(display(cwd, cp.path));
1022
- const list = [...files.values()].map((cp) => ` ${cp.before === null ? "delete " : "restore"} ${display(cwd, cp.path)}`).join("\n");
1023
- if (files.size > 1 || changed.length > 0) {
1024
- const ok = await screen.select(
1025
- changed.length > 0
1026
- ? `${changed.join(", ")} changed since the agent wrote ${changed.length > 1 ? "them" : "it"}. Undo anyway and discard those changes too?`
1027
- : `Undo the agent's last turn of changes (${files.size} files)?`,
1028
- [
1029
- { label: "No", value: false },
1030
- { label: changed.length > 0 ? "Yes, undo anyway" : "Yes, undo", value: true },
1031
- ],
1032
- { body: list },
1033
- );
1034
- if (!ok) return;
1035
- }
1036
- for (const cp of cps) await jade.checkpoints.restore(cp);
1037
- await rt.record(UNDO_KEY, { undone: [...undone, ...cps.map((c) => c.toolUseId)] } satisfies UndoState);
1038
- const what = [...files.values()].map((cp) =>
1039
- cp.before === null ? `deleted ${display(cwd, cp.path)} (you had created it)` : `restored ${display(cwd, cp.path)} to its content before your changes`,
1040
- );
1041
- notes.push(`The user undid your changes from your last turn: ${what.join("; ")}. Read these files again before changing them.`);
1042
- screen.log(green(`Undid ${cps.length} change${cps.length > 1 ? "s" : ""} from the last turn:`) + "\n" + dim(list));
1043
- }
1044
-
1045
1222
  /** 恢复的会话里已有的内容:终端界面里重新显示对话,逐行输出时只统计用量 */
1046
1223
  async function replayHistory() {
1047
1224
  await view.replay(await readAll(store, sessionId), tui);
@@ -1072,7 +1249,6 @@ async function resumeSession(): Promise<boolean> {
1072
1249
  return true;
1073
1250
  }
1074
1251
 
1075
- /** /memory:不带参数时列出记忆,可以删掉一条或新加一条;带参数时记下这段话 */
1076
1252
  // ---------- 命令 ----------
1077
1253
 
1078
1254
 
@@ -1085,6 +1261,8 @@ async function command(input: string): Promise<boolean> {
1085
1261
  case "help":
1086
1262
  screen.log(ALL_COMMANDS.map((c) => `${`/${c.name}${c.args ? ` ${c.args}` : ""}`.padEnd(commandWidth())}${dim(c.about)}`).join("\n"));
1087
1263
  screen.log(dim(KEYS));
1264
+ if (jade.keys.size)
1265
+ screen.log(dim(`Plugin keys: ${[...jade.keys].map(([k, { plugin, key }]) => `${k} ${key.description ?? ""} (${plugin})`.replace(" ", " ")).join(" · ")}`));
1088
1266
  break;
1089
1267
  case "model":
1090
1268
  await configure.model(rest[0]);
@@ -1101,50 +1279,13 @@ async function command(input: string): Promise<boolean> {
1101
1279
  if (!(MODES as readonly string[]).includes(m)) screen.log(red(`unknown mode ${m}`));
1102
1280
  else await setMode(m as Mode);
1103
1281
  screen.log(`mode: ${settings().mode}${pendingMode ? dim(" (from the next tool call)") : ""}`);
1282
+ if (settings().rules.length) screen.log(dim(`always allowed in this session:\n${settings().rules.map((r) => ` ${describeRule(r)}`).join("\n")}`));
1104
1283
  break;
1105
1284
  }
1106
- case "undo":
1107
- await undo();
1108
- break;
1109
- case "retry":
1110
- await retry();
1111
- break;
1112
- case "clear":
1113
- await switchSession();
1114
- break;
1115
- case "resume":
1116
- case "sessions": {
1117
- const id = rest[0] ? await findSession(rest[0]) : await pickSession(sessionId);
1118
- if (!id) break;
1119
- if (id === sessionId) screen.log(dim("That is the current session."));
1120
- else await switchSession(id);
1121
- break;
1122
- }
1123
- case "hooks":
1124
- 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"]) {
1125
- screen.log(`${p.padEnd(16)} ${rt.hookOrder(p).join(" → ") || dim("(none)")}`);
1126
- }
1127
- break;
1128
1285
  case "plugins":
1129
1286
  showPlugins();
1130
1287
  break;
1131
- case "rules":
1132
- screen.log(settings().rules.length ? settings().rules.map(describeRule).join("\n") : dim("(none)"));
1133
- break;
1134
- case "usage":
1135
- screen.log(
1136
- `input ${view.usage.inputTokens} output ${view.usage.outputTokens} cache read ${view.usage.cacheReadTokens} cache write ${view.usage.cacheWriteTokens} ` +
1137
- `cache hit ${percent(view.usage.cacheReadTokens, view.usage.inputTokens)}`,
1138
- );
1139
- screen.log(
1140
- dim(
1141
- `context window ${contextWindow} (${{ env: "JADE_CONTEXT_WINDOW", model: `known for ${modelLabel()}`, default: "default for unknown models" }[contextWindowInfo().source]}), ` +
1142
- `compacts at ${compactAt()}${compactTokens !== undefined ? " (JADE_COMPACT_TOKENS)" : ""}`,
1143
- ),
1144
- );
1145
- break;
1146
1288
  case "exit":
1147
- case "quit":
1148
1289
  return false;
1149
1290
  default: {
1150
1291
  const custom = customs.get(cmd!.toLowerCase());
@@ -1171,10 +1312,9 @@ async function command(input: string): Promise<boolean> {
1171
1312
 
1172
1313
  const MODE_HINTS: Record<string, string> = {
1173
1314
  ask: "ask before edits and commands",
1174
- "auto-edit": "edit files (and mkdir/touch) without asking; ask before other commands",
1175
- yolo: "never ask",
1176
- readonly: "read only, no edits or commands",
1315
+ auto: "edits in this directory run without asking; other commands are reviewed by the model, risky ones still ask",
1177
1316
  plan: "research read-only and propose a plan; edits start after you approve it",
1317
+ yolo: "never ask",
1178
1318
  };
1179
1319
 
1180
1320
  // ---------- 输入 ----------
@@ -1203,7 +1343,7 @@ function instantPlugin(name: string): boolean {
1203
1343
  const found = jade.commands.get(n);
1204
1344
  if (!found?.command.instant) return false;
1205
1345
  if (found.builtin) return true;
1206
- return !builtinNames.has(n) && !customs.has(n) && !skillCommands.has(n);
1346
+ return !hostNames.has(n) && !customs.has(n) && !skillCommands.has(n);
1207
1347
  }
1208
1348
 
1209
1349
  async function pump() {
@@ -1232,6 +1372,23 @@ async function pump() {
1232
1372
  if (exit) await quit();
1233
1373
  }
1234
1374
 
1375
+ /**
1376
+ * 有新版本时在后台升级,下次启动生效;JADE_AUTO_UPDATE=off 时只提示。
1377
+ * 每天最多查一次 npm;仓库里的开发版和 npm link 既不提示也不升级
1378
+ */
1379
+ async function checkForUpdate() {
1380
+ const install = detectInstall();
1381
+ if (install.kind === "dev") return;
1382
+ const latest = await newerVersion(home).catch(() => undefined);
1383
+ if (!latest) return;
1384
+ const manual = () => screen.log(dim(`[jade ${latest} is available (you have ${VERSION}); run jade update]`));
1385
+ if (!autoUpdateEnabled()) return manual();
1386
+ const result = await autoUpdate(home, latest, { install }).catch(() => undefined);
1387
+ if (result?.status === "installed") screen.log(dim(`[jade ${latest} was installed in the background; restart jade to use it]`));
1388
+ else if (result?.status === "failed") screen.log(yellow(`[automatic update to jade ${latest} failed (see ${display(cwd, result.log)}); run jade update]`));
1389
+ else if (result?.why !== "busy") manual();
1390
+ }
1391
+
1235
1392
  // ---------- 开始 ----------
1236
1393
 
1237
1394
  if (resumeId) {
@@ -1251,6 +1408,7 @@ if (tui) {
1251
1408
  // 之后由输入框驱动:onSubmit → pump
1252
1409
  ready = true;
1253
1410
  for (const text of [...(first ? [first] : []), ...early.splice(0)]) onSubmit(text);
1411
+ void checkForUpdate();
1254
1412
  } else {
1255
1413
  // -p 也能用自定义命令和插件的命令(内置命令需要交互,不在这里处理)
1256
1414
  const name = first?.startsWith("/") ? first.slice(1).split(/\s+/)[0]!.toLowerCase() : undefined;
@@ -1258,10 +1416,11 @@ if (tui) {
1258
1416
  const custom = name !== undefined ? customs.get(name) : undefined;
1259
1417
  await occupy(async () => {
1260
1418
  const skill = name !== undefined && !custom ? skillCommands.get(name) : undefined;
1261
- 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;
1419
+ const text = custom ? expandCommand(custom, args) : skill ? skillMessage(skill.name, args) : name !== undefined && !hostNames.has(name) && jade.commands.has(name) && !jade.commands.get(name)!.builtin ? await pluginCommand(name, args) : first;
1262
1420
  if (text) await say(text);
1263
1421
  });
1264
1422
  await leave();
1423
+ await sessions.settled();
1265
1424
  await closePlugins();
1266
1425
  await closeScreen();
1267
1426
  }