@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.
- package/README.md +1 -0
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/package.json +2 -2
- package/plugins/approval/index.ts +14 -11
- package/plugins/approval/policy.ts +34 -16
- package/plugins/fs/grep.ts +13 -3
- package/plugins/fs/index.ts +5 -5
- package/plugins/fs/plugin.json +1 -1
- package/plugins/mcp/index.ts +5 -5
- package/plugins/mcp/plugin.json +1 -1
- package/plugins/models/index.ts +4 -3
- package/plugins/models/provider.ts +12 -1
- package/plugins/repeats/index.ts +31 -1
- package/plugins/screenshot/browser.ts +221 -0
- package/plugins/screenshot/index.ts +3 -2
- package/plugins/screenshot/tool.ts +27 -51
- package/plugins/shell/index.ts +64 -6
- package/plugins/shell/plugin.json +1 -1
- package/plugins/shell/shell.ts +90 -33
- package/plugins/task/index.ts +12 -42
- package/plugins/task/plugin.json +1 -2
- package/plugins/task/subagent.ts +2 -2
- package/plugins/tools/index.ts +50 -0
- package/plugins/tools/plugin.json +7 -0
- package/plugins/tui/frontend.ts +27 -3
- package/plugins/tui/mascot.ts +8 -7
- package/plugins/tui/tui.ts +23 -7
- package/plugins/web/index.ts +7 -7
- package/plugins/web/plugin.json +1 -1
- package/plugins-dist/approval/index.js +16 -12
- package/plugins-dist/approval/policy.js +30 -15
- package/plugins-dist/fs/grep.js +12 -3
- package/plugins-dist/fs/index.js +5 -5
- package/plugins-dist/fs/plugin.json +1 -1
- package/plugins-dist/mcp/index.js +5 -5
- package/plugins-dist/mcp/plugin.json +1 -1
- package/plugins-dist/models/index.js +4 -3
- package/plugins-dist/models/provider.js +13 -1
- package/plugins-dist/repeats/index.js +27 -1
- package/plugins-dist/screenshot/browser.js +187 -0
- package/plugins-dist/screenshot/index.js +3 -2
- package/plugins-dist/screenshot/tool.js +27 -49
- package/plugins-dist/shell/index.js +68 -5
- package/plugins-dist/shell/plugin.json +1 -1
- package/plugins-dist/shell/shell.js +82 -30
- package/plugins-dist/task/index.js +11 -42
- package/plugins-dist/task/plugin.json +1 -3
- package/plugins-dist/task/subagent.js +1 -1
- package/plugins-dist/tools/index.js +49 -0
- package/plugins-dist/tools/plugin.json +9 -0
- package/plugins-dist/tui/frontend.js +28 -3
- package/plugins-dist/tui/mascot.js +8 -6
- package/plugins-dist/tui/tui.js +18 -7
- package/plugins-dist/tui/vendor.js +1388 -1088
- package/plugins-dist/web/index.js +6 -6
- package/plugins-dist/web/plugin.json +1 -1
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/src/api.ts +1 -1
|
@@ -202,8 +202,11 @@ export default definePlugin({
|
|
|
202
202
|
}
|
|
203
203
|
if (!canAsk())
|
|
204
204
|
return { approved: false, answer: "deny", by: "nobody", reason: nobody(call.name) };
|
|
205
|
-
const
|
|
206
|
-
const
|
|
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;
|
|
@@ -217,8 +220,8 @@ export default definePlugin({
|
|
|
217
220
|
// 别的插件要问的调用不能"总是允许":这里的规则管不到它的关卡
|
|
218
221
|
...(asked.mine
|
|
219
222
|
? [
|
|
220
|
-
{ label:
|
|
221
|
-
{ label:
|
|
223
|
+
{ label: "Always allow in this session", value: "always" },
|
|
224
|
+
{ label: "Always allow in this directory, in every session", value: "forever" },
|
|
222
225
|
]
|
|
223
226
|
: []),
|
|
224
227
|
{ label: "Deny", value: "deny" },
|
|
@@ -232,14 +235,14 @@ export default definePlugin({
|
|
|
232
235
|
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.` };
|
|
233
236
|
}
|
|
234
237
|
if (got?.answer === "always" && asked.mine) {
|
|
235
|
-
added.push(
|
|
238
|
+
added.push(...allow);
|
|
236
239
|
return { approved: true, answer: "always", by: got.by };
|
|
237
240
|
}
|
|
238
241
|
if (got?.answer === "forever" && asked.mine) {
|
|
239
|
-
forever.push(
|
|
242
|
+
forever.push(...allow);
|
|
240
243
|
try {
|
|
241
|
-
await addForever(foreverFile, ctx.cwd,
|
|
242
|
-
ui?.notify(`${
|
|
244
|
+
await addForever(foreverFile, ctx.cwd, allow);
|
|
245
|
+
ui?.notify(`${described} is now always allowed in ${ctx.cwd}. To ask again, remove it from ${foreverFile}`, "info");
|
|
243
246
|
}
|
|
244
247
|
catch (e) {
|
|
245
248
|
ui?.notify(`could not save the rule to ${foreverFile} (${e instanceof Error ? e.message : String(e)}); it only applies to this session`, "warning");
|
|
@@ -358,7 +361,7 @@ async function ask(ui, request, signal) {
|
|
|
358
361
|
const channels = [];
|
|
359
362
|
if (ui?.interactive) {
|
|
360
363
|
// 终端里多一项:拒绝并说明。选了它再问一句话,取消或什么都没写就是普通的拒绝
|
|
361
|
-
const options = [...request.options, { label: "Deny, and
|
|
364
|
+
const options = [...request.options, { label: "Deny, and say what to do instead", value: EXPLAIN }];
|
|
362
365
|
channels.push(ui.select({ ...request, options }, done.signal).then(async (a) => {
|
|
363
366
|
if (a !== EXPLAIN)
|
|
364
367
|
return { answer: a !== undefined && ANSWERS.includes(a) ? a : "deny", by: "terminal" };
|
|
@@ -407,11 +410,12 @@ async function readForever(file) {
|
|
|
407
410
|
return {};
|
|
408
411
|
}
|
|
409
412
|
}
|
|
410
|
-
async function addForever(file, cwd,
|
|
413
|
+
async function addForever(file, cwd, add) {
|
|
411
414
|
const all = await readForever(file);
|
|
412
415
|
const rules = all[cwd] ?? [];
|
|
413
|
-
|
|
414
|
-
rules.
|
|
416
|
+
for (const rule of add)
|
|
417
|
+
if (!rules.some((r) => JSON.stringify(r) === JSON.stringify(rule)))
|
|
418
|
+
rules.push(rule);
|
|
415
419
|
all[cwd] = rules;
|
|
416
420
|
await mkdir(path.dirname(file), { recursive: true });
|
|
417
421
|
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
|
import { realpathSync, statSync } from "node:fs";
|
|
6
7
|
import path from "node:path";
|
|
7
8
|
import { validate } from "./schema.js";
|
|
@@ -329,21 +330,33 @@ function prefixCovers(words, prefix) {
|
|
|
329
330
|
}
|
|
330
331
|
/**
|
|
331
332
|
* bash 的"总是允许"默认规则:一般取前两个词("cargo build"、"git commit"),
|
|
332
|
-
* 运行脚本的命令取三个词("npm run build")。第二个词就是选项("rm -rf x"
|
|
333
|
-
*
|
|
333
|
+
* 运行脚本的命令取三个词("npm run build")。第二个词就是选项("rm -rf x")、只有一个词时,只允许这一条命令本身。
|
|
334
|
+
* 复合命令("git add -A && git commit -m …"、"bun test 2>&1 | tail -20")里每条不是只读的命令各记一条:
|
|
335
|
+
* 关卡对复合命令逐条判断,所以下次换了提交信息、换了组合也不用再问。
|
|
336
|
+
* 分不了词、有输出重定向、或者不是只读的命令带输入重定向时,只允许整条命令原文
|
|
334
337
|
*/
|
|
335
|
-
export function
|
|
336
|
-
const exact = { tool: "bash", command: command.trim() };
|
|
337
|
-
// 复合命令里只有一条不是只读命令("bun test 2>&1 | tail -20")时,规则取它;关卡对复合命令逐条判断
|
|
338
|
+
export function bashRules(command) {
|
|
339
|
+
const exact = [{ tool: "bash", command: command.trim() }];
|
|
338
340
|
const cmds = shellCommands(command);
|
|
339
341
|
const unsafe = cmds?.filter((c) => c.words[0].value !== "cd" && commandKind(c.words.map((w) => w.value)) !== "read");
|
|
340
|
-
if (!cmds || !unsafe || unsafe.length
|
|
342
|
+
if (!cmds || !unsafe || unsafe.length === 0 || !cmds.every(quietOutputs) || unsafe.some((c) => c.inputs.length > 0))
|
|
341
343
|
return exact;
|
|
342
|
-
|
|
343
|
-
if (
|
|
344
|
+
// 只有一条命令、又只能按原文记时,记整条原文(和关卡比较的是同一个字符串)
|
|
345
|
+
if (cmds.length === 1 && !prefixOf(unsafe[0].words))
|
|
344
346
|
return exact;
|
|
347
|
+
const rules = unsafe.map((c) => {
|
|
348
|
+
const prefix = prefixOf(c.words);
|
|
349
|
+
return prefix ? { tool: "bash", prefix } : { tool: "bash", command: joined(c.words) };
|
|
350
|
+
});
|
|
351
|
+
return rules.filter((r, i) => rules.findIndex((o) => o.prefix === r.prefix && o.command === r.command) === i);
|
|
352
|
+
}
|
|
353
|
+
/** 一条简单命令的前缀规则;只能按原文记时返回 undefined */
|
|
354
|
+
function prefixOf(all) {
|
|
355
|
+
const words = all.map((w) => w.value);
|
|
356
|
+
if (words.length < 2 || words[1].startsWith("-") || words.some((w) => DANGEROUS_ARGS.test(w)))
|
|
357
|
+
return undefined;
|
|
345
358
|
const n = RUNNERS.test(words.slice(0, 2).join(" ")) && words.length >= 3 && !words[2].startsWith("-") ? 3 : 2;
|
|
346
|
-
return
|
|
359
|
+
return words.slice(0, n).join(" ");
|
|
347
360
|
}
|
|
348
361
|
const hostOf = (url) => {
|
|
349
362
|
try {
|
|
@@ -353,6 +366,8 @@ const hostOf = (url) => {
|
|
|
353
366
|
return undefined;
|
|
354
367
|
}
|
|
355
368
|
};
|
|
369
|
+
/** 本机的地址:localhost、127.x.x.x、::1(URL 会把 127.1 这类写法规范成 127.0.0.1) */
|
|
370
|
+
const isLoopback = (host) => host !== undefined && (host === "localhost" || host.endsWith(".localhost") || /^127(\.\d{1,3}){3}$/.test(host) || host === "[::1]");
|
|
356
371
|
/**
|
|
357
372
|
* Windows 上 bash 工具跑的是 Git Bash,模型常把路径写成 /c/Users/...(MSYS 的写法)。
|
|
358
373
|
* path.resolve 会把它当成当前盘符下的 \c\Users\...,判断成工作目录之外,只读命令也要确认。
|
|
@@ -465,14 +480,14 @@ export function policy(opts) {
|
|
|
465
480
|
return input;
|
|
466
481
|
return { ...input, path: path.resolve(opts.cwd, input.path) };
|
|
467
482
|
},
|
|
468
|
-
|
|
483
|
+
rulesFor(call) {
|
|
469
484
|
if (call.name === "bash")
|
|
470
|
-
return
|
|
485
|
+
return bashRules(String(call.input.command ?? ""));
|
|
471
486
|
const input = call.input;
|
|
472
487
|
if (typeof input?.url === "string") {
|
|
473
488
|
const host = hostOf(input.url);
|
|
474
489
|
if (host)
|
|
475
|
-
return { tool: call.name, host };
|
|
490
|
+
return [{ tool: call.name, host }];
|
|
476
491
|
}
|
|
477
492
|
if (typeof input?.path === "string" && !inside(input.path)) {
|
|
478
493
|
const full = path.resolve(opts.cwd, input.path);
|
|
@@ -483,9 +498,9 @@ export function policy(opts) {
|
|
|
483
498
|
catch {
|
|
484
499
|
// 还不存在的文件
|
|
485
500
|
}
|
|
486
|
-
return { tool: call.name, dir: isDir ? full : path.dirname(full) };
|
|
501
|
+
return [{ tool: call.name, dir: isDir ? full : path.dirname(full) }];
|
|
487
502
|
}
|
|
488
|
-
return { tool: call.name };
|
|
503
|
+
return [{ tool: call.name }];
|
|
489
504
|
},
|
|
490
505
|
decide(call, { mode, rules }) {
|
|
491
506
|
const { tool } = call;
|
|
@@ -496,7 +511,7 @@ export function policy(opts) {
|
|
|
496
511
|
const outside = (typeof input.path === "string" && !inside(input.path)) ||
|
|
497
512
|
(call.name === "glob" && typeof input.pattern === "string" && globEscapes(input.pattern));
|
|
498
513
|
/** 会把参数发到网络上的只读工具 */
|
|
499
|
-
const network = typeof input.url === "string";
|
|
514
|
+
const network = typeof input.url === "string" && !isLoopback(hostOf(input.url));
|
|
500
515
|
const covers = (r) => {
|
|
501
516
|
if (r.tool !== call.name)
|
|
502
517
|
return false;
|
package/plugins-dist/fs/grep.js
CHANGED
|
@@ -21,7 +21,8 @@ export function grepTool(cwd, opts = {}) {
|
|
|
21
21
|
`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. ` +
|
|
22
22
|
`output_mode: "content" (default) returns "file:line:text" for matches and "file-line-text" for context lines, at most ${MAX_MATCHES} matches; ` +
|
|
23
23
|
`"files" returns only the paths of matching files; "count" returns "file:count". ` +
|
|
24
|
-
`context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode
|
|
24
|
+
`context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode. ` +
|
|
25
|
+
"head_limit keeps only the first that many lines of the output.",
|
|
25
26
|
inputSchema: {
|
|
26
27
|
type: "object",
|
|
27
28
|
properties: {
|
|
@@ -32,6 +33,10 @@ export function grepTool(cwd, opts = {}) {
|
|
|
32
33
|
// files_with_matches 是 ripgrep / Claude Code 的叫法,很多模型会这样传,当作 files
|
|
33
34
|
output_mode: { type: "string", enum: ["content", "files", "count", "files_with_matches"] },
|
|
34
35
|
context: { type: "integer" },
|
|
36
|
+
// head_limit、glob 也是 ripgrep / Claude Code 的叫法;不接受的话模型要多花一轮去掉它们重发。
|
|
37
|
+
// 有的模型把数字写成字符串("30"),也接受
|
|
38
|
+
head_limit: { type: ["integer", "string"] },
|
|
39
|
+
glob: { type: "string" },
|
|
35
40
|
},
|
|
36
41
|
required: ["pattern"],
|
|
37
42
|
additionalProperties: false,
|
|
@@ -40,7 +45,7 @@ export function grepTool(cwd, opts = {}) {
|
|
|
40
45
|
concurrency: "safe",
|
|
41
46
|
idempotent: true,
|
|
42
47
|
async execute(input, { signal }) {
|
|
43
|
-
const { pattern, path: p = ".", include, ignore_case = false, output_mode = "content", context = 0 } = input;
|
|
48
|
+
const { pattern, path: p = ".", glob, include = glob, ignore_case = false, output_mode = "content", context = 0, head_limit } = input;
|
|
44
49
|
const mode = output_mode === "files_with_matches" ? "files" : output_mode;
|
|
45
50
|
let re;
|
|
46
51
|
try {
|
|
@@ -68,7 +73,11 @@ export function grepTool(cwd, opts = {}) {
|
|
|
68
73
|
found = result;
|
|
69
74
|
}
|
|
70
75
|
found ??= await jsGrep(search);
|
|
71
|
-
|
|
76
|
+
const lines = format(cwd, found, search).split("\n");
|
|
77
|
+
const limit = Number(head_limit);
|
|
78
|
+
if (limit > 0 && lines.length > limit)
|
|
79
|
+
lines.splice(limit, Infinity, `(showing the first ${limit} of ${lines.length} lines)`);
|
|
80
|
+
return { content: lines.join("\n") };
|
|
72
81
|
},
|
|
73
82
|
};
|
|
74
83
|
}
|
package/plugins-dist/fs/index.js
CHANGED
|
@@ -25,14 +25,14 @@ export default definePlugin({
|
|
|
25
25
|
});
|
|
26
26
|
for (const tool of fsTools(ctx.cwd, { responses, seen }))
|
|
27
27
|
ctx.kernel.tool(tool);
|
|
28
|
-
//
|
|
29
|
-
// jade/
|
|
28
|
+
// 嵌套 Agent(例如 jade/task 的子 Agent)的只读工具:另一套实例,它读过的文件不算主会话读过
|
|
29
|
+
// jade/tools 被隔离时它的服务已失效:嵌套 Agent 没有文件工具,文件工具本身照常
|
|
30
30
|
try {
|
|
31
|
-
const
|
|
32
|
-
if (
|
|
31
|
+
const shared = ctx.service("tools@1");
|
|
32
|
+
if (shared)
|
|
33
33
|
for (const tool of fsTools(ctx.cwd))
|
|
34
34
|
if (tool.effect === "read")
|
|
35
|
-
|
|
35
|
+
shared.register(tool);
|
|
36
36
|
}
|
|
37
37
|
catch { }
|
|
38
38
|
},
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// jade/mcp:配置的 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
|
// 服务是进程级的资源:第一个会话打开时读配置、确认项目层的服务、连接,之后各会话共用;进程退出时(进程作用域关闭)全部关掉。
|
|
@@ -207,11 +207,11 @@ export default definePlugin({
|
|
|
207
207
|
await servers.start();
|
|
208
208
|
for (const tool of mcpTools(servers.clients))
|
|
209
209
|
ctx.kernel.tool(tool);
|
|
210
|
-
//
|
|
211
|
-
const
|
|
212
|
-
if (
|
|
210
|
+
// 嵌套 Agent(例如 jade/task 的子 Agent)只拿声明了只读(readOnlyHint)的工具:另一套实例,和 jade/fs 一样
|
|
211
|
+
const shared = ctx.service("tools@1");
|
|
212
|
+
if (shared)
|
|
213
213
|
for (const tool of mcpTools(servers.clients, { readOnly: true }))
|
|
214
|
-
|
|
214
|
+
shared.register(tool);
|
|
215
215
|
const prompts = ctx.service("prompts@1");
|
|
216
216
|
for (const text of instructions(servers.clients))
|
|
217
217
|
prompts?.add({ text, untrusted: true });
|
|
@@ -16,7 +16,8 @@ export default definePlugin({
|
|
|
16
16
|
const modelsFile = path.join(ctx.home, "models.json");
|
|
17
17
|
// 当前的模型配置。改配置时整份换掉(updateEnvFile 改的是这一份,apply 再从文件读一遍)
|
|
18
18
|
let env = await envWithFile(envFile);
|
|
19
|
-
|
|
19
|
+
// 用的时候再取:jade/tui 也依赖这个插件(models@1),它在这之后才激活,这里取到的是 undefined,重试的提示就没人显示
|
|
20
|
+
const ui = () => ctx.service("ui@1");
|
|
20
21
|
const watchers = new Set();
|
|
21
22
|
const notify = () => {
|
|
22
23
|
for (const fn of watchers) {
|
|
@@ -36,10 +37,10 @@ export default definePlugin({
|
|
|
36
37
|
// 用创建时的这份配置:之后换了配置,新的一份自己建 provider
|
|
37
38
|
const build = (snapshot) => {
|
|
38
39
|
return (async () => {
|
|
39
|
-
const gate = new RateGate({ rpm: rpmFromEnv(snapshot), onLearn: (rpm) => ui?.notify(`rate limited: spacing requests to ${rpm} per minute from now on`, "warning") });
|
|
40
|
+
const gate = new RateGate({ rpm: rpmFromEnv(snapshot), onLearn: (rpm) => ui()?.notify(`rate limited: spacing requests to ${rpm} per minute from now on`, "warning") });
|
|
40
41
|
return withRetry(await providerFromEnv(snapshot), {
|
|
41
42
|
gate,
|
|
42
|
-
onRetry: ({ attempt, retries, delayMs, error }) => ui?.notify(`model request failed (${error.message}); retry ${attempt} of ${retries} in ${Math.round(delayMs / 1000)}s`, "warning"),
|
|
43
|
+
onRetry: ({ attempt, retries, delayMs, error }) => ui()?.notify(`model request failed (${error.message}); retry ${attempt} of ${retries} in ${Math.round(delayMs / 1000)}s`, "warning"),
|
|
43
44
|
});
|
|
44
45
|
})();
|
|
45
46
|
};
|
|
@@ -36,8 +36,20 @@ export function withRetry(inner, opts = {}) {
|
|
|
36
36
|
return { ...res, provider: res.provider ?? inner.id, ...(failures.length > 0 ? { retries: failures } : {}) };
|
|
37
37
|
}
|
|
38
38
|
catch (err) {
|
|
39
|
-
if (!(err instanceof ProviderError) ||
|
|
39
|
+
if (!(err instanceof ProviderError) || options.signal.aborted)
|
|
40
40
|
throw err;
|
|
41
|
+
if (!err.retryable || attempt > retries) {
|
|
42
|
+
if (failures.length === 0)
|
|
43
|
+
throw err;
|
|
44
|
+
// 失败时没有回复可以带上重试记录:写进错误信息里,会话日志(turn.ended)和界面上都看得到重试过、等了多久
|
|
45
|
+
const waited = Math.round(failures.reduce((ms, f) => ms + f.delayMs, 0) / 1000);
|
|
46
|
+
throw new ProviderError(`${err.message} (after ${failures.length} ${failures.length === 1 ? "retry" : "retries"}, ${waited}s of waiting)`, {
|
|
47
|
+
retryable: err.retryable,
|
|
48
|
+
status: err.status,
|
|
49
|
+
retryAfterMs: err.retryAfterMs,
|
|
50
|
+
cause: err,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
41
53
|
// 在计划的时间上随机缩短最多 20%,并行的子 Agent 同时遇到 429 时不会同时重试。
|
|
42
54
|
// 上游给的 retryAfterMs 只当下限:有的服务(尤其是并发数限流)每次都回 Retry-After: 1,
|
|
43
55
|
// 拿它代替退避计划会每秒撞一次,十几秒就把重试次数用完
|
|
@@ -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 移植。
|
|
@@ -38,6 +39,14 @@ function normalize(cwd, p) {
|
|
|
38
39
|
}
|
|
39
40
|
/** 提醒模型的失败次数 */
|
|
40
41
|
const WARN_AFTER = 2;
|
|
42
|
+
/** 同一处文字来回改到第几次时提醒:改过去、改回来各算一次,改回来一次是正常的撤销 */
|
|
43
|
+
const FLIP_AFTER = 3;
|
|
44
|
+
/** edit_file、multi_edit 里的每一处替换 */
|
|
45
|
+
function replacements(call) {
|
|
46
|
+
const input = call.input;
|
|
47
|
+
const list = call.name === "edit_file" ? [input] : call.name === "multi_edit" && Array.isArray(input?.edits) ? input.edits : [];
|
|
48
|
+
return list.filter((e) => typeof e?.old_string === "string" && typeof e?.new_string === "string");
|
|
49
|
+
}
|
|
41
50
|
const hash = (content) => createHash("sha1").update(JSON.stringify(content.map((b) => (b.kind === "text" ? b.text : b)))).digest("hex");
|
|
42
51
|
/** 会话里的 hook:model.before 数回复次数,tool.gate 拒绝重复,tool.after 加提醒,event 在用户发消息、压缩后重新计 */
|
|
43
52
|
export function repeatsHooks(opts) {
|
|
@@ -61,6 +70,8 @@ export function repeatsHooks(opts) {
|
|
|
61
70
|
const opened = new Map();
|
|
62
71
|
/** 本轮用 write_file 写过的文件 → 写完时的 changes;用户发消息时清空 */
|
|
63
72
|
const written = new Map();
|
|
73
|
+
/** 文件里互相替换的一对文字 → 本轮里换了几次(不分方向);用户发消息时清空 */
|
|
74
|
+
const flips = new Map();
|
|
64
75
|
const key = (call) => `${call.name}\0${JSON.stringify(call.input)}`;
|
|
65
76
|
const note = (text) => ({ kind: "text", text: `[Note from jade] ${text}`, origin: { by: "plugin", id }, trust: "trusted" });
|
|
66
77
|
return [
|
|
@@ -117,6 +128,20 @@ export function repeatsHooks(opts) {
|
|
|
117
128
|
const readBack = outcome.call.name === "read_file" && typeof file === "string" && written.get(normalize(cwd, file)) === changes
|
|
118
129
|
? 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.")
|
|
119
130
|
: undefined;
|
|
131
|
+
let most = 0;
|
|
132
|
+
if (typeof file === "string") {
|
|
133
|
+
for (const e of replacements(outcome.call)) {
|
|
134
|
+
const pair = `${normalize(cwd, file)}${[e.old_string, e.new_string].sort().join("")}`;
|
|
135
|
+
const n = (flips.get(pair) ?? 0) + 1;
|
|
136
|
+
flips.set(pair, n);
|
|
137
|
+
most = Math.max(most, n);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const flipped = most >= FLIP_AFTER
|
|
141
|
+
? note(`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. ` +
|
|
142
|
+
"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.")
|
|
143
|
+
: undefined;
|
|
144
|
+
const extra = [readBack, flipped].filter((b) => b !== undefined);
|
|
120
145
|
const before = succeeded.get(k);
|
|
121
146
|
// 只读之外的调用(包括这一个)可能改了东西,之后的调用都不算"什么都没变"
|
|
122
147
|
if (!read)
|
|
@@ -125,7 +150,7 @@ export function repeatsHooks(opts) {
|
|
|
125
150
|
const repeated = before !== undefined && before.version === (read ? version : version - 1) && before.result === result;
|
|
126
151
|
succeeded.set(k, { version, result });
|
|
127
152
|
if (!repeated)
|
|
128
|
-
return
|
|
153
|
+
return extra.length > 0 ? { ...outcome, content: [...outcome.content, ...extra] } : undefined;
|
|
129
154
|
const text = "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). " +
|
|
130
155
|
"Do not repeat it: use what you already have, or end your turn and tell the user where things stand.";
|
|
131
156
|
return { ...outcome, content: [...outcome.content, note(text)] };
|
|
@@ -152,6 +177,7 @@ export function repeatsHooks(opts) {
|
|
|
152
177
|
version++;
|
|
153
178
|
opened.clear();
|
|
154
179
|
written.clear();
|
|
180
|
+
flips.clear();
|
|
155
181
|
}
|
|
156
182
|
},
|
|
157
183
|
},
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// 用 DevTools 协议(CDP)让无头浏览器截一张图。
|
|
2
|
+
//
|
|
3
|
+
// 不用命令行的 --window-size + --screenshot:Windows 上浏览器窗口最窄 500px,要 390 宽时页面仍按 500 排版,
|
|
4
|
+
// 只截到左边 390px,看起来像内容被裁掉;也不能滚动到页面中间的某一段,页面一直不"加载完"时只有一句超时。
|
|
5
|
+
// 这里用 Emulation.setDeviceMetricsOverride 设视口(多窄都按给的宽度排版),可以先滚动到某个元素再截,
|
|
6
|
+
// 页面迟迟不触发 load 时照样截下当时的样子并说明。
|
|
7
|
+
//
|
|
8
|
+
// 连接用 --remote-debugging-port=0 加 WebSocket(Bun 和 Node ≥22 都有全局的 WebSocket);
|
|
9
|
+
// --remote-debugging-pipe 在 Bun 下收不到数据。端口只监听本机,用完就连同临时用户目录一起关掉。
|
|
10
|
+
import { readFile } from "node:fs/promises";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { spawn } from "./sys.js";
|
|
13
|
+
/** 浏览器启动到能连接的最长时间 */
|
|
14
|
+
const READY_MS = 10_000;
|
|
15
|
+
/** 等页面 load 事件的最长时间;到时间还没有就按当时的样子截 */
|
|
16
|
+
const LOAD_MS = 15_000;
|
|
17
|
+
/** load 之后等网络安静下来(脚本、图片、字体)的最长时间 */
|
|
18
|
+
const SETTLE_MS = 3000;
|
|
19
|
+
/** 滚动之后给懒加载的图片、滚动触发的动画的时间 */
|
|
20
|
+
const SCROLL_SETTLE_MS = 400;
|
|
21
|
+
/** 截图失败、原因可以直接告诉模型的错误 */
|
|
22
|
+
export class CaptureError extends Error {
|
|
23
|
+
}
|
|
24
|
+
function connect(url) {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const ws = new WebSocket(url);
|
|
27
|
+
let next = 0;
|
|
28
|
+
let closed = false;
|
|
29
|
+
const waiting = new Map();
|
|
30
|
+
const events = new Set();
|
|
31
|
+
const listeners = new Set();
|
|
32
|
+
ws.onerror = () => reject(new CaptureError("could not connect to the browser"));
|
|
33
|
+
ws.onclose = () => {
|
|
34
|
+
closed = true;
|
|
35
|
+
for (const w of waiting.values())
|
|
36
|
+
w.reject(new CaptureError("the browser closed before the screenshot was taken"));
|
|
37
|
+
waiting.clear();
|
|
38
|
+
};
|
|
39
|
+
ws.onmessage = (e) => {
|
|
40
|
+
const m = JSON.parse(String(e.data));
|
|
41
|
+
if (m.id !== undefined) {
|
|
42
|
+
const w = waiting.get(m.id);
|
|
43
|
+
waiting.delete(m.id);
|
|
44
|
+
if (m.error)
|
|
45
|
+
w?.reject(new CaptureError(m.error.message));
|
|
46
|
+
else
|
|
47
|
+
w?.resolve(m.result);
|
|
48
|
+
}
|
|
49
|
+
else if (m.method) {
|
|
50
|
+
// Page.lifecycleEvent 的名字在参数里:load、networkIdle……
|
|
51
|
+
const name = m.method === "Page.lifecycleEvent" ? `lifecycle:${m.params?.name}` : m.method;
|
|
52
|
+
events.add(name);
|
|
53
|
+
for (const l of listeners)
|
|
54
|
+
l(name);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
ws.onopen = () => resolve({
|
|
58
|
+
send: (method, params = {}, sessionId) => new Promise((res, rej) => {
|
|
59
|
+
if (closed)
|
|
60
|
+
return rej(new CaptureError("the browser closed before the screenshot was taken"));
|
|
61
|
+
const id = ++next;
|
|
62
|
+
waiting.set(id, { resolve: res, reject: rej });
|
|
63
|
+
ws.send(JSON.stringify({ id, method, params, sessionId }));
|
|
64
|
+
}),
|
|
65
|
+
seen: (method, ms) => new Promise((res) => {
|
|
66
|
+
if (events.has(method))
|
|
67
|
+
return res(true);
|
|
68
|
+
const done = (ok) => {
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
listeners.delete(l);
|
|
71
|
+
res(ok);
|
|
72
|
+
};
|
|
73
|
+
const l = (name) => name === method && done(true);
|
|
74
|
+
const timer = setTimeout(() => done(false), ms);
|
|
75
|
+
listeners.add(l);
|
|
76
|
+
}),
|
|
77
|
+
close: () => ws.close(),
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/** 浏览器把调试端口和连接路径写在用户目录的 DevToolsActivePort 里;等它出现 */
|
|
82
|
+
async function debuggerUrl(profile, proc, signal) {
|
|
83
|
+
let exited = false;
|
|
84
|
+
void proc.exited.then(() => (exited = true));
|
|
85
|
+
const deadline = Date.now() + READY_MS;
|
|
86
|
+
for (;;) {
|
|
87
|
+
signal.throwIfAborted();
|
|
88
|
+
try {
|
|
89
|
+
const [port, wsPath] = (await readFile(path.join(profile, "DevToolsActivePort"), "utf8")).trim().split("\n");
|
|
90
|
+
if (port && wsPath)
|
|
91
|
+
return `ws://127.0.0.1:${port}${wsPath}`;
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// 还没写出来
|
|
95
|
+
}
|
|
96
|
+
if (exited)
|
|
97
|
+
throw new CaptureError("the browser exited before it was ready");
|
|
98
|
+
if (Date.now() > deadline)
|
|
99
|
+
throw new CaptureError(`the browser was not ready within ${READY_MS / 1000}s`);
|
|
100
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* 在页面里执行:滚动到 CSS 选择器匹配的第一个元素;选择器无效或没有匹配时,找第一个包含这段文字的元素。
|
|
105
|
+
* 比视口高的元素对齐到顶部,其余的放在中间
|
|
106
|
+
*/
|
|
107
|
+
const SCROLL = (what) => `(() => {
|
|
108
|
+
const what = ${JSON.stringify(what)};
|
|
109
|
+
let el = null;
|
|
110
|
+
try { el = document.querySelector(what); } catch {}
|
|
111
|
+
if (!el) {
|
|
112
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
|
113
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
114
|
+
if (n.nodeValue.includes(what) && n.parentElement && n.parentElement.getClientRects().length) { el = n.parentElement; break; }
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (!el) return null;
|
|
118
|
+
el.scrollIntoView({ block: el.getBoundingClientRect().height > innerHeight ? "start" : "center", behavior: "instant" });
|
|
119
|
+
const text = (el.textContent || "").trim().replace(/\\s+/g, " ");
|
|
120
|
+
return "<" + el.tagName.toLowerCase() + ">" + (text ? ' "' + (text.length > 40 ? text.slice(0, 40) + "…" : text) + '"' : "");
|
|
121
|
+
})()`;
|
|
122
|
+
const METRICS = "JSON.stringify({ h: Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0), y: Math.round(scrollY) })";
|
|
123
|
+
export const capture = async (browser, req, signal) => {
|
|
124
|
+
const proc = await spawn([
|
|
125
|
+
browser,
|
|
126
|
+
"--headless=new",
|
|
127
|
+
"--disable-gpu",
|
|
128
|
+
"--hide-scrollbars",
|
|
129
|
+
"--no-first-run",
|
|
130
|
+
"--no-default-browser-check",
|
|
131
|
+
"--disable-extensions",
|
|
132
|
+
"--mute-audio",
|
|
133
|
+
"--remote-debugging-port=0",
|
|
134
|
+
`--user-data-dir=${req.profile}`,
|
|
135
|
+
"about:blank",
|
|
136
|
+
], { stdout: "ignore", stderr: "ignore" });
|
|
137
|
+
// 中止(用户打断、总的超时)时不等页面:下面的等待都按自己的时间走,这里直接结束
|
|
138
|
+
let abort;
|
|
139
|
+
const aborted = new Promise((_, reject) => (abort = () => reject(signal.reason)));
|
|
140
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
141
|
+
let cdp;
|
|
142
|
+
const work = async () => {
|
|
143
|
+
cdp = await connect(await debuggerUrl(req.profile, proc, signal));
|
|
144
|
+
const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });
|
|
145
|
+
const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });
|
|
146
|
+
const page = (method, params) => cdp.send(method, params, sessionId);
|
|
147
|
+
const evaluate = async (expression) => (await page("Runtime.evaluate", { expression, returnByValue: true })).result.value;
|
|
148
|
+
await page("Emulation.setDeviceMetricsOverride", { width: req.width, height: req.height, deviceScaleFactor: 1, mobile: false });
|
|
149
|
+
await page("Page.enable");
|
|
150
|
+
await page("Page.setLifecycleEventsEnabled", { enabled: true });
|
|
151
|
+
const { errorText } = await page("Page.navigate", { url: req.target });
|
|
152
|
+
if (errorText)
|
|
153
|
+
throw new CaptureError(`the page could not be loaded: ${errorText}`);
|
|
154
|
+
const loaded = await cdp.seen("Page.loadEventFired", LOAD_MS);
|
|
155
|
+
if (loaded)
|
|
156
|
+
await cdp.seen("lifecycle:networkIdle", SETTLE_MS);
|
|
157
|
+
signal.throwIfAborted();
|
|
158
|
+
let scrolledTo;
|
|
159
|
+
if (req.scrollTo !== undefined) {
|
|
160
|
+
const found = await evaluate(SCROLL(req.scrollTo));
|
|
161
|
+
if (found === null) {
|
|
162
|
+
throw new CaptureError(`nothing on the page matches scroll_to ${JSON.stringify(req.scrollTo)} (tried as a CSS selector, then as text)` +
|
|
163
|
+
(loaded ? "" : `; the page had not finished loading after ${LOAD_MS / 1000}s`));
|
|
164
|
+
}
|
|
165
|
+
scrolledTo = found;
|
|
166
|
+
await new Promise((r) => setTimeout(r, SCROLL_SETTLE_MS));
|
|
167
|
+
}
|
|
168
|
+
const { h, y } = JSON.parse(await evaluate(METRICS));
|
|
169
|
+
const { data } = await page("Page.captureScreenshot", { format: "png" });
|
|
170
|
+
return {
|
|
171
|
+
png: Buffer.from(data, "base64"),
|
|
172
|
+
pageHeight: h,
|
|
173
|
+
scrollY: y,
|
|
174
|
+
scrolledTo,
|
|
175
|
+
note: loaded ? undefined : `The page had not finished loading after ${LOAD_MS / 1000}s; this is how it looked at that point.`,
|
|
176
|
+
};
|
|
177
|
+
};
|
|
178
|
+
try {
|
|
179
|
+
return await Promise.race([work(), aborted]);
|
|
180
|
+
}
|
|
181
|
+
finally {
|
|
182
|
+
signal.removeEventListener("abort", abort);
|
|
183
|
+
cdp?.close();
|
|
184
|
+
proc.kill();
|
|
185
|
+
await proc.exited;
|
|
186
|
+
}
|
|
187
|
+
};
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// jade/screenshot:截图工具(见 tool.ts)。本机没有能无头截图的浏览器时不注册这个工具。
|
|
2
2
|
// 模型能不能看图片由 jade/models 的 models@1 给出(JADE_VISION):不能看时请求里没有这个工具和提示,调用了也不截图。
|
|
3
|
-
// 访问网络的 URL 由 jade/approval 的关卡决定要不要问用户(effect 是 read
|
|
3
|
+
// 访问网络的 URL 由 jade/approval 的关卡决定要不要问用户(effect 是 read,本机之外的 URL 会问)。
|
|
4
4
|
import { definePlugin } from "@uncarved/jade-api";
|
|
5
5
|
import { findBrowser, screenshotTool } from "./tool.js";
|
|
6
6
|
/** 提示词里的一段:有截图工具时才加 */
|
|
7
|
-
const NOTE = "- When the work is visual (a page, a drawing, styles), take a screenshot of the result and look at it instead of guessing from the source."
|
|
7
|
+
const NOTE = "- When the work is visual (a page, a drawing, styles), take a screenshot of the result and look at it instead of guessing from the source. " +
|
|
8
|
+
"If screenshots keep failing, or keep showing something you cannot explain after a couple of attempts, stop changing code to chase it: tell the user what you see and let them look.";
|
|
8
9
|
export default definePlugin({
|
|
9
10
|
process(ctx) {
|
|
10
11
|
const renderers = ctx.service("renderers@1");
|