@uncarved/jade 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -6
- 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 +51 -7
- package/dist/distro.js +199 -48
- package/dist/distro.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js +479 -303
- package/dist/main.js.map +1 -1
- package/dist/mcp.js +1 -1
- package/dist/mcp.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 +23 -5
- package/dist/plugins/policy.js +63 -10
- package/dist/plugins/policy.js.map +1 -1
- package/dist/plugins/prompts.d.ts +14 -1
- package/dist/plugins/prompts.js +118 -16
- 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 +18 -0
- package/dist/plugins/review.js +130 -0
- package/dist/plugins/review.js.map +1 -0
- 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 +57 -3
- package/dist/provider.js +80 -10
- 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 +10 -2
- package/dist/tools/task.js +40 -9
- 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 +144 -66
- 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 +22 -0
- package/dist/ui/markdown.js +242 -0
- package/dist/ui/markdown.js.map +1 -0
- package/dist/ui/render.d.ts +9 -8
- package/dist/ui/render.js +35 -62
- 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 +25 -2
- package/dist/ui/screen.js +104 -12
- package/dist/ui/screen.js.map +1 -1
- package/dist/ui/transcript.d.ts +13 -0
- package/dist/ui/transcript.js +157 -31
- package/dist/ui/transcript.js.map +1 -1
- package/dist/ui/tui.d.ts +2 -0
- package/dist/ui/tui.js +383 -81
- 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 +7 -6
- package/src/commands.ts +24 -0
- package/src/distro.ts +234 -52
- package/src/index.ts +3 -0
- package/src/main.ts +459 -300
- package/src/mcp.ts +1 -1
- 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 +70 -13
- package/src/plugins/prompts.ts +128 -16
- package/src/plugins/repeats.ts +75 -14
- package/src/plugins/review.ts +146 -0
- package/src/plugins/sessions.ts +109 -0
- package/src/provider.ts +117 -14
- 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 +56 -12
- package/src/tools/web.ts +370 -140
- package/src/ui/configure.ts +141 -67
- package/src/ui/diff.ts +1 -2
- package/src/ui/editor.ts +50 -1
- package/src/ui/markdown.ts +258 -0
- package/src/ui/render.ts +35 -48
- package/src/ui/renderers.ts +183 -0
- package/src/ui/screen.ts +113 -16
- package/src/ui/transcript.ts +164 -35
- package/src/ui/tui.tsx +424 -79
- package/src/update.ts +262 -0
package/dist/main.js
CHANGED
|
@@ -4,42 +4,48 @@
|
|
|
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
|
-
import { hasProvider, loadEnvFile, parseTokens } from "./config.js";
|
|
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
|
-
import {
|
|
36
|
+
import { reviewer } from "./plugins/review.js";
|
|
37
|
+
import { clip, shortPath } from "./ui/render.js";
|
|
34
38
|
import { transcript } from "./ui/transcript.js";
|
|
35
39
|
import { run, VERSION } from "./sys.js";
|
|
40
|
+
import { autoUpdate, autoUpdateEnabled, detectInstall, newerVersion, updateCli } from "./update.js";
|
|
36
41
|
const HELP = `Usage: jade [options] [prompt]
|
|
37
42
|
jade plugin <list|add|update|remove|enable|disable> (jade plugin --help)
|
|
43
|
+
jade update [--check] upgrade jade to the latest version on npm
|
|
38
44
|
|
|
39
45
|
-p, --print <prompt> run one prompt and exit
|
|
40
46
|
-c, --continue continue the most recent session in this directory
|
|
41
47
|
-r, --resume [id] resume a session by id, or pick one from a list
|
|
42
|
-
-m, --mode <mode> permission mode: ${MODES.join(" | ")} (default ask)
|
|
48
|
+
-m, --mode <mode> permission mode for this run: ${MODES.join(" | ")} (default: the last mode you switched to, or ask)
|
|
43
49
|
--cwd <dir> working directory (default: current directory)
|
|
44
50
|
-v, --version
|
|
45
51
|
-h, --help
|
|
@@ -52,23 +58,18 @@ const COMMANDS = [
|
|
|
52
58
|
{ name: "help", about: "list the commands and keys" },
|
|
53
59
|
{ name: "model", args: "[name]", about: "switch between saved models, or add one and configure its provider, API key and output limit" },
|
|
54
60
|
{ name: "mode", args: `[${MODES.join("|")}]`, about: "show or change the permission mode" },
|
|
55
|
-
{ name: "
|
|
56
|
-
{ name: "undo", about: "restore every file the agent changed in its last turn (run again to go further back)" },
|
|
57
|
-
{ name: "retry", about: "request the model again after a failed request, without sending another message" },
|
|
58
|
-
{ name: "usage", about: "token usage of this session, including sub-agents and compaction" },
|
|
59
|
-
{ name: "resume", args: "[id]", about: "pick a recent session in this directory and switch to it" },
|
|
60
|
-
{ name: "rules", about: `"always allow" rules of this session` },
|
|
61
|
-
{ name: "plugins", about: "built-in and installed plugins: their tools, hooks and commands" },
|
|
62
|
-
{ name: "hooks", about: "execution order of every extension point" },
|
|
61
|
+
{ name: "plugins", about: "built-in and installed plugins: their tools, hooks and commands, and the hook execution order" },
|
|
63
62
|
{ name: "exit", about: "quit (the session stays resumable)" },
|
|
64
63
|
];
|
|
65
64
|
/** 运行中也立即执行的命令(不碰运行时,或者只读;/mode 运行中先记在 pendingMode) */
|
|
66
|
-
const INSTANT = new Set(["help", "model", "mode", "
|
|
65
|
+
const INSTANT = new Set(["help", "model", "mode", "plugins", "exit"]);
|
|
67
66
|
/** 内置插件提供的命令(/memory 在 jade/memory 里,等等):名字保留给它们,自定义命令不能占用 */
|
|
68
|
-
const BUILTIN_PLUGIN_COMMANDS = ["memory", "checks", "mcp", "skills", "compact"];
|
|
69
|
-
const KEYS = `Keys: enter send · \\ or alt+enter new line · ↑↓ history · @ reference a file · esc interrupt (twice to also clear queued messages) · shift+tab cycle ask/auto
|
|
70
|
-
mouse wheel or PgUp/PgDn scroll the conversation · ctrl+home/ctrl+end jump to the top/bottom · shift+drag selects text
|
|
67
|
+
const BUILTIN_PLUGIN_COMMANDS = ["memory", "checks", "mcp", "skills", "compact", "clear", "resume", "retry", "undo", "search"];
|
|
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
|
|
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
|
|
71
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;
|
|
72
73
|
/** 回复被输出上限截断后,自动让模型接着做的次数(每条用户消息) */
|
|
73
74
|
const MAX_CONTINUES = 3;
|
|
74
75
|
const CONTINUE_NOTE = "Your previous reply was cut off because it reached the output token limit. Continue from where you stopped. " +
|
|
@@ -87,6 +88,8 @@ if (argv[0] === "plugin" || argv[0] === "plugins") {
|
|
|
87
88
|
process.exit(err instanceof UsageError ? 2 : 1);
|
|
88
89
|
}
|
|
89
90
|
}
|
|
91
|
+
if (argv[0] === "update")
|
|
92
|
+
process.exit(await updateCli(argv.slice(1)));
|
|
90
93
|
const opts = { prompt: [] };
|
|
91
94
|
for (let i = 0; i < argv.length; i++) {
|
|
92
95
|
const a = argv[i];
|
|
@@ -154,13 +157,27 @@ if (!(await stat(cwd).catch(() => undefined))?.isDirectory())
|
|
|
154
157
|
const home = process.env.JADE_HOME ?? path.join(os.homedir(), ".jade");
|
|
155
158
|
const envFile = path.join(home, ".env");
|
|
156
159
|
await loadEnvFile(envFile);
|
|
160
|
+
/** 新会话的权限模式:-m 只管这一次;没给时用上次在会话里切换到的模式(JADE_MODE,见 rememberMode),都没有时是 ask */
|
|
161
|
+
const savedMode = process.env.JADE_MODE?.trim();
|
|
162
|
+
const badSavedMode = savedMode && !MODES.includes(savedMode) ? savedMode : undefined;
|
|
163
|
+
if (savedMode && !badSavedMode)
|
|
164
|
+
opts.mode ??= savedMode;
|
|
157
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(() => { });
|
|
158
174
|
if (!hasProvider() && !tui) {
|
|
159
175
|
console.error(`jade: no model is configured.\n\n` +
|
|
160
176
|
`Run jade in a terminal and use /model, or put one of these in ${envFile} (or set them in the shell):\n` +
|
|
161
177
|
` OPENAI_COMPAT_BASE_URL=… OPENAI_COMPAT_API_KEY=… OPENAI_COMPAT_MODEL=… (any /chat/completions service)\n` +
|
|
162
178
|
` OPENAI_API_KEY=… [OPENAI_BASE_URL=… OPENAI_MODEL=…] (OpenAI Responses API)\n` +
|
|
163
|
-
` 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)`);
|
|
164
181
|
process.exit(2);
|
|
165
182
|
}
|
|
166
183
|
// 写错时直接报错:NaN 会让"是否超过阈值"永远为假,每次请求都压缩
|
|
@@ -186,21 +203,35 @@ const modelLabel = () => (hasProvider() ? providerInfo().model || "(no model)" :
|
|
|
186
203
|
let ready = false;
|
|
187
204
|
const early = [];
|
|
188
205
|
const inputs = new InputHistory(path.join(home, "history.jsonl"), cwd);
|
|
189
|
-
/** $JADE_HOME/plugins.json
|
|
206
|
+
/** $JADE_HOME/plugins.json 里停用的插件和内置插件(id) */
|
|
190
207
|
const disabledPlugins = new Set((await readPluginSettings(home)).disabled);
|
|
191
208
|
const repo = realPath(await repoRoot(cwd));
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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;
|
|
202
231
|
/** 自定义命令($JADE_HOME/commands、.jade/commands、插件带的 commands/);和内置命令同名的不生效 */
|
|
203
|
-
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));
|
|
204
235
|
const customLoaded = await loadCommands({ home, root: repo, cwd: realPath(cwd), plugins: bundled((b) => b.commands) });
|
|
205
236
|
const shadowed = customLoaded.filter((c) => builtinNames.has(c.name));
|
|
206
237
|
const customs = new Map(customLoaded.filter((c) => !builtinNames.has(c.name)).map((c) => [c.name, c]));
|
|
@@ -208,10 +239,10 @@ const ALL_COMMANDS = [
|
|
|
208
239
|
...COMMANDS,
|
|
209
240
|
...[...customs.values()].map((c) => ({ name: c.name, args: c.args, about: `${c.description} (${c.plugin ? `plugin ${c.plugin}` : c.layer})` })),
|
|
210
241
|
];
|
|
211
|
-
//
|
|
212
|
-
const screen =
|
|
213
|
-
? (await
|
|
214
|
-
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" },
|
|
215
246
|
version: VERSION,
|
|
216
247
|
commands: ALL_COMMANDS,
|
|
217
248
|
history: await inputs.load(),
|
|
@@ -227,9 +258,10 @@ const screen = tui
|
|
|
227
258
|
exit: () => (ready ? void quit() : process.exit(130)),
|
|
228
259
|
files: () => mentionCandidates(cwd),
|
|
229
260
|
cycleMode: () => ready && cycleMode(),
|
|
261
|
+
key: (spec) => ready && pluginKey(spec),
|
|
230
262
|
},
|
|
231
263
|
})
|
|
232
|
-
: plainScreen({ interactive: Boolean(process.stdin.isTTY) });
|
|
264
|
+
: plainScreen({ interactive: Boolean(process.stdin.isTTY) }));
|
|
233
265
|
/** 压缩、子 Agent 和主循环共用;/model 改配置后换掉里面的实现 */
|
|
234
266
|
const provider = switchable({
|
|
235
267
|
id: "unconfigured",
|
|
@@ -247,16 +279,10 @@ const configure = configurator({
|
|
|
247
279
|
contextWindow: () => contextWindow,
|
|
248
280
|
onApplied: () => screen.status({ model: modelLabel() }),
|
|
249
281
|
});
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
if (!(await configure.provider())) {
|
|
253
|
-
await screen.close();
|
|
254
|
-
process.exit(2);
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
else {
|
|
282
|
+
// 还没配置模型时,等插件加载完再问(见下面 registerProviders 之后):插件提供的服务也要列出来
|
|
283
|
+
if (providerEarly) {
|
|
258
284
|
try {
|
|
259
|
-
provider.set(retrying(await
|
|
285
|
+
provider.set(retrying(await providerEarly));
|
|
260
286
|
}
|
|
261
287
|
catch (err) {
|
|
262
288
|
await screen.close();
|
|
@@ -288,52 +314,153 @@ function retrying(inner) {
|
|
|
288
314
|
waiting = false;
|
|
289
315
|
},
|
|
290
316
|
onRetry: ({ attempt, retries, delayMs, error }) => {
|
|
291
|
-
const why = isRateLimit(error) ? "rate limited" : clip(error.message.replace(/\s+/g, " "), 160);
|
|
292
|
-
|
|
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)}]`));
|
|
293
321
|
waiting = true;
|
|
294
|
-
screen.busy(`Waiting to retry (${attempt}/${retries}, ${seconds(delayMs)})`);
|
|
322
|
+
screen.busy(`Waiting to retry (${why} · ${attempt}/${retries}, ${seconds(delayMs)})`);
|
|
295
323
|
},
|
|
296
324
|
});
|
|
297
325
|
}
|
|
298
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`);
|
|
299
327
|
const store = new JsonlLogStore(path.join(home, "sessions"));
|
|
300
|
-
const trust = new JsonlTrustStore(path.join(home, "trust.jsonl"));
|
|
301
328
|
const index = new SessionIndex(path.join(home, "index.jsonl"));
|
|
302
|
-
/**
|
|
329
|
+
/** 正在退出:这时 MCP 服务断开是预期的,不提示 */
|
|
303
330
|
let pluginsClosing = false;
|
|
304
|
-
|
|
305
|
-
|
|
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;
|
|
306
338
|
for (const w of skillsLoaded.warnings)
|
|
307
339
|
screen.log(yellow(`[warning] ${w}`));
|
|
308
340
|
const skills = skillsLoaded.skills;
|
|
309
|
-
const mcpClients = await
|
|
341
|
+
const mcpClients = await mcpConnecting;
|
|
310
342
|
/**
|
|
311
343
|
* 运行中切换的权限模式:这一轮正占着日志,写不进去。关卡先按它判断(下一个工具调用就生效),
|
|
312
344
|
* 这一轮结束后再记进日志(flushPendingMode)
|
|
313
345
|
*/
|
|
314
346
|
let pendingMode;
|
|
315
|
-
/**
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
347
|
+
/** 当前配置的模型和服务,写进系统提示词,用户问起时模型照这个回答;/model 改了配置后下一次请求就是新的 */
|
|
348
|
+
function currentModel() {
|
|
349
|
+
if (!hasProvider())
|
|
350
|
+
return undefined;
|
|
351
|
+
const info = providerInfo();
|
|
352
|
+
let host;
|
|
353
|
+
try {
|
|
354
|
+
host = info.baseURL ? new URL(info.baseURL).host : undefined;
|
|
355
|
+
}
|
|
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
|
+
}
|
|
365
|
+
const api = { anthropic: "the Anthropic API", openai: "the OpenAI Responses API", "openai-compat": "an OpenAI-compatible API" }[info.kind];
|
|
366
|
+
return { name: info.model, via: host ? `${api} at ${host}` : api };
|
|
367
|
+
}
|
|
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
|
+
}
|
|
462
|
+
if (badSavedMode)
|
|
463
|
+
screen.log(yellow(`[warning] JADE_MODE=${badSavedMode} is not a mode (${MODES.join(", ")}); starting in ${opts.mode ?? "ask"}`));
|
|
337
464
|
for (const c of shadowed)
|
|
338
465
|
screen.log(yellow(`[warning] custom command ${display(cwd, c.file)} is ignored: /${c.name} is a built-in command`));
|
|
339
466
|
// 插件的命令加进菜单(名字在各个会话的实例之间不变)。内置命令和 .jade/commands 里的同名命令优先
|
|
@@ -346,77 +473,41 @@ for (const sk of skills) {
|
|
|
346
473
|
skillCommands.set(name, sk);
|
|
347
474
|
ALL_COMMANDS.push({ name: sk.name, args: "[task]", about: `${clip(sk.description.replace(/\s+/g, " "), 80)} (skill)` });
|
|
348
475
|
}
|
|
349
|
-
//
|
|
350
|
-
const
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
}
|
|
356
|
-
if (builtinNames.has(name) || customs.has(name) || skillCommands.has(name)) {
|
|
357
|
-
const what = builtinNames.has(name) ? "a built-in command" : customs.has(name) ? "a custom command" : "a skill";
|
|
358
|
-
screen.log(yellow(`[warning] command /${c.name} of plugin ${plugin} is ignored: ${what} has that name`));
|
|
359
|
-
continue;
|
|
360
|
-
}
|
|
361
|
-
ALL_COMMANDS.push({ name: c.name, args: c.args, about: `${c.description ?? ""} (plugin ${plugin})`.trim() });
|
|
362
|
-
}
|
|
363
|
-
ALL_COMMANDS.splice(COMMANDS.length, 0, ...builtinPluginCommands);
|
|
364
|
-
/**
|
|
365
|
-
* 第三方插件:$JADE_HOME/plugins/<name>/(用户层)和 .jade/plugins/<name>/(项目层)。
|
|
366
|
-
* 项目层的首次加载及内容变化后要用户确认(7.1)。加载失败的跳过并提示,不影响启动
|
|
367
|
-
*/
|
|
368
|
-
async function loadPlugins() {
|
|
369
|
-
const out = [];
|
|
370
|
-
for (const f of foundPlugins) {
|
|
371
|
-
try {
|
|
372
|
-
const unsupported = pluginInfos.get(f.dir)?.bundle.unsupported ?? [];
|
|
373
|
-
if (unsupported.length)
|
|
374
|
-
screen.log(dim(`[note] plugin ${f.name}: jade does not support its ${unsupported.join(" and ")} yet; they are ignored`));
|
|
375
|
-
out.push(await loadPlugin(f, {
|
|
376
|
-
trust,
|
|
377
|
-
confirm: async ({ path: p, hash, files, command }) => (await screen.select(`Project plugin ${display(cwd, p)} is new or changed. Load and run it?`, [
|
|
378
|
-
{ label: "No", value: false },
|
|
379
|
-
{ label: "Yes, load it", value: true },
|
|
380
|
-
], {
|
|
381
|
-
body: dim(`${command ? `runs: ${command}\n` : ""}sha256 ${hash.slice(0, 12)}, ${files.length} files:\n${files.map((f) => ` ${f}`).join("\n")}`),
|
|
382
|
-
})) ?? false,
|
|
383
|
-
onExit: (p, { code, signal }) => {
|
|
384
|
-
if (!pluginsClosing)
|
|
385
|
-
screen.log(yellow(`[warning] plugin ${p.name} exited (${signal ?? `code ${code}`}); its hooks fail until jade restarts. /plugins shows its stderr`));
|
|
386
|
-
},
|
|
387
|
-
}));
|
|
388
|
-
}
|
|
389
|
-
catch (err) {
|
|
390
|
-
const hint = f.layer === "project" && !tui && err instanceof UntrustedPlugin ? " (run jade interactively in this directory once to confirm it)" : "";
|
|
391
|
-
screen.log(yellow(`[skipped] plugin ${display(cwd, f.dir)}: ${errorText(err)}${hint}`));
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
return out;
|
|
395
|
-
}
|
|
396
|
-
/** 结束进程外插件的进程 */
|
|
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 服务 */
|
|
397
482
|
async function closePlugins() {
|
|
398
483
|
pluginsClosing = true;
|
|
399
|
-
await Promise.all([
|
|
484
|
+
await Promise.all([plugins.close(), ...mcpClients.map((c) => c.close().catch(() => { }))]);
|
|
400
485
|
}
|
|
401
486
|
/**
|
|
402
487
|
* 连接 mcp.json 里配置的 MCP 服务。项目层(随仓库分发)的服务第一次启动前要用户确认,按配置内容记在 trust.jsonl;
|
|
403
|
-
*
|
|
488
|
+
* 连不上的跳过并提示,不影响启动。所有服务并发连接,不用确认的立即开始连。
|
|
489
|
+
* 启动时最多等 MCP_STARTUP_WAIT_MS:还没连上的在后台接着连,它们的工具从下一个会话(/clear)开始提供
|
|
490
|
+
* (一个会话里的工具列表不变,否则提示缓存失效)。
|
|
491
|
+
* dialogsAfter:在它完成之后才弹确认框,不和插件的确认框同时出现
|
|
404
492
|
*/
|
|
405
|
-
async function connectMcp() {
|
|
406
|
-
const
|
|
407
|
-
const mcp =
|
|
408
|
-
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 }] : [];
|
|
409
497
|
});
|
|
410
|
-
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 });
|
|
411
499
|
for (const w of warnings)
|
|
412
500
|
screen.log(yellow(`[warning] ${w}`));
|
|
413
501
|
const clients = [];
|
|
502
|
+
const connecting = [];
|
|
414
503
|
for (const entry of servers) {
|
|
415
504
|
if (entry.config.disabled)
|
|
416
505
|
continue;
|
|
417
506
|
if (entry.layer === "project") {
|
|
418
507
|
const hash = mcpTrustHash(repo, entry);
|
|
419
508
|
if (!(await trust.has(hash))) {
|
|
509
|
+
if (tui)
|
|
510
|
+
await dialogsAfter.catch(() => { });
|
|
420
511
|
const ok = tui
|
|
421
512
|
? ((await screen.select(`MCP server "${entry.name}" from ${display(cwd, entry.file)} is new or changed. Start it?`, [
|
|
422
513
|
{ label: "No", value: false },
|
|
@@ -430,19 +521,32 @@ async function connectMcp() {
|
|
|
430
521
|
await trust.add({ hash, path: entry.file, at: new Date().toISOString() });
|
|
431
522
|
}
|
|
432
523
|
}
|
|
433
|
-
|
|
524
|
+
const client = new McpClient(entry, {
|
|
434
525
|
cwd,
|
|
435
526
|
onDisconnect: (c, why) => {
|
|
436
527
|
if (!pluginsClosing)
|
|
437
528
|
screen.log(yellow(`[warning] MCP server ${c.name} disconnected: ${why}. jade reconnects on its next tool call; /mcp shows details`));
|
|
438
529
|
},
|
|
439
|
-
})
|
|
530
|
+
});
|
|
531
|
+
clients.push(client);
|
|
532
|
+
connecting.push(client.connect().catch((err) => screen.log(yellow(`[warning] MCP server ${client.name} is unavailable: ${errorText(err)}`))));
|
|
440
533
|
}
|
|
441
534
|
if (clients.length === 0)
|
|
442
535
|
return clients;
|
|
443
536
|
screen.busy(`Connecting to ${clients.length} MCP server${clients.length > 1 ? "s" : ""}`);
|
|
444
|
-
|
|
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);
|
|
445
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
|
+
}
|
|
446
550
|
return clients;
|
|
447
551
|
}
|
|
448
552
|
let resumeId = opts.resume;
|
|
@@ -454,7 +558,7 @@ if (resumeId === "") {
|
|
|
454
558
|
resumeId = await pickSession();
|
|
455
559
|
}
|
|
456
560
|
else if (resumeId)
|
|
457
|
-
resumeId = await
|
|
561
|
+
resumeId = matchSession(await index.list(cwd), resumeId);
|
|
458
562
|
if (opts.cont) {
|
|
459
563
|
resumeId = (await index.list(cwd))[0]?.id;
|
|
460
564
|
if (!resumeId) {
|
|
@@ -463,19 +567,36 @@ if (opts.cont) {
|
|
|
463
567
|
}
|
|
464
568
|
}
|
|
465
569
|
// /clear 换成新的运行时和会话
|
|
466
|
-
let rt
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
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));
|
|
470
579
|
// 权限设置记在日志里(derived),关卡从那里读,恢复会话后仍然有效
|
|
471
|
-
|
|
580
|
+
// 主会话不会是 readonly(只给子 Agent 用;旧会话里记的 readonly 由关卡换成 plan)
|
|
581
|
+
// 只取这一项:rt.state 每次都拷贝整段历史,而这里调用得很频繁(子 Agent 的每次关卡判断都会调用)
|
|
582
|
+
const settings = () => jade.policy.settings({ [POLICY_KEY]: rt.derived(POLICY_KEY) });
|
|
472
583
|
const saveSettings = async (next) => {
|
|
473
584
|
await rt.record(POLICY_KEY, next);
|
|
474
585
|
pendingMode = undefined;
|
|
475
586
|
screen.status({ mode: next.mode });
|
|
476
587
|
};
|
|
588
|
+
/**
|
|
589
|
+
* 用户切换的模式记进 $JADE_HOME/.env 的 JADE_MODE,之后新开的会话默认用它(恢复的会话仍用它自己记下的模式)。
|
|
590
|
+
* yolo 不记:免得以后一打开就什么都不问;要默认 yolo 可以手动写 JADE_MODE=yolo 或用 -m yolo
|
|
591
|
+
*/
|
|
592
|
+
async function rememberMode(mode) {
|
|
593
|
+
if (mode === "yolo" || process.env.JADE_MODE === mode)
|
|
594
|
+
return;
|
|
595
|
+
await updateEnvFile(envFile, { JADE_MODE: mode }).catch((err) => screen.log(yellow(`[warning] could not remember the mode in ${envFile}: ${errorText(err)}`)));
|
|
596
|
+
}
|
|
477
597
|
/** 换权限模式;运行时正在执行这一轮时先记在 pendingMode,关卡立即按它判断,这一轮结束后再写进日志 */
|
|
478
598
|
async function setMode(mode) {
|
|
599
|
+
await rememberMode(mode);
|
|
479
600
|
try {
|
|
480
601
|
await saveSettings({ ...settings(), mode });
|
|
481
602
|
}
|
|
@@ -499,31 +620,40 @@ async function flushPendingMode() {
|
|
|
499
620
|
}
|
|
500
621
|
}
|
|
501
622
|
// ---------- 渲染 ----------
|
|
502
|
-
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) });
|
|
503
624
|
rt.subscribe(view.onNotice);
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
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)})`;
|
|
508
631
|
if (!screen.interactive) {
|
|
509
632
|
screen.log(red(`✗ ${who}${head} denied: not running interactively`));
|
|
510
633
|
return { approved: false, reason: "The user is not available to approve this action." };
|
|
511
634
|
}
|
|
512
635
|
const rule = jade.policy.ruleFor(c);
|
|
513
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));
|
|
514
639
|
const answer = await screen.select(`Allow ${who}${head}?`, [
|
|
515
640
|
{ label: "Yes", value: "yes" },
|
|
516
641
|
{ label: `Yes, and always allow ${always} in this session`, value: "always" },
|
|
517
642
|
{ label: "No, and tell jade what to do instead", value: "no" },
|
|
518
|
-
], { body
|
|
643
|
+
], { body, signal });
|
|
644
|
+
signal?.throwIfAborted();
|
|
519
645
|
if (answer === "always")
|
|
520
646
|
await remember(rule);
|
|
521
647
|
const approved = answer === "yes" || answer === "always";
|
|
522
|
-
const
|
|
523
|
-
|
|
524
|
-
|
|
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.";
|
|
525
652
|
// 主 Agent 的调用的结果之后接在这一行后面
|
|
526
|
-
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)}` : ""), {
|
|
654
|
+
id: c.toolUseId,
|
|
655
|
+
details: view.details(c.name, c.input),
|
|
656
|
+
});
|
|
527
657
|
return { approved, reason };
|
|
528
658
|
}
|
|
529
659
|
async function approvePending() {
|
|
@@ -547,22 +677,51 @@ let subagentAsking = Promise.resolve();
|
|
|
547
677
|
function approveSubagent(...[c, signal]) {
|
|
548
678
|
const turn = subagentAsking.then(() => {
|
|
549
679
|
signal.throwIfAborted();
|
|
550
|
-
//
|
|
551
|
-
return
|
|
680
|
+
// 中断时不再等用户回答,对话框和插件那边的请求一起关掉
|
|
681
|
+
return ask(c, "sub-agent ", (rule) => void pendingRules.push(rule), signal);
|
|
552
682
|
});
|
|
553
683
|
subagentAsking = turn.catch(() => { });
|
|
554
684
|
return turn;
|
|
555
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
|
+
}
|
|
556
709
|
/** 编辑后检查的确认记录:同一个目录里的同一条命令只问一次,记在 trust.jsonl */
|
|
557
710
|
const checkHash = (c) => createHash("sha256").update(`jade-check\0${c.cwd}\0${c.command}`).digest("hex");
|
|
711
|
+
const confirmedChecks = new Set();
|
|
558
712
|
/**
|
|
559
713
|
* 编辑后检查的命令第一次运行前问用户:它会执行仓库里的代码(node_modules 里的 tsc、配置里的命令)。
|
|
560
714
|
* yolo 模式不问;不能交互时不运行
|
|
561
715
|
*/
|
|
562
716
|
async function approveCheck(c, signal) {
|
|
563
717
|
const hash = checkHash(c);
|
|
564
|
-
|
|
718
|
+
// 每批修改都会问一次:确认过的记在内存里,不用每次重读、解析整份 trust.jsonl
|
|
719
|
+
if (confirmedChecks.has(hash))
|
|
565
720
|
return true;
|
|
721
|
+
if (await trust.has(hash)) {
|
|
722
|
+
confirmedChecks.add(hash);
|
|
723
|
+
return true;
|
|
724
|
+
}
|
|
566
725
|
if (settings().mode === "yolo")
|
|
567
726
|
return true;
|
|
568
727
|
if (!screen.interactive)
|
|
@@ -576,8 +735,10 @@ async function approveCheck(c, signal) {
|
|
|
576
735
|
});
|
|
577
736
|
subagentAsking = run.catch(() => { });
|
|
578
737
|
const ok = (await run) ?? false;
|
|
579
|
-
if (ok)
|
|
738
|
+
if (ok) {
|
|
580
739
|
await trust.add({ hash, path: c.cwd, at: new Date().toISOString() });
|
|
740
|
+
confirmedChecks.add(hash);
|
|
741
|
+
}
|
|
581
742
|
else
|
|
582
743
|
screen.log(dim(`[${c.name} will not run in this session; /checks on to ask again]`));
|
|
583
744
|
return ok;
|
|
@@ -587,8 +748,10 @@ async function approveCheck(c, signal) {
|
|
|
587
748
|
function skillMessage(name, args) {
|
|
588
749
|
return `Use the "${name}" skill${args.trim() ? ` for this: ${args.trim()}` : "."}`;
|
|
589
750
|
}
|
|
590
|
-
/** 正在执行的插件命令;esc
|
|
591
|
-
|
|
751
|
+
/** 正在执行的插件命令;esc 中断它们。instant 的命令可以在另一个命令的模型回合里执行,所以可能同时有几个 */
|
|
752
|
+
const commandAborts = new Set();
|
|
753
|
+
/** 插件命令经 session 发起的换会话、重试:命令被 esc 中断后也要等它收尾,再处理下一条输入 */
|
|
754
|
+
let sessionWork;
|
|
592
755
|
/** 执行插件的斜杠命令,返回要发给模型的提示词(没有就是 undefined) */
|
|
593
756
|
async function pluginCommand(name, args) {
|
|
594
757
|
const found = jade.commands.get(name.toLowerCase());
|
|
@@ -597,7 +760,7 @@ async function pluginCommand(name, args) {
|
|
|
597
760
|
return undefined;
|
|
598
761
|
}
|
|
599
762
|
const ac = new AbortController();
|
|
600
|
-
|
|
763
|
+
commandAborts.add(ac);
|
|
601
764
|
try {
|
|
602
765
|
const result = await abortable(Promise.resolve(found.command.run(args, {
|
|
603
766
|
sessionId,
|
|
@@ -611,6 +774,8 @@ async function pluginCommand(name, args) {
|
|
|
611
774
|
input: (title, o) => screen.input(title, o),
|
|
612
775
|
},
|
|
613
776
|
note: (text) => void notes.push(text),
|
|
777
|
+
// instant 的命令在模型工作时执行,不能换会话、写日志
|
|
778
|
+
session: found.command.instant ? undefined : sessionControl(found.plugin),
|
|
614
779
|
})), ac.signal);
|
|
615
780
|
if (typeof result === "string") {
|
|
616
781
|
if (result)
|
|
@@ -628,14 +793,42 @@ async function pluginCommand(name, args) {
|
|
|
628
793
|
return undefined;
|
|
629
794
|
}
|
|
630
795
|
catch (err) {
|
|
631
|
-
|
|
796
|
+
// 用户按 esc 中断的不算出错
|
|
797
|
+
if (!ac.signal.aborted)
|
|
798
|
+
screen.log(red(`[error] /${found.command.name} (plugin ${found.plugin}): ${errorText(err)}`));
|
|
632
799
|
return undefined;
|
|
633
800
|
}
|
|
634
801
|
finally {
|
|
635
|
-
|
|
636
|
-
|
|
802
|
+
// instant 的命令没有 session,不会发起 sessionWork;运行中的是别的命令发起的,不能替它等、替它清掉
|
|
803
|
+
if (!found.command.instant) {
|
|
804
|
+
await sessionWork?.catch(() => { });
|
|
805
|
+
sessionWork = undefined;
|
|
806
|
+
}
|
|
807
|
+
commandAborts.delete(ac);
|
|
637
808
|
}
|
|
638
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
|
+
}
|
|
639
832
|
/** /plugins:内置插件的状态,每个第三方插件的来源、工具、hook、命令和带的内容;跳过的插件在启动时已经提示过 */
|
|
640
833
|
function showPlugins() {
|
|
641
834
|
const width = Math.max(...jade.builtins.map((b) => b.id.length)) + 2;
|
|
@@ -650,30 +843,36 @@ function showPlugins() {
|
|
|
650
843
|
lines.push(dim(` (none) put plugins in ${display(cwd, path.join(home, "plugins"))}/<name>/ or .jade/plugins/<name>/`));
|
|
651
844
|
}
|
|
652
845
|
const carried = (b) => [b.skills.length ? "skills" : "", b.commands.length ? "commands" : "", b.mcp ? "MCP servers" : ""].filter(Boolean).join(", ");
|
|
653
|
-
for (const { source, plugin } of jade.extensions) {
|
|
846
|
+
for (const { source, plugin, commands, keys } of jade.extensions) {
|
|
654
847
|
const exit = source.process?.exited;
|
|
655
848
|
const state = source.kind === "process" ? (exit ? red(` exited (${exit.signal ?? `code ${exit.code}`})`) : green(" running")) : "";
|
|
656
849
|
lines.push(`${bold(plugin.id)} ${plugin.version} ${dim(`${source.layer} · ${display(cwd, source.dir)} · ${source.kind === "process" ? `runs ${source.entry}` : source.entry}`)}${state}`);
|
|
657
850
|
const tools = (plugin.tools ?? []).map((t) => `${t.name} (${t.effect})`);
|
|
658
851
|
const hooks = [...new Set((plugin.hooks ?? []).map((h) => `${h.kind}:${h.point}`))];
|
|
659
|
-
const cmds =
|
|
852
|
+
const cmds = commands.map((c) => `/${c.name}`);
|
|
660
853
|
if (tools.length)
|
|
661
854
|
lines.push(` tools ${tools.join(", ")}`);
|
|
662
855
|
if (hooks.length)
|
|
663
856
|
lines.push(` hooks ${hooks.join(", ")}`);
|
|
664
857
|
if (cmds.length)
|
|
665
858
|
lines.push(` commands ${cmds.join(", ")}`);
|
|
666
|
-
if (
|
|
667
|
-
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(", ")}`);
|
|
668
863
|
if (carried(source.info.bundle))
|
|
669
864
|
lines.push(` carries ${carried(source.info.bundle)}`);
|
|
670
865
|
if (exit && source.process.stderr.length)
|
|
671
866
|
lines.push(dim(source.process.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
|
|
672
867
|
}
|
|
673
868
|
for (const p of contentOnly) {
|
|
674
|
-
lines.push(`${bold(p.
|
|
869
|
+
lines.push(`${bold(p.id)}${p.info.version ? ` ${p.info.version}` : ""} ${dim(`${p.layer} · ${display(cwd, p.dir)}`)}`);
|
|
675
870
|
lines.push(` carries ${carried(p.info.bundle)}`);
|
|
676
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
|
+
}
|
|
677
876
|
screen.log(lines.join("\n"));
|
|
678
877
|
}
|
|
679
878
|
async function savePendingRules() {
|
|
@@ -682,9 +881,12 @@ async function savePendingRules() {
|
|
|
682
881
|
const s = settings();
|
|
683
882
|
await saveSettings({ ...s, rules: [...s.rules, ...pendingRules.splice(0)] });
|
|
684
883
|
}
|
|
884
|
+
/** p 和 signal 谁先结束用谁:signal 中止时以它的 reason 拒绝 */
|
|
685
885
|
function abortable(p, signal) {
|
|
686
886
|
return new Promise((resolve, reject) => {
|
|
687
887
|
const stop = () => reject(signal.reason);
|
|
888
|
+
if (signal.aborted)
|
|
889
|
+
return stop();
|
|
688
890
|
signal.addEventListener("abort", stop, { once: true });
|
|
689
891
|
p.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
|
|
690
892
|
});
|
|
@@ -723,7 +925,8 @@ function interrupt() {
|
|
|
723
925
|
const again = interruptPending || Date.now() - interruptedAt < SECOND_ESC_MS;
|
|
724
926
|
interruptedAt = Date.now();
|
|
725
927
|
interruptPending = true;
|
|
726
|
-
|
|
928
|
+
for (const ac of commandAborts)
|
|
929
|
+
ac.abort(new Error("interrupted by user"));
|
|
727
930
|
rt.abort("interrupted by user");
|
|
728
931
|
screen.busy("Interrupting");
|
|
729
932
|
if (queue.length === 0)
|
|
@@ -741,16 +944,8 @@ function interrupt() {
|
|
|
741
944
|
* 离开会话但保留它:写入 session.detached,插件的收尾写入完成后再退出(4.2)。
|
|
742
945
|
* 没收到过输入的会话没什么可恢复的,删掉它的日志;返回会话是否保留了下来
|
|
743
946
|
*/
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
try {
|
|
747
|
-
await rt.detach();
|
|
748
|
-
return !(await discardIfEmpty(store, sessionId));
|
|
749
|
-
}
|
|
750
|
-
catch (err) {
|
|
751
|
-
screen.log(red(`[error] ${errorText(err)}`));
|
|
752
|
-
return true;
|
|
753
|
-
}
|
|
947
|
+
function leave() {
|
|
948
|
+
return sessions.leave();
|
|
754
949
|
}
|
|
755
950
|
/** 关掉界面后再提示怎么恢复:终端界面退出备用屏幕后,里面的内容就看不到了 */
|
|
756
951
|
async function closeScreen() {
|
|
@@ -768,6 +963,7 @@ async function quit(code = 0) {
|
|
|
768
963
|
// 中断后等这一轮收尾,再写 session.detached;pump 看到 quitting 就不再取排队的输入
|
|
769
964
|
await work?.catch(() => { });
|
|
770
965
|
await leave();
|
|
966
|
+
await sessions.settled();
|
|
771
967
|
await closePlugins();
|
|
772
968
|
await closeScreen();
|
|
773
969
|
process.exit(code);
|
|
@@ -779,24 +975,17 @@ async function quit(code = 0) {
|
|
|
779
975
|
*/
|
|
780
976
|
async function switchSession(id) {
|
|
781
977
|
await flushPendingMode();
|
|
782
|
-
|
|
783
|
-
const next = await makeJade(mode);
|
|
784
|
-
let nextRt;
|
|
978
|
+
let switched;
|
|
785
979
|
try {
|
|
786
|
-
|
|
787
|
-
? await Runtime.resume({ store, provider, plugins: next.plugins, sessionId: id })
|
|
788
|
-
: await Runtime.create({ store, provider, plugins: next.plugins });
|
|
980
|
+
switched = await sessions.switchTo(id, settings().mode);
|
|
789
981
|
}
|
|
790
982
|
catch (err) {
|
|
791
|
-
|
|
792
|
-
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)}`));
|
|
793
985
|
}
|
|
794
|
-
const kept =
|
|
795
|
-
|
|
796
|
-
jade = next;
|
|
797
|
-
rt = nextRt;
|
|
986
|
+
const { previous: old, kept } = switched;
|
|
987
|
+
adopt(sessions.current);
|
|
798
988
|
rt.subscribe(view.onNotice);
|
|
799
|
-
sessionId = rt.state.sessionId;
|
|
800
989
|
view.reset();
|
|
801
990
|
notes.length = 0;
|
|
802
991
|
announcedMode = undefined;
|
|
@@ -810,35 +999,42 @@ async function switchSession(id) {
|
|
|
810
999
|
await switchSession();
|
|
811
1000
|
}
|
|
812
1001
|
}
|
|
813
|
-
/**
|
|
814
|
-
|
|
815
|
-
|
|
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);
|
|
816
1032
|
if (all.length === 0) {
|
|
817
1033
|
screen.log(dim(`No other sessions in ${shortPath(cwd)}.`));
|
|
818
1034
|
return undefined;
|
|
819
1035
|
}
|
|
820
1036
|
return screen.select("Resume which session?", all.map((s) => ({ label: s.title || "(untitled)", value: s.id, hint: `${ago(s.at)} · ${s.id}` })));
|
|
821
1037
|
}
|
|
822
|
-
/** 这个目录的会话里 id 等于 arg 或以它开头的唯一一个;都不是时原样返回,交给 Runtime.resume 去找 */
|
|
823
|
-
async function findSession(arg) {
|
|
824
|
-
const hits = (await index.list(cwd)).filter((s) => s.id.startsWith(arg));
|
|
825
|
-
return hits.find((s) => s.id === arg)?.id ?? (hits.length === 1 ? hits[0].id : arg);
|
|
826
|
-
}
|
|
827
|
-
/** 显示用的相对时间 */
|
|
828
|
-
function ago(iso) {
|
|
829
|
-
const s = (Date.now() - Date.parse(iso)) / 1000;
|
|
830
|
-
if (!Number.isFinite(s))
|
|
831
|
-
return iso;
|
|
832
|
-
if (s < 60)
|
|
833
|
-
return "just now";
|
|
834
|
-
if (s < 3600)
|
|
835
|
-
return `${Math.floor(s / 60)} min ago`;
|
|
836
|
-
if (s < 86400)
|
|
837
|
-
return `${Math.floor(s / 3600)} h ago`;
|
|
838
|
-
if (s < 86400 * 7)
|
|
839
|
-
return `${Math.floor(s / 86400)} d ago`;
|
|
840
|
-
return iso.slice(0, 10);
|
|
841
|
-
}
|
|
842
1038
|
process.on("SIGINT", () => (running ? interrupt() : void quit(130)));
|
|
843
1039
|
/** guarded 里最近一次抛出的错误;每次 guarded 开始时清掉 */
|
|
844
1040
|
let lastThrown;
|
|
@@ -875,8 +1071,8 @@ function announceMode() {
|
|
|
875
1071
|
notes.push(PLAN_OFF);
|
|
876
1072
|
announcedMode = mode;
|
|
877
1073
|
}
|
|
878
|
-
/** Shift+Tab:ask → auto
|
|
879
|
-
const CYCLE = ["ask", "auto
|
|
1074
|
+
/** Shift+Tab:ask → auto → plan → ask;yolo 也回到 ask。运行中也能切换,从下一个工具调用起生效 */
|
|
1075
|
+
const CYCLE = ["ask", "auto", "plan"];
|
|
880
1076
|
function cycleMode() {
|
|
881
1077
|
const i = CYCLE.indexOf(settings().mode);
|
|
882
1078
|
setMode(CYCLE[(i + 1) % CYCLE.length]).catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
|
|
@@ -893,12 +1089,13 @@ async function offerPlan() {
|
|
|
893
1089
|
if (last?.role !== "assistant" || !last.content.some((b) => b.kind === "text" && b.text.trim()))
|
|
894
1090
|
return;
|
|
895
1091
|
const choice = await screen.select("Execute this plan?", [
|
|
896
|
-
{ label: "Yes,
|
|
1092
|
+
{ label: "Yes, in auto mode", value: "auto", hint: "edits and safe commands run without asking" },
|
|
897
1093
|
{ label: "Yes, and ask before each edit", value: "ask", hint: "mode ask" },
|
|
898
1094
|
{ label: "No, keep planning", value: "plan", hint: "type what to change" },
|
|
899
1095
|
]);
|
|
900
1096
|
if (!choice || choice === "plan")
|
|
901
1097
|
return;
|
|
1098
|
+
await rememberMode(choice);
|
|
902
1099
|
await saveSettings({ ...settings(), mode: choice });
|
|
903
1100
|
screen.log(dim(`mode: ${choice}`));
|
|
904
1101
|
await say("The plan is approved. Implement it now.");
|
|
@@ -924,14 +1121,39 @@ async function say(text) {
|
|
|
924
1121
|
await drive({ kind: "message", content });
|
|
925
1122
|
await offerPlan();
|
|
926
1123
|
}
|
|
927
|
-
/**
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
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;
|
|
933
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";
|
|
934
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."));
|
|
935
1157
|
// 计时从这次输入开始,不接着上一条排队消息的
|
|
936
1158
|
screen.busy(undefined);
|
|
937
1159
|
screen.busy("Working");
|
|
@@ -952,43 +1174,6 @@ async function drive(input) {
|
|
|
952
1174
|
}
|
|
953
1175
|
await savePendingRules().catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
|
|
954
1176
|
}
|
|
955
|
-
/** 撤销最近一轮里还没撤销的全部文件修改:同一个文件改过几次的,恢复到这一轮改它之前的样子 */
|
|
956
|
-
async function undo() {
|
|
957
|
-
const undone = new Set(rt.state.derived[UNDO_KEY]?.undone ?? []);
|
|
958
|
-
const cps = lastTurnChanges(rt.state.messages, await jade.checkpoints.list(sessionId), undone);
|
|
959
|
-
if (cps.length === 0)
|
|
960
|
-
return screen.log(dim("Nothing to undo."));
|
|
961
|
-
/** 文件 → 这一轮最早的快照(恢复成它的 before);cps 是最新的在前 */
|
|
962
|
-
const files = new Map();
|
|
963
|
-
for (const cp of cps)
|
|
964
|
-
files.set(cp.path, cp);
|
|
965
|
-
// 只有最新一次写入之后的内容能和文件现在的样子比较
|
|
966
|
-
const latest = new Map();
|
|
967
|
-
for (const cp of cps)
|
|
968
|
-
if (!latest.has(cp.path))
|
|
969
|
-
latest.set(cp.path, cp);
|
|
970
|
-
const changed = [];
|
|
971
|
-
for (const cp of latest.values())
|
|
972
|
-
if (!(await jade.checkpoints.unchangedSince(cp)))
|
|
973
|
-
changed.push(display(cwd, cp.path));
|
|
974
|
-
const list = [...files.values()].map((cp) => ` ${cp.before === null ? "delete " : "restore"} ${display(cwd, cp.path)}`).join("\n");
|
|
975
|
-
if (files.size > 1 || changed.length > 0) {
|
|
976
|
-
const ok = await screen.select(changed.length > 0
|
|
977
|
-
? `${changed.join(", ")} changed since the agent wrote ${changed.length > 1 ? "them" : "it"}. Undo anyway and discard those changes too?`
|
|
978
|
-
: `Undo the agent's last turn of changes (${files.size} files)?`, [
|
|
979
|
-
{ label: "No", value: false },
|
|
980
|
-
{ label: changed.length > 0 ? "Yes, undo anyway" : "Yes, undo", value: true },
|
|
981
|
-
], { body: list });
|
|
982
|
-
if (!ok)
|
|
983
|
-
return;
|
|
984
|
-
}
|
|
985
|
-
for (const cp of cps)
|
|
986
|
-
await jade.checkpoints.restore(cp);
|
|
987
|
-
await rt.record(UNDO_KEY, { undone: [...undone, ...cps.map((c) => c.toolUseId)] });
|
|
988
|
-
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`);
|
|
989
|
-
notes.push(`The user undid your changes from your last turn: ${what.join("; ")}. Read these files again before changing them.`);
|
|
990
|
-
screen.log(green(`Undid ${cps.length} change${cps.length > 1 ? "s" : ""} from the last turn:`) + "\n" + dim(list));
|
|
991
|
-
}
|
|
992
1177
|
/** 恢复的会话里已有的内容:终端界面里重新显示对话,逐行输出时只统计用量 */
|
|
993
1178
|
async function replayHistory() {
|
|
994
1179
|
await view.replay(await readAll(store, sessionId), tui);
|
|
@@ -1018,7 +1203,6 @@ async function resumeSession() {
|
|
|
1018
1203
|
screen.log(dim(`Resumed ${sessionId} (${rt.state.messages.length} messages, mode ${settings().mode})`));
|
|
1019
1204
|
return true;
|
|
1020
1205
|
}
|
|
1021
|
-
/** /memory:不带参数时列出记忆,可以删掉一条或新加一条;带参数时记下这段话 */
|
|
1022
1206
|
// ---------- 命令 ----------
|
|
1023
1207
|
const commandWidth = () => Math.max(...ALL_COMMANDS.map((c) => `/${c.name}${c.args ? ` ${c.args}` : ""}`.length)) + 2;
|
|
1024
1208
|
/** 执行命令;返回 false 表示退出 */
|
|
@@ -1028,6 +1212,8 @@ async function command(input) {
|
|
|
1028
1212
|
case "help":
|
|
1029
1213
|
screen.log(ALL_COMMANDS.map((c) => `${`/${c.name}${c.args ? ` ${c.args}` : ""}`.padEnd(commandWidth())}${dim(c.about)}`).join("\n"));
|
|
1030
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(" · ")}`));
|
|
1031
1217
|
break;
|
|
1032
1218
|
case "model":
|
|
1033
1219
|
await configure.model(rest[0]);
|
|
@@ -1044,47 +1230,14 @@ async function command(input) {
|
|
|
1044
1230
|
else
|
|
1045
1231
|
await setMode(m);
|
|
1046
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")}`));
|
|
1047
1235
|
break;
|
|
1048
1236
|
}
|
|
1049
|
-
case "undo":
|
|
1050
|
-
await undo();
|
|
1051
|
-
break;
|
|
1052
|
-
case "retry":
|
|
1053
|
-
await retry();
|
|
1054
|
-
break;
|
|
1055
|
-
case "clear":
|
|
1056
|
-
await switchSession();
|
|
1057
|
-
break;
|
|
1058
|
-
case "resume":
|
|
1059
|
-
case "sessions": {
|
|
1060
|
-
const id = rest[0] ? await findSession(rest[0]) : await pickSession(sessionId);
|
|
1061
|
-
if (!id)
|
|
1062
|
-
break;
|
|
1063
|
-
if (id === sessionId)
|
|
1064
|
-
screen.log(dim("That is the current session."));
|
|
1065
|
-
else
|
|
1066
|
-
await switchSession(id);
|
|
1067
|
-
break;
|
|
1068
|
-
}
|
|
1069
|
-
case "hooks":
|
|
1070
|
-
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"]) {
|
|
1071
|
-
screen.log(`${p.padEnd(16)} ${rt.hookOrder(p).join(" → ") || dim("(none)")}`);
|
|
1072
|
-
}
|
|
1073
|
-
break;
|
|
1074
1237
|
case "plugins":
|
|
1075
1238
|
showPlugins();
|
|
1076
1239
|
break;
|
|
1077
|
-
case "rules":
|
|
1078
|
-
screen.log(settings().rules.length ? settings().rules.map(describeRule).join("\n") : dim("(none)"));
|
|
1079
|
-
break;
|
|
1080
|
-
case "usage":
|
|
1081
|
-
screen.log(`input ${view.usage.inputTokens} output ${view.usage.outputTokens} cache read ${view.usage.cacheReadTokens} cache write ${view.usage.cacheWriteTokens} ` +
|
|
1082
|
-
`cache hit ${percent(view.usage.cacheReadTokens, view.usage.inputTokens)}`);
|
|
1083
|
-
screen.log(dim(`context window ${contextWindow} (${{ env: "JADE_CONTEXT_WINDOW", model: `known for ${modelLabel()}`, default: "default for unknown models" }[contextWindowInfo().source]}), ` +
|
|
1084
|
-
`compacts at ${compactAt()}${compactTokens !== undefined ? " (JADE_COMPACT_TOKENS)" : ""}`));
|
|
1085
|
-
break;
|
|
1086
1240
|
case "exit":
|
|
1087
|
-
case "quit":
|
|
1088
1241
|
return false;
|
|
1089
1242
|
default: {
|
|
1090
1243
|
const custom = customs.get(cmd.toLowerCase());
|
|
@@ -1111,10 +1264,9 @@ async function command(input) {
|
|
|
1111
1264
|
}
|
|
1112
1265
|
const MODE_HINTS = {
|
|
1113
1266
|
ask: "ask before edits and commands",
|
|
1114
|
-
|
|
1115
|
-
yolo: "never ask",
|
|
1116
|
-
readonly: "read only, no edits or commands",
|
|
1267
|
+
auto: "edits in this directory run without asking; other commands are reviewed by the model, risky ones still ask",
|
|
1117
1268
|
plan: "research read-only and propose a plan; edits start after you approve it",
|
|
1269
|
+
yolo: "never ask",
|
|
1118
1270
|
};
|
|
1119
1271
|
// ---------- 输入 ----------
|
|
1120
1272
|
/** 等待执行的输入:运行中提交的消息和需要独占运行时的命令排在这里,按顺序执行 */
|
|
@@ -1142,7 +1294,7 @@ function instantPlugin(name) {
|
|
|
1142
1294
|
return false;
|
|
1143
1295
|
if (found.builtin)
|
|
1144
1296
|
return true;
|
|
1145
|
-
return !
|
|
1297
|
+
return !hostNames.has(n) && !customs.has(n) && !skillCommands.has(n);
|
|
1146
1298
|
}
|
|
1147
1299
|
async function pump() {
|
|
1148
1300
|
if (running)
|
|
@@ -1175,6 +1327,28 @@ async function pump() {
|
|
|
1175
1327
|
if (exit)
|
|
1176
1328
|
await quit();
|
|
1177
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
|
+
}
|
|
1178
1352
|
// ---------- 开始 ----------
|
|
1179
1353
|
if (resumeId) {
|
|
1180
1354
|
let ok = false;
|
|
@@ -1195,6 +1369,7 @@ if (tui) {
|
|
|
1195
1369
|
ready = true;
|
|
1196
1370
|
for (const text of [...(first ? [first] : []), ...early.splice(0)])
|
|
1197
1371
|
onSubmit(text);
|
|
1372
|
+
void checkForUpdate();
|
|
1198
1373
|
}
|
|
1199
1374
|
else {
|
|
1200
1375
|
// -p 也能用自定义命令和插件的命令(内置命令需要交互,不在这里处理)
|
|
@@ -1203,11 +1378,12 @@ else {
|
|
|
1203
1378
|
const custom = name !== undefined ? customs.get(name) : undefined;
|
|
1204
1379
|
await occupy(async () => {
|
|
1205
1380
|
const skill = name !== undefined && !custom ? skillCommands.get(name) : undefined;
|
|
1206
|
-
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;
|
|
1207
1382
|
if (text)
|
|
1208
1383
|
await say(text);
|
|
1209
1384
|
});
|
|
1210
1385
|
await leave();
|
|
1386
|
+
await sessions.settled();
|
|
1211
1387
|
await closePlugins();
|
|
1212
1388
|
await closeScreen();
|
|
1213
1389
|
}
|