chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,76 @@
|
||||
---
|
||||
name: academy-rag-search
|
||||
description: Use when retrieving from or asking questions against a Academy knowledge base via the `academy` CLI — and especially when unsure whether to use `chat`, `session ask`, or `search chunks` for a given goal.
|
||||
metadata:
|
||||
tested_against: v0.10
|
||||
---
|
||||
|
||||
# Academy — retrieval & RAG queries
|
||||
|
||||
**REQUIRED BACKGROUND:** read the `academy-shared` skill first (auth, `--kb`
|
||||
resolution, the JSON envelope, exit codes, streaming/NDJSON output).
|
||||
|
||||
Academy gives you several ways to "ask about a knowledge base." Picking the wrong
|
||||
one wastes turns or returns the wrong shape. Use the decision table.
|
||||
|
||||
## Pick the command by your goal
|
||||
|
||||
| Your goal | Command | LLM synthesis? | Returns |
|
||||
|---|---|---|---|
|
||||
| Natural-language **answer** grounded in a KB | `chat "<q>" --kb <kb>` | yes | bounded answer events; `--reference` adds citations; `--verbose` adds execution detail |
|
||||
| Answer via a **custom agent** (its own KB scope, tools, web search) | `session ask --agent <id> "<q>"` | yes (+ tools) | bounded answer events; `--reference` adds citations; `--verbose` adds execution detail |
|
||||
| **Raw context chunks** to reason over yourself (no answer) | `search chunks "<q>" --kb <kb>` | no | ranked chunk list |
|
||||
| Which **documents** match a keyword (title/filename) | `search docs "<q>" --kb <kb>` | no | document list |
|
||||
| Find a **knowledge base** by name | `search kb "<q>"` | no | KB list |
|
||||
| Find a past **session** by title | `search sessions "<q>"` | no | session list |
|
||||
|
||||
### The three decisions that matter
|
||||
|
||||
1. **Answer vs raw context.** Want a written answer → `chat` / `session ask`.
|
||||
Want chunks to feed into your *own* reasoning (e.g. you'll synthesize across
|
||||
sources) → `search chunks`. Don't call `chat` just to read source text.
|
||||
2. **`chat` vs `session ask`.** `chat` = plain KB RAG Q&A. `session ask --agent
|
||||
<id>` = invoke a *configured custom agent* (it may scope its own KBs, call
|
||||
tools, do web search). If the user set up an agent for this, prefer it
|
||||
(`academy agent list` to find ids); otherwise `chat`.
|
||||
3. **One-shot vs multi-turn.** Both `chat` and `session ask` return a
|
||||
`data.session_id` in default JSON output. Pass `--session <id>` on the next
|
||||
call to continue the conversation. In NDJSON mode, read it from `init`.
|
||||
|
||||
## Safety / Gotchas
|
||||
|
||||
- `chat`, `search chunks`, `search docs` need a KB: pass `--kb <id-or-name>`, or
|
||||
set `ACADEMY_KB_ID`, or `academy link` the directory (resolved in that order).
|
||||
If none resolves it's exit 1 (`local.kb_id_required`); a bad name is exit 1
|
||||
(`local.kb_not_found`). Resolve names with `academy kb list` / `search kb`.
|
||||
(`search kb` / `search sessions` are tenant-wide and take no `--kb`.)
|
||||
- `chat` / `session ask` return one buffered JSON envelope with answer
|
||||
events by default. Add `--reference` for indexed citations and `--verbose`
|
||||
for execution detail; use `--format ndjson` for raw events or `--format
|
||||
text` for the live human-readable projection.
|
||||
- A stalled stream is not stopped by Ctrl-C (that just drops your local
|
||||
connection; the server keeps generating + billing). Stop it server-side:
|
||||
`academy session stop <session-id> --message <message-id>` (session_id from
|
||||
`data.session_id`, or from `init` under `--format ndjson`).
|
||||
Re-attach to a stream with `academy session resume <session-id>
|
||||
--message <message-id>`.
|
||||
- `search chunks --limit` defaults to **8** (tuned for an LLM context window);
|
||||
the `search docs/kb/sessions` lists default to 30. Tune retrieval with
|
||||
`--vector-threshold` / `--keyword-threshold`, or `--no-vector`/`--no-keyword`
|
||||
to disable a channel. Details: `references/search-chunks.md`.
|
||||
|
||||
## Quick examples
|
||||
|
||||
```bash
|
||||
# raw retrieval to reason over
|
||||
academy search chunks "retry backoff policy" --kb engineering --limit 12
|
||||
|
||||
# grounded answer (human transcript)
|
||||
academy chat "How do we handle retries?" --kb engineering --format text
|
||||
|
||||
# continue the conversation (session id from data.session_id above)
|
||||
academy chat "And the max attempts?" --kb engineering --session sess_abc
|
||||
|
||||
# answer via a custom agent
|
||||
academy session ask --agent ag_123 "Summarize this quarter's incidents"
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
# `chat` and `session ask` — RAG answers and raw streams
|
||||
|
||||
Both return one buffered JSON envelope with answer events by default.
|
||||
`--reference` adds lookup-index references; `--verbose` adds execution events.
|
||||
They share the raw SSE vocabulary under `--format ndjson`; `chat` does plain KB
|
||||
RAG, `session ask` invokes a custom agent.
|
||||
|
||||
## Commands & flags
|
||||
|
||||
```
|
||||
academy chat "<query>" --kb <name-or-id> [--session <id>]
|
||||
academy session ask "<query>" --agent <agent-id> [--session <id>]
|
||||
```
|
||||
|
||||
- `--kb` (chat) is required name-or-id. `--agent` (session ask) is required.
|
||||
- `--session <id>` continues an existing conversation; omit to start a new one.
|
||||
- `--format json` returns one `{ok,data:{events:[...]}}` envelope; `--format
|
||||
text` streams the same projection as readable text; `--format ndjson` emits
|
||||
the raw event stream.
|
||||
- `--reference` adds bounded reference indexes to JSON/text.
|
||||
- `--verbose` adds thinking, reflection, tool, metadata, and lifecycle events.
|
||||
- Combine them when both provenance and execution detail are needed.
|
||||
|
||||
## Event stream (`--format ndjson`)
|
||||
|
||||
Under `--format ndjson`, the CLI emits an `init` line first, then passes SDK
|
||||
events through verbatim:
|
||||
|
||||
```jsonc
|
||||
{"type":"init","session_id":"sess_abc","kb_id":"…","profile":"prod"} // session ask: agent_id instead of kb_id
|
||||
{"response_type":"thinking","content":"…"}
|
||||
{"response_type":"tool_call","tool_calls":[…]} // agent only
|
||||
{"response_type":"tool_result","content":"…"} // agent only
|
||||
{"response_type":"references","knowledge_references":[…]}
|
||||
{"response_type":"answer","content":"partial text…"} // streamed in pieces
|
||||
{"response_type":"complete","done":true}
|
||||
```
|
||||
|
||||
- Accumulate `response_type:"answer"` `content` pieces for the final answer.
|
||||
- `knowledge_references` carry the grounding chunks (source attribution).
|
||||
- **Keep `init.session_id`** to continue the chat (`--session`). The
|
||||
`assistant_message_id` needed for `session stop` / `session resume`
|
||||
rides on the SDK's `agent_query` frame, not on `init` — scan for it.
|
||||
- On failure mid-stream you get `response_type:"error"`; a transport/HTTP error
|
||||
surfaces as the normal error envelope on stderr with a typed code.
|
||||
|
||||
## Recovery
|
||||
|
||||
- **Stop server-side generation:** `academy session stop <session-id> --message
|
||||
<message-id>`. Ctrl-C only closes your local connection — the server keeps
|
||||
generating (and billing) until told to stop.
|
||||
- **Re-attach after a dropped connection:** `academy session resume
|
||||
<session-id> --message <message-id>`. The server replays the event log from
|
||||
index 0 then tails new events, so **dedupe by message_id** if you already
|
||||
consumed some events. Buffer TTL is ~1h (redis) or process-lifetime (memory).
|
||||
@@ -0,0 +1,46 @@
|
||||
# `search chunks` — hybrid retrieval (no LLM)
|
||||
|
||||
Raw vector + keyword retrieval against one knowledge base. Returns ranked chunks
|
||||
for you to reason over; it does NOT synthesize an answer (use `chat` for that).
|
||||
|
||||
## Command & flags
|
||||
|
||||
```
|
||||
academy search chunks "<query>" --kb <name-or-id> [flags]
|
||||
```
|
||||
|
||||
| Flag | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `--kb` | (required) | KB name or UUID |
|
||||
| `--limit`, `-L` | 8 | max chunks returned (1..1000); 8 is tuned for an LLM context window |
|
||||
| `--vector-threshold` | 0 (off) | min vector similarity, per-channel pre-fusion |
|
||||
| `--keyword-threshold` | 0 (off) | min keyword score, per-channel pre-fusion |
|
||||
| `--no-vector` | false | disable the vector channel (keyword-only) |
|
||||
| `--no-keyword` | false | disable the keyword channel (vector-only) |
|
||||
|
||||
You cannot disable both channels. `--limit` is a hard cap on returned chunks
|
||||
applied client-side (the server may internally retrieve a larger pool for recall,
|
||||
then the CLI trims).
|
||||
|
||||
## Output (`--format json`)
|
||||
|
||||
`data` is an array of chunk objects; `meta.count` is the number returned.
|
||||
|
||||
```jsonc
|
||||
{"ok":true,"meta":{"count":3},"data":[
|
||||
{"id":"chunk_…","content":"…","knowledge_id":"doc_…","knowledge_title":"…",
|
||||
"chunk_index":4,"score":0.82,"match_type":"hybrid","chunk_type":"text"}
|
||||
]}
|
||||
```
|
||||
|
||||
- `score` is the fused rank; `match_type` indicates which channel(s) hit.
|
||||
- `knowledge_id` / `knowledge_title` attribute the chunk to its source document.
|
||||
- Project just what you need with `--jq`, e.g.
|
||||
`academy search chunks "q" --kb eng --jq '.data[] | {score,content}'`.
|
||||
|
||||
## When to use vs alternatives
|
||||
|
||||
- Need an **answer** → `chat` (it does retrieval + synthesis internally).
|
||||
- Building your **own** prompt/context from sources → `search chunks` (this).
|
||||
- Finding **which documents** exist by keyword → `search docs --kb <kb>`.
|
||||
- Inspecting/debugging a specific document's chunks → `chunk list --doc <id>`.
|
||||
@@ -0,0 +1,211 @@
|
||||
---
|
||||
name: academy-shared
|
||||
description: Use when driving a Academy RAG server through the `academy` CLI as an agent — authenticating, managing knowledge bases / documents / sessions / agents, running search or chat, or interpreting the CLI's JSON envelopes and exit codes. Read this before any other academy-* skill.
|
||||
metadata:
|
||||
tested_against: v0.10
|
||||
---
|
||||
|
||||
# Academy CLI — shared base
|
||||
|
||||
`academy` is the agent-first CLI for a Academy RAG server. Every command prints
|
||||
a JSON envelope and uses a typed exit code, so you branch on machine-readable
|
||||
output, not prose. Read this skill before any task-specific `academy-*` skill.
|
||||
|
||||
## 1. Authenticate (do this first — order matters)
|
||||
|
||||
**Agents usually skip profiles entirely:** set `ACADEMY_API_KEY` (or
|
||||
`ACADEMY_TOKEN`) + `ACADEMY_HOST` and every command authenticates statelessly and
|
||||
zero-disk — no `profile add` / `auth login` needed. `auth token` echoes that env
|
||||
credential; `auth status` / `doctor` confirm it. The steps below set up a
|
||||
**persistent named profile** instead (interactive / multi-environment use).
|
||||
|
||||
Authentication is a **two-step sequence**. `academy auth login` operates on the
|
||||
*active profile*, so the profile must exist first:
|
||||
|
||||
```bash
|
||||
# 1. register a connection target and make it active
|
||||
academy profile add prod --host https://kb.example.com --use
|
||||
# 2a. API key (agent default — pipe the key on stdin, non-interactive):
|
||||
echo "$ACADEMY_API_KEY" | academy auth login --with-token
|
||||
# 2b. OR email+password (interactive prompt only — no flags; not for agents)
|
||||
academy auth login
|
||||
|
||||
academy auth status # verify: who am I, which tenant
|
||||
```
|
||||
|
||||
- Target a *non-active* profile for one command with the global `--profile NAME`
|
||||
(e.g. `academy --profile staging auth refresh`). There is no per-command
|
||||
`--name`/`--host` on auth commands.
|
||||
- Get the raw token for scripting with `ACADEMY_TOKEN=$(academy auth token)`
|
||||
(raw token by default; works with an env credential too; `--format json` gives
|
||||
the `{token, mode, profile}` envelope).
|
||||
- `academy auth logout` clears a profile's stored credentials but **keeps the
|
||||
profile registered** (re-auth later with `auth login`); use `profile remove`
|
||||
to delete the profile entirely.
|
||||
- `academy doctor` runs 4 health checks (reachability, credential, version, storage).
|
||||
|
||||
## 2. Selecting a knowledge base (`--kb`)
|
||||
|
||||
`--kb` accepts a **name or a UUID** (resolved server-side). Resolution order:
|
||||
`--kb` flag → `ACADEMY_KB_ID` env → directory link (`academy link --kb X` binds
|
||||
the cwd) → error. Read/create commands that operate "inside a project" inherit
|
||||
the link; **`search *` and destructive `--all` operations always require an
|
||||
explicit `--kb`** (so an agent never silently hits the wrong corpus).
|
||||
|
||||
**A KB must have an embedding model bound to be searchable.** A freshly created
|
||||
KB is `retrieval_ready:false` — uploaded docs stay unindexed and `search`/`chat`
|
||||
return nothing until you bind models. Create it ready in one step
|
||||
(`kb create --embedding-model <m> --chat-model <m>`, discover ids with
|
||||
`academy model list`) or bind after the fact
|
||||
(`kb config set <kb> --embedding-model <m> --chat-model <m>`). `kb status` /
|
||||
`kb check` report `retrieval_ready`, and `kb create` hints the fix when it is
|
||||
false — so an unconfigured KB is never silently "healthy".
|
||||
|
||||
## 3. Output contract — every command
|
||||
|
||||
Default output is `--format json`: a single envelope.
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `ok` | `true`/`false` — branch on this first (see batch/wait caveat below) |
|
||||
| `data` | success payload (object or array; absent on mutation-only success) |
|
||||
| `meta` | `count` / `has_more` / `dry_run` / `plan` … |
|
||||
| `error` | on failure: `{type, message, hint?, retry_argv?, retryable?, risk?}` |
|
||||
| `profile` | active profile name |
|
||||
|
||||
- `error.type` is a **stable typed code** (e.g. `local.kb_not_found`,
|
||||
`input.invalid_argument`, `input.confirmation_required`, `server.error`).
|
||||
Branch on it; `error.hint` usually tells you the next action.
|
||||
- `--format text` = a live human-readable projection. `chat` and `session ask`
|
||||
buffer a bounded answer-event projection into one JSON envelope by default;
|
||||
pass `--reference` for indexed citations, `--verbose` for execution detail,
|
||||
or `--format ndjson` for raw event lines. `session resume` remains
|
||||
an NDJSON streaming command.
|
||||
- `--jq '<expr>'` filters the envelope (e.g. `academy kb list --jq '.data[].id'`).
|
||||
- Exception: `academy auth token` emits the **raw token** by default (it's a
|
||||
scripting helper); pass `--format json` for the `{token, mode, profile}` envelope.
|
||||
- **Batch / wait caveat:** multi-item commands come in two shapes, but for
|
||||
**both you branch on the exit code, not `ok`**:
|
||||
- `doc/chunk/session delete` with several ids → a **batch** envelope:
|
||||
`status` is `success`/`partial`/`error`, `ok` is `true` *only* when every
|
||||
item succeeded (**`ok:false` on any failure**), `data` is a per-item array
|
||||
`[{id, ok, result|error}]`, and `meta.successes`/`failures` count the split.
|
||||
Exit 1 if any item failed.
|
||||
- `doc wait` → a normal `ok:true` envelope whose `data` partitions the ids
|
||||
into `{completed, failed, timeout}`; `ok` stays `true` even with failures
|
||||
(to avoid a contradictory envelope). Exit 1 if any doc failed, 124 on timeout.
|
||||
Either way, read the **exit code** first, then `data` for which items failed.
|
||||
|
||||
## 4. Exit codes (branch on these)
|
||||
|
||||
| Code | Meaning (typed code class) | Agent action |
|
||||
|---|---|---|
|
||||
| 0 | success (incl. `--dry-run`) | proceed |
|
||||
| 1 | `local.*` / unclassified (incl. `local.kb_not_found`) | read `error`, decide retry/abort |
|
||||
| 2 | flag / argument validation (bad/unknown/missing-required flag) | re-check `academy <cmd> --help` |
|
||||
| 3 | `auth.*` (missing / expired / forbidden) | re-auth, then retry |
|
||||
| 4 | `resource.not_found` (a server resource id) | verify the id |
|
||||
| 5 | `input.*` (other than confirmation_required) | adjust args, retry |
|
||||
| 6 | `server.rate_limited` | back off, retry |
|
||||
| 7 | `server.*` / `network.*` | transient — retry with backoff |
|
||||
| **10** | **`input.confirmation_required` (destructive)** | **see §5 — never auto-bypass** |
|
||||
| 124 | `operation.timeout` | raise `--timeout` or check the job |
|
||||
| 130 | `operation.cancelled` (SIGINT/SIGTERM) | stop, don't retry |
|
||||
|
||||
Note: a server resource id that doesn't exist → exit 4 (`resource.not_found`);
|
||||
a `--kb` *name* that doesn't resolve client-side → exit 1 (`local.kb_not_found`).
|
||||
`input.invalid_argument` spans two exit codes — a malformed *invocation*
|
||||
(unknown/missing flag, wrong arg count) exits **2** (fix the command, re-check
|
||||
`--help`), while a value rejected *after* parsing (e.g. a bad `--jq` expression)
|
||||
exits **5** (adjust the value, retry). Branch on the exit code to tell them apart.
|
||||
|
||||
## 5. Destructive writes (exit 10) — hard rule
|
||||
|
||||
Destructive commands (`kb/doc/chunk/session/agent delete`, `kb/agent update`,
|
||||
`auth logout`, `doc delete --all`, …) without `-y` exit **10** with
|
||||
`error.type = input.confirmation_required` and `error.risk = {level, action}`:
|
||||
|
||||
```jsonc
|
||||
{"ok":false,"error":{"type":"input.confirmation_required",
|
||||
"message":"delete knowledge base X requires explicit confirmation: re-run with -y",
|
||||
"retry_argv":["academy","kb","delete","X","-y"],"risk":{"level":"destructive","action":"kb.delete"}}}
|
||||
```
|
||||
|
||||
**Surface this to the user and get explicit approval. Re-run with `-y` ONLY
|
||||
after they approve. Never add `-y` on your own initiative.**
|
||||
|
||||
## 6. Preview before acting — `--dry-run`
|
||||
|
||||
Any mutation accepts `--dry-run`: it resolves the request, prints
|
||||
`meta.plan = {action, args}`, makes **zero** server/side-effect changes, exits 0.
|
||||
Use it to confirm a command is well-formed (and what it would do) before running
|
||||
it for real — especially before destructive or bulk operations.
|
||||
|
||||
## 7. Chaining (mutation → id)
|
||||
|
||||
Mutations return the new resource id in `data.id`. Chain with it:
|
||||
|
||||
```bash
|
||||
KB=$(academy kb create "Docs" --jq '.data.id' --format json | tr -d '"')
|
||||
academy doc upload ./manual.pdf --kb "$KB"
|
||||
```
|
||||
|
||||
## 7a. Reliability patterns for long-running agent runs
|
||||
|
||||
### Inspecting prior messages
|
||||
Use `academy message list --session <sess-id>` to review the message history of a session (e.g., after a stream drops) before deciding whether to re-ask or continue. Use `academy message search "<query>"` to locate a prior Q&A exchange across all sessions — prefer this over re-running an expensive query when the answer may already exist.
|
||||
|
||||
### Tool-approval unlock
|
||||
An agent run pauses mid-stream on a tool-approval event when the server requires human sign-off before executing a tool call. The pattern:
|
||||
|
||||
1. The stream emits a tool-approval event; capture the `pending_id`.
|
||||
2. **Surface the pending tool call to the user** (show tool name + proposed args). Do not auto-approve.
|
||||
3. After explicit user go-ahead: `academy session tool-approval resolve <pending-id> -y` to approve, or add `--reject --reason "..."` to reject.
|
||||
4. Resume the answer: `academy session resume <sess-id> --message <msg-id>`.
|
||||
|
||||
`--modified-args '{"key":"val"}'` replaces the tool arguments on approve (non-empty JSON object required). This is an exit-10 interaction — see §5.
|
||||
|
||||
## 8. Resource model & command map
|
||||
|
||||
```
|
||||
kb knowledge bases list/view/create/update/delete/pin/unpin/status/check
|
||||
doc documents in a KB list/view/create/upload/fetch/download/reparse/update/delete/wait
|
||||
chunk retrieval units list/view/delete (RAG debug; not search)
|
||||
session conversations list/view/delete/ask/stop/resume/tool-approval resolve
|
||||
message session messages list/search/delete
|
||||
agent custom agents list/view/create/update/delete/status/check
|
||||
model configured models list/view/create/update/delete (update rotates key / base-url in place, id preserved)
|
||||
search retrieval chunks / docs / kb / sessions
|
||||
chat one-shot KB RAG Q&A (streaming)
|
||||
api raw HTTP passthrough to any server endpoint (escape hatch)
|
||||
link/unlink bind cwd to a KB mcp serve expose academy as MCP tools
|
||||
```
|
||||
|
||||
**chat vs session ask vs search** — the most common confusion: see the
|
||||
`academy-rag-search` skill for the decision table. Briefly: `chat` = one-shot
|
||||
KB Q&A with an LLM; `session ask --agent <id>` = invoke a *custom agent*;
|
||||
`search chunks` = raw hybrid retrieval (no LLM).
|
||||
|
||||
## 9. CLI vs MCP
|
||||
|
||||
For your own scripted control, use the CLI (richer: dry-run, exit-10, all verbs).
|
||||
For an IDE/host agent that speaks MCP, `academy mcp serve` exposes a curated
|
||||
read+chat tool set: `kb_list`, `kb_view`, `doc_list`, `doc_view`, `doc_download`,
|
||||
`search_chunks`, `chunk_list`, `agent_list`, `chat`, `session_ask`. MCP tools
|
||||
take raw ids (no name resolution); resolve names via `kb_list` first.
|
||||
|
||||
## 10. Agent self-help
|
||||
|
||||
Run `academy <command> --help`. With `ACADEMY_AGENT_HELP=1` set, `--help` emits a
|
||||
JSON blob (`used_for` / `required_flags` / `examples`) instead of prose — parse
|
||||
that to learn a command without scraping the human help table.
|
||||
|
||||
## Common mistakes
|
||||
|
||||
| Mistake | Fix |
|
||||
|---|---|
|
||||
| `academy auth login` before any profile exists | `profile add <n> --host <url> --use` first (§1) |
|
||||
| Passing `--host` or `--name` to `auth login` | `auth login` takes neither — host comes from the profile; use `profile add <n> --host <url> --use`, then `auth login` |
|
||||
| Auto-adding `-y` to clear an exit-10 | Never; get user approval first (§5) |
|
||||
| Need the raw `chat` event stream | pass `--format ndjson`; use `--format text` for a live projected transcript |
|
||||
| `search chunks "q"` → exit 1 `local.kb_id_required` | Pass `--kb <name-or-id>`, set `ACADEMY_KB_ID`, or `academy link` the dir |
|
||||
@@ -0,0 +1,115 @@
|
||||
// Package skills embeds the bundled Agent Skills into the CLI binary so
|
||||
// `academy skills install` can write them out without a source checkout
|
||||
// (replacing the manual symlink-from-checkout MVP). The markdown under each
|
||||
// skill dir is the single source of truth — embedding it keeps the shipped
|
||||
// binary and the docs in lockstep (the parity tests guard the command/flag
|
||||
// vocabulary the skills reference).
|
||||
package skills
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed all:academy-shared all:academy-rag-search
|
||||
var fsys embed.FS
|
||||
|
||||
// Skill is one bundled skill: its directory name, the description parsed from
|
||||
// its SKILL.md frontmatter, and the relative file paths it contains.
|
||||
type Skill struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Files []string `json:"files"`
|
||||
}
|
||||
|
||||
// FS exposes the embedded skill tree for callers that want raw access.
|
||||
func FS() fs.FS { return fsys }
|
||||
|
||||
// List returns the bundled skills (top-level dirs that contain a SKILL.md),
|
||||
// sorted by name.
|
||||
func List() ([]Skill, error) {
|
||||
entries, err := fs.ReadDir(fsys, ".")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var skills []Skill
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
files, err := skillFiles(e.Name())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasSkillMD(files) {
|
||||
continue
|
||||
}
|
||||
skills = append(skills, Skill{
|
||||
Name: e.Name(),
|
||||
Description: descriptionOf(e.Name()),
|
||||
Files: files,
|
||||
})
|
||||
}
|
||||
sort.Slice(skills, func(i, j int) bool { return skills[i].Name < skills[j].Name })
|
||||
return skills, nil
|
||||
}
|
||||
|
||||
// skillFiles returns every file path under a skill dir (relative to the FS
|
||||
// root, e.g. "academy-shared/SKILL.md"), sorted.
|
||||
func skillFiles(dir string) ([]string, error) {
|
||||
var files []string
|
||||
err := fs.WalkDir(fsys, dir, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !d.IsDir() {
|
||||
files = append(files, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.Strings(files)
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func hasSkillMD(files []string) bool {
|
||||
for _, f := range files {
|
||||
if path.Base(f) == "SKILL.md" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// descriptionOf reads the `description:` line from a skill's SKILL.md YAML
|
||||
// frontmatter. Best-effort: returns "" if absent or unreadable.
|
||||
func descriptionOf(dir string) string {
|
||||
b, err := fs.ReadFile(fsys, path.Join(dir, "SKILL.md"))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
inFrontmatter := false
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
t := strings.TrimSpace(line)
|
||||
if t == "---" {
|
||||
if inFrontmatter {
|
||||
break // end of frontmatter
|
||||
}
|
||||
inFrontmatter = true
|
||||
continue
|
||||
}
|
||||
if inFrontmatter && strings.HasPrefix(t, "description:") {
|
||||
return strings.TrimSpace(strings.TrimPrefix(t, "description:"))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ReadFile returns the bytes of one embedded file path (as reported in
|
||||
// Skill.Files), for `skills install` to write to disk.
|
||||
func ReadFile(p string) ([]byte, error) { return fsys.ReadFile(p) }
|
||||
Reference in new issue
Block a user