@ferris1225/pi-subagents 7.0.0 → 7.0.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/CHANGELOG.md +22 -0
- package/README.md +30 -24
- package/index.ts +4 -11
- package/package.json +1 -1
- package/src/configuration/config.ts +39 -25
- package/src/configuration/models.ts +9 -42
- package/src/configuration/setup.ts +43 -30
- package/src/configuration/ui.ts +81 -49
- package/src/delegation/agents.ts +7 -7
- package/src/delegation/builtin-agents.ts +7 -7
- package/src/delegation/dispatch.ts +2 -2
- package/src/delegation/orchestration.ts +11 -7
- package/src/delegation/prompt.ts +3 -15
- package/src/execution/cli-run.ts +9 -7
- package/src/execution/run-control.ts +3 -3
- package/src/isolation/git-command.ts +2 -2
- package/src/isolation/recovery.ts +8 -24
- package/src/isolation/temp-hygiene.ts +1 -1
- package/src/lifecycle/durable.ts +15 -27
- package/src/lifecycle/stop.ts +2 -2
- package/src/lifecycle/thread-lifecycle.ts +2 -2
- package/src/lifecycle/thread-restore.ts +4 -6
- package/src/lifecycle/thread-shared.ts +9 -7
- package/src/lifecycle/tools.ts +2 -4
- package/src/presentation/announcements.ts +11 -15
- package/src/presentation/format.ts +1 -1
- package/src/presentation/monitor.ts +2 -7
package/src/configuration/ui.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Role settings and searchable model selection in a keyboard-driven overlay. */
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
4
|
Input, fuzzyFilter, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi,
|
|
5
5
|
type Component, type Focusable, type Keybinding, type KeybindingsManager, type OverlayOptions, type SelectItem, type TUI,
|
|
6
6
|
} from "@earendil-works/pi-tui";
|
|
7
7
|
import type { ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { BUILTIN_AGENT_NAMES, type AgentName } from "./config.ts";
|
|
8
9
|
|
|
9
10
|
type PickerContext = Pick<ExtensionCommandContext, "mode" | "ui">;
|
|
10
11
|
const PAGE_SIZE = 10;
|
|
@@ -19,9 +20,16 @@ export const SETUP_OVERLAY_OPTIONS: OverlayOptions = {
|
|
|
19
20
|
|
|
20
21
|
/** Modal height budget on the full terminal canvas instead of the input dock. */
|
|
21
22
|
function setupHeight(tui: TUI): number {
|
|
22
|
-
const termRows = tui.terminal
|
|
23
|
+
const termRows = tui.terminal.rows;
|
|
23
24
|
const maxRows = Math.floor(termRows * 0.88);
|
|
24
|
-
return Math.max(
|
|
25
|
+
return Math.max(1, Math.min(maxRows, termRows - 2));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function keyLabel(keys: KeybindingsManager, action: Keybinding): string {
|
|
29
|
+
const key = keys.getKeys(action)[0];
|
|
30
|
+
if (!key) return "unbound";
|
|
31
|
+
const labels: Record<string, string> = { up: "↑", down: "↓", enter: "Enter", escape: "Esc", pageUp: "PgUp", pageDown: "PgDn", ctrl: "Ctrl", alt: "Alt", shift: "Shift" };
|
|
32
|
+
return key.split("+").map((part) => labels[part] ?? part).join("+");
|
|
25
33
|
}
|
|
26
34
|
|
|
27
35
|
function padToWidth(text: string, width: number): string {
|
|
@@ -115,10 +123,7 @@ class Picker implements Component, Focusable {
|
|
|
115
123
|
}
|
|
116
124
|
|
|
117
125
|
private keyLabel(action: Keybinding): string {
|
|
118
|
-
|
|
119
|
-
if (!key) return "unbound";
|
|
120
|
-
const labels: Record<string, string> = { up: "↑", down: "↓", enter: "Enter", escape: "Esc", pageUp: "PgUp", pageDown: "PgDn", ctrl: "Ctrl", alt: "Alt", shift: "Shift" };
|
|
121
|
-
return key.split("+").map((part) => labels[part] ?? part).join("+");
|
|
126
|
+
return keyLabel(this.keybindings, action);
|
|
122
127
|
}
|
|
123
128
|
|
|
124
129
|
private detailLines(width: number): string[] {
|
|
@@ -151,7 +156,7 @@ class Picker implements Component, Focusable {
|
|
|
151
156
|
theme.bold(this.options.title + (this.details ? " · Details" : "")),
|
|
152
157
|
...(this.details ? [] : this.search.render(innerWidth)),
|
|
153
158
|
item ? theme.fg("accent", "› ") + theme.underline(item.label + (this.isSaved(item) ? " [saved]" : "")) : "No matches. Clear or change the search.",
|
|
154
|
-
].map((line) => truncateToWidth(line, width, "…"));
|
|
159
|
+
].slice(0, height).map((line) => truncateToWidth(line, width, "…"));
|
|
155
160
|
}
|
|
156
161
|
|
|
157
162
|
const navigation = move + " move · " + confirm + " select · " + cancel + " back";
|
|
@@ -289,29 +294,38 @@ export function promptSelectOne(
|
|
|
289
294
|
);
|
|
290
295
|
}
|
|
291
296
|
|
|
292
|
-
export interface
|
|
293
|
-
|
|
297
|
+
export interface RoleSettingsView {
|
|
298
|
+
role: AgentName;
|
|
294
299
|
model: string;
|
|
295
300
|
thinking: string;
|
|
296
|
-
|
|
301
|
+
unavailable: boolean;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export interface SettingsView {
|
|
305
|
+
main: string;
|
|
306
|
+
roles: RoleSettingsView[];
|
|
297
307
|
status: string;
|
|
298
|
-
focus:
|
|
308
|
+
focus: SettingKey;
|
|
299
309
|
}
|
|
300
310
|
|
|
301
|
-
const
|
|
311
|
+
const SETTING_FIELDS = ["model", "thinking", "reset"] as const;
|
|
312
|
+
export type SettingKey = `${AgentName}.${(typeof SETTING_FIELDS)[number]}`;
|
|
313
|
+
const SETTING_KEYS = BUILTIN_AGENT_NAMES.flatMap((role) => SETTING_FIELDS.map((field): SettingKey => `${role}.${field}`));
|
|
314
|
+
const ROLE_LABELS: Record<AgentName, string> = { researcher: "Researcher", worker: "Worker" };
|
|
315
|
+
const ROLE_DESCRIPTIONS: Record<AgentName, string> = { researcher: "Read-only research", worker: "Implementation & checks" };
|
|
302
316
|
|
|
303
|
-
class
|
|
317
|
+
class RoleSettings implements Component {
|
|
304
318
|
private cursor: number;
|
|
305
319
|
private detailTop = 0;
|
|
306
320
|
private detailPage = 1;
|
|
307
|
-
private readonly view:
|
|
321
|
+
private readonly view: SettingsView;
|
|
308
322
|
private readonly tui: TUI;
|
|
309
323
|
private readonly theme: Theme;
|
|
310
324
|
private readonly keys: KeybindingsManager;
|
|
311
|
-
private readonly done: (value:
|
|
325
|
+
private readonly done: (value: SettingKey | undefined) => void;
|
|
312
326
|
constructor(
|
|
313
|
-
view:
|
|
314
|
-
keys: KeybindingsManager, done: (value:
|
|
327
|
+
view: SettingsView, tui: TUI, theme: Theme,
|
|
328
|
+
keys: KeybindingsManager, done: (value: SettingKey | undefined) => void,
|
|
315
329
|
) {
|
|
316
330
|
this.view = view;
|
|
317
331
|
this.tui = tui;
|
|
@@ -324,42 +338,60 @@ class WorkerSettings implements Component {
|
|
|
324
338
|
render(width: number): string[] {
|
|
325
339
|
if (width <= 0) return [];
|
|
326
340
|
const height = setupHeight(this.tui);
|
|
327
|
-
const framed = width >=
|
|
341
|
+
const framed = width >= 36 && height >= 20;
|
|
328
342
|
const inner = Math.max(1, width - (framed ? 4 : 0));
|
|
329
|
-
const
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
return index === this.cursor ? this.theme.fg("accent", "› " + this.theme.bold(line)) : " " + line;
|
|
343
|
+
const theme = this.theme;
|
|
344
|
+
const entries = BUILTIN_AGENT_NAMES.flatMap((role) => {
|
|
345
|
+
const view = this.view.roles.find((entry) => entry.role === role)!;
|
|
346
|
+
return SETTING_FIELDS.map((field) => ({ role, field, view }));
|
|
334
347
|
});
|
|
335
|
-
const
|
|
336
|
-
const
|
|
337
|
-
const key = (action: Keybinding) =>
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
348
|
+
const active = entries[this.cursor]!;
|
|
349
|
+
const label = ROLE_LABELS[active.role];
|
|
350
|
+
const key = (action: Keybinding) => keyLabel(this.keys, action);
|
|
351
|
+
const navigation = key("tui.select.up") + key("tui.select.down") + " move · " + key("tui.select.confirm") + " edit · " + key("tui.select.cancel") + " close";
|
|
352
|
+
const rows: string[] = [];
|
|
353
|
+
for (const [index, { role, field, view }] of entries.entries()) {
|
|
354
|
+
if (framed && field === "model") {
|
|
355
|
+
if (index) rows.push("");
|
|
356
|
+
rows.push(theme.bold(ROLE_LABELS[role]) + theme.fg("muted", " · " + ROLE_DESCRIPTIONS[role]));
|
|
357
|
+
}
|
|
358
|
+
const name = field === "model" ? "Model" : field === "thinking" ? "Thinking" : "Reset";
|
|
359
|
+
const value = field === "model" ? view.model : field === "thinking" ? view.thinking : "Follow main · medium";
|
|
360
|
+
const prefix = framed ? name.padEnd(10) : ROLE_LABELS[role] + " " + name + " ";
|
|
361
|
+
const warning = field === "model" && view.unavailable ? " [unavailable]" : "";
|
|
362
|
+
const line = truncateToWidth(prefix + value, Math.max(1, inner - 2 - visibleWidth(warning)), "…") + theme.fg("warning", warning);
|
|
363
|
+
rows.push(index === this.cursor ? theme.fg("accent", "› " + theme.bold(line)) : " " + line);
|
|
345
364
|
}
|
|
346
|
-
|
|
365
|
+
const detail = active.field === "reset"
|
|
366
|
+
? "Reset only " + label + " to Follow main and medium thinking."
|
|
367
|
+
: label + " " + active.field + ": " + active.view[active.field];
|
|
368
|
+
const details = wrapTextWithAnsi(detail + (active.view.unavailable ? " · Model unavailable; choose an available model to resume this role." : ""), inner);
|
|
369
|
+
const footer = [this.view.status, navigation];
|
|
370
|
+
const header = [theme.fg("muted", truncateToWidth("Main · " + this.view.main, inner, "…"))];
|
|
371
|
+
if (framed) header.push("");
|
|
372
|
+
const chrome = framed ? 4 : 1;
|
|
373
|
+
const rowBudget = Math.max(1, height - chrome - header.length - footer.length);
|
|
374
|
+
const start = framed ? 0 : Math.max(0, Math.min(this.cursor - Math.floor(rowBudget / 2), rows.length - rowBudget));
|
|
375
|
+
const visibleRows = rows.slice(start, start + rowBudget);
|
|
376
|
+
const detailBudget = Math.max(0, height - chrome - header.length - visibleRows.length - footer.length - 1);
|
|
377
|
+
this.detailPage = Math.max(1, detailBudget);
|
|
347
378
|
this.detailTop = Math.max(0, Math.min(this.detailTop, details.length - this.detailPage));
|
|
348
|
-
const body = [
|
|
349
|
-
|
|
350
|
-
"", ...
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
if (
|
|
355
|
-
|
|
379
|
+
const body = [...header, ...visibleRows];
|
|
380
|
+
if (detailBudget) {
|
|
381
|
+
body.push("", ...details.slice(this.detailTop, this.detailTop + detailBudget).map((line) => theme.fg(active.view.unavailable ? "warning" : "muted", line)));
|
|
382
|
+
if (details.length > detailBudget) footer[0] = key("tui.select.pageUp") + "/" + key("tui.select.pageDown") + " details · " + this.view.status;
|
|
383
|
+
}
|
|
384
|
+
if (framed) return framePanel(theme, width, "Subagents · Models & thinking", undefined, body, footer);
|
|
385
|
+
if (height < 6) return [theme.bold(label), rows[this.cursor]!, key("tui.select.confirm") + " edit · " + key("tui.select.cancel") + " close"]
|
|
386
|
+
.slice(0, height).map((line) => truncateToWidth(line, width, "…"));
|
|
387
|
+
return [theme.bold("Subagents"), ...body, ...footer].map((line) => truncateToWidth(line, width, "…"));
|
|
356
388
|
}
|
|
357
389
|
|
|
358
390
|
handleInput(data: string): void {
|
|
359
391
|
if (this.keys.matches(data, "tui.select.cancel")) { this.done(undefined); return; }
|
|
360
392
|
if (this.keys.matches(data, "tui.select.confirm")) { this.done(SETTING_KEYS[this.cursor]); return; }
|
|
361
|
-
if (this.keys.matches(data, "tui.select.up")) { this.cursor = (this.cursor +
|
|
362
|
-
else if (this.keys.matches(data, "tui.select.down")) { this.cursor = (this.cursor + 1) %
|
|
393
|
+
if (this.keys.matches(data, "tui.select.up")) { this.cursor = (this.cursor + SETTING_KEYS.length - 1) % SETTING_KEYS.length; this.detailTop = 0; }
|
|
394
|
+
else if (this.keys.matches(data, "tui.select.down")) { this.cursor = (this.cursor + 1) % SETTING_KEYS.length; this.detailTop = 0; }
|
|
363
395
|
else if (this.keys.matches(data, "tui.select.pageUp")) this.detailTop -= this.detailPage;
|
|
364
396
|
else if (this.keys.matches(data, "tui.select.pageDown")) this.detailTop += this.detailPage;
|
|
365
397
|
this.tui.requestRender();
|
|
@@ -368,9 +400,9 @@ class WorkerSettings implements Component {
|
|
|
368
400
|
invalidate(): void {}
|
|
369
401
|
}
|
|
370
402
|
|
|
371
|
-
export function promptSettings(ctx: PickerContext, view:
|
|
372
|
-
return ctx.ui.custom<
|
|
373
|
-
(tui, theme, keys, done) => new
|
|
374
|
-
{ overlay: true, overlayOptions: SETUP_OVERLAY_OPTIONS, blocked: { kind: "question", message: "Configure subagent
|
|
403
|
+
export function promptSettings(ctx: PickerContext, view: SettingsView): Promise<SettingKey | undefined> {
|
|
404
|
+
return ctx.ui.custom<SettingKey | undefined>(
|
|
405
|
+
(tui, theme, keys, done) => new RoleSettings(view, tui, theme, keys, done),
|
|
406
|
+
{ overlay: true, overlayOptions: SETUP_OVERLAY_OPTIONS, blocked: { kind: "question", message: "Configure subagent models and thinking" } },
|
|
375
407
|
);
|
|
376
408
|
}
|
package/src/delegation/agents.ts
CHANGED
|
@@ -65,7 +65,7 @@ function isReadOnlyToolName(name: string, index: ToolInfoIndex): boolean {
|
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
/** Resolve a child against the parent's active and callable indirect tools.
|
|
68
|
-
* Inactive direct tools stay excluded.
|
|
68
|
+
* Inactive direct tools stay excluded. Researcher promotes only tools marked
|
|
69
69
|
* read-only; pi-subagents controls are removed so children stay leaves. */
|
|
70
70
|
export function resolveAgentTools(
|
|
71
71
|
agent: AgentConfig,
|
|
@@ -79,19 +79,19 @@ export function resolveAgentTools(
|
|
|
79
79
|
.map((tool) => tool.name)
|
|
80
80
|
.filter((name) => !active.includes(name))
|
|
81
81
|
.sort();
|
|
82
|
-
if (agent.name !== "
|
|
83
|
-
//
|
|
82
|
+
if (agent.name !== "researcher") return { ...agent, tools: [...active, ...indirect] };
|
|
83
|
+
// Researcher uses the live catalog's read-only classification. Codemode and
|
|
84
84
|
// tool_search are excluded because they can reach tools outside that set.
|
|
85
85
|
const tools = active.filter((tool) => isReadOnlyToolName(tool, toolIndex));
|
|
86
86
|
// The child explicitly activates these after registration, without giving
|
|
87
|
-
//
|
|
87
|
+
// researcher an orchestrating tool that could also reach writers.
|
|
88
88
|
if (active.some((tool) => toolIndex.get(tool)?.reachesTools)) {
|
|
89
89
|
tools.push(...indirect.filter((name) => isReadOnlyToolName(name, toolIndex)));
|
|
90
90
|
}
|
|
91
91
|
return { ...agent, tools };
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
/** Filesystem-write capability used by worktree admission.
|
|
94
|
+
/** Filesystem-write capability used by worktree admission. Researcher is a hard
|
|
95
95
|
* read-only boundary. An unresolved tools list means the child inherits
|
|
96
96
|
* arbitrary active tools and is therefore mutable; for a resolved list only
|
|
97
97
|
* proven read-only tools count as safe — shells, tool-reaching tools, and tools
|
|
@@ -100,8 +100,8 @@ export function isWriteCapableAgent(
|
|
|
100
100
|
agent: Pick<AgentConfig, "name" | "tools">,
|
|
101
101
|
toolInfos?: readonly ToolMetadata[],
|
|
102
102
|
): boolean {
|
|
103
|
-
if (agent.name === "
|
|
104
|
-
if (agent.name === "
|
|
103
|
+
if (agent.name === "researcher") return false;
|
|
104
|
+
if (agent.name === "worker") return true;
|
|
105
105
|
if (!agent.tools) return true;
|
|
106
106
|
const toolIndex = indexToolInfos(toolInfos);
|
|
107
107
|
return agent.tools.some((tool) => !isReadOnlyToolName(tool, toolIndex));
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* Worker prompts stay tool-agnostic: the host decides whether a writer
|
|
8
8
|
* reaches its tools directly or through a script tool such as
|
|
9
|
-
* codemode.
|
|
9
|
+
* codemode. Researcher receives only direct read-only tools.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
export interface BuiltinAgentDefinition {
|
|
@@ -15,7 +15,7 @@ export interface BuiltinAgentDefinition {
|
|
|
15
15
|
systemPrompt: string;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
const
|
|
18
|
+
const RESEARCHER_SYSTEM_PROMPT = `Answer the brief's bounded research question. Follow the brief within loaded project instructions; this role supplies the working method. The read-only boundary still wins. You have no interactive clarification; state material assumptions and gaps, then finish.
|
|
19
19
|
|
|
20
20
|
## Rules
|
|
21
21
|
|
|
@@ -30,7 +30,7 @@ const SCOUT_SYSTEM_PROMPT = `Answer the brief's bounded research question. Follo
|
|
|
30
30
|
Lead with the answer. Return only findings needed for the brief, with decisive citations rather than raw search logs or whole files. Cite repository facts as \`path:line-range\` and external facts as source URLs. Distinguish inference from verified facts, and name unresolved gaps.
|
|
31
31
|
`;
|
|
32
32
|
|
|
33
|
-
const
|
|
33
|
+
const WORKER_SYSTEM_PROMPT = `Execute the lead's bounded plan: implementation, fix, tests, or docs. Main owns architecture, ambiguity, review, and acceptance. Follow the brief within loaded project instructions; this role supplies the working method. The leaf boundary below still wins. You have no interactive clarification; resolve routine details, state material assumptions, and finish the authorized outcome.
|
|
34
34
|
|
|
35
35
|
## Rules
|
|
36
36
|
|
|
@@ -48,14 +48,14 @@ Lead with the outcome and whether the done condition was met. Keep the handoff c
|
|
|
48
48
|
|
|
49
49
|
export const BUILTIN_AGENTS: readonly BuiltinAgentDefinition[] = [
|
|
50
50
|
{
|
|
51
|
-
name: "
|
|
51
|
+
name: "researcher",
|
|
52
52
|
description:
|
|
53
53
|
"Search code, documentation, or external facts with citations; retrieval only, no commands or edits.",
|
|
54
|
-
systemPrompt:
|
|
54
|
+
systemPrompt: RESEARCHER_SYSTEM_PROMPT,
|
|
55
55
|
},
|
|
56
56
|
{
|
|
57
|
-
name: "
|
|
57
|
+
name: "worker",
|
|
58
58
|
description: "Implement a bounded change through its tests, docs, and verification.",
|
|
59
|
-
systemPrompt:
|
|
59
|
+
systemPrompt: WORKER_SYSTEM_PROMPT,
|
|
60
60
|
},
|
|
61
61
|
];
|
|
@@ -70,7 +70,7 @@ const SubagentParams = Type.Object({
|
|
|
70
70
|
/** Explicit overrides win. Implementation uses a worktree even for a single
|
|
71
71
|
* task; research and review stay in the current directory. */
|
|
72
72
|
export function defaultIsolationMode(agentName: string, requested?: IsolationMode): IsolationMode {
|
|
73
|
-
return requested ?? (agentName === "
|
|
73
|
+
return requested ?? (agentName === "worker" ? "worktree" : "shared");
|
|
74
74
|
}
|
|
75
75
|
|
|
76
76
|
interface PreparedDispatchTask {
|
|
@@ -162,7 +162,7 @@ export function registerSubagentTool(
|
|
|
162
162
|
pi.registerTool({
|
|
163
163
|
name: "subagent",
|
|
164
164
|
label: "Subagent",
|
|
165
|
-
description: "Dispatch workers to execute main's plan:
|
|
165
|
+
description: "Dispatch workers to execute main's plan: worker implements and verifies; researcher retrieves read-only evidence. Main reviews the integrated changes and owns acceptance. Use tasks for independent phases. Duplicate phases are rejected before allocation. Omit isolation for automatic selection. Use wait:true for dependencies; print/JSON sessions wait by default. Background results wake main.",
|
|
166
166
|
// Admission and lease reservation finish synchronously before child startup.
|
|
167
167
|
// Awaited runs must not block unrelated dispatch calls.
|
|
168
168
|
exposure: "model-only",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Keep changing model assignments outside the stable orchestration contract. */
|
|
2
2
|
|
|
3
|
-
import type
|
|
3
|
+
import { BUILTIN_AGENT_NAMES, type SubagentsConfig } from "../configuration/config.ts";
|
|
4
4
|
import {
|
|
5
5
|
availableModelsInScope, currentModelRef, modelRef, resolveAgentModelRoute, type ModelContext,
|
|
6
6
|
} from "../configuration/models.ts";
|
|
@@ -9,14 +9,18 @@ export const ORCHESTRATION_SECTION = "subagent_orchestration";
|
|
|
9
9
|
|
|
10
10
|
export function buildOrchestrationSection(config: SubagentsConfig, ctx: ModelContext): string {
|
|
11
11
|
const mainRef = currentModelRef(ctx);
|
|
12
|
-
const
|
|
13
|
-
selectedRef: config.model, mainRef, availableRefs: availableModelsInScope(ctx).map(modelRef),
|
|
14
|
-
});
|
|
12
|
+
const availableRefs = availableModelsInScope(ctx).map(modelRef);
|
|
15
13
|
return [
|
|
16
14
|
"Main judges difficulty, plans, handles complex work, and reviews: " + (mainRef ?? "Pi default"),
|
|
17
|
-
|
|
18
|
-
|
|
15
|
+
...BUILTIN_AGENT_NAMES.flatMap((role) => {
|
|
16
|
+
const settings = config[role];
|
|
17
|
+
const route = resolveAgentModelRoute({ selectedRef: settings.model, mainRef, availableRefs });
|
|
18
|
+
return [
|
|
19
|
+
role + ": " + (route.unavailableSelectedRef ? "unavailable (" + route.unavailableSelectedRef + ")" : route.primaryRef ?? "Pi default") + " (thinking preference: " + settings.thinking + "; clamped per model)",
|
|
20
|
+
...(route.unavailableSelectedRef ? [role + " dispatch is blocked. Restore availability or choose a model in /subagents-setup."] : []),
|
|
21
|
+
...(!settings.model ? [role + " currently follows main; choose a cheaper model in /subagents-setup to reduce main-model spending."] : []),
|
|
22
|
+
];
|
|
23
|
+
}),
|
|
19
24
|
"Worker failures return to main with evidence; never auto-upgrade a worker to main. No price or quality ordering is assumed.",
|
|
20
|
-
...(!config.model ? ["Workers currently follow main; choose a cheaper model in /subagents-setup to reduce main-model spending."] : []),
|
|
21
25
|
].join("\n");
|
|
22
26
|
}
|
package/src/delegation/prompt.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Builds the delegation directive installed into the parent prompt.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* The stable contract and the live leases are separate system-prompt
|
|
5
5
|
* sections. Pi appends a section delta only when that text changes, so an idle
|
|
6
|
-
* turn keeps the cached prefix.
|
|
7
|
-
* combined directive as a system-prompt append.
|
|
6
|
+
* turn keeps the cached prefix.
|
|
8
7
|
* Detailed role guidance remains in each child's own prompt.
|
|
9
8
|
*/
|
|
10
9
|
|
|
@@ -124,7 +123,7 @@ function delegationBody(agents: AgentConfig[]): string {
|
|
|
124
123
|
const dispatchRules = [
|
|
125
124
|
"Main leads planning and review; workers execute. The user's task sets the outcome. Honor requests to work in main or avoid subagents. Answer questions and review-only requests without starting implementation.",
|
|
126
125
|
"Main judges difficulty and reads only enough to plan. Delegate simple, bounded work by default: edits, fixes, tests, docs, research. Split complex tasks to expose routine parts; keep hard or uncertain work in main when delegation would add rework. Main always reviews. Keep a change and its tests with one owner. Choose team size from independent work, not available capacity.",
|
|
127
|
-
`Children inherit this session's live tool surface, including \`codemode\` when present${agents.some((agent) => agent.name === "
|
|
126
|
+
`Children inherit this session's live tool surface, including \`codemode\` when present${agents.some((agent) => agent.name === "researcher") ? "; researcher keeps only read-only tools" : ""}. Call delegation tools outside codemode. Do not plan a phase that needs a tool its role cannot reach.`,
|
|
128
127
|
"Use `subagent` for one bounded phase and parallel `tasks` for independent phases. Never overlap writers or duplicate an owned phase. If a result determines the next task or its scope, dispatch that phase alone and decide in main.",
|
|
129
128
|
"Children have no parent conversation; brief outcome, done condition, paths, evidence, boundaries, checks, and output. Name conditions for returning to main. Exchange compact briefs, results, and feedback. Pass completed work forward; assign only gaps.",
|
|
130
129
|
"After integration, main reviews the actual diff, callers, acceptance criteria, and check evidence. Child success is not review approval. Send authorized corrections to the owning worker. Re-check changed or unresolved areas; do not re-review unchanged work.",
|
|
@@ -160,17 +159,6 @@ function buildActiveLeaseSection(sources: Iterable<PhaseLeaseSource>): string {
|
|
|
160
159
|
].join("\n");
|
|
161
160
|
}
|
|
162
161
|
|
|
163
|
-
export function buildDelegationDirective(
|
|
164
|
-
agents: AgentConfig[],
|
|
165
|
-
activeLeaseSources: Iterable<PhaseLeaseSource> = [],
|
|
166
|
-
orchestration = "",
|
|
167
|
-
): string {
|
|
168
|
-
const leases = buildActiveLeaseSection(activeLeaseSources);
|
|
169
|
-
const stable = buildStableDelegationSection(agents, leases.length > 0);
|
|
170
|
-
if (!stable) return "";
|
|
171
|
-
return `\n${[stable, orchestration, leases].filter(Boolean).join("\n\n")}`;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
162
|
/**
|
|
175
163
|
* Install the directive as replaceable prompt sections. Mutating the section
|
|
176
164
|
* map lets Pi diff it; returning a full `systemPrompt` would force the whole
|
package/src/execution/cli-run.ts
CHANGED
|
@@ -142,7 +142,7 @@ export interface ChildLaunchOptions {
|
|
|
142
142
|
resumeExistingSession?: boolean;
|
|
143
143
|
/** Appended system prompt file, when the role carries one. */
|
|
144
144
|
promptPath?: string;
|
|
145
|
-
/** Activate
|
|
145
|
+
/** Activate researcher's approved indirect tools after they register. */
|
|
146
146
|
toolActivationPath?: string;
|
|
147
147
|
}
|
|
148
148
|
|
|
@@ -211,11 +211,11 @@ export async function runCliAgentAttempt(options: RunCliAttemptOptions): Promise
|
|
|
211
211
|
if (signal?.aborted || control?.isStopRequested()) {
|
|
212
212
|
return { ...result, exitCode: 1, stopReason: "aborted", errorMessage: control?.getStopMessage() ?? "Subagent was aborted" };
|
|
213
213
|
}
|
|
214
|
-
const
|
|
215
|
-
if (agent.systemPrompt.trim() ||
|
|
214
|
+
const activateResearcherTools = agent.name === "researcher" && !!agent.tools?.length;
|
|
215
|
+
if (agent.systemPrompt.trim() || activateResearcherTools) promptFile = await writePromptToTempFile(options.scratchRoot, agent.name, agent.systemPrompt);
|
|
216
216
|
let toolActivationPath: string | undefined;
|
|
217
|
-
if (
|
|
218
|
-
toolActivationPath = join(promptFile.dir, "activate-
|
|
217
|
+
if (activateResearcherTools && promptFile) {
|
|
218
|
+
toolActivationPath = join(promptFile.dir, "activate-researcher-tools.mjs");
|
|
219
219
|
await writeFile(toolActivationPath, `
|
|
220
220
|
export default function (pi) {
|
|
221
221
|
const approved = new Set(${JSON.stringify(agent.tools)});
|
|
@@ -348,9 +348,11 @@ export default function (pi) {
|
|
|
348
348
|
pendingSteers.delete(record.id);
|
|
349
349
|
if (record.success) {
|
|
350
350
|
const disposition = record.data?.disposition;
|
|
351
|
-
|
|
351
|
+
if (disposition !== "queued" && disposition !== "handled") {
|
|
352
|
+
pending.reject(new Error("Invalid steering acknowledgement: missing or unsupported disposition."));
|
|
353
|
+
} else pending.resolve({
|
|
352
354
|
requestId: record.id, acknowledgedAt: Date.now(),
|
|
353
|
-
disposition
|
|
355
|
+
disposition,
|
|
354
356
|
});
|
|
355
357
|
}
|
|
356
358
|
else pending.reject(new Error(record.error || "Steering was rejected."));
|
|
@@ -72,13 +72,13 @@ export type RunControlPhase =
|
|
|
72
72
|
export interface SteeringReceipt {
|
|
73
73
|
/** Present when the child acknowledged a matching RPC request. */
|
|
74
74
|
requestId?: string;
|
|
75
|
-
disposition: "queued" | "handled"
|
|
75
|
+
disposition: "queued" | "handled";
|
|
76
76
|
acknowledgedAt: number;
|
|
77
77
|
}
|
|
78
78
|
|
|
79
79
|
export interface AttemptControl {
|
|
80
80
|
stop(reason?: string): Promise<void>;
|
|
81
|
-
steer?(message: string): Promise<SteeringReceipt
|
|
81
|
+
steer?(message: string): Promise<SteeringReceipt>;
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
/** Prevent CLI prompt expansion when a message starts with a slash command. */
|
|
@@ -172,7 +172,7 @@ export class RunControl {
|
|
|
172
172
|
if (this.stopRequested || this.phase !== "running" || !this.attempt?.control.steer) {
|
|
173
173
|
throw new Error("This run is not accepting steering messages.");
|
|
174
174
|
}
|
|
175
|
-
return
|
|
175
|
+
return this.attempt.control.steer(message);
|
|
176
176
|
}
|
|
177
177
|
|
|
178
178
|
async stop(reason = "Subagent was aborted"): Promise<void> {
|
|
@@ -63,7 +63,7 @@ export const runCommand: CommandRunner = (command, args, options) =>
|
|
|
63
63
|
() => terminateProcessTree(child, true, usePosixProcessGroup),
|
|
64
64
|
GIT_COMMAND_KILL_GRACE_MS,
|
|
65
65
|
);
|
|
66
|
-
|
|
66
|
+
forceKillTimer.unref();
|
|
67
67
|
}
|
|
68
68
|
};
|
|
69
69
|
const fail = (error: Error): void => {
|
|
@@ -88,7 +88,7 @@ export const runCommand: CommandRunner = (command, args, options) =>
|
|
|
88
88
|
() => fail(new Error(`Command timed out after ${options.timeoutMs}ms: ${command}`)),
|
|
89
89
|
options.timeoutMs,
|
|
90
90
|
);
|
|
91
|
-
|
|
91
|
+
timeout.unref();
|
|
92
92
|
}
|
|
93
93
|
|
|
94
94
|
child.stdout?.on("data", (chunk: Buffer | string) => append(stdout, chunk));
|
|
@@ -13,12 +13,10 @@ const RECOVERY_MANIFEST_FILE_NAME = "pi-subagents-recovery.json";
|
|
|
13
13
|
const RECOVERY_MANIFEST_VERSION = 1;
|
|
14
14
|
|
|
15
15
|
export interface RecoveryRecord {
|
|
16
|
-
durableId
|
|
16
|
+
durableId: string;
|
|
17
17
|
runId: number;
|
|
18
18
|
createdAt: number;
|
|
19
19
|
integrated: boolean;
|
|
20
|
-
/** Legacy diagnostic metadata; cleanup authorization comes only from managed paths. */
|
|
21
|
-
originalRoot?: string;
|
|
22
20
|
worktreePath?: string;
|
|
23
21
|
patchPath?: string;
|
|
24
22
|
error?: string;
|
|
@@ -36,14 +34,14 @@ export function getRecoveryManifestPath(configPath: string): string {
|
|
|
36
34
|
function normalizeRecord(value: unknown): RecoveryRecord | undefined {
|
|
37
35
|
if (!value || typeof value !== "object") return undefined;
|
|
38
36
|
const raw = value as Record<string, unknown>;
|
|
37
|
+
if (typeof raw.durableId !== "string" || !raw.durableId) throw new Error("Unsupported recovery record: durableId is required. Recovery artifacts were left untouched.");
|
|
39
38
|
if (typeof raw.runId !== "number" || !Number.isInteger(raw.runId) || raw.runId < 1) return undefined;
|
|
40
39
|
if (typeof raw.createdAt !== "number" || !Number.isFinite(raw.createdAt)) return undefined;
|
|
41
40
|
return {
|
|
42
|
-
|
|
41
|
+
durableId: raw.durableId,
|
|
43
42
|
runId: raw.runId,
|
|
44
43
|
createdAt: raw.createdAt,
|
|
45
44
|
integrated: raw.integrated === true,
|
|
46
|
-
...(typeof raw.originalRoot === "string" && raw.originalRoot ? { originalRoot: raw.originalRoot } : {}),
|
|
47
45
|
...(typeof raw.worktreePath === "string" && raw.worktreePath ? { worktreePath: raw.worktreePath } : {}),
|
|
48
46
|
...(typeof raw.patchPath === "string" && raw.patchPath ? { patchPath: raw.patchPath } : {}),
|
|
49
47
|
...(typeof raw.error === "string" && raw.error ? { error: raw.error } : {}),
|
|
@@ -57,8 +55,8 @@ interface RecoveryManifestRead {
|
|
|
57
55
|
|
|
58
56
|
async function readManifest(path: string): Promise<RecoveryManifestRead> {
|
|
59
57
|
try {
|
|
60
|
-
const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown } | null;
|
|
61
|
-
if (!Array.isArray(parsed
|
|
58
|
+
const parsed = JSON.parse(await readFile(path, "utf8")) as { version?: unknown; records?: unknown } | null;
|
|
59
|
+
if (parsed?.version !== RECOVERY_MANIFEST_VERSION || !Array.isArray(parsed.records)) throw new Error(`Invalid recovery manifest: ${path}`);
|
|
62
60
|
return {
|
|
63
61
|
sourceCount: parsed.records.length,
|
|
64
62
|
records: parsed.records.flatMap((record) => {
|
|
@@ -96,21 +94,8 @@ export async function readRecoveryRecords(configPath: string): Promise<RecoveryR
|
|
|
96
94
|
});
|
|
97
95
|
}
|
|
98
96
|
|
|
99
|
-
/** Move valid records from the previous agent-root manifest into the internal-state
|
|
100
|
-
* root. Invalid legacy records are removed without touching their referenced paths. */
|
|
101
|
-
export async function relocateRecoveryManifest(configPath: string): Promise<void> {
|
|
102
|
-
const legacyPath = join(dirname(configPath), RECOVERY_MANIFEST_FILE_NAME);
|
|
103
|
-
const currentPath = getRecoveryManifestPath(configPath);
|
|
104
|
-
if (legacyPath === currentPath || !existsSync(legacyPath)) return;
|
|
105
|
-
await withManifestMutation(legacyPath, async () => {
|
|
106
|
-
const legacy = await readManifest(legacyPath);
|
|
107
|
-
await persistRecoveryRecords(configPath, legacy.records);
|
|
108
|
-
await rm(legacyPath, { force: true });
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
|
|
112
97
|
function recoveryKey(record: RecoveryRecord): string {
|
|
113
|
-
return `${record.durableId
|
|
98
|
+
return `${record.durableId}\0${record.worktreePath ?? ""}\0${record.patchPath ?? ""}\0${record.error ?? ""}`;
|
|
114
99
|
}
|
|
115
100
|
|
|
116
101
|
async function writeManifest(path: string, records: readonly RecoveryRecord[]): Promise<void> {
|
|
@@ -155,15 +140,14 @@ export async function persistRecoveryRecords(
|
|
|
155
140
|
export function recoveryRecordFromFinalization(
|
|
156
141
|
runId: number,
|
|
157
142
|
finalization: WorktreeFinalization,
|
|
143
|
+
durableId: string,
|
|
158
144
|
now = Date.now(),
|
|
159
|
-
durableId?: string,
|
|
160
145
|
): RecoveryRecord {
|
|
161
146
|
return {
|
|
162
|
-
|
|
147
|
+
durableId,
|
|
163
148
|
runId,
|
|
164
149
|
createdAt: now,
|
|
165
150
|
integrated: finalization.integrated,
|
|
166
|
-
...(finalization.originalRoot ? { originalRoot: finalization.originalRoot } : {}),
|
|
167
151
|
...(finalization.worktreePath ? { worktreePath: finalization.worktreePath } : {}),
|
|
168
152
|
...(finalization.patchPath ? { patchPath: finalization.patchPath } : {}),
|
|
169
153
|
...(finalization.error ? { error: finalization.error } : {}),
|
|
@@ -27,7 +27,7 @@ import { join } from "node:path";
|
|
|
27
27
|
export const TEMP_OWNER_FILE_NAME = "owner.json";
|
|
28
28
|
|
|
29
29
|
/** Transient directories created under `<project>/tmp`: the child prompt
|
|
30
|
-
* copies (`pi-subagents-*`)
|
|
30
|
+
* copies (`pi-subagents-*`). The singular `pi-subagent-` prefixes below belong
|
|
31
31
|
* to the durable roots and are swept separately, under a reference guard. */
|
|
32
32
|
const TEMP_DIR_PREFIXES = ["pi-subagents-"] as const;
|
|
33
33
|
|