@cqfe/sxin-chat-core 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ChatCore-C-G9isDM.d.cts → ChatCore-CCeoxjP9.d.cts} +437 -342
- package/dist/{ChatCore-C-G9isDM.d.ts → ChatCore-CCeoxjP9.d.ts} +437 -342
- package/dist/chunk-2AXUXZVK.mjs +2661 -0
- package/dist/index.cjs +1042 -1550
- package/dist/index.d.cts +228 -220
- package/dist/index.d.ts +228 -220
- package/dist/index.mjs +356 -141
- package/dist/vue/index.cjs +1068 -2055
- package/dist/vue/index.d.cts +2 -2
- package/dist/vue/index.d.ts +2 -2
- package/dist/vue/index.mjs +1 -1
- package/package.json +3 -3
- package/dist/chunk-K2ZOZPBB.mjs +0 -3391
package/dist/chunk-K2ZOZPBB.mjs
DELETED
|
@@ -1,3391 +0,0 @@
|
|
|
1
|
-
// src/constants.ts
|
|
2
|
-
var DEFAULT_MAX_CACHED_SESSIONS = 10;
|
|
3
|
-
var DEFAULT_MAX_CONCURRENT_STREAMS = 3;
|
|
4
|
-
var DEFAULT_ASSISTANT_ID = "lead_agent";
|
|
5
|
-
|
|
6
|
-
// src/parser/sxin-ast-attrs.ts
|
|
7
|
-
function formatStr(str) {
|
|
8
|
-
if (!str) return str;
|
|
9
|
-
return str.replace(/["`\s]/g, "");
|
|
10
|
-
}
|
|
11
|
-
function skipWhitespace(source, i) {
|
|
12
|
-
const len = source.length;
|
|
13
|
-
while (i < len && /\s/.test(source[i])) i++;
|
|
14
|
-
return i;
|
|
15
|
-
}
|
|
16
|
-
function readQuotedValue(source, j, key) {
|
|
17
|
-
const quote = source[j];
|
|
18
|
-
const close = source.indexOf(quote, j + 1);
|
|
19
|
-
if (close === -1) {
|
|
20
|
-
return { key, value: source.slice(j + 1), next: source.length, hasValue: true, truncated: true };
|
|
21
|
-
}
|
|
22
|
-
return { key, value: source.slice(j + 1, close), next: close + 1, hasValue: true, truncated: false };
|
|
23
|
-
}
|
|
24
|
-
function readBareValue(source, j, key) {
|
|
25
|
-
const valMatch = /^[^\s>]+/.exec(source.slice(j));
|
|
26
|
-
const raw = valMatch ? valMatch[0] : "";
|
|
27
|
-
const value = raw.endsWith("/") ? raw.slice(0, -1) : raw;
|
|
28
|
-
return { key, value, next: j + raw.length, hasValue: true, truncated: false };
|
|
29
|
-
}
|
|
30
|
-
function readAttrPair(source, i) {
|
|
31
|
-
const keyMatch = /^[\w-]+/.exec(source.slice(i));
|
|
32
|
-
if (!keyMatch) return null;
|
|
33
|
-
const key = keyMatch[0];
|
|
34
|
-
let j = skipWhitespace(source, i + key.length);
|
|
35
|
-
if (source[j] !== "=") return { key, value: "", next: j, hasValue: false, truncated: false };
|
|
36
|
-
j = skipWhitespace(source, j + 1);
|
|
37
|
-
if (j >= source.length) {
|
|
38
|
-
return { key, value: "", next: source.length, hasValue: true, truncated: true };
|
|
39
|
-
}
|
|
40
|
-
const quote = source[j];
|
|
41
|
-
return quote === '"' || quote === "'" ? readQuotedValue(source, j, key) : readBareValue(source, j, key);
|
|
42
|
-
}
|
|
43
|
-
function matchTerminator(source, i) {
|
|
44
|
-
if (source[i] === ">") return { selfClosing: false };
|
|
45
|
-
if (source[i] === "/" && source[i + 1] === ">") return { selfClosing: true };
|
|
46
|
-
return null;
|
|
47
|
-
}
|
|
48
|
-
function parseAttrs(source, pos) {
|
|
49
|
-
const attrs = {};
|
|
50
|
-
const len = source.length;
|
|
51
|
-
let i = pos;
|
|
52
|
-
while (i < len) {
|
|
53
|
-
i = skipWhitespace(source, i);
|
|
54
|
-
if (i >= len) break;
|
|
55
|
-
const term = matchTerminator(source, i);
|
|
56
|
-
if (term) return { attrs, pos: i, terminated: true, selfClosing: term.selfClosing };
|
|
57
|
-
const pair = readAttrPair(source, i);
|
|
58
|
-
if (!pair) {
|
|
59
|
-
i++;
|
|
60
|
-
continue;
|
|
61
|
-
}
|
|
62
|
-
i = pair.next;
|
|
63
|
-
if (!pair.hasValue) continue;
|
|
64
|
-
attrs[formatStr(pair.key)] = formatStr(pair.value);
|
|
65
|
-
if (pair.truncated) return { attrs, pos: len, terminated: false, selfClosing: false };
|
|
66
|
-
}
|
|
67
|
-
return { attrs, pos: len, terminated: false, selfClosing: false };
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// src/parser/sxin-ast-collect.ts
|
|
71
|
-
var INJECTED_TAGS = /* @__PURE__ */ new Set([
|
|
72
|
-
"think",
|
|
73
|
-
"current_user",
|
|
74
|
-
"request_context",
|
|
75
|
-
"system-reminder",
|
|
76
|
-
"memory",
|
|
77
|
-
"current_date",
|
|
78
|
-
"requested_capabilities",
|
|
79
|
-
"user_selections",
|
|
80
|
-
"current_uploads",
|
|
81
|
-
"uploaded_files",
|
|
82
|
-
"attachments",
|
|
83
|
-
"slash_skill_activation"
|
|
84
|
-
]);
|
|
85
|
-
function isInjectedElement(node) {
|
|
86
|
-
return INJECTED_TAGS.has(node.tagName);
|
|
87
|
-
}
|
|
88
|
-
function collectVisibleText(source, nodes) {
|
|
89
|
-
const parts = [];
|
|
90
|
-
const walk = (list) => {
|
|
91
|
-
for (const node of list) {
|
|
92
|
-
if (node.type === "text") {
|
|
93
|
-
parts.push(node.value);
|
|
94
|
-
} else if (node.type === "comment") {
|
|
95
|
-
parts.push(`<!--${node.content}-->`);
|
|
96
|
-
} else if (!node.closed && !INJECTED_TAGS.has(node.tagName)) {
|
|
97
|
-
parts.push(source.slice(node.start, node.end));
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
walk(nodes);
|
|
102
|
-
return parts.join("");
|
|
103
|
-
}
|
|
104
|
-
function collectTextKeepSxin(source, nodes) {
|
|
105
|
-
const parts = [];
|
|
106
|
-
const walk = (list) => {
|
|
107
|
-
for (const node of list) {
|
|
108
|
-
if (node.type === "text") {
|
|
109
|
-
parts.push(node.value);
|
|
110
|
-
} else if (node.type === "comment") {
|
|
111
|
-
parts.push(`<!--${node.content}-->`);
|
|
112
|
-
} else if (!isInjectedElement(node)) {
|
|
113
|
-
parts.push(source.slice(node.start, node.end));
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
};
|
|
117
|
-
walk(nodes);
|
|
118
|
-
return parts.join("");
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// src/parser/sxin-ast.ts
|
|
122
|
-
function isTagNameChar(c) {
|
|
123
|
-
return !!c && /[\w-]/.test(c);
|
|
124
|
-
}
|
|
125
|
-
var VOID_TAGS = /* @__PURE__ */ new Set([
|
|
126
|
-
"area",
|
|
127
|
-
"base",
|
|
128
|
-
"br",
|
|
129
|
-
"col",
|
|
130
|
-
"embed",
|
|
131
|
-
"hr",
|
|
132
|
-
"img",
|
|
133
|
-
"input",
|
|
134
|
-
"link",
|
|
135
|
-
"meta",
|
|
136
|
-
"param",
|
|
137
|
-
"source",
|
|
138
|
-
"track",
|
|
139
|
-
"wbr"
|
|
140
|
-
]);
|
|
141
|
-
function readTagName(source, pos) {
|
|
142
|
-
if (!/[a-zA-Z]/.test(source[pos] || "")) return null;
|
|
143
|
-
let end = pos + 1;
|
|
144
|
-
while (isTagNameChar(source[end])) end++;
|
|
145
|
-
return { name: source.slice(pos, end).toLowerCase(), end };
|
|
146
|
-
}
|
|
147
|
-
function attachNode(stack, topLevel, node) {
|
|
148
|
-
const parent = stack[stack.length - 1];
|
|
149
|
-
if (parent) parent.children.push(node);
|
|
150
|
-
else topLevel.push(node);
|
|
151
|
-
}
|
|
152
|
-
function flushTextAt(source, st, to) {
|
|
153
|
-
if (to > st.textStart) {
|
|
154
|
-
attachNode(st.stack, st.nodes, {
|
|
155
|
-
type: "text",
|
|
156
|
-
value: source.slice(st.textStart, to),
|
|
157
|
-
start: st.textStart,
|
|
158
|
-
end: to
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
function handleComment(source, i, st) {
|
|
163
|
-
if (!source.startsWith("<!--", i)) return false;
|
|
164
|
-
const close = source.indexOf("-->", i + 4);
|
|
165
|
-
if (close === -1) {
|
|
166
|
-
st.i = source.length;
|
|
167
|
-
return true;
|
|
168
|
-
}
|
|
169
|
-
flushTextAt(source, st, i);
|
|
170
|
-
attachNode(st.stack, st.nodes, {
|
|
171
|
-
type: "comment",
|
|
172
|
-
content: source.slice(i + 4, close),
|
|
173
|
-
start: i,
|
|
174
|
-
end: close + 3
|
|
175
|
-
});
|
|
176
|
-
st.i = close + 3;
|
|
177
|
-
st.textStart = st.i;
|
|
178
|
-
return true;
|
|
179
|
-
}
|
|
180
|
-
function handleCloseTag(source, i, st) {
|
|
181
|
-
if (source[i + 1] !== "/") return false;
|
|
182
|
-
const tag = readTagName(source, i + 2);
|
|
183
|
-
if (!tag) {
|
|
184
|
-
st.i = i + 1;
|
|
185
|
-
return true;
|
|
186
|
-
}
|
|
187
|
-
let k = tag.end;
|
|
188
|
-
while (k < source.length && /\s/.test(source[k])) k++;
|
|
189
|
-
if (source[k] !== ">") {
|
|
190
|
-
st.i = i + 1;
|
|
191
|
-
return true;
|
|
192
|
-
}
|
|
193
|
-
let depth = -1;
|
|
194
|
-
for (let d = st.stack.length - 1; d >= 0; d--) {
|
|
195
|
-
if (st.stack[d].tagName === tag.name) {
|
|
196
|
-
depth = d;
|
|
197
|
-
break;
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
if (depth === -1) {
|
|
201
|
-
st.i = k + 1;
|
|
202
|
-
return true;
|
|
203
|
-
}
|
|
204
|
-
flushTextAt(source, st, i);
|
|
205
|
-
while (st.stack.length - 1 > depth) {
|
|
206
|
-
st.stack.pop().end = i;
|
|
207
|
-
}
|
|
208
|
-
const target = st.stack[st.stack.length - 1];
|
|
209
|
-
st.stack.pop();
|
|
210
|
-
target.closed = true;
|
|
211
|
-
target.end = k + 1;
|
|
212
|
-
st.i = k + 1;
|
|
213
|
-
st.textStart = k + 1;
|
|
214
|
-
return true;
|
|
215
|
-
}
|
|
216
|
-
function handleOpenTag(source, i, st) {
|
|
217
|
-
const tag = readTagName(source, i + 1);
|
|
218
|
-
if (!tag) {
|
|
219
|
-
st.i = i + 1;
|
|
220
|
-
return;
|
|
221
|
-
}
|
|
222
|
-
const len = source.length;
|
|
223
|
-
const { attrs, pos, terminated, selfClosing } = parseAttrs(source, tag.end);
|
|
224
|
-
flushTextAt(source, st, i);
|
|
225
|
-
const asSelfClosing = selfClosing || terminated && VOID_TAGS.has(tag.name);
|
|
226
|
-
const el = {
|
|
227
|
-
type: "element",
|
|
228
|
-
tagName: tag.name,
|
|
229
|
-
attrs,
|
|
230
|
-
children: [],
|
|
231
|
-
selfClosing,
|
|
232
|
-
closed: asSelfClosing,
|
|
233
|
-
// 自闭合或 void 元素视为已闭合
|
|
234
|
-
start: i,
|
|
235
|
-
end: len
|
|
236
|
-
// 未闭合时延伸到 EOF
|
|
237
|
-
};
|
|
238
|
-
attachNode(st.stack, st.nodes, el);
|
|
239
|
-
if (!terminated) {
|
|
240
|
-
st.i = len;
|
|
241
|
-
st.textStart = len;
|
|
242
|
-
return;
|
|
243
|
-
}
|
|
244
|
-
if (asSelfClosing) {
|
|
245
|
-
el.end = selfClosing ? pos + 2 : pos + 1;
|
|
246
|
-
st.i = el.end;
|
|
247
|
-
} else {
|
|
248
|
-
st.stack.push(el);
|
|
249
|
-
st.i = pos + 1;
|
|
250
|
-
}
|
|
251
|
-
st.textStart = st.i;
|
|
252
|
-
}
|
|
253
|
-
var OPAQUE_CONTENT_TAGS = /* @__PURE__ */ new Set(["think"]);
|
|
254
|
-
function findCloseTagEnd(source, from, name) {
|
|
255
|
-
const lower = source.toLowerCase();
|
|
256
|
-
const needle = "</" + name;
|
|
257
|
-
let p = lower.indexOf(needle, from);
|
|
258
|
-
while (p !== -1) {
|
|
259
|
-
let k = p + needle.length;
|
|
260
|
-
while (k < source.length && /\s/.test(source[k])) k++;
|
|
261
|
-
if (source[k] === ">") return k + 1;
|
|
262
|
-
p = lower.indexOf(needle, p + 1);
|
|
263
|
-
}
|
|
264
|
-
return -1;
|
|
265
|
-
}
|
|
266
|
-
function handleOpaqueTag(source, i, st) {
|
|
267
|
-
const tag = readTagName(source, i + 1);
|
|
268
|
-
if (!tag || !OPAQUE_CONTENT_TAGS.has(tag.name)) return false;
|
|
269
|
-
const { attrs, pos, terminated, selfClosing } = parseAttrs(source, tag.end);
|
|
270
|
-
flushTextAt(source, st, i);
|
|
271
|
-
if (!terminated) {
|
|
272
|
-
attachNode(st.stack, st.nodes, {
|
|
273
|
-
type: "element",
|
|
274
|
-
tagName: tag.name,
|
|
275
|
-
attrs,
|
|
276
|
-
children: [],
|
|
277
|
-
selfClosing,
|
|
278
|
-
closed: false,
|
|
279
|
-
start: i,
|
|
280
|
-
end: source.length
|
|
281
|
-
});
|
|
282
|
-
st.i = source.length;
|
|
283
|
-
st.textStart = source.length;
|
|
284
|
-
return true;
|
|
285
|
-
}
|
|
286
|
-
const openEnd = selfClosing ? pos + 2 : pos + 1;
|
|
287
|
-
const closeEnd = selfClosing ? -1 : findCloseTagEnd(source, openEnd, tag.name);
|
|
288
|
-
const el = {
|
|
289
|
-
type: "element",
|
|
290
|
-
tagName: tag.name,
|
|
291
|
-
attrs,
|
|
292
|
-
children: [],
|
|
293
|
-
selfClosing,
|
|
294
|
-
closed: selfClosing || closeEnd !== -1,
|
|
295
|
-
start: i,
|
|
296
|
-
end: closeEnd !== -1 ? closeEnd : source.length
|
|
297
|
-
};
|
|
298
|
-
attachNode(st.stack, st.nodes, el);
|
|
299
|
-
st.i = el.end;
|
|
300
|
-
st.textStart = el.end;
|
|
301
|
-
return true;
|
|
302
|
-
}
|
|
303
|
-
function tokenizeSxin(source) {
|
|
304
|
-
const len = source.length;
|
|
305
|
-
const st = { nodes: [], stack: [], textStart: 0, i: 0 };
|
|
306
|
-
while (st.i < len) {
|
|
307
|
-
if (source[st.i] !== "<") {
|
|
308
|
-
st.i++;
|
|
309
|
-
continue;
|
|
310
|
-
}
|
|
311
|
-
if (handleComment(source, st.i, st)) continue;
|
|
312
|
-
if (handleCloseTag(source, st.i, st)) continue;
|
|
313
|
-
if (handleOpaqueTag(source, st.i, st)) continue;
|
|
314
|
-
handleOpenTag(source, st.i, st);
|
|
315
|
-
}
|
|
316
|
-
flushTextAt(source, st, len);
|
|
317
|
-
return st.nodes;
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
// src/parser/citation.ts
|
|
321
|
-
var toStringArray = (v) => {
|
|
322
|
-
if (!v) return [];
|
|
323
|
-
if (Array.isArray(v))
|
|
324
|
-
return v.map((x) => String(x)).map((x) => x.trim()).filter(Boolean);
|
|
325
|
-
return [String(v).trim()].filter(Boolean);
|
|
326
|
-
};
|
|
327
|
-
var pick = (obj, keys) => {
|
|
328
|
-
for (const k of keys) {
|
|
329
|
-
const v = obj?.[k];
|
|
330
|
-
if (v !== void 0 && v !== null && String(v).trim() !== "") return v;
|
|
331
|
-
}
|
|
332
|
-
return void 0;
|
|
333
|
-
};
|
|
334
|
-
var STRING_FIELD_KEYS = {
|
|
335
|
-
rawKey: ["key", "refId", "ref_id", "citationId", "citation_id"],
|
|
336
|
-
refId: ["refId", "ref_id", "citationId", "citation_id"],
|
|
337
|
-
globalRef: ["globalRef", "global_ref"],
|
|
338
|
-
minioBucket: ["minioBucket", "minio_bucket", "bucket", "minioBucketName"],
|
|
339
|
-
minioObject: ["minioObject", "minio_object", "object", "object_name", "objectName", "minioObjectName"],
|
|
340
|
-
previewUrl: ["previewUrl", "preview_url", "url", "preview"],
|
|
341
|
-
docUrl: ["docUrl", "doc_url"],
|
|
342
|
-
docId: ["docId", "doc_id", "document_id", "docid", "id"],
|
|
343
|
-
title: ["title", "docName", "doc_name", "docOriginalName", "doc_original_name", "file_name", "filename", "name"],
|
|
344
|
-
fileType: ["fileType", "file_type", "ext", "extension"]
|
|
345
|
-
};
|
|
346
|
-
var ARRAY_FIELD_KEYS = {
|
|
347
|
-
sourcePages: ["sourcePages", "source_pages", "pages", "page_idxs", "page_idx"],
|
|
348
|
-
highlightText: ["highlightText", "highlight_text"]
|
|
349
|
-
};
|
|
350
|
-
var pickString = (raw, meta, keys) => String(pick(raw, keys) ?? pick(meta, keys) ?? "").trim();
|
|
351
|
-
var pickStringArray = (raw, meta, keys) => toStringArray(pick(raw, keys) ?? pick(meta, keys));
|
|
352
|
-
var orUndefined = (s) => s || void 0;
|
|
353
|
-
var nonEmpty = (a) => a.length ? a : void 0;
|
|
354
|
-
var resolveCitationKey = (s) => {
|
|
355
|
-
if (s.rawKey) return s.rawKey;
|
|
356
|
-
if (s.minioBucket && s.minioObject) return `${s.minioBucket}:${s.minioObject}`;
|
|
357
|
-
if (s.docId) return `doc:${s.docId}`;
|
|
358
|
-
if (s.title) return `title:${s.title}`;
|
|
359
|
-
return "";
|
|
360
|
-
};
|
|
361
|
-
var parseBboxEntry = (entry) => {
|
|
362
|
-
const b = entry?.bbox;
|
|
363
|
-
const pageIdx = Number(entry?.page_idx);
|
|
364
|
-
const left = Number(b?.left);
|
|
365
|
-
const top = Number(b?.top);
|
|
366
|
-
const right = Number(b?.right);
|
|
367
|
-
const bottom = Number(b?.bottom);
|
|
368
|
-
if (![left, top, right, bottom].every(Number.isFinite)) return null;
|
|
369
|
-
return {
|
|
370
|
-
page: Number.isFinite(pageIdx) ? Math.max(1, pageIdx + 1) : 1,
|
|
371
|
-
bbox: [left, top, right, bottom]
|
|
372
|
-
};
|
|
373
|
-
};
|
|
374
|
-
var parseCitationLocations = (raw, meta) => {
|
|
375
|
-
const rawBboxes = Array.isArray(raw?.source_bboxes) ? raw.source_bboxes : Array.isArray(meta?.source_bboxes) ? meta.source_bboxes : [];
|
|
376
|
-
return rawBboxes.map(parseBboxEntry).filter(Boolean);
|
|
377
|
-
};
|
|
378
|
-
var normalizeOne = (raw) => {
|
|
379
|
-
if (!raw || typeof raw !== "object") return null;
|
|
380
|
-
const meta = raw.metadata && typeof raw.metadata === "object" ? raw.metadata : {};
|
|
381
|
-
const str = {};
|
|
382
|
-
for (const [field, keys] of Object.entries(STRING_FIELD_KEYS)) {
|
|
383
|
-
str[field] = pickString(raw, meta, keys);
|
|
384
|
-
}
|
|
385
|
-
const { refId, globalRef, minioBucket, minioObject, previewUrl, docUrl, docId, title, fileType } = str;
|
|
386
|
-
const arr = {};
|
|
387
|
-
for (const [field, keys] of Object.entries(ARRAY_FIELD_KEYS)) {
|
|
388
|
-
arr[field] = pickStringArray(raw, meta, keys);
|
|
389
|
-
}
|
|
390
|
-
const { sourcePages, highlightText } = arr;
|
|
391
|
-
const searchText = highlightText[0] || "";
|
|
392
|
-
const citationLocations = parseCitationLocations(raw, meta);
|
|
393
|
-
const key = resolveCitationKey(str);
|
|
394
|
-
if (!key && !previewUrl && !docUrl) return null;
|
|
395
|
-
return {
|
|
396
|
-
key,
|
|
397
|
-
refId: orUndefined(refId),
|
|
398
|
-
globalRef: orUndefined(globalRef),
|
|
399
|
-
title,
|
|
400
|
-
docId,
|
|
401
|
-
minioBucket: orUndefined(minioBucket),
|
|
402
|
-
minioObject: orUndefined(minioObject),
|
|
403
|
-
previewUrl: orUndefined(previewUrl),
|
|
404
|
-
docUrl: orUndefined(docUrl),
|
|
405
|
-
fileType: orUndefined(fileType),
|
|
406
|
-
sourcePages: nonEmpty(sourcePages),
|
|
407
|
-
citationLocations: nonEmpty(citationLocations),
|
|
408
|
-
highlightText: nonEmpty(highlightText),
|
|
409
|
-
searchText: orUndefined(searchText)
|
|
410
|
-
};
|
|
411
|
-
};
|
|
412
|
-
var KB_CITATION_CONTRACT = "support.kbCitation";
|
|
413
|
-
var REF_ID_KEYS = ["ref-id", "refId", "ref_id", "citation-id", "citationId", "citation_id", "id"];
|
|
414
|
-
var SEARCH_TEXT_KEYS = ["search-text", "searchText", "search_text", "keyword"];
|
|
415
|
-
var REF_ID_LIST_KEY_RE = /^(ref|citation)[-_]?ids?$/i;
|
|
416
|
-
var isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
417
|
-
var pickFirstString = (obj, keys) => {
|
|
418
|
-
for (const k of keys) {
|
|
419
|
-
const v = obj?.[k];
|
|
420
|
-
if (v === void 0 || v === null) continue;
|
|
421
|
-
const s = String(v).trim();
|
|
422
|
-
if (s) return s;
|
|
423
|
-
}
|
|
424
|
-
return void 0;
|
|
425
|
-
};
|
|
426
|
-
function extractCitationAnchorsFromSpec(spec) {
|
|
427
|
-
const anchors = [];
|
|
428
|
-
const seen = /* @__PURE__ */ new Set();
|
|
429
|
-
const candidates = [];
|
|
430
|
-
if (isPlainObject(spec)) candidates.push(spec);
|
|
431
|
-
for (const [key, value] of Object.entries(spec || {})) {
|
|
432
|
-
if (Array.isArray(value)) {
|
|
433
|
-
for (const item of value) if (isPlainObject(item)) candidates.push(item);
|
|
434
|
-
} else if (typeof value === "string" && /,/.test(value) && REF_ID_LIST_KEY_RE.test(key)) {
|
|
435
|
-
for (const id of value.split(",")) candidates.push({ "ref-id": id });
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
for (const item of candidates) {
|
|
439
|
-
const refId = pickFirstString(item, REF_ID_KEYS);
|
|
440
|
-
if (!refId || seen.has(refId)) continue;
|
|
441
|
-
seen.add(refId);
|
|
442
|
-
const anchor = { refId, title: "" };
|
|
443
|
-
const searchText = pickFirstString(item, SEARCH_TEXT_KEYS);
|
|
444
|
-
if (searchText) anchor.searchText = searchText;
|
|
445
|
-
anchors.push(anchor);
|
|
446
|
-
}
|
|
447
|
-
return anchors;
|
|
448
|
-
}
|
|
449
|
-
function extractCitationAnchors(blocks) {
|
|
450
|
-
const anchors = [];
|
|
451
|
-
const seen = /* @__PURE__ */ new Set();
|
|
452
|
-
for (const block of blocks) {
|
|
453
|
-
if (block.type !== "custom") continue;
|
|
454
|
-
const custom = block;
|
|
455
|
-
if (custom.tagName !== "sxin-item") continue;
|
|
456
|
-
const spec = custom.spec || {};
|
|
457
|
-
if (String(spec.contract || "").trim() !== KB_CITATION_CONTRACT) continue;
|
|
458
|
-
for (const anchor of extractCitationAnchorsFromSpec(spec)) {
|
|
459
|
-
if (seen.has(anchor.refId)) continue;
|
|
460
|
-
seen.add(anchor.refId);
|
|
461
|
-
anchors.push(anchor);
|
|
462
|
-
}
|
|
463
|
-
}
|
|
464
|
-
return anchors;
|
|
465
|
-
}
|
|
466
|
-
function parseKnowledgeItemsFromValue(value) {
|
|
467
|
-
if (!value) return [];
|
|
468
|
-
const rawList = Array.isArray(value) ? value : typeof value === "object" ? [value] : [];
|
|
469
|
-
const result = [];
|
|
470
|
-
for (const raw of rawList) {
|
|
471
|
-
const it = normalizeOne(raw);
|
|
472
|
-
if (it) result.push(it);
|
|
473
|
-
}
|
|
474
|
-
return result;
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
// src/parser/message-id.ts
|
|
478
|
-
var _idSeq = 0;
|
|
479
|
-
function genMessageId() {
|
|
480
|
-
return `msg-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
|
|
481
|
-
}
|
|
482
|
-
function genBlockId() {
|
|
483
|
-
return `block-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
// src/parser/hitl.ts
|
|
487
|
-
import { isEqual } from "lodash";
|
|
488
|
-
function parseHitlPayload(value) {
|
|
489
|
-
if (!value || typeof value !== "object") return null;
|
|
490
|
-
const raw = value;
|
|
491
|
-
const requests = raw.actionRequests ?? raw.action_requests;
|
|
492
|
-
if (!Array.isArray(requests) || !requests.length) return null;
|
|
493
|
-
const configs = raw.reviewConfigs ?? raw.review_configs;
|
|
494
|
-
return {
|
|
495
|
-
actionRequests: requests,
|
|
496
|
-
reviewConfigs: Array.isArray(configs) ? configs : []
|
|
497
|
-
};
|
|
498
|
-
}
|
|
499
|
-
function getAllowedDecisions(configs, actionName) {
|
|
500
|
-
const cfg = configs.find((c) => c.action_name === actionName);
|
|
501
|
-
const list = cfg?.allowedDecisions ?? cfg?.allowed_decisions;
|
|
502
|
-
return list?.length ? list : ["approve", "reject"];
|
|
503
|
-
}
|
|
504
|
-
function normalizeForCompare(value) {
|
|
505
|
-
if (Array.isArray(value)) return value.map(normalizeForCompare);
|
|
506
|
-
if (value && typeof value === "object") {
|
|
507
|
-
return Object.keys(value).sort().reduce((acc, key) => {
|
|
508
|
-
acc[key] = normalizeForCompare(value[key]);
|
|
509
|
-
return acc;
|
|
510
|
-
}, {});
|
|
511
|
-
}
|
|
512
|
-
return value;
|
|
513
|
-
}
|
|
514
|
-
function isSameArgs(a, b) {
|
|
515
|
-
return isEqual(normalizeForCompare(a), normalizeForCompare(b));
|
|
516
|
-
}
|
|
517
|
-
function buildHitlDecisions(requests, currentArgsList) {
|
|
518
|
-
return requests.map((req, i) => {
|
|
519
|
-
const current = currentArgsList[i];
|
|
520
|
-
if (!current || isSameArgs(req.args, current)) return { type: "approve" };
|
|
521
|
-
return { type: "edit", edited_action: { name: req.name, args: current } };
|
|
522
|
-
});
|
|
523
|
-
}
|
|
524
|
-
function buildRejectDecisions(requests) {
|
|
525
|
-
return requests.map(() => ({ type: "reject" }));
|
|
526
|
-
}
|
|
527
|
-
function buildInterruptReviewBlock(interrupt, responded) {
|
|
528
|
-
const payload = parseHitlPayload(interrupt.value);
|
|
529
|
-
if (!payload) return null;
|
|
530
|
-
const interruptId = String(interrupt.id || genMessageId());
|
|
531
|
-
const status = responded ? "completed" : "pending";
|
|
532
|
-
return {
|
|
533
|
-
id: `interrupt-review-${interruptId}`,
|
|
534
|
-
type: "interrupt-review",
|
|
535
|
-
status,
|
|
536
|
-
payload,
|
|
537
|
-
interruptId
|
|
538
|
-
};
|
|
539
|
-
}
|
|
540
|
-
function buildInterruptReviewGroup(interrupt, responded) {
|
|
541
|
-
const block = buildInterruptReviewBlock(interrupt, responded);
|
|
542
|
-
if (!block) return null;
|
|
543
|
-
return {
|
|
544
|
-
id: `interrupt-${block.interruptId}`,
|
|
545
|
-
type: "ai",
|
|
546
|
-
status: block.status,
|
|
547
|
-
source: "state",
|
|
548
|
-
originMessageIds: [],
|
|
549
|
-
blocks: [block],
|
|
550
|
-
toolIds: [],
|
|
551
|
-
tools: [],
|
|
552
|
-
rawMessages: [],
|
|
553
|
-
createdAt: Date.now()
|
|
554
|
-
};
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
// src/parser/thread-info.ts
|
|
558
|
-
var humanInputResponseRule = {
|
|
559
|
-
key: "clarificationAnswers",
|
|
560
|
-
extract(msg, acc) {
|
|
561
|
-
const additionalKwargs = msg?.additional_kwargs;
|
|
562
|
-
const response = additionalKwargs?.human_input_response;
|
|
563
|
-
const requestId = String(response?.request_id || "").trim().replace("clarification:", "");
|
|
564
|
-
if (requestId && response?.value !== void 0) {
|
|
565
|
-
acc.clarificationAnswers.set(requestId, String(response.value));
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
};
|
|
569
|
-
var THREAD_INFO_RULES = [humanInputResponseRule];
|
|
570
|
-
function extractThreadInfo(messages) {
|
|
571
|
-
const info = { clarificationAnswers: /* @__PURE__ */ new Map() };
|
|
572
|
-
for (const msg of messages ?? []) {
|
|
573
|
-
for (const rule of THREAD_INFO_RULES) {
|
|
574
|
-
rule.extract(msg, info);
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
return info;
|
|
578
|
-
}
|
|
579
|
-
function buildHumanInputResponse(requestId, options) {
|
|
580
|
-
return {
|
|
581
|
-
hide_from_ui: true,
|
|
582
|
-
human_input_response: {
|
|
583
|
-
version: 1,
|
|
584
|
-
kind: "human_input_response",
|
|
585
|
-
source: options.source,
|
|
586
|
-
request_id: requestId,
|
|
587
|
-
response_kind: options.responseKind,
|
|
588
|
-
value: options.value
|
|
589
|
-
}
|
|
590
|
-
};
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
// src/parser/thread.ts
|
|
594
|
-
function extractStateMessages(state) {
|
|
595
|
-
if (!state || typeof state !== "object") return [];
|
|
596
|
-
const values = state.values;
|
|
597
|
-
if (!values || typeof values !== "object") return [];
|
|
598
|
-
const messages = values.messages;
|
|
599
|
-
return Array.isArray(messages) ? messages : [];
|
|
600
|
-
}
|
|
601
|
-
function ensureRunningRun(runMap, runId, threadId) {
|
|
602
|
-
let runInfo = runMap.get(runId);
|
|
603
|
-
if (!runInfo) {
|
|
604
|
-
runInfo = {
|
|
605
|
-
runId,
|
|
606
|
-
threadId: threadId || "",
|
|
607
|
-
status: "running"
|
|
608
|
-
};
|
|
609
|
-
runMap.set(runId, runInfo);
|
|
610
|
-
}
|
|
611
|
-
return runInfo;
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
// src/types/sxin-message.ts
|
|
615
|
-
var asSxin = (m) => m ?? {};
|
|
616
|
-
|
|
617
|
-
// src/parser/run-messages.ts
|
|
618
|
-
var MESSAGE_TYPE_NORMALIZE = {
|
|
619
|
-
AIMessage: "ai",
|
|
620
|
-
AIMessageChunk: "ai",
|
|
621
|
-
HumanMessage: "human",
|
|
622
|
-
HumanMessageChunk: "human",
|
|
623
|
-
ToolMessage: "tool",
|
|
624
|
-
ToolMessageChunk: "tool",
|
|
625
|
-
SystemMessage: "system",
|
|
626
|
-
SystemMessageChunk: "system",
|
|
627
|
-
assistant: "ai",
|
|
628
|
-
user: "human"
|
|
629
|
-
};
|
|
630
|
-
function normalizeMessageType(message) {
|
|
631
|
-
const raw = String(asSxin(message).type || "").trim();
|
|
632
|
-
const normalized = MESSAGE_TYPE_NORMALIZE[raw];
|
|
633
|
-
if (normalized && normalized !== raw) {
|
|
634
|
-
return { ...asSxin(message), type: normalized };
|
|
635
|
-
}
|
|
636
|
-
return message;
|
|
637
|
-
}
|
|
638
|
-
function parseCreatedAt(value) {
|
|
639
|
-
if (value === null || value === void 0 || value === "") return void 0;
|
|
640
|
-
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
641
|
-
if (typeof value !== "string") return void 0;
|
|
642
|
-
const text = value.trim();
|
|
643
|
-
if (!text) return void 0;
|
|
644
|
-
if (/^\d+$/.test(text)) {
|
|
645
|
-
const ms2 = Number(text);
|
|
646
|
-
return Number.isFinite(ms2) ? ms2 : void 0;
|
|
647
|
-
}
|
|
648
|
-
const ms = Date.parse(text);
|
|
649
|
-
return Number.isFinite(ms) ? ms : void 0;
|
|
650
|
-
}
|
|
651
|
-
function toRunMessage(raw) {
|
|
652
|
-
if (!raw || typeof raw !== "object") return null;
|
|
653
|
-
const content = raw.content;
|
|
654
|
-
if (!content || typeof content !== "object" || Array.isArray(content)) return null;
|
|
655
|
-
if (!String(content.type || "").trim()) return null;
|
|
656
|
-
const seq = Number(raw.seq ?? 0);
|
|
657
|
-
if (!Number.isFinite(seq)) return null;
|
|
658
|
-
const createdAt = parseCreatedAt(raw.created_at);
|
|
659
|
-
return {
|
|
660
|
-
runId: String(raw.run_id ?? ""),
|
|
661
|
-
seq,
|
|
662
|
-
eventType: String(raw.event_type ?? ""),
|
|
663
|
-
...createdAt !== void 0 ? { createdAt } : {},
|
|
664
|
-
// feedback 可选:非空才映射
|
|
665
|
-
...raw.feedback !== void 0 && raw.feedback !== null ? { feedback: raw.feedback } : {},
|
|
666
|
-
content
|
|
667
|
-
};
|
|
668
|
-
}
|
|
669
|
-
function extractRunEnrichment(messages) {
|
|
670
|
-
const map = /* @__PURE__ */ new Map();
|
|
671
|
-
for (const msg of messages) {
|
|
672
|
-
const runId = String(msg?.runId || "").trim();
|
|
673
|
-
if (!runId) continue;
|
|
674
|
-
let entry = map.get(runId);
|
|
675
|
-
if (!entry) {
|
|
676
|
-
entry = {};
|
|
677
|
-
map.set(runId, entry);
|
|
678
|
-
}
|
|
679
|
-
if (msg.feedback !== void 0 && msg.feedback !== null) {
|
|
680
|
-
entry.feedback = msg.feedback;
|
|
681
|
-
}
|
|
682
|
-
const seconds = msg.content?.additional_kwargs?.turn_duration;
|
|
683
|
-
if (typeof seconds === "number" && !Number.isNaN(seconds) && seconds >= 0) {
|
|
684
|
-
entry.latencyMs = Math.round(seconds * 1e3);
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
return map;
|
|
688
|
-
}
|
|
689
|
-
function runMessagesToMessages(messages) {
|
|
690
|
-
return messages.map((msg) => {
|
|
691
|
-
const normalized = normalizeMessageType({ ...asSxin(msg.content) });
|
|
692
|
-
asSxin(normalized).runId = msg.runId;
|
|
693
|
-
if (msg.createdAt !== void 0) {
|
|
694
|
-
const date = new Date(msg.createdAt);
|
|
695
|
-
if (!Number.isNaN(date.getTime())) asSxin(normalized).created_at = date.toISOString();
|
|
696
|
-
}
|
|
697
|
-
return normalized;
|
|
698
|
-
});
|
|
699
|
-
}
|
|
700
|
-
function stateMessagesToRunMessages(messages) {
|
|
701
|
-
return messages.map((msg, i) => {
|
|
702
|
-
const sxin = asSxin(msg);
|
|
703
|
-
const createdAt = parseCreatedAt(sxin.created_at);
|
|
704
|
-
return {
|
|
705
|
-
runId: String(sxin.runId ?? sxin.additional_kwargs?.run_id ?? ""),
|
|
706
|
-
seq: i + 1,
|
|
707
|
-
eventType: "messages",
|
|
708
|
-
...createdAt !== void 0 ? { createdAt } : {},
|
|
709
|
-
content: msg
|
|
710
|
-
};
|
|
711
|
-
});
|
|
712
|
-
}
|
|
713
|
-
|
|
714
|
-
// src/parser/message-text.ts
|
|
715
|
-
function simpleHash(input) {
|
|
716
|
-
let hash = 5381;
|
|
717
|
-
for (let i = 0; i < input.length; i++) {
|
|
718
|
-
hash = (hash << 5) + hash + input.charCodeAt(i) & 4294967295;
|
|
719
|
-
}
|
|
720
|
-
return Math.abs(hash).toString(36);
|
|
721
|
-
}
|
|
722
|
-
function readMessageText(msg) {
|
|
723
|
-
if (!msg || typeof msg !== "object") return null;
|
|
724
|
-
const content = msg?.content;
|
|
725
|
-
if (typeof content === "string") return { text: content, trim: false };
|
|
726
|
-
if (Array.isArray(content)) {
|
|
727
|
-
const texts = [];
|
|
728
|
-
for (const part of content) {
|
|
729
|
-
if (part?.type === "text" && typeof part?.text === "string") {
|
|
730
|
-
texts.push(part.text);
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
return { text: texts.join("\n"), trim: true };
|
|
734
|
-
}
|
|
735
|
-
return null;
|
|
736
|
-
}
|
|
737
|
-
function readMessageContentText(msg) {
|
|
738
|
-
const read = readMessageText(msg);
|
|
739
|
-
if (!read) return "";
|
|
740
|
-
return read.trim ? read.text.trim() : read.text;
|
|
741
|
-
}
|
|
742
|
-
function extractTextFromMessage(msg) {
|
|
743
|
-
const read = readMessageText(msg);
|
|
744
|
-
if (!read) return "";
|
|
745
|
-
const text = collectVisibleText(read.text, tokenizeSxin(read.text));
|
|
746
|
-
return read.trim ? text.trim() : text;
|
|
747
|
-
}
|
|
748
|
-
function extractAiContentFromMessage(msg) {
|
|
749
|
-
const read = readMessageText(msg);
|
|
750
|
-
if (!read) return "";
|
|
751
|
-
const text = collectTextKeepSxin(read.text, tokenizeSxin(read.text));
|
|
752
|
-
return read.trim ? text.trim() : text;
|
|
753
|
-
}
|
|
754
|
-
function isVisibleUserMessage(msg) {
|
|
755
|
-
if (!msg || typeof msg !== "object") return false;
|
|
756
|
-
if (String(msg.type || "") !== "human") return false;
|
|
757
|
-
return msg.additional_kwargs?.hide_from_ui !== true;
|
|
758
|
-
}
|
|
759
|
-
function extractUserMessageTexts(rawMessages) {
|
|
760
|
-
if (!Array.isArray(rawMessages)) return [];
|
|
761
|
-
return rawMessages.filter((m) => isVisibleUserMessage(m)).map((m) => extractTextFromMessage(m).trim()).filter(Boolean).slice(0, 1);
|
|
762
|
-
}
|
|
763
|
-
function isHiddenUserMessage(msg) {
|
|
764
|
-
return msg?.role === "user" && msg?.additionalKwargs?.hide_from_ui === true;
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
// src/parser/report-artifact.ts
|
|
768
|
-
var genId = () => typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `id-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
|
769
|
-
function isWriteFileToolName(name) {
|
|
770
|
-
const n = String(name || "").trim().toLowerCase();
|
|
771
|
-
return n === "write_file" || n === "write_files";
|
|
772
|
-
}
|
|
773
|
-
function getToolCallArtifactMeta(toolCall) {
|
|
774
|
-
const meta = toolCall?.artifact_meta;
|
|
775
|
-
if (!meta || typeof meta !== "object") return null;
|
|
776
|
-
return meta;
|
|
777
|
-
}
|
|
778
|
-
function pathSuggestsBody(artifactPath) {
|
|
779
|
-
return /_正文(?:\.(?:md|markdown))?$/i.test(artifactPath) || /[/\\][^/\\]*正文[^/\\]*\.(?:md|markdown)$/i.test(artifactPath);
|
|
780
|
-
}
|
|
781
|
-
function pathSuggestsOutline(artifactPath) {
|
|
782
|
-
return /_大纲(?:\.(?:md|markdown))?$/i.test(artifactPath) || /[/\\][^/\\]*大纲[^/\\]*\.(?:md|markdown)$/i.test(artifactPath);
|
|
783
|
-
}
|
|
784
|
-
function descriptionSuggestsBody(description) {
|
|
785
|
-
return /正文/.test(description);
|
|
786
|
-
}
|
|
787
|
-
function descriptionSuggestsOutline(description) {
|
|
788
|
-
return /大纲/.test(description) && !descriptionSuggestsBody(description);
|
|
789
|
-
}
|
|
790
|
-
function extractKindSignals(toolCall) {
|
|
791
|
-
const meta = getToolCallArtifactMeta(toolCall);
|
|
792
|
-
return {
|
|
793
|
-
artifactPath: String(meta?.path || toolCall?.args?.path || "").trim(),
|
|
794
|
-
metaKind: String(meta?.kind || "").trim(),
|
|
795
|
-
description: String(toolCall?.args?.description || "").trim()
|
|
796
|
-
};
|
|
797
|
-
}
|
|
798
|
-
function resolveReportArtifactKind(toolCall) {
|
|
799
|
-
const { artifactPath, metaKind, description } = extractKindSignals(toolCall);
|
|
800
|
-
if (pathSuggestsBody(artifactPath) || descriptionSuggestsBody(description)) return "report_body";
|
|
801
|
-
if (pathSuggestsOutline(artifactPath) || descriptionSuggestsOutline(description)) return "report_outline";
|
|
802
|
-
if (metaKind === "report_body" || metaKind === "report_outline") return metaKind;
|
|
803
|
-
return null;
|
|
804
|
-
}
|
|
805
|
-
function extractTitleFromArtifactPath(path, kind = "report_outline") {
|
|
806
|
-
const raw = String(path || "").trim();
|
|
807
|
-
if (!raw) return "\u62A5\u544A";
|
|
808
|
-
const base = raw.split("/").pop() || raw;
|
|
809
|
-
const noExt = base.replace(/\.(md|markdown|html?)$/i, "");
|
|
810
|
-
if (kind === "report_body") {
|
|
811
|
-
return noExt.replace(/_正文$/i, "").replace(/_报告$/i, "").replace(/\s*正文\s*$/i, "").trim() || "\u62A5\u544A";
|
|
812
|
-
}
|
|
813
|
-
return noExt.replace(/_大纲$/i, "").replace(/\s*大纲\s*$/i, "").trim() || "\u62A5\u544A";
|
|
814
|
-
}
|
|
815
|
-
var OUTLINE_MAX_LEVEL = 3;
|
|
816
|
-
function normalizeSubChapter(raw, level) {
|
|
817
|
-
const legacyChildren = raw.children ?? raw.points ?? [];
|
|
818
|
-
const title = String(raw.title ?? raw.pointTitle ?? "");
|
|
819
|
-
const children = level >= OUTLINE_MAX_LEVEL ? [] : legacyChildren.map((c) => normalizeSubChapter(c, level + 1));
|
|
820
|
-
return {
|
|
821
|
-
id: String(raw.id ?? genId()),
|
|
822
|
-
title,
|
|
823
|
-
summary: String(raw.summary ?? raw.pointSummary ?? ""),
|
|
824
|
-
contentTheme: String(raw.contentTheme ?? raw.pointDesc ?? ""),
|
|
825
|
-
children
|
|
826
|
-
};
|
|
827
|
-
}
|
|
828
|
-
function normalizeOutline(raw) {
|
|
829
|
-
if (!Array.isArray(raw)) return [];
|
|
830
|
-
const outline = raw.map((item) => {
|
|
831
|
-
const ch = item;
|
|
832
|
-
const legacyChildren = ch.children ?? ch.points ?? [];
|
|
833
|
-
return {
|
|
834
|
-
id: String(ch.id ?? genId()),
|
|
835
|
-
chapterTitle: String(ch.chapterTitle ?? ""),
|
|
836
|
-
chapterSummary: String(ch.chapterSummary ?? ch.chapterDesc ?? ""),
|
|
837
|
-
children: legacyChildren.map((c) => normalizeSubChapter(c, 2))
|
|
838
|
-
};
|
|
839
|
-
});
|
|
840
|
-
return ensureOutlineContentThemes(outline);
|
|
841
|
-
}
|
|
842
|
-
function validateOutline(outline) {
|
|
843
|
-
if (!outline?.length) return false;
|
|
844
|
-
return outline.every((ch) => String(ch.chapterTitle || "").trim().length > 0);
|
|
845
|
-
}
|
|
846
|
-
function createEmptySubChapter() {
|
|
847
|
-
return {
|
|
848
|
-
id: genId(),
|
|
849
|
-
title: "",
|
|
850
|
-
summary: "",
|
|
851
|
-
contentTheme: "",
|
|
852
|
-
children: []
|
|
853
|
-
};
|
|
854
|
-
}
|
|
855
|
-
function ensureOutlineContentThemes(outline) {
|
|
856
|
-
const walk = (nodes) => {
|
|
857
|
-
nodes.forEach((node) => {
|
|
858
|
-
if (node.summary === void 0 || node.summary === null) {
|
|
859
|
-
node.summary = "";
|
|
860
|
-
}
|
|
861
|
-
if (node.contentTheme === void 0 || node.contentTheme === null) {
|
|
862
|
-
node.contentTheme = "";
|
|
863
|
-
}
|
|
864
|
-
if (node.children?.length) walk(node.children);
|
|
865
|
-
});
|
|
866
|
-
};
|
|
867
|
-
outline.forEach((ch) => {
|
|
868
|
-
if (ch.chapterSummary === void 0 || ch.chapterSummary === null) {
|
|
869
|
-
ch.chapterSummary = "";
|
|
870
|
-
}
|
|
871
|
-
walk(ch.children || []);
|
|
872
|
-
});
|
|
873
|
-
return outline;
|
|
874
|
-
}
|
|
875
|
-
function detectLevelOneIsChapter(lines) {
|
|
876
|
-
const levelOneCount = lines.filter((line) => /^#\s+.+$/.test(line.trim())).length;
|
|
877
|
-
return levelOneCount > 1;
|
|
878
|
-
}
|
|
879
|
-
function joinLines(existing, text) {
|
|
880
|
-
return existing ? `${existing}
|
|
881
|
-
${text}` : text;
|
|
882
|
-
}
|
|
883
|
-
function appendBullet(state, text) {
|
|
884
|
-
const line = `- ${text}`;
|
|
885
|
-
const top = state.stack[state.stack.length - 1]?.node;
|
|
886
|
-
if (top) {
|
|
887
|
-
top.contentTheme = joinLines(top.contentTheme, line);
|
|
888
|
-
return;
|
|
889
|
-
}
|
|
890
|
-
if (!state.currentChapter) return;
|
|
891
|
-
state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, line);
|
|
892
|
-
}
|
|
893
|
-
function appendSummaryText(state, text) {
|
|
894
|
-
if (!text) return;
|
|
895
|
-
const top = state.stack[state.stack.length - 1]?.node;
|
|
896
|
-
if (top) {
|
|
897
|
-
top.summary = joinLines(top.summary, text);
|
|
898
|
-
return;
|
|
899
|
-
}
|
|
900
|
-
if (!state.currentChapter) return;
|
|
901
|
-
state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, text);
|
|
902
|
-
}
|
|
903
|
-
function appendPlainText(state, text) {
|
|
904
|
-
if (!text) return;
|
|
905
|
-
const top = state.stack[state.stack.length - 1]?.node;
|
|
906
|
-
if (top) {
|
|
907
|
-
top.contentTheme = joinLines(top.contentTheme, text);
|
|
908
|
-
return;
|
|
909
|
-
}
|
|
910
|
-
if (!state.currentChapter) return;
|
|
911
|
-
state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, text);
|
|
912
|
-
}
|
|
913
|
-
function resolveTemplateName(title) {
|
|
914
|
-
return title.replace(/\s*·\s*大纲\s*$/i, "").replace(/\s*大纲\s*$/i, "").trim() || title;
|
|
915
|
-
}
|
|
916
|
-
function pushChapter(state, title) {
|
|
917
|
-
state.currentChapter = { id: genId(), chapterTitle: title, chapterSummary: "", children: [] };
|
|
918
|
-
state.outline.push(state.currentChapter);
|
|
919
|
-
state.stack.length = 0;
|
|
920
|
-
}
|
|
921
|
-
function pushSubChapter(state, level, title) {
|
|
922
|
-
const subChapterLevel = state.levelOneIsChapter ? level : level - 1;
|
|
923
|
-
if (subChapterLevel < 2 || !state.currentChapter) return false;
|
|
924
|
-
const sub = { id: genId(), title, summary: "", contentTheme: "", children: [] };
|
|
925
|
-
while (state.stack.length && state.stack[state.stack.length - 1].level >= subChapterLevel) {
|
|
926
|
-
state.stack.pop();
|
|
927
|
-
}
|
|
928
|
-
const parent = state.stack[state.stack.length - 1]?.node;
|
|
929
|
-
if (parent) parent.children.push(sub);
|
|
930
|
-
else state.currentChapter.children.push(sub);
|
|
931
|
-
state.stack.push({ node: sub, level: subChapterLevel });
|
|
932
|
-
return true;
|
|
933
|
-
}
|
|
934
|
-
function handleQuote(state, trimmed) {
|
|
935
|
-
if (!trimmed.startsWith(">")) return false;
|
|
936
|
-
const quoteText = trimmed.replace(/^(>\s*)+/, "").trim();
|
|
937
|
-
const summaryText = quoteText.replace(/^摘要\s*[::]\s*/i, "").trim();
|
|
938
|
-
appendSummaryText(state, summaryText || quoteText);
|
|
939
|
-
return true;
|
|
940
|
-
}
|
|
941
|
-
function handleHeading(state, trimmed) {
|
|
942
|
-
const heading = trimmed.match(/^(#{1,6})\s+(.+)$/);
|
|
943
|
-
if (!heading) return false;
|
|
944
|
-
const level = heading[1].length;
|
|
945
|
-
const title = heading[2].trim();
|
|
946
|
-
if (level === 1 && !state.levelOneIsChapter) {
|
|
947
|
-
state.templateName = resolveTemplateName(title);
|
|
948
|
-
return true;
|
|
949
|
-
}
|
|
950
|
-
if (level === 1 && state.levelOneIsChapter || level === 2 && !state.levelOneIsChapter) {
|
|
951
|
-
pushChapter(state, title);
|
|
952
|
-
return true;
|
|
953
|
-
}
|
|
954
|
-
return pushSubChapter(state, level, title);
|
|
955
|
-
}
|
|
956
|
-
function parseMarkdownToOutline(markdown) {
|
|
957
|
-
const lines = String(markdown || "").split(/\r?\n/);
|
|
958
|
-
const state = {
|
|
959
|
-
templateName: "",
|
|
960
|
-
outline: [],
|
|
961
|
-
currentChapter: null,
|
|
962
|
-
stack: [],
|
|
963
|
-
levelOneIsChapter: detectLevelOneIsChapter(lines)
|
|
964
|
-
};
|
|
965
|
-
for (const line of lines) {
|
|
966
|
-
const trimmed = line.trim();
|
|
967
|
-
if (!trimmed || trimmed === "---" || /^```/.test(trimmed)) continue;
|
|
968
|
-
if (handleQuote(state, trimmed)) continue;
|
|
969
|
-
if (handleHeading(state, trimmed)) continue;
|
|
970
|
-
const bullet = trimmed.match(/^[-*]\s+(.+)$/);
|
|
971
|
-
if (bullet) {
|
|
972
|
-
appendBullet(state, bullet[1].trim());
|
|
973
|
-
continue;
|
|
974
|
-
}
|
|
975
|
-
appendPlainText(state, trimmed);
|
|
976
|
-
}
|
|
977
|
-
return {
|
|
978
|
-
templateName: state.templateName || "\u62A5\u544A",
|
|
979
|
-
outline: normalizeOutline(state.outline)
|
|
980
|
-
};
|
|
981
|
-
}
|
|
982
|
-
var HTML_LIKE = /^\s*</;
|
|
983
|
-
function isReportBodyHtml(content) {
|
|
984
|
-
const s = String(content || "").trim();
|
|
985
|
-
if (!s) return false;
|
|
986
|
-
return HTML_LIKE.test(s);
|
|
987
|
-
}
|
|
988
|
-
function extractReportTitleFromBody(content, fallback = "") {
|
|
989
|
-
const s = String(content || "").trim();
|
|
990
|
-
if (!s) return fallback;
|
|
991
|
-
if (isReportBodyHtml(s)) {
|
|
992
|
-
const h1 = s.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);
|
|
993
|
-
if (h1?.[1]) {
|
|
994
|
-
const t = h1[1].replace(/<[^>]+>/g, "").trim();
|
|
995
|
-
if (t) return t;
|
|
996
|
-
}
|
|
997
|
-
}
|
|
998
|
-
const heading = s.match(/^#\s+(.+)$/m);
|
|
999
|
-
if (heading?.[1]) return heading[1].trim();
|
|
1000
|
-
return fallback;
|
|
1001
|
-
}
|
|
1002
|
-
|
|
1003
|
-
// src/parser/block-build-helper.ts
|
|
1004
|
-
function buildArtifactFiles(paths) {
|
|
1005
|
-
return paths.map((path) => {
|
|
1006
|
-
const name = path.split("/").pop() || path;
|
|
1007
|
-
const fileType = name.split(".").pop() || void 0;
|
|
1008
|
-
return { path, name, fileType };
|
|
1009
|
-
});
|
|
1010
|
-
}
|
|
1011
|
-
function toCreatedAtIso(createdAt) {
|
|
1012
|
-
const ms = Number(createdAt);
|
|
1013
|
-
if (!Number.isFinite(ms)) return (/* @__PURE__ */ new Date()).toISOString();
|
|
1014
|
-
const date = new Date(ms);
|
|
1015
|
-
return Number.isNaN(date.getTime()) ? (/* @__PURE__ */ new Date()).toISOString() : date.toISOString();
|
|
1016
|
-
}
|
|
1017
|
-
function buildReportOutlinePayload(input) {
|
|
1018
|
-
const { templateId, fallbackName, sourcePath, content, contentRef, createdAt } = input;
|
|
1019
|
-
const createdIso = toCreatedAtIso(createdAt);
|
|
1020
|
-
if (!content) {
|
|
1021
|
-
return {
|
|
1022
|
-
templateId,
|
|
1023
|
-
templateName: fallbackName,
|
|
1024
|
-
outline: [],
|
|
1025
|
-
createdAt: createdIso,
|
|
1026
|
-
sourcePath: sourcePath || void 0,
|
|
1027
|
-
contentRef
|
|
1028
|
-
};
|
|
1029
|
-
}
|
|
1030
|
-
const parsed = parseMarkdownToOutline(content);
|
|
1031
|
-
return {
|
|
1032
|
-
templateId,
|
|
1033
|
-
templateName: parsed.templateName || fallbackName,
|
|
1034
|
-
outline: parsed.outline,
|
|
1035
|
-
createdAt: createdIso,
|
|
1036
|
-
sourcePath: sourcePath || void 0,
|
|
1037
|
-
outlineMarkdown: content,
|
|
1038
|
-
contentRef
|
|
1039
|
-
};
|
|
1040
|
-
}
|
|
1041
|
-
function buildReportBodyPayload(input) {
|
|
1042
|
-
const { templateId, fallbackName, sourcePath, content, contentRef, createdAt } = input;
|
|
1043
|
-
const createdIso = toCreatedAtIso(createdAt);
|
|
1044
|
-
if (!content) {
|
|
1045
|
-
return {
|
|
1046
|
-
templateId,
|
|
1047
|
-
templateName: fallbackName,
|
|
1048
|
-
reportTitle: "",
|
|
1049
|
-
createdAt: createdIso,
|
|
1050
|
-
sourcePath: sourcePath || void 0,
|
|
1051
|
-
contentRef
|
|
1052
|
-
};
|
|
1053
|
-
}
|
|
1054
|
-
return {
|
|
1055
|
-
templateId,
|
|
1056
|
-
templateName: fallbackName,
|
|
1057
|
-
reportTitle: extractReportTitleFromBody(content, fallbackName),
|
|
1058
|
-
createdAt: createdIso,
|
|
1059
|
-
sourcePath: sourcePath || void 0,
|
|
1060
|
-
bodyMarkdown: content,
|
|
1061
|
-
contentRef
|
|
1062
|
-
};
|
|
1063
|
-
}
|
|
1064
|
-
function collectListSpecs(listEls, spec, source) {
|
|
1065
|
-
for (const listEl of listEls) {
|
|
1066
|
-
const itemType = formatStr(listEl.attrs["item-type"] || "");
|
|
1067
|
-
if (!itemType) continue;
|
|
1068
|
-
if (!spec[itemType]) spec[itemType] = [];
|
|
1069
|
-
for (const item of listEl.children) {
|
|
1070
|
-
if (item.type !== "element" || item.tagName !== "sxin-list-item") continue;
|
|
1071
|
-
spec[itemType].push(buildItemSpec(item, source));
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
function collectChildSpecs(children, spec, source) {
|
|
1076
|
-
for (const child of children) {
|
|
1077
|
-
if (child.type !== "element") continue;
|
|
1078
|
-
const key = formatStr(child.tagName);
|
|
1079
|
-
if (!spec[key]) spec[key] = [];
|
|
1080
|
-
spec[key].push(buildItemSpec(child, source));
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
function buildCustomBlockFromNode(el, source, status) {
|
|
1084
|
-
const spec = { ...el.attrs };
|
|
1085
|
-
const listEls = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-list");
|
|
1086
|
-
if (listEls.length > 0) {
|
|
1087
|
-
collectListSpecs(listEls, spec, source);
|
|
1088
|
-
} else {
|
|
1089
|
-
collectChildSpecs(el.children, spec, source);
|
|
1090
|
-
}
|
|
1091
|
-
return { id: genBlockId(), type: "custom", tagName: el.tagName, spec, status };
|
|
1092
|
-
}
|
|
1093
|
-
function buildItemSpec(el, source) {
|
|
1094
|
-
const attrs = { ...el.attrs };
|
|
1095
|
-
const inner = el.children.map((c) => source.slice(c.start, c.end)).join("").trim();
|
|
1096
|
-
if (inner) attrs.text = inner;
|
|
1097
|
-
return attrs;
|
|
1098
|
-
}
|
|
1099
|
-
function flushTextBuf(ctx) {
|
|
1100
|
-
const content = ctx.textBuf.value.replace(/\n{3,}/g, "\n\n").trim();
|
|
1101
|
-
ctx.textBuf.value = "";
|
|
1102
|
-
if (content) {
|
|
1103
|
-
ctx.blocks.push({ id: genBlockId(), type: "text", content, status: ctx.status });
|
|
1104
|
-
}
|
|
1105
|
-
}
|
|
1106
|
-
function handleSxinElement(ctx, node) {
|
|
1107
|
-
if (!node.closed && !ctx.isHistory) {
|
|
1108
|
-
flushTextBuf(ctx);
|
|
1109
|
-
return false;
|
|
1110
|
-
}
|
|
1111
|
-
flushTextBuf(ctx);
|
|
1112
|
-
ctx.blocks.push(buildCustomBlockFromNode(node, ctx.rawText, ctx.status));
|
|
1113
|
-
return true;
|
|
1114
|
-
}
|
|
1115
|
-
function walkNodes(ctx, nodes) {
|
|
1116
|
-
for (const node of nodes) {
|
|
1117
|
-
if (node.type === "text") {
|
|
1118
|
-
ctx.textBuf.value += node.value;
|
|
1119
|
-
continue;
|
|
1120
|
-
}
|
|
1121
|
-
if (node.type === "comment") {
|
|
1122
|
-
continue;
|
|
1123
|
-
}
|
|
1124
|
-
if (isInjectedElement(node)) {
|
|
1125
|
-
continue;
|
|
1126
|
-
}
|
|
1127
|
-
if (node.tagName.startsWith("sxin-")) {
|
|
1128
|
-
if (!handleSxinElement(ctx, node)) return false;
|
|
1129
|
-
continue;
|
|
1130
|
-
}
|
|
1131
|
-
ctx.textBuf.value += ctx.rawText.slice(node.start, node.end);
|
|
1132
|
-
}
|
|
1133
|
-
return true;
|
|
1134
|
-
}
|
|
1135
|
-
function extractBlocksFromNodes(nodes, rawText, source) {
|
|
1136
|
-
const isHistory = source === "history";
|
|
1137
|
-
const ctx = {
|
|
1138
|
-
rawText,
|
|
1139
|
-
isHistory,
|
|
1140
|
-
status: isHistory ? "completed" : "streaming",
|
|
1141
|
-
blocks: [],
|
|
1142
|
-
textBuf: { value: "" }
|
|
1143
|
-
};
|
|
1144
|
-
const completed = walkNodes(ctx, nodes);
|
|
1145
|
-
if (completed) flushTextBuf(ctx);
|
|
1146
|
-
return { blocks: ctx.blocks };
|
|
1147
|
-
}
|
|
1148
|
-
function extractBlocksFromContent(rawText, source) {
|
|
1149
|
-
return extractBlocksFromNodes(tokenizeSxin(rawText), rawText, source);
|
|
1150
|
-
}
|
|
1151
|
-
|
|
1152
|
-
// src/parser/group-builder-helper.ts
|
|
1153
|
-
function isHumanMessage(msg) {
|
|
1154
|
-
return String(asSxin(msg).type || "") === "human";
|
|
1155
|
-
}
|
|
1156
|
-
function parseHumanMessageId(id) {
|
|
1157
|
-
const raw = String(id || "");
|
|
1158
|
-
const match = raw.match(/^(.*?)__(memory|user)(\([^)]*\))?$/i);
|
|
1159
|
-
if (!match) return { baseId: raw, variant: null };
|
|
1160
|
-
return { baseId: match[1], variant: match[2].toLowerCase() };
|
|
1161
|
-
}
|
|
1162
|
-
function getHumanMessageBaseId(id) {
|
|
1163
|
-
return parseHumanMessageId(id).baseId;
|
|
1164
|
-
}
|
|
1165
|
-
function isAiMessage(msg) {
|
|
1166
|
-
const t = String(asSxin(msg).type || "");
|
|
1167
|
-
return ["ai", "AIMessage", "AIMessageChunk"].includes(t);
|
|
1168
|
-
}
|
|
1169
|
-
function isToolMessage(msg) {
|
|
1170
|
-
return String(asSxin(msg).type || "") === "tool";
|
|
1171
|
-
}
|
|
1172
|
-
function deriveToolsFromMessages(messages) {
|
|
1173
|
-
const tools = [];
|
|
1174
|
-
const byId = /* @__PURE__ */ new Map();
|
|
1175
|
-
for (const msg of messages) {
|
|
1176
|
-
const m = asSxin(msg);
|
|
1177
|
-
const toolCalls = m.tool_calls;
|
|
1178
|
-
if (Array.isArray(toolCalls)) {
|
|
1179
|
-
for (const tc of toolCalls) {
|
|
1180
|
-
const id = String(tc?.id || "").trim();
|
|
1181
|
-
if (!id || byId.has(id)) continue;
|
|
1182
|
-
const tool = { id, call: tc, aiMessage: msg, state: "pending", index: tools.length };
|
|
1183
|
-
byId.set(id, tool);
|
|
1184
|
-
tools.push(tool);
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
const toolCallId = String(m.tool_call_id || "").trim();
|
|
1188
|
-
if (!toolCallId) continue;
|
|
1189
|
-
const state = m.status === "error" ? "error" : "completed";
|
|
1190
|
-
const existing = byId.get(toolCallId);
|
|
1191
|
-
if (existing) {
|
|
1192
|
-
existing.result = msg;
|
|
1193
|
-
existing.state = state;
|
|
1194
|
-
} else {
|
|
1195
|
-
const tool = {
|
|
1196
|
-
id: toolCallId,
|
|
1197
|
-
call: { id: toolCallId, name: String(m.name || ""), args: {} },
|
|
1198
|
-
result: msg,
|
|
1199
|
-
state,
|
|
1200
|
-
index: tools.length
|
|
1201
|
-
};
|
|
1202
|
-
byId.set(toolCallId, tool);
|
|
1203
|
-
tools.push(tool);
|
|
1204
|
-
}
|
|
1205
|
-
}
|
|
1206
|
-
return tools;
|
|
1207
|
-
}
|
|
1208
|
-
function normalizeUsage(raw) {
|
|
1209
|
-
if (!raw || typeof raw !== "object") return void 0;
|
|
1210
|
-
const r = raw;
|
|
1211
|
-
const inputTokens = readAliasedNumber(r, ["input_tokens", "inputTokens", "prompt_tokens", "promptTokens"]);
|
|
1212
|
-
const outputTokens = readAliasedNumber(r, ["output_tokens", "outputTokens", "completion_tokens", "completionTokens"]);
|
|
1213
|
-
const totalTokens = readAliasedNumber(r, ["total_tokens", "totalTokens"]);
|
|
1214
|
-
if ([inputTokens, outputTokens, totalTokens].every(Number.isNaN)) {
|
|
1215
|
-
return void 0;
|
|
1216
|
-
}
|
|
1217
|
-
const usage = {
|
|
1218
|
-
input_tokens: toZeroIfNaN(inputTokens),
|
|
1219
|
-
output_tokens: toZeroIfNaN(outputTokens),
|
|
1220
|
-
total_tokens: toZeroIfNaN(totalTokens)
|
|
1221
|
-
};
|
|
1222
|
-
applyUsageDetails(usage, r);
|
|
1223
|
-
return usage;
|
|
1224
|
-
}
|
|
1225
|
-
function readAliasedNumber(r, aliases) {
|
|
1226
|
-
for (const key of aliases) {
|
|
1227
|
-
if (r[key] !== void 0 && r[key] !== null) return Number(r[key]);
|
|
1228
|
-
}
|
|
1229
|
-
return NaN;
|
|
1230
|
-
}
|
|
1231
|
-
function toZeroIfNaN(n) {
|
|
1232
|
-
return Number.isNaN(n) ? 0 : n;
|
|
1233
|
-
}
|
|
1234
|
-
function applyUsageDetails(usage, r) {
|
|
1235
|
-
const cacheRead = Number(r.input_token_details?.cache_read ?? r.input_token_details?.cacheRead);
|
|
1236
|
-
if (!Number.isNaN(cacheRead)) {
|
|
1237
|
-
usage.input_token_details = { cache_read: cacheRead };
|
|
1238
|
-
}
|
|
1239
|
-
const reasoning = Number(r.output_token_details?.reasoning ?? r.output_token_details?.reasoningTokens);
|
|
1240
|
-
if (!Number.isNaN(reasoning)) {
|
|
1241
|
-
usage.output_token_details = { reasoning };
|
|
1242
|
-
}
|
|
1243
|
-
}
|
|
1244
|
-
|
|
1245
|
-
// src/message/run-info.ts
|
|
1246
|
-
function buildRunInfo(run, threadId) {
|
|
1247
|
-
return {
|
|
1248
|
-
runId: String(run?.run_id || "").trim(),
|
|
1249
|
-
threadId: String(threadId || "").trim(),
|
|
1250
|
-
usage: buildRunUsage(run),
|
|
1251
|
-
latencyMs: buildRunLatencyMs(run),
|
|
1252
|
-
finishReason: toOptionalString(run?.finish_reason),
|
|
1253
|
-
modelName: toOptionalString(run?.model_name),
|
|
1254
|
-
status: buildRunStatus(run),
|
|
1255
|
-
createdAt: buildRunCreatedAt(run)
|
|
1256
|
-
};
|
|
1257
|
-
}
|
|
1258
|
-
function toOptionalString(value) {
|
|
1259
|
-
return value ? String(value) : void 0;
|
|
1260
|
-
}
|
|
1261
|
-
function buildRunUsage(run) {
|
|
1262
|
-
return normalizeUsage({
|
|
1263
|
-
input_tokens: run?.total_input_tokens,
|
|
1264
|
-
output_tokens: run?.total_output_tokens,
|
|
1265
|
-
total_tokens: run?.total_tokens
|
|
1266
|
-
});
|
|
1267
|
-
}
|
|
1268
|
-
function buildRunStatus(run) {
|
|
1269
|
-
return run?.status ? String(run.status) : void 0;
|
|
1270
|
-
}
|
|
1271
|
-
function buildRunCreatedAt(run) {
|
|
1272
|
-
return run?.created_at ? Number(new Date(run.created_at)) : void 0;
|
|
1273
|
-
}
|
|
1274
|
-
function buildRunDirectLatencyMs(run) {
|
|
1275
|
-
const direct = Number(run?.latency_ms);
|
|
1276
|
-
return direct || void 0;
|
|
1277
|
-
}
|
|
1278
|
-
function buildRunLatencyMs(run) {
|
|
1279
|
-
const direct = buildRunDirectLatencyMs(run);
|
|
1280
|
-
if (direct !== void 0) return direct;
|
|
1281
|
-
const created = Date.parse(String(run?.created_at ?? ""));
|
|
1282
|
-
const updated = Date.parse(String(run?.updated_at ?? ""));
|
|
1283
|
-
if (Number.isNaN(created) || Number.isNaN(updated)) return void 0;
|
|
1284
|
-
const diff = updated - created;
|
|
1285
|
-
return diff >= 0 ? diff : void 0;
|
|
1286
|
-
}
|
|
1287
|
-
function pickRunMessageMetadata(messages) {
|
|
1288
|
-
let modelName;
|
|
1289
|
-
let finishReason;
|
|
1290
|
-
for (const msg of messages) {
|
|
1291
|
-
if (!isAiMessage(msg)) {
|
|
1292
|
-
continue;
|
|
1293
|
-
}
|
|
1294
|
-
const responseMetadata = msg?.response_metadata || {};
|
|
1295
|
-
if (!modelName && responseMetadata.model_name) {
|
|
1296
|
-
modelName = String(responseMetadata.model_name);
|
|
1297
|
-
}
|
|
1298
|
-
if (!finishReason && responseMetadata.finish_reason) {
|
|
1299
|
-
finishReason = String(responseMetadata.finish_reason);
|
|
1300
|
-
}
|
|
1301
|
-
if (modelName && finishReason) {
|
|
1302
|
-
break;
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
return { modelName, finishReason };
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
// src/domain/block-builder.ts
|
|
1309
|
-
var DEFAULT_TWIN_TOOL_PREFIX = "city-digital-twin-display_";
|
|
1310
|
-
function createBlockBuilderLite(options) {
|
|
1311
|
-
const source = options.source;
|
|
1312
|
-
const isStreaming = !!options.isStreaming;
|
|
1313
|
-
const createdAt = Number.isFinite(options.createdAt) ? Number(options.createdAt) : Date.now();
|
|
1314
|
-
const twinEnabled = !!options.twin?.enabled;
|
|
1315
|
-
const twinToolPrefix = options.twin?.toolPrefix || DEFAULT_TWIN_TOOL_PREFIX;
|
|
1316
|
-
const presentFilesSet = /* @__PURE__ */ new Set();
|
|
1317
|
-
const writeFilesSet = /* @__PURE__ */ new Set();
|
|
1318
|
-
const toolParsers = /* @__PURE__ */ new Map();
|
|
1319
|
-
const registerParser = (names, parser) => {
|
|
1320
|
-
for (const name of Array.isArray(names) ? names : [names]) {
|
|
1321
|
-
toolParsers.set(name, parser);
|
|
1322
|
-
}
|
|
1323
|
-
};
|
|
1324
|
-
const parseBlockTool = (tool, status) => {
|
|
1325
|
-
const name = String(tool.call?.name || "").trim();
|
|
1326
|
-
const parser = toolParsers.get(name);
|
|
1327
|
-
return parser ? parser(tool, status) : [];
|
|
1328
|
-
};
|
|
1329
|
-
const parseAskClarification = (tool, _status) => {
|
|
1330
|
-
const args = tool.call?.args || {};
|
|
1331
|
-
return [
|
|
1332
|
-
{
|
|
1333
|
-
id: genBlockId(),
|
|
1334
|
-
type: "ask-clarification",
|
|
1335
|
-
context: args.context,
|
|
1336
|
-
question: args.question,
|
|
1337
|
-
clarification_type: args.clarification_type,
|
|
1338
|
-
options: Array.isArray(args.options) ? args.options : void 0,
|
|
1339
|
-
fields: Array.isArray(args.fields) ? args.fields : void 0,
|
|
1340
|
-
// clarification 的回答是跨 run 的,不能根据 streaming/source 判断状态,统一 pending,由渲染层结合 thread 级回答状态决定
|
|
1341
|
-
status: "pending",
|
|
1342
|
-
toolCallId: tool.id
|
|
1343
|
-
}
|
|
1344
|
-
];
|
|
1345
|
-
};
|
|
1346
|
-
const parseFormBlock = (tool, status, sourceTag) => {
|
|
1347
|
-
const args = tool.call?.args || {};
|
|
1348
|
-
const variant = String(args.variant || "input");
|
|
1349
|
-
const blockStatus = sourceTag === "ask_clarification" ? "pending" : status;
|
|
1350
|
-
return [
|
|
1351
|
-
{
|
|
1352
|
-
id: genBlockId(),
|
|
1353
|
-
type: "form",
|
|
1354
|
-
variant: ["input", "confirm", "delete_confirm"].includes(variant) ? variant : "input",
|
|
1355
|
-
title: args.title,
|
|
1356
|
-
question: args.question,
|
|
1357
|
-
context: args.context,
|
|
1358
|
-
fields: Array.isArray(args.fields) ? args.fields : [],
|
|
1359
|
-
values: args.values || {},
|
|
1360
|
-
stepInfo: args.stepInfo,
|
|
1361
|
-
customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
|
|
1362
|
-
status: blockStatus,
|
|
1363
|
-
toolCallId: tool.id,
|
|
1364
|
-
source: sourceTag
|
|
1365
|
-
}
|
|
1366
|
-
];
|
|
1367
|
-
};
|
|
1368
|
-
const parseListBlock = (tool, status) => {
|
|
1369
|
-
const args = tool.call?.args || {};
|
|
1370
|
-
const mode = String(args.mode || "select");
|
|
1371
|
-
return [
|
|
1372
|
-
{
|
|
1373
|
-
id: genBlockId(),
|
|
1374
|
-
type: "list",
|
|
1375
|
-
mode: ["select", "view"].includes(mode) ? mode : "select",
|
|
1376
|
-
title: args.title,
|
|
1377
|
-
dataSource: args.dataSource,
|
|
1378
|
-
items: Array.isArray(args.items) ? args.items : void 0,
|
|
1379
|
-
queryParams: args.queryParams,
|
|
1380
|
-
pagination: args.pagination,
|
|
1381
|
-
selectMode: args.selectMode || "single",
|
|
1382
|
-
customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
|
|
1383
|
-
status,
|
|
1384
|
-
toolCallId: tool.id
|
|
1385
|
-
}
|
|
1386
|
-
];
|
|
1387
|
-
};
|
|
1388
|
-
const parsePresentFiles = (tool, status) => {
|
|
1389
|
-
const args = tool.call?.args || {};
|
|
1390
|
-
const filepaths = Array.isArray(args?.filepaths) ? args.filepaths : [];
|
|
1391
|
-
if (!filepaths.length) return [];
|
|
1392
|
-
const paths = [];
|
|
1393
|
-
for (const path of filepaths) {
|
|
1394
|
-
if (presentFilesSet.has(path)) continue;
|
|
1395
|
-
presentFilesSet.add(path);
|
|
1396
|
-
paths.push(path);
|
|
1397
|
-
}
|
|
1398
|
-
if (!paths.length) return [];
|
|
1399
|
-
return [
|
|
1400
|
-
{
|
|
1401
|
-
id: genBlockId(),
|
|
1402
|
-
type: "artifact",
|
|
1403
|
-
files: buildArtifactFiles(paths),
|
|
1404
|
-
status
|
|
1405
|
-
}
|
|
1406
|
-
];
|
|
1407
|
-
};
|
|
1408
|
-
const resolveWriteFileContext = (tool) => {
|
|
1409
|
-
const meta = getToolCallArtifactMeta(tool.call);
|
|
1410
|
-
const args = tool.call?.args || {};
|
|
1411
|
-
const artifactPath = String(meta?.path || args.path || "").trim();
|
|
1412
|
-
const content = String(args.content || tool.result?.content || "").trim();
|
|
1413
|
-
const description = String(args.description || "").trim();
|
|
1414
|
-
const blockId = tool.id || artifactPath || `report-${Date.now()}`;
|
|
1415
|
-
const toolCreatedAt = Number(new Date(asSxin(tool.aiMessage).created_at || ""));
|
|
1416
|
-
const toolTime = Number.isFinite(toolCreatedAt) ? toolCreatedAt : createdAt;
|
|
1417
|
-
if (!content && source === "sse") return null;
|
|
1418
|
-
if (writeFilesSet.has(artifactPath)) return null;
|
|
1419
|
-
writeFilesSet.add(artifactPath);
|
|
1420
|
-
presentFilesSet.add(artifactPath);
|
|
1421
|
-
return { artifactPath, content, description, blockId, createdAt: toolTime };
|
|
1422
|
-
};
|
|
1423
|
-
const buildReportBlock = (kind, ctx, status) => {
|
|
1424
|
-
const isOutline = kind === "report_outline";
|
|
1425
|
-
const fallbackName = extractTitleFromArtifactPath(ctx.artifactPath, kind) || ctx.description.replace(isOutline ? /生成|大纲/g : /生成|正文|报告/g, "").trim() || "\u62A5\u544A";
|
|
1426
|
-
const isState = source === "state";
|
|
1427
|
-
const payloadInput = {
|
|
1428
|
-
templateId: ctx.blockId,
|
|
1429
|
-
fallbackName,
|
|
1430
|
-
sourcePath: ctx.artifactPath || void 0,
|
|
1431
|
-
content: isState ? void 0 : ctx.content || void 0,
|
|
1432
|
-
contentRef: isState && ctx.artifactPath ? { path: ctx.artifactPath } : void 0,
|
|
1433
|
-
createdAt: ctx.createdAt
|
|
1434
|
-
};
|
|
1435
|
-
return isOutline ? { id: genBlockId(), type: "report-outline", payload: buildReportOutlinePayload(payloadInput), status } : { id: genBlockId(), type: "report-body", payload: buildReportBodyPayload(payloadInput), status };
|
|
1436
|
-
};
|
|
1437
|
-
const parseWriteFile = (tool, status) => {
|
|
1438
|
-
const name = String(tool.call?.name || "").trim();
|
|
1439
|
-
if (!isWriteFileToolName(name)) return [];
|
|
1440
|
-
const kind = resolveReportArtifactKind(tool.call);
|
|
1441
|
-
if (!kind) return [];
|
|
1442
|
-
const ctx = resolveWriteFileContext(tool);
|
|
1443
|
-
if (!ctx) return [];
|
|
1444
|
-
const block = buildReportBlock(kind, ctx, status);
|
|
1445
|
-
return block ? [block] : [];
|
|
1446
|
-
};
|
|
1447
|
-
const parseClarification = (tool, status) => {
|
|
1448
|
-
const args = tool.call?.args || {};
|
|
1449
|
-
if (args.variant || args.fields?.length) {
|
|
1450
|
-
return parseFormBlock(tool, status, "ask_clarification");
|
|
1451
|
-
}
|
|
1452
|
-
return parseAskClarification(tool, status);
|
|
1453
|
-
};
|
|
1454
|
-
registerParser("ask_clarification", parseClarification);
|
|
1455
|
-
registerParser(
|
|
1456
|
-
["confirm_form", "form"],
|
|
1457
|
-
(tool, status) => parseFormBlock(tool, status, String(tool.call?.name || "").trim())
|
|
1458
|
-
);
|
|
1459
|
-
registerParser(["list_and_select", "list"], parseListBlock);
|
|
1460
|
-
registerParser("present_files", parsePresentFiles);
|
|
1461
|
-
registerParser(["write_file", "write_files"], parseWriteFile);
|
|
1462
|
-
const buildFromNodes = (nodes, rawText, tools) => {
|
|
1463
|
-
const blocks = [];
|
|
1464
|
-
const status = isStreaming ? "streaming" : "completed";
|
|
1465
|
-
const contentSource = source === "state" ? "history" : source;
|
|
1466
|
-
const { blocks: contentBlocks } = extractBlocksFromNodes(nodes, rawText, contentSource);
|
|
1467
|
-
blocks.push(...contentBlocks);
|
|
1468
|
-
for (const tool of tools) {
|
|
1469
|
-
const toolBlocks = parseBlockTool(tool, status);
|
|
1470
|
-
blocks.push(...toolBlocks);
|
|
1471
|
-
}
|
|
1472
|
-
if (twinEnabled) {
|
|
1473
|
-
const twinTool = tools.reverse().find((_) => _.call?.name.includes(twinToolPrefix));
|
|
1474
|
-
if (twinTool) {
|
|
1475
|
-
blocks.push({
|
|
1476
|
-
id: genBlockId(),
|
|
1477
|
-
type: "twin",
|
|
1478
|
-
toolName: twinTool.call.name.replace(twinToolPrefix, ""),
|
|
1479
|
-
args: twinTool.call.args
|
|
1480
|
-
});
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
return blocks;
|
|
1484
|
-
};
|
|
1485
|
-
const build = (content, tools) => buildFromNodes(tokenizeSxin(content), content, tools);
|
|
1486
|
-
return { build, buildFromNodes };
|
|
1487
|
-
}
|
|
1488
|
-
|
|
1489
|
-
// src/domain/fold.ts
|
|
1490
|
-
function messageRunId(msg) {
|
|
1491
|
-
const own = String(asSxin(msg).runId || "").trim();
|
|
1492
|
-
if (own) return own;
|
|
1493
|
-
return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
|
|
1494
|
-
}
|
|
1495
|
-
function foldMessages(target, flush) {
|
|
1496
|
-
let type = null;
|
|
1497
|
-
let buf = [];
|
|
1498
|
-
let groupRunId;
|
|
1499
|
-
const doFlush = () => {
|
|
1500
|
-
if (!buf.length || !type) return;
|
|
1501
|
-
flush(type, buf);
|
|
1502
|
-
buf = [];
|
|
1503
|
-
};
|
|
1504
|
-
for (const m of target) {
|
|
1505
|
-
if (isHumanMessage(m)) {
|
|
1506
|
-
if (!(type === "human" && buf.length && getHumanMessageBaseId(String(asSxin(m).id || "")) === getHumanMessageBaseId(String(asSxin(buf[0]).id || ""))))
|
|
1507
|
-
doFlush();
|
|
1508
|
-
type = "human";
|
|
1509
|
-
buf.push(m);
|
|
1510
|
-
} else if (isAiMessage(m) || isToolMessage(m)) {
|
|
1511
|
-
const mRunId = messageRunId(m);
|
|
1512
|
-
if (type !== "ai" || mRunId && groupRunId && mRunId !== groupRunId) doFlush();
|
|
1513
|
-
if (!buf.length) groupRunId = mRunId;
|
|
1514
|
-
type = "ai";
|
|
1515
|
-
buf.push(m);
|
|
1516
|
-
}
|
|
1517
|
-
}
|
|
1518
|
-
doFlush();
|
|
1519
|
-
}
|
|
1520
|
-
|
|
1521
|
-
// src/domain/group-materializer.ts
|
|
1522
|
-
function readCreatedAt(msg) {
|
|
1523
|
-
return Number(new Date(asSxin(msg).created_at || Date.now())) || Date.now();
|
|
1524
|
-
}
|
|
1525
|
-
function buildHumanGroup(messages, status) {
|
|
1526
|
-
const representative = messages.find(
|
|
1527
|
-
(m) => parseHumanMessageId(String(asSxin(m).id || "")).variant === "user" && isVisibleUserMessage(m)
|
|
1528
|
-
) || messages.find((m) => isVisibleUserMessage(m)) || messages[0];
|
|
1529
|
-
const firstId = messages.find((_) => _.id)?.id || genMessageId();
|
|
1530
|
-
const additionalKwargs = asSxin(representative).additional_kwargs;
|
|
1531
|
-
const texts = extractUserMessageTexts(messages);
|
|
1532
|
-
const runId = messageRunId(representative);
|
|
1533
|
-
return {
|
|
1534
|
-
id: firstId,
|
|
1535
|
-
type: "human",
|
|
1536
|
-
status,
|
|
1537
|
-
originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
|
|
1538
|
-
runId,
|
|
1539
|
-
rawMessages: messages,
|
|
1540
|
-
texts,
|
|
1541
|
-
additionalKwargs,
|
|
1542
|
-
blocks: [],
|
|
1543
|
-
toolIds: [],
|
|
1544
|
-
tools: [],
|
|
1545
|
-
createdAt: readCreatedAt(representative)
|
|
1546
|
-
};
|
|
1547
|
-
}
|
|
1548
|
-
function buildAiGroup(messages, options, twin) {
|
|
1549
|
-
const firstId = messages.find((_) => _.id)?.id || genMessageId();
|
|
1550
|
-
const groupTools = deriveToolsFromMessages(messages);
|
|
1551
|
-
const aiMessages = messages.filter(isAiMessage);
|
|
1552
|
-
const lastAi = aiMessages[aiMessages.length - 1] || messages[messages.length - 1];
|
|
1553
|
-
const content = readMessageContentText(lastAi);
|
|
1554
|
-
const createdAt = readCreatedAt(messages[0]);
|
|
1555
|
-
const blocks = options.isStreaming ? [] : createBlockBuilderLite({ source: options.source, twin, createdAt }).buildFromNodes(
|
|
1556
|
-
tokenizeSxin(content),
|
|
1557
|
-
content,
|
|
1558
|
-
groupTools
|
|
1559
|
-
);
|
|
1560
|
-
const anchors = extractCitationAnchors(blocks);
|
|
1561
|
-
const citations = anchors.length ? anchors : void 0;
|
|
1562
|
-
return {
|
|
1563
|
-
id: firstId,
|
|
1564
|
-
type: "ai",
|
|
1565
|
-
status: options.isStreaming ? "streaming" : "completed",
|
|
1566
|
-
originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
|
|
1567
|
-
runId: messageRunId(lastAi) || options.runId,
|
|
1568
|
-
rawMessages: messages,
|
|
1569
|
-
blocks,
|
|
1570
|
-
citations,
|
|
1571
|
-
toolIds: groupTools.map((t) => t.id),
|
|
1572
|
-
tools: groupTools,
|
|
1573
|
-
createdAt
|
|
1574
|
-
};
|
|
1575
|
-
}
|
|
1576
|
-
|
|
1577
|
-
// src/domain/clarification.ts
|
|
1578
|
-
function isClarificationAnswered(block, answers) {
|
|
1579
|
-
if (!block) return false;
|
|
1580
|
-
if (block.status === "completed") return true;
|
|
1581
|
-
if (block.isAnswered) return true;
|
|
1582
|
-
const toolCallId = block.toolCallId;
|
|
1583
|
-
return !!toolCallId && answers.has(toolCallId);
|
|
1584
|
-
}
|
|
1585
|
-
function isClarificationBlock(block) {
|
|
1586
|
-
return block.type === "ask-clarification" || block.type === "form" && block.source === "ask_clarification";
|
|
1587
|
-
}
|
|
1588
|
-
|
|
1589
|
-
// src/domain/viewmodel-state.ts
|
|
1590
|
-
import { shallowReactive, shallowRef } from "vue";
|
|
1591
|
-
function createViewModelState() {
|
|
1592
|
-
const extrasRef = shallowRef([]);
|
|
1593
|
-
const patches = shallowReactive(/* @__PURE__ */ new Map());
|
|
1594
|
-
const readFirstText = (group) => extractTextFromMessage(asSxin(group.rawMessages[0])).trim();
|
|
1595
|
-
return {
|
|
1596
|
-
get extras() {
|
|
1597
|
-
return extrasRef.value;
|
|
1598
|
-
},
|
|
1599
|
-
get patches() {
|
|
1600
|
-
return patches;
|
|
1601
|
-
},
|
|
1602
|
-
appendExtra(groups) {
|
|
1603
|
-
if (!groups.length) return;
|
|
1604
|
-
extrasRef.value = [...extrasRef.value, ...groups];
|
|
1605
|
-
},
|
|
1606
|
-
patchGroup(messageId, patch, sourceGroups) {
|
|
1607
|
-
const current = patches.get(messageId) ?? sourceGroups().find((g) => g.id === messageId);
|
|
1608
|
-
if (!current) return;
|
|
1609
|
-
const next = typeof patch === "function" ? patch(current) : { ...current, ...patch };
|
|
1610
|
-
patches.set(messageId, { ...next, id: current.id });
|
|
1611
|
-
},
|
|
1612
|
-
clearPatches() {
|
|
1613
|
-
patches.clear();
|
|
1614
|
-
extrasRef.value = [];
|
|
1615
|
-
},
|
|
1616
|
-
/** human extras 按序收敛:回显(同文本 + 当前流 runId)到达后按序移除乐观副本。
|
|
1617
|
-
* 用 runId 而非流式段判定:既有线程的回显可能经 reconcile 以 page-source 到达(不在流式段),
|
|
1618
|
-
* 但其 runId 与当前流一致;历史消息 runId 不同,不会误伤(连发同文本逐条配对)。
|
|
1619
|
-
* 无当前流 runId(流未开始)时不 prune——避免历史同文本消息误吞乐观副本。 */
|
|
1620
|
-
pruneExtras(decoratedGroups, currentRunId) {
|
|
1621
|
-
if (!extrasRef.value.some((g) => g.type === "human")) return;
|
|
1622
|
-
const runIdFilter = String(currentRunId || "").trim();
|
|
1623
|
-
if (!runIdFilter) return;
|
|
1624
|
-
const echoed = /* @__PURE__ */ new Map();
|
|
1625
|
-
for (const g of decoratedGroups) {
|
|
1626
|
-
if (g.type !== "human") continue;
|
|
1627
|
-
const runId = String(g.runId || "").trim();
|
|
1628
|
-
if (runId !== runIdFilter) continue;
|
|
1629
|
-
const text = readFirstText(g);
|
|
1630
|
-
echoed.set(text, (echoed.get(text) ?? 0) + 1);
|
|
1631
|
-
}
|
|
1632
|
-
const seenPerText = /* @__PURE__ */ new Map();
|
|
1633
|
-
extrasRef.value = extrasRef.value.filter((extra) => {
|
|
1634
|
-
if (extra.type !== "human") return true;
|
|
1635
|
-
const text = readFirstText(extra);
|
|
1636
|
-
const k = seenPerText.get(text) ?? 0;
|
|
1637
|
-
seenPerText.set(text, k + 1);
|
|
1638
|
-
return (echoed.get(text) ?? 0) <= k;
|
|
1639
|
-
});
|
|
1640
|
-
}
|
|
1641
|
-
};
|
|
1642
|
-
}
|
|
1643
|
-
|
|
1644
|
-
// src/domain/decorators.ts
|
|
1645
|
-
function applyPatchesAndExtras(groups, state, runIdFilter) {
|
|
1646
|
-
if (!state.patches.size && !state.extras.length) return groups;
|
|
1647
|
-
const patchedGroups = groups.map((g) => state.patches.get(g.id) ?? g);
|
|
1648
|
-
const anchor = runIdFilter ? patchedGroups.findIndex((g) => String(g.runId || "").trim() === runIdFilter) : -1;
|
|
1649
|
-
return anchor >= 0 ? [...patchedGroups.slice(0, anchor), ...state.extras, ...patchedGroups.slice(anchor)] : [...patchedGroups, ...state.extras];
|
|
1650
|
-
}
|
|
1651
|
-
function withInterruptBlock(groups, deps) {
|
|
1652
|
-
const interrupt = deps.getInterrupt();
|
|
1653
|
-
if (!interrupt) return groups;
|
|
1654
|
-
const interruptId = String(interrupt.id || "");
|
|
1655
|
-
const responded = !!interruptId && deps.respondedIds.has(interruptId);
|
|
1656
|
-
const block = buildInterruptReviewBlock(interrupt, responded);
|
|
1657
|
-
if (!block) return groups;
|
|
1658
|
-
const { interruptBlocks } = deps;
|
|
1659
|
-
const targetIndex = findLastAiIndex(groups);
|
|
1660
|
-
if (targetIndex >= 0) {
|
|
1661
|
-
const remembered = interruptBlocks.get(interruptId);
|
|
1662
|
-
if (remembered) {
|
|
1663
|
-
const updated = { ...block, status: responded ? "completed" : "pending" };
|
|
1664
|
-
interruptBlocks.set(interruptId, updated);
|
|
1665
|
-
const next2 = [...groups];
|
|
1666
|
-
next2[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, updated] };
|
|
1667
|
-
return next2;
|
|
1668
|
-
}
|
|
1669
|
-
interruptBlocks.set(interruptId, block);
|
|
1670
|
-
const next = [...groups];
|
|
1671
|
-
next[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, block] };
|
|
1672
|
-
return next;
|
|
1673
|
-
}
|
|
1674
|
-
const existing = [...interruptBlocks.values()].find(
|
|
1675
|
-
(b) => b.type === "interrupt-review" && b.interruptId === interruptId
|
|
1676
|
-
);
|
|
1677
|
-
if (existing) return groups;
|
|
1678
|
-
interruptBlocks.set(interruptId, block);
|
|
1679
|
-
return [
|
|
1680
|
-
...groups,
|
|
1681
|
-
{
|
|
1682
|
-
id: `interrupt-${interruptId}`,
|
|
1683
|
-
type: "ai",
|
|
1684
|
-
status: block.status,
|
|
1685
|
-
source: "state",
|
|
1686
|
-
originMessageIds: [],
|
|
1687
|
-
blocks: [block],
|
|
1688
|
-
toolIds: [],
|
|
1689
|
-
tools: [],
|
|
1690
|
-
rawMessages: [],
|
|
1691
|
-
createdAt: Date.now()
|
|
1692
|
-
}
|
|
1693
|
-
];
|
|
1694
|
-
}
|
|
1695
|
-
function findLastAiIndex(groups) {
|
|
1696
|
-
for (let i = groups.length - 1; i >= 0; i--) {
|
|
1697
|
-
if (groups[i].type === "ai") return i;
|
|
1698
|
-
}
|
|
1699
|
-
return -1;
|
|
1700
|
-
}
|
|
1701
|
-
function decorateAnswers(groups, answers, responded) {
|
|
1702
|
-
if (!answers.size && !responded.size) return groups;
|
|
1703
|
-
return groups.map((g) => {
|
|
1704
|
-
if (g.type !== "ai" || !g.blocks.length) return g;
|
|
1705
|
-
let touched = false;
|
|
1706
|
-
const blocks = g.blocks.map((b) => {
|
|
1707
|
-
const blk = b;
|
|
1708
|
-
if (isClarificationBlock(blk) && blk.toolCallId && answers.has(blk.toolCallId)) {
|
|
1709
|
-
touched = true;
|
|
1710
|
-
return { ...b, isAnswered: true, answer: answers.get(blk.toolCallId) };
|
|
1711
|
-
}
|
|
1712
|
-
if (blk.type === "interrupt-review" && blk.interruptId && responded.has(blk.interruptId)) {
|
|
1713
|
-
touched = true;
|
|
1714
|
-
return { ...b, isResponded: true };
|
|
1715
|
-
}
|
|
1716
|
-
return b;
|
|
1717
|
-
});
|
|
1718
|
-
return touched ? { ...g, blocks } : g;
|
|
1719
|
-
});
|
|
1720
|
-
}
|
|
1721
|
-
function filterInvisibleAiGroups(groups) {
|
|
1722
|
-
return groups.filter((g) => g.type !== "ai" || hasVisibleAiContent(g));
|
|
1723
|
-
}
|
|
1724
|
-
function hasVisibleAiContent(g) {
|
|
1725
|
-
if (g.status === "streaming") return true;
|
|
1726
|
-
if (g.streamingText) return true;
|
|
1727
|
-
if (g.blocks.length) return true;
|
|
1728
|
-
return g.tools.some((t) => t.result !== void 0 || t.state === "error");
|
|
1729
|
-
}
|
|
1730
|
-
|
|
1731
|
-
// src/domain/viewmodel.ts
|
|
1732
|
-
function createGroupDeriver(state) {
|
|
1733
|
-
const groupMemo = /* @__PURE__ */ new Map();
|
|
1734
|
-
const foldCache = { pageCount: -1, entries: [] };
|
|
1735
|
-
const interruptBlocks = /* @__PURE__ */ new Map();
|
|
1736
|
-
const derive = (deps) => {
|
|
1737
|
-
const { store, enrichments } = deps;
|
|
1738
|
-
const streaming = store.streamStatus === "streaming";
|
|
1739
|
-
const patched = store.getMessages().map((m) => {
|
|
1740
|
-
const patch = enrichments.resolveCitation(String(asSxin(m).id || ""));
|
|
1741
|
-
if (!patch || patch.content === void 0) return m;
|
|
1742
|
-
return { ...asSxin(m), content: patch.content };
|
|
1743
|
-
});
|
|
1744
|
-
const sourceOf = (id) => id ? store.getEntity(id)?.source ?? "stream" : "stream";
|
|
1745
|
-
const epochOf = (id) => id ? store.getEntity(id)?.epoch : void 0;
|
|
1746
|
-
const runIdFilter = String(deps.currentRunId || "").trim();
|
|
1747
|
-
const currentEpoch = store.streamEpoch;
|
|
1748
|
-
const pageCount = store.pageCount;
|
|
1749
|
-
const patchedPrefix = patched.slice(0, pageCount);
|
|
1750
|
-
const patchedStream = patched.slice(pageCount);
|
|
1751
|
-
let prefixEntries;
|
|
1752
|
-
if (foldCache.pageCount === pageCount) {
|
|
1753
|
-
prefixEntries = foldCache.entries;
|
|
1754
|
-
} else {
|
|
1755
|
-
prefixEntries = [];
|
|
1756
|
-
foldMessages(
|
|
1757
|
-
patchedPrefix,
|
|
1758
|
-
(type, buf) => prefixEntries.push({ type, ids: buf.map((m) => String(asSxin(m).id || "")) })
|
|
1759
|
-
);
|
|
1760
|
-
foldCache.pageCount = pageCount;
|
|
1761
|
-
foldCache.entries = prefixEntries;
|
|
1762
|
-
}
|
|
1763
|
-
const prefixById = new Map(patchedPrefix.map((m) => [String(asSxin(m).id || ""), m]));
|
|
1764
|
-
const folded = [];
|
|
1765
|
-
if (prefixEntries.every((e) => e.ids.every((id) => prefixById.has(id)))) {
|
|
1766
|
-
for (const e of prefixEntries) folded.push({ type: e.type, buf: e.ids.map((id) => prefixById.get(id)) });
|
|
1767
|
-
const streamFolded = [];
|
|
1768
|
-
foldMessages(patchedStream, (type, buf) => streamFolded.push({ type, buf }));
|
|
1769
|
-
const lastPrefix = folded[folded.length - 1];
|
|
1770
|
-
const firstStream = streamFolded[0];
|
|
1771
|
-
if (lastPrefix && firstStream && canMergeAtBoundary(lastPrefix, firstStream)) {
|
|
1772
|
-
lastPrefix.buf = [...lastPrefix.buf, ...firstStream.buf];
|
|
1773
|
-
streamFolded.shift();
|
|
1774
|
-
}
|
|
1775
|
-
folded.push(...streamFolded);
|
|
1776
|
-
} else {
|
|
1777
|
-
foldCache.pageCount = -1;
|
|
1778
|
-
foldCache.entries = [];
|
|
1779
|
-
foldMessages(patched, (type, buf) => folded.push({ type, buf }));
|
|
1780
|
-
}
|
|
1781
|
-
const groups = [];
|
|
1782
|
-
let epochActiveFrom = 0;
|
|
1783
|
-
if (streaming && !runIdFilter) {
|
|
1784
|
-
epochActiveFrom = -1;
|
|
1785
|
-
folded.forEach((entry, i) => {
|
|
1786
|
-
const id = String(asSxin(entry.buf[0]).id || "");
|
|
1787
|
-
if (entry.type === "human" && sourceOf(id) === "stream" && epochOf(id) === currentEpoch) epochActiveFrom = i;
|
|
1788
|
-
});
|
|
1789
|
-
if (epochActiveFrom < 0) epochActiveFrom = 0;
|
|
1790
|
-
}
|
|
1791
|
-
folded.forEach((entry, gi) => {
|
|
1792
|
-
const firstId = String(asSxin(entry.buf[0]).id || "");
|
|
1793
|
-
const firstSource = sourceOf(firstId);
|
|
1794
|
-
let groupRunId = messageRunId(entry.buf[0]);
|
|
1795
|
-
if (!groupRunId) {
|
|
1796
|
-
for (let i = 1; i < entry.buf.length; i++) {
|
|
1797
|
-
const rid = messageRunId(entry.buf[i]);
|
|
1798
|
-
if (rid) {
|
|
1799
|
-
groupRunId = rid;
|
|
1800
|
-
break;
|
|
1801
|
-
}
|
|
1802
|
-
}
|
|
1803
|
-
}
|
|
1804
|
-
groupRunId = groupRunId || void 0;
|
|
1805
|
-
const inActiveZone = streaming ? runIdFilter ? groupRunId === runIdFilter : firstSource === "stream" && epochOf(firstId) === currentEpoch && gi >= epochActiveFrom : false;
|
|
1806
|
-
const status = inActiveZone ? "streaming" : "completed";
|
|
1807
|
-
const blockSource = firstSource === "page" ? "history" : "sse";
|
|
1808
|
-
let verSum = 0;
|
|
1809
|
-
for (const m of entry.buf) verSum += store.getEntity(String(asSxin(m).id || ""))?.ver ?? 0;
|
|
1810
|
-
const memoKey = `${firstId}|${status}|${blockSource}|${entry.buf.length}|${verSum}|${enrichments.citationVersion}`;
|
|
1811
|
-
const cached = groupMemo.get(memoKey);
|
|
1812
|
-
if (cached) {
|
|
1813
|
-
groups.push(cached);
|
|
1814
|
-
return;
|
|
1815
|
-
}
|
|
1816
|
-
let g;
|
|
1817
|
-
if (entry.type === "human") {
|
|
1818
|
-
g = buildHumanGroup(entry.buf, status);
|
|
1819
|
-
} else {
|
|
1820
|
-
g = buildAiGroup(entry.buf, { source: blockSource, isStreaming: status === "streaming" }, deps.twin);
|
|
1821
|
-
}
|
|
1822
|
-
if (groupMemo.size > 2e3) groupMemo.clear();
|
|
1823
|
-
groupMemo.set(memoKey, g);
|
|
1824
|
-
groups.push(g);
|
|
1825
|
-
});
|
|
1826
|
-
for (const g of groups) {
|
|
1827
|
-
if (g.type === "ai" && g.status === "streaming") {
|
|
1828
|
-
const aiMessages = g.rawMessages.filter((m) => String(asSxin(m).type || "").startsWith("ai"));
|
|
1829
|
-
const lastAi = aiMessages[aiMessages.length - 1];
|
|
1830
|
-
g.streamingText = lastAi ? extractAiContentFromMessage(lastAi) : "";
|
|
1831
|
-
}
|
|
1832
|
-
}
|
|
1833
|
-
const sourceGroups = groups;
|
|
1834
|
-
const decorateSteps = [
|
|
1835
|
-
// 第 1 步:补丁应用 + 乐观 extras 锚点落位
|
|
1836
|
-
(gs) => applyPatchesAndExtras(gs, state, runIdFilter),
|
|
1837
|
-
// 第 2 步:interrupt 审核块注入(去重记忆 interruptBlocks 为构建器公开职责)
|
|
1838
|
-
(gs) => withInterruptBlock(gs, {
|
|
1839
|
-
getInterrupt: deps.getInterrupt,
|
|
1840
|
-
respondedIds: deps.respondedIds,
|
|
1841
|
-
interruptBlocks
|
|
1842
|
-
}),
|
|
1843
|
-
// 第 3 步:澄清回答 / interrupt 响应标记装饰
|
|
1844
|
-
(gs) => decorateAnswers(gs, enrichments.answers, deps.respondedIds),
|
|
1845
|
-
// 第 4 步:隐藏「无可见内容」的 AI 空气泡
|
|
1846
|
-
filterInvisibleAiGroups
|
|
1847
|
-
];
|
|
1848
|
-
const merged = decorateSteps.reduce((gs, step) => step(gs), sourceGroups);
|
|
1849
|
-
return { groups: merged, sourceGroups };
|
|
1850
|
-
};
|
|
1851
|
-
return {
|
|
1852
|
-
derive,
|
|
1853
|
-
clearCache() {
|
|
1854
|
-
groupMemo.clear();
|
|
1855
|
-
foldCache.pageCount = -1;
|
|
1856
|
-
foldCache.entries = [];
|
|
1857
|
-
interruptBlocks.clear();
|
|
1858
|
-
}
|
|
1859
|
-
};
|
|
1860
|
-
}
|
|
1861
|
-
function canMergeAtBoundary(prefixLast, streamFirst) {
|
|
1862
|
-
if (prefixLast.type === "human" && streamFirst.type === "human") {
|
|
1863
|
-
return getHumanMessageBaseId(String(asSxin(streamFirst.buf[0]).id || "")) === getHumanMessageBaseId(String(asSxin(prefixLast.buf[0]).id || ""));
|
|
1864
|
-
}
|
|
1865
|
-
if (prefixLast.type === "ai" && streamFirst.type === "ai") {
|
|
1866
|
-
const mRunId = messageRunId(streamFirst.buf[0]);
|
|
1867
|
-
const groupRunId = messageRunId(prefixLast.buf[0]);
|
|
1868
|
-
return !(mRunId && groupRunId && mRunId !== groupRunId);
|
|
1869
|
-
}
|
|
1870
|
-
return false;
|
|
1871
|
-
}
|
|
1872
|
-
function createOptimisticHuman(text, options) {
|
|
1873
|
-
const optimisticId = genMessageId();
|
|
1874
|
-
return {
|
|
1875
|
-
id: optimisticId,
|
|
1876
|
-
type: "human",
|
|
1877
|
-
status: "completed",
|
|
1878
|
-
originMessageIds: [optimisticId],
|
|
1879
|
-
rawMessages: [
|
|
1880
|
-
{
|
|
1881
|
-
id: optimisticId,
|
|
1882
|
-
type: "human",
|
|
1883
|
-
name: "user-input",
|
|
1884
|
-
content: [{ type: "text", text }],
|
|
1885
|
-
additional_kwargs: options?.kwargs
|
|
1886
|
-
}
|
|
1887
|
-
],
|
|
1888
|
-
additionalKwargs: options?.kwargs,
|
|
1889
|
-
blocks: [],
|
|
1890
|
-
toolIds: [],
|
|
1891
|
-
tools: [],
|
|
1892
|
-
createdAt: Date.now()
|
|
1893
|
-
};
|
|
1894
|
-
}
|
|
1895
|
-
|
|
1896
|
-
// src/runtime/thread-runtime.ts
|
|
1897
|
-
import { computed as computed3, effectScope, ref as ref3, shallowRef as shallowRef4 } from "vue";
|
|
1898
|
-
|
|
1899
|
-
// src/message/dict-merge.ts
|
|
1900
|
-
var MERGE_IGNORE_KEYS = ["index", "created", "timestamp"];
|
|
1901
|
-
var MERGE_RIGHT_WINS_KEYS = ["id", "name", "output_version", "model_provider"];
|
|
1902
|
-
function hasMergeableIndex(value) {
|
|
1903
|
-
if (typeof value !== "object" || value === null) return false;
|
|
1904
|
-
const idx = value.index;
|
|
1905
|
-
return typeof idx === "number" || typeof idx === "string";
|
|
1906
|
-
}
|
|
1907
|
-
function hasMergeableId(value) {
|
|
1908
|
-
if (typeof value !== "object" || value === null) return false;
|
|
1909
|
-
const id = value.id;
|
|
1910
|
-
return id != null && id !== "";
|
|
1911
|
-
}
|
|
1912
|
-
function findMergeTarget(merged, item) {
|
|
1913
|
-
if (!hasMergeableIndex(item) && !hasMergeableId(item)) return -1;
|
|
1914
|
-
return merged.findIndex((leftItem) => {
|
|
1915
|
-
const leftHasIndex = hasMergeableIndex(leftItem);
|
|
1916
|
-
const leftHasId = hasMergeableId(leftItem);
|
|
1917
|
-
const itemHasIndex = hasMergeableIndex(item);
|
|
1918
|
-
const itemHasId = hasMergeableId(item);
|
|
1919
|
-
if (itemHasIndex && leftHasIndex) {
|
|
1920
|
-
if (leftItem.index !== item.index) return false;
|
|
1921
|
-
if (leftHasId && itemHasId)
|
|
1922
|
-
return leftItem.id === item.id;
|
|
1923
|
-
return true;
|
|
1924
|
-
}
|
|
1925
|
-
if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {
|
|
1926
|
-
return leftItem.id === item.id;
|
|
1927
|
-
}
|
|
1928
|
-
return false;
|
|
1929
|
-
});
|
|
1930
|
-
}
|
|
1931
|
-
function mergeStringField(key, left, right) {
|
|
1932
|
-
if (key === "type") return left;
|
|
1933
|
-
if (MERGE_RIGHT_WINS_KEYS.includes(key)) return right || left;
|
|
1934
|
-
if (MERGE_IGNORE_KEYS.includes(key)) return left;
|
|
1935
|
-
return left + right;
|
|
1936
|
-
}
|
|
1937
|
-
function mergeNumberField(key, left, right) {
|
|
1938
|
-
return MERGE_IGNORE_KEYS.includes(key) ? left : left + right;
|
|
1939
|
-
}
|
|
1940
|
-
function mergeDicts(left, right) {
|
|
1941
|
-
if (left == null) return right;
|
|
1942
|
-
if (right == null) return left;
|
|
1943
|
-
if (Array.isArray(left) && Array.isArray(right)) return mergeLists(left, right);
|
|
1944
|
-
if (typeof left === "string" && typeof right === "string") return left + right;
|
|
1945
|
-
if (typeof left === "number" && typeof right === "number") return left + right;
|
|
1946
|
-
if (typeof left === "object" && typeof right === "object") {
|
|
1947
|
-
const merged = { ...left };
|
|
1948
|
-
for (const [key, value] of Object.entries(right)) {
|
|
1949
|
-
const l = merged[key];
|
|
1950
|
-
if (l == null) {
|
|
1951
|
-
merged[key] = value;
|
|
1952
|
-
} else if (value == null) {
|
|
1953
|
-
continue;
|
|
1954
|
-
} else if (typeof l === "string" && typeof value === "string") {
|
|
1955
|
-
merged[key] = mergeStringField(key, l, value);
|
|
1956
|
-
} else if (typeof l === "number" && typeof value === "number") {
|
|
1957
|
-
merged[key] = mergeNumberField(key, l, value);
|
|
1958
|
-
} else if (Array.isArray(l) && Array.isArray(value)) {
|
|
1959
|
-
merged[key] = mergeLists(l, value);
|
|
1960
|
-
} else if (typeof l === "object" && typeof value === "object") {
|
|
1961
|
-
merged[key] = mergeDicts(l, value);
|
|
1962
|
-
} else {
|
|
1963
|
-
merged[key] = value;
|
|
1964
|
-
}
|
|
1965
|
-
}
|
|
1966
|
-
return merged;
|
|
1967
|
-
}
|
|
1968
|
-
return right;
|
|
1969
|
-
}
|
|
1970
|
-
function mergeLists(left, right) {
|
|
1971
|
-
const merged = [...left];
|
|
1972
|
-
for (const item of right) {
|
|
1973
|
-
const target = findMergeTarget(merged, item);
|
|
1974
|
-
if (target !== -1) {
|
|
1975
|
-
merged[target] = mergeDicts(merged[target], item);
|
|
1976
|
-
} else if (typeof item === "object" && item !== null && "text" in item && item.text === "") {
|
|
1977
|
-
continue;
|
|
1978
|
-
} else {
|
|
1979
|
-
merged.push(item);
|
|
1980
|
-
}
|
|
1981
|
-
}
|
|
1982
|
-
return merged;
|
|
1983
|
-
}
|
|
1984
|
-
function mergeContent(left, right) {
|
|
1985
|
-
if (left == null) return right;
|
|
1986
|
-
if (right == null) return left;
|
|
1987
|
-
if (typeof left === "string" && typeof right === "string") return left + right;
|
|
1988
|
-
const leftArr = Array.isArray(left) ? left : [left];
|
|
1989
|
-
const rightArr = Array.isArray(right) ? right : [right];
|
|
1990
|
-
return mergeLists(leftArr, rightArr);
|
|
1991
|
-
}
|
|
1992
|
-
function parsePartialJson(text) {
|
|
1993
|
-
const tryParse = (s) => {
|
|
1994
|
-
try {
|
|
1995
|
-
return JSON.parse(s);
|
|
1996
|
-
} catch {
|
|
1997
|
-
return void 0;
|
|
1998
|
-
}
|
|
1999
|
-
};
|
|
2000
|
-
const direct = tryParse(text);
|
|
2001
|
-
if (direct !== void 0) return direct;
|
|
2002
|
-
let fixed = text;
|
|
2003
|
-
let inStr = false;
|
|
2004
|
-
let escaped = false;
|
|
2005
|
-
for (const ch of fixed) {
|
|
2006
|
-
if (escaped) {
|
|
2007
|
-
escaped = false;
|
|
2008
|
-
continue;
|
|
2009
|
-
}
|
|
2010
|
-
if (ch === "\\") {
|
|
2011
|
-
escaped = true;
|
|
2012
|
-
continue;
|
|
2013
|
-
}
|
|
2014
|
-
if (ch === '"') inStr = !inStr;
|
|
2015
|
-
}
|
|
2016
|
-
if (inStr) fixed += '"';
|
|
2017
|
-
const closers = [];
|
|
2018
|
-
for (const ch of fixed) {
|
|
2019
|
-
if (ch === "{") closers.push("}");
|
|
2020
|
-
else if (ch === "[") closers.push("]");
|
|
2021
|
-
else if (ch === "}" || ch === "]") closers.pop();
|
|
2022
|
-
}
|
|
2023
|
-
fixed += closers.reverse().join("");
|
|
2024
|
-
const repaired = tryParse(fixed);
|
|
2025
|
-
return repaired === void 0 ? null : repaired;
|
|
2026
|
-
}
|
|
2027
|
-
function collapseToolCallChunks(chunks) {
|
|
2028
|
-
const groups = [];
|
|
2029
|
-
for (const chunk of chunks) {
|
|
2030
|
-
const matched = groups.findIndex((group) => {
|
|
2031
|
-
const match = group[0];
|
|
2032
|
-
if (chunk?.id && chunk?.index !== void 0) return chunk.id === match.id && chunk.index === match.index;
|
|
2033
|
-
if (chunk?.id) return chunk.id === match.id;
|
|
2034
|
-
if (chunk?.index !== void 0) return chunk.index === match.index;
|
|
2035
|
-
return false;
|
|
2036
|
-
});
|
|
2037
|
-
if (matched !== -1) groups[matched].push(chunk);
|
|
2038
|
-
else groups.push([chunk]);
|
|
2039
|
-
}
|
|
2040
|
-
const toolCalls = [];
|
|
2041
|
-
const invalidToolCalls = [];
|
|
2042
|
-
for (const group of groups) {
|
|
2043
|
-
const name = group[0]?.name ?? "";
|
|
2044
|
-
const joinedArgs = group.map((c) => c?.args || "").join("");
|
|
2045
|
-
const argsStr = joinedArgs.trim().length ? joinedArgs.trim() : "{}";
|
|
2046
|
-
const id = group.find((c) => c?.id)?.id ?? group[0]?.id;
|
|
2047
|
-
const parsed = parsePartialJson(argsStr);
|
|
2048
|
-
if (!id || parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
2049
|
-
invalidToolCalls.push({ name, args: argsStr, id, error: "Malformed args.", type: "invalid_tool_call" });
|
|
2050
|
-
} else {
|
|
2051
|
-
toolCalls.push({ name, args: parsed, id, type: "tool_call" });
|
|
2052
|
-
}
|
|
2053
|
-
}
|
|
2054
|
-
return { tool_calls: toolCalls, invalid_tool_calls: invalidToolCalls };
|
|
2055
|
-
}
|
|
2056
|
-
function extractToolCallsFromContent(content) {
|
|
2057
|
-
if (!Array.isArray(content)) return [];
|
|
2058
|
-
return content.flatMap((block) => {
|
|
2059
|
-
if (block == null || typeof block !== "object") return [];
|
|
2060
|
-
const record = block;
|
|
2061
|
-
if (record.type !== "tool_call" && record.type !== "tool_use") return [];
|
|
2062
|
-
const rawArgs = record.args ?? record.input;
|
|
2063
|
-
let args = {};
|
|
2064
|
-
if (rawArgs != null && typeof rawArgs === "object" && !Array.isArray(rawArgs)) args = rawArgs;
|
|
2065
|
-
else if (typeof rawArgs === "string" && rawArgs.length > 0) {
|
|
2066
|
-
const parsed = parsePartialJson(rawArgs);
|
|
2067
|
-
if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) args = parsed;
|
|
2068
|
-
}
|
|
2069
|
-
return [{ id: record.id ?? "", name: record.name ?? "", args, type: "tool_call" }];
|
|
2070
|
-
});
|
|
2071
|
-
}
|
|
2072
|
-
function mergeMessageDicts(prev, next) {
|
|
2073
|
-
const merged = { ...prev };
|
|
2074
|
-
for (const [key, value] of Object.entries(next)) {
|
|
2075
|
-
if (key === "type") {
|
|
2076
|
-
if (merged.type == null) merged.type = value;
|
|
2077
|
-
continue;
|
|
2078
|
-
}
|
|
2079
|
-
if (MERGE_RIGHT_WINS_KEYS.includes(key)) {
|
|
2080
|
-
if (value != null && value !== "") merged[key] = value;
|
|
2081
|
-
continue;
|
|
2082
|
-
}
|
|
2083
|
-
if (key === "content") {
|
|
2084
|
-
merged.content = mergeContent(prev.content, value);
|
|
2085
|
-
} else if (key === "tool_call_chunks") {
|
|
2086
|
-
const prevChunks = Array.isArray(prev.tool_call_chunks) ? prev.tool_call_chunks : [];
|
|
2087
|
-
const nextChunks = Array.isArray(value) ? value : [];
|
|
2088
|
-
const chunks = mergeLists(prevChunks, nextChunks);
|
|
2089
|
-
merged.tool_call_chunks = chunks;
|
|
2090
|
-
const collapsed = collapseToolCallChunks(chunks);
|
|
2091
|
-
merged.tool_calls = collapsed.tool_calls;
|
|
2092
|
-
merged.invalid_tool_calls = collapsed.invalid_tool_calls;
|
|
2093
|
-
} else {
|
|
2094
|
-
merged[key] = mergeDicts(prev[key], value);
|
|
2095
|
-
}
|
|
2096
|
-
}
|
|
2097
|
-
if (!Array.isArray(merged.tool_calls) || merged.tool_calls.length === 0) {
|
|
2098
|
-
const extracted = extractToolCallsFromContent(merged.content);
|
|
2099
|
-
if (extracted.length > 0) merged.tool_calls = extracted;
|
|
2100
|
-
}
|
|
2101
|
-
return merged;
|
|
2102
|
-
}
|
|
2103
|
-
|
|
2104
|
-
// src/protocol/chunk-buffer.ts
|
|
2105
|
-
function normalizeEntry(raw) {
|
|
2106
|
-
const rawType = String(raw.type || "");
|
|
2107
|
-
if (rawType === "RemoveMessage") return { ...raw, type: "remove" };
|
|
2108
|
-
return raw;
|
|
2109
|
-
}
|
|
2110
|
-
function stampRunId(msg, streamRunId) {
|
|
2111
|
-
if (String(msg.runId || "").trim()) return msg;
|
|
2112
|
-
const kwargsRunId = String(msg.additional_kwargs?.run_id || "").trim();
|
|
2113
|
-
const rid = kwargsRunId || String(streamRunId || "").trim();
|
|
2114
|
-
if (!rid) return msg;
|
|
2115
|
-
return { ...msg, runId: rid };
|
|
2116
|
-
}
|
|
2117
|
-
function createChunkBuffer(options) {
|
|
2118
|
-
const schedule = options.schedule ?? ((fn) => setTimeout(fn, 0));
|
|
2119
|
-
const pending = /* @__PURE__ */ new Map();
|
|
2120
|
-
const accumulated = /* @__PURE__ */ new Map();
|
|
2121
|
-
let order = [];
|
|
2122
|
-
const dirty = /* @__PURE__ */ new Set();
|
|
2123
|
-
let scheduled = false;
|
|
2124
|
-
let timer = null;
|
|
2125
|
-
let streamRunId;
|
|
2126
|
-
const cancelSchedule = () => {
|
|
2127
|
-
scheduled = false;
|
|
2128
|
-
if (timer !== null) clearTimeout(timer);
|
|
2129
|
-
timer = null;
|
|
2130
|
-
};
|
|
2131
|
-
const scheduleFlush = () => {
|
|
2132
|
-
if (scheduled) return;
|
|
2133
|
-
scheduled = true;
|
|
2134
|
-
timer = schedule(() => {
|
|
2135
|
-
scheduled = false;
|
|
2136
|
-
timer = null;
|
|
2137
|
-
flush();
|
|
2138
|
-
});
|
|
2139
|
-
};
|
|
2140
|
-
function flush() {
|
|
2141
|
-
if (!order.length) return;
|
|
2142
|
-
const instructions = [];
|
|
2143
|
-
for (const id of order) {
|
|
2144
|
-
const entry = pending.get(id);
|
|
2145
|
-
if (!entry) continue;
|
|
2146
|
-
if (entry.isClear) {
|
|
2147
|
-
instructions.push({ kind: "clear" });
|
|
2148
|
-
accumulated.clear();
|
|
2149
|
-
continue;
|
|
2150
|
-
}
|
|
2151
|
-
if (entry.isRemove) {
|
|
2152
|
-
instructions.push({ kind: "remove", id });
|
|
2153
|
-
accumulated.delete(id);
|
|
2154
|
-
continue;
|
|
2155
|
-
}
|
|
2156
|
-
const base = accumulated.get(id);
|
|
2157
|
-
const merged = base ? entry.parts.reduce((acc, c) => mergeMessageDicts(acc, c), base) : entry.parts.reduce(mergeMessageDicts);
|
|
2158
|
-
accumulated.set(id, merged);
|
|
2159
|
-
instructions.push({ kind: "upsert", message: stampRunId(merged, streamRunId) });
|
|
2160
|
-
}
|
|
2161
|
-
pending.clear();
|
|
2162
|
-
order = [];
|
|
2163
|
-
dirty.clear();
|
|
2164
|
-
if (instructions.length) options.emit(instructions);
|
|
2165
|
-
}
|
|
2166
|
-
return {
|
|
2167
|
-
add(serialized) {
|
|
2168
|
-
if (!serialized || typeof serialized !== "object") return;
|
|
2169
|
-
const raw = serialized;
|
|
2170
|
-
const rawType = String(raw.type || "");
|
|
2171
|
-
const entry = normalizeEntry(raw);
|
|
2172
|
-
const type = String(entry.type || "");
|
|
2173
|
-
const id = String(entry.id || "").trim();
|
|
2174
|
-
if (!id) return;
|
|
2175
|
-
if (type === "remove") {
|
|
2176
|
-
if (id === "__remove_all__") {
|
|
2177
|
-
pending.set(id, { parts: [], isClear: true });
|
|
2178
|
-
} else {
|
|
2179
|
-
pending.set(id, { parts: [], isRemove: true });
|
|
2180
|
-
}
|
|
2181
|
-
if (!dirty.has(id)) {
|
|
2182
|
-
dirty.add(id);
|
|
2183
|
-
order.push(id);
|
|
2184
|
-
}
|
|
2185
|
-
scheduleFlush();
|
|
2186
|
-
return;
|
|
2187
|
-
}
|
|
2188
|
-
const isChunk = rawType.endsWith("MessageChunk");
|
|
2189
|
-
const existing = pending.get(id);
|
|
2190
|
-
if (!existing || existing.isRemove) {
|
|
2191
|
-
pending.set(id, { parts: [entry] });
|
|
2192
|
-
} else if (!isChunk) {
|
|
2193
|
-
existing.parts = [entry];
|
|
2194
|
-
} else {
|
|
2195
|
-
existing.parts.push(entry);
|
|
2196
|
-
}
|
|
2197
|
-
if (!dirty.has(id)) {
|
|
2198
|
-
dirty.add(id);
|
|
2199
|
-
order.push(id);
|
|
2200
|
-
}
|
|
2201
|
-
scheduleFlush();
|
|
2202
|
-
},
|
|
2203
|
-
noteStreamRunId(runId) {
|
|
2204
|
-
const trimmed = String(runId || "").trim();
|
|
2205
|
-
if (trimmed) streamRunId = trimmed;
|
|
2206
|
-
},
|
|
2207
|
-
reset() {
|
|
2208
|
-
cancelSchedule();
|
|
2209
|
-
pending.clear();
|
|
2210
|
-
order = [];
|
|
2211
|
-
dirty.clear();
|
|
2212
|
-
accumulated.clear();
|
|
2213
|
-
streamRunId = void 0;
|
|
2214
|
-
},
|
|
2215
|
-
flush,
|
|
2216
|
-
dispose() {
|
|
2217
|
-
cancelSchedule();
|
|
2218
|
-
pending.clear();
|
|
2219
|
-
order = [];
|
|
2220
|
-
dirty.clear();
|
|
2221
|
-
accumulated.clear();
|
|
2222
|
-
}
|
|
2223
|
-
};
|
|
2224
|
-
}
|
|
2225
|
-
|
|
2226
|
-
// src/runtime/history-pager.ts
|
|
2227
|
-
import { computed, ref } from "vue";
|
|
2228
|
-
function createHistoryPager(options) {
|
|
2229
|
-
const { threadId, transport, firstPage } = options;
|
|
2230
|
-
let cursor = firstPage.nextBeforeSeq;
|
|
2231
|
-
const hasMoreRef = ref(Boolean(firstPage.hasMore) && firstPage.nextBeforeSeq !== void 0);
|
|
2232
|
-
const loading = ref(false);
|
|
2233
|
-
const loadOlder = async () => {
|
|
2234
|
-
if (loading.value) return hasMoreRef.value;
|
|
2235
|
-
if (!hasMoreRef.value || cursor === void 0) {
|
|
2236
|
-
hasMoreRef.value = false;
|
|
2237
|
-
return false;
|
|
2238
|
-
}
|
|
2239
|
-
loading.value = true;
|
|
2240
|
-
try {
|
|
2241
|
-
const page = await transport.fetchMessagesPage(threadId, { beforeSeq: cursor });
|
|
2242
|
-
const pageMessages = runMessagesToMessages(page.messages);
|
|
2243
|
-
options.emitChanges({ kind: "prepend", messages: pageMessages });
|
|
2244
|
-
cursor = page.nextBeforeSeq;
|
|
2245
|
-
hasMoreRef.value = Boolean(page.hasMore) && page.nextBeforeSeq !== void 0;
|
|
2246
|
-
options.onPageLoaded?.(page);
|
|
2247
|
-
return hasMoreRef.value;
|
|
2248
|
-
} finally {
|
|
2249
|
-
loading.value = false;
|
|
2250
|
-
}
|
|
2251
|
-
};
|
|
2252
|
-
return { loadOlder, hasMore: computed(() => hasMoreRef.value), loading };
|
|
2253
|
-
}
|
|
2254
|
-
|
|
2255
|
-
// src/runtime/runtime-bootstrap.ts
|
|
2256
|
-
async function bootstrapRuntime(deps) {
|
|
2257
|
-
const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
|
|
2258
|
-
deps.valuesChannel.applyInitialValues(fetched.values);
|
|
2259
|
-
deps.valuesChannel.applyThreadState(fetched.threadState);
|
|
2260
|
-
deps.enrichments.applyFromStateMessages(extractStateMessages(fetched.threadState));
|
|
2261
|
-
deps.runs.fillFromRunsList(fetched.runsList ?? []);
|
|
2262
|
-
deps.runs.enrichFromPage(fetched.messagesPage);
|
|
2263
|
-
const pageMessages = runMessagesToMessages(fetched.messagesPage.messages);
|
|
2264
|
-
if (pageMessages.length) deps.store.applyInstructions([{ kind: "prepend", messages: pageMessages }]);
|
|
2265
|
-
deps.setPager(
|
|
2266
|
-
createHistoryPager({
|
|
2267
|
-
threadId: deps.threadId,
|
|
2268
|
-
transport: deps.transport,
|
|
2269
|
-
firstPage: fetched.messagesPage,
|
|
2270
|
-
onPageLoaded: (page) => deps.runs.enrichFromPage(page),
|
|
2271
|
-
emitChanges: (batch) => deps.store.applyInstructions([batch])
|
|
2272
|
-
})
|
|
2273
|
-
);
|
|
2274
|
-
await deps.refreshTokenUsage();
|
|
2275
|
-
deps.setChunkBuffer(createChunkBuffer({ emit: (ins) => deps.store.applyInstructions(ins) }));
|
|
2276
|
-
const finalize = () => finalizeAfterStream(deps);
|
|
2277
|
-
const afterFinish = () => afterStreamFinish(deps);
|
|
2278
|
-
deps.streamRef.value = deps.transport.createStream({
|
|
2279
|
-
assistantId: deps.assistantId,
|
|
2280
|
-
threadId: deps.threadId,
|
|
2281
|
-
onCreated: (run) => deps.markStreamRun(run?.run_id),
|
|
2282
|
-
onMetadataEvent: (data) => deps.markStreamRun(data?.run_id),
|
|
2283
|
-
onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
|
|
2284
|
-
onMessageTupleEvent: (serialized, metadata) => deps.getChunkBuffer()?.add(serialized, metadata),
|
|
2285
|
-
onStreamStart: deps.onStreamStart,
|
|
2286
|
-
onStreamEnd: finalize,
|
|
2287
|
-
onFinish: afterFinish,
|
|
2288
|
-
onError: (err) => console.error("[runtime] stream error", err)
|
|
2289
|
-
});
|
|
2290
|
-
deps.setInitialized();
|
|
2291
|
-
}
|
|
2292
|
-
function finalizeAfterStream(deps) {
|
|
2293
|
-
deps.getChunkBuffer()?.flush();
|
|
2294
|
-
deps.enrichments.applyFromStateMessages(deps.valuesChannel.getStreamMessages());
|
|
2295
|
-
deps.store.applyInstructions(buildValuesReplaceInstructions(deps.store, deps.valuesChannel.getStreamMessages()));
|
|
2296
|
-
deps.store.applyInstructions([{ kind: "finalize" }]);
|
|
2297
|
-
deps.runs.backfillCurrentRunMetadata(() => deps.store.getMessages());
|
|
2298
|
-
}
|
|
2299
|
-
function buildValuesReplaceInstructions(store, streamMessages) {
|
|
2300
|
-
const instructions = [];
|
|
2301
|
-
for (const msg of streamMessages) {
|
|
2302
|
-
const id = String(msg?.id || "").trim();
|
|
2303
|
-
if (!id) continue;
|
|
2304
|
-
const existing = store.getEntity(id);
|
|
2305
|
-
if (!existing) continue;
|
|
2306
|
-
if (existing.source !== "stream" || existing.epoch !== store.streamEpoch) continue;
|
|
2307
|
-
const runId = String(existing.msg?.runId || existing.msg?.additional_kwargs?.run_id || "").trim();
|
|
2308
|
-
const next = runId ? { ...msg, runId } : msg;
|
|
2309
|
-
instructions.push({ kind: "upsert", message: next });
|
|
2310
|
-
}
|
|
2311
|
-
return instructions;
|
|
2312
|
-
}
|
|
2313
|
-
async function afterStreamFinish(deps) {
|
|
2314
|
-
await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
|
|
2315
|
-
await reconcileWithPage(deps);
|
|
2316
|
-
await applyCitationsFallback(deps);
|
|
2317
|
-
}
|
|
2318
|
-
async function reconcileWithPage(deps) {
|
|
2319
|
-
try {
|
|
2320
|
-
const page = await deps.transport.fetchMessagesPage(deps.threadId);
|
|
2321
|
-
const messages = runMessagesToMessages(page.messages);
|
|
2322
|
-
if (messages.length) {
|
|
2323
|
-
deps.store.applyInstructions(messages.map((message) => ({ kind: "upsert", message, source: "page" })));
|
|
2324
|
-
}
|
|
2325
|
-
} catch (e) {
|
|
2326
|
-
console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
|
|
2327
|
-
}
|
|
2328
|
-
}
|
|
2329
|
-
async function applyCitationsFallback(deps) {
|
|
2330
|
-
if (deps.valuesChannel.getStreamMessages().length > 0) return;
|
|
2331
|
-
try {
|
|
2332
|
-
const state = await deps.transport.fetchThreadState(deps.threadId);
|
|
2333
|
-
if (!state) return;
|
|
2334
|
-
deps.enrichments.applyFromStateMessages(extractStateMessages(state));
|
|
2335
|
-
} catch (e) {
|
|
2336
|
-
console.warn("[runtime] citation state \u515C\u5E95\u63D0\u53D6\u5931\u8D25", e);
|
|
2337
|
-
}
|
|
2338
|
-
}
|
|
2339
|
-
async function runRuntimeInit(deps, hooks) {
|
|
2340
|
-
hooks.onStart();
|
|
2341
|
-
try {
|
|
2342
|
-
await bootstrapRuntime(deps);
|
|
2343
|
-
} finally {
|
|
2344
|
-
hooks.onEnd();
|
|
2345
|
-
}
|
|
2346
|
-
}
|
|
2347
|
-
|
|
2348
|
-
// src/protocol/values-channel.ts
|
|
2349
|
-
import { shallowRef as shallowRef2 } from "vue";
|
|
2350
|
-
import { extractInterrupts } from "@langchain/langgraph-sdk/ui";
|
|
2351
|
-
|
|
2352
|
-
// src/protocol/interrupt-reconcile.ts
|
|
2353
|
-
function reconcileInterrupts(prevValues, nextValues, firstEvent) {
|
|
2354
|
-
let base = prevValues;
|
|
2355
|
-
if (firstEvent && base && "__interrupt__" in base) {
|
|
2356
|
-
const { __interrupt__: _dropped, ...rest } = base;
|
|
2357
|
-
base = rest;
|
|
2358
|
-
}
|
|
2359
|
-
if (nextValues && typeof nextValues === "object" && "__interrupt__" in nextValues) {
|
|
2360
|
-
let interrupts = nextValues.__interrupt__;
|
|
2361
|
-
const prevInterrupts = base?.__interrupt__;
|
|
2362
|
-
if (Array.isArray(interrupts) && interrupts.length > 0 && Array.isArray(prevInterrupts)) {
|
|
2363
|
-
const merged = [...prevInterrupts];
|
|
2364
|
-
const existingIds = new Set(merged.map((i) => i?.id).filter((id) => id != null));
|
|
2365
|
-
for (const interrupt of interrupts) {
|
|
2366
|
-
const id = interrupt?.id;
|
|
2367
|
-
if (id != null) {
|
|
2368
|
-
if (existingIds.has(id)) continue;
|
|
2369
|
-
existingIds.add(id);
|
|
2370
|
-
}
|
|
2371
|
-
merged.push(interrupt);
|
|
2372
|
-
}
|
|
2373
|
-
interrupts = merged;
|
|
2374
|
-
}
|
|
2375
|
-
return { ...base, __interrupt__: interrupts };
|
|
2376
|
-
}
|
|
2377
|
-
if (nextValues && typeof nextValues === "object") {
|
|
2378
|
-
if (base && "__interrupt__" in base && Array.isArray(base.__interrupt__)) {
|
|
2379
|
-
return { ...nextValues, __interrupt__: base.__interrupt__ };
|
|
2380
|
-
}
|
|
2381
|
-
return nextValues;
|
|
2382
|
-
}
|
|
2383
|
-
return nextValues ?? {};
|
|
2384
|
-
}
|
|
2385
|
-
|
|
2386
|
-
// src/protocol/values-channel.ts
|
|
2387
|
-
function createValuesChannel(options = {}) {
|
|
2388
|
-
const valuesRef = shallowRef2({});
|
|
2389
|
-
const threadStateRef = shallowRef2(void 0);
|
|
2390
|
-
let firstEvent = true;
|
|
2391
|
-
let lastTitle = "";
|
|
2392
|
-
let latestStreamMessages = [];
|
|
2393
|
-
const readStateMessages = () => {
|
|
2394
|
-
const msgs = threadStateRef.value?.values?.messages;
|
|
2395
|
-
return Array.isArray(msgs) ? [...msgs] : [];
|
|
2396
|
-
};
|
|
2397
|
-
const readStreamMessages = () => [...latestStreamMessages];
|
|
2398
|
-
return {
|
|
2399
|
-
applyInitialValues(next) {
|
|
2400
|
-
valuesRef.value = { ...next ?? {} };
|
|
2401
|
-
},
|
|
2402
|
-
applyThreadState(state) {
|
|
2403
|
-
threadStateRef.value = state;
|
|
2404
|
-
},
|
|
2405
|
-
beginStream() {
|
|
2406
|
-
firstEvent = true;
|
|
2407
|
-
threadStateRef.value = void 0;
|
|
2408
|
-
latestStreamMessages = [];
|
|
2409
|
-
},
|
|
2410
|
-
applyValuesEvent(data) {
|
|
2411
|
-
const reconciled = reconcileInterrupts(valuesRef.value, data, firstEvent);
|
|
2412
|
-
firstEvent = false;
|
|
2413
|
-
valuesRef.value = reconciled;
|
|
2414
|
-
if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
|
|
2415
|
-
const title = String(reconciled?.title || "").trim();
|
|
2416
|
-
if (title && title !== lastTitle) {
|
|
2417
|
-
lastTitle = title;
|
|
2418
|
-
options.onTitle?.(title);
|
|
2419
|
-
}
|
|
2420
|
-
},
|
|
2421
|
-
getValues() {
|
|
2422
|
-
return valuesRef.value;
|
|
2423
|
-
},
|
|
2424
|
-
getStateMessages: readStateMessages,
|
|
2425
|
-
getStreamMessages: readStreamMessages,
|
|
2426
|
-
getInterrupt({ isLoading, error }) {
|
|
2427
|
-
return extractInterrupts(valuesRef.value, {
|
|
2428
|
-
isLoading,
|
|
2429
|
-
threadState: threadStateRef.value,
|
|
2430
|
-
error
|
|
2431
|
-
});
|
|
2432
|
-
}
|
|
2433
|
-
};
|
|
2434
|
-
}
|
|
2435
|
-
|
|
2436
|
-
// src/store/thread-state.ts
|
|
2437
|
-
import { ref as ref2, shallowReactive as shallowReactive2, shallowRef as shallowRef3 } from "vue";
|
|
2438
|
-
function createThreadStore(_options = {}) {
|
|
2439
|
-
const entities = /* @__PURE__ */ new Map();
|
|
2440
|
-
let order = [];
|
|
2441
|
-
let pageCountCache = -1;
|
|
2442
|
-
let cachedFlat = null;
|
|
2443
|
-
const version = ref2(0);
|
|
2444
|
-
const streamStatusRef = shallowRef3("idle");
|
|
2445
|
-
let streamEpoch = 0;
|
|
2446
|
-
const leadingPageCount = () => {
|
|
2447
|
-
let i = 0;
|
|
2448
|
-
while (i < order.length && entities.get(order[i])?.source === "page") i++;
|
|
2449
|
-
return i;
|
|
2450
|
-
};
|
|
2451
|
-
const lastPageIndex = () => {
|
|
2452
|
-
for (let i = order.length - 1; i >= 0; i--) {
|
|
2453
|
-
if (entities.get(order[i])?.source === "page") return i;
|
|
2454
|
-
}
|
|
2455
|
-
return -1;
|
|
2456
|
-
};
|
|
2457
|
-
const bump = () => {
|
|
2458
|
-
cachedFlat = null;
|
|
2459
|
-
pageCountCache = -1;
|
|
2460
|
-
version.value++;
|
|
2461
|
-
};
|
|
2462
|
-
const applyInstructions = (instructions) => {
|
|
2463
|
-
if (!instructions.length) return;
|
|
2464
|
-
let touched = false;
|
|
2465
|
-
for (const ins of instructions) {
|
|
2466
|
-
switch (ins.kind) {
|
|
2467
|
-
case "upsert": {
|
|
2468
|
-
const id = String(ins.message.id || "").trim();
|
|
2469
|
-
if (!id) break;
|
|
2470
|
-
const message = normalizeMessageType(ins.message);
|
|
2471
|
-
const existing = entities.get(id);
|
|
2472
|
-
if (existing) {
|
|
2473
|
-
existing.msg = message;
|
|
2474
|
-
existing.ver++;
|
|
2475
|
-
if (ins.source === "page") {
|
|
2476
|
-
existing.source = "page";
|
|
2477
|
-
} else {
|
|
2478
|
-
existing.source = "stream";
|
|
2479
|
-
existing.epoch = streamEpoch;
|
|
2480
|
-
}
|
|
2481
|
-
} else {
|
|
2482
|
-
entities.set(id, {
|
|
2483
|
-
msg: message,
|
|
2484
|
-
source: ins.source === "page" ? "page" : "stream",
|
|
2485
|
-
epoch: streamEpoch,
|
|
2486
|
-
ver: 1
|
|
2487
|
-
});
|
|
2488
|
-
if (ins.source === "page") {
|
|
2489
|
-
order.splice(lastPageIndex() + 1, 0, id);
|
|
2490
|
-
} else {
|
|
2491
|
-
order.push(id);
|
|
2492
|
-
}
|
|
2493
|
-
}
|
|
2494
|
-
touched = true;
|
|
2495
|
-
break;
|
|
2496
|
-
}
|
|
2497
|
-
case "remove": {
|
|
2498
|
-
if (!entities.has(ins.id)) break;
|
|
2499
|
-
const idx = order.indexOf(ins.id);
|
|
2500
|
-
if (idx >= 0) order.splice(idx, 1);
|
|
2501
|
-
entities.delete(ins.id);
|
|
2502
|
-
touched = true;
|
|
2503
|
-
break;
|
|
2504
|
-
}
|
|
2505
|
-
case "clear": {
|
|
2506
|
-
const removed = order.splice(leadingPageCount());
|
|
2507
|
-
for (const id of removed) entities.delete(id);
|
|
2508
|
-
touched = touched || removed.length > 0;
|
|
2509
|
-
break;
|
|
2510
|
-
}
|
|
2511
|
-
case "prepend": {
|
|
2512
|
-
const fresh = [];
|
|
2513
|
-
for (const msg of ins.messages) {
|
|
2514
|
-
const id = String(msg.id || "").trim();
|
|
2515
|
-
if (!id || entities.has(id)) continue;
|
|
2516
|
-
entities.set(id, {
|
|
2517
|
-
msg: normalizeMessageType(msg),
|
|
2518
|
-
source: "page",
|
|
2519
|
-
epoch: streamEpoch,
|
|
2520
|
-
ver: 1
|
|
2521
|
-
});
|
|
2522
|
-
fresh.push(id);
|
|
2523
|
-
}
|
|
2524
|
-
if (fresh.length) {
|
|
2525
|
-
order = [...fresh, ...order];
|
|
2526
|
-
touched = true;
|
|
2527
|
-
}
|
|
2528
|
-
break;
|
|
2529
|
-
}
|
|
2530
|
-
case "finalize": {
|
|
2531
|
-
if (streamStatusRef.value !== "settled") {
|
|
2532
|
-
streamStatusRef.value = "settled";
|
|
2533
|
-
touched = true;
|
|
2534
|
-
}
|
|
2535
|
-
break;
|
|
2536
|
-
}
|
|
2537
|
-
}
|
|
2538
|
-
}
|
|
2539
|
-
if (touched) bump();
|
|
2540
|
-
};
|
|
2541
|
-
return {
|
|
2542
|
-
applyInstructions,
|
|
2543
|
-
beginStream() {
|
|
2544
|
-
streamEpoch++;
|
|
2545
|
-
streamStatusRef.value = "streaming";
|
|
2546
|
-
bump();
|
|
2547
|
-
},
|
|
2548
|
-
getEntity: (id) => entities.get(id),
|
|
2549
|
-
get order() {
|
|
2550
|
-
return order;
|
|
2551
|
-
},
|
|
2552
|
-
get pageCount() {
|
|
2553
|
-
if (pageCountCache < 0) pageCountCache = leadingPageCount();
|
|
2554
|
-
return pageCountCache;
|
|
2555
|
-
},
|
|
2556
|
-
getMessages() {
|
|
2557
|
-
if (!cachedFlat) cachedFlat = order.map((id) => entities.get(id).msg);
|
|
2558
|
-
return cachedFlat;
|
|
2559
|
-
},
|
|
2560
|
-
get streamStatus() {
|
|
2561
|
-
return streamStatusRef.value;
|
|
2562
|
-
},
|
|
2563
|
-
get streamEpoch() {
|
|
2564
|
-
return streamEpoch;
|
|
2565
|
-
},
|
|
2566
|
-
version,
|
|
2567
|
-
streamStatusRef
|
|
2568
|
-
};
|
|
2569
|
-
}
|
|
2570
|
-
function readContentText(content) {
|
|
2571
|
-
if (typeof content === "string") return content;
|
|
2572
|
-
if (Array.isArray(content)) {
|
|
2573
|
-
return content.map((c) => c?.type === "text" ? String(c.text || "") : "").join("");
|
|
2574
|
-
}
|
|
2575
|
-
return "";
|
|
2576
|
-
}
|
|
2577
|
-
function isCitationCarrier(msg) {
|
|
2578
|
-
if (!isAiMessage(msg)) return false;
|
|
2579
|
-
return readContentText(asSxin(msg).content).includes("support.kbCitation");
|
|
2580
|
-
}
|
|
2581
|
-
function createEnrichments() {
|
|
2582
|
-
const citationPatches = shallowReactive2(/* @__PURE__ */ new Map());
|
|
2583
|
-
const answers = shallowReactive2(/* @__PURE__ */ new Map());
|
|
2584
|
-
let citationVersion = 0;
|
|
2585
|
-
return {
|
|
2586
|
-
get citationVersion() {
|
|
2587
|
-
return citationVersion;
|
|
2588
|
-
},
|
|
2589
|
-
applyFromStateMessages(messages) {
|
|
2590
|
-
for (const msg of messages) {
|
|
2591
|
-
const m = asSxin(msg);
|
|
2592
|
-
const id = String(m.id || "").trim();
|
|
2593
|
-
if (!id || !isCitationCarrier(msg)) continue;
|
|
2594
|
-
citationPatches.set(id, { content: m.content });
|
|
2595
|
-
citationVersion++;
|
|
2596
|
-
}
|
|
2597
|
-
const extracted = extractThreadInfo(messages).clarificationAnswers;
|
|
2598
|
-
for (const [key, value] of extracted) answers.set(key, value);
|
|
2599
|
-
},
|
|
2600
|
-
resolveCitation(messageId) {
|
|
2601
|
-
return citationPatches.get(messageId);
|
|
2602
|
-
},
|
|
2603
|
-
answers,
|
|
2604
|
-
setAnswer(requestId, answer) {
|
|
2605
|
-
answers.set(requestId, answer);
|
|
2606
|
-
},
|
|
2607
|
-
clearAnswers() {
|
|
2608
|
-
answers.clear();
|
|
2609
|
-
},
|
|
2610
|
-
dispose() {
|
|
2611
|
-
citationPatches.clear();
|
|
2612
|
-
answers.clear();
|
|
2613
|
-
}
|
|
2614
|
-
};
|
|
2615
|
-
}
|
|
2616
|
-
function createInterruptState() {
|
|
2617
|
-
const respondedIds = shallowRef3(/* @__PURE__ */ new Set());
|
|
2618
|
-
return {
|
|
2619
|
-
respondedIds,
|
|
2620
|
-
markResponded(id) {
|
|
2621
|
-
const next = new Set(respondedIds.value);
|
|
2622
|
-
next.add(id);
|
|
2623
|
-
respondedIds.value = next;
|
|
2624
|
-
},
|
|
2625
|
-
unmarkResponded(id) {
|
|
2626
|
-
if (!respondedIds.value.has(id)) return;
|
|
2627
|
-
const next = new Set(respondedIds.value);
|
|
2628
|
-
next.delete(id);
|
|
2629
|
-
respondedIds.value = next;
|
|
2630
|
-
}
|
|
2631
|
-
};
|
|
2632
|
-
}
|
|
2633
|
-
function createRunsStore(options) {
|
|
2634
|
-
const runsMap = shallowRef3(/* @__PURE__ */ new Map());
|
|
2635
|
-
const currentRunId = shallowRef3(null);
|
|
2636
|
-
return {
|
|
2637
|
-
runsMap,
|
|
2638
|
-
currentRunId,
|
|
2639
|
-
fillFromRunsList(runsList) {
|
|
2640
|
-
let next = null;
|
|
2641
|
-
for (const run of runsList) {
|
|
2642
|
-
const runId = String(run?.run_id || "").trim();
|
|
2643
|
-
if (!runId) continue;
|
|
2644
|
-
next ?? (next = new Map(runsMap.value));
|
|
2645
|
-
next.set(runId, buildRunInfo(run, options.threadId));
|
|
2646
|
-
}
|
|
2647
|
-
if (next) runsMap.value = next;
|
|
2648
|
-
},
|
|
2649
|
-
ensureRunning(runId) {
|
|
2650
|
-
if (runsMap.value.has(runId)) return;
|
|
2651
|
-
const next = new Map(runsMap.value);
|
|
2652
|
-
ensureRunningRun(next, runId, options.threadId);
|
|
2653
|
-
runsMap.value = next;
|
|
2654
|
-
},
|
|
2655
|
-
async refreshRuns() {
|
|
2656
|
-
try {
|
|
2657
|
-
const runsList = await options.transport.listRuns(options.threadId, 20);
|
|
2658
|
-
if (!Array.isArray(runsList)) return;
|
|
2659
|
-
const merged = new Map(runsMap.value);
|
|
2660
|
-
for (const run of runsList) {
|
|
2661
|
-
const runId = String(run.run_id || "").trim();
|
|
2662
|
-
if (!runId) continue;
|
|
2663
|
-
const info = buildRunInfo(run, options.threadId);
|
|
2664
|
-
const prev = merged.get(runId);
|
|
2665
|
-
if (!prev) {
|
|
2666
|
-
merged.set(runId, info);
|
|
2667
|
-
continue;
|
|
2668
|
-
}
|
|
2669
|
-
const directLatency = buildRunDirectLatencyMs(run);
|
|
2670
|
-
merged.set(runId, {
|
|
2671
|
-
...info,
|
|
2672
|
-
feedback: info.feedback ?? prev.feedback,
|
|
2673
|
-
latencyMs: directLatency ?? prev.latencyMs ?? info.latencyMs,
|
|
2674
|
-
modelName: info.modelName ?? prev.modelName,
|
|
2675
|
-
finishReason: info.finishReason ?? prev.finishReason
|
|
2676
|
-
});
|
|
2677
|
-
}
|
|
2678
|
-
runsMap.value = merged;
|
|
2679
|
-
} catch (e) {
|
|
2680
|
-
console.warn("[runs-store] refreshRuns failed", e);
|
|
2681
|
-
}
|
|
2682
|
-
},
|
|
2683
|
-
enrichFromPage(page) {
|
|
2684
|
-
const enrichment = extractRunEnrichment(page.messages);
|
|
2685
|
-
let next = null;
|
|
2686
|
-
for (const [runId, patch] of enrichment) {
|
|
2687
|
-
const run = (next ?? runsMap.value).get(runId);
|
|
2688
|
-
if (!run) continue;
|
|
2689
|
-
next ?? (next = new Map(runsMap.value));
|
|
2690
|
-
next.set(runId, {
|
|
2691
|
-
...run,
|
|
2692
|
-
...patch.feedback !== void 0 ? { feedback: patch.feedback } : {},
|
|
2693
|
-
...patch.latencyMs !== void 0 ? { latencyMs: patch.latencyMs } : {}
|
|
2694
|
-
});
|
|
2695
|
-
}
|
|
2696
|
-
if (next) runsMap.value = next;
|
|
2697
|
-
},
|
|
2698
|
-
backfillCurrentRunMetadata(getMessages) {
|
|
2699
|
-
const runId = currentRunId.value;
|
|
2700
|
-
if (!runId) return;
|
|
2701
|
-
const run = runsMap.value.get(runId);
|
|
2702
|
-
if (!run) return;
|
|
2703
|
-
if (run.modelName && run.finishReason) return;
|
|
2704
|
-
const currentRunMessages = getMessages().filter((m) => String(m?.runId || "") === runId);
|
|
2705
|
-
const source = currentRunMessages.length ? currentRunMessages : getMessages();
|
|
2706
|
-
const picked = pickRunMessageMetadata(source);
|
|
2707
|
-
if (!picked.modelName && !picked.finishReason) return;
|
|
2708
|
-
runsMap.value = new Map(runsMap.value).set(runId, {
|
|
2709
|
-
...run,
|
|
2710
|
-
...picked.modelName && !run.modelName ? { modelName: picked.modelName } : {},
|
|
2711
|
-
...picked.finishReason && !run.finishReason ? { finishReason: picked.finishReason } : {}
|
|
2712
|
-
});
|
|
2713
|
-
},
|
|
2714
|
-
patchRun(runId, patch) {
|
|
2715
|
-
const run = runsMap.value.get(runId);
|
|
2716
|
-
if (!run) return;
|
|
2717
|
-
runsMap.value = new Map(runsMap.value).set(runId, { ...run, ...patch });
|
|
2718
|
-
},
|
|
2719
|
-
dispose() {
|
|
2720
|
-
runsMap.value = /* @__PURE__ */ new Map();
|
|
2721
|
-
currentRunId.value = null;
|
|
2722
|
-
}
|
|
2723
|
-
};
|
|
2724
|
-
}
|
|
2725
|
-
|
|
2726
|
-
// src/runtime/derived-groups.ts
|
|
2727
|
-
import { computed as computed2, watch } from "vue";
|
|
2728
|
-
function createDerivedGroups(deps) {
|
|
2729
|
-
const deriver = createGroupDeriver(deps.state);
|
|
2730
|
-
const derived = computed2(() => {
|
|
2731
|
-
deps.store.version.value;
|
|
2732
|
-
return deriver.derive({
|
|
2733
|
-
store: deps.store,
|
|
2734
|
-
enrichments: deps.enrichments,
|
|
2735
|
-
getInterrupt: () => deps.valuesChannel.getInterrupt({ isLoading: deps.streamRef.value?.isLoading.value ?? false }),
|
|
2736
|
-
respondedIds: deps.interruptState.respondedIds.value,
|
|
2737
|
-
currentRunId: deps.runs.currentRunId.value ?? void 0,
|
|
2738
|
-
twin: deps.twin
|
|
2739
|
-
});
|
|
2740
|
-
});
|
|
2741
|
-
deps.scope.run(() => {
|
|
2742
|
-
watch(
|
|
2743
|
-
() => [deps.store.version.value, deps.runs.currentRunId.value],
|
|
2744
|
-
() => {
|
|
2745
|
-
deps.state.pruneExtras(derived.value.sourceGroups, deps.runs.currentRunId.value ?? void 0);
|
|
2746
|
-
},
|
|
2747
|
-
{ flush: "sync" }
|
|
2748
|
-
);
|
|
2749
|
-
});
|
|
2750
|
-
const groups = computed2(() => derived.value.groups);
|
|
2751
|
-
const sourceGroups = computed2(() => derived.value.sourceGroups);
|
|
2752
|
-
return { groups, sourceGroups };
|
|
2753
|
-
}
|
|
2754
|
-
|
|
2755
|
-
// src/runtime/thread-runtime.ts
|
|
2756
|
-
function createThreadRuntime(options) {
|
|
2757
|
-
const scope = effectScope();
|
|
2758
|
-
const store = createThreadStore({ threadId: options.threadId });
|
|
2759
|
-
const enrichments = createEnrichments();
|
|
2760
|
-
const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
|
|
2761
|
-
const interruptState = createInterruptState();
|
|
2762
|
-
const state = createViewModelState();
|
|
2763
|
-
const valuesChannel = createValuesChannel({
|
|
2764
|
-
onTitle: (title) => options.onTitle?.(options.threadId, title)
|
|
2765
|
-
});
|
|
2766
|
-
let chunkBuffer = null;
|
|
2767
|
-
const streamRef = shallowRef4(null);
|
|
2768
|
-
const isInitializing = ref3(false);
|
|
2769
|
-
const tokenUsage = shallowRef4(null);
|
|
2770
|
-
let initialized = false;
|
|
2771
|
-
let initPromise = null;
|
|
2772
|
-
let pager = null;
|
|
2773
|
-
const derivedGroups = createDerivedGroups({
|
|
2774
|
-
scope,
|
|
2775
|
-
store,
|
|
2776
|
-
enrichments,
|
|
2777
|
-
state,
|
|
2778
|
-
runs,
|
|
2779
|
-
interruptState,
|
|
2780
|
-
valuesChannel,
|
|
2781
|
-
streamRef,
|
|
2782
|
-
twin: options.twin
|
|
2783
|
-
});
|
|
2784
|
-
const { groups, sourceGroups } = derivedGroups;
|
|
2785
|
-
const interrupt = computed3(() => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }));
|
|
2786
|
-
const hasPendingInterrupt = computed3(() => {
|
|
2787
|
-
const it = interrupt.value;
|
|
2788
|
-
return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
|
|
2789
|
-
});
|
|
2790
|
-
const streamError = computed3(() => streamRef.value?.error.value ?? null);
|
|
2791
|
-
const isGenerating = computed3(() => store.streamStatusRef.value === "streaming");
|
|
2792
|
-
const hasPendingClarification = computed3(() => {
|
|
2793
|
-
store.version.value;
|
|
2794
|
-
const list = groups.value;
|
|
2795
|
-
return list.some((m, i) => {
|
|
2796
|
-
if (m.type !== "ai") return false;
|
|
2797
|
-
const hasUnanswered = m.blocks.some(
|
|
2798
|
-
(b) => isClarificationBlock(b) && !isClarificationAnswered(b, enrichments.answers)
|
|
2799
|
-
);
|
|
2800
|
-
if (!hasUnanswered) return false;
|
|
2801
|
-
return !list.slice(i + 1).some((x) => x.type === "human");
|
|
2802
|
-
});
|
|
2803
|
-
});
|
|
2804
|
-
const beginStream = () => {
|
|
2805
|
-
chunkBuffer?.reset();
|
|
2806
|
-
valuesChannel.beginStream();
|
|
2807
|
-
runs.currentRunId.value = null;
|
|
2808
|
-
};
|
|
2809
|
-
const streamStarted = () => {
|
|
2810
|
-
store.beginStream();
|
|
2811
|
-
};
|
|
2812
|
-
const markStreamRun = (runIdRaw) => {
|
|
2813
|
-
const runId = String(runIdRaw || "").trim();
|
|
2814
|
-
if (!runId) return;
|
|
2815
|
-
runs.currentRunId.value = runId;
|
|
2816
|
-
runs.ensureRunning(runId);
|
|
2817
|
-
chunkBuffer?.noteStreamRunId(runId);
|
|
2818
|
-
};
|
|
2819
|
-
const refreshTokenUsage = async () => {
|
|
2820
|
-
try {
|
|
2821
|
-
tokenUsage.value = await options.transport.fetchThreadTokenUsage(options.threadId);
|
|
2822
|
-
} catch (e) {
|
|
2823
|
-
console.warn("[runtime] refreshTokenUsage failed", e);
|
|
2824
|
-
}
|
|
2825
|
-
};
|
|
2826
|
-
const doInit = () => runRuntimeInit(
|
|
2827
|
-
{
|
|
2828
|
-
threadId: options.threadId,
|
|
2829
|
-
assistantId: options.assistantId,
|
|
2830
|
-
transport: options.transport,
|
|
2831
|
-
store,
|
|
2832
|
-
enrichments,
|
|
2833
|
-
runs,
|
|
2834
|
-
valuesChannel,
|
|
2835
|
-
streamRef,
|
|
2836
|
-
setChunkBuffer: (b) => chunkBuffer = b,
|
|
2837
|
-
getChunkBuffer: () => chunkBuffer,
|
|
2838
|
-
setPager: (p) => pager = p,
|
|
2839
|
-
setInitialized: () => initialized = true,
|
|
2840
|
-
markStreamRun,
|
|
2841
|
-
onStreamStart: streamStarted,
|
|
2842
|
-
refreshTokenUsage
|
|
2843
|
-
},
|
|
2844
|
-
{
|
|
2845
|
-
onStart: () => isInitializing.value = true,
|
|
2846
|
-
onEnd: () => isInitializing.value = false
|
|
2847
|
-
}
|
|
2848
|
-
);
|
|
2849
|
-
return {
|
|
2850
|
-
threadId: options.threadId,
|
|
2851
|
-
lastViewedAt: Date.now(),
|
|
2852
|
-
touch() {
|
|
2853
|
-
this.lastViewedAt = Date.now();
|
|
2854
|
-
},
|
|
2855
|
-
groups,
|
|
2856
|
-
isGenerating,
|
|
2857
|
-
isInitializing,
|
|
2858
|
-
runs: computed3(() => runs.runsMap.value),
|
|
2859
|
-
interrupt,
|
|
2860
|
-
hasPendingInterrupt,
|
|
2861
|
-
hasPendingClarification,
|
|
2862
|
-
streamError,
|
|
2863
|
-
tokenUsage,
|
|
2864
|
-
hasMoreHistory: computed3(() => pager?.hasMore.value ?? false),
|
|
2865
|
-
loadingHistory: computed3(() => pager?.loading.value ?? false),
|
|
2866
|
-
async init() {
|
|
2867
|
-
if (initialized) return;
|
|
2868
|
-
if (initPromise) return initPromise;
|
|
2869
|
-
initPromise = doInit();
|
|
2870
|
-
try {
|
|
2871
|
-
await initPromise;
|
|
2872
|
-
} finally {
|
|
2873
|
-
initPromise = null;
|
|
2874
|
-
}
|
|
2875
|
-
},
|
|
2876
|
-
submit(text, submitOptions) {
|
|
2877
|
-
const handle = streamRef.value;
|
|
2878
|
-
if (!handle) return;
|
|
2879
|
-
beginStream();
|
|
2880
|
-
const humanMessage = { type: "human", content: [{ type: "text", text }] };
|
|
2881
|
-
humanMessage.additional_kwargs = submitOptions?.kwargs;
|
|
2882
|
-
handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
|
|
2883
|
-
},
|
|
2884
|
-
async joinStream(runId, lastEventId) {
|
|
2885
|
-
const handle = streamRef.value;
|
|
2886
|
-
if (!handle) return;
|
|
2887
|
-
beginStream();
|
|
2888
|
-
markStreamRun(runId);
|
|
2889
|
-
await handle.joinStream(runId, lastEventId ?? "-1");
|
|
2890
|
-
},
|
|
2891
|
-
stop() {
|
|
2892
|
-
void options.transport.cancelRun(options.threadId, runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
|
|
2893
|
-
streamRef.value?.stop();
|
|
2894
|
-
},
|
|
2895
|
-
async resumeInterrupt(decisions) {
|
|
2896
|
-
const it = valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false });
|
|
2897
|
-
const interruptId = String(it?.id || "");
|
|
2898
|
-
if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
|
|
2899
|
-
const handle = streamRef.value;
|
|
2900
|
-
if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
|
|
2901
|
-
interruptState.markResponded(interruptId);
|
|
2902
|
-
beginStream();
|
|
2903
|
-
await handle.resumeInterrupt(decisions);
|
|
2904
|
-
},
|
|
2905
|
-
async loadOlderMessages() {
|
|
2906
|
-
if (!pager) return false;
|
|
2907
|
-
return pager.loadOlder();
|
|
2908
|
-
},
|
|
2909
|
-
appendOptimisticGroups(gs) {
|
|
2910
|
-
state.appendExtra(gs);
|
|
2911
|
-
},
|
|
2912
|
-
createOptimisticHuman(text, opts) {
|
|
2913
|
-
return createOptimisticHuman(text, opts);
|
|
2914
|
-
},
|
|
2915
|
-
patchGroup(messageId, patch) {
|
|
2916
|
-
state.patchGroup(messageId, patch, () => sourceGroups.value);
|
|
2917
|
-
},
|
|
2918
|
-
applyFeedback(messageId, feedback) {
|
|
2919
|
-
const runId = groups.value.find((g) => g.id === messageId)?.runId;
|
|
2920
|
-
state.patchGroup(messageId, { feedback }, () => sourceGroups.value);
|
|
2921
|
-
if (runId) runs.patchRun(runId, { feedback });
|
|
2922
|
-
},
|
|
2923
|
-
setClarificationAnswer(toolCallId, answer) {
|
|
2924
|
-
enrichments.setAnswer(toolCallId, answer);
|
|
2925
|
-
},
|
|
2926
|
-
clearClarificationAnswers() {
|
|
2927
|
-
enrichments.clearAnswers();
|
|
2928
|
-
},
|
|
2929
|
-
clarificationAnswers: computed3(() => enrichments.answers),
|
|
2930
|
-
dispose() {
|
|
2931
|
-
streamRef.value?.stop();
|
|
2932
|
-
chunkBuffer?.dispose();
|
|
2933
|
-
enrichments.dispose();
|
|
2934
|
-
runs.dispose();
|
|
2935
|
-
scope.stop();
|
|
2936
|
-
}
|
|
2937
|
-
};
|
|
2938
|
-
}
|
|
2939
|
-
|
|
2940
|
-
// src/runtime/thread-directory.ts
|
|
2941
|
-
import { ref as ref4, shallowReactive as shallowReactive3 } from "vue";
|
|
2942
|
-
var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending"]);
|
|
2943
|
-
function isActiveThreadStatus(status) {
|
|
2944
|
-
return typeof status === "string" && ACTIVE_THREAD_STATUSES.has(status);
|
|
2945
|
-
}
|
|
2946
|
-
var ThreadDirectory = class {
|
|
2947
|
-
constructor(options) {
|
|
2948
|
-
this.threads = ref4([]);
|
|
2949
|
-
this.threadsPagination = ref4({
|
|
2950
|
-
limit: 50,
|
|
2951
|
-
offset: 0,
|
|
2952
|
-
hasMore: true,
|
|
2953
|
-
isLoading: false
|
|
2954
|
-
});
|
|
2955
|
-
this.searchKeyword = "";
|
|
2956
|
-
/** 正在运行但已超出 SSE 连接上限的 thread(仅用于 UI 提示) */
|
|
2957
|
-
this.runningNotConnectedThreadIds = ref4(/* @__PURE__ */ new Set());
|
|
2958
|
-
/** 活跃 runtime 池(shallowReactive 追踪增删,runtime 实例不被深度代理) */
|
|
2959
|
-
this.cachedRuntimes = shallowReactive3(/* @__PURE__ */ new Map());
|
|
2960
|
-
this.transport = options.transport;
|
|
2961
|
-
this.assistantId = options.assistantId;
|
|
2962
|
-
this.maxCachedRuntimes = options.maxCachedRuntimes ?? DEFAULT_MAX_CACHED_SESSIONS;
|
|
2963
|
-
this.maxConcurrentStreams = options.maxConcurrentStreams ?? DEFAULT_MAX_CONCURRENT_STREAMS;
|
|
2964
|
-
this.twin = options.twin;
|
|
2965
|
-
this.notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
|
|
2966
|
-
this.defaultThreadTitle = options.defaultThreadTitle ?? "";
|
|
2967
|
-
}
|
|
2968
|
-
// ===== Thread 列表 =====
|
|
2969
|
-
/** 分页拉取历史 thread 列表(失败上抛由调用方提示,不再静默吞错——错误通道契约) */
|
|
2970
|
-
async fetchThreads(reset = false, keyword) {
|
|
2971
|
-
if (this.threadsPagination.value.isLoading) return;
|
|
2972
|
-
if (!reset && !this.threadsPagination.value.hasMore) return;
|
|
2973
|
-
if (keyword !== void 0) this.searchKeyword = keyword.trim();
|
|
2974
|
-
this.threadsPagination.value.isLoading = true;
|
|
2975
|
-
try {
|
|
2976
|
-
if (reset) {
|
|
2977
|
-
this.threads.value = [];
|
|
2978
|
-
this.threadsPagination.value.offset = 0;
|
|
2979
|
-
this.threadsPagination.value.hasMore = true;
|
|
2980
|
-
}
|
|
2981
|
-
const limit = this.threadsPagination.value.limit;
|
|
2982
|
-
const offset = this.threadsPagination.value.offset;
|
|
2983
|
-
const result = await this.transport.searchThreads({
|
|
2984
|
-
limit,
|
|
2985
|
-
offset,
|
|
2986
|
-
...this.searchKeyword ? { keyword: this.searchKeyword } : {}
|
|
2987
|
-
});
|
|
2988
|
-
const list = Array.isArray(result) ? result : [];
|
|
2989
|
-
this.threads.value = reset ? list : [...this.threads.value, ...list];
|
|
2990
|
-
if (list.length < limit) {
|
|
2991
|
-
this.threadsPagination.value.hasMore = false;
|
|
2992
|
-
} else {
|
|
2993
|
-
this.threadsPagination.value.offset = offset + list.length;
|
|
2994
|
-
}
|
|
2995
|
-
} finally {
|
|
2996
|
-
this.threadsPagination.value.isLoading = false;
|
|
2997
|
-
}
|
|
2998
|
-
}
|
|
2999
|
-
/** 创建新 thread(仅调 transport,不插入列表;确认可生成后由 prependThread 乐观插入) */
|
|
3000
|
-
async createThread(metadata) {
|
|
3001
|
-
try {
|
|
3002
|
-
return await this.transport.createThread(metadata);
|
|
3003
|
-
} catch (error) {
|
|
3004
|
-
console.error("[ThreadDirectory] create thread failed:", error);
|
|
3005
|
-
return null;
|
|
3006
|
-
}
|
|
3007
|
-
}
|
|
3008
|
-
/** 乐观插入列表顶部(已存在忽略;无标题给默认标题——默认文案属 UI 语义,经 notify 同源注入) */
|
|
3009
|
-
prependThread(thread) {
|
|
3010
|
-
if (!thread?.thread_id) return;
|
|
3011
|
-
if (this.threads.value.some((t) => t.thread_id === thread.thread_id)) return;
|
|
3012
|
-
const values = thread.values || {};
|
|
3013
|
-
const title = String(values.title || "").trim();
|
|
3014
|
-
const normalized = {
|
|
3015
|
-
...thread,
|
|
3016
|
-
values: title ? values : { ...values, title: this.defaultThreadTitle }
|
|
3017
|
-
};
|
|
3018
|
-
this.threads.value = [normalized, ...this.threads.value];
|
|
3019
|
-
}
|
|
3020
|
-
/** 本地更新标题(SSE 期间后端生成 title 后同步侧边栏) */
|
|
3021
|
-
updateThreadTitle(threadId, title) {
|
|
3022
|
-
const trimmed = String(title || "").trim();
|
|
3023
|
-
if (!trimmed) return;
|
|
3024
|
-
const idx = this.threads.value.findIndex((t) => t.thread_id === threadId);
|
|
3025
|
-
if (idx < 0) return;
|
|
3026
|
-
const thread = this.threads.value[idx];
|
|
3027
|
-
const currentTitle = String(thread.values?.title || "").trim();
|
|
3028
|
-
if (currentTitle === trimmed) return;
|
|
3029
|
-
this.threads.value[idx] = { ...thread, values: { ...thread.values, title: trimmed } };
|
|
3030
|
-
}
|
|
3031
|
-
/** 本地移除(不发请求;移动分组成功后同步历史列表) */
|
|
3032
|
-
removeThreadFromList(threadId) {
|
|
3033
|
-
const id = String(threadId || "").trim();
|
|
3034
|
-
if (!id) return;
|
|
3035
|
-
this.threads.value = this.threads.value.filter((t) => t.thread_id !== id);
|
|
3036
|
-
}
|
|
3037
|
-
/** 删除 thread(transport + 本地列表 + 活跃 runtime 清理) */
|
|
3038
|
-
async deleteThread(threadId) {
|
|
3039
|
-
const id = String(threadId || "").trim();
|
|
3040
|
-
if (!id) return false;
|
|
3041
|
-
try {
|
|
3042
|
-
await this.transport.deleteThread(id);
|
|
3043
|
-
this.threads.value = this.threads.value.filter((t) => t.thread_id !== id);
|
|
3044
|
-
this.releaseRuntime(id);
|
|
3045
|
-
return true;
|
|
3046
|
-
} catch (error) {
|
|
3047
|
-
console.error("[ThreadDirectory] delete thread failed:", error);
|
|
3048
|
-
return false;
|
|
3049
|
-
}
|
|
3050
|
-
}
|
|
3051
|
-
// ===== Runtime 池 =====
|
|
3052
|
-
/** 获取或创建 runtime(LRU;达上限时淘汰最久未查看的非生成中会话) */
|
|
3053
|
-
acquireRuntime(threadId) {
|
|
3054
|
-
const existing = this.cachedRuntimes.get(threadId);
|
|
3055
|
-
if (existing) return existing;
|
|
3056
|
-
if (this.cachedRuntimes.size >= this.maxCachedRuntimes) {
|
|
3057
|
-
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];
|
|
3058
|
-
if (!evictable) return "LIMIT_EXCEEDED";
|
|
3059
|
-
this.releaseRuntime(evictable[0]);
|
|
3060
|
-
}
|
|
3061
|
-
const runtime = createThreadRuntime({
|
|
3062
|
-
threadId,
|
|
3063
|
-
transport: this.transport,
|
|
3064
|
-
assistantId: this.assistantId,
|
|
3065
|
-
twin: this.twin,
|
|
3066
|
-
onTitle: (tid, title) => this.updateThreadTitle(tid, title)
|
|
3067
|
-
});
|
|
3068
|
-
this.cachedRuntimes.set(threadId, runtime);
|
|
3069
|
-
return runtime;
|
|
3070
|
-
}
|
|
3071
|
-
/** 释放指定 runtime(停止流并销毁) */
|
|
3072
|
-
releaseRuntime(threadId) {
|
|
3073
|
-
const runtime = this.cachedRuntimes.get(threadId);
|
|
3074
|
-
if (!runtime) return;
|
|
3075
|
-
runtime.dispose();
|
|
3076
|
-
this.cachedRuntimes.delete(threadId);
|
|
3077
|
-
}
|
|
3078
|
-
getRuntime(threadId) {
|
|
3079
|
-
return this.cachedRuntimes.get(threadId);
|
|
3080
|
-
}
|
|
3081
|
-
isThreadRunning(threadId) {
|
|
3082
|
-
return this.cachedRuntimes.get(threadId)?.isGenerating.value ?? false;
|
|
3083
|
-
}
|
|
3084
|
-
get activeCount() {
|
|
3085
|
-
return this.cachedRuntimes.size;
|
|
3086
|
-
}
|
|
3087
|
-
get generatingCount() {
|
|
3088
|
-
let count = 0;
|
|
3089
|
-
for (const rt of this.cachedRuntimes.values()) if (rt.isGenerating.value) count++;
|
|
3090
|
-
return count;
|
|
3091
|
-
}
|
|
3092
|
-
// ===== 刷新后恢复 =====
|
|
3093
|
-
/**
|
|
3094
|
-
* 恢复 running run 的 SSE:在已加载列表里过滤活跃线程 → listRuns 确认 → init + joinStream。
|
|
3095
|
-
* interrupted 线程不恢复(打开时经 init 恢复 interrupt 卡片)。并行确认,串行连接(并发上限内)。
|
|
3096
|
-
*/
|
|
3097
|
-
async recoverRunningThreads() {
|
|
3098
|
-
const activeThreads = this.threads.value.filter((t) => isActiveThreadStatus(t.status) && t.thread_id);
|
|
3099
|
-
const results = await Promise.all(
|
|
3100
|
-
activeThreads.map(async (thread) => {
|
|
3101
|
-
try {
|
|
3102
|
-
const runs = await this.transport.listRuns(thread.thread_id, 5);
|
|
3103
|
-
const running = Array.isArray(runs) ? runs.find((r) => r.status === "running" || r.status === "pending") : void 0;
|
|
3104
|
-
return running ? { threadId: thread.thread_id, runId: String(running.run_id) } : null;
|
|
3105
|
-
} catch (e) {
|
|
3106
|
-
console.warn("[ThreadDirectory] check running run failed", e);
|
|
3107
|
-
return null;
|
|
3108
|
-
}
|
|
3109
|
-
})
|
|
3110
|
-
);
|
|
3111
|
-
const runningInfos = results.filter((r) => !!r);
|
|
3112
|
-
const connected = /* @__PURE__ */ new Set();
|
|
3113
|
-
for (const info of runningInfos.slice(0, this.maxConcurrentStreams)) {
|
|
3114
|
-
const rt = this.acquireRuntime(info.threadId);
|
|
3115
|
-
if (rt === "LIMIT_EXCEEDED") break;
|
|
3116
|
-
try {
|
|
3117
|
-
rt.touch();
|
|
3118
|
-
await rt.init();
|
|
3119
|
-
await rt.joinStream(info.runId, "-1");
|
|
3120
|
-
connected.add(info.threadId);
|
|
3121
|
-
} catch (e) {
|
|
3122
|
-
console.warn("[ThreadDirectory] recover running thread failed", info.threadId, e);
|
|
3123
|
-
}
|
|
3124
|
-
}
|
|
3125
|
-
this.runningNotConnectedThreadIds.value = new Set(
|
|
3126
|
-
runningInfos.filter((i) => !connected.has(i.threadId)).map((i) => i.threadId)
|
|
3127
|
-
);
|
|
3128
|
-
}
|
|
3129
|
-
dispose() {
|
|
3130
|
-
for (const runtime of this.cachedRuntimes.values()) runtime.dispose();
|
|
3131
|
-
this.cachedRuntimes.clear();
|
|
3132
|
-
}
|
|
3133
|
-
};
|
|
3134
|
-
|
|
3135
|
-
// src/core/ChatCore.ts
|
|
3136
|
-
import { computed as computed4, ref as ref5 } from "vue";
|
|
3137
|
-
function createChatCore(options) {
|
|
3138
|
-
const notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
|
|
3139
|
-
const directory = new ThreadDirectory({
|
|
3140
|
-
transport: options.transport,
|
|
3141
|
-
assistantId: options.assistantId || "lead_agent",
|
|
3142
|
-
maxCachedRuntimes: options.maxCachedSessions,
|
|
3143
|
-
maxConcurrentStreams: options.maxConcurrentStreams,
|
|
3144
|
-
twin: options.twin,
|
|
3145
|
-
notify,
|
|
3146
|
-
defaultThreadTitle: options.defaultThreadTitle
|
|
3147
|
-
});
|
|
3148
|
-
const currentThreadId = ref5(null);
|
|
3149
|
-
const threads = computed4(() => directory.threads.value);
|
|
3150
|
-
const threadsPagination = computed4(() => directory.threadsPagination.value);
|
|
3151
|
-
const activeRuntime = computed4(
|
|
3152
|
-
() => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
|
|
3153
|
-
);
|
|
3154
|
-
const messages = computed4(() => activeRuntime.value?.groups.value ?? []);
|
|
3155
|
-
const isGenerating = computed4(
|
|
3156
|
-
() => !!activeRuntime.value && (activeRuntime.value.isGenerating.value || activeRuntime.value.isInitializing.value)
|
|
3157
|
-
);
|
|
3158
|
-
const isLoadingThread = computed4(() => activeRuntime.value?.isInitializing.value ?? false);
|
|
3159
|
-
const runs = computed4(
|
|
3160
|
-
() => activeRuntime.value?.runs.value ?? /* @__PURE__ */ new Map()
|
|
3161
|
-
);
|
|
3162
|
-
const toolCalls = computed4(() => messages.value.flatMap((g) => g.tools));
|
|
3163
|
-
const clarificationAnswers = computed4(
|
|
3164
|
-
() => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
|
|
3165
|
-
);
|
|
3166
|
-
const activeInterrupt = computed4(() => activeRuntime.value?.interrupt.value);
|
|
3167
|
-
const hasPendingInterrupt = computed4(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
|
|
3168
|
-
const hasPendingClarification = computed4(() => activeRuntime.value?.hasPendingClarification.value ?? false);
|
|
3169
|
-
const inputDisabled = computed4(
|
|
3170
|
-
() => isGenerating.value || hasPendingClarification.value || hasPendingInterrupt.value
|
|
3171
|
-
);
|
|
3172
|
-
const streamError = computed4(() => activeRuntime.value?.streamError.value ?? null);
|
|
3173
|
-
const hasMoreHistory = computed4(() => activeRuntime.value?.hasMoreHistory.value ?? false);
|
|
3174
|
-
const loadingHistory = computed4(() => activeRuntime.value?.loadingHistory.value ?? false);
|
|
3175
|
-
const tokenUsage = computed4(() => activeRuntime.value?.tokenUsage.value ?? null);
|
|
3176
|
-
const runningNotConnectedThreadIds = computed4(() => directory.runningNotConnectedThreadIds.value);
|
|
3177
|
-
const getRunById = (runId) => runId ? runs.value.get(runId) : void 0;
|
|
3178
|
-
const getRunsByThreadId = (threadId) => threadId ? Array.from(runs.value.values()).filter((r) => r.threadId === threadId) : [];
|
|
3179
|
-
const ensureThreadId = async () => {
|
|
3180
|
-
if (currentThreadId.value) return { threadId: currentThreadId.value, isNew: false, thread: null };
|
|
3181
|
-
const thread = await directory.createThread({ source: "chat" });
|
|
3182
|
-
if (thread?.thread_id) currentThreadId.value = thread.thread_id;
|
|
3183
|
-
return thread?.thread_id ? { threadId: thread.thread_id, isNew: true, thread } : null;
|
|
3184
|
-
};
|
|
3185
|
-
const acquireSendRuntime = (threadId) => {
|
|
3186
|
-
const current = directory.getRuntime(threadId);
|
|
3187
|
-
if (!current?.isGenerating.value && directory.generatingCount >= directory.maxConcurrentStreams) {
|
|
3188
|
-
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`);
|
|
3189
|
-
return null;
|
|
3190
|
-
}
|
|
3191
|
-
if (current) return current;
|
|
3192
|
-
const result = directory.acquireRuntime(threadId);
|
|
3193
|
-
if (result === "LIMIT_EXCEEDED") {
|
|
3194
|
-
notify("warning", "\u751F\u6210\u4E2D\u7684\u5BF9\u8BDD\u8FC7\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
|
|
3195
|
-
return null;
|
|
3196
|
-
}
|
|
3197
|
-
return result;
|
|
3198
|
-
};
|
|
3199
|
-
const sendMessage = async (text, sendOptions) => {
|
|
3200
|
-
if (isGenerating.value) return;
|
|
3201
|
-
const trimmed = String(text || "").trim();
|
|
3202
|
-
if (!trimmed) return;
|
|
3203
|
-
const info = await ensureThreadId();
|
|
3204
|
-
if (!info) return;
|
|
3205
|
-
const { threadId, isNew, thread } = info;
|
|
3206
|
-
if (runningNotConnectedThreadIds.value.has(threadId)) {
|
|
3207
|
-
notify("warning", "\u8BE5\u5BF9\u8BDD\u6B63\u5728\u751F\u6210\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210\u540E\u518D\u53D1\u9001");
|
|
3208
|
-
return;
|
|
3209
|
-
}
|
|
3210
|
-
const runtime = acquireSendRuntime(threadId);
|
|
3211
|
-
if (!runtime) return;
|
|
3212
|
-
runtime.touch();
|
|
3213
|
-
if (isNew && thread) directory.prependThread(thread);
|
|
3214
|
-
await runtime.init();
|
|
3215
|
-
const optimistic = runtime.createOptimisticHuman(trimmed, sendOptions);
|
|
3216
|
-
runtime.appendOptimisticGroups([optimistic]);
|
|
3217
|
-
runtime.submit(trimmed, sendOptions);
|
|
3218
|
-
};
|
|
3219
|
-
const loadThread = async (threadId) => {
|
|
3220
|
-
const result = directory.acquireRuntime(threadId);
|
|
3221
|
-
if (result === "LIMIT_EXCEEDED") {
|
|
3222
|
-
notify("warning", "\u751F\u6210\u4E2D\u7684\u5BF9\u8BDD\u8FC7\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
|
|
3223
|
-
return;
|
|
3224
|
-
}
|
|
3225
|
-
currentThreadId.value = threadId;
|
|
3226
|
-
result.touch();
|
|
3227
|
-
await result.init();
|
|
3228
|
-
};
|
|
3229
|
-
const regenerate = async (assistantMessageId) => {
|
|
3230
|
-
if (isGenerating.value) return;
|
|
3231
|
-
const list = messages.value;
|
|
3232
|
-
const idx = list.findIndex((m) => m.id === assistantMessageId);
|
|
3233
|
-
if (idx < 0) return;
|
|
3234
|
-
let question;
|
|
3235
|
-
let text = "";
|
|
3236
|
-
for (const m of list.slice(0, idx).reverse()) {
|
|
3237
|
-
if (m.type !== "human") continue;
|
|
3238
|
-
const [t] = m.texts ?? [];
|
|
3239
|
-
if (t) {
|
|
3240
|
-
question = m;
|
|
3241
|
-
text = t;
|
|
3242
|
-
break;
|
|
3243
|
-
}
|
|
3244
|
-
}
|
|
3245
|
-
if (!text) {
|
|
3246
|
-
notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
|
|
3247
|
-
return;
|
|
3248
|
-
}
|
|
3249
|
-
await sendMessage(text, { kwargs: { ...question?.additionalKwargs, hide_from_ui: false } });
|
|
3250
|
-
};
|
|
3251
|
-
return {
|
|
3252
|
-
messages,
|
|
3253
|
-
groupMessages: messages,
|
|
3254
|
-
isGenerating,
|
|
3255
|
-
isLoadingThread,
|
|
3256
|
-
currentThreadId,
|
|
3257
|
-
threads,
|
|
3258
|
-
threadsPagination,
|
|
3259
|
-
runs,
|
|
3260
|
-
toolCalls,
|
|
3261
|
-
getRunById,
|
|
3262
|
-
getRunsByThreadId,
|
|
3263
|
-
clarificationAnswers,
|
|
3264
|
-
setClarificationAnswer: (toolCallId, answer) => activeRuntime.value?.setClarificationAnswer(toolCallId, answer),
|
|
3265
|
-
clearClarificationAnswers: () => activeRuntime.value?.clearClarificationAnswers(),
|
|
3266
|
-
sendMessage,
|
|
3267
|
-
loadThread,
|
|
3268
|
-
stopGeneration: () => activeRuntime.value?.stop(),
|
|
3269
|
-
clearMessages: () => {
|
|
3270
|
-
currentThreadId.value = null;
|
|
3271
|
-
},
|
|
3272
|
-
updateGroupMessage: (messageId, patch) => activeRuntime.value?.patchGroup(messageId, patch),
|
|
3273
|
-
addOptimisticGroupMessages: (ms) => activeRuntime.value?.appendOptimisticGroups(ms),
|
|
3274
|
-
updateGroupMessageBlocks: (messageId, blocks) => activeRuntime.value?.patchGroup(messageId, { blocks }),
|
|
3275
|
-
applyFeedback: (messageId, feedback) => activeRuntime.value?.applyFeedback(messageId, feedback),
|
|
3276
|
-
regenerate,
|
|
3277
|
-
fetchThreads: (reset, keyword) => directory.fetchThreads(reset, keyword),
|
|
3278
|
-
deleteThread: async (threadId) => {
|
|
3279
|
-
const deleted = await directory.deleteThread(threadId);
|
|
3280
|
-
if (deleted && currentThreadId.value === threadId) currentThreadId.value = null;
|
|
3281
|
-
return deleted;
|
|
3282
|
-
},
|
|
3283
|
-
updateThreadTitle: (threadId, title) => directory.updateThreadTitle(threadId, title),
|
|
3284
|
-
removeThreadFromList: (threadId) => directory.removeThreadFromList(threadId),
|
|
3285
|
-
isThreadRunning: (threadId) => directory.isThreadRunning(threadId),
|
|
3286
|
-
runningNotConnectedThreadIds,
|
|
3287
|
-
recoverRunningThreads: () => directory.recoverRunningThreads(),
|
|
3288
|
-
activeInterrupt,
|
|
3289
|
-
hasPendingInterrupt,
|
|
3290
|
-
hasPendingClarification,
|
|
3291
|
-
inputDisabled,
|
|
3292
|
-
streamError,
|
|
3293
|
-
hasMoreHistory,
|
|
3294
|
-
loadingHistory,
|
|
3295
|
-
tokenUsage,
|
|
3296
|
-
loadOlderMessages: async () => await activeRuntime.value?.loadOlderMessages() ?? false,
|
|
3297
|
-
resumeInterrupt: async (decisions) => {
|
|
3298
|
-
const runtime = activeRuntime.value;
|
|
3299
|
-
if (!runtime) throw new Error("\u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u7684\u4F1A\u8BDD");
|
|
3300
|
-
await runtime.resumeInterrupt(decisions);
|
|
3301
|
-
},
|
|
3302
|
-
loadArtifactContent: async (path) => {
|
|
3303
|
-
const threadId = currentThreadId.value;
|
|
3304
|
-
if (!threadId || !activeRuntime.value) throw new Error("\u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u7684\u4F1A\u8BDD\uFF0C\u65E0\u6CD5\u52A0\u8F7D artifact \u5185\u5BB9");
|
|
3305
|
-
return options.transport.fetchArtifactContent(threadId, path, { full: true });
|
|
3306
|
-
},
|
|
3307
|
-
dispose: () => directory.dispose()
|
|
3308
|
-
};
|
|
3309
|
-
}
|
|
3310
|
-
|
|
3311
|
-
export {
|
|
3312
|
-
DEFAULT_MAX_CACHED_SESSIONS,
|
|
3313
|
-
DEFAULT_MAX_CONCURRENT_STREAMS,
|
|
3314
|
-
DEFAULT_ASSISTANT_ID,
|
|
3315
|
-
formatStr,
|
|
3316
|
-
INJECTED_TAGS,
|
|
3317
|
-
isInjectedElement,
|
|
3318
|
-
collectVisibleText,
|
|
3319
|
-
collectTextKeepSxin,
|
|
3320
|
-
tokenizeSxin,
|
|
3321
|
-
extractCitationAnchorsFromSpec,
|
|
3322
|
-
extractCitationAnchors,
|
|
3323
|
-
parseKnowledgeItemsFromValue,
|
|
3324
|
-
genMessageId,
|
|
3325
|
-
genBlockId,
|
|
3326
|
-
parseHitlPayload,
|
|
3327
|
-
getAllowedDecisions,
|
|
3328
|
-
normalizeForCompare,
|
|
3329
|
-
isSameArgs,
|
|
3330
|
-
buildHitlDecisions,
|
|
3331
|
-
buildRejectDecisions,
|
|
3332
|
-
buildInterruptReviewBlock,
|
|
3333
|
-
buildInterruptReviewGroup,
|
|
3334
|
-
extractThreadInfo,
|
|
3335
|
-
buildHumanInputResponse,
|
|
3336
|
-
extractStateMessages,
|
|
3337
|
-
ensureRunningRun,
|
|
3338
|
-
MESSAGE_TYPE_NORMALIZE,
|
|
3339
|
-
normalizeMessageType,
|
|
3340
|
-
toRunMessage,
|
|
3341
|
-
extractRunEnrichment,
|
|
3342
|
-
runMessagesToMessages,
|
|
3343
|
-
stateMessagesToRunMessages,
|
|
3344
|
-
simpleHash,
|
|
3345
|
-
readMessageContentText,
|
|
3346
|
-
extractTextFromMessage,
|
|
3347
|
-
extractAiContentFromMessage,
|
|
3348
|
-
isVisibleUserMessage,
|
|
3349
|
-
extractUserMessageTexts,
|
|
3350
|
-
isHiddenUserMessage,
|
|
3351
|
-
isWriteFileToolName,
|
|
3352
|
-
getToolCallArtifactMeta,
|
|
3353
|
-
resolveReportArtifactKind,
|
|
3354
|
-
extractTitleFromArtifactPath,
|
|
3355
|
-
OUTLINE_MAX_LEVEL,
|
|
3356
|
-
normalizeOutline,
|
|
3357
|
-
validateOutline,
|
|
3358
|
-
createEmptySubChapter,
|
|
3359
|
-
ensureOutlineContentThemes,
|
|
3360
|
-
parseMarkdownToOutline,
|
|
3361
|
-
isReportBodyHtml,
|
|
3362
|
-
extractReportTitleFromBody,
|
|
3363
|
-
buildArtifactFiles,
|
|
3364
|
-
buildReportOutlinePayload,
|
|
3365
|
-
buildReportBodyPayload,
|
|
3366
|
-
extractBlocksFromNodes,
|
|
3367
|
-
extractBlocksFromContent,
|
|
3368
|
-
isHumanMessage,
|
|
3369
|
-
parseHumanMessageId,
|
|
3370
|
-
getHumanMessageBaseId,
|
|
3371
|
-
isAiMessage,
|
|
3372
|
-
isToolMessage,
|
|
3373
|
-
deriveToolsFromMessages,
|
|
3374
|
-
normalizeUsage,
|
|
3375
|
-
buildRunInfo,
|
|
3376
|
-
buildRunDirectLatencyMs,
|
|
3377
|
-
pickRunMessageMetadata,
|
|
3378
|
-
DEFAULT_TWIN_TOOL_PREFIX,
|
|
3379
|
-
createBlockBuilderLite,
|
|
3380
|
-
foldMessages,
|
|
3381
|
-
buildHumanGroup,
|
|
3382
|
-
buildAiGroup,
|
|
3383
|
-
isClarificationAnswered,
|
|
3384
|
-
isClarificationBlock,
|
|
3385
|
-
createViewModelState,
|
|
3386
|
-
createGroupDeriver,
|
|
3387
|
-
createOptimisticHuman,
|
|
3388
|
-
createThreadRuntime,
|
|
3389
|
-
ThreadDirectory,
|
|
3390
|
-
createChatCore
|
|
3391
|
-
};
|