@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.
package/dist/index.cjs CHANGED
@@ -3,9 +3,6 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __typeError = (msg) => {
7
- throw TypeError(msg);
8
- };
9
6
  var __export = (target, all) => {
10
7
  for (var name in all)
11
8
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -19,10 +16,6 @@ var __copyProps = (to, from, except, desc) => {
19
16
  return to;
20
17
  };
21
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
23
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
24
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
25
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
26
19
 
27
20
  // src/index.ts
28
21
  var src_exports = {};
@@ -31,13 +24,13 @@ __export(src_exports, {
31
24
  DEFAULT_ASSISTANT_ID: () => DEFAULT_ASSISTANT_ID,
32
25
  DEFAULT_MAX_CACHED_SESSIONS: () => DEFAULT_MAX_CACHED_SESSIONS,
33
26
  DEFAULT_MAX_CONCURRENT_STREAMS: () => DEFAULT_MAX_CONCURRENT_STREAMS,
34
- DeerFlowBridgeAdapter: () => DeerFlowBridgeAdapter,
35
27
  INJECTED_TAGS: () => INJECTED_TAGS,
36
28
  MESSAGE_TYPE_NORMALIZE: () => MESSAGE_TYPE_NORMALIZE,
37
29
  OUTLINE_MAX_LEVEL: () => OUTLINE_MAX_LEVEL,
38
30
  ThreadDirectory: () => ThreadDirectory,
39
- V1FrameTranslator: () => V1FrameTranslator,
40
31
  applySemanticPatches: () => applySemanticPatches,
32
+ asArgsObject: () => asArgsObject,
33
+ assembleRun: () => assembleRun,
41
34
  backfillRunMessageFeedback: () => backfillRunMessageFeedback,
42
35
  buildArtifactFiles: () => buildArtifactFiles,
43
36
  buildHitlDecisions: () => buildHitlDecisions,
@@ -48,19 +41,16 @@ __export(src_exports, {
48
41
  buildReportOutlinePayload: () => buildReportOutlinePayload,
49
42
  buildRunDirectLatencyMs: () => buildRunDirectLatencyMs,
50
43
  buildRunInfo: () => buildRunInfo,
44
+ buildRunMeta: () => buildRunMeta,
51
45
  collectTextKeepSxin: () => collectTextKeepSxin,
52
46
  collectVisibleText: () => collectVisibleText,
53
47
  createChatCore: () => createChatCore,
54
48
  createEmptySubChapter: () => createEmptySubChapter,
55
- createEventHub: () => createEventHub,
56
- createFetchReaderFactory: () => createFetchReaderFactory,
57
- createMaterializer: () => createMaterializer,
58
- createMessageDiff: () => createMessageDiff,
59
49
  createMockTransport: () => createMockTransport,
60
- createRuntimeMaterializer: () => createRuntimeMaterializer,
61
50
  createSemanticOverlay: () => createSemanticOverlay,
62
51
  createThreadRuntime: () => createThreadRuntime,
63
52
  deriveToolsFromMessages: () => deriveToolsFromMessages,
53
+ emptyRunItem: () => emptyRunItem,
64
54
  ensureOutlineContentThemes: () => ensureOutlineContentThemes,
65
55
  ensureRunningRun: () => ensureRunningRun,
66
56
  extractAiContentFromMessage: () => extractAiContentFromMessage,
@@ -69,6 +59,7 @@ __export(src_exports, {
69
59
  extractCitationAnchors: () => extractCitationAnchors,
70
60
  extractCitationAnchorsFromSpec: () => extractCitationAnchorsFromSpec,
71
61
  extractFromToolResult: () => extractFromToolResult,
62
+ extractInputFromRows: () => extractInputFromRows,
72
63
  extractReportTitleFromBody: () => extractReportTitleFromBody,
73
64
  extractRunEnrichment: () => extractRunEnrichment,
74
65
  extractSemanticPatchesFromMessages: () => extractSemanticPatchesFromMessages,
@@ -77,7 +68,6 @@ __export(src_exports, {
77
68
  extractThreadInfo: () => extractThreadInfo,
78
69
  extractTitleFromArtifactPath: () => extractTitleFromArtifactPath,
79
70
  extractUserMessageTexts: () => extractUserMessageTexts,
80
- fetchAllPageMessages: () => fetchAllPageMessages,
81
71
  formatAnswerText: () => formatAnswerText,
82
72
  formatStr: () => formatStr,
83
73
  genBlockId: () => genBlockId,
@@ -85,6 +75,7 @@ __export(src_exports, {
85
75
  getAllowedDecisions: () => getAllowedDecisions,
86
76
  getHumanMessageBaseId: () => getHumanMessageBaseId,
87
77
  getToolCallArtifactMeta: () => getToolCallArtifactMeta,
78
+ groupRowsByRun: () => groupRowsByRun,
88
79
  isAiMessage: () => isAiMessage,
89
80
  isHiddenUserMessage: () => isHiddenUserMessage,
90
81
  isHumanMessage: () => isHumanMessage,
@@ -92,8 +83,10 @@ __export(src_exports, {
92
83
  isReportBodyHtml: () => isReportBodyHtml,
93
84
  isSameArgs: () => isSameArgs,
94
85
  isToolMessage: () => isToolMessage,
86
+ isUserEchoRow: () => isUserEchoRow,
95
87
  isVisibleUserMessage: () => isVisibleUserMessage,
96
88
  isWriteFileToolName: () => isWriteFileToolName,
89
+ mapBackendStatus: () => mapBackendStatus,
97
90
  mergeStateWithPageMessages: () => mergeStateWithPageMessages,
98
91
  normalizeForCompare: () => normalizeForCompare,
99
92
  normalizeMessageType: () => normalizeMessageType,
@@ -103,10 +96,12 @@ __export(src_exports, {
103
96
  parseHumanMessageId: () => parseHumanMessageId,
104
97
  parseKnowledgeItemsFromValue: () => parseKnowledgeItemsFromValue,
105
98
  parseMarkdownToOutline: () => parseMarkdownToOutline,
106
- parseSseFrames: () => parseSseFrames,
99
+ pickRicherArgs: () => pickRicherArgs,
107
100
  pickRunMessageMetadata: () => pickRunMessageMetadata,
101
+ projectRuns: () => projectRuns,
108
102
  readMessageContentText: () => readMessageContentText,
109
103
  resolveReportArtifactKind: () => resolveReportArtifactKind,
104
+ rowMessageId: () => rowMessageId,
110
105
  runMessagesToMessages: () => runMessagesToMessages,
111
106
  simpleHash: () => simpleHash,
112
107
  sliceBodySegments: () => sliceBodySegments,
@@ -892,11 +887,14 @@ function runMessagesToMessages(messages) {
892
887
  });
893
888
  }
894
889
  function stateMessagesToRunMessages(messages) {
890
+ let lastRunId = "";
895
891
  return messages.map((msg, i) => {
896
892
  const sxin = asSxin(msg);
893
+ const ownRunId = String(sxin.runId ?? sxin.additional_kwargs?.run_id ?? "").trim();
894
+ if (ownRunId) lastRunId = ownRunId;
897
895
  const createdAt = parseCreatedAt(sxin.created_at);
898
896
  return {
899
- runId: String(sxin.runId ?? sxin.additional_kwargs?.run_id ?? ""),
897
+ runId: ownRunId || lastRunId,
900
898
  seq: i + 1,
901
899
  eventType: "messages",
902
900
  ...createdAt !== void 0 ? { createdAt } : {},
@@ -1485,6 +1483,408 @@ function sliceBodySegments(body) {
1485
1483
  return segments;
1486
1484
  }
1487
1485
 
1486
+ // src/assembler/run-grouping.ts
1487
+ var LIVE_SEQ = Number.MAX_SAFE_INTEGER;
1488
+ function rowMessageId(msg) {
1489
+ return String(msg?.id || "").trim();
1490
+ }
1491
+ function isUserEchoRow(id) {
1492
+ return id.endsWith("__user");
1493
+ }
1494
+ function pageRowToAsmRow(row) {
1495
+ const id = rowMessageId(row.content);
1496
+ if (!id) return null;
1497
+ const out = {
1498
+ id,
1499
+ runId: String(row.runId || ""),
1500
+ seq: Number.isFinite(row.seq) ? row.seq : 0,
1501
+ msg: row.content
1502
+ };
1503
+ if (row.createdAt !== void 0) out.createdAt = row.createdAt;
1504
+ if (row.feedback !== void 0 && row.feedback !== null) out.feedback = row.feedback;
1505
+ return out;
1506
+ }
1507
+ function liveToAsmRow(msg, runId) {
1508
+ const id = rowMessageId(msg);
1509
+ if (!id || isUserEchoRow(id)) return null;
1510
+ return { id, runId, seq: LIVE_SEQ, msg };
1511
+ }
1512
+ function groupRowsByRun(rows, liveMessages, activeRunId, pendingRunId) {
1513
+ const byId = /* @__PURE__ */ new Map();
1514
+ const buckets = /* @__PURE__ */ new Map();
1515
+ for (const row of rows) {
1516
+ const asm = pageRowToAsmRow(row);
1517
+ if (!asm) continue;
1518
+ const prev = byId.get(asm.id);
1519
+ if (prev) {
1520
+ if (asm.seq >= prev.seq) {
1521
+ replaceInBucket(buckets, prev, asm);
1522
+ byId.set(asm.id, asm);
1523
+ }
1524
+ continue;
1525
+ }
1526
+ byId.set(asm.id, asm);
1527
+ pushToBucket(buckets, asm);
1528
+ }
1529
+ const liveRunId = String(activeRunId || pendingRunId || "").trim();
1530
+ if (liveRunId) {
1531
+ for (const msg of liveMessages) {
1532
+ const asm = liveToAsmRow(msg, liveRunId);
1533
+ if (!asm) continue;
1534
+ if (byId.has(asm.id)) continue;
1535
+ pushToBucket(buckets, asm);
1536
+ }
1537
+ }
1538
+ for (const list of buckets.values()) {
1539
+ list.sort((a, b) => a.seq - b.seq);
1540
+ }
1541
+ return buckets;
1542
+ }
1543
+ function pushToBucket(buckets, row) {
1544
+ const runId = String(row.runId || "").trim();
1545
+ if (!runId) return;
1546
+ const list = buckets.get(runId);
1547
+ if (list) list.push(row);
1548
+ else buckets.set(runId, [row]);
1549
+ }
1550
+ function replaceInBucket(buckets, prev, next) {
1551
+ const list = buckets.get(prev.runId);
1552
+ if (!list) return;
1553
+ const idx = list.indexOf(prev);
1554
+ if (idx >= 0) list[idx] = next;
1555
+ if (prev.runId !== next.runId) {
1556
+ const oldList = buckets.get(prev.runId);
1557
+ if (oldList) {
1558
+ const i = oldList.indexOf(prev);
1559
+ if (i >= 0) oldList.splice(i, 1);
1560
+ if (!oldList.length) buckets.delete(prev.runId);
1561
+ }
1562
+ pushToBucket(buckets, next);
1563
+ }
1564
+ }
1565
+
1566
+ // src/parser/extractors.ts
1567
+ function normalizeName(name) {
1568
+ const n = String(name || "").trim().toLowerCase();
1569
+ return n === "write_files" ? "write_file" : n;
1570
+ }
1571
+ function tryParseObject(result) {
1572
+ const text = String(result ?? "").trim();
1573
+ if (!text.startsWith("{")) return null;
1574
+ try {
1575
+ const parsed = JSON.parse(text);
1576
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
1577
+ return parsed;
1578
+ } catch {
1579
+ return null;
1580
+ }
1581
+ }
1582
+ function extractFromToolResult(name, result, toolCallLike) {
1583
+ const tool = normalizeName(name);
1584
+ const obj = tryParseObject(result);
1585
+ if (tool === "ask_clarification" && obj) {
1586
+ const question = obj.question ?? obj.title;
1587
+ if (typeof question !== "string" || !question.trim()) return void 0;
1588
+ const options = Array.isArray(obj.options) ? obj.options : void 0;
1589
+ return options ? { kind: "clarification", question, options } : { kind: "clarification", question };
1590
+ }
1591
+ if (tool === "write_file") {
1592
+ if (obj) {
1593
+ if (typeof obj.body === "string" && obj.body) {
1594
+ const outline = typeof obj.outline === "string" ? obj.outline : void 0;
1595
+ return outline ? { kind: "report", reportKind: "report_body", body: obj.body, outline } : { kind: "report", reportKind: "report_body", body: obj.body };
1596
+ }
1597
+ if (Array.isArray(obj.files) && obj.files.length) {
1598
+ return { kind: "artifact", files: obj.files };
1599
+ }
1600
+ }
1601
+ const reportKind = resolveReportArtifactKind(toolCallLike);
1602
+ if (reportKind) {
1603
+ const tc = toolCallLike ?? {};
1604
+ const sourcePath = String(tc?.artifact_meta?.path || tc?.args?.path || "").trim() || void 0;
1605
+ return {
1606
+ kind: "report",
1607
+ reportKind,
1608
+ sourcePath,
1609
+ title: sourcePath ? extractTitleFromArtifactPath(sourcePath, reportKind) : void 0
1610
+ };
1611
+ }
1612
+ }
1613
+ return void 0;
1614
+ }
1615
+
1616
+ // src/parser/tool-args.ts
1617
+ function asArgsObject(args) {
1618
+ if (args && typeof args === "object" && !Array.isArray(args)) return args;
1619
+ if (typeof args === "string") {
1620
+ try {
1621
+ const parsed = JSON.parse(args);
1622
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1623
+ return parsed;
1624
+ }
1625
+ } catch {
1626
+ }
1627
+ }
1628
+ return void 0;
1629
+ }
1630
+ function pickRicherArgs(prev, next) {
1631
+ const nextObj = asArgsObject(next);
1632
+ if (!nextObj) return void 0;
1633
+ const prevObj = asArgsObject(prev);
1634
+ if (!prevObj) return nextObj;
1635
+ const prevKeys = new Set(Object.keys(prevObj));
1636
+ const hasNewKey = Object.keys(nextObj).some((k) => !prevKeys.has(k));
1637
+ const longer = JSON.stringify(nextObj).length > JSON.stringify(prevObj).length;
1638
+ return hasNewKey || longer ? nextObj : void 0;
1639
+ }
1640
+
1641
+ // src/assembler/types.ts
1642
+ var BACKEND_STATUS_MAP = {
1643
+ success: "success",
1644
+ error: "error",
1645
+ interrupted: "interrupted",
1646
+ cancelled: "cancelled",
1647
+ pending: "pending",
1648
+ running: "running"
1649
+ };
1650
+
1651
+ // src/assembler/run-assembly.ts
1652
+ function emptyRunItem(runId, createdAt) {
1653
+ return {
1654
+ runId,
1655
+ input: { kind: "message", text: "" },
1656
+ status: "pending",
1657
+ body: "",
1658
+ segments: [{ type: "text", content: "" }],
1659
+ tools: [],
1660
+ attachments: [],
1661
+ clarifications: [],
1662
+ rawMessages: [],
1663
+ ...createdAt !== void 0 ? { createdAt } : {}
1664
+ };
1665
+ }
1666
+ function assembleRun(runId, options) {
1667
+ const rows = options.rows;
1668
+ const twinEnabled = !!options.twin?.enabled;
1669
+ const twinToolPrefix = options.twin?.toolPrefix || "city-digital-twin-display_";
1670
+ let body = "";
1671
+ let feedback;
1672
+ const tools = [];
1673
+ const toolByCallId = /* @__PURE__ */ new Map();
1674
+ let createdAt;
1675
+ for (const row of rows) {
1676
+ const msg = row.msg;
1677
+ const type = String(msg?.type || "");
1678
+ if (createdAt === void 0 && row.createdAt !== void 0) createdAt = row.createdAt;
1679
+ if (type === "ai") {
1680
+ const text = extractAiContentFromMessage(msg);
1681
+ if (text) body = body ? `${body}
1682
+ ${text}` : text;
1683
+ registerToolCalls(msg, tools, toolByCallId);
1684
+ } else if (type === "tool") {
1685
+ applyToolMessage(msg, tools, toolByCallId);
1686
+ } else if (type === "human") {
1687
+ }
1688
+ if (row.feedback !== void 0 && row.feedback !== null) feedback = row.feedback;
1689
+ }
1690
+ const attachments = assembleAttachments(tools, twinEnabled, twinToolPrefix);
1691
+ const clarifications = extractClarifications(tools);
1692
+ const segments = options.streaming ? [{ type: "text", content: body }] : sliceBodySegments(body);
1693
+ return {
1694
+ runId,
1695
+ // input 由 projectRuns 层填(需要 runs.list / 窗口 human 行两级来源),这里占位
1696
+ input: { kind: "message", text: "" },
1697
+ status: "success",
1698
+ body,
1699
+ segments,
1700
+ tools,
1701
+ attachments,
1702
+ ...feedback !== void 0 ? { feedback } : {},
1703
+ clarifications,
1704
+ ...createdAt !== void 0 ? { createdAt } : {},
1705
+ rawMessages: [...rows]
1706
+ };
1707
+ }
1708
+ function extractInputFromRows(rows) {
1709
+ for (const row of rows) {
1710
+ const msg = row.msg;
1711
+ if (!isVisibleUserMessage(msg)) continue;
1712
+ const kwargs = msg?.additional_kwargs;
1713
+ return {
1714
+ text: readMessageContentText(msg).trim(),
1715
+ ...kwargs && typeof kwargs === "object" ? { kwargs: { ...kwargs } } : {}
1716
+ };
1717
+ }
1718
+ return { text: "" };
1719
+ }
1720
+ function registerToolCalls(msg, tools, byCallId) {
1721
+ const calls = Array.isArray(msg?.tool_calls) ? msg.tool_calls : msg?.additional_kwargs?.tool_calls;
1722
+ if (!Array.isArray(calls)) return;
1723
+ for (const call of calls) {
1724
+ const callId = String(call?.id || "").trim();
1725
+ if (!callId) continue;
1726
+ const input = asArgsObject(call?.args);
1727
+ const artifactMeta = call?.artifact_meta;
1728
+ const prev = byCallId.get(callId);
1729
+ if (prev) {
1730
+ const richer = pickRicherArgs(prev.input, call?.args);
1731
+ if (richer) prev.input = richer;
1732
+ if (!prev.artifactMeta && artifactMeta) prev.artifactMeta = artifactMeta;
1733
+ continue;
1734
+ }
1735
+ const tool = { callId, name: String(call?.name || ""), status: "running" };
1736
+ if (input !== void 0) tool.input = input;
1737
+ if (artifactMeta !== void 0) tool.artifactMeta = artifactMeta;
1738
+ tools.push(tool);
1739
+ byCallId.set(callId, tool);
1740
+ }
1741
+ }
1742
+ function applyToolMessage(msg, tools, byCallId) {
1743
+ const callId = String(msg?.tool_call_id || "").trim();
1744
+ if (!callId) return;
1745
+ const tool = byCallId.get(callId);
1746
+ if (!tool) return;
1747
+ const result = readMessageContentText(msg);
1748
+ tool.result = result;
1749
+ const extracted = extractFromToolResult(tool.name, result, { artifact_meta: tool.artifactMeta, args: tool.input });
1750
+ if (extracted) tool.extracted = extracted;
1751
+ tool.status = String(msg?.status || "") === "error" ? "error" : "finished";
1752
+ }
1753
+ function assembleAttachments(tools, twinEnabled, twinToolPrefix) {
1754
+ const byKind = /* @__PURE__ */ new Map();
1755
+ for (const tool of tools) {
1756
+ const ex = tool.extracted;
1757
+ if (ex?.kind === "report") {
1758
+ byKind.set(`report:${ex.reportKind}`, {
1759
+ kind: "report",
1760
+ reportKind: ex.reportKind,
1761
+ body: ex.body,
1762
+ outline: ex.outline,
1763
+ sourcePath: ex.sourcePath,
1764
+ title: ex.title
1765
+ });
1766
+ } else if (ex?.kind === "artifact") {
1767
+ byKind.set("artifact", { kind: "artifact", files: ex.files });
1768
+ } else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
1769
+ byKind.set("twin", { kind: "twin", payload: tool.input });
1770
+ }
1771
+ }
1772
+ return [...byKind.values()];
1773
+ }
1774
+ function extractClarifications(tools) {
1775
+ const out = [];
1776
+ for (const tool of tools) {
1777
+ if (tool.name !== "ask_clarification") continue;
1778
+ const args = asArgsObject(tool.input);
1779
+ const question = String(args?.question ?? args?.title ?? "").trim();
1780
+ if (!question) continue;
1781
+ const record = { callId: tool.callId, question };
1782
+ if (args?.options !== void 0) record.options = args.options;
1783
+ if (Array.isArray(args?.fields)) record.fields = args.fields;
1784
+ out.push(record);
1785
+ }
1786
+ return out;
1787
+ }
1788
+ function mapBackendStatus(raw) {
1789
+ const v = String(raw || "").trim();
1790
+ return BACKEND_STATUS_MAP[v] ?? "success";
1791
+ }
1792
+
1793
+ // src/assembler/project-runs.ts
1794
+ function classifyInputKind(inputMsg) {
1795
+ const kwargs = inputMsg?.additional_kwargs;
1796
+ if (kwargs?.human_input_response && typeof kwargs.human_input_response === "object") return "clarification";
1797
+ return "message";
1798
+ }
1799
+ function inputFromRunMeta(meta) {
1800
+ const messages = meta.inputMessages ?? [];
1801
+ if (!messages.length) return null;
1802
+ const first = messages[0];
1803
+ const visible = messages.find((m) => isVisibleUserMessage(m));
1804
+ const text = visible ? readMessageContentText(visible) : "";
1805
+ const kwargs = first.additional_kwargs;
1806
+ const hasKwargs = kwargs && typeof kwargs === "object" && Object.keys(kwargs).length > 0;
1807
+ return {
1808
+ kind: classifyInputKind(first),
1809
+ text,
1810
+ ...hasKwargs ? { kwargs: { ...kwargs } } : {}
1811
+ };
1812
+ }
1813
+ function normalizeRequestId(raw) {
1814
+ return String(raw ?? "").trim().replace("clarification:", "");
1815
+ }
1816
+ function projectRuns(input) {
1817
+ const buckets = groupRowsByRun(input.rows, input.liveMessages, input.activeRunId, input.pendingRun?.runId ?? null);
1818
+ const metaByRunId = new Map(input.runsList.map((m) => [String(m.runId || ""), m]));
1819
+ const orderedBuckets = [...buckets.entries()].sort(
1820
+ (a, b) => (a[1][0]?.seq ?? 0) - (b[1][0]?.seq ?? 0)
1821
+ );
1822
+ const runs = [];
1823
+ for (const [runId, rows] of orderedBuckets) {
1824
+ const meta = metaByRunId.get(runId);
1825
+ const isStreamingRun = input.streaming && input.activeRunId === runId;
1826
+ const item = assembleRun(runId, { rows, streaming: isStreamingRun, twin: input.twin });
1827
+ const fromMeta = meta ? inputFromRunMeta(meta) : void 0;
1828
+ if (fromMeta) {
1829
+ item.input = fromMeta;
1830
+ } else {
1831
+ const fromRows = extractInputFromRows(rows);
1832
+ if (fromRows.text) {
1833
+ item.input = {
1834
+ kind: classifyInputKind(fromRows.kwargs),
1835
+ text: fromRows.text,
1836
+ ...fromRows.kwargs ? { kwargs: fromRows.kwargs } : {}
1837
+ };
1838
+ }
1839
+ }
1840
+ const pendingInput = input.pendingRun;
1841
+ if (pendingInput && runId === pendingInput.runId && !item.input.text) {
1842
+ item.input = {
1843
+ kind: pendingInput.kind,
1844
+ text: pendingInput.text,
1845
+ ...pendingInput.kwargs ? { kwargs: pendingInput.kwargs } : {}
1846
+ };
1847
+ }
1848
+ if (isStreamingRun) item.status = "running";
1849
+ else if (meta) {
1850
+ item.status = mapBackendStatus(meta.status);
1851
+ if (meta.tokens) item.tokens = meta.tokens;
1852
+ if (meta.createdAt !== void 0) item.createdAt = meta.createdAt;
1853
+ if (meta.stopReason) item.stopReason = meta.stopReason;
1854
+ }
1855
+ runs.push(item);
1856
+ }
1857
+ const pending = input.pendingRun;
1858
+ if (pending && !buckets.has(pending.runId)) {
1859
+ const placeholder = emptyRunItem(pending.runId, Date.now());
1860
+ placeholder.input = { kind: pending.kind, text: pending.text, ...pending.kwargs ? { kwargs: { ...pending.kwargs } } : {} };
1861
+ if (input.streaming && input.activeRunId === pending.runId) placeholder.status = "running";
1862
+ runs.push(placeholder);
1863
+ }
1864
+ const answers = input.answers;
1865
+ for (let i = 0; i < runs.length; i++) {
1866
+ const run = runs[i];
1867
+ for (const record of run.clarifications) {
1868
+ if (record.answer !== void 0) continue;
1869
+ const optimistic = answers?.get(record.callId);
1870
+ if (optimistic !== void 0) {
1871
+ record.answer = optimistic;
1872
+ continue;
1873
+ }
1874
+ for (let j = i + 1; j < runs.length; j++) {
1875
+ const laterKwargs = runs[j].input.kwargs;
1876
+ const response = laterKwargs?.human_input_response;
1877
+ if (!response || typeof response !== "object") continue;
1878
+ if (normalizeRequestId(response.request_id) !== normalizeRequestId(record.callId)) continue;
1879
+ record.answer = formatAnswerText(response.value);
1880
+ record.answerRunId = runs[j].runId;
1881
+ break;
1882
+ }
1883
+ }
1884
+ }
1885
+ return runs;
1886
+ }
1887
+
1488
1888
  // src/runtime/run-info.ts
1489
1889
  function buildRunInfo(run, threadId) {
1490
1890
  return {
@@ -1514,6 +1914,32 @@ function buildRunStatus(run) {
1514
1914
  function buildRunCreatedAt(run) {
1515
1915
  return run?.created_at ? Number(new Date(run.created_at)) : void 0;
1516
1916
  }
1917
+ function buildRunMeta(run) {
1918
+ const runId = String(run?.run_id || "").trim();
1919
+ if (!runId) return null;
1920
+ const inputMessages = run?.kwargs?.input?.messages ?? [];
1921
+ const totalTokens = Number(run?.total_tokens);
1922
+ const tokens = Number.isFinite(totalTokens) && totalTokens > 0 ? {
1923
+ total: totalTokens,
1924
+ input: Number(run?.total_input_tokens) || 0,
1925
+ output: Number(run?.total_output_tokens) || 0,
1926
+ ...Number.isFinite(Number(run?.llm_call_count)) ? { llmCallCount: Number(run.llm_call_count) } : {},
1927
+ byCaller: {
1928
+ leadAgent: Number(run?.lead_agent_tokens) || 0,
1929
+ subagent: Number(run?.subagent_tokens) || 0,
1930
+ middleware: Number(run?.middleware_tokens) || 0
1931
+ }
1932
+ } : void 0;
1933
+ const createdAt = buildRunCreatedAt(run);
1934
+ return {
1935
+ runId,
1936
+ status: String(run?.status || "").trim(),
1937
+ ...createdAt !== void 0 ? { createdAt } : {},
1938
+ ...Array.isArray(inputMessages) && inputMessages.length ? { inputMessages } : {},
1939
+ ...tokens ? { tokens } : {},
1940
+ ...run?.stop_reason !== void 0 && run?.stop_reason !== null ? { stopReason: String(run.stop_reason) } : {}
1941
+ };
1942
+ }
1517
1943
  function buildRunDirectLatencyMs(run) {
1518
1944
  const direct = Number(run?.latency_ms);
1519
1945
  return direct || void 0;
@@ -1620,7 +2046,7 @@ function applySemanticPatches(messages, patches) {
1620
2046
  }
1621
2047
 
1622
2048
  // src/runtime/thread-runtime.ts
1623
- var import_vue6 = require("vue");
2049
+ var import_vue4 = require("vue");
1624
2050
 
1625
2051
  // src/runtime/history-pager.ts
1626
2052
  var import_vue = require("vue");
@@ -1652,20 +2078,23 @@ function createHistoryPager(options) {
1652
2078
  }
1653
2079
 
1654
2080
  // src/runtime/runtime-bootstrap.ts
2081
+ function patchRows(rows, patches) {
2082
+ if (!patches.size || !rows.length) return rows;
2083
+ return rows.map((row) => {
2084
+ const id = String(row.content?.id || "").trim();
2085
+ const patch = id ? patches.get(id) : void 0;
2086
+ if (!patch) return row;
2087
+ const patched = applySemanticPatches([row.content], patches)[0];
2088
+ return patched === row.content ? row : { ...row, content: patched };
2089
+ });
2090
+ }
1655
2091
  async function bootstrapRuntime(deps) {
1656
2092
  const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
1657
- deps.valuesChannel.applyInitialValues(fetched.values);
1658
- deps.valuesChannel.applyThreadState(fetched.threadState);
1659
- const semantic = deps.overlay.applyState(fetched.threadState);
1660
- if (semantic.patched) {
1661
- console.debug(`[runtime] \u8BED\u4E49\u5C42\u52A0\u8F7D patched=${semantic.patched} cited=${semantic.citedIds.length}`);
1662
- }
2093
+ deps.overlay.applyState(fetched.threadState);
1663
2094
  deps.runs.fillFromRunsList(fetched.runsList ?? []);
1664
2095
  deps.runs.enrichFromPage(fetched.messagesPage);
1665
- const pageMessages = runMessagesToMessages(fetched.messagesPage.messages);
1666
- const seeded = applySemanticPatches(pageMessages, deps.overlay.getPatches());
1667
- if (seeded.length) deps.rm.hydrate(seeded);
1668
- deps.rm.applySemanticPatch(deps.overlay.getPatches());
2096
+ deps.runsListMeta.value = (fetched.runsList ?? []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
2097
+ deps.rowsStore.setAll(patchRows(fetched.messagesPage.messages, deps.overlay.getPatches()));
1669
2098
  deps.setPager(
1670
2099
  createHistoryPager({
1671
2100
  threadId: deps.threadId,
@@ -1673,7 +2102,7 @@ async function bootstrapRuntime(deps) {
1673
2102
  firstPage: fetched.messagesPage,
1674
2103
  onPageLoaded: (page) => {
1675
2104
  deps.runs.enrichFromPage(page);
1676
- deps.rm.prependHistory(runMessagesToMessages(page.messages));
2105
+ deps.rowsStore.prepend(page.messages);
1677
2106
  },
1678
2107
  emitChanges: () => {
1679
2108
  }
@@ -1690,7 +2119,7 @@ async function bootstrapRuntime(deps) {
1690
2119
  onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
1691
2120
  onMessageTupleEvent: () => {
1692
2121
  },
1693
- onSnapshotMessages: (messages) => deps.rm.applySnapshot(messages),
2122
+ onSnapshotMessages: (messages) => deps.applyLiveSnapshot(messages),
1694
2123
  onStreamStart: deps.onStreamStart,
1695
2124
  onStreamEnd: finalize,
1696
2125
  onFinish: afterFinish,
@@ -1699,22 +2128,32 @@ async function bootstrapRuntime(deps) {
1699
2128
  deps.setInitialized();
1700
2129
  }
1701
2130
  function finalizeAfterStream(deps) {
1702
- deps.rm.finalize();
1703
2131
  deps.onStreamSettled();
1704
- deps.runs.backfillCurrentRunMetadata(() => [...deps.rm.lastMessages()]);
1705
- deps.rm.applySemanticPatch(extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages()));
2132
+ deps.runs.backfillCurrentRunMetadata(
2133
+ () => deps.valuesChannel.getStreamMessages().map((m) => ({ ...m, runId: deps.runs.currentRunId.value }))
2134
+ );
2135
+ const patches = extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages());
2136
+ deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, patches));
1706
2137
  }
1707
2138
  async function afterStreamFinish(deps) {
1708
- await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
2139
+ await Promise.all([deps.runs.refreshRuns(), refreshRunsMeta(deps), deps.refreshTokenUsage()]);
1709
2140
  await reconcileWithPage(deps);
1710
2141
  await refreshSemanticLayer(deps);
1711
2142
  }
2143
+ async function refreshRunsMeta(deps) {
2144
+ try {
2145
+ const list = await deps.transport.listRuns(deps.threadId, 20);
2146
+ deps.runsListMeta.value = (Array.isArray(list) ? list : []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
2147
+ } catch (e) {
2148
+ console.warn("[runtime] runs.list \u5237\u65B0\u5931\u8D25", e);
2149
+ }
2150
+ }
1712
2151
  async function refreshSemanticLayer(deps) {
1713
2152
  try {
1714
2153
  const state = await deps.transport.fetchThreadState(deps.threadId);
1715
2154
  if (!state) return;
1716
2155
  const semantic = deps.overlay.applyState(state);
1717
- deps.rm.applySemanticPatch(deps.overlay.getPatches());
2156
+ deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, deps.overlay.getPatches()));
1718
2157
  if (semantic.patched) {
1719
2158
  console.debug(`[runtime] \u8BED\u4E49\u5C42\u5237\u65B0 patched=${semantic.patched} cited=${semantic.citedIds.length}`);
1720
2159
  }
@@ -1725,8 +2164,7 @@ async function refreshSemanticLayer(deps) {
1725
2164
  async function reconcileWithPage(deps) {
1726
2165
  try {
1727
2166
  const page = await deps.transport.fetchMessagesPage(deps.threadId);
1728
- const messages = runMessagesToMessages(page.messages);
1729
- if (messages.length) deps.rm.reconcileWithPage(messages);
2167
+ if (page.messages.length) deps.rowsStore.mergeLatest(page.messages);
1730
2168
  } catch (e) {
1731
2169
  console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
1732
2170
  }
@@ -1747,6 +2185,8 @@ function createStreamActions(ctx) {
1747
2185
  const handle = ctx.getHandle();
1748
2186
  if (!handle) return;
1749
2187
  ctx.beginStream();
2188
+ const kwargs = submitOptions?.kwargs ?? void 0;
2189
+ ctx.createPendingRun(text, "message", kwargs);
1750
2190
  const humanMessage = { type: "human", content: [{ type: "text", text }] };
1751
2191
  humanMessage.additional_kwargs = submitOptions?.kwargs;
1752
2192
  handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
@@ -1770,7 +2210,14 @@ function createStreamActions(ctx) {
1770
2210
  if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
1771
2211
  ctx.markResponded(interruptId);
1772
2212
  ctx.beginStream();
1773
- await handle.resumeInterrupt(decisions);
2213
+ const payload = parseHitlPayload(it.value);
2214
+ ctx.createPendingRun(payload ? "\u5DF2\u63D0\u4EA4\u5BA1\u6279\u51B3\u7B56" : "\u5DF2\u63D0\u4EA4\u56DE\u7B54", payload ? "hitl" : "clarification");
2215
+ try {
2216
+ await handle.resumeInterrupt(decisions);
2217
+ } catch (e) {
2218
+ ctx.unmarkResponded(interruptId);
2219
+ throw e;
2220
+ }
1774
2221
  },
1775
2222
  async loadOlderMessages() {
1776
2223
  if (!ctx.getPager()) return false;
@@ -1779,873 +2226,105 @@ function createStreamActions(ctx) {
1779
2226
  };
1780
2227
  }
1781
2228
 
1782
- // src/runtime/runtime-materializer.ts
1783
- var import_vue3 = require("vue");
1784
-
1785
- // src/materializer/materializer.ts
2229
+ // src/runtime/rows-store.ts
1786
2230
  var import_vue2 = require("vue");
1787
-
1788
- // src/materializer/indexes.ts
1789
- function createIndexes() {
1790
- return { byMessageId: /* @__PURE__ */ new Map(), byToolCallId: /* @__PURE__ */ new Map(), byRunId: /* @__PURE__ */ new Map() };
1791
- }
1792
- function rebuildIndexes(turns) {
1793
- const idx = createIndexes();
1794
- turns.forEach((turn, ti) => {
1795
- idx.byMessageId.set(turn.id, { turn: ti, ai: null });
1796
- idx.byRunId.set(turn.runId, { turn: ti, ai: 0 });
1797
- turn.ai.forEach((seg, ai_i) => {
1798
- idx.byMessageId.set(seg.id, { turn: ti, ai: ai_i });
1799
- for (const mid of seg.messageIds ?? []) {
1800
- if (mid) idx.byMessageId.set(mid, { turn: ti, ai: ai_i });
1801
- }
1802
- idx.byRunId.set(seg.runId, { turn: ti, ai: ai_i });
1803
- seg.tools.forEach((tool, tool_i) => {
1804
- idx.byToolCallId.set(tool.callId, { turn: ti, ai: ai_i, tool: tool_i });
2231
+ function createRowsStore() {
2232
+ const rows = (0, import_vue2.shallowRef)([]);
2233
+ const sortRows = (list) => [...list].sort((a, b) => a.seq - b.seq);
2234
+ return {
2235
+ rows,
2236
+ setAll(next) {
2237
+ rows.value = sortRows(next);
2238
+ },
2239
+ prepend(older) {
2240
+ if (!older.length) return;
2241
+ const seen = new Set(rows.value.map((r) => String(r.content?.id || "")));
2242
+ const fresh = older.filter((r) => {
2243
+ const id = String(r.content?.id || "");
2244
+ if (!id || seen.has(id)) return false;
2245
+ seen.add(id);
2246
+ return true;
1805
2247
  });
1806
- });
1807
- });
1808
- return idx;
1809
- }
1810
-
1811
- // src/materializer/extractors.ts
1812
- function normalizeName(name) {
1813
- const n = String(name || "").trim().toLowerCase();
1814
- return n === "write_files" ? "write_file" : n;
1815
- }
1816
- function tryParseObject(result) {
1817
- const text = String(result ?? "").trim();
1818
- if (!text.startsWith("{")) return null;
1819
- try {
1820
- const parsed = JSON.parse(text);
1821
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
1822
- return parsed;
1823
- } catch {
1824
- return null;
1825
- }
1826
- }
1827
- function extractFromToolResult(name, result, toolCallLike) {
1828
- const tool = normalizeName(name);
1829
- const obj = tryParseObject(result);
1830
- if (tool === "ask_clarification" && obj) {
1831
- const question = obj.question ?? obj.title;
1832
- if (typeof question !== "string" || !question.trim()) return void 0;
1833
- const options = Array.isArray(obj.options) ? obj.options : void 0;
1834
- return options ? { kind: "clarification", question, options } : { kind: "clarification", question };
1835
- }
1836
- if (tool === "write_file") {
1837
- if (obj) {
1838
- if (typeof obj.body === "string" && obj.body) {
1839
- const outline = typeof obj.outline === "string" ? obj.outline : void 0;
1840
- return outline ? { kind: "report", reportKind: "report_body", body: obj.body, outline } : { kind: "report", reportKind: "report_body", body: obj.body };
1841
- }
1842
- if (Array.isArray(obj.files) && obj.files.length) {
1843
- return { kind: "artifact", files: obj.files };
2248
+ if (!fresh.length) return;
2249
+ rows.value = sortRows([...fresh, ...rows.value]);
2250
+ },
2251
+ mergeLatest(latest) {
2252
+ if (!latest.length) return;
2253
+ const byId = new Map(rows.value.map((r) => [String(r.content?.id || ""), r]));
2254
+ for (const row of latest) {
2255
+ const id = String(row.content?.id || "");
2256
+ if (!id) continue;
2257
+ byId.set(id, row);
1844
2258
  }
2259
+ rows.value = sortRows([...byId.values()]);
1845
2260
  }
1846
- const reportKind = resolveReportArtifactKind(toolCallLike);
1847
- if (reportKind) {
1848
- const tc = toolCallLike ?? {};
1849
- const sourcePath = String(tc?.artifact_meta?.path || tc?.args?.path || "").trim() || void 0;
1850
- return {
1851
- kind: "report",
1852
- reportKind,
1853
- sourcePath,
1854
- title: sourcePath ? extractTitleFromArtifactPath(sourcePath, reportKind) : void 0
1855
- };
1856
- }
2261
+ };
2262
+ }
2263
+ function extractLiveIncrement(snapshot, lastSeenIds) {
2264
+ const fresh = [];
2265
+ for (const msg of snapshot) {
2266
+ const id = String(msg?.id || "").trim();
2267
+ if (!id || lastSeenIds.has(id)) continue;
2268
+ lastSeenIds.add(id);
2269
+ fresh.push(msg);
1857
2270
  }
1858
- return void 0;
2271
+ return fresh;
1859
2272
  }
1860
2273
 
1861
- // src/materializer/turn-machine-rules.ts
1862
- function messageRunId(msg) {
1863
- const own = String(asSxin(msg).runId || "").trim();
1864
- if (own) return own;
1865
- return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
1866
- }
1867
- function isHiddenHuman(msg) {
1868
- return msg?.additional_kwargs?.hide_from_ui === true;
1869
- }
1870
- function hasEmptyKwargs(msg) {
1871
- const kwargs = msg?.additional_kwargs;
1872
- return !kwargs || typeof kwargs !== "object" || Object.keys(kwargs).length === 0;
1873
- }
1874
- function resolveHumanKwargsMerge(prevKwargs, incomingKwargs, incomingIsVariant) {
1875
- if (incomingIsVariant) return prevKwargs;
1876
- const prevEmpty = !prevKwargs || typeof prevKwargs !== "object" || Object.keys(prevKwargs).length === 0;
1877
- return prevEmpty ? incomingKwargs : prevKwargs;
1878
- }
1879
- function readHir(msg) {
1880
- const response = msg?.additional_kwargs?.human_input_response;
1881
- if (!response || typeof response !== "object") return null;
1882
- const requestId = String(response.request_id || "").trim().replace("clarification:", "");
1883
- if (!requestId || response.value === void 0) return null;
1884
- return { requestId, value: response.value };
1885
- }
1886
- function buildClarification(tool) {
1887
- if (tool.name !== "ask_clarification") return null;
1888
- const args = tool.input ?? {};
1889
- const question = typeof args.question === "string" ? args.question : "";
1890
- if (!question) return null;
1891
- const fields = Array.isArray(args.fields) ? args.fields : void 0;
2274
+ // src/runtime/values-projection.ts
2275
+ function createValuesChannel(options = {}) {
2276
+ let latestStreamMessages = [];
2277
+ let lastTitle = "";
1892
2278
  return {
1893
- callId: tool.callId,
1894
- question,
1895
- ...args.options !== void 0 ? { options: args.options } : {},
1896
- ...fields?.length ? { fields } : {}
1897
- };
1898
- }
1899
- function createTurnRules(ctx) {
1900
- const { state } = ctx;
1901
- const registerToolCalls = (ti, ai_i, msg, effects) => {
1902
- const toolCalls = msg?.tool_calls;
1903
- if (!Array.isArray(toolCalls) || !toolCalls.length) return;
1904
- let turn = state.turns[ti];
1905
- for (const tc of toolCalls) {
1906
- const callId = String(tc?.id || "").trim();
1907
- if (!callId || ctx.indexes().byToolCallId.has(callId)) continue;
1908
- const tool = {
1909
- callId,
1910
- name: String(tc?.name || ""),
1911
- input: tc?.args,
1912
- artifactMeta: tc?.artifact_meta,
1913
- status: "running"
1914
- };
1915
- turn = ctx.cloneWith(turn, ai_i, (t) => {
1916
- t.ai[ai_i].tools = [...turn.ai[ai_i].tools, tool];
1917
- });
1918
- const tool_i = turn.ai[ai_i].tools.length - 1;
1919
- ctx.indexes().byToolCallId.set(callId, { turn: ti, ai: ai_i, tool: tool_i });
1920
- effects.push({ type: "tool-updated", turnId: turn.id, aiId: turn.ai[ai_i].id, tool });
1921
- const clarification = buildClarification(tool);
1922
- if (clarification) {
1923
- turn = ctx.cloneWith(turn, null, (t) => {
1924
- t.clarifications = [...turn.clarifications, clarification];
1925
- });
2279
+ beginStream() {
2280
+ latestStreamMessages = [];
2281
+ },
2282
+ applyValuesEvent(data) {
2283
+ if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
2284
+ const title = String(data?.title || "").trim();
2285
+ if (title && title !== lastTitle) {
2286
+ lastTitle = title;
2287
+ options.onTitle?.(title);
1926
2288
  }
2289
+ },
2290
+ getStreamMessages() {
2291
+ return [...latestStreamMessages];
1927
2292
  }
1928
- state.turns[ti] = turn;
1929
2293
  };
1930
- const openNewAi = (ti, msg, effects) => {
1931
- let turn = state.turns[ti];
1932
- if (state.openAi !== null) {
1933
- turn = ctx.sealAiSegment(turn, state.openAi, effects);
2294
+ }
2295
+
2296
+ // src/store/runs-store.ts
2297
+ var import_vue3 = require("vue");
2298
+ function createInterruptState() {
2299
+ const respondedIds = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Set());
2300
+ return {
2301
+ respondedIds,
2302
+ markResponded(id) {
2303
+ const next = new Set(respondedIds.value);
2304
+ next.add(id);
2305
+ respondedIds.value = next;
2306
+ },
2307
+ unmarkResponded(id) {
2308
+ if (!respondedIds.value.has(id)) return;
2309
+ const next = new Set(respondedIds.value);
2310
+ next.delete(id);
2311
+ respondedIds.value = next;
1934
2312
  }
1935
- const runId = messageRunId(msg) || ctx.streamRunId() || "";
1936
- const body = readMessageContentText(msg);
1937
- const seg = {
1938
- id: String(msg?.id || ""),
1939
- runId,
1940
- body,
1941
- streamingText: body,
1942
- tools: [],
1943
- attachments: [],
1944
- segments: [{ type: "text", content: body }],
1945
- status: "streaming",
1946
- // 段内消息 id 登记(rebuildIndexes 重建 byMessageId 的依据,防 finalize 后 update 索引 miss)
1947
- messageIds: [String(msg?.id || "")].filter(Boolean)
1948
- };
1949
- turn = ctx.cloneWith(turn, null, (t) => {
1950
- t.ai = [...turn.ai, seg];
1951
- if (!t.runId && runId) t.runId = runId;
1952
- t.rawMessages = [...t.rawMessages ?? [], msg];
1953
- });
1954
- state.turns[ti] = turn;
1955
- state.openAi = turn.ai.length - 1;
1956
- ctx.indexes().byRunId.set(runId, { turn: ti, ai: state.openAi });
1957
- if (seg.id) ctx.indexes().byMessageId.set(seg.id, { turn: ti, ai: state.openAi });
1958
- effects.push({ type: "ai-opened", turnId: turn.id, ai: turn.ai[turn.ai.length - 1] });
1959
- registerToolCalls(ti, state.openAi, msg, effects);
1960
2313
  };
1961
- const appendHuman = (msg, allowOptimistic, effects) => {
1962
- const id = String(msg?.id || "").trim();
1963
- const baseId = getHumanMessageBaseId(id) || id;
1964
- const msgRunId = String(msg?.additional_kwargs?.run_id || "").trim();
1965
- if (msgRunId) {
1966
- for (let ti = state.turns.length - 1; ti >= 0; ti--) {
1967
- const t = state.turns[ti];
1968
- const tBase = getHumanMessageBaseId(t.human.id) || t.human.id;
1969
- const tRun = String(t.human.kwargs?.run_id || "").trim();
1970
- if (tBase === baseId && tRun && tRun === msgRunId) {
1971
- const mergedKwargs = resolveHumanKwargsMerge(
1972
- t.human.kwargs,
1973
- msg?.additional_kwargs,
1974
- baseId !== id
1975
- );
1976
- const next = ctx.cloneWith(t, null, (t2) => {
1977
- t2.human = {
1978
- id: t.human.id || id,
1979
- text: t.human.text || extractTextFromMessage(msg),
1980
- kwargs: mergedKwargs
1981
- };
1982
- t2.rawMessages = [...t2.rawMessages ?? [], msg];
1983
- });
1984
- state.turns[ti] = next;
1985
- if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
1986
- effects.push({ type: "message-updated", turnId: next.id, aiId: null });
1987
- return;
1988
- }
1989
- }
1990
- }
1991
- if (state.openTurn !== null && !state.turns[state.openTurn].ai.length) {
1992
- const openHumanBase = getHumanMessageBaseId(state.turns[state.openTurn].human.id);
1993
- if (openHumanBase && openHumanBase === baseId) {
1994
- const ti = state.openTurn;
1995
- const mergedKwargs = resolveHumanKwargsMerge(
1996
- state.turns[ti].human.kwargs,
1997
- msg?.additional_kwargs,
1998
- baseId !== id
1999
- );
2000
- const next = ctx.cloneWith(state.turns[ti], null, (t) => {
2001
- t.human = { id, text: extractTextFromMessage(msg), kwargs: mergedKwargs };
2002
- t.rawMessages = [...t.rawMessages ?? [], msg];
2003
- });
2004
- state.turns[ti] = next;
2005
- ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
2006
- effects.push({ type: "message-updated", turnId: next.id, aiId: null });
2007
- return;
2008
- }
2009
- }
2010
- const optimistic = allowOptimistic && !!id && !ctx.indexes().byMessageId.has(id) && !messageRunId(msg) && hasEmptyKwargs(msg);
2011
- ctx.sealOpenTurn(effects);
2012
- const turn = {
2013
- id: id || `turn-${state.turns.length}`,
2014
- runId: "",
2015
- createdAt: Number(new Date(msg?.created_at || Date.now())) || Date.now(),
2016
- human: { id, text: extractTextFromMessage(msg), kwargs: msg?.additional_kwargs },
2017
- ai: [],
2018
- clarifications: [],
2019
- status: "streaming",
2020
- optimistic,
2021
- // 原始消息入档(排查用)
2022
- rawMessages: [msg]
2023
- };
2024
- state.turns.push(turn);
2025
- state.openTurn = state.turns.length - 1;
2026
- if (id) ctx.indexes().byMessageId.set(id, { turn: state.openTurn, ai: null });
2027
- if (optimistic) state.optimisticTurnId = turn.id;
2028
- effects.push({ type: "turn-opened", turn, optimistic });
2029
- };
2030
- const appendHiddenHuman = (msg, effects) => {
2031
- const hir = readHir(msg);
2032
- if (!hir) return;
2033
- const toolLoc = ctx.indexes().byToolCallId.get(hir.requestId);
2034
- const ti = toolLoc?.turn ?? state.openTurn ?? state.turns.length - 1;
2035
- if (ti < 0) return;
2036
- const turn = state.turns[ti];
2037
- const ci = turn.clarifications.findIndex((c) => c.callId === hir.requestId);
2038
- if (ci < 0) return;
2039
- const answer = formatAnswerText(hir.value);
2040
- const id = String(msg?.id || "").trim();
2041
- const next = ctx.cloneWith(turn, null, (t) => {
2042
- t.clarifications[ci] = { ...t.clarifications[ci], answer, answerMessageId: id || void 0 };
2043
- t.rawMessages = [...t.rawMessages ?? [], msg];
2044
- });
2045
- state.turns[ti] = next;
2046
- if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
2047
- effects.push({ type: "clarification-answered", turnId: next.id, callId: hir.requestId, answer });
2048
- };
2049
- const applyToolMessage = (msg, effects) => {
2050
- const m = msg;
2051
- const callId = String(m?.tool_call_id || "").trim();
2052
- if (!callId) return;
2053
- const result = readMessageContentText(m);
2054
- const status = m?.status === "error" ? "error" : "finished";
2055
- const id = String(m?.id || "").trim();
2056
- const loc = ctx.indexes().byToolCallId.get(callId);
2057
- if (loc) {
2058
- const turn2 = state.turns[loc.turn];
2059
- const old = turn2.ai[loc.ai].tools[loc.tool];
2060
- const tool = {
2061
- ...old,
2062
- status,
2063
- result,
2064
- extracted: extractFromToolResult(old.name, result, { artifact_meta: old.artifactMeta, args: old.input }) ?? old.extracted
2065
- };
2066
- const next2 = ctx.cloneWith(turn2, loc.ai, (t) => {
2067
- t.ai[loc.ai].tools[loc.tool] = tool;
2068
- if (t.ai[loc.ai].status === "sealed") t.ai[loc.ai].attachments = ctx.assembleAttachments(t.ai[loc.ai]);
2069
- t.rawMessages = [...t.rawMessages ?? [], msg];
2070
- });
2071
- state.turns[loc.turn] = next2;
2072
- if (id) ctx.indexes().byMessageId.set(id, { turn: loc.turn, ai: loc.ai });
2073
- effects.push({ type: "tool-updated", turnId: next2.id, aiId: next2.ai[loc.ai].id, tool });
2074
- return;
2075
- }
2076
- const ti = state.openTurn;
2077
- const ai_i = state.openAi;
2078
- if (ti === null || ai_i === null) return;
2079
- const orphan = {
2080
- callId,
2081
- name: String(m?.name || ""),
2082
- input: {},
2083
- status,
2084
- result,
2085
- extracted: extractFromToolResult(String(m?.name || ""), result)
2086
- };
2087
- const turn = state.turns[ti];
2088
- const next = ctx.cloneWith(turn, ai_i, (t) => {
2089
- t.ai[ai_i].tools = [...turn.ai[ai_i].tools, orphan];
2090
- t.rawMessages = [...t.rawMessages ?? [], msg];
2091
- });
2092
- state.turns[ti] = next;
2093
- ctx.indexes().byToolCallId.set(callId, { turn: ti, ai: ai_i, tool: next.ai[ai_i].tools.length - 1 });
2094
- if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: ai_i });
2095
- effects.push({ type: "tool-updated", turnId: next.id, aiId: next.ai[ai_i].id, tool: orphan });
2096
- };
2097
- const appendAi = (msg, effects) => {
2098
- const id = String(msg?.id || "").trim();
2099
- if (state.openTurn === null) {
2100
- appendHuman(
2101
- {
2102
- id: `${id || "ai"}-orphan`,
2103
- type: "human",
2104
- content: "",
2105
- additional_kwargs: {}
2106
- },
2107
- false,
2108
- effects
2109
- );
2110
- }
2111
- const ti = state.openTurn;
2112
- const runId = messageRunId(msg);
2113
- const openSeg = state.openAi !== null ? state.turns[ti].ai[state.openAi] : null;
2114
- if (openSeg && (!runId || !openSeg.runId || runId === openSeg.runId)) {
2115
- const text = readMessageContentText(msg);
2116
- const ai_i = state.openAi;
2117
- const turn = state.turns[ti];
2118
- const body = text || openSeg.body;
2119
- const next = ctx.cloneWith(turn, ai_i, (t) => {
2120
- t.ai[ai_i].body = body;
2121
- t.ai[ai_i].streamingText = body;
2122
- if (id && !t.ai[ai_i].messageIds?.includes(id)) {
2123
- t.ai[ai_i].messageIds = [...t.ai[ai_i].messageIds ?? [], id];
2124
- }
2125
- if (!t.ai[ai_i].runId) t.ai[ai_i].runId = runId || ctx.streamRunId() || "";
2126
- t.rawMessages = [...t.rawMessages ?? [], msg];
2127
- });
2128
- state.turns[ti] = next;
2129
- if (id && id !== openSeg.id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: ai_i });
2130
- effects.push({ type: "ai-delta", turnId: next.id, aiId: openSeg.id, body, streamingText: body });
2131
- registerToolCalls(ti, ai_i, msg, effects);
2132
- return;
2133
- }
2134
- openNewAi(ti, msg, effects);
2135
- };
2136
- return { appendHuman, appendHiddenHuman, appendAi, applyToolMessage, registerToolCalls };
2137
- }
2138
-
2139
- // src/materializer/turn-machine.ts
2140
- var DEFAULT_TWIN_TOOL_PREFIX = "city-digital-twin-display_";
2141
- function createTurnMachine(options) {
2142
- const state = { turns: [], openTurn: null, openAi: null, optimisticTurnId: null };
2143
- let indexes = createIndexes();
2144
- const twinEnabled = !!options?.twin?.enabled;
2145
- const twinToolPrefix = options?.twin?.toolPrefix || DEFAULT_TWIN_TOOL_PREFIX;
2146
- const streamRunId = () => String(options?.getStreamRunId?.() || "").trim();
2147
- const assembleAttachments = (seg) => {
2148
- const byKind = /* @__PURE__ */ new Map();
2149
- for (const tool of seg.tools) {
2150
- const ex = tool.extracted;
2151
- if (ex?.kind === "report") {
2152
- byKind.set(`report:${ex.reportKind}`, {
2153
- kind: "report",
2154
- reportKind: ex.reportKind,
2155
- body: ex.body,
2156
- outline: ex.outline,
2157
- sourcePath: ex.sourcePath,
2158
- title: ex.title
2159
- });
2160
- } else if (ex?.kind === "artifact") byKind.set("artifact", { kind: "artifact", files: ex.files });
2161
- else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
2162
- byKind.set("twin", { kind: "twin", payload: tool.input });
2163
- }
2164
- }
2165
- return [...byKind.values()];
2166
- };
2167
- const cloneWith = (turn, ai_i, mutate) => {
2168
- const next = {
2169
- ...turn,
2170
- human: { ...turn.human },
2171
- clarifications: [...turn.clarifications],
2172
- ai: turn.ai.map((seg, i) => i === ai_i ? { ...seg, tools: [...seg.tools] } : seg)
2173
- };
2174
- mutate(next);
2175
- return next;
2176
- };
2177
- const archiveRaw = (t, msg) => {
2178
- const id = String(msg?.id || "").trim();
2179
- const raws = t.rawMessages ?? [];
2180
- const ri = id ? raws.findIndex((r) => String(r?.id || "").trim() === id) : -1;
2181
- t.rawMessages = ri >= 0 ? [...raws.slice(0, ri), msg, ...raws.slice(ri + 1)] : [...raws, msg];
2182
- };
2183
- const sealAiSegment = (turn, ai_i, effects) => {
2184
- const seg = turn.ai[ai_i];
2185
- if (seg.status === "sealed") return turn;
2186
- const sealed = {
2187
- ...seg,
2188
- status: "sealed",
2189
- streamingText: void 0,
2190
- segments: sliceBodySegments(seg.body),
2191
- attachments: assembleAttachments(seg)
2192
- };
2193
- const next = cloneWith(turn, ai_i, (t) => {
2194
- t.ai[ai_i] = sealed;
2195
- });
2196
- effects.push({ type: "ai-sealed", turnId: next.id, aiId: sealed.id, segments: sealed.segments });
2197
- return next;
2198
- };
2199
- const sealOpenTurn = (effects) => {
2200
- const ti = state.openTurn;
2201
- if (ti === null) return;
2202
- let turn = state.turns[ti];
2203
- if (state.openAi !== null) {
2204
- turn = sealAiSegment(turn, state.openAi, effects);
2205
- state.openAi = null;
2206
- }
2207
- if (turn.status !== "sealed") {
2208
- const sealed = { ...turn, status: "sealed" };
2209
- state.turns[ti] = sealed;
2210
- effects.push({ type: "turn-sealed", turnId: sealed.id });
2211
- }
2212
- state.openTurn = null;
2213
- if (state.optimisticTurnId === turn.id) state.optimisticTurnId = null;
2214
- };
2215
- const rules = createTurnRules({
2216
- state,
2217
- indexes: () => indexes,
2218
- cloneWith,
2219
- sealOpenTurn,
2220
- sealAiSegment,
2221
- assembleAttachments,
2222
- streamRunId
2223
- });
2224
- const applyTailRemove = (id, effects) => {
2225
- const ti = state.openTurn;
2226
- if (state.optimisticTurnId && ti !== null && state.turns[ti]?.human.id === id) {
2227
- state.turns.pop();
2228
- state.openTurn = null;
2229
- state.openAi = null;
2230
- state.optimisticTurnId = null;
2231
- indexes = rebuildIndexes(state.turns);
2232
- effects.push({ type: "placeholder-dropped", turnId: id });
2233
- return;
2234
- }
2235
- };
2236
- const applyAppend = (msg, allowOptimistic, effects) => {
2237
- if (isHiddenHuman(msg)) return rules.appendHiddenHuman(msg, effects);
2238
- if (isHumanMessage(msg)) return rules.appendHuman(msg, allowOptimistic, effects);
2239
- if (isAiMessage(msg)) return rules.appendAi(msg, effects);
2240
- if (isToolMessage(msg)) return rules.applyToolMessage(msg, effects);
2241
- };
2242
- const applyUpdate = (id, msg, effects) => {
2243
- const loc = indexes.byMessageId.get(id);
2244
- if (!loc) return;
2245
- if (loc.ai === null) {
2246
- if (isHiddenHuman(msg)) return rules.appendHiddenHuman(msg, effects);
2247
- if (!isHumanMessage(msg)) return;
2248
- const turn2 = state.turns[loc.turn];
2249
- const wasOptimistic = state.optimisticTurnId === turn2.id;
2250
- const mergedKwargs = resolveHumanKwargsMerge(
2251
- turn2.human.kwargs,
2252
- msg?.additional_kwargs,
2253
- (getHumanMessageBaseId(id) || id) !== id
2254
- );
2255
- const next2 = cloneWith(turn2, null, (t) => {
2256
- t.human = { id, text: extractTextFromMessage(msg), kwargs: mergedKwargs };
2257
- t.optimistic = false;
2258
- archiveRaw(t, msg);
2259
- });
2260
- state.turns[loc.turn] = next2;
2261
- if (wasOptimistic) {
2262
- state.optimisticTurnId = null;
2263
- effects.push({ type: "placeholder-absorbed", turnId: next2.id });
2264
- } else {
2265
- effects.push({ type: "message-updated", turnId: next2.id, aiId: null });
2266
- }
2267
- return;
2268
- }
2269
- if (isToolMessage(msg)) {
2270
- rules.applyToolMessage(msg, effects);
2271
- return;
2272
- }
2273
- const turn = state.turns[loc.turn];
2274
- const seg = turn.ai[loc.ai];
2275
- const text = readMessageContentText(msg);
2276
- const body = text || seg.body;
2277
- const bodyChanged = body !== seg.body;
2278
- const next = cloneWith(turn, loc.ai, (t) => {
2279
- const target = t.ai[loc.ai];
2280
- target.body = body;
2281
- if (target.status === "streaming") target.streamingText = body;
2282
- if (target.status === "sealed" && bodyChanged) target.segments = sliceBodySegments(body);
2283
- if (!target.runId) {
2284
- const rid = messageRunId(msg) || streamRunId();
2285
- if (rid) target.runId = rid;
2286
- }
2287
- archiveRaw(t, msg);
2288
- });
2289
- state.turns[loc.turn] = next;
2290
- if (id !== seg.id && isAiMessage(msg)) {
2291
- indexes.byMessageId.set(id, { turn: loc.turn, ai: loc.ai });
2292
- const nextSeg = state.turns[loc.turn].ai[loc.ai];
2293
- if (!nextSeg.messageIds?.includes(id)) nextSeg.messageIds = [...nextSeg.messageIds ?? [], id];
2294
- }
2295
- effects.push({ type: "ai-delta", turnId: next.id, aiId: seg.id, body, streamingText: body });
2296
- rules.registerToolCalls(loc.turn, loc.ai, msg, effects);
2297
- };
2298
- const finalizeInto = (effects) => {
2299
- sealOpenTurn(effects);
2300
- indexes = rebuildIndexes(state.turns);
2301
- };
2302
- function resetMachine() {
2303
- state.turns = [];
2304
- state.openTurn = null;
2305
- state.openAi = null;
2306
- state.optimisticTurnId = null;
2307
- indexes = createIndexes();
2308
- }
2309
- return {
2310
- applyDeltas(deltas) {
2311
- const effects = [];
2312
- for (const d of deltas) {
2313
- if (d.type === "append") applyAppend(d.message, true, effects);
2314
- else if (d.type === "update") applyUpdate(d.id, d.message, effects);
2315
- else applyTailRemove(d.id, effects);
2316
- }
2317
- return effects;
2318
- },
2319
- seed(messages) {
2320
- if (state.openTurn !== null || state.openAi !== null) {
2321
- throw new Error("[materializer] \u6D41\u8FDB\u884C\u4E2D\u7981\u6B62 seed\uFF08\u5148 finalize \u5BC6\u5C01\u540E\u518D\u5168\u91CF\u91CD\u5EFA\uFF09");
2322
- }
2323
- resetMachine();
2324
- const effects = [];
2325
- for (const msg of messages) applyAppend(msg, false, effects);
2326
- finalizeInto(effects);
2327
- return effects;
2328
- },
2329
- finalize() {
2330
- const effects = [];
2331
- finalizeInto(effects);
2332
- return effects;
2333
- },
2334
- decorate(id, patch) {
2335
- const effects = [];
2336
- const loc = indexes.byMessageId.get(id);
2337
- if (!loc || loc.ai === null) return effects;
2338
- const turn = state.turns[loc.turn];
2339
- const next = cloneWith(turn, loc.ai, (t) => {
2340
- Object.assign(t.ai[loc.ai], patch);
2341
- });
2342
- state.turns[loc.turn] = next;
2343
- effects.push({ type: "message-updated", turnId: next.id, aiId: next.ai[loc.ai].id });
2344
- return effects;
2345
- },
2346
- reset: resetMachine,
2347
- get state() {
2348
- return state;
2349
- },
2350
- get indexes() {
2351
- return indexes;
2352
- }
2353
- };
2354
- }
2355
-
2356
- // src/materializer/diff.ts
2357
- function diffMessageSnapshots(baseline, next) {
2358
- const upserts = [];
2359
- const nextBaseline = /* @__PURE__ */ new Map();
2360
- for (const msg of next) {
2361
- const id = String(msg?.id || "").trim();
2362
- if (!id) continue;
2363
- if (baseline.get(id) !== msg) upserts.push(msg);
2364
- nextBaseline.set(id, msg);
2365
- }
2366
- const removals = [];
2367
- for (const id of baseline.keys()) if (!nextBaseline.has(id)) removals.push(id);
2368
- return { upserts, removals, nextBaseline };
2369
- }
2370
- function createMessageDiff() {
2371
- let baseline = /* @__PURE__ */ new Map();
2372
- return {
2373
- apply(next) {
2374
- const { upserts, removals, nextBaseline } = diffMessageSnapshots(baseline, next);
2375
- const deltas = [];
2376
- for (const msg of upserts) {
2377
- const id = String(msg?.id || "").trim();
2378
- deltas.push(baseline.has(id) ? { type: "update", id, message: msg } : { type: "append", message: msg });
2379
- }
2380
- for (const id of removals) deltas.push({ type: "tail-remove", id });
2381
- baseline = nextBaseline;
2382
- return deltas;
2383
- },
2384
- reset() {
2385
- baseline = /* @__PURE__ */ new Map();
2386
- },
2387
- get baselineSize() {
2388
- return baseline.size;
2389
- }
2390
- };
2391
- }
2392
-
2393
- // src/materializer/materializer.ts
2394
- function createMaterializer(options) {
2395
- const view = (0, import_vue2.shallowRef)({ turns: [] });
2396
- const machine = createTurnMachine(options);
2397
- const messageDiff = createMessageDiff();
2398
- const publishIfChanged = (effects) => {
2399
- if (!effects.length) return;
2400
- view.value = { turns: [...machine.state.turns] };
2401
- };
2402
- return {
2403
- view,
2404
- hydrate(seed) {
2405
- messageDiff.reset();
2406
- messageDiff.apply(seed);
2407
- const effects = machine.seed(seed);
2408
- publishIfChanged(effects);
2409
- },
2410
- applySnapshot(messages) {
2411
- const deltas = messageDiff.apply(messages);
2412
- if (!deltas.length) return;
2413
- const effects = machine.applyDeltas(deltas);
2414
- publishIfChanged(effects);
2415
- },
2416
- finalize() {
2417
- publishIfChanged(machine.finalize());
2418
- },
2419
- decorate(messageId, patch) {
2420
- publishIfChanged(machine.decorate(messageId, patch));
2421
- },
2422
- reset() {
2423
- messageDiff.reset();
2424
- machine.reset();
2425
- view.value = { turns: [] };
2426
- }
2427
- };
2428
- }
2429
-
2430
- // src/runtime/runtime-materializer.ts
2431
- var localSeq = 0;
2432
- function createRuntimeMaterializer(options) {
2433
- const materializer = createMaterializer({ twin: options.twin, getStreamRunId: options.getStreamRunId });
2434
- let lastMessages = [];
2435
- const answersMap = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Map());
2436
- const answers = (0, import_vue3.computed)(() => answersMap.value);
2437
- const turns = (0, import_vue3.computed)(() => materializer.view.value.turns);
2438
- const activeClarification = (0, import_vue3.computed)(() => {
2439
- const ts = materializer.view.value.turns;
2440
- const last = ts[ts.length - 1];
2441
- if (!last) return void 0;
2442
- for (let ci = last.clarifications.length - 1; ci >= 0; ci--) {
2443
- const c = last.clarifications[ci];
2444
- if (!c.answer && !answersMap.value.has(c.callId)) return c;
2445
- }
2446
- return void 0;
2447
- });
2448
- const feed = (messages) => {
2449
- lastMessages = messages;
2450
- materializer.applySnapshot(messages);
2451
- };
2452
- return {
2453
- view: materializer.view,
2454
- turns,
2455
- activeClarification,
2456
- answers,
2457
- setClarificationAnswer(toolCallId, answer) {
2458
- const next = new Map(answersMap.value);
2459
- next.set(toolCallId, answer);
2460
- answersMap.value = next;
2461
- },
2462
- clearClarificationAnswers() {
2463
- if (!answersMap.value.size) return;
2464
- answersMap.value = /* @__PURE__ */ new Map();
2465
- },
2466
- lastMessages: () => lastMessages,
2467
- hydrate(seed) {
2468
- lastMessages = seed;
2469
- materializer.hydrate(seed);
2470
- },
2471
- applySnapshot(messages) {
2472
- lastMessages = messages;
2473
- materializer.applySnapshot(messages);
2474
- },
2475
- finalize() {
2476
- materializer.finalize();
2477
- },
2478
- decorate(messageId, patch) {
2479
- materializer.decorate(messageId, patch);
2480
- },
2481
- prependHistory(older) {
2482
- const merged = [...older, ...lastMessages];
2483
- try {
2484
- materializer.hydrate(merged);
2485
- } catch {
2486
- return false;
2487
- }
2488
- lastMessages = merged;
2489
- return true;
2490
- },
2491
- reconcileWithPage(pageMessages) {
2492
- if (!pageMessages.length || !lastMessages.length) return;
2493
- const byId = new Map(pageMessages.map((m) => [String(m?.id || ""), m]));
2494
- feed(lastMessages.map((m) => byId.get(String(m?.id || "")) ?? m));
2495
- },
2496
- addOptimisticTurn(body) {
2497
- localSeq += 1;
2498
- const stamp = `${Date.now()}-${localSeq}`;
2499
- const humanMsg = {
2500
- id: `local-h-${stamp}`,
2501
- type: "human",
2502
- content: [{ type: "text", text: body }],
2503
- additional_kwargs: {}
2504
- };
2505
- const aiMsg = {
2506
- id: `local-a-${stamp}`,
2507
- type: "ai",
2508
- content: [{ type: "text", text: "" }],
2509
- additional_kwargs: {}
2510
- };
2511
- feed([...lastMessages, humanMsg, aiMsg]);
2512
- },
2513
- updateAiBody(aiId, body) {
2514
- const idx = lastMessages.findIndex((m) => String(m?.id || "") === aiId);
2515
- if (idx < 0) return;
2516
- const next = [...lastMessages];
2517
- next[idx] = { ...next[idx], content: [{ type: "text", text: body }] };
2518
- feed(next);
2519
- },
2520
- applySemanticPatch(patches) {
2521
- if (!patches.size || !lastMessages.length) return;
2522
- const next = applySemanticPatches(lastMessages, patches);
2523
- const changed = next.some((m, i) => m !== lastMessages[i]);
2524
- if (changed) feed(next);
2525
- }
2526
- };
2527
- }
2528
-
2529
- // src/runtime/values-projection.ts
2530
- var import_vue4 = require("vue");
2531
- var import_ui = require("@langchain/langgraph-sdk/ui");
2532
-
2533
- // src/runtime/interrupt-reconcile.ts
2534
- function reconcileInterrupts(prevValues, nextValues, firstEvent) {
2535
- let base = prevValues;
2536
- if (firstEvent && base && "__interrupt__" in base) {
2537
- const { __interrupt__: _dropped, ...rest } = base;
2538
- base = rest;
2539
- }
2540
- if (nextValues && typeof nextValues === "object" && "__interrupt__" in nextValues) {
2541
- let interrupts = nextValues.__interrupt__;
2542
- const prevInterrupts = base?.__interrupt__;
2543
- if (Array.isArray(interrupts) && interrupts.length > 0 && Array.isArray(prevInterrupts)) {
2544
- const merged = [...prevInterrupts];
2545
- const existingIds = new Set(merged.map((i) => i?.id).filter((id) => id != null));
2546
- for (const interrupt of interrupts) {
2547
- const id = interrupt?.id;
2548
- if (id != null) {
2549
- if (existingIds.has(id)) continue;
2550
- existingIds.add(id);
2551
- }
2552
- merged.push(interrupt);
2553
- }
2554
- interrupts = merged;
2555
- }
2556
- return { ...base, __interrupt__: interrupts };
2557
- }
2558
- if (nextValues && typeof nextValues === "object") {
2559
- if (base && "__interrupt__" in base && Array.isArray(base.__interrupt__)) {
2560
- return { ...nextValues, __interrupt__: base.__interrupt__ };
2561
- }
2562
- return nextValues;
2563
- }
2564
- return nextValues ?? {};
2565
- }
2566
-
2567
- // src/runtime/values-projection.ts
2568
- function createValuesChannel(options = {}) {
2569
- const valuesRef = (0, import_vue4.shallowRef)({});
2570
- const threadStateRef = (0, import_vue4.shallowRef)(void 0);
2571
- let firstEvent = true;
2572
- let lastTitle = "";
2573
- let latestStreamMessages = [];
2574
- const readStateMessages = () => {
2575
- const msgs = threadStateRef.value?.values?.messages;
2576
- return Array.isArray(msgs) ? [...msgs] : [];
2577
- };
2578
- const readStreamMessages = () => [...latestStreamMessages];
2579
- return {
2580
- applyInitialValues(next) {
2581
- valuesRef.value = { ...next ?? {} };
2582
- },
2583
- applyThreadState(state) {
2584
- threadStateRef.value = state;
2585
- },
2586
- beginStream() {
2587
- firstEvent = true;
2588
- threadStateRef.value = void 0;
2589
- latestStreamMessages = [];
2590
- },
2591
- applyValuesEvent(data) {
2592
- const reconciled = reconcileInterrupts(valuesRef.value, data, firstEvent);
2593
- firstEvent = false;
2594
- valuesRef.value = reconciled;
2595
- if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
2596
- const title = String(reconciled?.title || "").trim();
2597
- if (title && title !== lastTitle) {
2598
- lastTitle = title;
2599
- options.onTitle?.(title);
2600
- }
2601
- },
2602
- getValues() {
2603
- return valuesRef.value;
2604
- },
2605
- getStateMessages: readStateMessages,
2606
- getStreamMessages: readStreamMessages,
2607
- getInterrupt({ isLoading, error }) {
2608
- return (0, import_ui.extractInterrupts)(valuesRef.value, {
2609
- isLoading,
2610
- threadState: threadStateRef.value,
2611
- error
2612
- });
2613
- }
2614
- };
2615
- }
2616
-
2617
- // src/store/runs-store.ts
2618
- var import_vue5 = require("vue");
2619
- function createInterruptState() {
2620
- const respondedIds = (0, import_vue5.shallowRef)(/* @__PURE__ */ new Set());
2621
- return {
2622
- respondedIds,
2623
- markResponded(id) {
2624
- const next = new Set(respondedIds.value);
2625
- next.add(id);
2626
- respondedIds.value = next;
2627
- },
2628
- unmarkResponded(id) {
2629
- if (!respondedIds.value.has(id)) return;
2630
- const next = new Set(respondedIds.value);
2631
- next.delete(id);
2632
- respondedIds.value = next;
2633
- }
2634
- };
2635
- }
2636
- function createRunsStore(options) {
2637
- const runsMap = (0, import_vue5.shallowRef)(/* @__PURE__ */ new Map());
2638
- const currentRunId = (0, import_vue5.shallowRef)(null);
2639
- return {
2640
- runsMap,
2641
- currentRunId,
2642
- fillFromRunsList(runsList) {
2643
- let next = null;
2644
- for (const run of runsList) {
2645
- const runId = String(run?.run_id || "").trim();
2646
- if (!runId) continue;
2647
- next ?? (next = new Map(runsMap.value));
2648
- next.set(runId, buildRunInfo(run, options.threadId));
2314
+ }
2315
+ function createRunsStore(options) {
2316
+ const runsMap = (0, import_vue3.shallowRef)(/* @__PURE__ */ new Map());
2317
+ const currentRunId = (0, import_vue3.shallowRef)(null);
2318
+ return {
2319
+ runsMap,
2320
+ currentRunId,
2321
+ fillFromRunsList(runsList) {
2322
+ let next = null;
2323
+ for (const run of runsList) {
2324
+ const runId = String(run?.run_id || "").trim();
2325
+ if (!runId) continue;
2326
+ next ?? (next = new Map(runsMap.value));
2327
+ next.set(runId, buildRunInfo(run, options.threadId));
2649
2328
  }
2650
2329
  if (next) runsMap.value = next;
2651
2330
  },
@@ -2727,50 +2406,96 @@ function createRunsStore(options) {
2727
2406
  }
2728
2407
 
2729
2408
  // src/runtime/thread-runtime.ts
2409
+ var pendingSeq = 0;
2410
+ function newPendingRunId() {
2411
+ pendingSeq += 1;
2412
+ return `local-${Date.now()}-${pendingSeq}`;
2413
+ }
2730
2414
  function createThreadRuntime(options) {
2731
- const scope = (0, import_vue6.effectScope)();
2415
+ const scope = (0, import_vue4.effectScope)();
2732
2416
  const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
2733
2417
  const interruptState = createInterruptState();
2734
- const rm = createRuntimeMaterializer({
2735
- twin: options.twin,
2736
- // 段级 runId 兜底源(metadata 首帧权威值):流式 tuple 消息本体无 runId,
2737
- // 段打开/回填时经此兜底——点赞/反馈按 runId 提交的依赖
2738
- getStreamRunId: () => runs.currentRunId.value
2739
- });
2418
+ const rowsStore = createRowsStore();
2419
+ const overlay = createSemanticOverlay();
2740
2420
  const valuesChannel = createValuesChannel({
2741
2421
  onTitle: (title) => options.onTitle?.(options.threadId, title)
2742
2422
  });
2743
- const overlay = createSemanticOverlay();
2744
- const streamRef = (0, import_vue6.shallowRef)(null);
2745
- const isInitializing = (0, import_vue6.ref)(false);
2746
- const streaming = (0, import_vue6.ref)(false);
2747
- const tokenUsage = (0, import_vue6.shallowRef)(null);
2423
+ const streamRef = (0, import_vue4.shallowRef)(null);
2424
+ const isInitializing = (0, import_vue4.ref)(false);
2425
+ const streaming = (0, import_vue4.ref)(false);
2426
+ const tokenUsage = (0, import_vue4.shallowRef)(null);
2748
2427
  let initialized = false;
2749
2428
  let initPromise = null;
2750
2429
  let pager = null;
2751
- const interrupt = (0, import_vue6.computed)(() => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }));
2752
- const hasPendingInterrupt = (0, import_vue6.computed)(() => {
2430
+ const runsListMeta = (0, import_vue4.shallowRef)([]);
2431
+ const liveMessages = (0, import_vue4.shallowRef)([]);
2432
+ const lastSeenLiveIds = /* @__PURE__ */ new Set();
2433
+ const pendingRun = (0, import_vue4.shallowRef)(null);
2434
+ const answers = (0, import_vue4.shallowRef)(/* @__PURE__ */ new Map());
2435
+ const activeRunId = (0, import_vue4.computed)(() => runs.currentRunId.value);
2436
+ const runsProjection = (0, import_vue4.computed)(
2437
+ () => projectRuns({
2438
+ rows: rowsStore.rows.value,
2439
+ liveMessages: liveMessages.value,
2440
+ activeRunId: activeRunId.value,
2441
+ runsList: runsListMeta.value,
2442
+ pendingRun: pendingRun.value,
2443
+ answers: answers.value,
2444
+ twin: options.twin,
2445
+ streaming: streaming.value
2446
+ })
2447
+ );
2448
+ const interrupt = (0, import_vue4.computed)(() => streamRef.value?.interrupt.value);
2449
+ const hasPendingInterrupt = (0, import_vue4.computed)(() => {
2753
2450
  const it = interrupt.value;
2754
2451
  return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
2755
2452
  });
2756
- const streamError = (0, import_vue6.computed)(() => streamRef.value?.error.value ?? null);
2757
- const isGenerating = (0, import_vue6.computed)(() => streaming.value);
2453
+ const streamError = (0, import_vue4.computed)(() => streamRef.value?.error.value ?? null);
2454
+ const isGenerating = (0, import_vue4.computed)(() => streaming.value);
2455
+ const activeClarification = (0, import_vue4.computed)(() => {
2456
+ const list = runsProjection.value;
2457
+ for (let i = list.length - 1; i >= 0; i--) {
2458
+ const clarifications = list[i].clarifications;
2459
+ for (let c = clarifications.length - 1; c >= 0; c--) {
2460
+ if (clarifications[c].answer === void 0) return clarifications[c];
2461
+ }
2462
+ }
2463
+ return void 0;
2464
+ });
2465
+ const clarificationAnswers = (0, import_vue4.computed)(() => answers.value);
2758
2466
  const beginStream = () => {
2759
2467
  valuesChannel.beginStream();
2760
2468
  overlay.invalidate();
2761
2469
  runs.currentRunId.value = null;
2470
+ liveMessages.value = [];
2471
+ lastSeenLiveIds.clear();
2762
2472
  };
2763
2473
  const streamStarted = () => {
2764
2474
  streaming.value = true;
2765
2475
  };
2766
2476
  const streamSettled = () => {
2767
2477
  streaming.value = false;
2478
+ pendingRun.value = null;
2768
2479
  };
2769
2480
  const markStreamRun = (runIdRaw) => {
2770
2481
  const runId = String(runIdRaw || "").trim();
2771
2482
  if (!runId) return;
2772
2483
  runs.currentRunId.value = runId;
2773
2484
  runs.ensureRunning(runId);
2485
+ const pending = pendingRun.value;
2486
+ if (pending && pending.runId !== runId) {
2487
+ pendingRun.value = { ...pending, runId };
2488
+ }
2489
+ };
2490
+ const applyLiveSnapshot = (messages) => {
2491
+ if (!streaming.value) return;
2492
+ const fresh = extractLiveIncrement(messages, lastSeenLiveIds);
2493
+ const eligible = fresh.filter((m) => {
2494
+ const t = String(m?.type || "");
2495
+ return t === "ai" || t === "tool";
2496
+ });
2497
+ if (!eligible.length) return;
2498
+ liveMessages.value = [...liveMessages.value, ...eligible];
2774
2499
  };
2775
2500
  const refreshTokenUsage = async () => {
2776
2501
  try {
@@ -2785,13 +2510,15 @@ function createThreadRuntime(options) {
2785
2510
  assistantId: options.assistantId,
2786
2511
  transport: options.transport,
2787
2512
  runs,
2788
- valuesChannel,
2513
+ rowsStore,
2514
+ runsListMeta,
2789
2515
  overlay,
2790
- rm,
2516
+ valuesChannel,
2791
2517
  streamRef,
2792
2518
  setPager: (p) => pager = p,
2793
2519
  setInitialized: () => initialized = true,
2794
2520
  markStreamRun,
2521
+ applyLiveSnapshot,
2795
2522
  onStreamStart: streamStarted,
2796
2523
  onStreamSettled: streamSettled,
2797
2524
  refreshTokenUsage
@@ -2806,10 +2533,16 @@ function createThreadRuntime(options) {
2806
2533
  getHandle: () => streamRef.value,
2807
2534
  beginStream,
2808
2535
  markStreamRun,
2809
- getInterrupt: () => valuesChannel.getInterrupt({ isLoading: streamRef.value?.isLoading.value ?? false }),
2536
+ getInterrupt: () => streamRef.value?.interrupt.value,
2810
2537
  markResponded: (id) => interruptState.markResponded(id),
2538
+ unmarkResponded: (id) => interruptState.unmarkResponded(id),
2811
2539
  getPager: () => pager,
2812
- runs
2540
+ runs,
2541
+ createPendingRun: (text, kind, kwargs) => {
2542
+ const pending = { runId: newPendingRunId(), text, kind, kwargs };
2543
+ pendingRun.value = pending;
2544
+ return pending.runId;
2545
+ }
2813
2546
  });
2814
2547
  return {
2815
2548
  threadId: options.threadId,
@@ -2817,18 +2550,17 @@ function createThreadRuntime(options) {
2817
2550
  touch() {
2818
2551
  this.lastViewedAt = Date.now();
2819
2552
  },
2820
- view: rm.view,
2821
- turns: rm.turns,
2822
- activeClarification: rm.activeClarification,
2553
+ runs: runsProjection,
2554
+ runsInfo: (0, import_vue4.computed)(() => runs.runsMap.value),
2555
+ activeClarification,
2823
2556
  isGenerating,
2824
2557
  isInitializing,
2825
- runs: (0, import_vue6.computed)(() => runs.runsMap.value),
2826
2558
  interrupt,
2827
2559
  hasPendingInterrupt,
2828
2560
  streamError,
2829
2561
  tokenUsage,
2830
- hasMoreHistory: (0, import_vue6.computed)(() => pager?.hasMore.value ?? false),
2831
- loadingHistory: (0, import_vue6.computed)(() => pager?.loading.value ?? false),
2562
+ hasMoreHistory: (0, import_vue4.computed)(() => pager?.hasMore.value ?? false),
2563
+ loadingHistory: (0, import_vue4.computed)(() => pager?.loading.value ?? false),
2832
2564
  async init() {
2833
2565
  if (initialized) return;
2834
2566
  if (initPromise) return initPromise;
@@ -2845,17 +2577,43 @@ function createThreadRuntime(options) {
2845
2577
  resumeInterrupt: actions.resumeInterrupt,
2846
2578
  loadOlderMessages: actions.loadOlderMessages,
2847
2579
  applyFeedback(messageId, feedback) {
2848
- rm.decorate(messageId, { feedback });
2849
- const runId = rm.view.value.turns.flatMap((t) => t.ai).find((seg) => seg.id === messageId)?.runId;
2580
+ rowsStore.mergeLatest(
2581
+ rowsStore.rows.value.map((row) => {
2582
+ const id = String(row.content?.id || "");
2583
+ return id === messageId ? { ...row, feedback } : row;
2584
+ })
2585
+ );
2586
+ const runId = runsProjection.value.find((r) => r.rawMessages.some((m) => m.id === messageId))?.runId;
2850
2587
  if (runId) runs.patchRun(runId, { feedback });
2851
2588
  },
2852
- addOptimisticTurn: rm.addOptimisticTurn,
2853
- updateAiBody: rm.updateAiBody,
2854
- decorate: rm.decorate,
2855
- finalizeTurns: rm.finalize,
2856
- setClarificationAnswer: rm.setClarificationAnswer,
2857
- clearClarificationAnswers: rm.clearClarificationAnswers,
2858
- clarificationAnswers: rm.answers,
2589
+ addOptimisticTurn: (body) => {
2590
+ const runId = newPendingRunId();
2591
+ pendingRun.value = { runId, text: body, kind: "message" };
2592
+ },
2593
+ updateAiBody(aiId, body) {
2594
+ rowsStore.mergeLatest(
2595
+ rowsStore.rows.value.map((row) => {
2596
+ const id = String(row.content?.id || "");
2597
+ return id === aiId ? { ...row, content: { ...row.content, content: body } } : row;
2598
+ })
2599
+ );
2600
+ },
2601
+ decorate(messageId, patch) {
2602
+ if (patch.feedback) this.applyFeedback(messageId, patch.feedback);
2603
+ },
2604
+ finalizeTurns() {
2605
+ pendingRun.value = null;
2606
+ },
2607
+ setClarificationAnswer(toolCallId, answer) {
2608
+ const next = new Map(answers.value);
2609
+ next.set(toolCallId, answer);
2610
+ answers.value = next;
2611
+ },
2612
+ clearClarificationAnswers() {
2613
+ if (!answers.value.size) return;
2614
+ answers.value = /* @__PURE__ */ new Map();
2615
+ },
2616
+ clarificationAnswers,
2859
2617
  dispose() {
2860
2618
  streamRef.value?.stop();
2861
2619
  streamRef.value?.dispose?.();
@@ -2866,15 +2624,15 @@ function createThreadRuntime(options) {
2866
2624
  }
2867
2625
 
2868
2626
  // src/runtime/thread-directory.ts
2869
- var import_vue7 = require("vue");
2627
+ var import_vue5 = require("vue");
2870
2628
  var ACTIVE_THREAD_STATUSES = /* @__PURE__ */ new Set(["busy", "running", "pending", "interrupted"]);
2871
2629
  function isActiveThreadStatus(status) {
2872
2630
  return typeof status === "string" && ACTIVE_THREAD_STATUSES.has(status);
2873
2631
  }
2874
2632
  var ThreadDirectory = class {
2875
2633
  constructor(options) {
2876
- this.threads = (0, import_vue7.ref)([]);
2877
- this.threadsPagination = (0, import_vue7.ref)({
2634
+ this.threads = (0, import_vue5.ref)([]);
2635
+ this.threadsPagination = (0, import_vue5.ref)({
2878
2636
  limit: 50,
2879
2637
  offset: 0,
2880
2638
  hasMore: true,
@@ -2882,9 +2640,9 @@ var ThreadDirectory = class {
2882
2640
  });
2883
2641
  this.searchKeyword = "";
2884
2642
  /** 正在运行但已超出 SSE 连接上限的 thread(仅用于 UI 提示) */
2885
- this.runningNotConnectedThreadIds = (0, import_vue7.ref)(/* @__PURE__ */ new Set());
2643
+ this.runningNotConnectedThreadIds = (0, import_vue5.ref)(/* @__PURE__ */ new Set());
2886
2644
  /** 活跃 runtime 池(shallowReactive 追踪增删,runtime 实例不被深度代理) */
2887
- this.cachedRuntimes = (0, import_vue7.shallowReactive)(/* @__PURE__ */ new Map());
2645
+ this.cachedRuntimes = (0, import_vue5.shallowReactive)(/* @__PURE__ */ new Map());
2888
2646
  this.transport = options.transport;
2889
2647
  this.assistantId = options.assistantId;
2890
2648
  this.maxCachedRuntimes = options.maxCachedRuntimes ?? DEFAULT_MAX_CACHED_SESSIONS;
@@ -3070,7 +2828,7 @@ var ThreadDirectory = class {
3070
2828
  };
3071
2829
 
3072
2830
  // src/core/ChatCore.ts
3073
- var import_vue8 = require("vue");
2831
+ var import_vue6 = require("vue");
3074
2832
  function createChatCore(options) {
3075
2833
  const notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
3076
2834
  const directory = new ThreadDirectory({
@@ -3082,50 +2840,46 @@ function createChatCore(options) {
3082
2840
  notify,
3083
2841
  defaultThreadTitle: options.defaultThreadTitle
3084
2842
  });
3085
- const currentThreadId = (0, import_vue8.ref)(null);
3086
- const threads = (0, import_vue8.computed)(() => directory.threads.value);
3087
- const threadsPagination = (0, import_vue8.computed)(() => directory.threadsPagination.value);
3088
- const activeRuntime = (0, import_vue8.computed)(
2843
+ const currentThreadId = (0, import_vue6.ref)(null);
2844
+ const threads = (0, import_vue6.computed)(() => directory.threads.value);
2845
+ const threadsPagination = (0, import_vue6.computed)(() => directory.threadsPagination.value);
2846
+ const activeRuntime = (0, import_vue6.computed)(
3089
2847
  () => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
3090
2848
  );
3091
- const view = (0, import_vue8.computed)(() => activeRuntime.value?.view.value ?? { turns: [] });
3092
- const turns = (0, import_vue8.computed)(() => view.value.turns);
3093
- const activeClarification = (0, import_vue8.computed)(
3094
- () => activeRuntime.value?.activeClarification.value
3095
- );
3096
- const isGenerating = (0, import_vue8.computed)(
3097
- () => !!activeRuntime.value && (activeRuntime.value.isGenerating.value || activeRuntime.value.isInitializing.value)
3098
- );
3099
- const isLoadingThread = (0, import_vue8.computed)(() => activeRuntime.value?.isInitializing.value ?? false);
3100
- const runs = (0, import_vue8.computed)(
3101
- () => activeRuntime.value?.runs.value ?? /* @__PURE__ */ new Map()
3102
- );
3103
- const toolCalls = (0, import_vue8.computed)(
3104
- () => turns.value.flatMap(
3105
- (t) => t.ai.flatMap(
3106
- (seg) => seg.tools.map((tool, index) => ({
3107
- id: tool.callId,
3108
- call: { id: tool.callId, name: tool.name, args: tool.input },
3109
- result: tool.result ? { content: tool.result } : void 0,
3110
- state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
3111
- index
3112
- }))
3113
- )
2849
+ const runs = (0, import_vue6.computed)(() => activeRuntime.value?.runs.value ?? []);
2850
+ const runsInfo = (0, import_vue6.computed)(() => activeRuntime.value?.runsInfo.value ?? /* @__PURE__ */ new Map());
2851
+ const toolCalls = (0, import_vue6.computed)(
2852
+ () => runs.value.flatMap(
2853
+ (run) => run.tools.map((tool, index) => ({
2854
+ id: tool.callId,
2855
+ call: { id: tool.callId, name: tool.name, args: tool.input },
2856
+ result: tool.result ? { content: tool.result } : void 0,
2857
+ state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
2858
+ index
2859
+ }))
3114
2860
  )
3115
2861
  );
3116
- const clarificationAnswers = (0, import_vue8.computed)(
2862
+ const activeClarification = (0, import_vue6.computed)(() => activeRuntime.value?.activeClarification.value);
2863
+ const isGenerating = (0, import_vue6.computed)(
2864
+ () => !!activeRuntime.value && activeRuntime.value.isGenerating.value
2865
+ );
2866
+ const isLoadingThread = (0, import_vue6.computed)(() => activeRuntime.value?.isInitializing.value ?? false);
2867
+ const clarificationAnswers = (0, import_vue6.computed)(
3117
2868
  () => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
3118
2869
  );
3119
- const activeInterrupt = (0, import_vue8.computed)(() => activeRuntime.value?.interrupt.value);
3120
- const hasPendingInterrupt = (0, import_vue8.computed)(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
3121
- const inputDisabled = (0, import_vue8.computed)(() => isGenerating.value || hasPendingInterrupt.value);
3122
- const streamError = (0, import_vue8.computed)(() => activeRuntime.value?.streamError.value ?? null);
3123
- const hasMoreHistory = (0, import_vue8.computed)(() => activeRuntime.value?.hasMoreHistory.value ?? false);
3124
- const loadingHistory = (0, import_vue8.computed)(() => activeRuntime.value?.loadingHistory.value ?? false);
3125
- const tokenUsage = (0, import_vue8.computed)(() => activeRuntime.value?.tokenUsage.value ?? null);
3126
- const runningNotConnectedThreadIds = (0, import_vue8.computed)(() => directory.runningNotConnectedThreadIds.value);
3127
- const getRunById = (runId) => runId ? runs.value.get(runId) : void 0;
3128
- const getRunsByThreadId = (threadId) => threadId ? Array.from(runs.value.values()).filter((r) => r.threadId === threadId) : [];
2870
+ const activeInterrupt = (0, import_vue6.computed)(() => activeRuntime.value?.interrupt.value);
2871
+ const hasPendingInterrupt = (0, import_vue6.computed)(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
2872
+ const inputDisabled = (0, import_vue6.computed)(() => isGenerating.value || hasPendingInterrupt.value);
2873
+ const streamError = (0, import_vue6.computed)(() => activeRuntime.value?.streamError.value ?? null);
2874
+ const hasMoreHistory = (0, import_vue6.computed)(() => activeRuntime.value?.hasMoreHistory.value ?? false);
2875
+ const loadingHistory = (0, import_vue6.computed)(() => activeRuntime.value?.loadingHistory.value ?? false);
2876
+ const tokenUsage = (0, import_vue6.computed)(() => activeRuntime.value?.tokenUsage.value ?? null);
2877
+ const runningNotConnectedThreadIds = (0, import_vue6.computed)(() => directory.runningNotConnectedThreadIds.value);
2878
+ const getRunById = (runId) => {
2879
+ const info = runId ? runsInfo.value.get(runId) : void 0;
2880
+ return info;
2881
+ };
2882
+ const getRunsByThreadId = (threadId) => threadId ? Array.from(runsInfo.value.values()).filter((r) => r.threadId === threadId) : [];
3129
2883
  const ensureThreadId = async () => {
3130
2884
  if (currentThreadId.value) return { threadId: currentThreadId.value, isNew: false, thread: null };
3131
2885
  const thread = await directory.createThread({ source: "chat" });
@@ -3174,25 +2928,25 @@ function createChatCore(options) {
3174
2928
  result.touch();
3175
2929
  await result.init();
3176
2930
  };
3177
- const regenerateTurn = async (aiSegmentId) => {
2931
+ const regenerateTurn = async (runId) => {
3178
2932
  if (isGenerating.value) return;
3179
- const turn = turns.value.find((t) => t.ai.some((seg) => seg.id === aiSegmentId));
3180
- const text = turn?.human.text ?? "";
3181
- if (!turn || !text.trim()) {
2933
+ const run = runs.value.find((r) => r.runId === runId);
2934
+ const text = run?.input.text ?? "";
2935
+ if (!run || !text.trim()) {
3182
2936
  notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
3183
2937
  return;
3184
2938
  }
3185
- await sendMessage(text, { kwargs: { ...turn.human.kwargs ?? {}, hide_from_ui: false } });
2939
+ await sendMessage(text, { kwargs: { ...run.input.kwargs ?? {}, hide_from_ui: false } });
3186
2940
  };
3187
2941
  return {
3188
- view,
3189
- turns,
2942
+ runs,
2943
+ turns: runs,
3190
2944
  isGenerating,
3191
2945
  isLoadingThread,
3192
2946
  currentThreadId,
3193
2947
  threads,
3194
2948
  threadsPagination,
3195
- runs,
2949
+ runsInfo,
3196
2950
  toolCalls,
3197
2951
  getRunById,
3198
2952
  getRunsByThreadId,
@@ -3246,612 +3000,8 @@ function createChatCore(options) {
3246
3000
  };
3247
3001
  }
3248
3002
 
3249
- // src/bridge/sse.ts
3250
- function createFetchReaderFactory(fetchImpl = fetch) {
3251
- return async (req) => {
3252
- const res = await fetchImpl(req.url, {
3253
- method: req.method,
3254
- headers: req.headers,
3255
- body: req.body !== void 0 ? JSON.stringify(req.body) : void 0,
3256
- signal: req.signal,
3257
- credentials: "include"
3258
- });
3259
- if (!res.ok) throw new Error(`SSE \u8BF7\u6C42\u5931\u8D25 ${res.status}`);
3260
- if (!res.body) throw new Error("SSE \u54CD\u5E94\u65E0 body");
3261
- const reader = res.body.getReader();
3262
- return {
3263
- read: () => reader.read(),
3264
- cancel: async () => {
3265
- reader.releaseLock();
3266
- await res.body.cancel().catch(() => {
3267
- });
3268
- }
3269
- };
3270
- };
3271
- }
3272
- async function* parseSseFrames(reader) {
3273
- const decoder = new TextDecoder();
3274
- let buf = "";
3275
- try {
3276
- while (true) {
3277
- let chunk;
3278
- try {
3279
- chunk = await reader.read();
3280
- } catch (e) {
3281
- if (e?.name === "AbortError") break;
3282
- throw e;
3283
- }
3284
- if (chunk.done) break;
3285
- buf += typeof chunk.value === "string" ? chunk.value : decoder.decode(chunk.value, { stream: true });
3286
- let idx;
3287
- while ((idx = buf.search(/\n\n|\r\n\r\n/)) !== -1) {
3288
- const raw = buf.slice(0, idx);
3289
- buf = buf.slice(idx).replace(/^\r?\n\r?\n/, "");
3290
- const frame = parseFrame(raw);
3291
- if (frame) yield frame;
3292
- }
3293
- }
3294
- buf += decoder.decode();
3295
- const tail = parseFrame(buf);
3296
- if (tail) yield tail;
3297
- } finally {
3298
- await reader.cancel().catch(() => {
3299
- });
3300
- }
3301
- }
3302
- function parseFrame(raw) {
3303
- if (!raw.trim()) return void 0;
3304
- let event = "message";
3305
- let id;
3306
- const dataLines = [];
3307
- for (const line of raw.split(/\r?\n/)) {
3308
- if (line.startsWith("event:")) event = line.slice(6).trim();
3309
- else if (line.startsWith("id:")) id = line.slice(3).trim();
3310
- else if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
3311
- }
3312
- return { event, id, data: dataLines.join("\n") };
3313
- }
3314
-
3315
- // src/bridge/event-hub.ts
3316
- function createEventHub() {
3317
- const buffer = [];
3318
- const subscribers = /* @__PURE__ */ new Set();
3319
- let seq = 0;
3320
- let closed = false;
3321
- function publish(event) {
3322
- if (closed) return;
3323
- const n = ++seq;
3324
- const framed = { ...event, seq: n, event_id: String(n) };
3325
- buffer.push(framed);
3326
- for (const sub of subscribers) {
3327
- sub.queue.push(framed);
3328
- sub.wake?.();
3329
- }
3330
- }
3331
- function open() {
3332
- const sub = { queue: [...buffer], wake: null, closed: false };
3333
- if (closed) sub.closed = true;
3334
- else subscribers.add(sub);
3335
- const next = () => {
3336
- if (sub.closed) return Promise.resolve({ done: true, value: void 0 });
3337
- const queued = sub.queue.shift();
3338
- if (queued) return Promise.resolve({ done: false, value: queued });
3339
- return new Promise((resolve) => {
3340
- sub.wake = () => {
3341
- sub.wake = null;
3342
- const v = sub.queue.shift();
3343
- if (sub.closed || !v) return resolve({ done: true, value: void 0 });
3344
- resolve({ done: false, value: v });
3345
- };
3346
- });
3347
- };
3348
- const returnFn = () => {
3349
- if (!sub.closed) {
3350
- sub.closed = true;
3351
- subscribers.delete(sub);
3352
- sub.wake?.();
3353
- }
3354
- return Promise.resolve({ done: true, value: void 0 });
3355
- };
3356
- return {
3357
- events: { [Symbol.asyncIterator]: () => ({ next, return: returnFn }) },
3358
- ready: Promise.resolve(),
3359
- close() {
3360
- returnFn();
3361
- }
3362
- };
3363
- }
3364
- function close() {
3365
- if (closed) return;
3366
- closed = true;
3367
- for (const sub of subscribers) {
3368
- sub.closed = true;
3369
- sub.wake?.();
3370
- }
3371
- subscribers.clear();
3372
- }
3373
- return {
3374
- publish,
3375
- open,
3376
- close,
3377
- get bufferedCount() {
3378
- return buffer.length;
3379
- }
3380
- };
3381
- }
3382
-
3383
- // src/bridge/translate.ts
3384
- var V1FrameTranslator = class {
3385
- constructor(options) {
3386
- /** 当前 run 是否处于 interrupt 待恢复态(end 帧据此选 terminal) */
3387
- this.interrupted = false;
3388
- this.pendingInterrupts = 0;
3389
- this.lastError = null;
3390
- /** 已开始消息的组装状态,key = message id */
3391
- this.started = /* @__PURE__ */ new Map();
3392
- /** tools 通道防重:已合成 tool-started / tool-finished 的 callId(values 帧全量重放,须去重) */
3393
- this.toolsStarted = /* @__PURE__ */ new Set();
3394
- this.toolsFinished = /* @__PURE__ */ new Set();
3395
- this.push = options.push;
3396
- this.onMetadata = options.onMetadata;
3397
- }
3398
- /** 分发一个 v1 SSE 帧 */
3399
- handleFrame(event, dataRaw) {
3400
- let data;
3401
- try {
3402
- data = dataRaw ? JSON.parse(dataRaw) : void 0;
3403
- } catch {
3404
- return;
3405
- }
3406
- switch (event) {
3407
- case "metadata":
3408
- if (data && typeof data === "object") this.onMetadata?.(data);
3409
- break;
3410
- case "values":
3411
- this.handleValues(data);
3412
- break;
3413
- case "messages":
3414
- this.handleMessages(data);
3415
- break;
3416
- case "updates":
3417
- if (data && typeof data === "object") {
3418
- for (const [node, delta] of Object.entries(data)) {
3419
- this.emit("updates", { node, values: delta });
3420
- }
3421
- }
3422
- break;
3423
- case "custom":
3424
- this.emit("custom", { name: "custom", payload: data });
3425
- break;
3426
- case "error":
3427
- this.lastError = typeof data === "string" ? data : data?.message ?? String(data);
3428
- break;
3429
- case "end":
3430
- this.emit("lifecycle", {
3431
- event: this.interrupted ? "interrupted" : this.lastError ? "failed" : "completed",
3432
- ...this.lastError ? { error: this.lastError } : {}
3433
- });
3434
- break;
3435
- default:
3436
- break;
3437
- }
3438
- }
3439
- /** values 帧:剥离 __interrupt__ → values 事件 + 合成 input.requested + 合成 tools 通道事件 */
3440
- handleValues(data) {
3441
- if (!data || typeof data !== "object") return;
3442
- const values = { ...data };
3443
- const interrupts = values.__interrupt__;
3444
- if (Array.isArray(interrupts) && interrupts.length > 0) {
3445
- delete values.__interrupt__;
3446
- this.interrupted = true;
3447
- this.pendingInterrupts += interrupts.length;
3448
- interrupts.forEach((it, i) => {
3449
- this.emit("input.requested", {
3450
- // v1 的 Interrupt 无稳定 id,按序号合成;resume 走值语义不依赖该 id
3451
- interrupt_id: `intr-${this.pendingInterrupts}-${i}`,
3452
- payload: it?.value ?? it
3453
- });
3454
- });
3455
- }
3456
- this.emit("values", values);
3457
- this.synthesizeTools(values);
3458
- }
3459
- /**
3460
- * 从 values 快照合成 v2 tools 通道事件(toolCalls 投影只认 tool-started/tool-finished):
3461
- * - AIMessage.tool_calls(args 已完整)→ tool-started
3462
- * - ToolMessage(工具结果)→ tool-finished
3463
- * values 每步全量重放,必须按 callId 防重;AI 消息在 tool 消息之前,顺序天然满足。
3464
- */
3465
- synthesizeTools(values) {
3466
- const messages = Array.isArray(values.messages) ? values.messages : [];
3467
- for (const m of messages) {
3468
- if (!m || typeof m !== "object") continue;
3469
- const toolCalls = Array.isArray(m.tool_calls) ? m.tool_calls : [];
3470
- for (const tc of toolCalls) {
3471
- const callId2 = tc?.id;
3472
- if (!callId2 || this.toolsStarted.has(callId2)) continue;
3473
- this.toolsStarted.add(callId2);
3474
- this.emit("tools", {
3475
- event: "tool-started",
3476
- tool_call_id: String(callId2),
3477
- tool_name: String(tc?.name ?? ""),
3478
- input: tc?.args
3479
- });
3480
- }
3481
- const callId = m.tool_call_id;
3482
- if (m.type === "tool" && typeof callId === "string" && callId && !this.toolsFinished.has(callId)) {
3483
- this.toolsFinished.add(callId);
3484
- this.emit("tools", { event: "tool-finished", tool_call_id: callId, output: contentToText(m.content) });
3485
- }
3486
- }
3487
- }
3488
- /** messages 帧:增量 chunk → message-start(一次) + content-block 事件序列 */
3489
- handleMessages(tuple) {
3490
- const chunk = tuple?.[0];
3491
- if (!chunk) return;
3492
- if (String(chunk.type || "").toLowerCase() === "remove") return;
3493
- const node = tuple?.[1]?.langgraph_node;
3494
- const id = chunk.id;
3495
- if (!id) return;
3496
- let st = this.started.get(id);
3497
- if (!st) {
3498
- st = { textBlockStarted: false, toolBlockIndexes: /* @__PURE__ */ new Set() };
3499
- this.started.set(id, st);
3500
- this.emit(
3501
- "messages",
3502
- {
3503
- event: "message-start",
3504
- role: roleOf(chunk.type),
3505
- id,
3506
- ...chunk.tool_call_id ? { tool_call_id: chunk.tool_call_id } : {}
3507
- },
3508
- node
3509
- );
3510
- }
3511
- const text = contentToText(chunk.content);
3512
- if (text) {
3513
- if (!st.textBlockStarted) {
3514
- st.textBlockStarted = true;
3515
- this.emit("messages", { event: "content-block-start", index: 0, content: { type: "text", text: "" } }, node);
3516
- }
3517
- this.emit("messages", { event: "content-block-delta", index: 0, delta: { type: "text-delta", text } }, node);
3518
- }
3519
- const tccs = chunk.tool_call_chunks ?? [];
3520
- tccs.forEach((tc, i) => {
3521
- if (!tc) return;
3522
- const index = 1 + i;
3523
- if (!st.toolBlockIndexes.has(index)) {
3524
- st.toolBlockIndexes.add(index);
3525
- this.emit(
3526
- "messages",
3527
- {
3528
- event: "content-block-start",
3529
- index,
3530
- content: { type: "tool_call_chunk", id: tc.id, name: tc.name ?? "", args: "" }
3531
- },
3532
- node
3533
- );
3534
- }
3535
- if (tc.args) {
3536
- this.emit(
3537
- "messages",
3538
- { event: "content-block-delta", index, delta: { type: "tool-call-delta", args: tc.args } },
3539
- node
3540
- );
3541
- }
3542
- });
3543
- }
3544
- /** 产出一条未编号的协议事件(编号由事件中枢统一分配) */
3545
- emit(method, data, node) {
3546
- this.push({
3547
- type: "event",
3548
- method,
3549
- params: {
3550
- namespace: [],
3551
- timestamp: Date.now(),
3552
- ...node ? { node } : {},
3553
- data
3554
- }
3555
- });
3556
- }
3557
- };
3558
- function roleOf(type) {
3559
- const t = (type ?? "").toLowerCase();
3560
- if (t.includes("human")) return "human";
3561
- if (t.includes("system")) return "system";
3562
- if (t.includes("tool")) return "tool";
3563
- return "ai";
3564
- }
3565
- function contentToText(content) {
3566
- if (typeof content === "string") return content;
3567
- if (!Array.isArray(content)) return "";
3568
- return content.map((b) => typeof b === "string" ? b : b?.text ?? b?.content ?? "").filter(Boolean).join("");
3569
- }
3570
-
3571
- // src/bridge/history.ts
3572
- var PAGE_LIMIT = 200;
3573
- var MAX_PAGES = 50;
3574
- async function fetchAllPageMessages(apiUrl, threadId, buildHeaders, fetchImpl) {
3575
- const newerPages = [];
3576
- let beforeSeq;
3577
- for (let i = 0; i < MAX_PAGES; i++) {
3578
- const params = new URLSearchParams({ limit: String(PAGE_LIMIT) });
3579
- if (beforeSeq !== void 0) params.set("before_seq", String(beforeSeq));
3580
- const res = await fetchImpl(`${apiUrl}/threads/${threadId}/messages/page?${params.toString()}`, {
3581
- method: "GET",
3582
- headers: { "Content-Type": "application/json", Accept: "application/json", ...await buildHeaders() },
3583
- credentials: "include"
3584
- });
3585
- if (!res.ok) break;
3586
- const payload = await res.json();
3587
- const rows = (Array.isArray(payload) ? payload : payload?.messages ?? payload?.data) ?? [];
3588
- const pageMessages = runMessagesToMessages(
3589
- rows.map(toRunMessage).filter((m) => m !== null)
3590
- );
3591
- newerPages.push(pageMessages);
3592
- if (!payload?.has_more || payload.next_before_seq === void 0) break;
3593
- beforeSeq = payload.next_before_seq;
3594
- }
3595
- return newerPages.reverse().flat();
3596
- }
3597
-
3598
- // src/bridge/run-stream.ts
3599
- async function startRunStream(host, command, opts) {
3600
- const params = command.params ?? {};
3601
- const assistantId = params.assistant_id && params.assistant_id !== "_" ? params.assistant_id : opts.assistantId;
3602
- const body = {
3603
- assistant_id: assistantId,
3604
- // v1 公开流模式:values 为权威状态、messages-tuple 为 token 增量、custom 为进度
3605
- stream_mode: ["values", "messages-tuple", "custom"],
3606
- // 断开(刷新/断网)后 run 在后端继续执行。⚠️ 后端缺省 cancel(run_models.py:
3607
- // on_disconnect 默认 "cancel"),不传会在 SSE 断开时中断 run——刷新后 join 只能拿
3608
- // 到 end 帧。调用方 submitOptions.onDisconnect 会被 SDK v2 submit 链丢弃(自定义
3609
- // transport 通道不识别该字段),故在此固定补上(对齐旧 v1 管道 sse.ts 语义)。
3610
- on_disconnect: "continue",
3611
- // ⚠️ 不传 stream_resumable:后端仅接受 False/None,显式 True 会被 400 拒绝
3612
- //(run_models.py reject_resumable_streams 校验器)。
3613
- ...params.config ? { config: params.config } : {}
3614
- };
3615
- if (opts.isResume)
3616
- body.command = { resume: opts.explicitResume !== void 0 ? opts.explicitResume : params.input ?? null };
3617
- else body.input = params.input;
3618
- const ac = host.replaceAbort();
3619
- try {
3620
- const reader = await host.readerFactory({
3621
- url: opts.url,
3622
- method: "POST",
3623
- headers: { "Content-Type": "application/json", ...await host.buildHeaders() },
3624
- body,
3625
- signal: ac.signal
3626
- });
3627
- if (host.isDisposed()) {
3628
- await reader.cancel().catch(() => {
3629
- });
3630
- return { type: "success", id: command.id, result: {} };
3631
- }
3632
- const location = reader.headers?.get("Content-Location") ?? "";
3633
- const runId = location ? location.split("/").pop() ?? "" : "";
3634
- if (runId) host.setRunId(runId);
3635
- host.lifecycle("running");
3636
- void pumpRunStream(host, reader, ac, opts.isResume);
3637
- return { type: "success", id: command.id, result: runId ? { run_id: runId } : {} };
3638
- } catch (e) {
3639
- if (ac.signal.aborted) return { type: "success", id: command.id, result: {} };
3640
- return host.cmdError(command.id, `runs/stream \u8BF7\u6C42\u5931\u8D25\uFF1A${e?.message ?? e}`);
3641
- }
3642
- }
3643
- async function pumpRunStream(host, reader, ac, wasResume) {
3644
- const translator = new V1FrameTranslator({
3645
- push: (event) => host.publish(event),
3646
- // G10:首帧 metadata 的 run_id 权威(Content-Location 缺失时兜底)
3647
- onMetadata: (meta) => {
3648
- const runId = meta?.run_id;
3649
- if (typeof runId === "string" && runId) host.setRunIdIfEmpty(runId);
3650
- }
3651
- });
3652
- try {
3653
- for await (const frame of parseSseFrames(reader)) {
3654
- if (frame.event === "values" && host.onValuesFrame) {
3655
- try {
3656
- const raw = frame.data ? JSON.parse(frame.data) : void 0;
3657
- if (raw && typeof raw === "object") host.onValuesFrame(raw);
3658
- } catch {
3659
- }
3660
- }
3661
- translator.handleFrame(frame.event, frame.data);
3662
- if (frame.event === "end") break;
3663
- }
3664
- } catch (e) {
3665
- if (!ac.signal.aborted) host.lifecycle("failed", String(e?.message ?? e));
3666
- return;
3667
- }
3668
- if (translator.interrupted) host.setInterrupted();
3669
- else if (!wasResume) host.clearInterrupted();
3670
- host.clearAbort(ac);
3671
- }
3672
-
3673
- // src/bridge/adapter.ts
3674
- var _boundThreadId, _getThreadId, _lastRunId;
3675
- var DeerFlowBridgeAdapter = class {
3676
- constructor(options) {
3677
- __privateAdd(this, _boundThreadId, "");
3678
- __privateAdd(this, _getThreadId);
3679
- __privateAdd(this, _lastRunId, "");
3680
- /** 已确认存在的 thread(避免重复预创建) */
3681
- this.knownThreads = /* @__PURE__ */ new Set();
3682
- /** 线程处于 interrupt 待恢复态:下一个 run.start / input.respond 按 resume 翻译 */
3683
- this.interrupted = false;
3684
- this.activeAbort = null;
3685
- this.disposed = false;
3686
- this.apiUrl = options.apiUrl.replace(/\/$/, "");
3687
- this.assistantId = options.assistantId;
3688
- this.buildHeaders = options.buildHeaders;
3689
- this.fetchImpl = options.fetchImpl;
3690
- this.onValuesFrame = options.onValuesFrame;
3691
- this.onRunId = options.onRunId;
3692
- __privateSet(this, _getThreadId, options.getThreadId);
3693
- this.hub = createEventHub();
3694
- this.streamHost = {
3695
- buildHeaders: () => this.buildHeaders(),
3696
- readerFactory: options.readerFactory ?? createFetchReaderFactory(options.fetchImpl),
3697
- onValuesFrame: this.onValuesFrame,
3698
- publish: (event) => this.hub.publish(event),
3699
- lifecycle: (event, error) => this.lifecycle(event, error),
3700
- setRunId: (runId) => {
3701
- __privateSet(this, _lastRunId, runId);
3702
- this.onRunId?.(runId);
3703
- },
3704
- setRunIdIfEmpty: (runId) => {
3705
- if (!__privateGet(this, _lastRunId)) {
3706
- __privateSet(this, _lastRunId, runId);
3707
- this.onRunId?.(runId);
3708
- }
3709
- },
3710
- setInterrupted: () => {
3711
- this.interrupted = true;
3712
- },
3713
- clearInterrupted: () => {
3714
- this.interrupted = false;
3715
- },
3716
- isDisposed: () => this.disposed,
3717
- replaceAbort: () => {
3718
- this.activeAbort?.abort();
3719
- const ac = new AbortController();
3720
- this.activeAbort = ac;
3721
- return ac;
3722
- },
3723
- clearAbort: (ac) => {
3724
- if (this.activeAbort === ac) this.activeAbort = null;
3725
- },
3726
- cmdError: (id, message, error) => this.cmdError(id, message, error)
3727
- };
3728
- }
3729
- /** 当前生效的 threadId:外部 getter 优先(hydrate 早于 transport 绑定),setThreadId 兜底 */
3730
- get threadId() {
3731
- return __privateGet(this, _getThreadId).call(this) || __privateGet(this, _boundThreadId);
3732
- }
3733
- /** metadata 帧记录的 run_id(首帧权威,G10;Content-Location 优先时两者一致) */
3734
- get lastRunId() {
3735
- return __privateGet(this, _lastRunId);
3736
- }
3737
- /** 线程是否处于 interrupt 待恢复态(下一次 send 自动走 command.resume;观测/测试用) */
3738
- get isInterrupted() {
3739
- return this.interrupted;
3740
- }
3741
- /** {@inheritDoc TransportAdapter.setThreadId} */
3742
- setThreadId(threadId) {
3743
- __privateSet(this, _boundThreadId, threadId);
3744
- }
3745
- /** HTTP/SSE 传输无握手 */
3746
- open() {
3747
- return Promise.resolve();
3748
- }
3749
- /** 释放资源:断开进行中的 SSE,关闭事件中枢(唤醒挂起订阅) */
3750
- close() {
3751
- this.disposed = true;
3752
- this.activeAbort?.abort();
3753
- this.hub.close();
3754
- return Promise.resolve();
3755
- }
3756
- /** SSE 模式下 events() 为空流,真实投递走 openEventStream */
3757
- async *events() {
3758
- }
3759
- /** 发送协议命令:run.start / input.respond → v1 runs.stream,其余拒绝 */
3760
- async send(command) {
3761
- switch (command.method) {
3762
- case "run.start":
3763
- return this.startRun(command, this.interrupted);
3764
- case "input.respond": {
3765
- const p = command.params ?? {};
3766
- const resume = Array.isArray(p.responses) ? p.responses[0]?.response : p.response;
3767
- this.interrupted = false;
3768
- return this.startRun(command, true, resume);
3769
- }
3770
- default:
3771
- return this.cmdError(command.id, `deer-flow v1 \u6865\u63A5\u6682\u4E0D\u652F\u6301\u547D\u4EE4\uFF1A${command.method}`, "not_supported");
3772
- }
3773
- }
3774
- /** 打开订阅流:事件中枢重放缓冲全量回放后实时推送 */
3775
- openEventStream(_params) {
3776
- return this.hub.open();
3777
- }
3778
- /** hydrate 用:/state 与 messages/page 全量并发;messages 以 state 为基准(语义字段全),
3779
- * page(run-event 全量投影)补齐压缩缺失的头部/尾部——与 transport 的
3780
- * fetchThreadInitialValues 同一合并函数,保证 SDK getState 快照与物化器基线一致
3781
- * (不一致会让 watch(stream.messages) 的 diff 把快照差异误追加到对话尾部) */
3782
- async getState() {
3783
- if (!this.threadId) return null;
3784
- try {
3785
- const [res, pageMessages] = await Promise.all([
3786
- this.request(`/threads/${this.threadId}/state`, { method: "GET" }),
3787
- fetchAllPageMessages(this.apiUrl, this.threadId, this.buildHeaders, this.fetchImpl).catch(() => [])
3788
- ]);
3789
- if (!res.ok) return null;
3790
- const json = await res.json();
3791
- const values = { ...json.values ?? {} };
3792
- const stateMessages = extractStateMessages(json);
3793
- if (stateMessages.length > 0 || pageMessages.length > 0) {
3794
- values.messages = mergeStateWithPageMessages(stateMessages, pageMessages);
3795
- }
3796
- if (Array.isArray(values.__interrupt__) && values.__interrupt__.length > 0) {
3797
- this.interrupted = true;
3798
- delete values.__interrupt__;
3799
- }
3800
- if (Array.isArray(json.tasks) && json.tasks.some((t) => Array.isArray(t?.interrupts) && t.interrupts.length > 0))
3801
- this.interrupted = true;
3802
- return { values, tasks: json.tasks, next: json.next, checkpoint: null };
3803
- } catch {
3804
- return null;
3805
- }
3806
- }
3807
- // ---- 内部实现 ----
3808
- /** run.start / input.respond 落点:预创建 thread 后交 run-stream 打开 SSE 泵帧 */
3809
- async startRun(command, isResume, explicitResume) {
3810
- await this.ensureThread(this.threadId);
3811
- return startRunStream(this.streamHost, command, {
3812
- url: `${this.apiUrl}/threads/${this.threadId}/runs/stream`,
3813
- assistantId: this.assistantId,
3814
- isResume,
3815
- ...explicitResume !== void 0 ? { explicitResume } : {}
3816
- });
3817
- }
3818
- /** 统一 REST 请求入口:注入鉴权头 + cookie */
3819
- async request(path, init = {}) {
3820
- const headers = await this.buildHeaders();
3821
- return this.fetchImpl(this.apiUrl + path, {
3822
- ...init,
3823
- headers: { "Content-Type": "application/json", ...headers },
3824
- credentials: "include"
3825
- });
3826
- }
3827
- /** 预创建 thread(deer-flow POST /threads 支持客户端指定 id 且幂等) */
3828
- async ensureThread(threadId) {
3829
- if (!threadId || this.knownThreads.has(threadId)) return;
3830
- try {
3831
- const res = await this.request("/threads", {
3832
- method: "POST",
3833
- body: JSON.stringify({ thread_id: threadId, metadata: {} })
3834
- });
3835
- if (res.ok) this.knownThreads.add(threadId);
3836
- } catch {
3837
- }
3838
- }
3839
- /** 构造命令错误应答 */
3840
- cmdError(id, message, error = "unknown_error") {
3841
- return { type: "error", id, message, error };
3842
- }
3843
- /** 推送 lifecycle 事件(running / failed) */
3844
- lifecycle(event, error) {
3845
- const data = error ? { event, error } : { event };
3846
- this.hub.publish({ type: "event", method: "lifecycle", params: { namespace: [], timestamp: Date.now(), data } });
3847
- }
3848
- };
3849
- _boundThreadId = new WeakMap();
3850
- _getThreadId = new WeakMap();
3851
- _lastRunId = new WeakMap();
3852
-
3853
3003
  // src/test-utils/mockTransport.ts
3854
- var import_vue9 = require("vue");
3004
+ var import_vue7 = require("vue");
3855
3005
  var mockThreadSeq = 0;
3856
3006
  function createMockTransport() {
3857
3007
  const threads = [];
@@ -3859,6 +3009,7 @@ function createMockTransport() {
3859
3009
  const messagesPagesMap = /* @__PURE__ */ new Map();
3860
3010
  const tokenUsageMap = /* @__PURE__ */ new Map();
3861
3011
  const artifactContentMap = /* @__PURE__ */ new Map();
3012
+ const resumeErrorMap = /* @__PURE__ */ new Map();
3862
3013
  const handles = /* @__PURE__ */ new Map();
3863
3014
  const optionsMap = /* @__PURE__ */ new Map();
3864
3015
  const calls = { submit: [], resumeInterrupt: [], stop: [], joinStream: [], cancel: [] };
@@ -3942,13 +3093,15 @@ function createMockTransport() {
3942
3093
  return content;
3943
3094
  },
3944
3095
  createStream(options) {
3945
- const isLoading = (0, import_vue9.ref)(false);
3946
- const error = (0, import_vue9.ref)(null);
3096
+ const isLoading = (0, import_vue7.ref)(false);
3097
+ const error = (0, import_vue7.ref)(null);
3098
+ const interrupt = (0, import_vue7.ref)(void 0);
3947
3099
  const threadId = options.threadId;
3948
3100
  optionsMap.set(threadId, options);
3949
3101
  const handle = {
3950
3102
  isLoading,
3951
3103
  error,
3104
+ interrupt,
3952
3105
  submit(input, submitOptions) {
3953
3106
  calls.submit.push({ threadId, input, options: submitOptions });
3954
3107
  },
@@ -3961,6 +3114,8 @@ function createMockTransport() {
3961
3114
  },
3962
3115
  async resumeInterrupt(decisions) {
3963
3116
  calls.resumeInterrupt.push({ threadId, decisions });
3117
+ const err = resumeErrorMap.get(threadId)?.shift();
3118
+ if (err) throw err;
3964
3119
  }
3965
3120
  };
3966
3121
  handles.set(threadId, {
@@ -3971,12 +3126,12 @@ function createMockTransport() {
3971
3126
  isLoading.value = snapshot.isLoading;
3972
3127
  if (!snapshot.isLoading) ended = true;
3973
3128
  }
3974
- if (snapshot.values !== void 0 || snapshot.messages !== void 0 || "interrupt" in snapshot) {
3129
+ if (snapshot.values !== void 0 || snapshot.messages !== void 0) {
3975
3130
  const data = { ...snapshot.values ?? {} };
3976
3131
  if (snapshot.messages !== void 0) data.messages = snapshot.messages;
3977
- if ("interrupt" in snapshot) data.__interrupt__ = snapshot.interrupt ? [snapshot.interrupt] : [];
3978
3132
  options.onValuesEvent?.(data);
3979
3133
  }
3134
+ if ("interrupt" in snapshot) interrupt.value = snapshot.interrupt;
3980
3135
  if (ended) options.onStreamEnd?.();
3981
3136
  }
3982
3137
  });
@@ -4009,6 +3164,14 @@ function createMockTransport() {
4009
3164
  ;
4010
3165
  entry.handle.error.value = err;
4011
3166
  },
3167
+ __setResumeError(threadId, err) {
3168
+ let queue = resumeErrorMap.get(threadId);
3169
+ if (!queue) {
3170
+ queue = [];
3171
+ resumeErrorMap.set(threadId, queue);
3172
+ }
3173
+ queue.push(err);
3174
+ },
4012
3175
  __setInitialValues(threadId, values) {
4013
3176
  initialValuesMap.set(threadId, values);
4014
3177
  },
@@ -4031,20 +3194,20 @@ function createMockTransport() {
4031
3194
  }
4032
3195
 
4033
3196
  // src/index.ts
4034
- var CORE_VERSION = "2.0.0";
3197
+ var CORE_VERSION = "2.1.0";
4035
3198
  // Annotate the CommonJS export names for ESM import in node:
4036
3199
  0 && (module.exports = {
4037
3200
  CORE_VERSION,
4038
3201
  DEFAULT_ASSISTANT_ID,
4039
3202
  DEFAULT_MAX_CACHED_SESSIONS,
4040
3203
  DEFAULT_MAX_CONCURRENT_STREAMS,
4041
- DeerFlowBridgeAdapter,
4042
3204
  INJECTED_TAGS,
4043
3205
  MESSAGE_TYPE_NORMALIZE,
4044
3206
  OUTLINE_MAX_LEVEL,
4045
3207
  ThreadDirectory,
4046
- V1FrameTranslator,
4047
3208
  applySemanticPatches,
3209
+ asArgsObject,
3210
+ assembleRun,
4048
3211
  backfillRunMessageFeedback,
4049
3212
  buildArtifactFiles,
4050
3213
  buildHitlDecisions,
@@ -4055,19 +3218,16 @@ var CORE_VERSION = "2.0.0";
4055
3218
  buildReportOutlinePayload,
4056
3219
  buildRunDirectLatencyMs,
4057
3220
  buildRunInfo,
3221
+ buildRunMeta,
4058
3222
  collectTextKeepSxin,
4059
3223
  collectVisibleText,
4060
3224
  createChatCore,
4061
3225
  createEmptySubChapter,
4062
- createEventHub,
4063
- createFetchReaderFactory,
4064
- createMaterializer,
4065
- createMessageDiff,
4066
3226
  createMockTransport,
4067
- createRuntimeMaterializer,
4068
3227
  createSemanticOverlay,
4069
3228
  createThreadRuntime,
4070
3229
  deriveToolsFromMessages,
3230
+ emptyRunItem,
4071
3231
  ensureOutlineContentThemes,
4072
3232
  ensureRunningRun,
4073
3233
  extractAiContentFromMessage,
@@ -4076,6 +3236,7 @@ var CORE_VERSION = "2.0.0";
4076
3236
  extractCitationAnchors,
4077
3237
  extractCitationAnchorsFromSpec,
4078
3238
  extractFromToolResult,
3239
+ extractInputFromRows,
4079
3240
  extractReportTitleFromBody,
4080
3241
  extractRunEnrichment,
4081
3242
  extractSemanticPatchesFromMessages,
@@ -4084,7 +3245,6 @@ var CORE_VERSION = "2.0.0";
4084
3245
  extractThreadInfo,
4085
3246
  extractTitleFromArtifactPath,
4086
3247
  extractUserMessageTexts,
4087
- fetchAllPageMessages,
4088
3248
  formatAnswerText,
4089
3249
  formatStr,
4090
3250
  genBlockId,
@@ -4092,6 +3252,7 @@ var CORE_VERSION = "2.0.0";
4092
3252
  getAllowedDecisions,
4093
3253
  getHumanMessageBaseId,
4094
3254
  getToolCallArtifactMeta,
3255
+ groupRowsByRun,
4095
3256
  isAiMessage,
4096
3257
  isHiddenUserMessage,
4097
3258
  isHumanMessage,
@@ -4099,8 +3260,10 @@ var CORE_VERSION = "2.0.0";
4099
3260
  isReportBodyHtml,
4100
3261
  isSameArgs,
4101
3262
  isToolMessage,
3263
+ isUserEchoRow,
4102
3264
  isVisibleUserMessage,
4103
3265
  isWriteFileToolName,
3266
+ mapBackendStatus,
4104
3267
  mergeStateWithPageMessages,
4105
3268
  normalizeForCompare,
4106
3269
  normalizeMessageType,
@@ -4110,10 +3273,12 @@ var CORE_VERSION = "2.0.0";
4110
3273
  parseHumanMessageId,
4111
3274
  parseKnowledgeItemsFromValue,
4112
3275
  parseMarkdownToOutline,
4113
- parseSseFrames,
3276
+ pickRicherArgs,
4114
3277
  pickRunMessageMetadata,
3278
+ projectRuns,
4115
3279
  readMessageContentText,
4116
3280
  resolveReportArtifactKind,
3281
+ rowMessageId,
4117
3282
  runMessagesToMessages,
4118
3283
  simpleHash,
4119
3284
  sliceBodySegments,