pi-subagent-manager 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 +139 -2
- package/agents/researcher.md +14 -0
- package/agents/worker.md +6 -0
- package/package.json +61 -4
- package/src/config.ts +355 -0
- package/src/index.ts +216 -0
- package/src/mailbox.ts +261 -0
- package/src/manager.ts +576 -0
- package/src/paths.ts +73 -0
- package/src/runtime.ts +390 -0
- package/src/tools.ts +130 -0
- package/src/types.ts +114 -0
- package/src/ui.ts +391 -0
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { mkdir, realpath } from "node:fs/promises";
|
|
4
|
+
import {
|
|
5
|
+
createAgentSession,
|
|
6
|
+
DefaultResourceLoader,
|
|
7
|
+
getAgentDir,
|
|
8
|
+
ModelRuntime,
|
|
9
|
+
SessionManager,
|
|
10
|
+
SettingsManager,
|
|
11
|
+
type ExtensionContext,
|
|
12
|
+
} from "@earendil-works/pi-coding-agent";
|
|
13
|
+
import {
|
|
14
|
+
BOOTSTRAP_MESSAGE,
|
|
15
|
+
buildBootstrapMessage,
|
|
16
|
+
buildQueuedUserMessage,
|
|
17
|
+
buildUpdateDetails,
|
|
18
|
+
DurableMailbox,
|
|
19
|
+
} from "./mailbox.ts";
|
|
20
|
+
import { selectTools } from "./config.ts";
|
|
21
|
+
import { THINKING_LEVELS, type DriverFactory, type ThinkingLevel } from "./types.ts";
|
|
22
|
+
|
|
23
|
+
const BUILTINS = ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"];
|
|
24
|
+
|
|
25
|
+
/** Isolated SDK sessions; neither external extensions nor the CLI's MCP factories are loaded. */
|
|
26
|
+
export function createDriverFactory(getRootContext: () => ExtensionContext): DriverFactory {
|
|
27
|
+
// Keep resolved settings even after disposal: descendants inherit settings, not the caller's history.
|
|
28
|
+
const resolved = new Map<string, { provider: string; id: string; thinking: ThinkingLevel }>();
|
|
29
|
+
return async (options) => {
|
|
30
|
+
options.signal.throwIfAborted();
|
|
31
|
+
const ctx = getRootContext();
|
|
32
|
+
const rootId = ctx.sessionManager.getSessionId();
|
|
33
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(rootId))
|
|
34
|
+
throw new Error("Unsafe root session id for subagent storage");
|
|
35
|
+
const agentDir = getAgentDir();
|
|
36
|
+
const sessionDir = path.join(agentDir, "subagents", rootId);
|
|
37
|
+
options.signal.throwIfAborted();
|
|
38
|
+
await mkdir(sessionDir, { recursive: true });
|
|
39
|
+
options.signal.throwIfAborted();
|
|
40
|
+
let sessionManager: SessionManager;
|
|
41
|
+
if (options.sessionFile) {
|
|
42
|
+
options.signal.throwIfAborted();
|
|
43
|
+
const directory = await realpath(sessionDir);
|
|
44
|
+
options.signal.throwIfAborted();
|
|
45
|
+
const file = await realpath(options.sessionFile);
|
|
46
|
+
options.signal.throwIfAborted();
|
|
47
|
+
const relative = path.relative(directory, file);
|
|
48
|
+
if (
|
|
49
|
+
!relative ||
|
|
50
|
+
relative.startsWith(`..${path.sep}`) ||
|
|
51
|
+
relative === ".." ||
|
|
52
|
+
path.isAbsolute(relative) ||
|
|
53
|
+
!file.endsWith(".jsonl")
|
|
54
|
+
) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
"Subagent sessionFile must be a JSONL file inside this root's subagent sessions directory",
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
sessionManager = SessionManager.open(path.resolve(options.sessionFile), sessionDir, ctx.cwd);
|
|
60
|
+
if (options.sessionLeafId !== undefined) {
|
|
61
|
+
if (options.sessionLeafId === null) sessionManager.resetLeaf();
|
|
62
|
+
else sessionManager.branch(options.sessionLeafId);
|
|
63
|
+
}
|
|
64
|
+
} else {
|
|
65
|
+
sessionManager = SessionManager.create(ctx.cwd, sessionDir);
|
|
66
|
+
for (const message of options.inherited) {
|
|
67
|
+
// Summary messages are projections, not appendable SDK session entries.
|
|
68
|
+
if (message.role === "compactionSummary" || message.role === "branchSummary") {
|
|
69
|
+
sessionManager.appendMessage({
|
|
70
|
+
role: "user",
|
|
71
|
+
content: message.summary,
|
|
72
|
+
timestamp: message.timestamp,
|
|
73
|
+
});
|
|
74
|
+
} else if (message.role === "custom") {
|
|
75
|
+
sessionManager.appendCustomMessageEntry(
|
|
76
|
+
message.customType,
|
|
77
|
+
message.content,
|
|
78
|
+
message.display,
|
|
79
|
+
message.details,
|
|
80
|
+
);
|
|
81
|
+
} else if (
|
|
82
|
+
message.role === "user" ||
|
|
83
|
+
message.role === "assistant" ||
|
|
84
|
+
message.role === "toolResult" ||
|
|
85
|
+
message.role === "bashExecution"
|
|
86
|
+
) {
|
|
87
|
+
sessionManager.appendMessage(message);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
options.signal.throwIfAborted();
|
|
92
|
+
const runtime = await ModelRuntime.create({
|
|
93
|
+
authPath: path.join(agentDir, "auth.json"),
|
|
94
|
+
modelsPath: path.join(agentDir, "models.json"),
|
|
95
|
+
modelsStorePath: path.join(agentDir, "models-store.json"),
|
|
96
|
+
allowModelNetwork: false,
|
|
97
|
+
signal: options.signal,
|
|
98
|
+
});
|
|
99
|
+
options.signal.throwIfAborted();
|
|
100
|
+
for (const providerId of ctx.modelRegistry.getRegisteredProviderIds()) {
|
|
101
|
+
const native = ctx.modelRegistry.getRegisteredNativeProvider(providerId);
|
|
102
|
+
const config = ctx.modelRegistry.getRegisteredProviderConfig(providerId);
|
|
103
|
+
if (native) runtime.registerNativeProvider(native);
|
|
104
|
+
if (config) runtime.registerProvider(providerId, config);
|
|
105
|
+
}
|
|
106
|
+
const parent = options.parentPath ? resolved.get(`${rootId}:${options.parentPath}`) : undefined;
|
|
107
|
+
let provider = parent?.provider ?? ctx.model?.provider;
|
|
108
|
+
let id = parent?.id ?? ctx.model?.id;
|
|
109
|
+
if (options.type.model) {
|
|
110
|
+
const slash = options.type.model.indexOf("/");
|
|
111
|
+
if (slash < 1 || slash === options.type.model.length - 1)
|
|
112
|
+
throw new Error("Agent model must be provider/model-id");
|
|
113
|
+
provider = options.type.model.slice(0, slash);
|
|
114
|
+
id = options.type.model.slice(slash + 1);
|
|
115
|
+
}
|
|
116
|
+
const restored = options.sessionFile ? sessionManager.buildSessionContext() : undefined;
|
|
117
|
+
if (restored?.model) {
|
|
118
|
+
provider = restored.model.provider;
|
|
119
|
+
id = restored.model.modelId;
|
|
120
|
+
}
|
|
121
|
+
options.signal.throwIfAborted();
|
|
122
|
+
if (provider && ctx.modelRegistry.getProviderAuthStatus(provider).source === "runtime") {
|
|
123
|
+
const apiKey = await ctx.modelRegistry.getApiKeyForProvider(provider);
|
|
124
|
+
options.signal.throwIfAborted();
|
|
125
|
+
if (apiKey !== undefined)
|
|
126
|
+
await runtime.setRuntimeApiKey(provider, apiKey, { signal: options.signal });
|
|
127
|
+
options.signal.throwIfAborted();
|
|
128
|
+
}
|
|
129
|
+
const rootModel = provider && id ? ctx.modelRegistry.find(provider, id) : undefined;
|
|
130
|
+
if (rootModel?.api === "pi-virtual") {
|
|
131
|
+
throw new Error(
|
|
132
|
+
`Virtual model ${provider}/${id} cannot be reproduced through the public registry API. Set this agent type's model to a physical provider/model-id.`,
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
const model = provider && id ? runtime.getModel(provider, id) : undefined;
|
|
136
|
+
if (!model)
|
|
137
|
+
throw new Error(
|
|
138
|
+
`Subagent model ${provider ?? "(unset)"}/${id ?? "(unset)"} is unavailable; select a physical model in the root or agent type`,
|
|
139
|
+
);
|
|
140
|
+
const savedThinking =
|
|
141
|
+
restored && THINKING_LEVELS.includes(restored.thinkingLevel as ThinkingLevel)
|
|
142
|
+
? (restored.thinkingLevel as ThinkingLevel)
|
|
143
|
+
: undefined;
|
|
144
|
+
const thinkingLevel =
|
|
145
|
+
savedThinking ?? options.type.thinkingLevel ?? parent?.thinking ?? ctx.thinkingLevel ?? "off";
|
|
146
|
+
const toolNames = selectTools(options.type.tools, [
|
|
147
|
+
...BUILTINS,
|
|
148
|
+
...options.tools.map((tool) => tool.name),
|
|
149
|
+
]);
|
|
150
|
+
const allowed = new Set(toolNames);
|
|
151
|
+
const settingsManager = SettingsManager.inMemory({ cacheWarming: "off" });
|
|
152
|
+
let parkQueue = () => {};
|
|
153
|
+
const pauseBoundary = () => {
|
|
154
|
+
if (!options.shouldPause()) return undefined;
|
|
155
|
+
parkQueue();
|
|
156
|
+
return { continue: false };
|
|
157
|
+
};
|
|
158
|
+
const loader = new DefaultResourceLoader({
|
|
159
|
+
cwd: ctx.cwd,
|
|
160
|
+
agentDir,
|
|
161
|
+
settingsManager,
|
|
162
|
+
noExtensions: true,
|
|
163
|
+
noSkills: true,
|
|
164
|
+
noPromptTemplates: true,
|
|
165
|
+
noContextFiles: true,
|
|
166
|
+
noThemes: true,
|
|
167
|
+
systemPrompt: [
|
|
168
|
+
options.type.systemPrompt,
|
|
169
|
+
`Your thread path is ${options.path}.`,
|
|
170
|
+
options.parentPath
|
|
171
|
+
? `Your lexical parent is ${options.parentPath}; inherited conversation comes only from that parent.`
|
|
172
|
+
: "You are an independent root thread with no inherited history.",
|
|
173
|
+
"When finished, give your final answer normally so it can be handed back. To retain unfinished work without a final answer, call agent_pause (if available), then stop; resume only when instructed.",
|
|
174
|
+
].join("\n\n"),
|
|
175
|
+
appendSystemPromptOverride: () => [],
|
|
176
|
+
extensionFactories: [
|
|
177
|
+
(pi) => {
|
|
178
|
+
pi.on("turn_end", pauseBoundary);
|
|
179
|
+
pi.on("agent_before_settle", pauseBoundary);
|
|
180
|
+
pi.on("tool_call", (event) =>
|
|
181
|
+
allowed.has(event.toolName)
|
|
182
|
+
? undefined
|
|
183
|
+
: { block: true, reason: "Tool is not allowed by this agent type" },
|
|
184
|
+
);
|
|
185
|
+
},
|
|
186
|
+
],
|
|
187
|
+
});
|
|
188
|
+
options.signal.throwIfAborted();
|
|
189
|
+
await loader.reload();
|
|
190
|
+
options.signal.throwIfAborted();
|
|
191
|
+
const { session } = await createAgentSession({
|
|
192
|
+
cwd: ctx.cwd,
|
|
193
|
+
agentDir,
|
|
194
|
+
modelRuntime: runtime,
|
|
195
|
+
model,
|
|
196
|
+
thinkingLevel,
|
|
197
|
+
settingsManager,
|
|
198
|
+
resourceLoader: loader,
|
|
199
|
+
sessionManager,
|
|
200
|
+
tools: toolNames,
|
|
201
|
+
customTools: options.tools.filter((tool) => allowed.has(tool.name)),
|
|
202
|
+
});
|
|
203
|
+
try {
|
|
204
|
+
options.signal.throwIfAborted();
|
|
205
|
+
await session.bindExtensions({ mode: "print" });
|
|
206
|
+
options.signal.throwIfAborted();
|
|
207
|
+
} catch (error) {
|
|
208
|
+
session.dispose();
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
const mailbox = new DurableMailbox(sessionManager);
|
|
212
|
+
const emitCheckpoint = () =>
|
|
213
|
+
options.onEvent({
|
|
214
|
+
kind: "checkpoint",
|
|
215
|
+
text: "",
|
|
216
|
+
sessionFile: session.sessionFile,
|
|
217
|
+
sessionLeafId: sessionManager.getLeafId(),
|
|
218
|
+
});
|
|
219
|
+
const restoreAppends = mailbox.wrapAppends(emitCheckpoint);
|
|
220
|
+
const ensurePersistedSession = () => {
|
|
221
|
+
if (session.sessionFile && existsSync(session.sessionFile)) return;
|
|
222
|
+
sessionManager.appendMessage(buildBootstrapMessage());
|
|
223
|
+
emit("activity", BOOTSTRAP_MESSAGE);
|
|
224
|
+
};
|
|
225
|
+
const queueAccepted = async (kind: "steer" | "followUp", content: string) => {
|
|
226
|
+
ensurePersistedSession();
|
|
227
|
+
const accepted = mailbox.accept(kind, content);
|
|
228
|
+
emitCheckpoint();
|
|
229
|
+
if (kind === "followUp") session.agent.followUp(buildQueuedUserMessage(accepted));
|
|
230
|
+
else session.agent.steer(buildQueuedUserMessage(accepted));
|
|
231
|
+
mailbox.markEnqueued(accepted.id);
|
|
232
|
+
};
|
|
233
|
+
const resumePending = async () => {
|
|
234
|
+
for (const accepted of mailbox.replayablePending()) {
|
|
235
|
+
if (accepted.kind === "update") {
|
|
236
|
+
await session.sendCustomMessage(
|
|
237
|
+
{
|
|
238
|
+
customType: "subagent-update",
|
|
239
|
+
content: accepted.content,
|
|
240
|
+
display: true,
|
|
241
|
+
details: buildUpdateDetails(accepted),
|
|
242
|
+
},
|
|
243
|
+
{ triggerTurn: false },
|
|
244
|
+
);
|
|
245
|
+
mailbox.markEnqueued(accepted.id);
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (accepted.kind === "followUp") session.agent.followUp(buildQueuedUserMessage(accepted));
|
|
249
|
+
else session.agent.steer(buildQueuedUserMessage(accepted));
|
|
250
|
+
mailbox.markEnqueued(accepted.id);
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
const clearPromptQueues = () => {
|
|
254
|
+
session.clearQueue();
|
|
255
|
+
mailbox.clearQueuedInputs();
|
|
256
|
+
};
|
|
257
|
+
// In 0.99.2 a boundary's continue:false only declines EXTRA continuation;
|
|
258
|
+
// the public core hook is needed to stop automatic tool/steering continuation.
|
|
259
|
+
parkQueue = clearPromptQueues;
|
|
260
|
+
const finishTurn = session.agent.finishTurn;
|
|
261
|
+
session.agent.finishTurn = async (turn, signal) => {
|
|
262
|
+
const decision = await finishTurn?.(turn, signal);
|
|
263
|
+
if (options.shouldPause()) {
|
|
264
|
+
clearPromptQueues();
|
|
265
|
+
return { action: "end" };
|
|
266
|
+
}
|
|
267
|
+
return decision || undefined;
|
|
268
|
+
};
|
|
269
|
+
resolved.set(`${rootId}:${options.path}`, {
|
|
270
|
+
provider: model.provider,
|
|
271
|
+
id: model.id,
|
|
272
|
+
thinking: session.thinkingLevel,
|
|
273
|
+
});
|
|
274
|
+
let disposed = false;
|
|
275
|
+
let running = false;
|
|
276
|
+
let aborted = false;
|
|
277
|
+
let baseline = session.messages.length;
|
|
278
|
+
let finalOutput = "";
|
|
279
|
+
let abortPromise: Promise<void> | undefined;
|
|
280
|
+
const emit = (kind: "activity" | "error", text: string) =>
|
|
281
|
+
options.onEvent({ kind, text: text.slice(0, 1000) });
|
|
282
|
+
const unsubscribe = session.subscribe((event) => {
|
|
283
|
+
if (event.type === "tool_execution_start") emit("activity", `Tool: ${event.toolName}`);
|
|
284
|
+
if (event.type === "tool_execution_end")
|
|
285
|
+
emit(
|
|
286
|
+
event.isError ? "error" : "activity",
|
|
287
|
+
`Tool ${event.toolName}: ${event.isError ? "failed" : "finished"}`,
|
|
288
|
+
);
|
|
289
|
+
if (event.type === "message_end" && event.message.role === "assistant") {
|
|
290
|
+
const text = event.message.content
|
|
291
|
+
.filter((block) => block.type === "text")
|
|
292
|
+
.map((block) => block.text)
|
|
293
|
+
.join("");
|
|
294
|
+
if (text) emit("activity", text);
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
const assertOpen = () => {
|
|
298
|
+
if (disposed) throw new Error("Subagent driver is disposed");
|
|
299
|
+
};
|
|
300
|
+
return {
|
|
301
|
+
get sessionFile() {
|
|
302
|
+
const file = session.sessionFile;
|
|
303
|
+
return file && existsSync(file) ? file : undefined;
|
|
304
|
+
},
|
|
305
|
+
get sessionLeafId() {
|
|
306
|
+
return sessionManager.getLeafId();
|
|
307
|
+
},
|
|
308
|
+
async prompt(message) {
|
|
309
|
+
assertOpen();
|
|
310
|
+
if (running) throw new Error("Subagent is already running; use steer instead");
|
|
311
|
+
running = true;
|
|
312
|
+
aborted = false;
|
|
313
|
+
baseline = session.messages.length;
|
|
314
|
+
finalOutput = "";
|
|
315
|
+
try {
|
|
316
|
+
await resumePending();
|
|
317
|
+
await session.prompt(message, { expandPromptTemplates: false });
|
|
318
|
+
await session.waitForIdle();
|
|
319
|
+
const last = session.messages
|
|
320
|
+
.slice(baseline)
|
|
321
|
+
.filter((msg) => msg.role === "assistant")
|
|
322
|
+
.at(-1);
|
|
323
|
+
if (aborted || last?.stopReason === "aborted") throw new Error("Subagent run aborted");
|
|
324
|
+
if (last?.stopReason === "error")
|
|
325
|
+
throw new Error(last.errorMessage || "Subagent model failed");
|
|
326
|
+
if (last && !options.shouldPause())
|
|
327
|
+
finalOutput = last.content
|
|
328
|
+
.filter((block) => block.type === "text")
|
|
329
|
+
.map((block) => block.text)
|
|
330
|
+
.join("");
|
|
331
|
+
} catch (error) {
|
|
332
|
+
emit("error", error instanceof Error ? error.message : String(error));
|
|
333
|
+
throw error;
|
|
334
|
+
} finally {
|
|
335
|
+
running = false;
|
|
336
|
+
}
|
|
337
|
+
},
|
|
338
|
+
async steer(message) {
|
|
339
|
+
assertOpen();
|
|
340
|
+
await queueAccepted("steer", message);
|
|
341
|
+
},
|
|
342
|
+
snapshot() {
|
|
343
|
+
return structuredClone(session.messages);
|
|
344
|
+
},
|
|
345
|
+
output() {
|
|
346
|
+
return finalOutput;
|
|
347
|
+
},
|
|
348
|
+
async abort() {
|
|
349
|
+
if (disposed) return;
|
|
350
|
+
if (running) aborted = true;
|
|
351
|
+
clearPromptQueues();
|
|
352
|
+
if (!abortPromise)
|
|
353
|
+
abortPromise = session.abort().finally(() => {
|
|
354
|
+
abortPromise = undefined;
|
|
355
|
+
});
|
|
356
|
+
await abortPromise;
|
|
357
|
+
},
|
|
358
|
+
dispose() {
|
|
359
|
+
if (disposed) return;
|
|
360
|
+
disposed = true;
|
|
361
|
+
aborted = true;
|
|
362
|
+
restoreAppends();
|
|
363
|
+
unsubscribe();
|
|
364
|
+
session.dispose();
|
|
365
|
+
},
|
|
366
|
+
async sendUpdate(content) {
|
|
367
|
+
assertOpen();
|
|
368
|
+
try {
|
|
369
|
+
ensurePersistedSession();
|
|
370
|
+
const accepted = mailbox.accept("update", content);
|
|
371
|
+
emitCheckpoint();
|
|
372
|
+
// SDK session method is sendCustomMessage (ExtensionAPI calls it sendMessage).
|
|
373
|
+
await session.sendCustomMessage(
|
|
374
|
+
{
|
|
375
|
+
customType: "subagent-update",
|
|
376
|
+
content,
|
|
377
|
+
display: true,
|
|
378
|
+
details: buildUpdateDetails(accepted),
|
|
379
|
+
},
|
|
380
|
+
{ triggerTurn: false },
|
|
381
|
+
);
|
|
382
|
+
mailbox.markEnqueued(accepted.id);
|
|
383
|
+
} catch (error) {
|
|
384
|
+
emit("error", error instanceof Error ? error.message : String(error));
|
|
385
|
+
throw error;
|
|
386
|
+
}
|
|
387
|
+
},
|
|
388
|
+
};
|
|
389
|
+
};
|
|
390
|
+
}
|
package/src/tools.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { ThreadManager } from "./manager.ts";
|
|
4
|
+
import type { AgentType, ThreadView } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
const path = Type.String({ description: "Absolute agent path, or name relative to the caller" });
|
|
7
|
+
const text = Type.String({ minLength: 1 });
|
|
8
|
+
function compact(thread: ThreadView): ThreadView & { outputTruncated?: boolean } {
|
|
9
|
+
if (thread.output && thread.output.length > 16000)
|
|
10
|
+
return { ...thread, output: thread.output.slice(0, 16000), outputTruncated: true };
|
|
11
|
+
return thread;
|
|
12
|
+
}
|
|
13
|
+
function result(value: unknown) {
|
|
14
|
+
return {
|
|
15
|
+
content: [{ type: "text" as const, text: JSON.stringify(value, null, 2) }],
|
|
16
|
+
details: value,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** All threads see the same verbs, with caller identity bound by closure, never model input. */
|
|
21
|
+
export function agentTools(
|
|
22
|
+
getManager: () => ThreadManager,
|
|
23
|
+
caller: string,
|
|
24
|
+
getTypes: () => AgentType[],
|
|
25
|
+
): ToolDefinition[] {
|
|
26
|
+
const threads = () => getManager().scope(caller);
|
|
27
|
+
const make = (
|
|
28
|
+
name: string,
|
|
29
|
+
description: string,
|
|
30
|
+
parameters: any,
|
|
31
|
+
execute: (params: any, signal?: AbortSignal) => Promise<any> | any,
|
|
32
|
+
): ToolDefinition => ({
|
|
33
|
+
name,
|
|
34
|
+
label: name,
|
|
35
|
+
description,
|
|
36
|
+
parameters,
|
|
37
|
+
execute: async (_id, params, signal) => execute(params, signal),
|
|
38
|
+
});
|
|
39
|
+
return [
|
|
40
|
+
make(
|
|
41
|
+
"agent_types",
|
|
42
|
+
"List current agent types and their task descriptions. Reflects configuration reloads; call this before choosing a type.",
|
|
43
|
+
Type.Object({}),
|
|
44
|
+
() =>
|
|
45
|
+
result(
|
|
46
|
+
getTypes().map(({ name, description, model, thinkingLevel, color }) => ({
|
|
47
|
+
name,
|
|
48
|
+
description,
|
|
49
|
+
model,
|
|
50
|
+
thinkingLevel,
|
|
51
|
+
color,
|
|
52
|
+
})),
|
|
53
|
+
),
|
|
54
|
+
),
|
|
55
|
+
make(
|
|
56
|
+
"agent_spawn",
|
|
57
|
+
"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. Existing paths are retained and can be resumed with agent_steer. Use agent_types to discover current types.",
|
|
58
|
+
Type.Object({ path, type: text, task: text, wait: Type.Optional(Type.Boolean()) }),
|
|
59
|
+
async (params, signal) => result(compact(await threads().spawn(params, signal))),
|
|
60
|
+
),
|
|
61
|
+
make(
|
|
62
|
+
"agent_wait",
|
|
63
|
+
"Wait for a descendant to complete, fail, stop or pause. Paused means no final answer handback. Cancellation/timeouts do not stop the child; poll status or wait again.",
|
|
64
|
+
Type.Object({
|
|
65
|
+
path,
|
|
66
|
+
timeoutMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 3600000 })),
|
|
67
|
+
}),
|
|
68
|
+
async (params, signal) =>
|
|
69
|
+
result(compact(await threads().wait(params.path, params.timeoutMs, signal))),
|
|
70
|
+
),
|
|
71
|
+
make(
|
|
72
|
+
"agent_steer",
|
|
73
|
+
"Send input to a descendant. Working threads receive queued steering; completed, stopped and paused threads resume the SAME session with its previous context. Returns immediately; use agent_wait for the result.",
|
|
74
|
+
Type.Object({ path, message: text }),
|
|
75
|
+
async (params) => result(compact(await threads().steer(params.path, params.message))),
|
|
76
|
+
),
|
|
77
|
+
make(
|
|
78
|
+
"agent_status",
|
|
79
|
+
"Read a thread's status or list visible descendants. Root can inspect all trees. Completion retains the session; pause retains it without final answer handback.",
|
|
80
|
+
Type.Object({ path: Type.Optional(path) }),
|
|
81
|
+
(params) =>
|
|
82
|
+
result(params.path ? compact(threads().get(params.path)) : threads().list().map(compact)),
|
|
83
|
+
),
|
|
84
|
+
make(
|
|
85
|
+
"agent_update",
|
|
86
|
+
"Child-only: send progress to the parent without ending this task. Delivery is recorded and displayed but does not interrupt or automatically restart the parent model.",
|
|
87
|
+
Type.Object({ message: Type.String({ minLength: 1, maxLength: 8000 }) }),
|
|
88
|
+
(params) => result(compact(threads().update(params.message))),
|
|
89
|
+
),
|
|
90
|
+
make(
|
|
91
|
+
"agent_pause",
|
|
92
|
+
"Child-only: stop at this turn boundary WITHOUT returning a final answer. Keep the SAME session for user/parent input via agent_steer. To finish and hand back an answer instead, simply return your final assistant answer. Both states can be resumed.",
|
|
93
|
+
Type.Object({ reason: text }),
|
|
94
|
+
(params) => ({
|
|
95
|
+
...result({
|
|
96
|
+
path: caller,
|
|
97
|
+
pauseRequested: true,
|
|
98
|
+
status: threads().pause(params.reason).status,
|
|
99
|
+
}),
|
|
100
|
+
terminate: true,
|
|
101
|
+
}),
|
|
102
|
+
),
|
|
103
|
+
make(
|
|
104
|
+
"agent_stop",
|
|
105
|
+
"Stop a descendant and its working children. Session history is retained; resume with agent_steer. This is cooperative cancellation, not sandbox process termination.",
|
|
106
|
+
Type.Object({ path }),
|
|
107
|
+
async (params) => result(compact(await threads().stop(params.path))),
|
|
108
|
+
),
|
|
109
|
+
make(
|
|
110
|
+
"agent_output",
|
|
111
|
+
"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.",
|
|
112
|
+
Type.Object({
|
|
113
|
+
path,
|
|
114
|
+
offset: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
115
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 16000 })),
|
|
116
|
+
}),
|
|
117
|
+
(params) => {
|
|
118
|
+
const output = threads().output(params.path),
|
|
119
|
+
offset = params.offset ?? 0,
|
|
120
|
+
limit = params.limit ?? 8000;
|
|
121
|
+
return result({
|
|
122
|
+
path: threads().get(params.path).path,
|
|
123
|
+
text: output.slice(offset, offset + limit),
|
|
124
|
+
totalCharacters: output.length,
|
|
125
|
+
nextOffset: offset + limit < output.length ? offset + limit : null,
|
|
126
|
+
});
|
|
127
|
+
},
|
|
128
|
+
),
|
|
129
|
+
];
|
|
130
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
|
|
4
|
+
export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
5
|
+
export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
|
|
6
|
+
export interface AgentType {
|
|
7
|
+
name: string;
|
|
8
|
+
description: string;
|
|
9
|
+
model?: string;
|
|
10
|
+
thinkingLevel?: ThinkingLevel;
|
|
11
|
+
color?: string;
|
|
12
|
+
tools?: { allow?: string[]; block?: string[] };
|
|
13
|
+
systemPrompt: string;
|
|
14
|
+
filePath?: string;
|
|
15
|
+
source?: "bundled" | "user" | "project";
|
|
16
|
+
}
|
|
17
|
+
export type ThreadState = "starting" | "running" | "paused" | "completed" | "failed" | "stopped";
|
|
18
|
+
export interface ThreadView {
|
|
19
|
+
path: string;
|
|
20
|
+
parent: string | null;
|
|
21
|
+
owner: string;
|
|
22
|
+
type: string;
|
|
23
|
+
color?: string;
|
|
24
|
+
state: ThreadState;
|
|
25
|
+
task: string;
|
|
26
|
+
status: string;
|
|
27
|
+
output?: string;
|
|
28
|
+
error?: string;
|
|
29
|
+
createdAt: number;
|
|
30
|
+
updatedAt: number;
|
|
31
|
+
sessionFile?: string;
|
|
32
|
+
}
|
|
33
|
+
export type DriverEvent =
|
|
34
|
+
| { kind: "activity" | "error"; text: string }
|
|
35
|
+
| {
|
|
36
|
+
kind: "checkpoint";
|
|
37
|
+
text: string;
|
|
38
|
+
sessionFile?: string;
|
|
39
|
+
sessionLeafId?: string | null;
|
|
40
|
+
};
|
|
41
|
+
export interface AgentDriver {
|
|
42
|
+
prompt(message: string): Promise<void>;
|
|
43
|
+
steer(message: string): Promise<void>;
|
|
44
|
+
snapshot(): AgentMessage[];
|
|
45
|
+
output(): string;
|
|
46
|
+
abort(): Promise<void>;
|
|
47
|
+
dispose(): void;
|
|
48
|
+
sendUpdate(content: string): Promise<void> | void;
|
|
49
|
+
sessionFile?: string;
|
|
50
|
+
sessionLeafId?: string | null;
|
|
51
|
+
}
|
|
52
|
+
export interface DriverOptions {
|
|
53
|
+
path: string;
|
|
54
|
+
type: AgentType;
|
|
55
|
+
inherited: AgentMessage[];
|
|
56
|
+
tools: ToolDefinition[];
|
|
57
|
+
onEvent(event: DriverEvent): void;
|
|
58
|
+
shouldPause(): boolean;
|
|
59
|
+
parentPath: string | null;
|
|
60
|
+
sessionFile?: string;
|
|
61
|
+
sessionLeafId?: string | null;
|
|
62
|
+
signal: AbortSignal;
|
|
63
|
+
}
|
|
64
|
+
export interface SavedThreadView {
|
|
65
|
+
path: string;
|
|
66
|
+
parent: string | null;
|
|
67
|
+
owner: string;
|
|
68
|
+
type: string;
|
|
69
|
+
color?: string;
|
|
70
|
+
state: ThreadState;
|
|
71
|
+
task: string;
|
|
72
|
+
status: string;
|
|
73
|
+
output?: string;
|
|
74
|
+
error?: string;
|
|
75
|
+
createdAt: number;
|
|
76
|
+
sessionFile?: string;
|
|
77
|
+
sessionLeafId?: string | null;
|
|
78
|
+
}
|
|
79
|
+
export interface SavedThread {
|
|
80
|
+
view: SavedThreadView;
|
|
81
|
+
definition: AgentType;
|
|
82
|
+
/** Reserved threads may not have a transcript yet; preserve their initial context. */
|
|
83
|
+
inherited?: AgentMessage[];
|
|
84
|
+
}
|
|
85
|
+
export interface ThreadService {
|
|
86
|
+
list(): ThreadView[];
|
|
87
|
+
get(path: string): ThreadView;
|
|
88
|
+
output(path: string): string;
|
|
89
|
+
transcript(path: string): Promise<string>;
|
|
90
|
+
spawn(
|
|
91
|
+
args: { path: string; type: string; task: string; wait?: boolean },
|
|
92
|
+
signal?: AbortSignal,
|
|
93
|
+
): Promise<ThreadView>;
|
|
94
|
+
steer(path: string, message: string): Promise<ThreadView>;
|
|
95
|
+
wait(path: string, timeoutMs?: number, signal?: AbortSignal): Promise<ThreadView>;
|
|
96
|
+
update(message: string): ThreadView;
|
|
97
|
+
pause(reason: string): ThreadView;
|
|
98
|
+
stop(path: string): Promise<ThreadView>;
|
|
99
|
+
}
|
|
100
|
+
export type DriverFactory = (options: DriverOptions) => Promise<AgentDriver>;
|
|
101
|
+
export type ThreadEvent =
|
|
102
|
+
| { kind: "change"; thread: ThreadView }
|
|
103
|
+
| { kind: "update"; thread: ThreadView; message: string; recipient: string }
|
|
104
|
+
| { kind: "settled"; thread: ThreadView; recipient: string };
|
|
105
|
+
export interface ManagerOptions {
|
|
106
|
+
createDriver: DriverFactory;
|
|
107
|
+
rootSnapshot(): AgentMessage[];
|
|
108
|
+
getType(name: string): AgentType;
|
|
109
|
+
toolsFor(path: string): ToolDefinition[];
|
|
110
|
+
onEvent?(event: ThreadEvent): void;
|
|
111
|
+
maxDepth?: number;
|
|
112
|
+
maxThreads?: number;
|
|
113
|
+
maxConcurrent?: number;
|
|
114
|
+
}
|