runtime-model-lifecycle.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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).toHaveBeenCalledTimes(2);
  226. expect(modelFactory.mock.calls.map(([input]) => input.selection.modelId)).toEqual([
  227. "model-a",
  228. "model-b",
  229. ]);
  230. });
  231. it("captures model and context before async turn setup can observe a model switch", async () => {
  232. const registry = createToolRegistry();
  233. registry.register({
  234. inputSchema: {},
  235. metadata: {
  236. concurrentSafe: true,
  237. destructive: false,
  238. name: "ReadBeforeModelCapture",
  239. needsApproval: false,
  240. readOnly: true,
  241. riskLevel: "low",
  242. sideEffectScope: "none",
  243. },
  244. handler: async () => "marker",
  245. });
  246. let runtime: ReturnType<typeof createTestAgentRuntime>;
  247. const requests: Array<{ modelId: string; text: string }> = [];
  248. const modelFactory = vi.fn((input: { selection: ModelSelection }) => {
  249. const modelSelection = modelSelectionFromSelection(input.selection);
  250. let calls = 0;
  251. const model: Model = {
  252. providerId: modelSelection.providerId,
  253. modelId: modelSelection.modelId,
  254. properties: {
  255. contextWindow: 128_000,
  256. ...createTestModelFormatProperties(),
  257. supportsMidConversationSystem: false,
  258. supportsNativeWebSearch: false,
  259. supportsJsonSchemaOutput: true,
  260. supportsToolCall: true,
  261. },
  262. optionSpecs: {
  263. maxOutputTokens: { max: 8_000 },
  264. },
  265. options: { maxOutputTokens: 8_000 },
  266. bind() {
  267. return this;
  268. },
  269. async generateText(request: ModelRequest): Promise<ModelResult> {
  270. calls += 1;
  271. requests.push({
  272. modelId: modelSelection.modelId,
  273. text: JSON.stringify(request.messages),
  274. });
  275. if (modelSelection.modelId === "model-a" && calls === 1) {
  276. return result(modelSelection, {
  277. finishReason: "tool-calls",
  278. toolCalls: [
  279. {
  280. id: "read-before-model-capture",
  281. name: "ReadBeforeModelCapture",
  282. input: {},
  283. },
  284. ],
  285. });
  286. }
  287. return result(modelSelection, { finishReason: "stop", text: "done" });
  288. },
  289. streamText() {
  290. throw new Error("not used");
  291. },
  292. };
  293. return model;
  294. });
  295. runtime = createTestAgentRuntime(
  296. createSessionId("model-context-before-capture"),
  297. {
  298. mode: "build",
  299. modelSelection: createTestModelSelection(createTestModelSelection("test/model-a")),
  300. workingDirectory: "/tmp/zcode-model-context-before-capture",
  301. },
  302. {
  303. eventStore: createTestSessionEventStore(),
  304. modelFactory: modelFactory as never,
  305. toolRegistry: registry,
  306. },
  307. );
  308. let switched = false;
  309. const unsubscribe = runtime.subscribeEvents({
  310. onSessionEvent(event) {
  311. if (!switched && event.type === SessionEventType.TurnStarted) {
  312. switched = true;
  313. runtime.setSessionModelSelection(
  314. createTestModelSelection(createTestModelSelection("test/model-b")),
  315. );
  316. runtime.updateConfig({
  317. language: "zh-CN",
  318. outputStyle: {
  319. name: "Learning",
  320. prompt: "Explain tradeoffs while solving the task.",
  321. },
  322. });
  323. }
  324. },
  325. });
  326. try {
  327. await runtime.executeTurn("first");
  328. await runtime.executeTurn("second");
  329. } finally {
  330. unsubscribe();
  331. }
  332. expect(modelFactory.mock.calls.map(([input]) => input.selection.modelId)).toEqual([
  333. "model-a",
  334. "model-b",
  335. ]);
  336. expect(requests.map((request) => request.modelId)).toEqual(["model-a", "model-a", "model-b"]);
  337. expect(requests[0]?.text).toContain("model named test/model-a");
  338. expect(requests[0]?.text).not.toContain("Learning output style is active");
  339. expect(requests[1]?.text).toContain("model named test/model-a");
  340. expect(requests[1]?.text).not.toContain("model named test/model-b");
  341. expect(requests[1]?.text).not.toContain("Learning output style is active");
  342. expect(requests[2]?.text).toContain("model named test/model-b");
  343. expect(requests[2]?.text).toContain("Learning output style is active");
  344. });
  345. it("keeps the execution-scoped Model while permission approval pauses and resumes the loop", async () => {
  346. const registry = createToolRegistry();
  347. const handler = vi.fn(async () => "write-ok");
  348. registry.register({
  349. inputSchema: {},
  350. metadata: {
  351. concurrentSafe: false,
  352. destructive: false,
  353. name: "WriteMarker",
  354. needsApproval: true,
  355. readOnly: false,
  356. riskLevel: "medium",
  357. sideEffectScope: "workspace",
  358. },
  359. handler,
  360. });
  361. let approve!: () => void;
  362. const permissionGate = new Promise<{ decision: "allow" }>((resolve) => {
  363. approve = () => resolve({ decision: "allow" });
  364. });
  365. const permissionBroker = {
  366. requestPermission: vi.fn(() => permissionGate),
  367. };
  368. const requestAuthSource = {
  369. resolve: vi.fn().mockResolvedValue({ apiKey: "permission-turn-key" }),
  370. };
  371. const modelCalls: string[] = [];
  372. const requestAuthSources: unknown[] = [];
  373. const modelFactory = vi.fn(
  374. (input: {
  375. selection: ModelSelection;
  376. requestDependencies?: { requestAuth?: { source?: unknown } };
  377. }) => {
  378. const modelSelection = modelSelectionFromSelection(input.selection);
  379. requestAuthSources.push(input.requestDependencies?.requestAuth?.source);
  380. let calls = 0;
  381. return {
  382. ...createLifecycleTestModel(modelSelection),
  383. async generateText(): Promise<ModelResult> {
  384. calls += 1;
  385. modelCalls.push(`${modelSelection.modelId}:${calls}`);
  386. return calls === 1
  387. ? result(modelSelection, {
  388. finishReason: "tool-calls",
  389. toolCalls: [{ id: "write-marker", name: "WriteMarker", input: {} }],
  390. })
  391. : result(modelSelection, { finishReason: "stop", text: "done" });
  392. },
  393. } satisfies Model;
  394. },
  395. );
  396. const runtime = createTestAgentRuntime(
  397. createSessionId("execution-model-permission-continuation"),
  398. {
  399. mode: "build",
  400. modelSelection: createTestModelSelection(createTestModelSelection("test/session-model")),
  401. workingDirectory: "/tmp/zcode-execution-model-permission",
  402. },
  403. {
  404. eventStore: createTestSessionEventStore(),
  405. modelFactory: modelFactory as never,
  406. permissionBroker,
  407. toolRegistry: registry,
  408. },
  409. );
  410. const executing = runtime.executeTurn("permission task", undefined, {
  411. intent: {
  412. sourceCommandId: "permission-command",
  413. kind: "sendText",
  414. requestedDelivery: "start-now",
  415. modelSelection: { providerId: "temporary", modelId: "idle-model" },
  416. },
  417. modelExecution: {
  418. selectionScope: "execution",
  419. requestDependencies: { requestAuth: { source: requestAuthSource } },
  420. },
  421. });
  422. await vi.waitFor(() => expect(permissionBroker.requestPermission).toHaveBeenCalledTimes(1));
  423. expect(modelFactory).toHaveBeenCalledTimes(1);
  424. expect(modelCalls).toEqual(["idle-model:1"]);
  425. expect(requestAuthSources).toEqual([requestAuthSource]);
  426. approve();
  427. await executing;
  428. expect(handler).toHaveBeenCalledTimes(1);
  429. expect(modelFactory).toHaveBeenCalledTimes(1);
  430. expect(modelCalls).toEqual(["idle-model:1", "idle-model:2"]);
  431. expect(runtime.getSessionModelSelection()).toMatchObject({
  432. providerId: "test",
  433. modelId: "session-model",
  434. });
  435. });
  436. it("keeps the execution-scoped Model and request auth while reactive compact retries after a session model switch", async () => {
  437. let runtime: ReturnType<typeof createTestAgentRuntime>;
  438. let overflowThrown = false;
  439. const createdModelIds: string[] = [];
  440. const createdRequestAuthSources: unknown[] = [];
  441. const callsByModel: string[] = [];
  442. const modelFactory = vi.fn(
  443. (input: {
  444. selection: ModelSelection;
  445. requestDependencies?: { requestAuth?: { source?: unknown } };
  446. }) => {
  447. const modelSelection = modelSelectionFromSelection(input.selection);
  448. createdModelIds.push(modelSelection.modelId);
  449. createdRequestAuthSources.push(input.requestDependencies?.requestAuth?.source);
  450. const model: Model = {
  451. providerId: modelSelection.providerId,
  452. modelId: modelSelection.modelId,
  453. properties: {
  454. contextWindow: 128_000,
  455. ...createTestModelFormatProperties(),
  456. supportsMidConversationSystem: false,
  457. supportsNativeWebSearch: false,
  458. supportsJsonSchemaOutput: true,
  459. supportsToolCall: true,
  460. },
  461. optionSpecs: {
  462. maxOutputTokens: { max: 8_000 },
  463. },
  464. options: { maxOutputTokens: 8_000 },
  465. bind() {
  466. return this;
  467. },
  468. async generateText(request: ModelRequest): Promise<ModelResult> {
  469. const requestText = JSON.stringify(request.messages);
  470. const compactRequest = requestText.includes("create a detailed summary");
  471. callsByModel.push(`${modelSelection.modelId}:${compactRequest ? "compact" : "normal"}`);
  472. if (compactRequest) {
  473. return result(modelSelection, {
  474. finishReason: "stop",
  475. text: "<summary>Keep the active loop model.</summary>",
  476. });
  477. }
  478. if (requestText.includes("trigger overflow") && !overflowThrown) {
  479. overflowThrown = true;
  480. runtime.setSessionModelSelection(
  481. createTestModelSelection(createTestModelSelection("test/model-b")),
  482. );
  483. const error = new Error("provider context window exceeded") as Error & {
  484. code: string;
  485. };
  486. error.code = ModelErrorCode.ModelContextExceeded;
  487. throw error;
  488. }
  489. return result(modelSelection, { finishReason: "stop", text: "done" });
  490. },
  491. streamText() {
  492. throw new Error("not used");
  493. },
  494. };
  495. return model;
  496. },
  497. );
  498. runtime = createTestAgentRuntime(
  499. createSessionId("model-lifecycle-reactive-compact"),
  500. {
  501. compact: { enabled: true },
  502. mode: "build",
  503. modelSelection: createTestModelSelection(createTestModelSelection("test/model-a")),
  504. workingDirectory: "/tmp/zcode-model-lifecycle-reactive",
  505. },
  506. {
  507. eventStore: createTestSessionEventStore(),
  508. modelFactory: modelFactory as never,
  509. },
  510. );
  511. await runtime.executeTurn("first setup turn");
  512. await runtime.executeTurn("second setup turn");
  513. const requestAuthSource = {
  514. resolve: vi.fn().mockResolvedValue({ apiKey: "compact-turn-key" }),
  515. };
  516. await runtime.executeTurn("trigger overflow", undefined, {
  517. intent: {
  518. sourceCommandId: "compact-command",
  519. kind: "sendText",
  520. requestedDelivery: "start-now",
  521. modelSelection: { providerId: "temporary", modelId: "idle-model" },
  522. },
  523. modelExecution: {
  524. selectionScope: "execution",
  525. requestDependencies: { requestAuth: { source: requestAuthSource } },
  526. },
  527. });
  528. expect(createdModelIds).toEqual(["model-a", "model-a", "idle-model"]);
  529. expect(createdRequestAuthSources).toEqual([undefined, undefined, requestAuthSource]);
  530. expect(callsByModel.slice(-3)).toEqual([
  531. "idle-model:normal",
  532. "idle-model:compact",
  533. "idle-model:normal",
  534. ]);
  535. });
  536. it("attributes context usage to the Model executing the request", () => {
  537. const activeModelSelection = createTestModelSelection("test/model-a");
  538. const runtime = createTestAgentRuntime(
  539. createSessionId("model-context-usage-attribution"),
  540. { modelSelection: createTestModelSelection(createTestModelSelection("test/model-b")) },
  541. {
  542. eventStore: createTestSessionEventStore(),
  543. modelFactory: createTestModelFactory({}),
  544. },
  545. );
  546. const activeModel: Model = {
  547. providerId: activeModelSelection.providerId,
  548. modelId: activeModelSelection.modelId,
  549. properties: {
  550. contextWindow: 128_000,
  551. ...createTestModelFormatProperties(),
  552. supportsMidConversationSystem: false,
  553. supportsNativeWebSearch: false,
  554. supportsJsonSchemaOutput: true,
  555. supportsToolCall: true,
  556. },
  557. optionSpecs: {
  558. maxOutputTokens: { max: 8_000 },
  559. },
  560. options: { maxOutputTokens: 8_000 },
  561. bind() {
  562. return this;
  563. },
  564. async generateText(): Promise<ModelResult> {
  565. return result(activeModelSelection, { finishReason: "stop" });
  566. },
  567. streamText() {
  568. throw new Error("not used");
  569. },
  570. };
  571. const snapshot = (runtime as any).buildContextUsageSnapshot({
  572. messages: [{ role: "user", content: "hello" }],
  573. model: activeModel,
  574. tools: [],
  575. });
  576. expect(snapshot.model).toBe("test/model-a");
  577. });
  578. it("attributes assistant history to the loop Model instead of provider result metadata", async () => {
  579. const activeModelSelection = createTestModelSelection("test/model-a");
  580. const reportedModelSelection = createTestModelSelection("provider/model-reported-by-provider");
  581. const model: Model = {
  582. providerId: activeModelSelection.providerId,
  583. modelId: activeModelSelection.modelId,
  584. properties: {
  585. contextWindow: 128_000,
  586. ...createTestModelFormatProperties(),
  587. supportsMidConversationSystem: false,
  588. supportsNativeWebSearch: false,
  589. supportsJsonSchemaOutput: true,
  590. supportsToolCall: true,
  591. },
  592. optionSpecs: {
  593. maxOutputTokens: { max: 8_000 },
  594. },
  595. options: { maxOutputTokens: 8_000 },
  596. bind() {
  597. return this;
  598. },
  599. async generateText(): Promise<ModelResult> {
  600. return result(reportedModelSelection, { finishReason: "stop", text: "done" });
  601. },
  602. streamText() {
  603. throw new Error("not used");
  604. },
  605. };
  606. const runtime = createTestAgentRuntime(
  607. createSessionId("model-history-attribution"),
  608. { modelSelection: createTestModelSelection(activeModelSelection) },
  609. {
  610. eventStore: createTestSessionEventStore(),
  611. modelFactory: () => model,
  612. },
  613. );
  614. await runtime.executeTurn("hello");
  615. const assistant = (
  616. runtime as unknown as {
  617. messageHistory: {
  618. toRuntimeEntries(): Array<{
  619. message?: { modelId?: string; providerId?: string; role?: string };
  620. }>;
  621. };
  622. }
  623. ).messageHistory
  624. .toRuntimeEntries()
  625. .findLast((entry) => entry.message?.role === "assistant");
  626. expect(assistant?.message).toMatchObject({
  627. providerId: model.providerId,
  628. modelId: model.modelId,
  629. });
  630. });
  631. });
  632. function createLifecycleTestModel(modelSelection: ModelSelection): Model {
  633. return {
  634. providerId: modelSelection.providerId,
  635. modelId: modelSelection.modelId,
  636. properties: {
  637. contextWindow: 128_000,
  638. ...createTestModelFormatProperties(),
  639. supportsMidConversationSystem: false,
  640. supportsNativeWebSearch: false,
  641. supportsJsonSchemaOutput: true,
  642. supportsToolCall: true,
  643. },
  644. optionSpecs: {
  645. reasoningLevel: {
  646. values: ["low", "high"],
  647. },
  648. maxOutputTokens: { max: 8_000 },
  649. },
  650. options: {
  651. reasoningLevel: modelSelection.options?.reasoningLevel,
  652. maxOutputTokens: 8_000,
  653. },
  654. bind(options) {
  655. return { ...this, options: { ...this.options, ...options } };
  656. },
  657. async generateText(): Promise<ModelResult> {
  658. return result(modelSelection, { finishReason: "stop", text: "done" });
  659. },
  660. streamText() {
  661. throw new Error("not used");
  662. },
  663. };
  664. }
  665. function modelSelectionFromSelection(selection: ModelSelection): ModelSelection {
  666. return {
  667. providerId: createModelProviderId(selection.providerId),
  668. modelId: createModelId(selection.modelId),
  669. ...(selection.options ? { options: { ...selection.options } } : {}),
  670. };
  671. }
  672. function result(
  673. modelSelection: ModelSelection,
  674. input: {
  675. finishReason: string;
  676. text?: string;
  677. toolCalls?: Array<{ id: string; name: string; input: unknown }>;
  678. },
  679. ): ModelResult {
  680. return {
  681. finishReason: input.finishReason,
  682. text: input.text ?? "",
  683. toolCalls: input.toolCalls,
  684. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  685. };
  686. }