pi-web-ui 0.100.0 → 0.101.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/CHANGELOG.md +39 -1
- package/README.md +46 -44
- package/README.zh-CN.md +41 -39
- package/bin/pi-web-ui.mjs +4 -10
- package/dist/server/agent-formatters.js +191 -0
- package/dist/server/agent-service-daemon.js +1266 -0
- package/dist/server/agent-service.js +9883 -12935
- package/dist/server/approval-default-rules.js +158 -0
- package/dist/server/approval-rules.js +41 -167
- package/dist/server/ask-user-question-tool.js +94 -0
- package/dist/server/attachment-store.js +38 -1
- package/dist/server/bash-tool.js +83 -0
- package/dist/server/browser-page-tool.js +207 -0
- package/dist/server/client-id-utils.js +51 -0
- package/dist/server/client-state.js +23 -2
- package/dist/server/compaction-markers.js +34 -1
- package/dist/server/context-budget-runner.js +43 -0
- package/dist/server/dangling-tools.js +18 -5
- package/dist/server/delegate-mode.js +1 -0
- package/dist/server/dispatch-domain-handlers.js +631 -0
- package/dist/server/dispatch-plugin-handlers.js +300 -0
- package/dist/server/dsh/dsh-agent-service.js +9 -1
- package/dist/server/goal-evidence.js +9 -2
- package/dist/server/goal-service.js +1 -1
- package/dist/server/hashline-engine.js +1 -1
- package/dist/server/index.js +191 -969
- package/dist/server/left-panel-running.js +115 -0
- package/dist/server/lsp-tool.js +40 -12
- package/dist/server/markers-list-tool.js +34 -0
- package/dist/server/market-service.js +277 -0
- package/dist/server/mcp-bridge.js +137 -30
- package/dist/server/mcp-hot-reload.js +84 -27
- package/dist/server/mcp-manager.js +215 -0
- package/dist/server/message-entry-resolver.js +32 -0
- package/dist/server/orphan-manager.js +44 -0
- package/dist/server/persona-chain.js +63 -0
- package/dist/server/plan-mode.js +2 -0
- package/dist/server/plan-update-tool.js +96 -0
- package/dist/server/plugin-api-catalog.js +20 -0
- package/dist/server/plugin-facilities.js +13 -3
- package/dist/server/plugin-ui-slots.js +39 -0
- package/dist/server/plugins.js +71 -38
- package/dist/server/preset-fields.js +7 -0
- package/dist/server/preset-share.js +1 -0
- package/dist/server/process-utils.js +30 -0
- package/dist/server/prompt-assembler.js +80 -0
- package/dist/server/scm-commitmsg.js +74 -0
- package/dist/server/serialize.js +97 -7
- package/dist/server/session-branch.js +367 -0
- package/dist/server/session-parser.js +235 -0
- package/dist/server/session-search.js +158 -0
- package/dist/server/settings-service.js +13 -1
- package/dist/server/skill-content-filler.js +33 -0
- package/dist/server/subagent-handoff.js +18 -0
- package/dist/server/subagent-helpers.js +88 -0
- package/dist/server/terminals.js +155 -58
- package/dist/server/tool-guards.js +527 -0
- package/dist/server/tool-host-factories.js +217 -0
- package/dist/server/tool-manager.js +30 -5
- package/dist/server/wait-subscription-scan.js +46 -1
- package/dist/server/workspace-snapshot.js +18 -0
- package/extensions/webui.ts +90 -24
- package/package.json +1 -1
- package/plugin-sdk/README.md +17 -0
- package/plugin-sdk/index.d.ts +17 -0
- package/plugin-sdk/index.mjs +5 -0
- package/plugins/catalog.json +20 -0
- package/themes/aetheris.css +3 -1
- package/themes/translucent.css +8 -1
- package/themes/transparent.css +9 -1
- package/web/dist/assets/{TerminalPanel-C3I1Mc-C.js → TerminalPanel-DD7I5_aC.js} +1 -1
- package/web/dist/assets/index-CpjA1YdT.css +1 -0
- package/web/dist/assets/index-nKn87VuM.js +678 -0
- package/web/dist/index.html +2 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-B-E2EM_0.css +0 -1
- package/web/dist/assets/index-BYumAaGi.js +0 -379
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* prompt-assembler — 提示词渲染判定、上下文 Token 估算与定稿 Usage 探测纯函数。
|
|
3
|
+
*
|
|
4
|
+
* 负责:
|
|
5
|
+
* - estimateNonSystemTokens: 估算非系统消息与正在流式的助手内容的 token 占用
|
|
6
|
+
* - hasSettledAssistantUsage: 判定会话中是否已有定稿的助手 usage(input/output/totalTokens)
|
|
7
|
+
* - shouldRenderMainCompose: 判定当前预设/覆盖/工具开关是否需要渲染自定义系统提示词
|
|
8
|
+
*
|
|
9
|
+
* 从 agent-service.ts 抽出为独立模块。
|
|
10
|
+
*/
|
|
11
|
+
import { estimateTokens } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import { DEFAULT_PROMPT_TEMPLATE, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
|
|
13
|
+
/**
|
|
14
|
+
* 会话是否已获得定稿的助手模型 usage(决定是使用真实的 usage 还是估算值)。
|
|
15
|
+
*/
|
|
16
|
+
export function hasSettledAssistantUsage(messages) {
|
|
17
|
+
if (!Array.isArray(messages))
|
|
18
|
+
return false;
|
|
19
|
+
try {
|
|
20
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
21
|
+
const m = messages[i];
|
|
22
|
+
if (m && m.role === "assistant" && m.usage) {
|
|
23
|
+
const u = m.usage;
|
|
24
|
+
if ((u.input ?? 0) > 0 || (u.totalTokens ?? 0) > 0 || (u.output ?? 0) > 0) {
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
// fallback
|
|
32
|
+
}
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 估算会话中所有非系统消息(用户消息、工具调用/结果、自定义消息以及正在流式的助手内容)的 Token 开销。
|
|
37
|
+
* 用于在尚未获得定稿 LLM usage 时,配合精准的 baseTokens 给出平滑、真实的上下文预估,
|
|
38
|
+
* 杜绝 SDK 内部全量遍历粗估系统提示词与 baseTokens 双重叠加导致首轮突增翻倍。
|
|
39
|
+
*/
|
|
40
|
+
export function estimateNonSystemTokens(messages, streamingMessage) {
|
|
41
|
+
let total = 0;
|
|
42
|
+
if (!Array.isArray(messages))
|
|
43
|
+
return total;
|
|
44
|
+
try {
|
|
45
|
+
for (const m of messages) {
|
|
46
|
+
if (m?.role !== "system") {
|
|
47
|
+
total += estimateTokens(m);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (streamingMessage) {
|
|
51
|
+
total += estimateTokens(streamingMessage);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// best-effort
|
|
56
|
+
}
|
|
57
|
+
return total;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* 判定当前设置与预设是否属于定制模式,需要渲染独立系统提示词而非依赖 SDK 默认装配。
|
|
61
|
+
*/
|
|
62
|
+
export function shouldRenderMainCompose(opts) {
|
|
63
|
+
const tpl = (opts.promptTemplate ?? "").trim();
|
|
64
|
+
const ovs = opts.promptOverrides ?? {};
|
|
65
|
+
const hasOverride = Object.values(ovs).some((v) => typeof v === "string" && v.trim());
|
|
66
|
+
const preset = opts.preset ?? "standard";
|
|
67
|
+
return !!tpl || hasOverride || preset !== "standard" || opts.disabledToolCount > 0 || opts.isLazy === true;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* 渲染组合模板。非定制状态返回 undefined 让 SDK 内部装配。
|
|
71
|
+
*/
|
|
72
|
+
export function renderMainCompose(inputs, opts) {
|
|
73
|
+
if (!shouldRenderMainCompose(opts))
|
|
74
|
+
return undefined;
|
|
75
|
+
const texts = resolveSectionTexts(inputs);
|
|
76
|
+
const tpl = (opts.promptTemplate ?? "").trim();
|
|
77
|
+
const ovs = opts.promptOverrides ?? {};
|
|
78
|
+
const hasOverride = Object.values(ovs).some((v) => typeof v === "string" && v.trim());
|
|
79
|
+
return renderPromptTemplate(tpl || DEFAULT_PROMPT_TEMPLATE, texts, hasOverride ? ovs : undefined);
|
|
80
|
+
}
|
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
* getting that). Only a repo with no commits yet falls back to the UI
|
|
19
19
|
* language passed as fallbackLang.
|
|
20
20
|
*/
|
|
21
|
+
import { isNotRepoError, scmCommitContext } from "./scm.js";
|
|
22
|
+
import { pick } from "./i18n.js";
|
|
23
|
+
/** SCM AI 提交信息生成超时时间(毫秒) */
|
|
24
|
+
export const SCM_COMMITMSG_TIMEOUT_MS = 60_000;
|
|
21
25
|
/** Hard cap for the generated subject — the commit input is single-line and
|
|
22
26
|
* this keeps a chatty model from filling the whole header row. */
|
|
23
27
|
export const MAX_COMMITMSG_LEN = 200;
|
|
@@ -138,3 +142,73 @@ export function sanitizeCommitMessage(raw) {
|
|
|
138
142
|
out = `${out.slice(0, MAX_COMMITMSG_LEN - 1).trimEnd()}…`;
|
|
139
143
|
return out;
|
|
140
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* 完整的 SCM AI 提交信息生成逻辑封装:
|
|
147
|
+
* 提取 git 差异上下文 -> 组装 prompt -> 调用模型 completeSimple -> 结果清洗校验
|
|
148
|
+
*/
|
|
149
|
+
export async function generateScmCommitMessage(opts) {
|
|
150
|
+
const { cwd, model, runtime, lang, promptMode = "append", customPrompt = "", timeoutMs = SCM_COMMITMSG_TIMEOUT_MS, } = opts;
|
|
151
|
+
try {
|
|
152
|
+
const ctx = await scmCommitContext(cwd, () => lang);
|
|
153
|
+
const input = buildCommitMsgInput(ctx, lang === "zh" ? "zh" : "en");
|
|
154
|
+
if (!input) {
|
|
155
|
+
return {
|
|
156
|
+
ok: false,
|
|
157
|
+
error: pick(lang, "没有可描述的更改(工作区干净)", "Nothing to describe (working tree clean)", "scm.commitmsg.no.changes"),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
const ac = new AbortController();
|
|
161
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
162
|
+
const systemPrompt = buildCommitMsgPrompt(promptMode, customPrompt);
|
|
163
|
+
let msg;
|
|
164
|
+
try {
|
|
165
|
+
msg = await runtime.completeSimple(model, {
|
|
166
|
+
systemPrompt,
|
|
167
|
+
messages: [
|
|
168
|
+
{
|
|
169
|
+
role: "user",
|
|
170
|
+
timestamp: Date.now(),
|
|
171
|
+
content: [{ type: "text", text: input }],
|
|
172
|
+
},
|
|
173
|
+
],
|
|
174
|
+
}, { signal: ac.signal, maxTokens: 400 });
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
}
|
|
179
|
+
if (msg.stopReason === "error" || msg.stopReason === "aborted") {
|
|
180
|
+
return {
|
|
181
|
+
ok: false,
|
|
182
|
+
error: msg.errorMessage ||
|
|
183
|
+
pick(lang, `模型异常终止(${msg.stopReason})`, `Model terminated abnormally (${msg.stopReason})`, "scm.commitmsg.model.terminated"),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const raw = msg.content
|
|
187
|
+
.filter((b) => b.type === "text")
|
|
188
|
+
.map((b) => b.text ?? "")
|
|
189
|
+
.join("\n");
|
|
190
|
+
const text = sanitizeCommitMessage(raw);
|
|
191
|
+
if (!text) {
|
|
192
|
+
return {
|
|
193
|
+
ok: false,
|
|
194
|
+
error: pick(lang, "模型返回了空的提交信息", "The model returned an empty commit message", "scm.commitmsg.empty"),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
return { ok: true, text };
|
|
198
|
+
}
|
|
199
|
+
catch (err) {
|
|
200
|
+
if (isNotRepoError(err)) {
|
|
201
|
+
return {
|
|
202
|
+
ok: false,
|
|
203
|
+
error: pick(lang, "当前目录不是 Git 仓库", "Current directory is not a Git repository", "scm.commitmsg.not.repo"),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
if (err instanceof Error && /abort/i.test(`${err.name} ${err.message}`)) {
|
|
207
|
+
return {
|
|
208
|
+
ok: false,
|
|
209
|
+
error: pick(lang, `生成提交信息超时(${Math.round(timeoutMs / 1000)} 秒)`, `Commit-message generation timed out (${Math.round(timeoutMs / 1000)}s)`, "scm.commitmsg.timeout"),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
213
|
+
}
|
|
214
|
+
}
|
package/dist/server/serialize.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { splitQuotedPrompt } from "./text-quote.js";
|
|
2
|
+
import { saveAttachmentSync } from "./attachment-store.js";
|
|
2
3
|
export const TEXT_CAP = 200_000;
|
|
3
4
|
export const TOOL_OUTPUT_CAP = 100_000;
|
|
4
5
|
export const ARGS_CAP = 20_000;
|
|
@@ -18,6 +19,68 @@ const TOOL_RESULT_IMAGE_MAX = 8;
|
|
|
18
19
|
* 前端还得写容错);工具作者应自己封顶(见 present-files-tool.ts 的摘录预算)。
|
|
19
20
|
*/
|
|
20
21
|
const TOOL_DETAILS_CAP = 64_000;
|
|
22
|
+
/**
|
|
23
|
+
* 对带有嵌套调用列表(如 codemode 的 details.calls)的 details 做安全预算裁剪。
|
|
24
|
+
* 当 JSON 体积超过 TOOL_DETAILS_CAP(64KB)时,不直接丢弃整包,而是保留首尾
|
|
25
|
+
* 关键调用并精简单项 args/error 长度,保证 UI 仍能渲染出调用树。
|
|
26
|
+
*/
|
|
27
|
+
export function pruneCallsDetails(details, cap) {
|
|
28
|
+
const rawCalls = details.calls;
|
|
29
|
+
if (!Array.isArray(rawCalls))
|
|
30
|
+
return undefined;
|
|
31
|
+
const sanitizeCall = (c) => {
|
|
32
|
+
if (typeof c !== "object" || c === null)
|
|
33
|
+
return c;
|
|
34
|
+
const call = { ...c };
|
|
35
|
+
if (typeof call.args === "string" && call.args.length > 200) {
|
|
36
|
+
call.args = `${call.args.slice(0, 197)}...`;
|
|
37
|
+
}
|
|
38
|
+
if (typeof call.error === "string" && call.error.length > 300) {
|
|
39
|
+
call.error = `${call.error.slice(0, 297)}...`;
|
|
40
|
+
}
|
|
41
|
+
return call;
|
|
42
|
+
};
|
|
43
|
+
let calls = rawCalls.map(sanitizeCall);
|
|
44
|
+
let candidate = { ...details, calls };
|
|
45
|
+
let json = JSON.stringify(candidate);
|
|
46
|
+
if (json.length <= cap)
|
|
47
|
+
return candidate;
|
|
48
|
+
const headCount = 20;
|
|
49
|
+
const tailCount = 10;
|
|
50
|
+
if (calls.length > headCount + tailCount) {
|
|
51
|
+
const omitted = calls.length - (headCount + tailCount);
|
|
52
|
+
calls = [
|
|
53
|
+
...calls.slice(0, headCount),
|
|
54
|
+
{
|
|
55
|
+
id: "omitted",
|
|
56
|
+
name: `... (${omitted} calls omitted) ...`,
|
|
57
|
+
args: "",
|
|
58
|
+
status: "cancelled",
|
|
59
|
+
},
|
|
60
|
+
...calls.slice(-tailCount),
|
|
61
|
+
];
|
|
62
|
+
candidate = { ...details, calls };
|
|
63
|
+
json = JSON.stringify(candidate);
|
|
64
|
+
if (json.length <= cap)
|
|
65
|
+
return candidate;
|
|
66
|
+
}
|
|
67
|
+
if (calls.length > 10) {
|
|
68
|
+
calls = [
|
|
69
|
+
...calls.slice(0, 5),
|
|
70
|
+
{
|
|
71
|
+
id: "omitted",
|
|
72
|
+
name: `... (${rawCalls.length - 8} calls omitted) ...`,
|
|
73
|
+
args: "",
|
|
74
|
+
status: "cancelled",
|
|
75
|
+
},
|
|
76
|
+
...calls.slice(-3),
|
|
77
|
+
];
|
|
78
|
+
candidate = { ...details, calls };
|
|
79
|
+
if (JSON.stringify(candidate).length <= cap)
|
|
80
|
+
return candidate;
|
|
81
|
+
}
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
21
84
|
export function truncate(s, cap) {
|
|
22
85
|
const str = typeof s === "string" ? s : String(s ?? "");
|
|
23
86
|
if (str.length <= cap)
|
|
@@ -37,16 +100,36 @@ function imageBlockToUi(b, cap = Number.POSITIVE_INFINITY) {
|
|
|
37
100
|
if (typeof src?.url === "string" && src.url)
|
|
38
101
|
return { type: "image", dataUrl: src.url };
|
|
39
102
|
if (typeof img.data === "string" && img.data.length > 0) {
|
|
40
|
-
|
|
41
|
-
if (dataUrl.length > cap)
|
|
103
|
+
if (img.data.length > cap)
|
|
42
104
|
return undefined;
|
|
43
|
-
|
|
105
|
+
const mimeType = img.mimeType ?? "image/png";
|
|
106
|
+
try {
|
|
107
|
+
const buf = Buffer.from(img.data, "base64");
|
|
108
|
+
const rec = saveAttachmentSync(buf, mimeType);
|
|
109
|
+
return { type: "image", dataUrl: rec.url, mimeType };
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
const dataUrl = `data:${mimeType};base64,${img.data}`;
|
|
113
|
+
if (dataUrl.length > cap)
|
|
114
|
+
return undefined;
|
|
115
|
+
return { type: "image", dataUrl, mimeType };
|
|
116
|
+
}
|
|
44
117
|
}
|
|
45
118
|
if (src?.type === "base64" && src.data) {
|
|
46
|
-
|
|
47
|
-
if (dataUrl.length > cap)
|
|
119
|
+
if (src.data.length > cap)
|
|
48
120
|
return undefined;
|
|
49
|
-
|
|
121
|
+
const mimeType = src.mediaType ?? "image/png";
|
|
122
|
+
try {
|
|
123
|
+
const buf = Buffer.from(src.data, "base64");
|
|
124
|
+
const rec = saveAttachmentSync(buf, mimeType);
|
|
125
|
+
return { type: "image", dataUrl: rec.url, mimeType };
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
const dataUrl = `data:${mimeType};base64,${src.data}`;
|
|
129
|
+
if (dataUrl.length > cap)
|
|
130
|
+
return undefined;
|
|
131
|
+
return { type: "image", dataUrl, mimeType };
|
|
132
|
+
}
|
|
50
133
|
}
|
|
51
134
|
return undefined;
|
|
52
135
|
}
|
|
@@ -273,8 +356,15 @@ export function serializeMessage(m, seq) {
|
|
|
273
356
|
// ask_user_question/todo_list 同理。体积封顶,超限整丢(见 TOOL_DETAILS_CAP)。
|
|
274
357
|
if (m.details !== undefined) {
|
|
275
358
|
try {
|
|
276
|
-
|
|
359
|
+
const json = JSON.stringify(m.details);
|
|
360
|
+
if (json.length <= TOOL_DETAILS_CAP) {
|
|
277
361
|
msg.details = m.details;
|
|
362
|
+
}
|
|
363
|
+
else if (typeof m.details === "object" && m.details !== null && "calls" in m.details) {
|
|
364
|
+
const pruned = pruneCallsDetails(m.details, TOOL_DETAILS_CAP);
|
|
365
|
+
if (pruned)
|
|
366
|
+
msg.details = pruned;
|
|
367
|
+
}
|
|
278
368
|
}
|
|
279
369
|
catch {
|
|
280
370
|
// 循环引用等序列化不了的值:details 是附加信息,丢掉不影响消息本体。
|
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session branch evaluation, leaf calibration, and transcript topological reordering.
|
|
3
|
+
*
|
|
4
|
+
* Background (issue #567):
|
|
5
|
+
* When multiple devices access the same session, or when extensions append metadata
|
|
6
|
+
* (e.g. type: "custom" such as plannotator entries) pointing to an older ancestor node,
|
|
7
|
+
* the appended entries appear at the physical tail of the JSONL file.
|
|
8
|
+
*
|
|
9
|
+
* In the SDK's SessionManager._buildIndex():
|
|
10
|
+
* for (const entry of this.fileEntries) {
|
|
11
|
+
* if (entry.type === "session") continue;
|
|
12
|
+
* this.byId.set(entry.id, entry);
|
|
13
|
+
* this.leafId = entry.id; // file tail becomes the active leaf!
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* If metadata was appended to an older branch (e.g. node 292 while the main branch
|
|
17
|
+
* continued to 557), reopening the session or restarting the backend will restore
|
|
18
|
+
* the older branch (292), making later task history (293..557) invisible even though
|
|
19
|
+
* it is still safely stored in the JSONL file.
|
|
20
|
+
*
|
|
21
|
+
* This module provides:
|
|
22
|
+
* 1. selectBestSessionLeaf: Evaluates branch candidates by message count, freshness,
|
|
23
|
+
* and depth, detecting metadata-only hijacking or stale branch reversion.
|
|
24
|
+
* 2. calibrateSessionLeaf: In-memory leaf calibration for any SessionManager instance.
|
|
25
|
+
* 3. reorderEntriesForMainBranch: Topological reordering of session entries to ensure
|
|
26
|
+
* the active main branch leaf resides at the physical tail of the transcript file
|
|
27
|
+
* without losing or modifying any custom/metadata entries.
|
|
28
|
+
*/
|
|
29
|
+
function parseEntryTimestamp(ts) {
|
|
30
|
+
if (typeof ts === "string") {
|
|
31
|
+
const parsed = Date.parse(ts);
|
|
32
|
+
if (!Number.isNaN(parsed))
|
|
33
|
+
return parsed;
|
|
34
|
+
}
|
|
35
|
+
else if (typeof ts === "number" && !Number.isNaN(ts)) {
|
|
36
|
+
return ts;
|
|
37
|
+
}
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Identify all branch leaves and compute branch metrics (from root to leaf).
|
|
42
|
+
*/
|
|
43
|
+
export function findBranchCandidates(entries) {
|
|
44
|
+
const validEntries = [];
|
|
45
|
+
const byId = new Map();
|
|
46
|
+
const childCount = new Map();
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
if (!entry || typeof entry.id !== "string" || !entry.id)
|
|
49
|
+
continue;
|
|
50
|
+
if (entry.type === "session")
|
|
51
|
+
continue;
|
|
52
|
+
validEntries.push(entry);
|
|
53
|
+
byId.set(entry.id, entry);
|
|
54
|
+
}
|
|
55
|
+
for (const entry of validEntries) {
|
|
56
|
+
const pid = typeof entry.parentId === "string" ? entry.parentId : null;
|
|
57
|
+
if (pid && byId.has(pid)) {
|
|
58
|
+
childCount.set(pid, (childCount.get(pid) ?? 0) + 1);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const leaves = [];
|
|
62
|
+
for (const entry of validEntries) {
|
|
63
|
+
const id = entry.id;
|
|
64
|
+
if ((childCount.get(id) ?? 0) === 0) {
|
|
65
|
+
leaves.push(entry);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (leaves.length === 0)
|
|
69
|
+
return [];
|
|
70
|
+
const candidates = [];
|
|
71
|
+
for (const leaf of leaves) {
|
|
72
|
+
const leafId = leaf.id;
|
|
73
|
+
const path = [];
|
|
74
|
+
const visited = new Set();
|
|
75
|
+
let cur = leafId;
|
|
76
|
+
while (cur !== null && byId.has(cur) && !visited.has(cur)) {
|
|
77
|
+
visited.add(cur);
|
|
78
|
+
const node = byId.get(cur);
|
|
79
|
+
path.push(node);
|
|
80
|
+
cur = typeof node.parentId === "string" ? node.parentId : null;
|
|
81
|
+
}
|
|
82
|
+
path.reverse(); // root -> ... -> leaf
|
|
83
|
+
let messageCount = 0;
|
|
84
|
+
let lastMessageTimestamp = 0;
|
|
85
|
+
for (const node of path) {
|
|
86
|
+
if (node.type === "message") {
|
|
87
|
+
messageCount += 1;
|
|
88
|
+
const ts = parseEntryTimestamp(node.timestamp);
|
|
89
|
+
if (ts > lastMessageTimestamp) {
|
|
90
|
+
lastMessageTimestamp = ts;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const tailTimestamp = parseEntryTimestamp(leaf.timestamp);
|
|
95
|
+
candidates.push({
|
|
96
|
+
leafId,
|
|
97
|
+
leafEntry: leaf,
|
|
98
|
+
totalEntries: path.length,
|
|
99
|
+
messageCount,
|
|
100
|
+
lastMessageTimestamp,
|
|
101
|
+
tailTimestamp,
|
|
102
|
+
pathIds: path.map((n) => n.id),
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
return candidates;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Find the lowest common ancestor (LCA) entry ID of two branches.
|
|
109
|
+
*/
|
|
110
|
+
function findLowestCommonAncestor(branchA, branchB) {
|
|
111
|
+
const setA = new Set(branchA.pathIds);
|
|
112
|
+
let lca = null;
|
|
113
|
+
for (const id of branchB.pathIds) {
|
|
114
|
+
if (setA.has(id)) {
|
|
115
|
+
lca = id;
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return lca;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Select the best branch leaf from all branch candidates.
|
|
125
|
+
*
|
|
126
|
+
* If multiple leaves exist, compares the currently selected leaf against the candidate
|
|
127
|
+
* pool. If the current leaf is on an abandoned metadata-only branch (e.g. extension
|
|
128
|
+
* wrote to an older node after a completed task) or significantly lags behind the main
|
|
129
|
+
* conversation in message count, selects the main branch leaf.
|
|
130
|
+
*/
|
|
131
|
+
export function selectBestSessionLeaf(entries, currentLeafId) {
|
|
132
|
+
const candidates = findBranchCandidates(entries);
|
|
133
|
+
if (candidates.length === 0)
|
|
134
|
+
return null;
|
|
135
|
+
if (candidates.length === 1) {
|
|
136
|
+
const single = candidates[0];
|
|
137
|
+
return {
|
|
138
|
+
bestLeafId: single.leafId,
|
|
139
|
+
currentLeafId: currentLeafId ?? null,
|
|
140
|
+
changed: currentLeafId !== undefined && currentLeafId !== null && currentLeafId !== single.leafId,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
// Sort candidates by preference:
|
|
144
|
+
// 1. Message count (descending)
|
|
145
|
+
// 2. Last message timestamp (descending)
|
|
146
|
+
// 3. Total entry depth (descending)
|
|
147
|
+
// 4. Leaf timestamp (descending)
|
|
148
|
+
const sorted = [...candidates].sort((a, b) => {
|
|
149
|
+
if (b.messageCount !== a.messageCount)
|
|
150
|
+
return b.messageCount - a.messageCount;
|
|
151
|
+
if (b.lastMessageTimestamp !== a.lastMessageTimestamp)
|
|
152
|
+
return b.lastMessageTimestamp - a.lastMessageTimestamp;
|
|
153
|
+
if (b.totalEntries !== a.totalEntries)
|
|
154
|
+
return b.totalEntries - a.totalEntries;
|
|
155
|
+
return b.tailTimestamp - a.tailTimestamp;
|
|
156
|
+
});
|
|
157
|
+
const bestCandidate = sorted[0];
|
|
158
|
+
if (!currentLeafId) {
|
|
159
|
+
return {
|
|
160
|
+
bestLeafId: bestCandidate.leafId,
|
|
161
|
+
currentLeafId: null,
|
|
162
|
+
changed: true,
|
|
163
|
+
reason: "No current leaf specified; selected deepest candidate",
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
const currentCandidate = candidates.find((c) => c.leafId === currentLeafId);
|
|
167
|
+
if (!currentCandidate) {
|
|
168
|
+
return {
|
|
169
|
+
bestLeafId: bestCandidate.leafId,
|
|
170
|
+
currentLeafId,
|
|
171
|
+
changed: true,
|
|
172
|
+
reason: `Current leaf "${currentLeafId}" not found in branch leaves`,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
if (currentCandidate.leafId === bestCandidate.leafId) {
|
|
176
|
+
return {
|
|
177
|
+
bestLeafId: bestCandidate.leafId,
|
|
178
|
+
currentLeafId,
|
|
179
|
+
changed: false,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
// Check if current leaf is a hijacked/stale branch:
|
|
183
|
+
const lca = findLowestCommonAncestor(currentCandidate, bestCandidate);
|
|
184
|
+
const lcaIndexCurrent = lca ? currentCandidate.pathIds.indexOf(lca) : -1;
|
|
185
|
+
const currentEntriesAfterLca = lcaIndexCurrent >= 0 ? currentCandidate.pathIds.slice(lcaIndexCurrent + 1) : [];
|
|
186
|
+
const byId = new Map();
|
|
187
|
+
for (const e of entries) {
|
|
188
|
+
if (e && typeof e.id === "string")
|
|
189
|
+
byId.set(e.id, e);
|
|
190
|
+
}
|
|
191
|
+
let currentMessagesAfterLca = 0;
|
|
192
|
+
for (const id of currentEntriesAfterLca) {
|
|
193
|
+
const node = byId.get(id);
|
|
194
|
+
if (node?.type === "message")
|
|
195
|
+
currentMessagesAfterLca += 1;
|
|
196
|
+
}
|
|
197
|
+
const lcaIndexBest = lca ? bestCandidate.pathIds.indexOf(lca) : -1;
|
|
198
|
+
const bestEntriesAfterLca = lcaIndexBest >= 0 ? bestCandidate.pathIds.slice(lcaIndexBest + 1) : [];
|
|
199
|
+
let bestMessagesAfterLca = 0;
|
|
200
|
+
for (const id of bestEntriesAfterLca) {
|
|
201
|
+
const node = byId.get(id);
|
|
202
|
+
if (node?.type === "message")
|
|
203
|
+
bestMessagesAfterLca += 1;
|
|
204
|
+
}
|
|
205
|
+
// Pattern A: Metadata-only branch hijacking (issue #567)
|
|
206
|
+
// Current branch has 0 messages after LCA (only custom / extension metadata),
|
|
207
|
+
// while best branch has real messages after LCA.
|
|
208
|
+
if (currentMessagesAfterLca === 0 && bestMessagesAfterLca > 0) {
|
|
209
|
+
return {
|
|
210
|
+
bestLeafId: bestCandidate.leafId,
|
|
211
|
+
currentLeafId,
|
|
212
|
+
changed: true,
|
|
213
|
+
reason: `Current branch has no messages after divergence (LCA=${lca}), while main branch has ${bestMessagesAfterLca} messages`,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
// Pattern B: Substantial message gap (stale branch restored after task completed elsewhere)
|
|
217
|
+
if (bestCandidate.messageCount > currentCandidate.messageCount) {
|
|
218
|
+
return {
|
|
219
|
+
bestLeafId: bestCandidate.leafId,
|
|
220
|
+
currentLeafId,
|
|
221
|
+
changed: true,
|
|
222
|
+
reason: `Main branch has ${bestCandidate.messageCount} messages vs current branch's ${currentCandidate.messageCount}`,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
// Otherwise, current branch has equal or valid intentional message history
|
|
226
|
+
return {
|
|
227
|
+
bestLeafId: currentCandidate.leafId,
|
|
228
|
+
currentLeafId,
|
|
229
|
+
changed: false,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Calibrate the active leaf of a SessionManager in memory.
|
|
234
|
+
*/
|
|
235
|
+
export function calibrateSessionLeaf(sessionManager) {
|
|
236
|
+
try {
|
|
237
|
+
const entries = sessionManager.getEntries();
|
|
238
|
+
const currentLeafId = sessionManager.getLeafId();
|
|
239
|
+
const result = selectBestSessionLeaf(entries, currentLeafId);
|
|
240
|
+
if (result && result.changed && result.bestLeafId) {
|
|
241
|
+
sessionManager.branch(result.bestLeafId);
|
|
242
|
+
return {
|
|
243
|
+
changed: true,
|
|
244
|
+
calibratedLeafId: result.bestLeafId,
|
|
245
|
+
previousLeafId: currentLeafId,
|
|
246
|
+
reason: result.reason,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
return { changed: false, calibratedLeafId: currentLeafId ?? undefined };
|
|
250
|
+
}
|
|
251
|
+
catch (err) {
|
|
252
|
+
return { changed: false, calibratedLeafId: sessionManager.getLeafId() ?? undefined, reason: String(err) };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Reorder entries topologically so that the main branch's leaf is at the tail of the transcript.
|
|
257
|
+
*
|
|
258
|
+
* Preserves all entries and valid parent-child relationships (every node still appears after
|
|
259
|
+
* its parent). Side-branch metadata attached to older nodes is placed before the main branch's
|
|
260
|
+
* continuing path so SDK SessionManager's sequential scan lands on the main branch leaf.
|
|
261
|
+
*/
|
|
262
|
+
export function reorderEntriesForMainBranch(entries) {
|
|
263
|
+
if (entries.length <= 1)
|
|
264
|
+
return { entries, changed: false };
|
|
265
|
+
const nonHeader = entries.filter((e) => e && e.type !== "session" && typeof e.id === "string");
|
|
266
|
+
if (nonHeader.length <= 1)
|
|
267
|
+
return { entries, changed: false };
|
|
268
|
+
const tail = nonHeader[nonHeader.length - 1];
|
|
269
|
+
const calibration = selectBestSessionLeaf(nonHeader, tail.id);
|
|
270
|
+
if (!calibration || !calibration.changed || !calibration.bestLeafId) {
|
|
271
|
+
return { entries, changed: false };
|
|
272
|
+
}
|
|
273
|
+
const bestLeafId = calibration.bestLeafId;
|
|
274
|
+
const candidates = findBranchCandidates(nonHeader);
|
|
275
|
+
const bestCandidate = candidates.find((c) => c.leafId === bestLeafId);
|
|
276
|
+
if (!bestCandidate)
|
|
277
|
+
return { entries, changed: false };
|
|
278
|
+
const bestPathSet = new Set(bestCandidate.pathIds);
|
|
279
|
+
// Separate entries into:
|
|
280
|
+
// 1. Header (type === "session")
|
|
281
|
+
// 2. Entries on the best path
|
|
282
|
+
// 3. Entries on side branches
|
|
283
|
+
const headerEntries = [];
|
|
284
|
+
const sideEntries = [];
|
|
285
|
+
const mainEntries = [];
|
|
286
|
+
for (const e of entries) {
|
|
287
|
+
if (e.type === "session") {
|
|
288
|
+
headerEntries.push(e);
|
|
289
|
+
}
|
|
290
|
+
else if (e.id && bestPathSet.has(e.id)) {
|
|
291
|
+
mainEntries.push(e);
|
|
292
|
+
}
|
|
293
|
+
else {
|
|
294
|
+
sideEntries.push(e);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
// If no side entries exist or main entries are empty, nothing to reorder
|
|
298
|
+
if (sideEntries.length === 0 || mainEntries.length === 0) {
|
|
299
|
+
return { entries, changed: false };
|
|
300
|
+
}
|
|
301
|
+
// We want to interleave side entries after their respective parent in main entries,
|
|
302
|
+
// BUT ensure that the continuation of the main branch ends with bestCandidate.leafId.
|
|
303
|
+
// A robust topological sort:
|
|
304
|
+
// Each side entry must come after its parent.
|
|
305
|
+
// Since side branches branched off an ancestor in mainEntries, we can place side entries
|
|
306
|
+
// as early as possible (immediately after their parent) so that the deep main branch entries
|
|
307
|
+
// remain at the end of the file.
|
|
308
|
+
const result = [...headerEntries];
|
|
309
|
+
const placed = new Set();
|
|
310
|
+
// Helper to place a side entry and its side descendants
|
|
311
|
+
const sideChildrenOf = new Map();
|
|
312
|
+
for (const s of sideEntries) {
|
|
313
|
+
const pid = typeof s.parentId === "string" ? s.parentId : "";
|
|
314
|
+
let list = sideChildrenOf.get(pid);
|
|
315
|
+
if (!list) {
|
|
316
|
+
list = [];
|
|
317
|
+
sideChildrenOf.set(pid, list);
|
|
318
|
+
}
|
|
319
|
+
list.push(s);
|
|
320
|
+
}
|
|
321
|
+
const placeSideDescendants = (parentId) => {
|
|
322
|
+
const children = sideChildrenOf.get(parentId);
|
|
323
|
+
if (!children)
|
|
324
|
+
return;
|
|
325
|
+
for (const child of children) {
|
|
326
|
+
if (child.id && !placed.has(child.id)) {
|
|
327
|
+
placed.add(child.id);
|
|
328
|
+
result.push(child);
|
|
329
|
+
placeSideDescendants(child.id);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
for (const m of mainEntries) {
|
|
334
|
+
if (m.id)
|
|
335
|
+
placed.add(m.id);
|
|
336
|
+
result.push(m);
|
|
337
|
+
if (m.id) {
|
|
338
|
+
placeSideDescendants(m.id);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
// Any dangling side entries with unknown parents placed before the final main entry if possible
|
|
342
|
+
for (const s of sideEntries) {
|
|
343
|
+
if (s.id && !placed.has(s.id)) {
|
|
344
|
+
placed.add(s.id);
|
|
345
|
+
// Insert before the last entry (which is the best leaf)
|
|
346
|
+
if (result.length > headerEntries.length + 1) {
|
|
347
|
+
result.splice(result.length - 1, 0, s);
|
|
348
|
+
}
|
|
349
|
+
else {
|
|
350
|
+
result.push(s);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
// Verify that the new last non-header entry is bestLeafId
|
|
355
|
+
const newNonHeader = result.filter((e) => e && e.type !== "session" && typeof e.id === "string");
|
|
356
|
+
const newTail = newNonHeader[newNonHeader.length - 1];
|
|
357
|
+
const successfullyReordered = newTail?.id === bestLeafId;
|
|
358
|
+
if (!successfullyReordered) {
|
|
359
|
+
// Fallback: don't alter if topological sort couldn't guarantee tail
|
|
360
|
+
return { entries, changed: false };
|
|
361
|
+
}
|
|
362
|
+
return {
|
|
363
|
+
entries: result,
|
|
364
|
+
changed: true,
|
|
365
|
+
reason: calibration.reason,
|
|
366
|
+
};
|
|
367
|
+
}
|