@uncarved/jade 0.2.0 → 0.2.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 (57) hide show
  1. package/README.md +215 -0
  2. package/bin/jade.js +11 -0
  3. package/dist/main.js +2 -1
  4. package/dist/main.js.map +1 -1
  5. package/package.json +4 -4
  6. package/plugins/approval/index.ts +16 -2
  7. package/plugins/approval/plugin.json +4 -0
  8. package/plugins/approval/policy.ts +25 -5
  9. package/plugins/compact/compact.ts +7 -1
  10. package/plugins/fs/fs.ts +78 -12
  11. package/plugins/fs/grep.ts +35 -7
  12. package/plugins/fs/index.ts +7 -4
  13. package/plugins/mentions/index.ts +31 -11
  14. package/plugins/models/index.ts +17 -2
  15. package/plugins/print/index.ts +26 -8
  16. package/plugins/prompts/index.ts +29 -1
  17. package/plugins/prompts/prompts.ts +9 -4
  18. package/plugins/prompts/results.ts +63 -0
  19. package/plugins/prompts/sys.ts +16 -4
  20. package/plugins/task/index.ts +1 -0
  21. package/plugins/task/subagent.ts +96 -10
  22. package/plugins/todo/index.ts +2 -2
  23. package/plugins/tui/frontend.ts +27 -4
  24. package/plugins/tui/mentions.ts +48 -8
  25. package/plugins/tui/transcript.ts +5 -1
  26. package/plugins/tui/tui.ts +2 -5
  27. package/plugins/tui/vendor.ts +16 -0
  28. package/plugins/undo/checkpoint.ts +24 -0
  29. package/plugins/undo/index.ts +8 -4
  30. package/plugins/web/web.ts +6 -5
  31. package/plugins-dist/approval/index.js +18 -2
  32. package/plugins-dist/approval/plugin.json +4 -0
  33. package/plugins-dist/approval/policy.js +27 -5
  34. package/plugins-dist/compact/compact.js +7 -1
  35. package/plugins-dist/fs/fs.js +73 -12
  36. package/plugins-dist/fs/grep.js +35 -9
  37. package/plugins-dist/fs/index.js +7 -4
  38. package/plugins-dist/mentions/index.js +28 -10
  39. package/plugins-dist/models/index.js +16 -2
  40. package/plugins-dist/print/index.js +25 -6
  41. package/plugins-dist/prompts/index.js +28 -0
  42. package/plugins-dist/prompts/prompts.js +8 -4
  43. package/plugins-dist/prompts/results.js +60 -0
  44. package/plugins-dist/prompts/sys.js +15 -3
  45. package/plugins-dist/task/index.js +1 -0
  46. package/plugins-dist/task/subagent.js +86 -10
  47. package/plugins-dist/todo/index.js +2 -2
  48. package/plugins-dist/tui/frontend.js +28 -5
  49. package/plugins-dist/tui/mentions.js +44 -6
  50. package/plugins-dist/tui/transcript.js +3 -1
  51. package/plugins-dist/tui/tui.js +1 -2
  52. package/plugins-dist/tui/vendor.js +13822 -0
  53. package/plugins-dist/undo/checkpoint.js +27 -0
  54. package/plugins-dist/undo/index.js +7 -4
  55. package/plugins-dist/web/web.js +6 -5
  56. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  57. package/src/main.ts +2 -1
@@ -46,9 +46,9 @@ export function todoTool(): Tool {
46
46
  required: ["todos"],
47
47
  additionalProperties: false,
48
48
  },
49
- // 不碰文件和进程
49
+ // 不碰文件和进程;可以和同一批的读并发(用到清单的地方按模型给出的顺序取最后一次调用,与执行顺序无关)
50
50
  effect: "read",
51
- concurrency: "exclusive",
51
+ concurrency: "safe",
52
52
  idempotent: true,
53
53
  async execute(input) {
54
54
  const todos = (input as { todos?: unknown }).todos;
@@ -21,14 +21,32 @@ import { mentionCandidates } from "./mentions.ts";
21
21
  import type { SessionIndex } from "../sessions/index.ts";
22
22
  import { dim, red, safeScreen, yellow, type CommandInfo, type Screen } from "./screen.ts";
23
23
  import { transcript, type Transcript } from "./transcript.ts";
24
- import { tuiScreen } from "./tui.ts";
24
+
25
+ /**
26
+ * 界面(ink、React)用到时才加载:--help、参数出错、不在终端里时都不需要它,导入一次要几百毫秒。
27
+ * React 在加载时按 NODE_ENV 选开发版或生产版,开发版做大量检查,流式输出时 CPU 翻倍。
28
+ * 用户没设 NODE_ENV 时只在加载期间设成 production,加载完还原,免得传给之后 shell 工具、MCP 等子进程。
29
+ * ink 依赖的 yoga 有顶层 await,只能异步加载,做不到同步设置再还原:加载期间还没有会话,工具和 MCP 都没启动,
30
+ * 这时可能启动的子进程只有 git(不读它)和后台的 npm 自动升级(全局安装本来就不装 devDependencies)。
31
+ * 编译好的 plugins-dist 里 ink、react 已打包成生产版(vendor.ts),这里设 NODE_ENV 只对直接跑源码(bun)时有用
32
+ */
33
+ async function loadTui(): Promise<typeof import("./tui.ts")> {
34
+ if (process.env.NODE_ENV !== undefined) return import("./tui.ts");
35
+ process.env.NODE_ENV = "production";
36
+ try {
37
+ return await import("./tui.ts");
38
+ } finally {
39
+ delete process.env.NODE_ENV;
40
+ }
41
+ }
25
42
 
26
43
  const USAGE = `usage: jade [prompt] [--resume <session id> | --continue]
27
44
 
28
45
  Starts the terminal interface. With a prompt, sends it first.
29
46
  -c, --continue continue the most recent session in this directory
30
47
  -r, --resume resume a session by id (inside jade, /resume lists them)
31
- Run one prompt without the interface: jade -p <prompt>`;
48
+ Run one prompt without the interface: jade -p <prompt> (jade -p --help for more)
49
+ jade's own commands (plugins, update, --safe): jade help`;
32
50
 
33
51
  /** 前端自己的命令:帮助和退出。其余命令都来自 commands@1 */
34
52
  const OWN: CommandInfo[] = [
@@ -244,7 +262,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
244
262
  return 2;
245
263
  }
246
264
  const history = new InputHistory(path.join(home, "history.jsonl"), cwd);
247
- const [past, branch] = await Promise.all([history.load(), gitBranch(cwd)]);
265
+ const [past, branch, { tuiScreen }] = await Promise.all([history.load(), gitBranch(cwd), loadTui()]);
248
266
 
249
267
  /** 菜单里的命令:前端自己的 + 注册表里的,每次打开菜单时取 */
250
268
  const commandList = (): CommandInfo[] => [
@@ -314,6 +332,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
314
332
  screen,
315
333
  cwd,
316
334
  contextWindow: () => models?.current()?.contextWindow ?? 0,
335
+ maxTokens: () => models?.current()?.maxTokens,
317
336
  ...(compact ? { compactAt: () => compact.threshold() } : {}),
318
337
  canRetry,
319
338
  renderer: (tool) => renderers.forTool(tool),
@@ -573,7 +592,11 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
573
592
  } catch (e) {
574
593
  screen.log(red(`[error] ${errorText(e)}`));
575
594
  }
576
- if (!models?.current()) screen.log(yellow(`No model is configured yet. Put ANTHROPIC_API_KEY=... (or OPENAI_API_KEY=...) in ${path.join(home, ".env")}, then restart jade.`));
595
+ if (!models?.current()) {
596
+ // /model(jade/models 提供)当场就能配好,不用重启;没有这条命令时只能改文件
597
+ const file = `put ANTHROPIC_API_KEY=... (or OPENAI_API_KEY=...) in ${path.join(home, ".env")}, then restart jade`;
598
+ screen.log(yellow(commands.list().some((c) => c.name === "model") ? `No model is configured yet. Type /model to set one up, or ${file}.` : `No model is configured yet. To set one up, ${file}.`));
599
+ }
577
600
  else if (!resumed) screen.log(dim("Type / for commands, esc to interrupt."));
578
601
  ready = true;
579
602
  for (const text of [...(args.prompt ? [args.prompt] : []), ...early.splice(0)]) onSubmit(text);
@@ -18,6 +18,32 @@ export function mentionAt(value: string, cursor: number): { start: number; query
18
18
  /** 补全后的文本:@ 引用加一个空格,含空白的路径加引号 */
19
19
  export const mentionText = (p: string) => (/\s/.test(p) ? `@"${p}"` : `@${p}`);
20
20
 
21
+ /** 候选路径预先算好的小写形式和文件名(目录去掉末尾的 /),每按一个键都要用,不重复算 */
22
+ interface Prepared {
23
+ lower: string;
24
+ base: string;
25
+ }
26
+ const prepared = new WeakMap<readonly string[], Prepared[]>();
27
+
28
+ function prepare(paths: readonly string[]): Prepared[] {
29
+ let out = prepared.get(paths);
30
+ if (!out) {
31
+ out = paths.map((p) => {
32
+ const lower = p.toLowerCase();
33
+ const trimmed = lower.endsWith("/") ? lower.slice(0, -1) : lower;
34
+ return { lower, base: trimmed.slice(trimmed.lastIndexOf("/") + 1) };
35
+ });
36
+ prepared.set(paths, out);
37
+ }
38
+ return out;
39
+ }
40
+
41
+ /**
42
+ * 上一次排序时命中的全部候选(下标)。query 只是在后面追加了字符时,新的命中一定在这些里面
43
+ * (包含 q 加字符的也包含 q,按顺序出现的同理),只筛它们,不用再扫一遍全部路径
44
+ */
45
+ let last: { paths: readonly string[]; q: string; hits: number[] } | undefined;
46
+
21
47
  /**
22
48
  * 按 query 给候选路径排序:文件名以 query 开头的最前,其次文件名包含、路径包含,
23
49
  * 最后是按顺序出现 query 每个字符的模糊匹配;同一档里短的在前
@@ -25,21 +51,35 @@ export const mentionText = (p: string) => (/\s/.test(p) ? `@"${p}"` : `@${p}`);
25
51
  export function rankPaths(paths: string[], query: string, limit: number): string[] {
26
52
  const q = query.toLowerCase().replaceAll("\\", "/");
27
53
  if (!q) return paths.filter((p) => !p.slice(0, -1).includes("/")).slice(0, limit);
28
- const scored: { p: string; score: number }[] = [];
29
- for (const p of paths) {
30
- const lower = p.toLowerCase();
31
- const base = lower.replace(/\/$/, "").split("/").pop()!;
54
+ const info = prepare(paths);
55
+ const from = last && last.paths === paths && q.startsWith(last.q) ? last.hits : undefined;
56
+ const scored: { i: number; score: number }[] = [];
57
+ const check = (i: number) => {
58
+ const { lower, base } = info[i]!;
32
59
  let score: number;
33
60
  if (lower.startsWith(q)) score = 0;
34
61
  else if (base.startsWith(q)) score = 1;
35
62
  else if (base.includes(q)) score = 2;
36
63
  else if (lower.includes(q)) score = 3;
37
64
  else if (subsequence(lower, q)) score = 4;
38
- else continue;
39
- scored.push({ p, score });
65
+ else return;
66
+ scored.push({ i, score });
67
+ };
68
+ if (from) for (const i of from) check(i);
69
+ else for (let i = 0; i < paths.length; i++) check(i);
70
+ last = { paths, q, hits: scored.map((s) => s.i) };
71
+ const cmp = (a: { i: number; score: number }, b: { i: number; score: number }) =>
72
+ a.score - b.score || paths[a.i]!.length - paths[b.i]!.length || paths[a.i]!.localeCompare(paths[b.i]!);
73
+ // 只要前 limit 条:命中常有上万条,全部排序(localeCompare 很慢)每按一个键要十几毫秒
74
+ const top: { i: number; score: number }[] = [];
75
+ for (const s of scored) {
76
+ if (top.length === limit && cmp(s, top[limit - 1]!) >= 0) continue;
77
+ let at = top.length;
78
+ while (at > 0 && cmp(s, top[at - 1]!) < 0) at--;
79
+ top.splice(at, 0, s);
80
+ if (top.length > limit) top.pop();
40
81
  }
41
- scored.sort((a, b) => a.score - b.score || a.p.length - b.p.length || a.p.localeCompare(b.p));
42
- return scored.slice(0, limit).map((s) => s.p);
82
+ return top.map((s) => paths[s.i]!);
43
83
  }
44
84
 
45
85
  function subsequence(text: string, q: string): boolean {
@@ -19,6 +19,8 @@ export interface TranscriptOptions {
19
19
  contextWindow(): number;
20
20
  /** 自动压缩的阈值(状态栏显示用) */
21
21
  compactAt?(): number;
22
+ /** 每次回复的输出上限(回复被截断时的提示用);没有时说是服务的默认值 */
23
+ maxTokens?(): number | undefined;
22
24
  /** 上一轮失败后能否用 /retry 重新请求 */
23
25
  canRetry(): boolean;
24
26
  /** 插件为自己的工具注册的显示方式(随会话的插件实例变) */
@@ -391,7 +393,9 @@ export function transcript(opts: TranscriptOptions): Transcript {
391
393
  if (d.reason === "stopped") screen.log(yellow("[stopped: step budget for this turn used up; send a message to continue]"));
392
394
  else if (d.reason === "aborted") screen.log(yellow("[interrupted]"));
393
395
  else if (d.reason === "max_tokens") {
394
- const limit = process.env.JADE_MAX_TOKENS ? `${process.env.JADE_MAX_TOKENS} tokens` : "the provider's default";
396
+ // 不读 process.env:写在 $JADE_HOME/.env 里的只有 models 插件知道
397
+ const max = opts.maxTokens?.();
398
+ const limit = max ? `${max} tokens` : "the provider's default";
395
399
  screen.log(yellow(`[reply cut off at the output limit (${limit}); raise it with /model if this keeps happening]`));
396
400
  } else if (d.reason !== "end") screen.log(yellow(`[turn ended: ${d.reason}${d.error ? ` — ${d.error}` : ""}]`));
397
401
  if (self.turnFailed && !replaying && opts.canRetry()) screen.log(dim("[send /retry to request again without adding a message]"));
@@ -5,6 +5,7 @@
5
5
  // 不用 JSX:插件以 .ts 源码加载,Node 的类型剥离不处理 .tsx,所以组件用 createElement(h)写。
6
6
 
7
7
  import { writeSync } from "node:fs";
8
+ import type { DOMElement, Key } from "ink";
8
9
  import {
9
10
  Box,
10
11
  render,
@@ -14,10 +15,6 @@ import {
14
15
  useInput,
15
16
  usePaste,
16
17
  useWindowSize,
17
- type DOMElement,
18
- type Key,
19
- } from "ink";
20
- import {
21
18
  createContext,
22
19
  createElement as h,
23
20
  useContext,
@@ -26,7 +23,7 @@ import {
26
23
  useRef,
27
24
  useState,
28
25
  useSyncExternalStore,
29
- } from "react";
26
+ } from "./vendor.ts";
30
27
  import stringWidth from "string-width";
31
28
  import wrapAnsi from "wrap-ansi";
32
29
  import { mentionAt, mentionText, rankPaths } from "./mentions.ts";
@@ -0,0 +1,16 @@
1
+ // ink 和 react 只经这里导入。构建时 scripts/build-plugins.mjs 把编译出的 vendor.js 连同依赖打成一个文件:
2
+ // 逐个解析 ink 和它拉进来的整个 es-toolkit/compat 要约 470ms,打包后约 120ms(docs/review.md #28)。
3
+ // 两者必须打在同一个文件里,否则 ink 和界面各用一份 react,hooks 会失效。
4
+ // 只用到类型的从 "ink"/"react" 直接 import type,不经这里。
5
+
6
+ export { Box, render, Text, useBoxMetrics, useCursor, useInput, usePaste, useWindowSize } from "ink";
7
+ export {
8
+ createContext,
9
+ createElement,
10
+ useContext,
11
+ useEffect,
12
+ useReducer,
13
+ useRef,
14
+ useState,
15
+ useSyncExternalStore,
16
+ } from "react";
@@ -121,5 +121,29 @@ export function lastTurnChanges(messages: readonly Message[], checkpoints: reado
121
121
  return pending.slice(0, 1);
122
122
  }
123
123
 
124
+ /**
125
+ * 一轮里调用过的工具名:含 toolUseId 的那一轮;不给时是最近一轮。
126
+ * 一轮从用户发的消息开始,到下一条用户消息之前(与 lastTurnChanges 的划分相同)
127
+ */
128
+ export function turnToolNames(messages: readonly Message[], toolUseId?: string): Set<string> {
129
+ let names = new Set<string>();
130
+ let found = toolUseId === undefined;
131
+ for (let i = messages.length - 1; i >= 0; i--) {
132
+ const m = messages[i]!;
133
+ if (m.role === "assistant") {
134
+ for (const b of m.content) {
135
+ if (b.kind !== "tool_use") continue;
136
+ names.add(b.name);
137
+ if (b.id === toolUseId) found = true;
138
+ }
139
+ continue;
140
+ }
141
+ if (!m.content.some((b) => b.kind !== "tool_result" && b.origin.by === "user")) continue;
142
+ if (found) return names;
143
+ names = new Set();
144
+ }
145
+ return found ? names : new Set();
146
+ }
147
+
124
148
  /** 会话和工具调用的 id 用作文件名 */
125
149
  const safe = (id: string) => id.replace(/[^A-Za-z0-9_.-]/g, "_");
@@ -9,13 +9,16 @@ import { realpathSync } from "node:fs";
9
9
  import path from "node:path";
10
10
  import { definePlugin } from "../../src/api.ts";
11
11
  import type { Commands } from "../commands/index.ts";
12
- import { Checkpoints, lastTurnChanges, sha256, type Checkpoint } from "./checkpoint.ts";
12
+ import { Checkpoints, lastTurnChanges, sha256, turnToolNames, type Checkpoint } from "./checkpoint.ts";
13
13
  import { Notes } from "./notes.ts";
14
14
  import { dim, green } from "./style.ts";
15
15
 
16
16
  /** 会改文件、参数里有 path 的工具 */
17
17
  export const WRITE_TOOLS = new Set(["write_file", "edit_file", "multi_edit"]);
18
18
 
19
+ /** shell 命令改了什么无从得知,撤销不了;这一轮跑过时提醒一句 */
20
+ const SHELL_NOTE = "This turn also ran shell commands; what they changed is not undone.";
21
+
19
22
  const notes = new Notes();
20
23
 
21
24
  /** 显示用:工作目录内的路径用相对形式,统一为正斜杠 */
@@ -49,13 +52,14 @@ export default definePlugin({
49
52
  const cwd = realPath(ctx.cwd);
50
53
  ctx.service<Commands>("commands@1")?.register({
51
54
  name: "undo",
52
- description: "restore every file the agent changed in its last turn (run again to go further back)",
55
+ description: "restore the files the agent wrote or edited in its last turn, not changes made by shell commands (run again to go further back)",
53
56
  async run(_args, { sessions, ui, signal }) {
54
57
  const s = sessions.current;
55
58
  if (!s) return "No session is open.";
56
59
  const undone = await checkpoints.undone(s.id);
57
60
  const cps = lastTurnChanges(s.state.messages, await checkpoints.list(s.id), undone);
58
- if (cps.length === 0) return dim("Nothing to undo.");
61
+ if (cps.length === 0) return dim(turnToolNames(s.state.messages).has("bash") ? `Nothing to undo. ${SHELL_NOTE}` : "Nothing to undo.");
62
+ const shellToo = turnToolNames(s.state.messages, cps[0]!.toolUseId).has("bash");
59
63
  /** 文件 → 这一轮最早的快照(恢复成它的 before);cps 是最新的在前 */
60
64
  const files = new Map<string, Checkpoint>();
61
65
  for (const cp of cps) files.set(cp.path, cp);
@@ -92,7 +96,7 @@ export default definePlugin({
92
96
  cp.before === null ? `deleted ${show(cp.path)} (you had created it)` : `restored ${show(cp.path)} to its content before your changes`,
93
97
  );
94
98
  notes.add(s.id, `The user undid your changes from your last turn: ${what.join("; ")}. Read these files again before changing them.`);
95
- return green(`Undid ${cps.length} change${cps.length > 1 ? "s" : ""} from the last turn:`) + "\n" + dim(list);
99
+ return green(`Undid ${cps.length} change${cps.length > 1 ? "s" : ""} from the last turn:`) + "\n" + dim(list) + (shellToo ? `\n${dim(SHELL_NOTE)}` : "");
96
100
  },
97
101
  });
98
102
  },
@@ -14,7 +14,6 @@
14
14
 
15
15
  import { lookup as dnsLookup } from "node:dns/promises";
16
16
  import { isIP } from "node:net";
17
- import { Parser } from "htmlparser2";
18
17
  import type { Block, Tool } from "uncarved";
19
18
  import type { Env } from "./env.ts";
20
19
 
@@ -229,7 +228,7 @@ async function download(fetchImpl: typeof fetch, lookup: Lookup, target: URL, si
229
228
  if (!res.ok) {
230
229
  const body = await res.text().catch(() => "");
231
230
  return {
232
- content: `HTTP ${res.status} ${res.statusText} from ${url.href}${body ? `\n${clip(htmlToMarkdown(body).text || body, 1000)}` : ""}`,
231
+ content: `HTTP ${res.status} ${res.statusText} from ${url.href}${body ? `\n${clip((await htmlToMarkdown(body)).text || body, 1000)}` : ""}`,
233
232
  isError: true,
234
233
  retry: res.status === 403 || res.status === 429 || res.status >= 500,
235
234
  };
@@ -250,7 +249,7 @@ async function download(fetchImpl: typeof fetch, lookup: Lookup, target: URL, si
250
249
  const charset = /charset=([^;]+)/i.exec(res.headers.get("content-type") ?? "")?.[1]?.trim();
251
250
  const raw = decode(buf, charset);
252
251
  if (type === "text/html" || type === "application/xhtml+xml" || (!type && /^\s*<(!doctype|html)/i.test(raw))) {
253
- const { title, text } = htmlToMarkdown(raw, url.href);
252
+ const { title, text } = await htmlToMarkdown(raw, url.href);
254
253
  return { at: Date.now(), url: url.href, title, text, thin: text.length < THIN_CHARS };
255
254
  }
256
255
  if (type.startsWith("text/") || /json|xml|javascript|yaml|toml/.test(type) || !type) {
@@ -303,9 +302,11 @@ const BLOCKS = new Set(["p", "div", "section", "article", "main", "header", "ul"
303
302
 
304
303
  /**
305
304
  * 用 htmlparser2 把网页转成 markdown 风格的文本:标题、段落、列表、链接、代码块,去掉脚本、样式和导航。
306
- * 不追求还原排版,只要模型能读。Node 和 Bun 都能用(Bun 的 HTMLRewriter 在 Node 里没有)
305
+ * 不追求还原排版,只要模型能读。Node 和 Bun 都能用(Bun 的 HTMLRewriter 在 Node 里没有)。
306
+ * htmlparser2 第一次用到时才加载:导入要几十毫秒,每次启动都付不值得
307
307
  */
308
- export function htmlToMarkdown(html: string, base?: string): { title?: string; text: string } {
308
+ export async function htmlToMarkdown(html: string, base?: string): Promise<{ title?: string; text: string }> {
309
+ const { Parser } = await import("htmlparser2");
309
310
  const out: string[] = [];
310
311
  let skip = 0;
311
312
  let pre = 0;
@@ -10,8 +10,10 @@ import { reviewer } from "./review.js";
10
10
  const ANSWERS = ["once", "always", "deny"];
11
11
  /** derived 里保存"总是允许"规则的键 */
12
12
  const RULES_KEY = "jade/approval/rules";
13
- /** 等用户回答的时限:内核要求 hook 有有限的超时,超时按拒绝处理 */
13
+ /** 等用户回答的默认时限:内核要求 hook 有有限的超时,超时按拒绝处理。配置 askTimeoutMinutes 可以改 */
14
14
  const ASK_TIMEOUT_MS = 24 * 60 * 60 * 1000;
15
+ /** askTimeoutMinutes 的上限:内核的定时器最长约 24.8 天 */
16
+ const MAX_ASK_TIMEOUT_MINUTES = 7 * 24 * 60;
15
17
  const MAX_DETAIL_CHARS = 2000;
16
18
  /** 等工具的审批预览的时限,过了就用默认的 detail */
17
19
  const PREVIEW_TIMEOUT_MS = 5000;
@@ -28,6 +30,9 @@ const reviewedKey = (call) => {
28
30
  let mode = "ask";
29
31
  /** 配置里写错的模式:第一个会话打开时告诉用户(process 里可能还拿不到 ui@1:它的提供者可能排在后面激活) */
30
32
  let badMode;
33
+ let askTimeoutMs = ASK_TIMEOUT_MS;
34
+ /** 配置里写错的 askTimeoutMinutes,和 badMode 一样在第一个会话打开时告诉用户 */
35
+ let badTimeout;
31
36
  /** 经 allowRead 登记的目录;policy 每次判断时读它 */
32
37
  const readRoots = [];
33
38
  /** 经 allowWrite 登记的目录;policy 每次判断时读它 */
@@ -43,6 +48,13 @@ export default definePlugin({
43
48
  mode = configured;
44
49
  else if (configured !== undefined)
45
50
  badMode = JSON.stringify(configured);
51
+ const minutes = ctx.config.askTimeoutMinutes;
52
+ askTimeoutMs = ASK_TIMEOUT_MS;
53
+ badTimeout = undefined;
54
+ if (typeof minutes === "number" && Number.isFinite(minutes) && minutes > 0 && minutes <= MAX_ASK_TIMEOUT_MINUTES)
55
+ askTimeoutMs = minutes * 60_000;
56
+ else if (minutes !== undefined)
57
+ badTimeout = JSON.stringify(minutes);
46
58
  ctx.provide("approval@1", (caller) => ({
47
59
  mode: () => mode,
48
60
  setMode(next) {
@@ -72,6 +84,10 @@ export default definePlugin({
72
84
  ui?.notify(`jade/approval: mode must be one of ${MODES.join(", ")}, got ${badMode}; using ask`, "warning");
73
85
  badMode = undefined;
74
86
  }
87
+ if (badTimeout !== undefined) {
88
+ ui?.notify(`jade/approval: askTimeoutMinutes must be a number of minutes between 0 and ${MAX_ASK_TIMEOUT_MINUTES}, got ${badTimeout}; using 24 hours`, "warning");
89
+ badTimeout = undefined;
90
+ }
75
91
  const renderers = ctx.service("renderers@1");
76
92
  // auto 模式的审查用当前配置的模型;没有 models@1(模型插件被停用)或者配置里关掉时不做审查
77
93
  const models = ctx.service("models@1");
@@ -116,7 +132,7 @@ export default definePlugin({
116
132
  ctx.kernel.hook({
117
133
  kind: "gate",
118
134
  point: "tool.gate",
119
- timeoutMs: ASK_TIMEOUT_MS,
135
+ timeoutMs: askTimeoutMs,
120
136
  fn: async (call, hook) => {
121
137
  const saved = () => {
122
138
  const logged = hook.derived[RULES_KEY] ?? [];
@@ -16,6 +16,10 @@
16
16
  "default": "ask",
17
17
  "description": "ask: ask before changes; auto: changes inside the working directory and harmless commands go through; plan: change nothing, present a plan; readonly: change nothing; yolo: never ask"
18
18
  },
19
+ "askTimeoutMinutes": {
20
+ "default": 1440,
21
+ "description": "how long to wait for an answer to an approval question before denying the call (at most 10080, one week)"
22
+ },
19
23
  "review": {
20
24
  "default": true,
21
25
  "description": "in auto mode, let the model review the calls the rules cannot decide (it can only allow or pass them to you); false turns the review off"
@@ -375,14 +375,36 @@ function real(p) {
375
375
  }
376
376
  }
377
377
  export function policy(opts) {
378
- /** p 在 base 目录里 */
379
- const within = (base, p) => {
380
- // 按真实路径比较:目录里指向外面的符号链接也算外面
381
- const rel = path.relative(real(base), real(path.resolve(opts.cwd, p)));
378
+ /**
379
+ * 作为范围的目录(工作目录、登记的目录、规则里的目录)的真实路径,本会话内记住:复合命令的每个参数都要和它们比,
380
+ * 每次都 realpathSync 是一串同步 IO。只记已经存在的;要判断的路径本身每次都重新解析,符号链接可能随时被换掉
381
+ */
382
+ const bases = new Map();
383
+ const realBase = (dir) => {
384
+ let r = bases.get(dir);
385
+ if (r !== undefined)
386
+ return r;
387
+ try {
388
+ r = realpathSync(dir);
389
+ }
390
+ catch {
391
+ return real(dir);
392
+ }
393
+ bases.set(dir, r);
394
+ return r;
395
+ };
396
+ /** 真实路径 target 在真实路径 base 里 */
397
+ const contains = (base, target) => {
398
+ const rel = path.relative(base, target);
382
399
  // 只有 ".." 这一段才表示上级目录,名为 "..foo" 的目录仍在里面
383
400
  return rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
384
401
  };
385
- const inside = (p) => within(opts.cwd, p) || (opts.writeRoots ?? []).some((r) => within(r, p));
402
+ /** p 在 base 目录里。按真实路径比较:目录里指向外面的符号链接也算外面 */
403
+ const within = (base, p) => contains(realBase(base), real(path.resolve(opts.cwd, p)));
404
+ const inside = (p) => {
405
+ const target = real(path.resolve(opts.cwd, p));
406
+ return contains(realBase(opts.cwd), target) || (opts.writeRoots ?? []).some((r) => contains(realBase(r), target));
407
+ };
386
408
  /** glob 的 pattern 是绝对路径或含 ".." 段时,匹配范围会超出 path */
387
409
  const globEscapes = (pattern) => path.isAbsolute(pattern) || pattern.split(/[\\/]/).includes("..");
388
410
  /** 以 "." 或 "[" 开头的通配段可能匹配到 ".."(取决于 bash 版本和选项),按越界处理 */
@@ -36,10 +36,16 @@ function mediaTokens(b) {
36
36
  const bytes = typeof data === "string" ? (data.length * 3) / 4 : 0;
37
37
  return Math.max(IMAGE_TOKENS, Math.ceil(bytes / PDF_BYTES_PER_TOKEN));
38
38
  }
39
+ /** 块上不发给模型的字段:来源、信任标记,以及 provider 原样保存的原始块(ext,text 和 thinking 会被算两遍) */
40
+ const UNSENT = new Set(["origin", "trust", "ext"]);
39
41
  /** 粗略估算:英文和代码 4 个字符约 1 个 token,中日韩文字每个字约 1 个 token,图片和 PDF 单独估算 */
40
42
  export function estimateTokens(messages) {
41
43
  let media = 0;
42
- const text = JSON.stringify(messages, (_key, value) => {
44
+ const text = JSON.stringify(messages, function (key, value) {
45
+ // 只去掉块自己的这些字段:工具参数里同名的键照常计入。opaque 块的内容全在 ext 里,要算
46
+ const holder = this;
47
+ if (UNSENT.has(key) && typeof holder?.kind === "string" && holder.kind !== "opaque")
48
+ return undefined;
43
49
  const b = value;
44
50
  if (typeof b === "object" && b !== null && (b.kind === "image" || b.kind === "document")) {
45
51
  media += mediaTokens(b);
@@ -36,14 +36,48 @@ export function display(cwd, full) {
36
36
  const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
37
37
  return shown.split(path.sep).join("/");
38
38
  }
39
+ /** 本会话读过、写过的文件 */
40
+ export class SeenFiles {
41
+ files = new Map();
42
+ /** 因为压缩而失效的文件:再改时说明原因,而不是说"没读过" */
43
+ dropped = new Set();
44
+ /**
45
+ * 压缩或清理之后,模型看不到当初读到(写入)的内容了,但 mtime 和 size 没变,修改仍会放行;
46
+ * write_file 可能凭摘要里的记忆写出整个文件。这里按最终的投影检查:那次调用已被总结掉(投影里没有它的 tool_use),
47
+ * 或者结果已被清理(tool_result 里没有工具自己给的内容,只剩插件的占位说明),就当作没读过
48
+ */
49
+ prune(projection) {
50
+ const uses = new Set();
51
+ const cleared = new Set();
52
+ for (const m of projection) {
53
+ for (const b of m.content) {
54
+ if (b.kind === "tool_use")
55
+ uses.add(b.id);
56
+ else if (b.kind === "tool_result" && !b.content.some((c) => c.origin.by === "tool"))
57
+ cleared.add(b.toolUseId);
58
+ }
59
+ }
60
+ for (const [full, s] of this.files) {
61
+ if (s.id === undefined || (uses.has(s.id) && !cleared.has(s.id)))
62
+ continue;
63
+ this.files.delete(full);
64
+ this.dropped.add(full);
65
+ }
66
+ }
67
+ }
39
68
  export function fsTools(cwd, opts = {}) {
40
69
  const at = (p) => resolveIn(cwd, p);
41
- const seen = new Map();
42
- /** 文件没变时保留更早的 call:之前的回复里读过,这次回复里又读一遍,不影响修改 */
43
- const remember = (full, info, call) => {
70
+ const tracked = opts.seen ?? new SeenFiles();
71
+ const seen = tracked.files;
72
+ /**
73
+ * 文件没变时保留更早的 call:之前的回复里读过,这次回复里又读一遍,不影响修改。
74
+ * id 为 undefined 表示沿用原来的(edit_file)
75
+ */
76
+ const remember = (full, info, call, id) => {
44
77
  const s = seen.get(full);
45
78
  const same = s !== undefined && s.mtimeMs === info.mtimeMs && s.size === info.size;
46
- seen.set(full, { mtimeMs: info.mtimeMs, size: info.size, call: same ? Math.min(s.call, call) : call });
79
+ seen.set(full, { mtimeMs: info.mtimeMs, size: info.size, call: same ? Math.min(s.call, call) : call, id: id ?? s?.id });
80
+ tracked.dropped.delete(full);
47
81
  };
48
82
  /** 不能修改已有文件的原因;可以修改时返回 undefined。text 是文件现在的内容 */
49
83
  const staleness = (full, info) => {
@@ -58,6 +92,9 @@ export function fsTools(cwd, opts = {}) {
58
92
  }
59
93
  return undefined;
60
94
  }
95
+ if (tracked.dropped.has(full)) {
96
+ return `The earlier read of ${shown} was compacted out of the conversation, so its content is no longer in context. Read it again before changing it.`;
97
+ }
61
98
  return `${shown} exists but has not been read in this session. Read it with read_file before changing it.`;
62
99
  };
63
100
  const readFileTool = {
@@ -74,7 +111,7 @@ export function fsTools(cwd, opts = {}) {
74
111
  effect: "read",
75
112
  concurrency: "safe",
76
113
  idempotent: true,
77
- async execute(input) {
114
+ async execute(input, ctx) {
78
115
  const { path: p, offset = 1, limit = MAX_LINES } = input;
79
116
  if (limit < 1)
80
117
  return { content: "limit must be at least 1", isError: true };
@@ -110,7 +147,7 @@ export function fsTools(cwd, opts = {}) {
110
147
  return { content: `${display(cwd, full)} is a binary file (${buf.length} bytes) and cannot be shown as text`, isError: true };
111
148
  }
112
149
  const text = buf.toString("utf8");
113
- remember(full, info, opts.responses?.calls ?? -1);
150
+ remember(full, info, opts.responses?.calls ?? -1, ctx?.toolUseId);
114
151
  if (text.length === 0)
115
152
  return { content: "(empty file)" };
116
153
  const lines = text.split(/\r?\n/);
@@ -152,7 +189,7 @@ export function fsTools(cwd, opts = {}) {
152
189
  concurrency: "exclusive",
153
190
  // 写入完整内容,重复执行结果相同
154
191
  idempotent: true,
155
- async execute(input) {
192
+ async execute(input, ctx) {
156
193
  const { path: p, content: given } = input;
157
194
  const full = at(p);
158
195
  const info = await statOrUndefined(full);
@@ -167,7 +204,7 @@ export function fsTools(cwd, opts = {}) {
167
204
  return { content: problem, isError: true };
168
205
  await mkdir(path.dirname(full), { recursive: true });
169
206
  await writeFile(full, content);
170
- remember(full, await stat(full), -1);
207
+ remember(full, await stat(full), -1, ctx?.toolUseId);
171
208
  // 和 read_file 一样数行:末尾的换行不算多出一行
172
209
  const lines = content === "" ? 0 : content.split(/\r?\n/).length - (/\r?\n$/.test(content) ? 1 : 0);
173
210
  return { content: `Wrote ${lines} lines to ${display(cwd, full)}` };
@@ -195,7 +232,7 @@ export function fsTools(cwd, opts = {}) {
195
232
  total += r.count;
196
233
  }
197
234
  await writeFile(full, next);
198
- remember(full, await stat(full), -1);
235
+ remember(full, await stat(full), -1, undefined);
199
236
  return { content: `Edited ${shown} (${total} replacement${total === 1 ? "" : "s"})` };
200
237
  };
201
238
  const editFileTool = {
@@ -265,6 +302,7 @@ export function fsTools(cwd, opts = {}) {
265
302
  const globTool = {
266
303
  name: "glob",
267
304
  description: `Find files by glob pattern (e.g. "src/**/*.ts"), relative to path (default: the working directory). ` +
305
+ `Unlike grep's include, "*.ts" matches only directly under path; use "**/*.ts" for any depth. ` +
268
306
  `Skips files ignored by git, .git and node_modules. Returns at most ${MAX_GLOB} paths.`,
269
307
  inputSchema: {
270
308
  type: "object",
@@ -296,8 +334,9 @@ export function fsTools(cwd, opts = {}) {
296
334
  out.push(display(cwd, path.join(root, rel)));
297
335
  }
298
336
  out.sort();
337
+ // 和 grep 的 include 不同,不含 / 的模式只匹配第一层:模型常按 grep 的习惯写
299
338
  if (out.length === 0)
300
- return { content: "No files matched" };
339
+ return { content: pattern.includes("/") || pattern.startsWith("**") ? "No files matched" : `No files matched. "${pattern}" only matches directly under ${p === "." ? "the working directory" : p}; use "**/${pattern}" to search at any depth.` };
301
340
  return { content: out.join("\n") + (more ? `\n(more than ${MAX_GLOB} matches; narrow the pattern)` : "") };
302
341
  },
303
342
  };
@@ -341,19 +380,41 @@ function replaceIn(text, { old_string, new_string, replace_all }, shown) {
341
380
  const count = text.match(pattern)?.length ?? 0;
342
381
  if (count === 0)
343
382
  return `old_string not found in ${shown}${nearMiss(text, old_string)}`;
344
- if (count > 1 && !replace_all)
345
- return `old_string occurs ${count} times in ${shown}; add context to make it unique or set replace_all`;
383
+ if (count > 1 && !replace_all) {
384
+ return `old_string occurs ${count} times in ${shown} (${linesOf(text, pattern, 5)}); add context to make it unique or set replace_all`;
385
+ }
346
386
  // new_string 的换行沿用被替换那段的;那段只有一行时沿用整个文件的,单行改成多行也不会混进 LF
347
387
  const fileEol = eolOf(text, "\n");
348
388
  const to = (matched) => (new_string.includes("\r\n") ? new_string : new_string.replaceAll("\n", eolOf(matched, fileEol)));
349
389
  // 用函数作替换值,new_string 里的 $& $1 等不会被当成替换模式
350
390
  return { text: text.replace(replace_all ? pattern : new RegExp(pattern.source), to), count: replace_all ? count : 1 };
351
391
  }
392
+ /** pattern 前 max 处匹配所在的行号,例如 "lines 3, 17, 40" */
393
+ function linesOf(text, pattern, max) {
394
+ const found = [];
395
+ let line = 1;
396
+ let from = 0;
397
+ for (const m of text.matchAll(new RegExp(pattern.source, "g"))) {
398
+ for (let i = from; i < m.index; i++)
399
+ if (text.charCodeAt(i) === 10)
400
+ line++;
401
+ from = m.index;
402
+ found.push(line);
403
+ if (found.length === max)
404
+ break;
405
+ }
406
+ return `line${found.length > 1 ? "s" : ""} ${found.join(", ")}${found.length === max ? ", …" : ""}`;
407
+ }
352
408
  /**
353
409
  * old_string 找不到时帮模型定位:忽略空白后能匹配到哪几行,或者第一行出现在哪里。
354
410
  * 只给提示,不自动按模糊匹配修改:那样可能改错地方
355
411
  */
356
412
  export function nearMiss(text, needle) {
413
+ // 最常见的一种:把 read_file 每行开头的行号和制表符一起抄进来了
414
+ const raw = needle.split(/\r?\n/).filter((l) => l.trim() !== "");
415
+ if (raw.length > 0 && raw.every((l) => /^\s*\d+\t/.test(l))) {
416
+ return ". It seems to include read_file's line-number prefixes (the number and tab at the start of each line); they are not part of the file. Remove them and keep the rest exactly";
417
+ }
357
418
  const norm = (l) => l.trim().replace(/\s+/g, " ");
358
419
  const lines = text.split(/\r?\n/).map(norm);
359
420
  const want = needle.split(/\r?\n/).map(norm);