@restranger/repi-subagents 0.0.0-stage → 0.0.1-1a48fc0

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,353 @@
1
+ import { type Dirent, existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { parseAgentFile } from "./agent-file.js";
5
+ import { DEFAULT_AGENTS } from "./default-agents.js";
6
+ import { applyAgentOverrides, loadAgentOverrides } from "./overrides.js";
7
+ import type { AgentDefinition, AgentDiagnostic, AgentScanResult, AgentSource } from "./types.js";
8
+
9
+ export interface DiscoverAgentsOptions {
10
+ readonly cwd: string;
11
+ /** Defaults to `os.homedir()`; injectable for tests. */
12
+ readonly homeDir?: string;
13
+ /** Defaults to `process.env`; `PI_CODING_AGENT_DIR` and `XDG_CONFIG_HOME` are honored. */
14
+ readonly env?: Readonly<Record<string, string | undefined>>;
15
+ /** Explicit user directories, lowest priority first. Overrides the default user locations. */
16
+ readonly userDirs?: readonly string[];
17
+ /** Explicit project directories, lowest priority first. Overrides the default project locations. */
18
+ readonly projectDirs?: readonly string[];
19
+ /** When false, project-local agent files are ignored. */
20
+ readonly workspaceTrusted?: boolean;
21
+ readonly maxFiles?: number;
22
+ /** Whether to seed discovery with built-in default agents. Defaults to true when explicit userDirs/projectDirs are omitted. */
23
+ readonly includeBuiltins?: boolean;
24
+ }
25
+
26
+ export interface AgentDirectory {
27
+ readonly path: string;
28
+ readonly source: AgentSource;
29
+ }
30
+
31
+ const DEFAULT_MAX_FILES = 500;
32
+ const MAX_DEPTH = 8;
33
+ const IGNORED_DIRS = new Set(["node_modules", ".git", ".hg", ".svn"]);
34
+
35
+ /**
36
+ * Resolve the directory hierarchy from lowest to highest priority.
37
+ *
38
+ * The Pi locations come first so a `.repi/agents` file can deliberately override the same name in
39
+ * `.pi/agents`. Project directories always outrank every user directory.
40
+ */
41
+ export function resolveAgentDirectories(options: DiscoverAgentsOptions): AgentDirectory[] {
42
+ const cwd = resolve(options.cwd);
43
+ const home = options.homeDir ?? homedir();
44
+ const env = options.env ?? process.env;
45
+ const configHome = env.XDG_CONFIG_HOME ?? join(home, ".config");
46
+
47
+ const userDirs = options.userDirs ?? [
48
+ ...(env.PI_CODING_AGENT_DIR
49
+ ? [join(env.PI_CODING_AGENT_DIR, "agents")]
50
+ : [join(configHome, "pi", "agent", "agents"), join(home, ".pi", "agent", "agents")]),
51
+ ];
52
+ const projectDirs = options.projectDirs ?? [join(cwd, ".pi", "agents"), join(cwd, ".repi", "agents")];
53
+
54
+ const result: AgentDirectory[] = [];
55
+ const seen = new Set<string>();
56
+ const add = (path: string, source: AgentSource): void => {
57
+ const absolute = resolve(path);
58
+ if (seen.has(absolute)) {
59
+ return;
60
+ }
61
+ seen.add(absolute);
62
+ result.push({ path: absolute, source });
63
+ };
64
+
65
+ for (const dir of userDirs) {
66
+ add(dir, "user");
67
+ }
68
+ for (const dir of projectDirs) {
69
+ add(dir, "project");
70
+ }
71
+ return result;
72
+ }
73
+
74
+ /**
75
+ * Scan every configured directory for `*.md` agent declarations.
76
+ *
77
+ * Lower-priority files are read first and overwritten by higher-priority ones with the same name
78
+ * (case-insensitive), which makes project files win without special-casing them later.
79
+ */
80
+ export function discoverAgents(options: DiscoverAgentsOptions): AgentScanResult {
81
+ const directories = resolveAgentDirectories(options);
82
+ const diagnostics: AgentDiagnostic[] = [];
83
+ const agents = new Map<string, AgentDefinition>();
84
+ const includeBuiltins =
85
+ options.includeBuiltins ?? (options.userDirs === undefined && options.projectDirs === undefined);
86
+ if (includeBuiltins) {
87
+ for (const agent of DEFAULT_AGENTS) {
88
+ agents.set(agent.name.toLowerCase(), agent);
89
+ }
90
+ }
91
+ const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
92
+ const scanned: string[] = [];
93
+ let fileCount = 0;
94
+ let capped = false;
95
+
96
+ if (options.workspaceTrusted === false) {
97
+ diagnostics.push({
98
+ path: resolve(options.cwd),
99
+ level: "warning",
100
+ message: "Project-local agents are disabled because the workspace is not trusted.",
101
+ });
102
+ }
103
+
104
+ // Collect the highest-priority directories first: the file cap must never hide a project agent
105
+ // behind a pile of user files. Parsing still runs lowest priority first, so project files win.
106
+ const collected: Array<{ directory: AgentDirectory; files: string[] }> = [];
107
+ for (const directory of [...directories].reverse()) {
108
+ if (directory.source === "project" && options.workspaceTrusted === false) {
109
+ continue;
110
+ }
111
+ if (!existsSync(directory.path)) {
112
+ continue;
113
+ }
114
+ scanned.push(directory.path);
115
+
116
+ const files: string[] = [];
117
+ try {
118
+ // The collector reports whether it actually left agent files behind, so an exact
119
+ // `maxFiles` hit no longer warns about files that were never skipped.
120
+ if (
121
+ collectMarkdownFiles(
122
+ directory.path,
123
+ files,
124
+ diagnostics,
125
+ 0,
126
+ Math.max(0, maxFiles - fileCount),
127
+ new Set<string>(),
128
+ )
129
+ ) {
130
+ capped = true;
131
+ }
132
+ } catch (err) {
133
+ diagnostics.push({
134
+ path: directory.path,
135
+ level: "error",
136
+ message: `Could not read agent directory: ${errorMessage(err)}`,
137
+ });
138
+ continue;
139
+ }
140
+ fileCount += files.length;
141
+ collected.push({ directory, files });
142
+ }
143
+ // Listings report ascending priority.
144
+ scanned.reverse();
145
+
146
+ for (const { directory, files } of [...collected].reverse()) {
147
+ for (const file of files) {
148
+ let content: string;
149
+ try {
150
+ content = readFileSync(file, "utf8");
151
+ } catch (err) {
152
+ diagnostics.push({
153
+ path: file,
154
+ level: "error",
155
+ message: `Could not read agent file: ${errorMessage(err)}`,
156
+ });
157
+ continue;
158
+ }
159
+
160
+ const parsed = parseAgentFile(content, file, directory.source);
161
+ diagnostics.push(...parsed.diagnostics);
162
+ if (!parsed.agent) {
163
+ continue;
164
+ }
165
+
166
+ const key = parsed.agent.name.toLowerCase();
167
+ const previous = agents.get(key);
168
+ if (previous && previous.source === parsed.agent.source) {
169
+ diagnostics.push({
170
+ path: file,
171
+ level: "warning",
172
+ message: `Duplicate agent "${parsed.agent.name}" in ${parsed.agent.source} scope; ${file} overrides ${previous.filePath}.`,
173
+ });
174
+ }
175
+ agents.set(key, parsed.agent);
176
+ }
177
+ }
178
+
179
+ if (capped) {
180
+ diagnostics.push({
181
+ path: resolve(options.cwd),
182
+ level: "warning",
183
+ message: `Agent scan stopped at ${maxFiles} files; lower-priority directories were skipped.`,
184
+ });
185
+ }
186
+
187
+ const overrides = loadAgentOverrides({
188
+ cwd: options.cwd,
189
+ ...(options.homeDir !== undefined ? { homeDir: options.homeDir } : {}),
190
+ ...(options.env !== undefined ? { env: options.env } : {}),
191
+ ...(options.workspaceTrusted !== undefined ? { workspaceTrusted: options.workspaceTrusted } : {}),
192
+ });
193
+ diagnostics.push(...overrides.diagnostics);
194
+ const applied = applyAgentOverrides(agents, overrides);
195
+ diagnostics.push(...applied.diagnostics);
196
+
197
+ const ordered = [...applied.agents.values()].sort((left, right) => left.name.localeCompare(right.name));
198
+ return {
199
+ agents: ordered,
200
+ diagnostics,
201
+ directories: scanned,
202
+ configFiles: overrides.configFiles,
203
+ ...(overrides.maxConcurrent !== undefined ? { maxConcurrent: overrides.maxConcurrent } : {}),
204
+ };
205
+ }
206
+
207
+ /**
208
+ * Collect agent Markdown files under `dir` into `result`, never exceeding `remaining`.
209
+ *
210
+ * Returns `true` only when an agent file was actually skipped because of the cap. The caller turns
211
+ * that into a warning, so hitting exactly `maxFiles` with nothing left over stays silent.
212
+ */
213
+ function collectMarkdownFiles(
214
+ dir: string,
215
+ result: string[],
216
+ diagnostics: AgentDiagnostic[],
217
+ depth: number,
218
+ remaining: number,
219
+ visited: Set<string>,
220
+ ): boolean {
221
+ if (depth > MAX_DEPTH) {
222
+ return false;
223
+ }
224
+ // A dotfiles setup typically symlinks `~/.repi/agents` into another tree; following links with a
225
+ // visited set keeps those agents discoverable without recursing forever.
226
+ const key = directoryKey(dir);
227
+ if (visited.has(key)) {
228
+ return false;
229
+ }
230
+ visited.add(key);
231
+
232
+ let entries: Dirent[];
233
+ try {
234
+ entries = readdirSync(dir, { withFileTypes: true });
235
+ } catch (err) {
236
+ diagnostics.push({
237
+ path: dir,
238
+ level: "warning",
239
+ message: `Could not list agent directory: ${errorMessage(err)}`,
240
+ });
241
+ return false;
242
+ }
243
+
244
+ entries.sort((left, right) => left.name.localeCompare(right.name));
245
+ let truncated = false;
246
+ for (const entry of entries) {
247
+ if (entry.name.startsWith(".") || IGNORED_DIRS.has(entry.name)) {
248
+ continue;
249
+ }
250
+ const resolved = resolveEntry(dir, entry);
251
+ if (resolved.kind === "dir") {
252
+ if (result.length >= remaining) {
253
+ // The cap is reached: only look far enough to know whether this subtree holds agents.
254
+ if (containsAgentFile(resolved.path, depth + 1, visited)) {
255
+ truncated = true;
256
+ }
257
+ continue;
258
+ }
259
+ if (collectMarkdownFiles(resolved.path, result, diagnostics, depth + 1, remaining, visited)) {
260
+ truncated = true;
261
+ }
262
+ continue;
263
+ }
264
+ if (resolved.kind !== "file" || !isAgentFileName(entry.name)) {
265
+ continue;
266
+ }
267
+ if (result.length >= remaining) {
268
+ truncated = true;
269
+ continue;
270
+ }
271
+ result.push(resolved.path);
272
+ }
273
+ return truncated;
274
+ }
275
+
276
+ /** Cheap probe used after the file cap: does this subtree contain any agent declaration? */
277
+ function containsAgentFile(dir: string, depth: number, visited: Set<string>): boolean {
278
+ if (depth > MAX_DEPTH) {
279
+ return false;
280
+ }
281
+ const key = directoryKey(dir);
282
+ if (visited.has(key)) {
283
+ return false;
284
+ }
285
+ visited.add(key);
286
+ let entries: Dirent[];
287
+ try {
288
+ entries = readdirSync(dir, { withFileTypes: true });
289
+ } catch {
290
+ return false;
291
+ }
292
+ for (const entry of entries) {
293
+ if (entry.name.startsWith(".") || IGNORED_DIRS.has(entry.name)) {
294
+ continue;
295
+ }
296
+ const resolved = resolveEntry(dir, entry);
297
+ if (resolved.kind === "dir") {
298
+ if (containsAgentFile(resolved.path, depth + 1, visited)) {
299
+ return true;
300
+ }
301
+ continue;
302
+ }
303
+ if (resolved.kind === "file" && isAgentFileName(entry.name)) {
304
+ return true;
305
+ }
306
+ }
307
+ return false;
308
+ }
309
+
310
+ /**
311
+ * `Dirent.isFile()` / `isDirectory()` are both false for a symbolic link, which silently hid every
312
+ * agent shared through a symlinked directory. Links are followed one level deep.
313
+ */
314
+ function resolveEntry(dir: string, entry: Dirent): { kind: "file" | "dir" | "other"; path: string } {
315
+ const path = join(dir, entry.name);
316
+ if (entry.isDirectory()) {
317
+ return { kind: "dir", path };
318
+ }
319
+ if (entry.isFile()) {
320
+ return { kind: "file", path };
321
+ }
322
+ if (!entry.isSymbolicLink()) {
323
+ return { kind: "other", path };
324
+ }
325
+ try {
326
+ const target = statSync(path);
327
+ if (target.isDirectory()) {
328
+ return { kind: "dir", path };
329
+ }
330
+ if (target.isFile()) {
331
+ return { kind: "file", path };
332
+ }
333
+ } catch {
334
+ // Dangling or unreadable link: ignore it like any other non-agent entry.
335
+ }
336
+ return { kind: "other", path };
337
+ }
338
+
339
+ function directoryKey(path: string): string {
340
+ try {
341
+ return realpathSync(path);
342
+ } catch {
343
+ return path;
344
+ }
345
+ }
346
+
347
+ function isAgentFileName(name: string): boolean {
348
+ return name.endsWith(".md") && !name.endsWith(".chain.md");
349
+ }
350
+
351
+ function errorMessage(error: unknown): string {
352
+ return error instanceof Error ? error.message : String(error);
353
+ }
@@ -0,0 +1,119 @@
1
+ import { basename, isAbsolute, resolve } from "node:path";
2
+ import type { PiToolInfo } from "@restranger/repi-lib";
3
+
4
+ /**
5
+ * Built-in host extensions the child can re-create through the SDK.
6
+ *
7
+ * They are not files inside the parent package, so their `sourceInfo.path` is a
8
+ * `builtin:<name>` pseudo-path; the session factory maps these names onto the host's exported
9
+ * factories instead of `additionalExtensionPaths`.
10
+ */
11
+ export type ChildBuiltinExtension = "codemode" | "tool_search" | "mcp";
12
+
13
+ export interface ChildExtensionSources {
14
+ /** Absolute extension module files to load with `additionalExtensionPaths`. */
15
+ readonly paths: readonly string[];
16
+ /** Host built-ins to recreate with the SDK factories. */
17
+ readonly builtins: readonly ChildBuiltinExtension[];
18
+ /** Human-readable provenance labels for diagnostics and the fleet inspector. */
19
+ readonly labels: readonly string[];
20
+ /** Non-fatal notes, e.g. an inline parent extension that cannot be loaded by path. */
21
+ readonly diagnostics: readonly string[];
22
+ }
23
+
24
+ const MCP_RESOURCE_TOOLS = ["list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"] as const;
25
+
26
+ const BUILTIN_BY_TOOL = new Map<string, ChildBuiltinExtension>([
27
+ ["codemode", "codemode"],
28
+ ["tool_search", "tool_search"],
29
+ ...MCP_RESOURCE_TOOLS.map((name) => [name, "mcp"] as const),
30
+ ]);
31
+
32
+ const BUILTIN_BY_PATH = new Map<string, ChildBuiltinExtension>([
33
+ ["builtin:codemode", "codemode"],
34
+ ["builtin:tool-search", "tool_search"],
35
+ ["builtin:tool_search", "tool_search"],
36
+ ["builtin:mcp", "mcp"],
37
+ ]);
38
+
39
+ /**
40
+ * Resolve the extension surface a child needs for its requested tools.
41
+ *
42
+ * The parent's `getAllTools()` reports the exact module that registered each tool. Loading only
43
+ * those modules is the in-process equivalent of "the plugins flow into the child": the child gets
44
+ * the tools it was promised without re-instantiating every ambient extension (which would start a
45
+ * second copy of unrelated UI, provider and permission plugins in the same process).
46
+ *
47
+ * A tool registered by an inline parent factory has no reloadable path; the caller receives a
48
+ * diagnostic and the tool is simply absent from the child instead of failing the whole run.
49
+ */
50
+ export function resolveChildExtensions(
51
+ toolInfos: readonly PiToolInfo[] | undefined,
52
+ toolNames: readonly string[] | undefined,
53
+ options: { readonly cwd?: string; readonly excludePaths?: readonly string[] } = {},
54
+ ): ChildExtensionSources {
55
+ if (!toolNames || toolNames.length === 0) {
56
+ return { paths: [], builtins: [], labels: [], diagnostics: [] };
57
+ }
58
+
59
+ const byName = new Map<string, PiToolInfo>();
60
+ for (const info of toolInfos ?? []) {
61
+ if (typeof info?.name === "string") {
62
+ byName.set(info.name, info);
63
+ }
64
+ }
65
+
66
+ const excluded = new Set((options.excludePaths ?? []).map((path) => resolveExtrasPath(path, options.cwd)));
67
+ const paths: string[] = [];
68
+ const builtins: ChildBuiltinExtension[] = [];
69
+ const labels: string[] = [];
70
+ const diagnostics: string[] = [];
71
+
72
+ const addBuiltin = (name: ChildBuiltinExtension, label: string): void => {
73
+ if (!builtins.includes(name)) {
74
+ builtins.push(name);
75
+ labels.push(label);
76
+ }
77
+ };
78
+
79
+ for (const toolName of toolNames) {
80
+ const info = byName.get(toolName);
81
+ const sourcePath = info?.sourceInfo?.path;
82
+ const sourceLabel = info?.sourceInfo?.source ?? (sourcePath ? basename(sourcePath) : undefined);
83
+
84
+ if (sourcePath?.startsWith("builtin:")) {
85
+ const builtin = BUILTIN_BY_PATH.get(sourcePath) ?? BUILTIN_BY_TOOL.get(toolName);
86
+ if (builtin) {
87
+ addBuiltin(builtin, sourceLabel && sourceLabel !== "builtin" ? sourceLabel : `builtin:${builtin}`);
88
+ }
89
+ continue;
90
+ }
91
+
92
+ if (sourcePath?.startsWith("<inline:")) {
93
+ diagnostics.push(
94
+ `Tool "${toolName}" comes from an inline extension (${sourcePath}) and cannot be reloaded in a child session.`,
95
+ );
96
+ continue;
97
+ }
98
+
99
+ if (sourcePath) {
100
+ const absolute = resolveExtrasPath(sourcePath, options.cwd);
101
+ if (!excluded.has(absolute) && !paths.includes(absolute)) {
102
+ paths.push(absolute);
103
+ labels.push(sourceLabel ?? basename(absolute));
104
+ }
105
+ continue;
106
+ }
107
+
108
+ const builtin = BUILTIN_BY_TOOL.get(toolName);
109
+ if (builtin) {
110
+ addBuiltin(builtin, sourceLabel ?? `builtin:${builtin}`);
111
+ }
112
+ }
113
+
114
+ return { paths, builtins, labels, diagnostics };
115
+ }
116
+
117
+ function resolveExtrasPath(path: string, cwd: string | undefined): string {
118
+ return isAbsolute(path) ? path : resolve(cwd ?? process.cwd(), path);
119
+ }