slashCommandHelpers.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. /**
  2. * slashCommandHelpers — 纯函数辅助工具,供 SlashCommandPlugin.tsx 使用
  3. */
  4. import { $getRoot, $getSelection, $isRangeSelection, $isTextNode } from "lexical";
  5. import type { AgentSummary, Locale, SkillSummary, ZCodeSlashCommand } from "@zcode/shared";
  6. import type { MentionItem } from "@/mentions/mentionTypes.js";
  7. import { mapSubagentsToMentionItemsForTest } from "@/mentions/providers/subagentsMentionProvider.js";
  8. import { mapSkillsToMentionItemsForTest } from "@/mentions/providers/skillsMentionProvider.js";
  9. import {
  10. extractActivePromptInputTrigger,
  11. getActivePromptInputTokenTailLength,
  12. } from "./lib/promptInputTriggers.js";
  13. import type { PromptInputSuggestionItem } from "./lib/promptInputTriggers.js";
  14. export interface SlashCommandPluginProps {
  15. container?: HTMLElement | null;
  16. workspacePath: string;
  17. workspaceIdentity?: string;
  18. /** 已有 Session 的 id;null/undefined 表示新建草稿,决定 Skill catalog authority。 */
  19. sessionId?: string | null;
  20. disabled?: boolean;
  21. excludedCommandNames?: readonly string[];
  22. /**
  23. * App 层本地命令(如 `/side`)。命令目录仍以 CLI catalog 为权威;这里只允许渲染层
  24. * 追加"选中即执行 UI 行为"的命令,不参与发送,也不写回 CLI 命令列表。
  25. */
  26. appCommands?: readonly AppSlashCommand[];
  27. }
  28. /** App 层斜杠命令:选中即执行 UI 行为(不插入 mention、不发送)。 */
  29. export interface AppSlashCommand {
  30. /** 命令值(不含 `/`),如 "side"。 */
  31. value: string;
  32. /** 本地化描述,直接展示在 `/` 面板。 */
  33. description: string;
  34. /** 额外搜索关键词;应同时包含中英文别名,保证两种输入习惯都能搜到。 */
  35. keywords?: readonly string[];
  36. /** 选中命令后立即执行的 UI 行为。 */
  37. run: () => void;
  38. }
  39. const APP_SLASH_SUGGESTION_ID_PREFIX = "app-slash:";
  40. export function buildAppSlashCommandSuggestions(
  41. commands: readonly AppSlashCommand[],
  42. ): PromptInputSuggestionItem[] {
  43. return commands.flatMap((command) => {
  44. const value = normalizeSlashCommandValue(command.value);
  45. if (!value) {
  46. return [];
  47. }
  48. return [
  49. {
  50. id: `${APP_SLASH_SUGGESTION_ID_PREFIX}${value}`,
  51. trigger: "/",
  52. value,
  53. label: `/${value}`,
  54. description: command.description,
  55. keywords: [...new Set([value, command.description, ...(command.keywords ?? [])])],
  56. },
  57. ];
  58. });
  59. }
  60. export function isAppSlashCommandSuggestion(suggestion: PromptInputSuggestionItem): boolean {
  61. return suggestion.id.startsWith(APP_SLASH_SUGGESTION_ID_PREFIX);
  62. }
  63. /**
  64. * `/side` 门禁:草稿态没有父 session 可挂 child,辅助对话自身不允许再开辅助对话,
  65. * 只读与手机 viewport 与固定入口保持一致地隐藏。
  66. */
  67. export function shouldOfferSideSlashCommand(options: {
  68. isDraft: boolean;
  69. selectionSideChat: boolean;
  70. readOnly: boolean;
  71. isMobileViewport: boolean;
  72. }): boolean {
  73. return (
  74. !options.isDraft && !options.selectionSideChat && !options.readOnly && !options.isMobileViewport
  75. );
  76. }
  77. export function normalizeSlashCommandValue(name: string): string {
  78. // ZCode Agent 在远端可能直接返回 "/init" 作为命令名。
  79. // UI 的 value 需要去掉前导斜杠,否则插入 markdown 时会变成 "//init",并影响 / 面板匹配。
  80. return name.trim().replace(/^\/+/, "");
  81. }
  82. export function buildSlashSuggestions(commands: ZCodeSlashCommand[]): PromptInputSuggestionItem[] {
  83. return commands.flatMap((command) => {
  84. const value = normalizeSlashCommandValue(command.name);
  85. // UI 曾同时维护内建白名单、GLM `/goal` fallback 和 v4 追加目录,
  86. // CLI catalog 丢失时仍会显示部分命令,掩盖 `/init` 与自定义命令缺失。命令发现
  87. // 统一以 CLI protocol catalog 为权威,UI 不再追加命令或维护内建白名单。
  88. if (!value) {
  89. return [];
  90. }
  91. return [
  92. {
  93. id: `slash:${value}`,
  94. trigger: "/",
  95. value,
  96. label: command.inputHint?.trim() || `/${value}`,
  97. description: command.description,
  98. keywords: [...new Set([value, command.name, command.description, command.inputHint ?? ""])],
  99. },
  100. ];
  101. });
  102. }
  103. export function buildSubagentSuggestions(
  104. agents: Array<
  105. Pick<
  106. AgentSummary,
  107. "id" | "name" | "description" | "path" | "scope" | "source" | "enabled" | "modelSelection"
  108. >
  109. >,
  110. ): PromptInputSuggestionItem[] {
  111. return mapSubagentsToMentionItemsForTest(agents).map((item) =>
  112. mapSubagentMentionItemToSuggestion(item),
  113. );
  114. }
  115. export function buildSkillSuggestions(
  116. skills: Array<
  117. Pick<SkillSummary, "id" | "name" | "description" | "path" | "scope" | "pluginName">
  118. >,
  119. locale?: Locale,
  120. ): PromptInputSuggestionItem[] {
  121. return mapSkillsToMentionItemsForTest(skills, locale).map((item) => ({
  122. id: item.id,
  123. trigger: "/",
  124. value: item.value,
  125. label: `$${item.value}`,
  126. description: item.description,
  127. keywords: [...new Set([...(item.keywords ?? []), "skill", "skills", item.value])],
  128. data: item.data,
  129. }));
  130. }
  131. function mapSubagentMentionItemToSuggestion(item: MentionItem): PromptInputSuggestionItem {
  132. return {
  133. id: item.id,
  134. trigger: "/",
  135. value: item.value,
  136. label: item.label,
  137. description: item.description,
  138. keywords: [...new Set([...(item.keywords ?? []), "subagent", "agent"])],
  139. data: item.data,
  140. };
  141. }
  142. export function replaceActiveSlashToken(
  143. textBeforeCursor: string,
  144. textAfterCursor: string,
  145. replacementToken: string,
  146. ) {
  147. const activeTrigger = extractActivePromptInputTrigger(textBeforeCursor);
  148. if (!activeTrigger || activeTrigger.trigger !== "/") {
  149. return null;
  150. }
  151. const tokenStart = textBeforeCursor.length - activeTrigger.query.length - 1;
  152. const tailLength = getActivePromptInputTokenTailLength(
  153. activeTrigger,
  154. textAfterCursor,
  155. replacementToken,
  156. );
  157. const prefix = textBeforeCursor.slice(0, tokenStart);
  158. const suffix = textAfterCursor.slice(tailLength);
  159. return {
  160. cursorOffset: prefix.length + replacementToken.length + 1,
  161. text: `${prefix}${replacementToken} ${suffix}`,
  162. };
  163. }
  164. export function getTextAroundCursor() {
  165. const selection = $getSelection();
  166. if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
  167. return null;
  168. }
  169. const anchor = selection.anchor;
  170. if (anchor.type !== "text") {
  171. return {
  172. textAfterCursor: "",
  173. textBeforeCursor: $getRoot().getTextContent(),
  174. };
  175. }
  176. const node = anchor.getNode();
  177. if (!$isTextNode(node)) {
  178. return null;
  179. }
  180. const textContent = node.getTextContent();
  181. return {
  182. textAfterCursor: textContent.slice(anchor.offset),
  183. textBeforeCursor: textContent.slice(0, anchor.offset),
  184. };
  185. }