@cqfe/sxin-chat-core 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ChatCore-C-G9isDM.d.cts → ChatCore-CCeoxjP9.d.cts} +437 -342
- package/dist/{ChatCore-C-G9isDM.d.ts → ChatCore-CCeoxjP9.d.ts} +437 -342
- package/dist/chunk-2AXUXZVK.mjs +2661 -0
- package/dist/index.cjs +1042 -1550
- package/dist/index.d.cts +228 -220
- package/dist/index.d.ts +228 -220
- package/dist/index.mjs +356 -141
- package/dist/vue/index.cjs +1068 -2055
- 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 +3 -3
- package/dist/chunk-K2ZOZPBB.mjs +0 -3391
package/dist/index.cjs
CHANGED
|
@@ -24,35 +24,33 @@ __export(src_exports, {
|
|
|
24
24
|
DEFAULT_ASSISTANT_ID: () => DEFAULT_ASSISTANT_ID,
|
|
25
25
|
DEFAULT_MAX_CACHED_SESSIONS: () => DEFAULT_MAX_CACHED_SESSIONS,
|
|
26
26
|
DEFAULT_MAX_CONCURRENT_STREAMS: () => DEFAULT_MAX_CONCURRENT_STREAMS,
|
|
27
|
-
DEFAULT_TWIN_TOOL_PREFIX: () => DEFAULT_TWIN_TOOL_PREFIX,
|
|
28
27
|
INJECTED_TAGS: () => INJECTED_TAGS,
|
|
29
28
|
MESSAGE_TYPE_NORMALIZE: () => MESSAGE_TYPE_NORMALIZE,
|
|
30
29
|
OUTLINE_MAX_LEVEL: () => OUTLINE_MAX_LEVEL,
|
|
31
30
|
ThreadDirectory: () => ThreadDirectory,
|
|
32
|
-
|
|
31
|
+
applySemanticPatches: () => applySemanticPatches,
|
|
32
|
+
asArgsObject: () => asArgsObject,
|
|
33
|
+
assembleRun: () => assembleRun,
|
|
34
|
+
backfillRunMessageFeedback: () => backfillRunMessageFeedback,
|
|
33
35
|
buildArtifactFiles: () => buildArtifactFiles,
|
|
34
36
|
buildHitlDecisions: () => buildHitlDecisions,
|
|
35
|
-
buildHumanGroup: () => buildHumanGroup,
|
|
36
37
|
buildHumanInputResponse: () => buildHumanInputResponse,
|
|
37
38
|
buildInterruptReviewBlock: () => buildInterruptReviewBlock,
|
|
38
|
-
buildInterruptReviewGroup: () => buildInterruptReviewGroup,
|
|
39
39
|
buildRejectDecisions: () => buildRejectDecisions,
|
|
40
40
|
buildReportBodyPayload: () => buildReportBodyPayload,
|
|
41
41
|
buildReportOutlinePayload: () => buildReportOutlinePayload,
|
|
42
42
|
buildRunDirectLatencyMs: () => buildRunDirectLatencyMs,
|
|
43
43
|
buildRunInfo: () => buildRunInfo,
|
|
44
|
+
buildRunMeta: () => buildRunMeta,
|
|
44
45
|
collectTextKeepSxin: () => collectTextKeepSxin,
|
|
45
46
|
collectVisibleText: () => collectVisibleText,
|
|
46
|
-
createBlockBuilderLite: () => createBlockBuilderLite,
|
|
47
47
|
createChatCore: () => createChatCore,
|
|
48
48
|
createEmptySubChapter: () => createEmptySubChapter,
|
|
49
|
-
createGroupDeriver: () => createGroupDeriver,
|
|
50
49
|
createMockTransport: () => createMockTransport,
|
|
51
|
-
|
|
52
|
-
createStreamPump: () => createStreamPump,
|
|
50
|
+
createSemanticOverlay: () => createSemanticOverlay,
|
|
53
51
|
createThreadRuntime: () => createThreadRuntime,
|
|
54
|
-
createViewModelState: () => createViewModelState,
|
|
55
52
|
deriveToolsFromMessages: () => deriveToolsFromMessages,
|
|
53
|
+
emptyRunItem: () => emptyRunItem,
|
|
56
54
|
ensureOutlineContentThemes: () => ensureOutlineContentThemes,
|
|
57
55
|
ensureRunningRun: () => ensureRunningRun,
|
|
58
56
|
extractAiContentFromMessage: () => extractAiContentFromMessage,
|
|
@@ -60,31 +58,36 @@ __export(src_exports, {
|
|
|
60
58
|
extractBlocksFromNodes: () => extractBlocksFromNodes,
|
|
61
59
|
extractCitationAnchors: () => extractCitationAnchors,
|
|
62
60
|
extractCitationAnchorsFromSpec: () => extractCitationAnchorsFromSpec,
|
|
61
|
+
extractFromToolResult: () => extractFromToolResult,
|
|
62
|
+
extractInputFromRows: () => extractInputFromRows,
|
|
63
63
|
extractReportTitleFromBody: () => extractReportTitleFromBody,
|
|
64
64
|
extractRunEnrichment: () => extractRunEnrichment,
|
|
65
|
+
extractSemanticPatchesFromMessages: () => extractSemanticPatchesFromMessages,
|
|
65
66
|
extractStateMessages: () => extractStateMessages,
|
|
66
67
|
extractTextFromMessage: () => extractTextFromMessage,
|
|
67
68
|
extractThreadInfo: () => extractThreadInfo,
|
|
68
69
|
extractTitleFromArtifactPath: () => extractTitleFromArtifactPath,
|
|
69
70
|
extractUserMessageTexts: () => extractUserMessageTexts,
|
|
70
|
-
|
|
71
|
+
formatAnswerText: () => formatAnswerText,
|
|
71
72
|
formatStr: () => formatStr,
|
|
72
73
|
genBlockId: () => genBlockId,
|
|
73
74
|
genMessageId: () => genMessageId,
|
|
74
75
|
getAllowedDecisions: () => getAllowedDecisions,
|
|
75
76
|
getHumanMessageBaseId: () => getHumanMessageBaseId,
|
|
76
77
|
getToolCallArtifactMeta: () => getToolCallArtifactMeta,
|
|
78
|
+
groupRowsByRun: () => groupRowsByRun,
|
|
77
79
|
isAiMessage: () => isAiMessage,
|
|
78
|
-
isClarificationAnswered: () => isClarificationAnswered,
|
|
79
|
-
isClarificationBlock: () => isClarificationBlock,
|
|
80
80
|
isHiddenUserMessage: () => isHiddenUserMessage,
|
|
81
81
|
isHumanMessage: () => isHumanMessage,
|
|
82
82
|
isInjectedElement: () => isInjectedElement,
|
|
83
83
|
isReportBodyHtml: () => isReportBodyHtml,
|
|
84
84
|
isSameArgs: () => isSameArgs,
|
|
85
85
|
isToolMessage: () => isToolMessage,
|
|
86
|
+
isUserEchoRow: () => isUserEchoRow,
|
|
86
87
|
isVisibleUserMessage: () => isVisibleUserMessage,
|
|
87
88
|
isWriteFileToolName: () => isWriteFileToolName,
|
|
89
|
+
mapBackendStatus: () => mapBackendStatus,
|
|
90
|
+
mergeStateWithPageMessages: () => mergeStateWithPageMessages,
|
|
88
91
|
normalizeForCompare: () => normalizeForCompare,
|
|
89
92
|
normalizeMessageType: () => normalizeMessageType,
|
|
90
93
|
normalizeOutline: () => normalizeOutline,
|
|
@@ -93,11 +96,15 @@ __export(src_exports, {
|
|
|
93
96
|
parseHumanMessageId: () => parseHumanMessageId,
|
|
94
97
|
parseKnowledgeItemsFromValue: () => parseKnowledgeItemsFromValue,
|
|
95
98
|
parseMarkdownToOutline: () => parseMarkdownToOutline,
|
|
99
|
+
pickRicherArgs: () => pickRicherArgs,
|
|
96
100
|
pickRunMessageMetadata: () => pickRunMessageMetadata,
|
|
101
|
+
projectRuns: () => projectRuns,
|
|
97
102
|
readMessageContentText: () => readMessageContentText,
|
|
98
103
|
resolveReportArtifactKind: () => resolveReportArtifactKind,
|
|
104
|
+
rowMessageId: () => rowMessageId,
|
|
99
105
|
runMessagesToMessages: () => runMessagesToMessages,
|
|
100
106
|
simpleHash: () => simpleHash,
|
|
107
|
+
sliceBodySegments: () => sliceBodySegments,
|
|
101
108
|
stateMessagesToRunMessages: () => stateMessagesToRunMessages,
|
|
102
109
|
toRunMessage: () => toRunMessage,
|
|
103
110
|
tokenizeSxin: () => tokenizeSxin,
|
|
@@ -110,117 +117,6 @@ var DEFAULT_MAX_CACHED_SESSIONS = 10;
|
|
|
110
117
|
var DEFAULT_MAX_CONCURRENT_STREAMS = 3;
|
|
111
118
|
var DEFAULT_ASSISTANT_ID = "lead_agent";
|
|
112
119
|
|
|
113
|
-
// src/protocol/stream-pump.ts
|
|
114
|
-
var import_vue = require("vue");
|
|
115
|
-
var import_langgraph_sdk = require("@langchain/langgraph-sdk");
|
|
116
|
-
var STREAM_MODE = ["values", "messages-tuple"];
|
|
117
|
-
function isSilentStreamError(e) {
|
|
118
|
-
return e instanceof Error && (e.name === "AbortError" || e.name === "TimeoutError");
|
|
119
|
-
}
|
|
120
|
-
function createStreamPump(source, options) {
|
|
121
|
-
const isLoading = (0, import_vue.ref)(false);
|
|
122
|
-
const error = (0, import_vue.ref)(null);
|
|
123
|
-
let queue = Promise.resolve();
|
|
124
|
-
let currentController = null;
|
|
125
|
-
const runStream = async (open) => {
|
|
126
|
-
const controller = new AbortController();
|
|
127
|
-
currentController = controller;
|
|
128
|
-
try {
|
|
129
|
-
isLoading.value = true;
|
|
130
|
-
error.value = null;
|
|
131
|
-
options.onStreamStart?.();
|
|
132
|
-
for await (const { event, data } of open(controller.signal)) {
|
|
133
|
-
if (event === "error") throw new import_langgraph_sdk.StreamError(data);
|
|
134
|
-
if (event === "metadata") {
|
|
135
|
-
options.onMetadataEvent?.(data);
|
|
136
|
-
continue;
|
|
137
|
-
}
|
|
138
|
-
if (event === "values" || event.startsWith("values|")) {
|
|
139
|
-
if (event.includes("|")) continue;
|
|
140
|
-
options.onValuesEvent?.(data);
|
|
141
|
-
continue;
|
|
142
|
-
}
|
|
143
|
-
if (event === "messages" || event === "messages-tuple" || event.startsWith("messages|")) {
|
|
144
|
-
if (event.includes("|")) continue;
|
|
145
|
-
const [serialized, metadata] = Array.isArray(data) ? data : [];
|
|
146
|
-
options.onMessageTupleEvent?.(serialized, metadata);
|
|
147
|
-
continue;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
} catch (e) {
|
|
151
|
-
if (!isSilentStreamError(e)) {
|
|
152
|
-
error.value = e;
|
|
153
|
-
try {
|
|
154
|
-
await options.onError?.(e);
|
|
155
|
-
} catch {
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
} finally {
|
|
159
|
-
try {
|
|
160
|
-
await options.onStreamEnd?.();
|
|
161
|
-
} catch {
|
|
162
|
-
}
|
|
163
|
-
isLoading.value = false;
|
|
164
|
-
if (currentController === controller) currentController = null;
|
|
165
|
-
try {
|
|
166
|
-
await options.onFinish?.();
|
|
167
|
-
} catch {
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
};
|
|
171
|
-
const start = (open, startOptions) => {
|
|
172
|
-
if (startOptions?.abortPrevious) currentController?.abort();
|
|
173
|
-
const queued = queue.then(() => runStream(open));
|
|
174
|
-
queue = queued;
|
|
175
|
-
return queued;
|
|
176
|
-
};
|
|
177
|
-
return {
|
|
178
|
-
isLoading,
|
|
179
|
-
error,
|
|
180
|
-
/** 发起一次流式运行(发送用户消息);fire-and-forget(与现网 useThreadStream 一致) */
|
|
181
|
-
submit(input, submitOptions) {
|
|
182
|
-
void start(
|
|
183
|
-
(signal) => source.openRunStream(
|
|
184
|
-
{
|
|
185
|
-
input,
|
|
186
|
-
...submitOptions,
|
|
187
|
-
streamMode: STREAM_MODE,
|
|
188
|
-
// sdk client 在 run 创建时回调;透传给 CreateStreamOptions.onCreated
|
|
189
|
-
onRunCreated: (params) => options.onCreated?.(params)
|
|
190
|
-
},
|
|
191
|
-
signal
|
|
192
|
-
),
|
|
193
|
-
{ abortPrevious: true }
|
|
194
|
-
);
|
|
195
|
-
},
|
|
196
|
-
/** 加入既有 run 的 SSE 流(断线重连);await 至流结束 */
|
|
197
|
-
joinStream(runId, lastEventId) {
|
|
198
|
-
return start((signal) => source.openJoinStream(runId, lastEventId ?? "-1", signal), { abortPrevious: true });
|
|
199
|
-
},
|
|
200
|
-
/** 停止当前流(本地 abort,不取消服务端 run) */
|
|
201
|
-
stop() {
|
|
202
|
-
currentController?.abort();
|
|
203
|
-
},
|
|
204
|
-
/** 恢复 pending interrupt:发送 HITL 决策(Command(resume)),与 joinStream 的 SSE 重连语义不同;await 至流结束 */
|
|
205
|
-
resumeInterrupt(decisions) {
|
|
206
|
-
return start(
|
|
207
|
-
(signal) => source.openRunStream(
|
|
208
|
-
{
|
|
209
|
-
input: null,
|
|
210
|
-
command: { resume: decisions },
|
|
211
|
-
onDisconnect: "continue",
|
|
212
|
-
config: { recursion_limit: 1e3 },
|
|
213
|
-
streamMode: STREAM_MODE,
|
|
214
|
-
onRunCreated: (params) => options.onCreated?.(params)
|
|
215
|
-
},
|
|
216
|
-
signal
|
|
217
|
-
),
|
|
218
|
-
{ abortPrevious: true }
|
|
219
|
-
);
|
|
220
|
-
}
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
|
|
224
120
|
// src/parser/sxin-ast-attrs.ts
|
|
225
121
|
function formatStr(str) {
|
|
226
122
|
if (!str) return str;
|
|
@@ -757,24 +653,24 @@ function buildInterruptReviewBlock(interrupt, responded) {
|
|
|
757
653
|
interruptId
|
|
758
654
|
};
|
|
759
655
|
}
|
|
760
|
-
function buildInterruptReviewGroup(interrupt, responded) {
|
|
761
|
-
const block = buildInterruptReviewBlock(interrupt, responded);
|
|
762
|
-
if (!block) return null;
|
|
763
|
-
return {
|
|
764
|
-
id: `interrupt-${block.interruptId}`,
|
|
765
|
-
type: "ai",
|
|
766
|
-
status: block.status,
|
|
767
|
-
source: "state",
|
|
768
|
-
originMessageIds: [],
|
|
769
|
-
blocks: [block],
|
|
770
|
-
toolIds: [],
|
|
771
|
-
tools: [],
|
|
772
|
-
rawMessages: [],
|
|
773
|
-
createdAt: Date.now()
|
|
774
|
-
};
|
|
775
|
-
}
|
|
776
656
|
|
|
777
657
|
// src/parser/thread-info.ts
|
|
658
|
+
function formatAnswerText(value) {
|
|
659
|
+
if (value == null) return "";
|
|
660
|
+
if (typeof value === "string") return value;
|
|
661
|
+
if (typeof value === "object") {
|
|
662
|
+
const values = value.values;
|
|
663
|
+
if (values && typeof values === "object" && !Array.isArray(values)) {
|
|
664
|
+
return Object.values(values).filter((v) => v !== void 0 && v !== null && v !== "").map(String).join("; ");
|
|
665
|
+
}
|
|
666
|
+
try {
|
|
667
|
+
return JSON.stringify(value);
|
|
668
|
+
} catch {
|
|
669
|
+
return String(value);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
return String(value);
|
|
673
|
+
}
|
|
778
674
|
var humanInputResponseRule = {
|
|
779
675
|
key: "clarificationAnswers",
|
|
780
676
|
extract(msg, acc) {
|
|
@@ -782,7 +678,7 @@ var humanInputResponseRule = {
|
|
|
782
678
|
const response = additionalKwargs?.human_input_response;
|
|
783
679
|
const requestId = String(response?.request_id || "").trim().replace("clarification:", "");
|
|
784
680
|
if (requestId && response?.value !== void 0) {
|
|
785
|
-
acc.clarificationAnswers.set(requestId,
|
|
681
|
+
acc.clarificationAnswers.set(requestId, formatAnswerText(response.value));
|
|
786
682
|
}
|
|
787
683
|
}
|
|
788
684
|
};
|
|
@@ -818,6 +714,62 @@ function extractStateMessages(state) {
|
|
|
818
714
|
const messages = values.messages;
|
|
819
715
|
return Array.isArray(messages) ? messages : [];
|
|
820
716
|
}
|
|
717
|
+
function mergeStateWithPageMessages(stateMessages, pageMessages) {
|
|
718
|
+
if (!pageMessages.length) return stateMessages;
|
|
719
|
+
if (!stateMessages.length) return pageMessages;
|
|
720
|
+
const locateId = (m) => String(m?.id || m?.tool_call_id || "").trim();
|
|
721
|
+
const pageIndex = /* @__PURE__ */ new Map();
|
|
722
|
+
pageMessages.forEach((m, i) => {
|
|
723
|
+
const id = locateId(m);
|
|
724
|
+
if (id && !pageIndex.has(id)) pageIndex.set(id, i);
|
|
725
|
+
});
|
|
726
|
+
let anchorSi = -1;
|
|
727
|
+
let anchorPi = -1;
|
|
728
|
+
for (let si = 0; si < stateMessages.length; si++) {
|
|
729
|
+
const id = locateId(stateMessages[si]);
|
|
730
|
+
const pi = id ? pageIndex.get(id) : void 0;
|
|
731
|
+
if (pi !== void 0) {
|
|
732
|
+
anchorSi = si;
|
|
733
|
+
anchorPi = pi;
|
|
734
|
+
break;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
if (anchorSi < 0) return pageMessages;
|
|
738
|
+
const stateIds = /* @__PURE__ */ new Set();
|
|
739
|
+
for (const m of stateMessages) {
|
|
740
|
+
const id = String(m?.id || "").trim();
|
|
741
|
+
const callId = String(m?.tool_call_id || "").trim();
|
|
742
|
+
if (id) stateIds.add(id);
|
|
743
|
+
if (callId) stateIds.add(callId);
|
|
744
|
+
}
|
|
745
|
+
const headExtras = [];
|
|
746
|
+
for (let pi = 0; pi < anchorPi; pi++) {
|
|
747
|
+
const m = pageMessages[pi];
|
|
748
|
+
const id = locateId(m);
|
|
749
|
+
if (id && !stateIds.has(id)) headExtras.push(m);
|
|
750
|
+
}
|
|
751
|
+
const tailExtras = [];
|
|
752
|
+
for (let pi = anchorPi + 1; pi < pageMessages.length; pi++) {
|
|
753
|
+
const m = pageMessages[pi];
|
|
754
|
+
const id = locateId(m);
|
|
755
|
+
if (id && !stateIds.has(id)) tailExtras.push(m);
|
|
756
|
+
}
|
|
757
|
+
const runIdById = /* @__PURE__ */ new Map();
|
|
758
|
+
for (const m of pageMessages) {
|
|
759
|
+
const id = String(m?.id || "").trim();
|
|
760
|
+
const rid = String(m?.runId || "").trim();
|
|
761
|
+
if (id && rid && !runIdById.has(id)) runIdById.set(id, rid);
|
|
762
|
+
}
|
|
763
|
+
const stampRunId = (m) => {
|
|
764
|
+
const id = String(m?.id || "").trim();
|
|
765
|
+
if (!id) return m;
|
|
766
|
+
const rid = runIdById.get(id);
|
|
767
|
+
if (!rid) return m;
|
|
768
|
+
if (String(m?.runId || "").trim() || String(m?.additional_kwargs?.run_id || "").trim()) return m;
|
|
769
|
+
return { ...m, runId: rid };
|
|
770
|
+
};
|
|
771
|
+
return [...headExtras, ...stateMessages.map(stampRunId), ...tailExtras];
|
|
772
|
+
}
|
|
821
773
|
function ensureRunningRun(runMap, runId, threadId) {
|
|
822
774
|
let runInfo = runMap.get(runId);
|
|
823
775
|
if (!runInfo) {
|
|
@@ -831,7 +783,7 @@ function ensureRunningRun(runMap, runId, threadId) {
|
|
|
831
783
|
return runInfo;
|
|
832
784
|
}
|
|
833
785
|
|
|
834
|
-
// src/
|
|
786
|
+
// src/parser/sxin-message.ts
|
|
835
787
|
var asSxin = (m) => m ?? {};
|
|
836
788
|
|
|
837
789
|
// src/parser/run-messages.ts
|
|
@@ -906,6 +858,23 @@ function extractRunEnrichment(messages) {
|
|
|
906
858
|
}
|
|
907
859
|
return map;
|
|
908
860
|
}
|
|
861
|
+
function backfillRunMessageFeedback(source, target) {
|
|
862
|
+
if (!source.length || !target.length) return target;
|
|
863
|
+
const feedbackById = /* @__PURE__ */ new Map();
|
|
864
|
+
for (const row of source) {
|
|
865
|
+
const id = String(row?.content?.id || "").trim();
|
|
866
|
+
if (!id || row?.feedback === void 0 || row?.feedback === null) continue;
|
|
867
|
+
feedbackById.set(id, row.feedback);
|
|
868
|
+
}
|
|
869
|
+
if (!feedbackById.size) return target;
|
|
870
|
+
return target.map((row) => {
|
|
871
|
+
const id = String(row?.content?.id || "").trim();
|
|
872
|
+
if (!id) return row;
|
|
873
|
+
const feedback = feedbackById.get(id);
|
|
874
|
+
if (feedback === void 0 || row.feedback !== void 0) return row;
|
|
875
|
+
return { ...row, feedback };
|
|
876
|
+
});
|
|
877
|
+
}
|
|
909
878
|
function runMessagesToMessages(messages) {
|
|
910
879
|
return messages.map((msg) => {
|
|
911
880
|
const normalized = normalizeMessageType({ ...asSxin(msg.content) });
|
|
@@ -918,11 +887,14 @@ function runMessagesToMessages(messages) {
|
|
|
918
887
|
});
|
|
919
888
|
}
|
|
920
889
|
function stateMessagesToRunMessages(messages) {
|
|
890
|
+
let lastRunId = "";
|
|
921
891
|
return messages.map((msg, i) => {
|
|
922
892
|
const sxin = asSxin(msg);
|
|
893
|
+
const ownRunId = String(sxin.runId ?? sxin.additional_kwargs?.run_id ?? "").trim();
|
|
894
|
+
if (ownRunId) lastRunId = ownRunId;
|
|
923
895
|
const createdAt = parseCreatedAt(sxin.created_at);
|
|
924
896
|
return {
|
|
925
|
-
runId:
|
|
897
|
+
runId: ownRunId || lastRunId,
|
|
926
898
|
seq: i + 1,
|
|
927
899
|
eventType: "messages",
|
|
928
900
|
...createdAt !== void 0 ? { createdAt } : {},
|
|
@@ -959,6 +931,9 @@ function readMessageContentText(msg) {
|
|
|
959
931
|
if (!read) return "";
|
|
960
932
|
return read.trim ? read.text.trim() : read.text;
|
|
961
933
|
}
|
|
934
|
+
function hasKbCitationMessage(msg) {
|
|
935
|
+
return readMessageContentText(msg).includes("support.kbCitation");
|
|
936
|
+
}
|
|
962
937
|
function extractTextFromMessage(msg) {
|
|
963
938
|
const read = readMessageText(msg);
|
|
964
939
|
if (!read) return "";
|
|
@@ -1462,14 +1437,462 @@ function applyUsageDetails(usage, r) {
|
|
|
1462
1437
|
}
|
|
1463
1438
|
}
|
|
1464
1439
|
|
|
1465
|
-
// src/
|
|
1440
|
+
// src/parser/body-segments.ts
|
|
1441
|
+
var SEGMENT_TAGS = /* @__PURE__ */ new Set(["sxin-list", "sxin-item"]);
|
|
1442
|
+
function visibleTextOf(node) {
|
|
1443
|
+
if (node.type === "text") return node.value;
|
|
1444
|
+
if (node.type === "comment") return "";
|
|
1445
|
+
return node.children.map(visibleTextOf).join("");
|
|
1446
|
+
}
|
|
1447
|
+
function toItemSegment(el, source) {
|
|
1448
|
+
return {
|
|
1449
|
+
type: "item",
|
|
1450
|
+
tag: "sxin-item",
|
|
1451
|
+
attrs: { ...el.attrs },
|
|
1452
|
+
content: visibleTextOf(el) || void 0,
|
|
1453
|
+
raw: source.slice(el.start, el.end)
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
function toListSegment(el, source) {
|
|
1457
|
+
const children = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-item").map((c) => toItemSegment(c, source));
|
|
1458
|
+
return { type: "list", tag: "sxin-list", attrs: { ...el.attrs }, children, raw: source.slice(el.start, el.end) };
|
|
1459
|
+
}
|
|
1460
|
+
function sliceBodySegments(body) {
|
|
1461
|
+
const source = String(body ?? "");
|
|
1462
|
+
const segments = [];
|
|
1463
|
+
let textBuf = "";
|
|
1464
|
+
const flushText = () => {
|
|
1465
|
+
if (!textBuf) return;
|
|
1466
|
+
segments.push({ type: "text", content: textBuf });
|
|
1467
|
+
textBuf = "";
|
|
1468
|
+
};
|
|
1469
|
+
for (const node of tokenizeSxin(source)) {
|
|
1470
|
+
if (node.type === "element" && SEGMENT_TAGS.has(node.tagName)) {
|
|
1471
|
+
flushText();
|
|
1472
|
+
segments.push(node.tagName === "sxin-list" ? toListSegment(node, source) : toItemSegment(node, source));
|
|
1473
|
+
} else if (node.type === "comment") {
|
|
1474
|
+
continue;
|
|
1475
|
+
} else if (node.type === "text") {
|
|
1476
|
+
textBuf += node.value;
|
|
1477
|
+
} else {
|
|
1478
|
+
textBuf += source.slice(node.start, node.end);
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
flushText();
|
|
1482
|
+
if (!segments.length) segments.push({ type: "text", content: "" });
|
|
1483
|
+
return segments;
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
// src/assembler/run-grouping.ts
|
|
1487
|
+
var LIVE_SEQ = Number.MAX_SAFE_INTEGER;
|
|
1488
|
+
function rowMessageId(msg) {
|
|
1489
|
+
return String(msg?.id || "").trim();
|
|
1490
|
+
}
|
|
1491
|
+
function isUserEchoRow(id) {
|
|
1492
|
+
return id.endsWith("__user");
|
|
1493
|
+
}
|
|
1494
|
+
function pageRowToAsmRow(row) {
|
|
1495
|
+
const id = rowMessageId(row.content);
|
|
1496
|
+
if (!id) return null;
|
|
1497
|
+
const out = {
|
|
1498
|
+
id,
|
|
1499
|
+
runId: String(row.runId || ""),
|
|
1500
|
+
seq: Number.isFinite(row.seq) ? row.seq : 0,
|
|
1501
|
+
msg: row.content
|
|
1502
|
+
};
|
|
1503
|
+
if (row.createdAt !== void 0) out.createdAt = row.createdAt;
|
|
1504
|
+
if (row.feedback !== void 0 && row.feedback !== null) out.feedback = row.feedback;
|
|
1505
|
+
return out;
|
|
1506
|
+
}
|
|
1507
|
+
function liveToAsmRow(msg, runId) {
|
|
1508
|
+
const id = rowMessageId(msg);
|
|
1509
|
+
if (!id || isUserEchoRow(id)) return null;
|
|
1510
|
+
return { id, runId, seq: LIVE_SEQ, msg };
|
|
1511
|
+
}
|
|
1512
|
+
function groupRowsByRun(rows, liveMessages, activeRunId, pendingRunId) {
|
|
1513
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1514
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
1515
|
+
for (const row of rows) {
|
|
1516
|
+
const asm = pageRowToAsmRow(row);
|
|
1517
|
+
if (!asm) continue;
|
|
1518
|
+
const prev = byId.get(asm.id);
|
|
1519
|
+
if (prev) {
|
|
1520
|
+
if (asm.seq >= prev.seq) {
|
|
1521
|
+
replaceInBucket(buckets, prev, asm);
|
|
1522
|
+
byId.set(asm.id, asm);
|
|
1523
|
+
}
|
|
1524
|
+
continue;
|
|
1525
|
+
}
|
|
1526
|
+
byId.set(asm.id, asm);
|
|
1527
|
+
pushToBucket(buckets, asm);
|
|
1528
|
+
}
|
|
1529
|
+
const liveRunId = String(activeRunId || pendingRunId || "").trim();
|
|
1530
|
+
if (liveRunId) {
|
|
1531
|
+
for (const msg of liveMessages) {
|
|
1532
|
+
const asm = liveToAsmRow(msg, liveRunId);
|
|
1533
|
+
if (!asm) continue;
|
|
1534
|
+
if (byId.has(asm.id)) continue;
|
|
1535
|
+
pushToBucket(buckets, asm);
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
for (const list of buckets.values()) {
|
|
1539
|
+
list.sort((a, b) => a.seq - b.seq);
|
|
1540
|
+
}
|
|
1541
|
+
return buckets;
|
|
1542
|
+
}
|
|
1543
|
+
function pushToBucket(buckets, row) {
|
|
1544
|
+
const runId = String(row.runId || "").trim();
|
|
1545
|
+
if (!runId) return;
|
|
1546
|
+
const list = buckets.get(runId);
|
|
1547
|
+
if (list) list.push(row);
|
|
1548
|
+
else buckets.set(runId, [row]);
|
|
1549
|
+
}
|
|
1550
|
+
function replaceInBucket(buckets, prev, next) {
|
|
1551
|
+
const list = buckets.get(prev.runId);
|
|
1552
|
+
if (!list) return;
|
|
1553
|
+
const idx = list.indexOf(prev);
|
|
1554
|
+
if (idx >= 0) list[idx] = next;
|
|
1555
|
+
if (prev.runId !== next.runId) {
|
|
1556
|
+
const oldList = buckets.get(prev.runId);
|
|
1557
|
+
if (oldList) {
|
|
1558
|
+
const i = oldList.indexOf(prev);
|
|
1559
|
+
if (i >= 0) oldList.splice(i, 1);
|
|
1560
|
+
if (!oldList.length) buckets.delete(prev.runId);
|
|
1561
|
+
}
|
|
1562
|
+
pushToBucket(buckets, next);
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
// src/parser/extractors.ts
|
|
1567
|
+
function normalizeName(name) {
|
|
1568
|
+
const n = String(name || "").trim().toLowerCase();
|
|
1569
|
+
return n === "write_files" ? "write_file" : n;
|
|
1570
|
+
}
|
|
1571
|
+
function tryParseObject(result) {
|
|
1572
|
+
const text = String(result ?? "").trim();
|
|
1573
|
+
if (!text.startsWith("{")) return null;
|
|
1574
|
+
try {
|
|
1575
|
+
const parsed = JSON.parse(text);
|
|
1576
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
1577
|
+
return parsed;
|
|
1578
|
+
} catch {
|
|
1579
|
+
return null;
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
function extractFromToolResult(name, result, toolCallLike) {
|
|
1583
|
+
const tool = normalizeName(name);
|
|
1584
|
+
const obj = tryParseObject(result);
|
|
1585
|
+
if (tool === "ask_clarification" && obj) {
|
|
1586
|
+
const question = obj.question ?? obj.title;
|
|
1587
|
+
if (typeof question !== "string" || !question.trim()) return void 0;
|
|
1588
|
+
const options = Array.isArray(obj.options) ? obj.options : void 0;
|
|
1589
|
+
return options ? { kind: "clarification", question, options } : { kind: "clarification", question };
|
|
1590
|
+
}
|
|
1591
|
+
if (tool === "write_file") {
|
|
1592
|
+
if (obj) {
|
|
1593
|
+
if (typeof obj.body === "string" && obj.body) {
|
|
1594
|
+
const outline = typeof obj.outline === "string" ? obj.outline : void 0;
|
|
1595
|
+
return outline ? { kind: "report", reportKind: "report_body", body: obj.body, outline } : { kind: "report", reportKind: "report_body", body: obj.body };
|
|
1596
|
+
}
|
|
1597
|
+
if (Array.isArray(obj.files) && obj.files.length) {
|
|
1598
|
+
return { kind: "artifact", files: obj.files };
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
const reportKind = resolveReportArtifactKind(toolCallLike);
|
|
1602
|
+
if (reportKind) {
|
|
1603
|
+
const tc = toolCallLike ?? {};
|
|
1604
|
+
const sourcePath = String(tc?.artifact_meta?.path || tc?.args?.path || "").trim() || void 0;
|
|
1605
|
+
return {
|
|
1606
|
+
kind: "report",
|
|
1607
|
+
reportKind,
|
|
1608
|
+
sourcePath,
|
|
1609
|
+
title: sourcePath ? extractTitleFromArtifactPath(sourcePath, reportKind) : void 0
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
return void 0;
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
// src/parser/tool-args.ts
|
|
1617
|
+
function asArgsObject(args) {
|
|
1618
|
+
if (args && typeof args === "object" && !Array.isArray(args)) return args;
|
|
1619
|
+
if (typeof args === "string") {
|
|
1620
|
+
try {
|
|
1621
|
+
const parsed = JSON.parse(args);
|
|
1622
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1623
|
+
return parsed;
|
|
1624
|
+
}
|
|
1625
|
+
} catch {
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
return void 0;
|
|
1629
|
+
}
|
|
1630
|
+
function pickRicherArgs(prev, next) {
|
|
1631
|
+
const nextObj = asArgsObject(next);
|
|
1632
|
+
if (!nextObj) return void 0;
|
|
1633
|
+
const prevObj = asArgsObject(prev);
|
|
1634
|
+
if (!prevObj) return nextObj;
|
|
1635
|
+
const prevKeys = new Set(Object.keys(prevObj));
|
|
1636
|
+
const hasNewKey = Object.keys(nextObj).some((k) => !prevKeys.has(k));
|
|
1637
|
+
const longer = JSON.stringify(nextObj).length > JSON.stringify(prevObj).length;
|
|
1638
|
+
return hasNewKey || longer ? nextObj : void 0;
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
// src/assembler/types.ts
|
|
1642
|
+
var BACKEND_STATUS_MAP = {
|
|
1643
|
+
success: "success",
|
|
1644
|
+
error: "error",
|
|
1645
|
+
interrupted: "interrupted",
|
|
1646
|
+
cancelled: "cancelled",
|
|
1647
|
+
pending: "pending",
|
|
1648
|
+
running: "running"
|
|
1649
|
+
};
|
|
1650
|
+
|
|
1651
|
+
// src/assembler/run-assembly.ts
|
|
1652
|
+
function emptyRunItem(runId, createdAt) {
|
|
1653
|
+
return {
|
|
1654
|
+
runId,
|
|
1655
|
+
input: { kind: "message", text: "" },
|
|
1656
|
+
status: "pending",
|
|
1657
|
+
body: "",
|
|
1658
|
+
segments: [{ type: "text", content: "" }],
|
|
1659
|
+
tools: [],
|
|
1660
|
+
attachments: [],
|
|
1661
|
+
clarifications: [],
|
|
1662
|
+
rawMessages: [],
|
|
1663
|
+
...createdAt !== void 0 ? { createdAt } : {}
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
function assembleRun(runId, options) {
|
|
1667
|
+
const rows = options.rows;
|
|
1668
|
+
const twinEnabled = !!options.twin?.enabled;
|
|
1669
|
+
const twinToolPrefix = options.twin?.toolPrefix || "city-digital-twin-display_";
|
|
1670
|
+
let body = "";
|
|
1671
|
+
let feedback;
|
|
1672
|
+
const tools = [];
|
|
1673
|
+
const toolByCallId = /* @__PURE__ */ new Map();
|
|
1674
|
+
let createdAt;
|
|
1675
|
+
for (const row of rows) {
|
|
1676
|
+
const msg = row.msg;
|
|
1677
|
+
const type = String(msg?.type || "");
|
|
1678
|
+
if (createdAt === void 0 && row.createdAt !== void 0) createdAt = row.createdAt;
|
|
1679
|
+
if (type === "ai") {
|
|
1680
|
+
const text = extractAiContentFromMessage(msg);
|
|
1681
|
+
if (text) body = body ? `${body}
|
|
1682
|
+
${text}` : text;
|
|
1683
|
+
registerToolCalls(msg, tools, toolByCallId);
|
|
1684
|
+
} else if (type === "tool") {
|
|
1685
|
+
applyToolMessage(msg, tools, toolByCallId);
|
|
1686
|
+
} else if (type === "human") {
|
|
1687
|
+
}
|
|
1688
|
+
if (row.feedback !== void 0 && row.feedback !== null) feedback = row.feedback;
|
|
1689
|
+
}
|
|
1690
|
+
const attachments = assembleAttachments(tools, twinEnabled, twinToolPrefix);
|
|
1691
|
+
const clarifications = extractClarifications(tools);
|
|
1692
|
+
const segments = options.streaming ? [{ type: "text", content: body }] : sliceBodySegments(body);
|
|
1693
|
+
return {
|
|
1694
|
+
runId,
|
|
1695
|
+
// input 由 projectRuns 层填(需要 runs.list / 窗口 human 行两级来源),这里占位
|
|
1696
|
+
input: { kind: "message", text: "" },
|
|
1697
|
+
status: "success",
|
|
1698
|
+
body,
|
|
1699
|
+
segments,
|
|
1700
|
+
tools,
|
|
1701
|
+
attachments,
|
|
1702
|
+
...feedback !== void 0 ? { feedback } : {},
|
|
1703
|
+
clarifications,
|
|
1704
|
+
...createdAt !== void 0 ? { createdAt } : {},
|
|
1705
|
+
rawMessages: [...rows]
|
|
1706
|
+
};
|
|
1707
|
+
}
|
|
1708
|
+
function extractInputFromRows(rows) {
|
|
1709
|
+
for (const row of rows) {
|
|
1710
|
+
const msg = row.msg;
|
|
1711
|
+
if (!isVisibleUserMessage(msg)) continue;
|
|
1712
|
+
const kwargs = msg?.additional_kwargs;
|
|
1713
|
+
return {
|
|
1714
|
+
text: readMessageContentText(msg).trim(),
|
|
1715
|
+
...kwargs && typeof kwargs === "object" ? { kwargs: { ...kwargs } } : {}
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
return { text: "" };
|
|
1719
|
+
}
|
|
1720
|
+
function registerToolCalls(msg, tools, byCallId) {
|
|
1721
|
+
const calls = Array.isArray(msg?.tool_calls) ? msg.tool_calls : msg?.additional_kwargs?.tool_calls;
|
|
1722
|
+
if (!Array.isArray(calls)) return;
|
|
1723
|
+
for (const call of calls) {
|
|
1724
|
+
const callId = String(call?.id || "").trim();
|
|
1725
|
+
if (!callId) continue;
|
|
1726
|
+
const input = asArgsObject(call?.args);
|
|
1727
|
+
const artifactMeta = call?.artifact_meta;
|
|
1728
|
+
const prev = byCallId.get(callId);
|
|
1729
|
+
if (prev) {
|
|
1730
|
+
const richer = pickRicherArgs(prev.input, call?.args);
|
|
1731
|
+
if (richer) prev.input = richer;
|
|
1732
|
+
if (!prev.artifactMeta && artifactMeta) prev.artifactMeta = artifactMeta;
|
|
1733
|
+
continue;
|
|
1734
|
+
}
|
|
1735
|
+
const tool = { callId, name: String(call?.name || ""), status: "running" };
|
|
1736
|
+
if (input !== void 0) tool.input = input;
|
|
1737
|
+
if (artifactMeta !== void 0) tool.artifactMeta = artifactMeta;
|
|
1738
|
+
tools.push(tool);
|
|
1739
|
+
byCallId.set(callId, tool);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
function applyToolMessage(msg, tools, byCallId) {
|
|
1743
|
+
const callId = String(msg?.tool_call_id || "").trim();
|
|
1744
|
+
if (!callId) return;
|
|
1745
|
+
const tool = byCallId.get(callId);
|
|
1746
|
+
if (!tool) return;
|
|
1747
|
+
const result = readMessageContentText(msg);
|
|
1748
|
+
tool.result = result;
|
|
1749
|
+
const extracted = extractFromToolResult(tool.name, result, { artifact_meta: tool.artifactMeta, args: tool.input });
|
|
1750
|
+
if (extracted) tool.extracted = extracted;
|
|
1751
|
+
tool.status = String(msg?.status || "") === "error" ? "error" : "finished";
|
|
1752
|
+
}
|
|
1753
|
+
function assembleAttachments(tools, twinEnabled, twinToolPrefix) {
|
|
1754
|
+
const byKind = /* @__PURE__ */ new Map();
|
|
1755
|
+
for (const tool of tools) {
|
|
1756
|
+
const ex = tool.extracted;
|
|
1757
|
+
if (ex?.kind === "report") {
|
|
1758
|
+
byKind.set(`report:${ex.reportKind}`, {
|
|
1759
|
+
kind: "report",
|
|
1760
|
+
reportKind: ex.reportKind,
|
|
1761
|
+
body: ex.body,
|
|
1762
|
+
outline: ex.outline,
|
|
1763
|
+
sourcePath: ex.sourcePath,
|
|
1764
|
+
title: ex.title
|
|
1765
|
+
});
|
|
1766
|
+
} else if (ex?.kind === "artifact") {
|
|
1767
|
+
byKind.set("artifact", { kind: "artifact", files: ex.files });
|
|
1768
|
+
} else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
|
|
1769
|
+
byKind.set("twin", { kind: "twin", payload: tool.input });
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
return [...byKind.values()];
|
|
1773
|
+
}
|
|
1774
|
+
function extractClarifications(tools) {
|
|
1775
|
+
const out = [];
|
|
1776
|
+
for (const tool of tools) {
|
|
1777
|
+
if (tool.name !== "ask_clarification") continue;
|
|
1778
|
+
const args = asArgsObject(tool.input);
|
|
1779
|
+
const question = String(args?.question ?? args?.title ?? "").trim();
|
|
1780
|
+
if (!question) continue;
|
|
1781
|
+
const record = { callId: tool.callId, question };
|
|
1782
|
+
if (args?.options !== void 0) record.options = args.options;
|
|
1783
|
+
if (Array.isArray(args?.fields)) record.fields = args.fields;
|
|
1784
|
+
out.push(record);
|
|
1785
|
+
}
|
|
1786
|
+
return out;
|
|
1787
|
+
}
|
|
1788
|
+
function mapBackendStatus(raw) {
|
|
1789
|
+
const v = String(raw || "").trim();
|
|
1790
|
+
return BACKEND_STATUS_MAP[v] ?? "success";
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
// src/assembler/project-runs.ts
|
|
1794
|
+
function classifyInputKind(inputMsg) {
|
|
1795
|
+
const kwargs = inputMsg?.additional_kwargs;
|
|
1796
|
+
if (kwargs?.human_input_response && typeof kwargs.human_input_response === "object") return "clarification";
|
|
1797
|
+
return "message";
|
|
1798
|
+
}
|
|
1799
|
+
function inputFromRunMeta(meta) {
|
|
1800
|
+
const messages = meta.inputMessages ?? [];
|
|
1801
|
+
if (!messages.length) return null;
|
|
1802
|
+
const first = messages[0];
|
|
1803
|
+
const visible = messages.find((m) => isVisibleUserMessage(m));
|
|
1804
|
+
const text = visible ? readMessageContentText(visible) : "";
|
|
1805
|
+
const kwargs = first.additional_kwargs;
|
|
1806
|
+
const hasKwargs = kwargs && typeof kwargs === "object" && Object.keys(kwargs).length > 0;
|
|
1807
|
+
return {
|
|
1808
|
+
kind: classifyInputKind(first),
|
|
1809
|
+
text,
|
|
1810
|
+
...hasKwargs ? { kwargs: { ...kwargs } } : {}
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
function normalizeRequestId(raw) {
|
|
1814
|
+
return String(raw ?? "").trim().replace("clarification:", "");
|
|
1815
|
+
}
|
|
1816
|
+
function projectRuns(input) {
|
|
1817
|
+
const buckets = groupRowsByRun(input.rows, input.liveMessages, input.activeRunId, input.pendingRun?.runId ?? null);
|
|
1818
|
+
const metaByRunId = new Map(input.runsList.map((m) => [String(m.runId || ""), m]));
|
|
1819
|
+
const orderedBuckets = [...buckets.entries()].sort(
|
|
1820
|
+
(a, b) => (a[1][0]?.seq ?? 0) - (b[1][0]?.seq ?? 0)
|
|
1821
|
+
);
|
|
1822
|
+
const runs = [];
|
|
1823
|
+
for (const [runId, rows] of orderedBuckets) {
|
|
1824
|
+
const meta = metaByRunId.get(runId);
|
|
1825
|
+
const isStreamingRun = input.streaming && input.activeRunId === runId;
|
|
1826
|
+
const item = assembleRun(runId, { rows, streaming: isStreamingRun, twin: input.twin });
|
|
1827
|
+
const fromMeta = meta ? inputFromRunMeta(meta) : void 0;
|
|
1828
|
+
if (fromMeta) {
|
|
1829
|
+
item.input = fromMeta;
|
|
1830
|
+
} else {
|
|
1831
|
+
const fromRows = extractInputFromRows(rows);
|
|
1832
|
+
if (fromRows.text) {
|
|
1833
|
+
item.input = {
|
|
1834
|
+
kind: classifyInputKind(fromRows.kwargs),
|
|
1835
|
+
text: fromRows.text,
|
|
1836
|
+
...fromRows.kwargs ? { kwargs: fromRows.kwargs } : {}
|
|
1837
|
+
};
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
const pendingInput = input.pendingRun;
|
|
1841
|
+
if (pendingInput && runId === pendingInput.runId && !item.input.text) {
|
|
1842
|
+
item.input = {
|
|
1843
|
+
kind: pendingInput.kind,
|
|
1844
|
+
text: pendingInput.text,
|
|
1845
|
+
...pendingInput.kwargs ? { kwargs: pendingInput.kwargs } : {}
|
|
1846
|
+
};
|
|
1847
|
+
}
|
|
1848
|
+
if (isStreamingRun) item.status = "running";
|
|
1849
|
+
else if (meta) {
|
|
1850
|
+
item.status = mapBackendStatus(meta.status);
|
|
1851
|
+
if (meta.tokens) item.tokens = meta.tokens;
|
|
1852
|
+
if (meta.createdAt !== void 0) item.createdAt = meta.createdAt;
|
|
1853
|
+
if (meta.stopReason) item.stopReason = meta.stopReason;
|
|
1854
|
+
}
|
|
1855
|
+
runs.push(item);
|
|
1856
|
+
}
|
|
1857
|
+
const pending = input.pendingRun;
|
|
1858
|
+
if (pending && !buckets.has(pending.runId)) {
|
|
1859
|
+
const placeholder = emptyRunItem(pending.runId, Date.now());
|
|
1860
|
+
placeholder.input = { kind: pending.kind, text: pending.text, ...pending.kwargs ? { kwargs: { ...pending.kwargs } } : {} };
|
|
1861
|
+
if (input.streaming && input.activeRunId === pending.runId) placeholder.status = "running";
|
|
1862
|
+
runs.push(placeholder);
|
|
1863
|
+
}
|
|
1864
|
+
const answers = input.answers;
|
|
1865
|
+
for (let i = 0; i < runs.length; i++) {
|
|
1866
|
+
const run = runs[i];
|
|
1867
|
+
for (const record of run.clarifications) {
|
|
1868
|
+
if (record.answer !== void 0) continue;
|
|
1869
|
+
const optimistic = answers?.get(record.callId);
|
|
1870
|
+
if (optimistic !== void 0) {
|
|
1871
|
+
record.answer = optimistic;
|
|
1872
|
+
continue;
|
|
1873
|
+
}
|
|
1874
|
+
for (let j = i + 1; j < runs.length; j++) {
|
|
1875
|
+
const laterKwargs = runs[j].input.kwargs;
|
|
1876
|
+
const response = laterKwargs?.human_input_response;
|
|
1877
|
+
if (!response || typeof response !== "object") continue;
|
|
1878
|
+
if (normalizeRequestId(response.request_id) !== normalizeRequestId(record.callId)) continue;
|
|
1879
|
+
record.answer = formatAnswerText(response.value);
|
|
1880
|
+
record.answerRunId = runs[j].runId;
|
|
1881
|
+
break;
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
return runs;
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
// src/runtime/run-info.ts
|
|
1466
1889
|
function buildRunInfo(run, threadId) {
|
|
1467
1890
|
return {
|
|
1468
1891
|
runId: String(run?.run_id || "").trim(),
|
|
1469
1892
|
threadId: String(threadId || "").trim(),
|
|
1470
1893
|
usage: buildRunUsage(run),
|
|
1471
1894
|
latencyMs: buildRunLatencyMs(run),
|
|
1472
|
-
finishReason: toOptionalString(run?.finish_reason),
|
|
1895
|
+
finishReason: toOptionalString(run?.stop_reason ?? run?.finish_reason),
|
|
1473
1896
|
modelName: toOptionalString(run?.model_name),
|
|
1474
1897
|
status: buildRunStatus(run),
|
|
1475
1898
|
createdAt: buildRunCreatedAt(run)
|
|
@@ -1491,6 +1914,32 @@ function buildRunStatus(run) {
|
|
|
1491
1914
|
function buildRunCreatedAt(run) {
|
|
1492
1915
|
return run?.created_at ? Number(new Date(run.created_at)) : void 0;
|
|
1493
1916
|
}
|
|
1917
|
+
function buildRunMeta(run) {
|
|
1918
|
+
const runId = String(run?.run_id || "").trim();
|
|
1919
|
+
if (!runId) return null;
|
|
1920
|
+
const inputMessages = run?.kwargs?.input?.messages ?? [];
|
|
1921
|
+
const totalTokens = Number(run?.total_tokens);
|
|
1922
|
+
const tokens = Number.isFinite(totalTokens) && totalTokens > 0 ? {
|
|
1923
|
+
total: totalTokens,
|
|
1924
|
+
input: Number(run?.total_input_tokens) || 0,
|
|
1925
|
+
output: Number(run?.total_output_tokens) || 0,
|
|
1926
|
+
...Number.isFinite(Number(run?.llm_call_count)) ? { llmCallCount: Number(run.llm_call_count) } : {},
|
|
1927
|
+
byCaller: {
|
|
1928
|
+
leadAgent: Number(run?.lead_agent_tokens) || 0,
|
|
1929
|
+
subagent: Number(run?.subagent_tokens) || 0,
|
|
1930
|
+
middleware: Number(run?.middleware_tokens) || 0
|
|
1931
|
+
}
|
|
1932
|
+
} : void 0;
|
|
1933
|
+
const createdAt = buildRunCreatedAt(run);
|
|
1934
|
+
return {
|
|
1935
|
+
runId,
|
|
1936
|
+
status: String(run?.status || "").trim(),
|
|
1937
|
+
...createdAt !== void 0 ? { createdAt } : {},
|
|
1938
|
+
...Array.isArray(inputMessages) && inputMessages.length ? { inputMessages } : {},
|
|
1939
|
+
...tokens ? { tokens } : {},
|
|
1940
|
+
...run?.stop_reason !== void 0 && run?.stop_reason !== null ? { stopReason: String(run.stop_reason) } : {}
|
|
1941
|
+
};
|
|
1942
|
+
}
|
|
1494
1943
|
function buildRunDirectLatencyMs(run) {
|
|
1495
1944
|
const direct = Number(run?.latency_ms);
|
|
1496
1945
|
return direct || void 0;
|
|
@@ -1525,931 +1974,87 @@ function pickRunMessageMetadata(messages) {
|
|
|
1525
1974
|
return { modelName, finishReason };
|
|
1526
1975
|
}
|
|
1527
1976
|
|
|
1528
|
-
// src/
|
|
1529
|
-
var
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
const
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
return parser ? parser(tool, status) : [];
|
|
1548
|
-
};
|
|
1549
|
-
const parseAskClarification = (tool, _status) => {
|
|
1550
|
-
const args = tool.call?.args || {};
|
|
1551
|
-
return [
|
|
1552
|
-
{
|
|
1553
|
-
id: genBlockId(),
|
|
1554
|
-
type: "ask-clarification",
|
|
1555
|
-
context: args.context,
|
|
1556
|
-
question: args.question,
|
|
1557
|
-
clarification_type: args.clarification_type,
|
|
1558
|
-
options: Array.isArray(args.options) ? args.options : void 0,
|
|
1559
|
-
fields: Array.isArray(args.fields) ? args.fields : void 0,
|
|
1560
|
-
// clarification 的回答是跨 run 的,不能根据 streaming/source 判断状态,统一 pending,由渲染层结合 thread 级回答状态决定
|
|
1561
|
-
status: "pending",
|
|
1562
|
-
toolCallId: tool.id
|
|
1563
|
-
}
|
|
1564
|
-
];
|
|
1565
|
-
};
|
|
1566
|
-
const parseFormBlock = (tool, status, sourceTag) => {
|
|
1567
|
-
const args = tool.call?.args || {};
|
|
1568
|
-
const variant = String(args.variant || "input");
|
|
1569
|
-
const blockStatus = sourceTag === "ask_clarification" ? "pending" : status;
|
|
1570
|
-
return [
|
|
1571
|
-
{
|
|
1572
|
-
id: genBlockId(),
|
|
1573
|
-
type: "form",
|
|
1574
|
-
variant: ["input", "confirm", "delete_confirm"].includes(variant) ? variant : "input",
|
|
1575
|
-
title: args.title,
|
|
1576
|
-
question: args.question,
|
|
1577
|
-
context: args.context,
|
|
1578
|
-
fields: Array.isArray(args.fields) ? args.fields : [],
|
|
1579
|
-
values: args.values || {},
|
|
1580
|
-
stepInfo: args.stepInfo,
|
|
1581
|
-
customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
|
|
1582
|
-
status: blockStatus,
|
|
1583
|
-
toolCallId: tool.id,
|
|
1584
|
-
source: sourceTag
|
|
1585
|
-
}
|
|
1586
|
-
];
|
|
1587
|
-
};
|
|
1588
|
-
const parseListBlock = (tool, status) => {
|
|
1589
|
-
const args = tool.call?.args || {};
|
|
1590
|
-
const mode = String(args.mode || "select");
|
|
1591
|
-
return [
|
|
1592
|
-
{
|
|
1593
|
-
id: genBlockId(),
|
|
1594
|
-
type: "list",
|
|
1595
|
-
mode: ["select", "view"].includes(mode) ? mode : "select",
|
|
1596
|
-
title: args.title,
|
|
1597
|
-
dataSource: args.dataSource,
|
|
1598
|
-
items: Array.isArray(args.items) ? args.items : void 0,
|
|
1599
|
-
queryParams: args.queryParams,
|
|
1600
|
-
pagination: args.pagination,
|
|
1601
|
-
selectMode: args.selectMode || "single",
|
|
1602
|
-
customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
|
|
1603
|
-
status,
|
|
1604
|
-
toolCallId: tool.id
|
|
1605
|
-
}
|
|
1606
|
-
];
|
|
1607
|
-
};
|
|
1608
|
-
const parsePresentFiles = (tool, status) => {
|
|
1609
|
-
const args = tool.call?.args || {};
|
|
1610
|
-
const filepaths = Array.isArray(args?.filepaths) ? args.filepaths : [];
|
|
1611
|
-
if (!filepaths.length) return [];
|
|
1612
|
-
const paths = [];
|
|
1613
|
-
for (const path of filepaths) {
|
|
1614
|
-
if (presentFilesSet.has(path)) continue;
|
|
1615
|
-
presentFilesSet.add(path);
|
|
1616
|
-
paths.push(path);
|
|
1617
|
-
}
|
|
1618
|
-
if (!paths.length) return [];
|
|
1619
|
-
return [
|
|
1620
|
-
{
|
|
1621
|
-
id: genBlockId(),
|
|
1622
|
-
type: "artifact",
|
|
1623
|
-
files: buildArtifactFiles(paths),
|
|
1624
|
-
status
|
|
1625
|
-
}
|
|
1626
|
-
];
|
|
1627
|
-
};
|
|
1628
|
-
const resolveWriteFileContext = (tool) => {
|
|
1629
|
-
const meta = getToolCallArtifactMeta(tool.call);
|
|
1630
|
-
const args = tool.call?.args || {};
|
|
1631
|
-
const artifactPath = String(meta?.path || args.path || "").trim();
|
|
1632
|
-
const content = String(args.content || tool.result?.content || "").trim();
|
|
1633
|
-
const description = String(args.description || "").trim();
|
|
1634
|
-
const blockId = tool.id || artifactPath || `report-${Date.now()}`;
|
|
1635
|
-
const toolCreatedAt = Number(new Date(asSxin(tool.aiMessage).created_at || ""));
|
|
1636
|
-
const toolTime = Number.isFinite(toolCreatedAt) ? toolCreatedAt : createdAt;
|
|
1637
|
-
if (!content && source === "sse") return null;
|
|
1638
|
-
if (writeFilesSet.has(artifactPath)) return null;
|
|
1639
|
-
writeFilesSet.add(artifactPath);
|
|
1640
|
-
presentFilesSet.add(artifactPath);
|
|
1641
|
-
return { artifactPath, content, description, blockId, createdAt: toolTime };
|
|
1642
|
-
};
|
|
1643
|
-
const buildReportBlock = (kind, ctx, status) => {
|
|
1644
|
-
const isOutline = kind === "report_outline";
|
|
1645
|
-
const fallbackName = extractTitleFromArtifactPath(ctx.artifactPath, kind) || ctx.description.replace(isOutline ? /生成|大纲/g : /生成|正文|报告/g, "").trim() || "\u62A5\u544A";
|
|
1646
|
-
const isState = source === "state";
|
|
1647
|
-
const payloadInput = {
|
|
1648
|
-
templateId: ctx.blockId,
|
|
1649
|
-
fallbackName,
|
|
1650
|
-
sourcePath: ctx.artifactPath || void 0,
|
|
1651
|
-
content: isState ? void 0 : ctx.content || void 0,
|
|
1652
|
-
contentRef: isState && ctx.artifactPath ? { path: ctx.artifactPath } : void 0,
|
|
1653
|
-
createdAt: ctx.createdAt
|
|
1654
|
-
};
|
|
1655
|
-
return isOutline ? { id: genBlockId(), type: "report-outline", payload: buildReportOutlinePayload(payloadInput), status } : { id: genBlockId(), type: "report-body", payload: buildReportBodyPayload(payloadInput), status };
|
|
1656
|
-
};
|
|
1657
|
-
const parseWriteFile = (tool, status) => {
|
|
1658
|
-
const name = String(tool.call?.name || "").trim();
|
|
1659
|
-
if (!isWriteFileToolName(name)) return [];
|
|
1660
|
-
const kind = resolveReportArtifactKind(tool.call);
|
|
1661
|
-
if (!kind) return [];
|
|
1662
|
-
const ctx = resolveWriteFileContext(tool);
|
|
1663
|
-
if (!ctx) return [];
|
|
1664
|
-
const block = buildReportBlock(kind, ctx, status);
|
|
1665
|
-
return block ? [block] : [];
|
|
1666
|
-
};
|
|
1667
|
-
const parseClarification = (tool, status) => {
|
|
1668
|
-
const args = tool.call?.args || {};
|
|
1669
|
-
if (args.variant || args.fields?.length) {
|
|
1670
|
-
return parseFormBlock(tool, status, "ask_clarification");
|
|
1977
|
+
// src/runtime/semantic-overlay.ts
|
|
1978
|
+
var extractKwargsPatch = (msg) => {
|
|
1979
|
+
const kwargs = msg?.additional_kwargs;
|
|
1980
|
+
if (!kwargs || typeof kwargs !== "object") return void 0;
|
|
1981
|
+
const patch = {};
|
|
1982
|
+
if (kwargs.hide_from_ui === true) patch.hide_from_ui = true;
|
|
1983
|
+
if (kwargs.human_input_response && typeof kwargs.human_input_response === "object") {
|
|
1984
|
+
patch.human_input_response = kwargs.human_input_response;
|
|
1985
|
+
}
|
|
1986
|
+
return Object.keys(patch).length ? patch : void 0;
|
|
1987
|
+
};
|
|
1988
|
+
function extractSemanticPatchesFromMessages(messages) {
|
|
1989
|
+
const next = /* @__PURE__ */ new Map();
|
|
1990
|
+
for (const m of messages ?? []) {
|
|
1991
|
+
const id = String(m?.id || "").trim();
|
|
1992
|
+
if (!id) continue;
|
|
1993
|
+
const patch = { id };
|
|
1994
|
+
if (String(m?.type || "") === "ai" && hasKbCitationMessage(m)) {
|
|
1995
|
+
patch.content = m.content;
|
|
1671
1996
|
}
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
registerParser(
|
|
1676
|
-
["confirm_form", "form"],
|
|
1677
|
-
(tool, status) => parseFormBlock(tool, status, String(tool.call?.name || "").trim())
|
|
1678
|
-
);
|
|
1679
|
-
registerParser(["list_and_select", "list"], parseListBlock);
|
|
1680
|
-
registerParser("present_files", parsePresentFiles);
|
|
1681
|
-
registerParser(["write_file", "write_files"], parseWriteFile);
|
|
1682
|
-
const buildFromNodes = (nodes, rawText, tools) => {
|
|
1683
|
-
const blocks = [];
|
|
1684
|
-
const status = isStreaming ? "streaming" : "completed";
|
|
1685
|
-
const contentSource = source === "state" ? "history" : source;
|
|
1686
|
-
const { blocks: contentBlocks } = extractBlocksFromNodes(nodes, rawText, contentSource);
|
|
1687
|
-
blocks.push(...contentBlocks);
|
|
1688
|
-
for (const tool of tools) {
|
|
1689
|
-
const toolBlocks = parseBlockTool(tool, status);
|
|
1690
|
-
blocks.push(...toolBlocks);
|
|
1691
|
-
}
|
|
1692
|
-
if (twinEnabled) {
|
|
1693
|
-
const twinTool = tools.reverse().find((_) => _.call?.name.includes(twinToolPrefix));
|
|
1694
|
-
if (twinTool) {
|
|
1695
|
-
blocks.push({
|
|
1696
|
-
id: genBlockId(),
|
|
1697
|
-
type: "twin",
|
|
1698
|
-
toolName: twinTool.call.name.replace(twinToolPrefix, ""),
|
|
1699
|
-
args: twinTool.call.args
|
|
1700
|
-
});
|
|
1701
|
-
}
|
|
1997
|
+
if (String(m?.type || "") === "human") {
|
|
1998
|
+
const kwargs = extractKwargsPatch(m);
|
|
1999
|
+
if (kwargs) patch.additional_kwargs = kwargs;
|
|
1702
2000
|
}
|
|
1703
|
-
|
|
1704
|
-
};
|
|
1705
|
-
const build = (content, tools) => buildFromNodes(tokenizeSxin(content), content, tools);
|
|
1706
|
-
return { build, buildFromNodes };
|
|
1707
|
-
}
|
|
1708
|
-
|
|
1709
|
-
// src/domain/fold.ts
|
|
1710
|
-
function messageRunId(msg) {
|
|
1711
|
-
const own = String(asSxin(msg).runId || "").trim();
|
|
1712
|
-
if (own) return own;
|
|
1713
|
-
return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
|
|
1714
|
-
}
|
|
1715
|
-
function foldMessages(target, flush) {
|
|
1716
|
-
let type = null;
|
|
1717
|
-
let buf = [];
|
|
1718
|
-
let groupRunId;
|
|
1719
|
-
const doFlush = () => {
|
|
1720
|
-
if (!buf.length || !type) return;
|
|
1721
|
-
flush(type, buf);
|
|
1722
|
-
buf = [];
|
|
1723
|
-
};
|
|
1724
|
-
for (const m of target) {
|
|
1725
|
-
if (isHumanMessage(m)) {
|
|
1726
|
-
if (!(type === "human" && buf.length && getHumanMessageBaseId(String(asSxin(m).id || "")) === getHumanMessageBaseId(String(asSxin(buf[0]).id || ""))))
|
|
1727
|
-
doFlush();
|
|
1728
|
-
type = "human";
|
|
1729
|
-
buf.push(m);
|
|
1730
|
-
} else if (isAiMessage(m) || isToolMessage(m)) {
|
|
1731
|
-
const mRunId = messageRunId(m);
|
|
1732
|
-
if (type !== "ai" || mRunId && groupRunId && mRunId !== groupRunId) doFlush();
|
|
1733
|
-
if (!buf.length) groupRunId = mRunId;
|
|
1734
|
-
type = "ai";
|
|
1735
|
-
buf.push(m);
|
|
1736
|
-
}
|
|
1737
|
-
}
|
|
1738
|
-
doFlush();
|
|
1739
|
-
}
|
|
1740
|
-
|
|
1741
|
-
// src/domain/group-materializer.ts
|
|
1742
|
-
function readCreatedAt(msg) {
|
|
1743
|
-
return Number(new Date(asSxin(msg).created_at || Date.now())) || Date.now();
|
|
1744
|
-
}
|
|
1745
|
-
function buildHumanGroup(messages, status) {
|
|
1746
|
-
const representative = messages.find(
|
|
1747
|
-
(m) => parseHumanMessageId(String(asSxin(m).id || "")).variant === "user" && isVisibleUserMessage(m)
|
|
1748
|
-
) || messages.find((m) => isVisibleUserMessage(m)) || messages[0];
|
|
1749
|
-
const firstId = messages.find((_) => _.id)?.id || genMessageId();
|
|
1750
|
-
const additionalKwargs = asSxin(representative).additional_kwargs;
|
|
1751
|
-
const texts = extractUserMessageTexts(messages);
|
|
1752
|
-
const runId = messageRunId(representative);
|
|
1753
|
-
return {
|
|
1754
|
-
id: firstId,
|
|
1755
|
-
type: "human",
|
|
1756
|
-
status,
|
|
1757
|
-
originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
|
|
1758
|
-
runId,
|
|
1759
|
-
rawMessages: messages,
|
|
1760
|
-
texts,
|
|
1761
|
-
additionalKwargs,
|
|
1762
|
-
blocks: [],
|
|
1763
|
-
toolIds: [],
|
|
1764
|
-
tools: [],
|
|
1765
|
-
createdAt: readCreatedAt(representative)
|
|
1766
|
-
};
|
|
1767
|
-
}
|
|
1768
|
-
function buildAiGroup(messages, options, twin) {
|
|
1769
|
-
const firstId = messages.find((_) => _.id)?.id || genMessageId();
|
|
1770
|
-
const groupTools = deriveToolsFromMessages(messages);
|
|
1771
|
-
const aiMessages = messages.filter(isAiMessage);
|
|
1772
|
-
const lastAi = aiMessages[aiMessages.length - 1] || messages[messages.length - 1];
|
|
1773
|
-
const content = readMessageContentText(lastAi);
|
|
1774
|
-
const createdAt = readCreatedAt(messages[0]);
|
|
1775
|
-
const blocks = options.isStreaming ? [] : createBlockBuilderLite({ source: options.source, twin, createdAt }).buildFromNodes(
|
|
1776
|
-
tokenizeSxin(content),
|
|
1777
|
-
content,
|
|
1778
|
-
groupTools
|
|
1779
|
-
);
|
|
1780
|
-
const anchors = extractCitationAnchors(blocks);
|
|
1781
|
-
const citations = anchors.length ? anchors : void 0;
|
|
1782
|
-
return {
|
|
1783
|
-
id: firstId,
|
|
1784
|
-
type: "ai",
|
|
1785
|
-
status: options.isStreaming ? "streaming" : "completed",
|
|
1786
|
-
originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
|
|
1787
|
-
runId: messageRunId(lastAi) || options.runId,
|
|
1788
|
-
rawMessages: messages,
|
|
1789
|
-
blocks,
|
|
1790
|
-
citations,
|
|
1791
|
-
toolIds: groupTools.map((t) => t.id),
|
|
1792
|
-
tools: groupTools,
|
|
1793
|
-
createdAt
|
|
1794
|
-
};
|
|
1795
|
-
}
|
|
1796
|
-
|
|
1797
|
-
// src/domain/clarification.ts
|
|
1798
|
-
function isClarificationAnswered(block, answers) {
|
|
1799
|
-
if (!block) return false;
|
|
1800
|
-
if (block.status === "completed") return true;
|
|
1801
|
-
if (block.isAnswered) return true;
|
|
1802
|
-
const toolCallId = block.toolCallId;
|
|
1803
|
-
return !!toolCallId && answers.has(toolCallId);
|
|
1804
|
-
}
|
|
1805
|
-
function isClarificationBlock(block) {
|
|
1806
|
-
return block.type === "ask-clarification" || block.type === "form" && block.source === "ask_clarification";
|
|
1807
|
-
}
|
|
1808
|
-
|
|
1809
|
-
// src/domain/decorators.ts
|
|
1810
|
-
function applyPatchesAndExtras(groups, state, runIdFilter) {
|
|
1811
|
-
if (!state.patches.size && !state.extras.length) return groups;
|
|
1812
|
-
const patchedGroups = groups.map((g) => state.patches.get(g.id) ?? g);
|
|
1813
|
-
const anchor = runIdFilter ? patchedGroups.findIndex((g) => String(g.runId || "").trim() === runIdFilter) : -1;
|
|
1814
|
-
return anchor >= 0 ? [...patchedGroups.slice(0, anchor), ...state.extras, ...patchedGroups.slice(anchor)] : [...patchedGroups, ...state.extras];
|
|
1815
|
-
}
|
|
1816
|
-
function withInterruptBlock(groups, deps) {
|
|
1817
|
-
const interrupt = deps.getInterrupt();
|
|
1818
|
-
if (!interrupt) return groups;
|
|
1819
|
-
const interruptId = String(interrupt.id || "");
|
|
1820
|
-
const responded = !!interruptId && deps.respondedIds.has(interruptId);
|
|
1821
|
-
const block = buildInterruptReviewBlock(interrupt, responded);
|
|
1822
|
-
if (!block) return groups;
|
|
1823
|
-
const { interruptBlocks } = deps;
|
|
1824
|
-
const targetIndex = findLastAiIndex(groups);
|
|
1825
|
-
if (targetIndex >= 0) {
|
|
1826
|
-
const remembered = interruptBlocks.get(interruptId);
|
|
1827
|
-
if (remembered) {
|
|
1828
|
-
const updated = { ...block, status: responded ? "completed" : "pending" };
|
|
1829
|
-
interruptBlocks.set(interruptId, updated);
|
|
1830
|
-
const next2 = [...groups];
|
|
1831
|
-
next2[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, updated] };
|
|
1832
|
-
return next2;
|
|
1833
|
-
}
|
|
1834
|
-
interruptBlocks.set(interruptId, block);
|
|
1835
|
-
const next = [...groups];
|
|
1836
|
-
next[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, block] };
|
|
1837
|
-
return next;
|
|
2001
|
+
if (patch.content !== void 0 || patch.additional_kwargs) next.set(id, patch);
|
|
1838
2002
|
}
|
|
1839
|
-
|
|
1840
|
-
(b) => b.type === "interrupt-review" && b.interruptId === interruptId
|
|
1841
|
-
);
|
|
1842
|
-
if (existing) return groups;
|
|
1843
|
-
interruptBlocks.set(interruptId, block);
|
|
1844
|
-
return [
|
|
1845
|
-
...groups,
|
|
1846
|
-
{
|
|
1847
|
-
id: `interrupt-${interruptId}`,
|
|
1848
|
-
type: "ai",
|
|
1849
|
-
status: block.status,
|
|
1850
|
-
source: "state",
|
|
1851
|
-
originMessageIds: [],
|
|
1852
|
-
blocks: [block],
|
|
1853
|
-
toolIds: [],
|
|
1854
|
-
tools: [],
|
|
1855
|
-
rawMessages: [],
|
|
1856
|
-
createdAt: Date.now()
|
|
1857
|
-
}
|
|
1858
|
-
];
|
|
1859
|
-
}
|
|
1860
|
-
function findLastAiIndex(groups) {
|
|
1861
|
-
for (let i = groups.length - 1; i >= 0; i--) {
|
|
1862
|
-
if (groups[i].type === "ai") return i;
|
|
1863
|
-
}
|
|
1864
|
-
return -1;
|
|
1865
|
-
}
|
|
1866
|
-
function decorateAnswers(groups, answers, responded) {
|
|
1867
|
-
if (!answers.size && !responded.size) return groups;
|
|
1868
|
-
return groups.map((g) => {
|
|
1869
|
-
if (g.type !== "ai" || !g.blocks.length) return g;
|
|
1870
|
-
let touched = false;
|
|
1871
|
-
const blocks = g.blocks.map((b) => {
|
|
1872
|
-
const blk = b;
|
|
1873
|
-
if (isClarificationBlock(blk) && blk.toolCallId && answers.has(blk.toolCallId)) {
|
|
1874
|
-
touched = true;
|
|
1875
|
-
return { ...b, isAnswered: true, answer: answers.get(blk.toolCallId) };
|
|
1876
|
-
}
|
|
1877
|
-
if (blk.type === "interrupt-review" && blk.interruptId && responded.has(blk.interruptId)) {
|
|
1878
|
-
touched = true;
|
|
1879
|
-
return { ...b, isResponded: true };
|
|
1880
|
-
}
|
|
1881
|
-
return b;
|
|
1882
|
-
});
|
|
1883
|
-
return touched ? { ...g, blocks } : g;
|
|
1884
|
-
});
|
|
2003
|
+
return next;
|
|
1885
2004
|
}
|
|
1886
|
-
function
|
|
1887
|
-
|
|
1888
|
-
}
|
|
1889
|
-
function hasVisibleAiContent(g) {
|
|
1890
|
-
if (g.status === "streaming") return true;
|
|
1891
|
-
if (g.streamingText) return true;
|
|
1892
|
-
if (g.blocks.length) return true;
|
|
1893
|
-
return g.tools.some((t) => t.result !== void 0 || t.state === "error");
|
|
1894
|
-
}
|
|
1895
|
-
|
|
1896
|
-
// src/domain/viewmodel-state.ts
|
|
1897
|
-
var import_vue2 = require("vue");
|
|
1898
|
-
function createViewModelState() {
|
|
1899
|
-
const extrasRef = (0, import_vue2.shallowRef)([]);
|
|
1900
|
-
const patches = (0, import_vue2.shallowReactive)(/* @__PURE__ */ new Map());
|
|
1901
|
-
const readFirstText = (group) => extractTextFromMessage(asSxin(group.rawMessages[0])).trim();
|
|
2005
|
+
function createSemanticOverlay() {
|
|
2006
|
+
let patches = /* @__PURE__ */ new Map();
|
|
1902
2007
|
return {
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
return patches;
|
|
1908
|
-
},
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
const
|
|
1930
|
-
|
|
1931
|
-
const
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
if (runId !== runIdFilter) continue;
|
|
1936
|
-
const text = readFirstText(g);
|
|
1937
|
-
echoed.set(text, (echoed.get(text) ?? 0) + 1);
|
|
1938
|
-
}
|
|
1939
|
-
const seenPerText = /* @__PURE__ */ new Map();
|
|
1940
|
-
extrasRef.value = extrasRef.value.filter((extra) => {
|
|
1941
|
-
if (extra.type !== "human") return true;
|
|
1942
|
-
const text = readFirstText(extra);
|
|
1943
|
-
const k = seenPerText.get(text) ?? 0;
|
|
1944
|
-
seenPerText.set(text, k + 1);
|
|
1945
|
-
return (echoed.get(text) ?? 0) <= k;
|
|
1946
|
-
});
|
|
1947
|
-
}
|
|
1948
|
-
};
|
|
1949
|
-
}
|
|
1950
|
-
|
|
1951
|
-
// src/domain/viewmodel.ts
|
|
1952
|
-
function createGroupDeriver(state) {
|
|
1953
|
-
const groupMemo = /* @__PURE__ */ new Map();
|
|
1954
|
-
const foldCache = { pageCount: -1, entries: [] };
|
|
1955
|
-
const interruptBlocks = /* @__PURE__ */ new Map();
|
|
1956
|
-
const derive = (deps) => {
|
|
1957
|
-
const { store, enrichments } = deps;
|
|
1958
|
-
const streaming = store.streamStatus === "streaming";
|
|
1959
|
-
const patched = store.getMessages().map((m) => {
|
|
1960
|
-
const patch = enrichments.resolveCitation(String(asSxin(m).id || ""));
|
|
1961
|
-
if (!patch || patch.content === void 0) return m;
|
|
1962
|
-
return { ...asSxin(m), content: patch.content };
|
|
1963
|
-
});
|
|
1964
|
-
const sourceOf = (id) => id ? store.getEntity(id)?.source ?? "stream" : "stream";
|
|
1965
|
-
const epochOf = (id) => id ? store.getEntity(id)?.epoch : void 0;
|
|
1966
|
-
const runIdFilter = String(deps.currentRunId || "").trim();
|
|
1967
|
-
const currentEpoch = store.streamEpoch;
|
|
1968
|
-
const pageCount = store.pageCount;
|
|
1969
|
-
const patchedPrefix = patched.slice(0, pageCount);
|
|
1970
|
-
const patchedStream = patched.slice(pageCount);
|
|
1971
|
-
let prefixEntries;
|
|
1972
|
-
if (foldCache.pageCount === pageCount) {
|
|
1973
|
-
prefixEntries = foldCache.entries;
|
|
1974
|
-
} else {
|
|
1975
|
-
prefixEntries = [];
|
|
1976
|
-
foldMessages(
|
|
1977
|
-
patchedPrefix,
|
|
1978
|
-
(type, buf) => prefixEntries.push({ type, ids: buf.map((m) => String(asSxin(m).id || "")) })
|
|
1979
|
-
);
|
|
1980
|
-
foldCache.pageCount = pageCount;
|
|
1981
|
-
foldCache.entries = prefixEntries;
|
|
1982
|
-
}
|
|
1983
|
-
const prefixById = new Map(patchedPrefix.map((m) => [String(asSxin(m).id || ""), m]));
|
|
1984
|
-
const folded = [];
|
|
1985
|
-
if (prefixEntries.every((e) => e.ids.every((id) => prefixById.has(id)))) {
|
|
1986
|
-
for (const e of prefixEntries) folded.push({ type: e.type, buf: e.ids.map((id) => prefixById.get(id)) });
|
|
1987
|
-
const streamFolded = [];
|
|
1988
|
-
foldMessages(patchedStream, (type, buf) => streamFolded.push({ type, buf }));
|
|
1989
|
-
const lastPrefix = folded[folded.length - 1];
|
|
1990
|
-
const firstStream = streamFolded[0];
|
|
1991
|
-
if (lastPrefix && firstStream && canMergeAtBoundary(lastPrefix, firstStream)) {
|
|
1992
|
-
lastPrefix.buf = [...lastPrefix.buf, ...firstStream.buf];
|
|
1993
|
-
streamFolded.shift();
|
|
1994
|
-
}
|
|
1995
|
-
folded.push(...streamFolded);
|
|
1996
|
-
} else {
|
|
1997
|
-
foldCache.pageCount = -1;
|
|
1998
|
-
foldCache.entries = [];
|
|
1999
|
-
foldMessages(patched, (type, buf) => folded.push({ type, buf }));
|
|
2000
|
-
}
|
|
2001
|
-
const groups = [];
|
|
2002
|
-
let epochActiveFrom = 0;
|
|
2003
|
-
if (streaming && !runIdFilter) {
|
|
2004
|
-
epochActiveFrom = -1;
|
|
2005
|
-
folded.forEach((entry, i) => {
|
|
2006
|
-
const id = String(asSxin(entry.buf[0]).id || "");
|
|
2007
|
-
if (entry.type === "human" && sourceOf(id) === "stream" && epochOf(id) === currentEpoch) epochActiveFrom = i;
|
|
2008
|
-
});
|
|
2009
|
-
if (epochActiveFrom < 0) epochActiveFrom = 0;
|
|
2010
|
-
}
|
|
2011
|
-
folded.forEach((entry, gi) => {
|
|
2012
|
-
const firstId = String(asSxin(entry.buf[0]).id || "");
|
|
2013
|
-
const firstSource = sourceOf(firstId);
|
|
2014
|
-
let groupRunId = messageRunId(entry.buf[0]);
|
|
2015
|
-
if (!groupRunId) {
|
|
2016
|
-
for (let i = 1; i < entry.buf.length; i++) {
|
|
2017
|
-
const rid = messageRunId(entry.buf[i]);
|
|
2018
|
-
if (rid) {
|
|
2019
|
-
groupRunId = rid;
|
|
2020
|
-
break;
|
|
2021
|
-
}
|
|
2008
|
+
applyState(state) {
|
|
2009
|
+
const messages = extractStateMessages(state);
|
|
2010
|
+
patches = extractSemanticPatchesFromMessages(messages);
|
|
2011
|
+
const citedIds = messages.filter((m) => String(m?.type || "") === "ai" && hasKbCitationMessage(m)).map((m) => String(m?.id || "")).filter(Boolean);
|
|
2012
|
+
return { patched: patches.size, citedIds };
|
|
2013
|
+
},
|
|
2014
|
+
getPatches() {
|
|
2015
|
+
return new Map(patches);
|
|
2016
|
+
},
|
|
2017
|
+
invalidate() {
|
|
2018
|
+
patches = /* @__PURE__ */ new Map();
|
|
2019
|
+
}
|
|
2020
|
+
};
|
|
2021
|
+
}
|
|
2022
|
+
function applySemanticPatches(messages, patches) {
|
|
2023
|
+
if (!patches.size || !messages.length) return messages;
|
|
2024
|
+
return messages.map((m) => {
|
|
2025
|
+
const id = String(m?.id || "").trim();
|
|
2026
|
+
const patch = id ? patches.get(id) : void 0;
|
|
2027
|
+
if (!patch) return m;
|
|
2028
|
+
let next = m;
|
|
2029
|
+
if (patch.content !== void 0 && String(next?.type || "") === "ai" && !hasKbCitationMessage(next)) {
|
|
2030
|
+
next = { ...next, content: patch.content };
|
|
2031
|
+
}
|
|
2032
|
+
const localKwargs = next?.additional_kwargs;
|
|
2033
|
+
if (patch.additional_kwargs && Object.keys(patch.additional_kwargs).length) {
|
|
2034
|
+
const merged = { ...localKwargs };
|
|
2035
|
+
let changed = false;
|
|
2036
|
+
for (const [k, v] of Object.entries(patch.additional_kwargs)) {
|
|
2037
|
+
if (merged[k] === void 0) {
|
|
2038
|
+
merged[k] = v;
|
|
2039
|
+
changed = true;
|
|
2022
2040
|
}
|
|
2023
2041
|
}
|
|
2024
|
-
|
|
2025
|
-
const inActiveZone = streaming ? runIdFilter ? groupRunId === runIdFilter : firstSource === "stream" && epochOf(firstId) === currentEpoch && gi >= epochActiveFrom : false;
|
|
2026
|
-
const status = inActiveZone ? "streaming" : "completed";
|
|
2027
|
-
const blockSource = firstSource === "page" ? "history" : "sse";
|
|
2028
|
-
let verSum = 0;
|
|
2029
|
-
for (const m of entry.buf) verSum += store.getEntity(String(asSxin(m).id || ""))?.ver ?? 0;
|
|
2030
|
-
const memoKey = `${firstId}|${status}|${blockSource}|${entry.buf.length}|${verSum}|${enrichments.citationVersion}`;
|
|
2031
|
-
const cached = groupMemo.get(memoKey);
|
|
2032
|
-
if (cached) {
|
|
2033
|
-
groups.push(cached);
|
|
2034
|
-
return;
|
|
2035
|
-
}
|
|
2036
|
-
let g;
|
|
2037
|
-
if (entry.type === "human") {
|
|
2038
|
-
g = buildHumanGroup(entry.buf, status);
|
|
2039
|
-
} else {
|
|
2040
|
-
g = buildAiGroup(entry.buf, { source: blockSource, isStreaming: status === "streaming" }, deps.twin);
|
|
2041
|
-
}
|
|
2042
|
-
if (groupMemo.size > 2e3) groupMemo.clear();
|
|
2043
|
-
groupMemo.set(memoKey, g);
|
|
2044
|
-
groups.push(g);
|
|
2045
|
-
});
|
|
2046
|
-
for (const g of groups) {
|
|
2047
|
-
if (g.type === "ai" && g.status === "streaming") {
|
|
2048
|
-
const aiMessages = g.rawMessages.filter((m) => String(asSxin(m).type || "").startsWith("ai"));
|
|
2049
|
-
const lastAi = aiMessages[aiMessages.length - 1];
|
|
2050
|
-
g.streamingText = lastAi ? extractAiContentFromMessage(lastAi) : "";
|
|
2051
|
-
}
|
|
2052
|
-
}
|
|
2053
|
-
const sourceGroups = groups;
|
|
2054
|
-
const decorateSteps = [
|
|
2055
|
-
// 第 1 步:补丁应用 + 乐观 extras 锚点落位
|
|
2056
|
-
(gs) => applyPatchesAndExtras(gs, state, runIdFilter),
|
|
2057
|
-
// 第 2 步:interrupt 审核块注入(去重记忆 interruptBlocks 为构建器公开职责)
|
|
2058
|
-
(gs) => withInterruptBlock(gs, {
|
|
2059
|
-
getInterrupt: deps.getInterrupt,
|
|
2060
|
-
respondedIds: deps.respondedIds,
|
|
2061
|
-
interruptBlocks
|
|
2062
|
-
}),
|
|
2063
|
-
// 第 3 步:澄清回答 / interrupt 响应标记装饰
|
|
2064
|
-
(gs) => decorateAnswers(gs, enrichments.answers, deps.respondedIds),
|
|
2065
|
-
// 第 4 步:隐藏「无可见内容」的 AI 空气泡
|
|
2066
|
-
filterInvisibleAiGroups
|
|
2067
|
-
];
|
|
2068
|
-
const merged = decorateSteps.reduce((gs, step) => step(gs), sourceGroups);
|
|
2069
|
-
return { groups: merged, sourceGroups };
|
|
2070
|
-
};
|
|
2071
|
-
return {
|
|
2072
|
-
derive,
|
|
2073
|
-
clearCache() {
|
|
2074
|
-
groupMemo.clear();
|
|
2075
|
-
foldCache.pageCount = -1;
|
|
2076
|
-
foldCache.entries = [];
|
|
2077
|
-
interruptBlocks.clear();
|
|
2078
|
-
}
|
|
2079
|
-
};
|
|
2080
|
-
}
|
|
2081
|
-
function canMergeAtBoundary(prefixLast, streamFirst) {
|
|
2082
|
-
if (prefixLast.type === "human" && streamFirst.type === "human") {
|
|
2083
|
-
return getHumanMessageBaseId(String(asSxin(streamFirst.buf[0]).id || "")) === getHumanMessageBaseId(String(asSxin(prefixLast.buf[0]).id || ""));
|
|
2084
|
-
}
|
|
2085
|
-
if (prefixLast.type === "ai" && streamFirst.type === "ai") {
|
|
2086
|
-
const mRunId = messageRunId(streamFirst.buf[0]);
|
|
2087
|
-
const groupRunId = messageRunId(prefixLast.buf[0]);
|
|
2088
|
-
return !(mRunId && groupRunId && mRunId !== groupRunId);
|
|
2089
|
-
}
|
|
2090
|
-
return false;
|
|
2091
|
-
}
|
|
2092
|
-
function createOptimisticHuman(text, options) {
|
|
2093
|
-
const optimisticId = genMessageId();
|
|
2094
|
-
return {
|
|
2095
|
-
id: optimisticId,
|
|
2096
|
-
type: "human",
|
|
2097
|
-
status: "completed",
|
|
2098
|
-
originMessageIds: [optimisticId],
|
|
2099
|
-
rawMessages: [
|
|
2100
|
-
{
|
|
2101
|
-
id: optimisticId,
|
|
2102
|
-
type: "human",
|
|
2103
|
-
name: "user-input",
|
|
2104
|
-
content: [{ type: "text", text }],
|
|
2105
|
-
additional_kwargs: options?.kwargs
|
|
2106
|
-
}
|
|
2107
|
-
],
|
|
2108
|
-
additionalKwargs: options?.kwargs,
|
|
2109
|
-
blocks: [],
|
|
2110
|
-
toolIds: [],
|
|
2111
|
-
tools: [],
|
|
2112
|
-
createdAt: Date.now()
|
|
2113
|
-
};
|
|
2114
|
-
}
|
|
2115
|
-
|
|
2116
|
-
// src/runtime/thread-runtime.ts
|
|
2117
|
-
var import_vue7 = require("vue");
|
|
2118
|
-
|
|
2119
|
-
// src/message/dict-merge.ts
|
|
2120
|
-
var MERGE_IGNORE_KEYS = ["index", "created", "timestamp"];
|
|
2121
|
-
var MERGE_RIGHT_WINS_KEYS = ["id", "name", "output_version", "model_provider"];
|
|
2122
|
-
function hasMergeableIndex(value) {
|
|
2123
|
-
if (typeof value !== "object" || value === null) return false;
|
|
2124
|
-
const idx = value.index;
|
|
2125
|
-
return typeof idx === "number" || typeof idx === "string";
|
|
2126
|
-
}
|
|
2127
|
-
function hasMergeableId(value) {
|
|
2128
|
-
if (typeof value !== "object" || value === null) return false;
|
|
2129
|
-
const id = value.id;
|
|
2130
|
-
return id != null && id !== "";
|
|
2131
|
-
}
|
|
2132
|
-
function findMergeTarget(merged, item) {
|
|
2133
|
-
if (!hasMergeableIndex(item) && !hasMergeableId(item)) return -1;
|
|
2134
|
-
return merged.findIndex((leftItem) => {
|
|
2135
|
-
const leftHasIndex = hasMergeableIndex(leftItem);
|
|
2136
|
-
const leftHasId = hasMergeableId(leftItem);
|
|
2137
|
-
const itemHasIndex = hasMergeableIndex(item);
|
|
2138
|
-
const itemHasId = hasMergeableId(item);
|
|
2139
|
-
if (itemHasIndex && leftHasIndex) {
|
|
2140
|
-
if (leftItem.index !== item.index) return false;
|
|
2141
|
-
if (leftHasId && itemHasId)
|
|
2142
|
-
return leftItem.id === item.id;
|
|
2143
|
-
return true;
|
|
2144
|
-
}
|
|
2145
|
-
if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {
|
|
2146
|
-
return leftItem.id === item.id;
|
|
2147
|
-
}
|
|
2148
|
-
return false;
|
|
2149
|
-
});
|
|
2150
|
-
}
|
|
2151
|
-
function mergeStringField(key, left, right) {
|
|
2152
|
-
if (key === "type") return left;
|
|
2153
|
-
if (MERGE_RIGHT_WINS_KEYS.includes(key)) return right || left;
|
|
2154
|
-
if (MERGE_IGNORE_KEYS.includes(key)) return left;
|
|
2155
|
-
return left + right;
|
|
2156
|
-
}
|
|
2157
|
-
function mergeNumberField(key, left, right) {
|
|
2158
|
-
return MERGE_IGNORE_KEYS.includes(key) ? left : left + right;
|
|
2159
|
-
}
|
|
2160
|
-
function mergeDicts(left, right) {
|
|
2161
|
-
if (left == null) return right;
|
|
2162
|
-
if (right == null) return left;
|
|
2163
|
-
if (Array.isArray(left) && Array.isArray(right)) return mergeLists(left, right);
|
|
2164
|
-
if (typeof left === "string" && typeof right === "string") return left + right;
|
|
2165
|
-
if (typeof left === "number" && typeof right === "number") return left + right;
|
|
2166
|
-
if (typeof left === "object" && typeof right === "object") {
|
|
2167
|
-
const merged = { ...left };
|
|
2168
|
-
for (const [key, value] of Object.entries(right)) {
|
|
2169
|
-
const l = merged[key];
|
|
2170
|
-
if (l == null) {
|
|
2171
|
-
merged[key] = value;
|
|
2172
|
-
} else if (value == null) {
|
|
2173
|
-
continue;
|
|
2174
|
-
} else if (typeof l === "string" && typeof value === "string") {
|
|
2175
|
-
merged[key] = mergeStringField(key, l, value);
|
|
2176
|
-
} else if (typeof l === "number" && typeof value === "number") {
|
|
2177
|
-
merged[key] = mergeNumberField(key, l, value);
|
|
2178
|
-
} else if (Array.isArray(l) && Array.isArray(value)) {
|
|
2179
|
-
merged[key] = mergeLists(l, value);
|
|
2180
|
-
} else if (typeof l === "object" && typeof value === "object") {
|
|
2181
|
-
merged[key] = mergeDicts(l, value);
|
|
2182
|
-
} else {
|
|
2183
|
-
merged[key] = value;
|
|
2184
|
-
}
|
|
2185
|
-
}
|
|
2186
|
-
return merged;
|
|
2187
|
-
}
|
|
2188
|
-
return right;
|
|
2189
|
-
}
|
|
2190
|
-
function mergeLists(left, right) {
|
|
2191
|
-
const merged = [...left];
|
|
2192
|
-
for (const item of right) {
|
|
2193
|
-
const target = findMergeTarget(merged, item);
|
|
2194
|
-
if (target !== -1) {
|
|
2195
|
-
merged[target] = mergeDicts(merged[target], item);
|
|
2196
|
-
} else if (typeof item === "object" && item !== null && "text" in item && item.text === "") {
|
|
2197
|
-
continue;
|
|
2198
|
-
} else {
|
|
2199
|
-
merged.push(item);
|
|
2200
|
-
}
|
|
2201
|
-
}
|
|
2202
|
-
return merged;
|
|
2203
|
-
}
|
|
2204
|
-
function mergeContent(left, right) {
|
|
2205
|
-
if (left == null) return right;
|
|
2206
|
-
if (right == null) return left;
|
|
2207
|
-
if (typeof left === "string" && typeof right === "string") return left + right;
|
|
2208
|
-
const leftArr = Array.isArray(left) ? left : [left];
|
|
2209
|
-
const rightArr = Array.isArray(right) ? right : [right];
|
|
2210
|
-
return mergeLists(leftArr, rightArr);
|
|
2211
|
-
}
|
|
2212
|
-
function parsePartialJson(text) {
|
|
2213
|
-
const tryParse = (s) => {
|
|
2214
|
-
try {
|
|
2215
|
-
return JSON.parse(s);
|
|
2216
|
-
} catch {
|
|
2217
|
-
return void 0;
|
|
2218
|
-
}
|
|
2219
|
-
};
|
|
2220
|
-
const direct = tryParse(text);
|
|
2221
|
-
if (direct !== void 0) return direct;
|
|
2222
|
-
let fixed = text;
|
|
2223
|
-
let inStr = false;
|
|
2224
|
-
let escaped = false;
|
|
2225
|
-
for (const ch of fixed) {
|
|
2226
|
-
if (escaped) {
|
|
2227
|
-
escaped = false;
|
|
2228
|
-
continue;
|
|
2229
|
-
}
|
|
2230
|
-
if (ch === "\\") {
|
|
2231
|
-
escaped = true;
|
|
2232
|
-
continue;
|
|
2233
|
-
}
|
|
2234
|
-
if (ch === '"') inStr = !inStr;
|
|
2235
|
-
}
|
|
2236
|
-
if (inStr) fixed += '"';
|
|
2237
|
-
const closers = [];
|
|
2238
|
-
for (const ch of fixed) {
|
|
2239
|
-
if (ch === "{") closers.push("}");
|
|
2240
|
-
else if (ch === "[") closers.push("]");
|
|
2241
|
-
else if (ch === "}" || ch === "]") closers.pop();
|
|
2242
|
-
}
|
|
2243
|
-
fixed += closers.reverse().join("");
|
|
2244
|
-
const repaired = tryParse(fixed);
|
|
2245
|
-
return repaired === void 0 ? null : repaired;
|
|
2246
|
-
}
|
|
2247
|
-
function collapseToolCallChunks(chunks) {
|
|
2248
|
-
const groups = [];
|
|
2249
|
-
for (const chunk of chunks) {
|
|
2250
|
-
const matched = groups.findIndex((group) => {
|
|
2251
|
-
const match = group[0];
|
|
2252
|
-
if (chunk?.id && chunk?.index !== void 0) return chunk.id === match.id && chunk.index === match.index;
|
|
2253
|
-
if (chunk?.id) return chunk.id === match.id;
|
|
2254
|
-
if (chunk?.index !== void 0) return chunk.index === match.index;
|
|
2255
|
-
return false;
|
|
2256
|
-
});
|
|
2257
|
-
if (matched !== -1) groups[matched].push(chunk);
|
|
2258
|
-
else groups.push([chunk]);
|
|
2259
|
-
}
|
|
2260
|
-
const toolCalls = [];
|
|
2261
|
-
const invalidToolCalls = [];
|
|
2262
|
-
for (const group of groups) {
|
|
2263
|
-
const name = group[0]?.name ?? "";
|
|
2264
|
-
const joinedArgs = group.map((c) => c?.args || "").join("");
|
|
2265
|
-
const argsStr = joinedArgs.trim().length ? joinedArgs.trim() : "{}";
|
|
2266
|
-
const id = group.find((c) => c?.id)?.id ?? group[0]?.id;
|
|
2267
|
-
const parsed = parsePartialJson(argsStr);
|
|
2268
|
-
if (!id || parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
2269
|
-
invalidToolCalls.push({ name, args: argsStr, id, error: "Malformed args.", type: "invalid_tool_call" });
|
|
2270
|
-
} else {
|
|
2271
|
-
toolCalls.push({ name, args: parsed, id, type: "tool_call" });
|
|
2042
|
+
if (changed) next = { ...next, additional_kwargs: merged };
|
|
2272
2043
|
}
|
|
2273
|
-
|
|
2274
|
-
return { tool_calls: toolCalls, invalid_tool_calls: invalidToolCalls };
|
|
2275
|
-
}
|
|
2276
|
-
function extractToolCallsFromContent(content) {
|
|
2277
|
-
if (!Array.isArray(content)) return [];
|
|
2278
|
-
return content.flatMap((block) => {
|
|
2279
|
-
if (block == null || typeof block !== "object") return [];
|
|
2280
|
-
const record = block;
|
|
2281
|
-
if (record.type !== "tool_call" && record.type !== "tool_use") return [];
|
|
2282
|
-
const rawArgs = record.args ?? record.input;
|
|
2283
|
-
let args = {};
|
|
2284
|
-
if (rawArgs != null && typeof rawArgs === "object" && !Array.isArray(rawArgs)) args = rawArgs;
|
|
2285
|
-
else if (typeof rawArgs === "string" && rawArgs.length > 0) {
|
|
2286
|
-
const parsed = parsePartialJson(rawArgs);
|
|
2287
|
-
if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) args = parsed;
|
|
2288
|
-
}
|
|
2289
|
-
return [{ id: record.id ?? "", name: record.name ?? "", args, type: "tool_call" }];
|
|
2044
|
+
return next;
|
|
2290
2045
|
});
|
|
2291
2046
|
}
|
|
2292
|
-
function mergeMessageDicts(prev, next) {
|
|
2293
|
-
const merged = { ...prev };
|
|
2294
|
-
for (const [key, value] of Object.entries(next)) {
|
|
2295
|
-
if (key === "type") {
|
|
2296
|
-
if (merged.type == null) merged.type = value;
|
|
2297
|
-
continue;
|
|
2298
|
-
}
|
|
2299
|
-
if (MERGE_RIGHT_WINS_KEYS.includes(key)) {
|
|
2300
|
-
if (value != null && value !== "") merged[key] = value;
|
|
2301
|
-
continue;
|
|
2302
|
-
}
|
|
2303
|
-
if (key === "content") {
|
|
2304
|
-
merged.content = mergeContent(prev.content, value);
|
|
2305
|
-
} else if (key === "tool_call_chunks") {
|
|
2306
|
-
const prevChunks = Array.isArray(prev.tool_call_chunks) ? prev.tool_call_chunks : [];
|
|
2307
|
-
const nextChunks = Array.isArray(value) ? value : [];
|
|
2308
|
-
const chunks = mergeLists(prevChunks, nextChunks);
|
|
2309
|
-
merged.tool_call_chunks = chunks;
|
|
2310
|
-
const collapsed = collapseToolCallChunks(chunks);
|
|
2311
|
-
merged.tool_calls = collapsed.tool_calls;
|
|
2312
|
-
merged.invalid_tool_calls = collapsed.invalid_tool_calls;
|
|
2313
|
-
} else {
|
|
2314
|
-
merged[key] = mergeDicts(prev[key], value);
|
|
2315
|
-
}
|
|
2316
|
-
}
|
|
2317
|
-
if (!Array.isArray(merged.tool_calls) || merged.tool_calls.length === 0) {
|
|
2318
|
-
const extracted = extractToolCallsFromContent(merged.content);
|
|
2319
|
-
if (extracted.length > 0) merged.tool_calls = extracted;
|
|
2320
|
-
}
|
|
2321
|
-
return merged;
|
|
2322
|
-
}
|
|
2323
2047
|
|
|
2324
|
-
// src/
|
|
2325
|
-
|
|
2326
|
-
const rawType = String(raw.type || "");
|
|
2327
|
-
if (rawType === "RemoveMessage") return { ...raw, type: "remove" };
|
|
2328
|
-
return raw;
|
|
2329
|
-
}
|
|
2330
|
-
function stampRunId(msg, streamRunId) {
|
|
2331
|
-
if (String(msg.runId || "").trim()) return msg;
|
|
2332
|
-
const kwargsRunId = String(msg.additional_kwargs?.run_id || "").trim();
|
|
2333
|
-
const rid = kwargsRunId || String(streamRunId || "").trim();
|
|
2334
|
-
if (!rid) return msg;
|
|
2335
|
-
return { ...msg, runId: rid };
|
|
2336
|
-
}
|
|
2337
|
-
function createChunkBuffer(options) {
|
|
2338
|
-
const schedule = options.schedule ?? ((fn) => setTimeout(fn, 0));
|
|
2339
|
-
const pending = /* @__PURE__ */ new Map();
|
|
2340
|
-
const accumulated = /* @__PURE__ */ new Map();
|
|
2341
|
-
let order = [];
|
|
2342
|
-
const dirty = /* @__PURE__ */ new Set();
|
|
2343
|
-
let scheduled = false;
|
|
2344
|
-
let timer = null;
|
|
2345
|
-
let streamRunId;
|
|
2346
|
-
const cancelSchedule = () => {
|
|
2347
|
-
scheduled = false;
|
|
2348
|
-
if (timer !== null) clearTimeout(timer);
|
|
2349
|
-
timer = null;
|
|
2350
|
-
};
|
|
2351
|
-
const scheduleFlush = () => {
|
|
2352
|
-
if (scheduled) return;
|
|
2353
|
-
scheduled = true;
|
|
2354
|
-
timer = schedule(() => {
|
|
2355
|
-
scheduled = false;
|
|
2356
|
-
timer = null;
|
|
2357
|
-
flush();
|
|
2358
|
-
});
|
|
2359
|
-
};
|
|
2360
|
-
function flush() {
|
|
2361
|
-
if (!order.length) return;
|
|
2362
|
-
const instructions = [];
|
|
2363
|
-
for (const id of order) {
|
|
2364
|
-
const entry = pending.get(id);
|
|
2365
|
-
if (!entry) continue;
|
|
2366
|
-
if (entry.isClear) {
|
|
2367
|
-
instructions.push({ kind: "clear" });
|
|
2368
|
-
accumulated.clear();
|
|
2369
|
-
continue;
|
|
2370
|
-
}
|
|
2371
|
-
if (entry.isRemove) {
|
|
2372
|
-
instructions.push({ kind: "remove", id });
|
|
2373
|
-
accumulated.delete(id);
|
|
2374
|
-
continue;
|
|
2375
|
-
}
|
|
2376
|
-
const base = accumulated.get(id);
|
|
2377
|
-
const merged = base ? entry.parts.reduce((acc, c) => mergeMessageDicts(acc, c), base) : entry.parts.reduce(mergeMessageDicts);
|
|
2378
|
-
accumulated.set(id, merged);
|
|
2379
|
-
instructions.push({ kind: "upsert", message: stampRunId(merged, streamRunId) });
|
|
2380
|
-
}
|
|
2381
|
-
pending.clear();
|
|
2382
|
-
order = [];
|
|
2383
|
-
dirty.clear();
|
|
2384
|
-
if (instructions.length) options.emit(instructions);
|
|
2385
|
-
}
|
|
2386
|
-
return {
|
|
2387
|
-
add(serialized) {
|
|
2388
|
-
if (!serialized || typeof serialized !== "object") return;
|
|
2389
|
-
const raw = serialized;
|
|
2390
|
-
const rawType = String(raw.type || "");
|
|
2391
|
-
const entry = normalizeEntry(raw);
|
|
2392
|
-
const type = String(entry.type || "");
|
|
2393
|
-
const id = String(entry.id || "").trim();
|
|
2394
|
-
if (!id) return;
|
|
2395
|
-
if (type === "remove") {
|
|
2396
|
-
if (id === "__remove_all__") {
|
|
2397
|
-
pending.set(id, { parts: [], isClear: true });
|
|
2398
|
-
} else {
|
|
2399
|
-
pending.set(id, { parts: [], isRemove: true });
|
|
2400
|
-
}
|
|
2401
|
-
if (!dirty.has(id)) {
|
|
2402
|
-
dirty.add(id);
|
|
2403
|
-
order.push(id);
|
|
2404
|
-
}
|
|
2405
|
-
scheduleFlush();
|
|
2406
|
-
return;
|
|
2407
|
-
}
|
|
2408
|
-
const isChunk = rawType.endsWith("MessageChunk");
|
|
2409
|
-
const existing = pending.get(id);
|
|
2410
|
-
if (!existing || existing.isRemove) {
|
|
2411
|
-
pending.set(id, { parts: [entry] });
|
|
2412
|
-
} else if (!isChunk) {
|
|
2413
|
-
existing.parts = [entry];
|
|
2414
|
-
} else {
|
|
2415
|
-
existing.parts.push(entry);
|
|
2416
|
-
}
|
|
2417
|
-
if (!dirty.has(id)) {
|
|
2418
|
-
dirty.add(id);
|
|
2419
|
-
order.push(id);
|
|
2420
|
-
}
|
|
2421
|
-
scheduleFlush();
|
|
2422
|
-
},
|
|
2423
|
-
noteStreamRunId(runId) {
|
|
2424
|
-
const trimmed = String(runId || "").trim();
|
|
2425
|
-
if (trimmed) streamRunId = trimmed;
|
|
2426
|
-
},
|
|
2427
|
-
reset() {
|
|
2428
|
-
cancelSchedule();
|
|
2429
|
-
pending.clear();
|
|
2430
|
-
order = [];
|
|
2431
|
-
dirty.clear();
|
|
2432
|
-
accumulated.clear();
|
|
2433
|
-
streamRunId = void 0;
|
|
2434
|
-
},
|
|
2435
|
-
flush,
|
|
2436
|
-
dispose() {
|
|
2437
|
-
cancelSchedule();
|
|
2438
|
-
pending.clear();
|
|
2439
|
-
order = [];
|
|
2440
|
-
dirty.clear();
|
|
2441
|
-
accumulated.clear();
|
|
2442
|
-
}
|
|
2443
|
-
};
|
|
2444
|
-
}
|
|
2048
|
+
// src/runtime/thread-runtime.ts
|
|
2049
|
+
var import_vue4 = require("vue");
|
|
2445
2050
|
|
|
2446
2051
|
// src/runtime/history-pager.ts
|
|
2447
|
-
var
|
|
2052
|
+
var import_vue = require("vue");
|
|
2448
2053
|
function createHistoryPager(options) {
|
|
2449
2054
|
const { threadId, transport, firstPage } = options;
|
|
2450
2055
|
let cursor = firstPage.nextBeforeSeq;
|
|
2451
|
-
const hasMoreRef = (0,
|
|
2452
|
-
const loading = (0,
|
|
2056
|
+
const hasMoreRef = (0, import_vue.ref)(Boolean(firstPage.hasMore) && firstPage.nextBeforeSeq !== void 0);
|
|
2057
|
+
const loading = (0, import_vue.ref)(false);
|
|
2453
2058
|
const loadOlder = async () => {
|
|
2454
2059
|
if (loading.value) return hasMoreRef.value;
|
|
2455
2060
|
if (!hasMoreRef.value || cursor === void 0) {
|
|
@@ -2460,7 +2065,7 @@ function createHistoryPager(options) {
|
|
|
2460
2065
|
try {
|
|
2461
2066
|
const page = await transport.fetchMessagesPage(threadId, { beforeSeq: cursor });
|
|
2462
2067
|
const pageMessages = runMessagesToMessages(page.messages);
|
|
2463
|
-
options.emitChanges(
|
|
2068
|
+
options.emitChanges();
|
|
2464
2069
|
cursor = page.nextBeforeSeq;
|
|
2465
2070
|
hasMoreRef.value = Boolean(page.hasMore) && page.nextBeforeSeq !== void 0;
|
|
2466
2071
|
options.onPageLoaded?.(page);
|
|
@@ -2469,30 +2074,41 @@ function createHistoryPager(options) {
|
|
|
2469
2074
|
loading.value = false;
|
|
2470
2075
|
}
|
|
2471
2076
|
};
|
|
2472
|
-
return { loadOlder, hasMore: (0,
|
|
2077
|
+
return { loadOlder, hasMore: (0, import_vue.computed)(() => hasMoreRef.value), loading };
|
|
2473
2078
|
}
|
|
2474
2079
|
|
|
2475
2080
|
// src/runtime/runtime-bootstrap.ts
|
|
2081
|
+
function patchRows(rows, patches) {
|
|
2082
|
+
if (!patches.size || !rows.length) return rows;
|
|
2083
|
+
return rows.map((row) => {
|
|
2084
|
+
const id = String(row.content?.id || "").trim();
|
|
2085
|
+
const patch = id ? patches.get(id) : void 0;
|
|
2086
|
+
if (!patch) return row;
|
|
2087
|
+
const patched = applySemanticPatches([row.content], patches)[0];
|
|
2088
|
+
return patched === row.content ? row : { ...row, content: patched };
|
|
2089
|
+
});
|
|
2090
|
+
}
|
|
2476
2091
|
async function bootstrapRuntime(deps) {
|
|
2477
2092
|
const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
|
|
2478
|
-
deps.
|
|
2479
|
-
deps.valuesChannel.applyThreadState(fetched.threadState);
|
|
2480
|
-
deps.enrichments.applyFromStateMessages(extractStateMessages(fetched.threadState));
|
|
2093
|
+
deps.overlay.applyState(fetched.threadState);
|
|
2481
2094
|
deps.runs.fillFromRunsList(fetched.runsList ?? []);
|
|
2482
2095
|
deps.runs.enrichFromPage(fetched.messagesPage);
|
|
2483
|
-
|
|
2484
|
-
|
|
2096
|
+
deps.runsListMeta.value = (fetched.runsList ?? []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
|
|
2097
|
+
deps.rowsStore.setAll(patchRows(fetched.messagesPage.messages, deps.overlay.getPatches()));
|
|
2485
2098
|
deps.setPager(
|
|
2486
2099
|
createHistoryPager({
|
|
2487
2100
|
threadId: deps.threadId,
|
|
2488
2101
|
transport: deps.transport,
|
|
2489
2102
|
firstPage: fetched.messagesPage,
|
|
2490
|
-
onPageLoaded: (page) =>
|
|
2491
|
-
|
|
2103
|
+
onPageLoaded: (page) => {
|
|
2104
|
+
deps.runs.enrichFromPage(page);
|
|
2105
|
+
deps.rowsStore.prepend(page.messages);
|
|
2106
|
+
},
|
|
2107
|
+
emitChanges: () => {
|
|
2108
|
+
}
|
|
2492
2109
|
})
|
|
2493
2110
|
);
|
|
2494
2111
|
await deps.refreshTokenUsage();
|
|
2495
|
-
deps.setChunkBuffer(createChunkBuffer({ emit: (ins) => deps.store.applyInstructions(ins) }));
|
|
2496
2112
|
const finalize = () => finalizeAfterStream(deps);
|
|
2497
2113
|
const afterFinish = () => afterStreamFinish(deps);
|
|
2498
2114
|
deps.streamRef.value = deps.transport.createStream({
|
|
@@ -2501,7 +2117,9 @@ async function bootstrapRuntime(deps) {
|
|
|
2501
2117
|
onCreated: (run) => deps.markStreamRun(run?.run_id),
|
|
2502
2118
|
onMetadataEvent: (data) => deps.markStreamRun(data?.run_id),
|
|
2503
2119
|
onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
|
|
2504
|
-
onMessageTupleEvent: (
|
|
2120
|
+
onMessageTupleEvent: () => {
|
|
2121
|
+
},
|
|
2122
|
+
onSnapshotMessages: (messages) => deps.applyLiveSnapshot(messages),
|
|
2505
2123
|
onStreamStart: deps.onStreamStart,
|
|
2506
2124
|
onStreamEnd: finalize,
|
|
2507
2125
|
onFinish: afterFinish,
|
|
@@ -2510,50 +2128,45 @@ async function bootstrapRuntime(deps) {
|
|
|
2510
2128
|
deps.setInitialized();
|
|
2511
2129
|
}
|
|
2512
2130
|
function finalizeAfterStream(deps) {
|
|
2513
|
-
deps.
|
|
2514
|
-
deps.
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
function buildValuesReplaceInstructions(store, streamMessages) {
|
|
2520
|
-
const instructions = [];
|
|
2521
|
-
for (const msg of streamMessages) {
|
|
2522
|
-
const id = String(msg?.id || "").trim();
|
|
2523
|
-
if (!id) continue;
|
|
2524
|
-
const existing = store.getEntity(id);
|
|
2525
|
-
if (!existing) continue;
|
|
2526
|
-
if (existing.source !== "stream" || existing.epoch !== store.streamEpoch) continue;
|
|
2527
|
-
const runId = String(existing.msg?.runId || existing.msg?.additional_kwargs?.run_id || "").trim();
|
|
2528
|
-
const next = runId ? { ...msg, runId } : msg;
|
|
2529
|
-
instructions.push({ kind: "upsert", message: next });
|
|
2530
|
-
}
|
|
2531
|
-
return instructions;
|
|
2131
|
+
deps.onStreamSettled();
|
|
2132
|
+
deps.runs.backfillCurrentRunMetadata(
|
|
2133
|
+
() => deps.valuesChannel.getStreamMessages().map((m) => ({ ...m, runId: deps.runs.currentRunId.value }))
|
|
2134
|
+
);
|
|
2135
|
+
const patches = extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages());
|
|
2136
|
+
deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, patches));
|
|
2532
2137
|
}
|
|
2533
2138
|
async function afterStreamFinish(deps) {
|
|
2534
|
-
await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
|
|
2139
|
+
await Promise.all([deps.runs.refreshRuns(), refreshRunsMeta(deps), deps.refreshTokenUsage()]);
|
|
2535
2140
|
await reconcileWithPage(deps);
|
|
2536
|
-
await
|
|
2141
|
+
await refreshSemanticLayer(deps);
|
|
2537
2142
|
}
|
|
2538
|
-
async function
|
|
2143
|
+
async function refreshRunsMeta(deps) {
|
|
2539
2144
|
try {
|
|
2540
|
-
const
|
|
2541
|
-
|
|
2542
|
-
if (messages.length) {
|
|
2543
|
-
deps.store.applyInstructions(messages.map((message) => ({ kind: "upsert", message, source: "page" })));
|
|
2544
|
-
}
|
|
2145
|
+
const list = await deps.transport.listRuns(deps.threadId, 20);
|
|
2146
|
+
deps.runsListMeta.value = (Array.isArray(list) ? list : []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
|
|
2545
2147
|
} catch (e) {
|
|
2546
|
-
console.warn("[runtime] \
|
|
2148
|
+
console.warn("[runtime] runs.list \u5237\u65B0\u5931\u8D25", e);
|
|
2547
2149
|
}
|
|
2548
2150
|
}
|
|
2549
|
-
async function
|
|
2550
|
-
if (deps.valuesChannel.getStreamMessages().length > 0) return;
|
|
2151
|
+
async function refreshSemanticLayer(deps) {
|
|
2551
2152
|
try {
|
|
2552
2153
|
const state = await deps.transport.fetchThreadState(deps.threadId);
|
|
2553
2154
|
if (!state) return;
|
|
2554
|
-
deps.
|
|
2155
|
+
const semantic = deps.overlay.applyState(state);
|
|
2156
|
+
deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, deps.overlay.getPatches()));
|
|
2157
|
+
if (semantic.patched) {
|
|
2158
|
+
console.debug(`[runtime] \u8BED\u4E49\u5C42\u5237\u65B0 patched=${semantic.patched} cited=${semantic.citedIds.length}`);
|
|
2159
|
+
}
|
|
2160
|
+
} catch (e) {
|
|
2161
|
+
console.warn("[runtime] \u8BED\u4E49\u5C42\u5237\u65B0\u5931\u8D25", e);
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
async function reconcileWithPage(deps) {
|
|
2165
|
+
try {
|
|
2166
|
+
const page = await deps.transport.fetchMessagesPage(deps.threadId);
|
|
2167
|
+
if (page.messages.length) deps.rowsStore.mergeLatest(page.messages);
|
|
2555
2168
|
} catch (e) {
|
|
2556
|
-
console.warn("[runtime]
|
|
2169
|
+
console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
|
|
2557
2170
|
}
|
|
2558
2171
|
}
|
|
2559
2172
|
async function runRuntimeInit(deps, hooks) {
|
|
@@ -2565,276 +2178,125 @@ async function runRuntimeInit(deps, hooks) {
|
|
|
2565
2178
|
}
|
|
2566
2179
|
}
|
|
2567
2180
|
|
|
2568
|
-
// src/
|
|
2569
|
-
|
|
2570
|
-
var import_ui = require("@langchain/langgraph-sdk/ui");
|
|
2571
|
-
|
|
2572
|
-
// src/protocol/interrupt-reconcile.ts
|
|
2573
|
-
function reconcileInterrupts(prevValues, nextValues, firstEvent) {
|
|
2574
|
-
let base = prevValues;
|
|
2575
|
-
if (firstEvent && base && "__interrupt__" in base) {
|
|
2576
|
-
const { __interrupt__: _dropped, ...rest } = base;
|
|
2577
|
-
base = rest;
|
|
2578
|
-
}
|
|
2579
|
-
if (nextValues && typeof nextValues === "object" && "__interrupt__" in nextValues) {
|
|
2580
|
-
let interrupts = nextValues.__interrupt__;
|
|
2581
|
-
const prevInterrupts = base?.__interrupt__;
|
|
2582
|
-
if (Array.isArray(interrupts) && interrupts.length > 0 && Array.isArray(prevInterrupts)) {
|
|
2583
|
-
const merged = [...prevInterrupts];
|
|
2584
|
-
const existingIds = new Set(merged.map((i) => i?.id).filter((id) => id != null));
|
|
2585
|
-
for (const interrupt of interrupts) {
|
|
2586
|
-
const id = interrupt?.id;
|
|
2587
|
-
if (id != null) {
|
|
2588
|
-
if (existingIds.has(id)) continue;
|
|
2589
|
-
existingIds.add(id);
|
|
2590
|
-
}
|
|
2591
|
-
merged.push(interrupt);
|
|
2592
|
-
}
|
|
2593
|
-
interrupts = merged;
|
|
2594
|
-
}
|
|
2595
|
-
return { ...base, __interrupt__: interrupts };
|
|
2596
|
-
}
|
|
2597
|
-
if (nextValues && typeof nextValues === "object") {
|
|
2598
|
-
if (base && "__interrupt__" in base && Array.isArray(base.__interrupt__)) {
|
|
2599
|
-
return { ...nextValues, __interrupt__: base.__interrupt__ };
|
|
2600
|
-
}
|
|
2601
|
-
return nextValues;
|
|
2602
|
-
}
|
|
2603
|
-
return nextValues ?? {};
|
|
2604
|
-
}
|
|
2605
|
-
|
|
2606
|
-
// src/protocol/values-channel.ts
|
|
2607
|
-
function createValuesChannel(options = {}) {
|
|
2608
|
-
const valuesRef = (0, import_vue4.shallowRef)({});
|
|
2609
|
-
const threadStateRef = (0, import_vue4.shallowRef)(void 0);
|
|
2610
|
-
let firstEvent = true;
|
|
2611
|
-
let lastTitle = "";
|
|
2612
|
-
let latestStreamMessages = [];
|
|
2613
|
-
const readStateMessages = () => {
|
|
2614
|
-
const msgs = threadStateRef.value?.values?.messages;
|
|
2615
|
-
return Array.isArray(msgs) ? [...msgs] : [];
|
|
2616
|
-
};
|
|
2617
|
-
const readStreamMessages = () => [...latestStreamMessages];
|
|
2181
|
+
// src/runtime/runtime-stream-actions.ts
|
|
2182
|
+
function createStreamActions(ctx) {
|
|
2618
2183
|
return {
|
|
2619
|
-
|
|
2620
|
-
|
|
2184
|
+
submit(text, submitOptions) {
|
|
2185
|
+
const handle = ctx.getHandle();
|
|
2186
|
+
if (!handle) return;
|
|
2187
|
+
ctx.beginStream();
|
|
2188
|
+
const kwargs = submitOptions?.kwargs ?? void 0;
|
|
2189
|
+
ctx.createPendingRun(text, "message", kwargs);
|
|
2190
|
+
const humanMessage = { type: "human", content: [{ type: "text", text }] };
|
|
2191
|
+
humanMessage.additional_kwargs = submitOptions?.kwargs;
|
|
2192
|
+
handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
|
|
2621
2193
|
},
|
|
2622
|
-
|
|
2623
|
-
|
|
2194
|
+
async joinStream(runId, lastEventId) {
|
|
2195
|
+
const handle = ctx.getHandle();
|
|
2196
|
+
if (!handle) return;
|
|
2197
|
+
ctx.beginStream();
|
|
2198
|
+
ctx.markStreamRun(runId);
|
|
2199
|
+
await handle.joinStream(runId, lastEventId ?? "-1");
|
|
2624
2200
|
},
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
latestStreamMessages = [];
|
|
2201
|
+
stop() {
|
|
2202
|
+
void ctx.options.transport.cancelRun(ctx.options.threadId, ctx.runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
|
|
2203
|
+
ctx.getHandle()?.stop();
|
|
2629
2204
|
},
|
|
2630
|
-
|
|
2631
|
-
const
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2205
|
+
async resumeInterrupt(decisions) {
|
|
2206
|
+
const it = ctx.getInterrupt();
|
|
2207
|
+
const interruptId = String(it?.id || "");
|
|
2208
|
+
if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
|
|
2209
|
+
const handle = ctx.getHandle();
|
|
2210
|
+
if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
|
|
2211
|
+
ctx.markResponded(interruptId);
|
|
2212
|
+
ctx.beginStream();
|
|
2213
|
+
const payload = parseHitlPayload(it.value);
|
|
2214
|
+
ctx.createPendingRun(payload ? "\u5DF2\u63D0\u4EA4\u5BA1\u6279\u51B3\u7B56" : "\u5DF2\u63D0\u4EA4\u56DE\u7B54", payload ? "hitl" : "clarification");
|
|
2215
|
+
try {
|
|
2216
|
+
await handle.resumeInterrupt(decisions);
|
|
2217
|
+
} catch (e) {
|
|
2218
|
+
ctx.unmarkResponded(interruptId);
|
|
2219
|
+
throw e;
|
|
2639
2220
|
}
|
|
2640
2221
|
},
|
|
2641
|
-
|
|
2642
|
-
return
|
|
2643
|
-
|
|
2644
|
-
getStateMessages: readStateMessages,
|
|
2645
|
-
getStreamMessages: readStreamMessages,
|
|
2646
|
-
getInterrupt({ isLoading, error }) {
|
|
2647
|
-
return (0, import_ui.extractInterrupts)(valuesRef.value, {
|
|
2648
|
-
isLoading,
|
|
2649
|
-
threadState: threadStateRef.value,
|
|
2650
|
-
error
|
|
2651
|
-
});
|
|
2222
|
+
async loadOlderMessages() {
|
|
2223
|
+
if (!ctx.getPager()) return false;
|
|
2224
|
+
return ctx.getPager().loadOlder();
|
|
2652
2225
|
}
|
|
2653
2226
|
};
|
|
2654
2227
|
}
|
|
2655
2228
|
|
|
2656
|
-
// src/
|
|
2657
|
-
var
|
|
2658
|
-
function
|
|
2659
|
-
const
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
for (const ins of instructions) {
|
|
2686
|
-
switch (ins.kind) {
|
|
2687
|
-
case "upsert": {
|
|
2688
|
-
const id = String(ins.message.id || "").trim();
|
|
2689
|
-
if (!id) break;
|
|
2690
|
-
const message = normalizeMessageType(ins.message);
|
|
2691
|
-
const existing = entities.get(id);
|
|
2692
|
-
if (existing) {
|
|
2693
|
-
existing.msg = message;
|
|
2694
|
-
existing.ver++;
|
|
2695
|
-
if (ins.source === "page") {
|
|
2696
|
-
existing.source = "page";
|
|
2697
|
-
} else {
|
|
2698
|
-
existing.source = "stream";
|
|
2699
|
-
existing.epoch = streamEpoch;
|
|
2700
|
-
}
|
|
2701
|
-
} else {
|
|
2702
|
-
entities.set(id, {
|
|
2703
|
-
msg: message,
|
|
2704
|
-
source: ins.source === "page" ? "page" : "stream",
|
|
2705
|
-
epoch: streamEpoch,
|
|
2706
|
-
ver: 1
|
|
2707
|
-
});
|
|
2708
|
-
if (ins.source === "page") {
|
|
2709
|
-
order.splice(lastPageIndex() + 1, 0, id);
|
|
2710
|
-
} else {
|
|
2711
|
-
order.push(id);
|
|
2712
|
-
}
|
|
2713
|
-
}
|
|
2714
|
-
touched = true;
|
|
2715
|
-
break;
|
|
2716
|
-
}
|
|
2717
|
-
case "remove": {
|
|
2718
|
-
if (!entities.has(ins.id)) break;
|
|
2719
|
-
const idx = order.indexOf(ins.id);
|
|
2720
|
-
if (idx >= 0) order.splice(idx, 1);
|
|
2721
|
-
entities.delete(ins.id);
|
|
2722
|
-
touched = true;
|
|
2723
|
-
break;
|
|
2724
|
-
}
|
|
2725
|
-
case "clear": {
|
|
2726
|
-
const removed = order.splice(leadingPageCount());
|
|
2727
|
-
for (const id of removed) entities.delete(id);
|
|
2728
|
-
touched = touched || removed.length > 0;
|
|
2729
|
-
break;
|
|
2730
|
-
}
|
|
2731
|
-
case "prepend": {
|
|
2732
|
-
const fresh = [];
|
|
2733
|
-
for (const msg of ins.messages) {
|
|
2734
|
-
const id = String(msg.id || "").trim();
|
|
2735
|
-
if (!id || entities.has(id)) continue;
|
|
2736
|
-
entities.set(id, {
|
|
2737
|
-
msg: normalizeMessageType(msg),
|
|
2738
|
-
source: "page",
|
|
2739
|
-
epoch: streamEpoch,
|
|
2740
|
-
ver: 1
|
|
2741
|
-
});
|
|
2742
|
-
fresh.push(id);
|
|
2743
|
-
}
|
|
2744
|
-
if (fresh.length) {
|
|
2745
|
-
order = [...fresh, ...order];
|
|
2746
|
-
touched = true;
|
|
2747
|
-
}
|
|
2748
|
-
break;
|
|
2749
|
-
}
|
|
2750
|
-
case "finalize": {
|
|
2751
|
-
if (streamStatusRef.value !== "settled") {
|
|
2752
|
-
streamStatusRef.value = "settled";
|
|
2753
|
-
touched = true;
|
|
2754
|
-
}
|
|
2755
|
-
break;
|
|
2756
|
-
}
|
|
2229
|
+
// src/runtime/rows-store.ts
|
|
2230
|
+
var import_vue2 = require("vue");
|
|
2231
|
+
function createRowsStore() {
|
|
2232
|
+
const rows = (0, import_vue2.shallowRef)([]);
|
|
2233
|
+
const sortRows = (list) => [...list].sort((a, b) => a.seq - b.seq);
|
|
2234
|
+
return {
|
|
2235
|
+
rows,
|
|
2236
|
+
setAll(next) {
|
|
2237
|
+
rows.value = sortRows(next);
|
|
2238
|
+
},
|
|
2239
|
+
prepend(older) {
|
|
2240
|
+
if (!older.length) return;
|
|
2241
|
+
const seen = new Set(rows.value.map((r) => String(r.content?.id || "")));
|
|
2242
|
+
const fresh = older.filter((r) => {
|
|
2243
|
+
const id = String(r.content?.id || "");
|
|
2244
|
+
if (!id || seen.has(id)) return false;
|
|
2245
|
+
seen.add(id);
|
|
2246
|
+
return true;
|
|
2247
|
+
});
|
|
2248
|
+
if (!fresh.length) return;
|
|
2249
|
+
rows.value = sortRows([...fresh, ...rows.value]);
|
|
2250
|
+
},
|
|
2251
|
+
mergeLatest(latest) {
|
|
2252
|
+
if (!latest.length) return;
|
|
2253
|
+
const byId = new Map(rows.value.map((r) => [String(r.content?.id || ""), r]));
|
|
2254
|
+
for (const row of latest) {
|
|
2255
|
+
const id = String(row.content?.id || "");
|
|
2256
|
+
if (!id) continue;
|
|
2257
|
+
byId.set(id, row);
|
|
2757
2258
|
}
|
|
2259
|
+
rows.value = sortRows([...byId.values()]);
|
|
2758
2260
|
}
|
|
2759
|
-
if (touched) bump();
|
|
2760
|
-
};
|
|
2761
|
-
return {
|
|
2762
|
-
applyInstructions,
|
|
2763
|
-
beginStream() {
|
|
2764
|
-
streamEpoch++;
|
|
2765
|
-
streamStatusRef.value = "streaming";
|
|
2766
|
-
bump();
|
|
2767
|
-
},
|
|
2768
|
-
getEntity: (id) => entities.get(id),
|
|
2769
|
-
get order() {
|
|
2770
|
-
return order;
|
|
2771
|
-
},
|
|
2772
|
-
get pageCount() {
|
|
2773
|
-
if (pageCountCache < 0) pageCountCache = leadingPageCount();
|
|
2774
|
-
return pageCountCache;
|
|
2775
|
-
},
|
|
2776
|
-
getMessages() {
|
|
2777
|
-
if (!cachedFlat) cachedFlat = order.map((id) => entities.get(id).msg);
|
|
2778
|
-
return cachedFlat;
|
|
2779
|
-
},
|
|
2780
|
-
get streamStatus() {
|
|
2781
|
-
return streamStatusRef.value;
|
|
2782
|
-
},
|
|
2783
|
-
get streamEpoch() {
|
|
2784
|
-
return streamEpoch;
|
|
2785
|
-
},
|
|
2786
|
-
version,
|
|
2787
|
-
streamStatusRef
|
|
2788
2261
|
};
|
|
2789
2262
|
}
|
|
2790
|
-
function
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2263
|
+
function extractLiveIncrement(snapshot, lastSeenIds) {
|
|
2264
|
+
const fresh = [];
|
|
2265
|
+
for (const msg of snapshot) {
|
|
2266
|
+
const id = String(msg?.id || "").trim();
|
|
2267
|
+
if (!id || lastSeenIds.has(id)) continue;
|
|
2268
|
+
lastSeenIds.add(id);
|
|
2269
|
+
fresh.push(msg);
|
|
2794
2270
|
}
|
|
2795
|
-
return
|
|
2796
|
-
}
|
|
2797
|
-
function isCitationCarrier(msg) {
|
|
2798
|
-
if (!isAiMessage(msg)) return false;
|
|
2799
|
-
return readContentText(asSxin(msg).content).includes("support.kbCitation");
|
|
2271
|
+
return fresh;
|
|
2800
2272
|
}
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
let
|
|
2273
|
+
|
|
2274
|
+
// src/runtime/values-projection.ts
|
|
2275
|
+
function createValuesChannel(options = {}) {
|
|
2276
|
+
let latestStreamMessages = [];
|
|
2277
|
+
let lastTitle = "";
|
|
2805
2278
|
return {
|
|
2806
|
-
|
|
2807
|
-
|
|
2279
|
+
beginStream() {
|
|
2280
|
+
latestStreamMessages = [];
|
|
2808
2281
|
},
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
citationVersion++;
|
|
2282
|
+
applyValuesEvent(data) {
|
|
2283
|
+
if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
|
|
2284
|
+
const title = String(data?.title || "").trim();
|
|
2285
|
+
if (title && title !== lastTitle) {
|
|
2286
|
+
lastTitle = title;
|
|
2287
|
+
options.onTitle?.(title);
|
|
2816
2288
|
}
|
|
2817
|
-
const extracted = extractThreadInfo(messages).clarificationAnswers;
|
|
2818
|
-
for (const [key, value] of extracted) answers.set(key, value);
|
|
2819
|
-
},
|
|
2820
|
-
resolveCitation(messageId) {
|
|
2821
|
-
return citationPatches.get(messageId);
|
|
2822
|
-
},
|
|
2823
|
-
answers,
|
|
2824
|
-
setAnswer(requestId, answer) {
|
|
2825
|
-
answers.set(requestId, answer);
|
|
2826
2289
|
},
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
},
|
|
2830
|
-
dispose() {
|
|
2831
|
-
citationPatches.clear();
|
|
2832
|
-
answers.clear();
|
|
2290
|
+
getStreamMessages() {
|
|
2291
|
+
return [...latestStreamMessages];
|
|
2833
2292
|
}
|
|
2834
2293
|
};
|
|
2835
2294
|
}
|
|
2295
|
+
|
|
2296
|
+
// src/store/runs-store.ts
|
|
2297
|
+
var import_vue3 = require("vue");
|
|
2836
2298
|
function createInterruptState() {
|
|
2837
|
-
const respondedIds = (0,
|
|
2299
|
+
const respondedIds = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Set());
|
|
2838
2300
|
return {
|
|
2839
2301
|
respondedIds,
|
|
2840
2302
|
markResponded(id) {
|
|
@@ -2851,8 +2313,8 @@ function createInterruptState() {
|
|
|
2851
2313
|
};
|
|
2852
2314
|
}
|
|
2853
2315
|
function createRunsStore(options) {
|
|
2854
|
-
const runsMap = (0,
|
|
2855
|
-
const currentRunId = (0,
|
|
2316
|
+
const runsMap = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Map());
|
|
2317
|
+
const currentRunId = (0, import_vue3.shallowRef)(null);
|
|
2856
2318
|
return {
|
|
2857
2319
|
runsMap,
|
|
2858
2320
|
currentRunId,
|
|
@@ -2943,98 +2405,97 @@ function createRunsStore(options) {
|
|
|
2943
2405
|
};
|
|
2944
2406
|
}
|
|
2945
2407
|
|
|
2946
|
-
// src/runtime/derived-groups.ts
|
|
2947
|
-
var import_vue6 = require("vue");
|
|
2948
|
-
function createDerivedGroups(deps) {
|
|
2949
|
-
const deriver = createGroupDeriver(deps.state);
|
|
2950
|
-
const derived = (0, import_vue6.computed)(() => {
|
|
2951
|
-
deps.store.version.value;
|
|
2952
|
-
return deriver.derive({
|
|
2953
|
-
store: deps.store,
|
|
2954
|
-
enrichments: deps.enrichments,
|
|
2955
|
-
getInterrupt: () => deps.valuesChannel.getInterrupt({ isLoading: deps.streamRef.value?.isLoading.value ?? false }),
|
|
2956
|
-
respondedIds: deps.interruptState.respondedIds.value,
|
|
2957
|
-
currentRunId: deps.runs.currentRunId.value ?? void 0,
|
|
2958
|
-
twin: deps.twin
|
|
2959
|
-
});
|
|
2960
|
-
});
|
|
2961
|
-
deps.scope.run(() => {
|
|
2962
|
-
(0, import_vue6.watch)(
|
|
2963
|
-
() => [deps.store.version.value, deps.runs.currentRunId.value],
|
|
2964
|
-
() => {
|
|
2965
|
-
deps.state.pruneExtras(derived.value.sourceGroups, deps.runs.currentRunId.value ?? void 0);
|
|
2966
|
-
},
|
|
2967
|
-
{ flush: "sync" }
|
|
2968
|
-
);
|
|
2969
|
-
});
|
|
2970
|
-
const groups = (0, import_vue6.computed)(() => derived.value.groups);
|
|
2971
|
-
const sourceGroups = (0, import_vue6.computed)(() => derived.value.sourceGroups);
|
|
2972
|
-
return { groups, sourceGroups };
|
|
2973
|
-
}
|
|
2974
|
-
|
|
2975
2408
|
// src/runtime/thread-runtime.ts
|
|
2409
|
+
var pendingSeq = 0;
|
|
2410
|
+
function newPendingRunId() {
|
|
2411
|
+
pendingSeq += 1;
|
|
2412
|
+
return `local-${Date.now()}-${pendingSeq}`;
|
|
2413
|
+
}
|
|
2976
2414
|
function createThreadRuntime(options) {
|
|
2977
|
-
const scope = (0,
|
|
2978
|
-
const store = createThreadStore({ threadId: options.threadId });
|
|
2979
|
-
const enrichments = createEnrichments();
|
|
2415
|
+
const scope = (0, import_vue4.effectScope)();
|
|
2980
2416
|
const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
|
|
2981
2417
|
const interruptState = createInterruptState();
|
|
2982
|
-
const
|
|
2418
|
+
const rowsStore = createRowsStore();
|
|
2419
|
+
const overlay = createSemanticOverlay();
|
|
2983
2420
|
const valuesChannel = createValuesChannel({
|
|
2984
2421
|
onTitle: (title) => options.onTitle?.(options.threadId, title)
|
|
2985
2422
|
});
|
|
2986
|
-
|
|
2987
|
-
const
|
|
2988
|
-
const
|
|
2989
|
-
const tokenUsage = (0,
|
|
2423
|
+
const streamRef = (0, import_vue4.shallowRef)(null);
|
|
2424
|
+
const isInitializing = (0, import_vue4.ref)(false);
|
|
2425
|
+
const streaming = (0, import_vue4.ref)(false);
|
|
2426
|
+
const tokenUsage = (0, import_vue4.shallowRef)(null);
|
|
2990
2427
|
let initialized = false;
|
|
2991
2428
|
let initPromise = null;
|
|
2992
2429
|
let pager = null;
|
|
2993
|
-
const
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
2430
|
+
const runsListMeta = (0, import_vue4.shallowRef)([]);
|
|
2431
|
+
const liveMessages = (0, import_vue4.shallowRef)([]);
|
|
2432
|
+
const lastSeenLiveIds = /* @__PURE__ */ new Set();
|
|
2433
|
+
const pendingRun = (0, import_vue4.shallowRef)(null);
|
|
2434
|
+
const answers = (0, import_vue4.shallowRef)(/* @__PURE__ */ new Map());
|
|
2435
|
+
const activeRunId = (0, import_vue4.computed)(() => runs.currentRunId.value);
|
|
2436
|
+
const runsProjection = (0, import_vue4.computed)(
|
|
2437
|
+
() => projectRuns({
|
|
2438
|
+
rows: rowsStore.rows.value,
|
|
2439
|
+
liveMessages: liveMessages.value,
|
|
2440
|
+
activeRunId: activeRunId.value,
|
|
2441
|
+
runsList: runsListMeta.value,
|
|
2442
|
+
pendingRun: pendingRun.value,
|
|
2443
|
+
answers: answers.value,
|
|
2444
|
+
twin: options.twin,
|
|
2445
|
+
streaming: streaming.value
|
|
2446
|
+
})
|
|
2447
|
+
);
|
|
2448
|
+
const interrupt = (0, import_vue4.computed)(() => streamRef.value?.interrupt.value);
|
|
2449
|
+
const hasPendingInterrupt = (0, import_vue4.computed)(() => {
|
|
3007
2450
|
const it = interrupt.value;
|
|
3008
2451
|
return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
|
|
3009
2452
|
});
|
|
3010
|
-
const streamError = (0,
|
|
3011
|
-
const isGenerating = (0,
|
|
3012
|
-
const
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
return !list.slice(i + 1).some((x) => x.type === "human");
|
|
3022
|
-
});
|
|
2453
|
+
const streamError = (0, import_vue4.computed)(() => streamRef.value?.error.value ?? null);
|
|
2454
|
+
const isGenerating = (0, import_vue4.computed)(() => streaming.value);
|
|
2455
|
+
const activeClarification = (0, import_vue4.computed)(() => {
|
|
2456
|
+
const list = runsProjection.value;
|
|
2457
|
+
for (let i = list.length - 1; i >= 0; i--) {
|
|
2458
|
+
const clarifications = list[i].clarifications;
|
|
2459
|
+
for (let c = clarifications.length - 1; c >= 0; c--) {
|
|
2460
|
+
if (clarifications[c].answer === void 0) return clarifications[c];
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
return void 0;
|
|
3023
2464
|
});
|
|
2465
|
+
const clarificationAnswers = (0, import_vue4.computed)(() => answers.value);
|
|
3024
2466
|
const beginStream = () => {
|
|
3025
|
-
chunkBuffer?.reset();
|
|
3026
2467
|
valuesChannel.beginStream();
|
|
2468
|
+
overlay.invalidate();
|
|
3027
2469
|
runs.currentRunId.value = null;
|
|
2470
|
+
liveMessages.value = [];
|
|
2471
|
+
lastSeenLiveIds.clear();
|
|
3028
2472
|
};
|
|
3029
2473
|
const streamStarted = () => {
|
|
3030
|
-
|
|
2474
|
+
streaming.value = true;
|
|
2475
|
+
};
|
|
2476
|
+
const streamSettled = () => {
|
|
2477
|
+
streaming.value = false;
|
|
2478
|
+
pendingRun.value = null;
|
|
3031
2479
|
};
|
|
3032
2480
|
const markStreamRun = (runIdRaw) => {
|
|
3033
2481
|
const runId = String(runIdRaw || "").trim();
|
|
3034
2482
|
if (!runId) return;
|
|
3035
2483
|
runs.currentRunId.value = runId;
|
|
3036
2484
|
runs.ensureRunning(runId);
|
|
3037
|
-
|
|
2485
|
+
const pending = pendingRun.value;
|
|
2486
|
+
if (pending && pending.runId !== runId) {
|
|
2487
|
+
pendingRun.value = { ...pending, runId };
|
|
2488
|
+
}
|
|
2489
|
+
};
|
|
2490
|
+
const applyLiveSnapshot = (messages) => {
|
|
2491
|
+
if (!streaming.value) return;
|
|
2492
|
+
const fresh = extractLiveIncrement(messages, lastSeenLiveIds);
|
|
2493
|
+
const eligible = fresh.filter((m) => {
|
|
2494
|
+
const t = String(m?.type || "");
|
|
2495
|
+
return t === "ai" || t === "tool";
|
|
2496
|
+
});
|
|
2497
|
+
if (!eligible.length) return;
|
|
2498
|
+
liveMessages.value = [...liveMessages.value, ...eligible];
|
|
3038
2499
|
};
|
|
3039
2500
|
const refreshTokenUsage = async () => {
|
|
3040
2501
|
try {
|
|
@@ -3048,17 +2509,18 @@ function createThreadRuntime(options) {
|
|
|
3048
2509
|
threadId: options.threadId,
|
|
3049
2510
|
assistantId: options.assistantId,
|
|
3050
2511
|
transport: options.transport,
|
|
3051
|
-
store,
|
|
3052
|
-
enrichments,
|
|
3053
2512
|
runs,
|
|
2513
|
+
rowsStore,
|
|
2514
|
+
runsListMeta,
|
|
2515
|
+
overlay,
|
|
3054
2516
|
valuesChannel,
|
|
3055
2517
|
streamRef,
|
|
3056
|
-
setChunkBuffer: (b) => chunkBuffer = b,
|
|
3057
|
-
getChunkBuffer: () => chunkBuffer,
|
|
3058
2518
|
setPager: (p) => pager = p,
|
|
3059
2519
|
setInitialized: () => initialized = true,
|
|
3060
2520
|
markStreamRun,
|
|
2521
|
+
applyLiveSnapshot,
|
|
3061
2522
|
onStreamStart: streamStarted,
|
|
2523
|
+
onStreamSettled: streamSettled,
|
|
3062
2524
|
refreshTokenUsage
|
|
3063
2525
|
},
|
|
3064
2526
|
{
|
|
@@ -3066,23 +2528,39 @@ function createThreadRuntime(options) {
|
|
|
3066
2528
|
onEnd: () => isInitializing.value = false
|
|
3067
2529
|
}
|
|
3068
2530
|
);
|
|
2531
|
+
const actions = createStreamActions({
|
|
2532
|
+
options,
|
|
2533
|
+
getHandle: () => streamRef.value,
|
|
2534
|
+
beginStream,
|
|
2535
|
+
markStreamRun,
|
|
2536
|
+
getInterrupt: () => streamRef.value?.interrupt.value,
|
|
2537
|
+
markResponded: (id) => interruptState.markResponded(id),
|
|
2538
|
+
unmarkResponded: (id) => interruptState.unmarkResponded(id),
|
|
2539
|
+
getPager: () => pager,
|
|
2540
|
+
runs,
|
|
2541
|
+
createPendingRun: (text, kind, kwargs) => {
|
|
2542
|
+
const pending = { runId: newPendingRunId(), text, kind, kwargs };
|
|
2543
|
+
pendingRun.value = pending;
|
|
2544
|
+
return pending.runId;
|
|
2545
|
+
}
|
|
2546
|
+
});
|
|
3069
2547
|
return {
|
|
3070
2548
|
threadId: options.threadId,
|
|
3071
2549
|
lastViewedAt: Date.now(),
|
|
3072
2550
|
touch() {
|
|
3073
2551
|
this.lastViewedAt = Date.now();
|
|
3074
2552
|
},
|
|
3075
|
-
|
|
2553
|
+
runs: runsProjection,
|
|
2554
|
+
runsInfo: (0, import_vue4.computed)(() => runs.runsMap.value),
|
|
2555
|
+
activeClarification,
|
|
3076
2556
|
isGenerating,
|
|
3077
2557
|
isInitializing,
|
|
3078
|
-
runs: (0, import_vue7.computed)(() => runs.runsMap.value),
|
|
3079
2558
|
interrupt,
|
|
3080
2559
|
hasPendingInterrupt,
|
|
3081
|
-
hasPendingClarification,
|
|
3082
2560
|
streamError,
|
|
3083
2561
|
tokenUsage,
|
|
3084
|
-
hasMoreHistory: (0,
|
|
3085
|
-
loadingHistory: (0,
|
|
2562
|
+
hasMoreHistory: (0, import_vue4.computed)(() => pager?.hasMore.value ?? false),
|
|
2563
|
+
loadingHistory: (0, import_vue4.computed)(() => pager?.loading.value ?? false),
|
|
3086
2564
|
async init() {
|
|
3087
2565
|
if (initialized) return;
|
|
3088
2566
|
if (initPromise) return initPromise;
|
|
@@ -3093,64 +2571,52 @@ function createThreadRuntime(options) {
|
|
|
3093
2571
|
initPromise = null;
|
|
3094
2572
|
}
|
|
3095
2573
|
},
|
|
3096
|
-
submit
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
},
|
|
3111
|
-
stop() {
|
|
3112
|
-
void options.transport.cancelRun(options.threadId, runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
|
|
3113
|
-
streamRef.value?.stop();
|
|
3114
|
-
},
|
|
3115
|
-
async resumeInterrupt(decisions) {
|
|
3116
|
-
const it = valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false });
|
|
3117
|
-
const interruptId = String(it?.id || "");
|
|
3118
|
-
if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
|
|
3119
|
-
const handle = streamRef.value;
|
|
3120
|
-
if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
|
|
3121
|
-
interruptState.markResponded(interruptId);
|
|
3122
|
-
beginStream();
|
|
3123
|
-
await handle.resumeInterrupt(decisions);
|
|
3124
|
-
},
|
|
3125
|
-
async loadOlderMessages() {
|
|
3126
|
-
if (!pager) return false;
|
|
3127
|
-
return pager.loadOlder();
|
|
2574
|
+
submit: actions.submit,
|
|
2575
|
+
joinStream: actions.joinStream,
|
|
2576
|
+
stop: actions.stop,
|
|
2577
|
+
resumeInterrupt: actions.resumeInterrupt,
|
|
2578
|
+
loadOlderMessages: actions.loadOlderMessages,
|
|
2579
|
+
applyFeedback(messageId, feedback) {
|
|
2580
|
+
rowsStore.mergeLatest(
|
|
2581
|
+
rowsStore.rows.value.map((row) => {
|
|
2582
|
+
const id = String(row.content?.id || "");
|
|
2583
|
+
return id === messageId ? { ...row, feedback } : row;
|
|
2584
|
+
})
|
|
2585
|
+
);
|
|
2586
|
+
const runId = runsProjection.value.find((r) => r.rawMessages.some((m) => m.id === messageId))?.runId;
|
|
2587
|
+
if (runId) runs.patchRun(runId, { feedback });
|
|
3128
2588
|
},
|
|
3129
|
-
|
|
3130
|
-
|
|
2589
|
+
addOptimisticTurn: (body) => {
|
|
2590
|
+
const runId = newPendingRunId();
|
|
2591
|
+
pendingRun.value = { runId, text: body, kind: "message" };
|
|
3131
2592
|
},
|
|
3132
|
-
|
|
3133
|
-
|
|
2593
|
+
updateAiBody(aiId, body) {
|
|
2594
|
+
rowsStore.mergeLatest(
|
|
2595
|
+
rowsStore.rows.value.map((row) => {
|
|
2596
|
+
const id = String(row.content?.id || "");
|
|
2597
|
+
return id === aiId ? { ...row, content: { ...row.content, content: body } } : row;
|
|
2598
|
+
})
|
|
2599
|
+
);
|
|
3134
2600
|
},
|
|
3135
|
-
|
|
3136
|
-
|
|
2601
|
+
decorate(messageId, patch) {
|
|
2602
|
+
if (patch.feedback) this.applyFeedback(messageId, patch.feedback);
|
|
3137
2603
|
},
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
state.patchGroup(messageId, { feedback }, () => sourceGroups.value);
|
|
3141
|
-
if (runId) runs.patchRun(runId, { feedback });
|
|
2604
|
+
finalizeTurns() {
|
|
2605
|
+
pendingRun.value = null;
|
|
3142
2606
|
},
|
|
3143
2607
|
setClarificationAnswer(toolCallId, answer) {
|
|
3144
|
-
|
|
2608
|
+
const next = new Map(answers.value);
|
|
2609
|
+
next.set(toolCallId, answer);
|
|
2610
|
+
answers.value = next;
|
|
3145
2611
|
},
|
|
3146
2612
|
clearClarificationAnswers() {
|
|
3147
|
-
|
|
2613
|
+
if (!answers.value.size) return;
|
|
2614
|
+
answers.value = /* @__PURE__ */ new Map();
|
|
3148
2615
|
},
|
|
3149
|
-
clarificationAnswers
|
|
2616
|
+
clarificationAnswers,
|
|
3150
2617
|
dispose() {
|
|
3151
2618
|
streamRef.value?.stop();
|
|
3152
|
-
|
|
3153
|
-
enrichments.dispose();
|
|
2619
|
+
streamRef.value?.dispose?.();
|
|
3154
2620
|
runs.dispose();
|
|
3155
2621
|
scope.stop();
|
|
3156
2622
|
}
|
|
@@ -3158,15 +2624,15 @@ function createThreadRuntime(options) {
|
|
|
3158
2624
|
}
|
|
3159
2625
|
|
|
3160
2626
|
// src/runtime/thread-directory.ts
|
|
3161
|
-
var
|
|
3162
|
-
var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending"]);
|
|
2627
|
+
var import_vue5 = require("vue");
|
|
2628
|
+
var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending", "interrupted"]);
|
|
3163
2629
|
function isActiveThreadStatus(status) {
|
|
3164
2630
|
return typeof status === "string" && ACTIVE_THREAD_STATUSES.has(status);
|
|
3165
2631
|
}
|
|
3166
2632
|
var ThreadDirectory = class {
|
|
3167
2633
|
constructor(options) {
|
|
3168
|
-
this.threads = (0,
|
|
3169
|
-
this.threadsPagination = (0,
|
|
2634
|
+
this.threads = (0, import_vue5.ref)([]);
|
|
2635
|
+
this.threadsPagination = (0, import_vue5.ref)({
|
|
3170
2636
|
limit: 50,
|
|
3171
2637
|
offset: 0,
|
|
3172
2638
|
hasMore: true,
|
|
@@ -3174,9 +2640,9 @@ var ThreadDirectory = class {
|
|
|
3174
2640
|
});
|
|
3175
2641
|
this.searchKeyword = "";
|
|
3176
2642
|
/** 正在运行但已超出 SSE 连接上限的 thread(仅用于 UI 提示) */
|
|
3177
|
-
this.runningNotConnectedThreadIds = (0,
|
|
2643
|
+
this.runningNotConnectedThreadIds = (0, import_vue5.ref)(/* @__PURE__ */ new Set());
|
|
3178
2644
|
/** 活跃 runtime 池(shallowReactive 追踪增删,runtime 实例不被深度代理) */
|
|
3179
|
-
this.cachedRuntimes = (0,
|
|
2645
|
+
this.cachedRuntimes = (0, import_vue5.shallowReactive)(/* @__PURE__ */ new Map());
|
|
3180
2646
|
this.transport = options.transport;
|
|
3181
2647
|
this.assistantId = options.assistantId;
|
|
3182
2648
|
this.maxCachedRuntimes = options.maxCachedRuntimes ?? DEFAULT_MAX_CACHED_SESSIONS;
|
|
@@ -3311,17 +2777,26 @@ var ThreadDirectory = class {
|
|
|
3311
2777
|
}
|
|
3312
2778
|
// ===== 刷新后恢复 =====
|
|
3313
2779
|
/**
|
|
3314
|
-
*
|
|
3315
|
-
*
|
|
2780
|
+
* 恢复未完成 run 的 SSE:按 thread.status(含 interrupted)筛出候选线程并行 listRuns
|
|
2781
|
+
* 取最新 run → init + joinStream。
|
|
2782
|
+
* ⚠️ DeerFlow 语义:thread.status 与 run.status 的 'interrupted' 都表示「run 未完成」
|
|
2783
|
+
*(_derive_thread_status:tasks 非空 → interrupted;涵盖在跑、停在半路、HITL 挂起),
|
|
2784
|
+
* 不等于 LangGraph 官方的「HITL 挂起」——因此 run.status 不作硬判定,最新 run 一律
|
|
2785
|
+
* join:在跑则继续收流;已断则 join 返回 end 帧走 onFinish 对账(runs/state/citation
|
|
2786
|
+
* 刷新),页面收敛到最终状态。join 为只读幂等端点,误 join 无副作用。
|
|
2787
|
+
* 并行确认,串行连接(并发上限内)。
|
|
3316
2788
|
*/
|
|
3317
2789
|
async recoverRunningThreads() {
|
|
3318
|
-
const
|
|
2790
|
+
const candidates = this.threads.value.filter((t) => t.thread_id && isActiveThreadStatus(t.status));
|
|
3319
2791
|
const results = await Promise.all(
|
|
3320
|
-
|
|
2792
|
+
candidates.map(async (thread) => {
|
|
3321
2793
|
try {
|
|
3322
2794
|
const runs = await this.transport.listRuns(thread.thread_id, 5);
|
|
3323
|
-
|
|
3324
|
-
|
|
2795
|
+
if (!Array.isArray(runs) || runs.length === 0) return null;
|
|
2796
|
+
const latest = [...runs].sort(
|
|
2797
|
+
(a, b) => String(b?.created_at || "").localeCompare(String(a?.created_at || ""))
|
|
2798
|
+
)[0];
|
|
2799
|
+
return latest?.run_id ? { threadId: thread.thread_id, runId: String(latest.run_id) } : null;
|
|
3325
2800
|
} catch (e) {
|
|
3326
2801
|
console.warn("[ThreadDirectory] check running run failed", e);
|
|
3327
2802
|
return null;
|
|
@@ -3353,7 +2828,7 @@ var ThreadDirectory = class {
|
|
|
3353
2828
|
};
|
|
3354
2829
|
|
|
3355
2830
|
// src/core/ChatCore.ts
|
|
3356
|
-
var
|
|
2831
|
+
var import_vue6 = require("vue");
|
|
3357
2832
|
function createChatCore(options) {
|
|
3358
2833
|
const notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
|
|
3359
2834
|
const directory = new ThreadDirectory({
|
|
@@ -3365,37 +2840,46 @@ function createChatCore(options) {
|
|
|
3365
2840
|
notify,
|
|
3366
2841
|
defaultThreadTitle: options.defaultThreadTitle
|
|
3367
2842
|
});
|
|
3368
|
-
const currentThreadId = (0,
|
|
3369
|
-
const threads = (0,
|
|
3370
|
-
const threadsPagination = (0,
|
|
3371
|
-
const activeRuntime = (0,
|
|
2843
|
+
const currentThreadId = (0, import_vue6.ref)(null);
|
|
2844
|
+
const threads = (0, import_vue6.computed)(() => directory.threads.value);
|
|
2845
|
+
const threadsPagination = (0, import_vue6.computed)(() => directory.threadsPagination.value);
|
|
2846
|
+
const activeRuntime = (0, import_vue6.computed)(
|
|
3372
2847
|
() => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
|
|
3373
2848
|
);
|
|
3374
|
-
const
|
|
3375
|
-
const
|
|
3376
|
-
|
|
2849
|
+
const runs = (0, import_vue6.computed)(() => activeRuntime.value?.runs.value ?? []);
|
|
2850
|
+
const runsInfo = (0, import_vue6.computed)(() => activeRuntime.value?.runsInfo.value ?? /* @__PURE__ */ new Map());
|
|
2851
|
+
const toolCalls = (0, import_vue6.computed)(
|
|
2852
|
+
() => runs.value.flatMap(
|
|
2853
|
+
(run) => run.tools.map((tool, index) => ({
|
|
2854
|
+
id: tool.callId,
|
|
2855
|
+
call: { id: tool.callId, name: tool.name, args: tool.input },
|
|
2856
|
+
result: tool.result ? { content: tool.result } : void 0,
|
|
2857
|
+
state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
|
|
2858
|
+
index
|
|
2859
|
+
}))
|
|
2860
|
+
)
|
|
3377
2861
|
);
|
|
3378
|
-
const
|
|
3379
|
-
const
|
|
3380
|
-
() => activeRuntime.value
|
|
2862
|
+
const activeClarification = (0, import_vue6.computed)(() => activeRuntime.value?.activeClarification.value);
|
|
2863
|
+
const isGenerating = (0, import_vue6.computed)(
|
|
2864
|
+
() => !!activeRuntime.value && activeRuntime.value.isGenerating.value
|
|
3381
2865
|
);
|
|
3382
|
-
const
|
|
3383
|
-
const clarificationAnswers = (0,
|
|
2866
|
+
const isLoadingThread = (0, import_vue6.computed)(() => activeRuntime.value?.isInitializing.value ?? false);
|
|
2867
|
+
const clarificationAnswers = (0, import_vue6.computed)(
|
|
3384
2868
|
() => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
|
|
3385
2869
|
);
|
|
3386
|
-
const activeInterrupt = (0,
|
|
3387
|
-
const hasPendingInterrupt = (0,
|
|
3388
|
-
const
|
|
3389
|
-
const
|
|
3390
|
-
|
|
3391
|
-
);
|
|
3392
|
-
const
|
|
3393
|
-
const
|
|
3394
|
-
const
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
const getRunsByThreadId = (threadId) => threadId ? Array.from(
|
|
2870
|
+
const activeInterrupt = (0, import_vue6.computed)(() => activeRuntime.value?.interrupt.value);
|
|
2871
|
+
const hasPendingInterrupt = (0, import_vue6.computed)(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
|
|
2872
|
+
const inputDisabled = (0, import_vue6.computed)(() => isGenerating.value || hasPendingInterrupt.value);
|
|
2873
|
+
const streamError = (0, import_vue6.computed)(() => activeRuntime.value?.streamError.value ?? null);
|
|
2874
|
+
const hasMoreHistory = (0, import_vue6.computed)(() => activeRuntime.value?.hasMoreHistory.value ?? false);
|
|
2875
|
+
const loadingHistory = (0, import_vue6.computed)(() => activeRuntime.value?.loadingHistory.value ?? false);
|
|
2876
|
+
const tokenUsage = (0, import_vue6.computed)(() => activeRuntime.value?.tokenUsage.value ?? null);
|
|
2877
|
+
const runningNotConnectedThreadIds = (0, import_vue6.computed)(() => directory.runningNotConnectedThreadIds.value);
|
|
2878
|
+
const getRunById = (runId) => {
|
|
2879
|
+
const info = runId ? runsInfo.value.get(runId) : void 0;
|
|
2880
|
+
return info;
|
|
2881
|
+
};
|
|
2882
|
+
const getRunsByThreadId = (threadId) => threadId ? Array.from(runsInfo.value.values()).filter((r) => r.threadId === threadId) : [];
|
|
3399
2883
|
const ensureThreadId = async () => {
|
|
3400
2884
|
if (currentThreadId.value) return { threadId: currentThreadId.value, isNew: false, thread: null };
|
|
3401
2885
|
const thread = await directory.createThread({ source: "chat" });
|
|
@@ -3432,8 +2916,6 @@ function createChatCore(options) {
|
|
|
3432
2916
|
runtime.touch();
|
|
3433
2917
|
if (isNew && thread) directory.prependThread(thread);
|
|
3434
2918
|
await runtime.init();
|
|
3435
|
-
const optimistic = runtime.createOptimisticHuman(trimmed, sendOptions);
|
|
3436
|
-
runtime.appendOptimisticGroups([optimistic]);
|
|
3437
2919
|
runtime.submit(trimmed, sendOptions);
|
|
3438
2920
|
};
|
|
3439
2921
|
const loadThread = async (threadId) => {
|
|
@@ -3446,41 +2928,30 @@ function createChatCore(options) {
|
|
|
3446
2928
|
result.touch();
|
|
3447
2929
|
await result.init();
|
|
3448
2930
|
};
|
|
3449
|
-
const
|
|
2931
|
+
const regenerateTurn = async (runId) => {
|
|
3450
2932
|
if (isGenerating.value) return;
|
|
3451
|
-
const
|
|
3452
|
-
const
|
|
3453
|
-
if (
|
|
3454
|
-
let question;
|
|
3455
|
-
let text = "";
|
|
3456
|
-
for (const m of list.slice(0, idx).reverse()) {
|
|
3457
|
-
if (m.type !== "human") continue;
|
|
3458
|
-
const [t] = m.texts ?? [];
|
|
3459
|
-
if (t) {
|
|
3460
|
-
question = m;
|
|
3461
|
-
text = t;
|
|
3462
|
-
break;
|
|
3463
|
-
}
|
|
3464
|
-
}
|
|
3465
|
-
if (!text) {
|
|
2933
|
+
const run = runs.value.find((r) => r.runId === runId);
|
|
2934
|
+
const text = run?.input.text ?? "";
|
|
2935
|
+
if (!run || !text.trim()) {
|
|
3466
2936
|
notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
|
|
3467
2937
|
return;
|
|
3468
2938
|
}
|
|
3469
|
-
await sendMessage(text, { kwargs: { ...
|
|
2939
|
+
await sendMessage(text, { kwargs: { ...run.input.kwargs ?? {}, hide_from_ui: false } });
|
|
3470
2940
|
};
|
|
3471
2941
|
return {
|
|
3472
|
-
|
|
3473
|
-
|
|
2942
|
+
runs,
|
|
2943
|
+
turns: runs,
|
|
3474
2944
|
isGenerating,
|
|
3475
2945
|
isLoadingThread,
|
|
3476
2946
|
currentThreadId,
|
|
3477
2947
|
threads,
|
|
3478
2948
|
threadsPagination,
|
|
3479
|
-
|
|
2949
|
+
runsInfo,
|
|
3480
2950
|
toolCalls,
|
|
3481
2951
|
getRunById,
|
|
3482
2952
|
getRunsByThreadId,
|
|
3483
2953
|
clarificationAnswers,
|
|
2954
|
+
activeClarification,
|
|
3484
2955
|
setClarificationAnswer: (toolCallId, answer) => activeRuntime.value?.setClarificationAnswer(toolCallId, answer),
|
|
3485
2956
|
clearClarificationAnswers: () => activeRuntime.value?.clearClarificationAnswers(),
|
|
3486
2957
|
sendMessage,
|
|
@@ -3489,11 +2960,12 @@ function createChatCore(options) {
|
|
|
3489
2960
|
clearMessages: () => {
|
|
3490
2961
|
currentThreadId.value = null;
|
|
3491
2962
|
},
|
|
3492
|
-
updateGroupMessage: (messageId, patch) => activeRuntime.value?.patchGroup(messageId, patch),
|
|
3493
|
-
addOptimisticGroupMessages: (ms) => activeRuntime.value?.appendOptimisticGroups(ms),
|
|
3494
|
-
updateGroupMessageBlocks: (messageId, blocks) => activeRuntime.value?.patchGroup(messageId, { blocks }),
|
|
3495
2963
|
applyFeedback: (messageId, feedback) => activeRuntime.value?.applyFeedback(messageId, feedback),
|
|
3496
|
-
|
|
2964
|
+
regenerateTurn,
|
|
2965
|
+
addOptimisticTurn: (body) => activeRuntime.value?.addOptimisticTurn(body),
|
|
2966
|
+
updateAiBody: (aiId, body) => activeRuntime.value?.updateAiBody(aiId, body),
|
|
2967
|
+
decorate: (messageId, patch) => activeRuntime.value?.decorate(messageId, patch),
|
|
2968
|
+
finalizeTurns: () => activeRuntime.value?.finalizeTurns(),
|
|
3497
2969
|
fetchThreads: (reset, keyword) => directory.fetchThreads(reset, keyword),
|
|
3498
2970
|
deleteThread: async (threadId) => {
|
|
3499
2971
|
const deleted = await directory.deleteThread(threadId);
|
|
@@ -3506,8 +2978,8 @@ function createChatCore(options) {
|
|
|
3506
2978
|
runningNotConnectedThreadIds,
|
|
3507
2979
|
recoverRunningThreads: () => directory.recoverRunningThreads(),
|
|
3508
2980
|
activeInterrupt,
|
|
2981
|
+
interrupt: activeInterrupt,
|
|
3509
2982
|
hasPendingInterrupt,
|
|
3510
|
-
hasPendingClarification,
|
|
3511
2983
|
inputDisabled,
|
|
3512
2984
|
streamError,
|
|
3513
2985
|
hasMoreHistory,
|
|
@@ -3529,7 +3001,7 @@ function createChatCore(options) {
|
|
|
3529
3001
|
}
|
|
3530
3002
|
|
|
3531
3003
|
// src/test-utils/mockTransport.ts
|
|
3532
|
-
var
|
|
3004
|
+
var import_vue7 = require("vue");
|
|
3533
3005
|
var mockThreadSeq = 0;
|
|
3534
3006
|
function createMockTransport() {
|
|
3535
3007
|
const threads = [];
|
|
@@ -3537,6 +3009,7 @@ function createMockTransport() {
|
|
|
3537
3009
|
const messagesPagesMap = /* @__PURE__ */ new Map();
|
|
3538
3010
|
const tokenUsageMap = /* @__PURE__ */ new Map();
|
|
3539
3011
|
const artifactContentMap = /* @__PURE__ */ new Map();
|
|
3012
|
+
const resumeErrorMap = /* @__PURE__ */ new Map();
|
|
3540
3013
|
const handles = /* @__PURE__ */ new Map();
|
|
3541
3014
|
const optionsMap = /* @__PURE__ */ new Map();
|
|
3542
3015
|
const calls = { submit: [], resumeInterrupt: [], stop: [], joinStream: [], cancel: [] };
|
|
@@ -3620,13 +3093,15 @@ function createMockTransport() {
|
|
|
3620
3093
|
return content;
|
|
3621
3094
|
},
|
|
3622
3095
|
createStream(options) {
|
|
3623
|
-
const isLoading = (0,
|
|
3624
|
-
const error = (0,
|
|
3096
|
+
const isLoading = (0, import_vue7.ref)(false);
|
|
3097
|
+
const error = (0, import_vue7.ref)(null);
|
|
3098
|
+
const interrupt = (0, import_vue7.ref)(void 0);
|
|
3625
3099
|
const threadId = options.threadId;
|
|
3626
3100
|
optionsMap.set(threadId, options);
|
|
3627
3101
|
const handle = {
|
|
3628
3102
|
isLoading,
|
|
3629
3103
|
error,
|
|
3104
|
+
interrupt,
|
|
3630
3105
|
submit(input, submitOptions) {
|
|
3631
3106
|
calls.submit.push({ threadId, input, options: submitOptions });
|
|
3632
3107
|
},
|
|
@@ -3639,6 +3114,8 @@ function createMockTransport() {
|
|
|
3639
3114
|
},
|
|
3640
3115
|
async resumeInterrupt(decisions) {
|
|
3641
3116
|
calls.resumeInterrupt.push({ threadId, decisions });
|
|
3117
|
+
const err = resumeErrorMap.get(threadId)?.shift();
|
|
3118
|
+
if (err) throw err;
|
|
3642
3119
|
}
|
|
3643
3120
|
};
|
|
3644
3121
|
handles.set(threadId, {
|
|
@@ -3649,12 +3126,12 @@ function createMockTransport() {
|
|
|
3649
3126
|
isLoading.value = snapshot.isLoading;
|
|
3650
3127
|
if (!snapshot.isLoading) ended = true;
|
|
3651
3128
|
}
|
|
3652
|
-
if (snapshot.values !== void 0 || snapshot.messages !== void 0
|
|
3129
|
+
if (snapshot.values !== void 0 || snapshot.messages !== void 0) {
|
|
3653
3130
|
const data = { ...snapshot.values ?? {} };
|
|
3654
3131
|
if (snapshot.messages !== void 0) data.messages = snapshot.messages;
|
|
3655
|
-
if ("interrupt" in snapshot) data.__interrupt__ = snapshot.interrupt ? [snapshot.interrupt] : [];
|
|
3656
3132
|
options.onValuesEvent?.(data);
|
|
3657
3133
|
}
|
|
3134
|
+
if ("interrupt" in snapshot) interrupt.value = snapshot.interrupt;
|
|
3658
3135
|
if (ended) options.onStreamEnd?.();
|
|
3659
3136
|
}
|
|
3660
3137
|
});
|
|
@@ -3687,6 +3164,14 @@ function createMockTransport() {
|
|
|
3687
3164
|
;
|
|
3688
3165
|
entry.handle.error.value = err;
|
|
3689
3166
|
},
|
|
3167
|
+
__setResumeError(threadId, err) {
|
|
3168
|
+
let queue = resumeErrorMap.get(threadId);
|
|
3169
|
+
if (!queue) {
|
|
3170
|
+
queue = [];
|
|
3171
|
+
resumeErrorMap.set(threadId, queue);
|
|
3172
|
+
}
|
|
3173
|
+
queue.push(err);
|
|
3174
|
+
},
|
|
3690
3175
|
__setInitialValues(threadId, values) {
|
|
3691
3176
|
initialValuesMap.set(threadId, values);
|
|
3692
3177
|
},
|
|
@@ -3709,42 +3194,40 @@ function createMockTransport() {
|
|
|
3709
3194
|
}
|
|
3710
3195
|
|
|
3711
3196
|
// src/index.ts
|
|
3712
|
-
var CORE_VERSION = "2.
|
|
3197
|
+
var CORE_VERSION = "2.1.0";
|
|
3713
3198
|
// Annotate the CommonJS export names for ESM import in node:
|
|
3714
3199
|
0 && (module.exports = {
|
|
3715
3200
|
CORE_VERSION,
|
|
3716
3201
|
DEFAULT_ASSISTANT_ID,
|
|
3717
3202
|
DEFAULT_MAX_CACHED_SESSIONS,
|
|
3718
3203
|
DEFAULT_MAX_CONCURRENT_STREAMS,
|
|
3719
|
-
DEFAULT_TWIN_TOOL_PREFIX,
|
|
3720
3204
|
INJECTED_TAGS,
|
|
3721
3205
|
MESSAGE_TYPE_NORMALIZE,
|
|
3722
3206
|
OUTLINE_MAX_LEVEL,
|
|
3723
3207
|
ThreadDirectory,
|
|
3724
|
-
|
|
3208
|
+
applySemanticPatches,
|
|
3209
|
+
asArgsObject,
|
|
3210
|
+
assembleRun,
|
|
3211
|
+
backfillRunMessageFeedback,
|
|
3725
3212
|
buildArtifactFiles,
|
|
3726
3213
|
buildHitlDecisions,
|
|
3727
|
-
buildHumanGroup,
|
|
3728
3214
|
buildHumanInputResponse,
|
|
3729
3215
|
buildInterruptReviewBlock,
|
|
3730
|
-
buildInterruptReviewGroup,
|
|
3731
3216
|
buildRejectDecisions,
|
|
3732
3217
|
buildReportBodyPayload,
|
|
3733
3218
|
buildReportOutlinePayload,
|
|
3734
3219
|
buildRunDirectLatencyMs,
|
|
3735
3220
|
buildRunInfo,
|
|
3221
|
+
buildRunMeta,
|
|
3736
3222
|
collectTextKeepSxin,
|
|
3737
3223
|
collectVisibleText,
|
|
3738
|
-
createBlockBuilderLite,
|
|
3739
3224
|
createChatCore,
|
|
3740
3225
|
createEmptySubChapter,
|
|
3741
|
-
createGroupDeriver,
|
|
3742
3226
|
createMockTransport,
|
|
3743
|
-
|
|
3744
|
-
createStreamPump,
|
|
3227
|
+
createSemanticOverlay,
|
|
3745
3228
|
createThreadRuntime,
|
|
3746
|
-
createViewModelState,
|
|
3747
3229
|
deriveToolsFromMessages,
|
|
3230
|
+
emptyRunItem,
|
|
3748
3231
|
ensureOutlineContentThemes,
|
|
3749
3232
|
ensureRunningRun,
|
|
3750
3233
|
extractAiContentFromMessage,
|
|
@@ -3752,31 +3235,36 @@ var CORE_VERSION = "2.0.0";
|
|
|
3752
3235
|
extractBlocksFromNodes,
|
|
3753
3236
|
extractCitationAnchors,
|
|
3754
3237
|
extractCitationAnchorsFromSpec,
|
|
3238
|
+
extractFromToolResult,
|
|
3239
|
+
extractInputFromRows,
|
|
3755
3240
|
extractReportTitleFromBody,
|
|
3756
3241
|
extractRunEnrichment,
|
|
3242
|
+
extractSemanticPatchesFromMessages,
|
|
3757
3243
|
extractStateMessages,
|
|
3758
3244
|
extractTextFromMessage,
|
|
3759
3245
|
extractThreadInfo,
|
|
3760
3246
|
extractTitleFromArtifactPath,
|
|
3761
3247
|
extractUserMessageTexts,
|
|
3762
|
-
|
|
3248
|
+
formatAnswerText,
|
|
3763
3249
|
formatStr,
|
|
3764
3250
|
genBlockId,
|
|
3765
3251
|
genMessageId,
|
|
3766
3252
|
getAllowedDecisions,
|
|
3767
3253
|
getHumanMessageBaseId,
|
|
3768
3254
|
getToolCallArtifactMeta,
|
|
3255
|
+
groupRowsByRun,
|
|
3769
3256
|
isAiMessage,
|
|
3770
|
-
isClarificationAnswered,
|
|
3771
|
-
isClarificationBlock,
|
|
3772
3257
|
isHiddenUserMessage,
|
|
3773
3258
|
isHumanMessage,
|
|
3774
3259
|
isInjectedElement,
|
|
3775
3260
|
isReportBodyHtml,
|
|
3776
3261
|
isSameArgs,
|
|
3777
3262
|
isToolMessage,
|
|
3263
|
+
isUserEchoRow,
|
|
3778
3264
|
isVisibleUserMessage,
|
|
3779
3265
|
isWriteFileToolName,
|
|
3266
|
+
mapBackendStatus,
|
|
3267
|
+
mergeStateWithPageMessages,
|
|
3780
3268
|
normalizeForCompare,
|
|
3781
3269
|
normalizeMessageType,
|
|
3782
3270
|
normalizeOutline,
|
|
@@ -3785,11 +3273,15 @@ var CORE_VERSION = "2.0.0";
|
|
|
3785
3273
|
parseHumanMessageId,
|
|
3786
3274
|
parseKnowledgeItemsFromValue,
|
|
3787
3275
|
parseMarkdownToOutline,
|
|
3276
|
+
pickRicherArgs,
|
|
3788
3277
|
pickRunMessageMetadata,
|
|
3278
|
+
projectRuns,
|
|
3789
3279
|
readMessageContentText,
|
|
3790
3280
|
resolveReportArtifactKind,
|
|
3281
|
+
rowMessageId,
|
|
3791
3282
|
runMessagesToMessages,
|
|
3792
3283
|
simpleHash,
|
|
3284
|
+
sliceBodySegments,
|
|
3793
3285
|
stateMessagesToRunMessages,
|
|
3794
3286
|
toRunMessage,
|
|
3795
3287
|
tokenizeSxin,
|