@luxass/pi-subagents 0.0.0-stage → 0.0.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 +95 -2
- package/package.json +49 -3
- package/src/agents/explorer.md +10 -0
- package/src/agents/general-purpose.md +7 -0
- package/src/agents.ts +120 -0
- package/src/costs.ts +52 -0
- package/src/index.ts +114 -0
- package/src/manager.ts +722 -0
- package/src/mentions.ts +81 -0
- package/src/message-text.ts +16 -0
- package/src/models.ts +76 -0
- package/src/results.ts +237 -0
- package/src/session.ts +352 -0
- package/src/settings.ts +104 -0
- package/src/terminal-status.ts +62 -0
- package/src/tool-text.ts +69 -0
- package/src/tools.ts +210 -0
- package/src/ui/agent-card.ts +123 -0
- package/src/ui/agent-list.ts +162 -0
- package/src/ui/agent-panel.ts +250 -0
- package/src/ui/agent-preview.ts +124 -0
- package/src/ui/agent-status.ts +159 -0
- package/src/ui/background-shortcut.ts +33 -0
- package/src/ui/conversation.ts +298 -0
- package/src/ui/cost-status.ts +24 -0
- package/src/ui/text-layout.ts +29 -0
- package/src/ui/viewer.ts +224 -0
- package/src/ui/widget.ts +59 -0
package/src/session.ts
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { access } from "node:fs/promises";
|
|
3
|
+
import { resolve, sep } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
import type { Message } from "@earendil-works/pi-ai";
|
|
7
|
+
import {
|
|
8
|
+
convertToLlm,
|
|
9
|
+
createAgentSession,
|
|
10
|
+
createCodemodeExtension,
|
|
11
|
+
createMcpExtension,
|
|
12
|
+
DefaultResourceLoader,
|
|
13
|
+
getAgentDir,
|
|
14
|
+
ModelRuntime,
|
|
15
|
+
SessionManager,
|
|
16
|
+
SettingsManager,
|
|
17
|
+
stripFrontmatter,
|
|
18
|
+
type AgentSession,
|
|
19
|
+
type AgentSessionEvent,
|
|
20
|
+
type ExtensionAPI,
|
|
21
|
+
type ExtensionContext,
|
|
22
|
+
} from "@earendil-works/pi-coding-agent";
|
|
23
|
+
|
|
24
|
+
import {
|
|
25
|
+
DEFAULT_SUBAGENT_TOOLS,
|
|
26
|
+
isSubagentControlTool,
|
|
27
|
+
type SubagentDefinition,
|
|
28
|
+
} from "./agents.ts";
|
|
29
|
+
import { findSubagentModel, type SubagentModel } from "./models.ts";
|
|
30
|
+
import type { SubagentSettings } from "./settings.ts";
|
|
31
|
+
|
|
32
|
+
const BUILTIN_TOOLS = new Set([
|
|
33
|
+
"read",
|
|
34
|
+
"bash",
|
|
35
|
+
"powershell",
|
|
36
|
+
"edit",
|
|
37
|
+
"write",
|
|
38
|
+
"grep",
|
|
39
|
+
"find",
|
|
40
|
+
"ls",
|
|
41
|
+
]);
|
|
42
|
+
const PACKAGE_DIRECTORY = resolve(fileURLToPath(new URL("..", import.meta.url)));
|
|
43
|
+
const WRAP_UP_INSTRUCTION =
|
|
44
|
+
"You have one turn left. Wrap up now: report your findings, what you changed, and any unfinished work. Do not start new work.";
|
|
45
|
+
|
|
46
|
+
/** Custom message type of the note that follows an agent's inherited context. */
|
|
47
|
+
const SUBAGENT_INHERITED_CONTEXT_MESSAGE = "subagents-inherited-context";
|
|
48
|
+
/**
|
|
49
|
+
* Ends the copied conversation. Without it, an agent can take the main session's last request as
|
|
50
|
+
* its own and try to start the agent that it is.
|
|
51
|
+
*/
|
|
52
|
+
const INHERITED_CONTEXT_NOTE =
|
|
53
|
+
"The conversation above is a copy of the main session's conversation, given to you as background. You are a separate agent that the main session started. Do not continue that conversation or carry out its requests. Its tools are not yours: you cannot start or control agents, so use only the tools you have. Do the task in the next message and reply with its result.";
|
|
54
|
+
|
|
55
|
+
/** Thinking levels accepted by Pi 1.5. */
|
|
56
|
+
export type SubagentThinking = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
57
|
+
|
|
58
|
+
/** Optional `Agent` call parameters. A model here wins over the agent file's. The file's other values win. */
|
|
59
|
+
export interface SubagentOverrides {
|
|
60
|
+
model?: string;
|
|
61
|
+
thinking?: SubagentThinking;
|
|
62
|
+
max_turns?: number;
|
|
63
|
+
inherit_context?: boolean;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Launch policy resolved and validated before a task name is reserved. */
|
|
67
|
+
export interface SubagentPolicy {
|
|
68
|
+
definition: SubagentDefinition;
|
|
69
|
+
model: SubagentModel;
|
|
70
|
+
thinking: SubagentThinking;
|
|
71
|
+
maxTurns: number;
|
|
72
|
+
tools: string[];
|
|
73
|
+
extensionPaths: string[];
|
|
74
|
+
codemode: boolean;
|
|
75
|
+
mcp: boolean;
|
|
76
|
+
inherited: Message[];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Builds the model runtime shared by all agents of one main session, copying its providers. */
|
|
80
|
+
export async function createSubagentRuntime(ctx: ExtensionContext): Promise<ModelRuntime> {
|
|
81
|
+
const runtime = await ModelRuntime.create();
|
|
82
|
+
for (const providerId of ctx.modelRegistry.getRegisteredProviderIds()) {
|
|
83
|
+
const provider = ctx.modelRegistry.getRegisteredNativeProvider(providerId);
|
|
84
|
+
if (provider) runtime.registerNativeProvider(provider);
|
|
85
|
+
const config = ctx.modelRegistry.getRegisteredProviderConfig(providerId);
|
|
86
|
+
if (config) runtime.registerProvider(providerId, config);
|
|
87
|
+
}
|
|
88
|
+
return runtime;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Copies the conversation the main model currently sees, for `inherit_context`. */
|
|
92
|
+
export function inheritedSubagentContext(ctx: ExtensionContext): Message[] {
|
|
93
|
+
// Pi's own conversion before a model request. Summaries, extension messages such as earlier agent
|
|
94
|
+
// results, and `!` command output become user messages, exactly as the main model sees them.
|
|
95
|
+
const messages = convertToLlm(
|
|
96
|
+
structuredClone(ctx.sessionManager.buildSessionProjection().messages),
|
|
97
|
+
);
|
|
98
|
+
const answeredCalls = new Set(
|
|
99
|
+
messages.flatMap((message) => (message.role === "toolResult" ? [message.toolCallId] : [])),
|
|
100
|
+
);
|
|
101
|
+
const keptCalls = new Set<string>();
|
|
102
|
+
const inherited: Message[] = [];
|
|
103
|
+
for (const message of messages) {
|
|
104
|
+
if (message.role === "assistant") {
|
|
105
|
+
// A tool call without a result would leave the transcript invalid for the provider.
|
|
106
|
+
const content = message.content.filter((part) => {
|
|
107
|
+
if (part.type !== "toolCall") return true;
|
|
108
|
+
if (!answeredCalls.has(part.id)) return false;
|
|
109
|
+
keptCalls.add(part.id);
|
|
110
|
+
return true;
|
|
111
|
+
});
|
|
112
|
+
if (content.length) inherited.push({ ...message, content });
|
|
113
|
+
} else if (message.role !== "toolResult" || keptCalls.has(message.toolCallId)) {
|
|
114
|
+
inherited.push(message);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return inherited;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The model an agent runs on: the named one, or the caller's when no model is named. */
|
|
121
|
+
function resolveSubagentModel(
|
|
122
|
+
ctx: ExtensionContext,
|
|
123
|
+
requested: string | undefined,
|
|
124
|
+
settings: SubagentSettings,
|
|
125
|
+
): SubagentModel {
|
|
126
|
+
if (requested) {
|
|
127
|
+
return findSubagentModel(
|
|
128
|
+
ctx.modelRegistry.getAvailable(),
|
|
129
|
+
requested,
|
|
130
|
+
settings.preferredProviders,
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
if (!ctx.model) {
|
|
134
|
+
throw new Error("No model selected: choose a model in Pi before starting an agent.");
|
|
135
|
+
}
|
|
136
|
+
return ctx.model;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Resolves model, thinking, turn limit, and tool access for one start or continuation. */
|
|
140
|
+
export function resolveSubagentPolicy(options: {
|
|
141
|
+
definition: SubagentDefinition;
|
|
142
|
+
overrides: SubagentOverrides;
|
|
143
|
+
ctx: ExtensionContext;
|
|
144
|
+
pi: ExtensionAPI;
|
|
145
|
+
settings: SubagentSettings;
|
|
146
|
+
}): SubagentPolicy {
|
|
147
|
+
const { definition, overrides, ctx, pi, settings } = options;
|
|
148
|
+
const tools = [...new Set(definition.tools ?? DEFAULT_SUBAGENT_TOOLS)];
|
|
149
|
+
const extensionPaths = new Set<string>();
|
|
150
|
+
let codemode = false;
|
|
151
|
+
let mcp = false;
|
|
152
|
+
const mainTools = pi.getAllTools();
|
|
153
|
+
for (const name of tools) {
|
|
154
|
+
if (isSubagentControlTool(name))
|
|
155
|
+
throw new Error(`Agents cannot use ${name}: only the main session coordinates agents.`);
|
|
156
|
+
if (BUILTIN_TOOLS.has(name)) continue;
|
|
157
|
+
if (name.startsWith("mcp__")) {
|
|
158
|
+
mcp = true;
|
|
159
|
+
codemode = true;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const path = mainTools.find((tool) => tool.name === name)?.sourceInfo.path;
|
|
163
|
+
if (!path)
|
|
164
|
+
throw new Error(
|
|
165
|
+
`Tool ${name} is not available in the main session, so no extension provides it.`,
|
|
166
|
+
);
|
|
167
|
+
if (path === "builtin:codemode") {
|
|
168
|
+
codemode = true;
|
|
169
|
+
} else if (path === "builtin:mcp") {
|
|
170
|
+
mcp = true;
|
|
171
|
+
codemode = true;
|
|
172
|
+
} else if (path.startsWith("builtin:")) {
|
|
173
|
+
throw new Error(`Tool ${name} comes from Pi's ${path} extension, which agents cannot load.`);
|
|
174
|
+
} else {
|
|
175
|
+
const absolute = resolve(path);
|
|
176
|
+
if (absolute === PACKAGE_DIRECTORY || absolute.startsWith(PACKAGE_DIRECTORY + sep)) {
|
|
177
|
+
throw new Error(`Tool ${name} belongs to pi-subagents, which never loads inside an agent.`);
|
|
178
|
+
}
|
|
179
|
+
extensionPaths.add(path);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (codemode && !tools.includes("codemode")) tools.push("codemode");
|
|
183
|
+
// Checked here so a missing skill rejects the call before its task name is used. Pi lists
|
|
184
|
+
// each of the main session's skills as the command `skill:<name>`.
|
|
185
|
+
const mainSkills = new Set(
|
|
186
|
+
pi.getCommands().flatMap((command) => (command.source === "skill" ? [command.name] : [])),
|
|
187
|
+
);
|
|
188
|
+
const missingSkill = (definition.skills ?? []).find((name) => !mainSkills.has(`skill:${name}`));
|
|
189
|
+
if (missingSkill) {
|
|
190
|
+
throw new Error(`Skill ${missingSkill} listed by agent type ${definition.name} was not found.`);
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
definition,
|
|
194
|
+
// A model named in the call wins. The file's model is the type's default.
|
|
195
|
+
model: resolveSubagentModel(ctx, overrides.model ?? definition.model, settings),
|
|
196
|
+
thinking: definition.thinking ?? overrides.thinking ?? ctx.thinkingLevel ?? "off",
|
|
197
|
+
maxTurns: definition.max_turns ?? overrides.max_turns ?? settings.maxTurns,
|
|
198
|
+
tools,
|
|
199
|
+
extensionPaths: [...extensionPaths],
|
|
200
|
+
codemode,
|
|
201
|
+
mcp,
|
|
202
|
+
inherited: overrides.inherit_context ? inheritedSubagentContext(ctx) : [],
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** One live child session. Each `run` is one start or continuation with its own turn budget. */
|
|
207
|
+
export interface SubagentSession {
|
|
208
|
+
readonly session: AgentSession;
|
|
209
|
+
/** True when the turn limit stopped work that was still going. */
|
|
210
|
+
partial: boolean;
|
|
211
|
+
run(prompt: string): Promise<void>;
|
|
212
|
+
dispose(): Promise<void>;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Creates or reopens an agent's session without loading unrelated extensions. */
|
|
216
|
+
export async function createSubagentSession(options: {
|
|
217
|
+
ctx: ExtensionContext;
|
|
218
|
+
pi: ExtensionAPI;
|
|
219
|
+
runtime: ModelRuntime;
|
|
220
|
+
policy: SubagentPolicy;
|
|
221
|
+
sessionId: string;
|
|
222
|
+
sessionDirectory: string;
|
|
223
|
+
sessionFile?: string;
|
|
224
|
+
onEvent: (event: AgentSessionEvent) => void;
|
|
225
|
+
}): Promise<SubagentSession> {
|
|
226
|
+
const { ctx, pi, runtime, policy } = options;
|
|
227
|
+
const projectTrusted = ctx.isProjectTrusted();
|
|
228
|
+
// The session's settings stay in memory. A session saves its model and thinking level to its
|
|
229
|
+
// settings, and an agent must never change the user's settings files.
|
|
230
|
+
const settingsManager = SettingsManager.inMemory(pi.getSettings(), { projectTrusted });
|
|
231
|
+
// The loader reads the settings files, so it knows which paths are global and which belong to
|
|
232
|
+
// the project. It resolves each from its own folder, and it only reads while loading.
|
|
233
|
+
const resourceSettings = SettingsManager.create(ctx.cwd, getAgentDir(), { projectTrusted });
|
|
234
|
+
const resourceLoader: DefaultResourceLoader = new DefaultResourceLoader({
|
|
235
|
+
cwd: ctx.cwd,
|
|
236
|
+
agentDir: getAgentDir(),
|
|
237
|
+
settingsManager: resourceSettings,
|
|
238
|
+
noExtensions: true,
|
|
239
|
+
additionalExtensionPaths: policy.extensionPaths,
|
|
240
|
+
extensionFactories: [
|
|
241
|
+
...(policy.codemode ? [createCodemodeExtension({ mode: "on" })] : []),
|
|
242
|
+
...(policy.mcp ? [createMcpExtension()] : []),
|
|
243
|
+
],
|
|
244
|
+
// Runs after skills load, so the agent's listed skills can be added in full.
|
|
245
|
+
appendSystemPromptOverride: (base) => {
|
|
246
|
+
const skills = resourceLoader.getSkills().skills;
|
|
247
|
+
const skillTexts = (policy.definition.skills ?? []).map((name) => {
|
|
248
|
+
const skill = skills.find((candidate) => candidate.name === name);
|
|
249
|
+
if (!skill)
|
|
250
|
+
throw new Error(
|
|
251
|
+
`Skill ${name} listed by agent type ${policy.definition.name} was not found.`,
|
|
252
|
+
);
|
|
253
|
+
return stripFrontmatter(readFileSync(skill.filePath, "utf8")).trim();
|
|
254
|
+
});
|
|
255
|
+
return [...base, policy.definition.body, ...skillTexts].filter(Boolean);
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
await resourceLoader.reload();
|
|
259
|
+
// reload() collects load errors and does not throw. Without its extension the agent would run
|
|
260
|
+
// without a tool it was given, and still report success.
|
|
261
|
+
const [loadError] = resourceLoader.getExtensions().errors;
|
|
262
|
+
if (loadError) {
|
|
263
|
+
throw new Error(`Extension ${loadError.path} failed to load for the agent: ${loadError.error}`);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
let sessionManager: SessionManager;
|
|
267
|
+
if (options.sessionFile) {
|
|
268
|
+
await access(options.sessionFile);
|
|
269
|
+
sessionManager = SessionManager.open(options.sessionFile);
|
|
270
|
+
} else {
|
|
271
|
+
sessionManager = SessionManager.create(ctx.cwd, options.sessionDirectory, {
|
|
272
|
+
id: options.sessionId,
|
|
273
|
+
parentSession: ctx.sessionManager.getSessionFile(),
|
|
274
|
+
});
|
|
275
|
+
for (const message of policy.inherited) sessionManager.appendMessage(message);
|
|
276
|
+
if (policy.inherited.length) {
|
|
277
|
+
// Shown in `/agents` too, where it marks the end of the copied conversation.
|
|
278
|
+
sessionManager.appendCustomMessageEntry(
|
|
279
|
+
SUBAGENT_INHERITED_CONTEXT_MESSAGE,
|
|
280
|
+
INHERITED_CONTEXT_NOTE,
|
|
281
|
+
true,
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const { session } = await createAgentSession({
|
|
287
|
+
cwd: ctx.cwd,
|
|
288
|
+
modelRuntime: runtime,
|
|
289
|
+
model: policy.model,
|
|
290
|
+
thinkingLevel: policy.thinking,
|
|
291
|
+
tools: policy.tools,
|
|
292
|
+
settingsManager,
|
|
293
|
+
resourceLoader,
|
|
294
|
+
sessionManager,
|
|
295
|
+
});
|
|
296
|
+
// A reopened session restores its saved model. The current definition and call decide instead.
|
|
297
|
+
if (options.sessionFile) {
|
|
298
|
+
await session.setModel(policy.model);
|
|
299
|
+
session.setThinkingLevel(policy.thinking);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
let turns = 0;
|
|
303
|
+
let disposed = false;
|
|
304
|
+
const child: SubagentSession = {
|
|
305
|
+
session,
|
|
306
|
+
partial: false,
|
|
307
|
+
async run(prompt) {
|
|
308
|
+
turns = 0;
|
|
309
|
+
child.partial = false;
|
|
310
|
+
const text = policy.maxTurns === 1 ? `${prompt}\n\n${WRAP_UP_INSTRUCTION}` : prompt;
|
|
311
|
+
await session.prompt(text, { expandPromptTemplates: false });
|
|
312
|
+
await session.waitForIdle();
|
|
313
|
+
},
|
|
314
|
+
async dispose() {
|
|
315
|
+
if (disposed) return;
|
|
316
|
+
disposed = true;
|
|
317
|
+
await session.abort();
|
|
318
|
+
try {
|
|
319
|
+
await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
|
|
320
|
+
} finally {
|
|
321
|
+
session.dispose();
|
|
322
|
+
}
|
|
323
|
+
},
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
session.subscribe((event) => {
|
|
327
|
+
if (event.type === "turn_start" && policy.maxTurns > 0 && turns >= policy.maxTurns) {
|
|
328
|
+
// Another turn means work remains after the last allowed turn.
|
|
329
|
+
child.partial = true;
|
|
330
|
+
session.agent.abort();
|
|
331
|
+
}
|
|
332
|
+
if (event.type === "turn_end") {
|
|
333
|
+
turns++;
|
|
334
|
+
// A turn without tool calls is the agent's final answer. A wrap-up message there would force
|
|
335
|
+
// one more turn, and that reply would replace the answer.
|
|
336
|
+
const workRemains = event.toolResults.length > 0;
|
|
337
|
+
if (policy.maxTurns > 1 && turns === policy.maxTurns - 1 && workRemains) {
|
|
338
|
+
session.agent.steer({ role: "user", content: WRAP_UP_INSTRUCTION, timestamp: Date.now() });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
options.onEvent(event);
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
try {
|
|
345
|
+
// Print mode has no UI, so interactive tools fail inside an agent.
|
|
346
|
+
await session.bindExtensions({ mode: "print" });
|
|
347
|
+
} catch (error) {
|
|
348
|
+
await child.dispose();
|
|
349
|
+
throw error;
|
|
350
|
+
}
|
|
351
|
+
return child;
|
|
352
|
+
}
|
package/src/settings.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import {
|
|
2
|
+
arr,
|
|
3
|
+
bool,
|
|
4
|
+
compile,
|
|
5
|
+
int,
|
|
6
|
+
obj,
|
|
7
|
+
oneOf,
|
|
8
|
+
str,
|
|
9
|
+
type Validator,
|
|
10
|
+
} from "@earendil-works/pi-schema";
|
|
11
|
+
|
|
12
|
+
/** Effective subagent settings after field-wise defaults. */
|
|
13
|
+
export interface SubagentSettings {
|
|
14
|
+
maxConcurrent: number;
|
|
15
|
+
maxTurns: number;
|
|
16
|
+
backgroundByDefault: boolean;
|
|
17
|
+
disabledAgents: string[];
|
|
18
|
+
/** Providers to choose from, in order, when a model name matches on several providers. */
|
|
19
|
+
preferredProviders: string[];
|
|
20
|
+
widget: "background" | "all" | "off";
|
|
21
|
+
delivery: { mode: "grouped" | "immediate" };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const DEFAULT_SUBAGENT_SETTINGS: SubagentSettings = {
|
|
25
|
+
maxConcurrent: 8,
|
|
26
|
+
maxTurns: 0,
|
|
27
|
+
backgroundByDefault: true,
|
|
28
|
+
disabledAgents: [],
|
|
29
|
+
preferredProviders: [],
|
|
30
|
+
widget: "background",
|
|
31
|
+
delivery: { mode: "grouped" },
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
// Any object. Its fields are checked one at a time below.
|
|
35
|
+
const anyObject: Validator<Record<string, unknown>> = compile(obj({}, { open: true }));
|
|
36
|
+
|
|
37
|
+
// One check per field, so an invalid field falls back alone and valid fields keep their values.
|
|
38
|
+
const subagentSettingChecks = {
|
|
39
|
+
maxConcurrent: compile(int({ minimum: 1 })),
|
|
40
|
+
maxTurns: compile(int({ minimum: 0 })),
|
|
41
|
+
backgroundByDefault: compile(bool()),
|
|
42
|
+
disabledAgents: compile(arr(str())),
|
|
43
|
+
preferredProviders: compile(arr(str())),
|
|
44
|
+
widget: compile(oneOf(["background", "all", "off"])),
|
|
45
|
+
delivery: anyObject,
|
|
46
|
+
};
|
|
47
|
+
const deliveryModeCheck = compile(oneOf(["grouped", "immediate"]));
|
|
48
|
+
|
|
49
|
+
/** Reads the `subagents` section of Pi's merged settings. Each invalid field warns once and uses its default. */
|
|
50
|
+
export function readSubagentSettings(
|
|
51
|
+
value: unknown,
|
|
52
|
+
warn: (message: string) => void,
|
|
53
|
+
): SubagentSettings {
|
|
54
|
+
/** The value when it is valid. Otherwise one warning naming the first problem, and `undefined`. */
|
|
55
|
+
function read<Value>(name: string, fieldValue: unknown, check: Validator<Value>) {
|
|
56
|
+
if (fieldValue === undefined || check.check(fieldValue)) return fieldValue;
|
|
57
|
+
const [error] = check.errors(fieldValue);
|
|
58
|
+
// A path inside the value, such as /1 in an array, becomes disabledAgents.1.
|
|
59
|
+
const where = `${name}${error?.path.replaceAll("/", ".") ?? ""}`;
|
|
60
|
+
warn(
|
|
61
|
+
`Invalid subagents setting ${where}: ${error?.message ?? "invalid value"}. Using the default.`,
|
|
62
|
+
);
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function warnUnknown(prefix: string, fields: object, known: readonly string[]) {
|
|
67
|
+
for (const key of Object.keys(fields)) {
|
|
68
|
+
if (!known.includes(key))
|
|
69
|
+
warn(`Invalid subagents setting ${prefix}${key}: unknown field. Ignoring it.`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (value === undefined) return DEFAULT_SUBAGENT_SETTINGS;
|
|
74
|
+
if (!anyObject.check(value)) {
|
|
75
|
+
warn("Invalid subagents settings: expected an object. Using defaults.");
|
|
76
|
+
return DEFAULT_SUBAGENT_SETTINGS;
|
|
77
|
+
}
|
|
78
|
+
const input: Record<string, unknown> = value;
|
|
79
|
+
const checks = subagentSettingChecks;
|
|
80
|
+
warnUnknown("", input, Object.keys(checks));
|
|
81
|
+
|
|
82
|
+
const delivery: Record<string, unknown> = read("delivery", input.delivery, checks.delivery) ?? {};
|
|
83
|
+
warnUnknown("delivery.", delivery, ["mode"]);
|
|
84
|
+
|
|
85
|
+
const defaults = DEFAULT_SUBAGENT_SETTINGS;
|
|
86
|
+
return {
|
|
87
|
+
maxConcurrent:
|
|
88
|
+
read("maxConcurrent", input.maxConcurrent, checks.maxConcurrent) ?? defaults.maxConcurrent,
|
|
89
|
+
maxTurns: read("maxTurns", input.maxTurns, checks.maxTurns) ?? defaults.maxTurns,
|
|
90
|
+
backgroundByDefault:
|
|
91
|
+
read("backgroundByDefault", input.backgroundByDefault, checks.backgroundByDefault) ??
|
|
92
|
+
defaults.backgroundByDefault,
|
|
93
|
+
disabledAgents:
|
|
94
|
+
read("disabledAgents", input.disabledAgents, checks.disabledAgents) ??
|
|
95
|
+
defaults.disabledAgents,
|
|
96
|
+
preferredProviders:
|
|
97
|
+
read("preferredProviders", input.preferredProviders, checks.preferredProviders) ??
|
|
98
|
+
defaults.preferredProviders,
|
|
99
|
+
widget: read("widget", input.widget, checks.widget) ?? defaults.widget,
|
|
100
|
+
delivery: {
|
|
101
|
+
mode: read("delivery.mode", delivery.mode, deliveryModeCheck) ?? defaults.delivery.mode,
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { SubagentManager } from "./manager.ts";
|
|
2
|
+
|
|
3
|
+
// Pi's terminal API writes only the root OSC 7501 record. Use a child record so
|
|
4
|
+
// Pi can report that its own turn finished or is blocked without hiding subagent work.
|
|
5
|
+
const SUBAGENT_STATUS_ID = "pi-subagents";
|
|
6
|
+
const CLEAR_SUBAGENTS = `\x1b]7501;state=clear:id=${SUBAGENT_STATUS_ID}\x1b\\`;
|
|
7
|
+
|
|
8
|
+
/** Reports running subagents to Rex independently of Pi's main turn. */
|
|
9
|
+
export function reportSubagentsToRex(manager: SubagentManager): (() => void) | undefined {
|
|
10
|
+
if (
|
|
11
|
+
!process.stdout.isTTY ||
|
|
12
|
+
!process.env.REX_SESSION ||
|
|
13
|
+
!process.env.REX_BLOCK ||
|
|
14
|
+
process.env.PI_PROGRAM_STATUS === "0"
|
|
15
|
+
) {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
let reportedCount = 0;
|
|
20
|
+
let pending = false;
|
|
21
|
+
let disposed = false;
|
|
22
|
+
let resend = false;
|
|
23
|
+
|
|
24
|
+
const scheduleReport = () => {
|
|
25
|
+
if (pending) return;
|
|
26
|
+
pending = true;
|
|
27
|
+
// The manager can finish one agent and start a queued one in the same turn.
|
|
28
|
+
queueMicrotask(() => {
|
|
29
|
+
pending = false;
|
|
30
|
+
if (disposed) return;
|
|
31
|
+
const count = manager
|
|
32
|
+
.list()
|
|
33
|
+
.filter(({ status }) => status === "running" || status === "stopping").length;
|
|
34
|
+
if (!resend && count === reportedCount) return;
|
|
35
|
+
resend = false;
|
|
36
|
+
reportedCount = count;
|
|
37
|
+
if (count === 0) {
|
|
38
|
+
process.stdout.write(CLEAR_SUBAGENTS);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const message = `${count} ${count === 1 ? "subagent" : "subagents"} running`;
|
|
42
|
+
const encoded = Buffer.from(message).toString("base64");
|
|
43
|
+
process.stdout.write(`\x1b]7501;state=working:id=${SUBAGENT_STATUS_ID}:msg=${encoded}\x1b\\`);
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
const onResume = () => {
|
|
47
|
+
// Pi clears all records when it suspends, even if the count stays the same.
|
|
48
|
+
if (reportedCount === 0) return;
|
|
49
|
+
resend = true;
|
|
50
|
+
scheduleReport();
|
|
51
|
+
};
|
|
52
|
+
const unsubscribe = manager.subscribe(scheduleReport);
|
|
53
|
+
process.on("SIGCONT", onResume);
|
|
54
|
+
scheduleReport();
|
|
55
|
+
|
|
56
|
+
return () => {
|
|
57
|
+
disposed = true;
|
|
58
|
+
unsubscribe();
|
|
59
|
+
process.off("SIGCONT", onResume);
|
|
60
|
+
if (reportedCount > 0) process.stdout.write(CLEAR_SUBAGENTS);
|
|
61
|
+
};
|
|
62
|
+
}
|
package/src/tool-text.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
import type { SubagentDefinition } from "./agents.ts";
|
|
4
|
+
import type { SubagentRecord } from "./manager.ts";
|
|
5
|
+
|
|
6
|
+
/** What the `Agent` tool's result and progress carry, so the card can find its agent. */
|
|
7
|
+
export interface AgentToolDetails {
|
|
8
|
+
id?: string;
|
|
9
|
+
/** The run this call started, so its card keeps that run's outcome after a later resume. */
|
|
10
|
+
run?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A plain text tool result that points the card at its agent. */
|
|
14
|
+
export function subagentToolResult(
|
|
15
|
+
text: string,
|
|
16
|
+
details: AgentToolDetails = {},
|
|
17
|
+
): AgentToolResult<AgentToolDetails> {
|
|
18
|
+
return { content: [{ type: "text", text }], details };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* One line for the model: task name, type, the model it runs on, status, and whether the turn
|
|
23
|
+
* limit cut it short. The model is named so a requested model can be checked against the real one.
|
|
24
|
+
*/
|
|
25
|
+
export function subagentStatusLine(record: SubagentRecord): string {
|
|
26
|
+
const partial = record.partial ? " (partial: turn limit reached)" : "";
|
|
27
|
+
return `${record.name} (${record.agentType}, ${record.model}) is ${record.status}${partial}.`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The status line followed by the agent's answer, or its error when it has none. */
|
|
31
|
+
export function subagentFinishedText(record: SubagentRecord): string {
|
|
32
|
+
const body = record.result || record.error || "(no answer)";
|
|
33
|
+
const error = record.error && record.result ? `\nError: ${record.error}` : "";
|
|
34
|
+
return `${subagentStatusLine(record)}\n\n${body}${error}`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Describes the available types and their tools, so the model can choose. */
|
|
38
|
+
export function agentToolDescription(available: readonly SubagentDefinition[] | undefined): string {
|
|
39
|
+
const types = (available ?? [])
|
|
40
|
+
.map((definition) => {
|
|
41
|
+
const tools = (definition.tools ?? ["read", "bash", "edit", "write"]).join(", ");
|
|
42
|
+
return `- ${definition.name}: ${definition.description} Tools: ${tools}.`;
|
|
43
|
+
})
|
|
44
|
+
.join("\n");
|
|
45
|
+
return [
|
|
46
|
+
"Start an agent that works on a task in its own conversation, or continue a finished agent with resume.",
|
|
47
|
+
"Agents run in the background by default, and their results arrive by themselves. Set run_in_background: false to wait for the answer.",
|
|
48
|
+
"Every new agent needs a unique task name. Agents share the project's files and cannot start other agents.",
|
|
49
|
+
"A user message that starts with @<agent type> asks for a new agent of that type.",
|
|
50
|
+
"",
|
|
51
|
+
"When to delegate:",
|
|
52
|
+
"- Delegate self-contained work that can run while you do something else, such as a separate search, review, or change.",
|
|
53
|
+
"- Do the work yourself when your next step depends on it, or when it is quicker than writing the brief.",
|
|
54
|
+
"",
|
|
55
|
+
"Writing the prompt:",
|
|
56
|
+
"- A new agent knows only its prompt, unless inherit_context is true. Brief it like a capable colleague who has not seen this conversation: the goal, the relevant files, what you already know or tried, and what to report back.",
|
|
57
|
+
"- Ask for the concrete result you need next, not open-ended exploration.",
|
|
58
|
+
"- Agents that edit files at the same time must change different files.",
|
|
59
|
+
"",
|
|
60
|
+
"After starting:",
|
|
61
|
+
"- Do not poll a background agent, wait for it, or repeat its work. Continue with other work, or tell the user what you started and end your turn.",
|
|
62
|
+
"- Use steer_subagent to correct a running agent, and resume to give a finished agent a follow-up.",
|
|
63
|
+
"- The user sees only a short preview of each result. Tell them what matters.",
|
|
64
|
+
"",
|
|
65
|
+
"Available agent types:",
|
|
66
|
+
// Without a list, the session has not started and no request can reach the model yet.
|
|
67
|
+
available ? types || "- none" : "- listed when the session has started",
|
|
68
|
+
].join("\n");
|
|
69
|
+
}
|