Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeSkillDispatch.ts

58 lines2.4 KB

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;
21​
22export function planClaudeSkillDispatch(
23 prompt: string,
24 skills: ReadonlyMap<string, ClaudeSkillTarget>,
25): ClaudeSkillDispatch | undefined {
26 const mentions = [...prompt.matchAll(SKILL_MENTION_PATTERN)].flatMap((match) => {
27 const name = match[2] ?? "";
28 const skill = skills.get(name);
29 if (!skill) return [];
30 const start = (match.index ?? 0) + (match[1]?.length ?? 0);
31 return [{ name, skill, start, end: (match.index ?? 0) + match[0].length }];
32 });
33 const last = mentions.at(-1);
34 if (!last) {
35 return undefined;
36 }
37​
38 // Only the final skill gets native expansion. Earlier user-only skills need
39 // a fallback to their raw file because Claude's Skill tool refuses them.
40 const annotated = new Set([last.name]);
41 let promptWithInlineSlashes = "";
42 let cursor = 0;
43 for (const mention of mentions) {
44 promptWithInlineSlashes += `${prompt.slice(cursor, mention.start)}/${mention.name}`;
45 if (mention.skill.userInvocationOnly === true && !annotated.has(mention.name)) {
46 promptWithInlineSlashes += ` [The user invoked this skill. Follow the instructions at: ${mention.skill.path}]`;
47 annotated.add(mention.name);
48 }
49 cursor = mention.end;
50 }
51 promptWithInlineSlashes = `${promptWithInlineSlashes}${prompt.slice(cursor)}`.trimEnd();
52​
53 return {
54 leadingText:
55 prompt.slice(0, last.start).trim().length > 0 ? promptWithInlineSlashes : undefined,
56 commandText: `/${last.name}${prompt.slice(last.end)}`.trimEnd(),
57 };