pi-subagent-manager 0.1.1 → 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 +139 -17
- package/agents/architect.md +42 -0
- 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 +171 -42
- 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 +123 -29
- package/src/manager.ts +94 -5
- package/src/model-picker.ts +611 -0
- package/src/models.ts +60 -0
- package/src/runtime.ts +326 -64
- package/src/settings-ui.ts +173 -0
- package/src/settings.ts +269 -0
- package/src/status-ui.ts +288 -0
- package/src/thread-tree.ts +134 -0
- package/src/tools.ts +23 -11
- package/src/types.ts +31 -0
- package/src/ui.ts +924 -85
- package/agents/researcher.md +0 -14
- package/agents/worker.md +0 -6
package/src/settings.ts
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
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";
|
|
15
|
+
|
|
16
|
+
export interface ManagerSettings {
|
|
17
|
+
maxLevels: number;
|
|
18
|
+
maxConcurrent: number;
|
|
19
|
+
maxThreads: number;
|
|
20
|
+
scopedModelFiltering: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
|
|
24
|
+
maxLevels: 3,
|
|
25
|
+
maxConcurrent: 16,
|
|
26
|
+
maxThreads: 64,
|
|
27
|
+
scopedModelFiltering: true,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const KEYS = ["maxLevels", "maxConcurrent", "maxThreads", "scopedModelFiltering"] as const;
|
|
31
|
+
const MAX_LEVELS = 32;
|
|
32
|
+
|
|
33
|
+
function errorCode(error: unknown): string | undefined {
|
|
34
|
+
return typeof error === "object" && error !== null && "code" in error
|
|
35
|
+
? String((error as { code?: unknown }).code)
|
|
36
|
+
: undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function lstatIfPresent(
|
|
40
|
+
path: string,
|
|
41
|
+
): ReturnType<typeof lstatSync> | undefined {
|
|
42
|
+
try {
|
|
43
|
+
return lstatSync(path);
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (errorCode(error) === "ENOENT") return undefined;
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function assertNotSymlinkPath(
|
|
51
|
+
path: string,
|
|
52
|
+
): ReturnType<typeof lstatSync> | undefined {
|
|
53
|
+
const stat = lstatIfPresent(path);
|
|
54
|
+
if (stat?.isSymbolicLink()) throw new Error(`Unsafe symlink path: ${path}`);
|
|
55
|
+
return stat;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isSupportedKey(key: string): key is (typeof KEYS)[number] {
|
|
59
|
+
return KEYS.includes(key as (typeof KEYS)[number]);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function positiveSafeInteger(value: unknown): value is number {
|
|
63
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
64
|
+
}
|
|
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
|
+
|
|
72
|
+
function parseSettings(content: string): Partial<ManagerSettings> {
|
|
73
|
+
let parsed: unknown;
|
|
74
|
+
try {
|
|
75
|
+
parsed = JSON.parse(content);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
78
|
+
throw new Error(`Invalid JSON: ${detail}`);
|
|
79
|
+
}
|
|
80
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
81
|
+
throw new Error("Settings must be a JSON object");
|
|
82
|
+
}
|
|
83
|
+
const record = parsed as Record<string, unknown>;
|
|
84
|
+
for (const key of Object.keys(record)) {
|
|
85
|
+
if (!isSupportedKey(key)) throw new Error(`Unknown settings key: ${key}`);
|
|
86
|
+
}
|
|
87
|
+
const layer: Partial<ManagerSettings> = {};
|
|
88
|
+
for (const key of KEYS) {
|
|
89
|
+
if (!Object.hasOwn(record, key)) continue;
|
|
90
|
+
const value = record[key];
|
|
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));
|
|
97
|
+
if (key === "maxLevels" && value > MAX_LEVELS) throw new Error("maxLevels must be <= 32");
|
|
98
|
+
layer[key] = value;
|
|
99
|
+
}
|
|
100
|
+
return layer;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
interface SettingsLayer {
|
|
104
|
+
filePath: string;
|
|
105
|
+
directories: string[];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function layer(base: string, segments: string[]): SettingsLayer {
|
|
109
|
+
let current = resolve(base);
|
|
110
|
+
const directories = [current];
|
|
111
|
+
for (const segment of segments) {
|
|
112
|
+
current = join(current, segment);
|
|
113
|
+
directories.push(current);
|
|
114
|
+
}
|
|
115
|
+
return { filePath: join(current, "settings.json"), directories };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function readLayer(entry: SettingsLayer): Partial<ManagerSettings> | undefined {
|
|
119
|
+
for (const directory of entry.directories) {
|
|
120
|
+
const stat = assertNotSymlinkPath(directory);
|
|
121
|
+
if (!stat) return undefined;
|
|
122
|
+
if (!stat.isDirectory())
|
|
123
|
+
throw new Error(`Settings directory must be a directory: ${directory}`);
|
|
124
|
+
}
|
|
125
|
+
const stat = assertNotSymlinkPath(entry.filePath);
|
|
126
|
+
if (!stat) return undefined;
|
|
127
|
+
if (!stat.isFile())
|
|
128
|
+
throw new Error(`Settings must be a regular file: ${entry.filePath}`);
|
|
129
|
+
return parseSettings(readFileSync(entry.filePath, "utf8"));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function detail(error: unknown): string {
|
|
133
|
+
return error instanceof Error ? error.message : String(error);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function loadManagerSettings(options: {
|
|
137
|
+
cwd: string;
|
|
138
|
+
agentDir: string;
|
|
139
|
+
includeProject: boolean;
|
|
140
|
+
}): { settings: ManagerSettings; diagnostics: string[] } {
|
|
141
|
+
const diagnostics: string[] = [];
|
|
142
|
+
const settings: ManagerSettings = { ...DEFAULT_MANAGER_SETTINGS };
|
|
143
|
+
const layers = [layer(options.agentDir, ["subagent-manager"])];
|
|
144
|
+
if (options.includeProject)
|
|
145
|
+
layers.push(layer(options.cwd, [".pi", "agent", "subagent-manager"]));
|
|
146
|
+
for (const entry of layers) {
|
|
147
|
+
try {
|
|
148
|
+
const parsed = readLayer(entry);
|
|
149
|
+
if (parsed !== undefined) Object.assign(settings, parsed);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
diagnostics.push(`${entry.filePath}: ${detail(error)}`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return { settings, diagnostics };
|
|
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
|
+
}
|
package/src/status-ui.ts
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionCommandContext,
|
|
3
|
+
Theme,
|
|
4
|
+
} from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { getKeybindings, Key, matchesKey } from "@earendil-works/pi-tui";
|
|
6
|
+
import {
|
|
7
|
+
canOpenDialog,
|
|
8
|
+
DIALOG_OPTIONS,
|
|
9
|
+
type DialogHost,
|
|
10
|
+
dialogHeight,
|
|
11
|
+
dialogText,
|
|
12
|
+
frameDialog,
|
|
13
|
+
withDialogSession,
|
|
14
|
+
} from "./dialog.ts";
|
|
15
|
+
import type { ThreadService } from "./types.ts";
|
|
16
|
+
import { buildStatusTree, type StatusRow } from "./thread-tree.ts";
|
|
17
|
+
import { showThreads, threadMetrics } from "./ui.ts";
|
|
18
|
+
|
|
19
|
+
export { buildStatusTree, type StatusRow };
|
|
20
|
+
|
|
21
|
+
const ROOT = "/root";
|
|
22
|
+
const TITLE = "Agents status";
|
|
23
|
+
const TREE_TITLE = "Agents tree";
|
|
24
|
+
const FOOTER =
|
|
25
|
+
"Esc close · ↑↓ select · ←→ fold · PgUp/PgDn · Enter inspect · r refresh";
|
|
26
|
+
|
|
27
|
+
function agentCount(threads: readonly { path?: string }[]): number {
|
|
28
|
+
const paths = new Set<string>();
|
|
29
|
+
for (const thread of threads) {
|
|
30
|
+
if (thread?.path && thread.path !== ROOT) paths.add(thread.path);
|
|
31
|
+
}
|
|
32
|
+
return paths.size;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function lexicalParent(path: string): string | null {
|
|
36
|
+
const index = path.lastIndexOf("/");
|
|
37
|
+
return index > 0 ? path.slice(0, index) : null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function treeParent(rows: StatusRow[], index: number): StatusRow | undefined {
|
|
41
|
+
const depth = rows[index]?.prefix.length ?? 0;
|
|
42
|
+
for (let cursor = index - 1; cursor >= 0; cursor--) {
|
|
43
|
+
if (rows[cursor]!.prefix.length < depth) return rows[cursor];
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function firstChild(rows: StatusRow[], index: number): StatusRow | undefined {
|
|
49
|
+
const next = rows[index + 1];
|
|
50
|
+
return next && next.prefix.length > (rows[index]?.prefix.length ?? 0)
|
|
51
|
+
? next
|
|
52
|
+
: undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function label(row: StatusRow): string {
|
|
56
|
+
if (!row.thread)
|
|
57
|
+
return row.path === ROOT
|
|
58
|
+
? `${dialogText(row.path)} main running main`
|
|
59
|
+
: `${dialogText(row.path)} missing parent`;
|
|
60
|
+
return [row.path, row.thread.type, row.thread.state, row.thread.status]
|
|
61
|
+
.map((part) => dialogText(part))
|
|
62
|
+
.join(" ");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export class StatusDialog {
|
|
66
|
+
private selectedPath: string;
|
|
67
|
+
private collapsed = new Set<string>();
|
|
68
|
+
private viewport = 1;
|
|
69
|
+
private timer: ReturnType<typeof setInterval> | undefined;
|
|
70
|
+
|
|
71
|
+
constructor(
|
|
72
|
+
private host: DialogHost,
|
|
73
|
+
private theme: Theme,
|
|
74
|
+
private service: ThreadService,
|
|
75
|
+
private done: (path: string | undefined) => void,
|
|
76
|
+
selected?: string,
|
|
77
|
+
private title = TITLE,
|
|
78
|
+
) {
|
|
79
|
+
this.selectedPath = selected || ROOT;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
invalidate(): void {}
|
|
83
|
+
|
|
84
|
+
/** Arm the 1s refresh. Host disposal can leave the dialog promise pending. */
|
|
85
|
+
startRefresh(): void {
|
|
86
|
+
this.stopRefresh();
|
|
87
|
+
this.timer = setInterval(() => this.host.requestRender(), 1000);
|
|
88
|
+
if (typeof this.timer.unref === "function") this.timer.unref();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Stop the refresh. Safe to call more than once, including from dispose(). */
|
|
92
|
+
dispose(): void {
|
|
93
|
+
this.stopRefresh();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private stopRefresh(): void {
|
|
97
|
+
if (this.timer === undefined) return;
|
|
98
|
+
clearInterval(this.timer);
|
|
99
|
+
this.timer = undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private rows(): StatusRow[] {
|
|
103
|
+
return buildStatusTree(this.service.list(), this.collapsed);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private locate(rows: StatusRow[]): number {
|
|
107
|
+
const exact = rows.findIndex((row) => row.path === this.selectedPath);
|
|
108
|
+
if (exact >= 0) return exact;
|
|
109
|
+
let parent = lexicalParent(this.selectedPath);
|
|
110
|
+
while (parent) {
|
|
111
|
+
const index = rows.findIndex((row) => row.path === parent);
|
|
112
|
+
if (index >= 0) return index;
|
|
113
|
+
parent = lexicalParent(parent);
|
|
114
|
+
}
|
|
115
|
+
const root = rows.findIndex((row) => row.path === ROOT);
|
|
116
|
+
return root >= 0 ? root : 0;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
handleInput(data: string): void {
|
|
120
|
+
const keys = getKeybindings();
|
|
121
|
+
if (keys.matches(data, "tui.select.cancel")) {
|
|
122
|
+
this.done(undefined);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const rows = this.rows();
|
|
126
|
+
const index = this.locate(rows);
|
|
127
|
+
const row = rows[index];
|
|
128
|
+
if (row) this.selectedPath = row.path;
|
|
129
|
+
if (keys.matches(data, "tui.select.confirm")) {
|
|
130
|
+
if (row?.thread && row.path !== ROOT) this.done(row.path);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (data === "r") {
|
|
134
|
+
this.host.requestRender();
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (matchesKey(data, Key.left)) {
|
|
138
|
+
if (row?.hasChildren && !this.collapsed.has(row.path))
|
|
139
|
+
this.collapsed.add(row.path);
|
|
140
|
+
else if (row) {
|
|
141
|
+
const parent = treeParent(rows, index);
|
|
142
|
+
if (parent) this.selectedPath = parent.path;
|
|
143
|
+
}
|
|
144
|
+
} else if (matchesKey(data, Key.right)) {
|
|
145
|
+
if (row?.hasChildren && this.collapsed.has(row.path))
|
|
146
|
+
this.collapsed.delete(row.path);
|
|
147
|
+
else {
|
|
148
|
+
const child = row?.hasChildren ? firstChild(rows, index) : undefined;
|
|
149
|
+
if (child) this.selectedPath = child.path;
|
|
150
|
+
}
|
|
151
|
+
} else {
|
|
152
|
+
let next = index;
|
|
153
|
+
if (keys.matches(data, "tui.select.up")) next -= 1;
|
|
154
|
+
else if (keys.matches(data, "tui.select.down")) next += 1;
|
|
155
|
+
else if (matchesKey(data, Key.pageUp)) next -= this.viewport;
|
|
156
|
+
else if (matchesKey(data, Key.pageDown)) next += this.viewport;
|
|
157
|
+
else if (matchesKey(data, Key.home)) next = 0;
|
|
158
|
+
else if (matchesKey(data, Key.end)) next = Math.max(0, rows.length - 1);
|
|
159
|
+
else return;
|
|
160
|
+
this.selectedPath =
|
|
161
|
+
rows[Math.max(0, Math.min(rows.length - 1, next))]?.path ??
|
|
162
|
+
this.selectedPath;
|
|
163
|
+
}
|
|
164
|
+
this.host.requestRender();
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private line(row: StatusRow, selected: boolean): string {
|
|
168
|
+
const marker = row.hasChildren
|
|
169
|
+
? this.collapsed.has(row.path)
|
|
170
|
+
? "▸ "
|
|
171
|
+
: "▾ "
|
|
172
|
+
: "";
|
|
173
|
+
const text = ` ${row.prefix}${selected ? "›" : " "} ${marker}${label(row)}`;
|
|
174
|
+
if (selected) return this.theme.fg("accent", text);
|
|
175
|
+
if (row.thread?.state === "failed") return this.theme.fg("error", text);
|
|
176
|
+
if (row.thread?.state === "paused") return this.theme.fg("warning", text);
|
|
177
|
+
return text;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private detail(row: StatusRow | undefined): string[] {
|
|
181
|
+
if (!row?.thread) {
|
|
182
|
+
return [
|
|
183
|
+
` ${row?.path === ROOT ? "Main Pi session" : "Missing parent"}`,
|
|
184
|
+
"",
|
|
185
|
+
];
|
|
186
|
+
}
|
|
187
|
+
return [
|
|
188
|
+
` task ${dialogText(row.thread.task)}`,
|
|
189
|
+
` ${threadMetrics(row.thread)}`,
|
|
190
|
+
];
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
render(width: number): string[] {
|
|
194
|
+
const rows = this.rows();
|
|
195
|
+
const height = dialogHeight(this.host);
|
|
196
|
+
const index = this.locate(rows);
|
|
197
|
+
if (rows[index]) this.selectedPath = rows[index].path;
|
|
198
|
+
const budget = Math.max(0, height - 4);
|
|
199
|
+
const detail = budget > 2 ? this.detail(rows[index]) : [];
|
|
200
|
+
const treeCount = Math.max(0, budget - detail.length);
|
|
201
|
+
this.viewport = Math.max(1, treeCount);
|
|
202
|
+
const start = treeCount
|
|
203
|
+
? Math.max(
|
|
204
|
+
0,
|
|
205
|
+
Math.min(index - treeCount + 1, Math.max(0, rows.length - treeCount)),
|
|
206
|
+
)
|
|
207
|
+
: 0;
|
|
208
|
+
const body = [
|
|
209
|
+
...rows
|
|
210
|
+
.slice(start, start + treeCount)
|
|
211
|
+
.map((row) => this.line(row, row.path === this.selectedPath)),
|
|
212
|
+
...detail,
|
|
213
|
+
];
|
|
214
|
+
return frameDialog(
|
|
215
|
+
this.theme,
|
|
216
|
+
width,
|
|
217
|
+
height,
|
|
218
|
+
this.heading(rows, start, treeCount),
|
|
219
|
+
body,
|
|
220
|
+
FOOTER,
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
private heading(rows: StatusRow[], start: number, treeCount: number): string {
|
|
225
|
+
if (this.title !== TREE_TITLE) return this.title;
|
|
226
|
+
const agents = agentCount(this.service.list());
|
|
227
|
+
const noun = agents === 1 ? "agent" : "agents";
|
|
228
|
+
const total = rows.length;
|
|
229
|
+
const shown = Math.max(0, Math.min(treeCount, total - start));
|
|
230
|
+
if (shown <= 0) return `${TREE_TITLE} ${agents} ${noun}`;
|
|
231
|
+
return `${TREE_TITLE} ${agents} ${noun} ${start + 1}-${start + shown}/${total}`;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function showAgentDialog(
|
|
236
|
+
ctx: ExtensionCommandContext,
|
|
237
|
+
service: ThreadService,
|
|
238
|
+
options: {
|
|
239
|
+
title?: string;
|
|
240
|
+
selected?: string;
|
|
241
|
+
inspect?: (path: string) => Promise<void>;
|
|
242
|
+
} = {},
|
|
243
|
+
): Promise<void> {
|
|
244
|
+
const open = options.inspect ?? ((path: string) => showThreads(ctx, service, path));
|
|
245
|
+
let selected = options.selected;
|
|
246
|
+
for (;;) {
|
|
247
|
+
// Cleared on close and from dispose(): DialogSession host disposal can
|
|
248
|
+
// leave this promise pending, so finally alone may not run immediately.
|
|
249
|
+
let dialog: StatusDialog | undefined;
|
|
250
|
+
try {
|
|
251
|
+
const chosen = await ctx.ui.custom<string | undefined>((host, theme, _keys, done) => {
|
|
252
|
+
dialog = new StatusDialog(host, theme, service, done, selected, options.title);
|
|
253
|
+
dialog.startRefresh();
|
|
254
|
+
return dialog;
|
|
255
|
+
}, DIALOG_OPTIONS);
|
|
256
|
+
dialog?.dispose();
|
|
257
|
+
dialog = undefined;
|
|
258
|
+
if (!chosen) return;
|
|
259
|
+
selected = chosen;
|
|
260
|
+
await open(chosen);
|
|
261
|
+
} finally {
|
|
262
|
+
dialog?.dispose();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export async function showAgentStatus(
|
|
268
|
+
ctx: ExtensionCommandContext,
|
|
269
|
+
service: ThreadService,
|
|
270
|
+
inspect?: (path: string) => Promise<void>,
|
|
271
|
+
): Promise<void> {
|
|
272
|
+
if (!canOpenDialog(ctx)) return;
|
|
273
|
+
await showAgentDialog(ctx, service, { inspect });
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export async function showAgentTree(
|
|
277
|
+
ctx: ExtensionCommandContext,
|
|
278
|
+
service: ThreadService,
|
|
279
|
+
selectedPath?: string,
|
|
280
|
+
): Promise<void> {
|
|
281
|
+
if (!canOpenDialog(ctx)) return;
|
|
282
|
+
await withDialogSession(ctx, (scoped) =>
|
|
283
|
+
showAgentDialog(scoped, service, {
|
|
284
|
+
title: TREE_TITLE,
|
|
285
|
+
selected: selectedPath,
|
|
286
|
+
}),
|
|
287
|
+
);
|
|
288
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import type { ThreadView } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
const ROOT = "/root";
|
|
4
|
+
|
|
5
|
+
export interface StatusRow {
|
|
6
|
+
path: string;
|
|
7
|
+
prefix: string;
|
|
8
|
+
thread?: ThreadView;
|
|
9
|
+
hasChildren: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface StatusNode {
|
|
13
|
+
path: string;
|
|
14
|
+
thread?: ThreadView;
|
|
15
|
+
children: StatusNode[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function lexicalParent(path: string): string | null {
|
|
19
|
+
const index = path.lastIndexOf("/");
|
|
20
|
+
return index > 0 ? path.slice(0, index) : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function comparePath(a: string, b: string): number {
|
|
24
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function chainHas(
|
|
28
|
+
parentOf: Map<string, string | null>,
|
|
29
|
+
start: string,
|
|
30
|
+
target: string,
|
|
31
|
+
): boolean {
|
|
32
|
+
const seen = new Set<string>();
|
|
33
|
+
let current: string | null = start;
|
|
34
|
+
while (current) {
|
|
35
|
+
if (current === target || seen.has(current)) return true;
|
|
36
|
+
seen.add(current);
|
|
37
|
+
current = parentOf.get(current) ?? null;
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Flatten retained agents. Parent links win over path shape; /root is always present.
|
|
43
|
+
* `comparePaths` orders siblings and roots only. Cycle repair stays lexical.
|
|
44
|
+
*/
|
|
45
|
+
export function buildStatusTree(
|
|
46
|
+
threads: ThreadView[],
|
|
47
|
+
collapsed: Set<string>,
|
|
48
|
+
comparePaths: (a: string, b: string) => number = comparePath,
|
|
49
|
+
): StatusRow[] {
|
|
50
|
+
const threadsByPath = new Map<string, ThreadView>();
|
|
51
|
+
for (const thread of threads) {
|
|
52
|
+
if (thread?.path && !threadsByPath.has(thread.path))
|
|
53
|
+
threadsByPath.set(thread.path, thread);
|
|
54
|
+
}
|
|
55
|
+
const nodes = new Map<string, StatusNode>();
|
|
56
|
+
const parentOf = new Map<string, string | null>();
|
|
57
|
+
const nodeFor = (path: string): StatusNode => {
|
|
58
|
+
let node = nodes.get(path);
|
|
59
|
+
if (!node) {
|
|
60
|
+
node = { path, thread: threadsByPath.get(path), children: [] };
|
|
61
|
+
nodes.set(path, node);
|
|
62
|
+
}
|
|
63
|
+
return node;
|
|
64
|
+
};
|
|
65
|
+
const declaredParent = (path: string): string | null => {
|
|
66
|
+
if (path === ROOT) return null;
|
|
67
|
+
const thread = threadsByPath.get(path);
|
|
68
|
+
if (thread)
|
|
69
|
+
return thread.parent && thread.parent !== path ? thread.parent : null;
|
|
70
|
+
return lexicalParent(path);
|
|
71
|
+
};
|
|
72
|
+
const ensure = (path: string, seen = new Set<string>()): void => {
|
|
73
|
+
if (!path || seen.has(path)) return;
|
|
74
|
+
seen.add(path);
|
|
75
|
+
nodeFor(path);
|
|
76
|
+
if (parentOf.has(path)) return;
|
|
77
|
+
const parent = declaredParent(path);
|
|
78
|
+
parentOf.set(path, parent);
|
|
79
|
+
if (parent) ensure(parent, seen);
|
|
80
|
+
};
|
|
81
|
+
ensure(ROOT);
|
|
82
|
+
for (const path of threadsByPath.keys()) ensure(path);
|
|
83
|
+
|
|
84
|
+
const linked = new Set<string>();
|
|
85
|
+
for (const path of [...parentOf.keys()].sort(comparePath)) {
|
|
86
|
+
const parent = parentOf.get(path);
|
|
87
|
+
if (!parent || parent === path) continue;
|
|
88
|
+
if (chainHas(parentOf, parent, path)) {
|
|
89
|
+
parentOf.set(path, null);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const parentNode = nodeFor(parent);
|
|
93
|
+
const child = nodeFor(path);
|
|
94
|
+
if (!parentNode.children.includes(child)) parentNode.children.push(child);
|
|
95
|
+
linked.add(path);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const rows: StatusRow[] = [];
|
|
99
|
+
const visited = new Set<string>();
|
|
100
|
+
const conceal = (node: StatusNode) => {
|
|
101
|
+
for (const child of node.children) {
|
|
102
|
+
if (visited.has(child.path)) continue;
|
|
103
|
+
visited.add(child.path);
|
|
104
|
+
conceal(child);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
const walk = (list: StatusNode[], ancestors: boolean[], top: boolean) => {
|
|
108
|
+
const ordered = [...list]
|
|
109
|
+
.filter((node) => !visited.has(node.path))
|
|
110
|
+
.sort((a, b) => comparePaths(a.path, b.path));
|
|
111
|
+
for (const [index, node] of ordered.entries()) {
|
|
112
|
+
visited.add(node.path);
|
|
113
|
+
const last = index === ordered.length - 1;
|
|
114
|
+
const stem = ancestors.map((isLast) => (isLast ? " " : "│ ")).join("");
|
|
115
|
+
rows.push({
|
|
116
|
+
path: node.path,
|
|
117
|
+
prefix: stem + (top ? "" : last ? "└─ " : "├─ "),
|
|
118
|
+
hasChildren: node.children.length > 0,
|
|
119
|
+
...(node.thread ? { thread: node.thread } : {}),
|
|
120
|
+
});
|
|
121
|
+
if (collapsed.has(node.path)) conceal(node);
|
|
122
|
+
else if (node.children.length > 0)
|
|
123
|
+
walk(node.children, top ? [] : [...ancestors, last], false);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
walk(
|
|
127
|
+
[...nodes.values()].filter((node) => !linked.has(node.path)),
|
|
128
|
+
[],
|
|
129
|
+
true,
|
|
130
|
+
);
|
|
131
|
+
const missed = [...nodes.values()].filter((node) => !visited.has(node.path));
|
|
132
|
+
if (missed.length) walk(missed, [], true);
|
|
133
|
+
return rows;
|
|
134
|
+
}
|