@uncarved/jade 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +187 -2
- package/bin/jade.js +20 -0
- package/dist/commands.d.ts +30 -0
- package/dist/commands.js +106 -0
- package/dist/commands.js.map +1 -0
- package/dist/config.d.ts +34 -0
- package/dist/config.js +130 -0
- package/dist/config.js.map +1 -0
- package/dist/context.d.ts +17 -0
- package/dist/context.js +53 -0
- package/dist/context.js.map +1 -0
- package/dist/distro.d.ts +93 -0
- package/dist/distro.js +277 -0
- package/dist/distro.js.map +1 -0
- package/dist/history.d.ts +10 -0
- package/dist/history.js +47 -0
- package/dist/history.js.map +1 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +1124 -0
- package/dist/main.js.map +1 -0
- package/dist/mcp.d.ts +114 -0
- package/dist/mcp.js +640 -0
- package/dist/mcp.js.map +1 -0
- package/dist/memory.d.ts +19 -0
- package/dist/memory.js +129 -0
- package/dist/memory.js.map +1 -0
- package/dist/mentions.d.ts +35 -0
- package/dist/mentions.js +130 -0
- package/dist/mentions.js.map +1 -0
- package/dist/plugin-cli.d.ts +16 -0
- package/dist/plugin-cli.js +251 -0
- package/dist/plugin-cli.js.map +1 -0
- package/dist/plugins/budget.d.ts +9 -0
- package/dist/plugins/budget.js +30 -0
- package/dist/plugins/budget.js.map +1 -0
- package/dist/plugins/builtins.d.ts +10 -0
- package/dist/plugins/builtins.js +22 -0
- package/dist/plugins/builtins.js.map +1 -0
- package/dist/plugins/checks.d.ts +70 -0
- package/dist/plugins/checks.js +335 -0
- package/dist/plugins/checks.js.map +1 -0
- package/dist/plugins/compact.d.ts +26 -0
- package/dist/plugins/compact.js +216 -0
- package/dist/plugins/compact.js.map +1 -0
- package/dist/plugins/core.d.ts +42 -0
- package/dist/plugins/core.js +190 -0
- package/dist/plugins/core.js.map +1 -0
- package/dist/plugins/install.d.ts +68 -0
- package/dist/plugins/install.js +377 -0
- package/dist/plugins/install.js.map +1 -0
- package/dist/plugins/loader.d.ts +182 -0
- package/dist/plugins/loader.js +253 -0
- package/dist/plugins/loader.js.map +1 -0
- package/dist/plugins/policy.d.ts +64 -0
- package/dist/plugins/policy.js +269 -0
- package/dist/plugins/policy.js.map +1 -0
- package/dist/plugins/prompts.d.ts +28 -0
- package/dist/plugins/prompts.js +169 -0
- package/dist/plugins/prompts.js.map +1 -0
- package/dist/plugins/repeats.d.ts +9 -0
- package/dist/plugins/repeats.js +55 -0
- package/dist/plugins/repeats.js.map +1 -0
- package/dist/plugins/schema.d.ts +2 -0
- package/dist/plugins/schema.js +64 -0
- package/dist/plugins/schema.js.map +1 -0
- package/dist/provider.d.ts +52 -0
- package/dist/provider.js +187 -0
- package/dist/provider.js.map +1 -0
- package/dist/sessions.d.ts +13 -0
- package/dist/sessions.js +40 -0
- package/dist/sessions.js.map +1 -0
- package/dist/skills.d.ts +37 -0
- package/dist/skills.js +179 -0
- package/dist/skills.js.map +1 -0
- package/dist/sys.d.ts +44 -0
- package/dist/sys.js +115 -0
- package/dist/sys.js.map +1 -0
- package/dist/tools/checkpoint.d.ts +43 -0
- package/dist/tools/checkpoint.js +144 -0
- package/dist/tools/checkpoint.js.map +1 -0
- package/dist/tools/fs.d.ts +35 -0
- package/dist/tools/fs.js +417 -0
- package/dist/tools/fs.js.map +1 -0
- package/dist/tools/grep.d.ts +6 -0
- package/dist/tools/grep.js +243 -0
- package/dist/tools/grep.js.map +1 -0
- package/dist/tools/shell.d.ts +49 -0
- package/dist/tools/shell.js +295 -0
- package/dist/tools/shell.js.map +1 -0
- package/dist/tools/task.d.ts +31 -0
- package/dist/tools/task.js +86 -0
- package/dist/tools/task.js.map +1 -0
- package/dist/tools/todo.d.ts +10 -0
- package/dist/tools/todo.js +55 -0
- package/dist/tools/todo.js.map +1 -0
- package/dist/tools/web.d.ts +23 -0
- package/dist/tools/web.js +426 -0
- package/dist/tools/web.js.map +1 -0
- package/dist/ui/configure.d.ts +20 -0
- package/dist/ui/configure.js +285 -0
- package/dist/ui/configure.js.map +1 -0
- package/dist/ui/diff.d.ts +20 -0
- package/dist/ui/diff.js +142 -0
- package/dist/ui/diff.js.map +1 -0
- package/dist/ui/editor.d.ts +33 -0
- package/dist/ui/editor.js +128 -0
- package/dist/ui/editor.js.map +1 -0
- package/dist/ui/render.d.ts +13 -0
- package/dist/ui/render.js +84 -0
- package/dist/ui/render.js.map +1 -0
- package/dist/ui/screen.d.ts +90 -0
- package/dist/ui/screen.js +105 -0
- package/dist/ui/screen.js.map +1 -0
- package/dist/ui/transcript.d.ts +33 -0
- package/dist/ui/transcript.js +336 -0
- package/dist/ui/transcript.js.map +1 -0
- package/dist/ui/tui.d.ts +28 -0
- package/dist/ui/tui.js +884 -0
- package/dist/ui/tui.js.map +1 -0
- package/package.json +59 -4
- package/src/commands.ts +120 -0
- package/src/config.ts +146 -0
- package/src/context.ts +64 -0
- package/src/distro.ts +358 -0
- package/src/history.ts +55 -0
- package/src/index.ts +26 -0
- package/src/main.ts +1180 -0
- package/src/mcp.ts +693 -0
- package/src/memory.ts +135 -0
- package/src/mentions.ts +135 -0
- package/src/plugin-cli.ts +239 -0
- package/src/plugins/budget.ts +37 -0
- package/src/plugins/builtins.ts +31 -0
- package/src/plugins/checks.ts +390 -0
- package/src/plugins/compact.ts +257 -0
- package/src/plugins/core.ts +217 -0
- package/src/plugins/install.ts +429 -0
- package/src/plugins/loader.ts +386 -0
- package/src/plugins/policy.ts +304 -0
- package/src/plugins/prompts.ts +200 -0
- package/src/plugins/repeats.ts +62 -0
- package/src/plugins/schema.ts +67 -0
- package/src/provider.ts +208 -0
- package/src/sessions.ts +48 -0
- package/src/skills.ts +197 -0
- package/src/sys.ts +133 -0
- package/src/tools/checkpoint.ts +164 -0
- package/src/tools/fs.ts +432 -0
- package/src/tools/grep.ts +268 -0
- package/src/tools/shell.ts +339 -0
- package/src/tools/task.ts +105 -0
- package/src/tools/todo.ts +67 -0
- package/src/tools/web.ts +451 -0
- package/src/ui/configure.ts +310 -0
- package/src/ui/diff.ts +136 -0
- package/src/ui/editor.ts +136 -0
- package/src/ui/render.ts +74 -0
- package/src/ui/screen.ts +164 -0
- package/src/ui/transcript.ts +345 -0
- package/src/ui/tui.tsx +1374 -0
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
// /model:选服务、填地址和密钥、选模型、改输出上限、思考力度和上下文窗口。配置写进 $JADE_HOME/.env。
|
|
2
|
+
// 配置过的服务和模型都记在 $JADE_HOME/models.json 里:同一个服务(类型、地址、密钥都相同)下的模型放在一起,
|
|
3
|
+
// 每个模型带自己的设置。/model 可以直接切回去,换了服务或地址之前的也不会丢。
|
|
4
|
+
|
|
5
|
+
import { hasProvider, parseTokens, readSavedServices, updateEnvFile, writeSavedServices, type SavedModel, type SavedService } from "../config.ts";
|
|
6
|
+
import { EFFORTS, listModels, providerInfo, providerKind, type ProviderKind } from "../provider.ts";
|
|
7
|
+
import { shortPath } from "./render.ts";
|
|
8
|
+
import { dim, green, red, type Screen } from "./screen.ts";
|
|
9
|
+
|
|
10
|
+
export interface ConfigureOptions {
|
|
11
|
+
screen: Screen;
|
|
12
|
+
envFile: string;
|
|
13
|
+
/** 保存过的服务和模型($JADE_HOME/models.json) */
|
|
14
|
+
modelsFile: string;
|
|
15
|
+
/** 按新的环境变量换上 provider、更新上下文窗口;配置不完整时抛出 */
|
|
16
|
+
apply(): Promise<void>;
|
|
17
|
+
/** 当前的上下文窗口(显示用) */
|
|
18
|
+
contextWindow(): number;
|
|
19
|
+
/** 配置成功后更新状态栏 */
|
|
20
|
+
onApplied(): void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface Configure {
|
|
24
|
+
/** 选服务、填地址和密钥、选模型;返回是否配置成功 */
|
|
25
|
+
provider(): Promise<boolean>;
|
|
26
|
+
/** /model [name] */
|
|
27
|
+
model(arg: string | undefined): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const PROVIDERS: Array<{ kind: ProviderKind; label: string; hint: string }> = [
|
|
31
|
+
{ kind: "openai-compat", label: "OpenAI-compatible service", hint: "any /chat/completions endpoint" },
|
|
32
|
+
{ kind: "openai", label: "OpenAI", hint: "Responses API" },
|
|
33
|
+
{ kind: "anthropic", label: "Anthropic", hint: "Claude" },
|
|
34
|
+
];
|
|
35
|
+
|
|
36
|
+
const MODEL_KEY: Record<ProviderKind, string> = { "openai-compat": "OPENAI_COMPAT_MODEL", openai: "OPENAI_MODEL", anthropic: "ANTHROPIC_MODEL" };
|
|
37
|
+
const KEY_KEY: Record<ProviderKind, string> = { "openai-compat": "OPENAI_COMPAT_API_KEY", openai: "OPENAI_API_KEY", anthropic: "ANTHROPIC_API_KEY" };
|
|
38
|
+
const URL_KEY: Record<ProviderKind, string> = { "openai-compat": "OPENAI_COMPAT_BASE_URL", openai: "OPENAI_BASE_URL", anthropic: "ANTHROPIC_BASE_URL" };
|
|
39
|
+
|
|
40
|
+
/** 每个模型自己的设置:切换模型时一起换掉 */
|
|
41
|
+
const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW"];
|
|
42
|
+
|
|
43
|
+
/** 一个服务包含的变量 */
|
|
44
|
+
const serviceKeys = (kind: ProviderKind) => [
|
|
45
|
+
"JADE_PROVIDER",
|
|
46
|
+
URL_KEY[kind],
|
|
47
|
+
KEY_KEY[kind],
|
|
48
|
+
...(kind === "openai-compat" ? ["OPENAI_COMPAT_EXTRA_BODY"] : []),
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
type Env = Record<string, string | undefined>;
|
|
52
|
+
|
|
53
|
+
const pick = (env: Env, keys: string[]) => {
|
|
54
|
+
const out: Record<string, string> = {};
|
|
55
|
+
for (const k of keys) if (env[k] !== undefined) out[k] = env[k]!;
|
|
56
|
+
return out;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** 服务的类型、地址和密钥都相同的算同一个;配置无效时返回 undefined */
|
|
60
|
+
function serviceId(env: Env): string | undefined {
|
|
61
|
+
try {
|
|
62
|
+
const i = providerInfo(env);
|
|
63
|
+
return `${i.kind}|${i.baseURL ?? ""}|${env[KEY_KEY[i.kind]] ?? ""}`;
|
|
64
|
+
} catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 选择列表里服务的说明:类型和地址的主机名 */
|
|
70
|
+
function describeService(s: SavedService): string {
|
|
71
|
+
const i = providerInfo(s.env);
|
|
72
|
+
let host = i.baseURL ?? "";
|
|
73
|
+
try {
|
|
74
|
+
host = new URL(host).host;
|
|
75
|
+
} catch {}
|
|
76
|
+
return [i.kind, host].filter(Boolean).join(" · ");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 输入的 token 数:空表示不设;写错时报告并返回 false */
|
|
80
|
+
function tokensInput(screen: Screen, name: string, text: string): boolean {
|
|
81
|
+
if (!text) return true;
|
|
82
|
+
try {
|
|
83
|
+
parseTokens(name, text);
|
|
84
|
+
return true;
|
|
85
|
+
} catch (err) {
|
|
86
|
+
screen.log(red(errorText(err)));
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const errorText = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
|
92
|
+
|
|
93
|
+
export function configurator(opts: ConfigureOptions): Configure {
|
|
94
|
+
const { screen, envFile, modelsFile } = opts;
|
|
95
|
+
|
|
96
|
+
/** 保存过的、有效的服务,最近用过的在前 */
|
|
97
|
+
const savedServices = async () => (await readSavedServices(modelsFile)).filter((s) => serviceId(s.env) !== undefined);
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 把当前的服务和模型记下来,都放到最前面。
|
|
101
|
+
* replacing:换了密钥的那个服务原来的 id,它下面的模型归到新的密钥下
|
|
102
|
+
*/
|
|
103
|
+
async function remember(replacing?: string) {
|
|
104
|
+
if (!hasProvider()) return;
|
|
105
|
+
const id = serviceId(process.env);
|
|
106
|
+
const model = providerInfo().model;
|
|
107
|
+
if (!id || !model) return;
|
|
108
|
+
const kind = providerKind();
|
|
109
|
+
const services = await savedServices();
|
|
110
|
+
const old = services.filter((s) => serviceId(s.env) === id || (replacing !== undefined && serviceId(s.env) === replacing));
|
|
111
|
+
const models = old.flatMap((s) => s.models).filter((m, i, all) => m.name !== model && all.findIndex((x) => x.name === m.name) === i);
|
|
112
|
+
const service: SavedService = {
|
|
113
|
+
env: { ...pick(process.env, serviceKeys(kind)), JADE_PROVIDER: kind },
|
|
114
|
+
models: [{ name: model, settings: pick(process.env, MODEL_SETTINGS) }, ...models],
|
|
115
|
+
};
|
|
116
|
+
await writeSavedServices(modelsFile, [service, ...services.filter((s) => !old.includes(s))]);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 保存配置并换上新的 provider;失败时报告原因,旧的 provider 继续用 */
|
|
120
|
+
async function applyConfig(updates: Record<string, string | undefined>, replacing?: string): Promise<boolean> {
|
|
121
|
+
await updateEnvFile(envFile, updates);
|
|
122
|
+
try {
|
|
123
|
+
await opts.apply();
|
|
124
|
+
} catch (err) {
|
|
125
|
+
screen.log(red(`Saved to ${shortPath(envFile)}, but the configuration is incomplete: ${errorText(err)}`));
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
const info = providerInfo();
|
|
129
|
+
opts.onApplied();
|
|
130
|
+
await remember(replacing).catch((err) => screen.log(red(`Could not save the model list to ${shortPath(modelsFile)}: ${errorText(err)}`)));
|
|
131
|
+
screen.log(green(`Model: ${info.model} (${info.kind}${info.baseURL ? `, ${info.baseURL}` : ""}). Saved to ${shortPath(envFile)}.`));
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** 换成保存过的服务 s 上的模型 m:服务的变量和模型的设置写进 .env,模型没设的设置删掉 */
|
|
136
|
+
function useSaved(s: SavedService, m: SavedModel): Promise<boolean> {
|
|
137
|
+
const kind = providerKind(s.env);
|
|
138
|
+
const updates: Record<string, string | undefined> = {};
|
|
139
|
+
for (const k of serviceKeys(kind)) updates[k] = s.env[k];
|
|
140
|
+
for (const k of MODEL_SETTINGS) updates[k] = m.settings[k];
|
|
141
|
+
updates.JADE_PROVIDER = kind;
|
|
142
|
+
updates[MODEL_KEY[kind]] = m.name;
|
|
143
|
+
return applyConfig(updates);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 在当前的服务上换成 model:用过的带上它自己的设置;新的模型沿用输出上限和思考力度,
|
|
148
|
+
* 上下文窗口不沿用(不同模型差别很大),按模型名推断
|
|
149
|
+
*/
|
|
150
|
+
async function switchModel(model: string): Promise<boolean> {
|
|
151
|
+
const id = serviceId(process.env);
|
|
152
|
+
const service = (await savedServices()).find((s) => serviceId(s.env) === id);
|
|
153
|
+
const saved = service?.models.find((m) => m.name === model);
|
|
154
|
+
if (service && saved) return useSaved(service, saved);
|
|
155
|
+
return applyConfig({ [MODEL_KEY[providerKind()]]: model, JADE_CONTEXT_WINDOW: undefined });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 选模型:服务能列出模型时从列表里选,否则手动输入 */
|
|
159
|
+
async function chooseModel(env: Env, current: string | undefined, saved: string[] = []): Promise<string | undefined> {
|
|
160
|
+
const models = await listModels(env);
|
|
161
|
+
if (models.length > 0) {
|
|
162
|
+
const OTHER = "\0other";
|
|
163
|
+
const picked = await screen.select(
|
|
164
|
+
"Choose a model",
|
|
165
|
+
[
|
|
166
|
+
...models.map((m) => ({ label: m, value: m, hint: m === current ? "current" : saved.includes(m) ? "saved" : undefined })),
|
|
167
|
+
{ label: "Enter a name…", value: OTHER },
|
|
168
|
+
],
|
|
169
|
+
);
|
|
170
|
+
if (picked !== OTHER) return picked;
|
|
171
|
+
}
|
|
172
|
+
return (await screen.input("Model name", { initial: current })) || undefined;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function configureProvider(): Promise<boolean> {
|
|
176
|
+
const current = hasProvider() ? providerInfo() : undefined;
|
|
177
|
+
const currentId = hasProvider() ? serviceId(process.env) : undefined;
|
|
178
|
+
const kind = await screen.select(
|
|
179
|
+
"Which service should jade use?",
|
|
180
|
+
PROVIDERS.map((p) => ({ label: p.label, value: p.kind, hint: p.kind === current?.kind ? `${p.hint} · current` : p.hint })),
|
|
181
|
+
);
|
|
182
|
+
if (!kind) return false;
|
|
183
|
+
const same = kind === current?.kind;
|
|
184
|
+
|
|
185
|
+
let baseURL: string | undefined = process.env[URL_KEY[kind]];
|
|
186
|
+
if (kind !== "anthropic") {
|
|
187
|
+
const fallback = kind === "openai" ? "https://api.openai.com/v1" : "";
|
|
188
|
+
const answer = await screen.input("Base URL", { initial: baseURL ?? fallback, placeholder: "https://example.com/v1" });
|
|
189
|
+
if (answer === undefined) return false;
|
|
190
|
+
if (kind === "openai-compat" && !answer) {
|
|
191
|
+
screen.log(red("A base URL is required."));
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
baseURL = answer || undefined;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// 已知的密钥:当前服务的,或者保存过的同一个地址的服务的(最近用过的那个)
|
|
198
|
+
const sameAddress = (env: Env) => {
|
|
199
|
+
const i = providerInfo(env);
|
|
200
|
+
return i.kind === kind && (i.baseURL ?? "") === (providerInfo({ JADE_PROVIDER: kind, [URL_KEY[kind]]: baseURL }).baseURL ?? "");
|
|
201
|
+
};
|
|
202
|
+
const services = await savedServices();
|
|
203
|
+
const known = current && sameAddress(process.env) ? process.env[KEY_KEY[kind]] : services.find((s) => sameAddress(s.env))?.env[KEY_KEY[kind]];
|
|
204
|
+
const answer = await screen.input("API key", {
|
|
205
|
+
mask: true,
|
|
206
|
+
placeholder: known ? "leave empty to keep the saved key" : kind === "openai-compat" ? "leave empty if the service needs none" : "",
|
|
207
|
+
});
|
|
208
|
+
if (answer === undefined) return false;
|
|
209
|
+
const key = answer || known;
|
|
210
|
+
|
|
211
|
+
const serviceEnv: Env = { JADE_PROVIDER: kind, [URL_KEY[kind]]: baseURL, [KEY_KEY[kind]]: key };
|
|
212
|
+
if (kind === "openai-compat") {
|
|
213
|
+
// 额外的请求参数跟着服务走:同一个服务保留,换了服务用保存过的那份
|
|
214
|
+
const saved = services.find((s) => serviceId(s.env) === serviceId(serviceEnv));
|
|
215
|
+
serviceEnv.OPENAI_COMPAT_EXTRA_BODY = saved ? saved.env.OPENAI_COMPAT_EXTRA_BODY : sameAddress(process.env) ? process.env.OPENAI_COMPAT_EXTRA_BODY : undefined;
|
|
216
|
+
}
|
|
217
|
+
const target = services.find((s) => serviceId(s.env) === serviceId(serviceEnv));
|
|
218
|
+
const model = await chooseModel({ ...process.env, ...serviceEnv }, same ? current?.model : undefined, target?.models.map((m) => m.name));
|
|
219
|
+
if (!model) return false;
|
|
220
|
+
|
|
221
|
+
// 用过的模型带上它自己的设置
|
|
222
|
+
const saved = target?.models.find((m) => m.name === model);
|
|
223
|
+
if (target && saved) return useSaved({ ...target, env: { ...target.env, ...pick(serviceEnv, serviceKeys(kind)) } }, saved);
|
|
224
|
+
|
|
225
|
+
const updates: Record<string, string | undefined> = { ...serviceEnv, [MODEL_KEY[kind]]: model, JADE_CONTEXT_WINDOW: undefined };
|
|
226
|
+
// 思考力度的取值每种服务不同
|
|
227
|
+
if (!same) updates.JADE_EFFORT = undefined;
|
|
228
|
+
// 其他服务常常默认只给 4096 个输出 token,带思考的模型很容易用完
|
|
229
|
+
if (kind !== "anthropic" && !process.env.JADE_MAX_TOKENS) {
|
|
230
|
+
const max = await screen.input("Output limit per reply in tokens, e.g. 32000, 64K (empty for the service default)", { initial: "32K" });
|
|
231
|
+
if (max === undefined || !tokensInput(screen, "Output limit", max)) return false;
|
|
232
|
+
if (max) updates.JADE_MAX_TOKENS = max;
|
|
233
|
+
}
|
|
234
|
+
// 同一个地址只换了密钥:原来的服务下的模型归到新的密钥下
|
|
235
|
+
const rekeyed = same && currentId !== undefined && sameAddress(process.env) && key !== process.env[KEY_KEY[kind]];
|
|
236
|
+
return applyConfig(updates, rekeyed ? currentId : undefined);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function configureModel(arg: string | undefined) {
|
|
240
|
+
const info = providerInfo();
|
|
241
|
+
// 之前只有 .env 时配置的模型也记下来,之后换了不会丢
|
|
242
|
+
await remember().catch(() => {});
|
|
243
|
+
const currentId = serviceId(process.env);
|
|
244
|
+
const services = await savedServices();
|
|
245
|
+
/** 保存过的、不是当前的模型,按服务分组:当前服务的在前 */
|
|
246
|
+
const others = [...services.filter((s) => serviceId(s.env) === currentId), ...services.filter((s) => serviceId(s.env) !== currentId)].flatMap((s) =>
|
|
247
|
+
s.models.filter((m) => !(serviceId(s.env) === currentId && m.name === info.model)).map((m) => ({ service: s, model: m })),
|
|
248
|
+
);
|
|
249
|
+
if (arg) {
|
|
250
|
+
// 保存过的模型按名字切换(当前服务的优先),否则换当前服务的模型
|
|
251
|
+
const saved = others.find((o) => o.model.name === arg);
|
|
252
|
+
return void (await (saved ? useSaved(saved.service, saved.model) : switchModel(arg)));
|
|
253
|
+
}
|
|
254
|
+
const efforts = EFFORTS[info.kind];
|
|
255
|
+
const action = await screen.select<string>(`Model: ${info.model} (${info.kind})`, [
|
|
256
|
+
...others.map((o, i) => ({ label: `Use ${o.model.name}`, value: `saved:${i}`, hint: describeService(o.service) })),
|
|
257
|
+
{ label: "Add a model from this service", value: "model" as const, hint: `current: ${info.model}` },
|
|
258
|
+
{ label: "Add a service, or change the base URL or API key", value: "provider" as const, hint: info.baseURL },
|
|
259
|
+
{ label: "Output limit per reply", value: "max" as const, hint: process.env.JADE_MAX_TOKENS ? `${process.env.JADE_MAX_TOKENS} tokens` : "service default" },
|
|
260
|
+
...(efforts
|
|
261
|
+
? [{ label: "Reasoning effort", value: "effort" as const, hint: process.env.JADE_EFFORT ?? (info.kind === "anthropic" ? "high (default)" : "service default") }]
|
|
262
|
+
: []),
|
|
263
|
+
{
|
|
264
|
+
label: "Context window",
|
|
265
|
+
value: "window" as const,
|
|
266
|
+
hint: `${opts.contextWindow()} tokens${process.env.JADE_CONTEXT_WINDOW ? "" : " (default)"}`,
|
|
267
|
+
},
|
|
268
|
+
...(others.length ? [{ label: "Forget a saved model", value: "forget" as const }] : []),
|
|
269
|
+
]);
|
|
270
|
+
if (action?.startsWith("saved:")) {
|
|
271
|
+
const o = others[Number(action.slice(6))]!;
|
|
272
|
+
await useSaved(o.service, o.model);
|
|
273
|
+
} else if (action === "forget") {
|
|
274
|
+
const gone = await screen.select(
|
|
275
|
+
"Forget which model?",
|
|
276
|
+
others.map((o) => ({ label: o.model.name, value: o, hint: describeService(o.service) })),
|
|
277
|
+
);
|
|
278
|
+
if (!gone) return;
|
|
279
|
+
const id = serviceId(gone.service.env);
|
|
280
|
+
// 服务下没有模型了就连服务(和它的密钥)一起删掉
|
|
281
|
+
const rest = (await savedServices())
|
|
282
|
+
.map((s) => (serviceId(s.env) === id ? { ...s, models: s.models.filter((m) => m.name !== gone.model.name) } : s))
|
|
283
|
+
.filter((s) => s.models.length > 0);
|
|
284
|
+
await writeSavedServices(modelsFile, rest);
|
|
285
|
+
screen.log(dim(`Forgot ${gone.model.name} (${describeService(gone.service)}).`));
|
|
286
|
+
} else if (action === "model") {
|
|
287
|
+
const saved = services.find((s) => serviceId(s.env) === currentId)?.models.map((m) => m.name);
|
|
288
|
+
const model = await chooseModel(process.env, info.model, saved);
|
|
289
|
+
if (model && model !== info.model) await switchModel(model);
|
|
290
|
+
} else if (action === "provider") await configureProvider();
|
|
291
|
+
else if (action === "max") {
|
|
292
|
+
const max = await screen.input("Output limit per reply in tokens, e.g. 32000, 64K (empty for the service default)", { initial: process.env.JADE_MAX_TOKENS ?? "32K" });
|
|
293
|
+
if (max !== undefined && tokensInput(screen, "Output limit", max)) await applyConfig({ JADE_MAX_TOKENS: max || undefined });
|
|
294
|
+
} else if (action === "effort" && efforts) {
|
|
295
|
+
const DEFAULT = "\0default";
|
|
296
|
+
const effort = await screen.select("Reasoning effort", [
|
|
297
|
+
...efforts.map((e) => ({ label: e, value: e, hint: e === process.env.JADE_EFFORT ? "current" : undefined })),
|
|
298
|
+
{ label: "Default", value: DEFAULT, hint: info.kind === "anthropic" ? "high" : "service default" },
|
|
299
|
+
]);
|
|
300
|
+
if (effort !== undefined) await applyConfig({ JADE_EFFORT: effort === DEFAULT ? undefined : effort });
|
|
301
|
+
} else if (action === "window") {
|
|
302
|
+
const n = await screen.input("Context window in tokens, e.g. 128000, 512K, 1M (empty to infer it from the model name, or 128K if unknown)", {
|
|
303
|
+
initial: process.env.JADE_CONTEXT_WINDOW ?? "",
|
|
304
|
+
});
|
|
305
|
+
if (n !== undefined && tokensInput(screen, "Context window", n)) await applyConfig({ JADE_CONTEXT_WINDOW: n || undefined });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
return { provider: configureProvider, model: configureModel };
|
|
310
|
+
}
|
package/src/ui/diff.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// 按行比较两段文本,生成带行号和上下文的 unified diff,审批修改时显示。
|
|
2
|
+
//
|
|
3
|
+
// 先去掉相同的开头和结尾,只对中间部分求最长公共子序列;中间部分太大时(整个文件重写)
|
|
4
|
+
// 不再逐行比较,整段显示为删除加新增,避免占用大量内存和时间。
|
|
5
|
+
|
|
6
|
+
import { dim, green, red } from "./screen.ts";
|
|
7
|
+
|
|
8
|
+
export type DiffLine = { kind: " " | "-" | "+"; text: string; /** 旧文件里的行号(删除、相同) */ old?: number; /** 新文件里的行号(新增、相同) */ new?: number };
|
|
9
|
+
|
|
10
|
+
/** LCS 表的上限:中间部分的行数乘积超过它就整段替换 */
|
|
11
|
+
const MAX_CELLS = 4_000_000;
|
|
12
|
+
|
|
13
|
+
const splitLines = (s: string) => {
|
|
14
|
+
if (s === "") return [];
|
|
15
|
+
const lines = s.split(/\r?\n/);
|
|
16
|
+
if (lines.at(-1) === "") lines.pop();
|
|
17
|
+
return lines;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** 两段文本的逐行差异,包括相同的行 */
|
|
21
|
+
export function diffLines(before: string, after: string): DiffLine[] {
|
|
22
|
+
const a = splitLines(before);
|
|
23
|
+
const b = splitLines(after);
|
|
24
|
+
let start = 0;
|
|
25
|
+
while (start < a.length && start < b.length && a[start] === b[start]) start++;
|
|
26
|
+
let endA = a.length;
|
|
27
|
+
let endB = b.length;
|
|
28
|
+
while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
|
|
29
|
+
endA--;
|
|
30
|
+
endB--;
|
|
31
|
+
}
|
|
32
|
+
const out: DiffLine[] = [];
|
|
33
|
+
for (let i = 0; i < start; i++) out.push({ kind: " ", text: a[i]!, old: i + 1, new: i + 1 });
|
|
34
|
+
const midA = a.slice(start, endA);
|
|
35
|
+
const midB = b.slice(start, endB);
|
|
36
|
+
for (const op of middle(midA, midB)) {
|
|
37
|
+
if (op.kind === " ") out.push({ kind: " ", text: midA[op.i]!, old: start + op.i + 1, new: start + op.j + 1 });
|
|
38
|
+
else if (op.kind === "-") out.push({ kind: "-", text: midA[op.i]!, old: start + op.i + 1 });
|
|
39
|
+
else out.push({ kind: "+", text: midB[op.j]!, new: start + op.j + 1 });
|
|
40
|
+
}
|
|
41
|
+
for (let k = 0; endA + k < a.length; k++) out.push({ kind: " ", text: a[endA + k]!, old: endA + k + 1, new: endB + k + 1 });
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
type Op = { kind: " " | "-" | "+"; i: number; j: number };
|
|
46
|
+
|
|
47
|
+
function middle(a: string[], b: string[]): Op[] {
|
|
48
|
+
const n = a.length;
|
|
49
|
+
const m = b.length;
|
|
50
|
+
if (n === 0 || m === 0 || n * m > MAX_CELLS) {
|
|
51
|
+
return [...a.map((_, i) => ({ kind: "-" as const, i, j: 0 })), ...b.map((_, j) => ({ kind: "+" as const, i: 0, j }))];
|
|
52
|
+
}
|
|
53
|
+
// lcs[i][j]:a[i..] 和 b[j..] 的最长公共子序列长度,按行存成一维
|
|
54
|
+
const w = m + 1;
|
|
55
|
+
const lcs = new Uint32Array((n + 1) * w);
|
|
56
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
57
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
58
|
+
lcs[i * w + j] = a[i] === b[j] ? lcs[(i + 1) * w + j + 1]! + 1 : Math.max(lcs[(i + 1) * w + j]!, lcs[i * w + j + 1]!);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const ops: Op[] = [];
|
|
62
|
+
let i = 0;
|
|
63
|
+
let j = 0;
|
|
64
|
+
while (i < n && j < m) {
|
|
65
|
+
if (a[i] === b[j]) ops.push({ kind: " ", i: i++, j: j++ });
|
|
66
|
+
// 先删后加:同一处的修改显示成一组 - 再一组 +
|
|
67
|
+
else if (lcs[(i + 1) * w + j]! >= lcs[i * w + j + 1]!) ops.push({ kind: "-", i: i++, j });
|
|
68
|
+
else ops.push({ kind: "+", i, j: j++ });
|
|
69
|
+
}
|
|
70
|
+
while (i < n) ops.push({ kind: "-", i: i++, j });
|
|
71
|
+
while (j < m) ops.push({ kind: "+", i, j: j++ });
|
|
72
|
+
return ops;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 有改动的行加上前后 context 行;相隔不远的改动合成一段 */
|
|
76
|
+
export function hunks(lines: DiffLine[], context = 3): DiffLine[][] {
|
|
77
|
+
const changed = lines.flatMap((l, i) => (l.kind === " " ? [] : [i]));
|
|
78
|
+
const out: DiffLine[][] = [];
|
|
79
|
+
let from = -1;
|
|
80
|
+
let to = -1;
|
|
81
|
+
for (const i of changed) {
|
|
82
|
+
if (from >= 0 && i - context <= to + 1) {
|
|
83
|
+
to = Math.min(lines.length - 1, i + context);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (from >= 0) out.push(lines.slice(from, to + 1));
|
|
87
|
+
from = Math.max(0, i - context);
|
|
88
|
+
to = Math.min(lines.length - 1, i + context);
|
|
89
|
+
}
|
|
90
|
+
if (from >= 0) out.push(lines.slice(from, to + 1));
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface DiffStats {
|
|
95
|
+
added: number;
|
|
96
|
+
removed: number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function diffStats(lines: DiffLine[]): DiffStats {
|
|
100
|
+
let added = 0;
|
|
101
|
+
let removed = 0;
|
|
102
|
+
for (const l of lines) {
|
|
103
|
+
if (l.kind === "+") added++;
|
|
104
|
+
else if (l.kind === "-") removed++;
|
|
105
|
+
}
|
|
106
|
+
return { added, removed };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 显示用:每行前面是行号(新增行用新文件的行号,其余用旧文件的),段与段之间用 ⋯ 分开。
|
|
111
|
+
* 超过 maxLines 行时截断
|
|
112
|
+
*/
|
|
113
|
+
export function renderDiff(before: string, after: string, maxLines = 60): string {
|
|
114
|
+
const lines = diffLines(before, after);
|
|
115
|
+
const parts = hunks(lines);
|
|
116
|
+
if (parts.length === 0) return dim(" (no changes)");
|
|
117
|
+
const width = String(lines.reduce((w, l) => Math.max(w, l.old ?? 0, l.new ?? 0), 0)).length;
|
|
118
|
+
const out: string[] = [];
|
|
119
|
+
let shown = 0;
|
|
120
|
+
let total = 0;
|
|
121
|
+
for (const h of parts) total += h.length;
|
|
122
|
+
for (const [k, h] of parts.entries()) {
|
|
123
|
+
if (k > 0) out.push(dim(`${" ".repeat(width)} ⋯`));
|
|
124
|
+
for (const l of h) {
|
|
125
|
+
if (shown >= maxLines) break;
|
|
126
|
+
const no = String((l.kind === "+" ? l.new : l.old) ?? "").padStart(width);
|
|
127
|
+
const text = `${no} ${l.kind} ${l.text}`;
|
|
128
|
+
out.push(l.kind === "+" ? green(text) : l.kind === "-" ? red(text) : dim(text));
|
|
129
|
+
shown++;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (total > shown) out.push(dim(` … ${total - shown} more lines`));
|
|
133
|
+
const { added, removed } = diffStats(lines);
|
|
134
|
+
out.push(dim(` ${green(`+${added}`)} ${red(`-${removed}`)}`));
|
|
135
|
+
return out.join("\n");
|
|
136
|
+
}
|
package/src/ui/editor.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// 输入框的编辑操作和折行。都是纯函数,便于测试。
|
|
2
|
+
// cursor 是 value 中的下标(UTF-16),操作按码点移动,不会把代理对拆开。
|
|
3
|
+
|
|
4
|
+
import stringWidth from "string-width";
|
|
5
|
+
|
|
6
|
+
export interface EditState {
|
|
7
|
+
value: string;
|
|
8
|
+
cursor: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const empty: EditState = { value: "", cursor: 0 };
|
|
12
|
+
|
|
13
|
+
/** 光标前一个码点的起始下标 */
|
|
14
|
+
function prev(value: string, i: number): number {
|
|
15
|
+
if (i <= 0) return 0;
|
|
16
|
+
const c = value.charCodeAt(i - 1);
|
|
17
|
+
return c >= 0xdc00 && c <= 0xdfff && i >= 2 ? i - 2 : i - 1;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 光标后一个码点的结束下标 */
|
|
21
|
+
function next(value: string, i: number): number {
|
|
22
|
+
if (i >= value.length) return value.length;
|
|
23
|
+
const c = value.charCodeAt(i);
|
|
24
|
+
return c >= 0xd800 && c <= 0xdbff && i + 1 < value.length ? i + 2 : i + 1;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const lineStart = (value: string, i: number) => value.lastIndexOf("\n", i - 1) + 1;
|
|
28
|
+
const lineEnd = (value: string, i: number) => {
|
|
29
|
+
const n = value.indexOf("\n", i);
|
|
30
|
+
return n === -1 ? value.length : n;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export const edit = {
|
|
34
|
+
insert: (s: EditState, text: string): EditState => ({
|
|
35
|
+
value: s.value.slice(0, s.cursor) + text + s.value.slice(s.cursor),
|
|
36
|
+
cursor: s.cursor + text.length,
|
|
37
|
+
}),
|
|
38
|
+
backspace: (s: EditState): EditState => {
|
|
39
|
+
const p = prev(s.value, s.cursor);
|
|
40
|
+
return { value: s.value.slice(0, p) + s.value.slice(s.cursor), cursor: p };
|
|
41
|
+
},
|
|
42
|
+
del: (s: EditState): EditState => ({ value: s.value.slice(0, s.cursor) + s.value.slice(next(s.value, s.cursor)), cursor: s.cursor }),
|
|
43
|
+
left: (s: EditState): EditState => ({ ...s, cursor: prev(s.value, s.cursor) }),
|
|
44
|
+
right: (s: EditState): EditState => ({ ...s, cursor: next(s.value, s.cursor) }),
|
|
45
|
+
home: (s: EditState): EditState => ({ ...s, cursor: lineStart(s.value, s.cursor) }),
|
|
46
|
+
end: (s: EditState): EditState => ({ ...s, cursor: lineEnd(s.value, s.cursor) }),
|
|
47
|
+
/** 删除光标前的一个词(连同它和光标之间的空白),同 shell 的 Ctrl+W */
|
|
48
|
+
deleteWord: (s: EditState): EditState => {
|
|
49
|
+
const before = s.value.slice(0, s.cursor);
|
|
50
|
+
const kept = before.replace(/\S*\s*$/u, "");
|
|
51
|
+
return { value: kept + s.value.slice(s.cursor), cursor: kept.length };
|
|
52
|
+
},
|
|
53
|
+
/** 删除光标到行首 */
|
|
54
|
+
killBefore: (s: EditState): EditState => {
|
|
55
|
+
const start = lineStart(s.value, s.cursor);
|
|
56
|
+
return { value: s.value.slice(0, start) + s.value.slice(s.cursor), cursor: start };
|
|
57
|
+
},
|
|
58
|
+
/** 删除光标到行尾 */
|
|
59
|
+
killAfter: (s: EditState): EditState => ({ value: s.value.slice(0, s.cursor) + s.value.slice(lineEnd(s.value, s.cursor)), cursor: s.cursor }),
|
|
60
|
+
/** 光标所在行是第一行 / 最后一行(上下键在多行输入里移动光标,到边上才翻历史) */
|
|
61
|
+
onFirstLine: (s: EditState) => !s.value.slice(0, s.cursor).includes("\n"),
|
|
62
|
+
onLastLine: (s: EditState) => !s.value.slice(s.cursor).includes("\n"),
|
|
63
|
+
up: (s: EditState): EditState => {
|
|
64
|
+
const start = lineStart(s.value, s.cursor);
|
|
65
|
+
if (start === 0) return s;
|
|
66
|
+
const col = s.cursor - start;
|
|
67
|
+
const prevStart = lineStart(s.value, start - 1);
|
|
68
|
+
return { ...s, cursor: Math.min(prevStart + col, start - 1) };
|
|
69
|
+
},
|
|
70
|
+
down: (s: EditState): EditState => {
|
|
71
|
+
const end = lineEnd(s.value, s.cursor);
|
|
72
|
+
if (end === s.value.length) return s;
|
|
73
|
+
const col = s.cursor - lineStart(s.value, s.cursor);
|
|
74
|
+
return { ...s, cursor: Math.min(end + 1 + col, lineEnd(s.value, end + 1)) };
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
export interface Layout {
|
|
79
|
+
rows: string[];
|
|
80
|
+
/** 光标所在的行和列(列按显示宽度,中文占两列) */
|
|
81
|
+
row: number;
|
|
82
|
+
col: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 单个字符的显示宽度;每次按键都要把整段输入过一遍,stringWidth 较慢,ASCII 直接算,其余缓存 */
|
|
86
|
+
const widths = new Map<string, number>();
|
|
87
|
+
function charWidth(ch: string): number {
|
|
88
|
+
const c = ch.charCodeAt(0);
|
|
89
|
+
if (c >= 0x20 && c < 0x7f) return 1;
|
|
90
|
+
let w = widths.get(ch);
|
|
91
|
+
if (w === undefined) widths.set(ch, (w = stringWidth(ch)));
|
|
92
|
+
return w;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 按显示宽度折行(按字符折,不按词),并算出光标位置。width 至少为 2 */
|
|
96
|
+
export function layout(value: string, cursor: number, width: number): Layout {
|
|
97
|
+
width = Math.max(2, width);
|
|
98
|
+
const rows: string[] = [];
|
|
99
|
+
let row = 0;
|
|
100
|
+
let col = 0;
|
|
101
|
+
let current = "";
|
|
102
|
+
let currentWidth = 0;
|
|
103
|
+
let i = 0;
|
|
104
|
+
const place = () => {
|
|
105
|
+
row = rows.length;
|
|
106
|
+
col = currentWidth;
|
|
107
|
+
};
|
|
108
|
+
for (const ch of value) {
|
|
109
|
+
if (i === cursor) place();
|
|
110
|
+
if (ch === "\n") {
|
|
111
|
+
rows.push(current);
|
|
112
|
+
current = "";
|
|
113
|
+
currentWidth = 0;
|
|
114
|
+
} else {
|
|
115
|
+
const w = charWidth(ch);
|
|
116
|
+
if (currentWidth + w > width) {
|
|
117
|
+
rows.push(current);
|
|
118
|
+
current = "";
|
|
119
|
+
currentWidth = 0;
|
|
120
|
+
if (i === cursor) place();
|
|
121
|
+
}
|
|
122
|
+
current += ch;
|
|
123
|
+
currentWidth += w;
|
|
124
|
+
}
|
|
125
|
+
i += ch.length;
|
|
126
|
+
}
|
|
127
|
+
if (cursor >= value.length) place();
|
|
128
|
+
rows.push(current);
|
|
129
|
+
// 光标正好停在满行末尾时放到下一行开头
|
|
130
|
+
if (col >= width) {
|
|
131
|
+
row++;
|
|
132
|
+
col = 0;
|
|
133
|
+
if (row >= rows.length) rows.push("");
|
|
134
|
+
}
|
|
135
|
+
return { rows, row, col };
|
|
136
|
+
}
|
package/src/ui/render.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// 宿主显示用的纯函数:工具调用的一行摘要、审批时的预览、折叠的工具结果。不依赖运行时和界面状态。
|
|
2
|
+
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import type { PendingCall } from "uncarved";
|
|
7
|
+
import { applyEditsToText, display, type Edit } from "../tools/fs.ts";
|
|
8
|
+
import { renderDiff } from "./diff.ts";
|
|
9
|
+
import { dim, green, red, yellow } from "./screen.ts";
|
|
10
|
+
|
|
11
|
+
export const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
|
|
12
|
+
|
|
13
|
+
/** 家目录下的路径显示成 ~/… */
|
|
14
|
+
export function shortPath(p: string): string {
|
|
15
|
+
const rel = path.relative(os.homedir(), p);
|
|
16
|
+
const shown = rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? `~/${rel}` : rel === "" ? "~" : p;
|
|
17
|
+
return shown.split(path.sep).join("/");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 工具调用的一行摘要,显示在工具名后面的括号里 */
|
|
21
|
+
export function summarize(cwd: string, name: string, input: unknown): string {
|
|
22
|
+
const i = (input ?? {}) as Record<string, unknown>;
|
|
23
|
+
if (name === "bash") return clip(String(i.command ?? "").split("\n")[0]!, 120);
|
|
24
|
+
if (name === "task") return String(i.description ?? "");
|
|
25
|
+
if (name === "bash_output" || name === "kill_shell") return String(i.id ?? "");
|
|
26
|
+
if (name === "todo_write") return `${Array.isArray(i.todos) ? i.todos.length : 0} items`;
|
|
27
|
+
if (name === "web_fetch") return clip(String(i.url ?? ""), 120);
|
|
28
|
+
if (name === "web_search") return clip(String(i.query ?? ""), 120);
|
|
29
|
+
if (name === "memory") return `${i.action} ${i.scope}: ${clip(String(i.text ?? ""), 120)}`;
|
|
30
|
+
const where = typeof i.path === "string" ? display(cwd, i.path) : "";
|
|
31
|
+
if (name === "multi_edit") return `${where}, ${Array.isArray(i.edits) ? i.edits.length : 0} edits`;
|
|
32
|
+
if (name === "grep" || name === "glob") return `${i.pattern}${where && where !== "." ? ` in ${where}` : ""}`;
|
|
33
|
+
return where || clip(JSON.stringify(input), 120);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 审批时显示的内容:修改显示成带行号和上下文的 diff(读出文件、按工具的规则算出修改后的内容),
|
|
38
|
+
* 命令显示命令本身。文件读不了、替换不成立时退回到只显示参数里的新旧文本
|
|
39
|
+
*/
|
|
40
|
+
export async function preview(c: PendingCall, cwd: string): Promise<string> {
|
|
41
|
+
const i = (c.input ?? {}) as Record<string, unknown>;
|
|
42
|
+
const lines = (s: string, mark: string, color: (s: string) => string, max = 30) => {
|
|
43
|
+
const all = s.split("\n");
|
|
44
|
+
const shown = all.slice(0, max).map((l) => color(`${mark} ${l}`));
|
|
45
|
+
if (all.length > max) shown.push(dim(` … ${all.length - max} more lines`));
|
|
46
|
+
return shown.join("\n");
|
|
47
|
+
};
|
|
48
|
+
const raw = (e: Record<string, unknown>) => `${lines(String(e.old_string ?? ""), "-", red)}\n${lines(String(e.new_string ?? ""), "+", green)}`;
|
|
49
|
+
const file = typeof i.path === "string" ? path.resolve(cwd, i.path) : undefined;
|
|
50
|
+
const current = file ? await readFile(file, "utf8").catch(() => undefined) : undefined;
|
|
51
|
+
if (c.name === "edit_file" || (c.name === "multi_edit" && Array.isArray(i.edits))) {
|
|
52
|
+
const edits = (c.name === "edit_file" ? [i] : i.edits) as unknown as Edit[];
|
|
53
|
+
const fallback = () => edits.map((e) => raw(e as unknown as Record<string, unknown>)).join(dim("\n ⋯\n"));
|
|
54
|
+
if (current === undefined) return fallback();
|
|
55
|
+
const r = applyEditsToText(current, edits, display(cwd, file!));
|
|
56
|
+
if (typeof r === "string") return `${fallback()}\n${yellow(` (this edit will fail: ${clip(r, 200)})`)}`;
|
|
57
|
+
return renderDiff(current, r.text);
|
|
58
|
+
}
|
|
59
|
+
if (c.name === "write_file") {
|
|
60
|
+
const content = String(i.content ?? "");
|
|
61
|
+
if (current !== undefined) return `${dim(" overwrites the existing file:")}\n${renderDiff(current, content)}`;
|
|
62
|
+
return lines(content, "+", green, 20);
|
|
63
|
+
}
|
|
64
|
+
if (c.name === "bash") return lines(String(i.command ?? ""), "$", (s) => s);
|
|
65
|
+
if (c.name === "memory") return `${i.action === "remove" ? red("- ") : green("+ ")}${String(i.text ?? "")}`;
|
|
66
|
+
return dim(clip(JSON.stringify(c.input, null, 2), 2000));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 工具结果展开后的内容:缩进的全部行,超过 max 行时截断 */
|
|
70
|
+
export function detailsOf(lines: string[], color: (s: string) => string, max: number): string {
|
|
71
|
+
const body = lines.slice(0, max).map((l) => color(` ${l}`));
|
|
72
|
+
if (lines.length > max) body.push(dim(` … ${lines.length - max} more lines`));
|
|
73
|
+
return body.join("\n");
|
|
74
|
+
}
|