@kangyishuai/dsh-btw 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -12
- package/README.zh-CN.md +33 -12
- package/lib/client.js +1013 -404
- package/lib/format.js +73 -0
- package/lib/limits.js +2 -0
- package/lib/live.js +136 -0
- package/lib/markdown.js +695 -0
- package/lib/service.js +79 -31
- package/lib/settings.js +25 -4
- package/lib/subagent.js +11 -0
- package/lib/threads.js +110 -175
- package/locale/en.json +3 -2
- package/locale/zh.json +3 -2
- package/package.json +1 -1
package/lib/service.js
CHANGED
|
@@ -6,16 +6,20 @@ import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
|
6
6
|
import { renderBadge } from "./badge.js";
|
|
7
7
|
import { parseAllowedTools } from "./config.js";
|
|
8
8
|
import { createFollowUpQueue } from "./followup-queue.js";
|
|
9
|
+
import { formatDuration, formatTokens } from "./format.js";
|
|
9
10
|
import { appendRecord, lastRecord, listRecent } from "./history.js";
|
|
10
11
|
import { clip, LIMITS } from "./limits.js";
|
|
12
|
+
import { createLiveTracker } from "./live.js";
|
|
13
|
+
import { parseMarkdown } from "./markdown.js";
|
|
11
14
|
import { format, loadMessages, pickLanguage } from "./messages.js";
|
|
12
15
|
import { historyFile, resolveDataRoot } from "./paths.js";
|
|
13
|
-
import { loadSettings, saveSettings } from "./settings.js";
|
|
16
|
+
import { buildSettingsPatch, loadSettings, saveSettings } from "./settings.js";
|
|
14
17
|
import { observeUsage, runSideQuestion } from "./subagent.js";
|
|
15
18
|
import {
|
|
16
19
|
listThreads,
|
|
17
20
|
newThreadId,
|
|
18
21
|
parseCommandArgs,
|
|
22
|
+
promoteRecordForThread,
|
|
19
23
|
renderPromoteDraft,
|
|
20
24
|
threadHistory,
|
|
21
25
|
} from "./threads.js";
|
|
@@ -53,7 +57,8 @@ const FALLBACK = {
|
|
|
53
57
|
cancelled: "The side question was cancelled.",
|
|
54
58
|
tooLong: "That question is too long ({length} characters, limit {max}).",
|
|
55
59
|
threadFull: "This side-question thread is full ({max} turns). Start a new one.",
|
|
56
|
-
meta: "btw · new {newTokens} tokens · cached {cachedTokens} · {ms}
|
|
60
|
+
meta: "btw · new {newTokens} tokens · cached {cachedTokens} · {ms}",
|
|
61
|
+
panelOnly: "Side question answered; the full answer is in the side-question panel.",
|
|
57
62
|
reopen: "Last side question: {question}",
|
|
58
63
|
};
|
|
59
64
|
|
|
@@ -76,7 +81,9 @@ export class BtwService extends TypertRemoteService {
|
|
|
76
81
|
this.allowedTools = this.configAllowedTools;
|
|
77
82
|
this.language = pickLanguage(this.config?.language);
|
|
78
83
|
this.usageBySession = observeUsage(ctx);
|
|
79
|
-
//
|
|
84
|
+
// 面板流式:按 childSessionId 旁听 text-delta,`btw/live` 轮询取快照。
|
|
85
|
+
this.liveTracker = createLiveTracker(ctx);
|
|
86
|
+
// 抽屉追问借 composer 提交裸 `/btw`,真实参数从这里取(见 followup-queue.js)。
|
|
80
87
|
this.followUps = createFollowUpQueue({});
|
|
81
88
|
/** @type {Record<string, string>} */
|
|
82
89
|
this.messages = FALLBACK;
|
|
@@ -137,7 +144,7 @@ export class BtwService extends TypertRemoteService {
|
|
|
137
144
|
let threadId = parsed.threadId;
|
|
138
145
|
let scope = parsed.scope;
|
|
139
146
|
let rawQuestion = parsed.question;
|
|
140
|
-
// 裸 `/btw
|
|
147
|
+
// 裸 `/btw`(无参数)时先看有没有抽屉登记的追问:
|
|
141
148
|
// 有就当追问处理,没有才走「重开上一条」的老语义。
|
|
142
149
|
if (threadId === "" && rawQuestion === "") {
|
|
143
150
|
const queued = this.followUps.take(String(agent?.id ?? ""));
|
|
@@ -179,17 +186,31 @@ export class BtwService extends TypertRemoteService {
|
|
|
179
186
|
};
|
|
180
187
|
}
|
|
181
188
|
const history = [...sessionHistory, ...priorThread].slice(-LIMITS.replayRecords);
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
189
|
+
// 线程 id 在 fork 之前就定下来:面板流式卡片和最终记录必须是同一个线程。
|
|
190
|
+
const recordThreadId = threadId === "" ? newThreadId() : threadId;
|
|
191
|
+
// 面板流式:登记这次 run;fork 拿到 childId 后 onChild 会接上实时文本。
|
|
192
|
+
const run = this.liveTracker.begin(String(agent?.id ?? ""), {
|
|
193
|
+
threadId: recordThreadId,
|
|
186
194
|
question: question.text,
|
|
187
|
-
scope,
|
|
188
|
-
history,
|
|
189
|
-
allowedTools,
|
|
190
|
-
signal: invocation?.signal,
|
|
191
|
-
usageBySession: this.usageBySession,
|
|
192
195
|
});
|
|
196
|
+
/** @type {Awaited<ReturnType<typeof runSideQuestion>>} */
|
|
197
|
+
let outcome;
|
|
198
|
+
try {
|
|
199
|
+
outcome = await runSideQuestion({
|
|
200
|
+
ctx: this.scoped,
|
|
201
|
+
workspaceRegistry: this.scoped?.workspaceRegistry,
|
|
202
|
+
agent,
|
|
203
|
+
question: question.text,
|
|
204
|
+
scope,
|
|
205
|
+
history,
|
|
206
|
+
allowedTools,
|
|
207
|
+
signal: invocation?.signal,
|
|
208
|
+
usageBySession: this.usageBySession,
|
|
209
|
+
onChild: (childId) => this.liveTracker.attachChild(run, childId),
|
|
210
|
+
});
|
|
211
|
+
} finally {
|
|
212
|
+
this.liveTracker.finish(run);
|
|
213
|
+
}
|
|
193
214
|
|
|
194
215
|
if (outcome.code === "subagents_unavailable") {
|
|
195
216
|
return { kind: "error", text: this.messages.forkUnavailable ?? FALLBACK.forkUnavailable };
|
|
@@ -209,8 +230,8 @@ export class BtwService extends TypertRemoteService {
|
|
|
209
230
|
const recordId = `btw_${Date.now().toString(36)}`;
|
|
210
231
|
const record = {
|
|
211
232
|
id: recordId,
|
|
212
|
-
// 线程:追问沿用传入的 threadId
|
|
213
|
-
threadId:
|
|
233
|
+
// 线程:追问沿用传入的 threadId;首问用 fork 前就定下的新线程 id(v0.4 流式共用)
|
|
234
|
+
threadId: recordThreadId,
|
|
214
235
|
parentSessionId: String(agent?.id ?? ""),
|
|
215
236
|
childSessionId: outcome.childId ?? null,
|
|
216
237
|
question: question.text,
|
|
@@ -221,6 +242,10 @@ export class BtwService extends TypertRemoteService {
|
|
|
221
242
|
at: Date.now(),
|
|
222
243
|
};
|
|
223
244
|
await appendRecord(file, record).catch(() => {});
|
|
245
|
+
// 设置里关掉「主对话显示完整答案」时,只回一行提示;面板历史里仍有完整答案。
|
|
246
|
+
if (stored !== undefined && stored.echoAnswer === false) {
|
|
247
|
+
return { kind: "success", text: this.messages.panelOnly ?? FALLBACK.panelOnly };
|
|
248
|
+
}
|
|
224
249
|
return { kind: "success", text: this.formatAnswer(record) };
|
|
225
250
|
}
|
|
226
251
|
|
|
@@ -238,7 +263,7 @@ export class BtwService extends TypertRemoteService {
|
|
|
238
263
|
}
|
|
239
264
|
|
|
240
265
|
/**
|
|
241
|
-
*
|
|
266
|
+
* 徽章数据(抽屉底部展示用):记录条数与范围说明。
|
|
242
267
|
* @param {{ sessionId?: string, scope?: string, lang?: string } | undefined} request
|
|
243
268
|
* @returns {Promise<{ records: number, badge: string }>}
|
|
244
269
|
*/
|
|
@@ -259,7 +284,7 @@ export class BtwService extends TypertRemoteService {
|
|
|
259
284
|
}
|
|
260
285
|
|
|
261
286
|
/**
|
|
262
|
-
*
|
|
287
|
+
* 线程列表(抽屉展示用)。参数必须是单一标识符(网关 SRC 校验)。
|
|
263
288
|
* @param {{ sessionId?: string, limit?: number } | undefined} request
|
|
264
289
|
* @returns {Promise<any[]>}
|
|
265
290
|
*/
|
|
@@ -276,10 +301,32 @@ export class BtwService extends TypertRemoteService {
|
|
|
276
301
|
return listThreads(records);
|
|
277
302
|
}
|
|
278
303
|
|
|
304
|
+
/**
|
|
305
|
+
* 流式快照(面板轮询用):该父会话里正在跑的旁问 + 已解析的 Markdown 块。
|
|
306
|
+
*
|
|
307
|
+
* 为什么走轮询而不是让 client 订阅子会话事件:子会话是 fork 出来的,
|
|
308
|
+
* 它带着父会话的全部已完成轮次作为种子;client 一旦 retain 它就会把整段历史
|
|
309
|
+
* 拉到浏览器里。旁问只需要最后几 KB 的增量文本,host 缓冲 + 短轮询更省。
|
|
310
|
+
* @param {{ sessionId?: string } | undefined} request
|
|
311
|
+
* @returns {Promise<{ runs: any[] }>}
|
|
312
|
+
*/
|
|
313
|
+
async live(request) {
|
|
314
|
+
const input = request ?? {};
|
|
315
|
+
return {
|
|
316
|
+
runs: this.liveTracker.list(String(input.sessionId ?? "")).map((run) => ({
|
|
317
|
+
threadId: run.threadId,
|
|
318
|
+
question: run.question,
|
|
319
|
+
childId: run.childId,
|
|
320
|
+
ms: run.ms,
|
|
321
|
+
blocks: parseMarkdown(run.text).blocks,
|
|
322
|
+
})),
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
279
326
|
/**
|
|
280
327
|
* 生成「一键转正」草稿文本。**只返回文本,不插入、不发送**——
|
|
281
328
|
* 语义已与用户确认:插入 composer 草稿,由用户自己决定发不发。
|
|
282
|
-
* @param {{ sessionId?: string, recordId?: string, lang?: string, details?: string, unresolved?: string } | undefined} request
|
|
329
|
+
* @param {{ sessionId?: string, threadId?: string, recordId?: string, lang?: string, details?: string, unresolved?: string } | undefined} request
|
|
283
330
|
* @returns {Promise<{ ok: boolean, text?: string, reason?: string }>}
|
|
284
331
|
*/
|
|
285
332
|
async promote(request) {
|
|
@@ -288,14 +335,17 @@ export class BtwService extends TypertRemoteService {
|
|
|
288
335
|
historyFile(this.dataRoot, String(input.sessionId ?? "")),
|
|
289
336
|
LIMITS.perSessionRecords,
|
|
290
337
|
);
|
|
338
|
+
const threadId = String(input.threadId ?? "");
|
|
291
339
|
const wanted = String(input.recordId ?? "");
|
|
292
340
|
const record =
|
|
293
|
-
|
|
294
|
-
? records
|
|
295
|
-
:
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
341
|
+
threadId !== ""
|
|
342
|
+
? promoteRecordForThread(records, threadId)
|
|
343
|
+
: wanted === ""
|
|
344
|
+
? records[records.length - 1]
|
|
345
|
+
: records
|
|
346
|
+
.slice()
|
|
347
|
+
.reverse()
|
|
348
|
+
.find((entry) => String(entry?.id ?? "") === wanted);
|
|
299
349
|
if (record === undefined) return { ok: false, reason: "no_record" };
|
|
300
350
|
const text = renderPromoteDraft(record, {
|
|
301
351
|
lang: String(input.lang ?? ""),
|
|
@@ -355,10 +405,7 @@ export class BtwService extends TypertRemoteService {
|
|
|
355
405
|
*/
|
|
356
406
|
async updateSettings(request) {
|
|
357
407
|
const input = request ?? {};
|
|
358
|
-
const saved = await saveSettings(this.dataRoot,
|
|
359
|
-
...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
|
|
360
|
-
...(input.historyLimit === undefined ? {} : { historyLimit: input.historyLimit }),
|
|
361
|
-
});
|
|
408
|
+
const saved = await saveSettings(this.dataRoot, buildSettingsPatch(input));
|
|
362
409
|
this.allowedTools = new Set(saved.allowedTools);
|
|
363
410
|
return { ...saved, readOnly: saved.allowedTools.length === 0 };
|
|
364
411
|
}
|
|
@@ -367,9 +414,9 @@ export class BtwService extends TypertRemoteService {
|
|
|
367
414
|
formatAnswer(record) {
|
|
368
415
|
const usage = record.cost ?? {};
|
|
369
416
|
const meta = format(this.messages.meta ?? FALLBACK.meta, {
|
|
370
|
-
newTokens:
|
|
371
|
-
cachedTokens:
|
|
372
|
-
ms:
|
|
417
|
+
newTokens: formatTokens(usage.inputTokens),
|
|
418
|
+
cachedTokens: formatTokens(usage.cacheReadTokens),
|
|
419
|
+
ms: formatDuration(record.ms),
|
|
373
420
|
});
|
|
374
421
|
const lines = [record.answer, "", `— ${meta}`];
|
|
375
422
|
if (record.status === "truncated")
|
|
@@ -388,6 +435,7 @@ export class BtwService extends TypertRemoteService {
|
|
|
388
435
|
|
|
389
436
|
declareRemote(BtwService, "history");
|
|
390
437
|
declareRemote(BtwService, "last");
|
|
438
|
+
declareRemote(BtwService, "live");
|
|
391
439
|
declareRemote(BtwService, "stats");
|
|
392
440
|
declareRemote(BtwService, "queueFollowUp");
|
|
393
441
|
declareRemote(BtwService, "threads");
|
package/lib/settings.js
CHANGED
|
@@ -17,6 +17,8 @@ export const DEFAULT_SETTINGS = Object.freeze({
|
|
|
17
17
|
allowedTools: Object.freeze([]),
|
|
18
18
|
/** 每会话保留的旁问条数。 */
|
|
19
19
|
historyLimit: LIMITS.perSessionRecords,
|
|
20
|
+
/** 主对话里是否还回显完整答案;false = 只在旁问面板展示。 */
|
|
21
|
+
echoAnswer: true,
|
|
20
22
|
});
|
|
21
23
|
|
|
22
24
|
/** @param {string} dataRoot @returns {string} */
|
|
@@ -27,7 +29,7 @@ export function settingsPath(dataRoot) {
|
|
|
27
29
|
/**
|
|
28
30
|
* 把任意输入夹紧成合法设置。
|
|
29
31
|
* @param {any} raw
|
|
30
|
-
* @returns {{ schemaVersion: number, allowedTools: string[], historyLimit: number }}
|
|
32
|
+
* @returns {{ schemaVersion: number, allowedTools: string[], historyLimit: number, echoAnswer: boolean }}
|
|
31
33
|
*/
|
|
32
34
|
export function sanitizeSettings(raw) {
|
|
33
35
|
const input = raw !== null && typeof raw === "object" ? raw : {};
|
|
@@ -49,13 +51,32 @@ export function sanitizeSettings(raw) {
|
|
|
49
51
|
const historyLimit = Number.isFinite(limitRaw)
|
|
50
52
|
? Math.min(Math.max(Math.trunc(limitRaw), 1), 200)
|
|
51
53
|
: LIMITS.perSessionRecords;
|
|
52
|
-
|
|
54
|
+
// 只有显式 false 关闭;缺省/other 值保持 true(旧设置文件与向后兼容)。
|
|
55
|
+
const echoAnswer = input.echoAnswer === false ? false : true;
|
|
56
|
+
return { schemaVersion: SETTINGS_SCHEMA_VERSION, allowedTools, historyLimit, echoAnswer };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 把 updateSettings 的入参收敛成「只含已知字段」的补丁。
|
|
61
|
+
* **单独抽出来**是为了单测能直接断言 `echoAnswer` 没被漏掉(2026-11-18 真机踩到:
|
|
62
|
+
* updateSettings 手写 spread 时漏了这个新字段,设置保存后又被默认值覆盖)。
|
|
63
|
+
* @param {any} input
|
|
64
|
+
* @returns {Record<string, unknown>}
|
|
65
|
+
*/
|
|
66
|
+
export function buildSettingsPatch(input) {
|
|
67
|
+
const source = input !== null && typeof input === "object" ? input : {};
|
|
68
|
+
/** @type {Record<string, unknown>} */
|
|
69
|
+
const patch = {};
|
|
70
|
+
if (source.allowedTools !== undefined) patch.allowedTools = source.allowedTools;
|
|
71
|
+
if (source.historyLimit !== undefined) patch.historyLimit = source.historyLimit;
|
|
72
|
+
if (source.echoAnswer !== undefined) patch.echoAnswer = source.echoAnswer;
|
|
73
|
+
return patch;
|
|
53
74
|
}
|
|
54
75
|
|
|
55
76
|
/**
|
|
56
77
|
* 读设置;文件缺失、坏 JSON、坏字段一律静默回落到默认值。
|
|
57
78
|
* @param {string} dataRoot
|
|
58
|
-
* @returns {Promise<{ schemaVersion: number, allowedTools: string[], historyLimit: number }>}
|
|
79
|
+
* @returns {Promise<{ schemaVersion: number, allowedTools: string[], historyLimit: number, echoAnswer: boolean }>}
|
|
59
80
|
*/
|
|
60
81
|
export async function loadSettings(dataRoot) {
|
|
61
82
|
let text;
|
|
@@ -75,7 +96,7 @@ export async function loadSettings(dataRoot) {
|
|
|
75
96
|
* 原子写设置(先写临时文件再 rename)。
|
|
76
97
|
* @param {string} dataRoot
|
|
77
98
|
* @param {any} patch 只合并已知字段
|
|
78
|
-
* @returns {Promise<{ schemaVersion: number, allowedTools: string[], historyLimit: number }>}
|
|
99
|
+
* @returns {Promise<{ schemaVersion: number, allowedTools: string[], historyLimit: number, echoAnswer: boolean }>}
|
|
79
100
|
*/
|
|
80
101
|
export async function saveSettings(dataRoot, patch) {
|
|
81
102
|
const current = await loadSettings(dataRoot);
|
package/lib/subagent.js
CHANGED
|
@@ -82,6 +82,7 @@ export function makeReadOnlyGuard(allowedTools) {
|
|
|
82
82
|
* scope?: string,
|
|
83
83
|
* workspaceRegistry?: any,
|
|
84
84
|
* now?: () => number,
|
|
85
|
+
* onChild?: (childId: string) => void,
|
|
85
86
|
* }} input
|
|
86
87
|
* @returns {Promise<{ ok: boolean, text: string, status: string, childId?: string, usage?: Usage, ms: number, code?: string }>}
|
|
87
88
|
*/
|
|
@@ -121,6 +122,16 @@ export async function runSideQuestion(input) {
|
|
|
121
122
|
delivery: "caller",
|
|
122
123
|
});
|
|
123
124
|
|
|
125
|
+
// 把子会话 id 尽早交给调用方:面板要靠它在 `llm/stream` 上旁听实时文本。
|
|
126
|
+
// 注意此时子代理的第一次模型请求通常还没开始(网络往返在后面),不会漏 chunk。
|
|
127
|
+
if (typeof input.onChild === "function") {
|
|
128
|
+
try {
|
|
129
|
+
input.onChild(String(activation?.childId ?? ""));
|
|
130
|
+
} catch {
|
|
131
|
+
/* 观察者失败不影响旁问本身 */
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
124
135
|
// 只读保护挂在子代理自己的 ctx 上,随子代理释放。
|
|
125
136
|
const child = ctx?.agents?.get?.(activation?.childId);
|
|
126
137
|
const tools = child?.ctx?.tools ?? ctx?.tools;
|
package/lib/threads.js
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
// 旁问线程与「一键转正」的**纯逻辑**:不 import 任何宿主包,便于 node --test 直接引用
|
|
3
3
|
// (service.js 会 import 宿主 RPC 协议,在单测环境里解析不到)。
|
|
4
4
|
import { LIMITS } from "./limits.js";
|
|
5
|
+
import { parseMarkdown, truncateMarkdown } from "./markdown.js";
|
|
5
6
|
|
|
6
|
-
/**
|
|
7
|
+
/** 转正草稿的四节模板(Markdown 标题;落进输入框是未渲染源码,发送后由 DSH 渲染)。 */
|
|
7
8
|
export const PROMOTE_SECTIONS = [
|
|
8
9
|
{ key: "question", zh: "我问了什么", en: "What I asked" },
|
|
9
10
|
{ key: "answer", zh: "结论", en: "Conclusion" },
|
|
@@ -18,7 +19,7 @@ export const PROMOTE_SECTIONS = [
|
|
|
18
19
|
* @returns {string}
|
|
19
20
|
*/
|
|
20
21
|
export function newThreadId(now = Date.now(), rand = Math.random) {
|
|
21
|
-
// 短 id
|
|
22
|
+
// 短 id:抽屉发问要走 composer,命令文本(`/btw --thread <id> ...`)会短暂出现在
|
|
22
23
|
// 用户输入框里,id 越短越不刺眼。实测 16 字符的 `t_mwkfmjk1_qrb3` 太显眼。
|
|
23
24
|
// 单机单会话内冲突概率可忽略(时间 36 进制 + 2 位随机)。
|
|
24
25
|
const suffix = Math.floor(rand() * 36 ** 2)
|
|
@@ -77,10 +78,96 @@ export function threadHistory(records, threadId, maxTurns = LIMITS.threadTurns)
|
|
|
77
78
|
return thread.items.slice(-maxTurns);
|
|
78
79
|
}
|
|
79
80
|
|
|
81
|
+
/**
|
|
82
|
+
* 把一条记录变成面板可渲染的轮次。
|
|
83
|
+
*
|
|
84
|
+
* `blocks` 是 host 半解析好的 Markdown 树:client 只做 React 元素映射,
|
|
85
|
+
* 既不用在 classic script 里重复写解析器,也不会把模型输出当 HTML 执行。
|
|
86
|
+
* @param {any} record
|
|
87
|
+
* @returns {{
|
|
88
|
+
* id: string,
|
|
89
|
+
* question: string,
|
|
90
|
+
* chars: number,
|
|
91
|
+
* blocks: any[],
|
|
92
|
+
* cost: any,
|
|
93
|
+
* ms: number,
|
|
94
|
+
* at: number,
|
|
95
|
+
* status: string,
|
|
96
|
+
* }}
|
|
97
|
+
*/
|
|
98
|
+
export function threadTurn(record) {
|
|
99
|
+
const answer = String(record?.answer ?? "");
|
|
100
|
+
return {
|
|
101
|
+
id: String(record?.id ?? ""),
|
|
102
|
+
question: String(record?.question ?? ""),
|
|
103
|
+
chars: answer.length,
|
|
104
|
+
blocks: parseMarkdown(answer).blocks,
|
|
105
|
+
cost: record?.cost ?? null,
|
|
106
|
+
ms: Number(record?.ms ?? 0),
|
|
107
|
+
at: Number(record?.at ?? 0),
|
|
108
|
+
status: String(record?.status ?? ""),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 线程列表(给面板展示):**旧→新**排序,每项带完整轮次。
|
|
114
|
+
*
|
|
115
|
+
* 为什么改成正序:面板是聊天式界面,最新一条应该落在最下面;
|
|
116
|
+
* 反序会让「刚问的问题」出现在最上面,与自己/常聊天应用的心智相反。
|
|
117
|
+
* @param {any[]} records
|
|
118
|
+
* @returns {{
|
|
119
|
+
* threadId: string,
|
|
120
|
+
* turns: number,
|
|
121
|
+
* question: string,
|
|
122
|
+
* at: number,
|
|
123
|
+
* lastId: string,
|
|
124
|
+
* cost: any,
|
|
125
|
+
* ms: number,
|
|
126
|
+
* items: ReturnType<typeof threadTurn>[],
|
|
127
|
+
* }[]}
|
|
128
|
+
*/
|
|
129
|
+
export function listThreads(records) {
|
|
130
|
+
return groupThreads(records)
|
|
131
|
+
.map((thread) => {
|
|
132
|
+
const items = thread.items.map((record) => threadTurn(record));
|
|
133
|
+
return {
|
|
134
|
+
threadId: thread.threadId,
|
|
135
|
+
turns: items.length,
|
|
136
|
+
question: String(thread.items[0]?.question ?? ""),
|
|
137
|
+
at: thread.at,
|
|
138
|
+
lastId: String(thread.last?.id ?? ""),
|
|
139
|
+
cost: thread.last?.cost ?? null,
|
|
140
|
+
ms: Number(thread.last?.ms ?? 0),
|
|
141
|
+
items,
|
|
142
|
+
};
|
|
143
|
+
})
|
|
144
|
+
.sort((a, b) => a.at - b.at);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 线程级转正:用**首问**当「我问了什么」,用**最后一轮答案**当「结论」。
|
|
149
|
+
*
|
|
150
|
+
* 为什么不是只取最后一轮:线程追问两次后,用户说「转正」通常指整条旁问线索,
|
|
151
|
+
* 只把最后一次追问塞进草稿会丢掉原始问题(2026-11-18 可用性测试发现)。
|
|
152
|
+
* @param {any[]} records 该会话的历史记录
|
|
153
|
+
* @param {string} threadId
|
|
154
|
+
* @returns {any | undefined}
|
|
155
|
+
*/
|
|
156
|
+
export function promoteRecordForThread(records, threadId) {
|
|
157
|
+
const wanted = String(threadId ?? "");
|
|
158
|
+
if (wanted === "") return undefined;
|
|
159
|
+
const thread = groupThreads(records).find((entry) => entry.threadId === wanted);
|
|
160
|
+
if (thread === undefined) return undefined;
|
|
161
|
+
const first = thread.items[0];
|
|
162
|
+
const last = thread.items[thread.items.length - 1];
|
|
163
|
+
return { ...last, question: String(first?.question ?? last?.question ?? "") };
|
|
164
|
+
}
|
|
165
|
+
|
|
80
166
|
/**
|
|
81
167
|
* 把一条旁问渲染成可插入草稿的文本(**只生成文本,绝不发送**)。
|
|
82
168
|
*
|
|
83
|
-
*
|
|
169
|
+
* 语义(2026-11-17 与用户确认):转正保留 **Markdown 源码** —— 四节用 `##` 标题,
|
|
170
|
+
* 落进输入框是未渲染的原文,发送后由 DSH 正常渲染;不再剥掉 `**`/表格/围栏。
|
|
84
171
|
* @param {any} record
|
|
85
172
|
* @param {{ lang?: string, details?: string, unresolved?: string, maxChars?: number }} [options]
|
|
86
173
|
* @returns {string}
|
|
@@ -88,97 +175,37 @@ export function threadHistory(records, threadId, maxTurns = LIMITS.threadTurns)
|
|
|
88
175
|
export function renderPromoteDraft(record, options = {}) {
|
|
89
176
|
const lang = options.lang === "en" ? "en" : "zh";
|
|
90
177
|
const maxChars = Math.min(
|
|
91
|
-
Math.max(Number(options.maxChars) || LIMITS.
|
|
92
|
-
LIMITS.
|
|
178
|
+
Math.max(Number(options.maxChars) || LIMITS.promoteChars, 200),
|
|
179
|
+
LIMITS.promoteChars,
|
|
93
180
|
);
|
|
94
181
|
const section = (/** @type {string} */ key) => {
|
|
95
182
|
const found = PROMOTE_SECTIONS.find((entry) => entry.key === key);
|
|
96
183
|
return found === undefined ? key : lang === "en" ? found.en : found.zh;
|
|
97
184
|
};
|
|
98
|
-
const question =
|
|
99
|
-
const answer =
|
|
185
|
+
const question = String(record?.question ?? "").trim();
|
|
186
|
+
const answer = String(record?.answer ?? "").trim();
|
|
100
187
|
/** @type {string[]} */
|
|
101
188
|
const lines = [
|
|
102
|
-
|
|
189
|
+
`## ${section("question")}`,
|
|
190
|
+
"",
|
|
103
191
|
question === "" ? "—" : question,
|
|
104
192
|
"",
|
|
105
|
-
|
|
193
|
+
`## ${section("answer")}`,
|
|
194
|
+
"",
|
|
106
195
|
answer === "" ? "—" : answer,
|
|
107
196
|
];
|
|
108
|
-
const details =
|
|
109
|
-
if (details !== "")
|
|
110
|
-
|
|
111
|
-
|
|
197
|
+
const details = String(options.details ?? "").trim();
|
|
198
|
+
if (details !== "") {
|
|
199
|
+
lines.push("", `## ${section("details")}`, "", details);
|
|
200
|
+
}
|
|
201
|
+
const unresolved = String(options.unresolved ?? "").trim();
|
|
202
|
+
if (unresolved !== "") {
|
|
203
|
+
lines.push("", `## ${section("unresolved")}`, "", unresolved);
|
|
204
|
+
}
|
|
112
205
|
const text = lines.join("\n").trim();
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* 去掉常见 Markdown 标记,让文本适合直接阅读/放进输入框。
|
|
118
|
-
*
|
|
119
|
-
* @param {string} text
|
|
120
|
-
* @param {{ keepCode?: boolean, keepFence?: boolean }} [options]
|
|
121
|
-
* - keepCode 默认 true:``` 围栏内的内容原样保留(代码缩进有意义)
|
|
122
|
-
* - keepFence 默认 false:true 时保留 ``` 围栏标记,供 client 识别代码块边界
|
|
123
|
-
* @returns {string}
|
|
124
|
-
*/
|
|
125
|
-
export function stripMarkdown(text, options = {}) {
|
|
126
|
-
const raw = String(text ?? "");
|
|
127
|
-
if (options.keepCode === false) return stripAllMarkdown(raw);
|
|
128
|
-
const keepFence = options.keepFence === true;
|
|
129
|
-
// 先把围栏块抽出占位,避免下面的标记清理破坏代码内容。
|
|
130
|
-
/** @type {{ lang: string, body: string }[]} */
|
|
131
|
-
const fences = [];
|
|
132
|
-
const parked = raw.replace(
|
|
133
|
-
/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/gu,
|
|
134
|
-
(/** @type {string} */ _m, /** @type {string} */ lang, /** @type {string} */ body) => {
|
|
135
|
-
const fence = body.replace(/\n+$/u, "");
|
|
136
|
-
fences.push({ lang, body: fence });
|
|
137
|
-
return `@@BTWFENCE${fences.length - 1}@@`;
|
|
138
|
-
},
|
|
139
|
-
);
|
|
140
|
-
const cleaned = stripAllMarkdown(parked).replace(
|
|
141
|
-
/@@BTWFENCE(\d+)@@/gu,
|
|
142
|
-
(/** @type {string} */ _m, /** @type {string} */ i) => {
|
|
143
|
-
const fence = fences[Number(i)];
|
|
144
|
-
if (fence === undefined) return "";
|
|
145
|
-
// keepFence 时保留 ``` 标记:client 靠它识别代码块边界,渲染成 <pre> 后
|
|
146
|
-
// 再把标记本身隐藏掉。默认关,转正草稿等纯文本场景不需要它。
|
|
147
|
-
return keepFence ? `\n\`\`\`${fence.lang}\n${fence.body}\n\`\`\`\n` : `\n${fence.body}\n`;
|
|
148
|
-
},
|
|
149
|
-
);
|
|
150
|
-
return cleaned.replace(/\n{3,}/gu, "\n\n").trim();
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/**
|
|
154
|
-
* 纯标记清理(条目级,不含代码块保护)。
|
|
155
|
-
* @param {string} text
|
|
156
|
-
* @returns {string}
|
|
157
|
-
*/
|
|
158
|
-
function stripAllMarkdown(text) {
|
|
159
|
-
return (
|
|
160
|
-
String(text ?? "")
|
|
161
|
-
.replace(/^\s{0,3}#{1,6}\s+/gmu, "") // 标题井号
|
|
162
|
-
.replace(/^[ \t]*\|?[\s:|\t-]+\|[\s:|\t-]*$/gmu, "") // 表格分隔行 |---|---|
|
|
163
|
-
// 表格数据行 | a | b | → "a — b"(竖线对普通用户就是噪音)
|
|
164
|
-
.replace(
|
|
165
|
-
/^[ \t]*\|(.+)\|[ \t]*$/gmu,
|
|
166
|
-
(/** @type {string} */ _m, /** @type {string} */ body) =>
|
|
167
|
-
body
|
|
168
|
-
.split("|")
|
|
169
|
-
.map((cell) => cell.trim())
|
|
170
|
-
.filter((cell) => cell !== "")
|
|
171
|
-
.join(" — "),
|
|
172
|
-
)
|
|
173
|
-
.replace(/\*\*([^*\n]+)\*\*/gu, "$1") // **粗体**
|
|
174
|
-
.replace(/(?<![*\w])\*([^*\n]+)\*(?!\*)/gu, "$1") // *斜体*
|
|
175
|
-
.replace(/`{3,}[a-z]*\n?/giu, "") // ``` 代码围栏
|
|
176
|
-
.replace(/`([^`\n]+)`/gu, "$1") // `行内代码`
|
|
177
|
-
.replace(/^\s*[-*+]\s+/gmu, "· ") // 列表符号
|
|
178
|
-
.replace(/^\s*>\s?/gmu, "") // 引用
|
|
179
|
-
.replace(/\n{3,}/gu, "\n\n") // 压掉多余空行
|
|
180
|
-
.trim()
|
|
181
|
-
);
|
|
206
|
+
if (text.length <= maxChars) return text;
|
|
207
|
+
// 截断点可能落在代码围栏里:先补闭合,补不下就退到围栏之前,避免输入框里留半段代码。
|
|
208
|
+
return `${truncateMarkdown(text, maxChars - 1)}…`;
|
|
182
209
|
}
|
|
183
210
|
|
|
184
211
|
/**
|
|
@@ -208,7 +235,7 @@ export const THREAD_FLAG = "--thread";
|
|
|
208
235
|
/**
|
|
209
236
|
* 解析命令参数里的线程标记。
|
|
210
237
|
*
|
|
211
|
-
* 为什么用「命令行标记」而不是 Remote
|
|
238
|
+
* 为什么用「命令行标记」而不是 Remote:抽屉发问必须走 composer 提交,因为真实 Agent
|
|
212
239
|
* 只能从命令上下文拿到(见 ADR 0016)。所以线程 id 只能随这行文本一起传进来。
|
|
213
240
|
* @param {string} raw
|
|
214
241
|
* @returns {{ threadId: string, question: string }}
|
|
@@ -222,34 +249,6 @@ export function parseThreadFlag(raw) {
|
|
|
222
249
|
return { threadId: match[1], question: match[2].trim() };
|
|
223
250
|
}
|
|
224
251
|
|
|
225
|
-
/**
|
|
226
|
-
* 线程列表(给浮层展示):按最后一条时间倒序,每项带条数与首问。
|
|
227
|
-
* @param {any[]} records
|
|
228
|
-
* @returns {{ threadId: string, turns: number, question: string, answer: string, answerPlain: string, answerSegments: AnswerSegment[], lastId: string, cost: any, ms: number, at: number }[]}
|
|
229
|
-
*/
|
|
230
|
-
export function listThreads(records) {
|
|
231
|
-
return groupThreads(records)
|
|
232
|
-
.map((thread) => ({
|
|
233
|
-
threadId: thread.threadId,
|
|
234
|
-
turns: thread.items.length,
|
|
235
|
-
question: String(thread.items[0]?.question ?? ""),
|
|
236
|
-
answer: String(thread.last?.answer ?? ""),
|
|
237
|
-
// 展示用:去掉 Markdown 噪音但保留代码块(列表里显示原文的话,用户看到的是
|
|
238
|
-
// `**粗体**`、`|表|格|`、`|---|`,实测被抱怨「为什么给我一堆井号和竖线」)。
|
|
239
|
-
answerPlain: stripMarkdown(String(thread.last?.answer ?? "")),
|
|
240
|
-
// 渲染用:切好的段(代码块 / 链接 / 文本)。解析只在这里做一份,
|
|
241
|
-
// client 只负责把 kind 映射成元素(classic script 无法 import 这个模块)。
|
|
242
|
-
answerSegments: parseRichSegments(
|
|
243
|
-
stripMarkdown(String(thread.last?.answer ?? ""), { keepFence: true }),
|
|
244
|
-
),
|
|
245
|
-
lastId: String(thread.last?.id ?? ""),
|
|
246
|
-
cost: thread.last?.cost ?? null,
|
|
247
|
-
ms: Number(thread.last?.ms ?? 0),
|
|
248
|
-
at: thread.at,
|
|
249
|
-
}))
|
|
250
|
-
.sort((a, b) => b.at - a.at);
|
|
251
|
-
}
|
|
252
|
-
|
|
253
252
|
/** 范围档位(枚举,避免自由文本带来的歧义)。 */
|
|
254
253
|
export const SCOPES = ["session", "recent", "selection"];
|
|
255
254
|
|
|
@@ -281,67 +280,3 @@ export function parseCommandArgs(raw) {
|
|
|
281
280
|
}
|
|
282
281
|
return { threadId, scope, question: rest.trim() };
|
|
283
282
|
}
|
|
284
|
-
|
|
285
|
-
/**
|
|
286
|
-
* @typedef {{ kind: "text", text: string }} TextSegment
|
|
287
|
-
* @typedef {{ kind: "code", lang: string, text: string }} CodeSegment
|
|
288
|
-
* @typedef {{ kind: "link", text: string, href: string }} LinkSegment
|
|
289
|
-
* @typedef {TextSegment | CodeSegment | LinkSegment} AnswerSegment
|
|
290
|
-
*/
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* 把答案文本切成渲染段:代码块 / 链接 / 普通文本。
|
|
294
|
-
*
|
|
295
|
-
* 为什么需要它:`answerPlain` 保留了 ``` 围栏(`keepFence`),client 才能识别代码块边界,
|
|
296
|
-
* 把代码渲染成等宽 `<pre>` 而**不显示** ``` 本身;普通文本里的 URL 变成可点链接
|
|
297
|
-
* (之前答案里的链接是死文本)。
|
|
298
|
-
*
|
|
299
|
-
* 刻意**不做**完整 Markdown 渲染(表格/标题/粗体):仓库不引入构建步骤(ADR 0001),
|
|
300
|
-
* 手写完整渲染器的成本与风险远大于收益。粗体/表格已由 stripMarkdown 变成可读标点。
|
|
301
|
-
* @param {string} text
|
|
302
|
-
* @returns {AnswerSegment[]}
|
|
303
|
-
*/
|
|
304
|
-
export function parseRichSegments(text) {
|
|
305
|
-
const raw = String(text ?? "");
|
|
306
|
-
/** @type {AnswerSegment[]} */
|
|
307
|
-
const out = [];
|
|
308
|
-
// 1) 先按围栏切出代码块
|
|
309
|
-
const fenceRe = /```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/gu;
|
|
310
|
-
let last = 0;
|
|
311
|
-
for (;;) {
|
|
312
|
-
const match = fenceRe.exec(raw);
|
|
313
|
-
if (match === null) break;
|
|
314
|
-
if (match.index > last) out.push(...splitLinks(raw.slice(last, match.index)));
|
|
315
|
-
out.push({ kind: "code", lang: match[1] ?? "", text: (match[2] ?? "").replace(/\n+$/u, "") });
|
|
316
|
-
last = match.index + match[0].length;
|
|
317
|
-
}
|
|
318
|
-
if (last < raw.length) out.push(...splitLinks(raw.slice(last)));
|
|
319
|
-
return out.length > 0 ? out : [{ kind: "text", text: raw }];
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/**
|
|
323
|
-
* 把一段普通文本按 URL 切成 text/link 段。
|
|
324
|
-
* @param {string} text
|
|
325
|
-
* @returns {AnswerSegment[]}
|
|
326
|
-
*/
|
|
327
|
-
function splitLinks(text) {
|
|
328
|
-
/** @type {AnswerSegment[]} */
|
|
329
|
-
const out = [];
|
|
330
|
-
// 只认 http(s);末尾的标点(。,;:!?)】」)不属于 URL。
|
|
331
|
-
const urlRe = /https?:\/\/[^\s<>()\u3000-\u303f\uff00-\uffef]+/gu;
|
|
332
|
-
let last = 0;
|
|
333
|
-
for (;;) {
|
|
334
|
-
const match = urlRe.exec(text);
|
|
335
|
-
if (match === null) break;
|
|
336
|
-
const raw = match[0];
|
|
337
|
-
const trimmed = raw.replace(/[.,;:!?]+$/u, "");
|
|
338
|
-
if (match.index > last) out.push({ kind: "text", text: text.slice(last, match.index) });
|
|
339
|
-
if (trimmed !== "") out.push({ kind: "link", text: trimmed, href: trimmed });
|
|
340
|
-
const rest = raw.slice(trimmed.length);
|
|
341
|
-
if (rest !== "") out.push({ kind: "text", text: rest });
|
|
342
|
-
last = match.index + raw.length;
|
|
343
|
-
}
|
|
344
|
-
if (last < text.length) out.push({ kind: "text", text: text.slice(last) });
|
|
345
|
-
if (out.length === 0 && text !== "") out.push({ kind: "text", text });
|
|
346
|
-
return out;
|
|
347
|
-
}
|
package/locale/en.json
CHANGED
|
@@ -10,10 +10,11 @@
|
|
|
10
10
|
"noHistory": "No side question yet in this session."
|
|
11
11
|
},
|
|
12
12
|
"answer": {
|
|
13
|
-
"meta": "btw · new {newTokens} tokens · cached {cachedTokens} · {ms}
|
|
13
|
+
"meta": "btw · new {newTokens} tokens · cached {cachedTokens} · {ms}",
|
|
14
14
|
"reopen": "Last side question: {question}",
|
|
15
15
|
"truncated": "The answer was cut off; ask again to retry.",
|
|
16
|
-
"questionHeading": "Side question: {question}"
|
|
16
|
+
"questionHeading": "Side question: {question}",
|
|
17
|
+
"panelOnly": "Side question answered; the full answer is in the side-question panel."
|
|
17
18
|
},
|
|
18
19
|
"error": {
|
|
19
20
|
"forkUnavailable": "Side questions are unavailable right now (the subagent runtime is not loaded).",
|