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.
@@ -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
+ }
package/src/tools.ts CHANGED
@@ -40,23 +40,34 @@ export function agentTools(
40
40
  return [
41
41
  make(
42
42
  "agent_types",
43
- "List current agent types and their task descriptions. Reflects configuration reloads; call this before choosing a type.",
43
+ "List current agent types and their task descriptions. Reflects configuration reloads; call this before choosing a type. modelSuggestions are advisory display names, not model pins.",
44
44
  Type.Object({}),
45
45
  () =>
46
46
  result(
47
- getTypes().map(({ name, description, thinkingLevel, color, ...type }) => ({
48
- name,
49
- description,
50
- models: getModelPreferences(type),
51
- thinkingLevel,
52
- color,
53
- })),
47
+ getTypes().map(
48
+ ({ name, description, thinkingLevel, color, modelSuggestions, ...type }) => ({
49
+ name,
50
+ description,
51
+ models: getModelPreferences(type),
52
+ modelSuggestions: modelSuggestions === undefined ? undefined : [...modelSuggestions],
53
+ thinkingLevel,
54
+ color,
55
+ }),
56
+ ),
54
57
  ),
55
58
  ),
56
59
  make(
57
60
  "agent_spawn",
58
61
  "Spawn a named child. The lexical parent, NOT the caller, supplies a context snapshot. /root is the main thread; independent roots have no inherited context. Foreground waits by default; wait:false runs detached. For parallel work, spawn every independent sibling with wait:false before calling agent_wait; child agents with delegation tools should do the same. Existing paths are retained and can be resumed with agent_steer. Use agent_types to discover current types.",
59
- Type.Object({ path, type: text, task: text, wait: Type.Optional(Type.Boolean()) }),
62
+ Type.Object({
63
+ path: Type.String({
64
+ description:
65
+ "Task-based kebab-case path, not the agent type (e.g. /root/controller-security-research), or a task name relative to the caller",
66
+ }),
67
+ type: text,
68
+ task: text,
69
+ wait: Type.Optional(Type.Boolean()),
70
+ }),
60
71
  async (params, signal) => result(compact(await threads().spawn(params, signal))),
61
72
  ),
62
73
  make(
@@ -109,7 +120,7 @@ export function agentTools(
109
120
  ),
110
121
  make(
111
122
  "agent_output",
112
- "Read completed thread output in character pages. Paused threads deliberately have no final answer handback. All sessions can be viewed by the user with /agents thread PATH.",
123
+ "Read completed thread output in character pages. Paused threads deliberately have no final answer handback. All sessions can be viewed by the user with /agents tree; select a thread and press Enter to inspect it.",
113
124
  Type.Object({
114
125
  path,
115
126
  offset: Type.Optional(Type.Integer({ minimum: 0 })),
package/src/types.ts CHANGED
@@ -9,8 +9,10 @@ export interface AgentType {
9
9
  models?: string[];
10
10
  /** @deprecated Use ordered models instead. */
11
11
  model?: string;
12
+ /** Advisory display names. Not provider/model pins and never used for selection. */
13
+ modelSuggestions?: string[];
12
14
  thinkingLevel?: ThinkingLevel;
13
- /** Pi semantic token used as the agent name pill's background. */
15
+ /** Pi semantic token for the type pill background and task path foreground. */
14
16
  color?: string;
15
17
  tools?: { allow?: string[]; block?: string[] };
16
18
  systemPrompt: string;
@@ -32,6 +34,14 @@ export interface ThreadView {
32
34
  createdAt: number;
33
35
  updatedAt: number;
34
36
  sessionFile?: string;
37
+ /** Frozen active time. Renderer adds `Date.now() - startedAt` while a run is active. */
38
+ elapsedMs?: number;
39
+ /** Current run start. Live only; omitted from saved views so reloads do not count offline time. */
40
+ startedAt?: number;
41
+ /** Cumulative input tokens, including cache read/write. Live views include the in-progress message. */
42
+ inputTokens?: number;
43
+ /** Cumulative output tokens. Live views include the in-progress message. */
44
+ outputTokens?: number;
35
45
  }
36
46
  export type DriverEvent =
37
47
  | { kind: "activity" | "error"; text: string }
@@ -40,6 +50,14 @@ export type DriverEvent =
40
50
  text: string;
41
51
  sessionFile?: string;
42
52
  sessionLeafId?: string | null;
53
+ }
54
+ | {
55
+ kind: "usage";
56
+ /** Cumulative own-assistant tokens for this driver instance, excluding inherited history. */
57
+ inputTokens: number;
58
+ outputTokens: number;
59
+ /** Streaming message_update snapshot. Omit for authoritative message_end. */
60
+ partial?: boolean;
43
61
  };
44
62
  export interface AgentDriver {
45
63
  prompt(message: string): Promise<void>;
@@ -80,6 +98,10 @@ export interface SavedThreadView {
80
98
  createdAt: number;
81
99
  sessionFile?: string;
82
100
  sessionLeafId?: string | null;
101
+ /** Frozen cumulative active time. `startedAt` is intentionally not persisted. */
102
+ elapsedMs?: number;
103
+ inputTokens?: number;
104
+ outputTokens?: number;
83
105
  }
84
106
  export interface SavedThread {
85
107
  view: SavedThreadView;
@@ -105,6 +127,7 @@ export interface ThreadService {
105
127
  export type DriverFactory = (options: DriverOptions) => Promise<AgentDriver>;
106
128
  export type ThreadEvent =
107
129
  | { kind: "change"; thread: ThreadView }
130
+ | { kind: "metrics"; thread: ThreadView }
108
131
  | { kind: "update"; thread: ThreadView; message: string; recipient: string }
109
132
  | { kind: "settled"; thread: ThreadView; recipient: string };
110
133
  export interface ManagerOptions {