@cqfe/sxin-chat-core 1.0.1 → 1.0.3

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/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
- import { C as CreateStreamOptions, a as ChatStreamHandle, S as SxinNode, E as ElementNode, B as Block, b as CitationItem, I as IKwargs, R as RunInfo, c as RunMessage, d as ReportBodyPayload, e as ReportOutlinePayload, f as BlockBuilderOptions, G as GroupMessageTool, M as MessageTokenUsage, O as OutlineSubChapter, g as OutlineChapter, h as GroupMessageType, i as BlockBuilderLiteOptions, j as GroupMessage, k as SendMessageOptions, l as ChatTransport, T as ThreadInitialValues, m as MessagesPage, n as ThreadTokenUsage, o as StreamSubmitInput, p as StreamSubmitOptions, H as HitlResponse } from './ChatCore-C-G9isDM.cjs';
2
- export { A as AcquireResult, q as AgentThreadState, r as ArtifactBlock, s as ArtifactFile, t as AskClarificationBlock, u as BlockBase, v as BlockBuilderLite, w as BlockSource, x as BlockStatus, y as BuildAllOptions, z as ChatCore, D as ChatCoreOptions, F as ChatNotify, J as CommentNode, K as CustomBlock, L as DEFAULT_TWIN_TOOL_PREFIX, N as FetchMessagesPageOptions, P as FormBlock, Q as FormFieldItem, U as FormFieldType, V as GenerateBodyRequest, W as GenerateBodyResult, X as GroupMessageSource, Y as GroupMessageStatus, Z as HitlActionRequest, _ as HitlDecision, $ as HitlDecisionType, a0 as HitlInterruptPayload, a1 as HitlReviewConfig, a2 as IAttachment, a3 as IQuote, a4 as InlineCitation, a5 as InterruptReviewBlock, a6 as ListBlock, a7 as ListItem, a8 as Message, a9 as MessageMetadata, aa as MessageRole, ab as MessageSource, ac as MessageStatus, ad as ReportBodyBlock, ae as ReportGenerateBodyHumanKwargs, af as ReportOutlineBlock, ag as ReportSelectedArtifact, ah as ReportSelectedTemplate, ai as SearchThreadsOptions, aj as TextBlock, ak as TextNode, al as ThreadDirectory, am as ThreadDirectoryOptions, an as ThreadRuntime, ao as ThreadRuntimeOptions, ap as ThreadsPagination, aq as TwinBlock, ar as buildHitlDecisions, as as buildInterruptReviewBlock, at as buildInterruptReviewGroup, au as buildRejectDecisions, av as buildRunDirectLatencyMs, aw as buildRunInfo, ax as createBlockBuilderLite, ay as createChatCore, az as createThreadRuntime, aA as getAllowedDecisions, aB as isSameArgs, aC as normalizeForCompare, aD as parseHitlPayload, aE as pickRunMessageMetadata } from './ChatCore-C-G9isDM.cjs';
1
+ import { B as Block, C as CitationItem, I as IKwargs, R as RunInfo, a as RunMessage, b as ReportBodyPayload, c as ReportOutlinePayload, d as BlockBuilderOptions, G as GroupMessageTool, M as MessageTokenUsage, O as OutlineSubChapter, e as OutlineChapter, P as ProjectRunsInput, f as RunItem, A as AsmRow, g as RunStatus, E as ExtractedPayload, h as ChatTransport, T as ThreadInitialValues, i as MessagesPage, j as ThreadTokenUsage, S as StreamSubmitInput, k as StreamSubmitOptions, H as HitlResponse, l as CreateStreamOptions } from './ChatCore-CCeoxjP9.cjs';
2
+ export { m as AcquireResult, n as AgentThreadState, o as ArtifactFile, p as Attachment, q as BlockBase, r as BlockSource, s as BlockStatus, t as BodySegment, u as ChatCore, v as ChatCoreOptions, w as ChatNotify, x as ChatStreamHandle, y as ClarificationRecord, z as CustomBlock, F as FetchMessagesPageOptions, D as FormBlock, J as FormFieldItem, K as FormFieldType, L as GenerateBodyRequest, N as GenerateBodyResult, Q as HitlActionRequest, U as HitlDecision, V as HitlDecisionType, W as HitlInterruptPayload, X as HitlReviewConfig, Y as IAttachment, Z as IQuote, _ as InlineCitation, $ as InterruptReviewBlock, a0 as ItemSegment, a1 as ListBlock, a2 as ListItem, a3 as Message, a4 as MessageMetadata, a5 as MessageRole, a6 as MessageSource, a7 as MessageStatus, a8 as PendingRun, a9 as ReportAttachment, aa as ReportGenerateBodyHumanKwargs, ab as ReportSelectedArtifact, ac as ReportSelectedTemplate, ad as RunInputKind, ae as RunMeta, af as RunTokens, ag as SearchThreadsOptions, ah as SendMessageOptions, ai as TextBlock, aj as ThreadDirectory, ak as ThreadDirectoryOptions, al as ThreadRuntime, am as ThreadRuntimeOptions, an as ThreadsPagination, ao as ToolRun, ap as XmlAttrs, aq as buildHitlDecisions, ar as buildInterruptReviewBlock, as as buildRejectDecisions, at as buildRunDirectLatencyMs, au as buildRunInfo, av as buildRunMeta, aw as createChatCore, ax as createThreadRuntime, ay as getAllowedDecisions, az as isSameArgs, aA as normalizeForCompare, aB as parseHitlPayload, aC as pickRunMessageMetadata, aD as sliceBodySegments } from './ChatCore-CCeoxjP9.cjs';
3
3
  import { Message, Interrupt } from '@langchain/langgraph-sdk';
4
- import { Ref, ShallowRef } from 'vue';
4
+ import 'vue';
5
5
 
6
6
  /**
7
7
  * 项目内消息视图类型(评审 C5):LangGraph Message union + 消息链路实际依赖的自由字段,
@@ -34,68 +34,48 @@ declare const DEFAULT_MAX_CONCURRENT_STREAMS = 3;
34
34
  /** 默认 assistantId(web 为 import.meta.env.VITE_LANGGRAPH_ASSISTANT_ID 的兜底值) */
35
35
  declare const DEFAULT_ASSISTANT_ID = "lead_agent";
36
36
 
37
- /** SDK client.runs.stream yield 的单条 SSE 事件(解码后形态) */
38
- interface StreamEvent {
39
- event: string;
40
- data: any;
37
+ /**
38
+ * sxin AST 节点类型定义
39
+ *
40
+ * 独立成文件以打破 sxin-ast ↔ sxin-ast-collect 的模块环:
41
+ * tokenizer 与文本提取均只依赖本文件的类型,互不引用。
42
+ */
43
+ /** 文本节点:原文切片 */
44
+ interface TextNode {
45
+ type: 'text';
46
+ /** 原文内容 */
47
+ value: string;
48
+ /** 在原文中的起始偏移(含) */
49
+ start: number;
50
+ /** 在原文中的结束偏移(不含) */
51
+ end: number;
41
52
  }
42
- /** 发起一次 run 流的上行 payload(web 端 = client.runs.stream 的第三参) */
43
- interface RunStreamPayload {
44
- input?: unknown;
45
- command?: {
46
- resume?: unknown;
47
- };
48
- config?: Record<string, unknown>;
49
- onDisconnect?: 'continue' | 'cancel';
50
- streamMode?: string[];
51
- onRunCreated?: (params: {
52
- run_id: string;
53
- thread_id?: string;
54
- }) => void;
55
- [key: string]: unknown;
53
+ /** 注释节点:<!-- ... --> */
54
+ interface CommentNode {
55
+ type: 'comment';
56
+ /** 注释内部内容(不含 <!-- 与 -->) */
57
+ content: string;
58
+ start: number;
59
+ end: number;
56
60
  }
57
- /** 平台注入的网络源:HTTP/SSE 收发由 adapter 实现,core 只消费解码后的事件流 */
58
- interface StreamEventSource {
59
- /** 发起一次 run 流(web 端 = client.runs.stream) */
60
- openRunStream(payload: RunStreamPayload, signal: AbortSignal): AsyncIterable<StreamEvent>;
61
- /** 加入既有 run 的流(web 端 = client.runs.joinStream) */
62
- openJoinStream(runId: string, lastEventId: string, signal: AbortSignal): AsyncIterable<StreamEvent>;
61
+ /** 元素节点:<tag attrs>children</tag> 或 <tag attrs/> */
62
+ interface ElementNode {
63
+ type: 'element';
64
+ /** 标签名(统一小写,大小写不敏感) */
65
+ tagName: string;
66
+ /** 解析后的属性对象(key/value 均经 formatStr 格式化) */
67
+ attrs: Record<string, string>;
68
+ /** 子节点(已闭合或自闭合标签才有内容;未闭合标签延伸到 EOF) */
69
+ children: SxinNode[];
70
+ /** 是否自闭合(<tag/>) */
71
+ selfClosing: boolean;
72
+ /** 是否有配对闭合标签;false 表示流式截断或 LLM 少输出闭合标签 */
73
+ closed: boolean;
74
+ start: number;
75
+ /** closed=false 时等于原文长度 */
76
+ end: number;
63
77
  }
64
- declare function createStreamPump(source: StreamEventSource, options: CreateStreamOptions & {
65
- assistantId: string;
66
- threadId: string;
67
- }): ChatStreamHandle;
68
-
69
- /**
70
- * thread 指令集(store 的唯一消费接口,指令协议)。
71
- *
72
- * 指令语义:
73
- * - upsert / remove / clear / prepend:消息集合维护;定位一律按消息 id,禁止携带数组 index
74
- * (翻页 prepend 使 index 全局失效)
75
- * - finalize:流结束定稿
76
- * - runId 已在指令产出前盖章进消息本体(信封盖章),消费端只读不再推导
77
- *
78
- * values 快照替换(runtime-bootstrap buildValuesReplaceInstructions)复用 upsert:
79
- * source 不传(默认流式语义),仅整条替换当前轮流式段实体。
80
- */
81
-
82
- type ThreadInstruction = {
83
- kind: 'upsert';
84
- message: SxinMessage; /** 对账转正:流式实体转为 page 权威(source 语义切换) */
85
- source?: 'page';
86
- } | {
87
- kind: 'remove';
88
- id: string;
89
- } | {
90
- kind: 'clear';
91
- } | {
92
- kind: 'prepend';
93
- messages: SxinMessage[];
94
- } | {
95
- kind: 'finalize';
96
- };
97
- /** 指令出口(protocol 产出 → store 消费) */
98
- type InstructionSink = (instructions: ThreadInstruction[]) => void;
78
+ type SxinNode = TextNode | CommentNode | ElementNode;
99
79
 
100
80
  /**
101
81
  * sxin-ast-attrs.ts — sxin 标签开口内的属性串解析
@@ -223,6 +203,9 @@ interface ThreadInfo {
223
203
  /** 澄清/表单/list 的回答:request_id(toolCallId,已剥离 clarification: 前缀)→ 回答内容 */
224
204
  clarificationAnswers: Map<string, string>;
225
205
  }
206
+ /** 回答值 → 可读文本(展示侧只读文本值;结构化消费方在 rawMessages):
207
+ * 字符串原样;{values:{...}} 拼非空值为 '; ' 分隔;其他对象 JSON 兜底;其余 String()。 */
208
+ declare function formatAnswerText(value: unknown): string;
226
209
  /** 全量遍历原始消息,单遍提取所有 thread 级信息 */
227
210
  declare function extractThreadInfo(messages: Message[] | undefined | null): ThreadInfo;
228
211
  /** human_input_response 负载字段(协议结构,写侧与读侧保持一致) */
@@ -250,6 +233,23 @@ declare function buildHumanInputResponse(requestId: string, options: HumanInputR
250
233
  */
251
234
  /** 从 state payload 的 values 中提取 messages */
252
235
  declare function extractStateMessages(state: Record<string, unknown> | null | undefined): Message[];
236
+ /**
237
+ * 合并 state 与 page 两源历史消息:以 state 为基准(语义字段全:artifact_meta /
238
+ * human_input_response / hide_from_ui 仅 state 侧存在),page(run-event 全量投影,
239
+ * seq 旧→新)补齐 state 被上下文压缩缺失的头部消息与 checkpoint 滞后的尾部消息。
240
+ *
241
+ * 对齐依据:human/ai 消息两源 id 一致(实测);page 侧普通 tool 消息无 id,按
242
+ * tool_call_id 与 ai 的 tool_calls 配对判定存在性。
243
+ *
244
+ * 返回:合并后的完整消息序列(旧→新)。page 为空返回 state;state 为空返回 page;
245
+ * 完全无 id 锚点(异常场景)降级返回 page(既有「page 权威」行为)。
246
+ *
247
+ * 注意:bridge/sdk-demo 虽已删除(2026-11-18 传输层迁移),本函数**不可删**——
248
+ * 现正式用于 web 端 hydrate 基线合并(src/adapters/stream/hydrateBaseline.ts,
249
+ * 包装 client.threads.getState 以 page 补齐 /state 压缩缺失),迁移记录见
250
+ * docs/chat-core-client-mode-migration.md。
251
+ */
252
+ declare function mergeStateWithPageMessages(stateMessages: Message[], pageMessages: Message[]): Message[];
253
253
  /** 确保 runs map 中存在指定 runId 的 running 状态 RunInfo */
254
254
  declare function ensureRunningRun(runMap: Map<string, RunInfo>, runId: string, threadId: string | null): RunInfo;
255
255
 
@@ -271,6 +271,17 @@ declare function extractRunEnrichment(messages: RunMessage[]): Map<string, {
271
271
  feedback?: unknown;
272
272
  latencyMs?: number;
273
273
  }>;
274
+ /**
275
+ * 按消息 id 从原始 page 行回填行级 feedback 到组装后的行(伪 page 专用)。
276
+ * 背景:init 组装路径(fetchThreadInitialValues)以 state 为基准 + stateMessagesToRunMessages
277
+ * 伪 page,行级 feedback(page 行专属)在两次转换中丢失 → enrichFromPage 提取不到
278
+ * → runsMap.feedback 恒 undefined → 点赞/点踩历史不回显。与 mergeStateWithPageMessages
279
+ * 的 runId 盖章回填同一语义(page 是行级归属字段的权威源)。
280
+ * 纯函数:未命中/无 id 的行保持原引用;target 已有 feedback 不覆盖;入参不改。
281
+ *
282
+ * @deprecated 2026-11 语义层分离后 web 编排退役(page 直出行级字段天然在,无伪 page 装配)。
283
+ */
284
+ declare function backfillRunMessageFeedback(source: RunMessage[], target: RunMessage[]): RunMessage[];
274
285
  /** RunMessage[] → LangGraphMessage[](浅拷贝 content 并注入 runId 字段,供 initialValues 与 builder 消费) */
275
286
  declare function runMessagesToMessages(messages: RunMessage[]): Message[];
276
287
  /**
@@ -278,6 +289,13 @@ declare function runMessagesToMessages(messages: RunMessage[]): Message[];
278
289
  * page 接口为空而 state 有值时:用 state 数据构造伪 page(hasMore:false、无游标),
279
290
  * 伪 page 与真 page 对 pager 完全同构(此后不翻页)。
280
291
  * seq 按下标+1 生成(伪 page 不可翻页,seq 仅为满足游标安全约束的有限值)。
292
+ *
293
+ * runId 前向填充:checkpoint 快照仅 human(user-input 信封)携带 additional_kwargs.run_id,
294
+ * ai/tool 消息缺失——而 groupRowsByRun 对空 runId 行按「无归属窗口不渲染」丢弃,直接映射
295
+ * 会让兜底装配只剩 human 气泡(正文/工具链/clarification 全丢,见 thread 73f0a72c 故障)。
296
+ * 故继承最近一个带 run_id 的行:human 行开启新窗口,其后 ai/tool 归入同窗口(与
297
+ * 「human 触发 → 同 run 产出」的窗口语义一致);首个带 run_id 行之前的行无归属保持空串,
298
+ * 交由 pushToBucket 丢弃(system 行本就不渲染)。自身带 run_id 的行恒优先。
281
299
  */
282
300
  declare function stateMessagesToRunMessages(messages: Message[]): RunMessage[];
283
301
 
@@ -477,183 +495,171 @@ declare function isReportBodyHtml(content: string): boolean;
477
495
  declare function extractReportTitleFromBody(content: string, fallback?: string): string;
478
496
 
479
497
  /**
480
- * fold:消息序列切分(分组规则的唯一一份实现)。
481
- * runId 不在此推导——已在 protocol 信封盖章 / page 行自带,fold 只读消息本体;
482
- * 组 status 也不在 fold 时定死:fold 只按消息序列产出组,status 由 viewmodel 依
483
- * store.streamStatus 判定(见 group-materializer / viewmodel)。
484
- *
485
- * 本文件只做「序列切分」;GroupMessage 物料化(texts/tools/blocks/时间戳)见 group-materializer.ts。
498
+ * 装配 RunItem[](core 唯一投影入口;幂等纯函数)。
486
499
  */
500
+ declare function projectRuns(input: ProjectRunsInput): RunItem[];
487
501
 
502
+ /** 单 run 装配选项 */
503
+ interface AssembleRunOptions {
504
+ /** 窗口行(seq 升序;由 groupRowsByRun 保证) */
505
+ rows: readonly AsmRow[];
506
+ /** 流式进行中(本 run 为活跃 run):segments 不切片 */
507
+ streaming: boolean;
508
+ /** 数字孪生附件识别配置 */
509
+ twin?: {
510
+ enabled?: boolean;
511
+ toolPrefix?: string;
512
+ };
513
+ }
488
514
  /**
489
- * 消息序列按分组规则 fold(human 按 base id 归并 / ai-tool 连续归组)。
490
- * flush 回调由调用方决定组构建语义;未知类型消息忽略。
515
+ * 空的 RunItem 形状(pending 占位 run 用:无窗口行,只有 input)。
516
+ * segments 恒非空数组(单空 text 段,与 sliceBodySegments 契约一致)。
491
517
  */
492
- declare function foldMessages(target: Message[], flush: (type: GroupMessageType, buf: Message[]) => void): void;
493
-
518
+ declare function emptyRunItem(runId: string, createdAt?: number): RunItem;
494
519
  /**
495
- * group-materializer:fold 切分结果 → GroupMessage 物料化。
496
- * 组构建三要素:texts 预计算 / tools 派生(全库唯一入口 deriveToolsFromMessages)/ blocks 一次构建。
520
+ * 装配单个 run。
521
+ * 恒返回非空 RunItem(空窗口 → 空 body 形状,消费方无需判空)。
497
522
  */
523
+ declare function assembleRun(runId: string, options: AssembleRunOptions): RunItem;
524
+ /** 从窗口行提取 input 兜底(runs.list 缺失时用):首个可见 human 行的可见文本 + kwargs。
525
+ * 跳过 hide_from_ui=true 的隐藏消息(澄清回答等,isVisibleUserMessage 判定)——
526
+ * state 兜底路径的窗口行可能携带隐藏消息,取到会给 UI 渲染 raw 提示文本 */
527
+ declare function extractInputFromRows(rows: readonly AsmRow[]): {
528
+ text: string;
529
+ kwargs?: Record<string, unknown>;
530
+ };
531
+ /** 后端 run 状态 → RunStatus(BACKEND_STATUS_MAP 命中取值;未知值保守映射 success——历史已完成 run 的缺省) */
532
+ declare function mapBackendStatus(raw: string): RunStatus;
498
533
 
499
- /** 构建 human 类型的 GroupMessage */
500
- declare function buildHumanGroup(messages: Message[], status: GroupMessage['status']): GroupMessage;
501
- /** 构建 ai 类型的 GroupMessage;twin 为数字孪生 block 配置(缺省关闭) */
502
- declare function buildAiGroup(messages: Message[], options: {
503
- source: 'history' | 'sse' | 'state';
504
- isStreaming: boolean;
505
- id?: string;
506
- runId?: string;
507
- }, twin?: BlockBuilderLiteOptions['twin']): GroupMessage;
508
-
509
- /** 消息实体:消息本体 + 进入集合时确定的 runId + 来源段 */
510
- interface MessageEntity {
511
- /** 消息本体(盖章后的 dict) */
512
- msg: SxinMessage;
513
- /** 来源:page = messages/page 接口(历史权威);stream = SSE tuple 通道 */
514
- source: 'page' | 'stream';
515
- /** 进入集合时的流段代次(beginStream 自增):「当前轮流内消息」的唯一可靠判据 */
516
- epoch: number;
517
- /** 每次更新递增(对账/幂等判断用) */
518
- ver: number;
519
- }
520
- /** 流状态(runtime 状态机驱动迁移;viewmodel 据此判定组 status) */
521
- type StreamStatus = 'idle' | 'streaming' | 'settled';
522
- interface ThreadStore {
523
- /** 指令消费(protocol 的 chunk-buffer / runtime 的 pager 对账都汇到这里) */
524
- applyInstructions(instructions: ThreadInstruction[]): void;
525
- /** 新流开始(runtime 状态机迁移时调用):流状态 → streaming */
526
- beginStream(): void;
527
- /** 实体定位(O(1)) */
528
- getEntity(id: string): MessageEntity | undefined;
529
- /** 两段有序 id(page 段前缀 + 流式段后缀;只读引用,变更时整体替换) */
530
- readonly order: readonly string[];
531
- /** page 段长度(头部连续 page-source 前缀,= 流式段起始下标;派生值) */
532
- readonly pageCount: number;
533
- /** 有序消息数组(惰性构建,version 未变时返回缓存引用) */
534
- getMessages(): SxinMessage[];
535
- /** 流状态 */
536
- readonly streamStatus: StreamStatus;
537
- /** 流段代次(beginStream 自增):派生层判定「本轮在途消息」用,替代 runId/位置近似 */
538
- readonly streamEpoch: number;
539
- /** 变更版本号(消息集合或流状态变更时自增;computed 依赖此值触发重算) */
540
- readonly version: Ref<number>;
541
- /** 流状态响应式镜像(与 streamStatus 同步) */
542
- readonly streamStatusRef: ShallowRef<StreamStatus>;
543
- }
544
- /** citation 补丁:viewmodel 构建 blocks 时注入到 AI 消息(content 回补 state 侧标签) */
545
- interface CitationPatch {
546
- content?: unknown;
547
- }
548
- interface Enrichments {
549
- /** init 装配:从 state 侧消息一次提取 citation + 澄清回答(可多次调用,合并语义) */
550
- applyFromStateMessages(messages: Message[]): void;
551
- /** 构建 blocks 时的 citation 关联查询(按消息 id) */
552
- resolveCitation(messageId: string): CitationPatch | undefined;
553
- /**
554
- * citation patch 版本号:每次 citationPatches 实际变更(新增/覆盖)自增。
555
- * 仅作 buildGroups memoKey 的失效标量(私有计数,无需响应式)——补丁到达的
556
- * 派生通知由 shallowReactive Map 的追踪能力承担(set 即触发依赖它的 computed)。
557
- */
558
- readonly citationVersion: number;
559
- /** 澄清回答缓存(requestId/toolCallId → answer;只增不损) */
560
- readonly answers: Map<string, string>;
561
- /** 乐观写入回答(用户提交澄清表单时,回答消息不经过本端消息集合) */
562
- setAnswer(requestId: string, answer: string): void;
563
- /** 清空回答缓存(clearClarificationAnswers 通路;citation 补丁不受影响) */
564
- clearAnswers(): void;
565
- dispose(): void;
566
- }
534
+ /**
535
+ * assembler/run-grouping.ts — 装配行归一化与 run 窗口分组(纯函数)。
536
+ *
537
+ * 两个数据源归一化为 AsmRow:
538
+ * - page 行(RunMessage):窗口归属 runId / 真实 seq / 行级 feedback 天然在;
539
+ * - SDK live 消息(stream.messages):runId 未知 → 注入 activeRunId;seq 恒为
540
+ * MAX_SAFE_INTEGER(稳定排序下保持插入序,且排在已落库行之后——活跃 run 是最新 run)。
541
+ *
542
+ * 合并规则(无「对账动作」,只有「合并规则」——投影幂等):
543
+ * - 同 id 行 page 优先(feedback/seq 权威),live 重复行丢弃;
544
+ * - `__user` 后缀行语义按数据源区分:**page 行是后端 run-event 投影的触发输入本体**
545
+ * (实测每轮窗口的 human 行均为该形态,无无后缀原行——剔除会让 input 窗口兜底全部
546
+ * 落空),放行参与归组;live 行仍剔除(state 侧回放镜像,原行已在 page);
547
+ * - live 行在 activeRunId 为空时挂到 pendingRun.runId(metadata 未到的乐观窗口),
548
+ * 两者都缺则丢弃(无归属的孤儿行不渲染)。
549
+ */
550
+
551
+ /** 消息 id 提取(空 id 防御:无 id 行无法参与去重,直接丢弃) */
552
+ declare function rowMessageId(msg: Message): string;
553
+ /** `__user` 后缀重放行判定(resume run 窗口回放上一轮 human 的事件信封形态) */
554
+ declare function isUserEchoRow(id: string): boolean;
555
+ /**
556
+ * 归一化两个数据源并按 run 窗口分组。
557
+ * 返回 Map<runId, AsmRow[]>:桶内 seq 升序(同 seq 稳定保插入序)。
558
+ *
559
+ * @param rows page 行集合(消息层权威)
560
+ * @param liveMessages SDK 流窗口消息(活跃 run 的未落库行)
561
+ * @param activeRunId 当前活跃 run(null = 流已开但 metadata 未到)
562
+ * @param pendingRunId pending 占位 id(live 行在 activeRunId 缺失时的归属)
563
+ */
564
+ declare function groupRowsByRun(rows: readonly RunMessage[], liveMessages: readonly Message[], activeRunId: string | null, pendingRunId: string | null): Map<string, AsmRow[]>;
567
565
 
568
566
  /**
569
- * 澄清/表单块「已回答」判定(domain 层单一入口)。
570
- * 澄清类块的 status 由数据层恒置 pending(跨 run 回答态不能靠 status),三源任一命中即已回答:
571
- * ① block.status === 'completed' —— 历史/兜底路径已定稿
572
- * ② block.isAnswered —— 装饰派生从回答缓存注入的标记
573
- * ③ answers.has(block.toolCallId) —— 直接查 enrichment 回答缓存(装饰未覆盖时的兜底)
567
+ * extractors — §6.4 tool result → ExtractedPayload 提取(纯函数)。
574
568
  *
575
- * 位置判据由 hasPendingClarification 消费方组合:澄清块之后已出现新一轮
576
- * human → 视为已答(回答消息可能不在消息集合中,仅靠回答数据会永久误判待答)。
569
+ * 唯一调用点:tool 消息引用变化(diff update 命中 tool 消息)→ 回填 ToolRun.result
570
+ * 时同步写 extracted。物化器不感知业务语义——澄清卡片/报告附件的数据源在此收敛。
571
+ *
572
+ * 提取保守原则:仅识别「结果本体即携带载荷」的形态(JSON 且字段齐全);
573
+ * 报告产物例外(Bug 3):write_file result 可能是非 JSON 的 "OK" 等回执——此时
574
+ * 回退从 tool call 本身(artifact_meta / path / description,复用 parser 层
575
+ * resolveReportArtifactKind 判定)识别 report_outline / report_body,
576
+ * 产出带 sourcePath 的载荷(内容经 artifact 端点按需拉取)。
577
577
  */
578
- /** 判定所需的最小块字段集(兼容 AskClarificationBlock / FormBlock) */
579
- interface ClarificationBlockLike {
580
- status?: string;
581
- isAnswered?: boolean;
582
- toolCallId?: string;
583
- }
578
+
584
579
  /**
585
- * 判断澄清/表单块是否已回答。
586
- * @param block 澄清块(至少含 status / isAnswered / toolCallId)
587
- * @param answers enrichment 回答缓存(toolCallId → 回答内容)
580
+ * 从 tool result 提取业务载荷;无识别形态时返回 undefined(常态,消费方判空)。
581
+ *
582
+ * @param toolCallLike tool call 本体(artifact_meta + args),供 write_file result
583
+ * 非 JSON 时的报告产物回退判定(resolveReportArtifactKind 取 artifact_meta / args.path /
584
+ * args.description 三个信号);缺省时回退判定无信号,返回 undefined。
588
585
  */
589
- declare function isClarificationAnswered(block: ClarificationBlockLike | undefined | null, answers: Map<string, string>): boolean;
590
- /** 是否澄清类块(ask-clarification 专用块或 form(ask_clarification 来源)) */
591
- declare function isClarificationBlock(block: {
592
- type: string;
593
- source?: string;
594
- }): boolean;
586
+ declare function extractFromToolResult(name: string, result: string, toolCallLike?: unknown): ExtractedPayload | undefined;
595
587
 
596
- interface ViewModelState {
597
- /** 乐观组列表(ChatCore 乐观通路;human 回显后按序收敛移除) */
598
- readonly extras: GroupMessage[];
599
- /** 外部补丁(messageId → 补丁组;feedback / 报告生成中 blocks 改写) */
600
- readonly patches: Map<string, GroupMessage>;
601
- appendExtra(groups: GroupMessage[]): void;
602
- patchGroup(messageId: string, patch: Partial<GroupMessage> | ((g: GroupMessage) => GroupMessage), sourceGroups: () => GroupMessage[]): void;
603
- clearPatches(): void;
604
- /** human 回显收敛(指令消费时点调用):回显(同文本 + 当前流 runId)到达后按序移除乐观副本 */
605
- pruneExtras(decoratedGroups: readonly GroupMessage[], currentRunId?: string): void;
606
- }
607
- declare function createViewModelState(): ViewModelState;
588
+ /**
589
+ * materializer/tool-args — tool_call args 规整/补登判定(流式 args 分片场景)。
590
+ *
591
+ * 背景:tool_call_chunks 的 args 以 JSON 字符串分片增量到达,SDK 组装的消息快照
592
+ * 在 args 未拼全时即推送——首次登记 ToolRun 时 args 可能残缺(实测第二次
593
+ * ask_clarification 首次登记时只剩 clarification_type 一个键,question/fields 晚到),
594
+ * 需要「晚到的更完整 args 补登」语义(turn-machine-rules.registerToolCalls 去重命中分支)。
595
+ */
596
+ /** args 规整为对象:对象直出;字符串尝试 JSON.parse(非对象结果视为无法规整) */
597
+ declare function asArgsObject(args: unknown): Record<string, unknown> | undefined;
598
+ /**
599
+ * 新 args 是否比旧 args 更完整:是 → 返回规整后的新对象(补登用);否/无法规整 → undefined(不动)。
600
+ *
601
+ * 判据(_args 是同一 JSON 的累积分片,晚到快照是前缀的扩展_):
602
+ * - prev 无法规整(未拼全的 JSON 字符串)→ 任何可规整的 next 都更完整;
603
+ * - next 出现 prev 没有的键 → 更完整(键更多);
604
+ * - 键集合相同但序列化更长 → 更完整(args 前缀本身是合法 JSON、值被截断的场景——
605
+ * 如 `{"question":"要选哪"}` 分片补全为 `{"question":"要选哪个?"}`,旧「键更多」
606
+ * 判定会漏掉,导致截断的 question 永远留在 ToolRun.input 与澄清记录里)。
607
+ */
608
+ declare function pickRicherArgs(prev: unknown, next: unknown): Record<string, unknown> | undefined;
608
609
 
609
610
  /**
610
- * viewmodel:store 消息集合 → UI 组视图模型。
611
+ * runtime/semantic-overlay.ts — 语义覆盖层(REST 数据层「两层权威」设计的语义层)。
611
612
  *
612
- * 组派生是「带缓存的派生」:groupMemo(组级 memo)/ foldCache(L1 fold 前缀缓存)/
613
- * interruptBlocks(注入去重记忆)均为派生过程的内部状态,由 createGroupDeriver
614
- * 构建器显式持有并作为公开职责声明;唯一真状态(乐观 extras / 外部补丁,UI 指令写入)
615
- * 在 ViewModelState。缓存有意为普通结构(Map/对象)——computed 内读写不触发响应式,
616
- * 无循环风险(构建器生命周期 = derived-groups = runtime;线程切换新建 runtime 即新建缓存)。
613
+ * 职责(与消息层 page 权威互补,永不互相覆盖):
614
+ * - 权威源:/state(checkpoint),承载「仅 state 侧存在」的语义字段;
615
+ * - 提取:state.values.messages → 按消息 id 挂载的 SemanticPatch;
616
+ * - 应用:patch 回写消息副本(正文/keywords),渲染管线不感知数据源;
617
+ * - 失效:beginStream 时 invalidate——旧 checkpoint 的语义不适用于新一轮流;
618
+ * - 幂等:applyState 全量替换语义层;applySemanticPatches 多次应用零副作用。
617
619
  *
618
- * 组 status 判定:streamStatus==='streaming' 时仅最后一组 streaming,其余 completed
619
- * (旧轮次不翻回 streaming);非流式全部 completed。
620
- * blocks:流式组为空 + 预计算 streamingText(UI 直读);定稿组一次构建。
621
- */
622
-
623
- interface DeriveGroupsDeps {
624
- store: ThreadStore;
625
- enrichments: Enrichments;
626
- /** pending interrupt(values-channel 派生) */
627
- getInterrupt(): Interrupt | undefined;
628
- /** 已响应(乐观标记)interrupt id 集合 */
629
- respondedIds: Set<string>;
630
- /** 当前流 runId(乐观 human 收敛匹配用:回显消息 runId 与当前流一致,历史消息不同) */
631
- currentRunId?: string;
632
- /** 数字孪生 block 配置(缺省关闭) */
633
- twin?: BlockBuilderLiteOptions['twin'];
620
+ * 背景:重构前消息基准在 state/page 间摇摆(init 用 state 基准、流后 page 权威
621
+ * 替换把语义抹掉、再靠拉 /state 救回),合并规则散落 4 处。citation 两次断点
622
+ *(兜底守卫误判 + finalize 索引丢失致回填 update 被静默丢弃)都源于此结构。
623
+ */
624
+
625
+ /** 单条消息的语义补丁(全部可选;缺失字段不动本地消息) */
626
+ interface SemanticPatch {
627
+ /** 消息 id(对齐键) */
628
+ id: string;
629
+ /** citation 正文版本(state 侧 content,含 checkpoint 注入的 sxin-item 标签) */
630
+ content?: unknown;
631
+ /** additional_kwargs 补丁(hide_from_ui / human_input_response 等,合并缺失字段) */
632
+ additional_kwargs?: Record<string, unknown>;
634
633
  }
635
- /** 派生结果:装饰合并后的组列表 + store 源组(pruneExtras/patchGroup 消费) */
636
- interface BuildGroupsResult {
637
- /** 装饰合并后的完整组列表(UI 消费) */
638
- groups: GroupMessage[];
639
- /** store 源组(不含 extras 与补丁——二者在装饰链第 1 步才应用;供 pruneExtras 计数与 patchGroup 查找) */
640
- sourceGroups: GroupMessage[];
634
+ interface SemanticOverlay {
635
+ /** 从完整 /state 响应提取语义层(全量替换,幂等) */
636
+ applyState(state: Record<string, unknown> | null | undefined): {
637
+ patched: number;
638
+ citedIds: string[];
639
+ };
640
+ /** 当前语义补丁(只读副本) */
641
+ getPatches(): Map<string, SemanticPatch>;
642
+ /** 新流开始:语义层失效(旧 checkpoint 语义不适用于本轮流) */
643
+ invalidate(): void;
641
644
  }
642
645
  /**
643
- * 带缓存的组派生器(memo/记忆为公开职责)。
644
- * 与 state(ViewModelState)同生命周期创建;clearCache 供显式失效(测试/特例场景)。
646
+ * 从消息数组提取语义补丁(纯函数)。
647
+ * overlay.applyState 与流内 values 快照增量(finalizeAfterStream)共用同一提取规则。
645
648
  */
646
- interface GroupDeriver {
647
- derive(deps: DeriveGroupsDeps): BuildGroupsResult;
648
- clearCache(): void;
649
- }
649
+ declare function extractSemanticPatchesFromMessages(messages: Message[]): Map<string, SemanticPatch>;
650
+ /**
651
+ * 创建单线程语义覆盖层(纯数据,零 Vue)。
652
+ * patches 按 id 挂载;applyState 全量替换语义(新 checkpoint 覆盖旧语义)。
653
+ */
654
+ declare function createSemanticOverlay(): SemanticOverlay;
650
655
  /**
651
- * 创建组派生器:持有 groupMemo / foldCache / interruptBlocks 三个派生缓存
652
- * (组级 memo、L1 fold 前缀缓存、interrupt 注入去重记忆——写入幂等,仅服务派生内部)。
656
+ * 把语义补丁应用到消息数组(纯函数,新数组;入参不改)。
657
+ * 用途:init 种子——hydrate 前应用,materializer 首次构建时 hidden human 等
658
+ * 判定拿到的就是语义版消息。
659
+ * 规则:citation 正文仅当「本地不含且补丁含」时替换(幂等,普通对话零 delta);
660
+ * kwargs 只补本地缺失的键,不动已有值。
653
661
  */
654
- declare function createGroupDeriver(state: ViewModelState): GroupDeriver;
655
- /** 生成一条乐观 human GroupMessage(id 独立于服务端,回显后由 pruneExtras 收敛) */
656
- declare function createOptimisticHuman(text: string, options?: SendMessageOptions): GroupMessage;
662
+ declare function applySemanticPatches(messages: Message[], patches: ReadonlyMap<string, SemanticPatch>): Message[];
657
663
 
658
664
  /** __emit 可推进的快照字段(每次整体替换引用) */
659
665
  interface MockStreamSnapshot {
@@ -706,6 +712,8 @@ interface MockTransport extends ChatTransport {
706
712
  __setLoading(threadId: string, value: boolean): void;
707
713
  /** 注入流错误(句柄 error ref;真实泵的 error 事件路径单测在 stream-pump) */
708
714
  __setStreamError(threadId: string, err: Error): void;
715
+ /** 预置 resumeInterrupt 失败(一次性;下一次 resume 调用 reject,随后恢复成功) */
716
+ __setResumeError(threadId: string, err: Error): void;
709
717
  }
710
718
  /**
711
719
  * 内存版 ChatTransport:供 core 单测与移动端早期联调使用。
@@ -714,11 +722,11 @@ interface MockTransport extends ChatTransport {
714
722
  declare function createMockTransport(): MockTransport;
715
723
 
716
724
  /**
717
- * 公开入口:类型层 / transport 契约 / protocol 流泵 / parser 纯函数 /
718
- * domain 组与 block 构建 / runtime 运行时 / core 门面 / 测试工具。
719
- * 内部模块(store 装配、enrichments、帧泵内部)不对外导出。
725
+ * 公开入口:类型层 / transport 契约 / parser 纯函数 /
726
+ * assembler 装配层 / runtime 运行时 / core 门面 / 测试工具。
727
+ * 内部模块(store 装配、values 通道内部、rows-store)不对外导出。
720
728
  */
721
729
  /** 包版本常量,发布时由人工随 package.json 同步(changesets 只改 package.json,此处发版时核对) */
722
- declare const CORE_VERSION = "2.0.0";
730
+ declare const CORE_VERSION = "2.1.0";
723
731
 
724
- export { Block, BlockBuilderLiteOptions, BlockBuilderOptions, type BuildGroupsResult, CORE_VERSION, ChatStreamHandle, ChatTransport, CitationItem, CreateStreamOptions, DEFAULT_ASSISTANT_ID, DEFAULT_MAX_CACHED_SESSIONS, DEFAULT_MAX_CONCURRENT_STREAMS, type DeriveGroupsDeps, ElementNode, type GroupDeriver, GroupMessage, GroupMessageTool, GroupMessageType, HitlResponse, type HumanInputResponseOptions, IKwargs, INJECTED_TAGS, type InstructionSink, type KnowledgeItem, MESSAGE_TYPE_NORMALIZE, MessageTokenUsage, MessagesPage, type MockStreamSnapshot, type MockTransport, type MockTransportCalls, OUTLINE_MAX_LEVEL, OutlineChapter, OutlineSubChapter, ReportBodyPayload, ReportOutlinePayload, RunInfo, RunMessage, type RunStreamPayload, SendMessageOptions, type StreamEvent, type StreamEventSource, StreamSubmitInput, StreamSubmitOptions, type SxinMessage, SxinNode, type ThreadInfo, ThreadInitialValues, type ThreadInstruction, ThreadTokenUsage, type ViewModelState, buildAiGroup, buildArtifactFiles, buildHumanGroup, buildHumanInputResponse, buildReportBodyPayload, buildReportOutlinePayload, collectTextKeepSxin, collectVisibleText, createEmptySubChapter, createGroupDeriver, createMockTransport, createOptimisticHuman, createStreamPump, createViewModelState, deriveToolsFromMessages, ensureOutlineContentThemes, ensureRunningRun, extractAiContentFromMessage, extractBlocksFromContent, extractBlocksFromNodes, extractCitationAnchors, extractCitationAnchorsFromSpec, extractReportTitleFromBody, extractRunEnrichment, extractStateMessages, extractTextFromMessage, extractThreadInfo, extractTitleFromArtifactPath, extractUserMessageTexts, foldMessages, formatStr, genBlockId, genMessageId, getHumanMessageBaseId, getToolCallArtifactMeta, isAiMessage, isClarificationAnswered, isClarificationBlock, isHiddenUserMessage, isHumanMessage, isInjectedElement, isReportBodyHtml, isToolMessage, isVisibleUserMessage, isWriteFileToolName, normalizeMessageType, normalizeOutline, normalizeUsage, parseHumanMessageId, parseKnowledgeItemsFromValue, parseMarkdownToOutline, readMessageContentText, resolveReportArtifactKind, runMessagesToMessages, simpleHash, stateMessagesToRunMessages, toRunMessage, tokenizeSxin, validateOutline };
732
+ export { AsmRow, Block, BlockBuilderOptions, CORE_VERSION, ChatTransport, CitationItem, type CommentNode, CreateStreamOptions, DEFAULT_ASSISTANT_ID, DEFAULT_MAX_CACHED_SESSIONS, DEFAULT_MAX_CONCURRENT_STREAMS, type ElementNode, ExtractedPayload, GroupMessageTool, HitlResponse, type HumanInputResponseOptions, IKwargs, INJECTED_TAGS, type KnowledgeItem, MESSAGE_TYPE_NORMALIZE, MessageTokenUsage, MessagesPage, type MockStreamSnapshot, type MockTransport, type MockTransportCalls, OUTLINE_MAX_LEVEL, OutlineChapter, OutlineSubChapter, ProjectRunsInput, ReportBodyPayload, ReportOutlinePayload, RunInfo, RunItem, RunMessage, RunStatus, type SemanticOverlay, type SemanticPatch, StreamSubmitInput, StreamSubmitOptions, type SxinMessage, type SxinNode, type TextNode, type ThreadInfo, ThreadInitialValues, ThreadTokenUsage, applySemanticPatches, asArgsObject, assembleRun, backfillRunMessageFeedback, buildArtifactFiles, buildHumanInputResponse, buildReportBodyPayload, buildReportOutlinePayload, collectTextKeepSxin, collectVisibleText, createEmptySubChapter, createMockTransport, createSemanticOverlay, deriveToolsFromMessages, emptyRunItem, ensureOutlineContentThemes, ensureRunningRun, extractAiContentFromMessage, extractBlocksFromContent, extractBlocksFromNodes, extractCitationAnchors, extractCitationAnchorsFromSpec, extractFromToolResult, extractInputFromRows, extractReportTitleFromBody, extractRunEnrichment, extractSemanticPatchesFromMessages, extractStateMessages, extractTextFromMessage, extractThreadInfo, extractTitleFromArtifactPath, extractUserMessageTexts, formatAnswerText, formatStr, genBlockId, genMessageId, getHumanMessageBaseId, getToolCallArtifactMeta, groupRowsByRun, isAiMessage, isHiddenUserMessage, isHumanMessage, isInjectedElement, isReportBodyHtml, isToolMessage, isUserEchoRow, isVisibleUserMessage, isWriteFileToolName, mapBackendStatus, mergeStateWithPageMessages, normalizeMessageType, normalizeOutline, normalizeUsage, parseHumanMessageId, parseKnowledgeItemsFromValue, parseMarkdownToOutline, pickRicherArgs, projectRuns, readMessageContentText, resolveReportArtifactKind, rowMessageId, runMessagesToMessages, simpleHash, stateMessagesToRunMessages, toRunMessage, tokenizeSxin, validateOutline };