message-history.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import { describe, expect, it } from "vitest";
  2. import { createTestModelSelection } from "./test-model-selection.js";
  3. import { MessageHistoryImpl, countContextPrefixMessages } from "../src/agent/message-history.js";
  4. import { buildProviderRequestMessages } from "../src/runtime/helpers/provider-request-messages.js";
  5. import type { ContextBuildResult, ContextSection } from "../src/context/types.js";
  6. import { estimateTokens } from "../src/context/utils.js";
  7. import { buildContextHistoryEntries } from "../src/runtime/methods/context-history-entries.js";
  8. describe("message history metadata", () => {
  9. it("preserves assistant model provenance through request-local clones", () => {
  10. const history = new MessageHistoryImpl();
  11. const model = createTestModelSelection("provider-a/model-a");
  12. history.addAssistant("answer", undefined, undefined, model);
  13. const entries = history.toRuntimeEntries();
  14. expect(entries[0]?.message).toMatchObject({ providerId: "provider-a", modelId: "model-a" });
  15. entries[0]!.message.providerId = "mutated" as never;
  16. expect(history.toRuntimeEntries()[0]?.message).toMatchObject({
  17. providerId: "provider-a",
  18. modelId: "model-a",
  19. });
  20. });
  21. it("preserves assistant tokens in runtime entries without exposing them to the provider", () => {
  22. const history = new MessageHistoryImpl();
  23. const tokens = {
  24. input: 100,
  25. output: 20,
  26. reasoning: 0,
  27. cache: { read: 0, write: 0 },
  28. total: 120,
  29. };
  30. history.addAssistant("answer", undefined, undefined, undefined, tokens);
  31. expect(history.toRuntimeEntries()[0]?.tokens).toEqual(tokens);
  32. expect(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages).toEqual([
  33. { role: "assistant", content: "answer" },
  34. ]);
  35. expect(JSON.stringify(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages)).not.toContain(
  36. "tokens",
  37. );
  38. });
  39. it("borrows the current authoritative runtime entries without cloning the array", () => {
  40. const history = new MessageHistoryImpl();
  41. history.addUser("first prompt", { source: "real_user" });
  42. const beforeAppend = history.borrowReadOnlyRuntimeEntries();
  43. const retainedMembership = [...beforeAppend];
  44. expect(history.borrowReadOnlyRuntimeEntries()).toBe(beforeAppend);
  45. history.addAssistant("second message");
  46. expect(history.borrowReadOnlyRuntimeEntries()).toBe(beforeAppend);
  47. expect(beforeAppend).toHaveLength(2);
  48. expect(retainedMembership).toHaveLength(1);
  49. history.replaceMessages([
  50. {
  51. message: { role: "user", content: "replacement prompt" },
  52. metadata: { source: "real_user" },
  53. },
  54. ]);
  55. const afterReplace = history.borrowReadOnlyRuntimeEntries();
  56. expect(afterReplace).not.toBe(beforeAppend);
  57. expect(beforeAppend).toHaveLength(2);
  58. expect(afterReplace).toEqual([
  59. {
  60. message: { role: "user", content: "replacement prompt" },
  61. metadata: { source: "real_user" },
  62. },
  63. ]);
  64. });
  65. it("does not expose provider-visible render helpers on message history", () => {
  66. const history = new MessageHistoryImpl();
  67. expect("toModelMessages" in history).toBe(false);
  68. expect("getCacheableMessages" in history).toBe(false);
  69. expect("getIncrementalMessages" in history).toBe(false);
  70. });
  71. it("stores system reminder attachments as structured entries rendered only by provider builder", () => {
  72. const history = new MessageHistoryImpl();
  73. history.addUser("real prompt", { source: "real_user" });
  74. history.addAttachment("output_style", "style body");
  75. expect(history.toRuntimeEntries()).toEqual([
  76. {
  77. message: {
  78. role: "user",
  79. content: "real prompt",
  80. },
  81. metadata: { source: "real_user" },
  82. },
  83. {
  84. kind: "attachment",
  85. content: "style body",
  86. metadata: { source: "output_style" },
  87. },
  88. ]);
  89. expect(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages).toEqual([
  90. {
  91. role: "user",
  92. content: "real prompt",
  93. },
  94. {
  95. role: "system",
  96. content: "style body",
  97. },
  98. ]);
  99. });
  100. it("stores internal metadata without leaking it to provider messages", () => {
  101. const history = new MessageHistoryImpl();
  102. history.init("system prompt");
  103. history.addUser("hook context", {
  104. source: "hook_context",
  105. });
  106. const providerMessages = buildProviderRequestMessages({
  107. entries: history.toRuntimeEntries(),
  108. }).messages;
  109. expect(providerMessages).toEqual([
  110. { role: "system", content: "system prompt" },
  111. { role: "user", content: "hook context" },
  112. ]);
  113. expect(JSON.stringify(providerMessages)).not.toContain("hook_context");
  114. const entries = history.toRuntimeEntries();
  115. expect(entries[1]?.metadata).toEqual({ source: "hook_context" });
  116. entries[1]!.message.content = "mutated";
  117. entries[1]!.metadata!.source = "real_user";
  118. expect(history.toRuntimeEntries()[1]).toMatchObject({
  119. message: { role: "user", content: "hook context" },
  120. metadata: { source: "hook_context" },
  121. });
  122. });
  123. it("counts metadata-marked request prefix before falling back to legacy text detection", () => {
  124. const history = new MessageHistoryImpl();
  125. history.init([
  126. { role: "system", content: "system prompt" },
  127. {
  128. message: { role: "user", content: "skill listing" },
  129. metadata: {
  130. source: "skills_listing",
  131. },
  132. },
  133. {
  134. message: {
  135. role: "user",
  136. content: "<system-reminder>\nthis is a real user badcase\n</system-reminder>",
  137. },
  138. metadata: {
  139. source: "real_user",
  140. },
  141. },
  142. ]);
  143. expect(countContextPrefixMessages(history.toRuntimeEntries())).toBe(2);
  144. expect(history.getCacheStats().cachedMessages).toBe(2);
  145. expect(
  146. countContextPrefixMessages([
  147. { role: "system", content: "system prompt" },
  148. { role: "user", content: "<system-reminder>\nlegacy prefix\n</system-reminder>" },
  149. { role: "user", content: "real user prompt" },
  150. ]),
  151. ).toBe(2);
  152. });
  153. it("builds skills listing context as a structured attachment entry", () => {
  154. const skillsSection = contextSection({
  155. name: "Available Skills",
  156. source: "skills",
  157. content: "# Skills\n- review: Inspect code",
  158. });
  159. const dateSection = contextSection({
  160. name: "Request User Context",
  161. source: "request_user_context",
  162. content: "# currentDate\nToday's date is 2026-06-17.",
  163. });
  164. const contextResult: ContextBuildResult = {
  165. sections: [skillsSection, dateSection],
  166. totalChars: skillsSection.chars + dateSection.chars,
  167. totalTokens: skillsSection.tokens + dateSection.tokens,
  168. systemMessages: [],
  169. metaUserAttachments: [
  170. {
  171. source: "skills_listing",
  172. content: "# Skills\n- review: Inspect code",
  173. },
  174. {
  175. source: "context_prefix",
  176. content:
  177. "As you answer the user's questions, you can use the following context:\n# currentDate\nToday's date is 2026-06-17.\n\n IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.",
  178. },
  179. ],
  180. };
  181. expect(buildContextHistoryEntries(contextResult)).toEqual([
  182. {
  183. kind: "attachment",
  184. content: "# Skills\n- review: Inspect code",
  185. metadata: { source: "skills_listing" },
  186. },
  187. {
  188. kind: "attachment",
  189. content:
  190. "As you answer the user's questions, you can use the following context:\n# currentDate\nToday's date is 2026-06-17.\n\n IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.",
  191. metadata: { source: "context_prefix" },
  192. },
  193. ]);
  194. });
  195. });
  196. function contextSection(input: {
  197. name: string;
  198. source: ContextSection["source"];
  199. content: string;
  200. }): ContextSection {
  201. return {
  202. name: input.name,
  203. source: input.source,
  204. injectionTarget: "meta_user",
  205. cacheHint: "dynamic",
  206. content: input.content,
  207. chars: input.content.length,
  208. tokens: estimateTokens(input.content),
  209. preview: input.content.slice(0, 100),
  210. };
  211. }