@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.
@@ -0,0 +1,2661 @@
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/message-id.ts
321
+ var _idSeq = 0;
322
+ function genMessageId() {
323
+ return `msg-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
324
+ }
325
+ function genBlockId() {
326
+ return `block-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
327
+ }
328
+
329
+ // src/parser/hitl.ts
330
+ import { isEqual } from "lodash";
331
+ function parseHitlPayload(value) {
332
+ if (!value || typeof value !== "object") return null;
333
+ const raw = value;
334
+ const requests = raw.actionRequests ?? raw.action_requests;
335
+ if (!Array.isArray(requests) || !requests.length) return null;
336
+ const configs = raw.reviewConfigs ?? raw.review_configs;
337
+ return {
338
+ actionRequests: requests,
339
+ reviewConfigs: Array.isArray(configs) ? configs : []
340
+ };
341
+ }
342
+ function getAllowedDecisions(configs, actionName) {
343
+ const cfg = configs.find((c) => c.action_name === actionName);
344
+ const list = cfg?.allowedDecisions ?? cfg?.allowed_decisions;
345
+ return list?.length ? list : ["approve", "reject"];
346
+ }
347
+ function normalizeForCompare(value) {
348
+ if (Array.isArray(value)) return value.map(normalizeForCompare);
349
+ if (value && typeof value === "object") {
350
+ return Object.keys(value).sort().reduce((acc, key) => {
351
+ acc[key] = normalizeForCompare(value[key]);
352
+ return acc;
353
+ }, {});
354
+ }
355
+ return value;
356
+ }
357
+ function isSameArgs(a, b) {
358
+ return isEqual(normalizeForCompare(a), normalizeForCompare(b));
359
+ }
360
+ function buildHitlDecisions(requests, currentArgsList) {
361
+ return requests.map((req, i) => {
362
+ const current = currentArgsList[i];
363
+ if (!current || isSameArgs(req.args, current)) return { type: "approve" };
364
+ return { type: "edit", edited_action: { name: req.name, args: current } };
365
+ });
366
+ }
367
+ function buildRejectDecisions(requests) {
368
+ return requests.map(() => ({ type: "reject" }));
369
+ }
370
+ function buildInterruptReviewBlock(interrupt, responded) {
371
+ const payload = parseHitlPayload(interrupt.value);
372
+ if (!payload) return null;
373
+ const interruptId = String(interrupt.id || genMessageId());
374
+ const status = responded ? "completed" : "pending";
375
+ return {
376
+ id: `interrupt-review-${interruptId}`,
377
+ type: "interrupt-review",
378
+ status,
379
+ payload,
380
+ interruptId
381
+ };
382
+ }
383
+
384
+ // src/parser/thread-info.ts
385
+ function formatAnswerText(value) {
386
+ if (value == null) return "";
387
+ if (typeof value === "string") return value;
388
+ if (typeof value === "object") {
389
+ const values = value.values;
390
+ if (values && typeof values === "object" && !Array.isArray(values)) {
391
+ return Object.values(values).filter((v) => v !== void 0 && v !== null && v !== "").map(String).join("; ");
392
+ }
393
+ try {
394
+ return JSON.stringify(value);
395
+ } catch {
396
+ return String(value);
397
+ }
398
+ }
399
+ return String(value);
400
+ }
401
+ var humanInputResponseRule = {
402
+ key: "clarificationAnswers",
403
+ extract(msg, acc) {
404
+ const additionalKwargs = msg?.additional_kwargs;
405
+ const response = additionalKwargs?.human_input_response;
406
+ const requestId = String(response?.request_id || "").trim().replace("clarification:", "");
407
+ if (requestId && response?.value !== void 0) {
408
+ acc.clarificationAnswers.set(requestId, formatAnswerText(response.value));
409
+ }
410
+ }
411
+ };
412
+ var THREAD_INFO_RULES = [humanInputResponseRule];
413
+ function extractThreadInfo(messages) {
414
+ const info = { clarificationAnswers: /* @__PURE__ */ new Map() };
415
+ for (const msg of messages ?? []) {
416
+ for (const rule of THREAD_INFO_RULES) {
417
+ rule.extract(msg, info);
418
+ }
419
+ }
420
+ return info;
421
+ }
422
+ function buildHumanInputResponse(requestId, options) {
423
+ return {
424
+ hide_from_ui: true,
425
+ human_input_response: {
426
+ version: 1,
427
+ kind: "human_input_response",
428
+ source: options.source,
429
+ request_id: requestId,
430
+ response_kind: options.responseKind,
431
+ value: options.value
432
+ }
433
+ };
434
+ }
435
+
436
+ // src/parser/thread.ts
437
+ function extractStateMessages(state) {
438
+ if (!state || typeof state !== "object") return [];
439
+ const values = state.values;
440
+ if (!values || typeof values !== "object") return [];
441
+ const messages = values.messages;
442
+ return Array.isArray(messages) ? messages : [];
443
+ }
444
+ function mergeStateWithPageMessages(stateMessages, pageMessages) {
445
+ if (!pageMessages.length) return stateMessages;
446
+ if (!stateMessages.length) return pageMessages;
447
+ const locateId = (m) => String(m?.id || m?.tool_call_id || "").trim();
448
+ const pageIndex = /* @__PURE__ */ new Map();
449
+ pageMessages.forEach((m, i) => {
450
+ const id = locateId(m);
451
+ if (id && !pageIndex.has(id)) pageIndex.set(id, i);
452
+ });
453
+ let anchorSi = -1;
454
+ let anchorPi = -1;
455
+ for (let si = 0; si < stateMessages.length; si++) {
456
+ const id = locateId(stateMessages[si]);
457
+ const pi = id ? pageIndex.get(id) : void 0;
458
+ if (pi !== void 0) {
459
+ anchorSi = si;
460
+ anchorPi = pi;
461
+ break;
462
+ }
463
+ }
464
+ if (anchorSi < 0) return pageMessages;
465
+ const stateIds = /* @__PURE__ */ new Set();
466
+ for (const m of stateMessages) {
467
+ const id = String(m?.id || "").trim();
468
+ const callId = String(m?.tool_call_id || "").trim();
469
+ if (id) stateIds.add(id);
470
+ if (callId) stateIds.add(callId);
471
+ }
472
+ const headExtras = [];
473
+ for (let pi = 0; pi < anchorPi; pi++) {
474
+ const m = pageMessages[pi];
475
+ const id = locateId(m);
476
+ if (id && !stateIds.has(id)) headExtras.push(m);
477
+ }
478
+ const tailExtras = [];
479
+ for (let pi = anchorPi + 1; pi < pageMessages.length; pi++) {
480
+ const m = pageMessages[pi];
481
+ const id = locateId(m);
482
+ if (id && !stateIds.has(id)) tailExtras.push(m);
483
+ }
484
+ const runIdById = /* @__PURE__ */ new Map();
485
+ for (const m of pageMessages) {
486
+ const id = String(m?.id || "").trim();
487
+ const rid = String(m?.runId || "").trim();
488
+ if (id && rid && !runIdById.has(id)) runIdById.set(id, rid);
489
+ }
490
+ const stampRunId = (m) => {
491
+ const id = String(m?.id || "").trim();
492
+ if (!id) return m;
493
+ const rid = runIdById.get(id);
494
+ if (!rid) return m;
495
+ if (String(m?.runId || "").trim() || String(m?.additional_kwargs?.run_id || "").trim()) return m;
496
+ return { ...m, runId: rid };
497
+ };
498
+ return [...headExtras, ...stateMessages.map(stampRunId), ...tailExtras];
499
+ }
500
+ function ensureRunningRun(runMap, runId, threadId) {
501
+ let runInfo = runMap.get(runId);
502
+ if (!runInfo) {
503
+ runInfo = {
504
+ runId,
505
+ threadId: threadId || "",
506
+ status: "running"
507
+ };
508
+ runMap.set(runId, runInfo);
509
+ }
510
+ return runInfo;
511
+ }
512
+
513
+ // src/parser/sxin-message.ts
514
+ var asSxin = (m) => m ?? {};
515
+
516
+ // src/parser/run-messages.ts
517
+ var MESSAGE_TYPE_NORMALIZE = {
518
+ AIMessage: "ai",
519
+ AIMessageChunk: "ai",
520
+ HumanMessage: "human",
521
+ HumanMessageChunk: "human",
522
+ ToolMessage: "tool",
523
+ ToolMessageChunk: "tool",
524
+ SystemMessage: "system",
525
+ SystemMessageChunk: "system",
526
+ assistant: "ai",
527
+ user: "human"
528
+ };
529
+ function normalizeMessageType(message) {
530
+ const raw = String(asSxin(message).type || "").trim();
531
+ const normalized = MESSAGE_TYPE_NORMALIZE[raw];
532
+ if (normalized && normalized !== raw) {
533
+ return { ...asSxin(message), type: normalized };
534
+ }
535
+ return message;
536
+ }
537
+ function parseCreatedAt(value) {
538
+ if (value === null || value === void 0 || value === "") return void 0;
539
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
540
+ if (typeof value !== "string") return void 0;
541
+ const text = value.trim();
542
+ if (!text) return void 0;
543
+ if (/^\d+$/.test(text)) {
544
+ const ms2 = Number(text);
545
+ return Number.isFinite(ms2) ? ms2 : void 0;
546
+ }
547
+ const ms = Date.parse(text);
548
+ return Number.isFinite(ms) ? ms : void 0;
549
+ }
550
+ function toRunMessage(raw) {
551
+ if (!raw || typeof raw !== "object") return null;
552
+ const content = raw.content;
553
+ if (!content || typeof content !== "object" || Array.isArray(content)) return null;
554
+ if (!String(content.type || "").trim()) return null;
555
+ const seq = Number(raw.seq ?? 0);
556
+ if (!Number.isFinite(seq)) return null;
557
+ const createdAt = parseCreatedAt(raw.created_at);
558
+ return {
559
+ runId: String(raw.run_id ?? ""),
560
+ seq,
561
+ eventType: String(raw.event_type ?? ""),
562
+ ...createdAt !== void 0 ? { createdAt } : {},
563
+ // feedback 可选:非空才映射
564
+ ...raw.feedback !== void 0 && raw.feedback !== null ? { feedback: raw.feedback } : {},
565
+ content
566
+ };
567
+ }
568
+ function extractRunEnrichment(messages) {
569
+ const map = /* @__PURE__ */ new Map();
570
+ for (const msg of messages) {
571
+ const runId = String(msg?.runId || "").trim();
572
+ if (!runId) continue;
573
+ let entry = map.get(runId);
574
+ if (!entry) {
575
+ entry = {};
576
+ map.set(runId, entry);
577
+ }
578
+ if (msg.feedback !== void 0 && msg.feedback !== null) {
579
+ entry.feedback = msg.feedback;
580
+ }
581
+ const seconds = msg.content?.additional_kwargs?.turn_duration;
582
+ if (typeof seconds === "number" && !Number.isNaN(seconds) && seconds >= 0) {
583
+ entry.latencyMs = Math.round(seconds * 1e3);
584
+ }
585
+ }
586
+ return map;
587
+ }
588
+ function backfillRunMessageFeedback(source, target) {
589
+ if (!source.length || !target.length) return target;
590
+ const feedbackById = /* @__PURE__ */ new Map();
591
+ for (const row of source) {
592
+ const id = String(row?.content?.id || "").trim();
593
+ if (!id || row?.feedback === void 0 || row?.feedback === null) continue;
594
+ feedbackById.set(id, row.feedback);
595
+ }
596
+ if (!feedbackById.size) return target;
597
+ return target.map((row) => {
598
+ const id = String(row?.content?.id || "").trim();
599
+ if (!id) return row;
600
+ const feedback = feedbackById.get(id);
601
+ if (feedback === void 0 || row.feedback !== void 0) return row;
602
+ return { ...row, feedback };
603
+ });
604
+ }
605
+ function runMessagesToMessages(messages) {
606
+ return messages.map((msg) => {
607
+ const normalized = normalizeMessageType({ ...asSxin(msg.content) });
608
+ asSxin(normalized).runId = msg.runId;
609
+ if (msg.createdAt !== void 0) {
610
+ const date = new Date(msg.createdAt);
611
+ if (!Number.isNaN(date.getTime())) asSxin(normalized).created_at = date.toISOString();
612
+ }
613
+ return normalized;
614
+ });
615
+ }
616
+ function stateMessagesToRunMessages(messages) {
617
+ let lastRunId = "";
618
+ return messages.map((msg, i) => {
619
+ const sxin = asSxin(msg);
620
+ const ownRunId = String(sxin.runId ?? sxin.additional_kwargs?.run_id ?? "").trim();
621
+ if (ownRunId) lastRunId = ownRunId;
622
+ const createdAt = parseCreatedAt(sxin.created_at);
623
+ return {
624
+ runId: ownRunId || lastRunId,
625
+ seq: i + 1,
626
+ eventType: "messages",
627
+ ...createdAt !== void 0 ? { createdAt } : {},
628
+ content: msg
629
+ };
630
+ });
631
+ }
632
+
633
+ // src/parser/message-text.ts
634
+ function simpleHash(input) {
635
+ let hash = 5381;
636
+ for (let i = 0; i < input.length; i++) {
637
+ hash = (hash << 5) + hash + input.charCodeAt(i) & 4294967295;
638
+ }
639
+ return Math.abs(hash).toString(36);
640
+ }
641
+ function readMessageText(msg) {
642
+ if (!msg || typeof msg !== "object") return null;
643
+ const content = msg?.content;
644
+ if (typeof content === "string") return { text: content, trim: false };
645
+ if (Array.isArray(content)) {
646
+ const texts = [];
647
+ for (const part of content) {
648
+ if (part?.type === "text" && typeof part?.text === "string") {
649
+ texts.push(part.text);
650
+ }
651
+ }
652
+ return { text: texts.join("\n"), trim: true };
653
+ }
654
+ return null;
655
+ }
656
+ function readMessageContentText(msg) {
657
+ const read = readMessageText(msg);
658
+ if (!read) return "";
659
+ return read.trim ? read.text.trim() : read.text;
660
+ }
661
+ function hasKbCitationMessage(msg) {
662
+ return readMessageContentText(msg).includes("support.kbCitation");
663
+ }
664
+ function extractTextFromMessage(msg) {
665
+ const read = readMessageText(msg);
666
+ if (!read) return "";
667
+ const text = collectVisibleText(read.text, tokenizeSxin(read.text));
668
+ return read.trim ? text.trim() : text;
669
+ }
670
+ function extractAiContentFromMessage(msg) {
671
+ const read = readMessageText(msg);
672
+ if (!read) return "";
673
+ const text = collectTextKeepSxin(read.text, tokenizeSxin(read.text));
674
+ return read.trim ? text.trim() : text;
675
+ }
676
+ function isVisibleUserMessage(msg) {
677
+ if (!msg || typeof msg !== "object") return false;
678
+ if (String(msg.type || "") !== "human") return false;
679
+ return msg.additional_kwargs?.hide_from_ui !== true;
680
+ }
681
+ function extractUserMessageTexts(rawMessages) {
682
+ if (!Array.isArray(rawMessages)) return [];
683
+ return rawMessages.filter((m) => isVisibleUserMessage(m)).map((m) => extractTextFromMessage(m).trim()).filter(Boolean).slice(0, 1);
684
+ }
685
+ function isHiddenUserMessage(msg) {
686
+ return msg?.role === "user" && msg?.additionalKwargs?.hide_from_ui === true;
687
+ }
688
+
689
+ // src/parser/report-artifact.ts
690
+ var genId = () => typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `id-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
691
+ function isWriteFileToolName(name) {
692
+ const n = String(name || "").trim().toLowerCase();
693
+ return n === "write_file" || n === "write_files";
694
+ }
695
+ function getToolCallArtifactMeta(toolCall) {
696
+ const meta = toolCall?.artifact_meta;
697
+ if (!meta || typeof meta !== "object") return null;
698
+ return meta;
699
+ }
700
+ function pathSuggestsBody(artifactPath) {
701
+ return /_正文(?:\.(?:md|markdown))?$/i.test(artifactPath) || /[/\\][^/\\]*正文[^/\\]*\.(?:md|markdown)$/i.test(artifactPath);
702
+ }
703
+ function pathSuggestsOutline(artifactPath) {
704
+ return /_大纲(?:\.(?:md|markdown))?$/i.test(artifactPath) || /[/\\][^/\\]*大纲[^/\\]*\.(?:md|markdown)$/i.test(artifactPath);
705
+ }
706
+ function descriptionSuggestsBody(description) {
707
+ return /正文/.test(description);
708
+ }
709
+ function descriptionSuggestsOutline(description) {
710
+ return /大纲/.test(description) && !descriptionSuggestsBody(description);
711
+ }
712
+ function extractKindSignals(toolCall) {
713
+ const meta = getToolCallArtifactMeta(toolCall);
714
+ return {
715
+ artifactPath: String(meta?.path || toolCall?.args?.path || "").trim(),
716
+ metaKind: String(meta?.kind || "").trim(),
717
+ description: String(toolCall?.args?.description || "").trim()
718
+ };
719
+ }
720
+ function resolveReportArtifactKind(toolCall) {
721
+ const { artifactPath, metaKind, description } = extractKindSignals(toolCall);
722
+ if (pathSuggestsBody(artifactPath) || descriptionSuggestsBody(description)) return "report_body";
723
+ if (pathSuggestsOutline(artifactPath) || descriptionSuggestsOutline(description)) return "report_outline";
724
+ if (metaKind === "report_body" || metaKind === "report_outline") return metaKind;
725
+ return null;
726
+ }
727
+ function extractTitleFromArtifactPath(path, kind = "report_outline") {
728
+ const raw = String(path || "").trim();
729
+ if (!raw) return "\u62A5\u544A";
730
+ const base = raw.split("/").pop() || raw;
731
+ const noExt = base.replace(/\.(md|markdown|html?)$/i, "");
732
+ if (kind === "report_body") {
733
+ return noExt.replace(/_正文$/i, "").replace(/_报告$/i, "").replace(/\s*正文\s*$/i, "").trim() || "\u62A5\u544A";
734
+ }
735
+ return noExt.replace(/_大纲$/i, "").replace(/\s*大纲\s*$/i, "").trim() || "\u62A5\u544A";
736
+ }
737
+ var OUTLINE_MAX_LEVEL = 3;
738
+ function normalizeSubChapter(raw, level) {
739
+ const legacyChildren = raw.children ?? raw.points ?? [];
740
+ const title = String(raw.title ?? raw.pointTitle ?? "");
741
+ const children = level >= OUTLINE_MAX_LEVEL ? [] : legacyChildren.map((c) => normalizeSubChapter(c, level + 1));
742
+ return {
743
+ id: String(raw.id ?? genId()),
744
+ title,
745
+ summary: String(raw.summary ?? raw.pointSummary ?? ""),
746
+ contentTheme: String(raw.contentTheme ?? raw.pointDesc ?? ""),
747
+ children
748
+ };
749
+ }
750
+ function normalizeOutline(raw) {
751
+ if (!Array.isArray(raw)) return [];
752
+ const outline = raw.map((item) => {
753
+ const ch = item;
754
+ const legacyChildren = ch.children ?? ch.points ?? [];
755
+ return {
756
+ id: String(ch.id ?? genId()),
757
+ chapterTitle: String(ch.chapterTitle ?? ""),
758
+ chapterSummary: String(ch.chapterSummary ?? ch.chapterDesc ?? ""),
759
+ children: legacyChildren.map((c) => normalizeSubChapter(c, 2))
760
+ };
761
+ });
762
+ return ensureOutlineContentThemes(outline);
763
+ }
764
+ function validateOutline(outline) {
765
+ if (!outline?.length) return false;
766
+ return outline.every((ch) => String(ch.chapterTitle || "").trim().length > 0);
767
+ }
768
+ function createEmptySubChapter() {
769
+ return {
770
+ id: genId(),
771
+ title: "",
772
+ summary: "",
773
+ contentTheme: "",
774
+ children: []
775
+ };
776
+ }
777
+ function ensureOutlineContentThemes(outline) {
778
+ const walk = (nodes) => {
779
+ nodes.forEach((node) => {
780
+ if (node.summary === void 0 || node.summary === null) {
781
+ node.summary = "";
782
+ }
783
+ if (node.contentTheme === void 0 || node.contentTheme === null) {
784
+ node.contentTheme = "";
785
+ }
786
+ if (node.children?.length) walk(node.children);
787
+ });
788
+ };
789
+ outline.forEach((ch) => {
790
+ if (ch.chapterSummary === void 0 || ch.chapterSummary === null) {
791
+ ch.chapterSummary = "";
792
+ }
793
+ walk(ch.children || []);
794
+ });
795
+ return outline;
796
+ }
797
+ function detectLevelOneIsChapter(lines) {
798
+ const levelOneCount = lines.filter((line) => /^#\s+.+$/.test(line.trim())).length;
799
+ return levelOneCount > 1;
800
+ }
801
+ function joinLines(existing, text) {
802
+ return existing ? `${existing}
803
+ ${text}` : text;
804
+ }
805
+ function appendBullet(state, text) {
806
+ const line = `- ${text}`;
807
+ const top = state.stack[state.stack.length - 1]?.node;
808
+ if (top) {
809
+ top.contentTheme = joinLines(top.contentTheme, line);
810
+ return;
811
+ }
812
+ if (!state.currentChapter) return;
813
+ state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, line);
814
+ }
815
+ function appendSummaryText(state, text) {
816
+ if (!text) return;
817
+ const top = state.stack[state.stack.length - 1]?.node;
818
+ if (top) {
819
+ top.summary = joinLines(top.summary, text);
820
+ return;
821
+ }
822
+ if (!state.currentChapter) return;
823
+ state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, text);
824
+ }
825
+ function appendPlainText(state, text) {
826
+ if (!text) return;
827
+ const top = state.stack[state.stack.length - 1]?.node;
828
+ if (top) {
829
+ top.contentTheme = joinLines(top.contentTheme, text);
830
+ return;
831
+ }
832
+ if (!state.currentChapter) return;
833
+ state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, text);
834
+ }
835
+ function resolveTemplateName(title) {
836
+ return title.replace(/\s*·\s*大纲\s*$/i, "").replace(/\s*大纲\s*$/i, "").trim() || title;
837
+ }
838
+ function pushChapter(state, title) {
839
+ state.currentChapter = { id: genId(), chapterTitle: title, chapterSummary: "", children: [] };
840
+ state.outline.push(state.currentChapter);
841
+ state.stack.length = 0;
842
+ }
843
+ function pushSubChapter(state, level, title) {
844
+ const subChapterLevel = state.levelOneIsChapter ? level : level - 1;
845
+ if (subChapterLevel < 2 || !state.currentChapter) return false;
846
+ const sub = { id: genId(), title, summary: "", contentTheme: "", children: [] };
847
+ while (state.stack.length && state.stack[state.stack.length - 1].level >= subChapterLevel) {
848
+ state.stack.pop();
849
+ }
850
+ const parent = state.stack[state.stack.length - 1]?.node;
851
+ if (parent) parent.children.push(sub);
852
+ else state.currentChapter.children.push(sub);
853
+ state.stack.push({ node: sub, level: subChapterLevel });
854
+ return true;
855
+ }
856
+ function handleQuote(state, trimmed) {
857
+ if (!trimmed.startsWith(">")) return false;
858
+ const quoteText = trimmed.replace(/^(>\s*)+/, "").trim();
859
+ const summaryText = quoteText.replace(/^摘要\s*[::]\s*/i, "").trim();
860
+ appendSummaryText(state, summaryText || quoteText);
861
+ return true;
862
+ }
863
+ function handleHeading(state, trimmed) {
864
+ const heading = trimmed.match(/^(#{1,6})\s+(.+)$/);
865
+ if (!heading) return false;
866
+ const level = heading[1].length;
867
+ const title = heading[2].trim();
868
+ if (level === 1 && !state.levelOneIsChapter) {
869
+ state.templateName = resolveTemplateName(title);
870
+ return true;
871
+ }
872
+ if (level === 1 && state.levelOneIsChapter || level === 2 && !state.levelOneIsChapter) {
873
+ pushChapter(state, title);
874
+ return true;
875
+ }
876
+ return pushSubChapter(state, level, title);
877
+ }
878
+ function parseMarkdownToOutline(markdown) {
879
+ const lines = String(markdown || "").split(/\r?\n/);
880
+ const state = {
881
+ templateName: "",
882
+ outline: [],
883
+ currentChapter: null,
884
+ stack: [],
885
+ levelOneIsChapter: detectLevelOneIsChapter(lines)
886
+ };
887
+ for (const line of lines) {
888
+ const trimmed = line.trim();
889
+ if (!trimmed || trimmed === "---" || /^```/.test(trimmed)) continue;
890
+ if (handleQuote(state, trimmed)) continue;
891
+ if (handleHeading(state, trimmed)) continue;
892
+ const bullet = trimmed.match(/^[-*]\s+(.+)$/);
893
+ if (bullet) {
894
+ appendBullet(state, bullet[1].trim());
895
+ continue;
896
+ }
897
+ appendPlainText(state, trimmed);
898
+ }
899
+ return {
900
+ templateName: state.templateName || "\u62A5\u544A",
901
+ outline: normalizeOutline(state.outline)
902
+ };
903
+ }
904
+ var HTML_LIKE = /^\s*</;
905
+ function isReportBodyHtml(content) {
906
+ const s = String(content || "").trim();
907
+ if (!s) return false;
908
+ return HTML_LIKE.test(s);
909
+ }
910
+ function extractReportTitleFromBody(content, fallback = "") {
911
+ const s = String(content || "").trim();
912
+ if (!s) return fallback;
913
+ if (isReportBodyHtml(s)) {
914
+ const h1 = s.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);
915
+ if (h1?.[1]) {
916
+ const t = h1[1].replace(/<[^>]+>/g, "").trim();
917
+ if (t) return t;
918
+ }
919
+ }
920
+ const heading = s.match(/^#\s+(.+)$/m);
921
+ if (heading?.[1]) return heading[1].trim();
922
+ return fallback;
923
+ }
924
+
925
+ // src/parser/group-builder-helper.ts
926
+ function isHumanMessage(msg) {
927
+ return String(asSxin(msg).type || "") === "human";
928
+ }
929
+ function parseHumanMessageId(id) {
930
+ const raw = String(id || "");
931
+ const match = raw.match(/^(.*?)__(memory|user)(\([^)]*\))?$/i);
932
+ if (!match) return { baseId: raw, variant: null };
933
+ return { baseId: match[1], variant: match[2].toLowerCase() };
934
+ }
935
+ function getHumanMessageBaseId(id) {
936
+ return parseHumanMessageId(id).baseId;
937
+ }
938
+ function isAiMessage(msg) {
939
+ const t = String(asSxin(msg).type || "");
940
+ return ["ai", "AIMessage", "AIMessageChunk"].includes(t);
941
+ }
942
+ function isToolMessage(msg) {
943
+ return String(asSxin(msg).type || "") === "tool";
944
+ }
945
+ function deriveToolsFromMessages(messages) {
946
+ const tools = [];
947
+ const byId = /* @__PURE__ */ new Map();
948
+ for (const msg of messages) {
949
+ const m = asSxin(msg);
950
+ const toolCalls = m.tool_calls;
951
+ if (Array.isArray(toolCalls)) {
952
+ for (const tc of toolCalls) {
953
+ const id = String(tc?.id || "").trim();
954
+ if (!id || byId.has(id)) continue;
955
+ const tool = { id, call: tc, aiMessage: msg, state: "pending", index: tools.length };
956
+ byId.set(id, tool);
957
+ tools.push(tool);
958
+ }
959
+ }
960
+ const toolCallId = String(m.tool_call_id || "").trim();
961
+ if (!toolCallId) continue;
962
+ const state = m.status === "error" ? "error" : "completed";
963
+ const existing = byId.get(toolCallId);
964
+ if (existing) {
965
+ existing.result = msg;
966
+ existing.state = state;
967
+ } else {
968
+ const tool = {
969
+ id: toolCallId,
970
+ call: { id: toolCallId, name: String(m.name || ""), args: {} },
971
+ result: msg,
972
+ state,
973
+ index: tools.length
974
+ };
975
+ byId.set(toolCallId, tool);
976
+ tools.push(tool);
977
+ }
978
+ }
979
+ return tools;
980
+ }
981
+ function normalizeUsage(raw) {
982
+ if (!raw || typeof raw !== "object") return void 0;
983
+ const r = raw;
984
+ const inputTokens = readAliasedNumber(r, ["input_tokens", "inputTokens", "prompt_tokens", "promptTokens"]);
985
+ const outputTokens = readAliasedNumber(r, ["output_tokens", "outputTokens", "completion_tokens", "completionTokens"]);
986
+ const totalTokens = readAliasedNumber(r, ["total_tokens", "totalTokens"]);
987
+ if ([inputTokens, outputTokens, totalTokens].every(Number.isNaN)) {
988
+ return void 0;
989
+ }
990
+ const usage = {
991
+ input_tokens: toZeroIfNaN(inputTokens),
992
+ output_tokens: toZeroIfNaN(outputTokens),
993
+ total_tokens: toZeroIfNaN(totalTokens)
994
+ };
995
+ applyUsageDetails(usage, r);
996
+ return usage;
997
+ }
998
+ function readAliasedNumber(r, aliases) {
999
+ for (const key of aliases) {
1000
+ if (r[key] !== void 0 && r[key] !== null) return Number(r[key]);
1001
+ }
1002
+ return NaN;
1003
+ }
1004
+ function toZeroIfNaN(n) {
1005
+ return Number.isNaN(n) ? 0 : n;
1006
+ }
1007
+ function applyUsageDetails(usage, r) {
1008
+ const cacheRead = Number(r.input_token_details?.cache_read ?? r.input_token_details?.cacheRead);
1009
+ if (!Number.isNaN(cacheRead)) {
1010
+ usage.input_token_details = { cache_read: cacheRead };
1011
+ }
1012
+ const reasoning = Number(r.output_token_details?.reasoning ?? r.output_token_details?.reasoningTokens);
1013
+ if (!Number.isNaN(reasoning)) {
1014
+ usage.output_token_details = { reasoning };
1015
+ }
1016
+ }
1017
+
1018
+ // src/parser/body-segments.ts
1019
+ var SEGMENT_TAGS = /* @__PURE__ */ new Set(["sxin-list", "sxin-item"]);
1020
+ function visibleTextOf(node) {
1021
+ if (node.type === "text") return node.value;
1022
+ if (node.type === "comment") return "";
1023
+ return node.children.map(visibleTextOf).join("");
1024
+ }
1025
+ function toItemSegment(el, source) {
1026
+ return {
1027
+ type: "item",
1028
+ tag: "sxin-item",
1029
+ attrs: { ...el.attrs },
1030
+ content: visibleTextOf(el) || void 0,
1031
+ raw: source.slice(el.start, el.end)
1032
+ };
1033
+ }
1034
+ function toListSegment(el, source) {
1035
+ const children = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-item").map((c) => toItemSegment(c, source));
1036
+ return { type: "list", tag: "sxin-list", attrs: { ...el.attrs }, children, raw: source.slice(el.start, el.end) };
1037
+ }
1038
+ function sliceBodySegments(body) {
1039
+ const source = String(body ?? "");
1040
+ const segments = [];
1041
+ let textBuf = "";
1042
+ const flushText = () => {
1043
+ if (!textBuf) return;
1044
+ segments.push({ type: "text", content: textBuf });
1045
+ textBuf = "";
1046
+ };
1047
+ for (const node of tokenizeSxin(source)) {
1048
+ if (node.type === "element" && SEGMENT_TAGS.has(node.tagName)) {
1049
+ flushText();
1050
+ segments.push(node.tagName === "sxin-list" ? toListSegment(node, source) : toItemSegment(node, source));
1051
+ } else if (node.type === "comment") {
1052
+ continue;
1053
+ } else if (node.type === "text") {
1054
+ textBuf += node.value;
1055
+ } else {
1056
+ textBuf += source.slice(node.start, node.end);
1057
+ }
1058
+ }
1059
+ flushText();
1060
+ if (!segments.length) segments.push({ type: "text", content: "" });
1061
+ return segments;
1062
+ }
1063
+
1064
+ // src/assembler/run-grouping.ts
1065
+ var LIVE_SEQ = Number.MAX_SAFE_INTEGER;
1066
+ function rowMessageId(msg) {
1067
+ return String(msg?.id || "").trim();
1068
+ }
1069
+ function isUserEchoRow(id) {
1070
+ return id.endsWith("__user");
1071
+ }
1072
+ function pageRowToAsmRow(row) {
1073
+ const id = rowMessageId(row.content);
1074
+ if (!id) return null;
1075
+ const out = {
1076
+ id,
1077
+ runId: String(row.runId || ""),
1078
+ seq: Number.isFinite(row.seq) ? row.seq : 0,
1079
+ msg: row.content
1080
+ };
1081
+ if (row.createdAt !== void 0) out.createdAt = row.createdAt;
1082
+ if (row.feedback !== void 0 && row.feedback !== null) out.feedback = row.feedback;
1083
+ return out;
1084
+ }
1085
+ function liveToAsmRow(msg, runId) {
1086
+ const id = rowMessageId(msg);
1087
+ if (!id || isUserEchoRow(id)) return null;
1088
+ return { id, runId, seq: LIVE_SEQ, msg };
1089
+ }
1090
+ function groupRowsByRun(rows, liveMessages, activeRunId, pendingRunId) {
1091
+ const byId = /* @__PURE__ */ new Map();
1092
+ const buckets = /* @__PURE__ */ new Map();
1093
+ for (const row of rows) {
1094
+ const asm = pageRowToAsmRow(row);
1095
+ if (!asm) continue;
1096
+ const prev = byId.get(asm.id);
1097
+ if (prev) {
1098
+ if (asm.seq >= prev.seq) {
1099
+ replaceInBucket(buckets, prev, asm);
1100
+ byId.set(asm.id, asm);
1101
+ }
1102
+ continue;
1103
+ }
1104
+ byId.set(asm.id, asm);
1105
+ pushToBucket(buckets, asm);
1106
+ }
1107
+ const liveRunId = String(activeRunId || pendingRunId || "").trim();
1108
+ if (liveRunId) {
1109
+ for (const msg of liveMessages) {
1110
+ const asm = liveToAsmRow(msg, liveRunId);
1111
+ if (!asm) continue;
1112
+ if (byId.has(asm.id)) continue;
1113
+ pushToBucket(buckets, asm);
1114
+ }
1115
+ }
1116
+ for (const list of buckets.values()) {
1117
+ list.sort((a, b) => a.seq - b.seq);
1118
+ }
1119
+ return buckets;
1120
+ }
1121
+ function pushToBucket(buckets, row) {
1122
+ const runId = String(row.runId || "").trim();
1123
+ if (!runId) return;
1124
+ const list = buckets.get(runId);
1125
+ if (list) list.push(row);
1126
+ else buckets.set(runId, [row]);
1127
+ }
1128
+ function replaceInBucket(buckets, prev, next) {
1129
+ const list = buckets.get(prev.runId);
1130
+ if (!list) return;
1131
+ const idx = list.indexOf(prev);
1132
+ if (idx >= 0) list[idx] = next;
1133
+ if (prev.runId !== next.runId) {
1134
+ const oldList = buckets.get(prev.runId);
1135
+ if (oldList) {
1136
+ const i = oldList.indexOf(prev);
1137
+ if (i >= 0) oldList.splice(i, 1);
1138
+ if (!oldList.length) buckets.delete(prev.runId);
1139
+ }
1140
+ pushToBucket(buckets, next);
1141
+ }
1142
+ }
1143
+
1144
+ // src/parser/extractors.ts
1145
+ function normalizeName(name) {
1146
+ const n = String(name || "").trim().toLowerCase();
1147
+ return n === "write_files" ? "write_file" : n;
1148
+ }
1149
+ function tryParseObject(result) {
1150
+ const text = String(result ?? "").trim();
1151
+ if (!text.startsWith("{")) return null;
1152
+ try {
1153
+ const parsed = JSON.parse(text);
1154
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
1155
+ return parsed;
1156
+ } catch {
1157
+ return null;
1158
+ }
1159
+ }
1160
+ function extractFromToolResult(name, result, toolCallLike) {
1161
+ const tool = normalizeName(name);
1162
+ const obj = tryParseObject(result);
1163
+ if (tool === "ask_clarification" && obj) {
1164
+ const question = obj.question ?? obj.title;
1165
+ if (typeof question !== "string" || !question.trim()) return void 0;
1166
+ const options = Array.isArray(obj.options) ? obj.options : void 0;
1167
+ return options ? { kind: "clarification", question, options } : { kind: "clarification", question };
1168
+ }
1169
+ if (tool === "write_file") {
1170
+ if (obj) {
1171
+ if (typeof obj.body === "string" && obj.body) {
1172
+ const outline = typeof obj.outline === "string" ? obj.outline : void 0;
1173
+ return outline ? { kind: "report", reportKind: "report_body", body: obj.body, outline } : { kind: "report", reportKind: "report_body", body: obj.body };
1174
+ }
1175
+ if (Array.isArray(obj.files) && obj.files.length) {
1176
+ return { kind: "artifact", files: obj.files };
1177
+ }
1178
+ }
1179
+ const reportKind = resolveReportArtifactKind(toolCallLike);
1180
+ if (reportKind) {
1181
+ const tc = toolCallLike ?? {};
1182
+ const sourcePath = String(tc?.artifact_meta?.path || tc?.args?.path || "").trim() || void 0;
1183
+ return {
1184
+ kind: "report",
1185
+ reportKind,
1186
+ sourcePath,
1187
+ title: sourcePath ? extractTitleFromArtifactPath(sourcePath, reportKind) : void 0
1188
+ };
1189
+ }
1190
+ }
1191
+ return void 0;
1192
+ }
1193
+
1194
+ // src/parser/tool-args.ts
1195
+ function asArgsObject(args) {
1196
+ if (args && typeof args === "object" && !Array.isArray(args)) return args;
1197
+ if (typeof args === "string") {
1198
+ try {
1199
+ const parsed = JSON.parse(args);
1200
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1201
+ return parsed;
1202
+ }
1203
+ } catch {
1204
+ }
1205
+ }
1206
+ return void 0;
1207
+ }
1208
+ function pickRicherArgs(prev, next) {
1209
+ const nextObj = asArgsObject(next);
1210
+ if (!nextObj) return void 0;
1211
+ const prevObj = asArgsObject(prev);
1212
+ if (!prevObj) return nextObj;
1213
+ const prevKeys = new Set(Object.keys(prevObj));
1214
+ const hasNewKey = Object.keys(nextObj).some((k) => !prevKeys.has(k));
1215
+ const longer = JSON.stringify(nextObj).length > JSON.stringify(prevObj).length;
1216
+ return hasNewKey || longer ? nextObj : void 0;
1217
+ }
1218
+
1219
+ // src/assembler/types.ts
1220
+ var BACKEND_STATUS_MAP = {
1221
+ success: "success",
1222
+ error: "error",
1223
+ interrupted: "interrupted",
1224
+ cancelled: "cancelled",
1225
+ pending: "pending",
1226
+ running: "running"
1227
+ };
1228
+
1229
+ // src/assembler/run-assembly.ts
1230
+ function emptyRunItem(runId, createdAt) {
1231
+ return {
1232
+ runId,
1233
+ input: { kind: "message", text: "" },
1234
+ status: "pending",
1235
+ body: "",
1236
+ segments: [{ type: "text", content: "" }],
1237
+ tools: [],
1238
+ attachments: [],
1239
+ clarifications: [],
1240
+ rawMessages: [],
1241
+ ...createdAt !== void 0 ? { createdAt } : {}
1242
+ };
1243
+ }
1244
+ function assembleRun(runId, options) {
1245
+ const rows = options.rows;
1246
+ const twinEnabled = !!options.twin?.enabled;
1247
+ const twinToolPrefix = options.twin?.toolPrefix || "city-digital-twin-display_";
1248
+ let body = "";
1249
+ let feedback;
1250
+ const tools = [];
1251
+ const toolByCallId = /* @__PURE__ */ new Map();
1252
+ let createdAt;
1253
+ for (const row of rows) {
1254
+ const msg = row.msg;
1255
+ const type = String(msg?.type || "");
1256
+ if (createdAt === void 0 && row.createdAt !== void 0) createdAt = row.createdAt;
1257
+ if (type === "ai") {
1258
+ const text = extractAiContentFromMessage(msg);
1259
+ if (text) body = body ? `${body}
1260
+ ${text}` : text;
1261
+ registerToolCalls(msg, tools, toolByCallId);
1262
+ } else if (type === "tool") {
1263
+ applyToolMessage(msg, tools, toolByCallId);
1264
+ } else if (type === "human") {
1265
+ }
1266
+ if (row.feedback !== void 0 && row.feedback !== null) feedback = row.feedback;
1267
+ }
1268
+ const attachments = assembleAttachments(tools, twinEnabled, twinToolPrefix);
1269
+ const clarifications = extractClarifications(tools);
1270
+ const segments = options.streaming ? [{ type: "text", content: body }] : sliceBodySegments(body);
1271
+ return {
1272
+ runId,
1273
+ // input 由 projectRuns 层填(需要 runs.list / 窗口 human 行两级来源),这里占位
1274
+ input: { kind: "message", text: "" },
1275
+ status: "success",
1276
+ body,
1277
+ segments,
1278
+ tools,
1279
+ attachments,
1280
+ ...feedback !== void 0 ? { feedback } : {},
1281
+ clarifications,
1282
+ ...createdAt !== void 0 ? { createdAt } : {},
1283
+ rawMessages: [...rows]
1284
+ };
1285
+ }
1286
+ function extractInputFromRows(rows) {
1287
+ for (const row of rows) {
1288
+ const msg = row.msg;
1289
+ if (!isVisibleUserMessage(msg)) continue;
1290
+ const kwargs = msg?.additional_kwargs;
1291
+ return {
1292
+ text: readMessageContentText(msg).trim(),
1293
+ ...kwargs && typeof kwargs === "object" ? { kwargs: { ...kwargs } } : {}
1294
+ };
1295
+ }
1296
+ return { text: "" };
1297
+ }
1298
+ function registerToolCalls(msg, tools, byCallId) {
1299
+ const calls = Array.isArray(msg?.tool_calls) ? msg.tool_calls : msg?.additional_kwargs?.tool_calls;
1300
+ if (!Array.isArray(calls)) return;
1301
+ for (const call of calls) {
1302
+ const callId = String(call?.id || "").trim();
1303
+ if (!callId) continue;
1304
+ const input = asArgsObject(call?.args);
1305
+ const artifactMeta = call?.artifact_meta;
1306
+ const prev = byCallId.get(callId);
1307
+ if (prev) {
1308
+ const richer = pickRicherArgs(prev.input, call?.args);
1309
+ if (richer) prev.input = richer;
1310
+ if (!prev.artifactMeta && artifactMeta) prev.artifactMeta = artifactMeta;
1311
+ continue;
1312
+ }
1313
+ const tool = { callId, name: String(call?.name || ""), status: "running" };
1314
+ if (input !== void 0) tool.input = input;
1315
+ if (artifactMeta !== void 0) tool.artifactMeta = artifactMeta;
1316
+ tools.push(tool);
1317
+ byCallId.set(callId, tool);
1318
+ }
1319
+ }
1320
+ function applyToolMessage(msg, tools, byCallId) {
1321
+ const callId = String(msg?.tool_call_id || "").trim();
1322
+ if (!callId) return;
1323
+ const tool = byCallId.get(callId);
1324
+ if (!tool) return;
1325
+ const result = readMessageContentText(msg);
1326
+ tool.result = result;
1327
+ const extracted = extractFromToolResult(tool.name, result, { artifact_meta: tool.artifactMeta, args: tool.input });
1328
+ if (extracted) tool.extracted = extracted;
1329
+ tool.status = String(msg?.status || "") === "error" ? "error" : "finished";
1330
+ }
1331
+ function assembleAttachments(tools, twinEnabled, twinToolPrefix) {
1332
+ const byKind = /* @__PURE__ */ new Map();
1333
+ for (const tool of tools) {
1334
+ const ex = tool.extracted;
1335
+ if (ex?.kind === "report") {
1336
+ byKind.set(`report:${ex.reportKind}`, {
1337
+ kind: "report",
1338
+ reportKind: ex.reportKind,
1339
+ body: ex.body,
1340
+ outline: ex.outline,
1341
+ sourcePath: ex.sourcePath,
1342
+ title: ex.title
1343
+ });
1344
+ } else if (ex?.kind === "artifact") {
1345
+ byKind.set("artifact", { kind: "artifact", files: ex.files });
1346
+ } else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
1347
+ byKind.set("twin", { kind: "twin", payload: tool.input });
1348
+ }
1349
+ }
1350
+ return [...byKind.values()];
1351
+ }
1352
+ function extractClarifications(tools) {
1353
+ const out = [];
1354
+ for (const tool of tools) {
1355
+ if (tool.name !== "ask_clarification") continue;
1356
+ const args = asArgsObject(tool.input);
1357
+ const question = String(args?.question ?? args?.title ?? "").trim();
1358
+ if (!question) continue;
1359
+ const record = { callId: tool.callId, question };
1360
+ if (args?.options !== void 0) record.options = args.options;
1361
+ if (Array.isArray(args?.fields)) record.fields = args.fields;
1362
+ out.push(record);
1363
+ }
1364
+ return out;
1365
+ }
1366
+ function mapBackendStatus(raw) {
1367
+ const v = String(raw || "").trim();
1368
+ return BACKEND_STATUS_MAP[v] ?? "success";
1369
+ }
1370
+
1371
+ // src/assembler/project-runs.ts
1372
+ function classifyInputKind(inputMsg) {
1373
+ const kwargs = inputMsg?.additional_kwargs;
1374
+ if (kwargs?.human_input_response && typeof kwargs.human_input_response === "object") return "clarification";
1375
+ return "message";
1376
+ }
1377
+ function inputFromRunMeta(meta) {
1378
+ const messages = meta.inputMessages ?? [];
1379
+ if (!messages.length) return null;
1380
+ const first = messages[0];
1381
+ const visible = messages.find((m) => isVisibleUserMessage(m));
1382
+ const text = visible ? readMessageContentText(visible) : "";
1383
+ const kwargs = first.additional_kwargs;
1384
+ const hasKwargs = kwargs && typeof kwargs === "object" && Object.keys(kwargs).length > 0;
1385
+ return {
1386
+ kind: classifyInputKind(first),
1387
+ text,
1388
+ ...hasKwargs ? { kwargs: { ...kwargs } } : {}
1389
+ };
1390
+ }
1391
+ function normalizeRequestId(raw) {
1392
+ return String(raw ?? "").trim().replace("clarification:", "");
1393
+ }
1394
+ function projectRuns(input) {
1395
+ const buckets = groupRowsByRun(input.rows, input.liveMessages, input.activeRunId, input.pendingRun?.runId ?? null);
1396
+ const metaByRunId = new Map(input.runsList.map((m) => [String(m.runId || ""), m]));
1397
+ const orderedBuckets = [...buckets.entries()].sort(
1398
+ (a, b) => (a[1][0]?.seq ?? 0) - (b[1][0]?.seq ?? 0)
1399
+ );
1400
+ const runs = [];
1401
+ for (const [runId, rows] of orderedBuckets) {
1402
+ const meta = metaByRunId.get(runId);
1403
+ const isStreamingRun = input.streaming && input.activeRunId === runId;
1404
+ const item = assembleRun(runId, { rows, streaming: isStreamingRun, twin: input.twin });
1405
+ const fromMeta = meta ? inputFromRunMeta(meta) : void 0;
1406
+ if (fromMeta) {
1407
+ item.input = fromMeta;
1408
+ } else {
1409
+ const fromRows = extractInputFromRows(rows);
1410
+ if (fromRows.text) {
1411
+ item.input = {
1412
+ kind: classifyInputKind(fromRows.kwargs),
1413
+ text: fromRows.text,
1414
+ ...fromRows.kwargs ? { kwargs: fromRows.kwargs } : {}
1415
+ };
1416
+ }
1417
+ }
1418
+ const pendingInput = input.pendingRun;
1419
+ if (pendingInput && runId === pendingInput.runId && !item.input.text) {
1420
+ item.input = {
1421
+ kind: pendingInput.kind,
1422
+ text: pendingInput.text,
1423
+ ...pendingInput.kwargs ? { kwargs: pendingInput.kwargs } : {}
1424
+ };
1425
+ }
1426
+ if (isStreamingRun) item.status = "running";
1427
+ else if (meta) {
1428
+ item.status = mapBackendStatus(meta.status);
1429
+ if (meta.tokens) item.tokens = meta.tokens;
1430
+ if (meta.createdAt !== void 0) item.createdAt = meta.createdAt;
1431
+ if (meta.stopReason) item.stopReason = meta.stopReason;
1432
+ }
1433
+ runs.push(item);
1434
+ }
1435
+ const pending = input.pendingRun;
1436
+ if (pending && !buckets.has(pending.runId)) {
1437
+ const placeholder = emptyRunItem(pending.runId, Date.now());
1438
+ placeholder.input = { kind: pending.kind, text: pending.text, ...pending.kwargs ? { kwargs: { ...pending.kwargs } } : {} };
1439
+ if (input.streaming && input.activeRunId === pending.runId) placeholder.status = "running";
1440
+ runs.push(placeholder);
1441
+ }
1442
+ const answers = input.answers;
1443
+ for (let i = 0; i < runs.length; i++) {
1444
+ const run = runs[i];
1445
+ for (const record of run.clarifications) {
1446
+ if (record.answer !== void 0) continue;
1447
+ const optimistic = answers?.get(record.callId);
1448
+ if (optimistic !== void 0) {
1449
+ record.answer = optimistic;
1450
+ continue;
1451
+ }
1452
+ for (let j = i + 1; j < runs.length; j++) {
1453
+ const laterKwargs = runs[j].input.kwargs;
1454
+ const response = laterKwargs?.human_input_response;
1455
+ if (!response || typeof response !== "object") continue;
1456
+ if (normalizeRequestId(response.request_id) !== normalizeRequestId(record.callId)) continue;
1457
+ record.answer = formatAnswerText(response.value);
1458
+ record.answerRunId = runs[j].runId;
1459
+ break;
1460
+ }
1461
+ }
1462
+ }
1463
+ return runs;
1464
+ }
1465
+
1466
+ // src/runtime/run-info.ts
1467
+ function buildRunInfo(run, threadId) {
1468
+ return {
1469
+ runId: String(run?.run_id || "").trim(),
1470
+ threadId: String(threadId || "").trim(),
1471
+ usage: buildRunUsage(run),
1472
+ latencyMs: buildRunLatencyMs(run),
1473
+ finishReason: toOptionalString(run?.stop_reason ?? run?.finish_reason),
1474
+ modelName: toOptionalString(run?.model_name),
1475
+ status: buildRunStatus(run),
1476
+ createdAt: buildRunCreatedAt(run)
1477
+ };
1478
+ }
1479
+ function toOptionalString(value) {
1480
+ return value ? String(value) : void 0;
1481
+ }
1482
+ function buildRunUsage(run) {
1483
+ return normalizeUsage({
1484
+ input_tokens: run?.total_input_tokens,
1485
+ output_tokens: run?.total_output_tokens,
1486
+ total_tokens: run?.total_tokens
1487
+ });
1488
+ }
1489
+ function buildRunStatus(run) {
1490
+ return run?.status ? String(run.status) : void 0;
1491
+ }
1492
+ function buildRunCreatedAt(run) {
1493
+ return run?.created_at ? Number(new Date(run.created_at)) : void 0;
1494
+ }
1495
+ function buildRunMeta(run) {
1496
+ const runId = String(run?.run_id || "").trim();
1497
+ if (!runId) return null;
1498
+ const inputMessages = run?.kwargs?.input?.messages ?? [];
1499
+ const totalTokens = Number(run?.total_tokens);
1500
+ const tokens = Number.isFinite(totalTokens) && totalTokens > 0 ? {
1501
+ total: totalTokens,
1502
+ input: Number(run?.total_input_tokens) || 0,
1503
+ output: Number(run?.total_output_tokens) || 0,
1504
+ ...Number.isFinite(Number(run?.llm_call_count)) ? { llmCallCount: Number(run.llm_call_count) } : {},
1505
+ byCaller: {
1506
+ leadAgent: Number(run?.lead_agent_tokens) || 0,
1507
+ subagent: Number(run?.subagent_tokens) || 0,
1508
+ middleware: Number(run?.middleware_tokens) || 0
1509
+ }
1510
+ } : void 0;
1511
+ const createdAt = buildRunCreatedAt(run);
1512
+ return {
1513
+ runId,
1514
+ status: String(run?.status || "").trim(),
1515
+ ...createdAt !== void 0 ? { createdAt } : {},
1516
+ ...Array.isArray(inputMessages) && inputMessages.length ? { inputMessages } : {},
1517
+ ...tokens ? { tokens } : {},
1518
+ ...run?.stop_reason !== void 0 && run?.stop_reason !== null ? { stopReason: String(run.stop_reason) } : {}
1519
+ };
1520
+ }
1521
+ function buildRunDirectLatencyMs(run) {
1522
+ const direct = Number(run?.latency_ms);
1523
+ return direct || void 0;
1524
+ }
1525
+ function buildRunLatencyMs(run) {
1526
+ const direct = buildRunDirectLatencyMs(run);
1527
+ if (direct !== void 0) return direct;
1528
+ const created = Date.parse(String(run?.created_at ?? ""));
1529
+ const updated = Date.parse(String(run?.updated_at ?? ""));
1530
+ if (Number.isNaN(created) || Number.isNaN(updated)) return void 0;
1531
+ const diff = updated - created;
1532
+ return diff >= 0 ? diff : void 0;
1533
+ }
1534
+ function pickRunMessageMetadata(messages) {
1535
+ let modelName;
1536
+ let finishReason;
1537
+ for (const msg of messages) {
1538
+ if (!isAiMessage(msg)) {
1539
+ continue;
1540
+ }
1541
+ const responseMetadata = msg?.response_metadata || {};
1542
+ if (!modelName && responseMetadata.model_name) {
1543
+ modelName = String(responseMetadata.model_name);
1544
+ }
1545
+ if (!finishReason && responseMetadata.finish_reason) {
1546
+ finishReason = String(responseMetadata.finish_reason);
1547
+ }
1548
+ if (modelName && finishReason) {
1549
+ break;
1550
+ }
1551
+ }
1552
+ return { modelName, finishReason };
1553
+ }
1554
+
1555
+ // src/runtime/semantic-overlay.ts
1556
+ var extractKwargsPatch = (msg) => {
1557
+ const kwargs = msg?.additional_kwargs;
1558
+ if (!kwargs || typeof kwargs !== "object") return void 0;
1559
+ const patch = {};
1560
+ if (kwargs.hide_from_ui === true) patch.hide_from_ui = true;
1561
+ if (kwargs.human_input_response && typeof kwargs.human_input_response === "object") {
1562
+ patch.human_input_response = kwargs.human_input_response;
1563
+ }
1564
+ return Object.keys(patch).length ? patch : void 0;
1565
+ };
1566
+ function extractSemanticPatchesFromMessages(messages) {
1567
+ const next = /* @__PURE__ */ new Map();
1568
+ for (const m of messages ?? []) {
1569
+ const id = String(m?.id || "").trim();
1570
+ if (!id) continue;
1571
+ const patch = { id };
1572
+ if (String(m?.type || "") === "ai" && hasKbCitationMessage(m)) {
1573
+ patch.content = m.content;
1574
+ }
1575
+ if (String(m?.type || "") === "human") {
1576
+ const kwargs = extractKwargsPatch(m);
1577
+ if (kwargs) patch.additional_kwargs = kwargs;
1578
+ }
1579
+ if (patch.content !== void 0 || patch.additional_kwargs) next.set(id, patch);
1580
+ }
1581
+ return next;
1582
+ }
1583
+ function createSemanticOverlay() {
1584
+ let patches = /* @__PURE__ */ new Map();
1585
+ return {
1586
+ applyState(state) {
1587
+ const messages = extractStateMessages(state);
1588
+ patches = extractSemanticPatchesFromMessages(messages);
1589
+ const citedIds = messages.filter((m) => String(m?.type || "") === "ai" && hasKbCitationMessage(m)).map((m) => String(m?.id || "")).filter(Boolean);
1590
+ return { patched: patches.size, citedIds };
1591
+ },
1592
+ getPatches() {
1593
+ return new Map(patches);
1594
+ },
1595
+ invalidate() {
1596
+ patches = /* @__PURE__ */ new Map();
1597
+ }
1598
+ };
1599
+ }
1600
+ function applySemanticPatches(messages, patches) {
1601
+ if (!patches.size || !messages.length) return messages;
1602
+ return messages.map((m) => {
1603
+ const id = String(m?.id || "").trim();
1604
+ const patch = id ? patches.get(id) : void 0;
1605
+ if (!patch) return m;
1606
+ let next = m;
1607
+ if (patch.content !== void 0 && String(next?.type || "") === "ai" && !hasKbCitationMessage(next)) {
1608
+ next = { ...next, content: patch.content };
1609
+ }
1610
+ const localKwargs = next?.additional_kwargs;
1611
+ if (patch.additional_kwargs && Object.keys(patch.additional_kwargs).length) {
1612
+ const merged = { ...localKwargs };
1613
+ let changed = false;
1614
+ for (const [k, v] of Object.entries(patch.additional_kwargs)) {
1615
+ if (merged[k] === void 0) {
1616
+ merged[k] = v;
1617
+ changed = true;
1618
+ }
1619
+ }
1620
+ if (changed) next = { ...next, additional_kwargs: merged };
1621
+ }
1622
+ return next;
1623
+ });
1624
+ }
1625
+
1626
+ // src/runtime/thread-runtime.ts
1627
+ import { computed as computed2, effectScope, ref as ref2, shallowRef as shallowRef3 } from "vue";
1628
+
1629
+ // src/runtime/history-pager.ts
1630
+ import { computed, ref } from "vue";
1631
+ function createHistoryPager(options) {
1632
+ const { threadId, transport, firstPage } = options;
1633
+ let cursor = firstPage.nextBeforeSeq;
1634
+ const hasMoreRef = ref(Boolean(firstPage.hasMore) && firstPage.nextBeforeSeq !== void 0);
1635
+ const loading = ref(false);
1636
+ const loadOlder = async () => {
1637
+ if (loading.value) return hasMoreRef.value;
1638
+ if (!hasMoreRef.value || cursor === void 0) {
1639
+ hasMoreRef.value = false;
1640
+ return false;
1641
+ }
1642
+ loading.value = true;
1643
+ try {
1644
+ const page = await transport.fetchMessagesPage(threadId, { beforeSeq: cursor });
1645
+ const pageMessages = runMessagesToMessages(page.messages);
1646
+ options.emitChanges();
1647
+ cursor = page.nextBeforeSeq;
1648
+ hasMoreRef.value = Boolean(page.hasMore) && page.nextBeforeSeq !== void 0;
1649
+ options.onPageLoaded?.(page);
1650
+ return hasMoreRef.value;
1651
+ } finally {
1652
+ loading.value = false;
1653
+ }
1654
+ };
1655
+ return { loadOlder, hasMore: computed(() => hasMoreRef.value), loading };
1656
+ }
1657
+
1658
+ // src/runtime/runtime-bootstrap.ts
1659
+ function patchRows(rows, patches) {
1660
+ if (!patches.size || !rows.length) return rows;
1661
+ return rows.map((row) => {
1662
+ const id = String(row.content?.id || "").trim();
1663
+ const patch = id ? patches.get(id) : void 0;
1664
+ if (!patch) return row;
1665
+ const patched = applySemanticPatches([row.content], patches)[0];
1666
+ return patched === row.content ? row : { ...row, content: patched };
1667
+ });
1668
+ }
1669
+ async function bootstrapRuntime(deps) {
1670
+ const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
1671
+ deps.overlay.applyState(fetched.threadState);
1672
+ deps.runs.fillFromRunsList(fetched.runsList ?? []);
1673
+ deps.runs.enrichFromPage(fetched.messagesPage);
1674
+ deps.runsListMeta.value = (fetched.runsList ?? []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
1675
+ deps.rowsStore.setAll(patchRows(fetched.messagesPage.messages, deps.overlay.getPatches()));
1676
+ deps.setPager(
1677
+ createHistoryPager({
1678
+ threadId: deps.threadId,
1679
+ transport: deps.transport,
1680
+ firstPage: fetched.messagesPage,
1681
+ onPageLoaded: (page) => {
1682
+ deps.runs.enrichFromPage(page);
1683
+ deps.rowsStore.prepend(page.messages);
1684
+ },
1685
+ emitChanges: () => {
1686
+ }
1687
+ })
1688
+ );
1689
+ await deps.refreshTokenUsage();
1690
+ const finalize = () => finalizeAfterStream(deps);
1691
+ const afterFinish = () => afterStreamFinish(deps);
1692
+ deps.streamRef.value = deps.transport.createStream({
1693
+ assistantId: deps.assistantId,
1694
+ threadId: deps.threadId,
1695
+ onCreated: (run) => deps.markStreamRun(run?.run_id),
1696
+ onMetadataEvent: (data) => deps.markStreamRun(data?.run_id),
1697
+ onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
1698
+ onMessageTupleEvent: () => {
1699
+ },
1700
+ onSnapshotMessages: (messages) => deps.applyLiveSnapshot(messages),
1701
+ onStreamStart: deps.onStreamStart,
1702
+ onStreamEnd: finalize,
1703
+ onFinish: afterFinish,
1704
+ onError: (err) => console.error("[runtime] stream error", err)
1705
+ });
1706
+ deps.setInitialized();
1707
+ }
1708
+ function finalizeAfterStream(deps) {
1709
+ deps.onStreamSettled();
1710
+ deps.runs.backfillCurrentRunMetadata(
1711
+ () => deps.valuesChannel.getStreamMessages().map((m) => ({ ...m, runId: deps.runs.currentRunId.value }))
1712
+ );
1713
+ const patches = extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages());
1714
+ deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, patches));
1715
+ }
1716
+ async function afterStreamFinish(deps) {
1717
+ await Promise.all([deps.runs.refreshRuns(), refreshRunsMeta(deps), deps.refreshTokenUsage()]);
1718
+ await reconcileWithPage(deps);
1719
+ await refreshSemanticLayer(deps);
1720
+ }
1721
+ async function refreshRunsMeta(deps) {
1722
+ try {
1723
+ const list = await deps.transport.listRuns(deps.threadId, 20);
1724
+ deps.runsListMeta.value = (Array.isArray(list) ? list : []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
1725
+ } catch (e) {
1726
+ console.warn("[runtime] runs.list \u5237\u65B0\u5931\u8D25", e);
1727
+ }
1728
+ }
1729
+ async function refreshSemanticLayer(deps) {
1730
+ try {
1731
+ const state = await deps.transport.fetchThreadState(deps.threadId);
1732
+ if (!state) return;
1733
+ const semantic = deps.overlay.applyState(state);
1734
+ deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, deps.overlay.getPatches()));
1735
+ if (semantic.patched) {
1736
+ console.debug(`[runtime] \u8BED\u4E49\u5C42\u5237\u65B0 patched=${semantic.patched} cited=${semantic.citedIds.length}`);
1737
+ }
1738
+ } catch (e) {
1739
+ console.warn("[runtime] \u8BED\u4E49\u5C42\u5237\u65B0\u5931\u8D25", e);
1740
+ }
1741
+ }
1742
+ async function reconcileWithPage(deps) {
1743
+ try {
1744
+ const page = await deps.transport.fetchMessagesPage(deps.threadId);
1745
+ if (page.messages.length) deps.rowsStore.mergeLatest(page.messages);
1746
+ } catch (e) {
1747
+ console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
1748
+ }
1749
+ }
1750
+ async function runRuntimeInit(deps, hooks) {
1751
+ hooks.onStart();
1752
+ try {
1753
+ await bootstrapRuntime(deps);
1754
+ } finally {
1755
+ hooks.onEnd();
1756
+ }
1757
+ }
1758
+
1759
+ // src/runtime/runtime-stream-actions.ts
1760
+ function createStreamActions(ctx) {
1761
+ return {
1762
+ submit(text, submitOptions) {
1763
+ const handle = ctx.getHandle();
1764
+ if (!handle) return;
1765
+ ctx.beginStream();
1766
+ const kwargs = submitOptions?.kwargs ?? void 0;
1767
+ ctx.createPendingRun(text, "message", kwargs);
1768
+ const humanMessage = { type: "human", content: [{ type: "text", text }] };
1769
+ humanMessage.additional_kwargs = submitOptions?.kwargs;
1770
+ handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
1771
+ },
1772
+ async joinStream(runId, lastEventId) {
1773
+ const handle = ctx.getHandle();
1774
+ if (!handle) return;
1775
+ ctx.beginStream();
1776
+ ctx.markStreamRun(runId);
1777
+ await handle.joinStream(runId, lastEventId ?? "-1");
1778
+ },
1779
+ stop() {
1780
+ void ctx.options.transport.cancelRun(ctx.options.threadId, ctx.runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
1781
+ ctx.getHandle()?.stop();
1782
+ },
1783
+ async resumeInterrupt(decisions) {
1784
+ const it = ctx.getInterrupt();
1785
+ const interruptId = String(it?.id || "");
1786
+ if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
1787
+ const handle = ctx.getHandle();
1788
+ if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
1789
+ ctx.markResponded(interruptId);
1790
+ ctx.beginStream();
1791
+ const payload = parseHitlPayload(it.value);
1792
+ ctx.createPendingRun(payload ? "\u5DF2\u63D0\u4EA4\u5BA1\u6279\u51B3\u7B56" : "\u5DF2\u63D0\u4EA4\u56DE\u7B54", payload ? "hitl" : "clarification");
1793
+ try {
1794
+ await handle.resumeInterrupt(decisions);
1795
+ } catch (e) {
1796
+ ctx.unmarkResponded(interruptId);
1797
+ throw e;
1798
+ }
1799
+ },
1800
+ async loadOlderMessages() {
1801
+ if (!ctx.getPager()) return false;
1802
+ return ctx.getPager().loadOlder();
1803
+ }
1804
+ };
1805
+ }
1806
+
1807
+ // src/runtime/rows-store.ts
1808
+ import { shallowRef } from "vue";
1809
+ function createRowsStore() {
1810
+ const rows = shallowRef([]);
1811
+ const sortRows = (list) => [...list].sort((a, b) => a.seq - b.seq);
1812
+ return {
1813
+ rows,
1814
+ setAll(next) {
1815
+ rows.value = sortRows(next);
1816
+ },
1817
+ prepend(older) {
1818
+ if (!older.length) return;
1819
+ const seen = new Set(rows.value.map((r) => String(r.content?.id || "")));
1820
+ const fresh = older.filter((r) => {
1821
+ const id = String(r.content?.id || "");
1822
+ if (!id || seen.has(id)) return false;
1823
+ seen.add(id);
1824
+ return true;
1825
+ });
1826
+ if (!fresh.length) return;
1827
+ rows.value = sortRows([...fresh, ...rows.value]);
1828
+ },
1829
+ mergeLatest(latest) {
1830
+ if (!latest.length) return;
1831
+ const byId = new Map(rows.value.map((r) => [String(r.content?.id || ""), r]));
1832
+ for (const row of latest) {
1833
+ const id = String(row.content?.id || "");
1834
+ if (!id) continue;
1835
+ byId.set(id, row);
1836
+ }
1837
+ rows.value = sortRows([...byId.values()]);
1838
+ }
1839
+ };
1840
+ }
1841
+ function extractLiveIncrement(snapshot, lastSeenIds) {
1842
+ const fresh = [];
1843
+ for (const msg of snapshot) {
1844
+ const id = String(msg?.id || "").trim();
1845
+ if (!id || lastSeenIds.has(id)) continue;
1846
+ lastSeenIds.add(id);
1847
+ fresh.push(msg);
1848
+ }
1849
+ return fresh;
1850
+ }
1851
+
1852
+ // src/runtime/values-projection.ts
1853
+ function createValuesChannel(options = {}) {
1854
+ let latestStreamMessages = [];
1855
+ let lastTitle = "";
1856
+ return {
1857
+ beginStream() {
1858
+ latestStreamMessages = [];
1859
+ },
1860
+ applyValuesEvent(data) {
1861
+ if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
1862
+ const title = String(data?.title || "").trim();
1863
+ if (title && title !== lastTitle) {
1864
+ lastTitle = title;
1865
+ options.onTitle?.(title);
1866
+ }
1867
+ },
1868
+ getStreamMessages() {
1869
+ return [...latestStreamMessages];
1870
+ }
1871
+ };
1872
+ }
1873
+
1874
+ // src/store/runs-store.ts
1875
+ import { shallowRef as shallowRef2 } from "vue";
1876
+ function createInterruptState() {
1877
+ const respondedIds = shallowRef2(/* @__PURE__ */ new Set());
1878
+ return {
1879
+ respondedIds,
1880
+ markResponded(id) {
1881
+ const next = new Set(respondedIds.value);
1882
+ next.add(id);
1883
+ respondedIds.value = next;
1884
+ },
1885
+ unmarkResponded(id) {
1886
+ if (!respondedIds.value.has(id)) return;
1887
+ const next = new Set(respondedIds.value);
1888
+ next.delete(id);
1889
+ respondedIds.value = next;
1890
+ }
1891
+ };
1892
+ }
1893
+ function createRunsStore(options) {
1894
+ const runsMap = shallowRef2(/* @__PURE__ */ new Map());
1895
+ const currentRunId = shallowRef2(null);
1896
+ return {
1897
+ runsMap,
1898
+ currentRunId,
1899
+ fillFromRunsList(runsList) {
1900
+ let next = null;
1901
+ for (const run of runsList) {
1902
+ const runId = String(run?.run_id || "").trim();
1903
+ if (!runId) continue;
1904
+ next ?? (next = new Map(runsMap.value));
1905
+ next.set(runId, buildRunInfo(run, options.threadId));
1906
+ }
1907
+ if (next) runsMap.value = next;
1908
+ },
1909
+ ensureRunning(runId) {
1910
+ if (runsMap.value.has(runId)) return;
1911
+ const next = new Map(runsMap.value);
1912
+ ensureRunningRun(next, runId, options.threadId);
1913
+ runsMap.value = next;
1914
+ },
1915
+ async refreshRuns() {
1916
+ try {
1917
+ const runsList = await options.transport.listRuns(options.threadId, 20);
1918
+ if (!Array.isArray(runsList)) return;
1919
+ const merged = new Map(runsMap.value);
1920
+ for (const run of runsList) {
1921
+ const runId = String(run.run_id || "").trim();
1922
+ if (!runId) continue;
1923
+ const info = buildRunInfo(run, options.threadId);
1924
+ const prev = merged.get(runId);
1925
+ if (!prev) {
1926
+ merged.set(runId, info);
1927
+ continue;
1928
+ }
1929
+ const directLatency = buildRunDirectLatencyMs(run);
1930
+ merged.set(runId, {
1931
+ ...info,
1932
+ feedback: info.feedback ?? prev.feedback,
1933
+ latencyMs: directLatency ?? prev.latencyMs ?? info.latencyMs,
1934
+ modelName: info.modelName ?? prev.modelName,
1935
+ finishReason: info.finishReason ?? prev.finishReason
1936
+ });
1937
+ }
1938
+ runsMap.value = merged;
1939
+ } catch (e) {
1940
+ console.warn("[runs-store] refreshRuns failed", e);
1941
+ }
1942
+ },
1943
+ enrichFromPage(page) {
1944
+ const enrichment = extractRunEnrichment(page.messages);
1945
+ let next = null;
1946
+ for (const [runId, patch] of enrichment) {
1947
+ const run = (next ?? runsMap.value).get(runId);
1948
+ if (!run) continue;
1949
+ next ?? (next = new Map(runsMap.value));
1950
+ next.set(runId, {
1951
+ ...run,
1952
+ ...patch.feedback !== void 0 ? { feedback: patch.feedback } : {},
1953
+ ...patch.latencyMs !== void 0 ? { latencyMs: patch.latencyMs } : {}
1954
+ });
1955
+ }
1956
+ if (next) runsMap.value = next;
1957
+ },
1958
+ backfillCurrentRunMetadata(getMessages) {
1959
+ const runId = currentRunId.value;
1960
+ if (!runId) return;
1961
+ const run = runsMap.value.get(runId);
1962
+ if (!run) return;
1963
+ if (run.modelName && run.finishReason) return;
1964
+ const currentRunMessages = getMessages().filter((m) => String(m?.runId || "") === runId);
1965
+ const source = currentRunMessages.length ? currentRunMessages : getMessages();
1966
+ const picked = pickRunMessageMetadata(source);
1967
+ if (!picked.modelName && !picked.finishReason) return;
1968
+ runsMap.value = new Map(runsMap.value).set(runId, {
1969
+ ...run,
1970
+ ...picked.modelName && !run.modelName ? { modelName: picked.modelName } : {},
1971
+ ...picked.finishReason && !run.finishReason ? { finishReason: picked.finishReason } : {}
1972
+ });
1973
+ },
1974
+ patchRun(runId, patch) {
1975
+ const run = runsMap.value.get(runId);
1976
+ if (!run) return;
1977
+ runsMap.value = new Map(runsMap.value).set(runId, { ...run, ...patch });
1978
+ },
1979
+ dispose() {
1980
+ runsMap.value = /* @__PURE__ */ new Map();
1981
+ currentRunId.value = null;
1982
+ }
1983
+ };
1984
+ }
1985
+
1986
+ // src/runtime/thread-runtime.ts
1987
+ var pendingSeq = 0;
1988
+ function newPendingRunId() {
1989
+ pendingSeq += 1;
1990
+ return `local-${Date.now()}-${pendingSeq}`;
1991
+ }
1992
+ function createThreadRuntime(options) {
1993
+ const scope = effectScope();
1994
+ const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
1995
+ const interruptState = createInterruptState();
1996
+ const rowsStore = createRowsStore();
1997
+ const overlay = createSemanticOverlay();
1998
+ const valuesChannel = createValuesChannel({
1999
+ onTitle: (title) => options.onTitle?.(options.threadId, title)
2000
+ });
2001
+ const streamRef = shallowRef3(null);
2002
+ const isInitializing = ref2(false);
2003
+ const streaming = ref2(false);
2004
+ const tokenUsage = shallowRef3(null);
2005
+ let initialized = false;
2006
+ let initPromise = null;
2007
+ let pager = null;
2008
+ const runsListMeta = shallowRef3([]);
2009
+ const liveMessages = shallowRef3([]);
2010
+ const lastSeenLiveIds = /* @__PURE__ */ new Set();
2011
+ const pendingRun = shallowRef3(null);
2012
+ const answers = shallowRef3(/* @__PURE__ */ new Map());
2013
+ const activeRunId = computed2(() => runs.currentRunId.value);
2014
+ const runsProjection = computed2(
2015
+ () => projectRuns({
2016
+ rows: rowsStore.rows.value,
2017
+ liveMessages: liveMessages.value,
2018
+ activeRunId: activeRunId.value,
2019
+ runsList: runsListMeta.value,
2020
+ pendingRun: pendingRun.value,
2021
+ answers: answers.value,
2022
+ twin: options.twin,
2023
+ streaming: streaming.value
2024
+ })
2025
+ );
2026
+ const interrupt = computed2(() => streamRef.value?.interrupt.value);
2027
+ const hasPendingInterrupt = computed2(() => {
2028
+ const it = interrupt.value;
2029
+ return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
2030
+ });
2031
+ const streamError = computed2(() => streamRef.value?.error.value ?? null);
2032
+ const isGenerating = computed2(() => streaming.value);
2033
+ const activeClarification = computed2(() => {
2034
+ const list = runsProjection.value;
2035
+ for (let i = list.length - 1; i >= 0; i--) {
2036
+ const clarifications = list[i].clarifications;
2037
+ for (let c = clarifications.length - 1; c >= 0; c--) {
2038
+ if (clarifications[c].answer === void 0) return clarifications[c];
2039
+ }
2040
+ }
2041
+ return void 0;
2042
+ });
2043
+ const clarificationAnswers = computed2(() => answers.value);
2044
+ const beginStream = () => {
2045
+ valuesChannel.beginStream();
2046
+ overlay.invalidate();
2047
+ runs.currentRunId.value = null;
2048
+ liveMessages.value = [];
2049
+ lastSeenLiveIds.clear();
2050
+ };
2051
+ const streamStarted = () => {
2052
+ streaming.value = true;
2053
+ };
2054
+ const streamSettled = () => {
2055
+ streaming.value = false;
2056
+ pendingRun.value = null;
2057
+ };
2058
+ const markStreamRun = (runIdRaw) => {
2059
+ const runId = String(runIdRaw || "").trim();
2060
+ if (!runId) return;
2061
+ runs.currentRunId.value = runId;
2062
+ runs.ensureRunning(runId);
2063
+ const pending = pendingRun.value;
2064
+ if (pending && pending.runId !== runId) {
2065
+ pendingRun.value = { ...pending, runId };
2066
+ }
2067
+ };
2068
+ const applyLiveSnapshot = (messages) => {
2069
+ if (!streaming.value) return;
2070
+ const fresh = extractLiveIncrement(messages, lastSeenLiveIds);
2071
+ const eligible = fresh.filter((m) => {
2072
+ const t = String(m?.type || "");
2073
+ return t === "ai" || t === "tool";
2074
+ });
2075
+ if (!eligible.length) return;
2076
+ liveMessages.value = [...liveMessages.value, ...eligible];
2077
+ };
2078
+ const refreshTokenUsage = async () => {
2079
+ try {
2080
+ tokenUsage.value = await options.transport.fetchThreadTokenUsage(options.threadId);
2081
+ } catch (e) {
2082
+ console.warn("[runtime] refreshTokenUsage failed", e);
2083
+ }
2084
+ };
2085
+ const doInit = () => runRuntimeInit(
2086
+ {
2087
+ threadId: options.threadId,
2088
+ assistantId: options.assistantId,
2089
+ transport: options.transport,
2090
+ runs,
2091
+ rowsStore,
2092
+ runsListMeta,
2093
+ overlay,
2094
+ valuesChannel,
2095
+ streamRef,
2096
+ setPager: (p) => pager = p,
2097
+ setInitialized: () => initialized = true,
2098
+ markStreamRun,
2099
+ applyLiveSnapshot,
2100
+ onStreamStart: streamStarted,
2101
+ onStreamSettled: streamSettled,
2102
+ refreshTokenUsage
2103
+ },
2104
+ {
2105
+ onStart: () => isInitializing.value = true,
2106
+ onEnd: () => isInitializing.value = false
2107
+ }
2108
+ );
2109
+ const actions = createStreamActions({
2110
+ options,
2111
+ getHandle: () => streamRef.value,
2112
+ beginStream,
2113
+ markStreamRun,
2114
+ getInterrupt: () => streamRef.value?.interrupt.value,
2115
+ markResponded: (id) => interruptState.markResponded(id),
2116
+ unmarkResponded: (id) => interruptState.unmarkResponded(id),
2117
+ getPager: () => pager,
2118
+ runs,
2119
+ createPendingRun: (text, kind, kwargs) => {
2120
+ const pending = { runId: newPendingRunId(), text, kind, kwargs };
2121
+ pendingRun.value = pending;
2122
+ return pending.runId;
2123
+ }
2124
+ });
2125
+ return {
2126
+ threadId: options.threadId,
2127
+ lastViewedAt: Date.now(),
2128
+ touch() {
2129
+ this.lastViewedAt = Date.now();
2130
+ },
2131
+ runs: runsProjection,
2132
+ runsInfo: computed2(() => runs.runsMap.value),
2133
+ activeClarification,
2134
+ isGenerating,
2135
+ isInitializing,
2136
+ interrupt,
2137
+ hasPendingInterrupt,
2138
+ streamError,
2139
+ tokenUsage,
2140
+ hasMoreHistory: computed2(() => pager?.hasMore.value ?? false),
2141
+ loadingHistory: computed2(() => pager?.loading.value ?? false),
2142
+ async init() {
2143
+ if (initialized) return;
2144
+ if (initPromise) return initPromise;
2145
+ initPromise = doInit();
2146
+ try {
2147
+ await initPromise;
2148
+ } finally {
2149
+ initPromise = null;
2150
+ }
2151
+ },
2152
+ submit: actions.submit,
2153
+ joinStream: actions.joinStream,
2154
+ stop: actions.stop,
2155
+ resumeInterrupt: actions.resumeInterrupt,
2156
+ loadOlderMessages: actions.loadOlderMessages,
2157
+ applyFeedback(messageId, feedback) {
2158
+ rowsStore.mergeLatest(
2159
+ rowsStore.rows.value.map((row) => {
2160
+ const id = String(row.content?.id || "");
2161
+ return id === messageId ? { ...row, feedback } : row;
2162
+ })
2163
+ );
2164
+ const runId = runsProjection.value.find((r) => r.rawMessages.some((m) => m.id === messageId))?.runId;
2165
+ if (runId) runs.patchRun(runId, { feedback });
2166
+ },
2167
+ addOptimisticTurn: (body) => {
2168
+ const runId = newPendingRunId();
2169
+ pendingRun.value = { runId, text: body, kind: "message" };
2170
+ },
2171
+ updateAiBody(aiId, body) {
2172
+ rowsStore.mergeLatest(
2173
+ rowsStore.rows.value.map((row) => {
2174
+ const id = String(row.content?.id || "");
2175
+ return id === aiId ? { ...row, content: { ...row.content, content: body } } : row;
2176
+ })
2177
+ );
2178
+ },
2179
+ decorate(messageId, patch) {
2180
+ if (patch.feedback) this.applyFeedback(messageId, patch.feedback);
2181
+ },
2182
+ finalizeTurns() {
2183
+ pendingRun.value = null;
2184
+ },
2185
+ setClarificationAnswer(toolCallId, answer) {
2186
+ const next = new Map(answers.value);
2187
+ next.set(toolCallId, answer);
2188
+ answers.value = next;
2189
+ },
2190
+ clearClarificationAnswers() {
2191
+ if (!answers.value.size) return;
2192
+ answers.value = /* @__PURE__ */ new Map();
2193
+ },
2194
+ clarificationAnswers,
2195
+ dispose() {
2196
+ streamRef.value?.stop();
2197
+ streamRef.value?.dispose?.();
2198
+ runs.dispose();
2199
+ scope.stop();
2200
+ }
2201
+ };
2202
+ }
2203
+
2204
+ // src/runtime/thread-directory.ts
2205
+ import { ref as ref3, shallowReactive } from "vue";
2206
+ var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending", "interrupted"]);
2207
+ function isActiveThreadStatus(status) {
2208
+ return typeof status === "string" && ACTIVE_THREAD_STATUSES.has(status);
2209
+ }
2210
+ var ThreadDirectory = class {
2211
+ constructor(options) {
2212
+ this.threads = ref3([]);
2213
+ this.threadsPagination = ref3({
2214
+ limit: 50,
2215
+ offset: 0,
2216
+ hasMore: true,
2217
+ isLoading: false
2218
+ });
2219
+ this.searchKeyword = "";
2220
+ /** 正在运行但已超出 SSE 连接上限的 thread(仅用于 UI 提示) */
2221
+ this.runningNotConnectedThreadIds = ref3(/* @__PURE__ */ new Set());
2222
+ /** 活跃 runtime 池(shallowReactive 追踪增删,runtime 实例不被深度代理) */
2223
+ this.cachedRuntimes = shallowReactive(/* @__PURE__ */ new Map());
2224
+ this.transport = options.transport;
2225
+ this.assistantId = options.assistantId;
2226
+ this.maxCachedRuntimes = options.maxCachedRuntimes ?? DEFAULT_MAX_CACHED_SESSIONS;
2227
+ this.maxConcurrentStreams = options.maxConcurrentStreams ?? DEFAULT_MAX_CONCURRENT_STREAMS;
2228
+ this.twin = options.twin;
2229
+ this.notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
2230
+ this.defaultThreadTitle = options.defaultThreadTitle ?? "";
2231
+ }
2232
+ // ===== Thread 列表 =====
2233
+ /** 分页拉取历史 thread 列表(失败上抛由调用方提示,不再静默吞错——错误通道契约) */
2234
+ async fetchThreads(reset = false, keyword) {
2235
+ if (this.threadsPagination.value.isLoading) return;
2236
+ if (!reset && !this.threadsPagination.value.hasMore) return;
2237
+ if (keyword !== void 0) this.searchKeyword = keyword.trim();
2238
+ this.threadsPagination.value.isLoading = true;
2239
+ try {
2240
+ if (reset) {
2241
+ this.threads.value = [];
2242
+ this.threadsPagination.value.offset = 0;
2243
+ this.threadsPagination.value.hasMore = true;
2244
+ }
2245
+ const limit = this.threadsPagination.value.limit;
2246
+ const offset = this.threadsPagination.value.offset;
2247
+ const result = await this.transport.searchThreads({
2248
+ limit,
2249
+ offset,
2250
+ ...this.searchKeyword ? { keyword: this.searchKeyword } : {}
2251
+ });
2252
+ const list = Array.isArray(result) ? result : [];
2253
+ this.threads.value = reset ? list : [...this.threads.value, ...list];
2254
+ if (list.length < limit) {
2255
+ this.threadsPagination.value.hasMore = false;
2256
+ } else {
2257
+ this.threadsPagination.value.offset = offset + list.length;
2258
+ }
2259
+ } finally {
2260
+ this.threadsPagination.value.isLoading = false;
2261
+ }
2262
+ }
2263
+ /** 创建新 thread(仅调 transport,不插入列表;确认可生成后由 prependThread 乐观插入) */
2264
+ async createThread(metadata) {
2265
+ try {
2266
+ return await this.transport.createThread(metadata);
2267
+ } catch (error) {
2268
+ console.error("[ThreadDirectory] create thread failed:", error);
2269
+ return null;
2270
+ }
2271
+ }
2272
+ /** 乐观插入列表顶部(已存在忽略;无标题给默认标题——默认文案属 UI 语义,经 notify 同源注入) */
2273
+ prependThread(thread) {
2274
+ if (!thread?.thread_id) return;
2275
+ if (this.threads.value.some((t) => t.thread_id === thread.thread_id)) return;
2276
+ const values = thread.values || {};
2277
+ const title = String(values.title || "").trim();
2278
+ const normalized = {
2279
+ ...thread,
2280
+ values: title ? values : { ...values, title: this.defaultThreadTitle }
2281
+ };
2282
+ this.threads.value = [normalized, ...this.threads.value];
2283
+ }
2284
+ /** 本地更新标题(SSE 期间后端生成 title 后同步侧边栏) */
2285
+ updateThreadTitle(threadId, title) {
2286
+ const trimmed = String(title || "").trim();
2287
+ if (!trimmed) return;
2288
+ const idx = this.threads.value.findIndex((t) => t.thread_id === threadId);
2289
+ if (idx < 0) return;
2290
+ const thread = this.threads.value[idx];
2291
+ const currentTitle = String(thread.values?.title || "").trim();
2292
+ if (currentTitle === trimmed) return;
2293
+ this.threads.value[idx] = { ...thread, values: { ...thread.values, title: trimmed } };
2294
+ }
2295
+ /** 本地移除(不发请求;移动分组成功后同步历史列表) */
2296
+ removeThreadFromList(threadId) {
2297
+ const id = String(threadId || "").trim();
2298
+ if (!id) return;
2299
+ this.threads.value = this.threads.value.filter((t) => t.thread_id !== id);
2300
+ }
2301
+ /** 删除 thread(transport + 本地列表 + 活跃 runtime 清理) */
2302
+ async deleteThread(threadId) {
2303
+ const id = String(threadId || "").trim();
2304
+ if (!id) return false;
2305
+ try {
2306
+ await this.transport.deleteThread(id);
2307
+ this.threads.value = this.threads.value.filter((t) => t.thread_id !== id);
2308
+ this.releaseRuntime(id);
2309
+ return true;
2310
+ } catch (error) {
2311
+ console.error("[ThreadDirectory] delete thread failed:", error);
2312
+ return false;
2313
+ }
2314
+ }
2315
+ // ===== Runtime 池 =====
2316
+ /** 获取或创建 runtime(LRU;达上限时淘汰最久未查看的非生成中会话) */
2317
+ acquireRuntime(threadId) {
2318
+ const existing = this.cachedRuntimes.get(threadId);
2319
+ if (existing) return existing;
2320
+ if (this.cachedRuntimes.size >= this.maxCachedRuntimes) {
2321
+ 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];
2322
+ if (!evictable) return "LIMIT_EXCEEDED";
2323
+ this.releaseRuntime(evictable[0]);
2324
+ }
2325
+ const runtime = createThreadRuntime({
2326
+ threadId,
2327
+ transport: this.transport,
2328
+ assistantId: this.assistantId,
2329
+ twin: this.twin,
2330
+ onTitle: (tid, title) => this.updateThreadTitle(tid, title)
2331
+ });
2332
+ this.cachedRuntimes.set(threadId, runtime);
2333
+ return runtime;
2334
+ }
2335
+ /** 释放指定 runtime(停止流并销毁) */
2336
+ releaseRuntime(threadId) {
2337
+ const runtime = this.cachedRuntimes.get(threadId);
2338
+ if (!runtime) return;
2339
+ runtime.dispose();
2340
+ this.cachedRuntimes.delete(threadId);
2341
+ }
2342
+ getRuntime(threadId) {
2343
+ return this.cachedRuntimes.get(threadId);
2344
+ }
2345
+ isThreadRunning(threadId) {
2346
+ return this.cachedRuntimes.get(threadId)?.isGenerating.value ?? false;
2347
+ }
2348
+ get activeCount() {
2349
+ return this.cachedRuntimes.size;
2350
+ }
2351
+ get generatingCount() {
2352
+ let count = 0;
2353
+ for (const rt of this.cachedRuntimes.values()) if (rt.isGenerating.value) count++;
2354
+ return count;
2355
+ }
2356
+ // ===== 刷新后恢复 =====
2357
+ /**
2358
+ * 恢复未完成 run 的 SSE:按 thread.status(含 interrupted)筛出候选线程并行 listRuns
2359
+ * 取最新 run → init + joinStream。
2360
+ * ⚠️ DeerFlow 语义:thread.status 与 run.status 的 'interrupted' 都表示「run 未完成」
2361
+ *(_derive_thread_status:tasks 非空 → interrupted;涵盖在跑、停在半路、HITL 挂起),
2362
+ * 不等于 LangGraph 官方的「HITL 挂起」——因此 run.status 不作硬判定,最新 run 一律
2363
+ * join:在跑则继续收流;已断则 join 返回 end 帧走 onFinish 对账(runs/state/citation
2364
+ * 刷新),页面收敛到最终状态。join 为只读幂等端点,误 join 无副作用。
2365
+ * 并行确认,串行连接(并发上限内)。
2366
+ */
2367
+ async recoverRunningThreads() {
2368
+ const candidates = this.threads.value.filter((t) => t.thread_id && isActiveThreadStatus(t.status));
2369
+ const results = await Promise.all(
2370
+ candidates.map(async (thread) => {
2371
+ try {
2372
+ const runs = await this.transport.listRuns(thread.thread_id, 5);
2373
+ if (!Array.isArray(runs) || runs.length === 0) return null;
2374
+ const latest = [...runs].sort(
2375
+ (a, b) => String(b?.created_at || "").localeCompare(String(a?.created_at || ""))
2376
+ )[0];
2377
+ return latest?.run_id ? { threadId: thread.thread_id, runId: String(latest.run_id) } : null;
2378
+ } catch (e) {
2379
+ console.warn("[ThreadDirectory] check running run failed", e);
2380
+ return null;
2381
+ }
2382
+ })
2383
+ );
2384
+ const runningInfos = results.filter((r) => !!r);
2385
+ const connected = /* @__PURE__ */ new Set();
2386
+ for (const info of runningInfos.slice(0, this.maxConcurrentStreams)) {
2387
+ const rt = this.acquireRuntime(info.threadId);
2388
+ if (rt === "LIMIT_EXCEEDED") break;
2389
+ try {
2390
+ rt.touch();
2391
+ await rt.init();
2392
+ await rt.joinStream(info.runId, "-1");
2393
+ connected.add(info.threadId);
2394
+ } catch (e) {
2395
+ console.warn("[ThreadDirectory] recover running thread failed", info.threadId, e);
2396
+ }
2397
+ }
2398
+ this.runningNotConnectedThreadIds.value = new Set(
2399
+ runningInfos.filter((i) => !connected.has(i.threadId)).map((i) => i.threadId)
2400
+ );
2401
+ }
2402
+ dispose() {
2403
+ for (const runtime of this.cachedRuntimes.values()) runtime.dispose();
2404
+ this.cachedRuntimes.clear();
2405
+ }
2406
+ };
2407
+
2408
+ // src/core/ChatCore.ts
2409
+ import { computed as computed3, ref as ref4 } from "vue";
2410
+ function createChatCore(options) {
2411
+ const notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
2412
+ const directory = new ThreadDirectory({
2413
+ transport: options.transport,
2414
+ assistantId: options.assistantId || "lead_agent",
2415
+ maxCachedRuntimes: options.maxCachedSessions,
2416
+ maxConcurrentStreams: options.maxConcurrentStreams,
2417
+ twin: options.twin,
2418
+ notify,
2419
+ defaultThreadTitle: options.defaultThreadTitle
2420
+ });
2421
+ const currentThreadId = ref4(null);
2422
+ const threads = computed3(() => directory.threads.value);
2423
+ const threadsPagination = computed3(() => directory.threadsPagination.value);
2424
+ const activeRuntime = computed3(
2425
+ () => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
2426
+ );
2427
+ const runs = computed3(() => activeRuntime.value?.runs.value ?? []);
2428
+ const runsInfo = computed3(() => activeRuntime.value?.runsInfo.value ?? /* @__PURE__ */ new Map());
2429
+ const toolCalls = computed3(
2430
+ () => runs.value.flatMap(
2431
+ (run) => run.tools.map((tool, index) => ({
2432
+ id: tool.callId,
2433
+ call: { id: tool.callId, name: tool.name, args: tool.input },
2434
+ result: tool.result ? { content: tool.result } : void 0,
2435
+ state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
2436
+ index
2437
+ }))
2438
+ )
2439
+ );
2440
+ const activeClarification = computed3(() => activeRuntime.value?.activeClarification.value);
2441
+ const isGenerating = computed3(
2442
+ () => !!activeRuntime.value && activeRuntime.value.isGenerating.value
2443
+ );
2444
+ const isLoadingThread = computed3(() => activeRuntime.value?.isInitializing.value ?? false);
2445
+ const clarificationAnswers = computed3(
2446
+ () => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
2447
+ );
2448
+ const activeInterrupt = computed3(() => activeRuntime.value?.interrupt.value);
2449
+ const hasPendingInterrupt = computed3(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
2450
+ const inputDisabled = computed3(() => isGenerating.value || hasPendingInterrupt.value);
2451
+ const streamError = computed3(() => activeRuntime.value?.streamError.value ?? null);
2452
+ const hasMoreHistory = computed3(() => activeRuntime.value?.hasMoreHistory.value ?? false);
2453
+ const loadingHistory = computed3(() => activeRuntime.value?.loadingHistory.value ?? false);
2454
+ const tokenUsage = computed3(() => activeRuntime.value?.tokenUsage.value ?? null);
2455
+ const runningNotConnectedThreadIds = computed3(() => directory.runningNotConnectedThreadIds.value);
2456
+ const getRunById = (runId) => {
2457
+ const info = runId ? runsInfo.value.get(runId) : void 0;
2458
+ return info;
2459
+ };
2460
+ const getRunsByThreadId = (threadId) => threadId ? Array.from(runsInfo.value.values()).filter((r) => r.threadId === threadId) : [];
2461
+ const ensureThreadId = async () => {
2462
+ if (currentThreadId.value) return { threadId: currentThreadId.value, isNew: false, thread: null };
2463
+ const thread = await directory.createThread({ source: "chat" });
2464
+ if (thread?.thread_id) currentThreadId.value = thread.thread_id;
2465
+ return thread?.thread_id ? { threadId: thread.thread_id, isNew: true, thread } : null;
2466
+ };
2467
+ const acquireSendRuntime = (threadId) => {
2468
+ const current = directory.getRuntime(threadId);
2469
+ if (!current?.isGenerating.value && directory.generatingCount >= directory.maxConcurrentStreams) {
2470
+ 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`);
2471
+ return null;
2472
+ }
2473
+ if (current) return current;
2474
+ const result = directory.acquireRuntime(threadId);
2475
+ if (result === "LIMIT_EXCEEDED") {
2476
+ notify("warning", "\u751F\u6210\u4E2D\u7684\u5BF9\u8BDD\u8FC7\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
2477
+ return null;
2478
+ }
2479
+ return result;
2480
+ };
2481
+ const sendMessage = async (text, sendOptions) => {
2482
+ if (isGenerating.value) return;
2483
+ const trimmed = String(text || "").trim();
2484
+ if (!trimmed) return;
2485
+ const info = await ensureThreadId();
2486
+ if (!info) return;
2487
+ const { threadId, isNew, thread } = info;
2488
+ if (runningNotConnectedThreadIds.value.has(threadId)) {
2489
+ notify("warning", "\u8BE5\u5BF9\u8BDD\u6B63\u5728\u751F\u6210\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210\u540E\u518D\u53D1\u9001");
2490
+ return;
2491
+ }
2492
+ const runtime = acquireSendRuntime(threadId);
2493
+ if (!runtime) return;
2494
+ runtime.touch();
2495
+ if (isNew && thread) directory.prependThread(thread);
2496
+ await runtime.init();
2497
+ runtime.submit(trimmed, sendOptions);
2498
+ };
2499
+ const loadThread = async (threadId) => {
2500
+ const result = directory.acquireRuntime(threadId);
2501
+ if (result === "LIMIT_EXCEEDED") {
2502
+ notify("warning", "\u751F\u6210\u4E2D\u7684\u5BF9\u8BDD\u8FC7\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
2503
+ return;
2504
+ }
2505
+ currentThreadId.value = threadId;
2506
+ result.touch();
2507
+ await result.init();
2508
+ };
2509
+ const regenerateTurn = async (runId) => {
2510
+ if (isGenerating.value) return;
2511
+ const run = runs.value.find((r) => r.runId === runId);
2512
+ const text = run?.input.text ?? "";
2513
+ if (!run || !text.trim()) {
2514
+ notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
2515
+ return;
2516
+ }
2517
+ await sendMessage(text, { kwargs: { ...run.input.kwargs ?? {}, hide_from_ui: false } });
2518
+ };
2519
+ return {
2520
+ runs,
2521
+ turns: runs,
2522
+ isGenerating,
2523
+ isLoadingThread,
2524
+ currentThreadId,
2525
+ threads,
2526
+ threadsPagination,
2527
+ runsInfo,
2528
+ toolCalls,
2529
+ getRunById,
2530
+ getRunsByThreadId,
2531
+ clarificationAnswers,
2532
+ activeClarification,
2533
+ setClarificationAnswer: (toolCallId, answer) => activeRuntime.value?.setClarificationAnswer(toolCallId, answer),
2534
+ clearClarificationAnswers: () => activeRuntime.value?.clearClarificationAnswers(),
2535
+ sendMessage,
2536
+ loadThread,
2537
+ stopGeneration: () => activeRuntime.value?.stop(),
2538
+ clearMessages: () => {
2539
+ currentThreadId.value = null;
2540
+ },
2541
+ applyFeedback: (messageId, feedback) => activeRuntime.value?.applyFeedback(messageId, feedback),
2542
+ regenerateTurn,
2543
+ addOptimisticTurn: (body) => activeRuntime.value?.addOptimisticTurn(body),
2544
+ updateAiBody: (aiId, body) => activeRuntime.value?.updateAiBody(aiId, body),
2545
+ decorate: (messageId, patch) => activeRuntime.value?.decorate(messageId, patch),
2546
+ finalizeTurns: () => activeRuntime.value?.finalizeTurns(),
2547
+ fetchThreads: (reset, keyword) => directory.fetchThreads(reset, keyword),
2548
+ deleteThread: async (threadId) => {
2549
+ const deleted = await directory.deleteThread(threadId);
2550
+ if (deleted && currentThreadId.value === threadId) currentThreadId.value = null;
2551
+ return deleted;
2552
+ },
2553
+ updateThreadTitle: (threadId, title) => directory.updateThreadTitle(threadId, title),
2554
+ removeThreadFromList: (threadId) => directory.removeThreadFromList(threadId),
2555
+ isThreadRunning: (threadId) => directory.isThreadRunning(threadId),
2556
+ runningNotConnectedThreadIds,
2557
+ recoverRunningThreads: () => directory.recoverRunningThreads(),
2558
+ activeInterrupt,
2559
+ interrupt: activeInterrupt,
2560
+ hasPendingInterrupt,
2561
+ inputDisabled,
2562
+ streamError,
2563
+ hasMoreHistory,
2564
+ loadingHistory,
2565
+ tokenUsage,
2566
+ loadOlderMessages: async () => await activeRuntime.value?.loadOlderMessages() ?? false,
2567
+ resumeInterrupt: async (decisions) => {
2568
+ const runtime = activeRuntime.value;
2569
+ if (!runtime) throw new Error("\u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u7684\u4F1A\u8BDD");
2570
+ await runtime.resumeInterrupt(decisions);
2571
+ },
2572
+ loadArtifactContent: async (path) => {
2573
+ const threadId = currentThreadId.value;
2574
+ if (!threadId || !activeRuntime.value) throw new Error("\u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u7684\u4F1A\u8BDD\uFF0C\u65E0\u6CD5\u52A0\u8F7D artifact \u5185\u5BB9");
2575
+ return options.transport.fetchArtifactContent(threadId, path, { full: true });
2576
+ },
2577
+ dispose: () => directory.dispose()
2578
+ };
2579
+ }
2580
+
2581
+ export {
2582
+ DEFAULT_MAX_CACHED_SESSIONS,
2583
+ DEFAULT_MAX_CONCURRENT_STREAMS,
2584
+ DEFAULT_ASSISTANT_ID,
2585
+ formatStr,
2586
+ INJECTED_TAGS,
2587
+ isInjectedElement,
2588
+ collectVisibleText,
2589
+ collectTextKeepSxin,
2590
+ tokenizeSxin,
2591
+ genMessageId,
2592
+ genBlockId,
2593
+ parseHitlPayload,
2594
+ getAllowedDecisions,
2595
+ normalizeForCompare,
2596
+ isSameArgs,
2597
+ buildHitlDecisions,
2598
+ buildRejectDecisions,
2599
+ buildInterruptReviewBlock,
2600
+ formatAnswerText,
2601
+ extractThreadInfo,
2602
+ buildHumanInputResponse,
2603
+ extractStateMessages,
2604
+ mergeStateWithPageMessages,
2605
+ ensureRunningRun,
2606
+ MESSAGE_TYPE_NORMALIZE,
2607
+ normalizeMessageType,
2608
+ toRunMessage,
2609
+ extractRunEnrichment,
2610
+ backfillRunMessageFeedback,
2611
+ runMessagesToMessages,
2612
+ stateMessagesToRunMessages,
2613
+ simpleHash,
2614
+ readMessageContentText,
2615
+ extractTextFromMessage,
2616
+ extractAiContentFromMessage,
2617
+ isVisibleUserMessage,
2618
+ extractUserMessageTexts,
2619
+ isHiddenUserMessage,
2620
+ isWriteFileToolName,
2621
+ getToolCallArtifactMeta,
2622
+ resolveReportArtifactKind,
2623
+ extractTitleFromArtifactPath,
2624
+ OUTLINE_MAX_LEVEL,
2625
+ normalizeOutline,
2626
+ validateOutline,
2627
+ createEmptySubChapter,
2628
+ ensureOutlineContentThemes,
2629
+ parseMarkdownToOutline,
2630
+ isReportBodyHtml,
2631
+ extractReportTitleFromBody,
2632
+ isHumanMessage,
2633
+ parseHumanMessageId,
2634
+ getHumanMessageBaseId,
2635
+ isAiMessage,
2636
+ isToolMessage,
2637
+ deriveToolsFromMessages,
2638
+ normalizeUsage,
2639
+ sliceBodySegments,
2640
+ rowMessageId,
2641
+ isUserEchoRow,
2642
+ groupRowsByRun,
2643
+ extractFromToolResult,
2644
+ asArgsObject,
2645
+ pickRicherArgs,
2646
+ emptyRunItem,
2647
+ assembleRun,
2648
+ extractInputFromRows,
2649
+ mapBackendStatus,
2650
+ projectRuns,
2651
+ buildRunInfo,
2652
+ buildRunMeta,
2653
+ buildRunDirectLatencyMs,
2654
+ pickRunMessageMetadata,
2655
+ extractSemanticPatchesFromMessages,
2656
+ createSemanticOverlay,
2657
+ applySemanticPatches,
2658
+ createThreadRuntime,
2659
+ ThreadDirectory,
2660
+ createChatCore
2661
+ };