@herbertgao/pi-subagents 0.19.0 → 0.22.0-local.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,724 @@
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 {
58
+ basename,
59
+ dirname,
60
+ isAbsolute,
61
+ join,
62
+ relative,
63
+ resolve,
64
+ sep,
65
+ } from "node:path"
66
+ import {
67
+ DefaultPackageManager,
68
+ getAgentDir,
69
+ ProjectTrustStore,
70
+ SettingsManager,
71
+ } from "@earendil-works/pi-coding-agent"
72
+
73
+ /** Resource kinds a package may declare. Agents are `.md`, workflows are `.js`. */
74
+ export type PackageResourceKind = "agents" | "workflows"
75
+
76
+ /** File extension scanned for each kind, mirroring the local roots for each. */
77
+ const KIND_EXTENSION: Record<PackageResourceKind, string> = {
78
+ agents: ".md",
79
+ workflows: ".js",
80
+ }
81
+
82
+ /**
83
+ * Per-file size ceiling for package-provided resources, matching Claude Code's
84
+ * plugin-agent limit. These files come from third-party packages and are read
85
+ * eagerly on every agent load; a pathological one should be skipped, not
86
+ * `readFileSync`'d into the session.
87
+ */
88
+ export const MAX_PACKAGE_RESOURCE_BYTES = 1_048_576
89
+
90
+ /** One installed pi package that declared something we understand. */
91
+ export interface PiPackage {
92
+ /** The settings source string, e.g. `npm:@foo/bar@1.0.0` or an absolute path. */
93
+ source: string
94
+ /** `package.json` `name`, when the manifest could be read. */
95
+ name?: string
96
+ /** Unscoped, lowercased short name (`@scope/foo` becomes `foo`) for allowlist matching. */
97
+ shortName?: string
98
+ /** Which settings scope configured it. */
99
+ scope: "user" | "project"
100
+ /** Absolute path of the installed package root. */
101
+ root: string
102
+ /**
103
+ * What its manifest declared. Carried here rather than re-read downstream:
104
+ * `listPiPackages` has to parse the manifest anyway to know whether the
105
+ * package declares anything at all, and reading it twice would leave two
106
+ * places that could disagree about what a package said.
107
+ */
108
+ declared: DeclaredEntries
109
+ }
110
+
111
+ /**
112
+ * The gate for one resource kind, as persisted in our settings:
113
+ * `true` (default) = every declaring package, `false` = none, `string[]` =
114
+ * only packages whose short name, full name, or source matches an entry.
115
+ */
116
+ export type PackageGate = boolean | string[] | undefined
117
+
118
+ export interface PackageDiscoveryOptions {
119
+ /**
120
+ * Pi's project-trust state for `cwd`, from `ctx.isProjectTrusted()`. When
121
+ * false, `.pi/settings.json` is not read — so a package configured only by an
122
+ * untrusted project is invisible to us, exactly as it is to pi. Omitted falls
123
+ * back to the session state set by {@link setProjectTrusted}.
124
+ */
125
+ projectTrusted?: boolean
126
+ /** Gate override. Omitted falls back to the session state for the kind. */
127
+ gate?: PackageGate
128
+ }
129
+
130
+ // ---- Session state ----
131
+ //
132
+ // Held here rather than threaded through every caller, matching how the rest of
133
+ // this extension carries session-wide settings (`setMaxSubagentDepth`,
134
+ // `setWorktreeIsolationEnabled`, ...). The alternative was an options bag
135
+ // travelling from `index.ts` through `resolveWorkflowScript`,
136
+ // `resolveWorkflowSource`, `readSavedWorkflow` and `listSavedWorkflows` purely
137
+ // so a gate could be consulted at the bottom.
138
+ //
139
+ // Both gates start `undefined`, which reads as `true`: absent settings mean
140
+ // every declaring package contributes, matching pi's own default for the
141
+ // resources it owns.
142
+
143
+ let agentsGate: PackageGate
144
+ let workflowsGate: PackageGate
145
+ /**
146
+ * Defaults to `false` — an extension activates before any session context
147
+ * exists, and reading an untrusted project's package list only to take it away
148
+ * again is the wrong direction to fail. `index.ts` corrects it from
149
+ * `ctx.isProjectTrusted()` on `session_start`.
150
+ */
151
+ let projectTrustedState = false
152
+
153
+ /** Apply the `packageAgents` setting. Drops the cache, since roots may change. */
154
+ export function setPackageAgentsGate(gate: PackageGate): void {
155
+ agentsGate = gate
156
+ invalidatePackageCache()
157
+ }
158
+
159
+ /** Apply the `packageWorkflows` setting. Drops the cache, since roots may change. */
160
+ export function setPackageWorkflowsGate(gate: PackageGate): void {
161
+ workflowsGate = gate
162
+ invalidatePackageCache()
163
+ }
164
+
165
+ export function getPackageAgentsGate(): PackageGate {
166
+ return agentsGate
167
+ }
168
+
169
+ export function getPackageWorkflowsGate(): PackageGate {
170
+ return workflowsGate
171
+ }
172
+
173
+ /**
174
+ * Seed the trust state from pi's *saved* decision, before any session exists.
175
+ *
176
+ * The correction on `session_start` is too late for one thing that matters: the
177
+ * `Agent` tool's description — the list of agent types the model is told about —
178
+ * is built once at activation, so an agent registered after it never reaches the
179
+ * model even though dispatch would accept it. That is exactly the shape a team
180
+ * ships agents in: a package named in a committed `.pi/settings.json`, which is
181
+ * invisible until the project is trusted.
182
+ *
183
+ * Pi keeps that decision in `<agentDir>/trust.json`, keyed by canonical path
184
+ * with the nearest ancestor winning, so on the second and every later session in
185
+ * a trusted repo the answer is already on disk. No saved decision falls back to
186
+ * the global `defaultProjectTrust`, which is what pi does; `"ask"` resolves to
187
+ * untrusted here, because the prompt has not been answered yet and guessing yes
188
+ * would be the wrong direction to guess.
189
+ *
190
+ * Best-effort by design: any failure leaves the state untrusted, and
191
+ * `session_start` still delivers pi's real answer either way.
192
+ */
193
+ export function seedProjectTrust(cwd: string): void {
194
+ try {
195
+ if (typeof ProjectTrustStore !== "function") return
196
+ const agentDir = getAgentDir()
197
+ const saved = new ProjectTrustStore(agentDir).get(cwd)
198
+ if (typeof saved === "boolean") {
199
+ setProjectTrusted(saved)
200
+ return
201
+ }
202
+ const settings = SettingsManager.create(cwd, agentDir, {
203
+ projectTrusted: false,
204
+ })
205
+ setProjectTrusted(
206
+ settings.getGlobalSettings().defaultProjectTrust === "always",
207
+ )
208
+ } catch {
209
+ // Leave it untrusted; session_start corrects it.
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Record pi's project-trust answer. Drops the cache when the answer changes,
215
+ * since a project's `packages[]` becomes visible or invisible with it. A repeat
216
+ * of the same answer is a no-op — `session_start` fires on every new, resumed
217
+ * and forked session, and it has its own reason to invalidate.
218
+ */
219
+ export function setProjectTrusted(trusted: boolean): void {
220
+ if (projectTrustedState === trusted) return
221
+ projectTrustedState = trusted
222
+ invalidatePackageCache()
223
+ }
224
+
225
+ /** Reset every session-scoped value. Tests only — the extension never un-loads. */
226
+ export function resetPackageState(): void {
227
+ agentsGate = undefined
228
+ workflowsGate = undefined
229
+ projectTrustedState = false
230
+ invalidatePackageCache()
231
+ }
232
+
233
+ /** What a package declared, after normalising the accepted spellings. */
234
+ export interface DeclaredEntries {
235
+ agents?: string[]
236
+ workflows?: string[]
237
+ }
238
+
239
+ /** Absolute paths a declaration resolved to, split by what the loader needs. */
240
+ export interface ResolvedResourcePaths {
241
+ dirs: string[]
242
+ files: string[]
243
+ /**
244
+ * Canonical paths of `!` entries. Kept separate from `dirs`/`files` rather
245
+ * than subtracted from them because an exclusion usually names a file *inside*
246
+ * an included directory, which is not enumerated until load time.
247
+ */
248
+ excluded: ReadonlySet<string>
249
+ }
250
+
251
+ // ---- Manifest reading ----
252
+
253
+ /** A string array, or undefined for anything else. Mirrors pi's `readPiManifest` strictness. */
254
+ function stringArray(val: unknown): string[] | undefined {
255
+ return Array.isArray(val) && val.every((e) => typeof e === "string")
256
+ ? (val as string[])
257
+ : undefined
258
+ }
259
+
260
+ /**
261
+ * Normalize one accepted spelling into `{ agents, workflows }`.
262
+ * A bare array is the `agents` shorthand — the only kind that existed when the
263
+ * shorthand was worth having, and the shape the other fork's docs show.
264
+ */
265
+ function normalizeDeclaration(val: unknown): DeclaredEntries | undefined {
266
+ const asArray = stringArray(val)
267
+ if (asArray) return { agents: asArray }
268
+ if (!val || typeof val !== "object" || Array.isArray(val)) return undefined
269
+ const obj = val as Record<string, unknown>
270
+ const agents = stringArray(obj.agents)
271
+ const workflows = stringArray(obj.workflows)
272
+ if (!agents && !workflows) return undefined
273
+ return { agents, workflows }
274
+ }
275
+
276
+ /**
277
+ * Read the subagent declaration out of a parsed `package.json`.
278
+ *
279
+ * `pi.subagents` wins over the top-level `pi-subagents` when a package carries
280
+ * both — the pi-namespaced key is the primary spelling here, and a package that
281
+ * writes both almost certainly means them to be identical anyway.
282
+ */
283
+ export function readSubagentManifest(
284
+ pkg: unknown,
285
+ ): DeclaredEntries | undefined {
286
+ if (!pkg || typeof pkg !== "object") return undefined
287
+ const obj = pkg as Record<string, unknown>
288
+ const piKey = obj.pi
289
+ if (piKey && typeof piKey === "object" && !Array.isArray(piKey)) {
290
+ const nested = normalizeDeclaration(
291
+ (piKey as Record<string, unknown>).subagents,
292
+ )
293
+ if (nested) return nested
294
+ }
295
+ return normalizeDeclaration(obj["pi-subagents"])
296
+ }
297
+
298
+ /** Parse `<root>/package.json`, or undefined when it is missing or malformed. */
299
+ function readPackageJson(root: string): Record<string, unknown> | undefined {
300
+ try {
301
+ const parsed: unknown = JSON.parse(
302
+ readFileSync(join(root, "package.json"), "utf-8"),
303
+ )
304
+ return parsed && typeof parsed === "object"
305
+ ? (parsed as Record<string, unknown>)
306
+ : undefined
307
+ } catch {
308
+ return undefined
309
+ }
310
+ }
311
+
312
+ /** `@scope/foo` becomes `foo`, lowercased. The name a user types in an allowlist. */
313
+ export function unscopedShortName(name: string): string {
314
+ const short = name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name
315
+ return short.toLowerCase()
316
+ }
317
+
318
+ // ---- Path resolution ----
319
+
320
+ /**
321
+ * Canonical absolute path, resolving symlinks as far as the path exists.
322
+ *
323
+ * A plain `realpathSync` is not enough: an exclusion may name a file the package
324
+ * does not ship yet, and a bare `resolve()` fallback would leave it uncanonical
325
+ * — which on macOS means `/var/...` compared against a canonical `/private/var/...`
326
+ * root, so the containment check below rejects it. Canonicalizing the nearest
327
+ * existing ancestor and re-appending the rest keeps both sides comparable.
328
+ */
329
+ function realOrSelf(path: string): string {
330
+ const abs = resolve(path)
331
+ try {
332
+ return realpathSync(abs)
333
+ } catch {
334
+ const parent = dirname(abs)
335
+ return parent === abs ? abs : join(realOrSelf(parent), basename(abs))
336
+ }
337
+ }
338
+
339
+ /**
340
+ * True when `candidate` is inside `root`. Package manifests are third-party
341
+ * input, so `"../../.ssh"` must not become a scanned directory — pi refuses the
342
+ * same shape with "Refusing to use path outside package install root".
343
+ *
344
+ * Compared on canonical paths, because `..` is not the only way out: a symlinked
345
+ * `agents/` pointing at `/etc` is textually inside the root, and `readdirSync`
346
+ * follows it. Both sides are canonicalized so a package installed *under* a
347
+ * symlink (`/var` → `/private/var` on macOS) still matches itself.
348
+ */
349
+ function isInside(root: string, candidate: string): boolean {
350
+ const rel = relative(realOrSelf(root), realOrSelf(candidate))
351
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel)
352
+ }
353
+
354
+ /**
355
+ * Resolve one manifest entry against the package root, returning the path only
356
+ * when it stays inside the package and exists.
357
+ *
358
+ * Globs are deliberately not supported. Pi's own manifest expands them because
359
+ * it resolves four resource types across arbitrary layouts; here the entries are
360
+ * one or two directories, and a glob would mean walking a third-party tree to
361
+ * answer. A directory or a file path covers the declared use cases.
362
+ */
363
+ function expandEntry(root: string, entry: string): string | undefined {
364
+ const target = resolve(root, entry)
365
+ if (!isInside(root, target) || !existsSync(target)) return undefined
366
+ return target
367
+ }
368
+
369
+ /**
370
+ * Resolve one kind's declared entries into concrete absolute paths inside the
371
+ * package: directories to scan, and individual files.
372
+ *
373
+ * Split into `{ dirs, files }` rather than a flat list because the agent loader
374
+ * takes directories (it does its own `readdirSync` and frontmatter handling),
375
+ * while a manifest entry naming a single file has to be surfaced on its own.
376
+ *
377
+ * `!entry` marks an exclusion. Exact paths only — pi's own `!` is gitignore-style
378
+ * glob negation, and globs are not supported here for the reason above.
379
+ */
380
+ export function resolveDeclaredPaths(
381
+ root: string,
382
+ entries: string[] | undefined,
383
+ kind: PackageResourceKind,
384
+ ): ResolvedResourcePaths {
385
+ const dirs: string[] = []
386
+ const files: string[] = []
387
+ const excluded = new Set<string>()
388
+ if (!entries) return { dirs, files, excluded }
389
+
390
+ // Exclusions are collected first and stored canonically, so `!./agents/wip.md`
391
+ // matches the same file however the loader spelled its way to it. They do not
392
+ // have to exist: a package may exclude a path it ships conditionally.
393
+ for (const entry of entries) {
394
+ if (!entry.startsWith("!")) continue
395
+ const target = resolve(root, entry.slice(1))
396
+ if (isInside(root, target)) excluded.add(realOrSelf(target))
397
+ }
398
+
399
+ const ext = KIND_EXTENSION[kind]
400
+ for (const entry of entries) {
401
+ if (entry.startsWith("!")) continue
402
+ const path = expandEntry(root, entry)
403
+ if (!path || excluded.has(realOrSelf(path))) continue
404
+ let stat: ReturnType<typeof statSync>
405
+ try {
406
+ stat = statSync(path)
407
+ } catch {
408
+ continue
409
+ }
410
+ if (stat.isDirectory()) {
411
+ if (!dirs.includes(path)) dirs.push(path)
412
+ } else if (stat.isFile() && path.endsWith(ext) && !files.includes(path)) {
413
+ files.push(path)
414
+ }
415
+ }
416
+ return { dirs, files, excluded }
417
+ }
418
+
419
+ // ---- Package enumeration ----
420
+
421
+ interface ConfiguredPackageRow {
422
+ source: string
423
+ scope: "user" | "project"
424
+ installedPath?: string
425
+ }
426
+
427
+ /**
428
+ * Build a read-only view of pi's configured packages.
429
+ *
430
+ * Feature-detected rather than assumed: the peer range `>=1.1.0` is open-ended,
431
+ * so a later pi that drops or renames this API contributes no packages instead
432
+ * of failing activation.
433
+ */
434
+ function configuredPackages(
435
+ cwd: string,
436
+ projectTrusted: boolean,
437
+ ): ConfiguredPackageRow[] {
438
+ try {
439
+ if (typeof DefaultPackageManager !== "function") return []
440
+ const agentDir = getAgentDir()
441
+ const settingsManager = SettingsManager.create(cwd, agentDir, {
442
+ projectTrusted,
443
+ })
444
+ const manager = new DefaultPackageManager({
445
+ cwd,
446
+ agentDir,
447
+ settingsManager,
448
+ })
449
+ if (typeof manager.listConfiguredPackages !== "function") return []
450
+ return manager.listConfiguredPackages()
451
+ } catch {
452
+ return []
453
+ }
454
+ }
455
+
456
+ /**
457
+ * Every installed pi package that declares subagent resources, in pi's own
458
+ * order (global entries first, then project). Duplicates by root are collapsed —
459
+ * a package listed in both scopes is one package on disk.
460
+ */
461
+ export function listPiPackages(
462
+ cwd: string,
463
+ projectTrusted = false,
464
+ ): PiPackage[] {
465
+ const seen = new Set<string>()
466
+ const out: PiPackage[] = []
467
+ for (const entry of configuredPackages(cwd, projectTrusted)) {
468
+ const root = entry.installedPath
469
+ if (!root || seen.has(root)) continue
470
+ const manifest = readPackageJson(root)
471
+ const declared = manifest ? readSubagentManifest(manifest) : undefined
472
+ if (!manifest || !declared) continue
473
+ seen.add(root)
474
+ const name = typeof manifest.name === "string" ? manifest.name : undefined
475
+ out.push({
476
+ source: entry.source,
477
+ name,
478
+ shortName: name ? unscopedShortName(name) : undefined,
479
+ scope: entry.scope,
480
+ root,
481
+ declared,
482
+ })
483
+ }
484
+ return out
485
+ }
486
+
487
+ /**
488
+ * Whether `pkg` passes the gate. `true`/omitted admits everything; an array
489
+ * matches case-insensitively against the unscoped short name, the full package
490
+ * name, or the settings source string — users reach for whichever of the three
491
+ * they happen to have in front of them.
492
+ */
493
+ export function packageAllowed(pkg: PiPackage, gate: PackageGate): boolean {
494
+ if (gate === false) return false
495
+ if (gate === undefined || gate === true) return true
496
+ const candidates = new Set(
497
+ [pkg.shortName, pkg.name?.toLowerCase(), pkg.source.toLowerCase()].filter(
498
+ (v): v is string => typeof v === "string",
499
+ ),
500
+ )
501
+ return gate.some((allowed) => candidates.has(allowed.trim().toLowerCase()))
502
+ }
503
+
504
+ // ---- Caching ----
505
+
506
+ /** An admitted package's install root and the name to show for it. */
507
+ interface PackageOwner {
508
+ /** Normalized, so it compares against a normalized candidate path. */
509
+ root: string
510
+ name: string
511
+ }
512
+
513
+ /**
514
+ * `loadCustomAgents` runs on activation and again on every `Agent` call, so an
515
+ * uncached scan would re-read pi's settings and every package manifest per
516
+ * spawn. What is cached is only the *root list* — which packages declare what —
517
+ * because that changes when settings change, not when a file is edited. The
518
+ * agent files themselves are still re-read on every load, so editing a linked
519
+ * package's agent still takes effect immediately.
520
+ *
521
+ * Keyed by cwd because nested subagents load from `context.configCwd`, which is
522
+ * not necessarily the main session's directory, and by the gate because a
523
+ * settings change must not be served a stale allowlist.
524
+ */
525
+ interface CacheEntry {
526
+ agents: ResolvedResourcePaths
527
+ workflows: ResolvedResourcePaths
528
+ /**
529
+ * Every package the gate admitted, longest root first, so a path can be
530
+ * traced back to the package that contributed it. Recorded during the scan
531
+ * that already enumerated them rather than re-derived later: a second pass
532
+ * would re-read pi's settings and every manifest, and could disagree with
533
+ * this entry about which packages the gate let through.
534
+ */
535
+ owners: PackageOwner[]
536
+ }
537
+
538
+ /** A resolved-paths value with nothing in it. Fresh each call — callers get copies. */
539
+ function emptyPaths(): ResolvedResourcePaths {
540
+ return { dirs: [], files: [], excluded: new Set() }
541
+ }
542
+
543
+ /** A whole cache entry with nothing in it, for a gate that admits no package. */
544
+ function emptyEntry(): CacheEntry {
545
+ return { agents: emptyPaths(), workflows: emptyPaths(), owners: [] }
546
+ }
547
+ const cache = new Map<string, CacheEntry>()
548
+
549
+ /** Drop the memoized package scan. Called on `/reload` and after settings changes. */
550
+ export function invalidatePackageCache(): void {
551
+ cache.clear()
552
+ }
553
+
554
+ function scan(
555
+ cwd: string,
556
+ projectTrusted: boolean,
557
+ gate: PackageGate,
558
+ ): CacheEntry {
559
+ const entry = emptyEntry()
560
+ for (const pkg of listPiPackages(cwd, projectTrusted)) {
561
+ if (!packageAllowed(pkg, gate)) continue
562
+ // The root is normalized here, not at lookup time: the declared paths below
563
+ // go through `resolve(root, entry)`, so a root that arrived with a trailing
564
+ // separator would never prefix-match the very paths it produced.
565
+ //
566
+ // `name` is absent only when the manifest had no usable `name` string; the
567
+ // settings source (`npm:@foo/bar@1.0.0`) is the last resort, which is what
568
+ // pi itself falls back to when it labels a package-provided resource.
569
+ entry.owners.push({
570
+ root: resolve(pkg.root),
571
+ name: pkg.name ?? pkg.shortName ?? pkg.source,
572
+ })
573
+ for (const kind of ["agents", "workflows"] as const) {
574
+ const resolvedPaths = resolveDeclaredPaths(
575
+ pkg.root,
576
+ pkg.declared[kind],
577
+ kind,
578
+ )
579
+ entry[kind].dirs.push(...resolvedPaths.dirs)
580
+ entry[kind].files.push(...resolvedPaths.files)
581
+ // One flat set across packages: an exclusion is an absolute path, so it
582
+ // can only ever match inside the package that wrote it.
583
+ for (const path of resolvedPaths.excluded)
584
+ (entry[kind].excluded as Set<string>).add(path)
585
+ }
586
+ }
587
+ // Longest root first, so a package installed inside another's `node_modules`
588
+ // claims its own files rather than losing them to its host.
589
+ entry.owners.sort((a, b) => b.root.length - a.root.length)
590
+ return entry
591
+ }
592
+
593
+ function cacheEntryFor(
594
+ cwd: string,
595
+ kind: PackageResourceKind,
596
+ opts: PackageDiscoveryOptions,
597
+ ): CacheEntry {
598
+ const gate = opts.gate ?? (kind === "agents" ? agentsGate : workflowsGate)
599
+ // An empty allowlist matches nothing, like `false` — see `sanitizePackageGate`
600
+ // in settings.ts for why an empty array is kept rather than dropped.
601
+ if (gate === false || (Array.isArray(gate) && gate.length === 0))
602
+ return emptyEntry()
603
+ const projectTrusted = opts.projectTrusted ?? projectTrustedState
604
+ // `\u0000` written as an escape, not a raw byte: a literal NUL makes this
605
+ // whole file read as binary to grep, ripgrep and git, which silently drops
606
+ // it from search results.
607
+ const key = `${cwd}\u0000${projectTrusted ? 1 : 0}\u0000${JSON.stringify(gate ?? true)}`
608
+ let hit = cache.get(key)
609
+ if (!hit) {
610
+ hit = scan(cwd, projectTrusted, gate)
611
+ cache.set(key, hit)
612
+ }
613
+ return hit
614
+ }
615
+
616
+ function resolved(
617
+ cwd: string,
618
+ kind: PackageResourceKind,
619
+ opts: PackageDiscoveryOptions,
620
+ ): ResolvedResourcePaths {
621
+ return cacheEntryFor(cwd, kind, opts)[kind]
622
+ }
623
+
624
+ /**
625
+ * Name of the installed package that provided `path`, or undefined when no
626
+ * admitted package owns it. What `/agents` shows so a package agent can name its
627
+ * origin, and what a user needs in order to write a `packageAgents` allowlist.
628
+ *
629
+ * `kind` selects which gate to consult, because the two are configured
630
+ * separately: a package may be admitted for agents but not for workflows.
631
+ *
632
+ * A plain prefix test is enough. `resolveDeclaredPaths` builds every declared
633
+ * path as `resolve(root, entry)` without canonicalizing it — only the
634
+ * containment check and the exclusion set go through `realOrSelf` — so a
635
+ * `sourcePath` the loader derived from one is textually inside the root it came
636
+ * from. The `sep` anchor keeps `…/node_modules/foo` from claiming
637
+ * `…/node_modules/foo-bar`.
638
+ */
639
+ export function packageNameForPath(
640
+ path: string,
641
+ cwd: string,
642
+ kind: PackageResourceKind = "agents",
643
+ opts: PackageDiscoveryOptions = {},
644
+ ): string | undefined {
645
+ const abs = resolve(path)
646
+ return cacheEntryFor(cwd, kind, opts).owners.find(
647
+ (o) => abs === o.root || abs.startsWith(o.root + sep),
648
+ )?.name
649
+ }
650
+
651
+ /**
652
+ * Directories of package-declared agent files, lowest-precedence first.
653
+ * Fed to `loadCustomAgents` ahead of the global and project roots.
654
+ */
655
+ export function packageAgentDirs(
656
+ cwd: string,
657
+ opts: PackageDiscoveryOptions = {},
658
+ ): string[] {
659
+ // A copy: the cache holds this array for the rest of the session, so a caller
660
+ // that sorted or spliced it would corrupt every later load.
661
+ return [...resolved(cwd, "agents", opts).dirs]
662
+ }
663
+
664
+ /** Individually declared agent `.md` files (a manifest entry naming a file, not a directory). */
665
+ export function packageAgentFiles(
666
+ cwd: string,
667
+ opts: PackageDiscoveryOptions = {},
668
+ ): string[] {
669
+ return [...resolved(cwd, "agents", opts).files]
670
+ }
671
+
672
+ /**
673
+ * Whether a `!` entry in some package manifest excludes this path.
674
+ *
675
+ * Checked at load time rather than subtracted during resolution, because the
676
+ * common exclusion — `["./agents", "!./agents/wip.md"]` — names a file inside a
677
+ * directory that is not enumerated until the loader reads it.
678
+ */
679
+ export function isPackageResourceExcluded(
680
+ path: string,
681
+ cwd: string,
682
+ kind: PackageResourceKind,
683
+ opts: PackageDiscoveryOptions = {},
684
+ ): boolean {
685
+ const excluded = resolved(cwd, kind, opts).excluded
686
+ return excluded.size > 0 && excluded.has(realOrSelf(path))
687
+ }
688
+
689
+ /**
690
+ * Directories of package-declared workflow scripts, appended to
691
+ * `savedWorkflowRoots` so a name resolves there last.
692
+ */
693
+ export function packageWorkflowDirs(
694
+ cwd: string,
695
+ opts: PackageDiscoveryOptions = {},
696
+ ): string[] {
697
+ return [...resolved(cwd, "workflows", opts).dirs]
698
+ }
699
+
700
+ /**
701
+ * Individually declared workflow scripts, as `name -> absolute path`.
702
+ *
703
+ * A name lookup wants a directory, and a declared *file* has none — but standing
704
+ * its parent directory in as a root would make every sibling `.js` resolvable,
705
+ * so `workflows: ["./one.js"]` would quietly offer the package's other scripts
706
+ * too, and `["./index.js"]` would offer everything at the package root. That is
707
+ * the opposite of the rule the whole feature rests on, that a package only
708
+ * contributes what it names. An exact map keeps the declaration honest, and
709
+ * matches how a declared agent file is already handled.
710
+ *
711
+ * Later entries lose a name clash, so a package's own directory-sourced script
712
+ * is not displaced by a file entry from a package resolved after it.
713
+ */
714
+ export function packageWorkflowFiles(
715
+ cwd: string,
716
+ opts: PackageDiscoveryOptions = {},
717
+ ): Map<string, string> {
718
+ const out = new Map<string, string>()
719
+ for (const path of resolved(cwd, "workflows", opts).files) {
720
+ const name = basename(path, KIND_EXTENSION.workflows)
721
+ if (!out.has(name)) out.set(name, path)
722
+ }
723
+ return out
724
+ }