@johnnywu/pi-agent-profiles 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +120 -2
- package/dist/agent-profile.d.ts +52 -0
- package/dist/agent-profile.js +215 -0
- package/dist/agent-prompt.d.ts +16 -0
- package/dist/agent-prompt.js +71 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/package.json +33 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 jwu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,121 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-agent-profiles
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@johnnywu/pi-agent-profiles` is a shared library for loading Markdown agent profiles and applying them to Pi's system prompt. It supports Pi 1.6 and later in the 1.x series.
|
|
4
|
+
|
|
5
|
+
## Agent definitions
|
|
6
|
+
|
|
7
|
+
`loadAgentDefinitions()` scans `~/.pi/agent/agents/*.md` and `<cwd>/.pi/agents/*.md`. A project definition overrides a global definition with the same `name`. Within one directory, the first valid definition in filename order wins. Invalid definitions are skipped and returned as warnings with their file paths. `PI_CODING_AGENT_DIR` changes the base directory for global definitions.
|
|
8
|
+
|
|
9
|
+
```markdown
|
|
10
|
+
---
|
|
11
|
+
name: reviewer
|
|
12
|
+
description: "Reviews changes for correctness and test coverage."
|
|
13
|
+
models: anthropic/claude-sonnet-4-6, magpie/claude/*, deep-*
|
|
14
|
+
thinking: high
|
|
15
|
+
tools: read, grep, find, ls, subagent
|
|
16
|
+
skills: review-*, tdd
|
|
17
|
+
allowedAgents: scout, test-writer
|
|
18
|
+
maxDepth: 2
|
|
19
|
+
systemPrompt: replace
|
|
20
|
+
debug: false
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
Review the changes. Report actionable findings with file and line references.
|
|
24
|
+
|
|
25
|
+
<pi-subagents-runtime-tools />
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Start the file with a `---` block containing one `key: value` entry per line. The parser trims surrounding whitespace and strips quotes from the edges of a value. Blank lines and full-line `#` comments are ignored inside the block. Write lists as comma-separated values on one line (for example, `tools: read, grep`). The parser trims each item and skips empty items. Inline comments, YAML sequences, and multiline values have no special syntax. Field names are case-sensitive. The Markdown after the closing `---` is the agent prompt.
|
|
29
|
+
|
|
30
|
+
## Field reference
|
|
31
|
+
|
|
32
|
+
| Field | Default | Syntax and behavior |
|
|
33
|
+
| --- | --- | --- |
|
|
34
|
+
| `name` | Required | Non-empty string used to look up the profile. It can differ from the filename. |
|
|
35
|
+
| `description` | Omitted | Optional single-line summary for callers that display profile information. The Markdown body supplies the prompt. |
|
|
36
|
+
| `models` | Any model allowed | Comma-separated model IDs, provider-qualified IDs, or `*` patterns. See [Model selection](#model-selection). |
|
|
37
|
+
| `thinking` | `off` | One of `off`, `minimal`, `low`, `medium`, `high`, or `xhigh`. The launcher requests this reasoning level for the session. Pi may clamp it to the selected model's capabilities. |
|
|
38
|
+
| `tools` | Entry point's existing tool selection | Comma-separated tool names and `*` patterns, or a list of `+name` and `-name` entries. See [Tool selection](#tool-selection). |
|
|
39
|
+
| `skills` | No skills in the profile prompt | Comma-separated skill names or `*` patterns such as `review-*`. Matches the skill's declared `name` against the entry point's discovered skills. |
|
|
40
|
+
| `allowedAgents` | No additional name restriction | Comma-separated exact profile names for delegation, such as `scout, test-writer`. See [Delegation](#delegation). |
|
|
41
|
+
| `maxDepth` | `10` | Non-negative safe integer for the depth of delegated sessions. See [Delegation](#delegation). |
|
|
42
|
+
| `systemPrompt` | `append` | One of `append`, `replace`, or `replace-all`. See [Prompt composition](#prompt-composition). |
|
|
43
|
+
| `debug` | `false` | `true` or `false` in lowercase. With `true`, the launchers write `debug-system-prompt.md` in the session working directory when a turn starts, overwriting the previous copy. |
|
|
44
|
+
|
|
45
|
+
### Model selection
|
|
46
|
+
|
|
47
|
+
- `models: anthropic/claude-sonnet-4-6, magpie/claude/*, deep-*` allows three kinds of entries. A provider-qualified entry matches the full selection. An unqualified entry such as `deep-*` also matches the model ID portion of a qualified selection.
|
|
48
|
+
- `subagent` and `hc_run` accept an optional `model` argument. A selection outside a configured list fails before launch. Leave it out to use the first `models` entry. If that entry is a pattern, the launcher takes the first matching model in Pi's available catalog. A pattern with no available match produces an error even if later entries could match.
|
|
49
|
+
- `pi --agent` applies the first entry to the current session. If model selection or activation fails, it warns and keeps the current model.
|
|
50
|
+
- An omitted or empty `models` list allows any caller selection. With no explicit selection, Pi keeps its normal model selection. Rename old `model:` fields to `models:`. A profile that still contains `model:` is rejected with a migration message.
|
|
51
|
+
|
|
52
|
+
### Tool selection
|
|
53
|
+
|
|
54
|
+
| Example | Behavior |
|
|
55
|
+
| --- | --- |
|
|
56
|
+
| `tools: read, hc_*` | Select tools by exact name or by a `*` pattern. |
|
|
57
|
+
| `tools: +grep, -write` | Add and remove exact names in list order. Child Pi sessions start from their default selection. `pi --agent` starts from the current session's active tools. |
|
|
58
|
+
| `tools:` or omitted | Keep the entry point's existing tool selection. |
|
|
59
|
+
| `tools: read, -write` or `tools: +hc_*` | Reject the profile. Use names and patterns together, or modifiers exclusively. Modifiers require exact tool names. |
|
|
60
|
+
|
|
61
|
+
`pi-subagents` passes the list to the child Pi's `--tools`. `pi-herdr-agents` does the same and maps the exact `subagent` name to `hc_run`, preserving any `+` or `-` prefix. For a non-empty list, Herdr also adds `hc_send` and `hc_agents` for reporting, using `+` entries in modifier mode. Pi applies its own tool availability and MCP exposure rules.
|
|
62
|
+
|
|
63
|
+
`pi --agent` resolves names and patterns against registered tools, warns about entries with no match, and applies the result to the current session's active tool list. A non-empty allowlist with zero matches clears the active selection.
|
|
64
|
+
|
|
65
|
+
### Skills
|
|
66
|
+
|
|
67
|
+
Use `skills: review-*, tdd` to select matching skills or `skills: *` to select all discovered skills. `*` matches zero or more characters. Names and patterns are case-sensitive. An empty or omitted list leaves the profile prompt's skill selection empty. The shared prompt helper returns unmatched entries so each extension can report them. Pi renders the selected skill metadata in the system prompt.
|
|
68
|
+
|
|
69
|
+
### Delegation
|
|
70
|
+
|
|
71
|
+
`allowedAgents` restricts which named profiles a delegation tool can launch. Omit it or leave it empty to add no name restriction. The applicable delegation tool must also be available in the session.
|
|
72
|
+
|
|
73
|
+
| Entry point | `allowedAgents` | `maxDepth` |
|
|
74
|
+
| --- | --- | --- |
|
|
75
|
+
| `pi-subagents` | Filters the named agents offered by the child `subagent` tool when the launcher can pass a non-empty list of matching names. | The child `subagent` tool is disabled when the child depth exceeds the profile limit. |
|
|
76
|
+
| `pi-herdr-agents` | Intersects the profile list with any inherited list. When restricted, `hc_run` requires an allowed agent name. | Inherits the stricter of the profile limit and the parent limit. Exceeding it disables `hc_run` in the child. |
|
|
77
|
+
| `pi --agent` | Configures the `subagent` tool when the `pi-subagents` extension is loaded. | The field is parsed. `custom-agent` does not set a depth limit for the current session. |
|
|
78
|
+
|
|
79
|
+
The first delegated child starts at depth `1`. A child at depth `1` with `maxDepth: 0` cannot delegate further through its launcher. With `maxDepth: 1`, that child is still at the limit and may delegate if its tools and agent scope permit it. Each launch increments the depth. `pi-subagents` sets the new child's limit from the new profile, while Herdr also carries forward the inherited limit.
|
|
80
|
+
|
|
81
|
+
### Prompt composition
|
|
82
|
+
|
|
83
|
+
| `systemPrompt` | Base prompt | Project context | Profile body and tools |
|
|
84
|
+
| --- | --- | --- | --- |
|
|
85
|
+
| `append` | Keep Pi's base prompt | Keep | Append the Markdown body after any existing addendum. Pi renders its normal tool information. |
|
|
86
|
+
| `replace` | Use the profile's custom preamble | Keep | Render the Markdown body with the visible runtime tool list and guidelines. |
|
|
87
|
+
| `replace-all` | Use the profile's custom preamble | Omit | Render the same replacement prompt with the project context cleared. The child launchers also pass `--no-context-files`. |
|
|
88
|
+
|
|
89
|
+
All modes apply the profile's `skills` selection. In replacement modes, put `<pi-subagents-runtime-tools />` in the body to place the tool list and guidelines at that point. By default, they follow the body. In `append` mode, the marker is removed.
|
|
90
|
+
|
|
91
|
+
## Extension integration
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { applyAgentProfile, loadAgentDefinitions } from '@johnnywu/pi-agent-profiles';
|
|
95
|
+
|
|
96
|
+
const { agents, warnings } = await loadAgentDefinitions({ cwd: workspace });
|
|
97
|
+
const profile = agents.find((agent) => agent.name === selectedName);
|
|
98
|
+
// Report warnings and handle an unknown agent in the calling extension.
|
|
99
|
+
if (profile) {
|
|
100
|
+
pi.on('before_agent_start', (event) => {
|
|
101
|
+
const { missingSkills } = applyAgentProfile(profile, event.systemPromptOptions);
|
|
102
|
+
// Report missingSkills through the extension's UI or tool result.
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Use `loadAgentFromPath(path, cwd)` for an explicit Markdown path, or `parseAgentProfile(content, path, source)` when the caller already has the contents. `loadAgentDefinitions` also accepts `agentDir`, `globalDir`, and `projectDir` overrides.
|
|
108
|
+
|
|
109
|
+
Call `selectAgentModel(profile, requestedModel, getAvailableModels)` to select or validate a model before activation. Child launchers can pass `profile.tools` to Pi's `--tools`. Current-session extensions can call `selectAgentTools(entries, available, active)` to resolve the declared selection and get unmatched entries. `selectAgentSkills` and `formatRuntimeTools` expose the skill matching and tool formatting independently.
|
|
110
|
+
|
|
111
|
+
The integrating extension sets the model, thinking level, and tools, and handles delegation and debug output. Apply the profile after configuring the tools so the rendered tool descriptions reflect the active selection.
|
|
112
|
+
|
|
113
|
+
## Development
|
|
114
|
+
|
|
115
|
+
```sh
|
|
116
|
+
bun install
|
|
117
|
+
bun run lint
|
|
118
|
+
bun test
|
|
119
|
+
bun run build
|
|
120
|
+
npm pack --dry-run
|
|
121
|
+
```
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
declare const thinkingLevels: readonly ["off", "minimal", "low", "medium", "high", "xhigh"];
|
|
2
|
+
declare const promptModes: readonly ["append", "replace", "replace-all"];
|
|
3
|
+
export type AgentSource = 'global' | 'project' | 'path';
|
|
4
|
+
export type ThinkingLevel = (typeof thinkingLevels)[number];
|
|
5
|
+
export type SystemPromptMode = (typeof promptModes)[number];
|
|
6
|
+
export interface AgentProfile {
|
|
7
|
+
name: string;
|
|
8
|
+
description?: string;
|
|
9
|
+
models?: string[];
|
|
10
|
+
thinking: ThinkingLevel;
|
|
11
|
+
tools: string[];
|
|
12
|
+
skills?: string[];
|
|
13
|
+
allowedAgents?: string[];
|
|
14
|
+
maxDepth: number;
|
|
15
|
+
debug: boolean;
|
|
16
|
+
systemPromptMode: SystemPromptMode;
|
|
17
|
+
prompt: string;
|
|
18
|
+
source: AgentSource;
|
|
19
|
+
filePath: string;
|
|
20
|
+
}
|
|
21
|
+
export interface AgentDefinitionWarning {
|
|
22
|
+
filePath: string;
|
|
23
|
+
message: string;
|
|
24
|
+
}
|
|
25
|
+
export interface AgentDefinitions {
|
|
26
|
+
agents: AgentProfile[];
|
|
27
|
+
warnings: AgentDefinitionWarning[];
|
|
28
|
+
}
|
|
29
|
+
export interface LoadAgentDefinitionsOptions {
|
|
30
|
+
cwd?: string;
|
|
31
|
+
agentDir?: string;
|
|
32
|
+
globalDir?: string;
|
|
33
|
+
projectDir?: string;
|
|
34
|
+
fs?: AgentDefinitionFs;
|
|
35
|
+
}
|
|
36
|
+
export interface AgentDefinitionFs {
|
|
37
|
+
listFiles(dir: string): Promise<string[]>;
|
|
38
|
+
readFile(filePath: string): Promise<string>;
|
|
39
|
+
}
|
|
40
|
+
export declare function parseAgentProfile(content: string, filePath: string, source?: AgentSource): AgentProfile;
|
|
41
|
+
export declare function wildcardMatcher(pattern: string): RegExp;
|
|
42
|
+
export declare function selectAgentModel(profile: Pick<AgentProfile, 'name' | 'models'> | undefined, requestedModel?: string, getAvailableModels?: () => readonly {
|
|
43
|
+
provider: string;
|
|
44
|
+
id: string;
|
|
45
|
+
}[]): string | undefined;
|
|
46
|
+
export declare function selectAgentTools(entries: readonly string[], available: readonly string[], active: readonly string[]): {
|
|
47
|
+
selected: string[];
|
|
48
|
+
missing: string[];
|
|
49
|
+
};
|
|
50
|
+
export declare function loadAgentFromPath(selector: string, cwd?: string): Promise<AgentProfile>;
|
|
51
|
+
export declare function loadAgentDefinitions(options?: LoadAgentDefinitionsOptions): Promise<AgentDefinitions>;
|
|
52
|
+
export {};
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
const thinkingLevels = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh'];
|
|
5
|
+
const promptModes = ['append', 'replace', 'replace-all'];
|
|
6
|
+
const defaultFs = {
|
|
7
|
+
async listFiles(dir) {
|
|
8
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
9
|
+
return entries
|
|
10
|
+
.filter((entry) => entry.isFile() || entry.isSymbolicLink())
|
|
11
|
+
.map((entry) => join(dir, entry.name));
|
|
12
|
+
},
|
|
13
|
+
readFile(filePath) {
|
|
14
|
+
return readFile(filePath, 'utf8');
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
function errorMessage(error) {
|
|
18
|
+
return error instanceof Error ? error.message : String(error);
|
|
19
|
+
}
|
|
20
|
+
function csv(value = '') {
|
|
21
|
+
return value
|
|
22
|
+
.split(',')
|
|
23
|
+
.map((item) => item.trim())
|
|
24
|
+
.filter(Boolean);
|
|
25
|
+
}
|
|
26
|
+
function choice(field, value, choices) {
|
|
27
|
+
const match = choices.find((item) => item === (value ?? choices[0]));
|
|
28
|
+
if (!match)
|
|
29
|
+
throw new Error(`invalid ${field}: ${value}`);
|
|
30
|
+
return match;
|
|
31
|
+
}
|
|
32
|
+
export function parseAgentProfile(content, filePath, source = 'path') {
|
|
33
|
+
const normalized = content.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
|
|
34
|
+
if (!normalized.startsWith('---\n'))
|
|
35
|
+
throw new Error('missing frontmatter');
|
|
36
|
+
const match = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(normalized);
|
|
37
|
+
if (!match)
|
|
38
|
+
throw new Error('missing frontmatter terminator');
|
|
39
|
+
// The original scalar format allows bare wildcards and comma-separated names.
|
|
40
|
+
const fields = new Map();
|
|
41
|
+
for (const line of match[1].split('\n')) {
|
|
42
|
+
const trimmed = line.trim();
|
|
43
|
+
if (!trimmed || trimmed.startsWith('#'))
|
|
44
|
+
continue;
|
|
45
|
+
const separator = trimmed.indexOf(':');
|
|
46
|
+
if (separator === -1)
|
|
47
|
+
throw new Error(`invalid frontmatter line: ${line}`);
|
|
48
|
+
const key = trimmed.slice(0, separator).trim();
|
|
49
|
+
if (!key)
|
|
50
|
+
throw new Error(`invalid frontmatter key: ${line}`);
|
|
51
|
+
fields.set(key, trimmed
|
|
52
|
+
.slice(separator + 1)
|
|
53
|
+
.trim()
|
|
54
|
+
.replace(/^['"]|['"]$/g, ''));
|
|
55
|
+
}
|
|
56
|
+
if (fields.has('model'))
|
|
57
|
+
throw new Error('The `model` field is no longer supported. Please use `models` instead.');
|
|
58
|
+
const name = fields.get('name');
|
|
59
|
+
if (!name)
|
|
60
|
+
throw new Error('missing required field: name');
|
|
61
|
+
const thinking = choice('thinking', fields.get('thinking'), thinkingLevels);
|
|
62
|
+
const systemPromptMode = choice('systemPrompt', fields.get('systemPrompt'), promptModes);
|
|
63
|
+
const maxDepth = Number(fields.get('maxDepth') ?? 10);
|
|
64
|
+
if (!Number.isSafeInteger(maxDepth) || maxDepth < 0) {
|
|
65
|
+
throw new Error(`invalid maxDepth: ${fields.get('maxDepth')}`);
|
|
66
|
+
}
|
|
67
|
+
const debug = fields.get('debug');
|
|
68
|
+
if (debug !== undefined && debug !== 'true' && debug !== 'false') {
|
|
69
|
+
throw new Error(`invalid debug: ${debug}`);
|
|
70
|
+
}
|
|
71
|
+
const models = csv(fields.get('models'));
|
|
72
|
+
const tools = csv(fields.get('tools'));
|
|
73
|
+
validateToolList(tools);
|
|
74
|
+
const skills = csv(fields.get('skills'));
|
|
75
|
+
const allowedAgents = csv(fields.get('allowedAgents'));
|
|
76
|
+
return {
|
|
77
|
+
name,
|
|
78
|
+
description: fields.get('description') || undefined,
|
|
79
|
+
models: models.length ? models : undefined,
|
|
80
|
+
thinking,
|
|
81
|
+
tools,
|
|
82
|
+
skills: skills.length ? skills : undefined,
|
|
83
|
+
allowedAgents: allowedAgents.length ? allowedAgents : undefined,
|
|
84
|
+
maxDepth,
|
|
85
|
+
debug: debug === 'true',
|
|
86
|
+
systemPromptMode,
|
|
87
|
+
prompt: normalized
|
|
88
|
+
.slice(match[0].length)
|
|
89
|
+
.replace(/^\n+/, '')
|
|
90
|
+
.replaceAll('<pi-runtime-tools />', ''),
|
|
91
|
+
source,
|
|
92
|
+
filePath,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
export function wildcardMatcher(pattern) {
|
|
96
|
+
const expression = pattern
|
|
97
|
+
.split('*')
|
|
98
|
+
.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
|
|
99
|
+
.join('.*');
|
|
100
|
+
return new RegExp(`^${expression}$`);
|
|
101
|
+
}
|
|
102
|
+
export function selectAgentModel(profile, requestedModel, getAvailableModels) {
|
|
103
|
+
const requested = requestedModel?.trim() || undefined;
|
|
104
|
+
const allowed = profile?.models;
|
|
105
|
+
if (!profile || !allowed?.length)
|
|
106
|
+
return requested;
|
|
107
|
+
if (requested) {
|
|
108
|
+
const modelId = requested.slice(requested.indexOf('/') + 1);
|
|
109
|
+
if (!requested.includes('*') &&
|
|
110
|
+
allowed.some((pattern) => {
|
|
111
|
+
const matches = wildcardMatcher(pattern);
|
|
112
|
+
return matches.test(requested) || (!pattern.includes('/') && matches.test(modelId));
|
|
113
|
+
})) {
|
|
114
|
+
return requested;
|
|
115
|
+
}
|
|
116
|
+
throw new Error(`Model "${requested}" is not allowed for agent "${profile.name}". Allowed models: ${allowed.join(', ')}.`);
|
|
117
|
+
}
|
|
118
|
+
const first = allowed[0];
|
|
119
|
+
if (!first.includes('*'))
|
|
120
|
+
return first;
|
|
121
|
+
const matches = wildcardMatcher(first);
|
|
122
|
+
for (const { provider, id } of getAvailableModels?.() ?? []) {
|
|
123
|
+
const qualified = `${provider}/${id}`;
|
|
124
|
+
if (matches.test(qualified) || (!first.includes('/') && matches.test(id)))
|
|
125
|
+
return qualified;
|
|
126
|
+
}
|
|
127
|
+
throw new Error(`No available models match default pattern "${first}" for agent "${profile.name}".`);
|
|
128
|
+
}
|
|
129
|
+
function isToolModifier(entry) {
|
|
130
|
+
return entry.startsWith('+') || entry.startsWith('-');
|
|
131
|
+
}
|
|
132
|
+
function validateToolList(entries) {
|
|
133
|
+
const modifiers = entries.filter(isToolModifier);
|
|
134
|
+
if (modifiers.length && modifiers.length !== entries.length) {
|
|
135
|
+
throw new Error('invalid tools: tool names cannot be mixed with +name or -name entries');
|
|
136
|
+
}
|
|
137
|
+
const pattern = modifiers.find((entry) => entry.includes('*'));
|
|
138
|
+
if (pattern) {
|
|
139
|
+
throw new Error(`invalid tools: +name and -name entries take exact tool names, not patterns: ${pattern}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
export function selectAgentTools(entries, available, active) {
|
|
143
|
+
validateToolList(entries);
|
|
144
|
+
if (!entries.length)
|
|
145
|
+
return { selected: [...active], missing: [] };
|
|
146
|
+
const missing = new Set();
|
|
147
|
+
if (isToolModifier(entries[0])) {
|
|
148
|
+
const availableNames = new Set(available);
|
|
149
|
+
const selected = new Set(active);
|
|
150
|
+
for (const entry of entries) {
|
|
151
|
+
const name = entry.slice(1);
|
|
152
|
+
if (!availableNames.has(name)) {
|
|
153
|
+
missing.add(entry);
|
|
154
|
+
}
|
|
155
|
+
else if (entry.startsWith('+')) {
|
|
156
|
+
selected.add(name);
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
selected.delete(name);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return { selected: [...selected], missing: [...missing] };
|
|
163
|
+
}
|
|
164
|
+
const selected = new Set();
|
|
165
|
+
for (const entry of entries) {
|
|
166
|
+
const pattern = wildcardMatcher(entry);
|
|
167
|
+
const matches = available.filter((name) => pattern.test(name));
|
|
168
|
+
if (!matches.length)
|
|
169
|
+
missing.add(entry);
|
|
170
|
+
for (const name of matches)
|
|
171
|
+
selected.add(name);
|
|
172
|
+
}
|
|
173
|
+
return { selected: [...selected], missing: [...missing] };
|
|
174
|
+
}
|
|
175
|
+
export async function loadAgentFromPath(selector, cwd = process.cwd()) {
|
|
176
|
+
const input = selector.trim();
|
|
177
|
+
const filePath = resolve(cwd, /^~[/\\]/.test(input) ? join(homedir(), input.slice(2)) : input);
|
|
178
|
+
if (!filePath.toLowerCase().endsWith('.md'))
|
|
179
|
+
throw new Error('agent path must point to a .md file');
|
|
180
|
+
return parseAgentProfile(await readFile(filePath, 'utf8'), filePath);
|
|
181
|
+
}
|
|
182
|
+
export async function loadAgentDefinitions(options = {}) {
|
|
183
|
+
const cwd = options.cwd ?? process.cwd();
|
|
184
|
+
const agentDir = options.agentDir ?? (process.env.PI_CODING_AGENT_DIR || join(homedir(), '.pi', 'agent'));
|
|
185
|
+
const dirs = [
|
|
186
|
+
[resolve(options.globalDir ?? join(agentDir, 'agents')), 'global'],
|
|
187
|
+
[resolve(cwd, options.projectDir ?? join('.pi', 'agents')), 'project'],
|
|
188
|
+
];
|
|
189
|
+
const warnings = [];
|
|
190
|
+
const byName = new Map();
|
|
191
|
+
const fileSystem = options.fs ?? defaultFs;
|
|
192
|
+
for (const [dir, source] of dirs) {
|
|
193
|
+
const files = await fileSystem.listFiles(dir).catch((error) => {
|
|
194
|
+
if (error.code !== 'ENOENT')
|
|
195
|
+
warnings.push({ filePath: dir, message: errorMessage(error) });
|
|
196
|
+
return [];
|
|
197
|
+
});
|
|
198
|
+
const seen = new Set();
|
|
199
|
+
for (const filePath of [...files].sort()) {
|
|
200
|
+
if (!filePath.endsWith('.md'))
|
|
201
|
+
continue;
|
|
202
|
+
try {
|
|
203
|
+
const agent = parseAgentProfile(await fileSystem.readFile(filePath), filePath, source);
|
|
204
|
+
if (seen.has(agent.name))
|
|
205
|
+
continue;
|
|
206
|
+
seen.add(agent.name);
|
|
207
|
+
byName.set(agent.name, agent);
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
warnings.push({ filePath, message: errorMessage(error) });
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return { agents: [...byName.values()], warnings };
|
|
215
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { NormalizedBuildSystemPromptOptions } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { type AgentProfile } from './agent-profile.js';
|
|
3
|
+
export interface SkillSelection<T> {
|
|
4
|
+
selected: T[];
|
|
5
|
+
missing: string[];
|
|
6
|
+
}
|
|
7
|
+
export declare function selectAgentSkills<T extends {
|
|
8
|
+
name: string;
|
|
9
|
+
}>(patterns: readonly string[], available: readonly T[]): SkillSelection<T>;
|
|
10
|
+
type ToolPromptOptions = Pick<NormalizedBuildSystemPromptOptions, 'selectedTools' | 'hiddenTools' | 'toolSnippets' | 'toolGuidelines' | 'promptGuidelines'>;
|
|
11
|
+
export declare function formatRuntimeTools(options: ToolPromptOptions): string;
|
|
12
|
+
export interface AgentPromptResult {
|
|
13
|
+
missingSkills: string[];
|
|
14
|
+
}
|
|
15
|
+
export declare function applyAgentProfile(profile: Pick<AgentProfile, 'prompt' | 'systemPromptMode' | 'skills'>, options: NormalizedBuildSystemPromptOptions): AgentPromptResult;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { wildcardMatcher } from './agent-profile.js';
|
|
2
|
+
const runtimeToolsMarker = '<pi-subagents-runtime-tools />';
|
|
3
|
+
export function selectAgentSkills(patterns, available) {
|
|
4
|
+
const byName = new Map();
|
|
5
|
+
for (const skill of available) {
|
|
6
|
+
if (!byName.has(skill.name))
|
|
7
|
+
byName.set(skill.name, skill);
|
|
8
|
+
}
|
|
9
|
+
const selected = new Map();
|
|
10
|
+
const missing = new Set();
|
|
11
|
+
for (const pattern of patterns) {
|
|
12
|
+
const exact = byName.get(pattern);
|
|
13
|
+
let matches = exact ? [exact] : [];
|
|
14
|
+
if (pattern.includes('*')) {
|
|
15
|
+
const matcher = wildcardMatcher(pattern);
|
|
16
|
+
matches = [...byName.values()].filter((skill) => matcher.test(skill.name));
|
|
17
|
+
}
|
|
18
|
+
if (!matches.length)
|
|
19
|
+
missing.add(pattern);
|
|
20
|
+
for (const skill of matches)
|
|
21
|
+
selected.set(skill.name, skill);
|
|
22
|
+
}
|
|
23
|
+
return { selected: [...selected.values()], missing: [...missing] };
|
|
24
|
+
}
|
|
25
|
+
export function formatRuntimeTools(options) {
|
|
26
|
+
const visible = options.selectedTools.filter((name) => !options.hiddenTools.includes(name));
|
|
27
|
+
const toolLines = visible.map((name) => {
|
|
28
|
+
const snippet = options.toolSnippets[name];
|
|
29
|
+
return snippet ? `- ${name}: ${snippet}` : `- ${name}`;
|
|
30
|
+
});
|
|
31
|
+
const shellOnly = visible.includes('bash') && !['grep', 'find', 'ls'].some((name) => visible.includes(name));
|
|
32
|
+
const guidelines = new Set([
|
|
33
|
+
...(shellOnly ? ['Use bash for file operations like ls, rg, find'] : []),
|
|
34
|
+
...visible.flatMap((name) => options.toolGuidelines[name] ?? []),
|
|
35
|
+
...options.promptGuidelines,
|
|
36
|
+
'Be concise in your responses',
|
|
37
|
+
'Show file paths clearly when working with files',
|
|
38
|
+
]
|
|
39
|
+
.map((line) => line.trim())
|
|
40
|
+
.filter(Boolean));
|
|
41
|
+
return [
|
|
42
|
+
'Available tools:',
|
|
43
|
+
...(toolLines.length ? toolLines : ['(none)']),
|
|
44
|
+
'',
|
|
45
|
+
'Guidelines:',
|
|
46
|
+
...[...guidelines].map((line) => `- ${line}`),
|
|
47
|
+
].join('\n');
|
|
48
|
+
}
|
|
49
|
+
export function applyAgentProfile(profile, options) {
|
|
50
|
+
const { selected, missing } = selectAgentSkills(profile.skills ?? [], options.skills);
|
|
51
|
+
options.skills = selected;
|
|
52
|
+
if (profile.systemPromptMode === 'append') {
|
|
53
|
+
const prompt = profile.prompt.replaceAll(runtimeToolsMarker, '').trim();
|
|
54
|
+
if (prompt)
|
|
55
|
+
options.appendSystemPrompt = [options.appendSystemPrompt, prompt]
|
|
56
|
+
.filter(Boolean)
|
|
57
|
+
.join('\n\n');
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
const tools = formatRuntimeTools(options);
|
|
61
|
+
options.customPrompt = profile.prompt.includes(runtimeToolsMarker)
|
|
62
|
+
? profile.prompt
|
|
63
|
+
.replace(runtimeToolsMarker, () => tools)
|
|
64
|
+
.replaceAll(runtimeToolsMarker, '')
|
|
65
|
+
.trim()
|
|
66
|
+
: [profile.prompt.trim(), tools].filter(Boolean).join('\n\n');
|
|
67
|
+
if (profile.systemPromptMode === 'replace-all')
|
|
68
|
+
options.contextFiles = [];
|
|
69
|
+
}
|
|
70
|
+
return { missingSkills: missing };
|
|
71
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { loadAgentDefinitions, loadAgentFromPath, parseAgentProfile, selectAgentModel, selectAgentTools, type AgentDefinitions, type AgentDefinitionWarning, type AgentProfile, type AgentSource, type LoadAgentDefinitionsOptions, type SystemPromptMode, type ThinkingLevel, } from './agent-profile.js';
|
|
2
|
+
export { applyAgentProfile, formatRuntimeTools, selectAgentSkills, type AgentPromptResult, type SkillSelection, } from './agent-prompt.js';
|
package/dist/index.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnnywu/pi-agent-profiles",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Shared Markdown agent profiles and system prompt composition for Pi",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/jwu/pi-agent-profiles.git"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://github.com/jwu/pi-agent-profiles#readme",
|
|
10
|
+
"bugs": "https://github.com/jwu/pi-agent-profiles/issues",
|
|
11
|
+
"type": "module",
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"engines": { "node": ">=22.19.0" },
|
|
14
|
+
"exports": {
|
|
15
|
+
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" }
|
|
16
|
+
},
|
|
17
|
+
"files": ["dist"],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc -p tsconfig.build.json",
|
|
20
|
+
"format": "prettier --write src tests",
|
|
21
|
+
"lint": "prettier --check src tests && tsc --noEmit",
|
|
22
|
+
"test": "bun test",
|
|
23
|
+
"prepack": "npm run build"
|
|
24
|
+
},
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"@earendil-works/pi-coding-agent": "^1.6.0"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@earendil-works/pi-coding-agent": "1.6.0",
|
|
30
|
+
"@types/bun": "^1.3.0",
|
|
31
|
+
"@types/node": "^22.0.0",
|
|
32
|
+
"prettier": "^3.8.3",
|
|
33
|
+
"typescript": "^6.0.3"
|
|
34
|
+
}
|
|
35
|
+
}
|