@ymy88/pi-subagents 0.0.0-stage → 0.24.0

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