runtime-model-selection.test.ts 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. import { describe, expect, it, vi } from "vitest";
  2. import { createTestModelSelection } from "./test-model-selection.js";
  3. import {
  4. CoreErrorType,
  5. ModelRetryBudget,
  6. SessionEventType,
  7. createModelId,
  8. createModelProviderId,
  9. createSessionId,
  10. type Logger,
  11. } from "@zcode/contracts";
  12. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  13. import { createTestSessionEventStore } from "./test-event-store.js";
  14. import { createTestModelFactory } from "./test-runtime-model.js";
  15. /** 只捕获 warn 的 Logger 桩:退回路径的留痕本身是回归断言的一部分。 */
  16. function createWarnCapturingLogger(warn: ReturnType<typeof vi.fn>): Logger {
  17. const logger = {
  18. debug: vi.fn(),
  19. info: vi.fn(),
  20. warn,
  21. error: vi.fn(),
  22. child: () => logger,
  23. };
  24. return logger as unknown as Logger;
  25. }
  26. /** 加速 provider 上的请求按卡过期(3402)失败,其他 provider 正常完成。 */
  27. function createCardExpiryModelFactory(
  28. highspeedProviderId: string,
  29. requests: Array<{ modelId: string; providerId: string }>,
  30. ) {
  31. return createTestModelFactory({
  32. async generateText(_request, observation) {
  33. requests.push({
  34. modelId: String(observation.model.modelId),
  35. providerId: String(observation.model.providerId),
  36. });
  37. if (String(observation.model.providerId) === highspeedProviderId) {
  38. throw Object.assign(new Error("highspeed card is invalid"), {
  39. code: "invalid_model_request",
  40. context: {
  41. providerCode: "3402",
  42. providerId: highspeedProviderId,
  43. modelId: "GLM-5.3",
  44. source: "provider",
  45. statusCode: 400,
  46. },
  47. name: "AiSdkModelAdapterError",
  48. });
  49. }
  50. return {
  51. finishReason: "stop",
  52. model: observation.model,
  53. text: "continued with the original model",
  54. usage: { inputTokens: 1, outputTokens: 2, totalTokens: 3 },
  55. };
  56. },
  57. });
  58. }
  59. const cardExpiryFallbackRules = [
  60. { reason: "highspeed_card_expired" as const, providerErrorCode: "3402" },
  61. { reason: "highspeed_request_failed" as const },
  62. ];
  63. describe("AgentRuntime model selection event", () => {
  64. it("首轮只按 admitted Active Model 构造一次 Context", async () => {
  65. const runtime = createTestAgentRuntime(
  66. createSessionId("runtime-first-turn-single-context-build"),
  67. {
  68. modelSelection: createTestModelSelection("provider-a/model-a"),
  69. titleGeneration: { enabled: false },
  70. workingDirectory: "/workspace/project",
  71. },
  72. {
  73. eventStore: createTestSessionEventStore(),
  74. modelFactory: createTestModelFactory({
  75. async generateText(_request, observation) {
  76. return {
  77. finishReason: "stop",
  78. model: observation.model,
  79. text: "done",
  80. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  81. };
  82. },
  83. }),
  84. },
  85. );
  86. const internalRuntime = runtime as typeof runtime & {
  87. createContextBuilderFromSnapshot: (...args: unknown[]) => unknown;
  88. };
  89. const createContextBuilderFromSnapshot =
  90. internalRuntime.createContextBuilderFromSnapshot.bind(internalRuntime);
  91. let contextBuildCount = 0;
  92. internalRuntime.createContextBuilderFromSnapshot = (...args: unknown[]) => {
  93. contextBuildCount++;
  94. return createContextBuilderFromSnapshot(...args);
  95. };
  96. await runtime.executeTurn("first turn");
  97. expect(contextBuildCount).toBe(1);
  98. await runtime.executeTurn("second turn");
  99. expect(contextBuildCount).toBe(2);
  100. });
  101. it("uses the admitted Active Model for both Context and the provider request", async () => {
  102. const requests: Array<{ modelId: string; providerId: string; text: string }> = [];
  103. const runtime = createTestAgentRuntime(
  104. createSessionId("runtime-active-model-context"),
  105. {
  106. modelSelection: createTestModelSelection("provider-a/model-a"),
  107. titleGeneration: { enabled: false },
  108. workingDirectory: "/workspace/project",
  109. },
  110. {
  111. eventStore: createTestSessionEventStore(),
  112. modelFactory: createTestModelFactory({
  113. async generateText(request, observation) {
  114. requests.push({
  115. modelId: String(observation.model.modelId),
  116. providerId: String(observation.model.providerId),
  117. text: JSON.stringify(request.messages),
  118. });
  119. return {
  120. finishReason: "stop",
  121. model: observation.model,
  122. text: "done",
  123. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  124. };
  125. },
  126. }),
  127. },
  128. );
  129. await runtime.executeTurn("switch now", undefined, {
  130. intent: {
  131. kind: "sendText",
  132. modelSelection: {
  133. providerId: "provider-b",
  134. modelId: "model-b",
  135. options: { reasoningLevel: "high" },
  136. },
  137. requestedDelivery: "start-now",
  138. sourceCommandId: "switch-command",
  139. },
  140. });
  141. expect(requests).toHaveLength(1);
  142. expect(requests[0]).toMatchObject({ providerId: "provider-b", modelId: "model-b" });
  143. expect(requests[0]?.text).toContain("provider-b/model-b");
  144. expect(requests[0]?.text).not.toContain("provider-a/model-a");
  145. });
  146. it("uses an execution-scoped Active Model in Context without changing Session Selection", async () => {
  147. const requests: Array<{ modelId: string; providerId: string; text: string }> = [];
  148. const sessionSelection = createTestModelSelection("provider-a/model-a");
  149. const runtime = createTestAgentRuntime(
  150. createSessionId("runtime-execution-model-context"),
  151. {
  152. modelSelection: sessionSelection,
  153. titleGeneration: { enabled: false },
  154. workingDirectory: "/workspace/project",
  155. },
  156. {
  157. eventStore: createTestSessionEventStore(),
  158. modelFactory: createTestModelFactory({
  159. async generateText(request, observation) {
  160. requests.push({
  161. modelId: String(observation.model.modelId),
  162. providerId: String(observation.model.providerId),
  163. text: JSON.stringify(request.messages),
  164. });
  165. return {
  166. finishReason: "stop",
  167. model: observation.model,
  168. text: "done",
  169. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  170. };
  171. },
  172. }),
  173. },
  174. );
  175. await runtime.executeTurn("idle task", undefined, {
  176. intent: {
  177. kind: "sendText",
  178. modelSelection: {
  179. providerId: "account:zai-offpeak-idle-plan",
  180. modelId: "GLM-5.2",
  181. options: { reasoningLevel: "high" },
  182. },
  183. requestedDelivery: "start-now",
  184. sourceCommandId: "idle-command",
  185. },
  186. modelExecution: { selectionScope: "execution" },
  187. });
  188. expect(requests).toHaveLength(1);
  189. expect(requests[0]).toMatchObject({
  190. providerId: "account:zai-offpeak-idle-plan",
  191. modelId: "GLM-5.2",
  192. });
  193. expect(requests[0]?.text).toContain("account:zai-offpeak-idle-plan/GLM-5.2");
  194. expect(requests[0]?.text).not.toContain("provider-a/model-a");
  195. expect(runtime.getSessionModelSelection()).toEqual(sessionSelection);
  196. });
  197. it("applies a Session Selection change during an active turn only to the next Active Model", async () => {
  198. const requests: Array<{ modelId: string; providerId: string; text: string }> = [];
  199. let runtime: ReturnType<typeof createTestAgentRuntime>;
  200. runtime = createTestAgentRuntime(
  201. createSessionId("runtime-active-turn-selection-change"),
  202. {
  203. modelSelection: createTestModelSelection("provider-a/model-a"),
  204. titleGeneration: { enabled: false },
  205. workingDirectory: "/workspace/project",
  206. },
  207. {
  208. eventStore: createTestSessionEventStore(),
  209. modelFactory: createTestModelFactory({
  210. async generateText(request, observation) {
  211. requests.push({
  212. modelId: String(observation.model.modelId),
  213. providerId: String(observation.model.providerId),
  214. text: JSON.stringify(request.messages),
  215. });
  216. if (requests.length === 1) {
  217. runtime.setSessionModelSelection({
  218. providerId: "provider-b",
  219. modelId: "model-b",
  220. options: { reasoningLevel: "high" },
  221. });
  222. }
  223. return {
  224. finishReason: "stop",
  225. model: observation.model,
  226. text: "done",
  227. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  228. };
  229. },
  230. }),
  231. },
  232. );
  233. await runtime.executeTurn("first");
  234. await runtime.executeTurn("second");
  235. expect(requests).toHaveLength(2);
  236. expect(requests[0]).toMatchObject({ providerId: "provider-a", modelId: "model-a" });
  237. expect(requests[0]?.text).toContain("provider-a/model-a");
  238. expect(requests[0]?.text).not.toContain("provider-b/model-b");
  239. expect(requests[1]).toMatchObject({ providerId: "provider-b", modelId: "model-b" });
  240. expect(requests[1]?.text).toContain("provider-b/model-b");
  241. expect(requests[1]?.text).not.toContain("provider-a/model-a");
  242. });
  243. it("uses structured ModelSelection as the current Session model fact", () => {
  244. const runtime = createTestAgentRuntime(
  245. createSessionId("runtime-structured-session-model-selection"),
  246. {
  247. modelSelection: {
  248. providerId: "provider-a",
  249. modelId: "model-a",
  250. options: {
  251. reasoningLevel: "high",
  252. },
  253. },
  254. },
  255. { eventStore: createTestSessionEventStore() },
  256. );
  257. expect(runtime.getSessionModelSelection()).toEqual({
  258. providerId: "provider-a",
  259. modelId: "model-a",
  260. options: {
  261. reasoningLevel: "high",
  262. },
  263. });
  264. const nextSelection = {
  265. providerId: "provider-b",
  266. modelId: "model-b",
  267. options: {
  268. reasoningLevel: "low",
  269. },
  270. };
  271. runtime.setSessionModelSelection(nextSelection);
  272. nextSelection.options.reasoningLevel = "mutated-outside-runtime";
  273. expect(runtime.getSessionModelSelection()).toEqual({
  274. providerId: "provider-b",
  275. modelId: "model-b",
  276. options: {
  277. reasoningLevel: "low",
  278. },
  279. });
  280. });
  281. it("publishes the Active Model context window with ModelSelected", async () => {
  282. const sessionId = createSessionId("runtime-model-selection-context-window");
  283. const eventStore = createTestSessionEventStore();
  284. const runtime = createTestAgentRuntime(
  285. sessionId,
  286. {},
  287. {
  288. eventStore,
  289. modelFactory: createTestModelFactory({ properties: { contextWindow: 1_000_000 } }),
  290. },
  291. );
  292. await runtime.emitModelSelected({
  293. modelSelection: {
  294. providerId: createModelProviderId("deepseek"),
  295. modelId: createModelId("deepseek-v4-flash"),
  296. },
  297. supportedThoughtLevels: ["max", "high", "nothink"],
  298. traceContext: { traceId: "trace-runtime-model-selection" } as never,
  299. });
  300. const selected = (await eventStore.getEvents(sessionId)).find(
  301. (event) => event.type === SessionEventType.ModelSelected,
  302. );
  303. expect(selected?.payload).toMatchObject({
  304. contextWindow: 1_000_000,
  305. modelSelection: {
  306. providerId: "deepseek",
  307. modelId: "deepseek-v4-flash",
  308. },
  309. supportedThoughtLevels: ["max", "high", "nothink"],
  310. });
  311. });
  312. it("preserves the registry fallback origin in ModelSelected", async () => {
  313. const sessionId = createSessionId("runtime-model-selection-registry-fallback");
  314. const eventStore = createTestSessionEventStore();
  315. const runtime = createTestAgentRuntime(sessionId, {}, { eventStore });
  316. await runtime.emitModelSelected({
  317. modelSelection: {
  318. providerId: createModelProviderId("provider-b"),
  319. modelId: createModelId("model-b"),
  320. },
  321. previousModelSelection: {
  322. providerId: createModelProviderId("provider-a"),
  323. modelId: createModelId("model-a"),
  324. },
  325. origin: "registryFallback",
  326. traceContext: { traceId: "trace-runtime-model-selection-fallback" } as never,
  327. });
  328. const selected = (await eventStore.getEvents(sessionId)).find(
  329. (event) => event.type === SessionEventType.ModelSelected,
  330. );
  331. expect(selected?.payload).toMatchObject({
  332. origin: "registryFallback",
  333. previousModelSelection: {
  334. providerId: "provider-a",
  335. modelId: "model-a",
  336. },
  337. });
  338. });
  339. it("uses the execution-scoped Selection for foreground children without applying profile reasoning", async () => {
  340. const sessionId = createSessionId("runtime-turn-model-foreground-subagents");
  341. const eventStore = createTestSessionEventStore();
  342. const sessionModel = createTestModelSelection("user-provider/user-model");
  343. const childExecutions: Array<Record<string, unknown>> = [];
  344. const mainRequests: Array<Record<string, unknown>> = [];
  345. const runtime = createTestAgentRuntime(
  346. sessionId,
  347. {
  348. modelSelection: createTestModelSelection(sessionModel),
  349. subagents: {
  350. profiles: [
  351. {
  352. description: "Search source code",
  353. modelSelection: {
  354. providerId: "custom-provider",
  355. modelId: "custom-code-model",
  356. options: { reasoningLevel: "high" },
  357. },
  358. name: "Code Search",
  359. source: "user",
  360. systemPrompt: "Search code.",
  361. tools: ["Read"],
  362. },
  363. ],
  364. },
  365. titleGeneration: { enabled: false },
  366. workingDirectory: "/workspace/project",
  367. },
  368. {
  369. eventStore,
  370. modelFactory: createTestModelFactory({
  371. maxOutputTokens: (input) =>
  372. input.selection.providerId === "account:zai-offpeak-idle-plan" ? 16_000 : 32_000,
  373. async generateText(request, observation) {
  374. const metadata = observation.invocationContext?.metadata as
  375. | { querySource?: string; turnNumber?: number }
  376. | undefined;
  377. const capturedRequest = {
  378. maxOutputTokens: request.options?.maxOutputTokens,
  379. model: observation.model,
  380. };
  381. if (metadata?.querySource === "subagent") {
  382. childExecutions.push(capturedRequest);
  383. return {
  384. finishReason: "stop",
  385. model: observation.model,
  386. text: "child done",
  387. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  388. };
  389. }
  390. mainRequests.push(capturedRequest);
  391. if (metadata?.turnNumber === 0 && mainRequests.length === 1) {
  392. return {
  393. finishReason: "tool-calls",
  394. model: observation.model,
  395. text: "",
  396. toolCalls: [
  397. {
  398. id: "call_explore",
  399. name: "Agent",
  400. input: {
  401. description: "Explore source",
  402. prompt: "Explore the source.",
  403. subagent_type: "Explore",
  404. },
  405. },
  406. {
  407. id: "call_code_search",
  408. name: "Agent",
  409. input: {
  410. description: "Search source",
  411. prompt: "Search the source.",
  412. subagent_type: "Code Search",
  413. },
  414. },
  415. ],
  416. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  417. };
  418. }
  419. if (metadata?.turnNumber === 1 && mainRequests.length === 3) {
  420. return {
  421. finishReason: "tool-calls",
  422. model: observation.model,
  423. text: "",
  424. toolCalls: [
  425. {
  426. id: "call_code_search_ordinary",
  427. name: "Agent",
  428. input: {
  429. description: "Search source with profile settings",
  430. prompt: "Search the source with the configured profile.",
  431. subagent_type: "Code Search",
  432. },
  433. },
  434. ],
  435. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  436. };
  437. }
  438. return {
  439. finishReason: "stop",
  440. model: observation.model,
  441. text: "turn done",
  442. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  443. };
  444. },
  445. } as never),
  446. },
  447. );
  448. await runtime.executeTurn("run foreground children", undefined, {
  449. intent: {
  450. sourceCommandId: "idle-command",
  451. kind: "sendText",
  452. requestedDelivery: "start-now",
  453. modelSelection: {
  454. providerId: "account:zai-offpeak-idle-plan",
  455. modelId: "GLM-5.2",
  456. options: { reasoningLevel: "high" },
  457. },
  458. },
  459. modelExecution: {
  460. selectionScope: "execution",
  461. subagents: { foregroundModel: "submission", background: "deny" },
  462. },
  463. });
  464. await runtime.executeTurn("ordinary prompt");
  465. expect(childExecutions).toHaveLength(3);
  466. expect(childExecutions.slice(0, 2).map((execution) => execution.model)).toEqual([
  467. expect.objectContaining({
  468. providerId: "account:zai-offpeak-idle-plan",
  469. modelId: "GLM-5.2",
  470. }),
  471. expect.objectContaining({
  472. providerId: "account:zai-offpeak-idle-plan",
  473. modelId: "GLM-5.2",
  474. }),
  475. ]);
  476. expect(
  477. childExecutions
  478. .slice(0, 2)
  479. .map(
  480. (execution) =>
  481. (execution.model as { options?: { reasoningLevel?: string } }).options?.reasoningLevel,
  482. ),
  483. ).toEqual(["high", "high"]);
  484. expect(childExecutions.slice(0, 2).map((execution) => execution.maxOutputTokens)).toEqual([
  485. 16_000, 16_000,
  486. ]);
  487. expect(childExecutions[2]?.model).toEqual(
  488. expect.objectContaining({
  489. providerId: "custom-provider",
  490. modelId: "custom-code-model",
  491. }),
  492. );
  493. expect(childExecutions[2]?.model).toEqual(
  494. expect.objectContaining({ options: expect.objectContaining({ reasoningLevel: "high" }) }),
  495. );
  496. expect(mainRequests).toHaveLength(4);
  497. expect(mainRequests.at(-1)?.model).toEqual(
  498. expect.objectContaining({
  499. providerId: "user-provider",
  500. modelId: "user-model",
  501. }),
  502. );
  503. expect(runtime.getSessionModelSelection()).toEqual({
  504. providerId: String(sessionModel.providerId),
  505. modelId: String(sessionModel.modelId),
  506. });
  507. });
  508. it.each(["failure", "cancel"] as const)(
  509. "does not retain an execution-scoped Selection after %s",
  510. async (outcome) => {
  511. const sessionId = createSessionId(`runtime-turn-model-cleanup-${outcome}`);
  512. const abortController = new AbortController();
  513. const requests: Array<Record<string, unknown>> = [];
  514. let failFirstRequest = true;
  515. const runtime = createTestAgentRuntime(
  516. sessionId,
  517. {
  518. modelSelection: createTestModelSelection(
  519. createTestModelSelection("user-provider/user-model"),
  520. ),
  521. titleGeneration: { enabled: false },
  522. workingDirectory: "/workspace/project",
  523. },
  524. {
  525. eventStore: createTestSessionEventStore(),
  526. modelFactory: createTestModelFactory({
  527. async generateText(request, observation) {
  528. requests.push({
  529. model: observation.model,
  530. request,
  531. });
  532. if (failFirstRequest) {
  533. failFirstRequest = false;
  534. if (outcome === "cancel") {
  535. abortController.abort(new Error("user cancelled idle turn"));
  536. }
  537. throw new Error(`${outcome} idle turn`);
  538. }
  539. return {
  540. finishReason: "stop",
  541. model: observation.model,
  542. text: "ordinary turn done",
  543. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  544. };
  545. },
  546. } as never),
  547. },
  548. );
  549. await expect(
  550. runtime.executeTurn("idle turn", undefined, {
  551. abortSignal: abortController.signal,
  552. intent: {
  553. sourceCommandId: `idle-${outcome}`,
  554. kind: "sendText",
  555. requestedDelivery: "start-now",
  556. modelSelection: {
  557. providerId: "account:zai-offpeak-idle-plan",
  558. modelId: "GLM-5.2",
  559. },
  560. },
  561. modelExecution: {
  562. selectionScope: "execution",
  563. },
  564. }),
  565. ).rejects.toMatchObject({
  566. type: outcome === "cancel" ? CoreErrorType.TurnCancelled : CoreErrorType.UnknownError,
  567. });
  568. await runtime.executeTurn("ordinary prompt");
  569. expect(requests).toHaveLength(2);
  570. expect(requests[0]?.model).toEqual(
  571. expect.objectContaining({
  572. providerId: "account:zai-offpeak-idle-plan",
  573. modelId: "GLM-5.2",
  574. }),
  575. );
  576. expect(requests[1]?.model).toEqual(
  577. expect.objectContaining({ providerId: "user-provider", modelId: "user-model" }),
  578. );
  579. },
  580. );
  581. it("falls back to the Session Selection inside the same turn when the declared provider error hits", async () => {
  582. const sessionId = createSessionId("runtime-execution-selection-fallback");
  583. const eventStore = createTestSessionEventStore();
  584. const highspeedProviderId = "account:zai-highspeed-card";
  585. const requests: Array<{ modelId: string; providerId: string }> = [];
  586. const runtime = createTestAgentRuntime(
  587. sessionId,
  588. {
  589. modelSelection: createTestModelSelection("user-provider/user-model"),
  590. titleGeneration: { enabled: false },
  591. workingDirectory: "/workspace/project",
  592. },
  593. {
  594. eventStore,
  595. modelFactory: createTestModelFactory({
  596. async generateText(_request, observation) {
  597. requests.push({
  598. modelId: String(observation.model.modelId),
  599. providerId: String(observation.model.providerId),
  600. });
  601. if (String(observation.model.providerId) === highspeedProviderId) {
  602. throw Object.assign(new Error("highspeed card is invalid"), {
  603. code: "invalid_model_request",
  604. context: {
  605. providerCode: "3402",
  606. providerId: highspeedProviderId,
  607. modelId: "GLM-5.3",
  608. source: "provider",
  609. },
  610. name: "AiSdkModelAdapterError",
  611. });
  612. }
  613. return {
  614. finishReason: "stop",
  615. model: observation.model,
  616. text: "continued with the session model",
  617. usage: { inputTokens: 1, outputTokens: 2, totalTokens: 3 },
  618. };
  619. },
  620. }),
  621. },
  622. );
  623. const result = await runtime.executeTurn("continue after expiry", undefined, {
  624. inputId: "command-highspeed-expired",
  625. intent: {
  626. sourceCommandId: "command-highspeed-expired",
  627. kind: "sendText",
  628. requestedDelivery: "start-now",
  629. modelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  630. },
  631. modelExecution: {
  632. selectionScope: "execution",
  633. selectionFallback: {
  634. providerId: highspeedProviderId,
  635. rules: [
  636. { reason: "highspeed_card_expired", providerErrorCode: "3402" },
  637. { reason: "highspeed_request_failed" },
  638. ],
  639. },
  640. },
  641. });
  642. expect(result.response).toBe("continued with the session model");
  643. expect(requests).toEqual([
  644. { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  645. { providerId: "user-provider", modelId: "user-model" },
  646. ]);
  647. const fallbackEvent = (await eventStore.getEvents(sessionId)).find(
  648. (event) => event.type === SessionEventType.TurnExecutionModelFallback,
  649. );
  650. expect(fallbackEvent?.payload).toMatchObject({
  651. inputId: "command-highspeed-expired",
  652. reason: "highspeed_card_expired",
  653. fromModelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  654. toModelSelection: { providerId: "user-provider", modelId: "user-model" },
  655. });
  656. // execution 作用域从不改写 Session Selection:退回目标就是它自己。
  657. expect(runtime.getSessionModelSelection()).toMatchObject({
  658. providerId: "user-provider",
  659. modelId: "user-model",
  660. });
  661. });
  662. it("falls back to the Session Selection on any execution provider failure with a single-attempt budget", async () => {
  663. // docs/highspeed/highspeed-card-spec.md §2.2:加速请求任何失败(这里是网关 401,没有业务码)都退回;
  664. // 加速句柄 0 次重试(single-attempt),退回后的会话模型恢复默认预算。
  665. const sessionId = createSessionId("runtime-execution-selection-any-failure-fallback");
  666. const eventStore = createTestSessionEventStore();
  667. const highspeedProviderId = "account:zai-highspeed-card";
  668. const requests: Array<{ modelId: string; providerId: string; retryBudget: unknown }> = [];
  669. const runtime = createTestAgentRuntime(
  670. sessionId,
  671. {
  672. modelSelection: createTestModelSelection("user-provider/user-model"),
  673. titleGeneration: { enabled: false },
  674. workingDirectory: "/workspace/project",
  675. },
  676. {
  677. eventStore,
  678. modelFactory: createTestModelFactory({
  679. async generateText(_request, observation) {
  680. requests.push({
  681. modelId: String(observation.model.modelId),
  682. providerId: String(observation.model.providerId),
  683. retryBudget: observation.invocationContext?.modelRetryBudget,
  684. });
  685. if (String(observation.model.providerId) === highspeedProviderId) {
  686. throw Object.assign(new Error("Provider authentication failed."), {
  687. code: "provider_not_configured",
  688. context: {
  689. providerId: highspeedProviderId,
  690. modelId: "GLM-5.3",
  691. reason: "auth_failed",
  692. retryable: false,
  693. source: "provider",
  694. statusCode: 401,
  695. },
  696. name: "AiSdkModelAdapterError",
  697. });
  698. }
  699. return {
  700. finishReason: "stop",
  701. model: observation.model,
  702. text: "continued with the session model",
  703. usage: { inputTokens: 1, outputTokens: 2, totalTokens: 3 },
  704. };
  705. },
  706. }),
  707. },
  708. );
  709. const result = await runtime.executeTurn("continue after gateway failure", undefined, {
  710. inputId: "command-highspeed-401",
  711. intent: {
  712. sourceCommandId: "command-highspeed-401",
  713. kind: "sendText",
  714. requestedDelivery: "start-now",
  715. modelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  716. },
  717. modelExecution: {
  718. selectionScope: "execution",
  719. selectionFallback: {
  720. providerId: highspeedProviderId,
  721. rules: [
  722. { reason: "highspeed_card_expired", providerErrorCode: "3402" },
  723. { reason: "highspeed_request_failed" },
  724. ],
  725. },
  726. },
  727. });
  728. expect(result.response).toBe("continued with the session model");
  729. expect(requests).toEqual([
  730. {
  731. providerId: highspeedProviderId,
  732. modelId: "GLM-5.3",
  733. retryBudget: ModelRetryBudget.SingleAttempt,
  734. },
  735. { providerId: "user-provider", modelId: "user-model", retryBudget: ModelRetryBudget.Default },
  736. ]);
  737. const fallbackEvent = (await eventStore.getEvents(sessionId)).find(
  738. (event) => event.type === SessionEventType.TurnExecutionModelFallback,
  739. );
  740. expect(fallbackEvent?.payload).toMatchObject({
  741. inputId: "command-highspeed-401",
  742. reason: "highspeed_request_failed",
  743. fromModelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  744. toModelSelection: { providerId: "user-provider", modelId: "user-model" },
  745. });
  746. });
  747. it("falls back to the declared target when the runtime has no resident Session Selection", async () => {
  748. // 回归(2026-10-09 日志复盘):冷恢复落在 Registry 刚就绪、账号权益未解析的窗口时,持久化的会话选择
  749. // 校验失败不绑定;之后只发加速轮不会再绑定,3402 时退回目标为空,整轮按 "highspeed card is invalid"
  750. // 失败弹错。发起方抽卡时知道原模型,现在随 selectionFallback.target 下发,退回不再依赖 runtime 常驻选择。
  751. const sessionId = createSessionId("runtime-execution-selection-fallback-declared-target");
  752. const eventStore = createTestSessionEventStore();
  753. const highspeedProviderId = "account:bigmodel-highspeed-card";
  754. const target = { providerId: "account:bigmodel-team-coding-plan", modelId: "GLM-5.3" };
  755. const requests: Array<{ modelId: string; providerId: string }> = [];
  756. const warn = vi.fn();
  757. const runtime = createTestAgentRuntime(
  758. sessionId,
  759. {
  760. modelSelection: createTestModelSelection("user-provider/user-model"),
  761. titleGeneration: { enabled: false },
  762. workingDirectory: "/workspace/project",
  763. },
  764. {
  765. eventStore,
  766. logger: createWarnCapturingLogger(warn),
  767. modelFactory: createCardExpiryModelFactory(highspeedProviderId, requests),
  768. },
  769. );
  770. // 复现恢复竞态之后的 runtime:没有常驻选择。
  771. runtime.setSessionModelSelection(undefined);
  772. const result = await runtime.executeTurn("continue after expiry", undefined, {
  773. inputId: "command-highspeed-expired-unbound",
  774. intent: {
  775. sourceCommandId: "command-highspeed-expired-unbound",
  776. kind: "sendText",
  777. requestedDelivery: "start-now",
  778. modelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  779. },
  780. modelExecution: {
  781. selectionScope: "execution",
  782. selectionFallback: {
  783. providerId: highspeedProviderId,
  784. rules: cardExpiryFallbackRules,
  785. target,
  786. },
  787. },
  788. });
  789. expect(result.response).toBe("continued with the original model");
  790. expect(requests).toEqual([{ providerId: highspeedProviderId, modelId: "GLM-5.3" }, target]);
  791. const fallbackEvent = (await eventStore.getEvents(sessionId)).find(
  792. (event) => event.type === SessionEventType.TurnExecutionModelFallback,
  793. );
  794. expect(fallbackEvent?.payload).toMatchObject({
  795. inputId: "command-highspeed-expired-unbound",
  796. reason: "highspeed_card_expired",
  797. fromModelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  798. toModelSelection: target,
  799. });
  800. // 退回只作用于本轮,不借机改写会话常驻选择。
  801. expect(runtime.getSessionModelSelection()).toBeUndefined();
  802. expect(warn).toHaveBeenCalledWith(
  803. expect.any(String),
  804. expect.objectContaining({
  805. event: "model.execution_selection.fallback",
  806. toSource: "declared_target",
  807. toProviderId: target.providerId,
  808. providerErrorCode: "3402",
  809. }),
  810. );
  811. });
  812. it("prefers the declared target over the resident Session Selection", async () => {
  813. // target 是发起方抽卡时 Composer 的提交选择,比 runtime 内存里的常驻选择更接近用户此刻的意图;
  814. // 正常情况下两者相同,不同则以发起方为准。
  815. const sessionId = createSessionId("runtime-execution-selection-fallback-target-first");
  816. const eventStore = createTestSessionEventStore();
  817. const highspeedProviderId = "account:bigmodel-highspeed-card";
  818. const target = { providerId: "account:bigmodel-team-coding-plan", modelId: "GLM-5.3" };
  819. const requests: Array<{ modelId: string; providerId: string }> = [];
  820. const runtime = createTestAgentRuntime(
  821. sessionId,
  822. {
  823. modelSelection: createTestModelSelection("user-provider/user-model"),
  824. titleGeneration: { enabled: false },
  825. workingDirectory: "/workspace/project",
  826. },
  827. { eventStore, modelFactory: createCardExpiryModelFactory(highspeedProviderId, requests) },
  828. );
  829. await runtime.executeTurn("continue after expiry", undefined, {
  830. intent: {
  831. sourceCommandId: "command-highspeed-expired-target-first",
  832. kind: "sendText",
  833. requestedDelivery: "start-now",
  834. modelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  835. },
  836. modelExecution: {
  837. selectionScope: "execution",
  838. selectionFallback: {
  839. providerId: highspeedProviderId,
  840. rules: cardExpiryFallbackRules,
  841. target,
  842. },
  843. },
  844. });
  845. expect(requests).toEqual([{ providerId: highspeedProviderId, modelId: "GLM-5.3" }, target]);
  846. expect(runtime.getSessionModelSelection()).toMatchObject({
  847. providerId: "user-provider",
  848. modelId: "user-model",
  849. });
  850. });
  851. it("skips a declared target the model factory cannot resolve and falls back to the Session Selection", async () => {
  852. const sessionId = createSessionId("runtime-execution-selection-fallback-target-unresolvable");
  853. const eventStore = createTestSessionEventStore();
  854. const highspeedProviderId = "account:bigmodel-highspeed-card";
  855. const requests: Array<{ modelId: string; providerId: string }> = [];
  856. const warn = vi.fn();
  857. const baseFactory = createCardExpiryModelFactory(highspeedProviderId, requests);
  858. const runtime = createTestAgentRuntime(
  859. sessionId,
  860. {
  861. modelSelection: createTestModelSelection("user-provider/user-model"),
  862. titleGeneration: { enabled: false },
  863. workingDirectory: "/workspace/project",
  864. },
  865. {
  866. eventStore,
  867. logger: createWarnCapturingLogger(warn),
  868. modelFactory: (factoryInput) => {
  869. // 模拟目标 provider 不在当前 Registry:建模抛错只能跳过该候选,不能替换真实的加速失败原因。
  870. if (factoryInput.selection.providerId === "ghost-provider") {
  871. throw new Error("Provider Registry 中不存在 Provider: ghost-provider");
  872. }
  873. return baseFactory(factoryInput);
  874. },
  875. },
  876. );
  877. const result = await runtime.executeTurn("continue after expiry", undefined, {
  878. intent: {
  879. sourceCommandId: "command-highspeed-expired-ghost-target",
  880. kind: "sendText",
  881. requestedDelivery: "start-now",
  882. modelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  883. },
  884. modelExecution: {
  885. selectionScope: "execution",
  886. selectionFallback: {
  887. providerId: highspeedProviderId,
  888. rules: cardExpiryFallbackRules,
  889. target: { providerId: "ghost-provider", modelId: "GLM-5.3" },
  890. },
  891. },
  892. });
  893. expect(result.response).toBe("continued with the original model");
  894. expect(requests).toEqual([
  895. { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  896. { providerId: "user-provider", modelId: "user-model" },
  897. ]);
  898. expect(warn).toHaveBeenCalledWith(
  899. expect.any(String),
  900. expect.objectContaining({
  901. event: "model.execution_selection.fallback",
  902. toSource: "session_selection",
  903. skippedCandidates: [
  904. expect.objectContaining({ source: "declared_target", providerId: "ghost-provider" }),
  905. ],
  906. }),
  907. );
  908. });
  909. it("fails with the real execution error when neither a declared target nor a resident Session Selection resolves", async () => {
  910. // 无处可退时不能用建模错误或泛化文案掩埋根因,但必须留痕:过去这个分支完全静默。
  911. const sessionId = createSessionId("runtime-execution-selection-fallback-unavailable");
  912. const eventStore = createTestSessionEventStore();
  913. const highspeedProviderId = "account:bigmodel-highspeed-card";
  914. const requests: Array<{ modelId: string; providerId: string }> = [];
  915. const warn = vi.fn();
  916. const runtime = createTestAgentRuntime(
  917. sessionId,
  918. {
  919. modelSelection: createTestModelSelection("user-provider/user-model"),
  920. titleGeneration: { enabled: false },
  921. workingDirectory: "/workspace/project",
  922. },
  923. {
  924. eventStore,
  925. logger: createWarnCapturingLogger(warn),
  926. modelFactory: createCardExpiryModelFactory(highspeedProviderId, requests),
  927. },
  928. );
  929. runtime.setSessionModelSelection(undefined);
  930. const failure = (await runtime
  931. .executeTurn("continue after expiry", undefined, {
  932. intent: {
  933. sourceCommandId: "command-highspeed-expired-nowhere",
  934. kind: "sendText",
  935. requestedDelivery: "start-now",
  936. modelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  937. },
  938. modelExecution: {
  939. selectionScope: "execution",
  940. selectionFallback: { providerId: highspeedProviderId, rules: cardExpiryFallbackRules },
  941. },
  942. })
  943. .then(
  944. () => undefined,
  945. (error: unknown) => error,
  946. )) as (Error & { cause?: unknown }) | undefined;
  947. expect(failure).toBeInstanceOf(Error);
  948. const causeMessage = failure?.cause instanceof Error ? failure.cause.message : undefined;
  949. expect([failure?.message, causeMessage]).toContain("highspeed card is invalid");
  950. expect(requests).toEqual([{ providerId: highspeedProviderId, modelId: "GLM-5.3" }]);
  951. const fallbackEvents = (await eventStore.getEvents(sessionId)).filter(
  952. (event) => event.type === SessionEventType.TurnExecutionModelFallback,
  953. );
  954. expect(fallbackEvents).toHaveLength(0);
  955. expect(warn).toHaveBeenCalledWith(
  956. expect.any(String),
  957. expect.objectContaining({
  958. event: "model.execution_selection.fallback_unavailable",
  959. hasDeclaredTarget: false,
  960. hasSessionSelection: false,
  961. providerErrorCode: "3402",
  962. }),
  963. );
  964. });
  965. it("does not fall back when local streaming event persistence fails", async () => {
  966. // Bug 根因:selectionFallback 的无错误码规则曾把 stream 消费期间的本地落库异常也当成 provider 失败,
  967. // 不仅掩埋真实存储故障,还会错误地向原模型再发一次请求。
  968. const sessionId = createSessionId("runtime-execution-selection-local-persistence-failure");
  969. const eventStore = createTestSessionEventStore();
  970. const appendEvent = eventStore.append.bind(eventStore);
  971. eventStore.append = vi.fn(async (event) => {
  972. if (event.type === SessionEventType.ModelStreaming) {
  973. throw new Error("event store append failed");
  974. }
  975. return appendEvent(event);
  976. });
  977. const highspeedProviderId = "account:zai-highspeed-card";
  978. const streamedProviders: string[] = [];
  979. const runtime = createTestAgentRuntime(
  980. sessionId,
  981. {
  982. modelSelection: createTestModelSelection("user-provider/user-model"),
  983. modelStreaming: "on",
  984. titleGeneration: { enabled: false },
  985. workingDirectory: "/workspace/project",
  986. },
  987. {
  988. eventStore,
  989. modelFactory: createTestModelFactory({
  990. async *streamText(_request, observation) {
  991. streamedProviders.push(String(observation.model.providerId));
  992. yield { id: "text-1", type: "text_start" };
  993. yield { id: "text-1", text: "provider output", type: "text_delta" };
  994. yield { id: "text-1", type: "text_end" };
  995. yield {
  996. finishReason: "stop",
  997. type: "finish",
  998. usage: { inputTokens: 1, outputTokens: 2, totalTokens: 3 },
  999. };
  1000. },
  1001. }),
  1002. },
  1003. );
  1004. const failure = (await runtime
  1005. .executeTurn("persist this stream", undefined, {
  1006. inputId: "command-highspeed-local-persistence-failure",
  1007. intent: {
  1008. sourceCommandId: "command-highspeed-local-persistence-failure",
  1009. kind: "sendText",
  1010. requestedDelivery: "start-now",
  1011. modelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  1012. },
  1013. modelExecution: {
  1014. selectionScope: "execution",
  1015. selectionFallback: {
  1016. providerId: highspeedProviderId,
  1017. rules: [{ reason: "highspeed_request_failed" }],
  1018. },
  1019. },
  1020. })
  1021. .then(
  1022. () => undefined,
  1023. (error: unknown) => error,
  1024. )) as (Error & { cause?: unknown }) | undefined;
  1025. expect(failure).toBeInstanceOf(Error);
  1026. const causeMessage = failure?.cause instanceof Error ? failure.cause.message : undefined;
  1027. expect([failure?.message, causeMessage]).toContain("event store append failed");
  1028. expect(streamedProviders).toEqual([highspeedProviderId]);
  1029. const fallbackEvents = (await eventStore.getEvents(sessionId)).filter(
  1030. (event) => event.type === SessionEventType.TurnExecutionModelFallback,
  1031. );
  1032. expect(fallbackEvents).toHaveLength(0);
  1033. });
  1034. it("does not retry the accelerated stream when a matched fallback has no resolvable target", async () => {
  1035. // 无处可退已是终止边界;若继续进入通用 stream recovery,会在同一个失败加速端点重复请求。
  1036. const sessionId = createSessionId("runtime-execution-selection-stream-fallback-unavailable");
  1037. const eventStore = createTestSessionEventStore();
  1038. const highspeedProviderId = "account:zai-highspeed-card";
  1039. const streamedProviders: string[] = [];
  1040. const runtime = createTestAgentRuntime(
  1041. sessionId,
  1042. {
  1043. modelSelection: createTestModelSelection("user-provider/user-model"),
  1044. modelStreaming: "on",
  1045. titleGeneration: { enabled: false },
  1046. workingDirectory: "/workspace/project",
  1047. },
  1048. {
  1049. eventStore,
  1050. modelFactory: createTestModelFactory({
  1051. async *streamText(_request, observation) {
  1052. const providerId = String(observation.model.providerId);
  1053. streamedProviders.push(providerId);
  1054. yield { id: "text-1", type: "text_start" };
  1055. yield { id: "text-1", text: "partial accelerated output", type: "text_delta" };
  1056. throw Object.assign(new Error("accelerated stream failed"), {
  1057. code: "model_request_failed",
  1058. context: {
  1059. providerId,
  1060. modelId: "GLM-5.3",
  1061. reason: "network_error",
  1062. retryable: true,
  1063. source: "network",
  1064. },
  1065. name: "AiSdkModelAdapterError",
  1066. });
  1067. },
  1068. }),
  1069. },
  1070. );
  1071. runtime.setSessionModelSelection(undefined);
  1072. const failure = (await runtime
  1073. .executeTurn("stream without fallback target", undefined, {
  1074. inputId: "command-highspeed-stream-no-target",
  1075. intent: {
  1076. sourceCommandId: "command-highspeed-stream-no-target",
  1077. kind: "sendText",
  1078. requestedDelivery: "start-now",
  1079. modelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  1080. },
  1081. modelExecution: {
  1082. selectionScope: "execution",
  1083. selectionFallback: {
  1084. providerId: highspeedProviderId,
  1085. rules: [{ reason: "highspeed_request_failed" }],
  1086. },
  1087. },
  1088. })
  1089. .then(
  1090. () => undefined,
  1091. (error: unknown) => error,
  1092. )) as (Error & { cause?: unknown }) | undefined;
  1093. expect(failure).toBeInstanceOf(Error);
  1094. const causeMessage = failure?.cause instanceof Error ? failure.cause.message : undefined;
  1095. expect([failure?.message, causeMessage]).toContain("accelerated stream failed");
  1096. expect(streamedProviders).toEqual([highspeedProviderId]);
  1097. const fallbackEvents = (await eventStore.getEvents(sessionId)).filter(
  1098. (event) => event.type === SessionEventType.TurnExecutionModelFallback,
  1099. );
  1100. expect(fallbackEvents).toHaveLength(0);
  1101. });
  1102. it("falls back only once: a session model failure after the fallback fails the turn", async () => {
  1103. const sessionId = createSessionId("runtime-execution-selection-fallback-once");
  1104. const eventStore = createTestSessionEventStore();
  1105. const highspeedProviderId = "account:zai-highspeed-card";
  1106. const providers: string[] = [];
  1107. const runtime = createTestAgentRuntime(
  1108. sessionId,
  1109. {
  1110. modelSelection: createTestModelSelection("user-provider/user-model"),
  1111. titleGeneration: { enabled: false },
  1112. workingDirectory: "/workspace/project",
  1113. },
  1114. {
  1115. eventStore,
  1116. modelFactory: createTestModelFactory({
  1117. async generateText(_request, observation) {
  1118. const providerId = String(observation.model.providerId);
  1119. providers.push(providerId);
  1120. throw Object.assign(new Error("Provider returned a server error."), {
  1121. code: "model_request_failed",
  1122. context: {
  1123. providerId,
  1124. modelId: String(observation.model.modelId),
  1125. reason: "server_error",
  1126. retryable: true,
  1127. source: "provider",
  1128. statusCode: 503,
  1129. },
  1130. name: "AiSdkModelAdapterError",
  1131. });
  1132. },
  1133. }),
  1134. },
  1135. );
  1136. await expect(
  1137. runtime.executeTurn("both models fail", undefined, {
  1138. inputId: "command-highspeed-503",
  1139. intent: {
  1140. sourceCommandId: "command-highspeed-503",
  1141. kind: "sendText",
  1142. requestedDelivery: "start-now",
  1143. modelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  1144. },
  1145. modelExecution: {
  1146. selectionScope: "execution",
  1147. selectionFallback: {
  1148. providerId: highspeedProviderId,
  1149. rules: [{ reason: "highspeed_request_failed" }],
  1150. },
  1151. },
  1152. }),
  1153. ).rejects.toThrow();
  1154. // 加速模型失败一次即退回;退回后的会话模型再失败按真实错误整轮失败,不再二次降级。
  1155. expect(providers).toEqual([highspeedProviderId, "user-provider"]);
  1156. const fallbackEvents = (await eventStore.getEvents(sessionId)).filter(
  1157. (event) => event.type === SessionEventType.TurnExecutionModelFallback,
  1158. );
  1159. expect(fallbackEvents).toHaveLength(1);
  1160. });
  1161. it("falls back before same-model stream recovery when the execution stream fails after visible output", async () => {
  1162. // 退回必须先于 stream recovery:否则可见输出后的瞬态失败会先在加速模型上重试到预算耗尽。
  1163. const sessionId = createSessionId("runtime-execution-selection-stream-fallback");
  1164. const eventStore = createTestSessionEventStore();
  1165. const highspeedProviderId = "account:zai-highspeed-card";
  1166. const streamedProviders: string[] = [];
  1167. const runtime = createTestAgentRuntime(
  1168. sessionId,
  1169. {
  1170. modelSelection: createTestModelSelection("user-provider/user-model"),
  1171. modelStreaming: "on",
  1172. titleGeneration: { enabled: false },
  1173. workingDirectory: "/workspace/project",
  1174. },
  1175. {
  1176. eventStore,
  1177. modelFactory: createTestModelFactory({
  1178. async generateText() {
  1179. throw new Error("streaming runtime must not call generateText");
  1180. },
  1181. async *streamText(_request, observation) {
  1182. const providerId = String(observation.model.providerId);
  1183. streamedProviders.push(providerId);
  1184. yield { id: "text-1", type: "text_start" };
  1185. if (providerId === highspeedProviderId) {
  1186. yield { id: "text-1", text: "partial accelerated output", type: "text_delta" };
  1187. throw Object.assign(new Error("Network connection failed for the provider request."), {
  1188. code: "model_request_failed",
  1189. context: {
  1190. providerId,
  1191. modelId: "GLM-5.3",
  1192. reason: "network_error",
  1193. retryable: true,
  1194. source: "network",
  1195. },
  1196. name: "AiSdkModelAdapterError",
  1197. });
  1198. }
  1199. yield { id: "text-1", text: "continued with the session model", type: "text_delta" };
  1200. yield { id: "text-1", type: "text_end" };
  1201. yield {
  1202. finishReason: "stop",
  1203. type: "finish",
  1204. usage: { inputTokens: 1, outputTokens: 2, totalTokens: 3 },
  1205. };
  1206. },
  1207. }),
  1208. },
  1209. );
  1210. const result = await runtime.executeTurn("stream fails mid-way", undefined, {
  1211. inputId: "command-highspeed-stream",
  1212. intent: {
  1213. sourceCommandId: "command-highspeed-stream",
  1214. kind: "sendText",
  1215. requestedDelivery: "start-now",
  1216. modelSelection: { providerId: highspeedProviderId, modelId: "GLM-5.3" },
  1217. },
  1218. modelExecution: {
  1219. selectionScope: "execution",
  1220. selectionFallback: {
  1221. providerId: highspeedProviderId,
  1222. rules: [{ reason: "highspeed_request_failed" }],
  1223. },
  1224. },
  1225. });
  1226. expect(result.response).toBe("continued with the session model");
  1227. // 加速模型只开流一次,没有同模型重试;随后直接由会话模型接管。
  1228. expect(streamedProviders).toEqual([highspeedProviderId, "user-provider"]);
  1229. const events = await eventStore.getEvents(sessionId);
  1230. expect(
  1231. events.filter((event) => event.type === SessionEventType.TurnExecutionModelFallback),
  1232. ).toHaveLength(1);
  1233. });
  1234. it("preserves an explicit source-less model boundary in ModelSelected", async () => {
  1235. const sessionId = createSessionId("runtime-model-selection-source-less-boundary");
  1236. const eventStore = createTestSessionEventStore();
  1237. const runtime = createTestAgentRuntime(sessionId, {}, { eventStore });
  1238. await runtime.emitModelSelected({
  1239. modelSelection: {
  1240. providerId: createModelProviderId("child-provider"),
  1241. modelId: createModelId("child-model"),
  1242. },
  1243. previousModelSelection: null,
  1244. traceContext: { traceId: "trace-runtime-model-selection-source-less" } as never,
  1245. });
  1246. const selected = (await eventStore.getEvents(sessionId)).find(
  1247. (event) => event.type === SessionEventType.ModelSelected,
  1248. );
  1249. expect(selected?.payload).toMatchObject({
  1250. previousModelSelection: null,
  1251. modelSelection: {
  1252. providerId: "child-provider",
  1253. modelId: "child-model",
  1254. },
  1255. });
  1256. });
  1257. });