runtime-model-selection.test.ts 65 KB

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