fix(claude): skills picked from the composer now run (#9128)

Co-authored-by: Rodrigo Brechard <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-01 17:44:13 -07:00
1 parent 9a7b1e21e5
commit ea71a19d41
16 files changed
+1080 -82

No files matched your search

@@ -12,6 +12,7 @@ import {
import {
dedupeProviderSkillsByName,
getProviderSkillsForSlashMenu,
isProviderSkillUserInvocable,
} from "@t3tools/client-runtime/providerSkills";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -114,8 +115,14 @@ export function useComposerCommandMenu({
(item.command === "model" || onUpdateInteractionMode !== undefined),
);
// A provider expands a slash command only when it opens the whole
// message; elsewhere it arrives as literal text. Built-ins apply
// locally and skills insert a `$` mention the server dispatches from
// any position, so only provider commands are position-gated.
const providerCommands: ComposerCommandItem[] = [];
for (const command of selectedProviderStatus?.slashCommands ?? []) {
const expandableCommands =
trigger.rangeStart === 0 ? (selectedProviderStatus?.slashCommands ?? []) : [];
for (const command of expandableCommands) {
if (!command.name.toLowerCase().includes(q)) continue;
// Codex feedback uploads an existing thread's session and logs.
if (
@@ -149,7 +156,7 @@ export function useComposerCommandMenu({
if (trigger.kind === "skill") {
const enabledSkills = dedupeProviderSkillsByName(
(selectedProviderStatus?.skills ?? []).filter((skill) => skill.enabled),
(selectedProviderStatus?.skills ?? []).filter(isProviderSkillUserInvocable),
);
const normalizedQuery = normalizeSearchQuery(trigger.query, {
trimLeadingPattern: /^\$+/,
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vite-plus/test";
import { planClaudeSkillDispatch } from "./ClaudeSkillDispatch.ts";
const SKILLS = new Set(["implement", "review", "re-release-version"]);
describe("planClaudeSkillDispatch", () => {
it("leaves a prompt without a known skill untouched", () => {
expect(planClaudeSkillDispatch("fix the build", SKILLS)).toBeUndefined();
// Not a discovered skill, so it stays prose rather than becoming a command.
expect(planClaudeSkillDispatch("echo $HOME then $unknown", SKILLS)).toBeUndefined();
});
it("moves a mid-prompt mention into a trailing slash command", () => {
expect(planClaudeSkillDispatch("ok, now $implement all the tickets", SKILLS)).toEqual({
leadingText: "ok, now",
commandText: "/implement all the tickets",
skillName: "implement",
});
});
it("keeps a mention that opens the prompt as a single command block", () => {
expect(planClaudeSkillDispatch("$review\nfocus on auth", SKILLS)).toEqual({
leadingText: undefined,
commandText: "/review\nfocus on auth",
skillName: "review",
});
});
it("dispatches the last mention and rewrites earlier ones inline", () => {
expect(planClaudeSkillDispatch("$review the diff, then $implement the fixes", SKILLS)).toEqual({
leadingText: "/review the diff, then",
commandText: "/implement the fixes",
skillName: "implement",
});
});
it("ignores a dollar token glued to other text", () => {
expect(planClaudeSkillDispatch("cost is 5$implement", SKILLS)).toBeUndefined();
});
});
@@ -0,0 +1,78 @@
/**
* ClaudeSkillDispatch — turns `$skill` mentions in a composer prompt into the
* slash invocation Claude Code actually runs.
*
* The composer inserts `$name` for every provider. Codex parses that natively;
* Claude Code does not, and treats it as prose. Claude Code's only user-side
* invocation is a text block whose first character is `/`: the harness
* expands `/name args` into the SKILL.md body, and every character after the
* name (newlines included) arrives as `ARGUMENTS`. Verified against the CLI in
* stream-json mode, which is what the Agent SDK uses:
*
* - The check runs on the LAST text block of the message. Earlier text
* blocks are preserved verbatim, and image blocks may sit before it.
* - Leading whitespace, or a `/name` that starts a later line of the same
* block, is literal text.
* - Only one skill expands per message; a second `/x` becomes argument text
* (anthropics/claude-code#87113). The model still starts the rest through
* its Skill tool when it reads `/name` in the prompt, so earlier mentions
* are rewritten to `/name` inline.
*
* So one mention anywhere in the prompt becomes a guaranteed invocation, and
* the user's text on either side is kept in order.
*
* @module provider/Drivers/ClaudeSkillDispatch
*/
/**
* Same token shape the composer and timeline chips recognise
* (`packages/shared/src/composerInlineTokens.ts`), so a rendered chip and a
* dispatched skill are always the same set.
*/
const SKILL_MENTION_PATTERN = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g;
export interface ClaudeSkillDispatch {
/** Text before the dispatched mention, or `undefined` when it opens the prompt. */
readonly leadingText: string | undefined;
/** `/name` plus the trailing text, ready to be the message's last text block. */
readonly commandText: string;
readonly skillName: string;
}
/**
* Split `prompt` around the last `$skill` mention that names a known skill.
* Returns `undefined` when there is nothing to dispatch, in which case the
* prompt should go out unchanged. Mentions that do not match a discovered
* skill stay literal: a `$HOME` in prose must not become a command.
*/
export function planClaudeSkillDispatch(
prompt: string,
skillNames: ReadonlySet<string>,
): ClaudeSkillDispatch | undefined {
const mentions = [...prompt.matchAll(SKILL_MENTION_PATTERN)].flatMap((match) => {
const name = match[2] ?? "";
if (!skillNames.has(name)) return [];
const start = (match.index ?? 0) + (match[1]?.length ?? 0);
return [{ name, start, end: start + name.length + 1 }];
});
const last = mentions.at(-1);
if (!last) {
return undefined;
}
const leading = prompt.slice(0, last.start);
const trailing = prompt.slice(last.end);
const leadingWithInlineSlashes = mentions
.slice(0, -1)
.reduceRight(
(text, mention) => `${text.slice(0, mention.start)}/${text.slice(mention.start + 1)}`,
leading,
)
.trimEnd();
return {
leadingText: leadingWithInlineSlashes.length > 0 ? leadingWithInlineSlashes : undefined,
commandText: `/${last.name}${trailing}`.trimEnd(),
skillName: last.name,
};
}
@@ -4,7 +4,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { discoverClaudeSkills } from "./ClaudeSkills.ts";
import { discoverClaudeSkills, skillOverrideSettingsPaths } from "./ClaudeSkills.ts";
const writeSkill = Effect.fn(function* (
skillsDir: string,
@@ -66,7 +66,7 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
}),
);
it.effect("discovers project skills from the workspace .agents directory", () =>
it.effect("ignores .agents/skills, which Claude Code does not load", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -74,6 +74,8 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
const configDir = path.join(tempDir, "claude-home");
const workspace = path.join(tempDir, "workspace");
// Verified against the CLI: `/review` here is answered with
// `Unknown command`, so offering it would dispatch a dead command.
yield* writeSkill(
path.join(workspace, ".agents", "skills"),
"review",
@@ -82,19 +84,11 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
assert.deepEqual(skills, [
{
name: "review",
path: path.join(workspace, ".agents", "skills", "review", "SKILL.md"),
enabled: true,
scope: "project",
description: "Review the changes.",
},
]);
assert.deepEqual(skills, []);
}),
);
it.effect("prefers workspace .claude skills on three-way name collisions", () =>
it.effect("prefers user skills on name collisions even with a stray .agents copy", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -123,49 +117,16 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
assert.deepEqual(skills, [
{
name: "deploy",
path: path.join(workspace, ".claude", "skills", "deploy", "SKILL.md"),
path: path.join(configDir, "skills", "deploy", "SKILL.md"),
enabled: true,
scope: "project",
description: "Claude deploy.",
scope: "user",
description: "User deploy.",
},
]);
}),
);
it.effect("prefers workspace .agents skills over user skills on name collisions", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
const workspace = path.join(tempDir, "workspace");
yield* writeSkill(
path.join(configDir, "skills"),
"deploy",
["---", "name: deploy", "description: User deploy.", "---"].join("\n"),
);
yield* writeSkill(
path.join(workspace, ".agents", "skills"),
"deploy",
["---", "name: deploy", "description: Agents deploy.", "---"].join("\n"),
);
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
assert.deepEqual(skills, [
{
name: "deploy",
path: path.join(workspace, ".agents", "skills", "deploy", "SKILL.md"),
enabled: true,
scope: "project",
description: "Agents deploy.",
},
]);
}),
);
it.effect("prefers project skills over user skills on name collisions", () =>
it.effect("prefers user skills over project skills on name collisions", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -187,8 +148,8 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
assert.equal(skills.length, 1);
assert.equal(skills[0]?.scope, "project");
assert.equal(skills[0]?.description, "Project deploy.");
assert.equal(skills[0]?.scope, "user");
assert.equal(skills[0]?.description, "User deploy.");
}),
);
@@ -287,6 +248,424 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
}),
);
it.effect("marks skills that only the user can invoke", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
const workspace = path.join(tempDir, "workspace");
yield* writeSkill(
path.join(workspace, ".claude", "skills"),
"re-release-version",
[
"---",
"name: re-release-version",
"description: Move the current tag forward.",
"disable-model-invocation: true",
"---",
"",
"# Body",
].join("\n"),
);
yield* writeSkill(
path.join(workspace, ".claude", "skills"),
"release-version",
["---", "name: release-version", "description: Cut a release.", "---", "", "# Body"].join(
"\n",
),
);
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
assert.equal(
skills.find((skill) => skill.name === "re-release-version")?.userInvocationOnly,
true,
);
assert.equal(
skills.find((skill) => skill.name === "release-version")?.userInvocationOnly,
undefined,
);
}),
);
it.effect("disables skills switched off by skillOverrides", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
const workspace = path.join(tempDir, "workspace");
for (const name of ["kept", "off-by-user", "off-by-project"]) {
yield* writeSkill(
path.join(configDir, "skills"),
name,
["---", `name: ${name}`, "---", "", "# Body"].join("\n"),
);
}
yield* fs.makeDirectory(configDir, { recursive: true });
yield* fs.writeFileString(
path.join(configDir, "settings.json"),
'{ "skillOverrides": { "off-by-user": "off", "kept": "on" } }',
);
yield* fs.makeDirectory(path.join(workspace, ".claude"), { recursive: true });
yield* fs.writeFileString(
path.join(workspace, ".claude", "settings.json"),
'{ "skillOverrides": { "off-by-project": "off" } }',
);
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
assert.deepEqual(
skills.map((skill) => [skill.name, skill.enabled]),
[
["kept", true],
["off-by-project", false],
["off-by-user", false],
],
);
}),
);
it.effect("ignores unreadable settings when resolving skillOverrides", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
yield* writeSkill(
path.join(configDir, "skills"),
"kept",
["---", "name: kept", "---", "", "# Body"].join("\n"),
);
yield* fs.writeFileString(path.join(configDir, "settings.json"), "{ not json");
const skills = yield* discoverClaudeSkills({ homePath: configDir });
assert.deepEqual(
skills.map((skill) => [skill.name, skill.enabled]),
[["kept", true]],
);
}),
);
it.effect("treats a user-invocable-only override like disable-model-invocation", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
yield* writeSkill(
path.join(configDir, "skills"),
"ask-matt",
["---", "name: ask-matt", "---", "", "# Body"].join("\n"),
);
yield* fs.writeFileString(
path.join(configDir, "settings.json"),
'{ "skillOverrides": { "ask-matt": "user-invocable-only" } }',
);
const skills = yield* discoverClaudeSkills({ homePath: configDir });
assert.deepEqual(
skills.map((skill) => [skill.name, skill.enabled, skill.userInvocationOnly === true]),
[["ask-matt", true, true]],
);
}),
);
it.effect("drops every override in a file when one value is invalid, as Claude Code does", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
for (const name of ["unknown-mode", "boolean-false", "sibling-off"]) {
yield* writeSkill(
path.join(configDir, "skills"),
name,
["---", `name: ${name}`, "---", "", "# Body"].join("\n"),
);
}
// Verified against the CLI: with an unknown string or a boolean in the
// map, the valid "off" sibling is ignored too and every skill runs.
yield* fs.writeFileString(
path.join(configDir, "settings.json"),
'{ "skillOverrides": { "unknown-mode": "some-future-mode", "boolean-false": false, "sibling-off": "off" } }',
);
const skills = yield* discoverClaudeSkills({ homePath: configDir });
assert.deepEqual(
skills.map((skill) => [skill.name, skill.enabled]),
[
["boolean-false", true],
["sibling-off", true],
["unknown-mode", true],
],
);
}),
);
it.effect("reads repository root settings from a nested workspace", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
const repo = path.join(tempDir, "repo");
const workspace = path.join(repo, "packages", "app");
for (const name of ["root-off", "root-off-cwd-on", "cwd-off-root-on"]) {
yield* writeSkill(
path.join(configDir, "skills"),
name,
["---", `name: ${name}`, "---", "", "# Body"].join("\n"),
);
}
yield* fs.makeDirectory(path.join(repo, ".git"), { recursive: true });
yield* fs.makeDirectory(path.join(repo, ".claude"), { recursive: true });
yield* fs.makeDirectory(path.join(workspace, ".claude"), { recursive: true });
// The CLI ignores the root's plain settings.json from a nested cwd.
yield* fs.writeFileString(
path.join(repo, ".claude", "settings.json"),
'{ "skillOverrides": { "cwd-off-root-on": "off" } }',
);
// The root local file outranks the workspace local file, as in the CLI.
yield* fs.writeFileString(
path.join(repo, ".claude", "settings.local.json"),
'{ "skillOverrides": { "root-off": "off", "root-off-cwd-on": "off", "cwd-off-root-on": "on" } }',
);
yield* fs.writeFileString(
path.join(workspace, ".claude", "settings.local.json"),
'{ "skillOverrides": { "root-off-cwd-on": "on", "cwd-off-root-on": "off" } }',
);
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
assert.deepEqual(
skills.map((skill) => [skill.name, skill.enabled]),
[
["cwd-off-root-on", true],
["root-off", false],
["root-off-cwd-on", false],
],
);
}),
);
it.effect("ignores ancestor settings outside a repository", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
const parent = path.join(tempDir, "not-a-repo");
const workspace = path.join(parent, "workspace");
yield* writeSkill(
path.join(configDir, "skills"),
"kept",
["---", "name: kept", "---", "", "# Body"].join("\n"),
);
yield* fs.makeDirectory(path.join(parent, ".claude"), { recursive: true });
yield* fs.makeDirectory(workspace, { recursive: true });
yield* fs.writeFileString(
path.join(parent, ".claude", "settings.local.json"),
'{ "skillOverrides": { "kept": "off" } }',
);
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
assert.deepEqual(
skills.map((skill) => [skill.name, skill.enabled]),
[["kept", true]],
);
}),
);
it.effect("lets the administrator's managed policy outrank every other settings file", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
for (const [platform, expected] of [
["darwin", "/Library/Application Support/ClaudeCode/managed-settings.json"],
["linux", "/etc/claude-code/managed-settings.json"],
] as const) {
const paths = skillOverrideSettingsPaths(path, "/home/.claude", "/workspace", platform, {});
assert.deepEqual(paths, [
"/home/.claude/settings.json",
"/workspace/.claude/settings.json",
"/workspace/.claude/settings.local.json",
expected,
]);
}
assert.deepEqual(
skillOverrideSettingsPaths(path, "/home/.claude", undefined, "win32", {
PROGRAMDATA: "C:/ProgramData",
}).at(-1),
"C:/ProgramData/ClaudeCode/managed-settings.json",
);
assert.deepEqual(skillOverrideSettingsPaths(path, "/home/.claude", undefined, "win32", {}), [
"/home/.claude/settings.json",
]);
// Only the repository root's local file joins in, after the
// workspace's own local file so it wins.
assert.deepEqual(
skillOverrideSettingsPaths(
path,
"/home/.claude",
"/repo/packages/app",
"linux",
{},
"/repo",
),
[
"/home/.claude/settings.json",
"/repo/packages/app/.claude/settings.json",
"/repo/packages/app/.claude/settings.local.json",
"/repo/.claude/settings.local.json",
"/etc/claude-code/managed-settings.json",
],
);
// A workspace that is the root itself is not read twice.
assert.deepEqual(
skillOverrideSettingsPaths(path, "/home/.claude", "/repo", "linux", {}, "/repo"),
[
"/home/.claude/settings.json",
"/repo/.claude/settings.json",
"/repo/.claude/settings.local.json",
"/etc/claude-code/managed-settings.json",
],
);
}),
);
it.effect("records a skill Claude Code keeps out of its own slash commands", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
yield* writeSkill(
path.join(configDir, "skills"),
"agent-only",
["---", "name: agent-only", "user-invocable: false", "---", "", "# Body"].join("\n"),
);
const skills = yield* discoverClaudeSkills({ homePath: configDir });
assert.deepEqual(
skills.map((skill) => [skill.name, skill.userInvocable]),
[["agent-only", false]],
);
}),
);
it.effect("identifies a skill by its directory, as Claude Code does", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
yield* writeSkill(
path.join(configDir, "skills"),
"probe-alias",
["---", "name: probe-alias-frontmatter", "---", "", "# Body"].join("\n"),
);
yield* fs.writeFileString(
path.join(configDir, "settings.json"),
'{ "skillOverrides": { "probe-alias-frontmatter": "off" } }',
);
const skills = yield* discoverClaudeSkills({ homePath: configDir });
// The frontmatter name is not the command, so an override naming it is
// not the override Claude Code would apply either.
assert.deepEqual(
skills.map((skill) => [skill.name, skill.enabled]),
[["probe-alias", true]],
);
}),
);
it.effect("switches a skill off by its directory name", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
yield* writeSkill(
path.join(configDir, "skills"),
"probe-alias",
["---", "name: probe-alias-frontmatter", "---", "", "# Body"].join("\n"),
);
yield* fs.writeFileString(
path.join(configDir, "settings.json"),
'{ "skillOverrides": { "probe-alias": "off" } }',
);
const skills = yield* discoverClaudeSkills({ homePath: configDir });
assert.deepEqual(
skills.map((skill) => [skill.name, skill.enabled]),
[["probe-alias", false]],
);
}),
);
it.effect("accepts the YAML 1.1 boolean spellings Claude Code allows", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
const skillsDir = path.join(configDir, "skills");
yield* writeSkill(
skillsDir,
"user-only-yes",
["---", "disable-model-invocation: yes", "---", "", "# Body"].join("\n"),
);
yield* writeSkill(
skillsDir,
"agent-only-no",
["---", "user-invocable: no", "---", "", "# Body"].join("\n"),
);
yield* writeSkill(
skillsDir,
"plain-off",
["---", "disable-model-invocation: off", "---", "", "# Body"].join("\n"),
);
const skills = yield* discoverClaudeSkills({ homePath: configDir });
assert.deepEqual(
skills.map((skill) => [
skill.name,
skill.userInvocationOnly === true,
skill.userInvocable === false,
]),
[
["agent-only-no", false, true],
["plain-off", false, false],
["user-only-yes", true, false],
],
);
}),
);
it.effect("returns an empty list when no skill roots exist", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+250 -21
View File
@@ -1,10 +1,12 @@
/**
* ClaudeSkills — filesystem discovery of Claude Code skills for the `$` picker.
*
* Claude Code loads skills from `<config dir>/skills` (user scope), then
* `<cwd>/.agents/skills` and `<cwd>/.claude/skills` (project scope), one
* directory per skill with a `SKILL.md` carrying YAML frontmatter. Later roots
* win on name collisions, so precedence is user, `.agents`, then `.claude`.
* Claude Code loads skills from `<config dir>/skills` (user scope) and
* `<cwd>/.claude/skills` (project scope), one directory per skill with a
* `SKILL.md` carrying YAML frontmatter. The user root wins on name collisions,
* matching the CLI. `.agents/skills` is a Codex location: verified against the
* CLI, a skill that lives only there is answered with `Unknown command`, so it
* is not scanned here.
* The Agent SDK init handshake surfaces skills only as slash commands without
* their filesystem paths, so the provider snapshot scans the same locations
* directly, mirroring how the Codex app-server reports its skills.
@@ -17,6 +19,9 @@ import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { parse as parseYamlDocument } from "yaml";
import { expandHomePath } from "../../pathExpansion.ts";
@@ -28,7 +33,41 @@ const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
type SkillFrontmatter =
| { readonly kind: "missing" }
| { readonly kind: "malformed" }
| { readonly kind: "parsed"; readonly name?: string; readonly description?: string };
| {
readonly kind: "parsed";
readonly description?: string;
readonly userInvocationOnly?: boolean;
readonly userInvocable?: boolean;
};
/**
* Claude Code accepts the YAML 1.1 boolean spellings (`yes`/`no`, `on`/`off`,
* `1`/`0`), which the 1.2 core schema this parser uses leaves as strings and
* numbers. Verified against the CLI: a skill carrying `user-invocable: no` is
* absent from its published slash commands, so a strict `=== false` here would
* offer a command the CLI rejects.
*/
function parseFrontmatterBoolean(value: unknown): boolean | undefined {
if (typeof value === "boolean") return value;
if (typeof value === "number") {
return value === 1 ? true : value === 0 ? false : undefined;
}
if (typeof value !== "string") return undefined;
switch (value.trim().toLowerCase()) {
case "true":
case "yes":
case "on":
case "y":
return true;
case "false":
case "no":
case "off":
case "n":
return false;
default:
return undefined;
}
}
function parseSkillFrontmatter(contents: string): SkillFrontmatter {
const match = FRONTMATTER_PATTERN.exec(contents);
@@ -47,15 +86,187 @@ function parseSkillFrontmatter(contents: string): SkillFrontmatter {
}
const record = parsed as Record<string, unknown>;
const name = typeof record.name === "string" ? record.name.trim() : "";
const description = typeof record.description === "string" ? record.description.trim() : "";
return {
kind: "parsed",
...(name ? { name } : {}),
...(description ? { description } : {}),
...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true
? { userInvocationOnly: true }
: {}),
...(parseFrontmatterBoolean(record["user-invocable"]) === false
? { userInvocable: false }
: {}),
};
}
/**
* Where an administrator installs the policy file whose settings outrank every
* user and project one. Absent on almost every machine, which is why a missing
* file is the normal case rather than an error.
*/
export function claudeManagedSettingsPath(
path: Path.Path,
platform: NodeJS.Platform,
environment: NodeJS.ProcessEnv,
): string | undefined {
if (platform === "darwin") {
return "/Library/Application Support/ClaudeCode/managed-settings.json";
}
if (platform === "win32") {
const programData = environment.PROGRAMDATA?.trim();
return programData ? path.join(programData, "ClaudeCode", "managed-settings.json") : undefined;
}
return "/etc/claude-code/managed-settings.json";
}
/**
* Settings files Claude Code merges for `skillOverrides`, in increasing
* precedence: user, project, project-local, then the administrator's managed
* policy, which wins outright. When the workspace sits inside a git
* repository, the repository root's `settings.local.json` is read too and
* outranks the workspace's own local file. Verified against the CLI from a
* nested cwd: a root local file switching a skill off wins over a cwd one
* switching it on, the root's plain `settings.json` is not consulted, and
* without a `.git` above the cwd no root file is read. A skill the user
* switched off is reported disabled rather than dropped, so the picker can
* grey it out instead of silently losing it.
*/
export function skillOverrideSettingsPaths(
path: Path.Path,
configDirPath: string,
cwd: string | undefined,
platform: NodeJS.Platform,
environment: NodeJS.ProcessEnv,
repositoryRoot?: string,
): ReadonlyArray<string> {
const managedPath = claudeManagedSettingsPath(path, platform, environment);
const root = repositoryRoot !== undefined && repositoryRoot !== cwd ? repositoryRoot : undefined;
return [
path.join(configDirPath, "settings.json"),
...(cwd
? [
path.join(cwd, ".claude", "settings.json"),
path.join(cwd, ".claude", "settings.local.json"),
]
: []),
...(root ? [path.join(root, ".claude", "settings.local.json")] : []),
...(managedPath ? [managedPath] : []),
];
}
/**
* Nearest ancestor of `cwd` (inclusive) holding a `.git` entry, which is the
* boundary Claude Code walks up to for project settings. `undefined` outside
* a repository.
*/
const findRepositoryRoot = Effect.fn("findRepositoryRoot")(function* (
cwd: string,
): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
let current = path.resolve(cwd);
while (true) {
const isRoot = yield* fileSystem
.exists(path.join(current, ".git"))
.pipe(Effect.orElseSucceed(() => false));
if (isRoot) {
return current;
}
const parent = path.dirname(current);
if (parent === current) {
return undefined;
}
current = parent;
}
});
/**
* The four states Claude Code accepts. The CLI validates the whole map, not
* each entry: verified against it, one entry with an unknown value (or a
* boolean) makes it drop every override in that file, so this schema does the
* same rather than applying the valid siblings the CLI ignores.
*/
const SkillOverrideValue = Schema.Literals(["on", "name-only", "user-invocable-only", "off"]);
// Lenient because these settings files are hand-edited and Claude Code itself
// tolerates comments and trailing commas in them.
const SkillOverrideSettings = fromLenientJson(
Schema.Struct({
skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)),
}),
);
const decodeSkillOverrideSettings = Schema.decodeUnknownEffect(SkillOverrideSettings);
/**
* What a `skillOverrides` entry says about one skill. `"user-invocable-only"`
* hides it from the agent exactly as `disable-model-invocation` does, so it is
* kept apart from a plain on/off decision rather than collapsed into one.
*/
type SkillOverride = {
readonly enabled: boolean;
readonly userInvocationOnly: boolean;
};
function parseSkillOverride(value: typeof SkillOverrideValue.Type): SkillOverride {
switch (value) {
case "off":
return { enabled: false, userInvocationOnly: false };
case "user-invocable-only":
return { enabled: true, userInvocationOnly: true };
case "on":
case "name-only":
return { enabled: true, userInvocationOnly: false };
}
}
const readSkillOverrides = Effect.fn("readSkillOverrides")(function* (
configDirPath: string,
cwd: string | undefined,
environment: NodeJS.ProcessEnv,
): Effect.fn.Return<ReadonlyMap<string, SkillOverride>, never, FileSystem.FileSystem | Path.Path> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const platform = yield* HostProcessPlatform;
const overridesByName = new Map<string, SkillOverride>();
const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd);
for (const settingsPath of skillOverrideSettingsPaths(
path,
configDirPath,
cwd,
platform,
environment,
repositoryRoot,
)) {
const contents = yield* fileSystem
.readFileString(settingsPath)
.pipe(Effect.orElseSucceed(() => undefined));
if (contents === undefined) {
continue;
}
const parsed = yield* decodeSkillOverrideSettings(contents).pipe(
Effect.tapError((cause) =>
Effect.logDebug("claude settings file is unreadable; ignoring skillOverrides", {
path: settingsPath,
cause,
}),
),
Effect.orElseSucceed(() => undefined),
);
const overrides = parsed?.skillOverrides;
if (!overrides) {
continue;
}
for (const [name, value] of Object.entries(overrides)) {
overridesByName.set(name, parseSkillOverride(value));
}
}
return overridesByName;
});
/**
* Resolve the Claude config directory the CLI would use, matching the
* precedence the spawned CLI sees: the instance's `homePath` (exported as
@@ -85,12 +296,14 @@ const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(funct
});
/**
* Enumerate Claude Code skills from the user config dir, workspace
* `.agents/skills`, and workspace `.claude/skills`, in that order. Discovery
* is best-effort: unreadable roots and malformed skill entries are skipped so
* a broken skill never degrades the provider snapshot. On name collisions,
* later roots win: `.agents` beats user and `.claude` beats `.agents`, matching
* Claude Code's resolution.
* Enumerate Claude Code skills from the user config dir and the workspace
* `.claude/skills`. Discovery is best-effort: unreadable roots and malformed
* skill entries are skipped so a broken skill never degrades the provider
* snapshot. Roots are listed highest precedence first and the first hit for a
* name wins, matching Claude Code: verified against the CLI with the same
* skill name in both scopes, the user copy is the one that runs. Reporting the
* project copy instead would attach its invocation metadata to a command
* Claude Code resolves elsewhere.
*/
export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
config: Pick<ClaudeSettings, "homePath">,
@@ -100,15 +313,11 @@ export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function*
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
const skillOverrides = yield* readSkillOverrides(configDirPath, cwd, environment ?? process.env);
const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [
{ directory: path.join(configDirPath, "skills"), scope: "user" },
...(cwd
? [
{ directory: path.join(cwd, ".agents", "skills"), scope: "project" as const },
{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const },
]
: []),
...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
];
const skillsByName = new Map<string, ServerProviderSkill>();
@@ -134,19 +343,39 @@ export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function*
continue;
}
const name = (frontmatter.kind === "parsed" ? frontmatter.name : undefined) ?? entry.trim();
// Claude Code identifies a skill by its directory, not by the
// frontmatter `name`: verified against the CLI, a skill in `probe-alias/`
// declaring `name: probe-alias-frontmatter` is published as
// `probe-alias`, and only `skillOverrides["probe-alias"]` switches it
// off. Keying off the frontmatter name would report a command that does
// not exist and miss the override that disables it.
const name = entry.trim();
if (!name) {
continue;
}
// First root wins, so a later root never displaces a higher-precedence
// skill of the same name.
if (skillsByName.has(name)) {
continue;
}
const override = skillOverrides.get(name);
const userInvocationOnly =
(frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
override?.userInvocationOnly === true;
skillsByName.set(name, {
name,
path: skillPath,
enabled: true,
enabled: override?.enabled ?? true,
scope: root.scope,
...(frontmatter.kind === "parsed" && frontmatter.description
? { description: frontmatter.description }
: {}),
...(userInvocationOnly ? { userInvocationOnly: true } : {}),
...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
? { userInvocable: false }
: {}),
});
}
}
@@ -810,6 +810,138 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("dispatches a $skill mention as a trailing slash command block", () => {
// Claude Code only runs `/name` from the message's last text block, so a
// chip picked mid-prompt is moved there and the surrounding prose kept.
const homeDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "claude-skills-home-"));
NodeFS.mkdirSync(NodePath.join(homeDir, "skills", "implement"), { recursive: true });
NodeFS.writeFileSync(
NodePath.join(homeDir, "skills", "implement", "SKILL.md"),
"---\ndescription: Implement the tickets.\n---\n# Body\n",
);
const harness = makeHarness({ claudeConfig: { homePath: homeDir } });
return Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => NodeFS.rmSync(homeDir, { recursive: true, force: true })),
);
const adapter = yield* ClaudeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "ok, now $implement all the tickets\nstart with auth",
attachments: [],
});
const promptMessage = yield* Effect.promise(() =>
readFirstPromptMessage(harness.getLastCreateQueryInput()),
);
assert.deepEqual(promptMessage?.message.content, [
{ type: "text", text: "ok, now" },
{ type: "text", text: "/implement all the tickets\nstart with auth" },
]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("keeps the skill command block after image attachments", () => {
// A command block followed by an image is not expanded by the CLI; the
// image must come first.
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "claude-skill-image-"));
const homeDir = NodePath.join(baseDir, "claude-home");
NodeFS.mkdirSync(NodePath.join(homeDir, "skills", "review"), { recursive: true });
NodeFS.writeFileSync(
NodePath.join(homeDir, "skills", "review", "SKILL.md"),
"---\ndescription: Review.\n---\n# Body\n",
);
const harness = makeHarness({ baseDir, claudeConfig: { homePath: homeDir } });
return Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => NodeFS.rmSync(baseDir, { recursive: true, force: true })),
);
const adapter = yield* ClaudeAdapter;
const { attachmentsDir } = yield* ServerConfig;
const attachment = {
type: "image" as const,
id: "thread-claude-attachment-12345678-1234-1234-1234-123456789abc",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4,
};
const attachmentPath = NodePath.join(attachmentsDir, attachmentRelativePath(attachment)!);
NodeFS.mkdirSync(NodePath.dirname(attachmentPath), { recursive: true });
NodeFS.writeFileSync(attachmentPath, Uint8Array.from([1, 2, 3, 4]));
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "$review this screenshot",
attachments: [attachment],
});
const promptMessage = yield* Effect.promise(() =>
readFirstPromptMessage(harness.getLastCreateQueryInput()),
);
assert.isDefined(promptMessage);
const blocks = promptMessage.message.content as Array<{ type: string; text?: string }>;
assert.deepEqual(
blocks.map((block) => (block.type === "text" ? block.text : block.type)),
["image", "/review this screenshot"],
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("leaves a $ mention of an unknown or disabled skill as prose", () => {
const homeDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "claude-skills-off-"));
NodeFS.mkdirSync(NodePath.join(homeDir, "skills", "deploy"), { recursive: true });
NodeFS.writeFileSync(
NodePath.join(homeDir, "skills", "deploy", "SKILL.md"),
"---\ndescription: Deploy.\n---\n# Body\n",
);
NodeFS.writeFileSync(
NodePath.join(homeDir, "settings.json"),
JSON.stringify({ skillOverrides: { deploy: "off" } }),
);
const harness = makeHarness({ claudeConfig: { homePath: homeDir } });
return Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => NodeFS.rmSync(homeDir, { recursive: true, force: true })),
);
const adapter = yield* ClaudeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "run $deploy and echo $HOME",
attachments: [],
});
const promptText = yield* Effect.promise(() =>
readFirstPromptText(harness.getLastCreateQueryInput()),
);
assert.equal(promptText, "run $deploy and echo $HOME");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("maps Claude stream/runtime messages to canonical provider runtime events", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -79,6 +79,8 @@ import { ServerConfig } from "../../config.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
import { planClaudeSkillDispatch } from "../Drivers/ClaudeSkillDispatch.ts";
import { discoverClaudeSkills } from "../Drivers/ClaudeSkills.ts";
import {
BUNDLED_CLAUDE_MODEL_CATALOG,
type ClaudeModelCatalog,
@@ -1276,12 +1278,23 @@ const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* (
readonly attachmentsDir: string;
readonly boundInstanceId: ProviderInstanceId;
readonly modelCatalog: ClaudeModelCatalog;
/** Names of the skills Claude Code can run for this session's cwd. */
readonly skillNames: ReadonlySet<string>;
},
) {
const text = buildPromptText(input, dependencies.boundInstanceId, dependencies.modelCatalog);
const sdkContent: Array<Record<string, unknown>> = [];
if (text.length > 0) {
// Claude Code expands a skill only from the LAST text block, and only when
// `/name` is its first character. A `$skill` chip anywhere in the prompt is
// therefore split into [leading text, "/name trailing text"] so the CLI
// runs it natively and the prose around it survives. See ClaudeSkillDispatch.
const dispatch = planClaudeSkillDispatch(text, dependencies.skillNames);
if (dispatch) {
if (dispatch.leadingText !== undefined) {
sdkContent.push({ type: "text", text: dispatch.leadingText });
}
} else if (text.length > 0) {
sdkContent.push({ type: "text", text });
}
@@ -1332,6 +1345,12 @@ const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* (
);
}
// Images go before the command block: a text block after them still
// expands, a command block followed by an image does not.
if (dispatch) {
sdkContent.push({ type: "text", text: dispatch.commandText });
}
return buildUserMessage({ sdkContent });
});
@@ -4602,11 +4621,29 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
// Re-scan on every send: skills are added and switched off mid-session,
// and the scan is a few directory reads. A skill switched off via
// skillOverrides, or reserved for the agent with `user-invocable: false`,
// is left as prose: the CLI would answer `/name` with a notice instead of
// running it.
const skills = yield* discoverClaudeSkills(
claudeSettings,
context.session.cwd,
claudeEnvironment,
).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
const message = yield* buildUserMessageEffect(input, {
fileSystem,
attachmentsDir: serverConfig.attachmentsDir,
boundInstanceId,
modelCatalog,
skillNames: new Set(
skills
.filter((skill) => skill.enabled && skill.userInvocable !== false)
.map((skill) => skill.name),
),
});
yield* Queue.offer(context.promptQueue, {
@@ -177,7 +177,7 @@ describe("searchSlashCommandItems", () => {
]);
});
it("hides skills from slash completion after the first message line", () => {
it("hides provider commands from slash completion after the first message line", () => {
const items = [
{
id: "slash:model",
@@ -186,6 +186,14 @@ describe("searchSlashCommandItems", () => {
label: "/model",
description: "Switch model",
},
{
id: "provider-slash-command:claudeAgent:compact",
type: "provider-slash-command",
provider: claudeDriver,
command: { name: "compact" },
label: "/compact",
description: "Compact the conversation",
},
{
id: "skill:claudeAgent:unslop",
type: "skill",
@@ -204,9 +212,11 @@ describe("searchSlashCommandItems", () => {
expect(slashCommandItemsForPromptPosition(items, false).map((item) => item.id)).toEqual([
"slash:model",
"skill:claudeAgent:unslop",
]);
expect(slashCommandItemsForPromptPosition(items, true).map((item) => item.id)).toEqual([
"slash:model",
"provider-slash-command:claudeAgent:compact",
"skill:claudeAgent:unslop",
]);
});
@@ -12,6 +12,12 @@ type SlashSearchItem = Extract<
{ type: "slash-command" | "provider-slash-command" | "skill" }
>;
/**
* A provider expands a slash command only when it opens the whole message;
* anywhere else it reaches the agent as literal text, so it is not offered
* there. Built-ins apply locally on selection and skills insert a `$` mention
* the server dispatches from any position, so both stay available.
*/
export function slashCommandItemsForPromptPosition(
items: ReadonlyArray<SlashSearchItem>,
isAtPromptStart: boolean,
@@ -19,7 +25,7 @@ export function slashCommandItemsForPromptPosition(
if (isAtPromptStart) {
return [...items];
}
return items.filter((item) => item.type !== "skill");
return items.filter((item) => item.type !== "provider-slash-command");
}
function scoreSlashCommandItem(item: SlashSearchItem, query: string): number | null {
+13
View File
@@ -48,6 +48,19 @@ describe("searchProviderSkills", () => {
expect(searchProviderSkills(skills, "gfc").map((skill) => skill.name)).toEqual(["gh-fix-ci"]);
});
it("keeps user-only skills and omits agent-only ones", () => {
const skills = [
makeSkill({ name: "re-release-version", userInvocationOnly: true }),
makeSkill({ name: "release-context", userInvocable: false }),
makeSkill({ name: "release-version" }),
];
expect(searchProviderSkills(skills, "release").map((skill) => skill.name)).toEqual([
"release-version",
"re-release-version",
]);
});
it("omits disabled skills from results", () => {
const skills = [
makeSkill({ name: "ui", displayName: "Ui", enabled: false }),
+2 -1
View File
@@ -2,6 +2,7 @@ import type { ServerProviderSkill } from "@t3tools/contracts";
import {
dedupeProviderSkillsByName,
formatProviderSkillDisplayName,
isProviderSkillUserInvocable,
} from "@t3tools/client-runtime/providerSkills";
import {
insertRankedSearchResult,
@@ -73,7 +74,7 @@ export function searchProviderSkills(
query: string,
limit = Number.POSITIVE_INFINITY,
): ServerProviderSkill[] {
const enabledSkills = dedupeProviderSkillsByName(skills.filter((skill) => skill.enabled));
const enabledSkills = dedupeProviderSkillsByName(skills.filter(isProviderSkillUserInvocable));
const normalizedQuery = normalizeSearchQuery(query, { trimLeadingPattern: /^\$+/ });
if (!normalizedQuery) {