@cqfe/sxin-chat-core 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ChatCore-cSM1HmXp.d.cts → ChatCore-CCeoxjP9.d.cts} +228 -203
- package/dist/{ChatCore-cSM1HmXp.d.ts → ChatCore-CCeoxjP9.d.ts} +228 -203
- package/dist/{chunk-Z65C2UII.mjs → chunk-2AXUXZVK.mjs} +762 -931
- package/dist/index.cjs +763 -1598
- package/dist/index.d.cts +133 -523
- package/dist/index.d.ts +133 -523
- package/dist/index.mjs +48 -689
- package/dist/vue/index.cjs +785 -1024
- 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
|
@@ -1,11 +1,3 @@
|
|
|
1
|
-
var __typeError = (msg) => {
|
|
2
|
-
throw TypeError(msg);
|
|
3
|
-
};
|
|
4
|
-
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
5
|
-
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
6
|
-
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
7
|
-
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
8
|
-
|
|
9
1
|
// src/constants.ts
|
|
10
2
|
var DEFAULT_MAX_CACHED_SESSIONS = 10;
|
|
11
3
|
var DEFAULT_MAX_CONCURRENT_STREAMS = 3;
|
|
@@ -325,6 +317,70 @@ function tokenizeSxin(source) {
|
|
|
325
317
|
return st.nodes;
|
|
326
318
|
}
|
|
327
319
|
|
|
320
|
+
// src/parser/message-id.ts
|
|
321
|
+
var _idSeq = 0;
|
|
322
|
+
function genMessageId() {
|
|
323
|
+
return `msg-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
|
|
324
|
+
}
|
|
325
|
+
function genBlockId() {
|
|
326
|
+
return `block-${Date.now().toString(36)}-${(++_idSeq).toString(36)}`;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// src/parser/hitl.ts
|
|
330
|
+
import { isEqual } from "lodash";
|
|
331
|
+
function parseHitlPayload(value) {
|
|
332
|
+
if (!value || typeof value !== "object") return null;
|
|
333
|
+
const raw = value;
|
|
334
|
+
const requests = raw.actionRequests ?? raw.action_requests;
|
|
335
|
+
if (!Array.isArray(requests) || !requests.length) return null;
|
|
336
|
+
const configs = raw.reviewConfigs ?? raw.review_configs;
|
|
337
|
+
return {
|
|
338
|
+
actionRequests: requests,
|
|
339
|
+
reviewConfigs: Array.isArray(configs) ? configs : []
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function getAllowedDecisions(configs, actionName) {
|
|
343
|
+
const cfg = configs.find((c) => c.action_name === actionName);
|
|
344
|
+
const list = cfg?.allowedDecisions ?? cfg?.allowed_decisions;
|
|
345
|
+
return list?.length ? list : ["approve", "reject"];
|
|
346
|
+
}
|
|
347
|
+
function normalizeForCompare(value) {
|
|
348
|
+
if (Array.isArray(value)) return value.map(normalizeForCompare);
|
|
349
|
+
if (value && typeof value === "object") {
|
|
350
|
+
return Object.keys(value).sort().reduce((acc, key) => {
|
|
351
|
+
acc[key] = normalizeForCompare(value[key]);
|
|
352
|
+
return acc;
|
|
353
|
+
}, {});
|
|
354
|
+
}
|
|
355
|
+
return value;
|
|
356
|
+
}
|
|
357
|
+
function isSameArgs(a, b) {
|
|
358
|
+
return isEqual(normalizeForCompare(a), normalizeForCompare(b));
|
|
359
|
+
}
|
|
360
|
+
function buildHitlDecisions(requests, currentArgsList) {
|
|
361
|
+
return requests.map((req, i) => {
|
|
362
|
+
const current = currentArgsList[i];
|
|
363
|
+
if (!current || isSameArgs(req.args, current)) return { type: "approve" };
|
|
364
|
+
return { type: "edit", edited_action: { name: req.name, args: current } };
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
function buildRejectDecisions(requests) {
|
|
368
|
+
return requests.map(() => ({ type: "reject" }));
|
|
369
|
+
}
|
|
370
|
+
function buildInterruptReviewBlock(interrupt, responded) {
|
|
371
|
+
const payload = parseHitlPayload(interrupt.value);
|
|
372
|
+
if (!payload) return null;
|
|
373
|
+
const interruptId = String(interrupt.id || genMessageId());
|
|
374
|
+
const status = responded ? "completed" : "pending";
|
|
375
|
+
return {
|
|
376
|
+
id: `interrupt-review-${interruptId}`,
|
|
377
|
+
type: "interrupt-review",
|
|
378
|
+
status,
|
|
379
|
+
payload,
|
|
380
|
+
interruptId
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
328
384
|
// src/parser/thread-info.ts
|
|
329
385
|
function formatAnswerText(value) {
|
|
330
386
|
if (value == null) return "";
|
|
@@ -558,11 +614,14 @@ function runMessagesToMessages(messages) {
|
|
|
558
614
|
});
|
|
559
615
|
}
|
|
560
616
|
function stateMessagesToRunMessages(messages) {
|
|
617
|
+
let lastRunId = "";
|
|
561
618
|
return messages.map((msg, i) => {
|
|
562
619
|
const sxin = asSxin(msg);
|
|
620
|
+
const ownRunId = String(sxin.runId ?? sxin.additional_kwargs?.run_id ?? "").trim();
|
|
621
|
+
if (ownRunId) lastRunId = ownRunId;
|
|
563
622
|
const createdAt = parseCreatedAt(sxin.created_at);
|
|
564
623
|
return {
|
|
565
|
-
runId:
|
|
624
|
+
runId: ownRunId || lastRunId,
|
|
566
625
|
seq: i + 1,
|
|
567
626
|
eventType: "messages",
|
|
568
627
|
...createdAt !== void 0 ? { createdAt } : {},
|
|
@@ -1002,6 +1061,408 @@ function sliceBodySegments(body) {
|
|
|
1002
1061
|
return segments;
|
|
1003
1062
|
}
|
|
1004
1063
|
|
|
1064
|
+
// src/assembler/run-grouping.ts
|
|
1065
|
+
var LIVE_SEQ = Number.MAX_SAFE_INTEGER;
|
|
1066
|
+
function rowMessageId(msg) {
|
|
1067
|
+
return String(msg?.id || "").trim();
|
|
1068
|
+
}
|
|
1069
|
+
function isUserEchoRow(id) {
|
|
1070
|
+
return id.endsWith("__user");
|
|
1071
|
+
}
|
|
1072
|
+
function pageRowToAsmRow(row) {
|
|
1073
|
+
const id = rowMessageId(row.content);
|
|
1074
|
+
if (!id) return null;
|
|
1075
|
+
const out = {
|
|
1076
|
+
id,
|
|
1077
|
+
runId: String(row.runId || ""),
|
|
1078
|
+
seq: Number.isFinite(row.seq) ? row.seq : 0,
|
|
1079
|
+
msg: row.content
|
|
1080
|
+
};
|
|
1081
|
+
if (row.createdAt !== void 0) out.createdAt = row.createdAt;
|
|
1082
|
+
if (row.feedback !== void 0 && row.feedback !== null) out.feedback = row.feedback;
|
|
1083
|
+
return out;
|
|
1084
|
+
}
|
|
1085
|
+
function liveToAsmRow(msg, runId) {
|
|
1086
|
+
const id = rowMessageId(msg);
|
|
1087
|
+
if (!id || isUserEchoRow(id)) return null;
|
|
1088
|
+
return { id, runId, seq: LIVE_SEQ, msg };
|
|
1089
|
+
}
|
|
1090
|
+
function groupRowsByRun(rows, liveMessages, activeRunId, pendingRunId) {
|
|
1091
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1092
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
1093
|
+
for (const row of rows) {
|
|
1094
|
+
const asm = pageRowToAsmRow(row);
|
|
1095
|
+
if (!asm) continue;
|
|
1096
|
+
const prev = byId.get(asm.id);
|
|
1097
|
+
if (prev) {
|
|
1098
|
+
if (asm.seq >= prev.seq) {
|
|
1099
|
+
replaceInBucket(buckets, prev, asm);
|
|
1100
|
+
byId.set(asm.id, asm);
|
|
1101
|
+
}
|
|
1102
|
+
continue;
|
|
1103
|
+
}
|
|
1104
|
+
byId.set(asm.id, asm);
|
|
1105
|
+
pushToBucket(buckets, asm);
|
|
1106
|
+
}
|
|
1107
|
+
const liveRunId = String(activeRunId || pendingRunId || "").trim();
|
|
1108
|
+
if (liveRunId) {
|
|
1109
|
+
for (const msg of liveMessages) {
|
|
1110
|
+
const asm = liveToAsmRow(msg, liveRunId);
|
|
1111
|
+
if (!asm) continue;
|
|
1112
|
+
if (byId.has(asm.id)) continue;
|
|
1113
|
+
pushToBucket(buckets, asm);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
for (const list of buckets.values()) {
|
|
1117
|
+
list.sort((a, b) => a.seq - b.seq);
|
|
1118
|
+
}
|
|
1119
|
+
return buckets;
|
|
1120
|
+
}
|
|
1121
|
+
function pushToBucket(buckets, row) {
|
|
1122
|
+
const runId = String(row.runId || "").trim();
|
|
1123
|
+
if (!runId) return;
|
|
1124
|
+
const list = buckets.get(runId);
|
|
1125
|
+
if (list) list.push(row);
|
|
1126
|
+
else buckets.set(runId, [row]);
|
|
1127
|
+
}
|
|
1128
|
+
function replaceInBucket(buckets, prev, next) {
|
|
1129
|
+
const list = buckets.get(prev.runId);
|
|
1130
|
+
if (!list) return;
|
|
1131
|
+
const idx = list.indexOf(prev);
|
|
1132
|
+
if (idx >= 0) list[idx] = next;
|
|
1133
|
+
if (prev.runId !== next.runId) {
|
|
1134
|
+
const oldList = buckets.get(prev.runId);
|
|
1135
|
+
if (oldList) {
|
|
1136
|
+
const i = oldList.indexOf(prev);
|
|
1137
|
+
if (i >= 0) oldList.splice(i, 1);
|
|
1138
|
+
if (!oldList.length) buckets.delete(prev.runId);
|
|
1139
|
+
}
|
|
1140
|
+
pushToBucket(buckets, next);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
// src/parser/extractors.ts
|
|
1145
|
+
function normalizeName(name) {
|
|
1146
|
+
const n = String(name || "").trim().toLowerCase();
|
|
1147
|
+
return n === "write_files" ? "write_file" : n;
|
|
1148
|
+
}
|
|
1149
|
+
function tryParseObject(result) {
|
|
1150
|
+
const text = String(result ?? "").trim();
|
|
1151
|
+
if (!text.startsWith("{")) return null;
|
|
1152
|
+
try {
|
|
1153
|
+
const parsed = JSON.parse(text);
|
|
1154
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
1155
|
+
return parsed;
|
|
1156
|
+
} catch {
|
|
1157
|
+
return null;
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
function extractFromToolResult(name, result, toolCallLike) {
|
|
1161
|
+
const tool = normalizeName(name);
|
|
1162
|
+
const obj = tryParseObject(result);
|
|
1163
|
+
if (tool === "ask_clarification" && obj) {
|
|
1164
|
+
const question = obj.question ?? obj.title;
|
|
1165
|
+
if (typeof question !== "string" || !question.trim()) return void 0;
|
|
1166
|
+
const options = Array.isArray(obj.options) ? obj.options : void 0;
|
|
1167
|
+
return options ? { kind: "clarification", question, options } : { kind: "clarification", question };
|
|
1168
|
+
}
|
|
1169
|
+
if (tool === "write_file") {
|
|
1170
|
+
if (obj) {
|
|
1171
|
+
if (typeof obj.body === "string" && obj.body) {
|
|
1172
|
+
const outline = typeof obj.outline === "string" ? obj.outline : void 0;
|
|
1173
|
+
return outline ? { kind: "report", reportKind: "report_body", body: obj.body, outline } : { kind: "report", reportKind: "report_body", body: obj.body };
|
|
1174
|
+
}
|
|
1175
|
+
if (Array.isArray(obj.files) && obj.files.length) {
|
|
1176
|
+
return { kind: "artifact", files: obj.files };
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
const reportKind = resolveReportArtifactKind(toolCallLike);
|
|
1180
|
+
if (reportKind) {
|
|
1181
|
+
const tc = toolCallLike ?? {};
|
|
1182
|
+
const sourcePath = String(tc?.artifact_meta?.path || tc?.args?.path || "").trim() || void 0;
|
|
1183
|
+
return {
|
|
1184
|
+
kind: "report",
|
|
1185
|
+
reportKind,
|
|
1186
|
+
sourcePath,
|
|
1187
|
+
title: sourcePath ? extractTitleFromArtifactPath(sourcePath, reportKind) : void 0
|
|
1188
|
+
};
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
return void 0;
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
// src/parser/tool-args.ts
|
|
1195
|
+
function asArgsObject(args) {
|
|
1196
|
+
if (args && typeof args === "object" && !Array.isArray(args)) return args;
|
|
1197
|
+
if (typeof args === "string") {
|
|
1198
|
+
try {
|
|
1199
|
+
const parsed = JSON.parse(args);
|
|
1200
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1201
|
+
return parsed;
|
|
1202
|
+
}
|
|
1203
|
+
} catch {
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
return void 0;
|
|
1207
|
+
}
|
|
1208
|
+
function pickRicherArgs(prev, next) {
|
|
1209
|
+
const nextObj = asArgsObject(next);
|
|
1210
|
+
if (!nextObj) return void 0;
|
|
1211
|
+
const prevObj = asArgsObject(prev);
|
|
1212
|
+
if (!prevObj) return nextObj;
|
|
1213
|
+
const prevKeys = new Set(Object.keys(prevObj));
|
|
1214
|
+
const hasNewKey = Object.keys(nextObj).some((k) => !prevKeys.has(k));
|
|
1215
|
+
const longer = JSON.stringify(nextObj).length > JSON.stringify(prevObj).length;
|
|
1216
|
+
return hasNewKey || longer ? nextObj : void 0;
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
// src/assembler/types.ts
|
|
1220
|
+
var BACKEND_STATUS_MAP = {
|
|
1221
|
+
success: "success",
|
|
1222
|
+
error: "error",
|
|
1223
|
+
interrupted: "interrupted",
|
|
1224
|
+
cancelled: "cancelled",
|
|
1225
|
+
pending: "pending",
|
|
1226
|
+
running: "running"
|
|
1227
|
+
};
|
|
1228
|
+
|
|
1229
|
+
// src/assembler/run-assembly.ts
|
|
1230
|
+
function emptyRunItem(runId, createdAt) {
|
|
1231
|
+
return {
|
|
1232
|
+
runId,
|
|
1233
|
+
input: { kind: "message", text: "" },
|
|
1234
|
+
status: "pending",
|
|
1235
|
+
body: "",
|
|
1236
|
+
segments: [{ type: "text", content: "" }],
|
|
1237
|
+
tools: [],
|
|
1238
|
+
attachments: [],
|
|
1239
|
+
clarifications: [],
|
|
1240
|
+
rawMessages: [],
|
|
1241
|
+
...createdAt !== void 0 ? { createdAt } : {}
|
|
1242
|
+
};
|
|
1243
|
+
}
|
|
1244
|
+
function assembleRun(runId, options) {
|
|
1245
|
+
const rows = options.rows;
|
|
1246
|
+
const twinEnabled = !!options.twin?.enabled;
|
|
1247
|
+
const twinToolPrefix = options.twin?.toolPrefix || "city-digital-twin-display_";
|
|
1248
|
+
let body = "";
|
|
1249
|
+
let feedback;
|
|
1250
|
+
const tools = [];
|
|
1251
|
+
const toolByCallId = /* @__PURE__ */ new Map();
|
|
1252
|
+
let createdAt;
|
|
1253
|
+
for (const row of rows) {
|
|
1254
|
+
const msg = row.msg;
|
|
1255
|
+
const type = String(msg?.type || "");
|
|
1256
|
+
if (createdAt === void 0 && row.createdAt !== void 0) createdAt = row.createdAt;
|
|
1257
|
+
if (type === "ai") {
|
|
1258
|
+
const text = extractAiContentFromMessage(msg);
|
|
1259
|
+
if (text) body = body ? `${body}
|
|
1260
|
+
${text}` : text;
|
|
1261
|
+
registerToolCalls(msg, tools, toolByCallId);
|
|
1262
|
+
} else if (type === "tool") {
|
|
1263
|
+
applyToolMessage(msg, tools, toolByCallId);
|
|
1264
|
+
} else if (type === "human") {
|
|
1265
|
+
}
|
|
1266
|
+
if (row.feedback !== void 0 && row.feedback !== null) feedback = row.feedback;
|
|
1267
|
+
}
|
|
1268
|
+
const attachments = assembleAttachments(tools, twinEnabled, twinToolPrefix);
|
|
1269
|
+
const clarifications = extractClarifications(tools);
|
|
1270
|
+
const segments = options.streaming ? [{ type: "text", content: body }] : sliceBodySegments(body);
|
|
1271
|
+
return {
|
|
1272
|
+
runId,
|
|
1273
|
+
// input 由 projectRuns 层填(需要 runs.list / 窗口 human 行两级来源),这里占位
|
|
1274
|
+
input: { kind: "message", text: "" },
|
|
1275
|
+
status: "success",
|
|
1276
|
+
body,
|
|
1277
|
+
segments,
|
|
1278
|
+
tools,
|
|
1279
|
+
attachments,
|
|
1280
|
+
...feedback !== void 0 ? { feedback } : {},
|
|
1281
|
+
clarifications,
|
|
1282
|
+
...createdAt !== void 0 ? { createdAt } : {},
|
|
1283
|
+
rawMessages: [...rows]
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
function extractInputFromRows(rows) {
|
|
1287
|
+
for (const row of rows) {
|
|
1288
|
+
const msg = row.msg;
|
|
1289
|
+
if (!isVisibleUserMessage(msg)) continue;
|
|
1290
|
+
const kwargs = msg?.additional_kwargs;
|
|
1291
|
+
return {
|
|
1292
|
+
text: readMessageContentText(msg).trim(),
|
|
1293
|
+
...kwargs && typeof kwargs === "object" ? { kwargs: { ...kwargs } } : {}
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
return { text: "" };
|
|
1297
|
+
}
|
|
1298
|
+
function registerToolCalls(msg, tools, byCallId) {
|
|
1299
|
+
const calls = Array.isArray(msg?.tool_calls) ? msg.tool_calls : msg?.additional_kwargs?.tool_calls;
|
|
1300
|
+
if (!Array.isArray(calls)) return;
|
|
1301
|
+
for (const call of calls) {
|
|
1302
|
+
const callId = String(call?.id || "").trim();
|
|
1303
|
+
if (!callId) continue;
|
|
1304
|
+
const input = asArgsObject(call?.args);
|
|
1305
|
+
const artifactMeta = call?.artifact_meta;
|
|
1306
|
+
const prev = byCallId.get(callId);
|
|
1307
|
+
if (prev) {
|
|
1308
|
+
const richer = pickRicherArgs(prev.input, call?.args);
|
|
1309
|
+
if (richer) prev.input = richer;
|
|
1310
|
+
if (!prev.artifactMeta && artifactMeta) prev.artifactMeta = artifactMeta;
|
|
1311
|
+
continue;
|
|
1312
|
+
}
|
|
1313
|
+
const tool = { callId, name: String(call?.name || ""), status: "running" };
|
|
1314
|
+
if (input !== void 0) tool.input = input;
|
|
1315
|
+
if (artifactMeta !== void 0) tool.artifactMeta = artifactMeta;
|
|
1316
|
+
tools.push(tool);
|
|
1317
|
+
byCallId.set(callId, tool);
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
function applyToolMessage(msg, tools, byCallId) {
|
|
1321
|
+
const callId = String(msg?.tool_call_id || "").trim();
|
|
1322
|
+
if (!callId) return;
|
|
1323
|
+
const tool = byCallId.get(callId);
|
|
1324
|
+
if (!tool) return;
|
|
1325
|
+
const result = readMessageContentText(msg);
|
|
1326
|
+
tool.result = result;
|
|
1327
|
+
const extracted = extractFromToolResult(tool.name, result, { artifact_meta: tool.artifactMeta, args: tool.input });
|
|
1328
|
+
if (extracted) tool.extracted = extracted;
|
|
1329
|
+
tool.status = String(msg?.status || "") === "error" ? "error" : "finished";
|
|
1330
|
+
}
|
|
1331
|
+
function assembleAttachments(tools, twinEnabled, twinToolPrefix) {
|
|
1332
|
+
const byKind = /* @__PURE__ */ new Map();
|
|
1333
|
+
for (const tool of tools) {
|
|
1334
|
+
const ex = tool.extracted;
|
|
1335
|
+
if (ex?.kind === "report") {
|
|
1336
|
+
byKind.set(`report:${ex.reportKind}`, {
|
|
1337
|
+
kind: "report",
|
|
1338
|
+
reportKind: ex.reportKind,
|
|
1339
|
+
body: ex.body,
|
|
1340
|
+
outline: ex.outline,
|
|
1341
|
+
sourcePath: ex.sourcePath,
|
|
1342
|
+
title: ex.title
|
|
1343
|
+
});
|
|
1344
|
+
} else if (ex?.kind === "artifact") {
|
|
1345
|
+
byKind.set("artifact", { kind: "artifact", files: ex.files });
|
|
1346
|
+
} else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
|
|
1347
|
+
byKind.set("twin", { kind: "twin", payload: tool.input });
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
return [...byKind.values()];
|
|
1351
|
+
}
|
|
1352
|
+
function extractClarifications(tools) {
|
|
1353
|
+
const out = [];
|
|
1354
|
+
for (const tool of tools) {
|
|
1355
|
+
if (tool.name !== "ask_clarification") continue;
|
|
1356
|
+
const args = asArgsObject(tool.input);
|
|
1357
|
+
const question = String(args?.question ?? args?.title ?? "").trim();
|
|
1358
|
+
if (!question) continue;
|
|
1359
|
+
const record = { callId: tool.callId, question };
|
|
1360
|
+
if (args?.options !== void 0) record.options = args.options;
|
|
1361
|
+
if (Array.isArray(args?.fields)) record.fields = args.fields;
|
|
1362
|
+
out.push(record);
|
|
1363
|
+
}
|
|
1364
|
+
return out;
|
|
1365
|
+
}
|
|
1366
|
+
function mapBackendStatus(raw) {
|
|
1367
|
+
const v = String(raw || "").trim();
|
|
1368
|
+
return BACKEND_STATUS_MAP[v] ?? "success";
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
// src/assembler/project-runs.ts
|
|
1372
|
+
function classifyInputKind(inputMsg) {
|
|
1373
|
+
const kwargs = inputMsg?.additional_kwargs;
|
|
1374
|
+
if (kwargs?.human_input_response && typeof kwargs.human_input_response === "object") return "clarification";
|
|
1375
|
+
return "message";
|
|
1376
|
+
}
|
|
1377
|
+
function inputFromRunMeta(meta) {
|
|
1378
|
+
const messages = meta.inputMessages ?? [];
|
|
1379
|
+
if (!messages.length) return null;
|
|
1380
|
+
const first = messages[0];
|
|
1381
|
+
const visible = messages.find((m) => isVisibleUserMessage(m));
|
|
1382
|
+
const text = visible ? readMessageContentText(visible) : "";
|
|
1383
|
+
const kwargs = first.additional_kwargs;
|
|
1384
|
+
const hasKwargs = kwargs && typeof kwargs === "object" && Object.keys(kwargs).length > 0;
|
|
1385
|
+
return {
|
|
1386
|
+
kind: classifyInputKind(first),
|
|
1387
|
+
text,
|
|
1388
|
+
...hasKwargs ? { kwargs: { ...kwargs } } : {}
|
|
1389
|
+
};
|
|
1390
|
+
}
|
|
1391
|
+
function normalizeRequestId(raw) {
|
|
1392
|
+
return String(raw ?? "").trim().replace("clarification:", "");
|
|
1393
|
+
}
|
|
1394
|
+
function projectRuns(input) {
|
|
1395
|
+
const buckets = groupRowsByRun(input.rows, input.liveMessages, input.activeRunId, input.pendingRun?.runId ?? null);
|
|
1396
|
+
const metaByRunId = new Map(input.runsList.map((m) => [String(m.runId || ""), m]));
|
|
1397
|
+
const orderedBuckets = [...buckets.entries()].sort(
|
|
1398
|
+
(a, b) => (a[1][0]?.seq ?? 0) - (b[1][0]?.seq ?? 0)
|
|
1399
|
+
);
|
|
1400
|
+
const runs = [];
|
|
1401
|
+
for (const [runId, rows] of orderedBuckets) {
|
|
1402
|
+
const meta = metaByRunId.get(runId);
|
|
1403
|
+
const isStreamingRun = input.streaming && input.activeRunId === runId;
|
|
1404
|
+
const item = assembleRun(runId, { rows, streaming: isStreamingRun, twin: input.twin });
|
|
1405
|
+
const fromMeta = meta ? inputFromRunMeta(meta) : void 0;
|
|
1406
|
+
if (fromMeta) {
|
|
1407
|
+
item.input = fromMeta;
|
|
1408
|
+
} else {
|
|
1409
|
+
const fromRows = extractInputFromRows(rows);
|
|
1410
|
+
if (fromRows.text) {
|
|
1411
|
+
item.input = {
|
|
1412
|
+
kind: classifyInputKind(fromRows.kwargs),
|
|
1413
|
+
text: fromRows.text,
|
|
1414
|
+
...fromRows.kwargs ? { kwargs: fromRows.kwargs } : {}
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
const pendingInput = input.pendingRun;
|
|
1419
|
+
if (pendingInput && runId === pendingInput.runId && !item.input.text) {
|
|
1420
|
+
item.input = {
|
|
1421
|
+
kind: pendingInput.kind,
|
|
1422
|
+
text: pendingInput.text,
|
|
1423
|
+
...pendingInput.kwargs ? { kwargs: pendingInput.kwargs } : {}
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
if (isStreamingRun) item.status = "running";
|
|
1427
|
+
else if (meta) {
|
|
1428
|
+
item.status = mapBackendStatus(meta.status);
|
|
1429
|
+
if (meta.tokens) item.tokens = meta.tokens;
|
|
1430
|
+
if (meta.createdAt !== void 0) item.createdAt = meta.createdAt;
|
|
1431
|
+
if (meta.stopReason) item.stopReason = meta.stopReason;
|
|
1432
|
+
}
|
|
1433
|
+
runs.push(item);
|
|
1434
|
+
}
|
|
1435
|
+
const pending = input.pendingRun;
|
|
1436
|
+
if (pending && !buckets.has(pending.runId)) {
|
|
1437
|
+
const placeholder = emptyRunItem(pending.runId, Date.now());
|
|
1438
|
+
placeholder.input = { kind: pending.kind, text: pending.text, ...pending.kwargs ? { kwargs: { ...pending.kwargs } } : {} };
|
|
1439
|
+
if (input.streaming && input.activeRunId === pending.runId) placeholder.status = "running";
|
|
1440
|
+
runs.push(placeholder);
|
|
1441
|
+
}
|
|
1442
|
+
const answers = input.answers;
|
|
1443
|
+
for (let i = 0; i < runs.length; i++) {
|
|
1444
|
+
const run = runs[i];
|
|
1445
|
+
for (const record of run.clarifications) {
|
|
1446
|
+
if (record.answer !== void 0) continue;
|
|
1447
|
+
const optimistic = answers?.get(record.callId);
|
|
1448
|
+
if (optimistic !== void 0) {
|
|
1449
|
+
record.answer = optimistic;
|
|
1450
|
+
continue;
|
|
1451
|
+
}
|
|
1452
|
+
for (let j = i + 1; j < runs.length; j++) {
|
|
1453
|
+
const laterKwargs = runs[j].input.kwargs;
|
|
1454
|
+
const response = laterKwargs?.human_input_response;
|
|
1455
|
+
if (!response || typeof response !== "object") continue;
|
|
1456
|
+
if (normalizeRequestId(response.request_id) !== normalizeRequestId(record.callId)) continue;
|
|
1457
|
+
record.answer = formatAnswerText(response.value);
|
|
1458
|
+
record.answerRunId = runs[j].runId;
|
|
1459
|
+
break;
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
return runs;
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1005
1466
|
// src/runtime/run-info.ts
|
|
1006
1467
|
function buildRunInfo(run, threadId) {
|
|
1007
1468
|
return {
|
|
@@ -1031,6 +1492,32 @@ function buildRunStatus(run) {
|
|
|
1031
1492
|
function buildRunCreatedAt(run) {
|
|
1032
1493
|
return run?.created_at ? Number(new Date(run.created_at)) : void 0;
|
|
1033
1494
|
}
|
|
1495
|
+
function buildRunMeta(run) {
|
|
1496
|
+
const runId = String(run?.run_id || "").trim();
|
|
1497
|
+
if (!runId) return null;
|
|
1498
|
+
const inputMessages = run?.kwargs?.input?.messages ?? [];
|
|
1499
|
+
const totalTokens = Number(run?.total_tokens);
|
|
1500
|
+
const tokens = Number.isFinite(totalTokens) && totalTokens > 0 ? {
|
|
1501
|
+
total: totalTokens,
|
|
1502
|
+
input: Number(run?.total_input_tokens) || 0,
|
|
1503
|
+
output: Number(run?.total_output_tokens) || 0,
|
|
1504
|
+
...Number.isFinite(Number(run?.llm_call_count)) ? { llmCallCount: Number(run.llm_call_count) } : {},
|
|
1505
|
+
byCaller: {
|
|
1506
|
+
leadAgent: Number(run?.lead_agent_tokens) || 0,
|
|
1507
|
+
subagent: Number(run?.subagent_tokens) || 0,
|
|
1508
|
+
middleware: Number(run?.middleware_tokens) || 0
|
|
1509
|
+
}
|
|
1510
|
+
} : void 0;
|
|
1511
|
+
const createdAt = buildRunCreatedAt(run);
|
|
1512
|
+
return {
|
|
1513
|
+
runId,
|
|
1514
|
+
status: String(run?.status || "").trim(),
|
|
1515
|
+
...createdAt !== void 0 ? { createdAt } : {},
|
|
1516
|
+
...Array.isArray(inputMessages) && inputMessages.length ? { inputMessages } : {},
|
|
1517
|
+
...tokens ? { tokens } : {},
|
|
1518
|
+
...run?.stop_reason !== void 0 && run?.stop_reason !== null ? { stopReason: String(run.stop_reason) } : {}
|
|
1519
|
+
};
|
|
1520
|
+
}
|
|
1034
1521
|
function buildRunDirectLatencyMs(run) {
|
|
1035
1522
|
const direct = Number(run?.latency_ms);
|
|
1036
1523
|
return direct || void 0;
|
|
@@ -1136,756 +1623,11 @@ function applySemanticPatches(messages, patches) {
|
|
|
1136
1623
|
});
|
|
1137
1624
|
}
|
|
1138
1625
|
|
|
1139
|
-
// src/materializer/extractors.ts
|
|
1140
|
-
function normalizeName(name) {
|
|
1141
|
-
const n = String(name || "").trim().toLowerCase();
|
|
1142
|
-
return n === "write_files" ? "write_file" : n;
|
|
1143
|
-
}
|
|
1144
|
-
function tryParseObject(result) {
|
|
1145
|
-
const text = String(result ?? "").trim();
|
|
1146
|
-
if (!text.startsWith("{")) return null;
|
|
1147
|
-
try {
|
|
1148
|
-
const parsed = JSON.parse(text);
|
|
1149
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
1150
|
-
return parsed;
|
|
1151
|
-
} catch {
|
|
1152
|
-
return null;
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
function extractFromToolResult(name, result, toolCallLike) {
|
|
1156
|
-
const tool = normalizeName(name);
|
|
1157
|
-
const obj = tryParseObject(result);
|
|
1158
|
-
if (tool === "ask_clarification" && obj) {
|
|
1159
|
-
const question = obj.question ?? obj.title;
|
|
1160
|
-
if (typeof question !== "string" || !question.trim()) return void 0;
|
|
1161
|
-
const options = Array.isArray(obj.options) ? obj.options : void 0;
|
|
1162
|
-
return options ? { kind: "clarification", question, options } : { kind: "clarification", question };
|
|
1163
|
-
}
|
|
1164
|
-
if (tool === "write_file") {
|
|
1165
|
-
if (obj) {
|
|
1166
|
-
if (typeof obj.body === "string" && obj.body) {
|
|
1167
|
-
const outline = typeof obj.outline === "string" ? obj.outline : void 0;
|
|
1168
|
-
return outline ? { kind: "report", reportKind: "report_body", body: obj.body, outline } : { kind: "report", reportKind: "report_body", body: obj.body };
|
|
1169
|
-
}
|
|
1170
|
-
if (Array.isArray(obj.files) && obj.files.length) {
|
|
1171
|
-
return { kind: "artifact", files: obj.files };
|
|
1172
|
-
}
|
|
1173
|
-
}
|
|
1174
|
-
const reportKind = resolveReportArtifactKind(toolCallLike);
|
|
1175
|
-
if (reportKind) {
|
|
1176
|
-
const tc = toolCallLike ?? {};
|
|
1177
|
-
const sourcePath = String(tc?.artifact_meta?.path || tc?.args?.path || "").trim() || void 0;
|
|
1178
|
-
return {
|
|
1179
|
-
kind: "report",
|
|
1180
|
-
reportKind,
|
|
1181
|
-
sourcePath,
|
|
1182
|
-
title: sourcePath ? extractTitleFromArtifactPath(sourcePath, reportKind) : void 0
|
|
1183
|
-
};
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
return void 0;
|
|
1187
|
-
}
|
|
1188
|
-
|
|
1189
|
-
// src/materializer/diff.ts
|
|
1190
|
-
function diffMessageSnapshots(baseline, next) {
|
|
1191
|
-
const upserts = [];
|
|
1192
|
-
const nextBaseline = /* @__PURE__ */ new Map();
|
|
1193
|
-
for (const msg of next) {
|
|
1194
|
-
const id = String(msg?.id || "").trim();
|
|
1195
|
-
if (!id) continue;
|
|
1196
|
-
if (baseline.get(id) !== msg) upserts.push(msg);
|
|
1197
|
-
nextBaseline.set(id, msg);
|
|
1198
|
-
}
|
|
1199
|
-
const removals = [];
|
|
1200
|
-
for (const id of baseline.keys()) if (!nextBaseline.has(id)) removals.push(id);
|
|
1201
|
-
return { upserts, removals, nextBaseline };
|
|
1202
|
-
}
|
|
1203
|
-
function createMessageDiff() {
|
|
1204
|
-
let baseline = /* @__PURE__ */ new Map();
|
|
1205
|
-
return {
|
|
1206
|
-
apply(next) {
|
|
1207
|
-
const { upserts, removals, nextBaseline } = diffMessageSnapshots(baseline, next);
|
|
1208
|
-
const deltas = [];
|
|
1209
|
-
for (const msg of upserts) {
|
|
1210
|
-
const id = String(msg?.id || "").trim();
|
|
1211
|
-
deltas.push(baseline.has(id) ? { type: "update", id, message: msg } : { type: "append", message: msg });
|
|
1212
|
-
}
|
|
1213
|
-
for (const id of removals) deltas.push({ type: "tail-remove", id });
|
|
1214
|
-
baseline = nextBaseline;
|
|
1215
|
-
return deltas;
|
|
1216
|
-
},
|
|
1217
|
-
reset() {
|
|
1218
|
-
baseline = /* @__PURE__ */ new Map();
|
|
1219
|
-
},
|
|
1220
|
-
get baselineSize() {
|
|
1221
|
-
return baseline.size;
|
|
1222
|
-
}
|
|
1223
|
-
};
|
|
1224
|
-
}
|
|
1225
|
-
|
|
1226
|
-
// src/materializer/materializer.ts
|
|
1227
|
-
import { shallowRef } from "vue";
|
|
1228
|
-
|
|
1229
|
-
// src/materializer/indexes.ts
|
|
1230
|
-
function createIndexes() {
|
|
1231
|
-
return { byMessageId: /* @__PURE__ */ new Map(), byToolCallId: /* @__PURE__ */ new Map(), byRunId: /* @__PURE__ */ new Map() };
|
|
1232
|
-
}
|
|
1233
|
-
function rebuildIndexes(turns) {
|
|
1234
|
-
const idx = createIndexes();
|
|
1235
|
-
turns.forEach((turn, ti) => {
|
|
1236
|
-
idx.byMessageId.set(turn.id, { turn: ti, ai: null });
|
|
1237
|
-
idx.byRunId.set(turn.runId, { turn: ti, ai: 0 });
|
|
1238
|
-
turn.ai.forEach((seg, ai_i) => {
|
|
1239
|
-
idx.byMessageId.set(seg.id, { turn: ti, ai: ai_i });
|
|
1240
|
-
for (const mid of seg.messageIds ?? []) {
|
|
1241
|
-
if (mid) idx.byMessageId.set(mid, { turn: ti, ai: ai_i });
|
|
1242
|
-
}
|
|
1243
|
-
idx.byRunId.set(seg.runId, { turn: ti, ai: ai_i });
|
|
1244
|
-
seg.tools.forEach((tool, tool_i) => {
|
|
1245
|
-
idx.byToolCallId.set(tool.callId, { turn: ti, ai: ai_i, tool: tool_i });
|
|
1246
|
-
});
|
|
1247
|
-
});
|
|
1248
|
-
});
|
|
1249
|
-
return idx;
|
|
1250
|
-
}
|
|
1251
|
-
|
|
1252
|
-
// src/materializer/turn-machine-rules.ts
|
|
1253
|
-
function messageRunId(msg) {
|
|
1254
|
-
const own = String(asSxin(msg).runId || "").trim();
|
|
1255
|
-
if (own) return own;
|
|
1256
|
-
return String(asSxin(msg).additional_kwargs?.run_id || "").trim() || void 0;
|
|
1257
|
-
}
|
|
1258
|
-
function isHiddenHuman(msg) {
|
|
1259
|
-
return msg?.additional_kwargs?.hide_from_ui === true;
|
|
1260
|
-
}
|
|
1261
|
-
function hasEmptyKwargs(msg) {
|
|
1262
|
-
const kwargs = msg?.additional_kwargs;
|
|
1263
|
-
return !kwargs || typeof kwargs !== "object" || Object.keys(kwargs).length === 0;
|
|
1264
|
-
}
|
|
1265
|
-
function resolveHumanKwargsMerge(prevKwargs, incomingKwargs, incomingIsVariant) {
|
|
1266
|
-
if (incomingIsVariant) return prevKwargs;
|
|
1267
|
-
const prevEmpty = !prevKwargs || typeof prevKwargs !== "object" || Object.keys(prevKwargs).length === 0;
|
|
1268
|
-
return prevEmpty ? incomingKwargs : prevKwargs;
|
|
1269
|
-
}
|
|
1270
|
-
function readHir(msg) {
|
|
1271
|
-
const response = msg?.additional_kwargs?.human_input_response;
|
|
1272
|
-
if (!response || typeof response !== "object") return null;
|
|
1273
|
-
const requestId = String(response.request_id || "").trim().replace("clarification:", "");
|
|
1274
|
-
if (!requestId || response.value === void 0) return null;
|
|
1275
|
-
return { requestId, value: response.value };
|
|
1276
|
-
}
|
|
1277
|
-
function buildClarification(tool) {
|
|
1278
|
-
if (tool.name !== "ask_clarification") return null;
|
|
1279
|
-
const args = tool.input ?? {};
|
|
1280
|
-
const question = typeof args.question === "string" ? args.question : "";
|
|
1281
|
-
if (!question) return null;
|
|
1282
|
-
const fields = Array.isArray(args.fields) ? args.fields : void 0;
|
|
1283
|
-
return {
|
|
1284
|
-
callId: tool.callId,
|
|
1285
|
-
question,
|
|
1286
|
-
...args.options !== void 0 ? { options: args.options } : {},
|
|
1287
|
-
...fields?.length ? { fields } : {}
|
|
1288
|
-
};
|
|
1289
|
-
}
|
|
1290
|
-
function createTurnRules(ctx) {
|
|
1291
|
-
const { state } = ctx;
|
|
1292
|
-
const registerToolCalls = (ti, ai_i, msg, effects) => {
|
|
1293
|
-
const toolCalls = msg?.tool_calls;
|
|
1294
|
-
if (!Array.isArray(toolCalls) || !toolCalls.length) return;
|
|
1295
|
-
let turn = state.turns[ti];
|
|
1296
|
-
for (const tc of toolCalls) {
|
|
1297
|
-
const callId = String(tc?.id || "").trim();
|
|
1298
|
-
if (!callId || ctx.indexes().byToolCallId.has(callId)) continue;
|
|
1299
|
-
const tool = {
|
|
1300
|
-
callId,
|
|
1301
|
-
name: String(tc?.name || ""),
|
|
1302
|
-
input: tc?.args,
|
|
1303
|
-
artifactMeta: tc?.artifact_meta,
|
|
1304
|
-
status: "running"
|
|
1305
|
-
};
|
|
1306
|
-
turn = ctx.cloneWith(turn, ai_i, (t) => {
|
|
1307
|
-
t.ai[ai_i].tools = [...turn.ai[ai_i].tools, tool];
|
|
1308
|
-
});
|
|
1309
|
-
const tool_i = turn.ai[ai_i].tools.length - 1;
|
|
1310
|
-
ctx.indexes().byToolCallId.set(callId, { turn: ti, ai: ai_i, tool: tool_i });
|
|
1311
|
-
effects.push({ type: "tool-updated", turnId: turn.id, aiId: turn.ai[ai_i].id, tool });
|
|
1312
|
-
const clarification = buildClarification(tool);
|
|
1313
|
-
if (clarification) {
|
|
1314
|
-
turn = ctx.cloneWith(turn, null, (t) => {
|
|
1315
|
-
t.clarifications = [...turn.clarifications, clarification];
|
|
1316
|
-
});
|
|
1317
|
-
}
|
|
1318
|
-
}
|
|
1319
|
-
state.turns[ti] = turn;
|
|
1320
|
-
};
|
|
1321
|
-
const openNewAi = (ti, msg, effects) => {
|
|
1322
|
-
let turn = state.turns[ti];
|
|
1323
|
-
if (state.openAi !== null) {
|
|
1324
|
-
turn = ctx.sealAiSegment(turn, state.openAi, effects);
|
|
1325
|
-
}
|
|
1326
|
-
const runId = messageRunId(msg) || ctx.streamRunId() || "";
|
|
1327
|
-
const body = readMessageContentText(msg);
|
|
1328
|
-
const seg = {
|
|
1329
|
-
id: String(msg?.id || ""),
|
|
1330
|
-
runId,
|
|
1331
|
-
body,
|
|
1332
|
-
streamingText: body,
|
|
1333
|
-
tools: [],
|
|
1334
|
-
attachments: [],
|
|
1335
|
-
segments: [{ type: "text", content: body }],
|
|
1336
|
-
status: "streaming",
|
|
1337
|
-
// 段内消息 id 登记(rebuildIndexes 重建 byMessageId 的依据,防 finalize 后 update 索引 miss)
|
|
1338
|
-
messageIds: [String(msg?.id || "")].filter(Boolean)
|
|
1339
|
-
};
|
|
1340
|
-
turn = ctx.cloneWith(turn, null, (t) => {
|
|
1341
|
-
t.ai = [...turn.ai, seg];
|
|
1342
|
-
if (!t.runId && runId) t.runId = runId;
|
|
1343
|
-
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1344
|
-
});
|
|
1345
|
-
state.turns[ti] = turn;
|
|
1346
|
-
state.openAi = turn.ai.length - 1;
|
|
1347
|
-
ctx.indexes().byRunId.set(runId, { turn: ti, ai: state.openAi });
|
|
1348
|
-
if (seg.id) ctx.indexes().byMessageId.set(seg.id, { turn: ti, ai: state.openAi });
|
|
1349
|
-
effects.push({ type: "ai-opened", turnId: turn.id, ai: turn.ai[turn.ai.length - 1] });
|
|
1350
|
-
registerToolCalls(ti, state.openAi, msg, effects);
|
|
1351
|
-
};
|
|
1352
|
-
const appendHuman = (msg, allowOptimistic, effects) => {
|
|
1353
|
-
const id = String(msg?.id || "").trim();
|
|
1354
|
-
const baseId = getHumanMessageBaseId(id) || id;
|
|
1355
|
-
const msgRunId = String(msg?.additional_kwargs?.run_id || "").trim();
|
|
1356
|
-
if (msgRunId) {
|
|
1357
|
-
for (let ti = state.turns.length - 1; ti >= 0; ti--) {
|
|
1358
|
-
const t = state.turns[ti];
|
|
1359
|
-
const tBase = getHumanMessageBaseId(t.human.id) || t.human.id;
|
|
1360
|
-
const tRun = String(t.human.kwargs?.run_id || "").trim();
|
|
1361
|
-
if (tBase === baseId && tRun && tRun === msgRunId) {
|
|
1362
|
-
const mergedKwargs = resolveHumanKwargsMerge(
|
|
1363
|
-
t.human.kwargs,
|
|
1364
|
-
msg?.additional_kwargs,
|
|
1365
|
-
baseId !== id
|
|
1366
|
-
);
|
|
1367
|
-
const next = ctx.cloneWith(t, null, (t2) => {
|
|
1368
|
-
t2.human = {
|
|
1369
|
-
id: t.human.id || id,
|
|
1370
|
-
text: t.human.text || extractTextFromMessage(msg),
|
|
1371
|
-
kwargs: mergedKwargs
|
|
1372
|
-
};
|
|
1373
|
-
t2.rawMessages = [...t2.rawMessages ?? [], msg];
|
|
1374
|
-
});
|
|
1375
|
-
state.turns[ti] = next;
|
|
1376
|
-
if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
|
|
1377
|
-
effects.push({ type: "message-updated", turnId: next.id, aiId: null });
|
|
1378
|
-
return;
|
|
1379
|
-
}
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
if (state.openTurn !== null && !state.turns[state.openTurn].ai.length) {
|
|
1383
|
-
const openHumanBase = getHumanMessageBaseId(state.turns[state.openTurn].human.id);
|
|
1384
|
-
if (openHumanBase && openHumanBase === baseId) {
|
|
1385
|
-
const ti = state.openTurn;
|
|
1386
|
-
const mergedKwargs = resolveHumanKwargsMerge(
|
|
1387
|
-
state.turns[ti].human.kwargs,
|
|
1388
|
-
msg?.additional_kwargs,
|
|
1389
|
-
baseId !== id
|
|
1390
|
-
);
|
|
1391
|
-
const next = ctx.cloneWith(state.turns[ti], null, (t) => {
|
|
1392
|
-
t.human = { id, text: extractTextFromMessage(msg), kwargs: mergedKwargs };
|
|
1393
|
-
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1394
|
-
});
|
|
1395
|
-
state.turns[ti] = next;
|
|
1396
|
-
ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
|
|
1397
|
-
effects.push({ type: "message-updated", turnId: next.id, aiId: null });
|
|
1398
|
-
return;
|
|
1399
|
-
}
|
|
1400
|
-
}
|
|
1401
|
-
const optimistic = allowOptimistic && !!id && !ctx.indexes().byMessageId.has(id) && !messageRunId(msg) && hasEmptyKwargs(msg);
|
|
1402
|
-
ctx.sealOpenTurn(effects);
|
|
1403
|
-
const turn = {
|
|
1404
|
-
id: id || `turn-${state.turns.length}`,
|
|
1405
|
-
runId: "",
|
|
1406
|
-
createdAt: Number(new Date(msg?.created_at || Date.now())) || Date.now(),
|
|
1407
|
-
human: { id, text: extractTextFromMessage(msg), kwargs: msg?.additional_kwargs },
|
|
1408
|
-
ai: [],
|
|
1409
|
-
clarifications: [],
|
|
1410
|
-
status: "streaming",
|
|
1411
|
-
optimistic,
|
|
1412
|
-
// 原始消息入档(排查用)
|
|
1413
|
-
rawMessages: [msg]
|
|
1414
|
-
};
|
|
1415
|
-
state.turns.push(turn);
|
|
1416
|
-
state.openTurn = state.turns.length - 1;
|
|
1417
|
-
if (id) ctx.indexes().byMessageId.set(id, { turn: state.openTurn, ai: null });
|
|
1418
|
-
if (optimistic) state.optimisticTurnId = turn.id;
|
|
1419
|
-
effects.push({ type: "turn-opened", turn, optimistic });
|
|
1420
|
-
};
|
|
1421
|
-
const appendHiddenHuman = (msg, effects) => {
|
|
1422
|
-
const hir = readHir(msg);
|
|
1423
|
-
if (!hir) return;
|
|
1424
|
-
const toolLoc = ctx.indexes().byToolCallId.get(hir.requestId);
|
|
1425
|
-
const ti = toolLoc?.turn ?? state.openTurn ?? state.turns.length - 1;
|
|
1426
|
-
if (ti < 0) return;
|
|
1427
|
-
const turn = state.turns[ti];
|
|
1428
|
-
const ci = turn.clarifications.findIndex((c) => c.callId === hir.requestId);
|
|
1429
|
-
if (ci < 0) return;
|
|
1430
|
-
const answer = formatAnswerText(hir.value);
|
|
1431
|
-
const id = String(msg?.id || "").trim();
|
|
1432
|
-
const next = ctx.cloneWith(turn, null, (t) => {
|
|
1433
|
-
t.clarifications[ci] = { ...t.clarifications[ci], answer, answerMessageId: id || void 0 };
|
|
1434
|
-
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1435
|
-
});
|
|
1436
|
-
state.turns[ti] = next;
|
|
1437
|
-
if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: null });
|
|
1438
|
-
effects.push({ type: "clarification-answered", turnId: next.id, callId: hir.requestId, answer });
|
|
1439
|
-
};
|
|
1440
|
-
const applyToolMessage = (msg, effects) => {
|
|
1441
|
-
const m = msg;
|
|
1442
|
-
const callId = String(m?.tool_call_id || "").trim();
|
|
1443
|
-
if (!callId) return;
|
|
1444
|
-
const result = readMessageContentText(m);
|
|
1445
|
-
const status = m?.status === "error" ? "error" : "finished";
|
|
1446
|
-
const id = String(m?.id || "").trim();
|
|
1447
|
-
const loc = ctx.indexes().byToolCallId.get(callId);
|
|
1448
|
-
if (loc) {
|
|
1449
|
-
const turn2 = state.turns[loc.turn];
|
|
1450
|
-
const old = turn2.ai[loc.ai].tools[loc.tool];
|
|
1451
|
-
const tool = {
|
|
1452
|
-
...old,
|
|
1453
|
-
status,
|
|
1454
|
-
result,
|
|
1455
|
-
extracted: extractFromToolResult(old.name, result, { artifact_meta: old.artifactMeta, args: old.input }) ?? old.extracted
|
|
1456
|
-
};
|
|
1457
|
-
const next2 = ctx.cloneWith(turn2, loc.ai, (t) => {
|
|
1458
|
-
t.ai[loc.ai].tools[loc.tool] = tool;
|
|
1459
|
-
if (t.ai[loc.ai].status === "sealed") t.ai[loc.ai].attachments = ctx.assembleAttachments(t.ai[loc.ai]);
|
|
1460
|
-
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1461
|
-
});
|
|
1462
|
-
state.turns[loc.turn] = next2;
|
|
1463
|
-
if (id) ctx.indexes().byMessageId.set(id, { turn: loc.turn, ai: loc.ai });
|
|
1464
|
-
effects.push({ type: "tool-updated", turnId: next2.id, aiId: next2.ai[loc.ai].id, tool });
|
|
1465
|
-
return;
|
|
1466
|
-
}
|
|
1467
|
-
const ti = state.openTurn;
|
|
1468
|
-
const ai_i = state.openAi;
|
|
1469
|
-
if (ti === null || ai_i === null) return;
|
|
1470
|
-
const orphan = {
|
|
1471
|
-
callId,
|
|
1472
|
-
name: String(m?.name || ""),
|
|
1473
|
-
input: {},
|
|
1474
|
-
status,
|
|
1475
|
-
result,
|
|
1476
|
-
extracted: extractFromToolResult(String(m?.name || ""), result)
|
|
1477
|
-
};
|
|
1478
|
-
const turn = state.turns[ti];
|
|
1479
|
-
const next = ctx.cloneWith(turn, ai_i, (t) => {
|
|
1480
|
-
t.ai[ai_i].tools = [...turn.ai[ai_i].tools, orphan];
|
|
1481
|
-
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1482
|
-
});
|
|
1483
|
-
state.turns[ti] = next;
|
|
1484
|
-
ctx.indexes().byToolCallId.set(callId, { turn: ti, ai: ai_i, tool: next.ai[ai_i].tools.length - 1 });
|
|
1485
|
-
if (id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: ai_i });
|
|
1486
|
-
effects.push({ type: "tool-updated", turnId: next.id, aiId: next.ai[ai_i].id, tool: orphan });
|
|
1487
|
-
};
|
|
1488
|
-
const appendAi = (msg, effects) => {
|
|
1489
|
-
const id = String(msg?.id || "").trim();
|
|
1490
|
-
if (state.openTurn === null) {
|
|
1491
|
-
appendHuman(
|
|
1492
|
-
{
|
|
1493
|
-
id: `${id || "ai"}-orphan`,
|
|
1494
|
-
type: "human",
|
|
1495
|
-
content: "",
|
|
1496
|
-
additional_kwargs: {}
|
|
1497
|
-
},
|
|
1498
|
-
false,
|
|
1499
|
-
effects
|
|
1500
|
-
);
|
|
1501
|
-
}
|
|
1502
|
-
const ti = state.openTurn;
|
|
1503
|
-
const runId = messageRunId(msg);
|
|
1504
|
-
const openSeg = state.openAi !== null ? state.turns[ti].ai[state.openAi] : null;
|
|
1505
|
-
if (openSeg && (!runId || !openSeg.runId || runId === openSeg.runId)) {
|
|
1506
|
-
const text = readMessageContentText(msg);
|
|
1507
|
-
const ai_i = state.openAi;
|
|
1508
|
-
const turn = state.turns[ti];
|
|
1509
|
-
const body = text || openSeg.body;
|
|
1510
|
-
const next = ctx.cloneWith(turn, ai_i, (t) => {
|
|
1511
|
-
t.ai[ai_i].body = body;
|
|
1512
|
-
t.ai[ai_i].streamingText = body;
|
|
1513
|
-
if (id && !t.ai[ai_i].messageIds?.includes(id)) {
|
|
1514
|
-
t.ai[ai_i].messageIds = [...t.ai[ai_i].messageIds ?? [], id];
|
|
1515
|
-
}
|
|
1516
|
-
if (!t.ai[ai_i].runId) t.ai[ai_i].runId = runId || ctx.streamRunId() || "";
|
|
1517
|
-
t.rawMessages = [...t.rawMessages ?? [], msg];
|
|
1518
|
-
});
|
|
1519
|
-
state.turns[ti] = next;
|
|
1520
|
-
if (id && id !== openSeg.id) ctx.indexes().byMessageId.set(id, { turn: ti, ai: ai_i });
|
|
1521
|
-
effects.push({ type: "ai-delta", turnId: next.id, aiId: openSeg.id, body, streamingText: body });
|
|
1522
|
-
registerToolCalls(ti, ai_i, msg, effects);
|
|
1523
|
-
return;
|
|
1524
|
-
}
|
|
1525
|
-
openNewAi(ti, msg, effects);
|
|
1526
|
-
};
|
|
1527
|
-
return { appendHuman, appendHiddenHuman, appendAi, applyToolMessage, registerToolCalls };
|
|
1528
|
-
}
|
|
1529
|
-
|
|
1530
|
-
// src/materializer/turn-machine.ts
|
|
1531
|
-
var DEFAULT_TWIN_TOOL_PREFIX = "city-digital-twin-display_";
|
|
1532
|
-
function createTurnMachine(options) {
|
|
1533
|
-
const state = { turns: [], openTurn: null, openAi: null, optimisticTurnId: null };
|
|
1534
|
-
let indexes = createIndexes();
|
|
1535
|
-
const twinEnabled = !!options?.twin?.enabled;
|
|
1536
|
-
const twinToolPrefix = options?.twin?.toolPrefix || DEFAULT_TWIN_TOOL_PREFIX;
|
|
1537
|
-
const streamRunId = () => String(options?.getStreamRunId?.() || "").trim();
|
|
1538
|
-
const assembleAttachments = (seg) => {
|
|
1539
|
-
const byKind = /* @__PURE__ */ new Map();
|
|
1540
|
-
for (const tool of seg.tools) {
|
|
1541
|
-
const ex = tool.extracted;
|
|
1542
|
-
if (ex?.kind === "report") {
|
|
1543
|
-
byKind.set(`report:${ex.reportKind}`, {
|
|
1544
|
-
kind: "report",
|
|
1545
|
-
reportKind: ex.reportKind,
|
|
1546
|
-
body: ex.body,
|
|
1547
|
-
outline: ex.outline,
|
|
1548
|
-
sourcePath: ex.sourcePath,
|
|
1549
|
-
title: ex.title
|
|
1550
|
-
});
|
|
1551
|
-
} else if (ex?.kind === "artifact") byKind.set("artifact", { kind: "artifact", files: ex.files });
|
|
1552
|
-
else if (twinEnabled && tool.name.includes(twinToolPrefix)) {
|
|
1553
|
-
byKind.set("twin", { kind: "twin", payload: tool.input });
|
|
1554
|
-
}
|
|
1555
|
-
}
|
|
1556
|
-
return [...byKind.values()];
|
|
1557
|
-
};
|
|
1558
|
-
const cloneWith = (turn, ai_i, mutate) => {
|
|
1559
|
-
const next = {
|
|
1560
|
-
...turn,
|
|
1561
|
-
human: { ...turn.human },
|
|
1562
|
-
clarifications: [...turn.clarifications],
|
|
1563
|
-
ai: turn.ai.map((seg, i) => i === ai_i ? { ...seg, tools: [...seg.tools] } : seg)
|
|
1564
|
-
};
|
|
1565
|
-
mutate(next);
|
|
1566
|
-
return next;
|
|
1567
|
-
};
|
|
1568
|
-
const archiveRaw = (t, msg) => {
|
|
1569
|
-
const id = String(msg?.id || "").trim();
|
|
1570
|
-
const raws = t.rawMessages ?? [];
|
|
1571
|
-
const ri = id ? raws.findIndex((r) => String(r?.id || "").trim() === id) : -1;
|
|
1572
|
-
t.rawMessages = ri >= 0 ? [...raws.slice(0, ri), msg, ...raws.slice(ri + 1)] : [...raws, msg];
|
|
1573
|
-
};
|
|
1574
|
-
const sealAiSegment = (turn, ai_i, effects) => {
|
|
1575
|
-
const seg = turn.ai[ai_i];
|
|
1576
|
-
if (seg.status === "sealed") return turn;
|
|
1577
|
-
const sealed = {
|
|
1578
|
-
...seg,
|
|
1579
|
-
status: "sealed",
|
|
1580
|
-
streamingText: void 0,
|
|
1581
|
-
segments: sliceBodySegments(seg.body),
|
|
1582
|
-
attachments: assembleAttachments(seg)
|
|
1583
|
-
};
|
|
1584
|
-
const next = cloneWith(turn, ai_i, (t) => {
|
|
1585
|
-
t.ai[ai_i] = sealed;
|
|
1586
|
-
});
|
|
1587
|
-
effects.push({ type: "ai-sealed", turnId: next.id, aiId: sealed.id, segments: sealed.segments });
|
|
1588
|
-
return next;
|
|
1589
|
-
};
|
|
1590
|
-
const sealOpenTurn = (effects) => {
|
|
1591
|
-
const ti = state.openTurn;
|
|
1592
|
-
if (ti === null) return;
|
|
1593
|
-
let turn = state.turns[ti];
|
|
1594
|
-
if (state.openAi !== null) {
|
|
1595
|
-
turn = sealAiSegment(turn, state.openAi, effects);
|
|
1596
|
-
state.openAi = null;
|
|
1597
|
-
}
|
|
1598
|
-
if (turn.status !== "sealed") {
|
|
1599
|
-
const sealed = { ...turn, status: "sealed" };
|
|
1600
|
-
state.turns[ti] = sealed;
|
|
1601
|
-
effects.push({ type: "turn-sealed", turnId: sealed.id });
|
|
1602
|
-
}
|
|
1603
|
-
state.openTurn = null;
|
|
1604
|
-
if (state.optimisticTurnId === turn.id) state.optimisticTurnId = null;
|
|
1605
|
-
};
|
|
1606
|
-
const rules = createTurnRules({
|
|
1607
|
-
state,
|
|
1608
|
-
indexes: () => indexes,
|
|
1609
|
-
cloneWith,
|
|
1610
|
-
sealOpenTurn,
|
|
1611
|
-
sealAiSegment,
|
|
1612
|
-
assembleAttachments,
|
|
1613
|
-
streamRunId
|
|
1614
|
-
});
|
|
1615
|
-
const applyTailRemove = (id, effects) => {
|
|
1616
|
-
const ti = state.openTurn;
|
|
1617
|
-
if (state.optimisticTurnId && ti !== null && state.turns[ti]?.human.id === id) {
|
|
1618
|
-
state.turns.pop();
|
|
1619
|
-
state.openTurn = null;
|
|
1620
|
-
state.openAi = null;
|
|
1621
|
-
state.optimisticTurnId = null;
|
|
1622
|
-
indexes = rebuildIndexes(state.turns);
|
|
1623
|
-
effects.push({ type: "placeholder-dropped", turnId: id });
|
|
1624
|
-
return;
|
|
1625
|
-
}
|
|
1626
|
-
};
|
|
1627
|
-
const applyAppend = (msg, allowOptimistic, effects) => {
|
|
1628
|
-
if (isHiddenHuman(msg)) return rules.appendHiddenHuman(msg, effects);
|
|
1629
|
-
if (isHumanMessage(msg)) return rules.appendHuman(msg, allowOptimistic, effects);
|
|
1630
|
-
if (isAiMessage(msg)) return rules.appendAi(msg, effects);
|
|
1631
|
-
if (isToolMessage(msg)) return rules.applyToolMessage(msg, effects);
|
|
1632
|
-
};
|
|
1633
|
-
const applyUpdate = (id, msg, effects) => {
|
|
1634
|
-
const loc = indexes.byMessageId.get(id);
|
|
1635
|
-
if (!loc) return;
|
|
1636
|
-
if (loc.ai === null) {
|
|
1637
|
-
if (isHiddenHuman(msg)) return rules.appendHiddenHuman(msg, effects);
|
|
1638
|
-
if (!isHumanMessage(msg)) return;
|
|
1639
|
-
const turn2 = state.turns[loc.turn];
|
|
1640
|
-
const wasOptimistic = state.optimisticTurnId === turn2.id;
|
|
1641
|
-
const mergedKwargs = resolveHumanKwargsMerge(
|
|
1642
|
-
turn2.human.kwargs,
|
|
1643
|
-
msg?.additional_kwargs,
|
|
1644
|
-
(getHumanMessageBaseId(id) || id) !== id
|
|
1645
|
-
);
|
|
1646
|
-
const next2 = cloneWith(turn2, null, (t) => {
|
|
1647
|
-
t.human = { id, text: extractTextFromMessage(msg), kwargs: mergedKwargs };
|
|
1648
|
-
t.optimistic = false;
|
|
1649
|
-
archiveRaw(t, msg);
|
|
1650
|
-
});
|
|
1651
|
-
state.turns[loc.turn] = next2;
|
|
1652
|
-
if (wasOptimistic) {
|
|
1653
|
-
state.optimisticTurnId = null;
|
|
1654
|
-
effects.push({ type: "placeholder-absorbed", turnId: next2.id });
|
|
1655
|
-
} else {
|
|
1656
|
-
effects.push({ type: "message-updated", turnId: next2.id, aiId: null });
|
|
1657
|
-
}
|
|
1658
|
-
return;
|
|
1659
|
-
}
|
|
1660
|
-
if (isToolMessage(msg)) {
|
|
1661
|
-
rules.applyToolMessage(msg, effects);
|
|
1662
|
-
return;
|
|
1663
|
-
}
|
|
1664
|
-
const turn = state.turns[loc.turn];
|
|
1665
|
-
const seg = turn.ai[loc.ai];
|
|
1666
|
-
const text = readMessageContentText(msg);
|
|
1667
|
-
const body = text || seg.body;
|
|
1668
|
-
const bodyChanged = body !== seg.body;
|
|
1669
|
-
const next = cloneWith(turn, loc.ai, (t) => {
|
|
1670
|
-
const target = t.ai[loc.ai];
|
|
1671
|
-
target.body = body;
|
|
1672
|
-
if (target.status === "streaming") target.streamingText = body;
|
|
1673
|
-
if (target.status === "sealed" && bodyChanged) target.segments = sliceBodySegments(body);
|
|
1674
|
-
if (!target.runId) {
|
|
1675
|
-
const rid = messageRunId(msg) || streamRunId();
|
|
1676
|
-
if (rid) target.runId = rid;
|
|
1677
|
-
}
|
|
1678
|
-
archiveRaw(t, msg);
|
|
1679
|
-
});
|
|
1680
|
-
state.turns[loc.turn] = next;
|
|
1681
|
-
if (id !== seg.id && isAiMessage(msg)) {
|
|
1682
|
-
indexes.byMessageId.set(id, { turn: loc.turn, ai: loc.ai });
|
|
1683
|
-
const nextSeg = state.turns[loc.turn].ai[loc.ai];
|
|
1684
|
-
if (!nextSeg.messageIds?.includes(id)) nextSeg.messageIds = [...nextSeg.messageIds ?? [], id];
|
|
1685
|
-
}
|
|
1686
|
-
effects.push({ type: "ai-delta", turnId: next.id, aiId: seg.id, body, streamingText: body });
|
|
1687
|
-
rules.registerToolCalls(loc.turn, loc.ai, msg, effects);
|
|
1688
|
-
};
|
|
1689
|
-
const finalizeInto = (effects) => {
|
|
1690
|
-
sealOpenTurn(effects);
|
|
1691
|
-
indexes = rebuildIndexes(state.turns);
|
|
1692
|
-
};
|
|
1693
|
-
function resetMachine() {
|
|
1694
|
-
state.turns = [];
|
|
1695
|
-
state.openTurn = null;
|
|
1696
|
-
state.openAi = null;
|
|
1697
|
-
state.optimisticTurnId = null;
|
|
1698
|
-
indexes = createIndexes();
|
|
1699
|
-
}
|
|
1700
|
-
return {
|
|
1701
|
-
applyDeltas(deltas) {
|
|
1702
|
-
const effects = [];
|
|
1703
|
-
for (const d of deltas) {
|
|
1704
|
-
if (d.type === "append") applyAppend(d.message, true, effects);
|
|
1705
|
-
else if (d.type === "update") applyUpdate(d.id, d.message, effects);
|
|
1706
|
-
else applyTailRemove(d.id, effects);
|
|
1707
|
-
}
|
|
1708
|
-
return effects;
|
|
1709
|
-
},
|
|
1710
|
-
seed(messages) {
|
|
1711
|
-
if (state.openTurn !== null || state.openAi !== null) {
|
|
1712
|
-
throw new Error("[materializer] \u6D41\u8FDB\u884C\u4E2D\u7981\u6B62 seed\uFF08\u5148 finalize \u5BC6\u5C01\u540E\u518D\u5168\u91CF\u91CD\u5EFA\uFF09");
|
|
1713
|
-
}
|
|
1714
|
-
resetMachine();
|
|
1715
|
-
const effects = [];
|
|
1716
|
-
for (const msg of messages) applyAppend(msg, false, effects);
|
|
1717
|
-
finalizeInto(effects);
|
|
1718
|
-
return effects;
|
|
1719
|
-
},
|
|
1720
|
-
finalize() {
|
|
1721
|
-
const effects = [];
|
|
1722
|
-
finalizeInto(effects);
|
|
1723
|
-
return effects;
|
|
1724
|
-
},
|
|
1725
|
-
decorate(id, patch) {
|
|
1726
|
-
const effects = [];
|
|
1727
|
-
const loc = indexes.byMessageId.get(id);
|
|
1728
|
-
if (!loc || loc.ai === null) return effects;
|
|
1729
|
-
const turn = state.turns[loc.turn];
|
|
1730
|
-
const next = cloneWith(turn, loc.ai, (t) => {
|
|
1731
|
-
Object.assign(t.ai[loc.ai], patch);
|
|
1732
|
-
});
|
|
1733
|
-
state.turns[loc.turn] = next;
|
|
1734
|
-
effects.push({ type: "message-updated", turnId: next.id, aiId: next.ai[loc.ai].id });
|
|
1735
|
-
return effects;
|
|
1736
|
-
},
|
|
1737
|
-
reset: resetMachine,
|
|
1738
|
-
get state() {
|
|
1739
|
-
return state;
|
|
1740
|
-
},
|
|
1741
|
-
get indexes() {
|
|
1742
|
-
return indexes;
|
|
1743
|
-
}
|
|
1744
|
-
};
|
|
1745
|
-
}
|
|
1746
|
-
|
|
1747
|
-
// src/materializer/materializer.ts
|
|
1748
|
-
function createMaterializer(options) {
|
|
1749
|
-
const view = shallowRef({ turns: [] });
|
|
1750
|
-
const machine = createTurnMachine(options);
|
|
1751
|
-
const messageDiff = createMessageDiff();
|
|
1752
|
-
const publishIfChanged = (effects) => {
|
|
1753
|
-
if (!effects.length) return;
|
|
1754
|
-
view.value = { turns: [...machine.state.turns] };
|
|
1755
|
-
};
|
|
1756
|
-
return {
|
|
1757
|
-
view,
|
|
1758
|
-
hydrate(seed) {
|
|
1759
|
-
messageDiff.reset();
|
|
1760
|
-
messageDiff.apply(seed);
|
|
1761
|
-
const effects = machine.seed(seed);
|
|
1762
|
-
publishIfChanged(effects);
|
|
1763
|
-
},
|
|
1764
|
-
applySnapshot(messages) {
|
|
1765
|
-
const deltas = messageDiff.apply(messages);
|
|
1766
|
-
if (!deltas.length) return;
|
|
1767
|
-
const effects = machine.applyDeltas(deltas);
|
|
1768
|
-
publishIfChanged(effects);
|
|
1769
|
-
},
|
|
1770
|
-
finalize() {
|
|
1771
|
-
publishIfChanged(machine.finalize());
|
|
1772
|
-
},
|
|
1773
|
-
decorate(messageId, patch) {
|
|
1774
|
-
publishIfChanged(machine.decorate(messageId, patch));
|
|
1775
|
-
},
|
|
1776
|
-
reset() {
|
|
1777
|
-
messageDiff.reset();
|
|
1778
|
-
machine.reset();
|
|
1779
|
-
view.value = { turns: [] };
|
|
1780
|
-
}
|
|
1781
|
-
};
|
|
1782
|
-
}
|
|
1783
|
-
|
|
1784
|
-
// src/runtime/runtime-materializer.ts
|
|
1785
|
-
import { computed, shallowRef as shallowRef2 } from "vue";
|
|
1786
|
-
var localSeq = 0;
|
|
1787
|
-
function createRuntimeMaterializer(options) {
|
|
1788
|
-
const materializer = createMaterializer({ twin: options.twin, getStreamRunId: options.getStreamRunId });
|
|
1789
|
-
let lastMessages = [];
|
|
1790
|
-
const answersMap = shallowRef2(/* @__PURE__ */ new Map());
|
|
1791
|
-
const answers = computed(() => answersMap.value);
|
|
1792
|
-
const turns = computed(() => materializer.view.value.turns);
|
|
1793
|
-
const activeClarification = computed(() => {
|
|
1794
|
-
const ts = materializer.view.value.turns;
|
|
1795
|
-
const last = ts[ts.length - 1];
|
|
1796
|
-
if (!last) return void 0;
|
|
1797
|
-
for (let ci = last.clarifications.length - 1; ci >= 0; ci--) {
|
|
1798
|
-
const c = last.clarifications[ci];
|
|
1799
|
-
if (!c.answer && !answersMap.value.has(c.callId)) return c;
|
|
1800
|
-
}
|
|
1801
|
-
return void 0;
|
|
1802
|
-
});
|
|
1803
|
-
const feed = (messages) => {
|
|
1804
|
-
lastMessages = messages;
|
|
1805
|
-
materializer.applySnapshot(messages);
|
|
1806
|
-
};
|
|
1807
|
-
return {
|
|
1808
|
-
view: materializer.view,
|
|
1809
|
-
turns,
|
|
1810
|
-
activeClarification,
|
|
1811
|
-
answers,
|
|
1812
|
-
setClarificationAnswer(toolCallId, answer) {
|
|
1813
|
-
const next = new Map(answersMap.value);
|
|
1814
|
-
next.set(toolCallId, answer);
|
|
1815
|
-
answersMap.value = next;
|
|
1816
|
-
},
|
|
1817
|
-
clearClarificationAnswers() {
|
|
1818
|
-
if (!answersMap.value.size) return;
|
|
1819
|
-
answersMap.value = /* @__PURE__ */ new Map();
|
|
1820
|
-
},
|
|
1821
|
-
lastMessages: () => lastMessages,
|
|
1822
|
-
hydrate(seed) {
|
|
1823
|
-
lastMessages = seed;
|
|
1824
|
-
materializer.hydrate(seed);
|
|
1825
|
-
},
|
|
1826
|
-
applySnapshot(messages) {
|
|
1827
|
-
lastMessages = messages;
|
|
1828
|
-
materializer.applySnapshot(messages);
|
|
1829
|
-
},
|
|
1830
|
-
finalize() {
|
|
1831
|
-
materializer.finalize();
|
|
1832
|
-
},
|
|
1833
|
-
decorate(messageId, patch) {
|
|
1834
|
-
materializer.decorate(messageId, patch);
|
|
1835
|
-
},
|
|
1836
|
-
prependHistory(older) {
|
|
1837
|
-
const merged = [...older, ...lastMessages];
|
|
1838
|
-
try {
|
|
1839
|
-
materializer.hydrate(merged);
|
|
1840
|
-
} catch {
|
|
1841
|
-
return false;
|
|
1842
|
-
}
|
|
1843
|
-
lastMessages = merged;
|
|
1844
|
-
return true;
|
|
1845
|
-
},
|
|
1846
|
-
reconcileWithPage(pageMessages) {
|
|
1847
|
-
if (!pageMessages.length || !lastMessages.length) return;
|
|
1848
|
-
const byId = new Map(pageMessages.map((m) => [String(m?.id || ""), m]));
|
|
1849
|
-
feed(lastMessages.map((m) => byId.get(String(m?.id || "")) ?? m));
|
|
1850
|
-
},
|
|
1851
|
-
addOptimisticTurn(body) {
|
|
1852
|
-
localSeq += 1;
|
|
1853
|
-
const stamp = `${Date.now()}-${localSeq}`;
|
|
1854
|
-
const humanMsg = {
|
|
1855
|
-
id: `local-h-${stamp}`,
|
|
1856
|
-
type: "human",
|
|
1857
|
-
content: [{ type: "text", text: body }],
|
|
1858
|
-
additional_kwargs: {}
|
|
1859
|
-
};
|
|
1860
|
-
const aiMsg = {
|
|
1861
|
-
id: `local-a-${stamp}`,
|
|
1862
|
-
type: "ai",
|
|
1863
|
-
content: [{ type: "text", text: "" }],
|
|
1864
|
-
additional_kwargs: {}
|
|
1865
|
-
};
|
|
1866
|
-
feed([...lastMessages, humanMsg, aiMsg]);
|
|
1867
|
-
},
|
|
1868
|
-
updateAiBody(aiId, body) {
|
|
1869
|
-
const idx = lastMessages.findIndex((m) => String(m?.id || "") === aiId);
|
|
1870
|
-
if (idx < 0) return;
|
|
1871
|
-
const next = [...lastMessages];
|
|
1872
|
-
next[idx] = { ...next[idx], content: [{ type: "text", text: body }] };
|
|
1873
|
-
feed(next);
|
|
1874
|
-
},
|
|
1875
|
-
applySemanticPatch(patches) {
|
|
1876
|
-
if (!patches.size || !lastMessages.length) return;
|
|
1877
|
-
const next = applySemanticPatches(lastMessages, patches);
|
|
1878
|
-
const changed = next.some((m, i) => m !== lastMessages[i]);
|
|
1879
|
-
if (changed) feed(next);
|
|
1880
|
-
}
|
|
1881
|
-
};
|
|
1882
|
-
}
|
|
1883
|
-
|
|
1884
1626
|
// src/runtime/thread-runtime.ts
|
|
1885
|
-
import { computed as
|
|
1627
|
+
import { computed as computed2, effectScope, ref as ref2, shallowRef as shallowRef3 } from "vue";
|
|
1886
1628
|
|
|
1887
1629
|
// src/runtime/history-pager.ts
|
|
1888
|
-
import { computed
|
|
1630
|
+
import { computed, ref } from "vue";
|
|
1889
1631
|
function createHistoryPager(options) {
|
|
1890
1632
|
const { threadId, transport, firstPage } = options;
|
|
1891
1633
|
let cursor = firstPage.nextBeforeSeq;
|
|
@@ -1910,24 +1652,27 @@ function createHistoryPager(options) {
|
|
|
1910
1652
|
loading.value = false;
|
|
1911
1653
|
}
|
|
1912
1654
|
};
|
|
1913
|
-
return { loadOlder, hasMore:
|
|
1655
|
+
return { loadOlder, hasMore: computed(() => hasMoreRef.value), loading };
|
|
1914
1656
|
}
|
|
1915
1657
|
|
|
1916
1658
|
// src/runtime/runtime-bootstrap.ts
|
|
1659
|
+
function patchRows(rows, patches) {
|
|
1660
|
+
if (!patches.size || !rows.length) return rows;
|
|
1661
|
+
return rows.map((row) => {
|
|
1662
|
+
const id = String(row.content?.id || "").trim();
|
|
1663
|
+
const patch = id ? patches.get(id) : void 0;
|
|
1664
|
+
if (!patch) return row;
|
|
1665
|
+
const patched = applySemanticPatches([row.content], patches)[0];
|
|
1666
|
+
return patched === row.content ? row : { ...row, content: patched };
|
|
1667
|
+
});
|
|
1668
|
+
}
|
|
1917
1669
|
async function bootstrapRuntime(deps) {
|
|
1918
1670
|
const fetched = await deps.transport.fetchThreadInitialValues(deps.threadId);
|
|
1919
|
-
deps.
|
|
1920
|
-
deps.valuesChannel.applyThreadState(fetched.threadState);
|
|
1921
|
-
const semantic = deps.overlay.applyState(fetched.threadState);
|
|
1922
|
-
if (semantic.patched) {
|
|
1923
|
-
console.debug(`[runtime] \u8BED\u4E49\u5C42\u52A0\u8F7D patched=${semantic.patched} cited=${semantic.citedIds.length}`);
|
|
1924
|
-
}
|
|
1671
|
+
deps.overlay.applyState(fetched.threadState);
|
|
1925
1672
|
deps.runs.fillFromRunsList(fetched.runsList ?? []);
|
|
1926
1673
|
deps.runs.enrichFromPage(fetched.messagesPage);
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
if (seeded.length) deps.rm.hydrate(seeded);
|
|
1930
|
-
deps.rm.applySemanticPatch(deps.overlay.getPatches());
|
|
1674
|
+
deps.runsListMeta.value = (fetched.runsList ?? []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
|
|
1675
|
+
deps.rowsStore.setAll(patchRows(fetched.messagesPage.messages, deps.overlay.getPatches()));
|
|
1931
1676
|
deps.setPager(
|
|
1932
1677
|
createHistoryPager({
|
|
1933
1678
|
threadId: deps.threadId,
|
|
@@ -1935,7 +1680,7 @@ async function bootstrapRuntime(deps) {
|
|
|
1935
1680
|
firstPage: fetched.messagesPage,
|
|
1936
1681
|
onPageLoaded: (page) => {
|
|
1937
1682
|
deps.runs.enrichFromPage(page);
|
|
1938
|
-
deps.
|
|
1683
|
+
deps.rowsStore.prepend(page.messages);
|
|
1939
1684
|
},
|
|
1940
1685
|
emitChanges: () => {
|
|
1941
1686
|
}
|
|
@@ -1952,7 +1697,7 @@ async function bootstrapRuntime(deps) {
|
|
|
1952
1697
|
onValuesEvent: (data) => deps.valuesChannel.applyValuesEvent(data),
|
|
1953
1698
|
onMessageTupleEvent: () => {
|
|
1954
1699
|
},
|
|
1955
|
-
onSnapshotMessages: (messages) => deps.
|
|
1700
|
+
onSnapshotMessages: (messages) => deps.applyLiveSnapshot(messages),
|
|
1956
1701
|
onStreamStart: deps.onStreamStart,
|
|
1957
1702
|
onStreamEnd: finalize,
|
|
1958
1703
|
onFinish: afterFinish,
|
|
@@ -1961,22 +1706,32 @@ async function bootstrapRuntime(deps) {
|
|
|
1961
1706
|
deps.setInitialized();
|
|
1962
1707
|
}
|
|
1963
1708
|
function finalizeAfterStream(deps) {
|
|
1964
|
-
deps.rm.finalize();
|
|
1965
1709
|
deps.onStreamSettled();
|
|
1966
|
-
deps.runs.backfillCurrentRunMetadata(
|
|
1967
|
-
|
|
1710
|
+
deps.runs.backfillCurrentRunMetadata(
|
|
1711
|
+
() => deps.valuesChannel.getStreamMessages().map((m) => ({ ...m, runId: deps.runs.currentRunId.value }))
|
|
1712
|
+
);
|
|
1713
|
+
const patches = extractSemanticPatchesFromMessages(deps.valuesChannel.getStreamMessages());
|
|
1714
|
+
deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, patches));
|
|
1968
1715
|
}
|
|
1969
1716
|
async function afterStreamFinish(deps) {
|
|
1970
|
-
await Promise.all([deps.runs.refreshRuns(), deps.refreshTokenUsage()]);
|
|
1717
|
+
await Promise.all([deps.runs.refreshRuns(), refreshRunsMeta(deps), deps.refreshTokenUsage()]);
|
|
1971
1718
|
await reconcileWithPage(deps);
|
|
1972
1719
|
await refreshSemanticLayer(deps);
|
|
1973
1720
|
}
|
|
1721
|
+
async function refreshRunsMeta(deps) {
|
|
1722
|
+
try {
|
|
1723
|
+
const list = await deps.transport.listRuns(deps.threadId, 20);
|
|
1724
|
+
deps.runsListMeta.value = (Array.isArray(list) ? list : []).map((run) => buildRunMeta(run)).filter((m) => m !== null);
|
|
1725
|
+
} catch (e) {
|
|
1726
|
+
console.warn("[runtime] runs.list \u5237\u65B0\u5931\u8D25", e);
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1974
1729
|
async function refreshSemanticLayer(deps) {
|
|
1975
1730
|
try {
|
|
1976
1731
|
const state = await deps.transport.fetchThreadState(deps.threadId);
|
|
1977
1732
|
if (!state) return;
|
|
1978
1733
|
const semantic = deps.overlay.applyState(state);
|
|
1979
|
-
deps.
|
|
1734
|
+
deps.rowsStore.mergeLatest(patchRows(deps.rowsStore.rows.value, deps.overlay.getPatches()));
|
|
1980
1735
|
if (semantic.patched) {
|
|
1981
1736
|
console.debug(`[runtime] \u8BED\u4E49\u5C42\u5237\u65B0 patched=${semantic.patched} cited=${semantic.citedIds.length}`);
|
|
1982
1737
|
}
|
|
@@ -1987,8 +1742,7 @@ async function refreshSemanticLayer(deps) {
|
|
|
1987
1742
|
async function reconcileWithPage(deps) {
|
|
1988
1743
|
try {
|
|
1989
1744
|
const page = await deps.transport.fetchMessagesPage(deps.threadId);
|
|
1990
|
-
|
|
1991
|
-
if (messages.length) deps.rm.reconcileWithPage(messages);
|
|
1745
|
+
if (page.messages.length) deps.rowsStore.mergeLatest(page.messages);
|
|
1992
1746
|
} catch (e) {
|
|
1993
1747
|
console.warn("[runtime] \u5BF9\u8D26\u5931\u8D25\uFF0C\u4FDD\u7559\u6D41\u5F0F\u7D2F\u79EF\u73B0\u72B6", e);
|
|
1994
1748
|
}
|
|
@@ -2009,6 +1763,8 @@ function createStreamActions(ctx) {
|
|
|
2009
1763
|
const handle = ctx.getHandle();
|
|
2010
1764
|
if (!handle) return;
|
|
2011
1765
|
ctx.beginStream();
|
|
1766
|
+
const kwargs = submitOptions?.kwargs ?? void 0;
|
|
1767
|
+
ctx.createPendingRun(text, "message", kwargs);
|
|
2012
1768
|
const humanMessage = { type: "human", content: [{ type: "text", text }] };
|
|
2013
1769
|
humanMessage.additional_kwargs = submitOptions?.kwargs;
|
|
2014
1770
|
handle.submit({ messages: [humanMessage] }, { onDisconnect: "continue", config: { recursion_limit: 1e3 } });
|
|
@@ -2032,7 +1788,14 @@ function createStreamActions(ctx) {
|
|
|
2032
1788
|
if (!handle) throw new Error("\u4F1A\u8BDD\u5C1A\u672A\u521D\u59CB\u5316");
|
|
2033
1789
|
ctx.markResponded(interruptId);
|
|
2034
1790
|
ctx.beginStream();
|
|
2035
|
-
|
|
1791
|
+
const payload = parseHitlPayload(it.value);
|
|
1792
|
+
ctx.createPendingRun(payload ? "\u5DF2\u63D0\u4EA4\u5BA1\u6279\u51B3\u7B56" : "\u5DF2\u63D0\u4EA4\u56DE\u7B54", payload ? "hitl" : "clarification");
|
|
1793
|
+
try {
|
|
1794
|
+
await handle.resumeInterrupt(decisions);
|
|
1795
|
+
} catch (e) {
|
|
1796
|
+
ctx.unmarkResponded(interruptId);
|
|
1797
|
+
throw e;
|
|
1798
|
+
}
|
|
2036
1799
|
},
|
|
2037
1800
|
async loadOlderMessages() {
|
|
2038
1801
|
if (!ctx.getPager()) return false;
|
|
@@ -2041,98 +1804,77 @@ function createStreamActions(ctx) {
|
|
|
2041
1804
|
};
|
|
2042
1805
|
}
|
|
2043
1806
|
|
|
2044
|
-
// src/runtime/
|
|
2045
|
-
import { shallowRef
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
1807
|
+
// src/runtime/rows-store.ts
|
|
1808
|
+
import { shallowRef } from "vue";
|
|
1809
|
+
function createRowsStore() {
|
|
1810
|
+
const rows = shallowRef([]);
|
|
1811
|
+
const sortRows = (list) => [...list].sort((a, b) => a.seq - b.seq);
|
|
1812
|
+
return {
|
|
1813
|
+
rows,
|
|
1814
|
+
setAll(next) {
|
|
1815
|
+
rows.value = sortRows(next);
|
|
1816
|
+
},
|
|
1817
|
+
prepend(older) {
|
|
1818
|
+
if (!older.length) return;
|
|
1819
|
+
const seen = new Set(rows.value.map((r) => String(r.content?.id || "")));
|
|
1820
|
+
const fresh = older.filter((r) => {
|
|
1821
|
+
const id = String(r.content?.id || "");
|
|
1822
|
+
if (!id || seen.has(id)) return false;
|
|
1823
|
+
seen.add(id);
|
|
1824
|
+
return true;
|
|
1825
|
+
});
|
|
1826
|
+
if (!fresh.length) return;
|
|
1827
|
+
rows.value = sortRows([...fresh, ...rows.value]);
|
|
1828
|
+
},
|
|
1829
|
+
mergeLatest(latest) {
|
|
1830
|
+
if (!latest.length) return;
|
|
1831
|
+
const byId = new Map(rows.value.map((r) => [String(r.content?.id || ""), r]));
|
|
1832
|
+
for (const row of latest) {
|
|
1833
|
+
const id = String(row.content?.id || "");
|
|
1834
|
+
if (!id) continue;
|
|
1835
|
+
byId.set(id, row);
|
|
2068
1836
|
}
|
|
2069
|
-
|
|
2070
|
-
}
|
|
2071
|
-
return { ...base, __interrupt__: interrupts };
|
|
2072
|
-
}
|
|
2073
|
-
if (nextValues && typeof nextValues === "object") {
|
|
2074
|
-
if (base && "__interrupt__" in base && Array.isArray(base.__interrupt__)) {
|
|
2075
|
-
return { ...nextValues, __interrupt__: base.__interrupt__ };
|
|
1837
|
+
rows.value = sortRows([...byId.values()]);
|
|
2076
1838
|
}
|
|
2077
|
-
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
function extractLiveIncrement(snapshot, lastSeenIds) {
|
|
1842
|
+
const fresh = [];
|
|
1843
|
+
for (const msg of snapshot) {
|
|
1844
|
+
const id = String(msg?.id || "").trim();
|
|
1845
|
+
if (!id || lastSeenIds.has(id)) continue;
|
|
1846
|
+
lastSeenIds.add(id);
|
|
1847
|
+
fresh.push(msg);
|
|
2078
1848
|
}
|
|
2079
|
-
return
|
|
1849
|
+
return fresh;
|
|
2080
1850
|
}
|
|
2081
1851
|
|
|
2082
1852
|
// src/runtime/values-projection.ts
|
|
2083
1853
|
function createValuesChannel(options = {}) {
|
|
2084
|
-
const valuesRef = shallowRef3({});
|
|
2085
|
-
const threadStateRef = shallowRef3(void 0);
|
|
2086
|
-
let firstEvent = true;
|
|
2087
|
-
let lastTitle = "";
|
|
2088
1854
|
let latestStreamMessages = [];
|
|
2089
|
-
|
|
2090
|
-
const msgs = threadStateRef.value?.values?.messages;
|
|
2091
|
-
return Array.isArray(msgs) ? [...msgs] : [];
|
|
2092
|
-
};
|
|
2093
|
-
const readStreamMessages = () => [...latestStreamMessages];
|
|
1855
|
+
let lastTitle = "";
|
|
2094
1856
|
return {
|
|
2095
|
-
applyInitialValues(next) {
|
|
2096
|
-
valuesRef.value = { ...next ?? {} };
|
|
2097
|
-
},
|
|
2098
|
-
applyThreadState(state) {
|
|
2099
|
-
threadStateRef.value = state;
|
|
2100
|
-
},
|
|
2101
1857
|
beginStream() {
|
|
2102
|
-
firstEvent = true;
|
|
2103
|
-
threadStateRef.value = void 0;
|
|
2104
1858
|
latestStreamMessages = [];
|
|
2105
1859
|
},
|
|
2106
1860
|
applyValuesEvent(data) {
|
|
2107
|
-
const reconciled = reconcileInterrupts(valuesRef.value, data, firstEvent);
|
|
2108
|
-
firstEvent = false;
|
|
2109
|
-
valuesRef.value = reconciled;
|
|
2110
1861
|
if (Array.isArray(data?.messages)) latestStreamMessages = [...data.messages];
|
|
2111
|
-
const title = String(
|
|
1862
|
+
const title = String(data?.title || "").trim();
|
|
2112
1863
|
if (title && title !== lastTitle) {
|
|
2113
1864
|
lastTitle = title;
|
|
2114
1865
|
options.onTitle?.(title);
|
|
2115
1866
|
}
|
|
2116
1867
|
},
|
|
2117
|
-
|
|
2118
|
-
return
|
|
2119
|
-
},
|
|
2120
|
-
getStateMessages: readStateMessages,
|
|
2121
|
-
getStreamMessages: readStreamMessages,
|
|
2122
|
-
getInterrupt({ isLoading, error }) {
|
|
2123
|
-
return extractInterrupts(valuesRef.value, {
|
|
2124
|
-
isLoading,
|
|
2125
|
-
threadState: threadStateRef.value,
|
|
2126
|
-
error
|
|
2127
|
-
});
|
|
1868
|
+
getStreamMessages() {
|
|
1869
|
+
return [...latestStreamMessages];
|
|
2128
1870
|
}
|
|
2129
1871
|
};
|
|
2130
1872
|
}
|
|
2131
1873
|
|
|
2132
1874
|
// src/store/runs-store.ts
|
|
2133
|
-
import { shallowRef as
|
|
1875
|
+
import { shallowRef as shallowRef2 } from "vue";
|
|
2134
1876
|
function createInterruptState() {
|
|
2135
|
-
const respondedIds =
|
|
1877
|
+
const respondedIds = shallowRef2(/* @__PURE__ */ new Set());
|
|
2136
1878
|
return {
|
|
2137
1879
|
respondedIds,
|
|
2138
1880
|
markResponded(id) {
|
|
@@ -2149,8 +1891,8 @@ function createInterruptState() {
|
|
|
2149
1891
|
};
|
|
2150
1892
|
}
|
|
2151
1893
|
function createRunsStore(options) {
|
|
2152
|
-
const runsMap =
|
|
2153
|
-
const currentRunId =
|
|
1894
|
+
const runsMap = shallowRef2(/* @__PURE__ */ new Map());
|
|
1895
|
+
const currentRunId = shallowRef2(null);
|
|
2154
1896
|
return {
|
|
2155
1897
|
runsMap,
|
|
2156
1898
|
currentRunId,
|
|
@@ -2242,50 +1984,96 @@ function createRunsStore(options) {
|
|
|
2242
1984
|
}
|
|
2243
1985
|
|
|
2244
1986
|
// src/runtime/thread-runtime.ts
|
|
1987
|
+
var pendingSeq = 0;
|
|
1988
|
+
function newPendingRunId() {
|
|
1989
|
+
pendingSeq += 1;
|
|
1990
|
+
return `local-${Date.now()}-${pendingSeq}`;
|
|
1991
|
+
}
|
|
2245
1992
|
function createThreadRuntime(options) {
|
|
2246
1993
|
const scope = effectScope();
|
|
2247
1994
|
const runs = createRunsStore({ threadId: options.threadId, transport: options.transport });
|
|
2248
1995
|
const interruptState = createInterruptState();
|
|
2249
|
-
const
|
|
2250
|
-
|
|
2251
|
-
// 段级 runId 兜底源(metadata 首帧权威值):流式 tuple 消息本体无 runId,
|
|
2252
|
-
// 段打开/回填时经此兜底——点赞/反馈按 runId 提交的依赖
|
|
2253
|
-
getStreamRunId: () => runs.currentRunId.value
|
|
2254
|
-
});
|
|
1996
|
+
const rowsStore = createRowsStore();
|
|
1997
|
+
const overlay = createSemanticOverlay();
|
|
2255
1998
|
const valuesChannel = createValuesChannel({
|
|
2256
1999
|
onTitle: (title) => options.onTitle?.(options.threadId, title)
|
|
2257
2000
|
});
|
|
2258
|
-
const
|
|
2259
|
-
const streamRef = shallowRef5(null);
|
|
2001
|
+
const streamRef = shallowRef3(null);
|
|
2260
2002
|
const isInitializing = ref2(false);
|
|
2261
2003
|
const streaming = ref2(false);
|
|
2262
|
-
const tokenUsage =
|
|
2004
|
+
const tokenUsage = shallowRef3(null);
|
|
2263
2005
|
let initialized = false;
|
|
2264
2006
|
let initPromise = null;
|
|
2265
2007
|
let pager = null;
|
|
2266
|
-
const
|
|
2267
|
-
const
|
|
2008
|
+
const runsListMeta = shallowRef3([]);
|
|
2009
|
+
const liveMessages = shallowRef3([]);
|
|
2010
|
+
const lastSeenLiveIds = /* @__PURE__ */ new Set();
|
|
2011
|
+
const pendingRun = shallowRef3(null);
|
|
2012
|
+
const answers = shallowRef3(/* @__PURE__ */ new Map());
|
|
2013
|
+
const activeRunId = computed2(() => runs.currentRunId.value);
|
|
2014
|
+
const runsProjection = computed2(
|
|
2015
|
+
() => projectRuns({
|
|
2016
|
+
rows: rowsStore.rows.value,
|
|
2017
|
+
liveMessages: liveMessages.value,
|
|
2018
|
+
activeRunId: activeRunId.value,
|
|
2019
|
+
runsList: runsListMeta.value,
|
|
2020
|
+
pendingRun: pendingRun.value,
|
|
2021
|
+
answers: answers.value,
|
|
2022
|
+
twin: options.twin,
|
|
2023
|
+
streaming: streaming.value
|
|
2024
|
+
})
|
|
2025
|
+
);
|
|
2026
|
+
const interrupt = computed2(() => streamRef.value?.interrupt.value);
|
|
2027
|
+
const hasPendingInterrupt = computed2(() => {
|
|
2268
2028
|
const it = interrupt.value;
|
|
2269
2029
|
return !!it?.id && !interruptState.respondedIds.value.has(String(it.id));
|
|
2270
2030
|
});
|
|
2271
|
-
const streamError =
|
|
2272
|
-
const isGenerating =
|
|
2031
|
+
const streamError = computed2(() => streamRef.value?.error.value ?? null);
|
|
2032
|
+
const isGenerating = computed2(() => streaming.value);
|
|
2033
|
+
const activeClarification = computed2(() => {
|
|
2034
|
+
const list = runsProjection.value;
|
|
2035
|
+
for (let i = list.length - 1; i >= 0; i--) {
|
|
2036
|
+
const clarifications = list[i].clarifications;
|
|
2037
|
+
for (let c = clarifications.length - 1; c >= 0; c--) {
|
|
2038
|
+
if (clarifications[c].answer === void 0) return clarifications[c];
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
return void 0;
|
|
2042
|
+
});
|
|
2043
|
+
const clarificationAnswers = computed2(() => answers.value);
|
|
2273
2044
|
const beginStream = () => {
|
|
2274
2045
|
valuesChannel.beginStream();
|
|
2275
2046
|
overlay.invalidate();
|
|
2276
2047
|
runs.currentRunId.value = null;
|
|
2048
|
+
liveMessages.value = [];
|
|
2049
|
+
lastSeenLiveIds.clear();
|
|
2277
2050
|
};
|
|
2278
2051
|
const streamStarted = () => {
|
|
2279
2052
|
streaming.value = true;
|
|
2280
2053
|
};
|
|
2281
2054
|
const streamSettled = () => {
|
|
2282
2055
|
streaming.value = false;
|
|
2056
|
+
pendingRun.value = null;
|
|
2283
2057
|
};
|
|
2284
2058
|
const markStreamRun = (runIdRaw) => {
|
|
2285
2059
|
const runId = String(runIdRaw || "").trim();
|
|
2286
2060
|
if (!runId) return;
|
|
2287
2061
|
runs.currentRunId.value = runId;
|
|
2288
2062
|
runs.ensureRunning(runId);
|
|
2063
|
+
const pending = pendingRun.value;
|
|
2064
|
+
if (pending && pending.runId !== runId) {
|
|
2065
|
+
pendingRun.value = { ...pending, runId };
|
|
2066
|
+
}
|
|
2067
|
+
};
|
|
2068
|
+
const applyLiveSnapshot = (messages) => {
|
|
2069
|
+
if (!streaming.value) return;
|
|
2070
|
+
const fresh = extractLiveIncrement(messages, lastSeenLiveIds);
|
|
2071
|
+
const eligible = fresh.filter((m) => {
|
|
2072
|
+
const t = String(m?.type || "");
|
|
2073
|
+
return t === "ai" || t === "tool";
|
|
2074
|
+
});
|
|
2075
|
+
if (!eligible.length) return;
|
|
2076
|
+
liveMessages.value = [...liveMessages.value, ...eligible];
|
|
2289
2077
|
};
|
|
2290
2078
|
const refreshTokenUsage = async () => {
|
|
2291
2079
|
try {
|
|
@@ -2300,13 +2088,15 @@ function createThreadRuntime(options) {
|
|
|
2300
2088
|
assistantId: options.assistantId,
|
|
2301
2089
|
transport: options.transport,
|
|
2302
2090
|
runs,
|
|
2303
|
-
|
|
2091
|
+
rowsStore,
|
|
2092
|
+
runsListMeta,
|
|
2304
2093
|
overlay,
|
|
2305
|
-
|
|
2094
|
+
valuesChannel,
|
|
2306
2095
|
streamRef,
|
|
2307
2096
|
setPager: (p) => pager = p,
|
|
2308
2097
|
setInitialized: () => initialized = true,
|
|
2309
2098
|
markStreamRun,
|
|
2099
|
+
applyLiveSnapshot,
|
|
2310
2100
|
onStreamStart: streamStarted,
|
|
2311
2101
|
onStreamSettled: streamSettled,
|
|
2312
2102
|
refreshTokenUsage
|
|
@@ -2321,10 +2111,16 @@ function createThreadRuntime(options) {
|
|
|
2321
2111
|
getHandle: () => streamRef.value,
|
|
2322
2112
|
beginStream,
|
|
2323
2113
|
markStreamRun,
|
|
2324
|
-
getInterrupt: () =>
|
|
2114
|
+
getInterrupt: () => streamRef.value?.interrupt.value,
|
|
2325
2115
|
markResponded: (id) => interruptState.markResponded(id),
|
|
2116
|
+
unmarkResponded: (id) => interruptState.unmarkResponded(id),
|
|
2326
2117
|
getPager: () => pager,
|
|
2327
|
-
runs
|
|
2118
|
+
runs,
|
|
2119
|
+
createPendingRun: (text, kind, kwargs) => {
|
|
2120
|
+
const pending = { runId: newPendingRunId(), text, kind, kwargs };
|
|
2121
|
+
pendingRun.value = pending;
|
|
2122
|
+
return pending.runId;
|
|
2123
|
+
}
|
|
2328
2124
|
});
|
|
2329
2125
|
return {
|
|
2330
2126
|
threadId: options.threadId,
|
|
@@ -2332,18 +2128,17 @@ function createThreadRuntime(options) {
|
|
|
2332
2128
|
touch() {
|
|
2333
2129
|
this.lastViewedAt = Date.now();
|
|
2334
2130
|
},
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
activeClarification
|
|
2131
|
+
runs: runsProjection,
|
|
2132
|
+
runsInfo: computed2(() => runs.runsMap.value),
|
|
2133
|
+
activeClarification,
|
|
2338
2134
|
isGenerating,
|
|
2339
2135
|
isInitializing,
|
|
2340
|
-
runs: computed3(() => runs.runsMap.value),
|
|
2341
2136
|
interrupt,
|
|
2342
2137
|
hasPendingInterrupt,
|
|
2343
2138
|
streamError,
|
|
2344
2139
|
tokenUsage,
|
|
2345
|
-
hasMoreHistory:
|
|
2346
|
-
loadingHistory:
|
|
2140
|
+
hasMoreHistory: computed2(() => pager?.hasMore.value ?? false),
|
|
2141
|
+
loadingHistory: computed2(() => pager?.loading.value ?? false),
|
|
2347
2142
|
async init() {
|
|
2348
2143
|
if (initialized) return;
|
|
2349
2144
|
if (initPromise) return initPromise;
|
|
@@ -2360,17 +2155,43 @@ function createThreadRuntime(options) {
|
|
|
2360
2155
|
resumeInterrupt: actions.resumeInterrupt,
|
|
2361
2156
|
loadOlderMessages: actions.loadOlderMessages,
|
|
2362
2157
|
applyFeedback(messageId, feedback) {
|
|
2363
|
-
|
|
2364
|
-
|
|
2158
|
+
rowsStore.mergeLatest(
|
|
2159
|
+
rowsStore.rows.value.map((row) => {
|
|
2160
|
+
const id = String(row.content?.id || "");
|
|
2161
|
+
return id === messageId ? { ...row, feedback } : row;
|
|
2162
|
+
})
|
|
2163
|
+
);
|
|
2164
|
+
const runId = runsProjection.value.find((r) => r.rawMessages.some((m) => m.id === messageId))?.runId;
|
|
2365
2165
|
if (runId) runs.patchRun(runId, { feedback });
|
|
2366
2166
|
},
|
|
2367
|
-
addOptimisticTurn:
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2167
|
+
addOptimisticTurn: (body) => {
|
|
2168
|
+
const runId = newPendingRunId();
|
|
2169
|
+
pendingRun.value = { runId, text: body, kind: "message" };
|
|
2170
|
+
},
|
|
2171
|
+
updateAiBody(aiId, body) {
|
|
2172
|
+
rowsStore.mergeLatest(
|
|
2173
|
+
rowsStore.rows.value.map((row) => {
|
|
2174
|
+
const id = String(row.content?.id || "");
|
|
2175
|
+
return id === aiId ? { ...row, content: { ...row.content, content: body } } : row;
|
|
2176
|
+
})
|
|
2177
|
+
);
|
|
2178
|
+
},
|
|
2179
|
+
decorate(messageId, patch) {
|
|
2180
|
+
if (patch.feedback) this.applyFeedback(messageId, patch.feedback);
|
|
2181
|
+
},
|
|
2182
|
+
finalizeTurns() {
|
|
2183
|
+
pendingRun.value = null;
|
|
2184
|
+
},
|
|
2185
|
+
setClarificationAnswer(toolCallId, answer) {
|
|
2186
|
+
const next = new Map(answers.value);
|
|
2187
|
+
next.set(toolCallId, answer);
|
|
2188
|
+
answers.value = next;
|
|
2189
|
+
},
|
|
2190
|
+
clearClarificationAnswers() {
|
|
2191
|
+
if (!answers.value.size) return;
|
|
2192
|
+
answers.value = /* @__PURE__ */ new Map();
|
|
2193
|
+
},
|
|
2194
|
+
clarificationAnswers,
|
|
2374
2195
|
dispose() {
|
|
2375
2196
|
streamRef.value?.stop();
|
|
2376
2197
|
streamRef.value?.dispose?.();
|
|
@@ -2585,7 +2406,7 @@ var ThreadDirectory = class {
|
|
|
2585
2406
|
};
|
|
2586
2407
|
|
|
2587
2408
|
// src/core/ChatCore.ts
|
|
2588
|
-
import { computed as
|
|
2409
|
+
import { computed as computed3, ref as ref4 } from "vue";
|
|
2589
2410
|
function createChatCore(options) {
|
|
2590
2411
|
const notify = options.notify ?? ((type, text) => console.warn(`[chat:${type}] ${text}`));
|
|
2591
2412
|
const directory = new ThreadDirectory({
|
|
@@ -2598,49 +2419,45 @@ function createChatCore(options) {
|
|
|
2598
2419
|
defaultThreadTitle: options.defaultThreadTitle
|
|
2599
2420
|
});
|
|
2600
2421
|
const currentThreadId = ref4(null);
|
|
2601
|
-
const threads =
|
|
2602
|
-
const threadsPagination =
|
|
2603
|
-
const activeRuntime =
|
|
2422
|
+
const threads = computed3(() => directory.threads.value);
|
|
2423
|
+
const threadsPagination = computed3(() => directory.threadsPagination.value);
|
|
2424
|
+
const activeRuntime = computed3(
|
|
2604
2425
|
() => currentThreadId.value ? directory.getRuntime(currentThreadId.value) : void 0
|
|
2605
2426
|
);
|
|
2606
|
-
const
|
|
2607
|
-
const
|
|
2608
|
-
const
|
|
2609
|
-
() =>
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
);
|
|
2618
|
-
const toolCalls = computed4(
|
|
2619
|
-
() => turns.value.flatMap(
|
|
2620
|
-
(t) => t.ai.flatMap(
|
|
2621
|
-
(seg) => seg.tools.map((tool, index) => ({
|
|
2622
|
-
id: tool.callId,
|
|
2623
|
-
call: { id: tool.callId, name: tool.name, args: tool.input },
|
|
2624
|
-
result: tool.result ? { content: tool.result } : void 0,
|
|
2625
|
-
state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
|
|
2626
|
-
index
|
|
2627
|
-
}))
|
|
2628
|
-
)
|
|
2427
|
+
const runs = computed3(() => activeRuntime.value?.runs.value ?? []);
|
|
2428
|
+
const runsInfo = computed3(() => activeRuntime.value?.runsInfo.value ?? /* @__PURE__ */ new Map());
|
|
2429
|
+
const toolCalls = computed3(
|
|
2430
|
+
() => runs.value.flatMap(
|
|
2431
|
+
(run) => run.tools.map((tool, index) => ({
|
|
2432
|
+
id: tool.callId,
|
|
2433
|
+
call: { id: tool.callId, name: tool.name, args: tool.input },
|
|
2434
|
+
result: tool.result ? { content: tool.result } : void 0,
|
|
2435
|
+
state: tool.status === "finished" ? "completed" : tool.status === "error" ? "error" : "active",
|
|
2436
|
+
index
|
|
2437
|
+
}))
|
|
2629
2438
|
)
|
|
2630
2439
|
);
|
|
2631
|
-
const
|
|
2440
|
+
const activeClarification = computed3(() => activeRuntime.value?.activeClarification.value);
|
|
2441
|
+
const isGenerating = computed3(
|
|
2442
|
+
() => !!activeRuntime.value && activeRuntime.value.isGenerating.value
|
|
2443
|
+
);
|
|
2444
|
+
const isLoadingThread = computed3(() => activeRuntime.value?.isInitializing.value ?? false);
|
|
2445
|
+
const clarificationAnswers = computed3(
|
|
2632
2446
|
() => activeRuntime.value?.clarificationAnswers.value ?? /* @__PURE__ */ new Map()
|
|
2633
2447
|
);
|
|
2634
|
-
const activeInterrupt =
|
|
2635
|
-
const hasPendingInterrupt =
|
|
2636
|
-
const inputDisabled =
|
|
2637
|
-
const streamError =
|
|
2638
|
-
const hasMoreHistory =
|
|
2639
|
-
const loadingHistory =
|
|
2640
|
-
const tokenUsage =
|
|
2641
|
-
const runningNotConnectedThreadIds =
|
|
2642
|
-
const getRunById = (runId) =>
|
|
2643
|
-
|
|
2448
|
+
const activeInterrupt = computed3(() => activeRuntime.value?.interrupt.value);
|
|
2449
|
+
const hasPendingInterrupt = computed3(() => activeRuntime.value?.hasPendingInterrupt.value ?? false);
|
|
2450
|
+
const inputDisabled = computed3(() => isGenerating.value || hasPendingInterrupt.value);
|
|
2451
|
+
const streamError = computed3(() => activeRuntime.value?.streamError.value ?? null);
|
|
2452
|
+
const hasMoreHistory = computed3(() => activeRuntime.value?.hasMoreHistory.value ?? false);
|
|
2453
|
+
const loadingHistory = computed3(() => activeRuntime.value?.loadingHistory.value ?? false);
|
|
2454
|
+
const tokenUsage = computed3(() => activeRuntime.value?.tokenUsage.value ?? null);
|
|
2455
|
+
const runningNotConnectedThreadIds = computed3(() => directory.runningNotConnectedThreadIds.value);
|
|
2456
|
+
const getRunById = (runId) => {
|
|
2457
|
+
const info = runId ? runsInfo.value.get(runId) : void 0;
|
|
2458
|
+
return info;
|
|
2459
|
+
};
|
|
2460
|
+
const getRunsByThreadId = (threadId) => threadId ? Array.from(runsInfo.value.values()).filter((r) => r.threadId === threadId) : [];
|
|
2644
2461
|
const ensureThreadId = async () => {
|
|
2645
2462
|
if (currentThreadId.value) return { threadId: currentThreadId.value, isNew: false, thread: null };
|
|
2646
2463
|
const thread = await directory.createThread({ source: "chat" });
|
|
@@ -2689,25 +2506,25 @@ function createChatCore(options) {
|
|
|
2689
2506
|
result.touch();
|
|
2690
2507
|
await result.init();
|
|
2691
2508
|
};
|
|
2692
|
-
const regenerateTurn = async (
|
|
2509
|
+
const regenerateTurn = async (runId) => {
|
|
2693
2510
|
if (isGenerating.value) return;
|
|
2694
|
-
const
|
|
2695
|
-
const text =
|
|
2696
|
-
if (!
|
|
2511
|
+
const run = runs.value.find((r) => r.runId === runId);
|
|
2512
|
+
const text = run?.input.text ?? "";
|
|
2513
|
+
if (!run || !text.trim()) {
|
|
2697
2514
|
notify("warning", "\u672A\u627E\u5230\u53EF\u91CD\u65B0\u56DE\u7B54\u7684\u95EE\u9898");
|
|
2698
2515
|
return;
|
|
2699
2516
|
}
|
|
2700
|
-
await sendMessage(text, { kwargs: { ...
|
|
2517
|
+
await sendMessage(text, { kwargs: { ...run.input.kwargs ?? {}, hide_from_ui: false } });
|
|
2701
2518
|
};
|
|
2702
2519
|
return {
|
|
2703
|
-
|
|
2704
|
-
turns,
|
|
2520
|
+
runs,
|
|
2521
|
+
turns: runs,
|
|
2705
2522
|
isGenerating,
|
|
2706
2523
|
isLoadingThread,
|
|
2707
2524
|
currentThreadId,
|
|
2708
2525
|
threads,
|
|
2709
2526
|
threadsPagination,
|
|
2710
|
-
|
|
2527
|
+
runsInfo,
|
|
2711
2528
|
toolCalls,
|
|
2712
2529
|
getRunById,
|
|
2713
2530
|
getRunsByThreadId,
|
|
@@ -2762,9 +2579,6 @@ function createChatCore(options) {
|
|
|
2762
2579
|
}
|
|
2763
2580
|
|
|
2764
2581
|
export {
|
|
2765
|
-
__privateGet,
|
|
2766
|
-
__privateAdd,
|
|
2767
|
-
__privateSet,
|
|
2768
2582
|
DEFAULT_MAX_CACHED_SESSIONS,
|
|
2769
2583
|
DEFAULT_MAX_CONCURRENT_STREAMS,
|
|
2770
2584
|
DEFAULT_ASSISTANT_ID,
|
|
@@ -2774,6 +2588,15 @@ export {
|
|
|
2774
2588
|
collectVisibleText,
|
|
2775
2589
|
collectTextKeepSxin,
|
|
2776
2590
|
tokenizeSxin,
|
|
2591
|
+
genMessageId,
|
|
2592
|
+
genBlockId,
|
|
2593
|
+
parseHitlPayload,
|
|
2594
|
+
getAllowedDecisions,
|
|
2595
|
+
normalizeForCompare,
|
|
2596
|
+
isSameArgs,
|
|
2597
|
+
buildHitlDecisions,
|
|
2598
|
+
buildRejectDecisions,
|
|
2599
|
+
buildInterruptReviewBlock,
|
|
2777
2600
|
formatAnswerText,
|
|
2778
2601
|
extractThreadInfo,
|
|
2779
2602
|
buildHumanInputResponse,
|
|
@@ -2814,16 +2637,24 @@ export {
|
|
|
2814
2637
|
deriveToolsFromMessages,
|
|
2815
2638
|
normalizeUsage,
|
|
2816
2639
|
sliceBodySegments,
|
|
2640
|
+
rowMessageId,
|
|
2641
|
+
isUserEchoRow,
|
|
2642
|
+
groupRowsByRun,
|
|
2643
|
+
extractFromToolResult,
|
|
2644
|
+
asArgsObject,
|
|
2645
|
+
pickRicherArgs,
|
|
2646
|
+
emptyRunItem,
|
|
2647
|
+
assembleRun,
|
|
2648
|
+
extractInputFromRows,
|
|
2649
|
+
mapBackendStatus,
|
|
2650
|
+
projectRuns,
|
|
2817
2651
|
buildRunInfo,
|
|
2652
|
+
buildRunMeta,
|
|
2818
2653
|
buildRunDirectLatencyMs,
|
|
2819
2654
|
pickRunMessageMetadata,
|
|
2820
2655
|
extractSemanticPatchesFromMessages,
|
|
2821
2656
|
createSemanticOverlay,
|
|
2822
2657
|
applySemanticPatches,
|
|
2823
|
-
extractFromToolResult,
|
|
2824
|
-
createMessageDiff,
|
|
2825
|
-
createMaterializer,
|
|
2826
|
-
createRuntimeMaterializer,
|
|
2827
2658
|
createThreadRuntime,
|
|
2828
2659
|
ThreadDirectory,
|
|
2829
2660
|
createChatCore
|