plugin-reference-runtime.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // PLG01/PLG06/PLG07/PLG08/PLG11 的 runtime 集成取证(docs/plugin-reference-mention.md,
  2. // docs/conversation-session-case-catalog.md PLG 组):
  3. // turn start 注入顺序、冻结 catalog 语义、每轮重解析 + live 交集、model-only 输入不解析、
  4. // reminder 以 model-only notice 持久化并可由 hydration 重建(不落 TurnStarted input、不作为真实 user message)。
  5. import { describe, expect, it, vi } from "vitest";
  6. import {
  7. createSessionId,
  8. type McpPort,
  9. type PluginReferenceCatalog,
  10. type SkillPort,
  11. type McpServerStatus,
  12. } from "@zcode/contracts";
  13. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  14. import { createTestSessionEventStore } from "./test-event-store.js";
  15. import { createTestModelFactory } from "./test-runtime-model.js";
  16. const DEMO_CATALOG: PluginReferenceCatalog = {
  17. plugins: [
  18. {
  19. pluginId: "demo@mkt-a",
  20. name: "demo",
  21. marketplace: "mkt-a",
  22. enabled: true,
  23. conflictingPluginIds: [],
  24. skillQualifiedNames: ["demo:search"],
  25. mcpServerNames: ["plugin:demo:main"],
  26. subagentNames: ["demo:reviewer"],
  27. rootPath: "/plugins/demo",
  28. },
  29. ],
  30. };
  31. function createSkillPort(): SkillPort {
  32. return {
  33. async discoverSkills() {
  34. return {
  35. skills: [
  36. {
  37. name: "search",
  38. description: "search things",
  39. pluginName: "demo",
  40. qualifiedName: "demo:search",
  41. path: "/plugins/demo/skills/search/SKILL.md",
  42. directory: "/plugins/demo/skills/search",
  43. rootPath: "/plugins/demo/skills",
  44. scope: "user" as const,
  45. source: "plugin" as const,
  46. safeToAutoLoad: true,
  47. frontmatterKeys: [],
  48. },
  49. ],
  50. diagnostics: [],
  51. totalDiscovered: 1,
  52. };
  53. },
  54. async loadSkill() {
  55. throw new Error("not needed");
  56. },
  57. };
  58. }
  59. function createMcpPort(statuses: Record<string, McpServerStatus>): McpPort {
  60. const tools = [
  61. {
  62. serverName: "plugin:demo:main",
  63. toolName: "lookup",
  64. inputSchema: { type: "object", properties: {} },
  65. annotations: { readOnlyHint: true },
  66. },
  67. ];
  68. return {
  69. getToolSnapshot: () =>
  70. Object.fromEntries(
  71. Object.entries(statuses).map(([name, status]) => [
  72. name,
  73. {
  74. status,
  75. tools:
  76. status.status === "connected"
  77. ? tools.filter((tool) => tool.serverName === name)
  78. : undefined,
  79. toolsVersion: "1",
  80. },
  81. ]),
  82. ),
  83. connectConfiguredServers: async () => ({
  84. statuses,
  85. tools,
  86. }),
  87. connectServer: async () => ({
  88. status: "connected",
  89. transport: "stdio",
  90. toolCount: 1,
  91. updatedAt: "now",
  92. }),
  93. disconnectServer: async () => undefined,
  94. // 端口状态与工具快照来自同一份内存记录。
  95. status: async () => statuses,
  96. listTools: async () => [],
  97. callTool: async () => ({ content: [{ type: "text", text: "ok" }] }),
  98. close: async () => {},
  99. };
  100. }
  101. function connectedStatus(): Record<string, McpServerStatus> {
  102. return {
  103. "plugin:demo:main": {
  104. status: "connected",
  105. transport: "stdio",
  106. toolCount: 1,
  107. updatedAt: "now",
  108. },
  109. };
  110. }
  111. interface CapturedRequest {
  112. messages: Array<{ role: string; text: string }>;
  113. texts: string[];
  114. toolNames: string[];
  115. }
  116. function createRuntime(input: {
  117. catalog?: PluginReferenceCatalog;
  118. statuses?: Record<string, McpServerStatus>;
  119. requests: CapturedRequest[];
  120. }) {
  121. const sessionId = createSessionId("plugin-reference-runtime");
  122. const statuses = input.statuses ?? connectedStatus();
  123. return createTestAgentRuntime(
  124. sessionId,
  125. {
  126. mode: "build",
  127. ...(input.catalog ? { pluginReferenceCatalog: input.catalog } : {}),
  128. subagents: {
  129. profiles: [
  130. {
  131. name: "demo:reviewer",
  132. description: "E2E reviewer profile description",
  133. path: "/plugins/demo/agents/reviewer.md",
  134. source: "user",
  135. systemPrompt: "Review the requested files",
  136. },
  137. ],
  138. },
  139. mcp: {
  140. enabled: true,
  141. servers: {
  142. "plugin:demo:main": {
  143. type: "stdio",
  144. command: "node",
  145. args: ["server.js"],
  146. },
  147. },
  148. },
  149. },
  150. {
  151. eventStore: createTestSessionEventStore(),
  152. mcpPort: createMcpPort(statuses),
  153. skillPort: createSkillPort(),
  154. modelFactory: createTestModelFactory({
  155. properties: { supportsMidConversationSystem: true },
  156. async generateText(request: any) {
  157. const messages = request.messages.map((message: any) => ({
  158. role: String(message.role),
  159. text:
  160. typeof message.content === "string"
  161. ? message.content
  162. : JSON.stringify(message.content),
  163. }));
  164. input.requests.push({
  165. messages,
  166. texts: messages.map((message) => message.text),
  167. toolNames: (request.tools ?? []).map((tool: { name: string }) => tool.name),
  168. });
  169. return {
  170. finishReason: "stop",
  171. providerMetadata: undefined,
  172. text: "done",
  173. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  174. };
  175. },
  176. } as never),
  177. },
  178. );
  179. }
  180. function pluginReferenceIndexes(request: CapturedRequest): number[] {
  181. return request.texts
  182. .map((text, index) => (text.includes("<plugin_reference>") ? index : -1))
  183. .filter((index) => index >= 0);
  184. }
  185. describe("plugin reference runtime injection", () => {
  186. it("injects a single identifiers-only system reminder after the real user message (PLG01)", async () => {
  187. const requests: CapturedRequest[] = [];
  188. const runtime = createRuntime({ catalog: DEMO_CATALOG, requests });
  189. const result = await runtime.executeTurn(
  190. "PLG01_MARKER use [@Demo](plugin://demo@mkt-a) for this",
  191. );
  192. expect(result.response).toBe("done");
  193. const request = requests[0]!;
  194. const reminderIndexes = pluginReferenceIndexes(request);
  195. expect(reminderIndexes).toHaveLength(1);
  196. const reminderText = request.texts[reminderIndexes[0]!]!;
  197. expect(request.messages[reminderIndexes[0]!]?.role).toBe("system");
  198. expect(reminderText).not.toContain("<system-reminder>");
  199. expect(reminderText).toContain("<plugin_reference>");
  200. const pluginReminderText =
  201. reminderText.match(/<plugin_reference>[\s\S]*?<\/plugin_reference>/)?.[0] ?? "";
  202. expect(pluginReminderText).toContain('- id: "demo@mkt-a"');
  203. expect(pluginReminderText).toContain('skills: ["demo:search"]');
  204. expect(pluginReminderText).toContain('mcp_servers: ["plugin:demo:main"]');
  205. expect(pluginReminderText).toContain('subagents: ["demo:reviewer"]');
  206. // identifiers-only:描述、路径、命令、环境变量都不得出现。
  207. expect(pluginReminderText).not.toContain("/plugins/demo");
  208. expect(pluginReminderText).not.toContain("server.js");
  209. expect(pluginReminderText).not.toContain("search things");
  210. expect(pluginReminderText).not.toContain("E2E reviewer profile description");
  211. expect(pluginReminderText).not.toContain("Review the requested files");
  212. const userIndex = request.texts.findIndex((text) => text.includes("PLG01_MARKER"));
  213. expect(userIndex).toBeLessThan(reminderIndexes[0]!);
  214. });
  215. it("skips unknown ids and keeps the conversation running without any reminder (PLG02)", async () => {
  216. const requests: CapturedRequest[] = [];
  217. const runtime = createRuntime({ catalog: DEMO_CATALOG, requests });
  218. const result = await runtime.executeTurn(
  219. "PLG02_MARKER try [@ghost](plugin://ghost@mkt-x) please",
  220. );
  221. expect(result.response).toBe("done");
  222. expect(pluginReferenceIndexes(requests[0]!)).toHaveLength(0);
  223. });
  224. it("resolves against the frozen session catalog only (PLG06)", async () => {
  225. const requests: CapturedRequest[] = [];
  226. // catalog 未注入(模拟 Session 冻结时该 Plugin 尚未启用)→ unknown → 不注入。
  227. const runtime = createRuntime({ requests });
  228. await runtime.executeTurn("PLG06_MARKER [@Demo](plugin://demo@mkt-a)");
  229. expect(pluginReferenceIndexes(requests[0]!)).toHaveLength(0);
  230. });
  231. it("re-parses on every execution and re-intersects with live inventory (PLG07)", async () => {
  232. const requests: CapturedRequest[] = [];
  233. const statuses = connectedStatus();
  234. const runtime = createRuntime({ catalog: DEMO_CATALOG, statuses, requests });
  235. await runtime.executeTurn("PLG07_TURN1 [@Demo](plugin://demo@mkt-a)");
  236. // 模拟 MCP 断线:live status() 变化,冻结 catalog 与已发现 Skill 不变。
  237. statuses["plugin:demo:main"] = {
  238. status: "disconnected",
  239. transport: "stdio",
  240. toolCount: 0,
  241. updatedAt: "later",
  242. };
  243. await runtime.executeTurn("PLG07_TURN2 [@Demo](plugin://demo@mkt-a)");
  244. const secondRequest = requests[1]!;
  245. const reminderIndexes = pluginReferenceIndexes(secondRequest);
  246. // 第一轮 reminder 作为 append-only 历史保留;第二轮按 live inventory 生成新 reminder。
  247. expect(reminderIndexes).toHaveLength(2);
  248. const latestReminder = secondRequest.texts[reminderIndexes.at(-1)!]!;
  249. expect(latestReminder).toContain("mcp_servers: []");
  250. expect(latestReminder).toContain('skills: ["demo:search"]');
  251. });
  252. it("parses only persisted canonical displayInput, never an expanded command prompt (PLG07)", async () => {
  253. const requests: CapturedRequest[] = [];
  254. const runtime = createRuntime({ catalog: DEMO_CATALOG, requests });
  255. // 自定义命令模板展开后的模型输入即使带 plugin://,也不能凭空获得用户引用语义。
  256. await runtime.executeTurn("expanded template [@Demo](plugin://demo@mkt-a)", undefined, {
  257. displayInput: "/template-without-reference",
  258. });
  259. expect(pluginReferenceIndexes(requests[0]!)).toHaveLength(0);
  260. // 反向证明:权威 canonical displayInput 有引用时,即使 runtime prompt 本身没有链接也应注入。
  261. await runtime.executeTurn("expanded template without a plugin link", undefined, {
  262. displayInput: "use [@Demo](plugin://demo@mkt-a)",
  263. });
  264. expect(pluginReferenceIndexes(requests[1]!)).toHaveLength(1);
  265. });
  266. it("excludes MCP servers whose last visible tool is hidden for this turn (PLG10)", async () => {
  267. const requests: CapturedRequest[] = [];
  268. const runtime = createRuntime({ catalog: DEMO_CATALOG, requests });
  269. await runtime.executeTurn("PLG10_MARKER [@Demo](plugin://demo@mkt-a)", undefined, {
  270. toolDisallowlist: ["mcp__plugin_demo_main__lookup"],
  271. });
  272. const request = requests[0]!;
  273. const reminderIndexes = pluginReferenceIndexes(request);
  274. expect(reminderIndexes).toHaveLength(1);
  275. const reminder = request.texts[reminderIndexes[0]!]!;
  276. expect(reminder).toContain('skills: ["demo:search"]');
  277. expect(reminder).toContain("mcp_servers: []");
  278. expect(request.toolNames).not.toContain("mcp__plugin_demo_main__lookup");
  279. });
  280. it("does not parse model-only runtime inputs (PLG07 边界)", async () => {
  281. const requests: CapturedRequest[] = [];
  282. const runtime = createRuntime({ catalog: DEMO_CATALOG, requests });
  283. await runtime.executeTurn("PLG_MODEL_ONLY [@Demo](plugin://demo@mkt-a)", undefined, {
  284. inputVisibility: "model-only",
  285. inputSource: "goal-continuation",
  286. });
  287. expect(pluginReferenceIndexes(requests[0]!)).toHaveLength(0);
  288. });
  289. it("persists the reminder as a model-only notice without changing TurnStarted input (PLG08)", async () => {
  290. const requests: CapturedRequest[] = [];
  291. const runtime = createRuntime({ catalog: DEMO_CATALOG, requests });
  292. const persistNotice = vi.spyOn(
  293. runtime as unknown as {
  294. persistSyntheticUserNoticeForSession: (...args: any[]) => Promise<void>;
  295. },
  296. "persistSyntheticUserNoticeForSession",
  297. );
  298. const result = await runtime.executeTurn("PLG08_MARKER [@Demo](plugin://demo@mkt-a)");
  299. const turnStarted = result.events.find((event) => event.type === "turn_started");
  300. const payload = (turnStarted?.payload ?? {}) as { input?: string };
  301. // 用户可见输入保持 canonical 原文;reminder 不混入 TurnStarted input,也不是真实 user message。
  302. expect(payload.input).toContain("PLG08_MARKER");
  303. expect(payload.input ?? "").not.toContain("<plugin_reference>");
  304. expect(
  305. persistNotice.mock.calls.filter(([notice]) => notice.source === "plugin_reference"),
  306. ).toHaveLength(1);
  307. expect(persistNotice).toHaveBeenCalledWith(
  308. expect.objectContaining({
  309. sessionId: runtime.getSessionId(),
  310. source: "plugin_reference",
  311. text: expect.stringContaining("<plugin_reference>"),
  312. }),
  313. );
  314. });
  315. });