@av-pi-studio/server 0.0.111 → 0.0.113
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/dist/daemon/bootstrap.js +13 -0
- package/dist/extensions/sync-executor.d.ts +4 -0
- package/dist/extensions/sync-executor.js +9 -3
- package/dist/resources/pi-sdk.d.ts +26 -0
- package/dist/resources/pi-sdk.js +21 -0
- package/dist/resources/resource-service.d.ts +197 -0
- package/dist/resources/resource-service.js +717 -0
- package/dist/resources/skill-catalog.d.ts +69 -0
- package/dist/resources/skill-catalog.js +195 -0
- package/dist/resources/skills-cli.d.ts +37 -0
- package/dist/resources/skills-cli.js +113 -0
- package/dist/resources/skills-rpc.d.ts +18 -0
- package/dist/resources/skills-rpc.js +91 -0
- package/dist/resources/spawn-runner.d.ts +41 -0
- package/dist/resources/spawn-runner.js +77 -0
- package/dist/resources/toggle-patterns.d.ts +70 -0
- package/dist/resources/toggle-patterns.js +61 -0
- package/dist/resources/wire.d.ts +17 -0
- package/dist/resources/wire.js +54 -0
- package/package.json +4 -3
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds `{skills, packages}` exactly as Pi would load them, computed fresh on every call — no
|
|
3
|
+
* cache, no Pi-Studio-owned resource state (swe/architecture/pi-resource-management.md tenet 1,
|
|
4
|
+
* § List). Pure over its `BuildCatalogContext` input: every path it reads is either passed in or
|
|
5
|
+
* derived from Pi's own resolver output.
|
|
6
|
+
*/
|
|
7
|
+
/** `"agent_dir" | "agents_dir" | "package" | "settings_path"` — see § Behavior & algorithms
|
|
8
|
+
* "List" in the architecture doc. Kept as a literal union internally; the wire `skillInfoSchema`
|
|
9
|
+
* widens it to `z.string()` so a future Pi origin still parses on an older client. */
|
|
10
|
+
export type SkillOrigin = "agent_dir" | "agents_dir" | "package" | "settings_path";
|
|
11
|
+
export interface SkillProvenance {
|
|
12
|
+
source: string;
|
|
13
|
+
sourceUrl?: string;
|
|
14
|
+
installedAt?: string;
|
|
15
|
+
}
|
|
16
|
+
/** One resolved Agent Skill row. Matches `SkillInfo` (`packages/protocol`) field-for-field, plus
|
|
17
|
+
* `baseDir` — kept internally for the toggle task (task-004)'s pattern derivation
|
|
18
|
+
* (`toggle-patterns.ts`'s `topLevelPattern`/`packagePattern`), never sent on the wire. */
|
|
19
|
+
export interface CatalogSkill {
|
|
20
|
+
name: string;
|
|
21
|
+
description?: string;
|
|
22
|
+
path: string;
|
|
23
|
+
enabled: boolean;
|
|
24
|
+
origin: SkillOrigin;
|
|
25
|
+
originLabel: string;
|
|
26
|
+
packageSource?: string;
|
|
27
|
+
shadowedBy?: string;
|
|
28
|
+
symlinkTarget?: string;
|
|
29
|
+
provenance?: SkillProvenance;
|
|
30
|
+
disableModelInvocation?: boolean;
|
|
31
|
+
warnings?: string[];
|
|
32
|
+
removable: boolean;
|
|
33
|
+
/** Internal only: the pattern base for a future toggle (`relative(baseDir, path)`), never
|
|
34
|
+
* `agentDir` itself when the resource's own origin provides a more specific one. */
|
|
35
|
+
baseDir: string;
|
|
36
|
+
}
|
|
37
|
+
/** One `settings.json` `packages[]` entry resolved against disk. Matches `PiPackageInfo`
|
|
38
|
+
* field-for-field. */
|
|
39
|
+
export interface CatalogPackage {
|
|
40
|
+
source: string;
|
|
41
|
+
kind: "npm" | "git" | "local";
|
|
42
|
+
identity: string;
|
|
43
|
+
pinned: boolean;
|
|
44
|
+
curated: boolean;
|
|
45
|
+
filtered: boolean;
|
|
46
|
+
skillCount: number;
|
|
47
|
+
}
|
|
48
|
+
export interface BuildCatalogContext {
|
|
49
|
+
/** `effectivePiHomeKey(config)` — `<agentDir>/settings.json`, `<agentDir>/skills`. */
|
|
50
|
+
agentDir: string;
|
|
51
|
+
/** `$HOME` — `~/.agents/skills` is resolved from this, not from `agentDir`
|
|
52
|
+
* (`package-manager.js:83,2023`; architecture doc § Ground truth). Also `SettingsManager`'s
|
|
53
|
+
* `cwd` (project-scope settings are not consulted by this sprint's slice but `SettingsManager`
|
|
54
|
+
* still needs a `cwd` to construct). */
|
|
55
|
+
home: string;
|
|
56
|
+
/** `$XDG_STATE_HOME/skills/.skill-lock.json` if set, else `~/.agents/.skill-lock.json` — the
|
|
57
|
+
* caller computes this (architecture doc § Behavior & algorithms `ctx()`), not this module. */
|
|
58
|
+
lockPath: string;
|
|
59
|
+
}
|
|
60
|
+
export type BuildCatalogResult = {
|
|
61
|
+
ok: true;
|
|
62
|
+
skills: CatalogSkill[];
|
|
63
|
+
packages: CatalogPackage[];
|
|
64
|
+
} | {
|
|
65
|
+
ok: false;
|
|
66
|
+
error: "settings_unreadable";
|
|
67
|
+
};
|
|
68
|
+
export declare function buildCatalog(ctx: BuildCatalogContext): Promise<BuildCatalogResult>;
|
|
69
|
+
//# sourceMappingURL=skill-catalog.d.ts.map
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname, resolve as resolvePathAbs } from "node:path";
|
|
4
|
+
import { CURATED_PACKS, parseSource as parseCuratedSource } from "../extensions/curated-packs.js";
|
|
5
|
+
import { loadSkillsFromDir, openPiResources } from "./pi-sdk.js";
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
// buildCatalog
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
export async function buildCatalog(ctx) {
|
|
10
|
+
const settingsPath = resolvePathAbs(ctx.agentDir, "settings.json");
|
|
11
|
+
if (existsSync(settingsPath)) {
|
|
12
|
+
try {
|
|
13
|
+
JSON.parse(await readFile(settingsPath, "utf8"));
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return { ok: false, error: "settings_unreadable" };
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const { packages } = await openPiResources(ctx.agentDir, ctx.home);
|
|
20
|
+
const resolved = await packages.resolve(async () => "skip");
|
|
21
|
+
const userSkills = resolved.skills.filter((r) => r.metadata.scope === "user");
|
|
22
|
+
const lock = await readLock(ctx.lockPath);
|
|
23
|
+
// Per-path frontmatter/warnings via `loadSkillsFromDir`, cached per scan root (the directory
|
|
24
|
+
// containing the SKILL.md, or the shared skills root for a loose `.md` sibling) so two resolved
|
|
25
|
+
// paths under the same root share one scan.
|
|
26
|
+
const scanCache = new Map();
|
|
27
|
+
function scan(dir) {
|
|
28
|
+
let result = scanCache.get(dir);
|
|
29
|
+
if (!result) {
|
|
30
|
+
result = loadSkillsFromDir({ dir, source: "catalog" });
|
|
31
|
+
scanCache.set(dir, result);
|
|
32
|
+
}
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
const rows = [];
|
|
36
|
+
for (const r of userSkills) {
|
|
37
|
+
const skillDir = dirname(r.path);
|
|
38
|
+
const { skills: scanned, diagnostics } = scan(skillDir);
|
|
39
|
+
const match = scanned.find((s) => resolvePathAbs(s.filePath) === resolvePathAbs(r.path));
|
|
40
|
+
const warnings = diagnostics
|
|
41
|
+
.filter((d) => d.type === "warning" && d.path && resolvePathAbs(d.path) === resolvePathAbs(r.path))
|
|
42
|
+
.map((d) => d.message);
|
|
43
|
+
const origin = classifyOrigin(r.metadata, ctx.agentDir);
|
|
44
|
+
const originLabel = originLabelFor(origin, r.metadata.source);
|
|
45
|
+
const baseDir = r.metadata.baseDir ?? ctx.agentDir;
|
|
46
|
+
let symlinkTarget;
|
|
47
|
+
try {
|
|
48
|
+
const st = await lstat(skillDir);
|
|
49
|
+
if (st.isSymbolicLink())
|
|
50
|
+
symlinkTarget = await realpath(skillDir);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// Directory vanished between resolve() and here, or isn't readable — no symlink to report.
|
|
54
|
+
}
|
|
55
|
+
const name = match?.name ?? basename(skillDir);
|
|
56
|
+
let provenance;
|
|
57
|
+
if (origin === "agents_dir") {
|
|
58
|
+
const entry = lock[name];
|
|
59
|
+
if (entry)
|
|
60
|
+
provenance = entry;
|
|
61
|
+
}
|
|
62
|
+
rows.push({
|
|
63
|
+
name,
|
|
64
|
+
description: match?.description,
|
|
65
|
+
path: r.path,
|
|
66
|
+
enabled: r.enabled,
|
|
67
|
+
origin,
|
|
68
|
+
originLabel,
|
|
69
|
+
packageSource: origin === "package" ? r.metadata.source : undefined,
|
|
70
|
+
symlinkTarget,
|
|
71
|
+
provenance,
|
|
72
|
+
disableModelInvocation: match?.disableModelInvocation,
|
|
73
|
+
warnings: warnings.length > 0 ? warnings : undefined,
|
|
74
|
+
removable: origin !== "package",
|
|
75
|
+
baseDir,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
// Shadowing: first-wins by name over ENABLED rows only, in `resolve()`'s own precedence order
|
|
79
|
+
// (`userSkills` is already sorted project-first/local-before-auto-before-package by
|
|
80
|
+
// `resourcePrecedenceRank`, stable-sorted within equal ranks — agent_dir before agents_dir on a
|
|
81
|
+
// name collision, matching Pi's own first-wins semantics, D19). A disabled duplicate never wins
|
|
82
|
+
// or shadows: it is simply excluded from this pass.
|
|
83
|
+
const winnerPathByName = new Map();
|
|
84
|
+
for (const row of rows) {
|
|
85
|
+
if (!row.enabled)
|
|
86
|
+
continue;
|
|
87
|
+
const winnerPath = winnerPathByName.get(row.name);
|
|
88
|
+
if (winnerPath === undefined) {
|
|
89
|
+
winnerPathByName.set(row.name, row.path);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
row.shadowedBy = winnerPath;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const packagesList = buildPackages(packages.listConfiguredPackages(), userSkills);
|
|
96
|
+
return { ok: true, skills: rows, packages: packagesList };
|
|
97
|
+
}
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
// Origin classification
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
function classifyOrigin(metadata, agentDir) {
|
|
102
|
+
if (metadata.origin === "package")
|
|
103
|
+
return "package";
|
|
104
|
+
// Explicit `settings.skills` plain-path entries are tagged `source: "local"`
|
|
105
|
+
// (`resolveLocalEntries`); auto-discovered directories are tagged `source: "auto"`
|
|
106
|
+
// (`addAutoDiscoveredResources`) and distinguished from each other by `baseDir`:
|
|
107
|
+
// `<agentDir>` for `<agentDir>/skills`, `~/.agents` (from `$HOME`) for `~/.agents/skills`.
|
|
108
|
+
if (metadata.source === "local")
|
|
109
|
+
return "settings_path";
|
|
110
|
+
return metadata.baseDir !== undefined &&
|
|
111
|
+
resolvePathAbs(metadata.baseDir) === resolvePathAbs(agentDir)
|
|
112
|
+
? "agent_dir"
|
|
113
|
+
: "agents_dir";
|
|
114
|
+
}
|
|
115
|
+
function originLabelFor(origin, packageSource) {
|
|
116
|
+
switch (origin) {
|
|
117
|
+
case "agent_dir":
|
|
118
|
+
return "Pi skills";
|
|
119
|
+
case "agents_dir":
|
|
120
|
+
return "Agent Skills";
|
|
121
|
+
case "settings_path":
|
|
122
|
+
return "Skill paths";
|
|
123
|
+
case "package":
|
|
124
|
+
return packageSource;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
128
|
+
// Lock file (`~/.agents/.skill-lock.json`, v3)
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
async function readLock(lockPath) {
|
|
131
|
+
if (!existsSync(lockPath))
|
|
132
|
+
return {};
|
|
133
|
+
try {
|
|
134
|
+
const raw = JSON.parse(await readFile(lockPath, "utf8"));
|
|
135
|
+
if (raw === null ||
|
|
136
|
+
typeof raw !== "object" ||
|
|
137
|
+
raw.version !== 3 ||
|
|
138
|
+
typeof raw.skills !== "object") {
|
|
139
|
+
// Pre-v3 (or malformed) lock file: rows load without provenance; the `skills` CLI rewrites
|
|
140
|
+
// the file to v3 on its next write (architecture doc § Error handling & edge cases).
|
|
141
|
+
return {};
|
|
142
|
+
}
|
|
143
|
+
const out = {};
|
|
144
|
+
const entries = raw.skills;
|
|
145
|
+
for (const [name, value] of Object.entries(entries)) {
|
|
146
|
+
if (value === null || typeof value !== "object")
|
|
147
|
+
continue;
|
|
148
|
+
const entry = value;
|
|
149
|
+
if (typeof entry.source !== "string")
|
|
150
|
+
continue;
|
|
151
|
+
out[name] = {
|
|
152
|
+
source: entry.source,
|
|
153
|
+
sourceUrl: typeof entry.sourceUrl === "string" ? entry.sourceUrl : undefined,
|
|
154
|
+
installedAt: typeof entry.installedAt === "string" ? entry.installedAt : undefined,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return {};
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/** `npm:`/`git:` reuse `curated-packs.ts`'s own parser (Pi's dedup key, ref/version stripped);
|
|
164
|
+
* anything else is a local path, whose identity is the literal configured source string. */
|
|
165
|
+
function classifySource(source) {
|
|
166
|
+
if (source.startsWith("npm:") || source.startsWith("git:")) {
|
|
167
|
+
return parseCuratedSource(source);
|
|
168
|
+
}
|
|
169
|
+
return { kind: "local", identity: source, pinned: false };
|
|
170
|
+
}
|
|
171
|
+
const CURATED_IDENTITIES = new Set(Object.values(CURATED_PACKS).flatMap((pack) => pack.packages.map((entry) => classifySource(entry.source).identity)));
|
|
172
|
+
function buildPackages(configured, userSkills) {
|
|
173
|
+
const skillCountByIdentity = new Map();
|
|
174
|
+
for (const r of userSkills) {
|
|
175
|
+
if (r.metadata.origin !== "package")
|
|
176
|
+
continue;
|
|
177
|
+
const identity = classifySource(r.metadata.source).identity;
|
|
178
|
+
skillCountByIdentity.set(identity, (skillCountByIdentity.get(identity) ?? 0) + 1);
|
|
179
|
+
}
|
|
180
|
+
return configured
|
|
181
|
+
.filter((entry) => entry.scope === "user")
|
|
182
|
+
.map((entry) => {
|
|
183
|
+
const classified = classifySource(entry.source);
|
|
184
|
+
return {
|
|
185
|
+
source: entry.source,
|
|
186
|
+
kind: classified.kind,
|
|
187
|
+
identity: classified.identity,
|
|
188
|
+
pinned: classified.pinned,
|
|
189
|
+
curated: CURATED_IDENTITIES.has(classified.identity),
|
|
190
|
+
filtered: entry.filtered,
|
|
191
|
+
skillCount: skillCountByIdentity.get(classified.identity) ?? 0,
|
|
192
|
+
};
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
//# sourceMappingURL=skill-catalog.js.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve the `skills` CLI bundled as a pinned `packages/server` dependency. Returns `null` if the
|
|
3
|
+
* package isn't present (should never happen once installed — `skills` is a hard dependency, not
|
|
4
|
+
* optional, unlike the bundled `pi` CLI).
|
|
5
|
+
*/
|
|
6
|
+
export declare function resolveSkillsCli(): string | null;
|
|
7
|
+
export type SkillsOp = "add" | "remove" | "update";
|
|
8
|
+
/**
|
|
9
|
+
* Build the argv (minus `[node, cli]`) for one `skills` operation.
|
|
10
|
+
*
|
|
11
|
+
* - `add`: `<src> -g -a pi -y -s <names…>` — universal agent `pi`, non-interactive, picked names.
|
|
12
|
+
* The source MUST precede `-s`: `-s` is variadic and swallows a trailing source, so the CLI
|
|
13
|
+
* fails with "Missing required argument: source" (found live in sprint-076/task-008).
|
|
14
|
+
* - `remove`: `-g -y <name>` — **never `-a`**: passing `-a pi` to `remove` keeps the canonical copy
|
|
15
|
+
* if any other detected agent still links it, which would leave Pi-Studio's own remove silently
|
|
16
|
+
* no-op the deletion it promised.
|
|
17
|
+
* - `update`: `-g -y` — reinstalls every outdated global skill.
|
|
18
|
+
*/
|
|
19
|
+
export declare function skillsArgv(op: "add", src: string, names: string[]): string[];
|
|
20
|
+
export declare function skillsArgv(op: "remove", name: string): string[];
|
|
21
|
+
export declare function skillsArgv(op: "update"): string[];
|
|
22
|
+
/**
|
|
23
|
+
* Spawn environment for a `skills` CLI invocation. `cloneTimeoutMs` must stay below the caller's
|
|
24
|
+
* own item timeout (600 s for install/remove, 1 300 s for update_all) so the CLI's own clone
|
|
25
|
+
* deadline fires before the daemon's spawn-kill does, surfacing a useful `stderr` tail instead of
|
|
26
|
+
* a bare `timeout`.
|
|
27
|
+
*/
|
|
28
|
+
export declare function spawnEnv(agentDir: string, cloneTimeoutMs?: number): Record<string, string>;
|
|
29
|
+
/**
|
|
30
|
+
* Mirror of the `skills` CLI's own `sanitizeName` (`dist/cli.mjs`): the canonical on-disk
|
|
31
|
+
* directory name under `~/.agents/skills/` for a skill, derived from its frontmatter `name`. Used
|
|
32
|
+
* both by preview's `exists` flag (task-003) and install's post-spawn existence check / pre-spawn
|
|
33
|
+
* `name_exists` detection for `skills_repo` picks (task-005) — never by `remove`, which resolves
|
|
34
|
+
* the on-disk directory from the catalog's own resolved `path` instead.
|
|
35
|
+
*/
|
|
36
|
+
export declare function sanitizeSkillName(name: string): string;
|
|
37
|
+
//# sourceMappingURL=skills-cli.d.ts.map
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
/**
|
|
5
|
+
* Resolves the pinned `skills` CLI (sprint-076/task-002) and builds its argv/env for each
|
|
6
|
+
* operation (`add`, `remove`, `update`). Mirrors `resolveBundledPiCli()`
|
|
7
|
+
* (`agent/providers/pi/rpc-transport.ts`): the bin path is read from the dependency's own
|
|
8
|
+
* `package.json` `bin`, never hardcoded, so a future `skills` release that moves its entrypoint
|
|
9
|
+
* fails loudly instead of silently falling back to a stale path.
|
|
10
|
+
*
|
|
11
|
+
* `skills` 1.7.4 declares `bin: {skills: "./bin/cli.mjs", "add-skill": "./bin/cli.mjs"}` and no
|
|
12
|
+
* `exports`/`main` (spawn-only package — see swe/architecture/pi-resource-management.md § Ground
|
|
13
|
+
* truth). `skills` is the canonical bin name; `resolveSkillsCli()` prefers it, falling back to
|
|
14
|
+
* `add-skill` only if `skills` isn't declared.
|
|
15
|
+
*/
|
|
16
|
+
const PREFERRED_BIN_NAMES = ["skills", "add-skill"];
|
|
17
|
+
function resolveSkillsCliInPackage(root) {
|
|
18
|
+
try {
|
|
19
|
+
const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
20
|
+
if (typeof manifest.bin === "string") {
|
|
21
|
+
return join(root, manifest.bin);
|
|
22
|
+
}
|
|
23
|
+
if (manifest.bin && typeof manifest.bin === "object") {
|
|
24
|
+
for (const name of PREFERRED_BIN_NAMES) {
|
|
25
|
+
const declared = manifest.bin[name];
|
|
26
|
+
if (declared)
|
|
27
|
+
return join(root, declared);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
// Unreadable/malformed manifest — fall through to null.
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Resolve the `skills` CLI bundled as a pinned `packages/server` dependency. Returns `null` if the
|
|
38
|
+
* package isn't present (should never happen once installed — `skills` is a hard dependency, not
|
|
39
|
+
* optional, unlike the bundled `pi` CLI).
|
|
40
|
+
*/
|
|
41
|
+
export function resolveSkillsCli() {
|
|
42
|
+
// 1) ESM resolution — works in the compiled daemon (real `node` ESM).
|
|
43
|
+
try {
|
|
44
|
+
const manifestPath = fileURLToPath(import.meta.resolve("skills/package.json"));
|
|
45
|
+
const cli = resolveSkillsCliInPackage(dirname(manifestPath));
|
|
46
|
+
if (cli)
|
|
47
|
+
return cli;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// `import.meta.resolve` may be unavailable under some loaders (e.g. vitest); fall through.
|
|
51
|
+
}
|
|
52
|
+
// 2) Walk up from cwd looking for the dependency in node_modules (loader-independent).
|
|
53
|
+
const rel = join("node_modules", "skills");
|
|
54
|
+
let dir = process.cwd();
|
|
55
|
+
for (;;) {
|
|
56
|
+
const cli = resolveSkillsCliInPackage(join(dir, rel));
|
|
57
|
+
if (cli)
|
|
58
|
+
return cli;
|
|
59
|
+
const parent = dirname(dir);
|
|
60
|
+
if (parent === dir)
|
|
61
|
+
return null;
|
|
62
|
+
dir = parent;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
export function skillsArgv(op, a, b) {
|
|
66
|
+
switch (op) {
|
|
67
|
+
case "add": {
|
|
68
|
+
const src = a;
|
|
69
|
+
const names = b;
|
|
70
|
+
return ["add", src, "-g", "-a", "pi", "-y", "-s", ...names];
|
|
71
|
+
}
|
|
72
|
+
case "remove": {
|
|
73
|
+
const name = a;
|
|
74
|
+
return ["remove", "-g", "-y", name];
|
|
75
|
+
}
|
|
76
|
+
case "update":
|
|
77
|
+
return ["update", "-g", "-y"];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Default clone timeout the `skills` CLI itself uses (`SKILLS_CLONE_TIMEOUT_MS`, 300 000 ms). */
|
|
81
|
+
const DEFAULT_SKILLS_CLONE_TIMEOUT_MS = 300_000;
|
|
82
|
+
/**
|
|
83
|
+
* Spawn environment for a `skills` CLI invocation. `cloneTimeoutMs` must stay below the caller's
|
|
84
|
+
* own item timeout (600 s for install/remove, 1 300 s for update_all) so the CLI's own clone
|
|
85
|
+
* deadline fires before the daemon's spawn-kill does, surfacing a useful `stderr` tail instead of
|
|
86
|
+
* a bare `timeout`.
|
|
87
|
+
*/
|
|
88
|
+
export function spawnEnv(agentDir, cloneTimeoutMs = DEFAULT_SKILLS_CLONE_TIMEOUT_MS) {
|
|
89
|
+
return {
|
|
90
|
+
PI_CODING_AGENT_DIR: agentDir,
|
|
91
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
92
|
+
GIT_SSH_COMMAND: "ssh -o BatchMode=yes",
|
|
93
|
+
npm_config_yes: "true",
|
|
94
|
+
DISABLE_TELEMETRY: "1",
|
|
95
|
+
DO_NOT_TRACK: "1",
|
|
96
|
+
SKILLS_CLONE_TIMEOUT_MS: String(cloneTimeoutMs),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Mirror of the `skills` CLI's own `sanitizeName` (`dist/cli.mjs`): the canonical on-disk
|
|
101
|
+
* directory name under `~/.agents/skills/` for a skill, derived from its frontmatter `name`. Used
|
|
102
|
+
* both by preview's `exists` flag (task-003) and install's post-spawn existence check / pre-spawn
|
|
103
|
+
* `name_exists` detection for `skills_repo` picks (task-005) — never by `remove`, which resolves
|
|
104
|
+
* the on-disk directory from the catalog's own resolved `path` instead.
|
|
105
|
+
*/
|
|
106
|
+
export function sanitizeSkillName(name) {
|
|
107
|
+
return (name
|
|
108
|
+
.toLowerCase()
|
|
109
|
+
.replace(/[^a-z0-9._]+/g, "-")
|
|
110
|
+
.replace(/^[.-]+|[.-]+$/g, "")
|
|
111
|
+
.slice(0, 255) || "unnamed-skill");
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=skills-cli.js.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Logger } from "../logging/logger.js";
|
|
2
|
+
import type { HandlerRegistry } from "../ws/router.js";
|
|
3
|
+
import type { ResourceService } from "./resource-service.js";
|
|
4
|
+
/**
|
|
5
|
+
* `skills_list_request`/`skills_set_enabled_request`/`skills_remove_request`/
|
|
6
|
+
* `skills_update_all_request`/`skills_preview_request`/`skills_install_request`
|
|
7
|
+
* (swe/architecture/pi-resource-management.md § Wire family `skills_*`). Thin orchestration only —
|
|
8
|
+
* every decision (catalog resolution, toggle pattern derivation, remove strategy, source
|
|
9
|
+
* detection, spawn/queue/watcher/broadcast) already lives behind `ResourceService`; this module
|
|
10
|
+
* maps its results onto the wire response shape and validates the requests this family's
|
|
11
|
+
* untyped `ctx.message` can't guarantee the shape of.
|
|
12
|
+
*/
|
|
13
|
+
export interface SkillsRpcDeps {
|
|
14
|
+
service: ResourceService;
|
|
15
|
+
logger?: Logger;
|
|
16
|
+
}
|
|
17
|
+
export declare function registerSkillsHandlers(registry: HandlerRegistry, deps: SkillsRpcDeps): void;
|
|
18
|
+
//# sourceMappingURL=skills-rpc.d.ts.map
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
export function registerSkillsHandlers(registry, deps) {
|
|
2
|
+
const { service, logger } = deps;
|
|
3
|
+
registry.register("skills_list_request", async () => {
|
|
4
|
+
const result = await service.list();
|
|
5
|
+
return { type: "skills_list_response", ...result };
|
|
6
|
+
});
|
|
7
|
+
registry.register("skills_set_enabled_request", async (ctx) => {
|
|
8
|
+
const { path, enabled } = ctx.message;
|
|
9
|
+
// `ctx.message` is an unvalidated `Record<string, unknown>` (`ws/router.ts`), so the
|
|
10
|
+
// handler must check `path`/`enabled`'s shape itself rather than trust the wire schema a
|
|
11
|
+
// conforming client used — same posture as `extensions-rpc.ts`'s `isSlugArray`. Only a
|
|
12
|
+
// client bypassing the protocol schema (`path: z.string()`, `enabled: z.boolean()`, both
|
|
13
|
+
// required) can reach this branch.
|
|
14
|
+
if (typeof path !== "string" || typeof enabled !== "boolean") {
|
|
15
|
+
logger?.warn({ message: ctx.message }, "skills_set_enabled_request: rejecting malformed request");
|
|
16
|
+
const result = await service.list();
|
|
17
|
+
return {
|
|
18
|
+
type: "skills_set_enabled_response",
|
|
19
|
+
...result,
|
|
20
|
+
ok: false,
|
|
21
|
+
error: "invalid request: expected a string path and boolean enabled",
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
const result = await service.setEnabled(path, enabled);
|
|
25
|
+
return { type: "skills_set_enabled_response", ...result };
|
|
26
|
+
});
|
|
27
|
+
registry.register("skills_remove_request", async (ctx) => {
|
|
28
|
+
const { path, packageSource } = ctx.message;
|
|
29
|
+
// Same posture as `skills_set_enabled_request` above: `ctx.message` is unvalidated, so the
|
|
30
|
+
// handler re-checks the wire schema's xor (`path` XOR `packageSource`, both strings) itself.
|
|
31
|
+
// Only a client bypassing `skillsRemoveRequestSchema` can reach this branch.
|
|
32
|
+
const hasPath = typeof path === "string";
|
|
33
|
+
const hasPackageSource = typeof packageSource === "string";
|
|
34
|
+
if (hasPath === hasPackageSource) {
|
|
35
|
+
logger?.warn({ message: ctx.message }, "skills_remove_request: rejecting malformed request");
|
|
36
|
+
const result = await service.list();
|
|
37
|
+
return {
|
|
38
|
+
type: "skills_remove_response",
|
|
39
|
+
...result,
|
|
40
|
+
ok: false,
|
|
41
|
+
error: "invalid request: expected exactly one of a string path or packageSource",
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const result = hasPath
|
|
45
|
+
? await service.remove({ path })
|
|
46
|
+
: await service.remove({ packageSource: packageSource });
|
|
47
|
+
return { type: "skills_remove_response", ...result };
|
|
48
|
+
});
|
|
49
|
+
registry.register("skills_update_all_request", async () => {
|
|
50
|
+
const result = await service.updateAll();
|
|
51
|
+
return { type: "skills_update_all_response", ...result };
|
|
52
|
+
});
|
|
53
|
+
registry.register("skills_preview_request", async (ctx) => {
|
|
54
|
+
const { source } = ctx.message;
|
|
55
|
+
if (typeof source !== "string") {
|
|
56
|
+
logger?.warn({ message: ctx.message }, "skills_preview_request: rejecting malformed request");
|
|
57
|
+
return {
|
|
58
|
+
type: "skills_preview_response",
|
|
59
|
+
ok: false,
|
|
60
|
+
error: "invalid request: expected a string source",
|
|
61
|
+
kind: "invalid_source",
|
|
62
|
+
source: typeof source === "string" ? source : "",
|
|
63
|
+
skills: [],
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const result = await service.preview(source);
|
|
67
|
+
return { type: "skills_preview_response", ...result };
|
|
68
|
+
});
|
|
69
|
+
registry.register("skills_install_request", async (ctx) => {
|
|
70
|
+
const { source, skills, replace } = ctx.message;
|
|
71
|
+
const hasSkills = skills === undefined || Array.isArray(skills);
|
|
72
|
+
if (typeof source !== "string" ||
|
|
73
|
+
!hasSkills ||
|
|
74
|
+
(Array.isArray(skills) && !skills.every((s) => typeof s === "string")) ||
|
|
75
|
+
(replace !== undefined && typeof replace !== "boolean")) {
|
|
76
|
+
logger?.warn({ message: ctx.message }, "skills_install_request: rejecting malformed request");
|
|
77
|
+
const listed = await service.list();
|
|
78
|
+
return {
|
|
79
|
+
type: "skills_install_response",
|
|
80
|
+
ok: false,
|
|
81
|
+
error: "invalid request: expected a string source and optional skills[]/replace",
|
|
82
|
+
results: [],
|
|
83
|
+
skills: listed.skills,
|
|
84
|
+
packages: listed.packages,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
const result = await service.install(source, skills, replace);
|
|
88
|
+
return { type: "skills_install_response", ...result };
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
//# sourceMappingURL=skills-rpc.js.map
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { InstallSpawn } from "../extensions/sync-executor.js";
|
|
2
|
+
export interface SpawnOutcome {
|
|
3
|
+
ok: boolean;
|
|
4
|
+
/** Set only when the process never produced an exit code (`spawn_failed`) or was killed for
|
|
5
|
+
* running past `timeoutMs` (`timeout`). A plain nonzero exit leaves this `undefined` — callers
|
|
6
|
+
* map that case to their own domain reason (`install_failed`/`remove_failed`/`update_failed`). */
|
|
7
|
+
error?: "spawn_failed" | "timeout";
|
|
8
|
+
exitCode: number | null;
|
|
9
|
+
/** Bounded to `STDERR_TAIL_MAX` bytes and credential-redacted (redacted *before* truncation —
|
|
10
|
+
* truncating first could cut a credential mid-string and leave a partial, unredacted tail). */
|
|
11
|
+
stderr: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Runs `command` through the injected `InstallSpawn` seam, translating its result (or a thrown
|
|
15
|
+
* `spawn` error — e.g. ENOENT) into the `skills_*` error taxonomy. The seam itself owns the
|
|
16
|
+
* per-call timeout and process-tree kill (`sync-executor.ts`'s `defaultInstallSpawn`); this
|
|
17
|
+
* function only interprets the outcome.
|
|
18
|
+
*/
|
|
19
|
+
export declare function runSpawn(spawn: InstallSpawn, command: string[], env: Record<string, string>, timeoutMs: number, cwd?: string): Promise<SpawnOutcome>;
|
|
20
|
+
/**
|
|
21
|
+
* Extracts the human-readable failure block from a TUI-style CLI's stdout: strips ANSI escapes and
|
|
22
|
+
* spinner frames, keeps everything from the FIRST `■` marker on (the CLI ends with a generic `■ Canceled`), and drops the `│` gutter. Without
|
|
23
|
+
* a marker, returns the last few cleaned lines. Pure.
|
|
24
|
+
*/
|
|
25
|
+
export declare function cliFailureText(stdout: string): string;
|
|
26
|
+
/**
|
|
27
|
+
* Strips `user[:password]@` from URL-like substrings and masks `token`/`access_token` query
|
|
28
|
+
* values. Applied to logs, stderr tails, and every wire `source`/`sourceUrl`
|
|
29
|
+
* (architecture doc § Redaction & logging, D29). Pure.
|
|
30
|
+
*/
|
|
31
|
+
export declare function redactSource(source: string): string;
|
|
32
|
+
/**
|
|
33
|
+
* `process.env` with `undefined` entries dropped, so a spawn's `env` can be built as
|
|
34
|
+
* `{...processEnvSnapshot(), ...spawnEnv(agentDir)}` — the child still sees `PATH` etc. (needed to
|
|
35
|
+
* find `git`/`node`) while the skills-manager overrides win. Mirrors
|
|
36
|
+
* `extensions/sync-executor.ts`'s own unexported helper of the same name/shape; kept as an
|
|
37
|
+
* independent local copy since the two call sites don't share a module (same precedent as
|
|
38
|
+
* `STDERR_TAIL_MAX` above).
|
|
39
|
+
*/
|
|
40
|
+
export declare function processEnvSnapshot(): Record<string, string>;
|
|
41
|
+
//# sourceMappingURL=spawn-runner.d.ts.map
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared spawn seam for skills-manager mutations (install/remove/update_all — tasks 004/005/077),
|
|
3
|
+
* reusing `InstallSpawn`'s injectable child-process seam (`extensions/sync-executor.ts`) so tests
|
|
4
|
+
* fake the exact same shape `ExtensionsService`'s sync executor already does, plus the credential
|
|
5
|
+
* redaction every logged source/stderr tail and wire `source`/`sourceUrl` field goes through
|
|
6
|
+
* (swe/architecture/pi-resource-management.md § Spawn environment, § Redaction & logging, D29).
|
|
7
|
+
*/
|
|
8
|
+
/** stderr tail bound shared with `sync-executor.ts`'s own (unexported) `STDERR_TAIL_MAX` — kept
|
|
9
|
+
* as an independent local constant since the two call sites don't share a module. */
|
|
10
|
+
const STDERR_TAIL_MAX = 2048;
|
|
11
|
+
/**
|
|
12
|
+
* Runs `command` through the injected `InstallSpawn` seam, translating its result (or a thrown
|
|
13
|
+
* `spawn` error — e.g. ENOENT) into the `skills_*` error taxonomy. The seam itself owns the
|
|
14
|
+
* per-call timeout and process-tree kill (`sync-executor.ts`'s `defaultInstallSpawn`); this
|
|
15
|
+
* function only interprets the outcome.
|
|
16
|
+
*/
|
|
17
|
+
export async function runSpawn(spawn, command, env, timeoutMs, cwd) {
|
|
18
|
+
let result;
|
|
19
|
+
try {
|
|
20
|
+
result = await spawn({ command, env, timeoutMs, cwd });
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return { ok: false, error: "spawn_failed", exitCode: null, stderr: "" };
|
|
24
|
+
}
|
|
25
|
+
// The `skills` CLI prints its failures on stdout (stderr stays empty — verified live), so a
|
|
26
|
+
// failed run with no stderr falls back to the cleaned failure block of stdout.
|
|
27
|
+
const diagnostic = result.stderr.trim() === "" && result.exitCode !== 0
|
|
28
|
+
? cliFailureText(result.stdout ?? "")
|
|
29
|
+
: result.stderr;
|
|
30
|
+
const stderr = redactSource(diagnostic).slice(0, STDERR_TAIL_MAX);
|
|
31
|
+
if (result.timedOut)
|
|
32
|
+
return { ok: false, error: "timeout", exitCode: result.exitCode, stderr };
|
|
33
|
+
return { ok: result.exitCode === 0, exitCode: result.exitCode, stderr };
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Extracts the human-readable failure block from a TUI-style CLI's stdout: strips ANSI escapes and
|
|
37
|
+
* spinner frames, keeps everything from the FIRST `■` marker on (the CLI ends with a generic `■ Canceled`), and drops the `│` gutter. Without
|
|
38
|
+
* a marker, returns the last few cleaned lines. Pure.
|
|
39
|
+
*/
|
|
40
|
+
export function cliFailureText(stdout) {
|
|
41
|
+
const cleaned = stdout
|
|
42
|
+
// eslint-disable-next-line no-control-regex
|
|
43
|
+
.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, "")
|
|
44
|
+
.replace(/[◒◐◓◑]\s*[A-Za-z][^◒◐◓◑\n]*/g, "")
|
|
45
|
+
.split(/\r?\n/)
|
|
46
|
+
.map((line) => line.replace(/^│\s*/u, "").trimEnd())
|
|
47
|
+
.filter((line) => line.trim() !== "");
|
|
48
|
+
const marker = cleaned.findIndex((l) => l.startsWith("■"));
|
|
49
|
+
const lines = marker >= 0 ? cleaned.slice(marker) : cleaned.slice(-8);
|
|
50
|
+
return lines.map((l) => l.replace(/^■\s*/u, "")).join("\n");
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Strips `user[:password]@` from URL-like substrings and masks `token`/`access_token` query
|
|
54
|
+
* values. Applied to logs, stderr tails, and every wire `source`/`sourceUrl`
|
|
55
|
+
* (architecture doc § Redaction & logging, D29). Pure.
|
|
56
|
+
*/
|
|
57
|
+
export function redactSource(source) {
|
|
58
|
+
const withoutUserinfo = source.replace(/:\/\/[^@/\s]*@/g, "://");
|
|
59
|
+
return withoutUserinfo.replace(/([?&](?:access_)?token=)[^&\s]*/gi, "$1***");
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* `process.env` with `undefined` entries dropped, so a spawn's `env` can be built as
|
|
63
|
+
* `{...processEnvSnapshot(), ...spawnEnv(agentDir)}` — the child still sees `PATH` etc. (needed to
|
|
64
|
+
* find `git`/`node`) while the skills-manager overrides win. Mirrors
|
|
65
|
+
* `extensions/sync-executor.ts`'s own unexported helper of the same name/shape; kept as an
|
|
66
|
+
* independent local copy since the two call sites don't share a module (same precedent as
|
|
67
|
+
* `STDERR_TAIL_MAX` above).
|
|
68
|
+
*/
|
|
69
|
+
export function processEnvSnapshot() {
|
|
70
|
+
const env = {};
|
|
71
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
72
|
+
if (value !== undefined)
|
|
73
|
+
env[key] = value;
|
|
74
|
+
}
|
|
75
|
+
return env;
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=spawn-runner.js.map
|