@uncarved/jade 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/README.md +18 -6
  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 +51 -7
  7. package/dist/distro.js +199 -48
  8. package/dist/distro.js.map +1 -1
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.js +3 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/main.js +479 -303
  13. package/dist/main.js.map +1 -1
  14. package/dist/mcp.js +1 -1
  15. package/dist/mcp.js.map +1 -1
  16. package/dist/plugin-cli.d.ts +1 -1
  17. package/dist/plugin-cli.js +79 -36
  18. package/dist/plugin-cli.js.map +1 -1
  19. package/dist/plugins/budget.d.ts +2 -2
  20. package/dist/plugins/budget.js +2 -2
  21. package/dist/plugins/budget.js.map +1 -1
  22. package/dist/plugins/builtins.js +6 -3
  23. package/dist/plugins/builtins.js.map +1 -1
  24. package/dist/plugins/checks.d.ts +2 -1
  25. package/dist/plugins/checks.js +25 -5
  26. package/dist/plugins/checks.js.map +1 -1
  27. package/dist/plugins/compact.js +45 -1
  28. package/dist/plugins/compact.js.map +1 -1
  29. package/dist/plugins/core.d.ts +5 -0
  30. package/dist/plugins/core.js +39 -0
  31. package/dist/plugins/core.js.map +1 -1
  32. package/dist/plugins/host.d.ts +52 -0
  33. package/dist/plugins/host.js +115 -0
  34. package/dist/plugins/host.js.map +1 -0
  35. package/dist/plugins/install.d.ts +1 -1
  36. package/dist/plugins/loader.d.ts +238 -10
  37. package/dist/plugins/loader.js +175 -21
  38. package/dist/plugins/loader.js.map +1 -1
  39. package/dist/plugins/policy.d.ts +23 -5
  40. package/dist/plugins/policy.js +63 -10
  41. package/dist/plugins/policy.js.map +1 -1
  42. package/dist/plugins/prompts.d.ts +14 -1
  43. package/dist/plugins/prompts.js +118 -16
  44. package/dist/plugins/prompts.js.map +1 -1
  45. package/dist/plugins/repeats.d.ts +7 -0
  46. package/dist/plugins/repeats.js +74 -13
  47. package/dist/plugins/repeats.js.map +1 -1
  48. package/dist/plugins/review.d.ts +18 -0
  49. package/dist/plugins/review.js +130 -0
  50. package/dist/plugins/review.js.map +1 -0
  51. package/dist/plugins/sessions.d.ts +7 -0
  52. package/dist/plugins/sessions.js +110 -0
  53. package/dist/plugins/sessions.js.map +1 -0
  54. package/dist/provider.d.ts +57 -3
  55. package/dist/provider.js +80 -10
  56. package/dist/provider.js.map +1 -1
  57. package/dist/session-lifecycle.d.ts +61 -0
  58. package/dist/session-lifecycle.js +167 -0
  59. package/dist/session-lifecycle.js.map +1 -0
  60. package/dist/session-scope.d.ts +53 -0
  61. package/dist/session-scope.js +116 -0
  62. package/dist/session-scope.js.map +1 -0
  63. package/dist/sessions.d.ts +6 -0
  64. package/dist/sessions.js +20 -0
  65. package/dist/sessions.js.map +1 -1
  66. package/dist/sys.d.ts +4 -1
  67. package/dist/sys.js +18 -1
  68. package/dist/sys.js.map +1 -1
  69. package/dist/tools/ask.d.ts +11 -0
  70. package/dist/tools/ask.js +62 -0
  71. package/dist/tools/ask.js.map +1 -0
  72. package/dist/tools/fs.d.ts +4 -0
  73. package/dist/tools/fs.js +53 -12
  74. package/dist/tools/fs.js.map +1 -1
  75. package/dist/tools/grep.js +3 -2
  76. package/dist/tools/grep.js.map +1 -1
  77. package/dist/tools/shell.js +5 -1
  78. package/dist/tools/shell.js.map +1 -1
  79. package/dist/tools/task.d.ts +10 -2
  80. package/dist/tools/task.js +40 -9
  81. package/dist/tools/task.js.map +1 -1
  82. package/dist/tools/web.d.ts +33 -3
  83. package/dist/tools/web.js +351 -143
  84. package/dist/tools/web.js.map +1 -1
  85. package/dist/ui/configure.js +144 -66
  86. package/dist/ui/configure.js.map +1 -1
  87. package/dist/ui/diff.d.ts +1 -1
  88. package/dist/ui/diff.js +1 -2
  89. package/dist/ui/diff.js.map +1 -1
  90. package/dist/ui/editor.d.ts +8 -0
  91. package/dist/ui/editor.js +50 -1
  92. package/dist/ui/editor.js.map +1 -1
  93. package/dist/ui/markdown.d.ts +22 -0
  94. package/dist/ui/markdown.js +242 -0
  95. package/dist/ui/markdown.js.map +1 -0
  96. package/dist/ui/render.d.ts +9 -8
  97. package/dist/ui/render.js +35 -62
  98. package/dist/ui/render.js.map +1 -1
  99. package/dist/ui/renderers.d.ts +8 -0
  100. package/dist/ui/renderers.js +169 -0
  101. package/dist/ui/renderers.js.map +1 -0
  102. package/dist/ui/screen.d.ts +25 -2
  103. package/dist/ui/screen.js +104 -12
  104. package/dist/ui/screen.js.map +1 -1
  105. package/dist/ui/transcript.d.ts +13 -0
  106. package/dist/ui/transcript.js +157 -31
  107. package/dist/ui/transcript.js.map +1 -1
  108. package/dist/ui/tui.d.ts +2 -0
  109. package/dist/ui/tui.js +383 -81
  110. package/dist/ui/tui.js.map +1 -1
  111. package/dist/update.d.ts +53 -0
  112. package/dist/update.js +255 -0
  113. package/dist/update.js.map +1 -0
  114. package/package.json +7 -6
  115. package/src/commands.ts +24 -0
  116. package/src/distro.ts +234 -52
  117. package/src/index.ts +3 -0
  118. package/src/main.ts +459 -300
  119. package/src/mcp.ts +1 -1
  120. package/src/plugin-cli.ts +73 -34
  121. package/src/plugins/budget.ts +4 -4
  122. package/src/plugins/builtins.ts +6 -3
  123. package/src/plugins/checks.ts +25 -6
  124. package/src/plugins/compact.ts +40 -1
  125. package/src/plugins/core.ts +40 -0
  126. package/src/plugins/host.ts +146 -0
  127. package/src/plugins/install.ts +1 -1
  128. package/src/plugins/loader.ts +379 -23
  129. package/src/plugins/policy.ts +70 -13
  130. package/src/plugins/prompts.ts +128 -16
  131. package/src/plugins/repeats.ts +75 -14
  132. package/src/plugins/review.ts +146 -0
  133. package/src/plugins/sessions.ts +109 -0
  134. package/src/provider.ts +117 -14
  135. package/src/session-lifecycle.ts +194 -0
  136. package/src/session-scope.ts +135 -0
  137. package/src/sessions.ts +17 -0
  138. package/src/sys.ts +18 -1
  139. package/src/tools/ask.ts +72 -0
  140. package/src/tools/fs.ts +53 -12
  141. package/src/tools/grep.ts +3 -2
  142. package/src/tools/shell.ts +5 -1
  143. package/src/tools/task.ts +56 -12
  144. package/src/tools/web.ts +370 -140
  145. package/src/ui/configure.ts +141 -67
  146. package/src/ui/diff.ts +1 -2
  147. package/src/ui/editor.ts +50 -1
  148. package/src/ui/markdown.ts +258 -0
  149. package/src/ui/render.ts +35 -48
  150. package/src/ui/renderers.ts +183 -0
  151. package/src/ui/screen.ts +113 -16
  152. package/src/ui/transcript.ts +164 -35
  153. package/src/ui/tui.tsx +424 -79
  154. package/src/update.ts +262 -0
@@ -0,0 +1,135 @@
1
+ // 会话级的插件作用域(SessionScope):一套插件实例,加上绑定到这套实例的 ctx.status、ctx.input、ctx.send、ctx.signal。
2
+ //
3
+ // preparing ──activate──▶ active ──close──▶ closing ──dispose──▶ closed
4
+ // └──────────────────close──────────────────┘
5
+ //
6
+ // 换会话是一个事务:先在 preparing 里创建新的一套(工厂函数这时运行),成功了才关闭旧的、激活新的;
7
+ // 失败了只关闭新的,旧的一直是 active,不用恢复任何东西。见 docs/design/jade-plugin-lifecycle.md 第 3.2、5 节。
8
+
9
+ import type { Jade } from "./distro.ts";
10
+
11
+ export type ScopeState = "preparing" | "active" | "closing" | "closed";
12
+
13
+ /** 宿主的界面:作用域经它显示状态栏、改输入框、替用户发送、提示问题 */
14
+ export interface ScopeHost {
15
+ /** 换掉状态栏上插件的段落(按插件的 id) */
16
+ showStatus(segments: { plugin: string; text: string }[]): void;
17
+ /** 终端界面的输入框;-p 时没有 */
18
+ input?: { text(): string; insert(text: string): void; set(text: string): void };
19
+ /** 替用户提交一行;-p 时没有 */
20
+ send?(plugin: string, text: string): void;
21
+ warn(text: string): void;
22
+ /** 状态栏一段的整理(去掉控制字符、截断);返回空字符串表示去掉 */
23
+ tidy?(text: string): string;
24
+ }
25
+
26
+ export class SessionScope {
27
+ #state: ScopeState = "preparing";
28
+ readonly #host: ScopeHost;
29
+ readonly #abort = new AbortController();
30
+ /** 插件设置的状态栏段落;preparing 时先存着,activate 时显示 */
31
+ readonly #status = new Map<string, string>();
32
+ /** 已经提示过过期调用的插件,每个只提示一次 */
33
+ readonly #warned = new Set<string>();
34
+ #jade: Jade | undefined;
35
+ #disposing: Promise<string[]> | undefined;
36
+
37
+ constructor(host: ScopeHost) {
38
+ this.#host = host;
39
+ }
40
+
41
+ get state(): ScopeState {
42
+ return this.#state;
43
+ }
44
+
45
+ /** 关闭时中止:交给插件的 ctx.signal、快捷键的 signal 都是它 */
46
+ get signal(): AbortSignal {
47
+ return this.#abort.signal;
48
+ }
49
+
50
+ /** 这个作用域的插件实例;attach 之前不能用 */
51
+ get jade(): Jade {
52
+ if (!this.#jade) throw new Error("the session scope has no plugins yet");
53
+ return this.#jade;
54
+ }
55
+
56
+ /** 交给 createJade 的回调:插件的 ctx 都经过这里,按作用域的状态决定是否生效 */
57
+ get hooks() {
58
+ const host = this.#host;
59
+ return {
60
+ signal: this.signal,
61
+ onStatus: (plugin: string, text: string | undefined) => this.#setStatus(plugin, text),
62
+ input: host.input && {
63
+ text: (plugin?: string) => (this.#live(plugin, "ctx.input") ? host.input!.text() : ""),
64
+ insert: (text: string, plugin?: string) => void (this.#live(plugin, "ctx.input") && host.input!.insert(String(text))),
65
+ set: (text: string, plugin?: string) => void (this.#live(plugin, "ctx.input") && host.input!.set(String(text))),
66
+ },
67
+ send: host.send && ((plugin: string, text: string) => void (this.#live(plugin, "ctx.send") && host.send!(plugin, text))),
68
+ };
69
+ }
70
+
71
+ /** 创建好插件实例后挂上 */
72
+ attach(jade: Jade): void {
73
+ this.#jade = jade;
74
+ }
75
+
76
+ /** preparing → active:显示插件在准备期间设置的状态 */
77
+ activate(): void {
78
+ if (this.#state !== "preparing") throw new Error(`cannot activate the session scope: it is ${this.#state}`);
79
+ this.#state = "active";
80
+ this.#show();
81
+ }
82
+
83
+ /**
84
+ * → closing:中止 signal(进行中的快捷键等随之中止),之后 ctx.status、ctx.input、ctx.send 不再生效;
85
+ * dispose 完成(closed)之后还调用的才提示,那是插件忘了在 dispose 里停掉的定时器、监听。
86
+ * 不清状态栏:接着激活的作用域会换掉它;回滚时没激活过,也就没显示过
87
+ */
88
+ close(reason: string): void {
89
+ if (this.#state === "closing" || this.#state === "closed") return;
90
+ this.#state = "closing";
91
+ this.#abort.abort(new Error(reason));
92
+ }
93
+
94
+ /** 调用插件的 dispose(见 Jade.dispose),→ closed。先 close;只执行一次,返回要告诉用户的问题 */
95
+ dispose(): Promise<string[]> {
96
+ this.close("the session ended");
97
+ return (this.#disposing ??= (this.#jade ? this.#jade.dispose() : Promise.resolve([])).then((warnings) => {
98
+ this.#state = "closed";
99
+ return warnings;
100
+ }));
101
+ }
102
+
103
+ #setStatus(plugin: string, text: string | undefined) {
104
+ const line = text === undefined ? "" : (this.#host.tidy ?? ((t: string) => t.trim()))(String(text));
105
+ if (this.#state === "closing" || this.#state === "closed") {
106
+ // closing 时插件还没轮到 dispose(会话收尾还在进行),定时器再触发一次是正常的;dispose 里去掉自己的段落也正常
107
+ if (line && this.#state === "closed") this.#stale(plugin, "ctx.status", "after its session ended");
108
+ return;
109
+ }
110
+ if (line) this.#status.set(plugin, line);
111
+ else this.#status.delete(plugin);
112
+ if (this.#state === "active") this.#show();
113
+ }
114
+
115
+ #show() {
116
+ this.#host.showStatus([...this.#status].map(([plugin, text]) => ({ plugin, text })));
117
+ }
118
+
119
+ /** 是否 active。preparing 和 closed 时提示一次;closing 时插件还没轮到 dispose,不提示 */
120
+ #live(plugin: string | undefined, what: string): boolean {
121
+ if (this.#state === "active") return true;
122
+ if (this.#state === "preparing") this.#stale(plugin, what, "before its session started");
123
+ else if (this.#state === "closed") this.#stale(plugin, what, "after its session ended");
124
+ return false;
125
+ }
126
+
127
+ #stale(plugin: string | undefined, what: string, when: string) {
128
+ const key = plugin ?? "";
129
+ if (this.#warned.has(key)) return;
130
+ this.#warned.add(key);
131
+ const who = plugin ? `plugin ${plugin}` : "a plugin";
132
+ const fix = when.startsWith("after") ? "; stop timers and listeners in dispose, or when ctx.signal aborts" : "";
133
+ this.#host.warn(`${who} used ${what} ${when}, so it was ignored${fix}`);
134
+ }
135
+ }
package/src/sessions.ts CHANGED
@@ -59,3 +59,20 @@ export async function discardIfEmpty(store: LogStore & { dir: string }, sessionI
59
59
  await rm(path.join(store.dir, `${sessionId}.jsonl`), { force: true });
60
60
  return true;
61
61
  }
62
+
63
+ /** id 等于 arg 或以它开头的唯一一个会话;都不是时原样返回,交给 Runtime.resume 去找 */
64
+ export function matchSession(entries: { id: string }[], arg: string): string {
65
+ const hits = entries.filter((s) => s.id.startsWith(arg));
66
+ return hits.find((s) => s.id === arg)?.id ?? (hits.length === 1 ? hits[0]!.id : arg);
67
+ }
68
+
69
+ /** 显示用的相对时间 */
70
+ export function ago(iso: string, now = Date.now()): string {
71
+ const s = (now - Date.parse(iso)) / 1000;
72
+ if (!Number.isFinite(s)) return iso;
73
+ if (s < 60) return "just now";
74
+ if (s < 3600) return `${Math.floor(s / 60)} min ago`;
75
+ if (s < 86400) return `${Math.floor(s / 3600)} h ago`;
76
+ if (s < 86400 * 7) return `${Math.floor(s / 86400)} d ago`;
77
+ return iso.slice(0, 10);
78
+ }
package/src/sys.ts CHANGED
@@ -82,8 +82,25 @@ export async function text(stream: AsyncIterable<Uint8Array>): Promise<string> {
82
82
  return out + decoder.decode();
83
83
  }
84
84
 
85
- /** 在 PATH 里找可执行文件,找不到返回 undefined。Windows 上按 PATHEXT 补扩展名;带路径分隔符时只检查那个文件 */
85
+ /** which 的结果,按 PATH 和 PATHEXT 记;找不到的过一会儿再查(会话中途装上的工具能用上) */
86
+ const found = new Map<string, { file: string | undefined; at: number }>();
87
+ const MISS_TTL_MS = 30_000;
88
+
89
+ /**
90
+ * 在 PATH 里找可执行文件,找不到返回 undefined。Windows 上按 PATHEXT 补扩展名;带路径分隔符时只检查那个文件。
91
+ * 结果会记住:编辑后检查每批修改都要找 ruff、go,每次同步扫一遍 PATH 要几毫秒,期间事件循环停住
92
+ */
86
93
  export function which(bin: string): string | undefined {
94
+ if (bin.includes("/") || (process.platform === "win32" && bin.includes("\\"))) return lookup(bin);
95
+ const key = `${bin}\0${process.env.PATH ?? process.env.Path ?? ""}\0${process.env.PATHEXT ?? ""}`;
96
+ const hit = found.get(key);
97
+ if (hit && (hit.file !== undefined || Date.now() - hit.at < MISS_TTL_MS)) return hit.file;
98
+ const file = lookup(bin);
99
+ found.set(key, { file, at: Date.now() });
100
+ return file;
101
+ }
102
+
103
+ function lookup(bin: string): string | undefined {
87
104
  const win = process.platform === "win32";
88
105
  const exts = win ? ["", ...(process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
89
106
  const ok = (file: string) => {
@@ -0,0 +1,72 @@
1
+ // ask_user 工具:模型拿不准、而答案会改变它要做的事时,先问用户再动手。
2
+ //
3
+ // 每个问题给几个选项让用户选,也可以自己输入回答。怎么显示由宿主决定(ask);
4
+ // 不能交互(-p、非终端)时直接返回"用户不在",让模型按合理的假设继续并说明假设。
5
+
6
+ import type { Tool } from "uncarved";
7
+
8
+ export interface Question {
9
+ question: string;
10
+ options: { label: string; description?: string }[];
11
+ }
12
+
13
+ /** 宿主问用户:每个问题一个回答;用户取消时返回 undefined */
14
+ export type AskUser = (questions: Question[], signal: AbortSignal) => Promise<string[] | undefined>;
15
+
16
+ const MAX_QUESTIONS = 4;
17
+
18
+ export function askUserTool(ask: AskUser): Tool {
19
+ return {
20
+ name: "ask_user",
21
+ description:
22
+ "Ask the user one to four questions and wait for the answers. Use it before starting work when the request is ambiguous in a way that changes what you would do " +
23
+ "(scope, approach, a trade-off or preference only the user can decide). Do not ask about things you can find out from the code, docs or tools, " +
24
+ "or that have a sensible default (pick it and say so). Each question offers 2-4 options; the user can also type their own answer. " +
25
+ "Put your recommended option first.",
26
+ inputSchema: {
27
+ type: "object",
28
+ properties: {
29
+ questions: {
30
+ type: "array",
31
+ items: {
32
+ type: "object",
33
+ properties: {
34
+ question: { type: "string", description: "The complete question, ending with a question mark" },
35
+ options: {
36
+ type: "array",
37
+ items: {
38
+ type: "object",
39
+ properties: {
40
+ label: { type: "string", description: "1-5 words" },
41
+ description: { type: "string", description: "What choosing it means, trade-offs" },
42
+ },
43
+ required: ["label"],
44
+ additionalProperties: false,
45
+ },
46
+ },
47
+ },
48
+ required: ["question", "options"],
49
+ additionalProperties: false,
50
+ },
51
+ },
52
+ },
53
+ required: ["questions"],
54
+ additionalProperties: false,
55
+ },
56
+ // 不碰文件和进程:所有模式(包括 plan)都不用批准
57
+ effect: "read",
58
+ concurrency: "exclusive",
59
+ idempotent: false,
60
+ async execute(input, ctx) {
61
+ const { questions } = input as { questions: Question[] };
62
+ if (questions.length === 0 || questions.length > MAX_QUESTIONS) return { content: `questions must have 1-${MAX_QUESTIONS} items`, isError: true };
63
+ const bad = questions.find((q) => q.options.length < 2 || q.options.length > 4);
64
+ if (bad) return { content: `each question needs 2-4 options ("${bad.question}" has ${bad.options.length})`, isError: true };
65
+ const answers = await ask(questions, ctx.signal);
66
+ if (answers === undefined) {
67
+ return { content: "The user dismissed the questions without answering. Do not ask again: proceed with your best judgment and state your assumptions, or end your turn." };
68
+ }
69
+ return { content: questions.map((q, i) => `Q: ${q.question}\nA: ${answers[i] ?? "(no answer)"}`).join("\n\n") };
70
+ },
71
+ };
72
+ }
package/src/tools/fs.ts CHANGED
@@ -17,6 +17,8 @@ import { globMatcher, run } from "../sys.ts";
17
17
 
18
18
  const MAX_LINES = 2000;
19
19
  const MAX_LINE_CHARS = 2000;
20
+ /** 一次 read_file 返回的文本上限(约 25k token) */
21
+ const MAX_READ_CHARS = 100_000;
20
22
  const MAX_GLOB = 500;
21
23
  const MAX_IMAGE_BYTES = 5_000_000;
22
24
  const MAX_PDF_BYTES = 10_000_000;
@@ -51,6 +53,8 @@ export interface FsOptions {
51
53
  responses?: { readonly calls: number };
52
54
  /** grep 用的 ripgrep,默认 "rg";null 表示不用(测试) */
53
55
  rg?: string | null;
56
+ /** 会话的临时目录:里面的文件只有模型自己会写(包括它跑的命令生成的),修改前不用先读 */
57
+ scratch?: string;
54
58
  }
55
59
 
56
60
  /** 读过或写过的文件当时的样子;只在本进程内有效,恢复的会话靠 checkpoints 里记的 sha256 */
@@ -64,6 +68,11 @@ interface Seen {
64
68
  export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
65
69
  const at = (p: unknown) => resolveIn(cwd, p as string);
66
70
  const seen = new Map<string, Seen>();
71
+ const inScratch = (full: string) => {
72
+ if (opts.scratch === undefined) return false;
73
+ const rel = path.relative(opts.scratch, full);
74
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
75
+ };
67
76
  /** 文件没变时保留更早的 call:之前的回复里读过,这次回复里又读一遍,不影响修改 */
68
77
  const remember = async (ctx: { sessionId: string }, full: string, info: Stats, text: string, call: number) => {
69
78
  const s = seen.get(full);
@@ -73,6 +82,7 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
73
82
  };
74
83
  /** 不能修改已有文件的原因;可以修改时返回 undefined。text 是文件现在的内容 */
75
84
  const staleness = async (ctx: { sessionId: string }, full: string, info: Stats, text: string): Promise<string | undefined> => {
85
+ if (inScratch(full)) return undefined;
76
86
  const shown = display(cwd, full);
77
87
  const modified = `${shown} has been modified since it was last read (by the user or a command). Read it again before changing it.`;
78
88
  const s = seen.get(full);
@@ -98,7 +108,8 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
98
108
  name: "read_file",
99
109
  description:
100
110
  "Read a UTF-8 text file, an image (png, jpg, gif, webp) or a PDF. Text is returned as lines prefixed with their 1-based line number and a tab. " +
101
- `At most ${MAX_LINES} lines are returned per call; use offset (1-based start line) and limit to page through larger files.`,
111
+ `At most ${MAX_LINES} lines (about ${MAX_READ_CHARS / 1000}k characters) are returned per call; use offset (1-based start line) and limit to page through larger files. ` +
112
+ `Lines longer than ${MAX_LINE_CHARS} characters are cut and marked "[line truncated]"; do not copy a cut line into edit_file.`,
102
113
  inputSchema: {
103
114
  type: "object",
104
115
  properties: { path: str, offset: int, limit: int },
@@ -147,10 +158,20 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
147
158
  const start = Math.max(1, offset);
148
159
  const slice = lines.slice(start - 1, start - 1 + Math.min(limit, MAX_LINES));
149
160
  if (slice.length === 0) return { content: `(file has ${lines.length} lines; offset ${start} is past the end)`, isError: true };
150
- const body = slice
151
- .map((l, i) => `${start + i}\t${l.length > MAX_LINE_CHARS ? l.slice(0, MAX_LINE_CHARS) + "…" : l}`)
152
- .join("\n");
153
- const end = start + slice.length - 1;
161
+ // 按整行截断到 MAX_READ_CHARS:压缩过的代码、lock 文件一次就能占掉大半个上下文
162
+ const out: string[] = [];
163
+ let size = 0;
164
+ for (const [i, l] of slice.entries()) {
165
+ const row = `${start + i}\t${l.length > MAX_LINE_CHARS ? `${l.slice(0, MAX_LINE_CHARS)}… [line truncated: ${l.length} characters]` : l}`;
166
+ if (out.length > 0 && size + row.length + 1 > MAX_READ_CHARS) break;
167
+ out.push(row);
168
+ size += row.length + 1;
169
+ }
170
+ const body = out.join("\n");
171
+ const end = start + out.length - 1;
172
+ if (out.length < slice.length) {
173
+ return { content: `${body}\n(output capped at about ${MAX_READ_CHARS} characters: showing lines ${start}-${end} of ${lines.length}; continue with offset ${end + 1})` };
174
+ }
154
175
  return { content: end < lines.length ? `${body}\n(showing lines ${start}-${end} of ${lines.length})` : body };
155
176
  },
156
177
  };
@@ -171,12 +192,14 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
171
192
  // 写入完整内容,重复执行结果相同
172
193
  idempotent: true,
173
194
  async execute(input, ctx) {
174
- const { path: p, content } = input as { path: string; content: string };
195
+ const { path: p, content: given } = input as { path: string; content: string };
175
196
  const full = at(p);
176
197
  const info = await statOrUndefined(full);
177
198
  if (info?.isDirectory()) return { content: `${display(cwd, full)} is a directory`, isError: true };
178
199
  // 同样内容重复写入(崩溃后重跑)不算覆盖别人的修改
179
200
  const before = info ? await readFile(full, "utf8") : null;
201
+ // read_file 不显示换行风格和 BOM:覆盖已有文件时沿用原来的,否则整个文件每一行都算改了
202
+ const content = before === null ? given : keepStyle(before, given);
180
203
  const problem = info && before !== null && before !== content ? await staleness(ctx, full, info, before) : undefined;
181
204
  if (problem) return { content: problem, isError: true };
182
205
  await mkdir(path.dirname(full), { recursive: true });
@@ -341,19 +364,37 @@ export function applyEditsToText(text: string, edits: Edit[], shown: string): st
341
364
  return { text: next };
342
365
  }
343
366
 
367
+ /** text 里多数换行是 CRLF 时返回 "\r\n",多数是 LF 时返回 "\n",一样多或没有换行时返回 fallback */
368
+ function eolOf(text: string, fallback: string): string {
369
+ const crlf = text.split("\r\n").length - 1;
370
+ const lf = text.split("\n").length - 1 - crlf;
371
+ return crlf > lf ? "\r\n" : lf > crlf ? "\n" : fallback;
372
+ }
373
+
374
+ /** 原文件主要用 CRLF、新内容只有 LF 时换成 CRLF;原文件有 BOM、新内容没有时补上 */
375
+ export function keepStyle(before: string, content: string): string {
376
+ let out = content;
377
+ if (eolOf(before, "\n") === "\r\n" && !out.includes("\r\n")) out = out.replaceAll("\n", "\r\n");
378
+ if (before.startsWith("") && !out.startsWith("")) out = `${out}`;
379
+ return out;
380
+ }
381
+
382
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
383
+
344
384
  /** 在 text 上做一次替换;失败时返回原因 */
345
385
  function replaceIn(text: string, { old_string, new_string, replace_all }: Edit, shown: string): { text: string; count: number } | string {
346
386
  if (old_string === new_string) return "old_string and new_string are identical";
347
387
  if (old_string === "") return "old_string must not be empty; use write_file to create a file";
348
- // 文件是 CRLF 时,模型给的 LF 文本也能匹配
349
- const crlf = text.includes("\r\n") && !old_string.includes("\r\n");
350
- const from = crlf ? old_string.replaceAll("\n", "\r\n") : old_string;
351
- const to = crlf ? new_string.replaceAll("\n", "\r\n") : new_string;
352
- const count = text.split(from).length - 1;
388
+ // read_file 不显示换行风格:old_string 里的换行匹配 LF 和 CRLF,CRLF 文件、换行混用的文件都能对上
389
+ const pattern = new RegExp(old_string.split(/\r?\n/).map(escapeRegExp).join("\\r?\\n"), "g");
390
+ const count = text.match(pattern)?.length ?? 0;
353
391
  if (count === 0) return `old_string not found in ${shown}${nearMiss(text, old_string)}`;
354
392
  if (count > 1 && !replace_all) return `old_string occurs ${count} times in ${shown}; add context to make it unique or set replace_all`;
393
+ // new_string 的换行沿用被替换那段的;那段只有一行时沿用整个文件的,单行改成多行也不会混进 LF
394
+ const fileEol = eolOf(text, "\n");
395
+ const to = (matched: string) => (new_string.includes("\r\n") ? new_string : new_string.replaceAll("\n", eolOf(matched, fileEol)));
355
396
  // 用函数作替换值,new_string 里的 $& $1 等不会被当成替换模式
356
- return { text: replace_all ? text.replaceAll(from, () => to) : text.replace(from, () => to), count: replace_all ? count : 1 };
397
+ return { text: text.replace(replace_all ? pattern : new RegExp(pattern.source), to), count: replace_all ? count : 1 };
357
398
  }
358
399
 
359
400
  /**
package/src/tools/grep.ts CHANGED
@@ -61,7 +61,7 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
61
61
  name: "grep",
62
62
  description:
63
63
  "Search file contents with a regular expression (JavaScript syntax). Searches path (a file or directory, default: the working directory), " +
64
- `optionally only files matching the glob include (e.g. "**/*.ts"). Skips files ignored by git, binary files and .git/node_modules. ` +
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
67
  `context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode.`,
@@ -232,7 +232,8 @@ async function ripgrep(rg: string, s: Search): Promise<Found | undefined | "miss
232
232
  // ---------- JS ----------
233
233
 
234
234
  async function jsGrep(s: Search): Promise<Found> {
235
- const filter = s.include ? globMatcher(s.include) : undefined;
235
+ // 和 ripgrep 的 --glob 一致:不含 / 的模式("*.ts")匹配任意深度的文件名
236
+ const filter = s.include ? globMatcher(s.include.includes("/") ? s.include : `**/${s.include}`) : undefined;
236
237
  const files: FileHits[] = [];
237
238
  let matches = 0;
238
239
  const single = (await stat(s.root)).isFile();
@@ -143,7 +143,11 @@ export function shellTools(opts: ShellOptions): ShellTools {
143
143
  proc.exited,
144
144
  ]);
145
145
  signal.throwIfAborted();
146
- const parts = [timedOut ? `Timed out after ${timeout}ms (killed)` : `Exit code ${code}`];
146
+ const parts = [
147
+ timedOut
148
+ ? `Timed out after ${timeout}ms (killed). If it needs longer, raise timeout_ms (max ${MAX_TIMEOUT_MS / 1000}s); for servers and watchers use run_in_background.`
149
+ : `Exit code ${code}`,
150
+ ];
147
151
  if (stdout) parts.push(`<stdout>\n${stdout}\n</stdout>`);
148
152
  if (stderr) parts.push(`<stderr>\n${stderr}\n</stderr>`);
149
153
  return { content: parts.join("\n"), isError: timedOut || code !== 0 };
package/src/tools/task.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  // task 工具:启动一个只读的子 Agent。子 Agent 是一个普通会话,用日志引用和父会话关联(3.4、第六章)。
2
2
  // 子 Agent 调用的工具通过 ctx.progress 推给宿主显示;需要用户批准的调用(例如 web_fetch)交给宿主的 approve。
3
3
 
4
- import { Runtime, type EventDataMap, type LogStore, type Plugin, type Provider, type Tool } from "uncarved";
4
+ import { Runtime, type EventDataMap, type LogStore, type Message, type Plugin, type Provider, type Tool } from "uncarved";
5
5
 
6
6
  /** ctx.progress 推送的内容 */
7
7
  export type TaskProgress =
8
8
  | { kind: "task-start"; sessionId: string; description: string }
9
+ /** 子 Agent 在等模型回复 */
10
+ | { kind: "task-model" }
9
11
  | { kind: "task-tool"; name: string; input: unknown; decision: string };
10
12
 
11
13
  /** 子 Agent 的调用要用户批准时,宿主给出的回答 */
@@ -16,17 +18,30 @@ export interface SubagentApproval {
16
18
 
17
19
  export type ApproveSubagent = (call: { toolUseId: string; name: string; input: unknown }, signal: AbortSignal) => Promise<SubagentApproval>;
18
20
 
21
+ /** 一个子会话的控制:wrapUp 为 true 时步数上限收紧到一步,只让它写报告 */
22
+ export interface SubagentControl {
23
+ wrapUp: boolean;
24
+ }
25
+
19
26
  export interface TaskOptions {
20
27
  store: LogStore;
21
28
  provider: Provider;
22
- /** 每个子会话一套新的插件实例 */
23
- plugins: () => Plugin[];
29
+ /** 每个子会话一套新的插件实例;步数插件读取 control */
30
+ plugins: (control: SubagentControl) => Plugin[];
24
31
  /** 不给时一律拒绝 */
25
32
  approve?: ApproveSubagent;
26
33
  }
27
34
 
28
35
  const NOBODY: SubagentApproval = { approved: false, reason: "Nobody can approve this action for a sub-agent. Report what you need instead." };
29
36
 
37
+ /** 用完步数还没写报告时追加的消息 */
38
+ const WRAP_UP =
39
+ "You have reached your step limit. Do not call any more tools: write your report now from what you have found so far, " +
40
+ "and say what you could not check.";
41
+
42
+ /** 返回给主会话的报告上限,免得一个子 Agent 撑满主会话的上下文 */
43
+ const MAX_REPORT_CHARS = 20_000;
44
+
30
45
  export function taskTool(opts: TaskOptions): Tool {
31
46
  return {
32
47
  name: "task",
@@ -50,10 +65,11 @@ export function taskTool(opts: TaskOptions): Tool {
50
65
  idempotent: true,
51
66
  async execute(input, ctx) {
52
67
  const { description, prompt } = input as { description: string; prompt: string };
68
+ const control: SubagentControl = { wrapUp: false };
53
69
  const child = await Runtime.create({
54
70
  store: opts.store,
55
71
  provider: opts.provider,
56
- plugins: opts.plugins(),
72
+ plugins: opts.plugins(control),
57
73
  parent: ctx.parent,
58
74
  });
59
75
  const sessionId = child.state.sessionId;
@@ -62,7 +78,9 @@ export function taskTool(opts: TaskOptions): Tool {
62
78
  const names = new Map<string, string>();
63
79
  child.subscribe((n) => {
64
80
  if (n.type !== "event") return;
65
- if (n.event.type === "model.responded") {
81
+ if (n.event.type === "model.requested") {
82
+ progress({ kind: "task-model" });
83
+ } else if (n.event.type === "model.responded") {
66
84
  for (const b of (n.event.data as EventDataMap["model.responded"]).content) if (b.kind === "tool_use") names.set(b.id, b.name);
67
85
  } else if (n.event.type === "tool.decided") {
68
86
  const d = n.event.data as EventDataMap["tool.decided"];
@@ -72,17 +90,22 @@ export function taskTool(opts: TaskOptions): Tool {
72
90
  const forward = () => child.abort(ctx.signal.reason);
73
91
  ctx.signal.addEventListener("abort", forward, { once: true });
74
92
  let failure: unknown;
75
- try {
76
- await child.send({
77
- kind: "message",
78
- content: [{ kind: "text", text: prompt, origin: { by: "runtime" }, trust: "trusted" }],
79
- });
93
+ const turn = async (text: string) => {
94
+ await child.send({ kind: "message", content: [{ kind: "text", text, origin: { by: "runtime" }, trust: "trusted" }] });
80
95
  while (child.state.phase === "awaiting") {
81
96
  for (const c of child.state.batch.filter((x) => x.decision === "ask")) {
82
97
  const answer = opts.approve ? await opts.approve(c, ctx.signal) : NOBODY;
83
98
  await child.send({ kind: "approval", toolUseId: c.toolUseId, approved: answer.approved, reason: answer.reason });
84
99
  }
85
100
  }
101
+ };
102
+ try {
103
+ await turn(prompt);
104
+ // 步数用完时最后一条回复通常只有工具调用:再要一次报告,否则前面的调研全白做了
105
+ if (!lastText(child.state.messages)) {
106
+ control.wrapUp = true;
107
+ await turn(WRAP_UP);
108
+ }
86
109
  } catch (err) {
87
110
  failure = err;
88
111
  } finally {
@@ -93,8 +116,8 @@ export function taskTool(opts: TaskOptions): Tool {
93
116
  if (ctx.signal.aborted) throw failure ?? ctx.signal.reason;
94
117
 
95
118
  const ref = { sessionId, seq: child.state.lastSeq };
96
- const last = child.state.messages.findLast((m) => m.role === "assistant");
97
- const text = (last?.content ?? []).flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim();
119
+ // 还是没有报告时,把它一路上说过的话都带回去
120
+ const text = clip(lastText(child.state.messages) || allText(child.state.messages));
98
121
  if (failure) {
99
122
  const msg = failure instanceof Error ? failure.message : String(failure);
100
123
  return { content: `Sub-agent failed: ${msg}${text ? `\nLast output:\n${text}` : ""}`, isError: true, child: ref };
@@ -103,3 +126,24 @@ export function taskTool(opts: TaskOptions): Tool {
103
126
  },
104
127
  };
105
128
  }
129
+
130
+ const textOf = (m: Message) => m.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim();
131
+
132
+ /** 最后一条回复的正文 */
133
+ function lastText(messages: Message[]): string {
134
+ const last = messages.findLast((m) => m.role === "assistant");
135
+ return last ? textOf(last) : "";
136
+ }
137
+
138
+ /** 所有回复的正文 */
139
+ function allText(messages: Message[]): string {
140
+ return messages
141
+ .filter((m) => m.role === "assistant")
142
+ .map(textOf)
143
+ .filter(Boolean)
144
+ .join("\n\n");
145
+ }
146
+
147
+ function clip(s: string): string {
148
+ return s.length > MAX_REPORT_CHARS ? `${s.slice(0, MAX_REPORT_CHARS)}\n… (report truncated: ${s.length - MAX_REPORT_CHARS} more characters)` : s;
149
+ }