@cqfe/sxin-chat-core 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ChatCore-DyjH-HBV.d.cts → ChatCore-cSM1HmXp.d.cts} +410 -337
- package/dist/{ChatCore-DyjH-HBV.d.ts → ChatCore-cSM1HmXp.d.ts} +410 -337
- package/dist/chunk-Z65C2UII.mjs +2830 -0
- package/dist/index.cjs +1861 -1520
- package/dist/index.d.cts +628 -235
- package/dist/index.d.ts +628 -235
- package/dist/index.mjs +1001 -143
- package/dist/vue/index.cjs +1449 -2185
- package/dist/vue/index.d.cts +2 -2
- package/dist/vue/index.d.ts +2 -2
- package/dist/vue/index.mjs +1 -1
- package/package.json +4 -4
- package/dist/chunk-NLL3XGEI.mjs +0 -3378
|
@@ -0,0 +1,2830 @@
|
|
|
1
|
+
var __typeError = (msg) => {
|
|
2
|
+
throw TypeError(msg);
|
|
3
|
+
};
|
|
4
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
5
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
6
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
7
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
8
|
+
|
|
9
|
+
// src/constants.ts
|
|
10
|
+
var DEFAULT_MAX_CACHED_SESSIONS = 10;
|
|
11
|
+
var DEFAULT_MAX_CONCURRENT_STREAMS = 3;
|
|
12
|
+
var DEFAULT_ASSISTANT_ID = "lead_agent";
|
|
13
|
+
|
|
14
|
+
// src/parser/sxin-ast-attrs.ts
|
|
15
|
+
function formatStr(str) {
|
|
16
|
+
if (!str) return str;
|
|
17
|
+
return str.replace(/["`\s]/g, "");
|
|
18
|
+
}
|
|
19
|
+
function skipWhitespace(source, i) {
|
|
20
|
+
const len = source.length;
|
|
21
|
+
while (i < len && /\s/.test(source[i])) i++;
|
|
22
|
+
return i;
|
|
23
|
+
}
|
|
24
|
+
function readQuotedValue(source, j, key) {
|
|
25
|
+
const quote = source[j];
|
|
26
|
+
const close = source.indexOf(quote, j + 1);
|
|
27
|
+
if (close === -1) {
|
|
28
|
+
return { key, value: source.slice(j + 1), next: source.length, hasValue: true, truncated: true };
|
|
29
|
+
}
|
|
30
|
+
return { key, value: source.slice(j + 1, close), next: close + 1, hasValue: true, truncated: false };
|
|
31
|
+
}
|
|
32
|
+
function readBareValue(source, j, key) {
|
|
33
|
+
const valMatch = /^[^\s>]+/.exec(source.slice(j));
|
|
34
|
+
const raw = valMatch ? valMatch[0] : "";
|
|
35
|
+
const value = raw.endsWith("/") ? raw.slice(0, -1) : raw;
|
|
36
|
+
return { key, value, next: j + raw.length, hasValue: true, truncated: false };
|
|
37
|
+
}
|
|
38
|
+
function readAttrPair(source, i) {
|
|
39
|
+
const keyMatch = /^[\w-]+/.exec(source.slice(i));
|
|
40
|
+
if (!keyMatch) return null;
|
|
41
|
+
const key = keyMatch[0];
|
|
42
|
+
let j = skipWhitespace(source, i + key.length);
|
|
43
|
+
if (source[j] !== "=") return { key, value: "", next: j, hasValue: false, truncated: false };
|
|
44
|
+
j = skipWhitespace(source, j + 1);
|
|
45
|
+
if (j >= source.length) {
|
|
46
|
+
return { key, value: "", next: source.length, hasValue: true, truncated: true };
|
|
47
|
+
}
|
|
48
|
+
const quote = source[j];
|
|
49
|
+
return quote === '"' || quote === "'" ? readQuotedValue(source, j, key) : readBareValue(source, j, key);
|
|
50
|
+
}
|
|
51
|
+
function matchTerminator(source, i) {
|
|
52
|
+
if (source[i] === ">") return { selfClosing: false };
|
|
53
|
+
if (source[i] === "/" && source[i + 1] === ">") return { selfClosing: true };
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
function parseAttrs(source, pos) {
|
|
57
|
+
const attrs = {};
|
|
58
|
+
const len = source.length;
|
|
59
|
+
let i = pos;
|
|
60
|
+
while (i < len) {
|
|
61
|
+
i = skipWhitespace(source, i);
|
|
62
|
+
if (i >= len) break;
|
|
63
|
+
const term = matchTerminator(source, i);
|
|
64
|
+
if (term) return { attrs, pos: i, terminated: true, selfClosing: term.selfClosing };
|
|
65
|
+
const pair = readAttrPair(source, i);
|
|
66
|
+
if (!pair) {
|
|
67
|
+
i++;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
i = pair.next;
|
|
71
|
+
if (!pair.hasValue) continue;
|
|
72
|
+
attrs[formatStr(pair.key)] = formatStr(pair.value);
|
|
73
|
+
if (pair.truncated) return { attrs, pos: len, terminated: false, selfClosing: false };
|
|
74
|
+
}
|
|
75
|
+
return { attrs, pos: len, terminated: false, selfClosing: false };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// src/parser/sxin-ast-collect.ts
|
|
79
|
+
var INJECTED_TAGS = /* @__PURE__ */ new Set([
|
|
80
|
+
"think",
|
|
81
|
+
"current_user",
|
|
82
|
+
"request_context",
|
|
83
|
+
"system-reminder",
|
|
84
|
+
"memory",
|
|
85
|
+
"current_date",
|
|
86
|
+
"requested_capabilities",
|
|
87
|
+
"user_selections",
|
|
88
|
+
"current_uploads",
|
|
89
|
+
"uploaded_files",
|
|
90
|
+
"attachments",
|
|
91
|
+
"slash_skill_activation"
|
|
92
|
+
]);
|
|
93
|
+
function isInjectedElement(node) {
|
|
94
|
+
return INJECTED_TAGS.has(node.tagName);
|
|
95
|
+
}
|
|
96
|
+
function collectVisibleText(source, nodes) {
|
|
97
|
+
const parts = [];
|
|
98
|
+
const walk = (list) => {
|
|
99
|
+
for (const node of list) {
|
|
100
|
+
if (node.type === "text") {
|
|
101
|
+
parts.push(node.value);
|
|
102
|
+
} else if (node.type === "comment") {
|
|
103
|
+
parts.push(`<!--${node.content}-->`);
|
|
104
|
+
} else if (!node.closed && !INJECTED_TAGS.has(node.tagName)) {
|
|
105
|
+
parts.push(source.slice(node.start, node.end));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
walk(nodes);
|
|
110
|
+
return parts.join("");
|
|
111
|
+
}
|
|
112
|
+
function collectTextKeepSxin(source, nodes) {
|
|
113
|
+
const parts = [];
|
|
114
|
+
const walk = (list) => {
|
|
115
|
+
for (const node of list) {
|
|
116
|
+
if (node.type === "text") {
|
|
117
|
+
parts.push(node.value);
|
|
118
|
+
} else if (node.type === "comment") {
|
|
119
|
+
parts.push(`<!--${node.content}-->`);
|
|
120
|
+
} else if (!isInjectedElement(node)) {
|
|
121
|
+
parts.push(source.slice(node.start, node.end));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
walk(nodes);
|
|
126
|
+
return parts.join("");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// src/parser/sxin-ast.ts
|
|
130
|
+
function isTagNameChar(c) {
|
|
131
|
+
return !!c && /[\w-]/.test(c);
|
|
132
|
+
}
|
|
133
|
+
var VOID_TAGS = /* @__PURE__ */ new Set([
|
|
134
|
+
"area",
|
|
135
|
+
"base",
|
|
136
|
+
"br",
|
|
137
|
+
"col",
|
|
138
|
+
"embed",
|
|
139
|
+
"hr",
|
|
140
|
+
"img",
|
|
141
|
+
"input",
|
|
142
|
+
"link",
|
|
143
|
+
"meta",
|
|
144
|
+
"param",
|
|
145
|
+
"source",
|
|
146
|
+
"track",
|
|
147
|
+
"wbr"
|
|
148
|
+
]);
|
|
149
|
+
function readTagName(source, pos) {
|
|
150
|
+
if (!/[a-zA-Z]/.test(source[pos] || "")) return null;
|
|
151
|
+
let end = pos + 1;
|
|
152
|
+
while (isTagNameChar(source[end])) end++;
|
|
153
|
+
return { name: source.slice(pos, end).toLowerCase(), end };
|
|
154
|
+
}
|
|
155
|
+
function attachNode(stack, topLevel, node) {
|
|
156
|
+
const parent = stack[stack.length - 1];
|
|
157
|
+
if (parent) parent.children.push(node);
|
|
158
|
+
else topLevel.push(node);
|
|
159
|
+
}
|
|
160
|
+
function flushTextAt(source, st, to) {
|
|
161
|
+
if (to > st.textStart) {
|
|
162
|
+
attachNode(st.stack, st.nodes, {
|
|
163
|
+
type: "text",
|
|
164
|
+
value: source.slice(st.textStart, to),
|
|
165
|
+
start: st.textStart,
|
|
166
|
+
end: to
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function handleComment(source, i, st) {
|
|
171
|
+
if (!source.startsWith("<!--", i)) return false;
|
|
172
|
+
const close = source.indexOf("-->", i + 4);
|
|
173
|
+
if (close === -1) {
|
|
174
|
+
st.i = source.length;
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
flushTextAt(source, st, i);
|
|
178
|
+
attachNode(st.stack, st.nodes, {
|
|
179
|
+
type: "comment",
|
|
180
|
+
content: source.slice(i + 4, close),
|
|
181
|
+
start: i,
|
|
182
|
+
end: close + 3
|
|
183
|
+
});
|
|
184
|
+
st.i = close + 3;
|
|
185
|
+
st.textStart = st.i;
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
188
|
+
function handleCloseTag(source, i, st) {
|
|
189
|
+
if (source[i + 1] !== "/") return false;
|
|
190
|
+
const tag = readTagName(source, i + 2);
|
|
191
|
+
if (!tag) {
|
|
192
|
+
st.i = i + 1;
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
let k = tag.end;
|
|
196
|
+
while (k < source.length && /\s/.test(source[k])) k++;
|
|
197
|
+
if (source[k] !== ">") {
|
|
198
|
+
st.i = i + 1;
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
let depth = -1;
|
|
202
|
+
for (let d = st.stack.length - 1; d >= 0; d--) {
|
|
203
|
+
if (st.stack[d].tagName === tag.name) {
|
|
204
|
+
depth = d;
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (depth === -1) {
|
|
209
|
+
st.i = k + 1;
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
flushTextAt(source, st, i);
|
|
213
|
+
while (st.stack.length - 1 > depth) {
|
|
214
|
+
st.stack.pop().end = i;
|
|
215
|
+
}
|
|
216
|
+
const target = st.stack[st.stack.length - 1];
|
|
217
|
+
st.stack.pop();
|
|
218
|
+
target.closed = true;
|
|
219
|
+
target.end = k + 1;
|
|
220
|
+
st.i = k + 1;
|
|
221
|
+
st.textStart = k + 1;
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
function handleOpenTag(source, i, st) {
|
|
225
|
+
const tag = readTagName(source, i + 1);
|
|
226
|
+
if (!tag) {
|
|
227
|
+
st.i = i + 1;
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
const len = source.length;
|
|
231
|
+
const { attrs, pos, terminated, selfClosing } = parseAttrs(source, tag.end);
|
|
232
|
+
flushTextAt(source, st, i);
|
|
233
|
+
const asSelfClosing = selfClosing || terminated && VOID_TAGS.has(tag.name);
|
|
234
|
+
const el = {
|
|
235
|
+
type: "element",
|
|
236
|
+
tagName: tag.name,
|
|
237
|
+
attrs,
|
|
238
|
+
children: [],
|
|
239
|
+
selfClosing,
|
|
240
|
+
closed: asSelfClosing,
|
|
241
|
+
// 自闭合或 void 元素视为已闭合
|
|
242
|
+
start: i,
|
|
243
|
+
end: len
|
|
244
|
+
// 未闭合时延伸到 EOF
|
|
245
|
+
};
|
|
246
|
+
attachNode(st.stack, st.nodes, el);
|
|
247
|
+
if (!terminated) {
|
|
248
|
+
st.i = len;
|
|
249
|
+
st.textStart = len;
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (asSelfClosing) {
|
|
253
|
+
el.end = selfClosing ? pos + 2 : pos + 1;
|
|
254
|
+
st.i = el.end;
|
|
255
|
+
} else {
|
|
256
|
+
st.stack.push(el);
|
|
257
|
+
st.i = pos + 1;
|
|
258
|
+
}
|
|
259
|
+
st.textStart = st.i;
|
|
260
|
+
}
|
|
261
|
+
var OPAQUE_CONTENT_TAGS = /* @__PURE__ */ new Set(["think"]);
|
|
262
|
+
function findCloseTagEnd(source, from, name) {
|
|
263
|
+
const lower = source.toLowerCase();
|
|
264
|
+
const needle = "</" + name;
|
|
265
|
+
let p = lower.indexOf(needle, from);
|
|
266
|
+
while (p !== -1) {
|
|
267
|
+
let k = p + needle.length;
|
|
268
|
+
while (k < source.length && /\s/.test(source[k])) k++;
|
|
269
|
+
if (source[k] === ">") return k + 1;
|
|
270
|
+
p = lower.indexOf(needle, p + 1);
|
|
271
|
+
}
|
|
272
|
+
return -1;
|
|
273
|
+
}
|
|
274
|
+
function handleOpaqueTag(source, i, st) {
|
|
275
|
+
const tag = readTagName(source, i + 1);
|
|
276
|
+
if (!tag || !OPAQUE_CONTENT_TAGS.has(tag.name)) return false;
|
|
277
|
+
const { attrs, pos, terminated, selfClosing } = parseAttrs(source, tag.end);
|
|
278
|
+
flushTextAt(source, st, i);
|
|
279
|
+
if (!terminated) {
|
|
280
|
+
attachNode(st.stack, st.nodes, {
|
|
281
|
+
type: "element",
|
|
282
|
+
tagName: tag.name,
|
|
283
|
+
attrs,
|
|
284
|
+
children: [],
|
|
285
|
+
selfClosing,
|
|
286
|
+
closed: false,
|
|
287
|
+
start: i,
|
|
288
|
+
end: source.length
|
|
289
|
+
});
|
|
290
|
+
st.i = source.length;
|
|
291
|
+
st.textStart = source.length;
|
|
292
|
+
return true;
|
|
293
|
+
}
|
|
294
|
+
const openEnd = selfClosing ? pos + 2 : pos + 1;
|
|
295
|
+
const closeEnd = selfClosing ? -1 : findCloseTagEnd(source, openEnd, tag.name);
|
|
296
|
+
const el = {
|
|
297
|
+
type: "element",
|
|
298
|
+
tagName: tag.name,
|
|
299
|
+
attrs,
|
|
300
|
+
children: [],
|
|
301
|
+
selfClosing,
|
|
302
|
+
closed: selfClosing || closeEnd !== -1,
|
|
303
|
+
start: i,
|
|
304
|
+
end: closeEnd !== -1 ? closeEnd : source.length
|
|
305
|
+
};
|
|
306
|
+
attachNode(st.stack, st.nodes, el);
|
|
307
|
+
st.i = el.end;
|
|
308
|
+
st.textStart = el.end;
|
|
309
|
+
return true;
|
|
310
|
+
}
|
|
311
|
+
function tokenizeSxin(source) {
|
|
312
|
+
const len = source.length;
|
|
313
|
+
const st = { nodes: [], stack: [], textStart: 0, i: 0 };
|
|
314
|
+
while (st.i < len) {
|
|
315
|
+
if (source[st.i] !== "<") {
|
|
316
|
+
st.i++;
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
if (handleComment(source, st.i, st)) continue;
|
|
320
|
+
if (handleCloseTag(source, st.i, st)) continue;
|
|
321
|
+
if (handleOpaqueTag(source, st.i, st)) continue;
|
|
322
|
+
handleOpenTag(source, st.i, st);
|
|
323
|
+
}
|
|
324
|
+
flushTextAt(source, st, len);
|
|
325
|
+
return st.nodes;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// src/parser/thread-info.ts
|
|
329
|
+
function formatAnswerText(value) {
|
|
330
|
+
if (value == null) return "";
|
|
331
|
+
if (typeof value === "string") return value;
|
|
332
|
+
if (typeof value === "object") {
|
|
333
|
+
const values = value.values;
|
|
334
|
+
if (values && typeof values === "object" && !Array.isArray(values)) {
|
|
335
|
+
return Object.values(values).filter((v) => v !== void 0 && v !== null && v !== "").map(String).join("; ");
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
return JSON.stringify(value);
|
|
339
|
+
} catch {
|
|
340
|
+
return String(value);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return String(value);
|
|
344
|
+
}
|
|
345
|
+
var humanInputResponseRule = {
|
|
346
|
+
key: "clarificationAnswers",
|
|
347
|
+
extract(msg, acc) {
|
|
348
|
+
const additionalKwargs = msg?.additional_kwargs;
|
|
349
|
+
const response = additionalKwargs?.human_input_response;
|
|
350
|
+
const requestId = String(response?.request_id || "").trim().replace("clarification:", "");
|
|
351
|
+
if (requestId && response?.value !== void 0) {
|
|
352
|
+
acc.clarificationAnswers.set(requestId, formatAnswerText(response.value));
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
var THREAD_INFO_RULES = [humanInputResponseRule];
|
|
357
|
+
function extractThreadInfo(messages) {
|
|
358
|
+
const info = { clarificationAnswers: /* @__PURE__ */ new Map() };
|
|
359
|
+
for (const msg of messages ?? []) {
|
|
360
|
+
for (const rule of THREAD_INFO_RULES) {
|
|
361
|
+
rule.extract(msg, info);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return info;
|
|
365
|
+
}
|
|
366
|
+
function buildHumanInputResponse(requestId, options) {
|
|
367
|
+
return {
|
|
368
|
+
hide_from_ui: true,
|
|
369
|
+
human_input_response: {
|
|
370
|
+
version: 1,
|
|
371
|
+
kind: "human_input_response",
|
|
372
|
+
source: options.source,
|
|
373
|
+
request_id: requestId,
|
|
374
|
+
response_kind: options.responseKind,
|
|
375
|
+
value: options.value
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// src/parser/thread.ts
|
|
381
|
+
function extractStateMessages(state) {
|
|
382
|
+
if (!state || typeof state !== "object") return [];
|
|
383
|
+
const values = state.values;
|
|
384
|
+
if (!values || typeof values !== "object") return [];
|
|
385
|
+
const messages = values.messages;
|
|
386
|
+
return Array.isArray(messages) ? messages : [];
|
|
387
|
+
}
|
|
388
|
+
function mergeStateWithPageMessages(stateMessages, pageMessages) {
|
|
389
|
+
if (!pageMessages.length) return stateMessages;
|
|
390
|
+
if (!stateMessages.length) return pageMessages;
|
|
391
|
+
const locateId = (m) => String(m?.id || m?.tool_call_id || "").trim();
|
|
392
|
+
const pageIndex = /* @__PURE__ */ new Map();
|
|
393
|
+
pageMessages.forEach((m, i) => {
|
|
394
|
+
const id = locateId(m);
|
|
395
|
+
if (id && !pageIndex.has(id)) pageIndex.set(id, i);
|
|
396
|
+
});
|
|
397
|
+
let anchorSi = -1;
|
|
398
|
+
let anchorPi = -1;
|
|
399
|
+
for (let si = 0; si < stateMessages.length; si++) {
|
|
400
|
+
const id = locateId(stateMessages[si]);
|
|
401
|
+
const pi = id ? pageIndex.get(id) : void 0;
|
|
402
|
+
if (pi !== void 0) {
|
|
403
|
+
anchorSi = si;
|
|
404
|
+
anchorPi = pi;
|
|
405
|
+
break;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
if (anchorSi < 0) return pageMessages;
|
|
409
|
+
const stateIds = /* @__PURE__ */ new Set();
|
|
410
|
+
for (const m of stateMessages) {
|
|
411
|
+
const id = String(m?.id || "").trim();
|
|
412
|
+
const callId = String(m?.tool_call_id || "").trim();
|
|
413
|
+
if (id) stateIds.add(id);
|
|
414
|
+
if (callId) stateIds.add(callId);
|
|
415
|
+
}
|
|
416
|
+
const headExtras = [];
|
|
417
|
+
for (let pi = 0; pi < anchorPi; pi++) {
|
|
418
|
+
const m = pageMessages[pi];
|
|
419
|
+
const id = locateId(m);
|
|
420
|
+
if (id && !stateIds.has(id)) headExtras.push(m);
|
|
421
|
+
}
|
|
422
|
+
const tailExtras = [];
|
|
423
|
+
for (let pi = anchorPi + 1; pi < pageMessages.length; pi++) {
|
|
424
|
+
const m = pageMessages[pi];
|
|
425
|
+
const id = locateId(m);
|
|
426
|
+
if (id && !stateIds.has(id)) tailExtras.push(m);
|
|
427
|
+
}
|
|
428
|
+
const runIdById = /* @__PURE__ */ new Map();
|
|
429
|
+
for (const m of pageMessages) {
|
|
430
|
+
const id = String(m?.id || "").trim();
|
|
431
|
+
const rid = String(m?.runId || "").trim();
|
|
432
|
+
if (id && rid && !runIdById.has(id)) runIdById.set(id, rid);
|
|
433
|
+
}
|
|
434
|
+
const stampRunId = (m) => {
|
|
435
|
+
const id = String(m?.id || "").trim();
|
|
436
|
+
if (!id) return m;
|
|
437
|
+
const rid = runIdById.get(id);
|
|
438
|
+
if (!rid) return m;
|
|
439
|
+
if (String(m?.runId || "").trim() || String(m?.additional_kwargs?.run_id || "").trim()) return m;
|
|
440
|
+
return { ...m, runId: rid };
|
|
441
|
+
};
|
|
442
|
+
return [...headExtras, ...stateMessages.map(stampRunId), ...tailExtras];
|
|
443
|
+
}
|
|
444
|
+
function ensureRunningRun(runMap, runId, threadId) {
|
|
445
|
+
let runInfo = runMap.get(runId);
|
|
446
|
+
if (!runInfo) {
|
|
447
|
+
runInfo = {
|
|
448
|
+
runId,
|
|
449
|
+
threadId: threadId || "",
|
|
450
|
+
status: "running"
|
|
451
|
+
};
|
|
452
|
+
runMap.set(runId, runInfo);
|
|
453
|
+
}
|
|
454
|
+
return runInfo;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// src/parser/sxin-message.ts
|
|
458
|
+
var asSxin = (m) => m ?? {};
|
|
459
|
+
|
|
460
|
+
// src/parser/run-messages.ts
|
|
461
|
+
var MESSAGE_TYPE_NORMALIZE = {
|
|
462
|
+
AIMessage: "ai",
|
|
463
|
+
AIMessageChunk: "ai",
|
|
464
|
+
HumanMessage: "human",
|
|
465
|
+
HumanMessageChunk: "human",
|
|
466
|
+
ToolMessage: "tool",
|
|
467
|
+
ToolMessageChunk: "tool",
|
|
468
|
+
SystemMessage: "system",
|
|
469
|
+
SystemMessageChunk: "system",
|
|
470
|
+
assistant: "ai",
|
|
471
|
+
user: "human"
|
|
472
|
+
};
|
|
473
|
+
function normalizeMessageType(message) {
|
|
474
|
+
const raw = String(asSxin(message).type || "").trim();
|
|
475
|
+
const normalized = MESSAGE_TYPE_NORMALIZE[raw];
|
|
476
|
+
if (normalized && normalized !== raw) {
|
|
477
|
+
return { ...asSxin(message), type: normalized };
|
|
478
|
+
}
|
|
479
|
+
return message;
|
|
480
|
+
}
|
|
481
|
+
function parseCreatedAt(value) {
|
|
482
|
+
if (value === null || value === void 0 || value === "") return void 0;
|
|
483
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
484
|
+
if (typeof value !== "string") return void 0;
|
|
485
|
+
const text = value.trim();
|
|
486
|
+
if (!text) return void 0;
|
|
487
|
+
if (/^\d+$/.test(text)) {
|
|
488
|
+
const ms2 = Number(text);
|
|
489
|
+
return Number.isFinite(ms2) ? ms2 : void 0;
|
|
490
|
+
}
|
|
491
|
+
const ms = Date.parse(text);
|
|
492
|
+
return Number.isFinite(ms) ? ms : void 0;
|
|
493
|
+
}
|
|
494
|
+
function toRunMessage(raw) {
|
|
495
|
+
if (!raw || typeof raw !== "object") return null;
|
|
496
|
+
const content = raw.content;
|
|
497
|
+
if (!content || typeof content !== "object" || Array.isArray(content)) return null;
|
|
498
|
+
if (!String(content.type || "").trim()) return null;
|
|
499
|
+
const seq = Number(raw.seq ?? 0);
|
|
500
|
+
if (!Number.isFinite(seq)) return null;
|
|
501
|
+
const createdAt = parseCreatedAt(raw.created_at);
|
|
502
|
+
return {
|
|
503
|
+
runId: String(raw.run_id ?? ""),
|
|
504
|
+
seq,
|
|
505
|
+
eventType: String(raw.event_type ?? ""),
|
|
506
|
+
...createdAt !== void 0 ? { createdAt } : {},
|
|
507
|
+
// feedback 可选:非空才映射
|
|
508
|
+
...raw.feedback !== void 0 && raw.feedback !== null ? { feedback: raw.feedback } : {},
|
|
509
|
+
content
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
function extractRunEnrichment(messages) {
|
|
513
|
+
const map = /* @__PURE__ */ new Map();
|
|
514
|
+
for (const msg of messages) {
|
|
515
|
+
const runId = String(msg?.runId || "").trim();
|
|
516
|
+
if (!runId) continue;
|
|
517
|
+
let entry = map.get(runId);
|
|
518
|
+
if (!entry) {
|
|
519
|
+
entry = {};
|
|
520
|
+
map.set(runId, entry);
|
|
521
|
+
}
|
|
522
|
+
if (msg.feedback !== void 0 && msg.feedback !== null) {
|
|
523
|
+
entry.feedback = msg.feedback;
|
|
524
|
+
}
|
|
525
|
+
const seconds = msg.content?.additional_kwargs?.turn_duration;
|
|
526
|
+
if (typeof seconds === "number" && !Number.isNaN(seconds) && seconds >= 0) {
|
|
527
|
+
entry.latencyMs = Math.round(seconds * 1e3);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
return map;
|
|
531
|
+
}
|
|
532
|
+
function backfillRunMessageFeedback(source, target) {
|
|
533
|
+
if (!source.length || !target.length) return target;
|
|
534
|
+
const feedbackById = /* @__PURE__ */ new Map();
|
|
535
|
+
for (const row of source) {
|
|
536
|
+
const id = String(row?.content?.id || "").trim();
|
|
537
|
+
if (!id || row?.feedback === void 0 || row?.feedback === null) continue;
|
|
538
|
+
feedbackById.set(id, row.feedback);
|
|
539
|
+
}
|
|
540
|
+
if (!feedbackById.size) return target;
|
|
541
|
+
return target.map((row) => {
|
|
542
|
+
const id = String(row?.content?.id || "").trim();
|
|
543
|
+
if (!id) return row;
|
|
544
|
+
const feedback = feedbackById.get(id);
|
|
545
|
+
if (feedback === void 0 || row.feedback !== void 0) return row;
|
|
546
|
+
return { ...row, feedback };
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
function runMessagesToMessages(messages) {
|
|
550
|
+
return messages.map((msg) => {
|
|
551
|
+
const normalized = normalizeMessageType({ ...asSxin(msg.content) });
|
|
552
|
+
asSxin(normalized).runId = msg.runId;
|
|
553
|
+
if (msg.createdAt !== void 0) {
|
|
554
|
+
const date = new Date(msg.createdAt);
|
|
555
|
+
if (!Number.isNaN(date.getTime())) asSxin(normalized).created_at = date.toISOString();
|
|
556
|
+
}
|
|
557
|
+
return normalized;
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
function stateMessagesToRunMessages(messages) {
|
|
561
|
+
return messages.map((msg, i) => {
|
|
562
|
+
const sxin = asSxin(msg);
|
|
563
|
+
const createdAt = parseCreatedAt(sxin.created_at);
|
|
564
|
+
return {
|
|
565
|
+
runId: String(sxin.runId ?? sxin.additional_kwargs?.run_id ?? ""),
|
|
566
|
+
seq: i + 1,
|
|
567
|
+
eventType: "messages",
|
|
568
|
+
...createdAt !== void 0 ? { createdAt } : {},
|
|
569
|
+
content: msg
|
|
570
|
+
};
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// src/parser/message-text.ts
|
|
575
|
+
function simpleHash(input) {
|
|
576
|
+
let hash = 5381;
|
|
577
|
+
for (let i = 0; i < input.length; i++) {
|
|
578
|
+
hash = (hash << 5) + hash + input.charCodeAt(i) & 4294967295;
|
|
579
|
+
}
|
|
580
|
+
return Math.abs(hash).toString(36);
|
|
581
|
+
}
|
|
582
|
+
function readMessageText(msg) {
|
|
583
|
+
if (!msg || typeof msg !== "object") return null;
|
|
584
|
+
const content = msg?.content;
|
|
585
|
+
if (typeof content === "string") return { text: content, trim: false };
|
|
586
|
+
if (Array.isArray(content)) {
|
|
587
|
+
const texts = [];
|
|
588
|
+
for (const part of content) {
|
|
589
|
+
if (part?.type === "text" && typeof part?.text === "string") {
|
|
590
|
+
texts.push(part.text);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return { text: texts.join("\n"), trim: true };
|
|
594
|
+
}
|
|
595
|
+
return null;
|
|
596
|
+
}
|
|
597
|
+
function readMessageContentText(msg) {
|
|
598
|
+
const read = readMessageText(msg);
|
|
599
|
+
if (!read) return "";
|
|
600
|
+
return read.trim ? read.text.trim() : read.text;
|
|
601
|
+
}
|
|
602
|
+
function hasKbCitationMessage(msg) {
|
|
603
|
+
return readMessageContentText(msg).includes("support.kbCitation");
|
|
604
|
+
}
|
|
605
|
+
function extractTextFromMessage(msg) {
|
|
606
|
+
const read = readMessageText(msg);
|
|
607
|
+
if (!read) return "";
|
|
608
|
+
const text = collectVisibleText(read.text, tokenizeSxin(read.text));
|
|
609
|
+
return read.trim ? text.trim() : text;
|
|
610
|
+
}
|
|
611
|
+
function extractAiContentFromMessage(msg) {
|
|
612
|
+
const read = readMessageText(msg);
|
|
613
|
+
if (!read) return "";
|
|
614
|
+
const text = collectTextKeepSxin(read.text, tokenizeSxin(read.text));
|
|
615
|
+
return read.trim ? text.trim() : text;
|
|
616
|
+
}
|
|
617
|
+
function isVisibleUserMessage(msg) {
|
|
618
|
+
if (!msg || typeof msg !== "object") return false;
|
|
619
|
+
if (String(msg.type || "") !== "human") return false;
|
|
620
|
+
return msg.additional_kwargs?.hide_from_ui !== true;
|
|
621
|
+
}
|
|
622
|
+
function extractUserMessageTexts(rawMessages) {
|
|
623
|
+
if (!Array.isArray(rawMessages)) return [];
|
|
624
|
+
return rawMessages.filter((m) => isVisibleUserMessage(m)).map((m) => extractTextFromMessage(m).trim()).filter(Boolean).slice(0, 1);
|
|
625
|
+
}
|
|
626
|
+
function isHiddenUserMessage(msg) {
|
|
627
|
+
return msg?.role === "user" && msg?.additionalKwargs?.hide_from_ui === true;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// src/parser/report-artifact.ts
|
|
631
|
+
var genId = () => typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `id-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
|
632
|
+
function isWriteFileToolName(name) {
|
|
633
|
+
const n = String(name || "").trim().toLowerCase();
|
|
634
|
+
return n === "write_file" || n === "write_files";
|
|
635
|
+
}
|
|
636
|
+
function getToolCallArtifactMeta(toolCall) {
|
|
637
|
+
const meta = toolCall?.artifact_meta;
|
|
638
|
+
if (!meta || typeof meta !== "object") return null;
|
|
639
|
+
return meta;
|
|
640
|
+
}
|
|
641
|
+
function pathSuggestsBody(artifactPath) {
|
|
642
|
+
return /_正文(?:\.(?:md|markdown))?$/i.test(artifactPath) || /[/\\][^/\\]*正文[^/\\]*\.(?:md|markdown)$/i.test(artifactPath);
|
|
643
|
+
}
|
|
644
|
+
function pathSuggestsOutline(artifactPath) {
|
|
645
|
+
return /_大纲(?:\.(?:md|markdown))?$/i.test(artifactPath) || /[/\\][^/\\]*大纲[^/\\]*\.(?:md|markdown)$/i.test(artifactPath);
|
|
646
|
+
}
|
|
647
|
+
function descriptionSuggestsBody(description) {
|
|
648
|
+
return /正文/.test(description);
|
|
649
|
+
}
|
|
650
|
+
function descriptionSuggestsOutline(description) {
|
|
651
|
+
return /大纲/.test(description) && !descriptionSuggestsBody(description);
|
|
652
|
+
}
|
|
653
|
+
function extractKindSignals(toolCall) {
|
|
654
|
+
const meta = getToolCallArtifactMeta(toolCall);
|
|
655
|
+
return {
|
|
656
|
+
artifactPath: String(meta?.path || toolCall?.args?.path || "").trim(),
|
|
657
|
+
metaKind: String(meta?.kind || "").trim(),
|
|
658
|
+
description: String(toolCall?.args?.description || "").trim()
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
function resolveReportArtifactKind(toolCall) {
|
|
662
|
+
const { artifactPath, metaKind, description } = extractKindSignals(toolCall);
|
|
663
|
+
if (pathSuggestsBody(artifactPath) || descriptionSuggestsBody(description)) return "report_body";
|
|
664
|
+
if (pathSuggestsOutline(artifactPath) || descriptionSuggestsOutline(description)) return "report_outline";
|
|
665
|
+
if (metaKind === "report_body" || metaKind === "report_outline") return metaKind;
|
|
666
|
+
return null;
|
|
667
|
+
}
|
|
668
|
+
function extractTitleFromArtifactPath(path, kind = "report_outline") {
|
|
669
|
+
const raw = String(path || "").trim();
|
|
670
|
+
if (!raw) return "\u62A5\u544A";
|
|
671
|
+
const base = raw.split("/").pop() || raw;
|
|
672
|
+
const noExt = base.replace(/\.(md|markdown|html?)$/i, "");
|
|
673
|
+
if (kind === "report_body") {
|
|
674
|
+
return noExt.replace(/_正文$/i, "").replace(/_报告$/i, "").replace(/\s*正文\s*$/i, "").trim() || "\u62A5\u544A";
|
|
675
|
+
}
|
|
676
|
+
return noExt.replace(/_大纲$/i, "").replace(/\s*大纲\s*$/i, "").trim() || "\u62A5\u544A";
|
|
677
|
+
}
|
|
678
|
+
var OUTLINE_MAX_LEVEL = 3;
|
|
679
|
+
function normalizeSubChapter(raw, level) {
|
|
680
|
+
const legacyChildren = raw.children ?? raw.points ?? [];
|
|
681
|
+
const title = String(raw.title ?? raw.pointTitle ?? "");
|
|
682
|
+
const children = level >= OUTLINE_MAX_LEVEL ? [] : legacyChildren.map((c) => normalizeSubChapter(c, level + 1));
|
|
683
|
+
return {
|
|
684
|
+
id: String(raw.id ?? genId()),
|
|
685
|
+
title,
|
|
686
|
+
summary: String(raw.summary ?? raw.pointSummary ?? ""),
|
|
687
|
+
contentTheme: String(raw.contentTheme ?? raw.pointDesc ?? ""),
|
|
688
|
+
children
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
function normalizeOutline(raw) {
|
|
692
|
+
if (!Array.isArray(raw)) return [];
|
|
693
|
+
const outline = raw.map((item) => {
|
|
694
|
+
const ch = item;
|
|
695
|
+
const legacyChildren = ch.children ?? ch.points ?? [];
|
|
696
|
+
return {
|
|
697
|
+
id: String(ch.id ?? genId()),
|
|
698
|
+
chapterTitle: String(ch.chapterTitle ?? ""),
|
|
699
|
+
chapterSummary: String(ch.chapterSummary ?? ch.chapterDesc ?? ""),
|
|
700
|
+
children: legacyChildren.map((c) => normalizeSubChapter(c, 2))
|
|
701
|
+
};
|
|
702
|
+
});
|
|
703
|
+
return ensureOutlineContentThemes(outline);
|
|
704
|
+
}
|
|
705
|
+
function validateOutline(outline) {
|
|
706
|
+
if (!outline?.length) return false;
|
|
707
|
+
return outline.every((ch) => String(ch.chapterTitle || "").trim().length > 0);
|
|
708
|
+
}
|
|
709
|
+
function createEmptySubChapter() {
|
|
710
|
+
return {
|
|
711
|
+
id: genId(),
|
|
712
|
+
title: "",
|
|
713
|
+
summary: "",
|
|
714
|
+
contentTheme: "",
|
|
715
|
+
children: []
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
function ensureOutlineContentThemes(outline) {
|
|
719
|
+
const walk = (nodes) => {
|
|
720
|
+
nodes.forEach((node) => {
|
|
721
|
+
if (node.summary === void 0 || node.summary === null) {
|
|
722
|
+
node.summary = "";
|
|
723
|
+
}
|
|
724
|
+
if (node.contentTheme === void 0 || node.contentTheme === null) {
|
|
725
|
+
node.contentTheme = "";
|
|
726
|
+
}
|
|
727
|
+
if (node.children?.length) walk(node.children);
|
|
728
|
+
});
|
|
729
|
+
};
|
|
730
|
+
outline.forEach((ch) => {
|
|
731
|
+
if (ch.chapterSummary === void 0 || ch.chapterSummary === null) {
|
|
732
|
+
ch.chapterSummary = "";
|
|
733
|
+
}
|
|
734
|
+
walk(ch.children || []);
|
|
735
|
+
});
|
|
736
|
+
return outline;
|
|
737
|
+
}
|
|
738
|
+
function detectLevelOneIsChapter(lines) {
|
|
739
|
+
const levelOneCount = lines.filter((line) => /^#\s+.+$/.test(line.trim())).length;
|
|
740
|
+
return levelOneCount > 1;
|
|
741
|
+
}
|
|
742
|
+
function joinLines(existing, text) {
|
|
743
|
+
return existing ? `${existing}
|
|
744
|
+
${text}` : text;
|
|
745
|
+
}
|
|
746
|
+
function appendBullet(state, text) {
|
|
747
|
+
const line = `- ${text}`;
|
|
748
|
+
const top = state.stack[state.stack.length - 1]?.node;
|
|
749
|
+
if (top) {
|
|
750
|
+
top.contentTheme = joinLines(top.contentTheme, line);
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
if (!state.currentChapter) return;
|
|
754
|
+
state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, line);
|
|
755
|
+
}
|
|
756
|
+
function appendSummaryText(state, text) {
|
|
757
|
+
if (!text) return;
|
|
758
|
+
const top = state.stack[state.stack.length - 1]?.node;
|
|
759
|
+
if (top) {
|
|
760
|
+
top.summary = joinLines(top.summary, text);
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
if (!state.currentChapter) return;
|
|
764
|
+
state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, text);
|
|
765
|
+
}
|
|
766
|
+
function appendPlainText(state, text) {
|
|
767
|
+
if (!text) return;
|
|
768
|
+
const top = state.stack[state.stack.length - 1]?.node;
|
|
769
|
+
if (top) {
|
|
770
|
+
top.contentTheme = joinLines(top.contentTheme, text);
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
if (!state.currentChapter) return;
|
|
774
|
+
state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, text);
|
|
775
|
+
}
|
|
776
|
+
function resolveTemplateName(title) {
|
|
777
|
+
return title.replace(/\s*·\s*大纲\s*$/i, "").replace(/\s*大纲\s*$/i, "").trim() || title;
|
|
778
|
+
}
|
|
779
|
+
function pushChapter(state, title) {
|
|
780
|
+
state.currentChapter = { id: genId(), chapterTitle: title, chapterSummary: "", children: [] };
|
|
781
|
+
state.outline.push(state.currentChapter);
|
|
782
|
+
state.stack.length = 0;
|
|
783
|
+
}
|
|
784
|
+
function pushSubChapter(state, level, title) {
|
|
785
|
+
const subChapterLevel = state.levelOneIsChapter ? level : level - 1;
|
|
786
|
+
if (subChapterLevel < 2 || !state.currentChapter) return false;
|
|
787
|
+
const sub = { id: genId(), title, summary: "", contentTheme: "", children: [] };
|
|
788
|
+
while (state.stack.length && state.stack[state.stack.length - 1].level >= subChapterLevel) {
|
|
789
|
+
state.stack.pop();
|
|
790
|
+
}
|
|
791
|
+
const parent = state.stack[state.stack.length - 1]?.node;
|
|
792
|
+
if (parent) parent.children.push(sub);
|
|
793
|
+
else state.currentChapter.children.push(sub);
|
|
794
|
+
state.stack.push({ node: sub, level: subChapterLevel });
|
|
795
|
+
return true;
|
|
796
|
+
}
|
|
797
|
+
function handleQuote(state, trimmed) {
|
|
798
|
+
if (!trimmed.startsWith(">")) return false;
|
|
799
|
+
const quoteText = trimmed.replace(/^(>\s*)+/, "").trim();
|
|
800
|
+
const summaryText = quoteText.replace(/^摘要\s*[::]\s*/i, "").trim();
|
|
801
|
+
appendSummaryText(state, summaryText || quoteText);
|
|
802
|
+
return true;
|
|
803
|
+
}
|
|
804
|
+
function handleHeading(state, trimmed) {
|
|
805
|
+
const heading = trimmed.match(/^(#{1,6})\s+(.+)$/);
|
|
806
|
+
if (!heading) return false;
|
|
807
|
+
const level = heading[1].length;
|
|
808
|
+
const title = heading[2].trim();
|
|
809
|
+
if (level === 1 && !state.levelOneIsChapter) {
|
|
810
|
+
state.templateName = resolveTemplateName(title);
|
|
811
|
+
return true;
|
|
812
|
+
}
|
|
813
|
+
if (level === 1 && state.levelOneIsChapter || level === 2 && !state.levelOneIsChapter) {
|
|
814
|
+
pushChapter(state, title);
|
|
815
|
+
return true;
|
|
816
|
+
}
|
|
817
|
+
return pushSubChapter(state, level, title);
|
|
818
|
+
}
|
|
819
|
+
function parseMarkdownToOutline(markdown) {
|
|
820
|
+
const lines = String(markdown || "").split(/\r?\n/);
|
|
821
|
+
const state = {
|
|
822
|
+
templateName: "",
|
|
823
|
+
outline: [],
|
|
824
|
+
currentChapter: null,
|
|
825
|
+
stack: [],
|
|
826
|
+
levelOneIsChapter: detectLevelOneIsChapter(lines)
|
|
827
|
+
};
|
|
828
|
+
for (const line of lines) {
|
|
829
|
+
const trimmed = line.trim();
|
|
830
|
+
if (!trimmed || trimmed === "---" || /^```/.test(trimmed)) continue;
|
|
831
|
+
if (handleQuote(state, trimmed)) continue;
|
|
832
|
+
if (handleHeading(state, trimmed)) continue;
|
|
833
|
+
const bullet = trimmed.match(/^[-*]\s+(.+)$/);
|
|
834
|
+
if (bullet) {
|
|
835
|
+
appendBullet(state, bullet[1].trim());
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
appendPlainText(state, trimmed);
|
|
839
|
+
}
|
|
840
|
+
return {
|
|
841
|
+
templateName: state.templateName || "\u62A5\u544A",
|
|
842
|
+
outline: normalizeOutline(state.outline)
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
var HTML_LIKE = /^\s*</;
|
|
846
|
+
function isReportBodyHtml(content) {
|
|
847
|
+
const s = String(content || "").trim();
|
|
848
|
+
if (!s) return false;
|
|
849
|
+
return HTML_LIKE.test(s);
|
|
850
|
+
}
|
|
851
|
+
function extractReportTitleFromBody(content, fallback = "") {
|
|
852
|
+
const s = String(content || "").trim();
|
|
853
|
+
if (!s) return fallback;
|
|
854
|
+
if (isReportBodyHtml(s)) {
|
|
855
|
+
const h1 = s.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);
|
|
856
|
+
if (h1?.[1]) {
|
|
857
|
+
const t = h1[1].replace(/<[^>]+>/g, "").trim();
|
|
858
|
+
if (t) return t;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
const heading = s.match(/^#\s+(.+)$/m);
|
|
862
|
+
if (heading?.[1]) return heading[1].trim();
|
|
863
|
+
return fallback;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// src/parser/group-builder-helper.ts
|
|
867
|
+
function isHumanMessage(msg) {
|
|
868
|
+
return String(asSxin(msg).type || "") === "human";
|
|
869
|
+
}
|
|
870
|
+
function parseHumanMessageId(id) {
|
|
871
|
+
const raw = String(id || "");
|
|
872
|
+
const match = raw.match(/^(.*?)__(memory|user)(\([^)]*\))?$/i);
|
|
873
|
+
if (!match) return { baseId: raw, variant: null };
|
|
874
|
+
return { baseId: match[1], variant: match[2].toLowerCase() };
|
|
875
|
+
}
|
|
876
|
+
function getHumanMessageBaseId(id) {
|
|
877
|
+
return parseHumanMessageId(id).baseId;
|
|
878
|
+
}
|
|
879
|
+
function isAiMessage(msg) {
|
|
880
|
+
const t = String(asSxin(msg).type || "");
|
|
881
|
+
return ["ai", "AIMessage", "AIMessageChunk"].includes(t);
|
|
882
|
+
}
|
|
883
|
+
function isToolMessage(msg) {
|
|
884
|
+
return String(asSxin(msg).type || "") === "tool";
|
|
885
|
+
}
|
|
886
|
+
function deriveToolsFromMessages(messages) {
|
|
887
|
+
const tools = [];
|
|
888
|
+
const byId = /* @__PURE__ */ new Map();
|
|
889
|
+
for (const msg of messages) {
|
|
890
|
+
const m = asSxin(msg);
|
|
891
|
+
const toolCalls = m.tool_calls;
|
|
892
|
+
if (Array.isArray(toolCalls)) {
|
|
893
|
+
for (const tc of toolCalls) {
|
|
894
|
+
const id = String(tc?.id || "").trim();
|
|
895
|
+
if (!id || byId.has(id)) continue;
|
|
896
|
+
const tool = { id, call: tc, aiMessage: msg, state: "pending", index: tools.length };
|
|
897
|
+
byId.set(id, tool);
|
|
898
|
+
tools.push(tool);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
const toolCallId = String(m.tool_call_id || "").trim();
|
|
902
|
+
if (!toolCallId) continue;
|
|
903
|
+
const state = m.status === "error" ? "error" : "completed";
|
|
904
|
+
const existing = byId.get(toolCallId);
|
|
905
|
+
if (existing) {
|
|
906
|
+
existing.result = msg;
|
|
907
|
+
existing.state = state;
|
|
908
|
+
} else {
|
|
909
|
+
const tool = {
|
|
910
|
+
id: toolCallId,
|
|
911
|
+
call: { id: toolCallId, name: String(m.name || ""), args: {} },
|
|
912
|
+
result: msg,
|
|
913
|
+
state,
|
|
914
|
+
index: tools.length
|
|
915
|
+
};
|
|
916
|
+
byId.set(toolCallId, tool);
|
|
917
|
+
tools.push(tool);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
return tools;
|
|
921
|
+
}
|
|
922
|
+
function normalizeUsage(raw) {
|
|
923
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
924
|
+
const r = raw;
|
|
925
|
+
const inputTokens = readAliasedNumber(r, ["input_tokens", "inputTokens", "prompt_tokens", "promptTokens"]);
|
|
926
|
+
const outputTokens = readAliasedNumber(r, ["output_tokens", "outputTokens", "completion_tokens", "completionTokens"]);
|
|
927
|
+
const totalTokens = readAliasedNumber(r, ["total_tokens", "totalTokens"]);
|
|
928
|
+
if ([inputTokens, outputTokens, totalTokens].every(Number.isNaN)) {
|
|
929
|
+
return void 0;
|
|
930
|
+
}
|
|
931
|
+
const usage = {
|
|
932
|
+
input_tokens: toZeroIfNaN(inputTokens),
|
|
933
|
+
output_tokens: toZeroIfNaN(outputTokens),
|
|
934
|
+
total_tokens: toZeroIfNaN(totalTokens)
|
|
935
|
+
};
|
|
936
|
+
applyUsageDetails(usage, r);
|
|
937
|
+
return usage;
|
|
938
|
+
}
|
|
939
|
+
function readAliasedNumber(r, aliases) {
|
|
940
|
+
for (const key of aliases) {
|
|
941
|
+
if (r[key] !== void 0 && r[key] !== null) return Number(r[key]);
|
|
942
|
+
}
|
|
943
|
+
return NaN;
|
|
944
|
+
}
|
|
945
|
+
function toZeroIfNaN(n) {
|
|
946
|
+
return Number.isNaN(n) ? 0 : n;
|
|
947
|
+
}
|
|
948
|
+
function applyUsageDetails(usage, r) {
|
|
949
|
+
const cacheRead = Number(r.input_token_details?.cache_read ?? r.input_token_details?.cacheRead);
|
|
950
|
+
if (!Number.isNaN(cacheRead)) {
|
|
951
|
+
usage.input_token_details = { cache_read: cacheRead };
|
|
952
|
+
}
|
|
953
|
+
const reasoning = Number(r.output_token_details?.reasoning ?? r.output_token_details?.reasoningTokens);
|
|
954
|
+
if (!Number.isNaN(reasoning)) {
|
|
955
|
+
usage.output_token_details = { reasoning };
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// src/parser/body-segments.ts
|
|
960
|
+
var SEGMENT_TAGS = /* @__PURE__ */ new Set(["sxin-list", "sxin-item"]);
|
|
961
|
+
function visibleTextOf(node) {
|
|
962
|
+
if (node.type === "text") return node.value;
|
|
963
|
+
if (node.type === "comment") return "";
|
|
964
|
+
return node.children.map(visibleTextOf).join("");
|
|
965
|
+
}
|
|
966
|
+
function toItemSegment(el, source) {
|
|
967
|
+
return {
|
|
968
|
+
type: "item",
|
|
969
|
+
tag: "sxin-item",
|
|
970
|
+
attrs: { ...el.attrs },
|
|
971
|
+
content: visibleTextOf(el) || void 0,
|
|
972
|
+
raw: source.slice(el.start, el.end)
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
function toListSegment(el, source) {
|
|
976
|
+
const children = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-item").map((c) => toItemSegment(c, source));
|
|
977
|
+
return { type: "list", tag: "sxin-list", attrs: { ...el.attrs }, children, raw: source.slice(el.start, el.end) };
|
|
978
|
+
}
|
|
979
|
+
function sliceBodySegments(body) {
|
|
980
|
+
const source = String(body ?? "");
|
|
981
|
+
const segments = [];
|
|
982
|
+
let textBuf = "";
|
|
983
|
+
const flushText = () => {
|
|
984
|
+
if (!textBuf) return;
|
|
985
|
+
segments.push({ type: "text", content: textBuf });
|
|
986
|
+
textBuf = "";
|
|
987
|
+
};
|
|
988
|
+
for (const node of tokenizeSxin(source)) {
|
|
989
|
+
if (node.type === "element" && SEGMENT_TAGS.has(node.tagName)) {
|
|
990
|
+
flushText();
|
|
991
|
+
segments.push(node.tagName === "sxin-list" ? toListSegment(node, source) : toItemSegment(node, source));
|
|
992
|
+
} else if (node.type === "comment") {
|
|
993
|
+
continue;
|
|
994
|
+
} else if (node.type === "text") {
|
|
995
|
+
textBuf += node.value;
|
|
996
|
+
} else {
|
|
997
|
+
textBuf += source.slice(node.start, node.end);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
flushText();
|
|
1001
|
+
if (!segments.length) segments.push({ type: "text", content: "" });
|
|
1002
|
+
return segments;
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
// src/runtime/run-info.ts
|
|
1006
|
+
function buildRunInfo(run, threadId) {
|
|
1007
|
+
return {
|
|
1008
|
+
runId: String(run?.run_id || "").trim(),
|
|
1009
|
+
threadId: String(threadId || "").trim(),
|
|
1010
|
+
usage: buildRunUsage(run),
|
|
1011
|
+
latencyMs: buildRunLatencyMs(run),
|
|
1012
|
+
finishReason: toOptionalString(run?.stop_reason ?? run?.finish_reason),
|
|
1013
|
+
modelName: toOptionalString(run?.model_name),
|
|
1014
|
+
status: buildRunStatus(run),
|
|
1015
|
+
createdAt: buildRunCreatedAt(run)
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
function toOptionalString(value) {
|
|
1019
|
+
return value ? String(value) : void 0;
|
|
1020
|
+
}
|
|
1021
|
+
function buildRunUsage(run) {
|
|
1022
|
+
return normalizeUsage({
|
|
1023
|
+
input_tokens: run?.total_input_tokens,
|
|
1024
|
+
output_tokens: run?.total_output_tokens,
|
|
1025
|
+
total_tokens: run?.total_tokens
|
|
1026
|
+
});
|
|
1027
|
+
}
|
|
1028
|
+
function buildRunStatus(run) {
|
|
1029
|
+
return run?.status ? String(run.status) : void 0;
|
|
1030
|
+
}
|
|
1031
|
+
function buildRunCreatedAt(run) {
|
|
1032
|
+
return run?.created_at ? Number(new Date(run.created_at)) : void 0;
|
|
1033
|
+
}
|
|
1034
|
+
function buildRunDirectLatencyMs(run) {
|
|
1035
|
+
const direct = Number(run?.latency_ms);
|
|
1036
|
+
return direct || void 0;
|
|
1037
|
+
}
|
|
1038
|
+
function buildRunLatencyMs(run) {
|
|
1039
|
+
const direct = buildRunDirectLatencyMs(run);
|
|
1040
|
+
if (direct !== void 0) return direct;
|
|
1041
|
+
const created = Date.parse(String(run?.created_at ?? ""));
|
|
1042
|
+
const updated = Date.parse(String(run?.updated_at ?? ""));
|
|
1043
|
+
if (Number.isNaN(created) || Number.isNaN(updated)) return void 0;
|
|
1044
|
+
const diff = updated - created;
|
|
1045
|
+
return diff >= 0 ? diff : void 0;
|
|
1046
|
+
}
|
|
1047
|
+
function pickRunMessageMetadata(messages) {
|
|
1048
|
+
let modelName;
|
|
1049
|
+
let finishReason;
|
|
1050
|
+
for (const msg of messages) {
|
|
1051
|
+
if (!isAiMessage(msg)) {
|
|
1052
|
+
continue;
|
|
1053
|
+
}
|
|
1054
|
+
const responseMetadata = msg?.response_metadata || {};
|
|
1055
|
+
if (!modelName && responseMetadata.model_name) {
|
|
1056
|
+
modelName = String(responseMetadata.model_name);
|
|
1057
|
+
}
|
|
1058
|
+
if (!finishReason && responseMetadata.finish_reason) {
|
|
1059
|
+
finishReason = String(responseMetadata.finish_reason);
|
|
1060
|
+
}
|
|
1061
|
+
if (modelName && finishReason) {
|
|
1062
|
+
break;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
return { modelName, finishReason };
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
// src/runtime/semantic-overlay.ts
|
|
1069
|
+
var extractKwargsPatch = (msg) => {
|
|
1070
|
+
const kwargs = msg?.additional_kwargs;
|
|
1071
|
+
if (!kwargs || typeof kwargs !== "object") return void 0;
|
|
1072
|
+
const patch = {};
|
|
1073
|
+
if (kwargs.hide_from_ui === true) patch.hide_from_ui = true;
|
|
1074
|
+
if (kwargs.human_input_response && typeof kwargs.human_input_response === "object") {
|
|
1075
|
+
patch.human_input_response = kwargs.human_input_response;
|
|
1076
|
+
}
|
|
1077
|
+
return Object.keys(patch).length ? patch : void 0;
|
|
1078
|
+
};
|
|
1079
|
+
function extractSemanticPatchesFromMessages(messages) {
|
|
1080
|
+
const next = /* @__PURE__ */ new Map();
|
|
1081
|
+
for (const m of messages ?? []) {
|
|
1082
|
+
const id = String(m?.id || "").trim();
|
|
1083
|
+
if (!id) continue;
|
|
1084
|
+
const patch = { id };
|
|
1085
|
+
if (String(m?.type || "") === "ai" && hasKbCitationMessage(m)) {
|
|
1086
|
+
patch.content = m.content;
|
|
1087
|
+
}
|
|
1088
|
+
if (String(m?.type || "") === "human") {
|
|
1089
|
+
const kwargs = extractKwargsPatch(m);
|
|
1090
|
+
if (kwargs) patch.additional_kwargs = kwargs;
|
|
1091
|
+
}
|
|
1092
|
+
if (patch.content !== void 0 || patch.additional_kwargs) next.set(id, patch);
|
|
1093
|
+
}
|
|
1094
|
+
return next;
|
|
1095
|
+
}
|
|
1096
|
+
function createSemanticOverlay() {
|
|
1097
|
+
let patches = /* @__PURE__ */ new Map();
|
|
1098
|
+
return {
|
|
1099
|
+
applyState(state) {
|
|
1100
|
+
const messages = extractStateMessages(state);
|
|
1101
|
+
patches = extractSemanticPatchesFromMessages(messages);
|
|
1102
|
+
const citedIds = messages.filter((m) => String(m?.type || "") === "ai" && hasKbCitationMessage(m)).map((m) => String(m?.id || "")).filter(Boolean);
|
|
1103
|
+
return { patched: patches.size, citedIds };
|
|
1104
|
+
},
|
|
1105
|
+
getPatches() {
|
|
1106
|
+
return new Map(patches);
|
|
1107
|
+
},
|
|
1108
|
+
invalidate() {
|
|
1109
|
+
patches = /* @__PURE__ */ new Map();
|
|
1110
|
+
}
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
function applySemanticPatches(messages, patches) {
|
|
1114
|
+
if (!patches.size || !messages.length) return messages;
|
|
1115
|
+
return messages.map((m) => {
|
|
1116
|
+
const id = String(m?.id || "").trim();
|
|
1117
|
+
const patch = id ? patches.get(id) : void 0;
|
|
1118
|
+
if (!patch) return m;
|
|
1119
|
+
let next = m;
|
|
1120
|
+
if (patch.content !== void 0 && String(next?.type || "") === "ai" && !hasKbCitationMessage(next)) {
|
|
1121
|
+
next = { ...next, content: patch.content };
|
|
1122
|
+
}
|
|
1123
|
+
const localKwargs = next?.additional_kwargs;
|
|
1124
|
+
if (patch.additional_kwargs && Object.keys(patch.additional_kwargs).length) {
|
|
1125
|
+
const merged = { ...localKwargs };
|
|
1126
|
+
let changed = false;
|
|
1127
|
+
for (const [k, v] of Object.entries(patch.additional_kwargs)) {
|
|
1128
|
+
if (merged[k] === void 0) {
|
|
1129
|
+
merged[k] = v;
|
|
1130
|
+
changed = true;
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
if (changed) next = { ...next, additional_kwargs: merged };
|
|
1134
|
+
}
|
|
1135
|
+
return next;
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
// src/materializer/extractors.ts
|
|
1140
|
+
function normalizeName(name) {
|
|
1141
|
+
const n = String(name || "").trim().toLowerCase();
|
|
1142
|
+
return n === "write_files" ? "write_file" : n;
|
|
1143
|
+
}
|
|
1144
|
+
function tryParseObject(result) {
|
|
1145
|
+
const text = String(result ?? "").trim();
|
|
1146
|
+
if (!text.startsWith("{")) return null;
|
|
1147
|
+
try {
|
|
1148
|
+
const parsed = JSON.parse(text);
|
|
1149
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
1150
|
+
return parsed;
|
|
1151
|
+
} catch {
|
|
1152
|
+
return null;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
function extractFromToolResult(name, result, toolCallLike) {
|
|
1156
|
+
const tool = normalizeName(name);
|
|
1157
|
+
const obj = tryParseObject(result);
|
|
1158
|
+
if (tool === "ask_clarification" && obj) {
|
|
1159
|
+
const question = obj.question ?? obj.title;
|
|
1160
|
+
if (typeof question !== "string" || !question.trim()) return void 0;
|
|
1161
|
+
const options = Array.isArray(obj.options) ? obj.options : void 0;
|
|
1162
|
+
return options ? { kind: "clarification", question, options } : { kind: "clarification", question };
|
|
1163
|
+
}
|
|
1164
|
+
if (tool === "write_file") {
|
|
1165
|
+
if (obj) {
|
|
1166
|
+
if (typeof obj.body === "string" && obj.body) {
|
|
1167
|
+
const outline = typeof obj.outline === "string" ? obj.outline : void 0;
|
|
1168
|
+
return outline ? { kind: "report", reportKind: "report_body", body: obj.body, outline } : { kind: "report", reportKind: "report_body", body: obj.body };
|
|
1169
|
+
}
|
|
1170
|
+
if (Array.isArray(obj.files) && obj.files.length) {
|
|
1171
|
+
return { kind: "artifact", files: obj.files };
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
const reportKind = resolveReportArtifactKind(toolCallLike);
|
|
1175
|
+
if (reportKind) {
|
|
1176
|
+
const tc = toolCallLike ?? {};
|
|
1177
|
+
const sourcePath = String(tc?.artifact_meta?.path || tc?.args?.path || "").trim() || void 0;
|
|
1178
|
+
return {
|
|
1179
|
+
kind: "report",
|
|
1180
|
+
reportKind,
|
|
1181
|
+
sourcePath,
|
|
1182
|
+
title: sourcePath ? extractTitleFromArtifactPath(sourcePath, reportKind) : void 0
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
return void 0;
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// src/materializer/diff.ts
|
|
1190
|
+
function diffMessageSnapshots(baseline, next) {
|
|
1191
|
+
const upserts = [];
|
|
1192
|
+
const nextBaseline = /* @__PURE__ */ new Map();
|
|
1193
|
+
for (const msg of next) {
|
|
1194
|
+
const id = String(msg?.id || "").trim();
|
|
1195
|
+
if (!id) continue;
|
|
1196
|
+
if (baseline.get(id) !== msg) upserts.push(msg);
|
|
1197
|
+
nextBaseline.set(id, msg);
|
|
1198
|
+
}
|
|
1199
|
+
const removals = [];
|
|
1200
|
+
for (const id of baseline.keys()) if (!nextBaseline.has(id)) removals.push(id);
|
|
1201
|
+
return { upserts, removals, nextBaseline };
|
|
1202
|
+
}
|
|
1203
|
+
function createMessageDiff() {
|
|
1204
|
+
let baseline = /* @__PURE__ */ new Map();
|
|
1205
|
+
return {
|
|
1206
|
+
apply(next) {
|
|
1207
|
+
const { upserts, removals, nextBaseline } = diffMessageSnapshots(baseline, next);
|
|
1208
|
+
const deltas = [];
|
|
1209
|
+
for (const msg of upserts) {
|
|
1210
|
+
const id = String(msg?.id || "").trim();
|
|
1211
|
+
deltas.push(baseline.has(id) ? { type: "update", id, message: msg } : { type: "append", message: msg });
|
|
1212
|
+
}
|
|
1213
|
+
for (const id of removals) deltas.push({ type: "tail-remove", id });
|
|
1214
|
+
baseline = nextBaseline;
|
|
1215
|
+
return deltas;
|
|
1216
|
+
},
|
|
1217
|
+
reset() {
|
|
1218
|
+
baseline = /* @__PURE__ */ new Map();
|
|
1219
|
+
},
|
|
1220
|
+
get baselineSize() {
|
|
1221
|
+
return baseline.size;
|
|
1222
|
+
}
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
// src/materializer/materializer.ts
|
|
1227
|
+
import { shallowRef } from "vue";
|
|
1228
|
+
|
|
1229
|
+
// src/materializer/indexes.ts
|
|
1230
|
+
function createIndexes() {
|
|
1231
|
+
return { byMessageId: /* @__PURE__ */ new Map(), byToolCallId: /* @__PURE__ */ new Map(), byRunId: /* @__PURE__ */ new Map() };
|
|
1232
|
+
}
|
|
1233
|
+
function rebuildIndexes(turns) {
|
|
1234
|
+
const idx = createIndexes();
|
|
1235
|
+
turns.forEach((turn, ti) => {
|
|
1236
|
+
idx.byMessageId.set(turn.id, { turn: ti, ai: null });
|
|
1237
|
+
idx.byRunId.set(turn.runId, { turn: ti, ai: 0 });
|
|
1238
|
+
turn.ai.forEach((seg, ai_i) => {
|
|
1239
|
+
idx.byMessageId.set(seg.id, { turn: ti, ai: ai_i });
|
|
1240
|
+
for (const mid of seg.messageIds ?? []) {
|
|
1241
|
+
if (mid) idx.byMessageId.set(mid, { turn: ti, ai: ai_i });
|
|
1242
|
+
}
|
|
1243
|
+
idx.byRunId.set(seg.runId, { turn: ti, ai: ai_i });
|
|
1244
|
+
seg.tools.forEach((tool, tool_i) => {
|
|
1245
|
+
idx.byToolCallId.set(tool.callId, { turn: ti, ai: ai_i, tool: tool_i });
|
|
1246
|
+
});
|
|
1247
|
+
});
|
|
1248
|
+
});
|
|
1249
|
+
return idx;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
// src/materializer/turn-machine-rules.ts
|
|
1253
|
+
function messageRunId(msg) {
|
|
1254
|
+
const own = String(asSxin(msg).runId || "").trim();
|
|
1255
|
+
if (own) return own;
|
|
1256
|
+
return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
|
|
1257
|
+
}
|
|
1258
|
+
function isHiddenHuman(msg) {
|
|
1259
|
+
return msg?.additional_kwargs?.hide_from_ui === true;
|
|
1260
|
+
}
|
|
1261
|
+
function hasEmptyKwargs(msg) {
|
|
1262
|
+
const kwargs = msg?.additional_kwargs;
|
|
1263
|
+
return !kwargs || typeof kwargs !== "object" || Object.keys(kwargs).length === 0;
|
|
1264
|
+
}
|
|
1265
|
+
function resolveHumanKwargsMerge(prevKwargs, incomingKwargs, incomingIsVariant) {
|
|
1266
|
+
if (incomingIsVariant) return prevKwargs;
|
|
1267
|
+
const prevEmpty = !prevKwargs || typeof prevKwargs !== "object" || Object.keys(prevKwargs).length === 0;
|
|
1268
|
+
return prevEmpty ? incomingKwargs : prevKwargs;
|
|
1269
|
+
}
|
|
1270
|
+
function readHir(msg) {
|
|
1271
|
+
const response = msg?.additional_kwargs?.human_input_response;
|
|
1272
|
+
if (!response || typeof response !== "object") return null;
|
|
1273
|
+
const requestId = String(response.request_id || "").trim().replace("clarification:", "");
|
|
1274
|
+
if (!requestId || response.value === void 0) return null;
|
|
1275
|
+
return { requestId, value: response.value };
|
|
1276
|
+
}
|
|
1277
|
+
function buildClarification(tool) {
|
|
1278
|
+
if (tool.name !== "ask_clarification") return null;
|
|
1279
|
+
const args = tool.input ?? {};
|
|
1280
|
+
const question = typeof args.question === "string" ? args.question : "";
|
|
1281
|
+
if (!question) return null;
|
|
1282
|
+
const fields = Array.isArray(args.fields) ? args.fields : void 0;
|
|
1283
|
+
return {
|
|
1284
|
+
callId: tool.callId,
|
|
1285
|
+
question,
|
|
1286
|
+
...args.options !== void 0 ? { options: args.options } : {},
|
|
1287
|
+
...fields?.length ? { fields } : {}
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
function createTurnRules(ctx) {
|
|
1291
|
+
const { state } = ctx;
|
|
1292
|
+
const registerToolCalls = (ti, ai_i, msg, effects) => {
|
|
1293
|
+
const toolCalls = msg?.tool_calls;
|
|
1294
|
+
if (!Array.isArray(toolCalls) || !toolCalls.length) return;
|
|
1295
|
+
let turn = state.turns[ti];
|
|
1296
|
+
for (const tc of toolCalls) {
|
|
1297
|
+
const callId = String(tc?.id || "").trim();
|
|
1298
|
+
if (!callId || ctx.indexes().byToolCallId.has(callId)) continue;
|
|
1299
|
+
const tool = {
|
|
1300
|
+
callId,
|
|
1301
|
+
name: String(tc?.name || ""),
|
|
1302
|
+
input: tc?.args,
|
|
1303
|
+
artifactMeta: tc?.artifact_meta,
|
|
1304
|
+
status: "running"
|
|
1305
|
+
};
|
|
1306
|
+
turn = ctx.cloneWith(turn, ai_i, (t) => {
|
|
1307
|
+
t.ai[ai_i].tools = [...turn.ai[ai_i].tools, tool];
|
|
1308
|
+
});
|
|
1309
|
+
const tool_i = turn.ai[ai_i].tools.length - 1;
|
|
1310
|
+
ctx.indexes().byToolCallId.set(callId, { turn: ti, ai: ai_i, tool: tool_i });
|
|
1311
|
+
effects.push({ type: "tool-updated", turnId: turn.id, aiId: turn.ai[ai_i].id, tool });
|
|
1312
|
+
const clarification = buildClarification(tool);
|
|
1313
|
+
if (clarification) {
|
|
1314
|
+
turn = ctx.cloneWith(turn, null, (t) => {
|
|
1315
|
+
t.clarifications = [...turn.clarifications, clarification];
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
state.turns[ti] = turn;
|
|
1320
|
+
};
|
|
1321
|
+
const openNewAi = (ti, msg, effects) => {
|
|
1322
|
+
let turn = state.turns[ti];
|
|
1323
|
+
if (state.openAi !== null) {
|
|
1324
|
+
turn = ctx.sealAiSegment(turn, state.openAi, effects);
|
|
1325
|
+
}
|
|
1326
|
+
const runId = messageRunId(msg) || ctx.streamRunId() || "";
|
|
1327
|
+
const body = readMessageContentText(msg);
|
|
1328
|
+
const seg = {
|
|
1329
|
+
id: String(msg?.id || ""),
|
|
1330
|
+
runId,
|
|
1331
|
+
body,
|
|
1332
|
+
streamingText: body,
|
|
1333
|
+
tools: [],
|
|
1334
|
+
attachments: [],
|
|
1335
|
+
segments: [{ type: "text", content: body }],
|
|
1336
|
+
status: "streaming",
|
|
1337
|
+
// 段内消息 id 登记(rebuildIndexes 重建 byMessageId 的依据,防 finalize 后 update 索引 miss)
|
|
1338
|
+
messageIds: [String(msg?.id || "")].filter(Boolean)
|
|
1339
|
+
};
|
|
1340
|
+
turn = ctx.cloneWith(turn, null, (t) => {
|
|
1341
|
+
t.ai = [...turn.ai, seg];
|
|
1342
|
+
if (!t.runId && runId) t.runId = runId;
|
|
1343
|
+
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1344
|
+
});
|
|
1345
|
+
state.turns[ti] = turn;
|
|
1346
|
+
state.openAi = turn.ai.length - 1;
|
|
1347
|
+
ctx.indexes().byRunId.set(runId, { turn: ti, ai: state.openAi });
|
|
1348
|
+
if (seg.id) ctx.indexes().byMessageId.set(seg.id, { turn: ti, ai: state.openAi });
|
|
1349
|
+
effects.push({ type: "ai-opened", turnId: turn.id, ai: turn.ai[turn.ai.length - 1] });
|
|
1350
|
+
registerToolCalls(ti, state.openAi, msg, effects);
|
|
1351
|
+
};
|
|
1352
|
+
const appendHuman = (msg, allowOptimistic, effects) => {
|
|
1353
|
+
const id = String(msg?.id || "").trim();
|
|
1354
|
+
const baseId = getHumanMessageBaseId(id) || id;
|
|
1355
|
+
const msgRunId = String(msg?.additional_kwargs?.run_id || "").trim();
|
|
1356
|
+
if (msgRunId) {
|
|
1357
|
+
for (let ti = state.turns.length - 1; ti >= 0; ti--) {
|
|
1358
|
+
const t = state.turns[ti];
|
|
1359
|
+
const tBase = getHumanMessageBaseId(t.human.id) || t.human.id;
|
|
1360
|
+
const tRun = String(t.human.kwargs?.run_id || "").trim();
|
|
1361
|
+
if (tBase === baseId && tRun && tRun === msgRunId) {
|
|
1362
|
+
const mergedKwargs = resolveHumanKwargsMerge(
|
|
1363
|
+
t.human.kwargs,
|
|
1364
|
+
msg?.additional_kwargs,
|
|
1365
|
+
baseId !== id
|
|
1366
|
+
);
|
|
1367
|
+
const next = ctx.cloneWith(t, null, (t2) => {
|
|
1368
|
+
t2.human = {
|
|
1369
|
+
id: t.human.id || id,
|
|
1370
|
+
text: t.human.text || extractTextFromMessage(msg),
|
|
1371
|
+
kwargs: mergedKwargs
|
|
1372
|
+
};
|
|
1373
|
+
t2.rawMessages = [...t2.rawMessages ?? [], msg];
|
|
1374
|
+
});
|
|
1375
|
+
state.turns[ti] = next;
|
|
1376
|
+
if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
|
|
1377
|
+
effects.push({ type: "message-updated", turnId: next.id, aiId: null });
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
if (state.openTurn !== null && !state.turns[state.openTurn].ai.length) {
|
|
1383
|
+
const openHumanBase = getHumanMessageBaseId(state.turns[state.openTurn].human.id);
|
|
1384
|
+
if (openHumanBase && openHumanBase === baseId) {
|
|
1385
|
+
const ti = state.openTurn;
|
|
1386
|
+
const mergedKwargs = resolveHumanKwargsMerge(
|
|
1387
|
+
state.turns[ti].human.kwargs,
|
|
1388
|
+
msg?.additional_kwargs,
|
|
1389
|
+
baseId !== id
|
|
1390
|
+
);
|
|
1391
|
+
const next = ctx.cloneWith(state.turns[ti], null, (t) => {
|
|
1392
|
+
t.human = { id, text: extractTextFromMessage(msg), kwargs: mergedKwargs };
|
|
1393
|
+
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1394
|
+
});
|
|
1395
|
+
state.turns[ti] = next;
|
|
1396
|
+
ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
|
|
1397
|
+
effects.push({ type: "message-updated", turnId: next.id, aiId: null });
|
|
1398
|
+
return;
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
const optimistic = allowOptimistic && !!id && !ctx.indexes().byMessageId.has(id) && !messageRunId(msg) && hasEmptyKwargs(msg);
|
|
1402
|
+
ctx.sealOpenTurn(effects);
|
|
1403
|
+
const turn = {
|
|
1404
|
+
id: id || `turn-${state.turns.length}`,
|
|
1405
|
+
runId: "",
|
|
1406
|
+
createdAt: Number(new Date(msg?.created_at || Date.now())) || Date.now(),
|
|
1407
|
+
human: { id, text: extractTextFromMessage(msg), kwargs: msg?.additional_kwargs },
|
|
1408
|
+
ai: [],
|
|
1409
|
+
clarifications: [],
|
|
1410
|
+
status: "streaming",
|
|
1411
|
+
optimistic,
|
|
1412
|
+
// 原始消息入档(排查用)
|
|
1413
|
+
rawMessages: [msg]
|
|
1414
|
+
};
|
|
1415
|
+
state.turns.push(turn);
|
|
1416
|
+
state.openTurn = state.turns.length - 1;
|
|
1417
|
+
if (id) ctx.indexes().byMessageId.set(id, { turn: state.openTurn, ai: null });
|
|
1418
|
+
if (optimistic) state.optimisticTurnId = turn.id;
|
|
1419
|
+
effects.push({ type: "turn-opened", turn, optimistic });
|
|
1420
|
+
};
|
|
1421
|
+
const appendHiddenHuman = (msg, effects) => {
|
|
1422
|
+
const hir = readHir(msg);
|
|
1423
|
+
if (!hir) return;
|
|
1424
|
+
const toolLoc = ctx.indexes().byToolCallId.get(hir.requestId);
|
|
1425
|
+
const ti = toolLoc?.turn ?? state.openTurn ?? state.turns.length - 1;
|
|
1426
|
+
if (ti < 0) return;
|
|
1427
|
+
const turn = state.turns[ti];
|
|
1428
|
+
const ci = turn.clarifications.findIndex((c) => c.callId === hir.requestId);
|
|
1429
|
+
if (ci < 0) return;
|
|
1430
|
+
const answer = formatAnswerText(hir.value);
|
|
1431
|
+
const id = String(msg?.id || "").trim();
|
|
1432
|
+
const next = ctx.cloneWith(turn, null, (t) => {
|
|
1433
|
+
t.clarifications[ci] = { ...t.clarifications[ci], answer, answerMessageId: id || void 0 };
|
|
1434
|
+
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1435
|
+
});
|
|
1436
|
+
state.turns[ti] = next;
|
|
1437
|
+
if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
|
|
1438
|
+
effects.push({ type: "clarification-answered", turnId: next.id, callId: hir.requestId, answer });
|
|
1439
|
+
};
|
|
1440
|
+
const applyToolMessage = (msg, effects) => {
|
|
1441
|
+
const m = msg;
|
|
1442
|
+
const callId = String(m?.tool_call_id || "").trim();
|
|
1443
|
+
if (!callId) return;
|
|
1444
|
+
const result = readMessageContentText(m);
|
|
1445
|
+
const status = m?.status === "error" ? "error" : "finished";
|
|
1446
|
+
const id = String(m?.id || "").trim();
|
|
1447
|
+
const loc = ctx.indexes().byToolCallId.get(callId);
|
|
1448
|
+
if (loc) {
|
|
1449
|
+
const turn2 = state.turns[loc.turn];
|
|
1450
|
+
const old = turn2.ai[loc.ai].tools[loc.tool];
|
|
1451
|
+
const tool = {
|
|
1452
|
+
...old,
|
|
1453
|
+
status,
|
|
1454
|
+
result,
|
|
1455
|
+
extracted: extractFromToolResult(old.name, result, { artifact_meta: old.artifactMeta, args: old.input }) ?? old.extracted
|
|
1456
|
+
};
|
|
1457
|
+
const next2 = ctx.cloneWith(turn2, loc.ai, (t) => {
|
|
1458
|
+
t.ai[loc.ai].tools[loc.tool] = tool;
|
|
1459
|
+
if (t.ai[loc.ai].status === "sealed") t.ai[loc.ai].attachments = ctx.assembleAttachments(t.ai[loc.ai]);
|
|
1460
|
+
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1461
|
+
});
|
|
1462
|
+
state.turns[loc.turn] = next2;
|
|
1463
|
+
if (id) ctx.indexes().byMessageId.set(id, { turn: loc.turn, ai: loc.ai });
|
|
1464
|
+
effects.push({ type: "tool-updated", turnId: next2.id, aiId: next2.ai[loc.ai].id, tool });
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
const ti = state.openTurn;
|
|
1468
|
+
const ai_i = state.openAi;
|
|
1469
|
+
if (ti === null || ai_i === null) return;
|
|
1470
|
+
const orphan = {
|
|
1471
|
+
callId,
|
|
1472
|
+
name: String(m?.name || ""),
|
|
1473
|
+
input: {},
|
|
1474
|
+
status,
|
|
1475
|
+
result,
|
|
1476
|
+
extracted: extractFromToolResult(String(m?.name || ""), result)
|
|
1477
|
+
};
|
|
1478
|
+
const turn = state.turns[ti];
|
|
1479
|
+
const next = ctx.cloneWith(turn, ai_i, (t) => {
|
|
1480
|
+
t.ai[ai_i].tools = [...turn.ai[ai_i].tools, orphan];
|
|
1481
|
+
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1482
|
+
});
|
|
1483
|
+
state.turns[ti] = next;
|
|
1484
|
+
ctx.indexes().byToolCallId.set(callId, { turn: ti, ai: ai_i, tool: next.ai[ai_i].tools.length - 1 });
|
|
1485
|
+
if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: ai_i });
|
|
1486
|
+
effects.push({ type: "tool-updated", turnId: next.id, aiId: next.ai[ai_i].id, tool: orphan });
|
|
1487
|
+
};
|
|
1488
|
+
const appendAi = (msg, effects) => {
|
|
1489
|
+
const id = String(msg?.id || "").trim();
|
|
1490
|
+
if (state.openTurn === null) {
|
|
1491
|
+
appendHuman(
|
|
1492
|
+
{
|
|
1493
|
+
id: `${id || "ai"}-orphan`,
|
|
1494
|
+
type: "human",
|
|
1495
|
+
content: "",
|
|
1496
|
+
additional_kwargs: {}
|
|
1497
|
+
},
|
|
1498
|
+
false,
|
|
1499
|
+
effects
|
|
1500
|
+
);
|
|
1501
|
+
}
|
|
1502
|
+
const ti = state.openTurn;
|
|
1503
|
+
const runId = messageRunId(msg);
|
|
1504
|
+
const openSeg = state.openAi !== null ? state.turns[ti].ai[state.openAi] : null;
|
|
1505
|
+
if (openSeg && (!runId || !openSeg.runId || runId === openSeg.runId)) {
|
|
1506
|
+
const text = readMessageContentText(msg);
|
|
1507
|
+
const ai_i = state.openAi;
|
|
1508
|
+
const turn = state.turns[ti];
|
|
1509
|
+
const body = text || openSeg.body;
|
|
1510
|
+
const next = ctx.cloneWith(turn, ai_i, (t) => {
|
|
1511
|
+
t.ai[ai_i].body = body;
|
|
1512
|
+
t.ai[ai_i].streamingText = body;
|
|
1513
|
+
if (id && !t.ai[ai_i].messageIds?.includes(id)) {
|
|
1514
|
+
t.ai[ai_i].messageIds = [...t.ai[ai_i].messageIds ?? [], id];
|
|
1515
|
+
}
|
|
1516
|
+
if (!t.ai[ai_i].runId) t.ai[ai_i].runId = runId || ctx.streamRunId() || "";
|
|
1517
|
+
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1518
|
+
});
|
|
1519
|
+
state.turns[ti] = next;
|
|
1520
|
+
if (id && id !== openSeg.id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: ai_i });
|
|
1521
|
+
effects.push({ type: "ai-delta", turnId: next.id, aiId: openSeg.id, body, streamingText: body });
|
|
1522
|
+
registerToolCalls(ti, ai_i, msg, effects);
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
openNewAi(ti, msg, effects);
|
|
1526
|
+
};
|
|
1527
|
+
return { appendHuman, appendHiddenHuman, appendAi, applyToolMessage, registerToolCalls };
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
// src/materializer/turn-machine.ts
|
|
1531
|
+
var DEFAULT_TWIN_TOOL_PREFIX = "city-digital-twin-display_";
|
|
1532
|
+
function createTurnMachine(options) {
|
|
1533
|
+
const state = { turns: [], openTurn: null, openAi: null, optimisticTurnId: null };
|
|
1534
|
+
let indexes = createIndexes();
|
|
1535
|
+
const twinEnabled = !!options?.twin?.enabled;
|
|
1536
|
+
const twinToolPrefix = options?.twin?.toolPrefix || DEFAULT_TWIN_TOOL_PREFIX;
|
|
1537
|
+
const streamRunId = () => String(options?.getStreamRunId?.() || "").trim();
|
|
1538
|
+
const assembleAttachments = (seg) => {
|
|
1539
|
+
const byKind = /* @__PURE__ */ new Map();
|
|
1540
|
+
for (const tool of seg.tools) {
|
|
1541
|
+
const ex = tool.extracted;
|
|
1542
|
+
if (ex?.kind === "report") {
|
|
1543
|
+
byKind.set(`report:${ex.reportKind}`, {
|
|
1544
|
+
kind: "report",
|
|
1545
|
+
reportKind: ex.reportKind,
|
|
1546
|
+
body: ex.body,
|
|
1547
|
+
outline: ex.outline,
|
|
1548
|
+
sourcePath: ex.sourcePath,
|
|
1549
|
+
title: ex.title
|
|
1550
|
+
});
|
|
1551
|
+
} else if (ex?.kind === "artifact") byKind.set("artifact", { kind: "artifact", files: ex.files });
|
|
1552
|
+
else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
|
|
1553
|
+
byKind.set("twin", { kind: "twin", payload: tool.input });
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
return [...byKind.values()];
|
|
1557
|
+
};
|
|
1558
|
+
const cloneWith = (turn, ai_i, mutate) => {
|
|
1559
|
+
const next = {
|
|
1560
|
+
...turn,
|
|
1561
|
+
human: { ...turn.human },
|
|
1562
|
+
clarifications: [...turn.clarifications],
|
|
1563
|
+
ai: turn.ai.map((seg, i) => i === ai_i ? { ...seg, tools: [...seg.tools] } : seg)
|
|
1564
|
+
};
|
|
1565
|
+
mutate(next);
|
|
1566
|
+
return next;
|
|
1567
|
+
};
|
|
1568
|
+
const archiveRaw = (t, msg) => {
|
|
1569
|
+
const id = String(msg?.id || "").trim();
|
|
1570
|
+
const raws = t.rawMessages ?? [];
|
|
1571
|
+
const ri = id ? raws.findIndex((r) => String(r?.id || "").trim() === id) : -1;
|
|
1572
|
+
t.rawMessages = ri >= 0 ? [...raws.slice(0, ri), msg, ...raws.slice(ri + 1)] : [...raws, msg];
|
|
1573
|
+
};
|
|
1574
|
+
const sealAiSegment = (turn, ai_i, effects) => {
|
|
1575
|
+
const seg = turn.ai[ai_i];
|
|
1576
|
+
if (seg.status === "sealed") return turn;
|
|
1577
|
+
const sealed = {
|
|
1578
|
+
...seg,
|
|
1579
|
+
status: "sealed",
|
|
1580
|
+
streamingText: void 0,
|
|
1581
|
+
segments: sliceBodySegments(seg.body),
|
|
1582
|
+
attachments: assembleAttachments(seg)
|
|
1583
|
+
};
|
|
1584
|
+
const next = cloneWith(turn, ai_i, (t) => {
|
|
1585
|
+
t.ai[ai_i] = sealed;
|
|
1586
|
+
});
|
|
1587
|
+
effects.push({ type: "ai-sealed", turnId: next.id, aiId: sealed.id, segments: sealed.segments });
|
|
1588
|
+
return next;
|
|
1589
|
+
};
|
|
1590
|
+
const sealOpenTurn = (effects) => {
|
|
1591
|
+
const ti = state.openTurn;
|
|
1592
|
+
if (ti === null) return;
|
|
1593
|
+
let turn = state.turns[ti];
|
|
1594
|
+
if (state.openAi !== null) {
|
|
1595
|
+
turn = sealAiSegment(turn, state.openAi, effects);
|
|
1596
|
+
state.openAi = null;
|
|
1597
|
+
}
|
|
1598
|
+
if (turn.status !== "sealed") {
|
|
1599
|
+
const sealed = { ...turn, status: "sealed" };
|
|
1600
|
+
state.turns[ti] = sealed;
|
|
1601
|
+
effects.push({ type: "turn-sealed", turnId: sealed.id });
|
|
1602
|
+
}
|
|
1603
|
+
state.openTurn = null;
|
|
1604
|
+
if (state.optimisticTurnId === turn.id) state.optimisticTurnId = null;
|
|
1605
|
+
};
|
|
1606
|
+
const rules = createTurnRules({
|
|
1607
|
+
state,
|
|
1608
|
+
indexes: () => indexes,
|
|
1609
|
+
cloneWith,
|
|
1610
|
+
sealOpenTurn,
|
|
1611
|
+
sealAiSegment,
|
|
1612
|
+
assembleAttachments,
|
|
1613
|
+
streamRunId
|
|
1614
|
+
});
|
|
1615
|
+
const applyTailRemove = (id, effects) => {
|
|
1616
|
+
const ti = state.openTurn;
|
|
1617
|
+
if (state.optimisticTurnId && ti !== null && state.turns[ti]?.human.id === id) {
|
|
1618
|
+
state.turns.pop();
|
|
1619
|
+
state.openTurn = null;
|
|
1620
|
+
state.openAi = null;
|
|
1621
|
+
state.optimisticTurnId = null;
|
|
1622
|
+
indexes = rebuildIndexes(state.turns);
|
|
1623
|
+
effects.push({ type: "placeholder-dropped", turnId: id });
|
|
1624
|
+
return;
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
const applyAppend = (msg, allowOptimistic, effects) => {
|
|
1628
|
+
if (isHiddenHuman(msg)) return rules.appendHiddenHuman(msg, effects);
|
|
1629
|
+
if (isHumanMessage(msg)) return rules.appendHuman(msg, allowOptimistic, effects);
|
|
1630
|
+
if (isAiMessage(msg)) return rules.appendAi(msg, effects);
|
|
1631
|
+
if (isToolMessage(msg)) return rules.applyToolMessage(msg, effects);
|
|
1632
|
+
};
|
|
1633
|
+
const applyUpdate = (id, msg, effects) => {
|
|
1634
|
+
const loc = indexes.byMessageId.get(id);
|
|
1635
|
+
if (!loc) return;
|
|
1636
|
+
if (loc.ai === null) {
|
|
1637
|
+
if (isHiddenHuman(msg)) return rules.appendHiddenHuman(msg, effects);
|
|
1638
|
+
if (!isHumanMessage(msg)) return;
|
|
1639
|
+
const turn2 = state.turns[loc.turn];
|
|
1640
|
+
const wasOptimistic = state.optimisticTurnId === turn2.id;
|
|
1641
|
+
const mergedKwargs = resolveHumanKwargsMerge(
|
|
1642
|
+
turn2.human.kwargs,
|
|
1643
|
+
msg?.additional_kwargs,
|
|
1644
|
+
(getHumanMessageBaseId(id) || id) !== id
|
|
1645
|
+
);
|
|
1646
|
+
const next2 = cloneWith(turn2, null, (t) => {
|
|
1647
|
+
t.human = { id, text: extractTextFromMessage(msg), kwargs: mergedKwargs };
|
|
1648
|
+
t.optimistic = false;
|
|
1649
|
+
archiveRaw(t, msg);
|
|
1650
|
+
});
|
|
1651
|
+
state.turns[loc.turn] = next2;
|
|
1652
|
+
if (wasOptimistic) {
|
|
1653
|
+
state.optimisticTurnId = null;
|
|
1654
|
+
effects.push({ type: "placeholder-absorbed", turnId: next2.id });
|
|
1655
|
+
} else {
|
|
1656
|
+
effects.push({ type: "message-updated", turnId: next2.id, aiId: null });
|
|
1657
|
+
}
|
|
1658
|
+
return;
|
|
1659
|
+
}
|
|
1660
|
+
if (isToolMessage(msg)) {
|
|
1661
|
+
rules.applyToolMessage(msg, effects);
|
|
1662
|
+
return;
|
|
1663
|
+
}
|
|
1664
|
+
const turn = state.turns[loc.turn];
|
|
1665
|
+
const seg = turn.ai[loc.ai];
|
|
1666
|
+
const text = readMessageContentText(msg);
|
|
1667
|
+
const body = text || seg.body;
|
|
1668
|
+
const bodyChanged = body !== seg.body;
|
|
1669
|
+
const next = cloneWith(turn, loc.ai, (t) => {
|
|
1670
|
+
const target = t.ai[loc.ai];
|
|
1671
|
+
target.body = body;
|
|
1672
|
+
if (target.status === "streaming") target.streamingText = body;
|
|
1673
|
+
if (target.status === "sealed" && bodyChanged) target.segments = sliceBodySegments(body);
|
|
1674
|
+
if (!target.runId) {
|
|
1675
|
+
const rid = messageRunId(msg) || streamRunId();
|
|
1676
|
+
if (rid) target.runId = rid;
|
|
1677
|
+
}
|
|
1678
|
+
archiveRaw(t, msg);
|
|
1679
|
+
});
|
|
1680
|
+
state.turns[loc.turn] = next;
|
|
1681
|
+
if (id !== seg.id && isAiMessage(msg)) {
|
|
1682
|
+
indexes.byMessageId.set(id, { turn: loc.turn, ai: loc.ai });
|
|
1683
|
+
const nextSeg = state.turns[loc.turn].ai[loc.ai];
|
|
1684
|
+
if (!nextSeg.messageIds?.includes(id)) nextSeg.messageIds = [...nextSeg.messageIds ?? [], id];
|
|
1685
|
+
}
|
|
1686
|
+
effects.push({ type: "ai-delta", turnId: next.id, aiId: seg.id, body, streamingText: body });
|
|
1687
|
+
rules.registerToolCalls(loc.turn, loc.ai, msg, effects);
|
|
1688
|
+
};
|
|
1689
|
+
const finalizeInto = (effects) => {
|
|
1690
|
+
sealOpenTurn(effects);
|
|
1691
|
+
indexes = rebuildIndexes(state.turns);
|
|
1692
|
+
};
|
|
1693
|
+
function resetMachine() {
|
|
1694
|
+
state.turns = [];
|
|
1695
|
+
state.openTurn = null;
|
|
1696
|
+
state.openAi = null;
|
|
1697
|
+
state.optimisticTurnId = null;
|
|
1698
|
+
indexes = createIndexes();
|
|
1699
|
+
}
|
|
1700
|
+
return {
|
|
1701
|
+
applyDeltas(deltas) {
|
|
1702
|
+
const effects = [];
|
|
1703
|
+
for (const d of deltas) {
|
|
1704
|
+
if (d.type === "append") applyAppend(d.message, true, effects);
|
|
1705
|
+
else if (d.type === "update") applyUpdate(d.id, d.message, effects);
|
|
1706
|
+
else applyTailRemove(d.id, effects);
|
|
1707
|
+
}
|
|
1708
|
+
return effects;
|
|
1709
|
+
},
|
|
1710
|
+
seed(messages) {
|
|
1711
|
+
if (state.openTurn !== null || state.openAi !== null) {
|
|
1712
|
+
throw new Error("[materializer] \u6D41\u8FDB\u884C\u4E2D\u7981\u6B62 seed\uFF08\u5148 finalize \u5BC6\u5C01\u540E\u518D\u5168\u91CF\u91CD\u5EFA\uFF09");
|
|
1713
|
+
}
|
|
1714
|
+
resetMachine();
|
|
1715
|
+
const effects = [];
|
|
1716
|
+
for (const msg of messages) applyAppend(msg, false, effects);
|
|
1717
|
+
finalizeInto(effects);
|
|
1718
|
+
return effects;
|
|
1719
|
+
},
|
|
1720
|
+
finalize() {
|
|
1721
|
+
const effects = [];
|
|
1722
|
+
finalizeInto(effects);
|
|
1723
|
+
return effects;
|
|
1724
|
+
},
|
|
1725
|
+
decorate(id, patch) {
|
|
1726
|
+
const effects = [];
|
|
1727
|
+
const loc = indexes.byMessageId.get(id);
|
|
1728
|
+
if (!loc || loc.ai === null) return effects;
|
|
1729
|
+
const turn = state.turns[loc.turn];
|
|
1730
|
+
const next = cloneWith(turn, loc.ai, (t) => {
|
|
1731
|
+
Object.assign(t.ai[loc.ai], patch);
|
|
1732
|
+
});
|
|
1733
|
+
state.turns[loc.turn] = next;
|
|
1734
|
+
effects.push({ type: "message-updated", turnId: next.id, aiId: next.ai[loc.ai].id });
|
|
1735
|
+
return effects;
|
|
1736
|
+
},
|
|
1737
|
+
reset: resetMachine,
|
|
1738
|
+
get state() {
|
|
1739
|
+
return state;
|
|
1740
|
+
},
|
|
1741
|
+
get indexes() {
|
|
1742
|
+
return indexes;
|
|
1743
|
+
}
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
// src/materializer/materializer.ts
|
|
1748
|
+
function createMaterializer(options) {
|
|
1749
|
+
const view = shallowRef({ turns: [] });
|
|
1750
|
+
const machine = createTurnMachine(options);
|
|
1751
|
+
const messageDiff = createMessageDiff();
|
|
1752
|
+
const publishIfChanged = (effects) => {
|
|
1753
|
+
if (!effects.length) return;
|
|
1754
|
+
view.value = { turns: [...machine.state.turns] };
|
|
1755
|
+
};
|
|
1756
|
+
return {
|
|
1757
|
+
view,
|
|
1758
|
+
hydrate(seed) {
|
|
1759
|
+
messageDiff.reset();
|
|
1760
|
+
messageDiff.apply(seed);
|
|
1761
|
+
const effects = machine.seed(seed);
|
|
1762
|
+
publishIfChanged(effects);
|
|
1763
|
+
},
|
|
1764
|
+
applySnapshot(messages) {
|
|
1765
|
+
const deltas = messageDiff.apply(messages);
|
|
1766
|
+
if (!deltas.length) return;
|
|
1767
|
+
const effects = machine.applyDeltas(deltas);
|
|
1768
|
+
publishIfChanged(effects);
|
|
1769
|
+
},
|
|
1770
|
+
finalize() {
|
|
1771
|
+
publishIfChanged(machine.finalize());
|
|
1772
|
+
},
|
|
1773
|
+
decorate(messageId, patch) {
|
|
1774
|
+
publishIfChanged(machine.decorate(messageId, patch));
|
|
1775
|
+
},
|
|
1776
|
+
reset() {
|
|
1777
|
+
messageDiff.reset();
|
|
1778
|
+
machine.reset();
|
|
1779
|
+
view.value = { turns: [] };
|
|
1780
|
+
}
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
// src/runtime/runtime-materializer.ts
|
|
1785
|
+
import { computed, shallowRef as shallowRef2 } from "vue";
|
|
1786
|
+
var localSeq = 0;
|
|
1787
|
+
function createRuntimeMaterializer(options) {
|
|
1788
|
+
const materializer = createMaterializer({ twin: options.twin, getStreamRunId: options.getStreamRunId });
|
|
1789
|
+
let lastMessages = [];
|
|
1790
|
+
const answersMap = shallowRef2(/* @__PURE__ */ new Map());
|
|
1791
|
+
const answers = computed(() => answersMap.value);
|
|
1792
|
+
const turns = computed(() => materializer.view.value.turns);
|
|
1793
|
+
const activeClarification = computed(() => {
|
|
1794
|
+
const ts = materializer.view.value.turns;
|
|
1795
|
+
const last = ts[ts.length - 1];
|
|
1796
|
+
if (!last) return void 0;
|
|
1797
|
+
for (let ci = last.clarifications.length - 1; ci >= 0; ci--) {
|
|
1798
|
+
const c = last.clarifications[ci];
|
|
1799
|
+
if (!c.answer && !answersMap.value.has(c.callId)) return c;
|
|
1800
|
+
}
|
|
1801
|
+
return void 0;
|
|
1802
|
+
});
|
|
1803
|
+
const feed = (messages) => {
|
|
1804
|
+
lastMessages = messages;
|
|
1805
|
+
materializer.applySnapshot(messages);
|
|
1806
|
+
};
|
|
1807
|
+
return {
|
|
1808
|
+
view: materializer.view,
|
|
1809
|
+
turns,
|
|
1810
|
+
activeClarification,
|
|
1811
|
+
answers,
|
|
1812
|
+
setClarificationAnswer(toolCallId, answer) {
|
|
1813
|
+
const next = new Map(answersMap.value);
|
|
1814
|
+
next.set(toolCallId, answer);
|
|
1815
|
+
answersMap.value = next;
|
|
1816
|
+
},
|
|
1817
|
+
clearClarificationAnswers() {
|
|
1818
|
+
if (!answersMap.value.size) return;
|
|
1819
|
+
answersMap.value = /* @__PURE__ */ new Map();
|
|
1820
|
+
},
|
|
1821
|
+
lastMessages: () => lastMessages,
|
|
1822
|
+
hydrate(seed) {
|
|
1823
|
+
lastMessages = seed;
|
|
1824
|
+
materializer.hydrate(seed);
|
|
1825
|
+
},
|
|
1826
|
+
applySnapshot(messages) {
|
|
1827
|
+
lastMessages = messages;
|
|
1828
|
+
materializer.applySnapshot(messages);
|
|
1829
|
+
},
|
|
1830
|
+
finalize() {
|
|
1831
|
+
materializer.finalize();
|
|
1832
|
+
},
|
|
1833
|
+
decorate(messageId, patch) {
|
|
1834
|
+
materializer.decorate(messageId, patch);
|
|
1835
|
+
},
|
|
1836
|
+
prependHistory(older) {
|
|
1837
|
+
const merged = [...older, ...lastMessages];
|
|
1838
|
+
try {
|
|
1839
|
+
materializer.hydrate(merged);
|
|
1840
|
+
} catch {
|
|
1841
|
+
return false;
|
|
1842
|
+
}
|
|
1843
|
+
lastMessages = merged;
|
|
1844
|
+
return true;
|
|
1845
|
+
},
|
|
1846
|
+
reconcileWithPage(pageMessages) {
|
|
1847
|
+
if (!pageMessages.length || !lastMessages.length) return;
|
|
1848
|
+
const byId = new Map(pageMessages.map((m) => [String(m?.id || ""), m]));
|
|
1849
|
+
feed(lastMessages.map((m) => byId.get(String(m?.id || "")) ?? m));
|
|
1850
|
+
},
|
|
1851
|
+
addOptimisticTurn(body) {
|
|
1852
|
+
localSeq += 1;
|
|
1853
|
+
const stamp = `${Date.now()}-${localSeq}`;
|
|
1854
|
+
const humanMsg = {
|
|
1855
|
+
id: `local-h-${stamp}`,
|
|
1856
|
+
type: "human",
|
|
1857
|
+
content: [{ type: "text", text: body }],
|
|
1858
|
+
additional_kwargs: {}
|
|
1859
|
+
};
|
|
1860
|
+
const aiMsg = {
|
|
1861
|
+
id: `local-a-${stamp}`,
|
|
1862
|
+
type: "ai",
|
|
1863
|
+
content: [{ type: "text", text: "" }],
|
|
1864
|
+
additional_kwargs: {}
|
|
1865
|
+
};
|
|
1866
|
+
feed([...lastMessages, humanMsg, aiMsg]);
|
|
1867
|
+
},
|
|
1868
|
+
updateAiBody(aiId, body) {
|
|
1869
|
+
const idx = lastMessages.findIndex((m) => String(m?.id || "") === aiId);
|
|
1870
|
+
if (idx < 0) return;
|
|
1871
|
+
const next = [...lastMessages];
|
|
1872
|
+
next[idx] = { ...next[idx], content: [{ type: "text", text: body }] };
|
|
1873
|
+
feed(next);
|
|
1874
|
+
},
|
|
1875
|
+
applySemanticPatch(patches) {
|
|
1876
|
+
if (!patches.size || !lastMessages.length) return;
|
|
1877
|
+
const next = applySemanticPatches(lastMessages, patches);
|
|
1878
|
+
const changed = next.some((m, i) => m !== lastMessages[i]);
|
|
1879
|
+
if (changed) feed(next);
|
|
1880
|
+
}
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
// src/runtime/thread-runtime.ts
|
|
1885
|
+
import { computed as computed3, effectScope, ref as ref2, shallowRef as shallowRef5 } from "vue";
|
|
1886
|
+
|
|
1887
|
+
// src/runtime/history-pager.ts
|
|
1888
|
+
import { computed as computed2, ref } from "vue";
|
|
1889
|
+
function createHistoryPager(options) {
|
|
1890
|
+
const { threadId, transport, firstPage } = options;
|
|
1891
|
+
let cursor = firstPage.nextBeforeSeq;
|
|
1892
|
+
const hasMoreRef = ref(Boolean(firstPage.hasMore) && firstPage.nextBeforeSeq !== void 0);
|
|
1893
|
+
const loading = ref(false);
|
|
1894
|
+
const loadOlder = async () => {
|
|
1895
|
+
if (loading.value) return hasMoreRef.value;
|
|
1896
|
+
if (!hasMoreRef.value || cursor === void 0) {
|
|
1897
|
+
hasMoreRef.value = false;
|
|
1898
|
+
return false;
|
|
1899
|
+
}
|
|
1900
|
+
loading.value = true;
|
|
1901
|
+
try {
|
|
1902
|
+
const page = await transport.fetchMessagesPage(threadId, { beforeSeq: cursor });
|
|
1903
|
+
const pageMessages = runMessagesToMessages(page.messages);
|
|
1904
|
+
options.emitChanges();
|
|
1905
|
+
cursor = page.nextBeforeSeq;
|
|
1906
|
+
hasMoreRef.value = Boolean(page.hasMore) && page.nextBeforeSeq !== void 0;
|
|
1907
|
+
options.onPageLoaded?.(page);
|
|
1908
|
+
return hasMoreRef.value;
|
|
1909
|
+
} finally {
|
|
1910
|
+
loading.value = false;
|
|
1911
|
+
}
|
|
1912
|
+
};
|
|
1913
|
+
return { loadOlder, hasMore: computed2(() => hasMoreRef.value), loading };
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
// src/runtime/runtime-bootstrap.ts
|
|
1917
|
+
async function bootstrapRuntime(deps) {
|
|
1918
|
+
const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
|
|
1919
|
+
deps.valuesChannel.applyInitialValues(fetched.values);
|
|
1920
|
+
deps.valuesChannel.applyThreadState(fetched.threadState);
|
|
1921
|
+
const semantic = deps.overlay.applyState(fetched.threadState);
|
|
1922
|
+
if (semantic.patched) {
|
|
1923
|
+
console.debug(`[runtime] \u8BED\u4E49\u5C42\u52A0\u8F7D patched=${semantic.patched} cited=${semantic.citedIds.length}`);
|
|
1924
|
+
}
|
|
1925
|
+
deps.runs.fillFromRunsList(fetched.runsList ?? []);
|
|
1926
|
+
deps.runs.enrichFromPage(fetched.messagesPage);
|
|
1927
|
+
const pageMessages = runMessagesToMessages(fetched.messagesPage.messages);
|
|
1928
|
+
const seeded = applySemanticPatches(pageMessages, deps.overlay.getPatches());
|
|
1929
|
+
if (seeded.length) deps.rm.hydrate(seeded);
|
|
1930
|
+
deps.rm.applySemanticPatch(deps.overlay.getPatches());
|
|
1931
|
+
deps.setPager(
|
|
1932
|
+
createHistoryPager({
|
|
1933
|
+
threadId: deps.threadId,
|
|
1934
|
+
transport: deps.transport,
|
|
1935
|
+
firstPage: fetched.messagesPage,
|
|
1936
|
+
onPageLoaded: (page) => {
|
|
1937
|
+
deps.runs.enrichFromPage(page);
|
|
1938
|
+
deps.rm.prependHistory(runMessagesToMessages(page.messages));
|
|
1939
|
+
},
|
|
1940
|
+
emitChanges: () => {
|
|
1941
|
+
}
|
|
1942
|
+
})
|
|
1943
|
+
);
|
|
1944
|
+
await deps.refreshTokenUsage();
|
|
1945
|
+
const finalize = () => finalizeAfterStream(deps);
|
|
1946
|
+
const afterFinish = () => afterStreamFinish(deps);
|
|
1947
|
+
deps.streamRef.value = deps.transport.createStream({
|
|
1948
|
+
assistantId: deps.assistantId,
|
|
1949
|
+
threadId: deps.threadId,
|
|
1950
|
+
onCreated: (run) => deps.markStreamRun(run?.run_id),
|
|
1951
|
+
onMetadataEvent: (data) => deps.markStreamRun(data?.run_id),
|
|
1952
|
+
onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
|
|
1953
|
+
onMessageTupleEvent: () => {
|
|
1954
|
+
},
|
|
1955
|
+
onSnapshotMessages: (messages) => deps.rm.applySnapshot(messages),
|
|
1956
|
+
onStreamStart: deps.onStreamStart,
|
|
1957
|
+
onStreamEnd: finalize,
|
|
1958
|
+
onFinish: afterFinish,
|
|
1959
|
+
onError: (err) => console.error("[runtime] stream error", err)
|
|
1960
|
+
});
|
|
1961
|
+
deps.setInitialized();
|
|
1962
|
+
}
|
|
1963
|
+
function finalizeAfterStream(deps) {
|
|
1964
|
+
deps.rm.finalize();
|
|
1965
|
+
deps.onStreamSettled();
|
|
1966
|
+
deps.runs.backfillCurrentRunMetadata(() => [...deps.rm.lastMessages()]);
|
|
1967
|
+
deps.rm.applySemanticPatch(extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages()));
|
|
1968
|
+
}
|
|
1969
|
+
async function afterStreamFinish(deps) {
|
|
1970
|
+
await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
|
|
1971
|
+
await reconcileWithPage(deps);
|
|
1972
|
+
await refreshSemanticLayer(deps);
|
|
1973
|
+
}
|
|
1974
|
+
async function refreshSemanticLayer(deps) {
|
|
1975
|
+
try {
|
|
1976
|
+
const state = await deps.transport.fetchThreadState(deps.threadId);
|
|
1977
|
+
if (!state) return;
|
|
1978
|
+
const semantic = deps.overlay.applyState(state);
|
|
1979
|
+
deps.rm.applySemanticPatch(deps.overlay.getPatches());
|
|
1980
|
+
if (semantic.patched) {
|
|
1981
|
+
console.debug(`[runtime] \u8BED\u4E49\u5C42\u5237\u65B0 patched=${semantic.patched} cited=${semantic.citedIds.length}`);
|
|
1982
|
+
}
|
|
1983
|
+
} catch (e) {
|
|
1984
|
+
console.warn("[runtime] \u8BED\u4E49\u5C42\u5237\u65B0\u5931\u8D25", e);
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
async function reconcileWithPage(deps) {
|
|
1988
|
+
try {
|
|
1989
|
+
const page = await deps.transport.fetchMessagesPage(deps.threadId);
|
|
1990
|
+
const messages = runMessagesToMessages(page.messages);
|
|
1991
|
+
if (messages.length) deps.rm.reconcileWithPage(messages);
|
|
1992
|
+
} catch (e) {
|
|
1993
|
+
console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
async function runRuntimeInit(deps, hooks) {
|
|
1997
|
+
hooks.onStart();
|
|
1998
|
+
try {
|
|
1999
|
+
await bootstrapRuntime(deps);
|
|
2000
|
+
} finally {
|
|
2001
|
+
hooks.onEnd();
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
// src/runtime/runtime-stream-actions.ts
|
|
2006
|
+
function createStreamActions(ctx) {
|
|
2007
|
+
return {
|
|
2008
|
+
submit(text, submitOptions) {
|
|
2009
|
+
const handle = ctx.getHandle();
|
|
2010
|
+
if (!handle) return;
|
|
2011
|
+
ctx.beginStream();
|
|
2012
|
+
const humanMessage = { type: "human", content: [{ type: "text", text }] };
|
|
2013
|
+
humanMessage.additional_kwargs = submitOptions?.kwargs;
|
|
2014
|
+
handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
|
|
2015
|
+
},
|
|
2016
|
+
async joinStream(runId, lastEventId) {
|
|
2017
|
+
const handle = ctx.getHandle();
|
|
2018
|
+
if (!handle) return;
|
|
2019
|
+
ctx.beginStream();
|
|
2020
|
+
ctx.markStreamRun(runId);
|
|
2021
|
+
await handle.joinStream(runId, lastEventId ?? "-1");
|
|
2022
|
+
},
|
|
2023
|
+
stop() {
|
|
2024
|
+
void ctx.options.transport.cancelRun(ctx.options.threadId, ctx.runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
|
|
2025
|
+
ctx.getHandle()?.stop();
|
|
2026
|
+
},
|
|
2027
|
+
async resumeInterrupt(decisions) {
|
|
2028
|
+
const it = ctx.getInterrupt();
|
|
2029
|
+
const interruptId = String(it?.id || "");
|
|
2030
|
+
if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
|
|
2031
|
+
const handle = ctx.getHandle();
|
|
2032
|
+
if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
|
|
2033
|
+
ctx.markResponded(interruptId);
|
|
2034
|
+
ctx.beginStream();
|
|
2035
|
+
await handle.resumeInterrupt(decisions);
|
|
2036
|
+
},
|
|
2037
|
+
async loadOlderMessages() {
|
|
2038
|
+
if (!ctx.getPager()) return false;
|
|
2039
|
+
return ctx.getPager().loadOlder();
|
|
2040
|
+
}
|
|
2041
|
+
};
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
// src/runtime/values-projection.ts
|
|
2045
|
+
import { shallowRef as shallowRef3 } from "vue";
|
|
2046
|
+
import { extractInterrupts } from "@langchain/langgraph-sdk/ui";
|
|
2047
|
+
|
|
2048
|
+
// src/runtime/interrupt-reconcile.ts
|
|
2049
|
+
function reconcileInterrupts(prevValues, nextValues, firstEvent) {
|
|
2050
|
+
let base = prevValues;
|
|
2051
|
+
if (firstEvent && base && "__interrupt__" in base) {
|
|
2052
|
+
const { __interrupt__: _dropped, ...rest } = base;
|
|
2053
|
+
base = rest;
|
|
2054
|
+
}
|
|
2055
|
+
if (nextValues && typeof nextValues === "object" && "__interrupt__" in nextValues) {
|
|
2056
|
+
let interrupts = nextValues.__interrupt__;
|
|
2057
|
+
const prevInterrupts = base?.__interrupt__;
|
|
2058
|
+
if (Array.isArray(interrupts) && interrupts.length > 0 && Array.isArray(prevInterrupts)) {
|
|
2059
|
+
const merged = [...prevInterrupts];
|
|
2060
|
+
const existingIds = new Set(merged.map((i) => i?.id).filter((id) => id != null));
|
|
2061
|
+
for (const interrupt of interrupts) {
|
|
2062
|
+
const id = interrupt?.id;
|
|
2063
|
+
if (id != null) {
|
|
2064
|
+
if (existingIds.has(id)) continue;
|
|
2065
|
+
existingIds.add(id);
|
|
2066
|
+
}
|
|
2067
|
+
merged.push(interrupt);
|
|
2068
|
+
}
|
|
2069
|
+
interrupts = merged;
|
|
2070
|
+
}
|
|
2071
|
+
return { ...base, __interrupt__: interrupts };
|
|
2072
|
+
}
|
|
2073
|
+
if (nextValues && typeof nextValues === "object") {
|
|
2074
|
+
if (base && "__interrupt__" in base && Array.isArray(base.__interrupt__)) {
|
|
2075
|
+
return { ...nextValues, __interrupt__: base.__interrupt__ };
|
|
2076
|
+
}
|
|
2077
|
+
return nextValues;
|
|
2078
|
+
}
|
|
2079
|
+
return nextValues ?? {};
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
// src/runtime/values-projection.ts
|
|
2083
|
+
function createValuesChannel(options = {}) {
|
|
2084
|
+
const valuesRef = shallowRef3({});
|
|
2085
|
+
const threadStateRef = shallowRef3(void 0);
|
|
2086
|
+
let firstEvent = true;
|
|
2087
|
+
let lastTitle = "";
|
|
2088
|
+
let latestStreamMessages = [];
|
|
2089
|
+
const readStateMessages = () => {
|
|
2090
|
+
const msgs = threadStateRef.value?.values?.messages;
|
|
2091
|
+
return Array.isArray(msgs) ? [...msgs] : [];
|
|
2092
|
+
};
|
|
2093
|
+
const readStreamMessages = () => [...latestStreamMessages];
|
|
2094
|
+
return {
|
|
2095
|
+
applyInitialValues(next) {
|
|
2096
|
+
valuesRef.value = { ...next ?? {} };
|
|
2097
|
+
},
|
|
2098
|
+
applyThreadState(state) {
|
|
2099
|
+
threadStateRef.value = state;
|
|
2100
|
+
},
|
|
2101
|
+
beginStream() {
|
|
2102
|
+
firstEvent = true;
|
|
2103
|
+
threadStateRef.value = void 0;
|
|
2104
|
+
latestStreamMessages = [];
|
|
2105
|
+
},
|
|
2106
|
+
applyValuesEvent(data) {
|
|
2107
|
+
const reconciled = reconcileInterrupts(valuesRef.value, data, firstEvent);
|
|
2108
|
+
firstEvent = false;
|
|
2109
|
+
valuesRef.value = reconciled;
|
|
2110
|
+
if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
|
|
2111
|
+
const title = String(reconciled?.title || "").trim();
|
|
2112
|
+
if (title && title !== lastTitle) {
|
|
2113
|
+
lastTitle = title;
|
|
2114
|
+
options.onTitle?.(title);
|
|
2115
|
+
}
|
|
2116
|
+
},
|
|
2117
|
+
getValues() {
|
|
2118
|
+
return valuesRef.value;
|
|
2119
|
+
},
|
|
2120
|
+
getStateMessages: readStateMessages,
|
|
2121
|
+
getStreamMessages: readStreamMessages,
|
|
2122
|
+
getInterrupt({ isLoading, error }) {
|
|
2123
|
+
return extractInterrupts(valuesRef.value, {
|
|
2124
|
+
isLoading,
|
|
2125
|
+
threadState: threadStateRef.value,
|
|
2126
|
+
error
|
|
2127
|
+
});
|
|
2128
|
+
}
|
|
2129
|
+
};
|
|
2130
|
+
}
|
|
2131
|
+
|
|
2132
|
+
// src/store/runs-store.ts
|
|
2133
|
+
import { shallowRef as shallowRef4 } from "vue";
|
|
2134
|
+
function createInterruptState() {
|
|
2135
|
+
const respondedIds = shallowRef4(/* @__PURE__ */ new Set());
|
|
2136
|
+
return {
|
|
2137
|
+
respondedIds,
|
|
2138
|
+
markResponded(id) {
|
|
2139
|
+
const next = new Set(respondedIds.value);
|
|
2140
|
+
next.add(id);
|
|
2141
|
+
respondedIds.value = next;
|
|
2142
|
+
},
|
|
2143
|
+
unmarkResponded(id) {
|
|
2144
|
+
if (!respondedIds.value.has(id)) return;
|
|
2145
|
+
const next = new Set(respondedIds.value);
|
|
2146
|
+
next.delete(id);
|
|
2147
|
+
respondedIds.value = next;
|
|
2148
|
+
}
|
|
2149
|
+
};
|
|
2150
|
+
}
|
|
2151
|
+
function createRunsStore(options) {
|
|
2152
|
+
const runsMap = shallowRef4(/* @__PURE__ */ new Map());
|
|
2153
|
+
const currentRunId = shallowRef4(null);
|
|
2154
|
+
return {
|
|
2155
|
+
runsMap,
|
|
2156
|
+
currentRunId,
|
|
2157
|
+
fillFromRunsList(runsList) {
|
|
2158
|
+
let next = null;
|
|
2159
|
+
for (const run of runsList) {
|
|
2160
|
+
const runId = String(run?.run_id || "").trim();
|
|
2161
|
+
if (!runId) continue;
|
|
2162
|
+
next ?? (next = new Map(runsMap.value));
|
|
2163
|
+
next.set(runId, buildRunInfo(run, options.threadId));
|
|
2164
|
+
}
|
|
2165
|
+
if (next) runsMap.value = next;
|
|
2166
|
+
},
|
|
2167
|
+
ensureRunning(runId) {
|
|
2168
|
+
if (runsMap.value.has(runId)) return;
|
|
2169
|
+
const next = new Map(runsMap.value);
|
|
2170
|
+
ensureRunningRun(next, runId, options.threadId);
|
|
2171
|
+
runsMap.value = next;
|
|
2172
|
+
},
|
|
2173
|
+
async refreshRuns() {
|
|
2174
|
+
try {
|
|
2175
|
+
const runsList = await options.transport.listRuns(options.threadId, 20);
|
|
2176
|
+
if (!Array.isArray(runsList)) return;
|
|
2177
|
+
const merged = new Map(runsMap.value);
|
|
2178
|
+
for (const run of runsList) {
|
|
2179
|
+
const runId = String(run.run_id || "").trim();
|
|
2180
|
+
if (!runId) continue;
|
|
2181
|
+
const info = buildRunInfo(run, options.threadId);
|
|
2182
|
+
const prev = merged.get(runId);
|
|
2183
|
+
if (!prev) {
|
|
2184
|
+
merged.set(runId, info);
|
|
2185
|
+
continue;
|
|
2186
|
+
}
|
|
2187
|
+
const directLatency = buildRunDirectLatencyMs(run);
|
|
2188
|
+
merged.set(runId, {
|
|
2189
|
+
...info,
|
|
2190
|
+
feedback: info.feedback ?? prev.feedback,
|
|
2191
|
+
latencyMs: directLatency ?? prev.latencyMs ?? info.latencyMs,
|
|
2192
|
+
modelName: info.modelName ?? prev.modelName,
|
|
2193
|
+
finishReason: info.finishReason ?? prev.finishReason
|
|
2194
|
+
});
|
|
2195
|
+
}
|
|
2196
|
+
runsMap.value = merged;
|
|
2197
|
+
} catch (e) {
|
|
2198
|
+
console.warn("[runs-store] refreshRuns failed", e);
|
|
2199
|
+
}
|
|
2200
|
+
},
|
|
2201
|
+
enrichFromPage(page) {
|
|
2202
|
+
const enrichment = extractRunEnrichment(page.messages);
|
|
2203
|
+
let next = null;
|
|
2204
|
+
for (const [runId, patch] of enrichment) {
|
|
2205
|
+
const run = (next ?? runsMap.value).get(runId);
|
|
2206
|
+
if (!run) continue;
|
|
2207
|
+
next ?? (next = new Map(runsMap.value));
|
|
2208
|
+
next.set(runId, {
|
|
2209
|
+
...run,
|
|
2210
|
+
...patch.feedback !== void 0 ? { feedback: patch.feedback } : {},
|
|
2211
|
+
...patch.latencyMs !== void 0 ? { latencyMs: patch.latencyMs } : {}
|
|
2212
|
+
});
|
|
2213
|
+
}
|
|
2214
|
+
if (next) runsMap.value = next;
|
|
2215
|
+
},
|
|
2216
|
+
backfillCurrentRunMetadata(getMessages) {
|
|
2217
|
+
const runId = currentRunId.value;
|
|
2218
|
+
if (!runId) return;
|
|
2219
|
+
const run = runsMap.value.get(runId);
|
|
2220
|
+
if (!run) return;
|
|
2221
|
+
if (run.modelName && run.finishReason) return;
|
|
2222
|
+
const currentRunMessages = getMessages().filter((m) => String(m?.runId || "") === runId);
|
|
2223
|
+
const source = currentRunMessages.length ? currentRunMessages : getMessages();
|
|
2224
|
+
const picked = pickRunMessageMetadata(source);
|
|
2225
|
+
if (!picked.modelName && !picked.finishReason) return;
|
|
2226
|
+
runsMap.value = new Map(runsMap.value).set(runId, {
|
|
2227
|
+
...run,
|
|
2228
|
+
...picked.modelName && !run.modelName ? { modelName: picked.modelName } : {},
|
|
2229
|
+
...picked.finishReason && !run.finishReason ? { finishReason: picked.finishReason } : {}
|
|
2230
|
+
});
|
|
2231
|
+
},
|
|
2232
|
+
patchRun(runId, patch) {
|
|
2233
|
+
const run = runsMap.value.get(runId);
|
|
2234
|
+
if (!run) return;
|
|
2235
|
+
runsMap.value = new Map(runsMap.value).set(runId, { ...run, ...patch });
|
|
2236
|
+
},
|
|
2237
|
+
dispose() {
|
|
2238
|
+
runsMap.value = /* @__PURE__ */ new Map();
|
|
2239
|
+
currentRunId.value = null;
|
|
2240
|
+
}
|
|
2241
|
+
};
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
// src/runtime/thread-runtime.ts
|
|
2245
|
+
function createThreadRuntime(options) {
|
|
2246
|
+
const scope = effectScope();
|
|
2247
|
+
const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
|
|
2248
|
+
const interruptState = createInterruptState();
|
|
2249
|
+
const rm = createRuntimeMaterializer({
|
|
2250
|
+
twin: options.twin,
|
|
2251
|
+
// 段级 runId 兜底源(metadata 首帧权威值):流式 tuple 消息本体无 runId,
|
|
2252
|
+
// 段打开/回填时经此兜底——点赞/反馈按 runId 提交的依赖
|
|
2253
|
+
getStreamRunId: () => runs.currentRunId.value
|
|
2254
|
+
});
|
|
2255
|
+
const valuesChannel = createValuesChannel({
|
|
2256
|
+
onTitle: (title) => options.onTitle?.(options.threadId, title)
|
|
2257
|
+
});
|
|
2258
|
+
const overlay = createSemanticOverlay();
|
|
2259
|
+
const streamRef = shallowRef5(null);
|
|
2260
|
+
const isInitializing = ref2(false);
|
|
2261
|
+
const streaming = ref2(false);
|
|
2262
|
+
const tokenUsage = shallowRef5(null);
|
|
2263
|
+
let initialized = false;
|
|
2264
|
+
let initPromise = null;
|
|
2265
|
+
let pager = null;
|
|
2266
|
+
const interrupt = computed3(() => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }));
|
|
2267
|
+
const hasPendingInterrupt = computed3(() => {
|
|
2268
|
+
const it = interrupt.value;
|
|
2269
|
+
return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
|
|
2270
|
+
});
|
|
2271
|
+
const streamError = computed3(() => streamRef.value?.error.value ?? null);
|
|
2272
|
+
const isGenerating = computed3(() => streaming.value);
|
|
2273
|
+
const beginStream = () => {
|
|
2274
|
+
valuesChannel.beginStream();
|
|
2275
|
+
overlay.invalidate();
|
|
2276
|
+
runs.currentRunId.value = null;
|
|
2277
|
+
};
|
|
2278
|
+
const streamStarted = () => {
|
|
2279
|
+
streaming.value = true;
|
|
2280
|
+
};
|
|
2281
|
+
const streamSettled = () => {
|
|
2282
|
+
streaming.value = false;
|
|
2283
|
+
};
|
|
2284
|
+
const markStreamRun = (runIdRaw) => {
|
|
2285
|
+
const runId = String(runIdRaw || "").trim();
|
|
2286
|
+
if (!runId) return;
|
|
2287
|
+
runs.currentRunId.value = runId;
|
|
2288
|
+
runs.ensureRunning(runId);
|
|
2289
|
+
};
|
|
2290
|
+
const refreshTokenUsage = async () => {
|
|
2291
|
+
try {
|
|
2292
|
+
tokenUsage.value = await options.transport.fetchThreadTokenUsage(options.threadId);
|
|
2293
|
+
} catch (e) {
|
|
2294
|
+
console.warn("[runtime] refreshTokenUsage failed", e);
|
|
2295
|
+
}
|
|
2296
|
+
};
|
|
2297
|
+
const doInit = () => runRuntimeInit(
|
|
2298
|
+
{
|
|
2299
|
+
threadId: options.threadId,
|
|
2300
|
+
assistantId: options.assistantId,
|
|
2301
|
+
transport: options.transport,
|
|
2302
|
+
runs,
|
|
2303
|
+
valuesChannel,
|
|
2304
|
+
overlay,
|
|
2305
|
+
rm,
|
|
2306
|
+
streamRef,
|
|
2307
|
+
setPager: (p) => pager = p,
|
|
2308
|
+
setInitialized: () => initialized = true,
|
|
2309
|
+
markStreamRun,
|
|
2310
|
+
onStreamStart: streamStarted,
|
|
2311
|
+
onStreamSettled: streamSettled,
|
|
2312
|
+
refreshTokenUsage
|
|
2313
|
+
},
|
|
2314
|
+
{
|
|
2315
|
+
onStart: () => isInitializing.value = true,
|
|
2316
|
+
onEnd: () => isInitializing.value = false
|
|
2317
|
+
}
|
|
2318
|
+
);
|
|
2319
|
+
const actions = createStreamActions({
|
|
2320
|
+
options,
|
|
2321
|
+
getHandle: () => streamRef.value,
|
|
2322
|
+
beginStream,
|
|
2323
|
+
markStreamRun,
|
|
2324
|
+
getInterrupt: () => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }),
|
|
2325
|
+
markResponded: (id) => interruptState.markResponded(id),
|
|
2326
|
+
getPager: () => pager,
|
|
2327
|
+
runs
|
|
2328
|
+
});
|
|
2329
|
+
return {
|
|
2330
|
+
threadId: options.threadId,
|
|
2331
|
+
lastViewedAt: Date.now(),
|
|
2332
|
+
touch() {
|
|
2333
|
+
this.lastViewedAt = Date.now();
|
|
2334
|
+
},
|
|
2335
|
+
view: rm.view,
|
|
2336
|
+
turns: rm.turns,
|
|
2337
|
+
activeClarification: rm.activeClarification,
|
|
2338
|
+
isGenerating,
|
|
2339
|
+
isInitializing,
|
|
2340
|
+
runs: computed3(() => runs.runsMap.value),
|
|
2341
|
+
interrupt,
|
|
2342
|
+
hasPendingInterrupt,
|
|
2343
|
+
streamError,
|
|
2344
|
+
tokenUsage,
|
|
2345
|
+
hasMoreHistory: computed3(() => pager?.hasMore.value ?? false),
|
|
2346
|
+
loadingHistory: computed3(() => pager?.loading.value ?? false),
|
|
2347
|
+
async init() {
|
|
2348
|
+
if (initialized) return;
|
|
2349
|
+
if (initPromise) return initPromise;
|
|
2350
|
+
initPromise = doInit();
|
|
2351
|
+
try {
|
|
2352
|
+
await initPromise;
|
|
2353
|
+
} finally {
|
|
2354
|
+
initPromise = null;
|
|
2355
|
+
}
|
|
2356
|
+
},
|
|
2357
|
+
submit: actions.submit,
|
|
2358
|
+
joinStream: actions.joinStream,
|
|
2359
|
+
stop: actions.stop,
|
|
2360
|
+
resumeInterrupt: actions.resumeInterrupt,
|
|
2361
|
+
loadOlderMessages: actions.loadOlderMessages,
|
|
2362
|
+
applyFeedback(messageId, feedback) {
|
|
2363
|
+
rm.decorate(messageId, { feedback });
|
|
2364
|
+
const runId = rm.view.value.turns.flatMap((t) => t.ai).find((seg) => seg.id === messageId)?.runId;
|
|
2365
|
+
if (runId) runs.patchRun(runId, { feedback });
|
|
2366
|
+
},
|
|
2367
|
+
addOptimisticTurn: rm.addOptimisticTurn,
|
|
2368
|
+
updateAiBody: rm.updateAiBody,
|
|
2369
|
+
decorate: rm.decorate,
|
|
2370
|
+
finalizeTurns: rm.finalize,
|
|
2371
|
+
setClarificationAnswer: rm.setClarificationAnswer,
|
|
2372
|
+
clearClarificationAnswers: rm.clearClarificationAnswers,
|
|
2373
|
+
clarificationAnswers: rm.answers,
|
|
2374
|
+
dispose() {
|
|
2375
|
+
streamRef.value?.stop();
|
|
2376
|
+
streamRef.value?.dispose?.();
|
|
2377
|
+
runs.dispose();
|
|
2378
|
+
scope.stop();
|
|
2379
|
+
}
|
|
2380
|
+
};
|
|
2381
|
+
}
|
|
2382
|
+
|
|
2383
|
+
// src/runtime/thread-directory.ts
|
|
2384
|
+
import { ref as ref3, shallowReactive } from "vue";
|
|
2385
|
+
var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending", "interrupted"]);
|
|
2386
|
+
function isActiveThreadStatus(status) {
|
|
2387
|
+
return typeof status === "string" && ACTIVE_THREAD_STATUSES.has(status);
|
|
2388
|
+
}
|
|
2389
|
+
var ThreadDirectory = class {
|
|
2390
|
+
constructor(options) {
|
|
2391
|
+
this.threads = ref3([]);
|
|
2392
|
+
this.threadsPagination = ref3({
|
|
2393
|
+
limit: 50,
|
|
2394
|
+
offset: 0,
|
|
2395
|
+
hasMore: true,
|
|
2396
|
+
isLoading: false
|
|
2397
|
+
});
|
|
2398
|
+
this.searchKeyword = "";
|
|
2399
|
+
/** 正在运行但已超出 SSE 连接上限的 thread(仅用于 UI 提示) */
|
|
2400
|
+
this.runningNotConnectedThreadIds = ref3(/* @__PURE__ */ new Set());
|
|
2401
|
+
/** 活跃 runtime 池(shallowReactive 追踪增删,runtime 实例不被深度代理) */
|
|
2402
|
+
this.cachedRuntimes = shallowReactive(/* @__PURE__ */ new Map());
|
|
2403
|
+
this.transport = options.transport;
|
|
2404
|
+
this.assistantId = options.assistantId;
|
|
2405
|
+
this.maxCachedRuntimes = options.maxCachedRuntimes ?? DEFAULT_MAX_CACHED_SESSIONS;
|
|
2406
|
+
this.maxConcurrentStreams = options.maxConcurrentStreams ?? DEFAULT_MAX_CONCURRENT_STREAMS;
|
|
2407
|
+
this.twin = options.twin;
|
|
2408
|
+
this.notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
|
|
2409
|
+
this.defaultThreadTitle = options.defaultThreadTitle ?? "";
|
|
2410
|
+
}
|
|
2411
|
+
// ===== Thread 列表 =====
|
|
2412
|
+
/** 分页拉取历史 thread 列表(失败上抛由调用方提示,不再静默吞错——错误通道契约) */
|
|
2413
|
+
async fetchThreads(reset = false, keyword) {
|
|
2414
|
+
if (this.threadsPagination.value.isLoading) return;
|
|
2415
|
+
if (!reset && !this.threadsPagination.value.hasMore) return;
|
|
2416
|
+
if (keyword !== void 0) this.searchKeyword = keyword.trim();
|
|
2417
|
+
this.threadsPagination.value.isLoading = true;
|
|
2418
|
+
try {
|
|
2419
|
+
if (reset) {
|
|
2420
|
+
this.threads.value = [];
|
|
2421
|
+
this.threadsPagination.value.offset = 0;
|
|
2422
|
+
this.threadsPagination.value.hasMore = true;
|
|
2423
|
+
}
|
|
2424
|
+
const limit = this.threadsPagination.value.limit;
|
|
2425
|
+
const offset = this.threadsPagination.value.offset;
|
|
2426
|
+
const result = await this.transport.searchThreads({
|
|
2427
|
+
limit,
|
|
2428
|
+
offset,
|
|
2429
|
+
...this.searchKeyword ? { keyword: this.searchKeyword } : {}
|
|
2430
|
+
});
|
|
2431
|
+
const list = Array.isArray(result) ? result : [];
|
|
2432
|
+
this.threads.value = reset ? list : [...this.threads.value, ...list];
|
|
2433
|
+
if (list.length < limit) {
|
|
2434
|
+
this.threadsPagination.value.hasMore = false;
|
|
2435
|
+
} else {
|
|
2436
|
+
this.threadsPagination.value.offset = offset + list.length;
|
|
2437
|
+
}
|
|
2438
|
+
} finally {
|
|
2439
|
+
this.threadsPagination.value.isLoading = false;
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
/** 创建新 thread(仅调 transport,不插入列表;确认可生成后由 prependThread 乐观插入) */
|
|
2443
|
+
async createThread(metadata) {
|
|
2444
|
+
try {
|
|
2445
|
+
return await this.transport.createThread(metadata);
|
|
2446
|
+
} catch (error) {
|
|
2447
|
+
console.error("[ThreadDirectory] create thread failed:", error);
|
|
2448
|
+
return null;
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
/** 乐观插入列表顶部(已存在忽略;无标题给默认标题——默认文案属 UI 语义,经 notify 同源注入) */
|
|
2452
|
+
prependThread(thread) {
|
|
2453
|
+
if (!thread?.thread_id) return;
|
|
2454
|
+
if (this.threads.value.some((t) => t.thread_id === thread.thread_id)) return;
|
|
2455
|
+
const values = thread.values || {};
|
|
2456
|
+
const title = String(values.title || "").trim();
|
|
2457
|
+
const normalized = {
|
|
2458
|
+
...thread,
|
|
2459
|
+
values: title ? values : { ...values, title: this.defaultThreadTitle }
|
|
2460
|
+
};
|
|
2461
|
+
this.threads.value = [normalized, ...this.threads.value];
|
|
2462
|
+
}
|
|
2463
|
+
/** 本地更新标题(SSE 期间后端生成 title 后同步侧边栏) */
|
|
2464
|
+
updateThreadTitle(threadId, title) {
|
|
2465
|
+
const trimmed = String(title || "").trim();
|
|
2466
|
+
if (!trimmed) return;
|
|
2467
|
+
const idx = this.threads.value.findIndex((t) => t.thread_id === threadId);
|
|
2468
|
+
if (idx < 0) return;
|
|
2469
|
+
const thread = this.threads.value[idx];
|
|
2470
|
+
const currentTitle = String(thread.values?.title || "").trim();
|
|
2471
|
+
if (currentTitle === trimmed) return;
|
|
2472
|
+
this.threads.value[idx] = { ...thread, values: { ...thread.values, title: trimmed } };
|
|
2473
|
+
}
|
|
2474
|
+
/** 本地移除(不发请求;移动分组成功后同步历史列表) */
|
|
2475
|
+
removeThreadFromList(threadId) {
|
|
2476
|
+
const id = String(threadId || "").trim();
|
|
2477
|
+
if (!id) return;
|
|
2478
|
+
this.threads.value = this.threads.value.filter((t) => t.thread_id !== id);
|
|
2479
|
+
}
|
|
2480
|
+
/** 删除 thread(transport + 本地列表 + 活跃 runtime 清理) */
|
|
2481
|
+
async deleteThread(threadId) {
|
|
2482
|
+
const id = String(threadId || "").trim();
|
|
2483
|
+
if (!id) return false;
|
|
2484
|
+
try {
|
|
2485
|
+
await this.transport.deleteThread(id);
|
|
2486
|
+
this.threads.value = this.threads.value.filter((t) => t.thread_id !== id);
|
|
2487
|
+
this.releaseRuntime(id);
|
|
2488
|
+
return true;
|
|
2489
|
+
} catch (error) {
|
|
2490
|
+
console.error("[ThreadDirectory] delete thread failed:", error);
|
|
2491
|
+
return false;
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
// ===== Runtime 池 =====
|
|
2495
|
+
/** 获取或创建 runtime(LRU;达上限时淘汰最久未查看的非生成中会话) */
|
|
2496
|
+
acquireRuntime(threadId) {
|
|
2497
|
+
const existing = this.cachedRuntimes.get(threadId);
|
|
2498
|
+
if (existing) return existing;
|
|
2499
|
+
if (this.cachedRuntimes.size >= this.maxCachedRuntimes) {
|
|
2500
|
+
const evictable = Array.from(this.cachedRuntimes.entries()).filter(([, rt]) => !rt.isGenerating.value && !rt.isInitializing.value).sort((a, b) => a[1].lastViewedAt - b[1].lastViewedAt)[0];
|
|
2501
|
+
if (!evictable) return "LIMIT_EXCEEDED";
|
|
2502
|
+
this.releaseRuntime(evictable[0]);
|
|
2503
|
+
}
|
|
2504
|
+
const runtime = createThreadRuntime({
|
|
2505
|
+
threadId,
|
|
2506
|
+
transport: this.transport,
|
|
2507
|
+
assistantId: this.assistantId,
|
|
2508
|
+
twin: this.twin,
|
|
2509
|
+
onTitle: (tid, title) => this.updateThreadTitle(tid, title)
|
|
2510
|
+
});
|
|
2511
|
+
this.cachedRuntimes.set(threadId, runtime);
|
|
2512
|
+
return runtime;
|
|
2513
|
+
}
|
|
2514
|
+
/** 释放指定 runtime(停止流并销毁) */
|
|
2515
|
+
releaseRuntime(threadId) {
|
|
2516
|
+
const runtime = this.cachedRuntimes.get(threadId);
|
|
2517
|
+
if (!runtime) return;
|
|
2518
|
+
runtime.dispose();
|
|
2519
|
+
this.cachedRuntimes.delete(threadId);
|
|
2520
|
+
}
|
|
2521
|
+
getRuntime(threadId) {
|
|
2522
|
+
return this.cachedRuntimes.get(threadId);
|
|
2523
|
+
}
|
|
2524
|
+
isThreadRunning(threadId) {
|
|
2525
|
+
return this.cachedRuntimes.get(threadId)?.isGenerating.value ?? false;
|
|
2526
|
+
}
|
|
2527
|
+
get activeCount() {
|
|
2528
|
+
return this.cachedRuntimes.size;
|
|
2529
|
+
}
|
|
2530
|
+
get generatingCount() {
|
|
2531
|
+
let count = 0;
|
|
2532
|
+
for (const rt of this.cachedRuntimes.values()) if (rt.isGenerating.value) count++;
|
|
2533
|
+
return count;
|
|
2534
|
+
}
|
|
2535
|
+
// ===== 刷新后恢复 =====
|
|
2536
|
+
/**
|
|
2537
|
+
* 恢复未完成 run 的 SSE:按 thread.status(含 interrupted)筛出候选线程并行 listRuns
|
|
2538
|
+
* 取最新 run → init + joinStream。
|
|
2539
|
+
* ⚠️ DeerFlow 语义:thread.status 与 run.status 的 'interrupted' 都表示「run 未完成」
|
|
2540
|
+
*(_derive_thread_status:tasks 非空 → interrupted;涵盖在跑、停在半路、HITL 挂起),
|
|
2541
|
+
* 不等于 LangGraph 官方的「HITL 挂起」——因此 run.status 不作硬判定,最新 run 一律
|
|
2542
|
+
* join:在跑则继续收流;已断则 join 返回 end 帧走 onFinish 对账(runs/state/citation
|
|
2543
|
+
* 刷新),页面收敛到最终状态。join 为只读幂等端点,误 join 无副作用。
|
|
2544
|
+
* 并行确认,串行连接(并发上限内)。
|
|
2545
|
+
*/
|
|
2546
|
+
async recoverRunningThreads() {
|
|
2547
|
+
const candidates = this.threads.value.filter((t) => t.thread_id && isActiveThreadStatus(t.status));
|
|
2548
|
+
const results = await Promise.all(
|
|
2549
|
+
candidates.map(async (thread) => {
|
|
2550
|
+
try {
|
|
2551
|
+
const runs = await this.transport.listRuns(thread.thread_id, 5);
|
|
2552
|
+
if (!Array.isArray(runs) || runs.length === 0) return null;
|
|
2553
|
+
const latest = [...runs].sort(
|
|
2554
|
+
(a, b) => String(b?.created_at || "").localeCompare(String(a?.created_at || ""))
|
|
2555
|
+
)[0];
|
|
2556
|
+
return latest?.run_id ? { threadId: thread.thread_id, runId: String(latest.run_id) } : null;
|
|
2557
|
+
} catch (e) {
|
|
2558
|
+
console.warn("[ThreadDirectory] check running run failed", e);
|
|
2559
|
+
return null;
|
|
2560
|
+
}
|
|
2561
|
+
})
|
|
2562
|
+
);
|
|
2563
|
+
const runningInfos = results.filter((r) => !!r);
|
|
2564
|
+
const connected = /* @__PURE__ */ new Set();
|
|
2565
|
+
for (const info of runningInfos.slice(0, this.maxConcurrentStreams)) {
|
|
2566
|
+
const rt = this.acquireRuntime(info.threadId);
|
|
2567
|
+
if (rt === "LIMIT_EXCEEDED") break;
|
|
2568
|
+
try {
|
|
2569
|
+
rt.touch();
|
|
2570
|
+
await rt.init();
|
|
2571
|
+
await rt.joinStream(info.runId, "-1");
|
|
2572
|
+
connected.add(info.threadId);
|
|
2573
|
+
} catch (e) {
|
|
2574
|
+
console.warn("[ThreadDirectory] recover running thread failed", info.threadId, e);
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
this.runningNotConnectedThreadIds.value = new Set(
|
|
2578
|
+
runningInfos.filter((i) => !connected.has(i.threadId)).map((i) => i.threadId)
|
|
2579
|
+
);
|
|
2580
|
+
}
|
|
2581
|
+
dispose() {
|
|
2582
|
+
for (const runtime of this.cachedRuntimes.values()) runtime.dispose();
|
|
2583
|
+
this.cachedRuntimes.clear();
|
|
2584
|
+
}
|
|
2585
|
+
};
|
|
2586
|
+
|
|
2587
|
+
// src/core/ChatCore.ts
|
|
2588
|
+
import { computed as computed4, ref as ref4 } from "vue";
|
|
2589
|
+
function createChatCore(options) {
|
|
2590
|
+
const notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
|
|
2591
|
+
const directory = new ThreadDirectory({
|
|
2592
|
+
transport: options.transport,
|
|
2593
|
+
assistantId: options.assistantId || "lead_agent",
|
|
2594
|
+
maxCachedRuntimes: options.maxCachedSessions,
|
|
2595
|
+
maxConcurrentStreams: options.maxConcurrentStreams,
|
|
2596
|
+
twin: options.twin,
|
|
2597
|
+
notify,
|
|
2598
|
+
defaultThreadTitle: options.defaultThreadTitle
|
|
2599
|
+
});
|
|
2600
|
+
const currentThreadId = ref4(null);
|
|
2601
|
+
const threads = computed4(() => directory.threads.value);
|
|
2602
|
+
const threadsPagination = computed4(() => directory.threadsPagination.value);
|
|
2603
|
+
const activeRuntime = computed4(
|
|
2604
|
+
() => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
|
|
2605
|
+
);
|
|
2606
|
+
const view = computed4(() => activeRuntime.value?.view.value ?? { turns: [] });
|
|
2607
|
+
const turns = computed4(() => view.value.turns);
|
|
2608
|
+
const activeClarification = computed4(
|
|
2609
|
+
() => activeRuntime.value?.activeClarification.value
|
|
2610
|
+
);
|
|
2611
|
+
const isGenerating = computed4(
|
|
2612
|
+
() => !!activeRuntime.value && (activeRuntime.value.isGenerating.value || activeRuntime.value.isInitializing.value)
|
|
2613
|
+
);
|
|
2614
|
+
const isLoadingThread = computed4(() => activeRuntime.value?.isInitializing.value ?? false);
|
|
2615
|
+
const runs = computed4(
|
|
2616
|
+
() => activeRuntime.value?.runs.value ?? /* @__PURE__ */ new Map()
|
|
2617
|
+
);
|
|
2618
|
+
const toolCalls = computed4(
|
|
2619
|
+
() => turns.value.flatMap(
|
|
2620
|
+
(t) => t.ai.flatMap(
|
|
2621
|
+
(seg) => seg.tools.map((tool, index) => ({
|
|
2622
|
+
id: tool.callId,
|
|
2623
|
+
call: { id: tool.callId, name: tool.name, args: tool.input },
|
|
2624
|
+
result: tool.result ? { content: tool.result } : void 0,
|
|
2625
|
+
state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
|
|
2626
|
+
index
|
|
2627
|
+
}))
|
|
2628
|
+
)
|
|
2629
|
+
)
|
|
2630
|
+
);
|
|
2631
|
+
const clarificationAnswers = computed4(
|
|
2632
|
+
() => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
|
|
2633
|
+
);
|
|
2634
|
+
const activeInterrupt = computed4(() => activeRuntime.value?.interrupt.value);
|
|
2635
|
+
const hasPendingInterrupt = computed4(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
|
|
2636
|
+
const inputDisabled = computed4(() => isGenerating.value || hasPendingInterrupt.value);
|
|
2637
|
+
const streamError = computed4(() => activeRuntime.value?.streamError.value ?? null);
|
|
2638
|
+
const hasMoreHistory = computed4(() => activeRuntime.value?.hasMoreHistory.value ?? false);
|
|
2639
|
+
const loadingHistory = computed4(() => activeRuntime.value?.loadingHistory.value ?? false);
|
|
2640
|
+
const tokenUsage = computed4(() => activeRuntime.value?.tokenUsage.value ?? null);
|
|
2641
|
+
const runningNotConnectedThreadIds = computed4(() => directory.runningNotConnectedThreadIds.value);
|
|
2642
|
+
const getRunById = (runId) => runId ? runs.value.get(runId) : void 0;
|
|
2643
|
+
const getRunsByThreadId = (threadId) => threadId ? Array.from(runs.value.values()).filter((r) => r.threadId === threadId) : [];
|
|
2644
|
+
const ensureThreadId = async () => {
|
|
2645
|
+
if (currentThreadId.value) return { threadId: currentThreadId.value, isNew: false, thread: null };
|
|
2646
|
+
const thread = await directory.createThread({ source: "chat" });
|
|
2647
|
+
if (thread?.thread_id) currentThreadId.value = thread.thread_id;
|
|
2648
|
+
return thread?.thread_id ? { threadId: thread.thread_id, isNew: true, thread } : null;
|
|
2649
|
+
};
|
|
2650
|
+
const acquireSendRuntime = (threadId) => {
|
|
2651
|
+
const current = directory.getRuntime(threadId);
|
|
2652
|
+
if (!current?.isGenerating.value && directory.generatingCount >= directory.maxConcurrentStreams) {
|
|
2653
|
+
notify("warning", `\u5F53\u524D\u5DF2\u6709 ${directory.maxConcurrentStreams} \u4E2A\u5BF9\u8BDD\u6B63\u5728\u751F\u6210\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210\u540E\u518D\u53D1\u9001`);
|
|
2654
|
+
return null;
|
|
2655
|
+
}
|
|
2656
|
+
if (current) return current;
|
|
2657
|
+
const result = directory.acquireRuntime(threadId);
|
|
2658
|
+
if (result === "LIMIT_EXCEEDED") {
|
|
2659
|
+
notify("warning", "\u751F\u6210\u4E2D\u7684\u5BF9\u8BDD\u8FC7\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
|
|
2660
|
+
return null;
|
|
2661
|
+
}
|
|
2662
|
+
return result;
|
|
2663
|
+
};
|
|
2664
|
+
const sendMessage = async (text, sendOptions) => {
|
|
2665
|
+
if (isGenerating.value) return;
|
|
2666
|
+
const trimmed = String(text || "").trim();
|
|
2667
|
+
if (!trimmed) return;
|
|
2668
|
+
const info = await ensureThreadId();
|
|
2669
|
+
if (!info) return;
|
|
2670
|
+
const { threadId, isNew, thread } = info;
|
|
2671
|
+
if (runningNotConnectedThreadIds.value.has(threadId)) {
|
|
2672
|
+
notify("warning", "\u8BE5\u5BF9\u8BDD\u6B63\u5728\u751F\u6210\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210\u540E\u518D\u53D1\u9001");
|
|
2673
|
+
return;
|
|
2674
|
+
}
|
|
2675
|
+
const runtime = acquireSendRuntime(threadId);
|
|
2676
|
+
if (!runtime) return;
|
|
2677
|
+
runtime.touch();
|
|
2678
|
+
if (isNew && thread) directory.prependThread(thread);
|
|
2679
|
+
await runtime.init();
|
|
2680
|
+
runtime.submit(trimmed, sendOptions);
|
|
2681
|
+
};
|
|
2682
|
+
const loadThread = async (threadId) => {
|
|
2683
|
+
const result = directory.acquireRuntime(threadId);
|
|
2684
|
+
if (result === "LIMIT_EXCEEDED") {
|
|
2685
|
+
notify("warning", "\u751F\u6210\u4E2D\u7684\u5BF9\u8BDD\u8FC7\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
|
|
2686
|
+
return;
|
|
2687
|
+
}
|
|
2688
|
+
currentThreadId.value = threadId;
|
|
2689
|
+
result.touch();
|
|
2690
|
+
await result.init();
|
|
2691
|
+
};
|
|
2692
|
+
const regenerateTurn = async (aiSegmentId) => {
|
|
2693
|
+
if (isGenerating.value) return;
|
|
2694
|
+
const turn = turns.value.find((t) => t.ai.some((seg) => seg.id === aiSegmentId));
|
|
2695
|
+
const text = turn?.human.text ?? "";
|
|
2696
|
+
if (!turn || !text.trim()) {
|
|
2697
|
+
notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
|
|
2698
|
+
return;
|
|
2699
|
+
}
|
|
2700
|
+
await sendMessage(text, { kwargs: { ...turn.human.kwargs ?? {}, hide_from_ui: false } });
|
|
2701
|
+
};
|
|
2702
|
+
return {
|
|
2703
|
+
view,
|
|
2704
|
+
turns,
|
|
2705
|
+
isGenerating,
|
|
2706
|
+
isLoadingThread,
|
|
2707
|
+
currentThreadId,
|
|
2708
|
+
threads,
|
|
2709
|
+
threadsPagination,
|
|
2710
|
+
runs,
|
|
2711
|
+
toolCalls,
|
|
2712
|
+
getRunById,
|
|
2713
|
+
getRunsByThreadId,
|
|
2714
|
+
clarificationAnswers,
|
|
2715
|
+
activeClarification,
|
|
2716
|
+
setClarificationAnswer: (toolCallId, answer) => activeRuntime.value?.setClarificationAnswer(toolCallId, answer),
|
|
2717
|
+
clearClarificationAnswers: () => activeRuntime.value?.clearClarificationAnswers(),
|
|
2718
|
+
sendMessage,
|
|
2719
|
+
loadThread,
|
|
2720
|
+
stopGeneration: () => activeRuntime.value?.stop(),
|
|
2721
|
+
clearMessages: () => {
|
|
2722
|
+
currentThreadId.value = null;
|
|
2723
|
+
},
|
|
2724
|
+
applyFeedback: (messageId, feedback) => activeRuntime.value?.applyFeedback(messageId, feedback),
|
|
2725
|
+
regenerateTurn,
|
|
2726
|
+
addOptimisticTurn: (body) => activeRuntime.value?.addOptimisticTurn(body),
|
|
2727
|
+
updateAiBody: (aiId, body) => activeRuntime.value?.updateAiBody(aiId, body),
|
|
2728
|
+
decorate: (messageId, patch) => activeRuntime.value?.decorate(messageId, patch),
|
|
2729
|
+
finalizeTurns: () => activeRuntime.value?.finalizeTurns(),
|
|
2730
|
+
fetchThreads: (reset, keyword) => directory.fetchThreads(reset, keyword),
|
|
2731
|
+
deleteThread: async (threadId) => {
|
|
2732
|
+
const deleted = await directory.deleteThread(threadId);
|
|
2733
|
+
if (deleted && currentThreadId.value === threadId) currentThreadId.value = null;
|
|
2734
|
+
return deleted;
|
|
2735
|
+
},
|
|
2736
|
+
updateThreadTitle: (threadId, title) => directory.updateThreadTitle(threadId, title),
|
|
2737
|
+
removeThreadFromList: (threadId) => directory.removeThreadFromList(threadId),
|
|
2738
|
+
isThreadRunning: (threadId) => directory.isThreadRunning(threadId),
|
|
2739
|
+
runningNotConnectedThreadIds,
|
|
2740
|
+
recoverRunningThreads: () => directory.recoverRunningThreads(),
|
|
2741
|
+
activeInterrupt,
|
|
2742
|
+
interrupt: activeInterrupt,
|
|
2743
|
+
hasPendingInterrupt,
|
|
2744
|
+
inputDisabled,
|
|
2745
|
+
streamError,
|
|
2746
|
+
hasMoreHistory,
|
|
2747
|
+
loadingHistory,
|
|
2748
|
+
tokenUsage,
|
|
2749
|
+
loadOlderMessages: async () => await activeRuntime.value?.loadOlderMessages() ?? false,
|
|
2750
|
+
resumeInterrupt: async (decisions) => {
|
|
2751
|
+
const runtime = activeRuntime.value;
|
|
2752
|
+
if (!runtime) throw new Error("\u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u7684\u4F1A\u8BDD");
|
|
2753
|
+
await runtime.resumeInterrupt(decisions);
|
|
2754
|
+
},
|
|
2755
|
+
loadArtifactContent: async (path) => {
|
|
2756
|
+
const threadId = currentThreadId.value;
|
|
2757
|
+
if (!threadId || !activeRuntime.value) throw new Error("\u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u7684\u4F1A\u8BDD\uFF0C\u65E0\u6CD5\u52A0\u8F7D artifact \u5185\u5BB9");
|
|
2758
|
+
return options.transport.fetchArtifactContent(threadId, path, { full: true });
|
|
2759
|
+
},
|
|
2760
|
+
dispose: () => directory.dispose()
|
|
2761
|
+
};
|
|
2762
|
+
}
|
|
2763
|
+
|
|
2764
|
+
export {
|
|
2765
|
+
__privateGet,
|
|
2766
|
+
__privateAdd,
|
|
2767
|
+
__privateSet,
|
|
2768
|
+
DEFAULT_MAX_CACHED_SESSIONS,
|
|
2769
|
+
DEFAULT_MAX_CONCURRENT_STREAMS,
|
|
2770
|
+
DEFAULT_ASSISTANT_ID,
|
|
2771
|
+
formatStr,
|
|
2772
|
+
INJECTED_TAGS,
|
|
2773
|
+
isInjectedElement,
|
|
2774
|
+
collectVisibleText,
|
|
2775
|
+
collectTextKeepSxin,
|
|
2776
|
+
tokenizeSxin,
|
|
2777
|
+
formatAnswerText,
|
|
2778
|
+
extractThreadInfo,
|
|
2779
|
+
buildHumanInputResponse,
|
|
2780
|
+
extractStateMessages,
|
|
2781
|
+
mergeStateWithPageMessages,
|
|
2782
|
+
ensureRunningRun,
|
|
2783
|
+
MESSAGE_TYPE_NORMALIZE,
|
|
2784
|
+
normalizeMessageType,
|
|
2785
|
+
toRunMessage,
|
|
2786
|
+
extractRunEnrichment,
|
|
2787
|
+
backfillRunMessageFeedback,
|
|
2788
|
+
runMessagesToMessages,
|
|
2789
|
+
stateMessagesToRunMessages,
|
|
2790
|
+
simpleHash,
|
|
2791
|
+
readMessageContentText,
|
|
2792
|
+
extractTextFromMessage,
|
|
2793
|
+
extractAiContentFromMessage,
|
|
2794
|
+
isVisibleUserMessage,
|
|
2795
|
+
extractUserMessageTexts,
|
|
2796
|
+
isHiddenUserMessage,
|
|
2797
|
+
isWriteFileToolName,
|
|
2798
|
+
getToolCallArtifactMeta,
|
|
2799
|
+
resolveReportArtifactKind,
|
|
2800
|
+
extractTitleFromArtifactPath,
|
|
2801
|
+
OUTLINE_MAX_LEVEL,
|
|
2802
|
+
normalizeOutline,
|
|
2803
|
+
validateOutline,
|
|
2804
|
+
createEmptySubChapter,
|
|
2805
|
+
ensureOutlineContentThemes,
|
|
2806
|
+
parseMarkdownToOutline,
|
|
2807
|
+
isReportBodyHtml,
|
|
2808
|
+
extractReportTitleFromBody,
|
|
2809
|
+
isHumanMessage,
|
|
2810
|
+
parseHumanMessageId,
|
|
2811
|
+
getHumanMessageBaseId,
|
|
2812
|
+
isAiMessage,
|
|
2813
|
+
isToolMessage,
|
|
2814
|
+
deriveToolsFromMessages,
|
|
2815
|
+
normalizeUsage,
|
|
2816
|
+
sliceBodySegments,
|
|
2817
|
+
buildRunInfo,
|
|
2818
|
+
buildRunDirectLatencyMs,
|
|
2819
|
+
pickRunMessageMetadata,
|
|
2820
|
+
extractSemanticPatchesFromMessages,
|
|
2821
|
+
createSemanticOverlay,
|
|
2822
|
+
applySemanticPatches,
|
|
2823
|
+
extractFromToolResult,
|
|
2824
|
+
createMessageDiff,
|
|
2825
|
+
createMaterializer,
|
|
2826
|
+
createRuntimeMaterializer,
|
|
2827
|
+
createThreadRuntime,
|
|
2828
|
+
ThreadDirectory,
|
|
2829
|
+
createChatCore
|
|
2830
|
+
};
|