@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.
@@ -27,345 +27,18 @@ __export(vue_exports, {
27
27
  module.exports = __toCommonJS(vue_exports);
28
28
 
29
29
  // src/core/ChatCore.ts
30
- var import_vue8 = require("vue");
30
+ var import_vue6 = require("vue");
31
31
 
32
32
  // src/runtime/thread-directory.ts
33
- var import_vue7 = require("vue");
33
+ var import_vue5 = require("vue");
34
34
 
35
35
  // src/runtime/thread-runtime.ts
36
- var import_vue6 = require("vue");
37
-
38
- // src/message/dict-merge.ts
39
- var MERGE_IGNORE_KEYS = ["index", "created", "timestamp"];
40
- var MERGE_RIGHT_WINS_KEYS = ["id", "name", "output_version", "model_provider"];
41
- function hasMergeableIndex(value) {
42
- if (typeof value !== "object" || value === null) return false;
43
- const idx = value.index;
44
- return typeof idx === "number" || typeof idx === "string";
45
- }
46
- function hasMergeableId(value) {
47
- if (typeof value !== "object" || value === null) return false;
48
- const id = value.id;
49
- return id != null && id !== "";
50
- }
51
- function findMergeTarget(merged, item) {
52
- if (!hasMergeableIndex(item) && !hasMergeableId(item)) return -1;
53
- return merged.findIndex((leftItem) => {
54
- const leftHasIndex = hasMergeableIndex(leftItem);
55
- const leftHasId = hasMergeableId(leftItem);
56
- const itemHasIndex = hasMergeableIndex(item);
57
- const itemHasId = hasMergeableId(item);
58
- if (itemHasIndex && leftHasIndex) {
59
- if (leftItem.index !== item.index) return false;
60
- if (leftHasId && itemHasId)
61
- return leftItem.id === item.id;
62
- return true;
63
- }
64
- if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {
65
- return leftItem.id === item.id;
66
- }
67
- return false;
68
- });
69
- }
70
- function mergeStringField(key, left, right) {
71
- if (key === "type") return left;
72
- if (MERGE_RIGHT_WINS_KEYS.includes(key)) return right || left;
73
- if (MERGE_IGNORE_KEYS.includes(key)) return left;
74
- return left + right;
75
- }
76
- function mergeNumberField(key, left, right) {
77
- return MERGE_IGNORE_KEYS.includes(key) ? left : left + right;
78
- }
79
- function mergeDicts(left, right) {
80
- if (left == null) return right;
81
- if (right == null) return left;
82
- if (Array.isArray(left) && Array.isArray(right)) return mergeLists(left, right);
83
- if (typeof left === "string" && typeof right === "string") return left + right;
84
- if (typeof left === "number" && typeof right === "number") return left + right;
85
- if (typeof left === "object" && typeof right === "object") {
86
- const merged = { ...left };
87
- for (const [key, value] of Object.entries(right)) {
88
- const l = merged[key];
89
- if (l == null) {
90
- merged[key] = value;
91
- } else if (value == null) {
92
- continue;
93
- } else if (typeof l === "string" && typeof value === "string") {
94
- merged[key] = mergeStringField(key, l, value);
95
- } else if (typeof l === "number" && typeof value === "number") {
96
- merged[key] = mergeNumberField(key, l, value);
97
- } else if (Array.isArray(l) && Array.isArray(value)) {
98
- merged[key] = mergeLists(l, value);
99
- } else if (typeof l === "object" && typeof value === "object") {
100
- merged[key] = mergeDicts(l, value);
101
- } else {
102
- merged[key] = value;
103
- }
104
- }
105
- return merged;
106
- }
107
- return right;
108
- }
109
- function mergeLists(left, right) {
110
- const merged = [...left];
111
- for (const item of right) {
112
- const target = findMergeTarget(merged, item);
113
- if (target !== -1) {
114
- merged[target] = mergeDicts(merged[target], item);
115
- } else if (typeof item === "object" && item !== null && "text" in item && item.text === "") {
116
- continue;
117
- } else {
118
- merged.push(item);
119
- }
120
- }
121
- return merged;
122
- }
123
- function mergeContent(left, right) {
124
- if (left == null) return right;
125
- if (right == null) return left;
126
- if (typeof left === "string" && typeof right === "string") return left + right;
127
- const leftArr = Array.isArray(left) ? left : [left];
128
- const rightArr = Array.isArray(right) ? right : [right];
129
- return mergeLists(leftArr, rightArr);
130
- }
131
- function parsePartialJson(text) {
132
- const tryParse = (s) => {
133
- try {
134
- return JSON.parse(s);
135
- } catch {
136
- return void 0;
137
- }
138
- };
139
- const direct = tryParse(text);
140
- if (direct !== void 0) return direct;
141
- let fixed = text;
142
- let inStr = false;
143
- let escaped = false;
144
- for (const ch of fixed) {
145
- if (escaped) {
146
- escaped = false;
147
- continue;
148
- }
149
- if (ch === "\\") {
150
- escaped = true;
151
- continue;
152
- }
153
- if (ch === '"') inStr = !inStr;
154
- }
155
- if (inStr) fixed += '"';
156
- const closers = [];
157
- for (const ch of fixed) {
158
- if (ch === "{") closers.push("}");
159
- else if (ch === "[") closers.push("]");
160
- else if (ch === "}" || ch === "]") closers.pop();
161
- }
162
- fixed += closers.reverse().join("");
163
- const repaired = tryParse(fixed);
164
- return repaired === void 0 ? null : repaired;
165
- }
166
- function collapseToolCallChunks(chunks) {
167
- const groups = [];
168
- for (const chunk of chunks) {
169
- const matched = groups.findIndex((group) => {
170
- const match = group[0];
171
- if (chunk?.id && chunk?.index !== void 0) return chunk.id === match.id && chunk.index === match.index;
172
- if (chunk?.id) return chunk.id === match.id;
173
- if (chunk?.index !== void 0) return chunk.index === match.index;
174
- return false;
175
- });
176
- if (matched !== -1) groups[matched].push(chunk);
177
- else groups.push([chunk]);
178
- }
179
- const toolCalls = [];
180
- const invalidToolCalls = [];
181
- for (const group of groups) {
182
- const name = group[0]?.name ?? "";
183
- const joinedArgs = group.map((c) => c?.args || "").join("");
184
- const argsStr = joinedArgs.trim().length ? joinedArgs.trim() : "{}";
185
- const id = group.find((c) => c?.id)?.id ?? group[0]?.id;
186
- const parsed = parsePartialJson(argsStr);
187
- if (!id || parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
188
- invalidToolCalls.push({ name, args: argsStr, id, error: "Malformed args.", type: "invalid_tool_call" });
189
- } else {
190
- toolCalls.push({ name, args: parsed, id, type: "tool_call" });
191
- }
192
- }
193
- return { tool_calls: toolCalls, invalid_tool_calls: invalidToolCalls };
194
- }
195
- function extractToolCallsFromContent(content) {
196
- if (!Array.isArray(content)) return [];
197
- return content.flatMap((block) => {
198
- if (block == null || typeof block !== "object") return [];
199
- const record = block;
200
- if (record.type !== "tool_call" && record.type !== "tool_use") return [];
201
- const rawArgs = record.args ?? record.input;
202
- let args = {};
203
- if (rawArgs != null && typeof rawArgs === "object" && !Array.isArray(rawArgs)) args = rawArgs;
204
- else if (typeof rawArgs === "string" && rawArgs.length > 0) {
205
- const parsed = parsePartialJson(rawArgs);
206
- if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) args = parsed;
207
- }
208
- return [{ id: record.id ?? "", name: record.name ?? "", args, type: "tool_call" }];
209
- });
210
- }
211
- function mergeMessageDicts(prev, next) {
212
- const merged = { ...prev };
213
- for (const [key, value] of Object.entries(next)) {
214
- if (key === "type") {
215
- if (merged.type == null) merged.type = value;
216
- continue;
217
- }
218
- if (MERGE_RIGHT_WINS_KEYS.includes(key)) {
219
- if (value != null && value !== "") merged[key] = value;
220
- continue;
221
- }
222
- if (key === "content") {
223
- merged.content = mergeContent(prev.content, value);
224
- } else if (key === "tool_call_chunks") {
225
- const prevChunks = Array.isArray(prev.tool_call_chunks) ? prev.tool_call_chunks : [];
226
- const nextChunks = Array.isArray(value) ? value : [];
227
- const chunks = mergeLists(prevChunks, nextChunks);
228
- merged.tool_call_chunks = chunks;
229
- const collapsed = collapseToolCallChunks(chunks);
230
- merged.tool_calls = collapsed.tool_calls;
231
- merged.invalid_tool_calls = collapsed.invalid_tool_calls;
232
- } else {
233
- merged[key] = mergeDicts(prev[key], value);
234
- }
235
- }
236
- if (!Array.isArray(merged.tool_calls) || merged.tool_calls.length === 0) {
237
- const extracted = extractToolCallsFromContent(merged.content);
238
- if (extracted.length > 0) merged.tool_calls = extracted;
239
- }
240
- return merged;
241
- }
242
-
243
- // src/protocol/chunk-buffer.ts
244
- function normalizeEntry(raw) {
245
- const rawType = String(raw.type || "");
246
- if (rawType === "RemoveMessage") return { ...raw, type: "remove" };
247
- return raw;
248
- }
249
- function stampRunId(msg, streamRunId) {
250
- if (String(msg.runId || "").trim()) return msg;
251
- const kwargsRunId = String(msg.additional_kwargs?.run_id || "").trim();
252
- const rid = kwargsRunId || String(streamRunId || "").trim();
253
- if (!rid) return msg;
254
- return { ...msg, runId: rid };
255
- }
256
- function createChunkBuffer(options) {
257
- const schedule = options.schedule ?? ((fn) => setTimeout(fn, 0));
258
- const pending = /* @__PURE__ */ new Map();
259
- const accumulated = /* @__PURE__ */ new Map();
260
- let order = [];
261
- const dirty = /* @__PURE__ */ new Set();
262
- let scheduled = false;
263
- let timer = null;
264
- let streamRunId;
265
- const cancelSchedule = () => {
266
- scheduled = false;
267
- if (timer !== null) clearTimeout(timer);
268
- timer = null;
269
- };
270
- const scheduleFlush = () => {
271
- if (scheduled) return;
272
- scheduled = true;
273
- timer = schedule(() => {
274
- scheduled = false;
275
- timer = null;
276
- flush();
277
- });
278
- };
279
- function flush() {
280
- if (!order.length) return;
281
- const instructions = [];
282
- for (const id of order) {
283
- const entry = pending.get(id);
284
- if (!entry) continue;
285
- if (entry.isClear) {
286
- instructions.push({ kind: "clear" });
287
- accumulated.clear();
288
- continue;
289
- }
290
- if (entry.isRemove) {
291
- instructions.push({ kind: "remove", id });
292
- accumulated.delete(id);
293
- continue;
294
- }
295
- const base = accumulated.get(id);
296
- const merged = base ? entry.parts.reduce((acc, c) => mergeMessageDicts(acc, c), base) : entry.parts.reduce(mergeMessageDicts);
297
- accumulated.set(id, merged);
298
- instructions.push({ kind: "upsert", message: stampRunId(merged, streamRunId) });
299
- }
300
- pending.clear();
301
- order = [];
302
- dirty.clear();
303
- if (instructions.length) options.emit(instructions);
304
- }
305
- return {
306
- add(serialized) {
307
- if (!serialized || typeof serialized !== "object") return;
308
- const raw = serialized;
309
- const rawType = String(raw.type || "");
310
- const entry = normalizeEntry(raw);
311
- const type = String(entry.type || "");
312
- const id = String(entry.id || "").trim();
313
- if (!id) return;
314
- if (type === "remove") {
315
- if (id === "__remove_all__") {
316
- pending.set(id, { parts: [], isClear: true });
317
- } else {
318
- pending.set(id, { parts: [], isRemove: true });
319
- }
320
- if (!dirty.has(id)) {
321
- dirty.add(id);
322
- order.push(id);
323
- }
324
- scheduleFlush();
325
- return;
326
- }
327
- const isChunk = rawType.endsWith("MessageChunk");
328
- const existing = pending.get(id);
329
- if (!existing || existing.isRemove) {
330
- pending.set(id, { parts: [entry] });
331
- } else if (!isChunk) {
332
- existing.parts = [entry];
333
- } else {
334
- existing.parts.push(entry);
335
- }
336
- if (!dirty.has(id)) {
337
- dirty.add(id);
338
- order.push(id);
339
- }
340
- scheduleFlush();
341
- },
342
- noteStreamRunId(runId) {
343
- const trimmed = String(runId || "").trim();
344
- if (trimmed) streamRunId = trimmed;
345
- },
346
- reset() {
347
- cancelSchedule();
348
- pending.clear();
349
- order = [];
350
- dirty.clear();
351
- accumulated.clear();
352
- streamRunId = void 0;
353
- },
354
- flush,
355
- dispose() {
356
- cancelSchedule();
357
- pending.clear();
358
- order = [];
359
- dirty.clear();
360
- accumulated.clear();
361
- }
362
- };
363
- }
36
+ var import_vue4 = require("vue");
364
37
 
365
38
  // src/runtime/history-pager.ts
366
39
  var import_vue = require("vue");
367
40
 
368
- // src/types/sxin-message.ts
41
+ // src/parser/sxin-message.ts
369
42
  var asSxin = (m) => m ?? {};
370
43
 
371
44
  // src/parser/run-messages.ts
@@ -437,7 +110,7 @@ function createHistoryPager(options) {
437
110
  try {
438
111
  const page = await transport.fetchMessagesPage(threadId, { beforeSeq: cursor });
439
112
  const pageMessages = runMessagesToMessages(page.messages);
440
- options.emitChanges({ kind: "prepend", messages: pageMessages });
113
+ options.emitChanges();
441
114
  cursor = page.nextBeforeSeq;
442
115
  hasMoreRef.value = Boolean(page.hasMore) && page.nextBeforeSeq !== void 0;
443
116
  options.onPageLoaded?.(page);
@@ -449,267 +122,11 @@ function createHistoryPager(options) {
449
122
  return { loadOlder, hasMore: (0, import_vue.computed)(() => hasMoreRef.value), loading };
450
123
  }
451
124
 
452
- // src/parser/thread.ts
453
- function extractStateMessages(state) {
454
- if (!state || typeof state !== "object") return [];
455
- const values = state.values;
456
- if (!values || typeof values !== "object") return [];
457
- const messages = values.messages;
458
- return Array.isArray(messages) ? messages : [];
459
- }
460
- function ensureRunningRun(runMap, runId, threadId) {
461
- let runInfo = runMap.get(runId);
462
- if (!runInfo) {
463
- runInfo = {
464
- runId,
465
- threadId: threadId || "",
466
- status: "running"
467
- };
468
- runMap.set(runId, runInfo);
469
- }
470
- return runInfo;
471
- }
472
-
473
- // src/runtime/runtime-bootstrap.ts
474
- async function bootstrapRuntime(deps) {
475
- const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
476
- deps.valuesChannel.applyInitialValues(fetched.values);
477
- deps.valuesChannel.applyThreadState(fetched.threadState);
478
- deps.enrichments.applyFromStateMessages(extractStateMessages(fetched.threadState));
479
- deps.runs.fillFromRunsList(fetched.runsList ?? []);
480
- deps.runs.enrichFromPage(fetched.messagesPage);
481
- const pageMessages = runMessagesToMessages(fetched.messagesPage.messages);
482
- if (pageMessages.length) deps.store.applyInstructions([{ kind: "prepend", messages: pageMessages }]);
483
- deps.setPager(
484
- createHistoryPager({
485
- threadId: deps.threadId,
486
- transport: deps.transport,
487
- firstPage: fetched.messagesPage,
488
- onPageLoaded: (page) => deps.runs.enrichFromPage(page),
489
- emitChanges: (batch) => deps.store.applyInstructions([batch])
490
- })
491
- );
492
- await deps.refreshTokenUsage();
493
- deps.setChunkBuffer(createChunkBuffer({ emit: (ins) => deps.store.applyInstructions(ins) }));
494
- const finalize = () => finalizeAfterStream(deps);
495
- const afterFinish = () => afterStreamFinish(deps);
496
- deps.streamRef.value = deps.transport.createStream({
497
- assistantId: deps.assistantId,
498
- threadId: deps.threadId,
499
- onCreated: (run) => deps.markStreamRun(run?.run_id),
500
- onMetadataEvent: (data) => deps.markStreamRun(data?.run_id),
501
- onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
502
- onMessageTupleEvent: (serialized, metadata) => deps.getChunkBuffer()?.add(serialized, metadata),
503
- onStreamStart: deps.onStreamStart,
504
- onStreamEnd: finalize,
505
- onFinish: afterFinish,
506
- onError: (err) => console.error("[runtime] stream error", err)
507
- });
508
- deps.setInitialized();
509
- }
510
- function finalizeAfterStream(deps) {
511
- deps.getChunkBuffer()?.flush();
512
- deps.enrichments.applyFromStateMessages(deps.valuesChannel.getStreamMessages());
513
- deps.store.applyInstructions(buildValuesReplaceInstructions(deps.store, deps.valuesChannel.getStreamMessages()));
514
- deps.store.applyInstructions([{ kind: "finalize" }]);
515
- deps.runs.backfillCurrentRunMetadata(() => deps.store.getMessages());
516
- }
517
- function buildValuesReplaceInstructions(store, streamMessages) {
518
- const instructions = [];
519
- for (const msg of streamMessages) {
520
- const id = String(msg?.id || "").trim();
521
- if (!id) continue;
522
- const existing = store.getEntity(id);
523
- if (!existing) continue;
524
- if (existing.source !== "stream" || existing.epoch !== store.streamEpoch) continue;
525
- const runId = String(existing.msg?.runId || existing.msg?.additional_kwargs?.run_id || "").trim();
526
- const next = runId ? { ...msg, runId } : msg;
527
- instructions.push({ kind: "upsert", message: next });
528
- }
529
- return instructions;
530
- }
531
- async function afterStreamFinish(deps) {
532
- await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
533
- await reconcileWithPage(deps);
534
- await applyCitationsFallback(deps);
535
- }
536
- async function reconcileWithPage(deps) {
537
- try {
538
- const page = await deps.transport.fetchMessagesPage(deps.threadId);
539
- const messages = runMessagesToMessages(page.messages);
540
- if (messages.length) {
541
- deps.store.applyInstructions(messages.map((message) => ({ kind: "upsert", message, source: "page" })));
542
- }
543
- } catch (e) {
544
- console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
545
- }
546
- }
547
- async function applyCitationsFallback(deps) {
548
- if (deps.valuesChannel.getStreamMessages().length > 0) return;
549
- try {
550
- const state = await deps.transport.fetchThreadState(deps.threadId);
551
- if (!state) return;
552
- deps.enrichments.applyFromStateMessages(extractStateMessages(state));
553
- } catch (e) {
554
- console.warn("[runtime] citation state \u515C\u5E95\u63D0\u53D6\u5931\u8D25", e);
555
- }
556
- }
557
- async function runRuntimeInit(deps, hooks) {
558
- hooks.onStart();
559
- try {
560
- await bootstrapRuntime(deps);
561
- } finally {
562
- hooks.onEnd();
563
- }
564
- }
565
-
566
- // src/protocol/values-channel.ts
567
- var import_vue2 = require("vue");
568
- var import_ui = require("@langchain/langgraph-sdk/ui");
569
-
570
- // src/protocol/interrupt-reconcile.ts
571
- function reconcileInterrupts(prevValues, nextValues, firstEvent) {
572
- let base = prevValues;
573
- if (firstEvent && base && "__interrupt__" in base) {
574
- const { __interrupt__: _dropped, ...rest } = base;
575
- base = rest;
576
- }
577
- if (nextValues && typeof nextValues === "object" && "__interrupt__" in nextValues) {
578
- let interrupts = nextValues.__interrupt__;
579
- const prevInterrupts = base?.__interrupt__;
580
- if (Array.isArray(interrupts) && interrupts.length > 0 && Array.isArray(prevInterrupts)) {
581
- const merged = [...prevInterrupts];
582
- const existingIds = new Set(merged.map((i) => i?.id).filter((id) => id != null));
583
- for (const interrupt of interrupts) {
584
- const id = interrupt?.id;
585
- if (id != null) {
586
- if (existingIds.has(id)) continue;
587
- existingIds.add(id);
588
- }
589
- merged.push(interrupt);
590
- }
591
- interrupts = merged;
592
- }
593
- return { ...base, __interrupt__: interrupts };
594
- }
595
- if (nextValues && typeof nextValues === "object") {
596
- if (base && "__interrupt__" in base && Array.isArray(base.__interrupt__)) {
597
- return { ...nextValues, __interrupt__: base.__interrupt__ };
598
- }
599
- return nextValues;
600
- }
601
- return nextValues ?? {};
602
- }
603
-
604
- // src/protocol/values-channel.ts
605
- function createValuesChannel(options = {}) {
606
- const valuesRef = (0, import_vue2.shallowRef)({});
607
- const threadStateRef = (0, import_vue2.shallowRef)(void 0);
608
- let firstEvent = true;
609
- let lastTitle = "";
610
- let latestStreamMessages = [];
611
- const readStateMessages = () => {
612
- const msgs = threadStateRef.value?.values?.messages;
613
- return Array.isArray(msgs) ? [...msgs] : [];
614
- };
615
- const readStreamMessages = () => [...latestStreamMessages];
616
- return {
617
- applyInitialValues(next) {
618
- valuesRef.value = { ...next ?? {} };
619
- },
620
- applyThreadState(state) {
621
- threadStateRef.value = state;
622
- },
623
- beginStream() {
624
- firstEvent = true;
625
- threadStateRef.value = void 0;
626
- latestStreamMessages = [];
627
- },
628
- applyValuesEvent(data) {
629
- const reconciled = reconcileInterrupts(valuesRef.value, data, firstEvent);
630
- firstEvent = false;
631
- valuesRef.value = reconciled;
632
- if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
633
- const title = String(reconciled?.title || "").trim();
634
- if (title && title !== lastTitle) {
635
- lastTitle = title;
636
- options.onTitle?.(title);
637
- }
638
- },
639
- getValues() {
640
- return valuesRef.value;
641
- },
642
- getStateMessages: readStateMessages,
643
- getStreamMessages: readStreamMessages,
644
- getInterrupt({ isLoading, error }) {
645
- return (0, import_ui.extractInterrupts)(valuesRef.value, {
646
- isLoading,
647
- threadState: threadStateRef.value,
648
- error
649
- });
650
- }
651
- };
652
- }
653
-
654
- // src/store/thread-state.ts
655
- var import_vue3 = require("vue");
656
-
657
125
  // src/parser/group-builder-helper.ts
658
- function isHumanMessage(msg) {
659
- return String(asSxin(msg).type || "") === "human";
660
- }
661
- function parseHumanMessageId(id) {
662
- const raw = String(id || "");
663
- const match = raw.match(/^(.*?)__(memory|user)(\([^)]*\))?$/i);
664
- if (!match) return { baseId: raw, variant: null };
665
- return { baseId: match[1], variant: match[2].toLowerCase() };
666
- }
667
- function getHumanMessageBaseId(id) {
668
- return parseHumanMessageId(id).baseId;
669
- }
670
126
  function isAiMessage(msg) {
671
127
  const t = String(asSxin(msg).type || "");
672
128
  return ["ai", "AIMessage", "AIMessageChunk"].includes(t);
673
129
  }
674
- function isToolMessage(msg) {
675
- return String(asSxin(msg).type || "") === "tool";
676
- }
677
- function deriveToolsFromMessages(messages) {
678
- const tools = [];
679
- const byId = /* @__PURE__ */ new Map();
680
- for (const msg of messages) {
681
- const m = asSxin(msg);
682
- const toolCalls = m.tool_calls;
683
- if (Array.isArray(toolCalls)) {
684
- for (const tc of toolCalls) {
685
- const id = String(tc?.id || "").trim();
686
- if (!id || byId.has(id)) continue;
687
- const tool = { id, call: tc, aiMessage: msg, state: "pending", index: tools.length };
688
- byId.set(id, tool);
689
- tools.push(tool);
690
- }
691
- }
692
- const toolCallId = String(m.tool_call_id || "").trim();
693
- if (!toolCallId) continue;
694
- const state = m.status === "error" ? "error" : "completed";
695
- const existing = byId.get(toolCallId);
696
- if (existing) {
697
- existing.result = msg;
698
- existing.state = state;
699
- } else {
700
- const tool = {
701
- id: toolCallId,
702
- call: { id: toolCallId, name: String(m.name || ""), args: {} },
703
- result: msg,
704
- state,
705
- index: tools.length
706
- };
707
- byId.set(toolCallId, tool);
708
- tools.push(tool);
709
- }
710
- }
711
- return tools;
712
- }
713
130
  function normalizeUsage(raw) {
714
131
  if (!raw || typeof raw !== "object") return void 0;
715
132
  const r = raw;
@@ -747,37 +164,14 @@ function applyUsageDetails(usage, r) {
747
164
  }
748
165
  }
749
166
 
750
- // src/parser/thread-info.ts
751
- var humanInputResponseRule = {
752
- key: "clarificationAnswers",
753
- extract(msg, acc) {
754
- const additionalKwargs = msg?.additional_kwargs;
755
- const response = additionalKwargs?.human_input_response;
756
- const requestId = String(response?.request_id || "").trim().replace("clarification:", "");
757
- if (requestId && response?.value !== void 0) {
758
- acc.clarificationAnswers.set(requestId, String(response.value));
759
- }
760
- }
761
- };
762
- var THREAD_INFO_RULES = [humanInputResponseRule];
763
- function extractThreadInfo(messages) {
764
- const info = { clarificationAnswers: /* @__PURE__ */ new Map() };
765
- for (const msg of messages ?? []) {
766
- for (const rule of THREAD_INFO_RULES) {
767
- rule.extract(msg, info);
768
- }
769
- }
770
- return info;
771
- }
772
-
773
- // src/message/run-info.ts
167
+ // src/runtime/run-info.ts
774
168
  function buildRunInfo(run, threadId) {
775
169
  return {
776
170
  runId: String(run?.run_id || "").trim(),
777
171
  threadId: String(threadId || "").trim(),
778
172
  usage: buildRunUsage(run),
779
173
  latencyMs: buildRunLatencyMs(run),
780
- finishReason: toOptionalString(run?.finish_reason),
174
+ finishReason: toOptionalString(run?.stop_reason ?? run?.finish_reason),
781
175
  modelName: toOptionalString(run?.model_name),
782
176
  status: buildRunStatus(run),
783
177
  createdAt: buildRunCreatedAt(run)
@@ -799,6 +193,32 @@ function buildRunStatus(run) {
799
193
  function buildRunCreatedAt(run) {
800
194
  return run?.created_at ? Number(new Date(run.created_at)) : void 0;
801
195
  }
196
+ function buildRunMeta(run) {
197
+ const runId = String(run?.run_id || "").trim();
198
+ if (!runId) return null;
199
+ const inputMessages = run?.kwargs?.input?.messages ?? [];
200
+ const totalTokens = Number(run?.total_tokens);
201
+ const tokens = Number.isFinite(totalTokens) && totalTokens > 0 ? {
202
+ total: totalTokens,
203
+ input: Number(run?.total_input_tokens) || 0,
204
+ output: Number(run?.total_output_tokens) || 0,
205
+ ...Number.isFinite(Number(run?.llm_call_count)) ? { llmCallCount: Number(run.llm_call_count) } : {},
206
+ byCaller: {
207
+ leadAgent: Number(run?.lead_agent_tokens) || 0,
208
+ subagent: Number(run?.subagent_tokens) || 0,
209
+ middleware: Number(run?.middleware_tokens) || 0
210
+ }
211
+ } : void 0;
212
+ const createdAt = buildRunCreatedAt(run);
213
+ return {
214
+ runId,
215
+ status: String(run?.status || "").trim(),
216
+ ...createdAt !== void 0 ? { createdAt } : {},
217
+ ...Array.isArray(inputMessages) && inputMessages.length ? { inputMessages } : {},
218
+ ...tokens ? { tokens } : {},
219
+ ...run?.stop_reason !== void 0 && run?.stop_reason !== null ? { stopReason: String(run.stop_reason) } : {}
220
+ };
221
+ }
802
222
  function buildRunDirectLatencyMs(run) {
803
223
  const direct = Number(run?.latency_ms);
804
224
  return direct || void 0;
@@ -833,302 +253,25 @@ function pickRunMessageMetadata(messages) {
833
253
  return { modelName, finishReason };
834
254
  }
835
255
 
836
- // src/store/thread-state.ts
837
- function createThreadStore(_options = {}) {
838
- const entities = /* @__PURE__ */ new Map();
839
- let order = [];
840
- let pageCountCache = -1;
841
- let cachedFlat = null;
842
- const version = (0, import_vue3.ref)(0);
843
- const streamStatusRef = (0, import_vue3.shallowRef)("idle");
844
- let streamEpoch = 0;
845
- const leadingPageCount = () => {
846
- let i = 0;
847
- while (i < order.length && entities.get(order[i])?.source === "page") i++;
848
- return i;
849
- };
850
- const lastPageIndex = () => {
851
- for (let i = order.length - 1; i >= 0; i--) {
852
- if (entities.get(order[i])?.source === "page") return i;
853
- }
854
- return -1;
855
- };
856
- const bump = () => {
857
- cachedFlat = null;
858
- pageCountCache = -1;
859
- version.value++;
860
- };
861
- const applyInstructions = (instructions) => {
862
- if (!instructions.length) return;
863
- let touched = false;
864
- for (const ins of instructions) {
865
- switch (ins.kind) {
866
- case "upsert": {
867
- const id = String(ins.message.id || "").trim();
868
- if (!id) break;
869
- const message = normalizeMessageType(ins.message);
870
- const existing = entities.get(id);
871
- if (existing) {
872
- existing.msg = message;
873
- existing.ver++;
874
- if (ins.source === "page") {
875
- existing.source = "page";
876
- } else {
877
- existing.source = "stream";
878
- existing.epoch = streamEpoch;
879
- }
880
- } else {
881
- entities.set(id, {
882
- msg: message,
883
- source: ins.source === "page" ? "page" : "stream",
884
- epoch: streamEpoch,
885
- ver: 1
886
- });
887
- if (ins.source === "page") {
888
- order.splice(lastPageIndex() + 1, 0, id);
889
- } else {
890
- order.push(id);
891
- }
892
- }
893
- touched = true;
894
- break;
895
- }
896
- case "remove": {
897
- if (!entities.has(ins.id)) break;
898
- const idx = order.indexOf(ins.id);
899
- if (idx >= 0) order.splice(idx, 1);
900
- entities.delete(ins.id);
901
- touched = true;
902
- break;
903
- }
904
- case "clear": {
905
- const removed = order.splice(leadingPageCount());
906
- for (const id of removed) entities.delete(id);
907
- touched = touched || removed.length > 0;
908
- break;
909
- }
910
- case "prepend": {
911
- const fresh = [];
912
- for (const msg of ins.messages) {
913
- const id = String(msg.id || "").trim();
914
- if (!id || entities.has(id)) continue;
915
- entities.set(id, {
916
- msg: normalizeMessageType(msg),
917
- source: "page",
918
- epoch: streamEpoch,
919
- ver: 1
920
- });
921
- fresh.push(id);
922
- }
923
- if (fresh.length) {
924
- order = [...fresh, ...order];
925
- touched = true;
926
- }
927
- break;
928
- }
929
- case "finalize": {
930
- if (streamStatusRef.value !== "settled") {
931
- streamStatusRef.value = "settled";
932
- touched = true;
933
- }
934
- break;
935
- }
936
- }
937
- }
938
- if (touched) bump();
939
- };
940
- return {
941
- applyInstructions,
942
- beginStream() {
943
- streamEpoch++;
944
- streamStatusRef.value = "streaming";
945
- bump();
946
- },
947
- getEntity: (id) => entities.get(id),
948
- get order() {
949
- return order;
950
- },
951
- get pageCount() {
952
- if (pageCountCache < 0) pageCountCache = leadingPageCount();
953
- return pageCountCache;
954
- },
955
- getMessages() {
956
- if (!cachedFlat) cachedFlat = order.map((id) => entities.get(id).msg);
957
- return cachedFlat;
958
- },
959
- get streamStatus() {
960
- return streamStatusRef.value;
961
- },
962
- get streamEpoch() {
963
- return streamEpoch;
964
- },
965
- version,
966
- streamStatusRef
967
- };
256
+ // src/parser/thread.ts
257
+ function extractStateMessages(state) {
258
+ if (!state || typeof state !== "object") return [];
259
+ const values = state.values;
260
+ if (!values || typeof values !== "object") return [];
261
+ const messages = values.messages;
262
+ return Array.isArray(messages) ? messages : [];
968
263
  }
969
- function readContentText(content) {
970
- if (typeof content === "string") return content;
971
- if (Array.isArray(content)) {
972
- return content.map((c) => c?.type === "text" ? String(c.text || "") : "").join("");
264
+ function ensureRunningRun(runMap, runId, threadId) {
265
+ let runInfo = runMap.get(runId);
266
+ if (!runInfo) {
267
+ runInfo = {
268
+ runId,
269
+ threadId: threadId || "",
270
+ status: "running"
271
+ };
272
+ runMap.set(runId, runInfo);
973
273
  }
974
- return "";
975
- }
976
- function isCitationCarrier(msg) {
977
- if (!isAiMessage(msg)) return false;
978
- return readContentText(asSxin(msg).content).includes("support.kbCitation");
979
- }
980
- function createEnrichments() {
981
- const citationPatches = (0, import_vue3.shallowReactive)(/* @__PURE__ */ new Map());
982
- const answers = (0, import_vue3.shallowReactive)(/* @__PURE__ */ new Map());
983
- let citationVersion = 0;
984
- return {
985
- get citationVersion() {
986
- return citationVersion;
987
- },
988
- applyFromStateMessages(messages) {
989
- for (const msg of messages) {
990
- const m = asSxin(msg);
991
- const id = String(m.id || "").trim();
992
- if (!id || !isCitationCarrier(msg)) continue;
993
- citationPatches.set(id, { content: m.content });
994
- citationVersion++;
995
- }
996
- const extracted = extractThreadInfo(messages).clarificationAnswers;
997
- for (const [key, value] of extracted) answers.set(key, value);
998
- },
999
- resolveCitation(messageId) {
1000
- return citationPatches.get(messageId);
1001
- },
1002
- answers,
1003
- setAnswer(requestId, answer) {
1004
- answers.set(requestId, answer);
1005
- },
1006
- clearAnswers() {
1007
- answers.clear();
1008
- },
1009
- dispose() {
1010
- citationPatches.clear();
1011
- answers.clear();
1012
- }
1013
- };
1014
- }
1015
- function createInterruptState() {
1016
- const respondedIds = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Set());
1017
- return {
1018
- respondedIds,
1019
- markResponded(id) {
1020
- const next = new Set(respondedIds.value);
1021
- next.add(id);
1022
- respondedIds.value = next;
1023
- },
1024
- unmarkResponded(id) {
1025
- if (!respondedIds.value.has(id)) return;
1026
- const next = new Set(respondedIds.value);
1027
- next.delete(id);
1028
- respondedIds.value = next;
1029
- }
1030
- };
1031
- }
1032
- function createRunsStore(options) {
1033
- const runsMap = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Map());
1034
- const currentRunId = (0, import_vue3.shallowRef)(null);
1035
- return {
1036
- runsMap,
1037
- currentRunId,
1038
- fillFromRunsList(runsList) {
1039
- let next = null;
1040
- for (const run of runsList) {
1041
- const runId = String(run?.run_id || "").trim();
1042
- if (!runId) continue;
1043
- next ?? (next = new Map(runsMap.value));
1044
- next.set(runId, buildRunInfo(run, options.threadId));
1045
- }
1046
- if (next) runsMap.value = next;
1047
- },
1048
- ensureRunning(runId) {
1049
- if (runsMap.value.has(runId)) return;
1050
- const next = new Map(runsMap.value);
1051
- ensureRunningRun(next, runId, options.threadId);
1052
- runsMap.value = next;
1053
- },
1054
- async refreshRuns() {
1055
- try {
1056
- const runsList = await options.transport.listRuns(options.threadId, 20);
1057
- if (!Array.isArray(runsList)) return;
1058
- const merged = new Map(runsMap.value);
1059
- for (const run of runsList) {
1060
- const runId = String(run.run_id || "").trim();
1061
- if (!runId) continue;
1062
- const info = buildRunInfo(run, options.threadId);
1063
- const prev = merged.get(runId);
1064
- if (!prev) {
1065
- merged.set(runId, info);
1066
- continue;
1067
- }
1068
- const directLatency = buildRunDirectLatencyMs(run);
1069
- merged.set(runId, {
1070
- ...info,
1071
- feedback: info.feedback ?? prev.feedback,
1072
- latencyMs: directLatency ?? prev.latencyMs ?? info.latencyMs,
1073
- modelName: info.modelName ?? prev.modelName,
1074
- finishReason: info.finishReason ?? prev.finishReason
1075
- });
1076
- }
1077
- runsMap.value = merged;
1078
- } catch (e) {
1079
- console.warn("[runs-store] refreshRuns failed", e);
1080
- }
1081
- },
1082
- enrichFromPage(page) {
1083
- const enrichment = extractRunEnrichment(page.messages);
1084
- let next = null;
1085
- for (const [runId, patch] of enrichment) {
1086
- const run = (next ?? runsMap.value).get(runId);
1087
- if (!run) continue;
1088
- next ?? (next = new Map(runsMap.value));
1089
- next.set(runId, {
1090
- ...run,
1091
- ...patch.feedback !== void 0 ? { feedback: patch.feedback } : {},
1092
- ...patch.latencyMs !== void 0 ? { latencyMs: patch.latencyMs } : {}
1093
- });
1094
- }
1095
- if (next) runsMap.value = next;
1096
- },
1097
- backfillCurrentRunMetadata(getMessages) {
1098
- const runId = currentRunId.value;
1099
- if (!runId) return;
1100
- const run = runsMap.value.get(runId);
1101
- if (!run) return;
1102
- if (run.modelName && run.finishReason) return;
1103
- const currentRunMessages = getMessages().filter((m) => String(m?.runId || "") === runId);
1104
- const source = currentRunMessages.length ? currentRunMessages : getMessages();
1105
- const picked = pickRunMessageMetadata(source);
1106
- if (!picked.modelName && !picked.finishReason) return;
1107
- runsMap.value = new Map(runsMap.value).set(runId, {
1108
- ...run,
1109
- ...picked.modelName && !run.modelName ? { modelName: picked.modelName } : {},
1110
- ...picked.finishReason && !run.finishReason ? { finishReason: picked.finishReason } : {}
1111
- });
1112
- },
1113
- patchRun(runId, patch) {
1114
- const run = runsMap.value.get(runId);
1115
- if (!run) return;
1116
- runsMap.value = new Map(runsMap.value).set(runId, { ...run, ...patch });
1117
- },
1118
- dispose() {
1119
- runsMap.value = /* @__PURE__ */ new Map();
1120
- currentRunId.value = null;
1121
- }
1122
- };
1123
- }
1124
-
1125
- // src/parser/message-id.ts
1126
- var _idSeq = 0;
1127
- function genMessageId() {
1128
- return `msg-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
1129
- }
1130
- function genBlockId() {
1131
- return `block-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
274
+ return runInfo;
1132
275
  }
1133
276
 
1134
277
  // src/parser/sxin-ast-attrs.ts
@@ -1213,22 +356,6 @@ var INJECTED_TAGS = /* @__PURE__ */ new Set([
1213
356
  function isInjectedElement(node) {
1214
357
  return INJECTED_TAGS.has(node.tagName);
1215
358
  }
1216
- function collectVisibleText(source, nodes) {
1217
- const parts = [];
1218
- const walk = (list) => {
1219
- for (const node of list) {
1220
- if (node.type === "text") {
1221
- parts.push(node.value);
1222
- } else if (node.type === "comment") {
1223
- parts.push(`<!--${node.content}-->`);
1224
- } else if (!node.closed && !INJECTED_TAGS.has(node.tagName)) {
1225
- parts.push(source.slice(node.start, node.end));
1226
- }
1227
- }
1228
- };
1229
- walk(nodes);
1230
- return parts.join("");
1231
- }
1232
359
  function collectTextKeepSxin(source, nodes) {
1233
360
  const parts = [];
1234
361
  const walk = (list) => {
@@ -1466,11 +593,8 @@ function readMessageContentText(msg) {
1466
593
  if (!read) return "";
1467
594
  return read.trim ? read.text.trim() : read.text;
1468
595
  }
1469
- function extractTextFromMessage(msg) {
1470
- const read = readMessageText(msg);
1471
- if (!read) return "";
1472
- const text = collectVisibleText(read.text, tokenizeSxin(read.text));
1473
- return read.trim ? text.trim() : text;
596
+ function hasKbCitationMessage(msg) {
597
+ return readMessageContentText(msg).includes("support.kbCitation");
1474
598
  }
1475
599
  function extractAiContentFromMessage(msg) {
1476
600
  const read = readMessageText(msg);
@@ -1483,105 +607,413 @@ function isVisibleUserMessage(msg) {
1483
607
  if (String(msg.type || "") !== "human") return false;
1484
608
  return msg.additional_kwargs?.hide_from_ui !== true;
1485
609
  }
1486
- function extractUserMessageTexts(rawMessages) {
1487
- if (!Array.isArray(rawMessages)) return [];
1488
- return rawMessages.filter((m) => isVisibleUserMessage(m)).map((m) => extractTextFromMessage(m).trim()).filter(Boolean).slice(0, 1);
610
+
611
+ // src/runtime/semantic-overlay.ts
612
+ var extractKwargsPatch = (msg) => {
613
+ const kwargs = msg?.additional_kwargs;
614
+ if (!kwargs || typeof kwargs !== "object") return void 0;
615
+ const patch = {};
616
+ if (kwargs.hide_from_ui === true) patch.hide_from_ui = true;
617
+ if (kwargs.human_input_response && typeof kwargs.human_input_response === "object") {
618
+ patch.human_input_response = kwargs.human_input_response;
619
+ }
620
+ return Object.keys(patch).length ? patch : void 0;
621
+ };
622
+ function extractSemanticPatchesFromMessages(messages) {
623
+ const next = /* @__PURE__ */ new Map();
624
+ for (const m of messages ?? []) {
625
+ const id = String(m?.id || "").trim();
626
+ if (!id) continue;
627
+ const patch = { id };
628
+ if (String(m?.type || "") === "ai" && hasKbCitationMessage(m)) {
629
+ patch.content = m.content;
630
+ }
631
+ if (String(m?.type || "") === "human") {
632
+ const kwargs = extractKwargsPatch(m);
633
+ if (kwargs) patch.additional_kwargs = kwargs;
634
+ }
635
+ if (patch.content !== void 0 || patch.additional_kwargs) next.set(id, patch);
636
+ }
637
+ return next;
638
+ }
639
+ function createSemanticOverlay() {
640
+ let patches = /* @__PURE__ */ new Map();
641
+ return {
642
+ applyState(state) {
643
+ const messages = extractStateMessages(state);
644
+ patches = extractSemanticPatchesFromMessages(messages);
645
+ const citedIds = messages.filter((m) => String(m?.type || "") === "ai" && hasKbCitationMessage(m)).map((m) => String(m?.id || "")).filter(Boolean);
646
+ return { patched: patches.size, citedIds };
647
+ },
648
+ getPatches() {
649
+ return new Map(patches);
650
+ },
651
+ invalidate() {
652
+ patches = /* @__PURE__ */ new Map();
653
+ }
654
+ };
655
+ }
656
+ function applySemanticPatches(messages, patches) {
657
+ if (!patches.size || !messages.length) return messages;
658
+ return messages.map((m) => {
659
+ const id = String(m?.id || "").trim();
660
+ const patch = id ? patches.get(id) : void 0;
661
+ if (!patch) return m;
662
+ let next = m;
663
+ if (patch.content !== void 0 && String(next?.type || "") === "ai" && !hasKbCitationMessage(next)) {
664
+ next = { ...next, content: patch.content };
665
+ }
666
+ const localKwargs = next?.additional_kwargs;
667
+ if (patch.additional_kwargs && Object.keys(patch.additional_kwargs).length) {
668
+ const merged = { ...localKwargs };
669
+ let changed = false;
670
+ for (const [k, v] of Object.entries(patch.additional_kwargs)) {
671
+ if (merged[k] === void 0) {
672
+ merged[k] = v;
673
+ changed = true;
674
+ }
675
+ }
676
+ if (changed) next = { ...next, additional_kwargs: merged };
677
+ }
678
+ return next;
679
+ });
680
+ }
681
+
682
+ // src/runtime/runtime-bootstrap.ts
683
+ function patchRows(rows, patches) {
684
+ if (!patches.size || !rows.length) return rows;
685
+ return rows.map((row) => {
686
+ const id = String(row.content?.id || "").trim();
687
+ const patch = id ? patches.get(id) : void 0;
688
+ if (!patch) return row;
689
+ const patched = applySemanticPatches([row.content], patches)[0];
690
+ return patched === row.content ? row : { ...row, content: patched };
691
+ });
692
+ }
693
+ async function bootstrapRuntime(deps) {
694
+ const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
695
+ deps.overlay.applyState(fetched.threadState);
696
+ deps.runs.fillFromRunsList(fetched.runsList ?? []);
697
+ deps.runs.enrichFromPage(fetched.messagesPage);
698
+ deps.runsListMeta.value = (fetched.runsList ?? []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
699
+ deps.rowsStore.setAll(patchRows(fetched.messagesPage.messages, deps.overlay.getPatches()));
700
+ deps.setPager(
701
+ createHistoryPager({
702
+ threadId: deps.threadId,
703
+ transport: deps.transport,
704
+ firstPage: fetched.messagesPage,
705
+ onPageLoaded: (page) => {
706
+ deps.runs.enrichFromPage(page);
707
+ deps.rowsStore.prepend(page.messages);
708
+ },
709
+ emitChanges: () => {
710
+ }
711
+ })
712
+ );
713
+ await deps.refreshTokenUsage();
714
+ const finalize = () => finalizeAfterStream(deps);
715
+ const afterFinish = () => afterStreamFinish(deps);
716
+ deps.streamRef.value = deps.transport.createStream({
717
+ assistantId: deps.assistantId,
718
+ threadId: deps.threadId,
719
+ onCreated: (run) => deps.markStreamRun(run?.run_id),
720
+ onMetadataEvent: (data) => deps.markStreamRun(data?.run_id),
721
+ onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
722
+ onMessageTupleEvent: () => {
723
+ },
724
+ onSnapshotMessages: (messages) => deps.applyLiveSnapshot(messages),
725
+ onStreamStart: deps.onStreamStart,
726
+ onStreamEnd: finalize,
727
+ onFinish: afterFinish,
728
+ onError: (err) => console.error("[runtime] stream error", err)
729
+ });
730
+ deps.setInitialized();
731
+ }
732
+ function finalizeAfterStream(deps) {
733
+ deps.onStreamSettled();
734
+ deps.runs.backfillCurrentRunMetadata(
735
+ () => deps.valuesChannel.getStreamMessages().map((m) => ({ ...m, runId: deps.runs.currentRunId.value }))
736
+ );
737
+ const patches = extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages());
738
+ deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, patches));
739
+ }
740
+ async function afterStreamFinish(deps) {
741
+ await Promise.all([deps.runs.refreshRuns(), refreshRunsMeta(deps), deps.refreshTokenUsage()]);
742
+ await reconcileWithPage(deps);
743
+ await refreshSemanticLayer(deps);
744
+ }
745
+ async function refreshRunsMeta(deps) {
746
+ try {
747
+ const list = await deps.transport.listRuns(deps.threadId, 20);
748
+ deps.runsListMeta.value = (Array.isArray(list) ? list : []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
749
+ } catch (e) {
750
+ console.warn("[runtime] runs.list \u5237\u65B0\u5931\u8D25", e);
751
+ }
752
+ }
753
+ async function refreshSemanticLayer(deps) {
754
+ try {
755
+ const state = await deps.transport.fetchThreadState(deps.threadId);
756
+ if (!state) return;
757
+ const semantic = deps.overlay.applyState(state);
758
+ deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, deps.overlay.getPatches()));
759
+ if (semantic.patched) {
760
+ console.debug(`[runtime] \u8BED\u4E49\u5C42\u5237\u65B0 patched=${semantic.patched} cited=${semantic.citedIds.length}`);
761
+ }
762
+ } catch (e) {
763
+ console.warn("[runtime] \u8BED\u4E49\u5C42\u5237\u65B0\u5931\u8D25", e);
764
+ }
765
+ }
766
+ async function reconcileWithPage(deps) {
767
+ try {
768
+ const page = await deps.transport.fetchMessagesPage(deps.threadId);
769
+ if (page.messages.length) deps.rowsStore.mergeLatest(page.messages);
770
+ } catch (e) {
771
+ console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
772
+ }
773
+ }
774
+ async function runRuntimeInit(deps, hooks) {
775
+ hooks.onStart();
776
+ try {
777
+ await bootstrapRuntime(deps);
778
+ } finally {
779
+ hooks.onEnd();
780
+ }
1489
781
  }
1490
782
 
1491
- // src/domain/fold.ts
1492
- function messageRunId(msg) {
1493
- const own = String(asSxin(msg).runId || "").trim();
1494
- if (own) return own;
1495
- return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
1496
- }
1497
- function foldMessages(target, flush) {
1498
- let type = null;
1499
- let buf = [];
1500
- let groupRunId;
1501
- const doFlush = () => {
1502
- if (!buf.length || !type) return;
1503
- flush(type, buf);
1504
- buf = [];
783
+ // src/parser/hitl.ts
784
+ var import_lodash = require("lodash");
785
+ function parseHitlPayload(value) {
786
+ if (!value || typeof value !== "object") return null;
787
+ const raw = value;
788
+ const requests = raw.actionRequests ?? raw.action_requests;
789
+ if (!Array.isArray(requests) || !requests.length) return null;
790
+ const configs = raw.reviewConfigs ?? raw.review_configs;
791
+ return {
792
+ actionRequests: requests,
793
+ reviewConfigs: Array.isArray(configs) ? configs : []
1505
794
  };
1506
- for (const m of target) {
1507
- if (isHumanMessage(m)) {
1508
- if (!(type === "human" && buf.length && getHumanMessageBaseId(String(asSxin(m).id || "")) === getHumanMessageBaseId(String(asSxin(buf[0]).id || ""))))
1509
- doFlush();
1510
- type = "human";
1511
- buf.push(m);
1512
- } else if (isAiMessage(m) || isToolMessage(m)) {
1513
- const mRunId = messageRunId(m);
1514
- if (type !== "ai" || mRunId && groupRunId && mRunId !== groupRunId) doFlush();
1515
- if (!buf.length) groupRunId = mRunId;
1516
- type = "ai";
1517
- buf.push(m);
795
+ }
796
+
797
+ // src/runtime/runtime-stream-actions.ts
798
+ function createStreamActions(ctx) {
799
+ return {
800
+ submit(text, submitOptions) {
801
+ const handle = ctx.getHandle();
802
+ if (!handle) return;
803
+ ctx.beginStream();
804
+ const kwargs = submitOptions?.kwargs ?? void 0;
805
+ ctx.createPendingRun(text, "message", kwargs);
806
+ const humanMessage = { type: "human", content: [{ type: "text", text }] };
807
+ humanMessage.additional_kwargs = submitOptions?.kwargs;
808
+ handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
809
+ },
810
+ async joinStream(runId, lastEventId) {
811
+ const handle = ctx.getHandle();
812
+ if (!handle) return;
813
+ ctx.beginStream();
814
+ ctx.markStreamRun(runId);
815
+ await handle.joinStream(runId, lastEventId ?? "-1");
816
+ },
817
+ stop() {
818
+ void ctx.options.transport.cancelRun(ctx.options.threadId, ctx.runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
819
+ ctx.getHandle()?.stop();
820
+ },
821
+ async resumeInterrupt(decisions) {
822
+ const it = ctx.getInterrupt();
823
+ const interruptId = String(it?.id || "");
824
+ if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
825
+ const handle = ctx.getHandle();
826
+ if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
827
+ ctx.markResponded(interruptId);
828
+ ctx.beginStream();
829
+ const payload = parseHitlPayload(it.value);
830
+ ctx.createPendingRun(payload ? "\u5DF2\u63D0\u4EA4\u5BA1\u6279\u51B3\u7B56" : "\u5DF2\u63D0\u4EA4\u56DE\u7B54", payload ? "hitl" : "clarification");
831
+ try {
832
+ await handle.resumeInterrupt(decisions);
833
+ } catch (e) {
834
+ ctx.unmarkResponded(interruptId);
835
+ throw e;
836
+ }
837
+ },
838
+ async loadOlderMessages() {
839
+ if (!ctx.getPager()) return false;
840
+ return ctx.getPager().loadOlder();
841
+ }
842
+ };
843
+ }
844
+
845
+ // src/runtime/rows-store.ts
846
+ var import_vue2 = require("vue");
847
+ function createRowsStore() {
848
+ const rows = (0, import_vue2.shallowRef)([]);
849
+ const sortRows = (list) => [...list].sort((a, b) => a.seq - b.seq);
850
+ return {
851
+ rows,
852
+ setAll(next) {
853
+ rows.value = sortRows(next);
854
+ },
855
+ prepend(older) {
856
+ if (!older.length) return;
857
+ const seen = new Set(rows.value.map((r) => String(r.content?.id || "")));
858
+ const fresh = older.filter((r) => {
859
+ const id = String(r.content?.id || "");
860
+ if (!id || seen.has(id)) return false;
861
+ seen.add(id);
862
+ return true;
863
+ });
864
+ if (!fresh.length) return;
865
+ rows.value = sortRows([...fresh, ...rows.value]);
866
+ },
867
+ mergeLatest(latest) {
868
+ if (!latest.length) return;
869
+ const byId = new Map(rows.value.map((r) => [String(r.content?.id || ""), r]));
870
+ for (const row of latest) {
871
+ const id = String(row.content?.id || "");
872
+ if (!id) continue;
873
+ byId.set(id, row);
874
+ }
875
+ rows.value = sortRows([...byId.values()]);
1518
876
  }
877
+ };
878
+ }
879
+ function extractLiveIncrement(snapshot, lastSeenIds) {
880
+ const fresh = [];
881
+ for (const msg of snapshot) {
882
+ const id = String(msg?.id || "").trim();
883
+ if (!id || lastSeenIds.has(id)) continue;
884
+ lastSeenIds.add(id);
885
+ fresh.push(msg);
1519
886
  }
1520
- doFlush();
887
+ return fresh;
1521
888
  }
1522
889
 
1523
- // src/parser/citation.ts
1524
- var KB_CITATION_CONTRACT = "support.kbCitation";
1525
- var REF_ID_KEYS = ["ref-id", "refId", "ref_id", "citation-id", "citationId", "citation_id", "id"];
1526
- var SEARCH_TEXT_KEYS = ["search-text", "searchText", "search_text", "keyword"];
1527
- var REF_ID_LIST_KEY_RE = /^(ref|citation)[-_]?ids?$/i;
1528
- var isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
1529
- var pickFirstString = (obj, keys) => {
1530
- for (const k of keys) {
1531
- const v = obj?.[k];
1532
- if (v === void 0 || v === null) continue;
1533
- const s = String(v).trim();
1534
- if (s) return s;
890
+ // src/assembler/run-grouping.ts
891
+ var LIVE_SEQ = Number.MAX_SAFE_INTEGER;
892
+ function rowMessageId(msg) {
893
+ return String(msg?.id || "").trim();
894
+ }
895
+ function isUserEchoRow(id) {
896
+ return id.endsWith("__user");
897
+ }
898
+ function pageRowToAsmRow(row) {
899
+ const id = rowMessageId(row.content);
900
+ if (!id) return null;
901
+ const out = {
902
+ id,
903
+ runId: String(row.runId || ""),
904
+ seq: Number.isFinite(row.seq) ? row.seq : 0,
905
+ msg: row.content
906
+ };
907
+ if (row.createdAt !== void 0) out.createdAt = row.createdAt;
908
+ if (row.feedback !== void 0 && row.feedback !== null) out.feedback = row.feedback;
909
+ return out;
910
+ }
911
+ function liveToAsmRow(msg, runId) {
912
+ const id = rowMessageId(msg);
913
+ if (!id || isUserEchoRow(id)) return null;
914
+ return { id, runId, seq: LIVE_SEQ, msg };
915
+ }
916
+ function groupRowsByRun(rows, liveMessages, activeRunId, pendingRunId) {
917
+ const byId = /* @__PURE__ */ new Map();
918
+ const buckets = /* @__PURE__ */ new Map();
919
+ for (const row of rows) {
920
+ const asm = pageRowToAsmRow(row);
921
+ if (!asm) continue;
922
+ const prev = byId.get(asm.id);
923
+ if (prev) {
924
+ if (asm.seq >= prev.seq) {
925
+ replaceInBucket(buckets, prev, asm);
926
+ byId.set(asm.id, asm);
927
+ }
928
+ continue;
929
+ }
930
+ byId.set(asm.id, asm);
931
+ pushToBucket(buckets, asm);
1535
932
  }
1536
- return void 0;
1537
- };
1538
- function extractCitationAnchorsFromSpec(spec) {
1539
- const anchors = [];
1540
- const seen = /* @__PURE__ */ new Set();
1541
- const candidates = [];
1542
- if (isPlainObject(spec)) candidates.push(spec);
1543
- for (const [key, value] of Object.entries(spec || {})) {
1544
- if (Array.isArray(value)) {
1545
- for (const item of value) if (isPlainObject(item)) candidates.push(item);
1546
- } else if (typeof value === "string" && /,/.test(value) && REF_ID_LIST_KEY_RE.test(key)) {
1547
- for (const id of value.split(",")) candidates.push({ "ref-id": id });
933
+ const liveRunId = String(activeRunId || pendingRunId || "").trim();
934
+ if (liveRunId) {
935
+ for (const msg of liveMessages) {
936
+ const asm = liveToAsmRow(msg, liveRunId);
937
+ if (!asm) continue;
938
+ if (byId.has(asm.id)) continue;
939
+ pushToBucket(buckets, asm);
1548
940
  }
1549
941
  }
1550
- for (const item of candidates) {
1551
- const refId = pickFirstString(item, REF_ID_KEYS);
1552
- if (!refId || seen.has(refId)) continue;
1553
- seen.add(refId);
1554
- const anchor = { refId, title: "" };
1555
- const searchText = pickFirstString(item, SEARCH_TEXT_KEYS);
1556
- if (searchText) anchor.searchText = searchText;
1557
- anchors.push(anchor);
1558
- }
1559
- return anchors;
1560
- }
1561
- function extractCitationAnchors(blocks) {
1562
- const anchors = [];
1563
- const seen = /* @__PURE__ */ new Set();
1564
- for (const block of blocks) {
1565
- if (block.type !== "custom") continue;
1566
- const custom = block;
1567
- if (custom.tagName !== "sxin-item") continue;
1568
- const spec = custom.spec || {};
1569
- if (String(spec.contract || "").trim() !== KB_CITATION_CONTRACT) continue;
1570
- for (const anchor of extractCitationAnchorsFromSpec(spec)) {
1571
- if (seen.has(anchor.refId)) continue;
1572
- seen.add(anchor.refId);
1573
- anchors.push(anchor);
942
+ for (const list of buckets.values()) {
943
+ list.sort((a, b) => a.seq - b.seq);
944
+ }
945
+ return buckets;
946
+ }
947
+ function pushToBucket(buckets, row) {
948
+ const runId = String(row.runId || "").trim();
949
+ if (!runId) return;
950
+ const list = buckets.get(runId);
951
+ if (list) list.push(row);
952
+ else buckets.set(runId, [row]);
953
+ }
954
+ function replaceInBucket(buckets, prev, next) {
955
+ const list = buckets.get(prev.runId);
956
+ if (!list) return;
957
+ const idx = list.indexOf(prev);
958
+ if (idx >= 0) list[idx] = next;
959
+ if (prev.runId !== next.runId) {
960
+ const oldList = buckets.get(prev.runId);
961
+ if (oldList) {
962
+ const i = oldList.indexOf(prev);
963
+ if (i >= 0) oldList.splice(i, 1);
964
+ if (!oldList.length) buckets.delete(prev.runId);
1574
965
  }
966
+ pushToBucket(buckets, next);
1575
967
  }
1576
- return anchors;
1577
968
  }
1578
969
 
1579
- // src/parser/report-artifact.ts
1580
- var genId = () => typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `id-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
1581
- function isWriteFileToolName(name) {
1582
- const n = String(name || "").trim().toLowerCase();
1583
- return n === "write_file" || n === "write_files";
970
+ // src/parser/body-segments.ts
971
+ var SEGMENT_TAGS = /* @__PURE__ */ new Set(["sxin-list", "sxin-item"]);
972
+ function visibleTextOf(node) {
973
+ if (node.type === "text") return node.value;
974
+ if (node.type === "comment") return "";
975
+ return node.children.map(visibleTextOf).join("");
976
+ }
977
+ function toItemSegment(el, source) {
978
+ return {
979
+ type: "item",
980
+ tag: "sxin-item",
981
+ attrs: { ...el.attrs },
982
+ content: visibleTextOf(el) || void 0,
983
+ raw: source.slice(el.start, el.end)
984
+ };
1584
985
  }
986
+ function toListSegment(el, source) {
987
+ const children = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-item").map((c) => toItemSegment(c, source));
988
+ return { type: "list", tag: "sxin-list", attrs: { ...el.attrs }, children, raw: source.slice(el.start, el.end) };
989
+ }
990
+ function sliceBodySegments(body) {
991
+ const source = String(body ?? "");
992
+ const segments = [];
993
+ let textBuf = "";
994
+ const flushText = () => {
995
+ if (!textBuf) return;
996
+ segments.push({ type: "text", content: textBuf });
997
+ textBuf = "";
998
+ };
999
+ for (const node of tokenizeSxin(source)) {
1000
+ if (node.type === "element" && SEGMENT_TAGS.has(node.tagName)) {
1001
+ flushText();
1002
+ segments.push(node.tagName === "sxin-list" ? toListSegment(node, source) : toItemSegment(node, source));
1003
+ } else if (node.type === "comment") {
1004
+ continue;
1005
+ } else if (node.type === "text") {
1006
+ textBuf += node.value;
1007
+ } else {
1008
+ textBuf += source.slice(node.start, node.end);
1009
+ }
1010
+ }
1011
+ flushText();
1012
+ if (!segments.length) segments.push({ type: "text", content: "" });
1013
+ return segments;
1014
+ }
1015
+
1016
+ // src/parser/report-artifact.ts
1585
1017
  function getToolCallArtifactMeta(toolCall) {
1586
1018
  const meta = toolCall?.artifact_meta;
1587
1019
  if (!meta || typeof meta !== "object") return null;
@@ -1624,1002 +1056,572 @@ function extractTitleFromArtifactPath(path, kind = "report_outline") {
1624
1056
  }
1625
1057
  return noExt.replace(/_大纲$/i, "").replace(/\s*大纲\s*$/i, "").trim() || "\u62A5\u544A";
1626
1058
  }
1627
- var OUTLINE_MAX_LEVEL = 3;
1628
- function normalizeSubChapter(raw, level) {
1629
- const legacyChildren = raw.children ?? raw.points ?? [];
1630
- const title = String(raw.title ?? raw.pointTitle ?? "");
1631
- const children = level >= OUTLINE_MAX_LEVEL ? [] : legacyChildren.map((c) => normalizeSubChapter(c, level + 1));
1632
- return {
1633
- id: String(raw.id ?? genId()),
1634
- title,
1635
- summary: String(raw.summary ?? raw.pointSummary ?? ""),
1636
- contentTheme: String(raw.contentTheme ?? raw.pointDesc ?? ""),
1637
- children
1638
- };
1639
- }
1640
- function normalizeOutline(raw) {
1641
- if (!Array.isArray(raw)) return [];
1642
- const outline = raw.map((item) => {
1643
- const ch = item;
1644
- const legacyChildren = ch.children ?? ch.points ?? [];
1645
- return {
1646
- id: String(ch.id ?? genId()),
1647
- chapterTitle: String(ch.chapterTitle ?? ""),
1648
- chapterSummary: String(ch.chapterSummary ?? ch.chapterDesc ?? ""),
1649
- children: legacyChildren.map((c) => normalizeSubChapter(c, 2))
1650
- };
1651
- });
1652
- return ensureOutlineContentThemes(outline);
1059
+
1060
+ // src/parser/extractors.ts
1061
+ function normalizeName(name) {
1062
+ const n = String(name || "").trim().toLowerCase();
1063
+ return n === "write_files" ? "write_file" : n;
1653
1064
  }
1654
- function ensureOutlineContentThemes(outline) {
1655
- const walk = (nodes) => {
1656
- nodes.forEach((node) => {
1657
- if (node.summary === void 0 || node.summary === null) {
1658
- node.summary = "";
1065
+ function tryParseObject(result) {
1066
+ const text = String(result ?? "").trim();
1067
+ if (!text.startsWith("{")) return null;
1068
+ try {
1069
+ const parsed = JSON.parse(text);
1070
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
1071
+ return parsed;
1072
+ } catch {
1073
+ return null;
1074
+ }
1075
+ }
1076
+ function extractFromToolResult(name, result, toolCallLike) {
1077
+ const tool = normalizeName(name);
1078
+ const obj = tryParseObject(result);
1079
+ if (tool === "ask_clarification" && obj) {
1080
+ const question = obj.question ?? obj.title;
1081
+ if (typeof question !== "string" || !question.trim()) return void 0;
1082
+ const options = Array.isArray(obj.options) ? obj.options : void 0;
1083
+ return options ? { kind: "clarification", question, options } : { kind: "clarification", question };
1084
+ }
1085
+ if (tool === "write_file") {
1086
+ if (obj) {
1087
+ if (typeof obj.body === "string" && obj.body) {
1088
+ const outline = typeof obj.outline === "string" ? obj.outline : void 0;
1089
+ return outline ? { kind: "report", reportKind: "report_body", body: obj.body, outline } : { kind: "report", reportKind: "report_body", body: obj.body };
1659
1090
  }
1660
- if (node.contentTheme === void 0 || node.contentTheme === null) {
1661
- node.contentTheme = "";
1091
+ if (Array.isArray(obj.files) && obj.files.length) {
1092
+ return { kind: "artifact", files: obj.files };
1662
1093
  }
1663
- if (node.children?.length) walk(node.children);
1664
- });
1665
- };
1666
- outline.forEach((ch) => {
1667
- if (ch.chapterSummary === void 0 || ch.chapterSummary === null) {
1668
- ch.chapterSummary = "";
1669
- }
1670
- walk(ch.children || []);
1671
- });
1672
- return outline;
1673
- }
1674
- function detectLevelOneIsChapter(lines) {
1675
- const levelOneCount = lines.filter((line) => /^#\s+.+$/.test(line.trim())).length;
1676
- return levelOneCount > 1;
1677
- }
1678
- function joinLines(existing, text) {
1679
- return existing ? `${existing}
1680
- ${text}` : text;
1681
- }
1682
- function appendBullet(state, text) {
1683
- const line = `- ${text}`;
1684
- const top = state.stack[state.stack.length - 1]?.node;
1685
- if (top) {
1686
- top.contentTheme = joinLines(top.contentTheme, line);
1687
- return;
1688
- }
1689
- if (!state.currentChapter) return;
1690
- state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, line);
1691
- }
1692
- function appendSummaryText(state, text) {
1693
- if (!text) return;
1694
- const top = state.stack[state.stack.length - 1]?.node;
1695
- if (top) {
1696
- top.summary = joinLines(top.summary, text);
1697
- return;
1698
- }
1699
- if (!state.currentChapter) return;
1700
- state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, text);
1701
- }
1702
- function appendPlainText(state, text) {
1703
- if (!text) return;
1704
- const top = state.stack[state.stack.length - 1]?.node;
1705
- if (top) {
1706
- top.contentTheme = joinLines(top.contentTheme, text);
1707
- return;
1708
- }
1709
- if (!state.currentChapter) return;
1710
- state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, text);
1711
- }
1712
- function resolveTemplateName(title) {
1713
- return title.replace(/\s*·\s*大纲\s*$/i, "").replace(/\s*大纲\s*$/i, "").trim() || title;
1714
- }
1715
- function pushChapter(state, title) {
1716
- state.currentChapter = { id: genId(), chapterTitle: title, chapterSummary: "", children: [] };
1717
- state.outline.push(state.currentChapter);
1718
- state.stack.length = 0;
1719
- }
1720
- function pushSubChapter(state, level, title) {
1721
- const subChapterLevel = state.levelOneIsChapter ? level : level - 1;
1722
- if (subChapterLevel < 2 || !state.currentChapter) return false;
1723
- const sub = { id: genId(), title, summary: "", contentTheme: "", children: [] };
1724
- while (state.stack.length && state.stack[state.stack.length - 1].level >= subChapterLevel) {
1725
- state.stack.pop();
1726
- }
1727
- const parent = state.stack[state.stack.length - 1]?.node;
1728
- if (parent) parent.children.push(sub);
1729
- else state.currentChapter.children.push(sub);
1730
- state.stack.push({ node: sub, level: subChapterLevel });
1731
- return true;
1732
- }
1733
- function handleQuote(state, trimmed) {
1734
- if (!trimmed.startsWith(">")) return false;
1735
- const quoteText = trimmed.replace(/^(>\s*)+/, "").trim();
1736
- const summaryText = quoteText.replace(/^摘要\s*[::]\s*/i, "").trim();
1737
- appendSummaryText(state, summaryText || quoteText);
1738
- return true;
1739
- }
1740
- function handleHeading(state, trimmed) {
1741
- const heading = trimmed.match(/^(#{1,6})\s+(.+)$/);
1742
- if (!heading) return false;
1743
- const level = heading[1].length;
1744
- const title = heading[2].trim();
1745
- if (level === 1 && !state.levelOneIsChapter) {
1746
- state.templateName = resolveTemplateName(title);
1747
- return true;
1748
- }
1749
- if (level === 1 && state.levelOneIsChapter || level === 2 && !state.levelOneIsChapter) {
1750
- pushChapter(state, title);
1751
- return true;
1752
- }
1753
- return pushSubChapter(state, level, title);
1754
- }
1755
- function parseMarkdownToOutline(markdown) {
1756
- const lines = String(markdown || "").split(/\r?\n/);
1757
- const state = {
1758
- templateName: "",
1759
- outline: [],
1760
- currentChapter: null,
1761
- stack: [],
1762
- levelOneIsChapter: detectLevelOneIsChapter(lines)
1763
- };
1764
- for (const line of lines) {
1765
- const trimmed = line.trim();
1766
- if (!trimmed || trimmed === "---" || /^```/.test(trimmed)) continue;
1767
- if (handleQuote(state, trimmed)) continue;
1768
- if (handleHeading(state, trimmed)) continue;
1769
- const bullet = trimmed.match(/^[-*]\s+(.+)$/);
1770
- if (bullet) {
1771
- appendBullet(state, bullet[1].trim());
1772
- continue;
1773
- }
1774
- appendPlainText(state, trimmed);
1775
- }
1776
- return {
1777
- templateName: state.templateName || "\u62A5\u544A",
1778
- outline: normalizeOutline(state.outline)
1779
- };
1780
- }
1781
- var HTML_LIKE = /^\s*</;
1782
- function isReportBodyHtml(content) {
1783
- const s = String(content || "").trim();
1784
- if (!s) return false;
1785
- return HTML_LIKE.test(s);
1786
- }
1787
- function extractReportTitleFromBody(content, fallback = "") {
1788
- const s = String(content || "").trim();
1789
- if (!s) return fallback;
1790
- if (isReportBodyHtml(s)) {
1791
- const h1 = s.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);
1792
- if (h1?.[1]) {
1793
- const t = h1[1].replace(/<[^>]+>/g, "").trim();
1794
- if (t) return t;
1795
- }
1796
- }
1797
- const heading = s.match(/^#\s+(.+)$/m);
1798
- if (heading?.[1]) return heading[1].trim();
1799
- return fallback;
1800
- }
1801
-
1802
- // src/parser/block-build-helper.ts
1803
- function buildArtifactFiles(paths) {
1804
- return paths.map((path) => {
1805
- const name = path.split("/").pop() || path;
1806
- const fileType = name.split(".").pop() || void 0;
1807
- return { path, name, fileType };
1808
- });
1809
- }
1810
- function toCreatedAtIso(createdAt) {
1811
- const ms = Number(createdAt);
1812
- if (!Number.isFinite(ms)) return (/* @__PURE__ */ new Date()).toISOString();
1813
- const date = new Date(ms);
1814
- return Number.isNaN(date.getTime()) ? (/* @__PURE__ */ new Date()).toISOString() : date.toISOString();
1815
- }
1816
- function buildReportOutlinePayload(input) {
1817
- const { templateId, fallbackName, sourcePath, content, contentRef, createdAt } = input;
1818
- const createdIso = toCreatedAtIso(createdAt);
1819
- if (!content) {
1820
- return {
1821
- templateId,
1822
- templateName: fallbackName,
1823
- outline: [],
1824
- createdAt: createdIso,
1825
- sourcePath: sourcePath || void 0,
1826
- contentRef
1827
- };
1828
- }
1829
- const parsed = parseMarkdownToOutline(content);
1830
- return {
1831
- templateId,
1832
- templateName: parsed.templateName || fallbackName,
1833
- outline: parsed.outline,
1834
- createdAt: createdIso,
1835
- sourcePath: sourcePath || void 0,
1836
- outlineMarkdown: content,
1837
- contentRef
1838
- };
1839
- }
1840
- function buildReportBodyPayload(input) {
1841
- const { templateId, fallbackName, sourcePath, content, contentRef, createdAt } = input;
1842
- const createdIso = toCreatedAtIso(createdAt);
1843
- if (!content) {
1844
- return {
1845
- templateId,
1846
- templateName: fallbackName,
1847
- reportTitle: "",
1848
- createdAt: createdIso,
1849
- sourcePath: sourcePath || void 0,
1850
- contentRef
1851
- };
1852
- }
1853
- return {
1854
- templateId,
1855
- templateName: fallbackName,
1856
- reportTitle: extractReportTitleFromBody(content, fallbackName),
1857
- createdAt: createdIso,
1858
- sourcePath: sourcePath || void 0,
1859
- bodyMarkdown: content,
1860
- contentRef
1861
- };
1862
- }
1863
- function collectListSpecs(listEls, spec, source) {
1864
- for (const listEl of listEls) {
1865
- const itemType = formatStr(listEl.attrs["item-type"] || "");
1866
- if (!itemType) continue;
1867
- if (!spec[itemType]) spec[itemType] = [];
1868
- for (const item of listEl.children) {
1869
- if (item.type !== "element" || item.tagName !== "sxin-list-item") continue;
1870
- spec[itemType].push(buildItemSpec(item, source));
1871
- }
1872
- }
1873
- }
1874
- function collectChildSpecs(children, spec, source) {
1875
- for (const child of children) {
1876
- if (child.type !== "element") continue;
1877
- const key = formatStr(child.tagName);
1878
- if (!spec[key]) spec[key] = [];
1879
- spec[key].push(buildItemSpec(child, source));
1880
- }
1881
- }
1882
- function buildCustomBlockFromNode(el, source, status) {
1883
- const spec = { ...el.attrs };
1884
- const listEls = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-list");
1885
- if (listEls.length > 0) {
1886
- collectListSpecs(listEls, spec, source);
1887
- } else {
1888
- collectChildSpecs(el.children, spec, source);
1889
- }
1890
- return { id: genBlockId(), type: "custom", tagName: el.tagName, spec, status };
1891
- }
1892
- function buildItemSpec(el, source) {
1893
- const attrs = { ...el.attrs };
1894
- const inner = el.children.map((c) => source.slice(c.start, c.end)).join("").trim();
1895
- if (inner) attrs.text = inner;
1896
- return attrs;
1897
- }
1898
- function flushTextBuf(ctx) {
1899
- const content = ctx.textBuf.value.replace(/\n{3,}/g, "\n\n").trim();
1900
- ctx.textBuf.value = "";
1901
- if (content) {
1902
- ctx.blocks.push({ id: genBlockId(), type: "text", content, status: ctx.status });
1903
- }
1904
- }
1905
- function handleSxinElement(ctx, node) {
1906
- if (!node.closed && !ctx.isHistory) {
1907
- flushTextBuf(ctx);
1908
- return false;
1909
- }
1910
- flushTextBuf(ctx);
1911
- ctx.blocks.push(buildCustomBlockFromNode(node, ctx.rawText, ctx.status));
1912
- return true;
1913
- }
1914
- function walkNodes(ctx, nodes) {
1915
- for (const node of nodes) {
1916
- if (node.type === "text") {
1917
- ctx.textBuf.value += node.value;
1918
- continue;
1919
- }
1920
- if (node.type === "comment") {
1921
- continue;
1922
1094
  }
1923
- if (isInjectedElement(node)) {
1924
- continue;
1925
- }
1926
- if (node.tagName.startsWith("sxin-")) {
1927
- if (!handleSxinElement(ctx, node)) return false;
1928
- continue;
1095
+ const reportKind = resolveReportArtifactKind(toolCallLike);
1096
+ if (reportKind) {
1097
+ const tc = toolCallLike ?? {};
1098
+ const sourcePath = String(tc?.artifact_meta?.path || tc?.args?.path || "").trim() || void 0;
1099
+ return {
1100
+ kind: "report",
1101
+ reportKind,
1102
+ sourcePath,
1103
+ title: sourcePath ? extractTitleFromArtifactPath(sourcePath, reportKind) : void 0
1104
+ };
1929
1105
  }
1930
- ctx.textBuf.value += ctx.rawText.slice(node.start, node.end);
1931
1106
  }
1932
- return true;
1933
- }
1934
- function extractBlocksFromNodes(nodes, rawText, source) {
1935
- const isHistory = source === "history";
1936
- const ctx = {
1937
- rawText,
1938
- isHistory,
1939
- status: isHistory ? "completed" : "streaming",
1940
- blocks: [],
1941
- textBuf: { value: "" }
1942
- };
1943
- const completed = walkNodes(ctx, nodes);
1944
- if (completed) flushTextBuf(ctx);
1945
- return { blocks: ctx.blocks };
1107
+ return void 0;
1946
1108
  }
1947
1109
 
1948
- // src/domain/block-builder.ts
1949
- var DEFAULT_TWIN_TOOL_PREFIX = "city-digital-twin-display_";
1950
- function createBlockBuilderLite(options) {
1951
- const source = options.source;
1952
- const isStreaming = !!options.isStreaming;
1953
- const createdAt = Number.isFinite(options.createdAt) ? Number(options.createdAt) : Date.now();
1954
- const twinEnabled = !!options.twin?.enabled;
1955
- const twinToolPrefix = options.twin?.toolPrefix || DEFAULT_TWIN_TOOL_PREFIX;
1956
- const presentFilesSet = /* @__PURE__ */ new Set();
1957
- const writeFilesSet = /* @__PURE__ */ new Set();
1958
- const toolParsers = /* @__PURE__ */ new Map();
1959
- const registerParser = (names, parser) => {
1960
- for (const name of Array.isArray(names) ? names : [names]) {
1961
- toolParsers.set(name, parser);
1962
- }
1963
- };
1964
- const parseBlockTool = (tool, status) => {
1965
- const name = String(tool.call?.name || "").trim();
1966
- const parser = toolParsers.get(name);
1967
- return parser ? parser(tool, status) : [];
1968
- };
1969
- const parseAskClarification = (tool, _status) => {
1970
- const args = tool.call?.args || {};
1971
- return [
1972
- {
1973
- id: genBlockId(),
1974
- type: "ask-clarification",
1975
- context: args.context,
1976
- question: args.question,
1977
- clarification_type: args.clarification_type,
1978
- options: Array.isArray(args.options) ? args.options : void 0,
1979
- fields: Array.isArray(args.fields) ? args.fields : void 0,
1980
- // clarification 的回答是跨 run 的,不能根据 streaming/source 判断状态,统一 pending,由渲染层结合 thread 级回答状态决定
1981
- status: "pending",
1982
- toolCallId: tool.id
1983
- }
1984
- ];
1985
- };
1986
- const parseFormBlock = (tool, status, sourceTag) => {
1987
- const args = tool.call?.args || {};
1988
- const variant = String(args.variant || "input");
1989
- const blockStatus = sourceTag === "ask_clarification" ? "pending" : status;
1990
- return [
1991
- {
1992
- id: genBlockId(),
1993
- type: "form",
1994
- variant: ["input", "confirm", "delete_confirm"].includes(variant) ? variant : "input",
1995
- title: args.title,
1996
- question: args.question,
1997
- context: args.context,
1998
- fields: Array.isArray(args.fields) ? args.fields : [],
1999
- values: args.values || {},
2000
- stepInfo: args.stepInfo,
2001
- customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
2002
- status: blockStatus,
2003
- toolCallId: tool.id,
2004
- source: sourceTag
2005
- }
2006
- ];
2007
- };
2008
- const parseListBlock = (tool, status) => {
2009
- const args = tool.call?.args || {};
2010
- const mode = String(args.mode || "select");
2011
- return [
2012
- {
2013
- id: genBlockId(),
2014
- type: "list",
2015
- mode: ["select", "view"].includes(mode) ? mode : "select",
2016
- title: args.title,
2017
- dataSource: args.dataSource,
2018
- items: Array.isArray(args.items) ? args.items : void 0,
2019
- queryParams: args.queryParams,
2020
- pagination: args.pagination,
2021
- selectMode: args.selectMode || "single",
2022
- customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
2023
- status,
2024
- toolCallId: tool.id
2025
- }
2026
- ];
2027
- };
2028
- const parsePresentFiles = (tool, status) => {
2029
- const args = tool.call?.args || {};
2030
- const filepaths = Array.isArray(args?.filepaths) ? args.filepaths : [];
2031
- if (!filepaths.length) return [];
2032
- const paths = [];
2033
- for (const path of filepaths) {
2034
- if (presentFilesSet.has(path)) continue;
2035
- presentFilesSet.add(path);
2036
- paths.push(path);
2037
- }
2038
- if (!paths.length) return [];
2039
- return [
2040
- {
2041
- id: genBlockId(),
2042
- type: "artifact",
2043
- files: buildArtifactFiles(paths),
2044
- status
2045
- }
2046
- ];
2047
- };
2048
- const resolveWriteFileContext = (tool) => {
2049
- const meta = getToolCallArtifactMeta(tool.call);
2050
- const args = tool.call?.args || {};
2051
- const artifactPath = String(meta?.path || args.path || "").trim();
2052
- const content = String(args.content || tool.result?.content || "").trim();
2053
- const description = String(args.description || "").trim();
2054
- const blockId = tool.id || artifactPath || `report-${Date.now()}`;
2055
- const toolCreatedAt = Number(new Date(asSxin(tool.aiMessage).created_at || ""));
2056
- const toolTime = Number.isFinite(toolCreatedAt) ? toolCreatedAt : createdAt;
2057
- if (!content && source === "sse") return null;
2058
- if (writeFilesSet.has(artifactPath)) return null;
2059
- writeFilesSet.add(artifactPath);
2060
- presentFilesSet.add(artifactPath);
2061
- return { artifactPath, content, description, blockId, createdAt: toolTime };
2062
- };
2063
- const buildReportBlock = (kind, ctx, status) => {
2064
- const isOutline = kind === "report_outline";
2065
- const fallbackName = extractTitleFromArtifactPath(ctx.artifactPath, kind) || ctx.description.replace(isOutline ? /生成|大纲/g : /生成|正文|报告/g, "").trim() || "\u62A5\u544A";
2066
- const isState = source === "state";
2067
- const payloadInput = {
2068
- templateId: ctx.blockId,
2069
- fallbackName,
2070
- sourcePath: ctx.artifactPath || void 0,
2071
- content: isState ? void 0 : ctx.content || void 0,
2072
- contentRef: isState && ctx.artifactPath ? { path: ctx.artifactPath } : void 0,
2073
- createdAt: ctx.createdAt
2074
- };
2075
- return isOutline ? { id: genBlockId(), type: "report-outline", payload: buildReportOutlinePayload(payloadInput), status } : { id: genBlockId(), type: "report-body", payload: buildReportBodyPayload(payloadInput), status };
2076
- };
2077
- const parseWriteFile = (tool, status) => {
2078
- const name = String(tool.call?.name || "").trim();
2079
- if (!isWriteFileToolName(name)) return [];
2080
- const kind = resolveReportArtifactKind(tool.call);
2081
- if (!kind) return [];
2082
- const ctx = resolveWriteFileContext(tool);
2083
- if (!ctx) return [];
2084
- const block = buildReportBlock(kind, ctx, status);
2085
- return block ? [block] : [];
2086
- };
2087
- const parseClarification = (tool, status) => {
2088
- const args = tool.call?.args || {};
2089
- if (args.variant || args.fields?.length) {
2090
- return parseFormBlock(tool, status, "ask_clarification");
2091
- }
2092
- return parseAskClarification(tool, status);
2093
- };
2094
- registerParser("ask_clarification", parseClarification);
2095
- registerParser(
2096
- ["confirm_form", "form"],
2097
- (tool, status) => parseFormBlock(tool, status, String(tool.call?.name || "").trim())
2098
- );
2099
- registerParser(["list_and_select", "list"], parseListBlock);
2100
- registerParser("present_files", parsePresentFiles);
2101
- registerParser(["write_file", "write_files"], parseWriteFile);
2102
- const buildFromNodes = (nodes, rawText, tools) => {
2103
- const blocks = [];
2104
- const status = isStreaming ? "streaming" : "completed";
2105
- const contentSource = source === "state" ? "history" : source;
2106
- const { blocks: contentBlocks } = extractBlocksFromNodes(nodes, rawText, contentSource);
2107
- blocks.push(...contentBlocks);
2108
- for (const tool of tools) {
2109
- const toolBlocks = parseBlockTool(tool, status);
2110
- blocks.push(...toolBlocks);
2111
- }
2112
- if (twinEnabled) {
2113
- const twinTool = tools.reverse().find((_) => _.call?.name.includes(twinToolPrefix));
2114
- if (twinTool) {
2115
- blocks.push({
2116
- id: genBlockId(),
2117
- type: "twin",
2118
- toolName: twinTool.call.name.replace(twinToolPrefix, ""),
2119
- args: twinTool.call.args
2120
- });
1110
+ // src/parser/tool-args.ts
1111
+ function asArgsObject(args) {
1112
+ if (args && typeof args === "object" && !Array.isArray(args)) return args;
1113
+ if (typeof args === "string") {
1114
+ try {
1115
+ const parsed = JSON.parse(args);
1116
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1117
+ return parsed;
2121
1118
  }
2122
- }
2123
- return blocks;
2124
- };
2125
- const build = (content, tools) => buildFromNodes(tokenizeSxin(content), content, tools);
2126
- return { build, buildFromNodes };
2127
- }
2128
-
2129
- // src/domain/group-materializer.ts
2130
- function readCreatedAt(msg) {
2131
- return Number(new Date(asSxin(msg).created_at || Date.now())) || Date.now();
2132
- }
2133
- function buildHumanGroup(messages, status) {
2134
- const representative = messages.find(
2135
- (m) => parseHumanMessageId(String(asSxin(m).id || "")).variant === "user" && isVisibleUserMessage(m)
2136
- ) || messages.find((m) => isVisibleUserMessage(m)) || messages[0];
2137
- const firstId = messages.find((_) => _.id)?.id || genMessageId();
2138
- const additionalKwargs = asSxin(representative).additional_kwargs;
2139
- const texts = extractUserMessageTexts(messages);
2140
- const runId = messageRunId(representative);
2141
- return {
2142
- id: firstId,
2143
- type: "human",
2144
- status,
2145
- originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
2146
- runId,
2147
- rawMessages: messages,
2148
- texts,
2149
- additionalKwargs,
2150
- blocks: [],
2151
- toolIds: [],
2152
- tools: [],
2153
- createdAt: readCreatedAt(representative)
2154
- };
2155
- }
2156
- function buildAiGroup(messages, options, twin) {
2157
- const firstId = messages.find((_) => _.id)?.id || genMessageId();
2158
- const groupTools = deriveToolsFromMessages(messages);
2159
- const aiMessages = messages.filter(isAiMessage);
2160
- const lastAi = aiMessages[aiMessages.length - 1] || messages[messages.length - 1];
2161
- const content = readMessageContentText(lastAi);
2162
- const createdAt = readCreatedAt(messages[0]);
2163
- const blocks = options.isStreaming ? [] : createBlockBuilderLite({ source: options.source, twin, createdAt }).buildFromNodes(
2164
- tokenizeSxin(content),
2165
- content,
2166
- groupTools
2167
- );
2168
- const anchors = extractCitationAnchors(blocks);
2169
- const citations = anchors.length ? anchors : void 0;
2170
- return {
2171
- id: firstId,
2172
- type: "ai",
2173
- status: options.isStreaming ? "streaming" : "completed",
2174
- originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
2175
- runId: messageRunId(lastAi) || options.runId,
2176
- rawMessages: messages,
2177
- blocks,
2178
- citations,
2179
- toolIds: groupTools.map((t) => t.id),
2180
- tools: groupTools,
2181
- createdAt
2182
- };
2183
- }
2184
-
2185
- // src/domain/clarification.ts
2186
- function isClarificationAnswered(block, answers) {
2187
- if (!block) return false;
2188
- if (block.status === "completed") return true;
2189
- if (block.isAnswered) return true;
2190
- const toolCallId = block.toolCallId;
2191
- return !!toolCallId && answers.has(toolCallId);
1119
+ } catch {
1120
+ }
1121
+ }
1122
+ return void 0;
2192
1123
  }
2193
- function isClarificationBlock(block) {
2194
- return block.type === "ask-clarification" || block.type === "form" && block.source === "ask_clarification";
1124
+ function pickRicherArgs(prev, next) {
1125
+ const nextObj = asArgsObject(next);
1126
+ if (!nextObj) return void 0;
1127
+ const prevObj = asArgsObject(prev);
1128
+ if (!prevObj) return nextObj;
1129
+ const prevKeys = new Set(Object.keys(prevObj));
1130
+ const hasNewKey = Object.keys(nextObj).some((k) => !prevKeys.has(k));
1131
+ const longer = JSON.stringify(nextObj).length > JSON.stringify(prevObj).length;
1132
+ return hasNewKey || longer ? nextObj : void 0;
2195
1133
  }
2196
1134
 
2197
- // src/parser/hitl.ts
2198
- var import_lodash = require("lodash");
2199
- function parseHitlPayload(value) {
2200
- if (!value || typeof value !== "object") return null;
2201
- const raw = value;
2202
- const requests = raw.actionRequests ?? raw.action_requests;
2203
- if (!Array.isArray(requests) || !requests.length) return null;
2204
- const configs = raw.reviewConfigs ?? raw.review_configs;
1135
+ // src/assembler/types.ts
1136
+ var BACKEND_STATUS_MAP = {
1137
+ success: "success",
1138
+ error: "error",
1139
+ interrupted: "interrupted",
1140
+ cancelled: "cancelled",
1141
+ pending: "pending",
1142
+ running: "running"
1143
+ };
1144
+
1145
+ // src/assembler/run-assembly.ts
1146
+ function emptyRunItem(runId, createdAt) {
2205
1147
  return {
2206
- actionRequests: requests,
2207
- reviewConfigs: Array.isArray(configs) ? configs : []
1148
+ runId,
1149
+ input: { kind: "message", text: "" },
1150
+ status: "pending",
1151
+ body: "",
1152
+ segments: [{ type: "text", content: "" }],
1153
+ tools: [],
1154
+ attachments: [],
1155
+ clarifications: [],
1156
+ rawMessages: [],
1157
+ ...createdAt !== void 0 ? { createdAt } : {}
2208
1158
  };
2209
1159
  }
2210
- function buildInterruptReviewBlock(interrupt, responded) {
2211
- const payload = parseHitlPayload(interrupt.value);
2212
- if (!payload) return null;
2213
- const interruptId = String(interrupt.id || genMessageId());
2214
- const status = responded ? "completed" : "pending";
1160
+ function assembleRun(runId, options) {
1161
+ const rows = options.rows;
1162
+ const twinEnabled = !!options.twin?.enabled;
1163
+ const twinToolPrefix = options.twin?.toolPrefix || "city-digital-twin-display_";
1164
+ let body = "";
1165
+ let feedback;
1166
+ const tools = [];
1167
+ const toolByCallId = /* @__PURE__ */ new Map();
1168
+ let createdAt;
1169
+ for (const row of rows) {
1170
+ const msg = row.msg;
1171
+ const type = String(msg?.type || "");
1172
+ if (createdAt === void 0 && row.createdAt !== void 0) createdAt = row.createdAt;
1173
+ if (type === "ai") {
1174
+ const text = extractAiContentFromMessage(msg);
1175
+ if (text) body = body ? `${body}
1176
+ ${text}` : text;
1177
+ registerToolCalls(msg, tools, toolByCallId);
1178
+ } else if (type === "tool") {
1179
+ applyToolMessage(msg, tools, toolByCallId);
1180
+ } else if (type === "human") {
1181
+ }
1182
+ if (row.feedback !== void 0 && row.feedback !== null) feedback = row.feedback;
1183
+ }
1184
+ const attachments = assembleAttachments(tools, twinEnabled, twinToolPrefix);
1185
+ const clarifications = extractClarifications(tools);
1186
+ const segments = options.streaming ? [{ type: "text", content: body }] : sliceBodySegments(body);
2215
1187
  return {
2216
- id: `interrupt-review-${interruptId}`,
2217
- type: "interrupt-review",
2218
- status,
2219
- payload,
2220
- interruptId
1188
+ runId,
1189
+ // input 由 projectRuns 层填(需要 runs.list / 窗口 human 行两级来源),这里占位
1190
+ input: { kind: "message", text: "" },
1191
+ status: "success",
1192
+ body,
1193
+ segments,
1194
+ tools,
1195
+ attachments,
1196
+ ...feedback !== void 0 ? { feedback } : {},
1197
+ clarifications,
1198
+ ...createdAt !== void 0 ? { createdAt } : {},
1199
+ rawMessages: [...rows]
2221
1200
  };
2222
1201
  }
2223
-
2224
- // src/domain/decorators.ts
2225
- function applyPatchesAndExtras(groups, state, runIdFilter) {
2226
- if (!state.patches.size && !state.extras.length) return groups;
2227
- const patchedGroups = groups.map((g) => state.patches.get(g.id) ?? g);
2228
- const anchor = runIdFilter ? patchedGroups.findIndex((g) => String(g.runId || "").trim() === runIdFilter) : -1;
2229
- return anchor >= 0 ? [...patchedGroups.slice(0, anchor), ...state.extras, ...patchedGroups.slice(anchor)] : [...patchedGroups, ...state.extras];
2230
- }
2231
- function withInterruptBlock(groups, deps) {
2232
- const interrupt = deps.getInterrupt();
2233
- if (!interrupt) return groups;
2234
- const interruptId = String(interrupt.id || "");
2235
- const responded = !!interruptId && deps.respondedIds.has(interruptId);
2236
- const block = buildInterruptReviewBlock(interrupt, responded);
2237
- if (!block) return groups;
2238
- const { interruptBlocks } = deps;
2239
- const targetIndex = findLastAiIndex(groups);
2240
- if (targetIndex >= 0) {
2241
- const remembered = interruptBlocks.get(interruptId);
2242
- if (remembered) {
2243
- const updated = { ...block, status: responded ? "completed" : "pending" };
2244
- interruptBlocks.set(interruptId, updated);
2245
- const next2 = [...groups];
2246
- next2[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, updated] };
2247
- return next2;
2248
- }
2249
- interruptBlocks.set(interruptId, block);
2250
- const next = [...groups];
2251
- next[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, block] };
2252
- return next;
1202
+ function extractInputFromRows(rows) {
1203
+ for (const row of rows) {
1204
+ const msg = row.msg;
1205
+ if (!isVisibleUserMessage(msg)) continue;
1206
+ const kwargs = msg?.additional_kwargs;
1207
+ return {
1208
+ text: readMessageContentText(msg).trim(),
1209
+ ...kwargs && typeof kwargs === "object" ? { kwargs: { ...kwargs } } : {}
1210
+ };
2253
1211
  }
2254
- const existing = [...interruptBlocks.values()].find(
2255
- (b) => b.type === "interrupt-review" && b.interruptId === interruptId
2256
- );
2257
- if (existing) return groups;
2258
- interruptBlocks.set(interruptId, block);
2259
- return [
2260
- ...groups,
2261
- {
2262
- id: `interrupt-${interruptId}`,
2263
- type: "ai",
2264
- status: block.status,
2265
- source: "state",
2266
- originMessageIds: [],
2267
- blocks: [block],
2268
- toolIds: [],
2269
- tools: [],
2270
- rawMessages: [],
2271
- createdAt: Date.now()
1212
+ return { text: "" };
1213
+ }
1214
+ function registerToolCalls(msg, tools, byCallId) {
1215
+ const calls = Array.isArray(msg?.tool_calls) ? msg.tool_calls : msg?.additional_kwargs?.tool_calls;
1216
+ if (!Array.isArray(calls)) return;
1217
+ for (const call of calls) {
1218
+ const callId = String(call?.id || "").trim();
1219
+ if (!callId) continue;
1220
+ const input = asArgsObject(call?.args);
1221
+ const artifactMeta = call?.artifact_meta;
1222
+ const prev = byCallId.get(callId);
1223
+ if (prev) {
1224
+ const richer = pickRicherArgs(prev.input, call?.args);
1225
+ if (richer) prev.input = richer;
1226
+ if (!prev.artifactMeta && artifactMeta) prev.artifactMeta = artifactMeta;
1227
+ continue;
1228
+ }
1229
+ const tool = { callId, name: String(call?.name || ""), status: "running" };
1230
+ if (input !== void 0) tool.input = input;
1231
+ if (artifactMeta !== void 0) tool.artifactMeta = artifactMeta;
1232
+ tools.push(tool);
1233
+ byCallId.set(callId, tool);
1234
+ }
1235
+ }
1236
+ function applyToolMessage(msg, tools, byCallId) {
1237
+ const callId = String(msg?.tool_call_id || "").trim();
1238
+ if (!callId) return;
1239
+ const tool = byCallId.get(callId);
1240
+ if (!tool) return;
1241
+ const result = readMessageContentText(msg);
1242
+ tool.result = result;
1243
+ const extracted = extractFromToolResult(tool.name, result, { artifact_meta: tool.artifactMeta, args: tool.input });
1244
+ if (extracted) tool.extracted = extracted;
1245
+ tool.status = String(msg?.status || "") === "error" ? "error" : "finished";
1246
+ }
1247
+ function assembleAttachments(tools, twinEnabled, twinToolPrefix) {
1248
+ const byKind = /* @__PURE__ */ new Map();
1249
+ for (const tool of tools) {
1250
+ const ex = tool.extracted;
1251
+ if (ex?.kind === "report") {
1252
+ byKind.set(`report:${ex.reportKind}`, {
1253
+ kind: "report",
1254
+ reportKind: ex.reportKind,
1255
+ body: ex.body,
1256
+ outline: ex.outline,
1257
+ sourcePath: ex.sourcePath,
1258
+ title: ex.title
1259
+ });
1260
+ } else if (ex?.kind === "artifact") {
1261
+ byKind.set("artifact", { kind: "artifact", files: ex.files });
1262
+ } else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
1263
+ byKind.set("twin", { kind: "twin", payload: tool.input });
2272
1264
  }
2273
- ];
2274
- }
2275
- function findLastAiIndex(groups) {
2276
- for (let i = groups.length - 1; i >= 0; i--) {
2277
- if (groups[i].type === "ai") return i;
2278
1265
  }
2279
- return -1;
1266
+ return [...byKind.values()];
2280
1267
  }
2281
- function decorateAnswers(groups, answers, responded) {
2282
- if (!answers.size && !responded.size) return groups;
2283
- return groups.map((g) => {
2284
- if (g.type !== "ai" || !g.blocks.length) return g;
2285
- let touched = false;
2286
- const blocks = g.blocks.map((b) => {
2287
- const blk = b;
2288
- if (isClarificationBlock(blk) && blk.toolCallId && answers.has(blk.toolCallId)) {
2289
- touched = true;
2290
- return { ...b, isAnswered: true, answer: answers.get(blk.toolCallId) };
2291
- }
2292
- if (blk.type === "interrupt-review" && blk.interruptId && responded.has(blk.interruptId)) {
2293
- touched = true;
2294
- return { ...b, isResponded: true };
2295
- }
2296
- return b;
2297
- });
2298
- return touched ? { ...g, blocks } : g;
2299
- });
1268
+ function extractClarifications(tools) {
1269
+ const out = [];
1270
+ for (const tool of tools) {
1271
+ if (tool.name !== "ask_clarification") continue;
1272
+ const args = asArgsObject(tool.input);
1273
+ const question = String(args?.question ?? args?.title ?? "").trim();
1274
+ if (!question) continue;
1275
+ const record = { callId: tool.callId, question };
1276
+ if (args?.options !== void 0) record.options = args.options;
1277
+ if (Array.isArray(args?.fields)) record.fields = args.fields;
1278
+ out.push(record);
1279
+ }
1280
+ return out;
2300
1281
  }
2301
- function filterInvisibleAiGroups(groups) {
2302
- return groups.filter((g) => g.type !== "ai" || hasVisibleAiContent(g));
1282
+ function mapBackendStatus(raw) {
1283
+ const v = String(raw || "").trim();
1284
+ return BACKEND_STATUS_MAP[v] ?? "success";
2303
1285
  }
2304
- function hasVisibleAiContent(g) {
2305
- if (g.status === "streaming") return true;
2306
- if (g.streamingText) return true;
2307
- if (g.blocks.length) return true;
2308
- return g.tools.some((t) => t.result !== void 0 || t.state === "error");
1286
+
1287
+ // src/parser/thread-info.ts
1288
+ function formatAnswerText(value) {
1289
+ if (value == null) return "";
1290
+ if (typeof value === "string") return value;
1291
+ if (typeof value === "object") {
1292
+ const values = value.values;
1293
+ if (values && typeof values === "object" && !Array.isArray(values)) {
1294
+ return Object.values(values).filter((v) => v !== void 0 && v !== null && v !== "").map(String).join("; ");
1295
+ }
1296
+ try {
1297
+ return JSON.stringify(value);
1298
+ } catch {
1299
+ return String(value);
1300
+ }
1301
+ }
1302
+ return String(value);
2309
1303
  }
2310
1304
 
2311
- // src/domain/viewmodel-state.ts
2312
- var import_vue4 = require("vue");
2313
- function createViewModelState() {
2314
- const extrasRef = (0, import_vue4.shallowRef)([]);
2315
- const patches = (0, import_vue4.shallowReactive)(/* @__PURE__ */ new Map());
2316
- const readFirstText = (group) => extractTextFromMessage(asSxin(group.rawMessages[0])).trim();
1305
+ // src/assembler/project-runs.ts
1306
+ function classifyInputKind(inputMsg) {
1307
+ const kwargs = inputMsg?.additional_kwargs;
1308
+ if (kwargs?.human_input_response && typeof kwargs.human_input_response === "object") return "clarification";
1309
+ return "message";
1310
+ }
1311
+ function inputFromRunMeta(meta) {
1312
+ const messages = meta.inputMessages ?? [];
1313
+ if (!messages.length) return null;
1314
+ const first = messages[0];
1315
+ const visible = messages.find((m) => isVisibleUserMessage(m));
1316
+ const text = visible ? readMessageContentText(visible) : "";
1317
+ const kwargs = first.additional_kwargs;
1318
+ const hasKwargs = kwargs && typeof kwargs === "object" && Object.keys(kwargs).length > 0;
2317
1319
  return {
2318
- get extras() {
2319
- return extrasRef.value;
2320
- },
2321
- get patches() {
2322
- return patches;
2323
- },
2324
- appendExtra(groups) {
2325
- if (!groups.length) return;
2326
- extrasRef.value = [...extrasRef.value, ...groups];
2327
- },
2328
- patchGroup(messageId, patch, sourceGroups) {
2329
- const current = patches.get(messageId) ?? sourceGroups().find((g) => g.id === messageId);
2330
- if (!current) return;
2331
- const next = typeof patch === "function" ? patch(current) : { ...current, ...patch };
2332
- patches.set(messageId, { ...next, id: current.id });
2333
- },
2334
- clearPatches() {
2335
- patches.clear();
2336
- extrasRef.value = [];
2337
- },
2338
- /** human extras 按序收敛:回显(同文本 + 当前流 runId)到达后按序移除乐观副本。
2339
- * 用 runId 而非流式段判定:既有线程的回显可能经 reconcile 以 page-source 到达(不在流式段),
2340
- * 但其 runId 与当前流一致;历史消息 runId 不同,不会误伤(连发同文本逐条配对)。
2341
- * 无当前流 runId(流未开始)时不 prune——避免历史同文本消息误吞乐观副本。 */
2342
- pruneExtras(decoratedGroups, currentRunId) {
2343
- if (!extrasRef.value.some((g) => g.type === "human")) return;
2344
- const runIdFilter = String(currentRunId || "").trim();
2345
- if (!runIdFilter) return;
2346
- const echoed = /* @__PURE__ */ new Map();
2347
- for (const g of decoratedGroups) {
2348
- if (g.type !== "human") continue;
2349
- const runId = String(g.runId || "").trim();
2350
- if (runId !== runIdFilter) continue;
2351
- const text = readFirstText(g);
2352
- echoed.set(text, (echoed.get(text) ?? 0) + 1);
2353
- }
2354
- const seenPerText = /* @__PURE__ */ new Map();
2355
- extrasRef.value = extrasRef.value.filter((extra) => {
2356
- if (extra.type !== "human") return true;
2357
- const text = readFirstText(extra);
2358
- const k = seenPerText.get(text) ?? 0;
2359
- seenPerText.set(text, k + 1);
2360
- return (echoed.get(text) ?? 0) <= k;
2361
- });
2362
- }
1320
+ kind: classifyInputKind(first),
1321
+ text,
1322
+ ...hasKwargs ? { kwargs: { ...kwargs } } : {}
2363
1323
  };
2364
1324
  }
2365
-
2366
- // src/domain/viewmodel.ts
2367
- function createGroupDeriver(state) {
2368
- const groupMemo = /* @__PURE__ */ new Map();
2369
- const foldCache = { pageCount: -1, entries: [] };
2370
- const interruptBlocks = /* @__PURE__ */ new Map();
2371
- const derive = (deps) => {
2372
- const { store, enrichments } = deps;
2373
- const streaming = store.streamStatus === "streaming";
2374
- const patched = store.getMessages().map((m) => {
2375
- const patch = enrichments.resolveCitation(String(asSxin(m).id || ""));
2376
- if (!patch || patch.content === void 0) return m;
2377
- return { ...asSxin(m), content: patch.content };
2378
- });
2379
- const sourceOf = (id) => id ? store.getEntity(id)?.source ?? "stream" : "stream";
2380
- const epochOf = (id) => id ? store.getEntity(id)?.epoch : void 0;
2381
- const runIdFilter = String(deps.currentRunId || "").trim();
2382
- const currentEpoch = store.streamEpoch;
2383
- const pageCount = store.pageCount;
2384
- const patchedPrefix = patched.slice(0, pageCount);
2385
- const patchedStream = patched.slice(pageCount);
2386
- let prefixEntries;
2387
- if (foldCache.pageCount === pageCount) {
2388
- prefixEntries = foldCache.entries;
1325
+ function normalizeRequestId(raw) {
1326
+ return String(raw ?? "").trim().replace("clarification:", "");
1327
+ }
1328
+ function projectRuns(input) {
1329
+ const buckets = groupRowsByRun(input.rows, input.liveMessages, input.activeRunId, input.pendingRun?.runId ?? null);
1330
+ const metaByRunId = new Map(input.runsList.map((m) => [String(m.runId || ""), m]));
1331
+ const orderedBuckets = [...buckets.entries()].sort(
1332
+ (a, b) => (a[1][0]?.seq ?? 0) - (b[1][0]?.seq ?? 0)
1333
+ );
1334
+ const runs = [];
1335
+ for (const [runId, rows] of orderedBuckets) {
1336
+ const meta = metaByRunId.get(runId);
1337
+ const isStreamingRun = input.streaming && input.activeRunId === runId;
1338
+ const item = assembleRun(runId, { rows, streaming: isStreamingRun, twin: input.twin });
1339
+ const fromMeta = meta ? inputFromRunMeta(meta) : void 0;
1340
+ if (fromMeta) {
1341
+ item.input = fromMeta;
2389
1342
  } else {
2390
- prefixEntries = [];
2391
- foldMessages(
2392
- patchedPrefix,
2393
- (type, buf) => prefixEntries.push({ type, ids: buf.map((m) => String(asSxin(m).id || "")) })
2394
- );
2395
- foldCache.pageCount = pageCount;
2396
- foldCache.entries = prefixEntries;
2397
- }
2398
- const prefixById = new Map(patchedPrefix.map((m) => [String(asSxin(m).id || ""), m]));
2399
- const folded = [];
2400
- if (prefixEntries.every((e) => e.ids.every((id) => prefixById.has(id)))) {
2401
- for (const e of prefixEntries) folded.push({ type: e.type, buf: e.ids.map((id) => prefixById.get(id)) });
2402
- const streamFolded = [];
2403
- foldMessages(patchedStream, (type, buf) => streamFolded.push({ type, buf }));
2404
- const lastPrefix = folded[folded.length - 1];
2405
- const firstStream = streamFolded[0];
2406
- if (lastPrefix && firstStream && canMergeAtBoundary(lastPrefix, firstStream)) {
2407
- lastPrefix.buf = [...lastPrefix.buf, ...firstStream.buf];
2408
- streamFolded.shift();
1343
+ const fromRows = extractInputFromRows(rows);
1344
+ if (fromRows.text) {
1345
+ item.input = {
1346
+ kind: classifyInputKind(fromRows.kwargs),
1347
+ text: fromRows.text,
1348
+ ...fromRows.kwargs ? { kwargs: fromRows.kwargs } : {}
1349
+ };
2409
1350
  }
2410
- folded.push(...streamFolded);
2411
- } else {
2412
- foldCache.pageCount = -1;
2413
- foldCache.entries = [];
2414
- foldMessages(patched, (type, buf) => folded.push({ type, buf }));
2415
1351
  }
2416
- const groups = [];
2417
- let epochActiveFrom = 0;
2418
- if (streaming && !runIdFilter) {
2419
- epochActiveFrom = -1;
2420
- folded.forEach((entry, i) => {
2421
- const id = String(asSxin(entry.buf[0]).id || "");
2422
- if (entry.type === "human" && sourceOf(id) === "stream" && epochOf(id) === currentEpoch) epochActiveFrom = i;
2423
- });
2424
- if (epochActiveFrom < 0) epochActiveFrom = 0;
1352
+ const pendingInput = input.pendingRun;
1353
+ if (pendingInput && runId === pendingInput.runId && !item.input.text) {
1354
+ item.input = {
1355
+ kind: pendingInput.kind,
1356
+ text: pendingInput.text,
1357
+ ...pendingInput.kwargs ? { kwargs: pendingInput.kwargs } : {}
1358
+ };
2425
1359
  }
2426
- folded.forEach((entry, gi) => {
2427
- const firstId = String(asSxin(entry.buf[0]).id || "");
2428
- const firstSource = sourceOf(firstId);
2429
- let groupRunId = messageRunId(entry.buf[0]);
2430
- if (!groupRunId) {
2431
- for (let i = 1; i < entry.buf.length; i++) {
2432
- const rid = messageRunId(entry.buf[i]);
2433
- if (rid) {
2434
- groupRunId = rid;
2435
- break;
2436
- }
2437
- }
2438
- }
2439
- groupRunId = groupRunId || void 0;
2440
- const inActiveZone = streaming ? runIdFilter ? groupRunId === runIdFilter : firstSource === "stream" && epochOf(firstId) === currentEpoch && gi >= epochActiveFrom : false;
2441
- const status = inActiveZone ? "streaming" : "completed";
2442
- const blockSource = firstSource === "page" ? "history" : "sse";
2443
- let verSum = 0;
2444
- for (const m of entry.buf) verSum += store.getEntity(String(asSxin(m).id || ""))?.ver ?? 0;
2445
- const memoKey = `${firstId}|${status}|${blockSource}|${entry.buf.length}|${verSum}|${enrichments.citationVersion}`;
2446
- const cached = groupMemo.get(memoKey);
2447
- if (cached) {
2448
- groups.push(cached);
2449
- return;
1360
+ if (isStreamingRun) item.status = "running";
1361
+ else if (meta) {
1362
+ item.status = mapBackendStatus(meta.status);
1363
+ if (meta.tokens) item.tokens = meta.tokens;
1364
+ if (meta.createdAt !== void 0) item.createdAt = meta.createdAt;
1365
+ if (meta.stopReason) item.stopReason = meta.stopReason;
1366
+ }
1367
+ runs.push(item);
1368
+ }
1369
+ const pending = input.pendingRun;
1370
+ if (pending && !buckets.has(pending.runId)) {
1371
+ const placeholder = emptyRunItem(pending.runId, Date.now());
1372
+ placeholder.input = { kind: pending.kind, text: pending.text, ...pending.kwargs ? { kwargs: { ...pending.kwargs } } : {} };
1373
+ if (input.streaming && input.activeRunId === pending.runId) placeholder.status = "running";
1374
+ runs.push(placeholder);
1375
+ }
1376
+ const answers = input.answers;
1377
+ for (let i = 0; i < runs.length; i++) {
1378
+ const run = runs[i];
1379
+ for (const record of run.clarifications) {
1380
+ if (record.answer !== void 0) continue;
1381
+ const optimistic = answers?.get(record.callId);
1382
+ if (optimistic !== void 0) {
1383
+ record.answer = optimistic;
1384
+ continue;
2450
1385
  }
2451
- let g;
2452
- if (entry.type === "human") {
2453
- g = buildHumanGroup(entry.buf, status);
2454
- } else {
2455
- g = buildAiGroup(entry.buf, { source: blockSource, isStreaming: status === "streaming" }, deps.twin);
1386
+ for (let j = i + 1; j < runs.length; j++) {
1387
+ const laterKwargs = runs[j].input.kwargs;
1388
+ const response = laterKwargs?.human_input_response;
1389
+ if (!response || typeof response !== "object") continue;
1390
+ if (normalizeRequestId(response.request_id) !== normalizeRequestId(record.callId)) continue;
1391
+ record.answer = formatAnswerText(response.value);
1392
+ record.answerRunId = runs[j].runId;
1393
+ break;
2456
1394
  }
2457
- if (groupMemo.size > 2e3) groupMemo.clear();
2458
- groupMemo.set(memoKey, g);
2459
- groups.push(g);
2460
- });
2461
- for (const g of groups) {
2462
- if (g.type === "ai" && g.status === "streaming") {
2463
- const aiMessages = g.rawMessages.filter((m) => String(asSxin(m).type || "").startsWith("ai"));
2464
- const lastAi = aiMessages[aiMessages.length - 1];
2465
- g.streamingText = lastAi ? extractAiContentFromMessage(lastAi) : "";
1395
+ }
1396
+ }
1397
+ return runs;
1398
+ }
1399
+
1400
+ // src/runtime/values-projection.ts
1401
+ function createValuesChannel(options = {}) {
1402
+ let latestStreamMessages = [];
1403
+ let lastTitle = "";
1404
+ return {
1405
+ beginStream() {
1406
+ latestStreamMessages = [];
1407
+ },
1408
+ applyValuesEvent(data) {
1409
+ if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
1410
+ const title = String(data?.title || "").trim();
1411
+ if (title && title !== lastTitle) {
1412
+ lastTitle = title;
1413
+ options.onTitle?.(title);
2466
1414
  }
1415
+ },
1416
+ getStreamMessages() {
1417
+ return [...latestStreamMessages];
2467
1418
  }
2468
- const sourceGroups = groups;
2469
- const decorateSteps = [
2470
- // 第 1 步:补丁应用 + 乐观 extras 锚点落位
2471
- (gs) => applyPatchesAndExtras(gs, state, runIdFilter),
2472
- // 第 2 步:interrupt 审核块注入(去重记忆 interruptBlocks 为构建器公开职责)
2473
- (gs) => withInterruptBlock(gs, {
2474
- getInterrupt: deps.getInterrupt,
2475
- respondedIds: deps.respondedIds,
2476
- interruptBlocks
2477
- }),
2478
- // 第 3 步:澄清回答 / interrupt 响应标记装饰
2479
- (gs) => decorateAnswers(gs, enrichments.answers, deps.respondedIds),
2480
- // 第 4 步:隐藏「无可见内容」的 AI 空气泡
2481
- filterInvisibleAiGroups
2482
- ];
2483
- const merged = decorateSteps.reduce((gs, step) => step(gs), sourceGroups);
2484
- return { groups: merged, sourceGroups };
2485
1419
  };
1420
+ }
1421
+
1422
+ // src/store/runs-store.ts
1423
+ var import_vue3 = require("vue");
1424
+ function createInterruptState() {
1425
+ const respondedIds = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Set());
2486
1426
  return {
2487
- derive,
2488
- clearCache() {
2489
- groupMemo.clear();
2490
- foldCache.pageCount = -1;
2491
- foldCache.entries = [];
2492
- interruptBlocks.clear();
1427
+ respondedIds,
1428
+ markResponded(id) {
1429
+ const next = new Set(respondedIds.value);
1430
+ next.add(id);
1431
+ respondedIds.value = next;
1432
+ },
1433
+ unmarkResponded(id) {
1434
+ if (!respondedIds.value.has(id)) return;
1435
+ const next = new Set(respondedIds.value);
1436
+ next.delete(id);
1437
+ respondedIds.value = next;
2493
1438
  }
2494
1439
  };
2495
1440
  }
2496
- function canMergeAtBoundary(prefixLast, streamFirst) {
2497
- if (prefixLast.type === "human" && streamFirst.type === "human") {
2498
- return getHumanMessageBaseId(String(asSxin(streamFirst.buf[0]).id || "")) === getHumanMessageBaseId(String(asSxin(prefixLast.buf[0]).id || ""));
2499
- }
2500
- if (prefixLast.type === "ai" && streamFirst.type === "ai") {
2501
- const mRunId = messageRunId(streamFirst.buf[0]);
2502
- const groupRunId = messageRunId(prefixLast.buf[0]);
2503
- return !(mRunId && groupRunId && mRunId !== groupRunId);
2504
- }
2505
- return false;
2506
- }
2507
- function createOptimisticHuman(text, options) {
2508
- const optimisticId = genMessageId();
1441
+ function createRunsStore(options) {
1442
+ const runsMap = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Map());
1443
+ const currentRunId = (0, import_vue3.shallowRef)(null);
2509
1444
  return {
2510
- id: optimisticId,
2511
- type: "human",
2512
- status: "completed",
2513
- originMessageIds: [optimisticId],
2514
- rawMessages: [
2515
- {
2516
- id: optimisticId,
2517
- type: "human",
2518
- name: "user-input",
2519
- content: [{ type: "text", text }],
2520
- additional_kwargs: options?.kwargs
1445
+ runsMap,
1446
+ currentRunId,
1447
+ fillFromRunsList(runsList) {
1448
+ let next = null;
1449
+ for (const run of runsList) {
1450
+ const runId = String(run?.run_id || "").trim();
1451
+ if (!runId) continue;
1452
+ next ?? (next = new Map(runsMap.value));
1453
+ next.set(runId, buildRunInfo(run, options.threadId));
2521
1454
  }
2522
- ],
2523
- additionalKwargs: options?.kwargs,
2524
- blocks: [],
2525
- toolIds: [],
2526
- tools: [],
2527
- createdAt: Date.now()
1455
+ if (next) runsMap.value = next;
1456
+ },
1457
+ ensureRunning(runId) {
1458
+ if (runsMap.value.has(runId)) return;
1459
+ const next = new Map(runsMap.value);
1460
+ ensureRunningRun(next, runId, options.threadId);
1461
+ runsMap.value = next;
1462
+ },
1463
+ async refreshRuns() {
1464
+ try {
1465
+ const runsList = await options.transport.listRuns(options.threadId, 20);
1466
+ if (!Array.isArray(runsList)) return;
1467
+ const merged = new Map(runsMap.value);
1468
+ for (const run of runsList) {
1469
+ const runId = String(run.run_id || "").trim();
1470
+ if (!runId) continue;
1471
+ const info = buildRunInfo(run, options.threadId);
1472
+ const prev = merged.get(runId);
1473
+ if (!prev) {
1474
+ merged.set(runId, info);
1475
+ continue;
1476
+ }
1477
+ const directLatency = buildRunDirectLatencyMs(run);
1478
+ merged.set(runId, {
1479
+ ...info,
1480
+ feedback: info.feedback ?? prev.feedback,
1481
+ latencyMs: directLatency ?? prev.latencyMs ?? info.latencyMs,
1482
+ modelName: info.modelName ?? prev.modelName,
1483
+ finishReason: info.finishReason ?? prev.finishReason
1484
+ });
1485
+ }
1486
+ runsMap.value = merged;
1487
+ } catch (e) {
1488
+ console.warn("[runs-store] refreshRuns failed", e);
1489
+ }
1490
+ },
1491
+ enrichFromPage(page) {
1492
+ const enrichment = extractRunEnrichment(page.messages);
1493
+ let next = null;
1494
+ for (const [runId, patch] of enrichment) {
1495
+ const run = (next ?? runsMap.value).get(runId);
1496
+ if (!run) continue;
1497
+ next ?? (next = new Map(runsMap.value));
1498
+ next.set(runId, {
1499
+ ...run,
1500
+ ...patch.feedback !== void 0 ? { feedback: patch.feedback } : {},
1501
+ ...patch.latencyMs !== void 0 ? { latencyMs: patch.latencyMs } : {}
1502
+ });
1503
+ }
1504
+ if (next) runsMap.value = next;
1505
+ },
1506
+ backfillCurrentRunMetadata(getMessages) {
1507
+ const runId = currentRunId.value;
1508
+ if (!runId) return;
1509
+ const run = runsMap.value.get(runId);
1510
+ if (!run) return;
1511
+ if (run.modelName && run.finishReason) return;
1512
+ const currentRunMessages = getMessages().filter((m) => String(m?.runId || "") === runId);
1513
+ const source = currentRunMessages.length ? currentRunMessages : getMessages();
1514
+ const picked = pickRunMessageMetadata(source);
1515
+ if (!picked.modelName && !picked.finishReason) return;
1516
+ runsMap.value = new Map(runsMap.value).set(runId, {
1517
+ ...run,
1518
+ ...picked.modelName && !run.modelName ? { modelName: picked.modelName } : {},
1519
+ ...picked.finishReason && !run.finishReason ? { finishReason: picked.finishReason } : {}
1520
+ });
1521
+ },
1522
+ patchRun(runId, patch) {
1523
+ const run = runsMap.value.get(runId);
1524
+ if (!run) return;
1525
+ runsMap.value = new Map(runsMap.value).set(runId, { ...run, ...patch });
1526
+ },
1527
+ dispose() {
1528
+ runsMap.value = /* @__PURE__ */ new Map();
1529
+ currentRunId.value = null;
1530
+ }
2528
1531
  };
2529
1532
  }
2530
1533
 
2531
- // src/runtime/derived-groups.ts
2532
- var import_vue5 = require("vue");
2533
- function createDerivedGroups(deps) {
2534
- const deriver = createGroupDeriver(deps.state);
2535
- const derived = (0, import_vue5.computed)(() => {
2536
- deps.store.version.value;
2537
- return deriver.derive({
2538
- store: deps.store,
2539
- enrichments: deps.enrichments,
2540
- getInterrupt: () => deps.valuesChannel.getInterrupt({ isLoading: deps.streamRef.value?.isLoading.value ?? false }),
2541
- respondedIds: deps.interruptState.respondedIds.value,
2542
- currentRunId: deps.runs.currentRunId.value ?? void 0,
2543
- twin: deps.twin
2544
- });
2545
- });
2546
- deps.scope.run(() => {
2547
- (0, import_vue5.watch)(
2548
- () => [deps.store.version.value, deps.runs.currentRunId.value],
2549
- () => {
2550
- deps.state.pruneExtras(derived.value.sourceGroups, deps.runs.currentRunId.value ?? void 0);
2551
- },
2552
- { flush: "sync" }
2553
- );
2554
- });
2555
- const groups = (0, import_vue5.computed)(() => derived.value.groups);
2556
- const sourceGroups = (0, import_vue5.computed)(() => derived.value.sourceGroups);
2557
- return { groups, sourceGroups };
2558
- }
2559
-
2560
1534
  // src/runtime/thread-runtime.ts
1535
+ var pendingSeq = 0;
1536
+ function newPendingRunId() {
1537
+ pendingSeq += 1;
1538
+ return `local-${Date.now()}-${pendingSeq}`;
1539
+ }
2561
1540
  function createThreadRuntime(options) {
2562
- const scope = (0, import_vue6.effectScope)();
2563
- const store = createThreadStore({ threadId: options.threadId });
2564
- const enrichments = createEnrichments();
1541
+ const scope = (0, import_vue4.effectScope)();
2565
1542
  const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
2566
1543
  const interruptState = createInterruptState();
2567
- const state = createViewModelState();
1544
+ const rowsStore = createRowsStore();
1545
+ const overlay = createSemanticOverlay();
2568
1546
  const valuesChannel = createValuesChannel({
2569
1547
  onTitle: (title) => options.onTitle?.(options.threadId, title)
2570
1548
  });
2571
- let chunkBuffer = null;
2572
- const streamRef = (0, import_vue6.shallowRef)(null);
2573
- const isInitializing = (0, import_vue6.ref)(false);
2574
- const tokenUsage = (0, import_vue6.shallowRef)(null);
1549
+ const streamRef = (0, import_vue4.shallowRef)(null);
1550
+ const isInitializing = (0, import_vue4.ref)(false);
1551
+ const streaming = (0, import_vue4.ref)(false);
1552
+ const tokenUsage = (0, import_vue4.shallowRef)(null);
2575
1553
  let initialized = false;
2576
1554
  let initPromise = null;
2577
1555
  let pager = null;
2578
- const derivedGroups = createDerivedGroups({
2579
- scope,
2580
- store,
2581
- enrichments,
2582
- state,
2583
- runs,
2584
- interruptState,
2585
- valuesChannel,
2586
- streamRef,
2587
- twin: options.twin
2588
- });
2589
- const { groups, sourceGroups } = derivedGroups;
2590
- const interrupt = (0, import_vue6.computed)(() => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }));
2591
- const hasPendingInterrupt = (0, import_vue6.computed)(() => {
1556
+ const runsListMeta = (0, import_vue4.shallowRef)([]);
1557
+ const liveMessages = (0, import_vue4.shallowRef)([]);
1558
+ const lastSeenLiveIds = /* @__PURE__ */ new Set();
1559
+ const pendingRun = (0, import_vue4.shallowRef)(null);
1560
+ const answers = (0, import_vue4.shallowRef)(/* @__PURE__ */ new Map());
1561
+ const activeRunId = (0, import_vue4.computed)(() => runs.currentRunId.value);
1562
+ const runsProjection = (0, import_vue4.computed)(
1563
+ () => projectRuns({
1564
+ rows: rowsStore.rows.value,
1565
+ liveMessages: liveMessages.value,
1566
+ activeRunId: activeRunId.value,
1567
+ runsList: runsListMeta.value,
1568
+ pendingRun: pendingRun.value,
1569
+ answers: answers.value,
1570
+ twin: options.twin,
1571
+ streaming: streaming.value
1572
+ })
1573
+ );
1574
+ const interrupt = (0, import_vue4.computed)(() => streamRef.value?.interrupt.value);
1575
+ const hasPendingInterrupt = (0, import_vue4.computed)(() => {
2592
1576
  const it = interrupt.value;
2593
1577
  return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
2594
1578
  });
2595
- const streamError = (0, import_vue6.computed)(() => streamRef.value?.error.value ?? null);
2596
- const isGenerating = (0, import_vue6.computed)(() => store.streamStatusRef.value === "streaming");
2597
- const hasPendingClarification = (0, import_vue6.computed)(() => {
2598
- store.version.value;
2599
- const list = groups.value;
2600
- return list.some((m, i) => {
2601
- if (m.type !== "ai") return false;
2602
- const hasUnanswered = m.blocks.some(
2603
- (b) => isClarificationBlock(b) && !isClarificationAnswered(b, enrichments.answers)
2604
- );
2605
- if (!hasUnanswered) return false;
2606
- return !list.slice(i + 1).some((x) => x.type === "human");
2607
- });
1579
+ const streamError = (0, import_vue4.computed)(() => streamRef.value?.error.value ?? null);
1580
+ const isGenerating = (0, import_vue4.computed)(() => streaming.value);
1581
+ const activeClarification = (0, import_vue4.computed)(() => {
1582
+ const list = runsProjection.value;
1583
+ for (let i = list.length - 1; i >= 0; i--) {
1584
+ const clarifications = list[i].clarifications;
1585
+ for (let c = clarifications.length - 1; c >= 0; c--) {
1586
+ if (clarifications[c].answer === void 0) return clarifications[c];
1587
+ }
1588
+ }
1589
+ return void 0;
2608
1590
  });
1591
+ const clarificationAnswers = (0, import_vue4.computed)(() => answers.value);
2609
1592
  const beginStream = () => {
2610
- chunkBuffer?.reset();
2611
1593
  valuesChannel.beginStream();
1594
+ overlay.invalidate();
2612
1595
  runs.currentRunId.value = null;
1596
+ liveMessages.value = [];
1597
+ lastSeenLiveIds.clear();
2613
1598
  };
2614
1599
  const streamStarted = () => {
2615
- store.beginStream();
1600
+ streaming.value = true;
1601
+ };
1602
+ const streamSettled = () => {
1603
+ streaming.value = false;
1604
+ pendingRun.value = null;
2616
1605
  };
2617
1606
  const markStreamRun = (runIdRaw) => {
2618
1607
  const runId = String(runIdRaw || "").trim();
2619
1608
  if (!runId) return;
2620
1609
  runs.currentRunId.value = runId;
2621
1610
  runs.ensureRunning(runId);
2622
- chunkBuffer?.noteStreamRunId(runId);
1611
+ const pending = pendingRun.value;
1612
+ if (pending && pending.runId !== runId) {
1613
+ pendingRun.value = { ...pending, runId };
1614
+ }
1615
+ };
1616
+ const applyLiveSnapshot = (messages) => {
1617
+ if (!streaming.value) return;
1618
+ const fresh = extractLiveIncrement(messages, lastSeenLiveIds);
1619
+ const eligible = fresh.filter((m) => {
1620
+ const t = String(m?.type || "");
1621
+ return t === "ai" || t === "tool";
1622
+ });
1623
+ if (!eligible.length) return;
1624
+ liveMessages.value = [...liveMessages.value, ...eligible];
2623
1625
  };
2624
1626
  const refreshTokenUsage = async () => {
2625
1627
  try {
@@ -2633,17 +1635,18 @@ function createThreadRuntime(options) {
2633
1635
  threadId: options.threadId,
2634
1636
  assistantId: options.assistantId,
2635
1637
  transport: options.transport,
2636
- store,
2637
- enrichments,
2638
1638
  runs,
1639
+ rowsStore,
1640
+ runsListMeta,
1641
+ overlay,
2639
1642
  valuesChannel,
2640
1643
  streamRef,
2641
- setChunkBuffer: (b) => chunkBuffer = b,
2642
- getChunkBuffer: () => chunkBuffer,
2643
1644
  setPager: (p) => pager = p,
2644
1645
  setInitialized: () => initialized = true,
2645
1646
  markStreamRun,
1647
+ applyLiveSnapshot,
2646
1648
  onStreamStart: streamStarted,
1649
+ onStreamSettled: streamSettled,
2647
1650
  refreshTokenUsage
2648
1651
  },
2649
1652
  {
@@ -2651,23 +1654,39 @@ function createThreadRuntime(options) {
2651
1654
  onEnd: () => isInitializing.value = false
2652
1655
  }
2653
1656
  );
1657
+ const actions = createStreamActions({
1658
+ options,
1659
+ getHandle: () => streamRef.value,
1660
+ beginStream,
1661
+ markStreamRun,
1662
+ getInterrupt: () => streamRef.value?.interrupt.value,
1663
+ markResponded: (id) => interruptState.markResponded(id),
1664
+ unmarkResponded: (id) => interruptState.unmarkResponded(id),
1665
+ getPager: () => pager,
1666
+ runs,
1667
+ createPendingRun: (text, kind, kwargs) => {
1668
+ const pending = { runId: newPendingRunId(), text, kind, kwargs };
1669
+ pendingRun.value = pending;
1670
+ return pending.runId;
1671
+ }
1672
+ });
2654
1673
  return {
2655
1674
  threadId: options.threadId,
2656
1675
  lastViewedAt: Date.now(),
2657
1676
  touch() {
2658
1677
  this.lastViewedAt = Date.now();
2659
1678
  },
2660
- groups,
1679
+ runs: runsProjection,
1680
+ runsInfo: (0, import_vue4.computed)(() => runs.runsMap.value),
1681
+ activeClarification,
2661
1682
  isGenerating,
2662
1683
  isInitializing,
2663
- runs: (0, import_vue6.computed)(() => runs.runsMap.value),
2664
1684
  interrupt,
2665
1685
  hasPendingInterrupt,
2666
- hasPendingClarification,
2667
1686
  streamError,
2668
1687
  tokenUsage,
2669
- hasMoreHistory: (0, import_vue6.computed)(() => pager?.hasMore.value ?? false),
2670
- loadingHistory: (0, import_vue6.computed)(() => pager?.loading.value ?? false),
1688
+ hasMoreHistory: (0, import_vue4.computed)(() => pager?.hasMore.value ?? false),
1689
+ loadingHistory: (0, import_vue4.computed)(() => pager?.loading.value ?? false),
2671
1690
  async init() {
2672
1691
  if (initialized) return;
2673
1692
  if (initPromise) return initPromise;
@@ -2678,64 +1697,52 @@ function createThreadRuntime(options) {
2678
1697
  initPromise = null;
2679
1698
  }
2680
1699
  },
2681
- submit(text, submitOptions) {
2682
- const handle = streamRef.value;
2683
- if (!handle) return;
2684
- beginStream();
2685
- const humanMessage = { type: "human", content: [{ type: "text", text }] };
2686
- humanMessage.additional_kwargs = submitOptions?.kwargs;
2687
- handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
2688
- },
2689
- async joinStream(runId, lastEventId) {
2690
- const handle = streamRef.value;
2691
- if (!handle) return;
2692
- beginStream();
2693
- markStreamRun(runId);
2694
- await handle.joinStream(runId, lastEventId ?? "-1");
2695
- },
2696
- stop() {
2697
- void options.transport.cancelRun(options.threadId, runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
2698
- streamRef.value?.stop();
2699
- },
2700
- async resumeInterrupt(decisions) {
2701
- const it = valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false });
2702
- const interruptId = String(it?.id || "");
2703
- if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
2704
- const handle = streamRef.value;
2705
- if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
2706
- interruptState.markResponded(interruptId);
2707
- beginStream();
2708
- await handle.resumeInterrupt(decisions);
2709
- },
2710
- async loadOlderMessages() {
2711
- if (!pager) return false;
2712
- return pager.loadOlder();
1700
+ submit: actions.submit,
1701
+ joinStream: actions.joinStream,
1702
+ stop: actions.stop,
1703
+ resumeInterrupt: actions.resumeInterrupt,
1704
+ loadOlderMessages: actions.loadOlderMessages,
1705
+ applyFeedback(messageId, feedback) {
1706
+ rowsStore.mergeLatest(
1707
+ rowsStore.rows.value.map((row) => {
1708
+ const id = String(row.content?.id || "");
1709
+ return id === messageId ? { ...row, feedback } : row;
1710
+ })
1711
+ );
1712
+ const runId = runsProjection.value.find((r) => r.rawMessages.some((m) => m.id === messageId))?.runId;
1713
+ if (runId) runs.patchRun(runId, { feedback });
2713
1714
  },
2714
- appendOptimisticGroups(gs) {
2715
- state.appendExtra(gs);
1715
+ addOptimisticTurn: (body) => {
1716
+ const runId = newPendingRunId();
1717
+ pendingRun.value = { runId, text: body, kind: "message" };
2716
1718
  },
2717
- createOptimisticHuman(text, opts) {
2718
- return createOptimisticHuman(text, opts);
1719
+ updateAiBody(aiId, body) {
1720
+ rowsStore.mergeLatest(
1721
+ rowsStore.rows.value.map((row) => {
1722
+ const id = String(row.content?.id || "");
1723
+ return id === aiId ? { ...row, content: { ...row.content, content: body } } : row;
1724
+ })
1725
+ );
2719
1726
  },
2720
- patchGroup(messageId, patch) {
2721
- state.patchGroup(messageId, patch, () => sourceGroups.value);
1727
+ decorate(messageId, patch) {
1728
+ if (patch.feedback) this.applyFeedback(messageId, patch.feedback);
2722
1729
  },
2723
- applyFeedback(messageId, feedback) {
2724
- const runId = groups.value.find((g) => g.id === messageId)?.runId;
2725
- state.patchGroup(messageId, { feedback }, () => sourceGroups.value);
2726
- if (runId) runs.patchRun(runId, { feedback });
1730
+ finalizeTurns() {
1731
+ pendingRun.value = null;
2727
1732
  },
2728
1733
  setClarificationAnswer(toolCallId, answer) {
2729
- enrichments.setAnswer(toolCallId, answer);
1734
+ const next = new Map(answers.value);
1735
+ next.set(toolCallId, answer);
1736
+ answers.value = next;
2730
1737
  },
2731
1738
  clearClarificationAnswers() {
2732
- enrichments.clearAnswers();
1739
+ if (!answers.value.size) return;
1740
+ answers.value = /* @__PURE__ */ new Map();
2733
1741
  },
2734
- clarificationAnswers: (0, import_vue6.computed)(() => enrichments.answers),
1742
+ clarificationAnswers,
2735
1743
  dispose() {
2736
1744
  streamRef.value?.stop();
2737
- chunkBuffer?.dispose();
2738
- enrichments.dispose();
1745
+ streamRef.value?.dispose?.();
2739
1746
  runs.dispose();
2740
1747
  scope.stop();
2741
1748
  }
@@ -2747,14 +1754,14 @@ var DEFAULT_MAX_CACHED_SESSIONS = 10;
2747
1754
  var DEFAULT_MAX_CONCURRENT_STREAMS = 3;
2748
1755
 
2749
1756
  // src/runtime/thread-directory.ts
2750
- var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending"]);
1757
+ var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending", "interrupted"]);
2751
1758
  function isActiveThreadStatus(status) {
2752
1759
  return typeof status === "string" && ACTIVE_THREAD_STATUSES.has(status);
2753
1760
  }
2754
1761
  var ThreadDirectory = class {
2755
1762
  constructor(options) {
2756
- this.threads = (0, import_vue7.ref)([]);
2757
- this.threadsPagination = (0, import_vue7.ref)({
1763
+ this.threads = (0, import_vue5.ref)([]);
1764
+ this.threadsPagination = (0, import_vue5.ref)({
2758
1765
  limit: 50,
2759
1766
  offset: 0,
2760
1767
  hasMore: true,
@@ -2762,9 +1769,9 @@ var ThreadDirectory = class {
2762
1769
  });
2763
1770
  this.searchKeyword = "";
2764
1771
  /** 正在运行但已超出 SSE 连接上限的 thread(仅用于 UI 提示) */
2765
- this.runningNotConnectedThreadIds = (0, import_vue7.ref)(/* @__PURE__ */ new Set());
1772
+ this.runningNotConnectedThreadIds = (0, import_vue5.ref)(/* @__PURE__ */ new Set());
2766
1773
  /** 活跃 runtime 池(shallowReactive 追踪增删,runtime 实例不被深度代理) */
2767
- this.cachedRuntimes = (0, import_vue7.shallowReactive)(/* @__PURE__ */ new Map());
1774
+ this.cachedRuntimes = (0, import_vue5.shallowReactive)(/* @__PURE__ */ new Map());
2768
1775
  this.transport = options.transport;
2769
1776
  this.assistantId = options.assistantId;
2770
1777
  this.maxCachedRuntimes = options.maxCachedRuntimes ?? DEFAULT_MAX_CACHED_SESSIONS;
@@ -2899,17 +1906,26 @@ var ThreadDirectory = class {
2899
1906
  }
2900
1907
  // ===== 刷新后恢复 =====
2901
1908
  /**
2902
- * 恢复 running run 的 SSE:在已加载列表里过滤活跃线程 → listRuns 确认 → init + joinStream。
2903
- * interrupted 线程不恢复(打开时经 init 恢复 interrupt 卡片)。并行确认,串行连接(并发上限内)。
1909
+ * 恢复未完成 run 的 SSE:按 thread.status(含 interrupted)筛出候选线程并行 listRuns
1910
+ * 取最新 run → init + joinStream。
1911
+ * ⚠️ DeerFlow 语义:thread.status 与 run.status 的 'interrupted' 都表示「run 未完成」
1912
+ *(_derive_thread_status:tasks 非空 → interrupted;涵盖在跑、停在半路、HITL 挂起),
1913
+ * 不等于 LangGraph 官方的「HITL 挂起」——因此 run.status 不作硬判定,最新 run 一律
1914
+ * join:在跑则继续收流;已断则 join 返回 end 帧走 onFinish 对账(runs/state/citation
1915
+ * 刷新),页面收敛到最终状态。join 为只读幂等端点,误 join 无副作用。
1916
+ * 并行确认,串行连接(并发上限内)。
2904
1917
  */
2905
1918
  async recoverRunningThreads() {
2906
- const activeThreads = this.threads.value.filter((t) => isActiveThreadStatus(t.status) && t.thread_id);
1919
+ const candidates = this.threads.value.filter((t) => t.thread_id && isActiveThreadStatus(t.status));
2907
1920
  const results = await Promise.all(
2908
- activeThreads.map(async (thread) => {
1921
+ candidates.map(async (thread) => {
2909
1922
  try {
2910
1923
  const runs = await this.transport.listRuns(thread.thread_id, 5);
2911
- const running = Array.isArray(runs) ? runs.find((r) => r.status === "running" || r.status === "pending") : void 0;
2912
- return running ? { threadId: thread.thread_id, runId: String(running.run_id) } : null;
1924
+ if (!Array.isArray(runs) || runs.length === 0) return null;
1925
+ const latest = [...runs].sort(
1926
+ (a, b) => String(b?.created_at || "").localeCompare(String(a?.created_at || ""))
1927
+ )[0];
1928
+ return latest?.run_id ? { threadId: thread.thread_id, runId: String(latest.run_id) } : null;
2913
1929
  } catch (e) {
2914
1930
  console.warn("[ThreadDirectory] check running run failed", e);
2915
1931
  return null;
@@ -2952,37 +1968,46 @@ function createChatCore(options) {
2952
1968
  notify,
2953
1969
  defaultThreadTitle: options.defaultThreadTitle
2954
1970
  });
2955
- const currentThreadId = (0, import_vue8.ref)(null);
2956
- const threads = (0, import_vue8.computed)(() => directory.threads.value);
2957
- const threadsPagination = (0, import_vue8.computed)(() => directory.threadsPagination.value);
2958
- const activeRuntime = (0, import_vue8.computed)(
1971
+ const currentThreadId = (0, import_vue6.ref)(null);
1972
+ const threads = (0, import_vue6.computed)(() => directory.threads.value);
1973
+ const threadsPagination = (0, import_vue6.computed)(() => directory.threadsPagination.value);
1974
+ const activeRuntime = (0, import_vue6.computed)(
2959
1975
  () => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
2960
1976
  );
2961
- const messages = (0, import_vue8.computed)(() => activeRuntime.value?.groups.value ?? []);
2962
- const isGenerating = (0, import_vue8.computed)(
2963
- () => !!activeRuntime.value && (activeRuntime.value.isGenerating.value || activeRuntime.value.isInitializing.value)
1977
+ const runs = (0, import_vue6.computed)(() => activeRuntime.value?.runs.value ?? []);
1978
+ const runsInfo = (0, import_vue6.computed)(() => activeRuntime.value?.runsInfo.value ?? /* @__PURE__ */ new Map());
1979
+ const toolCalls = (0, import_vue6.computed)(
1980
+ () => runs.value.flatMap(
1981
+ (run) => run.tools.map((tool, index) => ({
1982
+ id: tool.callId,
1983
+ call: { id: tool.callId, name: tool.name, args: tool.input },
1984
+ result: tool.result ? { content: tool.result } : void 0,
1985
+ state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
1986
+ index
1987
+ }))
1988
+ )
2964
1989
  );
2965
- const isLoadingThread = (0, import_vue8.computed)(() => activeRuntime.value?.isInitializing.value ?? false);
2966
- const runs = (0, import_vue8.computed)(
2967
- () => activeRuntime.value?.runs.value ?? /* @__PURE__ */ new Map()
1990
+ const activeClarification = (0, import_vue6.computed)(() => activeRuntime.value?.activeClarification.value);
1991
+ const isGenerating = (0, import_vue6.computed)(
1992
+ () => !!activeRuntime.value && activeRuntime.value.isGenerating.value
2968
1993
  );
2969
- const toolCalls = (0, import_vue8.computed)(() => messages.value.flatMap((g) => g.tools));
2970
- const clarificationAnswers = (0, import_vue8.computed)(
1994
+ const isLoadingThread = (0, import_vue6.computed)(() => activeRuntime.value?.isInitializing.value ?? false);
1995
+ const clarificationAnswers = (0, import_vue6.computed)(
2971
1996
  () => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
2972
1997
  );
2973
- const activeInterrupt = (0, import_vue8.computed)(() => activeRuntime.value?.interrupt.value);
2974
- const hasPendingInterrupt = (0, import_vue8.computed)(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
2975
- const hasPendingClarification = (0, import_vue8.computed)(() => activeRuntime.value?.hasPendingClarification.value ?? false);
2976
- const inputDisabled = (0, import_vue8.computed)(
2977
- () => isGenerating.value || hasPendingClarification.value || hasPendingInterrupt.value
2978
- );
2979
- const streamError = (0, import_vue8.computed)(() => activeRuntime.value?.streamError.value ?? null);
2980
- const hasMoreHistory = (0, import_vue8.computed)(() => activeRuntime.value?.hasMoreHistory.value ?? false);
2981
- const loadingHistory = (0, import_vue8.computed)(() => activeRuntime.value?.loadingHistory.value ?? false);
2982
- const tokenUsage = (0, import_vue8.computed)(() => activeRuntime.value?.tokenUsage.value ?? null);
2983
- const runningNotConnectedThreadIds = (0, import_vue8.computed)(() => directory.runningNotConnectedThreadIds.value);
2984
- const getRunById = (runId) => runId ? runs.value.get(runId) : void 0;
2985
- const getRunsByThreadId = (threadId) => threadId ? Array.from(runs.value.values()).filter((r) => r.threadId === threadId) : [];
1998
+ const activeInterrupt = (0, import_vue6.computed)(() => activeRuntime.value?.interrupt.value);
1999
+ const hasPendingInterrupt = (0, import_vue6.computed)(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
2000
+ const inputDisabled = (0, import_vue6.computed)(() => isGenerating.value || hasPendingInterrupt.value);
2001
+ const streamError = (0, import_vue6.computed)(() => activeRuntime.value?.streamError.value ?? null);
2002
+ const hasMoreHistory = (0, import_vue6.computed)(() => activeRuntime.value?.hasMoreHistory.value ?? false);
2003
+ const loadingHistory = (0, import_vue6.computed)(() => activeRuntime.value?.loadingHistory.value ?? false);
2004
+ const tokenUsage = (0, import_vue6.computed)(() => activeRuntime.value?.tokenUsage.value ?? null);
2005
+ const runningNotConnectedThreadIds = (0, import_vue6.computed)(() => directory.runningNotConnectedThreadIds.value);
2006
+ const getRunById = (runId) => {
2007
+ const info = runId ? runsInfo.value.get(runId) : void 0;
2008
+ return info;
2009
+ };
2010
+ const getRunsByThreadId = (threadId) => threadId ? Array.from(runsInfo.value.values()).filter((r) => r.threadId === threadId) : [];
2986
2011
  const ensureThreadId = async () => {
2987
2012
  if (currentThreadId.value) return { threadId: currentThreadId.value, isNew: false, thread: null };
2988
2013
  const thread = await directory.createThread({ source: "chat" });
@@ -3019,8 +2044,6 @@ function createChatCore(options) {
3019
2044
  runtime.touch();
3020
2045
  if (isNew && thread) directory.prependThread(thread);
3021
2046
  await runtime.init();
3022
- const optimistic = runtime.createOptimisticHuman(trimmed, sendOptions);
3023
- runtime.appendOptimisticGroups([optimistic]);
3024
2047
  runtime.submit(trimmed, sendOptions);
3025
2048
  };
3026
2049
  const loadThread = async (threadId) => {
@@ -3033,41 +2056,30 @@ function createChatCore(options) {
3033
2056
  result.touch();
3034
2057
  await result.init();
3035
2058
  };
3036
- const regenerate = async (assistantMessageId) => {
2059
+ const regenerateTurn = async (runId) => {
3037
2060
  if (isGenerating.value) return;
3038
- const list = messages.value;
3039
- const idx = list.findIndex((m) => m.id === assistantMessageId);
3040
- if (idx < 0) return;
3041
- let question;
3042
- let text = "";
3043
- for (const m of list.slice(0, idx).reverse()) {
3044
- if (m.type !== "human") continue;
3045
- const [t] = m.texts ?? [];
3046
- if (t) {
3047
- question = m;
3048
- text = t;
3049
- break;
3050
- }
3051
- }
3052
- if (!text) {
2061
+ const run = runs.value.find((r) => r.runId === runId);
2062
+ const text = run?.input.text ?? "";
2063
+ if (!run || !text.trim()) {
3053
2064
  notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
3054
2065
  return;
3055
2066
  }
3056
- await sendMessage(text, { kwargs: { ...question?.additionalKwargs, hide_from_ui: false } });
2067
+ await sendMessage(text, { kwargs: { ...run.input.kwargs ?? {}, hide_from_ui: false } });
3057
2068
  };
3058
2069
  return {
3059
- messages,
3060
- groupMessages: messages,
2070
+ runs,
2071
+ turns: runs,
3061
2072
  isGenerating,
3062
2073
  isLoadingThread,
3063
2074
  currentThreadId,
3064
2075
  threads,
3065
2076
  threadsPagination,
3066
- runs,
2077
+ runsInfo,
3067
2078
  toolCalls,
3068
2079
  getRunById,
3069
2080
  getRunsByThreadId,
3070
2081
  clarificationAnswers,
2082
+ activeClarification,
3071
2083
  setClarificationAnswer: (toolCallId, answer) => activeRuntime.value?.setClarificationAnswer(toolCallId, answer),
3072
2084
  clearClarificationAnswers: () => activeRuntime.value?.clearClarificationAnswers(),
3073
2085
  sendMessage,
@@ -3076,11 +2088,12 @@ function createChatCore(options) {
3076
2088
  clearMessages: () => {
3077
2089
  currentThreadId.value = null;
3078
2090
  },
3079
- updateGroupMessage: (messageId, patch) => activeRuntime.value?.patchGroup(messageId, patch),
3080
- addOptimisticGroupMessages: (ms) => activeRuntime.value?.appendOptimisticGroups(ms),
3081
- updateGroupMessageBlocks: (messageId, blocks) => activeRuntime.value?.patchGroup(messageId, { blocks }),
3082
2091
  applyFeedback: (messageId, feedback) => activeRuntime.value?.applyFeedback(messageId, feedback),
3083
- regenerate,
2092
+ regenerateTurn,
2093
+ addOptimisticTurn: (body) => activeRuntime.value?.addOptimisticTurn(body),
2094
+ updateAiBody: (aiId, body) => activeRuntime.value?.updateAiBody(aiId, body),
2095
+ decorate: (messageId, patch) => activeRuntime.value?.decorate(messageId, patch),
2096
+ finalizeTurns: () => activeRuntime.value?.finalizeTurns(),
3084
2097
  fetchThreads: (reset, keyword) => directory.fetchThreads(reset, keyword),
3085
2098
  deleteThread: async (threadId) => {
3086
2099
  const deleted = await directory.deleteThread(threadId);
@@ -3093,8 +2106,8 @@ function createChatCore(options) {
3093
2106
  runningNotConnectedThreadIds,
3094
2107
  recoverRunningThreads: () => directory.recoverRunningThreads(),
3095
2108
  activeInterrupt,
2109
+ interrupt: activeInterrupt,
3096
2110
  hasPendingInterrupt,
3097
- hasPendingClarification,
3098
2111
  inputDisabled,
3099
2112
  streamError,
3100
2113
  hasMoreHistory,