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