plugin-reference.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. // PLG02-PLG05/PLG10 机制单测(docs/plugin-reference-mention.md、
  2. // docs/conversation-session-case-catalog.md PLG 组):
  3. // 严格 URI 解析、label 欺骗、未知/禁用/冲突 fail closed、live 交集、去重与上限、模板序列化。
  4. import { describe, expect, it } from "vitest";
  5. import type { PluginMetadata, PluginReferenceCatalog } from "@zcode/contracts";
  6. import {
  7. buildPluginReferenceCatalog,
  8. buildPluginReferenceReminderBody,
  9. extractPluginReferences,
  10. isValidPluginStableId,
  11. MAX_PLUGIN_REFERENCE_REMINDER_BYTES,
  12. MAX_PLUGIN_REFERENCES_PER_TURN,
  13. type LivePluginMcpServer,
  14. type LivePluginSkill,
  15. type LivePluginSubagent,
  16. } from "../src/plugin-reference/index.js";
  17. function pluginMetadata(
  18. overrides: Partial<PluginMetadata> & { id: string; name: string; marketplace: string },
  19. ): PluginMetadata {
  20. return {
  21. commandRootCount: 0,
  22. components: [],
  23. dataPath: `/data/${overrides.name}`,
  24. declaredMcpServerNames: [],
  25. enabled: true,
  26. hookDetails: [],
  27. manifestPath: `/plugins/${overrides.name}/plugin.json`,
  28. mcpServerNames: [],
  29. rootPath: `/plugins/${overrides.name}`,
  30. skillCount: 0,
  31. skillRootCount: 0,
  32. source: "cache",
  33. ...overrides,
  34. };
  35. }
  36. function catalogWith(
  37. entries: Partial<PluginReferenceCatalog["plugins"][number]>[],
  38. ): PluginReferenceCatalog {
  39. return {
  40. plugins: entries.map((entry) => ({
  41. pluginId: "demo@mkt-a",
  42. name: "demo",
  43. marketplace: "mkt-a",
  44. enabled: true,
  45. conflictingPluginIds: [],
  46. skillQualifiedNames: [],
  47. mcpServerNames: [],
  48. subagentNames: [],
  49. rootPath: "/plugins/demo",
  50. ...entry,
  51. })),
  52. };
  53. }
  54. const DEMO_SKILL: LivePluginSkill = {
  55. qualifiedName: "demo:search",
  56. pluginName: "demo",
  57. rootPath: "/plugins/demo/skills",
  58. source: "plugin",
  59. };
  60. const DEMO_MCP: LivePluginMcpServer = {
  61. serverName: "plugin:demo:main",
  62. connected: true,
  63. providerVisibleToolCount: 2,
  64. };
  65. const DEMO_SUBAGENT: LivePluginSubagent = {
  66. name: "demo:reviewer",
  67. path: "/plugins/demo/agents/reviewer.md",
  68. };
  69. describe("plugin reference strict URI parser", () => {
  70. it("extracts stable ids from canonical markdown links in first-appearance order", () => {
  71. const { references, invalidCount, truncatedCount } = extractPluginReferences(
  72. "check [@B](plugin://b@mkt) then [@A](plugin://a@mkt) and [@B again](plugin://b@mkt)",
  73. );
  74. expect(references).toEqual(["b@mkt", "a@mkt"]);
  75. expect(invalidCount).toBe(0);
  76. expect(truncatedCount).toBe(0);
  77. });
  78. it("takes identity only from the destination, never from the label", () => {
  79. const { references } = extractPluginReferences(
  80. "[@innocent-name](plugin://evil@mkt) and [@evil](./README.md)",
  81. );
  82. expect(references).toEqual(["evil@mkt"]);
  83. });
  84. it("rejects scheme case variants, query, fragment, credentials, percent and control characters", () => {
  85. const invalidInputs = [
  86. "[@x](Plugin://demo@mkt)",
  87. "[@x](PLUGIN://demo@mkt)",
  88. "[@x](plugin://demo@mkt?inject=1)",
  89. "[@x](plugin://demo@mkt#frag)",
  90. "[@x](plugin://user:pass@demo@mkt)",
  91. "[@x](plugin://demo%40mkt)",
  92. "[@x](<plugin://demo@mkt>)",
  93. "[@x](plugin://demo)",
  94. "[@x](plugin://@mkt)",
  95. "[@x](plugin://demo@)",
  96. ];
  97. for (const input of invalidInputs) {
  98. const { references } = extractPluginReferences(input);
  99. expect(references, input).toEqual([]);
  100. }
  101. });
  102. it("caps per-turn references and reports truncation", () => {
  103. const text = Array.from(
  104. { length: MAX_PLUGIN_REFERENCES_PER_TURN + 3 },
  105. (_, index) => `[@p${index}](plugin://p${index}@mkt)`,
  106. ).join(" ");
  107. const { references, truncatedCount } = extractPluginReferences(text);
  108. expect(references).toHaveLength(MAX_PLUGIN_REFERENCES_PER_TURN);
  109. expect(truncatedCount).toBe(3);
  110. });
  111. it("validates stable id charset and single separator strictly", () => {
  112. expect(isValidPluginStableId("demo@mkt-a")).toBe(true);
  113. expect(isValidPluginStableId("demo.plugin_1@zcode-plugins-official")).toBe(true);
  114. expect(isValidPluginStableId("demo@mkt@extra")).toBe(false);
  115. expect(isValidPluginStableId("demo mkt@a")).toBe(false);
  116. expect(isValidPluginStableId(`a@${"b".repeat(300)}`)).toBe(false);
  117. expect(isValidPluginStableId("-demo@mkt")).toBe(false);
  118. });
  119. });
  120. describe("plugin reference catalog builder", () => {
  121. it("marks enabled same-manifest-name plugins as mutually conflicting (fail closed)", () => {
  122. const catalog = buildPluginReferenceCatalog([
  123. pluginMetadata({ id: "demo@mkt-a", name: "demo", marketplace: "mkt-a" }),
  124. pluginMetadata({ id: "demo@mkt-b", name: "demo", marketplace: "mkt-b" }),
  125. pluginMetadata({ id: "other@mkt-a", name: "other", marketplace: "mkt-a" }),
  126. ]);
  127. const byId = new Map(catalog.plugins.map((entry) => [entry.pluginId, entry]));
  128. expect(byId.get("demo@mkt-a")?.conflictingPluginIds).toEqual(["demo@mkt-b"]);
  129. expect(byId.get("demo@mkt-b")?.conflictingPluginIds).toEqual(["demo@mkt-a"]);
  130. expect(byId.get("other@mkt-a")?.conflictingPluginIds).toEqual([]);
  131. });
  132. it("does not treat a disabled duplicate as a conflict and keeps disabled entries for diagnostics", () => {
  133. const catalog = buildPluginReferenceCatalog([
  134. pluginMetadata({ id: "demo@mkt-a", name: "demo", marketplace: "mkt-a" }),
  135. pluginMetadata({ id: "demo@mkt-b", name: "demo", marketplace: "mkt-b", enabled: false }),
  136. ]);
  137. const byId = new Map(catalog.plugins.map((entry) => [entry.pluginId, entry]));
  138. expect(byId.get("demo@mkt-a")?.conflictingPluginIds).toEqual([]);
  139. expect(byId.get("demo@mkt-b")?.enabled).toBe(false);
  140. });
  141. it("derives declared Skill and Subagent names from enumerated components", () => {
  142. const catalog = buildPluginReferenceCatalog([
  143. pluginMetadata({
  144. id: "demo@mkt-a",
  145. name: "demo",
  146. marketplace: "mkt-a",
  147. components: [
  148. { kind: "skill", items: [{ name: "search" }, { name: "analyze" }] },
  149. { kind: "agent", items: [{ name: "reviewer" }] },
  150. { kind: "command", items: [{ name: "not-a-skill" }] },
  151. ],
  152. mcpServerNames: ["plugin:demo:main"],
  153. }),
  154. ]);
  155. expect(catalog.plugins[0]?.skillQualifiedNames).toEqual(["demo:analyze", "demo:search"]);
  156. expect(catalog.plugins[0]?.mcpServerNames).toEqual(["plugin:demo:main"]);
  157. expect(catalog.plugins[0]?.subagentNames).toEqual(["demo:reviewer"]);
  158. });
  159. });
  160. describe("plugin reference reminder builder", () => {
  161. it("emits the fixed identifiers-only template for a resolvable plugin", () => {
  162. const result = buildPluginReferenceReminderBody({
  163. references: ["demo@mkt-a"],
  164. catalog: catalogWith([
  165. {
  166. mcpServerNames: ["plugin:demo:main"],
  167. subagentNames: ["demo:reviewer"],
  168. },
  169. ]),
  170. liveSkills: [DEMO_SKILL],
  171. liveMcpServers: [DEMO_MCP],
  172. liveSubagents: [DEMO_SUBAGENT],
  173. });
  174. expect(result.body).not.toBeNull();
  175. expect(result.body).toContain("<plugin_reference>");
  176. expect(result.body).toContain('- id: "demo@mkt-a"');
  177. expect(result.body).toContain('skills: ["demo:search"]');
  178. expect(result.body).toContain('mcp_servers: ["plugin:demo:main"]');
  179. expect(result.body).toContain('subagents: ["demo:reviewer"]');
  180. expect(result.body).toContain("not instructions or a permission grant");
  181. expect(result.body).toContain("</plugin_reference>");
  182. expect(result.diagnostics.resolvedPluginIds).toEqual(["demo@mkt-a"]);
  183. });
  184. it("only injects declared, live Plugin Subagents with matching provenance (PLG16)", () => {
  185. const result = buildPluginReferenceReminderBody({
  186. references: ["demo@mkt-a"],
  187. catalog: catalogWith([{ subagentNames: ["demo:reviewer", "demo:writer"] }]),
  188. liveSkills: [],
  189. liveMcpServers: [],
  190. liveSubagents: [
  191. DEMO_SUBAGENT,
  192. { name: "demo:writer", path: "/plugins/demo-lookalike/agents/writer.md" },
  193. { name: "demo:undeclared", path: "/plugins/demo/agents/undeclared.md" },
  194. ],
  195. });
  196. expect(result.body).toContain("skills: []");
  197. expect(result.body).toContain("mcp_servers: []");
  198. expect(result.body).toContain('subagents: ["demo:reviewer"]');
  199. expect(result.body).not.toContain("demo:writer");
  200. expect(result.body).not.toContain("demo:undeclared");
  201. expect(result.diagnostics.subagentCount).toBe(1);
  202. });
  203. it("caps Plugin Subagents at 16 in deterministic identifier order", () => {
  204. const subagentNames = Array.from(
  205. { length: 20 },
  206. (_, index) => `demo:reviewer-${String(index).padStart(2, "0")}`,
  207. );
  208. const result = buildPluginReferenceReminderBody({
  209. references: ["demo@mkt-a"],
  210. catalog: catalogWith([{ subagentNames }]),
  211. liveSkills: [],
  212. liveMcpServers: [],
  213. liveSubagents: subagentNames.map((name) => ({
  214. name,
  215. path: `/plugins/demo/agents/${name}.md`,
  216. })),
  217. });
  218. expect(result.diagnostics.subagentCount).toBe(16);
  219. expect(result.diagnostics.truncated).toBe(true);
  220. expect(result.body).toContain('"demo:reviewer-00"');
  221. expect(result.body).toContain('"demo:reviewer-15"');
  222. expect(result.body).not.toContain('"demo:reviewer-16"');
  223. });
  224. it("rejects invalid and overlong Subagent identifiers without exposing profile data", () => {
  225. const tooLongName = `demo:${"x".repeat(124)}`;
  226. const result = buildPluginReferenceReminderBody({
  227. references: ["demo@mkt-a"],
  228. catalog: catalogWith([
  229. {
  230. subagentNames: ["demo:bad\nidentifier", tooLongName],
  231. },
  232. ]),
  233. liveSkills: [],
  234. liveMcpServers: [],
  235. liveSubagents: [
  236. { name: "demo:bad\nidentifier", path: "/plugins/demo/agents/bad.md" },
  237. { name: tooLongName, path: "/plugins/demo/agents/too-long.md" },
  238. ],
  239. });
  240. expect(result.body).toBeNull();
  241. expect(JSON.stringify(result)).not.toContain("/plugins/demo/agents");
  242. expect(result.diagnostics.skipped).toEqual(
  243. expect.arrayContaining([
  244. { pluginId: "demo@mkt-a", reason: "invalid_identifier" },
  245. { pluginId: "demo@mkt-a", reason: "no_live_capabilities" },
  246. ]),
  247. );
  248. });
  249. it("skips unknown, disabled-in-session and ambiguous references without failing the turn", () => {
  250. const catalog: PluginReferenceCatalog = {
  251. plugins: [
  252. {
  253. pluginId: "conflict@mkt-a",
  254. name: "conflict",
  255. marketplace: "mkt-a",
  256. enabled: true,
  257. conflictingPluginIds: ["conflict@mkt-b"],
  258. skillQualifiedNames: ["conflict:tool"],
  259. mcpServerNames: [],
  260. subagentNames: [],
  261. rootPath: "/plugins/conflict",
  262. },
  263. {
  264. pluginId: "off@mkt-a",
  265. name: "off",
  266. marketplace: "mkt-a",
  267. enabled: false,
  268. conflictingPluginIds: [],
  269. skillQualifiedNames: [],
  270. mcpServerNames: [],
  271. subagentNames: [],
  272. rootPath: "/plugins/off",
  273. },
  274. ],
  275. };
  276. const result = buildPluginReferenceReminderBody({
  277. references: ["nope@mkt-a", "off@mkt-a", "conflict@mkt-a"],
  278. catalog,
  279. liveSkills: [],
  280. liveMcpServers: [],
  281. });
  282. expect(result.body).toBeNull();
  283. expect(result.diagnostics.skipped).toEqual([
  284. { pluginId: "nope@mkt-a", reason: "unknown" },
  285. { pluginId: "off@mkt-a", reason: "disabled_in_session" },
  286. { pluginId: "conflict@mkt-a", reason: "ambiguous" },
  287. ]);
  288. });
  289. it("intersects with live inventory: disconnected or tool-less MCP servers are excluded", () => {
  290. const catalog = catalogWith([{ mcpServerNames: ["plugin:demo:main", "plugin:demo:aux"] }]);
  291. const result = buildPluginReferenceReminderBody({
  292. references: ["demo@mkt-a"],
  293. catalog,
  294. liveSkills: [DEMO_SKILL],
  295. liveMcpServers: [
  296. { serverName: "plugin:demo:main", connected: false, providerVisibleToolCount: 2 },
  297. { serverName: "plugin:demo:aux", connected: true, providerVisibleToolCount: 0 },
  298. ],
  299. });
  300. expect(result.body).toContain("mcp_servers: []");
  301. expect(result.body).toContain('skills: ["demo:search"]');
  302. });
  303. it("enforces skill provenance by plugin name and rootPath prefix", () => {
  304. const catalog = catalogWith([{}]);
  305. const foreignSkills: LivePluginSkill[] = [
  306. { ...DEMO_SKILL, pluginName: "other" },
  307. { ...DEMO_SKILL, rootPath: "/plugins/demo-lookalike/skills" },
  308. { ...DEMO_SKILL, source: "user" },
  309. ];
  310. const result = buildPluginReferenceReminderBody({
  311. references: ["demo@mkt-a"],
  312. catalog,
  313. liveSkills: foreignSkills,
  314. liveMcpServers: [],
  315. });
  316. expect(result.body).toBeNull();
  317. expect(result.diagnostics.skipped).toEqual([
  318. { pluginId: "demo@mkt-a", reason: "no_live_capabilities" },
  319. ]);
  320. });
  321. it("only counts MCP servers declared in the frozen catalog entry", () => {
  322. const catalog = catalogWith([{ mcpServerNames: [] }]);
  323. const result = buildPluginReferenceReminderBody({
  324. references: ["demo@mkt-a"],
  325. catalog,
  326. liveSkills: [],
  327. liveMcpServers: [DEMO_MCP],
  328. });
  329. expect(result.body).toBeNull();
  330. });
  331. it("omits the entire reminder when every referenced plugin has no live capability", () => {
  332. const result = buildPluginReferenceReminderBody({
  333. references: ["demo@mkt-a"],
  334. catalog: catalogWith([{}]),
  335. liveSkills: [],
  336. liveMcpServers: [],
  337. });
  338. expect(result.body).toBeNull();
  339. expect(result.diagnostics.resolvedPluginIds).toEqual([]);
  340. });
  341. it("dedupes and sorts capability identifiers and JSON-escapes dynamic values", () => {
  342. const catalog = catalogWith([{ mcpServerNames: ["plugin:demo:main"] }]);
  343. const result = buildPluginReferenceReminderBody({
  344. references: ["demo@mkt-a"],
  345. catalog,
  346. liveSkills: [
  347. { ...DEMO_SKILL, qualifiedName: "demo:zeta" },
  348. { ...DEMO_SKILL, qualifiedName: "demo:alpha" },
  349. { ...DEMO_SKILL, qualifiedName: "demo:alpha" },
  350. ],
  351. liveMcpServers: [DEMO_MCP],
  352. });
  353. expect(result.body).toContain('skills: ["demo:alpha", "demo:zeta"]');
  354. // JSON.stringify 转义由固定引用格式承载:标识符本身经过字符集校验,不含引号。
  355. expect(result.body).not.toContain("skills: [demo:alpha");
  356. });
  357. it("rejects capability identifiers outside the allowed charset (fail closed per entry)", () => {
  358. const catalog = catalogWith([{}]);
  359. const result = buildPluginReferenceReminderBody({
  360. references: ["demo@mkt-a"],
  361. catalog,
  362. liveSkills: [{ ...DEMO_SKILL, qualifiedName: "demo:evil\ninjection" }],
  363. liveMcpServers: [],
  364. });
  365. expect(result.body).toBeNull();
  366. expect(result.diagnostics.skipped).toEqual(
  367. expect.arrayContaining([
  368. { pluginId: "demo@mkt-a", reason: "invalid_identifier" },
  369. { pluginId: "demo@mkt-a", reason: "no_live_capabilities" },
  370. ]),
  371. );
  372. });
  373. it("keeps plugins in reference order and truncates over per-turn capability budgets", () => {
  374. const catalog: PluginReferenceCatalog = {
  375. plugins: Array.from({ length: 3 }, (_, index) => ({
  376. pluginId: `p${index}@mkt`,
  377. name: `p${index}`,
  378. marketplace: "mkt",
  379. enabled: true,
  380. conflictingPluginIds: [],
  381. skillQualifiedNames: [],
  382. mcpServerNames: [],
  383. subagentNames: [],
  384. rootPath: `/plugins/p${index}`,
  385. })),
  386. };
  387. const liveSkills: LivePluginSkill[] = catalog.plugins.flatMap((entry) =>
  388. Array.from({ length: 20 }, (_, skillIndex) => ({
  389. qualifiedName: `${entry.name}:s${String(skillIndex).padStart(2, "0")}`,
  390. pluginName: entry.name,
  391. rootPath: `${entry.rootPath}/skills`,
  392. source: "plugin",
  393. })),
  394. );
  395. const result = buildPluginReferenceReminderBody({
  396. references: ["p0@mkt", "p1@mkt", "p2@mkt"],
  397. catalog,
  398. liveSkills,
  399. liveMcpServers: [],
  400. });
  401. // 32 个 Skill 预算:p0 占 20、p1 占 12(截断)、p2 无预算整条跳过。
  402. expect(result.diagnostics.resolvedPluginIds).toEqual(["p0@mkt", "p1@mkt"]);
  403. expect(result.diagnostics.skillCount).toBe(32);
  404. expect(result.diagnostics.truncated).toBe(true);
  405. expect(result.diagnostics.skipped).toEqual(
  406. expect.arrayContaining([{ pluginId: "p2@mkt", reason: "no_live_capabilities" }]),
  407. );
  408. });
  409. it("stays under the reminder byte budget by dropping trailing plugins", () => {
  410. // 逼近上限:长 stable ID(≤256)+ 长 capability 标识(≤128),总渲染量超过 8 KiB,
  411. // 验证按用户引用顺序保留前项、从尾部整条丢弃的截断路径。
  412. const idSuffix = "m".repeat(240);
  413. const catalog: PluginReferenceCatalog = {
  414. plugins: Array.from({ length: 8 }, (_, index) => ({
  415. pluginId: `p${index}@${idSuffix}`,
  416. name: `p${index}`,
  417. marketplace: idSuffix,
  418. enabled: true,
  419. conflictingPluginIds: [],
  420. skillQualifiedNames: [],
  421. mcpServerNames: Array.from(
  422. { length: 2 },
  423. (_, serverIndex) => `plugin:p${index}:${"x".repeat(100)}${serverIndex}`,
  424. ),
  425. subagentNames: [],
  426. rootPath: `/plugins/p${index}`,
  427. })),
  428. };
  429. const liveSkills: LivePluginSkill[] = catalog.plugins.flatMap((entry) =>
  430. Array.from({ length: 4 }, (_, skillIndex) => ({
  431. qualifiedName: `${entry.name}:${"s".repeat(120)}${skillIndex}`,
  432. pluginName: entry.name,
  433. rootPath: `${entry.rootPath}/skills`,
  434. source: "plugin",
  435. })),
  436. );
  437. const liveMcpServers: LivePluginMcpServer[] = catalog.plugins.flatMap((entry) =>
  438. entry.mcpServerNames.map((serverName) => ({
  439. serverName,
  440. connected: true,
  441. providerVisibleToolCount: 1,
  442. })),
  443. );
  444. const result = buildPluginReferenceReminderBody({
  445. references: catalog.plugins.map((entry) => entry.pluginId),
  446. catalog,
  447. liveSkills,
  448. liveMcpServers,
  449. });
  450. expect(result.body).not.toBeNull();
  451. expect(Buffer.byteLength(result.body ?? "", "utf8")).toBeLessThanOrEqual(
  452. MAX_PLUGIN_REFERENCE_REMINDER_BYTES,
  453. );
  454. expect(result.diagnostics.truncated).toBe(true);
  455. expect(result.diagnostics.resolvedPluginIds.length).toBeLessThan(catalog.plugins.length);
  456. expect(result.diagnostics.resolvedPluginIds[0]).toBe(catalog.plugins[0]?.pluginId);
  457. });
  458. it("never invents capabilities from tools filtered out by allow/disallow policy", () => {
  459. // provider-visible tool 计数由调用侧按注册表(策略过滤后)给出;计数为 0 时 fail closed。
  460. const catalog = catalogWith([{ mcpServerNames: ["plugin:demo:main"] }]);
  461. const result = buildPluginReferenceReminderBody({
  462. references: ["demo@mkt-a"],
  463. catalog,
  464. liveSkills: [],
  465. liveMcpServers: [
  466. { serverName: "plugin:demo:main", connected: true, providerVisibleToolCount: 0 },
  467. ],
  468. });
  469. expect(result.body).toBeNull();
  470. });
  471. });