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

ClaudeSkillDispatch.ts

66 lines2.7 KB

1import type { ServerProviderSkill } from "@t3tools/contracts";
2​
3/**
4 * Claude Code's only user-side invocation is a text block whose first character
5 * is `/`: the harness expands `/name args` into the SKILL.md body, and every
6 * character after the name (newlines included) arrives as `ARGUMENTS`. Only one
7 * skill expands per message; a second `/x` becomes argument text
8 * ([#87113](https://github.com/anthropics/claude-code/issues/87113)).
9 */
10​
11/**
12 * Same token shape the composer and timeline chips recognise
13 * (`packages/shared/src/composerInlineTokens.ts`), so a rendered chip and a
14 * dispatched skill are always the same set.
15 */
16const SKILL_MENTION_PATTERN =
17 /(^|\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;
18​
19export type ClaudeSkillTarget = Pick<ServerProviderSkill, "path" | "userInvocationOnly">;
20​
21export interface ClaudeSkillDispatch {
22 /** The whole prompt with mentions as `/name`, or `undefined` when the mention opens it. */
23 readonly leadingText: string | undefined;
24 /** `/name` plus the trailing text, ready to be the message's last text block. */
25 readonly commandText: string;
26 readonly skillName: string;
28​
29export function planClaudeSkillDispatch(
30 prompt: string,
31 skills: ReadonlyMap<string, ClaudeSkillTarget>,
32): ClaudeSkillDispatch | undefined {
33 const mentions = [...prompt.matchAll(SKILL_MENTION_PATTERN)].flatMap((match) => {
34 const name = match[2] ?? "";
35 const skill = skills.get(name);
36 if (!skill) return [];
37 const start = (match.index ?? 0) + (match[1]?.length ?? 0);
38 return [{ name, skill, start, end: (match.index ?? 0) + match[0].length }];
39 });
40 const last = mentions.at(-1);
41 if (!last) {
42 return undefined;
43 }
44​
45 // Only the final skill gets native expansion. Earlier user-only skills need
46 // a fallback to their raw file because Claude's Skill tool refuses them.
47 const annotated = new Set([last.name]);
48 let promptWithInlineSlashes = "";
49 let cursor = 0;
50 for (const mention of mentions) {
51 promptWithInlineSlashes += `${prompt.slice(cursor, mention.start)}/${mention.name}`;
52 if (mention.skill.userInvocationOnly === true && !annotated.has(mention.name)) {
53 promptWithInlineSlashes += ` [The user invoked this skill. Follow the instructions at: ${mention.skill.path}]`;
54 annotated.add(mention.name);
55 }
56 cursor = mention.end;
57 }
58 promptWithInlineSlashes = `${promptWithInlineSlashes}${prompt.slice(cursor)}`.trimEnd();
59​
60 return {
61 leadingText:
62 prompt.slice(0, last.start).trim().length > 0 ? promptWithInlineSlashes : undefined,
63 commandText: `/${last.name}${prompt.slice(last.end)}`.trimEnd(),
64 skillName: last.name,
65 };