runtime-model-lifecycle.test.ts 26 KB

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