runtime-model-lifecycle.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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. outputStyle: {
  396. name: "Learning",
  397. prompt: "Explain tradeoffs while solving the task.",
  398. },
  399. });
  400. }
  401. },
  402. });
  403. try {
  404. await runtime.executeTurn("first");
  405. await runtime.executeTurn("second");
  406. } finally {
  407. unsubscribe();
  408. }
  409. expect(modelFactory.mock.calls.map(([input]) => input.selection.modelId)).toEqual([
  410. "model-a",
  411. "model-b",
  412. ]);
  413. expect(requests.map((request) => request.modelId)).toEqual(["model-a", "model-a", "model-b"]);
  414. expect(requests[0]?.text).toContain("model named test/model-a");
  415. expect(requests[0]?.text).not.toContain("Learning output style is active");
  416. expect(requests[1]?.text).toContain("model named test/model-a");
  417. expect(requests[1]?.text).not.toContain("model named test/model-b");
  418. expect(requests[1]?.text).not.toContain("Learning output style is active");
  419. expect(requests[2]?.text).toContain("model named test/model-b");
  420. expect(requests[2]?.text).toContain("Learning output style is active");
  421. });
  422. it("keeps the execution-scoped Model while permission approval pauses and resumes the loop", async () => {
  423. const registry = createToolRegistry();
  424. const handler = vi.fn(async () => "write-ok");
  425. registry.register({
  426. inputSchema: {},
  427. metadata: {
  428. concurrentSafe: false,
  429. destructive: false,
  430. name: "WriteMarker",
  431. needsApproval: true,
  432. readOnly: false,
  433. riskLevel: "medium",
  434. sideEffectScope: "workspace",
  435. },
  436. handler,
  437. });
  438. let approve!: () => void;
  439. const permissionGate = new Promise<{ decision: "allow" }>((resolve) => {
  440. approve = () => resolve({ decision: "allow" });
  441. });
  442. const permissionBroker = {
  443. requestPermission: vi.fn(() => permissionGate),
  444. };
  445. const requestAuthSource = {
  446. resolve: vi.fn().mockResolvedValue({ apiKey: "permission-turn-key" }),
  447. };
  448. const modelCalls: string[] = [];
  449. const requestAuthSources: unknown[] = [];
  450. const modelFactory = vi.fn(
  451. (input: {
  452. selection: ModelSelection;
  453. requestDependencies?: { requestAuth?: { source?: unknown } };
  454. }) => {
  455. const modelSelection = modelSelectionFromSelection(input.selection);
  456. requestAuthSources.push(input.requestDependencies?.requestAuth?.source);
  457. let calls = 0;
  458. return {
  459. ...createLifecycleTestModel(modelSelection),
  460. async generateText(): Promise<ModelResult> {
  461. calls += 1;
  462. modelCalls.push(`${modelSelection.modelId}:${calls}`);
  463. return calls === 1
  464. ? result(modelSelection, {
  465. finishReason: "tool-calls",
  466. toolCalls: [{ id: "write-marker", name: "WriteMarker", input: {} }],
  467. })
  468. : result(modelSelection, { finishReason: "stop", text: "done" });
  469. },
  470. } satisfies Model;
  471. },
  472. );
  473. const runtime = createTestAgentRuntime(
  474. createSessionId("execution-model-permission-continuation"),
  475. {
  476. mode: "build",
  477. modelSelection: createTestModelSelection(createTestModelSelection("test/session-model")),
  478. workingDirectory: "/tmp/zcode-execution-model-permission",
  479. },
  480. {
  481. eventStore: createTestSessionEventStore(),
  482. modelFactory: modelFactory as never,
  483. permissionBroker,
  484. toolRegistry: registry,
  485. },
  486. );
  487. const executing = runtime.executeTurn("permission task", undefined, {
  488. intent: {
  489. sourceCommandId: "permission-command",
  490. kind: "sendText",
  491. requestedDelivery: "start-now",
  492. modelSelection: { providerId: "temporary", modelId: "idle-model" },
  493. },
  494. modelExecution: {
  495. selectionScope: "execution",
  496. requestDependencies: { requestAuth: { source: requestAuthSource } },
  497. },
  498. });
  499. await vi.waitFor(() => expect(permissionBroker.requestPermission).toHaveBeenCalledTimes(1));
  500. expect(modelFactory).toHaveBeenCalledTimes(1);
  501. expect(modelCalls).toEqual(["idle-model:1"]);
  502. expect(requestAuthSources).toEqual([requestAuthSource]);
  503. approve();
  504. await executing;
  505. expect(handler).toHaveBeenCalledTimes(1);
  506. expect(modelFactory).toHaveBeenCalledTimes(1);
  507. expect(modelCalls).toEqual(["idle-model:1", "idle-model:2"]);
  508. expect(runtime.getSessionModelSelection()).toMatchObject({
  509. providerId: "test",
  510. modelId: "session-model",
  511. });
  512. });
  513. it("keeps the execution-scoped Model and request auth while reactive compact retries after a session model switch", async () => {
  514. let runtime: ReturnType<typeof createTestAgentRuntime>;
  515. let overflowThrown = false;
  516. const createdModelIds: string[] = [];
  517. const createdRequestAuthSources: unknown[] = [];
  518. const callsByModel: string[] = [];
  519. const modelFactory = vi.fn(
  520. (input: {
  521. selection: ModelSelection;
  522. requestDependencies?: { requestAuth?: { source?: unknown } };
  523. }) => {
  524. const modelSelection = modelSelectionFromSelection(input.selection);
  525. createdModelIds.push(modelSelection.modelId);
  526. createdRequestAuthSources.push(input.requestDependencies?.requestAuth?.source);
  527. const model: Model = {
  528. providerId: modelSelection.providerId,
  529. modelId: modelSelection.modelId,
  530. properties: {
  531. contextWindow: 128_000,
  532. ...createTestModelFormatProperties(),
  533. supportsMidConversationSystem: false,
  534. supportsNativeWebSearch: false,
  535. supportsJsonSchemaOutput: true,
  536. supportsToolCall: true,
  537. },
  538. optionSpecs: {
  539. maxOutputTokens: { max: 8_000 },
  540. },
  541. options: { maxOutputTokens: 8_000 },
  542. bind() {
  543. return this;
  544. },
  545. async generateText(request: ModelRequest): Promise<ModelResult> {
  546. const requestText = JSON.stringify(request.messages);
  547. const compactRequest = requestText.includes("create a detailed summary");
  548. callsByModel.push(`${modelSelection.modelId}:${compactRequest ? "compact" : "normal"}`);
  549. if (compactRequest) {
  550. return result(modelSelection, {
  551. finishReason: "stop",
  552. text: "<summary>Keep the active loop model.</summary>",
  553. });
  554. }
  555. if (requestText.includes("trigger overflow") && !overflowThrown) {
  556. overflowThrown = true;
  557. runtime.setSessionModelSelection(
  558. createTestModelSelection(createTestModelSelection("test/model-b")),
  559. );
  560. const error = new Error("provider context window exceeded") as Error & {
  561. code: string;
  562. };
  563. error.code = ModelErrorCode.ModelContextExceeded;
  564. throw error;
  565. }
  566. return result(modelSelection, { finishReason: "stop", text: "done" });
  567. },
  568. streamText() {
  569. throw new Error("not used");
  570. },
  571. };
  572. return model;
  573. },
  574. );
  575. runtime = createTestAgentRuntime(
  576. createSessionId("model-lifecycle-reactive-compact"),
  577. {
  578. compact: { enabled: true },
  579. mode: "build",
  580. modelSelection: createTestModelSelection(createTestModelSelection("test/model-a")),
  581. workingDirectory: "/tmp/zcode-model-lifecycle-reactive",
  582. },
  583. {
  584. eventStore: createTestSessionEventStore(),
  585. modelFactory: modelFactory as never,
  586. },
  587. );
  588. await runtime.executeTurn("first setup turn");
  589. await runtime.executeTurn("second setup turn");
  590. const requestAuthSource = {
  591. resolve: vi.fn().mockResolvedValue({ apiKey: "compact-turn-key" }),
  592. };
  593. await runtime.executeTurn("trigger overflow", undefined, {
  594. intent: {
  595. sourceCommandId: "compact-command",
  596. kind: "sendText",
  597. requestedDelivery: "start-now",
  598. modelSelection: { providerId: "temporary", modelId: "idle-model" },
  599. },
  600. modelExecution: {
  601. selectionScope: "execution",
  602. requestDependencies: { requestAuth: { source: requestAuthSource } },
  603. },
  604. });
  605. expect(createdModelIds).toEqual(["model-a", "model-a", "idle-model"]);
  606. expect(createdRequestAuthSources).toEqual([undefined, undefined, requestAuthSource]);
  607. expect(callsByModel.slice(-3)).toEqual([
  608. "idle-model:normal",
  609. "idle-model:compact",
  610. "idle-model:normal",
  611. ]);
  612. });
  613. it("attributes context usage to the Model executing the request", () => {
  614. const activeModelSelection = createTestModelSelection("test/model-a");
  615. const runtime = createTestAgentRuntime(
  616. createSessionId("model-context-usage-attribution"),
  617. { modelSelection: createTestModelSelection(createTestModelSelection("test/model-b")) },
  618. {
  619. eventStore: createTestSessionEventStore(),
  620. modelFactory: createTestModelFactory({}),
  621. },
  622. );
  623. const activeModel: Model = {
  624. providerId: activeModelSelection.providerId,
  625. modelId: activeModelSelection.modelId,
  626. properties: {
  627. contextWindow: 128_000,
  628. ...createTestModelFormatProperties(),
  629. supportsMidConversationSystem: false,
  630. supportsNativeWebSearch: false,
  631. supportsJsonSchemaOutput: true,
  632. supportsToolCall: true,
  633. },
  634. optionSpecs: {
  635. maxOutputTokens: { max: 8_000 },
  636. },
  637. options: { maxOutputTokens: 8_000 },
  638. bind() {
  639. return this;
  640. },
  641. async generateText(): Promise<ModelResult> {
  642. return result(activeModelSelection, { finishReason: "stop" });
  643. },
  644. streamText() {
  645. throw new Error("not used");
  646. },
  647. };
  648. const snapshot = (runtime as any).buildContextUsageSnapshot({
  649. messages: [{ role: "user", content: "hello" }],
  650. model: activeModel,
  651. tools: [],
  652. });
  653. expect(snapshot.model).toBe("test/model-a");
  654. });
  655. it("attributes assistant history to the loop Model instead of provider result metadata", async () => {
  656. const activeModelSelection = createTestModelSelection("test/model-a");
  657. const reportedModelSelection = createTestModelSelection("provider/model-reported-by-provider");
  658. const model: Model = {
  659. providerId: activeModelSelection.providerId,
  660. modelId: activeModelSelection.modelId,
  661. properties: {
  662. contextWindow: 128_000,
  663. ...createTestModelFormatProperties(),
  664. supportsMidConversationSystem: false,
  665. supportsNativeWebSearch: false,
  666. supportsJsonSchemaOutput: true,
  667. supportsToolCall: true,
  668. },
  669. optionSpecs: {
  670. maxOutputTokens: { max: 8_000 },
  671. },
  672. options: { maxOutputTokens: 8_000 },
  673. bind() {
  674. return this;
  675. },
  676. async generateText(): Promise<ModelResult> {
  677. return result(reportedModelSelection, { finishReason: "stop", text: "done" });
  678. },
  679. streamText() {
  680. throw new Error("not used");
  681. },
  682. };
  683. const runtime = createTestAgentRuntime(
  684. createSessionId("model-history-attribution"),
  685. { modelSelection: createTestModelSelection(activeModelSelection) },
  686. {
  687. eventStore: createTestSessionEventStore(),
  688. modelFactory: () => model,
  689. },
  690. );
  691. await runtime.executeTurn("hello");
  692. const assistant = (
  693. runtime as unknown as {
  694. messageHistory: {
  695. toRuntimeEntries(): Array<{
  696. message?: { modelId?: string; providerId?: string; role?: string };
  697. }>;
  698. };
  699. }
  700. ).messageHistory
  701. .toRuntimeEntries()
  702. .findLast((entry) => entry.message?.role === "assistant");
  703. expect(assistant?.message).toMatchObject({
  704. providerId: model.providerId,
  705. modelId: model.modelId,
  706. });
  707. });
  708. });
  709. function createLifecycleTestModel(modelSelection: ModelSelection): Model {
  710. return {
  711. providerId: modelSelection.providerId,
  712. modelId: modelSelection.modelId,
  713. properties: {
  714. contextWindow: 128_000,
  715. ...createTestModelFormatProperties(),
  716. supportsMidConversationSystem: false,
  717. supportsNativeWebSearch: false,
  718. supportsJsonSchemaOutput: true,
  719. supportsToolCall: true,
  720. },
  721. optionSpecs: {
  722. reasoningLevel: {
  723. values: ["low", "high"],
  724. },
  725. maxOutputTokens: { max: 8_000 },
  726. },
  727. options: {
  728. reasoningLevel: modelSelection.options?.reasoningLevel,
  729. maxOutputTokens: 8_000,
  730. },
  731. bind(options) {
  732. return { ...this, options: { ...this.options, ...options } };
  733. },
  734. async generateText(): Promise<ModelResult> {
  735. return result(modelSelection, { finishReason: "stop", text: "done" });
  736. },
  737. streamText() {
  738. throw new Error("not used");
  739. },
  740. };
  741. }
  742. function modelSelectionFromSelection(selection: ModelSelection): ModelSelection {
  743. return {
  744. providerId: createModelProviderId(selection.providerId),
  745. modelId: createModelId(selection.modelId),
  746. ...(selection.options ? { options: { ...selection.options } } : {}),
  747. };
  748. }
  749. function result(
  750. modelSelection: ModelSelection,
  751. input: {
  752. finishReason: string;
  753. text?: string;
  754. toolCalls?: Array<{ id: string; name: string; input: unknown }>;
  755. },
  756. ): ModelResult {
  757. return {
  758. finishReason: input.finishReason,
  759. text: input.text ?? "",
  760. toolCalls: input.toolCalls,
  761. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  762. };
  763. }