@howaboua/pi-better-skills-tool 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,253 @@
1
+ import { readFileSync, realpathSync, statSync } from "node:fs";
2
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import {
4
+ type CatalogSkill,
5
+ directoryEntries,
6
+ entryKind,
7
+ isWithin,
8
+ } from "./discovery.js";
9
+
10
+ function withoutMarkdownSuffix(name: string): string {
11
+ return name.replace(/\.md$/i, "");
12
+ }
13
+
14
+ function normalizedPath(name: string): string {
15
+ return name.replaceAll("\\", "/");
16
+ }
17
+
18
+ function stripPathPrefix(name: string, prefix: string): string {
19
+ return name.toLowerCase().startsWith(prefix.toLowerCase())
20
+ ? name.slice(prefix.length)
21
+ : name;
22
+ }
23
+
24
+ function referenceCandidates(name: string, skill: CatalogSkill): string[] {
25
+ const normalized = normalizedPath(name);
26
+ const packageRelative = stripPathPrefix(
27
+ stripPathPrefix(normalized, "./references/"),
28
+ "references/",
29
+ );
30
+ const skillRelative = stripPathPrefix(
31
+ packageRelative,
32
+ `${skill.name}/references/`,
33
+ );
34
+ return [
35
+ ...new Set([
36
+ name,
37
+ withoutMarkdownSuffix(name),
38
+ normalized,
39
+ withoutMarkdownSuffix(normalized),
40
+ packageRelative,
41
+ withoutMarkdownSuffix(packageRelative),
42
+ skillRelative,
43
+ withoutMarkdownSuffix(skillRelative),
44
+ ]),
45
+ ];
46
+ }
47
+
48
+ function findSkillByName(
49
+ skills: CatalogSkill[],
50
+ name: string,
51
+ ): CatalogSkill | undefined {
52
+ return (
53
+ skills.find((skill) => skill.name === name) ??
54
+ skills.find((skill) => skill.name === withoutMarkdownSuffix(name))
55
+ );
56
+ }
57
+
58
+ function resolveSkillRead(
59
+ skills: CatalogSkill[],
60
+ name: string,
61
+ references: string[],
62
+ ): { skill: CatalogSkill; references: string[] } | undefined {
63
+ const direct = findSkillByName(skills, name);
64
+ if (direct) return { skill: direct, references };
65
+ const normalized = normalizedPath(name);
66
+ for (const skill of skills) {
67
+ if (normalized.toLowerCase() === `${skill.name}/skill.md`) {
68
+ return { skill, references };
69
+ }
70
+ const prefix = `${skill.name}/references/`;
71
+ if (normalized.toLowerCase().startsWith(prefix)) {
72
+ const reference = normalized.slice(prefix.length);
73
+ if (reference) {
74
+ return {
75
+ skill,
76
+ references: [...new Set([reference, ...references])],
77
+ };
78
+ }
79
+ }
80
+ }
81
+ if (!isAbsolute(name)) return undefined;
82
+ const requestedPath = resolve(name);
83
+ for (const skill of skills) {
84
+ if (requestedPath === resolve(skill.path)) {
85
+ return { skill, references };
86
+ }
87
+ const reference = referenceFiles(skill).find(
88
+ (path) => resolve(path) === requestedPath,
89
+ );
90
+ if (reference) {
91
+ return {
92
+ skill,
93
+ references: [...new Set([reference, ...references])],
94
+ };
95
+ }
96
+ }
97
+ return undefined;
98
+ }
99
+
100
+ function isOwnSkillDocument(reference: string, skill: CatalogSkill): boolean {
101
+ const normalized = normalizedPath(reference).toLowerCase();
102
+ return (
103
+ normalized === "skill.md" ||
104
+ normalized === `${skill.name}/skill.md` ||
105
+ (isAbsolute(reference) && resolve(reference) === resolve(skill.path))
106
+ );
107
+ }
108
+
109
+ function packageFiles(skill: CatalogSkill): string[] {
110
+ const root = realpathSync(skill.directory);
111
+ const paths: string[] = [];
112
+ const visitedDirectories = new Set<string>();
113
+
114
+ function listAssetEntries(directory: string): void {
115
+ for (const entry of directoryEntries(directory)) {
116
+ const path = join(directory, entry.name);
117
+ if (!entryKind(entry, path)) continue;
118
+ try {
119
+ if (!isWithin(root, realpathSync(path))) continue;
120
+ } catch {
121
+ continue;
122
+ }
123
+ paths.push(resolve(path));
124
+ }
125
+ }
126
+
127
+ function visit(directory: string): void {
128
+ const realDirectory = realpathSync(directory);
129
+ if (!isWithin(root, realDirectory) || visitedDirectories.has(realDirectory))
130
+ return;
131
+ visitedDirectories.add(realDirectory);
132
+ for (const entry of directoryEntries(directory)) {
133
+ const path = join(directory, entry.name);
134
+ const kind = entryKind(entry, path);
135
+ if (!kind) continue;
136
+ let realPath: string;
137
+ try {
138
+ realPath = realpathSync(path);
139
+ } catch {
140
+ continue;
141
+ }
142
+ if (!isWithin(root, realPath)) continue;
143
+ if (kind === "directory") {
144
+ if (directory === skill.directory && entry.name === "assets")
145
+ listAssetEntries(path);
146
+ else visit(path);
147
+ } else paths.push(resolve(path));
148
+ }
149
+ }
150
+
151
+ visit(skill.directory);
152
+ return paths.sort((left, right) => {
153
+ if (left === skill.path) return -1;
154
+ if (right === skill.path) return 1;
155
+ return left.localeCompare(right);
156
+ });
157
+ }
158
+
159
+ function formatSkillPaths(skill: CatalogSkill): string {
160
+ const paths = packageFiles(skill);
161
+ return `---\nSkill paths (${paths.length}):\n${paths.map((path) => `- ${path}`).join("\n")}`;
162
+ }
163
+
164
+ function formatSkill(skill: CatalogSkill): string {
165
+ return `${skill.body}\n\n${formatSkillPaths(skill)}`;
166
+ }
167
+
168
+ function referenceFiles(skill: CatalogSkill): string[] {
169
+ const root = resolve(skill.directory, "references");
170
+ return packageFiles(skill).filter(
171
+ (path) =>
172
+ isWithin(root, path) &&
173
+ path.toLowerCase().endsWith(".md") &&
174
+ statSync(path).isFile(),
175
+ );
176
+ }
177
+
178
+ function readReferences(
179
+ skill: CatalogSkill,
180
+ references: string[],
181
+ skills: CatalogSkill[],
182
+ ): string {
183
+ const root = resolve(skill.directory, "references");
184
+ const available = new Map(
185
+ referenceFiles(skill).map((path) => [
186
+ relative(root, path).replaceAll(sep, "/").replace(/\.md$/i, ""),
187
+ path,
188
+ ]),
189
+ );
190
+ const selected: Array<{ reference: string; content: string }> = [];
191
+ const seen = new Set<string>();
192
+ for (const requestedReference of references) {
193
+ const absoluteReference = isAbsolute(requestedReference)
194
+ ? [...available].find(
195
+ ([, path]) => resolve(path) === resolve(requestedReference),
196
+ )?.[0]
197
+ : undefined;
198
+ const reference =
199
+ absoluteReference ??
200
+ referenceCandidates(requestedReference, skill).find((candidate) =>
201
+ available.has(candidate),
202
+ );
203
+ const path = reference ? available.get(reference) : undefined;
204
+ if (!reference || !path) {
205
+ const separate = resolveSkillRead(skills, requestedReference, []);
206
+ if (separate && separate.skill !== skill) {
207
+ const command = [
208
+ "read",
209
+ separate.skill.name,
210
+ ...separate.references,
211
+ ].join(" ");
212
+ throw new Error(
213
+ `"${requestedReference}" is a separate skill, not a reference of "${skill.name}". Read it separately with "${command}"`,
214
+ );
215
+ }
216
+ const choices = [...available.keys()].join(", ") || "none";
217
+ throw new Error(
218
+ `Unknown reference "${requestedReference}" for skill "${skill.name}". Available: ${choices}`,
219
+ );
220
+ }
221
+ if (seen.has(reference)) continue;
222
+ seen.add(reference);
223
+ selected.push({ reference, content: readFileSync(path, "utf8").trim() });
224
+ }
225
+ const content =
226
+ selected.length === 1
227
+ ? (selected[0]?.content ?? "")
228
+ : selected
229
+ .map(
230
+ ({ reference, content: body }) => `--- ${reference} ---\n${body}`,
231
+ )
232
+ .join("\n\n");
233
+ return `${content}\n\n${formatSkillPaths(skill)}`;
234
+ }
235
+
236
+ export function readSkillPackage(
237
+ skills: CatalogSkill[],
238
+ name: string,
239
+ references: string[],
240
+ ): string {
241
+ const target = resolveSkillRead(skills, name, references);
242
+ if (!target) {
243
+ throw new Error(
244
+ `Unknown skill "${name}". Available: ${skills.map((skill) => skill.name).join(", ") || "none"}`,
245
+ );
246
+ }
247
+ const selectedReferences = target.references.filter(
248
+ (reference) => !isOwnSkillDocument(reference, target.skill),
249
+ );
250
+ return selectedReferences.length
251
+ ? readReferences(target.skill, selectedReferences, skills)
252
+ : formatSkill(target.skill);
253
+ }
package/src/tool.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { defineTool } from "@earendil-works/pi-coding-agent";
2
+ import type { Static } from "typebox";
3
+ import { Type } from "typebox";
4
+ import {
5
+ defaultSessionSkillsDir,
6
+ defaultSkillsDir,
7
+ type LoadedSkill,
8
+ runSkills,
9
+ } from "./catalog.js";
10
+
11
+ const SkillsParameters = Type.Object(
12
+ {
13
+ command: Type.String({
14
+ description: "list [category...] | read <skill> [reference...]",
15
+ }),
16
+ },
17
+ { additionalProperties: false },
18
+ );
19
+
20
+ type SkillsParameters = Static<typeof SkillsParameters>;
21
+
22
+ export interface SkillsToolOptions {
23
+ globalRoot?: string;
24
+ getLoadedSkills?(): readonly LoadedSkill[];
25
+ }
26
+
27
+ export function prepareSkillsCodeModeInput(input: unknown): SkillsParameters {
28
+ if (typeof input !== "string")
29
+ throw new Error("skills expects a string command");
30
+ return { command: input };
31
+ }
32
+
33
+ export function createSkillsTool(options: SkillsToolOptions = {}) {
34
+ return defineTool({
35
+ name: "skills",
36
+ label: "Skills",
37
+ description: "Active skill catalog, selected references and package paths.",
38
+ promptSnippet: "List or read skill instructions and references",
39
+ promptGuidelines: [
40
+ 'skills: At session start call skills once with "list". Before work read one always-applicable or task-relevant skill per call, followed only by that skill\'s references.',
41
+ ],
42
+ parameters: SkillsParameters,
43
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
44
+ const output = runSkills(
45
+ params.command,
46
+ options.globalRoot ?? defaultSkillsDir(),
47
+ defaultSessionSkillsDir(ctx.cwd),
48
+ options.getLoadedSkills?.() ?? [],
49
+ );
50
+ return {
51
+ content: [{ type: "text", text: output }],
52
+ details: {},
53
+ };
54
+ },
55
+ });
56
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "lib": ["ESNext", "DOM"]
5
+ },
6
+ "include": ["index.ts", "src/**/*.ts", "tests/**/*.ts"]
7
+ }