Open History to see the last commit
1import type { ServerProviderSkill } from "@t3tools/contracts";
2
3/**
4 * Claude expands one skill per message only when `/name` starts the text block.
5 * Everything after the name, including newlines or a second `/x`, becomes `ARGUMENTS`.
6 * https://github.com/anthropics/claude-code/issues/87113
7 */
8
9/** Match packages/shared/src/composerInlineTokens.ts so displayed chips and dispatched skills accept the same tokens. */
10const SKILL_MENTION_PATTERN =
11 /(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|$)/gu;
12
13export type ClaudeSkillTarget = Pick<ServerProviderSkill, "path" | "userInvocationOnly">;
14
15export interface ClaudeSkillDispatch {
16 /** The whole prompt with mentions as `/name`, or `undefined` when the mention opens it. */
17 readonly leadingText: string | undefined;
18 /** `/name` plus the trailing text, ready to be the message's last text block. */
19 readonly commandText: string;
20 readonly skillName: string;
21}
22
23export function planClaudeSkillDispatch(
24 prompt: string,
25 skills: ReadonlyMap<string, ClaudeSkillTarget>,
26): ClaudeSkillDispatch | undefined {
27 const mentions = [...prompt.matchAll(SKILL_MENTION_PATTERN)].flatMap((match) => {
28 const name = match[2] ?? "";
29 const skill = skills.get(name);
30 if (!skill) return [];
31 const start = (match.index ?? 0) + (match[1]?.length ?? 0);
32 return [{ name, skill, start, end: (match.index ?? 0) + match[0].length }];
33 });
34 const last = mentions.at(-1);
35 if (!last) {
36 return undefined;
37 }
38
39 // Only the final skill gets native expansion. Earlier user-only skills need
40 // a fallback to their raw file because Claude's Skill tool refuses them.
41 const annotated = new Set([last.name]);
42 let promptWithInlineSlashes = "";
43 let cursor = 0;
44 for (const mention of mentions) {
45 promptWithInlineSlashes += `${prompt.slice(cursor, mention.start)}/${mention.name}`;
46 if (mention.skill.userInvocationOnly === true && !annotated.has(mention.name)) {
47 promptWithInlineSlashes += ` [The user invoked this skill. Follow the instructions at: ${mention.skill.path}]`;
48 annotated.add(mention.name);
49 }
50 cursor = mention.end;
51 }
52 promptWithInlineSlashes = `${promptWithInlineSlashes}${prompt.slice(cursor)}`.trimEnd();
53
54 return {
55 leadingText:
56 prompt.slice(0, last.start).trim().length > 0 ? promptWithInlineSlashes : undefined,
57 commandText: `/${last.name}${prompt.slice(last.end)}`.trimEnd(),
58 skillName: last.name,
59 };
60}