@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.
@@ -0,0 +1,717 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { lstat, mkdir, mkdtemp, realpath, rm, unlink } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join, relative, resolve as resolvePathAbs, sep } from "node:path";
5
+ import { detectSkillSource, } from "@av-pi-studio/protocol";
6
+ import { resolveBundledPiCli } from "../agent/providers/pi/rpc-transport.js";
7
+ import { parseSource as parseCuratedSource } from "../extensions/curated-packs.js";
8
+ import { effectivePiHomeKey } from "../extensions/extensions-state.js";
9
+ import { defaultInstallSpawn } from "../extensions/sync-executor.js";
10
+ import { expandHome } from "../files/resolve-path.js";
11
+ import { createLimiter } from "../util/concurrency.js";
12
+ import { loadSkillsFromDir, openPiResources } from "./pi-sdk.js";
13
+ import { buildCatalog } from "./skill-catalog.js";
14
+ import { resolveSkillsCli, sanitizeSkillName, skillsArgv, spawnEnv } from "./skills-cli.js";
15
+ import { processEnvSnapshot, redactSource, runSpawn as runSpawnImpl, } from "./spawn-runner.js";
16
+ import { applyPackageToggle, packagePattern, replacePattern, topLevelPattern, } from "./toggle-patterns.js";
17
+ import { toPiPackageInfoList, toSkillInfoList } from "./wire.js";
18
+ /**
19
+ * `ResourceService`: list/toggle over Pi's skills + packages, the daemon-lifetime file watcher
20
+ * that notices an *external* edit to `settings.json`/the skill directories, and the FIFO queue +
21
+ * spawn/redaction/logging machinery shared by every mutating operation (`install`/`remove`/
22
+ * `update_all` — tasks 004/005/077; swe/architecture/pi-resource-management.md § Behavior &
23
+ * algorithms — "List"/"Toggle", § Queue, watcher, broadcast, § Spawn environment, § Redaction &
24
+ * logging). No cache (tenet 1): every call re-derives `ctx()` and re-resolves the catalog from
25
+ * disk.
26
+ *
27
+ * `list()`/`setEnabled()` bypass the FIFO install/remove/update-all queue entirely (D21) — Pi's
28
+ * own `proper-lockfile`-backed `SettingsManager` write serializes concurrent writers at the file
29
+ * level, so no in-process mutex is needed for these two operations.
30
+ */
31
+ const DEFAULT_EXTERNAL_DEBOUNCE_MS = 500;
32
+ /** Daemon-side bound for every `remove`/`update_all` spawn (architecture doc § Timeouts —
33
+ * "install, remove, update_all | 600 s per spawn"). */
34
+ const SPAWN_TIMEOUT_MS = 600_000;
35
+ /** Daemon-side bound for the preview `git clone` (architecture doc § Timeouts — "preview | 120 s"). */
36
+ const PREVIEW_CLONE_TIMEOUT_MS = 120_000;
37
+ /** `$XDG_STATE_HOME/skills/.skill-lock.json` if set, else `~/.agents/.skill-lock.json`
38
+ * (architecture doc § Behavior & algorithms `ctx()`, `skills` CLI 1.7.4 ground truth). */
39
+ function resolveLockPath(home) {
40
+ const xdgStateHome = process.env.XDG_STATE_HOME;
41
+ return xdgStateHome
42
+ ? join(xdgStateHome, "skills", ".skill-lock.json")
43
+ : join(home, ".agents", ".skill-lock.json");
44
+ }
45
+ function buildCtx(config) {
46
+ const home = homedir();
47
+ return {
48
+ agentDir: effectivePiHomeKey(config),
49
+ home,
50
+ agentsSkillsDir: join(home, ".agents", "skills"),
51
+ lockPath: resolveLockPath(home),
52
+ };
53
+ }
54
+ /** `npm:`/`git:` dedup key, ref/version stripped, mirroring `skill-catalog.ts`'s own (unexported)
55
+ * `classifySource` — `null` for anything `curated-packs.ts`'s `parseSource` rejects (a
56
+ * `local_path` settings entry sitting alongside a `pi_npm`/`pi_git` one), which never matches
57
+ * (task-004's `installPiPackage` only ever searches for an `npm:`/`git:` identity). */
58
+ function piPackageIdentity(source) {
59
+ try {
60
+ return parseCuratedSource(source).identity;
61
+ }
62
+ catch {
63
+ return null;
64
+ }
65
+ }
66
+ /** Derive a `git clone` URL (+ optional `--branch ref` / subpath) from a `skills_repo`-classified
67
+ * source (task-003 preview). Mirrors the relevant branches of the `skills` CLI's own
68
+ * `parseSource` (`dist/cli.mjs`) just enough to shallow-clone and locate the right subtree:
69
+ * - A GitHub/GitLab host URL's `/tree/<ref>/<path>` segment supplies both `ref` and `subpath`;
70
+ * without it, the bare repo URL is cloned at its default branch.
71
+ * - `owner/repo` (optionally `@<skill-name>` — a post-clone skill-name filter for `skills add`,
72
+ * not a git ref or subpath; preview deliberately ignores it and shows the whole repo) clones
73
+ * `https://github.com/<owner>/<repo>.git`.
74
+ * - Anything else (scp-like `git@host:…`, `ssh://…`, any `*.git`-suffixed URL) clones the
75
+ * normalized source verbatim. */
76
+ function parseSkillsRepoSource(normalized) {
77
+ if (/^https?:\/\//i.test(normalized)) {
78
+ try {
79
+ const url = new URL(normalized);
80
+ const segments = url.pathname.split("/").filter((s) => s.length > 0);
81
+ const [owner, rawRepo, marker, ref, ...subpathSegments] = segments;
82
+ if (owner && rawRepo) {
83
+ const repo = rawRepo.replace(/\.git$/, "");
84
+ const cloneUrl = `${url.protocol}//${url.host}/${owner}/${repo}.git`;
85
+ if (marker === "tree" && ref) {
86
+ return {
87
+ cloneUrl,
88
+ ref,
89
+ subpath: subpathSegments.length > 0 ? subpathSegments.join("/") : undefined,
90
+ };
91
+ }
92
+ return { cloneUrl };
93
+ }
94
+ }
95
+ catch {
96
+ // Malformed URL despite matching `GIT_HOST_URL_RE`/`GIT_SUFFIX_URL_RE` upstream — fall
97
+ // through to cloning the normalized string as-is below.
98
+ }
99
+ }
100
+ const ownerRepoMatch = /^([^/]+)\/([^/@]+)(?:@.+)?$/.exec(normalized);
101
+ if (ownerRepoMatch) {
102
+ const [, owner, rawRepo] = ownerRepoMatch;
103
+ return { cloneUrl: `https://github.com/${owner}/${(rawRepo ?? "").replace(/\.git$/, "")}.git` };
104
+ }
105
+ return { cloneUrl: normalized };
106
+ }
107
+ export class ResourceService {
108
+ config;
109
+ fileWatchService;
110
+ broadcastFn;
111
+ getActiveSessions;
112
+ logger;
113
+ externalDebounceMs;
114
+ spawnFn;
115
+ /** `$PI_STUDIO_HOME` — preview scratch root (task-003). */
116
+ studioHome;
117
+ /** FIFO for preview/install/remove/update_all (tasks 004/005/077) — separate from
118
+ * `ExtensionsService`'s own sync mutex; `list`/`setEnabled` bypass it entirely (D21,
119
+ * architecture doc § Queue, watcher, broadcast). */
120
+ queue = createLimiter(1);
121
+ watcherStarted = false;
122
+ externalTimer;
123
+ /** Timestamp (ms) until which an incoming fs event is attributed to this service's own last
124
+ * write, not an external edit — see {@link markOwnWrite} / {@link handleFsEvent}. */
125
+ ownWriteUntil = 0;
126
+ constructor(deps) {
127
+ this.config = deps.config;
128
+ this.fileWatchService = deps.fileWatchService;
129
+ this.broadcastFn = deps.broadcast;
130
+ this.getActiveSessions = deps.getActiveSessions;
131
+ this.logger = deps.logger;
132
+ this.externalDebounceMs = deps.externalDebounceMs ?? DEFAULT_EXTERNAL_DEBOUNCE_MS;
133
+ this.spawnFn = deps.spawn ?? defaultInstallSpawn;
134
+ this.studioHome =
135
+ deps.studioHome ?? process.env.PI_STUDIO_HOME ?? join(homedir(), ".pi-studio");
136
+ }
137
+ async list() {
138
+ const ctx = buildCtx(this.config);
139
+ this.ensureWatcher(ctx);
140
+ return this.loadResult(ctx);
141
+ }
142
+ /**
143
+ * `skills_preview_request` (architecture doc § Behavior & algorithms "Preview", task-003):
144
+ * stateless — `pi_npm`/`pi_git` answer `{kind, skills: []}` immediately (nothing to pick);
145
+ * `local_path` scans the host folder in place; `skills_repo` shallow-clones into a scratch dir
146
+ * under `<studioHome>/tmp/preview-*`, removed in `finally` regardless of outcome. Queued behind
147
+ * {@link queue} alongside install/remove/update_all (architecture doc § Queue, watcher,
148
+ * broadcast), but — unlike {@link enqueueMutation} — never writes to `settings.json`, so it
149
+ * skips `markOwnWrite`/re-list/broadcast entirely.
150
+ */
151
+ async preview(source) {
152
+ return this.queue(() => this.previewLocked(source));
153
+ }
154
+ async previewLocked(source) {
155
+ const ctx = buildCtx(this.config);
156
+ const detected = detectSkillSource(source);
157
+ if (!detected) {
158
+ return { ok: false, error: "invalid_source", kind: "invalid_source", source, skills: [] };
159
+ }
160
+ const { kind, normalized } = detected;
161
+ if (kind === "pi_npm" || kind === "pi_git") {
162
+ // Packages install as a unit (R3) — nothing to pick, so no scan is needed.
163
+ return { ok: true, kind, source, skills: [] };
164
+ }
165
+ if (kind === "local_path") {
166
+ const root = expandHome(normalized);
167
+ if (!existsSync(root) || !statSync(root).isDirectory()) {
168
+ return { ok: false, error: "invalid_source", kind, source, skills: [] };
169
+ }
170
+ return this.buildPreviewResult(ctx, kind, source, root);
171
+ }
172
+ return this.previewSkillsRepo(ctx, kind, source, normalized);
173
+ }
174
+ /** `skills_repo`: shallow clone into a scratch dir, scan it (honouring a `/tree/<ref>/<path>`
175
+ * subpath), then remove the scratch dir unconditionally. */
176
+ async previewSkillsRepo(ctx, kind, source, normalized) {
177
+ const { cloneUrl, ref, subpath } = parseSkillsRepoSource(normalized);
178
+ const tmpRoot = join(this.studioHome, "tmp");
179
+ await mkdir(tmpRoot, { recursive: true });
180
+ const scratch = await mkdtemp(join(tmpRoot, "preview-"));
181
+ try {
182
+ const cloneArgs = ["clone", "--depth", "1"];
183
+ if (ref)
184
+ cloneArgs.push("--branch", ref);
185
+ cloneArgs.push(cloneUrl, scratch);
186
+ const outcome = await this.runSpawn(["git", ...cloneArgs], { ...processEnvSnapshot(), ...spawnEnv(ctx.agentDir) }, PREVIEW_CLONE_TIMEOUT_MS);
187
+ if (!outcome.ok) {
188
+ return {
189
+ ok: false,
190
+ error: "preview_failed",
191
+ message: outcome.stderr || undefined,
192
+ kind,
193
+ source,
194
+ skills: [],
195
+ };
196
+ }
197
+ const root = subpath ? join(scratch, subpath) : scratch;
198
+ return this.buildPreviewResult(ctx, kind, source, root);
199
+ }
200
+ finally {
201
+ await rm(scratch, { recursive: true, force: true });
202
+ }
203
+ }
204
+ /** Scans `root` with Pi's own `loadSkillsFromDir`, turning both its loaded `Skill`s (always
205
+ * `valid: true` — the loader only returns an entry once description validation passes) and its
206
+ * description-less diagnostics (a `SKILL.md` that failed to load at all — `valid: false`) into
207
+ * one flat `PreviewSkill[]`, so an invalid skill still gets its own row instead of silently
208
+ * disappearing (task-003 acceptance #1). */
209
+ buildPreviewResult(ctx, kind, source, root) {
210
+ const { skills, diagnostics } = loadSkillsFromDir({ dir: root, source: "preview" });
211
+ const rows = [];
212
+ const coveredPaths = new Set(skills.map((s) => resolvePathAbs(s.filePath)));
213
+ for (const skill of skills) {
214
+ const warnings = diagnostics
215
+ .filter((d) => d.path !== undefined && resolvePathAbs(d.path) === resolvePathAbs(skill.filePath))
216
+ .map((d) => d.message);
217
+ rows.push({
218
+ name: skill.name,
219
+ description: skill.description,
220
+ relPath: relative(root, dirname(skill.filePath)).split(sep).join("/"),
221
+ warnings: warnings.length > 0 ? warnings : undefined,
222
+ valid: true,
223
+ exists: existsSync(join(ctx.agentsSkillsDir, sanitizeSkillName(skill.name), "SKILL.md")),
224
+ });
225
+ }
226
+ const seenInvalidPaths = new Set();
227
+ for (const d of diagnostics) {
228
+ if (d.path === undefined)
229
+ continue;
230
+ const abs = resolvePathAbs(d.path);
231
+ if (coveredPaths.has(abs) || seenInvalidPaths.has(abs))
232
+ continue;
233
+ seenInvalidPaths.add(abs);
234
+ const skillDir = dirname(abs);
235
+ const name = basename(skillDir);
236
+ const warnings = diagnostics
237
+ .filter((x) => x.path !== undefined && resolvePathAbs(x.path) === abs)
238
+ .map((x) => x.message);
239
+ rows.push({
240
+ name,
241
+ relPath: relative(root, skillDir).split(sep).join("/"),
242
+ warnings,
243
+ valid: false,
244
+ exists: existsSync(join(ctx.agentsSkillsDir, sanitizeSkillName(name), "SKILL.md")),
245
+ });
246
+ }
247
+ if (!rows.some((r) => r.valid)) {
248
+ return { ok: false, error: "no_valid_skills", kind, source, skills: rows };
249
+ }
250
+ return { ok: true, kind, source, skills: rows };
251
+ }
252
+ async setEnabled(path, enabled) {
253
+ const ctx = buildCtx(this.config);
254
+ this.ensureWatcher(ctx);
255
+ const catalog = await buildCatalog({
256
+ agentDir: ctx.agentDir,
257
+ home: ctx.home,
258
+ lockPath: ctx.lockPath,
259
+ });
260
+ if (!catalog.ok)
261
+ return { ok: false, error: catalog.error, skills: [], packages: [] };
262
+ const row = catalog.skills.find((s) => s.path === path);
263
+ if (!row) {
264
+ return {
265
+ ok: false,
266
+ error: "not_found",
267
+ skills: toSkillInfoList(catalog.skills),
268
+ packages: toPiPackageInfoList(catalog.packages),
269
+ };
270
+ }
271
+ const { settings } = await openPiResources(ctx.agentDir, ctx.home);
272
+ try {
273
+ if (row.origin === "package") {
274
+ if (row.packageSource === undefined) {
275
+ throw new Error("package row without packageSource");
276
+ }
277
+ const pattern = packagePattern(row.path, row.baseDir);
278
+ const updated = applyPackageToggle(settings.getPackages(), row.packageSource, pattern, enabled);
279
+ this.markOwnWrite();
280
+ settings.setPackages(updated);
281
+ }
282
+ else {
283
+ const pattern = topLevelPattern(row.path, row.baseDir, ctx.agentDir);
284
+ const updated = replacePattern(settings.getSkillPaths(), pattern, enabled);
285
+ this.markOwnWrite();
286
+ settings.setSkillPaths(updated);
287
+ }
288
+ }
289
+ catch (err) {
290
+ // The row was resolved moments ago from a live catalog scan; its package entry vanishing
291
+ // before the write (a concurrent `pi remove`/hand-edit) is a genuine race, not a client bug
292
+ // — surfaced as the same domain `not_found`, never an `rpc_error`.
293
+ this.logger?.warn({ err, path }, "skills_set_enabled_request: package entry vanished mid-toggle");
294
+ return {
295
+ ok: false,
296
+ error: "not_found",
297
+ skills: toSkillInfoList(catalog.skills),
298
+ packages: toPiPackageInfoList(catalog.packages),
299
+ };
300
+ }
301
+ await settings.flush();
302
+ this.broadcastChanged("mutation");
303
+ return this.loadResult(ctx);
304
+ }
305
+ /**
306
+ * `skills_install_request` (architecture doc § Behavior & algorithms "Install", tasks
307
+ * 004/005): dispatches on the daemon's own authoritative `detectSkillSource(source)` — a
308
+ * client-sent `kind` is never trusted. Queued behind {@link enqueueMutation} alongside
309
+ * remove/update_all; `markOwnWrite`/re-list/broadcast are handled there, not here.
310
+ */
311
+ async install(source, picked, replace) {
312
+ const detected = detectSkillSource(source);
313
+ const logKind = detected?.kind ?? "invalid_source";
314
+ return this.enqueueMutation("install", logKind, source, (ctx) => this.installSource(ctx, source, detected, picked, replace));
315
+ }
316
+ async installSource(ctx, source, detected, picked, replace) {
317
+ if (!detected) {
318
+ return { ok: false, results: [{ target: source, ok: false, error: "invalid_source" }] };
319
+ }
320
+ switch (detected.kind) {
321
+ case "pi_npm":
322
+ case "pi_git":
323
+ return this.installPiPackage(ctx, detected.normalized);
324
+ case "skills_repo":
325
+ return this.installSkillsRepo(ctx, detected.normalized, picked, replace);
326
+ case "local_path":
327
+ return this.installLocalPath(ctx, detected.normalized);
328
+ }
329
+ }
330
+ /** `pi_npm`/`pi_git` (task-004, R3/R8): spawn bundled `pi install <source>` as a unit, then one
331
+ * locked write upgrading the matched settings entry to skills-only object form
332
+ * (`extensions: [], prompts: [], themes: []`) — any pre-existing `skills` filter on that entry
333
+ * survives untouched (task-001 spike: `addSourceToSettings` only ever rewrites `source`). */
334
+ async installPiPackage(ctx, source) {
335
+ const cli = resolveBundledPiCli();
336
+ if (!cli) {
337
+ return { ok: false, results: [{ target: source, ok: false, error: "spawn_failed" }] };
338
+ }
339
+ const outcome = await this.runSpawn([process.execPath, cli, "install", source], { ...processEnvSnapshot(), ...spawnEnv(ctx.agentDir) }, SPAWN_TIMEOUT_MS);
340
+ if (!outcome.ok) {
341
+ return {
342
+ ok: false,
343
+ results: [
344
+ {
345
+ target: source,
346
+ ok: false,
347
+ error: outcome.error ?? "install_failed",
348
+ stderr: outcome.stderr,
349
+ },
350
+ ],
351
+ };
352
+ }
353
+ // The install itself succeeded (package fetched, bare `source` written); the filter write is
354
+ // a second, independent step — its own failure never rolls back the install (D25, no
355
+ // rollback): the package row simply shows `filtered: false` on the next list.
356
+ try {
357
+ const identity = piPackageIdentity(source);
358
+ const { settings } = await openPiResources(ctx.agentDir, ctx.home);
359
+ const packages = settings.getPackages();
360
+ const index = packages.findIndex((p) => piPackageIdentity(typeof p === "string" ? p : p.source) === identity);
361
+ if (index === -1)
362
+ throw new Error("installed package entry not found in settings");
363
+ const existing = packages[index];
364
+ const entry = typeof existing === "string" ? { source: existing } : { ...existing };
365
+ entry.extensions = [];
366
+ entry.prompts = [];
367
+ entry.themes = [];
368
+ const updated = [...packages];
369
+ updated[index] = entry;
370
+ this.markOwnWrite();
371
+ settings.setPackages(updated);
372
+ await settings.flush();
373
+ }
374
+ catch (err) {
375
+ this.logger?.warn({ err, source }, "skills_install: skills-only filter write failed");
376
+ return { ok: false, results: [{ target: source, ok: false, error: "install_failed" }] };
377
+ }
378
+ return { ok: true, results: [{ target: source, ok: true }] };
379
+ }
380
+ /** `skills_repo` (task-005): picked names already present under `agentsSkillsDir` without
381
+ * `replace` are excluded as `name_exists`, never spawned; the rest go through one `skills add
382
+ * <url> -g -a pi -y -s <picked…>` spawn, each name's own result decided by a post-spawn
383
+ * `<agentsSkillsDir>/<sanitized>/SKILL.md` existence check (D18's lock file is `skills`'s own
384
+ * bookkeeping, never hand-read here for the outcome). */
385
+ async installSkillsRepo(ctx, source, picked, replace) {
386
+ if (!picked || picked.length === 0) {
387
+ return { ok: false, results: [{ target: source, ok: false, error: "invalid_source" }] };
388
+ }
389
+ const toInstall = [];
390
+ const results = [];
391
+ for (const name of picked) {
392
+ const skillDir = join(ctx.agentsSkillsDir, sanitizeSkillName(name), "SKILL.md");
393
+ if (!replace && existsSync(skillDir)) {
394
+ results.push({ target: name, ok: false, error: "name_exists" });
395
+ }
396
+ else {
397
+ toInstall.push(name);
398
+ }
399
+ }
400
+ if (toInstall.length === 0) {
401
+ return { ok: results.every((r) => r.ok), results };
402
+ }
403
+ const cli = resolveSkillsCli();
404
+ if (!cli) {
405
+ for (const name of toInstall) {
406
+ results.push({ target: name, ok: false, error: "spawn_failed" });
407
+ }
408
+ return { ok: false, results };
409
+ }
410
+ const outcome = await this.runSpawn([process.execPath, cli, ...skillsArgv("add", source, toInstall)], { ...processEnvSnapshot(), ...spawnEnv(ctx.agentDir) }, SPAWN_TIMEOUT_MS);
411
+ for (const name of toInstall) {
412
+ const skillDir = join(ctx.agentsSkillsDir, sanitizeSkillName(name), "SKILL.md");
413
+ results.push(existsSync(skillDir)
414
+ ? { target: name, ok: true }
415
+ : {
416
+ target: name,
417
+ ok: false,
418
+ error: outcome.error ?? "install_failed",
419
+ stderr: outcome.stderr,
420
+ });
421
+ }
422
+ return { ok: results.every((r) => r.ok), results };
423
+ }
424
+ /** `local_path` (task-005): nothing copied — `settings.skills` gains one bare `<absPath>`
425
+ * entry, de-duplicated against any existing entry with the same stripped form (bare or
426
+ * `±`-prefixed).
427
+ *
428
+ * Deviation from the architecture doc's literal `"+" + absPath` pseudocode, found by code
429
+ * inspection of the installed `@earendil-works/pi-coding-agent` 1.4.0
430
+ * (`package-manager.js`'s `resolveLocalEntries`/`isPattern`/`applyPatterns`): a `±`-prefixed
431
+ * `settings.skills` entry is parsed as an *override pattern* that only flips the enabled state
432
+ * of a path already discovered via a *plain* (unprefixed) entry or auto-discovery — it is
433
+ * never itself scanned for resources. A `+<absPath>` entry with no matching plain entry
434
+ * resolves zero files. A bare entry, by contrast, goes through `resolveLocalEntries`'s `plain`
435
+ * branch (`collectFilesFromPaths`), which is exactly what the existing `remove`'s own
436
+ * `settings_path` handling above already assumes (a bare directory entry, e.g. the
437
+ * `removes a settings_path entry` test fixture). */
438
+ async installLocalPath(ctx, source) {
439
+ const absPath = expandHome(source);
440
+ if (!existsSync(absPath) || !statSync(absPath).isDirectory()) {
441
+ return { ok: false, results: [{ target: source, ok: false, error: "invalid_source" }] };
442
+ }
443
+ const { settings } = await openPiResources(ctx.agentDir, ctx.home);
444
+ const deduped = replacePattern(settings.getSkillPaths(), absPath, undefined);
445
+ deduped.push(absPath);
446
+ this.markOwnWrite();
447
+ settings.setSkillPaths(deduped);
448
+ await settings.flush();
449
+ return { ok: true, results: [{ target: absPath, ok: true }] };
450
+ }
451
+ /**
452
+ * `skills_remove_request` (architecture doc § Behavior & algorithms "Remove", D9/D20): removes
453
+ * one top-level skill the way its origin requires, or spawns `pi remove` for a whole package.
454
+ * Queued behind {@link enqueueMutation} alongside install/update_all — `markOwnWrite`/re-list/
455
+ * broadcast are handled there, not here.
456
+ */
457
+ async remove(target) {
458
+ if ("path" in target) {
459
+ const { path } = target;
460
+ return this.enqueueMutation("remove", "path", path, (ctx) => this.removeByPath(ctx, path));
461
+ }
462
+ const { packageSource } = target;
463
+ return this.enqueueMutation("remove", "package", packageSource, (ctx) => this.removePackage(ctx, packageSource));
464
+ }
465
+ /** `remove({path})` — settings-path entry, symlink, `skills`-CLI-tracked `agents_dir` skill, or
466
+ * a plain directory under `agent_dir`/`agents_dir` whose realpath must stay inside that origin
467
+ * root. Never follows symlinks; never deletes a package row's files (D9). */
468
+ async removeByPath(ctx, path) {
469
+ const catalog = await buildCatalog({
470
+ agentDir: ctx.agentDir,
471
+ home: ctx.home,
472
+ lockPath: ctx.lockPath,
473
+ });
474
+ if (!catalog.ok)
475
+ return { ok: false, error: catalog.error };
476
+ const row = catalog.skills.find((s) => s.path === path);
477
+ if (!row)
478
+ return { ok: false, error: "not_found" };
479
+ if (row.origin === "package")
480
+ return { ok: false, error: "not_removable" };
481
+ const { settings } = await openPiResources(ctx.agentDir, ctx.home);
482
+ const skillDir = dirname(row.path);
483
+ if (row.origin === "settings_path") {
484
+ // Drop every settings entry (any ± form) that provides this skill: the skill's own folder
485
+ // or file, or an ANCESTOR folder — `install`'s `local_path` registers the folder the user
486
+ // named, which may hold several skills (found live, sprint-077: matching only the skill's
487
+ // own dir was a silent `ok` no-op for a registered parent folder, and the skill stayed).
488
+ // Siblings from the same folder entry stop loading with it; files are untouched.
489
+ const entries = settings.getSkillPaths() ?? [];
490
+ const covering = entries.filter((entry) => {
491
+ const bare = /^[!+-]/.test(entry) ? entry.slice(1) : entry;
492
+ const abs = resolvePathAbs(ctx.agentDir, bare === "~" || bare.startsWith("~/") ? join(ctx.home, bare.slice(1)) : bare);
493
+ return abs === skillDir || abs === row.path || skillDir.startsWith(abs + sep);
494
+ });
495
+ if (covering.length === 0)
496
+ return { ok: false, error: "not_removable" };
497
+ settings.setSkillPaths(entries.filter((entry) => !covering.includes(entry)));
498
+ await settings.flush();
499
+ return { ok: true };
500
+ }
501
+ let isSymlink = false;
502
+ try {
503
+ isSymlink = (await lstat(skillDir)).isSymbolicLink();
504
+ }
505
+ catch {
506
+ // Vanished since the catalog scan — nothing to unlink/delete; still clean its toggle
507
+ // pattern below so a stale override doesn't linger.
508
+ }
509
+ if (isSymlink) {
510
+ // Unlinks the link itself — `fs.unlink` never follows a symlink, so the real target
511
+ // directory (e.g. a package install root) is left intact.
512
+ await unlink(skillDir);
513
+ }
514
+ else if (row.origin === "agents_dir" && row.provenance) {
515
+ const cli = resolveSkillsCli();
516
+ if (!cli)
517
+ return { ok: false, error: "spawn_failed" };
518
+ const outcome = await this.runSpawn([process.execPath, cli, ...skillsArgv("remove", row.name)], { ...processEnvSnapshot(), ...spawnEnv(ctx.agentDir) }, SPAWN_TIMEOUT_MS);
519
+ if (!outcome.ok) {
520
+ return { ok: false, error: outcome.error ?? "remove_failed", stderr: outcome.stderr };
521
+ }
522
+ }
523
+ else {
524
+ // A plain directory under `agent_dir`/`agents_dir` with no lock entry (hand-placed, never
525
+ // went through `skills add`). Its realpath must stay inside the origin root before
526
+ // deleting — a directory escaped via a parent symlink is refused untouched.
527
+ const originRoot = row.origin === "agent_dir" ? join(ctx.agentDir, "skills") : ctx.agentsSkillsDir;
528
+ let realDir;
529
+ let realRoot;
530
+ try {
531
+ [realDir, realRoot] = await Promise.all([realpath(skillDir), realpath(originRoot)]);
532
+ }
533
+ catch {
534
+ return { ok: false, error: "not_found" };
535
+ }
536
+ if (realDir !== realRoot && !realDir.startsWith(realRoot + sep)) {
537
+ return { ok: false, error: "not_removable" };
538
+ }
539
+ await rm(skillDir, { recursive: true, force: true });
540
+ }
541
+ const pattern = topLevelPattern(row.path, row.baseDir, ctx.agentDir);
542
+ settings.setSkillPaths(replacePattern(settings.getSkillPaths(), pattern, undefined));
543
+ await settings.flush();
544
+ return { ok: true };
545
+ }
546
+ /** `remove({packageSource})` — spawns bundled `pi remove <source>`; Pi owns deleting the
547
+ * package's install root and removing its `packages[]` entry. */
548
+ async removePackage(ctx, packageSource) {
549
+ const catalog = await buildCatalog({
550
+ agentDir: ctx.agentDir,
551
+ home: ctx.home,
552
+ lockPath: ctx.lockPath,
553
+ });
554
+ if (!catalog.ok)
555
+ return { ok: false, error: catalog.error };
556
+ // The wire only ever carries redacted sources (`wire.ts`), so the request is matched on its
557
+ // redacted form and the spawn gets the REAL entry from settings — never the client's string.
558
+ const requested = redactSource(packageSource);
559
+ const entry = catalog.packages.find((p) => redactSource(p.source) === requested);
560
+ if (!entry)
561
+ return { ok: false, error: "not_found" };
562
+ const cli = resolveBundledPiCli();
563
+ if (!cli)
564
+ return { ok: false, error: "spawn_failed" };
565
+ const outcome = await this.runSpawn([process.execPath, cli, "remove", entry.source], { ...processEnvSnapshot(), ...spawnEnv(ctx.agentDir) }, SPAWN_TIMEOUT_MS,
566
+ // `pi remove` resolves a local-path source against its cwd, while the catalog reports the
567
+ // entry as written in `<agentDir>/settings.json` (relative to agentDir) — match Pi's own
568
+ // base so a relative entry like `../../../pkg` is found. Found live in sprint-076/task-008.
569
+ ctx.agentDir);
570
+ if (!outcome.ok) {
571
+ return { ok: false, error: outcome.error ?? "remove_failed", stderr: outcome.stderr };
572
+ }
573
+ return { ok: true };
574
+ }
575
+ /**
576
+ * `skills_update_all_request` (architecture doc § Behavior & algorithms "Update all", R5): one
577
+ * queued operation spawning `skills update -g -y` then `pi update --extensions` in sequence —
578
+ * a failure in the first never skips the second; `ok` is true only when both succeed.
579
+ */
580
+ async updateAll() {
581
+ return this.enqueueMutation("update_all", "all", "", async (ctx) => {
582
+ const results = [
583
+ await this.updateAgentSkills(ctx),
584
+ await this.updatePiPackages(ctx),
585
+ ];
586
+ return { ok: results.every((r) => r.ok), results };
587
+ });
588
+ }
589
+ async updateAgentSkills(ctx) {
590
+ const cli = resolveSkillsCli();
591
+ if (!cli)
592
+ return { target: "agent-skills", ok: false, error: "spawn_failed" };
593
+ const outcome = await this.runSpawn([process.execPath, cli, ...skillsArgv("update")], { ...processEnvSnapshot(), ...spawnEnv(ctx.agentDir) }, SPAWN_TIMEOUT_MS);
594
+ return outcome.ok
595
+ ? { target: "agent-skills", ok: true }
596
+ : {
597
+ target: "agent-skills",
598
+ ok: false,
599
+ error: outcome.error ?? "update_failed",
600
+ stderr: outcome.stderr,
601
+ };
602
+ }
603
+ async updatePiPackages(ctx) {
604
+ const cli = resolveBundledPiCli();
605
+ if (!cli)
606
+ return { target: "pi-packages", ok: false, error: "spawn_failed" };
607
+ const outcome = await this.runSpawn([process.execPath, cli, "update", "--extensions"], { ...processEnvSnapshot(), ...spawnEnv(ctx.agentDir) }, SPAWN_TIMEOUT_MS);
608
+ return outcome.ok
609
+ ? { target: "pi-packages", ok: true }
610
+ : {
611
+ target: "pi-packages",
612
+ ok: false,
613
+ error: outcome.error ?? "update_failed",
614
+ stderr: outcome.stderr,
615
+ };
616
+ }
617
+ /** Runs `command` through the injected spawn seam, bounding and redacting its stderr tail
618
+ * (architecture doc § Spawn environment, § Redaction & logging). Shared by every queued
619
+ * mutation (install/remove/update_all — tasks 004/005/077); exposed as a method (rather than
620
+ * requiring every caller to thread `this.spawnFn` through) so operations only need `this`. */
621
+ async runSpawn(command, env, timeoutMs, cwd) {
622
+ return runSpawnImpl(this.spawnFn, command, env, timeoutMs, cwd);
623
+ }
624
+ /**
625
+ * FIFO-queues one mutating operation behind {@link queue}, then runs the tail every mutation
626
+ * shares: structured logging (`{op, kind, source, outcome, durationMs}`, warn with the redacted
627
+ * stderr tail on failure), re-list, and `skills_changed("mutation")` broadcast — always, so a
628
+ * failed spawn that still partially touched `settings.json` is reflected (architecture doc
629
+ * § Behavior & algorithms "Install", § Redaction & logging). `fn`'s own `ok`/`error` (the
630
+ * operation's outcome) wins over the re-list's, except when the re-list itself fails (e.g. a
631
+ * `settings.json` that became unreadable mid-operation), which then takes over as the surfaced
632
+ * error — `skills`/`packages` always come from the fresh re-list.
633
+ */
634
+ async enqueueMutation(op, kind, source, fn) {
635
+ return this.queue(async () => {
636
+ const ctx = buildCtx(this.config);
637
+ this.ensureWatcher(ctx);
638
+ const redactedSource = redactSource(source);
639
+ const start = Date.now();
640
+ const result = await fn(ctx);
641
+ const durationMs = Date.now() - start;
642
+ const outcome = result.ok ? "ok" : "failed";
643
+ this.logger?.info({ op, kind, source: redactedSource, outcome, durationMs }, `skills_${op}`);
644
+ if (!result.ok) {
645
+ this.logger?.warn({ op, kind, source: redactedSource, stderr: result.stderr }, `skills_${op} failed`);
646
+ }
647
+ this.markOwnWrite();
648
+ const listResult = await this.loadResult(ctx);
649
+ this.broadcastChanged("mutation");
650
+ return {
651
+ ...result,
652
+ skills: listResult.skills,
653
+ packages: listResult.packages,
654
+ ok: result.ok && listResult.ok,
655
+ error: result.ok ? (listResult.ok ? undefined : listResult.error) : result.error,
656
+ };
657
+ });
658
+ }
659
+ async loadResult(ctx) {
660
+ const catalog = await buildCatalog({
661
+ agentDir: ctx.agentDir,
662
+ home: ctx.home,
663
+ lockPath: ctx.lockPath,
664
+ });
665
+ if (!catalog.ok)
666
+ return { ok: false, error: catalog.error, skills: [], packages: [] };
667
+ return {
668
+ ok: true,
669
+ skills: toSkillInfoList(catalog.skills),
670
+ packages: toPiPackageInfoList(catalog.packages),
671
+ };
672
+ }
673
+ /** Started on the first `skills_*` RPC, lives for the daemon's lifetime (architecture doc
674
+ * § Queue, watcher, broadcast) — never torn down by this service itself. */
675
+ ensureWatcher(ctx) {
676
+ if (this.watcherStarted)
677
+ return;
678
+ this.watcherStarted = true;
679
+ const onFsEvent = () => this.handleFsEvent();
680
+ const watched = [
681
+ join(ctx.agentDir, "settings.json"),
682
+ join(ctx.agentDir, "skills"),
683
+ ctx.agentsSkillsDir,
684
+ ctx.lockPath,
685
+ ];
686
+ for (const path of watched)
687
+ this.fileWatchService.subscribe(path, onFsEvent);
688
+ }
689
+ /** Call immediately before the mutating `SettingsManager` setter so the fold window covers the
690
+ * resulting disk write and the watcher's own event latency (`FileWatchService`'s internal
691
+ * coalescing plus this service's own debounce below). */
692
+ markOwnWrite() {
693
+ this.ownWriteUntil = Date.now() + this.externalDebounceMs;
694
+ }
695
+ handleFsEvent() {
696
+ // Folded into the mutation's own broadcast — this event is (almost certainly) an echo of our
697
+ // own write, not a genuine external edit.
698
+ if (Date.now() < this.ownWriteUntil)
699
+ return;
700
+ // A queued mutation (install/remove/update_all) is in flight or about to run: any fs churn it
701
+ // causes folds into *its* own "mutation" broadcast once it completes (architecture doc
702
+ // § Queue, watcher, broadcast — "Events during a queued mutation fold into its own
703
+ // broadcast").
704
+ if (this.queue.activeCount > 0 || this.queue.pendingCount > 0)
705
+ return;
706
+ if (this.externalTimer)
707
+ return; // A burst inside the debounce window collapses to one push.
708
+ this.externalTimer = setTimeout(() => {
709
+ this.externalTimer = undefined;
710
+ this.broadcastChanged("external");
711
+ }, this.externalDebounceMs);
712
+ }
713
+ broadcastChanged(reason) {
714
+ this.broadcastFn(this.getActiveSessions(), { type: "skills_changed", reason });
715
+ }
716
+ }
717
+ //# sourceMappingURL=resource-service.js.map