pi-subagent-manager 0.2.0 → 0.3.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 +97 -18
- package/agents/architect.md +37 -2
- package/agents/coder.md +41 -0
- package/agents/reviewer.md +32 -0
- package/agents/tasker.md +38 -0
- package/agents/writer.md +34 -0
- package/docs/default-agents.md +105 -0
- package/docs/research-claude.md +258 -0
- package/docs/research-codex.md +143 -0
- package/docs/research-model-roles-coding.md +99 -0
- package/docs/research-model-roles-writing.md +78 -0
- package/package.json +8 -3
- package/src/agent-import.ts +245 -0
- package/src/config.ts +23 -9
- package/src/dialog.ts +631 -0
- package/src/import-discovery.ts +643 -0
- package/src/import-instructions.ts +156 -0
- package/src/import-picker.ts +231 -0
- package/src/index.ts +102 -24
- package/src/manager.ts +67 -2
- package/src/model-picker.ts +194 -92
- package/src/models.ts +8 -2
- package/src/runtime.ts +70 -15
- package/src/settings-ui.ts +173 -0
- package/src/settings.ts +153 -8
- package/src/status-ui.ts +288 -0
- package/src/thread-tree.ts +134 -0
- package/src/tools.ts +21 -10
- package/src/types.ts +24 -1
- package/src/ui.ts +760 -102
- package/agents/researcher.md +0 -14
- package/agents/worker.md +0 -6
package/src/runtime.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
2
3
|
import { existsSync } from "node:fs";
|
|
3
4
|
import { mkdir, readFile, realpath } from "node:fs/promises";
|
|
4
5
|
import {
|
|
@@ -130,7 +131,10 @@ async function assertAcceptedSessionFile(
|
|
|
130
131
|
}
|
|
131
132
|
|
|
132
133
|
/** Isolated SDK sessions; neither external extensions nor the CLI's MCP factories are loaded. */
|
|
133
|
-
export function createDriverFactory(
|
|
134
|
+
export function createDriverFactory(
|
|
135
|
+
getRootContext: () => ExtensionContext,
|
|
136
|
+
getScopedModelFiltering: () => boolean = () => true,
|
|
137
|
+
): DriverFactory {
|
|
134
138
|
// Keep resolved settings even after disposal: descendants inherit settings, not the caller's history.
|
|
135
139
|
const resolved = new Map<string, { provider: string; id: string; thinking: ThinkingLevel }>();
|
|
136
140
|
return async (options) => {
|
|
@@ -205,20 +209,33 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
205
209
|
const normalizeScopedModels = (
|
|
206
210
|
scopedModels: ExtensionContext["scopedModels"] | null | undefined,
|
|
207
211
|
): readonly ScopedModel[] => scopedModels ?? [];
|
|
208
|
-
const
|
|
212
|
+
const filteringEnabled = getScopedModelFiltering;
|
|
213
|
+
const selectModelPreference = (
|
|
214
|
+
candidates: readonly { model: { provider: string; id: string } }[],
|
|
215
|
+
filtering = filteringEnabled(),
|
|
216
|
+
) => {
|
|
209
217
|
try {
|
|
210
|
-
return selectPreferredModel(options.type,
|
|
218
|
+
return selectPreferredModel(options.type, candidates, filtering);
|
|
211
219
|
} catch (error) {
|
|
212
|
-
if (
|
|
220
|
+
if (
|
|
221
|
+
filtering &&
|
|
222
|
+
candidates.length === 0 &&
|
|
223
|
+
error instanceof Error &&
|
|
224
|
+
!error.message.includes("[]")
|
|
225
|
+
)
|
|
213
226
|
throw new Error(`${error.message} Current /scoped-models scope: [].`);
|
|
214
227
|
throw error;
|
|
215
228
|
}
|
|
216
229
|
};
|
|
230
|
+
const availableModelCandidates = () =>
|
|
231
|
+
ctx.modelRegistry.getAvailable().map((model) => ({ model }));
|
|
217
232
|
const initialScopedModels = normalizeScopedModels(ctx.scopedModels);
|
|
218
233
|
let provider = parent?.provider ?? ctx.model?.provider;
|
|
219
234
|
let id = parent?.id ?? ctx.model?.id;
|
|
220
235
|
if (modelPreferences !== undefined) {
|
|
221
|
-
|
|
236
|
+
const filtering = filteringEnabled();
|
|
237
|
+
const candidates = filtering ? initialScopedModels : availableModelCandidates();
|
|
238
|
+
({ provider, id } = parseModelIdentity(selectModelPreference(candidates, filtering)!));
|
|
222
239
|
} else if (restored?.model) {
|
|
223
240
|
provider = restored.model.provider;
|
|
224
241
|
id = restored.model.modelId;
|
|
@@ -309,6 +326,7 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
309
326
|
"When finished, give your final answer normally so it can be handed back. To retain unfinished work without a final answer, call agent_pause (if available), then stop; resume only when instructed.",
|
|
310
327
|
...(allowed.has("agent_spawn") && allowed.has("agent_wait")
|
|
311
328
|
? [
|
|
329
|
+
"Name child paths with concise task-based kebab-case slugs (e.g. /root/controller-security-research), independent of type.",
|
|
312
330
|
"For independent parallel work, launch all siblings with agent_spawn wait:false before calling agent_wait. Children share the main conversation's depth and concurrency limits; waiting parents count as active. Do not delegate work beyond your assigned scope.",
|
|
313
331
|
]
|
|
314
332
|
: []),
|
|
@@ -356,8 +374,8 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
356
374
|
currentIdentity: string | undefined,
|
|
357
375
|
liveScopedModels: readonly ScopedModel[],
|
|
358
376
|
) => {
|
|
359
|
-
if (modelPreferences === undefined) return;
|
|
360
|
-
const preferredIdentity =
|
|
377
|
+
if (!filteringEnabled() || modelPreferences === undefined) return;
|
|
378
|
+
const preferredIdentity = selectModelPreference(liveScopedModels, true);
|
|
361
379
|
if (!preferredIdentity) return;
|
|
362
380
|
if (!currentIdentity) throw new Error(`Subagent ${options.path} has no selected model`);
|
|
363
381
|
if (currentIdentity !== preferredIdentity) {
|
|
@@ -380,11 +398,11 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
380
398
|
session.setScopedModels([...liveScopedModels]);
|
|
381
399
|
lastScopedModelsKey = key;
|
|
382
400
|
}
|
|
383
|
-
if (modelPreferences === undefined) {
|
|
401
|
+
if (!filteringEnabled() || modelPreferences === undefined) {
|
|
384
402
|
updateResolved();
|
|
385
403
|
return;
|
|
386
404
|
}
|
|
387
|
-
const preferredIdentity =
|
|
405
|
+
const preferredIdentity = selectModelPreference(liveScopedModels, true);
|
|
388
406
|
if (!preferredIdentity) {
|
|
389
407
|
updateResolved();
|
|
390
408
|
return;
|
|
@@ -480,10 +498,22 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
480
498
|
let running = false;
|
|
481
499
|
let aborted = false;
|
|
482
500
|
let baseline = session.messages.length;
|
|
501
|
+
// Subscribe after inherited/restored history is loaded; only new assistant events are counted.
|
|
502
|
+
let settledInput = 0;
|
|
503
|
+
let settledOutput = 0;
|
|
504
|
+
const countedUsage = new WeakSet<object>();
|
|
483
505
|
let finalOutput = "";
|
|
484
506
|
let abortPromise: Promise<void> | undefined;
|
|
485
507
|
const emit = (kind: "activity" | "error", text: string) =>
|
|
486
508
|
options.onEvent({ kind, text: text.slice(0, 1000) });
|
|
509
|
+
const assistantUsage = (message: AssistantMessage) => {
|
|
510
|
+
const usage = message.usage;
|
|
511
|
+
const input = usage.input + usage.cacheRead + usage.cacheWrite;
|
|
512
|
+
const output = usage.output;
|
|
513
|
+
if (!Number.isFinite(input) || !Number.isFinite(output)) return;
|
|
514
|
+
return { input, output, reported: input + output + usage.totalTokens > 0 };
|
|
515
|
+
};
|
|
516
|
+
|
|
487
517
|
const unsubscribe = session.subscribe((event) => {
|
|
488
518
|
if (event.type === "tool_execution_start") emit("activity", `Tool: ${event.toolName}`);
|
|
489
519
|
if (event.type === "tool_execution_end")
|
|
@@ -491,12 +521,37 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
491
521
|
event.isError ? "error" : "activity",
|
|
492
522
|
`Tool ${event.toolName}: ${event.isError ? "failed" : "finished"}`,
|
|
493
523
|
);
|
|
494
|
-
if (
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
524
|
+
if (
|
|
525
|
+
(event.type === "message_update" || event.type === "message_end") &&
|
|
526
|
+
event.message.role === "assistant" &&
|
|
527
|
+
!countedUsage.has(event.message)
|
|
528
|
+
) {
|
|
529
|
+
const usage = assistantUsage(event.message);
|
|
530
|
+
if (event.type === "message_update") {
|
|
531
|
+
if (usage?.reported)
|
|
532
|
+
options.onEvent({
|
|
533
|
+
kind: "usage",
|
|
534
|
+
inputTokens: settledInput + usage.input,
|
|
535
|
+
outputTokens: settledOutput + usage.output,
|
|
536
|
+
partial: true,
|
|
537
|
+
});
|
|
538
|
+
} else {
|
|
539
|
+
countedUsage.add(event.message);
|
|
540
|
+
if (usage) {
|
|
541
|
+
settledInput += usage.input;
|
|
542
|
+
settledOutput += usage.output;
|
|
543
|
+
}
|
|
544
|
+
options.onEvent({
|
|
545
|
+
kind: "usage",
|
|
546
|
+
inputTokens: settledInput,
|
|
547
|
+
outputTokens: settledOutput,
|
|
548
|
+
});
|
|
549
|
+
const text = event.message.content
|
|
550
|
+
.filter((block) => block.type === "text")
|
|
551
|
+
.map((block) => block.text)
|
|
552
|
+
.join("");
|
|
553
|
+
if (text) emit("activity", text);
|
|
554
|
+
}
|
|
500
555
|
}
|
|
501
556
|
});
|
|
502
557
|
const assertOpen = () => {
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ConfigStore } from "./config.ts";
|
|
3
|
+
import {
|
|
4
|
+
canOpenDialog,
|
|
5
|
+
dialogInput,
|
|
6
|
+
dialogMenu,
|
|
7
|
+
withDialogSession,
|
|
8
|
+
} from "./dialog.ts";
|
|
9
|
+
import {
|
|
10
|
+
DEFAULT_MANAGER_SETTINGS,
|
|
11
|
+
saveManagerSettings,
|
|
12
|
+
type ManagerSettings,
|
|
13
|
+
} from "./settings.ts";
|
|
14
|
+
import { editAgentTypes } from "./ui.ts";
|
|
15
|
+
|
|
16
|
+
const FIELDS = [
|
|
17
|
+
{
|
|
18
|
+
id: "maxLevels",
|
|
19
|
+
label: "Maximum levels",
|
|
20
|
+
help: "Includes the root (L1). Positive integer, at most 32.",
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
id: "maxConcurrent",
|
|
24
|
+
label: "Concurrent agents",
|
|
25
|
+
help: "Shared active-thread limit, including waiting parents. Positive safe integer.",
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
id: "maxThreads",
|
|
29
|
+
label: "Retained threads",
|
|
30
|
+
help: "Maximum retained agent sessions. Positive safe integer.",
|
|
31
|
+
},
|
|
32
|
+
] as const;
|
|
33
|
+
|
|
34
|
+
const SCOPED_MODEL_FILTERING = {
|
|
35
|
+
id: "scopedModelFiltering",
|
|
36
|
+
label: "Scoped model filtering",
|
|
37
|
+
help: "On matches /scoped-models only. Off allows any available model. Draft only until save.",
|
|
38
|
+
} as const;
|
|
39
|
+
|
|
40
|
+
export async function configureAgents(
|
|
41
|
+
ctx: ExtensionCommandContext,
|
|
42
|
+
options: {
|
|
43
|
+
store: ConfigStore;
|
|
44
|
+
settings: ManagerSettings;
|
|
45
|
+
agentDir: string;
|
|
46
|
+
apply(): void;
|
|
47
|
+
},
|
|
48
|
+
): Promise<void> {
|
|
49
|
+
if (!canOpenDialog(ctx)) return;
|
|
50
|
+
await withDialogSession(ctx, (scoped) =>
|
|
51
|
+
configureAgentsDialog(scoped, options),
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function configureAgentsDialog(
|
|
56
|
+
ctx: ExtensionCommandContext,
|
|
57
|
+
options: {
|
|
58
|
+
store: ConfigStore;
|
|
59
|
+
settings: ManagerSettings;
|
|
60
|
+
agentDir: string;
|
|
61
|
+
apply(): void;
|
|
62
|
+
},
|
|
63
|
+
): Promise<void> {
|
|
64
|
+
let draft = { ...options.settings };
|
|
65
|
+
let scope: "user" | "project" = ctx.isProjectTrusted() ? "project" : "user";
|
|
66
|
+
let selectedId: string | undefined;
|
|
67
|
+
while (true) {
|
|
68
|
+
const dirty = JSON.stringify(draft) !== JSON.stringify(options.settings);
|
|
69
|
+
const action = await dialogMenu(
|
|
70
|
+
ctx,
|
|
71
|
+
`Agents settings${dirty ? " · unsaved" : ""}`,
|
|
72
|
+
[
|
|
73
|
+
...FIELDS.map((field) => ({
|
|
74
|
+
...field,
|
|
75
|
+
value: String(draft[field.id]),
|
|
76
|
+
})),
|
|
77
|
+
{
|
|
78
|
+
id: SCOPED_MODEL_FILTERING.id,
|
|
79
|
+
label: SCOPED_MODEL_FILTERING.label,
|
|
80
|
+
value: draft.scopedModelFiltering ? "on" : "off",
|
|
81
|
+
help: SCOPED_MODEL_FILTERING.help,
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
id: "scope",
|
|
85
|
+
label: "Save scope",
|
|
86
|
+
value: scope === "user" ? "Global" : "Trusted project",
|
|
87
|
+
help: "Project settings override global settings. Changes apply after saving.",
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
id: "types",
|
|
91
|
+
label: "Agent definitions",
|
|
92
|
+
value: `${options.store.list().length} types`,
|
|
93
|
+
help: "Create or edit agent definitions, model preferences and tool policy.",
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
id: "defaults",
|
|
97
|
+
label: "Restore defaults",
|
|
98
|
+
help: "Reset the draft only; save to apply.",
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: "save",
|
|
102
|
+
label: "Save and apply",
|
|
103
|
+
help: "Apply without interrupting existing agents or discarding retained sessions.",
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
id: "cancel",
|
|
107
|
+
label: "Cancel",
|
|
108
|
+
help: "Close without saving manager settings.",
|
|
109
|
+
},
|
|
110
|
+
],
|
|
111
|
+
{
|
|
112
|
+
selectedId,
|
|
113
|
+
saveId: "save",
|
|
114
|
+
footer: "↑↓/Tab navigate · Enter edit · Ctrl+S save · Esc cancel",
|
|
115
|
+
},
|
|
116
|
+
);
|
|
117
|
+
if (!action || action === "cancel") return;
|
|
118
|
+
selectedId = action;
|
|
119
|
+
try {
|
|
120
|
+
const field = FIELDS.find((field) => field.id === action);
|
|
121
|
+
if (field) {
|
|
122
|
+
const value = await dialogInput(
|
|
123
|
+
ctx,
|
|
124
|
+
field.label,
|
|
125
|
+
String(draft[field.id]),
|
|
126
|
+
field.help,
|
|
127
|
+
);
|
|
128
|
+
if (value === undefined) continue;
|
|
129
|
+
const number = Number(value.trim());
|
|
130
|
+
if (
|
|
131
|
+
!/^\d+$/.test(value.trim()) ||
|
|
132
|
+
!Number.isSafeInteger(number) ||
|
|
133
|
+
number < 1 ||
|
|
134
|
+
(field.id === "maxLevels" && number > 32)
|
|
135
|
+
)
|
|
136
|
+
throw new Error(field.help);
|
|
137
|
+
draft[field.id] = number;
|
|
138
|
+
} else if (action === "scopedModelFiltering") {
|
|
139
|
+
draft.scopedModelFiltering = !draft.scopedModelFiltering;
|
|
140
|
+
} else if (action === "scope") {
|
|
141
|
+
if (!ctx.isProjectTrusted())
|
|
142
|
+
ctx.ui.notify(
|
|
143
|
+
"Project settings require a trusted project; saving globally.",
|
|
144
|
+
"warning",
|
|
145
|
+
);
|
|
146
|
+
else scope = scope === "user" ? "project" : "user";
|
|
147
|
+
} else if (action === "defaults") draft = { ...DEFAULT_MANAGER_SETTINGS };
|
|
148
|
+
else if (action === "types") {
|
|
149
|
+
await editAgentTypes(ctx, options.store);
|
|
150
|
+
options.store.reload();
|
|
151
|
+
} else if (action === "save") {
|
|
152
|
+
const file = saveManagerSettings({
|
|
153
|
+
cwd: ctx.cwd,
|
|
154
|
+
agentDir: options.agentDir,
|
|
155
|
+
includeProject: ctx.isProjectTrusted(),
|
|
156
|
+
scope,
|
|
157
|
+
settings: draft,
|
|
158
|
+
});
|
|
159
|
+
options.apply();
|
|
160
|
+
ctx.ui.notify(
|
|
161
|
+
`Saved ${file}. Settings reloaded; project overrides take precedence.`,
|
|
162
|
+
"info",
|
|
163
|
+
);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
} catch (error) {
|
|
167
|
+
ctx.ui.notify(
|
|
168
|
+
error instanceof Error ? error.message : String(error),
|
|
169
|
+
"error",
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
package/src/settings.ts
CHANGED
|
@@ -1,19 +1,33 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
closeSync,
|
|
4
|
+
constants,
|
|
5
|
+
fchmodSync,
|
|
6
|
+
lstatSync,
|
|
7
|
+
mkdirSync,
|
|
8
|
+
openSync,
|
|
9
|
+
readFileSync,
|
|
10
|
+
renameSync,
|
|
11
|
+
unlinkSync,
|
|
12
|
+
writeFileSync,
|
|
13
|
+
} from "node:fs";
|
|
14
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
15
|
|
|
4
16
|
export interface ManagerSettings {
|
|
5
17
|
maxLevels: number;
|
|
6
18
|
maxConcurrent: number;
|
|
7
19
|
maxThreads: number;
|
|
20
|
+
scopedModelFiltering: boolean;
|
|
8
21
|
}
|
|
9
22
|
|
|
10
23
|
export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
|
|
11
24
|
maxLevels: 3,
|
|
12
25
|
maxConcurrent: 16,
|
|
13
26
|
maxThreads: 64,
|
|
27
|
+
scopedModelFiltering: true,
|
|
14
28
|
};
|
|
15
29
|
|
|
16
|
-
const KEYS = ["maxLevels", "maxConcurrent", "maxThreads"] as const;
|
|
30
|
+
const KEYS = ["maxLevels", "maxConcurrent", "maxThreads", "scopedModelFiltering"] as const;
|
|
17
31
|
const MAX_LEVELS = 32;
|
|
18
32
|
|
|
19
33
|
function errorCode(error: unknown): string | undefined {
|
|
@@ -22,7 +36,9 @@ function errorCode(error: unknown): string | undefined {
|
|
|
22
36
|
: undefined;
|
|
23
37
|
}
|
|
24
38
|
|
|
25
|
-
function lstatIfPresent(
|
|
39
|
+
function lstatIfPresent(
|
|
40
|
+
path: string,
|
|
41
|
+
): ReturnType<typeof lstatSync> | undefined {
|
|
26
42
|
try {
|
|
27
43
|
return lstatSync(path);
|
|
28
44
|
} catch (error) {
|
|
@@ -31,7 +47,9 @@ function lstatIfPresent(path: string): ReturnType<typeof lstatSync> | undefined
|
|
|
31
47
|
}
|
|
32
48
|
}
|
|
33
49
|
|
|
34
|
-
function assertNotSymlinkPath(
|
|
50
|
+
function assertNotSymlinkPath(
|
|
51
|
+
path: string,
|
|
52
|
+
): ReturnType<typeof lstatSync> | undefined {
|
|
35
53
|
const stat = lstatIfPresent(path);
|
|
36
54
|
if (stat?.isSymbolicLink()) throw new Error(`Unsafe symlink path: ${path}`);
|
|
37
55
|
return stat;
|
|
@@ -45,6 +63,12 @@ function positiveSafeInteger(value: unknown): value is number {
|
|
|
45
63
|
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
46
64
|
}
|
|
47
65
|
|
|
66
|
+
function requirement(key: (typeof KEYS)[number]): string {
|
|
67
|
+
return key === "scopedModelFiltering"
|
|
68
|
+
? "scopedModelFiltering must be a boolean"
|
|
69
|
+
: `${key} must be a positive safe integer`;
|
|
70
|
+
}
|
|
71
|
+
|
|
48
72
|
function parseSettings(content: string): Partial<ManagerSettings> {
|
|
49
73
|
let parsed: unknown;
|
|
50
74
|
try {
|
|
@@ -64,7 +88,12 @@ function parseSettings(content: string): Partial<ManagerSettings> {
|
|
|
64
88
|
for (const key of KEYS) {
|
|
65
89
|
if (!Object.hasOwn(record, key)) continue;
|
|
66
90
|
const value = record[key];
|
|
67
|
-
if (
|
|
91
|
+
if (key === "scopedModelFiltering") {
|
|
92
|
+
if (typeof value !== "boolean") throw new Error(requirement(key));
|
|
93
|
+
layer.scopedModelFiltering = value;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (!positiveSafeInteger(value)) throw new Error(requirement(key));
|
|
68
97
|
if (key === "maxLevels" && value > MAX_LEVELS) throw new Error("maxLevels must be <= 32");
|
|
69
98
|
layer[key] = value;
|
|
70
99
|
}
|
|
@@ -95,7 +124,8 @@ function readLayer(entry: SettingsLayer): Partial<ManagerSettings> | undefined {
|
|
|
95
124
|
}
|
|
96
125
|
const stat = assertNotSymlinkPath(entry.filePath);
|
|
97
126
|
if (!stat) return undefined;
|
|
98
|
-
if (!stat.isFile())
|
|
127
|
+
if (!stat.isFile())
|
|
128
|
+
throw new Error(`Settings must be a regular file: ${entry.filePath}`);
|
|
99
129
|
return parseSettings(readFileSync(entry.filePath, "utf8"));
|
|
100
130
|
}
|
|
101
131
|
|
|
@@ -111,7 +141,8 @@ export function loadManagerSettings(options: {
|
|
|
111
141
|
const diagnostics: string[] = [];
|
|
112
142
|
const settings: ManagerSettings = { ...DEFAULT_MANAGER_SETTINGS };
|
|
113
143
|
const layers = [layer(options.agentDir, ["subagent-manager"])];
|
|
114
|
-
if (options.includeProject)
|
|
144
|
+
if (options.includeProject)
|
|
145
|
+
layers.push(layer(options.cwd, [".pi", "agent", "subagent-manager"]));
|
|
115
146
|
for (const entry of layers) {
|
|
116
147
|
try {
|
|
117
148
|
const parsed = readLayer(entry);
|
|
@@ -122,3 +153,117 @@ export function loadManagerSettings(options: {
|
|
|
122
153
|
}
|
|
123
154
|
return { settings, diagnostics };
|
|
124
155
|
}
|
|
156
|
+
|
|
157
|
+
function serializedSettings(settings: ManagerSettings): string {
|
|
158
|
+
if (
|
|
159
|
+
settings === null ||
|
|
160
|
+
typeof settings !== "object" ||
|
|
161
|
+
Array.isArray(settings)
|
|
162
|
+
) {
|
|
163
|
+
throw new Error("Settings must be a JSON object");
|
|
164
|
+
}
|
|
165
|
+
for (const key of Object.keys(settings)) {
|
|
166
|
+
if (!isSupportedKey(key)) throw new Error(`Unknown settings key: ${key}`);
|
|
167
|
+
}
|
|
168
|
+
const parsed = parseSettings(JSON.stringify(settings));
|
|
169
|
+
for (const key of KEYS) {
|
|
170
|
+
if (!Object.hasOwn(parsed, key)) throw new Error(requirement(key));
|
|
171
|
+
}
|
|
172
|
+
const serialized = `${JSON.stringify(parsed, null, 2)}\n`;
|
|
173
|
+
const confirmed = parseSettings(serialized);
|
|
174
|
+
for (const key of KEYS) {
|
|
175
|
+
if (confirmed[key] !== parsed[key]) throw new Error(requirement(key));
|
|
176
|
+
}
|
|
177
|
+
return serialized;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function assertExistingDirectory(directory: string): void {
|
|
181
|
+
const stat = assertNotSymlinkPath(directory);
|
|
182
|
+
if (!stat?.isDirectory()) throw new Error(`Settings directory must be a directory: ${directory}`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function ensureOwnedDirectory(directory: string): void {
|
|
186
|
+
let stat = assertNotSymlinkPath(directory);
|
|
187
|
+
if (!stat) {
|
|
188
|
+
try {
|
|
189
|
+
mkdirSync(directory);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
192
|
+
}
|
|
193
|
+
stat = assertNotSymlinkPath(directory);
|
|
194
|
+
}
|
|
195
|
+
if (!stat?.isDirectory()) throw new Error(`Settings directory must be a directory: ${directory}`);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function ensureScopeDirectories(directories: string[]): void {
|
|
199
|
+
assertExistingDirectory(directories[0]);
|
|
200
|
+
for (let index = 1; index < directories.length; index++) {
|
|
201
|
+
assertExistingDirectory(directories[index - 1]);
|
|
202
|
+
ensureOwnedDirectory(directories[index]);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function assertRegularFileOrAbsent(filePath: string): void {
|
|
207
|
+
const stat = assertNotSymlinkPath(filePath);
|
|
208
|
+
if (stat && !stat.isFile())
|
|
209
|
+
throw new Error(`Settings must be a regular file: ${filePath}`);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function exclusiveCreateFlags(): number {
|
|
213
|
+
return constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW || 0);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function writeAtomically(entry: SettingsLayer, content: string): void {
|
|
217
|
+
const filePath = entry.filePath;
|
|
218
|
+
const temporary = join(dirname(filePath), `.settings.${randomUUID()}.tmp`);
|
|
219
|
+
let created = false;
|
|
220
|
+
try {
|
|
221
|
+
for (const directory of entry.directories) assertExistingDirectory(directory);
|
|
222
|
+
assertRegularFileOrAbsent(filePath);
|
|
223
|
+
const fd = openSync(temporary, exclusiveCreateFlags(), 0o600);
|
|
224
|
+
created = true;
|
|
225
|
+
try {
|
|
226
|
+
fchmodSync(fd, 0o600);
|
|
227
|
+
writeFileSync(fd, content);
|
|
228
|
+
} finally {
|
|
229
|
+
closeSync(fd);
|
|
230
|
+
}
|
|
231
|
+
for (const directory of entry.directories) assertExistingDirectory(directory);
|
|
232
|
+
assertRegularFileOrAbsent(filePath);
|
|
233
|
+
const tempStat = assertNotSymlinkPath(temporary);
|
|
234
|
+
if (!tempStat?.isFile())
|
|
235
|
+
throw new Error(`Settings must be a regular file: ${temporary}`);
|
|
236
|
+
renameSync(temporary, filePath);
|
|
237
|
+
} finally {
|
|
238
|
+
if (created) {
|
|
239
|
+
try {
|
|
240
|
+
if (lstatIfPresent(temporary)) unlinkSync(temporary);
|
|
241
|
+
} catch {
|
|
242
|
+
// Keep the original save error if cleanup fails.
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export function saveManagerSettings(options: {
|
|
249
|
+
cwd: string;
|
|
250
|
+
agentDir: string;
|
|
251
|
+
includeProject: boolean;
|
|
252
|
+
scope: "user" | "project";
|
|
253
|
+
settings: ManagerSettings;
|
|
254
|
+
}): string {
|
|
255
|
+
if (options.scope !== "user" && options.scope !== "project") {
|
|
256
|
+
throw new Error("Invalid settings scope");
|
|
257
|
+
}
|
|
258
|
+
if (options.scope === "project" && !options.includeProject) {
|
|
259
|
+
throw new Error("Project settings are not enabled/trusted");
|
|
260
|
+
}
|
|
261
|
+
const content = serializedSettings(options.settings);
|
|
262
|
+
const entry =
|
|
263
|
+
options.scope === "user"
|
|
264
|
+
? layer(options.agentDir, ["subagent-manager"])
|
|
265
|
+
: layer(options.cwd, [".pi", "agent", "subagent-manager"]);
|
|
266
|
+
ensureScopeDirectories(entry.directories);
|
|
267
|
+
writeAtomically(entry, content);
|
|
268
|
+
return entry.filePath;
|
|
269
|
+
}
|