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