runtime-model-lifecycle.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. ModelErrorCode,
  4. SessionEventType,
  5. createModelId,
  6. createModelProviderId,
  7. createSessionId,
  8. type Model,
  9. type ModelRequest,
  10. type ModelResult,
  11. type ModelSelection,
  12. } from "@zcode/contracts";
  13. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  14. import { createTestModelSelection } from "./test-model-selection.js";
  15. import { createToolRegistry } from "../src/tool/registry.js";
  16. import { createTestSessionEventStore } from "./test-event-store.js";
  17. import { createTestModelFormatProperties } from "./test-runtime-model.js";
  18. import { createTestModelFactory } from "./test-runtime-model.js";
  19. describe("Agent Runtime Model lifecycle", () => {
  20. it("does not fall back to the Adapter when the explicit ModelFactory is unavailable", async () => {
  21. const eventStore = createTestSessionEventStore();
  22. const modelSelection = createTestModelSelection("test/adapter-only-model");
  23. const generateText = vi.fn(async () =>
  24. result(modelSelection, { finishReason: "stop", text: "adapter fallback" }),
  25. );
  26. const runtime = createTestAgentRuntime(
  27. createSessionId("adapter-fallback-is-forbidden"),
  28. {
  29. mode: "build",
  30. modelSelection: createTestModelSelection(modelSelection),
  31. workingDirectory: "/tmp/zcode-adapter-fallback-is-forbidden",
  32. },
  33. {
  34. eventStore,
  35. modelFactory: () => {
  36. throw new Error("test model unavailable");
  37. },
  38. modelAdapter: {
  39. generateText,
  40. async *streamText() {
  41. throw new Error("not used");
  42. },
  43. },
  44. } as never,
  45. );
  46. await expect(runtime.executeTurn("must use a ModelFactory")).rejects.toThrow();
  47. expect(generateText).not.toHaveBeenCalled();
  48. const outcomes = (await eventStore.getEvents(runtime.sessionId)).filter(
  49. (event) => event.type === SessionEventType.TurnError,
  50. );
  51. expect(outcomes).toHaveLength(1);
  52. expect(JSON.stringify(outcomes[0])).toContain("test model unavailable");
  53. expect(runtime.getSessionModelSelection()).toEqual(modelSelection);
  54. });
  55. it("creates the Loop Model from the admitted Submission selection and applies its mode", async () => {
  56. const createdModelSelections: Array<ModelSelection> = [];
  57. const runtime = createTestAgentRuntime(
  58. createSessionId("submission-model-lifecycle"),
  59. {
  60. mode: "build",
  61. modelSelection: createTestModelSelection(createTestModelSelection("test/model-a")),
  62. workingDirectory: "/tmp/zcode-submission-model-lifecycle",
  63. },
  64. {
  65. eventStore: createTestSessionEventStore(),
  66. modelFactory: ((input: { selection: ModelSelection }) => {
  67. const modelSelection = modelSelectionFromSelection(input.selection);
  68. createdModelSelections.push(modelSelection);
  69. return createLifecycleTestModel(modelSelection);
  70. }) as never,
  71. },
  72. );
  73. await runtime.executeTurn("use the submitted model", undefined, {
  74. intent: {
  75. sourceCommandId: "submission-command",
  76. kind: "sendText",
  77. requestedDelivery: "start-now",
  78. modelSelection: {
  79. providerId: "other-provider",
  80. modelId: "model-b",
  81. options: { reasoningLevel: "high" },
  82. },
  83. mode: "plan",
  84. },
  85. });
  86. expect(createdModelSelections).toEqual([
  87. expect.objectContaining({
  88. providerId: "other-provider",
  89. modelId: "model-b",
  90. options: { reasoningLevel: "high" },
  91. }),
  92. ]);
  93. expect(runtime.getSessionModelSelection()).toMatchObject({
  94. providerId: "other-provider",
  95. modelId: "model-b",
  96. options: { reasoningLevel: "high" },
  97. });
  98. expect(runtime.getMode()).toBe("build");
  99. expect(runtime.getPlanEnabled()).toBe(true);
  100. });
  101. it("keeps an execution-scoped model isolated from the persistent Submission selection", async () => {
  102. const eventStore = createTestSessionEventStore();
  103. const createdModelIds: string[] = [];
  104. const createdRequestAuthSources: unknown[] = [];
  105. const secret = "turn-only-key-do-not-persist";
  106. const requestAuthSource = {
  107. resolve: vi.fn().mockResolvedValue({ apiKey: secret }),
  108. };
  109. const runtime = createTestAgentRuntime(
  110. createSessionId("temporary-execution-model-lifecycle"),
  111. {
  112. mode: "build",
  113. modelSelection: createTestModelSelection(createTestModelSelection("test/session-model")),
  114. workingDirectory: "/tmp/zcode-temporary-execution-model-lifecycle",
  115. },
  116. {
  117. eventStore,
  118. modelFactory: ((input: {
  119. selection: ModelSelection;
  120. requestDependencies?: { requestAuth?: { source?: unknown } };
  121. }) => {
  122. const modelSelection = modelSelectionFromSelection(input.selection);
  123. createdModelIds.push(String(modelSelection.modelId));
  124. createdRequestAuthSources.push(input.requestDependencies?.requestAuth?.source);
  125. return createLifecycleTestModel(modelSelection);
  126. }) as never,
  127. },
  128. );
  129. await runtime.executeTurn("temporary task", undefined, {
  130. intent: {
  131. sourceCommandId: "temporary-command",
  132. kind: "sendText",
  133. requestedDelivery: "start-now",
  134. modelSelection: { providerId: "temporary", modelId: "idle-model" },
  135. },
  136. modelExecution: {
  137. selectionScope: "execution",
  138. requestDependencies: { requestAuth: { source: requestAuthSource } },
  139. },
  140. });
  141. await runtime.executeTurn("ordinary task");
  142. expect(createdModelIds).toEqual(["idle-model", "session-model"]);
  143. expect(createdRequestAuthSources).toEqual([requestAuthSource, undefined]);
  144. expect(runtime.getSessionModelSelection()).toMatchObject({
  145. providerId: "test",
  146. modelId: "session-model",
  147. });
  148. expect(
  149. JSON.stringify(
  150. await eventStore.getEvents(createSessionId("temporary-execution-model-lifecycle")),
  151. ),
  152. ).not.toContain(secret);
  153. });
  154. it("keeps one Model across all steps of a loop and creates a new Model for the next turn", async () => {
  155. const registry = createToolRegistry();
  156. registry.register({
  157. inputSchema: {},
  158. metadata: {
  159. concurrentSafe: true,
  160. destructive: false,
  161. name: "ReadMarker",
  162. needsApproval: false,
  163. readOnly: true,
  164. riskLevel: "low",
  165. sideEffectScope: "none",
  166. },
  167. handler: async () => "marker",
  168. });
  169. let runtime: ReturnType<typeof createTestAgentRuntime>;
  170. const modelFactory = vi.fn((input: { selection: ModelSelection }) => {
  171. const modelSelection = modelSelectionFromSelection(input.selection);
  172. let calls = 0;
  173. const model: Model = {
  174. providerId: modelSelection.providerId,
  175. modelId: modelSelection.modelId,
  176. properties: {
  177. contextWindow: 128_000,
  178. ...createTestModelFormatProperties(),
  179. supportsMidConversationSystem: false,
  180. supportsNativeWebSearch: false,
  181. supportsJsonSchemaOutput: true,
  182. supportsToolCall: true,
  183. },
  184. optionSpecs: {
  185. maxOutputTokens: { max: 8_000 },
  186. },
  187. options: { maxOutputTokens: 8_000 },
  188. bind() {
  189. return this;
  190. },
  191. async generateText(request: ModelRequest): Promise<ModelResult> {
  192. calls += 1;
  193. if (modelSelection.modelId === "model-a" && calls === 1) {
  194. runtime.setSessionModelSelection(
  195. createTestModelSelection(createTestModelSelection("test/model-b")),
  196. );
  197. return result(modelSelection, {
  198. finishReason: "tool-calls",
  199. toolCalls: [{ id: "read-marker", name: "ReadMarker", input: {} }],
  200. });
  201. }
  202. return result(modelSelection, { finishReason: "stop", text: "done" });
  203. },
  204. streamText() {
  205. throw new Error("not used");
  206. },
  207. };
  208. return model;
  209. });
  210. runtime = createTestAgentRuntime(
  211. createSessionId("model-lifecycle"),
  212. {
  213. mode: "build",
  214. modelSelection: createTestModelSelection(createTestModelSelection("test/model-a")),
  215. workingDirectory: "/tmp/zcode-model-lifecycle",
  216. },
  217. {
  218. eventStore: createTestSessionEventStore(),
  219. modelFactory: modelFactory as never,
  220. toolRegistry: registry,
  221. },
  222. );
  223. await runtime.executeTurn("first");
  224. await runtime.executeTurn("second");
  225. expect(modelFactory.mock.calls.map(([input]) => input.selection.modelId)).toEqual([
  226. "model-a",
  227. "model-b",
  228. ]);
  229. });
  230. it("captures model and context before async turn setup can observe a model switch", async () => {
  231. const registry = createToolRegistry();
  232. registry.register({
  233. inputSchema: {},
  234. metadata: {
  235. concurrentSafe: true,
  236. destructive: false,
  237. name: "ReadBeforeModelCapture",
  238. needsApproval: false,
  239. readOnly: true,
  240. riskLevel: "low",
  241. sideEffectScope: "none",
  242. },
  243. handler: async () => "marker",
  244. });
  245. let runtime: ReturnType<typeof createTestAgentRuntime>;
  246. const requests: Array<{ modelId: string; text: string }> = [];
  247. const modelFactory = vi.fn((input: { selection: ModelSelection }) => {
  248. const modelSelection = modelSelectionFromSelection(input.selection);
  249. let calls = 0;
  250. const model: Model = {
  251. providerId: modelSelection.providerId,
  252. modelId: modelSelection.modelId,
  253. properties: {
  254. contextWindow: 128_000,
  255. ...createTestModelFormatProperties(),
  256. supportsMidConversationSystem: false,
  257. supportsNativeWebSearch: false,
  258. supportsJsonSchemaOutput: true,
  259. supportsToolCall: true,
  260. },
  261. optionSpecs: {
  262. maxOutputTokens: { max: 8_000 },
  263. },
  264. options: { maxOutputTokens: 8_000 },
  265. bind() {
  266. return this;
  267. },
  268. async generateText(request: ModelRequest): Promise<ModelResult> {
  269. calls += 1;
  270. requests.push({
  271. modelId: modelSelection.modelId,
  272. text: JSON.stringify(request.messages),
  273. });
  274. if (modelSelection.modelId === "model-a" && calls === 1) {
  275. return result(modelSelection, {
  276. finishReason: "tool-calls",
  277. toolCalls: [
  278. {
  279. id: "read-before-model-capture",
  280. name: "ReadBeforeModelCapture",
  281. input: {},
  282. },
  283. ],
  284. });
  285. }
  286. return result(modelSelection, { finishReason: "stop", text: "done" });
  287. },
  288. streamText() {
  289. throw new Error("not used");
  290. },
  291. };
  292. return model;
  293. });
  294. runtime = createTestAgentRuntime(
  295. createSessionId("model-context-before-capture"),
  296. {
  297. mode: "build",
  298. modelSelection: createTestModelSelection(createTestModelSelection("test/model-a")),
  299. workingDirectory: "/tmp/zcode-model-context-before-capture",
  300. },
  301. {
  302. eventStore: createTestSessionEventStore(),
  303. modelFactory: modelFactory as never,
  304. toolRegistry: registry,
  305. },
  306. );
  307. let switched = false;
  308. const unsubscribe = runtime.subscribeEvents({
  309. onSessionEvent(event) {
  310. if (!switched && event.type === SessionEventType.TurnStarted) {
  311. switched = true;
  312. runtime.setSessionModelSelection(
  313. createTestModelSelection(createTestModelSelection("test/model-b")),
  314. );
  315. runtime.updateConfig({
  316. language: "zh-CN",
  317. outputStyle: {
  318. name: "Learning",
  319. prompt: "Explain tradeoffs while solving the task.",
  320. },
  321. });
  322. }
  323. },
  324. });
  325. try {
  326. await runtime.executeTurn("first");
  327. await runtime.executeTurn("second");
  328. } finally {
  329. unsubscribe();
  330. }
  331. expect(modelFactory.mock.calls.map(([input]) => input.selection.modelId)).toEqual([
  332. "model-a",
  333. "model-b",
  334. ]);
  335. expect(requests.map((request) => request.modelId)).toEqual(["model-a", "model-a", "model-b"]);
  336. expect(requests[0]?.text).toContain("model named test/model-a");
  337. expect(requests[0]?.text).not.toContain("Learning output style is active");
  338. expect(requests[1]?.text).toContain("model named test/model-a");
  339. expect(requests[1]?.text).not.toContain("model named test/model-b");
  340. expect(requests[1]?.text).not.toContain("Learning output style is active");
  341. expect(requests[2]?.text).toContain("model named test/model-b");
  342. expect(requests[2]?.text).toContain("Learning output style is active");
  343. });
  344. it("keeps the execution-scoped Model while permission approval pauses and resumes the loop", async () => {
  345. const registry = createToolRegistry();
  346. const handler = vi.fn(async () => "write-ok");
  347. registry.register({
  348. inputSchema: {},
  349. metadata: {
  350. concurrentSafe: false,
  351. destructive: false,
  352. name: "WriteMarker",
  353. needsApproval: true,
  354. readOnly: false,
  355. riskLevel: "medium",
  356. sideEffectScope: "workspace",
  357. },
  358. handler,
  359. });
  360. let approve!: () => void;
  361. const permissionGate = new Promise<{ decision: "allow" }>((resolve) => {
  362. approve = () => resolve({ decision: "allow" });
  363. });
  364. const permissionBroker = {
  365. requestPermission: vi.fn(() => permissionGate),
  366. };
  367. const requestAuthSource = {
  368. resolve: vi.fn().mockResolvedValue({ apiKey: "permission-turn-key" }),
  369. };
  370. const modelCalls: string[] = [];
  371. const requestAuthSources: unknown[] = [];
  372. const modelFactory = vi.fn(
  373. (input: {
  374. selection: ModelSelection;
  375. requestDependencies?: { requestAuth?: { source?: unknown } };
  376. }) => {
  377. const modelSelection = modelSelectionFromSelection(input.selection);
  378. requestAuthSources.push(input.requestDependencies?.requestAuth?.source);
  379. let calls = 0;
  380. return {
  381. ...createLifecycleTestModel(modelSelection),
  382. async generateText(): Promise<ModelResult> {
  383. calls += 1;
  384. modelCalls.push(`${modelSelection.modelId}:${calls}`);
  385. return calls === 1
  386. ? result(modelSelection, {
  387. finishReason: "tool-calls",
  388. toolCalls: [{ id: "write-marker", name: "WriteMarker", input: {} }],
  389. })
  390. : result(modelSelection, { finishReason: "stop", text: "done" });
  391. },
  392. } satisfies Model;
  393. },
  394. );
  395. const runtime = createTestAgentRuntime(
  396. createSessionId("execution-model-permission-continuation"),
  397. {
  398. mode: "build",
  399. modelSelection: createTestModelSelection(createTestModelSelection("test/session-model")),
  400. workingDirectory: "/tmp/zcode-execution-model-permission",
  401. },
  402. {
  403. eventStore: createTestSessionEventStore(),
  404. modelFactory: modelFactory as never,
  405. permissionBroker,
  406. toolRegistry: registry,
  407. },
  408. );
  409. const executing = runtime.executeTurn("permission task", undefined, {
  410. intent: {
  411. sourceCommandId: "permission-command",
  412. kind: "sendText",
  413. requestedDelivery: "start-now",
  414. modelSelection: { providerId: "temporary", modelId: "idle-model" },
  415. },
  416. modelExecution: {
  417. selectionScope: "execution",
  418. requestDependencies: { requestAuth: { source: requestAuthSource } },
  419. },
  420. });
  421. await vi.waitFor(() => expect(permissionBroker.requestPermission).toHaveBeenCalledTimes(1));
  422. expect(modelFactory).toHaveBeenCalledTimes(1);
  423. expect(modelCalls).toEqual(["idle-model:1"]);
  424. expect(requestAuthSources).toEqual([requestAuthSource]);
  425. approve();
  426. await executing;
  427. expect(handler).toHaveBeenCalledTimes(1);
  428. expect(modelFactory).toHaveBeenCalledTimes(1);
  429. expect(modelCalls).toEqual(["idle-model:1", "idle-model:2"]);
  430. expect(runtime.getSessionModelSelection()).toMatchObject({
  431. providerId: "test",
  432. modelId: "session-model",
  433. });
  434. });
  435. it("keeps the execution-scoped Model and request auth while reactive compact retries after a session model switch", async () => {
  436. let runtime: ReturnType<typeof createTestAgentRuntime>;
  437. let overflowThrown = false;
  438. const createdModelIds: string[] = [];
  439. const createdRequestAuthSources: unknown[] = [];
  440. const callsByModel: string[] = [];
  441. const modelFactory = vi.fn(
  442. (input: {
  443. selection: ModelSelection;
  444. requestDependencies?: { requestAuth?: { source?: unknown } };
  445. }) => {
  446. const modelSelection = modelSelectionFromSelection(input.selection);
  447. createdModelIds.push(modelSelection.modelId);
  448. createdRequestAuthSources.push(input.requestDependencies?.requestAuth?.source);
  449. const model: Model = {
  450. providerId: modelSelection.providerId,
  451. modelId: modelSelection.modelId,
  452. properties: {
  453. contextWindow: 128_000,
  454. ...createTestModelFormatProperties(),
  455. supportsMidConversationSystem: false,
  456. supportsNativeWebSearch: false,
  457. supportsJsonSchemaOutput: true,
  458. supportsToolCall: true,
  459. },
  460. optionSpecs: {
  461. maxOutputTokens: { max: 8_000 },
  462. },
  463. options: { maxOutputTokens: 8_000 },
  464. bind() {
  465. return this;
  466. },
  467. async generateText(request: ModelRequest): Promise<ModelResult> {
  468. const requestText = JSON.stringify(request.messages);
  469. const compactRequest = requestText.includes("create a detailed summary");
  470. callsByModel.push(`${modelSelection.modelId}:${compactRequest ? "compact" : "normal"}`);
  471. if (compactRequest) {
  472. return result(modelSelection, {
  473. finishReason: "stop",
  474. text: "<summary>Keep the active loop model.</summary>",
  475. });
  476. }
  477. if (requestText.includes("trigger overflow") && !overflowThrown) {
  478. overflowThrown = true;
  479. runtime.setSessionModelSelection(
  480. createTestModelSelection(createTestModelSelection("test/model-b")),
  481. );
  482. const error = new Error("provider context window exceeded") as Error & {
  483. code: string;
  484. };
  485. error.code = ModelErrorCode.ModelContextExceeded;
  486. throw error;
  487. }
  488. return result(modelSelection, { finishReason: "stop", text: "done" });
  489. },
  490. streamText() {
  491. throw new Error("not used");
  492. },
  493. };
  494. return model;
  495. },
  496. );
  497. runtime = createTestAgentRuntime(
  498. createSessionId("model-lifecycle-reactive-compact"),
  499. {
  500. compact: { enabled: true },
  501. mode: "build",
  502. modelSelection: createTestModelSelection(createTestModelSelection("test/model-a")),
  503. workingDirectory: "/tmp/zcode-model-lifecycle-reactive",
  504. },
  505. {
  506. eventStore: createTestSessionEventStore(),
  507. modelFactory: modelFactory as never,
  508. },
  509. );
  510. await runtime.executeTurn("first setup turn");
  511. await runtime.executeTurn("second setup turn");
  512. const requestAuthSource = {
  513. resolve: vi.fn().mockResolvedValue({ apiKey: "compact-turn-key" }),
  514. };
  515. await runtime.executeTurn("trigger overflow", undefined, {
  516. intent: {
  517. sourceCommandId: "compact-command",
  518. kind: "sendText",
  519. requestedDelivery: "start-now",
  520. modelSelection: { providerId: "temporary", modelId: "idle-model" },
  521. },
  522. modelExecution: {
  523. selectionScope: "execution",
  524. requestDependencies: { requestAuth: { source: requestAuthSource } },
  525. },
  526. });
  527. expect(createdModelIds).toEqual(["model-a", "model-a", "idle-model"]);
  528. expect(createdRequestAuthSources).toEqual([undefined, undefined, requestAuthSource]);
  529. expect(callsByModel.slice(-3)).toEqual([
  530. "idle-model:normal",
  531. "idle-model:compact",
  532. "idle-model:normal",
  533. ]);
  534. });
  535. it("attributes context usage to the Model executing the request", () => {
  536. const activeModelSelection = createTestModelSelection("test/model-a");
  537. const runtime = createTestAgentRuntime(
  538. createSessionId("model-context-usage-attribution"),
  539. { modelSelection: createTestModelSelection(createTestModelSelection("test/model-b")) },
  540. {
  541. eventStore: createTestSessionEventStore(),
  542. modelFactory: createTestModelFactory({}),
  543. },
  544. );
  545. const activeModel: Model = {
  546. providerId: activeModelSelection.providerId,
  547. modelId: activeModelSelection.modelId,
  548. properties: {
  549. contextWindow: 128_000,
  550. ...createTestModelFormatProperties(),
  551. supportsMidConversationSystem: false,
  552. supportsNativeWebSearch: false,
  553. supportsJsonSchemaOutput: true,
  554. supportsToolCall: true,
  555. },
  556. optionSpecs: {
  557. maxOutputTokens: { max: 8_000 },
  558. },
  559. options: { maxOutputTokens: 8_000 },
  560. bind() {
  561. return this;
  562. },
  563. async generateText(): Promise<ModelResult> {
  564. return result(activeModelSelection, { finishReason: "stop" });
  565. },
  566. streamText() {
  567. throw new Error("not used");
  568. },
  569. };
  570. const snapshot = (runtime as any).buildContextUsageSnapshot({
  571. messages: [{ role: "user", content: "hello" }],
  572. model: activeModel,
  573. tools: [],
  574. });
  575. expect(snapshot.model).toBe("test/model-a");
  576. });
  577. it("attributes assistant history to the loop Model instead of provider result metadata", async () => {
  578. const activeModelSelection = createTestModelSelection("test/model-a");
  579. const reportedModelSelection = createTestModelSelection("provider/model-reported-by-provider");
  580. const model: Model = {
  581. providerId: activeModelSelection.providerId,
  582. modelId: activeModelSelection.modelId,
  583. properties: {
  584. contextWindow: 128_000,
  585. ...createTestModelFormatProperties(),
  586. supportsMidConversationSystem: false,
  587. supportsNativeWebSearch: false,
  588. supportsJsonSchemaOutput: true,
  589. supportsToolCall: true,
  590. },
  591. optionSpecs: {
  592. maxOutputTokens: { max: 8_000 },
  593. },
  594. options: { maxOutputTokens: 8_000 },
  595. bind() {
  596. return this;
  597. },
  598. async generateText(): Promise<ModelResult> {
  599. return result(reportedModelSelection, { finishReason: "stop", text: "done" });
  600. },
  601. streamText() {
  602. throw new Error("not used");
  603. },
  604. };
  605. const runtime = createTestAgentRuntime(
  606. createSessionId("model-history-attribution"),
  607. { modelSelection: createTestModelSelection(activeModelSelection) },
  608. {
  609. eventStore: createTestSessionEventStore(),
  610. modelFactory: () => model,
  611. },
  612. );
  613. await runtime.executeTurn("hello");
  614. const assistant = (
  615. runtime as unknown as {
  616. messageHistory: {
  617. toRuntimeEntries(): Array<{
  618. message?: { modelId?: string; providerId?: string; role?: string };
  619. }>;
  620. };
  621. }
  622. ).messageHistory
  623. .toRuntimeEntries()
  624. .findLast((entry) => entry.message?.role === "assistant");
  625. expect(assistant?.message).toMatchObject({
  626. providerId: model.providerId,
  627. modelId: model.modelId,
  628. });
  629. });
  630. });
  631. function createLifecycleTestModel(modelSelection: ModelSelection): Model {
  632. return {
  633. providerId: modelSelection.providerId,
  634. modelId: modelSelection.modelId,
  635. properties: {
  636. contextWindow: 128_000,
  637. ...createTestModelFormatProperties(),
  638. supportsMidConversationSystem: false,
  639. supportsNativeWebSearch: false,
  640. supportsJsonSchemaOutput: true,
  641. supportsToolCall: true,
  642. },
  643. optionSpecs: {
  644. reasoningLevel: {
  645. values: ["low", "high"],
  646. },
  647. maxOutputTokens: { max: 8_000 },
  648. },
  649. options: {
  650. reasoningLevel: modelSelection.options?.reasoningLevel,
  651. maxOutputTokens: 8_000,
  652. },
  653. bind(options) {
  654. return { ...this, options: { ...this.options, ...options } };
  655. },
  656. async generateText(): Promise<ModelResult> {
  657. return result(modelSelection, { finishReason: "stop", text: "done" });
  658. },
  659. streamText() {
  660. throw new Error("not used");
  661. },
  662. };
  663. }
  664. function modelSelectionFromSelection(selection: ModelSelection): ModelSelection {
  665. return {
  666. providerId: createModelProviderId(selection.providerId),
  667. modelId: createModelId(selection.modelId),
  668. ...(selection.options ? { options: { ...selection.options } } : {}),
  669. };
  670. }
  671. function result(
  672. modelSelection: ModelSelection,
  673. input: {
  674. finishReason: string;
  675. text?: string;
  676. toolCalls?: Array<{ id: string; name: string; input: unknown }>;
  677. },
  678. ): ModelResult {
  679. return {
  680. finishReason: input.finishReason,
  681. text: input.text ?? "",
  682. toolCalls: input.toolCalls,
  683. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  684. };
  685. }