@cqfe/sxin-chat-core 1.0.1 → 1.0.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/dist/index.cjs CHANGED
@@ -3,6 +3,9 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __typeError = (msg) => {
7
+ throw TypeError(msg);
8
+ };
6
9
  var __export = (target, all) => {
7
10
  for (var name in all)
8
11
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -16,6 +19,10 @@ var __copyProps = (to, from, except, desc) => {
16
19
  return to;
17
20
  };
18
21
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
23
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
24
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
25
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
19
26
 
20
27
  // src/index.ts
21
28
  var src_exports = {};
@@ -24,18 +31,18 @@ __export(src_exports, {
24
31
  DEFAULT_ASSISTANT_ID: () => DEFAULT_ASSISTANT_ID,
25
32
  DEFAULT_MAX_CACHED_SESSIONS: () => DEFAULT_MAX_CACHED_SESSIONS,
26
33
  DEFAULT_MAX_CONCURRENT_STREAMS: () => DEFAULT_MAX_CONCURRENT_STREAMS,
27
- DEFAULT_TWIN_TOOL_PREFIX: () => DEFAULT_TWIN_TOOL_PREFIX,
34
+ DeerFlowBridgeAdapter: () => DeerFlowBridgeAdapter,
28
35
  INJECTED_TAGS: () => INJECTED_TAGS,
29
36
  MESSAGE_TYPE_NORMALIZE: () => MESSAGE_TYPE_NORMALIZE,
30
37
  OUTLINE_MAX_LEVEL: () => OUTLINE_MAX_LEVEL,
31
38
  ThreadDirectory: () => ThreadDirectory,
32
- buildAiGroup: () => buildAiGroup,
39
+ V1FrameTranslator: () => V1FrameTranslator,
40
+ applySemanticPatches: () => applySemanticPatches,
41
+ backfillRunMessageFeedback: () => backfillRunMessageFeedback,
33
42
  buildArtifactFiles: () => buildArtifactFiles,
34
43
  buildHitlDecisions: () => buildHitlDecisions,
35
- buildHumanGroup: () => buildHumanGroup,
36
44
  buildHumanInputResponse: () => buildHumanInputResponse,
37
45
  buildInterruptReviewBlock: () => buildInterruptReviewBlock,
38
- buildInterruptReviewGroup: () => buildInterruptReviewGroup,
39
46
  buildRejectDecisions: () => buildRejectDecisions,
40
47
  buildReportBodyPayload: () => buildReportBodyPayload,
41
48
  buildReportOutlinePayload: () => buildReportOutlinePayload,
@@ -43,15 +50,16 @@ __export(src_exports, {
43
50
  buildRunInfo: () => buildRunInfo,
44
51
  collectTextKeepSxin: () => collectTextKeepSxin,
45
52
  collectVisibleText: () => collectVisibleText,
46
- createBlockBuilderLite: () => createBlockBuilderLite,
47
53
  createChatCore: () => createChatCore,
48
54
  createEmptySubChapter: () => createEmptySubChapter,
49
- createGroupDeriver: () => createGroupDeriver,
55
+ createEventHub: () => createEventHub,
56
+ createFetchReaderFactory: () => createFetchReaderFactory,
57
+ createMaterializer: () => createMaterializer,
58
+ createMessageDiff: () => createMessageDiff,
50
59
  createMockTransport: () => createMockTransport,
51
- createOptimisticHuman: () => createOptimisticHuman,
52
- createStreamPump: () => createStreamPump,
60
+ createRuntimeMaterializer: () => createRuntimeMaterializer,
61
+ createSemanticOverlay: () => createSemanticOverlay,
53
62
  createThreadRuntime: () => createThreadRuntime,
54
- createViewModelState: () => createViewModelState,
55
63
  deriveToolsFromMessages: () => deriveToolsFromMessages,
56
64
  ensureOutlineContentThemes: () => ensureOutlineContentThemes,
57
65
  ensureRunningRun: () => ensureRunningRun,
@@ -60,14 +68,17 @@ __export(src_exports, {
60
68
  extractBlocksFromNodes: () => extractBlocksFromNodes,
61
69
  extractCitationAnchors: () => extractCitationAnchors,
62
70
  extractCitationAnchorsFromSpec: () => extractCitationAnchorsFromSpec,
71
+ extractFromToolResult: () => extractFromToolResult,
63
72
  extractReportTitleFromBody: () => extractReportTitleFromBody,
64
73
  extractRunEnrichment: () => extractRunEnrichment,
74
+ extractSemanticPatchesFromMessages: () => extractSemanticPatchesFromMessages,
65
75
  extractStateMessages: () => extractStateMessages,
66
76
  extractTextFromMessage: () => extractTextFromMessage,
67
77
  extractThreadInfo: () => extractThreadInfo,
68
78
  extractTitleFromArtifactPath: () => extractTitleFromArtifactPath,
69
79
  extractUserMessageTexts: () => extractUserMessageTexts,
70
- foldMessages: () => foldMessages,
80
+ fetchAllPageMessages: () => fetchAllPageMessages,
81
+ formatAnswerText: () => formatAnswerText,
71
82
  formatStr: () => formatStr,
72
83
  genBlockId: () => genBlockId,
73
84
  genMessageId: () => genMessageId,
@@ -75,8 +86,6 @@ __export(src_exports, {
75
86
  getHumanMessageBaseId: () => getHumanMessageBaseId,
76
87
  getToolCallArtifactMeta: () => getToolCallArtifactMeta,
77
88
  isAiMessage: () => isAiMessage,
78
- isClarificationAnswered: () => isClarificationAnswered,
79
- isClarificationBlock: () => isClarificationBlock,
80
89
  isHiddenUserMessage: () => isHiddenUserMessage,
81
90
  isHumanMessage: () => isHumanMessage,
82
91
  isInjectedElement: () => isInjectedElement,
@@ -85,6 +94,7 @@ __export(src_exports, {
85
94
  isToolMessage: () => isToolMessage,
86
95
  isVisibleUserMessage: () => isVisibleUserMessage,
87
96
  isWriteFileToolName: () => isWriteFileToolName,
97
+ mergeStateWithPageMessages: () => mergeStateWithPageMessages,
88
98
  normalizeForCompare: () => normalizeForCompare,
89
99
  normalizeMessageType: () => normalizeMessageType,
90
100
  normalizeOutline: () => normalizeOutline,
@@ -93,11 +103,13 @@ __export(src_exports, {
93
103
  parseHumanMessageId: () => parseHumanMessageId,
94
104
  parseKnowledgeItemsFromValue: () => parseKnowledgeItemsFromValue,
95
105
  parseMarkdownToOutline: () => parseMarkdownToOutline,
106
+ parseSseFrames: () => parseSseFrames,
96
107
  pickRunMessageMetadata: () => pickRunMessageMetadata,
97
108
  readMessageContentText: () => readMessageContentText,
98
109
  resolveReportArtifactKind: () => resolveReportArtifactKind,
99
110
  runMessagesToMessages: () => runMessagesToMessages,
100
111
  simpleHash: () => simpleHash,
112
+ sliceBodySegments: () => sliceBodySegments,
101
113
  stateMessagesToRunMessages: () => stateMessagesToRunMessages,
102
114
  toRunMessage: () => toRunMessage,
103
115
  tokenizeSxin: () => tokenizeSxin,
@@ -110,117 +122,6 @@ var DEFAULT_MAX_CACHED_SESSIONS = 10;
110
122
  var DEFAULT_MAX_CONCURRENT_STREAMS = 3;
111
123
  var DEFAULT_ASSISTANT_ID = "lead_agent";
112
124
 
113
- // src/protocol/stream-pump.ts
114
- var import_vue = require("vue");
115
- var import_langgraph_sdk = require("@langchain/langgraph-sdk");
116
- var STREAM_MODE = ["values", "messages-tuple"];
117
- function isSilentStreamError(e) {
118
- return e instanceof Error && (e.name === "AbortError" || e.name === "TimeoutError");
119
- }
120
- function createStreamPump(source, options) {
121
- const isLoading = (0, import_vue.ref)(false);
122
- const error = (0, import_vue.ref)(null);
123
- let queue = Promise.resolve();
124
- let currentController = null;
125
- const runStream = async (open) => {
126
- const controller = new AbortController();
127
- currentController = controller;
128
- try {
129
- isLoading.value = true;
130
- error.value = null;
131
- options.onStreamStart?.();
132
- for await (const { event, data } of open(controller.signal)) {
133
- if (event === "error") throw new import_langgraph_sdk.StreamError(data);
134
- if (event === "metadata") {
135
- options.onMetadataEvent?.(data);
136
- continue;
137
- }
138
- if (event === "values" || event.startsWith("values|")) {
139
- if (event.includes("|")) continue;
140
- options.onValuesEvent?.(data);
141
- continue;
142
- }
143
- if (event === "messages" || event === "messages-tuple" || event.startsWith("messages|")) {
144
- if (event.includes("|")) continue;
145
- const [serialized, metadata] = Array.isArray(data) ? data : [];
146
- options.onMessageTupleEvent?.(serialized, metadata);
147
- continue;
148
- }
149
- }
150
- } catch (e) {
151
- if (!isSilentStreamError(e)) {
152
- error.value = e;
153
- try {
154
- await options.onError?.(e);
155
- } catch {
156
- }
157
- }
158
- } finally {
159
- try {
160
- await options.onStreamEnd?.();
161
- } catch {
162
- }
163
- isLoading.value = false;
164
- if (currentController === controller) currentController = null;
165
- try {
166
- await options.onFinish?.();
167
- } catch {
168
- }
169
- }
170
- };
171
- const start = (open, startOptions) => {
172
- if (startOptions?.abortPrevious) currentController?.abort();
173
- const queued = queue.then(() => runStream(open));
174
- queue = queued;
175
- return queued;
176
- };
177
- return {
178
- isLoading,
179
- error,
180
- /** 发起一次流式运行(发送用户消息);fire-and-forget(与现网 useThreadStream 一致) */
181
- submit(input, submitOptions) {
182
- void start(
183
- (signal) => source.openRunStream(
184
- {
185
- input,
186
- ...submitOptions,
187
- streamMode: STREAM_MODE,
188
- // sdk client 在 run 创建时回调;透传给 CreateStreamOptions.onCreated
189
- onRunCreated: (params) => options.onCreated?.(params)
190
- },
191
- signal
192
- ),
193
- { abortPrevious: true }
194
- );
195
- },
196
- /** 加入既有 run 的 SSE 流(断线重连);await 至流结束 */
197
- joinStream(runId, lastEventId) {
198
- return start((signal) => source.openJoinStream(runId, lastEventId ?? "-1", signal), { abortPrevious: true });
199
- },
200
- /** 停止当前流(本地 abort,不取消服务端 run) */
201
- stop() {
202
- currentController?.abort();
203
- },
204
- /** 恢复 pending interrupt:发送 HITL 决策(Command(resume)),与 joinStream 的 SSE 重连语义不同;await 至流结束 */
205
- resumeInterrupt(decisions) {
206
- return start(
207
- (signal) => source.openRunStream(
208
- {
209
- input: null,
210
- command: { resume: decisions },
211
- onDisconnect: "continue",
212
- config: { recursion_limit: 1e3 },
213
- streamMode: STREAM_MODE,
214
- onRunCreated: (params) => options.onCreated?.(params)
215
- },
216
- signal
217
- ),
218
- { abortPrevious: true }
219
- );
220
- }
221
- };
222
- }
223
-
224
125
  // src/parser/sxin-ast-attrs.ts
225
126
  function formatStr(str) {
226
127
  if (!str) return str;
@@ -757,24 +658,24 @@ function buildInterruptReviewBlock(interrupt, responded) {
757
658
  interruptId
758
659
  };
759
660
  }
760
- function buildInterruptReviewGroup(interrupt, responded) {
761
- const block = buildInterruptReviewBlock(interrupt, responded);
762
- if (!block) return null;
763
- return {
764
- id: `interrupt-${block.interruptId}`,
765
- type: "ai",
766
- status: block.status,
767
- source: "state",
768
- originMessageIds: [],
769
- blocks: [block],
770
- toolIds: [],
771
- tools: [],
772
- rawMessages: [],
773
- createdAt: Date.now()
774
- };
775
- }
776
661
 
777
662
  // src/parser/thread-info.ts
663
+ function formatAnswerText(value) {
664
+ if (value == null) return "";
665
+ if (typeof value === "string") return value;
666
+ if (typeof value === "object") {
667
+ const values = value.values;
668
+ if (values && typeof values === "object" && !Array.isArray(values)) {
669
+ return Object.values(values).filter((v) => v !== void 0 && v !== null && v !== "").map(String).join("; ");
670
+ }
671
+ try {
672
+ return JSON.stringify(value);
673
+ } catch {
674
+ return String(value);
675
+ }
676
+ }
677
+ return String(value);
678
+ }
778
679
  var humanInputResponseRule = {
779
680
  key: "clarificationAnswers",
780
681
  extract(msg, acc) {
@@ -782,7 +683,7 @@ var humanInputResponseRule = {
782
683
  const response = additionalKwargs?.human_input_response;
783
684
  const requestId = String(response?.request_id || "").trim().replace("clarification:", "");
784
685
  if (requestId && response?.value !== void 0) {
785
- acc.clarificationAnswers.set(requestId, String(response.value));
686
+ acc.clarificationAnswers.set(requestId, formatAnswerText(response.value));
786
687
  }
787
688
  }
788
689
  };
@@ -818,6 +719,62 @@ function extractStateMessages(state) {
818
719
  const messages = values.messages;
819
720
  return Array.isArray(messages) ? messages : [];
820
721
  }
722
+ function mergeStateWithPageMessages(stateMessages, pageMessages) {
723
+ if (!pageMessages.length) return stateMessages;
724
+ if (!stateMessages.length) return pageMessages;
725
+ const locateId = (m) => String(m?.id || m?.tool_call_id || "").trim();
726
+ const pageIndex = /* @__PURE__ */ new Map();
727
+ pageMessages.forEach((m, i) => {
728
+ const id = locateId(m);
729
+ if (id && !pageIndex.has(id)) pageIndex.set(id, i);
730
+ });
731
+ let anchorSi = -1;
732
+ let anchorPi = -1;
733
+ for (let si = 0; si < stateMessages.length; si++) {
734
+ const id = locateId(stateMessages[si]);
735
+ const pi = id ? pageIndex.get(id) : void 0;
736
+ if (pi !== void 0) {
737
+ anchorSi = si;
738
+ anchorPi = pi;
739
+ break;
740
+ }
741
+ }
742
+ if (anchorSi < 0) return pageMessages;
743
+ const stateIds = /* @__PURE__ */ new Set();
744
+ for (const m of stateMessages) {
745
+ const id = String(m?.id || "").trim();
746
+ const callId = String(m?.tool_call_id || "").trim();
747
+ if (id) stateIds.add(id);
748
+ if (callId) stateIds.add(callId);
749
+ }
750
+ const headExtras = [];
751
+ for (let pi = 0; pi < anchorPi; pi++) {
752
+ const m = pageMessages[pi];
753
+ const id = locateId(m);
754
+ if (id && !stateIds.has(id)) headExtras.push(m);
755
+ }
756
+ const tailExtras = [];
757
+ for (let pi = anchorPi + 1; pi < pageMessages.length; pi++) {
758
+ const m = pageMessages[pi];
759
+ const id = locateId(m);
760
+ if (id && !stateIds.has(id)) tailExtras.push(m);
761
+ }
762
+ const runIdById = /* @__PURE__ */ new Map();
763
+ for (const m of pageMessages) {
764
+ const id = String(m?.id || "").trim();
765
+ const rid = String(m?.runId || "").trim();
766
+ if (id && rid && !runIdById.has(id)) runIdById.set(id, rid);
767
+ }
768
+ const stampRunId = (m) => {
769
+ const id = String(m?.id || "").trim();
770
+ if (!id) return m;
771
+ const rid = runIdById.get(id);
772
+ if (!rid) return m;
773
+ if (String(m?.runId || "").trim() || String(m?.additional_kwargs?.run_id || "").trim()) return m;
774
+ return { ...m, runId: rid };
775
+ };
776
+ return [...headExtras, ...stateMessages.map(stampRunId), ...tailExtras];
777
+ }
821
778
  function ensureRunningRun(runMap, runId, threadId) {
822
779
  let runInfo = runMap.get(runId);
823
780
  if (!runInfo) {
@@ -831,7 +788,7 @@ function ensureRunningRun(runMap, runId, threadId) {
831
788
  return runInfo;
832
789
  }
833
790
 
834
- // src/types/sxin-message.ts
791
+ // src/parser/sxin-message.ts
835
792
  var asSxin = (m) => m ?? {};
836
793
 
837
794
  // src/parser/run-messages.ts
@@ -906,6 +863,23 @@ function extractRunEnrichment(messages) {
906
863
  }
907
864
  return map;
908
865
  }
866
+ function backfillRunMessageFeedback(source, target) {
867
+ if (!source.length || !target.length) return target;
868
+ const feedbackById = /* @__PURE__ */ new Map();
869
+ for (const row of source) {
870
+ const id = String(row?.content?.id || "").trim();
871
+ if (!id || row?.feedback === void 0 || row?.feedback === null) continue;
872
+ feedbackById.set(id, row.feedback);
873
+ }
874
+ if (!feedbackById.size) return target;
875
+ return target.map((row) => {
876
+ const id = String(row?.content?.id || "").trim();
877
+ if (!id) return row;
878
+ const feedback = feedbackById.get(id);
879
+ if (feedback === void 0 || row.feedback !== void 0) return row;
880
+ return { ...row, feedback };
881
+ });
882
+ }
909
883
  function runMessagesToMessages(messages) {
910
884
  return messages.map((msg) => {
911
885
  const normalized = normalizeMessageType({ ...asSxin(msg.content) });
@@ -959,6 +933,9 @@ function readMessageContentText(msg) {
959
933
  if (!read) return "";
960
934
  return read.trim ? read.text.trim() : read.text;
961
935
  }
936
+ function hasKbCitationMessage(msg) {
937
+ return readMessageContentText(msg).includes("support.kbCitation");
938
+ }
962
939
  function extractTextFromMessage(msg) {
963
940
  const read = readMessageText(msg);
964
941
  if (!read) return "";
@@ -1462,14 +1439,60 @@ function applyUsageDetails(usage, r) {
1462
1439
  }
1463
1440
  }
1464
1441
 
1465
- // src/message/run-info.ts
1442
+ // src/parser/body-segments.ts
1443
+ var SEGMENT_TAGS = /* @__PURE__ */ new Set(["sxin-list", "sxin-item"]);
1444
+ function visibleTextOf(node) {
1445
+ if (node.type === "text") return node.value;
1446
+ if (node.type === "comment") return "";
1447
+ return node.children.map(visibleTextOf).join("");
1448
+ }
1449
+ function toItemSegment(el, source) {
1450
+ return {
1451
+ type: "item",
1452
+ tag: "sxin-item",
1453
+ attrs: { ...el.attrs },
1454
+ content: visibleTextOf(el) || void 0,
1455
+ raw: source.slice(el.start, el.end)
1456
+ };
1457
+ }
1458
+ function toListSegment(el, source) {
1459
+ const children = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-item").map((c) => toItemSegment(c, source));
1460
+ return { type: "list", tag: "sxin-list", attrs: { ...el.attrs }, children, raw: source.slice(el.start, el.end) };
1461
+ }
1462
+ function sliceBodySegments(body) {
1463
+ const source = String(body ?? "");
1464
+ const segments = [];
1465
+ let textBuf = "";
1466
+ const flushText = () => {
1467
+ if (!textBuf) return;
1468
+ segments.push({ type: "text", content: textBuf });
1469
+ textBuf = "";
1470
+ };
1471
+ for (const node of tokenizeSxin(source)) {
1472
+ if (node.type === "element" && SEGMENT_TAGS.has(node.tagName)) {
1473
+ flushText();
1474
+ segments.push(node.tagName === "sxin-list" ? toListSegment(node, source) : toItemSegment(node, source));
1475
+ } else if (node.type === "comment") {
1476
+ continue;
1477
+ } else if (node.type === "text") {
1478
+ textBuf += node.value;
1479
+ } else {
1480
+ textBuf += source.slice(node.start, node.end);
1481
+ }
1482
+ }
1483
+ flushText();
1484
+ if (!segments.length) segments.push({ type: "text", content: "" });
1485
+ return segments;
1486
+ }
1487
+
1488
+ // src/runtime/run-info.ts
1466
1489
  function buildRunInfo(run, threadId) {
1467
1490
  return {
1468
1491
  runId: String(run?.run_id || "").trim(),
1469
1492
  threadId: String(threadId || "").trim(),
1470
1493
  usage: buildRunUsage(run),
1471
1494
  latencyMs: buildRunLatencyMs(run),
1472
- finishReason: toOptionalString(run?.finish_reason),
1495
+ finishReason: toOptionalString(run?.stop_reason ?? run?.finish_reason),
1473
1496
  modelName: toOptionalString(run?.model_name),
1474
1497
  status: buildRunStatus(run),
1475
1498
  createdAt: buildRunCreatedAt(run)
@@ -1525,931 +1548,87 @@ function pickRunMessageMetadata(messages) {
1525
1548
  return { modelName, finishReason };
1526
1549
  }
1527
1550
 
1528
- // src/domain/block-builder.ts
1529
- var DEFAULT_TWIN_TOOL_PREFIX = "city-digital-twin-display_";
1530
- function createBlockBuilderLite(options) {
1531
- const source = options.source;
1532
- const isStreaming = !!options.isStreaming;
1533
- const createdAt = Number.isFinite(options.createdAt) ? Number(options.createdAt) : Date.now();
1534
- const twinEnabled = !!options.twin?.enabled;
1535
- const twinToolPrefix = options.twin?.toolPrefix || DEFAULT_TWIN_TOOL_PREFIX;
1536
- const presentFilesSet = /* @__PURE__ */ new Set();
1537
- const writeFilesSet = /* @__PURE__ */ new Set();
1538
- const toolParsers = /* @__PURE__ */ new Map();
1539
- const registerParser = (names, parser) => {
1540
- for (const name of Array.isArray(names) ? names : [names]) {
1541
- toolParsers.set(name, parser);
1542
- }
1543
- };
1544
- const parseBlockTool = (tool, status) => {
1545
- const name = String(tool.call?.name || "").trim();
1546
- const parser = toolParsers.get(name);
1547
- return parser ? parser(tool, status) : [];
1548
- };
1549
- const parseAskClarification = (tool, _status) => {
1550
- const args = tool.call?.args || {};
1551
- return [
1552
- {
1553
- id: genBlockId(),
1554
- type: "ask-clarification",
1555
- context: args.context,
1556
- question: args.question,
1557
- clarification_type: args.clarification_type,
1558
- options: Array.isArray(args.options) ? args.options : void 0,
1559
- fields: Array.isArray(args.fields) ? args.fields : void 0,
1560
- // clarification 的回答是跨 run 的,不能根据 streaming/source 判断状态,统一 pending,由渲染层结合 thread 级回答状态决定
1561
- status: "pending",
1562
- toolCallId: tool.id
1563
- }
1564
- ];
1565
- };
1566
- const parseFormBlock = (tool, status, sourceTag) => {
1567
- const args = tool.call?.args || {};
1568
- const variant = String(args.variant || "input");
1569
- const blockStatus = sourceTag === "ask_clarification" ? "pending" : status;
1570
- return [
1571
- {
1572
- id: genBlockId(),
1573
- type: "form",
1574
- variant: ["input", "confirm", "delete_confirm"].includes(variant) ? variant : "input",
1575
- title: args.title,
1576
- question: args.question,
1577
- context: args.context,
1578
- fields: Array.isArray(args.fields) ? args.fields : [],
1579
- values: args.values || {},
1580
- stepInfo: args.stepInfo,
1581
- customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
1582
- status: blockStatus,
1583
- toolCallId: tool.id,
1584
- source: sourceTag
1585
- }
1586
- ];
1587
- };
1588
- const parseListBlock = (tool, status) => {
1589
- const args = tool.call?.args || {};
1590
- const mode = String(args.mode || "select");
1591
- return [
1592
- {
1593
- id: genBlockId(),
1594
- type: "list",
1595
- mode: ["select", "view"].includes(mode) ? mode : "select",
1596
- title: args.title,
1597
- dataSource: args.dataSource,
1598
- items: Array.isArray(args.items) ? args.items : void 0,
1599
- queryParams: args.queryParams,
1600
- pagination: args.pagination,
1601
- selectMode: args.selectMode || "single",
1602
- customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
1603
- status,
1604
- toolCallId: tool.id
1605
- }
1606
- ];
1607
- };
1608
- const parsePresentFiles = (tool, status) => {
1609
- const args = tool.call?.args || {};
1610
- const filepaths = Array.isArray(args?.filepaths) ? args.filepaths : [];
1611
- if (!filepaths.length) return [];
1612
- const paths = [];
1613
- for (const path of filepaths) {
1614
- if (presentFilesSet.has(path)) continue;
1615
- presentFilesSet.add(path);
1616
- paths.push(path);
1617
- }
1618
- if (!paths.length) return [];
1619
- return [
1620
- {
1621
- id: genBlockId(),
1622
- type: "artifact",
1623
- files: buildArtifactFiles(paths),
1624
- status
1625
- }
1626
- ];
1627
- };
1628
- const resolveWriteFileContext = (tool) => {
1629
- const meta = getToolCallArtifactMeta(tool.call);
1630
- const args = tool.call?.args || {};
1631
- const artifactPath = String(meta?.path || args.path || "").trim();
1632
- const content = String(args.content || tool.result?.content || "").trim();
1633
- const description = String(args.description || "").trim();
1634
- const blockId = tool.id || artifactPath || `report-${Date.now()}`;
1635
- const toolCreatedAt = Number(new Date(asSxin(tool.aiMessage).created_at || ""));
1636
- const toolTime = Number.isFinite(toolCreatedAt) ? toolCreatedAt : createdAt;
1637
- if (!content && source === "sse") return null;
1638
- if (writeFilesSet.has(artifactPath)) return null;
1639
- writeFilesSet.add(artifactPath);
1640
- presentFilesSet.add(artifactPath);
1641
- return { artifactPath, content, description, blockId, createdAt: toolTime };
1642
- };
1643
- const buildReportBlock = (kind, ctx, status) => {
1644
- const isOutline = kind === "report_outline";
1645
- const fallbackName = extractTitleFromArtifactPath(ctx.artifactPath, kind) || ctx.description.replace(isOutline ? /生成|大纲/g : /生成|正文|报告/g, "").trim() || "\u62A5\u544A";
1646
- const isState = source === "state";
1647
- const payloadInput = {
1648
- templateId: ctx.blockId,
1649
- fallbackName,
1650
- sourcePath: ctx.artifactPath || void 0,
1651
- content: isState ? void 0 : ctx.content || void 0,
1652
- contentRef: isState && ctx.artifactPath ? { path: ctx.artifactPath } : void 0,
1653
- createdAt: ctx.createdAt
1654
- };
1655
- return isOutline ? { id: genBlockId(), type: "report-outline", payload: buildReportOutlinePayload(payloadInput), status } : { id: genBlockId(), type: "report-body", payload: buildReportBodyPayload(payloadInput), status };
1656
- };
1657
- const parseWriteFile = (tool, status) => {
1658
- const name = String(tool.call?.name || "").trim();
1659
- if (!isWriteFileToolName(name)) return [];
1660
- const kind = resolveReportArtifactKind(tool.call);
1661
- if (!kind) return [];
1662
- const ctx = resolveWriteFileContext(tool);
1663
- if (!ctx) return [];
1664
- const block = buildReportBlock(kind, ctx, status);
1665
- return block ? [block] : [];
1666
- };
1667
- const parseClarification = (tool, status) => {
1668
- const args = tool.call?.args || {};
1669
- if (args.variant || args.fields?.length) {
1670
- return parseFormBlock(tool, status, "ask_clarification");
1671
- }
1672
- return parseAskClarification(tool, status);
1673
- };
1674
- registerParser("ask_clarification", parseClarification);
1675
- registerParser(
1676
- ["confirm_form", "form"],
1677
- (tool, status) => parseFormBlock(tool, status, String(tool.call?.name || "").trim())
1678
- );
1679
- registerParser(["list_and_select", "list"], parseListBlock);
1680
- registerParser("present_files", parsePresentFiles);
1681
- registerParser(["write_file", "write_files"], parseWriteFile);
1682
- const buildFromNodes = (nodes, rawText, tools) => {
1683
- const blocks = [];
1684
- const status = isStreaming ? "streaming" : "completed";
1685
- const contentSource = source === "state" ? "history" : source;
1686
- const { blocks: contentBlocks } = extractBlocksFromNodes(nodes, rawText, contentSource);
1687
- blocks.push(...contentBlocks);
1688
- for (const tool of tools) {
1689
- const toolBlocks = parseBlockTool(tool, status);
1690
- blocks.push(...toolBlocks);
1691
- }
1692
- if (twinEnabled) {
1693
- const twinTool = tools.reverse().find((_) => _.call?.name.includes(twinToolPrefix));
1694
- if (twinTool) {
1695
- blocks.push({
1696
- id: genBlockId(),
1697
- type: "twin",
1698
- toolName: twinTool.call.name.replace(twinToolPrefix, ""),
1699
- args: twinTool.call.args
1700
- });
1701
- }
1702
- }
1703
- return blocks;
1704
- };
1705
- const build = (content, tools) => buildFromNodes(tokenizeSxin(content), content, tools);
1706
- return { build, buildFromNodes };
1707
- }
1708
-
1709
- // src/domain/fold.ts
1710
- function messageRunId(msg) {
1711
- const own = String(asSxin(msg).runId || "").trim();
1712
- if (own) return own;
1713
- return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
1714
- }
1715
- function foldMessages(target, flush) {
1716
- let type = null;
1717
- let buf = [];
1718
- let groupRunId;
1719
- const doFlush = () => {
1720
- if (!buf.length || !type) return;
1721
- flush(type, buf);
1722
- buf = [];
1723
- };
1724
- for (const m of target) {
1725
- if (isHumanMessage(m)) {
1726
- if (!(type === "human" && buf.length && getHumanMessageBaseId(String(asSxin(m).id || "")) === getHumanMessageBaseId(String(asSxin(buf[0]).id || ""))))
1727
- doFlush();
1728
- type = "human";
1729
- buf.push(m);
1730
- } else if (isAiMessage(m) || isToolMessage(m)) {
1731
- const mRunId = messageRunId(m);
1732
- if (type !== "ai" || mRunId && groupRunId && mRunId !== groupRunId) doFlush();
1733
- if (!buf.length) groupRunId = mRunId;
1734
- type = "ai";
1735
- buf.push(m);
1736
- }
1737
- }
1738
- doFlush();
1739
- }
1740
-
1741
- // src/domain/group-materializer.ts
1742
- function readCreatedAt(msg) {
1743
- return Number(new Date(asSxin(msg).created_at || Date.now())) || Date.now();
1744
- }
1745
- function buildHumanGroup(messages, status) {
1746
- const representative = messages.find(
1747
- (m) => parseHumanMessageId(String(asSxin(m).id || "")).variant === "user" && isVisibleUserMessage(m)
1748
- ) || messages.find((m) => isVisibleUserMessage(m)) || messages[0];
1749
- const firstId = messages.find((_) => _.id)?.id || genMessageId();
1750
- const additionalKwargs = asSxin(representative).additional_kwargs;
1751
- const texts = extractUserMessageTexts(messages);
1752
- const runId = messageRunId(representative);
1753
- return {
1754
- id: firstId,
1755
- type: "human",
1756
- status,
1757
- originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
1758
- runId,
1759
- rawMessages: messages,
1760
- texts,
1761
- additionalKwargs,
1762
- blocks: [],
1763
- toolIds: [],
1764
- tools: [],
1765
- createdAt: readCreatedAt(representative)
1766
- };
1767
- }
1768
- function buildAiGroup(messages, options, twin) {
1769
- const firstId = messages.find((_) => _.id)?.id || genMessageId();
1770
- const groupTools = deriveToolsFromMessages(messages);
1771
- const aiMessages = messages.filter(isAiMessage);
1772
- const lastAi = aiMessages[aiMessages.length - 1] || messages[messages.length - 1];
1773
- const content = readMessageContentText(lastAi);
1774
- const createdAt = readCreatedAt(messages[0]);
1775
- const blocks = options.isStreaming ? [] : createBlockBuilderLite({ source: options.source, twin, createdAt }).buildFromNodes(
1776
- tokenizeSxin(content),
1777
- content,
1778
- groupTools
1779
- );
1780
- const anchors = extractCitationAnchors(blocks);
1781
- const citations = anchors.length ? anchors : void 0;
1782
- return {
1783
- id: firstId,
1784
- type: "ai",
1785
- status: options.isStreaming ? "streaming" : "completed",
1786
- originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
1787
- runId: messageRunId(lastAi) || options.runId,
1788
- rawMessages: messages,
1789
- blocks,
1790
- citations,
1791
- toolIds: groupTools.map((t) => t.id),
1792
- tools: groupTools,
1793
- createdAt
1794
- };
1795
- }
1796
-
1797
- // src/domain/clarification.ts
1798
- function isClarificationAnswered(block, answers) {
1799
- if (!block) return false;
1800
- if (block.status === "completed") return true;
1801
- if (block.isAnswered) return true;
1802
- const toolCallId = block.toolCallId;
1803
- return !!toolCallId && answers.has(toolCallId);
1804
- }
1805
- function isClarificationBlock(block) {
1806
- return block.type === "ask-clarification" || block.type === "form" && block.source === "ask_clarification";
1807
- }
1808
-
1809
- // src/domain/decorators.ts
1810
- function applyPatchesAndExtras(groups, state, runIdFilter) {
1811
- if (!state.patches.size && !state.extras.length) return groups;
1812
- const patchedGroups = groups.map((g) => state.patches.get(g.id) ?? g);
1813
- const anchor = runIdFilter ? patchedGroups.findIndex((g) => String(g.runId || "").trim() === runIdFilter) : -1;
1814
- return anchor >= 0 ? [...patchedGroups.slice(0, anchor), ...state.extras, ...patchedGroups.slice(anchor)] : [...patchedGroups, ...state.extras];
1815
- }
1816
- function withInterruptBlock(groups, deps) {
1817
- const interrupt = deps.getInterrupt();
1818
- if (!interrupt) return groups;
1819
- const interruptId = String(interrupt.id || "");
1820
- const responded = !!interruptId && deps.respondedIds.has(interruptId);
1821
- const block = buildInterruptReviewBlock(interrupt, responded);
1822
- if (!block) return groups;
1823
- const { interruptBlocks } = deps;
1824
- const targetIndex = findLastAiIndex(groups);
1825
- if (targetIndex >= 0) {
1826
- const remembered = interruptBlocks.get(interruptId);
1827
- if (remembered) {
1828
- const updated = { ...block, status: responded ? "completed" : "pending" };
1829
- interruptBlocks.set(interruptId, updated);
1830
- const next2 = [...groups];
1831
- next2[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, updated] };
1832
- return next2;
1833
- }
1834
- interruptBlocks.set(interruptId, block);
1835
- const next = [...groups];
1836
- next[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, block] };
1837
- return next;
1838
- }
1839
- const existing = [...interruptBlocks.values()].find(
1840
- (b) => b.type === "interrupt-review" && b.interruptId === interruptId
1841
- );
1842
- if (existing) return groups;
1843
- interruptBlocks.set(interruptId, block);
1844
- return [
1845
- ...groups,
1846
- {
1847
- id: `interrupt-${interruptId}`,
1848
- type: "ai",
1849
- status: block.status,
1850
- source: "state",
1851
- originMessageIds: [],
1852
- blocks: [block],
1853
- toolIds: [],
1854
- tools: [],
1855
- rawMessages: [],
1856
- createdAt: Date.now()
1857
- }
1858
- ];
1859
- }
1860
- function findLastAiIndex(groups) {
1861
- for (let i = groups.length - 1; i >= 0; i--) {
1862
- if (groups[i].type === "ai") return i;
1551
+ // src/runtime/semantic-overlay.ts
1552
+ var extractKwargsPatch = (msg) => {
1553
+ const kwargs = msg?.additional_kwargs;
1554
+ if (!kwargs || typeof kwargs !== "object") return void 0;
1555
+ const patch = {};
1556
+ if (kwargs.hide_from_ui === true) patch.hide_from_ui = true;
1557
+ if (kwargs.human_input_response && typeof kwargs.human_input_response === "object") {
1558
+ patch.human_input_response = kwargs.human_input_response;
1863
1559
  }
1864
- return -1;
1865
- }
1866
- function decorateAnswers(groups, answers, responded) {
1867
- if (!answers.size && !responded.size) return groups;
1868
- return groups.map((g) => {
1869
- if (g.type !== "ai" || !g.blocks.length) return g;
1870
- let touched = false;
1871
- const blocks = g.blocks.map((b) => {
1872
- const blk = b;
1873
- if (isClarificationBlock(blk) && blk.toolCallId && answers.has(blk.toolCallId)) {
1874
- touched = true;
1875
- return { ...b, isAnswered: true, answer: answers.get(blk.toolCallId) };
1876
- }
1877
- if (blk.type === "interrupt-review" && blk.interruptId && responded.has(blk.interruptId)) {
1878
- touched = true;
1879
- return { ...b, isResponded: true };
1880
- }
1881
- return b;
1882
- });
1883
- return touched ? { ...g, blocks } : g;
1884
- });
1885
- }
1886
- function filterInvisibleAiGroups(groups) {
1887
- return groups.filter((g) => g.type !== "ai" || hasVisibleAiContent(g));
1888
- }
1889
- function hasVisibleAiContent(g) {
1890
- if (g.status === "streaming") return true;
1891
- if (g.streamingText) return true;
1892
- if (g.blocks.length) return true;
1893
- return g.tools.some((t) => t.result !== void 0 || t.state === "error");
1894
- }
1895
-
1896
- // src/domain/viewmodel-state.ts
1897
- var import_vue2 = require("vue");
1898
- function createViewModelState() {
1899
- const extrasRef = (0, import_vue2.shallowRef)([]);
1900
- const patches = (0, import_vue2.shallowReactive)(/* @__PURE__ */ new Map());
1901
- const readFirstText = (group) => extractTextFromMessage(asSxin(group.rawMessages[0])).trim();
1902
- return {
1903
- get extras() {
1904
- return extrasRef.value;
1905
- },
1906
- get patches() {
1907
- return patches;
1908
- },
1909
- appendExtra(groups) {
1910
- if (!groups.length) return;
1911
- extrasRef.value = [...extrasRef.value, ...groups];
1912
- },
1913
- patchGroup(messageId, patch, sourceGroups) {
1914
- const current = patches.get(messageId) ?? sourceGroups().find((g) => g.id === messageId);
1915
- if (!current) return;
1916
- const next = typeof patch === "function" ? patch(current) : { ...current, ...patch };
1917
- patches.set(messageId, { ...next, id: current.id });
1918
- },
1919
- clearPatches() {
1920
- patches.clear();
1921
- extrasRef.value = [];
1922
- },
1923
- /** human extras 按序收敛:回显(同文本 + 当前流 runId)到达后按序移除乐观副本。
1924
- * 用 runId 而非流式段判定:既有线程的回显可能经 reconcile 以 page-source 到达(不在流式段),
1925
- * 但其 runId 与当前流一致;历史消息 runId 不同,不会误伤(连发同文本逐条配对)。
1926
- * 无当前流 runId(流未开始)时不 prune——避免历史同文本消息误吞乐观副本。 */
1927
- pruneExtras(decoratedGroups, currentRunId) {
1928
- if (!extrasRef.value.some((g) => g.type === "human")) return;
1929
- const runIdFilter = String(currentRunId || "").trim();
1930
- if (!runIdFilter) return;
1931
- const echoed = /* @__PURE__ */ new Map();
1932
- for (const g of decoratedGroups) {
1933
- if (g.type !== "human") continue;
1934
- const runId = String(g.runId || "").trim();
1935
- if (runId !== runIdFilter) continue;
1936
- const text = readFirstText(g);
1937
- echoed.set(text, (echoed.get(text) ?? 0) + 1);
1938
- }
1939
- const seenPerText = /* @__PURE__ */ new Map();
1940
- extrasRef.value = extrasRef.value.filter((extra) => {
1941
- if (extra.type !== "human") return true;
1942
- const text = readFirstText(extra);
1943
- const k = seenPerText.get(text) ?? 0;
1944
- seenPerText.set(text, k + 1);
1945
- return (echoed.get(text) ?? 0) <= k;
1946
- });
1947
- }
1948
- };
1949
- }
1950
-
1951
- // src/domain/viewmodel.ts
1952
- function createGroupDeriver(state) {
1953
- const groupMemo = /* @__PURE__ */ new Map();
1954
- const foldCache = { pageCount: -1, entries: [] };
1955
- const interruptBlocks = /* @__PURE__ */ new Map();
1956
- const derive = (deps) => {
1957
- const { store, enrichments } = deps;
1958
- const streaming = store.streamStatus === "streaming";
1959
- const patched = store.getMessages().map((m) => {
1960
- const patch = enrichments.resolveCitation(String(asSxin(m).id || ""));
1961
- if (!patch || patch.content === void 0) return m;
1962
- return { ...asSxin(m), content: patch.content };
1963
- });
1964
- const sourceOf = (id) => id ? store.getEntity(id)?.source ?? "stream" : "stream";
1965
- const epochOf = (id) => id ? store.getEntity(id)?.epoch : void 0;
1966
- const runIdFilter = String(deps.currentRunId || "").trim();
1967
- const currentEpoch = store.streamEpoch;
1968
- const pageCount = store.pageCount;
1969
- const patchedPrefix = patched.slice(0, pageCount);
1970
- const patchedStream = patched.slice(pageCount);
1971
- let prefixEntries;
1972
- if (foldCache.pageCount === pageCount) {
1973
- prefixEntries = foldCache.entries;
1974
- } else {
1975
- prefixEntries = [];
1976
- foldMessages(
1977
- patchedPrefix,
1978
- (type, buf) => prefixEntries.push({ type, ids: buf.map((m) => String(asSxin(m).id || "")) })
1979
- );
1980
- foldCache.pageCount = pageCount;
1981
- foldCache.entries = prefixEntries;
1982
- }
1983
- const prefixById = new Map(patchedPrefix.map((m) => [String(asSxin(m).id || ""), m]));
1984
- const folded = [];
1985
- if (prefixEntries.every((e) => e.ids.every((id) => prefixById.has(id)))) {
1986
- for (const e of prefixEntries) folded.push({ type: e.type, buf: e.ids.map((id) => prefixById.get(id)) });
1987
- const streamFolded = [];
1988
- foldMessages(patchedStream, (type, buf) => streamFolded.push({ type, buf }));
1989
- const lastPrefix = folded[folded.length - 1];
1990
- const firstStream = streamFolded[0];
1991
- if (lastPrefix && firstStream && canMergeAtBoundary(lastPrefix, firstStream)) {
1992
- lastPrefix.buf = [...lastPrefix.buf, ...firstStream.buf];
1993
- streamFolded.shift();
1994
- }
1995
- folded.push(...streamFolded);
1996
- } else {
1997
- foldCache.pageCount = -1;
1998
- foldCache.entries = [];
1999
- foldMessages(patched, (type, buf) => folded.push({ type, buf }));
2000
- }
2001
- const groups = [];
2002
- let epochActiveFrom = 0;
2003
- if (streaming && !runIdFilter) {
2004
- epochActiveFrom = -1;
2005
- folded.forEach((entry, i) => {
2006
- const id = String(asSxin(entry.buf[0]).id || "");
2007
- if (entry.type === "human" && sourceOf(id) === "stream" && epochOf(id) === currentEpoch) epochActiveFrom = i;
2008
- });
2009
- if (epochActiveFrom < 0) epochActiveFrom = 0;
2010
- }
2011
- folded.forEach((entry, gi) => {
2012
- const firstId = String(asSxin(entry.buf[0]).id || "");
2013
- const firstSource = sourceOf(firstId);
2014
- let groupRunId = messageRunId(entry.buf[0]);
2015
- if (!groupRunId) {
2016
- for (let i = 1; i < entry.buf.length; i++) {
2017
- const rid = messageRunId(entry.buf[i]);
2018
- if (rid) {
2019
- groupRunId = rid;
2020
- break;
2021
- }
2022
- }
2023
- }
2024
- groupRunId = groupRunId || void 0;
2025
- const inActiveZone = streaming ? runIdFilter ? groupRunId === runIdFilter : firstSource === "stream" && epochOf(firstId) === currentEpoch && gi >= epochActiveFrom : false;
2026
- const status = inActiveZone ? "streaming" : "completed";
2027
- const blockSource = firstSource === "page" ? "history" : "sse";
2028
- let verSum = 0;
2029
- for (const m of entry.buf) verSum += store.getEntity(String(asSxin(m).id || ""))?.ver ?? 0;
2030
- const memoKey = `${firstId}|${status}|${blockSource}|${entry.buf.length}|${verSum}|${enrichments.citationVersion}`;
2031
- const cached = groupMemo.get(memoKey);
2032
- if (cached) {
2033
- groups.push(cached);
2034
- return;
2035
- }
2036
- let g;
2037
- if (entry.type === "human") {
2038
- g = buildHumanGroup(entry.buf, status);
2039
- } else {
2040
- g = buildAiGroup(entry.buf, { source: blockSource, isStreaming: status === "streaming" }, deps.twin);
2041
- }
2042
- if (groupMemo.size > 2e3) groupMemo.clear();
2043
- groupMemo.set(memoKey, g);
2044
- groups.push(g);
2045
- });
2046
- for (const g of groups) {
2047
- if (g.type === "ai" && g.status === "streaming") {
2048
- const aiMessages = g.rawMessages.filter((m) => String(asSxin(m).type || "").startsWith("ai"));
2049
- const lastAi = aiMessages[aiMessages.length - 1];
2050
- g.streamingText = lastAi ? extractAiContentFromMessage(lastAi) : "";
2051
- }
1560
+ return Object.keys(patch).length ? patch : void 0;
1561
+ };
1562
+ function extractSemanticPatchesFromMessages(messages) {
1563
+ const next = /* @__PURE__ */ new Map();
1564
+ for (const m of messages ?? []) {
1565
+ const id = String(m?.id || "").trim();
1566
+ if (!id) continue;
1567
+ const patch = { id };
1568
+ if (String(m?.type || "") === "ai" && hasKbCitationMessage(m)) {
1569
+ patch.content = m.content;
2052
1570
  }
2053
- const sourceGroups = groups;
2054
- const decorateSteps = [
2055
- // 第 1 步:补丁应用 + 乐观 extras 锚点落位
2056
- (gs) => applyPatchesAndExtras(gs, state, runIdFilter),
2057
- // 第 2 步:interrupt 审核块注入(去重记忆 interruptBlocks 为构建器公开职责)
2058
- (gs) => withInterruptBlock(gs, {
2059
- getInterrupt: deps.getInterrupt,
2060
- respondedIds: deps.respondedIds,
2061
- interruptBlocks
2062
- }),
2063
- // 第 3 步:澄清回答 / interrupt 响应标记装饰
2064
- (gs) => decorateAnswers(gs, enrichments.answers, deps.respondedIds),
2065
- // 第 4 步:隐藏「无可见内容」的 AI 空气泡
2066
- filterInvisibleAiGroups
2067
- ];
2068
- const merged = decorateSteps.reduce((gs, step) => step(gs), sourceGroups);
2069
- return { groups: merged, sourceGroups };
2070
- };
2071
- return {
2072
- derive,
2073
- clearCache() {
2074
- groupMemo.clear();
2075
- foldCache.pageCount = -1;
2076
- foldCache.entries = [];
2077
- interruptBlocks.clear();
1571
+ if (String(m?.type || "") === "human") {
1572
+ const kwargs = extractKwargsPatch(m);
1573
+ if (kwargs) patch.additional_kwargs = kwargs;
2078
1574
  }
2079
- };
2080
- }
2081
- function canMergeAtBoundary(prefixLast, streamFirst) {
2082
- if (prefixLast.type === "human" && streamFirst.type === "human") {
2083
- return getHumanMessageBaseId(String(asSxin(streamFirst.buf[0]).id || "")) === getHumanMessageBaseId(String(asSxin(prefixLast.buf[0]).id || ""));
1575
+ if (patch.content !== void 0 || patch.additional_kwargs) next.set(id, patch);
2084
1576
  }
2085
- if (prefixLast.type === "ai" && streamFirst.type === "ai") {
2086
- const mRunId = messageRunId(streamFirst.buf[0]);
2087
- const groupRunId = messageRunId(prefixLast.buf[0]);
2088
- return !(mRunId && groupRunId && mRunId !== groupRunId);
2089
- }
2090
- return false;
1577
+ return next;
2091
1578
  }
2092
- function createOptimisticHuman(text, options) {
2093
- const optimisticId = genMessageId();
1579
+ function createSemanticOverlay() {
1580
+ let patches = /* @__PURE__ */ new Map();
2094
1581
  return {
2095
- id: optimisticId,
2096
- type: "human",
2097
- status: "completed",
2098
- originMessageIds: [optimisticId],
2099
- rawMessages: [
2100
- {
2101
- id: optimisticId,
2102
- type: "human",
2103
- name: "user-input",
2104
- content: [{ type: "text", text }],
2105
- additional_kwargs: options?.kwargs
2106
- }
2107
- ],
2108
- additionalKwargs: options?.kwargs,
2109
- blocks: [],
2110
- toolIds: [],
2111
- tools: [],
2112
- createdAt: Date.now()
2113
- };
2114
- }
2115
-
2116
- // src/runtime/thread-runtime.ts
2117
- var import_vue7 = require("vue");
2118
-
2119
- // src/message/dict-merge.ts
2120
- var MERGE_IGNORE_KEYS = ["index", "created", "timestamp"];
2121
- var MERGE_RIGHT_WINS_KEYS = ["id", "name", "output_version", "model_provider"];
2122
- function hasMergeableIndex(value) {
2123
- if (typeof value !== "object" || value === null) return false;
2124
- const idx = value.index;
2125
- return typeof idx === "number" || typeof idx === "string";
2126
- }
2127
- function hasMergeableId(value) {
2128
- if (typeof value !== "object" || value === null) return false;
2129
- const id = value.id;
2130
- return id != null && id !== "";
2131
- }
2132
- function findMergeTarget(merged, item) {
2133
- if (!hasMergeableIndex(item) && !hasMergeableId(item)) return -1;
2134
- return merged.findIndex((leftItem) => {
2135
- const leftHasIndex = hasMergeableIndex(leftItem);
2136
- const leftHasId = hasMergeableId(leftItem);
2137
- const itemHasIndex = hasMergeableIndex(item);
2138
- const itemHasId = hasMergeableId(item);
2139
- if (itemHasIndex && leftHasIndex) {
2140
- if (leftItem.index !== item.index) return false;
2141
- if (leftHasId && itemHasId)
2142
- return leftItem.id === item.id;
2143
- return true;
2144
- }
2145
- if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {
2146
- return leftItem.id === item.id;
2147
- }
2148
- return false;
2149
- });
2150
- }
2151
- function mergeStringField(key, left, right) {
2152
- if (key === "type") return left;
2153
- if (MERGE_RIGHT_WINS_KEYS.includes(key)) return right || left;
2154
- if (MERGE_IGNORE_KEYS.includes(key)) return left;
2155
- return left + right;
2156
- }
2157
- function mergeNumberField(key, left, right) {
2158
- return MERGE_IGNORE_KEYS.includes(key) ? left : left + right;
2159
- }
2160
- function mergeDicts(left, right) {
2161
- if (left == null) return right;
2162
- if (right == null) return left;
2163
- if (Array.isArray(left) && Array.isArray(right)) return mergeLists(left, right);
2164
- if (typeof left === "string" && typeof right === "string") return left + right;
2165
- if (typeof left === "number" && typeof right === "number") return left + right;
2166
- if (typeof left === "object" && typeof right === "object") {
2167
- const merged = { ...left };
2168
- for (const [key, value] of Object.entries(right)) {
2169
- const l = merged[key];
2170
- if (l == null) {
2171
- merged[key] = value;
2172
- } else if (value == null) {
2173
- continue;
2174
- } else if (typeof l === "string" && typeof value === "string") {
2175
- merged[key] = mergeStringField(key, l, value);
2176
- } else if (typeof l === "number" && typeof value === "number") {
2177
- merged[key] = mergeNumberField(key, l, value);
2178
- } else if (Array.isArray(l) && Array.isArray(value)) {
2179
- merged[key] = mergeLists(l, value);
2180
- } else if (typeof l === "object" && typeof value === "object") {
2181
- merged[key] = mergeDicts(l, value);
2182
- } else {
2183
- merged[key] = value;
2184
- }
2185
- }
2186
- return merged;
2187
- }
2188
- return right;
2189
- }
2190
- function mergeLists(left, right) {
2191
- const merged = [...left];
2192
- for (const item of right) {
2193
- const target = findMergeTarget(merged, item);
2194
- if (target !== -1) {
2195
- merged[target] = mergeDicts(merged[target], item);
2196
- } else if (typeof item === "object" && item !== null && "text" in item && item.text === "") {
2197
- continue;
2198
- } else {
2199
- merged.push(item);
2200
- }
2201
- }
2202
- return merged;
2203
- }
2204
- function mergeContent(left, right) {
2205
- if (left == null) return right;
2206
- if (right == null) return left;
2207
- if (typeof left === "string" && typeof right === "string") return left + right;
2208
- const leftArr = Array.isArray(left) ? left : [left];
2209
- const rightArr = Array.isArray(right) ? right : [right];
2210
- return mergeLists(leftArr, rightArr);
2211
- }
2212
- function parsePartialJson(text) {
2213
- const tryParse = (s) => {
2214
- try {
2215
- return JSON.parse(s);
2216
- } catch {
2217
- return void 0;
1582
+ applyState(state) {
1583
+ const messages = extractStateMessages(state);
1584
+ patches = extractSemanticPatchesFromMessages(messages);
1585
+ const citedIds = messages.filter((m) => String(m?.type || "") === "ai" && hasKbCitationMessage(m)).map((m) => String(m?.id || "")).filter(Boolean);
1586
+ return { patched: patches.size, citedIds };
1587
+ },
1588
+ getPatches() {
1589
+ return new Map(patches);
1590
+ },
1591
+ invalidate() {
1592
+ patches = /* @__PURE__ */ new Map();
2218
1593
  }
2219
1594
  };
2220
- const direct = tryParse(text);
2221
- if (direct !== void 0) return direct;
2222
- let fixed = text;
2223
- let inStr = false;
2224
- let escaped = false;
2225
- for (const ch of fixed) {
2226
- if (escaped) {
2227
- escaped = false;
2228
- continue;
2229
- }
2230
- if (ch === "\\") {
2231
- escaped = true;
2232
- continue;
2233
- }
2234
- if (ch === '"') inStr = !inStr;
2235
- }
2236
- if (inStr) fixed += '"';
2237
- const closers = [];
2238
- for (const ch of fixed) {
2239
- if (ch === "{") closers.push("}");
2240
- else if (ch === "[") closers.push("]");
2241
- else if (ch === "}" || ch === "]") closers.pop();
2242
- }
2243
- fixed += closers.reverse().join("");
2244
- const repaired = tryParse(fixed);
2245
- return repaired === void 0 ? null : repaired;
2246
- }
2247
- function collapseToolCallChunks(chunks) {
2248
- const groups = [];
2249
- for (const chunk of chunks) {
2250
- const matched = groups.findIndex((group) => {
2251
- const match = group[0];
2252
- if (chunk?.id && chunk?.index !== void 0) return chunk.id === match.id && chunk.index === match.index;
2253
- if (chunk?.id) return chunk.id === match.id;
2254
- if (chunk?.index !== void 0) return chunk.index === match.index;
2255
- return false;
2256
- });
2257
- if (matched !== -1) groups[matched].push(chunk);
2258
- else groups.push([chunk]);
2259
- }
2260
- const toolCalls = [];
2261
- const invalidToolCalls = [];
2262
- for (const group of groups) {
2263
- const name = group[0]?.name ?? "";
2264
- const joinedArgs = group.map((c) => c?.args || "").join("");
2265
- const argsStr = joinedArgs.trim().length ? joinedArgs.trim() : "{}";
2266
- const id = group.find((c) => c?.id)?.id ?? group[0]?.id;
2267
- const parsed = parsePartialJson(argsStr);
2268
- if (!id || parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
2269
- invalidToolCalls.push({ name, args: argsStr, id, error: "Malformed args.", type: "invalid_tool_call" });
2270
- } else {
2271
- toolCalls.push({ name, args: parsed, id, type: "tool_call" });
2272
- }
2273
- }
2274
- return { tool_calls: toolCalls, invalid_tool_calls: invalidToolCalls };
2275
- }
2276
- function extractToolCallsFromContent(content) {
2277
- if (!Array.isArray(content)) return [];
2278
- return content.flatMap((block) => {
2279
- if (block == null || typeof block !== "object") return [];
2280
- const record = block;
2281
- if (record.type !== "tool_call" && record.type !== "tool_use") return [];
2282
- const rawArgs = record.args ?? record.input;
2283
- let args = {};
2284
- if (rawArgs != null && typeof rawArgs === "object" && !Array.isArray(rawArgs)) args = rawArgs;
2285
- else if (typeof rawArgs === "string" && rawArgs.length > 0) {
2286
- const parsed = parsePartialJson(rawArgs);
2287
- if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) args = parsed;
2288
- }
2289
- return [{ id: record.id ?? "", name: record.name ?? "", args, type: "tool_call" }];
2290
- });
2291
1595
  }
2292
- function mergeMessageDicts(prev, next) {
2293
- const merged = { ...prev };
2294
- for (const [key, value] of Object.entries(next)) {
2295
- if (key === "type") {
2296
- if (merged.type == null) merged.type = value;
2297
- continue;
2298
- }
2299
- if (MERGE_RIGHT_WINS_KEYS.includes(key)) {
2300
- if (value != null && value !== "") merged[key] = value;
2301
- continue;
2302
- }
2303
- if (key === "content") {
2304
- merged.content = mergeContent(prev.content, value);
2305
- } else if (key === "tool_call_chunks") {
2306
- const prevChunks = Array.isArray(prev.tool_call_chunks) ? prev.tool_call_chunks : [];
2307
- const nextChunks = Array.isArray(value) ? value : [];
2308
- const chunks = mergeLists(prevChunks, nextChunks);
2309
- merged.tool_call_chunks = chunks;
2310
- const collapsed = collapseToolCallChunks(chunks);
2311
- merged.tool_calls = collapsed.tool_calls;
2312
- merged.invalid_tool_calls = collapsed.invalid_tool_calls;
2313
- } else {
2314
- merged[key] = mergeDicts(prev[key], value);
2315
- }
2316
- }
2317
- if (!Array.isArray(merged.tool_calls) || merged.tool_calls.length === 0) {
2318
- const extracted = extractToolCallsFromContent(merged.content);
2319
- if (extracted.length > 0) merged.tool_calls = extracted;
2320
- }
2321
- return merged;
2322
- }
2323
-
2324
- // src/protocol/chunk-buffer.ts
2325
- function normalizeEntry(raw) {
2326
- const rawType = String(raw.type || "");
2327
- if (rawType === "RemoveMessage") return { ...raw, type: "remove" };
2328
- return raw;
2329
- }
2330
- function stampRunId(msg, streamRunId) {
2331
- if (String(msg.runId || "").trim()) return msg;
2332
- const kwargsRunId = String(msg.additional_kwargs?.run_id || "").trim();
2333
- const rid = kwargsRunId || String(streamRunId || "").trim();
2334
- if (!rid) return msg;
2335
- return { ...msg, runId: rid };
2336
- }
2337
- function createChunkBuffer(options) {
2338
- const schedule = options.schedule ?? ((fn) => setTimeout(fn, 0));
2339
- const pending = /* @__PURE__ */ new Map();
2340
- const accumulated = /* @__PURE__ */ new Map();
2341
- let order = [];
2342
- const dirty = /* @__PURE__ */ new Set();
2343
- let scheduled = false;
2344
- let timer = null;
2345
- let streamRunId;
2346
- const cancelSchedule = () => {
2347
- scheduled = false;
2348
- if (timer !== null) clearTimeout(timer);
2349
- timer = null;
2350
- };
2351
- const scheduleFlush = () => {
2352
- if (scheduled) return;
2353
- scheduled = true;
2354
- timer = schedule(() => {
2355
- scheduled = false;
2356
- timer = null;
2357
- flush();
2358
- });
2359
- };
2360
- function flush() {
2361
- if (!order.length) return;
2362
- const instructions = [];
2363
- for (const id of order) {
2364
- const entry = pending.get(id);
2365
- if (!entry) continue;
2366
- if (entry.isClear) {
2367
- instructions.push({ kind: "clear" });
2368
- accumulated.clear();
2369
- continue;
2370
- }
2371
- if (entry.isRemove) {
2372
- instructions.push({ kind: "remove", id });
2373
- accumulated.delete(id);
2374
- continue;
2375
- }
2376
- const base = accumulated.get(id);
2377
- const merged = base ? entry.parts.reduce((acc, c) => mergeMessageDicts(acc, c), base) : entry.parts.reduce(mergeMessageDicts);
2378
- accumulated.set(id, merged);
2379
- instructions.push({ kind: "upsert", message: stampRunId(merged, streamRunId) });
1596
+ function applySemanticPatches(messages, patches) {
1597
+ if (!patches.size || !messages.length) return messages;
1598
+ return messages.map((m) => {
1599
+ const id = String(m?.id || "").trim();
1600
+ const patch = id ? patches.get(id) : void 0;
1601
+ if (!patch) return m;
1602
+ let next = m;
1603
+ if (patch.content !== void 0 && String(next?.type || "") === "ai" && !hasKbCitationMessage(next)) {
1604
+ next = { ...next, content: patch.content };
2380
1605
  }
2381
- pending.clear();
2382
- order = [];
2383
- dirty.clear();
2384
- if (instructions.length) options.emit(instructions);
2385
- }
2386
- return {
2387
- add(serialized) {
2388
- if (!serialized || typeof serialized !== "object") return;
2389
- const raw = serialized;
2390
- const rawType = String(raw.type || "");
2391
- const entry = normalizeEntry(raw);
2392
- const type = String(entry.type || "");
2393
- const id = String(entry.id || "").trim();
2394
- if (!id) return;
2395
- if (type === "remove") {
2396
- if (id === "__remove_all__") {
2397
- pending.set(id, { parts: [], isClear: true });
2398
- } else {
2399
- pending.set(id, { parts: [], isRemove: true });
1606
+ const localKwargs = next?.additional_kwargs;
1607
+ if (patch.additional_kwargs && Object.keys(patch.additional_kwargs).length) {
1608
+ const merged = { ...localKwargs };
1609
+ let changed = false;
1610
+ for (const [k, v] of Object.entries(patch.additional_kwargs)) {
1611
+ if (merged[k] === void 0) {
1612
+ merged[k] = v;
1613
+ changed = true;
2400
1614
  }
2401
- if (!dirty.has(id)) {
2402
- dirty.add(id);
2403
- order.push(id);
2404
- }
2405
- scheduleFlush();
2406
- return;
2407
- }
2408
- const isChunk = rawType.endsWith("MessageChunk");
2409
- const existing = pending.get(id);
2410
- if (!existing || existing.isRemove) {
2411
- pending.set(id, { parts: [entry] });
2412
- } else if (!isChunk) {
2413
- existing.parts = [entry];
2414
- } else {
2415
- existing.parts.push(entry);
2416
1615
  }
2417
- if (!dirty.has(id)) {
2418
- dirty.add(id);
2419
- order.push(id);
2420
- }
2421
- scheduleFlush();
2422
- },
2423
- noteStreamRunId(runId) {
2424
- const trimmed = String(runId || "").trim();
2425
- if (trimmed) streamRunId = trimmed;
2426
- },
2427
- reset() {
2428
- cancelSchedule();
2429
- pending.clear();
2430
- order = [];
2431
- dirty.clear();
2432
- accumulated.clear();
2433
- streamRunId = void 0;
2434
- },
2435
- flush,
2436
- dispose() {
2437
- cancelSchedule();
2438
- pending.clear();
2439
- order = [];
2440
- dirty.clear();
2441
- accumulated.clear();
1616
+ if (changed) next = { ...next, additional_kwargs: merged };
2442
1617
  }
2443
- };
1618
+ return next;
1619
+ });
2444
1620
  }
2445
1621
 
1622
+ // src/runtime/thread-runtime.ts
1623
+ var import_vue6 = require("vue");
1624
+
2446
1625
  // src/runtime/history-pager.ts
2447
- var import_vue3 = require("vue");
1626
+ var import_vue = require("vue");
2448
1627
  function createHistoryPager(options) {
2449
1628
  const { threadId, transport, firstPage } = options;
2450
1629
  let cursor = firstPage.nextBeforeSeq;
2451
- const hasMoreRef = (0, import_vue3.ref)(Boolean(firstPage.hasMore) && firstPage.nextBeforeSeq !== void 0);
2452
- const loading = (0, import_vue3.ref)(false);
1630
+ const hasMoreRef = (0, import_vue.ref)(Boolean(firstPage.hasMore) && firstPage.nextBeforeSeq !== void 0);
1631
+ const loading = (0, import_vue.ref)(false);
2453
1632
  const loadOlder = async () => {
2454
1633
  if (loading.value) return hasMoreRef.value;
2455
1634
  if (!hasMoreRef.value || cursor === void 0) {
@@ -2460,7 +1639,7 @@ function createHistoryPager(options) {
2460
1639
  try {
2461
1640
  const page = await transport.fetchMessagesPage(threadId, { beforeSeq: cursor });
2462
1641
  const pageMessages = runMessagesToMessages(page.messages);
2463
- options.emitChanges({ kind: "prepend", messages: pageMessages });
1642
+ options.emitChanges();
2464
1643
  cursor = page.nextBeforeSeq;
2465
1644
  hasMoreRef.value = Boolean(page.hasMore) && page.nextBeforeSeq !== void 0;
2466
1645
  options.onPageLoaded?.(page);
@@ -2469,7 +1648,7 @@ function createHistoryPager(options) {
2469
1648
  loading.value = false;
2470
1649
  }
2471
1650
  };
2472
- return { loadOlder, hasMore: (0, import_vue3.computed)(() => hasMoreRef.value), loading };
1651
+ return { loadOlder, hasMore: (0, import_vue.computed)(() => hasMoreRef.value), loading };
2473
1652
  }
2474
1653
 
2475
1654
  // src/runtime/runtime-bootstrap.ts
@@ -2477,22 +1656,30 @@ async function bootstrapRuntime(deps) {
2477
1656
  const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
2478
1657
  deps.valuesChannel.applyInitialValues(fetched.values);
2479
1658
  deps.valuesChannel.applyThreadState(fetched.threadState);
2480
- deps.enrichments.applyFromStateMessages(extractStateMessages(fetched.threadState));
1659
+ const semantic = deps.overlay.applyState(fetched.threadState);
1660
+ if (semantic.patched) {
1661
+ console.debug(`[runtime] \u8BED\u4E49\u5C42\u52A0\u8F7D patched=${semantic.patched} cited=${semantic.citedIds.length}`);
1662
+ }
2481
1663
  deps.runs.fillFromRunsList(fetched.runsList ?? []);
2482
1664
  deps.runs.enrichFromPage(fetched.messagesPage);
2483
1665
  const pageMessages = runMessagesToMessages(fetched.messagesPage.messages);
2484
- if (pageMessages.length) deps.store.applyInstructions([{ kind: "prepend", messages: pageMessages }]);
1666
+ const seeded = applySemanticPatches(pageMessages, deps.overlay.getPatches());
1667
+ if (seeded.length) deps.rm.hydrate(seeded);
1668
+ deps.rm.applySemanticPatch(deps.overlay.getPatches());
2485
1669
  deps.setPager(
2486
1670
  createHistoryPager({
2487
1671
  threadId: deps.threadId,
2488
1672
  transport: deps.transport,
2489
1673
  firstPage: fetched.messagesPage,
2490
- onPageLoaded: (page) => deps.runs.enrichFromPage(page),
2491
- emitChanges: (batch) => deps.store.applyInstructions([batch])
1674
+ onPageLoaded: (page) => {
1675
+ deps.runs.enrichFromPage(page);
1676
+ deps.rm.prependHistory(runMessagesToMessages(page.messages));
1677
+ },
1678
+ emitChanges: () => {
1679
+ }
2492
1680
  })
2493
1681
  );
2494
1682
  await deps.refreshTokenUsage();
2495
- deps.setChunkBuffer(createChunkBuffer({ emit: (ins) => deps.store.applyInstructions(ins) }));
2496
1683
  const finalize = () => finalizeAfterStream(deps);
2497
1684
  const afterFinish = () => afterStreamFinish(deps);
2498
1685
  deps.streamRef.value = deps.transport.createStream({
@@ -2501,7 +1688,9 @@ async function bootstrapRuntime(deps) {
2501
1688
  onCreated: (run) => deps.markStreamRun(run?.run_id),
2502
1689
  onMetadataEvent: (data) => deps.markStreamRun(data?.run_id),
2503
1690
  onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
2504
- onMessageTupleEvent: (serialized, metadata) => deps.getChunkBuffer()?.add(serialized, metadata),
1691
+ onMessageTupleEvent: () => {
1692
+ },
1693
+ onSnapshotMessages: (messages) => deps.rm.applySnapshot(messages),
2505
1694
  onStreamStart: deps.onStreamStart,
2506
1695
  onStreamEnd: finalize,
2507
1696
  onFinish: afterFinish,
@@ -2510,50 +1699,36 @@ async function bootstrapRuntime(deps) {
2510
1699
  deps.setInitialized();
2511
1700
  }
2512
1701
  function finalizeAfterStream(deps) {
2513
- deps.getChunkBuffer()?.flush();
2514
- deps.enrichments.applyFromStateMessages(deps.valuesChannel.getStreamMessages());
2515
- deps.store.applyInstructions(buildValuesReplaceInstructions(deps.store, deps.valuesChannel.getStreamMessages()));
2516
- deps.store.applyInstructions([{ kind: "finalize" }]);
2517
- deps.runs.backfillCurrentRunMetadata(() => deps.store.getMessages());
2518
- }
2519
- function buildValuesReplaceInstructions(store, streamMessages) {
2520
- const instructions = [];
2521
- for (const msg of streamMessages) {
2522
- const id = String(msg?.id || "").trim();
2523
- if (!id) continue;
2524
- const existing = store.getEntity(id);
2525
- if (!existing) continue;
2526
- if (existing.source !== "stream" || existing.epoch !== store.streamEpoch) continue;
2527
- const runId = String(existing.msg?.runId || existing.msg?.additional_kwargs?.run_id || "").trim();
2528
- const next = runId ? { ...msg, runId } : msg;
2529
- instructions.push({ kind: "upsert", message: next });
2530
- }
2531
- return instructions;
1702
+ deps.rm.finalize();
1703
+ deps.onStreamSettled();
1704
+ deps.runs.backfillCurrentRunMetadata(() => [...deps.rm.lastMessages()]);
1705
+ deps.rm.applySemanticPatch(extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages()));
2532
1706
  }
2533
1707
  async function afterStreamFinish(deps) {
2534
1708
  await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
2535
1709
  await reconcileWithPage(deps);
2536
- await applyCitationsFallback(deps);
1710
+ await refreshSemanticLayer(deps);
2537
1711
  }
2538
- async function reconcileWithPage(deps) {
1712
+ async function refreshSemanticLayer(deps) {
2539
1713
  try {
2540
- const page = await deps.transport.fetchMessagesPage(deps.threadId);
2541
- const messages = runMessagesToMessages(page.messages);
2542
- if (messages.length) {
2543
- deps.store.applyInstructions(messages.map((message) => ({ kind: "upsert", message, source: "page" })));
1714
+ const state = await deps.transport.fetchThreadState(deps.threadId);
1715
+ if (!state) return;
1716
+ const semantic = deps.overlay.applyState(state);
1717
+ deps.rm.applySemanticPatch(deps.overlay.getPatches());
1718
+ if (semantic.patched) {
1719
+ console.debug(`[runtime] \u8BED\u4E49\u5C42\u5237\u65B0 patched=${semantic.patched} cited=${semantic.citedIds.length}`);
2544
1720
  }
2545
1721
  } catch (e) {
2546
- console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
1722
+ console.warn("[runtime] \u8BED\u4E49\u5C42\u5237\u65B0\u5931\u8D25", e);
2547
1723
  }
2548
1724
  }
2549
- async function applyCitationsFallback(deps) {
2550
- if (deps.valuesChannel.getStreamMessages().length > 0) return;
1725
+ async function reconcileWithPage(deps) {
2551
1726
  try {
2552
- const state = await deps.transport.fetchThreadState(deps.threadId);
2553
- if (!state) return;
2554
- deps.enrichments.applyFromStateMessages(extractStateMessages(state));
1727
+ const page = await deps.transport.fetchMessagesPage(deps.threadId);
1728
+ const messages = runMessagesToMessages(page.messages);
1729
+ if (messages.length) deps.rm.reconcileWithPage(messages);
2555
1730
  } catch (e) {
2556
- console.warn("[runtime] citation state \u515C\u5E95\u63D0\u53D6\u5931\u8D25", e);
1731
+ console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
2557
1732
  }
2558
1733
  }
2559
1734
  async function runRuntimeInit(deps, hooks) {
@@ -2565,20 +1740,806 @@ async function runRuntimeInit(deps, hooks) {
2565
1740
  }
2566
1741
  }
2567
1742
 
2568
- // src/protocol/values-channel.ts
2569
- var import_vue4 = require("vue");
2570
- var import_ui = require("@langchain/langgraph-sdk/ui");
2571
-
2572
- // src/protocol/interrupt-reconcile.ts
2573
- function reconcileInterrupts(prevValues, nextValues, firstEvent) {
2574
- let base = prevValues;
2575
- if (firstEvent && base && "__interrupt__" in base) {
2576
- const { __interrupt__: _dropped, ...rest } = base;
2577
- base = rest;
2578
- }
2579
- if (nextValues && typeof nextValues === "object" && "__interrupt__" in nextValues) {
2580
- let interrupts = nextValues.__interrupt__;
2581
- const prevInterrupts = base?.__interrupt__;
1743
+ // src/runtime/runtime-stream-actions.ts
1744
+ function createStreamActions(ctx) {
1745
+ return {
1746
+ submit(text, submitOptions) {
1747
+ const handle = ctx.getHandle();
1748
+ if (!handle) return;
1749
+ ctx.beginStream();
1750
+ const humanMessage = { type: "human", content: [{ type: "text", text }] };
1751
+ humanMessage.additional_kwargs = submitOptions?.kwargs;
1752
+ handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
1753
+ },
1754
+ async joinStream(runId, lastEventId) {
1755
+ const handle = ctx.getHandle();
1756
+ if (!handle) return;
1757
+ ctx.beginStream();
1758
+ ctx.markStreamRun(runId);
1759
+ await handle.joinStream(runId, lastEventId ?? "-1");
1760
+ },
1761
+ stop() {
1762
+ void ctx.options.transport.cancelRun(ctx.options.threadId, ctx.runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
1763
+ ctx.getHandle()?.stop();
1764
+ },
1765
+ async resumeInterrupt(decisions) {
1766
+ const it = ctx.getInterrupt();
1767
+ const interruptId = String(it?.id || "");
1768
+ if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
1769
+ const handle = ctx.getHandle();
1770
+ if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
1771
+ ctx.markResponded(interruptId);
1772
+ ctx.beginStream();
1773
+ await handle.resumeInterrupt(decisions);
1774
+ },
1775
+ async loadOlderMessages() {
1776
+ if (!ctx.getPager()) return false;
1777
+ return ctx.getPager().loadOlder();
1778
+ }
1779
+ };
1780
+ }
1781
+
1782
+ // src/runtime/runtime-materializer.ts
1783
+ var import_vue3 = require("vue");
1784
+
1785
+ // src/materializer/materializer.ts
1786
+ var import_vue2 = require("vue");
1787
+
1788
+ // src/materializer/indexes.ts
1789
+ function createIndexes() {
1790
+ return { byMessageId: /* @__PURE__ */ new Map(), byToolCallId: /* @__PURE__ */ new Map(), byRunId: /* @__PURE__ */ new Map() };
1791
+ }
1792
+ function rebuildIndexes(turns) {
1793
+ const idx = createIndexes();
1794
+ turns.forEach((turn, ti) => {
1795
+ idx.byMessageId.set(turn.id, { turn: ti, ai: null });
1796
+ idx.byRunId.set(turn.runId, { turn: ti, ai: 0 });
1797
+ turn.ai.forEach((seg, ai_i) => {
1798
+ idx.byMessageId.set(seg.id, { turn: ti, ai: ai_i });
1799
+ for (const mid of seg.messageIds ?? []) {
1800
+ if (mid) idx.byMessageId.set(mid, { turn: ti, ai: ai_i });
1801
+ }
1802
+ idx.byRunId.set(seg.runId, { turn: ti, ai: ai_i });
1803
+ seg.tools.forEach((tool, tool_i) => {
1804
+ idx.byToolCallId.set(tool.callId, { turn: ti, ai: ai_i, tool: tool_i });
1805
+ });
1806
+ });
1807
+ });
1808
+ return idx;
1809
+ }
1810
+
1811
+ // src/materializer/extractors.ts
1812
+ function normalizeName(name) {
1813
+ const n = String(name || "").trim().toLowerCase();
1814
+ return n === "write_files" ? "write_file" : n;
1815
+ }
1816
+ function tryParseObject(result) {
1817
+ const text = String(result ?? "").trim();
1818
+ if (!text.startsWith("{")) return null;
1819
+ try {
1820
+ const parsed = JSON.parse(text);
1821
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
1822
+ return parsed;
1823
+ } catch {
1824
+ return null;
1825
+ }
1826
+ }
1827
+ function extractFromToolResult(name, result, toolCallLike) {
1828
+ const tool = normalizeName(name);
1829
+ const obj = tryParseObject(result);
1830
+ if (tool === "ask_clarification" && obj) {
1831
+ const question = obj.question ?? obj.title;
1832
+ if (typeof question !== "string" || !question.trim()) return void 0;
1833
+ const options = Array.isArray(obj.options) ? obj.options : void 0;
1834
+ return options ? { kind: "clarification", question, options } : { kind: "clarification", question };
1835
+ }
1836
+ if (tool === "write_file") {
1837
+ if (obj) {
1838
+ if (typeof obj.body === "string" && obj.body) {
1839
+ const outline = typeof obj.outline === "string" ? obj.outline : void 0;
1840
+ return outline ? { kind: "report", reportKind: "report_body", body: obj.body, outline } : { kind: "report", reportKind: "report_body", body: obj.body };
1841
+ }
1842
+ if (Array.isArray(obj.files) && obj.files.length) {
1843
+ return { kind: "artifact", files: obj.files };
1844
+ }
1845
+ }
1846
+ const reportKind = resolveReportArtifactKind(toolCallLike);
1847
+ if (reportKind) {
1848
+ const tc = toolCallLike ?? {};
1849
+ const sourcePath = String(tc?.artifact_meta?.path || tc?.args?.path || "").trim() || void 0;
1850
+ return {
1851
+ kind: "report",
1852
+ reportKind,
1853
+ sourcePath,
1854
+ title: sourcePath ? extractTitleFromArtifactPath(sourcePath, reportKind) : void 0
1855
+ };
1856
+ }
1857
+ }
1858
+ return void 0;
1859
+ }
1860
+
1861
+ // src/materializer/turn-machine-rules.ts
1862
+ function messageRunId(msg) {
1863
+ const own = String(asSxin(msg).runId || "").trim();
1864
+ if (own) return own;
1865
+ return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
1866
+ }
1867
+ function isHiddenHuman(msg) {
1868
+ return msg?.additional_kwargs?.hide_from_ui === true;
1869
+ }
1870
+ function hasEmptyKwargs(msg) {
1871
+ const kwargs = msg?.additional_kwargs;
1872
+ return !kwargs || typeof kwargs !== "object" || Object.keys(kwargs).length === 0;
1873
+ }
1874
+ function resolveHumanKwargsMerge(prevKwargs, incomingKwargs, incomingIsVariant) {
1875
+ if (incomingIsVariant) return prevKwargs;
1876
+ const prevEmpty = !prevKwargs || typeof prevKwargs !== "object" || Object.keys(prevKwargs).length === 0;
1877
+ return prevEmpty ? incomingKwargs : prevKwargs;
1878
+ }
1879
+ function readHir(msg) {
1880
+ const response = msg?.additional_kwargs?.human_input_response;
1881
+ if (!response || typeof response !== "object") return null;
1882
+ const requestId = String(response.request_id || "").trim().replace("clarification:", "");
1883
+ if (!requestId || response.value === void 0) return null;
1884
+ return { requestId, value: response.value };
1885
+ }
1886
+ function buildClarification(tool) {
1887
+ if (tool.name !== "ask_clarification") return null;
1888
+ const args = tool.input ?? {};
1889
+ const question = typeof args.question === "string" ? args.question : "";
1890
+ if (!question) return null;
1891
+ const fields = Array.isArray(args.fields) ? args.fields : void 0;
1892
+ return {
1893
+ callId: tool.callId,
1894
+ question,
1895
+ ...args.options !== void 0 ? { options: args.options } : {},
1896
+ ...fields?.length ? { fields } : {}
1897
+ };
1898
+ }
1899
+ function createTurnRules(ctx) {
1900
+ const { state } = ctx;
1901
+ const registerToolCalls = (ti, ai_i, msg, effects) => {
1902
+ const toolCalls = msg?.tool_calls;
1903
+ if (!Array.isArray(toolCalls) || !toolCalls.length) return;
1904
+ let turn = state.turns[ti];
1905
+ for (const tc of toolCalls) {
1906
+ const callId = String(tc?.id || "").trim();
1907
+ if (!callId || ctx.indexes().byToolCallId.has(callId)) continue;
1908
+ const tool = {
1909
+ callId,
1910
+ name: String(tc?.name || ""),
1911
+ input: tc?.args,
1912
+ artifactMeta: tc?.artifact_meta,
1913
+ status: "running"
1914
+ };
1915
+ turn = ctx.cloneWith(turn, ai_i, (t) => {
1916
+ t.ai[ai_i].tools = [...turn.ai[ai_i].tools, tool];
1917
+ });
1918
+ const tool_i = turn.ai[ai_i].tools.length - 1;
1919
+ ctx.indexes().byToolCallId.set(callId, { turn: ti, ai: ai_i, tool: tool_i });
1920
+ effects.push({ type: "tool-updated", turnId: turn.id, aiId: turn.ai[ai_i].id, tool });
1921
+ const clarification = buildClarification(tool);
1922
+ if (clarification) {
1923
+ turn = ctx.cloneWith(turn, null, (t) => {
1924
+ t.clarifications = [...turn.clarifications, clarification];
1925
+ });
1926
+ }
1927
+ }
1928
+ state.turns[ti] = turn;
1929
+ };
1930
+ const openNewAi = (ti, msg, effects) => {
1931
+ let turn = state.turns[ti];
1932
+ if (state.openAi !== null) {
1933
+ turn = ctx.sealAiSegment(turn, state.openAi, effects);
1934
+ }
1935
+ const runId = messageRunId(msg) || ctx.streamRunId() || "";
1936
+ const body = readMessageContentText(msg);
1937
+ const seg = {
1938
+ id: String(msg?.id || ""),
1939
+ runId,
1940
+ body,
1941
+ streamingText: body,
1942
+ tools: [],
1943
+ attachments: [],
1944
+ segments: [{ type: "text", content: body }],
1945
+ status: "streaming",
1946
+ // 段内消息 id 登记(rebuildIndexes 重建 byMessageId 的依据,防 finalize 后 update 索引 miss)
1947
+ messageIds: [String(msg?.id || "")].filter(Boolean)
1948
+ };
1949
+ turn = ctx.cloneWith(turn, null, (t) => {
1950
+ t.ai = [...turn.ai, seg];
1951
+ if (!t.runId && runId) t.runId = runId;
1952
+ t.rawMessages = [...t.rawMessages ?? [], msg];
1953
+ });
1954
+ state.turns[ti] = turn;
1955
+ state.openAi = turn.ai.length - 1;
1956
+ ctx.indexes().byRunId.set(runId, { turn: ti, ai: state.openAi });
1957
+ if (seg.id) ctx.indexes().byMessageId.set(seg.id, { turn: ti, ai: state.openAi });
1958
+ effects.push({ type: "ai-opened", turnId: turn.id, ai: turn.ai[turn.ai.length - 1] });
1959
+ registerToolCalls(ti, state.openAi, msg, effects);
1960
+ };
1961
+ const appendHuman = (msg, allowOptimistic, effects) => {
1962
+ const id = String(msg?.id || "").trim();
1963
+ const baseId = getHumanMessageBaseId(id) || id;
1964
+ const msgRunId = String(msg?.additional_kwargs?.run_id || "").trim();
1965
+ if (msgRunId) {
1966
+ for (let ti = state.turns.length - 1; ti >= 0; ti--) {
1967
+ const t = state.turns[ti];
1968
+ const tBase = getHumanMessageBaseId(t.human.id) || t.human.id;
1969
+ const tRun = String(t.human.kwargs?.run_id || "").trim();
1970
+ if (tBase === baseId && tRun && tRun === msgRunId) {
1971
+ const mergedKwargs = resolveHumanKwargsMerge(
1972
+ t.human.kwargs,
1973
+ msg?.additional_kwargs,
1974
+ baseId !== id
1975
+ );
1976
+ const next = ctx.cloneWith(t, null, (t2) => {
1977
+ t2.human = {
1978
+ id: t.human.id || id,
1979
+ text: t.human.text || extractTextFromMessage(msg),
1980
+ kwargs: mergedKwargs
1981
+ };
1982
+ t2.rawMessages = [...t2.rawMessages ?? [], msg];
1983
+ });
1984
+ state.turns[ti] = next;
1985
+ if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
1986
+ effects.push({ type: "message-updated", turnId: next.id, aiId: null });
1987
+ return;
1988
+ }
1989
+ }
1990
+ }
1991
+ if (state.openTurn !== null && !state.turns[state.openTurn].ai.length) {
1992
+ const openHumanBase = getHumanMessageBaseId(state.turns[state.openTurn].human.id);
1993
+ if (openHumanBase && openHumanBase === baseId) {
1994
+ const ti = state.openTurn;
1995
+ const mergedKwargs = resolveHumanKwargsMerge(
1996
+ state.turns[ti].human.kwargs,
1997
+ msg?.additional_kwargs,
1998
+ baseId !== id
1999
+ );
2000
+ const next = ctx.cloneWith(state.turns[ti], null, (t) => {
2001
+ t.human = { id, text: extractTextFromMessage(msg), kwargs: mergedKwargs };
2002
+ t.rawMessages = [...t.rawMessages ?? [], msg];
2003
+ });
2004
+ state.turns[ti] = next;
2005
+ ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
2006
+ effects.push({ type: "message-updated", turnId: next.id, aiId: null });
2007
+ return;
2008
+ }
2009
+ }
2010
+ const optimistic = allowOptimistic && !!id && !ctx.indexes().byMessageId.has(id) && !messageRunId(msg) && hasEmptyKwargs(msg);
2011
+ ctx.sealOpenTurn(effects);
2012
+ const turn = {
2013
+ id: id || `turn-${state.turns.length}`,
2014
+ runId: "",
2015
+ createdAt: Number(new Date(msg?.created_at || Date.now())) || Date.now(),
2016
+ human: { id, text: extractTextFromMessage(msg), kwargs: msg?.additional_kwargs },
2017
+ ai: [],
2018
+ clarifications: [],
2019
+ status: "streaming",
2020
+ optimistic,
2021
+ // 原始消息入档(排查用)
2022
+ rawMessages: [msg]
2023
+ };
2024
+ state.turns.push(turn);
2025
+ state.openTurn = state.turns.length - 1;
2026
+ if (id) ctx.indexes().byMessageId.set(id, { turn: state.openTurn, ai: null });
2027
+ if (optimistic) state.optimisticTurnId = turn.id;
2028
+ effects.push({ type: "turn-opened", turn, optimistic });
2029
+ };
2030
+ const appendHiddenHuman = (msg, effects) => {
2031
+ const hir = readHir(msg);
2032
+ if (!hir) return;
2033
+ const toolLoc = ctx.indexes().byToolCallId.get(hir.requestId);
2034
+ const ti = toolLoc?.turn ?? state.openTurn ?? state.turns.length - 1;
2035
+ if (ti < 0) return;
2036
+ const turn = state.turns[ti];
2037
+ const ci = turn.clarifications.findIndex((c) => c.callId === hir.requestId);
2038
+ if (ci < 0) return;
2039
+ const answer = formatAnswerText(hir.value);
2040
+ const id = String(msg?.id || "").trim();
2041
+ const next = ctx.cloneWith(turn, null, (t) => {
2042
+ t.clarifications[ci] = { ...t.clarifications[ci], answer, answerMessageId: id || void 0 };
2043
+ t.rawMessages = [...t.rawMessages ?? [], msg];
2044
+ });
2045
+ state.turns[ti] = next;
2046
+ if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
2047
+ effects.push({ type: "clarification-answered", turnId: next.id, callId: hir.requestId, answer });
2048
+ };
2049
+ const applyToolMessage = (msg, effects) => {
2050
+ const m = msg;
2051
+ const callId = String(m?.tool_call_id || "").trim();
2052
+ if (!callId) return;
2053
+ const result = readMessageContentText(m);
2054
+ const status = m?.status === "error" ? "error" : "finished";
2055
+ const id = String(m?.id || "").trim();
2056
+ const loc = ctx.indexes().byToolCallId.get(callId);
2057
+ if (loc) {
2058
+ const turn2 = state.turns[loc.turn];
2059
+ const old = turn2.ai[loc.ai].tools[loc.tool];
2060
+ const tool = {
2061
+ ...old,
2062
+ status,
2063
+ result,
2064
+ extracted: extractFromToolResult(old.name, result, { artifact_meta: old.artifactMeta, args: old.input }) ?? old.extracted
2065
+ };
2066
+ const next2 = ctx.cloneWith(turn2, loc.ai, (t) => {
2067
+ t.ai[loc.ai].tools[loc.tool] = tool;
2068
+ if (t.ai[loc.ai].status === "sealed") t.ai[loc.ai].attachments = ctx.assembleAttachments(t.ai[loc.ai]);
2069
+ t.rawMessages = [...t.rawMessages ?? [], msg];
2070
+ });
2071
+ state.turns[loc.turn] = next2;
2072
+ if (id) ctx.indexes().byMessageId.set(id, { turn: loc.turn, ai: loc.ai });
2073
+ effects.push({ type: "tool-updated", turnId: next2.id, aiId: next2.ai[loc.ai].id, tool });
2074
+ return;
2075
+ }
2076
+ const ti = state.openTurn;
2077
+ const ai_i = state.openAi;
2078
+ if (ti === null || ai_i === null) return;
2079
+ const orphan = {
2080
+ callId,
2081
+ name: String(m?.name || ""),
2082
+ input: {},
2083
+ status,
2084
+ result,
2085
+ extracted: extractFromToolResult(String(m?.name || ""), result)
2086
+ };
2087
+ const turn = state.turns[ti];
2088
+ const next = ctx.cloneWith(turn, ai_i, (t) => {
2089
+ t.ai[ai_i].tools = [...turn.ai[ai_i].tools, orphan];
2090
+ t.rawMessages = [...t.rawMessages ?? [], msg];
2091
+ });
2092
+ state.turns[ti] = next;
2093
+ ctx.indexes().byToolCallId.set(callId, { turn: ti, ai: ai_i, tool: next.ai[ai_i].tools.length - 1 });
2094
+ if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: ai_i });
2095
+ effects.push({ type: "tool-updated", turnId: next.id, aiId: next.ai[ai_i].id, tool: orphan });
2096
+ };
2097
+ const appendAi = (msg, effects) => {
2098
+ const id = String(msg?.id || "").trim();
2099
+ if (state.openTurn === null) {
2100
+ appendHuman(
2101
+ {
2102
+ id: `${id || "ai"}-orphan`,
2103
+ type: "human",
2104
+ content: "",
2105
+ additional_kwargs: {}
2106
+ },
2107
+ false,
2108
+ effects
2109
+ );
2110
+ }
2111
+ const ti = state.openTurn;
2112
+ const runId = messageRunId(msg);
2113
+ const openSeg = state.openAi !== null ? state.turns[ti].ai[state.openAi] : null;
2114
+ if (openSeg && (!runId || !openSeg.runId || runId === openSeg.runId)) {
2115
+ const text = readMessageContentText(msg);
2116
+ const ai_i = state.openAi;
2117
+ const turn = state.turns[ti];
2118
+ const body = text || openSeg.body;
2119
+ const next = ctx.cloneWith(turn, ai_i, (t) => {
2120
+ t.ai[ai_i].body = body;
2121
+ t.ai[ai_i].streamingText = body;
2122
+ if (id && !t.ai[ai_i].messageIds?.includes(id)) {
2123
+ t.ai[ai_i].messageIds = [...t.ai[ai_i].messageIds ?? [], id];
2124
+ }
2125
+ if (!t.ai[ai_i].runId) t.ai[ai_i].runId = runId || ctx.streamRunId() || "";
2126
+ t.rawMessages = [...t.rawMessages ?? [], msg];
2127
+ });
2128
+ state.turns[ti] = next;
2129
+ if (id && id !== openSeg.id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: ai_i });
2130
+ effects.push({ type: "ai-delta", turnId: next.id, aiId: openSeg.id, body, streamingText: body });
2131
+ registerToolCalls(ti, ai_i, msg, effects);
2132
+ return;
2133
+ }
2134
+ openNewAi(ti, msg, effects);
2135
+ };
2136
+ return { appendHuman, appendHiddenHuman, appendAi, applyToolMessage, registerToolCalls };
2137
+ }
2138
+
2139
+ // src/materializer/turn-machine.ts
2140
+ var DEFAULT_TWIN_TOOL_PREFIX = "city-digital-twin-display_";
2141
+ function createTurnMachine(options) {
2142
+ const state = { turns: [], openTurn: null, openAi: null, optimisticTurnId: null };
2143
+ let indexes = createIndexes();
2144
+ const twinEnabled = !!options?.twin?.enabled;
2145
+ const twinToolPrefix = options?.twin?.toolPrefix || DEFAULT_TWIN_TOOL_PREFIX;
2146
+ const streamRunId = () => String(options?.getStreamRunId?.() || "").trim();
2147
+ const assembleAttachments = (seg) => {
2148
+ const byKind = /* @__PURE__ */ new Map();
2149
+ for (const tool of seg.tools) {
2150
+ const ex = tool.extracted;
2151
+ if (ex?.kind === "report") {
2152
+ byKind.set(`report:${ex.reportKind}`, {
2153
+ kind: "report",
2154
+ reportKind: ex.reportKind,
2155
+ body: ex.body,
2156
+ outline: ex.outline,
2157
+ sourcePath: ex.sourcePath,
2158
+ title: ex.title
2159
+ });
2160
+ } else if (ex?.kind === "artifact") byKind.set("artifact", { kind: "artifact", files: ex.files });
2161
+ else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
2162
+ byKind.set("twin", { kind: "twin", payload: tool.input });
2163
+ }
2164
+ }
2165
+ return [...byKind.values()];
2166
+ };
2167
+ const cloneWith = (turn, ai_i, mutate) => {
2168
+ const next = {
2169
+ ...turn,
2170
+ human: { ...turn.human },
2171
+ clarifications: [...turn.clarifications],
2172
+ ai: turn.ai.map((seg, i) => i === ai_i ? { ...seg, tools: [...seg.tools] } : seg)
2173
+ };
2174
+ mutate(next);
2175
+ return next;
2176
+ };
2177
+ const archiveRaw = (t, msg) => {
2178
+ const id = String(msg?.id || "").trim();
2179
+ const raws = t.rawMessages ?? [];
2180
+ const ri = id ? raws.findIndex((r) => String(r?.id || "").trim() === id) : -1;
2181
+ t.rawMessages = ri >= 0 ? [...raws.slice(0, ri), msg, ...raws.slice(ri + 1)] : [...raws, msg];
2182
+ };
2183
+ const sealAiSegment = (turn, ai_i, effects) => {
2184
+ const seg = turn.ai[ai_i];
2185
+ if (seg.status === "sealed") return turn;
2186
+ const sealed = {
2187
+ ...seg,
2188
+ status: "sealed",
2189
+ streamingText: void 0,
2190
+ segments: sliceBodySegments(seg.body),
2191
+ attachments: assembleAttachments(seg)
2192
+ };
2193
+ const next = cloneWith(turn, ai_i, (t) => {
2194
+ t.ai[ai_i] = sealed;
2195
+ });
2196
+ effects.push({ type: "ai-sealed", turnId: next.id, aiId: sealed.id, segments: sealed.segments });
2197
+ return next;
2198
+ };
2199
+ const sealOpenTurn = (effects) => {
2200
+ const ti = state.openTurn;
2201
+ if (ti === null) return;
2202
+ let turn = state.turns[ti];
2203
+ if (state.openAi !== null) {
2204
+ turn = sealAiSegment(turn, state.openAi, effects);
2205
+ state.openAi = null;
2206
+ }
2207
+ if (turn.status !== "sealed") {
2208
+ const sealed = { ...turn, status: "sealed" };
2209
+ state.turns[ti] = sealed;
2210
+ effects.push({ type: "turn-sealed", turnId: sealed.id });
2211
+ }
2212
+ state.openTurn = null;
2213
+ if (state.optimisticTurnId === turn.id) state.optimisticTurnId = null;
2214
+ };
2215
+ const rules = createTurnRules({
2216
+ state,
2217
+ indexes: () => indexes,
2218
+ cloneWith,
2219
+ sealOpenTurn,
2220
+ sealAiSegment,
2221
+ assembleAttachments,
2222
+ streamRunId
2223
+ });
2224
+ const applyTailRemove = (id, effects) => {
2225
+ const ti = state.openTurn;
2226
+ if (state.optimisticTurnId && ti !== null && state.turns[ti]?.human.id === id) {
2227
+ state.turns.pop();
2228
+ state.openTurn = null;
2229
+ state.openAi = null;
2230
+ state.optimisticTurnId = null;
2231
+ indexes = rebuildIndexes(state.turns);
2232
+ effects.push({ type: "placeholder-dropped", turnId: id });
2233
+ return;
2234
+ }
2235
+ };
2236
+ const applyAppend = (msg, allowOptimistic, effects) => {
2237
+ if (isHiddenHuman(msg)) return rules.appendHiddenHuman(msg, effects);
2238
+ if (isHumanMessage(msg)) return rules.appendHuman(msg, allowOptimistic, effects);
2239
+ if (isAiMessage(msg)) return rules.appendAi(msg, effects);
2240
+ if (isToolMessage(msg)) return rules.applyToolMessage(msg, effects);
2241
+ };
2242
+ const applyUpdate = (id, msg, effects) => {
2243
+ const loc = indexes.byMessageId.get(id);
2244
+ if (!loc) return;
2245
+ if (loc.ai === null) {
2246
+ if (isHiddenHuman(msg)) return rules.appendHiddenHuman(msg, effects);
2247
+ if (!isHumanMessage(msg)) return;
2248
+ const turn2 = state.turns[loc.turn];
2249
+ const wasOptimistic = state.optimisticTurnId === turn2.id;
2250
+ const mergedKwargs = resolveHumanKwargsMerge(
2251
+ turn2.human.kwargs,
2252
+ msg?.additional_kwargs,
2253
+ (getHumanMessageBaseId(id) || id) !== id
2254
+ );
2255
+ const next2 = cloneWith(turn2, null, (t) => {
2256
+ t.human = { id, text: extractTextFromMessage(msg), kwargs: mergedKwargs };
2257
+ t.optimistic = false;
2258
+ archiveRaw(t, msg);
2259
+ });
2260
+ state.turns[loc.turn] = next2;
2261
+ if (wasOptimistic) {
2262
+ state.optimisticTurnId = null;
2263
+ effects.push({ type: "placeholder-absorbed", turnId: next2.id });
2264
+ } else {
2265
+ effects.push({ type: "message-updated", turnId: next2.id, aiId: null });
2266
+ }
2267
+ return;
2268
+ }
2269
+ if (isToolMessage(msg)) {
2270
+ rules.applyToolMessage(msg, effects);
2271
+ return;
2272
+ }
2273
+ const turn = state.turns[loc.turn];
2274
+ const seg = turn.ai[loc.ai];
2275
+ const text = readMessageContentText(msg);
2276
+ const body = text || seg.body;
2277
+ const bodyChanged = body !== seg.body;
2278
+ const next = cloneWith(turn, loc.ai, (t) => {
2279
+ const target = t.ai[loc.ai];
2280
+ target.body = body;
2281
+ if (target.status === "streaming") target.streamingText = body;
2282
+ if (target.status === "sealed" && bodyChanged) target.segments = sliceBodySegments(body);
2283
+ if (!target.runId) {
2284
+ const rid = messageRunId(msg) || streamRunId();
2285
+ if (rid) target.runId = rid;
2286
+ }
2287
+ archiveRaw(t, msg);
2288
+ });
2289
+ state.turns[loc.turn] = next;
2290
+ if (id !== seg.id && isAiMessage(msg)) {
2291
+ indexes.byMessageId.set(id, { turn: loc.turn, ai: loc.ai });
2292
+ const nextSeg = state.turns[loc.turn].ai[loc.ai];
2293
+ if (!nextSeg.messageIds?.includes(id)) nextSeg.messageIds = [...nextSeg.messageIds ?? [], id];
2294
+ }
2295
+ effects.push({ type: "ai-delta", turnId: next.id, aiId: seg.id, body, streamingText: body });
2296
+ rules.registerToolCalls(loc.turn, loc.ai, msg, effects);
2297
+ };
2298
+ const finalizeInto = (effects) => {
2299
+ sealOpenTurn(effects);
2300
+ indexes = rebuildIndexes(state.turns);
2301
+ };
2302
+ function resetMachine() {
2303
+ state.turns = [];
2304
+ state.openTurn = null;
2305
+ state.openAi = null;
2306
+ state.optimisticTurnId = null;
2307
+ indexes = createIndexes();
2308
+ }
2309
+ return {
2310
+ applyDeltas(deltas) {
2311
+ const effects = [];
2312
+ for (const d of deltas) {
2313
+ if (d.type === "append") applyAppend(d.message, true, effects);
2314
+ else if (d.type === "update") applyUpdate(d.id, d.message, effects);
2315
+ else applyTailRemove(d.id, effects);
2316
+ }
2317
+ return effects;
2318
+ },
2319
+ seed(messages) {
2320
+ if (state.openTurn !== null || state.openAi !== null) {
2321
+ throw new Error("[materializer] \u6D41\u8FDB\u884C\u4E2D\u7981\u6B62 seed\uFF08\u5148 finalize \u5BC6\u5C01\u540E\u518D\u5168\u91CF\u91CD\u5EFA\uFF09");
2322
+ }
2323
+ resetMachine();
2324
+ const effects = [];
2325
+ for (const msg of messages) applyAppend(msg, false, effects);
2326
+ finalizeInto(effects);
2327
+ return effects;
2328
+ },
2329
+ finalize() {
2330
+ const effects = [];
2331
+ finalizeInto(effects);
2332
+ return effects;
2333
+ },
2334
+ decorate(id, patch) {
2335
+ const effects = [];
2336
+ const loc = indexes.byMessageId.get(id);
2337
+ if (!loc || loc.ai === null) return effects;
2338
+ const turn = state.turns[loc.turn];
2339
+ const next = cloneWith(turn, loc.ai, (t) => {
2340
+ Object.assign(t.ai[loc.ai], patch);
2341
+ });
2342
+ state.turns[loc.turn] = next;
2343
+ effects.push({ type: "message-updated", turnId: next.id, aiId: next.ai[loc.ai].id });
2344
+ return effects;
2345
+ },
2346
+ reset: resetMachine,
2347
+ get state() {
2348
+ return state;
2349
+ },
2350
+ get indexes() {
2351
+ return indexes;
2352
+ }
2353
+ };
2354
+ }
2355
+
2356
+ // src/materializer/diff.ts
2357
+ function diffMessageSnapshots(baseline, next) {
2358
+ const upserts = [];
2359
+ const nextBaseline = /* @__PURE__ */ new Map();
2360
+ for (const msg of next) {
2361
+ const id = String(msg?.id || "").trim();
2362
+ if (!id) continue;
2363
+ if (baseline.get(id) !== msg) upserts.push(msg);
2364
+ nextBaseline.set(id, msg);
2365
+ }
2366
+ const removals = [];
2367
+ for (const id of baseline.keys()) if (!nextBaseline.has(id)) removals.push(id);
2368
+ return { upserts, removals, nextBaseline };
2369
+ }
2370
+ function createMessageDiff() {
2371
+ let baseline = /* @__PURE__ */ new Map();
2372
+ return {
2373
+ apply(next) {
2374
+ const { upserts, removals, nextBaseline } = diffMessageSnapshots(baseline, next);
2375
+ const deltas = [];
2376
+ for (const msg of upserts) {
2377
+ const id = String(msg?.id || "").trim();
2378
+ deltas.push(baseline.has(id) ? { type: "update", id, message: msg } : { type: "append", message: msg });
2379
+ }
2380
+ for (const id of removals) deltas.push({ type: "tail-remove", id });
2381
+ baseline = nextBaseline;
2382
+ return deltas;
2383
+ },
2384
+ reset() {
2385
+ baseline = /* @__PURE__ */ new Map();
2386
+ },
2387
+ get baselineSize() {
2388
+ return baseline.size;
2389
+ }
2390
+ };
2391
+ }
2392
+
2393
+ // src/materializer/materializer.ts
2394
+ function createMaterializer(options) {
2395
+ const view = (0, import_vue2.shallowRef)({ turns: [] });
2396
+ const machine = createTurnMachine(options);
2397
+ const messageDiff = createMessageDiff();
2398
+ const publishIfChanged = (effects) => {
2399
+ if (!effects.length) return;
2400
+ view.value = { turns: [...machine.state.turns] };
2401
+ };
2402
+ return {
2403
+ view,
2404
+ hydrate(seed) {
2405
+ messageDiff.reset();
2406
+ messageDiff.apply(seed);
2407
+ const effects = machine.seed(seed);
2408
+ publishIfChanged(effects);
2409
+ },
2410
+ applySnapshot(messages) {
2411
+ const deltas = messageDiff.apply(messages);
2412
+ if (!deltas.length) return;
2413
+ const effects = machine.applyDeltas(deltas);
2414
+ publishIfChanged(effects);
2415
+ },
2416
+ finalize() {
2417
+ publishIfChanged(machine.finalize());
2418
+ },
2419
+ decorate(messageId, patch) {
2420
+ publishIfChanged(machine.decorate(messageId, patch));
2421
+ },
2422
+ reset() {
2423
+ messageDiff.reset();
2424
+ machine.reset();
2425
+ view.value = { turns: [] };
2426
+ }
2427
+ };
2428
+ }
2429
+
2430
+ // src/runtime/runtime-materializer.ts
2431
+ var localSeq = 0;
2432
+ function createRuntimeMaterializer(options) {
2433
+ const materializer = createMaterializer({ twin: options.twin, getStreamRunId: options.getStreamRunId });
2434
+ let lastMessages = [];
2435
+ const answersMap = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Map());
2436
+ const answers = (0, import_vue3.computed)(() => answersMap.value);
2437
+ const turns = (0, import_vue3.computed)(() => materializer.view.value.turns);
2438
+ const activeClarification = (0, import_vue3.computed)(() => {
2439
+ const ts = materializer.view.value.turns;
2440
+ const last = ts[ts.length - 1];
2441
+ if (!last) return void 0;
2442
+ for (let ci = last.clarifications.length - 1; ci >= 0; ci--) {
2443
+ const c = last.clarifications[ci];
2444
+ if (!c.answer && !answersMap.value.has(c.callId)) return c;
2445
+ }
2446
+ return void 0;
2447
+ });
2448
+ const feed = (messages) => {
2449
+ lastMessages = messages;
2450
+ materializer.applySnapshot(messages);
2451
+ };
2452
+ return {
2453
+ view: materializer.view,
2454
+ turns,
2455
+ activeClarification,
2456
+ answers,
2457
+ setClarificationAnswer(toolCallId, answer) {
2458
+ const next = new Map(answersMap.value);
2459
+ next.set(toolCallId, answer);
2460
+ answersMap.value = next;
2461
+ },
2462
+ clearClarificationAnswers() {
2463
+ if (!answersMap.value.size) return;
2464
+ answersMap.value = /* @__PURE__ */ new Map();
2465
+ },
2466
+ lastMessages: () => lastMessages,
2467
+ hydrate(seed) {
2468
+ lastMessages = seed;
2469
+ materializer.hydrate(seed);
2470
+ },
2471
+ applySnapshot(messages) {
2472
+ lastMessages = messages;
2473
+ materializer.applySnapshot(messages);
2474
+ },
2475
+ finalize() {
2476
+ materializer.finalize();
2477
+ },
2478
+ decorate(messageId, patch) {
2479
+ materializer.decorate(messageId, patch);
2480
+ },
2481
+ prependHistory(older) {
2482
+ const merged = [...older, ...lastMessages];
2483
+ try {
2484
+ materializer.hydrate(merged);
2485
+ } catch {
2486
+ return false;
2487
+ }
2488
+ lastMessages = merged;
2489
+ return true;
2490
+ },
2491
+ reconcileWithPage(pageMessages) {
2492
+ if (!pageMessages.length || !lastMessages.length) return;
2493
+ const byId = new Map(pageMessages.map((m) => [String(m?.id || ""), m]));
2494
+ feed(lastMessages.map((m) => byId.get(String(m?.id || "")) ?? m));
2495
+ },
2496
+ addOptimisticTurn(body) {
2497
+ localSeq += 1;
2498
+ const stamp = `${Date.now()}-${localSeq}`;
2499
+ const humanMsg = {
2500
+ id: `local-h-${stamp}`,
2501
+ type: "human",
2502
+ content: [{ type: "text", text: body }],
2503
+ additional_kwargs: {}
2504
+ };
2505
+ const aiMsg = {
2506
+ id: `local-a-${stamp}`,
2507
+ type: "ai",
2508
+ content: [{ type: "text", text: "" }],
2509
+ additional_kwargs: {}
2510
+ };
2511
+ feed([...lastMessages, humanMsg, aiMsg]);
2512
+ },
2513
+ updateAiBody(aiId, body) {
2514
+ const idx = lastMessages.findIndex((m) => String(m?.id || "") === aiId);
2515
+ if (idx < 0) return;
2516
+ const next = [...lastMessages];
2517
+ next[idx] = { ...next[idx], content: [{ type: "text", text: body }] };
2518
+ feed(next);
2519
+ },
2520
+ applySemanticPatch(patches) {
2521
+ if (!patches.size || !lastMessages.length) return;
2522
+ const next = applySemanticPatches(lastMessages, patches);
2523
+ const changed = next.some((m, i) => m !== lastMessages[i]);
2524
+ if (changed) feed(next);
2525
+ }
2526
+ };
2527
+ }
2528
+
2529
+ // src/runtime/values-projection.ts
2530
+ var import_vue4 = require("vue");
2531
+ var import_ui = require("@langchain/langgraph-sdk/ui");
2532
+
2533
+ // src/runtime/interrupt-reconcile.ts
2534
+ function reconcileInterrupts(prevValues, nextValues, firstEvent) {
2535
+ let base = prevValues;
2536
+ if (firstEvent && base && "__interrupt__" in base) {
2537
+ const { __interrupt__: _dropped, ...rest } = base;
2538
+ base = rest;
2539
+ }
2540
+ if (nextValues && typeof nextValues === "object" && "__interrupt__" in nextValues) {
2541
+ let interrupts = nextValues.__interrupt__;
2542
+ const prevInterrupts = base?.__interrupt__;
2582
2543
  if (Array.isArray(interrupts) && interrupts.length > 0 && Array.isArray(prevInterrupts)) {
2583
2544
  const merged = [...prevInterrupts];
2584
2545
  const existingIds = new Set(merged.map((i) => i?.id).filter((id) => id != null));
@@ -2603,7 +2564,7 @@ function reconcileInterrupts(prevValues, nextValues, firstEvent) {
2603
2564
  return nextValues ?? {};
2604
2565
  }
2605
2566
 
2606
- // src/protocol/values-channel.ts
2567
+ // src/runtime/values-projection.ts
2607
2568
  function createValuesChannel(options = {}) {
2608
2569
  const valuesRef = (0, import_vue4.shallowRef)({});
2609
2570
  const threadStateRef = (0, import_vue4.shallowRef)(void 0);
@@ -2653,186 +2614,8 @@ function createValuesChannel(options = {}) {
2653
2614
  };
2654
2615
  }
2655
2616
 
2656
- // src/store/thread-state.ts
2617
+ // src/store/runs-store.ts
2657
2618
  var import_vue5 = require("vue");
2658
- function createThreadStore(_options = {}) {
2659
- const entities = /* @__PURE__ */ new Map();
2660
- let order = [];
2661
- let pageCountCache = -1;
2662
- let cachedFlat = null;
2663
- const version = (0, import_vue5.ref)(0);
2664
- const streamStatusRef = (0, import_vue5.shallowRef)("idle");
2665
- let streamEpoch = 0;
2666
- const leadingPageCount = () => {
2667
- let i = 0;
2668
- while (i < order.length && entities.get(order[i])?.source === "page") i++;
2669
- return i;
2670
- };
2671
- const lastPageIndex = () => {
2672
- for (let i = order.length - 1; i >= 0; i--) {
2673
- if (entities.get(order[i])?.source === "page") return i;
2674
- }
2675
- return -1;
2676
- };
2677
- const bump = () => {
2678
- cachedFlat = null;
2679
- pageCountCache = -1;
2680
- version.value++;
2681
- };
2682
- const applyInstructions = (instructions) => {
2683
- if (!instructions.length) return;
2684
- let touched = false;
2685
- for (const ins of instructions) {
2686
- switch (ins.kind) {
2687
- case "upsert": {
2688
- const id = String(ins.message.id || "").trim();
2689
- if (!id) break;
2690
- const message = normalizeMessageType(ins.message);
2691
- const existing = entities.get(id);
2692
- if (existing) {
2693
- existing.msg = message;
2694
- existing.ver++;
2695
- if (ins.source === "page") {
2696
- existing.source = "page";
2697
- } else {
2698
- existing.source = "stream";
2699
- existing.epoch = streamEpoch;
2700
- }
2701
- } else {
2702
- entities.set(id, {
2703
- msg: message,
2704
- source: ins.source === "page" ? "page" : "stream",
2705
- epoch: streamEpoch,
2706
- ver: 1
2707
- });
2708
- if (ins.source === "page") {
2709
- order.splice(lastPageIndex() + 1, 0, id);
2710
- } else {
2711
- order.push(id);
2712
- }
2713
- }
2714
- touched = true;
2715
- break;
2716
- }
2717
- case "remove": {
2718
- if (!entities.has(ins.id)) break;
2719
- const idx = order.indexOf(ins.id);
2720
- if (idx >= 0) order.splice(idx, 1);
2721
- entities.delete(ins.id);
2722
- touched = true;
2723
- break;
2724
- }
2725
- case "clear": {
2726
- const removed = order.splice(leadingPageCount());
2727
- for (const id of removed) entities.delete(id);
2728
- touched = touched || removed.length > 0;
2729
- break;
2730
- }
2731
- case "prepend": {
2732
- const fresh = [];
2733
- for (const msg of ins.messages) {
2734
- const id = String(msg.id || "").trim();
2735
- if (!id || entities.has(id)) continue;
2736
- entities.set(id, {
2737
- msg: normalizeMessageType(msg),
2738
- source: "page",
2739
- epoch: streamEpoch,
2740
- ver: 1
2741
- });
2742
- fresh.push(id);
2743
- }
2744
- if (fresh.length) {
2745
- order = [...fresh, ...order];
2746
- touched = true;
2747
- }
2748
- break;
2749
- }
2750
- case "finalize": {
2751
- if (streamStatusRef.value !== "settled") {
2752
- streamStatusRef.value = "settled";
2753
- touched = true;
2754
- }
2755
- break;
2756
- }
2757
- }
2758
- }
2759
- if (touched) bump();
2760
- };
2761
- return {
2762
- applyInstructions,
2763
- beginStream() {
2764
- streamEpoch++;
2765
- streamStatusRef.value = "streaming";
2766
- bump();
2767
- },
2768
- getEntity: (id) => entities.get(id),
2769
- get order() {
2770
- return order;
2771
- },
2772
- get pageCount() {
2773
- if (pageCountCache < 0) pageCountCache = leadingPageCount();
2774
- return pageCountCache;
2775
- },
2776
- getMessages() {
2777
- if (!cachedFlat) cachedFlat = order.map((id) => entities.get(id).msg);
2778
- return cachedFlat;
2779
- },
2780
- get streamStatus() {
2781
- return streamStatusRef.value;
2782
- },
2783
- get streamEpoch() {
2784
- return streamEpoch;
2785
- },
2786
- version,
2787
- streamStatusRef
2788
- };
2789
- }
2790
- function readContentText(content) {
2791
- if (typeof content === "string") return content;
2792
- if (Array.isArray(content)) {
2793
- return content.map((c) => c?.type === "text" ? String(c.text || "") : "").join("");
2794
- }
2795
- return "";
2796
- }
2797
- function isCitationCarrier(msg) {
2798
- if (!isAiMessage(msg)) return false;
2799
- return readContentText(asSxin(msg).content).includes("support.kbCitation");
2800
- }
2801
- function createEnrichments() {
2802
- const citationPatches = (0, import_vue5.shallowReactive)(/* @__PURE__ */ new Map());
2803
- const answers = (0, import_vue5.shallowReactive)(/* @__PURE__ */ new Map());
2804
- let citationVersion = 0;
2805
- return {
2806
- get citationVersion() {
2807
- return citationVersion;
2808
- },
2809
- applyFromStateMessages(messages) {
2810
- for (const msg of messages) {
2811
- const m = asSxin(msg);
2812
- const id = String(m.id || "").trim();
2813
- if (!id || !isCitationCarrier(msg)) continue;
2814
- citationPatches.set(id, { content: m.content });
2815
- citationVersion++;
2816
- }
2817
- const extracted = extractThreadInfo(messages).clarificationAnswers;
2818
- for (const [key, value] of extracted) answers.set(key, value);
2819
- },
2820
- resolveCitation(messageId) {
2821
- return citationPatches.get(messageId);
2822
- },
2823
- answers,
2824
- setAnswer(requestId, answer) {
2825
- answers.set(requestId, answer);
2826
- },
2827
- clearAnswers() {
2828
- answers.clear();
2829
- },
2830
- dispose() {
2831
- citationPatches.clear();
2832
- answers.clear();
2833
- }
2834
- };
2835
- }
2836
2619
  function createInterruptState() {
2837
2620
  const respondedIds = (0, import_vue5.shallowRef)(/* @__PURE__ */ new Set());
2838
2621
  return {
@@ -2943,98 +2726,51 @@ function createRunsStore(options) {
2943
2726
  };
2944
2727
  }
2945
2728
 
2946
- // src/runtime/derived-groups.ts
2947
- var import_vue6 = require("vue");
2948
- function createDerivedGroups(deps) {
2949
- const deriver = createGroupDeriver(deps.state);
2950
- const derived = (0, import_vue6.computed)(() => {
2951
- deps.store.version.value;
2952
- return deriver.derive({
2953
- store: deps.store,
2954
- enrichments: deps.enrichments,
2955
- getInterrupt: () => deps.valuesChannel.getInterrupt({ isLoading: deps.streamRef.value?.isLoading.value ?? false }),
2956
- respondedIds: deps.interruptState.respondedIds.value,
2957
- currentRunId: deps.runs.currentRunId.value ?? void 0,
2958
- twin: deps.twin
2959
- });
2960
- });
2961
- deps.scope.run(() => {
2962
- (0, import_vue6.watch)(
2963
- () => [deps.store.version.value, deps.runs.currentRunId.value],
2964
- () => {
2965
- deps.state.pruneExtras(derived.value.sourceGroups, deps.runs.currentRunId.value ?? void 0);
2966
- },
2967
- { flush: "sync" }
2968
- );
2969
- });
2970
- const groups = (0, import_vue6.computed)(() => derived.value.groups);
2971
- const sourceGroups = (0, import_vue6.computed)(() => derived.value.sourceGroups);
2972
- return { groups, sourceGroups };
2973
- }
2974
-
2975
2729
  // src/runtime/thread-runtime.ts
2976
2730
  function createThreadRuntime(options) {
2977
- const scope = (0, import_vue7.effectScope)();
2978
- const store = createThreadStore({ threadId: options.threadId });
2979
- const enrichments = createEnrichments();
2731
+ const scope = (0, import_vue6.effectScope)();
2980
2732
  const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
2981
2733
  const interruptState = createInterruptState();
2982
- const state = createViewModelState();
2734
+ const rm = createRuntimeMaterializer({
2735
+ twin: options.twin,
2736
+ // 段级 runId 兜底源(metadata 首帧权威值):流式 tuple 消息本体无 runId,
2737
+ // 段打开/回填时经此兜底——点赞/反馈按 runId 提交的依赖
2738
+ getStreamRunId: () => runs.currentRunId.value
2739
+ });
2983
2740
  const valuesChannel = createValuesChannel({
2984
2741
  onTitle: (title) => options.onTitle?.(options.threadId, title)
2985
2742
  });
2986
- let chunkBuffer = null;
2987
- const streamRef = (0, import_vue7.shallowRef)(null);
2988
- const isInitializing = (0, import_vue7.ref)(false);
2989
- const tokenUsage = (0, import_vue7.shallowRef)(null);
2743
+ const overlay = createSemanticOverlay();
2744
+ const streamRef = (0, import_vue6.shallowRef)(null);
2745
+ const isInitializing = (0, import_vue6.ref)(false);
2746
+ const streaming = (0, import_vue6.ref)(false);
2747
+ const tokenUsage = (0, import_vue6.shallowRef)(null);
2990
2748
  let initialized = false;
2991
2749
  let initPromise = null;
2992
2750
  let pager = null;
2993
- const derivedGroups = createDerivedGroups({
2994
- scope,
2995
- store,
2996
- enrichments,
2997
- state,
2998
- runs,
2999
- interruptState,
3000
- valuesChannel,
3001
- streamRef,
3002
- twin: options.twin
3003
- });
3004
- const { groups, sourceGroups } = derivedGroups;
3005
- const interrupt = (0, import_vue7.computed)(() => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }));
3006
- const hasPendingInterrupt = (0, import_vue7.computed)(() => {
2751
+ const interrupt = (0, import_vue6.computed)(() => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }));
2752
+ const hasPendingInterrupt = (0, import_vue6.computed)(() => {
3007
2753
  const it = interrupt.value;
3008
2754
  return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
3009
2755
  });
3010
- const streamError = (0, import_vue7.computed)(() => streamRef.value?.error.value ?? null);
3011
- const isGenerating = (0, import_vue7.computed)(() => store.streamStatusRef.value === "streaming");
3012
- const hasPendingClarification = (0, import_vue7.computed)(() => {
3013
- store.version.value;
3014
- const list = groups.value;
3015
- return list.some((m, i) => {
3016
- if (m.type !== "ai") return false;
3017
- const hasUnanswered = m.blocks.some(
3018
- (b) => isClarificationBlock(b) && !isClarificationAnswered(b, enrichments.answers)
3019
- );
3020
- if (!hasUnanswered) return false;
3021
- return !list.slice(i + 1).some((x) => x.type === "human");
3022
- });
3023
- });
2756
+ const streamError = (0, import_vue6.computed)(() => streamRef.value?.error.value ?? null);
2757
+ const isGenerating = (0, import_vue6.computed)(() => streaming.value);
3024
2758
  const beginStream = () => {
3025
- chunkBuffer?.reset();
3026
2759
  valuesChannel.beginStream();
2760
+ overlay.invalidate();
3027
2761
  runs.currentRunId.value = null;
3028
2762
  };
3029
2763
  const streamStarted = () => {
3030
- store.beginStream();
2764
+ streaming.value = true;
2765
+ };
2766
+ const streamSettled = () => {
2767
+ streaming.value = false;
3031
2768
  };
3032
2769
  const markStreamRun = (runIdRaw) => {
3033
2770
  const runId = String(runIdRaw || "").trim();
3034
2771
  if (!runId) return;
3035
2772
  runs.currentRunId.value = runId;
3036
2773
  runs.ensureRunning(runId);
3037
- chunkBuffer?.noteStreamRunId(runId);
3038
2774
  };
3039
2775
  const refreshTokenUsage = async () => {
3040
2776
  try {
@@ -3048,17 +2784,16 @@ function createThreadRuntime(options) {
3048
2784
  threadId: options.threadId,
3049
2785
  assistantId: options.assistantId,
3050
2786
  transport: options.transport,
3051
- store,
3052
- enrichments,
3053
2787
  runs,
3054
2788
  valuesChannel,
2789
+ overlay,
2790
+ rm,
3055
2791
  streamRef,
3056
- setChunkBuffer: (b) => chunkBuffer = b,
3057
- getChunkBuffer: () => chunkBuffer,
3058
2792
  setPager: (p) => pager = p,
3059
2793
  setInitialized: () => initialized = true,
3060
2794
  markStreamRun,
3061
2795
  onStreamStart: streamStarted,
2796
+ onStreamSettled: streamSettled,
3062
2797
  refreshTokenUsage
3063
2798
  },
3064
2799
  {
@@ -3066,23 +2801,34 @@ function createThreadRuntime(options) {
3066
2801
  onEnd: () => isInitializing.value = false
3067
2802
  }
3068
2803
  );
2804
+ const actions = createStreamActions({
2805
+ options,
2806
+ getHandle: () => streamRef.value,
2807
+ beginStream,
2808
+ markStreamRun,
2809
+ getInterrupt: () => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }),
2810
+ markResponded: (id) => interruptState.markResponded(id),
2811
+ getPager: () => pager,
2812
+ runs
2813
+ });
3069
2814
  return {
3070
2815
  threadId: options.threadId,
3071
2816
  lastViewedAt: Date.now(),
3072
2817
  touch() {
3073
2818
  this.lastViewedAt = Date.now();
3074
2819
  },
3075
- groups,
2820
+ view: rm.view,
2821
+ turns: rm.turns,
2822
+ activeClarification: rm.activeClarification,
3076
2823
  isGenerating,
3077
2824
  isInitializing,
3078
- runs: (0, import_vue7.computed)(() => runs.runsMap.value),
2825
+ runs: (0, import_vue6.computed)(() => runs.runsMap.value),
3079
2826
  interrupt,
3080
2827
  hasPendingInterrupt,
3081
- hasPendingClarification,
3082
2828
  streamError,
3083
2829
  tokenUsage,
3084
- hasMoreHistory: (0, import_vue7.computed)(() => pager?.hasMore.value ?? false),
3085
- loadingHistory: (0, import_vue7.computed)(() => pager?.loading.value ?? false),
2830
+ hasMoreHistory: (0, import_vue6.computed)(() => pager?.hasMore.value ?? false),
2831
+ loadingHistory: (0, import_vue6.computed)(() => pager?.loading.value ?? false),
3086
2832
  async init() {
3087
2833
  if (initialized) return;
3088
2834
  if (initPromise) return initPromise;
@@ -3093,64 +2839,26 @@ function createThreadRuntime(options) {
3093
2839
  initPromise = null;
3094
2840
  }
3095
2841
  },
3096
- submit(text, submitOptions) {
3097
- const handle = streamRef.value;
3098
- if (!handle) return;
3099
- beginStream();
3100
- const humanMessage = { type: "human", content: [{ type: "text", text }] };
3101
- humanMessage.additional_kwargs = submitOptions?.kwargs;
3102
- handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
3103
- },
3104
- async joinStream(runId, lastEventId) {
3105
- const handle = streamRef.value;
3106
- if (!handle) return;
3107
- beginStream();
3108
- markStreamRun(runId);
3109
- await handle.joinStream(runId, lastEventId ?? "-1");
3110
- },
3111
- stop() {
3112
- void options.transport.cancelRun(options.threadId, runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
3113
- streamRef.value?.stop();
3114
- },
3115
- async resumeInterrupt(decisions) {
3116
- const it = valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false });
3117
- const interruptId = String(it?.id || "");
3118
- if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
3119
- const handle = streamRef.value;
3120
- if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
3121
- interruptState.markResponded(interruptId);
3122
- beginStream();
3123
- await handle.resumeInterrupt(decisions);
3124
- },
3125
- async loadOlderMessages() {
3126
- if (!pager) return false;
3127
- return pager.loadOlder();
3128
- },
3129
- appendOptimisticGroups(gs) {
3130
- state.appendExtra(gs);
3131
- },
3132
- createOptimisticHuman(text, opts) {
3133
- return createOptimisticHuman(text, opts);
3134
- },
3135
- patchGroup(messageId, patch) {
3136
- state.patchGroup(messageId, patch, () => sourceGroups.value);
3137
- },
2842
+ submit: actions.submit,
2843
+ joinStream: actions.joinStream,
2844
+ stop: actions.stop,
2845
+ resumeInterrupt: actions.resumeInterrupt,
2846
+ loadOlderMessages: actions.loadOlderMessages,
3138
2847
  applyFeedback(messageId, feedback) {
3139
- const runId = groups.value.find((g) => g.id === messageId)?.runId;
3140
- state.patchGroup(messageId, { feedback }, () => sourceGroups.value);
2848
+ rm.decorate(messageId, { feedback });
2849
+ const runId = rm.view.value.turns.flatMap((t) => t.ai).find((seg) => seg.id === messageId)?.runId;
3141
2850
  if (runId) runs.patchRun(runId, { feedback });
3142
2851
  },
3143
- setClarificationAnswer(toolCallId, answer) {
3144
- enrichments.setAnswer(toolCallId, answer);
3145
- },
3146
- clearClarificationAnswers() {
3147
- enrichments.clearAnswers();
3148
- },
3149
- clarificationAnswers: (0, import_vue7.computed)(() => enrichments.answers),
2852
+ addOptimisticTurn: rm.addOptimisticTurn,
2853
+ updateAiBody: rm.updateAiBody,
2854
+ decorate: rm.decorate,
2855
+ finalizeTurns: rm.finalize,
2856
+ setClarificationAnswer: rm.setClarificationAnswer,
2857
+ clearClarificationAnswers: rm.clearClarificationAnswers,
2858
+ clarificationAnswers: rm.answers,
3150
2859
  dispose() {
3151
2860
  streamRef.value?.stop();
3152
- chunkBuffer?.dispose();
3153
- enrichments.dispose();
2861
+ streamRef.value?.dispose?.();
3154
2862
  runs.dispose();
3155
2863
  scope.stop();
3156
2864
  }
@@ -3158,15 +2866,15 @@ function createThreadRuntime(options) {
3158
2866
  }
3159
2867
 
3160
2868
  // src/runtime/thread-directory.ts
3161
- var import_vue8 = require("vue");
3162
- var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending"]);
2869
+ var import_vue7 = require("vue");
2870
+ var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending", "interrupted"]);
3163
2871
  function isActiveThreadStatus(status) {
3164
2872
  return typeof status === "string" && ACTIVE_THREAD_STATUSES.has(status);
3165
2873
  }
3166
2874
  var ThreadDirectory = class {
3167
2875
  constructor(options) {
3168
- this.threads = (0, import_vue8.ref)([]);
3169
- this.threadsPagination = (0, import_vue8.ref)({
2876
+ this.threads = (0, import_vue7.ref)([]);
2877
+ this.threadsPagination = (0, import_vue7.ref)({
3170
2878
  limit: 50,
3171
2879
  offset: 0,
3172
2880
  hasMore: true,
@@ -3174,9 +2882,9 @@ var ThreadDirectory = class {
3174
2882
  });
3175
2883
  this.searchKeyword = "";
3176
2884
  /** 正在运行但已超出 SSE 连接上限的 thread(仅用于 UI 提示) */
3177
- this.runningNotConnectedThreadIds = (0, import_vue8.ref)(/* @__PURE__ */ new Set());
2885
+ this.runningNotConnectedThreadIds = (0, import_vue7.ref)(/* @__PURE__ */ new Set());
3178
2886
  /** 活跃 runtime 池(shallowReactive 追踪增删,runtime 实例不被深度代理) */
3179
- this.cachedRuntimes = (0, import_vue8.shallowReactive)(/* @__PURE__ */ new Map());
2887
+ this.cachedRuntimes = (0, import_vue7.shallowReactive)(/* @__PURE__ */ new Map());
3180
2888
  this.transport = options.transport;
3181
2889
  this.assistantId = options.assistantId;
3182
2890
  this.maxCachedRuntimes = options.maxCachedRuntimes ?? DEFAULT_MAX_CACHED_SESSIONS;
@@ -3311,17 +3019,26 @@ var ThreadDirectory = class {
3311
3019
  }
3312
3020
  // ===== 刷新后恢复 =====
3313
3021
  /**
3314
- * 恢复 running run 的 SSE:在已加载列表里过滤活跃线程 → listRuns 确认 → init + joinStream。
3315
- * interrupted 线程不恢复(打开时经 init 恢复 interrupt 卡片)。并行确认,串行连接(并发上限内)。
3022
+ * 恢复未完成 run 的 SSE:按 thread.status(含 interrupted)筛出候选线程并行 listRuns
3023
+ * 取最新 run → init + joinStream。
3024
+ * ⚠️ DeerFlow 语义:thread.status 与 run.status 的 'interrupted' 都表示「run 未完成」
3025
+ *(_derive_thread_status:tasks 非空 → interrupted;涵盖在跑、停在半路、HITL 挂起),
3026
+ * 不等于 LangGraph 官方的「HITL 挂起」——因此 run.status 不作硬判定,最新 run 一律
3027
+ * join:在跑则继续收流;已断则 join 返回 end 帧走 onFinish 对账(runs/state/citation
3028
+ * 刷新),页面收敛到最终状态。join 为只读幂等端点,误 join 无副作用。
3029
+ * 并行确认,串行连接(并发上限内)。
3316
3030
  */
3317
3031
  async recoverRunningThreads() {
3318
- const activeThreads = this.threads.value.filter((t) => isActiveThreadStatus(t.status) && t.thread_id);
3032
+ const candidates = this.threads.value.filter((t) => t.thread_id && isActiveThreadStatus(t.status));
3319
3033
  const results = await Promise.all(
3320
- activeThreads.map(async (thread) => {
3034
+ candidates.map(async (thread) => {
3321
3035
  try {
3322
3036
  const runs = await this.transport.listRuns(thread.thread_id, 5);
3323
- const running = Array.isArray(runs) ? runs.find((r) => r.status === "running" || r.status === "pending") : void 0;
3324
- return running ? { threadId: thread.thread_id, runId: String(running.run_id) } : null;
3037
+ if (!Array.isArray(runs) || runs.length === 0) return null;
3038
+ const latest = [...runs].sort(
3039
+ (a, b) => String(b?.created_at || "").localeCompare(String(a?.created_at || ""))
3040
+ )[0];
3041
+ return latest?.run_id ? { threadId: thread.thread_id, runId: String(latest.run_id) } : null;
3325
3042
  } catch (e) {
3326
3043
  console.warn("[ThreadDirectory] check running run failed", e);
3327
3044
  return null;
@@ -3353,7 +3070,7 @@ var ThreadDirectory = class {
3353
3070
  };
3354
3071
 
3355
3072
  // src/core/ChatCore.ts
3356
- var import_vue9 = require("vue");
3073
+ var import_vue8 = require("vue");
3357
3074
  function createChatCore(options) {
3358
3075
  const notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
3359
3076
  const directory = new ThreadDirectory({
@@ -3365,35 +3082,48 @@ function createChatCore(options) {
3365
3082
  notify,
3366
3083
  defaultThreadTitle: options.defaultThreadTitle
3367
3084
  });
3368
- const currentThreadId = (0, import_vue9.ref)(null);
3369
- const threads = (0, import_vue9.computed)(() => directory.threads.value);
3370
- const threadsPagination = (0, import_vue9.computed)(() => directory.threadsPagination.value);
3371
- const activeRuntime = (0, import_vue9.computed)(
3085
+ const currentThreadId = (0, import_vue8.ref)(null);
3086
+ const threads = (0, import_vue8.computed)(() => directory.threads.value);
3087
+ const threadsPagination = (0, import_vue8.computed)(() => directory.threadsPagination.value);
3088
+ const activeRuntime = (0, import_vue8.computed)(
3372
3089
  () => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
3373
3090
  );
3374
- const messages = (0, import_vue9.computed)(() => activeRuntime.value?.groups.value ?? []);
3375
- const isGenerating = (0, import_vue9.computed)(
3091
+ const view = (0, import_vue8.computed)(() => activeRuntime.value?.view.value ?? { turns: [] });
3092
+ const turns = (0, import_vue8.computed)(() => view.value.turns);
3093
+ const activeClarification = (0, import_vue8.computed)(
3094
+ () => activeRuntime.value?.activeClarification.value
3095
+ );
3096
+ const isGenerating = (0, import_vue8.computed)(
3376
3097
  () => !!activeRuntime.value && (activeRuntime.value.isGenerating.value || activeRuntime.value.isInitializing.value)
3377
3098
  );
3378
- const isLoadingThread = (0, import_vue9.computed)(() => activeRuntime.value?.isInitializing.value ?? false);
3379
- const runs = (0, import_vue9.computed)(
3099
+ const isLoadingThread = (0, import_vue8.computed)(() => activeRuntime.value?.isInitializing.value ?? false);
3100
+ const runs = (0, import_vue8.computed)(
3380
3101
  () => activeRuntime.value?.runs.value ?? /* @__PURE__ */ new Map()
3381
3102
  );
3382
- const toolCalls = (0, import_vue9.computed)(() => messages.value.flatMap((g) => g.tools));
3383
- const clarificationAnswers = (0, import_vue9.computed)(
3384
- () => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
3103
+ const toolCalls = (0, import_vue8.computed)(
3104
+ () => turns.value.flatMap(
3105
+ (t) => t.ai.flatMap(
3106
+ (seg) => seg.tools.map((tool, index) => ({
3107
+ id: tool.callId,
3108
+ call: { id: tool.callId, name: tool.name, args: tool.input },
3109
+ result: tool.result ? { content: tool.result } : void 0,
3110
+ state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
3111
+ index
3112
+ }))
3113
+ )
3114
+ )
3385
3115
  );
3386
- const activeInterrupt = (0, import_vue9.computed)(() => activeRuntime.value?.interrupt.value);
3387
- const hasPendingInterrupt = (0, import_vue9.computed)(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
3388
- const hasPendingClarification = (0, import_vue9.computed)(() => activeRuntime.value?.hasPendingClarification.value ?? false);
3389
- const inputDisabled = (0, import_vue9.computed)(
3390
- () => isGenerating.value || hasPendingClarification.value || hasPendingInterrupt.value
3116
+ const clarificationAnswers = (0, import_vue8.computed)(
3117
+ () => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
3391
3118
  );
3392
- const streamError = (0, import_vue9.computed)(() => activeRuntime.value?.streamError.value ?? null);
3393
- const hasMoreHistory = (0, import_vue9.computed)(() => activeRuntime.value?.hasMoreHistory.value ?? false);
3394
- const loadingHistory = (0, import_vue9.computed)(() => activeRuntime.value?.loadingHistory.value ?? false);
3395
- const tokenUsage = (0, import_vue9.computed)(() => activeRuntime.value?.tokenUsage.value ?? null);
3396
- const runningNotConnectedThreadIds = (0, import_vue9.computed)(() => directory.runningNotConnectedThreadIds.value);
3119
+ const activeInterrupt = (0, import_vue8.computed)(() => activeRuntime.value?.interrupt.value);
3120
+ const hasPendingInterrupt = (0, import_vue8.computed)(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
3121
+ const inputDisabled = (0, import_vue8.computed)(() => isGenerating.value || hasPendingInterrupt.value);
3122
+ const streamError = (0, import_vue8.computed)(() => activeRuntime.value?.streamError.value ?? null);
3123
+ const hasMoreHistory = (0, import_vue8.computed)(() => activeRuntime.value?.hasMoreHistory.value ?? false);
3124
+ const loadingHistory = (0, import_vue8.computed)(() => activeRuntime.value?.loadingHistory.value ?? false);
3125
+ const tokenUsage = (0, import_vue8.computed)(() => activeRuntime.value?.tokenUsage.value ?? null);
3126
+ const runningNotConnectedThreadIds = (0, import_vue8.computed)(() => directory.runningNotConnectedThreadIds.value);
3397
3127
  const getRunById = (runId) => runId ? runs.value.get(runId) : void 0;
3398
3128
  const getRunsByThreadId = (threadId) => threadId ? Array.from(runs.value.values()).filter((r) => r.threadId === threadId) : [];
3399
3129
  const ensureThreadId = async () => {
@@ -3432,8 +3162,6 @@ function createChatCore(options) {
3432
3162
  runtime.touch();
3433
3163
  if (isNew && thread) directory.prependThread(thread);
3434
3164
  await runtime.init();
3435
- const optimistic = runtime.createOptimisticHuman(trimmed, sendOptions);
3436
- runtime.appendOptimisticGroups([optimistic]);
3437
3165
  runtime.submit(trimmed, sendOptions);
3438
3166
  };
3439
3167
  const loadThread = async (threadId) => {
@@ -3446,31 +3174,19 @@ function createChatCore(options) {
3446
3174
  result.touch();
3447
3175
  await result.init();
3448
3176
  };
3449
- const regenerate = async (assistantMessageId) => {
3177
+ const regenerateTurn = async (aiSegmentId) => {
3450
3178
  if (isGenerating.value) return;
3451
- const list = messages.value;
3452
- const idx = list.findIndex((m) => m.id === assistantMessageId);
3453
- if (idx < 0) return;
3454
- let question;
3455
- let text = "";
3456
- for (const m of list.slice(0, idx).reverse()) {
3457
- if (m.type !== "human") continue;
3458
- const [t] = m.texts ?? [];
3459
- if (t) {
3460
- question = m;
3461
- text = t;
3462
- break;
3463
- }
3464
- }
3465
- if (!text) {
3179
+ const turn = turns.value.find((t) => t.ai.some((seg) => seg.id === aiSegmentId));
3180
+ const text = turn?.human.text ?? "";
3181
+ if (!turn || !text.trim()) {
3466
3182
  notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
3467
3183
  return;
3468
3184
  }
3469
- await sendMessage(text, { kwargs: { ...question?.additionalKwargs, hide_from_ui: false } });
3185
+ await sendMessage(text, { kwargs: { ...turn.human.kwargs ?? {}, hide_from_ui: false } });
3470
3186
  };
3471
3187
  return {
3472
- messages,
3473
- groupMessages: messages,
3188
+ view,
3189
+ turns,
3474
3190
  isGenerating,
3475
3191
  isLoadingThread,
3476
3192
  currentThreadId,
@@ -3481,6 +3197,7 @@ function createChatCore(options) {
3481
3197
  getRunById,
3482
3198
  getRunsByThreadId,
3483
3199
  clarificationAnswers,
3200
+ activeClarification,
3484
3201
  setClarificationAnswer: (toolCallId, answer) => activeRuntime.value?.setClarificationAnswer(toolCallId, answer),
3485
3202
  clearClarificationAnswers: () => activeRuntime.value?.clearClarificationAnswers(),
3486
3203
  sendMessage,
@@ -3489,11 +3206,12 @@ function createChatCore(options) {
3489
3206
  clearMessages: () => {
3490
3207
  currentThreadId.value = null;
3491
3208
  },
3492
- updateGroupMessage: (messageId, patch) => activeRuntime.value?.patchGroup(messageId, patch),
3493
- addOptimisticGroupMessages: (ms) => activeRuntime.value?.appendOptimisticGroups(ms),
3494
- updateGroupMessageBlocks: (messageId, blocks) => activeRuntime.value?.patchGroup(messageId, { blocks }),
3495
3209
  applyFeedback: (messageId, feedback) => activeRuntime.value?.applyFeedback(messageId, feedback),
3496
- regenerate,
3210
+ regenerateTurn,
3211
+ addOptimisticTurn: (body) => activeRuntime.value?.addOptimisticTurn(body),
3212
+ updateAiBody: (aiId, body) => activeRuntime.value?.updateAiBody(aiId, body),
3213
+ decorate: (messageId, patch) => activeRuntime.value?.decorate(messageId, patch),
3214
+ finalizeTurns: () => activeRuntime.value?.finalizeTurns(),
3497
3215
  fetchThreads: (reset, keyword) => directory.fetchThreads(reset, keyword),
3498
3216
  deleteThread: async (threadId) => {
3499
3217
  const deleted = await directory.deleteThread(threadId);
@@ -3506,8 +3224,8 @@ function createChatCore(options) {
3506
3224
  runningNotConnectedThreadIds,
3507
3225
  recoverRunningThreads: () => directory.recoverRunningThreads(),
3508
3226
  activeInterrupt,
3227
+ interrupt: activeInterrupt,
3509
3228
  hasPendingInterrupt,
3510
- hasPendingClarification,
3511
3229
  inputDisabled,
3512
3230
  streamError,
3513
3231
  hasMoreHistory,
@@ -3528,8 +3246,612 @@ function createChatCore(options) {
3528
3246
  };
3529
3247
  }
3530
3248
 
3249
+ // src/bridge/sse.ts
3250
+ function createFetchReaderFactory(fetchImpl = fetch) {
3251
+ return async (req) => {
3252
+ const res = await fetchImpl(req.url, {
3253
+ method: req.method,
3254
+ headers: req.headers,
3255
+ body: req.body !== void 0 ? JSON.stringify(req.body) : void 0,
3256
+ signal: req.signal,
3257
+ credentials: "include"
3258
+ });
3259
+ if (!res.ok) throw new Error(`SSE \u8BF7\u6C42\u5931\u8D25 ${res.status}`);
3260
+ if (!res.body) throw new Error("SSE \u54CD\u5E94\u65E0 body");
3261
+ const reader = res.body.getReader();
3262
+ return {
3263
+ read: () => reader.read(),
3264
+ cancel: async () => {
3265
+ reader.releaseLock();
3266
+ await res.body.cancel().catch(() => {
3267
+ });
3268
+ }
3269
+ };
3270
+ };
3271
+ }
3272
+ async function* parseSseFrames(reader) {
3273
+ const decoder = new TextDecoder();
3274
+ let buf = "";
3275
+ try {
3276
+ while (true) {
3277
+ let chunk;
3278
+ try {
3279
+ chunk = await reader.read();
3280
+ } catch (e) {
3281
+ if (e?.name === "AbortError") break;
3282
+ throw e;
3283
+ }
3284
+ if (chunk.done) break;
3285
+ buf += typeof chunk.value === "string" ? chunk.value : decoder.decode(chunk.value, { stream: true });
3286
+ let idx;
3287
+ while ((idx = buf.search(/\n\n|\r\n\r\n/)) !== -1) {
3288
+ const raw = buf.slice(0, idx);
3289
+ buf = buf.slice(idx).replace(/^\r?\n\r?\n/, "");
3290
+ const frame = parseFrame(raw);
3291
+ if (frame) yield frame;
3292
+ }
3293
+ }
3294
+ buf += decoder.decode();
3295
+ const tail = parseFrame(buf);
3296
+ if (tail) yield tail;
3297
+ } finally {
3298
+ await reader.cancel().catch(() => {
3299
+ });
3300
+ }
3301
+ }
3302
+ function parseFrame(raw) {
3303
+ if (!raw.trim()) return void 0;
3304
+ let event = "message";
3305
+ let id;
3306
+ const dataLines = [];
3307
+ for (const line of raw.split(/\r?\n/)) {
3308
+ if (line.startsWith("event:")) event = line.slice(6).trim();
3309
+ else if (line.startsWith("id:")) id = line.slice(3).trim();
3310
+ else if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
3311
+ }
3312
+ return { event, id, data: dataLines.join("\n") };
3313
+ }
3314
+
3315
+ // src/bridge/event-hub.ts
3316
+ function createEventHub() {
3317
+ const buffer = [];
3318
+ const subscribers = /* @__PURE__ */ new Set();
3319
+ let seq = 0;
3320
+ let closed = false;
3321
+ function publish(event) {
3322
+ if (closed) return;
3323
+ const n = ++seq;
3324
+ const framed = { ...event, seq: n, event_id: String(n) };
3325
+ buffer.push(framed);
3326
+ for (const sub of subscribers) {
3327
+ sub.queue.push(framed);
3328
+ sub.wake?.();
3329
+ }
3330
+ }
3331
+ function open() {
3332
+ const sub = { queue: [...buffer], wake: null, closed: false };
3333
+ if (closed) sub.closed = true;
3334
+ else subscribers.add(sub);
3335
+ const next = () => {
3336
+ if (sub.closed) return Promise.resolve({ done: true, value: void 0 });
3337
+ const queued = sub.queue.shift();
3338
+ if (queued) return Promise.resolve({ done: false, value: queued });
3339
+ return new Promise((resolve) => {
3340
+ sub.wake = () => {
3341
+ sub.wake = null;
3342
+ const v = sub.queue.shift();
3343
+ if (sub.closed || !v) return resolve({ done: true, value: void 0 });
3344
+ resolve({ done: false, value: v });
3345
+ };
3346
+ });
3347
+ };
3348
+ const returnFn = () => {
3349
+ if (!sub.closed) {
3350
+ sub.closed = true;
3351
+ subscribers.delete(sub);
3352
+ sub.wake?.();
3353
+ }
3354
+ return Promise.resolve({ done: true, value: void 0 });
3355
+ };
3356
+ return {
3357
+ events: { [Symbol.asyncIterator]: () => ({ next, return: returnFn }) },
3358
+ ready: Promise.resolve(),
3359
+ close() {
3360
+ returnFn();
3361
+ }
3362
+ };
3363
+ }
3364
+ function close() {
3365
+ if (closed) return;
3366
+ closed = true;
3367
+ for (const sub of subscribers) {
3368
+ sub.closed = true;
3369
+ sub.wake?.();
3370
+ }
3371
+ subscribers.clear();
3372
+ }
3373
+ return {
3374
+ publish,
3375
+ open,
3376
+ close,
3377
+ get bufferedCount() {
3378
+ return buffer.length;
3379
+ }
3380
+ };
3381
+ }
3382
+
3383
+ // src/bridge/translate.ts
3384
+ var V1FrameTranslator = class {
3385
+ constructor(options) {
3386
+ /** 当前 run 是否处于 interrupt 待恢复态(end 帧据此选 terminal) */
3387
+ this.interrupted = false;
3388
+ this.pendingInterrupts = 0;
3389
+ this.lastError = null;
3390
+ /** 已开始消息的组装状态,key = message id */
3391
+ this.started = /* @__PURE__ */ new Map();
3392
+ /** tools 通道防重:已合成 tool-started / tool-finished 的 callId(values 帧全量重放,须去重) */
3393
+ this.toolsStarted = /* @__PURE__ */ new Set();
3394
+ this.toolsFinished = /* @__PURE__ */ new Set();
3395
+ this.push = options.push;
3396
+ this.onMetadata = options.onMetadata;
3397
+ }
3398
+ /** 分发一个 v1 SSE 帧 */
3399
+ handleFrame(event, dataRaw) {
3400
+ let data;
3401
+ try {
3402
+ data = dataRaw ? JSON.parse(dataRaw) : void 0;
3403
+ } catch {
3404
+ return;
3405
+ }
3406
+ switch (event) {
3407
+ case "metadata":
3408
+ if (data && typeof data === "object") this.onMetadata?.(data);
3409
+ break;
3410
+ case "values":
3411
+ this.handleValues(data);
3412
+ break;
3413
+ case "messages":
3414
+ this.handleMessages(data);
3415
+ break;
3416
+ case "updates":
3417
+ if (data && typeof data === "object") {
3418
+ for (const [node, delta] of Object.entries(data)) {
3419
+ this.emit("updates", { node, values: delta });
3420
+ }
3421
+ }
3422
+ break;
3423
+ case "custom":
3424
+ this.emit("custom", { name: "custom", payload: data });
3425
+ break;
3426
+ case "error":
3427
+ this.lastError = typeof data === "string" ? data : data?.message ?? String(data);
3428
+ break;
3429
+ case "end":
3430
+ this.emit("lifecycle", {
3431
+ event: this.interrupted ? "interrupted" : this.lastError ? "failed" : "completed",
3432
+ ...this.lastError ? { error: this.lastError } : {}
3433
+ });
3434
+ break;
3435
+ default:
3436
+ break;
3437
+ }
3438
+ }
3439
+ /** values 帧:剥离 __interrupt__ → values 事件 + 合成 input.requested + 合成 tools 通道事件 */
3440
+ handleValues(data) {
3441
+ if (!data || typeof data !== "object") return;
3442
+ const values = { ...data };
3443
+ const interrupts = values.__interrupt__;
3444
+ if (Array.isArray(interrupts) && interrupts.length > 0) {
3445
+ delete values.__interrupt__;
3446
+ this.interrupted = true;
3447
+ this.pendingInterrupts += interrupts.length;
3448
+ interrupts.forEach((it, i) => {
3449
+ this.emit("input.requested", {
3450
+ // v1 的 Interrupt 无稳定 id,按序号合成;resume 走值语义不依赖该 id
3451
+ interrupt_id: `intr-${this.pendingInterrupts}-${i}`,
3452
+ payload: it?.value ?? it
3453
+ });
3454
+ });
3455
+ }
3456
+ this.emit("values", values);
3457
+ this.synthesizeTools(values);
3458
+ }
3459
+ /**
3460
+ * 从 values 快照合成 v2 tools 通道事件(toolCalls 投影只认 tool-started/tool-finished):
3461
+ * - AIMessage.tool_calls(args 已完整)→ tool-started
3462
+ * - ToolMessage(工具结果)→ tool-finished
3463
+ * values 每步全量重放,必须按 callId 防重;AI 消息在 tool 消息之前,顺序天然满足。
3464
+ */
3465
+ synthesizeTools(values) {
3466
+ const messages = Array.isArray(values.messages) ? values.messages : [];
3467
+ for (const m of messages) {
3468
+ if (!m || typeof m !== "object") continue;
3469
+ const toolCalls = Array.isArray(m.tool_calls) ? m.tool_calls : [];
3470
+ for (const tc of toolCalls) {
3471
+ const callId2 = tc?.id;
3472
+ if (!callId2 || this.toolsStarted.has(callId2)) continue;
3473
+ this.toolsStarted.add(callId2);
3474
+ this.emit("tools", {
3475
+ event: "tool-started",
3476
+ tool_call_id: String(callId2),
3477
+ tool_name: String(tc?.name ?? ""),
3478
+ input: tc?.args
3479
+ });
3480
+ }
3481
+ const callId = m.tool_call_id;
3482
+ if (m.type === "tool" && typeof callId === "string" && callId && !this.toolsFinished.has(callId)) {
3483
+ this.toolsFinished.add(callId);
3484
+ this.emit("tools", { event: "tool-finished", tool_call_id: callId, output: contentToText(m.content) });
3485
+ }
3486
+ }
3487
+ }
3488
+ /** messages 帧:增量 chunk → message-start(一次) + content-block 事件序列 */
3489
+ handleMessages(tuple) {
3490
+ const chunk = tuple?.[0];
3491
+ if (!chunk) return;
3492
+ if (String(chunk.type || "").toLowerCase() === "remove") return;
3493
+ const node = tuple?.[1]?.langgraph_node;
3494
+ const id = chunk.id;
3495
+ if (!id) return;
3496
+ let st = this.started.get(id);
3497
+ if (!st) {
3498
+ st = { textBlockStarted: false, toolBlockIndexes: /* @__PURE__ */ new Set() };
3499
+ this.started.set(id, st);
3500
+ this.emit(
3501
+ "messages",
3502
+ {
3503
+ event: "message-start",
3504
+ role: roleOf(chunk.type),
3505
+ id,
3506
+ ...chunk.tool_call_id ? { tool_call_id: chunk.tool_call_id } : {}
3507
+ },
3508
+ node
3509
+ );
3510
+ }
3511
+ const text = contentToText(chunk.content);
3512
+ if (text) {
3513
+ if (!st.textBlockStarted) {
3514
+ st.textBlockStarted = true;
3515
+ this.emit("messages", { event: "content-block-start", index: 0, content: { type: "text", text: "" } }, node);
3516
+ }
3517
+ this.emit("messages", { event: "content-block-delta", index: 0, delta: { type: "text-delta", text } }, node);
3518
+ }
3519
+ const tccs = chunk.tool_call_chunks ?? [];
3520
+ tccs.forEach((tc, i) => {
3521
+ if (!tc) return;
3522
+ const index = 1 + i;
3523
+ if (!st.toolBlockIndexes.has(index)) {
3524
+ st.toolBlockIndexes.add(index);
3525
+ this.emit(
3526
+ "messages",
3527
+ {
3528
+ event: "content-block-start",
3529
+ index,
3530
+ content: { type: "tool_call_chunk", id: tc.id, name: tc.name ?? "", args: "" }
3531
+ },
3532
+ node
3533
+ );
3534
+ }
3535
+ if (tc.args) {
3536
+ this.emit(
3537
+ "messages",
3538
+ { event: "content-block-delta", index, delta: { type: "tool-call-delta", args: tc.args } },
3539
+ node
3540
+ );
3541
+ }
3542
+ });
3543
+ }
3544
+ /** 产出一条未编号的协议事件(编号由事件中枢统一分配) */
3545
+ emit(method, data, node) {
3546
+ this.push({
3547
+ type: "event",
3548
+ method,
3549
+ params: {
3550
+ namespace: [],
3551
+ timestamp: Date.now(),
3552
+ ...node ? { node } : {},
3553
+ data
3554
+ }
3555
+ });
3556
+ }
3557
+ };
3558
+ function roleOf(type) {
3559
+ const t = (type ?? "").toLowerCase();
3560
+ if (t.includes("human")) return "human";
3561
+ if (t.includes("system")) return "system";
3562
+ if (t.includes("tool")) return "tool";
3563
+ return "ai";
3564
+ }
3565
+ function contentToText(content) {
3566
+ if (typeof content === "string") return content;
3567
+ if (!Array.isArray(content)) return "";
3568
+ return content.map((b) => typeof b === "string" ? b : b?.text ?? b?.content ?? "").filter(Boolean).join("");
3569
+ }
3570
+
3571
+ // src/bridge/history.ts
3572
+ var PAGE_LIMIT = 200;
3573
+ var MAX_PAGES = 50;
3574
+ async function fetchAllPageMessages(apiUrl, threadId, buildHeaders, fetchImpl) {
3575
+ const newerPages = [];
3576
+ let beforeSeq;
3577
+ for (let i = 0; i < MAX_PAGES; i++) {
3578
+ const params = new URLSearchParams({ limit: String(PAGE_LIMIT) });
3579
+ if (beforeSeq !== void 0) params.set("before_seq", String(beforeSeq));
3580
+ const res = await fetchImpl(`${apiUrl}/threads/${threadId}/messages/page?${params.toString()}`, {
3581
+ method: "GET",
3582
+ headers: { "Content-Type": "application/json", Accept: "application/json", ...await buildHeaders() },
3583
+ credentials: "include"
3584
+ });
3585
+ if (!res.ok) break;
3586
+ const payload = await res.json();
3587
+ const rows = (Array.isArray(payload) ? payload : payload?.messages ?? payload?.data) ?? [];
3588
+ const pageMessages = runMessagesToMessages(
3589
+ rows.map(toRunMessage).filter((m) => m !== null)
3590
+ );
3591
+ newerPages.push(pageMessages);
3592
+ if (!payload?.has_more || payload.next_before_seq === void 0) break;
3593
+ beforeSeq = payload.next_before_seq;
3594
+ }
3595
+ return newerPages.reverse().flat();
3596
+ }
3597
+
3598
+ // src/bridge/run-stream.ts
3599
+ async function startRunStream(host, command, opts) {
3600
+ const params = command.params ?? {};
3601
+ const assistantId = params.assistant_id && params.assistant_id !== "_" ? params.assistant_id : opts.assistantId;
3602
+ const body = {
3603
+ assistant_id: assistantId,
3604
+ // v1 公开流模式:values 为权威状态、messages-tuple 为 token 增量、custom 为进度
3605
+ stream_mode: ["values", "messages-tuple", "custom"],
3606
+ // 断开(刷新/断网)后 run 在后端继续执行。⚠️ 后端缺省 cancel(run_models.py:
3607
+ // on_disconnect 默认 "cancel"),不传会在 SSE 断开时中断 run——刷新后 join 只能拿
3608
+ // 到 end 帧。调用方 submitOptions.onDisconnect 会被 SDK v2 submit 链丢弃(自定义
3609
+ // transport 通道不识别该字段),故在此固定补上(对齐旧 v1 管道 sse.ts 语义)。
3610
+ on_disconnect: "continue",
3611
+ // ⚠️ 不传 stream_resumable:后端仅接受 False/None,显式 True 会被 400 拒绝
3612
+ //(run_models.py reject_resumable_streams 校验器)。
3613
+ ...params.config ? { config: params.config } : {}
3614
+ };
3615
+ if (opts.isResume)
3616
+ body.command = { resume: opts.explicitResume !== void 0 ? opts.explicitResume : params.input ?? null };
3617
+ else body.input = params.input;
3618
+ const ac = host.replaceAbort();
3619
+ try {
3620
+ const reader = await host.readerFactory({
3621
+ url: opts.url,
3622
+ method: "POST",
3623
+ headers: { "Content-Type": "application/json", ...await host.buildHeaders() },
3624
+ body,
3625
+ signal: ac.signal
3626
+ });
3627
+ if (host.isDisposed()) {
3628
+ await reader.cancel().catch(() => {
3629
+ });
3630
+ return { type: "success", id: command.id, result: {} };
3631
+ }
3632
+ const location = reader.headers?.get("Content-Location") ?? "";
3633
+ const runId = location ? location.split("/").pop() ?? "" : "";
3634
+ if (runId) host.setRunId(runId);
3635
+ host.lifecycle("running");
3636
+ void pumpRunStream(host, reader, ac, opts.isResume);
3637
+ return { type: "success", id: command.id, result: runId ? { run_id: runId } : {} };
3638
+ } catch (e) {
3639
+ if (ac.signal.aborted) return { type: "success", id: command.id, result: {} };
3640
+ return host.cmdError(command.id, `runs/stream \u8BF7\u6C42\u5931\u8D25\uFF1A${e?.message ?? e}`);
3641
+ }
3642
+ }
3643
+ async function pumpRunStream(host, reader, ac, wasResume) {
3644
+ const translator = new V1FrameTranslator({
3645
+ push: (event) => host.publish(event),
3646
+ // G10:首帧 metadata 的 run_id 权威(Content-Location 缺失时兜底)
3647
+ onMetadata: (meta) => {
3648
+ const runId = meta?.run_id;
3649
+ if (typeof runId === "string" && runId) host.setRunIdIfEmpty(runId);
3650
+ }
3651
+ });
3652
+ try {
3653
+ for await (const frame of parseSseFrames(reader)) {
3654
+ if (frame.event === "values" && host.onValuesFrame) {
3655
+ try {
3656
+ const raw = frame.data ? JSON.parse(frame.data) : void 0;
3657
+ if (raw && typeof raw === "object") host.onValuesFrame(raw);
3658
+ } catch {
3659
+ }
3660
+ }
3661
+ translator.handleFrame(frame.event, frame.data);
3662
+ if (frame.event === "end") break;
3663
+ }
3664
+ } catch (e) {
3665
+ if (!ac.signal.aborted) host.lifecycle("failed", String(e?.message ?? e));
3666
+ return;
3667
+ }
3668
+ if (translator.interrupted) host.setInterrupted();
3669
+ else if (!wasResume) host.clearInterrupted();
3670
+ host.clearAbort(ac);
3671
+ }
3672
+
3673
+ // src/bridge/adapter.ts
3674
+ var _boundThreadId, _getThreadId, _lastRunId;
3675
+ var DeerFlowBridgeAdapter = class {
3676
+ constructor(options) {
3677
+ __privateAdd(this, _boundThreadId, "");
3678
+ __privateAdd(this, _getThreadId);
3679
+ __privateAdd(this, _lastRunId, "");
3680
+ /** 已确认存在的 thread(避免重复预创建) */
3681
+ this.knownThreads = /* @__PURE__ */ new Set();
3682
+ /** 线程处于 interrupt 待恢复态:下一个 run.start / input.respond 按 resume 翻译 */
3683
+ this.interrupted = false;
3684
+ this.activeAbort = null;
3685
+ this.disposed = false;
3686
+ this.apiUrl = options.apiUrl.replace(/\/$/, "");
3687
+ this.assistantId = options.assistantId;
3688
+ this.buildHeaders = options.buildHeaders;
3689
+ this.fetchImpl = options.fetchImpl;
3690
+ this.onValuesFrame = options.onValuesFrame;
3691
+ this.onRunId = options.onRunId;
3692
+ __privateSet(this, _getThreadId, options.getThreadId);
3693
+ this.hub = createEventHub();
3694
+ this.streamHost = {
3695
+ buildHeaders: () => this.buildHeaders(),
3696
+ readerFactory: options.readerFactory ?? createFetchReaderFactory(options.fetchImpl),
3697
+ onValuesFrame: this.onValuesFrame,
3698
+ publish: (event) => this.hub.publish(event),
3699
+ lifecycle: (event, error) => this.lifecycle(event, error),
3700
+ setRunId: (runId) => {
3701
+ __privateSet(this, _lastRunId, runId);
3702
+ this.onRunId?.(runId);
3703
+ },
3704
+ setRunIdIfEmpty: (runId) => {
3705
+ if (!__privateGet(this, _lastRunId)) {
3706
+ __privateSet(this, _lastRunId, runId);
3707
+ this.onRunId?.(runId);
3708
+ }
3709
+ },
3710
+ setInterrupted: () => {
3711
+ this.interrupted = true;
3712
+ },
3713
+ clearInterrupted: () => {
3714
+ this.interrupted = false;
3715
+ },
3716
+ isDisposed: () => this.disposed,
3717
+ replaceAbort: () => {
3718
+ this.activeAbort?.abort();
3719
+ const ac = new AbortController();
3720
+ this.activeAbort = ac;
3721
+ return ac;
3722
+ },
3723
+ clearAbort: (ac) => {
3724
+ if (this.activeAbort === ac) this.activeAbort = null;
3725
+ },
3726
+ cmdError: (id, message, error) => this.cmdError(id, message, error)
3727
+ };
3728
+ }
3729
+ /** 当前生效的 threadId:外部 getter 优先(hydrate 早于 transport 绑定),setThreadId 兜底 */
3730
+ get threadId() {
3731
+ return __privateGet(this, _getThreadId).call(this) || __privateGet(this, _boundThreadId);
3732
+ }
3733
+ /** metadata 帧记录的 run_id(首帧权威,G10;Content-Location 优先时两者一致) */
3734
+ get lastRunId() {
3735
+ return __privateGet(this, _lastRunId);
3736
+ }
3737
+ /** 线程是否处于 interrupt 待恢复态(下一次 send 自动走 command.resume;观测/测试用) */
3738
+ get isInterrupted() {
3739
+ return this.interrupted;
3740
+ }
3741
+ /** {@inheritDoc TransportAdapter.setThreadId} */
3742
+ setThreadId(threadId) {
3743
+ __privateSet(this, _boundThreadId, threadId);
3744
+ }
3745
+ /** HTTP/SSE 传输无握手 */
3746
+ open() {
3747
+ return Promise.resolve();
3748
+ }
3749
+ /** 释放资源:断开进行中的 SSE,关闭事件中枢(唤醒挂起订阅) */
3750
+ close() {
3751
+ this.disposed = true;
3752
+ this.activeAbort?.abort();
3753
+ this.hub.close();
3754
+ return Promise.resolve();
3755
+ }
3756
+ /** SSE 模式下 events() 为空流,真实投递走 openEventStream */
3757
+ async *events() {
3758
+ }
3759
+ /** 发送协议命令:run.start / input.respond → v1 runs.stream,其余拒绝 */
3760
+ async send(command) {
3761
+ switch (command.method) {
3762
+ case "run.start":
3763
+ return this.startRun(command, this.interrupted);
3764
+ case "input.respond": {
3765
+ const p = command.params ?? {};
3766
+ const resume = Array.isArray(p.responses) ? p.responses[0]?.response : p.response;
3767
+ this.interrupted = false;
3768
+ return this.startRun(command, true, resume);
3769
+ }
3770
+ default:
3771
+ return this.cmdError(command.id, `deer-flow v1 \u6865\u63A5\u6682\u4E0D\u652F\u6301\u547D\u4EE4\uFF1A${command.method}`, "not_supported");
3772
+ }
3773
+ }
3774
+ /** 打开订阅流:事件中枢重放缓冲全量回放后实时推送 */
3775
+ openEventStream(_params) {
3776
+ return this.hub.open();
3777
+ }
3778
+ /** hydrate 用:/state 与 messages/page 全量并发;messages 以 state 为基准(语义字段全),
3779
+ * page(run-event 全量投影)补齐压缩缺失的头部/尾部——与 transport 的
3780
+ * fetchThreadInitialValues 同一合并函数,保证 SDK getState 快照与物化器基线一致
3781
+ * (不一致会让 watch(stream.messages) 的 diff 把快照差异误追加到对话尾部) */
3782
+ async getState() {
3783
+ if (!this.threadId) return null;
3784
+ try {
3785
+ const [res, pageMessages] = await Promise.all([
3786
+ this.request(`/threads/${this.threadId}/state`, { method: "GET" }),
3787
+ fetchAllPageMessages(this.apiUrl, this.threadId, this.buildHeaders, this.fetchImpl).catch(() => [])
3788
+ ]);
3789
+ if (!res.ok) return null;
3790
+ const json = await res.json();
3791
+ const values = { ...json.values ?? {} };
3792
+ const stateMessages = extractStateMessages(json);
3793
+ if (stateMessages.length > 0 || pageMessages.length > 0) {
3794
+ values.messages = mergeStateWithPageMessages(stateMessages, pageMessages);
3795
+ }
3796
+ if (Array.isArray(values.__interrupt__) && values.__interrupt__.length > 0) {
3797
+ this.interrupted = true;
3798
+ delete values.__interrupt__;
3799
+ }
3800
+ if (Array.isArray(json.tasks) && json.tasks.some((t) => Array.isArray(t?.interrupts) && t.interrupts.length > 0))
3801
+ this.interrupted = true;
3802
+ return { values, tasks: json.tasks, next: json.next, checkpoint: null };
3803
+ } catch {
3804
+ return null;
3805
+ }
3806
+ }
3807
+ // ---- 内部实现 ----
3808
+ /** run.start / input.respond 落点:预创建 thread 后交 run-stream 打开 SSE 泵帧 */
3809
+ async startRun(command, isResume, explicitResume) {
3810
+ await this.ensureThread(this.threadId);
3811
+ return startRunStream(this.streamHost, command, {
3812
+ url: `${this.apiUrl}/threads/${this.threadId}/runs/stream`,
3813
+ assistantId: this.assistantId,
3814
+ isResume,
3815
+ ...explicitResume !== void 0 ? { explicitResume } : {}
3816
+ });
3817
+ }
3818
+ /** 统一 REST 请求入口:注入鉴权头 + cookie */
3819
+ async request(path, init = {}) {
3820
+ const headers = await this.buildHeaders();
3821
+ return this.fetchImpl(this.apiUrl + path, {
3822
+ ...init,
3823
+ headers: { "Content-Type": "application/json", ...headers },
3824
+ credentials: "include"
3825
+ });
3826
+ }
3827
+ /** 预创建 thread(deer-flow POST /threads 支持客户端指定 id 且幂等) */
3828
+ async ensureThread(threadId) {
3829
+ if (!threadId || this.knownThreads.has(threadId)) return;
3830
+ try {
3831
+ const res = await this.request("/threads", {
3832
+ method: "POST",
3833
+ body: JSON.stringify({ thread_id: threadId, metadata: {} })
3834
+ });
3835
+ if (res.ok) this.knownThreads.add(threadId);
3836
+ } catch {
3837
+ }
3838
+ }
3839
+ /** 构造命令错误应答 */
3840
+ cmdError(id, message, error = "unknown_error") {
3841
+ return { type: "error", id, message, error };
3842
+ }
3843
+ /** 推送 lifecycle 事件(running / failed) */
3844
+ lifecycle(event, error) {
3845
+ const data = error ? { event, error } : { event };
3846
+ this.hub.publish({ type: "event", method: "lifecycle", params: { namespace: [], timestamp: Date.now(), data } });
3847
+ }
3848
+ };
3849
+ _boundThreadId = new WeakMap();
3850
+ _getThreadId = new WeakMap();
3851
+ _lastRunId = new WeakMap();
3852
+
3531
3853
  // src/test-utils/mockTransport.ts
3532
- var import_vue10 = require("vue");
3854
+ var import_vue9 = require("vue");
3533
3855
  var mockThreadSeq = 0;
3534
3856
  function createMockTransport() {
3535
3857
  const threads = [];
@@ -3620,8 +3942,8 @@ function createMockTransport() {
3620
3942
  return content;
3621
3943
  },
3622
3944
  createStream(options) {
3623
- const isLoading = (0, import_vue10.ref)(false);
3624
- const error = (0, import_vue10.ref)(null);
3945
+ const isLoading = (0, import_vue9.ref)(false);
3946
+ const error = (0, import_vue9.ref)(null);
3625
3947
  const threadId = options.threadId;
3626
3948
  optionsMap.set(threadId, options);
3627
3949
  const handle = {
@@ -3716,18 +4038,18 @@ var CORE_VERSION = "2.0.0";
3716
4038
  DEFAULT_ASSISTANT_ID,
3717
4039
  DEFAULT_MAX_CACHED_SESSIONS,
3718
4040
  DEFAULT_MAX_CONCURRENT_STREAMS,
3719
- DEFAULT_TWIN_TOOL_PREFIX,
4041
+ DeerFlowBridgeAdapter,
3720
4042
  INJECTED_TAGS,
3721
4043
  MESSAGE_TYPE_NORMALIZE,
3722
4044
  OUTLINE_MAX_LEVEL,
3723
4045
  ThreadDirectory,
3724
- buildAiGroup,
4046
+ V1FrameTranslator,
4047
+ applySemanticPatches,
4048
+ backfillRunMessageFeedback,
3725
4049
  buildArtifactFiles,
3726
4050
  buildHitlDecisions,
3727
- buildHumanGroup,
3728
4051
  buildHumanInputResponse,
3729
4052
  buildInterruptReviewBlock,
3730
- buildInterruptReviewGroup,
3731
4053
  buildRejectDecisions,
3732
4054
  buildReportBodyPayload,
3733
4055
  buildReportOutlinePayload,
@@ -3735,15 +4057,16 @@ var CORE_VERSION = "2.0.0";
3735
4057
  buildRunInfo,
3736
4058
  collectTextKeepSxin,
3737
4059
  collectVisibleText,
3738
- createBlockBuilderLite,
3739
4060
  createChatCore,
3740
4061
  createEmptySubChapter,
3741
- createGroupDeriver,
4062
+ createEventHub,
4063
+ createFetchReaderFactory,
4064
+ createMaterializer,
4065
+ createMessageDiff,
3742
4066
  createMockTransport,
3743
- createOptimisticHuman,
3744
- createStreamPump,
4067
+ createRuntimeMaterializer,
4068
+ createSemanticOverlay,
3745
4069
  createThreadRuntime,
3746
- createViewModelState,
3747
4070
  deriveToolsFromMessages,
3748
4071
  ensureOutlineContentThemes,
3749
4072
  ensureRunningRun,
@@ -3752,14 +4075,17 @@ var CORE_VERSION = "2.0.0";
3752
4075
  extractBlocksFromNodes,
3753
4076
  extractCitationAnchors,
3754
4077
  extractCitationAnchorsFromSpec,
4078
+ extractFromToolResult,
3755
4079
  extractReportTitleFromBody,
3756
4080
  extractRunEnrichment,
4081
+ extractSemanticPatchesFromMessages,
3757
4082
  extractStateMessages,
3758
4083
  extractTextFromMessage,
3759
4084
  extractThreadInfo,
3760
4085
  extractTitleFromArtifactPath,
3761
4086
  extractUserMessageTexts,
3762
- foldMessages,
4087
+ fetchAllPageMessages,
4088
+ formatAnswerText,
3763
4089
  formatStr,
3764
4090
  genBlockId,
3765
4091
  genMessageId,
@@ -3767,8 +4093,6 @@ var CORE_VERSION = "2.0.0";
3767
4093
  getHumanMessageBaseId,
3768
4094
  getToolCallArtifactMeta,
3769
4095
  isAiMessage,
3770
- isClarificationAnswered,
3771
- isClarificationBlock,
3772
4096
  isHiddenUserMessage,
3773
4097
  isHumanMessage,
3774
4098
  isInjectedElement,
@@ -3777,6 +4101,7 @@ var CORE_VERSION = "2.0.0";
3777
4101
  isToolMessage,
3778
4102
  isVisibleUserMessage,
3779
4103
  isWriteFileToolName,
4104
+ mergeStateWithPageMessages,
3780
4105
  normalizeForCompare,
3781
4106
  normalizeMessageType,
3782
4107
  normalizeOutline,
@@ -3785,11 +4110,13 @@ var CORE_VERSION = "2.0.0";
3785
4110
  parseHumanMessageId,
3786
4111
  parseKnowledgeItemsFromValue,
3787
4112
  parseMarkdownToOutline,
4113
+ parseSseFrames,
3788
4114
  pickRunMessageMetadata,
3789
4115
  readMessageContentText,
3790
4116
  resolveReportArtifactKind,
3791
4117
  runMessagesToMessages,
3792
4118
  simpleHash,
4119
+ sliceBodySegments,
3793
4120
  stateMessagesToRunMessages,
3794
4121
  toRunMessage,
3795
4122
  tokenizeSxin,