conversation-session-context-window-cold-resume.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. import { DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  2. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  3. import { readdir, readFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { DatabaseSync } from "node:sqlite";
  6. import { restartIntoWorkspacePreservingProfile as restartWithFixture } from "#e2e/helpers/model-provider-restart-runtime";
  7. import {
  8. TID_V4_COMPOSER_INPUT,
  9. TID_V4_MODEL_CONFIG,
  10. TID_V4_SESSION_PANE,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import {
  14. clearAppData,
  15. getE2EAppDataPaths,
  16. setInputValueByTestIdDom,
  17. waitForDefaultWorkspaceReady,
  18. } from "#e2e/helpers/desktop-app";
  19. import {
  20. restartIntoWorkspacePreservingProfile,
  21. waitForSelectedModel,
  22. } from "#e2e/helpers/model-provider-restart";
  23. import {
  24. CONTEXT_WINDOW_COLD_RESUME_MAX_TOKENS,
  25. CONTEXT_WINDOW_COLD_RESUME_MAX_OUTPUT_TOKENS,
  26. CONTEXT_WINDOW_COLD_RESUME_MODEL_ID,
  27. CONTEXT_WINDOW_COLD_RESUME_PROVIDER_ID,
  28. } from "#e2e/helpers/provider-readiness-history-fixture";
  29. import {
  30. clickV4Send,
  31. getV4CompactMarkers,
  32. getV4ConfigProjection,
  33. selectV4TaskById,
  34. sendV4Prompt,
  35. V4_MAIN_PANE_ID,
  36. waitForV4CompactMarker,
  37. waitForV4Pane,
  38. waitForV4TimelineContaining,
  39. } from "#e2e/helpers/v4-conversation";
  40. const PROVIDER_ID = CONTEXT_WINDOW_COLD_RESUME_PROVIDER_ID;
  41. const MODEL_ID = CONTEXT_WINDOW_COLD_RESUME_MODEL_ID;
  42. const CONTEXT_WINDOW = CONTEXT_WINDOW_COLD_RESUME_MAX_TOKENS;
  43. const MAX_OUTPUT_TOKENS = CONTEXT_WINDOW_COLD_RESUME_MAX_OUTPUT_TOKENS;
  44. const HIGH_USAGE_INPUT_TOKENS = 157_762;
  45. const TOOL_CALL_ID = "call_cw_pwd";
  46. const CREATE_HISTORY_MARKER = "E2E_CW_CREATE_HISTORY";
  47. const CREATE_HISTORY_REPLY = "cw-history-created-ok";
  48. const PARKING_MARKER = "E2E_CW_PARKING";
  49. const PARKING_REPLY = "cw-parking-ok";
  50. const HIGH_USAGE_MARKER = "E2E_CW_HIGH_USAGE_TOOL";
  51. const TOOL_FOLLOWUP_REPLY = "cw-tool-followup-ok";
  52. const CONTINUE_REPLY = "cw-continue-ok";
  53. const paths = getE2EAppDataPaths();
  54. describe("上下文窗口与输出预算冷恢复 E2E", () => {
  55. // 修复原因:wdio 的 Mocha 单 case 上限固定 120s,用例内 this.timeout 不生效。原单个 it 含 4 次 Electron
  56. // 完整重启(每次要等旧进程树退出屏障 + 新 session 重建),本机空载已需约 75s,Windows CI 负载下超过 120s 时,
  57. // Mocha 在重启中途截断,随后的清理又撞上旧进程退出屏障,表现为 "Electron reload 旧进程退出屏障失败"。
  58. // 按重启阶段拆成共享同一批真实会话、顺序执行的三个 it,每段独占 120s 预算,断言不变。
  59. let targetSessionId: string;
  60. let parkingSessionId: string;
  61. let preCompactProjection: ConfigProjection;
  62. let postCompactProjection: ConfigProjection;
  63. let coldPostCompactProjection: ConfigProjection;
  64. after(async () => {
  65. await browser.electron.restoreAllMocks();
  66. await clearAppData();
  67. });
  68. it("CW01-CW03: 1M/64K 会话冷恢复 limits 正确,工具续轮不误发 compact", async () => {
  69. await waitForDefaultWorkspaceReady(30_000);
  70. await waitForSelectedModel(PROVIDER_ID, MODEL_ID);
  71. // 先通过真实 UI/协议创建并完成 1M 会话;再创建一个 parking 会话保持选中,
  72. // 这样重启后目标会话尚未 resume,可在点击前安装首投影记录器。
  73. // 启动夹具已经是目标目录的空草稿,直接首发,避免无意义地替换预热中的草稿。
  74. await sendV4Prompt(CREATE_HISTORY_MARKER);
  75. await waitForV4TimelineContaining(CREATE_HISTORY_REPLY);
  76. targetSessionId = await waitForBoundSession("真实 1M 历史会话没有创建成功");
  77. // 冷恢复夹具固定在项目目录;全局新建会创建独立 cwd,不能复用该目录的记录器。
  78. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  79. await sendV4Prompt(PARKING_MARKER);
  80. await waitForV4TimelineContaining(PARKING_REPLY);
  81. parkingSessionId = await waitForBoundSession("parking 会话没有创建成功");
  82. expect(parkingSessionId).not.toBe(targetSessionId);
  83. await restartIntoWorkspacePreservingProfile();
  84. await waitForV4Pane(
  85. (snapshot) => snapshot.sessionId !== targetSessionId,
  86. "重启后目标会话在记录器安装前已被提前打开",
  87. );
  88. await installContextWindowProjectionRecorder(paths.workspace, targetSessionId);
  89. await selectV4TaskById(targetSessionId);
  90. await waitForV4TimelineContaining(CREATE_HISTORY_MARKER);
  91. await waitForV4TimelineContaining(CREATE_HISTORY_REPLY);
  92. await waitForV4Pane(
  93. (snapshot) => snapshot.sessionId === targetSessionId,
  94. "1M 历史 session 没有完成冷恢复",
  95. );
  96. const coldProjection = await waitForConfigProjection(
  97. (projection) => projection.usageUsed > 0 && projection.usageMax === CONTEXT_WINDOW,
  98. "已配置 1M provider 的历史 session 首投影没有使用 1M",
  99. );
  100. expect(coldProjection.usageMax).toBe(CONTEXT_WINDOW);
  101. const observedContextWindows = await readContextWindowProjectionRecorder();
  102. const nonZeroContextWindows = observedContextWindows.filter((value) => value > 0);
  103. // Bug 根因:旧 E2E 直接伪造 sqlite 历史,没有走真实 create/request/restart;
  104. // 这里从点击冷会话之前记录 Zustand + DOM,锁住用户能看到的第一份投影。
  105. expect(observedContextWindows).not.toContain(200_000);
  106. expect(nonZeroContextWindows[0]).toBe(CONTEXT_WINDOW);
  107. expect(new Set(nonZeroContextWindows)).toEqual(new Set([CONTEXT_WINDOW]));
  108. const highUsagePrompt =
  109. `${HIGH_USAGE_MARKER}: run readonly Bash pwd, then reply with ` + `"${TOOL_FOLLOWUP_REPLY}".`;
  110. await sendV4Prompt(highUsagePrompt);
  111. await waitForV4TimelineContaining(TOOL_FOLLOWUP_REPLY);
  112. await waitForV4Pane(
  113. (snapshot) => snapshot.sessionId === targetSessionId && !snapshot.canStop,
  114. "高 usage 工具续轮没有完成",
  115. 90_000,
  116. );
  117. const highUsageProjection = await waitForConfigProjection(
  118. (projection) =>
  119. projection.usageMax === CONTEXT_WINDOW && projection.usageUsed >= HIGH_USAGE_INPUT_TOKENS,
  120. "provider usage 没有更新到同一 1M session 的状态投影",
  121. );
  122. expect(highUsageProjection.usageUsed).toBeGreaterThanOrEqual(HIGH_USAGE_INPUT_TOKENS);
  123. const afterTool = await waitForModelIoSequence(targetSessionId, 3);
  124. expect(afterTool.filter((record) => record.querySource === "compact")).toHaveLength(0);
  125. const afterToolMainTurns = afterTool.filter((record) => record.querySource === "main_turn");
  126. expect(afterToolMainTurns).toHaveLength(3);
  127. expect(
  128. afterToolMainTurns.every((record) => record.body.max_completion_tokens === MAX_OUTPUT_TOKENS),
  129. ).toBe(true);
  130. // 修复原因:compact.auto.skipped 是异步落盘的 debug 诊断事件,不能作为 formal gate;
  131. // 这里用真实 provider 请求序列和 fail-closed fixture 证明 1M 会话没有误发 compact。
  132. expect(afterTool.every((record) => record.modelId === MODEL_ID)).toBe(true);
  133. expect(JSON.stringify(afterToolMainTurns[2]?.body)).toContain(TOOL_CALL_ID);
  134. expect(await getV4CompactMarkers()).toHaveLength(0);
  135. await sendV4Prompt("继续");
  136. await waitForV4TimelineContaining(CONTINUE_REPLY);
  137. await waitForV4Pane(
  138. (snapshot) => snapshot.sessionId === targetSessionId && !snapshot.canStop,
  139. "“继续”轮没有完成",
  140. 90_000,
  141. );
  142. const finalRequests = await waitForModelIoSequence(targetSessionId, 4);
  143. expect(finalRequests.filter((record) => record.querySource === "compact")).toHaveLength(0);
  144. const finalMainTurns = finalRequests.filter((record) => record.querySource === "main_turn");
  145. expect(finalMainTurns).toHaveLength(4);
  146. expect(
  147. finalMainTurns.every((record) => record.body.max_completion_tokens === MAX_OUTPUT_TOKENS),
  148. ).toBe(true);
  149. expect(finalRequests.every((record) => record.modelId === MODEL_ID)).toBe(true);
  150. expect(JSON.stringify(finalMainTurns[3]?.body)).toContain("继续");
  151. expect(await getV4CompactMarkers()).toHaveLength(0);
  152. expect((await getV4ConfigProjection()).usageMax).toBe(CONTEXT_WINDOW);
  153. });
  154. it("CW04: compact 后重启保持压缩后水位", async () => {
  155. preCompactProjection = await getV4ConfigProjection();
  156. expect(preCompactProjection.usageUsed).toBeGreaterThanOrEqual(HIGH_USAGE_INPUT_TOKENS);
  157. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "/compact", {
  158. timeout: 15_000,
  159. timeoutMsg: "CW04 手动 compact 前 composer 输入框没有出现",
  160. });
  161. await clickV4Send();
  162. await waitForV4CompactMarker({ origin: "manual", status: "success" }, 90_000);
  163. await waitForV4Pane(
  164. (snapshot) => snapshot.sessionId === targetSessionId && !snapshot.canStop,
  165. "CW04 手动 compact 完成后没有回到 idle",
  166. 90_000,
  167. );
  168. postCompactProjection = await waitForConfigProjection(
  169. (projection) =>
  170. projection.usageMax === CONTEXT_WINDOW &&
  171. projection.usageUsed > 0 &&
  172. projection.usageUsed < preCompactProjection.usageUsed,
  173. "CW04 热态 meter 没有下降到 post-compact 水位",
  174. );
  175. // Bug 根因:compact 后水位持久化在 user summary boundary;冷恢复如果继续只看
  176. // assistant tokens,会越过 boundary 并把 meter 恢复到 compact 前的旧值。
  177. await selectV4TaskById(parkingSessionId);
  178. // Bug 根因:只等 pane sessionId 会早于 parking 会话的 initial snapshot;此时立即
  179. // 重启会中断在途 subscribe,让旧窗口短暂显示“重新连接”错误页。
  180. await waitForV4TimelineContaining(PARKING_REPLY);
  181. await waitForV4Pane(
  182. (snapshot) => snapshot.sessionId === parkingSessionId && !snapshot.canStop,
  183. "CW04 重启前没有切回 parking session",
  184. );
  185. await restartIntoWorkspacePreservingProfile();
  186. await waitForV4Pane(
  187. (snapshot) => snapshot.sessionId !== targetSessionId,
  188. "CW04 第二次重启后目标 session 被提前打开",
  189. );
  190. await selectV4TaskById(targetSessionId);
  191. await waitForV4Pane(
  192. (snapshot) => snapshot.sessionId === targetSessionId && !snapshot.canStop,
  193. "CW04 compact 历史 session 没有完成冷恢复",
  194. 90_000,
  195. );
  196. await waitForV4CompactMarker({ origin: "manual", status: "success" }, 90_000);
  197. await waitForSelectedModel(PROVIDER_ID, MODEL_ID);
  198. coldPostCompactProjection = await waitForConfigProjection(
  199. (projection) => projection.usageMax === CONTEXT_WINDOW && projection.usageUsed > 0,
  200. "CW04 冷恢复后没有发布 context usage",
  201. );
  202. expect(coldPostCompactProjection.usageUsed).toBe(postCompactProjection.usageUsed);
  203. expect(coldPostCompactProjection.usageUsed).toBeLessThan(preCompactProjection.usageUsed);
  204. });
  205. it("CW05-CW06: 缺档位历史选择保留容量,未知模型不伪造容量", async () => {
  206. // Todo123:只在隔离 E2E 进程退出屏障后改这条真实创建的会话,模拟旧选择缺档位。
  207. // transcript、compact 水位和旧字段均不改;不构造假的聊天正文来替代恢复。
  208. await selectV4TaskById(parkingSessionId);
  209. await restartWithFixture(paths.workspace, {
  210. afterElectronProcessExit: () => patchFixtureSelection(targetSessionId, false),
  211. });
  212. await installContextWindowProjectionRecorder(paths.workspace, targetSessionId);
  213. await selectV4TaskById(targetSessionId);
  214. await waitForV4TimelineContaining(CREATE_HISTORY_REPLY);
  215. const missingReasoning = await waitForConfigProjection(
  216. (projection) => projection.usageMax === CONTEXT_WINDOW && projection.usageUsed > 0,
  217. "CW05 缺档位历史选择未保留真实容量与用量",
  218. );
  219. expect(missingReasoning.usageUsed).toBe(coldPostCompactProjection.usageUsed);
  220. expect(await readContextWindowProjectionRecorder()).not.toContain(200_000);
  221. await selectV4TaskById(parkingSessionId);
  222. await restartWithFixture(paths.workspace, {
  223. afterElectronProcessExit: () => patchFixtureSelection(targetSessionId, true),
  224. });
  225. await selectV4TaskById(targetSessionId);
  226. await waitForV4TimelineContaining(CREATE_HISTORY_REPLY);
  227. await waitForV4Pane(
  228. (snapshot) => snapshot.sessionId === targetSessionId && !snapshot.canStop,
  229. "CW06 未知模型会话应可打开",
  230. );
  231. await waitForConfigProjection(
  232. (projection) => projection.usageMax === 0,
  233. "CW06 未知模型不应显示伪造容量",
  234. );
  235. });
  236. });
  237. function patchFixtureSelection(sessionId: string, unknownModel: boolean): void {
  238. // node:sqlite 仅有同步 API;这里只写测试专属库中指定 session 的新字段。
  239. const database = new DatabaseSync(join(paths.homeDir, ".zcode", "cli", "db", "db.sqlite"));
  240. try {
  241. const result = database
  242. .prepare(`UPDATE session_entry
  243. SET data=json_set(data, '$.modelSelection', json(?))
  244. WHERE session_id=? AND type='runtime/model_selection'`)
  245. .run(
  246. JSON.stringify({
  247. providerId: PROVIDER_ID,
  248. modelId: unknownModel ? "missing-cw-model" : MODEL_ID,
  249. }),
  250. sessionId,
  251. );
  252. expect(Number(result.changes)).toBeGreaterThan(0);
  253. } finally {
  254. database.close();
  255. }
  256. }
  257. async function waitForBoundSession(timeoutMsg: string): Promise<string> {
  258. const snapshot = await waitForV4Pane(
  259. (current) => Boolean(current.sessionId && current.sessionId !== "draft" && !current.canStop),
  260. timeoutMsg,
  261. 90_000,
  262. );
  263. if (!snapshot.sessionId || snapshot.sessionId === "draft") {
  264. throw new Error(`${timeoutMsg}; sessionId=${snapshot.sessionId}`);
  265. }
  266. return snapshot.sessionId;
  267. }
  268. interface ConfigProjection {
  269. mode: string | null;
  270. usageMax: number;
  271. usageUsed: number;
  272. }
  273. async function waitForConfigProjection(
  274. predicate: (projection: ConfigProjection) => boolean,
  275. timeoutMsg: string,
  276. ): Promise<ConfigProjection> {
  277. let latest: ConfigProjection = await getV4ConfigProjection();
  278. await browser.waitUntil(
  279. async () => {
  280. latest = await getV4ConfigProjection();
  281. return predicate(latest);
  282. },
  283. {
  284. interval: 100,
  285. timeout: 30_000,
  286. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(latest)}`,
  287. },
  288. );
  289. return latest;
  290. }
  291. interface ContextWindowProjectionRecorder {
  292. dom: number[];
  293. store: number[];
  294. }
  295. async function installContextWindowProjectionRecorder(
  296. workspacePath: string,
  297. sessionId: string,
  298. ): Promise<void> {
  299. const paneTestId = testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID);
  300. await browser.execute(
  301. (targetWorkspacePath, targetSessionId, targetPaneTestId, modelConfigTestId) => {
  302. interface SessionStoreState {
  303. getWorkspaceState: (workspace: string) => {
  304. taskRuntimeByTaskId: Record<
  305. string,
  306. {
  307. contextWindow?: number | null;
  308. usage?: { size?: number } | null;
  309. }
  310. >;
  311. };
  312. }
  313. interface SessionStoreBridge {
  314. getState: () => SessionStoreState;
  315. subscribe: (listener: (state: SessionStoreState) => void) => () => void;
  316. }
  317. interface RecorderHost {
  318. __zcodeContextWindowColdResumeE2E?: {
  319. dom: number[];
  320. observer: MutationObserver;
  321. store: number[];
  322. unsubscribe: () => void;
  323. };
  324. __zcodeSessionStoreE2E?: SessionStoreBridge;
  325. }
  326. const host = window as unknown as RecorderHost;
  327. host.__zcodeContextWindowColdResumeE2E?.observer.disconnect();
  328. host.__zcodeContextWindowColdResumeE2E?.unsubscribe();
  329. const dom: number[] = [];
  330. const store: number[] = [];
  331. const append = (target: number[], value: unknown) => {
  332. const numeric = Number(value);
  333. if (Number.isFinite(numeric) && target[target.length - 1] !== numeric) {
  334. target.push(numeric);
  335. }
  336. };
  337. const recordDom = () => {
  338. const pane = document.querySelector<HTMLElement>(`[data-testid="${targetPaneTestId}"]`);
  339. if (pane?.getAttribute("data-session-id") !== targetSessionId) {
  340. return;
  341. }
  342. const modelConfig = pane.querySelector<HTMLElement>(`[data-testid="${modelConfigTestId}"]`);
  343. append(dom, modelConfig?.getAttribute("data-usage-max"));
  344. };
  345. const observer = new MutationObserver(recordDom);
  346. observer.observe(document.body, {
  347. attributeFilter: ["data-session-id", "data-usage-max"],
  348. attributes: true,
  349. childList: true,
  350. subtree: true,
  351. });
  352. const bridge = host.__zcodeSessionStoreE2E;
  353. if (!bridge) {
  354. throw new Error("ZCode session E2E store bridge 未注册");
  355. }
  356. const recordStore = (state: SessionStoreState) => {
  357. const runtime =
  358. state.getWorkspaceState(targetWorkspacePath).taskRuntimeByTaskId[targetSessionId];
  359. append(store, runtime?.usage?.size ?? runtime?.contextWindow);
  360. };
  361. const unsubscribe = bridge.subscribe(recordStore);
  362. recordStore(bridge.getState());
  363. recordDom();
  364. host.__zcodeContextWindowColdResumeE2E = {
  365. dom,
  366. observer,
  367. store,
  368. unsubscribe,
  369. };
  370. },
  371. workspacePath,
  372. sessionId,
  373. paneTestId,
  374. TID_V4_MODEL_CONFIG,
  375. );
  376. }
  377. async function readContextWindowProjectionRecorder(): Promise<number[]> {
  378. const recorder = await browser.execute(() => {
  379. const value = (
  380. window as unknown as {
  381. __zcodeContextWindowColdResumeE2E?: ContextWindowProjectionRecorder;
  382. }
  383. ).__zcodeContextWindowColdResumeE2E;
  384. return value ? { dom: [...value.dom], store: [...value.store] } : null;
  385. });
  386. if (!recorder) {
  387. throw new Error("1M context 冷恢复投影记录器意外丢失");
  388. }
  389. return [...recorder.store, ...recorder.dom];
  390. }
  391. interface ModelIoRecord {
  392. error?: unknown;
  393. model?: { modelId?: string };
  394. querySource?: string;
  395. request?: { body?: unknown };
  396. response?: unknown;
  397. sessionId?: string;
  398. }
  399. interface ModelIoMatch {
  400. body: Record<string, unknown>;
  401. modelId: string | undefined;
  402. querySource: string;
  403. }
  404. async function waitForModelIoSequence(
  405. sessionId: string,
  406. expectedMainTurnCount: number,
  407. ): Promise<ModelIoMatch[]> {
  408. let matched: ModelIoMatch[] = [];
  409. // 修复原因:timeoutMsg 是调用 waitUntil 前就求值的字符串,latest 永远打印初始空数组,
  410. // 曾把"follow-up 请求被 replay 拒绝、只有 2 个 main_turn"误导成"读不到 model-io"。超时后再按实际结果报错。
  411. await browser
  412. .waitUntil(
  413. async () => {
  414. matched = await readSuccessfulModelIo(sessionId);
  415. return (
  416. matched.filter((record) => record.querySource === "main_turn").length >=
  417. expectedMainTurnCount
  418. );
  419. },
  420. { interval: 100, timeout: 30_000 },
  421. )
  422. .catch(() => {
  423. throw new Error(
  424. `model-io 没有达到 ${expectedMainTurnCount} 个 main_turn; ` +
  425. `latest=${JSON.stringify(matched.map((record) => record.querySource))}`,
  426. );
  427. });
  428. return matched;
  429. }
  430. async function readSuccessfulModelIo(sessionId: string): Promise<ModelIoMatch[]> {
  431. const debugDir = join(paths.homeDir, ".zcode", "cli", "debug");
  432. const files = (await readdir(debugDir).catch(() => []))
  433. .filter((name) => name.startsWith("model-io-") && name.endsWith(".jsonl"))
  434. .sort();
  435. const matched: ModelIoMatch[] = [];
  436. for (const file of files) {
  437. const content = await readFile(join(debugDir, file), "utf-8").catch(() => "");
  438. for (const line of content.split("\n")) {
  439. const record = parseJsonObject(line) as ModelIoRecord | null;
  440. if (
  441. !record ||
  442. record.error !== undefined ||
  443. record.response === undefined ||
  444. record.sessionId !== sessionId ||
  445. typeof record.querySource !== "string"
  446. ) {
  447. continue;
  448. }
  449. const body = parseJsonObject(record.request?.body);
  450. if (!body || body.bodySource === "ai_sdk_options") {
  451. continue;
  452. }
  453. matched.push({
  454. body,
  455. modelId: record.model?.modelId,
  456. querySource: record.querySource,
  457. });
  458. }
  459. }
  460. return matched;
  461. }
  462. function parseJsonObject(value: unknown): Record<string, unknown> | null {
  463. if (typeof value === "string") {
  464. try {
  465. return parseJsonObject(JSON.parse(value));
  466. } catch {
  467. return null;
  468. }
  469. }
  470. return value && typeof value === "object" && !Array.isArray(value)
  471. ? (value as Record<string, unknown>)
  472. : null;
  473. }