@uncarved/jade 0.2.0 → 0.3.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 +277 -0
- package/assets/logo.svg +1 -0
- package/bin/jade.js +15 -0
- package/dist/api.d.ts +5 -250
- package/dist/api.js +5 -7
- package/dist/api.js.map +1 -1
- package/dist/fetch.d.ts +8 -0
- package/dist/fetch.js +19 -17
- package/dist/fetch.js.map +1 -1
- package/dist/host.d.ts +12 -1
- package/dist/host.js +49 -1
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.js +28 -5
- package/dist/main.js.map +1 -1
- package/dist/remote.js +4 -0
- package/dist/remote.js.map +1 -1
- package/dist/session.d.ts +2 -0
- package/dist/session.js +133 -13
- package/dist/session.js.map +1 -1
- package/dist/source.d.ts +2 -10
- package/dist/source.js.map +1 -1
- package/dist/update.d.ts +8 -20
- package/dist/update.js +12 -1
- package/dist/update.js.map +1 -1
- package/package.json +6 -4
- package/plugins/approval/index.ts +246 -84
- package/plugins/approval/plugin.json +5 -1
- package/plugins/approval/policy.ts +27 -6
- package/plugins/approval/review.ts +1 -1
- package/plugins/ask/index.ts +2 -2
- package/plugins/budget/index.ts +1 -1
- package/plugins/checks/checks.ts +3 -2
- package/plugins/checks/index.ts +2 -5
- package/plugins/commands/index.ts +2 -44
- package/plugins/compact/compact.ts +15 -4
- package/plugins/compact/index.ts +13 -16
- package/plugins/continue/index.ts +1 -1
- package/plugins/cost/index.ts +143 -0
- package/plugins/cost/plugin.json +13 -0
- package/plugins/custom-commands/index.ts +85 -0
- package/plugins/custom-commands/plugin.json +8 -0
- package/plugins/editor/index.ts +88 -0
- package/plugins/editor/plugin.json +17 -0
- package/plugins/fs/fs.ts +110 -17
- package/plugins/fs/grep.ts +41 -11
- package/plugins/fs/index.ts +9 -7
- package/plugins/fs/renderers.ts +1 -1
- package/plugins/hooks/index.ts +152 -0
- package/plugins/hooks/plugin.json +14 -0
- package/plugins/keys/index.ts +2 -18
- package/plugins/mcp/index.ts +40 -12
- package/plugins/mcp/install.ts +139 -0
- package/plugins/mcp/mcp.ts +2 -1
- package/plugins/mcp/plugin.json +1 -1
- package/plugins/mcp/project.ts +37 -1
- package/plugins/memory/index.ts +4 -9
- package/plugins/memory/plugin.json +1 -1
- package/plugins/mentions/index.ts +33 -13
- package/plugins/models/configure.ts +258 -150
- package/plugins/models/context.ts +2 -2
- package/plugins/models/index.ts +50 -42
- package/plugins/models/plugin.json +1 -1
- package/plugins/models/provider.ts +22 -4
- package/plugins/models/saved.ts +8 -4
- package/plugins/modes/index.ts +2 -17
- package/plugins/plugins/index.ts +2 -2
- package/plugins/print/index.ts +60 -12
- package/plugins/print/plugin.json +1 -0
- package/plugins/prompts/index.ts +50 -14
- package/plugins/{memory → prompts}/notes.ts +21 -9
- package/plugins/prompts/plugin.json +8 -2
- package/plugins/prompts/prompts.ts +14 -8
- package/plugins/prompts/results.ts +63 -0
- package/plugins/prompts/sys.ts +16 -4
- package/plugins/renderers/index.ts +2 -43
- package/plugins/repeats/index.ts +1 -1
- package/plugins/schedule/index.ts +2 -2
- package/plugins/scratch/index.ts +2 -3
- package/plugins/screenshot/index.ts +26 -13
- package/plugins/screenshot/plugin.json +1 -1
- package/plugins/sessions/index.ts +2 -17
- package/plugins/shell/index.ts +56 -6
- package/plugins/shell/plugin.json +3 -1
- package/plugins/shell/renderers.ts +1 -1
- package/plugins/shell/service.ts +2 -13
- package/plugins/shell/shell.ts +31 -16
- package/plugins/skills/index.ts +172 -37
- package/plugins/skills/install.ts +212 -0
- package/plugins/skills/plugin.json +3 -2
- package/plugins/skills/project.ts +38 -1
- package/plugins/skills/skills.ts +28 -9
- package/plugins/steer/index.ts +142 -0
- package/plugins/steer/plugin.json +8 -0
- package/plugins/suggest/index.ts +16 -11
- package/plugins/suggest/plugin.json +1 -1
- package/plugins/task/index.ts +8 -16
- package/plugins/task/plugin.json +9 -2
- package/plugins/task/subagent.ts +119 -15
- package/plugins/todo/index.ts +4 -4
- package/plugins/tui/editor.ts +10 -2
- package/plugins/tui/frontend.ts +130 -25
- package/plugins/tui/index.ts +3 -8
- package/plugins/tui/markdown.ts +51 -6
- package/plugins/tui/mascot.ts +505 -0
- package/plugins/tui/mentions.ts +48 -8
- package/plugins/tui/plugin.json +2 -2
- package/plugins/tui/screen.ts +6 -0
- package/plugins/tui/transcript.ts +22 -3
- package/plugins/tui/tui.ts +323 -95
- package/plugins/tui/vendor.ts +16 -0
- package/plugins/undo/checkpoint.ts +26 -2
- package/plugins/undo/index.ts +86 -24
- package/plugins/undo/plugin.json +8 -2
- package/plugins/undo/snapshot.ts +129 -0
- package/plugins/update/index.ts +11 -15
- package/plugins/update/plugin.json +2 -1
- package/plugins/web/index.ts +2 -5
- package/plugins/web/renderers.ts +1 -1
- package/plugins/web/web.ts +6 -5
- package/plugins-dist/approval/index.js +232 -50
- package/plugins-dist/approval/plugin.json +5 -1
- package/plugins-dist/approval/policy.js +27 -5
- package/plugins-dist/ask/index.js +1 -1
- package/plugins-dist/budget/index.js +1 -1
- package/plugins-dist/checks/checks.js +2 -1
- package/plugins-dist/checks/index.js +1 -1
- package/plugins-dist/commands/index.js +1 -1
- package/plugins-dist/compact/compact.js +13 -2
- package/plugins-dist/compact/index.js +12 -8
- package/plugins-dist/continue/index.js +1 -1
- package/plugins-dist/cost/index.js +135 -0
- package/plugins-dist/cost/plugin.json +16 -0
- package/plugins-dist/custom-commands/index.js +86 -0
- package/plugins-dist/custom-commands/plugin.json +12 -0
- package/plugins-dist/editor/index.js +89 -0
- package/plugins-dist/editor/plugin.json +21 -0
- package/plugins-dist/fs/fs.js +106 -17
- package/plugins-dist/fs/grep.js +40 -12
- package/plugins-dist/fs/index.js +8 -5
- package/plugins-dist/hooks/index.js +145 -0
- package/plugins-dist/hooks/plugin.json +19 -0
- package/plugins-dist/keys/index.js +1 -1
- package/plugins-dist/mcp/index.js +41 -9
- package/plugins-dist/mcp/install.js +160 -0
- package/plugins-dist/mcp/mcp.js +2 -1
- package/plugins-dist/mcp/plugin.json +2 -1
- package/plugins-dist/mcp/project.js +42 -1
- package/plugins-dist/memory/index.js +3 -5
- package/plugins-dist/memory/plugin.json +1 -1
- package/plugins-dist/mentions/index.js +29 -11
- package/plugins-dist/models/configure.js +252 -151
- package/plugins-dist/models/context.js +2 -2
- package/plugins-dist/models/index.js +53 -16
- package/plugins-dist/models/plugin.json +1 -1
- package/plugins-dist/models/provider.js +4 -2
- package/plugins-dist/models/saved.js +9 -4
- package/plugins-dist/modes/index.js +1 -1
- package/plugins-dist/plugins/index.js +1 -1
- package/plugins-dist/print/index.js +62 -9
- package/plugins-dist/print/plugin.json +3 -0
- package/plugins-dist/prompts/index.js +49 -2
- package/plugins-dist/{memory → prompts}/notes.js +10 -7
- package/plugins-dist/prompts/plugin.json +8 -2
- package/plugins-dist/prompts/prompts.js +13 -8
- package/plugins-dist/prompts/results.js +60 -0
- package/plugins-dist/prompts/sys.js +15 -3
- package/plugins-dist/renderers/index.js +1 -1
- package/plugins-dist/repeats/index.js +1 -1
- package/plugins-dist/schedule/index.js +1 -1
- package/plugins-dist/scratch/index.js +1 -1
- package/plugins-dist/screenshot/index.js +25 -11
- package/plugins-dist/screenshot/plugin.json +1 -1
- package/plugins-dist/sessions/index.js +1 -1
- package/plugins-dist/shell/index.js +55 -3
- package/plugins-dist/shell/plugin.json +3 -1
- package/plugins-dist/shell/shell.js +26 -8
- package/plugins-dist/skills/index.js +184 -35
- package/plugins-dist/skills/install.js +178 -0
- package/plugins-dist/skills/plugin.json +6 -2
- package/plugins-dist/skills/project.js +43 -1
- package/plugins-dist/skills/skills.js +27 -10
- package/plugins-dist/steer/index.js +135 -0
- package/plugins-dist/steer/plugin.json +12 -0
- package/plugins-dist/suggest/index.js +15 -9
- package/plugins-dist/suggest/plugin.json +1 -1
- package/plugins-dist/task/index.js +7 -4
- package/plugins-dist/task/plugin.json +10 -2
- package/plugins-dist/task/subagent.js +106 -15
- package/plugins-dist/todo/index.js +3 -3
- package/plugins-dist/tui/editor.js +7 -2
- package/plugins-dist/tui/frontend.js +135 -18
- package/plugins-dist/tui/index.js +2 -1
- package/plugins-dist/tui/markdown.js +48 -6
- package/plugins-dist/tui/mascot.js +439 -0
- package/plugins-dist/tui/mentions.js +44 -6
- package/plugins-dist/tui/plugin.json +3 -2
- package/plugins-dist/tui/screen.js +2 -0
- package/plugins-dist/tui/transcript.js +19 -2
- package/plugins-dist/tui/tui.js +303 -83
- package/plugins-dist/tui/vendor.js +13822 -0
- package/plugins-dist/undo/checkpoint.js +28 -1
- package/plugins-dist/undo/index.js +92 -22
- package/plugins-dist/undo/plugin.json +10 -3
- package/plugins-dist/undo/snapshot.js +111 -0
- package/plugins-dist/update/index.js +9 -10
- package/plugins-dist/update/plugin.json +4 -1
- package/plugins-dist/web/index.js +1 -1
- package/plugins-dist/web/web.js +6 -5
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/sdk/python/jade_plugin.py +8 -0
- package/src/api.ts +7 -262
- package/src/fetch.ts +18 -16
- package/src/host.ts +49 -1
- package/src/index.ts +1 -1
- package/src/main.ts +25 -6
- package/src/remote.ts +2 -0
- package/src/session.ts +134 -15
- package/src/source.ts +2 -11
- package/src/update.ts +16 -10
- package/plugins/undo/notes.ts +0 -43
- package/plugins-dist/undo/notes.js +0 -36
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// 模型的上下文窗口(最大输入 token 数)。前端显示上下文用量,以后的 jade/compact 据此决定什么时候压缩。
|
|
2
2
|
//
|
|
3
|
-
// 窗口优先取 JADE_CONTEXT_WINDOW;不设时按模型名在一张小表里找(只收录确定的、取偏小的值),找不到用
|
|
3
|
+
// 窗口优先取 JADE_CONTEXT_WINDOW;不设时按模型名在一张小表里找(只收录确定的、取偏小的值),找不到用 256000。
|
|
4
4
|
import { parseTokens } from "./config.js";
|
|
5
5
|
/** 认不出模型时的窗口 */
|
|
6
|
-
export const DEFAULT_CONTEXT_WINDOW =
|
|
6
|
+
export const DEFAULT_CONTEXT_WINDOW = 256_000;
|
|
7
7
|
/** 模型名(不区分大小写,可以带 "anthropic/" 这类前缀)→ 窗口;按顺序取第一个匹配的 */
|
|
8
8
|
const KNOWN_WINDOWS = [
|
|
9
9
|
[/claude/i, 200_000],
|
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
// /model 改了配置之后不用重开会话:provider@1 给核心的是一个转发到当前 provider 的壳(设计第 10 节),
|
|
5
5
|
// 下一次请求就用新的。
|
|
6
6
|
import path from "node:path";
|
|
7
|
-
import { definePlugin } from "
|
|
7
|
+
import { definePlugin } from "@uncarved/jade-api";
|
|
8
8
|
import { contextWindow } from "./context.js";
|
|
9
|
-
import { envWithFile, hasProvider } from "./config.js";
|
|
9
|
+
import { envWithFile, hasProvider, parseTokens } from "./config.js";
|
|
10
10
|
import { configurator } from "./configure.js";
|
|
11
11
|
import { isBuiltinKind, listModels, MODEL_KEY, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, visionFromEnv, withRetry } from "./provider.js";
|
|
12
|
-
import { readSavedServices } from "./saved.js";
|
|
12
|
+
import { MODEL_SETTINGS, readSavedServices } from "./saved.js";
|
|
13
13
|
export default definePlugin({
|
|
14
14
|
async process(ctx) {
|
|
15
15
|
const envFile = path.join(ctx.home, ".env");
|
|
@@ -60,27 +60,38 @@ export default definePlugin({
|
|
|
60
60
|
};
|
|
61
61
|
/** 保存过的模型的 provider,按配置缓存:models.json 里的密钥或设置改了就另建一份 */
|
|
62
62
|
const savedProviders = new Map();
|
|
63
|
+
const cachedBuild = (snapshot) => {
|
|
64
|
+
const key = JSON.stringify(snapshot);
|
|
65
|
+
const cached = savedProviders.get(key);
|
|
66
|
+
if (cached)
|
|
67
|
+
return cached;
|
|
68
|
+
const p = build(snapshot);
|
|
69
|
+
savedProviders.set(key, p);
|
|
70
|
+
// 创建失败时下次重试
|
|
71
|
+
p.catch(() => savedProviders.delete(key));
|
|
72
|
+
return p;
|
|
73
|
+
};
|
|
63
74
|
const saved = async (name) => {
|
|
64
75
|
for (const s of await readSavedServices(modelsFile)) {
|
|
65
76
|
const m = s.models.find((x) => x.name === name);
|
|
66
77
|
const kind = providerKind(s.env);
|
|
67
78
|
if (!m || !isBuiltinKind(kind))
|
|
68
79
|
continue;
|
|
69
|
-
|
|
70
|
-
const key = JSON.stringify(snapshot);
|
|
71
|
-
const cached = savedProviders.get(key);
|
|
72
|
-
if (cached)
|
|
73
|
-
return cached;
|
|
74
|
-
const p = build(snapshot);
|
|
75
|
-
savedProviders.set(key, p);
|
|
76
|
-
// 创建失败时下次重试
|
|
77
|
-
p.catch(() => savedProviders.delete(key));
|
|
78
|
-
return p;
|
|
80
|
+
return cachedBuild({ ...s.env, ...m.settings, JADE_PROVIDER: kind, [MODEL_KEY[kind]]: m.name });
|
|
79
81
|
}
|
|
82
|
+
if (!hasProvider(env))
|
|
83
|
+
throw notConfigured();
|
|
80
84
|
// 只写在 .env 里、没保存过的当前模型
|
|
81
|
-
if (
|
|
85
|
+
if (providerInfo(env).model === name)
|
|
82
86
|
return provider();
|
|
83
|
-
|
|
87
|
+
// 当前服务上的另一个模型(没保存过):用这个服务的地址和密钥,不带当前模型自己的设置,用服务的默认值
|
|
88
|
+
const kind = providerKind(env);
|
|
89
|
+
if (!isBuiltinKind(kind))
|
|
90
|
+
throw new Error(`model ${JSON.stringify(name)} is not one of the models saved by /model (${modelsFile})`);
|
|
91
|
+
const snapshot = { ...env, JADE_PROVIDER: kind, [MODEL_KEY[kind]]: name };
|
|
92
|
+
for (const k of MODEL_SETTINGS)
|
|
93
|
+
delete snapshot[k];
|
|
94
|
+
return cachedBuild(snapshot);
|
|
84
95
|
};
|
|
85
96
|
const current = (request, options) => provider().then((p) => p.complete(request, options));
|
|
86
97
|
const complete = (request, { model, ...options }) => (model ? saved(model).then((p) => p.complete(request, options)) : current(request, options));
|
|
@@ -99,7 +110,21 @@ export default definePlugin({
|
|
|
99
110
|
// 写错的 JADE_VISION 在创建 provider 时报错,这里当作不能看
|
|
100
111
|
vision = false;
|
|
101
112
|
}
|
|
102
|
-
|
|
113
|
+
let maxTokens;
|
|
114
|
+
try {
|
|
115
|
+
maxTokens = env.JADE_MAX_TOKENS ? parseTokens("JADE_MAX_TOKENS", env.JADE_MAX_TOKENS) : undefined;
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
// 写错的在创建 provider 时报错
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
kind: info.kind,
|
|
122
|
+
model: info.model,
|
|
123
|
+
via: via(info.kind, info.baseURL),
|
|
124
|
+
contextWindow: contextWindow(info.model, env),
|
|
125
|
+
vision,
|
|
126
|
+
...(maxTokens === undefined ? {} : { maxTokens }),
|
|
127
|
+
};
|
|
103
128
|
},
|
|
104
129
|
complete,
|
|
105
130
|
list: () => listModels(env),
|
|
@@ -148,6 +173,18 @@ export default definePlugin({
|
|
|
148
173
|
},
|
|
149
174
|
});
|
|
150
175
|
},
|
|
176
|
+
session(ctx) {
|
|
177
|
+
// 重试过的请求:把每次失败写进会话日志,事后能查到为什么慢、为什么重新输出(插件事件,不进上下文)
|
|
178
|
+
ctx.kernel.hook({
|
|
179
|
+
kind: "observe",
|
|
180
|
+
point: "model.after",
|
|
181
|
+
fn: async (res, hook) => {
|
|
182
|
+
const retries = res.retries;
|
|
183
|
+
if (retries?.length)
|
|
184
|
+
await hook.emit("retried", { retries });
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
},
|
|
151
188
|
});
|
|
152
189
|
function via(kind, baseURL) {
|
|
153
190
|
const host = baseURL ? safeHost(baseURL) : undefined;
|
|
@@ -19,6 +19,7 @@ export function withRetry(inner, opts = {}) {
|
|
|
19
19
|
return {
|
|
20
20
|
id: `retry(${inner.id})`,
|
|
21
21
|
async complete(request, options) {
|
|
22
|
+
const failures = [];
|
|
22
23
|
for (let attempt = 1;; attempt++) {
|
|
23
24
|
let streamed = false;
|
|
24
25
|
await opts.gate?.acquire(options.signal);
|
|
@@ -32,7 +33,7 @@ export function withRetry(inner, opts = {}) {
|
|
|
32
33
|
},
|
|
33
34
|
});
|
|
34
35
|
// 实际回复的是被包装者(4.7 第 3 款)
|
|
35
|
-
return { ...res, provider: res.provider ?? inner.id };
|
|
36
|
+
return { ...res, provider: res.provider ?? inner.id, ...(failures.length > 0 ? { retries: failures } : {}) };
|
|
36
37
|
}
|
|
37
38
|
catch (err) {
|
|
38
39
|
if (!(err instanceof ProviderError) || !err.retryable || attempt > retries || options.signal.aborted)
|
|
@@ -48,6 +49,7 @@ export function withRetry(inner, opts = {}) {
|
|
|
48
49
|
// 失败的这次已经推送过增量的,先让订阅者作废它们(4.7)
|
|
49
50
|
if (streamed)
|
|
50
51
|
options.onDelta?.({ kind: "reset" });
|
|
52
|
+
failures.push({ attempt, delayMs, error: err.message, ...(err.status !== undefined ? { status: err.status } : {}), ...(streamed ? { discarded: true } : {}) });
|
|
51
53
|
opts.onRetry?.({ attempt, retries, delayMs, error: err });
|
|
52
54
|
await sleep(delayMs, options.signal);
|
|
53
55
|
}
|
|
@@ -319,7 +321,7 @@ export async function listModels(env = process.env, fetchImpl = fetch) {
|
|
|
319
321
|
return [];
|
|
320
322
|
}
|
|
321
323
|
}
|
|
322
|
-
function jsonObject(name, text) {
|
|
324
|
+
export function jsonObject(name, text) {
|
|
323
325
|
let value;
|
|
324
326
|
try {
|
|
325
327
|
value = JSON.parse(text);
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// 保存过的模型:$JADE_HOME/models.json。同一个服务(类型、地址、密钥都相同)只存一份,下面是在它上面用过的模型,
|
|
2
|
-
//
|
|
2
|
+
// 每个模型带自己的设置(输出上限、思考力度、上下文窗口、openai-compat 的额外请求参数等)。.env 里始终是当前用的那一个,这里记着用过的全部,
|
|
3
3
|
// /model 可以切回去。
|
|
4
4
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
/** 每个模型自己的设置:切换模型时一起换掉 */
|
|
7
|
-
export const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW", "JADE_RPM", "JADE_VISION"];
|
|
7
|
+
export const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW", "JADE_RPM", "JADE_VISION", "OPENAI_COMPAT_EXTRA_BODY"];
|
|
8
8
|
const strings = (v) => typeof v === "object" && v !== null ? Object.fromEntries(Object.entries(v).filter(([, x]) => typeof x === "string")) : {};
|
|
9
9
|
/** 读不了或格式不对时返回空数组 */
|
|
10
10
|
export async function readSavedServices(file) {
|
|
@@ -16,11 +16,16 @@ export async function readSavedServices(file) {
|
|
|
16
16
|
const s = raw;
|
|
17
17
|
if (!s || !Array.isArray(s.models))
|
|
18
18
|
return [];
|
|
19
|
+
// 以前额外请求参数存在服务上:分给它下面没有自己那份的模型
|
|
20
|
+
const { OPENAI_COMPAT_EXTRA_BODY: extraBody, ...env } = strings(s.env);
|
|
19
21
|
const models = s.models.flatMap((m) => {
|
|
20
22
|
const name = m?.name;
|
|
21
|
-
|
|
23
|
+
const settings = strings(m.settings);
|
|
24
|
+
if (extraBody && settings.OPENAI_COMPAT_EXTRA_BODY === undefined)
|
|
25
|
+
settings.OPENAI_COMPAT_EXTRA_BODY = extraBody;
|
|
26
|
+
return typeof name === "string" && name ? [{ name, settings }] : [];
|
|
22
27
|
});
|
|
23
|
-
return models.length ? [{ env
|
|
28
|
+
return models.length ? [{ env, models }] : [];
|
|
24
29
|
});
|
|
25
30
|
}
|
|
26
31
|
catch {
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// 用户的选择在工具结果里,会话日志里看得到
|
|
9
9
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
10
|
import path from "node:path";
|
|
11
|
-
import { definePlugin } from "
|
|
11
|
+
import { definePlugin } from "@uncarved/jade-api";
|
|
12
12
|
export const DESCRIPTIONS = {
|
|
13
13
|
ask: "ask before edits and commands",
|
|
14
14
|
auto: "edits in this directory and harmless commands run without asking; others still ask",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// jade/plugins:/plugins 命令。列出这次启动里每个插件的状态和原因(failed、skipped、conflicted……),
|
|
2
2
|
// 以及每个服务由谁提供。数据来自核心自己的 jade@1 服务,和救援 CLI `jade plugins list` 是同一份状态。
|
|
3
|
-
import { definePlugin } from "
|
|
3
|
+
import { definePlugin } from "@uncarved/jade-api";
|
|
4
4
|
export default definePlugin({
|
|
5
5
|
process(ctx) {
|
|
6
6
|
const commands = ctx.require("commands@1");
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
// jade/print:jade -p "<prompt>" 跑一轮就退出。模型的回复写到 stdout,工具调用和提示写到 stderr。
|
|
2
2
|
// 不能向用户提问:ui@1 的 select 总是返回 undefined,要审批的调用由审批插件拒绝。
|
|
3
|
-
import { definePlugin } from "
|
|
4
|
-
const USAGE = `usage: jade -p <prompt> [--resume <session id>]
|
|
3
|
+
import { definePlugin } from "@uncarved/jade-api";
|
|
4
|
+
const USAGE = `usage: jade -p <prompt> [--resume <session id> | --continue] [--json]
|
|
5
5
|
echo <prompt> | jade -p
|
|
6
|
+
cat <file> | jade -p - <prompt>
|
|
7
|
+
|
|
8
|
+
With "-", what comes in on stdin is added after the prompt (without a prompt, stdin is the prompt).
|
|
6
9
|
|
|
7
10
|
Runs one prompt and exits. The reply goes to stdout; tool calls and notices go to stderr.
|
|
8
|
-
|
|
11
|
+
-c, --continue continues the most recent session in this directory.
|
|
12
|
+
--json prints one JSON object on stdout instead of the reply as it is written:
|
|
13
|
+
{"session", "result" (the final reply), "reason" (why the turn ended), "error"?, "usage"}
|
|
14
|
+
Exit code: 0 when the turn ends normally, 1 on an error, 130 when interrupted.
|
|
15
|
+
jade's own commands (plugins, update, --safe): jade help`;
|
|
9
16
|
const ui = {
|
|
10
17
|
interactive: false,
|
|
11
18
|
notify(message, level = "info") {
|
|
@@ -14,6 +21,8 @@ const ui = {
|
|
|
14
21
|
select: async () => undefined,
|
|
15
22
|
input: async () => undefined,
|
|
16
23
|
};
|
|
24
|
+
/** --continue 用:process() 里记下的工作目录和会话索引(jade/sessions 的 sessions@1,用到的时候取) */
|
|
25
|
+
let here;
|
|
17
26
|
const frontend = {
|
|
18
27
|
async run({ argv, sessions }) {
|
|
19
28
|
const args = parse(argv);
|
|
@@ -25,15 +34,38 @@ const frontend = {
|
|
|
25
34
|
process.stdout.write(`${USAGE}\n`);
|
|
26
35
|
return 0;
|
|
27
36
|
}
|
|
28
|
-
|
|
37
|
+
// 有 prompt 参数时只在写了 "-" 时读 stdin:脚本启动 jade -p 时 stdin 常是没人关的管道,默认去读会一直等下去
|
|
38
|
+
const piped = args.stdin || (args.prompt === undefined && !process.stdin.isTTY) ? (await readStdin()).trim() : "";
|
|
39
|
+
const prompt = [args.prompt, piped].filter(Boolean).join("\n\n");
|
|
29
40
|
if (!prompt) {
|
|
30
41
|
process.stderr.write(`no prompt given\n\n${USAGE}\n`);
|
|
31
42
|
return 2;
|
|
32
43
|
}
|
|
33
|
-
|
|
44
|
+
if (args.cont) {
|
|
45
|
+
const latest = (await here?.index()?.list(here.cwd))?.[0]?.id;
|
|
46
|
+
if (!latest) {
|
|
47
|
+
process.stderr.write("jade: there is no earlier session in this directory to continue\n");
|
|
48
|
+
return 2;
|
|
49
|
+
}
|
|
50
|
+
args.resume = latest;
|
|
51
|
+
}
|
|
52
|
+
let session;
|
|
53
|
+
try {
|
|
54
|
+
session = await sessions.open(args.resume ? { resume: args.resume } : {});
|
|
55
|
+
}
|
|
56
|
+
catch (e) {
|
|
57
|
+
// 例如 --resume 的会话不存在:只说原因,不带插件名的包装
|
|
58
|
+
process.stderr.write(`jade: ${args.resume ? `could not resume ${args.resume}` : "could not start a session"}: ${errorText(e)}\n`);
|
|
59
|
+
return args.resume ? 2 : 1;
|
|
60
|
+
}
|
|
34
61
|
let ended;
|
|
35
62
|
let midLine = false;
|
|
63
|
+
/** --json:回复不边写边打印,最后一次回复的正文和用量合计在结束时一起输出 */
|
|
64
|
+
let result = "";
|
|
65
|
+
const used = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
|
|
36
66
|
const out = (text) => {
|
|
67
|
+
if (args.json)
|
|
68
|
+
return;
|
|
37
69
|
process.stdout.write(text);
|
|
38
70
|
midLine = !text.endsWith("\n");
|
|
39
71
|
};
|
|
@@ -48,7 +80,12 @@ const frontend = {
|
|
|
48
80
|
return;
|
|
49
81
|
const e = n.event;
|
|
50
82
|
if (e.type === "model.responded") {
|
|
51
|
-
const content = e.data
|
|
83
|
+
const { content, usage } = e.data;
|
|
84
|
+
const text = content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n");
|
|
85
|
+
if (text)
|
|
86
|
+
result = text;
|
|
87
|
+
for (const k of Object.keys(used))
|
|
88
|
+
used[k] += usage?.[k] ?? 0;
|
|
52
89
|
if (!streamed)
|
|
53
90
|
for (const b of content)
|
|
54
91
|
if (b.kind === "text")
|
|
@@ -93,12 +130,14 @@ const frontend = {
|
|
|
93
130
|
out("\n");
|
|
94
131
|
process.stderr.write(`session ${session.id}\n`);
|
|
95
132
|
const end = ended;
|
|
133
|
+
if (args.json) {
|
|
134
|
+
const error = failure !== undefined ? errorText(failure) : end?.error;
|
|
135
|
+
process.stdout.write(`${JSON.stringify({ session: session.id, result, reason: end?.reason ?? "error", ...(error ? { error } : {}), usage: used })}\n`);
|
|
136
|
+
}
|
|
96
137
|
if (end?.reason === "aborted")
|
|
97
138
|
return 130;
|
|
98
139
|
if (failure !== undefined || end?.reason === "error") {
|
|
99
|
-
|
|
100
|
-
const cause = failure instanceof Error && failure.cause instanceof Error ? failure.cause : failure;
|
|
101
|
-
process.stderr.write(`error: ${cause instanceof Error ? cause.message : (end?.error ?? String(cause ?? "the turn failed"))}\n`);
|
|
140
|
+
process.stderr.write(`error: ${failure !== undefined ? errorText(failure) : (end?.error ?? "the turn failed")}\n`);
|
|
102
141
|
return 1;
|
|
103
142
|
}
|
|
104
143
|
return 0;
|
|
@@ -106,6 +145,7 @@ const frontend = {
|
|
|
106
145
|
};
|
|
107
146
|
export default definePlugin({
|
|
108
147
|
process(ctx) {
|
|
148
|
+
here = { cwd: ctx.cwd, index: () => ctx.service("sessions@1") };
|
|
109
149
|
ctx.provide("ui@1", ui);
|
|
110
150
|
ctx.provide("frontend@1", frontend);
|
|
111
151
|
},
|
|
@@ -119,6 +159,12 @@ function parse(argv) {
|
|
|
119
159
|
continue;
|
|
120
160
|
if (a === "-h" || a === "--help")
|
|
121
161
|
out.help = true;
|
|
162
|
+
else if (a === "-")
|
|
163
|
+
out.stdin = true;
|
|
164
|
+
else if (a === "-c" || a === "--continue")
|
|
165
|
+
out.cont = true;
|
|
166
|
+
else if (a === "--json")
|
|
167
|
+
out.json = true;
|
|
122
168
|
else if (a === "--resume") {
|
|
123
169
|
const id = argv[++i];
|
|
124
170
|
if (!id)
|
|
@@ -130,6 +176,8 @@ function parse(argv) {
|
|
|
130
176
|
else
|
|
131
177
|
words.push(a);
|
|
132
178
|
}
|
|
179
|
+
if (out.cont && out.resume)
|
|
180
|
+
return "--continue and --resume both pick the session; use one of them";
|
|
133
181
|
if (words.length > 0)
|
|
134
182
|
out.prompt = words.join(" ");
|
|
135
183
|
return out;
|
|
@@ -147,6 +195,11 @@ function summary(input) {
|
|
|
147
195
|
const line = (s ?? "").split("\n")[0];
|
|
148
196
|
return line.length > 120 ? `${line.slice(0, 120)}…` : line;
|
|
149
197
|
}
|
|
198
|
+
/** 经过膜的错误包成了 PluginError,带着插件名;用户要看的是原因 */
|
|
199
|
+
function errorText(e) {
|
|
200
|
+
const cause = e instanceof Error && e.cause instanceof Error ? e.cause : e;
|
|
201
|
+
return cause instanceof Error ? cause.message : String(cause);
|
|
202
|
+
}
|
|
150
203
|
function firstLine(content) {
|
|
151
204
|
const text = content.find((b) => b.kind === "text");
|
|
152
205
|
return text && "text" in text ? text.text.split("\n")[0] : "(no message)";
|
|
@@ -1,10 +1,19 @@
|
|
|
1
1
|
// jade/prompts:在 context.build 里生成系统提示词。其他插件经 prompts@1 往里加段落。
|
|
2
|
+
// 也负责内核不写的、给模型看的说明:内容为空的错误工具结果在投影里补一句原因(results.ts);
|
|
3
|
+
// 其他插件经 prompts@1 的 note 给模型留一句说明(notes.ts)。
|
|
4
|
+
import os from "node:os";
|
|
2
5
|
import path from "node:path";
|
|
3
|
-
import { definePlugin } from "
|
|
6
|
+
import { definePlugin } from "@uncarved/jade-api";
|
|
7
|
+
import { Notes } from "./notes.js";
|
|
4
8
|
import { allInstructions, environment, mainPrompt, realPath } from "./prompts.js";
|
|
9
|
+
import { explainEmptyResults, whyEmpty } from "./results.js";
|
|
5
10
|
const ID = "jade/prompts";
|
|
6
11
|
/** 其他插件加的段落。模块每个进程只加载一次,进程级和会话级共用 */
|
|
7
12
|
const sections = [];
|
|
13
|
+
/** 打开着的会话 → 它读到的指令文件(prompts@1.instructions) */
|
|
14
|
+
const loaded = new Map();
|
|
15
|
+
/** 其他插件留给模型的说明 */
|
|
16
|
+
const notes = new Notes();
|
|
8
17
|
function segment(text, trust = "trusted", stability = "stable", by = ID, source) {
|
|
9
18
|
return { text, stability, origin: { by: "plugin", id: by, ...(source ? { source } : {}) }, trust };
|
|
10
19
|
}
|
|
@@ -30,15 +39,53 @@ export default definePlugin({
|
|
|
30
39
|
caller.onDispose(remove);
|
|
31
40
|
return remove;
|
|
32
41
|
},
|
|
42
|
+
note(session, text) {
|
|
43
|
+
if (typeof session !== "string" || !session)
|
|
44
|
+
throw new Error("prompts.note: session must be a session id");
|
|
45
|
+
if (typeof text !== "string" || !text)
|
|
46
|
+
throw new Error("prompts.note: text must be a non-empty string");
|
|
47
|
+
notes.add(session, { plugin: caller.plugin, text, trusted: caller.layer !== "project" });
|
|
48
|
+
},
|
|
49
|
+
instructions: (session) => (loaded.get(session) ?? []).map((i) => ({ ...i, source: { ...i.source } })),
|
|
33
50
|
}));
|
|
34
51
|
},
|
|
35
52
|
async session(ctx) {
|
|
36
53
|
const models = ctx.service("models@1");
|
|
37
|
-
const [env, instructions] = await Promise.all([environment(ctx.cwd), allInstructions(ctx.home, ctx.cwd)]);
|
|
54
|
+
const [env, instructions] = await Promise.all([environment(ctx.cwd), allInstructions(ctx.home, ctx.cwd, ctx.config.claudeInstructions === false ? null : os.homedir())]);
|
|
55
|
+
loaded.set(ctx.session.id, instructions.map(({ text, trust, source }) => ({ text, trust, source })));
|
|
56
|
+
await ctx.effect(() => () => void loaded.delete(ctx.session.id));
|
|
38
57
|
const fixed = [segment(env), ...instructions.map((i) => segment(i.text, i.trust, "stable", ID, i.source))];
|
|
39
58
|
// 告诉用户读了哪些指令文件,否则看不出它们生效了
|
|
40
59
|
if (instructions.length > 0)
|
|
41
60
|
ctx.service("ui@1")?.notify(`loaded instructions: ${instructions.map((i) => display(realPath(ctx.cwd), i.file)).join(", ")}`);
|
|
61
|
+
// 内容为空的错误工具结果补上说明(results.ts)。原因记在 derived 里;同一批里可能有几个,
|
|
62
|
+
// observe 并发执行、拿到的 derived 快照可能是旧的,所以在这里累积,每次记完整的一份。
|
|
63
|
+
// 运行时不等 observe:紧接着的模型调用投影时记录可能还没落盘,所以投影也看这份累积的。
|
|
64
|
+
// observe 在事件写入时就(以微任务)开始执行,早于之后的投影;下一轮之前记录一定已落盘,恢复会话时从 derived 读,
|
|
65
|
+
// 所以投影只取决于日志,每次相同
|
|
66
|
+
const reasonsKey = `${ID}/empty-results`;
|
|
67
|
+
let reasons;
|
|
68
|
+
ctx.kernel.hook({
|
|
69
|
+
kind: "observe",
|
|
70
|
+
point: "event",
|
|
71
|
+
fn: async (e, hook) => {
|
|
72
|
+
const found = whyEmpty(e);
|
|
73
|
+
if (!found)
|
|
74
|
+
return;
|
|
75
|
+
reasons ??= { ...(hook.derived[reasonsKey] ?? {}) };
|
|
76
|
+
reasons[found.toolUseId] = found.why;
|
|
77
|
+
await hook.record(reasonsKey, { ...reasons });
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
ctx.kernel.hook({
|
|
81
|
+
kind: "transform",
|
|
82
|
+
point: "context.project",
|
|
83
|
+
// 出错时跳过(不补说明),不让这一轮失败
|
|
84
|
+
optional: true,
|
|
85
|
+
fn: (messages, hook) => explainEmptyResults(messages, { ...hook.derived[reasonsKey], ...reasons }, ID),
|
|
86
|
+
});
|
|
87
|
+
ctx.kernel.hook(notes.hook(ctx.session.id, `${ID}/notes`));
|
|
88
|
+
await ctx.effect(() => () => notes.drop(ctx.session.id));
|
|
42
89
|
ctx.kernel.hook({
|
|
43
90
|
kind: "transform",
|
|
44
91
|
point: "context.build",
|
|
@@ -1,15 +1,18 @@
|
|
|
1
|
-
// 给模型的说明([Note from jade]
|
|
2
|
-
//
|
|
1
|
+
// 给模型的说明([Note from jade],prompts@1 的 note):命令里做的事(例如用户删掉了一条记忆、撤销了模型改的文件)
|
|
2
|
+
// 要让模型知道,但命令拿不到会话日志,也不该替用户发一条消息。所以先记下来,下一次请求模型时在 context.project 里
|
|
3
3
|
// 附在最后一条消息后面,并用 ctx.record 写进日志(derived):之后的投影、恢复的会话里它都在同一个位置。
|
|
4
|
-
// 插件之间不共享代码,jade/undo 里也有一份。
|
|
5
4
|
export class Notes {
|
|
6
5
|
/** 会话 → 还没交给模型的说明 */
|
|
7
6
|
#pending = new Map();
|
|
8
|
-
add(sessionId,
|
|
9
|
-
this.#pending.set(sessionId, [...(this.#pending.get(sessionId) ?? []),
|
|
7
|
+
add(sessionId, note) {
|
|
8
|
+
this.#pending.set(sessionId, [...(this.#pending.get(sessionId) ?? []), note]);
|
|
9
|
+
}
|
|
10
|
+
/** 会话关闭:还没交给模型的说明不再留着 */
|
|
11
|
+
drop(sessionId) {
|
|
12
|
+
this.#pending.delete(sessionId);
|
|
10
13
|
}
|
|
11
14
|
/** 会话里的 context.project hook;key 是 derived 里的键 */
|
|
12
|
-
hook(sessionId,
|
|
15
|
+
hook(sessionId, key) {
|
|
13
16
|
return {
|
|
14
17
|
kind: "transform",
|
|
15
18
|
point: "context.project",
|
|
@@ -27,7 +30,7 @@ export class Notes {
|
|
|
27
30
|
const notes = state[i];
|
|
28
31
|
if (!notes?.length || m.role !== "user")
|
|
29
32
|
return m;
|
|
30
|
-
const blocks = notes.map((
|
|
33
|
+
const blocks = notes.map((n) => ({ kind: "text", text: `[Note from jade] ${n.text}`, origin: { by: "plugin", id: n.plugin }, trust: n.trusted ? "trusted" : "untrusted" }));
|
|
31
34
|
return { ...m, content: [...m.content, ...blocks] };
|
|
32
35
|
});
|
|
33
36
|
},
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "jade/prompts",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"api": "^1",
|
|
5
5
|
"entry": "./index.js",
|
|
6
6
|
"provides": [
|
|
@@ -9,5 +9,11 @@
|
|
|
9
9
|
"optional": [
|
|
10
10
|
"models@1",
|
|
11
11
|
"ui@1"
|
|
12
|
-
]
|
|
12
|
+
],
|
|
13
|
+
"config": {
|
|
14
|
+
"claudeInstructions": {
|
|
15
|
+
"default": true,
|
|
16
|
+
"description": "when $JADE_HOME has no AGENTS.md or CLAUDE.md, use ~/.claude/CLAUDE.md as the user instructions; false turns this off"
|
|
17
|
+
}
|
|
18
|
+
}
|
|
13
19
|
}
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
// 主体和环境信息都是 stable:环境信息在会话开始时取一次,不在每次请求时更新,
|
|
4
4
|
// 否则它一变,排在后面的整段历史都无法命中提示缓存。
|
|
5
5
|
// 指令文件兼容 AGENTS.md 和 CLAUDE.md,同一目录两者都有时只读 AGENTS.md。
|
|
6
|
-
//
|
|
6
|
+
// 用户层的先找 $JADE_HOME,没有时用 ~/.claude 里的(和 jade/skills 读 ~/.claude/skills 一样,已有的全局指令不用再抄一份)。
|
|
7
|
+
// 用户层的是 trusted;项目层(随仓库分发)的是 untrusted,并记下出处(宪法 7.2)。
|
|
7
8
|
// 项目层从仓库根目录到工作目录逐级查找,上级的在前,离工作目录近的在后。
|
|
8
9
|
import { createHash } from "node:crypto";
|
|
9
10
|
import { realpathSync } from "node:fs";
|
|
@@ -71,7 +72,8 @@ export async function environment(cwd, today = localDate()) {
|
|
|
71
72
|
const [branch, status, entries] = await gitSnapshot(cwd);
|
|
72
73
|
if (branch) {
|
|
73
74
|
lines.push(`- Git branch: ${branch}`);
|
|
74
|
-
|
|
75
|
+
const shown = status === undefined ? "unknown (git status did not finish)" : status ? `\n${status.split("\n").slice(0, 30).join("\n")}` : "clean";
|
|
76
|
+
lines.push(`- Git status at session start: ${shown}`);
|
|
75
77
|
}
|
|
76
78
|
else {
|
|
77
79
|
lines.push("- Not a git repository");
|
|
@@ -83,10 +85,10 @@ export async function environment(cwd, today = localDate()) {
|
|
|
83
85
|
}
|
|
84
86
|
return lines.join("\n");
|
|
85
87
|
}
|
|
86
|
-
/** 用户层(home
|
|
87
|
-
export async function allInstructions(home, cwd) {
|
|
88
|
+
/** 用户层(home 里,没有时 userHome/.claude 里;userHome 给 null 时不找)和项目层(仓库根目录到 cwd 逐级)的指令文件,按顺序 */
|
|
89
|
+
export async function allInstructions(home, cwd, userHome = os.homedir()) {
|
|
88
90
|
const out = [];
|
|
89
|
-
const user = await instructions(home, home, "user");
|
|
91
|
+
const user = (await instructions(home, home, "user")) ?? (userHome === null ? undefined : await instructions(userHome, path.join(userHome, ".claude"), "user"));
|
|
90
92
|
if (user)
|
|
91
93
|
out.push({ text: `# User instructions (${user.source.path})\n\n${user.text}`, trust: "trusted", source: user.source, file: user.file });
|
|
92
94
|
const root = realPath(await repoRoot(cwd));
|
|
@@ -153,7 +155,8 @@ function gitSnapshot(cwd) {
|
|
|
153
155
|
// 三个 git 命令同时跑:Windows 上每启动一次 git 要几十毫秒,启动时会串起来等
|
|
154
156
|
p = Promise.all([
|
|
155
157
|
git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]),
|
|
156
|
-
git
|
|
158
|
+
// 巨型仓库里 git status 可能要很久,会话打开要等它:超时就不给
|
|
159
|
+
git(cwd, ["status", "--short"], STATUS_TIMEOUT_MS),
|
|
157
160
|
// 让模型一开始就知道仓库的大致样子,不用先盲猜语言、到处 ls
|
|
158
161
|
topLevel(cwd),
|
|
159
162
|
]);
|
|
@@ -212,9 +215,11 @@ export function repoRoot(cwd) {
|
|
|
212
215
|
}
|
|
213
216
|
return p;
|
|
214
217
|
}
|
|
215
|
-
|
|
218
|
+
/** 会话开始时 git status 最多等这么久 */
|
|
219
|
+
const STATUS_TIMEOUT_MS = 3000;
|
|
220
|
+
async function git(cwd, args, timeoutMs) {
|
|
216
221
|
try {
|
|
217
|
-
const { code, stdout } = await run(["git", ...args], { cwd });
|
|
222
|
+
const { code, stdout } = await run(["git", ...args], timeoutMs === undefined ? { cwd } : { cwd, timeoutMs });
|
|
218
223
|
return code === 0 ? stdout.trim() : undefined;
|
|
219
224
|
}
|
|
220
225
|
catch {
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// 内容为空的错误工具结果:内核不写说明文字(I-1),模型只看到 is_error,分不清是工具名写错、没执行还是被拒绝,
|
|
2
|
+
// 容易原样重试。这里在投影里按原因补一句说明(I-4:只改投影,不改日志)。
|
|
3
|
+
//
|
|
4
|
+
// 空结果有四种来源,块本身只能分出最后一种(origin 不是 runtime):
|
|
5
|
+
// - 调用了不存在的工具:运行时直接拒绝(tool.decided 没有 reason,也没有 decidedBy)
|
|
6
|
+
// - 崩溃恢复时,执行到一半的非幂等工具记为 tool.interrupted
|
|
7
|
+
// - 这一轮先结束了(用户中断、出错、输出被截断),没有结果的调用由内核补成空的错误结果
|
|
8
|
+
// - 关卡拒绝但没给原因(例如关卡 hook 出错或超时,按拒绝处理;tool.decided 有 decidedBy)
|
|
9
|
+
// tool.decided 的 origin 一律是 runtime,分不出前一种和最后一种,要看 decidedBy(与内核 step.ts 的判断相同)。
|
|
10
|
+
// 前两种只有日志事件分得出来,由 observe 记进 derived,投影时按它说明;恢复会话后同样成立,
|
|
11
|
+
// 投影也只取决于日志,每次算出的结果相同,不破坏提示缓存。
|
|
12
|
+
/** 从事件判断空结果的原因;不是这两种返回 undefined */
|
|
13
|
+
export function whyEmpty(e) {
|
|
14
|
+
if (e.type === "tool.decided") {
|
|
15
|
+
const d = e.data;
|
|
16
|
+
if (d.decision === "deny" && !d.reason && d.decidedBy === undefined)
|
|
17
|
+
return { toolUseId: d.toolUseId, why: "unknown-tool" };
|
|
18
|
+
}
|
|
19
|
+
if (e.type === "tool.interrupted")
|
|
20
|
+
return { toolUseId: e.data.toolUseId, why: "interrupted" };
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
function explanation(why, origin, name) {
|
|
24
|
+
if (why === "unknown-tool") {
|
|
25
|
+
return `There is no tool named ${JSON.stringify(name ?? "")}; the call was not run. Use only the tools you were given.`;
|
|
26
|
+
}
|
|
27
|
+
if (why === "interrupted") {
|
|
28
|
+
return "This call was interrupted while it was running (jade stopped before it finished), so it may have partly taken effect. Check its effects before running it again.";
|
|
29
|
+
}
|
|
30
|
+
if (origin.by === "runtime") {
|
|
31
|
+
return "This call has no result: the turn ended before it finished (the user interrupted, an error occurred, or the response was cut off). It may not have run, or may have stopped partway; check its effects before relying on them or running it again.";
|
|
32
|
+
}
|
|
33
|
+
if (origin.by === "user")
|
|
34
|
+
return "The user declined this call.";
|
|
35
|
+
return "This call was blocked by a check in jade, which gave no reason. Do not retry it unchanged.";
|
|
36
|
+
}
|
|
37
|
+
/** 给内容为空的错误工具结果补上说明;没有要补的时候原样返回 */
|
|
38
|
+
export function explainEmptyResults(messages, reasons, plugin) {
|
|
39
|
+
let names;
|
|
40
|
+
const nameOf = (id) => {
|
|
41
|
+
names ??= new Map(messages.flatMap((m) => m.content.flatMap((b) => (b.kind === "tool_use" ? [[b.id, b.name]] : []))));
|
|
42
|
+
return names.get(id);
|
|
43
|
+
};
|
|
44
|
+
let changed = false;
|
|
45
|
+
const out = messages.map((m) => {
|
|
46
|
+
if (m.role !== "user" || !m.content.some((b) => b.kind === "tool_result" && b.isError && b.content.length === 0))
|
|
47
|
+
return m;
|
|
48
|
+
changed = true;
|
|
49
|
+
return {
|
|
50
|
+
...m,
|
|
51
|
+
content: m.content.map((b) => {
|
|
52
|
+
if (b.kind !== "tool_result" || !b.isError || b.content.length > 0)
|
|
53
|
+
return b;
|
|
54
|
+
const text = explanation(reasons[b.toolUseId], b.origin, nameOf(b.toolUseId));
|
|
55
|
+
return { ...b, content: [{ kind: "text", text, origin: { by: "plugin", id: plugin }, trust: "trusted" }] };
|
|
56
|
+
}),
|
|
57
|
+
};
|
|
58
|
+
});
|
|
59
|
+
return changed ? out : messages;
|
|
60
|
+
}
|