@dabuliu_wsy/dsh-im 0.0.0-stage → 0.2.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.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +197 -3
  3. package/cordis.patch.yml +4 -0
  4. package/dist/core/agent-state.d.ts +38 -0
  5. package/dist/core/agent-state.js +59 -0
  6. package/dist/core/arbiter-bridge.d.ts +25 -0
  7. package/dist/core/arbiter-bridge.js +20 -0
  8. package/dist/core/arbiter.d.ts +29 -0
  9. package/dist/core/arbiter.js +59 -0
  10. package/dist/core/avatar-brands.d.ts +23 -0
  11. package/dist/core/avatar-brands.js +75 -0
  12. package/dist/core/avatar-presets.d.ts +21 -0
  13. package/dist/core/avatar-presets.js +38 -0
  14. package/dist/core/avatar.d.ts +1 -0
  15. package/dist/core/avatar.js +18 -0
  16. package/dist/core/blocked.d.ts +12 -0
  17. package/dist/core/blocked.js +23 -0
  18. package/dist/core/budget-plan.d.ts +41 -0
  19. package/dist/core/budget-plan.js +69 -0
  20. package/dist/core/calibration-samples.d.ts +77 -0
  21. package/dist/core/calibration-samples.js +168 -0
  22. package/dist/core/calibrator.d.ts +57 -0
  23. package/dist/core/calibrator.js +125 -0
  24. package/dist/core/chapter-tree.d.ts +128 -0
  25. package/dist/core/chapter-tree.js +400 -0
  26. package/dist/core/consensus.d.ts +135 -0
  27. package/dist/core/consensus.js +394 -0
  28. package/dist/core/context-budget.d.ts +153 -0
  29. package/dist/core/context-budget.js +183 -0
  30. package/dist/core/curator.d.ts +28 -0
  31. package/dist/core/curator.js +190 -0
  32. package/dist/core/dual-window.d.ts +86 -0
  33. package/dist/core/dual-window.js +175 -0
  34. package/dist/core/events.d.ts +110 -0
  35. package/dist/core/events.js +117 -0
  36. package/dist/core/facts.d.ts +114 -0
  37. package/dist/core/facts.js +400 -0
  38. package/dist/core/fence.d.ts +34 -0
  39. package/dist/core/fence.js +129 -0
  40. package/dist/core/floor.d.ts +18 -0
  41. package/dist/core/floor.js +80 -0
  42. package/dist/core/ids.d.ts +11 -0
  43. package/dist/core/ids.js +29 -0
  44. package/dist/core/im.d.ts +167 -0
  45. package/dist/core/im.js +1307 -0
  46. package/dist/core/index.d.ts +33 -0
  47. package/dist/core/index.js +33 -0
  48. package/dist/core/log.d.ts +21 -0
  49. package/dist/core/log.js +63 -0
  50. package/dist/core/memory-claims.d.ts +67 -0
  51. package/dist/core/memory-claims.js +164 -0
  52. package/dist/core/memory-context.d.ts +121 -0
  53. package/dist/core/memory-context.js +303 -0
  54. package/dist/core/memory-visibility.d.ts +58 -0
  55. package/dist/core/memory-visibility.js +36 -0
  56. package/dist/core/memory.d.ts +12 -0
  57. package/dist/core/memory.js +73 -0
  58. package/dist/core/metrics.d.ts +49 -0
  59. package/dist/core/metrics.js +89 -0
  60. package/dist/core/multi-hop.d.ts +116 -0
  61. package/dist/core/multi-hop.js +278 -0
  62. package/dist/core/persist.d.ts +21 -0
  63. package/dist/core/persist.js +94 -0
  64. package/dist/core/proactive.d.ts +54 -0
  65. package/dist/core/proactive.js +108 -0
  66. package/dist/core/prompt.d.ts +82 -0
  67. package/dist/core/prompt.js +164 -0
  68. package/dist/core/receipt.d.ts +107 -0
  69. package/dist/core/receipt.js +86 -0
  70. package/dist/core/retrieval.d.ts +69 -0
  71. package/dist/core/retrieval.js +260 -0
  72. package/dist/core/role-state.d.ts +16 -0
  73. package/dist/core/role-state.js +65 -0
  74. package/dist/core/runtime.d.ts +137 -0
  75. package/dist/core/runtime.js +574 -0
  76. package/dist/core/summary.d.ts +19 -0
  77. package/dist/core/summary.js +96 -0
  78. package/dist/core/text.d.ts +10 -0
  79. package/dist/core/text.js +45 -0
  80. package/dist/core/time.d.ts +22 -0
  81. package/dist/core/time.js +84 -0
  82. package/dist/core/tool-schema.d.ts +12 -0
  83. package/dist/core/tool-schema.js +92 -0
  84. package/dist/core/tools.d.ts +137 -0
  85. package/dist/core/tools.js +348 -0
  86. package/dist/core/types.d.ts +400 -0
  87. package/dist/core/types.js +1 -0
  88. package/dist/core/window.d.ts +6 -0
  89. package/dist/core/window.js +7 -0
  90. package/dist/core/workspace-node.d.ts +28 -0
  91. package/dist/core/workspace-node.js +232 -0
  92. package/dist/core/workspace.d.ts +9 -0
  93. package/dist/core/workspace.js +45 -0
  94. package/dist/host/agent-session.d.ts +279 -0
  95. package/dist/host/agent-session.js +935 -0
  96. package/dist/host/attachment-gc.d.ts +37 -0
  97. package/dist/host/attachment-gc.js +97 -0
  98. package/dist/host/calibration-samples-store.d.ts +5 -0
  99. package/dist/host/calibration-samples-store.js +67 -0
  100. package/dist/host/capabilities.d.ts +45 -0
  101. package/dist/host/capabilities.js +67 -0
  102. package/dist/host/derived-store.d.ts +36 -0
  103. package/dist/host/derived-store.js +199 -0
  104. package/dist/host/dsh-llm.d.ts +143 -0
  105. package/dist/host/dsh-llm.js +395 -0
  106. package/dist/host/event-store.d.ts +47 -0
  107. package/dist/host/event-store.js +154 -0
  108. package/dist/host/fs-atomic.d.ts +1 -0
  109. package/dist/host/fs-atomic.js +26 -0
  110. package/dist/host/im-api.d.ts +352 -0
  111. package/dist/host/im-api.js +1137 -0
  112. package/dist/host/index.d.ts +103 -0
  113. package/dist/host/index.js +453 -0
  114. package/dist/host/memory-index.d.ts +65 -0
  115. package/dist/host/memory-index.js +181 -0
  116. package/dist/host/metrics-store.d.ts +7 -0
  117. package/dist/host/metrics-store.js +104 -0
  118. package/dist/host/models.d.ts +39 -0
  119. package/dist/host/models.js +67 -0
  120. package/dist/host/persona-tools.d.ts +57 -0
  121. package/dist/host/persona-tools.js +226 -0
  122. package/dist/host/preflight.d.ts +31 -0
  123. package/dist/host/preflight.js +29 -0
  124. package/dist/host/receipt-store.d.ts +26 -0
  125. package/dist/host/receipt-store.js +68 -0
  126. package/dist/host/run-check.d.ts +51 -0
  127. package/dist/host/run-check.js +190 -0
  128. package/dist/host/state-roots.d.ts +50 -0
  129. package/dist/host/state-roots.js +163 -0
  130. package/dist/host/tool-cache.d.ts +25 -0
  131. package/dist/host/tool-cache.js +90 -0
  132. package/dist/host/tool-call-budget.d.ts +29 -0
  133. package/dist/host/tool-call-budget.js +38 -0
  134. package/dsh-plugin.json +25 -0
  135. package/lib/client.inner.cjs +3346 -0
  136. package/lib/client.js +3354 -0
  137. package/package.json +86 -6
@@ -0,0 +1,82 @@
1
+ import type { ThreadKind } from './types.ts';
2
+ export interface PromptMessage {
3
+ id: string;
4
+ kind: 'user' | 'persona' | 'system';
5
+ authorName: string;
6
+ text: string;
7
+ createdAt: number;
8
+ seq?: number;
9
+ }
10
+ export interface PromptPersona {
11
+ id: string;
12
+ name: string;
13
+ post?: string;
14
+ personality?: string;
15
+ duties?: string[];
16
+ /** 角色勾选的能力集;有工具时提示词里带工具纪律(没有 shell)。 */
17
+ toolAllow?: string[];
18
+ }
19
+ export interface WindowInput {
20
+ messages: readonly PromptMessage[];
21
+ personaId: string;
22
+ personaName: string;
23
+ currentId?: string;
24
+ summaryUntilSeq?: number;
25
+ keep?: number;
26
+ charBudget?: number;
27
+ }
28
+ /** 线程类型:群聊 / 三人小窗 / 一对一私聊。私聊和群的话术边界不同,prompt 必须分开写。 */
29
+ export interface PromptInput extends WindowInput {
30
+ persona: PromptPersona;
31
+ threadTitle: string;
32
+ /** 线程类型;缺省按群聊处理(老调用方/测试不用改)。 */
33
+ threadKind?: ThreadKind;
34
+ summary?: string;
35
+ /** 角色状态快照块(结论,不是历史)。 */
36
+ stateBlock?: string;
37
+ /** 共识状态块(A 用户指令 / B 群共识 / C 任务;D 已被 builder 排除)。 */
38
+ consensusBlock?: string;
39
+ /** Phase 1 引用句柄块(历史片段 + 句柄目录;只含数据,不是指令)。 */
40
+ memoryBlock?: string;
41
+ /** 冷区章节目录块(双层窗口;只含 #seq 句柄,不是指令)。 */
42
+ contextBlock?: string;
43
+ /** 按需检索到的相关历史块(原始事件)。 */
44
+ retrievalBlock?: string;
45
+ /**
46
+ * 已算好的热区窗口(双层窗口的 `hot`)。
47
+ * 传了就用它,不再内部重跑 `selectWindow`——保证 prompt 实际用的窗口与回执/去重审计是同一份。
48
+ */
49
+ window?: PromptMessage[];
50
+ /**
51
+ * 已经在其它块(热区 / L1 摘要 / 记忆句柄)引用过的 seq:角色补充要点不再重复引用,
52
+ * 保证同一 seq 在最终 prompt 里最多出现一次(跨层去重)。
53
+ */
54
+ excludeSeqRefs?: ReadonlySet<number>;
55
+ }
56
+ /** 窗口/摘要块的标题按会话类型换词:私聊里还写“群聊”,模型会继续按群聊自我定位。 */
57
+ export declare function threadLabels(kind: ThreadKind | undefined): {
58
+ recent: string;
59
+ summary: string;
60
+ };
61
+ /** 老数据没有 seq:按数组顺序补一个单调序号,返回新数组。 */
62
+ export declare function assignSeqs<T extends object>(messages: readonly T[]): (T & {
63
+ seq: number;
64
+ })[];
65
+ export declare function seqOf(messages: readonly PromptMessage[], id: string): number | undefined;
66
+ /**
67
+ * 选窗口:只取摘要边界之后的消息;保证当前消息、@自己的、自己最近 3 条、
68
+ * 系统/工具结果不被窗口滑掉;再按“最多 N 条 / 不超过字符预算”从新到旧收。
69
+ */
70
+ export declare function selectWindow(input: WindowInput): PromptMessage[];
71
+ /** 渲染窗口文本:自己的发言必须打上 [你之前的发言],这是防串身份的关键。 */
72
+ export declare function renderWindow(messages: readonly PromptMessage[], personaName: string): string;
73
+ /** 角色私有补充:从本地数据拼,不额外调用模型。 */
74
+ export declare function roleSupplement(personaName: string, messages: readonly PromptMessage[], limit?: number): string[];
75
+ export declare function buildSystem(persona: PromptPersona, threadTitle: string, threadKind?: ThreadKind): string;
76
+ export interface AssembledPrompt {
77
+ system: string;
78
+ prompt: string;
79
+ window: PromptMessage[];
80
+ }
81
+ /** 组装一次发言的输入:固定前缀 → 角色状态 → 摘要 → 共识状态 → 检索到的相关历史 → 最近窗口 → 当前消息。 */
82
+ export declare function assemblePrompt(input: PromptInput): AssembledPrompt;
@@ -0,0 +1,164 @@
1
+ /**
2
+ * 群聊 prompt 组装:固定前缀(人设/岗位/规则/身份约束)→ 群级摘要(按边界切分)
3
+ * → 最近窗口(带 #序号 / 角色名 / [你之前的发言] 标签)→ 当前消息。
4
+ *
5
+ * 纯函数、无网络,便于单测和后续换成原生 session 的输入层。
6
+ */
7
+ import { hostToolGranted } from './tools.js';
8
+ import { stripLegacyReasoning } from './text.js';
9
+ /** 窗口/摘要块的标题按会话类型换词:私聊里还写“群聊”,模型会继续按群聊自我定位。 */
10
+ export function threadLabels(kind) {
11
+ return kind === 'dm'
12
+ ? { recent: '[最近私聊]', summary: '[本轮私聊摘要]' }
13
+ : { recent: '[最近群聊]', summary: '[本轮群聊摘要]' };
14
+ }
15
+ const DEFAULT_KEEP = 20;
16
+ const DEFAULT_CHAR_BUDGET = 6000;
17
+ /** 老数据没有 seq:按数组顺序补一个单调序号,返回新数组。 */
18
+ export function assignSeqs(messages) {
19
+ let last = 0;
20
+ return messages.map((message) => {
21
+ const existing = message.seq;
22
+ const seq = typeof existing === 'number' && existing > last ? existing : last + 1;
23
+ last = seq;
24
+ return { ...message, seq };
25
+ });
26
+ }
27
+ export function seqOf(messages, id) {
28
+ return messages.find((message) => message.id === id)?.seq;
29
+ }
30
+ function mentionsPersona(message, personaName) {
31
+ return message.kind === 'user' && message.text.includes('@' + personaName);
32
+ }
33
+ /**
34
+ * 选窗口:只取摘要边界之后的消息;保证当前消息、@自己的、自己最近 3 条、
35
+ * 系统/工具结果不被窗口滑掉;再按“最多 N 条 / 不超过字符预算”从新到旧收。
36
+ */
37
+ export function selectWindow(input) {
38
+ const keep = Math.max(1, input.keep ?? DEFAULT_KEEP);
39
+ const budget = Math.max(200, input.charBudget ?? DEFAULT_CHAR_BUDGET);
40
+ const boundary = input.summaryUntilSeq ?? 0;
41
+ const candidates = input.messages.filter((message) => (message.id !== input.currentId && (message.seq ?? 0) > boundary));
42
+ const guaranteed = new Set();
43
+ const picked = [];
44
+ let chars = 0;
45
+ const take = (message) => {
46
+ if (guaranteed.has(message.id))
47
+ return;
48
+ guaranteed.add(message.id);
49
+ picked.push(message);
50
+ chars += message.text.length;
51
+ };
52
+ // 保底 1:@该角色 / 回复它的消息(从新到旧最多 3 条)
53
+ candidates.filter((message) => mentionsPersona(message, input.personaName)).slice(-3).forEach(take);
54
+ // 保底 2:该角色自己的最近 3 条发言
55
+ candidates.filter((message) => message.kind === 'persona' && message.authorName === input.personaName).slice(-3).forEach(take);
56
+ // 其余按时间倒序收,受条数与字符预算限制
57
+ for (let index = candidates.length - 1; index >= 0; index--) {
58
+ if (picked.length >= keep)
59
+ break;
60
+ const message = candidates[index];
61
+ if (guaranteed.has(message.id))
62
+ continue;
63
+ if (chars + message.text.length > budget)
64
+ continue;
65
+ take(message);
66
+ }
67
+ return picked.sort((left, right) => (left.seq ?? 0) - (right.seq ?? 0));
68
+ }
69
+ function label(message, personaId) {
70
+ const head = `[#${message.seq ?? 0}]`;
71
+ if (message.kind === 'system')
72
+ return `${head}[系统] ${message.text}`;
73
+ if (message.kind === 'user')
74
+ return `${head}[用户 ${message.authorName}] ${message.text}`;
75
+ const self = message.authorName === personaId || message.authorName === personaId;
76
+ return `${head}[角色 ${message.authorName}]${self ? '[你之前的发言] ' : ' '}${message.text}`;
77
+ }
78
+ /** 渲染窗口文本:自己的发言必须打上 [你之前的发言],这是防串身份的关键。 */
79
+ export function renderWindow(messages, personaName) {
80
+ return messages.map((message) => {
81
+ const head = `[#${message.seq ?? 0}]`;
82
+ if (message.kind === 'system')
83
+ return `${head}[系统] ${message.text}`;
84
+ if (message.kind === 'user')
85
+ return `${head}[用户 ${message.authorName}] ${message.text}`;
86
+ const self = message.authorName === personaName;
87
+ return `${head}[角色 ${message.authorName}]${self ? '[你之前的发言]' : ''} ${message.text}`;
88
+ }).join('\n');
89
+ }
90
+ /** 角色私有补充:从本地数据拼,不额外调用模型。 */
91
+ export function roleSupplement(personaName, messages, limit = 2) {
92
+ return messages
93
+ .filter((message) => message.kind === 'persona' && message.authorName === personaName)
94
+ .slice(-limit)
95
+ .map((message) => `- [#${message.seq ?? 0}] ${message.text.slice(0, 80)}`);
96
+ }
97
+ export function buildSystem(persona, threadTitle, threadKind = 'group') {
98
+ const who = `角色「${persona.name}」${persona.post ? ',岗位是「' + persona.post + '」' : ''}`;
99
+ const opening = threadKind === 'dm'
100
+ ? `你在和用户的一对一私聊小窗里(小窗名「${threadTitle}」),只有你和用户两个人看得到。你是${who}。`
101
+ : threadKind === 'triad'
102
+ ? `你在三人小窗「${threadTitle}」里${who};这个小窗只有用户、你和另一位角色。`
103
+ : `你是群「${threadTitle}」里的${who}。`;
104
+ const rules = threadKind === 'dm'
105
+ ? '私聊规则:这是一对一私聊,你可以直接回复用户;不要声称“我只能在群里说话 / 私聊发不出去 / 我没有私聊能力”,也不要让用户回群里再说;不要模拟或代替其他角色。'
106
+ : '群规则:只代表你自己发言;不要以“名字:”开头;不要模拟或代替其他角色;不要复述插件内部状态文件。';
107
+ return [
108
+ opening,
109
+ persona.personality ? `人设:${persona.personality}` : '',
110
+ persona.duties?.length ? `职责:${persona.duties.join('、')}` : '',
111
+ rules,
112
+ '身份约束:只有标记为【你之前的发言】的内容才是你说过的,其他都是别人说的。',
113
+ persona.toolAllow?.length
114
+ ? [
115
+ '工具纪律:只能用授予你的工具(读/搜项目文件、写本会话目录、run_check、以及你被授予的宿主工具组);没有 shell,不能执行任意命令或脚本,也不能运行测试文件本身(需要跑检查请用 run_check)。同一个路径不要反复读;拿到足够信息就停止调用工具,直接给出结论。',
116
+ hostToolGranted('bcdp_help', persona.toolAllow) ? '你被授予了浏览器(bcdp)工具,可以打开页面、查看和操作。' : '',
117
+ hostToolGranted('mcp__magpie-image__generate_image', persona.toolAllow) ? '你被授予了画图(Magpie)工具,可以生图或生视频,并用 generation_result 取结果。' : '',
118
+ '出现在工具列表里但没被授予的宿主工具会被拒绝,不要尝试绕过。',
119
+ ].filter(Boolean).join('\n')
120
+ : '',
121
+ '只输出你要说的那段话,不要解释这些规则。',
122
+ ].filter(Boolean).join('\n');
123
+ }
124
+ /** 组装一次发言的输入:固定前缀 → 角色状态 → 摘要 → 共识状态 → 检索到的相关历史 → 最近窗口 → 当前消息。 */
125
+ export function assemblePrompt(input) {
126
+ // 旧版泄漏的思维链不进新 prompt:只在组装时清洗窗口/摘要输入,state 原样保留。
127
+ const messages = input.messages.map((message) => (message.text ? { ...message, text: stripLegacyReasoning(message.text) } : message));
128
+ const window = input.window ?? selectWindow({ ...input, messages });
129
+ const current = input.currentId
130
+ ? messages.find((message) => message.id === input.currentId)
131
+ : undefined;
132
+ const summary = input.summary?.trim();
133
+ const labels = threadLabels(input.threadKind);
134
+ // 补充要点只从**没进窗口、也没被 L1/句柄块引用**的消息里取:
135
+ // 同一 seq 不能在 prompt 里出现两次。
136
+ const windowIds = new Set(window.map((message) => message.id));
137
+ const excludeRefs = input.excludeSeqRefs;
138
+ const supplementSource = messages.filter((message) => (!windowIds.has(message.id) && !(message.seq !== undefined && excludeRefs?.has(message.seq))));
139
+ const supplement = roleSupplement(input.personaName, supplementSource.length ? supplementSource : messages)
140
+ .filter((line) => {
141
+ // roleSupplement 的每行形如 `- [#seq] ...`:排除已经被其它块引用的 seq。
142
+ const match = /^-\s*\[#(\d+)\]/.exec(line);
143
+ if (!match)
144
+ return true;
145
+ return !excludeRefs?.has(Number(match[1]));
146
+ });
147
+ const summaryBlock = summary
148
+ ? [labels.summary, summary, ...(supplement.length ? ['[你之前的发言要点]', ...supplement] : [])].join('\n')
149
+ : supplement.length ? ['[你之前的发言要点]', ...supplement].join('\n') : '';
150
+ const prompt = [
151
+ input.stateBlock?.trim(),
152
+ summaryBlock,
153
+ input.consensusBlock?.trim(),
154
+ input.memoryBlock?.trim(),
155
+ input.contextBlock?.trim(),
156
+ input.retrievalBlock?.trim(),
157
+ labels.recent,
158
+ renderWindow(window, input.personaName),
159
+ current
160
+ ? ['[当前消息]', renderWindow([current], input.personaName)].join('\n')
161
+ : '',
162
+ ].filter(Boolean).join('\n\n');
163
+ return { system: buildSystem(input.persona, input.threadTitle, input.threadKind ?? 'group'), prompt, window };
164
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * 两阶段回执(receipt):发送前记 intent,结束后补 outcome。
3
+ *
4
+ * 目的:任何一轮都能回答“模型当时看到了什么、用的是哪版规则”,
5
+ * 出问题时可离线复现,不靠猜。
6
+ */
7
+ export declare const HASH_ALGO_VERSION = "fnv1a32-v1";
8
+ export declare const PROMPT_TEMPLATE_VERSION = "im-prompt-v1";
9
+ export declare const VISIBILITY_POLICY_VERSION = "visibility-v1";
10
+ export declare const EVENT_LOG_SCHEMA_VERSION = 1;
11
+ /** 规范化 JSON:键排序、去 undefined、NFC 归一,保证同样的内容 hash 相同。 */
12
+ export declare function canonicalJson(value: unknown): string;
13
+ /** 确定性哈希(FNV-1a 32 位,纯 JS,客户端也能用)。 */
14
+ export declare function stableHash(text: string): string;
15
+ export declare function fingerprint(parts: Record<string, unknown>): string;
16
+ export interface ReceiptVersions {
17
+ eventLogSchema: number;
18
+ promptTemplate: string;
19
+ visibilityPolicy: string;
20
+ hashAlgo: string;
21
+ factsVersion?: string;
22
+ }
23
+ export interface ReceiptSampling {
24
+ temperature?: number;
25
+ maxTokens?: number;
26
+ reasoningEffort?: string;
27
+ }
28
+ export interface ReceiptIntent {
29
+ turnId: string;
30
+ personaId: string;
31
+ provider: string;
32
+ model: string;
33
+ /** 本轮窗口里的事件序号(回放时用来比对“看到的是不是这一批”)。 */
34
+ windowSeqs: number[];
35
+ summaryUntil: number;
36
+ versions: ReceiptVersions;
37
+ sampling?: ReceiptSampling;
38
+ systemPromptHash: string;
39
+ promptHash: string;
40
+ /** 角色状态快照的内容 hash(回执变厚:状态版本可回放)。 */
41
+ stateSnapshotHash?: string;
42
+ /** 按需检索的审计字段:结构化 query + 完整命中 + 最终选中 + 索引版本。 */
43
+ retrieval?: {
44
+ query: ReceiptRetrievalQuery;
45
+ hitIds: number[];
46
+ selectedIds: number[];
47
+ indexVersion: string;
48
+ };
49
+ /** 窗口里是否含不可信内容(群消息/工具结果)。 */
50
+ untrusted: boolean;
51
+ /** Phase 1 引用句柄协议审计:选中/目录 seq、话题段、字数与背压原因(不含正文)。 */
52
+ memoryContext?: import('./memory-context.ts').MemoryContextReceipt;
53
+ /** A-1 群级预算快照(粘滞;同输入同预算,可离线对照)。 */
54
+ budget?: import('./context-budget.ts').ContextBudgetReceipt;
55
+ /** A-1 预算变更事件:只在成员/模型/档位/ratio 显式变化时出现(不是每轮都写)。 */
56
+ budgetChanged?: import('./context-budget.ts').BudgetChangedEvent;
57
+ at: number;
58
+ }
59
+ /** 回执里的结构化检索 query(能 diff,不用自然语言字符串)。 */
60
+ export interface ReceiptRetrievalQuery {
61
+ topicId: number;
62
+ entities: {
63
+ type: string;
64
+ value: string;
65
+ }[];
66
+ replyChainRoots: number[];
67
+ params: {
68
+ retrievalVersion: string;
69
+ topicSegVersion: string;
70
+ weights: Record<string, number>;
71
+ };
72
+ }
73
+ export interface ReceiptOutcome {
74
+ tokensIn?: number;
75
+ tokensOut?: number;
76
+ ms: number;
77
+ finish: 'stop' | 'tool-calls' | 'max-tokens' | 'error' | 'aborted';
78
+ }
79
+ export interface TurnReceipt {
80
+ intent: ReceiptIntent;
81
+ outcome?: ReceiptOutcome;
82
+ }
83
+ export declare function defaultVersions(extra?: Partial<ReceiptVersions>): ReceiptVersions;
84
+ export declare function createIntent(input: {
85
+ turnId: string;
86
+ personaId: string;
87
+ provider: string;
88
+ model: string;
89
+ windowSeqs: number[];
90
+ summaryUntil?: number;
91
+ systemPrompt: string;
92
+ prompt: string;
93
+ sampling?: ReceiptSampling;
94
+ untrusted?: boolean;
95
+ versions?: Partial<ReceiptVersions>;
96
+ stateSnapshotHash?: string;
97
+ retrieval?: ReceiptIntent['retrieval'];
98
+ memoryContext?: ReceiptIntent['memoryContext'];
99
+ budget?: ReceiptIntent['budget'];
100
+ budgetChanged?: ReceiptIntent['budgetChanged'];
101
+ at: number;
102
+ }): ReceiptIntent;
103
+ /** 回执自检:窗口序号是否与“现在按同一规则重算的窗口”一致。 */
104
+ export declare function verifyReceipt(intent: ReceiptIntent, currentWindowSeqs: readonly number[]): {
105
+ ok: boolean;
106
+ reason?: string;
107
+ };
@@ -0,0 +1,86 @@
1
+ /**
2
+ * 两阶段回执(receipt):发送前记 intent,结束后补 outcome。
3
+ *
4
+ * 目的:任何一轮都能回答“模型当时看到了什么、用的是哪版规则”,
5
+ * 出问题时可离线复现,不靠猜。
6
+ */
7
+ export const HASH_ALGO_VERSION = 'fnv1a32-v1';
8
+ export const PROMPT_TEMPLATE_VERSION = 'im-prompt-v1';
9
+ export const VISIBILITY_POLICY_VERSION = 'visibility-v1';
10
+ export const EVENT_LOG_SCHEMA_VERSION = 1;
11
+ /** 规范化 JSON:键排序、去 undefined、NFC 归一,保证同样的内容 hash 相同。 */
12
+ export function canonicalJson(value) {
13
+ if (value === null || typeof value !== 'object') {
14
+ return typeof value === 'string' ? JSON.stringify(value.normalize('NFC')) : JSON.stringify(value) ?? 'null';
15
+ }
16
+ if (Array.isArray(value)) {
17
+ return '[' + value.map((item) => (item === undefined ? 'null' : canonicalJson(item))).join(',') + ']';
18
+ }
19
+ const keys = Object.keys(value).sort();
20
+ const parts = [];
21
+ for (const key of keys) {
22
+ const item = value[key];
23
+ if (item === undefined)
24
+ continue;
25
+ parts.push(JSON.stringify(key.normalize('NFC')) + ':' + canonicalJson(item));
26
+ }
27
+ return '{' + parts.join(',') + '}';
28
+ }
29
+ /** 确定性哈希(FNV-1a 32 位,纯 JS,客户端也能用)。 */
30
+ export function stableHash(text) {
31
+ let hash = 0x811c9dc5;
32
+ const normalized = text.normalize('NFC');
33
+ for (let index = 0; index < normalized.length; index++) {
34
+ hash ^= normalized.charCodeAt(index);
35
+ hash = Math.imul(hash, 0x01000193) >>> 0;
36
+ }
37
+ return HASH_ALGO_VERSION + ':' + hash.toString(16).padStart(8, '0');
38
+ }
39
+ export function fingerprint(parts) {
40
+ return stableHash(canonicalJson(parts));
41
+ }
42
+ export function defaultVersions(extra = {}) {
43
+ return {
44
+ eventLogSchema: EVENT_LOG_SCHEMA_VERSION,
45
+ promptTemplate: PROMPT_TEMPLATE_VERSION,
46
+ visibilityPolicy: VISIBILITY_POLICY_VERSION,
47
+ hashAlgo: HASH_ALGO_VERSION,
48
+ ...extra,
49
+ };
50
+ }
51
+ export function createIntent(input) {
52
+ return {
53
+ turnId: input.turnId,
54
+ personaId: input.personaId,
55
+ provider: input.provider,
56
+ model: input.model,
57
+ windowSeqs: [...input.windowSeqs],
58
+ summaryUntil: input.summaryUntil ?? 0,
59
+ versions: defaultVersions(input.versions),
60
+ ...(input.sampling === undefined ? {} : { sampling: input.sampling }),
61
+ systemPromptHash: stableHash(input.systemPrompt),
62
+ promptHash: stableHash(input.prompt),
63
+ ...(input.stateSnapshotHash ? { stateSnapshotHash: input.stateSnapshotHash } : {}),
64
+ ...(input.retrieval ? { retrieval: input.retrieval } : {}),
65
+ ...(input.memoryContext ? { memoryContext: input.memoryContext } : {}),
66
+ ...(input.budget ? { budget: input.budget } : {}),
67
+ ...(input.budgetChanged ? { budgetChanged: input.budgetChanged } : {}),
68
+ untrusted: Boolean(input.untrusted),
69
+ at: input.at,
70
+ };
71
+ }
72
+ /** 回执自检:窗口序号是否与“现在按同一规则重算的窗口”一致。 */
73
+ export function verifyReceipt(intent, currentWindowSeqs) {
74
+ if (intent.versions.hashAlgo !== HASH_ALGO_VERSION) {
75
+ return { ok: false, reason: 'hash 算法版本不一致,无法比对' };
76
+ }
77
+ if (intent.windowSeqs.length !== currentWindowSeqs.length) {
78
+ return { ok: false, reason: `窗口长度变化:${intent.windowSeqs.length} → ${currentWindowSeqs.length}` };
79
+ }
80
+ for (let index = 0; index < intent.windowSeqs.length; index++) {
81
+ if (intent.windowSeqs[index] !== currentWindowSeqs[index]) {
82
+ return { ok: false, reason: `第 ${index + 1} 条窗口事件不同:#${intent.windowSeqs[index]} → #${currentWindowSeqs[index]}` };
83
+ }
84
+ }
85
+ return { ok: true };
86
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * 按需检索(Phase 2):确定性、零外部依赖(不依赖 embedding)。
3
+ *
4
+ * 群聊的相关性主要由「回复链 / 实体 / 人名 / 编号 / 话题」决定,不是语义相似度:
5
+ * - 回复链:当前消息里显式 `#123` 引用的事件;
6
+ * - 实体:@该角色、角色名、文件路径、`「引号内容」`、时间/编号;
7
+ * - 话题:按用户消息边界切段,同一段的旧事件加分(话题分段版本记进 indexVersion)。
8
+ *
9
+ * 候选 = 全部可见事件 − 当前窗口 − 当前消息;**不排除 L1 摘要区间**:
10
+ * 摘要是有损压缩,检索要补的正是它丢掉的原始细节。
11
+ *
12
+ * 排序:score desc → seq desc(确定性 tie-break)。结果按 token 预算(窗口预算的 20%)裁剪,
13
+ * 条数上限 8 只是兜底。query / 完整命中列表 / 最终选中列表都交给回执审计。
14
+ */
15
+ import type { Message, RetrievalQuery, RetrievalResult } from './types.ts';
16
+ export declare const RETRIEVAL_VERSION = "retrieval-v1";
17
+ export declare const TOPIC_SEG_VERSION = "topics-v1";
18
+ export declare const DEFAULT_MAX_HITS = 8;
19
+ export declare const DEFAULT_MAX_TOTAL_CHARS = 2400;
20
+ export declare const MAX_RECORDED_HITS = 50;
21
+ /** 打分权重:默认值写死(探针集就是拿默认值测的);可整体覆盖做实验。 */
22
+ export declare const DEFAULT_WEIGHTS: {
23
+ readonly replyChain: 100;
24
+ readonly mentionPersona: 50;
25
+ readonly roleNameOrFile: 40;
26
+ readonly quotedOrTimeOrNumber: 30;
27
+ readonly sameTopic: 20;
28
+ readonly recencyMax: 10;
29
+ };
30
+ export type RetrievalWeights = typeof DEFAULT_WEIGHTS;
31
+ export interface RetrievalInput {
32
+ messages: readonly Message[];
33
+ personaName: string;
34
+ memberNames?: readonly string[];
35
+ /** 当前用户消息文本(检索词来源)。 */
36
+ currentText: string;
37
+ /** 窗口内 / 当前消息的 seq:不参与检索(L1 摘要区间不排除)。 */
38
+ excludeSeqs?: ReadonlySet<number>;
39
+ /** 可见性谓词(默认全部可见;调用方传入已按可见性过滤的消息也可以)。 */
40
+ isVisible?: (message: Message) => boolean;
41
+ /** token 预算(字符≈token 的保守估算),默认 2400。 */
42
+ maxTotalChars?: number;
43
+ maxHits?: number;
44
+ weights?: Partial<RetrievalWeights>;
45
+ }
46
+ export interface RetrievalTerms {
47
+ /** 强实体(带类型,回执里结构化记录)。 */
48
+ entities: RetrievalQuery['entities'];
49
+ /** 弱词(ASCII 词 + 中文 bigram),只用于打分,不进回执。 */
50
+ weak: string[];
51
+ replyChainRoots: number[];
52
+ }
53
+ export declare function extractRetrievalTerms(input: {
54
+ text: string;
55
+ personaName: string;
56
+ memberNames?: readonly string[];
57
+ }): RetrievalTerms;
58
+ /** 话题分段:每个用户消息开启一段,system 消息归并到当前段(确定性)。 */
59
+ export interface TopicSegmentInfo {
60
+ /** 每条消息(按 seq 升序)对应的 topicId;topicId 用该段用户消息的 seq。 */
61
+ topicBySeq: Map<number, number>;
62
+ currentTopicId: number;
63
+ version: string;
64
+ }
65
+ export declare function segmentTopics(messages: readonly Message[]): TopicSegmentInfo;
66
+ /** 检索窗口之外的旧事件:返回按分数排序的完整命中列表 + 受预算约束的选中列表。 */
67
+ export declare function retrieveRelevant(input: RetrievalInput): RetrievalResult;
68
+ /** 渲染 prompt 的 `[相关历史]` 块;没有命中返回空串。 */
69
+ export declare function renderRetrieval(result: RetrievalResult | undefined): string;