plugin-reference.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. export interface EffectivePluginToolGroup {
  2. readonly source: string;
  3. readonly tools: readonly string[];
  4. /** Deferred App tools must be discovered before they can be invoked. */
  5. readonly access?: 'direct' | 'tool_search';
  6. }
  7. export interface EffectivePluginCapabilityInventory {
  8. readonly name: string;
  9. readonly appTools: readonly EffectivePluginToolGroup[];
  10. readonly mcpTools: readonly EffectivePluginToolGroup[];
  11. readonly skills: readonly string[];
  12. }
  13. /**
  14. * Resolve canonical `@Plugin` references against the enabled capability
  15. * inventory for this turn. References must be whitespace-delimited so email
  16. * addresses, prefixes, and punctuation-attached plain text are not treated as
  17. * an explicit Plugin selection.
  18. */
  19. export function detectPluginReferencesForMessages<T extends EffectivePluginCapabilityInventory>(
  20. messages: readonly { content?: string }[],
  21. fallbackText: string,
  22. plugins: readonly T[] | undefined,
  23. ): T[] {
  24. if (!plugins || plugins.length === 0) return [];
  25. const texts =
  26. messages.length === 0
  27. ? [fallbackText]
  28. : messages.flatMap((message) => (message.content?.trim() ? [message.content] : []));
  29. const selected: T[] = [];
  30. const seen = new Set<string>();
  31. for (const text of texts) {
  32. for (const match of detectReferencesInText(text, plugins)) {
  33. const key = normalizedName(match.name);
  34. if (seen.has(key)) continue;
  35. seen.add(key);
  36. selected.push(match);
  37. }
  38. }
  39. return selected;
  40. }
  41. /** Render one self-contained reminder for every Plugin selected in this turn. */
  42. export function buildPluginReferenceReminder(
  43. plugins: readonly EffectivePluginCapabilityInventory[],
  44. ): string | undefined {
  45. if (plugins.length === 0) return undefined;
  46. const blocks = plugins.map((plugin) => {
  47. const name = inlineCode(plugin.name);
  48. return [
  49. `<selected-plugin name="${escapeXml(plugin.name)}">`,
  50. `Referenced as \`@${name}\`.`,
  51. '',
  52. '<connected-app-tools>',
  53. formatAppToolGroups(plugin.appTools),
  54. '</connected-app-tools>',
  55. '',
  56. '<plugin-mcp-tools>',
  57. formatToolGroups(plugin.mcpTools, 'server'),
  58. '</plugin-mcp-tools>',
  59. '',
  60. '<plugin-skills>',
  61. formatSkills(plugin.skills),
  62. '</plugin-skills>',
  63. '</selected-plugin>',
  64. ].join('\n');
  65. });
  66. return [
  67. '<system-reminder>',
  68. 'The user explicitly selected the following Plugin capabilities for this request.',
  69. 'Prefer them when relevant; other tools remain available if needed.',
  70. '',
  71. blocks.join('\n\n'),
  72. '',
  73. 'Only the capabilities listed above are effective for this turn.',
  74. 'Do not invent or claim unavailable Plugin capabilities.',
  75. ...(plugins.some((plugin) => plugin.appTools.some((group) => group.access === 'tool_search'))
  76. ? [
  77. 'For App tools marked `via tool_search + mcp_invoke`, discover the exact tool with `tool_search` before calling it through `mcp_invoke`.',
  78. ]
  79. : []),
  80. 'Before following a listed Skill, call the `skill` tool with its exact name.',
  81. 'The existing tool schemas and loaded SKILL.md content are authoritative.',
  82. '</system-reminder>',
  83. ].join('\n');
  84. }
  85. function formatAppToolGroups(groups: readonly EffectivePluginToolGroup[]): string {
  86. if (groups.length === 0) return 'none';
  87. return [...groups]
  88. .sort((left, right) => {
  89. const sourceOrder = normalizedName(left.source).localeCompare(normalizedName(right.source));
  90. if (sourceOrder !== 0) return sourceOrder;
  91. return (left.access ?? 'direct').localeCompare(right.access ?? 'direct');
  92. })
  93. .map((group) => {
  94. const tools = formatToolNames(group.tools);
  95. const access = group.access === 'tool_search' ? ' via `tool_search` + `mcp_invoke`' : '';
  96. return `- app \`${inlineCode(group.source)}\`${access}: ${tools || 'none'}`;
  97. })
  98. .join('\n');
  99. }
  100. function detectReferencesInText<T extends EffectivePluginCapabilityInventory>(
  101. text: string,
  102. plugins: readonly T[],
  103. ): T[] {
  104. const normalizedText = text.normalize('NFKC');
  105. const matches: Array<{ index: number; plugin: T }> = [];
  106. for (const plugin of plugins) {
  107. const name = normalizedName(plugin.name);
  108. if (!name) continue;
  109. const pattern = new RegExp(`(^|\\s)@${escapeRegExp(name)}(?=\\s|$)`, 'giu');
  110. const match = pattern.exec(normalizedText);
  111. if (!match) continue;
  112. matches.push({ index: match.index + (match[1]?.length ?? 0), plugin });
  113. }
  114. matches.sort((left, right) => left.index - right.index);
  115. return matches.map((match) => match.plugin);
  116. }
  117. function formatToolGroups(
  118. groups: readonly EffectivePluginToolGroup[],
  119. label: 'app' | 'server',
  120. ): string {
  121. if (groups.length === 0) return 'none';
  122. return [...groups]
  123. .sort((left, right) => normalizedName(left.source).localeCompare(normalizedName(right.source)))
  124. .map((group) => {
  125. const tools = formatToolNames(group.tools);
  126. return `- ${label} \`${inlineCode(group.source)}\`: ${tools || 'none'}`;
  127. })
  128. .join('\n');
  129. }
  130. function formatToolNames(tools: readonly string[]): string {
  131. return [...new Set(tools)]
  132. .sort((left, right) => normalizedName(left).localeCompare(normalizedName(right)))
  133. .map((tool) => `\`${inlineCode(tool)}\``)
  134. .join(', ');
  135. }
  136. function formatSkills(skills: readonly string[]): string {
  137. if (skills.length === 0) return 'none';
  138. return [...new Set(skills)]
  139. .sort((left, right) => normalizedName(left).localeCompare(normalizedName(right)))
  140. .map((skill) => `- \`${inlineCode(skill)}\``)
  141. .join('\n');
  142. }
  143. function normalizedName(value: string): string {
  144. return value.trim().normalize('NFKC').toLocaleLowerCase('en-US');
  145. }
  146. function inlineCode(value: string): string {
  147. return escapeXml(value).replace(/`/gu, '\\`');
  148. }
  149. function escapeRegExp(value: string): string {
  150. return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
  151. }
  152. function escapeXml(value: string): string {
  153. return value
  154. .replace(/&/gu, '&amp;')
  155. .replace(/</gu, '&lt;')
  156. .replace(/>/gu, '&gt;')
  157. .replace(/"/gu, '&quot;')
  158. .replace(/'/gu, '&apos;');
  159. }