pi-subagent-manager 0.1.1 → 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/README.md +51 -8
- package/agents/architect.md +7 -0
- package/package.json +1 -1
- package/src/config.ts +157 -42
- package/src/index.ts +22 -6
- package/src/manager.ts +27 -3
- package/src/model-picker.ts +509 -0
- package/src/models.ts +54 -0
- package/src/runtime.ts +264 -57
- package/src/settings.ts +124 -0
- package/src/tools.ts +4 -3
- package/src/types.ts +8 -0
- package/src/ui.ts +221 -40
package/README.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# pi-subagent-manager
|
|
2
2
|
|
|
3
|
+
[](https://www.npmjs.com/package/pi-subagent-manager)
|
|
4
|
+
[](https://www.npmjs.com/package/pi-subagent-manager)
|
|
5
|
+
[](https://github.com/championswimmer/pi-subagent-manager/actions/workflows/tests.yml)
|
|
6
|
+
|
|
3
7
|
A pi extension for named, steerable subagent threads. Agent **types** describe a model's job; thread **paths** describe its ancestry.
|
|
4
8
|
|
|
5
9
|
Requires pi **0.99.2+**. No build step.
|
|
@@ -40,7 +44,11 @@ A child can report progress with `agent_update` without ending its task. Pause i
|
|
|
40
44
|
|
|
41
45
|
`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
46
|
|
|
43
|
-
|
|
47
|
+
New child conversations use pi's JSONL session format in the main session's session directory (normally `<pi-agent-dir>/sessions/<encoded-cwd>/`; custom session directories are respected). Each transcript has a name such as `worker /root/task` and a `parentSession` link to its lexical parent's transcript, so saved children appear as nested rows in `pi --resume` and `/resume` with **Threaded** sorting and an empty search. Recent/Fuzzy sorting and search show flat rows; named-only filtering can hide an unnamed parent. Independent roots link to the main session for display only; they still inherit no conversation history.
|
|
48
|
+
|
|
49
|
+
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. Existing transcripts under `<pi-agent-dir>/subagents/<parent-session-id>/` remain reopenable through the parent registry; they are not automatically moved or added to the native resume picker.
|
|
50
|
+
|
|
51
|
+
Resume the **main session** to continue using the managed thread tree and its tool policies. Opening a child directly in pi opens its transcript as a normal interactive session, not as a managed subagent. Avoid opening the same child while its parent is still running it. Because children are now ordinary sessions, `pi --continue` can pick a recently modified child instead of the main session; use `pi --resume` to select the main session explicitly.
|
|
44
52
|
|
|
45
53
|
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
54
|
|
|
@@ -52,7 +60,9 @@ Definitions are Markdown files with YAML frontmatter:
|
|
|
52
60
|
---
|
|
53
61
|
name: coding-researcher
|
|
54
62
|
description: Investigate APIs and find evidence before implementation
|
|
55
|
-
|
|
63
|
+
models:
|
|
64
|
+
- anthropic/claude-sonnet-4-6
|
|
65
|
+
- openai/gpt-5
|
|
56
66
|
thinkingLevel: high
|
|
57
67
|
color: accent
|
|
58
68
|
tools:
|
|
@@ -66,11 +76,14 @@ report concrete findings, and do not modify files.
|
|
|
66
76
|
|
|
67
77
|
The Markdown body is the agent's system prompt. `name` and `description` are required. Other fields are optional:
|
|
68
78
|
|
|
69
|
-
- **
|
|
79
|
+
- **models:** an ordered YAML list of exact `provider/model-id` preferences. Model IDs may contain additional slashes. The first entry that exists in `/scoped-models` wins; the scan follows the list order, not the scoped-model order.
|
|
80
|
+
- **model:** deprecated compatibility alias for a single preference. Existing definitions still parse, but saving normalizes them to `models:` and does not write `model:` back out.
|
|
70
81
|
- **thinkingLevel:** `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. The SDK applies the selected model's supported levels.
|
|
71
|
-
- **color:** a pi semantic
|
|
82
|
+
- **color:** a pi semantic color, such as `accent`, `success`, `warning`, `error`, `muted` or `dim`, used as the background of the agent's name pill. Text is bold and automatically contrasts with the background. The color picker previews the pill; colors follow theme changes. Unset uses `accent`.
|
|
72
83
|
- **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
84
|
|
|
85
|
+
If `models`/`model` is omitted, the agent inherits the effective parent/default model. Matching is strict: preferences are matched verbatim against `/scoped-models`, and if none match — including when `/scoped-models` is empty — spawn fails with an actionable error instead of falling back to the registry.
|
|
86
|
+
|
|
74
87
|
Discovery precedence:
|
|
75
88
|
|
|
76
89
|
1. Bundled `researcher` and `worker` defaults.
|
|
@@ -81,7 +94,7 @@ Project types override global types. Malformed definitions and same-scope duplic
|
|
|
81
94
|
|
|
82
95
|
### Configuration and thread UI
|
|
83
96
|
|
|
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`.
|
|
97
|
+
- `/agents types`: create/edit agent types. Field dialogs edit YAML defaults while preserving the prompt. Model preferences use an ordered picker: add available models (scoped entries are marked), remove entries, and move them up/down to control preference order. The YAML editor edits the header together; **Open in external editor** edits the whole Markdown file using `$VISUAL`, `$EDITOR`, or `vi`.
|
|
85
98
|
- `/agents reload`: reload definitions and show diagnostics.
|
|
86
99
|
- `/agents`: pick a thread, inspect its output/transcript, send input/resume, or stop it.
|
|
87
100
|
- `/agents thread /root/coding-researcher`: open one thread directly.
|
|
@@ -106,14 +119,43 @@ A compact, themed activity widget appears **below the editor, above pi's footer/
|
|
|
106
119
|
{ "path": "coding-researcher", "type": "researcher", "task": "Investigate this API", "wait": false }
|
|
107
120
|
```
|
|
108
121
|
|
|
109
|
-
Then use `agent_wait` or `agent_status` on `/root/coding-researcher`.
|
|
122
|
+
Then use `agent_wait` or `agent_status` on `/root/coding-researcher`.
|
|
123
|
+
|
|
124
|
+
### Parallel and nested work
|
|
125
|
+
|
|
126
|
+
Launch **all independent siblings with `wait: false` before waiting**. For example, `/root` can launch `team-a` and `team-b`, then each team can launch `worker-a` and `worker-b` the same way. This works even if tool calls are delivered sequentially: detached children run in separate SDK sessions. Same-turn foreground calls also overlap when pi executes their tool batch in parallel, but spawning one foreground child and awaiting it before launching the next is sequential.
|
|
127
|
+
|
|
128
|
+
Use a delegating type such as `worker` or `architect` for team coordinators. A custom allow list must include `agent_spawn` and `agent_wait`; the bundled read-only `researcher` intentionally does not have delegation tools. Children never bypass their tool policy or the shared limits.
|
|
129
|
+
|
|
130
|
+
### Manager settings
|
|
131
|
+
|
|
132
|
+
Settings belong to **this extension**, not another subagent package:
|
|
133
|
+
|
|
134
|
+
- Global: `<pi-agent-dir>/subagent-manager/settings.json` (normally `~/.pi/agent/subagent-manager/settings.json`).
|
|
135
|
+
- Project: `<cwd>/.pi/agent/subagent-manager/settings.json`, loaded only when pi trusts the project; overrides global values.
|
|
136
|
+
|
|
137
|
+
```json
|
|
138
|
+
{
|
|
139
|
+
"maxLevels": 3,
|
|
140
|
+
"maxConcurrent": 16,
|
|
141
|
+
"maxThreads": 64
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
All keys are optional. `maxLevels` includes the main conversation as **L1**: the default permits L2 children and L3 grandchildren, but no L4. An independent root such as `/k` is still L2, so independent paths cannot bypass the limit. `maxLevels: 1` disables new children; supported values are integers from 1 to 32.
|
|
146
|
+
|
|
147
|
+
`maxConcurrent` counts starting/running threads **across the entire tree**, including parents waiting for children; `maxThreads` counts all retained threads. Both require positive safe integers. Capacity exhaustion fails clearly rather than queuing. Omitted settings use the defaults above. Unknown keys, malformed values and symlinked settings paths produce warnings; an invalid file is ignored atomically, preserving the preceding valid layer/defaults.
|
|
148
|
+
|
|
149
|
+
Use `/agents reload` to reload definitions and settings. New limits do not cancel existing threads or discard retained sessions; they govern new spawns and future concurrency reservations. Lowering the level limit still permits resuming previously retained deeper sessions, but no new agents can be spawned beyond the limit. `/reload` or reopening the parent also reloads settings. This extension does **not** read `.pi/subagents.json` or settings owned by `@tintinweb/pi-subagents`; avoid loading both extensions because they both register `/agents`.
|
|
150
|
+
|
|
151
|
+
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
152
|
|
|
111
153
|
## Boundaries
|
|
112
154
|
|
|
113
155
|
- Tool policies are **not a sandbox**. Agents share the working directory and OS permissions; concurrent edits may conflict.
|
|
114
156
|
- 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
157
|
- 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
|
|
158
|
+
- Defaults limit the tree to 3 levels including the main conversation, 16 active threads and 64 retained threads per parent session. Waiting agents count as active. Configure them using this extension's manager settings.
|
|
117
159
|
|
|
118
160
|
## Development
|
|
119
161
|
|
|
@@ -124,11 +166,12 @@ npm test
|
|
|
124
166
|
npm run format:check
|
|
125
167
|
```
|
|
126
168
|
|
|
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.
|
|
169
|
+
The suite is offline: meaningful lifecycle/policy tests plus scripted-provider SDK tests for nested parallel launches, level settings, 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
170
|
|
|
129
171
|
The code is deliberately layered:
|
|
130
172
|
|
|
131
173
|
- `config.ts`: frontmatter validation, precedence and atomic saves.
|
|
174
|
+
- `settings.ts`: validated global/project manager limits and safe configuration paths.
|
|
132
175
|
- `paths.ts`: canonical ancestry and safe context snapshots.
|
|
133
176
|
- `manager.ts`: runtime-independent ownership, lifecycle and retained registry. `scope(caller)` exposes the same caller-bound `ThreadService` to tools and UI.
|
|
134
177
|
- `runtime.ts`: isolated pi SDK sessions, providers and safe turn boundaries.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: architect
|
|
3
|
+
description: Plan technical approaches, decompose work, and identify risks before implementation.
|
|
4
|
+
color: mdHeading
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
You are an architect agent. Clarify the goal, inspect the available context, propose a concrete implementation approach, and break work into small, verifiable steps. Call out tradeoffs, edge cases, and migration risks, but do not make unrelated code changes. Send concise progress updates when useful and pause if you need clarification or missing context. Tool filtering is not an OS sandbox.
|
package/package.json
CHANGED
package/src/config.ts
CHANGED
|
@@ -11,9 +11,10 @@ import { dirname, join, resolve } from "node:path";
|
|
|
11
11
|
import { fileURLToPath } from "node:url";
|
|
12
12
|
import { randomUUID } from "node:crypto";
|
|
13
13
|
import { isMap, isScalar, parseDocument, stringify } from "yaml";
|
|
14
|
+
import { getModelPreferences } from "./models.js";
|
|
14
15
|
import { THINKING_LEVELS, type AgentType } from "./types.js";
|
|
15
16
|
|
|
16
|
-
// Pi semantic
|
|
17
|
+
// Pi semantic color tokens, resolved as concrete colors for agent name backgrounds.
|
|
17
18
|
export const AGENT_COLORS = [
|
|
18
19
|
"accent",
|
|
19
20
|
"border",
|
|
@@ -68,7 +69,17 @@ export const AGENT_COLORS = [
|
|
|
68
69
|
|
|
69
70
|
const NAME = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
|
|
70
71
|
const TOOL = /^[a-zA-Z0-9_-]+$/;
|
|
71
|
-
const FIELDS = new Set([
|
|
72
|
+
const FIELDS = new Set([
|
|
73
|
+
"name",
|
|
74
|
+
"description",
|
|
75
|
+
"models",
|
|
76
|
+
"model",
|
|
77
|
+
"thinkingLevel",
|
|
78
|
+
"color",
|
|
79
|
+
"tools",
|
|
80
|
+
]);
|
|
81
|
+
const SUBAGENT_MANAGER_DIR = "subagent-manager";
|
|
82
|
+
const AGENTS_DIR = "agents";
|
|
72
83
|
|
|
73
84
|
type AgentScope = "user" | "project";
|
|
74
85
|
type SaveOrigin = Pick<AgentType, "name" | "source" | "filePath">;
|
|
@@ -79,7 +90,9 @@ function errorCode(error: unknown): string | undefined {
|
|
|
79
90
|
: undefined;
|
|
80
91
|
}
|
|
81
92
|
|
|
82
|
-
function lstatIfPresent(
|
|
93
|
+
function lstatIfPresent(
|
|
94
|
+
path: string,
|
|
95
|
+
): ReturnType<typeof lstatSync> | undefined {
|
|
83
96
|
try {
|
|
84
97
|
return lstatSync(path);
|
|
85
98
|
} catch (error) {
|
|
@@ -88,13 +101,18 @@ function lstatIfPresent(path: string): ReturnType<typeof lstatSync> | undefined
|
|
|
88
101
|
}
|
|
89
102
|
}
|
|
90
103
|
|
|
91
|
-
function assertNotSymlinkPath(
|
|
104
|
+
function assertNotSymlinkPath(
|
|
105
|
+
path: string,
|
|
106
|
+
): ReturnType<typeof lstatSync> | undefined {
|
|
92
107
|
const stat = lstatIfPresent(path);
|
|
93
108
|
if (stat?.isSymbolicLink()) throw new Error(`Unsafe symlink path: ${path}`);
|
|
94
109
|
return stat;
|
|
95
110
|
}
|
|
96
111
|
|
|
97
|
-
function validatePreservedDestination(
|
|
112
|
+
function validatePreservedDestination(
|
|
113
|
+
filePath: string,
|
|
114
|
+
directory: string,
|
|
115
|
+
): string {
|
|
98
116
|
const resolved = resolve(filePath);
|
|
99
117
|
if (dirname(resolved) !== directory || !resolved.endsWith(".md"))
|
|
100
118
|
throw new Error(`Unsafe agent destination: ${resolved}`);
|
|
@@ -104,7 +122,9 @@ function validatePreservedDestination(filePath: string, directory: string): stri
|
|
|
104
122
|
}
|
|
105
123
|
|
|
106
124
|
function frontmatter(content: string): { yaml: string; body: string } {
|
|
107
|
-
const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m.exec(
|
|
125
|
+
const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m.exec(
|
|
126
|
+
content,
|
|
127
|
+
);
|
|
108
128
|
if (!match || match.index !== 0)
|
|
109
129
|
throw new Error("Expected YAML frontmatter enclosed by --- lines");
|
|
110
130
|
return { yaml: match[1], body: content.slice(match[0].length) };
|
|
@@ -117,8 +137,13 @@ function record(value: unknown, label: string): Record<string, unknown> {
|
|
|
117
137
|
}
|
|
118
138
|
|
|
119
139
|
function toolNames(value: unknown, label: string): string[] {
|
|
120
|
-
if (
|
|
121
|
-
|
|
140
|
+
if (
|
|
141
|
+
!Array.isArray(value) ||
|
|
142
|
+
value.some((name) => typeof name !== "string" || !TOOL.test(name))
|
|
143
|
+
) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`${label} must be an array of exact tool names (no wildcards or patterns)`,
|
|
146
|
+
);
|
|
122
147
|
}
|
|
123
148
|
if (new Set(value).size !== value.length)
|
|
124
149
|
throw new Error(`${label} contains duplicate tool names`);
|
|
@@ -128,10 +153,13 @@ function toolNames(value: unknown, label: string): string[] {
|
|
|
128
153
|
function toolPolicy(value: unknown): NonNullable<AgentType["tools"]> {
|
|
129
154
|
const mapping = record(value, "tools");
|
|
130
155
|
for (const key of Object.keys(mapping))
|
|
131
|
-
if (key !== "allow" && key !== "block")
|
|
156
|
+
if (key !== "allow" && key !== "block")
|
|
157
|
+
throw new Error(`Unknown tools field: ${key}`);
|
|
132
158
|
const result: NonNullable<AgentType["tools"]> = {};
|
|
133
|
-
if (Object.hasOwn(mapping, "allow"))
|
|
134
|
-
|
|
159
|
+
if (Object.hasOwn(mapping, "allow"))
|
|
160
|
+
result.allow = toolNames(mapping.allow, "tools.allow");
|
|
161
|
+
if (Object.hasOwn(mapping, "block"))
|
|
162
|
+
result.block = toolNames(mapping.block, "tools.block");
|
|
135
163
|
return result;
|
|
136
164
|
}
|
|
137
165
|
|
|
@@ -139,10 +167,12 @@ export function parseAgentType(content: string, filePath?: string): AgentType {
|
|
|
139
167
|
try {
|
|
140
168
|
const { yaml, body } = frontmatter(content);
|
|
141
169
|
const doc = parseDocument(yaml, { uniqueKeys: true });
|
|
142
|
-
if (doc.errors.length)
|
|
170
|
+
if (doc.errors.length)
|
|
171
|
+
throw new Error(doc.errors.map((error) => error.message).join("; "));
|
|
143
172
|
const data = record(doc.toJS({ maxAliasCount: 0 }), "Frontmatter");
|
|
144
173
|
for (const key of Object.keys(data))
|
|
145
|
-
if (!FIELDS.has(key))
|
|
174
|
+
if (!FIELDS.has(key))
|
|
175
|
+
throw new Error(`Unknown frontmatter field: ${key}`);
|
|
146
176
|
if (typeof data.name !== "string" || !NAME.test(data.name))
|
|
147
177
|
throw new Error(
|
|
148
178
|
"name must be a safe identifier using letters, numbers, underscores or hyphens",
|
|
@@ -154,19 +184,27 @@ export function parseAgentType(content: string, filePath?: string): AgentType {
|
|
|
154
184
|
description: data.description,
|
|
155
185
|
systemPrompt: body,
|
|
156
186
|
};
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
187
|
+
const models = getModelPreferences({
|
|
188
|
+
models: data.models,
|
|
189
|
+
model: data.model,
|
|
190
|
+
});
|
|
191
|
+
if (models !== undefined) result.models = models;
|
|
162
192
|
if (Object.hasOwn(data, "thinkingLevel")) {
|
|
163
|
-
if (
|
|
164
|
-
|
|
193
|
+
if (
|
|
194
|
+
!THINKING_LEVELS.includes(
|
|
195
|
+
data.thinkingLevel as AgentType["thinkingLevel"] & string,
|
|
196
|
+
)
|
|
197
|
+
)
|
|
198
|
+
throw new Error(
|
|
199
|
+
`thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`,
|
|
200
|
+
);
|
|
165
201
|
result.thinkingLevel = data.thinkingLevel as AgentType["thinkingLevel"];
|
|
166
202
|
}
|
|
167
203
|
if (Object.hasOwn(data, "color")) {
|
|
168
204
|
if (!AGENT_COLORS.includes(data.color as (typeof AGENT_COLORS)[number]))
|
|
169
|
-
throw new Error(
|
|
205
|
+
throw new Error(
|
|
206
|
+
`color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`,
|
|
207
|
+
);
|
|
170
208
|
result.color = data.color as string;
|
|
171
209
|
}
|
|
172
210
|
if (Object.hasOwn(data, "tools")) result.tools = toolPolicy(data.tools);
|
|
@@ -180,25 +218,32 @@ export function parseAgentType(content: string, filePath?: string): AgentType {
|
|
|
180
218
|
}
|
|
181
219
|
|
|
182
220
|
export function serializeAgentType(type: AgentType): string {
|
|
183
|
-
if (typeof type.systemPrompt !== "string")
|
|
221
|
+
if (typeof type.systemPrompt !== "string")
|
|
222
|
+
throw new Error("systemPrompt must be a string");
|
|
184
223
|
const data: Record<string, unknown> = {
|
|
185
224
|
name: type.name,
|
|
186
225
|
description: type.description,
|
|
187
226
|
};
|
|
188
|
-
|
|
227
|
+
const models = getModelPreferences(type);
|
|
228
|
+
if (models !== undefined) data.models = models;
|
|
229
|
+
for (const key of ["thinkingLevel", "color", "tools"] as const)
|
|
189
230
|
if (type[key] !== undefined) data[key] = type[key];
|
|
190
231
|
const content = `---\n${stringify(data)}---\n${type.systemPrompt}`;
|
|
191
232
|
parseAgentType(content);
|
|
192
233
|
return content;
|
|
193
234
|
}
|
|
194
235
|
|
|
195
|
-
export function selectTools(
|
|
236
|
+
export function selectTools(
|
|
237
|
+
policy: AgentType["tools"],
|
|
238
|
+
available: string[],
|
|
239
|
+
): string[] {
|
|
196
240
|
const validated = policy === undefined ? {} : toolPolicy(policy);
|
|
197
241
|
const names = new Set(available);
|
|
198
242
|
for (const name of [...(validated.allow ?? []), ...(validated.block ?? [])]) {
|
|
199
243
|
if (!names.has(name)) throw new Error(`Unavailable tool name: ${name}`);
|
|
200
244
|
}
|
|
201
|
-
const allow =
|
|
245
|
+
const allow =
|
|
246
|
+
validated.allow === undefined ? names : new Set(validated.allow);
|
|
202
247
|
const block = new Set(validated.block ?? []);
|
|
203
248
|
return [...names].filter((name) => allow.has(name) && !block.has(name));
|
|
204
249
|
}
|
|
@@ -224,11 +269,27 @@ export class ConfigStore {
|
|
|
224
269
|
this.types.clear();
|
|
225
270
|
this.diagnostics = [];
|
|
226
271
|
const layers: [string, NonNullable<AgentType["source"]>][] = [
|
|
227
|
-
[
|
|
228
|
-
|
|
272
|
+
[
|
|
273
|
+
this.options.bundledDir ??
|
|
274
|
+
fileURLToPath(new URL("../agents/", import.meta.url)),
|
|
275
|
+
"bundled",
|
|
276
|
+
],
|
|
277
|
+
...this.scopeDirectories("user").map(
|
|
278
|
+
(directory): [string, NonNullable<AgentType["source"]>] => [
|
|
279
|
+
directory,
|
|
280
|
+
"user",
|
|
281
|
+
],
|
|
282
|
+
),
|
|
229
283
|
];
|
|
230
284
|
if (this.options.includeProject)
|
|
231
|
-
layers.push(
|
|
285
|
+
layers.push(
|
|
286
|
+
...this.scopeDirectories("project").map(
|
|
287
|
+
(directory): [string, NonNullable<AgentType["source"]>] => [
|
|
288
|
+
directory,
|
|
289
|
+
"project",
|
|
290
|
+
],
|
|
291
|
+
),
|
|
292
|
+
);
|
|
232
293
|
for (const [directory, source] of layers) {
|
|
233
294
|
let files: string[];
|
|
234
295
|
try {
|
|
@@ -252,7 +313,9 @@ export class ConfigStore {
|
|
|
252
313
|
let content = "";
|
|
253
314
|
try {
|
|
254
315
|
if (!lstatSync(filePath).isFile())
|
|
255
|
-
throw new Error(
|
|
316
|
+
throw new Error(
|
|
317
|
+
"Agent definition must be a regular file, not a symlink",
|
|
318
|
+
);
|
|
256
319
|
content = readFileSync(filePath, "utf8");
|
|
257
320
|
const type = parseAgentType(content, filePath);
|
|
258
321
|
if (seenNames.has(type.name)) {
|
|
@@ -290,7 +353,9 @@ export class ConfigStore {
|
|
|
290
353
|
}
|
|
291
354
|
|
|
292
355
|
list(): AgentType[] {
|
|
293
|
-
return structuredClone(
|
|
356
|
+
return structuredClone(
|
|
357
|
+
[...this.types.values()].sort((a, b) => a.name.localeCompare(b.name)),
|
|
358
|
+
);
|
|
294
359
|
}
|
|
295
360
|
|
|
296
361
|
get(name: string): AgentType {
|
|
@@ -303,27 +368,71 @@ export class ConfigStore {
|
|
|
303
368
|
return this.options.includeProject;
|
|
304
369
|
}
|
|
305
370
|
|
|
306
|
-
private
|
|
307
|
-
if (scope !== "user" && scope !== "project")
|
|
371
|
+
private preferredScopeDirectory(scope: AgentScope): string {
|
|
372
|
+
if (scope !== "user" && scope !== "project")
|
|
373
|
+
throw new Error("Invalid agent scope");
|
|
308
374
|
if (scope === "project" && !this.options.includeProject)
|
|
309
375
|
throw new Error("Project agents are not enabled/trusted");
|
|
310
376
|
return scope === "user"
|
|
311
|
-
? resolve(this.options.agentDir,
|
|
312
|
-
: resolve(
|
|
377
|
+
? resolve(this.options.agentDir, SUBAGENT_MANAGER_DIR, AGENTS_DIR)
|
|
378
|
+
: resolve(
|
|
379
|
+
this.options.cwd,
|
|
380
|
+
".pi",
|
|
381
|
+
"agent",
|
|
382
|
+
SUBAGENT_MANAGER_DIR,
|
|
383
|
+
AGENTS_DIR,
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
private scopeDirectories(scope: AgentScope): string[] {
|
|
388
|
+
return scope === "user"
|
|
389
|
+
? [
|
|
390
|
+
resolve(this.options.agentDir, AGENTS_DIR),
|
|
391
|
+
this.preferredScopeDirectory(scope),
|
|
392
|
+
]
|
|
393
|
+
: [
|
|
394
|
+
resolve(this.options.cwd, ".pi", AGENTS_DIR),
|
|
395
|
+
this.preferredScopeDirectory(scope),
|
|
396
|
+
];
|
|
313
397
|
}
|
|
314
398
|
|
|
315
399
|
private destinationBasePaths(scope: AgentScope, directory: string): string[] {
|
|
316
|
-
|
|
317
|
-
|
|
400
|
+
if (scope === "user") {
|
|
401
|
+
const base = resolve(this.options.agentDir);
|
|
402
|
+
return [base, join(base, SUBAGENT_MANAGER_DIR), directory];
|
|
403
|
+
}
|
|
404
|
+
const base = resolve(this.options.cwd);
|
|
405
|
+
const projectPi = join(base, ".pi");
|
|
406
|
+
const projectAgent = join(projectPi, "agent");
|
|
407
|
+
return [
|
|
408
|
+
base,
|
|
409
|
+
projectPi,
|
|
410
|
+
projectAgent,
|
|
411
|
+
join(projectAgent, SUBAGENT_MANAGER_DIR),
|
|
412
|
+
directory,
|
|
413
|
+
];
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
private canPreserveDestination(
|
|
417
|
+
name: string,
|
|
418
|
+
scope: AgentScope,
|
|
419
|
+
original?: SaveOrigin,
|
|
420
|
+
): boolean {
|
|
421
|
+
return (
|
|
422
|
+
original?.name === name &&
|
|
423
|
+
original.source === scope &&
|
|
424
|
+
typeof original.filePath === "string" &&
|
|
425
|
+
dirname(resolve(original.filePath)) ===
|
|
426
|
+
this.preferredScopeDirectory(scope)
|
|
427
|
+
);
|
|
318
428
|
}
|
|
319
429
|
|
|
320
430
|
destination(name: string, scope: AgentScope, original?: SaveOrigin): string {
|
|
321
431
|
if (!NAME.test(name)) throw new Error("Unsafe agent name");
|
|
322
|
-
const directory = this.
|
|
432
|
+
const directory = this.preferredScopeDirectory(scope);
|
|
323
433
|
if (
|
|
324
|
-
|
|
325
|
-
original
|
|
326
|
-
typeof original.filePath === "string"
|
|
434
|
+
this.canPreserveDestination(name, scope, original) &&
|
|
435
|
+
typeof original?.filePath === "string"
|
|
327
436
|
) {
|
|
328
437
|
return validatePreservedDestination(original.filePath, directory);
|
|
329
438
|
}
|
|
@@ -336,13 +445,19 @@ export class ConfigStore {
|
|
|
336
445
|
const filePath = this.destination(validated.name, scope, original);
|
|
337
446
|
const directory = dirname(filePath);
|
|
338
447
|
// Reject redirected destination directories and files before writing.
|
|
339
|
-
for (const path of [
|
|
448
|
+
for (const path of [
|
|
449
|
+
...this.destinationBasePaths(scope, directory),
|
|
450
|
+
filePath,
|
|
451
|
+
]) {
|
|
340
452
|
const stat = assertNotSymlinkPath(path);
|
|
341
453
|
if (path === filePath && stat && !stat.isFile())
|
|
342
454
|
throw new Error(`Unsafe agent destination: ${filePath}`);
|
|
343
455
|
}
|
|
344
456
|
mkdirSync(directory, { recursive: true });
|
|
345
|
-
const temporary = join(
|
|
457
|
+
const temporary = join(
|
|
458
|
+
dirname(filePath),
|
|
459
|
+
`.${validated.name}.${randomUUID()}.tmp`,
|
|
460
|
+
);
|
|
346
461
|
try {
|
|
347
462
|
writeFileSync(temporary, content, { flag: "wx", mode: 0o600 });
|
|
348
463
|
renameSync(temporary, filePath);
|
package/src/index.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { buildSessionContext, getAgentDir } from "@earendil-works/pi-coding-agen
|
|
|
3
3
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { ConfigStore } from "./config.ts";
|
|
5
5
|
import { ThreadManager } from "./manager.ts";
|
|
6
|
+
import { DEFAULT_MANAGER_SETTINGS, loadManagerSettings } from "./settings.ts";
|
|
6
7
|
import { createDriverFactory } from "./runtime.ts";
|
|
7
8
|
import { agentTools } from "./tools.ts";
|
|
8
9
|
import { editAgentTypes, showThreads, updateWidget } from "./ui.ts";
|
|
@@ -24,6 +25,16 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
24
25
|
includeProject: false,
|
|
25
26
|
});
|
|
26
27
|
let manager: ThreadManager | undefined;
|
|
28
|
+
let limits = { ...DEFAULT_MANAGER_SETTINGS };
|
|
29
|
+
const loadLimits = (ctx: ExtensionContext) => {
|
|
30
|
+
const loaded = loadManagerSettings({
|
|
31
|
+
cwd: ctx.cwd,
|
|
32
|
+
agentDir: getAgentDir(),
|
|
33
|
+
includeProject: ctx.isProjectTrusted(),
|
|
34
|
+
});
|
|
35
|
+
limits = loaded.settings;
|
|
36
|
+
return loaded.diagnostics;
|
|
37
|
+
};
|
|
27
38
|
let generation = 0;
|
|
28
39
|
let persistenceSignature = "";
|
|
29
40
|
const requireManager = () => {
|
|
@@ -112,7 +123,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
112
123
|
|
|
113
124
|
for (const tool of agentTools(requireManager, "/root", () => store.list())) pi.registerTool(tool);
|
|
114
125
|
pi.on("before_agent_start", async (event) => ({
|
|
115
|
-
systemPrompt: `${event.systemPrompt}\n\n## pi-subagent\nYou are /root. Thread paths determine context ancestry, independently of agent type. Children can pause WITHOUT handing back an answer; completed and paused sessions can both receive more work via agent_steer. Working child threads appear above the footer. Available types:\n${store
|
|
126
|
+
systemPrompt: `${event.systemPrompt}\n\n## pi-subagent\nYou are /root. Thread paths determine context ancestry, independently of agent type. Children can pause WITHOUT handing back an answer; completed and paused sessions can both receive more work via agent_steer. Working child threads appear above the footer. The main conversation is L1; the maximum is ${limits.maxLevels} levels including L1. For independent work, spawn all siblings with wait:false before calling agent_wait; the same pattern applies inside child agents that have delegation tools. Waiting parents count toward the shared ${limits.maxConcurrent}-thread concurrency limit. Available types:\n${store
|
|
116
127
|
.list()
|
|
117
128
|
.map((type) => `- ${type.name}: ${type.description}`)
|
|
118
129
|
.join(
|
|
@@ -131,7 +142,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
131
142
|
includeProject: ctx.isProjectTrusted(),
|
|
132
143
|
});
|
|
133
144
|
persistenceSignature = "";
|
|
145
|
+
const settingsDiagnostics = loadLimits(ctx);
|
|
134
146
|
const instance = new ThreadManager({
|
|
147
|
+
...limits,
|
|
135
148
|
createDriver: createDriverFactory(requireContext),
|
|
136
149
|
rootSnapshot: () => buildSessionContext(requireContext().sessionManager.getBranch()).messages,
|
|
137
150
|
getType: (name) => store.get(name),
|
|
@@ -167,7 +180,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
167
180
|
}
|
|
168
181
|
restoreRootMailbox(ctx);
|
|
169
182
|
updateWidget(ctx, requireManager().list());
|
|
170
|
-
|
|
183
|
+
const diagnostics = [...store.diagnostics, ...settingsDiagnostics];
|
|
184
|
+
if (diagnostics.length) ctx.ui.notify(diagnostics.join("\n"), "warning");
|
|
171
185
|
};
|
|
172
186
|
pi.on("session_start", async (_event, ctx) => attachSession(ctx));
|
|
173
187
|
pi.on("session_tree", async (_event, ctx) => attachSession(ctx));
|
|
@@ -202,11 +216,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
202
216
|
store.reload();
|
|
203
217
|
} else if (command === "reload") {
|
|
204
218
|
store.reload();
|
|
219
|
+
const diagnostics = [...store.diagnostics, ...loadLimits(ctx)];
|
|
220
|
+
requireManager().setLimits(limits);
|
|
205
221
|
ctx.ui.notify(
|
|
206
|
-
|
|
207
|
-
?
|
|
208
|
-
: `Loaded ${store.list().length} agent types`,
|
|
209
|
-
|
|
222
|
+
diagnostics.length
|
|
223
|
+
? diagnostics.join("\n")
|
|
224
|
+
: `Loaded ${store.list().length} agent types; maximum ${limits.maxLevels} levels`,
|
|
225
|
+
diagnostics.length ? "warning" : "info",
|
|
210
226
|
);
|
|
211
227
|
} else if (!command || command === "thread") {
|
|
212
228
|
await showThreads(ctx, requireManager().scope("/root"), rest.join(" ") || undefined);
|
package/src/manager.ts
CHANGED
|
@@ -10,6 +10,7 @@ import type {
|
|
|
10
10
|
ThreadView,
|
|
11
11
|
} from "./types.ts";
|
|
12
12
|
import { canonicalPath, inheritContext, isDescendant, parentPath } from "./paths.ts";
|
|
13
|
+
import { DEFAULT_MANAGER_SETTINGS, type ManagerSettings } from "./settings.ts";
|
|
13
14
|
|
|
14
15
|
interface Record {
|
|
15
16
|
view: ThreadView;
|
|
@@ -58,6 +59,11 @@ export class ThreadManager {
|
|
|
58
59
|
private epoch = 0;
|
|
59
60
|
constructor(private options: ManagerOptions) {}
|
|
60
61
|
|
|
62
|
+
/** New limits affect future launches/resumes, never cancel existing work. */
|
|
63
|
+
setLimits(limits: ManagerSettings): void {
|
|
64
|
+
this.options = { ...this.options, ...limits };
|
|
65
|
+
}
|
|
66
|
+
|
|
61
67
|
list(): ThreadView[] {
|
|
62
68
|
return [...this.records.values()].map((record) => this.view(record));
|
|
63
69
|
}
|
|
@@ -199,9 +205,17 @@ export class ThreadManager {
|
|
|
199
205
|
if (caller !== "/root" && parent !== caller)
|
|
200
206
|
throw new Error("An agent may spawn only its immediate children");
|
|
201
207
|
if (!args.task.trim()) throw new Error("Task must not be empty");
|
|
202
|
-
|
|
208
|
+
const segments = path.slice(1).split("/");
|
|
209
|
+
// Independent roots still represent agents launched by the main L1 conversation.
|
|
210
|
+
const level = segments.length + (segments[0] === "root" ? 0 : 1);
|
|
211
|
+
const maxLevels = this.options.maxLevels ?? DEFAULT_MANAGER_SETTINGS.maxLevels;
|
|
212
|
+
if (
|
|
213
|
+
this.options.maxLevels === undefined && this.options.maxDepth !== undefined
|
|
214
|
+
? segments.length - 1 > this.options.maxDepth
|
|
215
|
+
: level > maxLevels
|
|
216
|
+
)
|
|
203
217
|
throw new Error("Agent depth limit reached");
|
|
204
|
-
if (this.records.size >= (this.options.maxThreads ??
|
|
218
|
+
if (this.records.size >= (this.options.maxThreads ?? DEFAULT_MANAGER_SETTINGS.maxThreads))
|
|
205
219
|
throw new Error("Total thread limit reached");
|
|
206
220
|
this.assertCapacity();
|
|
207
221
|
const type = structuredClone(this.options.getType(args.type));
|
|
@@ -450,6 +464,7 @@ export class ThreadManager {
|
|
|
450
464
|
const parentRecord = this.record(record.view.parent);
|
|
451
465
|
if (!parentRecord.driver) await this.ensureDriver(parentRecord, readOnly);
|
|
452
466
|
}
|
|
467
|
+
const parentSessionFile = this.lexicalParentSessionFile(record);
|
|
453
468
|
const options: DriverOptions = {
|
|
454
469
|
path: record.view.path,
|
|
455
470
|
type: record.definition,
|
|
@@ -469,6 +484,7 @@ export class ThreadManager {
|
|
|
469
484
|
this.touch(record);
|
|
470
485
|
}
|
|
471
486
|
},
|
|
487
|
+
...(parentSessionFile ? { parentSessionFile } : {}),
|
|
472
488
|
...(record.sessionLeafId !== undefined ? { sessionLeafId: record.sessionLeafId } : {}),
|
|
473
489
|
};
|
|
474
490
|
return this.options.createDriver(options);
|
|
@@ -527,6 +543,14 @@ export class ThreadManager {
|
|
|
527
543
|
const leaf = record.driver?.sessionLeafId;
|
|
528
544
|
return leaf !== undefined ? leaf : record.sessionLeafId;
|
|
529
545
|
}
|
|
546
|
+
/** Live persisted file, else the saved file of a restored parent that has not been opened. */
|
|
547
|
+
private lexicalParentSessionFile(record: Record): string | undefined {
|
|
548
|
+
const parent = record.view.parent;
|
|
549
|
+
if (!parent || parent === "/root") return undefined;
|
|
550
|
+
const parentRecord = this.records.get(parent);
|
|
551
|
+
if (!parentRecord) return undefined;
|
|
552
|
+
return parentRecord.driver?.sessionFile ?? parentRecord.view.sessionFile;
|
|
553
|
+
}
|
|
530
554
|
private view(record: Record): ThreadView {
|
|
531
555
|
return structuredClone({
|
|
532
556
|
...record.view,
|
|
@@ -560,7 +584,7 @@ export class ThreadManager {
|
|
|
560
584
|
private assertCapacity(): void {
|
|
561
585
|
if (
|
|
562
586
|
[...this.records.values()].filter((record) => active(record.view)).length >=
|
|
563
|
-
(this.options.maxConcurrent ??
|
|
587
|
+
(this.options.maxConcurrent ?? DEFAULT_MANAGER_SETTINGS.maxConcurrent)
|
|
564
588
|
)
|
|
565
589
|
throw new Error("Concurrent thread limit reached; wait for a thread to settle");
|
|
566
590
|
}
|