@uncarved/jade 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -6
- package/bin/jade.js +23 -0
- package/dist/commands.d.ts +20 -0
- package/dist/commands.js +20 -0
- package/dist/commands.js.map +1 -1
- package/dist/distro.d.ts +51 -7
- package/dist/distro.js +199 -48
- package/dist/distro.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js +479 -303
- package/dist/main.js.map +1 -1
- package/dist/mcp.js +1 -1
- package/dist/mcp.js.map +1 -1
- package/dist/plugin-cli.d.ts +1 -1
- package/dist/plugin-cli.js +79 -36
- package/dist/plugin-cli.js.map +1 -1
- package/dist/plugins/budget.d.ts +2 -2
- package/dist/plugins/budget.js +2 -2
- package/dist/plugins/budget.js.map +1 -1
- package/dist/plugins/builtins.js +6 -3
- package/dist/plugins/builtins.js.map +1 -1
- package/dist/plugins/checks.d.ts +2 -1
- package/dist/plugins/checks.js +25 -5
- package/dist/plugins/checks.js.map +1 -1
- package/dist/plugins/compact.js +45 -1
- package/dist/plugins/compact.js.map +1 -1
- package/dist/plugins/core.d.ts +5 -0
- package/dist/plugins/core.js +39 -0
- package/dist/plugins/core.js.map +1 -1
- package/dist/plugins/host.d.ts +52 -0
- package/dist/plugins/host.js +115 -0
- package/dist/plugins/host.js.map +1 -0
- package/dist/plugins/install.d.ts +1 -1
- package/dist/plugins/loader.d.ts +238 -10
- package/dist/plugins/loader.js +175 -21
- package/dist/plugins/loader.js.map +1 -1
- package/dist/plugins/policy.d.ts +23 -5
- package/dist/plugins/policy.js +63 -10
- package/dist/plugins/policy.js.map +1 -1
- package/dist/plugins/prompts.d.ts +14 -1
- package/dist/plugins/prompts.js +118 -16
- package/dist/plugins/prompts.js.map +1 -1
- package/dist/plugins/repeats.d.ts +7 -0
- package/dist/plugins/repeats.js +74 -13
- package/dist/plugins/repeats.js.map +1 -1
- package/dist/plugins/review.d.ts +18 -0
- package/dist/plugins/review.js +130 -0
- package/dist/plugins/review.js.map +1 -0
- package/dist/plugins/sessions.d.ts +7 -0
- package/dist/plugins/sessions.js +110 -0
- package/dist/plugins/sessions.js.map +1 -0
- package/dist/provider.d.ts +57 -3
- package/dist/provider.js +80 -10
- package/dist/provider.js.map +1 -1
- package/dist/session-lifecycle.d.ts +61 -0
- package/dist/session-lifecycle.js +167 -0
- package/dist/session-lifecycle.js.map +1 -0
- package/dist/session-scope.d.ts +53 -0
- package/dist/session-scope.js +116 -0
- package/dist/session-scope.js.map +1 -0
- package/dist/sessions.d.ts +6 -0
- package/dist/sessions.js +20 -0
- package/dist/sessions.js.map +1 -1
- package/dist/sys.d.ts +4 -1
- package/dist/sys.js +18 -1
- package/dist/sys.js.map +1 -1
- package/dist/tools/ask.d.ts +11 -0
- package/dist/tools/ask.js +62 -0
- package/dist/tools/ask.js.map +1 -0
- package/dist/tools/fs.d.ts +4 -0
- package/dist/tools/fs.js +53 -12
- package/dist/tools/fs.js.map +1 -1
- package/dist/tools/grep.js +3 -2
- package/dist/tools/grep.js.map +1 -1
- package/dist/tools/shell.js +5 -1
- package/dist/tools/shell.js.map +1 -1
- package/dist/tools/task.d.ts +10 -2
- package/dist/tools/task.js +40 -9
- package/dist/tools/task.js.map +1 -1
- package/dist/tools/web.d.ts +33 -3
- package/dist/tools/web.js +351 -143
- package/dist/tools/web.js.map +1 -1
- package/dist/ui/configure.js +144 -66
- package/dist/ui/configure.js.map +1 -1
- package/dist/ui/diff.d.ts +1 -1
- package/dist/ui/diff.js +1 -2
- package/dist/ui/diff.js.map +1 -1
- package/dist/ui/editor.d.ts +8 -0
- package/dist/ui/editor.js +50 -1
- package/dist/ui/editor.js.map +1 -1
- package/dist/ui/markdown.d.ts +22 -0
- package/dist/ui/markdown.js +242 -0
- package/dist/ui/markdown.js.map +1 -0
- package/dist/ui/render.d.ts +9 -8
- package/dist/ui/render.js +35 -62
- package/dist/ui/render.js.map +1 -1
- package/dist/ui/renderers.d.ts +8 -0
- package/dist/ui/renderers.js +169 -0
- package/dist/ui/renderers.js.map +1 -0
- package/dist/ui/screen.d.ts +25 -2
- package/dist/ui/screen.js +104 -12
- package/dist/ui/screen.js.map +1 -1
- package/dist/ui/transcript.d.ts +13 -0
- package/dist/ui/transcript.js +157 -31
- package/dist/ui/transcript.js.map +1 -1
- package/dist/ui/tui.d.ts +2 -0
- package/dist/ui/tui.js +383 -81
- package/dist/ui/tui.js.map +1 -1
- package/dist/update.d.ts +53 -0
- package/dist/update.js +255 -0
- package/dist/update.js.map +1 -0
- package/package.json +7 -6
- package/src/commands.ts +24 -0
- package/src/distro.ts +234 -52
- package/src/index.ts +3 -0
- package/src/main.ts +459 -300
- package/src/mcp.ts +1 -1
- package/src/plugin-cli.ts +73 -34
- package/src/plugins/budget.ts +4 -4
- package/src/plugins/builtins.ts +6 -3
- package/src/plugins/checks.ts +25 -6
- package/src/plugins/compact.ts +40 -1
- package/src/plugins/core.ts +40 -0
- package/src/plugins/host.ts +146 -0
- package/src/plugins/install.ts +1 -1
- package/src/plugins/loader.ts +379 -23
- package/src/plugins/policy.ts +70 -13
- package/src/plugins/prompts.ts +128 -16
- package/src/plugins/repeats.ts +75 -14
- package/src/plugins/review.ts +146 -0
- package/src/plugins/sessions.ts +109 -0
- package/src/provider.ts +117 -14
- package/src/session-lifecycle.ts +194 -0
- package/src/session-scope.ts +135 -0
- package/src/sessions.ts +17 -0
- package/src/sys.ts +18 -1
- package/src/tools/ask.ts +72 -0
- package/src/tools/fs.ts +53 -12
- package/src/tools/grep.ts +3 -2
- package/src/tools/shell.ts +5 -1
- package/src/tools/task.ts +56 -12
- package/src/tools/web.ts +370 -140
- package/src/ui/configure.ts +141 -67
- package/src/ui/diff.ts +1 -2
- package/src/ui/editor.ts +50 -1
- package/src/ui/markdown.ts +258 -0
- package/src/ui/render.ts +35 -48
- package/src/ui/renderers.ts +183 -0
- package/src/ui/screen.ts +113 -16
- package/src/ui/transcript.ts +164 -35
- package/src/ui/tui.tsx +424 -79
- package/src/update.ts +262 -0
package/src/ui/configure.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// 每个模型带自己的设置。/model 可以直接切回去,换了服务或地址之前的也不会丢。
|
|
4
4
|
|
|
5
5
|
import { hasProvider, parseTokens, readSavedServices, updateEnvFile, writeSavedServices, type SavedModel, type SavedService } from "../config.ts";
|
|
6
|
-
import { EFFORTS, listModels, providerInfo, providerKind, rpmFromEnv, visionFromEnv, type ProviderKind } from "../provider.ts";
|
|
6
|
+
import { EFFORTS, isBuiltinKind, listModels, pluginProvider, pluginProviders, providerInfo, providerKind, rpmFromEnv, visionFromEnv, type ProviderKind } from "../provider.ts";
|
|
7
7
|
import { shortPath } from "./render.ts";
|
|
8
8
|
import { dim, green, red, type Screen } from "./screen.ts";
|
|
9
9
|
|
|
@@ -50,18 +50,22 @@ function visionSetting(): boolean | undefined {
|
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
function visionHint(kind:
|
|
53
|
+
function visionHint(kind: string): string {
|
|
54
54
|
const v = visionSetting();
|
|
55
|
-
return v === undefined ? `${kind
|
|
55
|
+
return v === undefined ? `${isBuiltinKind(kind) && kind !== "openai-compat" ? "yes" : "no"} (default)` : v ? "yes" : "no";
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
/**
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
]
|
|
58
|
+
/** 插件服务声明的配置项(见 ProviderDef.settings) */
|
|
59
|
+
const settingsOf = (kind: string) => pluginProvider(kind)?.def.settings ?? [];
|
|
60
|
+
|
|
61
|
+
/** 一个服务包含的变量(不含模型名);插件服务是它声明的配置项 */
|
|
62
|
+
const serviceKeys = (kind: string) =>
|
|
63
|
+
isBuiltinKind(kind)
|
|
64
|
+
? ["JADE_PROVIDER", URL_KEY[kind], KEY_KEY[kind], ...(kind === "openai-compat" ? ["OPENAI_COMPAT_EXTRA_BODY"] : [])]
|
|
65
|
+
: ["JADE_PROVIDER", ...settingsOf(kind).filter((x) => !x.model).map((x) => x.env)];
|
|
66
|
+
|
|
67
|
+
/** 保存模型名的变量;插件服务没有声明模型名时 undefined */
|
|
68
|
+
const modelKey = (kind: string): string | undefined => (isBuiltinKind(kind) ? MODEL_KEY[kind] : settingsOf(kind).find((x) => x.model)?.env);
|
|
65
69
|
|
|
66
70
|
type Env = Record<string, string | undefined>;
|
|
67
71
|
|
|
@@ -71,10 +75,14 @@ const pick = (env: Env, keys: string[]) => {
|
|
|
71
75
|
return out;
|
|
72
76
|
};
|
|
73
77
|
|
|
74
|
-
/**
|
|
78
|
+
/**
|
|
79
|
+
* 服务的类型、地址和密钥都相同的算同一个;插件服务是类型和它声明的配置项(模型名除外)都相同。
|
|
80
|
+
* 配置无效、插件服务的插件没有加载时返回 undefined
|
|
81
|
+
*/
|
|
75
82
|
function serviceId(env: Env): string | undefined {
|
|
76
83
|
try {
|
|
77
84
|
const i = providerInfo(env);
|
|
85
|
+
if (!isBuiltinKind(i.kind)) return pluginProvider(i.kind) ? [i.kind, ...serviceKeys(i.kind).slice(1).map((k) => env[k] ?? "")].join("|") : undefined;
|
|
78
86
|
return `${i.kind}|${i.baseURL ?? ""}|${env[KEY_KEY[i.kind]] ?? ""}`;
|
|
79
87
|
} catch {
|
|
80
88
|
return undefined;
|
|
@@ -109,10 +117,19 @@ function modelNames(models: SavedModel[]): string {
|
|
|
109
117
|
return models.length > 3 ? `${names} +${models.length - 3}` : names;
|
|
110
118
|
}
|
|
111
119
|
|
|
112
|
-
/** "
|
|
113
|
-
function
|
|
114
|
-
const
|
|
115
|
-
|
|
120
|
+
/** 主菜单里设置那一项的简要说明,例如 "64K out · 1M ctx · images" */
|
|
121
|
+
function settingsSummary(kind: string, contextWindow: number): string {
|
|
122
|
+
const env = process.env;
|
|
123
|
+
const images = visionSetting() ?? (isBuiltinKind(kind) && kind !== "openai-compat");
|
|
124
|
+
return [
|
|
125
|
+
env.JADE_MAX_TOKENS && `${env.JADE_MAX_TOKENS} out`,
|
|
126
|
+
env.JADE_EFFORT && `${env.JADE_EFFORT} effort`,
|
|
127
|
+
`${env.JADE_CONTEXT_WINDOW ?? contextWindow} ctx`,
|
|
128
|
+
env.JADE_RPM && `${env.JADE_RPM}/min`,
|
|
129
|
+
images ? "images" : "no images",
|
|
130
|
+
]
|
|
131
|
+
.filter(Boolean)
|
|
132
|
+
.join(" · ");
|
|
116
133
|
}
|
|
117
134
|
|
|
118
135
|
const errorText = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
|
@@ -133,14 +150,18 @@ export function configurator(opts: ConfigureOptions): Configure {
|
|
|
133
150
|
const model = providerInfo().model;
|
|
134
151
|
if (!id || !model) return;
|
|
135
152
|
const kind = providerKind();
|
|
136
|
-
|
|
137
|
-
const
|
|
138
|
-
const
|
|
153
|
+
// 写回时保留现在认不出的服务(例如提供它的插件这次没加载),不然它和它的密钥就丢了
|
|
154
|
+
const all = await readSavedServices(modelsFile);
|
|
155
|
+
const old = all.filter((s) => {
|
|
156
|
+
const sid = serviceId(s.env);
|
|
157
|
+
return sid !== undefined && (sid === id || (replacing !== undefined && sid === replacing));
|
|
158
|
+
});
|
|
159
|
+
const models = old.flatMap((s) => s.models).filter((m, i, list) => m.name !== model && list.findIndex((x) => x.name === m.name) === i);
|
|
139
160
|
const service: SavedService = {
|
|
140
161
|
env: { ...pick(process.env, serviceKeys(kind)), JADE_PROVIDER: kind },
|
|
141
162
|
models: [{ name: model, settings: pick(process.env, MODEL_SETTINGS) }, ...models],
|
|
142
163
|
};
|
|
143
|
-
await writeSavedServices(modelsFile, [service, ...
|
|
164
|
+
await writeSavedServices(modelsFile, [service, ...all.filter((s) => !old.includes(s))]);
|
|
144
165
|
}
|
|
145
166
|
|
|
146
167
|
/** 保存配置并换上新的 provider;失败时报告原因,旧的 provider 继续用 */
|
|
@@ -166,7 +187,8 @@ export function configurator(opts: ConfigureOptions): Configure {
|
|
|
166
187
|
for (const k of serviceKeys(kind)) updates[k] = s.env[k];
|
|
167
188
|
for (const k of MODEL_SETTINGS) updates[k] = m.settings[k];
|
|
168
189
|
updates.JADE_PROVIDER = kind;
|
|
169
|
-
|
|
190
|
+
const mk = modelKey(kind);
|
|
191
|
+
if (mk) updates[mk] = m.name;
|
|
170
192
|
return applyConfig(updates);
|
|
171
193
|
}
|
|
172
194
|
|
|
@@ -179,7 +201,13 @@ export function configurator(opts: ConfigureOptions): Configure {
|
|
|
179
201
|
const service = (await savedServices()).find((s) => serviceId(s.env) === id);
|
|
180
202
|
const saved = service?.models.find((m) => m.name === model);
|
|
181
203
|
if (service && saved) return useSaved(service, saved);
|
|
182
|
-
|
|
204
|
+
const kind = providerKind();
|
|
205
|
+
const mk = modelKey(kind);
|
|
206
|
+
if (!mk) {
|
|
207
|
+
screen.log(red(`${kind} is provided by plugin ${pluginProvider(kind)?.plugin ?? "(not loaded)"}, which does not declare a model setting; set the model in ${shortPath(envFile)}.`));
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
return applyConfig({ [mk]: model, JADE_CONTEXT_WINDOW: undefined });
|
|
183
211
|
}
|
|
184
212
|
|
|
185
213
|
/** 选模型:服务能列出模型时从列表里选,否则手动输入 */
|
|
@@ -202,11 +230,12 @@ export function configurator(opts: ConfigureOptions): Configure {
|
|
|
202
230
|
async function configureProvider(): Promise<boolean> {
|
|
203
231
|
const current = hasProvider() ? providerInfo() : undefined;
|
|
204
232
|
const currentId = hasProvider() ? serviceId(process.env) : undefined;
|
|
205
|
-
const kind = await screen.select(
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
);
|
|
233
|
+
const kind = await screen.select<string>("Which service should jade use?", [
|
|
234
|
+
...PROVIDERS.map((p) => ({ label: p.label, value: p.kind, hint: p.kind === current?.kind ? `${p.hint} · current` : p.hint })),
|
|
235
|
+
...pluginProviders().map((p) => ({ label: p.def.kind, value: p.def.kind, hint: `plugin ${p.plugin}${p.def.kind === current?.kind ? " · current" : ""}` })),
|
|
236
|
+
]);
|
|
209
237
|
if (!kind) return false;
|
|
238
|
+
if (!isBuiltinKind(kind)) return configurePlugin(kind);
|
|
210
239
|
const same = kind === current?.kind;
|
|
211
240
|
|
|
212
241
|
let baseURL: string | undefined = process.env[URL_KEY[kind]];
|
|
@@ -263,6 +292,45 @@ export function configurator(opts: ConfigureOptions): Configure {
|
|
|
263
292
|
return applyConfig(updates, rekeyed ? currentId : undefined);
|
|
264
293
|
}
|
|
265
294
|
|
|
295
|
+
/** 插件提供的服务:依次询问它声明的配置项,再选模型(声明了模型名时) */
|
|
296
|
+
async function configurePlugin(kind: string): Promise<boolean> {
|
|
297
|
+
const settings = settingsOf(kind);
|
|
298
|
+
const same = providerKind() === kind && hasProvider();
|
|
299
|
+
const services = await savedServices();
|
|
300
|
+
/** 已知的值:当前用的就是这个服务时取当前的,否则取最近保存过的这个服务的 */
|
|
301
|
+
const known = (k: string) => (same ? process.env[k] : services.find((s) => providerKind(s.env) === kind)?.env[k]);
|
|
302
|
+
const env: Env = { JADE_PROVIDER: kind };
|
|
303
|
+
for (const x of settings.filter((s) => !s.model)) {
|
|
304
|
+
const old = known(x.env);
|
|
305
|
+
const answer = await screen.input(x.label, {
|
|
306
|
+
mask: x.secret,
|
|
307
|
+
initial: x.secret ? undefined : old,
|
|
308
|
+
placeholder: x.secret && old ? "leave empty to keep the saved value" : x.placeholder,
|
|
309
|
+
});
|
|
310
|
+
if (answer === undefined) return false;
|
|
311
|
+
// 密钥留空表示沿用,其他的留空表示不设
|
|
312
|
+
const value = answer.trim() || (x.secret ? old : undefined);
|
|
313
|
+
if (x.required && !value) {
|
|
314
|
+
screen.log(red(`${x.label} is required.`));
|
|
315
|
+
return false;
|
|
316
|
+
}
|
|
317
|
+
env[x.env] = value;
|
|
318
|
+
}
|
|
319
|
+
const updates: Record<string, string | undefined> = { ...env, JADE_CONTEXT_WINDOW: undefined };
|
|
320
|
+
// 思考力度的取值每种服务不同
|
|
321
|
+
if (!same) updates.JADE_EFFORT = undefined;
|
|
322
|
+
const mk = modelKey(kind);
|
|
323
|
+
if (mk) {
|
|
324
|
+
const target = services.find((s) => serviceId(s.env) === serviceId(env));
|
|
325
|
+
const model = await chooseModel({ ...process.env, ...env }, same ? process.env[mk] : undefined, target?.models.map((m) => m.name));
|
|
326
|
+
if (!model) return false;
|
|
327
|
+
const saved = target?.models.find((m) => m.name === model);
|
|
328
|
+
if (target && saved) return useSaved({ ...target, env: { ...target.env, ...pick(env, serviceKeys(kind)) } }, saved);
|
|
329
|
+
updates[mk] = model;
|
|
330
|
+
}
|
|
331
|
+
return applyConfig(updates);
|
|
332
|
+
}
|
|
333
|
+
|
|
266
334
|
async function configureModel(arg: string | undefined) {
|
|
267
335
|
const info = providerInfo();
|
|
268
336
|
// 之前只有 .env 时配置的模型也记下来,之后换了不会丢
|
|
@@ -278,57 +346,59 @@ export function configurator(opts: ConfigureOptions): Configure {
|
|
|
278
346
|
const saved = others.find((o) => o.model.name === arg);
|
|
279
347
|
return void (await (saved ? useSaved(saved.service, saved.model) : switchModel(arg)));
|
|
280
348
|
}
|
|
281
|
-
//
|
|
282
|
-
|
|
283
|
-
const
|
|
284
|
-
const
|
|
285
|
-
const action = await screen.select<string>(
|
|
286
|
-
|
|
287
|
-
...(
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
{ label: "
|
|
291
|
-
{ label: "Add a service, or change the base URL or API key", value: "provider" as const, hint: info.baseURL },
|
|
292
|
-
{ label: "Output limit per reply", value: "max" as const, hint: process.env.JADE_MAX_TOKENS ? `${process.env.JADE_MAX_TOKENS} tokens` : "service default" },
|
|
293
|
-
...(efforts
|
|
294
|
-
? [{ label: "Reasoning effort", value: "effort" as const, hint: process.env.JADE_EFFORT ?? (info.kind === "anthropic" ? "high (default)" : "service default") }]
|
|
295
|
-
: []),
|
|
296
|
-
{
|
|
297
|
-
label: "Context window",
|
|
298
|
-
value: "window" as const,
|
|
299
|
-
hint: `${opts.contextWindow()} tokens${process.env.JADE_CONTEXT_WINDOW ? "" : " (default)"}`,
|
|
300
|
-
},
|
|
301
|
-
{
|
|
302
|
-
label: "Requests per minute",
|
|
303
|
-
value: "rpm" as const,
|
|
304
|
-
hint: process.env.JADE_RPM ? `${process.env.JADE_RPM}/min` : "no limit (slows down after being rate limited)",
|
|
305
|
-
},
|
|
306
|
-
{ label: "Can see images", value: "vision" as const, hint: visionHint(info.kind) },
|
|
307
|
-
...(others.length ? [{ label: "Forget a saved model", value: "forget" as const }] : []),
|
|
349
|
+
// 主菜单只管切换:保存过的模型全部直接列出(当前的在最前,然后是同一服务的),选中就换;
|
|
350
|
+
// 添加模型、当前模型的设置、删除各占一项,细节进子菜单再看。模型多于 10 个时可以打字筛选
|
|
351
|
+
const here = describeService({ env: process.env as Record<string, string>, models: [] });
|
|
352
|
+
const multi = services.length > 1;
|
|
353
|
+
const action = await screen.select<string>("Switch model", [
|
|
354
|
+
{ label: info.model, value: "current", hint: multi ? `current · ${here}` : "current" },
|
|
355
|
+
...others.map((o, i) => ({ label: o.model.name, value: `saved:${i}`, hint: multi ? describeService(o.service) : undefined })),
|
|
356
|
+
{ label: "Add a model…", value: "add", hint: "from this service or another one" },
|
|
357
|
+
{ label: `Settings for ${info.model}…`, value: "settings", hint: settingsSummary(info.kind, opts.contextWindow()) },
|
|
358
|
+
...(others.length ? [{ label: "Remove a saved model…", value: "forget" }] : []),
|
|
308
359
|
]);
|
|
309
360
|
if (action?.startsWith("saved:")) {
|
|
310
361
|
const o = others[Number(action.slice(6))]!;
|
|
311
362
|
await useSaved(o.service, o.model);
|
|
312
|
-
} else if (action === "
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
363
|
+
} else if (action === "add") {
|
|
364
|
+
const where = await screen.select<string>("Add a model from", [
|
|
365
|
+
{ label: "This service", value: "model", hint: here },
|
|
366
|
+
{ label: "Another service…", value: "provider", hint: "or change this one's base URL / API key" },
|
|
367
|
+
]);
|
|
368
|
+
if (where === "model") {
|
|
369
|
+
const saved = services.find((s) => serviceId(s.env) === currentId)?.models.map((m) => m.name);
|
|
370
|
+
const model = await chooseModel(process.env, info.model, saved);
|
|
371
|
+
if (model && model !== info.model) await switchModel(model);
|
|
372
|
+
} else if (where === "provider") await configureProvider();
|
|
373
|
+
} else if (action === "settings") await configureSettings();
|
|
374
|
+
else if (action === "forget") {
|
|
316
375
|
const owners = services.filter((s) => others.some((o) => o.service === s));
|
|
317
|
-
const gone = await pickSaved(owners, "
|
|
376
|
+
const gone = await pickSaved(owners, "Remove a model from which service?", (s, m) => !(serviceId(s.env) === currentId && m.name === info.model));
|
|
318
377
|
if (!gone) return;
|
|
319
378
|
const id = serviceId(gone.service.env);
|
|
320
|
-
//
|
|
321
|
-
const rest = (await
|
|
379
|
+
// 服务下没有模型了就连服务(和它的密钥)一起删掉;认不出的服务原样保留
|
|
380
|
+
const rest = (await readSavedServices(modelsFile))
|
|
322
381
|
.map((s) => (serviceId(s.env) === id ? { ...s, models: s.models.filter((m) => m.name !== gone.model.name) } : s))
|
|
323
382
|
.filter((s) => s.models.length > 0);
|
|
324
383
|
await writeSavedServices(modelsFile, rest);
|
|
325
|
-
screen.log(dim(`
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
384
|
+
screen.log(dim(`Removed ${gone.model.name} (${describeService(gone.service)}).`));
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** 当前模型自己的设置(切换模型时跟着换):输出上限、思考力度、上下文窗口、限速、能不能看图 */
|
|
389
|
+
async function configureSettings() {
|
|
390
|
+
const info = providerInfo();
|
|
391
|
+
const efforts = isBuiltinKind(info.kind) ? EFFORTS[info.kind] : undefined;
|
|
392
|
+
const action = await screen.select<string>(`Settings for ${info.model}`, [
|
|
393
|
+
{ label: "Output limit per reply", value: "max", hint: process.env.JADE_MAX_TOKENS ? `${process.env.JADE_MAX_TOKENS} tokens` : "service default" },
|
|
394
|
+
...(efforts
|
|
395
|
+
? [{ label: "Reasoning effort", value: "effort", hint: process.env.JADE_EFFORT ?? (info.kind === "anthropic" ? "high (default)" : "service default") }]
|
|
396
|
+
: []),
|
|
397
|
+
{ label: "Context window", value: "window", hint: `${opts.contextWindow()} tokens${process.env.JADE_CONTEXT_WINDOW ? "" : " (default)"}` },
|
|
398
|
+
{ label: "Requests per minute", value: "rpm", hint: process.env.JADE_RPM ? `${process.env.JADE_RPM}/min` : "no limit (slows down after being rate limited)" },
|
|
399
|
+
{ label: "Can see images", value: "vision", hint: visionHint(info.kind) },
|
|
400
|
+
]);
|
|
401
|
+
if (action === "max") {
|
|
332
402
|
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" });
|
|
333
403
|
if (max !== undefined && tokensInput(screen, "Output limit", max)) await applyConfig({ JADE_MAX_TOKENS: max || undefined });
|
|
334
404
|
} else if (action === "effort" && efforts) {
|
|
@@ -353,7 +423,11 @@ export function configurator(opts: ConfigureOptions): Configure {
|
|
|
353
423
|
const choice = await screen.select("Can this model see images (screenshots, image files)?", [
|
|
354
424
|
{ label: "Yes", value: "on", hint: current === true ? "current" : "the screenshot tool becomes available" },
|
|
355
425
|
{ label: "No", value: "off", hint: current === false ? "current" : "images are replaced with a note" },
|
|
356
|
-
{
|
|
426
|
+
{
|
|
427
|
+
label: "Default",
|
|
428
|
+
value: DEFAULT,
|
|
429
|
+
hint: info.kind === "openai-compat" ? "no for compatible services" : isBuiltinKind(info.kind) ? "yes" : "no for plugin services",
|
|
430
|
+
},
|
|
357
431
|
]);
|
|
358
432
|
if (choice === undefined) return;
|
|
359
433
|
// 换了 provider 立即生效:图片发不发、截图工具给不给模型都在每次请求时按它判断,不用重启
|
package/src/ui/diff.ts
CHANGED
|
@@ -110,8 +110,7 @@ export function diffStats(lines: DiffLine[]): DiffStats {
|
|
|
110
110
|
* 显示用:每行前面是行号(新增行用新文件的行号,其余用旧文件的),段与段之间用 ⋯ 分开。
|
|
111
111
|
* 超过 maxLines 行时截断
|
|
112
112
|
*/
|
|
113
|
-
export function renderDiff(before: string, after: string, maxLines = 60): string {
|
|
114
|
-
const lines = diffLines(before, after);
|
|
113
|
+
export function renderDiff(before: string, after: string, maxLines = 60, lines = diffLines(before, after)): string {
|
|
115
114
|
const parts = hunks(lines);
|
|
116
115
|
if (parts.length === 0) return dim(" (no changes)");
|
|
117
116
|
const width = String(lines.reduce((w, l) => Math.max(w, l.old ?? 0, l.new ?? 0), 0)).length;
|
package/src/ui/editor.ts
CHANGED
|
@@ -84,7 +84,7 @@ export interface Layout {
|
|
|
84
84
|
|
|
85
85
|
/** 单个字符的显示宽度;每次按键都要把整段输入过一遍,stringWidth 较慢,ASCII 直接算,其余缓存 */
|
|
86
86
|
const widths = new Map<string, number>();
|
|
87
|
-
function charWidth(ch: string): number {
|
|
87
|
+
export function charWidth(ch: string): number {
|
|
88
88
|
const c = ch.charCodeAt(0);
|
|
89
89
|
if (c >= 0x20 && c < 0x7f) return 1;
|
|
90
90
|
let w = widths.get(ch);
|
|
@@ -92,6 +92,55 @@ function charWidth(ch: string): number {
|
|
|
92
92
|
return w;
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
+
/** 光标可以停的每个位置(码点边界)在折行后的行和列,和 layout 的折法一致 */
|
|
96
|
+
function stops(value: string, width: number): { i: number; row: number; col: number }[] {
|
|
97
|
+
width = Math.max(2, width);
|
|
98
|
+
const out: { i: number; row: number; col: number }[] = [];
|
|
99
|
+
let row = 0;
|
|
100
|
+
let w = 0;
|
|
101
|
+
let i = 0;
|
|
102
|
+
// 正好停在满行末尾时算下一行开头(同 layout)
|
|
103
|
+
const stop = (at: number) => out.push(w >= width ? { i: at, row: row + 1, col: 0 } : { i: at, row, col: w });
|
|
104
|
+
for (const ch of value) {
|
|
105
|
+
if (ch === "\n") {
|
|
106
|
+
stop(i);
|
|
107
|
+
row++;
|
|
108
|
+
w = 0;
|
|
109
|
+
} else {
|
|
110
|
+
const cw = charWidth(ch);
|
|
111
|
+
if (w + cw > width) {
|
|
112
|
+
row++;
|
|
113
|
+
w = 0;
|
|
114
|
+
}
|
|
115
|
+
stop(i);
|
|
116
|
+
w += cw;
|
|
117
|
+
}
|
|
118
|
+
i += ch.length;
|
|
119
|
+
}
|
|
120
|
+
stop(value.length);
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 折行后第 row 行里最接近第 col 列(不超过它)的光标位置;没有这一行时返回 undefined */
|
|
125
|
+
export function offsetAt(value: string, width: number, row: number, col: number): number | undefined {
|
|
126
|
+
const inRow = stops(value, width).filter((s) => s.row === row);
|
|
127
|
+
if (inRow.length === 0) return undefined;
|
|
128
|
+
return (inRow.findLast((s) => s.col <= col) ?? inRow[0]!).i;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 按折行后的屏幕行上下移动光标,保持显示列(中文占两列)。已经在第一行 / 最后一行时返回 undefined,
|
|
133
|
+
* 由调用方去翻历史
|
|
134
|
+
*/
|
|
135
|
+
export function moveRow(s: EditState, width: number, by: -1 | 1): EditState | undefined {
|
|
136
|
+
const all = stops(s.value, width);
|
|
137
|
+
const here = all.find((x) => x.i === s.cursor) ?? all.at(-1)!;
|
|
138
|
+
const target = here.row + by;
|
|
139
|
+
if (target < 0 || target > all.at(-1)!.row) return undefined;
|
|
140
|
+
const cursor = offsetAt(s.value, width, target, here.col);
|
|
141
|
+
return cursor === undefined ? undefined : { ...s, cursor };
|
|
142
|
+
}
|
|
143
|
+
|
|
95
144
|
/** 按显示宽度折行(按字符折,不按词),并算出光标位置。width 至少为 2 */
|
|
96
145
|
export function layout(value: string, cursor: number, width: number): Layout {
|
|
97
146
|
width = Math.max(2, width);
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// 终端里显示模型回复的 Markdown:标题、粗体、斜体、行内代码、链接、列表、引用、分隔线、代码块和表格。
|
|
2
|
+
// 回复是流式到达的,按完整的行逐行处理:代码块要记住是否在块里,表格要攒齐所有行才能算列宽,
|
|
3
|
+
// 所以做成有状态的 markdownStream。表格和分隔线跟终端宽度有关,交出去的是按宽度现排的函数。
|
|
4
|
+
|
|
5
|
+
import stringWidth from "string-width";
|
|
6
|
+
import wrapAnsi from "wrap-ansi";
|
|
7
|
+
import { bold, cyan, dim, italic, strike, underline } from "./screen.ts";
|
|
8
|
+
|
|
9
|
+
/** 排好版的一行,或者按显示宽度现排的若干行(表格、分隔线) */
|
|
10
|
+
export type MdLine = string | { render(width: number): string[] };
|
|
11
|
+
|
|
12
|
+
export interface MarkdownStream {
|
|
13
|
+
/** 送进一个完整的行,返回可以显示的行;表格的行先攒着,等表格结束 */
|
|
14
|
+
push(line: string): MdLine[];
|
|
15
|
+
/** 回复结束:交出攒着的内容,恢复初始状态 */
|
|
16
|
+
flush(): MdLine[];
|
|
17
|
+
/** 攒着还没交出的内容,流式输出时先显示在底部 */
|
|
18
|
+
pending(): MdLine[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type Align = "left" | "center" | "right";
|
|
22
|
+
|
|
23
|
+
const FENCE = /^\s*(`{3,}|~{3,})\s*([^`\s]*)/;
|
|
24
|
+
const RULE = /^\s{0,3}([-*_])(\s*\1){2,}\s*$/;
|
|
25
|
+
const DELIMITER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
|
|
26
|
+
|
|
27
|
+
export function markdownStream(): MarkdownStream {
|
|
28
|
+
/** 所在代码块的开头标记(``` 或 ~~~),不在代码块里时为 undefined */
|
|
29
|
+
let fence: string | undefined;
|
|
30
|
+
/** 带 | 的一行:下一行是分隔行时它是表头,否则是普通的一行 */
|
|
31
|
+
let candidate: string | undefined;
|
|
32
|
+
let table: { align: Align[]; rows: string[][] } | undefined;
|
|
33
|
+
|
|
34
|
+
const endTable = (): MdLine[] => {
|
|
35
|
+
const out: MdLine[] = [];
|
|
36
|
+
if (table) out.push(tableLine(table.rows, table.align));
|
|
37
|
+
else if (candidate !== undefined) out.push(renderLine(candidate));
|
|
38
|
+
table = undefined;
|
|
39
|
+
candidate = undefined;
|
|
40
|
+
return out;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
function push(line: string): MdLine[] {
|
|
44
|
+
if (fence) {
|
|
45
|
+
const m = line.match(FENCE);
|
|
46
|
+
if (m && m[1]![0] === fence[0] && m[1]!.length >= fence.length && !m[2]) {
|
|
47
|
+
fence = undefined;
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
// 左边一条竖线和正文分开;长行折行后续行也带竖线
|
|
51
|
+
return [hanging(dim("┃ "), line, dim("┃ "))];
|
|
52
|
+
}
|
|
53
|
+
if (table) {
|
|
54
|
+
if (line.includes("|") && line.trim()) {
|
|
55
|
+
table.rows.push(cells(line));
|
|
56
|
+
return [];
|
|
57
|
+
}
|
|
58
|
+
return [...endTable(), ...push(line)];
|
|
59
|
+
}
|
|
60
|
+
if (candidate !== undefined) {
|
|
61
|
+
if (DELIMITER.test(line) && line.includes("-")) {
|
|
62
|
+
const header = cells(candidate);
|
|
63
|
+
const align = cells(line).map((c): Align => (c.startsWith(":") && c.endsWith(":") ? "center" : c.endsWith(":") ? "right" : "left"));
|
|
64
|
+
while (align.length < header.length) align.push("left");
|
|
65
|
+
table = { align, rows: [header] };
|
|
66
|
+
candidate = undefined;
|
|
67
|
+
return [];
|
|
68
|
+
}
|
|
69
|
+
return [...endTable(), ...push(line)];
|
|
70
|
+
}
|
|
71
|
+
const m = line.match(FENCE);
|
|
72
|
+
if (m) {
|
|
73
|
+
fence = m[1]!;
|
|
74
|
+
return m[2] ? [dim(`┃ ${m[2]}`)] : [];
|
|
75
|
+
}
|
|
76
|
+
if (splitCells(line).length > 1) {
|
|
77
|
+
candidate = line;
|
|
78
|
+
return [];
|
|
79
|
+
}
|
|
80
|
+
return [renderLine(line)];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return {
|
|
84
|
+
push,
|
|
85
|
+
flush() {
|
|
86
|
+
const out = endTable();
|
|
87
|
+
fence = undefined;
|
|
88
|
+
return out;
|
|
89
|
+
},
|
|
90
|
+
pending: () => (table ? [tableLine(table.rows, table.align)] : candidate !== undefined ? [renderLine(candidate)] : []),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 整段 Markdown 排好版(测试和一次性显示用) */
|
|
95
|
+
export function renderMarkdown(text: string, width: number): string[] {
|
|
96
|
+
const md = markdownStream();
|
|
97
|
+
const out = [...text.split("\n").flatMap((l) => md.push(l)), ...md.flush()];
|
|
98
|
+
return out.flatMap((l) => (typeof l === "string" ? [l] : l.render(width)));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 代码块和表格以外的一行 */
|
|
102
|
+
function renderLine(line: string): MdLine {
|
|
103
|
+
if (RULE.test(line)) return { render: (width) => [dim("─".repeat(Math.max(1, Math.min(width, 80))))] };
|
|
104
|
+
const heading = line.match(/^\s{0,3}(#{1,6})\s+(.*?)(\s+#+)?\s*$/);
|
|
105
|
+
if (heading) {
|
|
106
|
+
const text = inline(heading[2]!);
|
|
107
|
+
return heading[1]!.length === 1 ? bold(underline(text)) : bold(text);
|
|
108
|
+
}
|
|
109
|
+
const quote = line.match(/^\s*>\s?(.*)$/);
|
|
110
|
+
if (quote) return hanging(dim("│ "), inline(quote[1]!), dim("│ "));
|
|
111
|
+
const item = line.match(/^(\s*)([-*+])\s+(\[[ xX]\]\s+)?(.*)$/);
|
|
112
|
+
// 列表项折行时续行和正文对齐
|
|
113
|
+
if (item) {
|
|
114
|
+
const box = item[3] ? (item[3][1] === " " ? "☐ " : "☑ ") : "";
|
|
115
|
+
return hanging(`${item[1]}${box ? "" : cyan("• ")}${box}`, inline(item[4]!));
|
|
116
|
+
}
|
|
117
|
+
const ordered = line.match(/^(\s*)(\d+[.)])\s+(.*)$/);
|
|
118
|
+
if (ordered) return hanging(`${ordered[1]}${cyan(ordered[2]!)} `, inline(ordered[3]!));
|
|
119
|
+
return inline(line);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 行内格式:`代码`、**粗体**、*斜体*、~~删除线~~、[链接](url)、反斜杠转义。代码里的内容原样显示。
|
|
124
|
+
* 行内代码先换成占位符,粗体、斜体处理完再换回来,"**用 `foo()` 实现**" 这样跨过代码的粗体才认得出
|
|
125
|
+
*/
|
|
126
|
+
export function inline(text: string): string {
|
|
127
|
+
const codes: string[] = [];
|
|
128
|
+
return text
|
|
129
|
+
.replace(/`+[^`]*?`+/g, (code) => `\x01${codes.push(cyan(code.replace(/^`+ ?|`+$/g, "").replace(/ $/, ""))) - 1}\x01`)
|
|
130
|
+
.replace(/\\([\\`*_{}[\]()#+\-.!|~<>])/g, (_, c: string) => `\0${c.charCodeAt(0)}\0`)
|
|
131
|
+
.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_, label: string, url: string) =>
|
|
132
|
+
label === url ? underline(url) : `${underline(label)}${dim(` (${url})`)}`,
|
|
133
|
+
)
|
|
134
|
+
.replace(/<(https?:\/\/[^>\s]+)>/g, (_, url: string) => underline(url))
|
|
135
|
+
.replace(/\*\*(?=\S)(.+?)(?<=\S)\*\*|(?<![\w])__(?=\S)(.+?)(?<=\S)__(?![\w])/g, (_, a?: string, b?: string) => bold(a ?? b!))
|
|
136
|
+
.replace(/(?<![*\w])\*(?=[^\s*])(.+?)(?<=[^\s*])\*(?![*\w])|(?<![_\w])_(?=[^\s_])(.+?)(?<=[^\s_])_(?![_\w])/g, (_, a?: string, b?: string) => italic(a ?? b!))
|
|
137
|
+
.replace(/~~(?=\S)(.+?)(?<=\S)~~/g, (_, s: string) => strike(s))
|
|
138
|
+
.replace(/\0(\d+)\0/g, (_, c: string) => String.fromCharCode(Number(c)))
|
|
139
|
+
.replace(/\x01(\d+)\x01/g, (_, i: string) => codes[Number(i)]!);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 制表符换成空格,按 stop 列一个制表位对齐(按显示宽度算,忽略颜色)。终端按 8 列显示 tab,按 0 列算宽度会对不齐、超宽 */
|
|
143
|
+
export function expandTabs(text: string, stop = 4): string {
|
|
144
|
+
if (!text.includes("\t")) return text;
|
|
145
|
+
return text
|
|
146
|
+
.split("\n")
|
|
147
|
+
.map((line) => {
|
|
148
|
+
if (!line.includes("\t")) return line;
|
|
149
|
+
let out = "";
|
|
150
|
+
let col = 0;
|
|
151
|
+
const parts = line.split("\t");
|
|
152
|
+
parts.forEach((p, i) => {
|
|
153
|
+
out += p;
|
|
154
|
+
col += stringWidth(p);
|
|
155
|
+
if (i < parts.length - 1) {
|
|
156
|
+
const n = stop - (col % stop);
|
|
157
|
+
out += " ".repeat(n);
|
|
158
|
+
col += n;
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
return out;
|
|
162
|
+
})
|
|
163
|
+
.join("\n");
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 折行时续行缩进到 head 之后(列表项的正文、代码块的竖线);rest 是续行开头显示的内容,宽度和 head 相同 */
|
|
167
|
+
function hanging(head: string, body: string, rest = " ".repeat(stringWidth(head))): MdLine {
|
|
168
|
+
return {
|
|
169
|
+
render: (width) => {
|
|
170
|
+
const room = Math.max(1, width - stringWidth(head));
|
|
171
|
+
return wrapAnsi(expandTabs(body), room, { hard: true, trim: false })
|
|
172
|
+
.split("\n")
|
|
173
|
+
// 折行处留下的行尾空格看不见,去掉免得多占一列
|
|
174
|
+
.map((r, i) => (i === 0 ? head : rest) + r.trimEnd());
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 按没转义、不在行内代码里的 | 拆开一行 */
|
|
180
|
+
function splitCells(line: string): string[] {
|
|
181
|
+
const out: string[] = [];
|
|
182
|
+
let cell = "";
|
|
183
|
+
let code = false;
|
|
184
|
+
for (let i = 0; i < line.length; i++) {
|
|
185
|
+
const c = line[i]!;
|
|
186
|
+
if (c === "\\" && line[i + 1] === "|") {
|
|
187
|
+
cell += "|";
|
|
188
|
+
i++;
|
|
189
|
+
} else if (c === "`") {
|
|
190
|
+
code = !code;
|
|
191
|
+
cell += c;
|
|
192
|
+
} else if (c === "|" && !code) {
|
|
193
|
+
out.push(cell);
|
|
194
|
+
cell = "";
|
|
195
|
+
} else cell += c;
|
|
196
|
+
}
|
|
197
|
+
out.push(cell);
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 表格一行的各个单元格,去掉两端的 | */
|
|
202
|
+
function cells(line: string): string[] {
|
|
203
|
+
const parts = splitCells(line.trim());
|
|
204
|
+
if (parts.length > 1 && parts[0]!.trim() === "") parts.shift();
|
|
205
|
+
if (parts.length > 1 && parts.at(-1)!.trim() === "") parts.pop();
|
|
206
|
+
return parts.map((c) => c.trim());
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function tableLine(rows: string[][], align: Align[]): MdLine {
|
|
210
|
+
const shown = rows.map((r, i) => r.map((c) => (i === 0 ? bold(inline(c)) : inline(c))));
|
|
211
|
+
return { render: (width) => renderTable(shown, align, width) };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* 画带边框的表格。放不下时按比例收窄较宽的列、单元格内折行;
|
|
216
|
+
* 窄到每列连 3 列都分不到时,改成每行一段「表头: 值」
|
|
217
|
+
*/
|
|
218
|
+
function renderTable(rows: string[][], align: Align[], width: number): string[] {
|
|
219
|
+
const n = Math.max(...rows.map((r) => r.length));
|
|
220
|
+
const grid = rows.map((r) => Array.from({ length: n }, (_, i) => r[i] ?? ""));
|
|
221
|
+
const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => stringWidth(r[i]!))));
|
|
222
|
+
const room = width - (3 * n + 1);
|
|
223
|
+
if (room < 3 * n) {
|
|
224
|
+
const [head, ...body] = grid;
|
|
225
|
+
return body.flatMap((r, k) => [
|
|
226
|
+
...(k ? [""] : []),
|
|
227
|
+
...r.flatMap((c, i) => wrapAnsi(`${head![i]}${dim(":")} ${c}`, Math.max(1, width), { hard: true }).split("\n")),
|
|
228
|
+
]);
|
|
229
|
+
}
|
|
230
|
+
// 从最窄的列开始,能放下的列按原宽,放不下的平分剩下的宽度
|
|
231
|
+
const widths = [...natural];
|
|
232
|
+
if (natural.reduce((a, b) => a + b, 0) > room) {
|
|
233
|
+
let left = room;
|
|
234
|
+
let open = n;
|
|
235
|
+
for (const i of [...natural.keys()].sort((a, b) => natural[a]! - natural[b]!)) {
|
|
236
|
+
const share = Math.floor(left / open);
|
|
237
|
+
widths[i] = Math.min(natural[i]!, share);
|
|
238
|
+
left -= widths[i]!;
|
|
239
|
+
open--;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const pad = (s: string, w: number, a: Align) => {
|
|
243
|
+
const gap = w - stringWidth(s);
|
|
244
|
+
if (a === "right") return " ".repeat(gap) + s;
|
|
245
|
+
if (a === "center") return " ".repeat(Math.floor(gap / 2)) + s + " ".repeat(Math.ceil(gap / 2));
|
|
246
|
+
return s + " ".repeat(gap);
|
|
247
|
+
};
|
|
248
|
+
const border = (l: string, m: string, r: string) => dim(l + widths.map((w) => "─".repeat(w + 2)).join(m) + r);
|
|
249
|
+
const row = (r: string[]) => {
|
|
250
|
+
const parts = r.map((c, i) => wrapAnsi(c, widths[i]!, { hard: true, trim: true }).split("\n"));
|
|
251
|
+
const height = Math.max(...parts.map((p) => p.length));
|
|
252
|
+
return Array.from({ length: height }, (_, k) =>
|
|
253
|
+
dim("│ ") + parts.map((p, i) => pad(p[k] ?? "", widths[i]!, align[i] ?? "left")).join(dim(" │ ")) + dim(" │"),
|
|
254
|
+
);
|
|
255
|
+
};
|
|
256
|
+
const [head, ...body] = grid;
|
|
257
|
+
return [border("┌", "┬", "┐"), ...row(head!), border("├", "┼", "┤"), ...body.flatMap(row), border("└", "┴", "┘")];
|
|
258
|
+
}
|