@zew1me/pi-skills-patch 0.0.0-stage → 0.1.1-alpha.162
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.
- package/README.md +11 -2
- package/dist/ATTRIBUTION.md +330 -0
- package/dist/LICENSE +21 -0
- package/dist/patches/pi-1.0.3/baseline.absent +2 -0
- package/dist/patches/pi-1.0.3/baseline.sha256 +8 -0
- package/dist/patches/pi-1.0.3/patched.sha256 +10 -0
- package/dist/patches/pi-1.0.3/pre-expansion-patched.sha256 +10 -0
- package/dist/patches/pi-1.0.3/pre-expansion-upgrade.patch +339 -0
- package/dist/patches/pi-1.0.3/skills.patch +1132 -0
- package/dist/patches/pi-1.1.0/baseline.absent +2 -0
- package/dist/patches/pi-1.1.0/baseline.sha256 +8 -0
- package/dist/patches/pi-1.1.0/patched.sha256 +10 -0
- package/dist/patches/pi-1.1.0/pre-expansion-patched.sha256 +10 -0
- package/dist/patches/pi-1.1.0/pre-expansion-upgrade.patch +339 -0
- package/dist/patches/pi-1.1.0/skills.patch +1138 -0
- package/dist/patches/pi-1.3.0/baseline.absent +2 -0
- package/dist/patches/pi-1.3.0/baseline.sha256 +8 -0
- package/dist/patches/pi-1.3.0/patched.sha256 +10 -0
- package/dist/patches/pi-1.3.0/pre-expansion-patched.sha256 +10 -0
- package/dist/patches/pi-1.3.0/pre-expansion-upgrade.patch +339 -0
- package/dist/patches/pi-1.3.0/skills.patch +1138 -0
- package/dist/patches/pi-1.4.0/baseline.absent +2 -0
- package/dist/patches/pi-1.4.0/baseline.sha256 +8 -0
- package/dist/patches/pi-1.4.0/patched.sha256 +10 -0
- package/dist/patches/pi-1.4.0/skills.patch +1138 -0
- package/dist/patches/pi-1.5.2/baseline.absent +2 -0
- package/dist/patches/pi-1.5.2/baseline.sha256 +8 -0
- package/dist/patches/pi-1.5.2/patched.sha256 +10 -0
- package/dist/patches/pi-1.5.2/skills.patch +1138 -0
- package/dist/patches/pi-1.6.0/baseline.absent +2 -0
- package/dist/patches/pi-1.6.0/baseline.sha256 +8 -0
- package/dist/patches/pi-1.6.0/patched.sha256 +10 -0
- package/dist/patches/pi-1.6.0/skills.patch +1138 -0
- package/dist/scripts/install-extensions.sh +454 -0
- package/package.json +31 -4
|
@@ -0,0 +1,1138 @@
|
|
|
1
|
+
diff --git a/dist/bundle/cli-runtime.js b/dist/bundle/cli-runtime.js
|
|
2
|
+
index 8661166..99f5492 100755
|
|
3
|
+
--- a/dist/bundle/cli-runtime.js
|
|
4
|
+
+++ b/dist/bundle/cli-runtime.js
|
|
5
|
+
@@ -1,3 +1,5 @@
|
|
6
|
+
#!/usr/bin/env node
|
|
7
|
+
-import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
8
|
+
-import{configureHttpDispatcher,main}from"./chunks/chunk-66G7ITPS.js";import"./chunks/chunk-RH6M5TBT.js";import"./chunks/chunk-AKJ3ZOR3.js";import"./chunks/chunk-6MWTY2OB.js";import"./chunks/chunk-GDR5JFDJ.js";import"./chunks/chunk-5GTPJSRI.js";import"./chunks/chunk-3ZATHNCK.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-WJUNYZC5.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-S3GGRYIO.js";import"./chunks/chunk-22CYIUS4.js";import"./chunks/chunk-ZBURYEWF.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-PYGXRV27.js";import"./chunks/chunk-HACVPRBJ.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-4L3WN2XY.js";function setupCli(){process.title=APP_NAME,process.env.PI_CODING_AGENT="true",process.env.AI_AGENT="pi",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();main(process.argv.slice(2));
|
|
9
|
+
+import { setupCli } from "../cli/setup.js";
|
|
10
|
+
+import { main } from "../main.js";
|
|
11
|
+
+setupCli();
|
|
12
|
+
+main(process.argv.slice(2));
|
|
13
|
+
diff --git a/dist/bundle/rpc-entry.js b/dist/bundle/rpc-entry.js
|
|
14
|
+
index cc7c2f1..b571534 100755
|
|
15
|
+
--- a/dist/bundle/rpc-entry.js
|
|
16
|
+
+++ b/dist/bundle/rpc-entry.js
|
|
17
|
+
@@ -1,3 +1,13 @@
|
|
18
|
+
#!/usr/bin/env node
|
|
19
|
+
-import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
20
|
+
-import{configureHttpDispatcher,main}from"./chunks/chunk-66G7ITPS.js";import"./chunks/chunk-RH6M5TBT.js";import"./chunks/chunk-AKJ3ZOR3.js";import"./chunks/chunk-6MWTY2OB.js";import"./chunks/chunk-GDR5JFDJ.js";import"./chunks/chunk-5GTPJSRI.js";import"./chunks/chunk-3ZATHNCK.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-WJUNYZC5.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-S3GGRYIO.js";import"./chunks/chunk-22CYIUS4.js";import"./chunks/chunk-ZBURYEWF.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-PYGXRV27.js";import"./chunks/chunk-HACVPRBJ.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-4L3WN2XY.js";process.title=`${APP_NAME}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
|
|
21
|
+
+import { APP_NAME } from "../config.js";
|
|
22
|
+
+import { configureHttpDispatcher } from "../core/http-dispatcher.js";
|
|
23
|
+
+import { main } from "../main.js";
|
|
24
|
+
+
|
|
25
|
+
+process.title = `${APP_NAME}-rpc`;
|
|
26
|
+
+process.env.PI_CODING_AGENT = "true";
|
|
27
|
+
+process.env.AI_AGENT = "pi";
|
|
28
|
+
+process.emitWarning = () => {};
|
|
29
|
+
+
|
|
30
|
+
+configureHttpDispatcher();
|
|
31
|
+
+
|
|
32
|
+
+main(["--mode", "rpc", ...process.argv.slice(2)]);
|
|
33
|
+
diff --git a/dist/core/resource-loader.js b/dist/core/resource-loader.js
|
|
34
|
+
index 563d7d5..786a237 100644
|
|
35
|
+
--- a/dist/core/resource-loader.js
|
|
36
|
+
+++ b/dist/core/resource-loader.js
|
|
37
|
+
@@ -12,6 +12,7 @@ import { findGitPaths } from "./footer-data-provider.js";
|
|
38
|
+
import { DefaultPackageManager } from "./package-manager.js";
|
|
39
|
+
import { loadPromptTemplates } from "./prompt-templates.js";
|
|
40
|
+
import { SettingsManager } from "./settings-manager.js";
|
|
41
|
+
+import { resolveActiveSkillPaths } from "./skill-management.js";
|
|
42
|
+
import { loadSkills } from "./skills.js";
|
|
43
|
+
import { BUILTIN_PATH_PREFIX, createSourceInfo, getSyntheticPathSource, isSyntheticPath, } from "./source-info.js";
|
|
44
|
+
import { resetTimings } from "./timings.js";
|
|
45
|
+
@@ -421,11 +422,20 @@ export class DefaultResourceLoader {
|
|
46
|
+
}
|
|
47
|
+
this.extensionsResult = this.extensionsOverride ? this.extensionsOverride(extensionsResult) : extensionsResult;
|
|
48
|
+
this.applyExtensionSourceInfo(this.extensionsResult.extensions, metadataByPath);
|
|
49
|
+
- const skillPaths = this.noSkills
|
|
50
|
+
- ? this.mergePaths(cliEnabledSkills, this.additionalSkillPaths)
|
|
51
|
+
- : this.mergePaths([...cliEnabledSkills, ...enabledSkills], this.additionalSkillPaths);
|
|
52
|
+
+ // Discovered skills are catalog entries, not active until explicitly enabled.
|
|
53
|
+
+ const activeSkills = this.noSkills
|
|
54
|
+
+ ? { paths: [], diagnostics: [] }
|
|
55
|
+
+ : await resolveActiveSkillPaths({
|
|
56
|
+
+ cwd: this.cwd,
|
|
57
|
+
+ agentDir: this.agentDir,
|
|
58
|
+
+ settingsManager: this.settingsManager,
|
|
59
|
+
+ resolvedSkillResources: resolvedPaths.skills,
|
|
60
|
+
+ resolveResourcePath: (p) => this.resolveResourcePath(p),
|
|
61
|
+
+ });
|
|
62
|
+
+ const skillPaths = this.mergePaths([...cliEnabledSkills, ...activeSkills.paths], this.additionalSkillPaths);
|
|
63
|
+
this.lastSkillPaths = skillPaths;
|
|
64
|
+
this.updateSkillsFromPaths(skillPaths, metadataByPath);
|
|
65
|
+
+ this.skillDiagnostics.push(...activeSkills.diagnostics);
|
|
66
|
+
for (const p of this.additionalSkillPaths) {
|
|
67
|
+
if (isLocalPath(p)) {
|
|
68
|
+
const resolved = this.resolveResourcePath(p);
|
|
69
|
+
diff --git a/dist/core/skill-management-core.js b/dist/core/skill-management-core.js
|
|
70
|
+
new file mode 100644
|
|
71
|
+
index 0000000..0b4ae56
|
|
72
|
+
--- /dev/null
|
|
73
|
+
+++ b/dist/core/skill-management-core.js
|
|
74
|
+
@@ -0,0 +1,719 @@
|
|
75
|
+
+/**
|
|
76
|
+
+ * Opt-in skill management for the patched Pi runtime.
|
|
77
|
+
+ *
|
|
78
|
+
+ * This module holds every piece of original logic in the `/skills` patch. It deliberately imports nothing:
|
|
79
|
+
+ * both Node built-ins and Pi's own helpers arrive through the injected {@link SkillEnvironment} seam. That
|
|
80
|
+
+ * keeps the module type-checkable and unit-testable inside this repository, while `skill-management.ts`
|
|
81
|
+
+ * binds the real implementations when the file is compiled inside a Pi source tree.
|
|
82
|
+
+ */
|
|
83
|
+
+function isObjectRecord(value) {
|
|
84
|
+
+ return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
85
|
+
+}
|
|
86
|
+
+function readJson(env, path) {
|
|
87
|
+
+ if (!env.fs.existsSync(path))
|
|
88
|
+
+ return {};
|
|
89
|
+
+ try {
|
|
90
|
+
+ const value = JSON.parse(env.fs.readFileSync(path, "utf-8"));
|
|
91
|
+
+ if (!isObjectRecord(value))
|
|
92
|
+
+ throw new Error("Expected a JSON object");
|
|
93
|
+
+ return value;
|
|
94
|
+
+ }
|
|
95
|
+
+ catch (error) {
|
|
96
|
+
+ throw new Error(`Could not parse ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
97
|
+
+ }
|
|
98
|
+
+}
|
|
99
|
+
+function writeJson(env, path, value) {
|
|
100
|
+
+ env.fs.mkdirSync(env.path.dirname(path), { recursive: true });
|
|
101
|
+
+ const tempPath = `${path}.${String(env.processId())}.tmp`;
|
|
102
|
+
+ env.fs.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`);
|
|
103
|
+
+ env.fs.renameSync(tempPath, path);
|
|
104
|
+
+}
|
|
105
|
+
+const skillConfigLockAttempts = 100;
|
|
106
|
+
+const skillConfigLockDelayMs = 20;
|
|
107
|
+
+function errorCode(error) {
|
|
108
|
+
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : undefined;
|
|
109
|
+
+}
|
|
110
|
+
+/** Follows Pi's trust-store lock: retry only while another process holds the lock. */
|
|
111
|
+
+function acquireSkillConfigLock(env, path) {
|
|
112
|
+
+ const configDir = env.path.dirname(path);
|
|
113
|
+
+ env.fs.mkdirSync(configDir, { recursive: true });
|
|
114
|
+
+ for (let attempt = 1;; attempt += 1) {
|
|
115
|
+
+ try {
|
|
116
|
+
+ return env.lockSync(configDir, { realpath: false, lockfilePath: `${path}.lock` });
|
|
117
|
+
+ }
|
|
118
|
+
+ catch (error) {
|
|
119
|
+
+ if (errorCode(error) !== "ELOCKED" || attempt >= skillConfigLockAttempts)
|
|
120
|
+
+ throw error;
|
|
121
|
+
+ env.sleepSync(skillConfigLockDelayMs);
|
|
122
|
+
+ }
|
|
123
|
+
+ }
|
|
124
|
+
+}
|
|
125
|
+
+/**
|
|
126
|
+
+ * Runs a read-modify-write of one configuration file under its lock.
|
|
127
|
+
+ *
|
|
128
|
+
+ * A failed release is reported rather than thrown, so it never hides the update's own result or error.
|
|
129
|
+
+ */
|
|
130
|
+
+function withSkillConfigLock(env, path, fn) {
|
|
131
|
+
+ const release = acquireSkillConfigLock(env, path);
|
|
132
|
+
+ try {
|
|
133
|
+
+ return fn();
|
|
134
|
+
+ }
|
|
135
|
+
+ finally {
|
|
136
|
+
+ try {
|
|
137
|
+
+ release();
|
|
138
|
+
+ }
|
|
139
|
+
+ catch (error) {
|
|
140
|
+
+ env.reportError(`Could not release skill configuration lock ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
141
|
+
+ }
|
|
142
|
+
+ }
|
|
143
|
+
+}
|
|
144
|
+
+function git(env, cwd, args) {
|
|
145
|
+
+ try {
|
|
146
|
+
+ return env
|
|
147
|
+
+ .execFileSync("git", ["-C", cwd, ...args], {
|
|
148
|
+
+ encoding: "utf-8",
|
|
149
|
+
+ stdio: ["ignore", "pipe", "ignore"],
|
|
150
|
+
+ timeout: 2000,
|
|
151
|
+
+ })
|
|
152
|
+
+ .trim();
|
|
153
|
+
+ }
|
|
154
|
+
+ catch {
|
|
155
|
+
+ return undefined;
|
|
156
|
+
+ }
|
|
157
|
+
+}
|
|
158
|
+
+export function normalizeGitRemoteUrl(rawUrl) {
|
|
159
|
+
+ if (!rawUrl)
|
|
160
|
+
+ return undefined;
|
|
161
|
+
+ const url = rawUrl.trim().replace(/^git\+/, "");
|
|
162
|
+
+ if (!url)
|
|
163
|
+
+ return undefined;
|
|
164
|
+
+ const scpLike = /^(?:[^@]+@)?([^:]+):(.+)$/.exec(url);
|
|
165
|
+
+ const scpHost = scpLike?.[1];
|
|
166
|
+
+ const scpPath = scpLike?.[2];
|
|
167
|
+
+ if (scpHost && scpPath !== undefined && !url.includes("://")) {
|
|
168
|
+
+ const repoPath = scpPath.replace(/\.git$/i, "").replace(/^\/+|\/+$/g, "");
|
|
169
|
+
+ return repoPath ? `${scpHost.toLowerCase()}:${repoPath}` : undefined;
|
|
170
|
+
+ }
|
|
171
|
+
+ try {
|
|
172
|
+
+ const parsed = new URL(url);
|
|
173
|
+
+ const repoPath = parsed.pathname.replace(/\.git$/i, "").replace(/^\/+|\/+$/g, "");
|
|
174
|
+
+ const defaultPort = parsed.protocol === "ssh:" ? "22" : parsed.protocol === "git:" ? "9418" : undefined;
|
|
175
|
+
+ const host = parsed.port && parsed.port !== defaultPort ? parsed.host : parsed.hostname;
|
|
176
|
+
+ return host && repoPath ? `${host.toLowerCase()}:${repoPath}` : undefined;
|
|
177
|
+
+ }
|
|
178
|
+
+ catch {
|
|
179
|
+
+ return undefined;
|
|
180
|
+
+ }
|
|
181
|
+
+}
|
|
182
|
+
+export function resolveRepoKey(env, cwd) {
|
|
183
|
+
+ for (const remote of ["upstream", "origin"]) {
|
|
184
|
+
+ const key = normalizeGitRemoteUrl(git(env, cwd, ["remote", "get-url", remote]));
|
|
185
|
+
+ if (key)
|
|
186
|
+
+ return key;
|
|
187
|
+
+ }
|
|
188
|
+
+ const firstRemote = git(env, cwd, ["remote"])
|
|
189
|
+
+ ?.split(/\r?\n/)
|
|
190
|
+
+ .map((name) => name.trim())
|
|
191
|
+
+ .find(Boolean);
|
|
192
|
+
+ const firstKey = firstRemote && normalizeGitRemoteUrl(git(env, cwd, ["remote", "get-url", firstRemote]));
|
|
193
|
+
+ if (firstKey)
|
|
194
|
+
+ return firstKey;
|
|
195
|
+
+ const root = git(env, cwd, ["rev-parse", "--show-toplevel"]);
|
|
196
|
+
+ if (!root)
|
|
197
|
+
+ return undefined;
|
|
198
|
+
+ const rel = env.path.relative(env.homedir(), root).split(env.path.sep).join("/");
|
|
199
|
+
+ return rel && !rel.startsWith("..") && rel !== "." ? `local:~/${rel}` : `local:${root}`;
|
|
200
|
+
+}
|
|
201
|
+
+export function sourceOf(entry) {
|
|
202
|
+
+ if (typeof entry === "string")
|
|
203
|
+
+ return entry;
|
|
204
|
+
+ if (!entry || typeof entry !== "object")
|
|
205
|
+
+ return undefined;
|
|
206
|
+
+ const record = entry;
|
|
207
|
+
+ const source = record.source ?? record.path ?? record.name;
|
|
208
|
+
+ return typeof source === "string" ? source : undefined;
|
|
209
|
+
+}
|
|
210
|
+
+export function enabledEntries(value) {
|
|
211
|
+
+ if (!isObjectRecord(value))
|
|
212
|
+
+ return [];
|
|
213
|
+
+ const enabled = value.enabled;
|
|
214
|
+
+ return Array.isArray(enabled) ? enabled : [];
|
|
215
|
+
+}
|
|
216
|
+
+export function scopeFromArgs(args, allowSession = false) {
|
|
217
|
+
+ const allowed = allowSession ? ["--global", "--repo", "--session"] : ["--global", "--repo"];
|
|
218
|
+
+ const scopes = args.filter((arg) => allowed.includes(arg));
|
|
219
|
+
+ const scope = scopes[0];
|
|
220
|
+
+ if (scopes.length !== 1 || scope === undefined) {
|
|
221
|
+
+ throw new Error(`Specify exactly one scope: ${allowSession ? "--global, --repo, or --session" : "--global or --repo"}.`);
|
|
222
|
+
+ }
|
|
223
|
+
+ return scope.slice(2);
|
|
224
|
+
+}
|
|
225
|
+
+export function configLocation(env, scope, cwd, agentDir) {
|
|
226
|
+
+ if (scope === "global")
|
|
227
|
+
+ return { path: env.path.join(agentDir, "skills.json") };
|
|
228
|
+
+ if (scope === "repo") {
|
|
229
|
+
+ const key = resolveRepoKey(env, cwd);
|
|
230
|
+
+ if (!key)
|
|
231
|
+
+ throw new Error("Repository scope requires a git repository.");
|
|
232
|
+
+ return { path: env.path.join(agentDir, "repo-skills.json"), key };
|
|
233
|
+
+ }
|
|
234
|
+
+ return {};
|
|
235
|
+
+}
|
|
236
|
+
+export function looksLikePath(value) {
|
|
237
|
+
+ return (value.includes("/") ||
|
|
238
|
+
+ value.includes("\\") ||
|
|
239
|
+
+ value.startsWith(".") ||
|
|
240
|
+
+ value.startsWith("~") ||
|
|
241
|
+
+ value.startsWith("$"));
|
|
242
|
+
+}
|
|
243
|
+
+const environmentVariableReference = /\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))/g;
|
|
244
|
+
+/**
|
|
245
|
+
+ * Expands `$NAME` and `${NAME}` references in a skill path.
|
|
246
|
+
+ *
|
|
247
|
+
+ * `/skills` arguments never pass through a shell, so without this a path such as `$HOME/skills/x` would be
|
|
248
|
+
+ * resolved against the working directory. An unset variable is left as written rather than removed: a path
|
|
249
|
+
+ * that genuinely contains `$` still resolves, and callers can name the variable when the path does not exist.
|
|
250
|
+
+ */
|
|
251
|
+
+export function expandEnvironmentVariables(env, input) {
|
|
252
|
+
+ const unset = [];
|
|
253
|
+
+ const value = input.replace(environmentVariableReference, (reference, braced, bare) => {
|
|
254
|
+
+ const name = braced ?? bare ?? "";
|
|
255
|
+
+ const expanded = env.environmentVariable(name);
|
|
256
|
+
+ if (expanded !== undefined)
|
|
257
|
+
+ return expanded;
|
|
258
|
+
+ if (!unset.includes(name))
|
|
259
|
+
+ unset.push(name);
|
|
260
|
+
+ return reference;
|
|
261
|
+
+ });
|
|
262
|
+
+ return { value, unset };
|
|
263
|
+
+}
|
|
264
|
+
+/** Resolves a path-like skill source to the absolute path it names, expanding variables and `~`. */
|
|
265
|
+
+function resolveSkillPath(env, source, cwd) {
|
|
266
|
+
+ return env.resolvePath(expandEnvironmentVariables(env, source).value, cwd, { trim: true });
|
|
267
|
+
+}
|
|
268
|
+
+/** True for a path that does not depend on the directory it is read from: absolute, `~`, or a `file:` URL. */
|
|
269
|
+
+function isAnchoredPath(env, value) {
|
|
270
|
+
+ return env.path.isAbsolute(value) || value === "~" || value.startsWith("~/") || value.startsWith("file:");
|
|
271
|
+
+}
|
|
272
|
+
+/** The checkout root for `cwd`; relative repository entries resolve against it. */
|
|
273
|
+
+function findRepoRoot(env, cwd) {
|
|
274
|
+
+ return git(env, cwd, ["rev-parse", "--show-toplevel"]);
|
|
275
|
+
+}
|
|
276
|
+
+/** `path` relative to `root` with `/` separators, comparing real paths, or undefined when it lies outside. */
|
|
277
|
+
+function pathInside(env, root, path) {
|
|
278
|
+
+ const real = (value) => (env.fs.existsSync(value) ? env.fs.realpathSync(value) : value);
|
|
279
|
+
+ const relative = env.path.relative(real(root), real(path));
|
|
280
|
+
+ if (relative === ".." || relative.startsWith(`..${env.path.sep}`) || env.path.isAbsolute(relative))
|
|
281
|
+
+ return undefined;
|
|
282
|
+
+ return relative.split(env.path.sep).join("/");
|
|
283
|
+
+}
|
|
284
|
+
+/**
|
|
285
|
+
+ * Chooses how an added path is written to configuration.
|
|
286
|
+
+ *
|
|
287
|
+
+ * Repository entries are shared by every checkout with the same remote, so a path inside the current checkout
|
|
288
|
+
+ * is stored relative to its root. Otherwise a `~` or `$NAME` spelling that resolves now is kept as typed, so it
|
|
289
|
+
+ * is expanded each time skills load rather than frozen at add time, and any other path is stored absolute,
|
|
290
|
+
+ * under `~` when it is in the home directory.
|
|
291
|
+
+ */
|
|
292
|
+
+function persistedForm(env, source, resolvedPath, context) {
|
|
293
|
+
+ const repoRelative = context.scope === "repo" && context.repoRoot !== undefined
|
|
294
|
+
+ ? pathInside(env, context.repoRoot, resolvedPath)
|
|
295
|
+
+ : undefined;
|
|
296
|
+
+ if (repoRelative !== undefined) {
|
|
297
|
+
+ return repoRelative === "" ? "." : looksLikePath(repoRelative) ? repoRelative : `./${repoRelative}`;
|
|
298
|
+
+ }
|
|
299
|
+
+ const typed = source.trim();
|
|
300
|
+
+ if (isPortableSpelling(env, typed))
|
|
301
|
+
+ return typed;
|
|
302
|
+
+ const home = pathInside(env, env.homedir(), resolvedPath);
|
|
303
|
+
+ return home === undefined ? resolvedPath : home === "" ? "~" : `~/${home}`;
|
|
304
|
+
+}
|
|
305
|
+
+/** Variables naming a working directory: a path spelled with them means the directory it named at add time. */
|
|
306
|
+
+const directoryVariables = new Set(["PWD", "OLDPWD"]);
|
|
307
|
+
+function referencesDirectoryVariable(typed) {
|
|
308
|
+
+ return [...typed.matchAll(environmentVariableReference)].some((match) => directoryVariables.has(match[1] ?? match[2] ?? ""));
|
|
309
|
+
+}
|
|
310
|
+
+/** True for a `~` or `$NAME` path that resolves the same way from any directory in the current environment. */
|
|
311
|
+
+function isPortableSpelling(env, typed) {
|
|
312
|
+
+ const spelled = typed === "~" || typed.startsWith("~/") || typed.search(environmentVariableReference) !== -1;
|
|
313
|
+
+ if (!spelled || !looksLikePath(typed) || referencesDirectoryVariable(typed))
|
|
314
|
+
+ return false;
|
|
315
|
+
+ const { value, unset } = expandEnvironmentVariables(env, typed);
|
|
316
|
+
+ return unset.length === 0 && isAnchoredPath(env, value.trim());
|
|
317
|
+
+}
|
|
318
|
+
+function unsetVariableHint(env, source) {
|
|
319
|
+
+ const { unset } = expandEnvironmentVariables(env, source);
|
|
320
|
+
+ if (unset.length === 0)
|
|
321
|
+
+ return undefined;
|
|
322
|
+
+ const names = unset.map((name) => `$${name}`).join(", ");
|
|
323
|
+
+ return `environment variable ${names} ${unset.length === 1 ? "is" : "are"} not set`;
|
|
324
|
+
+}
|
|
325
|
+
+function skillNotFoundMessage(env, source) {
|
|
326
|
+
+ const hint = looksLikePath(source) ? unsetVariableHint(env, source) : undefined;
|
|
327
|
+
+ return `Skill not found in the catalog or at an existing path: ${source}${hint ? ` (${hint})` : ""}`;
|
|
328
|
+
+}
|
|
329
|
+
+/** Explains why a persisted path entry could not be found, beyond its simply not existing. */
|
|
330
|
+
+function unresolvedEntryHint(env, source, scope) {
|
|
331
|
+
+ if (!looksLikePath(source))
|
|
332
|
+
+ return undefined;
|
|
333
|
+
+ const unset = unsetVariableHint(env, source);
|
|
334
|
+
+ if (unset !== undefined)
|
|
335
|
+
+ return unset;
|
|
336
|
+
+ if (isAnchoredPath(env, expandEnvironmentVariables(env, source).value.trim()))
|
|
337
|
+
+ return undefined;
|
|
338
|
+
+ return scope === "repo"
|
|
339
|
+
+ ? "relative repository paths resolve against the root of the current checkout"
|
|
340
|
+
+ : "relative paths resolve against the working directory; remove it, then add it again to store its absolute path";
|
|
341
|
+
+}
|
|
342
|
+
+function unresolvedSkillDiagnostic(env, entry) {
|
|
343
|
+
+ const hint = unresolvedEntryHint(env, entry.source, entry.scope);
|
|
344
|
+
+ return {
|
|
345
|
+
+ type: "warning",
|
|
346
|
+
+ message: `Active skill could not be resolved${hint ? `: ${hint}` : ""}`,
|
|
347
|
+
+ path: entry.source,
|
|
348
|
+
+ };
|
|
349
|
+
+}
|
|
350
|
+
+/** True when `path` exists and Pi's own loader finds at least one skill in it. */
|
|
351
|
+
+function containsSkills(env, path, options) {
|
|
352
|
+
+ if (!env.fs.existsSync(path))
|
|
353
|
+
+ return false;
|
|
354
|
+
+ const { skills } = env.loadSkills({
|
|
355
|
+
+ cwd: options.cwd,
|
|
356
|
+
+ agentDir: options.agentDir,
|
|
357
|
+
+ skillPaths: [path],
|
|
358
|
+
+ includeDefaults: false,
|
|
359
|
+
+ });
|
|
360
|
+
+ return skills.length > 0;
|
|
361
|
+
+}
|
|
362
|
+
+/**
|
|
363
|
+
+ * Normalizes an entry already persisted in a configuration file, for comparison.
|
|
364
|
+
+ *
|
|
365
|
+
+ * User input is normalized before it is stored, so a stored bare value is a catalog name and is compared
|
|
366
|
+
+ * literally. Resolving it against whatever happens to exist in the current directory would let an unrelated
|
|
367
|
+
+ * local folder make a catalog-name entry match, or block, a path entry. A path entry compares by the real path
|
|
368
|
+
+ * it names, so `~/x`, `$HOME/x`, and a repository-relative `x` all match the same absolute path.
|
|
369
|
+
+ */
|
|
370
|
+
+function normalizePersistedSource(env, source, context) {
|
|
371
|
+
+ if (!source)
|
|
372
|
+
+ return undefined;
|
|
373
|
+
+ if (!looksLikePath(source))
|
|
374
|
+
+ return source;
|
|
375
|
+
+ const value = expandEnvironmentVariables(env, source).value.trim();
|
|
376
|
+
+ const path = context.scope === "repo" && context.repoRoot !== undefined && !isAnchoredPath(env, value)
|
|
377
|
+
+ ? env.path.resolve(context.repoRoot, value)
|
|
378
|
+
+ : env.resolvePath(value, context.cwd, { trim: true });
|
|
379
|
+
+ return env.fs.existsSync(path) ? env.fs.realpathSync(path) : path;
|
|
380
|
+
+}
|
|
381
|
+
+export function updatePersistedSkill(env, action, source, scope, options) {
|
|
382
|
+
+ const location = configLocation(env, scope, options.cwd, options.agentDir);
|
|
383
|
+
+ const path = location.path;
|
|
384
|
+
+ if (path === undefined)
|
|
385
|
+
+ throw new Error(`Scope ${scope} has no persisted configuration.`);
|
|
386
|
+
+ const context = {
|
|
387
|
+
+ cwd: options.cwd,
|
|
388
|
+
+ scope,
|
|
389
|
+
+ repoRoot: scope === "repo" ? findRepoRoot(env, options.cwd) : undefined,
|
|
390
|
+
+ };
|
|
391
|
+
+ const key = normalizePersistedSource(env, source, context);
|
|
392
|
+
+ const matches = (entry) => normalizePersistedSource(env, sourceOf(entry), context) === key;
|
|
393
|
+
+ return withSkillConfigLock(env, path, () => {
|
|
394
|
+
+ const config = readJson(env, path);
|
|
395
|
+
+ const existing = location.key === undefined ? config : config[location.key];
|
|
396
|
+
+ const target = location.key === undefined ? config : isObjectRecord(existing) ? existing : {};
|
|
397
|
+
+ const enabled = enabledEntries(target);
|
|
398
|
+
+ const matched = enabled.some(matches);
|
|
399
|
+
+ if (action === "remove" && !matched)
|
|
400
|
+
+ return false;
|
|
401
|
+
+ target.enabled =
|
|
402
|
+
+ action === "add" ? (matched ? enabled : [...enabled, source]) : enabled.filter((entry) => !matches(entry));
|
|
403
|
+
+ if (location.key !== undefined)
|
|
404
|
+
+ config[location.key] = target;
|
|
405
|
+
+ writeJson(env, path, config);
|
|
406
|
+
+ return true;
|
|
407
|
+
+ });
|
|
408
|
+
+}
|
|
409
|
+
+/**
|
|
410
|
+
+ * Removes a persisted entry by its normalized form first, then by each other reading of a bare name.
|
|
411
|
+
+ *
|
|
412
|
+
+ * A bare name is stored as the catalog name, or as the path it named when that path existed at add time.
|
|
413
|
+
+ * Whether the path exists now says nothing about which form was stored: the path may have been deleted, or an
|
|
414
|
+
+ * unrelated folder with the same name may sit in the current directory. So after the normalized form, a bare
|
|
415
|
+
+ * name also tries its literal catalog name and its resolved path, without requiring that path to exist.
|
|
416
|
+
+ */
|
|
417
|
+
+function removePersistedSkill(env, source, target, scope, options) {
|
|
418
|
+
+ const candidates = looksLikePath(source)
|
|
419
|
+
+ ? [target]
|
|
420
|
+
+ : [target, source, env.resolvePath(source, options.cwd, { trim: true })];
|
|
421
|
+
+ return [...new Set(candidates)].some((candidate) => updatePersistedSkill(env, "remove", candidate, scope, options));
|
|
422
|
+
+}
|
|
423
|
+
+export function getActiveSkillEntries(env, { cwd, agentDir, strict = false, onWarn }) {
|
|
424
|
+
+ const entries = [];
|
|
425
|
+
+ const safeRead = (path) => {
|
|
426
|
+
+ try {
|
|
427
|
+
+ return readJson(env, path);
|
|
428
|
+
+ }
|
|
429
|
+
+ catch (error) {
|
|
430
|
+
+ if (strict)
|
|
431
|
+
+ throw error;
|
|
432
|
+
+ onWarn?.(`Ignoring skill configuration: ${error instanceof Error ? error.message : String(error)}`);
|
|
433
|
+
+ return {};
|
|
434
|
+
+ }
|
|
435
|
+
+ };
|
|
436
|
+
+ for (const source of enabledEntries(safeRead(env.path.join(agentDir, "skills.json")))) {
|
|
437
|
+
+ const value = sourceOf(source);
|
|
438
|
+
+ if (value)
|
|
439
|
+
+ entries.push({ scope: "global", source: value });
|
|
440
|
+
+ }
|
|
441
|
+
+ const key = resolveRepoKey(env, cwd);
|
|
442
|
+
+ if (key) {
|
|
443
|
+
+ const config = safeRead(env.path.join(agentDir, "repo-skills.json"));
|
|
444
|
+
+ for (const source of enabledEntries(config[key])) {
|
|
445
|
+
+ const value = sourceOf(source);
|
|
446
|
+
+ if (value)
|
|
447
|
+
+ entries.push({ scope: "repo", source: value });
|
|
448
|
+
+ }
|
|
449
|
+
+ }
|
|
450
|
+
+ return entries;
|
|
451
|
+
+}
|
|
452
|
+
+function getProjectAgentSkillDirs(env, cwd) {
|
|
453
|
+
+ const dirs = [];
|
|
454
|
+
+ const repoRoot = git(env, cwd, ["rev-parse", "--show-toplevel"]);
|
|
455
|
+
+ const stopAt = repoRoot ? env.fs.realpathSync(env.path.resolve(repoRoot)) : undefined;
|
|
456
|
+
+ const resolvedCwd = env.path.resolve(cwd);
|
|
457
|
+
+ if (!env.fs.existsSync(resolvedCwd))
|
|
458
|
+
+ return dirs;
|
|
459
|
+
+ let current = env.fs.realpathSync(resolvedCwd);
|
|
460
|
+
+ for (;;) {
|
|
461
|
+
+ if (stopAt !== undefined) {
|
|
462
|
+
+ const fromRoot = env.path.relative(stopAt, current);
|
|
463
|
+
+ if (fromRoot === ".." || fromRoot.startsWith(`..${env.path.sep}`) || env.path.isAbsolute(fromRoot))
|
|
464
|
+
+ break;
|
|
465
|
+
+ }
|
|
466
|
+
+ dirs.push(env.path.join(current, ".agents", "skills"));
|
|
467
|
+
+ if (current === stopAt)
|
|
468
|
+
+ break;
|
|
469
|
+
+ const parent = env.path.dirname(current);
|
|
470
|
+
+ if (parent === current)
|
|
471
|
+
+ break;
|
|
472
|
+
+ current = parent;
|
|
473
|
+
+ }
|
|
474
|
+
+ return dirs;
|
|
475
|
+
+}
|
|
476
|
+
+export function getSkillCatalogDirs(env, { cwd, agentDir, projectTrusted = false }) {
|
|
477
|
+
+ const dirs = [env.path.join(agentDir, "skills"), env.path.join(env.homedir(), ".agents", "skills")];
|
|
478
|
+
+ if (projectTrusted) {
|
|
479
|
+
+ dirs.push(env.path.join(cwd, env.configDirName, "skills"), ...getProjectAgentSkillDirs(env, cwd));
|
|
480
|
+
+ }
|
|
481
|
+
+ return dirs;
|
|
482
|
+
+}
|
|
483
|
+
+export async function getSkillCatalog(env, { cwd, agentDir, settingsManager, resolvedSkillResources }) {
|
|
484
|
+
+ const manager = settingsManager ?? env.createSettingsManager(cwd, agentDir);
|
|
485
|
+
+ const found = new Map();
|
|
486
|
+
+ const addSkills = (skills) => {
|
|
487
|
+
+ for (const skill of skills) {
|
|
488
|
+
+ if (!found.has(skill.name))
|
|
489
|
+
+ found.set(skill.name, skill);
|
|
490
|
+
+ }
|
|
491
|
+
+ };
|
|
492
|
+
+ for (const dir of getSkillCatalogDirs(env, { cwd, agentDir, projectTrusted: manager.isProjectTrusted() })) {
|
|
493
|
+
+ addSkills(env.loadSkillsFromDir({ dir, source: "path" }).skills);
|
|
494
|
+
+ }
|
|
495
|
+
+ const resolved = resolvedSkillResources ?? (await env.resolvePackageResources({ cwd, agentDir, settingsManager: manager })).skills;
|
|
496
|
+
+ const addResolvedSkills = (resources) => {
|
|
497
|
+
+ const paths = resources.filter((resource) => resource.enabled).map((resource) => resource.path);
|
|
498
|
+
+ addSkills(env.loadSkills({ cwd, agentDir, skillPaths: paths, includeDefaults: false }).skills);
|
|
499
|
+
+ };
|
|
500
|
+
+ addResolvedSkills(resolved.filter((resource) => resource.metadata.origin === "package"));
|
|
501
|
+
+ addResolvedSkills(resolved.filter((resource) => resource.metadata.origin === "top-level" && resource.metadata.source === "local"));
|
|
502
|
+
+ return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
503
|
+
+}
|
|
504
|
+
+async function resolveSkillSource(env, source, options) {
|
|
505
|
+
+ if (looksLikePath(source)) {
|
|
506
|
+
+ const resolvedPath = resolveSkillPath(env, source, options.cwd);
|
|
507
|
+
+ return { normalized: resolvedPath, resolved: env.fs.existsSync(resolvedPath) ? resolvedPath : undefined };
|
|
508
|
+
+ }
|
|
509
|
+
+ const resolvedPath = env.resolvePath(source, options.cwd, { trim: true });
|
|
510
|
+
+ // Build the catalog once, then use it both to prefer catalog names over same-named local folders and to
|
|
511
|
+
+ // resolve the selected skill. A bare local folder is retained as a path only when no catalog entry wins.
|
|
512
|
+
+ const catalog = await getSkillCatalog(env, options);
|
|
513
|
+
+ const catalogSkill = catalog.find((skill) => skill.name === source);
|
|
514
|
+
+ const normalized = containsSkills(env, resolvedPath, options) && !catalogSkill ? resolvedPath : source;
|
|
515
|
+
+ return { normalized, resolved: normalized === source ? catalogSkill?.filePath : resolvedPath };
|
|
516
|
+
+}
|
|
517
|
+
+function commandName(allowSession = false) {
|
|
518
|
+
+ return allowSession ? "/skills" : "pi skills";
|
|
519
|
+
+}
|
|
520
|
+
+export function usage(allowSession = false) {
|
|
521
|
+
+ const command = commandName(allowSession);
|
|
522
|
+
+ const scopes = `--global|--repo${allowSession ? "|--session" : ""}`;
|
|
523
|
+
+ return [
|
|
524
|
+
+ `Usage: ${command} <active|list|search|add|remove${allowSession ? "|reload" : ""}>`,
|
|
525
|
+
+ ` ${command} active`,
|
|
526
|
+
+ ` ${command} list`,
|
|
527
|
+
+ ` ${command} search <query>`,
|
|
528
|
+
+ ` ${command} add <skill-or-path> ${scopes}`,
|
|
529
|
+
+ ` ${command} remove <skill-or-path> ${scopes}`,
|
|
530
|
+
+ ...(allowSession ? [` ${command} reload`] : []),
|
|
531
|
+
+ ];
|
|
532
|
+
+}
|
|
533
|
+
+function runActiveCommand(env, rest, surface, options) {
|
|
534
|
+
+ if (rest.length !== 0)
|
|
535
|
+
+ throw new Error(`Usage: ${surface} active`);
|
|
536
|
+
+ const entries = getActiveSkillEntries(env, { ...options, strict: true });
|
|
537
|
+
+ return {
|
|
538
|
+
+ exitCode: 0,
|
|
539
|
+
+ lines: entries.length
|
|
540
|
+
+ ? ["Active skills:", ...entries.map((entry) => ` ${entry.scope}: ${entry.source}`)]
|
|
541
|
+
+ : ["Skills: none"],
|
|
542
|
+
+ activeEntries: entries,
|
|
543
|
+
+ };
|
|
544
|
+
+}
|
|
545
|
+
+async function runCatalogCommand(env, command, rest, surface, options) {
|
|
546
|
+
+ if (command === "list" && rest.length !== 0)
|
|
547
|
+
+ throw new Error(`Usage: ${surface} list`);
|
|
548
|
+
+ const query = command === "search" ? rest.join(" ").trim().toLowerCase() : "";
|
|
549
|
+
+ if (command === "search" && !query)
|
|
550
|
+
+ throw new Error(`Usage: ${surface} search <query>`);
|
|
551
|
+
+ const skills = (await getSkillCatalog(env, options)).filter((skill) => !query || `${skill.name} ${skill.description}`.toLowerCase().includes(query));
|
|
552
|
+
+ return {
|
|
553
|
+
+ exitCode: 0,
|
|
554
|
+
+ lines: skills.length
|
|
555
|
+
+ ? skills.map((skill) => `${skill.name}\t${skill.description}`)
|
|
556
|
+
+ : [query ? "No matching skills." : "No catalog skills found."],
|
|
557
|
+
+ };
|
|
558
|
+
+}
|
|
559
|
+
+/** What `add` writes for a resolved source: a catalog name as is, a path in its {@link persistedForm}. */
|
|
560
|
+
+function persistedAddForm(env, source, target, scope, cwd) {
|
|
561
|
+
+ if (!looksLikePath(source) && target === source)
|
|
562
|
+
+ return source;
|
|
563
|
+
+ return persistedForm(env, source, target, {
|
|
564
|
+
+ cwd,
|
|
565
|
+
+ scope,
|
|
566
|
+
+ repoRoot: scope === "repo" ? findRepoRoot(env, cwd) : undefined,
|
|
567
|
+
+ });
|
|
568
|
+
+}
|
|
569
|
+
+async function runMutationCommand(env, command, rest, surface, options) {
|
|
570
|
+
+ const scopeList = `--global|--repo${options.allowSession ? "|--session" : ""}`;
|
|
571
|
+
+ const source = rest.find((arg) => !arg.startsWith("--"));
|
|
572
|
+
+ if (!source)
|
|
573
|
+
+ throw new Error(`Usage: ${surface} ${command} <skill-or-path> ${scopeList}`);
|
|
574
|
+
+ const scope = scopeFromArgs(rest, options.allowSession);
|
|
575
|
+
+ if (rest.length !== 2 || rest.some((arg) => ![source, `--${scope}`].includes(arg))) {
|
|
576
|
+
+ throw new Error(`Usage: ${surface} ${command} <skill-or-path> ${scopeList}`);
|
|
577
|
+
+ }
|
|
578
|
+
+ // Removal never consults the catalog, whose package resolution can install missing packages. A stored bare
|
|
579
|
+
+ // value is a catalog name, so removing a bare name tries that literal name first and its resolved path after.
|
|
580
|
+
+ const resolution = command === "add" ? await resolveSkillSource(env, source, options) : undefined;
|
|
581
|
+
+ const target = command === "remove"
|
|
582
|
+
+ ? looksLikePath(source)
|
|
583
|
+
+ ? resolveSkillPath(env, source, options.cwd)
|
|
584
|
+
+ : source
|
|
585
|
+
+ : resolution?.normalized;
|
|
586
|
+
+ if (!target)
|
|
587
|
+
+ throw new Error(`Skill source is invalid: ${source}`);
|
|
588
|
+
+ if (command === "add" && !resolution?.resolved) {
|
|
589
|
+
+ throw new Error(skillNotFoundMessage(env, source));
|
|
590
|
+
+ }
|
|
591
|
+
+ if (scope === "session")
|
|
592
|
+
+ return { exitCode: 0, lines: [], session: { action: command, source: target } };
|
|
593
|
+
+ const updated = command === "add"
|
|
594
|
+
+ ? updatePersistedSkill(env, command, persistedAddForm(env, source, target, scope, options.cwd), scope, options)
|
|
595
|
+
+ : removePersistedSkill(env, source, target, scope, options);
|
|
596
|
+
+ if (!updated)
|
|
597
|
+
+ throw new Error(`Skill is not enabled for ${scope} scope: ${source}`);
|
|
598
|
+
+ return { exitCode: 0, lines: [`${command === "add" ? "Enabled" : "Disabled"} ${source} for ${scope} scope.`] };
|
|
599
|
+
+}
|
|
600
|
+
+export async function runSkillsCommand(env, args, options) {
|
|
601
|
+
+ try {
|
|
602
|
+
+ const surface = commandName(options.allowSession);
|
|
603
|
+
+ const [command, ...rest] = args;
|
|
604
|
+
+ if (command === "active")
|
|
605
|
+
+ return runActiveCommand(env, rest, surface, options);
|
|
606
|
+
+ if (command === "list" || command === "search") {
|
|
607
|
+
+ return await runCatalogCommand(env, command, rest, surface, options);
|
|
608
|
+
+ }
|
|
609
|
+
+ if (command === "add" || command === "remove") {
|
|
610
|
+
+ return await runMutationCommand(env, command, rest, surface, options);
|
|
611
|
+
+ }
|
|
612
|
+
+ return { exitCode: 1, lines: usage(options.allowSession) };
|
|
613
|
+
+ }
|
|
614
|
+
+ catch (error) {
|
|
615
|
+
+ return { exitCode: 1, lines: [error instanceof Error ? error.message : String(error)] };
|
|
616
|
+
+ }
|
|
617
|
+
+}
|
|
618
|
+
+/**
|
|
619
|
+
+ * Resolves the skills that are explicitly active for this session into concrete paths.
|
|
620
|
+
+ *
|
|
621
|
+
+ * Entries are either paths, which must exist, or catalog names, which are looked up by name. Path entries
|
|
622
|
+
+ * are expanded here, each time skills load, rather than when they are added: `~` and `$NAME` take the current
|
|
623
|
+
+ * environment, and a relative repository entry resolves against the root of the current checkout. The loader
|
|
624
|
+
+ * keeps the result until its next reload (`/reload`, `/skills reload`, or the reload `/skills add` and
|
|
625
|
+
+ * `/skills remove` trigger), which is what makes this a once-per-session expansion. The catalog is built at
|
|
626
|
+
+ * most once per call: every caller resolves a whole entry list in one pass, so a longer-lived cache would only
|
|
627
|
+
+ * need invalidating without ever being reused.
|
|
628
|
+
+ */
|
|
629
|
+
+export async function resolveActiveSkillPaths(env, context) {
|
|
630
|
+
+ const { cwd, agentDir, settingsManager, resolvedSkillResources, resolveResourcePath } = context;
|
|
631
|
+
+ const paths = [];
|
|
632
|
+
+ const diagnostics = [];
|
|
633
|
+
+ const entries = getActiveSkillEntries(env, {
|
|
634
|
+
+ cwd,
|
|
635
|
+
+ agentDir,
|
|
636
|
+
+ onWarn: (message) => diagnostics.push({ type: "warning", message }),
|
|
637
|
+
+ });
|
|
638
|
+
+ let catalogPathsByName;
|
|
639
|
+
+ const findCatalogSkillPath = async (name) => {
|
|
640
|
+
+ catalogPathsByName ??= new Map((await getSkillCatalog(env, {
|
|
641
|
+
+ cwd,
|
|
642
|
+
+ agentDir,
|
|
643
|
+
+ ...(settingsManager ? { settingsManager } : {}),
|
|
644
|
+
+ ...(resolvedSkillResources ? { resolvedSkillResources } : {}),
|
|
645
|
+
+ })).map((skill) => [skill.name, skill.filePath]));
|
|
646
|
+
+ return catalogPathsByName.get(name);
|
|
647
|
+
+ };
|
|
648
|
+
+ let repoRoot;
|
|
649
|
+
+ const entryPath = (entry) => {
|
|
650
|
+
+ const value = expandEnvironmentVariables(env, entry.source).value.trim();
|
|
651
|
+
+ if (entry.scope === "repo" && !isAnchoredPath(env, value)) {
|
|
652
|
+
+ repoRoot ??= { value: findRepoRoot(env, cwd) };
|
|
653
|
+
+ if (repoRoot.value !== undefined)
|
|
654
|
+
+ return env.path.resolve(repoRoot.value, value);
|
|
655
|
+
+ }
|
|
656
|
+
+ return resolveResourcePath(value);
|
|
657
|
+
+ };
|
|
658
|
+
+ for (const entry of entries) {
|
|
659
|
+
+ if (!looksLikePath(entry.source)) {
|
|
660
|
+
+ const resolved = await findCatalogSkillPath(entry.source);
|
|
661
|
+
+ if (resolved)
|
|
662
|
+
+ paths.push(resolved);
|
|
663
|
+
+ else
|
|
664
|
+
+ diagnostics.push(unresolvedSkillDiagnostic(env, entry));
|
|
665
|
+
+ continue;
|
|
666
|
+
+ }
|
|
667
|
+
+ const path = entryPath(entry);
|
|
668
|
+
+ if (env.fs.existsSync(path))
|
|
669
|
+
+ paths.push(path);
|
|
670
|
+
+ else
|
|
671
|
+
+ diagnostics.push(unresolvedSkillDiagnostic(env, entry));
|
|
672
|
+
+ }
|
|
673
|
+
+ return { paths, diagnostics };
|
|
674
|
+
+}
|
|
675
|
+
+/**
|
|
676
|
+
+ * Resolves a single skill entry for session scope.
|
|
677
|
+
+ *
|
|
678
|
+
+ * Returns both the normalized form (an expanded path, or the catalog name unchanged) and the concrete file
|
|
679
|
+
+ * path when one exists. Session activation needs both: the normalized form to match entries already in the
|
|
680
|
+
+ * session list, and the resolved path to add.
|
|
681
|
+
+ */
|
|
682
|
+
+export async function resolveSkillEntryPath(env, context, source) {
|
|
683
|
+
+ const { cwd, agentDir, settingsManager, resolvedSkillResources, resolveResourcePath } = context;
|
|
684
|
+
+ if (looksLikePath(source)) {
|
|
685
|
+
+ const normalized = resolveResourcePath(expandEnvironmentVariables(env, source).value);
|
|
686
|
+
+ return { normalized, resolved: env.fs.existsSync(normalized) ? normalized : undefined };
|
|
687
|
+
+ }
|
|
688
|
+
+ const catalog = await getSkillCatalog(env, {
|
|
689
|
+
+ cwd,
|
|
690
|
+
+ agentDir,
|
|
691
|
+
+ ...(settingsManager ? { settingsManager } : {}),
|
|
692
|
+
+ ...(resolvedSkillResources ? { resolvedSkillResources } : {}),
|
|
693
|
+
+ });
|
|
694
|
+
+ return { normalized: source, resolved: catalog.find((skill) => skill.name === source)?.filePath };
|
|
695
|
+
+}
|
|
696
|
+
+/**
|
|
697
|
+
+ * Applies a session-scope activation to the resource loader's own skill list.
|
|
698
|
+
+ *
|
|
699
|
+
+ * Returns the line to show, or `undefined` when it has already reported an error. The list is mutated in
|
|
700
|
+
+ * place because the loader holds the same array.
|
|
701
|
+
+ */
|
|
702
|
+
+async function applySessionSkillChange(env, session, context) {
|
|
703
|
+
+ const { cwd, agentDir, settingsManager, additionalSkillPaths, resolveResourcePath } = context;
|
|
704
|
+
+ if (!additionalSkillPaths) {
|
|
705
|
+
+ context.showError("Session skill activation is unavailable for this resource loader.");
|
|
706
|
+
+ return undefined;
|
|
707
|
+
+ }
|
|
708
|
+
+ if (session.action === "add") {
|
|
709
|
+
+ const pathContext = { cwd, agentDir, settingsManager, resolveResourcePath };
|
|
710
|
+
+ const { resolved } = await resolveSkillEntryPath(env, pathContext, session.source);
|
|
711
|
+
+ if (!resolved) {
|
|
712
|
+
+ context.showError(`Skill not found in the catalog: ${session.source}`);
|
|
713
|
+
+ return undefined;
|
|
714
|
+
+ }
|
|
715
|
+
+ if (!additionalSkillPaths.includes(resolved))
|
|
716
|
+
+ additionalSkillPaths.push(resolved);
|
|
717
|
+
+ return `Enabled ${resolved} for this session.`;
|
|
718
|
+
+ }
|
|
719
|
+
+ // Removal must not resolve packages. Recover bare names from the already-enabled paths, and compare explicit
|
|
720
|
+
+ // paths after applying the same resolution used by the resource loader.
|
|
721
|
+
+ const normalized = looksLikePath(session.source)
|
|
722
|
+
+ ? resolveResourcePath(expandEnvironmentVariables(env, session.source).value)
|
|
723
|
+
+ : session.source;
|
|
724
|
+
+ const skillPaths = looksLikePath(session.source)
|
|
725
|
+
+ ? []
|
|
726
|
+
+ : env
|
|
727
|
+
+ .loadSkills({ cwd, agentDir, skillPaths: additionalSkillPaths, includeDefaults: false })
|
|
728
|
+
+ .skills.filter((skill) => skill.name === session.source)
|
|
729
|
+
+ .map((skill) => skill.filePath);
|
|
730
|
+
+ const direct = (path) => path === session.source || path === normalized || skillPaths.includes(path);
|
|
731
|
+
+ // A bare name added as a local path stays removable by that name after the path is deleted, but only when
|
|
732
|
+
+ // nothing matches it directly.
|
|
733
|
+
+ const localPath = looksLikePath(session.source) ? undefined : env.resolvePath(session.source, cwd, { trim: true });
|
|
734
|
+
+ const matches = additionalSkillPaths.some(direct) ? direct : (path) => path === localPath;
|
|
735
|
+
+ if (!additionalSkillPaths.some(matches)) {
|
|
736
|
+
+ context.showError(`Skill is not enabled for this session: ${session.source}`);
|
|
737
|
+
+ return undefined;
|
|
738
|
+
+ }
|
|
739
|
+
+ const retained = additionalSkillPaths.filter((path) => !matches(path));
|
|
740
|
+
+ additionalSkillPaths.splice(0, additionalSkillPaths.length, ...retained);
|
|
741
|
+
+ return `Disabled ${session.source} for this session.`;
|
|
742
|
+
+}
|
|
743
|
+
+/** Renders `/skills active`, which adds session paths to the persisted scopes the shared command reports. */
|
|
744
|
+
+function formatActiveSkillLines(activeEntries, additionalSkillPaths) {
|
|
745
|
+
+ const entries = [
|
|
746
|
+
+ ...(activeEntries ?? []),
|
|
747
|
+
+ ...(additionalSkillPaths ?? []).map((source) => ({ scope: "session", source })),
|
|
748
|
+
+ ];
|
|
749
|
+
+ return entries.length
|
|
750
|
+
+ ? ["Active skills:", ...entries.map((entry) => ` ${entry.scope}: ${entry.source}`)]
|
|
751
|
+
+ : ["Skills: none"];
|
|
752
|
+
+}
|
|
753
|
+
+/**
|
|
754
|
+
+ * Runs the interactive `/skills` command.
|
|
755
|
+
+ *
|
|
756
|
+
+ * This holds the whole command body so `InteractiveMode` only needs to forward its context. Session scope
|
|
757
|
+
+ * resolves entries here rather than through resource-loader methods, so the loader keeps no skill-specific
|
|
758
|
+
+ * API of its own.
|
|
759
|
+
+ */
|
|
760
|
+
+export async function handleSkillsInteractive(env, text, context) {
|
|
761
|
+
+ const args = text.slice("/skills".length).trim().split(/\s+/).filter(Boolean);
|
|
762
|
+
+ if (args.length === 1 && args[0] === "reload") {
|
|
763
|
+
+ await context.reload();
|
|
764
|
+
+ return;
|
|
765
|
+
+ }
|
|
766
|
+
+ const { cwd, agentDir, settingsManager } = context;
|
|
767
|
+
+ const result = await runSkillsCommand(env, args, { cwd, agentDir, settingsManager, allowSession: true });
|
|
768
|
+
+ if (result.exitCode !== 0) {
|
|
769
|
+
+ context.showWarning(result.lines.join("\n"));
|
|
770
|
+
+ return;
|
|
771
|
+
+ }
|
|
772
|
+
+ let lines = result.lines;
|
|
773
|
+
+ if (result.session) {
|
|
774
|
+
+ const line = await applySessionSkillChange(env, result.session, context);
|
|
775
|
+
+ if (line === undefined)
|
|
776
|
+
+ return;
|
|
777
|
+
+ lines = [line];
|
|
778
|
+
+ }
|
|
779
|
+
+ if (args[0] === "active") {
|
|
780
|
+
+ lines = formatActiveSkillLines(result.activeEntries, context.additionalSkillPaths);
|
|
781
|
+
+ }
|
|
782
|
+
+ if (args[0] === "add" || args[0] === "remove") {
|
|
783
|
+
+ if (context.isBusy()) {
|
|
784
|
+
+ lines = [...lines, "Change will apply after `/skills reload` when the current operation finishes."];
|
|
785
|
+
+ }
|
|
786
|
+
+ else {
|
|
787
|
+
+ await context.reload();
|
|
788
|
+
+ }
|
|
789
|
+
+ }
|
|
790
|
+
+ if (lines.length > 0)
|
|
791
|
+
+ context.showOutput(lines.join("\n"));
|
|
792
|
+
+}
|
|
793
|
+
+//# sourceMappingURL=skill-management-core.js.map
|
|
794
|
+
|
|
795
|
+
diff --git a/dist/core/skill-management.js b/dist/core/skill-management.js
|
|
796
|
+
new file mode 100644
|
|
797
|
+
index 0000000..8b712ef
|
|
798
|
+
--- /dev/null
|
|
799
|
+
+++ b/dist/core/skill-management.js
|
|
800
|
+
@@ -0,0 +1,132 @@
|
|
801
|
+
+/**
|
|
802
|
+
+ * Pi-facing entry point for opt-in skill management.
|
|
803
|
+
+ *
|
|
804
|
+
+ * This file is copied into `packages/coding-agent/src/core/` when the runtime patch is built. It is the only
|
|
805
|
+
+ * place that names Pi's own modules and Node's built-ins; all logic lives in `skill-management-core.ts`,
|
|
806
|
+
+ * which this module binds to the real implementations.
|
|
807
|
+
+ *
|
|
808
|
+
+ * Every export keeps the signature Pi's call sites use, so the integration patch against upstream files
|
|
809
|
+
+ * stays a handful of lines.
|
|
810
|
+
+ */
|
|
811
|
+
+import { execFileSync } from "node:child_process";
|
|
812
|
+
+import chalk from "chalk";
|
|
813
|
+
+import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
|
|
814
|
+
+import { homedir } from "node:os";
|
|
815
|
+
+import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
816
|
+
+import lockfile from "proper-lockfile";
|
|
817
|
+
+import { createProjectTrustContext } from "../cli/project-trust.js";
|
|
818
|
+
+import { CONFIG_DIR_NAME } from "../config.js";
|
|
819
|
+
+import { resolveProjectTrusted } from "./project-trust.js";
|
|
820
|
+
+import { ProjectTrustStore } from "./trust-manager.js";
|
|
821
|
+
+import { resolvePath } from "../utils/paths.js";
|
|
822
|
+
+import { DefaultPackageManager } from "./package-manager.js";
|
|
823
|
+
+import { SettingsManager } from "./settings-manager.js";
|
|
824
|
+
+import { loadSkills, loadSkillsFromDir } from "./skills.js";
|
|
825
|
+
+import * as core from "./skill-management-core.js";
|
|
826
|
+
+const lockWait = new Int32Array(new SharedArrayBuffer(4));
|
|
827
|
+
+const env = {
|
|
828
|
+
+ fs: { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync },
|
|
829
|
+
+ path: { dirname, isAbsolute, join, relative, resolve, sep },
|
|
830
|
+
+ homedir,
|
|
831
|
+
+ environmentVariable: (name) => process.env[name],
|
|
832
|
+
+ execFileSync,
|
|
833
|
+
+ processId: () => process.pid,
|
|
834
|
+
+ lockSync: (directory, options) => lockfile.lockSync(directory, options),
|
|
835
|
+
+ sleepSync: (milliseconds) => {
|
|
836
|
+
+ Atomics.wait(lockWait, 0, 0, milliseconds);
|
|
837
|
+
+ },
|
|
838
|
+
+ reportError: (message) => {
|
|
839
|
+
+ console.error(message);
|
|
840
|
+
+ },
|
|
841
|
+
+ configDirName: CONFIG_DIR_NAME,
|
|
842
|
+
+ resolvePath,
|
|
843
|
+
+ loadSkillsFromDir,
|
|
844
|
+
+ loadSkills,
|
|
845
|
+
+ createSettingsManager: (cwd, agentDir) => SettingsManager.create(cwd, agentDir, { projectTrusted: false }),
|
|
846
|
+
+ // The core declares only the narrow `SettingsManagerLike` it calls, but every caller supplies a real
|
|
847
|
+
+ // SettingsManager: either pi's own, or the one `createSettingsManager` builds just above.
|
|
848
|
+
+ resolvePackageResources: async ({ cwd, agentDir, settingsManager }) => new DefaultPackageManager({
|
|
849
|
+
+ cwd,
|
|
850
|
+
+ agentDir,
|
|
851
|
+
+ settingsManager: settingsManager,
|
|
852
|
+
+ }).resolve(),
|
|
853
|
+
+};
|
|
854
|
+
+/** Re-exported unchanged: a pure string predicate with no environment dependency. */
|
|
855
|
+
+export const looksLikePath = core.looksLikePath;
|
|
856
|
+
+/** Re-exported unchanged: reads a configured entry's source with no environment dependency. */
|
|
857
|
+
+export const sourceOf = core.sourceOf;
|
|
858
|
+
+export function getActiveSkillEntries(options) {
|
|
859
|
+
+ return core.getActiveSkillEntries(env, options);
|
|
860
|
+
+}
|
|
861
|
+
+export async function getSkillCatalog(options) {
|
|
862
|
+
+ return core.getSkillCatalog(env, options);
|
|
863
|
+
+}
|
|
864
|
+
+export async function runSkillsCommand(args, options) {
|
|
865
|
+
+ return core.runSkillsCommand(env, args, options);
|
|
866
|
+
+}
|
|
867
|
+
+/**
|
|
868
|
+
+ * Resolves the explicitly active skills for a resource loader.
|
|
869
|
+
+ *
|
|
870
|
+
+ * `DefaultResourceLoader` calls this instead of carrying the resolution logic itself, which keeps the
|
|
871
|
+
+ * upstream diff to a single call site.
|
|
872
|
+
+ */
|
|
873
|
+
+export async function resolveActiveSkillPaths(context) {
|
|
874
|
+
+ return core.resolveActiveSkillPaths(env, context);
|
|
875
|
+
+}
|
|
876
|
+
+/**
|
|
877
|
+
+ * Runs the one-shot `pi skills ...` command and prints its result.
|
|
878
|
+
+ *
|
|
879
|
+
+ * Trust resolution lives here rather than in `main.ts` so the upstream entry point only needs to route the
|
|
880
|
+
+ * subcommand. Catalog-reading subcommands may surface project-local skills, so they resolve project trust
|
|
881
|
+
+ * first; mutations and `active` do not.
|
|
882
|
+
+ */
|
|
883
|
+
+export async function handleSkillsCli(options) {
|
|
884
|
+
+ const { args, cwd, agentDir, settingsManager } = options;
|
|
885
|
+
+ const hasUI = Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
886
|
+
+ if (args[0] !== undefined && ["list", "search", "add"].includes(args[0])) {
|
|
887
|
+
+ settingsManager.setProjectTrusted(await resolveProjectTrusted({
|
|
888
|
+
+ cwd,
|
|
889
|
+
+ trustStore: new ProjectTrustStore(agentDir),
|
|
890
|
+
+ defaultProjectTrust: settingsManager.getDefaultProjectTrust(),
|
|
891
|
+
+ projectTrustContext: createProjectTrustContext({
|
|
892
|
+
+ cwd,
|
|
893
|
+
+ mode: hasUI ? "interactive" : "print",
|
|
894
|
+
+ settingsManager,
|
|
895
|
+
+ hasUI,
|
|
896
|
+
+ }),
|
|
897
|
+
+ }));
|
|
898
|
+
+ }
|
|
899
|
+
+ const result = await runSkillsCommand(args, { cwd, agentDir, settingsManager });
|
|
900
|
+
+ const output = result.lines.join("\n");
|
|
901
|
+
+ if (result.exitCode === 0) {
|
|
902
|
+
+ if (output)
|
|
903
|
+
+ console.log(output);
|
|
904
|
+
+ }
|
|
905
|
+
+ else {
|
|
906
|
+
+ console.error(chalk.red(output));
|
|
907
|
+
+ process.exitCode = result.exitCode;
|
|
908
|
+
+ }
|
|
909
|
+
+}
|
|
910
|
+
+/** Runs the interactive `/skills` command. See `skill-management-core.ts` for the behaviour. */
|
|
911
|
+
+export async function handleSkillsInteractive(text, context) {
|
|
912
|
+
+ return core.handleSkillsInteractive(env, text, context);
|
|
913
|
+
+}
|
|
914
|
+
+// The runtime module keeps the full public surface the previous hand-written patch exposed, so repository
|
|
915
|
+
+// tests and any other consumer can reach the pure helpers directly.
|
|
916
|
+
+export const normalizeGitRemoteUrl = core.normalizeGitRemoteUrl;
|
|
917
|
+
+export const scopeFromArgs = core.scopeFromArgs;
|
|
918
|
+
+export const usage = core.usage;
|
|
919
|
+
+export function resolveRepoKey(cwd) {
|
|
920
|
+
+ return core.resolveRepoKey(env, cwd);
|
|
921
|
+
+}
|
|
922
|
+
+export function getSkillCatalogDirs(options) {
|
|
923
|
+
+ return core.getSkillCatalogDirs(env, options);
|
|
924
|
+
+}
|
|
925
|
+
+/**
|
|
926
|
+
+ * Resolves one skill entry to a concrete file path, for session scope and for callers that need to check a
|
|
927
|
+
+ * catalog name without loading every active skill.
|
|
928
|
+
+ */
|
|
929
|
+
+export async function resolveSkillEntryPath(context, source) {
|
|
930
|
+
+ return core.resolveSkillEntryPath(env, context, source);
|
|
931
|
+
+}
|
|
932
|
+
+//# sourceMappingURL=skill-management.js.map
|
|
933
|
+
|
|
934
|
+
diff --git a/dist/core/slash-commands.js b/dist/core/slash-commands.js
|
|
935
|
+
index 25cc1c5..211383c 100644
|
|
936
|
+
--- a/dist/core/slash-commands.js
|
|
937
|
+
+++ b/dist/core/slash-commands.js
|
|
938
|
+
@@ -23,6 +23,7 @@ export const BUILTIN_SLASH_COMMANDS = [
|
|
939
|
+
{ name: "compact", description: "Manually compact the session context" },
|
|
940
|
+
{ name: "resume", description: "Resume a different session" },
|
|
941
|
+
{ name: "reload", description: "Reload keybindings, extensions, skills, prompts, themes, and context files" },
|
|
942
|
+
+ { name: "skills", description: "List and manage active skills", argumentHint: "<active|list|search|add|remove|reload>" },
|
|
943
|
+
{ name: "quit", description: `Quit ${APP_NAME}` },
|
|
944
|
+
];
|
|
945
|
+
//# sourceMappingURL=slash-commands.js.map
|
|
946
|
+
|
|
947
|
+
diff --git a/dist/main.js b/dist/main.js
|
|
948
|
+
index e4fb658..19b28ba 100644
|
|
949
|
+
--- a/dist/main.js
|
|
950
|
+
+++ b/dist/main.js
|
|
951
|
+
@@ -26,6 +26,7 @@ import { AuthStorage, ReadOnlyAuthStorage } from "./core/auth-storage.js";
|
|
952
|
+
import { exportFromFile } from "./core/export-html/index.js";
|
|
953
|
+
import { applyHttpProxySettings, configureHttpDispatcher } from "./core/http-dispatcher.js";
|
|
954
|
+
import { resolveCliModel, resolveModelScope } from "./core/model-resolver.js";
|
|
955
|
+
+import { handleSkillsCli } from "./core/skill-management.js";
|
|
956
|
+
import { ModelRuntime } from "./core/model-runtime.js";
|
|
957
|
+
import { restoreStdout, takeOverStdout } from "./core/output-guard.js";
|
|
958
|
+
import { resolveProjectTrusted } from "./core/project-trust.js";
|
|
959
|
+
@@ -489,6 +490,10 @@ export async function main(args, options) {
|
|
960
|
+
process.exitCode = await runMcpCommand(args.slice(1), { cwd, agentDir });
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
+ if (args[0] === "skills") {
|
|
964
|
+
+ await handleSkillsCli({ args: args.slice(1), cwd, agentDir, settingsManager: bootstrapSettingsManager });
|
|
965
|
+
+ return;
|
|
966
|
+
+ }
|
|
967
|
+
const parsed = parseArgs(args);
|
|
968
|
+
if (parsed.diagnostics.length > 0) {
|
|
969
|
+
for (const d of parsed.diagnostics) {
|
|
970
|
+
diff --git a/dist/modes/interactive/interactive-mode.js b/dist/modes/interactive/interactive-mode.js
|
|
971
|
+
index d2343a5..111ee06 100644
|
|
972
|
+
--- a/dist/modes/interactive/interactive-mode.js
|
|
973
|
+
+++ b/dist/modes/interactive/interactive-mode.js
|
|
974
|
+
@@ -28,6 +28,7 @@ import { DefaultPackageManager } from "../../core/package-manager.js";
|
|
975
|
+
import { RADIUS_MCP_URL, RADIUS_PROVIDER_ID } from "../../core/radius.js";
|
|
976
|
+
import { formatMissingSessionCwdPrompt, MissingSessionCwdError } from "../../core/session-cwd.js";
|
|
977
|
+
import { SessionManager, sessionEntryToContextMessages, } from "../../core/session-manager.js";
|
|
978
|
+
+import { handleSkillsInteractive } from "../../core/skill-management.js";
|
|
979
|
+
import { BUILTIN_SLASH_COMMANDS } from "../../core/slash-commands.js";
|
|
980
|
+
import { isInstallTelemetryEnabled } from "../../core/telemetry.js";
|
|
981
|
+
import { withBuiltInRenderers } from "../../core/tools/renderers/index.js";
|
|
982
|
+
@@ -39,7 +40,7 @@ import { copyToClipboard, readClipboardFilePaths, readClipboardText } from "../.
|
|
983
|
+
import { extensionForImageMimeType, readClipboardImage } from "../../utils/clipboard-image.js";
|
|
984
|
+
import { parseGitUrl } from "../../utils/git.js";
|
|
985
|
+
import { ensurePngTranscoder } from "../../utils/image-convert.js";
|
|
986
|
+
-import { getCwdRelativePath } from "../../utils/paths.js";
|
|
987
|
+
+import { getCwdRelativePath, resolvePath } from "../../utils/paths.js";
|
|
988
|
+
import { getPiUserAgent } from "../../utils/pi-user-agent.js";
|
|
989
|
+
import { killTrackedDetachedChildren } from "../../utils/shell.js";
|
|
990
|
+
import { loadAllHighlightLanguages } from "../../utils/syntax-highlight.js";
|
|
991
|
+
@@ -2660,6 +2661,11 @@ export class InteractiveMode {
|
|
992
|
+
await this.handleReloadCommand();
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
+ if (text === "/skills" || text.startsWith("/skills ")) {
|
|
996
|
+
+ this.editor.setText("");
|
|
997
|
+
+ await this.handleSkillsCommand(text);
|
|
998
|
+
+ return;
|
|
999
|
+
+ }
|
|
1000
|
+
if (text === "/debug") {
|
|
1001
|
+
this.handleDebugCommand();
|
|
1002
|
+
this.editor.setText("");
|
|
1003
|
+
@@ -5366,6 +5372,24 @@ export class InteractiveMode {
|
|
1004
|
+
// =========================================================================
|
|
1005
|
+
// Command handlers
|
|
1006
|
+
// =========================================================================
|
|
1007
|
+
+ async handleSkillsCommand(text) {
|
|
1008
|
+
+ await handleSkillsInteractive(text, {
|
|
1009
|
+
+ cwd: this.sessionManager.getCwd(),
|
|
1010
|
+
+ agentDir: getAgentDir(),
|
|
1011
|
+
+ settingsManager: this.settingsManager,
|
|
1012
|
+
+ additionalSkillPaths: this.session.resourceLoader.additionalSkillPaths,
|
|
1013
|
+
+ resolveResourcePath: (p) => resolvePath(p, this.sessionManager.getCwd()),
|
|
1014
|
+
+ isBusy: () => this.session.isStreaming || this.session.isCompacting,
|
|
1015
|
+
+ reload: () => this.handleReloadCommand(),
|
|
1016
|
+
+ showWarning: (message) => this.showWarning(message),
|
|
1017
|
+
+ showError: (message) => this.showError(message),
|
|
1018
|
+
+ showOutput: (message) => {
|
|
1019
|
+
+ this.chatContainer.addChild(new Spacer(1));
|
|
1020
|
+
+ this.chatContainer.addChild(new Text(message, 1, 0));
|
|
1021
|
+
+ this.ui.requestRender();
|
|
1022
|
+
+ },
|
|
1023
|
+
+ });
|
|
1024
|
+
+ }
|
|
1025
|
+
async handleReloadCommand() {
|
|
1026
|
+
if (this.session.isStreaming) {
|
|
1027
|
+
this.showWarning("Wait for the current response to finish before reloading.");
|
|
1028
|
+
diff --git a/docs/skills.md b/docs/skills.md
|
|
1029
|
+
index 19d2bf2..2a17b24 100644
|
|
1030
|
+
--- a/docs/skills.md
|
|
1031
|
+
+++ b/docs/skills.md
|
|
1032
|
+
@@ -40,9 +40,11 @@ Use relative paths from the skill directory when referring to bundled files. Pi
|
|
1033
|
+
|
|
1034
|
+
## Understand how skills load
|
|
1035
|
+
|
|
1036
|
+
-At startup, Pi scans configured skill locations and adds each skill’s name, description, and path to the system prompt. It does not add the full instructions.
|
|
1037
|
+
+Pi starts with no active skills. Configured skill locations form a catalog, but catalog entries are not added to the system prompt unless they are explicitly [activated](#activate-skills).
|
|
1038
|
+
|
|
1039
|
+
-When a task matches, the model reads `SKILL.md` and follows its instructions. This keeps detailed guidance out of context until it is needed. A model might fail to load a relevant skill, so use `/skill:name` when you need to force it.
|
|
1040
|
+
+At startup, Pi resolves the active skills and adds each active skill’s name, description, and path to the system prompt. It does not add the full instructions.
|
|
1041
|
+
+
|
|
1042
|
+
+When a task matches, the model reads `SKILL.md` and follows its instructions. This keeps detailed guidance out of context until it is needed. A model might fail to load a relevant skill, so use `/skill:name` when you need to force it. Only active skills register `/skill:name` commands.
|
|
1043
|
+
|
|
1044
|
+
Arguments after `/skill:name` are appended to the loaded instructions as a user request:
|
|
1045
|
+
|
|
1046
|
+
@@ -56,14 +58,82 @@ Set `disable-model-invocation: true` in frontmatter when a skill should be avail
|
|
1047
|
+
|
|
1048
|
+
## Add it to Pi
|
|
1049
|
+
|
|
1050
|
+
-Place the skill in your user or project skills directory. Directories containing `SKILL.md` are discovered recursively.
|
|
1051
|
+
+Place the skill in your user or project skills directory to add it to the catalog. Directories containing `SKILL.md` are discovered recursively.
|
|
1052
|
+
|
|
1053
|
+
Pi also supports the Agent Skills locations `~/.agents/skills/` and `.agents/skills/`. Project `.agents/skills/` directories are discovered from the working directory through its ancestors, stopping at the repository root when one exists.
|
|
1054
|
+
|
|
1055
|
+
Pi accepts some standalone Markdown skills, but a directory containing `SKILL.md` is the portable form and should be preferred. See [Settings](settings.md#resources) and [Pi Packages](packages.md) for additional locations.
|
|
1056
|
+
|
|
1057
|
+
+Catalog sources are considered in this order; name collisions keep the first skill found:
|
|
1058
|
+
+
|
|
1059
|
+
+- Global directories: `~/.pi/agent/skills/` and `~/.agents/skills/`
|
|
1060
|
+
+- Project directories, only after the project is trusted: `.pi/skills/` and `.agents/skills/` in the working directory and its ancestors
|
|
1061
|
+
+- Packages: `skills/` directories or `pi.skills` entries in `package.json`; project packages require trust
|
|
1062
|
+
+- Settings: the global `skills` array and, when trusted, the project `skills` array; entries may be files or directories and use package-manager precedence within this group
|
|
1063
|
+
+
|
|
1064
|
+
Project skills can instruct the model to run scripts or modify files. Review unfamiliar skills and their supporting files before granting project trust.
|
|
1065
|
+
|
|
1066
|
+
+## Activate skills
|
|
1067
|
+
+
|
|
1068
|
+
+A catalog skill enters the system prompt only when it is active. Active skills come from:
|
|
1069
|
+
+
|
|
1070
|
+
+- Session/CLI: `--skill <path>` (repeatable, additive even with `--no-skills`) or `/skills add <name> --session`
|
|
1071
|
+
+- Global: `~/.pi/agent/skills.json`
|
|
1072
|
+
+- Repository: `~/.pi/agent/repo-skills.json`, keyed by git repository identity
|
|
1073
|
+
+
|
|
1074
|
+
+Package- and settings-provided skills that previously loaded automatically must now be enabled in `~/.pi/agent/skills.json` or the applicable entry in `~/.pi/agent/repo-skills.json`. Use `pi skills list` to find catalog skill names.
|
|
1075
|
+
+
|
|
1076
|
+
+Enable global skills with `~/.pi/agent/skills.json`:
|
|
1077
|
+
+
|
|
1078
|
+
+```json
|
|
1079
|
+
+{
|
|
1080
|
+
+ "enabled": [
|
|
1081
|
+
+ "~/.agents/skills/code-review-and-quality",
|
|
1082
|
+
+ { "source": "~/.agents/skills/browser-testing-with-devtools" }
|
|
1083
|
+
+ ]
|
|
1084
|
+
+}
|
|
1085
|
+
+```
|
|
1086
|
+
+
|
|
1087
|
+
+Enable repository-scoped skills with `~/.pi/agent/repo-skills.json`:
|
|
1088
|
+
+
|
|
1089
|
+
+```json
|
|
1090
|
+
+{
|
|
1091
|
+
+ "github.com:earendil-works/pi": {
|
|
1092
|
+
+ "enabled": ["~/.agents/skills/pi-development"]
|
|
1093
|
+
+ },
|
|
1094
|
+
+ "local:~/Documents/repos/private-tool": {
|
|
1095
|
+
+ "enabled": ["~/.agents/skills/private-tool"]
|
|
1096
|
+
+ }
|
|
1097
|
+
+}
|
|
1098
|
+
+```
|
|
1099
|
+
+
|
|
1100
|
+
+Repository keys are resolved from git remotes in this order: `upstream`, then `origin`, then the first configured remote. Remote URLs are normalized so `git@github.com:earendil-works/pi.git`, `https://github.com/earendil-works/pi`, and `ssh://git@github.com/earendil-works/pi.git` all become `github.com:earendil-works/pi`. Non-default ports stay part of the key. If no remote exists, Pi falls back to `local:<repo-root-relative-to-$HOME>`, such as `local:~/Documents/repos/private-tool`.
|
|
1101
|
+
+
|
|
1102
|
+
+Manage activation with either the interactive `/skills` command or the one-shot CLI:
|
|
1103
|
+
+
|
|
1104
|
+
+```text
|
|
1105
|
+
+/skills active
|
|
1106
|
+
+/skills list
|
|
1107
|
+
+/skills search browser
|
|
1108
|
+
+/skills add browser-testing-with-devtools --session
|
|
1109
|
+
+/skills add browser-testing-with-devtools --repo
|
|
1110
|
+
+/skills remove browser-testing-with-devtools --global
|
|
1111
|
+
+/skills reload
|
|
1112
|
+
+
|
|
1113
|
+
+pi skills active
|
|
1114
|
+
+pi skills list
|
|
1115
|
+
+pi skills search browser
|
|
1116
|
+
+pi skills add browser-testing-with-devtools --global
|
|
1117
|
+
+pi skills add browser-testing-with-devtools --repo
|
|
1118
|
+
+pi skills remove browser-testing-with-devtools --repo
|
|
1119
|
+
+```
|
|
1120
|
+
+
|
|
1121
|
+
+`--session` is interactive-only and lasts until the session ends. `--global` and `--repo` persist to their respective JSON configuration. `list` and `search` show catalog skills. `pi skills active` shows the configured global and repository entries; `/skills active` also shows session entries.
|
|
1122
|
+
+
|
|
1123
|
+
+Path arguments may use `~`, `$NAME`, or `${NAME}`; `/skills` expands them itself because its arguments never pass through a shell. With `--repo`, a path inside the current checkout is stored relative to the repository root, so the entry works in every clone and worktree with the same remote. Otherwise `add` keeps a `~` or `$NAME` spelling as typed and stores any other path as an absolute path, under `~` when it is in your home directory. Stored paths are expanded whenever Pi loads skills: at startup, after `/skills add` or `/skills remove`, and on `/reload` or `/skills reload`. Other relative entries resolve against the repository root in `repo-skills.json` and against the working directory in `skills.json`, so prefer absolute, `~`, or `$NAME` paths in `skills.json`.
|
|
1124
|
+
+
|
|
1125
|
+
+Use `--no-skills` to suppress global and repository active skills; explicit `--skill` paths still load.
|
|
1126
|
+
+
|
|
1127
|
+
## Write portable frontmatter
|
|
1128
|
+
|
|
1129
|
+
The Agent Skills specification defines these fields:
|
|
1130
|
+
@@ -86,7 +156,7 @@ Malformed `SKILL.md` files and declared skills without descriptions are not load
|
|
1131
|
+
|
|
1132
|
+
## Validate and share a skill
|
|
1133
|
+
|
|
1134
|
+
-Run Pi from a location where the skill is discoverable, then inspect the startup diagnostics and `/skill:name` command. Run `/reload` after editing a skill during an active session.
|
|
1135
|
+
+Run Pi from a location where the skill is discoverable, confirm it appears in `pi skills list`, activate it, then inspect the startup diagnostics and `/skill:name` command. Run `/reload` after editing a skill during an active session.
|
|
1136
|
+
|
|
1137
|
+
Use a [Pi package](packages.md) to distribute one or more skills through npm or git. Keep environment setup inside the skill and declare any required runtime dependencies in the package.
|
|
1138
|
+
|