message-history.test.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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("isolates announcement delta arrays across add, read and replace without exposing metadata", () => {
  10. const history = new MessageHistoryImpl();
  11. const delta = {
  12. addedNames: ["WebFetch"],
  13. removedNames: ["TodoWrite"],
  14. readdedNames: ["WebFetch"],
  15. };
  16. const expected = structuredClone(delta);
  17. history.addEntries([
  18. {
  19. message: { role: "user", content: "Tool availability changed." },
  20. metadata: { source: "legacy_synthetic", toolSearchAnnouncement: delta },
  21. },
  22. ]);
  23. for (const names of Object.values(delta)) names.push("source mutation");
  24. const entries = history.toRuntimeEntries();
  25. expect(entries[0]?.metadata?.toolSearchAnnouncement).toEqual(expected);
  26. history.replaceMessages(entries);
  27. for (const names of Object.values(entries[0]!.metadata!.toolSearchAnnouncement!))
  28. (names as string[]).push("copy mutation");
  29. expect(history.toRuntimeEntries()[0]?.metadata?.toolSearchAnnouncement).toEqual(expected);
  30. expect(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages).toEqual([
  31. { role: "user", content: "Tool availability changed." },
  32. ]);
  33. });
  34. it("preserves assistant model provenance through request-local clones", () => {
  35. const history = new MessageHistoryImpl();
  36. const model = createTestModelSelection("provider-a/model-a");
  37. history.addAssistant("answer", undefined, undefined, model);
  38. const entries = history.toRuntimeEntries();
  39. expect(entries[0]?.message).toMatchObject({ providerId: "provider-a", modelId: "model-a" });
  40. entries[0]!.message.providerId = "mutated" as never;
  41. expect(history.toRuntimeEntries()[0]?.message).toMatchObject({
  42. providerId: "provider-a",
  43. modelId: "model-a",
  44. });
  45. });
  46. it("preserves assistant tokens in runtime entries without exposing them to the provider", () => {
  47. const history = new MessageHistoryImpl();
  48. const tokens = {
  49. input: 100,
  50. output: 20,
  51. reasoning: 0,
  52. cache: { read: 0, write: 0 },
  53. total: 120,
  54. };
  55. history.addAssistant("answer", undefined, undefined, undefined, tokens);
  56. expect(history.toRuntimeEntries()[0]?.tokens).toEqual(tokens);
  57. expect(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages).toEqual([
  58. { role: "assistant", content: "answer" },
  59. ]);
  60. });
  61. it("borrows the current authoritative runtime entries without cloning the array", () => {
  62. const history = new MessageHistoryImpl();
  63. history.addUser("first prompt", { source: "real_user" });
  64. const beforeAppend = history.borrowReadOnlyRuntimeEntries();
  65. const retainedMembership = [...beforeAppend];
  66. expect(history.borrowReadOnlyRuntimeEntries()).toBe(beforeAppend);
  67. history.addAssistant("second message");
  68. expect(history.borrowReadOnlyRuntimeEntries()).toBe(beforeAppend);
  69. expect(beforeAppend).toHaveLength(2);
  70. expect(retainedMembership).toHaveLength(1);
  71. history.replaceMessages([
  72. {
  73. message: { role: "user", content: "replacement prompt" },
  74. metadata: { source: "real_user" },
  75. },
  76. ]);
  77. const afterReplace = history.borrowReadOnlyRuntimeEntries();
  78. expect(afterReplace).not.toBe(beforeAppend);
  79. expect(beforeAppend).toHaveLength(2);
  80. expect(afterReplace).toEqual([
  81. {
  82. message: { role: "user", content: "replacement prompt" },
  83. metadata: { source: "real_user" },
  84. },
  85. ]);
  86. });
  87. it("stores system reminder attachments as structured entries rendered only by provider builder", () => {
  88. const history = new MessageHistoryImpl();
  89. history.addUser("real prompt", { source: "real_user" });
  90. history.addAttachment("output_style", "style body");
  91. expect(history.toRuntimeEntries()).toEqual([
  92. {
  93. message: {
  94. role: "user",
  95. content: "real prompt",
  96. },
  97. metadata: { source: "real_user" },
  98. },
  99. {
  100. kind: "attachment",
  101. content: "style body",
  102. metadata: { source: "output_style" },
  103. },
  104. ]);
  105. expect(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages).toEqual([
  106. {
  107. role: "user",
  108. content: "real prompt",
  109. },
  110. {
  111. role: "system",
  112. content: "style body",
  113. },
  114. ]);
  115. });
  116. it("stores internal metadata without leaking it to provider messages", () => {
  117. const history = new MessageHistoryImpl();
  118. history.init("system prompt");
  119. history.addUser("hook context", {
  120. source: "hook_context",
  121. });
  122. const providerMessages = buildProviderRequestMessages({
  123. entries: history.toRuntimeEntries(),
  124. }).messages;
  125. expect(providerMessages).toEqual([
  126. { role: "system", content: "system prompt" },
  127. { role: "user", content: "hook context" },
  128. ]);
  129. const entries = history.toRuntimeEntries();
  130. expect(entries[1]?.metadata).toEqual({ source: "hook_context" });
  131. entries[1]!.message.content = "mutated";
  132. entries[1]!.metadata!.source = "real_user";
  133. expect(history.toRuntimeEntries()[1]).toMatchObject({
  134. message: { role: "user", content: "hook context" },
  135. metadata: { source: "hook_context" },
  136. });
  137. });
  138. it("counts metadata-marked request prefix before falling back to legacy text detection", () => {
  139. const history = new MessageHistoryImpl();
  140. history.init([
  141. { role: "system", content: "system prompt" },
  142. {
  143. message: { role: "user", content: "skill listing" },
  144. metadata: {
  145. source: "skills_listing",
  146. },
  147. },
  148. {
  149. message: {
  150. role: "user",
  151. content: "<system-reminder>\nthis is a real user badcase\n</system-reminder>",
  152. },
  153. metadata: {
  154. source: "real_user",
  155. },
  156. },
  157. ]);
  158. expect(countContextPrefixMessages(history.toRuntimeEntries())).toBe(2);
  159. expect(history.getCacheStats().cachedMessages).toBe(2);
  160. expect(
  161. countContextPrefixMessages([
  162. { role: "system", content: "system prompt" },
  163. { role: "user", content: "<system-reminder>\nlegacy prefix\n</system-reminder>" },
  164. { role: "user", content: "real user prompt" },
  165. ]),
  166. ).toBe(2);
  167. });
  168. it("builds skills listing context as a structured attachment entry", () => {
  169. const skillsSection = contextSection({
  170. name: "Available Skills",
  171. source: "skills",
  172. content: "# Skills\n- review: Inspect code",
  173. });
  174. const dateSection = contextSection({
  175. name: "Request User Context",
  176. source: "request_user_context",
  177. content: "# currentDate\nToday's date is 2026-06-17.",
  178. });
  179. const contextResult: ContextBuildResult = {
  180. sections: [skillsSection, dateSection],
  181. totalChars: skillsSection.chars + dateSection.chars,
  182. totalTokens: skillsSection.tokens + dateSection.tokens,
  183. systemMessages: [],
  184. metaUserAttachments: [
  185. {
  186. source: "skills_listing",
  187. content: "# Skills\n- review: Inspect code",
  188. },
  189. {
  190. source: "context_prefix",
  191. content:
  192. "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.",
  193. },
  194. ],
  195. };
  196. expect(buildContextHistoryEntries(contextResult)).toEqual([
  197. {
  198. kind: "attachment",
  199. content: "# Skills\n- review: Inspect code",
  200. metadata: { source: "skills_listing" },
  201. },
  202. {
  203. kind: "attachment",
  204. content:
  205. "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.",
  206. metadata: { source: "context_prefix" },
  207. },
  208. ]);
  209. });
  210. });
  211. function contextSection(input: {
  212. name: string;
  213. source: ContextSection["source"];
  214. content: string;
  215. }): ContextSection {
  216. return {
  217. name: input.name,
  218. source: input.source,
  219. injectionTarget: "meta_user",
  220. cacheHint: "dynamic",
  221. content: input.content,
  222. chars: input.content.length,
  223. tokens: estimateTokens(input.content),
  224. preview: input.content.slice(0, 100),
  225. };
  226. }