@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.mjs CHANGED
@@ -6,28 +6,30 @@ import {
6
6
  MESSAGE_TYPE_NORMALIZE,
7
7
  OUTLINE_MAX_LEVEL,
8
8
  ThreadDirectory,
9
- __privateAdd,
10
- __privateGet,
11
- __privateSet,
12
9
  applySemanticPatches,
10
+ asArgsObject,
11
+ assembleRun,
13
12
  backfillRunMessageFeedback,
13
+ buildHitlDecisions,
14
14
  buildHumanInputResponse,
15
+ buildInterruptReviewBlock,
16
+ buildRejectDecisions,
15
17
  buildRunDirectLatencyMs,
16
18
  buildRunInfo,
19
+ buildRunMeta,
17
20
  collectTextKeepSxin,
18
21
  collectVisibleText,
19
22
  createChatCore,
20
23
  createEmptySubChapter,
21
- createMaterializer,
22
- createMessageDiff,
23
- createRuntimeMaterializer,
24
24
  createSemanticOverlay,
25
25
  createThreadRuntime,
26
26
  deriveToolsFromMessages,
27
+ emptyRunItem,
27
28
  ensureOutlineContentThemes,
28
29
  ensureRunningRun,
29
30
  extractAiContentFromMessage,
30
31
  extractFromToolResult,
32
+ extractInputFromRows,
31
33
  extractReportTitleFromBody,
32
34
  extractRunEnrichment,
33
35
  extractSemanticPatchesFromMessages,
@@ -38,25 +40,37 @@ import {
38
40
  extractUserMessageTexts,
39
41
  formatAnswerText,
40
42
  formatStr,
43
+ genBlockId,
44
+ genMessageId,
45
+ getAllowedDecisions,
41
46
  getHumanMessageBaseId,
42
47
  getToolCallArtifactMeta,
48
+ groupRowsByRun,
43
49
  isAiMessage,
44
50
  isHiddenUserMessage,
45
51
  isHumanMessage,
46
52
  isInjectedElement,
47
53
  isReportBodyHtml,
54
+ isSameArgs,
48
55
  isToolMessage,
56
+ isUserEchoRow,
49
57
  isVisibleUserMessage,
50
58
  isWriteFileToolName,
59
+ mapBackendStatus,
51
60
  mergeStateWithPageMessages,
61
+ normalizeForCompare,
52
62
  normalizeMessageType,
53
63
  normalizeOutline,
54
64
  normalizeUsage,
65
+ parseHitlPayload,
55
66
  parseHumanMessageId,
56
67
  parseMarkdownToOutline,
68
+ pickRicherArgs,
57
69
  pickRunMessageMetadata,
70
+ projectRuns,
58
71
  readMessageContentText,
59
72
  resolveReportArtifactKind,
73
+ rowMessageId,
60
74
  runMessagesToMessages,
61
75
  simpleHash,
62
76
  sliceBodySegments,
@@ -64,7 +78,7 @@ import {
64
78
  toRunMessage,
65
79
  tokenizeSxin,
66
80
  validateOutline
67
- } from "./chunk-Z65C2UII.mjs";
81
+ } from "./chunk-2AXUXZVK.mjs";
68
82
 
69
83
  // src/parser/citation.ts
70
84
  var toStringArray = (v) => {
@@ -223,72 +237,6 @@ function parseKnowledgeItemsFromValue(value) {
223
237
  return result;
224
238
  }
225
239
 
226
- // src/parser/hitl.ts
227
- import { isEqual } from "lodash";
228
-
229
- // src/parser/message-id.ts
230
- var _idSeq = 0;
231
- function genMessageId() {
232
- return `msg-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
233
- }
234
- function genBlockId() {
235
- return `block-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
236
- }
237
-
238
- // src/parser/hitl.ts
239
- function parseHitlPayload(value) {
240
- if (!value || typeof value !== "object") return null;
241
- const raw = value;
242
- const requests = raw.actionRequests ?? raw.action_requests;
243
- if (!Array.isArray(requests) || !requests.length) return null;
244
- const configs = raw.reviewConfigs ?? raw.review_configs;
245
- return {
246
- actionRequests: requests,
247
- reviewConfigs: Array.isArray(configs) ? configs : []
248
- };
249
- }
250
- function getAllowedDecisions(configs, actionName) {
251
- const cfg = configs.find((c) => c.action_name === actionName);
252
- const list = cfg?.allowedDecisions ?? cfg?.allowed_decisions;
253
- return list?.length ? list : ["approve", "reject"];
254
- }
255
- function normalizeForCompare(value) {
256
- if (Array.isArray(value)) return value.map(normalizeForCompare);
257
- if (value && typeof value === "object") {
258
- return Object.keys(value).sort().reduce((acc, key) => {
259
- acc[key] = normalizeForCompare(value[key]);
260
- return acc;
261
- }, {});
262
- }
263
- return value;
264
- }
265
- function isSameArgs(a, b) {
266
- return isEqual(normalizeForCompare(a), normalizeForCompare(b));
267
- }
268
- function buildHitlDecisions(requests, currentArgsList) {
269
- return requests.map((req, i) => {
270
- const current = currentArgsList[i];
271
- if (!current || isSameArgs(req.args, current)) return { type: "approve" };
272
- return { type: "edit", edited_action: { name: req.name, args: current } };
273
- });
274
- }
275
- function buildRejectDecisions(requests) {
276
- return requests.map(() => ({ type: "reject" }));
277
- }
278
- function buildInterruptReviewBlock(interrupt, responded) {
279
- const payload = parseHitlPayload(interrupt.value);
280
- if (!payload) return null;
281
- const interruptId = String(interrupt.id || genMessageId());
282
- const status = responded ? "completed" : "pending";
283
- return {
284
- id: `interrupt-review-${interruptId}`,
285
- type: "interrupt-review",
286
- status,
287
- payload,
288
- interruptId
289
- };
290
- }
291
-
292
240
  // src/parser/block-build-helper.ts
293
241
  function buildArtifactFiles(paths) {
294
242
  return paths.map((path) => {
@@ -438,610 +386,6 @@ function extractBlocksFromContent(rawText, source) {
438
386
  return extractBlocksFromNodes(tokenizeSxin(rawText), rawText, source);
439
387
  }
440
388
 
441
- // src/bridge/sse.ts
442
- function createFetchReaderFactory(fetchImpl = fetch) {
443
- return async (req) => {
444
- const res = await fetchImpl(req.url, {
445
- method: req.method,
446
- headers: req.headers,
447
- body: req.body !== void 0 ? JSON.stringify(req.body) : void 0,
448
- signal: req.signal,
449
- credentials: "include"
450
- });
451
- if (!res.ok) throw new Error(`SSE \u8BF7\u6C42\u5931\u8D25 ${res.status}`);
452
- if (!res.body) throw new Error("SSE \u54CD\u5E94\u65E0 body");
453
- const reader = res.body.getReader();
454
- return {
455
- read: () => reader.read(),
456
- cancel: async () => {
457
- reader.releaseLock();
458
- await res.body.cancel().catch(() => {
459
- });
460
- }
461
- };
462
- };
463
- }
464
- async function* parseSseFrames(reader) {
465
- const decoder = new TextDecoder();
466
- let buf = "";
467
- try {
468
- while (true) {
469
- let chunk;
470
- try {
471
- chunk = await reader.read();
472
- } catch (e) {
473
- if (e?.name === "AbortError") break;
474
- throw e;
475
- }
476
- if (chunk.done) break;
477
- buf += typeof chunk.value === "string" ? chunk.value : decoder.decode(chunk.value, { stream: true });
478
- let idx;
479
- while ((idx = buf.search(/\n\n|\r\n\r\n/)) !== -1) {
480
- const raw = buf.slice(0, idx);
481
- buf = buf.slice(idx).replace(/^\r?\n\r?\n/, "");
482
- const frame = parseFrame(raw);
483
- if (frame) yield frame;
484
- }
485
- }
486
- buf += decoder.decode();
487
- const tail = parseFrame(buf);
488
- if (tail) yield tail;
489
- } finally {
490
- await reader.cancel().catch(() => {
491
- });
492
- }
493
- }
494
- function parseFrame(raw) {
495
- if (!raw.trim()) return void 0;
496
- let event = "message";
497
- let id;
498
- const dataLines = [];
499
- for (const line of raw.split(/\r?\n/)) {
500
- if (line.startsWith("event:")) event = line.slice(6).trim();
501
- else if (line.startsWith("id:")) id = line.slice(3).trim();
502
- else if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
503
- }
504
- return { event, id, data: dataLines.join("\n") };
505
- }
506
-
507
- // src/bridge/event-hub.ts
508
- function createEventHub() {
509
- const buffer = [];
510
- const subscribers = /* @__PURE__ */ new Set();
511
- let seq = 0;
512
- let closed = false;
513
- function publish(event) {
514
- if (closed) return;
515
- const n = ++seq;
516
- const framed = { ...event, seq: n, event_id: String(n) };
517
- buffer.push(framed);
518
- for (const sub of subscribers) {
519
- sub.queue.push(framed);
520
- sub.wake?.();
521
- }
522
- }
523
- function open() {
524
- const sub = { queue: [...buffer], wake: null, closed: false };
525
- if (closed) sub.closed = true;
526
- else subscribers.add(sub);
527
- const next = () => {
528
- if (sub.closed) return Promise.resolve({ done: true, value: void 0 });
529
- const queued = sub.queue.shift();
530
- if (queued) return Promise.resolve({ done: false, value: queued });
531
- return new Promise((resolve) => {
532
- sub.wake = () => {
533
- sub.wake = null;
534
- const v = sub.queue.shift();
535
- if (sub.closed || !v) return resolve({ done: true, value: void 0 });
536
- resolve({ done: false, value: v });
537
- };
538
- });
539
- };
540
- const returnFn = () => {
541
- if (!sub.closed) {
542
- sub.closed = true;
543
- subscribers.delete(sub);
544
- sub.wake?.();
545
- }
546
- return Promise.resolve({ done: true, value: void 0 });
547
- };
548
- return {
549
- events: { [Symbol.asyncIterator]: () => ({ next, return: returnFn }) },
550
- ready: Promise.resolve(),
551
- close() {
552
- returnFn();
553
- }
554
- };
555
- }
556
- function close() {
557
- if (closed) return;
558
- closed = true;
559
- for (const sub of subscribers) {
560
- sub.closed = true;
561
- sub.wake?.();
562
- }
563
- subscribers.clear();
564
- }
565
- return {
566
- publish,
567
- open,
568
- close,
569
- get bufferedCount() {
570
- return buffer.length;
571
- }
572
- };
573
- }
574
-
575
- // src/bridge/translate.ts
576
- var V1FrameTranslator = class {
577
- constructor(options) {
578
- /** 当前 run 是否处于 interrupt 待恢复态(end 帧据此选 terminal) */
579
- this.interrupted = false;
580
- this.pendingInterrupts = 0;
581
- this.lastError = null;
582
- /** 已开始消息的组装状态,key = message id */
583
- this.started = /* @__PURE__ */ new Map();
584
- /** tools 通道防重:已合成 tool-started / tool-finished 的 callId(values 帧全量重放,须去重) */
585
- this.toolsStarted = /* @__PURE__ */ new Set();
586
- this.toolsFinished = /* @__PURE__ */ new Set();
587
- this.push = options.push;
588
- this.onMetadata = options.onMetadata;
589
- }
590
- /** 分发一个 v1 SSE 帧 */
591
- handleFrame(event, dataRaw) {
592
- let data;
593
- try {
594
- data = dataRaw ? JSON.parse(dataRaw) : void 0;
595
- } catch {
596
- return;
597
- }
598
- switch (event) {
599
- case "metadata":
600
- if (data && typeof data === "object") this.onMetadata?.(data);
601
- break;
602
- case "values":
603
- this.handleValues(data);
604
- break;
605
- case "messages":
606
- this.handleMessages(data);
607
- break;
608
- case "updates":
609
- if (data && typeof data === "object") {
610
- for (const [node, delta] of Object.entries(data)) {
611
- this.emit("updates", { node, values: delta });
612
- }
613
- }
614
- break;
615
- case "custom":
616
- this.emit("custom", { name: "custom", payload: data });
617
- break;
618
- case "error":
619
- this.lastError = typeof data === "string" ? data : data?.message ?? String(data);
620
- break;
621
- case "end":
622
- this.emit("lifecycle", {
623
- event: this.interrupted ? "interrupted" : this.lastError ? "failed" : "completed",
624
- ...this.lastError ? { error: this.lastError } : {}
625
- });
626
- break;
627
- default:
628
- break;
629
- }
630
- }
631
- /** values 帧:剥离 __interrupt__ → values 事件 + 合成 input.requested + 合成 tools 通道事件 */
632
- handleValues(data) {
633
- if (!data || typeof data !== "object") return;
634
- const values = { ...data };
635
- const interrupts = values.__interrupt__;
636
- if (Array.isArray(interrupts) && interrupts.length > 0) {
637
- delete values.__interrupt__;
638
- this.interrupted = true;
639
- this.pendingInterrupts += interrupts.length;
640
- interrupts.forEach((it, i) => {
641
- this.emit("input.requested", {
642
- // v1 的 Interrupt 无稳定 id,按序号合成;resume 走值语义不依赖该 id
643
- interrupt_id: `intr-${this.pendingInterrupts}-${i}`,
644
- payload: it?.value ?? it
645
- });
646
- });
647
- }
648
- this.emit("values", values);
649
- this.synthesizeTools(values);
650
- }
651
- /**
652
- * 从 values 快照合成 v2 tools 通道事件(toolCalls 投影只认 tool-started/tool-finished):
653
- * - AIMessage.tool_calls(args 已完整)→ tool-started
654
- * - ToolMessage(工具结果)→ tool-finished
655
- * values 每步全量重放,必须按 callId 防重;AI 消息在 tool 消息之前,顺序天然满足。
656
- */
657
- synthesizeTools(values) {
658
- const messages = Array.isArray(values.messages) ? values.messages : [];
659
- for (const m of messages) {
660
- if (!m || typeof m !== "object") continue;
661
- const toolCalls = Array.isArray(m.tool_calls) ? m.tool_calls : [];
662
- for (const tc of toolCalls) {
663
- const callId2 = tc?.id;
664
- if (!callId2 || this.toolsStarted.has(callId2)) continue;
665
- this.toolsStarted.add(callId2);
666
- this.emit("tools", {
667
- event: "tool-started",
668
- tool_call_id: String(callId2),
669
- tool_name: String(tc?.name ?? ""),
670
- input: tc?.args
671
- });
672
- }
673
- const callId = m.tool_call_id;
674
- if (m.type === "tool" && typeof callId === "string" && callId && !this.toolsFinished.has(callId)) {
675
- this.toolsFinished.add(callId);
676
- this.emit("tools", { event: "tool-finished", tool_call_id: callId, output: contentToText(m.content) });
677
- }
678
- }
679
- }
680
- /** messages 帧:增量 chunk → message-start(一次) + content-block 事件序列 */
681
- handleMessages(tuple) {
682
- const chunk = tuple?.[0];
683
- if (!chunk) return;
684
- if (String(chunk.type || "").toLowerCase() === "remove") return;
685
- const node = tuple?.[1]?.langgraph_node;
686
- const id = chunk.id;
687
- if (!id) return;
688
- let st = this.started.get(id);
689
- if (!st) {
690
- st = { textBlockStarted: false, toolBlockIndexes: /* @__PURE__ */ new Set() };
691
- this.started.set(id, st);
692
- this.emit(
693
- "messages",
694
- {
695
- event: "message-start",
696
- role: roleOf(chunk.type),
697
- id,
698
- ...chunk.tool_call_id ? { tool_call_id: chunk.tool_call_id } : {}
699
- },
700
- node
701
- );
702
- }
703
- const text = contentToText(chunk.content);
704
- if (text) {
705
- if (!st.textBlockStarted) {
706
- st.textBlockStarted = true;
707
- this.emit("messages", { event: "content-block-start", index: 0, content: { type: "text", text: "" } }, node);
708
- }
709
- this.emit("messages", { event: "content-block-delta", index: 0, delta: { type: "text-delta", text } }, node);
710
- }
711
- const tccs = chunk.tool_call_chunks ?? [];
712
- tccs.forEach((tc, i) => {
713
- if (!tc) return;
714
- const index = 1 + i;
715
- if (!st.toolBlockIndexes.has(index)) {
716
- st.toolBlockIndexes.add(index);
717
- this.emit(
718
- "messages",
719
- {
720
- event: "content-block-start",
721
- index,
722
- content: { type: "tool_call_chunk", id: tc.id, name: tc.name ?? "", args: "" }
723
- },
724
- node
725
- );
726
- }
727
- if (tc.args) {
728
- this.emit(
729
- "messages",
730
- { event: "content-block-delta", index, delta: { type: "tool-call-delta", args: tc.args } },
731
- node
732
- );
733
- }
734
- });
735
- }
736
- /** 产出一条未编号的协议事件(编号由事件中枢统一分配) */
737
- emit(method, data, node) {
738
- this.push({
739
- type: "event",
740
- method,
741
- params: {
742
- namespace: [],
743
- timestamp: Date.now(),
744
- ...node ? { node } : {},
745
- data
746
- }
747
- });
748
- }
749
- };
750
- function roleOf(type) {
751
- const t = (type ?? "").toLowerCase();
752
- if (t.includes("human")) return "human";
753
- if (t.includes("system")) return "system";
754
- if (t.includes("tool")) return "tool";
755
- return "ai";
756
- }
757
- function contentToText(content) {
758
- if (typeof content === "string") return content;
759
- if (!Array.isArray(content)) return "";
760
- return content.map((b) => typeof b === "string" ? b : b?.text ?? b?.content ?? "").filter(Boolean).join("");
761
- }
762
-
763
- // src/bridge/history.ts
764
- var PAGE_LIMIT = 200;
765
- var MAX_PAGES = 50;
766
- async function fetchAllPageMessages(apiUrl, threadId, buildHeaders, fetchImpl) {
767
- const newerPages = [];
768
- let beforeSeq;
769
- for (let i = 0; i < MAX_PAGES; i++) {
770
- const params = new URLSearchParams({ limit: String(PAGE_LIMIT) });
771
- if (beforeSeq !== void 0) params.set("before_seq", String(beforeSeq));
772
- const res = await fetchImpl(`${apiUrl}/threads/${threadId}/messages/page?${params.toString()}`, {
773
- method: "GET",
774
- headers: { "Content-Type": "application/json", Accept: "application/json", ...await buildHeaders() },
775
- credentials: "include"
776
- });
777
- if (!res.ok) break;
778
- const payload = await res.json();
779
- const rows = (Array.isArray(payload) ? payload : payload?.messages ?? payload?.data) ?? [];
780
- const pageMessages = runMessagesToMessages(
781
- rows.map(toRunMessage).filter((m) => m !== null)
782
- );
783
- newerPages.push(pageMessages);
784
- if (!payload?.has_more || payload.next_before_seq === void 0) break;
785
- beforeSeq = payload.next_before_seq;
786
- }
787
- return newerPages.reverse().flat();
788
- }
789
-
790
- // src/bridge/run-stream.ts
791
- async function startRunStream(host, command, opts) {
792
- const params = command.params ?? {};
793
- const assistantId = params.assistant_id && params.assistant_id !== "_" ? params.assistant_id : opts.assistantId;
794
- const body = {
795
- assistant_id: assistantId,
796
- // v1 公开流模式:values 为权威状态、messages-tuple 为 token 增量、custom 为进度
797
- stream_mode: ["values", "messages-tuple", "custom"],
798
- // 断开(刷新/断网)后 run 在后端继续执行。⚠️ 后端缺省 cancel(run_models.py:
799
- // on_disconnect 默认 "cancel"),不传会在 SSE 断开时中断 run——刷新后 join 只能拿
800
- // 到 end 帧。调用方 submitOptions.onDisconnect 会被 SDK v2 submit 链丢弃(自定义
801
- // transport 通道不识别该字段),故在此固定补上(对齐旧 v1 管道 sse.ts 语义)。
802
- on_disconnect: "continue",
803
- // ⚠️ 不传 stream_resumable:后端仅接受 False/None,显式 True 会被 400 拒绝
804
- //(run_models.py reject_resumable_streams 校验器)。
805
- ...params.config ? { config: params.config } : {}
806
- };
807
- if (opts.isResume)
808
- body.command = { resume: opts.explicitResume !== void 0 ? opts.explicitResume : params.input ?? null };
809
- else body.input = params.input;
810
- const ac = host.replaceAbort();
811
- try {
812
- const reader = await host.readerFactory({
813
- url: opts.url,
814
- method: "POST",
815
- headers: { "Content-Type": "application/json", ...await host.buildHeaders() },
816
- body,
817
- signal: ac.signal
818
- });
819
- if (host.isDisposed()) {
820
- await reader.cancel().catch(() => {
821
- });
822
- return { type: "success", id: command.id, result: {} };
823
- }
824
- const location = reader.headers?.get("Content-Location") ?? "";
825
- const runId = location ? location.split("/").pop() ?? "" : "";
826
- if (runId) host.setRunId(runId);
827
- host.lifecycle("running");
828
- void pumpRunStream(host, reader, ac, opts.isResume);
829
- return { type: "success", id: command.id, result: runId ? { run_id: runId } : {} };
830
- } catch (e) {
831
- if (ac.signal.aborted) return { type: "success", id: command.id, result: {} };
832
- return host.cmdError(command.id, `runs/stream \u8BF7\u6C42\u5931\u8D25\uFF1A${e?.message ?? e}`);
833
- }
834
- }
835
- async function pumpRunStream(host, reader, ac, wasResume) {
836
- const translator = new V1FrameTranslator({
837
- push: (event) => host.publish(event),
838
- // G10:首帧 metadata 的 run_id 权威(Content-Location 缺失时兜底)
839
- onMetadata: (meta) => {
840
- const runId = meta?.run_id;
841
- if (typeof runId === "string" && runId) host.setRunIdIfEmpty(runId);
842
- }
843
- });
844
- try {
845
- for await (const frame of parseSseFrames(reader)) {
846
- if (frame.event === "values" && host.onValuesFrame) {
847
- try {
848
- const raw = frame.data ? JSON.parse(frame.data) : void 0;
849
- if (raw && typeof raw === "object") host.onValuesFrame(raw);
850
- } catch {
851
- }
852
- }
853
- translator.handleFrame(frame.event, frame.data);
854
- if (frame.event === "end") break;
855
- }
856
- } catch (e) {
857
- if (!ac.signal.aborted) host.lifecycle("failed", String(e?.message ?? e));
858
- return;
859
- }
860
- if (translator.interrupted) host.setInterrupted();
861
- else if (!wasResume) host.clearInterrupted();
862
- host.clearAbort(ac);
863
- }
864
-
865
- // src/bridge/adapter.ts
866
- var _boundThreadId, _getThreadId, _lastRunId;
867
- var DeerFlowBridgeAdapter = class {
868
- constructor(options) {
869
- __privateAdd(this, _boundThreadId, "");
870
- __privateAdd(this, _getThreadId);
871
- __privateAdd(this, _lastRunId, "");
872
- /** 已确认存在的 thread(避免重复预创建) */
873
- this.knownThreads = /* @__PURE__ */ new Set();
874
- /** 线程处于 interrupt 待恢复态:下一个 run.start / input.respond 按 resume 翻译 */
875
- this.interrupted = false;
876
- this.activeAbort = null;
877
- this.disposed = false;
878
- this.apiUrl = options.apiUrl.replace(/\/$/, "");
879
- this.assistantId = options.assistantId;
880
- this.buildHeaders = options.buildHeaders;
881
- this.fetchImpl = options.fetchImpl;
882
- this.onValuesFrame = options.onValuesFrame;
883
- this.onRunId = options.onRunId;
884
- __privateSet(this, _getThreadId, options.getThreadId);
885
- this.hub = createEventHub();
886
- this.streamHost = {
887
- buildHeaders: () => this.buildHeaders(),
888
- readerFactory: options.readerFactory ?? createFetchReaderFactory(options.fetchImpl),
889
- onValuesFrame: this.onValuesFrame,
890
- publish: (event) => this.hub.publish(event),
891
- lifecycle: (event, error) => this.lifecycle(event, error),
892
- setRunId: (runId) => {
893
- __privateSet(this, _lastRunId, runId);
894
- this.onRunId?.(runId);
895
- },
896
- setRunIdIfEmpty: (runId) => {
897
- if (!__privateGet(this, _lastRunId)) {
898
- __privateSet(this, _lastRunId, runId);
899
- this.onRunId?.(runId);
900
- }
901
- },
902
- setInterrupted: () => {
903
- this.interrupted = true;
904
- },
905
- clearInterrupted: () => {
906
- this.interrupted = false;
907
- },
908
- isDisposed: () => this.disposed,
909
- replaceAbort: () => {
910
- this.activeAbort?.abort();
911
- const ac = new AbortController();
912
- this.activeAbort = ac;
913
- return ac;
914
- },
915
- clearAbort: (ac) => {
916
- if (this.activeAbort === ac) this.activeAbort = null;
917
- },
918
- cmdError: (id, message, error) => this.cmdError(id, message, error)
919
- };
920
- }
921
- /** 当前生效的 threadId:外部 getter 优先(hydrate 早于 transport 绑定),setThreadId 兜底 */
922
- get threadId() {
923
- return __privateGet(this, _getThreadId).call(this) || __privateGet(this, _boundThreadId);
924
- }
925
- /** metadata 帧记录的 run_id(首帧权威,G10;Content-Location 优先时两者一致) */
926
- get lastRunId() {
927
- return __privateGet(this, _lastRunId);
928
- }
929
- /** 线程是否处于 interrupt 待恢复态(下一次 send 自动走 command.resume;观测/测试用) */
930
- get isInterrupted() {
931
- return this.interrupted;
932
- }
933
- /** {@inheritDoc TransportAdapter.setThreadId} */
934
- setThreadId(threadId) {
935
- __privateSet(this, _boundThreadId, threadId);
936
- }
937
- /** HTTP/SSE 传输无握手 */
938
- open() {
939
- return Promise.resolve();
940
- }
941
- /** 释放资源:断开进行中的 SSE,关闭事件中枢(唤醒挂起订阅) */
942
- close() {
943
- this.disposed = true;
944
- this.activeAbort?.abort();
945
- this.hub.close();
946
- return Promise.resolve();
947
- }
948
- /** SSE 模式下 events() 为空流,真实投递走 openEventStream */
949
- async *events() {
950
- }
951
- /** 发送协议命令:run.start / input.respond → v1 runs.stream,其余拒绝 */
952
- async send(command) {
953
- switch (command.method) {
954
- case "run.start":
955
- return this.startRun(command, this.interrupted);
956
- case "input.respond": {
957
- const p = command.params ?? {};
958
- const resume = Array.isArray(p.responses) ? p.responses[0]?.response : p.response;
959
- this.interrupted = false;
960
- return this.startRun(command, true, resume);
961
- }
962
- default:
963
- return this.cmdError(command.id, `deer-flow v1 \u6865\u63A5\u6682\u4E0D\u652F\u6301\u547D\u4EE4\uFF1A${command.method}`, "not_supported");
964
- }
965
- }
966
- /** 打开订阅流:事件中枢重放缓冲全量回放后实时推送 */
967
- openEventStream(_params) {
968
- return this.hub.open();
969
- }
970
- /** hydrate 用:/state 与 messages/page 全量并发;messages 以 state 为基准(语义字段全),
971
- * page(run-event 全量投影)补齐压缩缺失的头部/尾部——与 transport 的
972
- * fetchThreadInitialValues 同一合并函数,保证 SDK getState 快照与物化器基线一致
973
- * (不一致会让 watch(stream.messages) 的 diff 把快照差异误追加到对话尾部) */
974
- async getState() {
975
- if (!this.threadId) return null;
976
- try {
977
- const [res, pageMessages] = await Promise.all([
978
- this.request(`/threads/${this.threadId}/state`, { method: "GET" }),
979
- fetchAllPageMessages(this.apiUrl, this.threadId, this.buildHeaders, this.fetchImpl).catch(() => [])
980
- ]);
981
- if (!res.ok) return null;
982
- const json = await res.json();
983
- const values = { ...json.values ?? {} };
984
- const stateMessages = extractStateMessages(json);
985
- if (stateMessages.length > 0 || pageMessages.length > 0) {
986
- values.messages = mergeStateWithPageMessages(stateMessages, pageMessages);
987
- }
988
- if (Array.isArray(values.__interrupt__) && values.__interrupt__.length > 0) {
989
- this.interrupted = true;
990
- delete values.__interrupt__;
991
- }
992
- if (Array.isArray(json.tasks) && json.tasks.some((t) => Array.isArray(t?.interrupts) && t.interrupts.length > 0))
993
- this.interrupted = true;
994
- return { values, tasks: json.tasks, next: json.next, checkpoint: null };
995
- } catch {
996
- return null;
997
- }
998
- }
999
- // ---- 内部实现 ----
1000
- /** run.start / input.respond 落点:预创建 thread 后交 run-stream 打开 SSE 泵帧 */
1001
- async startRun(command, isResume, explicitResume) {
1002
- await this.ensureThread(this.threadId);
1003
- return startRunStream(this.streamHost, command, {
1004
- url: `${this.apiUrl}/threads/${this.threadId}/runs/stream`,
1005
- assistantId: this.assistantId,
1006
- isResume,
1007
- ...explicitResume !== void 0 ? { explicitResume } : {}
1008
- });
1009
- }
1010
- /** 统一 REST 请求入口:注入鉴权头 + cookie */
1011
- async request(path, init = {}) {
1012
- const headers = await this.buildHeaders();
1013
- return this.fetchImpl(this.apiUrl + path, {
1014
- ...init,
1015
- headers: { "Content-Type": "application/json", ...headers },
1016
- credentials: "include"
1017
- });
1018
- }
1019
- /** 预创建 thread(deer-flow POST /threads 支持客户端指定 id 且幂等) */
1020
- async ensureThread(threadId) {
1021
- if (!threadId || this.knownThreads.has(threadId)) return;
1022
- try {
1023
- const res = await this.request("/threads", {
1024
- method: "POST",
1025
- body: JSON.stringify({ thread_id: threadId, metadata: {} })
1026
- });
1027
- if (res.ok) this.knownThreads.add(threadId);
1028
- } catch {
1029
- }
1030
- }
1031
- /** 构造命令错误应答 */
1032
- cmdError(id, message, error = "unknown_error") {
1033
- return { type: "error", id, message, error };
1034
- }
1035
- /** 推送 lifecycle 事件(running / failed) */
1036
- lifecycle(event, error) {
1037
- const data = error ? { event, error } : { event };
1038
- this.hub.publish({ type: "event", method: "lifecycle", params: { namespace: [], timestamp: Date.now(), data } });
1039
- }
1040
- };
1041
- _boundThreadId = new WeakMap();
1042
- _getThreadId = new WeakMap();
1043
- _lastRunId = new WeakMap();
1044
-
1045
389
  // src/test-utils/mockTransport.ts
1046
390
  import { ref } from "vue";
1047
391
  var mockThreadSeq = 0;
@@ -1051,6 +395,7 @@ function createMockTransport() {
1051
395
  const messagesPagesMap = /* @__PURE__ */ new Map();
1052
396
  const tokenUsageMap = /* @__PURE__ */ new Map();
1053
397
  const artifactContentMap = /* @__PURE__ */ new Map();
398
+ const resumeErrorMap = /* @__PURE__ */ new Map();
1054
399
  const handles = /* @__PURE__ */ new Map();
1055
400
  const optionsMap = /* @__PURE__ */ new Map();
1056
401
  const calls = { submit: [], resumeInterrupt: [], stop: [], joinStream: [], cancel: [] };
@@ -1136,11 +481,13 @@ function createMockTransport() {
1136
481
  createStream(options) {
1137
482
  const isLoading = ref(false);
1138
483
  const error = ref(null);
484
+ const interrupt = ref(void 0);
1139
485
  const threadId = options.threadId;
1140
486
  optionsMap.set(threadId, options);
1141
487
  const handle = {
1142
488
  isLoading,
1143
489
  error,
490
+ interrupt,
1144
491
  submit(input, submitOptions) {
1145
492
  calls.submit.push({ threadId, input, options: submitOptions });
1146
493
  },
@@ -1153,6 +500,8 @@ function createMockTransport() {
1153
500
  },
1154
501
  async resumeInterrupt(decisions) {
1155
502
  calls.resumeInterrupt.push({ threadId, decisions });
503
+ const err = resumeErrorMap.get(threadId)?.shift();
504
+ if (err) throw err;
1156
505
  }
1157
506
  };
1158
507
  handles.set(threadId, {
@@ -1163,12 +512,12 @@ function createMockTransport() {
1163
512
  isLoading.value = snapshot.isLoading;
1164
513
  if (!snapshot.isLoading) ended = true;
1165
514
  }
1166
- if (snapshot.values !== void 0 || snapshot.messages !== void 0 || "interrupt" in snapshot) {
515
+ if (snapshot.values !== void 0 || snapshot.messages !== void 0) {
1167
516
  const data = { ...snapshot.values ?? {} };
1168
517
  if (snapshot.messages !== void 0) data.messages = snapshot.messages;
1169
- if ("interrupt" in snapshot) data.__interrupt__ = snapshot.interrupt ? [snapshot.interrupt] : [];
1170
518
  options.onValuesEvent?.(data);
1171
519
  }
520
+ if ("interrupt" in snapshot) interrupt.value = snapshot.interrupt;
1172
521
  if (ended) options.onStreamEnd?.();
1173
522
  }
1174
523
  });
@@ -1201,6 +550,14 @@ function createMockTransport() {
1201
550
  ;
1202
551
  entry.handle.error.value = err;
1203
552
  },
553
+ __setResumeError(threadId, err) {
554
+ let queue = resumeErrorMap.get(threadId);
555
+ if (!queue) {
556
+ queue = [];
557
+ resumeErrorMap.set(threadId, queue);
558
+ }
559
+ queue.push(err);
560
+ },
1204
561
  __setInitialValues(threadId, values) {
1205
562
  initialValuesMap.set(threadId, values);
1206
563
  },
@@ -1223,19 +580,19 @@ function createMockTransport() {
1223
580
  }
1224
581
 
1225
582
  // src/index.ts
1226
- var CORE_VERSION = "2.0.0";
583
+ var CORE_VERSION = "2.1.0";
1227
584
  export {
1228
585
  CORE_VERSION,
1229
586
  DEFAULT_ASSISTANT_ID,
1230
587
  DEFAULT_MAX_CACHED_SESSIONS,
1231
588
  DEFAULT_MAX_CONCURRENT_STREAMS,
1232
- DeerFlowBridgeAdapter,
1233
589
  INJECTED_TAGS,
1234
590
  MESSAGE_TYPE_NORMALIZE,
1235
591
  OUTLINE_MAX_LEVEL,
1236
592
  ThreadDirectory,
1237
- V1FrameTranslator,
1238
593
  applySemanticPatches,
594
+ asArgsObject,
595
+ assembleRun,
1239
596
  backfillRunMessageFeedback,
1240
597
  buildArtifactFiles,
1241
598
  buildHitlDecisions,
@@ -1246,19 +603,16 @@ export {
1246
603
  buildReportOutlinePayload,
1247
604
  buildRunDirectLatencyMs,
1248
605
  buildRunInfo,
606
+ buildRunMeta,
1249
607
  collectTextKeepSxin,
1250
608
  collectVisibleText,
1251
609
  createChatCore,
1252
610
  createEmptySubChapter,
1253
- createEventHub,
1254
- createFetchReaderFactory,
1255
- createMaterializer,
1256
- createMessageDiff,
1257
611
  createMockTransport,
1258
- createRuntimeMaterializer,
1259
612
  createSemanticOverlay,
1260
613
  createThreadRuntime,
1261
614
  deriveToolsFromMessages,
615
+ emptyRunItem,
1262
616
  ensureOutlineContentThemes,
1263
617
  ensureRunningRun,
1264
618
  extractAiContentFromMessage,
@@ -1267,6 +621,7 @@ export {
1267
621
  extractCitationAnchors,
1268
622
  extractCitationAnchorsFromSpec,
1269
623
  extractFromToolResult,
624
+ extractInputFromRows,
1270
625
  extractReportTitleFromBody,
1271
626
  extractRunEnrichment,
1272
627
  extractSemanticPatchesFromMessages,
@@ -1275,7 +630,6 @@ export {
1275
630
  extractThreadInfo,
1276
631
  extractTitleFromArtifactPath,
1277
632
  extractUserMessageTexts,
1278
- fetchAllPageMessages,
1279
633
  formatAnswerText,
1280
634
  formatStr,
1281
635
  genBlockId,
@@ -1283,6 +637,7 @@ export {
1283
637
  getAllowedDecisions,
1284
638
  getHumanMessageBaseId,
1285
639
  getToolCallArtifactMeta,
640
+ groupRowsByRun,
1286
641
  isAiMessage,
1287
642
  isHiddenUserMessage,
1288
643
  isHumanMessage,
@@ -1290,8 +645,10 @@ export {
1290
645
  isReportBodyHtml,
1291
646
  isSameArgs,
1292
647
  isToolMessage,
648
+ isUserEchoRow,
1293
649
  isVisibleUserMessage,
1294
650
  isWriteFileToolName,
651
+ mapBackendStatus,
1295
652
  mergeStateWithPageMessages,
1296
653
  normalizeForCompare,
1297
654
  normalizeMessageType,
@@ -1301,10 +658,12 @@ export {
1301
658
  parseHumanMessageId,
1302
659
  parseKnowledgeItemsFromValue,
1303
660
  parseMarkdownToOutline,
1304
- parseSseFrames,
661
+ pickRicherArgs,
1305
662
  pickRunMessageMetadata,
663
+ projectRuns,
1306
664
  readMessageContentText,
1307
665
  resolveReportArtifactKind,
666
+ rowMessageId,
1308
667
  runMessagesToMessages,
1309
668
  simpleHash,
1310
669
  sliceBodySegments,