pi-better-subagents 0.27.2 → 0.28.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 +20 -8
- package/agent-commands.ts +29 -10
- package/agent-inspection.ts +116 -5
- package/agents-catalog-tool.ts +5 -3
- package/batch.mjs +6 -0
- package/catalog-resolver.ts +28 -0
- package/catalog-runtime.ts +8 -0
- package/catalog-schema.ts +110 -8
- package/catalog-skill-edits.ts +116 -0
- package/catalog-ui.ts +172 -27
- package/child-ownership.ts +7 -1
- package/config.ts +35 -3
- package/continuation.ts +3 -0
- package/docs/agent-catalog-operations.md +47 -4
- package/docs/agent-catalog.md +12 -1
- package/docs/usage.md +81 -8
- package/index.ts +212 -8
- package/package.json +1 -1
- package/registry.ts +11 -0
- package/settings-page.ts +220 -47
- package/shared-worktree-context.ts +158 -0
- package/skill-picker.ts +349 -0
- package/skills.ts +183 -0
package/settings-page.ts
CHANGED
|
@@ -2,6 +2,8 @@ import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
|
2
2
|
import * as Tui from "@earendil-works/pi-tui";
|
|
3
3
|
import { isConcurrencyCap } from "./config.ts";
|
|
4
4
|
import { DELEGATION_MODES, type DelegationMode } from "./delegation.ts";
|
|
5
|
+
import type { SkillExposureMode } from "./skills.ts";
|
|
6
|
+
import { createSkillPicker, type DiscoveredSkill } from "./skill-picker.ts";
|
|
5
7
|
|
|
6
8
|
export interface SubagentSettingsSnapshot {
|
|
7
9
|
mode: DelegationMode;
|
|
@@ -10,19 +12,59 @@ export interface SubagentSettingsSnapshot {
|
|
|
10
12
|
capSource: "session" | "config";
|
|
11
13
|
defaultMode: DelegationMode;
|
|
12
14
|
defaultCap: number;
|
|
15
|
+
/** Session draft, or the saved global default when this session has no override. */
|
|
16
|
+
skillsMode: SkillExposureMode;
|
|
17
|
+
skillsPaths: readonly string[];
|
|
18
|
+
skillsSource: "session" | "config" | "default";
|
|
19
|
+
/** A saved `defaultSkills` value the launcher cannot read, kept visible rather than hidden. */
|
|
20
|
+
skillsError?: string;
|
|
13
21
|
}
|
|
14
22
|
|
|
15
23
|
export interface SubagentSettingsHandlers {
|
|
16
24
|
get(): SubagentSettingsSnapshot;
|
|
17
25
|
changeMode(mode: DelegationMode): void;
|
|
18
26
|
changeCap(cap: number): void;
|
|
27
|
+
changeSkills(mode: SkillExposureMode, paths: readonly string[]): void;
|
|
28
|
+
/** Loaded Pi skill metadata for the checkbox picker. Absent means manual paths only. */
|
|
29
|
+
discoverSkills?(): readonly DiscoveredSkill[];
|
|
19
30
|
save(): { ok: boolean; message: string };
|
|
20
31
|
reset(): void;
|
|
21
32
|
/** Opens the same catalog as `/agents`. The caller closes this page first. */
|
|
22
33
|
openAgents?(): void;
|
|
23
34
|
}
|
|
24
35
|
|
|
25
|
-
|
|
36
|
+
type EditTarget = { kind: "cap" };
|
|
37
|
+
|
|
38
|
+
type Row =
|
|
39
|
+
| { kind: "mode" }
|
|
40
|
+
| { kind: "cap" }
|
|
41
|
+
| { kind: "skills" }
|
|
42
|
+
| { kind: "choose" }
|
|
43
|
+
| { kind: "agents" }
|
|
44
|
+
| { kind: "reset" };
|
|
45
|
+
|
|
46
|
+
const SKILL_MODES: readonly { mode: SkillExposureMode; label: string }[] = [
|
|
47
|
+
{ mode: "inherit", label: "Discover automatically" },
|
|
48
|
+
{ mode: "none", label: "No skill catalog" },
|
|
49
|
+
{ mode: "explicit", label: "Selected skills" },
|
|
50
|
+
];
|
|
51
|
+
|
|
52
|
+
const LABEL_WIDTH = 26;
|
|
53
|
+
|
|
54
|
+
function skillLabel(mode: SkillExposureMode): string {
|
|
55
|
+
return SKILL_MODES.find((entry) => entry.mode === mode)!.label;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function cycleSkillMode(mode: SkillExposureMode): SkillExposureMode {
|
|
59
|
+
return mode === "inherit" ? "none" : "inherit";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function skillSource(settings: SubagentSettingsSnapshot): string {
|
|
63
|
+
if (settings.skillsError) return `Config error: ${settings.skillsError}`;
|
|
64
|
+
if (settings.skillsSource === "session") return "Source: this session (unsaved)";
|
|
65
|
+
if (settings.skillsSource === "config") return "Source: config defaultSkills";
|
|
66
|
+
return "Source: discovery default";
|
|
67
|
+
}
|
|
26
68
|
|
|
27
69
|
function cell(text: string, width: number): string {
|
|
28
70
|
const clipped = Tui.truncateToWidth(text, width, "");
|
|
@@ -34,111 +76,242 @@ export function createSubagentSettingsPage(
|
|
|
34
76
|
handlers: SubagentSettingsHandlers,
|
|
35
77
|
requestRender: () => void,
|
|
36
78
|
close: () => void,
|
|
79
|
+
getHeight: () => number = () => process.stdout.rows ?? 30,
|
|
37
80
|
): Tui.Component & Tui.Focusable {
|
|
38
81
|
const input = new Tui.Input();
|
|
39
82
|
let focused = false;
|
|
40
83
|
let row = 0;
|
|
41
|
-
let editing
|
|
84
|
+
let editing: EditTarget | undefined;
|
|
85
|
+
let picker: ReturnType<typeof createSkillPicker> | undefined;
|
|
86
|
+
let rememberedSkillPaths: string[] | undefined;
|
|
87
|
+
let viewportStart = 0;
|
|
42
88
|
let message = "";
|
|
43
89
|
let error = false;
|
|
90
|
+
|
|
44
91
|
function report(text: string, failed = false): void {
|
|
45
92
|
message = text;
|
|
46
93
|
error = failed;
|
|
47
94
|
requestRender();
|
|
48
95
|
}
|
|
49
|
-
|
|
96
|
+
|
|
97
|
+
function rowsOf(settings: SubagentSettingsSnapshot): Row[] {
|
|
98
|
+
const rows: Row[] = [{ kind: "mode" }, { kind: "cap" }, { kind: "skills" }, { kind: "choose" }];
|
|
99
|
+
rows.push({ kind: "agents" }, { kind: "reset" });
|
|
100
|
+
return rows;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function startEditing(target: EditTarget, value: string): void {
|
|
104
|
+
editing = target;
|
|
105
|
+
input.setValue(value);
|
|
106
|
+
input.handleInput("\x05");
|
|
107
|
+
input.focused = focused;
|
|
108
|
+
report("");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function finishEditing(text: string): void {
|
|
112
|
+
input.focused = false;
|
|
113
|
+
editing = undefined;
|
|
114
|
+
report(text);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function openSkillPicker(initial: readonly string[], previousMode: SkillExposureMode): void {
|
|
118
|
+
picker = createSkillPicker({
|
|
119
|
+
theme,
|
|
120
|
+
skills: handlers.discoverSkills?.() ?? [],
|
|
121
|
+
selected: initial,
|
|
122
|
+
requestRender,
|
|
123
|
+
getHeight,
|
|
124
|
+
title: "Selected skills",
|
|
125
|
+
apply(paths) {
|
|
126
|
+
try {
|
|
127
|
+
if (paths.length === 0) {
|
|
128
|
+
handlers.changeSkills("none", []);
|
|
129
|
+
rememberedSkillPaths = [];
|
|
130
|
+
report("No skills checked. Skill exposure set to No skill catalog.");
|
|
131
|
+
return { ok: true, message: "No skill catalog selected." };
|
|
132
|
+
}
|
|
133
|
+
handlers.changeSkills("explicit", paths);
|
|
134
|
+
rememberedSkillPaths = [...paths];
|
|
135
|
+
report(`${paths.length} skill${paths.length === 1 ? "" : "s"} selected.`);
|
|
136
|
+
return { ok: true, message: `${paths.length} selected.` };
|
|
137
|
+
} catch (cause) {
|
|
138
|
+
return { ok: false, message: cause instanceof Error ? cause.message : String(cause) };
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
finish() { picker = undefined; requestRender(); },
|
|
142
|
+
cancel() {
|
|
143
|
+
picker = undefined;
|
|
144
|
+
report(previousMode === "explicit" ? "Skill selection unchanged." : "Skill mode unchanged.");
|
|
145
|
+
requestRender();
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
picker.focused = focused;
|
|
149
|
+
requestRender();
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function action(settings: SubagentSettingsSnapshot, selected: Row): void {
|
|
50
153
|
try {
|
|
51
|
-
|
|
52
|
-
if (row === 0) {
|
|
154
|
+
if (selected.kind === "mode") {
|
|
53
155
|
const next = DELEGATION_MODES[(DELEGATION_MODES.indexOf(settings.mode) + 1) % DELEGATION_MODES.length]!;
|
|
54
156
|
handlers.changeMode(next);
|
|
55
157
|
report("Session mode updated.");
|
|
56
|
-
} else if (
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
158
|
+
} else if (selected.kind === "cap") {
|
|
159
|
+
startEditing({ kind: "cap" }, String(settings.maxConcurrent));
|
|
160
|
+
} else if (selected.kind === "skills") {
|
|
161
|
+
if (settings.skillsMode === "explicit") rememberedSkillPaths = [...settings.skillsPaths];
|
|
162
|
+
const next = cycleSkillMode(settings.skillsMode);
|
|
163
|
+
handlers.changeSkills(next, []);
|
|
164
|
+
report(`Skill exposure: ${skillLabel(next).toLowerCase()}.`);
|
|
165
|
+
} else if (selected.kind === "choose") {
|
|
166
|
+
openSkillPicker(
|
|
167
|
+
settings.skillsMode === "explicit" ? settings.skillsPaths : rememberedSkillPaths ?? [],
|
|
168
|
+
settings.skillsMode,
|
|
169
|
+
);
|
|
170
|
+
return;
|
|
171
|
+
} else if (selected.kind === "agents") {
|
|
63
172
|
handlers.openAgents?.();
|
|
64
173
|
} else {
|
|
65
174
|
handlers.reset();
|
|
175
|
+
rememberedSkillPaths = undefined;
|
|
66
176
|
report("Session settings reset to saved defaults.");
|
|
67
177
|
}
|
|
68
178
|
} catch (cause) {
|
|
69
179
|
report(cause instanceof Error ? cause.message : String(cause), true);
|
|
70
180
|
}
|
|
71
181
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
182
|
+
|
|
183
|
+
const submit = (value: string) => {
|
|
184
|
+
const target = editing;
|
|
185
|
+
if (!target) return;
|
|
186
|
+
const settings = handlers.get();
|
|
187
|
+
if (target.kind === "cap") {
|
|
188
|
+
const cap = /^\d+$/.test(value.trim()) ? Number(value.trim()) : NaN;
|
|
189
|
+
if (!isConcurrencyCap(cap)) {
|
|
190
|
+
report("Enter a positive whole number.", true);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
handlers.changeCap(cap);
|
|
195
|
+
finishEditing("Session cap updated.");
|
|
196
|
+
} catch (cause) {
|
|
197
|
+
report(cause instanceof Error ? cause.message : String(cause), true);
|
|
198
|
+
}
|
|
76
199
|
return;
|
|
77
200
|
}
|
|
78
|
-
try {
|
|
79
|
-
handlers.changeCap(cap);
|
|
80
|
-
editing = false;
|
|
81
|
-
input.focused = false;
|
|
82
|
-
report("Session cap updated.");
|
|
83
|
-
} catch (cause) {
|
|
84
|
-
report(cause instanceof Error ? cause.message : String(cause), true);
|
|
85
|
-
}
|
|
86
201
|
};
|
|
202
|
+
|
|
203
|
+
input.onSubmit = submit;
|
|
87
204
|
input.onEscape = () => {
|
|
88
|
-
editing = false;
|
|
89
205
|
input.focused = false;
|
|
90
|
-
|
|
206
|
+
editing = undefined;
|
|
207
|
+
report("Edit cancelled.");
|
|
91
208
|
};
|
|
209
|
+
|
|
92
210
|
return {
|
|
93
211
|
get focused() { return focused; },
|
|
94
|
-
set focused(value: boolean) {
|
|
95
|
-
|
|
212
|
+
set focused(value: boolean) {
|
|
213
|
+
focused = value;
|
|
214
|
+
input.focused = editing !== undefined && value;
|
|
215
|
+
if (picker) picker.focused = value;
|
|
216
|
+
},
|
|
217
|
+
invalidate() { input.invalidate(); picker?.invalidate(); },
|
|
96
218
|
handleInput(data: string) {
|
|
219
|
+
if (picker) {
|
|
220
|
+
picker.handleInput(data);
|
|
221
|
+
requestRender();
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const settings = handlers.get();
|
|
97
225
|
if (editing) {
|
|
98
226
|
input.handleInput(data);
|
|
99
227
|
requestRender();
|
|
100
228
|
return;
|
|
101
229
|
}
|
|
230
|
+
const rows = rowsOf(settings);
|
|
231
|
+
row = Math.min(row, rows.length - 1);
|
|
232
|
+
const selected = rows[row]!;
|
|
102
233
|
if (Tui.matchesKey(data, Tui.Key.escape)) close();
|
|
103
234
|
else if (Tui.matchesKey(data, Tui.Key.up)) row = Math.max(0, row - 1);
|
|
104
|
-
else if (Tui.matchesKey(data, Tui.Key.down)) row = Math.min(
|
|
105
|
-
else if (Tui.matchesKey(data, Tui.Key.enter) || data === " ") action();
|
|
235
|
+
else if (Tui.matchesKey(data, Tui.Key.down)) row = Math.min(rows.length - 1, row + 1);
|
|
236
|
+
else if (Tui.matchesKey(data, Tui.Key.enter) || data === " ") action(settings, selected);
|
|
106
237
|
else if (Tui.matchesKey(data, "ctrl+s")) {
|
|
107
238
|
const result = handlers.save();
|
|
239
|
+
if (result.ok) {
|
|
240
|
+
rememberedSkillPaths = settings.skillsMode === "explicit" ? [...settings.skillsPaths] : undefined;
|
|
241
|
+
}
|
|
108
242
|
report(result.message, !result.ok);
|
|
109
243
|
}
|
|
110
244
|
requestRender();
|
|
111
245
|
},
|
|
112
246
|
render(width: number) {
|
|
247
|
+
if (picker) return picker.render(width);
|
|
113
248
|
const settings = handlers.get();
|
|
249
|
+
const rows = rowsOf(settings);
|
|
250
|
+
row = Math.min(row, rows.length - 1);
|
|
114
251
|
const w = Math.max(1, Math.floor(width));
|
|
115
252
|
const compact = w < 40;
|
|
116
|
-
const
|
|
117
|
-
const valueWidth = Math.max(1, w - labelWidth - 1);
|
|
118
|
-
const current = [settings.mode, String(settings.maxConcurrent)];
|
|
253
|
+
const valueWidth = Math.max(1, w - LABEL_WIDTH - 1);
|
|
119
254
|
const highlight = (text: string, selected: boolean): string => selected
|
|
120
255
|
? theme.bg("selectedBg", theme.bold(cell(text, w))) : text;
|
|
121
256
|
const marker = (selected: boolean) => selected ? "> " : " ";
|
|
257
|
+
const source = skillSource(settings);
|
|
122
258
|
const lines: string[] = [theme.fg("accent", theme.bold(" Subagent settings")), ""];
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
if (index === labels.length - 1) lines.push("");
|
|
259
|
+
|
|
260
|
+
const pushSetting = (label: string, value: string, selected: boolean, active: string): void => {
|
|
126
261
|
const title = theme.fg(selected ? "accent" : "text", marker(selected) + label);
|
|
127
|
-
if (
|
|
262
|
+
if (compact) {
|
|
128
263
|
lines.push(highlight(title, selected));
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
264
|
+
lines.push(" " + (selected ? theme.inverse(active) : theme.fg("text", active)));
|
|
265
|
+
} else {
|
|
266
|
+
lines.push(highlight(cell(title, LABEL_WIDTH) + " " +
|
|
267
|
+
(selected ? theme.inverse(active) : theme.fg("text", active)), selected));
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
let selectedStart = 2;
|
|
272
|
+
let selectedEnd = 3;
|
|
273
|
+
rows.forEach((entry, index) => {
|
|
274
|
+
const selected = index === row;
|
|
275
|
+
if (selected) selectedStart = lines.length;
|
|
276
|
+
if (entry.kind === "mode" || entry.kind === "cap") {
|
|
277
|
+
const label = entry.kind === "mode" ? "Delegation mode" : "Concurrent subagents";
|
|
278
|
+
const value = entry.kind === "mode" ? settings.mode : String(settings.maxConcurrent);
|
|
279
|
+
const active = editing?.kind === "cap" && entry.kind === "cap"
|
|
280
|
+
? input.render(compact ? Math.max(1, w - 2) : valueWidth)[0]!
|
|
281
|
+
: value;
|
|
282
|
+
pushSetting(label, value, selected, active);
|
|
283
|
+
} else if (entry.kind === "skills") {
|
|
284
|
+
pushSetting("Skill exposure", skillLabel(settings.skillsMode), selected, skillLabel(settings.skillsMode));
|
|
285
|
+
const sourceLine = compact ? " " + source : " ".repeat(LABEL_WIDTH) + " " + source;
|
|
286
|
+
lines.push(theme.fg(settings.skillsError ? "error" : "muted",
|
|
287
|
+
Tui.truncateToWidth(sourceLine, w, "")));
|
|
288
|
+
} else if (entry.kind === "choose") {
|
|
289
|
+
const value = settings.skillsMode === "explicit" ? `${settings.skillsPaths.length} checked` : "Choose…";
|
|
290
|
+
pushSetting("Selected skills", value, selected, value);
|
|
291
|
+
} else if (entry.kind === "agents") {
|
|
292
|
+
lines.push(highlight(theme.fg(selected ? "accent" : "text", marker(selected) + "Agents"), selected));
|
|
133
293
|
} else {
|
|
134
|
-
|
|
135
|
-
lines.push(highlight(
|
|
136
|
-
(selected && !editing ? theme.inverse(active) : theme.fg("text", active)), selected));
|
|
294
|
+
lines.push("");
|
|
295
|
+
lines.push(highlight(theme.fg(selected ? "accent" : "text", marker(selected) + "Reset to defaults"), selected));
|
|
137
296
|
}
|
|
297
|
+
if (selected) selectedEnd = lines.length;
|
|
138
298
|
});
|
|
139
|
-
|
|
140
|
-
lines.
|
|
141
|
-
|
|
299
|
+
|
|
300
|
+
const body = lines.slice(2);
|
|
301
|
+
const footer: string[] = [];
|
|
302
|
+
if (message) footer.push("", theme.fg(error ? "error" : "muted", message));
|
|
303
|
+
footer.push("", theme.fg("dim", editing
|
|
304
|
+
? "Enter Apply · Esc Cancel"
|
|
305
|
+
: "Up/Down Select · Space/Enter Change · ctrl+s Save default · Esc Back"));
|
|
306
|
+
const height = Math.max(1, Math.floor(getHeight()));
|
|
307
|
+
const room = Math.max(1, height - 2 - footer.length);
|
|
308
|
+
if (selectedEnd - 2 > viewportStart + room) viewportStart = selectedEnd - 2 - room;
|
|
309
|
+
if (selectedStart - 2 < viewportStart) viewportStart = selectedStart - 2;
|
|
310
|
+
viewportStart = Math.max(0, Math.min(viewportStart, body.length - room));
|
|
311
|
+
const visible = [...lines.slice(0, 2), ...body.slice(viewportStart, viewportStart + room), ...footer];
|
|
312
|
+
// A very short terminal prioritizes the active control over chrome.
|
|
313
|
+
const result = height < 2 + footer.length + 1 ? body.slice(selectedStart - 2, selectedStart - 2 + height) : visible;
|
|
314
|
+
return result.map((line) => Tui.truncateToWidth(line, w, ""));
|
|
142
315
|
},
|
|
143
316
|
};
|
|
144
317
|
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// Generated from packages/pi-better-harness/extensions/worktree-context.ts. Do not edit directly.
|
|
2
|
+
/**
|
|
3
|
+
* Project context follows the linked worktree that owns the working directory.
|
|
4
|
+
*
|
|
5
|
+
* Pi loads one global context file from the agent directory and one file from
|
|
6
|
+
* every ancestor of the working directory. In a linked worktree (`git worktree
|
|
7
|
+
* add`) those ancestors include the main checkout, so the worktree inherits its
|
|
8
|
+
* instructions in addition to its own. The worktree is the project context root:
|
|
9
|
+
* keep the global file and files at or below the worktree root, drop everything
|
|
10
|
+
* loaded above it. A worktree without its own context file therefore starts
|
|
11
|
+
* without the main checkout's file instead of falling back to it.
|
|
12
|
+
*
|
|
13
|
+
* This module only filters. It never adds a context file or a prompt section, so
|
|
14
|
+
* `--no-context-files` keeps its empty list, and it returns nothing to Pi, so
|
|
15
|
+
* guidance keeps arriving as sections (ADR 0016, ADR 0021). A host that
|
|
16
|
+
* rebuilds the prompt from `systemPromptOptions` after the `before_agent_start`
|
|
17
|
+
* handlers applies the filtered list; on a host that does not rebuild, the
|
|
18
|
+
* mutation is inert rather than a whole-prompt return.
|
|
19
|
+
*
|
|
20
|
+
* Subagent children use a vendored copy of this file
|
|
21
|
+
* (`packages/pi-better-subagents/shared-worktree-context.ts`) because a
|
|
22
|
+
* standalone Subagents install has no Harness package.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
26
|
+
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
27
|
+
|
|
28
|
+
/** The subset of a loaded context file this module needs to read. */
|
|
29
|
+
export interface ProjectContextFile {
|
|
30
|
+
path: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The subset of Pi's structured prompt options this module edits. */
|
|
34
|
+
export interface ProjectContextOptions {
|
|
35
|
+
/** Working directory the prompt was built for. Falls back to `process.cwd()`. */
|
|
36
|
+
cwd?: string;
|
|
37
|
+
contextFiles?: ProjectContextFile[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface GitPaths {
|
|
41
|
+
/** Directory holding the `.git` file or directory found for the working tree. */
|
|
42
|
+
repoDir: string;
|
|
43
|
+
/** Git directory for this working tree (`.git/worktrees/<name>` when linked). */
|
|
44
|
+
gitDir: string;
|
|
45
|
+
/** Git directory holding the shared object database and administrative state. */
|
|
46
|
+
commonGitDir: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function canonicalizePath(path: string): string {
|
|
50
|
+
try {
|
|
51
|
+
return realpathSync(path);
|
|
52
|
+
} catch {
|
|
53
|
+
return path;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Compare paths the way the host does: resolved, and case-folded on Windows. */
|
|
58
|
+
function comparisonKey(path: string): string {
|
|
59
|
+
const resolved = resolve(path);
|
|
60
|
+
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** True when `child` is `parent` or inside it. */
|
|
64
|
+
function isPathWithin(parent: string, child: string): boolean {
|
|
65
|
+
const parentKey = comparisonKey(parent);
|
|
66
|
+
const childKey = comparisonKey(child);
|
|
67
|
+
if (childKey === parentKey) return true;
|
|
68
|
+
return childKey.startsWith(parentKey.endsWith(sep) ? parentKey : `${parentKey}${sep}`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Find the nearest working tree above `startDir` without running Git. */
|
|
72
|
+
function findGitPaths(startDir: string): GitPaths | undefined {
|
|
73
|
+
let dir = resolve(startDir);
|
|
74
|
+
while (true) {
|
|
75
|
+
const gitPath = join(dir, ".git");
|
|
76
|
+
if (existsSync(gitPath)) {
|
|
77
|
+
try {
|
|
78
|
+
const stat = statSync(gitPath);
|
|
79
|
+
if (stat.isFile()) {
|
|
80
|
+
const content = readFileSync(gitPath, "utf8").trim();
|
|
81
|
+
if (!content.startsWith("gitdir: ")) return undefined;
|
|
82
|
+
const gitDir = resolve(dir, content.slice(8).trim());
|
|
83
|
+
if (!existsSync(join(gitDir, "HEAD"))) return undefined;
|
|
84
|
+
// A linked worktree has `commondir`; a submodule's gitdir has none,
|
|
85
|
+
// and keeps ordinary ancestor inheritance.
|
|
86
|
+
const commonDirPath = join(gitDir, "commondir");
|
|
87
|
+
const commonGitDir = existsSync(commonDirPath)
|
|
88
|
+
? resolve(gitDir, readFileSync(commonDirPath, "utf8").trim())
|
|
89
|
+
: gitDir;
|
|
90
|
+
return { repoDir: dir, gitDir, commonGitDir };
|
|
91
|
+
}
|
|
92
|
+
if (stat.isDirectory()) {
|
|
93
|
+
if (!existsSync(join(gitPath, "HEAD"))) return undefined;
|
|
94
|
+
return { repoDir: dir, gitDir: gitPath, commonGitDir: gitPath };
|
|
95
|
+
}
|
|
96
|
+
} catch {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const parent = dirname(dir);
|
|
101
|
+
if (parent === dir) return undefined;
|
|
102
|
+
dir = parent;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The linked worktree root that owns `cwd`, or undefined for an ordinary
|
|
108
|
+
* checkout. Returned canonicalized, because a worktree's `.git` file records the
|
|
109
|
+
* real path while `cwd` may still be a symlink (macOS `/tmp` → `/private/tmp`).
|
|
110
|
+
*/
|
|
111
|
+
export function findLinkedWorktreeRoot(cwd: string): string | undefined {
|
|
112
|
+
const gitPaths = findGitPaths(canonicalizePath(cwd));
|
|
113
|
+
// Only a shared object store makes this a worktree; the main checkout, a
|
|
114
|
+
// separate `.git` directory and a submodule keep ordinary inheritance.
|
|
115
|
+
if (!gitPaths || gitPaths.gitDir === gitPaths.commonGitDir) return undefined;
|
|
116
|
+
return canonicalizePath(gitPaths.repoDir);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Where Pi selected a context file, canonicalized through its directory only.
|
|
121
|
+
*
|
|
122
|
+
* Resolving the whole path would follow a filename symlink to its target, which
|
|
123
|
+
* inverts both cases that matter: a worktree `AGENTS.md` linking to the main
|
|
124
|
+
* checkout's file would look like inherited context, and the main checkout's
|
|
125
|
+
* `AGENTS.md` linking back into the worktree would look local. The boundary is
|
|
126
|
+
* the location the loader selected, so resolve the containing directory (macOS
|
|
127
|
+
* `/tmp` → `/private/tmp`, a symlinked cwd, a symlinked agent directory) and
|
|
128
|
+
* keep the selected filename itself.
|
|
129
|
+
*/
|
|
130
|
+
function selectedContextPath(filePath: string): string {
|
|
131
|
+
return join(canonicalizePath(dirname(filePath)), basename(filePath));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Drop project context loaded above the linked worktree that owns `cwd`.
|
|
136
|
+
*
|
|
137
|
+
* The global file Pi selected under `agentDir` always survives, even when that
|
|
138
|
+
* filename is a symlink to a file outside the agent directory, because the
|
|
139
|
+
* global selection is not inherited checkout context. Outside a linked worktree
|
|
140
|
+
* this is a no-op, so ordinary repositories keep every ancestor file. A host
|
|
141
|
+
* that hands over no prompt options is left unchanged. Mutates
|
|
142
|
+
* `options.contextFiles` in place because Pi hands the handler its mutable
|
|
143
|
+
* prompt options.
|
|
144
|
+
*/
|
|
145
|
+
export function restrictContextFilesToWorktree(options: ProjectContextOptions | undefined, agentDir: string): void {
|
|
146
|
+
if (!options) return;
|
|
147
|
+
const files = options.contextFiles;
|
|
148
|
+
if (!files || files.length === 0) return;
|
|
149
|
+
const worktreeRoot = findLinkedWorktreeRoot(options.cwd ?? process.cwd());
|
|
150
|
+
if (!worktreeRoot) return;
|
|
151
|
+
const allowedRoots = [worktreeRoot, canonicalizePath(agentDir)];
|
|
152
|
+
const kept = files.filter((file) => {
|
|
153
|
+
const path = selectedContextPath(file.path);
|
|
154
|
+
return allowedRoots.some((root) => isPathWithin(root, path));
|
|
155
|
+
});
|
|
156
|
+
if (kept.length === files.length) return;
|
|
157
|
+
options.contextFiles = kept;
|
|
158
|
+
}
|