-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathagents.ts
More file actions
251 lines (212 loc) · 6.4 KB
/
agents.ts
File metadata and controls
251 lines (212 loc) · 6.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/**
* Agent discovery and configuration
*/
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import { KNOWN_FIELDS } from "./agent-serializer.js";
import { parseChain } from "./chain-serializer.js";
import { mergeAgentsForScope } from "./agent-selection.js";
import { parseFrontmatter } from "./frontmatter.js";
export type AgentScope = "user" | "project" | "both";
export type AgentSource = "builtin" | "user" | "project";
export interface AgentConfig {
name: string;
description: string;
tools?: string[];
mcpDirectTools?: string[];
model?: string;
thinking?: string;
systemPrompt: string;
source: AgentSource;
filePath: string;
skills?: string[];
extensions?: string[];
// Chain behavior fields
output?: string;
defaultReads?: string[];
defaultProgress?: boolean;
interactive?: boolean;
extraFields?: Record<string, string>;
}
export interface ChainStepConfig {
agent: string;
task: string;
output?: string | false;
reads?: string[] | false;
model?: string;
skills?: string[] | false;
progress?: boolean;
}
export interface ChainConfig {
name: string;
description: string;
source: AgentSource;
filePath: string;
steps: ChainStepConfig[];
extraFields?: Record<string, string>;
}
export interface AgentDiscoveryResult {
agents: AgentConfig[];
projectAgentsDir: string | null;
}
function loadAgentsFromDir(dir: string, source: AgentSource): AgentConfig[] {
const agents: AgentConfig[] = [];
if (!fs.existsSync(dir)) {
return agents;
}
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return agents;
}
for (const entry of entries) {
if (!entry.name.endsWith(".md")) continue;
if (entry.name.endsWith(".chain.md")) continue;
if (!entry.isFile() && !entry.isSymbolicLink()) continue;
const filePath = path.join(dir, entry.name);
let content: string;
try {
content = fs.readFileSync(filePath, "utf-8");
} catch {
continue;
}
const { frontmatter, body } = parseFrontmatter(content);
if (!frontmatter.name || !frontmatter.description) {
continue;
}
const rawTools = frontmatter.tools
?.split(",")
.map((t) => t.trim())
.filter(Boolean);
const mcpDirectTools: string[] = [];
const tools: string[] = [];
if (rawTools) {
for (const tool of rawTools) {
if (tool.startsWith("mcp:")) {
mcpDirectTools.push(tool.slice(4));
} else {
tools.push(tool);
}
}
}
// Parse defaultReads as comma-separated list (like tools)
const defaultReads = frontmatter.defaultReads
?.split(",")
.map((f) => f.trim())
.filter(Boolean);
const skillStr = frontmatter.skill || frontmatter.skills;
const skills = skillStr
?.split(",")
.map((s) => s.trim())
.filter(Boolean);
let extensions: string[] | undefined;
if (frontmatter.extensions !== undefined) {
extensions = frontmatter.extensions
.split(",")
.map((e) => e.trim())
.filter(Boolean);
}
const extraFields: Record<string, string> = {};
for (const [key, value] of Object.entries(frontmatter)) {
if (!KNOWN_FIELDS.has(key)) extraFields[key] = value;
}
agents.push({
name: frontmatter.name,
description: frontmatter.description,
tools: tools.length > 0 ? tools : undefined,
mcpDirectTools: mcpDirectTools.length > 0 ? mcpDirectTools : undefined,
model: frontmatter.model,
thinking: frontmatter.thinking,
systemPrompt: body,
source,
filePath,
skills: skills && skills.length > 0 ? skills : undefined,
extensions,
// Chain behavior fields
output: frontmatter.output,
defaultReads: defaultReads && defaultReads.length > 0 ? defaultReads : undefined,
defaultProgress: frontmatter.defaultProgress === "true",
interactive: frontmatter.interactive === "true",
extraFields: Object.keys(extraFields).length > 0 ? extraFields : undefined,
});
}
return agents;
}
function loadChainsFromDir(dir: string, source: AgentSource): ChainConfig[] {
const chains: ChainConfig[] = [];
if (!fs.existsSync(dir)) {
return chains;
}
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return chains;
}
for (const entry of entries) {
if (!entry.name.endsWith(".chain.md")) continue;
if (!entry.isFile() && !entry.isSymbolicLink()) continue;
const filePath = path.join(dir, entry.name);
let content: string;
try {
content = fs.readFileSync(filePath, "utf-8");
} catch {
continue;
}
try {
chains.push(parseChain(content, source, filePath));
} catch {
continue;
}
}
return chains;
}
function isDirectory(p: string): boolean {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
function findNearestProjectAgentsDir(cwd: string): string | null {
let currentDir = cwd;
while (true) {
const candidate = path.join(currentDir, ".pi", "agents");
if (isDirectory(candidate)) return candidate;
const parentDir = path.dirname(currentDir);
if (parentDir === currentDir) return null;
currentDir = parentDir;
}
}
const BUILTIN_AGENTS_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "agents");
export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryResult {
const userDir = path.join(os.homedir(), ".pi", "agent", "agents");
const projectAgentsDir = findNearestProjectAgentsDir(cwd);
const builtinAgents = loadAgentsFromDir(BUILTIN_AGENTS_DIR, "builtin");
const userAgents = scope === "project" ? [] : loadAgentsFromDir(userDir, "user");
const projectAgents = scope === "user" || !projectAgentsDir ? [] : loadAgentsFromDir(projectAgentsDir, "project");
const agents = mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents);
return { agents, projectAgentsDir };
}
export function discoverAgentsAll(cwd: string): {
builtin: AgentConfig[];
user: AgentConfig[];
project: AgentConfig[];
chains: ChainConfig[];
userDir: string;
projectDir: string | null;
} {
const userDir = path.join(os.homedir(), ".pi", "agent", "agents");
const projectDir = findNearestProjectAgentsDir(cwd);
const builtin = loadAgentsFromDir(BUILTIN_AGENTS_DIR, "builtin");
const user = loadAgentsFromDir(userDir, "user");
const project = projectDir ? loadAgentsFromDir(projectDir, "project") : [];
const chains = [
...loadChainsFromDir(userDir, "user"),
...(projectDir ? loadChainsFromDir(projectDir, "project") : []),
];
return { builtin, user, project, chains, userDir, projectDir };
}