@240xu/dsh-message-ops 0.11.0 → 0.11.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 +39 -8
- package/package.json +1 -2
- package/src/client.js +468 -66
- package/src/index.js +30 -19
- package/src/ops-core.js +148 -23
- package/src/session-file.js +79 -13
- package/src/session-trash.js +38 -8
- package/test/branch-export-removed.test.js +0 -73
- package/test/client-p0-locks.test.js +0 -131
- package/test/client-perf-locks.test.js +0 -259
- package/test/composer-refill.test.js +0 -106
- package/test/derived-cache.test.js +0 -202
- package/test/dock-preview.test.js +0 -666
- package/test/fence.test.js +0 -181
- package/test/injected-regex.test.js +0 -62
- package/test/legacy-format.test.js +0 -120
- package/test/ops-core.test.js +0 -363
- package/test/ops-search.test.js +0 -104
- package/test/redo-contract.test.js +0 -55
- package/test/revert-commit.test.js +0 -98
- package/test/revert-contract.test.js +0 -118
- package/test/session-file.test.js +0 -86
- package/test/session-trash.test.js +0 -179
- package/test/step-restore.test.js +0 -112
- package/test/surface-visibility.test.js +0 -166
- package/test/transcript-visibility.test.js +0 -111
- package/test/undo-slash.test.js +0 -89
- package/test/user-revert-anchor.test.js +0 -103
- package/test/v4-stream-contract.test.js +0 -62
package/src/index.js
CHANGED
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
import { zstdCompressSync } from "node:zlib";
|
|
10
10
|
import { open as openFile, truncate as truncateFile, stat as statFile } from "node:fs/promises";
|
|
11
11
|
import { isSessionId, sessionIdVariants, findSessionDirs, readSessionFileAsync, listMessages, computeShadowed, messageText, messageTextFull, turnBounds, markCommitted } from "./session-file.js";
|
|
12
|
-
import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqFrom, buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, planNoticeWindow, noticeWindowPreamble, noticeWindowPostamble,
|
|
12
|
+
import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqFrom, buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, planNoticeWindow, noticeWindowPreamble, noticeWindowPostamble, sessionLogOf, alignLiveTurnCursor,
|
|
13
13
|
OpsError, planRevert, planDelete, planRestore, applyRestore, applySurfaceReplace,
|
|
14
|
-
restoreProgress, pendingRestoreTurns,
|
|
14
|
+
restoreProgress, pendingRestoreTurns, buildRestoreIndex, restoreProgressFromIndex, pendingRestoreTurnsFromIndex,
|
|
15
15
|
isTrustedApiRequest, isJsonContentType, webAuthGate,
|
|
16
16
|
} from "./ops-core.js";
|
|
17
17
|
import { deleteSessionToTrash, listTrash, restoreTrash, purgeTrash, resolveSessionTitle } from "./session-trash.js";
|
|
@@ -51,8 +51,8 @@ async function fence(targetCtx, req, res) {
|
|
|
51
51
|
}
|
|
52
52
|
// 0.10.8:宿主同条件 GET 被读全量(审计缺口)。宿主 /api admit = 三层围栏
|
|
53
53
|
// 之外还要 BrowserAuth cookie(无 cookie → 401);前端同源 fetch 自动带
|
|
54
|
-
// cookie
|
|
55
|
-
//
|
|
54
|
+
// cookie,取数不受影响。无 credentials 服务 = 老宿主旧围栏;有服务但
|
|
55
|
+
// 记录不可读 = 401 fail-closed(webAuthGate 内部告警一次)。
|
|
56
56
|
if (!(await webAuthGate(targetCtx, req))) {
|
|
57
57
|
sendJson(res, 401, { ok: false, error: "unauthorized (browser auth cookie required; reopen the URL printed by dsh web)" });
|
|
58
58
|
return false;
|
|
@@ -355,6 +355,7 @@ async function buildDerived(logPath) {
|
|
|
355
355
|
// seqText 索引,也不扫一遍 events(seqText 为 null 时下面两处都短路:
|
|
356
356
|
// 本循环直接跳过,marker 循环体也一次都不会执行)。
|
|
357
357
|
const seqText = messages.some((m) => m.marker === true) ? new Map() : null;
|
|
358
|
+
const restoreIndex = seqText ? buildRestoreIndex(events) : null;
|
|
358
359
|
for (const e of seqText ? events : []) {
|
|
359
360
|
if (!e || typeof e.seq !== "number") continue;
|
|
360
361
|
if (e.type !== "user/message" && e.type !== "assistant/message") continue;
|
|
@@ -379,10 +380,10 @@ async function buildDerived(logPath) {
|
|
|
379
380
|
// —— 这正是 opencode 的 `messages.slice(0, boundaryIndex)`(边界自己也不显示)。
|
|
380
381
|
for (const m of messages) {
|
|
381
382
|
if (!m || m.marker !== true) continue;
|
|
382
|
-
const prog =
|
|
383
|
+
const prog = restoreProgressFromIndex(restoreIndex, m.seq);
|
|
383
384
|
if (!prog) { m.restoreComplete = false; m.pendingTurns = []; continue; }
|
|
384
385
|
m.restoreComplete = prog.complete;
|
|
385
|
-
m.pendingTurns =
|
|
386
|
+
m.pendingTurns = pendingRestoreTurnsFromIndex(restoreIndex, m.seq, prog).map((t) => ({
|
|
386
387
|
upTo: t.seqs[t.seqs.length - 1],
|
|
387
388
|
count: t.seqs.length,
|
|
388
389
|
// 0.10.2:轮起点常落在注入行上(system-reminder / 后台任务 / 子代理通知),
|
|
@@ -621,8 +622,7 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
|
621
622
|
// 承载 notice,而不是拒绝。引擎 append-only 插不进已有 step,但合成一整个 turn 合法
|
|
622
623
|
//��已对官方校验闸实测:append 型 / 单节点 replace / 多节点 replace 全 PASS,遮蔽受保护头正确拒绝)。
|
|
623
624
|
// 带 reason:"message-ops",UI 与审计可识别,不与真实模型轮次混淆。
|
|
624
|
-
|
|
625
|
-
const turnStep = { turn: win.turn, step: win.step };
|
|
625
|
+
let win = planNoticeWindow(events);
|
|
626
626
|
const notice = mode === "delete"
|
|
627
627
|
? `[消息删除] 已遮蔽 seq ${seq}`
|
|
628
628
|
: null; // revert 文案含 shadowed 数量,规划后拼
|
|
@@ -630,6 +630,9 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
|
630
630
|
if (acq !== null && acq.session !== undefined) {
|
|
631
631
|
try {
|
|
632
632
|
const session = acq.session;
|
|
633
|
+
const liveEvents = sessionLogOf(session);
|
|
634
|
+
if (liveEvents) win = planNoticeWindow(liveEvents);
|
|
635
|
+
const turnStep = { turn: win.turn, step: win.step };
|
|
633
636
|
// 0.5.4(P0):v4 准入要求 system/message 带正 turn/step——缺字段时持久层
|
|
634
637
|
// encodeEventBatch 的 SessionFormatError 未捕获会**打死整个 dsh 进程**。
|
|
635
638
|
const plan = mode === "delete" ? planDelete(session.surface, seq) : planRevert(session.surface, seq);
|
|
@@ -649,6 +652,7 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
|
649
652
|
const event = applySurfaceReplace(session, plan.startSeq, plan.endSeq, plan.shadowedSeqs, text, turnStep);
|
|
650
653
|
// 必须闭合:否则引擎内存里 turn 16 永远开着 → isRunning 恒真 → 后续操作全被 409
|
|
651
654
|
for (const post of noticeWindowPostamble(win)) session.append(post.kind, post.data);
|
|
655
|
+
if (win.synthetic) alignLiveTurnCursor(targetCtx, session, win.turn);
|
|
652
656
|
flushSessions(targetCtx, session);
|
|
653
657
|
return {
|
|
654
658
|
ok: true, mode, seq,
|
|
@@ -678,7 +682,7 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
|
678
682
|
type: e.kind, seq: cursor++, time: baseTime + i, data: e.data,
|
|
679
683
|
}));
|
|
680
684
|
const marker = buildMarkerEvent({
|
|
681
|
-
seq: cursor++, time: baseTime + batch.length, turnStep, text, version: header?.version ?? 4,
|
|
685
|
+
seq: cursor++, time: baseTime + batch.length, turnStep: { turn: win.turn, step: win.step }, text, version: header?.version ?? 4,
|
|
682
686
|
startSeq: plan.startSeq, endSeq: plan.endSeq, shadowedSeqs: plan.shadowedSeqs,
|
|
683
687
|
});
|
|
684
688
|
batch.push(marker);
|
|
@@ -704,27 +708,34 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
|
|
|
704
708
|
// 0.8.0(B1 修复):步进恢复必须排除先前轮次已重放的源 seq,
|
|
705
709
|
// 否则每轮从区间头重放 → 消息副本成倍出现。
|
|
706
710
|
// 合成 turn 承载 notice 的完整理由见 opsCommit() 处(0.8.2,实测 340/364 空闲会话)。
|
|
707
|
-
const
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
711
|
+
const buildPlan = (sourceEvents) => {
|
|
712
|
+
const window = planNoticeWindow(sourceEvents);
|
|
713
|
+
const progress = restoreProgress(sourceEvents, restoreSeq);
|
|
714
|
+
const restorePlan = planRestore(sourceEvents, restoreSeq, upToSeq, progress ? progress.restoredSeqs : null);
|
|
715
|
+
restorePlan.turnStep = { turn: window.turn, step: window.step };
|
|
716
|
+
restorePlan.window = window;
|
|
717
|
+
if (discard) restorePlan.discard = true;
|
|
718
|
+
if (restorePlan.replayable.length === 0 && progress && !progress.complete && progress.pendingSeqs.length > 0) {
|
|
719
|
+
// 请求的 upTo 之前已全部重放过 → 只补一条进度 notice(不重复重放)
|
|
720
|
+
restorePlan.upToSeq = upToSeq != null ? Math.min(upToSeq, restorePlan.endSeq) : restorePlan.endSeq;
|
|
721
|
+
}
|
|
722
|
+
return { win: window, plan: restorePlan };
|
|
723
|
+
};
|
|
724
|
+
let { win, plan } = buildPlan(events);
|
|
717
725
|
const acq = await acquireSession(targetCtx, sessionId);
|
|
718
726
|
if (acq !== null && acq.session !== undefined) {
|
|
719
727
|
// 0.10.8 孤儿护栏(与 opsCommit 同型):planRestore/进度校验本就在 preamble
|
|
720
728
|
// 之前完成;applyRestore 里的引擎 append 若抛(如 replay 坐标错开),
|
|
721
729
|
// preamble 已落——闭合合成 turn 再原样抛出,不留常开孤儿窗口。
|
|
722
730
|
try {
|
|
731
|
+
const liveEvents = sessionLogOf(acq.session);
|
|
732
|
+
if (liveEvents) ({ win, plan } = buildPlan(liveEvents));
|
|
723
733
|
for (const pre of noticeWindowPreamble(win)) acq.session.append(pre.kind, pre.data);
|
|
724
734
|
const result = applyRestore(acq.session, plan, {
|
|
725
735
|
flush: () => { flushSessions(targetCtx, acq.session); },
|
|
726
736
|
});
|
|
727
737
|
for (const post of noticeWindowPostamble(win)) acq.session.append(post.kind, post.data);
|
|
738
|
+
if (win.synthetic) alignLiveTurnCursor(targetCtx, acq.session, win.turn);
|
|
728
739
|
return { ok: true, ...result, discarded: plan.discard === true, upToSeq: plan.upToSeq, restoredSourceSeqs: plan.replayable.map((i) => i.seq), range: { startSeq: plan.startSeq, endSeq: plan.endSeq } };
|
|
729
740
|
} catch (err) {
|
|
730
741
|
for (const post of noticeWindowPostamble(win)) {
|
package/src/ops-core.js
CHANGED
|
@@ -120,6 +120,21 @@ function messageSource(role, version) {
|
|
|
120
120
|
return { kind: "plugin", plugin: PLUGIN_NAME, role: r };
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
+
function assistantReplaySource(item, version) {
|
|
124
|
+
const source = item && item.source;
|
|
125
|
+
if (version === 4) {
|
|
126
|
+
if (!source || source.kind !== "model" || typeof source.provider !== "string" || !source.provider
|
|
127
|
+
|| typeof source.model !== "string" || !source.model) {
|
|
128
|
+
throw new OpsError("assistant replay requires the original model source", 500);
|
|
129
|
+
}
|
|
130
|
+
return { ...source };
|
|
131
|
+
}
|
|
132
|
+
if (source && typeof source === "object" && typeof source.kind === "string" && source.kind) {
|
|
133
|
+
return { ...source };
|
|
134
|
+
}
|
|
135
|
+
return messageSource("assistant", version);
|
|
136
|
+
}
|
|
137
|
+
|
|
123
138
|
/**
|
|
124
139
|
* 重放事件的 data 形状 —— **按事件类型分派**。
|
|
125
140
|
*
|
|
@@ -148,7 +163,7 @@ export function replayEventData(item, ts, version = 4) {
|
|
|
148
163
|
message: {
|
|
149
164
|
id: item.id ?? randomUUID(),
|
|
150
165
|
role: "assistant",
|
|
151
|
-
source:
|
|
166
|
+
source: assistantReplaySource(item, version),
|
|
152
167
|
content: [{ type: "text", text: item.text }],
|
|
153
168
|
},
|
|
154
169
|
// ⚠️ v4 契约 `stream: AssistantStreamRecord[]` **非可选**
|
|
@@ -221,6 +236,27 @@ export function deriveTurnStep(events) {
|
|
|
221
236
|
* @returns {{synthetic: boolean, turn: number, step: number,
|
|
222
237
|
* preamble?: Array, postamble?: Array}}
|
|
223
238
|
*/
|
|
239
|
+
/** 合成 turn 落盘后,把宿主 idle agent 的 turn 游标对齐到该 turn(否则下一条真实消息会重号)。 */
|
|
240
|
+
export function alignLiveTurnCursor(ctx, session, turn) {
|
|
241
|
+
if (!Number.isSafeInteger(turn) || turn < 1 || !session || typeof session.id !== "string") return false;
|
|
242
|
+
const agent = ctx && ctx.agents && typeof ctx.agents.get === "function" ? ctx.agents.get(session.id) : undefined;
|
|
243
|
+
if (!agent || agent.phase?.kind !== "idle" || typeof agent.setPhase !== "function") return false;
|
|
244
|
+
const lastTurn = Number.isSafeInteger(agent.phase.lastTurn) ? agent.phase.lastTurn : 0;
|
|
245
|
+
if (lastTurn >= turn) return false;
|
|
246
|
+
agent.setPhase({ kind: "idle", lastTurn: turn });
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function sessionLogOf(session) {
|
|
251
|
+
if (!session) return null;
|
|
252
|
+
if (Array.isArray(session.log)) return session.log;
|
|
253
|
+
if (Array.isArray(session.events)) return session.events;
|
|
254
|
+
if (typeof session.events === "function") {
|
|
255
|
+
try { const log = session.events(); return Array.isArray(log) ? log : null; } catch { return null; }
|
|
256
|
+
}
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
|
|
224
260
|
export function planNoticeWindow(events) {
|
|
225
261
|
let turn = null, step = null, maxTurn = 0;
|
|
226
262
|
for (const e of events ?? []) {
|
|
@@ -236,6 +272,7 @@ export function planNoticeWindow(events) {
|
|
|
236
272
|
}
|
|
237
273
|
// 会话正开着 turn+step(例如上一轮被中断)→ 直接用现成窗口,不造合成 turn
|
|
238
274
|
if (turn !== null && step !== null) return { synthetic: false, turn, step };
|
|
275
|
+
if (turn !== null) throw new OpsError("session is between steps; retry after the current turn settles", 409);
|
|
239
276
|
const nextTurn = maxTurn + 1;
|
|
240
277
|
return { synthetic: true, turn: nextTurn, step: 1 };
|
|
241
278
|
}
|
|
@@ -258,25 +295,27 @@ export function noticeWindowPostamble(win) {
|
|
|
258
295
|
// (dsh-session/lib/index.js:783-786)。UI 的 trajectory 装配器无防护地读
|
|
259
296
|
// `match.event.data.reason.kind`(dsh-client-ui-trajectory/lib/client.js:997-998)
|
|
260
297
|
// → 缺字段会让整个会话页白屏(ConversationNodeAssembler.replayContext 抛 TypeError)。
|
|
261
|
-
//
|
|
262
|
-
{ kind: "turn/end", data: { turn: win.turn, reason: { kind: "
|
|
298
|
+
// 用 "completed":这是成功的记账 turn;用 "interrupted" 会被聊天 UI 渲染成“已停止”。
|
|
299
|
+
{ kind: "turn/end", data: { turn: win.turn, reason: { kind: "completed" } } },
|
|
263
300
|
];
|
|
264
301
|
}
|
|
265
302
|
|
|
266
303
|
export function applySurfaceReplace(session, startSeq, endSeq, sourceEventSeqs, noticeText, turnStep) {
|
|
267
304
|
const ts = turnStep && Number.isSafeInteger(turnStep.turn) && turnStep.turn > 0
|
|
268
305
|
? turnStep : { turn: 1, step: 1 };
|
|
306
|
+
const sources = [...new Set((Array.isArray(sourceEventSeqs) ? sourceEventSeqs : []).flat(Infinity))];
|
|
307
|
+
if (!sources.every(Number.isSafeInteger)) throw new OpsError("surface replace sources must be integer seqs", 500);
|
|
269
308
|
const data = { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", source: messageSource("system", 4), content: [{ type: "text", text: noticeText }] } };
|
|
270
309
|
if (replaceShape) {
|
|
271
|
-
return session.append("system/message", data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs });
|
|
310
|
+
return session.append("system/message", data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs: sources });
|
|
272
311
|
}
|
|
273
312
|
try {
|
|
274
|
-
const event = session.append("system/message", data, { surfaceOp: replaceOpFor("legacy", startSeq, endSeq), sourceEventSeqs });
|
|
313
|
+
const event = session.append("system/message", data, { surfaceOp: replaceOpFor("legacy", startSeq, endSeq), sourceEventSeqs: sources });
|
|
275
314
|
replaceShape = "legacy";
|
|
276
315
|
return event;
|
|
277
316
|
} catch (err) {
|
|
278
317
|
if (!/invalid replace surfaceOp/.test(String(err && err.message))) throw err;
|
|
279
|
-
const event = session.append("system/message", data, { surfaceOp: replaceOpFor("new", startSeq, endSeq), sourceEventSeqs });
|
|
318
|
+
const event = session.append("system/message", data, { surfaceOp: replaceOpFor("new", startSeq, endSeq), sourceEventSeqs: sources });
|
|
280
319
|
replaceShape = "new";
|
|
281
320
|
return event;
|
|
282
321
|
}
|
|
@@ -318,6 +357,9 @@ export function planRestore(events, restoreSeq, upToSeq, excludeSeqs) {
|
|
|
318
357
|
type: e.type,
|
|
319
358
|
role: e.type === "user/message" ? "user" : "assistant",
|
|
320
359
|
text,
|
|
360
|
+
source: e.type === "assistant/message" && e.data && e.data.message
|
|
361
|
+
? e.data.message.source
|
|
362
|
+
: undefined,
|
|
321
363
|
});
|
|
322
364
|
} else {
|
|
323
365
|
skipped++; // tool/call 等不可安全重放的事件:跳过并在结果里计数
|
|
@@ -426,6 +468,71 @@ export function restoreProgress(events, markerSeq) {
|
|
|
426
468
|
};
|
|
427
469
|
}
|
|
428
470
|
|
|
471
|
+
export function buildRestoreIndex(events) {
|
|
472
|
+
const bySeq = new Map();
|
|
473
|
+
const noticesByMarker = new Map();
|
|
474
|
+
const candidates = [];
|
|
475
|
+
for (const e of events) {
|
|
476
|
+
if (!e || typeof e.seq !== "number") continue;
|
|
477
|
+
bySeq.set(e.seq, e);
|
|
478
|
+
if (e.type === "user/message" || e.type === "assistant/message") {
|
|
479
|
+
if ((messageText(e) || "").trim()) candidates.push(e.seq);
|
|
480
|
+
}
|
|
481
|
+
const markerSeq = e.data && e.data.restoresSeq;
|
|
482
|
+
if (Number.isSafeInteger(markerSeq)) {
|
|
483
|
+
const list = noticesByMarker.get(markerSeq);
|
|
484
|
+
if (list) list.push(e); else noticesByMarker.set(markerSeq, [e]);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return { bySeq, noticesByMarker, candidates };
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
export function restoreProgressFromIndex(index, markerSeq) {
|
|
491
|
+
const marker = index.bySeq.get(markerSeq);
|
|
492
|
+
if (!marker) return null;
|
|
493
|
+
const range = readReplaceOp(marker);
|
|
494
|
+
if (!range) return null;
|
|
495
|
+
const { startSeq, endSeq } = range;
|
|
496
|
+
const candidates = [];
|
|
497
|
+
for (const q of index.candidates) {
|
|
498
|
+
if (q >= startSeq && q <= endSeq) candidates.push(q);
|
|
499
|
+
}
|
|
500
|
+
const notices = index.noticesByMarker.get(markerSeq) || [];
|
|
501
|
+
const restored = new Set();
|
|
502
|
+
let legacy = false;
|
|
503
|
+
let discarded = false;
|
|
504
|
+
for (const n of notices) {
|
|
505
|
+
if (n.data.discarded === true) { discarded = true; continue; }
|
|
506
|
+
const seqs = n.data && Array.isArray(n.data.restoredSourceSeqs) ? n.data.restoredSourceSeqs : null;
|
|
507
|
+
if (!seqs) { legacy = true; continue; }
|
|
508
|
+
for (const q of seqs) if (Number.isSafeInteger(q)) restored.add(q);
|
|
509
|
+
}
|
|
510
|
+
const pending = candidates.filter((q) => !restored.has(q));
|
|
511
|
+
return {
|
|
512
|
+
startSeq,
|
|
513
|
+
endSeq,
|
|
514
|
+
restoredSeqs: Array.from(restored).sort((a, b) => a - b),
|
|
515
|
+
pendingSeqs: pending,
|
|
516
|
+
complete: legacy || discarded ? true : pending.length === 0,
|
|
517
|
+
legacy,
|
|
518
|
+
discarded,
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export function pendingRestoreTurnsFromIndex(index, markerSeq, progress) {
|
|
523
|
+
if (!progress || progress.pendingSeqs.length === 0) return [];
|
|
524
|
+
const turns = [];
|
|
525
|
+
let current = null;
|
|
526
|
+
for (const q of progress.pendingSeqs) {
|
|
527
|
+
const e = index.bySeq.get(q);
|
|
528
|
+
if (!e) continue;
|
|
529
|
+
if (e.type === "user/message") { current = { turnSeq: q, seqs: [q] }; turns.push(current); }
|
|
530
|
+
else if (current) current.seqs.push(q);
|
|
531
|
+
else turns.push({ turnSeq: q, seqs: [q] });
|
|
532
|
+
}
|
|
533
|
+
return turns;
|
|
534
|
+
}
|
|
535
|
+
|
|
429
536
|
/**
|
|
430
537
|
* 0.8.0:贴条按行展示用 —— 列出该标记仍未重放的「轮」(一个 user 消息及其后
|
|
431
538
|
* 到下一个 user 之前的 assistant 回复算一轮,对齐 opencode 按轮步进恢复)。
|
|
@@ -527,8 +634,8 @@ export function isJsonContentType(req) {
|
|
|
527
634
|
// 同机无凭证进程 GET 即可整卷消息/全文(宿主同条件 401——审计缺口)。
|
|
528
635
|
// 对齐修法(选型理由见报告):前端本来就带 cookie → 围栏里**校验同款
|
|
529
636
|
// cookie**;secret 经 credentials 服务的合法读法取(no-op modifyRecord,
|
|
530
|
-
//
|
|
531
|
-
//
|
|
637
|
+
// 勿写勿落盘)。无 credentials 服务 = 老宿主 → 保留旧围栏;有服务但记录
|
|
638
|
+
// 缺失/格式升级 → **fail-closed** 并告警,避免永久 allow-all。
|
|
532
639
|
// 非浏览器 GET(curl 等)从 200 变 401 = 与宿主对齐的有意行为变化。
|
|
533
640
|
|
|
534
641
|
const AUTH_RECORD_KEY = "client-connection/browser-session";
|
|
@@ -625,7 +732,8 @@ export function browserAuthPayload(req, secret) {
|
|
|
625
732
|
/**
|
|
626
733
|
* 经 credentials 服务读宿主 BrowserAuth 签名 secret。**唯一读法**:
|
|
627
734
|
* no-op modifyRecord(mutate 返回 undefined = 记录未动、返回 current),
|
|
628
|
-
* 不落盘不经 argv。宿主无该成分 / 记录缺失 / 格式或长度不符 → null
|
|
735
|
+
* 不落盘不经 argv。宿主无该成分 / 记录缺失 / 格式或长度不符 → null。
|
|
736
|
+
* 调用方据此决定老宿主降级还是 fail-closed(有 credentials 服务即后者)。
|
|
629
737
|
* @param {object|undefined} credentials ctx.get("credentials")
|
|
630
738
|
* @returns {Promise<Buffer|null>}
|
|
631
739
|
*/
|
|
@@ -651,6 +759,7 @@ export async function loadBrowserAuthSecret(credentials) {
|
|
|
651
759
|
const WEB_AUTH_RETRY_MS = 10_000;
|
|
652
760
|
let __webAuthSecret = null;
|
|
653
761
|
let __webAuthProbeAt = 0;
|
|
762
|
+
let __webAuthProbe = null;
|
|
654
763
|
let __webAuthWarned = false;
|
|
655
764
|
|
|
656
765
|
/** 测试钩子:直接注入/清除 secret,绕开 credentials 服务。 */
|
|
@@ -658,13 +767,14 @@ export function _setWebAuthSecret(secret) { __webAuthSecret = secret; }
|
|
|
658
767
|
export function _resetWebAuth() {
|
|
659
768
|
__webAuthSecret = null;
|
|
660
769
|
__webAuthProbeAt = 0;
|
|
770
|
+
__webAuthProbe = null;
|
|
661
771
|
__webAuthWarned = false;
|
|
662
772
|
}
|
|
663
773
|
|
|
664
774
|
/**
|
|
665
|
-
* 围栏的鉴权半段:取活跃 secret
|
|
775
|
+
* 围栏的鉴权半段:取活跃 secret(含单飞探测与 10s 失败 memo)。
|
|
666
776
|
* secret 存在但请求未携有效 cookie → false(路由层回 401);
|
|
667
|
-
*
|
|
777
|
+
* 无 credentials 服务(老宿主)→ true = 旧围栏;有服务但记录不可读 → false(fail-closed)。
|
|
668
778
|
* @param {object|undefined} ctx 插件 ctx(get("credentials"))
|
|
669
779
|
* @param {object} req http 请求
|
|
670
780
|
*/
|
|
@@ -672,19 +782,32 @@ export async function webAuthGate(ctx, req) {
|
|
|
672
782
|
if (__webAuthSecret !== null) {
|
|
673
783
|
return browserAuthPayload(req, __webAuthSecret) !== undefined;
|
|
674
784
|
}
|
|
785
|
+
|
|
786
|
+
let credentials = null;
|
|
787
|
+
try { credentials = ctx && typeof ctx.get === "function" ? ctx.get("credentials") : null; } catch { /* legacy ctx */ }
|
|
788
|
+
if (!credentials || typeof credentials.modifyRecord !== "function") return true;
|
|
789
|
+
|
|
675
790
|
const now = Date.now();
|
|
676
|
-
if (now - __webAuthProbeAt
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
791
|
+
if (__webAuthProbe === null && now - __webAuthProbeAt >= WEB_AUTH_RETRY_MS) {
|
|
792
|
+
__webAuthProbeAt = now;
|
|
793
|
+
__webAuthProbe = loadBrowserAuthSecret(credentials)
|
|
794
|
+
.then((secret) => {
|
|
795
|
+
__webAuthSecret = secret;
|
|
796
|
+
if (secret === null && !__webAuthWarned) {
|
|
797
|
+
__webAuthWarned = true;
|
|
798
|
+
console.warn(
|
|
799
|
+
"[message-ops] BrowserAuth cookie 鉴权已启用但 `client-connection/browser-session` 记录不可读"
|
|
800
|
+
+ "——GET 鉴权 fail-closed;请检查该记录是否存在",
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
return secret;
|
|
804
|
+
})
|
|
805
|
+
.finally(() => { __webAuthProbe = null; });
|
|
686
806
|
}
|
|
687
|
-
|
|
807
|
+
|
|
808
|
+
if (__webAuthProbe === null) return false;
|
|
809
|
+
const secret = await __webAuthProbe;
|
|
810
|
+
return secret !== null && browserAuthPayload(req, secret) !== undefined;
|
|
688
811
|
}
|
|
689
812
|
|
|
690
813
|
|
|
@@ -765,6 +888,8 @@ export function nextSeqFrom(events) {
|
|
|
765
888
|
|
|
766
889
|
/** 磁盘回撤/删除标记事件(字段镜像引擎金标准:type/seq/time/data/sourceEventSeqs/surfaceOp)。 */
|
|
767
890
|
export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq, shadowedSeqs, version = 4 }) {
|
|
891
|
+
const sources = [...new Set((Array.isArray(shadowedSeqs) ? shadowedSeqs : []).flat(Infinity))];
|
|
892
|
+
if (!sources.every(Number.isSafeInteger)) throw new OpsError("surface replace sources must be integer seqs", 500);
|
|
768
893
|
return {
|
|
769
894
|
type: "system/message",
|
|
770
895
|
seq,
|
|
@@ -774,7 +899,7 @@ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq,
|
|
|
774
899
|
step: turnStep.step,
|
|
775
900
|
message: { id: randomUUID(), role: "system", source: messageSource("system", version), content: [{ type: "text", text }] },
|
|
776
901
|
},
|
|
777
|
-
sourceEventSeqs:
|
|
902
|
+
sourceEventSeqs: sources,
|
|
778
903
|
surfaceOp: { op: "replace", startSeq, endSeq },
|
|
779
904
|
};
|
|
780
905
|
}
|
package/src/session-file.js
CHANGED
|
@@ -17,8 +17,6 @@ import os from "node:os";
|
|
|
17
17
|
import { constants, zstdCompressSync, zstdDecompressSync } from "node:zlib";
|
|
18
18
|
|
|
19
19
|
const ZSTD_MAGIC = 0xfd2fb528;
|
|
20
|
-
/** 魔数的字节形态(Buffer.indexOf 用;小端 0xfd2fb528 → 28 b5 2f fd)。 */
|
|
21
|
-
const ZSTD_MAGIC_BYTES = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
|
|
22
20
|
|
|
23
21
|
/** 带语义状态码的操作错误(单点:HTTP 直接映射 status,工具端转失败文本)。 */
|
|
24
22
|
export class OpsError extends Error {
|
|
@@ -67,14 +65,52 @@ function compressFrame(input) {
|
|
|
67
65
|
});
|
|
68
66
|
}
|
|
69
67
|
|
|
68
|
+
/**
|
|
69
|
+
* 按 RFC 8878 计算一个 zstd 帧的精确结束偏移。
|
|
70
|
+
* 魔数可能出现在压缩载荷内,因此不能用 Buffer.indexOf 定帧界。
|
|
71
|
+
* @returns {{end:number}|{error:'truncated'|'malformed'}}
|
|
72
|
+
*/
|
|
73
|
+
function zstdFrameEnd(buf, start) {
|
|
74
|
+
if (start + 4 > buf.length || buf.readUInt32LE(start) !== ZSTD_MAGIC) return { error: "malformed" };
|
|
75
|
+
let p = start + 4;
|
|
76
|
+
if (p >= buf.length) return { error: "truncated" };
|
|
77
|
+
const fhd = buf[p++];
|
|
78
|
+
if ((fhd & 0x18) !== 0) return { error: "malformed" };
|
|
79
|
+
const fcsFlag = fhd >> 6;
|
|
80
|
+
const singleSegment = (fhd >> 5) & 1;
|
|
81
|
+
const checksum = (fhd >> 2) & 1;
|
|
82
|
+
const dictFlag = fhd & 3;
|
|
83
|
+
if (!singleSegment) {
|
|
84
|
+
if (p >= buf.length) return { error: "truncated" };
|
|
85
|
+
p += 1;
|
|
86
|
+
}
|
|
87
|
+
const dictSize = [0, 1, 2, 4][dictFlag];
|
|
88
|
+
const fcsSize = fcsFlag === 0 ? (singleSegment ? 1 : 0) : [0, 2, 4, 8][fcsFlag];
|
|
89
|
+
p += dictSize + fcsSize;
|
|
90
|
+
if (p > buf.length) return { error: "truncated" };
|
|
91
|
+
for (;;) {
|
|
92
|
+
if (p + 3 > buf.length) return { error: "truncated" };
|
|
93
|
+
const bh = buf[p] | (buf[p + 1] << 8) | (buf[p + 2] << 16);
|
|
94
|
+
p += 3;
|
|
95
|
+
const last = bh & 1;
|
|
96
|
+
const type = (bh >> 1) & 3;
|
|
97
|
+
const size = bh >>> 3;
|
|
98
|
+
if (type === 3) return { error: "malformed" };
|
|
99
|
+
const payload = type === 1 ? 1 : size;
|
|
100
|
+
if (p + payload > buf.length) return { error: "truncated" };
|
|
101
|
+
p += payload;
|
|
102
|
+
if (last) break;
|
|
103
|
+
}
|
|
104
|
+
if (checksum) {
|
|
105
|
+
if (p + 4 > buf.length) return { error: "truncated" };
|
|
106
|
+
p += 4;
|
|
107
|
+
}
|
|
108
|
+
return { end: p };
|
|
109
|
+
}
|
|
110
|
+
|
|
70
111
|
/**
|
|
71
112
|
* 扫描串联 zstd 流的完整帧边界(不解压块)。
|
|
72
|
-
*
|
|
73
|
-
* 找「下一个魔数」用 Buffer.indexOf(原生 memchr 实现)而不是逐字节
|
|
74
|
-
* readUInt32LE 循环 —— 10.8MB 日志的逐字节扫描实测 44~73ms 且全程同步
|
|
75
|
-
* 阻塞事件循环(单次卡顿 146ms 的主要来源);indexOf 同样从 offset+4
|
|
76
|
-
* 起找、同样要求 4 字节完整落在缓冲区内,语义与原循环**逐位等价**
|
|
77
|
-
* (命中区间 [offset+4, buf.length-4],找不到则 end=buf.length)。
|
|
113
|
+
* 帧界按结构计算,任何非帧字节或畸形帧都 fail-closed。
|
|
78
114
|
* @returns {{frames: {start:number,end:number}[], tornStart?: number}}
|
|
79
115
|
*/
|
|
80
116
|
export function scanZstdFrames(buf) {
|
|
@@ -86,11 +122,16 @@ export function scanZstdFrames(buf) {
|
|
|
86
122
|
if (buf.readUInt32LE(offset) !== ZSTD_MAGIC) {
|
|
87
123
|
throw new Error(`corrupt zstd session log: invalid frame magic at byte ${offset}`);
|
|
88
124
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
125
|
+
const parsed = zstdFrameEnd(buf, offset);
|
|
126
|
+
if (parsed.error === "truncated") {
|
|
127
|
+
frames.push({ start, end: buf.length });
|
|
128
|
+
return { frames, tornStart: start };
|
|
129
|
+
}
|
|
130
|
+
if (parsed.error) {
|
|
131
|
+
throw new Error(`corrupt zstd session log: malformed frame at byte ${offset}`);
|
|
132
|
+
}
|
|
133
|
+
frames.push({ start, end: parsed.end });
|
|
134
|
+
offset = parsed.end;
|
|
94
135
|
}
|
|
95
136
|
return { frames };
|
|
96
137
|
}
|
|
@@ -135,6 +176,25 @@ export function readSessionFile(file) {
|
|
|
135
176
|
return { header, events };
|
|
136
177
|
}
|
|
137
178
|
|
|
179
|
+
/** Read only the first zstd frame (header); a damaged body cannot block titles. */
|
|
180
|
+
export function readSessionHeader(file) {
|
|
181
|
+
const buf = fs.readFileSync(file);
|
|
182
|
+
if (buf.length < 4 || buf.readUInt32LE(0) !== ZSTD_MAGIC) {
|
|
183
|
+
throw new Error(`session log ${file}: no zstd header frame`);
|
|
184
|
+
}
|
|
185
|
+
const parsed = zstdFrameEnd(buf, 0);
|
|
186
|
+
if (parsed.error) throw new Error(`session log ${file}: ${parsed.error} header frame`);
|
|
187
|
+
const text = zstdDecompressSync(buf.subarray(0, parsed.end)).toString("utf8");
|
|
188
|
+
for (const line of text.split("\n")) {
|
|
189
|
+
const t = line.trim();
|
|
190
|
+
if (!t) continue;
|
|
191
|
+
let json;
|
|
192
|
+
try { json = JSON.parse(t); } catch { continue; }
|
|
193
|
+
if (json && typeof json === "object" && json.type === "session") return json;
|
|
194
|
+
}
|
|
195
|
+
throw new Error(`session log ${file}: no {type:"session"} header line in the first frame`);
|
|
196
|
+
}
|
|
197
|
+
|
|
138
198
|
/** 物化整份日志:header 帧(恰一行)+ 单一事件帧(全部事件行)。 */
|
|
139
199
|
export function encodeSessionFile(header, events) {
|
|
140
200
|
const headerText = JSON.stringify(header) + "\n";
|
|
@@ -224,6 +284,11 @@ export function turnBounds(events) {
|
|
|
224
284
|
}
|
|
225
285
|
|
|
226
286
|
export function listMessages(events) {
|
|
287
|
+
const syntheticTurns = new Set();
|
|
288
|
+
for (const e of events) {
|
|
289
|
+
if (e && e.type === "turn/start" && e.data && e.data.reason === "message-ops"
|
|
290
|
+
&& Number.isSafeInteger(e.data.turn)) syntheticTurns.add(e.data.turn);
|
|
291
|
+
}
|
|
227
292
|
const messages = [];
|
|
228
293
|
for (const e of events) {
|
|
229
294
|
if (!e || typeof e.seq !== "number") continue;
|
|
@@ -252,6 +317,7 @@ export function listMessages(events) {
|
|
|
252
317
|
? e.data.restoresSeq : null,
|
|
253
318
|
time: e.time ?? null,
|
|
254
319
|
turn: (e.data && e.data.turn) ?? null,
|
|
320
|
+
syntheticTurn: syntheticTurns.has(e.data && e.data.turn) || undefined,
|
|
255
321
|
// 0.9.1:assistant 节点的宿主 node-key 是 `14:assistant-step<turn>:<step>`,
|
|
256
322
|
// 没有 step 就无法把渲染行映射回日志 seq → 回滚时助手回答藏不掉。
|
|
257
323
|
step: (e.data && e.data.step) ?? null,
|
package/src/session-trash.js
CHANGED
|
@@ -14,7 +14,7 @@ import fs from "node:fs";
|
|
|
14
14
|
import os from "node:os";
|
|
15
15
|
import path from "node:path";
|
|
16
16
|
import { randomUUID } from "node:crypto";
|
|
17
|
-
import { OpsError, isSessionId, sessionIdVariants, sessionsRoot,
|
|
17
|
+
import { OpsError, isSessionId, sessionIdVariants, sessionsRoot, readSessionHeader } from "./session-file.js";
|
|
18
18
|
|
|
19
19
|
export const TRASH_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
20
20
|
const TRASH_ID_RE = /^\d{10,}-[0-9a-f]{8}$/;
|
|
@@ -76,7 +76,7 @@ function titleOfRow(row) {
|
|
|
76
76
|
|
|
77
77
|
function headerTitle(dir) {
|
|
78
78
|
try {
|
|
79
|
-
const
|
|
79
|
+
const header = readSessionHeader(path.join(dir, fs.readdirSync(dir).find((f) => /^session(\.v[34])?\.jsonl\.zstd$/.test(f)) || ""));
|
|
80
80
|
for (const key of ["title", "name", "displayTitle"]) {
|
|
81
81
|
if (header && typeof header[key] === "string" && header[key].trim()) return header[key].trim();
|
|
82
82
|
}
|
|
@@ -315,13 +315,19 @@ export async function deleteSessionToTrash(ctx, sessionId, confirmTitle) {
|
|
|
315
315
|
manifest.state = "trashed";
|
|
316
316
|
writeManifest(root, manifest);
|
|
317
317
|
} catch (err) {
|
|
318
|
+
let dataBack = !moved && fs.existsSync(source) && !fs.existsSync(target);
|
|
319
|
+
let metadataBack = dataBack;
|
|
318
320
|
if (moved) {
|
|
319
321
|
try {
|
|
320
322
|
moveDir(target, source);
|
|
323
|
+
dataBack = true;
|
|
321
324
|
await restoreMetadata(ctx, sessionId, meta);
|
|
325
|
+
metadataBack = true;
|
|
322
326
|
} catch { /* leave the manifest for manual restore */ }
|
|
323
327
|
}
|
|
324
|
-
|
|
328
|
+
if (dataBack && metadataBack) {
|
|
329
|
+
try { fs.rmSync(root, { recursive: true, force: true }); } catch { /* best effort */ }
|
|
330
|
+
}
|
|
325
331
|
throw err;
|
|
326
332
|
}
|
|
327
333
|
|
|
@@ -363,18 +369,42 @@ export async function listTrash(ctx, { purgeExpired = false, now = Date.now() }
|
|
|
363
369
|
return entries;
|
|
364
370
|
}
|
|
365
371
|
|
|
366
|
-
|
|
367
|
-
const manifest = readManifest(trashId);
|
|
372
|
+
function restoreTarget(manifest) {
|
|
368
373
|
if (!manifest || !Array.isArray(manifest.dirs) || manifest.dirs.length !== 1) {
|
|
369
374
|
throw new OpsError("unsupported trash manifest", 500);
|
|
370
375
|
}
|
|
371
|
-
|
|
372
|
-
|
|
376
|
+
if (!isSessionId(manifest.sessionId)) {
|
|
377
|
+
throw new OpsError("invalid trash manifest sessionId", 500);
|
|
378
|
+
}
|
|
379
|
+
const raw = manifest.dirs[0].rel;
|
|
380
|
+
if (typeof raw !== "string" || raw.length === 0 || path.isAbsolute(raw)) {
|
|
381
|
+
throw new OpsError("invalid trash manifest rel", 500);
|
|
382
|
+
}
|
|
383
|
+
const parts = raw.split(/[\\/]+/);
|
|
384
|
+
if (parts.length !== 2 || parts.some((part) => !part || part === "." || part === "..")) {
|
|
385
|
+
throw new OpsError("invalid trash manifest rel", 500);
|
|
386
|
+
}
|
|
387
|
+
if (!sessionIdVariants(manifest.sessionId).includes(parts[1])) {
|
|
388
|
+
throw new OpsError("trash manifest rel does not match sessionId", 500);
|
|
389
|
+
}
|
|
390
|
+
const root = path.resolve(sessionsRoot());
|
|
391
|
+
const target = path.join(root, ...parts);
|
|
392
|
+
if (!target.startsWith(root + path.sep)) {
|
|
393
|
+
throw new OpsError("trash manifest rel escapes the sessions root", 500);
|
|
394
|
+
}
|
|
395
|
+
return { rel: path.join(...parts), target };
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export async function restoreTrash(ctx, trashId) {
|
|
399
|
+
const manifest = readManifest(trashId);
|
|
400
|
+
const { rel, target } = restoreTarget(manifest);
|
|
373
401
|
if (fs.existsSync(target)) throw new OpsError("session directory already exists; refusing to overwrite", 409);
|
|
374
402
|
|
|
375
403
|
const root = path.join(trashRoot(), trashId);
|
|
376
404
|
const source = path.join(root, "data", rel);
|
|
377
|
-
|
|
405
|
+
let sourceStat;
|
|
406
|
+
try { sourceStat = fs.lstatSync(source); } catch { throw new OpsError("trash payload missing", 404); }
|
|
407
|
+
if (!sourceStat.isDirectory()) throw new OpsError("trash payload is not a directory", 500);
|
|
378
408
|
|
|
379
409
|
try {
|
|
380
410
|
moveDir(source, target);
|