@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.5

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.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1244 -2
  3. package/package.json +75 -4
  4. package/src/abortable.ts +43 -0
  5. package/src/agent-color.ts +161 -0
  6. package/src/agent-file-toggle.ts +297 -0
  7. package/src/agent-manager.ts +1874 -0
  8. package/src/agent-runner.ts +1552 -0
  9. package/src/agent-source-badge.ts +75 -0
  10. package/src/agent-types.ts +346 -0
  11. package/src/child-context.ts +15 -0
  12. package/src/clock.ts +25 -0
  13. package/src/completion-outbox.ts +125 -0
  14. package/src/context.ts +58 -0
  15. package/src/cross-extension-rpc.ts +221 -0
  16. package/src/custom-agents.ts +436 -0
  17. package/src/default-agents.ts +126 -0
  18. package/src/detached-results.ts +134 -0
  19. package/src/enabled-models.ts +180 -0
  20. package/src/enterprise-local.ts +66 -0
  21. package/src/env.ts +33 -0
  22. package/src/group-join.ts +148 -0
  23. package/src/index.ts +4423 -0
  24. package/src/invocation-config.ts +189 -0
  25. package/src/memory.ts +179 -0
  26. package/src/mention-clone.ts +195 -0
  27. package/src/mention.ts +141 -0
  28. package/src/model-call.ts +83 -0
  29. package/src/model-resolver.ts +266 -0
  30. package/src/model-scope.ts +70 -0
  31. package/src/nested-tools.ts +448 -0
  32. package/src/output-file.ts +164 -0
  33. package/src/package-resources.ts +624 -0
  34. package/src/prompts.ts +156 -0
  35. package/src/quota-admission.ts +99 -0
  36. package/src/schedule-store.ts +153 -0
  37. package/src/schedule.ts +446 -0
  38. package/src/settings.ts +728 -0
  39. package/src/skill-loader.ts +137 -0
  40. package/src/startup-error.ts +29 -0
  41. package/src/status-note.ts +90 -0
  42. package/src/structured-output.ts +130 -0
  43. package/src/types.ts +404 -0
  44. package/src/ui/agent-mention.ts +216 -0
  45. package/src/ui/agent-row.ts +235 -0
  46. package/src/ui/agent-widget.ts +692 -0
  47. package/src/ui/conversation-viewer.ts +832 -0
  48. package/src/ui/fleet-list.ts +675 -0
  49. package/src/ui/notification-view.ts +120 -0
  50. package/src/ui/schedule-menu.ts +105 -0
  51. package/src/ui/select-item.ts +45 -0
  52. package/src/ui/viewer-keys.ts +39 -0
  53. package/src/ui/workflow-card.ts +462 -0
  54. package/src/ui/workflow-dialog.ts +1115 -0
  55. package/src/ui/workflow-menu.ts +193 -0
  56. package/src/usage.ts +167 -0
  57. package/src/workflow/collisions.ts +123 -0
  58. package/src/workflow/entry.ts +47 -0
  59. package/src/workflow/host.ts +401 -0
  60. package/src/workflow/journal.ts +164 -0
  61. package/src/workflow/json-schema.ts +129 -0
  62. package/src/workflow/meta.ts +326 -0
  63. package/src/workflow/progress.ts +549 -0
  64. package/src/workflow/runtime.ts +1216 -0
  65. package/src/workflow/saved.ts +259 -0
  66. package/src/workflow/task.ts +302 -0
  67. package/src/workflow/tool-description.ts +200 -0
  68. package/src/workflow/worker-source.ts +781 -0
  69. package/src/worktree.ts +230 -0
  70. package/src/xml.ts +13 -0
@@ -0,0 +1,624 @@
1
+ /**
2
+ * package-resources.ts — Discover agent and workflow files that installed pi
3
+ * packages declare in their `package.json`.
4
+ *
5
+ * ## Why this exists
6
+ *
7
+ * Pi already ships four resource types inside packages — `extensions`, `skills`,
8
+ * `prompts`, `themes` — resolved from a `pi` manifest key or, when there is no
9
+ * `pi` key at all, from convention directories. Subagents are *our* concept, so
10
+ * pi knows nothing about them and a package author's only option was to copy
11
+ * `.md` files into `.pi/agents/` on every container start (#109).
12
+ *
13
+ * ## The contract
14
+ *
15
+ * Two-sided, deliberately:
16
+ *
17
+ * 1. The package author opts in by naming the paths in `package.json`.
18
+ * 2. The user opts in by running `pi install`, which is already the trust
19
+ * decision for that package — pi executes its `extensions/` and injects its
20
+ * `skills/` into the system prompt with no further prompt. A declared `.md`
21
+ * agent is strictly less privileged than either, so it rides the boundary
22
+ * the user already crossed rather than inventing a second one.
23
+ *
24
+ * There is deliberately **no convention-directory fallback**. Pi scans `skills/`
25
+ * only when a package has no `pi` key whatsoever; we never scan an undeclared
26
+ * `agents/`. A package that happens to carry an `agents/` folder for some other
27
+ * tool must not start contributing subagents to pi because it was installed for
28
+ * an unrelated reason.
29
+ *
30
+ * ## Which packages are visible
31
+ *
32
+ * Only what pi itself has configured — `settings.json -> packages[]`, global and
33
+ * project — read through pi's own `DefaultPackageManager.listConfiguredPackages()`.
34
+ * That call is synchronous, pure, and never installs anything; it also resolves
35
+ * npm / git / local install roots, pnpm global roots and legacy fallbacks, which
36
+ * is why it is worth borrowing rather than reimplementing.
37
+ *
38
+ * `node_modules` is never scanned. Being a transitive dependency of the user's
39
+ * project means nothing here — the same rule pi applies to itself.
40
+ *
41
+ * ## Accepted manifest spellings
42
+ *
43
+ * All four mean the same thing. The `pi-subagents` top-level key exists for
44
+ * cross-compatibility with `nicobailon/pi-subagents`, which reads the same two
45
+ * shapes, so a package author writes one manifest that works on either extension.
46
+ *
47
+ * "pi": { "subagents": { "agents": ["./agents"], "workflows": ["./flows"] } }
48
+ * "pi": { "subagents": ["./agents"] } // shorthand for { agents }
49
+ * "pi-subagents": { "agents": ["./agents"] }
50
+ * "pi-subagents": ["./agents"] // shorthand for { agents }
51
+ *
52
+ * Adding `pi.subagents` is safe for pi itself: its `readPiManifest` reads only
53
+ * `extensions`/`skills`/`prompts`/`themes` and ignores every other key.
54
+ */
55
+
56
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
57
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
58
+ import { DefaultPackageManager, getAgentDir, SettingsManager } from "@earendil-works/pi-coding-agent";
59
+
60
+ /** Resource kinds a package may declare. Agents are `.md`, workflows are `.js`. */
61
+ export type PackageResourceKind = "agents" | "workflows";
62
+
63
+ /** File extension scanned for each kind, mirroring the local roots for each. */
64
+ const KIND_EXTENSION: Record<PackageResourceKind, string> = {
65
+ agents: ".md",
66
+ workflows: ".js",
67
+ };
68
+
69
+ /**
70
+ * Per-file size ceiling for package-provided resources, matching Claude Code's
71
+ * plugin-agent limit. These files come from third-party packages and are read
72
+ * eagerly on every agent load; a pathological one should be skipped, not
73
+ * `readFileSync`'d into the session.
74
+ */
75
+ export const MAX_PACKAGE_RESOURCE_BYTES = 1_048_576;
76
+
77
+ /** One installed pi package that declared something we understand. */
78
+ export interface PiPackage {
79
+ /** The settings source string, e.g. `npm:@foo/bar@1.0.0` or an absolute path. */
80
+ source: string;
81
+ /** `package.json` `name`, when the manifest could be read. */
82
+ name?: string;
83
+ /** Unscoped, lowercased short name (`@scope/foo` becomes `foo`) for allowlist matching. */
84
+ shortName?: string;
85
+ /** Which settings scope configured it. */
86
+ scope: "user" | "project";
87
+ /** Absolute path of the installed package root. */
88
+ root: string;
89
+ /**
90
+ * What its manifest declared. Carried here rather than re-read downstream:
91
+ * `listPiPackages` has to parse the manifest anyway to know whether the
92
+ * package declares anything at all, and reading it twice would leave two
93
+ * places that could disagree about what a package said.
94
+ */
95
+ declared: DeclaredEntries;
96
+ }
97
+
98
+ /**
99
+ * The gate for one resource kind, as persisted in our settings:
100
+ * `true` (default) = every declaring package, `false` = none, `string[]` =
101
+ * only packages whose short name, full name, or source matches an entry.
102
+ */
103
+ export type PackageGate = boolean | string[] | undefined;
104
+
105
+ export interface PackageDiscoveryOptions {
106
+ /**
107
+ * Pi's project-trust state for `cwd`, from `ctx.isProjectTrusted()`. When
108
+ * false, `.pi/settings.json` is not read — so a package configured only by an
109
+ * untrusted project is invisible to us, exactly as it is to pi. Omitted falls
110
+ * back to the session state set by {@link setProjectTrusted}.
111
+ */
112
+ projectTrusted?: boolean;
113
+ /** Gate override. Omitted falls back to the session state for the kind. */
114
+ gate?: PackageGate;
115
+ }
116
+
117
+ // ---- Session state ----
118
+ //
119
+ // Held here rather than threaded through every caller, matching how the rest of
120
+ // this extension carries session-wide settings (`setMaxSubagentDepth`,
121
+ // `setWorktreeIsolationEnabled`, ...). The alternative was an options bag
122
+ // travelling from `index.ts` through `resolveWorkflowScript`,
123
+ // `resolveWorkflowSource`, `readSavedWorkflow` and `listSavedWorkflows` purely
124
+ // so a gate could be consulted at the bottom.
125
+ //
126
+ // Both gates start `undefined`, which reads as `true`: absent settings mean
127
+ // every declaring package contributes, matching pi's own default for the
128
+ // resources it owns.
129
+
130
+ let agentsGate: PackageGate;
131
+ let workflowsGate: PackageGate;
132
+ /**
133
+ * Defaults to `false` — an extension activates before any session context
134
+ * exists, and pi's persisted trust file is not a substitute for its canonical
135
+ * answer (project trust events and `--approve`/`--noapprove` override it). Only
136
+ * `ctx.isProjectTrusted()` on `session_start` raises it, via `setProjectTrusted`.
137
+ */
138
+ let projectTrustedState = false;
139
+
140
+ /** Apply the `packageAgents` setting. Drops the cache, since roots may change. */
141
+ export function setPackageAgentsGate(gate: PackageGate): void {
142
+ agentsGate = gate;
143
+ invalidatePackageCache();
144
+ }
145
+
146
+ /** Apply the `packageWorkflows` setting. Drops the cache, since roots may change. */
147
+ export function setPackageWorkflowsGate(gate: PackageGate): void {
148
+ workflowsGate = gate;
149
+ invalidatePackageCache();
150
+ }
151
+
152
+ export function getPackageAgentsGate(): PackageGate {
153
+ return agentsGate;
154
+ }
155
+
156
+ export function getPackageWorkflowsGate(): PackageGate {
157
+ return workflowsGate;
158
+ }
159
+
160
+ /**
161
+ * Record pi's project-trust answer. Drops the cache when the answer changes,
162
+ * since a project's `packages[]` becomes visible or invisible with it. A repeat
163
+ * of the same answer is a no-op — `session_start` fires on every new, resumed
164
+ * and forked session, and it has its own reason to invalidate.
165
+ */
166
+ export function setProjectTrusted(trusted: boolean): void {
167
+ if (projectTrustedState === trusted) return;
168
+ projectTrustedState = trusted;
169
+ invalidatePackageCache();
170
+ }
171
+
172
+ /**
173
+ * Pi's project-trust answer as last recorded, `false` until one is. The loader
174
+ * for project-supplied agent files reads this, so a missing answer fails closed.
175
+ */
176
+ export function isProjectTrusted(): boolean {
177
+ return projectTrustedState;
178
+ }
179
+
180
+ /** Reset every session-scoped value. Tests only — the extension never un-loads. */
181
+ export function resetPackageState(): void {
182
+ agentsGate = undefined;
183
+ workflowsGate = undefined;
184
+ projectTrustedState = false;
185
+ invalidatePackageCache();
186
+ }
187
+
188
+ /** What a package declared, after normalising the accepted spellings. */
189
+ export interface DeclaredEntries {
190
+ agents?: string[];
191
+ workflows?: string[];
192
+ }
193
+
194
+ /** Absolute paths a declaration resolved to, split by what the loader needs. */
195
+ export interface ResolvedResourcePaths {
196
+ dirs: string[];
197
+ files: string[];
198
+ /**
199
+ * Canonical paths of `!` entries. Kept separate from `dirs`/`files` rather
200
+ * than subtracted from them because an exclusion usually names a file *inside*
201
+ * an included directory, which is not enumerated until load time.
202
+ */
203
+ excluded: ReadonlySet<string>;
204
+ }
205
+
206
+ // ---- Manifest reading ----
207
+
208
+ /** A string array, or undefined for anything else. Mirrors pi's `readPiManifest` strictness. */
209
+ function stringArray(val: unknown): string[] | undefined {
210
+ return Array.isArray(val) && val.every(e => typeof e === "string") ? (val as string[]) : undefined;
211
+ }
212
+
213
+ /**
214
+ * Normalize one accepted spelling into `{ agents, workflows }`.
215
+ * A bare array is the `agents` shorthand — the only kind that existed when the
216
+ * shorthand was worth having, and the shape the other fork's docs show.
217
+ */
218
+ function normalizeDeclaration(val: unknown): DeclaredEntries | undefined {
219
+ const asArray = stringArray(val);
220
+ if (asArray) return { agents: asArray };
221
+ if (!val || typeof val !== "object" || Array.isArray(val)) return undefined;
222
+ const obj = val as Record<string, unknown>;
223
+ const agents = stringArray(obj.agents);
224
+ const workflows = stringArray(obj.workflows);
225
+ if (!agents && !workflows) return undefined;
226
+ return { agents, workflows };
227
+ }
228
+
229
+ /**
230
+ * Read the subagent declaration out of a parsed `package.json`.
231
+ *
232
+ * `pi.subagents` wins over the top-level `pi-subagents` when a package carries
233
+ * both — the pi-namespaced key is the primary spelling here, and a package that
234
+ * writes both almost certainly means them to be identical anyway.
235
+ */
236
+ export function readSubagentManifest(pkg: unknown): DeclaredEntries | undefined {
237
+ if (!pkg || typeof pkg !== "object") return undefined;
238
+ const obj = pkg as Record<string, unknown>;
239
+ const piKey = obj.pi;
240
+ if (piKey && typeof piKey === "object" && !Array.isArray(piKey)) {
241
+ const nested = normalizeDeclaration((piKey as Record<string, unknown>).subagents);
242
+ if (nested) return nested;
243
+ }
244
+ return normalizeDeclaration(obj["pi-subagents"]);
245
+ }
246
+
247
+ /** Parse `<root>/package.json`, or undefined when it is missing or malformed. */
248
+ function readPackageJson(root: string): Record<string, unknown> | undefined {
249
+ try {
250
+ const parsed: unknown = JSON.parse(readFileSync(join(root, "package.json"), "utf-8"));
251
+ return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : undefined;
252
+ } catch {
253
+ return undefined;
254
+ }
255
+ }
256
+
257
+ /** `@scope/foo` becomes `foo`, lowercased. The name a user types in an allowlist. */
258
+ export function unscopedShortName(name: string): string {
259
+ const short = name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
260
+ return short.toLowerCase();
261
+ }
262
+
263
+ // ---- Path resolution ----
264
+
265
+ /**
266
+ * Canonical absolute path, resolving symlinks as far as the path exists.
267
+ *
268
+ * A plain `realpathSync` is not enough: an exclusion may name a file the package
269
+ * does not ship yet, and a bare `resolve()` fallback would leave it uncanonical
270
+ * — which on macOS means `/var/...` compared against a canonical `/private/var/...`
271
+ * root, so the containment check below rejects it. Canonicalizing the nearest
272
+ * existing ancestor and re-appending the rest keeps both sides comparable.
273
+ */
274
+ function realOrSelf(path: string): string {
275
+ const abs = resolve(path);
276
+ try {
277
+ return realpathSync(abs);
278
+ } catch {
279
+ const parent = dirname(abs);
280
+ return parent === abs ? abs : join(realOrSelf(parent), basename(abs));
281
+ }
282
+ }
283
+
284
+ /**
285
+ * True when `candidate` is inside `root`. Package manifests are third-party
286
+ * input, so `"../../.ssh"` must not become a scanned directory — pi refuses the
287
+ * same shape with "Refusing to use path outside package install root".
288
+ *
289
+ * Compared on canonical paths, because `..` is not the only way out: a symlinked
290
+ * `agents/` pointing at `/etc` is textually inside the root, and `readdirSync`
291
+ * follows it. Both sides are canonicalized so a package installed *under* a
292
+ * symlink (`/var` → `/private/var` on macOS) still matches itself.
293
+ */
294
+ function isInside(root: string, candidate: string): boolean {
295
+ const rel = relative(realOrSelf(root), realOrSelf(candidate));
296
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
297
+ }
298
+
299
+ /**
300
+ * Resolve one manifest entry against the package root, returning the path only
301
+ * when it stays inside the package and exists.
302
+ *
303
+ * Globs are deliberately not supported. Pi's own manifest expands them because
304
+ * it resolves four resource types across arbitrary layouts; here the entries are
305
+ * one or two directories, and a glob would mean walking a third-party tree to
306
+ * answer. A directory or a file path covers the declared use cases.
307
+ */
308
+ function expandEntry(root: string, entry: string): string | undefined {
309
+ const target = resolve(root, entry);
310
+ if (!isInside(root, target) || !existsSync(target)) return undefined;
311
+ return target;
312
+ }
313
+
314
+ /**
315
+ * Resolve one kind's declared entries into concrete absolute paths inside the
316
+ * package: directories to scan, and individual files.
317
+ *
318
+ * Split into `{ dirs, files }` rather than a flat list because the agent loader
319
+ * takes directories (it does its own `readdirSync` and frontmatter handling),
320
+ * while a manifest entry naming a single file has to be surfaced on its own.
321
+ *
322
+ * `!entry` marks an exclusion. Exact paths only — pi's own `!` is gitignore-style
323
+ * glob negation, and globs are not supported here for the reason above.
324
+ */
325
+ export function resolveDeclaredPaths(
326
+ root: string,
327
+ entries: string[] | undefined,
328
+ kind: PackageResourceKind,
329
+ ): ResolvedResourcePaths {
330
+ const dirs: string[] = [];
331
+ const files: string[] = [];
332
+ const excluded = new Set<string>();
333
+ if (!entries) return { dirs, files, excluded };
334
+
335
+ // Exclusions are collected first and stored canonically, so `!./agents/wip.md`
336
+ // matches the same file however the loader spelled its way to it. They do not
337
+ // have to exist: a package may exclude a path it ships conditionally.
338
+ for (const entry of entries) {
339
+ if (!entry.startsWith("!")) continue;
340
+ const target = resolve(root, entry.slice(1));
341
+ if (isInside(root, target)) excluded.add(realOrSelf(target));
342
+ }
343
+
344
+ const ext = KIND_EXTENSION[kind];
345
+ for (const entry of entries) {
346
+ if (entry.startsWith("!")) continue;
347
+ const path = expandEntry(root, entry);
348
+ if (!path || excluded.has(realOrSelf(path))) continue;
349
+ let stat: ReturnType<typeof statSync>;
350
+ try {
351
+ stat = statSync(path);
352
+ } catch {
353
+ continue;
354
+ }
355
+ if (stat.isDirectory()) {
356
+ if (!dirs.includes(path)) dirs.push(path);
357
+ } else if (stat.isFile() && path.endsWith(ext) && !files.includes(path)) {
358
+ files.push(path);
359
+ }
360
+ }
361
+ return { dirs, files, excluded };
362
+ }
363
+
364
+ // ---- Package enumeration ----
365
+
366
+ interface ConfiguredPackageRow {
367
+ source: string;
368
+ scope: "user" | "project";
369
+ installedPath?: string;
370
+ }
371
+
372
+ /**
373
+ * Build a read-only view of pi's configured packages.
374
+ *
375
+ * Feature-detected rather than assumed: the peer range `>=1.1.0` is open-ended,
376
+ * so a later pi that drops or renames this API contributes no packages instead
377
+ * of failing activation.
378
+ */
379
+ function configuredPackages(cwd: string, projectTrusted: boolean): ConfiguredPackageRow[] {
380
+ try {
381
+ if (typeof DefaultPackageManager !== "function") return [];
382
+ const agentDir = getAgentDir();
383
+ const settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted });
384
+ const manager = new DefaultPackageManager({ cwd, agentDir, settingsManager });
385
+ if (typeof manager.listConfiguredPackages !== "function") return [];
386
+ return manager.listConfiguredPackages();
387
+ } catch {
388
+ return [];
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Every installed pi package that declares subagent resources, in pi's own
394
+ * order (global entries first, then project). Duplicates by root are collapsed —
395
+ * a package listed in both scopes is one package on disk.
396
+ */
397
+ export function listPiPackages(cwd: string, projectTrusted = false): PiPackage[] {
398
+ const seen = new Set<string>();
399
+ const out: PiPackage[] = [];
400
+ for (const entry of configuredPackages(cwd, projectTrusted)) {
401
+ const root = entry.installedPath;
402
+ if (!root || seen.has(root)) continue;
403
+ const manifest = readPackageJson(root);
404
+ const declared = manifest ? readSubagentManifest(manifest) : undefined;
405
+ if (!manifest || !declared) continue;
406
+ seen.add(root);
407
+ const name = typeof manifest.name === "string" ? manifest.name : undefined;
408
+ out.push({
409
+ source: entry.source,
410
+ name,
411
+ shortName: name ? unscopedShortName(name) : undefined,
412
+ scope: entry.scope,
413
+ root,
414
+ declared,
415
+ });
416
+ }
417
+ return out;
418
+ }
419
+
420
+ /**
421
+ * Whether `pkg` passes the gate. `true`/omitted admits everything; an array
422
+ * matches case-insensitively against the unscoped short name, the full package
423
+ * name, or the settings source string — users reach for whichever of the three
424
+ * they happen to have in front of them.
425
+ */
426
+ export function packageAllowed(pkg: PiPackage, gate: PackageGate): boolean {
427
+ if (gate === false) return false;
428
+ if (gate === undefined || gate === true) return true;
429
+ const candidates = new Set(
430
+ [pkg.shortName, pkg.name?.toLowerCase(), pkg.source.toLowerCase()].filter(
431
+ (v): v is string => typeof v === "string",
432
+ ),
433
+ );
434
+ return gate.some(allowed => candidates.has(allowed.trim().toLowerCase()));
435
+ }
436
+
437
+ // ---- Caching ----
438
+
439
+ /** An admitted package's install root and the name to show for it. */
440
+ interface PackageOwner {
441
+ /** Normalized, so it compares against a normalized candidate path. */
442
+ root: string;
443
+ name: string;
444
+ }
445
+
446
+ /**
447
+ * `loadCustomAgents` runs on activation and again on every `Agent` call, so an
448
+ * uncached scan would re-read pi's settings and every package manifest per
449
+ * spawn. What is cached is only the *root list* — which packages declare what —
450
+ * because that changes when settings change, not when a file is edited. The
451
+ * agent files themselves are still re-read on every load, so editing a linked
452
+ * package's agent still takes effect immediately.
453
+ *
454
+ * Keyed by cwd because nested subagents load from `context.configCwd`, which is
455
+ * not necessarily the main session's directory, and by the gate because a
456
+ * settings change must not be served a stale allowlist.
457
+ */
458
+ interface CacheEntry {
459
+ agents: ResolvedResourcePaths;
460
+ workflows: ResolvedResourcePaths;
461
+ /**
462
+ * Every package the gate admitted, longest root first, so a path can be
463
+ * traced back to the package that contributed it. Recorded during the scan
464
+ * that already enumerated them rather than re-derived later: a second pass
465
+ * would re-read pi's settings and every manifest, and could disagree with
466
+ * this entry about which packages the gate let through.
467
+ */
468
+ owners: PackageOwner[];
469
+ }
470
+
471
+ /** A resolved-paths value with nothing in it. Fresh each call — callers get copies. */
472
+ function emptyPaths(): ResolvedResourcePaths {
473
+ return { dirs: [], files: [], excluded: new Set() };
474
+ }
475
+
476
+ /** A whole cache entry with nothing in it, for a gate that admits no package. */
477
+ function emptyEntry(): CacheEntry {
478
+ return { agents: emptyPaths(), workflows: emptyPaths(), owners: [] };
479
+ }
480
+ const cache = new Map<string, CacheEntry>();
481
+
482
+ /** Drop the memoized package scan. Called on `/reload` and after settings changes. */
483
+ export function invalidatePackageCache(): void {
484
+ cache.clear();
485
+ }
486
+
487
+ function scan(cwd: string, projectTrusted: boolean, gate: PackageGate): CacheEntry {
488
+ const entry = emptyEntry();
489
+ for (const pkg of listPiPackages(cwd, projectTrusted)) {
490
+ if (!packageAllowed(pkg, gate)) continue;
491
+ // The root is normalized here, not at lookup time: the declared paths below
492
+ // go through `resolve(root, entry)`, so a root that arrived with a trailing
493
+ // separator would never prefix-match the very paths it produced.
494
+ //
495
+ // `name` is absent only when the manifest had no usable `name` string; the
496
+ // settings source (`npm:@foo/bar@1.0.0`) is the last resort, which is what
497
+ // pi itself falls back to when it labels a package-provided resource.
498
+ entry.owners.push({ root: resolve(pkg.root), name: pkg.name ?? pkg.shortName ?? pkg.source });
499
+ for (const kind of ["agents", "workflows"] as const) {
500
+ const resolvedPaths = resolveDeclaredPaths(pkg.root, pkg.declared[kind], kind);
501
+ entry[kind].dirs.push(...resolvedPaths.dirs);
502
+ entry[kind].files.push(...resolvedPaths.files);
503
+ // One flat set across packages: an exclusion is an absolute path, so it
504
+ // can only ever match inside the package that wrote it.
505
+ for (const path of resolvedPaths.excluded) (entry[kind].excluded as Set<string>).add(path);
506
+ }
507
+ }
508
+ // Longest root first, so a package installed inside another's `node_modules`
509
+ // claims its own files rather than losing them to its host.
510
+ entry.owners.sort((a, b) => b.root.length - a.root.length);
511
+ return entry;
512
+ }
513
+
514
+ function cacheEntryFor(cwd: string, kind: PackageResourceKind, opts: PackageDiscoveryOptions): CacheEntry {
515
+ const gate = opts.gate ?? (kind === "agents" ? agentsGate : workflowsGate);
516
+ // An empty allowlist matches nothing, like `false` — see `sanitizePackageGate`
517
+ // in settings.ts for why an empty array is kept rather than dropped.
518
+ if (gate === false || (Array.isArray(gate) && gate.length === 0)) return emptyEntry();
519
+ const projectTrusted = opts.projectTrusted ?? projectTrustedState;
520
+ // `\u0000` written as an escape, not a raw byte: a literal NUL makes this
521
+ // whole file read as binary to grep, ripgrep and git, which silently drops
522
+ // it from search results.
523
+ const key = `${cwd}\u0000${projectTrusted ? 1 : 0}\u0000${JSON.stringify(gate ?? true)}`;
524
+ let hit = cache.get(key);
525
+ if (!hit) {
526
+ hit = scan(cwd, projectTrusted, gate);
527
+ cache.set(key, hit);
528
+ }
529
+ return hit;
530
+ }
531
+
532
+ function resolved(cwd: string, kind: PackageResourceKind, opts: PackageDiscoveryOptions): ResolvedResourcePaths {
533
+ return cacheEntryFor(cwd, kind, opts)[kind];
534
+ }
535
+
536
+ /**
537
+ * Name of the installed package that provided `path`, or undefined when no
538
+ * admitted package owns it. What `/agents` shows so a package agent can name its
539
+ * origin, and what a user needs in order to write a `packageAgents` allowlist.
540
+ *
541
+ * `kind` selects which gate to consult, because the two are configured
542
+ * separately: a package may be admitted for agents but not for workflows.
543
+ *
544
+ * A plain prefix test is enough. `resolveDeclaredPaths` builds every declared
545
+ * path as `resolve(root, entry)` without canonicalizing it — only the
546
+ * containment check and the exclusion set go through `realOrSelf` — so a
547
+ * `sourcePath` the loader derived from one is textually inside the root it came
548
+ * from. The `sep` anchor keeps `…/node_modules/foo` from claiming
549
+ * `…/node_modules/foo-bar`.
550
+ */
551
+ export function packageNameForPath(
552
+ path: string,
553
+ cwd: string,
554
+ kind: PackageResourceKind = "agents",
555
+ opts: PackageDiscoveryOptions = {},
556
+ ): string | undefined {
557
+ const abs = resolve(path);
558
+ return cacheEntryFor(cwd, kind, opts).owners.find(
559
+ o => abs === o.root || abs.startsWith(o.root + sep),
560
+ )?.name;
561
+ }
562
+
563
+ /**
564
+ * Directories of package-declared agent files, lowest-precedence first.
565
+ * Fed to `loadCustomAgents` ahead of the global and project roots.
566
+ */
567
+ export function packageAgentDirs(cwd: string, opts: PackageDiscoveryOptions = {}): string[] {
568
+ // A copy: the cache holds this array for the rest of the session, so a caller
569
+ // that sorted or spliced it would corrupt every later load.
570
+ return [...resolved(cwd, "agents", opts).dirs];
571
+ }
572
+
573
+ /** Individually declared agent `.md` files (a manifest entry naming a file, not a directory). */
574
+ export function packageAgentFiles(cwd: string, opts: PackageDiscoveryOptions = {}): string[] {
575
+ return [...resolved(cwd, "agents", opts).files];
576
+ }
577
+
578
+ /**
579
+ * Whether a `!` entry in some package manifest excludes this path.
580
+ *
581
+ * Checked at load time rather than subtracted during resolution, because the
582
+ * common exclusion — `["./agents", "!./agents/wip.md"]` — names a file inside a
583
+ * directory that is not enumerated until the loader reads it.
584
+ */
585
+ export function isPackageResourceExcluded(
586
+ path: string,
587
+ cwd: string,
588
+ kind: PackageResourceKind,
589
+ opts: PackageDiscoveryOptions = {},
590
+ ): boolean {
591
+ const excluded = resolved(cwd, kind, opts).excluded;
592
+ return excluded.size > 0 && excluded.has(realOrSelf(path));
593
+ }
594
+
595
+ /**
596
+ * Directories of package-declared workflow scripts, appended to
597
+ * `savedWorkflowRoots` so a name resolves there last.
598
+ */
599
+ export function packageWorkflowDirs(cwd: string, opts: PackageDiscoveryOptions = {}): string[] {
600
+ return [...resolved(cwd, "workflows", opts).dirs];
601
+ }
602
+
603
+ /**
604
+ * Individually declared workflow scripts, as `name -> absolute path`.
605
+ *
606
+ * A name lookup wants a directory, and a declared *file* has none — but standing
607
+ * its parent directory in as a root would make every sibling `.js` resolvable,
608
+ * so `workflows: ["./one.js"]` would quietly offer the package's other scripts
609
+ * too, and `["./index.js"]` would offer everything at the package root. That is
610
+ * the opposite of the rule the whole feature rests on, that a package only
611
+ * contributes what it names. An exact map keeps the declaration honest, and
612
+ * matches how a declared agent file is already handled.
613
+ *
614
+ * Later entries lose a name clash, so a package's own directory-sourced script
615
+ * is not displaced by a file entry from a package resolved after it.
616
+ */
617
+ export function packageWorkflowFiles(cwd: string, opts: PackageDiscoveryOptions = {}): Map<string, string> {
618
+ const out = new Map<string, string>();
619
+ for (const path of resolved(cwd, "workflows", opts).files) {
620
+ const name = basename(path, KIND_EXTENSION.workflows);
621
+ if (!out.has(name)) out.set(name, path);
622
+ }
623
+ return out;
624
+ }