sample-model.test.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import { describe, expect, it, vi } from "vitest";
  2. import { getCurrentModelInvocationContext, type ModelStatusSink } from "@zcode/contracts";
  3. import { sampleModel } from "../src/runtime/methods/sample-model.js";
  4. import { createModelStatusSink } from "../src/runtime/methods/model-status.js";
  5. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  6. const input = {
  7. request: {
  8. messages: [
  9. { role: "user" as const, content: { type: "text" as const, text: "Explain fractions" } },
  10. ],
  11. maxTokens: 400,
  12. },
  13. source: { pluginId: "lesson", serverName: "teacher", appIdentity: "app" },
  14. };
  15. function fixture() {
  16. const usage = vi.fn(async () => {});
  17. const generateText = vi.fn(async (_request: unknown) => ({
  18. text: "A half is 1/2",
  19. finishReason: "stop",
  20. usage: { inputTokens: 12, outputTokens: 8 },
  21. }));
  22. const model = {
  23. providerId: "fixture",
  24. modelId: "math",
  25. properties: { inputFormat: { supportsText: true, supportsImage: true } },
  26. optionSpecs: { maxOutputTokens: { max: 100 } },
  27. options: {},
  28. generateText,
  29. streamText: vi.fn(),
  30. bind: vi.fn(),
  31. };
  32. const runtime = {
  33. config: { mode: "plan", taskType: "interactive" },
  34. sessionId: "task",
  35. sessionFeatures: new Set(),
  36. rootTraceContext: { traceId: "trace", spanId: "parent" },
  37. modelFactory: vi.fn(() => model),
  38. getSessionModelSelection: vi.fn(() => ({ providerId: "fixture", modelId: "math" })),
  39. ensureSessionPersisted: vi.fn(async () => {}),
  40. appendEvent: vi.fn(),
  41. logModelNetworkStatus: vi.fn(),
  42. createEvent: vi.fn((type, payload) => ({ type, payload, timestamp: new Date() })),
  43. createModelStatusSink,
  44. extractToolCallsFromResult: vi.fn(() => []),
  45. sessionStore: {
  46. recordModelUsage: usage,
  47. upsertTurnUsage: vi.fn(),
  48. upsertToolUsage: vi.fn(),
  49. },
  50. } as unknown as AgentRuntimeInternal;
  51. return {
  52. runtime,
  53. model,
  54. usage,
  55. generateText,
  56. options: { abortSignal: new AbortController().signal },
  57. };
  58. }
  59. describe("task-bound sampling execution", () => {
  60. it.each(["success", "failure", "cancelled"] as const)(
  61. "releases status publishing after %s",
  62. async (outcome) => {
  63. const f = fixture();
  64. let sink: ModelStatusSink | undefined;
  65. f.generateText.mockImplementationOnce(async () => {
  66. sink = getCurrentModelInvocationContext()?.statusSink;
  67. if (outcome !== "success")
  68. throw outcome === "cancelled"
  69. ? new DOMException("cancelled", "AbortError")
  70. : new Error("sampling failed");
  71. return { text: "done", finishReason: "stop", usage: { inputTokens: 1, outputTokens: 1 } };
  72. });
  73. await sampleModel.call(f.runtime, input, f.options).catch(() => {});
  74. expect(sink).toBeDefined();
  75. await sink!.publish({ type: "model_request_started", attempt: 1 } as never);
  76. expect(f.runtime.logModelNetworkStatus).not.toHaveBeenCalled();
  77. },
  78. );
  79. it("uses task model, limits output, keeps main history unchanged and records usage", async () => {
  80. const f = fixture();
  81. f.generateText.mockImplementationOnce(async () => {
  82. await getCurrentModelInvocationContext()?.statusSink?.publish({
  83. type: "model_request_started",
  84. attempt: 1,
  85. } as never);
  86. return { text: "A half", finishReason: "stop", usage: { inputTokens: 12, outputTokens: 8 } };
  87. });
  88. expect(
  89. await sampleModel.call(
  90. f.runtime,
  91. {
  92. ...input,
  93. request: {
  94. ...input.request,
  95. systemPrompt: "Teach gently",
  96. modelPreferences: { hints: [{ name: "other" }] },
  97. },
  98. },
  99. f.options,
  100. ),
  101. ).toEqual({
  102. role: "assistant",
  103. model: "math",
  104. content: { type: "text", text: "A half" },
  105. stopReason: "endTurn",
  106. });
  107. expect(f.generateText).toHaveBeenCalledWith(
  108. expect.objectContaining({
  109. messages: [
  110. { role: "system", content: "Teach gently" },
  111. { role: "user", content: [{ type: "text", text: "Explain fractions" }] },
  112. ],
  113. options: { maxOutputTokens: 100 },
  114. }),
  115. );
  116. expect(f.runtime.appendEvent).not.toHaveBeenCalled();
  117. expect(f.runtime.modelFactory).toHaveBeenCalledWith({
  118. selection: { providerId: "fixture", modelId: "math" },
  119. });
  120. expect(f.usage).toHaveBeenCalledWith(
  121. expect.objectContaining({
  122. querySource: "mcp_app_sampling",
  123. status: "completed",
  124. sessionID: "task",
  125. outputTokens: 8,
  126. }),
  127. );
  128. });
  129. it("passes images as image input and refuses unsupported models before calling them", async () => {
  130. const f = fixture();
  131. const imageInput = {
  132. ...input,
  133. request: {
  134. ...input.request,
  135. messages: [
  136. {
  137. role: "user" as const,
  138. content: { type: "image" as const, mimeType: "image/png" as const, data: "AQ==" },
  139. },
  140. ],
  141. },
  142. };
  143. await sampleModel.call(f.runtime, imageInput, f.options);
  144. expect(f.generateText).toHaveBeenCalledWith(
  145. expect.objectContaining({
  146. messages: [
  147. {
  148. role: "user",
  149. content: [
  150. { type: "image", mediaType: "image/png", dataUrl: "data:image/png;base64,AQ==" },
  151. ],
  152. },
  153. ],
  154. }),
  155. );
  156. f.model.properties.inputFormat.supportsImage = false;
  157. await expect(sampleModel.call(f.runtime, imageInput, f.options)).rejects.toThrow("image input");
  158. expect(f.generateText).toHaveBeenCalledTimes(1);
  159. });
  160. it("keeps truncated stop reason and records cancelled usage on late success", async () => {
  161. const f = fixture();
  162. f.generateText.mockResolvedValueOnce({
  163. text: "Partial",
  164. finishReason: "length",
  165. usage: { inputTokens: 1, outputTokens: 1 },
  166. });
  167. expect((await sampleModel.call(f.runtime, input, f.options)).stopReason).toBe("maxTokens");
  168. const abort = new AbortController();
  169. f.generateText.mockImplementationOnce(async () => {
  170. abort.abort();
  171. return { text: "late", finishReason: "stop", usage: { inputTokens: 1, outputTokens: 1 } };
  172. });
  173. await expect(
  174. sampleModel.call(f.runtime, input, { abortSignal: abort.signal }),
  175. ).rejects.toThrow();
  176. expect(f.usage).toHaveBeenLastCalledWith(
  177. expect.objectContaining({ status: "cancelled", outputTokens: 1 }),
  178. );
  179. expect(f.runtime.appendEvent).not.toHaveBeenCalled();
  180. });
  181. });