@uncarved/jade 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/README.md +204 -198
  2. package/bin/jade.js +23 -0
  3. package/dist/commands.d.ts +20 -0
  4. package/dist/commands.js +20 -0
  5. package/dist/commands.js.map +1 -1
  6. package/dist/distro.d.ts +43 -6
  7. package/dist/distro.js +198 -48
  8. package/dist/distro.js.map +1 -1
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.js +2 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/main.js +436 -300
  13. package/dist/main.js.map +1 -1
  14. package/dist/plugin-cli.d.ts +1 -1
  15. package/dist/plugin-cli.js +79 -36
  16. package/dist/plugin-cli.js.map +1 -1
  17. package/dist/plugins/budget.d.ts +2 -2
  18. package/dist/plugins/budget.js +2 -2
  19. package/dist/plugins/budget.js.map +1 -1
  20. package/dist/plugins/builtins.js +6 -3
  21. package/dist/plugins/builtins.js.map +1 -1
  22. package/dist/plugins/checks.d.ts +2 -1
  23. package/dist/plugins/checks.js +25 -5
  24. package/dist/plugins/checks.js.map +1 -1
  25. package/dist/plugins/compact.js +45 -1
  26. package/dist/plugins/compact.js.map +1 -1
  27. package/dist/plugins/core.d.ts +5 -0
  28. package/dist/plugins/core.js +39 -0
  29. package/dist/plugins/core.js.map +1 -1
  30. package/dist/plugins/host.d.ts +52 -0
  31. package/dist/plugins/host.js +115 -0
  32. package/dist/plugins/host.js.map +1 -0
  33. package/dist/plugins/install.d.ts +1 -1
  34. package/dist/plugins/loader.d.ts +238 -10
  35. package/dist/plugins/loader.js +175 -21
  36. package/dist/plugins/loader.js.map +1 -1
  37. package/dist/plugins/policy.d.ts +2 -0
  38. package/dist/plugins/policy.js +17 -1
  39. package/dist/plugins/policy.js.map +1 -1
  40. package/dist/plugins/prompts.d.ts +6 -1
  41. package/dist/plugins/prompts.js +103 -15
  42. package/dist/plugins/prompts.js.map +1 -1
  43. package/dist/plugins/repeats.d.ts +7 -0
  44. package/dist/plugins/repeats.js +74 -13
  45. package/dist/plugins/repeats.js.map +1 -1
  46. package/dist/plugins/review.d.ts +2 -0
  47. package/dist/plugins/review.js +41 -3
  48. package/dist/plugins/review.js.map +1 -1
  49. package/dist/plugins/sessions.d.ts +7 -0
  50. package/dist/plugins/sessions.js +110 -0
  51. package/dist/plugins/sessions.js.map +1 -0
  52. package/dist/provider.d.ts +56 -2
  53. package/dist/provider.js +73 -7
  54. package/dist/provider.js.map +1 -1
  55. package/dist/session-lifecycle.d.ts +61 -0
  56. package/dist/session-lifecycle.js +167 -0
  57. package/dist/session-lifecycle.js.map +1 -0
  58. package/dist/session-scope.d.ts +53 -0
  59. package/dist/session-scope.js +116 -0
  60. package/dist/session-scope.js.map +1 -0
  61. package/dist/sessions.d.ts +6 -0
  62. package/dist/sessions.js +20 -0
  63. package/dist/sessions.js.map +1 -1
  64. package/dist/sys.d.ts +4 -1
  65. package/dist/sys.js +18 -1
  66. package/dist/sys.js.map +1 -1
  67. package/dist/tools/ask.d.ts +11 -0
  68. package/dist/tools/ask.js +62 -0
  69. package/dist/tools/ask.js.map +1 -0
  70. package/dist/tools/fs.d.ts +4 -0
  71. package/dist/tools/fs.js +53 -12
  72. package/dist/tools/fs.js.map +1 -1
  73. package/dist/tools/grep.js +3 -2
  74. package/dist/tools/grep.js.map +1 -1
  75. package/dist/tools/shell.js +5 -1
  76. package/dist/tools/shell.js.map +1 -1
  77. package/dist/tools/task.d.ts +6 -2
  78. package/dist/tools/task.js +36 -8
  79. package/dist/tools/task.js.map +1 -1
  80. package/dist/tools/web.d.ts +33 -3
  81. package/dist/tools/web.js +351 -143
  82. package/dist/tools/web.js.map +1 -1
  83. package/dist/ui/configure.js +91 -22
  84. package/dist/ui/configure.js.map +1 -1
  85. package/dist/ui/diff.d.ts +1 -1
  86. package/dist/ui/diff.js +1 -2
  87. package/dist/ui/diff.js.map +1 -1
  88. package/dist/ui/editor.d.ts +8 -0
  89. package/dist/ui/editor.js +50 -1
  90. package/dist/ui/editor.js.map +1 -1
  91. package/dist/ui/markdown.d.ts +6 -1
  92. package/dist/ui/markdown.js +57 -19
  93. package/dist/ui/markdown.js.map +1 -1
  94. package/dist/ui/render.d.ts +9 -10
  95. package/dist/ui/render.js +35 -72
  96. package/dist/ui/render.js.map +1 -1
  97. package/dist/ui/renderers.d.ts +8 -0
  98. package/dist/ui/renderers.js +169 -0
  99. package/dist/ui/renderers.js.map +1 -0
  100. package/dist/ui/screen.d.ts +22 -2
  101. package/dist/ui/screen.js +104 -15
  102. package/dist/ui/screen.js.map +1 -1
  103. package/dist/ui/transcript.d.ts +13 -0
  104. package/dist/ui/transcript.js +105 -15
  105. package/dist/ui/transcript.js.map +1 -1
  106. package/dist/ui/tui.d.ts +2 -0
  107. package/dist/ui/tui.js +309 -58
  108. package/dist/ui/tui.js.map +1 -1
  109. package/dist/update.d.ts +53 -0
  110. package/dist/update.js +255 -0
  111. package/dist/update.js.map +1 -0
  112. package/package.json +6 -5
  113. package/src/commands.ts +24 -0
  114. package/src/distro.ts +228 -51
  115. package/src/index.ts +2 -0
  116. package/src/main.ts +413 -292
  117. package/src/plugin-cli.ts +73 -34
  118. package/src/plugins/budget.ts +4 -4
  119. package/src/plugins/builtins.ts +6 -3
  120. package/src/plugins/checks.ts +25 -6
  121. package/src/plugins/compact.ts +40 -1
  122. package/src/plugins/core.ts +40 -0
  123. package/src/plugins/host.ts +146 -0
  124. package/src/plugins/install.ts +1 -1
  125. package/src/plugins/loader.ts +379 -23
  126. package/src/plugins/policy.ts +17 -1
  127. package/src/plugins/prompts.ts +108 -15
  128. package/src/plugins/repeats.ts +75 -14
  129. package/src/plugins/review.ts +40 -3
  130. package/src/plugins/sessions.ts +109 -0
  131. package/src/provider.ts +109 -10
  132. package/src/session-lifecycle.ts +194 -0
  133. package/src/session-scope.ts +135 -0
  134. package/src/sessions.ts +17 -0
  135. package/src/sys.ts +18 -1
  136. package/src/tools/ask.ts +72 -0
  137. package/src/tools/fs.ts +53 -12
  138. package/src/tools/grep.ts +3 -2
  139. package/src/tools/shell.ts +5 -1
  140. package/src/tools/task.ts +51 -11
  141. package/src/tools/web.ts +370 -140
  142. package/src/ui/configure.ts +90 -27
  143. package/src/ui/diff.ts +1 -2
  144. package/src/ui/editor.ts +50 -1
  145. package/src/ui/markdown.ts +258 -219
  146. package/src/ui/render.ts +35 -57
  147. package/src/ui/renderers.ts +183 -0
  148. package/src/ui/screen.ts +113 -19
  149. package/src/ui/transcript.ts +109 -16
  150. package/src/ui/tui.tsx +353 -58
  151. package/src/update.ts +262 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uncarved/jade",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "A coding agent harness built on the uncarved kernel",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -42,16 +42,17 @@
42
42
  "prepublishOnly": "node ../../scripts/require-bun-publish.mjs && bun run build"
43
43
  },
44
44
  "dependencies": {
45
- "@uncarved/plugin-stdio": "0.1.0",
45
+ "@uncarved/plugin-stdio": "0.2.0",
46
46
  "@uncarved/provider-anthropic": "0.1.2",
47
- "@uncarved/provider-openai-compat": "0.1.3",
48
- "@uncarved/provider-openai-responses": "0.1.3",
47
+ "@uncarved/provider-openai-compat": "0.1.4",
48
+ "@uncarved/provider-openai-responses": "0.1.4",
49
49
  "@uncarved/store-jsonl": "0.1.0",
50
+ "htmlparser2": "^10.0.0",
50
51
  "ink": "7.1.1",
51
52
  "picomatch": "^4.0.3",
52
53
  "react": "^19.2.0",
53
54
  "string-width": "^8.2.0",
54
- "uncarved": "0.1.2",
55
+ "uncarved": "0.1.3",
55
56
  "wrap-ansi": "^10.0.2"
56
57
  },
57
58
  "devDependencies": {
package/src/commands.ts CHANGED
@@ -13,6 +13,8 @@
13
13
 
14
14
  import { readdir, readFile } from "node:fs/promises";
15
15
  import path from "node:path";
16
+ import type { Jade } from "./distro.ts";
17
+ import type { CommandInfo } from "./ui/screen.ts";
16
18
 
17
19
  export interface CustomCommand {
18
20
  name: string;
@@ -118,3 +120,25 @@ export function projectDirs(root: string, cwd: string): string[] {
118
120
  if (rel) for (const seg of rel.split(path.sep)) dirs.push(path.join(dirs.at(-1)!, seg));
119
121
  return dirs;
120
122
  }
123
+
124
+ /**
125
+ * 斜杠命令同名时谁生效:宿主命令 > 内置插件的命令 > 自定义命令和 skill > 第三方插件(第三方之间先到先得)。
126
+ * 内置插件和第三方插件之间的先后由 createJade 定(jade.commands 里内置插件优先;内置插件被代替或停用时,第三方插件可以用它的命令名);
127
+ * 这里再让第三方插件给宿主命令、自定义命令和 skill 让位。返回菜单里内置插件的和第三方插件的命令,以及被忽略的命令的警告
128
+ */
129
+ export function pluginMenu(
130
+ commands: Jade["commands"],
131
+ taken: { host: Set<string>; custom: { has(name: string): boolean }; skill: { has(name: string): boolean } },
132
+ ): { builtin: CommandInfo[]; plugins: CommandInfo[]; warnings: string[] } {
133
+ const out = { builtin: [] as CommandInfo[], plugins: [] as CommandInfo[], warnings: [] as string[] };
134
+ for (const [name, { plugin, command: c, builtin }] of commands) {
135
+ if (builtin) {
136
+ out.builtin.push({ name: c.name, args: c.args, about: c.description ?? "" });
137
+ continue;
138
+ }
139
+ const what = taken.host.has(name) ? "a built-in command" : taken.custom.has(name) ? "a custom command" : taken.skill.has(name) ? "a skill" : undefined;
140
+ if (what) out.warnings.push(`command /${c.name} of plugin ${plugin} is ignored: ${what} has that name`);
141
+ else out.plugins.push({ name: c.name, args: c.args, about: `${c.description ?? ""} (plugin ${plugin})`.trim() });
142
+ }
143
+ return out;
144
+ }
package/src/distro.ts CHANGED
@@ -1,32 +1,39 @@
1
1
  // 组装发行版:内核之外的功能都是插件。内置插件(见 plugins/builtins.ts)和第三方插件用同一套接口,
2
2
  // 在这里拼成一份插件清单。宿主(main.ts)和测试都通过这里创建,内核本身不知道这些插件的存在。
3
3
  //
4
- // 用户可以停用内置插件($JADE_HOME/plugins.json),第三方插件可以用 replaces 代替内置插件;jade/policy 两者都不行。
4
+ // 用户可以停用内置插件($JADE_HOME/plugins.json),第三方插件可以在 plugin.json 里用 replaces 代替内置插件;jade/policy 两者都不行。
5
5
 
6
6
  import path from "node:path";
7
- import { checkCompat, definePlugin, type LogStore, type ModelRequest, type Plugin, type Provider, type Tool } from "uncarved";
7
+ import { checkCompat, definePlugin, subsetPlugin, type LogStore, type ModelRequest, type Plugin, type Provider, type Tool } from "uncarved";
8
8
  import { budget } from "./plugins/budget.ts";
9
9
  import { BUILTINS, BUILTIN_IDS, REQUIRED_IDS } from "./plugins/builtins.ts";
10
10
  import { checks as checksPlugin, type ApproveCheck, type Check, type Checks } from "./plugins/checks.ts";
11
- import { checksCommand, compactCommand, mcpCommand, mcpInstructions, memoryCommand, skillsCommand, withCounter, withSystem } from "./plugins/core.ts";
11
+ import { checksCommand, compactCommand, mcpCommand, mcpInstructions, memoryCommand, searchCommand, skillsCommand, withCounter, withSystem } from "./plugins/core.ts";
12
12
  import { Memory, memoryTool } from "./memory.ts";
13
13
  import { mcpTools, type McpClient } from "./mcp.ts";
14
14
  import { skillTool, skillsPrompt, type Skill } from "./skills.ts";
15
15
  import { compactor, type Compactor } from "./plugins/compact.ts";
16
- import { COMMAND_NAME, JADE_VERSION, type HostContext, type JadePlugin, type LoadedPlugin, type PluginCommand } from "./plugins/loader.ts";
16
+ import { COMMAND_NAME, DISPOSE_TIMEOUT_MS, JADE_VERSION, KEY_SPEC, RESERVED_KEYS, type HostContext, type HostInput, type PluginKey, type ToolRenderer, type JadePlugin, type LoadedPlugin, type PluginCommand } from "./plugins/loader.ts";
17
17
  import { policy, type AllowRule, type Mode, type Policy, type PolicyOptions } from "./plugins/policy.ts";
18
18
  import { prompts, realPath, repoRoot } from "./plugins/prompts.ts";
19
19
  import { repeats } from "./plugins/repeats.ts";
20
+ import { sessionsPlugin, undoPlugin } from "./plugins/sessions.ts";
20
21
  import { fsTools } from "./tools/fs.ts";
21
22
  import { Checkpoints } from "./tools/checkpoint.ts";
22
23
  import { shellTools } from "./tools/shell.ts";
23
- import { taskTool, type ApproveSubagent } from "./tools/task.ts";
24
+ import { taskTool, type ApproveSubagent, type SubagentControl } from "./tools/task.ts";
24
25
  import { todoTool } from "./tools/todo.ts";
26
+ import { askUserTool, type AskUser } from "./tools/ask.ts";
25
27
  import { webTools } from "./tools/web.ts";
26
28
  import { screenshotTool } from "./tools/screenshot.ts";
29
+ import { askRenderers, fsRenderers, memoryRenderers, shellRenderers, taskRenderers, todoRenderers, webRenderers } from "./ui/renderers.ts";
27
30
  import { visionFromEnv } from "./provider.ts";
28
31
 
29
32
  const READ_ONLY = new Set(["read_file", "list_dir", "glob", "grep"]);
33
+ /** 子 Agent 也执行的第三方插件 hook */
34
+ const TOOL_HOOKS: ReadonlySet<string> = new Set(["tool.gate", "tool.before", "tool.after"]);
35
+ /** 子 Agent 一轮最多调用模型的次数(子 Agent 的提示词里写的是同一个数) */
36
+ const SUBAGENT_STEPS = 40;
30
37
 
31
38
  export interface JadeOptions {
32
39
  cwd: string;
@@ -39,13 +46,15 @@ export interface JadeOptions {
39
46
  projectPlugins?: Plugin[];
40
47
  /** 用 loadPlugin 加载的第三方插件(用户层和项目层),每次 createJade 创建一套新实例 */
41
48
  extensions?: LoadedPlugin[];
42
- /** 停用的插件:内置插件的 id,或者第三方插件的 id(第三方插件按目录名停用由宿主在加载前处理) */
49
+ /** 停用的内置插件的 id(第三方插件由宿主在加载前按 id 筛掉,见 resolvePlugins) */
43
50
  disabled?: Iterable<string>;
44
51
  /** 压缩阈值;传函数时每次投影前取值 */
45
52
  compactTokens?: number | (() => number);
46
53
  maxSteps?: number;
47
54
  /** 当前配置的模型,写进主 Agent 的系统提示词(见 prompts 的 model);每次请求时取 */
48
55
  model?: () => { name: string; via: string } | undefined;
56
+ /** 会话的临时目录:写进提示词让模型把临时文件放这里;关卡按工作目录对待,修改前不用先读 */
57
+ scratch?: string;
49
58
  /** 测试用 */
50
59
  today?: string;
51
60
  /** 读取搜索服务配置用,默认 process.env;测试用 */
@@ -56,6 +65,8 @@ export interface JadeOptions {
56
65
  lookup?: (hostname: string) => Promise<string[]>;
57
66
  /** 截图用的浏览器;不给时按 JADE_BROWSER 和常见安装位置找,null 表示不提供截图工具 */
58
67
  browser?: string | null;
68
+ /** ask_user 工具向用户提问;不给就不提供这个工具 */
69
+ askUser?: AskUser;
59
70
  /** 子 Agent 要用户批准的调用(例如 web_fetch)交给宿主;不给就拒绝 */
60
71
  approveSubagent?: ApproveSubagent;
61
72
  /** 子 Agent 也遵守的"总是允许"规则(主会话的),每次判断时取 */
@@ -77,6 +88,14 @@ export interface JadeOptions {
77
88
  mcp?: McpClient[];
78
89
  /** loadSkills 找到的 skill */
79
90
  skills?: Skill[];
91
+ /** 插件用 ctx.status 设置状态栏上自己的那一段;plugin 是插件的 id,text 为 undefined 时去掉 */
92
+ onStatus?(plugin: string, text: string | undefined): void;
93
+ /** 终端界面的输入框,给用户层插件的 ctx.input(多一个参数:调用的插件的 id);-p 时没有 */
94
+ input?: HostInput;
95
+ /** 用户层插件的 ctx.send:替用户提交一行;plugin 是插件的 id。-p 时没有 */
96
+ send?(plugin: string, text: string): void;
97
+ /** 插件的 ctx.signal:这套实例的会话结束时中止(见 SessionScope);不给时永不中止 */
98
+ signal?: AbortSignal;
80
99
  }
81
100
 
82
101
  export interface BuiltinState {
@@ -103,17 +122,39 @@ export interface Jade {
103
122
  /** 每个内置插件的状态 */
104
123
  builtins: BuiltinState[];
105
124
  /** 成功加入本会话的第三方插件实例 */
106
- extensions: { source: LoadedPlugin; plugin: JadePlugin }[];
125
+ extensions: Extension[];
107
126
  /** 插件(内置的和第三方的)提供的斜杠命令,按小写的名字 */
108
127
  commands: Map<string, { plugin: string; command: PluginCommand; builtin: boolean }>;
128
+ /** 第三方插件为自己的工具注册的显示方式,按工具名 */
129
+ renderers: Map<string, { plugin: string; renderer: ToolRenderer }>;
130
+ /** 第三方插件的快捷键,按 KEY_SPEC 的写法(小写) */
131
+ keys: Map<string, { plugin: string; key: PluginKey }>;
109
132
  /** 主会话的工具;宿主用 read_file / list_dir 读取 @ 引用的文件 */
110
133
  tools: Tool[];
134
+ /**
135
+ * 不再用这套实例时调用(在 shutdown 和会话收尾之后):调用第三方插件的 dispose,同时进行、各自限时。
136
+ * 只执行一次;返回要告诉用户的问题
137
+ */
138
+ dispose(): Promise<string[]>;
111
139
  /** 宿主退出时调用:杀掉后台 shell */
112
140
  shutdown(): void;
113
141
  /** 启动时要告诉用户的问题,例如找不到 shell */
114
142
  warnings: string[];
115
143
  }
116
144
 
145
+ /**
146
+ * 加入本会话的一个第三方插件实例,和 jade 从它上面检查过、留下的扩展点。jade 只用这里的,不改写实例:
147
+ * 进程外插件的实例是在会话之间共用的进程对象(它的快捷键和命令每套单独生成,见 LoadedPlugin.adapters),
148
+ * 项目层插件的实例是内核认的那个对象(宪法 7.1)。不合格的扩展点不在这里,并且已经给出警告
149
+ */
150
+ export interface Extension {
151
+ source: LoadedPlugin;
152
+ plugin: JadePlugin;
153
+ commands: PluginCommand[];
154
+ keys: PluginKey[];
155
+ renderers: ToolRenderer[];
156
+ }
157
+
117
158
  export async function createJade(opts: JadeOptions): Promise<Jade> {
118
159
  const { cwd, store, provider } = opts;
119
160
  const skills = opts.skills ?? [];
@@ -133,24 +174,24 @@ export async function createJade(opts: JadeOptions): Promise<Jade> {
133
174
  // run 也给插件和编辑后检查用,所以 jade/shell 停用时也创建,只是不把工具交给模型
134
175
  const shell = shellTools({ cwd });
135
176
  const root = await repoRoot(cwd);
136
- const host: HostContext = { jade: JADE_VERSION, cwd: realPath(cwd), root: realPath(root), home: opts.home, definePlugin, run: shell.run };
177
+ const host: HostContext = { jade: JADE_VERSION, cwd: realPath(cwd), root: realPath(root), home: opts.home, definePlugin, run: shell.run, complete: completer(provider), status: (plugin, text) => opts.onStatus?.(plugin, text), checkpoints, input: opts.input, send: opts.send, signal: opts.signal ?? new AbortController().signal };
137
178
 
138
179
  // 第三方插件先创建:要先知道它们代替哪些内置插件
139
- const made = await createExtensions(opts.extensions ?? [], host, disabled, warnings);
180
+ const made = await createExtensions(opts.extensions ?? [], host, warnings);
140
181
 
141
182
  // ---------- 内置插件(jade/prompts 最后创建:它要知道最终有哪些工具) ----------
142
183
  const built = new Map<string, JadePlugin>();
143
184
  const add = (p: JadePlugin) => built.set(p.id, p);
144
185
 
145
- const pol = policy({ cwd, mode: opts.mode, pendingMode: opts.pendingMode, review: opts.review, readRoots: off("jade/skills") ? [] : skills.map((x) => x.dir) });
186
+ const pol = policy({ cwd, mode: opts.mode, pendingMode: opts.pendingMode, review: opts.review, readRoots: off("jade/skills") ? [] : skills.map((x) => x.dir), scratch: opts.scratch });
146
187
  add(pol.plugin);
147
188
  // 占位,组装完成后换成真正的提示词插件
148
189
  if (!off("jade/prompts")) add({ id: "jade/prompts", version: "0.3.0", kernel: "^0.1" });
149
190
 
150
191
  // 文件工具据此判断读取和修改是不是同一次回复里发出的
151
192
  const responses = { calls: 0 };
152
- if (!off("jade/fs")) add(withCounter({ id: "jade/fs", version: "0.1.0", kernel: "^0.1", tools: fsTools(cwd, { checkpoints, responses }) }, responses));
153
- if (!off("jade/shell")) add({ id: "jade/shell", version: "0.1.0", kernel: "^0.1", tools: shell.tools });
193
+ if (!off("jade/fs")) add(withCounter({ id: "jade/fs", version: "0.1.0", kernel: "^0.1", tools: fsTools(cwd, { checkpoints, responses, scratch: opts.scratch }), renderers: fsRenderers(cwd) }, responses));
194
+ if (!off("jade/shell")) add({ id: "jade/shell", version: "0.1.0", kernel: "^0.1", tools: shell.tools, renderers: shellRenderers });
154
195
  let web: Tool[] = [];
155
196
  let hasScreenshot = false;
156
197
  if (!off("jade/web")) {
@@ -176,6 +217,8 @@ export async function createJade(opts: JadeOptions): Promise<Jade> {
176
217
  version: "0.2.0",
177
218
  kernel: "^0.1",
178
219
  tools: shot ? [...web, shot] : web,
220
+ renderers: webRenderers,
221
+ commands: [searchCommand({ envFile: path.join(opts.home, ".env"), env: opts.env })],
179
222
  ...(shot
180
223
  ? {
181
224
  needs: ["transform:context.build"],
@@ -190,22 +233,30 @@ export async function createJade(opts: JadeOptions): Promise<Jade> {
190
233
  : {}),
191
234
  });
192
235
  }
193
- if (!off("jade/todo")) add({ id: "jade/todo", version: "0.1.0", kernel: "^0.1", tools: [todoTool()] });
236
+ if (!off("jade/todo")) add({ id: "jade/todo", version: "0.1.0", kernel: "^0.1", tools: [todoTool()], renderers: todoRenderers });
237
+ if (!off("jade/ask") && opts.askUser) add({ id: "jade/ask", version: "0.1.0", kernel: "^0.1", tools: [askUserTool(opts.askUser)], renderers: askRenderers });
194
238
 
195
239
  let memory: Memory | undefined;
196
240
  if (!off("jade/memory")) {
197
241
  memory = new Memory(opts.home, root);
198
242
  const text = await memory.prompt();
199
- add(withSystem({ id: "jade/memory", version: "0.1.0", kernel: "^0.1", tools: [memoryTool(memory)], commands: [memoryCommand(memory)] }, text ? [{ text, trust: "trusted" }] : []));
243
+ add(withSystem({ id: "jade/memory", version: "0.1.0", kernel: "^0.1", tools: [memoryTool(memory)], commands: [memoryCommand(memory)], renderers: memoryRenderers }, text ? [{ text, trust: "trusted" }] : []));
200
244
  }
201
245
 
202
246
  /** 最终加载了的内置插件,子 Agent 据此决定给哪些工具;组装完成后才填上 */
203
247
  const kept = new Set<string>();
204
248
  /** 子 Agent 的提示词,组装完成后生成 */
205
249
  const subSystem: { plugin?: Plugin } = {};
250
+ /** 第三方插件(项目层和用户层),组装完成后填上 */
251
+ let thirdParty: Plugin[] = [];
206
252
  if (!off("jade/task")) {
207
- const subagentPlugins = subagent(opts, subSystem, () => ({ fs: kept.has("jade/fs"), web: kept.has("jade/web") ? web : [], mcp: kept.has("jade/mcp") ? mcp : [] }));
208
- add({ id: "jade/task", version: "0.1.0", kernel: "^0.1", tools: [taskTool({ store, provider, plugins: subagentPlugins, approve: opts.approveSubagent })] });
253
+ const subagentPlugins = subagent(opts, subSystem, () => ({
254
+ fs: kept.has("jade/fs"),
255
+ web: kept.has("jade/web") ? web : [],
256
+ mcp: kept.has("jade/mcp") ? mcp : [],
257
+ extensions: thirdParty,
258
+ }));
259
+ add({ id: "jade/task", version: "0.1.0", kernel: "^0.1", tools: [taskTool({ store, provider, plugins: subagentPlugins, approve: opts.approveSubagent })], renderers: taskRenderers });
209
260
  }
210
261
 
211
262
  if (!off("jade/skills")) {
@@ -244,31 +295,41 @@ export async function createJade(opts: JadeOptions): Promise<Jade> {
244
295
  add({ ...compact.plugin, commands: [compactCommand(compact)] });
245
296
  }
246
297
  if (!off("jade/budget")) add(budget({ maxSteps: opts.maxSteps }));
298
+ if (!off("jade/sessions")) add(sessionsPlugin());
299
+ if (!off("jade/undo")) add(undoPlugin(host));
247
300
  if (!off("jade/repeats")) {
248
301
  // 自己数回复次数:不依赖 jade/fs 是否加载
249
302
  const own = { calls: 0 };
250
- add(withCounter(repeats({ responses: own }), own));
303
+ add(withCounter(repeats({ responses: own, cwd }), own));
251
304
  }
252
305
 
253
306
  // ---------- 代替关系:被代替的内置插件让位,代替者的工具名可以和它重复 ----------
254
- const claims = (p: JadePlugin) => (p.replaces ?? []).filter((id) => BUILTIN_IDS.has(id) && !REQUIRED_IDS.has(id) && built.has(id));
307
+ // 代替关系写在清单里(plugin.json 的 replaces),不看实例
308
+ const claims = (m: Extension) => (m.source.info.replaces ?? []).filter((id) => BUILTIN_IDS.has(id) && !REQUIRED_IDS.has(id) && built.has(id));
255
309
  for (const { source, plugin } of made) {
256
- for (const id of plugin.replaces ?? []) {
310
+ for (const id of source.info.replaces ?? []) {
257
311
  if (REQUIRED_IDS.has(id)) warnings.push(`plugin ${plugin.id} (${source.layer}): cannot replace ${id}; add a gate hook to make approvals stricter instead`);
258
312
  else if (!BUILTIN_IDS.has(id)) warnings.push(`plugin ${plugin.id} (${source.layer}): replaces unknown built-in plugin ${id}`);
259
313
  }
260
314
  }
261
315
  // 从"全部声明都生效"开始;被拒绝的插件声明的代替撤销,内置插件回来之后可能又拒绝别的插件,直到不再变化
262
- let replaced = new Set(made.flatMap((m) => claims(m.plugin)));
316
+ let replaced = new Set(made.flatMap(claims));
263
317
  let result: ReturnType<typeof accept>;
264
318
  for (;;) {
265
319
  result = accept(made, [...built.values()].filter((p) => !replaced.has(p.id)));
266
- const next = new Set(result.accepted.flatMap((m) => claims(m.plugin)));
320
+ const next = new Set(result.accepted.flatMap(claims));
267
321
  if (next.size === replaced.size) break;
268
322
  replaced = next;
269
323
  }
270
324
  warnings.push(...result.rejected);
271
325
  const added = result.accepted;
326
+ // 被拒绝的实例不会再用:现在就收尾
327
+ for (const m of made) {
328
+ if (added.includes(m)) continue;
329
+ const w = await disposeInstance(m.source, m.plugin);
330
+ if (w) warnings.push(w);
331
+ }
332
+ let disposing: Promise<string[]> | undefined;
272
333
  const builtin = [...built.values()].filter((p) => !replaced.has(p.id));
273
334
  for (const p of builtin) kept.add(p.id);
274
335
 
@@ -276,6 +337,8 @@ export async function createJade(opts: JadeOptions): Promise<Jade> {
276
337
  const toolNames = new Set(allTools.map((t) => t.name));
277
338
  const webNames = kept.has("jade/web") ? web.map((t) => t.name) : [];
278
339
  const at = builtin.findIndex((p) => p.id === "jade/prompts");
340
+ // 子 Agent 的提示词和主 Agent 的同时生成:两者都要跑几个 git 命令
341
+ const subPrompts = kept.has("jade/task") ? prompts({ cwd, home: opts.home, role: "subagent", today: opts.today, web: webNames }) : undefined;
279
342
  if (at >= 0) {
280
343
  builtin[at] = await prompts({
281
344
  cwd,
@@ -286,26 +349,39 @@ export async function createJade(opts: JadeOptions): Promise<Jade> {
286
349
  web: webNames,
287
350
  screenshot: hasScreenshot,
288
351
  checks: kept.has("jade/checks") && Boolean(checks),
352
+ scratch: opts.scratch,
289
353
  tools: toolNames,
290
354
  model: opts.model,
291
355
  });
292
356
  }
293
- if (kept.has("jade/task")) subSystem.plugin = await prompts({ cwd, home: opts.home, role: "subagent", today: opts.today, web: webNames });
357
+ if (subPrompts) subSystem.plugin = await subPrompts;
294
358
 
295
359
  const builtins: BuiltinState[] = BUILTINS.map((b) => {
296
360
  if (kept.has(b.id)) return { ...b, state: "on" as const };
297
- const by = added.find((a) => claims(a.plugin).includes(b.id))?.plugin.id;
361
+ const by = added.find((a) => claims(a).includes(b.id))?.plugin.id;
298
362
  return by ? { ...b, state: "replaced" as const, by } : { ...b, state: "disabled" as const };
299
363
  });
300
364
 
301
- const plugins = [...builtin, ...(opts.projectPlugins ?? []), ...added.map((a) => a.plugin)];
365
+ thirdParty = [...(opts.projectPlugins ?? []), ...added.map((a) => a.plugin)];
366
+ const plugins = [...builtin, ...thirdParty];
302
367
  const commands = new Map<string, { plugin: string; command: PluginCommand; builtin: boolean }>();
303
- for (const p of [...builtin, ...added.map((a) => a.plugin)] as JadePlugin[]) {
304
- const isBuiltin = BUILTIN_IDS.has(p.id) && builtin.includes(p);
305
- for (const c of p.commands ?? []) {
368
+ const owners = [
369
+ ...(builtin as JadePlugin[]).map((p) => ({ id: p.id, commands: p.commands ?? [], builtin: BUILTIN_IDS.has(p.id) })),
370
+ ...added.map((a) => ({ id: a.plugin.id, commands: a.commands, builtin: false })),
371
+ ];
372
+ for (const p of owners) {
373
+ for (const c of p.commands) {
306
374
  const taken = commands.get(c.name.toLowerCase());
307
375
  if (taken) warnings.push(`plugin ${p.id}: command /${c.name} is ignored: plugin ${taken.plugin} already provides it`);
308
- else commands.set(c.name.toLowerCase(), { plugin: p.id, command: c, builtin: isBuiltin });
376
+ else commands.set(c.name.toLowerCase(), { plugin: p.id, command: c, builtin: p.builtin });
377
+ }
378
+ }
379
+ const keys = new Map<string, { plugin: string; key: PluginKey }>();
380
+ for (const { plugin, keys: own } of added) {
381
+ for (const k of own) {
382
+ const taken = keys.get(k.key);
383
+ if (taken) warnings.push(`plugin ${plugin.id}: key ${k.key} is ignored: plugin ${taken.plugin} already uses it`);
384
+ else keys.set(k.key, { plugin: plugin.id, key: k });
309
385
  }
310
386
  }
311
387
  if (shell.unavailable && kept.has("jade/shell")) warnings.push(shell.unavailable);
@@ -319,6 +395,13 @@ export async function createJade(opts: JadeOptions): Promise<Jade> {
319
395
  builtins,
320
396
  extensions: added,
321
397
  commands,
398
+ keys,
399
+ renderers: new Map(
400
+ [...(builtin as JadePlugin[]).map((p) => ({ id: p.id, renderers: p.renderers ?? [] })), ...added.map((a) => ({ id: a.plugin.id, renderers: a.renderers }))].flatMap((p) =>
401
+ p.renderers.map((r) => [r.tool, { plugin: p.id, renderer: r }] as const),
402
+ ),
403
+ ),
404
+ dispose: () => (disposing ??= Promise.all(added.map(({ source, plugin }) => disposeInstance(source, plugin))).then((ws) => ws.filter((w): w is string => w !== undefined))),
322
405
  tools: allTools,
323
406
  shutdown: shell.shutdown,
324
407
  warnings,
@@ -329,48 +412,114 @@ export async function createJade(opts: JadeOptions): Promise<Jade> {
329
412
  * 创建第三方插件的实例。有问题的插件跳过并给出警告,而不是让整个 jade 起不来:工厂出错、内核不兼容、命令格式不对。
330
413
  * 只带内容(skills、命令、MCP 配置)的插件没有实例,由宿主处理
331
414
  */
332
- async function createExtensions(sources: LoadedPlugin[], host: HostContext, disabled: Set<string>, warnings: string[]) {
333
- const out: { source: LoadedPlugin; plugin: JadePlugin }[] = [];
415
+ async function createExtensions(sources: LoadedPlugin[], host: HostContext, warnings: string[]): Promise<Extension[]> {
416
+ const out: Extension[] = [];
417
+ /** 创建了却不用的实例也要收尾 */
418
+ const discard = async (source: LoadedPlugin, plugin: JadePlugin) => {
419
+ const w = await disposeInstance(source, plugin);
420
+ if (w) warnings.push(w);
421
+ };
334
422
  for (const source of sources) {
335
423
  if (!source.create) continue;
336
- const where = `plugin ${source.name} (${source.layer})`;
337
- let plugin: JadePlugin;
424
+ const where = `plugin ${source.id} (${source.layer})`;
425
+ let created: JadePlugin | undefined;
338
426
  try {
339
- plugin = await source.create(host);
340
- checkCompat(plugin);
427
+ created = await source.create(host);
428
+ // 清单里的 id 决定了停用、重复检查和状态栏,实例不能换成别的
429
+ if (created.id !== source.id) throw new Error(`its id ${JSON.stringify(created.id)} does not match "id" in plugin.json (use ctx.definePlugin, which fills it in)`);
430
+ checkCompat(created);
341
431
  } catch (err) {
342
432
  warnings.push(`${where} is skipped: ${err instanceof Error ? err.message : String(err)}`);
433
+ if (created) await discard(source, created);
343
434
  continue;
344
435
  }
345
- if (disabled.has(plugin.id)) continue;
346
- if (plugin.replaces !== undefined && !(Array.isArray(plugin.replaces) && plugin.replaces.every((x) => typeof x === "string"))) {
347
- warnings.push(`${where} is skipped: "replaces" must be an array of plugin ids`);
348
- continue;
349
- }
350
- const commands = (plugin.commands ?? []).filter((c) => {
351
- const ok = c && typeof c.name === "string" && COMMAND_NAME.test(c.name) && typeof c.run === "function";
436
+ const plugin = created;
437
+ // disposeInstance 只调用函数:不合格的不用删
438
+ if (plugin.dispose !== undefined && typeof plugin.dispose !== "function") warnings.push(`${where}: dispose is ignored: it must be a function`);
439
+ if ("replaces" in plugin) warnings.push(`${where}: replaces is ignored: write it in plugin.json instead ("replaces": ["jade/…"])`);
440
+ // 进程外插件的快捷键和命令按清单为这一套生成;模块插件的就在实例上
441
+ const parts = source.adapters ? source.adapters(host) : plugin;
442
+ const commands = listOf(parts.commands).filter((c): c is PluginCommand => {
443
+ const ok = Boolean(c) && typeof c.name === "string" && COMMAND_NAME.test(c.name) && typeof c.run === "function";
352
444
  if (!ok) warnings.push(`${where}: command ${JSON.stringify(c?.name)} is ignored: it needs a name of letters, digits, - and _, and a run function`);
353
445
  return ok;
354
446
  });
355
- // 原地修改而不是复制:内核只认加载器返回的那个项目层插件对象(宪法 7.1)
356
- if (plugin.commands) plugin.commands = commands;
357
- out.push({ source, plugin });
447
+ // 模型服务不属于某套插件实例:改成在模块里导出(export const providers),加载时就注册。jade 不读实例上的 providers
448
+ if ("providers" in plugin) warnings.push(`${where}: providers is ignored: export it from the plugin module instead (export const providers = [...])`);
449
+ const keys = listOf(parts.keys).flatMap((k): PluginKey[] => {
450
+ const key = typeof k?.key === "string" ? k.key.toLowerCase() : undefined;
451
+ if (key !== undefined && KEY_SPEC.test(key) && !RESERVED_KEYS.has(key) && typeof k.run === "function") return [{ key, description: k.description, run: (ctx) => k.run(ctx) }];
452
+ warnings.push(`${where}: key ${JSON.stringify(k?.key)} is ignored: it needs a run function and a key like ctrl+<letter> or alt+<letter or digit> that jade does not use itself`);
453
+ return [];
454
+ });
455
+ const own = new Set((plugin.tools ?? []).map((t) => t.name));
456
+ const seen = new Set<string>();
457
+ // 只认自己的工具:别的工具的显示(尤其是审批时的预览)不能由插件改
458
+ const renderers = listOf(plugin.renderers).filter((r) => {
459
+ const tool = r?.tool;
460
+ const fields = r as unknown as Record<string, unknown> | undefined;
461
+ const fns = Boolean(fields) && ["summary", "details", "preview", "before", "result"].every((k) => fields![k] === undefined || typeof fields![k] === "function");
462
+ let why: string | undefined;
463
+ if (typeof tool !== "string" || !fns) why = "it needs a tool name, and summary, details, preview, before and result must be functions";
464
+ else if (!own.has(tool)) why = "a plugin can only render its own tools";
465
+ else if (seen.has(tool)) why = "the tool already has a renderer";
466
+ if (why) warnings.push(`${where}: renderer for ${JSON.stringify(tool)} is ignored: ${why}`);
467
+ else seen.add(tool!);
468
+ return !why;
469
+ });
470
+ // jade 不再提供的扩展点:写了也不起作用,提示一次
471
+ for (const gone of REMOVED) if (gone in plugin) warnings.push(`${where}: ${gone} is ignored: jade does not offer it to plugins`);
472
+ out.push({ source, plugin, commands, keys, renderers });
358
473
  }
359
474
  return out;
360
475
  }
361
476
 
477
+ /** 去掉了的扩展点(见 docs/design/jade-plugin-lifecycle.md 第 9 节) */
478
+ const REMOVED = ["responder", "suggest", "beforeSend"] as const;
479
+
480
+ /** 插件给的列表:没给时为空;给的不是数组时当作一个不合格的项,好让上面提示 */
481
+ function listOf<T>(v: T[] | undefined): T[] {
482
+ return v === undefined ? [] : Array.isArray(v) ? v : [undefined as T];
483
+ }
484
+
485
+ /**
486
+ * 调用第三方插件实例的 dispose,限时 DISPOSE_TIMEOUT_MS;返回要告诉用户的问题,没有时 undefined。
487
+ * 进程外插件的进程在会话之间共用,不在这里结束(见 LoadedPlugin.close)
488
+ */
489
+ async function disposeInstance(source: LoadedPlugin, plugin: JadePlugin): Promise<string | undefined> {
490
+ if (source.kind === "process" || typeof plugin.dispose !== "function") return undefined;
491
+ const where = `plugin ${source.id} (${source.layer})`;
492
+ let timer: ReturnType<typeof setTimeout> | undefined;
493
+ const timeout = new Promise<"timeout">((resolve) => {
494
+ timer = setTimeout(() => resolve("timeout"), DISPOSE_TIMEOUT_MS);
495
+ });
496
+ try {
497
+ const result = await Promise.race([Promise.resolve().then(() => plugin.dispose!()), timeout]);
498
+ return result === "timeout" ? `${where}: dispose did not finish within ${DISPOSE_TIMEOUT_MS / 1000}s` : undefined;
499
+ } catch (err) {
500
+ return `${where}: dispose failed: ${err instanceof Error ? err.message : String(err)}`;
501
+ } finally {
502
+ clearTimeout(timer);
503
+ }
504
+ }
505
+
362
506
  /** 按顺序检查第三方插件的 id 和工具名不和已有的(留下的内置插件、排在前面的第三方插件)重复 */
363
- function accept(made: { source: LoadedPlugin; plugin: JadePlugin }[], existing: Plugin[]) {
507
+ function accept(made: Extension[], existing: Plugin[]) {
364
508
  const ids = new Set(existing.map((p) => p.id));
365
509
  const toolNames = new Set(existing.flatMap((p) => (p.tools ?? []).map((t) => t.name)));
366
510
  const accepted: typeof made = [];
367
511
  const rejected: string[] = [];
368
512
  for (const m of made) {
369
- const where = `plugin ${m.source.name} (${m.source.layer})`;
513
+ const where = `plugin ${m.source.id} (${m.source.layer})`;
370
514
  if (ids.has(m.plugin.id)) {
371
515
  rejected.push(`${where} is skipped: another plugin already has the id ${m.plugin.id}`);
372
516
  continue;
373
517
  }
518
+ // jade、jade/… 留给内置插件:会话里记的键按 id 划分(jade/undo 的撤销记录等),代替内置插件用 replaces,不用它的 id
519
+ if (m.plugin.id === "jade" || m.plugin.id.startsWith("jade/")) {
520
+ rejected.push(`${where} is skipped: the id ${m.plugin.id} is reserved for jade's built-in plugins (use "replaces" in plugin.json to stand in for one)`);
521
+ continue;
522
+ }
374
523
  const clash = (m.plugin.tools ?? []).find((t) => toolNames.has(t.name));
375
524
  if (clash) {
376
525
  rejected.push(`${where} is skipped: tool ${clash.name} already exists`);
@@ -383,11 +532,15 @@ function accept(made: { source: LoadedPlugin; plugin: JadePlugin }[], existing:
383
532
  return { accepted, rejected };
384
533
  }
385
534
 
386
- /** 子 Agent 的插件:只读工具(含 web 工具)、子 Agent 提示词、只读策略(加上主会话的规则)、步数上限。每次调用返回新实例 */
387
- function subagent(opts: JadeOptions, system: { plugin?: Plugin }, available: () => { fs: boolean; web: Tool[]; mcp: McpClient[] }): () => Plugin[] {
535
+ /** 子 Agent 的插件:只读工具(含 web 工具)、子 Agent 提示词、只读策略(加上主会话的规则)、压缩、步数上限。每次调用返回新实例 */
536
+ function subagent(
537
+ opts: JadeOptions,
538
+ system: { plugin?: Plugin },
539
+ available: () => { fs: boolean; web: Tool[]; mcp: McpClient[]; extensions: Plugin[] },
540
+ ): (control: SubagentControl) => Plugin[] {
388
541
  // 有哪些工具要到组装完成才知道,所以每次调用时再取
389
- return () => {
390
- const { fs, web, mcp } = available();
542
+ return (control) => {
543
+ const { fs, web, mcp, extensions } = available();
391
544
  const tools: Plugin = {
392
545
  id: "jade/tools-readonly",
393
546
  version: "0.1.0",
@@ -395,6 +548,30 @@ function subagent(opts: JadeOptions, system: { plugin?: Plugin }, available: ()
395
548
  tools: [...(fs ? fsTools(opts.cwd).filter((t) => READ_ONLY.has(t.name)) : []), ...web, ...mcpTools(mcp, { readOnly: true })],
396
549
  };
397
550
  const pol = policy({ cwd: opts.cwd, mode: "readonly", id: "jade/policy-subagent", rules: opts.sharedRules });
398
- return [tools, ...(system.plugin ? [system.plugin] : []), pol.plugin, budget({ maxSteps: 40, id: "jade/budget-subagent" })];
551
+ // 大范围调研时读的文件多:没有压缩会撑爆上下文,前面的调研全部白做
552
+ const compact = compactor({ provider: opts.provider, thresholdTokens: opts.compactTokens, id: "jade/compact-subagent" }).plugin;
553
+ const steps = budget({ maxSteps: () => (control.wrapUp ? 1 : SUBAGENT_STEPS), id: "jade/budget-subagent" });
554
+ // 第三方插件只带工具级的 hook(拦截、改写参数、给结果脱敏),子 Agent 读到的内容也经过它们;
555
+ // 不带它们的工具、提示词和 observe hook(例如按轮次触发的功能不该被子 Agent 触发)
556
+ const tooling = extensions
557
+ .map((p) => subsetPlugin(p, { tools: () => false, hooks: (h) => TOOL_HOOKS.has(h.point) }))
558
+ .filter((p) => p.hooks?.length);
559
+ return [tools, ...(system.plugin ? [system.plugin] : []), pol.plugin, compact, steps, ...tooling];
560
+ };
561
+ }
562
+
563
+ /** 插件上下文的 complete:用会话的 provider 发一次不带工具的请求 */
564
+ function completer(provider: Provider): HostContext["complete"] {
565
+ const origin = { by: "plugin", id: "jade/extension" } as const;
566
+ return async (req, signal) => {
567
+ const res = await provider.complete(
568
+ {
569
+ system: req.system ? [{ text: req.system, stability: "stable", origin, trust: "trusted" }] : [],
570
+ messages: [{ role: "user", content: [{ kind: "text", text: req.prompt, origin, trust: "untrusted" }] }],
571
+ tools: [],
572
+ },
573
+ { signal, onDelta: req.onText && ((d) => void (d.kind === "text" && req.onText!(d.text))) },
574
+ );
575
+ return { text: res.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join(""), model: res.model, usage: res.usage };
399
576
  };
400
577
  }
package/src/index.ts CHANGED
@@ -18,6 +18,7 @@ export * from "./tools/shell.ts";
18
18
  export * from "./tools/task.ts";
19
19
  export * from "./tools/checkpoint.ts";
20
20
  export * from "./tools/todo.ts";
21
+ export * from "./tools/ask.ts";
21
22
  export * from "./config.ts";
22
23
  export * from "./context.ts";
23
24
  export * from "./commands.ts";
@@ -26,3 +27,4 @@ export * from "./plugins/install.ts";
26
27
  export * from "./plugins/builtins.ts";
27
28
  export * from "./mcp.ts";
28
29
  export * from "./skills.ts";
30
+ export * from "./plugins/host.ts";