@cqfe/sxin-chat-core 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,13 +27,13 @@ __export(vue_exports, {
27
27
  module.exports = __toCommonJS(vue_exports);
28
28
 
29
29
  // src/core/ChatCore.ts
30
- var import_vue8 = require("vue");
30
+ var import_vue6 = require("vue");
31
31
 
32
32
  // src/runtime/thread-directory.ts
33
- var import_vue7 = require("vue");
33
+ var import_vue5 = require("vue");
34
34
 
35
35
  // src/runtime/thread-runtime.ts
36
- var import_vue6 = require("vue");
36
+ var import_vue4 = require("vue");
37
37
 
38
38
  // src/runtime/history-pager.ts
39
39
  var import_vue = require("vue");
@@ -122,6 +122,137 @@ function createHistoryPager(options) {
122
122
  return { loadOlder, hasMore: (0, import_vue.computed)(() => hasMoreRef.value), loading };
123
123
  }
124
124
 
125
+ // src/parser/group-builder-helper.ts
126
+ function isAiMessage(msg) {
127
+ const t = String(asSxin(msg).type || "");
128
+ return ["ai", "AIMessage", "AIMessageChunk"].includes(t);
129
+ }
130
+ function normalizeUsage(raw) {
131
+ if (!raw || typeof raw !== "object") return void 0;
132
+ const r = raw;
133
+ const inputTokens = readAliasedNumber(r, ["input_tokens", "inputTokens", "prompt_tokens", "promptTokens"]);
134
+ const outputTokens = readAliasedNumber(r, ["output_tokens", "outputTokens", "completion_tokens", "completionTokens"]);
135
+ const totalTokens = readAliasedNumber(r, ["total_tokens", "totalTokens"]);
136
+ if ([inputTokens, outputTokens, totalTokens].every(Number.isNaN)) {
137
+ return void 0;
138
+ }
139
+ const usage = {
140
+ input_tokens: toZeroIfNaN(inputTokens),
141
+ output_tokens: toZeroIfNaN(outputTokens),
142
+ total_tokens: toZeroIfNaN(totalTokens)
143
+ };
144
+ applyUsageDetails(usage, r);
145
+ return usage;
146
+ }
147
+ function readAliasedNumber(r, aliases) {
148
+ for (const key of aliases) {
149
+ if (r[key] !== void 0 && r[key] !== null) return Number(r[key]);
150
+ }
151
+ return NaN;
152
+ }
153
+ function toZeroIfNaN(n) {
154
+ return Number.isNaN(n) ? 0 : n;
155
+ }
156
+ function applyUsageDetails(usage, r) {
157
+ const cacheRead = Number(r.input_token_details?.cache_read ?? r.input_token_details?.cacheRead);
158
+ if (!Number.isNaN(cacheRead)) {
159
+ usage.input_token_details = { cache_read: cacheRead };
160
+ }
161
+ const reasoning = Number(r.output_token_details?.reasoning ?? r.output_token_details?.reasoningTokens);
162
+ if (!Number.isNaN(reasoning)) {
163
+ usage.output_token_details = { reasoning };
164
+ }
165
+ }
166
+
167
+ // src/runtime/run-info.ts
168
+ function buildRunInfo(run, threadId) {
169
+ return {
170
+ runId: String(run?.run_id || "").trim(),
171
+ threadId: String(threadId || "").trim(),
172
+ usage: buildRunUsage(run),
173
+ latencyMs: buildRunLatencyMs(run),
174
+ finishReason: toOptionalString(run?.stop_reason ?? run?.finish_reason),
175
+ modelName: toOptionalString(run?.model_name),
176
+ status: buildRunStatus(run),
177
+ createdAt: buildRunCreatedAt(run)
178
+ };
179
+ }
180
+ function toOptionalString(value) {
181
+ return value ? String(value) : void 0;
182
+ }
183
+ function buildRunUsage(run) {
184
+ return normalizeUsage({
185
+ input_tokens: run?.total_input_tokens,
186
+ output_tokens: run?.total_output_tokens,
187
+ total_tokens: run?.total_tokens
188
+ });
189
+ }
190
+ function buildRunStatus(run) {
191
+ return run?.status ? String(run.status) : void 0;
192
+ }
193
+ function buildRunCreatedAt(run) {
194
+ return run?.created_at ? Number(new Date(run.created_at)) : void 0;
195
+ }
196
+ function buildRunMeta(run) {
197
+ const runId = String(run?.run_id || "").trim();
198
+ if (!runId) return null;
199
+ const inputMessages = run?.kwargs?.input?.messages ?? [];
200
+ const totalTokens = Number(run?.total_tokens);
201
+ const tokens = Number.isFinite(totalTokens) && totalTokens > 0 ? {
202
+ total: totalTokens,
203
+ input: Number(run?.total_input_tokens) || 0,
204
+ output: Number(run?.total_output_tokens) || 0,
205
+ ...Number.isFinite(Number(run?.llm_call_count)) ? { llmCallCount: Number(run.llm_call_count) } : {},
206
+ byCaller: {
207
+ leadAgent: Number(run?.lead_agent_tokens) || 0,
208
+ subagent: Number(run?.subagent_tokens) || 0,
209
+ middleware: Number(run?.middleware_tokens) || 0
210
+ }
211
+ } : void 0;
212
+ const createdAt = buildRunCreatedAt(run);
213
+ return {
214
+ runId,
215
+ status: String(run?.status || "").trim(),
216
+ ...createdAt !== void 0 ? { createdAt } : {},
217
+ ...Array.isArray(inputMessages) && inputMessages.length ? { inputMessages } : {},
218
+ ...tokens ? { tokens } : {},
219
+ ...run?.stop_reason !== void 0 && run?.stop_reason !== null ? { stopReason: String(run.stop_reason) } : {}
220
+ };
221
+ }
222
+ function buildRunDirectLatencyMs(run) {
223
+ const direct = Number(run?.latency_ms);
224
+ return direct || void 0;
225
+ }
226
+ function buildRunLatencyMs(run) {
227
+ const direct = buildRunDirectLatencyMs(run);
228
+ if (direct !== void 0) return direct;
229
+ const created = Date.parse(String(run?.created_at ?? ""));
230
+ const updated = Date.parse(String(run?.updated_at ?? ""));
231
+ if (Number.isNaN(created) || Number.isNaN(updated)) return void 0;
232
+ const diff = updated - created;
233
+ return diff >= 0 ? diff : void 0;
234
+ }
235
+ function pickRunMessageMetadata(messages) {
236
+ let modelName;
237
+ let finishReason;
238
+ for (const msg of messages) {
239
+ if (!isAiMessage(msg)) {
240
+ continue;
241
+ }
242
+ const responseMetadata = msg?.response_metadata || {};
243
+ if (!modelName && responseMetadata.model_name) {
244
+ modelName = String(responseMetadata.model_name);
245
+ }
246
+ if (!finishReason && responseMetadata.finish_reason) {
247
+ finishReason = String(responseMetadata.finish_reason);
248
+ }
249
+ if (modelName && finishReason) {
250
+ break;
251
+ }
252
+ }
253
+ return { modelName, finishReason };
254
+ }
255
+
125
256
  // src/parser/thread.ts
126
257
  function extractStateMessages(state) {
127
258
  if (!state || typeof state !== "object") return [];
@@ -222,7 +353,10 @@ var INJECTED_TAGS = /* @__PURE__ */ new Set([
222
353
  "attachments",
223
354
  "slash_skill_activation"
224
355
  ]);
225
- function collectVisibleText(source, nodes) {
356
+ function isInjectedElement(node) {
357
+ return INJECTED_TAGS.has(node.tagName);
358
+ }
359
+ function collectTextKeepSxin(source, nodes) {
226
360
  const parts = [];
227
361
  const walk = (list) => {
228
362
  for (const node of list) {
@@ -230,7 +364,7 @@ function collectVisibleText(source, nodes) {
230
364
  parts.push(node.value);
231
365
  } else if (node.type === "comment") {
232
366
  parts.push(`<!--${node.content}-->`);
233
- } else if (!node.closed && !INJECTED_TAGS.has(node.tagName)) {
367
+ } else if (!isInjectedElement(node)) {
234
368
  parts.push(source.slice(node.start, node.end));
235
369
  }
236
370
  }
@@ -462,12 +596,17 @@ function readMessageContentText(msg) {
462
596
  function hasKbCitationMessage(msg) {
463
597
  return readMessageContentText(msg).includes("support.kbCitation");
464
598
  }
465
- function extractTextFromMessage(msg) {
599
+ function extractAiContentFromMessage(msg) {
466
600
  const read = readMessageText(msg);
467
601
  if (!read) return "";
468
- const text = collectVisibleText(read.text, tokenizeSxin(read.text));
602
+ const text = collectTextKeepSxin(read.text, tokenizeSxin(read.text));
469
603
  return read.trim ? text.trim() : text;
470
604
  }
605
+ function isVisibleUserMessage(msg) {
606
+ if (!msg || typeof msg !== "object") return false;
607
+ if (String(msg.type || "") !== "human") return false;
608
+ return msg.additional_kwargs?.hide_from_ui !== true;
609
+ }
471
610
 
472
611
  // src/runtime/semantic-overlay.ts
473
612
  var extractKwargsPatch = (msg) => {
@@ -541,20 +680,23 @@ function applySemanticPatches(messages, patches) {
541
680
  }
542
681
 
543
682
  // src/runtime/runtime-bootstrap.ts
683
+ function patchRows(rows, patches) {
684
+ if (!patches.size || !rows.length) return rows;
685
+ return rows.map((row) => {
686
+ const id = String(row.content?.id || "").trim();
687
+ const patch = id ? patches.get(id) : void 0;
688
+ if (!patch) return row;
689
+ const patched = applySemanticPatches([row.content], patches)[0];
690
+ return patched === row.content ? row : { ...row, content: patched };
691
+ });
692
+ }
544
693
  async function bootstrapRuntime(deps) {
545
694
  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
- }
695
+ deps.overlay.applyState(fetched.threadState);
552
696
  deps.runs.fillFromRunsList(fetched.runsList ?? []);
553
697
  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());
698
+ deps.runsListMeta.value = (fetched.runsList ?? []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
699
+ deps.rowsStore.setAll(patchRows(fetched.messagesPage.messages, deps.overlay.getPatches()));
558
700
  deps.setPager(
559
701
  createHistoryPager({
560
702
  threadId: deps.threadId,
@@ -562,7 +704,7 @@ async function bootstrapRuntime(deps) {
562
704
  firstPage: fetched.messagesPage,
563
705
  onPageLoaded: (page) => {
564
706
  deps.runs.enrichFromPage(page);
565
- deps.rm.prependHistory(runMessagesToMessages(page.messages));
707
+ deps.rowsStore.prepend(page.messages);
566
708
  },
567
709
  emitChanges: () => {
568
710
  }
@@ -579,7 +721,7 @@ async function bootstrapRuntime(deps) {
579
721
  onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
580
722
  onMessageTupleEvent: () => {
581
723
  },
582
- onSnapshotMessages: (messages) => deps.rm.applySnapshot(messages),
724
+ onSnapshotMessages: (messages) => deps.applyLiveSnapshot(messages),
583
725
  onStreamStart: deps.onStreamStart,
584
726
  onStreamEnd: finalize,
585
727
  onFinish: afterFinish,
@@ -588,22 +730,32 @@ async function bootstrapRuntime(deps) {
588
730
  deps.setInitialized();
589
731
  }
590
732
  function finalizeAfterStream(deps) {
591
- deps.rm.finalize();
592
733
  deps.onStreamSettled();
593
- deps.runs.backfillCurrentRunMetadata(() => [...deps.rm.lastMessages()]);
594
- deps.rm.applySemanticPatch(extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages()));
734
+ deps.runs.backfillCurrentRunMetadata(
735
+ () => deps.valuesChannel.getStreamMessages().map((m) => ({ ...m, runId: deps.runs.currentRunId.value }))
736
+ );
737
+ const patches = extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages());
738
+ deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, patches));
595
739
  }
596
740
  async function afterStreamFinish(deps) {
597
- await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
741
+ await Promise.all([deps.runs.refreshRuns(), refreshRunsMeta(deps), deps.refreshTokenUsage()]);
598
742
  await reconcileWithPage(deps);
599
743
  await refreshSemanticLayer(deps);
600
744
  }
745
+ async function refreshRunsMeta(deps) {
746
+ try {
747
+ const list = await deps.transport.listRuns(deps.threadId, 20);
748
+ deps.runsListMeta.value = (Array.isArray(list) ? list : []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
749
+ } catch (e) {
750
+ console.warn("[runtime] runs.list \u5237\u65B0\u5931\u8D25", e);
751
+ }
752
+ }
601
753
  async function refreshSemanticLayer(deps) {
602
754
  try {
603
755
  const state = await deps.transport.fetchThreadState(deps.threadId);
604
756
  if (!state) return;
605
757
  const semantic = deps.overlay.applyState(state);
606
- deps.rm.applySemanticPatch(deps.overlay.getPatches());
758
+ deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, deps.overlay.getPatches()));
607
759
  if (semantic.patched) {
608
760
  console.debug(`[runtime] \u8BED\u4E49\u5C42\u5237\u65B0 patched=${semantic.patched} cited=${semantic.citedIds.length}`);
609
761
  }
@@ -614,8 +766,7 @@ async function refreshSemanticLayer(deps) {
614
766
  async function reconcileWithPage(deps) {
615
767
  try {
616
768
  const page = await deps.transport.fetchMessagesPage(deps.threadId);
617
- const messages = runMessagesToMessages(page.messages);
618
- if (messages.length) deps.rm.reconcileWithPage(messages);
769
+ if (page.messages.length) deps.rowsStore.mergeLatest(page.messages);
619
770
  } catch (e) {
620
771
  console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
621
772
  }
@@ -629,6 +780,20 @@ async function runRuntimeInit(deps, hooks) {
629
780
  }
630
781
  }
631
782
 
783
+ // src/parser/hitl.ts
784
+ var import_lodash = require("lodash");
785
+ function parseHitlPayload(value) {
786
+ if (!value || typeof value !== "object") return null;
787
+ const raw = value;
788
+ const requests = raw.actionRequests ?? raw.action_requests;
789
+ if (!Array.isArray(requests) || !requests.length) return null;
790
+ const configs = raw.reviewConfigs ?? raw.review_configs;
791
+ return {
792
+ actionRequests: requests,
793
+ reviewConfigs: Array.isArray(configs) ? configs : []
794
+ };
795
+ }
796
+
632
797
  // src/runtime/runtime-stream-actions.ts
633
798
  function createStreamActions(ctx) {
634
799
  return {
@@ -636,6 +801,8 @@ function createStreamActions(ctx) {
636
801
  const handle = ctx.getHandle();
637
802
  if (!handle) return;
638
803
  ctx.beginStream();
804
+ const kwargs = submitOptions?.kwargs ?? void 0;
805
+ ctx.createPendingRun(text, "message", kwargs);
639
806
  const humanMessage = { type: "human", content: [{ type: "text", text }] };
640
807
  humanMessage.additional_kwargs = submitOptions?.kwargs;
641
808
  handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
@@ -659,7 +826,14 @@ function createStreamActions(ctx) {
659
826
  if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
660
827
  ctx.markResponded(interruptId);
661
828
  ctx.beginStream();
662
- await handle.resumeInterrupt(decisions);
829
+ const payload = parseHitlPayload(it.value);
830
+ ctx.createPendingRun(payload ? "\u5DF2\u63D0\u4EA4\u5BA1\u6279\u51B3\u7B56" : "\u5DF2\u63D0\u4EA4\u56DE\u7B54", payload ? "hitl" : "clarification");
831
+ try {
832
+ await handle.resumeInterrupt(decisions);
833
+ } catch (e) {
834
+ ctx.unmarkResponded(interruptId);
835
+ throw e;
836
+ }
663
837
  },
664
838
  async loadOlderMessages() {
665
839
  if (!ctx.getPager()) return false;
@@ -668,108 +842,175 @@ function createStreamActions(ctx) {
668
842
  };
669
843
  }
670
844
 
671
- // src/runtime/runtime-materializer.ts
672
- var import_vue3 = require("vue");
673
-
674
- // src/materializer/materializer.ts
845
+ // src/runtime/rows-store.ts
675
846
  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 });
847
+ function createRowsStore() {
848
+ const rows = (0, import_vue2.shallowRef)([]);
849
+ const sortRows = (list) => [...list].sort((a, b) => a.seq - b.seq);
850
+ return {
851
+ rows,
852
+ setAll(next) {
853
+ rows.value = sortRows(next);
854
+ },
855
+ prepend(older) {
856
+ if (!older.length) return;
857
+ const seen = new Set(rows.value.map((r) => String(r.content?.id || "")));
858
+ const fresh = older.filter((r) => {
859
+ const id = String(r.content?.id || "");
860
+ if (!id || seen.has(id)) return false;
861
+ seen.add(id);
862
+ return true;
694
863
  });
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";
719
- }
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)
864
+ if (!fresh.length) return;
865
+ rows.value = sortRows([...fresh, ...rows.value]);
866
+ },
867
+ mergeLatest(latest) {
868
+ if (!latest.length) return;
869
+ const byId = new Map(rows.value.map((r) => [String(r.content?.id || ""), r]));
870
+ for (const row of latest) {
871
+ const id = String(row.content?.id || "");
872
+ if (!id) continue;
873
+ byId.set(id, row);
874
+ }
875
+ rows.value = sortRows([...byId.values()]);
876
+ }
733
877
  };
734
- applyUsageDetails(usage, r);
735
- return usage;
736
878
  }
737
- function readAliasedNumber(r, aliases) {
738
- for (const key of aliases) {
739
- if (r[key] !== void 0 && r[key] !== null) return Number(r[key]);
879
+ function extractLiveIncrement(snapshot, lastSeenIds) {
880
+ const fresh = [];
881
+ for (const msg of snapshot) {
882
+ const id = String(msg?.id || "").trim();
883
+ if (!id || lastSeenIds.has(id)) continue;
884
+ lastSeenIds.add(id);
885
+ fresh.push(msg);
740
886
  }
741
- return NaN;
887
+ return fresh;
742
888
  }
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 };
889
+
890
+ // src/assembler/run-grouping.ts
891
+ var LIVE_SEQ = Number.MAX_SAFE_INTEGER;
892
+ function rowMessageId(msg) {
893
+ return String(msg?.id || "").trim();
894
+ }
895
+ function isUserEchoRow(id) {
896
+ return id.endsWith("__user");
897
+ }
898
+ function pageRowToAsmRow(row) {
899
+ const id = rowMessageId(row.content);
900
+ if (!id) return null;
901
+ const out = {
902
+ id,
903
+ runId: String(row.runId || ""),
904
+ seq: Number.isFinite(row.seq) ? row.seq : 0,
905
+ msg: row.content
906
+ };
907
+ if (row.createdAt !== void 0) out.createdAt = row.createdAt;
908
+ if (row.feedback !== void 0 && row.feedback !== null) out.feedback = row.feedback;
909
+ return out;
910
+ }
911
+ function liveToAsmRow(msg, runId) {
912
+ const id = rowMessageId(msg);
913
+ if (!id || isUserEchoRow(id)) return null;
914
+ return { id, runId, seq: LIVE_SEQ, msg };
915
+ }
916
+ function groupRowsByRun(rows, liveMessages, activeRunId, pendingRunId) {
917
+ const byId = /* @__PURE__ */ new Map();
918
+ const buckets = /* @__PURE__ */ new Map();
919
+ for (const row of rows) {
920
+ const asm = pageRowToAsmRow(row);
921
+ if (!asm) continue;
922
+ const prev = byId.get(asm.id);
923
+ if (prev) {
924
+ if (asm.seq >= prev.seq) {
925
+ replaceInBucket(buckets, prev, asm);
926
+ byId.set(asm.id, asm);
927
+ }
928
+ continue;
929
+ }
930
+ byId.set(asm.id, asm);
931
+ pushToBucket(buckets, asm);
750
932
  }
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 };
933
+ const liveRunId = String(activeRunId || pendingRunId || "").trim();
934
+ if (liveRunId) {
935
+ for (const msg of liveMessages) {
936
+ const asm = liveToAsmRow(msg, liveRunId);
937
+ if (!asm) continue;
938
+ if (byId.has(asm.id)) continue;
939
+ pushToBucket(buckets, asm);
940
+ }
941
+ }
942
+ for (const list of buckets.values()) {
943
+ list.sort((a, b) => a.seq - b.seq);
944
+ }
945
+ return buckets;
946
+ }
947
+ function pushToBucket(buckets, row) {
948
+ const runId = String(row.runId || "").trim();
949
+ if (!runId) return;
950
+ const list = buckets.get(runId);
951
+ if (list) list.push(row);
952
+ else buckets.set(runId, [row]);
953
+ }
954
+ function replaceInBucket(buckets, prev, next) {
955
+ const list = buckets.get(prev.runId);
956
+ if (!list) return;
957
+ const idx = list.indexOf(prev);
958
+ if (idx >= 0) list[idx] = next;
959
+ if (prev.runId !== next.runId) {
960
+ const oldList = buckets.get(prev.runId);
961
+ if (oldList) {
962
+ const i = oldList.indexOf(prev);
963
+ if (i >= 0) oldList.splice(i, 1);
964
+ if (!oldList.length) buckets.delete(prev.runId);
965
+ }
966
+ pushToBucket(buckets, next);
754
967
  }
755
968
  }
756
969
 
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);
970
+ // src/parser/body-segments.ts
971
+ var SEGMENT_TAGS = /* @__PURE__ */ new Set(["sxin-list", "sxin-item"]);
972
+ function visibleTextOf(node) {
973
+ if (node.type === "text") return node.value;
974
+ if (node.type === "comment") return "";
975
+ return node.children.map(visibleTextOf).join("");
976
+ }
977
+ function toItemSegment(el, source) {
978
+ return {
979
+ type: "item",
980
+ tag: "sxin-item",
981
+ attrs: { ...el.attrs },
982
+ content: visibleTextOf(el) || void 0,
983
+ raw: source.slice(el.start, el.end)
984
+ };
985
+ }
986
+ function toListSegment(el, source) {
987
+ const children = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-item").map((c) => toItemSegment(c, source));
988
+ return { type: "list", tag: "sxin-list", attrs: { ...el.attrs }, children, raw: source.slice(el.start, el.end) };
989
+ }
990
+ function sliceBodySegments(body) {
991
+ const source = String(body ?? "");
992
+ const segments = [];
993
+ let textBuf = "";
994
+ const flushText = () => {
995
+ if (!textBuf) return;
996
+ segments.push({ type: "text", content: textBuf });
997
+ textBuf = "";
998
+ };
999
+ for (const node of tokenizeSxin(source)) {
1000
+ if (node.type === "element" && SEGMENT_TAGS.has(node.tagName)) {
1001
+ flushText();
1002
+ segments.push(node.tagName === "sxin-list" ? toListSegment(node, source) : toItemSegment(node, source));
1003
+ } else if (node.type === "comment") {
1004
+ continue;
1005
+ } else if (node.type === "text") {
1006
+ textBuf += node.value;
1007
+ } else {
1008
+ textBuf += source.slice(node.start, node.end);
770
1009
  }
771
1010
  }
772
- return String(value);
1011
+ flushText();
1012
+ if (!segments.length) segments.push({ type: "text", content: "" });
1013
+ return segments;
773
1014
  }
774
1015
 
775
1016
  // src/parser/report-artifact.ts
@@ -816,7 +1057,7 @@ function extractTitleFromArtifactPath(path, kind = "report_outline") {
816
1057
  return noExt.replace(/_大纲$/i, "").replace(/\s*大纲\s*$/i, "").trim() || "\u62A5\u544A";
817
1058
  }
818
1059
 
819
- // src/materializer/extractors.ts
1060
+ // src/parser/extractors.ts
820
1061
  function normalizeName(name) {
821
1062
  const n = String(name || "").trim().toLowerCase();
822
1063
  return n === "write_files" ? "write_file" : n;
@@ -866,877 +1107,322 @@ function extractFromToolResult(name, result, toolCallLike) {
866
1107
  return void 0;
867
1108
  }
868
1109
 
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;
1110
+ // src/parser/tool-args.ts
1111
+ function asArgsObject(args) {
1112
+ if (args && typeof args === "object" && !Array.isArray(args)) return args;
1113
+ if (typeof args === "string") {
1114
+ try {
1115
+ const parsed = JSON.parse(args);
1116
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1117
+ return parsed;
1118
+ }
1119
+ } catch {
1120
+ }
1121
+ }
1122
+ return void 0;
874
1123
  }
875
- function isHiddenHuman(msg) {
876
- return msg?.additional_kwargs?.hide_from_ui === true;
1124
+ function pickRicherArgs(prev, next) {
1125
+ const nextObj = asArgsObject(next);
1126
+ if (!nextObj) return void 0;
1127
+ const prevObj = asArgsObject(prev);
1128
+ if (!prevObj) return nextObj;
1129
+ const prevKeys = new Set(Object.keys(prevObj));
1130
+ const hasNewKey = Object.keys(nextObj).some((k) => !prevKeys.has(k));
1131
+ const longer = JSON.stringify(nextObj).length > JSON.stringify(prevObj).length;
1132
+ return hasNewKey || longer ? nextObj : void 0;
877
1133
  }
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;
1134
+
1135
+ // src/assembler/types.ts
1136
+ var BACKEND_STATUS_MAP = {
1137
+ success: "success",
1138
+ error: "error",
1139
+ interrupted: "interrupted",
1140
+ cancelled: "cancelled",
1141
+ pending: "pending",
1142
+ running: "running"
1143
+ };
1144
+
1145
+ // src/assembler/run-assembly.ts
1146
+ function emptyRunItem(runId, createdAt) {
900
1147
  return {
901
- callId: tool.callId,
902
- question,
903
- ...args.options !== void 0 ? { options: args.options } : {},
904
- ...fields?.length ? { fields } : {}
1148
+ runId,
1149
+ input: { kind: "message", text: "" },
1150
+ status: "pending",
1151
+ body: "",
1152
+ segments: [{ type: "text", content: "" }],
1153
+ tools: [],
1154
+ attachments: [],
1155
+ clarifications: [],
1156
+ rawMessages: [],
1157
+ ...createdAt !== void 0 ? { createdAt } : {}
905
1158
  };
906
1159
  }
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)
956
- };
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);
968
- };
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
- }
998
- }
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
- }
1017
- }
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;
1083
- }
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
- );
1118
- }
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;
1141
- }
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) {
1160
+ function assembleRun(runId, options) {
1161
+ const rows = options.rows;
1162
+ const twinEnabled = !!options.twin?.enabled;
1163
+ const twinToolPrefix = options.twin?.toolPrefix || "city-digital-twin-display_";
1164
+ let body = "";
1165
+ let feedback;
1166
+ const tools = [];
1167
+ const toolByCallId = /* @__PURE__ */ new Map();
1168
+ let createdAt;
1169
+ for (const row of rows) {
1170
+ const msg = row.msg;
1171
+ const type = String(msg?.type || "");
1172
+ if (createdAt === void 0 && row.createdAt !== void 0) createdAt = row.createdAt;
1173
+ if (type === "ai") {
1174
+ const text = extractAiContentFromMessage(msg);
1175
+ if (text) body = body ? `${body}
1176
+ ${text}` : text;
1177
+ registerToolCalls(msg, tools, toolByCallId);
1178
+ } else if (type === "tool") {
1179
+ applyToolMessage(msg, tools, toolByCallId);
1180
+ } else if (type === "human") {
1181
+ }
1182
+ if (row.feedback !== void 0 && row.feedback !== null) feedback = row.feedback;
1183
+ }
1184
+ const attachments = assembleAttachments(tools, twinEnabled, twinToolPrefix);
1185
+ const clarifications = extractClarifications(tools);
1186
+ const segments = options.streaming ? [{ type: "text", content: body }] : sliceBodySegments(body);
1155
1187
  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)
1188
+ runId,
1189
+ // input 由 projectRuns 层填(需要 runs.list / 窗口 human 行两级来源),这里占位
1190
+ input: { kind: "message", text: "" },
1191
+ status: "success",
1192
+ body,
1193
+ segments,
1194
+ tools,
1195
+ attachments,
1196
+ ...feedback !== void 0 ? { feedback } : {},
1197
+ clarifications,
1198
+ ...createdAt !== void 0 ? { createdAt } : {},
1199
+ rawMessages: [...rows]
1161
1200
  };
1162
1201
  }
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") {
1202
+ function extractInputFromRows(rows) {
1203
+ for (const row of rows) {
1204
+ const msg = row.msg;
1205
+ if (!isVisibleUserMessage(msg)) continue;
1206
+ const kwargs = msg?.additional_kwargs;
1207
+ return {
1208
+ text: readMessageContentText(msg).trim(),
1209
+ ...kwargs && typeof kwargs === "object" ? { kwargs: { ...kwargs } } : {}
1210
+ };
1211
+ }
1212
+ return { text: "" };
1213
+ }
1214
+ function registerToolCalls(msg, tools, byCallId) {
1215
+ const calls = Array.isArray(msg?.tool_calls) ? msg.tool_calls : msg?.additional_kwargs?.tool_calls;
1216
+ if (!Array.isArray(calls)) return;
1217
+ for (const call of calls) {
1218
+ const callId = String(call?.id || "").trim();
1219
+ if (!callId) continue;
1220
+ const input = asArgsObject(call?.args);
1221
+ const artifactMeta = call?.artifact_meta;
1222
+ const prev = byCallId.get(callId);
1223
+ if (prev) {
1224
+ const richer = pickRicherArgs(prev.input, call?.args);
1225
+ if (richer) prev.input = richer;
1226
+ if (!prev.artifactMeta && artifactMeta) prev.artifactMeta = artifactMeta;
1181
1227
  continue;
1182
- } else if (node.type === "text") {
1183
- textBuf += node.value;
1184
- } else {
1185
- textBuf += source.slice(node.start, node.end);
1186
1228
  }
1229
+ const tool = { callId, name: String(call?.name || ""), status: "running" };
1230
+ if (input !== void 0) tool.input = input;
1231
+ if (artifactMeta !== void 0) tool.artifactMeta = artifactMeta;
1232
+ tools.push(tool);
1233
+ byCallId.set(callId, tool);
1187
1234
  }
1188
- flushText();
1189
- if (!segments.length) segments.push({ type: "text", content: "" });
1190
- return segments;
1191
1235
  }
1192
-
1193
- // src/materializer/turn-machine.ts
1194
- var DEFAULT_TWIN_TOOL_PREFIX = "city-digital-twin-display_";
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;
1288
- }
1289
- };
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);
1295
- };
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);
1236
+ function applyToolMessage(msg, tools, byCallId) {
1237
+ const callId = String(msg?.tool_call_id || "").trim();
1238
+ if (!callId) return;
1239
+ const tool = byCallId.get(callId);
1240
+ if (!tool) return;
1241
+ const result = readMessageContentText(msg);
1242
+ tool.result = result;
1243
+ const extracted = extractFromToolResult(tool.name, result, { artifact_meta: tool.artifactMeta, args: tool.input });
1244
+ if (extracted) tool.extracted = extracted;
1245
+ tool.status = String(msg?.status || "") === "error" ? "error" : "finished";
1246
+ }
1247
+ function assembleAttachments(tools, twinEnabled, twinToolPrefix) {
1248
+ const byKind = /* @__PURE__ */ new Map();
1249
+ for (const tool of tools) {
1250
+ const ex = tool.extracted;
1251
+ if (ex?.kind === "report") {
1252
+ byKind.set(`report:${ex.reportKind}`, {
1253
+ kind: "report",
1254
+ reportKind: ex.reportKind,
1255
+ body: ex.body,
1256
+ outline: ex.outline,
1257
+ sourcePath: ex.sourcePath,
1258
+ title: ex.title
1313
1259
  });
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 });
1320
- }
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;
1340
- }
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];
1260
+ } else if (ex?.kind === "artifact") {
1261
+ byKind.set("artifact", { kind: "artifact", files: ex.files });
1262
+ } else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
1263
+ byKind.set("twin", { kind: "twin", payload: tool.input });
1348
1264
  }
1349
- effects.push({ type: "ai-delta", turnId: next.id, aiId: seg.id, body, streamingText: body });
1350
- rules.registerToolCalls(loc.turn, loc.ai, msg, effects);
1351
- };
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
1265
  }
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");
1376
- }
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
- }
1407
- };
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);
1266
+ return [...byKind.values()];
1267
+ }
1268
+ function extractClarifications(tools) {
1269
+ const out = [];
1270
+ for (const tool of tools) {
1271
+ if (tool.name !== "ask_clarification") continue;
1272
+ const args = asArgsObject(tool.input);
1273
+ const question = String(args?.question ?? args?.title ?? "").trim();
1274
+ if (!question) continue;
1275
+ const record = { callId: tool.callId, question };
1276
+ if (args?.options !== void 0) record.options = args.options;
1277
+ if (Array.isArray(args?.fields)) record.fields = args.fields;
1278
+ out.push(record);
1419
1279
  }
1420
- const removals = [];
1421
- for (const id of baseline.keys()) if (!nextBaseline.has(id)) removals.push(id);
1422
- return { upserts, removals, nextBaseline };
1280
+ return out;
1423
1281
  }
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 });
1433
- }
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
- }
1444
- };
1282
+ function mapBackendStatus(raw) {
1283
+ const v = String(raw || "").trim();
1284
+ return BACKEND_STATUS_MAP[v] ?? "success";
1445
1285
  }
1446
1286
 
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] };
1455
- };
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: [] };
1287
+ // src/parser/thread-info.ts
1288
+ function formatAnswerText(value) {
1289
+ if (value == null) return "";
1290
+ if (typeof value === "string") return value;
1291
+ if (typeof value === "object") {
1292
+ const values = value.values;
1293
+ if (values && typeof values === "object" && !Array.isArray(values)) {
1294
+ return Object.values(values).filter((v) => v !== void 0 && v !== null && v !== "").map(String).join("; ");
1480
1295
  }
1481
- };
1296
+ try {
1297
+ return JSON.stringify(value);
1298
+ } catch {
1299
+ return String(value);
1300
+ }
1301
+ }
1302
+ return String(value);
1482
1303
  }
1483
1304
 
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);
1505
- };
1305
+ // src/assembler/project-runs.ts
1306
+ function classifyInputKind(inputMsg) {
1307
+ const kwargs = inputMsg?.additional_kwargs;
1308
+ if (kwargs?.human_input_response && typeof kwargs.human_input_response === "object") return "clarification";
1309
+ return "message";
1310
+ }
1311
+ function inputFromRunMeta(meta) {
1312
+ const messages = meta.inputMessages ?? [];
1313
+ if (!messages.length) return null;
1314
+ const first = messages[0];
1315
+ const visible = messages.find((m) => isVisibleUserMessage(m));
1316
+ const text = visible ? readMessageContentText(visible) : "";
1317
+ const kwargs = first.additional_kwargs;
1318
+ const hasKwargs = kwargs && typeof kwargs === "object" && Object.keys(kwargs).length > 0;
1506
1319
  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);
1579
- }
1320
+ kind: classifyInputKind(first),
1321
+ text,
1322
+ ...hasKwargs ? { kwargs: { ...kwargs } } : {}
1580
1323
  };
1581
1324
  }
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);
1325
+ function normalizeRequestId(raw) {
1326
+ return String(raw ?? "").trim().replace("clarification:", "");
1327
+ }
1328
+ function projectRuns(input) {
1329
+ const buckets = groupRowsByRun(input.rows, input.liveMessages, input.activeRunId, input.pendingRun?.runId ?? null);
1330
+ const metaByRunId = new Map(input.runsList.map((m) => [String(m.runId || ""), m]));
1331
+ const orderedBuckets = [...buckets.entries()].sort(
1332
+ (a, b) => (a[1][0]?.seq ?? 0) - (b[1][0]?.seq ?? 0)
1333
+ );
1334
+ const runs = [];
1335
+ for (const [runId, rows] of orderedBuckets) {
1336
+ const meta = metaByRunId.get(runId);
1337
+ const isStreamingRun = input.streaming && input.activeRunId === runId;
1338
+ const item = assembleRun(runId, { rows, streaming: isStreamingRun, twin: input.twin });
1339
+ const fromMeta = meta ? inputFromRunMeta(meta) : void 0;
1340
+ if (fromMeta) {
1341
+ item.input = fromMeta;
1342
+ } else {
1343
+ const fromRows = extractInputFromRows(rows);
1344
+ if (fromRows.text) {
1345
+ item.input = {
1346
+ kind: classifyInputKind(fromRows.kwargs),
1347
+ text: fromRows.text,
1348
+ ...fromRows.kwargs ? { kwargs: fromRows.kwargs } : {}
1349
+ };
1607
1350
  }
1608
- interrupts = merged;
1609
1351
  }
1610
- return { ...base, __interrupt__: interrupts };
1352
+ const pendingInput = input.pendingRun;
1353
+ if (pendingInput && runId === pendingInput.runId && !item.input.text) {
1354
+ item.input = {
1355
+ kind: pendingInput.kind,
1356
+ text: pendingInput.text,
1357
+ ...pendingInput.kwargs ? { kwargs: pendingInput.kwargs } : {}
1358
+ };
1359
+ }
1360
+ if (isStreamingRun) item.status = "running";
1361
+ else if (meta) {
1362
+ item.status = mapBackendStatus(meta.status);
1363
+ if (meta.tokens) item.tokens = meta.tokens;
1364
+ if (meta.createdAt !== void 0) item.createdAt = meta.createdAt;
1365
+ if (meta.stopReason) item.stopReason = meta.stopReason;
1366
+ }
1367
+ runs.push(item);
1611
1368
  }
1612
- if (nextValues && typeof nextValues === "object") {
1613
- if (base && "__interrupt__" in base && Array.isArray(base.__interrupt__)) {
1614
- return { ...nextValues, __interrupt__: base.__interrupt__ };
1369
+ const pending = input.pendingRun;
1370
+ if (pending && !buckets.has(pending.runId)) {
1371
+ const placeholder = emptyRunItem(pending.runId, Date.now());
1372
+ placeholder.input = { kind: pending.kind, text: pending.text, ...pending.kwargs ? { kwargs: { ...pending.kwargs } } : {} };
1373
+ if (input.streaming && input.activeRunId === pending.runId) placeholder.status = "running";
1374
+ runs.push(placeholder);
1375
+ }
1376
+ const answers = input.answers;
1377
+ for (let i = 0; i < runs.length; i++) {
1378
+ const run = runs[i];
1379
+ for (const record of run.clarifications) {
1380
+ if (record.answer !== void 0) continue;
1381
+ const optimistic = answers?.get(record.callId);
1382
+ if (optimistic !== void 0) {
1383
+ record.answer = optimistic;
1384
+ continue;
1385
+ }
1386
+ for (let j = i + 1; j < runs.length; j++) {
1387
+ const laterKwargs = runs[j].input.kwargs;
1388
+ const response = laterKwargs?.human_input_response;
1389
+ if (!response || typeof response !== "object") continue;
1390
+ if (normalizeRequestId(response.request_id) !== normalizeRequestId(record.callId)) continue;
1391
+ record.answer = formatAnswerText(response.value);
1392
+ record.answerRunId = runs[j].runId;
1393
+ break;
1394
+ }
1615
1395
  }
1616
- return nextValues;
1617
1396
  }
1618
- return nextValues ?? {};
1397
+ return runs;
1619
1398
  }
1620
1399
 
1621
1400
  // src/runtime/values-projection.ts
1622
1401
  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
1402
  let latestStreamMessages = [];
1628
- const readStateMessages = () => {
1629
- const msgs = threadStateRef.value?.values?.messages;
1630
- return Array.isArray(msgs) ? [...msgs] : [];
1631
- };
1632
- const readStreamMessages = () => [...latestStreamMessages];
1403
+ let lastTitle = "";
1633
1404
  return {
1634
- applyInitialValues(next) {
1635
- valuesRef.value = { ...next ?? {} };
1636
- },
1637
- applyThreadState(state) {
1638
- threadStateRef.value = state;
1639
- },
1640
1405
  beginStream() {
1641
- firstEvent = true;
1642
- threadStateRef.value = void 0;
1643
1406
  latestStreamMessages = [];
1644
1407
  },
1645
1408
  applyValuesEvent(data) {
1646
- const reconciled = reconcileInterrupts(valuesRef.value, data, firstEvent);
1647
- firstEvent = false;
1648
- valuesRef.value = reconciled;
1649
1409
  if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
1650
- const title = String(reconciled?.title || "").trim();
1410
+ const title = String(data?.title || "").trim();
1651
1411
  if (title && title !== lastTitle) {
1652
1412
  lastTitle = title;
1653
1413
  options.onTitle?.(title);
1654
1414
  }
1655
1415
  },
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
1666
- });
1416
+ getStreamMessages() {
1417
+ return [...latestStreamMessages];
1667
1418
  }
1668
1419
  };
1669
1420
  }
1670
1421
 
1671
1422
  // src/store/runs-store.ts
1672
- var import_vue5 = require("vue");
1673
-
1674
- // src/runtime/run-info.ts
1675
- function buildRunInfo(run, threadId) {
1676
- return {
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)
1685
- };
1686
- }
1687
- function toOptionalString(value) {
1688
- return value ? String(value) : void 0;
1689
- }
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
- });
1696
- }
1697
- function buildRunStatus(run) {
1698
- return run?.status ? String(run.status) : void 0;
1699
- }
1700
- function buildRunCreatedAt(run) {
1701
- return run?.created_at ? Number(new Date(run.created_at)) : void 0;
1702
- }
1703
- function buildRunDirectLatencyMs(run) {
1704
- const direct = Number(run?.latency_ms);
1705
- return direct || void 0;
1706
- }
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;
1715
- }
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
- }
1733
- }
1734
- return { modelName, finishReason };
1735
- }
1736
-
1737
- // src/store/runs-store.ts
1423
+ var import_vue3 = require("vue");
1738
1424
  function createInterruptState() {
1739
- const respondedIds = (0, import_vue5.shallowRef)(/* @__PURE__ */ new Set());
1425
+ const respondedIds = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Set());
1740
1426
  return {
1741
1427
  respondedIds,
1742
1428
  markResponded(id) {
@@ -1753,8 +1439,8 @@ function createInterruptState() {
1753
1439
  };
1754
1440
  }
1755
1441
  function createRunsStore(options) {
1756
- const runsMap = (0, import_vue5.shallowRef)(/* @__PURE__ */ new Map());
1757
- const currentRunId = (0, import_vue5.shallowRef)(null);
1442
+ const runsMap = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Map());
1443
+ const currentRunId = (0, import_vue3.shallowRef)(null);
1758
1444
  return {
1759
1445
  runsMap,
1760
1446
  currentRunId,
@@ -1846,50 +1532,96 @@ function createRunsStore(options) {
1846
1532
  }
1847
1533
 
1848
1534
  // src/runtime/thread-runtime.ts
1535
+ var pendingSeq = 0;
1536
+ function newPendingRunId() {
1537
+ pendingSeq += 1;
1538
+ return `local-${Date.now()}-${pendingSeq}`;
1539
+ }
1849
1540
  function createThreadRuntime(options) {
1850
- const scope = (0, import_vue6.effectScope)();
1541
+ const scope = (0, import_vue4.effectScope)();
1851
1542
  const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
1852
1543
  const interruptState = createInterruptState();
1853
- const rm = createRuntimeMaterializer({
1854
- twin: options.twin,
1855
- // 段级 runId 兜底源(metadata 首帧权威值):流式 tuple 消息本体无 runId,
1856
- // 段打开/回填时经此兜底——点赞/反馈按 runId 提交的依赖
1857
- getStreamRunId: () => runs.currentRunId.value
1858
- });
1544
+ const rowsStore = createRowsStore();
1545
+ const overlay = createSemanticOverlay();
1859
1546
  const valuesChannel = createValuesChannel({
1860
1547
  onTitle: (title) => options.onTitle?.(options.threadId, title)
1861
1548
  });
1862
- const overlay = createSemanticOverlay();
1863
- const streamRef = (0, import_vue6.shallowRef)(null);
1864
- const isInitializing = (0, import_vue6.ref)(false);
1865
- const streaming = (0, import_vue6.ref)(false);
1866
- const tokenUsage = (0, import_vue6.shallowRef)(null);
1549
+ const streamRef = (0, import_vue4.shallowRef)(null);
1550
+ const isInitializing = (0, import_vue4.ref)(false);
1551
+ const streaming = (0, import_vue4.ref)(false);
1552
+ const tokenUsage = (0, import_vue4.shallowRef)(null);
1867
1553
  let initialized = false;
1868
1554
  let initPromise = null;
1869
1555
  let pager = null;
1870
- const interrupt = (0, import_vue6.computed)(() => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }));
1871
- const hasPendingInterrupt = (0, import_vue6.computed)(() => {
1556
+ const runsListMeta = (0, import_vue4.shallowRef)([]);
1557
+ const liveMessages = (0, import_vue4.shallowRef)([]);
1558
+ const lastSeenLiveIds = /* @__PURE__ */ new Set();
1559
+ const pendingRun = (0, import_vue4.shallowRef)(null);
1560
+ const answers = (0, import_vue4.shallowRef)(/* @__PURE__ */ new Map());
1561
+ const activeRunId = (0, import_vue4.computed)(() => runs.currentRunId.value);
1562
+ const runsProjection = (0, import_vue4.computed)(
1563
+ () => projectRuns({
1564
+ rows: rowsStore.rows.value,
1565
+ liveMessages: liveMessages.value,
1566
+ activeRunId: activeRunId.value,
1567
+ runsList: runsListMeta.value,
1568
+ pendingRun: pendingRun.value,
1569
+ answers: answers.value,
1570
+ twin: options.twin,
1571
+ streaming: streaming.value
1572
+ })
1573
+ );
1574
+ const interrupt = (0, import_vue4.computed)(() => streamRef.value?.interrupt.value);
1575
+ const hasPendingInterrupt = (0, import_vue4.computed)(() => {
1872
1576
  const it = interrupt.value;
1873
1577
  return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
1874
1578
  });
1875
- const streamError = (0, import_vue6.computed)(() => streamRef.value?.error.value ?? null);
1876
- const isGenerating = (0, import_vue6.computed)(() => streaming.value);
1579
+ const streamError = (0, import_vue4.computed)(() => streamRef.value?.error.value ?? null);
1580
+ const isGenerating = (0, import_vue4.computed)(() => streaming.value);
1581
+ const activeClarification = (0, import_vue4.computed)(() => {
1582
+ const list = runsProjection.value;
1583
+ for (let i = list.length - 1; i >= 0; i--) {
1584
+ const clarifications = list[i].clarifications;
1585
+ for (let c = clarifications.length - 1; c >= 0; c--) {
1586
+ if (clarifications[c].answer === void 0) return clarifications[c];
1587
+ }
1588
+ }
1589
+ return void 0;
1590
+ });
1591
+ const clarificationAnswers = (0, import_vue4.computed)(() => answers.value);
1877
1592
  const beginStream = () => {
1878
1593
  valuesChannel.beginStream();
1879
1594
  overlay.invalidate();
1880
1595
  runs.currentRunId.value = null;
1596
+ liveMessages.value = [];
1597
+ lastSeenLiveIds.clear();
1881
1598
  };
1882
1599
  const streamStarted = () => {
1883
1600
  streaming.value = true;
1884
1601
  };
1885
1602
  const streamSettled = () => {
1886
1603
  streaming.value = false;
1604
+ pendingRun.value = null;
1887
1605
  };
1888
1606
  const markStreamRun = (runIdRaw) => {
1889
1607
  const runId = String(runIdRaw || "").trim();
1890
1608
  if (!runId) return;
1891
1609
  runs.currentRunId.value = runId;
1892
1610
  runs.ensureRunning(runId);
1611
+ const pending = pendingRun.value;
1612
+ if (pending && pending.runId !== runId) {
1613
+ pendingRun.value = { ...pending, runId };
1614
+ }
1615
+ };
1616
+ const applyLiveSnapshot = (messages) => {
1617
+ if (!streaming.value) return;
1618
+ const fresh = extractLiveIncrement(messages, lastSeenLiveIds);
1619
+ const eligible = fresh.filter((m) => {
1620
+ const t = String(m?.type || "");
1621
+ return t === "ai" || t === "tool";
1622
+ });
1623
+ if (!eligible.length) return;
1624
+ liveMessages.value = [...liveMessages.value, ...eligible];
1893
1625
  };
1894
1626
  const refreshTokenUsage = async () => {
1895
1627
  try {
@@ -1904,13 +1636,15 @@ function createThreadRuntime(options) {
1904
1636
  assistantId: options.assistantId,
1905
1637
  transport: options.transport,
1906
1638
  runs,
1907
- valuesChannel,
1639
+ rowsStore,
1640
+ runsListMeta,
1908
1641
  overlay,
1909
- rm,
1642
+ valuesChannel,
1910
1643
  streamRef,
1911
1644
  setPager: (p) => pager = p,
1912
1645
  setInitialized: () => initialized = true,
1913
1646
  markStreamRun,
1647
+ applyLiveSnapshot,
1914
1648
  onStreamStart: streamStarted,
1915
1649
  onStreamSettled: streamSettled,
1916
1650
  refreshTokenUsage
@@ -1925,10 +1659,16 @@ function createThreadRuntime(options) {
1925
1659
  getHandle: () => streamRef.value,
1926
1660
  beginStream,
1927
1661
  markStreamRun,
1928
- getInterrupt: () => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }),
1662
+ getInterrupt: () => streamRef.value?.interrupt.value,
1929
1663
  markResponded: (id) => interruptState.markResponded(id),
1664
+ unmarkResponded: (id) => interruptState.unmarkResponded(id),
1930
1665
  getPager: () => pager,
1931
- runs
1666
+ runs,
1667
+ createPendingRun: (text, kind, kwargs) => {
1668
+ const pending = { runId: newPendingRunId(), text, kind, kwargs };
1669
+ pendingRun.value = pending;
1670
+ return pending.runId;
1671
+ }
1932
1672
  });
1933
1673
  return {
1934
1674
  threadId: options.threadId,
@@ -1936,18 +1676,17 @@ function createThreadRuntime(options) {
1936
1676
  touch() {
1937
1677
  this.lastViewedAt = Date.now();
1938
1678
  },
1939
- view: rm.view,
1940
- turns: rm.turns,
1941
- activeClarification: rm.activeClarification,
1679
+ runs: runsProjection,
1680
+ runsInfo: (0, import_vue4.computed)(() => runs.runsMap.value),
1681
+ activeClarification,
1942
1682
  isGenerating,
1943
1683
  isInitializing,
1944
- runs: (0, import_vue6.computed)(() => runs.runsMap.value),
1945
1684
  interrupt,
1946
1685
  hasPendingInterrupt,
1947
1686
  streamError,
1948
1687
  tokenUsage,
1949
- hasMoreHistory: (0, import_vue6.computed)(() => pager?.hasMore.value ?? false),
1950
- loadingHistory: (0, import_vue6.computed)(() => pager?.loading.value ?? false),
1688
+ hasMoreHistory: (0, import_vue4.computed)(() => pager?.hasMore.value ?? false),
1689
+ loadingHistory: (0, import_vue4.computed)(() => pager?.loading.value ?? false),
1951
1690
  async init() {
1952
1691
  if (initialized) return;
1953
1692
  if (initPromise) return initPromise;
@@ -1964,17 +1703,43 @@ function createThreadRuntime(options) {
1964
1703
  resumeInterrupt: actions.resumeInterrupt,
1965
1704
  loadOlderMessages: actions.loadOlderMessages,
1966
1705
  applyFeedback(messageId, feedback) {
1967
- rm.decorate(messageId, { feedback });
1968
- const runId = rm.view.value.turns.flatMap((t) => t.ai).find((seg) => seg.id === messageId)?.runId;
1706
+ rowsStore.mergeLatest(
1707
+ rowsStore.rows.value.map((row) => {
1708
+ const id = String(row.content?.id || "");
1709
+ return id === messageId ? { ...row, feedback } : row;
1710
+ })
1711
+ );
1712
+ const runId = runsProjection.value.find((r) => r.rawMessages.some((m) => m.id === messageId))?.runId;
1969
1713
  if (runId) runs.patchRun(runId, { feedback });
1970
1714
  },
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,
1715
+ addOptimisticTurn: (body) => {
1716
+ const runId = newPendingRunId();
1717
+ pendingRun.value = { runId, text: body, kind: "message" };
1718
+ },
1719
+ updateAiBody(aiId, body) {
1720
+ rowsStore.mergeLatest(
1721
+ rowsStore.rows.value.map((row) => {
1722
+ const id = String(row.content?.id || "");
1723
+ return id === aiId ? { ...row, content: { ...row.content, content: body } } : row;
1724
+ })
1725
+ );
1726
+ },
1727
+ decorate(messageId, patch) {
1728
+ if (patch.feedback) this.applyFeedback(messageId, patch.feedback);
1729
+ },
1730
+ finalizeTurns() {
1731
+ pendingRun.value = null;
1732
+ },
1733
+ setClarificationAnswer(toolCallId, answer) {
1734
+ const next = new Map(answers.value);
1735
+ next.set(toolCallId, answer);
1736
+ answers.value = next;
1737
+ },
1738
+ clearClarificationAnswers() {
1739
+ if (!answers.value.size) return;
1740
+ answers.value = /* @__PURE__ */ new Map();
1741
+ },
1742
+ clarificationAnswers,
1978
1743
  dispose() {
1979
1744
  streamRef.value?.stop();
1980
1745
  streamRef.value?.dispose?.();
@@ -1995,8 +1760,8 @@ function isActiveThreadStatus(status) {
1995
1760
  }
1996
1761
  var ThreadDirectory = class {
1997
1762
  constructor(options) {
1998
- this.threads = (0, import_vue7.ref)([]);
1999
- this.threadsPagination = (0, import_vue7.ref)({
1763
+ this.threads = (0, import_vue5.ref)([]);
1764
+ this.threadsPagination = (0, import_vue5.ref)({
2000
1765
  limit: 50,
2001
1766
  offset: 0,
2002
1767
  hasMore: true,
@@ -2004,9 +1769,9 @@ var ThreadDirectory = class {
2004
1769
  });
2005
1770
  this.searchKeyword = "";
2006
1771
  /** 正在运行但已超出 SSE 连接上限的 thread(仅用于 UI 提示) */
2007
- this.runningNotConnectedThreadIds = (0, import_vue7.ref)(/* @__PURE__ */ new Set());
1772
+ this.runningNotConnectedThreadIds = (0, import_vue5.ref)(/* @__PURE__ */ new Set());
2008
1773
  /** 活跃 runtime 池(shallowReactive 追踪增删,runtime 实例不被深度代理) */
2009
- this.cachedRuntimes = (0, import_vue7.shallowReactive)(/* @__PURE__ */ new Map());
1774
+ this.cachedRuntimes = (0, import_vue5.shallowReactive)(/* @__PURE__ */ new Map());
2010
1775
  this.transport = options.transport;
2011
1776
  this.assistantId = options.assistantId;
2012
1777
  this.maxCachedRuntimes = options.maxCachedRuntimes ?? DEFAULT_MAX_CACHED_SESSIONS;
@@ -2203,50 +1968,46 @@ function createChatCore(options) {
2203
1968
  notify,
2204
1969
  defaultThreadTitle: options.defaultThreadTitle
2205
1970
  });
2206
- const currentThreadId = (0, import_vue8.ref)(null);
2207
- const threads = (0, import_vue8.computed)(() => directory.threads.value);
2208
- const threadsPagination = (0, import_vue8.computed)(() => directory.threadsPagination.value);
2209
- const activeRuntime = (0, import_vue8.computed)(
1971
+ const currentThreadId = (0, import_vue6.ref)(null);
1972
+ const threads = (0, import_vue6.computed)(() => directory.threads.value);
1973
+ const threadsPagination = (0, import_vue6.computed)(() => directory.threadsPagination.value);
1974
+ const activeRuntime = (0, import_vue6.computed)(
2210
1975
  () => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
2211
1976
  );
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
- );
2217
- const isGenerating = (0, import_vue8.computed)(
2218
- () => !!activeRuntime.value && (activeRuntime.value.isGenerating.value || activeRuntime.value.isInitializing.value)
2219
- );
2220
- const isLoadingThread = (0, import_vue8.computed)(() => activeRuntime.value?.isInitializing.value ?? false);
2221
- const runs = (0, import_vue8.computed)(
2222
- () => activeRuntime.value?.runs.value ?? /* @__PURE__ */ new Map()
2223
- );
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
- )
1977
+ const runs = (0, import_vue6.computed)(() => activeRuntime.value?.runs.value ?? []);
1978
+ const runsInfo = (0, import_vue6.computed)(() => activeRuntime.value?.runsInfo.value ?? /* @__PURE__ */ new Map());
1979
+ const toolCalls = (0, import_vue6.computed)(
1980
+ () => runs.value.flatMap(
1981
+ (run) => run.tools.map((tool, index) => ({
1982
+ id: tool.callId,
1983
+ call: { id: tool.callId, name: tool.name, args: tool.input },
1984
+ result: tool.result ? { content: tool.result } : void 0,
1985
+ state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
1986
+ index
1987
+ }))
2235
1988
  )
2236
1989
  );
2237
- const clarificationAnswers = (0, import_vue8.computed)(
1990
+ const activeClarification = (0, import_vue6.computed)(() => activeRuntime.value?.activeClarification.value);
1991
+ const isGenerating = (0, import_vue6.computed)(
1992
+ () => !!activeRuntime.value && activeRuntime.value.isGenerating.value
1993
+ );
1994
+ const isLoadingThread = (0, import_vue6.computed)(() => activeRuntime.value?.isInitializing.value ?? false);
1995
+ const clarificationAnswers = (0, import_vue6.computed)(
2238
1996
  () => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
2239
1997
  );
2240
- const activeInterrupt = (0, import_vue8.computed)(() => activeRuntime.value?.interrupt.value);
2241
- const hasPendingInterrupt = (0, import_vue8.computed)(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
2242
- const inputDisabled = (0, import_vue8.computed)(() => isGenerating.value || hasPendingInterrupt.value);
2243
- const streamError = (0, import_vue8.computed)(() => activeRuntime.value?.streamError.value ?? null);
2244
- const hasMoreHistory = (0, import_vue8.computed)(() => activeRuntime.value?.hasMoreHistory.value ?? false);
2245
- const loadingHistory = (0, import_vue8.computed)(() => activeRuntime.value?.loadingHistory.value ?? false);
2246
- const tokenUsage = (0, import_vue8.computed)(() => activeRuntime.value?.tokenUsage.value ?? null);
2247
- const runningNotConnectedThreadIds = (0, import_vue8.computed)(() => directory.runningNotConnectedThreadIds.value);
2248
- const getRunById = (runId) => runId ? runs.value.get(runId) : void 0;
2249
- const getRunsByThreadId = (threadId) => threadId ? Array.from(runs.value.values()).filter((r) => r.threadId === threadId) : [];
1998
+ const activeInterrupt = (0, import_vue6.computed)(() => activeRuntime.value?.interrupt.value);
1999
+ const hasPendingInterrupt = (0, import_vue6.computed)(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
2000
+ const inputDisabled = (0, import_vue6.computed)(() => isGenerating.value || hasPendingInterrupt.value);
2001
+ const streamError = (0, import_vue6.computed)(() => activeRuntime.value?.streamError.value ?? null);
2002
+ const hasMoreHistory = (0, import_vue6.computed)(() => activeRuntime.value?.hasMoreHistory.value ?? false);
2003
+ const loadingHistory = (0, import_vue6.computed)(() => activeRuntime.value?.loadingHistory.value ?? false);
2004
+ const tokenUsage = (0, import_vue6.computed)(() => activeRuntime.value?.tokenUsage.value ?? null);
2005
+ const runningNotConnectedThreadIds = (0, import_vue6.computed)(() => directory.runningNotConnectedThreadIds.value);
2006
+ const getRunById = (runId) => {
2007
+ const info = runId ? runsInfo.value.get(runId) : void 0;
2008
+ return info;
2009
+ };
2010
+ const getRunsByThreadId = (threadId) => threadId ? Array.from(runsInfo.value.values()).filter((r) => r.threadId === threadId) : [];
2250
2011
  const ensureThreadId = async () => {
2251
2012
  if (currentThreadId.value) return { threadId: currentThreadId.value, isNew: false, thread: null };
2252
2013
  const thread = await directory.createThread({ source: "chat" });
@@ -2295,25 +2056,25 @@ function createChatCore(options) {
2295
2056
  result.touch();
2296
2057
  await result.init();
2297
2058
  };
2298
- const regenerateTurn = async (aiSegmentId) => {
2059
+ const regenerateTurn = async (runId) => {
2299
2060
  if (isGenerating.value) return;
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()) {
2061
+ const run = runs.value.find((r) => r.runId === runId);
2062
+ const text = run?.input.text ?? "";
2063
+ if (!run || !text.trim()) {
2303
2064
  notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
2304
2065
  return;
2305
2066
  }
2306
- await sendMessage(text, { kwargs: { ...turn.human.kwargs ?? {}, hide_from_ui: false } });
2067
+ await sendMessage(text, { kwargs: { ...run.input.kwargs ?? {}, hide_from_ui: false } });
2307
2068
  };
2308
2069
  return {
2309
- view,
2310
- turns,
2070
+ runs,
2071
+ turns: runs,
2311
2072
  isGenerating,
2312
2073
  isLoadingThread,
2313
2074
  currentThreadId,
2314
2075
  threads,
2315
2076
  threadsPagination,
2316
- runs,
2077
+ runsInfo,
2317
2078
  toolCalls,
2318
2079
  getRunById,
2319
2080
  getRunsByThreadId,