@aoshizuku/pi-subagent 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +173 -2
- package/agents/explore.md +20 -0
- package/agents/general.md +17 -0
- package/package.json +55 -5
- package/src/batcher.ts +77 -0
- package/src/child.ts +212 -0
- package/src/cleanup.ts +40 -0
- package/src/config.ts +181 -0
- package/src/detail.ts +408 -0
- package/src/focus.ts +240 -0
- package/src/hud-state.ts +183 -0
- package/src/index.ts +1013 -0
- package/src/list.ts +223 -0
- package/src/manager.ts +588 -0
- package/src/models.ts +80 -0
- package/src/observer.ts +275 -0
- package/src/prompts.ts +103 -0
- package/src/render.ts +592 -0
- package/src/result.ts +226 -0
- package/src/run.ts +204 -0
- package/src/settings.ts +140 -0
- package/src/shizuku-settings.ts +92 -0
- package/src/stop-confirm.ts +47 -0
- package/src/test-helpers.ts +194 -0
- package/src/tool-line.ts +85 -0
- package/src/types.ts +257 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,1013 @@
|
|
|
1
|
+
// pi-subagent: delegate a bounded task to a fresh in-process pi session with its own context window.
|
|
2
|
+
// Phase 1: foreground `agent`, /agents types, /agents reload. Phase 2: background runs and notifications,
|
|
3
|
+
// agent_send / agent_stop, persistence and restore, cleanup, the extension allowlist, the HUD rows (drawn by
|
|
4
|
+
// pi-hud), keyboard focus, the detail overlay and the /agents list (docs/08 §3).
|
|
5
|
+
|
|
6
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
|
|
10
|
+
import { StringEnum } from "@earendil-works/pi-ai";
|
|
11
|
+
import {
|
|
12
|
+
type AgentToolResult,
|
|
13
|
+
type AgentToolUpdateCallback,
|
|
14
|
+
type BoundaryResult,
|
|
15
|
+
type BoundaryState,
|
|
16
|
+
type CustomMessageEntryDraft,
|
|
17
|
+
type ExtensionAPI,
|
|
18
|
+
type ExtensionContext,
|
|
19
|
+
getAgentDir,
|
|
20
|
+
type ModelRegistry,
|
|
21
|
+
} from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
23
|
+
import { Type } from "typebox";
|
|
24
|
+
|
|
25
|
+
import { DEFAULT_WINDOW_MS, NotificationBatcher } from "./batcher.js";
|
|
26
|
+
import { createChildSessionFactory } from "./child.js";
|
|
27
|
+
import { cleanupOldSessions, DAY_MS } from "./cleanup.js";
|
|
28
|
+
import { CONFIG_FILE_NAME, isThinkingLevel, loadConfig, type SubagentConfig, THINKING_LEVELS, type ThinkingLevel } from "./config.js";
|
|
29
|
+
import { setSetting, settingsItems } from "./settings.js";
|
|
30
|
+
import { exposeSettings } from "./shizuku-settings.js";
|
|
31
|
+
import { AgentDetailView, type DetailSource, isStoppable, OVERLAY_OPTIONS } from "./detail.js";
|
|
32
|
+
import { FocusController } from "./focus.js";
|
|
33
|
+
import {
|
|
34
|
+
buildHudState,
|
|
35
|
+
EMPTY_STATE,
|
|
36
|
+
focusOrder,
|
|
37
|
+
HUD_CHANNEL,
|
|
38
|
+
HUD_REQUEST_CHANNEL,
|
|
39
|
+
type HudState,
|
|
40
|
+
nextExpiry,
|
|
41
|
+
OPEN_CHANNEL,
|
|
42
|
+
STATE_CHANNEL,
|
|
43
|
+
STATE_REQUEST_CHANNEL,
|
|
44
|
+
} from "./hud-state.js";
|
|
45
|
+
import { AgentListView, describeAgents } from "./list.js";
|
|
46
|
+
import { type AgentEntry, AgentManager, type AgentRecord, ENTRY_TYPE, isActive, isTerminal, STOP_WAIT_MS, toEntry } from "./manager.js";
|
|
47
|
+
import { formatModel, type ModelCatalog, type ModelRef, resolveModel, resolveThinking } from "./models.js";
|
|
48
|
+
import { contextPercent, type ProgressSnapshot } from "./observer.js";
|
|
49
|
+
import {
|
|
50
|
+
AGENT_SEND_DESCRIPTION,
|
|
51
|
+
AGENT_SEND_GUIDELINE,
|
|
52
|
+
AGENT_STOP_DESCRIPTION,
|
|
53
|
+
AGENT_STOP_GUIDELINE,
|
|
54
|
+
agentGuidelines,
|
|
55
|
+
PARAM_DESCRIPTIONS,
|
|
56
|
+
PROMPT_SNIPPET,
|
|
57
|
+
toolDescription,
|
|
58
|
+
} from "./prompts.js";
|
|
59
|
+
import {
|
|
60
|
+
agentCardRenderers,
|
|
61
|
+
type AgentToolDetails,
|
|
62
|
+
CardLink,
|
|
63
|
+
callLabel,
|
|
64
|
+
NOTIFICATION_PREVIEW_LINES,
|
|
65
|
+
type NotificationDetails,
|
|
66
|
+
notificationLines,
|
|
67
|
+
renderStopCall,
|
|
68
|
+
renderStopResult,
|
|
69
|
+
} from "./render.js";
|
|
70
|
+
import {
|
|
71
|
+
durationOf,
|
|
72
|
+
formatDuration,
|
|
73
|
+
formatNotification,
|
|
74
|
+
formatResult,
|
|
75
|
+
formatStarted,
|
|
76
|
+
isContinuable,
|
|
77
|
+
type NotificationItem,
|
|
78
|
+
writeResultFile,
|
|
79
|
+
} from "./result.js";
|
|
80
|
+
import { type ChildSessionFactory, type ChildSpec, SESSION_ENDED } from "./run.js";
|
|
81
|
+
import { type AgentType, builtinAgentsDir, effectiveTools, type LoadedTypes, loadAgentTypes, lookupType } from "./types.js";
|
|
82
|
+
|
|
83
|
+
export const TOOL_NAME = "agent";
|
|
84
|
+
export const SEND_TOOL_NAME = "agent_send";
|
|
85
|
+
export const STOP_TOOL_NAME = "agent_stop";
|
|
86
|
+
export const NOTIFICATION_TYPE = "subagent-notification";
|
|
87
|
+
/** A zero-height widget below the editor; its factory hands us the TUI for the editor-focus check. */
|
|
88
|
+
const FOCUS_WIDGET_KEY = "pi-subagent-focus";
|
|
89
|
+
const PROGRESS_THROTTLE_MS = 100;
|
|
90
|
+
const HEARTBEAT_MS = 1000;
|
|
91
|
+
|
|
92
|
+
const agentSchema = Type.Object({
|
|
93
|
+
description: Type.String({ description: PARAM_DESCRIPTIONS.description }),
|
|
94
|
+
prompt: Type.String({ description: PARAM_DESCRIPTIONS.prompt }),
|
|
95
|
+
agent_type: Type.Optional(Type.String({ description: PARAM_DESCRIPTIONS.agent_type })),
|
|
96
|
+
model: Type.Optional(Type.String({ description: PARAM_DESCRIPTIONS.model })),
|
|
97
|
+
thinking: Type.Optional(StringEnum(THINKING_LEVELS, { description: PARAM_DESCRIPTIONS.thinking })),
|
|
98
|
+
background: Type.Optional(Type.Boolean({ description: PARAM_DESCRIPTIONS.background })),
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const sendSchema = Type.Object({
|
|
102
|
+
agent_id: Type.String({ description: PARAM_DESCRIPTIONS.agent_id }),
|
|
103
|
+
message: Type.String({ description: PARAM_DESCRIPTIONS.message }),
|
|
104
|
+
background: Type.Optional(Type.Boolean({ description: PARAM_DESCRIPTIONS.send_background })),
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
const stopSchema = Type.Object({
|
|
108
|
+
agent_id: Type.String({ description: PARAM_DESCRIPTIONS.agent_id }),
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
export interface SubagentDeps {
|
|
112
|
+
/** Child session factory for a session; tests substitute a fake. Default: real in-process pi sessions. */
|
|
113
|
+
createFactory?: (ctx: ExtensionContext, agentDir: string, childExtensions: () => readonly string[]) => ChildSessionFactory;
|
|
114
|
+
/** Default: getAgentDir(). */
|
|
115
|
+
agentDir?: () => string;
|
|
116
|
+
/** Default: the plugin's agents/ directory. */
|
|
117
|
+
builtinDir?: string;
|
|
118
|
+
/** Notification merge window (default 3 s). */
|
|
119
|
+
windowMs?: number;
|
|
120
|
+
/** How long agent_stop waits for a stopped run (default 5 s). */
|
|
121
|
+
stopWaitMs?: number;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
interface FocusableTui {
|
|
125
|
+
getFocusedComponent(): unknown;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
interface SessionState {
|
|
129
|
+
ctx: ExtensionContext;
|
|
130
|
+
config: SubagentConfig;
|
|
131
|
+
configError?: string;
|
|
132
|
+
configWarnings: string[];
|
|
133
|
+
loaded: LoadedTypes;
|
|
134
|
+
manager: AgentManager;
|
|
135
|
+
batcher: NotificationBatcher<AgentRecord>;
|
|
136
|
+
/** Child session files; undefined for an in-memory parent (children are in-memory too). */
|
|
137
|
+
childDir?: string;
|
|
138
|
+
resultDir: string;
|
|
139
|
+
parentSessionFile?: string;
|
|
140
|
+
/** print / json: pi exits after this run, so background runs are unavailable (docs/02 §12). */
|
|
141
|
+
oneShot: boolean;
|
|
142
|
+
/** Set at session_shutdown; nothing touches pi or ctx afterwards. */
|
|
143
|
+
closed: boolean;
|
|
144
|
+
focus?: FocusController;
|
|
145
|
+
/** pi-hud draws the agent rows (subagent:hud). */
|
|
146
|
+
hudRendering: boolean;
|
|
147
|
+
/** The /agents list is in the editor slot (docs/07 §7). */
|
|
148
|
+
listOpen: boolean;
|
|
149
|
+
/** The detail overlay is showing, on its own or on top of the list (docs/07 §5). */
|
|
150
|
+
detailOpen: boolean;
|
|
151
|
+
/** The TUI from the focus widget's factory (a proxy that follows renderer switches). */
|
|
152
|
+
tui?: object;
|
|
153
|
+
lastState?: string;
|
|
154
|
+
expiryTimer?: ReturnType<typeof setTimeout>;
|
|
155
|
+
disposers: Array<() => void>;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
interface LaunchOptions {
|
|
159
|
+
background: boolean;
|
|
160
|
+
verb: "Started" | "Continuing";
|
|
161
|
+
signal?: AbortSignal;
|
|
162
|
+
onUpdate?: AgentToolUpdateCallback<AgentToolDetails>;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
type AgentParams = { description: string; prompt: string; agent_type?: string; model?: string; thinking?: ThinkingLevel; background?: boolean };
|
|
166
|
+
|
|
167
|
+
export function createSubagentExtension(deps: SubagentDeps = {}): (pi: ExtensionAPI) => void {
|
|
168
|
+
const builtinDir = deps.builtinDir ?? builtinAgentsDir();
|
|
169
|
+
const agentDirOf = deps.agentDir ?? getAgentDir;
|
|
170
|
+
const stopWaitMs = deps.stopWaitMs ?? STOP_WAIT_MS;
|
|
171
|
+
|
|
172
|
+
return function piSubagent(pi: ExtensionAPI): void {
|
|
173
|
+
let state: SessionState | undefined;
|
|
174
|
+
let registeredKey: string | undefined;
|
|
175
|
+
// Background cards look up their agent in the current session's manager (docs/07 §1.4).
|
|
176
|
+
const cardLink = new CardLink();
|
|
177
|
+
const cardRenderers = agentCardRenderers(cardLink);
|
|
178
|
+
|
|
179
|
+
const registerAgentTool = (description: string, guidelines: string[]): void => {
|
|
180
|
+
const key = `${description}\n\n${guidelines.join("\n")}`;
|
|
181
|
+
if (key === registeredKey) return;
|
|
182
|
+
registeredKey = key;
|
|
183
|
+
pi.registerTool<typeof agentSchema, AgentToolDetails>({
|
|
184
|
+
name: TOOL_NAME,
|
|
185
|
+
label: "Agent",
|
|
186
|
+
description,
|
|
187
|
+
promptSnippet: PROMPT_SNIPPET,
|
|
188
|
+
promptGuidelines: guidelines,
|
|
189
|
+
parameters: agentSchema,
|
|
190
|
+
// No executionMode: one "sequential" tool would serialize the whole batch (agent-loop.ts:525-533).
|
|
191
|
+
renderShell: "self",
|
|
192
|
+
execute: (_toolCallId, params, signal, onUpdate, ctx) =>
|
|
193
|
+
runAgentTool(
|
|
194
|
+
requireState(state),
|
|
195
|
+
pi,
|
|
196
|
+
// StringEnum's static type does not narrow across typebox copies; the schema already validated it.
|
|
197
|
+
{ ...params, thinking: isThinkingLevel(params.thinking) ? params.thinking : undefined },
|
|
198
|
+
signal,
|
|
199
|
+
onUpdate,
|
|
200
|
+
ctx,
|
|
201
|
+
),
|
|
202
|
+
renderCall: cardRenderers.renderCall,
|
|
203
|
+
renderResult: cardRenderers.renderResult,
|
|
204
|
+
});
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const registerDescription = (current: Pick<SessionState, "loaded" | "oneShot">): void => {
|
|
208
|
+
const options = { background: !current.oneShot };
|
|
209
|
+
registerAgentTool(toolDescription(current.loaded.types.values(), options), agentGuidelines(options));
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
const loadTypes = (ctx: ExtensionContext, config: SubagentConfig): LoadedTypes => {
|
|
213
|
+
const agentDir = agentDirOf();
|
|
214
|
+
return loadAgentTypes(
|
|
215
|
+
{
|
|
216
|
+
builtinDir,
|
|
217
|
+
userDir: join(agentDir, "agents"),
|
|
218
|
+
projectDir: join(ctx.cwd, ".pi", "agents"),
|
|
219
|
+
projectTrusted: ctx.isProjectTrusted(),
|
|
220
|
+
},
|
|
221
|
+
config,
|
|
222
|
+
);
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const loadSettings = (ctx: ExtensionContext): Pick<SessionState, "config" | "configError" | "configWarnings" | "loaded"> => {
|
|
226
|
+
const loadedConfig = loadConfig(join(agentDirOf(), CONFIG_FILE_NAME));
|
|
227
|
+
return {
|
|
228
|
+
config: loadedConfig.config,
|
|
229
|
+
configError: loadedConfig.error,
|
|
230
|
+
configWarnings: loadedConfig.warnings,
|
|
231
|
+
loaded: loadTypes(ctx, loadedConfig.config),
|
|
232
|
+
};
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
// Registered at load with the built-in types so the tools exist before session_start; the description
|
|
236
|
+
// is rebuilt once per session_start, never mid-session (docs/04 §6).
|
|
237
|
+
registerDescription({ loaded: loadAgentTypes({ builtinDir, userDir: "", projectDir: "", projectTrusted: false }), oneShot: false });
|
|
238
|
+
|
|
239
|
+
pi.registerTool<typeof sendSchema, AgentToolDetails>({
|
|
240
|
+
name: SEND_TOOL_NAME,
|
|
241
|
+
label: "Agent Send",
|
|
242
|
+
description: AGENT_SEND_DESCRIPTION,
|
|
243
|
+
promptSnippet: "Send a follow-up to a subagent by its agent id; a finished one resumes with its full context",
|
|
244
|
+
promptGuidelines: [AGENT_SEND_GUIDELINE],
|
|
245
|
+
parameters: sendSchema,
|
|
246
|
+
renderShell: "self",
|
|
247
|
+
execute: (_toolCallId, params, signal, onUpdate, ctx) => runSendTool(requireState(state), pi, params, signal, onUpdate, ctx),
|
|
248
|
+
renderCall: cardRenderers.renderCall,
|
|
249
|
+
renderResult: cardRenderers.renderResult,
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
pi.registerTool({
|
|
253
|
+
name: STOP_TOOL_NAME,
|
|
254
|
+
label: "Agent Stop",
|
|
255
|
+
description: AGENT_STOP_DESCRIPTION,
|
|
256
|
+
promptSnippet: "Stop a running or queued subagent by its agent id",
|
|
257
|
+
promptGuidelines: [AGENT_STOP_GUIDELINE],
|
|
258
|
+
parameters: stopSchema,
|
|
259
|
+
execute: (_toolCallId, params) => runStopTool(requireState(state), params.agent_id, stopWaitMs),
|
|
260
|
+
renderShell: "self",
|
|
261
|
+
renderCall: renderStopCall,
|
|
262
|
+
renderResult: renderStopResult,
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
pi.registerMessageRenderer<NotificationDetails>(NOTIFICATION_TYPE, (message, options, theme) => {
|
|
266
|
+
// Markers sit in the gutter's column 0 (pi-shizuku README.md), not at pi's outputPad.
|
|
267
|
+
return new Text(notificationLines(message.details, options.expanded, theme).join("\n"), 0, 0);
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
// Busy parent: drain everything that finished during this turn into one message (docs/06 §5.3).
|
|
271
|
+
pi.on("turn_end", (event) => drainAtBoundary(state, event));
|
|
272
|
+
pi.on("agent_before_settle", (event) => drainAtBoundary(state, event));
|
|
273
|
+
// Agents that finished after the last boundary. An aborted run is not restarted: the notification is
|
|
274
|
+
// recorded and the model sees it with the next prompt.
|
|
275
|
+
pi.on("agent_settled", (event) => drainSettled(pi, state, event.aborted));
|
|
276
|
+
|
|
277
|
+
pi.on("session_start", (_event, ctx) => {
|
|
278
|
+
const settings = loadSettings(ctx);
|
|
279
|
+
const sessionManager = ctx.sessionManager;
|
|
280
|
+
const parentId = sessionManager.getSessionId();
|
|
281
|
+
const parentSessionFile = sessionManager.getSessionFile();
|
|
282
|
+
const subagentsRoot = parentSessionFile ? join(sessionManager.getSessionDir(), "subagents") : undefined;
|
|
283
|
+
const childDir = subagentsRoot ? join(subagentsRoot, parentId) : undefined;
|
|
284
|
+
const tmpRoot = join(tmpdir(), "pi-subagent");
|
|
285
|
+
const resultDir = childDir ?? join(tmpRoot, parentId);
|
|
286
|
+
const childExtensions = (): readonly string[] => current.config.childExtensions;
|
|
287
|
+
const factory =
|
|
288
|
+
deps.createFactory?.(ctx, agentDirOf(), childExtensions) ??
|
|
289
|
+
createChildSessionFactory({ parentRegistry: ctx.modelRegistry, agentDir: agentDirOf(), childExtensions });
|
|
290
|
+
|
|
291
|
+
const current: SessionState = {
|
|
292
|
+
...settings,
|
|
293
|
+
ctx,
|
|
294
|
+
childDir,
|
|
295
|
+
resultDir,
|
|
296
|
+
parentSessionFile,
|
|
297
|
+
oneShot: ctx.mode === "print" || ctx.mode === "json",
|
|
298
|
+
closed: false,
|
|
299
|
+
hudRendering: false,
|
|
300
|
+
listOpen: false,
|
|
301
|
+
detailOpen: false,
|
|
302
|
+
disposers: [],
|
|
303
|
+
manager: new AgentManager({
|
|
304
|
+
factory,
|
|
305
|
+
maxConcurrent: () => current.config.maxConcurrent,
|
|
306
|
+
firstId: nextAgentNumber(resultDir),
|
|
307
|
+
persist: (record) => {
|
|
308
|
+
if (!current.closed) pi.appendEntry(ENTRY_TYPE, toEntry(record));
|
|
309
|
+
},
|
|
310
|
+
onFinished: (record) => finalize(current, record),
|
|
311
|
+
}),
|
|
312
|
+
batcher: new NotificationBatcher<AgentRecord>({
|
|
313
|
+
isIdle: () => ctx.isIdle(),
|
|
314
|
+
hasRunning: () => current.manager.list().some((record) => record.background && isActive(record.status)),
|
|
315
|
+
deliverIdle: (batch) => deliver(pi, current, batch, true),
|
|
316
|
+
windowMs: deps.windowMs ?? DEFAULT_WINDOW_MS,
|
|
317
|
+
}),
|
|
318
|
+
};
|
|
319
|
+
state = current;
|
|
320
|
+
|
|
321
|
+
// Restore (docs/06 §8): records from this session's entries; the ones a dead process left running are closed.
|
|
322
|
+
const entries: AgentEntry[] = [];
|
|
323
|
+
for (const entry of sessionManager.getEntries()) {
|
|
324
|
+
if (entry.type === "custom" && entry.customType === ENTRY_TYPE) entries.push(entry.data as AgentEntry);
|
|
325
|
+
}
|
|
326
|
+
for (const record of current.manager.restore(entries)) pi.appendEntry(ENTRY_TYPE, toEntry(record));
|
|
327
|
+
// After restore, so cards drawn before session_start (resume, /reload) redraw to their record's state.
|
|
328
|
+
cardLink.attach(current.manager);
|
|
329
|
+
|
|
330
|
+
registerDescription(current);
|
|
331
|
+
notifyProblems(ctx, current);
|
|
332
|
+
|
|
333
|
+
const maxAge = current.config.retentionDays * DAY_MS;
|
|
334
|
+
if (subagentsRoot) void cleanupOldSessions(subagentsRoot, parentId, maxAge);
|
|
335
|
+
void cleanupOldSessions(tmpRoot, parentId, maxAge);
|
|
336
|
+
|
|
337
|
+
setupHud(pi, current);
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
pi.on("session_shutdown", async () => {
|
|
341
|
+
const current = state;
|
|
342
|
+
state = undefined;
|
|
343
|
+
if (!current) return;
|
|
344
|
+
current.closed = true;
|
|
345
|
+
// pi disposes an open list or detail with the session UI without settling its custom() promise, so
|
|
346
|
+
// the finally blocks in openList / openDetail may never run; this state is dead either way.
|
|
347
|
+
current.listOpen = false;
|
|
348
|
+
current.detailOpen = false;
|
|
349
|
+
current.batcher.dispose();
|
|
350
|
+
current.focus?.dispose();
|
|
351
|
+
if (current.expiryTimer) clearTimeout(current.expiryTimer);
|
|
352
|
+
for (const dispose of current.disposers.splice(0)) {
|
|
353
|
+
try {
|
|
354
|
+
dispose();
|
|
355
|
+
} catch {
|
|
356
|
+
// Best effort while pi tears the session down.
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
pi.events.emit(STATE_CHANNEL, EMPTY_STATE);
|
|
360
|
+
// The link stays attached through shutdown, so cards of agents it aborts redraw as stopped.
|
|
361
|
+
await current.manager.shutdown();
|
|
362
|
+
cardLink.detach(current.manager);
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
// The /shizuku panel (pi-shizuku-settings) edits the scalar fields of pi-subagent.json; a change goes
|
|
366
|
+
// into the running session's config at once. Type overrides stay with /agents reload.
|
|
367
|
+
exposeSettings(pi, {
|
|
368
|
+
id: "pi-subagent",
|
|
369
|
+
title: "pi-subagent",
|
|
370
|
+
description: "Delegate bounded tasks to fresh in-process sessions",
|
|
371
|
+
file: join(agentDirOf(), CONFIG_FILE_NAME),
|
|
372
|
+
items: () => settingsItems(state?.config ?? loadConfig(join(agentDirOf(), CONFIG_FILE_NAME)).config),
|
|
373
|
+
set: (id, value) =>
|
|
374
|
+
setSetting(join(agentDirOf(), CONFIG_FILE_NAME), id, value, (patch) => {
|
|
375
|
+
const current = state;
|
|
376
|
+
if (!current) return;
|
|
377
|
+
current.config = { ...current.config, ...patch };
|
|
378
|
+
// A higher limit can start queued agents now.
|
|
379
|
+
if (patch.maxConcurrent !== undefined) current.manager.pump();
|
|
380
|
+
}),
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
pi.registerCommand("agents", {
|
|
384
|
+
description: "Subagents: /agents lists this session's agents, /agents types lists types, /agents reload re-reads type files and config",
|
|
385
|
+
getArgumentCompletions: (prefix) =>
|
|
386
|
+
["types", "reload"].filter((name) => name.startsWith(prefix.trim())).map((name) => ({ value: name, label: name })),
|
|
387
|
+
handler: async (args, ctx) => {
|
|
388
|
+
const current = state;
|
|
389
|
+
if (!current) return;
|
|
390
|
+
const command = args.trim().toLowerCase();
|
|
391
|
+
if (command === "") {
|
|
392
|
+
if (ctx.mode !== "tui" || !ctx.hasUI) {
|
|
393
|
+
ctx.ui.notify(describeAgents(current.manager.list()), "info");
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
await openList(current);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
if (command === "types") {
|
|
400
|
+
ctx.ui.notify(describeTypes(current), "info");
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (command === "reload") {
|
|
404
|
+
Object.assign(current, loadSettings(ctx));
|
|
405
|
+
const before = registeredKey;
|
|
406
|
+
registerDescription(current);
|
|
407
|
+
current.manager.pump();
|
|
408
|
+
const changed = registeredKey !== before;
|
|
409
|
+
ctx.ui.notify(
|
|
410
|
+
`Reloaded ${current.loaded.types.size} agent types.${
|
|
411
|
+
changed
|
|
412
|
+
? " The agent tool description changed; the next request will not hit the prompt cache."
|
|
413
|
+
: " The agent tool description is unchanged."
|
|
414
|
+
}`,
|
|
415
|
+
"info",
|
|
416
|
+
);
|
|
417
|
+
notifyProblems(ctx, current);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
ctx.ui.notify("Usage: /agents | /agents types | /agents reload", "info");
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export default createSubagentExtension();
|
|
427
|
+
|
|
428
|
+
function requireState(state: SessionState | undefined): SessionState {
|
|
429
|
+
if (!state) throw new Error("pi-subagent is not ready: no active session");
|
|
430
|
+
return state;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// ---------------------------------------------------------------------------------------------------------
|
|
434
|
+
// Tools
|
|
435
|
+
// ---------------------------------------------------------------------------------------------------------
|
|
436
|
+
|
|
437
|
+
async function runAgentTool(
|
|
438
|
+
state: SessionState,
|
|
439
|
+
pi: ExtensionAPI,
|
|
440
|
+
params: AgentParams,
|
|
441
|
+
signal: AbortSignal | undefined,
|
|
442
|
+
onUpdate: AgentToolUpdateCallback<AgentToolDetails> | undefined,
|
|
443
|
+
ctx: ExtensionContext,
|
|
444
|
+
): Promise<AgentToolResult<AgentToolDetails>> {
|
|
445
|
+
// 1. Type and model; errors are thrown so the model sees them and corrects the call.
|
|
446
|
+
const type = lookupType(state.loaded.types, params.agent_type);
|
|
447
|
+
if (!type) {
|
|
448
|
+
const known = [...state.loaded.types.keys()].join(", ");
|
|
449
|
+
throw new Error(
|
|
450
|
+
`Unknown agent type "${params.agent_type}". Available types: ${known}. Type files added after the session started are loaded with /agents reload.`,
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
if (params.background === true && state.oneShot) throw oneShotError();
|
|
454
|
+
// A type's background default does not apply in one-shot modes; the run falls back to the foreground.
|
|
455
|
+
const background = params.background ?? (type.background && !state.oneShot);
|
|
456
|
+
const parentModel = parentModelOf(ctx);
|
|
457
|
+
const resolution = resolveModel({ param: params.model, configured: type.model, parent: parentModel }, catalogOf(ctx.modelRegistry));
|
|
458
|
+
const thinking = resolveThinking(params.thinking, type.thinking, ctx.thinkingLevel ?? pi.getThinkingLevel());
|
|
459
|
+
|
|
460
|
+
// 2. Snapshot the parent now, not when the agent leaves the queue (docs/02 §2).
|
|
461
|
+
const description = callLabel(params);
|
|
462
|
+
const record = state.manager.create({
|
|
463
|
+
type: type.name,
|
|
464
|
+
description,
|
|
465
|
+
prompt: params.prompt,
|
|
466
|
+
model: formatModel(resolution.model),
|
|
467
|
+
background,
|
|
468
|
+
maxTurns: type.maxTurns,
|
|
469
|
+
});
|
|
470
|
+
record.notes.push(...resolution.notes);
|
|
471
|
+
const spec = childSpec(state, pi, ctx, record, type, resolution.model, thinking);
|
|
472
|
+
return launch(state, record, type, spec, params.prompt, { background, verb: "Started", signal, onUpdate });
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
async function runSendTool(
|
|
476
|
+
state: SessionState,
|
|
477
|
+
pi: ExtensionAPI,
|
|
478
|
+
params: { agent_id: string; message: string; background?: boolean },
|
|
479
|
+
signal: AbortSignal | undefined,
|
|
480
|
+
onUpdate: AgentToolUpdateCallback<AgentToolDetails> | undefined,
|
|
481
|
+
ctx: ExtensionContext,
|
|
482
|
+
): Promise<AgentToolResult<AgentToolDetails>> {
|
|
483
|
+
const agentId = params.agent_id.trim();
|
|
484
|
+
const record = state.manager.get(agentId);
|
|
485
|
+
if (!record) throw unknownAgent(state, agentId);
|
|
486
|
+
const message = params.message;
|
|
487
|
+
|
|
488
|
+
if (!isTerminal(record.status)) {
|
|
489
|
+
const sent = await state.manager.send(agentId, message);
|
|
490
|
+
if (sent.kind !== "finished") {
|
|
491
|
+
return {
|
|
492
|
+
content: [{ type: "text", text: `Message queued for ${agentId}; it will be part of the report you receive when it finishes.` }],
|
|
493
|
+
details: undefined as unknown as AgentToolDetails,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// Finished: reopen the transcript and run again (docs/06 §6).
|
|
499
|
+
if (record.contextLimited) {
|
|
500
|
+
const fill = record.context ? ` (${contextPercent(record.context)}% used)` : "";
|
|
501
|
+
throw new Error(`${agentId} cannot be continued: its context window is nearly full${fill}. Start a new agent.`);
|
|
502
|
+
}
|
|
503
|
+
const transcript = existingFile(record.sessionFile);
|
|
504
|
+
if (!transcript) throw new Error(`${agentId} cannot be continued: its transcript is no longer available. Start a new agent.`);
|
|
505
|
+
if (params.background === true && state.oneShot) throw oneShotError();
|
|
506
|
+
const background = params.background ?? false;
|
|
507
|
+
const type = lookupType(state.loaded.types, record.type);
|
|
508
|
+
if (!type) throw new Error(`${agentId} cannot be continued: its agent type "${record.type}" is no longer loaded. Start a new agent.`);
|
|
509
|
+
// Type and model resolve as they would now; a changed type file applies.
|
|
510
|
+
const resolution = resolveModel({ configured: type.model, parent: parentModelOf(ctx) }, catalogOf(ctx.modelRegistry));
|
|
511
|
+
const thinking = resolveThinking(undefined, type.thinking, ctx.thinkingLevel ?? pi.getThinkingLevel());
|
|
512
|
+
state.manager.reopen(agentId, { prompt: message, model: formatModel(resolution.model), background, maxTurns: type.maxTurns });
|
|
513
|
+
record.notes.push(...resolution.notes);
|
|
514
|
+
const spec = { ...childSpec(state, pi, ctx, record, type, resolution.model, thinking), resumeFile: transcript };
|
|
515
|
+
return launch(state, record, type, spec, message, { background, verb: "Continuing", signal, onUpdate });
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
async function runStopTool(state: SessionState, rawId: string, waitMs: number): Promise<AgentToolResult<undefined>> {
|
|
519
|
+
const agentId = rawId.trim();
|
|
520
|
+
const before = state.manager.get(agentId);
|
|
521
|
+
if (!before) throw unknownAgent(state, agentId);
|
|
522
|
+
const wasActive = isActive(before.status);
|
|
523
|
+
const record = (await state.manager.stop(agentId, "parent", waitMs)) ?? before;
|
|
524
|
+
const formatted = formatResult(record, {
|
|
525
|
+
maxChars: state.config.resultMaxChars,
|
|
526
|
+
resultFile: record.resultFile,
|
|
527
|
+
transcript: existingFile(record.sessionFile),
|
|
528
|
+
});
|
|
529
|
+
const first = wasActive
|
|
530
|
+
? `Stopped subagent ${agentId} (${record.description}) after ${formatDuration(durationOf(record))}.`
|
|
531
|
+
: `${agentId} had already finished: ${record.status}.`;
|
|
532
|
+
return { content: [{ type: "text", text: `${first}\n${formatted.text}` }], details: undefined };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** Queue and run; the foreground waits with progress, the background returns at once (docs/06 §4). */
|
|
536
|
+
async function launch(
|
|
537
|
+
state: SessionState,
|
|
538
|
+
record: AgentRecord,
|
|
539
|
+
type: AgentType,
|
|
540
|
+
spec: ChildSpec,
|
|
541
|
+
task: string,
|
|
542
|
+
options: LaunchOptions,
|
|
543
|
+
): Promise<AgentToolResult<AgentToolDetails>> {
|
|
544
|
+
if (options.background) {
|
|
545
|
+
// Not tied to the tool call's signal: Esc on the parent does not stop background agents (docs/06 §4.2).
|
|
546
|
+
void state.manager.execute(record, { spec, task }).catch(() => {});
|
|
547
|
+
const position = state.manager.position(record.agentId);
|
|
548
|
+
const details = detailsOf(record, type, { truncated: false, queuePosition: position || undefined });
|
|
549
|
+
// execute() took a slot synchronously unless it queued; the status flips to running a tick later.
|
|
550
|
+
if (position === 0 && details.status === "queued") details.status = "running";
|
|
551
|
+
return {
|
|
552
|
+
content: [{ type: "text", text: formatStarted(record, position, options.verb) }],
|
|
553
|
+
details: { ...details, background: true, run: record.runs },
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const progress = progressReporter(record, type, options.onUpdate, () => state.manager.position(record.agentId));
|
|
558
|
+
try {
|
|
559
|
+
await state.manager.execute(record, {
|
|
560
|
+
spec,
|
|
561
|
+
task,
|
|
562
|
+
signal: options.signal,
|
|
563
|
+
onQueued: () => progress.emit(),
|
|
564
|
+
onStart: () => progress.start(),
|
|
565
|
+
onProgress: (snapshot) => progress.schedule(snapshot),
|
|
566
|
+
});
|
|
567
|
+
} finally {
|
|
568
|
+
progress.stop();
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// The result file was written when the run finished (finalize).
|
|
572
|
+
const transcript = existingFile(record.sessionFile);
|
|
573
|
+
const formatted = formatResult(record, { maxChars: state.config.resultMaxChars, resultFile: record.resultFile, transcript });
|
|
574
|
+
return {
|
|
575
|
+
content: [{ type: "text", text: formatted.text }],
|
|
576
|
+
details: detailsOf(record, type, { truncated: formatted.truncated, sessionFile: transcript }),
|
|
577
|
+
// Failed, aborted and out-of-turns runs are errors the model must notice; details stay for the card.
|
|
578
|
+
isError: record.status !== "completed",
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function childSpec(
|
|
583
|
+
state: SessionState,
|
|
584
|
+
pi: ExtensionAPI,
|
|
585
|
+
ctx: ExtensionContext,
|
|
586
|
+
record: AgentRecord,
|
|
587
|
+
type: AgentType,
|
|
588
|
+
model: ModelRef | undefined,
|
|
589
|
+
thinking: ThinkingLevel | undefined,
|
|
590
|
+
): ChildSpec {
|
|
591
|
+
return {
|
|
592
|
+
agentId: record.agentId,
|
|
593
|
+
description: record.description,
|
|
594
|
+
type: { ...type, tools: effectiveTools(type, pi.getActiveTools()) },
|
|
595
|
+
cwd: ctx.cwd,
|
|
596
|
+
model,
|
|
597
|
+
thinking,
|
|
598
|
+
sessionDir: state.childDir,
|
|
599
|
+
parentSessionFile: state.parentSessionFile,
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function oneShotError(): Error {
|
|
604
|
+
return new Error(
|
|
605
|
+
"background is not available in print or json mode: pi exits when this run ends, so the notification could never arrive. Run the agent in the foreground.",
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function unknownAgent(state: SessionState, agentId: string): Error {
|
|
610
|
+
const known = state.manager.list().map((record) => record.agentId);
|
|
611
|
+
return new Error(`Unknown subagent ${agentId}.${known.length > 0 ? ` Known agents: ${known.join(", ")}.` : " No subagents have been started in this session."}`);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function parentModelOf(ctx: ExtensionContext): ModelRef | undefined {
|
|
615
|
+
return ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
function existingFile(path: string | undefined): string | undefined {
|
|
619
|
+
return path && existsSync(path) ? path : undefined;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
// ---------------------------------------------------------------------------------------------------------
|
|
624
|
+
// Finishing and notifications (docs/06 §5)
|
|
625
|
+
// ---------------------------------------------------------------------------------------------------------
|
|
626
|
+
|
|
627
|
+
/** A run reached its terminal state: write the result file, then notify if this ending calls for it. */
|
|
628
|
+
function finalize(state: SessionState, record: AgentRecord): void {
|
|
629
|
+
if (state.closed) {
|
|
630
|
+
record.notified = true;
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
try {
|
|
634
|
+
record.resultFile = writeResultFile(state.resultDir, record.agentId, record.text ?? "");
|
|
635
|
+
} catch (error) {
|
|
636
|
+
record.notes.push(`could not write the result file: ${(error as Error).message}`);
|
|
637
|
+
}
|
|
638
|
+
if (shouldNotify(record)) state.batcher.enqueue(record);
|
|
639
|
+
else record.notified = true;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** docs/06 §5.2: background runs only; not when the model stopped it itself or the session is ending. */
|
|
643
|
+
export function shouldNotify(record: Pick<AgentRecord, "background" | "status" | "stoppedBy" | "reason">): boolean {
|
|
644
|
+
if (!record.background) return false;
|
|
645
|
+
if (record.status === "aborted" && (record.stoppedBy === "parent" || record.reason === SESSION_ENDED)) return false;
|
|
646
|
+
return true;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function notificationMessage(state: SessionState, batch: readonly AgentRecord[]): {
|
|
650
|
+
customType: string;
|
|
651
|
+
content: string;
|
|
652
|
+
display: boolean;
|
|
653
|
+
details: NotificationDetails;
|
|
654
|
+
} {
|
|
655
|
+
const items: NotificationItem[] = batch.map((record) => ({ record, continuable: isContinuable(record, existingFile(record.sessionFile)) }));
|
|
656
|
+
return {
|
|
657
|
+
customType: NOTIFICATION_TYPE,
|
|
658
|
+
content: formatNotification(items, { perAgent: state.config.notifyMaxChars, batch: state.config.notifyBatchMaxChars }),
|
|
659
|
+
display: true,
|
|
660
|
+
details: {
|
|
661
|
+
agents: batch.map((record) => ({
|
|
662
|
+
agentId: record.agentId,
|
|
663
|
+
type: record.type,
|
|
664
|
+
description: record.description,
|
|
665
|
+
status: record.status,
|
|
666
|
+
reason: record.reason,
|
|
667
|
+
toolCalls: record.stats.toolCalls,
|
|
668
|
+
durationMs: durationOf(record),
|
|
669
|
+
resultFile: record.resultFile,
|
|
670
|
+
preview: (record.text ?? "").split(/\r?\n/).slice(0, NOTIFICATION_PREVIEW_LINES),
|
|
671
|
+
})),
|
|
672
|
+
},
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function deliver(pi: ExtensionAPI, state: SessionState, batch: AgentRecord[], triggerTurn: boolean): void {
|
|
677
|
+
if (state.closed || batch.length === 0) return;
|
|
678
|
+
for (const record of batch) record.notified = true;
|
|
679
|
+
pi.sendMessage(notificationMessage(state, batch), { triggerTurn, deliverAs: "steer" });
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
function drainAtBoundary(state: SessionState | undefined, event: BoundaryState): BoundaryResult | undefined {
|
|
683
|
+
if (!state || state.closed || event.outcome !== "completed" || state.batcher.size === 0) return undefined;
|
|
684
|
+
const batch = state.batcher.take();
|
|
685
|
+
for (const record of batch) record.notified = true;
|
|
686
|
+
const draft: CustomMessageEntryDraft = { type: "custom_message", ...notificationMessage(state, batch) };
|
|
687
|
+
return { entries: [...event.entries, draft], continue: true };
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function drainSettled(pi: ExtensionAPI, state: SessionState | undefined, aborted: boolean): void {
|
|
691
|
+
if (!state || state.closed || state.batcher.size === 0) return;
|
|
692
|
+
deliver(pi, state, state.batcher.take(), !aborted);
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// ---------------------------------------------------------------------------------------------------------
|
|
696
|
+
// HUD rows, keyboard focus, the /agents list (bottom slot) and the detail overlay (docs/07 §3-§7)
|
|
697
|
+
// ---------------------------------------------------------------------------------------------------------
|
|
698
|
+
|
|
699
|
+
function setupHud(pi: ExtensionAPI, state: SessionState): void {
|
|
700
|
+
const { ctx, manager } = state;
|
|
701
|
+
|
|
702
|
+
const emitState = (force = false): void => {
|
|
703
|
+
if (state.closed) return;
|
|
704
|
+
const now = Date.now();
|
|
705
|
+
const parent = parentModelOf(ctx);
|
|
706
|
+
const hud: HudState = buildHudState(manager.list(), {
|
|
707
|
+
now,
|
|
708
|
+
parentModel: parent ? formatModel(parent) : undefined,
|
|
709
|
+
focusId: state.focus?.active ? state.focus.selectedId : undefined,
|
|
710
|
+
focusArmed: state.focus?.armed === true,
|
|
711
|
+
});
|
|
712
|
+
const json = JSON.stringify(hud);
|
|
713
|
+
if (force || json !== state.lastState) {
|
|
714
|
+
state.lastState = json;
|
|
715
|
+
pi.events.emit(STATE_CHANNEL, hud);
|
|
716
|
+
}
|
|
717
|
+
// Finished rows leave the HUD 60 s after they end; refresh then.
|
|
718
|
+
if (state.expiryTimer) clearTimeout(state.expiryTimer);
|
|
719
|
+
state.expiryTimer = undefined;
|
|
720
|
+
const expiry = nextExpiry(manager.list(), now);
|
|
721
|
+
if (expiry !== undefined) {
|
|
722
|
+
state.expiryTimer = setTimeout(() => emitState(), expiry - now + 50);
|
|
723
|
+
state.expiryTimer.unref?.();
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
|
|
727
|
+
state.disposers.push(
|
|
728
|
+
manager.subscribe(() => {
|
|
729
|
+
state.focus?.sync();
|
|
730
|
+
emitState();
|
|
731
|
+
}),
|
|
732
|
+
);
|
|
733
|
+
state.disposers.push(pi.events.on(STATE_REQUEST_CHANNEL, () => emitState(true)));
|
|
734
|
+
state.disposers.push(
|
|
735
|
+
pi.events.on(HUD_CHANNEL, (data) => {
|
|
736
|
+
state.hudRendering = (data as { rendering?: unknown } | undefined)?.rendering === true;
|
|
737
|
+
state.focus?.setHudRendering(state.hudRendering);
|
|
738
|
+
}),
|
|
739
|
+
);
|
|
740
|
+
state.disposers.push(
|
|
741
|
+
pi.events.on(OPEN_CHANNEL, (data) => {
|
|
742
|
+
const agentId = (data as { agentId?: unknown } | undefined)?.agentId;
|
|
743
|
+
state.focus?.exit();
|
|
744
|
+
// An agent row opens its detail, also on top of an open list; "+N more" opens the list unless it is open.
|
|
745
|
+
if (typeof agentId === "string" && manager.get(agentId)) void openDetail(state, agentId, "mouse");
|
|
746
|
+
else void openList(state);
|
|
747
|
+
}),
|
|
748
|
+
);
|
|
749
|
+
|
|
750
|
+
if (ctx.mode === "tui" && ctx.hasUI) {
|
|
751
|
+
// The widget renders nothing (zero lines below the editor); its factory gives us the TUI, whose focused
|
|
752
|
+
// component tells whether the editor or a dialog/selector has the keyboard.
|
|
753
|
+
ctx.ui.setWidget(
|
|
754
|
+
FOCUS_WIDGET_KEY,
|
|
755
|
+
(tui) => {
|
|
756
|
+
state.tui = tui;
|
|
757
|
+
return { render: () => [], invalidate: () => {} };
|
|
758
|
+
},
|
|
759
|
+
{ placement: "belowEditor" },
|
|
760
|
+
);
|
|
761
|
+
state.disposers.push(() => ctx.ui.setWidget(FOCUS_WIDGET_KEY, undefined));
|
|
762
|
+
|
|
763
|
+
const focus = new FocusController({
|
|
764
|
+
hudRendering: () => state.hudRendering,
|
|
765
|
+
editorEmpty: () => ctx.ui.getEditorText() === "",
|
|
766
|
+
// Our own list and overlay first: they hold the keyboard even when the TUI reference is missing.
|
|
767
|
+
editorFocused: () => !state.listOpen && !state.detailOpen && editorHasFocus(state.tui),
|
|
768
|
+
agentIds: () => focusOrder(manager.list()).map((record) => record.agentId),
|
|
769
|
+
open: (agentId) => void openDetail(state, agentId, "focus"),
|
|
770
|
+
stop: (agentId) => void manager.stop(agentId, "user"),
|
|
771
|
+
canStop: (agentId) => {
|
|
772
|
+
const record = manager.get(agentId);
|
|
773
|
+
return record !== undefined && isStoppable(record);
|
|
774
|
+
},
|
|
775
|
+
confirmStop: () => state.config.confirmStop,
|
|
776
|
+
onChange: () => emitState(),
|
|
777
|
+
});
|
|
778
|
+
state.focus = focus;
|
|
779
|
+
state.disposers.push(ctx.ui.onTerminalInput(focus.handleInput));
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// pi-hud may have announced itself before this session existed; ask again.
|
|
783
|
+
pi.events.emit(HUD_REQUEST_CHANNEL, undefined);
|
|
784
|
+
emitState(true);
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/**
|
|
788
|
+
* The editor (pi's or a custom one) has a getText method; selectors, dialogs and overlays do not. Without a
|
|
789
|
+
* TUI reference (not captured yet) fall back to the editor-empty check alone.
|
|
790
|
+
*/
|
|
791
|
+
export function editorHasFocus(tui: object | undefined): boolean {
|
|
792
|
+
// getFocusedComponent is on pi-tui's TuiBase (tui.ts:623) but not in its public TUI interface.
|
|
793
|
+
const getFocused = (tui as Partial<FocusableTui> | undefined)?.getFocusedComponent;
|
|
794
|
+
if (!tui || typeof getFocused !== "function") return true;
|
|
795
|
+
const focused = getFocused.call(tui) as { getText?: unknown } | null | undefined;
|
|
796
|
+
return typeof focused?.getText === "function";
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
function detailSource(state: SessionState): DetailSource {
|
|
800
|
+
const { manager } = state;
|
|
801
|
+
return {
|
|
802
|
+
get: (agentId) => manager.get(agentId),
|
|
803
|
+
progress: (agentId) => manager.progress(agentId),
|
|
804
|
+
subscribe: (listener) => manager.subscribe(listener),
|
|
805
|
+
stop: (agentId) => void manager.stop(agentId, "user"),
|
|
806
|
+
report: (record) => {
|
|
807
|
+
const file = existingFile(record.resultFile);
|
|
808
|
+
if (file) {
|
|
809
|
+
try {
|
|
810
|
+
return readFileSync(file, "utf8");
|
|
811
|
+
} catch {
|
|
812
|
+
// Fall back to the in-memory text.
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
return record.text ?? "";
|
|
816
|
+
},
|
|
817
|
+
transcript: (record) => existingFile(record.sessionFile),
|
|
818
|
+
confirmStop: () => state.config.confirmStop,
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
/**
|
|
823
|
+
* Open the detail overlay: long content, so an overlay with a bounded height that scrolls itself. It may sit
|
|
824
|
+
* on top of the /agents list; pi gives the keyboard back to the list when the overlay closes. From focus
|
|
825
|
+
* mode, closing it returns to focus mode (docs/07 §5-§6). One detail at a time: further requests are ignored.
|
|
826
|
+
*/
|
|
827
|
+
async function openDetail(state: SessionState, agentId: string, origin: "focus" | "mouse" | "list"): Promise<void> {
|
|
828
|
+
const { ctx } = state;
|
|
829
|
+
if (state.closed || state.detailOpen || ctx.mode !== "tui" || !ctx.hasUI) {
|
|
830
|
+
if (origin === "focus") state.focus?.resume();
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
state.detailOpen = true;
|
|
834
|
+
try {
|
|
835
|
+
const source = detailSource(state);
|
|
836
|
+
await ctx.ui.custom<void>((tui, theme, keybindings, done) => new AgentDetailView(tui, theme, keybindings, source, agentId, () => done()), {
|
|
837
|
+
overlay: true,
|
|
838
|
+
overlayOptions: { ...OVERLAY_OPTIONS },
|
|
839
|
+
});
|
|
840
|
+
} catch {
|
|
841
|
+
// The UI went away (session switch); nothing to restore.
|
|
842
|
+
} finally {
|
|
843
|
+
state.detailOpen = false;
|
|
844
|
+
if (origin === "focus") state.focus?.resume();
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* The /agents list; also the target of the HUD's "+N more" row. A short selection list, so it goes in the
|
|
850
|
+
* editor slot at the bottom like pi's own selectors (no overlay) and the transcript stays visible. Enter opens
|
|
851
|
+
* the detail overlay on top while the list stays open underneath, keeping its selection (docs/07 §7).
|
|
852
|
+
* Ignored while the list or a detail is already showing.
|
|
853
|
+
*/
|
|
854
|
+
async function openList(state: SessionState): Promise<void> {
|
|
855
|
+
const { ctx, manager } = state;
|
|
856
|
+
if (state.closed || state.listOpen || state.detailOpen || ctx.mode !== "tui" || !ctx.hasUI) return;
|
|
857
|
+
state.listOpen = true;
|
|
858
|
+
try {
|
|
859
|
+
await ctx.ui.custom<void>(
|
|
860
|
+
(tui, theme, keybindings, done) =>
|
|
861
|
+
new AgentListView(
|
|
862
|
+
tui,
|
|
863
|
+
theme,
|
|
864
|
+
keybindings,
|
|
865
|
+
{
|
|
866
|
+
list: () => manager.list(),
|
|
867
|
+
stop: (agentId) => void manager.stop(agentId, "user"),
|
|
868
|
+
open: (agentId) => void openDetail(state, agentId, "list"),
|
|
869
|
+
confirmStop: () => state.config.confirmStop,
|
|
870
|
+
},
|
|
871
|
+
() => done(),
|
|
872
|
+
),
|
|
873
|
+
);
|
|
874
|
+
} catch {
|
|
875
|
+
// The UI went away (session switch) or the list could not be shown; nothing to restore.
|
|
876
|
+
} finally {
|
|
877
|
+
state.listOpen = false;
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// ---------------------------------------------------------------------------------------------------------
|
|
882
|
+
// Helpers
|
|
883
|
+
// ---------------------------------------------------------------------------------------------------------
|
|
884
|
+
|
|
885
|
+
function detailsOf(
|
|
886
|
+
record: AgentRecord,
|
|
887
|
+
type: AgentType,
|
|
888
|
+
extra: { truncated: boolean; sessionFile?: string; progress?: ProgressSnapshot; queuePosition?: number },
|
|
889
|
+
): AgentToolDetails {
|
|
890
|
+
const stats = extra.progress ?? record.stats;
|
|
891
|
+
return {
|
|
892
|
+
agentId: record.agentId,
|
|
893
|
+
type: record.type,
|
|
894
|
+
description: record.description,
|
|
895
|
+
status: record.status,
|
|
896
|
+
reason: record.reason,
|
|
897
|
+
turns: stats.turns,
|
|
898
|
+
toolCalls: stats.toolCalls,
|
|
899
|
+
durationMs: durationOf(record),
|
|
900
|
+
usage: { ...stats.usage },
|
|
901
|
+
model: record.model,
|
|
902
|
+
maxTurns: type.maxTurns,
|
|
903
|
+
sessionFile: extra.sessionFile,
|
|
904
|
+
resultFile: record.resultFile,
|
|
905
|
+
truncated: extra.truncated,
|
|
906
|
+
progress: extra.progress,
|
|
907
|
+
queuePosition: extra.queuePosition,
|
|
908
|
+
};
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/** Throttled onUpdate (at most every 100 ms) plus a 1 s heartbeat so the elapsed time keeps moving. */
|
|
912
|
+
function progressReporter(
|
|
913
|
+
record: AgentRecord,
|
|
914
|
+
type: AgentType,
|
|
915
|
+
onUpdate: AgentToolUpdateCallback<AgentToolDetails> | undefined,
|
|
916
|
+
position: () => number,
|
|
917
|
+
) {
|
|
918
|
+
let latest: ProgressSnapshot | undefined;
|
|
919
|
+
let lastEmit = 0;
|
|
920
|
+
let pending: NodeJS.Timeout | undefined;
|
|
921
|
+
let heartbeat: NodeJS.Timeout | undefined;
|
|
922
|
+
|
|
923
|
+
const emit = (): void => {
|
|
924
|
+
if (!onUpdate) return;
|
|
925
|
+
lastEmit = Date.now();
|
|
926
|
+
const queuePosition = record.status === "queued" ? position() : undefined;
|
|
927
|
+
const text = record.status === "queued" ? `${record.agentId} queued (${queuePosition})` : `${record.agentId} running`;
|
|
928
|
+
onUpdate({ content: [{ type: "text", text }], details: detailsOf(record, type, { truncated: false, progress: latest, queuePosition }) });
|
|
929
|
+
};
|
|
930
|
+
|
|
931
|
+
return {
|
|
932
|
+
emit,
|
|
933
|
+
start(): void {
|
|
934
|
+
emit();
|
|
935
|
+
if (onUpdate) heartbeat = setInterval(emit, HEARTBEAT_MS);
|
|
936
|
+
},
|
|
937
|
+
schedule(snapshot: ProgressSnapshot): void {
|
|
938
|
+
latest = snapshot;
|
|
939
|
+
if (!onUpdate || pending) return;
|
|
940
|
+
pending = setTimeout(
|
|
941
|
+
() => {
|
|
942
|
+
pending = undefined;
|
|
943
|
+
emit();
|
|
944
|
+
},
|
|
945
|
+
Math.max(0, PROGRESS_THROTTLE_MS - (Date.now() - lastEmit)),
|
|
946
|
+
);
|
|
947
|
+
},
|
|
948
|
+
stop(): void {
|
|
949
|
+
if (pending) clearTimeout(pending);
|
|
950
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
951
|
+
pending = undefined;
|
|
952
|
+
heartbeat = undefined;
|
|
953
|
+
},
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
function catalogOf(registry: ModelRegistry): ModelCatalog {
|
|
958
|
+
type RegistryModel = Parameters<ModelRegistry["hasConfiguredAuth"]>[0];
|
|
959
|
+
return {
|
|
960
|
+
find: (provider, id) => registry.find(provider, id),
|
|
961
|
+
available: () => registry.getAvailable(),
|
|
962
|
+
hasAuth: (model) => registry.hasConfiguredAuth(model as RegistryModel),
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
/** Continue numbering after result files left by earlier runs of this parent session (e.g. before /reload). */
|
|
967
|
+
export function nextAgentNumber(resultDir: string): number {
|
|
968
|
+
let max = 0;
|
|
969
|
+
try {
|
|
970
|
+
for (const name of readdirSync(resultDir)) {
|
|
971
|
+
const match = /^ag-(\d+)\.result(?:\.\d+)?\.md$/.exec(name);
|
|
972
|
+
if (match) max = Math.max(max, Number(match[1]));
|
|
973
|
+
}
|
|
974
|
+
} catch {
|
|
975
|
+
// No directory yet.
|
|
976
|
+
}
|
|
977
|
+
return max + 1;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
function notifyProblems(ctx: ExtensionContext, state: SessionState): void {
|
|
981
|
+
if (!ctx.hasUI) return;
|
|
982
|
+
if (state.configError) ctx.ui.notify(`pi-subagent: ${state.configError}; using defaults`, "warning");
|
|
983
|
+
const warnings = [...state.configWarnings.map((warning) => `pi-subagent.json: ${warning}`), ...state.loaded.warnings];
|
|
984
|
+
if (warnings.length > 0) {
|
|
985
|
+
ctx.ui.notify(`pi-subagent: ${warnings.length} agent type warning(s); see /agents types\n${warnings.join("\n")}`, "warning");
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
export function describeTypes(state: Pick<SessionState, "loaded" | "configError" | "configWarnings">): string {
|
|
990
|
+
const lines = ["Agent types:"];
|
|
991
|
+
for (const type of state.loaded.types.values()) {
|
|
992
|
+
const parts = [
|
|
993
|
+
`tools: ${type.tools.length > 0 ? type.tools.join(", ") : "none"}`,
|
|
994
|
+
`model: ${type.model ?? "inherit"}`,
|
|
995
|
+
`thinking: ${type.thinking ?? "inherit"}`,
|
|
996
|
+
`max_turns: ${type.maxTurns}`,
|
|
997
|
+
`context_limit: ${type.contextLimit}%`,
|
|
998
|
+
];
|
|
999
|
+
if (type.background) parts.push("background");
|
|
1000
|
+
lines.push(`- ${type.name} (${type.source}) ${parts.join(" · ")}`);
|
|
1001
|
+
lines.push(` ${type.description}`);
|
|
1002
|
+
}
|
|
1003
|
+
if (state.loaded.skippedProject > 0) {
|
|
1004
|
+
lines.push(`Skipped ${state.loaded.skippedProject} project type file(s): the project is not trusted.`);
|
|
1005
|
+
}
|
|
1006
|
+
const warnings = [
|
|
1007
|
+
...(state.configError ? [`pi-subagent.json: ${state.configError}`] : []),
|
|
1008
|
+
...state.configWarnings.map((warning) => `pi-subagent.json: ${warning}`),
|
|
1009
|
+
...state.loaded.warnings,
|
|
1010
|
+
];
|
|
1011
|
+
if (warnings.length > 0) lines.push("Warnings:", ...warnings.map((warning) => `- ${warning}`));
|
|
1012
|
+
return lines.join("\n");
|
|
1013
|
+
}
|