pi-subagent-manager 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +139 -2
- package/agents/researcher.md +14 -0
- package/agents/worker.md +6 -0
- package/package.json +61 -4
- package/src/config.ts +355 -0
- package/src/index.ts +216 -0
- package/src/mailbox.ts +261 -0
- package/src/manager.ts +576 -0
- package/src/paths.ts +73 -0
- package/src/runtime.ts +390 -0
- package/src/tools.ts +130 -0
- package/src/types.ts +114 -0
- package/src/ui.ts +391 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 pi-subagent contributors
|
|
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,140 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-subagent-manager
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A pi extension for named, steerable subagent threads. Agent **types** describe a model's job; thread **paths** describe its ancestry.
|
|
4
|
+
|
|
5
|
+
Requires pi **0.99.2+**. No build step.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pi install /absolute/path/to/pi-subagent
|
|
9
|
+
# Or try it without installing:
|
|
10
|
+
pi -e ./src/index.ts
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Threads and context
|
|
14
|
+
|
|
15
|
+
`/root` is the main pi conversation. A child gets a snapshot of its **lexical parent**, with its own system prompt and tool policy:
|
|
16
|
+
|
|
17
|
+
```text
|
|
18
|
+
/root
|
|
19
|
+
/root/coding-researcher
|
|
20
|
+
/root/change-file-names
|
|
21
|
+
/root/change-file-names/review
|
|
22
|
+
/k # independent root: no /root history
|
|
23
|
+
/k/l # inherits /k, never /root/coding-researcher
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
A nested parent must already exist. Relative names resolve under the calling agent. Root can control all trees; children can spawn immediate children and address only their descendants. Dot segments, URL escapes and ambiguous slash spellings are rejected.
|
|
27
|
+
|
|
28
|
+
Snapshots preserve conversation messages, including custom messages and shell output, but omit the parent's system prompt and unmatched tool calls/results. Later parent turns do not silently change a child's context. Model/thinking defaults inherit the effective parent's settings; independent roots use the main session's model defaults, **not its history**.
|
|
29
|
+
|
|
30
|
+
## Finish, pause, resume
|
|
31
|
+
|
|
32
|
+
There are two handback modes, with **one retained session**:
|
|
33
|
+
|
|
34
|
+
| Child action | State | Parent receives | Further work |
|
|
35
|
+
| --------------------- | ----------- | --------------------------------------- | ----------------------- |
|
|
36
|
+
| Return a final answer | `completed` | Final answer, not the entire transcript | Resume the same session |
|
|
37
|
+
| Call `agent_pause` | `paused` | Status/reason, no final answer | Resume the same session |
|
|
38
|
+
|
|
39
|
+
A child can report progress with `agent_update` without ending its task. Pause is enforced at the turn boundary. Call it alone, rather than alongside unrelated tools.
|
|
40
|
+
|
|
41
|
+
`agent_steer` queues input for a working child, or resumes a paused/completed/stopped child. `agent_stop` cancels a thread and its working descendants, retaining their sessions. Resume a stopped ancestor before continuing its descendants. Failure also retains the thread for inspection and retry.
|
|
42
|
+
|
|
43
|
+
Child conversations use pi's JSONL session format under `<pi-agent-dir>/subagents/<parent-session-id>/`. The parent saves the thread registry in its own session. `/reload` or reopening that parent restores retained threads; interrupted work becomes paused, never automatically restarted. Pending steering and progress mailboxes are persisted too.
|
|
44
|
+
|
|
45
|
+
A forked **main** session gets a fresh registry, so separate parents never write to the same child transcript. Parent tree navigation restores the selected branch's registry **and each child's saved transcript leaf**. Resuming from an older checkpoint creates another branch in the append-only child file; newer branches remain intact. Legacy registries without child leaf IDs reopen their latest transcript. In-memory main sessions cannot survive process exit.
|
|
46
|
+
|
|
47
|
+
## Agent types
|
|
48
|
+
|
|
49
|
+
Definitions are Markdown files with YAML frontmatter:
|
|
50
|
+
|
|
51
|
+
```markdown
|
|
52
|
+
---
|
|
53
|
+
name: coding-researcher
|
|
54
|
+
description: Investigate APIs and find evidence before implementation
|
|
55
|
+
model: anthropic/claude-sonnet-4-6
|
|
56
|
+
thinkingLevel: high
|
|
57
|
+
color: accent
|
|
58
|
+
tools:
|
|
59
|
+
allow: [read, grep, find, ls, agent_types, agent_update, agent_pause]
|
|
60
|
+
block: []
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
You are a coding researcher. Read the relevant source and documentation,
|
|
64
|
+
report concrete findings, and do not modify files.
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The Markdown body is the agent's system prompt. `name` and `description` are required. Other fields are optional:
|
|
68
|
+
|
|
69
|
+
- **model:** `provider/model-id`; omission uses parent/default model. Model IDs may contain slashes.
|
|
70
|
+
- **thinkingLevel:** `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. The SDK applies the selected model's supported levels.
|
|
71
|
+
- **color:** a pi semantic foreground color, such as `accent`, `success`, `warning`, `error`, `muted` or `dim`. Colors follow theme changes.
|
|
72
|
+
- **tools:** exact-name `allow` and/or `block` lists. Block wins. An empty allow list means **no tools**; omission allows supported tools. Unavailable names fail clearly, rather than widening access.
|
|
73
|
+
|
|
74
|
+
Discovery precedence:
|
|
75
|
+
|
|
76
|
+
1. Bundled `researcher` and `worker` defaults.
|
|
77
|
+
2. `<pi-agent-dir>/agents/*.md` (normally `~/.pi/agent/agents/`).
|
|
78
|
+
3. `<cwd>/.pi/agents/*.md`, only when pi trusts the project.
|
|
79
|
+
|
|
80
|
+
Project types override global types. Malformed definitions and same-scope duplicate names produce diagnostics and fail closed for the affected type. Existing threads retain their original type definition; edits affect new threads.
|
|
81
|
+
|
|
82
|
+
### Configuration and thread UI
|
|
83
|
+
|
|
84
|
+
- `/agents types`: create/edit agent types. Field dialogs edit YAML defaults while preserving the prompt. The YAML editor edits the header together; **Open in external editor** edits the whole Markdown file using `$VISUAL`, `$EDITOR`, or `vi`.
|
|
85
|
+
- `/agents reload`: reload definitions and show diagnostics.
|
|
86
|
+
- `/agents`: pick a thread, inspect its output/transcript, send input/resume, or stop it.
|
|
87
|
+
- `/agents thread /root/coding-researcher`: open one thread directly.
|
|
88
|
+
|
|
89
|
+
A compact, themed activity widget appears **below the editor, above pi's footer/status area**. Working threads are prioritized; excess rows are counted instead of taking over the screen. The existing footer is unchanged.
|
|
90
|
+
|
|
91
|
+
## Model-facing tools
|
|
92
|
+
|
|
93
|
+
| Tool | Purpose |
|
|
94
|
+
| -------------- | --------------------------------------------------- |
|
|
95
|
+
| `agent_types` | Discover current types and their intended jobs |
|
|
96
|
+
| `agent_spawn` | Spawn `{path, type, task, wait?}`; waits by default |
|
|
97
|
+
| `agent_wait` | Wait for settlement; optional `timeoutMs` |
|
|
98
|
+
| `agent_steer` | Send `{path, message}` to a retained thread |
|
|
99
|
+
| `agent_status` | Inspect one path, or list visible threads |
|
|
100
|
+
| `agent_update` | Child progress report, without completion |
|
|
101
|
+
| `agent_pause` | Child pauses without an answer handback |
|
|
102
|
+
| `agent_stop` | Cooperatively cancel a descendant/subtree |
|
|
103
|
+
| `agent_output` | Page through final text using character offsets |
|
|
104
|
+
|
|
105
|
+
```json
|
|
106
|
+
{ "path": "coding-researcher", "type": "researcher", "task": "Investigate this API", "wait": false }
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Then use `agent_wait` or `agent_status` on `/root/coding-researcher`. Wait timeouts and cancellation do **not** kill detached children. Progress/settlement notifications do not force a parent model turn; they are recorded and visible for the parent's next interaction. Large final answers are paginated, not silently lost.
|
|
110
|
+
|
|
111
|
+
## Boundaries
|
|
112
|
+
|
|
113
|
+
- Tool policies are **not a sandbox**. Agents share the working directory and OS permissions; concurrent edits may conflict.
|
|
114
|
+
- Child sessions load pi built-in tools and this extension's controls, **not automatically discovered third-party extensions, MCP servers, skills or project context files**. This prevents recursive extension loading and keeps the tool policy explicit.
|
|
115
|
+
- Custom/native model provider registrations and runtime-only API keys are mirrored. Virtual/router models need a concrete configured model; unsupported providers fail with an actionable error.
|
|
116
|
+
- Defaults limit depth to 8, active threads to 16 and total retained threads to 64 per parent session. Waiting agents count as active. Limits live in `ManagerOptions`.
|
|
117
|
+
|
|
118
|
+
## Development
|
|
119
|
+
|
|
120
|
+
```sh
|
|
121
|
+
npm install
|
|
122
|
+
npm run check
|
|
123
|
+
npm test
|
|
124
|
+
npm run format:check
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
The suite is offline: meaningful lifecycle/policy tests plus scripted-provider SDK tests for pause, persistence and recovery. Generated JSONL scenarios cover multilevel nested agents, unopened lexical parents, interrupted work, durable mailboxes, root forks and same-file tree navigation. No live model credentials are required.
|
|
128
|
+
|
|
129
|
+
The code is deliberately layered:
|
|
130
|
+
|
|
131
|
+
- `config.ts`: frontmatter validation, precedence and atomic saves.
|
|
132
|
+
- `paths.ts`: canonical ancestry and safe context snapshots.
|
|
133
|
+
- `manager.ts`: runtime-independent ownership, lifecycle and retained registry. `scope(caller)` exposes the same caller-bound `ThreadService` to tools and UI.
|
|
134
|
+
- `runtime.ts`: isolated pi SDK sessions, providers and safe turn boundaries.
|
|
135
|
+
- `mailbox.ts`: accepted-input persistence, replay and transcript reconciliation.
|
|
136
|
+
- `tools.ts`: caller-bound model tool surface.
|
|
137
|
+
- `ui.ts`: configuration dialogs and activity/thread UI.
|
|
138
|
+
- `index.ts`: parent-session lifecycle and extension wiring.
|
|
139
|
+
|
|
140
|
+
The initial design is kept in [`.agents/plans`](.agents/plans); superseded review snapshots have been removed. Research came before implementation: [Claude](docs/research-claude.md) and [Codex](docs/research-codex.md).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: researcher
|
|
3
|
+
description: Research and inspect code without modifying files.
|
|
4
|
+
color: accent
|
|
5
|
+
tools:
|
|
6
|
+
allow:
|
|
7
|
+
- read
|
|
8
|
+
- grep
|
|
9
|
+
- find
|
|
10
|
+
- ls
|
|
11
|
+
- agent_update
|
|
12
|
+
- agent_pause
|
|
13
|
+
---
|
|
14
|
+
You are a research agent. Inspect the available sources and code, report evidence and actionable findings, and do not modify files. Send concise progress updates when useful. Pause when you need clarification or additional access. Tool filtering is not an OS sandbox.
|
package/agents/worker.md
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: worker
|
|
3
|
+
description: Carry out a focused implementation task with the default available tools.
|
|
4
|
+
color: success
|
|
5
|
+
---
|
|
6
|
+
You are a worker agent. Complete the assigned task, stay within its scope, and verify your changes when practical. Report your results and any limitations concisely. Send progress updates when useful and pause if blocked. You share the working directory with other agents; do not overwrite unrelated changes. Tool filtering is not an OS sandbox.
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-subagent-manager",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Hierarchical, steerable subagent threads for pi",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi",
|
|
9
|
+
"subagents"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"author": "Arnav Gupta",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/championswimmer/pi-subagent-manager.git"
|
|
16
|
+
},
|
|
17
|
+
"homepage": "https://github.com/championswimmer/pi-subagent-manager#readme",
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/championswimmer/pi-subagent-manager/issues"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"src",
|
|
26
|
+
"agents",
|
|
27
|
+
"README.md"
|
|
28
|
+
],
|
|
29
|
+
"pi": {
|
|
30
|
+
"extensions": [
|
|
31
|
+
"./src/index.ts"
|
|
32
|
+
]
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"check": "tsc --noEmit",
|
|
36
|
+
"test": "tsx --test tests/*.test.ts",
|
|
37
|
+
"format": "prettier --write --print-width 100 src tests README.md",
|
|
38
|
+
"format:check": "prettier --check --print-width 100 src tests README.md"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"shell-quote": "^1.8.3",
|
|
42
|
+
"yaml": "^2.8.1"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"@earendil-works/pi-agent-core": "*",
|
|
46
|
+
"@earendil-works/pi-ai": "*",
|
|
47
|
+
"@earendil-works/pi-coding-agent": ">=0.99.2",
|
|
48
|
+
"@earendil-works/pi-tui": "*",
|
|
49
|
+
"typebox": "*"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@earendil-works/pi-agent-core": "^0.99.2",
|
|
53
|
+
"@earendil-works/pi-ai": "^0.99.2",
|
|
54
|
+
"@earendil-works/pi-coding-agent": "0.99.2",
|
|
55
|
+
"@earendil-works/pi-tui": "^0.99.2",
|
|
56
|
+
"@types/node": "^22.0.0",
|
|
57
|
+
"@types/shell-quote": "^1.7.5",
|
|
58
|
+
"prettier": "^3.9.9",
|
|
59
|
+
"tsx": "^4.20.0",
|
|
60
|
+
"typebox": "1.3.27",
|
|
61
|
+
"typescript": "^5.9.0"
|
|
62
|
+
}
|
|
63
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import {
|
|
2
|
+
lstatSync,
|
|
3
|
+
mkdirSync,
|
|
4
|
+
readFileSync,
|
|
5
|
+
readdirSync,
|
|
6
|
+
renameSync,
|
|
7
|
+
unlinkSync,
|
|
8
|
+
writeFileSync,
|
|
9
|
+
} from "node:fs";
|
|
10
|
+
import { dirname, join, resolve } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import { isMap, isScalar, parseDocument, stringify } from "yaml";
|
|
14
|
+
import { THINKING_LEVELS, type AgentType } from "./types.js";
|
|
15
|
+
|
|
16
|
+
// Pi semantic foreground tokens (background tokens are intentionally excluded).
|
|
17
|
+
export const AGENT_COLORS = [
|
|
18
|
+
"accent",
|
|
19
|
+
"border",
|
|
20
|
+
"borderAccent",
|
|
21
|
+
"borderMuted",
|
|
22
|
+
"success",
|
|
23
|
+
"error",
|
|
24
|
+
"warning",
|
|
25
|
+
"muted",
|
|
26
|
+
"dim",
|
|
27
|
+
"text",
|
|
28
|
+
"thinkingText",
|
|
29
|
+
"scrollbarTrack",
|
|
30
|
+
"scrollbarThumb",
|
|
31
|
+
"searchMatchText",
|
|
32
|
+
"userMessageText",
|
|
33
|
+
"customMessageText",
|
|
34
|
+
"customMessageLabel",
|
|
35
|
+
"toolTitle",
|
|
36
|
+
"toolOutput",
|
|
37
|
+
"mdHeading",
|
|
38
|
+
"mdLink",
|
|
39
|
+
"mdLinkUrl",
|
|
40
|
+
"mdCode",
|
|
41
|
+
"mdCodeBlock",
|
|
42
|
+
"mdCodeBlockBorder",
|
|
43
|
+
"mdQuote",
|
|
44
|
+
"mdQuoteBorder",
|
|
45
|
+
"mdHr",
|
|
46
|
+
"mdListBullet",
|
|
47
|
+
"toolDiffAdded",
|
|
48
|
+
"toolDiffRemoved",
|
|
49
|
+
"toolDiffContext",
|
|
50
|
+
"syntaxComment",
|
|
51
|
+
"syntaxKeyword",
|
|
52
|
+
"syntaxFunction",
|
|
53
|
+
"syntaxVariable",
|
|
54
|
+
"syntaxString",
|
|
55
|
+
"syntaxNumber",
|
|
56
|
+
"syntaxType",
|
|
57
|
+
"syntaxOperator",
|
|
58
|
+
"syntaxPunctuation",
|
|
59
|
+
"thinkingOff",
|
|
60
|
+
"thinkingMinimal",
|
|
61
|
+
"thinkingLow",
|
|
62
|
+
"thinkingMedium",
|
|
63
|
+
"thinkingHigh",
|
|
64
|
+
"thinkingXhigh",
|
|
65
|
+
"thinkingMax",
|
|
66
|
+
"bashMode",
|
|
67
|
+
] as const;
|
|
68
|
+
|
|
69
|
+
const NAME = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
|
|
70
|
+
const TOOL = /^[a-zA-Z0-9_-]+$/;
|
|
71
|
+
const FIELDS = new Set(["name", "description", "model", "thinkingLevel", "color", "tools"]);
|
|
72
|
+
|
|
73
|
+
type AgentScope = "user" | "project";
|
|
74
|
+
type SaveOrigin = Pick<AgentType, "name" | "source" | "filePath">;
|
|
75
|
+
|
|
76
|
+
function errorCode(error: unknown): string | undefined {
|
|
77
|
+
return typeof error === "object" && error !== null && "code" in error
|
|
78
|
+
? String((error as { code?: unknown }).code)
|
|
79
|
+
: undefined;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function lstatIfPresent(path: string): ReturnType<typeof lstatSync> | undefined {
|
|
83
|
+
try {
|
|
84
|
+
return lstatSync(path);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (errorCode(error) === "ENOENT") return undefined;
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function assertNotSymlinkPath(path: string): ReturnType<typeof lstatSync> | undefined {
|
|
92
|
+
const stat = lstatIfPresent(path);
|
|
93
|
+
if (stat?.isSymbolicLink()) throw new Error(`Unsafe symlink path: ${path}`);
|
|
94
|
+
return stat;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function validatePreservedDestination(filePath: string, directory: string): string {
|
|
98
|
+
const resolved = resolve(filePath);
|
|
99
|
+
if (dirname(resolved) !== directory || !resolved.endsWith(".md"))
|
|
100
|
+
throw new Error(`Unsafe agent destination: ${resolved}`);
|
|
101
|
+
const stat = lstatIfPresent(resolved);
|
|
102
|
+
if (!stat?.isFile()) throw new Error(`Unsafe agent destination: ${resolved}`);
|
|
103
|
+
return resolved;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function frontmatter(content: string): { yaml: string; body: string } {
|
|
107
|
+
const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m.exec(content);
|
|
108
|
+
if (!match || match.index !== 0)
|
|
109
|
+
throw new Error("Expected YAML frontmatter enclosed by --- lines");
|
|
110
|
+
return { yaml: match[1], body: content.slice(match[0].length) };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function record(value: unknown, label: string): Record<string, unknown> {
|
|
114
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
115
|
+
throw new Error(`${label} must be a mapping`);
|
|
116
|
+
return value as Record<string, unknown>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function toolNames(value: unknown, label: string): string[] {
|
|
120
|
+
if (!Array.isArray(value) || value.some((name) => typeof name !== "string" || !TOOL.test(name))) {
|
|
121
|
+
throw new Error(`${label} must be an array of exact tool names (no wildcards or patterns)`);
|
|
122
|
+
}
|
|
123
|
+
if (new Set(value).size !== value.length)
|
|
124
|
+
throw new Error(`${label} contains duplicate tool names`);
|
|
125
|
+
return [...value];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function toolPolicy(value: unknown): NonNullable<AgentType["tools"]> {
|
|
129
|
+
const mapping = record(value, "tools");
|
|
130
|
+
for (const key of Object.keys(mapping))
|
|
131
|
+
if (key !== "allow" && key !== "block") throw new Error(`Unknown tools field: ${key}`);
|
|
132
|
+
const result: NonNullable<AgentType["tools"]> = {};
|
|
133
|
+
if (Object.hasOwn(mapping, "allow")) result.allow = toolNames(mapping.allow, "tools.allow");
|
|
134
|
+
if (Object.hasOwn(mapping, "block")) result.block = toolNames(mapping.block, "tools.block");
|
|
135
|
+
return result;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function parseAgentType(content: string, filePath?: string): AgentType {
|
|
139
|
+
try {
|
|
140
|
+
const { yaml, body } = frontmatter(content);
|
|
141
|
+
const doc = parseDocument(yaml, { uniqueKeys: true });
|
|
142
|
+
if (doc.errors.length) throw new Error(doc.errors.map((error) => error.message).join("; "));
|
|
143
|
+
const data = record(doc.toJS({ maxAliasCount: 0 }), "Frontmatter");
|
|
144
|
+
for (const key of Object.keys(data))
|
|
145
|
+
if (!FIELDS.has(key)) throw new Error(`Unknown frontmatter field: ${key}`);
|
|
146
|
+
if (typeof data.name !== "string" || !NAME.test(data.name))
|
|
147
|
+
throw new Error(
|
|
148
|
+
"name must be a safe identifier using letters, numbers, underscores or hyphens",
|
|
149
|
+
);
|
|
150
|
+
if (typeof data.description !== "string" || !data.description.trim())
|
|
151
|
+
throw new Error("description must be a nonempty string");
|
|
152
|
+
const result: AgentType = {
|
|
153
|
+
name: data.name,
|
|
154
|
+
description: data.description,
|
|
155
|
+
systemPrompt: body,
|
|
156
|
+
};
|
|
157
|
+
if (Object.hasOwn(data, "model")) {
|
|
158
|
+
if (typeof data.model !== "string" || !/^[^\s/]+\/[^\s]+$/.test(data.model))
|
|
159
|
+
throw new Error("model must be provider/model-id");
|
|
160
|
+
result.model = data.model;
|
|
161
|
+
}
|
|
162
|
+
if (Object.hasOwn(data, "thinkingLevel")) {
|
|
163
|
+
if (!THINKING_LEVELS.includes(data.thinkingLevel as AgentType["thinkingLevel"] & string))
|
|
164
|
+
throw new Error(`thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`);
|
|
165
|
+
result.thinkingLevel = data.thinkingLevel as AgentType["thinkingLevel"];
|
|
166
|
+
}
|
|
167
|
+
if (Object.hasOwn(data, "color")) {
|
|
168
|
+
if (!AGENT_COLORS.includes(data.color as (typeof AGENT_COLORS)[number]))
|
|
169
|
+
throw new Error(`color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`);
|
|
170
|
+
result.color = data.color as string;
|
|
171
|
+
}
|
|
172
|
+
if (Object.hasOwn(data, "tools")) result.tools = toolPolicy(data.tools);
|
|
173
|
+
if (filePath !== undefined) result.filePath = filePath;
|
|
174
|
+
return result;
|
|
175
|
+
} catch (error) {
|
|
176
|
+
throw new Error(
|
|
177
|
+
`${filePath ?? "Agent definition"}: ${error instanceof Error ? error.message : String(error)}`,
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function serializeAgentType(type: AgentType): string {
|
|
183
|
+
if (typeof type.systemPrompt !== "string") throw new Error("systemPrompt must be a string");
|
|
184
|
+
const data: Record<string, unknown> = {
|
|
185
|
+
name: type.name,
|
|
186
|
+
description: type.description,
|
|
187
|
+
};
|
|
188
|
+
for (const key of ["model", "thinkingLevel", "color", "tools"] as const)
|
|
189
|
+
if (type[key] !== undefined) data[key] = type[key];
|
|
190
|
+
const content = `---\n${stringify(data)}---\n${type.systemPrompt}`;
|
|
191
|
+
parseAgentType(content);
|
|
192
|
+
return content;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function selectTools(policy: AgentType["tools"], available: string[]): string[] {
|
|
196
|
+
const validated = policy === undefined ? {} : toolPolicy(policy);
|
|
197
|
+
const names = new Set(available);
|
|
198
|
+
for (const name of [...(validated.allow ?? []), ...(validated.block ?? [])]) {
|
|
199
|
+
if (!names.has(name)) throw new Error(`Unavailable tool name: ${name}`);
|
|
200
|
+
}
|
|
201
|
+
const allow = validated.allow === undefined ? names : new Set(validated.allow);
|
|
202
|
+
const block = new Set(validated.block ?? []);
|
|
203
|
+
return [...names].filter((name) => allow.has(name) && !block.has(name));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface ConfigStoreOptions {
|
|
207
|
+
cwd: string;
|
|
208
|
+
agentDir: string;
|
|
209
|
+
includeProject: boolean;
|
|
210
|
+
bundledDir?: string;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export class ConfigStore {
|
|
214
|
+
diagnostics: string[] = [];
|
|
215
|
+
private types = new Map<string, AgentType>();
|
|
216
|
+
private readonly options: ConfigStoreOptions;
|
|
217
|
+
|
|
218
|
+
constructor(options: ConfigStoreOptions) {
|
|
219
|
+
this.options = { ...options };
|
|
220
|
+
this.reload();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
reload(): void {
|
|
224
|
+
this.types.clear();
|
|
225
|
+
this.diagnostics = [];
|
|
226
|
+
const layers: [string, NonNullable<AgentType["source"]>][] = [
|
|
227
|
+
[this.options.bundledDir ?? fileURLToPath(new URL("../agents/", import.meta.url)), "bundled"],
|
|
228
|
+
[join(this.options.agentDir, "agents"), "user"],
|
|
229
|
+
];
|
|
230
|
+
if (this.options.includeProject)
|
|
231
|
+
layers.push([join(this.options.cwd, ".pi", "agents"), "project"]);
|
|
232
|
+
for (const [directory, source] of layers) {
|
|
233
|
+
let files: string[];
|
|
234
|
+
try {
|
|
235
|
+
const stat = assertNotSymlinkPath(directory);
|
|
236
|
+
if (!stat) continue;
|
|
237
|
+
if (!stat.isDirectory())
|
|
238
|
+
throw new Error(`Agent directory must be a directory: ${directory}`);
|
|
239
|
+
files = readdirSync(directory)
|
|
240
|
+
.filter((file) => file.endsWith(".md"))
|
|
241
|
+
.sort();
|
|
242
|
+
} catch (error) {
|
|
243
|
+
this.diagnostics.push(`${directory}: ${String(error)}`);
|
|
244
|
+
// An unreadable override layer cannot safely expose lower-precedence policies.
|
|
245
|
+
this.types.clear();
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
const blocked = new Set<string>();
|
|
249
|
+
const seenNames = new Set<string>();
|
|
250
|
+
for (const file of files) {
|
|
251
|
+
const filePath = join(directory, file);
|
|
252
|
+
let content = "";
|
|
253
|
+
try {
|
|
254
|
+
if (!lstatSync(filePath).isFile())
|
|
255
|
+
throw new Error("Agent definition must be a regular file, not a symlink");
|
|
256
|
+
content = readFileSync(filePath, "utf8");
|
|
257
|
+
const type = parseAgentType(content, filePath);
|
|
258
|
+
if (seenNames.has(type.name)) {
|
|
259
|
+
blocked.add(type.name);
|
|
260
|
+
this.diagnostics.push(
|
|
261
|
+
`${filePath}: Duplicate agent name in ${source} layer: ${type.name}`,
|
|
262
|
+
);
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
seenNames.add(type.name);
|
|
266
|
+
this.types.set(type.name, { ...type, source });
|
|
267
|
+
} catch (error) {
|
|
268
|
+
blocked.add(file.slice(0, -3));
|
|
269
|
+
// Extract declared names even if another field or duplicate key is malformed.
|
|
270
|
+
try {
|
|
271
|
+
const doc = parseDocument(frontmatter(content).yaml);
|
|
272
|
+
if (isMap(doc.contents))
|
|
273
|
+
for (const pair of doc.contents.items) {
|
|
274
|
+
if (
|
|
275
|
+
isScalar(pair.key) &&
|
|
276
|
+
pair.key.value === "name" &&
|
|
277
|
+
isScalar(pair.value) &&
|
|
278
|
+
typeof pair.value.value === "string"
|
|
279
|
+
)
|
|
280
|
+
blocked.add(pair.value.value);
|
|
281
|
+
}
|
|
282
|
+
} catch {
|
|
283
|
+
/* Filename still provides a fail-closed tombstone. */
|
|
284
|
+
}
|
|
285
|
+
this.diagnostics.push(`${filePath}: ${String(error)}`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
for (const name of blocked) this.types.delete(name);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
list(): AgentType[] {
|
|
293
|
+
return structuredClone([...this.types.values()].sort((a, b) => a.name.localeCompare(b.name)));
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
get(name: string): AgentType {
|
|
297
|
+
const type = this.types.get(name);
|
|
298
|
+
if (!type) throw new Error(`Unknown or invalid agent type: ${name}`);
|
|
299
|
+
return structuredClone(type);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
canSaveProject(): boolean {
|
|
303
|
+
return this.options.includeProject;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private scopeDirectory(scope: AgentScope): string {
|
|
307
|
+
if (scope !== "user" && scope !== "project") throw new Error("Invalid agent scope");
|
|
308
|
+
if (scope === "project" && !this.options.includeProject)
|
|
309
|
+
throw new Error("Project agents are not enabled/trusted");
|
|
310
|
+
return scope === "user"
|
|
311
|
+
? resolve(this.options.agentDir, "agents")
|
|
312
|
+
: resolve(this.options.cwd, ".pi", "agents");
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
private destinationBasePaths(scope: AgentScope, directory: string): string[] {
|
|
316
|
+
const base = resolve(scope === "user" ? this.options.agentDir : this.options.cwd);
|
|
317
|
+
return scope === "user" ? [base, directory] : [base, join(base, ".pi"), directory];
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
destination(name: string, scope: AgentScope, original?: SaveOrigin): string {
|
|
321
|
+
if (!NAME.test(name)) throw new Error("Unsafe agent name");
|
|
322
|
+
const directory = this.scopeDirectory(scope);
|
|
323
|
+
if (
|
|
324
|
+
original?.name === name &&
|
|
325
|
+
original.source === scope &&
|
|
326
|
+
typeof original.filePath === "string"
|
|
327
|
+
) {
|
|
328
|
+
return validatePreservedDestination(original.filePath, directory);
|
|
329
|
+
}
|
|
330
|
+
return resolve(directory, `${name}.md`);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
save(type: AgentType, scope: AgentScope, original?: SaveOrigin): AgentType {
|
|
334
|
+
const content = serializeAgentType(type);
|
|
335
|
+
const validated = parseAgentType(content);
|
|
336
|
+
const filePath = this.destination(validated.name, scope, original);
|
|
337
|
+
const directory = dirname(filePath);
|
|
338
|
+
// Reject redirected destination directories and files before writing.
|
|
339
|
+
for (const path of [...this.destinationBasePaths(scope, directory), filePath]) {
|
|
340
|
+
const stat = assertNotSymlinkPath(path);
|
|
341
|
+
if (path === filePath && stat && !stat.isFile())
|
|
342
|
+
throw new Error(`Unsafe agent destination: ${filePath}`);
|
|
343
|
+
}
|
|
344
|
+
mkdirSync(directory, { recursive: true });
|
|
345
|
+
const temporary = join(dirname(filePath), `.${validated.name}.${randomUUID()}.tmp`);
|
|
346
|
+
try {
|
|
347
|
+
writeFileSync(temporary, content, { flag: "wx", mode: 0o600 });
|
|
348
|
+
renameSync(temporary, filePath);
|
|
349
|
+
} finally {
|
|
350
|
+
if (lstatIfPresent(temporary)) unlinkSync(temporary);
|
|
351
|
+
}
|
|
352
|
+
this.reload();
|
|
353
|
+
return { ...validated, filePath, source: scope };
|
|
354
|
+
}
|
|
355
|
+
}
|