@240xu/dsh-message-ops 0.11.0 → 0.11.1
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 +27 -28
- package/package.json +1 -1
- package/src/client.js +1 -646
- package/src/index.js +6 -182
- package/test/composer-refill.test.js +2 -2
- package/test/ops-core.test.js +1 -6
- package/test/revert-contract.test.js +17 -5
- package/src/session-trash.js +0 -402
- package/test/ops-search.test.js +0 -104
- package/test/session-trash.test.js +0 -179
package/src/index.js
CHANGED
|
@@ -14,7 +14,6 @@ import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqF
|
|
|
14
14
|
restoreProgress, pendingRestoreTurns,
|
|
15
15
|
isTrustedApiRequest, isJsonContentType, webAuthGate,
|
|
16
16
|
} from "./ops-core.js";
|
|
17
|
-
import { deleteSessionToTrash, listTrash, restoreTrash, purgeTrash, resolveSessionTitle } from "./session-trash.js";
|
|
18
17
|
|
|
19
18
|
export const name = "dsh-message-ops";
|
|
20
19
|
// 保持 inject 为空:tools 是可选增强而非硬依赖(cordis 的 inject 是
|
|
@@ -456,9 +455,8 @@ async function loadDerived(logPath) {
|
|
|
456
455
|
return entry.promise;
|
|
457
456
|
}
|
|
458
457
|
|
|
459
|
-
async function opsList(targetCtx, sessionId
|
|
458
|
+
async function opsList(targetCtx, sessionId) {
|
|
460
459
|
if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
|
|
461
|
-
const compact = opts && opts.compact === true;
|
|
462
460
|
const { logPath } = pickSessionDir(sessionId);
|
|
463
461
|
// 文件派生段(读日志 → 消息 → 遮蔽集 → marker 进度 → turn 边界)走缓存:
|
|
464
462
|
// key = logPath、失效看读前 stat 的 mtimeMs+size,见 loadDerived 注释。
|
|
@@ -472,8 +470,6 @@ async function opsList(targetCtx, sessionId, opts = {}) {
|
|
|
472
470
|
applyLiveCommitted(messages, live);
|
|
473
471
|
const visibleNodes = live && live.surface && Array.isArray(live.surface.nodes) ? new Set(live.surface.nodes) : null;
|
|
474
472
|
let visibleCount = 0;
|
|
475
|
-
let shadowedCount = 0;
|
|
476
|
-
let markerCount = 0;
|
|
477
473
|
for (const m of messages) {
|
|
478
474
|
m.visible = visibleNodes ? visibleNodes.has(m.seq) : !shadowed.has(m.seq);
|
|
479
475
|
// 0.9.6:**shadowed 与 visible 是两套语义,不能混用。**
|
|
@@ -488,128 +484,22 @@ async function opsList(targetCtx, sessionId, opts = {}) {
|
|
|
488
484
|
// transcript 藏行必须用它;visible 只留给「可回滚目标」(lastRevertable)。
|
|
489
485
|
m.shadowed = shadowed.has(m.seq);
|
|
490
486
|
if (m.visible) visibleCount++;
|
|
491
|
-
if (m.shadowed) shadowedCount++;
|
|
492
|
-
if (m.marker === true) markerCount++;
|
|
493
487
|
}
|
|
494
488
|
|
|
495
|
-
const visibleMessages = compact
|
|
496
|
-
? messages.map((m) => ({
|
|
497
|
-
seq: m.seq,
|
|
498
|
-
role: m.role,
|
|
499
|
-
snippet: m.snippet,
|
|
500
|
-
time: m.time,
|
|
501
|
-
visible: m.visible,
|
|
502
|
-
shadowed: m.shadowed,
|
|
503
|
-
}))
|
|
504
|
-
: messages;
|
|
505
|
-
|
|
506
489
|
return {
|
|
507
490
|
ok: true,
|
|
508
|
-
session: {
|
|
509
|
-
id: header.id,
|
|
510
|
-
createdAt: header.createdAt,
|
|
511
|
-
parentSession: header.parentSession ?? null,
|
|
512
|
-
confirmTitle: resolveSessionTitle(targetCtx, sessionId) || header.id,
|
|
513
|
-
},
|
|
491
|
+
session: { id: header.id, createdAt: header.createdAt, parentSession: header.parentSession ?? null },
|
|
514
492
|
running: isRunning(targetCtx, sessionId),
|
|
515
493
|
runningSource: __runningSource,
|
|
516
494
|
total: messages.length,
|
|
517
495
|
visibleCount,
|
|
518
|
-
shadowedCount,
|
|
519
|
-
markerCount,
|
|
520
496
|
turnEndSeq,
|
|
521
|
-
messages
|
|
497
|
+
messages,
|
|
522
498
|
};
|
|
523
499
|
}
|
|
524
500
|
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
// ---------------------------------------------------------------------------
|
|
528
|
-
const SEARCH_CACHE_MAX = 8;
|
|
529
|
-
const searchCache = new Map(); // logPath -> { mtimeMs, size, promise }
|
|
530
|
-
|
|
531
|
-
/** Build the searchable corpus once per log revision (full text, lowercased lazily). */
|
|
532
|
-
async function buildSearchCorpus(logPath) {
|
|
533
|
-
const { events } = await readSessionFileAsync(logPath);
|
|
534
|
-
const messages = listMessages(events);
|
|
535
|
-
const shadowed = computeShadowed(events);
|
|
536
|
-
const bySeq = new Map();
|
|
537
|
-
for (const e of events) if (e && typeof e.seq === "number") bySeq.set(e.seq, e);
|
|
538
|
-
const corpus = [];
|
|
539
|
-
for (const m of messages) {
|
|
540
|
-
const ev = bySeq.get(m.seq);
|
|
541
|
-
const text = ev ? messageTextFull(ev) : "";
|
|
542
|
-
corpus.push({
|
|
543
|
-
seq: m.seq,
|
|
544
|
-
type: m.type,
|
|
545
|
-
role: m.role,
|
|
546
|
-
marker: m.marker === true,
|
|
547
|
-
shadowed: shadowed.has(m.seq),
|
|
548
|
-
text: text || m.snippet || "",
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
return corpus;
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
async function loadSearchCorpus(logPath) {
|
|
555
|
-
const st = await statFile(logPath);
|
|
556
|
-
const hit = searchCache.get(logPath);
|
|
557
|
-
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
|
|
558
|
-
searchCache.delete(logPath);
|
|
559
|
-
searchCache.set(logPath, hit);
|
|
560
|
-
return hit.promise;
|
|
561
|
-
}
|
|
562
|
-
const entry = { mtimeMs: st.mtimeMs, size: st.size, promise: buildSearchCorpus(logPath) };
|
|
563
|
-
searchCache.delete(logPath);
|
|
564
|
-
searchCache.set(logPath, entry);
|
|
565
|
-
while (searchCache.size > SEARCH_CACHE_MAX) searchCache.delete(searchCache.keys().next().value);
|
|
566
|
-
entry.promise.catch(() => { if (searchCache.get(logPath) === entry) searchCache.delete(logPath); });
|
|
567
|
-
return entry.promise;
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
function searchSnippet(text, query, radius = 45) {
|
|
571
|
-
const lower = text.toLowerCase();
|
|
572
|
-
const at = lower.indexOf(query);
|
|
573
|
-
const start = at < 0 ? 0 : Math.max(0, at - radius);
|
|
574
|
-
const end = at < 0 ? Math.min(text.length, 160) : Math.min(text.length, at + query.length + radius);
|
|
575
|
-
const raw = text.slice(start, end).replace(/\s+/g, " ").trim();
|
|
576
|
-
return (start > 0 ? "…" : "") + raw.slice(0, 158) + (end < text.length ? "…" : "");
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
async function opsSearch(targetCtx, sessionId, query, opts = {}) {
|
|
580
|
-
if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
|
|
581
|
-
const q = typeof query === "string" ? query.trim() : "";
|
|
582
|
-
if (q.length === 0) throw new OpsError("query is required", 400);
|
|
583
|
-
if (q.length > 500) throw new OpsError("query too long (max 500)", 400);
|
|
584
|
-
const role = opts && typeof opts.role === "string" && opts.role ? opts.role : null;
|
|
585
|
-
if (role && !["user", "assistant", "system", "tool"].includes(role)) {
|
|
586
|
-
throw new OpsError("invalid role", 400);
|
|
587
|
-
}
|
|
588
|
-
const limit = Number.isSafeInteger(opts && opts.limit) ? Math.max(1, Math.min(100, opts.limit)) : 50;
|
|
589
|
-
const { logPath } = pickSessionDir(sessionId);
|
|
590
|
-
const corpus = await loadSearchCorpus(logPath);
|
|
591
|
-
const needle = q.toLowerCase();
|
|
592
|
-
const results = [];
|
|
593
|
-
let total = 0;
|
|
594
|
-
for (const row of corpus) {
|
|
595
|
-
if (role && row.role !== role) continue;
|
|
596
|
-
if (!row.text.toLowerCase().includes(needle)) continue;
|
|
597
|
-
total++;
|
|
598
|
-
if (results.length >= limit) continue;
|
|
599
|
-
results.push({
|
|
600
|
-
seq: row.seq,
|
|
601
|
-
type: row.type,
|
|
602
|
-
role: row.role,
|
|
603
|
-
marker: row.marker,
|
|
604
|
-
shadowed: row.shadowed,
|
|
605
|
-
snippet: searchSnippet(row.text, needle),
|
|
606
|
-
});
|
|
607
|
-
}
|
|
608
|
-
return { ok: true, query: q, role, limit, total, truncated: total > results.length, results };
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
/** 测试钩子(非公开 API):直接驱动 list / search 与文件派生缓存。 */
|
|
612
|
-
export const _internals = { opsList, opsSearch, loadDerived, loadSearchCorpus, derivedCache, searchCache };
|
|
501
|
+
/** 测试钩子(非公开 API):直接驱动 list 与文件派生缓存。 */
|
|
502
|
+
export const _internals = { opsList, loadDerived, derivedCache };
|
|
613
503
|
|
|
614
504
|
async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
615
505
|
if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
|
|
@@ -907,40 +797,13 @@ export function apply(ctx) {
|
|
|
907
797
|
if (!(await fence(targetCtx, req, res))) return;
|
|
908
798
|
try {
|
|
909
799
|
const url = new URL(req.url, "http://localhost");
|
|
910
|
-
return sendJson(res, 200, await opsList(targetCtx, url.searchParams.get("sessionId") || ""
|
|
911
|
-
compact: url.searchParams.get("view") === "compact",
|
|
912
|
-
}));
|
|
800
|
+
return sendJson(res, 200, await opsList(targetCtx, url.searchParams.get("sessionId") || ""));
|
|
913
801
|
} catch (err) {
|
|
914
802
|
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
915
803
|
}
|
|
916
804
|
},
|
|
917
805
|
}), "dsh-message-ops: messages route");
|
|
918
806
|
|
|
919
|
-
// --- GET /api/message-ops/search:会话内全文搜索(服务端,匹配 snippet 之外) --
|
|
920
|
-
targetCtx.effect(() => host.register({
|
|
921
|
-
kind: "exact",
|
|
922
|
-
path: "/api/message-ops/search",
|
|
923
|
-
handler: async (req, res) => {
|
|
924
|
-
if (req.method !== "GET") return sendJson(res, 405, { ok: false, error: "method not allowed" });
|
|
925
|
-
if (!(await fence(targetCtx, req, res))) return;
|
|
926
|
-
try {
|
|
927
|
-
const url = new URL(req.url, "http://localhost");
|
|
928
|
-
const limitRaw = Number.parseInt(url.searchParams.get("limit") || "", 10);
|
|
929
|
-
return sendJson(res, 200, await opsSearch(
|
|
930
|
-
targetCtx,
|
|
931
|
-
url.searchParams.get("sessionId") || "",
|
|
932
|
-
url.searchParams.get("q") || "",
|
|
933
|
-
{
|
|
934
|
-
role: url.searchParams.get("role") || null,
|
|
935
|
-
limit: Number.isSafeInteger(limitRaw) ? limitRaw : undefined,
|
|
936
|
-
},
|
|
937
|
-
));
|
|
938
|
-
} catch (err) {
|
|
939
|
-
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
940
|
-
}
|
|
941
|
-
},
|
|
942
|
-
}), "dsh-message-ops: search route");
|
|
943
|
-
|
|
944
807
|
// --- GET /api/message-ops/text:单条消息全文(0.5.2 引用按钮按需取) ----------
|
|
945
808
|
// assistant 消息的 fullText 不在 messages 列表里(载荷控制),quote 点击时单取。
|
|
946
809
|
targetCtx.effect(() => host.register({
|
|
@@ -1014,45 +877,6 @@ export function apply(ctx) {
|
|
|
1014
877
|
},
|
|
1015
878
|
}), "dsh-message-ops: restore route");
|
|
1016
879
|
|
|
1017
|
-
// --- Session trash:删除整条会话(可逆),列表 / 恢复 / 永久清理 ----------
|
|
1018
|
-
targetCtx.effect(() => host.register({
|
|
1019
|
-
kind: "exact",
|
|
1020
|
-
path: "/api/message-ops/session/trash",
|
|
1021
|
-
handler: async (req, res) => {
|
|
1022
|
-
if (req.method !== "GET") return sendJson(res, 405, { ok: false, error: "method not allowed" });
|
|
1023
|
-
if (!(await fence(targetCtx, req, res))) return;
|
|
1024
|
-
try {
|
|
1025
|
-
return sendJson(res, 200, { ok: true, entries: await listTrash(targetCtx, { purgeExpired: true }) });
|
|
1026
|
-
} catch (err) {
|
|
1027
|
-
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
1028
|
-
}
|
|
1029
|
-
},
|
|
1030
|
-
}), "dsh-message-ops: session trash route");
|
|
1031
|
-
|
|
1032
|
-
const sessionAction = (path, action) => targetCtx.effect(() => host.register({
|
|
1033
|
-
kind: "exact",
|
|
1034
|
-
path,
|
|
1035
|
-
handler: async (req, res) => {
|
|
1036
|
-
if (req.method !== "POST") return sendJson(res, 405, { ok: false, error: "method not allowed" });
|
|
1037
|
-
if (!(await writeFence(targetCtx, req, res))) return;
|
|
1038
|
-
const body = await readFencedBody(req, res);
|
|
1039
|
-
if (body === undefined) return;
|
|
1040
|
-
if (!body || typeof body !== "object") return sendJson(res, 400, { ok: false, error: "invalid json" });
|
|
1041
|
-
try {
|
|
1042
|
-
return sendJson(res, 200, await action(targetCtx, body));
|
|
1043
|
-
} catch (err) {
|
|
1044
|
-
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
1045
|
-
}
|
|
1046
|
-
},
|
|
1047
|
-
}), "dsh-message-ops: " + path);
|
|
1048
|
-
|
|
1049
|
-
sessionAction("/api/message-ops/session/delete", (c, b) =>
|
|
1050
|
-
deleteSessionToTrash(c, b.sessionId, b.confirmTitle));
|
|
1051
|
-
sessionAction("/api/message-ops/session/restore", (c, b) =>
|
|
1052
|
-
restoreTrash(c, b.trashId));
|
|
1053
|
-
sessionAction("/api/message-ops/session/purge", (c, b) =>
|
|
1054
|
-
purgeTrash(c, b.trashId));
|
|
1055
|
-
|
|
1056
880
|
}
|
|
1057
881
|
|
|
1058
882
|
const ws = ctx.get("webServer");
|
|
@@ -65,9 +65,9 @@ test('R4:afterWrite 必须传带 session- 前缀的 id 给 openSession', () =>
|
|
|
65
65
|
|
|
66
66
|
test('R2:所有 revert 入口都接了 refillComposer', () => {
|
|
67
67
|
const calls = (src.match(/\brefillComposer\(/g) || []).length
|
|
68
|
-
//
|
|
68
|
+
// 三个回滚入口:runUndo(/undo) + runRevert(AI 时钟) + runUserRevert(悬停)
|
|
69
69
|
// 注意:定义写法是 `refillComposer = (`,不匹配 `refillComposer(`
|
|
70
|
-
assert.equal(calls,
|
|
70
|
+
assert.equal(calls, 3, `refillComposer 调用 ${calls} 处,应为 3 个回滚入口`)
|
|
71
71
|
assert.ok(/var refillComposer = \(/.test(src), '缺 refillComposer 定义')
|
|
72
72
|
// 反例:restore / redo 不该回填(它们是加回内容,不是删)
|
|
73
73
|
const redo = src.match(/var runRedo = \(\) => \{[\s\S]*?\n \}/)
|
package/test/ops-core.test.js
CHANGED
|
@@ -174,7 +174,7 @@ test('apply:无 webServer、无 tools 时走 inject 等待,不抛错', () =>
|
|
|
174
174
|
assert.equal(ctx.registrations.length, 0)
|
|
175
175
|
})
|
|
176
176
|
|
|
177
|
-
test('apply:webServer 存在时注册全部
|
|
177
|
+
test('apply:webServer 存在时注册全部 5 条路由;tools 缺失走 inject 等待', () => {
|
|
178
178
|
const ctx = mockCtx({ webServer: { register: (route) => ctx.registrations.push(route) } })
|
|
179
179
|
assert.doesNotThrow(() => apply(ctx))
|
|
180
180
|
const paths = ctx.registrations.map((r) => r.path).sort()
|
|
@@ -183,11 +183,6 @@ test('apply:webServer 存在时注册全部 10 条路由;tools 缺失走 inj
|
|
|
183
183
|
'/api/message-ops/messages',
|
|
184
184
|
'/api/message-ops/restore',
|
|
185
185
|
'/api/message-ops/revert',
|
|
186
|
-
'/api/message-ops/search',
|
|
187
|
-
'/api/message-ops/session/delete',
|
|
188
|
-
'/api/message-ops/session/purge',
|
|
189
|
-
'/api/message-ops/session/restore',
|
|
190
|
-
'/api/message-ops/session/trash',
|
|
191
186
|
'/api/message-ops/text',
|
|
192
187
|
], '0.9.0:branch/export 路由已移除(改用官方 session/fork 与 /api/session.export)')
|
|
193
188
|
// tools 缺失 → 容错等待而非 fatal
|
|
@@ -15,8 +15,20 @@ import { zstdCompressSync } from 'node:zlib'
|
|
|
15
15
|
import { createRequire } from 'node:module'
|
|
16
16
|
import { join, dirname } from 'node:path'
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
// Optional local contract fixtures. CI does not ship sessionfix; these tests
|
|
19
|
+
// are skipped there rather than hard-failing on a machine-specific path.
|
|
20
|
+
const SEQ_IMPL = process.env.SESSIONFIX_SEQCORE ?? '/data/data/com.termux/files/home/dsh-plugins-src/sessionfix/lib/seqcore.js'
|
|
21
|
+
const GATE_IMPL = process.env.SESSIONFIX_V4GATE ?? '/data/data/com.termux/files/home/dsh-plugins-src/sessionfix/lib/v4gate.mjs'
|
|
22
|
+
let decodeFrames, parseRows, officialValidate
|
|
23
|
+
try {
|
|
24
|
+
({ decodeFrames, parseRows } = await import(SEQ_IMPL))
|
|
25
|
+
;({ officialValidate } = await import(GATE_IMPL))
|
|
26
|
+
} catch {
|
|
27
|
+
decodeFrames = parseRows = officialValidate = undefined
|
|
28
|
+
}
|
|
29
|
+
const contractSkip = process.env.SESSIONFIX_CONTRACT !== '1'
|
|
30
|
+
? 'optional sessionfix contract tests; set SESSIONFIX_CONTRACT=1 to run'
|
|
31
|
+
: (decodeFrames === undefined ? 'sessionfix contract fixtures not available' : false)
|
|
20
32
|
import {
|
|
21
33
|
planNoticeWindow, noticeWindowPreamble, noticeWindowPostamble,
|
|
22
34
|
buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, planRestore, restoreProgress,
|
|
@@ -39,7 +51,7 @@ function idleSessionBase() {
|
|
|
39
51
|
].map((e, i) => ({ ...e, seq: i, time: 1000 + i }))
|
|
40
52
|
}
|
|
41
53
|
|
|
42
|
-
test('契约:合成窗口承载的 revert marker 通过官方三层闸', () => {
|
|
54
|
+
test('契约:合成窗口承载的 revert marker 通过官方三层闸', { skip: contractSkip }, () => {
|
|
43
55
|
const base = idleSessionBase()
|
|
44
56
|
const win = planNoticeWindow(base)
|
|
45
57
|
assert.equal(win.synthetic, true, '空闲会话应规划合成窗口')
|
|
@@ -68,7 +80,7 @@ test('契约:合成窗口必须自带 reason(UI 层硬要求)', () => {
|
|
|
68
80
|
assert.equal(turnEnd.data.reason.kind, 'interrupted')
|
|
69
81
|
})
|
|
70
82
|
|
|
71
|
-
test('契约:缺 reason 的 turn/end 会被官方闸拦下(回归证明这条规则有效)', () => {
|
|
83
|
+
test('契约:缺 reason 的 turn/end 会被官方闸拦下(回归证明这条规则有效)', { skip: contractSkip }, () => {
|
|
72
84
|
const base = idleSessionBase()
|
|
73
85
|
const bad = [...base, { type: 'turn/start', seq: base.length, time: 6000, data: { turn: 2 } },
|
|
74
86
|
{ type: 'step/start', seq: base.length + 1, time: 6001, data: { turn: 2, step: 1 } },
|
|
@@ -80,7 +92,7 @@ test('契约:缺 reason 的 turn/end 会被官方闸拦下(回归证明这
|
|
|
80
92
|
assert.match(v.error, /reason/, `错误信息应指向 reason,实际:${v.error}`)
|
|
81
93
|
})
|
|
82
94
|
|
|
83
|
-
test('契约:完整 restore 链路(notice + 重放)通过官方三层闸', () => {
|
|
95
|
+
test('契约:完整 restore 链路(notice + 重放)通过官方三层闸', { skip: contractSkip }, () => {
|
|
84
96
|
const base = idleSessionBase()
|
|
85
97
|
let cursor = base.length, t = 5000
|
|
86
98
|
const win = planNoticeWindow(base)
|