@uncarved/jade 0.3.0 → 0.4.0
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/dist/host.d.ts +2 -0
- package/dist/host.js +39 -5
- package/dist/host.js.map +1 -1
- package/dist/remote.js +5 -0
- package/dist/remote.js.map +1 -1
- package/dist/session.d.ts +7 -0
- package/dist/session.js +482 -27
- package/dist/session.js.map +1 -1
- package/package.json +4 -4
- package/plugins/approval/index.ts +49 -24
- package/plugins/approval/policy.ts +48 -25
- package/plugins/approval/review.ts +9 -5
- package/plugins/checks/checks.ts +10 -7
- package/plugins/checks/index.ts +13 -13
- package/plugins/checks/plugin.json +1 -1
- package/plugins/checks/project.ts +37 -38
- package/plugins/commands/index.ts +27 -3
- package/plugins/compact/compact.ts +13 -5
- package/plugins/compact/index.ts +20 -3
- package/plugins/compact/style.ts +13 -14
- package/plugins/completions/index.ts +35 -0
- package/plugins/completions/plugin.json +7 -0
- package/plugins/copy/index.ts +46 -0
- package/plugins/copy/plugin.json +7 -0
- package/plugins/editor/index.ts +10 -4
- package/plugins/fs/diff.ts +7 -6
- package/plugins/fs/fs.ts +8 -4
- package/plugins/fs/grep.ts +55 -12
- package/plugins/fs/index.ts +2 -7
- package/plugins/fs/plugin.json +1 -1
- package/plugins/fs/renderers.ts +16 -15
- package/plugins/fs/style.ts +16 -15
- package/plugins/hooks/index.ts +3 -2
- package/plugins/keys/index.ts +5 -1
- package/plugins/mcp/index.ts +197 -78
- package/plugins/mcp/install.ts +5 -3
- package/plugins/mcp/mcp.ts +163 -11
- package/plugins/mcp/plugin.json +2 -1
- package/plugins/mcp/project.ts +47 -50
- package/plugins/memory/index.ts +4 -4
- package/plugins/memory/style.ts +13 -14
- package/plugins/mentions/candidates.ts +67 -0
- package/plugins/mentions/index.ts +12 -5
- package/plugins/mentions/plugin.json +1 -1
- package/plugins/mentions/style.ts +13 -14
- package/plugins/models/configure.ts +10 -9
- package/plugins/models/index.ts +31 -4
- package/plugins/models/provider.ts +12 -1
- package/plugins/modes/index.ts +13 -2
- package/plugins/print/index.ts +7 -4
- package/plugins/prompts/index.ts +0 -0
- package/plugins/renderers/index.ts +10 -5
- package/plugins/repeats/index.ts +39 -9
- package/plugins/schedule/index.ts +2 -0
- package/plugins/screenshot/browser.ts +231 -0
- package/plugins/screenshot/index.ts +3 -2
- package/plugins/screenshot/tool.ts +27 -51
- package/plugins/sessions/index.ts +48 -2
- package/plugins/shell/index.ts +75 -22
- package/plugins/shell/plugin.json +1 -2
- package/plugins/shell/renderers.ts +9 -7
- package/plugins/shell/shell.ts +93 -34
- package/plugins/skills/index.ts +28 -19
- package/plugins/skills/project.ts +12 -7
- package/plugins/steer/index.ts +5 -4
- package/plugins/task/index.ts +81 -81
- package/plugins/task/plugin.json +5 -2
- package/plugins/task/style.ts +13 -14
- package/plugins/task/subagent.ts +67 -184
- package/plugins/todo/index.ts +39 -9
- package/plugins/tools/index.ts +57 -0
- package/plugins/tools/plugin.json +7 -0
- package/plugins/tui/frontend.ts +161 -87
- package/plugins/tui/index.ts +2 -3
- package/plugins/tui/mascot.ts +8 -7
- package/plugins/tui/mentions.ts +11 -80
- package/plugins/tui/plugin.json +1 -1
- package/plugins/tui/screen.ts +55 -5
- package/plugins/tui/transcript.ts +17 -7
- package/plugins/tui/tui.ts +356 -104
- package/plugins/tui/vendor.ts +1 -1
- package/plugins/undo/checkpoint.ts +5 -3
- package/plugins/undo/index.ts +43 -14
- package/plugins/undo/style.ts +13 -14
- package/plugins/web/index.ts +7 -18
- package/plugins/web/plugin.json +1 -1
- package/plugins-dist/approval/index.js +363 -414
- package/plugins-dist/approval/policy.js +395 -497
- package/plugins-dist/approval/review.js +132 -158
- package/plugins-dist/approval/schema.js +50 -55
- package/plugins-dist/ask/index.js +115 -129
- package/plugins-dist/budget/index.js +27 -31
- package/plugins-dist/checks/checks.js +293 -329
- package/plugins-dist/checks/index.js +119 -139
- package/plugins-dist/checks/plugin.json +2 -1
- package/plugins-dist/checks/project.js +57 -65
- package/plugins-dist/commands/index.js +47 -29
- package/plugins-dist/compact/compact.js +233 -249
- package/plugins-dist/compact/index.js +98 -95
- package/plugins-dist/compact/style.js +9 -14
- package/plugins-dist/completions/index.js +30 -0
- package/plugins-dist/completions/plugin.json +9 -0
- package/plugins-dist/continue/index.js +40 -52
- package/plugins-dist/copy/index.js +40 -0
- package/plugins-dist/copy/plugin.json +9 -0
- package/plugins-dist/cost/index.js +98 -115
- package/plugins-dist/custom-commands/index.js +55 -72
- package/plugins-dist/editor/index.js +64 -72
- package/plugins-dist/fs/diff.js +111 -124
- package/plugins-dist/fs/fs.js +426 -469
- package/plugins-dist/fs/grep.js +262 -244
- package/plugins-dist/fs/index.js +20 -34
- package/plugins-dist/fs/plugin.json +1 -2
- package/plugins-dist/fs/renderers.js +100 -112
- package/plugins-dist/fs/style.js +11 -15
- package/plugins-dist/fs/sys.js +31 -43
- package/plugins-dist/hooks/index.js +107 -127
- package/plugins-dist/keys/index.js +27 -31
- package/plugins-dist/mcp/index.js +271 -199
- package/plugins-dist/mcp/install.js +123 -137
- package/plugins-dist/mcp/mcp.js +638 -577
- package/plugins-dist/mcp/plugin.json +3 -1
- package/plugins-dist/mcp/project.js +98 -115
- package/plugins-dist/memory/index.js +83 -88
- package/plugins-dist/memory/memory.js +111 -128
- package/plugins-dist/memory/style.js +9 -14
- package/plugins-dist/mentions/attach.js +91 -99
- package/plugins-dist/mentions/candidates.js +49 -0
- package/plugins-dist/mentions/index.js +71 -81
- package/plugins-dist/mentions/plugin.json +2 -1
- package/plugins-dist/mentions/style.js +9 -14
- package/plugins-dist/models/config.js +29 -43
- package/plugins-dist/models/configure.js +392 -473
- package/plugins-dist/models/context.js +14 -22
- package/plugins-dist/models/index.js +182 -188
- package/plugins-dist/models/provider.js +243 -295
- package/plugins-dist/models/saved.js +59 -71
- package/plugins-dist/modes/index.js +138 -165
- package/plugins-dist/plugins/index.js +34 -34
- package/plugins-dist/print/index.js +192 -175
- package/plugins-dist/prompts/index.js +81 -89
- package/plugins-dist/prompts/notes.js +31 -37
- package/plugins-dist/prompts/prompts.js +155 -193
- package/plugins-dist/prompts/results.js +40 -53
- package/plugins-dist/prompts/sys.js +39 -50
- package/plugins-dist/renderers/index.js +32 -32
- package/plugins-dist/repeats/index.js +134 -151
- package/plugins-dist/schedule/cron.js +49 -56
- package/plugins-dist/schedule/index.js +229 -247
- package/plugins-dist/schedule/store.js +93 -109
- package/plugins-dist/scratch/index.js +12 -18
- package/plugins-dist/screenshot/browser.js +169 -0
- package/plugins-dist/screenshot/index.js +37 -45
- package/plugins-dist/screenshot/sys.js +53 -65
- package/plugins-dist/screenshot/tool.js +101 -151
- package/plugins-dist/sessions/index.js +149 -117
- package/plugins-dist/shell/index.js +117 -74
- package/plugins-dist/shell/plugin.json +1 -2
- package/plugins-dist/shell/renderers.js +28 -33
- package/plugins-dist/shell/service.js +17 -23
- package/plugins-dist/shell/shell.js +317 -320
- package/plugins-dist/shell/sys.js +64 -79
- package/plugins-dist/skills/index.js +193 -211
- package/plugins-dist/skills/install.js +122 -149
- package/plugins-dist/skills/project.js +65 -73
- package/plugins-dist/skills/skills.js +135 -171
- package/plugins-dist/steer/index.js +108 -125
- package/plugins-dist/suggest/index.js +235 -259
- package/plugins-dist/task/index.js +130 -148
- package/plugins-dist/task/plugin.json +5 -4
- package/plugins-dist/task/style.js +9 -14
- package/plugins-dist/task/subagent.js +156 -279
- package/plugins-dist/todo/index.js +79 -63
- package/plugins-dist/tools/index.js +43 -0
- package/plugins-dist/tools/plugin.json +9 -0
- package/plugins-dist/tui/editor.js +145 -160
- package/plugins-dist/tui/frontend.js +641 -655
- package/plugins-dist/tui/history.js +34 -37
- package/plugins-dist/tui/index.js +16 -18
- package/plugins-dist/tui/markdown.js +203 -247
- package/plugins-dist/tui/mascot.js +266 -353
- package/plugins-dist/tui/mentions.js +67 -144
- package/plugins-dist/tui/plugin.json +1 -2
- package/plugins-dist/tui/render.js +35 -45
- package/plugins-dist/tui/screen.js +197 -180
- package/plugins-dist/tui/transcript.js +436 -468
- package/plugins-dist/tui/tui.js +1554 -1645
- package/plugins-dist/tui/vendor.js +1388 -1088
- package/plugins-dist/undo/checkpoint.js +95 -118
- package/plugins-dist/undo/index.js +185 -192
- package/plugins-dist/undo/snapshot.js +83 -99
- package/plugins-dist/undo/style.js +9 -14
- package/plugins-dist/update/index.js +26 -28
- package/plugins-dist/web/env.js +55 -68
- package/plugins-dist/web/index.js +80 -110
- package/plugins-dist/web/plugin.json +1 -2
- package/plugins-dist/web/renderers.js +4 -5
- package/plugins-dist/web/web.js +514 -593
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/sdk/python/jade_plugin.py +9 -2
- package/src/api.ts +1 -1
- package/src/host.ts +39 -4
- package/src/remote.ts +6 -1
- package/src/session.ts +489 -34
|
@@ -252,16 +252,17 @@ export function configurator(opts: ConfigureOptions): Configure {
|
|
|
252
252
|
const same = kind === current?.kind;
|
|
253
253
|
|
|
254
254
|
let baseURL: string | undefined = env[URL_KEY[kind]];
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
255
|
+
// Anthropic 也能改地址(代理、兼容服务):留空用官方地址。不预填官方地址:预填了回车就会把它写进
|
|
256
|
+
// ANTHROPIC_BASE_URL,和以前没写地址时保存的同一个服务对不上(找不到保存过的密钥,models.json 里多出一份)
|
|
257
|
+
const fallback = kind === "openai" ? "https://api.openai.com/v1" : "";
|
|
258
|
+
const placeholder = kind === "anthropic" ? "empty for https://api.anthropic.com (SDK adds /v1)" : "https://example.com/v1";
|
|
259
|
+
const url = await ui.input({ title: "Base URL", initial: baseURL ?? fallback, placeholder }, opts.signal);
|
|
260
|
+
if (url === undefined) return false;
|
|
261
|
+
if (kind === "openai-compat" && !url) {
|
|
262
|
+
report("A base URL is required.");
|
|
263
|
+
return false;
|
|
264
264
|
}
|
|
265
|
+
baseURL = url || undefined;
|
|
265
266
|
|
|
266
267
|
// 已知的密钥:当前服务的,或者保存过的同一个地址的服务的(最近用过的那个)
|
|
267
268
|
const sameAddress = (e: Env) => {
|
package/plugins/models/index.ts
CHANGED
|
@@ -14,13 +14,21 @@ import { configurator } from "./configure.ts";
|
|
|
14
14
|
import { isBuiltinKind, listModels, MODEL_KEY, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, visionFromEnv, withRetry, type RetriedResponse } from "./provider.ts";
|
|
15
15
|
import { MODEL_SETTINGS, readSavedServices, type Env } from "./saved.ts";
|
|
16
16
|
|
|
17
|
+
/** 进程级的配置交给会话里的提示用:有没有配好模型、有没有 /model、.env 在哪 */
|
|
18
|
+
let setup: { configured(): boolean; command: boolean; envFile: string } | undefined;
|
|
19
|
+
/** 没配模型的提示一个进程只说一次 */
|
|
20
|
+
let hinted = false;
|
|
21
|
+
|
|
17
22
|
export default definePlugin({
|
|
18
23
|
async process(ctx) {
|
|
19
24
|
const envFile = path.join(ctx.home, ".env");
|
|
20
25
|
const modelsFile = path.join(ctx.home, "models.json");
|
|
21
26
|
// 当前的模型配置。改配置时整份换掉(updateEnvFile 改的是这一份,apply 再从文件读一遍)
|
|
22
27
|
let env = await envWithFile(envFile);
|
|
23
|
-
|
|
28
|
+
hinted = false;
|
|
29
|
+
setup = { configured: () => hasProvider(env), command: false, envFile };
|
|
30
|
+
// 用的时候再取:jade/tui 也依赖这个插件(models@1),它在这之后才激活,这里取到的是 undefined,重试的提示就没人显示
|
|
31
|
+
const ui = () => ctx.service<UI>("ui@1");
|
|
24
32
|
const watchers = new Set<() => void>();
|
|
25
33
|
const notify = () => {
|
|
26
34
|
for (const fn of watchers) {
|
|
@@ -44,11 +52,11 @@ export default definePlugin({
|
|
|
44
52
|
// 用创建时的这份配置:之后换了配置,新的一份自己建 provider
|
|
45
53
|
const build = (snapshot: Env): Promise<Provider> => {
|
|
46
54
|
return (async () => {
|
|
47
|
-
const gate = new RateGate({ rpm: rpmFromEnv(snapshot), onLearn: (rpm) => ui?.notify(`rate limited: spacing requests to ${rpm} per minute from now on`, "warning") });
|
|
55
|
+
const gate = new RateGate({ rpm: rpmFromEnv(snapshot), onLearn: (rpm) => ui()?.notify(`rate limited: spacing requests to ${rpm} per minute from now on`, "warning") });
|
|
48
56
|
return withRetry(await providerFromEnv(snapshot), {
|
|
49
57
|
gate,
|
|
50
58
|
onRetry: ({ attempt, retries, delayMs, error }) =>
|
|
51
|
-
ui?.notify(`model request failed (${error.message}); retry ${attempt} of ${retries} in ${Math.round(delayMs / 1000)}s`, "warning"),
|
|
59
|
+
ui()?.notify(`model request failed (${error.message}); retry ${attempt} of ${retries} in ${Math.round(delayMs / 1000)}s`, "warning"),
|
|
52
60
|
});
|
|
53
61
|
})();
|
|
54
62
|
};
|
|
@@ -156,7 +164,9 @@ export default definePlugin({
|
|
|
156
164
|
notify();
|
|
157
165
|
};
|
|
158
166
|
|
|
159
|
-
ctx.service<Commands>("commands@1")
|
|
167
|
+
const commands = ctx.service<Commands>("commands@1");
|
|
168
|
+
setup.command = commands !== undefined;
|
|
169
|
+
commands?.register({
|
|
160
170
|
name: "model",
|
|
161
171
|
args: "[name]",
|
|
162
172
|
description: "switch models, or add one with its provider, API key and limits",
|
|
@@ -178,6 +188,23 @@ export default definePlugin({
|
|
|
178
188
|
},
|
|
179
189
|
|
|
180
190
|
session(ctx) {
|
|
191
|
+
const ui = ctx.service<UI>("ui@1");
|
|
192
|
+
// 还没配模型:告诉用户怎么配。/model 当场就能配好,不用重启;没有这条命令时只能改文件
|
|
193
|
+
if (setup && !setup.configured() && !hinted && ui?.interactive) {
|
|
194
|
+
hinted = true;
|
|
195
|
+
const file = `put ANTHROPIC_API_KEY=... (or OPENAI_API_KEY=...) in ${setup.envFile}, then restart jade`;
|
|
196
|
+
ui.notify(setup.command ? `No model is configured yet. Type /model to set one up, or ${file}.` : `No model is configured yet. To set one up, ${file}.`, "warning");
|
|
197
|
+
}
|
|
198
|
+
// 回复被输出上限截断:上限是这里的配置(JADE_MAX_TOKENS),只有这里知道怎么改
|
|
199
|
+
ctx.kernel.hook({
|
|
200
|
+
kind: "observe",
|
|
201
|
+
point: "event",
|
|
202
|
+
fn: (e) => {
|
|
203
|
+
if (e.type === "turn.ended" && (e.data as { reason?: string }).reason === "max_tokens" && setup?.command) {
|
|
204
|
+
ui?.notify("if replies keep getting cut off, raise the output limit with /model", "info");
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
});
|
|
181
208
|
// 重试过的请求:把每次失败写进会话日志,事后能查到为什么慢、为什么重新输出(插件事件,不进上下文)
|
|
182
209
|
ctx.kernel.hook({
|
|
183
210
|
kind: "observe",
|
|
@@ -73,7 +73,18 @@ export function withRetry(inner: Provider, opts: RetryOptions = {}): Provider {
|
|
|
73
73
|
// 实际回复的是被包装者(4.7 第 3 款)
|
|
74
74
|
return { ...res, provider: res.provider ?? inner.id, ...(failures.length > 0 ? { retries: failures } : {}) };
|
|
75
75
|
} catch (err) {
|
|
76
|
-
if (!(err instanceof ProviderError) ||
|
|
76
|
+
if (!(err instanceof ProviderError) || options.signal.aborted) throw err;
|
|
77
|
+
if (!err.retryable || attempt > retries) {
|
|
78
|
+
if (failures.length === 0) throw err;
|
|
79
|
+
// 失败时没有回复可以带上重试记录:写进错误信息里,会话日志(turn.ended)和界面上都看得到重试过、等了多久
|
|
80
|
+
const waited = Math.round(failures.reduce((ms, f) => ms + f.delayMs, 0) / 1000);
|
|
81
|
+
throw new ProviderError(`${err.message} (after ${failures.length} ${failures.length === 1 ? "retry" : "retries"}, ${waited}s of waiting)`, {
|
|
82
|
+
retryable: err.retryable,
|
|
83
|
+
status: err.status,
|
|
84
|
+
retryAfterMs: err.retryAfterMs,
|
|
85
|
+
cause: err,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
77
88
|
// 在计划的时间上随机缩短最多 20%,并行的子 Agent 同时遇到 429 时不会同时重试。
|
|
78
89
|
// 上游给的 retryAfterMs 只当下限:有的服务(尤其是并发数限流)每次都回 Retry-After: 1,
|
|
79
90
|
// 拿它代替退避计划会每秒撞一次,十几秒就把重试次数用完
|
package/plugins/modes/index.ts
CHANGED
|
@@ -181,7 +181,8 @@ export default definePlugin({
|
|
|
181
181
|
}
|
|
182
182
|
|
|
183
183
|
// 能问用户时才有 propose_plan;它只在 plan 模式下发给模型
|
|
184
|
-
|
|
184
|
+
// 子会话(子 Agent)不提交计划:计划由用户的会话提交
|
|
185
|
+
const canPropose = !!ui?.interactive && ctx.session.parent === undefined;
|
|
185
186
|
if (canPropose) ctx.kernel.tool(proposePlanTool(approval, ui!));
|
|
186
187
|
ctx.kernel.hook({
|
|
187
188
|
kind: "transform",
|
|
@@ -199,8 +200,18 @@ export default definePlugin({
|
|
|
199
200
|
note = undefined;
|
|
200
201
|
}
|
|
201
202
|
};
|
|
203
|
+
// 状态栏上的当前模式:窄的时候也留着(去掉 shift+tab 提示),颜色说明它放得多宽
|
|
204
|
+
const show = () => {
|
|
205
|
+
const mode = approval.mode();
|
|
206
|
+
const tone = mode === "yolo" ? "error" : mode === "auto" ? "warn" : mode === "plan" ? "accent" : "ok";
|
|
207
|
+
ctx.status?.({ text: `${mode} (shift+tab)`, short: mode, tone, keep: true });
|
|
208
|
+
};
|
|
202
209
|
sync();
|
|
203
|
-
|
|
210
|
+
show();
|
|
211
|
+
const onChange = () => {
|
|
212
|
+
sync();
|
|
213
|
+
show();
|
|
214
|
+
};
|
|
204
215
|
listeners.add(onChange);
|
|
205
216
|
ctx.effect(() => () => void listeners.delete(onChange));
|
|
206
217
|
},
|
package/plugins/print/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// jade/print:jade -p "<prompt>" 跑一轮就退出。模型的回复写到 stdout,工具调用和提示写到 stderr。
|
|
2
2
|
// 不能向用户提问:ui@1 的 select 总是返回 undefined,要审批的调用由审批插件拒绝。
|
|
3
3
|
|
|
4
|
+
import { stripVTControlCharacters } from "node:util";
|
|
4
5
|
import type { Block, LogEvent, RuntimeNotice, Usage } from "uncarved";
|
|
5
6
|
import { definePlugin, type Frontend, type UI } from "@uncarved/jade-api";
|
|
6
7
|
import type { SessionIndex } from "@uncarved/jade-api/services";
|
|
@@ -18,10 +19,12 @@ Runs one prompt and exits. The reply goes to stdout; tool calls and notices go t
|
|
|
18
19
|
Exit code: 0 when the turn ends normally, 1 on an error, 130 when interrupted.
|
|
19
20
|
jade's own commands (plugins, update, --safe): jade help`;
|
|
20
21
|
|
|
21
|
-
|
|
22
|
+
/** -p 的 ui@1(导出给测试) */
|
|
23
|
+
export const ui: UI = {
|
|
22
24
|
interactive: false,
|
|
23
25
|
notify(message, level = "info") {
|
|
24
|
-
|
|
26
|
+
// 输出常常被重定向、交给别的程序:插件和工具带来的颜色、控制序列都去掉
|
|
27
|
+
process.stderr.write(`${level === "info" ? "" : `[${level}] `}${stripVTControlCharacters(String(message))}\n`);
|
|
25
28
|
},
|
|
26
29
|
select: async () => undefined,
|
|
27
30
|
input: async () => undefined,
|
|
@@ -96,11 +99,11 @@ const frontend: Frontend = {
|
|
|
96
99
|
}
|
|
97
100
|
if (e.type === "tool.decided") {
|
|
98
101
|
const d = e.data as { decision: string; reason?: string };
|
|
99
|
-
if (d.decision === "deny") process.stderr.write(` denied${d.reason ? `: ${d.reason}` : ""}\n`);
|
|
102
|
+
if (d.decision === "deny") process.stderr.write(` denied${d.reason ? `: ${stripVTControlCharacters(d.reason)}` : ""}\n`);
|
|
100
103
|
}
|
|
101
104
|
if (e.type === "tool.completed") {
|
|
102
105
|
const d = e.data as { isError: boolean; content: Block[] };
|
|
103
|
-
if (d.isError) process.stderr.write(` failed: ${firstLine(d.content)}\n`);
|
|
106
|
+
if (d.isError) process.stderr.write(` failed: ${stripVTControlCharacters(firstLine(d.content))}\n`);
|
|
104
107
|
}
|
|
105
108
|
if (e.type === "turn.ended") ended = e.data as { reason: string; error?: string };
|
|
106
109
|
});
|
package/plugins/prompts/index.ts
CHANGED
|
Binary file
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// jade/renderers:工具调用和插件事件在对话里怎么显示的注册表。前端查这里;没有登记的用前端的默认显示。
|
|
2
|
-
//
|
|
2
|
+
// 显示的文字是 jade-api 的 Text(带语义样式的片段,也可以是普通字符串),怎么画由前端决定;
|
|
3
|
+
// 前端负责过滤掉字符串里颜色之外的控制序列。
|
|
3
4
|
|
|
4
5
|
import { definePlugin } from "@uncarved/jade-api";
|
|
5
6
|
import type { EventRenderer, Renderers, ToolRenderer } from "@uncarved/jade-api/services";
|
|
@@ -7,9 +8,13 @@ import type { EventRenderer, Renderers, ToolRenderer } from "@uncarved/jade-api/
|
|
|
7
8
|
const tools = new Map<string, { renderer: ToolRenderer; plugin: string }>();
|
|
8
9
|
const events = new Map<string, { renderer: EventRenderer; plugin: string }>();
|
|
9
10
|
|
|
10
|
-
function add<T>(map: Map<string, { renderer: T; plugin: string }>, key: string, renderer: T, plugin: string, what: string, onDispose: (d: () => void) => void): () => void {
|
|
11
|
+
function add<T>(map: Map<string, { renderer: T; plugin: string }>, key: string, renderer: T, plugin: string, what: string, onDispose: (d: () => void) => void, report: (m: string) => void): () => void {
|
|
12
|
+
// 重名时先登记的留下,后来的跳过并报告(同 commands@1)
|
|
11
13
|
const taken = map.get(key);
|
|
12
|
-
if (taken)
|
|
14
|
+
if (taken) {
|
|
15
|
+
report(`the renderer for ${what} ${key} from ${plugin} was skipped: ${taken.plugin} already registered one`);
|
|
16
|
+
return () => {};
|
|
17
|
+
}
|
|
13
18
|
const entry = { renderer, plugin };
|
|
14
19
|
map.set(key, entry);
|
|
15
20
|
const revoke = () => {
|
|
@@ -24,11 +29,11 @@ export default definePlugin({
|
|
|
24
29
|
ctx.provide("renderers@1", (caller): Renderers => ({
|
|
25
30
|
tool(renderer) {
|
|
26
31
|
if (typeof renderer?.tool !== "string" || !renderer.tool) throw new Error("a tool renderer needs the tool name");
|
|
27
|
-
return add(tools, renderer.tool, renderer, caller.plugin, "tool", caller.onDispose);
|
|
32
|
+
return add(tools, renderer.tool, renderer, caller.plugin, "tool", caller.onDispose, ctx.report);
|
|
28
33
|
},
|
|
29
34
|
event(renderer) {
|
|
30
35
|
if (typeof renderer?.event !== "string" || !renderer.event || typeof renderer.render !== "function") throw new Error("an event renderer needs the event type and render");
|
|
31
|
-
return add(events, `${caller.plugin}/${renderer.event}`, renderer, caller.plugin, "event", caller.onDispose);
|
|
36
|
+
return add(events, `${caller.plugin}/${renderer.event}`, renderer, caller.plugin, "event", caller.onDispose, ctx.report);
|
|
32
37
|
},
|
|
33
38
|
forTool: (tool) => tools.get(tool),
|
|
34
39
|
forEvent: (type) => events.get(type),
|
package/plugins/repeats/index.ts
CHANGED
|
@@ -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 移植。
|
|
@@ -24,10 +25,10 @@ export const COMPACT_KEY = "jade/compact";
|
|
|
24
25
|
/** 只打开一个文件或网址的命令:start "" x、start x、xdg-open x、open x、explorer x */
|
|
25
26
|
const OPEN = /^\s*(?:start\s+""|start|xdg-open|open|explorer(?:\.exe)?)\s+(?:"([^"]+)"|'([^']+)'|([^\s"'&|;<>]+))\s*$/i;
|
|
26
27
|
|
|
27
|
-
/**
|
|
28
|
-
export function openTarget(call: { name: string; input: unknown }, cwd: string): string | undefined {
|
|
29
|
-
if (
|
|
30
|
-
const command = (call.input as
|
|
28
|
+
/** 执行命令的调用(shell 是命令所在的字段,见工具的 meta.shell)打开的目标(规范化后),不是打开命令时是 undefined */
|
|
29
|
+
export function openTarget(call: { name: string; input: unknown }, cwd: string, shell: string | undefined): string | undefined {
|
|
30
|
+
if (shell === undefined) return undefined;
|
|
31
|
+
const command = (call.input as Record<string, unknown> | null)?.[shell];
|
|
31
32
|
if (typeof command !== "string") return undefined;
|
|
32
33
|
const m = OPEN.exec(command);
|
|
33
34
|
const target = m && (m[1] ?? m[2] ?? m[3]);
|
|
@@ -42,11 +43,20 @@ function normalize(cwd: string, p: string): string {
|
|
|
42
43
|
|
|
43
44
|
/** 提醒模型的失败次数 */
|
|
44
45
|
const WARN_AFTER = 2;
|
|
46
|
+
/** 同一处文字来回改到第几次时提醒:改过去、改回来各算一次,改回来一次是正常的撤销 */
|
|
47
|
+
const FLIP_AFTER = 3;
|
|
48
|
+
|
|
49
|
+
/** edit_file、multi_edit 里的每一处替换 */
|
|
50
|
+
function replacements(call: { name: string; input: unknown }): { old_string: string; new_string: string }[] {
|
|
51
|
+
const input = call.input as { old_string?: unknown; new_string?: unknown; edits?: unknown } | null;
|
|
52
|
+
const list = call.name === "edit_file" ? [input] : call.name === "multi_edit" && Array.isArray(input?.edits) ? input.edits : [];
|
|
53
|
+
return list.filter((e): e is { old_string: string; new_string: string } => typeof e?.old_string === "string" && typeof e?.new_string === "string");
|
|
54
|
+
}
|
|
45
55
|
|
|
46
56
|
const hash = (content: Block[]) => createHash("sha1").update(JSON.stringify(content.map((b) => (b.kind === "text" ? b.text : b)))).digest("hex");
|
|
47
57
|
|
|
48
58
|
/** 会话里的 hook:model.before 数回复次数,tool.gate 拒绝重复,tool.after 加提醒,event 在用户发消息、压缩后重新计 */
|
|
49
|
-
export function repeatsHooks(opts: { cwd: string; id?: string }): LocalHookSpec[] {
|
|
59
|
+
export function repeatsHooks(opts: { cwd: string; id?: string; /** 执行命令的工具把命令放在哪个字段(ctx.session.tool 的 meta.shell) */ shell: (tool: string) => string | undefined }): LocalHookSpec[] {
|
|
50
60
|
const id = opts.id ?? ID;
|
|
51
61
|
const cwd = opts.cwd;
|
|
52
62
|
/** 模型调用的次数,每次调用模型前加一 */
|
|
@@ -67,6 +77,8 @@ export function repeatsHooks(opts: { cwd: string; id?: string }): LocalHookSpec[
|
|
|
67
77
|
const opened = new Map<string, number>();
|
|
68
78
|
/** 本轮用 write_file 写过的文件 → 写完时的 changes;用户发消息时清空 */
|
|
69
79
|
const written = new Map<string, number>();
|
|
80
|
+
/** 文件里互相替换的一对文字 → 本轮里换了几次(不分方向);用户发消息时清空 */
|
|
81
|
+
const flips = new Map<string, number>();
|
|
70
82
|
const key = (call: { name: string; input: unknown }) => `${call.name}\0${JSON.stringify(call.input)}`;
|
|
71
83
|
const note = (text: string): Block => ({ kind: "text", text: `[Note from jade] ${text}`, origin: { by: "plugin", id }, trust: "trusted" });
|
|
72
84
|
return [
|
|
@@ -87,7 +99,7 @@ export function repeatsHooks(opts: { cwd: string; id?: string }): LocalHookSpec[
|
|
|
87
99
|
return { decision: "deny", reason: "This call is identical to an earlier call in the same response and was not run; use that call's result." };
|
|
88
100
|
}
|
|
89
101
|
current.keys.add(k);
|
|
90
|
-
const target = openTarget(call, cwd);
|
|
102
|
+
const target = openTarget(call, cwd, opts.shell(call.name));
|
|
91
103
|
// 同一次回复里排在前面的调用可能改了它,还没执行,不拒绝
|
|
92
104
|
if (target !== undefined && opened.get(target) === changes && !current.mutates) {
|
|
93
105
|
return {
|
|
@@ -111,7 +123,7 @@ export function repeatsHooks(opts: { cwd: string; id?: string }): LocalHookSpec[
|
|
|
111
123
|
readOnly.delete(outcome.call.toolUseId);
|
|
112
124
|
if (!outcome.isError) {
|
|
113
125
|
failures.delete(k);
|
|
114
|
-
const target = openTarget(outcome.call, cwd);
|
|
126
|
+
const target = openTarget(outcome.call, cwd, opts.shell(outcome.call.name));
|
|
115
127
|
if (target !== undefined) opened.set(target, changes);
|
|
116
128
|
else if (!read) changes++;
|
|
117
129
|
const file = (outcome.call.input as { path?: unknown } | null)?.path;
|
|
@@ -120,13 +132,30 @@ export function repeatsHooks(opts: { cwd: string; id?: string }): LocalHookSpec[
|
|
|
120
132
|
outcome.call.name === "read_file" && typeof file === "string" && written.get(normalize(cwd, file)) === changes
|
|
121
133
|
? note("You wrote this file with write_file earlier and nothing has changed since: its content is exactly what you gave. Do not read files back to check them.")
|
|
122
134
|
: undefined;
|
|
135
|
+
let most = 0;
|
|
136
|
+
if (typeof file === "string") {
|
|
137
|
+
for (const e of replacements(outcome.call)) {
|
|
138
|
+
const pair = `${normalize(cwd, file)}${[e.old_string, e.new_string].sort().join("")}`;
|
|
139
|
+
const n = (flips.get(pair) ?? 0) + 1;
|
|
140
|
+
flips.set(pair, n);
|
|
141
|
+
most = Math.max(most, n);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const flipped =
|
|
145
|
+
most >= FLIP_AFTER
|
|
146
|
+
? note(
|
|
147
|
+
`You have now switched this same text back and forth ${most} times in this file. Going back and forth means what you are judging by is unreliable or incomplete. ` +
|
|
148
|
+
"Do not flip it again: check your assumption another way (measure it, read the code involved), or tell the user what you see and ask.",
|
|
149
|
+
)
|
|
150
|
+
: undefined;
|
|
151
|
+
const extra = [readBack, flipped].filter((b) => b !== undefined);
|
|
123
152
|
const before = succeeded.get(k);
|
|
124
153
|
// 只读之外的调用(包括这一个)可能改了东西,之后的调用都不算"什么都没变"
|
|
125
154
|
if (!read) version++;
|
|
126
155
|
const result = hash(outcome.content);
|
|
127
156
|
const repeated = before !== undefined && before.version === (read ? version : version - 1) && before.result === result;
|
|
128
157
|
succeeded.set(k, { version, result });
|
|
129
|
-
if (!repeated) return
|
|
158
|
+
if (!repeated) return extra.length > 0 ? { ...outcome, content: [...outcome.content, ...extra] } : undefined;
|
|
130
159
|
const text =
|
|
131
160
|
"This exact call already ran earlier with the same result, and nothing has changed since (no edits, no other commands, no new message from the user). " +
|
|
132
161
|
"Do not repeat it: use what you already have, or end your turn and tell the user where things stand.";
|
|
@@ -152,6 +181,7 @@ export function repeatsHooks(opts: { cwd: string; id?: string }): LocalHookSpec[
|
|
|
152
181
|
version++;
|
|
153
182
|
opened.clear();
|
|
154
183
|
written.clear();
|
|
184
|
+
flips.clear();
|
|
155
185
|
}
|
|
156
186
|
},
|
|
157
187
|
},
|
|
@@ -160,6 +190,6 @@ export function repeatsHooks(opts: { cwd: string; id?: string }): LocalHookSpec[
|
|
|
160
190
|
|
|
161
191
|
export default definePlugin({
|
|
162
192
|
session(ctx) {
|
|
163
|
-
for (const h of repeatsHooks({ cwd: ctx.cwd, id: ctx.plugin })) ctx.kernel.hook(h);
|
|
193
|
+
for (const h of repeatsHooks({ cwd: ctx.cwd, id: ctx.plugin, shell: (t) => ctx.session.tool(t)?.meta?.shell })) ctx.kernel.hook(h);
|
|
164
194
|
},
|
|
165
195
|
});
|
|
@@ -249,6 +249,8 @@ export default definePlugin({
|
|
|
249
249
|
},
|
|
250
250
|
|
|
251
251
|
async session(ctx) {
|
|
252
|
+
// 子会话(子 Agent)不建定时任务,也不接收:到点的任务投到用户的会话里
|
|
253
|
+
if (ctx.session.parent) return;
|
|
252
254
|
const store = new ScheduleStore(ctx.home);
|
|
253
255
|
for (const t of tools(store, ctx.cwd)) ctx.kernel.tool(t);
|
|
254
256
|
|
|
@@ -0,0 +1,231 @@
|
|
|
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
|
+
|
|
11
|
+
import { readFile } from "node:fs/promises";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { spawn, type Proc } from "./sys.ts";
|
|
14
|
+
|
|
15
|
+
/** 浏览器启动到能连接的最长时间 */
|
|
16
|
+
const READY_MS = 10_000;
|
|
17
|
+
/** 等页面 load 事件的最长时间;到时间还没有就按当时的样子截 */
|
|
18
|
+
const LOAD_MS = 15_000;
|
|
19
|
+
/** load 之后等网络安静下来(脚本、图片、字体)的最长时间 */
|
|
20
|
+
const SETTLE_MS = 3000;
|
|
21
|
+
/** 让浏览器自己关的最长时间,过了就直接结束进程 */
|
|
22
|
+
const CLOSE_MS = 5000;
|
|
23
|
+
/** 滚动之后给懒加载的图片、滚动触发的动画的时间 */
|
|
24
|
+
const SCROLL_SETTLE_MS = 400;
|
|
25
|
+
|
|
26
|
+
export interface CaptureRequest {
|
|
27
|
+
/** file:// 或 http(s):// */
|
|
28
|
+
target: string;
|
|
29
|
+
width: number;
|
|
30
|
+
height: number;
|
|
31
|
+
/** CSS 选择器,或页面上出现的一段文字:先滚动到它再截 */
|
|
32
|
+
scrollTo?: string;
|
|
33
|
+
/** 浏览器的用户目录:每次给一个新的临时目录 */
|
|
34
|
+
profile: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface Shot {
|
|
38
|
+
png: Buffer;
|
|
39
|
+
/** 整个页面的高度和截到的是哪一段 */
|
|
40
|
+
pageHeight: number;
|
|
41
|
+
scrollY: number;
|
|
42
|
+
/** 滚动到的元素,例如 <h2> "Trusted by…" */
|
|
43
|
+
scrolledTo?: string;
|
|
44
|
+
/** 截图不是页面完全加载后的样子时的说明 */
|
|
45
|
+
note?: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 截图失败、原因可以直接告诉模型的错误 */
|
|
49
|
+
export class CaptureError extends Error {}
|
|
50
|
+
|
|
51
|
+
export type Capture = (browser: string, req: CaptureRequest, signal: AbortSignal) => Promise<Shot>;
|
|
52
|
+
|
|
53
|
+
interface Cdp {
|
|
54
|
+
send<T = unknown>(method: string, params?: object, sessionId?: string): Promise<T>;
|
|
55
|
+
/** 等一个事件;已经来过的也算。到时间还没有返回 false */
|
|
56
|
+
seen(method: string, ms: number): Promise<boolean>;
|
|
57
|
+
close(): void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function connect(url: string): Promise<Cdp> {
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
const ws = new WebSocket(url);
|
|
63
|
+
let next = 0;
|
|
64
|
+
let closed = false;
|
|
65
|
+
const waiting = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();
|
|
66
|
+
const events = new Set<string>();
|
|
67
|
+
const listeners = new Set<(method: string) => void>();
|
|
68
|
+
ws.onerror = () => reject(new CaptureError("could not connect to the browser"));
|
|
69
|
+
ws.onclose = () => {
|
|
70
|
+
closed = true;
|
|
71
|
+
for (const w of waiting.values()) w.reject(new CaptureError("the browser closed before the screenshot was taken"));
|
|
72
|
+
waiting.clear();
|
|
73
|
+
};
|
|
74
|
+
ws.onmessage = (e) => {
|
|
75
|
+
const m = JSON.parse(String(e.data)) as { id?: number; method?: string; result?: unknown; error?: { message: string } };
|
|
76
|
+
if (m.id !== undefined) {
|
|
77
|
+
const w = waiting.get(m.id);
|
|
78
|
+
waiting.delete(m.id);
|
|
79
|
+
if (m.error) w?.reject(new CaptureError(m.error.message));
|
|
80
|
+
else w?.resolve(m.result);
|
|
81
|
+
} else if (m.method) {
|
|
82
|
+
// Page.lifecycleEvent 的名字在参数里:load、networkIdle……
|
|
83
|
+
const name = m.method === "Page.lifecycleEvent" ? `lifecycle:${(m as { params?: { name?: string } }).params?.name}` : m.method;
|
|
84
|
+
events.add(name);
|
|
85
|
+
for (const l of listeners) l(name);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
ws.onopen = () =>
|
|
89
|
+
resolve({
|
|
90
|
+
send: (method, params = {}, sessionId) =>
|
|
91
|
+
new Promise((res, rej) => {
|
|
92
|
+
if (closed) return rej(new CaptureError("the browser closed before the screenshot was taken"));
|
|
93
|
+
const id = ++next;
|
|
94
|
+
waiting.set(id, { resolve: res as (v: unknown) => void, reject: rej });
|
|
95
|
+
ws.send(JSON.stringify({ id, method, params, sessionId }));
|
|
96
|
+
}),
|
|
97
|
+
seen: (method, ms) =>
|
|
98
|
+
new Promise((res) => {
|
|
99
|
+
if (events.has(method)) return res(true);
|
|
100
|
+
const done = (ok: boolean) => {
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
listeners.delete(l);
|
|
103
|
+
res(ok);
|
|
104
|
+
};
|
|
105
|
+
const l = (name: string) => name === method && done(true);
|
|
106
|
+
const timer = setTimeout(() => done(false), ms);
|
|
107
|
+
listeners.add(l);
|
|
108
|
+
}),
|
|
109
|
+
close: () => ws.close(),
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 浏览器把调试端口和连接路径写在用户目录的 DevToolsActivePort 里;等它出现 */
|
|
115
|
+
async function debuggerUrl(profile: string, proc: Proc, signal: AbortSignal): Promise<string> {
|
|
116
|
+
let exited = false;
|
|
117
|
+
void proc.exited.then(() => (exited = true));
|
|
118
|
+
const deadline = Date.now() + READY_MS;
|
|
119
|
+
for (;;) {
|
|
120
|
+
signal.throwIfAborted();
|
|
121
|
+
try {
|
|
122
|
+
const [port, wsPath] = (await readFile(path.join(profile, "DevToolsActivePort"), "utf8")).trim().split("\n");
|
|
123
|
+
if (port && wsPath) return `ws://127.0.0.1:${port}${wsPath}`;
|
|
124
|
+
} catch {
|
|
125
|
+
// 还没写出来
|
|
126
|
+
}
|
|
127
|
+
if (exited) throw new CaptureError("the browser exited before it was ready");
|
|
128
|
+
if (Date.now() > deadline) throw new CaptureError(`the browser was not ready within ${READY_MS / 1000}s`);
|
|
129
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* 在页面里执行:滚动到 CSS 选择器匹配的第一个元素;选择器无效或没有匹配时,找第一个包含这段文字的元素。
|
|
135
|
+
* 比视口高的元素对齐到顶部,其余的放在中间
|
|
136
|
+
*/
|
|
137
|
+
const SCROLL = (what: string) => `(() => {
|
|
138
|
+
const what = ${JSON.stringify(what)};
|
|
139
|
+
let el = null;
|
|
140
|
+
try { el = document.querySelector(what); } catch {}
|
|
141
|
+
if (!el) {
|
|
142
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
|
143
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
144
|
+
if (n.nodeValue.includes(what) && n.parentElement && n.parentElement.getClientRects().length) { el = n.parentElement; break; }
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (!el) return null;
|
|
148
|
+
el.scrollIntoView({ block: el.getBoundingClientRect().height > innerHeight ? "start" : "center", behavior: "instant" });
|
|
149
|
+
const text = (el.textContent || "").trim().replace(/\\s+/g, " ");
|
|
150
|
+
return "<" + el.tagName.toLowerCase() + ">" + (text ? ' "' + (text.length > 40 ? text.slice(0, 40) + "…" : text) + '"' : "");
|
|
151
|
+
})()`;
|
|
152
|
+
|
|
153
|
+
const METRICS = "JSON.stringify({ h: Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0), y: Math.round(scrollY) })";
|
|
154
|
+
|
|
155
|
+
export const capture: Capture = async (browser, req, signal) => {
|
|
156
|
+
const proc = await spawn(
|
|
157
|
+
[
|
|
158
|
+
browser,
|
|
159
|
+
"--headless=new",
|
|
160
|
+
"--disable-gpu",
|
|
161
|
+
"--hide-scrollbars",
|
|
162
|
+
"--no-first-run",
|
|
163
|
+
"--no-default-browser-check",
|
|
164
|
+
"--disable-extensions",
|
|
165
|
+
"--mute-audio",
|
|
166
|
+
"--remote-debugging-port=0",
|
|
167
|
+
`--user-data-dir=${req.profile}`,
|
|
168
|
+
"about:blank",
|
|
169
|
+
],
|
|
170
|
+
{ stdout: "ignore", stderr: "ignore" },
|
|
171
|
+
);
|
|
172
|
+
// 中止(用户打断、总的超时)时不等页面:下面的等待都按自己的时间走,这里直接结束
|
|
173
|
+
let abort!: () => void;
|
|
174
|
+
const aborted = new Promise<never>((_, reject) => (abort = () => reject(signal.reason)));
|
|
175
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
176
|
+
let cdp: Cdp | undefined;
|
|
177
|
+
const work = async (): Promise<Shot> => {
|
|
178
|
+
cdp = await connect(await debuggerUrl(req.profile, proc, signal));
|
|
179
|
+
const { targetId } = await cdp.send<{ targetId: string }>("Target.createTarget", { url: "about:blank" });
|
|
180
|
+
const { sessionId } = await cdp.send<{ sessionId: string }>("Target.attachToTarget", { targetId, flatten: true });
|
|
181
|
+
const page = <T>(method: string, params?: object) => cdp!.send<T>(method, params, sessionId);
|
|
182
|
+
const evaluate = async <T>(expression: string) => (await page<{ result: { value: T } }>("Runtime.evaluate", { expression, returnByValue: true })).result.value;
|
|
183
|
+
|
|
184
|
+
await page("Emulation.setDeviceMetricsOverride", { width: req.width, height: req.height, deviceScaleFactor: 1, mobile: false });
|
|
185
|
+
await page("Page.enable");
|
|
186
|
+
await page("Page.setLifecycleEventsEnabled", { enabled: true });
|
|
187
|
+
const { errorText } = await page<{ errorText?: string }>("Page.navigate", { url: req.target });
|
|
188
|
+
if (errorText) throw new CaptureError(`the page could not be loaded: ${errorText}`);
|
|
189
|
+
const loaded = await cdp.seen("Page.loadEventFired", LOAD_MS);
|
|
190
|
+
if (loaded) await cdp.seen("lifecycle:networkIdle", SETTLE_MS);
|
|
191
|
+
signal.throwIfAborted();
|
|
192
|
+
|
|
193
|
+
let scrolledTo: string | undefined;
|
|
194
|
+
if (req.scrollTo !== undefined) {
|
|
195
|
+
const found = await evaluate<string | null>(SCROLL(req.scrollTo));
|
|
196
|
+
if (found === null) {
|
|
197
|
+
throw new CaptureError(
|
|
198
|
+
`nothing on the page matches scroll_to ${JSON.stringify(req.scrollTo)} (tried as a CSS selector, then as text)` +
|
|
199
|
+
(loaded ? "" : `; the page had not finished loading after ${LOAD_MS / 1000}s`),
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
scrolledTo = found;
|
|
203
|
+
await new Promise((r) => setTimeout(r, SCROLL_SETTLE_MS));
|
|
204
|
+
}
|
|
205
|
+
const { h, y } = JSON.parse(await evaluate<string>(METRICS)) as { h: number; y: number };
|
|
206
|
+
const { data } = await page<{ data: string }>("Page.captureScreenshot", { format: "png" });
|
|
207
|
+
return {
|
|
208
|
+
png: Buffer.from(data, "base64"),
|
|
209
|
+
pageHeight: h,
|
|
210
|
+
scrollY: y,
|
|
211
|
+
scrolledTo,
|
|
212
|
+
note: loaded ? undefined : `The page had not finished loading after ${LOAD_MS / 1000}s; this is how it looked at that point.`,
|
|
213
|
+
};
|
|
214
|
+
};
|
|
215
|
+
try {
|
|
216
|
+
return await Promise.race([work(), aborted]);
|
|
217
|
+
} finally {
|
|
218
|
+
signal.removeEventListener("abort", abort);
|
|
219
|
+
// 先让浏览器自己关:直接结束主进程时,Windows 上它的子进程还会占着 profile 好几秒,临时目录删不掉。
|
|
220
|
+
// 中止了(用户打断、超时)就不等它:马上结束,删不掉的临时目录留给系统清理
|
|
221
|
+
if (cdp && !signal.aborted) {
|
|
222
|
+
void cdp.send("Browser.close").catch(() => {});
|
|
223
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
224
|
+
await Promise.race([proc.exited, new Promise((r) => (timer = setTimeout(r, CLOSE_MS)))]);
|
|
225
|
+
clearTimeout(timer);
|
|
226
|
+
}
|
|
227
|
+
cdp?.close();
|
|
228
|
+
proc.kill();
|
|
229
|
+
await proc.exited;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
@@ -1,6 +1,6 @@
|
|
|
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
|
|
|
5
5
|
import { definePlugin } from "@uncarved/jade-api";
|
|
6
6
|
import type { Models, Prompts, Renderers } from "@uncarved/jade-api/services";
|
|
@@ -8,7 +8,8 @@ import { findBrowser, screenshotTool } from "./tool.ts";
|
|
|
8
8
|
|
|
9
9
|
/** 提示词里的一段:有截图工具时才加 */
|
|
10
10
|
const NOTE =
|
|
11
|
-
"- 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."
|
|
11
|
+
"- 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. " +
|
|
12
|
+
"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.";
|
|
12
13
|
|
|
13
14
|
export default definePlugin({
|
|
14
15
|
process(ctx) {
|