runtime-model-selection.test.ts 62 KB

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