Skip to content

Commit d5e47e1

Browse files
byapparovclaude
andcommitted
feat(skill): scope headless skill discovery and add an allowlist (#157)
`aictrl run` never scans ~/.claude, ~/.agents or ~/.opencode for skills, however discovery reaches them (home scan, a non-git upward walk, a symlinked home or project directory, ~/.opencode as a config directory), so the skill tool description no longer depends on $HOME. There is no switch back; a caller lists home skills explicitly in config, e.g. skills.paths: ["~/.claude/skills"]. `~/` in skills.paths now expands from Global.Path.home, the home path discovery uses. `aictrl run --skill <name>` (repeatable) and config `skills.allow` restrict the run to the named skills: only they are listed, loadable, and reported in tool_catalog and skill_discovered/skill_loaded events, for the main session and every subagent. The skill tool rejects other names with an allowlist error. --skill is rejected with --attach or an empty name. The allowlist matches names, not sources. Headless detection reads the in-memory HeadlessRun mark that `run` enables (#152), so Skill.setScope carries only the allowlist. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 4bcf6c0 commit d5e47e1

12 files changed

Lines changed: 618 additions & 17 deletions

File tree

‎EVENTS.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,8 @@ Emitted once per session, immediately after `session_start` and before the first
132132

133133
#### `skills[]` — skill packs resolved for this session (separate from `tools[]`)
134134

135+
Only skills in scope for the run are listed; see [Skill Events](#skill-events).
136+
135137
- **`name`** (string, **required**) — skill name from `SKILL.md` frontmatter.
136138
- **`version`** (string or null, **required**) — version string from the `version` field in `SKILL.md` frontmatter. `null` when no version is declared.
137139

@@ -432,6 +434,8 @@ with truthful process/session failure status.
432434

433435
Skills are loaded progressively. The model first sees skill names and descriptions in the tool schema. Full skill content only enters context when the model explicitly invokes the skill tool.
434436

437+
Skill events, and `tool_catalog.skills[]`, cover only the skills in scope for the run. Without `--attach`, `aictrl run` skips `~/.claude/skills`, `~/.agents/skills` and `~/.opencode/skills` (config `skills.paths` can list home skills explicitly), and `--skill <name>` (repeatable) or config `skills.allow` limits the set further (see [Skill Scope](packages/cli/README.md#skill-scope)). A skill outside the allowlist is neither discovered nor loadable: the skill tool rejects it with `Skill "<name>" is not in the skill allowlist for this run`, and no `skill_loaded` event is emitted. With `--attach`, the attached server's own skill discovery applies.
438+
435439
### `skill_discovered`
436440

437441
Emitted per skill when the skill tool is initialized and skill descriptions are registered in the tool schema. This happens at the start of each LLM turn.
@@ -441,7 +445,7 @@ Emitted per skill when the skill tool is initialized and skill descriptions are
441445
"type": "skill_discovered",
442446
"name": "commit",
443447
"description": "Create well-structured git commits",
444-
"location": "/home/user/.claude/skills/commit/SKILL.md"
448+
"location": "/work/repo/.claude/skills/commit/SKILL.md"
445449
}
446450
```
447451

@@ -453,7 +457,7 @@ Emitted when the model invokes the skill tool and the full SKILL.md content ente
453457
{
454458
"type": "skill_loaded",
455459
"name": "commit",
456-
"location": "/home/user/.claude/skills/commit/SKILL.md"
460+
"location": "/work/repo/.claude/skills/commit/SKILL.md"
457461
}
458462
```
459463

@@ -465,7 +469,7 @@ Emitted when the model reads a file that belongs to a skill directory (e.g., a s
465469
{
466470
"type": "skill_resource_loaded",
467471
"skillName": "commit",
468-
"filePath": "/home/user/.claude/skills/commit/templates/conventional.md"
472+
"filePath": "/work/repo/.claude/skills/commit/templates/conventional.md"
469473
}
470474
```
471475

‎README.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,16 @@ In headless mode, Aictrl automatically rejects all interactive permission reques
7474
every request, and a one-shot run has nobody following a todo list. To track a plan, instruct
7575
the agent to keep one in a file.
7676

77+
### Skill Scope
78+
79+
`aictrl run` does not list skills from `~/.claude`, `~/.agents` or `~/.opencode`;
80+
list them explicitly in config `skills.paths` (e.g. `["~/.claude/skills"]`) to use
81+
them. Project skills, the global aictrl
82+
config directories (`~/.config/aictrl`, `~/.aictrl`) and config
83+
`skills.paths`/`skills.urls` are still listed. Pass `--skill <name>` (repeatable)
84+
or set config `skills.allow` to list and load only the named skills.
85+
See the [full contract](packages/cli/README.md#skill-scope).
86+
7787
### CI/CD Integration
7888

7989
Set `AICTRL_HEADLESS=true` in your environment to force headless behavior even in pseudo-TTYs.

‎packages/cli/README.md‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,43 @@ In headless mode, Aictrl automatically rejects permissions that would otherwise
101101
every request, and a one-shot run has nobody following a todo list. To track a plan, instruct
102102
the agent to keep one in a file.
103103

104+
### Skill Scope
105+
106+
`aictrl run` lists project skills (`.aictrl/skill(s)/`, and `.claude/skills/`,
107+
`.agents/skills/` or `.opencode/skills/` from the working directory up to the
108+
repository root), skills in the global config directory (`~/.config/aictrl/`,
109+
`~/.aictrl/`) and config `skills.paths`/`skills.urls`. It does **not** scan
110+
`~/.claude/skills/`, `~/.agents/skills/` or `~/.opencode/skills/`, so the skill
111+
list does not depend on what happens to be in `$HOME`. To use home skills, list
112+
their folder explicitly in config `skills.paths` (`~/` expands to the home directory):
113+
114+
```json
115+
{ "skills": { "paths": ["~/.claude/skills"] } }
116+
```
117+
118+
To limit a run to the skills it needs, pass `--skill <name>` (repeatable) or set
119+
config `skills.allow`. Only those skills are then listed in the `skill` tool,
120+
loadable by it, and reported in `tool_catalog`/`skill_discovered` events, for the
121+
main session and every subagent. An allowlist filters discovered skills; it does
122+
not bring back home-directory skills. `skills.allow: []` allows no skills.
123+
124+
An allowlist matches skill **names**, not where a skill comes from. When several
125+
sources define the same name, the later source wins (project over home, config
126+
`skills.paths`/`skills.urls` last), so in a repository you do not control, the
127+
content under an allowed name can come from that repository.
128+
129+
`skills.allow` follows normal config precedence, so a project config can replace
130+
a global value. It applies to every command that reads config (for example
131+
`aictrl acp`), not only `aictrl run`. `--skill` replaces `skills.allow` for a single
132+
`aictrl run`.
133+
134+
With `--attach`, the attached server discovers skills: its own skill discovery
135+
applies, and `--skill` is rejected.
136+
137+
```bash
138+
aictrl run --skill code-review "review this PR"
139+
```
140+
104141
## GitHub Agent
105142

106143
Install the GitHub agent into any repository:

‎packages/cli/src/cli/cmd/run.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import { CodeSearchTool } from "../../tool/codesearch"
3939
import { WebSearchTool } from "../../tool/websearch"
4040
import { TaskTool } from "../../tool/task"
4141
import { SkillTool } from "../../tool/skill"
42+
import { Skill } from "../../skill"
4243
import { BashTool } from "../../tool/bash"
4344
import { TodoWriteTool } from "../../tool/todo"
4445
import { Locale } from "../../util/locale"
@@ -422,6 +423,13 @@ export const RunCommand = cmd({
422423
describe: "show thinking blocks",
423424
default: false,
424425
})
426+
.option("skill", {
427+
type: "string",
428+
array: true,
429+
// One value per flag, so a trailing message is not taken as a skill name.
430+
nargs: 1,
431+
describe: "only list and load this skill (repeatable); overrides config skills.allow",
432+
})
425433
},
426434
handler: async (args) => {
427435
const invocation = createRunInvocation(args.format === "json")
@@ -496,6 +504,17 @@ export const RunCommand = cmd({
496504
await fail("--fork requires --continue or --session", "INVOCATION_INVALID_ARGUMENTS")
497505
}
498506

507+
if (args.skill?.length && args.attach) {
508+
// The attached server discovers skills, so a local allowlist cannot reach it.
509+
await fail("--skill is not supported with --attach", "INVOCATION_INVALID_ARGUMENTS")
510+
}
511+
512+
const allowlist = args.skill?.map((name) => name.trim())
513+
if (allowlist?.some((name) => !name)) {
514+
// An empty name (e.g. an unset shell variable) would otherwise silently allow no skills.
515+
await fail("--skill requires a skill name", "INVOCATION_INVALID_ARGUMENTS")
516+
}
517+
499518
const rules: PermissionNext.Ruleset = [
500519
{
501520
permission: "question",
@@ -1131,6 +1150,7 @@ export const RunCommand = cmd({
11311150

11321151
// Sessions this process serves belong to the headless run until it finishes.
11331152
HeadlessRun.enable()
1153+
Skill.setScope({ allow: allowlist })
11341154
const execution = bootstrap(process.cwd(), async () => {
11351155
const sdk = {
11361156
session: {

‎packages/cli/src/config/config.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -661,6 +661,12 @@ export namespace Config {
661661
.array(z.string())
662662
.optional()
663663
.describe("URLs to fetch skills from (e.g., https://example.com/.well-known/skills/)"),
664+
allow: z
665+
.array(z.string())
666+
.optional()
667+
.describe(
668+
"Only skills with these names are listed and loadable, from whichever source defines them; `aictrl run --skill` overrides it",
669+
),
664670
})
665671
export type Skills = z.infer<typeof Skills>
666672

‎packages/cli/src/skill/skill.ts‎

Lines changed: 66 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import z from "zod"
22
import path from "path"
3-
import os from "os"
3+
import fs from "fs/promises"
44
import { Config } from "../config/config"
55
import { Instance } from "../project/instance"
66
import { NamedError } from "@aictrl/util/error"
@@ -9,6 +9,7 @@ import { Log } from "../util/log"
99
import { Global } from "@/global"
1010
import { Filesystem } from "@/util/filesystem"
1111
import { Flag } from "@/flag/flag"
12+
import { HeadlessRun } from "@/flag/headless-run"
1213
import { Bus } from "@/bus"
1314
import { Session } from "@/session"
1415
import { Discovery } from "./discovery"
@@ -68,9 +69,53 @@ export namespace Skill {
6869
const AICTRL_SKILL_PATTERN = "{skill,skills}/**/SKILL.md"
6970
const SKILL_PATTERN = "**/SKILL.md"
7071

72+
/**
73+
* Invocation-level skill scope. `aictrl run` sets it before bootstrapping, so
74+
* the main session and every subagent share one scoped skill set.
75+
*/
76+
export type Scope = {
77+
/** Only these skill names are listed and loadable; replaces config `skills.allow`. */
78+
allow?: string[]
79+
}
80+
81+
let invocation: Scope = {}
82+
83+
/** Applies to instances created afterwards; an instance keeps the scope it was discovered with. */
84+
export function setScope(next: Scope) {
85+
invocation = next
86+
}
87+
88+
/**
89+
* Decides whether home-directory skills are scanned and which skill names are allowed.
90+
* Headless runs skip home-directory skills; config `skills.paths` can still list them explicitly.
91+
*/
92+
function policy(config: Config.Info) {
93+
const allow = invocation.allow?.length ? invocation.allow : config.skills?.allow
94+
return {
95+
home: !HeadlessRun.enabled(),
96+
allow: allow && new Set(allow),
97+
}
98+
}
99+
100+
/** ~/.claude, ~/.agents and ~/.opencode under both the configured and the symlink-resolved home path. */
101+
async function homeRoots() {
102+
const real = await fs.realpath(Global.Path.home).catch(() => Global.Path.home)
103+
return [...new Set([Global.Path.home, real])].flatMap((home) => EXTERNAL_DIRS.map((dir) => path.join(home, dir)))
104+
}
105+
71106
export const state = Instance.state(async () => {
72107
const skills: Record<string, Info> = {}
73108
const dirs = new Set<string>()
109+
const config = await Config.get()
110+
const access = policy(config)
111+
const home = EXTERNAL_DIRS.map((dir) => path.join(Global.Path.home, dir))
112+
// Home skill roots to skip, however a scan reaches them, including through a symlink.
113+
const skipped = new Set(access.home ? [] : await homeRoots())
114+
const skip = async (root: string) => {
115+
if (skipped.size === 0) return false
116+
if (skipped.has(root)) return true
117+
return skipped.has(await fs.realpath(root).catch(() => root))
118+
}
74119

75120
const addSkill = async (match: string) => {
76121
const md = await ConfigMarkdown.parse(match).catch((err) => {
@@ -86,6 +131,7 @@ export namespace Skill {
86131

87132
const parsed = Info.pick({ name: true, description: true }).safeParse(md.data)
88133
if (!parsed.success) return
134+
if (access.allow && !access.allow.has(parsed.data.name)) return
89135

90136
// Warn on duplicate skill names
91137
if (skills[parsed.data.name]) {
@@ -136,22 +182,25 @@ export namespace Skill {
136182

137183
// Scan external skill directories (.claude/skills/, .agents/skills/, etc.)
138184
// Load global (home) first, then project-level (so project-level overwrites)
139-
for (const dir of EXTERNAL_DIRS) {
140-
const root = path.join(Global.Path.home, dir)
185+
for (const root of home) {
186+
if (await skip(root)) continue
141187
if (!(await Filesystem.isDir(root))) continue
142188
await scanExternal(root, "global")
143189
}
144190

191+
// A non-git project's upward walk, or a symlinked project directory, can reach the home directories too.
145192
for await (const root of Filesystem.up({
146193
targets: EXTERNAL_DIRS,
147194
start: Instance.directory,
148195
stop: Instance.worktree,
149196
})) {
197+
if (await skip(root)) continue
150198
await scanExternal(root, "project")
151199
}
152200

153-
// Scan .aictrl/skill/ directories
201+
// Scan .aictrl/skill/ directories (config directories include ~/.opencode)
154202
for (const dir of await Config.directories()) {
203+
if (await skip(dir)) continue
155204
const matches = await Glob.scan(AICTRL_SKILL_PATTERN, {
156205
cwd: dir,
157206
absolute: true,
@@ -164,9 +213,8 @@ export namespace Skill {
164213
}
165214

166215
// Scan additional skill paths from config
167-
const config = await Config.get()
168216
for (const skillPath of config.skills?.paths ?? []) {
169-
const expanded = skillPath.startsWith("~/") ? path.join(os.homedir(), skillPath.slice(2)) : skillPath
217+
const expanded = skillPath.startsWith("~/") ? path.join(Global.Path.home, skillPath.slice(2)) : skillPath
170218
const resolved = path.isAbsolute(expanded) ? expanded : path.join(Instance.directory, expanded)
171219
if (!(await Filesystem.isDir(resolved))) {
172220
log.warn("skill path not found", { path: resolved })
@@ -187,7 +235,8 @@ export namespace Skill {
187235
for (const url of config.skills?.urls ?? []) {
188236
const list = await Discovery.pull(url)
189237
for (const dir of list) {
190-
dirs.add(dir)
238+
// Under an allowlist, addSkill records only the allowed skills' directories.
239+
if (!access.allow) dirs.add(dir)
191240
const matches = await Glob.scan(SKILL_PATTERN, {
192241
cwd: dir,
193242
absolute: true,
@@ -200,16 +249,26 @@ export namespace Skill {
200249
}
201250
}
202251

252+
for (const name of access.allow ?? []) {
253+
if (!skills[name]) log.warn("allowed skill not found", { name })
254+
}
255+
203256
return {
204257
skills,
205258
dirs: Array.from(dirs),
259+
allow: access.allow && Array.from(access.allow),
206260
}
207261
})
208262

209263
export async function get(name: string) {
210264
return state().then((x) => x.skills[name])
211265
}
212266

267+
/** Skill names this invocation is restricted to, or undefined when every discovered skill is allowed. */
268+
export async function allowed() {
269+
return state().then((x) => x.allow)
270+
}
271+
213272
export async function all() {
214273
return state().then((x) => Object.values(x.skills))
215274
}

‎packages/cli/src/tool/skill.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,16 @@ function publish(ctx?: Tool.InitContext, skills?: Awaited<ReturnType<typeof Skil
3030
}
3131
}
3232

33+
async function unavailable(name: string) {
34+
// Under an allowlist, Skill.all() holds only the allowed skills that were discovered.
35+
const available = await Skill.all().then((x) => x.map((skill) => skill.name).join(", ") || "none")
36+
const allow = await Skill.allowed()
37+
if (allow && !allow.includes(name)) {
38+
return `Skill "${name}" is not in the skill allowlist for this run. Allowed skills: ${available}`
39+
}
40+
return `Skill "${name}" not found. Available skills: ${available}`
41+
}
42+
3343
export const SkillTool = Tool.define("skill", async (ctx) => {
3444
const skills = await Skill.all()
3545
publish(ctx, skills)
@@ -85,10 +95,7 @@ export const SkillTool = Tool.define("skill", async (ctx) => {
8595
async execute(params: z.infer<typeof parameters>, ctx) {
8696
const skill = await Skill.get(params.name)
8797

88-
if (!skill) {
89-
const available = await Skill.all().then((x) => Object.keys(x).join(", "))
90-
throw new Error(`Skill "${params.name}" not found. Available skills: ${available || "none"}`)
91-
}
98+
if (!skill) throw new Error(await unavailable(params.name))
9299

93100
await Plugin.trigger("skill.load", { sessionID: ctx.sessionID, name: skill.name, location: skill.location }, skill)
94101

0 commit comments

Comments
 (0)