@cobia/pi-onward 0.5.2 → 0.5.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/CHANGELOG.md +8 -0
- package/README.md +24 -4
- package/package.json +1 -1
- package/src/actions/pi.ts +3 -3
- package/src/actions/registry.ts +7 -7
- package/src/extension/command-display.ts +217 -0
- package/src/extension/command.ts +210 -226
- package/src/extension/settings.ts +2 -4
- package/src/extension/text.ts +96 -85
- package/src/policy/config.ts +3 -3
- package/src/policy/delay.ts +4 -4
- package/src/policy/policy.ts +2 -2
- package/src/policy/rules.ts +20 -22
- package/src/runtime/recovery.ts +32 -29
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.5.3]
|
|
4
|
+
|
|
5
|
+
- 菜单、帮助、Tab 补全、报错和查看输出改用三个插件共用的显示约定。
|
|
6
|
+
- 菜单改为按使用顺序排列,`status` 放在第一项;两个作用域入口合并为 `--scope …`,根菜单不再超过 pi 选择框的 10 项。
|
|
7
|
+
- 菜单和 status 的标题改为“图标 命令路径 · 状态”,恢复进行中时图标与状态栏一致。
|
|
8
|
+
- 命令、配置和动作的报错改为中文,命令报错改用 error 级别并指向对应动作的帮助。
|
|
9
|
+
- 开关统一称为“自动恢复”,帮助按固定的节顺序排列并按终端宽度折行。
|
|
10
|
+
|
|
3
11
|
## [0.5.2]
|
|
4
12
|
|
|
5
13
|
- 提供基于规则与阶段的自动恢复,支持命令和动作调用。
|
package/README.md
CHANGED
|
@@ -58,6 +58,25 @@ onward 处理两类失败:Pi 明确以错误结束,或者正常结束但没
|
|
|
58
58
|
|
|
59
59
|
`status` 显示命中的规则、当前阶段、连续失败次数、已启动续跑次数和动作结果;查询不会改变恢复状态,也不会把这些信息发给模型
|
|
60
60
|
|
|
61
|
+
菜单按使用顺序列出动作,标题显示当前状态和默认写入的配置层,图标与[状态栏](#状态栏)相同;开启且待命时是 ⏩,关闭或没有可用规则时是 💤,配置无效时是 🛑:
|
|
62
|
+
|
|
63
|
+
```text
|
|
64
|
+
⏩ onward · 开,1 条规则生效 · 默认改全局配置
|
|
65
|
+
|
|
66
|
+
status 查看当前状态
|
|
67
|
+
show 查看配置参数、来源和规则
|
|
68
|
+
actions 查看已加载的恢复动作
|
|
69
|
+
on 启用自动恢复
|
|
70
|
+
off 停用自动恢复
|
|
71
|
+
set … 修改配置参数
|
|
72
|
+
unset … 移除指定配置项
|
|
73
|
+
--scope … 只看、只改某一层配置
|
|
74
|
+
reset 重置配置参数,保留规则
|
|
75
|
+
--help 显示帮助
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
名称后的 `…` 表示选中后只把命令填进输入框,补完参数再回车;选中 `--scope …` 后输入框是 `/onward --scope` 加一个空格,用 Tab 选择 `global` 或 `project` 后回车,打开只看、只改那一层的菜单。菜单、`--help` 的动作表和 Tab 补全的顺序与说明相同
|
|
79
|
+
|
|
61
80
|
`off`、`on` 默认修改全局配置并立即生效,同时取消当前恢复。项目级开关优先于全局;只修改当前项目时,使用 `/onward --scope project off` 或 `on`。启用开关不会立即发起模型请求
|
|
62
81
|
|
|
63
82
|
`onward.stop` 只结束本轮恢复;需要持续停用自动恢复时,使用 `/onward off`
|
|
@@ -257,14 +276,14 @@ onward 处理两类失败:Pi 明确以错误结束,或者正常结束但没
|
|
|
257
276
|
| 命令 | 作用 |
|
|
258
277
|
| :--- | :--- |
|
|
259
278
|
| `/onward` | 打开状态和配置菜单,默认修改全局配置 |
|
|
279
|
+
| `/onward status` | 查看当前阶段、失败数、已启动续跑数及动作结果 |
|
|
280
|
+
| `/onward show [rules]` | 查看已加载配置、来源、规则和文件位置;`rules` 只列规则 |
|
|
260
281
|
| `/onward actions` | 查看已加载的具名动作及注册失败原因 |
|
|
261
|
-
| `/onward off` | 停用自动恢复并取消当前恢复过程 |
|
|
262
282
|
| `/onward on` | 启用自动恢复,不立即请求模型 |
|
|
263
|
-
| `/onward
|
|
283
|
+
| `/onward off` | 停用自动恢复并取消当前恢复过程 |
|
|
264
284
|
| `/onward set 字段=值 …` | 修改上限、动作时限或全局 quietStartup,全部参数先校验 |
|
|
265
|
-
| `/onward show [rules]` | 查看已加载配置、来源、规则和文件位置;`rules` 只列规则 |
|
|
266
|
-
| `/onward status` | 查看当前阶段、失败数、已启动续跑数及动作结果 |
|
|
267
285
|
| `/onward unset 字段 …` | 删除指定配置项,采用下层值或默认值 |
|
|
286
|
+
| `/onward reset` | 删除本层开关、恢复上限和 quietStartup,保留规则及其他手写内容;重置运行状态 |
|
|
268
287
|
| `/onward --help` | 查看完整用法;单个动作的帮助用 `/onward <动作> --help` |
|
|
269
288
|
|
|
270
289
|
修改或查看指定层时,把 `--scope` 写在动作前,例如 `/onward --scope project set maxFailures=5`。`status`、`actions` 不接受 `--scope`
|
|
@@ -289,6 +308,7 @@ onward 处理两类失败:Pi 明确以错误结束,或者正常结束但没
|
|
|
289
308
|
- `set` 的每个参数必须是完整的 `字段=值`,恰好一个等号、两侧非空;不能拆成 `字段 = 值`。`unset` 只接受裸字段名。重复字段均报错,即使值相同。
|
|
290
309
|
- 帮助只豁免 `set/unset` 完全没填参数的情况。已填写的参数仍须合法:`set --help` 显示帮助,`set maxFailures=0 --help` 报错。
|
|
291
310
|
- 结构错误从左到右只报告第一个;结构通过后汇总未知字段、重复字段、非法值及作用域限制。帮助和报错都不写配置、不重载文件、不改变恢复状态。
|
|
311
|
+
- 报错点名出错的参数并指向对应动作的帮助,例如 `onward:maxFailures 必须是 1~1000 的整数。查看用法:/onward set --help`;多处错误时首行写出数量,每处一行。
|
|
292
312
|
|
|
293
313
|
Tab 补全沿用同一套校验:当前参数可以尚未输入完整;前面已由空格或 Tab 结束的参数若有错误,先修正才会提供后续候选。输入 `--help` 后不再补全
|
|
294
314
|
|
package/package.json
CHANGED
package/src/actions/pi.ts
CHANGED
|
@@ -19,7 +19,7 @@ export function piActions(pi: Pick<ExtensionAPI, "getCommands" | "sendUserMessag
|
|
|
19
19
|
execute(params, context) {
|
|
20
20
|
const prompt = String(params.prompt ?? "继续");
|
|
21
21
|
if (prompt.includes("{taskPrompt}") && !context.taskPrompt?.trim())
|
|
22
|
-
return { kind: "failed", message: "
|
|
22
|
+
return { kind: "failed", message: "没有可用的任务提示词,无法展开 {taskPrompt}" };
|
|
23
23
|
const vars: Record<string, string> = {
|
|
24
24
|
failures: String(context.failures),
|
|
25
25
|
rule: context.rule,
|
|
@@ -56,11 +56,11 @@ export function piActions(pi: Pick<ExtensionAPI, "getCommands" | "sendUserMessag
|
|
|
56
56
|
if (context.signal.aborted) return { kind: "cancelled", message: "命令分派已取消" };
|
|
57
57
|
const name = String(params.name);
|
|
58
58
|
if (name === "onward" || name.startsWith("onward:"))
|
|
59
|
-
return { kind: "failed", message: "
|
|
59
|
+
return { kind: "failed", message: "不能自动调用 onward 自己的控制命令" };
|
|
60
60
|
if (!pi.getCommands().some((command) => command.source === "extension" && command.name === name))
|
|
61
61
|
return {
|
|
62
62
|
kind: "failed",
|
|
63
|
-
message:
|
|
63
|
+
message: `扩展命令 /${name} 未加载,没有向模型发送文字`,
|
|
64
64
|
};
|
|
65
65
|
pi.sendUserMessage(`/${name}${params.args ? ` ${params.args}` : ""}`, { expandPromptTemplates: true });
|
|
66
66
|
return { kind: "dispatched", message: `已分派 /${name};完成情况由目标插件报告` };
|
package/src/actions/registry.ts
CHANGED
|
@@ -28,10 +28,10 @@ export class ActionRegistry {
|
|
|
28
28
|
const add = (candidate: unknown) => {
|
|
29
29
|
try {
|
|
30
30
|
if (!isDefinition(candidate))
|
|
31
|
-
throw new Error("
|
|
31
|
+
throw new Error("动作定义无效:需要 name、parameters、phase、modes 和 execute");
|
|
32
32
|
if (seen.has(candidate.name)) {
|
|
33
33
|
this.actions.delete(candidate.name);
|
|
34
|
-
throw new Error("
|
|
34
|
+
throw new Error("动作名称重复");
|
|
35
35
|
}
|
|
36
36
|
seen.add(candidate.name);
|
|
37
37
|
const definition = {
|
|
@@ -41,11 +41,11 @@ export class ActionRegistry {
|
|
|
41
41
|
};
|
|
42
42
|
const validate = ajv.compile(definition.parameters);
|
|
43
43
|
if ((validate as ValidateFunction & { $async?: boolean }).$async)
|
|
44
|
-
throw new Error("
|
|
44
|
+
throw new Error("参数 Schema 必须同步校验");
|
|
45
45
|
this.actions.set(definition.name, { definition, validate });
|
|
46
46
|
} catch (error) {
|
|
47
47
|
const name = isRecord(candidate) && typeof candidate.name === "string" ? candidate.name : "<unnamed>";
|
|
48
|
-
this.errors.push(
|
|
48
|
+
this.errors.push(`动作 ${name} 注册失败:${errorText(error)}`);
|
|
49
49
|
}
|
|
50
50
|
};
|
|
51
51
|
for (const definition of builtins) add(definition);
|
|
@@ -78,16 +78,16 @@ export class ActionRegistry {
|
|
|
78
78
|
if (!rule.enabled) continue;
|
|
79
79
|
for (const stage of rule.stages) {
|
|
80
80
|
const problem = this.check(stage.action);
|
|
81
|
-
if (problem) errors.push(
|
|
81
|
+
if (problem) errors.push(`规则 "${rule.name}" 从第 ${stage.minFailures} 次失败起:${problem}`);
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
return errors;
|
|
85
85
|
}
|
|
86
86
|
check(call: ActionCall): string | undefined {
|
|
87
87
|
const registered = this.get(call.use);
|
|
88
|
-
if (!registered) return
|
|
88
|
+
if (!registered) return `动作 ${call.use} 未加载或注册失败`;
|
|
89
89
|
if (!registered.validate(call.with ?? {}))
|
|
90
|
-
return
|
|
90
|
+
return `${call.use} 的参数无效:${registered.validate.errors?.map((error) => `${error.instancePath || "/"} ${error.message}`).join(";")}`;
|
|
91
91
|
return undefined;
|
|
92
92
|
}
|
|
93
93
|
parameters(call: ActionCall): Parameters {
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 命令显示约定的共用实现:菜单、帮助、Tab 补全、报错、查看输出和通知。
|
|
3
|
+
* pi-sequel、pi-onward、pi-wecom-aibot 各有一份,内容必须完全相同,由根目录测试检查。
|
|
4
|
+
*/
|
|
5
|
+
import { visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
6
|
+
|
|
7
|
+
/** 菜单、帮助的「动作」表和 Tab 候选共用的一项。 */
|
|
8
|
+
export interface Entry {
|
|
9
|
+
/** 要输入的词,例如 run、--scope、--help。 */
|
|
10
|
+
name: string;
|
|
11
|
+
/** 动词开头的短语,不超过 16 个汉字,不带句号。 */
|
|
12
|
+
description: string;
|
|
13
|
+
/** menu:打开子菜单;input:只把命令填进输入框,补完参数再回车;不写:直接执行。 */
|
|
14
|
+
opens?: "menu" | "input";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type Row = readonly [label: string, value: string];
|
|
18
|
+
type Block = readonly string[] | readonly Row[];
|
|
19
|
+
|
|
20
|
+
export const HELP_ENTRY: Entry = { name: "--help", description: "显示帮助" };
|
|
21
|
+
|
|
22
|
+
const MARKS = { menu: " ›", input: " …" } as const;
|
|
23
|
+
/** 帮助正文最多 78 列,宽终端里也保持好读。 */
|
|
24
|
+
const HELP_WIDTH = 78;
|
|
25
|
+
/** 终端再窄也按 20 列排版,避免折成一两个字一行。 */
|
|
26
|
+
const MIN_WIDTH = 20;
|
|
27
|
+
/** 说明列窄于这个宽度时,说明另起一行。 */
|
|
28
|
+
const MIN_TEXT_WIDTH = 16;
|
|
29
|
+
|
|
30
|
+
export function entryLabel(entry: Entry): string {
|
|
31
|
+
return entry.opens ? `${entry.name}${MARKS[entry.opens]}` : entry.name;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 名称补齐到本组最宽的一项再空两格;说明里的换行和连续空白合成一个空格。 */
|
|
35
|
+
export function columns(rows: readonly Row[]): string[] {
|
|
36
|
+
const width = keyWidth(rows);
|
|
37
|
+
return rows.map(([label, value]) => {
|
|
38
|
+
const text = value.replace(/\s+/g, " ").trim();
|
|
39
|
+
return text ? `${label}${" ".repeat(width - visibleWidth(label))} ${text}` : label;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 菜单、帮助和 Tab 用同一组标签,名称、标记、说明和间隔都一样。 */
|
|
44
|
+
export function entryLabels(entries: readonly Entry[]): string[] {
|
|
45
|
+
return columns(entries.map((entry) => [entryLabel(entry), entry.description]));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 标题:图标 命令路径 · 状态[ · 补充]。 */
|
|
49
|
+
export function title(icon: string, path: string, ...segments: (string | undefined)[]): string {
|
|
50
|
+
return [`${icon} ${path}`, ...segments.filter((segment): segment is string => !!segment)].join(" · ");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 单行通知:命令名:内容。 */
|
|
54
|
+
export function message(command: string, text: string): string {
|
|
55
|
+
return `${command}:${text}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 报错:一处问题写成一行;多处问题首行写数量,每处一行;最后指向最具体的帮助。 */
|
|
59
|
+
export function commandError(command: string, problems: readonly string[], help: string): string {
|
|
60
|
+
const items = problems.map((problem) => problem.trim().replace(/。+$/, ""));
|
|
61
|
+
const hint = `查看用法:${help}`;
|
|
62
|
+
if (items.length === 1) return `${command}:${items[0]}。${hint}`;
|
|
63
|
+
return [`${command}:${items.length} 处错误,未执行`, ...items.map((item) => ` ${item}`), hint].join("\n");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface MenuItem<T> extends Entry {
|
|
67
|
+
value: T;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 弹出菜单,返回选中的项;Esc 返回 undefined。 */
|
|
71
|
+
export async function chooseEntry<T>(
|
|
72
|
+
select: (heading: string, options: string[]) => Promise<string | undefined>,
|
|
73
|
+
heading: string,
|
|
74
|
+
items: readonly MenuItem<T>[],
|
|
75
|
+
): Promise<MenuItem<T> | undefined> {
|
|
76
|
+
const labels = entryLabels(items);
|
|
77
|
+
const picked = await select(heading, labels);
|
|
78
|
+
const index = picked === undefined ? -1 : labels.indexOf(picked);
|
|
79
|
+
return index < 0 ? undefined : items[index];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 两列对齐:缩进两格,键列补齐到所有分组中最宽的一项再空两格;值里的换行在值列对齐;分组之间空一行。 */
|
|
83
|
+
export function table(...groups: readonly (readonly Row[])[]): string[] {
|
|
84
|
+
const shown = groups.filter((rows) => rows.length);
|
|
85
|
+
const width = keyWidth(shown.flat());
|
|
86
|
+
return shown.flatMap((rows, index) => [...(index ? [""] : []), ...rowLines(rows, width)]);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 通知文字可用的列数:pi 在通知左右各留一列。不在终端里或不知道宽度时返回 undefined,不预先折行。 */
|
|
90
|
+
export function noticeWidth(mode: string | undefined): number | undefined {
|
|
91
|
+
const columns = mode === "tui" ? process.stdout.columns : undefined;
|
|
92
|
+
return columns ? Math.max(MIN_WIDTH, columns - 2) : undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
type Level = "info" | "warning" | "error";
|
|
96
|
+
|
|
97
|
+
/** notify 用到的那部分 pi 上下文。 */
|
|
98
|
+
export interface NoticeContext {
|
|
99
|
+
mode?: string;
|
|
100
|
+
ui: { notify(message: string, type?: Level): void };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 命令的通知都从这里发出:多行文字按通知宽度预先折行,避免宿主再折一次;单行交给宿主折行。 */
|
|
104
|
+
export function notify(ctx: NoticeContext, text: string, level: Level = "info"): void {
|
|
105
|
+
const width = noticeWidth(ctx.mode);
|
|
106
|
+
ctx.ui.notify(width !== undefined && text.includes("\n") ? wrapLines(text, width) : text, level);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** 按宽度预先折行:表格行的续行对齐到值列,其他行对齐到行首空格。宽度为 Infinity 时不折行。 */
|
|
110
|
+
function wrapLines(text: string, width: number): string {
|
|
111
|
+
return text
|
|
112
|
+
.split("\n")
|
|
113
|
+
.flatMap((line) => {
|
|
114
|
+
const indent = /^ */.exec(line)![0];
|
|
115
|
+
const content = line.slice(indent.length);
|
|
116
|
+
const row = indent ? /^(\S(?:.*?\S)?)( {2,})(\S.*)$/.exec(content) : null;
|
|
117
|
+
if (!row) return wrap(indent, content, width);
|
|
118
|
+
const head = `${indent}${row[1]}${row[2]}`;
|
|
119
|
+
// 窄终端把标签与说明分行,避免把说明挤成逐字换行。
|
|
120
|
+
return width - visibleWidth(head) < MIN_TEXT_WIDTH
|
|
121
|
+
? [...wrap(indent, row[1], width), ...wrap(`${indent} `, row[3], width)]
|
|
122
|
+
: wrap(head, row[3], width);
|
|
123
|
+
})
|
|
124
|
+
.join("\n");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface HelpPage {
|
|
128
|
+
/** 命令路径,例如 sequel run。 */
|
|
129
|
+
path: string;
|
|
130
|
+
description: string;
|
|
131
|
+
/** 完整用法,每种写法一行,例如 /sequel run [字段=值 …] [--help]。 */
|
|
132
|
+
usage: readonly string[];
|
|
133
|
+
notes?: readonly string[];
|
|
134
|
+
actions?: readonly Entry[];
|
|
135
|
+
fields?: readonly Row[];
|
|
136
|
+
options?: readonly Row[];
|
|
137
|
+
/** 插件特有的节,排在选项和示例之间。 */
|
|
138
|
+
extra?: readonly (readonly [heading: string, body: Block])[];
|
|
139
|
+
examples?: readonly string[];
|
|
140
|
+
syntax?: readonly string[];
|
|
141
|
+
more?: readonly string[];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 帮助的节按固定顺序排列,没有内容的节省略。给出宽度时预先折行,最宽 78 列,续行与正文对齐。 */
|
|
145
|
+
export function helpText(page: HelpPage, width?: number): string {
|
|
146
|
+
const available = width === undefined ? Number.POSITIVE_INFINITY : Math.min(HELP_WIDTH, width);
|
|
147
|
+
const sections: (readonly [heading: string, body: Block | undefined])[] = [
|
|
148
|
+
["说明", page.notes],
|
|
149
|
+
["动作", page.actions?.map((entry): Row => [entryLabel(entry), entry.description])],
|
|
150
|
+
["字段", page.fields],
|
|
151
|
+
["选项", page.options],
|
|
152
|
+
...(page.extra ?? []),
|
|
153
|
+
["示例", page.examples],
|
|
154
|
+
["语法", page.syntax],
|
|
155
|
+
["详细帮助", page.more],
|
|
156
|
+
];
|
|
157
|
+
const body = sections.flatMap(([heading, block]) =>
|
|
158
|
+
block?.length ? ["", heading, ...(isRows(block) ? table(block) : block.map((line) => ` ${line}`))] : [],
|
|
159
|
+
);
|
|
160
|
+
return [
|
|
161
|
+
...wrap("", `${page.path} — ${page.description}`, available),
|
|
162
|
+
...page.usage.flatMap((line, index) => wrap(index ? " " : "用法:", line, available)),
|
|
163
|
+
...(body.length ? wrapLines(body.join("\n"), available).split("\n") : []),
|
|
164
|
+
].join("\n");
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** 查看输出:首行是标题,正文各块之间空一行;表格块的键列在整份输出里对齐。折行由 notify 负责。 */
|
|
168
|
+
export function report(headline: string, blocks: readonly Block[]): string {
|
|
169
|
+
const shown = blocks.filter((block) => block.length);
|
|
170
|
+
const labels = keyWidth(shown.filter(isRows).flat());
|
|
171
|
+
const lines = [headline, ...shown.flatMap((block) => ["", ...(isRows(block) ? rowLines(block, labels) : block)])];
|
|
172
|
+
return lines.join("\n");
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function isRows(block: Block): block is readonly Row[] {
|
|
176
|
+
return typeof block[0] !== "string";
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function keyWidth(rows: readonly Row[]): number {
|
|
180
|
+
return Math.max(0, ...rows.map(([label]) => visibleWidth(label)));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function rowLines(rows: readonly Row[], width: number): string[] {
|
|
184
|
+
return rows.flatMap(([label, value]) => {
|
|
185
|
+
const [first, ...rest] = value.split("\n");
|
|
186
|
+
const head = first ? ` ${label}${" ".repeat(width - visibleWidth(label))} ${first}` : ` ${label}`;
|
|
187
|
+
return [head, ...rest.map((line) => ` ${" ".repeat(width)} ${line}`)];
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** 行首不放的标点和行末不放的开括号。 */
|
|
192
|
+
const NO_LINE_START = /^[,。;:!?、)」』》】”’]/u;
|
|
193
|
+
const NO_LINE_END = /[(「『《【“‘]$/u;
|
|
194
|
+
|
|
195
|
+
/** 放不下时少折两格:行首的标点挂到上一行末尾,行末的开括号移到下一行,都不会超宽。 */
|
|
196
|
+
function wrap(prefix: string, text: string, width: number): string[] {
|
|
197
|
+
if (!text) return [prefix.trimEnd()];
|
|
198
|
+
const padding = visibleWidth(prefix);
|
|
199
|
+
const available = Math.max(1, width - padding);
|
|
200
|
+
if (visibleWidth(text) <= available) return [`${prefix}${text}`];
|
|
201
|
+
const lines = wrapTextWithAnsi(text, available > 8 ? available - 2 : available);
|
|
202
|
+
for (let index = 1; index < lines.length; index++) {
|
|
203
|
+
const head = NO_LINE_START.exec(lines[index]!)?.[0];
|
|
204
|
+
if (head) {
|
|
205
|
+
lines[index - 1] += head;
|
|
206
|
+
lines[index] = lines[index]!.slice(head.length);
|
|
207
|
+
}
|
|
208
|
+
const tail = NO_LINE_END.exec(lines[index - 1]!)?.[0];
|
|
209
|
+
if (tail && lines[index - 1]!.length > tail.length) {
|
|
210
|
+
lines[index - 1] = lines[index - 1]!.slice(0, -tail.length);
|
|
211
|
+
lines[index] = `${tail}${lines[index]}`;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return lines
|
|
215
|
+
.filter((line, index) => line || !index)
|
|
216
|
+
.map((line, index) => `${index ? " ".repeat(padding) : prefix}${line}`);
|
|
217
|
+
}
|