@uncarved/jade 0.4.1 → 0.4.2
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 +279 -279
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/session.js +7 -0
- package/dist/session.js.map +1 -1
- package/package.json +3 -3
- package/plugins/mentions/candidates.ts +14 -0
- package/plugins/mentions/index.ts +2 -2
- package/plugins/models/configure.ts +25 -1
- package/plugins/models/index.ts +62 -5
- package/plugins/models/plugin.json +1 -1
- package/plugins/models/provider.ts +31 -9
- package/plugins/models/saved.ts +1 -1
- package/plugins/screenshot/browser.ts +1 -1
- package/plugins/shell/shell.ts +33 -7
- package/plugins/steer/index.ts +1 -1
- package/plugins/todo/index.ts +6 -10
- package/plugins/tui/frontend.ts +6 -2
- package/plugins/tui/markdown.ts +10 -8
- package/plugins/tui/mentions.ts +10 -0
- package/plugins/tui/transcript.ts +14 -17
- package/plugins/tui/tui.ts +13 -12
- package/plugins/tui/width.ts +240 -0
- package/plugins-dist/mentions/candidates.js +6 -0
- package/plugins-dist/mentions/index.js +2 -2
- package/plugins-dist/models/configure.js +22 -1
- package/plugins-dist/models/index.js +58 -4
- package/plugins-dist/models/plugin.json +2 -1
- package/plugins-dist/models/provider.js +23 -8
- package/plugins-dist/models/saved.js +1 -1
- package/plugins-dist/screenshot/browser.js +1 -1
- package/plugins-dist/shell/shell.js +21 -7
- package/plugins-dist/steer/index.js +1 -1
- package/plugins-dist/todo/index.js +3 -8
- package/plugins-dist/tui/frontend.js +5 -2
- package/plugins-dist/tui/markdown.js +11 -9
- package/plugins-dist/tui/mentions.js +6 -0
- package/plugins-dist/tui/transcript.js +9 -12
- package/plugins-dist/tui/tui.js +10 -9
- package/plugins-dist/tui/vendor.js +1388 -1088
- package/plugins-dist/tui/width.js +219 -0
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/src/api.ts +1 -1
- package/src/session.ts +5 -0
package/plugins/shell/shell.ts
CHANGED
|
@@ -112,6 +112,7 @@ export function shellTools(opts: ShellOptions): ShellTools {
|
|
|
112
112
|
`Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` +
|
|
113
113
|
`Each call starts a fresh shell: cd and environment variables do not persist. ` +
|
|
114
114
|
`Default timeout ${DEFAULT_TIMEOUT_MS / 1000}s (timeout_ms, max ${MAX_TIMEOUT_MS / 1000}s). ` +
|
|
115
|
+
`Output beyond ${MAX_OUTPUT_CHARS} characters (stdout and stderr together) keeps only the start and end. ` +
|
|
115
116
|
"Set run_in_background for servers, watchers and other long-running commands: it returns an id at once, " +
|
|
116
117
|
"then read new output with bash_output and stop it with kill_shell. " +
|
|
117
118
|
"Never start interactive programs. Prefer read_file/grep/glob over cat/grep/find.",
|
|
@@ -145,12 +146,13 @@ export function shellTools(opts: ShellOptions): ShellTools {
|
|
|
145
146
|
};
|
|
146
147
|
signal.addEventListener("abort", kill, { once: true });
|
|
147
148
|
try {
|
|
148
|
-
const [
|
|
149
|
+
const [out, err, code] = await Promise.all([
|
|
149
150
|
collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text }), true, killed.done),
|
|
150
151
|
collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text }), true, killed.done),
|
|
151
152
|
Promise.race([proc.exited, killed.done.then(() => null)]),
|
|
152
153
|
]);
|
|
153
154
|
signal.throwIfAborted();
|
|
155
|
+
const [stdout, stderr] = clipStreams(out, err);
|
|
154
156
|
const parts = [
|
|
155
157
|
timedOut
|
|
156
158
|
? `Timed out after ${timeout}ms (killed). If it needs longer, raise timeout_ms (max ${MAX_TIMEOUT_MS / 1000}s); for servers and watchers use run_in_background.`
|
|
@@ -269,12 +271,13 @@ export async function capture(executable: string, env: NodeJS.ProcessEnv | undef
|
|
|
269
271
|
}, opts.timeoutMs);
|
|
270
272
|
opts.signal?.addEventListener("abort", kill, { once: true });
|
|
271
273
|
try {
|
|
272
|
-
const [
|
|
274
|
+
const [out, err, code] = await Promise.all([
|
|
273
275
|
collect(proc.stdout, onOutput, true, killed.done),
|
|
274
276
|
collect(proc.stderr, onOutput, true, killed.done),
|
|
275
277
|
Promise.race([proc.exited, killed.done.then(() => null)]),
|
|
276
278
|
]);
|
|
277
279
|
opts.signal?.throwIfAborted();
|
|
280
|
+
const [stdout, stderr] = clipStreams(out, err);
|
|
278
281
|
return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join("\n"), timedOut };
|
|
279
282
|
} finally {
|
|
280
283
|
clearTimeout(timer);
|
|
@@ -396,11 +399,18 @@ function giveUp(): { start(): void; done: Promise<void> } {
|
|
|
396
399
|
return { start, done };
|
|
397
400
|
}
|
|
398
401
|
|
|
402
|
+
/** 读到的输出:total 不超过 MAX_OUTPUT_CHARS 时 head + tail 就是全部,否则 head 是开头一半、tail 至少是结尾一半 */
|
|
403
|
+
interface Collected {
|
|
404
|
+
head: string;
|
|
405
|
+
tail: string;
|
|
406
|
+
total: number;
|
|
407
|
+
}
|
|
408
|
+
|
|
399
409
|
/**
|
|
400
|
-
*
|
|
401
|
-
*
|
|
410
|
+
* 边读边截,输出再多也只占几倍 MAX_OUTPUT_CHARS 的内存;最后截成多长由 clipStreams 按 stdout、stderr 合计决定。
|
|
411
|
+
* keep 为 false 时只推给 onChunk,不累积
|
|
402
412
|
*/
|
|
403
|
-
async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string) => void, keep = true, stop?: Promise<void>): Promise<
|
|
413
|
+
async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string) => void, keep = true, stop?: Promise<void>): Promise<Collected> {
|
|
404
414
|
const half = MAX_OUTPUT_CHARS / 2;
|
|
405
415
|
const decoder = new TextDecoder();
|
|
406
416
|
let head = "";
|
|
@@ -434,8 +444,24 @@ async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string
|
|
|
434
444
|
}
|
|
435
445
|
const rest = decoder.decode();
|
|
436
446
|
if (rest) add(rest);
|
|
437
|
-
|
|
438
|
-
|
|
447
|
+
return { head, tail, total };
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** 截到最多 limit 个字符:保留开头和结尾各一半,中间截掉 */
|
|
451
|
+
function clipCollected(c: Collected, limit: number): string {
|
|
452
|
+
const full = c.total <= MAX_OUTPUT_CHARS ? c.head + c.tail : undefined;
|
|
453
|
+
if (c.total <= limit) return full!.trimEnd();
|
|
454
|
+
const half = Math.floor(limit / 2);
|
|
455
|
+
const head = (full ?? c.head).slice(0, half);
|
|
456
|
+
const tail = half > 0 ? (full ?? c.tail).slice(-half) : "";
|
|
457
|
+
return `${head}\n… (${c.total - 2 * half} characters omitted) …\n${tail}`.trimEnd();
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** stdout、stderr 合计最多 MAX_OUTPUT_CHARS:短的那路最多占一半,剩下的都给另一路 */
|
|
461
|
+
function clipStreams(out: Collected, err: Collected): [string, string] {
|
|
462
|
+
const small = Math.min(out.total, err.total, MAX_OUTPUT_CHARS / 2);
|
|
463
|
+
const outLimit = out.total <= err.total ? small : MAX_OUTPUT_CHARS - small;
|
|
464
|
+
return [clipCollected(out, outLimit), clipCollected(err, MAX_OUTPUT_CHARS - outLimit)];
|
|
439
465
|
}
|
|
440
466
|
|
|
441
467
|
/** 保留开头和结尾,中间截掉 */
|
package/plugins/steer/index.ts
CHANGED
package/plugins/todo/index.ts
CHANGED
|
@@ -39,7 +39,7 @@ export function todoTool(onChange?: (todos: Todo[]) => void): Tool {
|
|
|
39
39
|
description:
|
|
40
40
|
"Maintain a task list for multi-step work. Each call replaces the whole list. " +
|
|
41
41
|
"Use it when a task has three or more steps: write the plan, mark one item in_progress while working on it, " +
|
|
42
|
-
"and mark items completed as soon as they are done. Skip it for simple tasks.",
|
|
42
|
+
"and mark items completed as soon as they are done, including the last one before you reply. Skip it for simple tasks.",
|
|
43
43
|
inputSchema: {
|
|
44
44
|
type: "object",
|
|
45
45
|
properties: {
|
|
@@ -88,7 +88,7 @@ const bold = (text: string): Span => ({ text, style: "bold" });
|
|
|
88
88
|
const args = (input: unknown) => (input !== null && typeof input === "object" ? input : {}) as Record<string, unknown>;
|
|
89
89
|
const list = (input: unknown) => (Array.isArray(args(input).todos) ? (args(input).todos as Todo[]) : []);
|
|
90
90
|
|
|
91
|
-
//
|
|
91
|
+
// 这一轮跑的时候完整的清单在输入框上方(ctx.panel),对话里每次更新只占一行,展开(ctrl+o、点击)看当时的完整清单。
|
|
92
92
|
// 前端没有那个位置时,对话里的一行照样能展开
|
|
93
93
|
export const todoRenderer: ToolRenderer = {
|
|
94
94
|
tool: "todo_write",
|
|
@@ -99,7 +99,7 @@ export const todoRenderer: ToolRenderer = {
|
|
|
99
99
|
result: ({ isError }) => (isError ? undefined : null),
|
|
100
100
|
};
|
|
101
101
|
|
|
102
|
-
/**
|
|
102
|
+
/** 输入框上方的一块:还有没做完的项时显示,全部做完或清空时去掉(一轮结束时也去掉) */
|
|
103
103
|
export function todoPanel(todos: Todo[]): Text | undefined {
|
|
104
104
|
if (todos.every((t) => t?.status === "completed")) return undefined;
|
|
105
105
|
const p = progressOf(todos);
|
|
@@ -112,12 +112,8 @@ export default definePlugin({
|
|
|
112
112
|
},
|
|
113
113
|
session(ctx) {
|
|
114
114
|
ctx.kernel.tool(todoTool((todos) => ctx.panel?.(todoPanel(todos))));
|
|
115
|
-
//
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const todos = latestTodos(ctx.session.state().messages);
|
|
119
|
-
if (Array.isArray(todos)) ctx.panel?.(todoPanel(todos));
|
|
120
|
-
});
|
|
121
|
-
}
|
|
115
|
+
// 清单只在这一轮跑的时候显示:模型做完常常不再把最后一项标完成,留着就一直挡在输入框上方。
|
|
116
|
+
// 一轮结束就收起,完整清单在对话里那一行展开看
|
|
117
|
+
if (ctx.panel) ctx.session.afterTurn(() => ctx.panel?.(undefined));
|
|
122
118
|
},
|
|
123
119
|
});
|
package/plugins/tui/frontend.ts
CHANGED
|
@@ -374,7 +374,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
|
|
|
374
374
|
},
|
|
375
375
|
// 打了补全的触发字符(例如 @)时向登记它的插件要候选
|
|
376
376
|
completions: completionList,
|
|
377
|
-
complete: async (trigger) => (await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates()) ?? [],
|
|
377
|
+
complete: async (trigger, dir) => (await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates(dir)) ?? [],
|
|
378
378
|
interrupt: () => ready && interrupt(),
|
|
379
379
|
unqueue: () => takeBack(),
|
|
380
380
|
exit: () => void quit(0),
|
|
@@ -405,7 +405,11 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
|
|
|
405
405
|
|
|
406
406
|
let current: Session | undefined;
|
|
407
407
|
let unsubscribe: (() => void) | undefined;
|
|
408
|
-
const canRetry = () =>
|
|
408
|
+
const canRetry = () => {
|
|
409
|
+
// state 每次都拷贝整段历史,只取一次
|
|
410
|
+
const state = current?.state;
|
|
411
|
+
return state?.phase === "idle" && state.messages.at(-1)?.role === "user";
|
|
412
|
+
};
|
|
409
413
|
|
|
410
414
|
const view: Transcript = transcript({
|
|
411
415
|
screen,
|
package/plugins/tui/markdown.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// 回复是流式到达的,按完整的行逐行处理:代码块要记住是否在块里,表格要攒齐所有行才能算列宽,
|
|
3
3
|
// 所以做成有状态的 markdownStream。表格和分隔线跟终端宽度有关,交出去的是按宽度现排的函数。
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import { visibleWidth, wrapLines, wrapText } from "./width.ts";
|
|
6
6
|
import wrapAnsi from "wrap-ansi";
|
|
7
7
|
import { bold, cyan, dim, italic, strike, underline } from "./screen.ts";
|
|
8
8
|
|
|
@@ -128,12 +128,14 @@ const WRAP = { hard: true, trim: false } as const;
|
|
|
128
128
|
*/
|
|
129
129
|
export function wrapRows(text: string, width: number): string[] {
|
|
130
130
|
const expanded = expandTabs(text);
|
|
131
|
+
const grouped = wrapLines(expanded, width);
|
|
132
|
+
if (grouped) return grouped.flatMap((rows) => rows.map((r, i) => (i === 0 ? r : softRow(r))));
|
|
131
133
|
// 整段一起折:颜色可能跨行,分开折会丢掉后面几行的颜色
|
|
132
134
|
const rows = wrapAnsi(expanded, width, WRAP).split("\n");
|
|
133
135
|
const logical = expanded.split("\n");
|
|
134
136
|
if (rows.length === logical.length) return rows;
|
|
135
137
|
// 每个原来的行占了几行:放得下的占一行,放不下的单独折一次数出来(颜色不占宽度,不影响在哪里折)
|
|
136
|
-
const counts = logical.map((l) => (
|
|
138
|
+
const counts = logical.map((l) => (visibleWidth(l) <= width ? 1 : wrapAnsi(l, width, WRAP).split("\n").length));
|
|
137
139
|
if (counts.reduce((a, b) => a + b, 0) !== rows.length) return rows;
|
|
138
140
|
let at = 0;
|
|
139
141
|
for (const n of counts) {
|
|
@@ -196,7 +198,7 @@ export function expandTabs(text: string, stop = 4): string {
|
|
|
196
198
|
const parts = line.split("\t");
|
|
197
199
|
parts.forEach((p, i) => {
|
|
198
200
|
out += p;
|
|
199
|
-
col +=
|
|
201
|
+
col += visibleWidth(p);
|
|
200
202
|
if (i < parts.length - 1) {
|
|
201
203
|
const n = stop - (col % stop);
|
|
202
204
|
out += " ".repeat(n);
|
|
@@ -209,12 +211,12 @@ export function expandTabs(text: string, stop = 4): string {
|
|
|
209
211
|
}
|
|
210
212
|
|
|
211
213
|
/** 折行时续行缩进到 head 之后(列表项的正文、代码块的竖线);rest 是续行开头显示的内容,宽度和 head 相同 */
|
|
212
|
-
function hanging(head: string, body: string, rest = " ".repeat(
|
|
214
|
+
function hanging(head: string, body: string, rest = " ".repeat(visibleWidth(head))): MdLine {
|
|
213
215
|
return {
|
|
214
216
|
render: (width) => {
|
|
215
|
-
const indent =
|
|
217
|
+
const indent = visibleWidth(head);
|
|
216
218
|
const room = Math.max(1, width - indent);
|
|
217
|
-
const rows =
|
|
219
|
+
const rows = wrapText(expandTabs(body), room);
|
|
218
220
|
// 折行处留下的行尾空格看不见,去掉免得多占一列;去掉了几个记在续行的记号里,复制时补回去
|
|
219
221
|
return rows.map((r, i) => (i === 0 ? head + r.trimEnd() : softRow(rest + r.trimEnd(), rows[i - 1]!.length - rows[i - 1]!.trimEnd().length, indent)));
|
|
220
222
|
},
|
|
@@ -263,7 +265,7 @@ function tableLine(rows: string[][], align: Align[]): MdLine {
|
|
|
263
265
|
function renderTable(rows: string[][], align: Align[], width: number): string[] {
|
|
264
266
|
const n = Math.max(...rows.map((r) => r.length));
|
|
265
267
|
const grid = rows.map((r) => Array.from({ length: n }, (_, i) => r[i] ?? ""));
|
|
266
|
-
const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) =>
|
|
268
|
+
const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => visibleWidth(r[i]!))));
|
|
267
269
|
const room = width - (3 * n + 1);
|
|
268
270
|
if (room < 3 * n) {
|
|
269
271
|
const [head, ...body] = grid;
|
|
@@ -285,7 +287,7 @@ function renderTable(rows: string[][], align: Align[], width: number): string[]
|
|
|
285
287
|
}
|
|
286
288
|
}
|
|
287
289
|
const pad = (s: string, w: number, a: Align) => {
|
|
288
|
-
const gap = w -
|
|
290
|
+
const gap = w - visibleWidth(s);
|
|
289
291
|
if (a === "right") return " ".repeat(gap) + s;
|
|
290
292
|
if (a === "center") return " ".repeat(Math.floor(gap / 2)) + s + " ".repeat(Math.ceil(gap / 2));
|
|
291
293
|
return s + " ".repeat(gap);
|
package/plugins/tui/mentions.ts
CHANGED
|
@@ -10,6 +10,16 @@ export function mentionAt(value: string, cursor: number, triggers: readonly stri
|
|
|
10
10
|
return { trigger: m[1]!, start: cursor - m[2]!.length - m[1]!.length, query: m[2]!.replace(/^"/, "") };
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
/**
|
|
14
|
+
* 输入的是 ../、./、~/、/ 或盘符开头的路径时,最后一个 / 之前的部分(含 /,反斜杠换成 /):候选改成现列这个目录下一层。
|
|
15
|
+
* 预先列好的候选只有工作目录里的相对路径,这些路径在里面找不到。其他情况返回 undefined
|
|
16
|
+
*/
|
|
17
|
+
export function mentionDir(query: string): string | undefined {
|
|
18
|
+
const q = query.replaceAll("\\", "/");
|
|
19
|
+
if (!/^(\.{1,2}\/|~\/|\/|[A-Za-z]:\/)/.test(q)) return undefined;
|
|
20
|
+
return q.slice(0, q.lastIndexOf("/") + 1);
|
|
21
|
+
}
|
|
22
|
+
|
|
13
23
|
/** 补全后的文本:触发字符加候选,含空白的加引号 */
|
|
14
24
|
export const mentionText = (trigger: string, p: string) => (/\s/.test(p) ? `${trigger}"${p}"` : `${trigger}${p}`);
|
|
15
25
|
|
|
@@ -13,8 +13,6 @@ export type Notice = Parameters<Parameters<Runtime["subscribe"]>[0]>[0];
|
|
|
13
13
|
export interface TranscriptOptions {
|
|
14
14
|
screen: Screen;
|
|
15
15
|
cwd: string;
|
|
16
|
-
/** 子 Agent 的用量在它自己的日志里,从这里读;不给就不统计子 Agent 的用量 */
|
|
17
|
-
readLog?(sessionId: string): Promise<LogEvent[]>;
|
|
18
16
|
/** 模型的上下文窗口(状态栏显示用) */
|
|
19
17
|
contextWindow(): number;
|
|
20
18
|
/** 每次回复的输出上限(回复被截断时的提示用);没有时说是服务的默认值 */
|
|
@@ -80,16 +78,12 @@ export function transcript(opts: TranscriptOptions): Transcript {
|
|
|
80
78
|
if (u) screen.status({ spent: { input: usage.inputTokens, output: usage.outputTokens } });
|
|
81
79
|
};
|
|
82
80
|
/**
|
|
83
|
-
* 一个事件带来的用量:模型回复;插件事件 data 里的 usage(压缩时的总结调用、auto
|
|
84
|
-
*
|
|
81
|
+
* 一个事件带来的用量:模型回复;插件事件 data 里的 usage(压缩时的总结调用、auto 模式的审查这类插件自己发的请求,
|
|
82
|
+
* 还有 jade/task 记下的子 Agent 的用量)
|
|
85
83
|
*/
|
|
86
|
-
|
|
84
|
+
function countUsage(e: LogEvent) {
|
|
87
85
|
if (e.type === "model.responded") addUsage((e as LogEvent<"model.responded">).data.usage);
|
|
88
86
|
else if (e.origin.by === "plugin") addUsage(usageOf((e.data as { usage?: unknown } | null)?.usage));
|
|
89
|
-
else if (e.type === "tool.completed") {
|
|
90
|
-
const child = (e as LogEvent<"tool.completed">).data.child;
|
|
91
|
-
if (child && opts.readLog) for (const c of await opts.readLog(child.sessionId).catch(() => [])) await countUsage(c);
|
|
92
|
-
}
|
|
93
87
|
}
|
|
94
88
|
|
|
95
89
|
/**
|
|
@@ -220,10 +214,14 @@ export function transcript(opts: TranscriptOptions): Transcript {
|
|
|
220
214
|
const shown = (t: string) => (t.startsWith("/") ? cyan(`› ${t}`) : `\n${bold(`› ${t.replace(/\n/g, "\n ")}`)}`);
|
|
221
215
|
// 很长的输入(粘贴的日志)只显示开头几行,其余折叠起来,点击或 ctrl+o 展开
|
|
222
216
|
const lines = text.split("\n");
|
|
223
|
-
if (lines.length <= MAX_ECHO_LINES)
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
217
|
+
if (lines.length <= MAX_ECHO_LINES) screen.log(shown(text));
|
|
218
|
+
else {
|
|
219
|
+
// 展开时接着显示其余的行
|
|
220
|
+
const rest = lines.slice(ECHO_HEAD_LINES);
|
|
221
|
+
screen.log(`${shown(lines.slice(0, ECHO_HEAD_LINES).join("\n"))}\n ${dim(`… +${rest.length} lines`)}`, { details: rest.map((l) => ` ${l}`).join("\n") });
|
|
222
|
+
}
|
|
223
|
+
// 消息前后都空一行,和上一段、下一段回复分开(只空前面的话,消息看起来像是下面回复的标题)
|
|
224
|
+
if (!text.startsWith("/")) screen.log("");
|
|
227
225
|
},
|
|
228
226
|
reset() {
|
|
229
227
|
for (const k of Object.keys(usage) as (keyof Usage)[]) usage[k] = 0;
|
|
@@ -307,7 +305,7 @@ export function transcript(opts: TranscriptOptions): Transcript {
|
|
|
307
305
|
return;
|
|
308
306
|
case "model.responded": {
|
|
309
307
|
const d = e.data as EventDataMap["model.responded"];
|
|
310
|
-
|
|
308
|
+
countUsage(e);
|
|
311
309
|
showContext(e as LogEvent<"model.responded">);
|
|
312
310
|
if (!replaying) finishSpeed(d.usage);
|
|
313
311
|
for (const b of d.content) if (b.kind === "tool_use") toolNames.set(b.id, b.name);
|
|
@@ -366,7 +364,6 @@ export function transcript(opts: TranscriptOptions): Transcript {
|
|
|
366
364
|
}
|
|
367
365
|
case "tool.completed": {
|
|
368
366
|
const d = e.data as EventDataMap["tool.completed"];
|
|
369
|
-
void countUsage(e);
|
|
370
367
|
activity("Working");
|
|
371
368
|
doneProgress(d.toolUseId);
|
|
372
369
|
const call = calls.get(d.toolUseId);
|
|
@@ -437,7 +434,7 @@ export function transcript(opts: TranscriptOptions): Transcript {
|
|
|
437
434
|
*/
|
|
438
435
|
function renderPluginEvent(e: LogEvent) {
|
|
439
436
|
if (e.origin.by !== "plugin") return;
|
|
440
|
-
|
|
437
|
+
countUsage(e);
|
|
441
438
|
const found = opts.eventRenderer?.(e.type);
|
|
442
439
|
if (!found) return renderPluginNotice(e);
|
|
443
440
|
let shown: ReturnType<EventRenderer["render"]>;
|
|
@@ -463,7 +460,7 @@ export function transcript(opts: TranscriptOptions): Transcript {
|
|
|
463
460
|
async function replay(events: LogEvent[], show: boolean) {
|
|
464
461
|
if (!show) {
|
|
465
462
|
for (const e of events) {
|
|
466
|
-
|
|
463
|
+
countUsage(e);
|
|
467
464
|
if (e.type === "model.responded") showContext(e as LogEvent<"model.responded">);
|
|
468
465
|
}
|
|
469
466
|
return;
|
package/plugins/tui/tui.ts
CHANGED
|
@@ -24,8 +24,8 @@ import {
|
|
|
24
24
|
useState,
|
|
25
25
|
useSyncExternalStore,
|
|
26
26
|
} from "./vendor.ts";
|
|
27
|
-
import
|
|
28
|
-
import { mentionAt, mentionText, rankPaths } from "./mentions.ts";
|
|
27
|
+
import { visibleWidth } from "./width.ts";
|
|
28
|
+
import { mentionAt, mentionDir, mentionText, rankPaths } from "./mentions.ts";
|
|
29
29
|
import { charWidth, edit, empty, layout, moveRow, offsetAt, type EditState } from "./editor.ts";
|
|
30
30
|
import { expandTabs, markdownStream, softInfo, visibleRow, wrapRows, type MdLine } from "./markdown.ts";
|
|
31
31
|
import { cells, FRAME_MS, Mascot, moodOf, nextChange, title } from "./mascot.ts";
|
|
@@ -75,8 +75,8 @@ export interface TuiHandlers {
|
|
|
75
75
|
exit(): void;
|
|
76
76
|
/** 登记了的补全(completions@1):触发字符、占位提示里的说明、候选菜单下的说明;每次渲染时取 */
|
|
77
77
|
completions?(): CompletionInfo[];
|
|
78
|
-
/** 打了触发字符时的候选(像路径一样用 / 分层,目录以 /
|
|
79
|
-
complete?(trigger: string): Promise<string[]>;
|
|
78
|
+
/** 打了触发字符时的候选(像路径一样用 / 分层,目录以 / 结尾);每次开始输入一段新的补全时取一次,dir 见 mentionDir */
|
|
79
|
+
complete?(trigger: string, dir?: string): Promise<string[]>;
|
|
80
80
|
/** 输入框有焦点时按下 jade 自己不用的 ctrl+<字母>、alt+<字母或数字>、shift+tab(见 keySpec);返回 true 表示有插件处理了 */
|
|
81
81
|
key?(spec: string): boolean;
|
|
82
82
|
}
|
|
@@ -187,12 +187,12 @@ const elapsed = (t: Thinking) =>
|
|
|
187
187
|
|
|
188
188
|
/** 按显示宽度取 text 末尾最多 cols 列;截掉了开头时以 … 开头 */
|
|
189
189
|
export function tail(text: string, cols: number): string {
|
|
190
|
-
if (
|
|
190
|
+
if (visibleWidth(text) <= cols) return text;
|
|
191
191
|
const chars = [...text];
|
|
192
192
|
let out = "";
|
|
193
193
|
let w = 1;
|
|
194
194
|
for (let i = chars.length - 1; i >= 0; i--) {
|
|
195
|
-
const cw =
|
|
195
|
+
const cw = visibleWidth(chars[i]!);
|
|
196
196
|
if (w + cw > cols) break;
|
|
197
197
|
out = chars[i] + out;
|
|
198
198
|
w += cw;
|
|
@@ -213,7 +213,7 @@ function thinkingRow(t: Thinking, width: number): string {
|
|
|
213
213
|
?.trim()
|
|
214
214
|
.replace(/\s+/g, " ");
|
|
215
215
|
// 留出 " · "、" ▸" 和一列余量
|
|
216
|
-
const room = width -
|
|
216
|
+
const room = width - visibleWidth(label) - 6;
|
|
217
217
|
return dim(latest && room >= 8 ? `${label} · ${tail(latest, room)}` : `${label}…`);
|
|
218
218
|
}
|
|
219
219
|
|
|
@@ -1405,7 +1405,7 @@ const TONE: Record<NonNullable<StatusSegment["tone"]>, string> = { ok: "green",
|
|
|
1405
1405
|
export function fitSegments(segments: Segment[], width: number): Segment[] {
|
|
1406
1406
|
const kept = segments.map((s) => ({ ...s }));
|
|
1407
1407
|
const total = () =>
|
|
1408
|
-
kept.reduce((n, s, i) => n +
|
|
1408
|
+
kept.reduce((n, s, i) => n + visibleWidth(s.text) + (i ? 3 : 0), 0);
|
|
1409
1409
|
const steps = kept
|
|
1410
1410
|
.flatMap((s) => [
|
|
1411
1411
|
...(s.short !== undefined && s.shortAt !== undefined
|
|
@@ -1500,7 +1500,7 @@ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
|
|
|
1500
1500
|
/** 一行提示:按宽度选第一个放得下的写法,都放不下时用最后一个并截断 */
|
|
1501
1501
|
function Hint({ variants, width }: { variants: string[]; width: number }) {
|
|
1502
1502
|
const text =
|
|
1503
|
-
variants.find((v) =>
|
|
1503
|
+
variants.find((v) => visibleWidth(v) <= width) ?? variants.at(-1)!;
|
|
1504
1504
|
return h(Text, { dimColor: true, wrap: "truncate-end" }, text);
|
|
1505
1505
|
}
|
|
1506
1506
|
|
|
@@ -1825,19 +1825,20 @@ function Prompt({
|
|
|
1825
1825
|
const notice = getNotice();
|
|
1826
1826
|
|
|
1827
1827
|
const mentioning = mention?.trigger;
|
|
1828
|
-
|
|
1828
|
+
const mentionScope = mention ? mentionDir(mention.query) : undefined;
|
|
1829
|
+
// 每次开始输入一段新的补全、或者在工作目录外换了目录时重新取一次:候选可能已经变了(例如文件)
|
|
1829
1830
|
useEffect(() => {
|
|
1830
1831
|
if (mentioning === undefined || !handlers.complete) return;
|
|
1831
1832
|
let live = true;
|
|
1832
1833
|
setPaths([]);
|
|
1833
|
-
handlers.complete(mentioning).then(
|
|
1834
|
+
handlers.complete(mentioning, mentionScope).then(
|
|
1834
1835
|
(p) => void (live && setPaths(p)),
|
|
1835
1836
|
() => {},
|
|
1836
1837
|
);
|
|
1837
1838
|
return () => {
|
|
1838
1839
|
live = false;
|
|
1839
1840
|
};
|
|
1840
|
-
}, [mentioning]);
|
|
1841
|
+
}, [mentioning, mentionScope]);
|
|
1841
1842
|
const completion = completions.find((c) => c.trigger === mentioning);
|
|
1842
1843
|
// 结果多时只显示选中项附近的几条
|
|
1843
1844
|
const first = around(hit, results.length, menuRows);
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// 显示宽度和折行的快路径。string-width / wrap-ansi 对每个非 ASCII 字符都要过 Intl.Segmenter 和 Unicode 属性正则,
|
|
2
|
+
// 中文一行要零点几毫秒(ASCII 的上百倍),长对话恢复、缩放、展开详情时会卡。
|
|
3
|
+
// 常用字符(ASCII、拉丁补充、标点符号、制表符、CJK、假名、谚文音节、全角)各自成一个字素簇,宽度可以逐个码点查表;
|
|
4
|
+
// 只含这些字符和 jade 自己的颜色码时走这里,结果和库逐字节一致(见 test/tui-width.test.ts),其余情况交回给库。
|
|
5
|
+
|
|
6
|
+
import stringWidth from "string-width";
|
|
7
|
+
import wrapAnsi from "wrap-ansi";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 不会和前后字符组成一个字素簇、NFC 规范化不改变的码点:组合附加符号、零宽字符、变体选择符、谚文字母、代理项都不在里面。
|
|
11
|
+
* 2329、232A 规范化后会变成 3008、3009,302A–302F、3099–309A 是组合附加符号。导出给测试用
|
|
12
|
+
*/
|
|
13
|
+
export function standalone(c: number): boolean {
|
|
14
|
+
if (c < 0x7f) return c >= 0x20;
|
|
15
|
+
if (c < 0x2010) return c >= 0xa0 && c <= 0xff && c !== 0xad;
|
|
16
|
+
if (c <= 0x2027) return true;
|
|
17
|
+
if (c >= 0x2030 && c <= 0x205e) return true;
|
|
18
|
+
if (c >= 0x2190 && c <= 0x27bf) return c !== 0x2329 && c !== 0x232a;
|
|
19
|
+
if (c >= 0x2e80 && c <= 0x2fdf) return true;
|
|
20
|
+
if (c >= 0x3000 && c <= 0x30ff) return !(c >= 0x302a && c <= 0x302f) && c !== 0x3099 && c !== 0x309a;
|
|
21
|
+
if (c >= 0x3100 && c <= 0x9fff) return true;
|
|
22
|
+
if (c >= 0xac00 && c <= 0xd7a3) return true;
|
|
23
|
+
return (c >= 0xff01 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** standalone 码点的宽度加一(0 表示还没算),按需用 string-width 算出来存着 */
|
|
27
|
+
const widths = new Uint8Array(0x10000);
|
|
28
|
+
function charWidth(c: number): number {
|
|
29
|
+
let w = widths[c]!;
|
|
30
|
+
if (w === 0) widths[c] = w = stringWidth(String.fromCharCode(c)) + 1;
|
|
31
|
+
return w - 1;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 颜色码:jade 的样式只用单个参数的 SGR(screen.ts 的 paint) */
|
|
35
|
+
const SGR = /\x1b\[(\d{1,2})m/y;
|
|
36
|
+
|
|
37
|
+
/** 从 i 开始的颜色码,返回它的参数和长度;不是 jade 用的那几种时返回 undefined */
|
|
38
|
+
function sgrAt(s: string, i: number): { code: number; length: number } | undefined {
|
|
39
|
+
SGR.lastIndex = i;
|
|
40
|
+
const m = SGR.exec(s);
|
|
41
|
+
if (!m) return undefined;
|
|
42
|
+
const code = Number(m[1]);
|
|
43
|
+
return CLOSE_OF.has(code) || RESETS.has(code) ? { code, length: m[0].length } : undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 样式码 → 关闭码(wrap-ansi 经 ansi-styles 得到的同一张表) */
|
|
47
|
+
const CLOSE_OF = new Map<number, number>([
|
|
48
|
+
[1, 22], [2, 22], [3, 23], [4, 24], [9, 29],
|
|
49
|
+
...[30, 31, 32, 33, 34, 35, 36, 37, 90, 91, 92, 93, 94, 95, 96, 97].map((c) => [c, 39] as [number, number]),
|
|
50
|
+
]);
|
|
51
|
+
const RESETS = new Set([22, 23, 24, 29, 39]);
|
|
52
|
+
|
|
53
|
+
/** 快路径能处理时的显示宽度(忽略颜色码),否则 undefined */
|
|
54
|
+
function fastWidth(s: string): number | undefined {
|
|
55
|
+
let w = 0;
|
|
56
|
+
for (let i = 0; i < s.length; i++) {
|
|
57
|
+
const c = s.charCodeAt(i);
|
|
58
|
+
if (c === 0x1b) {
|
|
59
|
+
const m = sgrAt(s, i);
|
|
60
|
+
if (!m) return undefined;
|
|
61
|
+
i += m.length - 1;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (!standalone(c)) return undefined;
|
|
65
|
+
w += c < 0x7f ? 1 : charWidth(c);
|
|
66
|
+
}
|
|
67
|
+
return w;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 显示宽度,和 string-width 一致 */
|
|
71
|
+
export function visibleWidth(s: string): number {
|
|
72
|
+
return fastWidth(s) ?? stringWidth(s);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface Token {
|
|
76
|
+
value: string;
|
|
77
|
+
width: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface Word {
|
|
81
|
+
tokens: Token[];
|
|
82
|
+
value: string;
|
|
83
|
+
width: number;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 按空格拆成词;颜色码跟着所在的词。有快路径处理不了的字符时返回 undefined */
|
|
87
|
+
function words(line: string): Word[] | undefined {
|
|
88
|
+
let word: Word = { tokens: [], value: "", width: 0 };
|
|
89
|
+
const out = [word];
|
|
90
|
+
for (let i = 0; i < line.length; i++) {
|
|
91
|
+
const c = line.charCodeAt(i);
|
|
92
|
+
if (c === 0x20) {
|
|
93
|
+
word = { tokens: [], value: "", width: 0 };
|
|
94
|
+
out.push(word);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
let token: Token;
|
|
98
|
+
if (c === 0x1b) {
|
|
99
|
+
const m = sgrAt(line, i);
|
|
100
|
+
if (!m) return undefined;
|
|
101
|
+
token = { value: line.slice(i, i + m.length), width: 0 };
|
|
102
|
+
i += m.length - 1;
|
|
103
|
+
} else {
|
|
104
|
+
if (!standalone(c)) return undefined;
|
|
105
|
+
token = { value: line[i]!, width: c < 0x7f ? 1 : charWidth(c) };
|
|
106
|
+
}
|
|
107
|
+
word.tokens.push(token);
|
|
108
|
+
word.value += token.value;
|
|
109
|
+
word.width += token.width;
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** wrap-ansi 的 wrapWord:长词逐个字符往下排,返回最后一行的宽度 */
|
|
115
|
+
function wrapWord(rows: string[], tokens: Token[], columns: number, rowWidth: number): number {
|
|
116
|
+
let visible = rowWidth;
|
|
117
|
+
tokens.forEach((t, i) => {
|
|
118
|
+
if (t.width > 0 && visible > 0 && visible + t.width > columns) {
|
|
119
|
+
rows.push("");
|
|
120
|
+
visible = 0;
|
|
121
|
+
}
|
|
122
|
+
rows[rows.length - 1] += t.value;
|
|
123
|
+
visible += t.width;
|
|
124
|
+
if (visible === columns && i < tokens.length - 1) {
|
|
125
|
+
rows.push("");
|
|
126
|
+
visible = 0;
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
if (!visible && rows.at(-1)!.length > 0 && rows.length > 1) rows[rows.length - 2] += rows.pop()!;
|
|
130
|
+
return fastWidth(rows.at(-1)!)!;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
interface Style {
|
|
134
|
+
family: string;
|
|
135
|
+
open: number;
|
|
136
|
+
close: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** wrap-ansi 对一个样式码的处理:关闭码去掉对应的样式,打开码换掉同类的样式并排到最后 */
|
|
140
|
+
function applySgr(code: number, active: Style[], resetsOnly = false) {
|
|
141
|
+
if (code === 39) {
|
|
142
|
+
const i = active.findIndex((s) => s.family === "foreground");
|
|
143
|
+
if (i !== -1) active.splice(i, 1);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (RESETS.has(code)) {
|
|
147
|
+
for (let i = active.length - 1; i >= 0; i--) if (active[i]!.family.startsWith("modifier-") && active[i]!.close === code) active.splice(i, 1);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (resetsOnly) return;
|
|
151
|
+
const close = CLOSE_OF.get(code)!;
|
|
152
|
+
const family = close === 39 ? "foreground" : `modifier-${code}`;
|
|
153
|
+
const i = active.findIndex((s) => s.family === family);
|
|
154
|
+
if (i !== -1) active.splice(i, 1);
|
|
155
|
+
active.push({ family, open: code, close });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** wrap-ansi 的 restoreStylesAcrossRows:每个折行处先关掉还开着的样式,下一行开头再打开 */
|
|
159
|
+
function restoreStyles(s: string): string {
|
|
160
|
+
let out = "";
|
|
161
|
+
const active: Style[] = [];
|
|
162
|
+
let copied = 0;
|
|
163
|
+
let i = 0;
|
|
164
|
+
while (i < s.length) {
|
|
165
|
+
const c = s.charCodeAt(i);
|
|
166
|
+
if (c === 0x1b) {
|
|
167
|
+
const m = sgrAt(s, i)!;
|
|
168
|
+
applySgr(m.code, active);
|
|
169
|
+
i += m.length;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (c !== 0x0a) {
|
|
173
|
+
i++;
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
out += s.slice(copied, i);
|
|
177
|
+
if (i > copied) out += [...active].reverse().map((st) => `\x1b[${st.close}m`).join("");
|
|
178
|
+
out += "\n";
|
|
179
|
+
copied = ++i;
|
|
180
|
+
if (i < s.length && s[i] !== "\n") {
|
|
181
|
+
const opening = [...active];
|
|
182
|
+
for (let j = i, m = sgrAt(s, j); m; j += m.length, m = sgrAt(s, j)) applySgr(m.code, opening, true);
|
|
183
|
+
out += opening.map((st) => `\x1b[${st.open}m`).join("");
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return out + s.slice(copied);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** wrap-ansi 对一行(不含换行和制表符)的 hard、trim: false 折法;快路径处理不了时返回 undefined */
|
|
190
|
+
function fastWrap(line: string, columns: number): string[] | undefined {
|
|
191
|
+
const width = fastWidth(line);
|
|
192
|
+
if (width === undefined) return undefined;
|
|
193
|
+
if (width <= columns) return [line];
|
|
194
|
+
const list = words(line)!;
|
|
195
|
+
const rows = [""];
|
|
196
|
+
let rowLength = 0;
|
|
197
|
+
list.forEach((word, k) => {
|
|
198
|
+
if (k > 0) {
|
|
199
|
+
if (rowLength >= columns) {
|
|
200
|
+
rows.push("");
|
|
201
|
+
rowLength = 0;
|
|
202
|
+
}
|
|
203
|
+
rows[rows.length - 1] += " ";
|
|
204
|
+
rowLength++;
|
|
205
|
+
}
|
|
206
|
+
if (word.width > columns) {
|
|
207
|
+
const remaining = columns - rowLength;
|
|
208
|
+
const thisLine = 1 + Math.floor((word.width - remaining - 1) / columns);
|
|
209
|
+
const nextLine = Math.floor((word.width - 1) / columns);
|
|
210
|
+
if (nextLine < thisLine) {
|
|
211
|
+
rows.push("");
|
|
212
|
+
rowLength = 0;
|
|
213
|
+
}
|
|
214
|
+
rowLength = wrapWord(rows, word.tokens, columns, rowLength);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (rowLength + word.width > columns && rowLength > 0 && word.width > 0) {
|
|
218
|
+
rows.push("");
|
|
219
|
+
rowLength = 0;
|
|
220
|
+
}
|
|
221
|
+
rows[rows.length - 1] += word.value;
|
|
222
|
+
rowLength += word.width;
|
|
223
|
+
});
|
|
224
|
+
return line.includes("\x1b") ? restoreStyles(rows.join("\n")).split("\n") : rows;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const WRAP = { hard: true, trim: false } as const;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* 按原来的行分组折行:每一项是一个原来的行折成的若干行,连起来和 wrapAnsi(text, width, { hard: true, trim: false }).split("\n") 一样。
|
|
231
|
+
* text 里不能有制表符;有 \r 时(wrap-ansi 会把 \r\n 当成一个换行)返回 undefined
|
|
232
|
+
*/
|
|
233
|
+
export function wrapLines(text: string, width: number): string[][] | undefined {
|
|
234
|
+
if (text.includes("\r")) return undefined;
|
|
235
|
+
return text.split("\n").map((line) => fastWrap(line, width) ?? wrapAnsi(line, width, WRAP).split("\n"));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 和 wrapAnsi(text, width, { hard: true, trim: false }).split("\n") 一样,常用字符走快路径;text 里不能有制表符 */
|
|
239
|
+
export const wrapText = (text: string, width: number): string[] =>
|
|
240
|
+
wrapLines(text, width)?.flat() ?? wrapAnsi(text, width, WRAP).split("\n");
|