@cqfe/sxin-chat-core 1.0.0 → 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/{ChatCore-DyjH-HBV.d.cts → ChatCore-cSM1HmXp.d.cts} +410 -337
- package/dist/{ChatCore-DyjH-HBV.d.ts → ChatCore-cSM1HmXp.d.ts} +410 -337
- package/dist/chunk-Z65C2UII.mjs +2830 -0
- package/dist/index.cjs +1861 -1520
- package/dist/index.d.cts +628 -235
- package/dist/index.d.ts +628 -235
- package/dist/index.mjs +1001 -143
- package/dist/vue/index.cjs +1449 -2185
- package/dist/vue/index.d.cts +2 -2
- package/dist/vue/index.d.ts +2 -2
- package/dist/vue/index.mjs +1 -1
- package/package.json +4 -4
- package/dist/chunk-NLL3XGEI.mjs +0 -3378
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,49 +31,54 @@ __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
|
-
|
|
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
|
-
|
|
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,
|
|
42
49
|
buildRunDirectLatencyMs: () => buildRunDirectLatencyMs,
|
|
43
50
|
buildRunInfo: () => buildRunInfo,
|
|
44
|
-
collectCitation: () => collectCitation,
|
|
45
51
|
collectTextKeepSxin: () => collectTextKeepSxin,
|
|
46
52
|
collectVisibleText: () => collectVisibleText,
|
|
47
|
-
createBlockBuilderLite: () => createBlockBuilderLite,
|
|
48
53
|
createChatCore: () => createChatCore,
|
|
49
54
|
createEmptySubChapter: () => createEmptySubChapter,
|
|
50
|
-
|
|
55
|
+
createEventHub: () => createEventHub,
|
|
56
|
+
createFetchReaderFactory: () => createFetchReaderFactory,
|
|
57
|
+
createMaterializer: () => createMaterializer,
|
|
58
|
+
createMessageDiff: () => createMessageDiff,
|
|
51
59
|
createMockTransport: () => createMockTransport,
|
|
52
|
-
|
|
53
|
-
|
|
60
|
+
createRuntimeMaterializer: () => createRuntimeMaterializer,
|
|
61
|
+
createSemanticOverlay: () => createSemanticOverlay,
|
|
54
62
|
createThreadRuntime: () => createThreadRuntime,
|
|
55
|
-
createViewModelState: () => createViewModelState,
|
|
56
63
|
deriveToolsFromMessages: () => deriveToolsFromMessages,
|
|
57
64
|
ensureOutlineContentThemes: () => ensureOutlineContentThemes,
|
|
58
65
|
ensureRunningRun: () => ensureRunningRun,
|
|
59
66
|
extractAiContentFromMessage: () => extractAiContentFromMessage,
|
|
60
67
|
extractBlocksFromContent: () => extractBlocksFromContent,
|
|
61
68
|
extractBlocksFromNodes: () => extractBlocksFromNodes,
|
|
69
|
+
extractCitationAnchors: () => extractCitationAnchors,
|
|
70
|
+
extractCitationAnchorsFromSpec: () => extractCitationAnchorsFromSpec,
|
|
71
|
+
extractFromToolResult: () => extractFromToolResult,
|
|
62
72
|
extractReportTitleFromBody: () => extractReportTitleFromBody,
|
|
63
73
|
extractRunEnrichment: () => extractRunEnrichment,
|
|
74
|
+
extractSemanticPatchesFromMessages: () => extractSemanticPatchesFromMessages,
|
|
64
75
|
extractStateMessages: () => extractStateMessages,
|
|
65
76
|
extractTextFromMessage: () => extractTextFromMessage,
|
|
66
77
|
extractThreadInfo: () => extractThreadInfo,
|
|
67
78
|
extractTitleFromArtifactPath: () => extractTitleFromArtifactPath,
|
|
68
79
|
extractUserMessageTexts: () => extractUserMessageTexts,
|
|
69
|
-
|
|
80
|
+
fetchAllPageMessages: () => fetchAllPageMessages,
|
|
81
|
+
formatAnswerText: () => formatAnswerText,
|
|
70
82
|
formatStr: () => formatStr,
|
|
71
83
|
genBlockId: () => genBlockId,
|
|
72
84
|
genMessageId: () => genMessageId,
|
|
@@ -74,8 +86,6 @@ __export(src_exports, {
|
|
|
74
86
|
getHumanMessageBaseId: () => getHumanMessageBaseId,
|
|
75
87
|
getToolCallArtifactMeta: () => getToolCallArtifactMeta,
|
|
76
88
|
isAiMessage: () => isAiMessage,
|
|
77
|
-
isClarificationAnswered: () => isClarificationAnswered,
|
|
78
|
-
isClarificationBlock: () => isClarificationBlock,
|
|
79
89
|
isHiddenUserMessage: () => isHiddenUserMessage,
|
|
80
90
|
isHumanMessage: () => isHumanMessage,
|
|
81
91
|
isInjectedElement: () => isInjectedElement,
|
|
@@ -84,6 +94,7 @@ __export(src_exports, {
|
|
|
84
94
|
isToolMessage: () => isToolMessage,
|
|
85
95
|
isVisibleUserMessage: () => isVisibleUserMessage,
|
|
86
96
|
isWriteFileToolName: () => isWriteFileToolName,
|
|
97
|
+
mergeStateWithPageMessages: () => mergeStateWithPageMessages,
|
|
87
98
|
normalizeForCompare: () => normalizeForCompare,
|
|
88
99
|
normalizeMessageType: () => normalizeMessageType,
|
|
89
100
|
normalizeOutline: () => normalizeOutline,
|
|
@@ -92,11 +103,13 @@ __export(src_exports, {
|
|
|
92
103
|
parseHumanMessageId: () => parseHumanMessageId,
|
|
93
104
|
parseKnowledgeItemsFromValue: () => parseKnowledgeItemsFromValue,
|
|
94
105
|
parseMarkdownToOutline: () => parseMarkdownToOutline,
|
|
106
|
+
parseSseFrames: () => parseSseFrames,
|
|
95
107
|
pickRunMessageMetadata: () => pickRunMessageMetadata,
|
|
96
108
|
readMessageContentText: () => readMessageContentText,
|
|
97
109
|
resolveReportArtifactKind: () => resolveReportArtifactKind,
|
|
98
110
|
runMessagesToMessages: () => runMessagesToMessages,
|
|
99
111
|
simpleHash: () => simpleHash,
|
|
112
|
+
sliceBodySegments: () => sliceBodySegments,
|
|
100
113
|
stateMessagesToRunMessages: () => stateMessagesToRunMessages,
|
|
101
114
|
toRunMessage: () => toRunMessage,
|
|
102
115
|
tokenizeSxin: () => tokenizeSxin,
|
|
@@ -109,117 +122,6 @@ var DEFAULT_MAX_CACHED_SESSIONS = 10;
|
|
|
109
122
|
var DEFAULT_MAX_CONCURRENT_STREAMS = 3;
|
|
110
123
|
var DEFAULT_ASSISTANT_ID = "lead_agent";
|
|
111
124
|
|
|
112
|
-
// src/protocol/stream-pump.ts
|
|
113
|
-
var import_vue = require("vue");
|
|
114
|
-
var import_langgraph_sdk = require("@langchain/langgraph-sdk");
|
|
115
|
-
var STREAM_MODE = ["values", "messages-tuple"];
|
|
116
|
-
function isSilentStreamError(e) {
|
|
117
|
-
return e instanceof Error && (e.name === "AbortError" || e.name === "TimeoutError");
|
|
118
|
-
}
|
|
119
|
-
function createStreamPump(source, options) {
|
|
120
|
-
const isLoading = (0, import_vue.ref)(false);
|
|
121
|
-
const error = (0, import_vue.ref)(null);
|
|
122
|
-
let queue = Promise.resolve();
|
|
123
|
-
let currentController = null;
|
|
124
|
-
const runStream = async (open) => {
|
|
125
|
-
const controller = new AbortController();
|
|
126
|
-
currentController = controller;
|
|
127
|
-
try {
|
|
128
|
-
isLoading.value = true;
|
|
129
|
-
error.value = null;
|
|
130
|
-
options.onStreamStart?.();
|
|
131
|
-
for await (const { event, data } of open(controller.signal)) {
|
|
132
|
-
if (event === "error") throw new import_langgraph_sdk.StreamError(data);
|
|
133
|
-
if (event === "metadata") {
|
|
134
|
-
options.onMetadataEvent?.(data);
|
|
135
|
-
continue;
|
|
136
|
-
}
|
|
137
|
-
if (event === "values" || event.startsWith("values|")) {
|
|
138
|
-
if (event.includes("|")) continue;
|
|
139
|
-
options.onValuesEvent?.(data);
|
|
140
|
-
continue;
|
|
141
|
-
}
|
|
142
|
-
if (event === "messages" || event === "messages-tuple" || event.startsWith("messages|")) {
|
|
143
|
-
if (event.includes("|")) continue;
|
|
144
|
-
const [serialized, metadata] = Array.isArray(data) ? data : [];
|
|
145
|
-
options.onMessageTupleEvent?.(serialized, metadata);
|
|
146
|
-
continue;
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
} catch (e) {
|
|
150
|
-
if (!isSilentStreamError(e)) {
|
|
151
|
-
error.value = e;
|
|
152
|
-
try {
|
|
153
|
-
await options.onError?.(e);
|
|
154
|
-
} catch {
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
} finally {
|
|
158
|
-
try {
|
|
159
|
-
await options.onStreamEnd?.();
|
|
160
|
-
} catch {
|
|
161
|
-
}
|
|
162
|
-
isLoading.value = false;
|
|
163
|
-
if (currentController === controller) currentController = null;
|
|
164
|
-
try {
|
|
165
|
-
await options.onFinish?.();
|
|
166
|
-
} catch {
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
};
|
|
170
|
-
const start = (open, startOptions) => {
|
|
171
|
-
if (startOptions?.abortPrevious) currentController?.abort();
|
|
172
|
-
const queued = queue.then(() => runStream(open));
|
|
173
|
-
queue = queued;
|
|
174
|
-
return queued;
|
|
175
|
-
};
|
|
176
|
-
return {
|
|
177
|
-
isLoading,
|
|
178
|
-
error,
|
|
179
|
-
/** 发起一次流式运行(发送用户消息);fire-and-forget(与现网 useThreadStream 一致) */
|
|
180
|
-
submit(input, submitOptions) {
|
|
181
|
-
void start(
|
|
182
|
-
(signal) => source.openRunStream(
|
|
183
|
-
{
|
|
184
|
-
input,
|
|
185
|
-
...submitOptions,
|
|
186
|
-
streamMode: STREAM_MODE,
|
|
187
|
-
// sdk client 在 run 创建时回调;透传给 CreateStreamOptions.onCreated
|
|
188
|
-
onRunCreated: (params) => options.onCreated?.(params)
|
|
189
|
-
},
|
|
190
|
-
signal
|
|
191
|
-
),
|
|
192
|
-
{ abortPrevious: true }
|
|
193
|
-
);
|
|
194
|
-
},
|
|
195
|
-
/** 加入既有 run 的 SSE 流(断线重连);await 至流结束 */
|
|
196
|
-
joinStream(runId, lastEventId) {
|
|
197
|
-
return start((signal) => source.openJoinStream(runId, lastEventId ?? "-1", signal), { abortPrevious: true });
|
|
198
|
-
},
|
|
199
|
-
/** 停止当前流(本地 abort,不取消服务端 run) */
|
|
200
|
-
stop() {
|
|
201
|
-
currentController?.abort();
|
|
202
|
-
},
|
|
203
|
-
/** 恢复 pending interrupt:发送 HITL 决策(Command(resume)),与 joinStream 的 SSE 重连语义不同;await 至流结束 */
|
|
204
|
-
resumeInterrupt(decisions) {
|
|
205
|
-
return start(
|
|
206
|
-
(signal) => source.openRunStream(
|
|
207
|
-
{
|
|
208
|
-
input: null,
|
|
209
|
-
command: { resume: decisions },
|
|
210
|
-
onDisconnect: "continue",
|
|
211
|
-
config: { recursion_limit: 1e3 },
|
|
212
|
-
streamMode: STREAM_MODE,
|
|
213
|
-
onRunCreated: (params) => options.onCreated?.(params)
|
|
214
|
-
},
|
|
215
|
-
signal
|
|
216
|
-
),
|
|
217
|
-
{ abortPrevious: true }
|
|
218
|
-
);
|
|
219
|
-
}
|
|
220
|
-
};
|
|
221
|
-
}
|
|
222
|
-
|
|
223
125
|
// src/parser/sxin-ast-attrs.ts
|
|
224
126
|
function formatStr(str) {
|
|
225
127
|
if (!str) return str;
|
|
@@ -626,18 +528,59 @@ var normalizeOne = (raw) => {
|
|
|
626
528
|
searchText: orUndefined(searchText)
|
|
627
529
|
};
|
|
628
530
|
};
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
531
|
+
var KB_CITATION_CONTRACT = "support.kbCitation";
|
|
532
|
+
var REF_ID_KEYS = ["ref-id", "refId", "ref_id", "citation-id", "citationId", "citation_id", "id"];
|
|
533
|
+
var SEARCH_TEXT_KEYS = ["search-text", "searchText", "search_text", "keyword"];
|
|
534
|
+
var REF_ID_LIST_KEY_RE = /^(ref|citation)[-_]?ids?$/i;
|
|
535
|
+
var isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
536
|
+
var pickFirstString = (obj, keys) => {
|
|
537
|
+
for (const k of keys) {
|
|
538
|
+
const v = obj?.[k];
|
|
539
|
+
if (v === void 0 || v === null) continue;
|
|
540
|
+
const s = String(v).trim();
|
|
541
|
+
if (s) return s;
|
|
542
|
+
}
|
|
543
|
+
return void 0;
|
|
544
|
+
};
|
|
545
|
+
function extractCitationAnchorsFromSpec(spec) {
|
|
546
|
+
const anchors = [];
|
|
547
|
+
const seen = /* @__PURE__ */ new Set();
|
|
548
|
+
const candidates = [];
|
|
549
|
+
if (isPlainObject(spec)) candidates.push(spec);
|
|
550
|
+
for (const [key, value] of Object.entries(spec || {})) {
|
|
551
|
+
if (Array.isArray(value)) {
|
|
552
|
+
for (const item of value) if (isPlainObject(item)) candidates.push(item);
|
|
553
|
+
} else if (typeof value === "string" && /,/.test(value) && REF_ID_LIST_KEY_RE.test(key)) {
|
|
554
|
+
for (const id of value.split(",")) candidates.push({ "ref-id": id });
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
for (const item of candidates) {
|
|
558
|
+
const refId = pickFirstString(item, REF_ID_KEYS);
|
|
559
|
+
if (!refId || seen.has(refId)) continue;
|
|
560
|
+
seen.add(refId);
|
|
561
|
+
const anchor = { refId, title: "" };
|
|
562
|
+
const searchText = pickFirstString(item, SEARCH_TEXT_KEYS);
|
|
563
|
+
if (searchText) anchor.searchText = searchText;
|
|
564
|
+
anchors.push(anchor);
|
|
640
565
|
}
|
|
566
|
+
return anchors;
|
|
567
|
+
}
|
|
568
|
+
function extractCitationAnchors(blocks) {
|
|
569
|
+
const anchors = [];
|
|
570
|
+
const seen = /* @__PURE__ */ new Set();
|
|
571
|
+
for (const block of blocks) {
|
|
572
|
+
if (block.type !== "custom") continue;
|
|
573
|
+
const custom = block;
|
|
574
|
+
if (custom.tagName !== "sxin-item") continue;
|
|
575
|
+
const spec = custom.spec || {};
|
|
576
|
+
if (String(spec.contract || "").trim() !== KB_CITATION_CONTRACT) continue;
|
|
577
|
+
for (const anchor of extractCitationAnchorsFromSpec(spec)) {
|
|
578
|
+
if (seen.has(anchor.refId)) continue;
|
|
579
|
+
seen.add(anchor.refId);
|
|
580
|
+
anchors.push(anchor);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return anchors;
|
|
641
584
|
}
|
|
642
585
|
function parseKnowledgeItemsFromValue(value) {
|
|
643
586
|
if (!value) return [];
|
|
@@ -715,24 +658,24 @@ function buildInterruptReviewBlock(interrupt, responded) {
|
|
|
715
658
|
interruptId
|
|
716
659
|
};
|
|
717
660
|
}
|
|
718
|
-
function buildInterruptReviewGroup(interrupt, responded) {
|
|
719
|
-
const block = buildInterruptReviewBlock(interrupt, responded);
|
|
720
|
-
if (!block) return null;
|
|
721
|
-
return {
|
|
722
|
-
id: `interrupt-${block.interruptId}`,
|
|
723
|
-
type: "ai",
|
|
724
|
-
status: block.status,
|
|
725
|
-
source: "state",
|
|
726
|
-
originMessageIds: [],
|
|
727
|
-
blocks: [block],
|
|
728
|
-
toolIds: [],
|
|
729
|
-
tools: [],
|
|
730
|
-
rawMessages: [],
|
|
731
|
-
createdAt: Date.now()
|
|
732
|
-
};
|
|
733
|
-
}
|
|
734
661
|
|
|
735
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
|
+
}
|
|
736
679
|
var humanInputResponseRule = {
|
|
737
680
|
key: "clarificationAnswers",
|
|
738
681
|
extract(msg, acc) {
|
|
@@ -740,7 +683,7 @@ var humanInputResponseRule = {
|
|
|
740
683
|
const response = additionalKwargs?.human_input_response;
|
|
741
684
|
const requestId = String(response?.request_id || "").trim().replace("clarification:", "");
|
|
742
685
|
if (requestId && response?.value !== void 0) {
|
|
743
|
-
acc.clarificationAnswers.set(requestId,
|
|
686
|
+
acc.clarificationAnswers.set(requestId, formatAnswerText(response.value));
|
|
744
687
|
}
|
|
745
688
|
}
|
|
746
689
|
};
|
|
@@ -776,6 +719,62 @@ function extractStateMessages(state) {
|
|
|
776
719
|
const messages = values.messages;
|
|
777
720
|
return Array.isArray(messages) ? messages : [];
|
|
778
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
|
+
}
|
|
779
778
|
function ensureRunningRun(runMap, runId, threadId) {
|
|
780
779
|
let runInfo = runMap.get(runId);
|
|
781
780
|
if (!runInfo) {
|
|
@@ -789,7 +788,7 @@ function ensureRunningRun(runMap, runId, threadId) {
|
|
|
789
788
|
return runInfo;
|
|
790
789
|
}
|
|
791
790
|
|
|
792
|
-
// src/
|
|
791
|
+
// src/parser/sxin-message.ts
|
|
793
792
|
var asSxin = (m) => m ?? {};
|
|
794
793
|
|
|
795
794
|
// src/parser/run-messages.ts
|
|
@@ -864,6 +863,23 @@ function extractRunEnrichment(messages) {
|
|
|
864
863
|
}
|
|
865
864
|
return map;
|
|
866
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
|
+
}
|
|
867
883
|
function runMessagesToMessages(messages) {
|
|
868
884
|
return messages.map((msg) => {
|
|
869
885
|
const normalized = normalizeMessageType({ ...asSxin(msg.content) });
|
|
@@ -917,6 +933,9 @@ function readMessageContentText(msg) {
|
|
|
917
933
|
if (!read) return "";
|
|
918
934
|
return read.trim ? read.text.trim() : read.text;
|
|
919
935
|
}
|
|
936
|
+
function hasKbCitationMessage(msg) {
|
|
937
|
+
return readMessageContentText(msg).includes("support.kbCitation");
|
|
938
|
+
}
|
|
920
939
|
function extractTextFromMessage(msg) {
|
|
921
940
|
const read = readMessageText(msg);
|
|
922
941
|
if (!read) return "";
|
|
@@ -1302,11 +1321,6 @@ function walkNodes(ctx, nodes) {
|
|
|
1302
1321
|
if (isInjectedElement(node)) {
|
|
1303
1322
|
continue;
|
|
1304
1323
|
}
|
|
1305
|
-
if (node.tagName === "sxin-kb-citation" && node.closed) {
|
|
1306
|
-
flushTextBuf(ctx);
|
|
1307
|
-
collectCitation(node, ctx.citations);
|
|
1308
|
-
continue;
|
|
1309
|
-
}
|
|
1310
1324
|
if (node.tagName.startsWith("sxin-")) {
|
|
1311
1325
|
if (!handleSxinElement(ctx, node)) return false;
|
|
1312
1326
|
continue;
|
|
@@ -1322,12 +1336,11 @@ function extractBlocksFromNodes(nodes, rawText, source) {
|
|
|
1322
1336
|
isHistory,
|
|
1323
1337
|
status: isHistory ? "completed" : "streaming",
|
|
1324
1338
|
blocks: [],
|
|
1325
|
-
citations: [],
|
|
1326
1339
|
textBuf: { value: "" }
|
|
1327
1340
|
};
|
|
1328
1341
|
const completed = walkNodes(ctx, nodes);
|
|
1329
1342
|
if (completed) flushTextBuf(ctx);
|
|
1330
|
-
return { blocks: ctx.blocks
|
|
1343
|
+
return { blocks: ctx.blocks };
|
|
1331
1344
|
}
|
|
1332
1345
|
function extractBlocksFromContent(rawText, source) {
|
|
1333
1346
|
return extractBlocksFromNodes(tokenizeSxin(rawText), rawText, source);
|
|
@@ -1426,14 +1439,60 @@ function applyUsageDetails(usage, r) {
|
|
|
1426
1439
|
}
|
|
1427
1440
|
}
|
|
1428
1441
|
|
|
1429
|
-
// src/
|
|
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
|
|
1430
1489
|
function buildRunInfo(run, threadId) {
|
|
1431
1490
|
return {
|
|
1432
1491
|
runId: String(run?.run_id || "").trim(),
|
|
1433
1492
|
threadId: String(threadId || "").trim(),
|
|
1434
1493
|
usage: buildRunUsage(run),
|
|
1435
1494
|
latencyMs: buildRunLatencyMs(run),
|
|
1436
|
-
finishReason: toOptionalString(run?.finish_reason),
|
|
1495
|
+
finishReason: toOptionalString(run?.stop_reason ?? run?.finish_reason),
|
|
1437
1496
|
modelName: toOptionalString(run?.model_name),
|
|
1438
1497
|
status: buildRunStatus(run),
|
|
1439
1498
|
createdAt: buildRunCreatedAt(run)
|
|
@@ -1489,943 +1548,87 @@ function pickRunMessageMetadata(messages) {
|
|
|
1489
1548
|
return { modelName, finishReason };
|
|
1490
1549
|
}
|
|
1491
1550
|
|
|
1492
|
-
// src/
|
|
1493
|
-
var
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
const
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
const presentFilesSet = /* @__PURE__ */ new Set();
|
|
1501
|
-
const writeFilesSet = /* @__PURE__ */ new Set();
|
|
1502
|
-
const toolParsers = /* @__PURE__ */ new Map();
|
|
1503
|
-
const registerParser = (names, parser) => {
|
|
1504
|
-
for (const name of Array.isArray(names) ? names : [names]) {
|
|
1505
|
-
toolParsers.set(name, parser);
|
|
1506
|
-
}
|
|
1507
|
-
};
|
|
1508
|
-
const parseBlockTool = (tool, status) => {
|
|
1509
|
-
const name = String(tool.call?.name || "").trim();
|
|
1510
|
-
const parser = toolParsers.get(name);
|
|
1511
|
-
return parser ? parser(tool, status) : [];
|
|
1512
|
-
};
|
|
1513
|
-
const parseAskClarification = (tool, _status) => {
|
|
1514
|
-
const args = tool.call?.args || {};
|
|
1515
|
-
return [
|
|
1516
|
-
{
|
|
1517
|
-
id: genBlockId(),
|
|
1518
|
-
type: "ask-clarification",
|
|
1519
|
-
context: args.context,
|
|
1520
|
-
question: args.question,
|
|
1521
|
-
clarification_type: args.clarification_type,
|
|
1522
|
-
options: Array.isArray(args.options) ? args.options : void 0,
|
|
1523
|
-
fields: Array.isArray(args.fields) ? args.fields : void 0,
|
|
1524
|
-
// clarification 的回答是跨 run 的,不能根据 streaming/source 判断状态,统一 pending,由渲染层结合 thread 级回答状态决定
|
|
1525
|
-
status: "pending",
|
|
1526
|
-
toolCallId: tool.id
|
|
1527
|
-
}
|
|
1528
|
-
];
|
|
1529
|
-
};
|
|
1530
|
-
const parseFormBlock = (tool, status, sourceTag) => {
|
|
1531
|
-
const args = tool.call?.args || {};
|
|
1532
|
-
const variant = String(args.variant || "input");
|
|
1533
|
-
const blockStatus = sourceTag === "ask_clarification" ? "pending" : status;
|
|
1534
|
-
return [
|
|
1535
|
-
{
|
|
1536
|
-
id: genBlockId(),
|
|
1537
|
-
type: "form",
|
|
1538
|
-
variant: ["input", "confirm", "delete_confirm"].includes(variant) ? variant : "input",
|
|
1539
|
-
title: args.title,
|
|
1540
|
-
question: args.question,
|
|
1541
|
-
context: args.context,
|
|
1542
|
-
fields: Array.isArray(args.fields) ? args.fields : [],
|
|
1543
|
-
values: args.values || {},
|
|
1544
|
-
stepInfo: args.stepInfo,
|
|
1545
|
-
customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
|
|
1546
|
-
status: blockStatus,
|
|
1547
|
-
toolCallId: tool.id,
|
|
1548
|
-
source: sourceTag
|
|
1549
|
-
}
|
|
1550
|
-
];
|
|
1551
|
-
};
|
|
1552
|
-
const parseListBlock = (tool, status) => {
|
|
1553
|
-
const args = tool.call?.args || {};
|
|
1554
|
-
const mode = String(args.mode || "select");
|
|
1555
|
-
return [
|
|
1556
|
-
{
|
|
1557
|
-
id: genBlockId(),
|
|
1558
|
-
type: "list",
|
|
1559
|
-
mode: ["select", "view"].includes(mode) ? mode : "select",
|
|
1560
|
-
title: args.title,
|
|
1561
|
-
dataSource: args.dataSource,
|
|
1562
|
-
items: Array.isArray(args.items) ? args.items : void 0,
|
|
1563
|
-
queryParams: args.queryParams,
|
|
1564
|
-
pagination: args.pagination,
|
|
1565
|
-
selectMode: args.selectMode || "single",
|
|
1566
|
-
customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
|
|
1567
|
-
status,
|
|
1568
|
-
toolCallId: tool.id
|
|
1569
|
-
}
|
|
1570
|
-
];
|
|
1571
|
-
};
|
|
1572
|
-
const parsePresentFiles = (tool, status) => {
|
|
1573
|
-
const args = tool.call?.args || {};
|
|
1574
|
-
const filepaths = Array.isArray(args?.filepaths) ? args.filepaths : [];
|
|
1575
|
-
if (!filepaths.length) return [];
|
|
1576
|
-
const paths = [];
|
|
1577
|
-
for (const path of filepaths) {
|
|
1578
|
-
if (presentFilesSet.has(path)) continue;
|
|
1579
|
-
presentFilesSet.add(path);
|
|
1580
|
-
paths.push(path);
|
|
1581
|
-
}
|
|
1582
|
-
if (!paths.length) return [];
|
|
1583
|
-
return [
|
|
1584
|
-
{
|
|
1585
|
-
id: genBlockId(),
|
|
1586
|
-
type: "artifact",
|
|
1587
|
-
files: buildArtifactFiles(paths),
|
|
1588
|
-
status
|
|
1589
|
-
}
|
|
1590
|
-
];
|
|
1591
|
-
};
|
|
1592
|
-
const resolveWriteFileContext = (tool) => {
|
|
1593
|
-
const meta = getToolCallArtifactMeta(tool.call);
|
|
1594
|
-
const args = tool.call?.args || {};
|
|
1595
|
-
const artifactPath = String(meta?.path || args.path || "").trim();
|
|
1596
|
-
const content = String(args.content || tool.result?.content || "").trim();
|
|
1597
|
-
const description = String(args.description || "").trim();
|
|
1598
|
-
const blockId = tool.id || artifactPath || `report-${Date.now()}`;
|
|
1599
|
-
const toolCreatedAt = Number(new Date(asSxin(tool.aiMessage).created_at || ""));
|
|
1600
|
-
const toolTime = Number.isFinite(toolCreatedAt) ? toolCreatedAt : createdAt;
|
|
1601
|
-
if (!content && source === "sse") return null;
|
|
1602
|
-
if (writeFilesSet.has(artifactPath)) return null;
|
|
1603
|
-
writeFilesSet.add(artifactPath);
|
|
1604
|
-
presentFilesSet.add(artifactPath);
|
|
1605
|
-
return { artifactPath, content, description, blockId, createdAt: toolTime };
|
|
1606
|
-
};
|
|
1607
|
-
const buildReportBlock = (kind, ctx, status) => {
|
|
1608
|
-
const isOutline = kind === "report_outline";
|
|
1609
|
-
const fallbackName = extractTitleFromArtifactPath(ctx.artifactPath, kind) || ctx.description.replace(isOutline ? /生成|大纲/g : /生成|正文|报告/g, "").trim() || "\u62A5\u544A";
|
|
1610
|
-
const isState = source === "state";
|
|
1611
|
-
const payloadInput = {
|
|
1612
|
-
templateId: ctx.blockId,
|
|
1613
|
-
fallbackName,
|
|
1614
|
-
sourcePath: ctx.artifactPath || void 0,
|
|
1615
|
-
content: isState ? void 0 : ctx.content || void 0,
|
|
1616
|
-
contentRef: isState && ctx.artifactPath ? { path: ctx.artifactPath } : void 0,
|
|
1617
|
-
createdAt: ctx.createdAt
|
|
1618
|
-
};
|
|
1619
|
-
return isOutline ? { id: genBlockId(), type: "report-outline", payload: buildReportOutlinePayload(payloadInput), status } : { id: genBlockId(), type: "report-body", payload: buildReportBodyPayload(payloadInput), status };
|
|
1620
|
-
};
|
|
1621
|
-
const parseWriteFile = (tool, status) => {
|
|
1622
|
-
const name = String(tool.call?.name || "").trim();
|
|
1623
|
-
if (!isWriteFileToolName(name)) return [];
|
|
1624
|
-
const kind = resolveReportArtifactKind(tool.call);
|
|
1625
|
-
if (!kind) return [];
|
|
1626
|
-
const ctx = resolveWriteFileContext(tool);
|
|
1627
|
-
if (!ctx) return [];
|
|
1628
|
-
const block = buildReportBlock(kind, ctx, status);
|
|
1629
|
-
return block ? [block] : [];
|
|
1630
|
-
};
|
|
1631
|
-
const parseClarification = (tool, status) => {
|
|
1632
|
-
const args = tool.call?.args || {};
|
|
1633
|
-
if (args.variant || args.fields?.length) {
|
|
1634
|
-
return parseFormBlock(tool, status, "ask_clarification");
|
|
1635
|
-
}
|
|
1636
|
-
return parseAskClarification(tool, status);
|
|
1637
|
-
};
|
|
1638
|
-
registerParser("ask_clarification", parseClarification);
|
|
1639
|
-
registerParser(
|
|
1640
|
-
["confirm_form", "form"],
|
|
1641
|
-
(tool, status) => parseFormBlock(tool, status, String(tool.call?.name || "").trim())
|
|
1642
|
-
);
|
|
1643
|
-
registerParser(["list_and_select", "list"], parseListBlock);
|
|
1644
|
-
registerParser("present_files", parsePresentFiles);
|
|
1645
|
-
registerParser(["write_file", "write_files"], parseWriteFile);
|
|
1646
|
-
const buildFromNodes = (nodes, rawText, tools) => {
|
|
1647
|
-
const blocks = [];
|
|
1648
|
-
const status = isStreaming ? "streaming" : "completed";
|
|
1649
|
-
const contentSource = source === "state" ? "history" : source;
|
|
1650
|
-
const { blocks: contentBlocks, citations } = extractBlocksFromNodes(nodes, rawText, contentSource);
|
|
1651
|
-
blocks.push(...contentBlocks);
|
|
1652
|
-
for (const tool of tools) {
|
|
1653
|
-
const toolBlocks = parseBlockTool(tool, status);
|
|
1654
|
-
blocks.push(...toolBlocks);
|
|
1655
|
-
}
|
|
1656
|
-
if (citations.length > 0) {
|
|
1657
|
-
blocks.push({
|
|
1658
|
-
id: genBlockId(),
|
|
1659
|
-
type: "citation",
|
|
1660
|
-
items: citations.map((c) => ({ ...c, title: c.title || "" })),
|
|
1661
|
-
status
|
|
1662
|
-
});
|
|
1663
|
-
}
|
|
1664
|
-
if (twinEnabled) {
|
|
1665
|
-
const twinTool = tools.reverse().find((_) => _.call?.name.includes(twinToolPrefix));
|
|
1666
|
-
if (twinTool) {
|
|
1667
|
-
blocks.push({
|
|
1668
|
-
id: genBlockId(),
|
|
1669
|
-
type: "twin",
|
|
1670
|
-
toolName: twinTool.call.name.replace(twinToolPrefix, ""),
|
|
1671
|
-
args: twinTool.call.args
|
|
1672
|
-
});
|
|
1673
|
-
}
|
|
1674
|
-
}
|
|
1675
|
-
return blocks;
|
|
1676
|
-
};
|
|
1677
|
-
const build = (content, tools) => buildFromNodes(tokenizeSxin(content), content, tools);
|
|
1678
|
-
return { build, buildFromNodes };
|
|
1679
|
-
}
|
|
1680
|
-
|
|
1681
|
-
// src/domain/fold.ts
|
|
1682
|
-
function messageRunId(msg) {
|
|
1683
|
-
const own = String(asSxin(msg).runId || "").trim();
|
|
1684
|
-
if (own) return own;
|
|
1685
|
-
return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
|
|
1686
|
-
}
|
|
1687
|
-
function foldMessages(target, flush) {
|
|
1688
|
-
let type = null;
|
|
1689
|
-
let buf = [];
|
|
1690
|
-
let groupRunId;
|
|
1691
|
-
const doFlush = () => {
|
|
1692
|
-
if (!buf.length || !type) return;
|
|
1693
|
-
flush(type, buf);
|
|
1694
|
-
buf = [];
|
|
1695
|
-
};
|
|
1696
|
-
for (const m of target) {
|
|
1697
|
-
if (isHumanMessage(m)) {
|
|
1698
|
-
if (!(type === "human" && buf.length && getHumanMessageBaseId(String(asSxin(m).id || "")) === getHumanMessageBaseId(String(asSxin(buf[0]).id || ""))))
|
|
1699
|
-
doFlush();
|
|
1700
|
-
type = "human";
|
|
1701
|
-
buf.push(m);
|
|
1702
|
-
} else if (isAiMessage(m) || isToolMessage(m)) {
|
|
1703
|
-
const mRunId = messageRunId(m);
|
|
1704
|
-
if (type !== "ai" || mRunId && groupRunId && mRunId !== groupRunId) doFlush();
|
|
1705
|
-
if (!buf.length) groupRunId = mRunId;
|
|
1706
|
-
type = "ai";
|
|
1707
|
-
buf.push(m);
|
|
1708
|
-
}
|
|
1709
|
-
}
|
|
1710
|
-
doFlush();
|
|
1711
|
-
}
|
|
1712
|
-
|
|
1713
|
-
// src/domain/group-materializer.ts
|
|
1714
|
-
function readCreatedAt(msg) {
|
|
1715
|
-
return Number(new Date(asSxin(msg).created_at || Date.now())) || Date.now();
|
|
1716
|
-
}
|
|
1717
|
-
function buildHumanGroup(messages, status) {
|
|
1718
|
-
const representative = messages.find(
|
|
1719
|
-
(m) => parseHumanMessageId(String(asSxin(m).id || "")).variant === "user" && isVisibleUserMessage(m)
|
|
1720
|
-
) || messages.find((m) => isVisibleUserMessage(m)) || messages[0];
|
|
1721
|
-
const firstId = messages.find((_) => _.id)?.id || genMessageId();
|
|
1722
|
-
const additionalKwargs = asSxin(representative).additional_kwargs;
|
|
1723
|
-
const texts = extractUserMessageTexts(messages);
|
|
1724
|
-
const runId = messageRunId(representative);
|
|
1725
|
-
return {
|
|
1726
|
-
id: firstId,
|
|
1727
|
-
type: "human",
|
|
1728
|
-
status,
|
|
1729
|
-
originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
|
|
1730
|
-
runId,
|
|
1731
|
-
rawMessages: messages,
|
|
1732
|
-
texts,
|
|
1733
|
-
additionalKwargs,
|
|
1734
|
-
blocks: [],
|
|
1735
|
-
toolIds: [],
|
|
1736
|
-
tools: [],
|
|
1737
|
-
createdAt: readCreatedAt(representative)
|
|
1738
|
-
};
|
|
1739
|
-
}
|
|
1740
|
-
function buildAiGroup(messages, options, twin) {
|
|
1741
|
-
const firstId = messages.find((_) => _.id)?.id || genMessageId();
|
|
1742
|
-
const groupTools = deriveToolsFromMessages(messages);
|
|
1743
|
-
const aiMessages = messages.filter(isAiMessage);
|
|
1744
|
-
const lastAi = aiMessages[aiMessages.length - 1] || messages[messages.length - 1];
|
|
1745
|
-
const content = readMessageContentText(lastAi);
|
|
1746
|
-
const createdAt = readCreatedAt(messages[0]);
|
|
1747
|
-
const blocks = options.isStreaming ? [] : createBlockBuilderLite({ source: options.source, twin, createdAt }).buildFromNodes(
|
|
1748
|
-
tokenizeSxin(content),
|
|
1749
|
-
content,
|
|
1750
|
-
groupTools
|
|
1751
|
-
);
|
|
1752
|
-
return {
|
|
1753
|
-
id: firstId,
|
|
1754
|
-
type: "ai",
|
|
1755
|
-
status: options.isStreaming ? "streaming" : "completed",
|
|
1756
|
-
originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
|
|
1757
|
-
runId: messageRunId(lastAi) || options.runId,
|
|
1758
|
-
rawMessages: messages,
|
|
1759
|
-
blocks,
|
|
1760
|
-
toolIds: groupTools.map((t) => t.id),
|
|
1761
|
-
tools: groupTools,
|
|
1762
|
-
createdAt
|
|
1763
|
-
};
|
|
1764
|
-
}
|
|
1765
|
-
|
|
1766
|
-
// src/domain/clarification.ts
|
|
1767
|
-
function isClarificationAnswered(block, answers) {
|
|
1768
|
-
if (!block) return false;
|
|
1769
|
-
if (block.status === "completed") return true;
|
|
1770
|
-
if (block.isAnswered) return true;
|
|
1771
|
-
const toolCallId = block.toolCallId;
|
|
1772
|
-
return !!toolCallId && answers.has(toolCallId);
|
|
1773
|
-
}
|
|
1774
|
-
function isClarificationBlock(block) {
|
|
1775
|
-
return block.type === "ask-clarification" || block.type === "form" && block.source === "ask_clarification";
|
|
1776
|
-
}
|
|
1777
|
-
|
|
1778
|
-
// src/domain/decorators.ts
|
|
1779
|
-
function applyPatchesAndExtras(groups, state, runIdFilter) {
|
|
1780
|
-
if (!state.patches.size && !state.extras.length) return groups;
|
|
1781
|
-
const patchedGroups = groups.map((g) => state.patches.get(g.id) ?? g);
|
|
1782
|
-
const anchor = runIdFilter ? patchedGroups.findIndex((g) => String(g.runId || "").trim() === runIdFilter) : -1;
|
|
1783
|
-
return anchor >= 0 ? [...patchedGroups.slice(0, anchor), ...state.extras, ...patchedGroups.slice(anchor)] : [...patchedGroups, ...state.extras];
|
|
1784
|
-
}
|
|
1785
|
-
function withInterruptBlock(groups, deps) {
|
|
1786
|
-
const interrupt = deps.getInterrupt();
|
|
1787
|
-
if (!interrupt) return groups;
|
|
1788
|
-
const interruptId = String(interrupt.id || "");
|
|
1789
|
-
const responded = !!interruptId && deps.respondedIds.has(interruptId);
|
|
1790
|
-
const block = buildInterruptReviewBlock(interrupt, responded);
|
|
1791
|
-
if (!block) return groups;
|
|
1792
|
-
const { interruptBlocks } = deps;
|
|
1793
|
-
const targetIndex = findLastAiIndex(groups);
|
|
1794
|
-
if (targetIndex >= 0) {
|
|
1795
|
-
const remembered = interruptBlocks.get(interruptId);
|
|
1796
|
-
if (remembered) {
|
|
1797
|
-
const updated = { ...block, status: responded ? "completed" : "pending" };
|
|
1798
|
-
interruptBlocks.set(interruptId, updated);
|
|
1799
|
-
const next2 = [...groups];
|
|
1800
|
-
next2[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, updated] };
|
|
1801
|
-
return next2;
|
|
1802
|
-
}
|
|
1803
|
-
interruptBlocks.set(interruptId, block);
|
|
1804
|
-
const next = [...groups];
|
|
1805
|
-
next[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, block] };
|
|
1806
|
-
return next;
|
|
1807
|
-
}
|
|
1808
|
-
const existing = [...interruptBlocks.values()].find(
|
|
1809
|
-
(b) => b.type === "interrupt-review" && b.interruptId === interruptId
|
|
1810
|
-
);
|
|
1811
|
-
if (existing) return groups;
|
|
1812
|
-
interruptBlocks.set(interruptId, block);
|
|
1813
|
-
return [
|
|
1814
|
-
...groups,
|
|
1815
|
-
{
|
|
1816
|
-
id: `interrupt-${interruptId}`,
|
|
1817
|
-
type: "ai",
|
|
1818
|
-
status: block.status,
|
|
1819
|
-
source: "state",
|
|
1820
|
-
originMessageIds: [],
|
|
1821
|
-
blocks: [block],
|
|
1822
|
-
toolIds: [],
|
|
1823
|
-
tools: [],
|
|
1824
|
-
rawMessages: [],
|
|
1825
|
-
createdAt: Date.now()
|
|
1826
|
-
}
|
|
1827
|
-
];
|
|
1828
|
-
}
|
|
1829
|
-
function findLastAiIndex(groups) {
|
|
1830
|
-
for (let i = groups.length - 1; i >= 0; i--) {
|
|
1831
|
-
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;
|
|
1832
1559
|
}
|
|
1833
|
-
return
|
|
1834
|
-
}
|
|
1835
|
-
function
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
const
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
touched = true;
|
|
1844
|
-
return { ...b, isAnswered: true, answer: answers.get(blk.toolCallId) };
|
|
1845
|
-
}
|
|
1846
|
-
if (blk.type === "interrupt-review" && blk.interruptId && responded.has(blk.interruptId)) {
|
|
1847
|
-
touched = true;
|
|
1848
|
-
return { ...b, isResponded: true };
|
|
1849
|
-
}
|
|
1850
|
-
return b;
|
|
1851
|
-
});
|
|
1852
|
-
return touched ? { ...g, blocks } : g;
|
|
1853
|
-
});
|
|
1854
|
-
}
|
|
1855
|
-
function filterInvisibleAiGroups(groups) {
|
|
1856
|
-
return groups.filter((g) => g.type !== "ai" || hasVisibleAiContent(g));
|
|
1857
|
-
}
|
|
1858
|
-
function hasVisibleAiContent(g) {
|
|
1859
|
-
if (g.status === "streaming") return true;
|
|
1860
|
-
if (g.streamingText) return true;
|
|
1861
|
-
if (g.blocks.length) return true;
|
|
1862
|
-
return g.tools.some((t) => t.result !== void 0 || t.state === "error");
|
|
1863
|
-
}
|
|
1864
|
-
|
|
1865
|
-
// src/domain/viewmodel-state.ts
|
|
1866
|
-
var import_vue2 = require("vue");
|
|
1867
|
-
function createViewModelState() {
|
|
1868
|
-
const extrasRef = (0, import_vue2.shallowRef)([]);
|
|
1869
|
-
const patches = (0, import_vue2.shallowReactive)(/* @__PURE__ */ new Map());
|
|
1870
|
-
const readFirstText = (group) => extractTextFromMessage(asSxin(group.rawMessages[0])).trim();
|
|
1871
|
-
return {
|
|
1872
|
-
get extras() {
|
|
1873
|
-
return extrasRef.value;
|
|
1874
|
-
},
|
|
1875
|
-
get patches() {
|
|
1876
|
-
return patches;
|
|
1877
|
-
},
|
|
1878
|
-
appendExtra(groups) {
|
|
1879
|
-
if (!groups.length) return;
|
|
1880
|
-
extrasRef.value = [...extrasRef.value, ...groups];
|
|
1881
|
-
},
|
|
1882
|
-
patchGroup(messageId, patch, sourceGroups) {
|
|
1883
|
-
const current = patches.get(messageId) ?? sourceGroups().find((g) => g.id === messageId);
|
|
1884
|
-
if (!current) return;
|
|
1885
|
-
const next = typeof patch === "function" ? patch(current) : { ...current, ...patch };
|
|
1886
|
-
patches.set(messageId, { ...next, id: current.id });
|
|
1887
|
-
},
|
|
1888
|
-
clearPatches() {
|
|
1889
|
-
patches.clear();
|
|
1890
|
-
extrasRef.value = [];
|
|
1891
|
-
},
|
|
1892
|
-
/** human extras 按序收敛:回显(同文本 + 当前流 runId)到达后按序移除乐观副本。
|
|
1893
|
-
* 用 runId 而非流式段判定:既有线程的回显可能经 reconcile 以 page-source 到达(不在流式段),
|
|
1894
|
-
* 但其 runId 与当前流一致;历史消息 runId 不同,不会误伤(连发同文本逐条配对)。
|
|
1895
|
-
* 无当前流 runId(流未开始)时不 prune——避免历史同文本消息误吞乐观副本。 */
|
|
1896
|
-
pruneExtras(decoratedGroups, currentRunId) {
|
|
1897
|
-
if (!extrasRef.value.some((g) => g.type === "human")) return;
|
|
1898
|
-
const runIdFilter = String(currentRunId || "").trim();
|
|
1899
|
-
if (!runIdFilter) return;
|
|
1900
|
-
const echoed = /* @__PURE__ */ new Map();
|
|
1901
|
-
for (const g of decoratedGroups) {
|
|
1902
|
-
if (g.type !== "human") continue;
|
|
1903
|
-
const runId = String(g.runId || "").trim();
|
|
1904
|
-
if (runId !== runIdFilter) continue;
|
|
1905
|
-
const text = readFirstText(g);
|
|
1906
|
-
echoed.set(text, (echoed.get(text) ?? 0) + 1);
|
|
1907
|
-
}
|
|
1908
|
-
const seenPerText = /* @__PURE__ */ new Map();
|
|
1909
|
-
extrasRef.value = extrasRef.value.filter((extra) => {
|
|
1910
|
-
if (extra.type !== "human") return true;
|
|
1911
|
-
const text = readFirstText(extra);
|
|
1912
|
-
const k = seenPerText.get(text) ?? 0;
|
|
1913
|
-
seenPerText.set(text, k + 1);
|
|
1914
|
-
return (echoed.get(text) ?? 0) <= k;
|
|
1915
|
-
});
|
|
1916
|
-
}
|
|
1917
|
-
};
|
|
1918
|
-
}
|
|
1919
|
-
|
|
1920
|
-
// src/domain/viewmodel.ts
|
|
1921
|
-
function createGroupDeriver(state) {
|
|
1922
|
-
const groupMemo = /* @__PURE__ */ new Map();
|
|
1923
|
-
const foldCache = { pageCount: -1, entries: [] };
|
|
1924
|
-
const interruptBlocks = /* @__PURE__ */ new Map();
|
|
1925
|
-
const derive = (deps) => {
|
|
1926
|
-
const { store, enrichments } = deps;
|
|
1927
|
-
const streaming = store.streamStatus === "streaming";
|
|
1928
|
-
const patched = store.getMessages().map((m) => {
|
|
1929
|
-
const patch = enrichments.resolveCitation(String(asSxin(m).id || ""));
|
|
1930
|
-
if (!patch) return m;
|
|
1931
|
-
return {
|
|
1932
|
-
...asSxin(m),
|
|
1933
|
-
...patch.content !== void 0 ? { content: patch.content } : {},
|
|
1934
|
-
additional_kwargs: {
|
|
1935
|
-
...asSxin(m).additional_kwargs ?? {},
|
|
1936
|
-
...patch.citationInfo !== void 0 ? { citation_info: patch.citationInfo } : {}
|
|
1937
|
-
}
|
|
1938
|
-
};
|
|
1939
|
-
});
|
|
1940
|
-
const sourceOf = (id) => id ? store.getEntity(id)?.source ?? "stream" : "stream";
|
|
1941
|
-
const epochOf = (id) => id ? store.getEntity(id)?.epoch : void 0;
|
|
1942
|
-
const runIdFilter = String(deps.currentRunId || "").trim();
|
|
1943
|
-
const currentEpoch = store.streamEpoch;
|
|
1944
|
-
const pageCount = store.pageCount;
|
|
1945
|
-
const patchedPrefix = patched.slice(0, pageCount);
|
|
1946
|
-
const patchedStream = patched.slice(pageCount);
|
|
1947
|
-
let prefixEntries;
|
|
1948
|
-
if (foldCache.pageCount === pageCount) {
|
|
1949
|
-
prefixEntries = foldCache.entries;
|
|
1950
|
-
} else {
|
|
1951
|
-
prefixEntries = [];
|
|
1952
|
-
foldMessages(
|
|
1953
|
-
patchedPrefix,
|
|
1954
|
-
(type, buf) => prefixEntries.push({ type, ids: buf.map((m) => String(asSxin(m).id || "")) })
|
|
1955
|
-
);
|
|
1956
|
-
foldCache.pageCount = pageCount;
|
|
1957
|
-
foldCache.entries = prefixEntries;
|
|
1958
|
-
}
|
|
1959
|
-
const prefixById = new Map(patchedPrefix.map((m) => [String(asSxin(m).id || ""), m]));
|
|
1960
|
-
const folded = [];
|
|
1961
|
-
if (prefixEntries.every((e) => e.ids.every((id) => prefixById.has(id)))) {
|
|
1962
|
-
for (const e of prefixEntries) folded.push({ type: e.type, buf: e.ids.map((id) => prefixById.get(id)) });
|
|
1963
|
-
const streamFolded = [];
|
|
1964
|
-
foldMessages(patchedStream, (type, buf) => streamFolded.push({ type, buf }));
|
|
1965
|
-
const lastPrefix = folded[folded.length - 1];
|
|
1966
|
-
const firstStream = streamFolded[0];
|
|
1967
|
-
if (lastPrefix && firstStream && canMergeAtBoundary(lastPrefix, firstStream)) {
|
|
1968
|
-
lastPrefix.buf = [...lastPrefix.buf, ...firstStream.buf];
|
|
1969
|
-
streamFolded.shift();
|
|
1970
|
-
}
|
|
1971
|
-
folded.push(...streamFolded);
|
|
1972
|
-
} else {
|
|
1973
|
-
foldCache.pageCount = -1;
|
|
1974
|
-
foldCache.entries = [];
|
|
1975
|
-
foldMessages(patched, (type, buf) => folded.push({ type, buf }));
|
|
1976
|
-
}
|
|
1977
|
-
const groups = [];
|
|
1978
|
-
let epochActiveFrom = 0;
|
|
1979
|
-
if (streaming && !runIdFilter) {
|
|
1980
|
-
epochActiveFrom = -1;
|
|
1981
|
-
folded.forEach((entry, i) => {
|
|
1982
|
-
const id = String(asSxin(entry.buf[0]).id || "");
|
|
1983
|
-
if (entry.type === "human" && sourceOf(id) === "stream" && epochOf(id) === currentEpoch) epochActiveFrom = i;
|
|
1984
|
-
});
|
|
1985
|
-
if (epochActiveFrom < 0) epochActiveFrom = 0;
|
|
1986
|
-
}
|
|
1987
|
-
folded.forEach((entry, gi) => {
|
|
1988
|
-
const firstId = String(asSxin(entry.buf[0]).id || "");
|
|
1989
|
-
const firstSource = sourceOf(firstId);
|
|
1990
|
-
let groupRunId = messageRunId(entry.buf[0]);
|
|
1991
|
-
if (!groupRunId) {
|
|
1992
|
-
for (let i = 1; i < entry.buf.length; i++) {
|
|
1993
|
-
const rid = messageRunId(entry.buf[i]);
|
|
1994
|
-
if (rid) {
|
|
1995
|
-
groupRunId = rid;
|
|
1996
|
-
break;
|
|
1997
|
-
}
|
|
1998
|
-
}
|
|
1999
|
-
}
|
|
2000
|
-
groupRunId = groupRunId || void 0;
|
|
2001
|
-
const inActiveZone = streaming ? runIdFilter ? groupRunId === runIdFilter : firstSource === "stream" && epochOf(firstId) === currentEpoch && gi >= epochActiveFrom : false;
|
|
2002
|
-
const status = inActiveZone ? "streaming" : "completed";
|
|
2003
|
-
const blockSource = firstSource === "page" ? "history" : "sse";
|
|
2004
|
-
let verSum = 0;
|
|
2005
|
-
for (const m of entry.buf) verSum += store.getEntity(String(asSxin(m).id || ""))?.ver ?? 0;
|
|
2006
|
-
const memoKey = `${firstId}|${status}|${blockSource}|${entry.buf.length}|${verSum}|${enrichments.citationVersion}`;
|
|
2007
|
-
const cached = groupMemo.get(memoKey);
|
|
2008
|
-
if (cached) {
|
|
2009
|
-
groups.push(cached);
|
|
2010
|
-
return;
|
|
2011
|
-
}
|
|
2012
|
-
let g;
|
|
2013
|
-
if (entry.type === "human") {
|
|
2014
|
-
g = buildHumanGroup(entry.buf, status);
|
|
2015
|
-
} else {
|
|
2016
|
-
g = buildAiGroup(entry.buf, { source: blockSource, isStreaming: status === "streaming" }, deps.twin);
|
|
2017
|
-
}
|
|
2018
|
-
if (groupMemo.size > 2e3) groupMemo.clear();
|
|
2019
|
-
groupMemo.set(memoKey, g);
|
|
2020
|
-
groups.push(g);
|
|
2021
|
-
});
|
|
2022
|
-
for (const g of groups) {
|
|
2023
|
-
if (g.type === "ai" && g.status === "streaming") {
|
|
2024
|
-
const aiMessages = g.rawMessages.filter((m) => String(asSxin(m).type || "").startsWith("ai"));
|
|
2025
|
-
const lastAi = aiMessages[aiMessages.length - 1];
|
|
2026
|
-
g.streamingText = lastAi ? extractAiContentFromMessage(lastAi) : "";
|
|
2027
|
-
}
|
|
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;
|
|
2028
1570
|
}
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
(gs) => applyPatchesAndExtras(gs, state, runIdFilter),
|
|
2033
|
-
// 第 2 步:interrupt 审核块注入(去重记忆 interruptBlocks 为构建器公开职责)
|
|
2034
|
-
(gs) => withInterruptBlock(gs, {
|
|
2035
|
-
getInterrupt: deps.getInterrupt,
|
|
2036
|
-
respondedIds: deps.respondedIds,
|
|
2037
|
-
interruptBlocks
|
|
2038
|
-
}),
|
|
2039
|
-
// 第 3 步:澄清回答 / interrupt 响应标记装饰
|
|
2040
|
-
(gs) => decorateAnswers(gs, enrichments.answers, deps.respondedIds),
|
|
2041
|
-
// 第 4 步:隐藏「无可见内容」的 AI 空气泡
|
|
2042
|
-
filterInvisibleAiGroups
|
|
2043
|
-
];
|
|
2044
|
-
const merged = decorateSteps.reduce((gs, step) => step(gs), sourceGroups);
|
|
2045
|
-
return { groups: merged, sourceGroups };
|
|
2046
|
-
};
|
|
2047
|
-
return {
|
|
2048
|
-
derive,
|
|
2049
|
-
clearCache() {
|
|
2050
|
-
groupMemo.clear();
|
|
2051
|
-
foldCache.pageCount = -1;
|
|
2052
|
-
foldCache.entries = [];
|
|
2053
|
-
interruptBlocks.clear();
|
|
1571
|
+
if (String(m?.type || "") === "human") {
|
|
1572
|
+
const kwargs = extractKwargsPatch(m);
|
|
1573
|
+
if (kwargs) patch.additional_kwargs = kwargs;
|
|
2054
1574
|
}
|
|
2055
|
-
|
|
2056
|
-
}
|
|
2057
|
-
function canMergeAtBoundary(prefixLast, streamFirst) {
|
|
2058
|
-
if (prefixLast.type === "human" && streamFirst.type === "human") {
|
|
2059
|
-
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);
|
|
2060
1576
|
}
|
|
2061
|
-
|
|
2062
|
-
const mRunId = messageRunId(streamFirst.buf[0]);
|
|
2063
|
-
const groupRunId = messageRunId(prefixLast.buf[0]);
|
|
2064
|
-
return !(mRunId && groupRunId && mRunId !== groupRunId);
|
|
2065
|
-
}
|
|
2066
|
-
return false;
|
|
1577
|
+
return next;
|
|
2067
1578
|
}
|
|
2068
|
-
function
|
|
2069
|
-
|
|
1579
|
+
function createSemanticOverlay() {
|
|
1580
|
+
let patches = /* @__PURE__ */ new Map();
|
|
2070
1581
|
return {
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
}
|
|
2083
|
-
],
|
|
2084
|
-
additionalKwargs: options?.kwargs,
|
|
2085
|
-
blocks: [],
|
|
2086
|
-
toolIds: [],
|
|
2087
|
-
tools: [],
|
|
2088
|
-
createdAt: Date.now()
|
|
2089
|
-
};
|
|
2090
|
-
}
|
|
2091
|
-
|
|
2092
|
-
// src/runtime/thread-runtime.ts
|
|
2093
|
-
var import_vue7 = require("vue");
|
|
2094
|
-
|
|
2095
|
-
// src/message/dict-merge.ts
|
|
2096
|
-
var MERGE_IGNORE_KEYS = ["index", "created", "timestamp"];
|
|
2097
|
-
var MERGE_RIGHT_WINS_KEYS = ["id", "name", "output_version", "model_provider"];
|
|
2098
|
-
function hasMergeableIndex(value) {
|
|
2099
|
-
if (typeof value !== "object" || value === null) return false;
|
|
2100
|
-
const idx = value.index;
|
|
2101
|
-
return typeof idx === "number" || typeof idx === "string";
|
|
2102
|
-
}
|
|
2103
|
-
function hasMergeableId(value) {
|
|
2104
|
-
if (typeof value !== "object" || value === null) return false;
|
|
2105
|
-
const id = value.id;
|
|
2106
|
-
return id != null && id !== "";
|
|
2107
|
-
}
|
|
2108
|
-
function findMergeTarget(merged, item) {
|
|
2109
|
-
if (!hasMergeableIndex(item) && !hasMergeableId(item)) return -1;
|
|
2110
|
-
return merged.findIndex((leftItem) => {
|
|
2111
|
-
const leftHasIndex = hasMergeableIndex(leftItem);
|
|
2112
|
-
const leftHasId = hasMergeableId(leftItem);
|
|
2113
|
-
const itemHasIndex = hasMergeableIndex(item);
|
|
2114
|
-
const itemHasId = hasMergeableId(item);
|
|
2115
|
-
if (itemHasIndex && leftHasIndex) {
|
|
2116
|
-
if (leftItem.index !== item.index) return false;
|
|
2117
|
-
if (leftHasId && itemHasId)
|
|
2118
|
-
return leftItem.id === item.id;
|
|
2119
|
-
return true;
|
|
2120
|
-
}
|
|
2121
|
-
if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {
|
|
2122
|
-
return leftItem.id === item.id;
|
|
2123
|
-
}
|
|
2124
|
-
return false;
|
|
2125
|
-
});
|
|
2126
|
-
}
|
|
2127
|
-
function mergeStringField(key, left, right) {
|
|
2128
|
-
if (key === "type") return left;
|
|
2129
|
-
if (MERGE_RIGHT_WINS_KEYS.includes(key)) return right || left;
|
|
2130
|
-
if (MERGE_IGNORE_KEYS.includes(key)) return left;
|
|
2131
|
-
return left + right;
|
|
2132
|
-
}
|
|
2133
|
-
function mergeNumberField(key, left, right) {
|
|
2134
|
-
return MERGE_IGNORE_KEYS.includes(key) ? left : left + right;
|
|
2135
|
-
}
|
|
2136
|
-
function mergeDicts(left, right) {
|
|
2137
|
-
if (left == null) return right;
|
|
2138
|
-
if (right == null) return left;
|
|
2139
|
-
if (Array.isArray(left) && Array.isArray(right)) return mergeLists(left, right);
|
|
2140
|
-
if (typeof left === "string" && typeof right === "string") return left + right;
|
|
2141
|
-
if (typeof left === "number" && typeof right === "number") return left + right;
|
|
2142
|
-
if (typeof left === "object" && typeof right === "object") {
|
|
2143
|
-
const merged = { ...left };
|
|
2144
|
-
for (const [key, value] of Object.entries(right)) {
|
|
2145
|
-
const l = merged[key];
|
|
2146
|
-
if (l == null) {
|
|
2147
|
-
merged[key] = value;
|
|
2148
|
-
} else if (value == null) {
|
|
2149
|
-
continue;
|
|
2150
|
-
} else if (typeof l === "string" && typeof value === "string") {
|
|
2151
|
-
merged[key] = mergeStringField(key, l, value);
|
|
2152
|
-
} else if (typeof l === "number" && typeof value === "number") {
|
|
2153
|
-
merged[key] = mergeNumberField(key, l, value);
|
|
2154
|
-
} else if (Array.isArray(l) && Array.isArray(value)) {
|
|
2155
|
-
merged[key] = mergeLists(l, value);
|
|
2156
|
-
} else if (typeof l === "object" && typeof value === "object") {
|
|
2157
|
-
merged[key] = mergeDicts(l, value);
|
|
2158
|
-
} else {
|
|
2159
|
-
merged[key] = value;
|
|
2160
|
-
}
|
|
2161
|
-
}
|
|
2162
|
-
return merged;
|
|
2163
|
-
}
|
|
2164
|
-
return right;
|
|
2165
|
-
}
|
|
2166
|
-
function mergeLists(left, right) {
|
|
2167
|
-
const merged = [...left];
|
|
2168
|
-
for (const item of right) {
|
|
2169
|
-
const target = findMergeTarget(merged, item);
|
|
2170
|
-
if (target !== -1) {
|
|
2171
|
-
merged[target] = mergeDicts(merged[target], item);
|
|
2172
|
-
} else if (typeof item === "object" && item !== null && "text" in item && item.text === "") {
|
|
2173
|
-
continue;
|
|
2174
|
-
} else {
|
|
2175
|
-
merged.push(item);
|
|
2176
|
-
}
|
|
2177
|
-
}
|
|
2178
|
-
return merged;
|
|
2179
|
-
}
|
|
2180
|
-
function mergeContent(left, right) {
|
|
2181
|
-
if (left == null) return right;
|
|
2182
|
-
if (right == null) return left;
|
|
2183
|
-
if (typeof left === "string" && typeof right === "string") return left + right;
|
|
2184
|
-
const leftArr = Array.isArray(left) ? left : [left];
|
|
2185
|
-
const rightArr = Array.isArray(right) ? right : [right];
|
|
2186
|
-
return mergeLists(leftArr, rightArr);
|
|
2187
|
-
}
|
|
2188
|
-
function parsePartialJson(text) {
|
|
2189
|
-
const tryParse = (s) => {
|
|
2190
|
-
try {
|
|
2191
|
-
return JSON.parse(s);
|
|
2192
|
-
} catch {
|
|
2193
|
-
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();
|
|
2194
1593
|
}
|
|
2195
1594
|
};
|
|
2196
|
-
const direct = tryParse(text);
|
|
2197
|
-
if (direct !== void 0) return direct;
|
|
2198
|
-
let fixed = text;
|
|
2199
|
-
let inStr = false;
|
|
2200
|
-
let escaped = false;
|
|
2201
|
-
for (const ch of fixed) {
|
|
2202
|
-
if (escaped) {
|
|
2203
|
-
escaped = false;
|
|
2204
|
-
continue;
|
|
2205
|
-
}
|
|
2206
|
-
if (ch === "\\") {
|
|
2207
|
-
escaped = true;
|
|
2208
|
-
continue;
|
|
2209
|
-
}
|
|
2210
|
-
if (ch === '"') inStr = !inStr;
|
|
2211
|
-
}
|
|
2212
|
-
if (inStr) fixed += '"';
|
|
2213
|
-
const closers = [];
|
|
2214
|
-
for (const ch of fixed) {
|
|
2215
|
-
if (ch === "{") closers.push("}");
|
|
2216
|
-
else if (ch === "[") closers.push("]");
|
|
2217
|
-
else if (ch === "}" || ch === "]") closers.pop();
|
|
2218
|
-
}
|
|
2219
|
-
fixed += closers.reverse().join("");
|
|
2220
|
-
const repaired = tryParse(fixed);
|
|
2221
|
-
return repaired === void 0 ? null : repaired;
|
|
2222
|
-
}
|
|
2223
|
-
function collapseToolCallChunks(chunks) {
|
|
2224
|
-
const groups = [];
|
|
2225
|
-
for (const chunk of chunks) {
|
|
2226
|
-
const matched = groups.findIndex((group) => {
|
|
2227
|
-
const match = group[0];
|
|
2228
|
-
if (chunk?.id && chunk?.index !== void 0) return chunk.id === match.id && chunk.index === match.index;
|
|
2229
|
-
if (chunk?.id) return chunk.id === match.id;
|
|
2230
|
-
if (chunk?.index !== void 0) return chunk.index === match.index;
|
|
2231
|
-
return false;
|
|
2232
|
-
});
|
|
2233
|
-
if (matched !== -1) groups[matched].push(chunk);
|
|
2234
|
-
else groups.push([chunk]);
|
|
2235
|
-
}
|
|
2236
|
-
const toolCalls = [];
|
|
2237
|
-
const invalidToolCalls = [];
|
|
2238
|
-
for (const group of groups) {
|
|
2239
|
-
const name = group[0]?.name ?? "";
|
|
2240
|
-
const joinedArgs = group.map((c) => c?.args || "").join("");
|
|
2241
|
-
const argsStr = joinedArgs.trim().length ? joinedArgs.trim() : "{}";
|
|
2242
|
-
const id = group.find((c) => c?.id)?.id ?? group[0]?.id;
|
|
2243
|
-
const parsed = parsePartialJson(argsStr);
|
|
2244
|
-
if (!id || parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
2245
|
-
invalidToolCalls.push({ name, args: argsStr, id, error: "Malformed args.", type: "invalid_tool_call" });
|
|
2246
|
-
} else {
|
|
2247
|
-
toolCalls.push({ name, args: parsed, id, type: "tool_call" });
|
|
2248
|
-
}
|
|
2249
|
-
}
|
|
2250
|
-
return { tool_calls: toolCalls, invalid_tool_calls: invalidToolCalls };
|
|
2251
|
-
}
|
|
2252
|
-
function extractToolCallsFromContent(content) {
|
|
2253
|
-
if (!Array.isArray(content)) return [];
|
|
2254
|
-
return content.flatMap((block) => {
|
|
2255
|
-
if (block == null || typeof block !== "object") return [];
|
|
2256
|
-
const record = block;
|
|
2257
|
-
if (record.type !== "tool_call" && record.type !== "tool_use") return [];
|
|
2258
|
-
const rawArgs = record.args ?? record.input;
|
|
2259
|
-
let args = {};
|
|
2260
|
-
if (rawArgs != null && typeof rawArgs === "object" && !Array.isArray(rawArgs)) args = rawArgs;
|
|
2261
|
-
else if (typeof rawArgs === "string" && rawArgs.length > 0) {
|
|
2262
|
-
const parsed = parsePartialJson(rawArgs);
|
|
2263
|
-
if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) args = parsed;
|
|
2264
|
-
}
|
|
2265
|
-
return [{ id: record.id ?? "", name: record.name ?? "", args, type: "tool_call" }];
|
|
2266
|
-
});
|
|
2267
1595
|
}
|
|
2268
|
-
function
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
if (
|
|
2276
|
-
|
|
2277
|
-
continue;
|
|
2278
|
-
}
|
|
2279
|
-
if (key === "content") {
|
|
2280
|
-
merged.content = mergeContent(prev.content, value);
|
|
2281
|
-
} else if (key === "tool_call_chunks") {
|
|
2282
|
-
const prevChunks = Array.isArray(prev.tool_call_chunks) ? prev.tool_call_chunks : [];
|
|
2283
|
-
const nextChunks = Array.isArray(value) ? value : [];
|
|
2284
|
-
const chunks = mergeLists(prevChunks, nextChunks);
|
|
2285
|
-
merged.tool_call_chunks = chunks;
|
|
2286
|
-
const collapsed = collapseToolCallChunks(chunks);
|
|
2287
|
-
merged.tool_calls = collapsed.tool_calls;
|
|
2288
|
-
merged.invalid_tool_calls = collapsed.invalid_tool_calls;
|
|
2289
|
-
} else {
|
|
2290
|
-
merged[key] = mergeDicts(prev[key], value);
|
|
2291
|
-
}
|
|
2292
|
-
}
|
|
2293
|
-
if (!Array.isArray(merged.tool_calls) || merged.tool_calls.length === 0) {
|
|
2294
|
-
const extracted = extractToolCallsFromContent(merged.content);
|
|
2295
|
-
if (extracted.length > 0) merged.tool_calls = extracted;
|
|
2296
|
-
}
|
|
2297
|
-
return merged;
|
|
2298
|
-
}
|
|
2299
|
-
|
|
2300
|
-
// src/protocol/chunk-buffer.ts
|
|
2301
|
-
function normalizeEntry(raw) {
|
|
2302
|
-
const rawType = String(raw.type || "");
|
|
2303
|
-
if (rawType === "RemoveMessage") return { ...raw, type: "remove" };
|
|
2304
|
-
return raw;
|
|
2305
|
-
}
|
|
2306
|
-
function stampRunId(msg, streamRunId) {
|
|
2307
|
-
if (String(msg.runId || "").trim()) return msg;
|
|
2308
|
-
const kwargsRunId = String(msg.additional_kwargs?.run_id || "").trim();
|
|
2309
|
-
const rid = kwargsRunId || String(streamRunId || "").trim();
|
|
2310
|
-
if (!rid) return msg;
|
|
2311
|
-
return { ...msg, runId: rid };
|
|
2312
|
-
}
|
|
2313
|
-
function createChunkBuffer(options) {
|
|
2314
|
-
const schedule = options.schedule ?? ((fn) => setTimeout(fn, 0));
|
|
2315
|
-
const pending = /* @__PURE__ */ new Map();
|
|
2316
|
-
const accumulated = /* @__PURE__ */ new Map();
|
|
2317
|
-
let order = [];
|
|
2318
|
-
const dirty = /* @__PURE__ */ new Set();
|
|
2319
|
-
let scheduled = false;
|
|
2320
|
-
let timer = null;
|
|
2321
|
-
let streamRunId;
|
|
2322
|
-
const cancelSchedule = () => {
|
|
2323
|
-
scheduled = false;
|
|
2324
|
-
if (timer !== null) clearTimeout(timer);
|
|
2325
|
-
timer = null;
|
|
2326
|
-
};
|
|
2327
|
-
const scheduleFlush = () => {
|
|
2328
|
-
if (scheduled) return;
|
|
2329
|
-
scheduled = true;
|
|
2330
|
-
timer = schedule(() => {
|
|
2331
|
-
scheduled = false;
|
|
2332
|
-
timer = null;
|
|
2333
|
-
flush();
|
|
2334
|
-
});
|
|
2335
|
-
};
|
|
2336
|
-
function flush() {
|
|
2337
|
-
if (!order.length) return;
|
|
2338
|
-
const instructions = [];
|
|
2339
|
-
for (const id of order) {
|
|
2340
|
-
const entry = pending.get(id);
|
|
2341
|
-
if (!entry) continue;
|
|
2342
|
-
if (entry.isClear) {
|
|
2343
|
-
instructions.push({ kind: "clear" });
|
|
2344
|
-
accumulated.clear();
|
|
2345
|
-
continue;
|
|
2346
|
-
}
|
|
2347
|
-
if (entry.isRemove) {
|
|
2348
|
-
instructions.push({ kind: "remove", id });
|
|
2349
|
-
accumulated.delete(id);
|
|
2350
|
-
continue;
|
|
2351
|
-
}
|
|
2352
|
-
const base = accumulated.get(id);
|
|
2353
|
-
const merged = base ? entry.parts.reduce((acc, c) => mergeMessageDicts(acc, c), base) : entry.parts.reduce(mergeMessageDicts);
|
|
2354
|
-
accumulated.set(id, merged);
|
|
2355
|
-
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 };
|
|
2356
1605
|
}
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
const raw = serialized;
|
|
2366
|
-
const rawType = String(raw.type || "");
|
|
2367
|
-
const entry = normalizeEntry(raw);
|
|
2368
|
-
const type = String(entry.type || "");
|
|
2369
|
-
const id = String(entry.id || "").trim();
|
|
2370
|
-
if (!id) return;
|
|
2371
|
-
if (type === "remove") {
|
|
2372
|
-
if (id === "__remove_all__") {
|
|
2373
|
-
pending.set(id, { parts: [], isClear: true });
|
|
2374
|
-
} else {
|
|
2375
|
-
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;
|
|
2376
1614
|
}
|
|
2377
|
-
if (!dirty.has(id)) {
|
|
2378
|
-
dirty.add(id);
|
|
2379
|
-
order.push(id);
|
|
2380
|
-
}
|
|
2381
|
-
scheduleFlush();
|
|
2382
|
-
return;
|
|
2383
|
-
}
|
|
2384
|
-
const isChunk = rawType.endsWith("MessageChunk");
|
|
2385
|
-
const existing = pending.get(id);
|
|
2386
|
-
if (!existing || existing.isRemove) {
|
|
2387
|
-
pending.set(id, { parts: [entry] });
|
|
2388
|
-
} else if (!isChunk) {
|
|
2389
|
-
existing.parts = [entry];
|
|
2390
|
-
} else {
|
|
2391
|
-
existing.parts.push(entry);
|
|
2392
1615
|
}
|
|
2393
|
-
if (
|
|
2394
|
-
dirty.add(id);
|
|
2395
|
-
order.push(id);
|
|
2396
|
-
}
|
|
2397
|
-
scheduleFlush();
|
|
2398
|
-
},
|
|
2399
|
-
noteStreamRunId(runId) {
|
|
2400
|
-
const trimmed = String(runId || "").trim();
|
|
2401
|
-
if (trimmed) streamRunId = trimmed;
|
|
2402
|
-
},
|
|
2403
|
-
reset() {
|
|
2404
|
-
cancelSchedule();
|
|
2405
|
-
pending.clear();
|
|
2406
|
-
order = [];
|
|
2407
|
-
dirty.clear();
|
|
2408
|
-
accumulated.clear();
|
|
2409
|
-
streamRunId = void 0;
|
|
2410
|
-
},
|
|
2411
|
-
flush,
|
|
2412
|
-
dispose() {
|
|
2413
|
-
cancelSchedule();
|
|
2414
|
-
pending.clear();
|
|
2415
|
-
order = [];
|
|
2416
|
-
dirty.clear();
|
|
2417
|
-
accumulated.clear();
|
|
1616
|
+
if (changed) next = { ...next, additional_kwargs: merged };
|
|
2418
1617
|
}
|
|
2419
|
-
|
|
1618
|
+
return next;
|
|
1619
|
+
});
|
|
2420
1620
|
}
|
|
2421
1621
|
|
|
1622
|
+
// src/runtime/thread-runtime.ts
|
|
1623
|
+
var import_vue6 = require("vue");
|
|
1624
|
+
|
|
2422
1625
|
// src/runtime/history-pager.ts
|
|
2423
|
-
var
|
|
1626
|
+
var import_vue = require("vue");
|
|
2424
1627
|
function createHistoryPager(options) {
|
|
2425
1628
|
const { threadId, transport, firstPage } = options;
|
|
2426
1629
|
let cursor = firstPage.nextBeforeSeq;
|
|
2427
|
-
const hasMoreRef = (0,
|
|
2428
|
-
const loading = (0,
|
|
1630
|
+
const hasMoreRef = (0, import_vue.ref)(Boolean(firstPage.hasMore) && firstPage.nextBeforeSeq !== void 0);
|
|
1631
|
+
const loading = (0, import_vue.ref)(false);
|
|
2429
1632
|
const loadOlder = async () => {
|
|
2430
1633
|
if (loading.value) return hasMoreRef.value;
|
|
2431
1634
|
if (!hasMoreRef.value || cursor === void 0) {
|
|
@@ -2436,7 +1639,7 @@ function createHistoryPager(options) {
|
|
|
2436
1639
|
try {
|
|
2437
1640
|
const page = await transport.fetchMessagesPage(threadId, { beforeSeq: cursor });
|
|
2438
1641
|
const pageMessages = runMessagesToMessages(page.messages);
|
|
2439
|
-
options.emitChanges(
|
|
1642
|
+
options.emitChanges();
|
|
2440
1643
|
cursor = page.nextBeforeSeq;
|
|
2441
1644
|
hasMoreRef.value = Boolean(page.hasMore) && page.nextBeforeSeq !== void 0;
|
|
2442
1645
|
options.onPageLoaded?.(page);
|
|
@@ -2445,7 +1648,7 @@ function createHistoryPager(options) {
|
|
|
2445
1648
|
loading.value = false;
|
|
2446
1649
|
}
|
|
2447
1650
|
};
|
|
2448
|
-
return { loadOlder, hasMore: (0,
|
|
1651
|
+
return { loadOlder, hasMore: (0, import_vue.computed)(() => hasMoreRef.value), loading };
|
|
2449
1652
|
}
|
|
2450
1653
|
|
|
2451
1654
|
// src/runtime/runtime-bootstrap.ts
|
|
@@ -2453,22 +1656,30 @@ async function bootstrapRuntime(deps) {
|
|
|
2453
1656
|
const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
|
|
2454
1657
|
deps.valuesChannel.applyInitialValues(fetched.values);
|
|
2455
1658
|
deps.valuesChannel.applyThreadState(fetched.threadState);
|
|
2456
|
-
deps.
|
|
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
|
+
}
|
|
2457
1663
|
deps.runs.fillFromRunsList(fetched.runsList ?? []);
|
|
2458
1664
|
deps.runs.enrichFromPage(fetched.messagesPage);
|
|
2459
1665
|
const pageMessages = runMessagesToMessages(fetched.messagesPage.messages);
|
|
2460
|
-
|
|
1666
|
+
const seeded = applySemanticPatches(pageMessages, deps.overlay.getPatches());
|
|
1667
|
+
if (seeded.length) deps.rm.hydrate(seeded);
|
|
1668
|
+
deps.rm.applySemanticPatch(deps.overlay.getPatches());
|
|
2461
1669
|
deps.setPager(
|
|
2462
1670
|
createHistoryPager({
|
|
2463
1671
|
threadId: deps.threadId,
|
|
2464
1672
|
transport: deps.transport,
|
|
2465
1673
|
firstPage: fetched.messagesPage,
|
|
2466
|
-
onPageLoaded: (page) =>
|
|
2467
|
-
|
|
1674
|
+
onPageLoaded: (page) => {
|
|
1675
|
+
deps.runs.enrichFromPage(page);
|
|
1676
|
+
deps.rm.prependHistory(runMessagesToMessages(page.messages));
|
|
1677
|
+
},
|
|
1678
|
+
emitChanges: () => {
|
|
1679
|
+
}
|
|
2468
1680
|
})
|
|
2469
1681
|
);
|
|
2470
1682
|
await deps.refreshTokenUsage();
|
|
2471
|
-
deps.setChunkBuffer(createChunkBuffer({ emit: (ins) => deps.store.applyInstructions(ins) }));
|
|
2472
1683
|
const finalize = () => finalizeAfterStream(deps);
|
|
2473
1684
|
const afterFinish = () => afterStreamFinish(deps);
|
|
2474
1685
|
deps.streamRef.value = deps.transport.createStream({
|
|
@@ -2477,7 +1688,9 @@ async function bootstrapRuntime(deps) {
|
|
|
2477
1688
|
onCreated: (run) => deps.markStreamRun(run?.run_id),
|
|
2478
1689
|
onMetadataEvent: (data) => deps.markStreamRun(data?.run_id),
|
|
2479
1690
|
onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
|
|
2480
|
-
onMessageTupleEvent: (
|
|
1691
|
+
onMessageTupleEvent: () => {
|
|
1692
|
+
},
|
|
1693
|
+
onSnapshotMessages: (messages) => deps.rm.applySnapshot(messages),
|
|
2481
1694
|
onStreamStart: deps.onStreamStart,
|
|
2482
1695
|
onStreamEnd: finalize,
|
|
2483
1696
|
onFinish: afterFinish,
|
|
@@ -2486,52 +1699,38 @@ async function bootstrapRuntime(deps) {
|
|
|
2486
1699
|
deps.setInitialized();
|
|
2487
1700
|
}
|
|
2488
1701
|
function finalizeAfterStream(deps) {
|
|
2489
|
-
deps.
|
|
2490
|
-
deps.
|
|
2491
|
-
deps.
|
|
2492
|
-
deps.
|
|
2493
|
-
deps.runs.backfillCurrentRunMetadata(() => deps.store.getMessages());
|
|
2494
|
-
}
|
|
2495
|
-
function buildValuesReplaceInstructions(store, streamMessages) {
|
|
2496
|
-
const instructions = [];
|
|
2497
|
-
for (const msg of streamMessages) {
|
|
2498
|
-
const id = String(msg?.id || "").trim();
|
|
2499
|
-
if (!id) continue;
|
|
2500
|
-
const existing = store.getEntity(id);
|
|
2501
|
-
if (!existing) continue;
|
|
2502
|
-
if (existing.source !== "stream" || existing.epoch !== store.streamEpoch) continue;
|
|
2503
|
-
const runId = String(existing.msg?.runId || existing.msg?.additional_kwargs?.run_id || "").trim();
|
|
2504
|
-
const next = runId ? { ...msg, runId } : msg;
|
|
2505
|
-
instructions.push({ kind: "upsert", message: next });
|
|
2506
|
-
}
|
|
2507
|
-
return instructions;
|
|
1702
|
+
deps.rm.finalize();
|
|
1703
|
+
deps.onStreamSettled();
|
|
1704
|
+
deps.runs.backfillCurrentRunMetadata(() => [...deps.rm.lastMessages()]);
|
|
1705
|
+
deps.rm.applySemanticPatch(extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages()));
|
|
2508
1706
|
}
|
|
2509
1707
|
async function afterStreamFinish(deps) {
|
|
2510
1708
|
await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
|
|
2511
1709
|
await reconcileWithPage(deps);
|
|
2512
|
-
await
|
|
1710
|
+
await refreshSemanticLayer(deps);
|
|
1711
|
+
}
|
|
1712
|
+
async function refreshSemanticLayer(deps) {
|
|
1713
|
+
try {
|
|
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}`);
|
|
1720
|
+
}
|
|
1721
|
+
} catch (e) {
|
|
1722
|
+
console.warn("[runtime] \u8BED\u4E49\u5C42\u5237\u65B0\u5931\u8D25", e);
|
|
1723
|
+
}
|
|
2513
1724
|
}
|
|
2514
1725
|
async function reconcileWithPage(deps) {
|
|
2515
1726
|
try {
|
|
2516
1727
|
const page = await deps.transport.fetchMessagesPage(deps.threadId);
|
|
2517
1728
|
const messages = runMessagesToMessages(page.messages);
|
|
2518
|
-
if (messages.length)
|
|
2519
|
-
deps.store.applyInstructions(messages.map((message) => ({ kind: "upsert", message, source: "page" })));
|
|
2520
|
-
}
|
|
1729
|
+
if (messages.length) deps.rm.reconcileWithPage(messages);
|
|
2521
1730
|
} catch (e) {
|
|
2522
1731
|
console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
|
|
2523
1732
|
}
|
|
2524
1733
|
}
|
|
2525
|
-
async function applyCitationsFallback(deps) {
|
|
2526
|
-
if (deps.valuesChannel.getStreamMessages().length > 0) return;
|
|
2527
|
-
try {
|
|
2528
|
-
const state = await deps.transport.fetchThreadState(deps.threadId);
|
|
2529
|
-
if (!state) return;
|
|
2530
|
-
deps.enrichments.applyFromStateMessages(extractStateMessages(state));
|
|
2531
|
-
} catch (e) {
|
|
2532
|
-
console.warn("[runtime] citation state \u515C\u5E95\u63D0\u53D6\u5931\u8D25", e);
|
|
2533
|
-
}
|
|
2534
|
-
}
|
|
2535
1734
|
async function runRuntimeInit(deps, hooks) {
|
|
2536
1735
|
hooks.onStart();
|
|
2537
1736
|
try {
|
|
@@ -2541,11 +1740,797 @@ async function runRuntimeInit(deps, hooks) {
|
|
|
2541
1740
|
}
|
|
2542
1741
|
}
|
|
2543
1742
|
|
|
2544
|
-
// src/
|
|
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
|
|
2545
2530
|
var import_vue4 = require("vue");
|
|
2546
2531
|
var import_ui = require("@langchain/langgraph-sdk/ui");
|
|
2547
2532
|
|
|
2548
|
-
// src/
|
|
2533
|
+
// src/runtime/interrupt-reconcile.ts
|
|
2549
2534
|
function reconcileInterrupts(prevValues, nextValues, firstEvent) {
|
|
2550
2535
|
let base = prevValues;
|
|
2551
2536
|
if (firstEvent && base && "__interrupt__" in base) {
|
|
@@ -2579,7 +2564,7 @@ function reconcileInterrupts(prevValues, nextValues, firstEvent) {
|
|
|
2579
2564
|
return nextValues ?? {};
|
|
2580
2565
|
}
|
|
2581
2566
|
|
|
2582
|
-
// src/
|
|
2567
|
+
// src/runtime/values-projection.ts
|
|
2583
2568
|
function createValuesChannel(options = {}) {
|
|
2584
2569
|
const valuesRef = (0, import_vue4.shallowRef)({});
|
|
2585
2570
|
const threadStateRef = (0, import_vue4.shallowRef)(void 0);
|
|
@@ -2629,197 +2614,8 @@ function createValuesChannel(options = {}) {
|
|
|
2629
2614
|
};
|
|
2630
2615
|
}
|
|
2631
2616
|
|
|
2632
|
-
// src/store/
|
|
2617
|
+
// src/store/runs-store.ts
|
|
2633
2618
|
var import_vue5 = require("vue");
|
|
2634
|
-
function createThreadStore(_options = {}) {
|
|
2635
|
-
const entities = /* @__PURE__ */ new Map();
|
|
2636
|
-
let order = [];
|
|
2637
|
-
let pageCountCache = -1;
|
|
2638
|
-
let cachedFlat = null;
|
|
2639
|
-
const version = (0, import_vue5.ref)(0);
|
|
2640
|
-
const streamStatusRef = (0, import_vue5.shallowRef)("idle");
|
|
2641
|
-
let streamEpoch = 0;
|
|
2642
|
-
const leadingPageCount = () => {
|
|
2643
|
-
let i = 0;
|
|
2644
|
-
while (i < order.length && entities.get(order[i])?.source === "page") i++;
|
|
2645
|
-
return i;
|
|
2646
|
-
};
|
|
2647
|
-
const lastPageIndex = () => {
|
|
2648
|
-
for (let i = order.length - 1; i >= 0; i--) {
|
|
2649
|
-
if (entities.get(order[i])?.source === "page") return i;
|
|
2650
|
-
}
|
|
2651
|
-
return -1;
|
|
2652
|
-
};
|
|
2653
|
-
const bump = () => {
|
|
2654
|
-
cachedFlat = null;
|
|
2655
|
-
pageCountCache = -1;
|
|
2656
|
-
version.value++;
|
|
2657
|
-
};
|
|
2658
|
-
const applyInstructions = (instructions) => {
|
|
2659
|
-
if (!instructions.length) return;
|
|
2660
|
-
let touched = false;
|
|
2661
|
-
for (const ins of instructions) {
|
|
2662
|
-
switch (ins.kind) {
|
|
2663
|
-
case "upsert": {
|
|
2664
|
-
const id = String(ins.message.id || "").trim();
|
|
2665
|
-
if (!id) break;
|
|
2666
|
-
const message = normalizeMessageType(ins.message);
|
|
2667
|
-
const existing = entities.get(id);
|
|
2668
|
-
if (existing) {
|
|
2669
|
-
existing.msg = message;
|
|
2670
|
-
existing.ver++;
|
|
2671
|
-
if (ins.source === "page") {
|
|
2672
|
-
existing.source = "page";
|
|
2673
|
-
} else {
|
|
2674
|
-
existing.source = "stream";
|
|
2675
|
-
existing.epoch = streamEpoch;
|
|
2676
|
-
}
|
|
2677
|
-
} else {
|
|
2678
|
-
entities.set(id, {
|
|
2679
|
-
msg: message,
|
|
2680
|
-
source: ins.source === "page" ? "page" : "stream",
|
|
2681
|
-
epoch: streamEpoch,
|
|
2682
|
-
ver: 1
|
|
2683
|
-
});
|
|
2684
|
-
if (ins.source === "page") {
|
|
2685
|
-
order.splice(lastPageIndex() + 1, 0, id);
|
|
2686
|
-
} else {
|
|
2687
|
-
order.push(id);
|
|
2688
|
-
}
|
|
2689
|
-
}
|
|
2690
|
-
touched = true;
|
|
2691
|
-
break;
|
|
2692
|
-
}
|
|
2693
|
-
case "remove": {
|
|
2694
|
-
if (!entities.has(ins.id)) break;
|
|
2695
|
-
const idx = order.indexOf(ins.id);
|
|
2696
|
-
if (idx >= 0) order.splice(idx, 1);
|
|
2697
|
-
entities.delete(ins.id);
|
|
2698
|
-
touched = true;
|
|
2699
|
-
break;
|
|
2700
|
-
}
|
|
2701
|
-
case "clear": {
|
|
2702
|
-
const removed = order.splice(leadingPageCount());
|
|
2703
|
-
for (const id of removed) entities.delete(id);
|
|
2704
|
-
touched = touched || removed.length > 0;
|
|
2705
|
-
break;
|
|
2706
|
-
}
|
|
2707
|
-
case "prepend": {
|
|
2708
|
-
const fresh = [];
|
|
2709
|
-
for (const msg of ins.messages) {
|
|
2710
|
-
const id = String(msg.id || "").trim();
|
|
2711
|
-
if (!id || entities.has(id)) continue;
|
|
2712
|
-
entities.set(id, {
|
|
2713
|
-
msg: normalizeMessageType(msg),
|
|
2714
|
-
source: "page",
|
|
2715
|
-
epoch: streamEpoch,
|
|
2716
|
-
ver: 1
|
|
2717
|
-
});
|
|
2718
|
-
fresh.push(id);
|
|
2719
|
-
}
|
|
2720
|
-
if (fresh.length) {
|
|
2721
|
-
order = [...fresh, ...order];
|
|
2722
|
-
touched = true;
|
|
2723
|
-
}
|
|
2724
|
-
break;
|
|
2725
|
-
}
|
|
2726
|
-
case "finalize": {
|
|
2727
|
-
if (streamStatusRef.value !== "settled") {
|
|
2728
|
-
streamStatusRef.value = "settled";
|
|
2729
|
-
touched = true;
|
|
2730
|
-
}
|
|
2731
|
-
break;
|
|
2732
|
-
}
|
|
2733
|
-
}
|
|
2734
|
-
}
|
|
2735
|
-
if (touched) bump();
|
|
2736
|
-
};
|
|
2737
|
-
return {
|
|
2738
|
-
applyInstructions,
|
|
2739
|
-
beginStream() {
|
|
2740
|
-
streamEpoch++;
|
|
2741
|
-
streamStatusRef.value = "streaming";
|
|
2742
|
-
bump();
|
|
2743
|
-
},
|
|
2744
|
-
getEntity: (id) => entities.get(id),
|
|
2745
|
-
get order() {
|
|
2746
|
-
return order;
|
|
2747
|
-
},
|
|
2748
|
-
get pageCount() {
|
|
2749
|
-
if (pageCountCache < 0) pageCountCache = leadingPageCount();
|
|
2750
|
-
return pageCountCache;
|
|
2751
|
-
},
|
|
2752
|
-
getMessages() {
|
|
2753
|
-
if (!cachedFlat) cachedFlat = order.map((id) => entities.get(id).msg);
|
|
2754
|
-
return cachedFlat;
|
|
2755
|
-
},
|
|
2756
|
-
get streamStatus() {
|
|
2757
|
-
return streamStatusRef.value;
|
|
2758
|
-
},
|
|
2759
|
-
get streamEpoch() {
|
|
2760
|
-
return streamEpoch;
|
|
2761
|
-
},
|
|
2762
|
-
version,
|
|
2763
|
-
streamStatusRef
|
|
2764
|
-
};
|
|
2765
|
-
}
|
|
2766
|
-
function hasCitationInfo(v) {
|
|
2767
|
-
if (!v) return false;
|
|
2768
|
-
if (Array.isArray(v)) return v.length > 0;
|
|
2769
|
-
if (typeof v === "object") return Object.keys(v).length > 0;
|
|
2770
|
-
return Boolean(v);
|
|
2771
|
-
}
|
|
2772
|
-
function readContentText(content) {
|
|
2773
|
-
if (typeof content === "string") return content;
|
|
2774
|
-
if (Array.isArray(content)) {
|
|
2775
|
-
return content.map((c) => c?.type === "text" ? String(c.text || "") : "").join("");
|
|
2776
|
-
}
|
|
2777
|
-
return "";
|
|
2778
|
-
}
|
|
2779
|
-
function isCitationCarrier(msg) {
|
|
2780
|
-
const m = asSxin(msg);
|
|
2781
|
-
if (!isAiMessage(msg)) return false;
|
|
2782
|
-
if (readContentText(m.content).includes("<sxin-kb-citation")) return true;
|
|
2783
|
-
return hasCitationInfo(m.additional_kwargs?.citation_info);
|
|
2784
|
-
}
|
|
2785
|
-
function createEnrichments() {
|
|
2786
|
-
const citationPatches = (0, import_vue5.shallowReactive)(/* @__PURE__ */ new Map());
|
|
2787
|
-
const answers = (0, import_vue5.shallowReactive)(/* @__PURE__ */ new Map());
|
|
2788
|
-
let citationVersion = 0;
|
|
2789
|
-
return {
|
|
2790
|
-
get citationVersion() {
|
|
2791
|
-
return citationVersion;
|
|
2792
|
-
},
|
|
2793
|
-
applyFromStateMessages(messages) {
|
|
2794
|
-
for (const msg of messages) {
|
|
2795
|
-
const m = asSxin(msg);
|
|
2796
|
-
const id = String(m.id || "").trim();
|
|
2797
|
-
if (!id || !isCitationCarrier(msg)) continue;
|
|
2798
|
-
citationPatches.set(id, {
|
|
2799
|
-
content: m.content,
|
|
2800
|
-
citationInfo: m.additional_kwargs?.citation_info
|
|
2801
|
-
});
|
|
2802
|
-
citationVersion++;
|
|
2803
|
-
}
|
|
2804
|
-
const extracted = extractThreadInfo(messages).clarificationAnswers;
|
|
2805
|
-
for (const [key, value] of extracted) answers.set(key, value);
|
|
2806
|
-
},
|
|
2807
|
-
resolveCitation(messageId) {
|
|
2808
|
-
return citationPatches.get(messageId);
|
|
2809
|
-
},
|
|
2810
|
-
answers,
|
|
2811
|
-
setAnswer(requestId, answer) {
|
|
2812
|
-
answers.set(requestId, answer);
|
|
2813
|
-
},
|
|
2814
|
-
clearAnswers() {
|
|
2815
|
-
answers.clear();
|
|
2816
|
-
},
|
|
2817
|
-
dispose() {
|
|
2818
|
-
citationPatches.clear();
|
|
2819
|
-
answers.clear();
|
|
2820
|
-
}
|
|
2821
|
-
};
|
|
2822
|
-
}
|
|
2823
2619
|
function createInterruptState() {
|
|
2824
2620
|
const respondedIds = (0, import_vue5.shallowRef)(/* @__PURE__ */ new Set());
|
|
2825
2621
|
return {
|
|
@@ -2930,98 +2726,51 @@ function createRunsStore(options) {
|
|
|
2930
2726
|
};
|
|
2931
2727
|
}
|
|
2932
2728
|
|
|
2933
|
-
// src/runtime/derived-groups.ts
|
|
2934
|
-
var import_vue6 = require("vue");
|
|
2935
|
-
function createDerivedGroups(deps) {
|
|
2936
|
-
const deriver = createGroupDeriver(deps.state);
|
|
2937
|
-
const derived = (0, import_vue6.computed)(() => {
|
|
2938
|
-
deps.store.version.value;
|
|
2939
|
-
return deriver.derive({
|
|
2940
|
-
store: deps.store,
|
|
2941
|
-
enrichments: deps.enrichments,
|
|
2942
|
-
getInterrupt: () => deps.valuesChannel.getInterrupt({ isLoading: deps.streamRef.value?.isLoading.value ?? false }),
|
|
2943
|
-
respondedIds: deps.interruptState.respondedIds.value,
|
|
2944
|
-
currentRunId: deps.runs.currentRunId.value ?? void 0,
|
|
2945
|
-
twin: deps.twin
|
|
2946
|
-
});
|
|
2947
|
-
});
|
|
2948
|
-
deps.scope.run(() => {
|
|
2949
|
-
(0, import_vue6.watch)(
|
|
2950
|
-
() => [deps.store.version.value, deps.runs.currentRunId.value],
|
|
2951
|
-
() => {
|
|
2952
|
-
deps.state.pruneExtras(derived.value.sourceGroups, deps.runs.currentRunId.value ?? void 0);
|
|
2953
|
-
},
|
|
2954
|
-
{ flush: "sync" }
|
|
2955
|
-
);
|
|
2956
|
-
});
|
|
2957
|
-
const groups = (0, import_vue6.computed)(() => derived.value.groups);
|
|
2958
|
-
const sourceGroups = (0, import_vue6.computed)(() => derived.value.sourceGroups);
|
|
2959
|
-
return { groups, sourceGroups };
|
|
2960
|
-
}
|
|
2961
|
-
|
|
2962
2729
|
// src/runtime/thread-runtime.ts
|
|
2963
2730
|
function createThreadRuntime(options) {
|
|
2964
|
-
const scope = (0,
|
|
2965
|
-
const store = createThreadStore({ threadId: options.threadId });
|
|
2966
|
-
const enrichments = createEnrichments();
|
|
2731
|
+
const scope = (0, import_vue6.effectScope)();
|
|
2967
2732
|
const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
|
|
2968
2733
|
const interruptState = createInterruptState();
|
|
2969
|
-
const
|
|
2734
|
+
const rm = createRuntimeMaterializer({
|
|
2735
|
+
twin: options.twin,
|
|
2736
|
+
// 段级 runId 兜底源(metadata 首帧权威值):流式 tuple 消息本体无 runId,
|
|
2737
|
+
// 段打开/回填时经此兜底——点赞/反馈按 runId 提交的依赖
|
|
2738
|
+
getStreamRunId: () => runs.currentRunId.value
|
|
2739
|
+
});
|
|
2970
2740
|
const valuesChannel = createValuesChannel({
|
|
2971
2741
|
onTitle: (title) => options.onTitle?.(options.threadId, title)
|
|
2972
2742
|
});
|
|
2973
|
-
|
|
2974
|
-
const streamRef = (0,
|
|
2975
|
-
const isInitializing = (0,
|
|
2976
|
-
const
|
|
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);
|
|
2977
2748
|
let initialized = false;
|
|
2978
2749
|
let initPromise = null;
|
|
2979
2750
|
let pager = null;
|
|
2980
|
-
const
|
|
2981
|
-
|
|
2982
|
-
store,
|
|
2983
|
-
enrichments,
|
|
2984
|
-
state,
|
|
2985
|
-
runs,
|
|
2986
|
-
interruptState,
|
|
2987
|
-
valuesChannel,
|
|
2988
|
-
streamRef,
|
|
2989
|
-
twin: options.twin
|
|
2990
|
-
});
|
|
2991
|
-
const { groups, sourceGroups } = derivedGroups;
|
|
2992
|
-
const interrupt = (0, import_vue7.computed)(() => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }));
|
|
2993
|
-
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)(() => {
|
|
2994
2753
|
const it = interrupt.value;
|
|
2995
2754
|
return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
|
|
2996
2755
|
});
|
|
2997
|
-
const streamError = (0,
|
|
2998
|
-
const isGenerating = (0,
|
|
2999
|
-
const hasPendingClarification = (0, import_vue7.computed)(() => {
|
|
3000
|
-
store.version.value;
|
|
3001
|
-
const list = groups.value;
|
|
3002
|
-
return list.some((m, i) => {
|
|
3003
|
-
if (m.type !== "ai") return false;
|
|
3004
|
-
const hasUnanswered = m.blocks.some(
|
|
3005
|
-
(b) => isClarificationBlock(b) && !isClarificationAnswered(b, enrichments.answers)
|
|
3006
|
-
);
|
|
3007
|
-
if (!hasUnanswered) return false;
|
|
3008
|
-
return !list.slice(i + 1).some((x) => x.type === "human");
|
|
3009
|
-
});
|
|
3010
|
-
});
|
|
2756
|
+
const streamError = (0, import_vue6.computed)(() => streamRef.value?.error.value ?? null);
|
|
2757
|
+
const isGenerating = (0, import_vue6.computed)(() => streaming.value);
|
|
3011
2758
|
const beginStream = () => {
|
|
3012
|
-
chunkBuffer?.reset();
|
|
3013
2759
|
valuesChannel.beginStream();
|
|
2760
|
+
overlay.invalidate();
|
|
3014
2761
|
runs.currentRunId.value = null;
|
|
3015
2762
|
};
|
|
3016
2763
|
const streamStarted = () => {
|
|
3017
|
-
|
|
2764
|
+
streaming.value = true;
|
|
2765
|
+
};
|
|
2766
|
+
const streamSettled = () => {
|
|
2767
|
+
streaming.value = false;
|
|
3018
2768
|
};
|
|
3019
2769
|
const markStreamRun = (runIdRaw) => {
|
|
3020
2770
|
const runId = String(runIdRaw || "").trim();
|
|
3021
2771
|
if (!runId) return;
|
|
3022
2772
|
runs.currentRunId.value = runId;
|
|
3023
2773
|
runs.ensureRunning(runId);
|
|
3024
|
-
chunkBuffer?.noteStreamRunId(runId);
|
|
3025
2774
|
};
|
|
3026
2775
|
const refreshTokenUsage = async () => {
|
|
3027
2776
|
try {
|
|
@@ -3035,17 +2784,16 @@ function createThreadRuntime(options) {
|
|
|
3035
2784
|
threadId: options.threadId,
|
|
3036
2785
|
assistantId: options.assistantId,
|
|
3037
2786
|
transport: options.transport,
|
|
3038
|
-
store,
|
|
3039
|
-
enrichments,
|
|
3040
2787
|
runs,
|
|
3041
2788
|
valuesChannel,
|
|
2789
|
+
overlay,
|
|
2790
|
+
rm,
|
|
3042
2791
|
streamRef,
|
|
3043
|
-
setChunkBuffer: (b) => chunkBuffer = b,
|
|
3044
|
-
getChunkBuffer: () => chunkBuffer,
|
|
3045
2792
|
setPager: (p) => pager = p,
|
|
3046
2793
|
setInitialized: () => initialized = true,
|
|
3047
2794
|
markStreamRun,
|
|
3048
2795
|
onStreamStart: streamStarted,
|
|
2796
|
+
onStreamSettled: streamSettled,
|
|
3049
2797
|
refreshTokenUsage
|
|
3050
2798
|
},
|
|
3051
2799
|
{
|
|
@@ -3053,23 +2801,34 @@ function createThreadRuntime(options) {
|
|
|
3053
2801
|
onEnd: () => isInitializing.value = false
|
|
3054
2802
|
}
|
|
3055
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
|
+
});
|
|
3056
2814
|
return {
|
|
3057
2815
|
threadId: options.threadId,
|
|
3058
2816
|
lastViewedAt: Date.now(),
|
|
3059
2817
|
touch() {
|
|
3060
2818
|
this.lastViewedAt = Date.now();
|
|
3061
2819
|
},
|
|
3062
|
-
|
|
2820
|
+
view: rm.view,
|
|
2821
|
+
turns: rm.turns,
|
|
2822
|
+
activeClarification: rm.activeClarification,
|
|
3063
2823
|
isGenerating,
|
|
3064
2824
|
isInitializing,
|
|
3065
|
-
runs: (0,
|
|
2825
|
+
runs: (0, import_vue6.computed)(() => runs.runsMap.value),
|
|
3066
2826
|
interrupt,
|
|
3067
2827
|
hasPendingInterrupt,
|
|
3068
|
-
hasPendingClarification,
|
|
3069
2828
|
streamError,
|
|
3070
2829
|
tokenUsage,
|
|
3071
|
-
hasMoreHistory: (0,
|
|
3072
|
-
loadingHistory: (0,
|
|
2830
|
+
hasMoreHistory: (0, import_vue6.computed)(() => pager?.hasMore.value ?? false),
|
|
2831
|
+
loadingHistory: (0, import_vue6.computed)(() => pager?.loading.value ?? false),
|
|
3073
2832
|
async init() {
|
|
3074
2833
|
if (initialized) return;
|
|
3075
2834
|
if (initPromise) return initPromise;
|
|
@@ -3080,64 +2839,26 @@ function createThreadRuntime(options) {
|
|
|
3080
2839
|
initPromise = null;
|
|
3081
2840
|
}
|
|
3082
2841
|
},
|
|
3083
|
-
submit
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
humanMessage.additional_kwargs = submitOptions?.kwargs;
|
|
3089
|
-
handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
|
|
3090
|
-
},
|
|
3091
|
-
async joinStream(runId, lastEventId) {
|
|
3092
|
-
const handle = streamRef.value;
|
|
3093
|
-
if (!handle) return;
|
|
3094
|
-
beginStream();
|
|
3095
|
-
markStreamRun(runId);
|
|
3096
|
-
await handle.joinStream(runId, lastEventId ?? "-1");
|
|
3097
|
-
},
|
|
3098
|
-
stop() {
|
|
3099
|
-
void options.transport.cancelRun(options.threadId, runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
|
|
3100
|
-
streamRef.value?.stop();
|
|
3101
|
-
},
|
|
3102
|
-
async resumeInterrupt(decisions) {
|
|
3103
|
-
const it = valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false });
|
|
3104
|
-
const interruptId = String(it?.id || "");
|
|
3105
|
-
if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
|
|
3106
|
-
const handle = streamRef.value;
|
|
3107
|
-
if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
|
|
3108
|
-
interruptState.markResponded(interruptId);
|
|
3109
|
-
beginStream();
|
|
3110
|
-
await handle.resumeInterrupt(decisions);
|
|
3111
|
-
},
|
|
3112
|
-
async loadOlderMessages() {
|
|
3113
|
-
if (!pager) return false;
|
|
3114
|
-
return pager.loadOlder();
|
|
3115
|
-
},
|
|
3116
|
-
appendOptimisticGroups(gs) {
|
|
3117
|
-
state.appendExtra(gs);
|
|
3118
|
-
},
|
|
3119
|
-
createOptimisticHuman(text, opts) {
|
|
3120
|
-
return createOptimisticHuman(text, opts);
|
|
3121
|
-
},
|
|
3122
|
-
patchGroup(messageId, patch) {
|
|
3123
|
-
state.patchGroup(messageId, patch, () => sourceGroups.value);
|
|
3124
|
-
},
|
|
2842
|
+
submit: actions.submit,
|
|
2843
|
+
joinStream: actions.joinStream,
|
|
2844
|
+
stop: actions.stop,
|
|
2845
|
+
resumeInterrupt: actions.resumeInterrupt,
|
|
2846
|
+
loadOlderMessages: actions.loadOlderMessages,
|
|
3125
2847
|
applyFeedback(messageId, feedback) {
|
|
3126
|
-
|
|
3127
|
-
|
|
2848
|
+
rm.decorate(messageId, { feedback });
|
|
2849
|
+
const runId = rm.view.value.turns.flatMap((t) => t.ai).find((seg) => seg.id === messageId)?.runId;
|
|
3128
2850
|
if (runId) runs.patchRun(runId, { feedback });
|
|
3129
2851
|
},
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
clarificationAnswers:
|
|
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,
|
|
3137
2859
|
dispose() {
|
|
3138
2860
|
streamRef.value?.stop();
|
|
3139
|
-
|
|
3140
|
-
enrichments.dispose();
|
|
2861
|
+
streamRef.value?.dispose?.();
|
|
3141
2862
|
runs.dispose();
|
|
3142
2863
|
scope.stop();
|
|
3143
2864
|
}
|
|
@@ -3145,15 +2866,15 @@ function createThreadRuntime(options) {
|
|
|
3145
2866
|
}
|
|
3146
2867
|
|
|
3147
2868
|
// src/runtime/thread-directory.ts
|
|
3148
|
-
var
|
|
3149
|
-
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"]);
|
|
3150
2871
|
function isActiveThreadStatus(status) {
|
|
3151
2872
|
return typeof status === "string" && ACTIVE_THREAD_STATUSES.has(status);
|
|
3152
2873
|
}
|
|
3153
2874
|
var ThreadDirectory = class {
|
|
3154
2875
|
constructor(options) {
|
|
3155
|
-
this.threads = (0,
|
|
3156
|
-
this.threadsPagination = (0,
|
|
2876
|
+
this.threads = (0, import_vue7.ref)([]);
|
|
2877
|
+
this.threadsPagination = (0, import_vue7.ref)({
|
|
3157
2878
|
limit: 50,
|
|
3158
2879
|
offset: 0,
|
|
3159
2880
|
hasMore: true,
|
|
@@ -3161,9 +2882,9 @@ var ThreadDirectory = class {
|
|
|
3161
2882
|
});
|
|
3162
2883
|
this.searchKeyword = "";
|
|
3163
2884
|
/** 正在运行但已超出 SSE 连接上限的 thread(仅用于 UI 提示) */
|
|
3164
|
-
this.runningNotConnectedThreadIds = (0,
|
|
2885
|
+
this.runningNotConnectedThreadIds = (0, import_vue7.ref)(/* @__PURE__ */ new Set());
|
|
3165
2886
|
/** 活跃 runtime 池(shallowReactive 追踪增删,runtime 实例不被深度代理) */
|
|
3166
|
-
this.cachedRuntimes = (0,
|
|
2887
|
+
this.cachedRuntimes = (0, import_vue7.shallowReactive)(/* @__PURE__ */ new Map());
|
|
3167
2888
|
this.transport = options.transport;
|
|
3168
2889
|
this.assistantId = options.assistantId;
|
|
3169
2890
|
this.maxCachedRuntimes = options.maxCachedRuntimes ?? DEFAULT_MAX_CACHED_SESSIONS;
|
|
@@ -3298,17 +3019,26 @@ var ThreadDirectory = class {
|
|
|
3298
3019
|
}
|
|
3299
3020
|
// ===== 刷新后恢复 =====
|
|
3300
3021
|
/**
|
|
3301
|
-
*
|
|
3302
|
-
*
|
|
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
|
+
* 并行确认,串行连接(并发上限内)。
|
|
3303
3030
|
*/
|
|
3304
3031
|
async recoverRunningThreads() {
|
|
3305
|
-
const
|
|
3032
|
+
const candidates = this.threads.value.filter((t) => t.thread_id && isActiveThreadStatus(t.status));
|
|
3306
3033
|
const results = await Promise.all(
|
|
3307
|
-
|
|
3034
|
+
candidates.map(async (thread) => {
|
|
3308
3035
|
try {
|
|
3309
3036
|
const runs = await this.transport.listRuns(thread.thread_id, 5);
|
|
3310
|
-
|
|
3311
|
-
|
|
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;
|
|
3312
3042
|
} catch (e) {
|
|
3313
3043
|
console.warn("[ThreadDirectory] check running run failed", e);
|
|
3314
3044
|
return null;
|
|
@@ -3340,7 +3070,7 @@ var ThreadDirectory = class {
|
|
|
3340
3070
|
};
|
|
3341
3071
|
|
|
3342
3072
|
// src/core/ChatCore.ts
|
|
3343
|
-
var
|
|
3073
|
+
var import_vue8 = require("vue");
|
|
3344
3074
|
function createChatCore(options) {
|
|
3345
3075
|
const notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
|
|
3346
3076
|
const directory = new ThreadDirectory({
|
|
@@ -3352,35 +3082,48 @@ function createChatCore(options) {
|
|
|
3352
3082
|
notify,
|
|
3353
3083
|
defaultThreadTitle: options.defaultThreadTitle
|
|
3354
3084
|
});
|
|
3355
|
-
const currentThreadId = (0,
|
|
3356
|
-
const threads = (0,
|
|
3357
|
-
const threadsPagination = (0,
|
|
3358
|
-
const activeRuntime = (0,
|
|
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)(
|
|
3359
3089
|
() => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
|
|
3360
3090
|
);
|
|
3361
|
-
const
|
|
3362
|
-
const
|
|
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)(
|
|
3363
3097
|
() => !!activeRuntime.value && (activeRuntime.value.isGenerating.value || activeRuntime.value.isInitializing.value)
|
|
3364
3098
|
);
|
|
3365
|
-
const isLoadingThread = (0,
|
|
3366
|
-
const runs = (0,
|
|
3099
|
+
const isLoadingThread = (0, import_vue8.computed)(() => activeRuntime.value?.isInitializing.value ?? false);
|
|
3100
|
+
const runs = (0, import_vue8.computed)(
|
|
3367
3101
|
() => activeRuntime.value?.runs.value ?? /* @__PURE__ */ new Map()
|
|
3368
3102
|
);
|
|
3369
|
-
const toolCalls = (0,
|
|
3370
|
-
|
|
3371
|
-
|
|
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
|
+
)
|
|
3372
3115
|
);
|
|
3373
|
-
const
|
|
3374
|
-
|
|
3375
|
-
const hasPendingClarification = (0, import_vue9.computed)(() => activeRuntime.value?.hasPendingClarification.value ?? false);
|
|
3376
|
-
const inputDisabled = (0, import_vue9.computed)(
|
|
3377
|
-
() => isGenerating.value || hasPendingClarification.value || hasPendingInterrupt.value
|
|
3116
|
+
const clarificationAnswers = (0, import_vue8.computed)(
|
|
3117
|
+
() => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
|
|
3378
3118
|
);
|
|
3379
|
-
const
|
|
3380
|
-
const
|
|
3381
|
-
const
|
|
3382
|
-
const
|
|
3383
|
-
const
|
|
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);
|
|
3384
3127
|
const getRunById = (runId) => runId ? runs.value.get(runId) : void 0;
|
|
3385
3128
|
const getRunsByThreadId = (threadId) => threadId ? Array.from(runs.value.values()).filter((r) => r.threadId === threadId) : [];
|
|
3386
3129
|
const ensureThreadId = async () => {
|
|
@@ -3419,8 +3162,6 @@ function createChatCore(options) {
|
|
|
3419
3162
|
runtime.touch();
|
|
3420
3163
|
if (isNew && thread) directory.prependThread(thread);
|
|
3421
3164
|
await runtime.init();
|
|
3422
|
-
const optimistic = runtime.createOptimisticHuman(trimmed, sendOptions);
|
|
3423
|
-
runtime.appendOptimisticGroups([optimistic]);
|
|
3424
3165
|
runtime.submit(trimmed, sendOptions);
|
|
3425
3166
|
};
|
|
3426
3167
|
const loadThread = async (threadId) => {
|
|
@@ -3433,31 +3174,19 @@ function createChatCore(options) {
|
|
|
3433
3174
|
result.touch();
|
|
3434
3175
|
await result.init();
|
|
3435
3176
|
};
|
|
3436
|
-
const
|
|
3177
|
+
const regenerateTurn = async (aiSegmentId) => {
|
|
3437
3178
|
if (isGenerating.value) return;
|
|
3438
|
-
const
|
|
3439
|
-
const
|
|
3440
|
-
if (
|
|
3441
|
-
let question;
|
|
3442
|
-
let text = "";
|
|
3443
|
-
for (const m of list.slice(0, idx).reverse()) {
|
|
3444
|
-
if (m.type !== "human") continue;
|
|
3445
|
-
const [t] = m.texts ?? [];
|
|
3446
|
-
if (t) {
|
|
3447
|
-
question = m;
|
|
3448
|
-
text = t;
|
|
3449
|
-
break;
|
|
3450
|
-
}
|
|
3451
|
-
}
|
|
3452
|
-
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()) {
|
|
3453
3182
|
notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
|
|
3454
3183
|
return;
|
|
3455
3184
|
}
|
|
3456
|
-
await sendMessage(text, { kwargs: { ...
|
|
3185
|
+
await sendMessage(text, { kwargs: { ...turn.human.kwargs ?? {}, hide_from_ui: false } });
|
|
3457
3186
|
};
|
|
3458
3187
|
return {
|
|
3459
|
-
|
|
3460
|
-
|
|
3188
|
+
view,
|
|
3189
|
+
turns,
|
|
3461
3190
|
isGenerating,
|
|
3462
3191
|
isLoadingThread,
|
|
3463
3192
|
currentThreadId,
|
|
@@ -3468,6 +3197,7 @@ function createChatCore(options) {
|
|
|
3468
3197
|
getRunById,
|
|
3469
3198
|
getRunsByThreadId,
|
|
3470
3199
|
clarificationAnswers,
|
|
3200
|
+
activeClarification,
|
|
3471
3201
|
setClarificationAnswer: (toolCallId, answer) => activeRuntime.value?.setClarificationAnswer(toolCallId, answer),
|
|
3472
3202
|
clearClarificationAnswers: () => activeRuntime.value?.clearClarificationAnswers(),
|
|
3473
3203
|
sendMessage,
|
|
@@ -3476,11 +3206,12 @@ function createChatCore(options) {
|
|
|
3476
3206
|
clearMessages: () => {
|
|
3477
3207
|
currentThreadId.value = null;
|
|
3478
3208
|
},
|
|
3479
|
-
updateGroupMessage: (messageId, patch) => activeRuntime.value?.patchGroup(messageId, patch),
|
|
3480
|
-
addOptimisticGroupMessages: (ms) => activeRuntime.value?.appendOptimisticGroups(ms),
|
|
3481
|
-
updateGroupMessageBlocks: (messageId, blocks) => activeRuntime.value?.patchGroup(messageId, { blocks }),
|
|
3482
3209
|
applyFeedback: (messageId, feedback) => activeRuntime.value?.applyFeedback(messageId, feedback),
|
|
3483
|
-
|
|
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(),
|
|
3484
3215
|
fetchThreads: (reset, keyword) => directory.fetchThreads(reset, keyword),
|
|
3485
3216
|
deleteThread: async (threadId) => {
|
|
3486
3217
|
const deleted = await directory.deleteThread(threadId);
|
|
@@ -3493,8 +3224,8 @@ function createChatCore(options) {
|
|
|
3493
3224
|
runningNotConnectedThreadIds,
|
|
3494
3225
|
recoverRunningThreads: () => directory.recoverRunningThreads(),
|
|
3495
3226
|
activeInterrupt,
|
|
3227
|
+
interrupt: activeInterrupt,
|
|
3496
3228
|
hasPendingInterrupt,
|
|
3497
|
-
hasPendingClarification,
|
|
3498
3229
|
inputDisabled,
|
|
3499
3230
|
streamError,
|
|
3500
3231
|
hasMoreHistory,
|
|
@@ -3515,8 +3246,612 @@ function createChatCore(options) {
|
|
|
3515
3246
|
};
|
|
3516
3247
|
}
|
|
3517
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
|
+
|
|
3518
3853
|
// src/test-utils/mockTransport.ts
|
|
3519
|
-
var
|
|
3854
|
+
var import_vue9 = require("vue");
|
|
3520
3855
|
var mockThreadSeq = 0;
|
|
3521
3856
|
function createMockTransport() {
|
|
3522
3857
|
const threads = [];
|
|
@@ -3607,8 +3942,8 @@ function createMockTransport() {
|
|
|
3607
3942
|
return content;
|
|
3608
3943
|
},
|
|
3609
3944
|
createStream(options) {
|
|
3610
|
-
const isLoading = (0,
|
|
3611
|
-
const error = (0,
|
|
3945
|
+
const isLoading = (0, import_vue9.ref)(false);
|
|
3946
|
+
const error = (0, import_vue9.ref)(null);
|
|
3612
3947
|
const threadId = options.threadId;
|
|
3613
3948
|
optionsMap.set(threadId, options);
|
|
3614
3949
|
const handle = {
|
|
@@ -3703,49 +4038,54 @@ var CORE_VERSION = "2.0.0";
|
|
|
3703
4038
|
DEFAULT_ASSISTANT_ID,
|
|
3704
4039
|
DEFAULT_MAX_CACHED_SESSIONS,
|
|
3705
4040
|
DEFAULT_MAX_CONCURRENT_STREAMS,
|
|
3706
|
-
|
|
4041
|
+
DeerFlowBridgeAdapter,
|
|
3707
4042
|
INJECTED_TAGS,
|
|
3708
4043
|
MESSAGE_TYPE_NORMALIZE,
|
|
3709
4044
|
OUTLINE_MAX_LEVEL,
|
|
3710
4045
|
ThreadDirectory,
|
|
3711
|
-
|
|
4046
|
+
V1FrameTranslator,
|
|
4047
|
+
applySemanticPatches,
|
|
4048
|
+
backfillRunMessageFeedback,
|
|
3712
4049
|
buildArtifactFiles,
|
|
3713
4050
|
buildHitlDecisions,
|
|
3714
|
-
buildHumanGroup,
|
|
3715
4051
|
buildHumanInputResponse,
|
|
3716
4052
|
buildInterruptReviewBlock,
|
|
3717
|
-
buildInterruptReviewGroup,
|
|
3718
4053
|
buildRejectDecisions,
|
|
3719
4054
|
buildReportBodyPayload,
|
|
3720
4055
|
buildReportOutlinePayload,
|
|
3721
4056
|
buildRunDirectLatencyMs,
|
|
3722
4057
|
buildRunInfo,
|
|
3723
|
-
collectCitation,
|
|
3724
4058
|
collectTextKeepSxin,
|
|
3725
4059
|
collectVisibleText,
|
|
3726
|
-
createBlockBuilderLite,
|
|
3727
4060
|
createChatCore,
|
|
3728
4061
|
createEmptySubChapter,
|
|
3729
|
-
|
|
4062
|
+
createEventHub,
|
|
4063
|
+
createFetchReaderFactory,
|
|
4064
|
+
createMaterializer,
|
|
4065
|
+
createMessageDiff,
|
|
3730
4066
|
createMockTransport,
|
|
3731
|
-
|
|
3732
|
-
|
|
4067
|
+
createRuntimeMaterializer,
|
|
4068
|
+
createSemanticOverlay,
|
|
3733
4069
|
createThreadRuntime,
|
|
3734
|
-
createViewModelState,
|
|
3735
4070
|
deriveToolsFromMessages,
|
|
3736
4071
|
ensureOutlineContentThemes,
|
|
3737
4072
|
ensureRunningRun,
|
|
3738
4073
|
extractAiContentFromMessage,
|
|
3739
4074
|
extractBlocksFromContent,
|
|
3740
4075
|
extractBlocksFromNodes,
|
|
4076
|
+
extractCitationAnchors,
|
|
4077
|
+
extractCitationAnchorsFromSpec,
|
|
4078
|
+
extractFromToolResult,
|
|
3741
4079
|
extractReportTitleFromBody,
|
|
3742
4080
|
extractRunEnrichment,
|
|
4081
|
+
extractSemanticPatchesFromMessages,
|
|
3743
4082
|
extractStateMessages,
|
|
3744
4083
|
extractTextFromMessage,
|
|
3745
4084
|
extractThreadInfo,
|
|
3746
4085
|
extractTitleFromArtifactPath,
|
|
3747
4086
|
extractUserMessageTexts,
|
|
3748
|
-
|
|
4087
|
+
fetchAllPageMessages,
|
|
4088
|
+
formatAnswerText,
|
|
3749
4089
|
formatStr,
|
|
3750
4090
|
genBlockId,
|
|
3751
4091
|
genMessageId,
|
|
@@ -3753,8 +4093,6 @@ var CORE_VERSION = "2.0.0";
|
|
|
3753
4093
|
getHumanMessageBaseId,
|
|
3754
4094
|
getToolCallArtifactMeta,
|
|
3755
4095
|
isAiMessage,
|
|
3756
|
-
isClarificationAnswered,
|
|
3757
|
-
isClarificationBlock,
|
|
3758
4096
|
isHiddenUserMessage,
|
|
3759
4097
|
isHumanMessage,
|
|
3760
4098
|
isInjectedElement,
|
|
@@ -3763,6 +4101,7 @@ var CORE_VERSION = "2.0.0";
|
|
|
3763
4101
|
isToolMessage,
|
|
3764
4102
|
isVisibleUserMessage,
|
|
3765
4103
|
isWriteFileToolName,
|
|
4104
|
+
mergeStateWithPageMessages,
|
|
3766
4105
|
normalizeForCompare,
|
|
3767
4106
|
normalizeMessageType,
|
|
3768
4107
|
normalizeOutline,
|
|
@@ -3771,11 +4110,13 @@ var CORE_VERSION = "2.0.0";
|
|
|
3771
4110
|
parseHumanMessageId,
|
|
3772
4111
|
parseKnowledgeItemsFromValue,
|
|
3773
4112
|
parseMarkdownToOutline,
|
|
4113
|
+
parseSseFrames,
|
|
3774
4114
|
pickRunMessageMetadata,
|
|
3775
4115
|
readMessageContentText,
|
|
3776
4116
|
resolveReportArtifactKind,
|
|
3777
4117
|
runMessagesToMessages,
|
|
3778
4118
|
simpleHash,
|
|
4119
|
+
sliceBodySegments,
|
|
3779
4120
|
stateMessagesToRunMessages,
|
|
3780
4121
|
toRunMessage,
|
|
3781
4122
|
tokenizeSxin,
|