runtime-model-lifecycle.test.ts 28 KB

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