@uncarved/jade 0.3.0 → 0.3.1

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 (59) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/package.json +2 -2
  5. package/plugins/approval/index.ts +14 -11
  6. package/plugins/approval/policy.ts +34 -16
  7. package/plugins/fs/grep.ts +13 -3
  8. package/plugins/fs/index.ts +5 -5
  9. package/plugins/fs/plugin.json +1 -1
  10. package/plugins/mcp/index.ts +5 -5
  11. package/plugins/mcp/plugin.json +1 -1
  12. package/plugins/models/index.ts +4 -3
  13. package/plugins/models/provider.ts +12 -1
  14. package/plugins/repeats/index.ts +31 -1
  15. package/plugins/screenshot/browser.ts +221 -0
  16. package/plugins/screenshot/index.ts +3 -2
  17. package/plugins/screenshot/tool.ts +27 -51
  18. package/plugins/shell/index.ts +64 -6
  19. package/plugins/shell/plugin.json +1 -1
  20. package/plugins/shell/shell.ts +90 -33
  21. package/plugins/task/index.ts +12 -42
  22. package/plugins/task/plugin.json +1 -2
  23. package/plugins/task/subagent.ts +2 -2
  24. package/plugins/tools/index.ts +50 -0
  25. package/plugins/tools/plugin.json +7 -0
  26. package/plugins/tui/frontend.ts +27 -3
  27. package/plugins/tui/mascot.ts +8 -7
  28. package/plugins/tui/tui.ts +23 -7
  29. package/plugins/web/index.ts +7 -7
  30. package/plugins/web/plugin.json +1 -1
  31. package/plugins-dist/approval/index.js +16 -12
  32. package/plugins-dist/approval/policy.js +30 -15
  33. package/plugins-dist/fs/grep.js +12 -3
  34. package/plugins-dist/fs/index.js +5 -5
  35. package/plugins-dist/fs/plugin.json +1 -1
  36. package/plugins-dist/mcp/index.js +5 -5
  37. package/plugins-dist/mcp/plugin.json +1 -1
  38. package/plugins-dist/models/index.js +4 -3
  39. package/plugins-dist/models/provider.js +13 -1
  40. package/plugins-dist/repeats/index.js +27 -1
  41. package/plugins-dist/screenshot/browser.js +187 -0
  42. package/plugins-dist/screenshot/index.js +3 -2
  43. package/plugins-dist/screenshot/tool.js +27 -49
  44. package/plugins-dist/shell/index.js +68 -5
  45. package/plugins-dist/shell/plugin.json +1 -1
  46. package/plugins-dist/shell/shell.js +82 -30
  47. package/plugins-dist/task/index.js +11 -42
  48. package/plugins-dist/task/plugin.json +1 -3
  49. package/plugins-dist/task/subagent.js +1 -1
  50. package/plugins-dist/tools/index.js +49 -0
  51. package/plugins-dist/tools/plugin.json +9 -0
  52. package/plugins-dist/tui/frontend.js +28 -3
  53. package/plugins-dist/tui/mascot.js +8 -6
  54. package/plugins-dist/tui/tui.js +18 -7
  55. package/plugins-dist/tui/vendor.js +1388 -1088
  56. package/plugins-dist/web/index.js +6 -6
  57. package/plugins-dist/web/plugin.json +1 -1
  58. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  59. package/src/api.ts +1 -1
package/README.md CHANGED
@@ -95,6 +95,7 @@ jade 自带的功能全是 `apps/jade/plugins/` 下的普通插件,和第三
95
95
  | `jade/modes` | 模式切换、计划模式 |
96
96
  | `jade/compact` | 上下文压缩、溢出后自动重试 |
97
97
  | `jade/task` | 子 Agent(嵌套 Runtime) |
98
+ | `jade/tools` | 给嵌套 Agent 用的工具的注册表(`tools@1`) |
98
99
  | `jade/mcp` | MCP 服务工具 |
99
100
  | `jade/skills`、`jade/memory` | 技能目录、长期记忆 |
100
101
  | `jade/schedule` | 定时任务(cron,重启后仍生效) |
package/dist/api.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { PluginLayer } from "@uncarved/jade-api";
2
2
  export * from "@uncarved/jade-api";
3
3
  /** 插件 API 的版本,插件在 plugin.json 的 api 字段里用 ^ 范围声明。和 @uncarved/jade-api 的版本一致 */
4
- export declare const API_VERSION = "1.1.0";
4
+ export declare const API_VERSION = "1.2.0";
5
5
  /** 来源层级,后面的层级更高(3.3) */
6
6
  export declare const LAYERS: readonly PluginLayer[];
7
7
  /** 插件代码抛出的错误,标明归属 */
package/dist/api.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // 再加上只有核心用得到值的东西:API 版本、层级顺序、错误类。
3
3
  export * from "@uncarved/jade-api";
4
4
  /** 插件 API 的版本,插件在 plugin.json 的 api 字段里用 ^ 范围声明。和 @uncarved/jade-api 的版本一致 */
5
- export const API_VERSION = "1.1.0";
5
+ export const API_VERSION = "1.2.0";
6
6
  /** 来源层级,后面的层级更高(3.3) */
7
7
  export const LAYERS = ["bundled", "user", "project"];
8
8
  // ---------- 错误 ----------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uncarved/jade",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "A coding agent harness built on the uncarved kernel: a small stable host core, everything else is a plugin",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -46,7 +46,7 @@
46
46
  "prepublishOnly": "node ../../scripts/require-bun-publish.mjs && bun run build"
47
47
  },
48
48
  "dependencies": {
49
- "@uncarved/jade-api": "1.1.0",
49
+ "@uncarved/jade-api": "1.2.0",
50
50
  "@uncarved/provider-anthropic": "0.1.4",
51
51
  "@uncarved/provider-openai-compat": "0.1.5",
52
52
  "@uncarved/provider-openai-responses": "0.1.4",
@@ -202,8 +202,11 @@ export default definePlugin({
202
202
  if (again.decision === "deny") return { approved: false, answer: "deny", by: "rule", reason: again.reason };
203
203
  }
204
204
  if (!canAsk()) return { approved: false, answer: "deny", by: "nobody", reason: nobody(call.name) };
205
- const rule = rules.ruleFor(call);
206
- const shown = (await preview(renderers, call)) ?? detail(call);
205
+ const allow = rules.rulesFor(call);
206
+ const described = allow.map(describeRule).join(", ");
207
+ // "总是允许"的范围只在正文里写一次:写进选项里时,长命令会把两个选项句尾的区别(本会话 / 这个目录)挤出屏幕
208
+ const covers = asked.mine ? `"Always allow" covers: ${allow.length === 1 && allow[0]!.command !== undefined ? `${allow[0]!.tool}, this exact command only` : described}\n\n` : "";
209
+ const shown = covers + ((await preview(renderers, call)) ?? detail(call));
207
210
  const expired = new AbortController();
208
211
  const timer = setTimeout(() => expired.abort(), askTimeoutMs);
209
212
  let got: { answer: Answer; by: string; said?: string } | undefined;
@@ -219,8 +222,8 @@ export default definePlugin({
219
222
  // 别的插件要问的调用不能"总是允许":这里的规则管不到它的关卡
220
223
  ...(asked.mine
221
224
  ? [
222
- { label: `Always allow ${describeRule(rule)} in this session`, value: "always" as const },
223
- { label: `Always allow ${describeRule(rule)} in this directory, in every session`, value: "forever" as const },
225
+ { label: "Always allow in this session", value: "always" as const },
226
+ { label: "Always allow in this directory, in every session", value: "forever" as const },
224
227
  ]
225
228
  : []),
226
229
  { label: "Deny", value: "deny" },
@@ -235,14 +238,14 @@ export default definePlugin({
235
238
  return { approved: false, answer: "deny", by: "timeout", reason: `Nobody answered the approval request for ${call.name} in time. Do not retry it; tell the user what you wanted to do.` };
236
239
  }
237
240
  if (got?.answer === "always" && asked.mine) {
238
- added.push(rule);
241
+ added.push(...allow);
239
242
  return { approved: true, answer: "always", by: got.by };
240
243
  }
241
244
  if (got?.answer === "forever" && asked.mine) {
242
- forever.push(rule);
245
+ forever.push(...allow);
243
246
  try {
244
- await addForever(foreverFile, ctx.cwd, rule);
245
- ui?.notify(`${describeRule(rule)} is now always allowed in ${ctx.cwd}. To ask again, remove it from ${foreverFile}`, "info");
247
+ await addForever(foreverFile, ctx.cwd, allow);
248
+ ui?.notify(`${described} is now always allowed in ${ctx.cwd}. To ask again, remove it from ${foreverFile}`, "info");
246
249
  } catch (e) {
247
250
  ui?.notify(`could not save the rule to ${foreverFile} (${e instanceof Error ? e.message : String(e)}); it only applies to this session`, "warning");
248
251
  }
@@ -368,7 +371,7 @@ async function ask(ui: UI | undefined, request: SelectRequest<Answer>, signal: A
368
371
  const channels: Promise<{ answer: Answer; by: string; said?: string } | typeof NONE>[] = [];
369
372
  if (ui?.interactive) {
370
373
  // 终端里多一项:拒绝并说明。选了它再问一句话,取消或什么都没写就是普通的拒绝
371
- const options = [...request.options, { label: "Deny, and tell the agent what to do instead", value: EXPLAIN }];
374
+ const options = [...request.options, { label: "Deny, and say what to do instead", value: EXPLAIN }];
372
375
  channels.push(
373
376
  ui.select<string>({ ...request, options }, done.signal).then(async (a) => {
374
377
  if (a !== EXPLAIN) return { answer: a !== undefined && ANSWERS.includes(a) ? (a as Answer) : "deny", by: "terminal" };
@@ -418,10 +421,10 @@ async function readForever(file: string): Promise<Record<string, AllowRule[]>> {
418
421
  }
419
422
  }
420
423
 
421
- async function addForever(file: string, cwd: string, rule: AllowRule): Promise<void> {
424
+ async function addForever(file: string, cwd: string, add: AllowRule[]): Promise<void> {
422
425
  const all = await readForever(file);
423
426
  const rules = all[cwd] ?? [];
424
- if (!rules.some((r) => JSON.stringify(r) === JSON.stringify(rule))) rules.push(rule);
427
+ for (const rule of add) if (!rules.some((r) => JSON.stringify(r) === JSON.stringify(rule))) rules.push(rule);
425
428
  all[cwd] = rules;
426
429
  await mkdir(path.dirname(file), { recursive: true });
427
430
  await writeFile(file, `${JSON.stringify(all, null, 2)}\n`);
@@ -2,6 +2,7 @@
2
2
  // 纯判断,不碰界面和日志;那些在 index.ts。
3
3
  //
4
4
  // 带 url 参数的只读工具(web_fetch)也要问:网页里的提示注入可以让模型把读到的内容拼进 URL 发出去。
5
+ // 指向本机的 URL(localhost 上的开发服务器,截图最常见的用途)不问:数据不会离开这台机器。
5
6
 
6
7
  import { realpathSync, statSync } from "node:fs";
7
8
  import path from "node:path";
@@ -53,7 +54,8 @@ export interface PolicyOptions {
53
54
 
54
55
  export interface Policy {
55
56
  /** 给"总是允许"一个默认规则:bash 取命令的前两个词,工作目录之外的路径取所在目录,URL 取主机,其他取工具名 */
56
- ruleFor(call: { name: string; input: unknown }): AllowRule;
57
+ /** 用户选"总是允许"时记下的规则;bash 的复合命令可能是好几条 */
58
+ rulesFor(call: { name: string; input: unknown }): AllowRule[];
57
59
  decide(call: GatedToolCall, settings: PolicySettings): GateResult;
58
60
  /** 工具参数里的相对路径换成绝对路径,日志里记下的、关卡判断的都是确定的路径 */
59
61
  absolutePath(input: unknown): unknown;
@@ -364,19 +366,31 @@ function prefixCovers(words: Word[], prefix: string): boolean {
364
366
 
365
367
  /**
366
368
  * bash 的"总是允许"默认规则:一般取前两个词("cargo build"、"git commit"),
367
- * 运行脚本的命令取三个词("npm run build")。第二个词就是选项("rm -rf x")、只有一个词、
368
- * 或者分不了词时,只允许这一条命令本身
369
+ * 运行脚本的命令取三个词("npm run build")。第二个词就是选项("rm -rf x")、只有一个词时,只允许这一条命令本身。
370
+ * 复合命令("git add -A && git commit -m …"、"bun test 2>&1 | tail -20")里每条不是只读的命令各记一条:
371
+ * 关卡对复合命令逐条判断,所以下次换了提交信息、换了组合也不用再问。
372
+ * 分不了词、有输出重定向、或者不是只读的命令带输入重定向时,只允许整条命令原文
369
373
  */
370
- export function bashRule(command: string): AllowRule {
371
- const exact = { tool: "bash", command: command.trim() };
372
- // 复合命令里只有一条不是只读命令("bun test 2>&1 | tail -20")时,规则取它;关卡对复合命令逐条判断
374
+ export function bashRules(command: string): AllowRule[] {
375
+ const exact = [{ tool: "bash", command: command.trim() }];
373
376
  const cmds = shellCommands(command);
374
377
  const unsafe = cmds?.filter((c) => c.words[0]!.value !== "cd" && commandKind(c.words.map((w) => w.value)) !== "read");
375
- if (!cmds || !unsafe || unsafe.length !== 1 || !cmds.every(quietOutputs) || unsafe[0]!.inputs.length > 0) return exact;
376
- const words = unsafe[0]!.words.map((w) => w.value);
377
- if (!words || words.length < 2 || words[1]!.startsWith("-") || words.some((w) => DANGEROUS_ARGS.test(w))) return exact;
378
+ if (!cmds || !unsafe || unsafe.length === 0 || !cmds.every(quietOutputs) || unsafe.some((c) => c.inputs.length > 0)) return exact;
379
+ // 只有一条命令、又只能按原文记时,记整条原文(和关卡比较的是同一个字符串)
380
+ if (cmds.length === 1 && !prefixOf(unsafe[0]!.words)) return exact;
381
+ const rules = unsafe.map((c): AllowRule => {
382
+ const prefix = prefixOf(c.words);
383
+ return prefix ? { tool: "bash", prefix } : { tool: "bash", command: joined(c.words) };
384
+ });
385
+ return rules.filter((r, i) => rules.findIndex((o) => o.prefix === r.prefix && o.command === r.command) === i);
386
+ }
387
+
388
+ /** 一条简单命令的前缀规则;只能按原文记时返回 undefined */
389
+ function prefixOf(all: Word[]): string | undefined {
390
+ const words = all.map((w) => w.value);
391
+ if (words.length < 2 || words[1]!.startsWith("-") || words.some((w) => DANGEROUS_ARGS.test(w))) return undefined;
378
392
  const n = RUNNERS.test(words.slice(0, 2).join(" ")) && words.length >= 3 && !words[2]!.startsWith("-") ? 3 : 2;
379
- return { tool: "bash", prefix: words.slice(0, n).join(" ") };
393
+ return words.slice(0, n).join(" ");
380
394
  }
381
395
 
382
396
  const hostOf = (url: string) => {
@@ -387,6 +401,10 @@ const hostOf = (url: string) => {
387
401
  }
388
402
  };
389
403
 
404
+ /** 本机的地址:localhost、127.x.x.x、::1(URL 会把 127.1 这类写法规范成 127.0.0.1) */
405
+ const isLoopback = (host: string | undefined) =>
406
+ host !== undefined && (host === "localhost" || host.endsWith(".localhost") || /^127(\.\d{1,3}){3}$/.test(host) || host === "[::1]");
407
+
390
408
  /**
391
409
  * Windows 上 bash 工具跑的是 Git Bash,模型常把路径写成 /c/Users/...(MSYS 的写法)。
392
410
  * path.resolve 会把它当成当前盘符下的 \c\Users\...,判断成工作目录之外,只读命令也要确认。
@@ -496,12 +514,12 @@ export function policy(opts: PolicyOptions): Policy {
496
514
  if (!input || typeof input !== "object" || typeof (input as { path?: unknown }).path !== "string") return input;
497
515
  return { ...input, path: path.resolve(opts.cwd, (input as { path: string }).path) };
498
516
  },
499
- ruleFor(call) {
500
- if (call.name === "bash") return bashRule(String((call.input as { command?: unknown }).command ?? ""));
517
+ rulesFor(call) {
518
+ if (call.name === "bash") return bashRules(String((call.input as { command?: unknown }).command ?? ""));
501
519
  const input = call.input as { path?: unknown; url?: unknown } | null;
502
520
  if (typeof input?.url === "string") {
503
521
  const host = hostOf(input.url);
504
- if (host) return { tool: call.name, host };
522
+ if (host) return [{ tool: call.name, host }];
505
523
  }
506
524
  if (typeof input?.path === "string" && !inside(input.path)) {
507
525
  const full = path.resolve(opts.cwd, input.path);
@@ -511,9 +529,9 @@ export function policy(opts: PolicyOptions): Policy {
511
529
  } catch {
512
530
  // 还不存在的文件
513
531
  }
514
- return { tool: call.name, dir: isDir ? full : path.dirname(full) };
532
+ return [{ tool: call.name, dir: isDir ? full : path.dirname(full) }];
515
533
  }
516
- return { tool: call.name };
534
+ return [{ tool: call.name }];
517
535
  },
518
536
  decide(call, { mode, rules }) {
519
537
  const { tool } = call;
@@ -525,7 +543,7 @@ export function policy(opts: PolicyOptions): Policy {
525
543
  (typeof input.path === "string" && !inside(input.path)) ||
526
544
  (call.name === "glob" && typeof input.pattern === "string" && globEscapes(input.pattern));
527
545
  /** 会把参数发到网络上的只读工具 */
528
- const network = typeof input.url === "string";
546
+ const network = typeof input.url === "string" && !isLoopback(hostOf(input.url));
529
547
  const covers = (r: AllowRule) => {
530
548
  if (r.tool !== call.name) return false;
531
549
  if (r.command !== undefined) return (input.command ?? "").trim() === r.command;
@@ -64,7 +64,8 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
64
64
  `optionally only files matching the glob include (e.g. "*.ts" matches at any depth; "src/**/*.ts" limits it to src). Skips files ignored by git, binary files and .git/node_modules. ` +
65
65
  `output_mode: "content" (default) returns "file:line:text" for matches and "file-line-text" for context lines, at most ${MAX_MATCHES} matches; ` +
66
66
  `"files" returns only the paths of matching files; "count" returns "file:count". ` +
67
- `context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode.`,
67
+ `context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode. ` +
68
+ "head_limit keeps only the first that many lines of the output.",
68
69
  inputSchema: {
69
70
  type: "object",
70
71
  properties: {
@@ -75,6 +76,10 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
75
76
  // files_with_matches 是 ripgrep / Claude Code 的叫法,很多模型会这样传,当作 files
76
77
  output_mode: { type: "string", enum: ["content", "files", "count", "files_with_matches"] },
77
78
  context: { type: "integer" },
79
+ // head_limit、glob 也是 ripgrep / Claude Code 的叫法;不接受的话模型要多花一轮去掉它们重发。
80
+ // 有的模型把数字写成字符串("30"),也接受
81
+ head_limit: { type: ["integer", "string"] },
82
+ glob: { type: "string" },
78
83
  },
79
84
  required: ["pattern"],
80
85
  additionalProperties: false,
@@ -83,10 +88,12 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
83
88
  concurrency: "safe",
84
89
  idempotent: true,
85
90
  async execute(input, { signal }) {
86
- const { pattern, path: p = ".", include, ignore_case = false, output_mode = "content", context = 0 } = input as {
91
+ const { pattern, path: p = ".", glob, include = glob, ignore_case = false, output_mode = "content", context = 0, head_limit } = input as {
87
92
  pattern: string;
88
93
  path?: string;
89
94
  include?: string;
95
+ glob?: string;
96
+ head_limit?: number | string;
90
97
  ignore_case?: boolean;
91
98
  output_mode?: Mode | "files_with_matches";
92
99
  context?: number;
@@ -115,7 +122,10 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
115
122
  else found = result;
116
123
  }
117
124
  found ??= await jsGrep(search);
118
- return { content: format(cwd, found, search) };
125
+ const lines = format(cwd, found, search).split("\n");
126
+ const limit = Number(head_limit);
127
+ if (limit > 0 && lines.length > limit) lines.splice(limit, Infinity, `(showing the first ${limit} of ${lines.length} lines)`);
128
+ return { content: lines.join("\n") };
119
129
  },
120
130
  };
121
131
  }
@@ -1,7 +1,7 @@
1
1
  // jade/fs:文件工具 read_file、write_file、edit_file、multi_edit、list_dir、glob、grep。
2
2
 
3
3
  import { definePlugin } from "@uncarved/jade-api";
4
- import type { Renderers, Task } from "@uncarved/jade-api/services";
4
+ import type { Renderers, Tools } from "@uncarved/jade-api/services";
5
5
  import { fsTools, SeenFiles } from "./fs.ts";
6
6
  import { fsRenderers } from "./renderers.ts";
7
7
 
@@ -26,11 +26,11 @@ export default definePlugin({
26
26
  },
27
27
  });
28
28
  for (const tool of fsTools(ctx.cwd, { responses, seen })) ctx.kernel.tool(tool);
29
- // 子 Agent(jade/task)的只读工具:另一套实例,子 Agent 读过的文件不算主会话读过
30
- // jade/task 被隔离时它的服务已失效:子 Agent 没有文件工具,文件工具本身照常
29
+ // 嵌套 Agent(例如 jade/task 的子 Agent)的只读工具:另一套实例,它读过的文件不算主会话读过
30
+ // jade/tools 被隔离时它的服务已失效:嵌套 Agent 没有文件工具,文件工具本身照常
31
31
  try {
32
- const task = ctx.service<Task>("task@1");
33
- if (task) for (const tool of fsTools(ctx.cwd)) if (tool.effect === "read") task.tool(tool);
32
+ const shared = ctx.service<Tools>("tools@1");
33
+ if (shared) for (const tool of fsTools(ctx.cwd)) if (tool.effect === "read") shared.register(tool);
34
34
  } catch {}
35
35
  },
36
36
  });
@@ -3,5 +3,5 @@
3
3
  "version": "0.2.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["renderers@1", "task@1"]
6
+ "optional": ["renderers@1", "tools@1"]
7
7
  }
@@ -1,4 +1,4 @@
1
- // jade/mcp:配置的 MCP 服务的工具交给模型(声明只读的也经 task@1 交给子 Agent);/mcp 查看状态、重连,
1
+ // jade/mcp:配置的 MCP 服务的工具交给模型(声明只读的也经 tools@1 交给嵌套 Agent);/mcp 查看状态、重连,
2
2
  // /mcp add、/mcp remove 改配置文件(见 install.ts;终端里是 jade mcp add|remove)。
3
3
  //
4
4
  // 服务是进程级的资源:第一个会话打开时读配置、确认项目层的服务、连接,之后各会话共用;进程退出时(进程作用域关闭)全部关掉。
@@ -8,7 +8,7 @@
8
8
 
9
9
  import path from "node:path";
10
10
  import { definePlugin, type Cli, type ProcessContext, type UI } from "@uncarved/jade-api";
11
- import type { Commands, Prompts, Task } from "@uncarved/jade-api/services";
11
+ import type { Commands, Prompts, Tools } from "@uncarved/jade-api/services";
12
12
  import { describeServer, loadMcpConfig, McpClient, mcpTools, mcpTrustHash } from "./mcp.ts";
13
13
  import { manageMcp, manageUsage } from "./install.ts";
14
14
  import { bold, clip, dim, display, estimateTokens, green, realPath, red, repoRoot, splitArgs, TrustFile, yellow } from "./project.ts";
@@ -211,9 +211,9 @@ export default definePlugin({
211
211
  if (!servers) return;
212
212
  await servers.start();
213
213
  for (const tool of mcpTools(servers.clients)) ctx.kernel.tool(tool);
214
- // 子 Agent(jade/task)只拿声明了只读(readOnlyHint)的工具:另一套实例,和 jade/fs 一样
215
- const task = ctx.service<Task>("task@1");
216
- if (task) for (const tool of mcpTools(servers.clients, { readOnly: true })) task.tool(tool);
214
+ // 嵌套 Agent(例如 jade/task 的子 Agent)只拿声明了只读(readOnlyHint)的工具:另一套实例,和 jade/fs 一样
215
+ const shared = ctx.service<Tools>("tools@1");
216
+ if (shared) for (const tool of mcpTools(servers.clients, { readOnly: true })) shared.register(tool);
217
217
  const prompts = ctx.service<Prompts>("prompts@1");
218
218
  for (const text of instructions(servers.clients)) prompts?.add({ text, untrusted: true });
219
219
  },
@@ -3,5 +3,5 @@
3
3
  "version": "0.2.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["ui@1", "commands@1", "prompts@1", "task@1", "cli@1"]
6
+ "optional": ["ui@1", "commands@1", "prompts@1", "tools@1", "cli@1"]
7
7
  }
@@ -20,7 +20,8 @@ export default definePlugin({
20
20
  const modelsFile = path.join(ctx.home, "models.json");
21
21
  // 当前的模型配置。改配置时整份换掉(updateEnvFile 改的是这一份,apply 再从文件读一遍)
22
22
  let env = await envWithFile(envFile);
23
- const ui = ctx.service<UI>("ui@1");
23
+ // 用的时候再取:jade/tui 也依赖这个插件(models@1),它在这之后才激活,这里取到的是 undefined,重试的提示就没人显示
24
+ const ui = () => ctx.service<UI>("ui@1");
24
25
  const watchers = new Set<() => void>();
25
26
  const notify = () => {
26
27
  for (const fn of watchers) {
@@ -44,11 +45,11 @@ export default definePlugin({
44
45
  // 用创建时的这份配置:之后换了配置,新的一份自己建 provider
45
46
  const build = (snapshot: Env): Promise<Provider> => {
46
47
  return (async () => {
47
- const gate = new RateGate({ rpm: rpmFromEnv(snapshot), onLearn: (rpm) => ui?.notify(`rate limited: spacing requests to ${rpm} per minute from now on`, "warning") });
48
+ const gate = new RateGate({ rpm: rpmFromEnv(snapshot), onLearn: (rpm) => ui()?.notify(`rate limited: spacing requests to ${rpm} per minute from now on`, "warning") });
48
49
  return withRetry(await providerFromEnv(snapshot), {
49
50
  gate,
50
51
  onRetry: ({ attempt, retries, delayMs, error }) =>
51
- ui?.notify(`model request failed (${error.message}); retry ${attempt} of ${retries} in ${Math.round(delayMs / 1000)}s`, "warning"),
52
+ ui()?.notify(`model request failed (${error.message}); retry ${attempt} of ${retries} in ${Math.round(delayMs / 1000)}s`, "warning"),
52
53
  });
53
54
  })();
54
55
  };
@@ -73,7 +73,18 @@ export function withRetry(inner: Provider, opts: RetryOptions = {}): Provider {
73
73
  // 实际回复的是被包装者(4.7 第 3 款)
74
74
  return { ...res, provider: res.provider ?? inner.id, ...(failures.length > 0 ? { retries: failures } : {}) };
75
75
  } catch (err) {
76
- if (!(err instanceof ProviderError) || !err.retryable || attempt > retries || options.signal.aborted) throw err;
76
+ if (!(err instanceof ProviderError) || options.signal.aborted) throw err;
77
+ if (!err.retryable || attempt > retries) {
78
+ if (failures.length === 0) throw err;
79
+ // 失败时没有回复可以带上重试记录:写进错误信息里,会话日志(turn.ended)和界面上都看得到重试过、等了多久
80
+ const waited = Math.round(failures.reduce((ms, f) => ms + f.delayMs, 0) / 1000);
81
+ throw new ProviderError(`${err.message} (after ${failures.length} ${failures.length === 1 ? "retry" : "retries"}, ${waited}s of waiting)`, {
82
+ retryable: err.retryable,
83
+ status: err.status,
84
+ retryAfterMs: err.retryAfterMs,
85
+ cause: err,
86
+ });
87
+ }
77
88
  // 在计划的时间上随机缩短最多 20%,并行的子 Agent 同时遇到 429 时不会同时重试。
78
89
  // 上游给的 retryAfterMs 只当下限:有的服务(尤其是并发数限流)每次都回 Retry-After: 1,
79
90
  // 拿它代替退避计划会每秒撞一次,十几秒就把重试次数用完
@@ -8,6 +8,7 @@
8
8
  // 不拒绝:也可能是在等外面的东西变化,只提醒。压缩插件清理或总结了历史后,之前的结果可能已经不在上下文里,都不算重复。
9
9
  // 打开文件给用户看(start、xdg-open……)会弹出新窗口:这一轮里打开过、之后什么都没改,再打开就直接拒绝。
10
10
  // write_file 之后什么都没改又读回同一个文件,提醒模型内容就是它写的那些。
11
+ // 同一个文件里同一处文字被来回改(A 改成 B、B 改回 A、又改成 B):模型在凭不可靠的依据猜,第三次起提醒它停下来换个办法查,或者问用户。
11
12
  // 这些记录只在本会话的作用域里:恢复会话后从零开始,最多多重试一轮。
12
13
  //
13
14
  // 从旧 jade 的 plugins/repeats.ts 移植。
@@ -42,6 +43,15 @@ function normalize(cwd: string, p: string): string {
42
43
 
43
44
  /** 提醒模型的失败次数 */
44
45
  const WARN_AFTER = 2;
46
+ /** 同一处文字来回改到第几次时提醒:改过去、改回来各算一次,改回来一次是正常的撤销 */
47
+ const FLIP_AFTER = 3;
48
+
49
+ /** edit_file、multi_edit 里的每一处替换 */
50
+ function replacements(call: { name: string; input: unknown }): { old_string: string; new_string: string }[] {
51
+ const input = call.input as { old_string?: unknown; new_string?: unknown; edits?: unknown } | null;
52
+ const list = call.name === "edit_file" ? [input] : call.name === "multi_edit" && Array.isArray(input?.edits) ? input.edits : [];
53
+ return list.filter((e): e is { old_string: string; new_string: string } => typeof e?.old_string === "string" && typeof e?.new_string === "string");
54
+ }
45
55
 
46
56
  const hash = (content: Block[]) => createHash("sha1").update(JSON.stringify(content.map((b) => (b.kind === "text" ? b.text : b)))).digest("hex");
47
57
 
@@ -67,6 +77,8 @@ export function repeatsHooks(opts: { cwd: string; id?: string }): LocalHookSpec[
67
77
  const opened = new Map<string, number>();
68
78
  /** 本轮用 write_file 写过的文件 → 写完时的 changes;用户发消息时清空 */
69
79
  const written = new Map<string, number>();
80
+ /** 文件里互相替换的一对文字 → 本轮里换了几次(不分方向);用户发消息时清空 */
81
+ const flips = new Map<string, number>();
70
82
  const key = (call: { name: string; input: unknown }) => `${call.name}\0${JSON.stringify(call.input)}`;
71
83
  const note = (text: string): Block => ({ kind: "text", text: `[Note from jade] ${text}`, origin: { by: "plugin", id }, trust: "trusted" });
72
84
  return [
@@ -120,13 +132,30 @@ export function repeatsHooks(opts: { cwd: string; id?: string }): LocalHookSpec[
120
132
  outcome.call.name === "read_file" && typeof file === "string" && written.get(normalize(cwd, file)) === changes
121
133
  ? note("You wrote this file with write_file earlier and nothing has changed since: its content is exactly what you gave. Do not read files back to check them.")
122
134
  : undefined;
135
+ let most = 0;
136
+ if (typeof file === "string") {
137
+ for (const e of replacements(outcome.call)) {
138
+ const pair = `${normalize(cwd, file)}${[e.old_string, e.new_string].sort().join("")}`;
139
+ const n = (flips.get(pair) ?? 0) + 1;
140
+ flips.set(pair, n);
141
+ most = Math.max(most, n);
142
+ }
143
+ }
144
+ const flipped =
145
+ most >= FLIP_AFTER
146
+ ? note(
147
+ `You have now switched this same text back and forth ${most} times in this file. Going back and forth means what you are judging by is unreliable or incomplete. ` +
148
+ "Do not flip it again: check your assumption another way (measure it, read the code involved), or tell the user what you see and ask.",
149
+ )
150
+ : undefined;
151
+ const extra = [readBack, flipped].filter((b) => b !== undefined);
123
152
  const before = succeeded.get(k);
124
153
  // 只读之外的调用(包括这一个)可能改了东西,之后的调用都不算"什么都没变"
125
154
  if (!read) version++;
126
155
  const result = hash(outcome.content);
127
156
  const repeated = before !== undefined && before.version === (read ? version : version - 1) && before.result === result;
128
157
  succeeded.set(k, { version, result });
129
- if (!repeated) return readBack ? { ...outcome, content: [...outcome.content, readBack] } : undefined;
158
+ if (!repeated) return extra.length > 0 ? { ...outcome, content: [...outcome.content, ...extra] } : undefined;
130
159
  const text =
131
160
  "This exact call already ran earlier with the same result, and nothing has changed since (no edits, no other commands, no new message from the user). " +
132
161
  "Do not repeat it: use what you already have, or end your turn and tell the user where things stand.";
@@ -152,6 +181,7 @@ export function repeatsHooks(opts: { cwd: string; id?: string }): LocalHookSpec[
152
181
  version++;
153
182
  opened.clear();
154
183
  written.clear();
184
+ flips.clear();
155
185
  }
156
186
  },
157
187
  },