Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,57 @@
---
name: review-agent
description: Perform a read-only, defect-first review of a specified code change and return every actionable finding. Use when another agent delegates review of uncommitted changes, a base-branch diff, a commit, or custom review instructions.
---
# Review Agent
Inspect the requested target directly and return every finding that the author would likely fix.
Do not modify files, create commits, push branches, post review comments, or delegate the review
to another agent.
## Review the change
1. Read the applicable `AGENTS.md` instructions.
2. Inspect the complete diff for the requested target and enough surrounding code to understand
each changed path.
3. Identify concrete regressions introduced by the change. Continue through the whole diff after
finding the first issue.
4. Check the relevant tests and call sites to confirm that each finding is real and actionable.
For a base-branch review, compare the changes that would actually merge rather than diffing
directly against the branch tip. Resolve the comparison ref to the branch's upstream when that
upstream exists and is ahead of the local branch; otherwise use the local branch. Run
`git merge-base HEAD <comparison-ref>`, then inspect `git diff <merge-base-sha>`. If the local
branch cannot be resolved, try its configured upstream explicitly before reporting that the target
is unavailable.
Flag an issue only when all of these are true:
- It affects correctness, security, performance, or maintainability in a meaningful way.
- It is discrete and actionable.
- It was introduced by the reviewed change.
- The affected scenario or call path can be demonstrated from the code.
- The author would probably fix it if they knew about it.
Do not flag speculative concerns, pre-existing problems, intentional behavior changes, or style
nits that do not obscure the code.
## Write the result
Present findings first, ordered by severity. Use one entry per issue in this form:
`[P1] Imperative finding title — path/to/file.rs:line`
Follow the title with one short paragraph explaining the affected scenario and why the behavior is
wrong. Keep the cited range as small as possible and make sure it overlaps the reviewed diff.
Use these priorities:
- `P0`: universal release blocker or critical failure.
- `P1`: urgent defect that should be fixed next.
- `P2`: ordinary defect that should be fixed.
- `P3`: low-impact issue that is still worth fixing.
If there are no qualifying findings, say `No findings.` Do not invent a finding to fill the result.
After the findings, add a brief overall assessment and mention any material test gaps or residual
risks.

View File

@@ -0,0 +1,6 @@
interface:
display_name: "Review Agent"
short_description: "Find actionable bugs in code changes"
default_prompt: "Use $review-agent to review the requested code changes and return actionable findings."
policy:
allow_implicit_invocation: false

View File

@@ -0,0 +1,229 @@
---
name: skill-creator
description: Create or update a Codex skill with appropriately scoped instructions and any needed supporting resources.
metadata:
short-description: Create or update a skill
---
# Skill Creator
Create skills that give Codex useful, non-obvious guidance without constraining unrelated work.
## Core Principles
**Assume Codex is already capable.** Include only information that changes its decisions or improves its work. Remove generic advice, repeated instructions, speculative edge cases, and examples that do not materially clarify the task.
**Preserve user intent and scope.** A skill should support the requested task, not replace the user's chosen product, expand the assignment, modify unrelated configuration, or imply permission for additional external actions. Do not turn a particular example, past failure, or personal preference into a universal requirement.
Approval to complete a task does not expand its scope or execution permissions. For retrying or externally mutating workflows, define a stopping condition proportional to the risk.
**Match specificity to the risk.** Give the model room to choose an appropriate approach when multiple approaches are reasonable. Use detailed steps, deterministic scripts, or absolute language only when correctness, safety, permissions, or a genuinely fragile workflow requires them.
For open-ended work, describe the outcome and relevant decision criteria. For workflows with a preferred shape, offer useful examples or configurable scripts. Reserve fixed sequences and narrow parameters for operations where deviation would cause a concrete problem. Preserve non-obvious operational invariants, distinguish actual requirements from optional recommendations or local conventions, and avoid restating policies already enforced elsewhere.
**Keep discovery cheap and precise.** Skill names and descriptions are available before a skill is loaded. Describe the actual capability and when it applies, adding exclusions only when they prevent likely misrouting. Avoid exhaustive capability lists and catchalls that attract unrelated requests.
Keep skills self-contained; refer to another skill or tool only when the requested workflow genuinely requires it and it is available in the target environment. Specialized review, hardening, or audit workflows should apply when requested or genuinely needed, not merely because ordinary work touches the same subject.
**Disclose detail progressively.** Keep shared purpose, essential constraints, and useful routing in `SKILL.md`. Put substantial mode-specific guidance, schemas, examples, or procedures in supporting references and read only the references relevant to the current task. A simple self-contained skill does not need a router or extra files.
## Anatomy of a Skill
Every skill is a folder containing a required `SKILL.md` file and any optional resources its actual workflow needs:
```text
skill-name/
|-- SKILL.md Required skill instructions
| |-- YAML frontmatter Required name and description
| `-- Markdown body Instructions loaded when the skill is used
|-- agents/ Optional UI metadata and invocation policy
| `-- openai.yaml
|-- scripts/ Optional executable helpers
|-- references/ Optional documentation loaded as needed
`-- assets/ Optional files used in generated output
```
Choose the structure that fits the actual task. Some skills are short and self-contained; others route among operating modes or delegate complex mechanics to scripts. Avoid creating directories, placeholders, examples, or ancillary documentation without a clear use.
### SKILL.md
The YAML frontmatter identifies the skill and determines when it should be considered. Include the required `name` and `description`, and preserve supported optional fields such as existing `metadata` when appropriate.
The Markdown body is loaded only when the skill is used. Put the purpose, essential workflow, real constraints, and useful links there. Keep detailed procedures and examples in supporting references when they are relevant only to particular modes.
Skill information is disclosed in three stages:
1. **Name and description:** Available during skill selection, so keep them concise and discriminating.
2. **SKILL.md body:** Loaded when the skill applies, so keep its instructions relevant to that task.
3. **Supporting resources:** Read or execute only when the current task actually needs them.
The entrypoint should be as short as the task permits while retaining important constraints. A large upper bound is not a target: move conditional detail into references when doing so improves clarity or context use, rather than waiting for the file to become unwieldy.
### Scripts
Use `scripts/` for executable code when the same logic would otherwise be rewritten repeatedly or deterministic execution materially improves reliability.
- **Example:** `scripts/rotate_pdf.py` for a PDF operation that would otherwise require recreating the same code.
- **Useful for:** Repeated transformations, reliable API operations, data processing, and other concrete automation.
- **Validation:** Run new or changed scripts to verify their behavior. Scripts can usually be executed without loading their full implementation into context, although an agent may need to inspect them when patching or adapting them.
### References
Use `references/` for documentation that is needed only in particular contexts.
- **Examples:** `references/schema.md` for database tables, `references/policies.md` for domain rules, `references/api_docs.md` for an API, or separate writing guides for different deliverables.
- **Useful for:** Schemas, API documentation, company policies, format-specific procedures, detailed workflows, and substantial examples.
- **Routing:** Link each reference from `SKILL.md` or another relevant resource and explain when it should be read. Keep information in one place instead of duplicating it across the entrypoint and references.
Keep references focused on maintained, task-specific information that changes the agent's decisions. Avoid copied manuals, exhaustive catalogs, and generic tutorials already available from authoritative sources. Before removing existing resources, inspect their callers and purpose.
For large references, include useful search terms or a short contents section when that makes the needed material easier to find.
### Assets
Use `assets/` for files that belong in generated output rather than in the model's instructions.
- **Examples:** `assets/logo.png`, `assets/slides.pptx`, `assets/font.ttf`, or `assets/frontend-template/`.
- **Useful for:** Templates, images, fonts, icons, boilerplate projects, and other files copied or adapted into the result.
- **Context:** Do not load assets as instructions unless the task requires inspecting them.
### UI Metadata and Invocation Policy
`agents/openai.yaml` can provide UI-facing metadata such as `display_name`, `short_description`, and `default_prompt`, along with invocation policy. When creating or updating those settings, read [references/openai_yaml.md](references/openai_yaml.md) and keep the values consistent with the skill.
Automatic skill selection is allowed by default. Change that default only when the user explicitly requests an explicit-only skill:
```yaml
policy:
allow_implicit_invocation: false
```
This keeps the skill available when explicitly invoked as `$skill-name` without adding it to the model context automatically. Preserve unrelated existing UI, policy, and dependency fields when updating `agents/openai.yaml`.
The initializer creates this file automatically. For new or interface-only metadata, generate it with:
```bash
scripts/generate_openai_yaml.py <path/to/skill-folder> --interface key=value
```
The generator replaces the entire file. If an existing file contains `policy` or `dependencies`, update only the intended fields in place instead of regenerating it.
Include optional interface fields only when the user provides or requests them.
### What Not to Include
Include files that directly support the skill's work. Avoid adding a `README.md`, installation guide, changelog, duplicated quick reference, or other auxiliary documentation unless a specific task or packaging requirement calls for it.
## Progressive Disclosure in Practice
For a skill with multiple substantial modes, keep the shared guidance and mode-selection criteria in `SKILL.md`. Link each supporting reference where its use becomes relevant. Do not load every reference by default, duplicate reference content in the entrypoint, or add a routing layer when there is nothing meaningful to route.
For example, a deployment skill can keep provider selection in `SKILL.md` and separate provider details:
```text
cloud-deploy/
|-- SKILL.md
`-- references/
|-- aws.md
|-- gcp.md
`-- azure.md
```
When the user chooses AWS, read `references/aws.md`; do not also load the GCP and Azure guides. The same pattern can separate business domains, deliverable types, or other genuinely distinct operating modes.
A short skill can instead route to details only when an advanced operation needs them:
```markdown
## Documents
Handle ordinary edits directly.
- For tracked changes, read [references/redlining.md](references/redlining.md).
- For document internals, read [references/ooxml.md](references/ooxml.md).
```
These examples illustrate options, not a required structure. Choose the organization that makes the skill easier to use without loading irrelevant material.
## Create or Update a Skill
Adapt the work to the request. Creating a complex new skill may involve understanding realistic use cases, choosing supporting resources, initializing files, writing instructions, and validating the result. A narrow update to an existing skill may require only a focused edit and validation.
Ask clarifying questions only when the missing information matters and cannot be reasonably inferred. Respect a user-specified location; otherwise create discoverable skills in `$AKODE_HOME/skills`, or `~/.akode/skills` when `AKODE_HOME` is unset.
Keep automatic skill selection enabled unless the user explicitly requests an explicit-only skill. When the intended invocation mode is genuinely unclear and matters to the requested workflow, ask whether the user wants normal automatic discovery or explicit-only invocation; otherwise preserve the default. Do not infer explicit-only invocation from sensitive operations or required approvals: keep the skill discoverable and require authorization immediately before the actual mutation. Preserve an existing skill's invocation policy unless the user asks to change it.
For a new or substantially revised skill, consider the actual requests it should handle and which reusable resources would improve those tasks:
- A repeated PDF transformation may justify a `scripts/rotate_pdf.py` helper.
- An application-building workflow may benefit from an `assets/frontend-template/` starter.
- A data-analysis skill may need a `references/schema.md` guide to avoid rediscovering table relationships.
Create those resources only when their concrete benefit justifies them. If the user has already explained the task clearly, proceed without requesting additional examples.
### Naming
- Use lowercase letters, digits, and hyphens.
- Keep names under 64 characters and prefer short action-oriented names.
- Namespace by tool or domain when doing so improves discovery.
- Name the skill folder after the skill.
### Initialize a New Skill
For a new skill, use the bundled initializer when it helps create the required files consistently:
```bash
scripts/init_skill.py <skill-name> --path <output-directory> [--resources scripts,references,assets] [--examples]
```
For example:
```bash
scripts/init_skill.py my-skill --path "${AKODE_HOME:-$HOME/.akode}/skills"
scripts/init_skill.py my-skill --path "${AKODE_HOME:-$HOME/.akode}/skills" --resources references
```
Request only the resource directories the skill needs. Use `--examples` only when concrete placeholders would help, and replace or remove them before finishing. Do not initialize an existing skill again.
The initializer creates the skill directory, a concise `SKILL.md` starter, and `agents/openai.yaml`. It creates resource directories and example files only when requested. Pass generated UI values as `--interface key=value` when needed.
### Write the Instructions
The frontmatter `description` should briefly explain what the skill does and when it applies. Include a meaningful boundary when similar requests should not activate the skill.
For example:
```yaml
description: Create or edit Word documents when formatting, tracked changes, or comments require document-specific handling.
```
Put detailed workflows, tool choices, examples, and operating modes in the body or relevant references rather than listing them all in the description. Preserve supported optional frontmatter, such as existing `metadata`, when appropriate.
Write only the instructions needed for another Codex instance to perform the task well. State the desired outcome, non-obvious context, real constraints, and relevant references or tools. Preserve the user's explicit choices and existing authorization boundaries. Avoid prescribing a fixed structure, process, or number of steps when the task does not require one.
### Validate and Iterate
Validate the completed skill with:
```bash
scripts/quick_validate.py <path/to/skill-folder>
```
The validator checks frontmatter, naming, and unfinished scaffold placeholders; it does not prove that the skill makes good decisions. Also check that descriptions remain discriminating, instructions preserve user intent, references are discoverable, and any added scripts actually work.
When testing is warranted, verify observable behavior or meaningful invariants. Avoid tests that merely match generated wording, headings, or regex patterns.
Improve the skill based on real usage or demonstrated failures. Prefer a narrow correction to accumulating universal rules for every observed example.
## Independent Forward-Testing
Use an independent subagent pass when a skill is sufficiently complex or risky that realistic behavioral validation would add meaningful confidence, and when delegation is available and authorized. Ordinary creation or small edits do not automatically require subagents.
Give the evaluating agent a realistic user request, the skill, and the minimum raw artifacts needed to perform the task. Do not provide the intended answer, suspected bug, proposed fix, or prior conclusions unless the evaluation genuinely requires them.
For example:
```text
Use $skill-name at /path/to/skill-name to complete this realistic request.
```
Keep the evaluation scoped to permitted resources and side effects. Use an isolated temporary workspace for generated artifacts so they do not enter the working tree or contaminate later evaluations. Ask for approval when the proposed evaluation would require additional authorization, affect a live production system, or impose substantial time or cost. Review the actual outcome and artifacts, then make only changes supported by the observed behavior.

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Skill Creator"
short_description: "Create or update a skill"
icon_small: "./assets/skill-creator-small.svg"
icon_large: "./assets/skill-creator.png"

View File

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 20 20">
<path fill="#0D0D0D" d="M12.03 4.113a3.612 3.612 0 0 1 5.108 5.108l-6.292 6.29c-.324.324-.56.561-.791.752l-.235.176c-.205.14-.422.261-.65.36l-.229.093a4.136 4.136 0 0 1-.586.16l-.764.134-2.394.4c-.142.024-.294.05-.423.06-.098.007-.232.01-.378-.026l-.149-.05a1.081 1.081 0 0 1-.521-.474l-.046-.093a1.104 1.104 0 0 1-.075-.527c.01-.129.035-.28.06-.422l.398-2.394c.1-.602.162-.987.295-1.35l.093-.23c.1-.228.22-.445.36-.65l.176-.235c.19-.232.428-.467.751-.79l6.292-6.292Zm-5.35 7.232c-.35.35-.534.535-.66.688l-.11.147a2.67 2.67 0 0 0-.24.433l-.062.154c-.08.22-.124.462-.232 1.112l-.398 2.394-.001.001h.003l2.393-.399.717-.126a2.63 2.63 0 0 0 .394-.105l.154-.063a2.65 2.65 0 0 0 .433-.24l.147-.11c.153-.126.339-.31.688-.66l4.988-4.988-3.227-3.226-4.987 4.988Zm9.517-6.291a2.281 2.281 0 0 0-3.225 0l-.364.362 3.226 3.227.363-.364c.89-.89.89-2.334 0-3.225ZM4.583 1.783a.3.3 0 0 1 .294.241c.117.585.347 1.092.707 1.48.357.385.859.668 1.549.783a.3.3 0 0 1 0 .592c-.69.115-1.192.398-1.549.783-.315.34-.53.77-.657 1.265l-.05.215a.3.3 0 0 1-.588 0c-.117-.585-.347-1.092-.707-1.48-.357-.384-.859-.668-1.549-.783a.3.3 0 0 1 0-.592c.69-.115 1.192-.398 1.549-.783.36-.388.59-.895.707-1.48l.015-.05a.3.3 0 0 1 .279-.19Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,49 @@
# openai.yaml fields (full example + descriptions)
`agents/openai.yaml` is an extended, product-specific config intended for the machine/harness to read, not the agent. Other product-specific config can also live in the `agents/` folder.
## Full example
```yaml
interface:
display_name: "Optional user-facing name"
short_description: "Optional user-facing description"
icon_small: "./assets/small-400px.png"
icon_large: "./assets/large-logo.svg"
brand_color: "#3B82F6"
default_prompt: "Optional surrounding prompt to use the skill with"
dependencies:
tools:
- type: "mcp"
value: "github"
description: "GitHub MCP server"
transport: "streamable_http"
url: "https://api.githubcopilot.com/mcp/"
policy:
allow_implicit_invocation: true
```
## Field descriptions and constraints
Top-level constraints:
- Quote all string values.
- Keep keys unquoted.
- For `interface.default_prompt`: generate a helpful, short (typically 1 sentence) example starting prompt based on the skill. It must explicitly mention the skill as `$skill-name` (e.g., "Use $skill-name-here to draft a concise weekly status update.").
- `interface.display_name`: Human-facing title shown in UI skill lists and chips.
- `interface.short_description`: Human-facing short UI blurb (25–64 chars) for quick scanning.
- `interface.icon_small`: Path to a small icon asset (relative to skill dir). Default to `./assets/` and place icons in the skill's `assets/` folder.
- `interface.icon_large`: Path to a larger logo asset (relative to skill dir). Default to `./assets/` and place icons in the skill's `assets/` folder.
- `interface.brand_color`: Hex color used for UI accents (e.g., badges).
- `interface.default_prompt`: Default prompt snippet inserted when invoking the skill.
- `dependencies.tools[].type`: Dependency category. Only `mcp` is supported for now.
- `dependencies.tools[].value`: Identifier of the tool or dependency.
- `dependencies.tools[].description`: Human-readable explanation of the dependency.
- `dependencies.tools[].transport`: Connection type when `type` is `mcp`.
- `dependencies.tools[].url`: MCP server URL when `type` is `mcp`.
- `policy.allow_implicit_invocation`: When false, the skill is not injected into
the model context by default, but can still be invoked explicitly via `$skill`.
Defaults to true.

View File

@@ -0,0 +1,231 @@
#!/usr/bin/env python3
"""
OpenAI YAML Generator - Creates agents/openai.yaml for a skill folder.
Usage:
generate_openai_yaml.py <skill_dir> [--name <skill_name>] [--interface key=value]
"""
import argparse
import re
import sys
from pathlib import Path
ACRONYMS = {
"GH",
"MCP",
"API",
"CI",
"CLI",
"LLM",
"PDF",
"PR",
"UI",
"URL",
"SQL",
}
BRANDS = {
"openai": "OpenAI",
"openapi": "OpenAPI",
"github": "GitHub",
"pagerduty": "PagerDuty",
"datadog": "DataDog",
"sqlite": "SQLite",
"fastapi": "FastAPI",
}
SMALL_WORDS = {"and", "or", "to", "up", "with"}
ALLOWED_INTERFACE_KEYS = {
"display_name",
"short_description",
"icon_small",
"icon_large",
"brand_color",
"default_prompt",
}
def yaml_quote(value):
escaped = value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
return f'"{escaped}"'
def format_display_name(skill_name):
words = [word for word in skill_name.split("-") if word]
formatted = []
for index, word in enumerate(words):
lower = word.lower()
upper = word.upper()
if upper in ACRONYMS:
formatted.append(upper)
continue
if lower in BRANDS:
formatted.append(BRANDS[lower])
continue
if index > 0 and lower in SMALL_WORDS:
formatted.append(lower)
continue
formatted.append(word.capitalize())
return " ".join(formatted)
def generate_short_description(display_name):
description = f"Help with {display_name} tasks"
if len(description) < 25:
description = f"Help with {display_name} tasks and workflows"
if len(description) < 25:
description = f"Help with {display_name} tasks with guidance"
if len(description) > 64:
description = f"Help with {display_name}"
if len(description) > 64:
description = f"{display_name} helper"
if len(description) > 64:
description = f"{display_name} tools"
if len(description) > 64:
suffix = " helper"
max_name_length = 64 - len(suffix)
trimmed = display_name[:max_name_length].rstrip()
description = f"{trimmed}{suffix}"
if len(description) > 64:
description = description[:64].rstrip()
if len(description) < 25:
description = f"{description} workflows"
if len(description) > 64:
description = description[:64].rstrip()
return description
def read_frontmatter_name(skill_dir):
skill_md = Path(skill_dir) / "SKILL.md"
if not skill_md.exists():
print(f"[ERROR] SKILL.md not found in {skill_dir}")
return None
content = skill_md.read_text()
match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
if not match:
print("[ERROR] Invalid SKILL.md frontmatter format.")
return None
frontmatter_text = match.group(1)
import yaml
try:
frontmatter = yaml.safe_load(frontmatter_text)
except yaml.YAMLError as exc:
print(f"[ERROR] Invalid YAML frontmatter: {exc}")
return None
if not isinstance(frontmatter, dict):
print("[ERROR] Frontmatter must be a YAML dictionary.")
return None
name = frontmatter.get("name", "")
if not isinstance(name, str) or not name.strip():
print("[ERROR] Frontmatter 'name' is missing or invalid.")
return None
return name.strip()
def parse_interface_overrides(raw_overrides):
overrides = {}
optional_order = []
for item in raw_overrides:
if "=" not in item:
print(f"[ERROR] Invalid interface override '{item}'. Use key=value.")
return None, None
key, value = item.split("=", 1)
key = key.strip()
value = value.strip()
if not key:
print(f"[ERROR] Invalid interface override '{item}'. Key is empty.")
return None, None
if key not in ALLOWED_INTERFACE_KEYS:
allowed = ", ".join(sorted(ALLOWED_INTERFACE_KEYS))
print(f"[ERROR] Unknown interface field '{key}'. Allowed: {allowed}")
return None, None
overrides[key] = value
if (
key not in ("display_name", "short_description")
and key not in optional_order
):
optional_order.append(key)
return overrides, optional_order
def write_openai_yaml(skill_dir, skill_name, raw_overrides):
overrides, optional_order = parse_interface_overrides(raw_overrides)
if overrides is None:
return None
display_name = overrides.get("display_name") or format_display_name(skill_name)
short_description = overrides.get(
"short_description"
) or generate_short_description(display_name)
if not (25 <= len(short_description) <= 64):
print(
"[ERROR] short_description must be 25-64 characters "
f"(got {len(short_description)})."
)
return None
interface_lines = [
"interface:",
f" display_name: {yaml_quote(display_name)}",
f" short_description: {yaml_quote(short_description)}",
]
for key in optional_order:
value = overrides.get(key)
if value is not None:
interface_lines.append(f" {key}: {yaml_quote(value)}")
agents_dir = Path(skill_dir) / "agents"
agents_dir.mkdir(parents=True, exist_ok=True)
output_path = agents_dir / "openai.yaml"
output_path.write_text("\n".join(interface_lines) + "\n")
print(f"[OK] Created agents/openai.yaml")
return output_path
def main():
parser = argparse.ArgumentParser(
description="Create agents/openai.yaml for a skill directory.",
)
parser.add_argument("skill_dir", help="Path to the skill directory")
parser.add_argument(
"--name",
help="Skill name override (defaults to SKILL.md frontmatter)",
)
parser.add_argument(
"--interface",
action="append",
default=[],
help="Interface override in key=value format (repeatable)",
)
args = parser.parse_args()
skill_dir = Path(args.skill_dir).resolve()
if not skill_dir.exists():
print(f"[ERROR] Skill directory not found: {skill_dir}")
sys.exit(1)
if not skill_dir.is_dir():
print(f"[ERROR] Path is not a directory: {skill_dir}")
sys.exit(1)
skill_name = args.name or read_frontmatter_name(skill_dir)
if not skill_name:
sys.exit(1)
result = write_openai_yaml(skill_dir, skill_name, args.interface)
if result:
sys.exit(0)
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,308 @@
#!/usr/bin/env python3
"""
Skill Initializer - Creates a new skill from template
Usage:
init_skill.py <skill-name> --path <path> [--resources scripts,references,assets] [--examples] [--interface key=value]
Examples:
init_skill.py my-new-skill --path skills/public
init_skill.py my-new-skill --path skills/public --resources scripts,references
init_skill.py my-api-helper --path skills/private --resources scripts --examples
init_skill.py custom-skill --path /custom/location
init_skill.py my-skill --path skills/public --interface short_description="Short UI label"
"""
import argparse
import re
import sys
from pathlib import Path
from generate_openai_yaml import write_openai_yaml
MAX_SKILL_NAME_LENGTH = 64
ALLOWED_RESOURCES = {"scripts", "references", "assets"}
SKILL_TEMPLATE = """---
name: {skill_name}
description: "[TODO: Briefly describe what this skill does and when it applies.]"
---
# {skill_title}
[TODO: Add the task-specific guidance Codex needs. Reference supporting files only when they are relevant.]
"""
EXAMPLE_SCRIPT = '''#!/usr/bin/env python3
"""
Example helper script for {skill_name}
This is a placeholder script that can be executed directly.
Replace with actual implementation or delete if not needed.
Example real scripts from other skills:
- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields
- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images
"""
def main():
print("This is an example script for {skill_name}")
# TODO: Add actual script logic here
# This could be data processing, file conversion, API calls, etc.
if __name__ == "__main__":
main()
'''
EXAMPLE_REFERENCE = """# Reference for {skill_title}
Replace this placeholder with maintained, task-specific details that Codex
would not reliably know, such as operational constraints, local schemas, or
fragile integration behavior.
Delete this file if no supported workflow needs it.
"""
EXAMPLE_ASSET = """# Example Asset File
This placeholder represents where asset files would be stored.
Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed.
Asset files are NOT intended to be loaded into context, but rather used within
the output Codex produces.
Example asset files from other skills:
- Brand guidelines: logo.png, slides_template.pptx
- Frontend builder: hello-world/ directory with HTML/React boilerplate
- Typography: custom-font.ttf, font-family.woff2
- Data: sample_data.csv, test_dataset.json
## Common Asset Types
- Templates: .pptx, .docx, boilerplate directories
- Images: .png, .jpg, .svg, .gif
- Fonts: .ttf, .otf, .woff, .woff2
- Boilerplate code: Project directories, starter files
- Icons: .ico, .svg
- Data files: .csv, .json, .xml, .yaml
Note: This is a text placeholder. Actual assets can be any file type.
"""
def normalize_skill_name(skill_name):
"""Normalize a skill name to lowercase hyphen-case."""
normalized = skill_name.strip().lower()
normalized = re.sub(r"[^a-z0-9]+", "-", normalized)
normalized = normalized.strip("-")
normalized = re.sub(r"-{2,}", "-", normalized)
return normalized
def title_case_skill_name(skill_name):
"""Convert hyphenated skill name to Title Case for display."""
return " ".join(word.capitalize() for word in skill_name.split("-"))
def parse_resources(raw_resources):
if not raw_resources:
return []
resources = [item.strip() for item in raw_resources.split(",") if item.strip()]
invalid = sorted({item for item in resources if item not in ALLOWED_RESOURCES})
if invalid:
allowed = ", ".join(sorted(ALLOWED_RESOURCES))
print(f"[ERROR] Unknown resource type(s): {', '.join(invalid)}")
print(f" Allowed: {allowed}")
sys.exit(1)
deduped = []
seen = set()
for resource in resources:
if resource not in seen:
deduped.append(resource)
seen.add(resource)
return deduped
def create_resource_dirs(
skill_dir, skill_name, skill_title, resources, include_examples
):
for resource in resources:
resource_dir = skill_dir / resource
resource_dir.mkdir(exist_ok=True)
if resource == "scripts":
if include_examples:
example_script = resource_dir / "example.py"
example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))
example_script.chmod(0o755)
print("[OK] Created scripts/example.py")
else:
print("[OK] Created scripts/")
elif resource == "references":
if include_examples:
example_reference = resource_dir / "api_reference.md"
example_reference.write_text(
EXAMPLE_REFERENCE.format(skill_title=skill_title)
)
print("[OK] Created references/api_reference.md")
else:
print("[OK] Created references/")
elif resource == "assets":
if include_examples:
example_asset = resource_dir / "example_asset.txt"
example_asset.write_text(EXAMPLE_ASSET)
print("[OK] Created assets/example_asset.txt")
else:
print("[OK] Created assets/")
def init_skill(skill_name, path, resources, include_examples, interface_overrides):
"""
Initialize a new skill directory with template SKILL.md.
Args:
skill_name: Name of the skill
path: Path where the skill directory should be created
resources: Resource directories to create
include_examples: Whether to create example files in resource directories
Returns:
Path to created skill directory, or None if error
"""
# Determine skill directory path
skill_dir = Path(path).resolve() / skill_name
# Check if directory already exists
if skill_dir.exists():
print(f"[ERROR] Skill directory already exists: {skill_dir}")
return None
# Create skill directory
try:
skill_dir.mkdir(parents=True, exist_ok=False)
print(f"[OK] Created skill directory: {skill_dir}")
except Exception as e:
print(f"[ERROR] Error creating directory: {e}")
return None
# Create SKILL.md from template
skill_title = title_case_skill_name(skill_name)
skill_content = SKILL_TEMPLATE.format(
skill_name=skill_name, skill_title=skill_title
)
skill_md_path = skill_dir / "SKILL.md"
try:
skill_md_path.write_text(skill_content)
print("[OK] Created SKILL.md")
except Exception as e:
print(f"[ERROR] Error creating SKILL.md: {e}")
return None
# Create agents/openai.yaml
try:
result = write_openai_yaml(skill_dir, skill_name, interface_overrides)
if not result:
return None
except Exception as e:
print(f"[ERROR] Error creating agents/openai.yaml: {e}")
return None
# Create resource directories if requested
if resources:
try:
create_resource_dirs(
skill_dir, skill_name, skill_title, resources, include_examples
)
except Exception as e:
print(f"[ERROR] Error creating resource directories: {e}")
return None
# Print next steps
print(f"\n[OK] Skill '{skill_name}' initialized successfully at {skill_dir}")
print("\nNext steps:")
print("1. Edit SKILL.md to complete the TODO items and update the description")
if resources:
if include_examples:
print(
"2. Customize or delete the example files in scripts/, references/, and assets/"
)
else:
print("2. Add resources to scripts/, references/, and assets/ as needed")
else:
print(
"2. Create resource directories only if needed (scripts/, references/, assets/)"
)
print("3. Update agents/openai.yaml if the UI metadata should differ")
print("4. Run the validator when ready to check the skill structure")
print(
"5. Consider independent forward-testing only when complexity or risk warrants it"
)
return skill_dir
def main():
parser = argparse.ArgumentParser(
description="Create a new skill directory with a SKILL.md template.",
)
parser.add_argument("skill_name", help="Skill name (normalized to hyphen-case)")
parser.add_argument("--path", required=True, help="Output directory for the skill")
parser.add_argument(
"--resources",
default="",
help="Comma-separated list: scripts,references,assets",
)
parser.add_argument(
"--examples",
action="store_true",
help="Create example files inside the selected resource directories",
)
parser.add_argument(
"--interface",
action="append",
default=[],
help="Interface override in key=value format (repeatable)",
)
args = parser.parse_args()
raw_skill_name = args.skill_name
skill_name = normalize_skill_name(raw_skill_name)
if not skill_name:
print("[ERROR] Skill name must include at least one letter or digit.")
sys.exit(1)
if len(skill_name) > MAX_SKILL_NAME_LENGTH:
print(
f"[ERROR] Skill name '{skill_name}' is too long ({len(skill_name)} characters). "
f"Maximum is {MAX_SKILL_NAME_LENGTH} characters."
)
sys.exit(1)
if skill_name != raw_skill_name:
print(f"Note: Normalized skill name from '{raw_skill_name}' to '{skill_name}'.")
resources = parse_resources(args.resources)
if args.examples and not resources:
print("[ERROR] --examples requires --resources to be set.")
sys.exit(1)
path = args.path
print(f"Initializing skill: {skill_name}")
print(f" Location: {path}")
if resources:
print(f" Resources: {', '.join(resources)}")
if args.examples:
print(" Examples: enabled")
else:
print(" Resources: none (create as needed)")
print()
result = init_skill(skill_name, path, resources, args.examples, args.interface)
if result:
sys.exit(0)
else:
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""
Quick validation script for skills - minimal version
"""
import re
import sys
from pathlib import Path
import yaml
MAX_SKILL_NAME_LENGTH = 64
def validate_skill(skill_path):
"""Basic validation of a skill"""
skill_path = Path(skill_path)
skill_md = skill_path / "SKILL.md"
if not skill_md.exists():
return False, "SKILL.md not found"
content = skill_md.read_text()
if not content.startswith("---"):
return False, "No YAML frontmatter found"
match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
if not match:
return False, "Invalid frontmatter format"
frontmatter_text = match.group(1)
try:
frontmatter = yaml.safe_load(frontmatter_text)
if not isinstance(frontmatter, dict):
return False, "Frontmatter must be a YAML dictionary"
except yaml.YAMLError as e:
return False, f"Invalid YAML in frontmatter: {e}"
allowed_properties = {"name", "description", "license", "allowed-tools", "metadata"}
unexpected_keys = set(frontmatter.keys()) - allowed_properties
if unexpected_keys:
allowed = ", ".join(sorted(allowed_properties))
unexpected = ", ".join(sorted(unexpected_keys))
return (
False,
f"Unexpected key(s) in SKILL.md frontmatter: {unexpected}. Allowed properties are: {allowed}",
)
if "name" not in frontmatter:
return False, "Missing 'name' in frontmatter"
if "description" not in frontmatter:
return False, "Missing 'description' in frontmatter"
name = frontmatter.get("name", "")
if not isinstance(name, str):
return False, f"Name must be a string, got {type(name).__name__}"
name = name.strip()
if name:
if not re.match(r"^[a-z0-9-]+$", name):
return (
False,
f"Name '{name}' should be hyphen-case (lowercase letters, digits, and hyphens only)",
)
if name.startswith("-") or name.endswith("-") or "--" in name:
return (
False,
f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens",
)
if len(name) > MAX_SKILL_NAME_LENGTH:
return (
False,
f"Name is too long ({len(name)} characters). "
f"Maximum is {MAX_SKILL_NAME_LENGTH} characters.",
)
description = frontmatter.get("description", "")
if not isinstance(description, str):
return False, f"Description must be a string, got {type(description).__name__}"
description = description.strip()
if description.startswith("[TODO:"):
return False, "Description contains an unfinished TODO placeholder"
if description:
if "<" in description or ">" in description:
return False, "Description cannot contain angle brackets (< or >)"
if len(description) > 1024:
return (
False,
f"Description is too long ({len(description)} characters). Maximum is 1024 characters.",
)
body = content[match.end() :]
fence_marker = None
fence_length = 0
for line in body.splitlines():
fence = re.match(r"^[ \t]*(?:(?:[-+*]|\d+[.)])[ \t]+)?(`{3,}|~{3,})(.*)$", line)
if fence:
marker = fence.group(1)
if fence_marker is None:
fence_marker = marker[0]
fence_length = len(marker)
elif (
marker[0] == fence_marker
and len(marker) >= fence_length
and not fence.group(2).strip()
):
fence_marker = None
fence_length = 0
continue
if fence_marker is None and re.fullmatch(
r"[ ]{0,3}\[TODO:[^\n]*\][ \t]*", line
):
return False, "Skill instructions contain an unfinished TODO placeholder"
return True, "Skill is valid!"
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python quick_validate.py <skill_directory>")
sys.exit(1)
valid, message = validate_skill(sys.argv[1])
print(message)
sys.exit(0 if valid else 1)

View File

@@ -0,0 +1,201 @@
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use akode_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use crate::SkillInterface;
const MAX_NAME_LEN: usize = 64;
const MAX_DESCRIPTION_LEN: usize = 1024;
/// Interface metadata deserialized from a skill's `agents/openai.yaml` file.
#[derive(Debug, Default, Deserialize)]
pub struct SkillInterfaceFile {
display_name: Option<String>,
short_description: Option<String>,
icon_small: Option<PathBuf>,
icon_large: Option<PathBuf>,
brand_color: Option<String>,
default_prompt: Option<String>,
}
/// Controls whether interface icons may resolve through a plugin's shared assets directory.
#[derive(Debug, Clone, Copy)]
pub enum SkillInterfaceAssetPolicy<'a> {
LocalOnly,
PluginShared { plugin_root: &'a AbsolutePathBuf },
}
/// Validates skill interface metadata and resolves its asset paths.
pub fn resolve_skill_interface(
interface: Option<SkillInterfaceFile>,
skill_dir: &AbsolutePathBuf,
asset_policy: SkillInterfaceAssetPolicy<'_>,
) -> Option<SkillInterface> {
let interface = interface?;
let interface = SkillInterface {
display_name: resolve_str(
interface.display_name,
MAX_NAME_LEN,
"interface.display_name",
),
short_description: resolve_str(
interface.short_description,
MAX_DESCRIPTION_LEN,
"interface.short_description",
),
icon_small: resolve_asset_path(
skill_dir,
asset_policy,
"interface.icon_small",
interface.icon_small,
),
icon_large: resolve_asset_path(
skill_dir,
asset_policy,
"interface.icon_large",
interface.icon_large,
),
brand_color: resolve_color_str(interface.brand_color, "interface.brand_color"),
default_prompt: resolve_str(
interface.default_prompt,
MAX_DESCRIPTION_LEN,
"interface.default_prompt",
),
};
let has_fields = interface.display_name.is_some()
|| interface.short_description.is_some()
|| interface.icon_small.is_some()
|| interface.icon_large.is_some()
|| interface.brand_color.is_some()
|| interface.default_prompt.is_some();
has_fields.then_some(interface)
}
fn resolve_asset_path(
skill_dir: &AbsolutePathBuf,
asset_policy: SkillInterfaceAssetPolicy<'_>,
field: &'static str,
path: Option<PathBuf>,
) -> Option<AbsolutePathBuf> {
let path = path?;
if path.as_os_str().is_empty() {
return None;
}
let assets_dir = skill_dir.join("assets");
if path.is_absolute() {
tracing::warn!(
"ignoring {field}: icon must be a relative assets path (not {})",
assets_dir.display()
);
return None;
}
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::Normal(component) => normalized.push(component),
Component::ParentDir => {
return resolve_plugin_shared_asset_path(skill_dir, asset_policy, field, &path);
}
Component::Prefix(_) | Component::RootDir => {
tracing::warn!("ignoring {field}: icon path must be under assets/");
return None;
}
}
}
let mut components = normalized.components();
match components.next() {
Some(Component::Normal(component)) if component == "assets" => {}
_ => {
tracing::warn!("ignoring {field}: icon path must be under assets/");
return None;
}
}
Some(skill_dir.join(normalized))
}
fn resolve_plugin_shared_asset_path(
skill_dir: &AbsolutePathBuf,
asset_policy: SkillInterfaceAssetPolicy<'_>,
field: &'static str,
path: &Path,
) -> Option<AbsolutePathBuf> {
let SkillInterfaceAssetPolicy::PluginShared { plugin_root } = asset_policy else {
tracing::warn!("ignoring {field}: icon path must not contain '..'");
return None;
};
let plugin_assets_dir = lexically_normalize(plugin_root.join("assets").as_path());
let resolved = lexically_normalize(skill_dir.join(path).as_path());
if !resolved.starts_with(&plugin_assets_dir) {
tracing::warn!("ignoring {field}: icon path with '..' must resolve under plugin assets/");
return None;
}
AbsolutePathBuf::try_from(resolved)
.map_err(|error| {
tracing::warn!("ignoring {field}: icon path must resolve to an absolute path: {error}");
error
})
.ok()
}
fn lexically_normalize(path: &Path) -> PathBuf {
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
normalized.pop();
}
Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
normalized.push(component.as_os_str());
}
}
}
normalized
}
fn resolve_str(value: Option<String>, max_len: usize, field: &'static str) -> Option<String> {
let value = value?;
let value = value.split_whitespace().collect::<Vec<_>>().join(" ");
if value.is_empty() {
tracing::warn!("ignoring {field}: value is empty");
return None;
}
if value.chars().count() > max_len {
tracing::warn!("ignoring {field}: exceeds maximum length of {max_len} characters");
return None;
}
Some(value)
}
fn resolve_color_str(value: Option<String>, field: &'static str) -> Option<String> {
let value = value?;
let value = value.trim();
if value.is_empty() {
tracing::warn!("ignoring {field}: value is empty");
return None;
}
let mut chars = value.chars();
if value.len() == 7
&& chars.next() == Some('#')
&& chars.all(|character| character.is_ascii_hexdigit())
{
Some(value.to_string())
} else {
tracing::warn!("ignoring {field}: expected #RRGGBB, got {value}");
None
}
}
#[cfg(test)]
#[path = "interface_tests.rs"]
mod tests;

View File

@@ -0,0 +1,165 @@
use std::path::PathBuf;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use super::SkillInterfaceAssetPolicy;
use super::SkillInterfaceFile;
use super::resolve_skill_interface;
use crate::SkillInterface;
fn absolute_path(path: &str) -> AbsolutePathBuf {
AbsolutePathBuf::try_from(
std::env::current_dir()
.expect("current directory")
.join(path),
)
.expect("absolute path")
}
#[test]
fn resolves_local_interface_fields_and_assets() {
let skill_dir = absolute_path("skill");
let interface = SkillInterfaceFile {
display_name: Some(" Demo skill ".to_string()),
short_description: Some(" Short description ".to_string()),
icon_small: Some(PathBuf::from("./assets/icon.svg")),
icon_large: Some(PathBuf::from("assets/icon-large.png")),
brand_color: Some(" #123ABC ".to_string()),
default_prompt: Some(" Run the demo ".to_string()),
};
assert_eq!(
resolve_skill_interface(
Some(interface),
&skill_dir,
SkillInterfaceAssetPolicy::LocalOnly,
),
Some(SkillInterface {
display_name: Some("Demo skill".to_string()),
short_description: Some("Short description".to_string()),
icon_small: Some(skill_dir.join("assets/icon.svg")),
icon_large: Some(skill_dir.join("assets/icon-large.png")),
brand_color: Some("#123ABC".to_string()),
default_prompt: Some("Run the demo".to_string()),
})
);
}
#[test]
fn rejects_invalid_local_interface_fields() {
let skill_dir = absolute_path("skill");
let interface = SkillInterfaceFile {
display_name: None,
short_description: None,
icon_small: Some(PathBuf::from("../outside.svg")),
icon_large: Some(PathBuf::from("icon.png")),
brand_color: Some("blue".to_string()),
default_prompt: Some("x".repeat(1025)),
};
assert_eq!(
resolve_skill_interface(
Some(interface),
&skill_dir,
SkillInterfaceAssetPolicy::LocalOnly,
),
None
);
}
#[test]
fn rejects_absolute_asset_paths() {
let skill_dir = absolute_path("skill");
let interface = SkillInterfaceFile {
icon_small: Some(absolute_path("outside.svg").as_path().to_path_buf()),
..Default::default()
};
assert_eq!(
resolve_skill_interface(
Some(interface),
&skill_dir,
SkillInterfaceAssetPolicy::LocalOnly,
),
None
);
}
#[test]
fn drops_invalid_fields_without_discarding_valid_interface_fields() {
let skill_dir = absolute_path("skill");
let interface = SkillInterfaceFile {
display_name: Some("Demo skill".to_string()),
short_description: None,
icon_small: Some(PathBuf::from("assets/icon.svg")),
icon_large: Some(PathBuf::from("icon.png")),
brand_color: Some("blue".to_string()),
default_prompt: Some("x".repeat(1025)),
};
assert_eq!(
resolve_skill_interface(
Some(interface),
&skill_dir,
SkillInterfaceAssetPolicy::LocalOnly,
),
Some(SkillInterface {
display_name: Some("Demo skill".to_string()),
short_description: None,
icon_small: Some(skill_dir.join("assets/icon.svg")),
icon_large: None,
brand_color: None,
default_prompt: None,
})
);
}
#[test]
fn resolves_plugin_shared_assets() {
let plugin_root = absolute_path("plugin");
let skill_dir = plugin_root.join("skills/demo");
let interface = SkillInterfaceFile {
icon_small: Some(PathBuf::from("../../assets/icon.svg")),
..Default::default()
};
assert_eq!(
resolve_skill_interface(
Some(interface),
&skill_dir,
SkillInterfaceAssetPolicy::PluginShared {
plugin_root: &plugin_root,
},
),
Some(SkillInterface {
display_name: None,
short_description: None,
icon_small: Some(plugin_root.join("assets/icon.svg")),
icon_large: None,
brand_color: None,
default_prompt: None,
})
);
}
#[test]
fn rejects_plugin_assets_outside_shared_assets_root() {
let plugin_root = absolute_path("plugin");
let skill_dir = plugin_root.join("skills/demo");
let interface = SkillInterfaceFile {
icon_small: Some(PathBuf::from("../../other/icon.svg")),
..Default::default()
};
assert_eq!(
resolve_skill_interface(
Some(interface),
&skill_dir,
SkillInterfaceAssetPolicy::PluginShared {
plugin_root: &plugin_root,
},
),
None
);
}

View File

@@ -0,0 +1,160 @@
use std::path::Path;
use akode_protocol::parse_command::ParsedCommand;
use akode_shell_command::parse_command::parse_command_impl;
use akode_shell_command::parse_command::tokenize_powershell_command;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathConvention;
use akode_utils_path_uri::PathUri;
use crate::SkillMetadata;
/// A skill document read or script execution identified in a shell command.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ImplicitSkillAccess {
Document(PathUri),
Script(PathUri),
}
/// Provides the indexed skill lookups used to recognize implicit invocations.
pub trait ImplicitSkillLookup {
fn implicit_skill_for_scripts_dir(&self, path: &AbsolutePathBuf) -> Option<&SkillMetadata>;
fn implicit_skill_for_doc_path(&self, path: &AbsolutePathBuf) -> Option<&SkillMetadata>;
}
pub fn detect_implicit_skill_invocation_for_command(
outcome: &impl ImplicitSkillLookup,
command: &str,
workdir: &AbsolutePathBuf,
) -> Option<SkillMetadata> {
let workdir = canonicalize_if_exists(workdir);
let tokens = if PathConvention::native() == PathConvention::Windows {
tokenize_powershell_command(command)
} else {
tokenize_command(command)
};
if let Some(candidate) = detect_skill_script_run(outcome, tokens.as_slice(), &workdir) {
return Some(candidate);
}
detect_skill_doc_read(outcome, tokens.as_slice(), &workdir)
}
/// Resolves statically recognizable skill accesses without consulting the host filesystem.
pub fn implicit_skill_accesses_for_command(
command: &str,
workdir: &PathUri,
) -> Vec<ImplicitSkillAccess> {
let tokens = if workdir.infer_path_convention() == Some(PathConvention::Windows) {
tokenize_powershell_command(command)
} else {
tokenize_command(command)
};
let mut accesses = Vec::new();
if let Some(script) = script_run_token(&tokens)
&& let Ok(path) = workdir.join(script)
{
accesses.push(ImplicitSkillAccess::Script(path));
}
for parsed in parse_command_impl(&tokens) {
if let ParsedCommand::Read { path, .. } = parsed
&& let Some(path) = path.to_str()
&& let Ok(path) = workdir.join(path)
{
accesses.push(ImplicitSkillAccess::Document(path));
}
}
accesses
}
fn tokenize_command(command: &str) -> Vec<String> {
shlex::split(command)
.unwrap_or_else(|| command.split_whitespace().map(str::to_string).collect())
}
fn script_run_token(tokens: &[String]) -> Option<&str> {
const RUNNERS: [&str; 10] = [
"python", "python3", "bash", "zsh", "sh", "node", "deno", "ruby", "perl", "pwsh",
];
const SCRIPT_EXTENSIONS: [&str; 7] = [".py", ".sh", ".js", ".ts", ".rb", ".pl", ".ps1"];
let runner_token = tokens.first()?;
let runner = command_basename(runner_token).to_ascii_lowercase();
let runner = runner.strip_suffix(".exe").unwrap_or(&runner);
if !RUNNERS.contains(&runner) {
return None;
}
let mut script_token = None;
for token in tokens.iter().skip(1) {
if token == "--" || token.starts_with('-') {
continue;
}
script_token = Some(token.as_str());
break;
}
let script_token = script_token?;
if SCRIPT_EXTENSIONS
.iter()
.any(|extension| script_token.to_ascii_lowercase().ends_with(extension))
{
return Some(script_token);
}
None
}
fn detect_skill_script_run(
outcome: &impl ImplicitSkillLookup,
tokens: &[String],
workdir: &AbsolutePathBuf,
) -> Option<SkillMetadata> {
let script_token = script_run_token(tokens)?;
let script_path = Path::new(script_token);
let script_path = canonicalize_if_exists(&workdir.join(script_path));
for path in script_path.ancestors() {
if let Some(candidate) = outcome.implicit_skill_for_scripts_dir(&path) {
return Some(candidate.clone());
}
}
None
}
fn detect_skill_doc_read(
outcome: &impl ImplicitSkillLookup,
tokens: &[String],
workdir: &AbsolutePathBuf,
) -> Option<SkillMetadata> {
for command in parse_command_impl(tokens) {
if let ParsedCommand::Read { path, .. } = command {
let candidate_path = canonicalize_if_exists(&workdir.join(path.as_path()));
if let Some(candidate) = outcome.implicit_skill_for_doc_path(&candidate_path) {
return Some(candidate.clone());
}
}
}
None
}
fn command_basename(command: &str) -> String {
Path::new(command)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(command)
.to_string()
}
fn canonicalize_if_exists(path: &AbsolutePathBuf) -> AbsolutePathBuf {
path.canonicalize().unwrap_or_else(|_| path.clone())
}
#[cfg(test)]
#[path = "invocation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,215 @@
use std::collections::HashMap;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_absolute_path::test_support::PathBufExt;
use akode_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use super::*;
#[derive(Default)]
struct TestLookup {
by_scripts_dir: HashMap<AbsolutePathBuf, SkillMetadata>,
by_doc_path: HashMap<AbsolutePathBuf, SkillMetadata>,
}
impl ImplicitSkillLookup for TestLookup {
fn implicit_skill_for_scripts_dir(&self, path: &AbsolutePathBuf) -> Option<&SkillMetadata> {
self.by_scripts_dir.get(path)
}
fn implicit_skill_for_doc_path(&self, path: &AbsolutePathBuf) -> Option<&SkillMetadata> {
self.by_doc_path.get(path)
}
}
fn test_skill_metadata(skill_doc_path: AbsolutePathBuf) -> SkillMetadata {
SkillMetadata {
name: "test-skill".to_string(),
description: "test".to_string(),
short_description: None,
interface: None,
dependencies: None,
policy: None,
path_to_skills_md: skill_doc_path.into(),
scope: akode_protocol::protocol::SkillScope::User,
plugin_id: None,
}
}
fn test_path_display(unix_path: &str) -> String {
test_path_buf(unix_path).display().to_string()
}
#[test]
fn script_run_detection_matches_runner_plus_extension() {
let tokens = vec![
"python3".to_string(),
"-u".to_string(),
"scripts/fetch_comments.py".to_string(),
];
assert!(script_run_token(&tokens).is_some());
}
#[test]
fn script_run_detection_excludes_python_c() {
let tokens = vec![
"python3".to_string(),
"-c".to_string(),
"print(1)".to_string(),
];
assert!(script_run_token(&tokens).is_none());
}
#[test]
fn powershell_skill_doc_read_matches_common_forms() {
let skill_doc_path = test_path_buf("/tmp/skill-test/SKILL.md").abs();
let spaced_skill_doc_path = test_path_buf("/tmp/skill test/SKILL.md").abs();
let skill = test_skill_metadata(skill_doc_path.clone());
let spaced_skill = test_skill_metadata(spaced_skill_doc_path.clone());
let outcome = TestLookup {
by_doc_path: HashMap::from([
(canonicalize_if_exists(&skill_doc_path), skill),
(canonicalize_if_exists(&spaced_skill_doc_path), spaced_skill),
]),
..Default::default()
};
let path = skill_doc_path.display();
let spaced_path = spaced_skill_doc_path.display();
for command in [
format!("Get-Content {path}"),
format!("Get-Content -Raw {path}"),
format!("Get-Content \"{spaced_path}\""),
format!("Get-Content -Raw \"{spaced_path}\""),
format!("get-content -raw '{spaced_path}'"),
] {
let found = detect_implicit_skill_invocation_for_command(
&outcome,
&command,
&test_path_buf("/tmp").abs(),
);
assert_eq!(
found.map(|value| value.name),
Some("test-skill".to_string()),
"command: {command}"
);
}
}
#[test]
fn windows_executor_skill_reads_share_powershell_classification() {
let workdir = PathUri::parse("file:///C:/skills").expect("Windows workdir URI");
let document = PathUri::parse("file:///C:/skills/demo/SKILL.md").expect("skill URI");
for command in [
r"Get-Content C:\skills\demo\SKILL.md",
r"get-content -Raw C:\skills\demo\SKILL.md",
r"Get-Content -Path C:\skills\demo\SKILL.md",
r"Get-Content -LiteralPath C:\skills\demo\SKILL.md",
r"Get-Content C:\skills\demo\SKILL.md -Raw",
r"Get-Content -Raw -LiteralPath C:\skills\demo\SKILL.md",
r"gc C:\skills\demo\SKILL.md",
r"type C:\skills\demo\SKILL.md",
] {
assert_eq!(
implicit_skill_accesses_for_command(command, &workdir),
vec![ImplicitSkillAccess::Document(document.clone())],
"command: {command}"
);
}
}
#[test]
fn skill_doc_read_detection_matches_absolute_path() {
let skill_doc_path = test_path_buf("/tmp/skill-test/SKILL.md").abs();
let normalized_skill_doc_path = canonicalize_if_exists(&skill_doc_path);
let skill = test_skill_metadata(skill_doc_path);
let outcome = TestLookup {
by_doc_path: HashMap::from([(normalized_skill_doc_path, skill)]),
..Default::default()
};
let tokens = vec![
"cat".to_string(),
test_path_display("/tmp/skill-test/SKILL.md"),
"|".to_string(),
"head".to_string(),
];
let found = detect_skill_doc_read(&outcome, &tokens, &test_path_buf("/tmp").abs());
assert_eq!(
found.map(|value| value.name),
Some("test-skill".to_string())
);
}
#[test]
fn skill_doc_read_detection_matches_shared_read_parser() {
let skill_doc_path = test_path_buf("/tmp/skill-test/SKILL.md").abs();
let normalized_skill_doc_path = canonicalize_if_exists(&skill_doc_path);
let skill = test_skill_metadata(skill_doc_path);
let outcome = TestLookup {
by_doc_path: HashMap::from([(normalized_skill_doc_path, skill)]),
..Default::default()
};
let tokens = vec![
"nl".to_string(),
"-ba".to_string(),
test_path_display("/tmp/skill-test/SKILL.md"),
];
let found = detect_skill_doc_read(&outcome, &tokens, &test_path_buf("/tmp").abs());
assert_eq!(
found.map(|value| value.name),
Some("test-skill".to_string())
);
}
#[test]
fn skill_script_run_detection_matches_relative_path_from_skill_root() {
let skill_doc_path = test_path_buf("/tmp/skill-test/SKILL.md").abs();
let scripts_dir = canonicalize_if_exists(&test_path_buf("/tmp/skill-test/scripts").abs());
let skill = test_skill_metadata(skill_doc_path);
let outcome = TestLookup {
by_scripts_dir: HashMap::from([(scripts_dir, skill)]),
..Default::default()
};
let tokens = vec![
"python3".to_string(),
"scripts/fetch_comments.py".to_string(),
];
let found = detect_skill_script_run(&outcome, &tokens, &test_path_buf("/tmp/skill-test").abs());
assert_eq!(
found.map(|value| value.name),
Some("test-skill".to_string())
);
}
#[test]
fn skill_script_run_detection_matches_absolute_path_from_any_workdir() {
let skill_doc_path = test_path_buf("/tmp/skill-test/SKILL.md").abs();
let scripts_dir = canonicalize_if_exists(&test_path_buf("/tmp/skill-test/scripts").abs());
let skill = test_skill_metadata(skill_doc_path);
let outcome = TestLookup {
by_scripts_dir: HashMap::from([(scripts_dir, skill)]),
..Default::default()
};
let tokens = vec![
"python3".to_string(),
test_path_display("/tmp/skill-test/scripts/fetch_comments.py"),
];
let found = detect_skill_script_run(&outcome, &tokens, &test_path_buf("/tmp/other").abs());
assert_eq!(
found.map(|value| value.name),
Some("test-skill".to_string())
);
}

217
akode-rs/skills/src/lib.rs Normal file
View File

@@ -0,0 +1,217 @@
mod interface;
mod invocation;
mod loading;
mod mentions;
mod metadata;
mod model;
mod name_counts;
mod parser;
mod selection;
pub use interface::SkillInterfaceAssetPolicy;
pub use interface::SkillInterfaceFile;
pub use interface::resolve_skill_interface;
pub use invocation::ImplicitSkillAccess;
pub use invocation::ImplicitSkillLookup;
pub use invocation::detect_implicit_skill_invocation_for_command;
pub use invocation::implicit_skill_accesses_for_command;
pub use loading::LoadedSkillRoot;
pub use loading::LoadedSkills;
pub use loading::SkillError;
pub use loading::SkillLoadFuture;
pub use loading::SkillRootLoadRequest;
pub use loading::SkillRootLoader;
pub use loading::SkillRootSnapshotCache;
pub use loading::SkillRootSnapshots;
pub use mentions::ToolMentionKind;
pub use mentions::ToolMentions;
pub use mentions::app_id_from_path;
pub use mentions::extract_tool_mentions;
pub use mentions::extract_tool_mentions_with_sigil;
pub use mentions::normalize_skill_path;
pub use mentions::plugin_config_name_from_path;
pub use mentions::tool_kind_for_path;
pub use metadata::ParsedSkillMetadata;
pub use metadata::parse_skill_metadata;
pub use model::EnvironmentSkillMetadata;
pub use model::SkillDependencies;
pub use model::SkillInterface;
pub use model::SkillMetadata;
pub use model::SkillPolicy;
pub use model::SkillToolDependency;
pub use name_counts::build_skill_name_counts;
pub use parser::ParsedSkillFrontmatter;
pub use parser::SkillParseError;
pub use parser::parse_skill_frontmatter_metadata;
pub use selection::ExplicitSkillLookup;
pub use selection::collect_explicit_skill_mentions;
use akode_utils_absolute_path::AbsolutePathBuf;
use include_dir::Dir;
use std::collections::hash_map::DefaultHasher;
use std::fs;
use std::hash::Hash;
use std::hash::Hasher;
use thiserror::Error;
const SYSTEM_SKILLS_DIR: Dir = include_dir::include_dir!("$CARGO_MANIFEST_DIR/src/assets/samples");
const SYSTEM_SKILLS_DIR_NAME: &str = ".system";
const SKILLS_DIR_NAME: &str = "skills";
const SYSTEM_SKILLS_MARKER_FILENAME: &str = ".codex-system-skills.marker";
const SYSTEM_SKILLS_MARKER_SALT: &str = "v1";
/// Returns the on-disk cache location for embedded system skills from an absolute AKODE_HOME.
pub fn system_cache_root_dir(codex_home: &AbsolutePathBuf) -> AbsolutePathBuf {
codex_home
.join(SKILLS_DIR_NAME)
.join(SYSTEM_SKILLS_DIR_NAME)
}
/// Installs embedded system skills into `AKODE_HOME/skills/.system`.
///
/// Clears any existing system skills directory first and then writes the embedded
/// skills directory into place.
///
/// To avoid doing unnecessary work on every startup, a marker file is written
/// with a fingerprint of the embedded directory. When the marker matches, the
/// install is skipped.
pub fn install_system_skills(codex_home: &AbsolutePathBuf) -> Result<(), SystemSkillsError> {
let skills_root_dir = codex_home.join(SKILLS_DIR_NAME);
fs::create_dir_all(skills_root_dir.as_path())
.map_err(|source| SystemSkillsError::io("create skills root dir", source))?;
let dest_system = system_cache_root_dir(codex_home);
let marker_path = dest_system.join(SYSTEM_SKILLS_MARKER_FILENAME);
let expected_fingerprint = embedded_system_skills_fingerprint();
if dest_system.as_path().is_dir()
&& read_marker(&marker_path).is_ok_and(|marker| marker == expected_fingerprint)
{
return Ok(());
}
if dest_system.as_path().exists() {
fs::remove_dir_all(dest_system.as_path())
.map_err(|source| SystemSkillsError::io("remove existing system skills dir", source))?;
}
write_embedded_dir(&SYSTEM_SKILLS_DIR, &dest_system)?;
fs::write(marker_path.as_path(), format!("{expected_fingerprint}\n"))
.map_err(|source| SystemSkillsError::io("write system skills marker", source))?;
Ok(())
}
fn read_marker(path: &AbsolutePathBuf) -> Result<String, SystemSkillsError> {
Ok(fs::read_to_string(path.as_path())
.map_err(|source| SystemSkillsError::io("read system skills marker", source))?
.trim()
.to_string())
}
fn embedded_system_skills_fingerprint() -> String {
let mut items = Vec::new();
collect_fingerprint_items(&SYSTEM_SKILLS_DIR, &mut items);
items.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
let mut hasher = DefaultHasher::new();
SYSTEM_SKILLS_MARKER_SALT.hash(&mut hasher);
for (path, contents_hash) in items {
path.hash(&mut hasher);
contents_hash.hash(&mut hasher);
}
format!("{:x}", hasher.finish())
}
fn collect_fingerprint_items(dir: &Dir<'_>, items: &mut Vec<(String, Option<u64>)>) {
for entry in dir.entries() {
match entry {
include_dir::DirEntry::Dir(subdir) => {
items.push((subdir.path().to_string_lossy().to_string(), None));
collect_fingerprint_items(subdir, items);
}
include_dir::DirEntry::File(file) => {
let mut file_hasher = DefaultHasher::new();
file.contents().hash(&mut file_hasher);
items.push((
file.path().to_string_lossy().to_string(),
Some(file_hasher.finish()),
));
}
}
}
}
/// Writes the embedded `include_dir::Dir` to disk under `dest`.
///
/// Preserves the embedded directory structure.
fn write_embedded_dir(dir: &Dir<'_>, dest: &AbsolutePathBuf) -> Result<(), SystemSkillsError> {
fs::create_dir_all(dest.as_path())
.map_err(|source| SystemSkillsError::io("create system skills dir", source))?;
for entry in dir.entries() {
match entry {
include_dir::DirEntry::Dir(subdir) => {
let subdir_dest = dest.join(subdir.path());
fs::create_dir_all(subdir_dest.as_path()).map_err(|source| {
SystemSkillsError::io("create system skills subdir", source)
})?;
write_embedded_dir(subdir, dest)?;
}
include_dir::DirEntry::File(file) => {
let path = dest.join(file.path());
if let Some(parent) = path.as_path().parent() {
fs::create_dir_all(parent).map_err(|source| {
SystemSkillsError::io("create system skills file parent", source)
})?;
}
fs::write(path.as_path(), file.contents())
.map_err(|source| SystemSkillsError::io("write system skill file", source))?;
}
}
}
Ok(())
}
#[derive(Debug, Error)]
pub enum SystemSkillsError {
#[error("io error while {action}: {source}")]
Io {
action: &'static str,
#[source]
source: std::io::Error,
},
}
impl SystemSkillsError {
fn io(action: &'static str, source: std::io::Error) -> Self {
Self::Io { action, source }
}
}
#[cfg(test)]
mod tests {
use super::SYSTEM_SKILLS_DIR;
use super::collect_fingerprint_items;
#[test]
fn fingerprint_traverses_nested_entries() {
let mut items = Vec::new();
collect_fingerprint_items(&SYSTEM_SKILLS_DIR, &mut items);
let mut paths: Vec<String> = items.into_iter().map(|(path, _)| path).collect();
paths.sort_unstable();
assert!(
paths
.binary_search_by(|probe| probe.as_str().cmp("skill-creator/SKILL.md"))
.is_ok()
);
assert!(
paths
.binary_search_by(|probe| probe.as_str().cmp("skill-creator/scripts/init_skill.py"))
.is_ok()
);
}
}

View File

@@ -0,0 +1,120 @@
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::hash::Hash;
use std::hash::Hasher;
use std::pin::Pin;
use std::sync::Arc;
use akode_protocol::protocol::Product;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use crate::SkillMetadata;
/// A skill document that could not be read, parsed, or validated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillError {
pub path: AbsolutePathBuf,
pub message: String,
}
/// Filesystem-independent metadata discovered beneath one canonical skill root.
#[derive(Debug, Clone, PartialEq)]
pub struct LoadedSkillRoot {
pub root: AbsolutePathBuf,
pub skills: Vec<SkillMetadata>,
pub skill_discovery_path_by_path: Arc<HashMap<PathUri, PathUri>>,
pub errors: Vec<SkillError>,
pub is_agent_plugin: bool,
}
/// Skills and errors produced by loading an ordered set of roots.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct LoadedSkills {
pub skills: Vec<SkillMetadata>,
pub errors: Vec<SkillError>,
}
/// Caches parsed roots without assigning ownership of the cache to a loader.
///
/// Implementations own storage and determine its lifetime; loaders may reuse an existing snapshot
/// or publish a newly loaded one without learning about the caller's broader state.
pub trait SkillRootSnapshotCache<Root>: Send + Sync {
fn get(&self, root: &Root) -> Option<LoadedSkillRoot>;
fn insert(&self, root: Root, snapshot: LoadedSkillRoot);
}
/// Shared access to one owner-managed collection of parsed skill roots.
///
/// Equality and hashing use the cache allocation's identity so callers can include the handle in
/// their own cache keys without inspecting or taking ownership of its contents.
pub struct SkillRootSnapshots<Root> {
cache: Arc<dyn SkillRootSnapshotCache<Root>>,
}
impl<Root> SkillRootSnapshots<Root> {
pub fn new(cache: Arc<dyn SkillRootSnapshotCache<Root>>) -> Self {
Self { cache }
}
pub fn get(&self, root: &Root) -> Option<LoadedSkillRoot> {
self.cache.get(root)
}
pub fn insert(&self, root: Root, snapshot: LoadedSkillRoot) {
self.cache.insert(root, snapshot);
}
}
impl<Root> Clone for SkillRootSnapshots<Root> {
fn clone(&self) -> Self {
Self {
cache: Arc::clone(&self.cache),
}
}
}
impl<Root> PartialEq for SkillRootSnapshots<Root> {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.cache, &other.cache)
}
}
impl<Root> Eq for SkillRootSnapshots<Root> {}
impl<Root> Hash for SkillRootSnapshots<Root> {
fn hash<H: Hasher>(&self, state: &mut H) {
(Arc::as_ptr(&self.cache) as *const ()).hash(state);
}
}
impl<Root> fmt::Debug for SkillRootSnapshots<Root> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SkillRootSnapshots").finish_non_exhaustive()
}
}
/// Inputs for loading roots while optionally reusing snapshots owned by the caller.
#[derive(Debug, Clone)]
pub struct SkillRootLoadRequest<Root> {
pub roots: Vec<Root>,
pub restriction_product: Option<Product>,
pub snapshots: Option<SkillRootSnapshots<Root>>,
}
/// Object-safe future returned by a shared skill-root loader.
pub type SkillLoadFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// Loads ordered skill roots without owning their source inventory or capability state.
///
/// Implementations are responsible for filesystem access, metadata parsing, root precedence,
/// product filtering, and reuse of any snapshots supplied in the request.
pub trait SkillRootLoader<Root>: Send + Sync {
fn load_roots(&self, request: SkillRootLoadRequest<Root>) -> SkillLoadFuture<'_, LoadedSkills>;
}
#[cfg(test)]
#[path = "loading_tests.rs"]
mod tests;

View File

@@ -0,0 +1,79 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Mutex;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use super::LoadedSkillRoot;
use super::LoadedSkills;
use super::SkillLoadFuture;
use super::SkillRootLoadRequest;
use super::SkillRootLoader;
use super::SkillRootSnapshotCache;
use super::SkillRootSnapshots;
#[derive(Default)]
struct TestSnapshotCache {
snapshots: Mutex<HashMap<String, LoadedSkillRoot>>,
}
impl SkillRootSnapshotCache<String> for TestSnapshotCache {
fn get(&self, root: &String) -> Option<LoadedSkillRoot> {
self.snapshots.lock().unwrap().get(root).cloned()
}
fn insert(&self, root: String, snapshot: LoadedSkillRoot) {
self.snapshots.lock().unwrap().insert(root, snapshot);
}
}
struct TestSkillRootLoader;
impl SkillRootLoader<String> for TestSkillRootLoader {
fn load_roots(
&self,
_request: SkillRootLoadRequest<String>,
) -> SkillLoadFuture<'_, LoadedSkills> {
Box::pin(async { LoadedSkills::default() })
}
}
#[test]
fn snapshot_handles_share_owner_managed_values_and_identity() {
let snapshots = SkillRootSnapshots::new(Arc::new(TestSnapshotCache::default()));
let cloned_snapshots = snapshots.clone();
let separate_snapshots = SkillRootSnapshots::new(Arc::new(TestSnapshotCache::default()));
let root = "plugin-root".to_string();
let snapshot = LoadedSkillRoot {
root: AbsolutePathBuf::try_from(std::env::temp_dir()).unwrap(),
skills: Vec::new(),
skill_discovery_path_by_path: Arc::new(HashMap::new()),
errors: Vec::new(),
is_agent_plugin: false,
};
snapshots.insert(root.clone(), snapshot.clone());
assert_eq!(cloned_snapshots.get(&root), Some(snapshot));
assert_eq!(separate_snapshots.get(&root), None);
assert_eq!(snapshots, cloned_snapshots);
assert_ne!(snapshots, separate_snapshots);
assert_eq!(
HashSet::from([snapshots, cloned_snapshots, separate_snapshots]).len(),
2
);
}
#[test]
fn skill_root_loader_supports_shared_trait_objects() {
let loader: Arc<dyn SkillRootLoader<String>> = Arc::new(TestSkillRootLoader);
let future = loader.load_roots(SkillRootLoadRequest {
roots: vec!["plugin-root".to_string()],
restriction_product: None,
snapshots: None,
});
drop(future);
}

View File

@@ -0,0 +1,232 @@
use std::collections::HashSet;
pub struct ToolMentions<'a> {
names: HashSet<&'a str>,
paths: HashSet<&'a str>,
plain_names: HashSet<&'a str>,
}
impl<'a> ToolMentions<'a> {
pub fn is_empty(&self) -> bool {
self.names.is_empty() && self.paths.is_empty()
}
pub fn plain_names(&self) -> impl Iterator<Item = &'a str> + '_ {
self.plain_names.iter().copied()
}
pub fn contains_plain_name(&self, name: &str) -> bool {
self.plain_names.contains(name)
}
pub fn paths(&self) -> impl Iterator<Item = &'a str> + '_ {
self.paths.iter().copied()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ToolMentionKind {
App,
Mcp,
Plugin,
Skill,
Other,
}
const APP_PATH_PREFIX: &str = "app://";
const MCP_PATH_PREFIX: &str = "mcp://";
const PLUGIN_PATH_PREFIX: &str = "plugin://";
const SKILL_PATH_PREFIX: &str = "skill://";
const SKILL_FILENAME: &str = "SKILL.md";
const TOOL_MENTION_SIGIL: char = '$';
pub fn tool_kind_for_path(path: &str) -> ToolMentionKind {
if path.starts_with(APP_PATH_PREFIX) {
ToolMentionKind::App
} else if path.starts_with(MCP_PATH_PREFIX) {
ToolMentionKind::Mcp
} else if path.starts_with(PLUGIN_PATH_PREFIX) {
ToolMentionKind::Plugin
} else if path.starts_with(SKILL_PATH_PREFIX) || is_skill_filename(path) {
ToolMentionKind::Skill
} else {
ToolMentionKind::Other
}
}
fn is_skill_filename(path: &str) -> bool {
let file_name = path.rsplit(['/', '\\']).next().unwrap_or(path);
file_name.eq_ignore_ascii_case(SKILL_FILENAME)
}
pub fn app_id_from_path(path: &str) -> Option<&str> {
path.strip_prefix(APP_PATH_PREFIX)
.filter(|value| !value.is_empty())
}
/// Desktop app/browser mentions append `?app=...` or `?browserFamily=...`.
/// Ignore these targeting parameters when matching the plugin ID.
pub fn plugin_config_name_from_path(path: &str) -> Option<&str> {
path.strip_prefix(PLUGIN_PATH_PREFIX)
.and_then(|value| value.split('?').next())
.filter(|value| !value.is_empty())
}
pub fn normalize_skill_path(path: &str) -> &str {
path.strip_prefix(SKILL_PATH_PREFIX).unwrap_or(path)
}
/// Extract `$tool-name` mentions from a single text input.
///
/// Supports explicit resource links in the form `[$tool-name](resource path)`. When a
/// resource path is present, it is captured for exact path matching while also tracking
/// the name for fallback matching.
pub fn extract_tool_mentions(text: &str) -> ToolMentions<'_> {
extract_tool_mentions_with_sigil(text, TOOL_MENTION_SIGIL)
}
pub fn extract_tool_mentions_with_sigil(text: &str, sigil: char) -> ToolMentions<'_> {
let text_bytes = text.as_bytes();
let mut mentioned_names: HashSet<&str> = HashSet::new();
let mut mentioned_paths: HashSet<&str> = HashSet::new();
let mut plain_names: HashSet<&str> = HashSet::new();
let mut index = 0;
while index < text_bytes.len() {
let byte = text_bytes[index];
if byte == b'['
&& let Some((name, path, end_index)) =
parse_linked_tool_mention(text, text_bytes, index, sigil)
{
if !is_common_env_var(name) {
if !matches!(
tool_kind_for_path(path),
ToolMentionKind::App | ToolMentionKind::Mcp | ToolMentionKind::Plugin
) {
mentioned_names.insert(name);
}
mentioned_paths.insert(path);
}
index = end_index;
continue;
}
if byte != sigil as u8 {
index += 1;
continue;
}
let name_start = index + 1;
let Some(first_name_byte) = text_bytes.get(name_start) else {
index += 1;
continue;
};
if !is_mention_name_char(*first_name_byte) {
index += 1;
continue;
}
let mut name_end = name_start + 1;
while let Some(next_byte) = text_bytes.get(name_end)
&& is_mention_name_char(*next_byte)
{
name_end += 1;
}
let name = &text[name_start..name_end];
if !is_common_env_var(name) {
mentioned_names.insert(name);
plain_names.insert(name);
}
index = name_end;
}
ToolMentions {
names: mentioned_names,
paths: mentioned_paths,
plain_names,
}
}
fn parse_linked_tool_mention<'a>(
text: &'a str,
text_bytes: &[u8],
start: usize,
sigil: char,
) -> Option<(&'a str, &'a str, usize)> {
let sigil_index = start + 1;
if text_bytes.get(sigil_index) != Some(&(sigil as u8)) {
return None;
}
let name_start = sigil_index + 1;
let first_name_byte = text_bytes.get(name_start)?;
if !is_mention_name_char(*first_name_byte) {
return None;
}
let mut name_end = name_start + 1;
while let Some(next_byte) = text_bytes.get(name_end)
&& is_mention_name_char(*next_byte)
{
name_end += 1;
}
if text_bytes.get(name_end) != Some(&b']') {
return None;
}
let mut path_start = name_end + 1;
while let Some(next_byte) = text_bytes.get(path_start)
&& next_byte.is_ascii_whitespace()
{
path_start += 1;
}
if text_bytes.get(path_start) != Some(&b'(') {
return None;
}
let mut path_end = path_start + 1;
while let Some(next_byte) = text_bytes.get(path_end)
&& *next_byte != b')'
{
path_end += 1;
}
if text_bytes.get(path_end) != Some(&b')') {
return None;
}
let path = text[path_start + 1..path_end].trim();
if path.is_empty() {
return None;
}
let name = &text[name_start..name_end];
Some((name, path, path_end + 1))
}
fn is_common_env_var(name: &str) -> bool {
let upper = name.to_ascii_uppercase();
matches!(
upper.as_str(),
"PATH"
| "HOME"
| "USER"
| "SHELL"
| "PWD"
| "TMPDIR"
| "TEMP"
| "TMP"
| "LANG"
| "TERM"
| "XDG_CONFIG_HOME"
)
}
fn is_mention_name_char(byte: u8) -> bool {
matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-' | b':')
}
#[cfg(test)]
#[path = "mentions_tests.rs"]
mod tests;

View File

@@ -0,0 +1,105 @@
use std::collections::HashSet;
use pretty_assertions::assert_eq;
use super::*;
fn set<'a>(items: &'a [&'a str]) -> HashSet<&'a str> {
items.iter().copied().collect()
}
fn assert_mentions(text: &str, expected_names: &[&str], expected_paths: &[&str]) {
let mentions = extract_tool_mentions(text);
assert_eq!(mentions.names, set(expected_names));
assert_eq!(mentions.paths, set(expected_paths));
}
#[test]
fn handles_plain_and_linked_mentions() {
assert_mentions(
"use $alpha and [$beta](/tmp/beta)",
&["alpha", "beta"],
&["/tmp/beta"],
);
}
#[test]
fn skips_common_env_vars() {
assert_mentions("use $PATH and $alpha", &["alpha"], &[]);
assert_mentions("use [$HOME](/tmp/skill)", &[], &[]);
assert_mentions("use $XDG_CONFIG_HOME and $beta", &["beta"], &[]);
}
#[test]
fn requires_link_syntax() {
assert_mentions("[beta](/tmp/beta)", &[], &[]);
assert_mentions("[$beta] /tmp/beta", &["beta"], &[]);
assert_mentions("[$beta]()", &["beta"], &[]);
}
#[test]
fn trims_linked_paths_and_allows_spacing() {
assert_mentions("use [$beta] ( /tmp/beta )", &["beta"], &["/tmp/beta"]);
}
#[test]
fn stops_at_non_name_chars() {
assert_mentions(
"use $alpha.skill and $beta_extra",
&["alpha", "beta_extra"],
&[],
);
}
#[test]
fn keeps_plugin_skill_namespaces() {
assert_mentions(
"use $slack:search and $alpha",
&["alpha", "slack:search"],
&[],
);
}
#[test]
fn requires_exact_name_boundaries() {
assert_mentions(
"use $notion-research-doc but not $notion-research-docs or $notion-research-doc_extra",
&[
"notion-research-doc",
"notion-research-docs",
"notion-research-doc_extra",
],
&[],
);
}
#[test]
fn handles_many_sigils_without_looping() {
let prefix = "$".repeat(256);
assert_mentions(&format!("{prefix} not-a-mention"), &[], &[]);
}
#[test]
fn plugin_config_names_ignore_mention_query_parameters() {
let paths = [
"plugin://sample@test",
"plugin://sample@test?app=com.example.editor",
"plugin://sample@test?browserFamily=chrome",
];
assert_eq!(
paths.map(plugin_config_name_from_path),
[Some("sample@test"); 3],
);
}
#[test]
fn plugin_config_names_require_a_plugin_identity() {
let paths = [
"plugin://",
"plugin://?app=com.example.editor",
"app://sample@test?app=com.example.editor",
];
assert_eq!(paths.map(plugin_config_name_from_path), [None; 3]);
}

View File

@@ -0,0 +1,164 @@
//! Parses optional skill YAML metadata with shared host and executor validation.
use akode_protocol::protocol::Product;
use serde::Deserialize;
use crate::SkillDependencies;
use crate::SkillInterfaceFile;
use crate::SkillPolicy;
use crate::SkillToolDependency;
const MAX_DEPENDENCY_TYPE_LEN: usize = 64;
const MAX_DEPENDENCY_TRANSPORT_LEN: usize = 64;
const MAX_DEPENDENCY_VALUE_LEN: usize = 1024;
const MAX_DEPENDENCY_DESCRIPTION_LEN: usize = 1024;
const MAX_DEPENDENCY_COMMAND_LEN: usize = 1024;
const MAX_DEPENDENCY_URL_LEN: usize = 1024;
/// Parsed optional metadata; callers resolve interface assets for their filesystem.
#[derive(Debug, Default)]
pub struct ParsedSkillMetadata {
pub interface: Option<SkillInterfaceFile>,
pub dependencies: Option<SkillDependencies>,
pub policy: Option<SkillPolicy>,
}
/// Parses `agents/openai.yaml`, dropping invalid individual dependency declarations.
pub fn parse_skill_metadata(contents: &str) -> Result<ParsedSkillMetadata, serde_yaml::Error> {
let parsed: SkillMetadataFile = serde_yaml::from_str(contents)?;
Ok(ParsedSkillMetadata {
interface: parsed.interface,
dependencies: resolve_dependencies(parsed.dependencies),
policy: resolve_policy(parsed.policy),
})
}
#[derive(Debug, Default, Deserialize)]
struct SkillMetadataFile {
#[serde(default)]
interface: Option<SkillInterfaceFile>,
#[serde(default)]
dependencies: Option<Dependencies>,
#[serde(default)]
policy: Option<Policy>,
}
#[derive(Debug, Default, Deserialize)]
struct Dependencies {
#[serde(default)]
tools: Vec<DependencyTool>,
}
#[derive(Debug, Deserialize)]
struct Policy {
#[serde(default)]
allow_implicit_invocation: Option<bool>,
#[serde(default)]
products: Vec<Product>,
}
#[derive(Debug, Default, Deserialize)]
struct DependencyTool {
#[serde(rename = "type")]
kind: Option<String>,
value: Option<String>,
description: Option<String>,
transport: Option<String>,
command: Option<String>,
url: Option<String>,
oauth: Option<DependencyOAuth>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct DependencyOAuth {
#[serde(alias = "callback_port")]
callback_port: Option<u16>,
}
fn resolve_dependencies(dependencies: Option<Dependencies>) -> Option<SkillDependencies> {
let dependencies = dependencies?;
let tools = dependencies
.tools
.into_iter()
.filter_map(resolve_dependency_tool)
.collect::<Vec<_>>();
if tools.is_empty() {
None
} else {
Some(SkillDependencies { tools })
}
}
fn resolve_policy(policy: Option<Policy>) -> Option<SkillPolicy> {
policy.map(|policy| SkillPolicy {
allow_implicit_invocation: policy.allow_implicit_invocation,
products: policy.products,
})
}
fn resolve_dependency_tool(tool: DependencyTool) -> Option<SkillToolDependency> {
let r#type = resolve_required_str(
tool.kind,
MAX_DEPENDENCY_TYPE_LEN,
"dependencies.tools.type",
)?;
let value = resolve_required_str(
tool.value,
MAX_DEPENDENCY_VALUE_LEN,
"dependencies.tools.value",
)?;
let description = resolve_str(
tool.description,
MAX_DEPENDENCY_DESCRIPTION_LEN,
"dependencies.tools.description",
);
let transport = resolve_str(
tool.transport,
MAX_DEPENDENCY_TRANSPORT_LEN,
"dependencies.tools.transport",
);
let command = resolve_str(
tool.command,
MAX_DEPENDENCY_COMMAND_LEN,
"dependencies.tools.command",
);
let url = resolve_str(tool.url, MAX_DEPENDENCY_URL_LEN, "dependencies.tools.url");
let oauth_callback_port = tool.oauth.and_then(|oauth| oauth.callback_port);
Some(SkillToolDependency {
r#type,
value,
description,
transport,
command,
url,
oauth_callback_port,
})
}
fn resolve_str(value: Option<String>, max_len: usize, field: &'static str) -> Option<String> {
let value = value?;
let value = value.split_whitespace().collect::<Vec<_>>().join(" ");
if value.is_empty() {
tracing::warn!("ignoring {field}: value is empty");
return None;
}
if value.chars().count() > max_len {
tracing::warn!("ignoring {field}: exceeds maximum length of {max_len} characters");
return None;
}
Some(value)
}
fn resolve_required_str(
value: Option<String>,
max_len: usize,
field: &'static str,
) -> Option<String> {
let Some(value) = value else {
tracing::warn!("ignoring {field}: value is missing");
return None;
};
resolve_str(Some(value), max_len, field)
}

View File

@@ -0,0 +1,112 @@
use akode_protocol::protocol::Product;
use akode_protocol::protocol::SkillScope;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
/// Metadata for one skill materialized on the host filesystem.
#[derive(Debug, Clone, PartialEq)]
pub struct SkillMetadata {
pub name: String,
pub description: String,
pub short_description: Option<String>,
pub interface: Option<SkillInterface>,
pub dependencies: Option<SkillDependencies>,
pub policy: Option<SkillPolicy>,
/// Path to the SKILL.md file that declares this skill.
pub path_to_skills_md: PathUri,
pub scope: SkillScope,
pub plugin_id: Option<String>,
}
impl SkillMetadata {
pub fn allows_implicit_invocation(&self) -> bool {
self.policy
.as_ref()
.and_then(|policy| policy.allow_implicit_invocation)
.unwrap_or(true)
}
pub fn matches_product_restriction_for_product(
&self,
restriction_product: Option<Product>,
) -> bool {
matches_product_restriction(self.policy.as_ref(), restriction_product)
}
}
/// URI-native metadata for one skill owned by an execution environment.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EnvironmentSkillMetadata {
pub path_to_skills_md: PathUri,
pub name: String,
pub description: String,
pub short_description: Option<String>,
pub dependencies: Option<SkillDependencies>,
pub policy: Option<SkillPolicy>,
}
impl EnvironmentSkillMetadata {
pub fn allows_implicit_invocation(&self) -> bool {
self.policy
.as_ref()
.and_then(|policy| policy.allow_implicit_invocation)
.unwrap_or(true)
}
pub fn matches_product_restriction(&self, restriction_product: Option<Product>) -> bool {
matches_product_restriction(self.policy.as_ref(), restriction_product)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SkillPolicy {
pub allow_implicit_invocation: Option<bool>,
pub products: Vec<Product>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillInterface {
pub display_name: Option<String>,
pub short_description: Option<String>,
pub icon_small: Option<AbsolutePathBuf>,
pub icon_large: Option<AbsolutePathBuf>,
pub brand_color: Option<String>,
pub default_prompt: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SkillDependencies {
pub tools: Vec<SkillToolDependency>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SkillToolDependency {
pub r#type: String,
pub value: String,
pub description: Option<String>,
pub transport: Option<String>,
pub command: Option<String>,
pub url: Option<String>,
pub oauth_callback_port: Option<u16>,
}
fn matches_product_restriction(
policy: Option<&SkillPolicy>,
restriction_product: Option<Product>,
) -> bool {
match policy {
Some(policy) => {
policy.products.is_empty()
|| restriction_product
.is_some_and(|product| product.matches_product_restriction(&policy.products))
}
None => true,
}
}
#[cfg(test)]
#[path = "model_tests.rs"]
mod tests;

View File

@@ -0,0 +1,36 @@
use super::*;
#[test]
fn missing_policy_allows_implicit_invocation_and_all_products() {
let skill = EnvironmentSkillMetadata {
path_to_skills_md: PathUri::parse("file:///skills/demo/SKILL.md").expect("valid skill URI"),
name: "demo".to_string(),
description: "Demo skill".to_string(),
short_description: None,
dependencies: None,
policy: None,
};
assert!(skill.allows_implicit_invocation());
assert!(skill.matches_product_restriction(/*restriction_product*/ None));
}
#[test]
fn policy_restricts_implicit_invocation_and_products() {
let policy = SkillPolicy {
allow_implicit_invocation: Some(false),
products: vec![Product::Codex],
};
let skill = EnvironmentSkillMetadata {
path_to_skills_md: PathUri::parse("file:///skills/demo/SKILL.md").expect("valid skill URI"),
name: "demo".to_string(),
description: "Demo skill".to_string(),
short_description: None,
dependencies: None,
policy: Some(policy),
};
assert!(!skill.allows_implicit_invocation());
assert!(skill.matches_product_restriction(Some(Product::Codex)));
assert!(!skill.matches_product_restriction(/*restriction_product*/ None));
}

View File

@@ -0,0 +1,25 @@
use std::collections::HashMap;
use std::collections::HashSet;
use akode_utils_path_uri::PathUri;
use crate::SkillMetadata;
/// Counts how often each skill name appears (exact and ASCII-lowercase), excluding disabled paths.
pub fn build_skill_name_counts(
skills: &[SkillMetadata],
disabled_paths: &HashSet<PathUri>,
) -> (HashMap<String, usize>, HashMap<String, usize>) {
let mut exact_counts: HashMap<String, usize> = HashMap::new();
let mut lower_counts: HashMap<String, usize> = HashMap::new();
for skill in skills {
if disabled_paths.contains(&skill.path_to_skills_md) {
continue;
}
*exact_counts.entry(skill.name.clone()).or_insert(0) += 1;
*lower_counts
.entry(skill.name.to_ascii_lowercase())
.or_insert(0) += 1;
}
(exact_counts, lower_counts)
}

View File

@@ -0,0 +1,225 @@
use serde::Deserialize;
use thiserror::Error;
const MAX_NAME_LEN: usize = 64;
#[derive(Debug, Deserialize)]
struct SkillFrontmatter {
#[serde(default)]
name: Option<String>,
#[serde(default)]
description: Option<String>,
#[serde(default)]
metadata: SkillFrontmatterMetadata,
}
#[derive(Debug, Default, Deserialize)]
struct SkillFrontmatterMetadata {
#[serde(default, rename = "short-description")]
short_description: Option<String>,
}
/// Validated metadata parsed from a `SKILL.md` frontmatter block.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedSkillFrontmatter {
pub name: String,
pub description: String,
pub short_description: Option<String>,
}
/// Error produced while parsing or validating `SKILL.md` metadata.
#[derive(Debug, Error)]
pub enum SkillParseError {
#[error("missing YAML frontmatter delimited by ---")]
MissingFrontmatter,
#[error("invalid YAML: {0}")]
InvalidYaml(#[source] serde_yaml::Error),
#[error("missing field `{0}`")]
MissingField(&'static str),
#[error("invalid {field}: {reason}")]
InvalidField { field: &'static str, reason: String },
}
/// Parses and validates the metadata frontmatter from `SKILL.md` contents.
pub fn parse_skill_frontmatter_metadata(
contents: &str,
default_name: impl FnOnce() -> String,
) -> Result<ParsedSkillFrontmatter, SkillParseError> {
let frontmatter = extract_frontmatter(contents).ok_or(SkillParseError::MissingFrontmatter)?;
let parsed: SkillFrontmatter = match serde_yaml::from_str(&frontmatter) {
Ok(parsed) => Ok(parsed),
Err(original_error) => match repair_frontmatter_scalar_fields(&frontmatter) {
// Some third-party skills use prose like `description: Build for AWS: ECS`
// or `argument-hint: <duration: e.g. 7d>`. Keep the repair line-oriented
// so unrelated invalid YAML still surfaces.
Some(repaired_frontmatter) => {
serde_yaml::from_str(&repaired_frontmatter).map_err(|_| original_error)
}
None => Err(original_error),
},
}
.map_err(SkillParseError::InvalidYaml)?;
let name = parsed
.name
.as_deref()
.map(sanitize_single_line)
.filter(|value| !value.is_empty())
.unwrap_or_else(default_name);
let description = parsed
.description
.as_deref()
.map(sanitize_single_line)
.unwrap_or_default();
let short_description = parsed
.metadata
.short_description
.as_deref()
.map(sanitize_single_line)
.filter(|value| !value.is_empty());
validate_len(&name, MAX_NAME_LEN, "name")?;
if description.is_empty() {
return Err(SkillParseError::MissingField("description"));
}
Ok(ParsedSkillFrontmatter {
name,
description,
short_description,
})
}
fn sanitize_single_line(raw: &str) -> String {
raw.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn repair_frontmatter_scalar_fields(frontmatter: &str) -> Option<String> {
let mut changed = false;
let mut block_scalar_indent: Option<usize> = None;
let mut repaired_lines = Vec::new();
for line in frontmatter.lines() {
let indent = line
.chars()
.take_while(|character| *character == ' ')
.count();
if let Some(block_indent) = block_scalar_indent {
if line.trim().is_empty() || indent > block_indent {
repaired_lines.push(line.to_string());
continue;
}
block_scalar_indent = None;
}
let Some((key, value)) = line.split_once(':') else {
repaired_lines.push(line.to_string());
continue;
};
if key.trim().is_empty() || !value.chars().next().is_none_or(char::is_whitespace) {
repaired_lines.push(line.to_string());
continue;
}
let trimmed_start = value.trim_start();
let leading_whitespace = &value[..value.len() - trimmed_start.len()];
let mut scalar = trimmed_start;
let mut comment = "";
for (index, character) in trimmed_start.char_indices() {
if character == '#'
&& (index == 0
|| trimmed_start[..index]
.chars()
.next_back()
.is_some_and(char::is_whitespace))
{
let comment_start = trimmed_start[..index].trim_end().len();
scalar = &trimmed_start[..comment_start];
comment = &trimmed_start[comment_start..];
break;
}
}
let scalar = scalar.trim_end();
let Some(first_char) = scalar.chars().next() else {
repaired_lines.push(line.to_string());
continue;
};
if matches!(first_char, '|' | '>') {
block_scalar_indent = Some(indent);
repaired_lines.push(line.to_string());
continue;
}
if matches!(first_char, '\'' | '"') {
repaired_lines.push(line.to_string());
continue;
}
let mut has_colon_separator = false;
let mut chars = scalar.chars().peekable();
while let Some(character) = chars.next() {
if character == ':'
&& matches!(chars.peek(), Some(next_character) if next_character.is_whitespace())
{
has_colon_separator = true;
break;
}
}
let invalid_flow_like_scalar = matches!(first_char, '[' | '{' | '@' | '`')
&& serde_yaml::from_str::<serde_yaml::Value>(scalar).is_err();
if !has_colon_separator && !invalid_flow_like_scalar {
repaired_lines.push(line.to_string());
continue;
}
let quoted_scalar = format!("'{}'", scalar.replace('\'', "''"));
repaired_lines.push(format!(
"{key}:{leading_whitespace}{quoted_scalar}{comment}"
));
changed = true;
}
changed.then(|| repaired_lines.join("\n"))
}
fn validate_len(
value: &str,
max_len: usize,
field_name: &'static str,
) -> Result<(), SkillParseError> {
if value.is_empty() {
return Err(SkillParseError::MissingField(field_name));
}
if value.chars().count() > max_len {
return Err(SkillParseError::InvalidField {
field: field_name,
reason: format!("exceeds maximum length of {max_len} characters"),
});
}
Ok(())
}
fn extract_frontmatter(contents: &str) -> Option<String> {
let mut lines = contents.lines();
if !matches!(lines.next(), Some(line) if line.trim() == "---") {
return None;
}
let mut frontmatter_lines = Vec::new();
let mut found_closing = false;
for line in lines.by_ref() {
if line.trim() == "---" {
found_closing = true;
break;
}
frontmatter_lines.push(line);
}
if frontmatter_lines.is_empty() || !found_closing {
return None;
}
Some(frontmatter_lines.join("\n"))
}
#[cfg(test)]
#[path = "parser_tests.rs"]
mod tests;

View File

@@ -0,0 +1,119 @@
use pretty_assertions::assert_eq;
use super::ParsedSkillFrontmatter;
use super::parse_skill_frontmatter_metadata;
#[test]
fn parses_repairs_and_sanitizes_frontmatter() {
let parsed = parse_skill_frontmatter_metadata(
"---\nname: deploy service\ndescription: Build for AWS: ECS\nmetadata:\n short-description: Deploy safely\n---\n",
|| "fallback".to_string(),
)
.expect("valid frontmatter");
assert_eq!(
parsed,
ParsedSkillFrontmatter {
name: "deploy service".to_string(),
description: "Build for AWS: ECS".to_string(),
short_description: Some("Deploy safely".to_string()),
}
);
}
#[test]
fn uses_default_name_and_requires_description() {
let parsed = parse_skill_frontmatter_metadata("---\ndescription: Demo skill\n---\n", || {
"demo".to_string()
})
.expect("valid frontmatter");
assert_eq!(
parsed,
ParsedSkillFrontmatter {
name: "demo".to_string(),
description: "Demo skill".to_string(),
short_description: None,
}
);
let error =
parse_skill_frontmatter_metadata("---\nname: demo\n---\n", || "fallback".to_string())
.expect_err("description should be required");
assert_eq!(error.to_string(), "missing field `description`");
}
#[test]
fn repairs_short_descriptions_containing_colons_and_apostrophes() {
let parsed = parse_skill_frontmatter_metadata(
"---\nname: short\ndescription: Short skill\nmetadata:\n short-description: What's included: builds and tests\n---\n",
|| "fallback".to_string(),
)
.expect("frontmatter with an unquoted short description should be repaired");
assert_eq!(
parsed,
ParsedSkillFrontmatter {
name: "short".to_string(),
description: "Short skill".to_string(),
short_description: Some("What's included: builds and tests".to_string()),
}
);
}
#[test]
fn repairs_unrecognized_frontmatter_fields_that_need_quotes() {
let parsed = parse_skill_frontmatter_metadata(
"---\nname: unknown\ndescription: Unknown fields\nargument-hint: <duration: e.g. 7d, 2w>\ntags: [next,@supabase/ssr]\n---\n",
|| "fallback".to_string(),
)
.expect("frontmatter with unrecognized fields should be repaired");
assert_eq!(
parsed,
ParsedSkillFrontmatter {
name: "unknown".to_string(),
description: "Unknown fields".to_string(),
short_description: None,
}
);
}
#[test]
fn preserves_block_scalar_bodies_while_repairing_other_fields() {
let parsed = parse_skill_frontmatter_metadata(
"---\nname: block\ndescription: |-\n Build for AWS: ECS\nargument-hint: <duration: e.g. 7d>\n---\n",
|| "fallback".to_string(),
)
.expect("frontmatter repair should preserve block scalar bodies");
assert_eq!(
parsed,
ParsedSkillFrontmatter {
name: "block".to_string(),
description: "Build for AWS: ECS".to_string(),
short_description: None,
}
);
}
#[test]
fn preserves_overlong_descriptions_and_short_descriptions() {
let description = "💡".repeat(/*n*/ 1_025);
let short_description = "x".repeat(/*n*/ 1_025);
let parsed = parse_skill_frontmatter_metadata(
&format!(
"---\nname: long\ndescription: {description}\nmetadata:\n short-description: {short_description}\n---\n"
),
|| "fallback".to_string(),
)
.expect("descriptions should not be truncated during frontmatter parsing");
assert_eq!(
parsed,
ParsedSkillFrontmatter {
name: "long".to_string(),
description,
short_description: Some(short_description),
}
);
}

View File

@@ -0,0 +1,204 @@
use std::collections::HashMap;
use std::collections::HashSet;
use akode_protocol::user_input::UserInput;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::LegacyAppPathString;
use akode_utils_path_uri::PathUri;
use crate::SkillMetadata;
use crate::ToolMentionKind;
use crate::ToolMentions;
use crate::build_skill_name_counts;
use crate::extract_tool_mentions;
use crate::normalize_skill_path;
use crate::tool_kind_for_path;
/// Supplies ordered skills, disabled identities, and discovery paths for explicit selection.
///
/// Implementations should preserve skill discovery order and expose the logical discovery path
/// associated with each canonical skill identity when one is available.
pub trait ExplicitSkillLookup {
fn skills(&self) -> &[SkillMetadata];
fn disabled_paths(&self) -> &HashSet<PathUri>;
fn skill_discovery_path_for_path(&self, path: &PathUri) -> Option<&PathUri>;
fn is_skill_enabled(&self, skill: &SkillMetadata) -> bool {
!self.disabled_paths().contains(&skill.path_to_skills_md)
}
}
/// Collect explicitly mentioned skills from structured and text mentions.
///
/// Structured `UserInput::Skill` selections are resolved first by path against
/// enabled skills. Text inputs are then scanned to extract `$skill-name` tokens, and we
/// iterate loaded skills in their existing order to preserve prior ordering semantics.
/// Explicit paths match either a skill's canonical identity or its logical discovery
/// path, and plain names are only used when the match is unambiguous.
///
/// Complexity: `O(T + (N_s + N_t) * S)` time, `O(S + M)` space, where:
/// `S` = number of skills, `T` = total text length, `N_s` = number of structured skill inputs,
/// `N_t` = number of text inputs, `M` = max mentions parsed from a single text input.
pub fn collect_explicit_skill_mentions(
inputs: &[UserInput],
loaded_skills: &impl ExplicitSkillLookup,
connector_slug_counts: &HashMap<String, usize>,
) -> Vec<SkillMetadata> {
let skill_name_counts =
build_skill_name_counts(loaded_skills.skills(), loaded_skills.disabled_paths()).0;
let selection_context = SkillSelectionContext {
loaded_skills,
skill_name_counts: &skill_name_counts,
connector_slug_counts,
};
let mut selected: Vec<SkillMetadata> = Vec::new();
let mut seen_names: HashSet<String> = HashSet::new();
let mut seen_paths: HashSet<PathUri> = HashSet::new();
let mut blocked_plain_names: HashSet<String> = HashSet::new();
for input in inputs {
if let UserInput::Skill { name, path, .. } = input {
blocked_plain_names.insert(name.clone());
let Ok(path) = AbsolutePathBuf::relative_to_current_dir(path) else {
continue;
};
let path = PathUri::from_abs_path(&path);
let Some(skill) = selection_context
.loaded_skills
.skills()
.iter()
.find(|skill| {
skill.path_to_skills_md == path
|| selection_context
.loaded_skills
.skill_discovery_path_for_path(&skill.path_to_skills_md)
.is_some_and(|discovery_path| discovery_path == &path)
})
else {
continue;
};
if !selection_context.loaded_skills.is_skill_enabled(skill)
|| seen_paths.contains(&skill.path_to_skills_md)
{
continue;
}
seen_paths.insert(skill.path_to_skills_md.clone());
seen_names.insert(skill.name.clone());
selected.push(skill.clone());
}
}
for input in inputs {
if let UserInput::Text { text, .. } = input {
let mentioned_names = extract_tool_mentions(text);
select_skills_from_mentions(
&selection_context,
&blocked_plain_names,
&mentioned_names,
&mut seen_names,
&mut seen_paths,
&mut selected,
);
}
}
selected
}
struct SkillSelectionContext<'a> {
loaded_skills: &'a dyn ExplicitSkillLookup,
skill_name_counts: &'a HashMap<String, usize>,
connector_slug_counts: &'a HashMap<String, usize>,
}
/// Select mentioned skills while preserving the order of `skills`.
fn select_skills_from_mentions(
selection_context: &SkillSelectionContext<'_>,
blocked_plain_names: &HashSet<String>,
mentions: &ToolMentions<'_>,
seen_names: &mut HashSet<String>,
seen_paths: &mut HashSet<PathUri>,
selected: &mut Vec<SkillMetadata>,
) {
if mentions.is_empty() {
return;
}
let mention_skill_paths: HashSet<PathUri> = mentions
.paths()
.filter(|path| {
!matches!(
tool_kind_for_path(path),
ToolMentionKind::App | ToolMentionKind::Mcp | ToolMentionKind::Plugin
)
})
.filter_map(|path| {
let path = normalize_skill_path(path);
PathUri::from_host_native_path(path)
.ok()
.or_else(|| LegacyAppPathString::from_string(path).to_inferred_path_uri())
})
.collect();
for skill in selection_context.loaded_skills.skills() {
if !selection_context.loaded_skills.is_skill_enabled(skill)
|| seen_paths.contains(&skill.path_to_skills_md)
{
continue;
}
let matches_discovery_path = selection_context
.loaded_skills
.skill_discovery_path_for_path(&skill.path_to_skills_md)
.is_some_and(|discovery_path| mention_skill_paths.contains(discovery_path));
if mention_skill_paths.contains(&skill.path_to_skills_md) || matches_discovery_path {
seen_paths.insert(skill.path_to_skills_md.clone());
seen_names.insert(skill.name.clone());
selected.push(skill.clone());
}
}
for skill in selection_context.loaded_skills.skills() {
if !selection_context.loaded_skills.is_skill_enabled(skill)
|| seen_paths.contains(&skill.path_to_skills_md)
{
continue;
}
if blocked_plain_names.contains(skill.name.as_str()) {
continue;
}
if !mentions.contains_plain_name(skill.name.as_str()) {
continue;
}
let skill_count = selection_context
.skill_name_counts
.get(skill.name.as_str())
.copied()
.unwrap_or(0);
let connector_count = selection_context
.connector_slug_counts
.get(&skill.name.to_ascii_lowercase())
.copied()
.unwrap_or(0);
if skill_count != 1 || connector_count != 0 {
continue;
}
if seen_names.insert(skill.name.clone()) {
seen_paths.insert(skill.path_to_skills_md.clone());
selected.push(skill.clone());
}
}
}
#[cfg(test)]
#[path = "selection_tests.rs"]
mod tests;

View File

@@ -0,0 +1,431 @@
use super::*;
use akode_utils_absolute_path::test_support::PathBufExt;
use akode_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::collections::HashSet;
#[derive(Default)]
struct TestLookup {
skills: Vec<SkillMetadata>,
disabled_paths: HashSet<PathUri>,
skill_discovery_path_by_path: HashMap<PathUri, PathUri>,
}
impl ExplicitSkillLookup for TestLookup {
fn skills(&self) -> &[SkillMetadata] {
&self.skills
}
fn disabled_paths(&self) -> &HashSet<PathUri> {
&self.disabled_paths
}
fn skill_discovery_path_for_path(&self, path: &PathUri) -> Option<&PathUri> {
self.skill_discovery_path_by_path.get(path)
}
}
fn make_skill(name: &str, path: &str) -> SkillMetadata {
SkillMetadata {
name: name.to_string(),
description: format!("{name} skill"),
short_description: None,
interface: None,
dependencies: None,
policy: None,
path_to_skills_md: test_path_buf(path).abs().into(),
scope: akode_protocol::protocol::SkillScope::User,
plugin_id: None,
}
}
fn linked_skill_mention(name: &str, unix_path: &str) -> String {
format!("[${name}]({})", test_path_buf(unix_path).display())
}
fn collect_mentions(
inputs: &[UserInput],
skills: &[SkillMetadata],
disabled_paths: &HashSet<PathUri>,
connector_slug_counts: &HashMap<String, usize>,
) -> Vec<SkillMetadata> {
let loaded_skills = TestLookup {
skills: skills.to_vec(),
disabled_paths: disabled_paths.clone(),
..Default::default()
};
collect_explicit_skill_mentions(inputs, &loaded_skills, connector_slug_counts)
}
fn skill_outcome_with_discovery_path(skill: SkillMetadata, discovery_path: &str) -> TestLookup {
TestLookup {
skill_discovery_path_by_path: HashMap::from([(
skill.path_to_skills_md.clone(),
test_path_buf(discovery_path).abs().into(),
)]),
skills: vec![skill],
..Default::default()
}
}
#[test]
fn collect_explicit_skill_mentions_text_respects_skill_order() {
let alpha = make_skill("alpha-skill", "/tmp/alpha");
let beta = make_skill("beta-skill", "/tmp/beta");
let skills = vec![beta.clone(), alpha.clone()];
let inputs = vec![UserInput::Text {
text: "first $alpha-skill then $beta-skill".to_string(),
text_elements: Vec::new(),
}];
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
// Text scanning should not change the previous selection ordering semantics.
assert_eq!(selected, vec![beta, alpha]);
}
#[test]
fn collect_explicit_skill_mentions_prioritizes_structured_inputs() {
let alpha = make_skill("alpha-skill", "/tmp/alpha");
let beta = make_skill("beta-skill", "/tmp/beta");
let skills = vec![alpha.clone(), beta.clone()];
let inputs = vec![
UserInput::Text {
text: "please run $alpha-skill".to_string(),
text_elements: Vec::new(),
},
UserInput::Skill {
name: "beta-skill".to_string(),
path: test_path_buf("/tmp/beta"),
},
];
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
assert_eq!(selected, vec![beta, alpha]);
}
#[test]
fn collect_explicit_skill_mentions_accepts_structured_discovery_path() {
let skill = make_skill("linked-skill", "/tmp/shared/linked-skill/SKILL.md");
let loaded_skills = skill_outcome_with_discovery_path(
skill.clone(),
"/tmp/project/.agents/skills/linked-skill/SKILL.md",
);
let inputs = vec![UserInput::Skill {
name: "linked-skill".to_string(),
path: test_path_buf("/tmp/project/.agents/skills/linked-skill/SKILL.md"),
}];
let selected = collect_explicit_skill_mentions(&inputs, &loaded_skills, &HashMap::new());
assert_eq!(selected, vec![skill]);
}
#[test]
fn collect_explicit_skill_mentions_accepts_linked_discovery_path() {
let skill = make_skill("linked-skill", "/tmp/shared/linked-skill/SKILL.md");
let loaded_skills = skill_outcome_with_discovery_path(
skill.clone(),
"/tmp/project/.agents/skills/linked-skill/SKILL.md",
);
let inputs = vec![UserInput::Text {
text: linked_skill_mention(
"linked-skill",
"/tmp/project/.agents/skills/linked-skill/SKILL.md",
),
text_elements: Vec::new(),
}];
let selected = collect_explicit_skill_mentions(&inputs, &loaded_skills, &HashMap::new());
assert_eq!(selected, vec![skill]);
}
#[test]
fn collect_explicit_skill_mentions_rejects_disabled_discovery_path() {
let skill = make_skill("linked-skill", "/tmp/shared/linked-skill/SKILL.md");
let mut loaded_skills = skill_outcome_with_discovery_path(
skill.clone(),
"/tmp/project/.agents/skills/linked-skill/SKILL.md",
);
loaded_skills.disabled_paths.insert(skill.path_to_skills_md);
let inputs = vec![UserInput::Skill {
name: "linked-skill".to_string(),
path: test_path_buf("/tmp/project/.agents/skills/linked-skill/SKILL.md"),
}];
let selected = collect_explicit_skill_mentions(&inputs, &loaded_skills, &HashMap::new());
assert_eq!(selected, Vec::new());
}
#[test]
fn collect_explicit_skill_mentions_skips_invalid_structured_and_blocks_plain_fallback() {
let alpha = make_skill("alpha-skill", "/tmp/alpha");
let skills = vec![alpha];
let inputs = vec![
UserInput::Text {
text: "please run $alpha-skill".to_string(),
text_elements: Vec::new(),
},
UserInput::Skill {
name: "alpha-skill".to_string(),
path: test_path_buf("/tmp/missing"),
},
];
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
assert_eq!(selected, Vec::new());
}
#[test]
fn collect_explicit_skill_mentions_skips_disabled_structured_and_blocks_plain_fallback() {
let alpha = make_skill("alpha-skill", "/tmp/alpha");
let skills = vec![alpha];
let inputs = vec![
UserInput::Text {
text: "please run $alpha-skill".to_string(),
text_elements: Vec::new(),
},
UserInput::Skill {
name: "alpha-skill".to_string(),
path: test_path_buf("/tmp/alpha"),
},
];
let disabled = HashSet::from([test_path_buf("/tmp/alpha").abs().into()]);
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &disabled, &connector_counts);
assert_eq!(selected, Vec::new());
}
#[test]
fn collect_explicit_skill_mentions_dedupes_by_path() {
let alpha = make_skill("alpha-skill", "/tmp/alpha");
let skills = vec![alpha.clone()];
let mention = linked_skill_mention("alpha-skill", "/tmp/alpha");
let inputs = vec![UserInput::Text {
text: format!("use {mention} and {mention}"),
text_elements: Vec::new(),
}];
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
assert_eq!(selected, vec![alpha]);
}
#[test]
fn collect_explicit_skill_mentions_skips_ambiguous_name() {
let alpha = make_skill("demo-skill", "/tmp/alpha");
let beta = make_skill("demo-skill", "/tmp/beta");
let skills = vec![alpha, beta];
let inputs = vec![UserInput::Text {
text: "use $demo-skill and again $demo-skill".to_string(),
text_elements: Vec::new(),
}];
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
assert_eq!(selected, Vec::new());
}
#[test]
fn collect_explicit_skill_mentions_prefers_linked_path_over_name() {
let alpha = make_skill("demo-skill", "/tmp/alpha");
let beta = make_skill("demo-skill", "/tmp/beta");
let skills = vec![alpha, beta.clone()];
let inputs = vec![UserInput::Text {
text: format!(
"use $demo-skill and {}",
linked_skill_mention("demo-skill", "/tmp/beta")
),
text_elements: Vec::new(),
}];
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
assert_eq!(selected, vec![beta]);
}
#[test]
fn collect_explicit_skill_mentions_skips_plain_name_when_connector_matches() {
let alpha = make_skill("alpha-skill", "/tmp/alpha");
let skills = vec![alpha];
let inputs = vec![UserInput::Text {
text: "use $alpha-skill".to_string(),
text_elements: Vec::new(),
}];
let connector_counts = HashMap::from([("alpha-skill".to_string(), 1)]);
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
assert_eq!(selected, Vec::new());
}
#[test]
fn collect_explicit_skill_mentions_allows_explicit_path_with_connector_conflict() {
let alpha = make_skill("alpha-skill", "/tmp/alpha");
let skills = vec![alpha.clone()];
let inputs = vec![UserInput::Text {
text: format!("use {}", linked_skill_mention("alpha-skill", "/tmp/alpha")),
text_elements: Vec::new(),
}];
let connector_counts = HashMap::from([("alpha-skill".to_string(), 1)]);
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
assert_eq!(selected, vec![alpha]);
}
#[test]
fn collect_explicit_skill_mentions_skips_when_linked_path_disabled() {
let alpha = make_skill("demo-skill", "/tmp/alpha");
let beta = make_skill("demo-skill", "/tmp/beta");
let skills = vec![alpha, beta];
let inputs = vec![UserInput::Text {
text: format!("use {}", linked_skill_mention("demo-skill", "/tmp/alpha")),
text_elements: Vec::new(),
}];
let disabled = HashSet::from([test_path_buf("/tmp/alpha").abs().into()]);
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &disabled, &connector_counts);
assert_eq!(selected, Vec::new());
}
#[test]
fn collect_explicit_skill_mentions_prefers_resource_path() {
let alpha = make_skill("demo-skill", "/tmp/alpha");
let beta = make_skill("demo-skill", "/tmp/beta");
let skills = vec![alpha, beta.clone()];
let inputs = vec![UserInput::Text {
text: format!("use {}", linked_skill_mention("demo-skill", "/tmp/beta")),
text_elements: Vec::new(),
}];
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
assert_eq!(selected, vec![beta]);
}
#[test]
fn collect_explicit_skill_mentions_skips_missing_path_with_no_fallback() {
let alpha = make_skill("demo-skill", "/tmp/alpha");
let beta = make_skill("demo-skill", "/tmp/beta");
let skills = vec![alpha, beta];
let inputs = vec![UserInput::Text {
text: format!("use {}", linked_skill_mention("demo-skill", "/tmp/missing")),
text_elements: Vec::new(),
}];
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
assert_eq!(selected, Vec::new());
}
#[test]
fn collect_explicit_skill_mentions_skips_missing_path_without_fallback() {
let alpha = make_skill("demo-skill", "/tmp/alpha");
let skills = vec![alpha];
let inputs = vec![UserInput::Text {
text: format!("use {}", linked_skill_mention("demo-skill", "/tmp/missing")),
text_elements: Vec::new(),
}];
let connector_counts = HashMap::new();
let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts);
assert_eq!(selected, Vec::new());
}
/// Linked native paths use URI identity across Windows case and separator spellings.
#[test]
fn collect_explicit_skill_mentions_matches_windows_path_identity() {
let skill = SkillMetadata {
path_to_skills_md: PathUri::parse("file:///C:/Skills/Demo/SKILL.md").unwrap(),
..make_skill("demo-skill", "/tmp/demo/SKILL.md")
};
let loaded_skills = TestLookup {
skill_discovery_path_by_path: HashMap::from([(
skill.path_to_skills_md.clone(),
PathUri::parse("file:///C:/Project/.agents/skills/Demo/SKILL.md").unwrap(),
)]),
skills: vec![skill.clone()],
..Default::default()
};
for path in [
r"c:\skills\demo\skill.md",
"C:/SKILLS/DEMO/skill.md",
"skill://c:/project/.agents/skills/demo/skill.md",
] {
let inputs = vec![UserInput::Text {
text: format!("use [$demo-skill]({path})"),
text_elements: Vec::new(),
}];
let selected = collect_explicit_skill_mentions(&inputs, &loaded_skills, &HashMap::new());
assert_eq!(selected, vec![skill.clone()]);
}
}
/// A differently cased disabled Windows identity still blocks a linked skill selection.
#[test]
fn collect_explicit_skill_mentions_rejects_disabled_windows_path_identity() {
let skill = SkillMetadata {
path_to_skills_md: PathUri::parse("file:///C:/Skills/Demo/SKILL.md").unwrap(),
..make_skill("demo-skill", "/tmp/demo/SKILL.md")
};
let loaded_skills = TestLookup {
skills: vec![skill],
disabled_paths: HashSet::from([PathUri::parse("file:///C:/skills/demo/skill.md").unwrap()]),
..Default::default()
};
let inputs = vec![UserInput::Text {
text: r"use [$demo-skill](C:\Skills\Demo\SKILL.md)".to_string(),
text_elements: Vec::new(),
}];
let selected = collect_explicit_skill_mentions(&inputs, &loaded_skills, &HashMap::new());
assert_eq!(selected, Vec::new());
}
/// Native mention text retains literal spaces, percent escapes, and fragments in skill paths.
#[test]
fn collect_explicit_skill_mentions_preserves_native_uri_characters() {
let percent = make_skill("demo-skill", "/tmp/demo skill%23/SKILL.md");
let fragment = make_skill("demo-skill", "/tmp/demo skill#/SKILL.md");
let loaded_skills = TestLookup {
skills: vec![percent.clone(), fragment.clone()],
..Default::default()
};
for (path, skill) in [
("/tmp/demo skill%23/SKILL.md", percent),
("/tmp/demo skill#/SKILL.md", fragment),
] {
let inputs = vec![UserInput::Text {
text: linked_skill_mention("demo-skill", path),
text_elements: Vec::new(),
}];
let selected = collect_explicit_skill_mentions(&inputs, &loaded_skills, &HashMap::new());
assert_eq!(selected, vec![skill]);
}
}