@uncarved/jade 0.1.2 → 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 (151) hide show
  1. package/README.md +204 -198
  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 +43 -6
  7. package/dist/distro.js +198 -48
  8. package/dist/distro.js.map +1 -1
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.js +2 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/main.js +436 -300
  13. package/dist/main.js.map +1 -1
  14. package/dist/plugin-cli.d.ts +1 -1
  15. package/dist/plugin-cli.js +79 -36
  16. package/dist/plugin-cli.js.map +1 -1
  17. package/dist/plugins/budget.d.ts +2 -2
  18. package/dist/plugins/budget.js +2 -2
  19. package/dist/plugins/budget.js.map +1 -1
  20. package/dist/plugins/builtins.js +6 -3
  21. package/dist/plugins/builtins.js.map +1 -1
  22. package/dist/plugins/checks.d.ts +2 -1
  23. package/dist/plugins/checks.js +25 -5
  24. package/dist/plugins/checks.js.map +1 -1
  25. package/dist/plugins/compact.js +45 -1
  26. package/dist/plugins/compact.js.map +1 -1
  27. package/dist/plugins/core.d.ts +5 -0
  28. package/dist/plugins/core.js +39 -0
  29. package/dist/plugins/core.js.map +1 -1
  30. package/dist/plugins/host.d.ts +52 -0
  31. package/dist/plugins/host.js +115 -0
  32. package/dist/plugins/host.js.map +1 -0
  33. package/dist/plugins/install.d.ts +1 -1
  34. package/dist/plugins/loader.d.ts +238 -10
  35. package/dist/plugins/loader.js +175 -21
  36. package/dist/plugins/loader.js.map +1 -1
  37. package/dist/plugins/policy.d.ts +2 -0
  38. package/dist/plugins/policy.js +17 -1
  39. package/dist/plugins/policy.js.map +1 -1
  40. package/dist/plugins/prompts.d.ts +6 -1
  41. package/dist/plugins/prompts.js +103 -15
  42. package/dist/plugins/prompts.js.map +1 -1
  43. package/dist/plugins/repeats.d.ts +7 -0
  44. package/dist/plugins/repeats.js +74 -13
  45. package/dist/plugins/repeats.js.map +1 -1
  46. package/dist/plugins/review.d.ts +2 -0
  47. package/dist/plugins/review.js +41 -3
  48. package/dist/plugins/review.js.map +1 -1
  49. package/dist/plugins/sessions.d.ts +7 -0
  50. package/dist/plugins/sessions.js +110 -0
  51. package/dist/plugins/sessions.js.map +1 -0
  52. package/dist/provider.d.ts +56 -2
  53. package/dist/provider.js +73 -7
  54. package/dist/provider.js.map +1 -1
  55. package/dist/session-lifecycle.d.ts +61 -0
  56. package/dist/session-lifecycle.js +167 -0
  57. package/dist/session-lifecycle.js.map +1 -0
  58. package/dist/session-scope.d.ts +53 -0
  59. package/dist/session-scope.js +116 -0
  60. package/dist/session-scope.js.map +1 -0
  61. package/dist/sessions.d.ts +6 -0
  62. package/dist/sessions.js +20 -0
  63. package/dist/sessions.js.map +1 -1
  64. package/dist/sys.d.ts +4 -1
  65. package/dist/sys.js +18 -1
  66. package/dist/sys.js.map +1 -1
  67. package/dist/tools/ask.d.ts +11 -0
  68. package/dist/tools/ask.js +62 -0
  69. package/dist/tools/ask.js.map +1 -0
  70. package/dist/tools/fs.d.ts +4 -0
  71. package/dist/tools/fs.js +53 -12
  72. package/dist/tools/fs.js.map +1 -1
  73. package/dist/tools/grep.js +3 -2
  74. package/dist/tools/grep.js.map +1 -1
  75. package/dist/tools/shell.js +5 -1
  76. package/dist/tools/shell.js.map +1 -1
  77. package/dist/tools/task.d.ts +6 -2
  78. package/dist/tools/task.js +36 -8
  79. package/dist/tools/task.js.map +1 -1
  80. package/dist/tools/web.d.ts +33 -3
  81. package/dist/tools/web.js +351 -143
  82. package/dist/tools/web.js.map +1 -1
  83. package/dist/ui/configure.js +91 -22
  84. package/dist/ui/configure.js.map +1 -1
  85. package/dist/ui/diff.d.ts +1 -1
  86. package/dist/ui/diff.js +1 -2
  87. package/dist/ui/diff.js.map +1 -1
  88. package/dist/ui/editor.d.ts +8 -0
  89. package/dist/ui/editor.js +50 -1
  90. package/dist/ui/editor.js.map +1 -1
  91. package/dist/ui/markdown.d.ts +6 -1
  92. package/dist/ui/markdown.js +57 -19
  93. package/dist/ui/markdown.js.map +1 -1
  94. package/dist/ui/render.d.ts +9 -10
  95. package/dist/ui/render.js +35 -72
  96. package/dist/ui/render.js.map +1 -1
  97. package/dist/ui/renderers.d.ts +8 -0
  98. package/dist/ui/renderers.js +169 -0
  99. package/dist/ui/renderers.js.map +1 -0
  100. package/dist/ui/screen.d.ts +22 -2
  101. package/dist/ui/screen.js +104 -15
  102. package/dist/ui/screen.js.map +1 -1
  103. package/dist/ui/transcript.d.ts +13 -0
  104. package/dist/ui/transcript.js +105 -15
  105. package/dist/ui/transcript.js.map +1 -1
  106. package/dist/ui/tui.d.ts +2 -0
  107. package/dist/ui/tui.js +309 -58
  108. package/dist/ui/tui.js.map +1 -1
  109. package/dist/update.d.ts +53 -0
  110. package/dist/update.js +255 -0
  111. package/dist/update.js.map +1 -0
  112. package/package.json +6 -5
  113. package/src/commands.ts +24 -0
  114. package/src/distro.ts +228 -51
  115. package/src/index.ts +2 -0
  116. package/src/main.ts +413 -292
  117. package/src/plugin-cli.ts +73 -34
  118. package/src/plugins/budget.ts +4 -4
  119. package/src/plugins/builtins.ts +6 -3
  120. package/src/plugins/checks.ts +25 -6
  121. package/src/plugins/compact.ts +40 -1
  122. package/src/plugins/core.ts +40 -0
  123. package/src/plugins/host.ts +146 -0
  124. package/src/plugins/install.ts +1 -1
  125. package/src/plugins/loader.ts +379 -23
  126. package/src/plugins/policy.ts +17 -1
  127. package/src/plugins/prompts.ts +108 -15
  128. package/src/plugins/repeats.ts +75 -14
  129. package/src/plugins/review.ts +40 -3
  130. package/src/plugins/sessions.ts +109 -0
  131. package/src/provider.ts +109 -10
  132. package/src/session-lifecycle.ts +194 -0
  133. package/src/session-scope.ts +135 -0
  134. package/src/sessions.ts +17 -0
  135. package/src/sys.ts +18 -1
  136. package/src/tools/ask.ts +72 -0
  137. package/src/tools/fs.ts +53 -12
  138. package/src/tools/grep.ts +3 -2
  139. package/src/tools/shell.ts +5 -1
  140. package/src/tools/task.ts +51 -11
  141. package/src/tools/web.ts +370 -140
  142. package/src/ui/configure.ts +90 -27
  143. package/src/ui/diff.ts +1 -2
  144. package/src/ui/editor.ts +50 -1
  145. package/src/ui/markdown.ts +258 -219
  146. package/src/ui/render.ts +35 -57
  147. package/src/ui/renderers.ts +183 -0
  148. package/src/ui/screen.ts +113 -19
  149. package/src/ui/transcript.ts +109 -16
  150. package/src/ui/tui.tsx +353 -58
  151. package/src/update.ts +262 -0
package/src/main.ts CHANGED
@@ -5,50 +5,55 @@
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
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
48
  import { reviewer } from "./plugins/review.ts";
46
- import { callDetails, clip, preview, shortPath, summarize } from "./ui/render.ts";
49
+ import { clip, shortPath } from "./ui/render.ts";
47
50
  import { transcript } from "./ui/transcript.ts";
48
51
  import { run, VERSION } from "./sys.ts";
52
+ import { autoUpdate, autoUpdateEnabled, detectInstall, newerVersion, updateCli } from "./update.ts";
49
53
 
50
54
  const HELP = `Usage: jade [options] [prompt]
51
55
  jade plugin <list|add|update|remove|enable|disable> (jade plugin --help)
56
+ jade update [--check] upgrade jade to the latest version on npm
52
57
 
53
58
  -p, --print <prompt> run one prompt and exit
54
59
  -c, --continue continue the most recent session in this directory
@@ -67,25 +72,21 @@ const COMMANDS: CommandInfo[] = [
67
72
  { name: "help", about: "list the commands and keys" },
68
73
  { name: "model", args: "[name]", about: "switch between saved models, or add one and configure its provider, API key and output limit" },
69
74
  { name: "mode", args: `[${MODES.join("|")}]`, about: "show or change the permission mode" },
70
- { name: "clear", about: "start a new session (the current one stays resumable)" },
71
- { name: "undo", about: "restore every file the agent changed in its last turn (run again to go further back)" },
72
- { name: "retry", about: "request the model again after a failed request, without sending another message" },
73
- { name: "usage", about: "token usage of this session, including sub-agents and compaction" },
74
- { name: "resume", args: "[id]", about: "pick a recent session in this directory and switch to it" },
75
- { name: "rules", about: `"always allow" rules of this session` },
76
- { name: "plugins", about: "built-in and installed plugins: their tools, hooks and commands" },
77
- { 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" },
78
76
  { name: "exit", about: "quit (the session stays resumable)" },
79
77
  ];
80
78
  /** 运行中也立即执行的命令(不碰运行时,或者只读;/mode 运行中先记在 pendingMode) */
81
- const INSTANT = new Set(["help", "model", "mode", "usage", "rules", "hooks", "plugins", "exit", "quit"]);
79
+ const INSTANT = new Set(["help", "model", "mode", "plugins", "exit"]);
82
80
  /** 内置插件提供的命令(/memory 在 jade/memory 里,等等):名字保留给它们,自定义命令不能占用 */
83
- const BUILTIN_PLUGIN_COMMANDS = ["memory", "checks", "mcp", "skills", "compact"];
81
+ const BUILTIN_PLUGIN_COMMANDS = ["memory", "checks", "mcp", "skills", "compact", "clear", "resume", "retry", "undo", "search"];
84
82
 
85
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
86
- mouse wheel or PgUp/PgDn scroll the conversation · ctrl+home/ctrl+end jump to the top/bottom · shift+drag selects text
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
87
85
  While jade is working you can keep typing: messages are queued and sent when the current turn ends.`;
88
86
 
87
+ /** 终端界面启动时最多等 MCP 服务连接这么久,没连上的在后台接着连 */
88
+ const MCP_STARTUP_WAIT_MS = 5000;
89
+
89
90
  /** 回复被输出上限截断后,自动让模型接着做的次数(每条用户消息) */
90
91
  const MAX_CONTINUES = 3;
91
92
  const CONTINUE_NOTE =
@@ -106,6 +107,7 @@ if (argv[0] === "plugin" || argv[0] === "plugins") {
106
107
  process.exit(err instanceof UsageError ? 2 : 1);
107
108
  }
108
109
  }
110
+ if (argv[0] === "update") process.exit(await updateCli(argv.slice(1)));
109
111
  const opts: { print?: string; cont?: boolean; resume?: string; mode?: Mode; cwd?: string; prompt: string[] } = { prompt: [] };
110
112
  for (let i = 0; i < argv.length; i++) {
111
113
  const a = argv[i]!;
@@ -172,13 +174,22 @@ const badSavedMode = savedMode && !(MODES as readonly string[]).includes(savedMo
172
174
  if (savedMode && !badSavedMode) opts.mode ??= savedMode as Mode;
173
175
 
174
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(() => {});
175
185
  if (!hasProvider() && !tui) {
176
186
  console.error(
177
187
  `jade: no model is configured.\n\n` +
178
188
  `Run jade in a terminal and use /model, or put one of these in ${envFile} (or set them in the shell):\n` +
179
189
  ` OPENAI_COMPAT_BASE_URL=… OPENAI_COMPAT_API_KEY=… OPENAI_COMPAT_MODEL=… (any /chat/completions service)\n` +
180
190
  ` OPENAI_API_KEY=… [OPENAI_BASE_URL=… OPENAI_MODEL=…] (OpenAI Responses API)\n` +
181
- ` 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)`,
182
193
  );
183
194
  process.exit(2);
184
195
  }
@@ -208,22 +219,41 @@ const early: string[] = [];
208
219
 
209
220
  const inputs = new InputHistory(path.join(home, "history.jsonl"), cwd);
210
221
 
211
- /** $JADE_HOME/plugins.json 里停用的插件(目录名或 id)和内置插件(id) */
222
+ /** $JADE_HOME/plugins.json 里停用的插件和内置插件(id) */
212
223
  const disabledPlugins = new Set((await readPluginSettings(home)).disabled);
213
224
  const repo = realPath(await repoRoot(cwd));
214
- /** 第三方插件目录;停用的不加载,也不读它们带的内容 */
215
- const foundPlugins = (await discoverPlugins({ home, root: repo, cwd: realPath(cwd) })).filter((f) => !disabledPlugins.has(f.name));
216
- /** 不执行代码就能读到的插件信息(带的 skills、命令、MCP 配置);读不了的插件在 loadPlugins 里报告 */
217
- const pluginInfos = new Map<string, PluginInfo>();
218
- for (const f of foundPlugins) {
219
- const info = await inspectPlugin(f.dir).catch(() => undefined);
220
- if (info) pluginInfos.set(f.dir, info);
221
- }
222
- const bundled = (pick: (b: PluginBundle) => string[]) =>
223
- 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;
224
252
 
225
253
  /** 自定义命令($JADE_HOME/commands、.jade/commands、插件带的 commands/);和内置命令同名的不生效 */
226
- 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));
227
257
  const customLoaded = await loadCommands({ home, root: repo, cwd: realPath(cwd), plugins: bundled((b) => b.commands) });
228
258
  const shadowed = customLoaded.filter((c) => builtinNames.has(c.name));
229
259
  const customs = new Map(customLoaded.filter((c) => !builtinNames.has(c.name)).map((c) => [c.name, c]));
@@ -232,10 +262,10 @@ const ALL_COMMANDS: CommandInfo[] = [
232
262
  ...[...customs.values()].map((c) => ({ name: c.name, args: c.args, about: `${c.description} (${c.plugin ? `plugin ${c.plugin}` : c.layer})` })),
233
263
  ];
234
264
 
235
- // 终端界面依赖 ink 和 react,加载要几百毫秒,只在真的用到时才导入
236
- const screen: Screen = tui
237
- ? (await import("./ui/tui.tsx")).tuiScreen({
238
- 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" },
239
269
  version: VERSION,
240
270
  commands: ALL_COMMANDS,
241
271
  history: await inputs.load(),
@@ -249,9 +279,10 @@ const screen: Screen = tui
249
279
  exit: () => (ready ? void quit() : process.exit(130)),
250
280
  files: () => mentionCandidates(cwd),
251
281
  cycleMode: () => ready && cycleMode(),
282
+ key: (spec) => ready && pluginKey(spec),
252
283
  },
253
284
  })
254
- : plainScreen({ interactive: Boolean(process.stdin.isTTY) });
285
+ : plainScreen({ interactive: Boolean(process.stdin.isTTY) }));
255
286
 
256
287
  /** 压缩、子 Agent 和主循环共用;/model 改配置后换掉里面的实现 */
257
288
  const provider = switchable({
@@ -272,15 +303,10 @@ const configure = configurator({
272
303
  onApplied: () => screen.status({ model: modelLabel() }),
273
304
  });
274
305
 
275
- if (!hasProvider()) {
276
- screen.log(bold("Welcome to jade.") + " No model is configured yet; let's set one up.");
277
- if (!(await configure.provider())) {
278
- await screen.close();
279
- process.exit(2);
280
- }
281
- } else {
306
+ // 还没配置模型时,等插件加载完再问(见下面 registerProviders 之后):插件提供的服务也要列出来
307
+ if (providerEarly) {
282
308
  try {
283
- provider.set(retrying(await providerFromEnv()));
309
+ provider.set(retrying(await providerEarly));
284
310
  } catch (err) {
285
311
  await screen.close();
286
312
  fail(errorText(err));
@@ -311,10 +337,11 @@ function retrying(inner: Provider) {
311
337
  waiting = false;
312
338
  },
313
339
  onRetry: ({ attempt, retries, delayMs, error }) => {
314
- const why = isRateLimit(error) ? "rate limited" : clip(error.message.replace(/\s+/g, " "), 160);
315
- 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)}]`));
316
343
  waiting = true;
317
- screen.busy(`Waiting to retry (${attempt}/${retries}, ${seconds(delayMs)})`);
344
+ screen.busy(`Waiting to retry (${why} · ${attempt}/${retries}, ${seconds(delayMs)})`);
318
345
  },
319
346
  });
320
347
  }
@@ -322,16 +349,20 @@ function retrying(inner: Provider) {
322
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`);
323
350
 
324
351
  const store = new JsonlLogStore(path.join(home, "sessions"));
325
- const trust = new JsonlTrustStore(path.join(home, "trust.jsonl"));
326
352
  const index = new SessionIndex(path.join(home, "index.jsonl"));
327
353
 
328
- /** 正在结束进程外插件:这时它们退出是预期的,不提示 */
354
+ /** 正在退出:这时 MCP 服务断开是预期的,不提示 */
329
355
  let pluginsClosing = false;
330
- const pluginSources = await loadPlugins();
331
- 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;
332
363
  for (const w of skillsLoaded.warnings) screen.log(yellow(`[warning] ${w}`));
333
364
  const skills = skillsLoaded.skills;
334
- const mcpClients = await connectMcp();
365
+ const mcpClients = await mcpConnecting;
335
366
  /**
336
367
  * 运行中切换的权限模式:这一轮正占着日志,写不进去。关卡先按它判断(下一个工具调用就生效),
337
368
  * 这一轮结束后再记进日志(flushPendingMode)
@@ -345,12 +376,35 @@ function currentModel(): { name: string; via: string } | undefined {
345
376
  try {
346
377
  host = info.baseURL ? new URL(info.baseURL).host : undefined;
347
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
+ }
348
386
  const api = { anthropic: "the Anthropic API", openai: "the OpenAI Responses API", "openai-compat": "an OpenAI-compatible API" }[info.kind];
349
387
  return { name: info.model, via: host ? `${api} at ${host}` : api };
350
388
  }
351
- /** 每个会话用一套新的插件实例:插件里有按会话记的状态(例如压缩、重复调用的计数) */
352
- const makeJade = (mode?: Mode) =>
353
- createJade({
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({
354
408
  cwd,
355
409
  home,
356
410
  store,
@@ -362,18 +416,73 @@ const makeJade = (mode?: Mode) =>
362
416
  mcp: mcpClients,
363
417
  skills,
364
418
  compactTokens: compactAt,
419
+ scratch,
365
420
  approveSubagent,
421
+ // 不能交互时(-p)没有人回答,不提供这个工具
422
+ askUser: screen.interactive ? askUser : undefined,
366
423
  sharedRules: (): AllowRule[] => [...settings().rules, ...pendingRules],
367
424
  pendingMode: () => pendingMode,
368
425
  // auto 模式的审查用当前的模型;rt 换会话时跟着换,所以每次取
369
- review: reviewer({ provider, cwd, messages: () => rt.state.messages }),
426
+ review: reviewer({ provider, cwd, scratch, messages: () => rt.state.messages }),
370
427
  approveCheck: process.env.JADE_CHECKS === "off" ? undefined : approveCheck,
371
428
  checkConfirmed: (c) => trust.has(checkHash(c)),
372
429
  checksUnavailable: process.env.JADE_CHECKS === "off" ? "Edit-time checks are turned off by JADE_CHECKS=off." : undefined,
373
- });
430
+ ...next.hooks,
431
+ }));
432
+ return next;
433
+ }
374
434
 
375
- let jade: Jade = await makeJade(opts.mode);
376
- 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
+ }
377
486
  if (badSavedMode) screen.log(yellow(`[warning] JADE_MODE=${badSavedMode} is not a mode (${MODES.join(", ")}); starting in ${opts.mode ?? "ask"}`));
378
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`));
379
488
  // 插件的命令加进菜单(名字在各个会话的实例之间不变)。内置命令和 .jade/commands 里的同名命令优先
@@ -385,84 +494,40 @@ for (const sk of skills) {
385
494
  skillCommands.set(name, sk);
386
495
  ALL_COMMANDS.push({ name: sk.name, args: "[task]", about: `${clip(sk.description.replace(/\s+/g, " "), 80)} (skill)` });
387
496
  }
388
- // 内置插件的命令排在宿主命令后面;第三方插件的命令排在最后
389
- const builtinPluginCommands: CommandInfo[] = [];
390
- for (const [name, { plugin, command: c, builtin }] of jade.commands) {
391
- if (builtin) {
392
- builtinPluginCommands.push({ name: c.name, args: c.args, about: c.description ?? "" });
393
- continue;
394
- }
395
- if (builtinNames.has(name) || customs.has(name) || skillCommands.has(name)) {
396
- const what = builtinNames.has(name) ? "a built-in command" : customs.has(name) ? "a custom command" : "a skill";
397
- screen.log(yellow(`[warning] command /${c.name} of plugin ${plugin} is ignored: ${what} has that name`));
398
- continue;
399
- }
400
- ALL_COMMANDS.push({ name: c.name, args: c.args, about: `${c.description ?? ""} (plugin ${plugin})`.trim() });
401
- }
402
- 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);
403
502
 
404
- /**
405
- * 第三方插件:$JADE_HOME/plugins/<name>/(用户层)和 .jade/plugins/<name>/(项目层)。
406
- * 项目层的首次加载及内容变化后要用户确认(7.1)。加载失败的跳过并提示,不影响启动
407
- */
408
- async function loadPlugins(): Promise<LoadedPlugin[]> {
409
- const out: LoadedPlugin[] = [];
410
- for (const f of foundPlugins) {
411
- try {
412
- const unsupported = pluginInfos.get(f.dir)?.bundle.unsupported ?? [];
413
- if (unsupported.length) screen.log(dim(`[note] plugin ${f.name}: jade does not support its ${unsupported.join(" and ")} yet; they are ignored`));
414
- out.push(
415
- await loadPlugin(f, {
416
- trust,
417
- confirm: async ({ path: p, hash, files, command }) =>
418
- (await screen.select(
419
- `Project plugin ${display(cwd, p)} is new or changed. Load and run it?`,
420
- [
421
- { label: "No", value: false },
422
- { label: "Yes, load it", value: true },
423
- ],
424
- {
425
- body: dim(
426
- `${command ? `runs: ${command}\n` : ""}sha256 ${hash.slice(0, 12)}, ${files.length} files:\n${files.map((f) => ` ${f}`).join("\n")}`,
427
- ),
428
- },
429
- )) ?? false,
430
- onExit: (p, { code, signal }) => {
431
- if (!pluginsClosing) screen.log(yellow(`[warning] plugin ${p.name} exited (${signal ?? `code ${code}`}); its hooks fail until jade restarts. /plugins shows its stderr`));
432
- },
433
- }),
434
- );
435
- } catch (err) {
436
- const hint = f.layer === "project" && !tui && err instanceof UntrustedPlugin ? " (run jade interactively in this directory once to confirm it)" : "";
437
- screen.log(yellow(`[skipped] plugin ${display(cwd, f.dir)}: ${errorText(err)}${hint}`));
438
- }
439
- }
440
- return out;
441
- }
442
-
443
- /** 结束进程外插件的进程 */
503
+ /** 结束进程外插件的进程和 MCP 服务 */
444
504
  async function closePlugins() {
445
505
  pluginsClosing = true;
446
- 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(() => {}))]);
447
507
  }
448
508
 
449
509
  /**
450
510
  * 连接 mcp.json 里配置的 MCP 服务。项目层(随仓库分发)的服务第一次启动前要用户确认,按配置内容记在 trust.jsonl;
451
- * 连不上的跳过并提示,不影响启动。所有服务并发连接
511
+ * 连不上的跳过并提示,不影响启动。所有服务并发连接,不用确认的立即开始连。
512
+ * 启动时最多等 MCP_STARTUP_WAIT_MS:还没连上的在后台接着连,它们的工具从下一个会话(/clear)开始提供
513
+ * (一个会话里的工具列表不变,否则提示缓存失效)。
514
+ * dialogsAfter:在它完成之后才弹确认框,不和插件的确认框同时出现
452
515
  */
453
- async function connectMcp(): Promise<McpClient[]> {
454
- const plugins = foundPlugins.flatMap((f) => {
455
- const mcp = pluginInfos.get(f.dir)?.bundle.mcp;
456
- 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 }] : [];
457
520
  });
458
- 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 });
459
522
  for (const w of warnings) screen.log(yellow(`[warning] ${w}`));
460
523
  const clients: McpClient[] = [];
524
+ const connecting: Promise<unknown>[] = [];
461
525
  for (const entry of servers) {
462
526
  if (entry.config.disabled) continue;
463
527
  if (entry.layer === "project") {
464
528
  const hash = mcpTrustHash(repo, entry);
465
529
  if (!(await trust.has(hash))) {
530
+ if (tui) await dialogsAfter.catch(() => {});
466
531
  const ok = tui
467
532
  ? ((await screen.select(
468
533
  `MCP server "${entry.name}" from ${display(cwd, entry.file)} is new or changed. Start it?`,
@@ -480,21 +545,31 @@ async function connectMcp(): Promise<McpClient[]> {
480
545
  await trust.add({ hash, path: entry.file, at: new Date().toISOString() });
481
546
  }
482
547
  }
483
- clients.push(
484
- new McpClient(entry, {
485
- cwd,
486
- onDisconnect: (c, why) => {
487
- if (!pluginsClosing) screen.log(yellow(`[warning] MCP server ${c.name} disconnected: ${why}. jade reconnects on its next tool call; /mcp shows details`));
488
- },
489
- }),
490
- );
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)}`))));
491
556
  }
492
557
  if (clients.length === 0) return clients;
493
558
  screen.busy(`Connecting to ${clients.length} MCP server${clients.length > 1 ? "s" : ""}`);
494
- await Promise.all(
495
- clients.map((c) => c.connect().catch((err) => screen.log(yellow(`[warning] MCP server ${c.name} is unavailable: ${errorText(err)}`)))),
496
- );
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);
497
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
+ }
498
573
  return clients;
499
574
  }
500
575
 
@@ -505,7 +580,7 @@ if (resumeId === "") {
505
580
  fail("--resume without an id needs a terminal to pick from; pass the id");
506
581
  }
507
582
  resumeId = await pickSession();
508
- } else if (resumeId) resumeId = await findSession(resumeId);
583
+ } else if (resumeId) resumeId = matchSession(await index.list(cwd), resumeId);
509
584
  if (opts.cont) {
510
585
  resumeId = (await index.list(cwd))[0]?.id;
511
586
  if (!resumeId) {
@@ -515,14 +590,20 @@ if (opts.cont) {
515
590
  }
516
591
 
517
592
  // /clear 换成新的运行时和会话
518
- let rt = resumeId
519
- ? await Runtime.resume({ store, provider, plugins: jade.plugins, sessionId: resumeId })
520
- : await Runtime.create({ store, provider, plugins: jade.plugins });
521
- 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));
522
602
 
523
603
  // 权限设置记在日志里(derived),关卡从那里读,恢复会话后仍然有效
524
604
  // 主会话不会是 readonly(只给子 Agent 用;旧会话里记的 readonly 由关卡换成 plan)
525
- const settings = () => jade.policy.settings(rt.state.derived) as PolicySettings & { mode: Mode };
605
+ // 只取这一项:rt.state 每次都拷贝整段历史,而这里调用得很频繁(子 Agent 的每次关卡判断都会调用)
606
+ const settings = () => jade.policy.settings({ [POLICY_KEY]: rt.derived(POLICY_KEY) }) as PolicySettings & { mode: Mode };
526
607
  const saveSettings = async (next: PolicySettings) => {
527
608
  await rt.record(POLICY_KEY, next);
528
609
  pendingMode = undefined;
@@ -564,24 +645,27 @@ async function flushPendingMode() {
564
645
 
565
646
  // ---------- 渲染 ----------
566
647
 
567
- 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) });
568
649
  rt.subscribe(view.onNotice);
569
650
 
570
- const percent = (part: number, whole: number) => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "—");
571
-
572
651
  // ---------- 审批 ----------
573
652
 
574
653
  type Call = { toolUseId: string; name: string; input: unknown; reason?: string };
575
654
 
576
- /** 问用户是否允许一个调用;选了"总是允许"时交给 remember 记下规则 */
577
- async function ask(c: Call, who: string, remember: (rule: AllowRule) => Promise<void> | void): Promise<SubagentApproval> {
578
- 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)})`;
579
661
  if (!screen.interactive) {
580
662
  screen.log(red(`✗ ${who}${head} denied: not running interactively`));
581
663
  return { approved: false, reason: "The user is not available to approve this action." };
582
664
  }
583
665
  const rule = jade.policy.ruleFor(c);
584
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));
585
669
  const answer = await screen.select(
586
670
  `Allow ${who}${head}?`,
587
671
  [
@@ -589,18 +673,19 @@ async function ask(c: Call, who: string, remember: (rule: AllowRule) => Promise<
589
673
  { label: `Yes, and always allow ${always} in this session`, value: "always" as const },
590
674
  { label: "No, and tell jade what to do instead", value: "no" as const },
591
675
  ],
592
- // 关卡给了理由的(例如 auto 模式下审查转给用户的),说明为什么要问
593
- { body: (c.reason ? `${yellow(c.reason)}\n\n` : "") + (await preview(c, cwd)) },
676
+ { body, signal },
594
677
  );
678
+ signal?.throwIfAborted();
595
679
  if (answer === "always") await remember(rule);
596
680
  const approved = answer === "yes" || answer === "always";
597
- const reason = approved
598
- ? undefined
599
- : (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.";
600
685
  // 主 Agent 的调用的结果之后接在这一行后面
601
- screen.log(approved ? green(`✓ ${who}${head}`) : red(`✗ ${who}${head}`) + dim(reason ? ` — ${clip(reason, 200)}` : ""), {
686
+ screen.log((approved ? green(`✓ ${who}${head}`) : red(`✗ ${who}${head}`)) + dim(reason ? ` — ${clip(reason, 200)}` : ""), {
602
687
  id: c.toolUseId,
603
- details: callDetails(c.name, c.input),
688
+ details: view.details(c.name, c.input),
604
689
  });
605
690
  return { approved, reason };
606
691
  }
@@ -628,15 +713,42 @@ let subagentAsking: Promise<unknown> = Promise.resolve();
628
713
  function approveSubagent(...[c, signal]: Parameters<ApproveSubagent>): Promise<SubagentApproval> {
629
714
  const turn = subagentAsking.then(() => {
630
715
  signal.throwIfAborted();
631
- // 中断时不再等用户回答;对话框由用户自己关掉
632
- 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);
633
718
  });
634
719
  subagentAsking = turn.catch(() => {});
635
720
  return turn;
636
721
  }
637
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
+
638
749
  /** 编辑后检查的确认记录:同一个目录里的同一条命令只问一次,记在 trust.jsonl */
639
750
  const checkHash = (c: Check) => createHash("sha256").update(`jade-check\0${c.cwd}\0${c.command}`).digest("hex");
751
+ const confirmedChecks = new Set<string>();
640
752
 
641
753
  /**
642
754
  * 编辑后检查的命令第一次运行前问用户:它会执行仓库里的代码(node_modules 里的 tsc、配置里的命令)。
@@ -644,7 +756,12 @@ const checkHash = (c: Check) => createHash("sha256").update(`jade-check\0${c.cwd
644
756
  */
645
757
  async function approveCheck(c: Check, signal: AbortSignal): Promise<boolean> {
646
758
  const hash = checkHash(c);
647
- 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
+ }
648
765
  if (settings().mode === "yolo") return true;
649
766
  if (!screen.interactive) return false;
650
767
  const run = subagentAsking.then(() => {
@@ -663,8 +780,10 @@ async function approveCheck(c: Check, signal: AbortSignal): Promise<boolean> {
663
780
  });
664
781
  subagentAsking = run.catch(() => {});
665
782
  const ok = (await run) ?? false;
666
- if (ok) await trust.add({ hash, path: c.cwd, at: new Date().toISOString() });
667
- 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]`));
668
787
  return ok;
669
788
  }
670
789
 
@@ -674,8 +793,10 @@ function skillMessage(name: string, args: string): string {
674
793
  return `Use the "${name}" skill${args.trim() ? ` for this: ${args.trim()}` : "."}`;
675
794
  }
676
795
 
677
- /** 正在执行的插件命令;esc 中断它 */
678
- let commandAbort: AbortController | undefined;
796
+ /** 正在执行的插件命令;esc 中断它们。instant 的命令可以在另一个命令的模型回合里执行,所以可能同时有几个 */
797
+ const commandAborts = new Set<AbortController>();
798
+ /** 插件命令经 session 发起的换会话、重试:命令被 esc 中断后也要等它收尾,再处理下一条输入 */
799
+ let sessionWork: Promise<unknown> | undefined;
679
800
 
680
801
  /** 执行插件的斜杠命令,返回要发给模型的提示词(没有就是 undefined) */
681
802
  async function pluginCommand(name: string, args: string): Promise<string | undefined> {
@@ -685,7 +806,7 @@ async function pluginCommand(name: string, args: string): Promise<string | undef
685
806
  return undefined;
686
807
  }
687
808
  const ac = new AbortController();
688
- commandAbort = ac;
809
+ commandAborts.add(ac);
689
810
  try {
690
811
  const result = await abortable(
691
812
  Promise.resolve(
@@ -701,6 +822,8 @@ async function pluginCommand(name: string, args: string): Promise<string | undef
701
822
  input: (title, o) => screen.input(title, o),
702
823
  },
703
824
  note: (text) => void notes.push(text),
825
+ // instant 的命令在模型工作时执行,不能换会话、写日志
826
+ session: found.command.instant ? undefined : sessionControl(found.plugin),
704
827
  }),
705
828
  ),
706
829
  ac.signal,
@@ -719,13 +842,40 @@ async function pluginCommand(name: string, args: string): Promise<string | undef
719
842
  }
720
843
  return undefined;
721
844
  } catch (err) {
722
- 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)}`));
723
847
  return undefined;
724
848
  } finally {
725
- 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);
726
855
  }
727
856
  }
728
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
+
729
879
  /** /plugins:内置插件的状态,每个第三方插件的来源、工具、hook、命令和带的内容;跳过的插件在启动时已经提示过 */
730
880
  function showPlugins() {
731
881
  const width = Math.max(...jade.builtins.map((b) => b.id.length)) + 2;
@@ -741,24 +891,29 @@ function showPlugins() {
741
891
  }
742
892
  const carried = (b: PluginBundle) =>
743
893
  [b.skills.length ? "skills" : "", b.commands.length ? "commands" : "", b.mcp ? "MCP servers" : ""].filter(Boolean).join(", ");
744
- for (const { source, plugin } of jade.extensions) {
894
+ for (const { source, plugin, commands, keys } of jade.extensions) {
745
895
  const exit = source.process?.exited;
746
896
  const state = source.kind === "process" ? (exit ? red(` exited (${exit.signal ?? `code ${exit.code}`})`) : green(" running")) : "";
747
897
  lines.push(`${bold(plugin.id)} ${plugin.version} ${dim(`${source.layer} · ${display(cwd, source.dir)} · ${source.kind === "process" ? `runs ${source.entry}` : source.entry}`)}${state}`);
748
898
  const tools = (plugin.tools ?? []).map((t) => `${t.name} (${t.effect})`);
749
899
  const hooks = [...new Set((plugin.hooks ?? []).map((h) => `${h.kind}:${h.point}`))];
750
- const cmds = (plugin.commands ?? []).map((c) => `/${c.name}`);
900
+ const cmds = commands.map((c) => `/${c.name}`);
751
901
  if (tools.length) lines.push(` tools ${tools.join(", ")}`);
752
902
  if (hooks.length) lines.push(` hooks ${hooks.join(", ")}`);
753
903
  if (cmds.length) lines.push(` commands ${cmds.join(", ")}`);
754
- 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(", ")}`);
755
906
  if (carried(source.info.bundle)) lines.push(` carries ${carried(source.info.bundle)}`);
756
907
  if (exit && source.process!.stderr.length) lines.push(dim(source.process!.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
757
908
  }
758
909
  for (const p of contentOnly) {
759
- 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)}`)}`);
760
911
  lines.push(` carries ${carried(p.info.bundle)}`);
761
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
+ }
762
917
  screen.log(lines.join("\n"));
763
918
  }
764
919
 
@@ -768,9 +923,11 @@ async function savePendingRules() {
768
923
  await saveSettings({ ...s, rules: [...s.rules, ...pendingRules.splice(0)] });
769
924
  }
770
925
 
926
+ /** p 和 signal 谁先结束用谁:signal 中止时以它的 reason 拒绝 */
771
927
  function abortable<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
772
928
  return new Promise((resolve, reject) => {
773
929
  const stop = () => reject(signal.reason);
930
+ if (signal.aborted) return stop();
774
931
  signal.addEventListener("abort", stop, { once: true });
775
932
  p.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
776
933
  });
@@ -812,7 +969,7 @@ function interrupt() {
812
969
  const again = interruptPending || Date.now() - interruptedAt < SECOND_ESC_MS;
813
970
  interruptedAt = Date.now();
814
971
  interruptPending = true;
815
- commandAbort?.abort(new Error("interrupted by user"));
972
+ for (const ac of commandAborts) ac.abort(new Error("interrupted by user"));
816
973
  rt.abort("interrupted by user");
817
974
  screen.busy("Interrupting");
818
975
  if (queue.length === 0) return;
@@ -829,15 +986,8 @@ function interrupt() {
829
986
  * 离开会话但保留它:写入 session.detached,插件的收尾写入完成后再退出(4.2)。
830
987
  * 没收到过输入的会话没什么可恢复的,删掉它的日志;返回会话是否保留了下来
831
988
  */
832
- async function leave(): Promise<boolean> {
833
- jade.shutdown();
834
- try {
835
- await rt.detach();
836
- return !(await discardIfEmpty(store, sessionId));
837
- } catch (err) {
838
- screen.log(red(`[error] ${errorText(err)}`));
839
- return true;
840
- }
989
+ function leave(): Promise<boolean> {
990
+ return sessions.leave();
841
991
  }
842
992
 
843
993
  /** 关掉界面后再提示怎么恢复:终端界面退出备用屏幕后,里面的内容就看不到了 */
@@ -854,6 +1004,7 @@ async function quit(code = 0) {
854
1004
  // 中断后等这一轮收尾,再写 session.detached;pump 看到 quitting 就不再取排队的输入
855
1005
  await work?.catch(() => {});
856
1006
  await leave();
1007
+ await sessions.settled();
857
1008
  await closePlugins();
858
1009
  await closeScreen();
859
1010
  process.exit(code);
@@ -866,23 +1017,16 @@ async function quit(code = 0) {
866
1017
  */
867
1018
  async function switchSession(id?: string) {
868
1019
  await flushPendingMode();
869
- const mode = settings().mode;
870
- const next = await makeJade(mode);
871
- let nextRt: Runtime;
1020
+ let switched: { previous: string; kept: boolean };
872
1021
  try {
873
- nextRt = id
874
- ? await Runtime.resume({ store, provider, plugins: next.plugins, sessionId: id })
875
- : await Runtime.create({ store, provider, plugins: next.plugins });
1022
+ switched = await sessions.switchTo(id, settings().mode);
876
1023
  } catch (err) {
877
- next.shutdown();
878
- 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)}`));
879
1026
  }
880
- const kept = await leave();
881
- const old = sessionId;
882
- jade = next;
883
- rt = nextRt;
1027
+ const { previous: old, kept } = switched;
1028
+ adopt(sessions.current);
884
1029
  rt.subscribe(view.onNotice);
885
- sessionId = rt.state.sessionId;
886
1030
  view.reset();
887
1031
  notes.length = 0;
888
1032
  announcedMode = undefined;
@@ -896,9 +1040,35 @@ async function switchSession(id?: string) {
896
1040
  }
897
1041
  }
898
1042
 
899
- /** 从这个目录最近的会话里选一个;取消或没有时返回 undefined */
900
- async function pickSession(current?: string): Promise<string | undefined> {
901
- 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);
902
1072
  if (all.length === 0) {
903
1073
  screen.log(dim(`No other sessions in ${shortPath(cwd)}.`));
904
1074
  return undefined;
@@ -909,23 +1079,6 @@ async function pickSession(current?: string): Promise<string | undefined> {
909
1079
  );
910
1080
  }
911
1081
 
912
- /** 这个目录的会话里 id 等于 arg 或以它开头的唯一一个;都不是时原样返回,交给 Runtime.resume 去找 */
913
- async function findSession(arg: string): Promise<string> {
914
- const hits = (await index.list(cwd)).filter((s) => s.id.startsWith(arg));
915
- return hits.find((s) => s.id === arg)?.id ?? (hits.length === 1 ? hits[0]!.id : arg);
916
- }
917
-
918
- /** 显示用的相对时间 */
919
- function ago(iso: string): string {
920
- const s = (Date.now() - Date.parse(iso)) / 1000;
921
- if (!Number.isFinite(s)) return iso;
922
- if (s < 60) return "just now";
923
- if (s < 3600) return `${Math.floor(s / 60)} min ago`;
924
- if (s < 86400) return `${Math.floor(s / 3600)} h ago`;
925
- if (s < 86400 * 7) return `${Math.floor(s / 86400)} d ago`;
926
- return iso.slice(0, 10);
927
- }
928
-
929
1082
  process.on("SIGINT", () => (running ? interrupt() : void quit(130)));
930
1083
 
931
1084
  /** guarded 里最近一次抛出的错误;每次 guarded 开始时清掉 */
@@ -1013,15 +1166,36 @@ async function say(text: string) {
1013
1166
  await offerPlan();
1014
1167
  }
1015
1168
 
1016
- /** 上一轮在模型回复之前就失败了:最后一条消息还没有回复 */
1017
- 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
+ }
1018
1184
 
1019
- async function retry() {
1020
- if (!canRetry()) return screen.log(dim("Nothing to retry: the last message already has a reply."));
1021
- 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);
1022
1191
  }
1023
1192
 
1193
+ /** 上一轮在模型回复之前就失败了:最后一条消息还没有回复 */
1194
+ const canRetry = () => rt.phase === "idle" && rt.state.messages.at(-1)?.role === "user";
1195
+
1024
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."));
1025
1199
  // 计时从这次输入开始,不接着上一条排队消息的
1026
1200
  screen.busy(undefined);
1027
1201
  screen.busy("Working");
@@ -1045,42 +1219,6 @@ async function drive(input: UserInput) {
1045
1219
  await savePendingRules().catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
1046
1220
  }
1047
1221
 
1048
- /** 撤销最近一轮里还没撤销的全部文件修改:同一个文件改过几次的,恢复到这一轮改它之前的样子 */
1049
- async function undo() {
1050
- const undone = new Set((rt.state.derived[UNDO_KEY] as UndoState | undefined)?.undone ?? []);
1051
- const cps = lastTurnChanges(rt.state.messages, await jade.checkpoints.list(sessionId), undone);
1052
- if (cps.length === 0) return screen.log(dim("Nothing to undo."));
1053
- /** 文件 → 这一轮最早的快照(恢复成它的 before);cps 是最新的在前 */
1054
- const files = new Map<string, Checkpoint>();
1055
- for (const cp of cps) files.set(cp.path, cp);
1056
- // 只有最新一次写入之后的内容能和文件现在的样子比较
1057
- const latest = new Map<string, Checkpoint>();
1058
- for (const cp of cps) if (!latest.has(cp.path)) latest.set(cp.path, cp);
1059
- const changed: string[] = [];
1060
- for (const cp of latest.values()) if (!(await jade.checkpoints.unchangedSince(cp))) changed.push(display(cwd, cp.path));
1061
- const list = [...files.values()].map((cp) => ` ${cp.before === null ? "delete " : "restore"} ${display(cwd, cp.path)}`).join("\n");
1062
- if (files.size > 1 || changed.length > 0) {
1063
- const ok = await screen.select(
1064
- changed.length > 0
1065
- ? `${changed.join(", ")} changed since the agent wrote ${changed.length > 1 ? "them" : "it"}. Undo anyway and discard those changes too?`
1066
- : `Undo the agent's last turn of changes (${files.size} files)?`,
1067
- [
1068
- { label: "No", value: false },
1069
- { label: changed.length > 0 ? "Yes, undo anyway" : "Yes, undo", value: true },
1070
- ],
1071
- { body: list },
1072
- );
1073
- if (!ok) return;
1074
- }
1075
- for (const cp of cps) await jade.checkpoints.restore(cp);
1076
- await rt.record(UNDO_KEY, { undone: [...undone, ...cps.map((c) => c.toolUseId)] } satisfies UndoState);
1077
- const what = [...files.values()].map((cp) =>
1078
- cp.before === null ? `deleted ${display(cwd, cp.path)} (you had created it)` : `restored ${display(cwd, cp.path)} to its content before your changes`,
1079
- );
1080
- notes.push(`The user undid your changes from your last turn: ${what.join("; ")}. Read these files again before changing them.`);
1081
- screen.log(green(`Undid ${cps.length} change${cps.length > 1 ? "s" : ""} from the last turn:`) + "\n" + dim(list));
1082
- }
1083
-
1084
1222
  /** 恢复的会话里已有的内容:终端界面里重新显示对话,逐行输出时只统计用量 */
1085
1223
  async function replayHistory() {
1086
1224
  await view.replay(await readAll(store, sessionId), tui);
@@ -1111,7 +1249,6 @@ async function resumeSession(): Promise<boolean> {
1111
1249
  return true;
1112
1250
  }
1113
1251
 
1114
- /** /memory:不带参数时列出记忆,可以删掉一条或新加一条;带参数时记下这段话 */
1115
1252
  // ---------- 命令 ----------
1116
1253
 
1117
1254
 
@@ -1124,6 +1261,8 @@ async function command(input: string): Promise<boolean> {
1124
1261
  case "help":
1125
1262
  screen.log(ALL_COMMANDS.map((c) => `${`/${c.name}${c.args ? ` ${c.args}` : ""}`.padEnd(commandWidth())}${dim(c.about)}`).join("\n"));
1126
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(" · ")}`));
1127
1266
  break;
1128
1267
  case "model":
1129
1268
  await configure.model(rest[0]);
@@ -1140,50 +1279,13 @@ async function command(input: string): Promise<boolean> {
1140
1279
  if (!(MODES as readonly string[]).includes(m)) screen.log(red(`unknown mode ${m}`));
1141
1280
  else await setMode(m as Mode);
1142
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")}`));
1143
1283
  break;
1144
1284
  }
1145
- case "undo":
1146
- await undo();
1147
- break;
1148
- case "retry":
1149
- await retry();
1150
- break;
1151
- case "clear":
1152
- await switchSession();
1153
- break;
1154
- case "resume":
1155
- case "sessions": {
1156
- const id = rest[0] ? await findSession(rest[0]) : await pickSession(sessionId);
1157
- if (!id) break;
1158
- if (id === sessionId) screen.log(dim("That is the current session."));
1159
- else await switchSession(id);
1160
- break;
1161
- }
1162
- case "hooks":
1163
- 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"]) {
1164
- screen.log(`${p.padEnd(16)} ${rt.hookOrder(p).join(" → ") || dim("(none)")}`);
1165
- }
1166
- break;
1167
1285
  case "plugins":
1168
1286
  showPlugins();
1169
1287
  break;
1170
- case "rules":
1171
- screen.log(settings().rules.length ? settings().rules.map(describeRule).join("\n") : dim("(none)"));
1172
- break;
1173
- case "usage":
1174
- screen.log(
1175
- `input ${view.usage.inputTokens} output ${view.usage.outputTokens} cache read ${view.usage.cacheReadTokens} cache write ${view.usage.cacheWriteTokens} ` +
1176
- `cache hit ${percent(view.usage.cacheReadTokens, view.usage.inputTokens)}`,
1177
- );
1178
- screen.log(
1179
- dim(
1180
- `context window ${contextWindow} (${{ env: "JADE_CONTEXT_WINDOW", model: `known for ${modelLabel()}`, default: "default for unknown models" }[contextWindowInfo().source]}), ` +
1181
- `compacts at ${compactAt()}${compactTokens !== undefined ? " (JADE_COMPACT_TOKENS)" : ""}`,
1182
- ),
1183
- );
1184
- break;
1185
1288
  case "exit":
1186
- case "quit":
1187
1289
  return false;
1188
1290
  default: {
1189
1291
  const custom = customs.get(cmd!.toLowerCase());
@@ -1241,7 +1343,7 @@ function instantPlugin(name: string): boolean {
1241
1343
  const found = jade.commands.get(n);
1242
1344
  if (!found?.command.instant) return false;
1243
1345
  if (found.builtin) return true;
1244
- return !builtinNames.has(n) && !customs.has(n) && !skillCommands.has(n);
1346
+ return !hostNames.has(n) && !customs.has(n) && !skillCommands.has(n);
1245
1347
  }
1246
1348
 
1247
1349
  async function pump() {
@@ -1270,6 +1372,23 @@ async function pump() {
1270
1372
  if (exit) await quit();
1271
1373
  }
1272
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
+
1273
1392
  // ---------- 开始 ----------
1274
1393
 
1275
1394
  if (resumeId) {
@@ -1289,6 +1408,7 @@ if (tui) {
1289
1408
  // 之后由输入框驱动:onSubmit → pump
1290
1409
  ready = true;
1291
1410
  for (const text of [...(first ? [first] : []), ...early.splice(0)]) onSubmit(text);
1411
+ void checkForUpdate();
1292
1412
  } else {
1293
1413
  // -p 也能用自定义命令和插件的命令(内置命令需要交互,不在这里处理)
1294
1414
  const name = first?.startsWith("/") ? first.slice(1).split(/\s+/)[0]!.toLowerCase() : undefined;
@@ -1296,10 +1416,11 @@ if (tui) {
1296
1416
  const custom = name !== undefined ? customs.get(name) : undefined;
1297
1417
  await occupy(async () => {
1298
1418
  const skill = name !== undefined && !custom ? skillCommands.get(name) : undefined;
1299
- 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;
1300
1420
  if (text) await say(text);
1301
1421
  });
1302
1422
  await leave();
1423
+ await sessions.settled();
1303
1424
  await closePlugins();
1304
1425
  await closeScreen();
1305
1426
  }