@cqfe/sxin-chat-core 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -2,197 +2,1048 @@ import {
2
2
  DEFAULT_ASSISTANT_ID,
3
3
  DEFAULT_MAX_CACHED_SESSIONS,
4
4
  DEFAULT_MAX_CONCURRENT_STREAMS,
5
- DEFAULT_TWIN_TOOL_PREFIX,
6
5
  INJECTED_TAGS,
7
6
  MESSAGE_TYPE_NORMALIZE,
8
7
  OUTLINE_MAX_LEVEL,
9
8
  ThreadDirectory,
10
- buildAiGroup,
11
- buildArtifactFiles,
12
- buildHitlDecisions,
13
- buildHumanGroup,
9
+ __privateAdd,
10
+ __privateGet,
11
+ __privateSet,
12
+ applySemanticPatches,
13
+ backfillRunMessageFeedback,
14
14
  buildHumanInputResponse,
15
- buildInterruptReviewBlock,
16
- buildInterruptReviewGroup,
17
- buildRejectDecisions,
18
- buildReportBodyPayload,
19
- buildReportOutlinePayload,
20
15
  buildRunDirectLatencyMs,
21
16
  buildRunInfo,
22
17
  collectTextKeepSxin,
23
18
  collectVisibleText,
24
- createBlockBuilderLite,
25
19
  createChatCore,
26
20
  createEmptySubChapter,
27
- createGroupDeriver,
28
- createOptimisticHuman,
21
+ createMaterializer,
22
+ createMessageDiff,
23
+ createRuntimeMaterializer,
24
+ createSemanticOverlay,
29
25
  createThreadRuntime,
30
- createViewModelState,
31
26
  deriveToolsFromMessages,
32
27
  ensureOutlineContentThemes,
33
28
  ensureRunningRun,
34
29
  extractAiContentFromMessage,
35
- extractBlocksFromContent,
36
- extractBlocksFromNodes,
37
- extractCitationAnchors,
38
- extractCitationAnchorsFromSpec,
30
+ extractFromToolResult,
39
31
  extractReportTitleFromBody,
40
32
  extractRunEnrichment,
33
+ extractSemanticPatchesFromMessages,
41
34
  extractStateMessages,
42
35
  extractTextFromMessage,
43
36
  extractThreadInfo,
44
37
  extractTitleFromArtifactPath,
45
38
  extractUserMessageTexts,
46
- foldMessages,
39
+ formatAnswerText,
47
40
  formatStr,
48
- genBlockId,
49
- genMessageId,
50
- getAllowedDecisions,
51
41
  getHumanMessageBaseId,
52
42
  getToolCallArtifactMeta,
53
43
  isAiMessage,
54
- isClarificationAnswered,
55
- isClarificationBlock,
56
44
  isHiddenUserMessage,
57
45
  isHumanMessage,
58
46
  isInjectedElement,
59
47
  isReportBodyHtml,
60
- isSameArgs,
61
48
  isToolMessage,
62
49
  isVisibleUserMessage,
63
50
  isWriteFileToolName,
64
- normalizeForCompare,
51
+ mergeStateWithPageMessages,
65
52
  normalizeMessageType,
66
53
  normalizeOutline,
67
54
  normalizeUsage,
68
- parseHitlPayload,
69
55
  parseHumanMessageId,
70
- parseKnowledgeItemsFromValue,
71
56
  parseMarkdownToOutline,
72
57
  pickRunMessageMetadata,
73
58
  readMessageContentText,
74
59
  resolveReportArtifactKind,
75
60
  runMessagesToMessages,
76
61
  simpleHash,
62
+ sliceBodySegments,
77
63
  stateMessagesToRunMessages,
78
64
  toRunMessage,
79
65
  tokenizeSxin,
80
66
  validateOutline
81
- } from "./chunk-K2ZOZPBB.mjs";
67
+ } from "./chunk-Z65C2UII.mjs";
82
68
 
83
- // src/protocol/stream-pump.ts
84
- import { ref } from "vue";
85
- import { StreamError } from "@langchain/langgraph-sdk";
86
- var STREAM_MODE = ["values", "messages-tuple"];
87
- function isSilentStreamError(e) {
88
- return e instanceof Error && (e.name === "AbortError" || e.name === "TimeoutError");
89
- }
90
- function createStreamPump(source, options) {
91
- const isLoading = ref(false);
92
- const error = ref(null);
93
- let queue = Promise.resolve();
94
- let currentController = null;
95
- const runStream = async (open) => {
96
- const controller = new AbortController();
97
- currentController = controller;
98
- try {
99
- isLoading.value = true;
100
- error.value = null;
101
- options.onStreamStart?.();
102
- for await (const { event, data } of open(controller.signal)) {
103
- if (event === "error") throw new StreamError(data);
104
- if (event === "metadata") {
105
- options.onMetadataEvent?.(data);
106
- continue;
107
- }
108
- if (event === "values" || event.startsWith("values|")) {
109
- if (event.includes("|")) continue;
110
- options.onValuesEvent?.(data);
111
- continue;
112
- }
113
- if (event === "messages" || event === "messages-tuple" || event.startsWith("messages|")) {
114
- if (event.includes("|")) continue;
115
- const [serialized, metadata] = Array.isArray(data) ? data : [];
116
- options.onMessageTupleEvent?.(serialized, metadata);
117
- continue;
118
- }
119
- }
120
- } catch (e) {
121
- if (!isSilentStreamError(e)) {
122
- error.value = e;
123
- try {
124
- await options.onError?.(e);
125
- } catch {
126
- }
69
+ // src/parser/citation.ts
70
+ var toStringArray = (v) => {
71
+ if (!v) return [];
72
+ if (Array.isArray(v))
73
+ return v.map((x) => String(x)).map((x) => x.trim()).filter(Boolean);
74
+ return [String(v).trim()].filter(Boolean);
75
+ };
76
+ var pick = (obj, keys) => {
77
+ for (const k of keys) {
78
+ const v = obj?.[k];
79
+ if (v !== void 0 && v !== null && String(v).trim() !== "") return v;
80
+ }
81
+ return void 0;
82
+ };
83
+ var STRING_FIELD_KEYS = {
84
+ rawKey: ["key", "refId", "ref_id", "citationId", "citation_id"],
85
+ refId: ["refId", "ref_id", "citationId", "citation_id"],
86
+ globalRef: ["globalRef", "global_ref"],
87
+ minioBucket: ["minioBucket", "minio_bucket", "bucket", "minioBucketName"],
88
+ minioObject: ["minioObject", "minio_object", "object", "object_name", "objectName", "minioObjectName"],
89
+ previewUrl: ["previewUrl", "preview_url", "url", "preview"],
90
+ docUrl: ["docUrl", "doc_url"],
91
+ docId: ["docId", "doc_id", "document_id", "docid", "id"],
92
+ title: ["title", "docName", "doc_name", "docOriginalName", "doc_original_name", "file_name", "filename", "name"],
93
+ fileType: ["fileType", "file_type", "ext", "extension"]
94
+ };
95
+ var ARRAY_FIELD_KEYS = {
96
+ sourcePages: ["sourcePages", "source_pages", "pages", "page_idxs", "page_idx"],
97
+ highlightText: ["highlightText", "highlight_text"]
98
+ };
99
+ var pickString = (raw, meta, keys) => String(pick(raw, keys) ?? pick(meta, keys) ?? "").trim();
100
+ var pickStringArray = (raw, meta, keys) => toStringArray(pick(raw, keys) ?? pick(meta, keys));
101
+ var orUndefined = (s) => s || void 0;
102
+ var nonEmpty = (a) => a.length ? a : void 0;
103
+ var resolveCitationKey = (s) => {
104
+ if (s.rawKey) return s.rawKey;
105
+ if (s.minioBucket && s.minioObject) return `${s.minioBucket}:${s.minioObject}`;
106
+ if (s.docId) return `doc:${s.docId}`;
107
+ if (s.title) return `title:${s.title}`;
108
+ return "";
109
+ };
110
+ var parseBboxEntry = (entry) => {
111
+ const b = entry?.bbox;
112
+ const pageIdx = Number(entry?.page_idx);
113
+ const left = Number(b?.left);
114
+ const top = Number(b?.top);
115
+ const right = Number(b?.right);
116
+ const bottom = Number(b?.bottom);
117
+ if (![left, top, right, bottom].every(Number.isFinite)) return null;
118
+ return {
119
+ page: Number.isFinite(pageIdx) ? Math.max(1, pageIdx + 1) : 1,
120
+ bbox: [left, top, right, bottom]
121
+ };
122
+ };
123
+ var parseCitationLocations = (raw, meta) => {
124
+ const rawBboxes = Array.isArray(raw?.source_bboxes) ? raw.source_bboxes : Array.isArray(meta?.source_bboxes) ? meta.source_bboxes : [];
125
+ return rawBboxes.map(parseBboxEntry).filter(Boolean);
126
+ };
127
+ var normalizeOne = (raw) => {
128
+ if (!raw || typeof raw !== "object") return null;
129
+ const meta = raw.metadata && typeof raw.metadata === "object" ? raw.metadata : {};
130
+ const str = {};
131
+ for (const [field, keys] of Object.entries(STRING_FIELD_KEYS)) {
132
+ str[field] = pickString(raw, meta, keys);
133
+ }
134
+ const { refId, globalRef, minioBucket, minioObject, previewUrl, docUrl, docId, title, fileType } = str;
135
+ const arr = {};
136
+ for (const [field, keys] of Object.entries(ARRAY_FIELD_KEYS)) {
137
+ arr[field] = pickStringArray(raw, meta, keys);
138
+ }
139
+ const { sourcePages, highlightText } = arr;
140
+ const searchText = highlightText[0] || "";
141
+ const citationLocations = parseCitationLocations(raw, meta);
142
+ const key = resolveCitationKey(str);
143
+ if (!key && !previewUrl && !docUrl) return null;
144
+ return {
145
+ key,
146
+ refId: orUndefined(refId),
147
+ globalRef: orUndefined(globalRef),
148
+ title,
149
+ docId,
150
+ minioBucket: orUndefined(minioBucket),
151
+ minioObject: orUndefined(minioObject),
152
+ previewUrl: orUndefined(previewUrl),
153
+ docUrl: orUndefined(docUrl),
154
+ fileType: orUndefined(fileType),
155
+ sourcePages: nonEmpty(sourcePages),
156
+ citationLocations: nonEmpty(citationLocations),
157
+ highlightText: nonEmpty(highlightText),
158
+ searchText: orUndefined(searchText)
159
+ };
160
+ };
161
+ var KB_CITATION_CONTRACT = "support.kbCitation";
162
+ var REF_ID_KEYS = ["ref-id", "refId", "ref_id", "citation-id", "citationId", "citation_id", "id"];
163
+ var SEARCH_TEXT_KEYS = ["search-text", "searchText", "search_text", "keyword"];
164
+ var REF_ID_LIST_KEY_RE = /^(ref|citation)[-_]?ids?$/i;
165
+ var isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
166
+ var pickFirstString = (obj, keys) => {
167
+ for (const k of keys) {
168
+ const v = obj?.[k];
169
+ if (v === void 0 || v === null) continue;
170
+ const s = String(v).trim();
171
+ if (s) return s;
172
+ }
173
+ return void 0;
174
+ };
175
+ function extractCitationAnchorsFromSpec(spec) {
176
+ const anchors = [];
177
+ const seen = /* @__PURE__ */ new Set();
178
+ const candidates = [];
179
+ if (isPlainObject(spec)) candidates.push(spec);
180
+ for (const [key, value] of Object.entries(spec || {})) {
181
+ if (Array.isArray(value)) {
182
+ for (const item of value) if (isPlainObject(item)) candidates.push(item);
183
+ } else if (typeof value === "string" && /,/.test(value) && REF_ID_LIST_KEY_RE.test(key)) {
184
+ for (const id of value.split(",")) candidates.push({ "ref-id": id });
185
+ }
186
+ }
187
+ for (const item of candidates) {
188
+ const refId = pickFirstString(item, REF_ID_KEYS);
189
+ if (!refId || seen.has(refId)) continue;
190
+ seen.add(refId);
191
+ const anchor = { refId, title: "" };
192
+ const searchText = pickFirstString(item, SEARCH_TEXT_KEYS);
193
+ if (searchText) anchor.searchText = searchText;
194
+ anchors.push(anchor);
195
+ }
196
+ return anchors;
197
+ }
198
+ function extractCitationAnchors(blocks) {
199
+ const anchors = [];
200
+ const seen = /* @__PURE__ */ new Set();
201
+ for (const block of blocks) {
202
+ if (block.type !== "custom") continue;
203
+ const custom = block;
204
+ if (custom.tagName !== "sxin-item") continue;
205
+ const spec = custom.spec || {};
206
+ if (String(spec.contract || "").trim() !== KB_CITATION_CONTRACT) continue;
207
+ for (const anchor of extractCitationAnchorsFromSpec(spec)) {
208
+ if (seen.has(anchor.refId)) continue;
209
+ seen.add(anchor.refId);
210
+ anchors.push(anchor);
211
+ }
212
+ }
213
+ return anchors;
214
+ }
215
+ function parseKnowledgeItemsFromValue(value) {
216
+ if (!value) return [];
217
+ const rawList = Array.isArray(value) ? value : typeof value === "object" ? [value] : [];
218
+ const result = [];
219
+ for (const raw of rawList) {
220
+ const it = normalizeOne(raw);
221
+ if (it) result.push(it);
222
+ }
223
+ return result;
224
+ }
225
+
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
+ // src/parser/block-build-helper.ts
293
+ function buildArtifactFiles(paths) {
294
+ return paths.map((path) => {
295
+ const name = path.split("/").pop() || path;
296
+ const fileType = name.split(".").pop() || void 0;
297
+ return { path, name, fileType };
298
+ });
299
+ }
300
+ function toCreatedAtIso(createdAt) {
301
+ const ms = Number(createdAt);
302
+ if (!Number.isFinite(ms)) return (/* @__PURE__ */ new Date()).toISOString();
303
+ const date = new Date(ms);
304
+ return Number.isNaN(date.getTime()) ? (/* @__PURE__ */ new Date()).toISOString() : date.toISOString();
305
+ }
306
+ function buildReportOutlinePayload(input) {
307
+ const { templateId, fallbackName, sourcePath, content, contentRef, createdAt } = input;
308
+ const createdIso = toCreatedAtIso(createdAt);
309
+ if (!content) {
310
+ return {
311
+ templateId,
312
+ templateName: fallbackName,
313
+ outline: [],
314
+ createdAt: createdIso,
315
+ sourcePath: sourcePath || void 0,
316
+ contentRef
317
+ };
318
+ }
319
+ const parsed = parseMarkdownToOutline(content);
320
+ return {
321
+ templateId,
322
+ templateName: parsed.templateName || fallbackName,
323
+ outline: parsed.outline,
324
+ createdAt: createdIso,
325
+ sourcePath: sourcePath || void 0,
326
+ outlineMarkdown: content,
327
+ contentRef
328
+ };
329
+ }
330
+ function buildReportBodyPayload(input) {
331
+ const { templateId, fallbackName, sourcePath, content, contentRef, createdAt } = input;
332
+ const createdIso = toCreatedAtIso(createdAt);
333
+ if (!content) {
334
+ return {
335
+ templateId,
336
+ templateName: fallbackName,
337
+ reportTitle: "",
338
+ createdAt: createdIso,
339
+ sourcePath: sourcePath || void 0,
340
+ contentRef
341
+ };
342
+ }
343
+ return {
344
+ templateId,
345
+ templateName: fallbackName,
346
+ reportTitle: extractReportTitleFromBody(content, fallbackName),
347
+ createdAt: createdIso,
348
+ sourcePath: sourcePath || void 0,
349
+ bodyMarkdown: content,
350
+ contentRef
351
+ };
352
+ }
353
+ function collectListSpecs(listEls, spec, source) {
354
+ for (const listEl of listEls) {
355
+ const itemType = formatStr(listEl.attrs["item-type"] || "");
356
+ if (!itemType) continue;
357
+ if (!spec[itemType]) spec[itemType] = [];
358
+ for (const item of listEl.children) {
359
+ if (item.type !== "element" || item.tagName !== "sxin-list-item") continue;
360
+ spec[itemType].push(buildItemSpec(item, source));
361
+ }
362
+ }
363
+ }
364
+ function collectChildSpecs(children, spec, source) {
365
+ for (const child of children) {
366
+ if (child.type !== "element") continue;
367
+ const key = formatStr(child.tagName);
368
+ if (!spec[key]) spec[key] = [];
369
+ spec[key].push(buildItemSpec(child, source));
370
+ }
371
+ }
372
+ function buildCustomBlockFromNode(el, source, status) {
373
+ const spec = { ...el.attrs };
374
+ const listEls = el.children.filter((c) => c.type === "element" && c.tagName === "sxin-list");
375
+ if (listEls.length > 0) {
376
+ collectListSpecs(listEls, spec, source);
377
+ } else {
378
+ collectChildSpecs(el.children, spec, source);
379
+ }
380
+ return { id: genBlockId(), type: "custom", tagName: el.tagName, spec, status };
381
+ }
382
+ function buildItemSpec(el, source) {
383
+ const attrs = { ...el.attrs };
384
+ const inner = el.children.map((c) => source.slice(c.start, c.end)).join("").trim();
385
+ if (inner) attrs.text = inner;
386
+ return attrs;
387
+ }
388
+ function flushTextBuf(ctx) {
389
+ const content = ctx.textBuf.value.replace(/\n{3,}/g, "\n\n").trim();
390
+ ctx.textBuf.value = "";
391
+ if (content) {
392
+ ctx.blocks.push({ id: genBlockId(), type: "text", content, status: ctx.status });
393
+ }
394
+ }
395
+ function handleSxinElement(ctx, node) {
396
+ if (!node.closed && !ctx.isHistory) {
397
+ flushTextBuf(ctx);
398
+ return false;
399
+ }
400
+ flushTextBuf(ctx);
401
+ ctx.blocks.push(buildCustomBlockFromNode(node, ctx.rawText, ctx.status));
402
+ return true;
403
+ }
404
+ function walkNodes(ctx, nodes) {
405
+ for (const node of nodes) {
406
+ if (node.type === "text") {
407
+ ctx.textBuf.value += node.value;
408
+ continue;
409
+ }
410
+ if (node.type === "comment") {
411
+ continue;
412
+ }
413
+ if (isInjectedElement(node)) {
414
+ continue;
415
+ }
416
+ if (node.tagName.startsWith("sxin-")) {
417
+ if (!handleSxinElement(ctx, node)) return false;
418
+ continue;
419
+ }
420
+ ctx.textBuf.value += ctx.rawText.slice(node.start, node.end);
421
+ }
422
+ return true;
423
+ }
424
+ function extractBlocksFromNodes(nodes, rawText, source) {
425
+ const isHistory = source === "history";
426
+ const ctx = {
427
+ rawText,
428
+ isHistory,
429
+ status: isHistory ? "completed" : "streaming",
430
+ blocks: [],
431
+ textBuf: { value: "" }
432
+ };
433
+ const completed = walkNodes(ctx, nodes);
434
+ if (completed) flushTextBuf(ctx);
435
+ return { blocks: ctx.blocks };
436
+ }
437
+ function extractBlocksFromContent(rawText, source) {
438
+ return extractBlocksFromNodes(tokenizeSxin(rawText), rawText, source);
439
+ }
440
+
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
+ });
127
460
  }
128
- } finally {
461
+ };
462
+ };
463
+ }
464
+ async function* parseSseFrames(reader) {
465
+ const decoder = new TextDecoder();
466
+ let buf = "";
467
+ try {
468
+ while (true) {
469
+ let chunk;
129
470
  try {
130
- await options.onStreamEnd?.();
131
- } catch {
471
+ chunk = await reader.read();
472
+ } catch (e) {
473
+ if (e?.name === "AbortError") break;
474
+ throw e;
132
475
  }
133
- isLoading.value = false;
134
- if (currentController === controller) currentController = null;
135
- try {
136
- await options.onFinish?.();
137
- } catch {
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;
138
484
  }
139
485
  }
140
- };
141
- const start = (open, startOptions) => {
142
- if (startOptions?.abortPrevious) currentController?.abort();
143
- const queued = queue.then(() => runStream(open));
144
- queue = queued;
145
- return queued;
146
- };
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
+ }
147
565
  return {
148
- isLoading,
149
- error,
150
- /** 发起一次流式运行(发送用户消息);fire-and-forget(与现网 useThreadStream 一致) */
151
- submit(input, submitOptions) {
152
- void start(
153
- (signal) => source.openRunStream(
154
- {
155
- input,
156
- ...submitOptions,
157
- streamMode: STREAM_MODE,
158
- // sdk client 在 run 创建时回调;透传给 CreateStreamOptions.onCreated
159
- onRunCreated: (params) => options.onCreated?.(params)
160
- },
161
- signal
162
- ),
163
- { abortPrevious: true }
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
164
701
  );
165
- },
166
- /** 加入既有 run 的 SSE 流(断线重连);await 至流结束 */
167
- joinStream(runId, lastEventId) {
168
- return start((signal) => source.openJoinStream(runId, lastEventId ?? "-1", signal), { abortPrevious: true });
169
- },
170
- /** 停止当前流(本地 abort,不取消服务端 run) */
171
- stop() {
172
- currentController?.abort();
173
- },
174
- /** 恢复 pending interrupt:发送 HITL 决策(Command(resume)),与 joinStream 的 SSE 重连语义不同;await 至流结束 */
175
- resumeInterrupt(decisions) {
176
- return start(
177
- (signal) => source.openRunStream(
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",
178
719
  {
179
- input: null,
180
- command: { resume: decisions },
181
- onDisconnect: "continue",
182
- config: { recursion_limit: 1e3 },
183
- streamMode: STREAM_MODE,
184
- onRunCreated: (params) => options.onCreated?.(params)
720
+ event: "content-block-start",
721
+ index,
722
+ content: { type: "tool_call_chunk", id: tc.id, name: tc.name ?? "", args: "" }
185
723
  },
186
- signal
187
- ),
188
- { abortPrevious: true }
189
- );
190
- }
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 } : {}
191
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);
192
863
  }
193
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
+
194
1045
  // src/test-utils/mockTransport.ts
195
- import { ref as ref2 } from "vue";
1046
+ import { ref } from "vue";
196
1047
  var mockThreadSeq = 0;
197
1048
  function createMockTransport() {
198
1049
  const threads = [];
@@ -283,8 +1134,8 @@ function createMockTransport() {
283
1134
  return content;
284
1135
  },
285
1136
  createStream(options) {
286
- const isLoading = ref2(false);
287
- const error = ref2(null);
1137
+ const isLoading = ref(false);
1138
+ const error = ref(null);
288
1139
  const threadId = options.threadId;
289
1140
  optionsMap.set(threadId, options);
290
1141
  const handle = {
@@ -378,18 +1229,18 @@ export {
378
1229
  DEFAULT_ASSISTANT_ID,
379
1230
  DEFAULT_MAX_CACHED_SESSIONS,
380
1231
  DEFAULT_MAX_CONCURRENT_STREAMS,
381
- DEFAULT_TWIN_TOOL_PREFIX,
1232
+ DeerFlowBridgeAdapter,
382
1233
  INJECTED_TAGS,
383
1234
  MESSAGE_TYPE_NORMALIZE,
384
1235
  OUTLINE_MAX_LEVEL,
385
1236
  ThreadDirectory,
386
- buildAiGroup,
1237
+ V1FrameTranslator,
1238
+ applySemanticPatches,
1239
+ backfillRunMessageFeedback,
387
1240
  buildArtifactFiles,
388
1241
  buildHitlDecisions,
389
- buildHumanGroup,
390
1242
  buildHumanInputResponse,
391
1243
  buildInterruptReviewBlock,
392
- buildInterruptReviewGroup,
393
1244
  buildRejectDecisions,
394
1245
  buildReportBodyPayload,
395
1246
  buildReportOutlinePayload,
@@ -397,15 +1248,16 @@ export {
397
1248
  buildRunInfo,
398
1249
  collectTextKeepSxin,
399
1250
  collectVisibleText,
400
- createBlockBuilderLite,
401
1251
  createChatCore,
402
1252
  createEmptySubChapter,
403
- createGroupDeriver,
1253
+ createEventHub,
1254
+ createFetchReaderFactory,
1255
+ createMaterializer,
1256
+ createMessageDiff,
404
1257
  createMockTransport,
405
- createOptimisticHuman,
406
- createStreamPump,
1258
+ createRuntimeMaterializer,
1259
+ createSemanticOverlay,
407
1260
  createThreadRuntime,
408
- createViewModelState,
409
1261
  deriveToolsFromMessages,
410
1262
  ensureOutlineContentThemes,
411
1263
  ensureRunningRun,
@@ -414,14 +1266,17 @@ export {
414
1266
  extractBlocksFromNodes,
415
1267
  extractCitationAnchors,
416
1268
  extractCitationAnchorsFromSpec,
1269
+ extractFromToolResult,
417
1270
  extractReportTitleFromBody,
418
1271
  extractRunEnrichment,
1272
+ extractSemanticPatchesFromMessages,
419
1273
  extractStateMessages,
420
1274
  extractTextFromMessage,
421
1275
  extractThreadInfo,
422
1276
  extractTitleFromArtifactPath,
423
1277
  extractUserMessageTexts,
424
- foldMessages,
1278
+ fetchAllPageMessages,
1279
+ formatAnswerText,
425
1280
  formatStr,
426
1281
  genBlockId,
427
1282
  genMessageId,
@@ -429,8 +1284,6 @@ export {
429
1284
  getHumanMessageBaseId,
430
1285
  getToolCallArtifactMeta,
431
1286
  isAiMessage,
432
- isClarificationAnswered,
433
- isClarificationBlock,
434
1287
  isHiddenUserMessage,
435
1288
  isHumanMessage,
436
1289
  isInjectedElement,
@@ -439,6 +1292,7 @@ export {
439
1292
  isToolMessage,
440
1293
  isVisibleUserMessage,
441
1294
  isWriteFileToolName,
1295
+ mergeStateWithPageMessages,
442
1296
  normalizeForCompare,
443
1297
  normalizeMessageType,
444
1298
  normalizeOutline,
@@ -447,11 +1301,13 @@ export {
447
1301
  parseHumanMessageId,
448
1302
  parseKnowledgeItemsFromValue,
449
1303
  parseMarkdownToOutline,
1304
+ parseSseFrames,
450
1305
  pickRunMessageMetadata,
451
1306
  readMessageContentText,
452
1307
  resolveReportArtifactKind,
453
1308
  runMessagesToMessages,
454
1309
  simpleHash,
1310
+ sliceBodySegments,
455
1311
  stateMessagesToRunMessages,
456
1312
  toRunMessage,
457
1313
  tokenizeSxin,