@cqfe/sxin-chat-core 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,337 +35,10 @@ var import_vue7 = require("vue");
35
35
  // src/runtime/thread-runtime.ts
36
36
  var import_vue6 = require("vue");
37
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
- }
364
-
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);
@@ -470,791 +143,100 @@ function ensureRunningRun(runMap, runId, threadId) {
470
143
  return runInfo;
471
144
  }
472
145
 
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();
146
+ // src/parser/sxin-ast-attrs.ts
147
+ function formatStr(str) {
148
+ if (!str) return str;
149
+ return str.replace(/["`\s]/g, "");
509
150
  }
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 });
151
+ function skipWhitespace(source, i) {
152
+ const len = source.length;
153
+ while (i < len && /\s/.test(source[i])) i++;
154
+ return i;
155
+ }
156
+ function readQuotedValue(source, j, key) {
157
+ const quote = source[j];
158
+ const close = source.indexOf(quote, j + 1);
159
+ if (close === -1) {
160
+ return { key, value: source.slice(j + 1), next: source.length, hasValue: true, truncated: true };
528
161
  }
529
- return instructions;
162
+ return { key, value: source.slice(j + 1, close), next: close + 1, hasValue: true, truncated: false };
530
163
  }
531
- async function afterStreamFinish(deps) {
532
- await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
533
- await reconcileWithPage(deps);
534
- await applyCitationsFallback(deps);
164
+ function readBareValue(source, j, key) {
165
+ const valMatch = /^[^\s>]+/.exec(source.slice(j));
166
+ const raw = valMatch ? valMatch[0] : "";
167
+ const value = raw.endsWith("/") ? raw.slice(0, -1) : raw;
168
+ return { key, value, next: j + raw.length, hasValue: true, truncated: false };
535
169
  }
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);
170
+ function readAttrPair(source, i) {
171
+ const keyMatch = /^[\w-]+/.exec(source.slice(i));
172
+ if (!keyMatch) return null;
173
+ const key = keyMatch[0];
174
+ let j = skipWhitespace(source, i + key.length);
175
+ if (source[j] !== "=") return { key, value: "", next: j, hasValue: false, truncated: false };
176
+ j = skipWhitespace(source, j + 1);
177
+ if (j >= source.length) {
178
+ return { key, value: "", next: source.length, hasValue: true, truncated: true };
545
179
  }
180
+ const quote = source[j];
181
+ return quote === '"' || quote === "'" ? readQuotedValue(source, j, key) : readBareValue(source, j, key);
546
182
  }
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
- }
183
+ function matchTerminator(source, i) {
184
+ if (source[i] === ">") return { selfClosing: false };
185
+ if (source[i] === "/" && source[i + 1] === ">") return { selfClosing: true };
186
+ return null;
556
187
  }
557
- async function runRuntimeInit(deps, hooks) {
558
- hooks.onStart();
559
- try {
560
- await bootstrapRuntime(deps);
561
- } finally {
562
- hooks.onEnd();
188
+ function parseAttrs(source, pos) {
189
+ const attrs = {};
190
+ const len = source.length;
191
+ let i = pos;
192
+ while (i < len) {
193
+ i = skipWhitespace(source, i);
194
+ if (i >= len) break;
195
+ const term = matchTerminator(source, i);
196
+ if (term) return { attrs, pos: i, terminated: true, selfClosing: term.selfClosing };
197
+ const pair = readAttrPair(source, i);
198
+ if (!pair) {
199
+ i++;
200
+ continue;
201
+ }
202
+ i = pair.next;
203
+ if (!pair.hasValue) continue;
204
+ attrs[formatStr(pair.key)] = formatStr(pair.value);
205
+ if (pair.truncated) return { attrs, pos: len, terminated: false, selfClosing: false };
563
206
  }
207
+ return { attrs, pos: len, terminated: false, selfClosing: false };
564
208
  }
565
209
 
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);
210
+ // src/parser/sxin-ast-collect.ts
211
+ var INJECTED_TAGS = /* @__PURE__ */ new Set([
212
+ "think",
213
+ "current_user",
214
+ "request_context",
215
+ "system-reminder",
216
+ "memory",
217
+ "current_date",
218
+ "requested_capabilities",
219
+ "user_selections",
220
+ "current_uploads",
221
+ "uploaded_files",
222
+ "attachments",
223
+ "slash_skill_activation"
224
+ ]);
225
+ function collectVisibleText(source, nodes) {
226
+ const parts = [];
227
+ const walk = (list) => {
228
+ for (const node of list) {
229
+ if (node.type === "text") {
230
+ parts.push(node.value);
231
+ } else if (node.type === "comment") {
232
+ parts.push(`<!--${node.content}-->`);
233
+ } else if (!node.closed && !INJECTED_TAGS.has(node.tagName)) {
234
+ parts.push(source.slice(node.start, node.end));
590
235
  }
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
236
  }
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
- // 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
- function isAiMessage(msg) {
671
- const t = String(asSxin(msg).type || "");
672
- return ["ai", "AIMessage", "AIMessageChunk"].includes(t);
673
- }
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
- function normalizeUsage(raw) {
714
- if (!raw || typeof raw !== "object") return void 0;
715
- const r = raw;
716
- const inputTokens = readAliasedNumber(r, ["input_tokens", "inputTokens", "prompt_tokens", "promptTokens"]);
717
- const outputTokens = readAliasedNumber(r, ["output_tokens", "outputTokens", "completion_tokens", "completionTokens"]);
718
- const totalTokens = readAliasedNumber(r, ["total_tokens", "totalTokens"]);
719
- if ([inputTokens, outputTokens, totalTokens].every(Number.isNaN)) {
720
- return void 0;
721
- }
722
- const usage = {
723
- input_tokens: toZeroIfNaN(inputTokens),
724
- output_tokens: toZeroIfNaN(outputTokens),
725
- total_tokens: toZeroIfNaN(totalTokens)
726
- };
727
- applyUsageDetails(usage, r);
728
- return usage;
729
- }
730
- function readAliasedNumber(r, aliases) {
731
- for (const key of aliases) {
732
- if (r[key] !== void 0 && r[key] !== null) return Number(r[key]);
733
- }
734
- return NaN;
735
- }
736
- function toZeroIfNaN(n) {
737
- return Number.isNaN(n) ? 0 : n;
738
- }
739
- function applyUsageDetails(usage, r) {
740
- const cacheRead = Number(r.input_token_details?.cache_read ?? r.input_token_details?.cacheRead);
741
- if (!Number.isNaN(cacheRead)) {
742
- usage.input_token_details = { cache_read: cacheRead };
743
- }
744
- const reasoning = Number(r.output_token_details?.reasoning ?? r.output_token_details?.reasoningTokens);
745
- if (!Number.isNaN(reasoning)) {
746
- usage.output_token_details = { reasoning };
747
- }
748
- }
749
-
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
774
- function buildRunInfo(run, threadId) {
775
- return {
776
- runId: String(run?.run_id || "").trim(),
777
- threadId: String(threadId || "").trim(),
778
- usage: buildRunUsage(run),
779
- latencyMs: buildRunLatencyMs(run),
780
- finishReason: toOptionalString(run?.finish_reason),
781
- modelName: toOptionalString(run?.model_name),
782
- status: buildRunStatus(run),
783
- createdAt: buildRunCreatedAt(run)
784
- };
785
- }
786
- function toOptionalString(value) {
787
- return value ? String(value) : void 0;
788
- }
789
- function buildRunUsage(run) {
790
- return normalizeUsage({
791
- input_tokens: run?.total_input_tokens,
792
- output_tokens: run?.total_output_tokens,
793
- total_tokens: run?.total_tokens
794
- });
795
- }
796
- function buildRunStatus(run) {
797
- return run?.status ? String(run.status) : void 0;
798
- }
799
- function buildRunCreatedAt(run) {
800
- return run?.created_at ? Number(new Date(run.created_at)) : void 0;
801
- }
802
- function buildRunDirectLatencyMs(run) {
803
- const direct = Number(run?.latency_ms);
804
- return direct || void 0;
805
- }
806
- function buildRunLatencyMs(run) {
807
- const direct = buildRunDirectLatencyMs(run);
808
- if (direct !== void 0) return direct;
809
- const created = Date.parse(String(run?.created_at ?? ""));
810
- const updated = Date.parse(String(run?.updated_at ?? ""));
811
- if (Number.isNaN(created) || Number.isNaN(updated)) return void 0;
812
- const diff = updated - created;
813
- return diff >= 0 ? diff : void 0;
814
- }
815
- function pickRunMessageMetadata(messages) {
816
- let modelName;
817
- let finishReason;
818
- for (const msg of messages) {
819
- if (!isAiMessage(msg)) {
820
- continue;
821
- }
822
- const responseMetadata = msg?.response_metadata || {};
823
- if (!modelName && responseMetadata.model_name) {
824
- modelName = String(responseMetadata.model_name);
825
- }
826
- if (!finishReason && responseMetadata.finish_reason) {
827
- finishReason = String(responseMetadata.finish_reason);
828
- }
829
- if (modelName && finishReason) {
830
- break;
831
- }
832
- }
833
- return { modelName, finishReason };
834
- }
835
-
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
- };
968
- }
969
- function hasCitationInfo(v) {
970
- if (!v) return false;
971
- if (Array.isArray(v)) return v.length > 0;
972
- if (typeof v === "object") return Object.keys(v).length > 0;
973
- return Boolean(v);
974
- }
975
- function readContentText(content) {
976
- if (typeof content === "string") return content;
977
- if (Array.isArray(content)) {
978
- return content.map((c) => c?.type === "text" ? String(c.text || "") : "").join("");
979
- }
980
- return "";
981
- }
982
- function isCitationCarrier(msg) {
983
- const m = asSxin(msg);
984
- if (!isAiMessage(msg)) return false;
985
- if (readContentText(m.content).includes("<sxin-kb-citation")) return true;
986
- return hasCitationInfo(m.additional_kwargs?.citation_info);
987
- }
988
- function createEnrichments() {
989
- const citationPatches = (0, import_vue3.shallowReactive)(/* @__PURE__ */ new Map());
990
- const answers = (0, import_vue3.shallowReactive)(/* @__PURE__ */ new Map());
991
- let citationVersion = 0;
992
- return {
993
- get citationVersion() {
994
- return citationVersion;
995
- },
996
- applyFromStateMessages(messages) {
997
- for (const msg of messages) {
998
- const m = asSxin(msg);
999
- const id = String(m.id || "").trim();
1000
- if (!id || !isCitationCarrier(msg)) continue;
1001
- citationPatches.set(id, {
1002
- content: m.content,
1003
- citationInfo: m.additional_kwargs?.citation_info
1004
- });
1005
- citationVersion++;
1006
- }
1007
- const extracted = extractThreadInfo(messages).clarificationAnswers;
1008
- for (const [key, value] of extracted) answers.set(key, value);
1009
- },
1010
- resolveCitation(messageId) {
1011
- return citationPatches.get(messageId);
1012
- },
1013
- answers,
1014
- setAnswer(requestId, answer) {
1015
- answers.set(requestId, answer);
1016
- },
1017
- clearAnswers() {
1018
- answers.clear();
1019
- },
1020
- dispose() {
1021
- citationPatches.clear();
1022
- answers.clear();
1023
- }
1024
- };
1025
- }
1026
- function createInterruptState() {
1027
- const respondedIds = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Set());
1028
- return {
1029
- respondedIds,
1030
- markResponded(id) {
1031
- const next = new Set(respondedIds.value);
1032
- next.add(id);
1033
- respondedIds.value = next;
1034
- },
1035
- unmarkResponded(id) {
1036
- if (!respondedIds.value.has(id)) return;
1037
- const next = new Set(respondedIds.value);
1038
- next.delete(id);
1039
- respondedIds.value = next;
1040
- }
1041
- };
1042
- }
1043
- function createRunsStore(options) {
1044
- const runsMap = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Map());
1045
- const currentRunId = (0, import_vue3.shallowRef)(null);
1046
- return {
1047
- runsMap,
1048
- currentRunId,
1049
- fillFromRunsList(runsList) {
1050
- let next = null;
1051
- for (const run of runsList) {
1052
- const runId = String(run?.run_id || "").trim();
1053
- if (!runId) continue;
1054
- next ?? (next = new Map(runsMap.value));
1055
- next.set(runId, buildRunInfo(run, options.threadId));
1056
- }
1057
- if (next) runsMap.value = next;
1058
- },
1059
- ensureRunning(runId) {
1060
- if (runsMap.value.has(runId)) return;
1061
- const next = new Map(runsMap.value);
1062
- ensureRunningRun(next, runId, options.threadId);
1063
- runsMap.value = next;
1064
- },
1065
- async refreshRuns() {
1066
- try {
1067
- const runsList = await options.transport.listRuns(options.threadId, 20);
1068
- if (!Array.isArray(runsList)) return;
1069
- const merged = new Map(runsMap.value);
1070
- for (const run of runsList) {
1071
- const runId = String(run.run_id || "").trim();
1072
- if (!runId) continue;
1073
- const info = buildRunInfo(run, options.threadId);
1074
- const prev = merged.get(runId);
1075
- if (!prev) {
1076
- merged.set(runId, info);
1077
- continue;
1078
- }
1079
- const directLatency = buildRunDirectLatencyMs(run);
1080
- merged.set(runId, {
1081
- ...info,
1082
- feedback: info.feedback ?? prev.feedback,
1083
- latencyMs: directLatency ?? prev.latencyMs ?? info.latencyMs,
1084
- modelName: info.modelName ?? prev.modelName,
1085
- finishReason: info.finishReason ?? prev.finishReason
1086
- });
1087
- }
1088
- runsMap.value = merged;
1089
- } catch (e) {
1090
- console.warn("[runs-store] refreshRuns failed", e);
1091
- }
1092
- },
1093
- enrichFromPage(page) {
1094
- const enrichment = extractRunEnrichment(page.messages);
1095
- let next = null;
1096
- for (const [runId, patch] of enrichment) {
1097
- const run = (next ?? runsMap.value).get(runId);
1098
- if (!run) continue;
1099
- next ?? (next = new Map(runsMap.value));
1100
- next.set(runId, {
1101
- ...run,
1102
- ...patch.feedback !== void 0 ? { feedback: patch.feedback } : {},
1103
- ...patch.latencyMs !== void 0 ? { latencyMs: patch.latencyMs } : {}
1104
- });
1105
- }
1106
- if (next) runsMap.value = next;
1107
- },
1108
- backfillCurrentRunMetadata(getMessages) {
1109
- const runId = currentRunId.value;
1110
- if (!runId) return;
1111
- const run = runsMap.value.get(runId);
1112
- if (!run) return;
1113
- if (run.modelName && run.finishReason) return;
1114
- const currentRunMessages = getMessages().filter((m) => String(m?.runId || "") === runId);
1115
- const source = currentRunMessages.length ? currentRunMessages : getMessages();
1116
- const picked = pickRunMessageMetadata(source);
1117
- if (!picked.modelName && !picked.finishReason) return;
1118
- runsMap.value = new Map(runsMap.value).set(runId, {
1119
- ...run,
1120
- ...picked.modelName && !run.modelName ? { modelName: picked.modelName } : {},
1121
- ...picked.finishReason && !run.finishReason ? { finishReason: picked.finishReason } : {}
1122
- });
1123
- },
1124
- patchRun(runId, patch) {
1125
- const run = runsMap.value.get(runId);
1126
- if (!run) return;
1127
- runsMap.value = new Map(runsMap.value).set(runId, { ...run, ...patch });
1128
- },
1129
- dispose() {
1130
- runsMap.value = /* @__PURE__ */ new Map();
1131
- currentRunId.value = null;
1132
- }
1133
- };
1134
- }
1135
-
1136
- // src/parser/message-id.ts
1137
- var _idSeq = 0;
1138
- function genMessageId() {
1139
- return `msg-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
1140
- }
1141
- function genBlockId() {
1142
- return `block-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
1143
- }
1144
-
1145
- // src/parser/sxin-ast-attrs.ts
1146
- function formatStr(str) {
1147
- if (!str) return str;
1148
- return str.replace(/["`\s]/g, "");
1149
- }
1150
- function skipWhitespace(source, i) {
1151
- const len = source.length;
1152
- while (i < len && /\s/.test(source[i])) i++;
1153
- return i;
1154
- }
1155
- function readQuotedValue(source, j, key) {
1156
- const quote = source[j];
1157
- const close = source.indexOf(quote, j + 1);
1158
- if (close === -1) {
1159
- return { key, value: source.slice(j + 1), next: source.length, hasValue: true, truncated: true };
1160
- }
1161
- return { key, value: source.slice(j + 1, close), next: close + 1, hasValue: true, truncated: false };
1162
- }
1163
- function readBareValue(source, j, key) {
1164
- const valMatch = /^[^\s>]+/.exec(source.slice(j));
1165
- const raw = valMatch ? valMatch[0] : "";
1166
- const value = raw.endsWith("/") ? raw.slice(0, -1) : raw;
1167
- return { key, value, next: j + raw.length, hasValue: true, truncated: false };
1168
- }
1169
- function readAttrPair(source, i) {
1170
- const keyMatch = /^[\w-]+/.exec(source.slice(i));
1171
- if (!keyMatch) return null;
1172
- const key = keyMatch[0];
1173
- let j = skipWhitespace(source, i + key.length);
1174
- if (source[j] !== "=") return { key, value: "", next: j, hasValue: false, truncated: false };
1175
- j = skipWhitespace(source, j + 1);
1176
- if (j >= source.length) {
1177
- return { key, value: "", next: source.length, hasValue: true, truncated: true };
1178
- }
1179
- const quote = source[j];
1180
- return quote === '"' || quote === "'" ? readQuotedValue(source, j, key) : readBareValue(source, j, key);
1181
- }
1182
- function matchTerminator(source, i) {
1183
- if (source[i] === ">") return { selfClosing: false };
1184
- if (source[i] === "/" && source[i + 1] === ">") return { selfClosing: true };
1185
- return null;
1186
- }
1187
- function parseAttrs(source, pos) {
1188
- const attrs = {};
1189
- const len = source.length;
1190
- let i = pos;
1191
- while (i < len) {
1192
- i = skipWhitespace(source, i);
1193
- if (i >= len) break;
1194
- const term = matchTerminator(source, i);
1195
- if (term) return { attrs, pos: i, terminated: true, selfClosing: term.selfClosing };
1196
- const pair = readAttrPair(source, i);
1197
- if (!pair) {
1198
- i++;
1199
- continue;
1200
- }
1201
- i = pair.next;
1202
- if (!pair.hasValue) continue;
1203
- attrs[formatStr(pair.key)] = formatStr(pair.value);
1204
- if (pair.truncated) return { attrs, pos: len, terminated: false, selfClosing: false };
1205
- }
1206
- return { attrs, pos: len, terminated: false, selfClosing: false };
1207
- }
1208
-
1209
- // src/parser/sxin-ast-collect.ts
1210
- var INJECTED_TAGS = /* @__PURE__ */ new Set([
1211
- "think",
1212
- "current_user",
1213
- "request_context",
1214
- "system-reminder",
1215
- "memory",
1216
- "current_date",
1217
- "requested_capabilities",
1218
- "user_selections",
1219
- "current_uploads",
1220
- "uploaded_files",
1221
- "attachments",
1222
- "slash_skill_activation"
1223
- ]);
1224
- function isInjectedElement(node) {
1225
- return INJECTED_TAGS.has(node.tagName);
1226
- }
1227
- function collectVisibleText(source, nodes) {
1228
- const parts = [];
1229
- const walk = (list) => {
1230
- for (const node of list) {
1231
- if (node.type === "text") {
1232
- parts.push(node.value);
1233
- } else if (node.type === "comment") {
1234
- parts.push(`<!--${node.content}-->`);
1235
- } else if (!node.closed && !INJECTED_TAGS.has(node.tagName)) {
1236
- parts.push(source.slice(node.start, node.end));
1237
- }
1238
- }
1239
- };
1240
- walk(nodes);
1241
- return parts.join("");
1242
- }
1243
- function collectTextKeepSxin(source, nodes) {
1244
- const parts = [];
1245
- const walk = (list) => {
1246
- for (const node of list) {
1247
- if (node.type === "text") {
1248
- parts.push(node.value);
1249
- } else if (node.type === "comment") {
1250
- parts.push(`<!--${node.content}-->`);
1251
- } else if (!isInjectedElement(node)) {
1252
- parts.push(source.slice(node.start, node.end));
1253
- }
1254
- }
1255
- };
1256
- walk(nodes);
1257
- return parts.join("");
237
+ };
238
+ walk(nodes);
239
+ return parts.join("");
1258
240
  }
1259
241
 
1260
242
  // src/parser/sxin-ast.ts
@@ -1477,66 +459,320 @@ function readMessageContentText(msg) {
1477
459
  if (!read) return "";
1478
460
  return read.trim ? read.text.trim() : read.text;
1479
461
  }
462
+ function hasKbCitationMessage(msg) {
463
+ return readMessageContentText(msg).includes("support.kbCitation");
464
+ }
1480
465
  function extractTextFromMessage(msg) {
1481
466
  const read = readMessageText(msg);
1482
467
  if (!read) return "";
1483
468
  const text = collectVisibleText(read.text, tokenizeSxin(read.text));
1484
469
  return read.trim ? text.trim() : text;
1485
470
  }
1486
- function extractAiContentFromMessage(msg) {
1487
- const read = readMessageText(msg);
1488
- if (!read) return "";
1489
- const text = collectTextKeepSxin(read.text, tokenizeSxin(read.text));
1490
- return read.trim ? text.trim() : text;
471
+
472
+ // src/runtime/semantic-overlay.ts
473
+ var extractKwargsPatch = (msg) => {
474
+ const kwargs = msg?.additional_kwargs;
475
+ if (!kwargs || typeof kwargs !== "object") return void 0;
476
+ const patch = {};
477
+ if (kwargs.hide_from_ui === true) patch.hide_from_ui = true;
478
+ if (kwargs.human_input_response && typeof kwargs.human_input_response === "object") {
479
+ patch.human_input_response = kwargs.human_input_response;
480
+ }
481
+ return Object.keys(patch).length ? patch : void 0;
482
+ };
483
+ function extractSemanticPatchesFromMessages(messages) {
484
+ const next = /* @__PURE__ */ new Map();
485
+ for (const m of messages ?? []) {
486
+ const id = String(m?.id || "").trim();
487
+ if (!id) continue;
488
+ const patch = { id };
489
+ if (String(m?.type || "") === "ai" && hasKbCitationMessage(m)) {
490
+ patch.content = m.content;
491
+ }
492
+ if (String(m?.type || "") === "human") {
493
+ const kwargs = extractKwargsPatch(m);
494
+ if (kwargs) patch.additional_kwargs = kwargs;
495
+ }
496
+ if (patch.content !== void 0 || patch.additional_kwargs) next.set(id, patch);
497
+ }
498
+ return next;
1491
499
  }
1492
- function isVisibleUserMessage(msg) {
1493
- if (!msg || typeof msg !== "object") return false;
1494
- if (String(msg.type || "") !== "human") return false;
1495
- return msg.additional_kwargs?.hide_from_ui !== true;
500
+ function createSemanticOverlay() {
501
+ let patches = /* @__PURE__ */ new Map();
502
+ return {
503
+ applyState(state) {
504
+ const messages = extractStateMessages(state);
505
+ patches = extractSemanticPatchesFromMessages(messages);
506
+ const citedIds = messages.filter((m) => String(m?.type || "") === "ai" && hasKbCitationMessage(m)).map((m) => String(m?.id || "")).filter(Boolean);
507
+ return { patched: patches.size, citedIds };
508
+ },
509
+ getPatches() {
510
+ return new Map(patches);
511
+ },
512
+ invalidate() {
513
+ patches = /* @__PURE__ */ new Map();
514
+ }
515
+ };
1496
516
  }
1497
- function extractUserMessageTexts(rawMessages) {
1498
- if (!Array.isArray(rawMessages)) return [];
1499
- return rawMessages.filter((m) => isVisibleUserMessage(m)).map((m) => extractTextFromMessage(m).trim()).filter(Boolean).slice(0, 1);
517
+ function applySemanticPatches(messages, patches) {
518
+ if (!patches.size || !messages.length) return messages;
519
+ return messages.map((m) => {
520
+ const id = String(m?.id || "").trim();
521
+ const patch = id ? patches.get(id) : void 0;
522
+ if (!patch) return m;
523
+ let next = m;
524
+ if (patch.content !== void 0 && String(next?.type || "") === "ai" && !hasKbCitationMessage(next)) {
525
+ next = { ...next, content: patch.content };
526
+ }
527
+ const localKwargs = next?.additional_kwargs;
528
+ if (patch.additional_kwargs && Object.keys(patch.additional_kwargs).length) {
529
+ const merged = { ...localKwargs };
530
+ let changed = false;
531
+ for (const [k, v] of Object.entries(patch.additional_kwargs)) {
532
+ if (merged[k] === void 0) {
533
+ merged[k] = v;
534
+ changed = true;
535
+ }
536
+ }
537
+ if (changed) next = { ...next, additional_kwargs: merged };
538
+ }
539
+ return next;
540
+ });
1500
541
  }
1501
542
 
1502
- // src/domain/fold.ts
1503
- function messageRunId(msg) {
1504
- const own = String(asSxin(msg).runId || "").trim();
1505
- if (own) return own;
1506
- return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
543
+ // src/runtime/runtime-bootstrap.ts
544
+ async function bootstrapRuntime(deps) {
545
+ const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
546
+ deps.valuesChannel.applyInitialValues(fetched.values);
547
+ deps.valuesChannel.applyThreadState(fetched.threadState);
548
+ const semantic = deps.overlay.applyState(fetched.threadState);
549
+ if (semantic.patched) {
550
+ console.debug(`[runtime] \u8BED\u4E49\u5C42\u52A0\u8F7D patched=${semantic.patched} cited=${semantic.citedIds.length}`);
551
+ }
552
+ deps.runs.fillFromRunsList(fetched.runsList ?? []);
553
+ deps.runs.enrichFromPage(fetched.messagesPage);
554
+ const pageMessages = runMessagesToMessages(fetched.messagesPage.messages);
555
+ const seeded = applySemanticPatches(pageMessages, deps.overlay.getPatches());
556
+ if (seeded.length) deps.rm.hydrate(seeded);
557
+ deps.rm.applySemanticPatch(deps.overlay.getPatches());
558
+ deps.setPager(
559
+ createHistoryPager({
560
+ threadId: deps.threadId,
561
+ transport: deps.transport,
562
+ firstPage: fetched.messagesPage,
563
+ onPageLoaded: (page) => {
564
+ deps.runs.enrichFromPage(page);
565
+ deps.rm.prependHistory(runMessagesToMessages(page.messages));
566
+ },
567
+ emitChanges: () => {
568
+ }
569
+ })
570
+ );
571
+ await deps.refreshTokenUsage();
572
+ const finalize = () => finalizeAfterStream(deps);
573
+ const afterFinish = () => afterStreamFinish(deps);
574
+ deps.streamRef.value = deps.transport.createStream({
575
+ assistantId: deps.assistantId,
576
+ threadId: deps.threadId,
577
+ onCreated: (run) => deps.markStreamRun(run?.run_id),
578
+ onMetadataEvent: (data) => deps.markStreamRun(data?.run_id),
579
+ onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
580
+ onMessageTupleEvent: () => {
581
+ },
582
+ onSnapshotMessages: (messages) => deps.rm.applySnapshot(messages),
583
+ onStreamStart: deps.onStreamStart,
584
+ onStreamEnd: finalize,
585
+ onFinish: afterFinish,
586
+ onError: (err) => console.error("[runtime] stream error", err)
587
+ });
588
+ deps.setInitialized();
589
+ }
590
+ function finalizeAfterStream(deps) {
591
+ deps.rm.finalize();
592
+ deps.onStreamSettled();
593
+ deps.runs.backfillCurrentRunMetadata(() => [...deps.rm.lastMessages()]);
594
+ deps.rm.applySemanticPatch(extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages()));
595
+ }
596
+ async function afterStreamFinish(deps) {
597
+ await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
598
+ await reconcileWithPage(deps);
599
+ await refreshSemanticLayer(deps);
600
+ }
601
+ async function refreshSemanticLayer(deps) {
602
+ try {
603
+ const state = await deps.transport.fetchThreadState(deps.threadId);
604
+ if (!state) return;
605
+ const semantic = deps.overlay.applyState(state);
606
+ deps.rm.applySemanticPatch(deps.overlay.getPatches());
607
+ if (semantic.patched) {
608
+ console.debug(`[runtime] \u8BED\u4E49\u5C42\u5237\u65B0 patched=${semantic.patched} cited=${semantic.citedIds.length}`);
609
+ }
610
+ } catch (e) {
611
+ console.warn("[runtime] \u8BED\u4E49\u5C42\u5237\u65B0\u5931\u8D25", e);
612
+ }
613
+ }
614
+ async function reconcileWithPage(deps) {
615
+ try {
616
+ const page = await deps.transport.fetchMessagesPage(deps.threadId);
617
+ const messages = runMessagesToMessages(page.messages);
618
+ if (messages.length) deps.rm.reconcileWithPage(messages);
619
+ } catch (e) {
620
+ console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
621
+ }
622
+ }
623
+ async function runRuntimeInit(deps, hooks) {
624
+ hooks.onStart();
625
+ try {
626
+ await bootstrapRuntime(deps);
627
+ } finally {
628
+ hooks.onEnd();
629
+ }
630
+ }
631
+
632
+ // src/runtime/runtime-stream-actions.ts
633
+ function createStreamActions(ctx) {
634
+ return {
635
+ submit(text, submitOptions) {
636
+ const handle = ctx.getHandle();
637
+ if (!handle) return;
638
+ ctx.beginStream();
639
+ const humanMessage = { type: "human", content: [{ type: "text", text }] };
640
+ humanMessage.additional_kwargs = submitOptions?.kwargs;
641
+ handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
642
+ },
643
+ async joinStream(runId, lastEventId) {
644
+ const handle = ctx.getHandle();
645
+ if (!handle) return;
646
+ ctx.beginStream();
647
+ ctx.markStreamRun(runId);
648
+ await handle.joinStream(runId, lastEventId ?? "-1");
649
+ },
650
+ stop() {
651
+ void ctx.options.transport.cancelRun(ctx.options.threadId, ctx.runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
652
+ ctx.getHandle()?.stop();
653
+ },
654
+ async resumeInterrupt(decisions) {
655
+ const it = ctx.getInterrupt();
656
+ const interruptId = String(it?.id || "");
657
+ if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
658
+ const handle = ctx.getHandle();
659
+ if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
660
+ ctx.markResponded(interruptId);
661
+ ctx.beginStream();
662
+ await handle.resumeInterrupt(decisions);
663
+ },
664
+ async loadOlderMessages() {
665
+ if (!ctx.getPager()) return false;
666
+ return ctx.getPager().loadOlder();
667
+ }
668
+ };
669
+ }
670
+
671
+ // src/runtime/runtime-materializer.ts
672
+ var import_vue3 = require("vue");
673
+
674
+ // src/materializer/materializer.ts
675
+ var import_vue2 = require("vue");
676
+
677
+ // src/materializer/indexes.ts
678
+ function createIndexes() {
679
+ return { byMessageId: /* @__PURE__ */ new Map(), byToolCallId: /* @__PURE__ */ new Map(), byRunId: /* @__PURE__ */ new Map() };
680
+ }
681
+ function rebuildIndexes(turns) {
682
+ const idx = createIndexes();
683
+ turns.forEach((turn, ti) => {
684
+ idx.byMessageId.set(turn.id, { turn: ti, ai: null });
685
+ idx.byRunId.set(turn.runId, { turn: ti, ai: 0 });
686
+ turn.ai.forEach((seg, ai_i) => {
687
+ idx.byMessageId.set(seg.id, { turn: ti, ai: ai_i });
688
+ for (const mid of seg.messageIds ?? []) {
689
+ if (mid) idx.byMessageId.set(mid, { turn: ti, ai: ai_i });
690
+ }
691
+ idx.byRunId.set(seg.runId, { turn: ti, ai: ai_i });
692
+ seg.tools.forEach((tool, tool_i) => {
693
+ idx.byToolCallId.set(tool.callId, { turn: ti, ai: ai_i, tool: tool_i });
694
+ });
695
+ });
696
+ });
697
+ return idx;
698
+ }
699
+
700
+ // src/parser/group-builder-helper.ts
701
+ function isHumanMessage(msg) {
702
+ return String(asSxin(msg).type || "") === "human";
703
+ }
704
+ function parseHumanMessageId(id) {
705
+ const raw = String(id || "");
706
+ const match = raw.match(/^(.*?)__(memory|user)(\([^)]*\))?$/i);
707
+ if (!match) return { baseId: raw, variant: null };
708
+ return { baseId: match[1], variant: match[2].toLowerCase() };
709
+ }
710
+ function getHumanMessageBaseId(id) {
711
+ return parseHumanMessageId(id).baseId;
712
+ }
713
+ function isAiMessage(msg) {
714
+ const t = String(asSxin(msg).type || "");
715
+ return ["ai", "AIMessage", "AIMessageChunk"].includes(t);
716
+ }
717
+ function isToolMessage(msg) {
718
+ return String(asSxin(msg).type || "") === "tool";
1507
719
  }
1508
- function foldMessages(target, flush) {
1509
- let type = null;
1510
- let buf = [];
1511
- let groupRunId;
1512
- const doFlush = () => {
1513
- if (!buf.length || !type) return;
1514
- flush(type, buf);
1515
- buf = [];
720
+ function normalizeUsage(raw) {
721
+ if (!raw || typeof raw !== "object") return void 0;
722
+ const r = raw;
723
+ const inputTokens = readAliasedNumber(r, ["input_tokens", "inputTokens", "prompt_tokens", "promptTokens"]);
724
+ const outputTokens = readAliasedNumber(r, ["output_tokens", "outputTokens", "completion_tokens", "completionTokens"]);
725
+ const totalTokens = readAliasedNumber(r, ["total_tokens", "totalTokens"]);
726
+ if ([inputTokens, outputTokens, totalTokens].every(Number.isNaN)) {
727
+ return void 0;
728
+ }
729
+ const usage = {
730
+ input_tokens: toZeroIfNaN(inputTokens),
731
+ output_tokens: toZeroIfNaN(outputTokens),
732
+ total_tokens: toZeroIfNaN(totalTokens)
1516
733
  };
1517
- for (const m of target) {
1518
- if (isHumanMessage(m)) {
1519
- if (!(type === "human" && buf.length && getHumanMessageBaseId(String(asSxin(m).id || "")) === getHumanMessageBaseId(String(asSxin(buf[0]).id || ""))))
1520
- doFlush();
1521
- type = "human";
1522
- buf.push(m);
1523
- } else if (isAiMessage(m) || isToolMessage(m)) {
1524
- const mRunId = messageRunId(m);
1525
- if (type !== "ai" || mRunId && groupRunId && mRunId !== groupRunId) doFlush();
1526
- if (!buf.length) groupRunId = mRunId;
1527
- type = "ai";
1528
- buf.push(m);
734
+ applyUsageDetails(usage, r);
735
+ return usage;
736
+ }
737
+ function readAliasedNumber(r, aliases) {
738
+ for (const key of aliases) {
739
+ if (r[key] !== void 0 && r[key] !== null) return Number(r[key]);
740
+ }
741
+ return NaN;
742
+ }
743
+ function toZeroIfNaN(n) {
744
+ return Number.isNaN(n) ? 0 : n;
745
+ }
746
+ function applyUsageDetails(usage, r) {
747
+ const cacheRead = Number(r.input_token_details?.cache_read ?? r.input_token_details?.cacheRead);
748
+ if (!Number.isNaN(cacheRead)) {
749
+ usage.input_token_details = { cache_read: cacheRead };
750
+ }
751
+ const reasoning = Number(r.output_token_details?.reasoning ?? r.output_token_details?.reasoningTokens);
752
+ if (!Number.isNaN(reasoning)) {
753
+ usage.output_token_details = { reasoning };
754
+ }
755
+ }
756
+
757
+ // src/parser/thread-info.ts
758
+ function formatAnswerText(value) {
759
+ if (value == null) return "";
760
+ if (typeof value === "string") return value;
761
+ if (typeof value === "object") {
762
+ const values = value.values;
763
+ if (values && typeof values === "object" && !Array.isArray(values)) {
764
+ return Object.values(values).filter((v) => v !== void 0 && v !== null && v !== "").map(String).join("; ");
765
+ }
766
+ try {
767
+ return JSON.stringify(value);
768
+ } catch {
769
+ return String(value);
1529
770
  }
1530
771
  }
1531
- doFlush();
772
+ return String(value);
1532
773
  }
1533
774
 
1534
775
  // src/parser/report-artifact.ts
1535
- var genId = () => typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `id-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
1536
- function isWriteFileToolName(name) {
1537
- const n = String(name || "").trim().toLowerCase();
1538
- return n === "write_file" || n === "write_files";
1539
- }
1540
776
  function getToolCallArtifactMeta(toolCall) {
1541
777
  const meta = toolCall?.artifact_meta;
1542
778
  if (!meta || typeof meta !== "object") return null;
@@ -1565,1049 +801,1095 @@ function extractKindSignals(toolCall) {
1565
801
  function resolveReportArtifactKind(toolCall) {
1566
802
  const { artifactPath, metaKind, description } = extractKindSignals(toolCall);
1567
803
  if (pathSuggestsBody(artifactPath) || descriptionSuggestsBody(description)) return "report_body";
1568
- if (pathSuggestsOutline(artifactPath) || descriptionSuggestsOutline(description)) return "report_outline";
1569
- if (metaKind === "report_body" || metaKind === "report_outline") return metaKind;
1570
- return null;
1571
- }
1572
- function extractTitleFromArtifactPath(path, kind = "report_outline") {
1573
- const raw = String(path || "").trim();
1574
- if (!raw) return "\u62A5\u544A";
1575
- const base = raw.split("/").pop() || raw;
1576
- const noExt = base.replace(/\.(md|markdown|html?)$/i, "");
1577
- if (kind === "report_body") {
1578
- return noExt.replace(/_正文$/i, "").replace(/_报告$/i, "").replace(/\s*正文\s*$/i, "").trim() || "\u62A5\u544A";
1579
- }
1580
- return noExt.replace(/_大纲$/i, "").replace(/\s*大纲\s*$/i, "").trim() || "\u62A5\u544A";
1581
- }
1582
- var OUTLINE_MAX_LEVEL = 3;
1583
- function normalizeSubChapter(raw, level) {
1584
- const legacyChildren = raw.children ?? raw.points ?? [];
1585
- const title = String(raw.title ?? raw.pointTitle ?? "");
1586
- const children = level >= OUTLINE_MAX_LEVEL ? [] : legacyChildren.map((c) => normalizeSubChapter(c, level + 1));
1587
- return {
1588
- id: String(raw.id ?? genId()),
1589
- title,
1590
- summary: String(raw.summary ?? raw.pointSummary ?? ""),
1591
- contentTheme: String(raw.contentTheme ?? raw.pointDesc ?? ""),
1592
- children
1593
- };
1594
- }
1595
- function normalizeOutline(raw) {
1596
- if (!Array.isArray(raw)) return [];
1597
- const outline = raw.map((item) => {
1598
- const ch = item;
1599
- const legacyChildren = ch.children ?? ch.points ?? [];
1600
- return {
1601
- id: String(ch.id ?? genId()),
1602
- chapterTitle: String(ch.chapterTitle ?? ""),
1603
- chapterSummary: String(ch.chapterSummary ?? ch.chapterDesc ?? ""),
1604
- children: legacyChildren.map((c) => normalizeSubChapter(c, 2))
1605
- };
1606
- });
1607
- return ensureOutlineContentThemes(outline);
1608
- }
1609
- function ensureOutlineContentThemes(outline) {
1610
- const walk = (nodes) => {
1611
- nodes.forEach((node) => {
1612
- if (node.summary === void 0 || node.summary === null) {
1613
- node.summary = "";
1614
- }
1615
- if (node.contentTheme === void 0 || node.contentTheme === null) {
1616
- node.contentTheme = "";
1617
- }
1618
- if (node.children?.length) walk(node.children);
1619
- });
1620
- };
1621
- outline.forEach((ch) => {
1622
- if (ch.chapterSummary === void 0 || ch.chapterSummary === null) {
1623
- ch.chapterSummary = "";
1624
- }
1625
- walk(ch.children || []);
1626
- });
1627
- return outline;
1628
- }
1629
- function detectLevelOneIsChapter(lines) {
1630
- const levelOneCount = lines.filter((line) => /^#\s+.+$/.test(line.trim())).length;
1631
- return levelOneCount > 1;
1632
- }
1633
- function joinLines(existing, text) {
1634
- return existing ? `${existing}
1635
- ${text}` : text;
1636
- }
1637
- function appendBullet(state, text) {
1638
- const line = `- ${text}`;
1639
- const top = state.stack[state.stack.length - 1]?.node;
1640
- if (top) {
1641
- top.contentTheme = joinLines(top.contentTheme, line);
1642
- return;
1643
- }
1644
- if (!state.currentChapter) return;
1645
- state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, line);
1646
- }
1647
- function appendSummaryText(state, text) {
1648
- if (!text) return;
1649
- const top = state.stack[state.stack.length - 1]?.node;
1650
- if (top) {
1651
- top.summary = joinLines(top.summary, text);
1652
- return;
1653
- }
1654
- if (!state.currentChapter) return;
1655
- state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, text);
1656
- }
1657
- function appendPlainText(state, text) {
1658
- if (!text) return;
1659
- const top = state.stack[state.stack.length - 1]?.node;
1660
- if (top) {
1661
- top.contentTheme = joinLines(top.contentTheme, text);
1662
- return;
1663
- }
1664
- if (!state.currentChapter) return;
1665
- state.currentChapter.chapterSummary = joinLines(state.currentChapter.chapterSummary, text);
1666
- }
1667
- function resolveTemplateName(title) {
1668
- return title.replace(/\s*·\s*大纲\s*$/i, "").replace(/\s*大纲\s*$/i, "").trim() || title;
1669
- }
1670
- function pushChapter(state, title) {
1671
- state.currentChapter = { id: genId(), chapterTitle: title, chapterSummary: "", children: [] };
1672
- state.outline.push(state.currentChapter);
1673
- state.stack.length = 0;
1674
- }
1675
- function pushSubChapter(state, level, title) {
1676
- const subChapterLevel = state.levelOneIsChapter ? level : level - 1;
1677
- if (subChapterLevel < 2 || !state.currentChapter) return false;
1678
- const sub = { id: genId(), title, summary: "", contentTheme: "", children: [] };
1679
- while (state.stack.length && state.stack[state.stack.length - 1].level >= subChapterLevel) {
1680
- state.stack.pop();
1681
- }
1682
- const parent = state.stack[state.stack.length - 1]?.node;
1683
- if (parent) parent.children.push(sub);
1684
- else state.currentChapter.children.push(sub);
1685
- state.stack.push({ node: sub, level: subChapterLevel });
1686
- return true;
1687
- }
1688
- function handleQuote(state, trimmed) {
1689
- if (!trimmed.startsWith(">")) return false;
1690
- const quoteText = trimmed.replace(/^(>\s*)+/, "").trim();
1691
- const summaryText = quoteText.replace(/^摘要\s*[::]\s*/i, "").trim();
1692
- appendSummaryText(state, summaryText || quoteText);
1693
- return true;
1694
- }
1695
- function handleHeading(state, trimmed) {
1696
- const heading = trimmed.match(/^(#{1,6})\s+(.+)$/);
1697
- if (!heading) return false;
1698
- const level = heading[1].length;
1699
- const title = heading[2].trim();
1700
- if (level === 1 && !state.levelOneIsChapter) {
1701
- state.templateName = resolveTemplateName(title);
1702
- return true;
1703
- }
1704
- if (level === 1 && state.levelOneIsChapter || level === 2 && !state.levelOneIsChapter) {
1705
- pushChapter(state, title);
1706
- return true;
1707
- }
1708
- return pushSubChapter(state, level, title);
1709
- }
1710
- function parseMarkdownToOutline(markdown) {
1711
- const lines = String(markdown || "").split(/\r?\n/);
1712
- const state = {
1713
- templateName: "",
1714
- outline: [],
1715
- currentChapter: null,
1716
- stack: [],
1717
- levelOneIsChapter: detectLevelOneIsChapter(lines)
1718
- };
1719
- for (const line of lines) {
1720
- const trimmed = line.trim();
1721
- if (!trimmed || trimmed === "---" || /^```/.test(trimmed)) continue;
1722
- if (handleQuote(state, trimmed)) continue;
1723
- if (handleHeading(state, trimmed)) continue;
1724
- const bullet = trimmed.match(/^[-*]\s+(.+)$/);
1725
- if (bullet) {
1726
- appendBullet(state, bullet[1].trim());
1727
- continue;
1728
- }
1729
- appendPlainText(state, trimmed);
1730
- }
1731
- return {
1732
- templateName: state.templateName || "\u62A5\u544A",
1733
- outline: normalizeOutline(state.outline)
1734
- };
804
+ if (pathSuggestsOutline(artifactPath) || descriptionSuggestsOutline(description)) return "report_outline";
805
+ if (metaKind === "report_body" || metaKind === "report_outline") return metaKind;
806
+ return null;
1735
807
  }
1736
- var HTML_LIKE = /^\s*</;
1737
- function isReportBodyHtml(content) {
1738
- const s = String(content || "").trim();
1739
- if (!s) return false;
1740
- return HTML_LIKE.test(s);
1741
- }
1742
- function extractReportTitleFromBody(content, fallback = "") {
1743
- const s = String(content || "").trim();
1744
- if (!s) return fallback;
1745
- if (isReportBodyHtml(s)) {
1746
- const h1 = s.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);
1747
- if (h1?.[1]) {
1748
- const t = h1[1].replace(/<[^>]+>/g, "").trim();
1749
- if (t) return t;
1750
- }
808
+ function extractTitleFromArtifactPath(path, kind = "report_outline") {
809
+ const raw = String(path || "").trim();
810
+ if (!raw) return "\u62A5\u544A";
811
+ const base = raw.split("/").pop() || raw;
812
+ const noExt = base.replace(/\.(md|markdown|html?)$/i, "");
813
+ if (kind === "report_body") {
814
+ return noExt.replace(/_正文$/i, "").replace(/_报告$/i, "").replace(/\s*正文\s*$/i, "").trim() || "\u62A5\u544A";
1751
815
  }
1752
- const heading = s.match(/^#\s+(.+)$/m);
1753
- if (heading?.[1]) return heading[1].trim();
1754
- return fallback;
816
+ return noExt.replace(/_大纲$/i, "").replace(/\s*大纲\s*$/i, "").trim() || "\u62A5\u544A";
1755
817
  }
1756
818
 
1757
- // src/parser/citation.ts
1758
- function collectCitation(el, citations) {
1759
- const citationId = String(el.attrs["citation-id"] || "").trim();
1760
- const searchText = String(el.attrs["search-text"] || el.attrs["keyword"] || "").trim() || void 0;
1761
- if (!citationId) return;
1762
- const existing = citations.find((c) => c.refId === citationId);
1763
- if (!existing) {
1764
- const item = { refId: citationId, title: "" };
1765
- if (searchText) item.searchText = searchText;
1766
- citations.push(item);
1767
- } else if (searchText && !existing.searchText) {
1768
- existing.searchText = searchText;
819
+ // src/materializer/extractors.ts
820
+ function normalizeName(name) {
821
+ const n = String(name || "").trim().toLowerCase();
822
+ return n === "write_files" ? "write_file" : n;
823
+ }
824
+ function tryParseObject(result) {
825
+ const text = String(result ?? "").trim();
826
+ if (!text.startsWith("{")) return null;
827
+ try {
828
+ const parsed = JSON.parse(text);
829
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
830
+ return parsed;
831
+ } catch {
832
+ return null;
833
+ }
834
+ }
835
+ function extractFromToolResult(name, result, toolCallLike) {
836
+ const tool = normalizeName(name);
837
+ const obj = tryParseObject(result);
838
+ if (tool === "ask_clarification" && obj) {
839
+ const question = obj.question ?? obj.title;
840
+ if (typeof question !== "string" || !question.trim()) return void 0;
841
+ const options = Array.isArray(obj.options) ? obj.options : void 0;
842
+ return options ? { kind: "clarification", question, options } : { kind: "clarification", question };
843
+ }
844
+ if (tool === "write_file") {
845
+ if (obj) {
846
+ if (typeof obj.body === "string" && obj.body) {
847
+ const outline = typeof obj.outline === "string" ? obj.outline : void 0;
848
+ return outline ? { kind: "report", reportKind: "report_body", body: obj.body, outline } : { kind: "report", reportKind: "report_body", body: obj.body };
849
+ }
850
+ if (Array.isArray(obj.files) && obj.files.length) {
851
+ return { kind: "artifact", files: obj.files };
852
+ }
853
+ }
854
+ const reportKind = resolveReportArtifactKind(toolCallLike);
855
+ if (reportKind) {
856
+ const tc = toolCallLike ?? {};
857
+ const sourcePath = String(tc?.artifact_meta?.path || tc?.args?.path || "").trim() || void 0;
858
+ return {
859
+ kind: "report",
860
+ reportKind,
861
+ sourcePath,
862
+ title: sourcePath ? extractTitleFromArtifactPath(sourcePath, reportKind) : void 0
863
+ };
864
+ }
1769
865
  }
866
+ return void 0;
1770
867
  }
1771
868
 
1772
- // src/parser/block-build-helper.ts
1773
- function buildArtifactFiles(paths) {
1774
- return paths.map((path) => {
1775
- const name = path.split("/").pop() || path;
1776
- const fileType = name.split(".").pop() || void 0;
1777
- return { path, name, fileType };
1778
- });
869
+ // src/materializer/turn-machine-rules.ts
870
+ function messageRunId(msg) {
871
+ const own = String(asSxin(msg).runId || "").trim();
872
+ if (own) return own;
873
+ return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
1779
874
  }
1780
- function toCreatedAtIso(createdAt) {
1781
- const ms = Number(createdAt);
1782
- if (!Number.isFinite(ms)) return (/* @__PURE__ */ new Date()).toISOString();
1783
- const date = new Date(ms);
1784
- return Number.isNaN(date.getTime()) ? (/* @__PURE__ */ new Date()).toISOString() : date.toISOString();
1785
- }
1786
- function buildReportOutlinePayload(input) {
1787
- const { templateId, fallbackName, sourcePath, content, contentRef, createdAt } = input;
1788
- const createdIso = toCreatedAtIso(createdAt);
1789
- if (!content) {
1790
- return {
1791
- templateId,
1792
- templateName: fallbackName,
1793
- outline: [],
1794
- createdAt: createdIso,
1795
- sourcePath: sourcePath || void 0,
1796
- contentRef
1797
- };
1798
- }
1799
- const parsed = parseMarkdownToOutline(content);
875
+ function isHiddenHuman(msg) {
876
+ return msg?.additional_kwargs?.hide_from_ui === true;
877
+ }
878
+ function hasEmptyKwargs(msg) {
879
+ const kwargs = msg?.additional_kwargs;
880
+ return !kwargs || typeof kwargs !== "object" || Object.keys(kwargs).length === 0;
881
+ }
882
+ function resolveHumanKwargsMerge(prevKwargs, incomingKwargs, incomingIsVariant) {
883
+ if (incomingIsVariant) return prevKwargs;
884
+ const prevEmpty = !prevKwargs || typeof prevKwargs !== "object" || Object.keys(prevKwargs).length === 0;
885
+ return prevEmpty ? incomingKwargs : prevKwargs;
886
+ }
887
+ function readHir(msg) {
888
+ const response = msg?.additional_kwargs?.human_input_response;
889
+ if (!response || typeof response !== "object") return null;
890
+ const requestId = String(response.request_id || "").trim().replace("clarification:", "");
891
+ if (!requestId || response.value === void 0) return null;
892
+ return { requestId, value: response.value };
893
+ }
894
+ function buildClarification(tool) {
895
+ if (tool.name !== "ask_clarification") return null;
896
+ const args = tool.input ?? {};
897
+ const question = typeof args.question === "string" ? args.question : "";
898
+ if (!question) return null;
899
+ const fields = Array.isArray(args.fields) ? args.fields : void 0;
1800
900
  return {
1801
- templateId,
1802
- templateName: parsed.templateName || fallbackName,
1803
- outline: parsed.outline,
1804
- createdAt: createdIso,
1805
- sourcePath: sourcePath || void 0,
1806
- outlineMarkdown: content,
1807
- contentRef
901
+ callId: tool.callId,
902
+ question,
903
+ ...args.options !== void 0 ? { options: args.options } : {},
904
+ ...fields?.length ? { fields } : {}
1808
905
  };
1809
906
  }
1810
- function buildReportBodyPayload(input) {
1811
- const { templateId, fallbackName, sourcePath, content, contentRef, createdAt } = input;
1812
- const createdIso = toCreatedAtIso(createdAt);
1813
- if (!content) {
1814
- return {
1815
- templateId,
1816
- templateName: fallbackName,
1817
- reportTitle: "",
1818
- createdAt: createdIso,
1819
- sourcePath: sourcePath || void 0,
1820
- contentRef
907
+ function createTurnRules(ctx) {
908
+ const { state } = ctx;
909
+ const registerToolCalls = (ti, ai_i, msg, effects) => {
910
+ const toolCalls = msg?.tool_calls;
911
+ if (!Array.isArray(toolCalls) || !toolCalls.length) return;
912
+ let turn = state.turns[ti];
913
+ for (const tc of toolCalls) {
914
+ const callId = String(tc?.id || "").trim();
915
+ if (!callId || ctx.indexes().byToolCallId.has(callId)) continue;
916
+ const tool = {
917
+ callId,
918
+ name: String(tc?.name || ""),
919
+ input: tc?.args,
920
+ artifactMeta: tc?.artifact_meta,
921
+ status: "running"
922
+ };
923
+ turn = ctx.cloneWith(turn, ai_i, (t) => {
924
+ t.ai[ai_i].tools = [...turn.ai[ai_i].tools, tool];
925
+ });
926
+ const tool_i = turn.ai[ai_i].tools.length - 1;
927
+ ctx.indexes().byToolCallId.set(callId, { turn: ti, ai: ai_i, tool: tool_i });
928
+ effects.push({ type: "tool-updated", turnId: turn.id, aiId: turn.ai[ai_i].id, tool });
929
+ const clarification = buildClarification(tool);
930
+ if (clarification) {
931
+ turn = ctx.cloneWith(turn, null, (t) => {
932
+ t.clarifications = [...turn.clarifications, clarification];
933
+ });
934
+ }
935
+ }
936
+ state.turns[ti] = turn;
937
+ };
938
+ const openNewAi = (ti, msg, effects) => {
939
+ let turn = state.turns[ti];
940
+ if (state.openAi !== null) {
941
+ turn = ctx.sealAiSegment(turn, state.openAi, effects);
942
+ }
943
+ const runId = messageRunId(msg) || ctx.streamRunId() || "";
944
+ const body = readMessageContentText(msg);
945
+ const seg = {
946
+ id: String(msg?.id || ""),
947
+ runId,
948
+ body,
949
+ streamingText: body,
950
+ tools: [],
951
+ attachments: [],
952
+ segments: [{ type: "text", content: body }],
953
+ status: "streaming",
954
+ // 段内消息 id 登记(rebuildIndexes 重建 byMessageId 的依据,防 finalize 后 update 索引 miss)
955
+ messageIds: [String(msg?.id || "")].filter(Boolean)
1821
956
  };
1822
- }
1823
- return {
1824
- templateId,
1825
- templateName: fallbackName,
1826
- reportTitle: extractReportTitleFromBody(content, fallbackName),
1827
- createdAt: createdIso,
1828
- sourcePath: sourcePath || void 0,
1829
- bodyMarkdown: content,
1830
- contentRef
957
+ turn = ctx.cloneWith(turn, null, (t) => {
958
+ t.ai = [...turn.ai, seg];
959
+ if (!t.runId && runId) t.runId = runId;
960
+ t.rawMessages = [...t.rawMessages ?? [], msg];
961
+ });
962
+ state.turns[ti] = turn;
963
+ state.openAi = turn.ai.length - 1;
964
+ ctx.indexes().byRunId.set(runId, { turn: ti, ai: state.openAi });
965
+ if (seg.id) ctx.indexes().byMessageId.set(seg.id, { turn: ti, ai: state.openAi });
966
+ effects.push({ type: "ai-opened", turnId: turn.id, ai: turn.ai[turn.ai.length - 1] });
967
+ registerToolCalls(ti, state.openAi, msg, effects);
1831
968
  };
1832
- }
1833
- function collectListSpecs(listEls, spec, source) {
1834
- for (const listEl of listEls) {
1835
- const itemType = formatStr(listEl.attrs["item-type"] || "");
1836
- if (!itemType) continue;
1837
- if (!spec[itemType]) spec[itemType] = [];
1838
- for (const item of listEl.children) {
1839
- if (item.type !== "element" || item.tagName !== "sxin-list-item") continue;
1840
- spec[itemType].push(buildItemSpec(item, source));
969
+ const appendHuman = (msg, allowOptimistic, effects) => {
970
+ const id = String(msg?.id || "").trim();
971
+ const baseId = getHumanMessageBaseId(id) || id;
972
+ const msgRunId = String(msg?.additional_kwargs?.run_id || "").trim();
973
+ if (msgRunId) {
974
+ for (let ti = state.turns.length - 1; ti >= 0; ti--) {
975
+ const t = state.turns[ti];
976
+ const tBase = getHumanMessageBaseId(t.human.id) || t.human.id;
977
+ const tRun = String(t.human.kwargs?.run_id || "").trim();
978
+ if (tBase === baseId && tRun && tRun === msgRunId) {
979
+ const mergedKwargs = resolveHumanKwargsMerge(
980
+ t.human.kwargs,
981
+ msg?.additional_kwargs,
982
+ baseId !== id
983
+ );
984
+ const next = ctx.cloneWith(t, null, (t2) => {
985
+ t2.human = {
986
+ id: t.human.id || id,
987
+ text: t.human.text || extractTextFromMessage(msg),
988
+ kwargs: mergedKwargs
989
+ };
990
+ t2.rawMessages = [...t2.rawMessages ?? [], msg];
991
+ });
992
+ state.turns[ti] = next;
993
+ if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
994
+ effects.push({ type: "message-updated", turnId: next.id, aiId: null });
995
+ return;
996
+ }
997
+ }
1841
998
  }
1842
- }
1843
- }
1844
- function collectChildSpecs(children, spec, source) {
1845
- for (const child of children) {
1846
- if (child.type !== "element") continue;
1847
- const key = formatStr(child.tagName);
1848
- if (!spec[key]) spec[key] = [];
1849
- spec[key].push(buildItemSpec(child, source));
1850
- }
1851
- }
1852
- function buildCustomBlockFromNode(el, source, status) {
1853
- const spec = { ...el.attrs };
1854
- const listEls = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-list");
1855
- if (listEls.length > 0) {
1856
- collectListSpecs(listEls, spec, source);
1857
- } else {
1858
- collectChildSpecs(el.children, spec, source);
1859
- }
1860
- return { id: genBlockId(), type: "custom", tagName: el.tagName, spec, status };
1861
- }
1862
- function buildItemSpec(el, source) {
1863
- const attrs = { ...el.attrs };
1864
- const inner = el.children.map((c) => source.slice(c.start, c.end)).join("").trim();
1865
- if (inner) attrs.text = inner;
1866
- return attrs;
1867
- }
1868
- function flushTextBuf(ctx) {
1869
- const content = ctx.textBuf.value.replace(/\n{3,}/g, "\n\n").trim();
1870
- ctx.textBuf.value = "";
1871
- if (content) {
1872
- ctx.blocks.push({ id: genBlockId(), type: "text", content, status: ctx.status });
1873
- }
1874
- }
1875
- function handleSxinElement(ctx, node) {
1876
- if (!node.closed && !ctx.isHistory) {
1877
- flushTextBuf(ctx);
1878
- return false;
1879
- }
1880
- flushTextBuf(ctx);
1881
- ctx.blocks.push(buildCustomBlockFromNode(node, ctx.rawText, ctx.status));
1882
- return true;
1883
- }
1884
- function walkNodes(ctx, nodes) {
1885
- for (const node of nodes) {
1886
- if (node.type === "text") {
1887
- ctx.textBuf.value += node.value;
1888
- continue;
999
+ if (state.openTurn !== null && !state.turns[state.openTurn].ai.length) {
1000
+ const openHumanBase = getHumanMessageBaseId(state.turns[state.openTurn].human.id);
1001
+ if (openHumanBase && openHumanBase === baseId) {
1002
+ const ti = state.openTurn;
1003
+ const mergedKwargs = resolveHumanKwargsMerge(
1004
+ state.turns[ti].human.kwargs,
1005
+ msg?.additional_kwargs,
1006
+ baseId !== id
1007
+ );
1008
+ const next = ctx.cloneWith(state.turns[ti], null, (t) => {
1009
+ t.human = { id, text: extractTextFromMessage(msg), kwargs: mergedKwargs };
1010
+ t.rawMessages = [...t.rawMessages ?? [], msg];
1011
+ });
1012
+ state.turns[ti] = next;
1013
+ ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
1014
+ effects.push({ type: "message-updated", turnId: next.id, aiId: null });
1015
+ return;
1016
+ }
1889
1017
  }
1890
- if (node.type === "comment") {
1891
- continue;
1018
+ const optimistic = allowOptimistic && !!id && !ctx.indexes().byMessageId.has(id) && !messageRunId(msg) && hasEmptyKwargs(msg);
1019
+ ctx.sealOpenTurn(effects);
1020
+ const turn = {
1021
+ id: id || `turn-${state.turns.length}`,
1022
+ runId: "",
1023
+ createdAt: Number(new Date(msg?.created_at || Date.now())) || Date.now(),
1024
+ human: { id, text: extractTextFromMessage(msg), kwargs: msg?.additional_kwargs },
1025
+ ai: [],
1026
+ clarifications: [],
1027
+ status: "streaming",
1028
+ optimistic,
1029
+ // 原始消息入档(排查用)
1030
+ rawMessages: [msg]
1031
+ };
1032
+ state.turns.push(turn);
1033
+ state.openTurn = state.turns.length - 1;
1034
+ if (id) ctx.indexes().byMessageId.set(id, { turn: state.openTurn, ai: null });
1035
+ if (optimistic) state.optimisticTurnId = turn.id;
1036
+ effects.push({ type: "turn-opened", turn, optimistic });
1037
+ };
1038
+ const appendHiddenHuman = (msg, effects) => {
1039
+ const hir = readHir(msg);
1040
+ if (!hir) return;
1041
+ const toolLoc = ctx.indexes().byToolCallId.get(hir.requestId);
1042
+ const ti = toolLoc?.turn ?? state.openTurn ?? state.turns.length - 1;
1043
+ if (ti < 0) return;
1044
+ const turn = state.turns[ti];
1045
+ const ci = turn.clarifications.findIndex((c) => c.callId === hir.requestId);
1046
+ if (ci < 0) return;
1047
+ const answer = formatAnswerText(hir.value);
1048
+ const id = String(msg?.id || "").trim();
1049
+ const next = ctx.cloneWith(turn, null, (t) => {
1050
+ t.clarifications[ci] = { ...t.clarifications[ci], answer, answerMessageId: id || void 0 };
1051
+ t.rawMessages = [...t.rawMessages ?? [], msg];
1052
+ });
1053
+ state.turns[ti] = next;
1054
+ if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
1055
+ effects.push({ type: "clarification-answered", turnId: next.id, callId: hir.requestId, answer });
1056
+ };
1057
+ const applyToolMessage = (msg, effects) => {
1058
+ const m = msg;
1059
+ const callId = String(m?.tool_call_id || "").trim();
1060
+ if (!callId) return;
1061
+ const result = readMessageContentText(m);
1062
+ const status = m?.status === "error" ? "error" : "finished";
1063
+ const id = String(m?.id || "").trim();
1064
+ const loc = ctx.indexes().byToolCallId.get(callId);
1065
+ if (loc) {
1066
+ const turn2 = state.turns[loc.turn];
1067
+ const old = turn2.ai[loc.ai].tools[loc.tool];
1068
+ const tool = {
1069
+ ...old,
1070
+ status,
1071
+ result,
1072
+ extracted: extractFromToolResult(old.name, result, { artifact_meta: old.artifactMeta, args: old.input }) ?? old.extracted
1073
+ };
1074
+ const next2 = ctx.cloneWith(turn2, loc.ai, (t) => {
1075
+ t.ai[loc.ai].tools[loc.tool] = tool;
1076
+ if (t.ai[loc.ai].status === "sealed") t.ai[loc.ai].attachments = ctx.assembleAttachments(t.ai[loc.ai]);
1077
+ t.rawMessages = [...t.rawMessages ?? [], msg];
1078
+ });
1079
+ state.turns[loc.turn] = next2;
1080
+ if (id) ctx.indexes().byMessageId.set(id, { turn: loc.turn, ai: loc.ai });
1081
+ effects.push({ type: "tool-updated", turnId: next2.id, aiId: next2.ai[loc.ai].id, tool });
1082
+ return;
1892
1083
  }
1893
- if (isInjectedElement(node)) {
1894
- continue;
1084
+ const ti = state.openTurn;
1085
+ const ai_i = state.openAi;
1086
+ if (ti === null || ai_i === null) return;
1087
+ const orphan = {
1088
+ callId,
1089
+ name: String(m?.name || ""),
1090
+ input: {},
1091
+ status,
1092
+ result,
1093
+ extracted: extractFromToolResult(String(m?.name || ""), result)
1094
+ };
1095
+ const turn = state.turns[ti];
1096
+ const next = ctx.cloneWith(turn, ai_i, (t) => {
1097
+ t.ai[ai_i].tools = [...turn.ai[ai_i].tools, orphan];
1098
+ t.rawMessages = [...t.rawMessages ?? [], msg];
1099
+ });
1100
+ state.turns[ti] = next;
1101
+ ctx.indexes().byToolCallId.set(callId, { turn: ti, ai: ai_i, tool: next.ai[ai_i].tools.length - 1 });
1102
+ if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: ai_i });
1103
+ effects.push({ type: "tool-updated", turnId: next.id, aiId: next.ai[ai_i].id, tool: orphan });
1104
+ };
1105
+ const appendAi = (msg, effects) => {
1106
+ const id = String(msg?.id || "").trim();
1107
+ if (state.openTurn === null) {
1108
+ appendHuman(
1109
+ {
1110
+ id: `${id || "ai"}-orphan`,
1111
+ type: "human",
1112
+ content: "",
1113
+ additional_kwargs: {}
1114
+ },
1115
+ false,
1116
+ effects
1117
+ );
1895
1118
  }
1896
- if (node.tagName === "sxin-kb-citation" && node.closed) {
1897
- flushTextBuf(ctx);
1898
- collectCitation(node, ctx.citations);
1899
- continue;
1119
+ const ti = state.openTurn;
1120
+ const runId = messageRunId(msg);
1121
+ const openSeg = state.openAi !== null ? state.turns[ti].ai[state.openAi] : null;
1122
+ if (openSeg && (!runId || !openSeg.runId || runId === openSeg.runId)) {
1123
+ const text = readMessageContentText(msg);
1124
+ const ai_i = state.openAi;
1125
+ const turn = state.turns[ti];
1126
+ const body = text || openSeg.body;
1127
+ const next = ctx.cloneWith(turn, ai_i, (t) => {
1128
+ t.ai[ai_i].body = body;
1129
+ t.ai[ai_i].streamingText = body;
1130
+ if (id && !t.ai[ai_i].messageIds?.includes(id)) {
1131
+ t.ai[ai_i].messageIds = [...t.ai[ai_i].messageIds ?? [], id];
1132
+ }
1133
+ if (!t.ai[ai_i].runId) t.ai[ai_i].runId = runId || ctx.streamRunId() || "";
1134
+ t.rawMessages = [...t.rawMessages ?? [], msg];
1135
+ });
1136
+ state.turns[ti] = next;
1137
+ if (id && id !== openSeg.id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: ai_i });
1138
+ effects.push({ type: "ai-delta", turnId: next.id, aiId: openSeg.id, body, streamingText: body });
1139
+ registerToolCalls(ti, ai_i, msg, effects);
1140
+ return;
1900
1141
  }
1901
- if (node.tagName.startsWith("sxin-")) {
1902
- if (!handleSxinElement(ctx, node)) return false;
1142
+ openNewAi(ti, msg, effects);
1143
+ };
1144
+ return { appendHuman, appendHiddenHuman, appendAi, applyToolMessage, registerToolCalls };
1145
+ }
1146
+
1147
+ // src/parser/body-segments.ts
1148
+ var SEGMENT_TAGS = /* @__PURE__ */ new Set(["sxin-list", "sxin-item"]);
1149
+ function visibleTextOf(node) {
1150
+ if (node.type === "text") return node.value;
1151
+ if (node.type === "comment") return "";
1152
+ return node.children.map(visibleTextOf).join("");
1153
+ }
1154
+ function toItemSegment(el, source) {
1155
+ return {
1156
+ type: "item",
1157
+ tag: "sxin-item",
1158
+ attrs: { ...el.attrs },
1159
+ content: visibleTextOf(el) || void 0,
1160
+ raw: source.slice(el.start, el.end)
1161
+ };
1162
+ }
1163
+ function toListSegment(el, source) {
1164
+ const children = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-item").map((c) => toItemSegment(c, source));
1165
+ return { type: "list", tag: "sxin-list", attrs: { ...el.attrs }, children, raw: source.slice(el.start, el.end) };
1166
+ }
1167
+ function sliceBodySegments(body) {
1168
+ const source = String(body ?? "");
1169
+ const segments = [];
1170
+ let textBuf = "";
1171
+ const flushText = () => {
1172
+ if (!textBuf) return;
1173
+ segments.push({ type: "text", content: textBuf });
1174
+ textBuf = "";
1175
+ };
1176
+ for (const node of tokenizeSxin(source)) {
1177
+ if (node.type === "element" && SEGMENT_TAGS.has(node.tagName)) {
1178
+ flushText();
1179
+ segments.push(node.tagName === "sxin-list" ? toListSegment(node, source) : toItemSegment(node, source));
1180
+ } else if (node.type === "comment") {
1903
1181
  continue;
1182
+ } else if (node.type === "text") {
1183
+ textBuf += node.value;
1184
+ } else {
1185
+ textBuf += source.slice(node.start, node.end);
1904
1186
  }
1905
- ctx.textBuf.value += ctx.rawText.slice(node.start, node.end);
1906
1187
  }
1907
- return true;
1908
- }
1909
- function extractBlocksFromNodes(nodes, rawText, source) {
1910
- const isHistory = source === "history";
1911
- const ctx = {
1912
- rawText,
1913
- isHistory,
1914
- status: isHistory ? "completed" : "streaming",
1915
- blocks: [],
1916
- citations: [],
1917
- textBuf: { value: "" }
1918
- };
1919
- const completed = walkNodes(ctx, nodes);
1920
- if (completed) flushTextBuf(ctx);
1921
- return { blocks: ctx.blocks, citations: ctx.citations };
1188
+ flushText();
1189
+ if (!segments.length) segments.push({ type: "text", content: "" });
1190
+ return segments;
1922
1191
  }
1923
1192
 
1924
- // src/domain/block-builder.ts
1193
+ // src/materializer/turn-machine.ts
1925
1194
  var DEFAULT_TWIN_TOOL_PREFIX = "city-digital-twin-display_";
1926
- function createBlockBuilderLite(options) {
1927
- const source = options.source;
1928
- const isStreaming = !!options.isStreaming;
1929
- const createdAt = Number.isFinite(options.createdAt) ? Number(options.createdAt) : Date.now();
1930
- const twinEnabled = !!options.twin?.enabled;
1931
- const twinToolPrefix = options.twin?.toolPrefix || DEFAULT_TWIN_TOOL_PREFIX;
1932
- const presentFilesSet = /* @__PURE__ */ new Set();
1933
- const writeFilesSet = /* @__PURE__ */ new Set();
1934
- const toolParsers = /* @__PURE__ */ new Map();
1935
- const registerParser = (names, parser) => {
1936
- for (const name of Array.isArray(names) ? names : [names]) {
1937
- toolParsers.set(name, parser);
1195
+ function createTurnMachine(options) {
1196
+ const state = { turns: [], openTurn: null, openAi: null, optimisticTurnId: null };
1197
+ let indexes = createIndexes();
1198
+ const twinEnabled = !!options?.twin?.enabled;
1199
+ const twinToolPrefix = options?.twin?.toolPrefix || DEFAULT_TWIN_TOOL_PREFIX;
1200
+ const streamRunId = () => String(options?.getStreamRunId?.() || "").trim();
1201
+ const assembleAttachments = (seg) => {
1202
+ const byKind = /* @__PURE__ */ new Map();
1203
+ for (const tool of seg.tools) {
1204
+ const ex = tool.extracted;
1205
+ if (ex?.kind === "report") {
1206
+ byKind.set(`report:${ex.reportKind}`, {
1207
+ kind: "report",
1208
+ reportKind: ex.reportKind,
1209
+ body: ex.body,
1210
+ outline: ex.outline,
1211
+ sourcePath: ex.sourcePath,
1212
+ title: ex.title
1213
+ });
1214
+ } else if (ex?.kind === "artifact") byKind.set("artifact", { kind: "artifact", files: ex.files });
1215
+ else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
1216
+ byKind.set("twin", { kind: "twin", payload: tool.input });
1217
+ }
1218
+ }
1219
+ return [...byKind.values()];
1220
+ };
1221
+ const cloneWith = (turn, ai_i, mutate) => {
1222
+ const next = {
1223
+ ...turn,
1224
+ human: { ...turn.human },
1225
+ clarifications: [...turn.clarifications],
1226
+ ai: turn.ai.map((seg, i) => i === ai_i ? { ...seg, tools: [...seg.tools] } : seg)
1227
+ };
1228
+ mutate(next);
1229
+ return next;
1230
+ };
1231
+ const archiveRaw = (t, msg) => {
1232
+ const id = String(msg?.id || "").trim();
1233
+ const raws = t.rawMessages ?? [];
1234
+ const ri = id ? raws.findIndex((r) => String(r?.id || "").trim() === id) : -1;
1235
+ t.rawMessages = ri >= 0 ? [...raws.slice(0, ri), msg, ...raws.slice(ri + 1)] : [...raws, msg];
1236
+ };
1237
+ const sealAiSegment = (turn, ai_i, effects) => {
1238
+ const seg = turn.ai[ai_i];
1239
+ if (seg.status === "sealed") return turn;
1240
+ const sealed = {
1241
+ ...seg,
1242
+ status: "sealed",
1243
+ streamingText: void 0,
1244
+ segments: sliceBodySegments(seg.body),
1245
+ attachments: assembleAttachments(seg)
1246
+ };
1247
+ const next = cloneWith(turn, ai_i, (t) => {
1248
+ t.ai[ai_i] = sealed;
1249
+ });
1250
+ effects.push({ type: "ai-sealed", turnId: next.id, aiId: sealed.id, segments: sealed.segments });
1251
+ return next;
1252
+ };
1253
+ const sealOpenTurn = (effects) => {
1254
+ const ti = state.openTurn;
1255
+ if (ti === null) return;
1256
+ let turn = state.turns[ti];
1257
+ if (state.openAi !== null) {
1258
+ turn = sealAiSegment(turn, state.openAi, effects);
1259
+ state.openAi = null;
1260
+ }
1261
+ if (turn.status !== "sealed") {
1262
+ const sealed = { ...turn, status: "sealed" };
1263
+ state.turns[ti] = sealed;
1264
+ effects.push({ type: "turn-sealed", turnId: sealed.id });
1265
+ }
1266
+ state.openTurn = null;
1267
+ if (state.optimisticTurnId === turn.id) state.optimisticTurnId = null;
1268
+ };
1269
+ const rules = createTurnRules({
1270
+ state,
1271
+ indexes: () => indexes,
1272
+ cloneWith,
1273
+ sealOpenTurn,
1274
+ sealAiSegment,
1275
+ assembleAttachments,
1276
+ streamRunId
1277
+ });
1278
+ const applyTailRemove = (id, effects) => {
1279
+ const ti = state.openTurn;
1280
+ if (state.optimisticTurnId && ti !== null && state.turns[ti]?.human.id === id) {
1281
+ state.turns.pop();
1282
+ state.openTurn = null;
1283
+ state.openAi = null;
1284
+ state.optimisticTurnId = null;
1285
+ indexes = rebuildIndexes(state.turns);
1286
+ effects.push({ type: "placeholder-dropped", turnId: id });
1287
+ return;
1938
1288
  }
1939
1289
  };
1940
- const parseBlockTool = (tool, status) => {
1941
- const name = String(tool.call?.name || "").trim();
1942
- const parser = toolParsers.get(name);
1943
- return parser ? parser(tool, status) : [];
1290
+ const applyAppend = (msg, allowOptimistic, effects) => {
1291
+ if (isHiddenHuman(msg)) return rules.appendHiddenHuman(msg, effects);
1292
+ if (isHumanMessage(msg)) return rules.appendHuman(msg, allowOptimistic, effects);
1293
+ if (isAiMessage(msg)) return rules.appendAi(msg, effects);
1294
+ if (isToolMessage(msg)) return rules.applyToolMessage(msg, effects);
1944
1295
  };
1945
- const parseAskClarification = (tool, _status) => {
1946
- const args = tool.call?.args || {};
1947
- return [
1948
- {
1949
- id: genBlockId(),
1950
- type: "ask-clarification",
1951
- context: args.context,
1952
- question: args.question,
1953
- clarification_type: args.clarification_type,
1954
- options: Array.isArray(args.options) ? args.options : void 0,
1955
- fields: Array.isArray(args.fields) ? args.fields : void 0,
1956
- // clarification 的回答是跨 run 的,不能根据 streaming/source 判断状态,统一 pending,由渲染层结合 thread 级回答状态决定
1957
- status: "pending",
1958
- toolCallId: tool.id
1296
+ const applyUpdate = (id, msg, effects) => {
1297
+ const loc = indexes.byMessageId.get(id);
1298
+ if (!loc) return;
1299
+ if (loc.ai === null) {
1300
+ if (isHiddenHuman(msg)) return rules.appendHiddenHuman(msg, effects);
1301
+ if (!isHumanMessage(msg)) return;
1302
+ const turn2 = state.turns[loc.turn];
1303
+ const wasOptimistic = state.optimisticTurnId === turn2.id;
1304
+ const mergedKwargs = resolveHumanKwargsMerge(
1305
+ turn2.human.kwargs,
1306
+ msg?.additional_kwargs,
1307
+ (getHumanMessageBaseId(id) || id) !== id
1308
+ );
1309
+ const next2 = cloneWith(turn2, null, (t) => {
1310
+ t.human = { id, text: extractTextFromMessage(msg), kwargs: mergedKwargs };
1311
+ t.optimistic = false;
1312
+ archiveRaw(t, msg);
1313
+ });
1314
+ state.turns[loc.turn] = next2;
1315
+ if (wasOptimistic) {
1316
+ state.optimisticTurnId = null;
1317
+ effects.push({ type: "placeholder-absorbed", turnId: next2.id });
1318
+ } else {
1319
+ effects.push({ type: "message-updated", turnId: next2.id, aiId: null });
1959
1320
  }
1960
- ];
1961
- };
1962
- const parseFormBlock = (tool, status, sourceTag) => {
1963
- const args = tool.call?.args || {};
1964
- const variant = String(args.variant || "input");
1965
- const blockStatus = sourceTag === "ask_clarification" ? "pending" : status;
1966
- return [
1967
- {
1968
- id: genBlockId(),
1969
- type: "form",
1970
- variant: ["input", "confirm", "delete_confirm"].includes(variant) ? variant : "input",
1971
- title: args.title,
1972
- question: args.question,
1973
- context: args.context,
1974
- fields: Array.isArray(args.fields) ? args.fields : [],
1975
- values: args.values || {},
1976
- stepInfo: args.stepInfo,
1977
- customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
1978
- status: blockStatus,
1979
- toolCallId: tool.id,
1980
- source: sourceTag
1321
+ return;
1322
+ }
1323
+ if (isToolMessage(msg)) {
1324
+ rules.applyToolMessage(msg, effects);
1325
+ return;
1326
+ }
1327
+ const turn = state.turns[loc.turn];
1328
+ const seg = turn.ai[loc.ai];
1329
+ const text = readMessageContentText(msg);
1330
+ const body = text || seg.body;
1331
+ const bodyChanged = body !== seg.body;
1332
+ const next = cloneWith(turn, loc.ai, (t) => {
1333
+ const target = t.ai[loc.ai];
1334
+ target.body = body;
1335
+ if (target.status === "streaming") target.streamingText = body;
1336
+ if (target.status === "sealed" && bodyChanged) target.segments = sliceBodySegments(body);
1337
+ if (!target.runId) {
1338
+ const rid = messageRunId(msg) || streamRunId();
1339
+ if (rid) target.runId = rid;
1981
1340
  }
1982
- ];
1341
+ archiveRaw(t, msg);
1342
+ });
1343
+ state.turns[loc.turn] = next;
1344
+ if (id !== seg.id && isAiMessage(msg)) {
1345
+ indexes.byMessageId.set(id, { turn: loc.turn, ai: loc.ai });
1346
+ const nextSeg = state.turns[loc.turn].ai[loc.ai];
1347
+ if (!nextSeg.messageIds?.includes(id)) nextSeg.messageIds = [...nextSeg.messageIds ?? [], id];
1348
+ }
1349
+ effects.push({ type: "ai-delta", turnId: next.id, aiId: seg.id, body, streamingText: body });
1350
+ rules.registerToolCalls(loc.turn, loc.ai, msg, effects);
1983
1351
  };
1984
- const parseListBlock = (tool, status) => {
1985
- const args = tool.call?.args || {};
1986
- const mode = String(args.mode || "select");
1987
- return [
1988
- {
1989
- id: genBlockId(),
1990
- type: "list",
1991
- mode: ["select", "view"].includes(mode) ? mode : "select",
1992
- title: args.title,
1993
- dataSource: args.dataSource,
1994
- items: Array.isArray(args.items) ? args.items : void 0,
1995
- queryParams: args.queryParams,
1996
- pagination: args.pagination,
1997
- selectMode: args.selectMode || "single",
1998
- customActions: Array.isArray(args.customActions) ? args.customActions : void 0,
1999
- status,
2000
- toolCallId: tool.id
1352
+ const finalizeInto = (effects) => {
1353
+ sealOpenTurn(effects);
1354
+ indexes = rebuildIndexes(state.turns);
1355
+ };
1356
+ function resetMachine() {
1357
+ state.turns = [];
1358
+ state.openTurn = null;
1359
+ state.openAi = null;
1360
+ state.optimisticTurnId = null;
1361
+ indexes = createIndexes();
1362
+ }
1363
+ return {
1364
+ applyDeltas(deltas) {
1365
+ const effects = [];
1366
+ for (const d of deltas) {
1367
+ if (d.type === "append") applyAppend(d.message, true, effects);
1368
+ else if (d.type === "update") applyUpdate(d.id, d.message, effects);
1369
+ else applyTailRemove(d.id, effects);
1370
+ }
1371
+ return effects;
1372
+ },
1373
+ seed(messages) {
1374
+ if (state.openTurn !== null || state.openAi !== null) {
1375
+ throw new Error("[materializer] \u6D41\u8FDB\u884C\u4E2D\u7981\u6B62 seed\uFF08\u5148 finalize \u5BC6\u5C01\u540E\u518D\u5168\u91CF\u91CD\u5EFA\uFF09");
2001
1376
  }
2002
- ];
1377
+ resetMachine();
1378
+ const effects = [];
1379
+ for (const msg of messages) applyAppend(msg, false, effects);
1380
+ finalizeInto(effects);
1381
+ return effects;
1382
+ },
1383
+ finalize() {
1384
+ const effects = [];
1385
+ finalizeInto(effects);
1386
+ return effects;
1387
+ },
1388
+ decorate(id, patch) {
1389
+ const effects = [];
1390
+ const loc = indexes.byMessageId.get(id);
1391
+ if (!loc || loc.ai === null) return effects;
1392
+ const turn = state.turns[loc.turn];
1393
+ const next = cloneWith(turn, loc.ai, (t) => {
1394
+ Object.assign(t.ai[loc.ai], patch);
1395
+ });
1396
+ state.turns[loc.turn] = next;
1397
+ effects.push({ type: "message-updated", turnId: next.id, aiId: next.ai[loc.ai].id });
1398
+ return effects;
1399
+ },
1400
+ reset: resetMachine,
1401
+ get state() {
1402
+ return state;
1403
+ },
1404
+ get indexes() {
1405
+ return indexes;
1406
+ }
2003
1407
  };
2004
- const parsePresentFiles = (tool, status) => {
2005
- const args = tool.call?.args || {};
2006
- const filepaths = Array.isArray(args?.filepaths) ? args.filepaths : [];
2007
- if (!filepaths.length) return [];
2008
- const paths = [];
2009
- for (const path of filepaths) {
2010
- if (presentFilesSet.has(path)) continue;
2011
- presentFilesSet.add(path);
2012
- paths.push(path);
2013
- }
2014
- if (!paths.length) return [];
2015
- return [
2016
- {
2017
- id: genBlockId(),
2018
- type: "artifact",
2019
- files: buildArtifactFiles(paths),
2020
- status
1408
+ }
1409
+
1410
+ // src/materializer/diff.ts
1411
+ function diffMessageSnapshots(baseline, next) {
1412
+ const upserts = [];
1413
+ const nextBaseline = /* @__PURE__ */ new Map();
1414
+ for (const msg of next) {
1415
+ const id = String(msg?.id || "").trim();
1416
+ if (!id) continue;
1417
+ if (baseline.get(id) !== msg) upserts.push(msg);
1418
+ nextBaseline.set(id, msg);
1419
+ }
1420
+ const removals = [];
1421
+ for (const id of baseline.keys()) if (!nextBaseline.has(id)) removals.push(id);
1422
+ return { upserts, removals, nextBaseline };
1423
+ }
1424
+ function createMessageDiff() {
1425
+ let baseline = /* @__PURE__ */ new Map();
1426
+ return {
1427
+ apply(next) {
1428
+ const { upserts, removals, nextBaseline } = diffMessageSnapshots(baseline, next);
1429
+ const deltas = [];
1430
+ for (const msg of upserts) {
1431
+ const id = String(msg?.id || "").trim();
1432
+ deltas.push(baseline.has(id) ? { type: "update", id, message: msg } : { type: "append", message: msg });
2021
1433
  }
2022
- ];
1434
+ for (const id of removals) deltas.push({ type: "tail-remove", id });
1435
+ baseline = nextBaseline;
1436
+ return deltas;
1437
+ },
1438
+ reset() {
1439
+ baseline = /* @__PURE__ */ new Map();
1440
+ },
1441
+ get baselineSize() {
1442
+ return baseline.size;
1443
+ }
2023
1444
  };
2024
- const resolveWriteFileContext = (tool) => {
2025
- const meta = getToolCallArtifactMeta(tool.call);
2026
- const args = tool.call?.args || {};
2027
- const artifactPath = String(meta?.path || args.path || "").trim();
2028
- const content = String(args.content || tool.result?.content || "").trim();
2029
- const description = String(args.description || "").trim();
2030
- const blockId = tool.id || artifactPath || `report-${Date.now()}`;
2031
- const toolCreatedAt = Number(new Date(asSxin(tool.aiMessage).created_at || ""));
2032
- const toolTime = Number.isFinite(toolCreatedAt) ? toolCreatedAt : createdAt;
2033
- if (!content && source === "sse") return null;
2034
- if (writeFilesSet.has(artifactPath)) return null;
2035
- writeFilesSet.add(artifactPath);
2036
- presentFilesSet.add(artifactPath);
2037
- return { artifactPath, content, description, blockId, createdAt: toolTime };
1445
+ }
1446
+
1447
+ // src/materializer/materializer.ts
1448
+ function createMaterializer(options) {
1449
+ const view = (0, import_vue2.shallowRef)({ turns: [] });
1450
+ const machine = createTurnMachine(options);
1451
+ const messageDiff = createMessageDiff();
1452
+ const publishIfChanged = (effects) => {
1453
+ if (!effects.length) return;
1454
+ view.value = { turns: [...machine.state.turns] };
2038
1455
  };
2039
- const buildReportBlock = (kind, ctx, status) => {
2040
- const isOutline = kind === "report_outline";
2041
- const fallbackName = extractTitleFromArtifactPath(ctx.artifactPath, kind) || ctx.description.replace(isOutline ? /生成|大纲/g : /生成|正文|报告/g, "").trim() || "\u62A5\u544A";
2042
- const isState = source === "state";
2043
- const payloadInput = {
2044
- templateId: ctx.blockId,
2045
- fallbackName,
2046
- sourcePath: ctx.artifactPath || void 0,
2047
- content: isState ? void 0 : ctx.content || void 0,
2048
- contentRef: isState && ctx.artifactPath ? { path: ctx.artifactPath } : void 0,
2049
- createdAt: ctx.createdAt
2050
- };
2051
- return isOutline ? { id: genBlockId(), type: "report-outline", payload: buildReportOutlinePayload(payloadInput), status } : { id: genBlockId(), type: "report-body", payload: buildReportBodyPayload(payloadInput), status };
1456
+ return {
1457
+ view,
1458
+ hydrate(seed) {
1459
+ messageDiff.reset();
1460
+ messageDiff.apply(seed);
1461
+ const effects = machine.seed(seed);
1462
+ publishIfChanged(effects);
1463
+ },
1464
+ applySnapshot(messages) {
1465
+ const deltas = messageDiff.apply(messages);
1466
+ if (!deltas.length) return;
1467
+ const effects = machine.applyDeltas(deltas);
1468
+ publishIfChanged(effects);
1469
+ },
1470
+ finalize() {
1471
+ publishIfChanged(machine.finalize());
1472
+ },
1473
+ decorate(messageId, patch) {
1474
+ publishIfChanged(machine.decorate(messageId, patch));
1475
+ },
1476
+ reset() {
1477
+ messageDiff.reset();
1478
+ machine.reset();
1479
+ view.value = { turns: [] };
1480
+ }
2052
1481
  };
2053
- const parseWriteFile = (tool, status) => {
2054
- const name = String(tool.call?.name || "").trim();
2055
- if (!isWriteFileToolName(name)) return [];
2056
- const kind = resolveReportArtifactKind(tool.call);
2057
- if (!kind) return [];
2058
- const ctx = resolveWriteFileContext(tool);
2059
- if (!ctx) return [];
2060
- const block = buildReportBlock(kind, ctx, status);
2061
- return block ? [block] : [];
1482
+ }
1483
+
1484
+ // src/runtime/runtime-materializer.ts
1485
+ var localSeq = 0;
1486
+ function createRuntimeMaterializer(options) {
1487
+ const materializer = createMaterializer({ twin: options.twin, getStreamRunId: options.getStreamRunId });
1488
+ let lastMessages = [];
1489
+ const answersMap = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Map());
1490
+ const answers = (0, import_vue3.computed)(() => answersMap.value);
1491
+ const turns = (0, import_vue3.computed)(() => materializer.view.value.turns);
1492
+ const activeClarification = (0, import_vue3.computed)(() => {
1493
+ const ts = materializer.view.value.turns;
1494
+ const last = ts[ts.length - 1];
1495
+ if (!last) return void 0;
1496
+ for (let ci = last.clarifications.length - 1; ci >= 0; ci--) {
1497
+ const c = last.clarifications[ci];
1498
+ if (!c.answer && !answersMap.value.has(c.callId)) return c;
1499
+ }
1500
+ return void 0;
1501
+ });
1502
+ const feed = (messages) => {
1503
+ lastMessages = messages;
1504
+ materializer.applySnapshot(messages);
2062
1505
  };
2063
- const parseClarification = (tool, status) => {
2064
- const args = tool.call?.args || {};
2065
- if (args.variant || args.fields?.length) {
2066
- return parseFormBlock(tool, status, "ask_clarification");
1506
+ return {
1507
+ view: materializer.view,
1508
+ turns,
1509
+ activeClarification,
1510
+ answers,
1511
+ setClarificationAnswer(toolCallId, answer) {
1512
+ const next = new Map(answersMap.value);
1513
+ next.set(toolCallId, answer);
1514
+ answersMap.value = next;
1515
+ },
1516
+ clearClarificationAnswers() {
1517
+ if (!answersMap.value.size) return;
1518
+ answersMap.value = /* @__PURE__ */ new Map();
1519
+ },
1520
+ lastMessages: () => lastMessages,
1521
+ hydrate(seed) {
1522
+ lastMessages = seed;
1523
+ materializer.hydrate(seed);
1524
+ },
1525
+ applySnapshot(messages) {
1526
+ lastMessages = messages;
1527
+ materializer.applySnapshot(messages);
1528
+ },
1529
+ finalize() {
1530
+ materializer.finalize();
1531
+ },
1532
+ decorate(messageId, patch) {
1533
+ materializer.decorate(messageId, patch);
1534
+ },
1535
+ prependHistory(older) {
1536
+ const merged = [...older, ...lastMessages];
1537
+ try {
1538
+ materializer.hydrate(merged);
1539
+ } catch {
1540
+ return false;
1541
+ }
1542
+ lastMessages = merged;
1543
+ return true;
1544
+ },
1545
+ reconcileWithPage(pageMessages) {
1546
+ if (!pageMessages.length || !lastMessages.length) return;
1547
+ const byId = new Map(pageMessages.map((m) => [String(m?.id || ""), m]));
1548
+ feed(lastMessages.map((m) => byId.get(String(m?.id || "")) ?? m));
1549
+ },
1550
+ addOptimisticTurn(body) {
1551
+ localSeq += 1;
1552
+ const stamp = `${Date.now()}-${localSeq}`;
1553
+ const humanMsg = {
1554
+ id: `local-h-${stamp}`,
1555
+ type: "human",
1556
+ content: [{ type: "text", text: body }],
1557
+ additional_kwargs: {}
1558
+ };
1559
+ const aiMsg = {
1560
+ id: `local-a-${stamp}`,
1561
+ type: "ai",
1562
+ content: [{ type: "text", text: "" }],
1563
+ additional_kwargs: {}
1564
+ };
1565
+ feed([...lastMessages, humanMsg, aiMsg]);
1566
+ },
1567
+ updateAiBody(aiId, body) {
1568
+ const idx = lastMessages.findIndex((m) => String(m?.id || "") === aiId);
1569
+ if (idx < 0) return;
1570
+ const next = [...lastMessages];
1571
+ next[idx] = { ...next[idx], content: [{ type: "text", text: body }] };
1572
+ feed(next);
1573
+ },
1574
+ applySemanticPatch(patches) {
1575
+ if (!patches.size || !lastMessages.length) return;
1576
+ const next = applySemanticPatches(lastMessages, patches);
1577
+ const changed = next.some((m, i) => m !== lastMessages[i]);
1578
+ if (changed) feed(next);
2067
1579
  }
2068
- return parseAskClarification(tool, status);
2069
1580
  };
2070
- registerParser("ask_clarification", parseClarification);
2071
- registerParser(
2072
- ["confirm_form", "form"],
2073
- (tool, status) => parseFormBlock(tool, status, String(tool.call?.name || "").trim())
2074
- );
2075
- registerParser(["list_and_select", "list"], parseListBlock);
2076
- registerParser("present_files", parsePresentFiles);
2077
- registerParser(["write_file", "write_files"], parseWriteFile);
2078
- const buildFromNodes = (nodes, rawText, tools) => {
2079
- const blocks = [];
2080
- const status = isStreaming ? "streaming" : "completed";
2081
- const contentSource = source === "state" ? "history" : source;
2082
- const { blocks: contentBlocks, citations } = extractBlocksFromNodes(nodes, rawText, contentSource);
2083
- blocks.push(...contentBlocks);
2084
- for (const tool of tools) {
2085
- const toolBlocks = parseBlockTool(tool, status);
2086
- blocks.push(...toolBlocks);
2087
- }
2088
- if (citations.length > 0) {
2089
- blocks.push({
2090
- id: genBlockId(),
2091
- type: "citation",
2092
- items: citations.map((c) => ({ ...c, title: c.title || "" })),
2093
- status
1581
+ }
1582
+
1583
+ // src/runtime/values-projection.ts
1584
+ var import_vue4 = require("vue");
1585
+ var import_ui = require("@langchain/langgraph-sdk/ui");
1586
+
1587
+ // src/runtime/interrupt-reconcile.ts
1588
+ function reconcileInterrupts(prevValues, nextValues, firstEvent) {
1589
+ let base = prevValues;
1590
+ if (firstEvent && base && "__interrupt__" in base) {
1591
+ const { __interrupt__: _dropped, ...rest } = base;
1592
+ base = rest;
1593
+ }
1594
+ if (nextValues && typeof nextValues === "object" && "__interrupt__" in nextValues) {
1595
+ let interrupts = nextValues.__interrupt__;
1596
+ const prevInterrupts = base?.__interrupt__;
1597
+ if (Array.isArray(interrupts) && interrupts.length > 0 && Array.isArray(prevInterrupts)) {
1598
+ const merged = [...prevInterrupts];
1599
+ const existingIds = new Set(merged.map((i) => i?.id).filter((id) => id != null));
1600
+ for (const interrupt of interrupts) {
1601
+ const id = interrupt?.id;
1602
+ if (id != null) {
1603
+ if (existingIds.has(id)) continue;
1604
+ existingIds.add(id);
1605
+ }
1606
+ merged.push(interrupt);
1607
+ }
1608
+ interrupts = merged;
1609
+ }
1610
+ return { ...base, __interrupt__: interrupts };
1611
+ }
1612
+ if (nextValues && typeof nextValues === "object") {
1613
+ if (base && "__interrupt__" in base && Array.isArray(base.__interrupt__)) {
1614
+ return { ...nextValues, __interrupt__: base.__interrupt__ };
1615
+ }
1616
+ return nextValues;
1617
+ }
1618
+ return nextValues ?? {};
1619
+ }
1620
+
1621
+ // src/runtime/values-projection.ts
1622
+ function createValuesChannel(options = {}) {
1623
+ const valuesRef = (0, import_vue4.shallowRef)({});
1624
+ const threadStateRef = (0, import_vue4.shallowRef)(void 0);
1625
+ let firstEvent = true;
1626
+ let lastTitle = "";
1627
+ let latestStreamMessages = [];
1628
+ const readStateMessages = () => {
1629
+ const msgs = threadStateRef.value?.values?.messages;
1630
+ return Array.isArray(msgs) ? [...msgs] : [];
1631
+ };
1632
+ const readStreamMessages = () => [...latestStreamMessages];
1633
+ return {
1634
+ applyInitialValues(next) {
1635
+ valuesRef.value = { ...next ?? {} };
1636
+ },
1637
+ applyThreadState(state) {
1638
+ threadStateRef.value = state;
1639
+ },
1640
+ beginStream() {
1641
+ firstEvent = true;
1642
+ threadStateRef.value = void 0;
1643
+ latestStreamMessages = [];
1644
+ },
1645
+ applyValuesEvent(data) {
1646
+ const reconciled = reconcileInterrupts(valuesRef.value, data, firstEvent);
1647
+ firstEvent = false;
1648
+ valuesRef.value = reconciled;
1649
+ if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
1650
+ const title = String(reconciled?.title || "").trim();
1651
+ if (title && title !== lastTitle) {
1652
+ lastTitle = title;
1653
+ options.onTitle?.(title);
1654
+ }
1655
+ },
1656
+ getValues() {
1657
+ return valuesRef.value;
1658
+ },
1659
+ getStateMessages: readStateMessages,
1660
+ getStreamMessages: readStreamMessages,
1661
+ getInterrupt({ isLoading, error }) {
1662
+ return (0, import_ui.extractInterrupts)(valuesRef.value, {
1663
+ isLoading,
1664
+ threadState: threadStateRef.value,
1665
+ error
2094
1666
  });
2095
1667
  }
2096
- if (twinEnabled) {
2097
- const twinTool = tools.reverse().find((_) => _.call?.name.includes(twinToolPrefix));
2098
- if (twinTool) {
2099
- blocks.push({
2100
- id: genBlockId(),
2101
- type: "twin",
2102
- toolName: twinTool.call.name.replace(twinToolPrefix, ""),
2103
- args: twinTool.call.args
2104
- });
2105
- }
2106
- }
2107
- return blocks;
2108
1668
  };
2109
- const build = (content, tools) => buildFromNodes(tokenizeSxin(content), content, tools);
2110
- return { build, buildFromNodes };
2111
1669
  }
2112
1670
 
2113
- // src/domain/group-materializer.ts
2114
- function readCreatedAt(msg) {
2115
- return Number(new Date(asSxin(msg).created_at || Date.now())) || Date.now();
2116
- }
2117
- function buildHumanGroup(messages, status) {
2118
- const representative = messages.find(
2119
- (m) => parseHumanMessageId(String(asSxin(m).id || "")).variant === "user" && isVisibleUserMessage(m)
2120
- ) || messages.find((m) => isVisibleUserMessage(m)) || messages[0];
2121
- const firstId = messages.find((_) => _.id)?.id || genMessageId();
2122
- const additionalKwargs = asSxin(representative).additional_kwargs;
2123
- const texts = extractUserMessageTexts(messages);
2124
- const runId = messageRunId(representative);
1671
+ // src/store/runs-store.ts
1672
+ var import_vue5 = require("vue");
1673
+
1674
+ // src/runtime/run-info.ts
1675
+ function buildRunInfo(run, threadId) {
2125
1676
  return {
2126
- id: firstId,
2127
- type: "human",
2128
- status,
2129
- originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
2130
- runId,
2131
- rawMessages: messages,
2132
- texts,
2133
- additionalKwargs,
2134
- blocks: [],
2135
- toolIds: [],
2136
- tools: [],
2137
- createdAt: readCreatedAt(representative)
1677
+ runId: String(run?.run_id || "").trim(),
1678
+ threadId: String(threadId || "").trim(),
1679
+ usage: buildRunUsage(run),
1680
+ latencyMs: buildRunLatencyMs(run),
1681
+ finishReason: toOptionalString(run?.stop_reason ?? run?.finish_reason),
1682
+ modelName: toOptionalString(run?.model_name),
1683
+ status: buildRunStatus(run),
1684
+ createdAt: buildRunCreatedAt(run)
2138
1685
  };
2139
1686
  }
2140
- function buildAiGroup(messages, options, twin) {
2141
- const firstId = messages.find((_) => _.id)?.id || genMessageId();
2142
- const groupTools = deriveToolsFromMessages(messages);
2143
- const aiMessages = messages.filter(isAiMessage);
2144
- const lastAi = aiMessages[aiMessages.length - 1] || messages[messages.length - 1];
2145
- const content = readMessageContentText(lastAi);
2146
- const createdAt = readCreatedAt(messages[0]);
2147
- const blocks = options.isStreaming ? [] : createBlockBuilderLite({ source: options.source, twin, createdAt }).buildFromNodes(
2148
- tokenizeSxin(content),
2149
- content,
2150
- groupTools
2151
- );
2152
- return {
2153
- id: firstId,
2154
- type: "ai",
2155
- status: options.isStreaming ? "streaming" : "completed",
2156
- originMessageIds: messages.map((m) => String(asSxin(m).id || "").trim()).filter(Boolean),
2157
- runId: messageRunId(lastAi) || options.runId,
2158
- rawMessages: messages,
2159
- blocks,
2160
- toolIds: groupTools.map((t) => t.id),
2161
- tools: groupTools,
2162
- createdAt
2163
- };
1687
+ function toOptionalString(value) {
1688
+ return value ? String(value) : void 0;
2164
1689
  }
2165
-
2166
- // src/domain/clarification.ts
2167
- function isClarificationAnswered(block, answers) {
2168
- if (!block) return false;
2169
- if (block.status === "completed") return true;
2170
- if (block.isAnswered) return true;
2171
- const toolCallId = block.toolCallId;
2172
- return !!toolCallId && answers.has(toolCallId);
1690
+ function buildRunUsage(run) {
1691
+ return normalizeUsage({
1692
+ input_tokens: run?.total_input_tokens,
1693
+ output_tokens: run?.total_output_tokens,
1694
+ total_tokens: run?.total_tokens
1695
+ });
2173
1696
  }
2174
- function isClarificationBlock(block) {
2175
- return block.type === "ask-clarification" || block.type === "form" && block.source === "ask_clarification";
1697
+ function buildRunStatus(run) {
1698
+ return run?.status ? String(run.status) : void 0;
2176
1699
  }
2177
-
2178
- // src/parser/hitl.ts
2179
- var import_lodash = require("lodash");
2180
- function parseHitlPayload(value) {
2181
- if (!value || typeof value !== "object") return null;
2182
- const raw = value;
2183
- const requests = raw.actionRequests ?? raw.action_requests;
2184
- if (!Array.isArray(requests) || !requests.length) return null;
2185
- const configs = raw.reviewConfigs ?? raw.review_configs;
2186
- return {
2187
- actionRequests: requests,
2188
- reviewConfigs: Array.isArray(configs) ? configs : []
2189
- };
1700
+ function buildRunCreatedAt(run) {
1701
+ return run?.created_at ? Number(new Date(run.created_at)) : void 0;
2190
1702
  }
2191
- function buildInterruptReviewBlock(interrupt, responded) {
2192
- const payload = parseHitlPayload(interrupt.value);
2193
- if (!payload) return null;
2194
- const interruptId = String(interrupt.id || genMessageId());
2195
- const status = responded ? "completed" : "pending";
2196
- return {
2197
- id: `interrupt-review-${interruptId}`,
2198
- type: "interrupt-review",
2199
- status,
2200
- payload,
2201
- interruptId
2202
- };
1703
+ function buildRunDirectLatencyMs(run) {
1704
+ const direct = Number(run?.latency_ms);
1705
+ return direct || void 0;
2203
1706
  }
2204
-
2205
- // src/domain/decorators.ts
2206
- function applyPatchesAndExtras(groups, state, runIdFilter) {
2207
- if (!state.patches.size && !state.extras.length) return groups;
2208
- const patchedGroups = groups.map((g) => state.patches.get(g.id) ?? g);
2209
- const anchor = runIdFilter ? patchedGroups.findIndex((g) => String(g.runId || "").trim() === runIdFilter) : -1;
2210
- return anchor >= 0 ? [...patchedGroups.slice(0, anchor), ...state.extras, ...patchedGroups.slice(anchor)] : [...patchedGroups, ...state.extras];
2211
- }
2212
- function withInterruptBlock(groups, deps) {
2213
- const interrupt = deps.getInterrupt();
2214
- if (!interrupt) return groups;
2215
- const interruptId = String(interrupt.id || "");
2216
- const responded = !!interruptId && deps.respondedIds.has(interruptId);
2217
- const block = buildInterruptReviewBlock(interrupt, responded);
2218
- if (!block) return groups;
2219
- const { interruptBlocks } = deps;
2220
- const targetIndex = findLastAiIndex(groups);
2221
- if (targetIndex >= 0) {
2222
- const remembered = interruptBlocks.get(interruptId);
2223
- if (remembered) {
2224
- const updated = { ...block, status: responded ? "completed" : "pending" };
2225
- interruptBlocks.set(interruptId, updated);
2226
- const next2 = [...groups];
2227
- next2[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, updated] };
2228
- return next2;
2229
- }
2230
- interruptBlocks.set(interruptId, block);
2231
- const next = [...groups];
2232
- next[targetIndex] = { ...groups[targetIndex], blocks: [...groups[targetIndex].blocks, block] };
2233
- return next;
2234
- }
2235
- const existing = [...interruptBlocks.values()].find(
2236
- (b) => b.type === "interrupt-review" && b.interruptId === interruptId
2237
- );
2238
- if (existing) return groups;
2239
- interruptBlocks.set(interruptId, block);
2240
- return [
2241
- ...groups,
2242
- {
2243
- id: `interrupt-${interruptId}`,
2244
- type: "ai",
2245
- status: block.status,
2246
- source: "state",
2247
- originMessageIds: [],
2248
- blocks: [block],
2249
- toolIds: [],
2250
- tools: [],
2251
- rawMessages: [],
2252
- createdAt: Date.now()
2253
- }
2254
- ];
1707
+ function buildRunLatencyMs(run) {
1708
+ const direct = buildRunDirectLatencyMs(run);
1709
+ if (direct !== void 0) return direct;
1710
+ const created = Date.parse(String(run?.created_at ?? ""));
1711
+ const updated = Date.parse(String(run?.updated_at ?? ""));
1712
+ if (Number.isNaN(created) || Number.isNaN(updated)) return void 0;
1713
+ const diff = updated - created;
1714
+ return diff >= 0 ? diff : void 0;
2255
1715
  }
2256
- function findLastAiIndex(groups) {
2257
- for (let i = groups.length - 1; i >= 0; i--) {
2258
- if (groups[i].type === "ai") return i;
1716
+ function pickRunMessageMetadata(messages) {
1717
+ let modelName;
1718
+ let finishReason;
1719
+ for (const msg of messages) {
1720
+ if (!isAiMessage(msg)) {
1721
+ continue;
1722
+ }
1723
+ const responseMetadata = msg?.response_metadata || {};
1724
+ if (!modelName && responseMetadata.model_name) {
1725
+ modelName = String(responseMetadata.model_name);
1726
+ }
1727
+ if (!finishReason && responseMetadata.finish_reason) {
1728
+ finishReason = String(responseMetadata.finish_reason);
1729
+ }
1730
+ if (modelName && finishReason) {
1731
+ break;
1732
+ }
2259
1733
  }
2260
- return -1;
2261
- }
2262
- function decorateAnswers(groups, answers, responded) {
2263
- if (!answers.size && !responded.size) return groups;
2264
- return groups.map((g) => {
2265
- if (g.type !== "ai" || !g.blocks.length) return g;
2266
- let touched = false;
2267
- const blocks = g.blocks.map((b) => {
2268
- const blk = b;
2269
- if (isClarificationBlock(blk) && blk.toolCallId && answers.has(blk.toolCallId)) {
2270
- touched = true;
2271
- return { ...b, isAnswered: true, answer: answers.get(blk.toolCallId) };
2272
- }
2273
- if (blk.type === "interrupt-review" && blk.interruptId && responded.has(blk.interruptId)) {
2274
- touched = true;
2275
- return { ...b, isResponded: true };
2276
- }
2277
- return b;
2278
- });
2279
- return touched ? { ...g, blocks } : g;
2280
- });
2281
- }
2282
- function filterInvisibleAiGroups(groups) {
2283
- return groups.filter((g) => g.type !== "ai" || hasVisibleAiContent(g));
2284
- }
2285
- function hasVisibleAiContent(g) {
2286
- if (g.status === "streaming") return true;
2287
- if (g.streamingText) return true;
2288
- if (g.blocks.length) return true;
2289
- return g.tools.some((t) => t.result !== void 0 || t.state === "error");
1734
+ return { modelName, finishReason };
2290
1735
  }
2291
1736
 
2292
- // src/domain/viewmodel-state.ts
2293
- var import_vue4 = require("vue");
2294
- function createViewModelState() {
2295
- const extrasRef = (0, import_vue4.shallowRef)([]);
2296
- const patches = (0, import_vue4.shallowReactive)(/* @__PURE__ */ new Map());
2297
- const readFirstText = (group) => extractTextFromMessage(asSxin(group.rawMessages[0])).trim();
1737
+ // src/store/runs-store.ts
1738
+ function createInterruptState() {
1739
+ const respondedIds = (0, import_vue5.shallowRef)(/* @__PURE__ */ new Set());
2298
1740
  return {
2299
- get extras() {
2300
- return extrasRef.value;
2301
- },
2302
- get patches() {
2303
- return patches;
2304
- },
2305
- appendExtra(groups) {
2306
- if (!groups.length) return;
2307
- extrasRef.value = [...extrasRef.value, ...groups];
2308
- },
2309
- patchGroup(messageId, patch, sourceGroups) {
2310
- const current = patches.get(messageId) ?? sourceGroups().find((g) => g.id === messageId);
2311
- if (!current) return;
2312
- const next = typeof patch === "function" ? patch(current) : { ...current, ...patch };
2313
- patches.set(messageId, { ...next, id: current.id });
2314
- },
2315
- clearPatches() {
2316
- patches.clear();
2317
- extrasRef.value = [];
1741
+ respondedIds,
1742
+ markResponded(id) {
1743
+ const next = new Set(respondedIds.value);
1744
+ next.add(id);
1745
+ respondedIds.value = next;
2318
1746
  },
2319
- /** human extras 按序收敛:回显(同文本 + 当前流 runId)到达后按序移除乐观副本。
2320
- * 用 runId 而非流式段判定:既有线程的回显可能经 reconcile 以 page-source 到达(不在流式段),
2321
- * 但其 runId 与当前流一致;历史消息 runId 不同,不会误伤(连发同文本逐条配对)。
2322
- * 无当前流 runId(流未开始)时不 prune——避免历史同文本消息误吞乐观副本。 */
2323
- pruneExtras(decoratedGroups, currentRunId) {
2324
- if (!extrasRef.value.some((g) => g.type === "human")) return;
2325
- const runIdFilter = String(currentRunId || "").trim();
2326
- if (!runIdFilter) return;
2327
- const echoed = /* @__PURE__ */ new Map();
2328
- for (const g of decoratedGroups) {
2329
- if (g.type !== "human") continue;
2330
- const runId = String(g.runId || "").trim();
2331
- if (runId !== runIdFilter) continue;
2332
- const text = readFirstText(g);
2333
- echoed.set(text, (echoed.get(text) ?? 0) + 1);
2334
- }
2335
- const seenPerText = /* @__PURE__ */ new Map();
2336
- extrasRef.value = extrasRef.value.filter((extra) => {
2337
- if (extra.type !== "human") return true;
2338
- const text = readFirstText(extra);
2339
- const k = seenPerText.get(text) ?? 0;
2340
- seenPerText.set(text, k + 1);
2341
- return (echoed.get(text) ?? 0) <= k;
2342
- });
1747
+ unmarkResponded(id) {
1748
+ if (!respondedIds.value.has(id)) return;
1749
+ const next = new Set(respondedIds.value);
1750
+ next.delete(id);
1751
+ respondedIds.value = next;
2343
1752
  }
2344
1753
  };
2345
1754
  }
2346
-
2347
- // src/domain/viewmodel.ts
2348
- function createGroupDeriver(state) {
2349
- const groupMemo = /* @__PURE__ */ new Map();
2350
- const foldCache = { pageCount: -1, entries: [] };
2351
- const interruptBlocks = /* @__PURE__ */ new Map();
2352
- const derive = (deps) => {
2353
- const { store, enrichments } = deps;
2354
- const streaming = store.streamStatus === "streaming";
2355
- const patched = store.getMessages().map((m) => {
2356
- const patch = enrichments.resolveCitation(String(asSxin(m).id || ""));
2357
- if (!patch) return m;
2358
- return {
2359
- ...asSxin(m),
2360
- ...patch.content !== void 0 ? { content: patch.content } : {},
2361
- additional_kwargs: {
2362
- ...asSxin(m).additional_kwargs ?? {},
2363
- ...patch.citationInfo !== void 0 ? { citation_info: patch.citationInfo } : {}
2364
- }
2365
- };
2366
- });
2367
- const sourceOf = (id) => id ? store.getEntity(id)?.source ?? "stream" : "stream";
2368
- const epochOf = (id) => id ? store.getEntity(id)?.epoch : void 0;
2369
- const runIdFilter = String(deps.currentRunId || "").trim();
2370
- const currentEpoch = store.streamEpoch;
2371
- const pageCount = store.pageCount;
2372
- const patchedPrefix = patched.slice(0, pageCount);
2373
- const patchedStream = patched.slice(pageCount);
2374
- let prefixEntries;
2375
- if (foldCache.pageCount === pageCount) {
2376
- prefixEntries = foldCache.entries;
2377
- } else {
2378
- prefixEntries = [];
2379
- foldMessages(
2380
- patchedPrefix,
2381
- (type, buf) => prefixEntries.push({ type, ids: buf.map((m) => String(asSxin(m).id || "")) })
2382
- );
2383
- foldCache.pageCount = pageCount;
2384
- foldCache.entries = prefixEntries;
2385
- }
2386
- const prefixById = new Map(patchedPrefix.map((m) => [String(asSxin(m).id || ""), m]));
2387
- const folded = [];
2388
- if (prefixEntries.every((e) => e.ids.every((id) => prefixById.has(id)))) {
2389
- for (const e of prefixEntries) folded.push({ type: e.type, buf: e.ids.map((id) => prefixById.get(id)) });
2390
- const streamFolded = [];
2391
- foldMessages(patchedStream, (type, buf) => streamFolded.push({ type, buf }));
2392
- const lastPrefix = folded[folded.length - 1];
2393
- const firstStream = streamFolded[0];
2394
- if (lastPrefix && firstStream && canMergeAtBoundary(lastPrefix, firstStream)) {
2395
- lastPrefix.buf = [...lastPrefix.buf, ...firstStream.buf];
2396
- streamFolded.shift();
1755
+ function createRunsStore(options) {
1756
+ const runsMap = (0, import_vue5.shallowRef)(/* @__PURE__ */ new Map());
1757
+ const currentRunId = (0, import_vue5.shallowRef)(null);
1758
+ return {
1759
+ runsMap,
1760
+ currentRunId,
1761
+ fillFromRunsList(runsList) {
1762
+ let next = null;
1763
+ for (const run of runsList) {
1764
+ const runId = String(run?.run_id || "").trim();
1765
+ if (!runId) continue;
1766
+ next ?? (next = new Map(runsMap.value));
1767
+ next.set(runId, buildRunInfo(run, options.threadId));
2397
1768
  }
2398
- folded.push(...streamFolded);
2399
- } else {
2400
- foldCache.pageCount = -1;
2401
- foldCache.entries = [];
2402
- foldMessages(patched, (type, buf) => folded.push({ type, buf }));
2403
- }
2404
- const groups = [];
2405
- let epochActiveFrom = 0;
2406
- if (streaming && !runIdFilter) {
2407
- epochActiveFrom = -1;
2408
- folded.forEach((entry, i) => {
2409
- const id = String(asSxin(entry.buf[0]).id || "");
2410
- if (entry.type === "human" && sourceOf(id) === "stream" && epochOf(id) === currentEpoch) epochActiveFrom = i;
2411
- });
2412
- if (epochActiveFrom < 0) epochActiveFrom = 0;
2413
- }
2414
- folded.forEach((entry, gi) => {
2415
- const firstId = String(asSxin(entry.buf[0]).id || "");
2416
- const firstSource = sourceOf(firstId);
2417
- let groupRunId = messageRunId(entry.buf[0]);
2418
- if (!groupRunId) {
2419
- for (let i = 1; i < entry.buf.length; i++) {
2420
- const rid = messageRunId(entry.buf[i]);
2421
- if (rid) {
2422
- groupRunId = rid;
2423
- break;
1769
+ if (next) runsMap.value = next;
1770
+ },
1771
+ ensureRunning(runId) {
1772
+ if (runsMap.value.has(runId)) return;
1773
+ const next = new Map(runsMap.value);
1774
+ ensureRunningRun(next, runId, options.threadId);
1775
+ runsMap.value = next;
1776
+ },
1777
+ async refreshRuns() {
1778
+ try {
1779
+ const runsList = await options.transport.listRuns(options.threadId, 20);
1780
+ if (!Array.isArray(runsList)) return;
1781
+ const merged = new Map(runsMap.value);
1782
+ for (const run of runsList) {
1783
+ const runId = String(run.run_id || "").trim();
1784
+ if (!runId) continue;
1785
+ const info = buildRunInfo(run, options.threadId);
1786
+ const prev = merged.get(runId);
1787
+ if (!prev) {
1788
+ merged.set(runId, info);
1789
+ continue;
2424
1790
  }
1791
+ const directLatency = buildRunDirectLatencyMs(run);
1792
+ merged.set(runId, {
1793
+ ...info,
1794
+ feedback: info.feedback ?? prev.feedback,
1795
+ latencyMs: directLatency ?? prev.latencyMs ?? info.latencyMs,
1796
+ modelName: info.modelName ?? prev.modelName,
1797
+ finishReason: info.finishReason ?? prev.finishReason
1798
+ });
2425
1799
  }
1800
+ runsMap.value = merged;
1801
+ } catch (e) {
1802
+ console.warn("[runs-store] refreshRuns failed", e);
2426
1803
  }
2427
- groupRunId = groupRunId || void 0;
2428
- const inActiveZone = streaming ? runIdFilter ? groupRunId === runIdFilter : firstSource === "stream" && epochOf(firstId) === currentEpoch && gi >= epochActiveFrom : false;
2429
- const status = inActiveZone ? "streaming" : "completed";
2430
- const blockSource = firstSource === "page" ? "history" : "sse";
2431
- let verSum = 0;
2432
- for (const m of entry.buf) verSum += store.getEntity(String(asSxin(m).id || ""))?.ver ?? 0;
2433
- const memoKey = `${firstId}|${status}|${blockSource}|${entry.buf.length}|${verSum}|${enrichments.citationVersion}`;
2434
- const cached = groupMemo.get(memoKey);
2435
- if (cached) {
2436
- groups.push(cached);
2437
- return;
2438
- }
2439
- let g;
2440
- if (entry.type === "human") {
2441
- g = buildHumanGroup(entry.buf, status);
2442
- } else {
2443
- g = buildAiGroup(entry.buf, { source: blockSource, isStreaming: status === "streaming" }, deps.twin);
2444
- }
2445
- if (groupMemo.size > 2e3) groupMemo.clear();
2446
- groupMemo.set(memoKey, g);
2447
- groups.push(g);
2448
- });
2449
- for (const g of groups) {
2450
- if (g.type === "ai" && g.status === "streaming") {
2451
- const aiMessages = g.rawMessages.filter((m) => String(asSxin(m).type || "").startsWith("ai"));
2452
- const lastAi = aiMessages[aiMessages.length - 1];
2453
- g.streamingText = lastAi ? extractAiContentFromMessage(lastAi) : "";
1804
+ },
1805
+ enrichFromPage(page) {
1806
+ const enrichment = extractRunEnrichment(page.messages);
1807
+ let next = null;
1808
+ for (const [runId, patch] of enrichment) {
1809
+ const run = (next ?? runsMap.value).get(runId);
1810
+ if (!run) continue;
1811
+ next ?? (next = new Map(runsMap.value));
1812
+ next.set(runId, {
1813
+ ...run,
1814
+ ...patch.feedback !== void 0 ? { feedback: patch.feedback } : {},
1815
+ ...patch.latencyMs !== void 0 ? { latencyMs: patch.latencyMs } : {}
1816
+ });
2454
1817
  }
1818
+ if (next) runsMap.value = next;
1819
+ },
1820
+ backfillCurrentRunMetadata(getMessages) {
1821
+ const runId = currentRunId.value;
1822
+ if (!runId) return;
1823
+ const run = runsMap.value.get(runId);
1824
+ if (!run) return;
1825
+ if (run.modelName && run.finishReason) return;
1826
+ const currentRunMessages = getMessages().filter((m) => String(m?.runId || "") === runId);
1827
+ const source = currentRunMessages.length ? currentRunMessages : getMessages();
1828
+ const picked = pickRunMessageMetadata(source);
1829
+ if (!picked.modelName && !picked.finishReason) return;
1830
+ runsMap.value = new Map(runsMap.value).set(runId, {
1831
+ ...run,
1832
+ ...picked.modelName && !run.modelName ? { modelName: picked.modelName } : {},
1833
+ ...picked.finishReason && !run.finishReason ? { finishReason: picked.finishReason } : {}
1834
+ });
1835
+ },
1836
+ patchRun(runId, patch) {
1837
+ const run = runsMap.value.get(runId);
1838
+ if (!run) return;
1839
+ runsMap.value = new Map(runsMap.value).set(runId, { ...run, ...patch });
1840
+ },
1841
+ dispose() {
1842
+ runsMap.value = /* @__PURE__ */ new Map();
1843
+ currentRunId.value = null;
2455
1844
  }
2456
- const sourceGroups = groups;
2457
- const decorateSteps = [
2458
- // 第 1 步:补丁应用 + 乐观 extras 锚点落位
2459
- (gs) => applyPatchesAndExtras(gs, state, runIdFilter),
2460
- // 第 2 步:interrupt 审核块注入(去重记忆 interruptBlocks 为构建器公开职责)
2461
- (gs) => withInterruptBlock(gs, {
2462
- getInterrupt: deps.getInterrupt,
2463
- respondedIds: deps.respondedIds,
2464
- interruptBlocks
2465
- }),
2466
- // 第 3 步:澄清回答 / interrupt 响应标记装饰
2467
- (gs) => decorateAnswers(gs, enrichments.answers, deps.respondedIds),
2468
- // 第 4 步:隐藏「无可见内容」的 AI 空气泡
2469
- filterInvisibleAiGroups
2470
- ];
2471
- const merged = decorateSteps.reduce((gs, step) => step(gs), sourceGroups);
2472
- return { groups: merged, sourceGroups };
2473
- };
2474
- return {
2475
- derive,
2476
- clearCache() {
2477
- groupMemo.clear();
2478
- foldCache.pageCount = -1;
2479
- foldCache.entries = [];
2480
- interruptBlocks.clear();
2481
- }
2482
- };
2483
- }
2484
- function canMergeAtBoundary(prefixLast, streamFirst) {
2485
- if (prefixLast.type === "human" && streamFirst.type === "human") {
2486
- return getHumanMessageBaseId(String(asSxin(streamFirst.buf[0]).id || "")) === getHumanMessageBaseId(String(asSxin(prefixLast.buf[0]).id || ""));
2487
- }
2488
- if (prefixLast.type === "ai" && streamFirst.type === "ai") {
2489
- const mRunId = messageRunId(streamFirst.buf[0]);
2490
- const groupRunId = messageRunId(prefixLast.buf[0]);
2491
- return !(mRunId && groupRunId && mRunId !== groupRunId);
2492
- }
2493
- return false;
2494
- }
2495
- function createOptimisticHuman(text, options) {
2496
- const optimisticId = genMessageId();
2497
- return {
2498
- id: optimisticId,
2499
- type: "human",
2500
- status: "completed",
2501
- originMessageIds: [optimisticId],
2502
- rawMessages: [
2503
- {
2504
- id: optimisticId,
2505
- type: "human",
2506
- name: "user-input",
2507
- content: [{ type: "text", text }],
2508
- additional_kwargs: options?.kwargs
2509
- }
2510
- ],
2511
- additionalKwargs: options?.kwargs,
2512
- blocks: [],
2513
- toolIds: [],
2514
- tools: [],
2515
- createdAt: Date.now()
2516
1845
  };
2517
1846
  }
2518
1847
 
2519
- // src/runtime/derived-groups.ts
2520
- var import_vue5 = require("vue");
2521
- function createDerivedGroups(deps) {
2522
- const deriver = createGroupDeriver(deps.state);
2523
- const derived = (0, import_vue5.computed)(() => {
2524
- deps.store.version.value;
2525
- return deriver.derive({
2526
- store: deps.store,
2527
- enrichments: deps.enrichments,
2528
- getInterrupt: () => deps.valuesChannel.getInterrupt({ isLoading: deps.streamRef.value?.isLoading.value ?? false }),
2529
- respondedIds: deps.interruptState.respondedIds.value,
2530
- currentRunId: deps.runs.currentRunId.value ?? void 0,
2531
- twin: deps.twin
2532
- });
2533
- });
2534
- deps.scope.run(() => {
2535
- (0, import_vue5.watch)(
2536
- () => [deps.store.version.value, deps.runs.currentRunId.value],
2537
- () => {
2538
- deps.state.pruneExtras(derived.value.sourceGroups, deps.runs.currentRunId.value ?? void 0);
2539
- },
2540
- { flush: "sync" }
2541
- );
2542
- });
2543
- const groups = (0, import_vue5.computed)(() => derived.value.groups);
2544
- const sourceGroups = (0, import_vue5.computed)(() => derived.value.sourceGroups);
2545
- return { groups, sourceGroups };
2546
- }
2547
-
2548
1848
  // src/runtime/thread-runtime.ts
2549
1849
  function createThreadRuntime(options) {
2550
1850
  const scope = (0, import_vue6.effectScope)();
2551
- const store = createThreadStore({ threadId: options.threadId });
2552
- const enrichments = createEnrichments();
2553
1851
  const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
2554
1852
  const interruptState = createInterruptState();
2555
- const state = createViewModelState();
1853
+ const rm = createRuntimeMaterializer({
1854
+ twin: options.twin,
1855
+ // 段级 runId 兜底源(metadata 首帧权威值):流式 tuple 消息本体无 runId,
1856
+ // 段打开/回填时经此兜底——点赞/反馈按 runId 提交的依赖
1857
+ getStreamRunId: () => runs.currentRunId.value
1858
+ });
2556
1859
  const valuesChannel = createValuesChannel({
2557
1860
  onTitle: (title) => options.onTitle?.(options.threadId, title)
2558
1861
  });
2559
- let chunkBuffer = null;
1862
+ const overlay = createSemanticOverlay();
2560
1863
  const streamRef = (0, import_vue6.shallowRef)(null);
2561
1864
  const isInitializing = (0, import_vue6.ref)(false);
1865
+ const streaming = (0, import_vue6.ref)(false);
2562
1866
  const tokenUsage = (0, import_vue6.shallowRef)(null);
2563
1867
  let initialized = false;
2564
1868
  let initPromise = null;
2565
1869
  let pager = null;
2566
- const derivedGroups = createDerivedGroups({
2567
- scope,
2568
- store,
2569
- enrichments,
2570
- state,
2571
- runs,
2572
- interruptState,
2573
- valuesChannel,
2574
- streamRef,
2575
- twin: options.twin
2576
- });
2577
- const { groups, sourceGroups } = derivedGroups;
2578
1870
  const interrupt = (0, import_vue6.computed)(() => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }));
2579
1871
  const hasPendingInterrupt = (0, import_vue6.computed)(() => {
2580
1872
  const it = interrupt.value;
2581
1873
  return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
2582
1874
  });
2583
1875
  const streamError = (0, import_vue6.computed)(() => streamRef.value?.error.value ?? null);
2584
- const isGenerating = (0, import_vue6.computed)(() => store.streamStatusRef.value === "streaming");
2585
- const hasPendingClarification = (0, import_vue6.computed)(() => {
2586
- store.version.value;
2587
- const list = groups.value;
2588
- return list.some((m, i) => {
2589
- if (m.type !== "ai") return false;
2590
- const hasUnanswered = m.blocks.some(
2591
- (b) => isClarificationBlock(b) && !isClarificationAnswered(b, enrichments.answers)
2592
- );
2593
- if (!hasUnanswered) return false;
2594
- return !list.slice(i + 1).some((x) => x.type === "human");
2595
- });
2596
- });
1876
+ const isGenerating = (0, import_vue6.computed)(() => streaming.value);
2597
1877
  const beginStream = () => {
2598
- chunkBuffer?.reset();
2599
1878
  valuesChannel.beginStream();
1879
+ overlay.invalidate();
2600
1880
  runs.currentRunId.value = null;
2601
1881
  };
2602
1882
  const streamStarted = () => {
2603
- store.beginStream();
1883
+ streaming.value = true;
1884
+ };
1885
+ const streamSettled = () => {
1886
+ streaming.value = false;
2604
1887
  };
2605
1888
  const markStreamRun = (runIdRaw) => {
2606
1889
  const runId = String(runIdRaw || "").trim();
2607
1890
  if (!runId) return;
2608
1891
  runs.currentRunId.value = runId;
2609
1892
  runs.ensureRunning(runId);
2610
- chunkBuffer?.noteStreamRunId(runId);
2611
1893
  };
2612
1894
  const refreshTokenUsage = async () => {
2613
1895
  try {
@@ -2621,17 +1903,16 @@ function createThreadRuntime(options) {
2621
1903
  threadId: options.threadId,
2622
1904
  assistantId: options.assistantId,
2623
1905
  transport: options.transport,
2624
- store,
2625
- enrichments,
2626
1906
  runs,
2627
1907
  valuesChannel,
1908
+ overlay,
1909
+ rm,
2628
1910
  streamRef,
2629
- setChunkBuffer: (b) => chunkBuffer = b,
2630
- getChunkBuffer: () => chunkBuffer,
2631
1911
  setPager: (p) => pager = p,
2632
1912
  setInitialized: () => initialized = true,
2633
1913
  markStreamRun,
2634
1914
  onStreamStart: streamStarted,
1915
+ onStreamSettled: streamSettled,
2635
1916
  refreshTokenUsage
2636
1917
  },
2637
1918
  {
@@ -2639,19 +1920,30 @@ function createThreadRuntime(options) {
2639
1920
  onEnd: () => isInitializing.value = false
2640
1921
  }
2641
1922
  );
1923
+ const actions = createStreamActions({
1924
+ options,
1925
+ getHandle: () => streamRef.value,
1926
+ beginStream,
1927
+ markStreamRun,
1928
+ getInterrupt: () => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }),
1929
+ markResponded: (id) => interruptState.markResponded(id),
1930
+ getPager: () => pager,
1931
+ runs
1932
+ });
2642
1933
  return {
2643
1934
  threadId: options.threadId,
2644
1935
  lastViewedAt: Date.now(),
2645
1936
  touch() {
2646
1937
  this.lastViewedAt = Date.now();
2647
1938
  },
2648
- groups,
1939
+ view: rm.view,
1940
+ turns: rm.turns,
1941
+ activeClarification: rm.activeClarification,
2649
1942
  isGenerating,
2650
1943
  isInitializing,
2651
1944
  runs: (0, import_vue6.computed)(() => runs.runsMap.value),
2652
1945
  interrupt,
2653
1946
  hasPendingInterrupt,
2654
- hasPendingClarification,
2655
1947
  streamError,
2656
1948
  tokenUsage,
2657
1949
  hasMoreHistory: (0, import_vue6.computed)(() => pager?.hasMore.value ?? false),
@@ -2666,64 +1958,26 @@ function createThreadRuntime(options) {
2666
1958
  initPromise = null;
2667
1959
  }
2668
1960
  },
2669
- submit(text, submitOptions) {
2670
- const handle = streamRef.value;
2671
- if (!handle) return;
2672
- beginStream();
2673
- const humanMessage = { type: "human", content: [{ type: "text", text }] };
2674
- humanMessage.additional_kwargs = submitOptions?.kwargs;
2675
- handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
2676
- },
2677
- async joinStream(runId, lastEventId) {
2678
- const handle = streamRef.value;
2679
- if (!handle) return;
2680
- beginStream();
2681
- markStreamRun(runId);
2682
- await handle.joinStream(runId, lastEventId ?? "-1");
2683
- },
2684
- stop() {
2685
- void options.transport.cancelRun(options.threadId, runs.currentRunId.value).catch((e) => console.warn("[runtime] cancel run failed", e));
2686
- streamRef.value?.stop();
2687
- },
2688
- async resumeInterrupt(decisions) {
2689
- const it = valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false });
2690
- const interruptId = String(it?.id || "");
2691
- if (!it || !interruptId) throw new Error("\u5F53\u524D\u6CA1\u6709\u5F85\u54CD\u5E94\u7684\u4E2D\u65AD");
2692
- const handle = streamRef.value;
2693
- if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
2694
- interruptState.markResponded(interruptId);
2695
- beginStream();
2696
- await handle.resumeInterrupt(decisions);
2697
- },
2698
- async loadOlderMessages() {
2699
- if (!pager) return false;
2700
- return pager.loadOlder();
2701
- },
2702
- appendOptimisticGroups(gs) {
2703
- state.appendExtra(gs);
2704
- },
2705
- createOptimisticHuman(text, opts) {
2706
- return createOptimisticHuman(text, opts);
2707
- },
2708
- patchGroup(messageId, patch) {
2709
- state.patchGroup(messageId, patch, () => sourceGroups.value);
2710
- },
1961
+ submit: actions.submit,
1962
+ joinStream: actions.joinStream,
1963
+ stop: actions.stop,
1964
+ resumeInterrupt: actions.resumeInterrupt,
1965
+ loadOlderMessages: actions.loadOlderMessages,
2711
1966
  applyFeedback(messageId, feedback) {
2712
- const runId = groups.value.find((g) => g.id === messageId)?.runId;
2713
- state.patchGroup(messageId, { feedback }, () => sourceGroups.value);
1967
+ rm.decorate(messageId, { feedback });
1968
+ const runId = rm.view.value.turns.flatMap((t) => t.ai).find((seg) => seg.id === messageId)?.runId;
2714
1969
  if (runId) runs.patchRun(runId, { feedback });
2715
1970
  },
2716
- setClarificationAnswer(toolCallId, answer) {
2717
- enrichments.setAnswer(toolCallId, answer);
2718
- },
2719
- clearClarificationAnswers() {
2720
- enrichments.clearAnswers();
2721
- },
2722
- clarificationAnswers: (0, import_vue6.computed)(() => enrichments.answers),
1971
+ addOptimisticTurn: rm.addOptimisticTurn,
1972
+ updateAiBody: rm.updateAiBody,
1973
+ decorate: rm.decorate,
1974
+ finalizeTurns: rm.finalize,
1975
+ setClarificationAnswer: rm.setClarificationAnswer,
1976
+ clearClarificationAnswers: rm.clearClarificationAnswers,
1977
+ clarificationAnswers: rm.answers,
2723
1978
  dispose() {
2724
1979
  streamRef.value?.stop();
2725
- chunkBuffer?.dispose();
2726
- enrichments.dispose();
1980
+ streamRef.value?.dispose?.();
2727
1981
  runs.dispose();
2728
1982
  scope.stop();
2729
1983
  }
@@ -2735,7 +1989,7 @@ var DEFAULT_MAX_CACHED_SESSIONS = 10;
2735
1989
  var DEFAULT_MAX_CONCURRENT_STREAMS = 3;
2736
1990
 
2737
1991
  // src/runtime/thread-directory.ts
2738
- var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending"]);
1992
+ var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending", "interrupted"]);
2739
1993
  function isActiveThreadStatus(status) {
2740
1994
  return typeof status === "string" && ACTIVE_THREAD_STATUSES.has(status);
2741
1995
  }
@@ -2887,17 +2141,26 @@ var ThreadDirectory = class {
2887
2141
  }
2888
2142
  // ===== 刷新后恢复 =====
2889
2143
  /**
2890
- * 恢复 running run 的 SSE:在已加载列表里过滤活跃线程 → listRuns 确认 → init + joinStream。
2891
- * interrupted 线程不恢复(打开时经 init 恢复 interrupt 卡片)。并行确认,串行连接(并发上限内)。
2144
+ * 恢复未完成 run 的 SSE:按 thread.status(含 interrupted)筛出候选线程并行 listRuns
2145
+ * 取最新 run → init + joinStream。
2146
+ * ⚠️ DeerFlow 语义:thread.status 与 run.status 的 'interrupted' 都表示「run 未完成」
2147
+ *(_derive_thread_status:tasks 非空 → interrupted;涵盖在跑、停在半路、HITL 挂起),
2148
+ * 不等于 LangGraph 官方的「HITL 挂起」——因此 run.status 不作硬判定,最新 run 一律
2149
+ * join:在跑则继续收流;已断则 join 返回 end 帧走 onFinish 对账(runs/state/citation
2150
+ * 刷新),页面收敛到最终状态。join 为只读幂等端点,误 join 无副作用。
2151
+ * 并行确认,串行连接(并发上限内)。
2892
2152
  */
2893
2153
  async recoverRunningThreads() {
2894
- const activeThreads = this.threads.value.filter((t) => isActiveThreadStatus(t.status) && t.thread_id);
2154
+ const candidates = this.threads.value.filter((t) => t.thread_id && isActiveThreadStatus(t.status));
2895
2155
  const results = await Promise.all(
2896
- activeThreads.map(async (thread) => {
2156
+ candidates.map(async (thread) => {
2897
2157
  try {
2898
2158
  const runs = await this.transport.listRuns(thread.thread_id, 5);
2899
- const running = Array.isArray(runs) ? runs.find((r) => r.status === "running" || r.status === "pending") : void 0;
2900
- return running ? { threadId: thread.thread_id, runId: String(running.run_id) } : null;
2159
+ if (!Array.isArray(runs) || runs.length === 0) return null;
2160
+ const latest = [...runs].sort(
2161
+ (a, b) => String(b?.created_at || "").localeCompare(String(a?.created_at || ""))
2162
+ )[0];
2163
+ return latest?.run_id ? { threadId: thread.thread_id, runId: String(latest.run_id) } : null;
2901
2164
  } catch (e) {
2902
2165
  console.warn("[ThreadDirectory] check running run failed", e);
2903
2166
  return null;
@@ -2946,7 +2209,11 @@ function createChatCore(options) {
2946
2209
  const activeRuntime = (0, import_vue8.computed)(
2947
2210
  () => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
2948
2211
  );
2949
- const messages = (0, import_vue8.computed)(() => activeRuntime.value?.groups.value ?? []);
2212
+ const view = (0, import_vue8.computed)(() => activeRuntime.value?.view.value ?? { turns: [] });
2213
+ const turns = (0, import_vue8.computed)(() => view.value.turns);
2214
+ const activeClarification = (0, import_vue8.computed)(
2215
+ () => activeRuntime.value?.activeClarification.value
2216
+ );
2950
2217
  const isGenerating = (0, import_vue8.computed)(
2951
2218
  () => !!activeRuntime.value && (activeRuntime.value.isGenerating.value || activeRuntime.value.isInitializing.value)
2952
2219
  );
@@ -2954,16 +2221,25 @@ function createChatCore(options) {
2954
2221
  const runs = (0, import_vue8.computed)(
2955
2222
  () => activeRuntime.value?.runs.value ?? /* @__PURE__ */ new Map()
2956
2223
  );
2957
- const toolCalls = (0, import_vue8.computed)(() => messages.value.flatMap((g) => g.tools));
2224
+ const toolCalls = (0, import_vue8.computed)(
2225
+ () => turns.value.flatMap(
2226
+ (t) => t.ai.flatMap(
2227
+ (seg) => seg.tools.map((tool, index) => ({
2228
+ id: tool.callId,
2229
+ call: { id: tool.callId, name: tool.name, args: tool.input },
2230
+ result: tool.result ? { content: tool.result } : void 0,
2231
+ state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
2232
+ index
2233
+ }))
2234
+ )
2235
+ )
2236
+ );
2958
2237
  const clarificationAnswers = (0, import_vue8.computed)(
2959
2238
  () => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
2960
2239
  );
2961
2240
  const activeInterrupt = (0, import_vue8.computed)(() => activeRuntime.value?.interrupt.value);
2962
2241
  const hasPendingInterrupt = (0, import_vue8.computed)(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
2963
- const hasPendingClarification = (0, import_vue8.computed)(() => activeRuntime.value?.hasPendingClarification.value ?? false);
2964
- const inputDisabled = (0, import_vue8.computed)(
2965
- () => isGenerating.value || hasPendingClarification.value || hasPendingInterrupt.value
2966
- );
2242
+ const inputDisabled = (0, import_vue8.computed)(() => isGenerating.value || hasPendingInterrupt.value);
2967
2243
  const streamError = (0, import_vue8.computed)(() => activeRuntime.value?.streamError.value ?? null);
2968
2244
  const hasMoreHistory = (0, import_vue8.computed)(() => activeRuntime.value?.hasMoreHistory.value ?? false);
2969
2245
  const loadingHistory = (0, import_vue8.computed)(() => activeRuntime.value?.loadingHistory.value ?? false);
@@ -3007,8 +2283,6 @@ function createChatCore(options) {
3007
2283
  runtime.touch();
3008
2284
  if (isNew && thread) directory.prependThread(thread);
3009
2285
  await runtime.init();
3010
- const optimistic = runtime.createOptimisticHuman(trimmed, sendOptions);
3011
- runtime.appendOptimisticGroups([optimistic]);
3012
2286
  runtime.submit(trimmed, sendOptions);
3013
2287
  };
3014
2288
  const loadThread = async (threadId) => {
@@ -3021,31 +2295,19 @@ function createChatCore(options) {
3021
2295
  result.touch();
3022
2296
  await result.init();
3023
2297
  };
3024
- const regenerate = async (assistantMessageId) => {
2298
+ const regenerateTurn = async (aiSegmentId) => {
3025
2299
  if (isGenerating.value) return;
3026
- const list = messages.value;
3027
- const idx = list.findIndex((m) => m.id === assistantMessageId);
3028
- if (idx < 0) return;
3029
- let question;
3030
- let text = "";
3031
- for (const m of list.slice(0, idx).reverse()) {
3032
- if (m.type !== "human") continue;
3033
- const [t] = m.texts ?? [];
3034
- if (t) {
3035
- question = m;
3036
- text = t;
3037
- break;
3038
- }
3039
- }
3040
- if (!text) {
2300
+ const turn = turns.value.find((t) => t.ai.some((seg) => seg.id === aiSegmentId));
2301
+ const text = turn?.human.text ?? "";
2302
+ if (!turn || !text.trim()) {
3041
2303
  notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
3042
2304
  return;
3043
2305
  }
3044
- await sendMessage(text, { kwargs: { ...question?.additionalKwargs, hide_from_ui: false } });
2306
+ await sendMessage(text, { kwargs: { ...turn.human.kwargs ?? {}, hide_from_ui: false } });
3045
2307
  };
3046
2308
  return {
3047
- messages,
3048
- groupMessages: messages,
2309
+ view,
2310
+ turns,
3049
2311
  isGenerating,
3050
2312
  isLoadingThread,
3051
2313
  currentThreadId,
@@ -3056,6 +2318,7 @@ function createChatCore(options) {
3056
2318
  getRunById,
3057
2319
  getRunsByThreadId,
3058
2320
  clarificationAnswers,
2321
+ activeClarification,
3059
2322
  setClarificationAnswer: (toolCallId, answer) => activeRuntime.value?.setClarificationAnswer(toolCallId, answer),
3060
2323
  clearClarificationAnswers: () => activeRuntime.value?.clearClarificationAnswers(),
3061
2324
  sendMessage,
@@ -3064,11 +2327,12 @@ function createChatCore(options) {
3064
2327
  clearMessages: () => {
3065
2328
  currentThreadId.value = null;
3066
2329
  },
3067
- updateGroupMessage: (messageId, patch) => activeRuntime.value?.patchGroup(messageId, patch),
3068
- addOptimisticGroupMessages: (ms) => activeRuntime.value?.appendOptimisticGroups(ms),
3069
- updateGroupMessageBlocks: (messageId, blocks) => activeRuntime.value?.patchGroup(messageId, { blocks }),
3070
2330
  applyFeedback: (messageId, feedback) => activeRuntime.value?.applyFeedback(messageId, feedback),
3071
- regenerate,
2331
+ regenerateTurn,
2332
+ addOptimisticTurn: (body) => activeRuntime.value?.addOptimisticTurn(body),
2333
+ updateAiBody: (aiId, body) => activeRuntime.value?.updateAiBody(aiId, body),
2334
+ decorate: (messageId, patch) => activeRuntime.value?.decorate(messageId, patch),
2335
+ finalizeTurns: () => activeRuntime.value?.finalizeTurns(),
3072
2336
  fetchThreads: (reset, keyword) => directory.fetchThreads(reset, keyword),
3073
2337
  deleteThread: async (threadId) => {
3074
2338
  const deleted = await directory.deleteThread(threadId);
@@ -3081,8 +2345,8 @@ function createChatCore(options) {
3081
2345
  runningNotConnectedThreadIds,
3082
2346
  recoverRunningThreads: () => directory.recoverRunningThreads(),
3083
2347
  activeInterrupt,
2348
+ interrupt: activeInterrupt,
3084
2349
  hasPendingInterrupt,
3085
- hasPendingClarification,
3086
2350
  inputDisabled,
3087
2351
  streamError,
3088
2352
  hasMoreHistory,