@giladbarnea/pi-simple-team 1.0.46 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -12
- package/child-tools.ts +24 -22
- package/index.ts +388 -302
- package/model-preflight.ts +1 -1
- package/package.json +1 -1
- package/render.ts +62 -58
- package/system-prompt.ts +11 -12
- package/team-registry.ts +13 -26
- package/team-selection.ts +57 -0
- package/team-ui.ts +16 -7
- package/teamlog.ts +26 -8
- package/teammate.ts +18 -0
package/index.ts
CHANGED
|
@@ -28,8 +28,8 @@ import { renderReminderToolCall, renderReminderToolResult, renderTeamMessage, re
|
|
|
28
28
|
import { openTeamOverview, type TeamSnapshot } from "./team-ui.ts";
|
|
29
29
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
30
30
|
import { Type } from "typebox";
|
|
31
|
-
|
|
32
|
-
type
|
|
31
|
+
import { resolveTargets, resolveTeammates, interruptedTeammateIds, targetDescription, interruptDescription, type SelectableTeam } from "./team-selection.ts";
|
|
32
|
+
import type { Teammate, TeammateRecord, ThinkingLevel } from "./teammate.ts";
|
|
33
33
|
|
|
34
34
|
type JsonRecord = Record<string, unknown>;
|
|
35
35
|
|
|
@@ -39,15 +39,6 @@ interface TeamStatus {
|
|
|
39
39
|
updated: string;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
interface TeammateSpec {
|
|
43
|
-
name: string;
|
|
44
|
-
prompt: string;
|
|
45
|
-
model: string;
|
|
46
|
-
thinking?: ThinkingLevel;
|
|
47
|
-
inheritContext?: boolean;
|
|
48
|
-
canOverseeOwnTeams?: boolean;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
42
|
type TeammateTransport = "rpc" | "herdr";
|
|
52
43
|
|
|
53
44
|
interface TeammateState {
|
|
@@ -55,8 +46,8 @@ interface TeammateState {
|
|
|
55
46
|
prompt: string;
|
|
56
47
|
model: string;
|
|
57
48
|
thinking: ThinkingLevel;
|
|
58
|
-
|
|
59
|
-
|
|
49
|
+
inheritMainContext: boolean;
|
|
50
|
+
canManageOwnTeams: boolean;
|
|
60
51
|
transport: TeammateTransport;
|
|
61
52
|
sessionId?: string;
|
|
62
53
|
sessionFile?: string;
|
|
@@ -68,6 +59,8 @@ interface TeammateState {
|
|
|
68
59
|
resolveReady?: () => void;
|
|
69
60
|
rejectReady?: (error: Error) => void;
|
|
70
61
|
alive: boolean;
|
|
62
|
+
active: boolean;
|
|
63
|
+
pendingTurnDeliveries: number;
|
|
71
64
|
deliveryQueue: Promise<void>;
|
|
72
65
|
}
|
|
73
66
|
|
|
@@ -99,6 +92,7 @@ const teamMessageType = "pi-simple-team";
|
|
|
99
92
|
const teams = new Map<string, TeamState>();
|
|
100
93
|
const callbackToken = crypto.randomBytes(24).toString("hex");
|
|
101
94
|
let callbackServer: http.Server | undefined;
|
|
95
|
+
let callbackReady: Promise<void> | undefined;
|
|
102
96
|
let callbackUrl = "";
|
|
103
97
|
|
|
104
98
|
function status(word: string, phrase: string): TeamStatus {
|
|
@@ -118,6 +112,58 @@ function toolResult(payload: JsonRecord) {
|
|
|
118
112
|
};
|
|
119
113
|
}
|
|
120
114
|
|
|
115
|
+
/** @example teamIdentity({ name: "review", id: "session-review" }) // { teamName: "review", teamId: "session-review" } */
|
|
116
|
+
function teamIdentity(team: { name: string; id?: string }): { teamName: string; teamId: string } {
|
|
117
|
+
return { teamName: team.name, teamId: team.id ?? team.name };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** @example teammateReference({ name: "reviewer", sessionId: "pi-session" }) // { name: "reviewer", teammateId: "pi-session" } */
|
|
121
|
+
function teammateReference(teammate: { name: string; sessionId?: string }): { name: string; teammateId: string } {
|
|
122
|
+
return { name: teammate.name, teammateId: teammate.sessionId! };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** @example teammateSummary(idleTeammate).active // false */
|
|
126
|
+
function teammateSummary(teammate: TeammateState): Pick<TeammateRecord, "name" | "teammateId" | "live" | "active"> {
|
|
127
|
+
return { ...teammateReference(teammate), live: teammate.alive, active: teammate.alive && (teammate.active || teammate.pendingTurnDeliveries > 0) };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** @example teammateRecord(teammate).teammateId === teammate.sessionId */
|
|
131
|
+
function teammateRecord(teammate: TeammateState): TeammateRecord {
|
|
132
|
+
return {
|
|
133
|
+
...teammateSummary(teammate),
|
|
134
|
+
systemPrompt: teammate.prompt,
|
|
135
|
+
model: teammate.model,
|
|
136
|
+
thinking: teammate.thinking,
|
|
137
|
+
inheritMainContext: teammate.inheritMainContext,
|
|
138
|
+
canManageOwnTeams: teammate.canManageOwnTeams,
|
|
139
|
+
showOnHerdrPane: teammate.transport === "herdr",
|
|
140
|
+
sessionFile: teammate.sessionFile!,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** @example lifecycleInstruction(true).includes("idle") // true */
|
|
145
|
+
function lifecycleInstruction(startIdle: boolean): string {
|
|
146
|
+
const nextAction = startIdle
|
|
147
|
+
? "No teammates have active work. Use team_send_message to start idle teammates, or team_resume for stopped teammates."
|
|
148
|
+
: "Teammates will message you with milestones or requests for help. Avoid repeated status polling and shell sleeps. Set your status to explain what you expect from them. If you have no independent work, tell the user and end your turn. Ask the user whether to schedule progress checks every 15 minutes. If they agree, use schedule_reminder. After each check, schedule the next while the team needs oversight.";
|
|
149
|
+
return `${bundledSkillsInstruction}\n\n${nextAction}`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** @example lifecycleResult(emptyTeam).started // false */
|
|
153
|
+
function lifecycleResult(team: TeamState): JsonRecord {
|
|
154
|
+
const teammates = [...team.members.values()].map(teammateRecord);
|
|
155
|
+
const started = teammates.some((teammate) => teammate.active);
|
|
156
|
+
return { ...teamIdentity(team), started, teammates, instruction: teammates.length > 0 ? lifecycleInstruction(!started) : bundledSkillsInstruction };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** @example mainMessageResult(team).published // true */
|
|
160
|
+
function mainMessageResult(team: TeamState): JsonRecord {
|
|
161
|
+
return {
|
|
162
|
+
...teamIdentity(team), published: true, status: formatStatus(team),
|
|
163
|
+
instruction: "Do not wait for a reply. Continue your work or set your status to explain what you need from main.",
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
121
167
|
interface CommandResult {
|
|
122
168
|
stdout: string;
|
|
123
169
|
stderr: string;
|
|
@@ -127,7 +173,7 @@ function runCommand(command: string, args: string[], timeoutMilliseconds = 30_00
|
|
|
127
173
|
return new Promise((resolve, reject) => {
|
|
128
174
|
childProcess.execFile(command, args, { timeout: timeoutMilliseconds, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
|
|
129
175
|
if (error) {
|
|
130
|
-
reject(new Error(`${command} ${args.join(" ")} failed: ${
|
|
176
|
+
reject(new Error(`${command} ${args.slice(0, 2).join(" ")} failed: ${stderr.trim() || error.message}`));
|
|
131
177
|
return;
|
|
132
178
|
}
|
|
133
179
|
resolve({ stdout, stderr });
|
|
@@ -138,6 +184,8 @@ function runCommand(command: string, args: string[], timeoutMilliseconds = 30_00
|
|
|
138
184
|
async function validateHerdrAvailability(): Promise<string> {
|
|
139
185
|
const tabId = process.env.HERDR_TAB_ID?.trim();
|
|
140
186
|
if (!tabId) throw new Error("showOnHerdrPanes requires HERDR_TAB_ID in the main Pi process");
|
|
187
|
+
const paneId = process.env.HERDR_PANE_ID?.trim();
|
|
188
|
+
if (!paneId) throw new Error("Visible teammates require a parent Herdr pane. Run the main Pi session in Herdr, or set showOnHerdrPane to false.");
|
|
141
189
|
|
|
142
190
|
let result: CommandResult;
|
|
143
191
|
try {
|
|
@@ -150,14 +198,14 @@ async function validateHerdrAvailability(): Promise<string> {
|
|
|
150
198
|
if (!status.server?.running || status.server.compatible === false) {
|
|
151
199
|
throw new Error("showOnHerdrPanes requires a running compatible Herdr server");
|
|
152
200
|
}
|
|
153
|
-
return
|
|
201
|
+
return paneId;
|
|
154
202
|
}
|
|
155
203
|
|
|
156
204
|
function formatTeammateMessage(team: TeamState, from: string, message: string): string {
|
|
157
205
|
return [`[from ${from} on team ${team.name}]`, message, "", "Current team status:", JSON.stringify(formatStatus(team), null, 2)].join("\n");
|
|
158
206
|
}
|
|
159
207
|
|
|
160
|
-
async function deliverMessage(team: TeamState, from: string, recipient: TeammateState, message: string, formattedMessage: string, interrupt: boolean): Promise<void> {
|
|
208
|
+
async function deliverMessage(team: TeamState, from: string, recipient: TeammateState, message: string, formattedMessage: string, interrupt: boolean, triggerTurn = true): Promise<void> {
|
|
161
209
|
if (!recipient.alive || !recipient.deliveryUrl) throw new Error(`Teammate ${recipient.name} is not ready`);
|
|
162
210
|
const controller = new AbortController();
|
|
163
211
|
const timeout = setTimeout(() => controller.abort(), deliveryTimeoutMilliseconds);
|
|
@@ -168,7 +216,7 @@ async function deliverMessage(team: TeamState, from: string, recipient: Teammate
|
|
|
168
216
|
body: JSON.stringify({
|
|
169
217
|
token: callbackToken,
|
|
170
218
|
tool: "deliver",
|
|
171
|
-
args: { team: team.name, from, to: recipient.name, sentAt: new Date().toISOString(), message, formattedMessage, interrupt },
|
|
219
|
+
args: { team: team.name, from, to: recipient.name, sentAt: new Date().toISOString(), message, formattedMessage, interrupt, triggerTurn },
|
|
172
220
|
}),
|
|
173
221
|
signal: controller.signal,
|
|
174
222
|
});
|
|
@@ -184,7 +232,7 @@ async function deliverMessage(team: TeamState, from: string, recipient: Teammate
|
|
|
184
232
|
}
|
|
185
233
|
}
|
|
186
234
|
|
|
187
|
-
async function deliverToTeammate(team: TeamState, from: string, recipient: TeammateState, message: string, interrupt: boolean): Promise<void> {
|
|
235
|
+
async function deliverToTeammate(team: TeamState, from: string, recipient: TeammateState, message: string, interrupt: boolean, triggerTurn = true): Promise<void> {
|
|
188
236
|
const formattedMessage = formatTeammateMessage(team, from, message);
|
|
189
237
|
appendTeamLog(team, {
|
|
190
238
|
team: team.name,
|
|
@@ -192,36 +240,76 @@ async function deliverToTeammate(team: TeamState, from: string, recipient: Teamm
|
|
|
192
240
|
direction: from === "main" ? "main->teammate" : "teammate->teammate",
|
|
193
241
|
kind: "deliver",
|
|
194
242
|
summary: preview(message),
|
|
195
|
-
details: { from, to: recipient.name, interrupt },
|
|
243
|
+
details: { from, to: recipient.name, interrupt, triggerTurn },
|
|
196
244
|
});
|
|
197
|
-
await deliverMessage(team, from, recipient, message, formattedMessage, interrupt);
|
|
245
|
+
await deliverMessage(team, from, recipient, message, formattedMessage, interrupt, triggerTurn);
|
|
198
246
|
}
|
|
199
247
|
|
|
200
|
-
function
|
|
248
|
+
function queueDelivery(team: TeamState, from: string, recipient: TeammateState, message: string, interrupt: boolean, triggerTurn = true): Promise<void> {
|
|
201
249
|
appendTeamLog(team, {
|
|
202
250
|
team: team.name,
|
|
203
251
|
teammate: recipient.name,
|
|
204
252
|
direction: from === "main" ? "main->teammate" : "teammate->teammate",
|
|
205
253
|
kind: "send",
|
|
206
254
|
summary: preview(message),
|
|
207
|
-
details: { from, to: recipient.name, interrupt, message },
|
|
255
|
+
details: { from, to: recipient.name, interrupt, message, triggerTurn },
|
|
208
256
|
});
|
|
257
|
+
if (triggerTurn) recipient.pendingTurnDeliveries += 1;
|
|
258
|
+
const delivery = recipient.deliveryQueue.then(() => deliverToTeammate(team, from, recipient, message, interrupt, triggerTurn)).finally(() => {
|
|
259
|
+
if (triggerTurn) recipient.pendingTurnDeliveries -= 1;
|
|
260
|
+
persistActiveTeamManifest(team);
|
|
261
|
+
});
|
|
262
|
+
recipient.deliveryQueue = delivery.catch(() => undefined);
|
|
263
|
+
return delivery;
|
|
264
|
+
}
|
|
209
265
|
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
.
|
|
214
|
-
|
|
215
|
-
team.
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
summary: preview(`delivery to ${recipient.name} failed: ${errorMessage}`),
|
|
222
|
-
details: { from, to: recipient.name, error: errorMessage },
|
|
223
|
-
});
|
|
266
|
+
function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState, message: string, interrupt: boolean): void {
|
|
267
|
+
void queueDelivery(team, from, recipient, message, interrupt).catch(async (error) => {
|
|
268
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
269
|
+
team.statuses.set(recipient.name, status("error", errorMessage));
|
|
270
|
+
appendTeamLog(team, {
|
|
271
|
+
team: team.name,
|
|
272
|
+
teammate: recipient.name,
|
|
273
|
+
direction: from === "main" ? "main->teammate" : "teammate->teammate",
|
|
274
|
+
kind: "error",
|
|
275
|
+
summary: preview(`delivery to ${recipient.name} failed: ${errorMessage}`),
|
|
276
|
+
details: { from, to: recipient.name, error: errorMessage },
|
|
224
277
|
});
|
|
278
|
+
const notification = `Message delivery failed for teammate "${recipient.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}).\nOriginal message:\n${message}\nCause: ${errorMessage}\nCheck the teammate's status before retrying.`;
|
|
279
|
+
try {
|
|
280
|
+
if (from === "main") {
|
|
281
|
+
team.ownerPi.sendMessage(
|
|
282
|
+
{ customType: teamMessageType, content: notification, display: true, details: { team: team.name, from: "runtime", sentAt: new Date().toISOString(), message: notification } },
|
|
283
|
+
{ deliverAs: "steer", triggerTurn: true },
|
|
284
|
+
);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
await deliverToTeammate(team, "runtime", team.members.get(from)!, notification, false);
|
|
288
|
+
} catch (notificationError) {
|
|
289
|
+
appendTeamLog(team, { team: team.name, teammate: from, direction: "runtime", kind: "error", summary: `Could not notify sender "${from}" of delivery failure: ${notificationError instanceof Error ? notificationError.message : String(notificationError)}` });
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumptionPrompt?: string): Promise<void> {
|
|
295
|
+
if (startIdle && resumptionPrompt === undefined) return;
|
|
296
|
+
const outcomes = await Promise.allSettled(teammates.map((teammate) => {
|
|
297
|
+
// A fork can continue main's workflow unless its latest message restates its own assignment.
|
|
298
|
+
const assignment = `You are teammate "${teammate.name}" on team "${team.name}". Work on your individual assignment, continuing from any prior progress:\n\n${teammate.prompt}\n\nMain coordinates the team. If you inherited main's conversation, use it as background for your own assignment.`;
|
|
299
|
+
return queueDelivery(team, "main", teammate, resumptionPrompt ?? assignment, false, !startIdle);
|
|
300
|
+
}));
|
|
301
|
+
const completed = teammates.filter((_teammate, index) => outcomes[index].status === "fulfilled").map((teammate) => teammate.name);
|
|
302
|
+
const errors = outcomes.flatMap((outcome, index) => {
|
|
303
|
+
if (outcome.status === "fulfilled") return [];
|
|
304
|
+
const teammate = teammates[index];
|
|
305
|
+
const cause: unknown = outcome.reason;
|
|
306
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
307
|
+
team.statuses.set(teammate.name, status("error", message));
|
|
308
|
+
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "error", summary: message });
|
|
309
|
+
return [`${teammate.name}: ${message}`];
|
|
310
|
+
});
|
|
311
|
+
if (errors.length === 0) return;
|
|
312
|
+
throw new Error(`Team "${team.name}" (team ID: ${team.id ?? team.name}) remains active. ${startIdle ? "Instructions recorded for" : "Work started for"}: ${JSON.stringify(completed)}. Failed teammates: ${errors.join("; ")}. Inspect team_status before retrying; do not spawn the team again.`);
|
|
225
313
|
}
|
|
226
314
|
|
|
227
315
|
/** @example resolveTeamIdentifier([{ id: "main-review", name: "review" }], "review")?.id // "main-review" */
|
|
@@ -230,21 +318,27 @@ function resolveTeamIdentifier<IdentifiedTeam extends { id?: string; name: strin
|
|
|
230
318
|
teamIdentifier: string,
|
|
231
319
|
): IdentifiedTeam | undefined {
|
|
232
320
|
const matches = [...candidates].filter((team) => team.id === teamIdentifier || team.name === teamIdentifier);
|
|
233
|
-
if (matches.length > 1) throw new Error(`Ambiguous team name: ${teamIdentifier}. Pass the persistent team ID.`);
|
|
321
|
+
if (matches.length > 1) throw new Error(`Ambiguous team name: ${JSON.stringify(teamIdentifier)}. Available team IDs by name: ${JSON.stringify(teamChoices(matches))}. Pass the intended persistent team ID in the team parameter.`);
|
|
234
322
|
return matches[0];
|
|
235
323
|
}
|
|
236
324
|
|
|
325
|
+
/** @example teamChoices([{ name: "review", id: "first-review" }, { name: "review", id: "second-review" }]) // { review: ["first-review", "second-review"] } */
|
|
326
|
+
function teamChoices(candidates: Iterable<{ name: string; id?: string }>): Record<string, string[]> {
|
|
327
|
+
const choices = [...candidates];
|
|
328
|
+
return Object.fromEntries([...new Set(choices.map((team) => team.name))].map((name) => [name, choices.filter((team) => team.name === name).map((team) => team.id ?? team.name)]));
|
|
329
|
+
}
|
|
330
|
+
|
|
237
331
|
function resolveTeam(owner: symbol, teamIdentifier?: string): TeamState {
|
|
238
332
|
const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
|
|
239
333
|
if (teamIdentifier) {
|
|
240
334
|
const team = resolveTeamIdentifier(ownedTeams, teamIdentifier);
|
|
241
|
-
if (!team) throw new Error(`Unknown team: ${teamIdentifier}
|
|
335
|
+
if (!team) throw new Error(`Unknown team: ${JSON.stringify(teamIdentifier)}. Available owned team IDs by name: ${JSON.stringify(teamChoices(ownedTeams))}. Use team_list to find dormant teams, or pass an owned active team name or ID in the team parameter.`);
|
|
242
336
|
return team;
|
|
243
337
|
}
|
|
244
338
|
|
|
245
339
|
if (ownedTeams.length === 1) return ownedTeams[0];
|
|
246
|
-
if (ownedTeams.length === 0) throw new Error("No teams
|
|
247
|
-
throw new Error(`Multiple teams exist: ${
|
|
340
|
+
if (ownedTeams.length === 0) throw new Error("No active teams are owned by this session. Use team_spawn or team_resume first.");
|
|
341
|
+
throw new Error(`Multiple teams exist. Available team IDs by name: ${JSON.stringify(teamChoices(ownedTeams))}. Pass team explicitly using the intended team ID.`);
|
|
248
342
|
}
|
|
249
343
|
|
|
250
344
|
function resolveCallbackTeam(teamName: string): TeamState {
|
|
@@ -253,26 +347,13 @@ function resolveCallbackTeam(teamName: string): TeamState {
|
|
|
253
347
|
return team;
|
|
254
348
|
}
|
|
255
349
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
const missing = names.filter((name, index) => recipients[index] === undefined);
|
|
260
|
-
if (missing.length > 0) throw new Error(`Unknown teammate(s) in ${team.name}: ${missing.join(", ")}`);
|
|
261
|
-
return recipients as TeammateState[];
|
|
350
|
+
/** @example selectableTeam(team).teammates[0].teammateId === team.members.values().next().value.sessionId */
|
|
351
|
+
function selectableTeam(team: TeamState): SelectableTeam {
|
|
352
|
+
return { ...teamIdentity(team), teammates: [...team.members.values()].map(teammateReference) };
|
|
262
353
|
}
|
|
263
354
|
|
|
264
|
-
function
|
|
265
|
-
|
|
266
|
-
const names = targetNames.map(compactName).filter((name) => name !== "main");
|
|
267
|
-
return names.map((name) => {
|
|
268
|
-
const matches = ownedTeams.flatMap((team) => {
|
|
269
|
-
const teammate = team.members.get(name);
|
|
270
|
-
return teammate ? [teammate] : [];
|
|
271
|
-
});
|
|
272
|
-
if (matches.length === 0) throw new Error(`Unknown teammate: ${name}`);
|
|
273
|
-
if (matches.length > 1) throw new Error(`Ambiguous teammate across teams: ${name}`);
|
|
274
|
-
return matches[0];
|
|
275
|
-
});
|
|
355
|
+
function ownedTargetTeams(owner: symbol): SelectableTeam[] {
|
|
356
|
+
return [...teams.values()].filter((team) => team.owner === owner).map(selectableTeam);
|
|
276
357
|
}
|
|
277
358
|
|
|
278
359
|
async function getTeammateContextUsage(teammate: TeammateState, signal?: AbortSignal): Promise<KnownContextUsage> {
|
|
@@ -280,7 +361,7 @@ async function getTeammateContextUsage(teammate: TeammateState, signal?: AbortSi
|
|
|
280
361
|
const response = await fetch(teammate.deliveryUrl, {
|
|
281
362
|
method: "POST",
|
|
282
363
|
headers: { "content-type": "application/json" },
|
|
283
|
-
body: JSON.stringify({ token: callbackToken, tool: "
|
|
364
|
+
body: JSON.stringify({ token: callbackToken, tool: "get_context_window_usage", args: {} }),
|
|
284
365
|
signal,
|
|
285
366
|
});
|
|
286
367
|
if (!response.ok) throw new Error(`Teammate ${teammate.name} rejected context-window query: ${response.status} ${await response.text()}`);
|
|
@@ -292,8 +373,8 @@ function formatStatus(team: TeamState): Record<string, TeamStatus> {
|
|
|
292
373
|
return Object.fromEntries([...team.statuses.entries()].sort(([a], [b]) => a.localeCompare(b)));
|
|
293
374
|
}
|
|
294
375
|
|
|
295
|
-
function allStatuses(owner: symbol):
|
|
296
|
-
return
|
|
376
|
+
function allStatuses(owner: symbol): Array<{ teamName: string; teamId: string; status: Record<string, TeamStatus> }> {
|
|
377
|
+
return [...teams.values()].filter((team) => team.owner === owner).map((team) => ({ ...teamIdentity(team), status: formatStatus(team) }));
|
|
297
378
|
}
|
|
298
379
|
|
|
299
380
|
function ownedTeamSnapshots(owner: symbol): TeamSnapshot[] {
|
|
@@ -302,7 +383,7 @@ function ownedTeamSnapshots(owner: symbol): TeamSnapshot[] {
|
|
|
302
383
|
.map((team) => ({
|
|
303
384
|
name: team.name,
|
|
304
385
|
created: team.created,
|
|
305
|
-
|
|
386
|
+
transports: (["rpc", "herdr"] as const).filter((transport) => [...team.members.values()].some((teammate) => teammate.alive && teammate.transport === transport)),
|
|
306
387
|
roster: [...team.members.keys()],
|
|
307
388
|
statuses: formatStatus(team),
|
|
308
389
|
log: [...team.log],
|
|
@@ -315,7 +396,7 @@ function updateStatus(team: TeamState, participant: string, word?: string, phras
|
|
|
315
396
|
team.statuses.set(participant, status(word ?? previous.word, phrase ?? previous.phrase));
|
|
316
397
|
}
|
|
317
398
|
|
|
318
|
-
/** Pure status reads are meta-actions and stay out of the log, like
|
|
399
|
+
/** Pure status reads are meta-actions and stay out of the log, like team_log reads. */
|
|
319
400
|
function logStatusDeclaration(team: TeamState, participant: string, word?: string, phrase?: string): void {
|
|
320
401
|
if (word === undefined && phrase === undefined) return;
|
|
321
402
|
appendTeamLog(team, {
|
|
@@ -328,7 +409,7 @@ function logStatusDeclaration(team: TeamState, participant: string, word?: strin
|
|
|
328
409
|
});
|
|
329
410
|
}
|
|
330
411
|
|
|
331
|
-
function createTeammateState(
|
|
412
|
+
function createTeammateState(teammateSpec: Teammate): TeammateState {
|
|
332
413
|
const teammateName = compactName(teammateSpec.name);
|
|
333
414
|
const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
|
|
334
415
|
let resolveReady: (() => void) | undefined;
|
|
@@ -340,17 +421,19 @@ function createTeammateState(team: TeamState, teammateSpec: TeammateSpec): Teamm
|
|
|
340
421
|
|
|
341
422
|
return {
|
|
342
423
|
name: teammateName,
|
|
343
|
-
prompt: teammateSpec.
|
|
424
|
+
prompt: teammateSpec.systemPrompt,
|
|
344
425
|
model: teammateSpec.model,
|
|
345
426
|
thinking,
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
transport:
|
|
427
|
+
inheritMainContext: Boolean(teammateSpec.inheritMainContext),
|
|
428
|
+
canManageOwnTeams: Boolean(teammateSpec.canManageOwnTeams),
|
|
429
|
+
transport: teammateSpec.showOnHerdrPane ? "herdr" : "rpc",
|
|
349
430
|
sessionMaterialized: false,
|
|
350
431
|
ready,
|
|
351
432
|
resolveReady,
|
|
352
433
|
rejectReady,
|
|
353
434
|
alive: true,
|
|
435
|
+
active: false,
|
|
436
|
+
pendingTurnDeliveries: 0,
|
|
354
437
|
deliveryQueue: Promise.resolve(),
|
|
355
438
|
};
|
|
356
439
|
}
|
|
@@ -364,7 +447,7 @@ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, par
|
|
|
364
447
|
PI_SIMPLE_TEAM_TEAM_NAME: team.name,
|
|
365
448
|
PI_SIMPLE_TEAM_MEMBER: teammate.name,
|
|
366
449
|
PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
|
|
367
|
-
|
|
450
|
+
PI_SIMPLE_TEAM_CAN_MANAGE_OWN_TEAMS: teammate.canManageOwnTeams ? "1" : "0",
|
|
368
451
|
};
|
|
369
452
|
}
|
|
370
453
|
|
|
@@ -374,20 +457,21 @@ function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
|
|
|
374
457
|
teammate: teammate.name,
|
|
375
458
|
direction: "runtime",
|
|
376
459
|
kind: "spawn",
|
|
377
|
-
summary: `spawned ${teammate.name} (model=${teammate.model}, thinking=${teammate.thinking}, context=${teammate.
|
|
378
|
-
details: { model: teammate.model, thinking: teammate.thinking,
|
|
460
|
+
summary: `spawned ${teammate.name} (model=${teammate.model}, thinking=${teammate.thinking}, context=${teammate.inheritMainContext ? "inherited" : "fresh"})`,
|
|
461
|
+
details: { model: teammate.model, thinking: teammate.thinking, inheritMainContext: teammate.inheritMainContext, transport: teammate.transport, paneId: teammate.paneId },
|
|
379
462
|
});
|
|
380
463
|
}
|
|
381
464
|
|
|
382
465
|
interface ChildStartOptions {
|
|
383
466
|
sessionFile?: string;
|
|
384
467
|
restartEmpty?: boolean;
|
|
468
|
+
signal?: AbortSignal;
|
|
385
469
|
}
|
|
386
470
|
|
|
387
471
|
function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[], options: ChildStartOptions): void {
|
|
388
472
|
const sessionArgs = options.sessionFile
|
|
389
473
|
? ["--session", options.sessionFile]
|
|
390
|
-
: teammate.
|
|
474
|
+
: teammate.inheritMainContext && !options.restartEmpty
|
|
391
475
|
? ["--fork", team.mainSessionFile!]
|
|
392
476
|
: [];
|
|
393
477
|
const modelArgs = options.sessionFile ? [] : ["--model", teammate.model, "--thinking", teammate.thinking];
|
|
@@ -402,7 +486,7 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
402
486
|
"--no-themes",
|
|
403
487
|
...modelArgs,
|
|
404
488
|
"--system-prompt",
|
|
405
|
-
composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.
|
|
489
|
+
composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.canManageOwnTeams),
|
|
406
490
|
];
|
|
407
491
|
const proc = childProcess.spawn(team.parentPiExecutable, args, {
|
|
408
492
|
cwd: team.projectDirectory ?? process.cwd(),
|
|
@@ -426,33 +510,40 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
426
510
|
}
|
|
427
511
|
|
|
428
512
|
function parseHerdrPaneId(stdout: string, teammateName: string): string {
|
|
429
|
-
const response = JSON.parse(stdout) as { result?: {
|
|
430
|
-
const paneId = response.result?.
|
|
431
|
-
if (!paneId) throw new Error(`herdr
|
|
513
|
+
const response = JSON.parse(stdout) as { result?: { pane?: { pane_id?: string } } };
|
|
514
|
+
const paneId = response.result?.pane?.pane_id;
|
|
515
|
+
if (!paneId) throw new Error(`herdr pane split did not return a pane for teammate "${teammateName}"`);
|
|
432
516
|
return paneId;
|
|
433
517
|
}
|
|
434
518
|
|
|
519
|
+
/** @example shellQuote("two words") // "'two words'" */
|
|
520
|
+
function shellQuote(value: string): string {
|
|
521
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
522
|
+
}
|
|
523
|
+
|
|
435
524
|
async function attachHerdrTeammate(
|
|
436
525
|
team: TeamState,
|
|
437
526
|
teammate: TeammateState,
|
|
438
527
|
participants: string[],
|
|
439
|
-
|
|
528
|
+
herdrParentPaneId: string,
|
|
440
529
|
options: ChildStartOptions,
|
|
441
530
|
): Promise<void> {
|
|
442
|
-
const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.
|
|
531
|
+
const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.canManageOwnTeams);
|
|
443
532
|
const environment = childEnvironmentOverrides(team, teammate, participants);
|
|
444
533
|
const sessionArgs = options.sessionFile
|
|
445
534
|
? ["--session", options.sessionFile]
|
|
446
|
-
: teammate.
|
|
535
|
+
: teammate.inheritMainContext && !options.restartEmpty
|
|
447
536
|
? ["--fork", team.mainSessionFile!]
|
|
448
537
|
: [];
|
|
449
538
|
const modelArgs = options.sessionFile ? [] : ["--model", teammate.model, "--thinking", teammate.thinking];
|
|
450
|
-
const args = ["
|
|
539
|
+
const args = ["pane", "split", "--pane", herdrParentPaneId, "--direction", "right", "--no-focus", "--cwd", team.projectDirectory ?? process.cwd()];
|
|
451
540
|
for (const [name, value] of Object.entries(environment)) {
|
|
452
541
|
if (value !== undefined) args.push("--env", `${name}=${value}`);
|
|
453
542
|
}
|
|
454
|
-
args
|
|
455
|
-
|
|
543
|
+
const result = await runCommand("herdr", args);
|
|
544
|
+
teammate.paneId = parseHerdrPaneId(result.stdout, teammate.name);
|
|
545
|
+
await runCommand("herdr", ["pane", "rename", teammate.paneId, teammate.name]);
|
|
546
|
+
const command = [
|
|
456
547
|
team.parentPiExecutable,
|
|
457
548
|
...sessionArgs,
|
|
458
549
|
"--no-extensions",
|
|
@@ -461,20 +552,23 @@ async function attachHerdrTeammate(
|
|
|
461
552
|
...modelArgs,
|
|
462
553
|
"--system-prompt",
|
|
463
554
|
systemPrompt,
|
|
464
|
-
);
|
|
465
|
-
|
|
466
|
-
teammate.paneId = parseHerdrPaneId(result.stdout, teammate.name);
|
|
555
|
+
].map(shellQuote).join(" ");
|
|
556
|
+
await runCommand("herdr", ["pane", "run", teammate.paneId, command]);
|
|
467
557
|
appendSpawnLog(team, teammate);
|
|
468
558
|
}
|
|
469
559
|
|
|
470
560
|
/** Every child registers its delivery runtime through the parent callback; startup completes only after registration. */
|
|
471
|
-
async function awaitChildRegistration(teammate: TeammateState): Promise<void> {
|
|
561
|
+
async function awaitChildRegistration(teammate: TeammateState, signal?: AbortSignal): Promise<void> {
|
|
562
|
+
signal?.throwIfAborted();
|
|
472
563
|
let readinessTimeout: ReturnType<typeof setTimeout> | undefined;
|
|
564
|
+
let onAbort: (() => void) | undefined;
|
|
473
565
|
try {
|
|
474
566
|
await Promise.race([
|
|
475
567
|
teammate.ready!,
|
|
476
568
|
new Promise<never>((_, reject) => {
|
|
477
569
|
readinessTimeout = setTimeout(() => reject(new Error(`Timed out waiting for teammate ${teammate.name} to register`)), 30_000);
|
|
570
|
+
onAbort = () => reject(signal!.reason);
|
|
571
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
478
572
|
}),
|
|
479
573
|
]);
|
|
480
574
|
} catch (error) {
|
|
@@ -482,6 +576,7 @@ async function awaitChildRegistration(teammate: TeammateState): Promise<void> {
|
|
|
482
576
|
throw error;
|
|
483
577
|
} finally {
|
|
484
578
|
if (readinessTimeout) clearTimeout(readinessTimeout);
|
|
579
|
+
if (onAbort) signal?.removeEventListener("abort", onAbort);
|
|
485
580
|
}
|
|
486
581
|
}
|
|
487
582
|
|
|
@@ -489,12 +584,13 @@ async function startTeammate(
|
|
|
489
584
|
team: TeamState,
|
|
490
585
|
teammate: TeammateState,
|
|
491
586
|
participants: string[],
|
|
492
|
-
|
|
587
|
+
herdrParentPaneId?: string,
|
|
493
588
|
startOptions: ChildStartOptions = {},
|
|
494
589
|
): Promise<void> {
|
|
495
|
-
|
|
590
|
+
startOptions.signal?.throwIfAborted();
|
|
591
|
+
if (teammate.transport === "herdr") await attachHerdrTeammate(team, teammate, participants, herdrParentPaneId!, startOptions);
|
|
496
592
|
else attachRpcTeammate(team, teammate, participants, startOptions);
|
|
497
|
-
await awaitChildRegistration(teammate);
|
|
593
|
+
await awaitChildRegistration(teammate, startOptions.signal);
|
|
498
594
|
}
|
|
499
595
|
|
|
500
596
|
function manifestMemberFromTeammate(teammate: TeammateState): TeamManifestMember {
|
|
@@ -503,22 +599,13 @@ function manifestMemberFromTeammate(teammate: TeammateState): TeamManifestMember
|
|
|
503
599
|
}
|
|
504
600
|
if (fs.existsSync(teammate.sessionFile)) teammate.sessionMaterialized = true;
|
|
505
601
|
return {
|
|
506
|
-
|
|
507
|
-
prompt: teammate.prompt,
|
|
508
|
-
model: teammate.model,
|
|
509
|
-
thinking: teammate.thinking,
|
|
510
|
-
inheritContext: teammate.inheritContext,
|
|
511
|
-
canOverseeOwnTeams: teammate.canOverseeOwnTeams,
|
|
512
|
-
transport: teammate.transport,
|
|
513
|
-
live: teammate.alive,
|
|
514
|
-
sessionId: teammate.sessionId,
|
|
515
|
-
sessionFile: teammate.sessionFile,
|
|
602
|
+
...teammateRecord(teammate),
|
|
516
603
|
sessionMaterialized: teammate.sessionMaterialized,
|
|
517
604
|
};
|
|
518
605
|
}
|
|
519
606
|
|
|
520
607
|
function persistActiveTeamManifest(team: TeamState): void {
|
|
521
|
-
if (!team.manifest) return;
|
|
608
|
+
if (!team.manifest || !teams.has(team.id ?? team.name)) return;
|
|
522
609
|
const updatedAt = new Date().toISOString();
|
|
523
610
|
team.manifest = {
|
|
524
611
|
...team.manifest,
|
|
@@ -557,7 +644,7 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
|
|
|
557
644
|
};
|
|
558
645
|
processToStop.once("exit", resolveExit);
|
|
559
646
|
processToStop.kill("SIGTERM");
|
|
560
|
-
if (!teammate.
|
|
647
|
+
if (!teammate.canManageOwnTeams) {
|
|
561
648
|
forceKillTimeout = setTimeout(() => processToStop.kill("SIGKILL"), defaultRpcShutdownGraceMilliseconds);
|
|
562
649
|
forceKillTimeout.unref();
|
|
563
650
|
}
|
|
@@ -611,24 +698,28 @@ function closeCallbackServerIfUnused(): void {
|
|
|
611
698
|
if (teams.size > 0 || !callbackServer) return;
|
|
612
699
|
callbackServer.close();
|
|
613
700
|
callbackServer = undefined;
|
|
701
|
+
callbackReady = undefined;
|
|
614
702
|
callbackUrl = "";
|
|
615
703
|
}
|
|
616
704
|
|
|
617
705
|
async function ensureCallbackServer(): Promise<void> {
|
|
618
|
-
if (
|
|
706
|
+
if (callbackReady) return callbackReady;
|
|
619
707
|
|
|
620
|
-
|
|
708
|
+
const server = http.createServer((request, response) => {
|
|
621
709
|
void handleCallbackRequest(request, response);
|
|
622
710
|
});
|
|
711
|
+
callbackServer = server;
|
|
623
712
|
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
713
|
+
callbackReady = new Promise<void>((resolve, reject) => {
|
|
714
|
+
server.once("error", reject);
|
|
715
|
+
server.listen(0, "127.0.0.1", () => {
|
|
716
|
+
const address = server.address();
|
|
627
717
|
if (!address || typeof address === "string") throw new Error("Team callback server did not get a port");
|
|
628
718
|
callbackUrl = `http://127.0.0.1:${address.port}/callback`;
|
|
629
719
|
resolve();
|
|
630
720
|
});
|
|
631
721
|
});
|
|
722
|
+
return callbackReady;
|
|
632
723
|
}
|
|
633
724
|
|
|
634
725
|
async function readJsonBody(request: http.IncomingMessage): Promise<JsonRecord> {
|
|
@@ -661,6 +752,8 @@ function validateChildDeliveryUrl(rawUrl: string, teammateName: string): string
|
|
|
661
752
|
}
|
|
662
753
|
|
|
663
754
|
function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonRecord): void {
|
|
755
|
+
if (event.type === "agent_start" || event.type === "work_queued") teammate.active = true;
|
|
756
|
+
if (event.type === "agent_settled" || event.type === "session_shutdown") teammate.active = false;
|
|
664
757
|
if (event.type === "session_shutdown") {
|
|
665
758
|
teammate.alive = false;
|
|
666
759
|
teammate.deliveryUrl = undefined;
|
|
@@ -671,6 +764,7 @@ function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonR
|
|
|
671
764
|
}
|
|
672
765
|
const logInput = normalizeChildEvent(team.name, teammate.name, event);
|
|
673
766
|
if (logInput) appendTeamLog(team, logInput);
|
|
767
|
+
if (["agent_start", "work_queued", "agent_settled", "session_shutdown"].includes(String(event.type))) persistActiveTeamManifest(team);
|
|
674
768
|
}
|
|
675
769
|
|
|
676
770
|
async function handleCallbackRequest(request: http.IncomingMessage, response: http.ServerResponse): Promise<void> {
|
|
@@ -706,6 +800,7 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
706
800
|
teammate.sessionFile = sessionFile;
|
|
707
801
|
teammate.sessionMaterialized = fs.existsSync(sessionFile);
|
|
708
802
|
teammate.alive = true;
|
|
803
|
+
teammate.active = false;
|
|
709
804
|
team.statuses.set(teammate.name, status("idle", "Spawned"));
|
|
710
805
|
teammate.resolveReady?.();
|
|
711
806
|
writeJson(response, 200, { accepted: true, team: team.name, from });
|
|
@@ -722,7 +817,7 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
722
817
|
if (tool === "team_context") {
|
|
723
818
|
if (!teammate) throw new Error(`Unknown teammate: ${from}`);
|
|
724
819
|
writeJson(response, 200, {
|
|
725
|
-
team
|
|
820
|
+
...selectableTeam(team),
|
|
726
821
|
from,
|
|
727
822
|
participants: [...team.members.keys()],
|
|
728
823
|
status: formatStatus(team),
|
|
@@ -730,16 +825,19 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
730
825
|
return;
|
|
731
826
|
}
|
|
732
827
|
|
|
733
|
-
if (tool === "
|
|
734
|
-
const
|
|
828
|
+
if (tool === "team_send_message") {
|
|
829
|
+
const candidates = [selectableTeam(team)];
|
|
830
|
+
const selections = resolveTargets(candidates, args.targets as string[]);
|
|
735
831
|
const message = String(args.message ?? "");
|
|
736
|
-
const
|
|
737
|
-
for (const
|
|
738
|
-
|
|
832
|
+
const interrupted = interruptedTeammateIds(candidates, selections, args.interrupt as boolean | string[] | undefined);
|
|
833
|
+
for (const selection of selections) {
|
|
834
|
+
for (const recipient of selection.teammates) enqueueDelivery(team, from, team.members.get(recipient.name)!, message, interrupted.has(recipient.teammateId));
|
|
835
|
+
}
|
|
836
|
+
writeJson(response, 200, { published: true, teams: [{ ...teamIdentity(team), status: formatStatus(team) }], instruction: "Do not wait for replies. Teammates will message you back." });
|
|
739
837
|
return;
|
|
740
838
|
}
|
|
741
839
|
|
|
742
|
-
if (tool === "
|
|
840
|
+
if (tool === "send_main_message") {
|
|
743
841
|
const rawMessage = String(args.message ?? "");
|
|
744
842
|
const details: TeamMessageDetails = { team: team.name, from, sentAt: new Date().toISOString(), message: rawMessage };
|
|
745
843
|
appendTeamLog(team, {
|
|
@@ -754,16 +852,16 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
754
852
|
{ customType: teamMessageType, content: `[${team.name}/${from}] ${rawMessage}`, display: true, details },
|
|
755
853
|
{ deliverAs: "steer", triggerTurn: true },
|
|
756
854
|
);
|
|
757
|
-
writeJson(response, 200,
|
|
855
|
+
writeJson(response, 200, mainMessageResult(team));
|
|
758
856
|
return;
|
|
759
857
|
}
|
|
760
858
|
|
|
761
|
-
if (tool === "
|
|
859
|
+
if (tool === "team_status") {
|
|
762
860
|
const gerund = args.gerund as string | undefined;
|
|
763
861
|
const phrase = args.phrase as string | undefined;
|
|
764
862
|
updateStatus(team, from, gerund, phrase);
|
|
765
863
|
logStatusDeclaration(team, from, gerund, phrase);
|
|
766
|
-
writeJson(response, 200, { team
|
|
864
|
+
writeJson(response, 200, { ...teamIdentity(team), status: formatStatus(team) });
|
|
767
865
|
return;
|
|
768
866
|
}
|
|
769
867
|
|
|
@@ -776,12 +874,13 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
776
874
|
function teammateSchema(modelGuidance: string) {
|
|
777
875
|
return Type.Object({
|
|
778
876
|
name: Type.String({ description: "Teammate name" }),
|
|
779
|
-
|
|
877
|
+
systemPrompt: Type.String({ description: "Individual teammate system prompt" }),
|
|
780
878
|
model: Type.String({ description: `Canonical provider/model id for this teammate. ${modelGuidance}` }),
|
|
781
879
|
thinking: Type.Optional(StringEnum(thinkingLevels, { description: "Thinking level for this teammate. Defaults to xhigh.", default: defaultThinkingLevel })),
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
880
|
+
inheritMainContext: Type.Optional(Type.Boolean({ description: "Start with a clone of your context window rather than start fresh. Defaults to false.", default: false })),
|
|
881
|
+
canManageOwnTeams: Type.Optional(Type.Boolean({ description: "Allow this teammate to create and manage teams of its own. Defaults to false.", default: false })),
|
|
882
|
+
showOnHerdrPane: Type.Optional(Type.Boolean({ description: "Open a visible Herdr pane for this teammate. Defaults to false.", default: false })),
|
|
883
|
+
}, { additionalProperties: false });
|
|
785
884
|
}
|
|
786
885
|
|
|
787
886
|
function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiExecutable: string, manifest: TeamManifest, lease: TeamLease): TeamState {
|
|
@@ -803,16 +902,8 @@ function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiExecutab
|
|
|
803
902
|
nextLogSequence: 1,
|
|
804
903
|
};
|
|
805
904
|
for (const member of manifest.members) {
|
|
806
|
-
const teammate = createTeammateState(
|
|
807
|
-
|
|
808
|
-
prompt: member.prompt,
|
|
809
|
-
model: member.model,
|
|
810
|
-
thinking: member.thinking as ThinkingLevel,
|
|
811
|
-
inheritContext: member.inheritContext,
|
|
812
|
-
canOverseeOwnTeams: Boolean(member.canOverseeOwnTeams),
|
|
813
|
-
});
|
|
814
|
-
teammate.transport = "rpc";
|
|
815
|
-
teammate.sessionId = member.sessionId;
|
|
905
|
+
const teammate = createTeammateState(member);
|
|
906
|
+
teammate.sessionId = member.teammateId;
|
|
816
907
|
teammate.sessionFile = member.sessionFile;
|
|
817
908
|
teammate.sessionMaterialized = member.sessionMaterialized;
|
|
818
909
|
teammate.alive = false;
|
|
@@ -836,7 +927,7 @@ function sessionFileForResume(teammate: TeammateState): string | undefined {
|
|
|
836
927
|
if (teammate.sessionMaterialized) {
|
|
837
928
|
throw new Error(`Materialized session file for ${teammate.name} is missing: ${teammate.sessionFile}`);
|
|
838
929
|
}
|
|
839
|
-
//
|
|
930
|
+
// Pi assigns a session path before its first assistant response creates the file.
|
|
840
931
|
return undefined;
|
|
841
932
|
}
|
|
842
933
|
|
|
@@ -844,7 +935,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
844
935
|
const childRuntimeConfig = readChildRuntimeConfig();
|
|
845
936
|
if (childRuntimeConfig) {
|
|
846
937
|
registerChildTools(pi, childRuntimeConfig);
|
|
847
|
-
if (!childRuntimeConfig.
|
|
938
|
+
if (!childRuntimeConfig.canManageOwnTeams) return;
|
|
848
939
|
}
|
|
849
940
|
|
|
850
941
|
const parentPiExecutable = process.argv[1];
|
|
@@ -877,32 +968,33 @@ export default function (pi: ExtensionAPI) {
|
|
|
877
968
|
defineTool({
|
|
878
969
|
name: "team_spawn",
|
|
879
970
|
label: "Team Spawn",
|
|
880
|
-
description:
|
|
881
|
-
promptSnippet:
|
|
971
|
+
description: "You are automatically part of the team as main. Do not include yourself in teammates. Use team_resume to continue an existing team, or team_add_teammates to grow one.",
|
|
972
|
+
promptSnippet: "Spawn a versatile team of agents.",
|
|
882
973
|
renderShell: "self",
|
|
883
974
|
renderCall: (args, theme, context) => renderTeamToolCall("team_spawn", args, theme, context, sessionTeammateRoster),
|
|
884
975
|
renderResult: (result, options, theme, context) => renderTeamToolResult("team_spawn", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
885
976
|
parameters: Type.Object({
|
|
886
|
-
|
|
887
|
-
|
|
977
|
+
teamName: Type.String({ description: "Name for the new team" }),
|
|
978
|
+
commonPrompt: Type.String({ description: "Common system prompt for all teammates" }),
|
|
888
979
|
teammates: Type.Array(teammateSchema(modelGuidance), { description: "Teammates to spawn" }),
|
|
889
|
-
showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false })),
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
980
|
+
showOnHerdrPanes: Type.Optional(Type.Boolean({ description: "Open visible Herdr panes for the team. Overrides individual teammate Herdr settings when explicitly supplied. Defaults to false.", default: false })),
|
|
981
|
+
startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start teammates idle. Otherwise, start work following their common and individual system prompts once everyone is ready. Set true when only a few teammates should start first, then message those teammates." })),
|
|
982
|
+
}, { additionalProperties: false }),
|
|
983
|
+
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
984
|
+
signal?.throwIfAborted();
|
|
985
|
+
const teamName = compactName(params.teamName);
|
|
893
986
|
const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
|
|
894
|
-
const
|
|
895
|
-
|
|
896
|
-
const teammateSpecs = params.teammates as TeammateSpec[];
|
|
987
|
+
const teammateSpecs: Teammate[] = params.teammates.map((teammate) => ({ ...teammate, showOnHerdrPane: params.showOnHerdrPanes ?? teammate.showOnHerdrPane ?? false }));
|
|
988
|
+
const herdrParentPaneId = showOnHerdrPanes || teammateSpecs.some((teammate) => teammate.showOnHerdrPane) ? await validateHerdrAvailability() : undefined;
|
|
897
989
|
const teammateNames = teammateSpecs.map((teammate) => compactName(teammate.name));
|
|
898
990
|
const duplicateNames = teammateNames.filter((name, index) => teammateNames.indexOf(name) !== index);
|
|
899
991
|
if (duplicateNames.length > 0) throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
|
|
900
992
|
if (teammateNames.includes("main")) throw new Error('"main" is reserved');
|
|
901
993
|
|
|
902
994
|
validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
|
|
903
|
-
const inheritsMainContext = teammateSpecs.some((teammate) => Boolean(teammate.
|
|
995
|
+
const inheritsMainContext = teammateSpecs.some((teammate) => Boolean(teammate.inheritMainContext));
|
|
904
996
|
const mainSessionFile = inheritsMainContext ? context.sessionManager.getSessionFile() : undefined;
|
|
905
|
-
if (inheritsMainContext && !mainSessionFile) throw new Error("
|
|
997
|
+
if (inheritsMainContext && !mainSessionFile) throw new Error("inheritMainContext requires a saved main session. Use a saved main session or retry with inheritMainContext: false.");
|
|
906
998
|
const originMainSessionId = context.sessionManager?.getSessionId?.();
|
|
907
999
|
const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
|
|
908
1000
|
const projectDirectory = rawProjectDirectory ? canonicalProjectDirectory(rawProjectDirectory) : undefined;
|
|
@@ -912,6 +1004,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
912
1004
|
const lease = teamId ? claimTeamLease(teamId, originMainSessionId) : undefined;
|
|
913
1005
|
if (teamId && projectDirectory && listTeamManifests(projectDirectory).some((manifest) => manifest.id === teamId)) {
|
|
914
1006
|
releaseTeamLease(lease!);
|
|
1007
|
+
// TODO: Consider resuming here if all supplied spawn settings can be preserved.
|
|
915
1008
|
throw new Error(`Team already exists: ${teamId}. Use team_resume.`);
|
|
916
1009
|
}
|
|
917
1010
|
sessionTeammateRoster.push(...teammateNames.filter((teammateName) => !sessionTeammateRoster.includes(teammateName)));
|
|
@@ -930,7 +1023,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
930
1023
|
name: teamName,
|
|
931
1024
|
projectDirectory,
|
|
932
1025
|
showOnHerdrPanes,
|
|
933
|
-
teamPrompt: params.
|
|
1026
|
+
teamPrompt: params.commonPrompt,
|
|
934
1027
|
mainSessionFile,
|
|
935
1028
|
members: new Map(),
|
|
936
1029
|
statuses: new Map([["main", status("available", "Main agent")]]),
|
|
@@ -943,16 +1036,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
943
1036
|
teams.set(runtimeTeamId, team);
|
|
944
1037
|
try {
|
|
945
1038
|
for (const teammateSpec of teammateSpecs) {
|
|
946
|
-
const teammate = createTeammateState(
|
|
1039
|
+
const teammate = createTeammateState(teammateSpec);
|
|
947
1040
|
team.members.set(teammate.name, teammate);
|
|
948
1041
|
team.statuses.set(teammate.name, status("idle", "Spawned"));
|
|
949
|
-
await startTeammate(team, teammate, teammateNames,
|
|
1042
|
+
await startTeammate(team, teammate, teammateNames, herdrParentPaneId, { signal });
|
|
950
1043
|
}
|
|
1044
|
+
signal?.throwIfAborted();
|
|
951
1045
|
|
|
952
1046
|
if (teamId && originMainSessionId && projectDirectory) {
|
|
953
1047
|
const timestamp = new Date().toISOString();
|
|
954
1048
|
const manifest: TeamManifest = {
|
|
955
|
-
version:
|
|
1049
|
+
version: 2,
|
|
956
1050
|
id: teamId,
|
|
957
1051
|
name: team.name,
|
|
958
1052
|
originMainSessionId,
|
|
@@ -972,19 +1066,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
972
1066
|
closeCallbackServerIfUnused();
|
|
973
1067
|
throw error;
|
|
974
1068
|
}
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
id: team.id,
|
|
978
|
-
team: team.name,
|
|
979
|
-
teammates: [...team.members.keys()],
|
|
980
|
-
sessions: Object.fromEntries(
|
|
981
|
-
[...team.members.values()]
|
|
982
|
-
.filter((teammate) => teammate.sessionId && teammate.sessionFile)
|
|
983
|
-
.map((teammate) => [teammate.name, { sessionId: teammate.sessionId, sessionFile: teammate.sessionFile }]),
|
|
984
|
-
),
|
|
985
|
-
status: formatStatus(team),
|
|
986
|
-
instruction: bundledSkillsInstruction,
|
|
987
|
-
});
|
|
1069
|
+
await kickoffTeammates(team, [...team.members.values()], Boolean(params.startIdle));
|
|
1070
|
+
return toolResult(lifecycleResult(team));
|
|
988
1071
|
},
|
|
989
1072
|
}),
|
|
990
1073
|
);
|
|
@@ -994,15 +1077,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
994
1077
|
defineTool({
|
|
995
1078
|
name: "schedule_reminder",
|
|
996
1079
|
label: "Schedule Reminder",
|
|
997
|
-
description: "Set
|
|
998
|
-
promptSnippet: "Use schedule_reminder as a safety net for team oversight if delegates do not wake you proactively. Ask whether the user wants periodic checks, such as every 30 minutes. Recommend this safety net more strongly as the expected run time grows, especially for multi-hour unattended work. For periodic checks, schedule the next reminder after each check.",
|
|
1080
|
+
description: "Set a one-shot reminder for yourself. Use it when work needs a later check. For periodic checks, schedule the next reminder after each check.",
|
|
999
1081
|
renderShell: "self",
|
|
1000
1082
|
renderCall: (args, theme, context) => renderReminderToolCall(args, theme, context),
|
|
1001
1083
|
renderResult: (result, options, theme, context) => renderReminderToolResult(result, options, theme, context),
|
|
1002
1084
|
parameters: Type.Object({
|
|
1003
1085
|
delayMinutes: Type.Number({ exclusiveMinimum: 0, maximum: 35_791, description: "Minutes until the reminder" }),
|
|
1004
1086
|
message: Type.String({ minLength: 1, description: "Custom message that wakes you" }),
|
|
1005
|
-
}),
|
|
1087
|
+
}, { additionalProperties: false }),
|
|
1006
1088
|
async execute(_toolCallId, params) {
|
|
1007
1089
|
const delayMilliseconds = params.delayMinutes * 60_000;
|
|
1008
1090
|
const scheduledAt = new Date(Date.now() + delayMilliseconds).toISOString();
|
|
@@ -1023,20 +1105,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
1023
1105
|
pi.registerTool(
|
|
1024
1106
|
defineTool({
|
|
1025
1107
|
name: "team_list",
|
|
1108
|
+
// TODO: Make listing dormant teams opt-in with includeDormantTeams: boolean.
|
|
1026
1109
|
label: "Team List",
|
|
1027
1110
|
description: childRuntimeConfig
|
|
1028
|
-
? "List active and dormant teams
|
|
1111
|
+
? "List active and dormant teams in the current project that this managing teammate's Pi session created."
|
|
1029
1112
|
: "List active and dormant teams for the current project.",
|
|
1030
|
-
promptSnippet: "List teams for the current project",
|
|
1031
1113
|
renderShell: "self",
|
|
1032
1114
|
renderCall: (_args, theme, context) => renderTeamToolCall("team_list", {}, theme, context, sessionTeammateRoster),
|
|
1033
1115
|
renderResult: (result, options, theme, context) => renderTeamToolResult("team_list", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
1034
|
-
parameters: Type.Object({}),
|
|
1116
|
+
parameters: Type.Object({}, { additionalProperties: false }),
|
|
1035
1117
|
async execute(_toolCallId, _params, _signal, _onUpdate, context) {
|
|
1036
1118
|
const projectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
|
|
1037
1119
|
if (!projectDirectory) throw new Error("team_list requires a project directory");
|
|
1038
1120
|
const managerSessionId = childRuntimeConfig ? context.sessionManager?.getSessionId?.() : undefined;
|
|
1039
|
-
if (childRuntimeConfig && !managerSessionId) throw new Error("team_list requires a persistent
|
|
1121
|
+
if (childRuntimeConfig && !managerSessionId) throw new Error("team_list requires a persistent managing teammate Pi session");
|
|
1040
1122
|
const manifests = listTeamManifests(projectDirectory).filter(
|
|
1041
1123
|
(manifest) => !managerSessionId || manifest.originMainSessionId === managerSessionId,
|
|
1042
1124
|
);
|
|
@@ -1044,18 +1126,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
1044
1126
|
teams: manifests.map((manifest) => {
|
|
1045
1127
|
const liveTeam = teams.get(manifest.id);
|
|
1046
1128
|
return {
|
|
1047
|
-
|
|
1048
|
-
name: manifest.name,
|
|
1129
|
+
...teamIdentity(manifest),
|
|
1049
1130
|
state: manifest.state,
|
|
1050
1131
|
leaseState: readTeamLeaseState(manifest.id).state,
|
|
1051
|
-
teammates: manifest.members.map((member) =>
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
canOverseeOwnTeams: Boolean(member.canOverseeOwnTeams),
|
|
1056
|
-
sessionId: member.sessionId,
|
|
1057
|
-
sessionFile: member.sessionFile,
|
|
1058
|
-
})),
|
|
1132
|
+
teammates: manifest.members.map(({ sessionMaterialized, ...member }) => {
|
|
1133
|
+
const runtime = liveTeam?.members.get(member.name);
|
|
1134
|
+
return runtime ? teammateRecord(runtime) : member;
|
|
1135
|
+
}),
|
|
1059
1136
|
createdAt: manifest.createdAt,
|
|
1060
1137
|
updatedAt: manifest.updatedAt,
|
|
1061
1138
|
shutdownAt: manifest.shutdownAt,
|
|
@@ -1072,35 +1149,34 @@ export default function (pi: ExtensionAPI) {
|
|
|
1072
1149
|
name: "team_resume",
|
|
1073
1150
|
label: "Team Resume",
|
|
1074
1151
|
description: childRuntimeConfig
|
|
1075
|
-
? "Resume all or selected stopped
|
|
1076
|
-
: "Resume all stopped teammates
|
|
1077
|
-
promptSnippet: "Resume all or selected stopped teammates",
|
|
1152
|
+
? "Resume all or selected stopped teammates from a current-project team created by your Pi session. Already-running teammates remain as they are."
|
|
1153
|
+
: "Resume all or selected stopped teammates from a team in the current project. Already-running teammates remain as they are.",
|
|
1078
1154
|
renderShell: "self",
|
|
1079
1155
|
renderCall: (args, theme, context) => renderTeamToolCall("team_resume", args, theme, context, sessionTeammateRoster),
|
|
1080
1156
|
renderResult: (result, options, theme, context) => renderTeamToolResult("team_resume", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
1081
1157
|
parameters: Type.Object({
|
|
1082
1158
|
team: Type.String({ description: "Team name or persistent ID" }),
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1159
|
+
// TODO: Should allow defining new teammates or even existing teammates (any Pi session ID belonging to this project) from other teams and sessions for maximum flexibility.
|
|
1160
|
+
teammates: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description: "Teammate names or Pi session IDs within this team. Omit to resume all stopped teammates." })),
|
|
1161
|
+
showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false, description: "Open visible Herdr panes for selected teammates. Defaults to false." })),
|
|
1162
|
+
startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start resumed teammates idle." })),
|
|
1163
|
+
resumptionPrompt: Type.Optional(Type.String({ description: "Instructions added once to resumed teammates' conversation context. Does not change system prompts or independently start work." })),
|
|
1164
|
+
}, { additionalProperties: false }),
|
|
1165
|
+
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
1166
|
+
signal?.throwIfAborted();
|
|
1087
1167
|
const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
|
|
1088
1168
|
if (!rawProjectDirectory) throw new Error("team_resume requires a project directory");
|
|
1089
1169
|
const managerSessionId = childRuntimeConfig ? context.sessionManager?.getSessionId?.() : undefined;
|
|
1090
|
-
if (childRuntimeConfig && !managerSessionId) throw new Error("team_resume requires a persistent
|
|
1170
|
+
if (childRuntimeConfig && !managerSessionId) throw new Error("team_resume requires a persistent managing teammate Pi session");
|
|
1091
1171
|
const availableManifests = listTeamManifests(rawProjectDirectory).filter(
|
|
1092
1172
|
(candidate) => !managerSessionId || candidate.originMainSessionId === managerSessionId,
|
|
1093
1173
|
);
|
|
1094
1174
|
const manifest = resolveTeamIdentifier(availableManifests, params.team);
|
|
1095
|
-
if (!manifest) throw new Error(`Unknown current-project team: ${params.team}
|
|
1096
|
-
const
|
|
1097
|
-
const
|
|
1098
|
-
if (duplicateNames.length > 0) throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
|
|
1099
|
-
const manifestMemberNames = new Set(manifest.members.map((member) => member.name));
|
|
1100
|
-
const missingNames = requestedNames.filter((name) => !manifestMemberNames.has(name));
|
|
1101
|
-
if (missingNames.length > 0) throw new Error(`Unknown teammate(s) in ${manifest.name}: ${missingNames.join(", ")}`);
|
|
1175
|
+
if (!manifest) throw new Error(`Unknown current-project team: ${JSON.stringify(params.team)}. Call team_list and pass a listed teamId or unique teamName in the team parameter.`);
|
|
1176
|
+
const members = manifest.members;
|
|
1177
|
+
const requestedNames = resolveTeammates(members, params.teammates ?? members.map((member) => member.teammateId)).map((member) => member.name);
|
|
1102
1178
|
const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
|
|
1103
|
-
const
|
|
1179
|
+
const herdrParentPaneId = showOnHerdrPanes ? await validateHerdrAvailability() : undefined;
|
|
1104
1180
|
|
|
1105
1181
|
const existingTeam = [...teams.values()].find((candidate) => candidate.id === manifest.id);
|
|
1106
1182
|
if (existingTeam && existingTeam.owner !== owner) {
|
|
@@ -1124,6 +1200,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1124
1200
|
}
|
|
1125
1201
|
|
|
1126
1202
|
const teammates = requestedNames.map((name) => team.members.get(name)!).filter((teammate) => !teammate.alive);
|
|
1203
|
+
const alreadyLiveTeammates = [...team.members.values()].filter((teammate) => teammate.alive);
|
|
1127
1204
|
let starts: Array<{ teammate: TeammateState; sessionFile: string | undefined }>;
|
|
1128
1205
|
try {
|
|
1129
1206
|
starts = teammates.map((teammate) => ({ teammate, sessionFile: sessionFileForResume(teammate) }));
|
|
@@ -1140,12 +1217,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
1140
1217
|
try {
|
|
1141
1218
|
for (const { teammate, sessionFile } of starts) {
|
|
1142
1219
|
prepareTeammateStart(teammate, showOnHerdrPanes ? "herdr" : "rpc");
|
|
1143
|
-
await startTeammate(team, teammate, participantNames,
|
|
1220
|
+
await startTeammate(team, teammate, participantNames, herdrParentPaneId, {
|
|
1144
1221
|
sessionFile,
|
|
1145
1222
|
restartEmpty: sessionFile === undefined,
|
|
1223
|
+
signal,
|
|
1146
1224
|
});
|
|
1147
1225
|
team.statuses.set(teammate.name, status("idle", "Resumed"));
|
|
1148
1226
|
}
|
|
1227
|
+
signal?.throwIfAborted();
|
|
1149
1228
|
persistActiveTeamManifest(team);
|
|
1150
1229
|
} catch (error) {
|
|
1151
1230
|
if (!existingTeam) {
|
|
@@ -1165,16 +1244,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
1165
1244
|
throw error;
|
|
1166
1245
|
}
|
|
1167
1246
|
|
|
1247
|
+
await kickoffTeammates(team, starts.map(({ teammate }) => teammate), Boolean(params.startIdle), params.resumptionPrompt);
|
|
1168
1248
|
return toolResult({
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
starts.map(({ teammate }) => [teammate.name, { sessionId: teammate.sessionId, sessionFile: teammate.sessionFile }]),
|
|
1177
|
-
),
|
|
1249
|
+
...lifecycleResult(team),
|
|
1250
|
+
teammates: [...team.members.values()].map((teammate) => {
|
|
1251
|
+
const resumed = starts.find((start) => start.teammate === teammate);
|
|
1252
|
+
return { ...teammateRecord(teammate), ...(resumed ? { contextRestored: resumed.sessionFile !== undefined } : {}) };
|
|
1253
|
+
}),
|
|
1254
|
+
alreadyActiveTeammates: alreadyLiveTeammates.filter((teammate) => teammateSummary(teammate).active).map(teammateReference),
|
|
1255
|
+
status: formatStatus(team),
|
|
1178
1256
|
});
|
|
1179
1257
|
},
|
|
1180
1258
|
}),
|
|
@@ -1182,27 +1260,28 @@ export default function (pi: ExtensionAPI) {
|
|
|
1182
1260
|
|
|
1183
1261
|
pi.registerTool(
|
|
1184
1262
|
defineTool({
|
|
1185
|
-
name: "
|
|
1263
|
+
name: "team_add_teammates",
|
|
1186
1264
|
label: "Team Add",
|
|
1187
|
-
description: "Add
|
|
1265
|
+
description: "Add teammates to an active team you own. Existing teammates continue their work.",
|
|
1188
1266
|
promptSnippet: "Add new teammates to a running team",
|
|
1189
1267
|
renderShell: "self",
|
|
1190
|
-
renderCall: (args, theme, context) => renderTeamToolCall("
|
|
1191
|
-
renderResult: (result, options, theme, context) => renderTeamToolResult("
|
|
1268
|
+
renderCall: (args, theme, context) => renderTeamToolCall("team_add_teammates", args, theme, context, sessionTeammateRoster),
|
|
1269
|
+
renderResult: (result, options, theme, context) => renderTeamToolResult("team_add_teammates", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
1192
1270
|
parameters: Type.Object({
|
|
1193
|
-
team: Type.String({ description: "Team name or persistent ID" }),
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
);
|
|
1271
|
+
team: Type.Optional(Type.String({ description: "Team name or persistent ID. Omit when exactly one owned active team exists." })),
|
|
1272
|
+
// TODO: Accept existing current-project Pi session IDs as well as new teammate definitions.
|
|
1273
|
+
teammates: Type.Array(teammateSchema(""), { minItems: 1, description: "New teammate definitions to add. Existing Pi sessions cannot yet be attached." }),
|
|
1274
|
+
startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start added teammates idle." })),
|
|
1275
|
+
}, { additionalProperties: false }),
|
|
1276
|
+
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
1277
|
+
signal?.throwIfAborted();
|
|
1278
|
+
const team = resolveTeam(owner, params.team);
|
|
1201
1279
|
if (!team || !team.manifest || !team.lease || team.manifest.state !== "active") {
|
|
1202
|
-
throw new Error(`
|
|
1280
|
+
throw new Error(`team_add_teammates requires a running team owned by this main session: ${params.team}`);
|
|
1203
1281
|
}
|
|
1204
1282
|
|
|
1205
|
-
const teammateSpecs = params.teammates as
|
|
1283
|
+
const teammateSpecs = params.teammates as Teammate[];
|
|
1284
|
+
const herdrParentPaneId = teammateSpecs.some((teammate) => teammate.showOnHerdrPane) ? await validateHerdrAvailability() : undefined;
|
|
1206
1285
|
const teammateNames = teammateSpecs.map((teammate) => compactName(teammate.name));
|
|
1207
1286
|
const duplicateNames = teammateNames.filter(
|
|
1208
1287
|
(name, index) => teammateNames.indexOf(name) !== index || team.members.has(name),
|
|
@@ -1213,14 +1292,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
1213
1292
|
if (teammateNames.includes("main")) throw new Error('"main" is reserved');
|
|
1214
1293
|
validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
|
|
1215
1294
|
|
|
1216
|
-
const inheritsMainContext = teammateSpecs.some((teammate) => Boolean(teammate.
|
|
1295
|
+
const inheritsMainContext = teammateSpecs.some((teammate) => Boolean(teammate.inheritMainContext));
|
|
1217
1296
|
const mainSessionFile = inheritsMainContext ? context.sessionManager.getSessionFile() : undefined;
|
|
1218
|
-
if (inheritsMainContext && !mainSessionFile) throw new Error("
|
|
1297
|
+
if (inheritsMainContext && !mainSessionFile) throw new Error("inheritMainContext requires a saved main session. Use a saved main session or retry with inheritMainContext: false.");
|
|
1219
1298
|
if (mainSessionFile) team.mainSessionFile = mainSessionFile;
|
|
1220
1299
|
|
|
1221
|
-
const addedTeammates = teammateSpecs.map(
|
|
1300
|
+
const addedTeammates = teammateSpecs.map(createTeammateState);
|
|
1222
1301
|
for (const teammate of addedTeammates) {
|
|
1223
|
-
teammate.transport = "rpc";
|
|
1224
1302
|
team.members.set(teammate.name, teammate);
|
|
1225
1303
|
team.statuses.set(teammate.name, status("idle", "Spawned"));
|
|
1226
1304
|
}
|
|
@@ -1228,10 +1306,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
1228
1306
|
sessionTeammateRoster.push(...teammateNames.filter((name) => !sessionTeammateRoster.includes(name)));
|
|
1229
1307
|
|
|
1230
1308
|
try {
|
|
1231
|
-
for (const teammate of addedTeammates) await startTeammate(team, teammate, participantNames);
|
|
1309
|
+
for (const teammate of addedTeammates) await startTeammate(team, teammate, participantNames, herdrParentPaneId, { signal });
|
|
1310
|
+
signal?.throwIfAborted();
|
|
1232
1311
|
persistActiveTeamManifest(team);
|
|
1233
1312
|
} catch (error) {
|
|
1234
|
-
for (const teammate of addedTeammates)
|
|
1313
|
+
for (const teammate of addedTeammates) {
|
|
1314
|
+
if (teammate.transport === "herdr") await closeHerdrPane(teammate);
|
|
1315
|
+
else await stopRpcTeammate(teammate);
|
|
1316
|
+
}
|
|
1235
1317
|
for (const teammate of addedTeammates) {
|
|
1236
1318
|
team.members.delete(teammate.name);
|
|
1237
1319
|
team.statuses.delete(teammate.name);
|
|
@@ -1239,14 +1321,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
1239
1321
|
throw error;
|
|
1240
1322
|
}
|
|
1241
1323
|
|
|
1324
|
+
await kickoffTeammates(team, addedTeammates, Boolean(params.startIdle));
|
|
1242
1325
|
return toolResult({
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
team: team.name,
|
|
1246
|
-
added: teammateNames,
|
|
1247
|
-
sessions: Object.fromEntries(
|
|
1248
|
-
addedTeammates.map((teammate) => [teammate.name, { sessionId: teammate.sessionId, sessionFile: teammate.sessionFile }]),
|
|
1249
|
-
),
|
|
1326
|
+
...lifecycleResult(team),
|
|
1327
|
+
teammates: [...team.members.values()].map(teammateSummary),
|
|
1250
1328
|
status: formatStatus(team),
|
|
1251
1329
|
});
|
|
1252
1330
|
},
|
|
@@ -1255,58 +1333,63 @@ export default function (pi: ExtensionAPI) {
|
|
|
1255
1333
|
|
|
1256
1334
|
pi.registerTool(
|
|
1257
1335
|
defineTool({
|
|
1258
|
-
name: "
|
|
1336
|
+
name: "team_send_message",
|
|
1259
1337
|
label: "Team Send",
|
|
1260
1338
|
description: childRuntimeConfig
|
|
1261
|
-
? "
|
|
1262
|
-
: "
|
|
1263
|
-
promptSnippet: "
|
|
1339
|
+
? "Message teammates in your parent team or teams you own."
|
|
1340
|
+
: "Message teammates in teams you own.",
|
|
1341
|
+
promptSnippet: "Message your teammates.",
|
|
1264
1342
|
renderShell: "self",
|
|
1265
|
-
renderCall: (args, theme, context) => renderTeamToolCall("
|
|
1266
|
-
renderResult: (result, options, theme, context) => renderTeamToolResult("
|
|
1343
|
+
renderCall: (args, theme, context) => renderTeamToolCall("team_send_message", args, theme, context, sessionTeammateRoster),
|
|
1344
|
+
renderResult: (result, options, theme, context) => renderTeamToolResult("team_send_message", result, options, theme, context, getMarkdownTheme(), sessionTeammateRoster),
|
|
1267
1345
|
parameters: Type.Object({
|
|
1268
|
-
|
|
1269
|
-
to: Type.Array(Type.String(), { description: "Recipient teammate names" }),
|
|
1346
|
+
targets: Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description: targetDescription }),
|
|
1270
1347
|
message: Type.String({ description: "Message to send" }),
|
|
1271
|
-
interrupt: Type.Optional(Type.Boolean({
|
|
1272
|
-
}),
|
|
1348
|
+
interrupt: Type.Optional(Type.Union([Type.Boolean(), Type.Array(Type.String({ minLength: 1 }))], { description: interruptDescription })),
|
|
1349
|
+
}, { additionalProperties: false }),
|
|
1273
1350
|
async execute(_toolCallId, params, signal) {
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1351
|
+
const parent = childRuntimeConfig ? await callParent(childRuntimeConfig, "team_context", {}, signal) as unknown as SelectableTeam : undefined;
|
|
1352
|
+
const candidates = [...ownedTargetTeams(owner), ...(parent ? [parent] : [])];
|
|
1353
|
+
const selections = resolveTargets(candidates, params.targets);
|
|
1354
|
+
const interrupted = interruptedTeammateIds(candidates, selections, params.interrupt);
|
|
1355
|
+
const statuses: JsonRecord[] = [];
|
|
1356
|
+
for (const selection of selections) {
|
|
1357
|
+
if (selection.team === parent) {
|
|
1358
|
+
const result = await callParent(childRuntimeConfig!, "team_send_message", {
|
|
1359
|
+
targets: selection.teammates.map((teammate) => teammate.teammateId), message: params.message,
|
|
1360
|
+
interrupt: selection.teammates.filter((teammate) => interrupted.has(teammate.teammateId)).map((teammate) => teammate.teammateId),
|
|
1361
|
+
}, signal);
|
|
1362
|
+
statuses.push(...result.teams as JsonRecord[]);
|
|
1363
|
+
continue;
|
|
1364
|
+
}
|
|
1365
|
+
const team = teams.get(selection.team.teamId)!;
|
|
1366
|
+
for (const recipient of selection.teammates) enqueueDelivery(team, "main", team.members.get(recipient.name)!, params.message, interrupted.has(recipient.teammateId));
|
|
1367
|
+
statuses.push({ ...teamIdentity(team), status: formatStatus(team) });
|
|
1280
1368
|
}
|
|
1281
|
-
|
|
1282
|
-
const recipients = resolveRecipients(team, params.to);
|
|
1283
|
-
const interrupt = Boolean(params.interrupt);
|
|
1284
|
-
for (const recipient of recipients) enqueueDelivery(team, "main", recipient, params.message, interrupt);
|
|
1285
|
-
return toolResult({ accepted: true, team: team.name, from: "main", to: recipients.map((recipient) => recipient.name), interrupt });
|
|
1369
|
+
return toolResult({ published: true, teams: statuses, instruction: "Do not wait for replies. Teammates will message you back." });
|
|
1286
1370
|
},
|
|
1287
1371
|
}),
|
|
1288
1372
|
);
|
|
1289
1373
|
|
|
1290
1374
|
pi.registerTool(
|
|
1291
1375
|
defineTool({
|
|
1292
|
-
name: "
|
|
1376
|
+
name: "team_status",
|
|
1293
1377
|
label: "Team Status",
|
|
1294
1378
|
description: childRuntimeConfig
|
|
1295
|
-
? "
|
|
1296
|
-
: "Set
|
|
1297
|
-
promptSnippet: "Set/read team status maps",
|
|
1379
|
+
? "Omit `team` to set or read parent-team status. Set `team` to set or read an owned team's status."
|
|
1380
|
+
: "Set your own status for a team and/or read team statuses.",
|
|
1298
1381
|
renderShell: "self",
|
|
1299
|
-
renderCall: (args, theme, context) => renderTeamToolCall("
|
|
1300
|
-
renderResult: (result, options, theme, context) => renderTeamToolResult("
|
|
1382
|
+
renderCall: (args, theme, context) => renderTeamToolCall("team_status", args, theme, context, sessionTeammateRoster),
|
|
1383
|
+
renderResult: (result, options, theme, context) => renderTeamToolResult("team_status", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
1301
1384
|
parameters: Type.Object({
|
|
1302
|
-
team: Type.Optional(Type.String({ description: childRuntimeConfig ? "Owned team name. Omit to use the parent team." : "Team name
|
|
1385
|
+
team: Type.Optional(Type.String({ description: childRuntimeConfig ? "Owned team name or ID. Omit to use the parent team." : "Team name or ID. Omit to read all teams, or to set your status when exactly one owned team exists." })),
|
|
1303
1386
|
// TODO: make gerund and phrase optionality a XOR.
|
|
1304
|
-
gerund: Type.Optional(Type.String({ description: "
|
|
1305
|
-
phrase: Type.Optional(Type.String({ description: "Short
|
|
1306
|
-
}),
|
|
1387
|
+
gerund: Type.Optional(Type.String({ description: "One-word gerund for your status." })),
|
|
1388
|
+
phrase: Type.Optional(Type.String({ description: "Short, action-oriented status phrase." })),
|
|
1389
|
+
}, { additionalProperties: false }),
|
|
1307
1390
|
async execute(_toolCallId, params, signal) {
|
|
1308
1391
|
if (childRuntimeConfig && !params.team) {
|
|
1309
|
-
return toolResult(await callParent(childRuntimeConfig, "
|
|
1392
|
+
return toolResult(await callParent(childRuntimeConfig, "team_status", {
|
|
1310
1393
|
...(params.gerund === undefined ? {} : { gerund: params.gerund }),
|
|
1311
1394
|
...(params.phrase === undefined ? {} : { phrase: params.phrase }),
|
|
1312
1395
|
}, signal));
|
|
@@ -1317,32 +1400,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
1317
1400
|
const team = resolveTeam(owner, params.team);
|
|
1318
1401
|
updateStatus(team, "main", params.gerund, params.phrase);
|
|
1319
1402
|
logStatusDeclaration(team, "main", params.gerund, params.phrase);
|
|
1320
|
-
return toolResult({ team
|
|
1403
|
+
return toolResult({ ...teamIdentity(team), status: formatStatus(team) });
|
|
1321
1404
|
},
|
|
1322
1405
|
}),
|
|
1323
1406
|
);
|
|
1324
1407
|
|
|
1325
1408
|
pi.registerTool(
|
|
1326
1409
|
defineTool({
|
|
1327
|
-
name: "
|
|
1328
|
-
label: "
|
|
1329
|
-
description:
|
|
1330
|
-
? "Report your own context-window use when targets is omitted. When targets is present, report selected teammates in owned teams and yourself last."
|
|
1331
|
-
: "Report context-window use for selected teammates and main. Main's report is always last.",
|
|
1332
|
-
promptSnippet: "Report context-window use for selected teammates and main",
|
|
1410
|
+
name: "get_context_window_usage",
|
|
1411
|
+
label: "Context Window Usage",
|
|
1412
|
+
description: "Get context-window use of selected teammates. Your own window's use is always included.",
|
|
1333
1413
|
parameters: Type.Object({
|
|
1334
|
-
targets:
|
|
1335
|
-
|
|
1336
|
-
: Type.Array(Type.String({ minLength: 1 }), { description: "Teammate names. Use an empty list to report only main." }),
|
|
1337
|
-
}),
|
|
1414
|
+
targets: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: `${targetDescription} Omit or pass an empty list for only your own usage.` })),
|
|
1415
|
+
}, { additionalProperties: false }),
|
|
1338
1416
|
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
1339
|
-
|
|
1340
|
-
const text = formatContextWindowReport("You have", requireKnownContextUsage(context.getContextUsage()));
|
|
1341
|
-
return { content: [{ type: "text" as const, text }], details: {} };
|
|
1342
|
-
}
|
|
1343
|
-
const teammates = resolveContextTargets(owner, params.targets);
|
|
1417
|
+
const selections = resolveTargets(ownedTargetTeams(owner), params.targets ?? []);
|
|
1344
1418
|
const reports = await Promise.all(
|
|
1345
|
-
teammates.map(async (teammate) => formatContextWindowReport(
|
|
1419
|
+
selections.flatMap(({ team, teammates }) => teammates.map(async (teammate) => formatContextWindowReport(
|
|
1420
|
+
`Teammate ${teammate.name} (Pi session ID: ${teammate.teammateId}) on team ${team.teamName} (team ID: ${team.teamId}) has`,
|
|
1421
|
+
await getTeammateContextUsage(teams.get(team.teamId)!.members.get(teammate.name)!, signal),
|
|
1422
|
+
))),
|
|
1346
1423
|
);
|
|
1347
1424
|
reports.push(formatContextWindowReport("You have", requireKnownContextUsage(context.getContextUsage())));
|
|
1348
1425
|
return { content: [{ type: "text" as const, text: reports.join("\n") }], details: {} };
|
|
@@ -1353,16 +1430,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
1353
1430
|
// TODO: main could use more automatic meta/discoverability information in the return payload. To help orient around what has been read already, what hasn't been read, inside and outside the filtered space, how long is the log, etc.
|
|
1354
1431
|
pi.registerTool(
|
|
1355
1432
|
defineTool({
|
|
1356
|
-
name: "
|
|
1433
|
+
name: "team_log",
|
|
1357
1434
|
label: "Team Log",
|
|
1358
|
-
description: "Inspect
|
|
1359
|
-
promptSnippet: "Inspect team event log",
|
|
1435
|
+
description: "Inspect paged event logs for selected teammates or teams you own.",
|
|
1360
1436
|
renderShell: "self",
|
|
1361
|
-
renderCall: (args, theme, context) => renderTeamToolCall("
|
|
1362
|
-
renderResult: (result, options, theme, context) => renderTeamToolResult("
|
|
1437
|
+
renderCall: (args, theme, context) => renderTeamToolCall("team_log", args, theme, context, sessionTeammateRoster),
|
|
1438
|
+
renderResult: (result, options, theme, context) => renderTeamToolResult("team_log", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
1363
1439
|
parameters: Type.Object({
|
|
1364
|
-
|
|
1365
|
-
teammate: Type.Optional(Type.String({ description: "Filter to one teammate name" })),
|
|
1440
|
+
targets: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description: `${targetDescription} Omit for all teams you own.` })),
|
|
1366
1441
|
kind: Type.Optional(
|
|
1367
1442
|
Type.Array(Type.String({ minLength: 1 }), {
|
|
1368
1443
|
minItems: 1,
|
|
@@ -1372,30 +1447,42 @@ export default function (pi: ExtensionAPI) {
|
|
|
1372
1447
|
search: Type.Optional(Type.String({ description: "Case-insensitive substring search over summary, teammate, direction, kind, and details" })),
|
|
1373
1448
|
since: Type.Optional(Type.String({ description: "ISO timestamp filter; only entries at or after this time" })),
|
|
1374
1449
|
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, description: "Max rows to return, default 20, maximum 100" })),
|
|
1375
|
-
cursor: Type.Optional(Type.String({ description:
|
|
1376
|
-
}),
|
|
1450
|
+
cursor: Type.Optional(Type.String({ description: "Opaque cursor from the previous response. Keep the same targets and filters when paging." })),
|
|
1451
|
+
}, { additionalProperties: false }),
|
|
1377
1452
|
async execute(_toolCallId, params) {
|
|
1378
|
-
const
|
|
1379
|
-
const
|
|
1380
|
-
|
|
1453
|
+
const candidates = ownedTargetTeams(owner);
|
|
1454
|
+
const selections = resolveTargets(candidates, params.targets ?? candidates.map((team) => team.teamId));
|
|
1455
|
+
const entries = selections.flatMap((selection) => {
|
|
1456
|
+
const team = teams.get(selection.team.teamId)!;
|
|
1457
|
+
const names = new Set(selection.teammates.map((teammate) => teammate.name));
|
|
1458
|
+
return team.log.filter((entry) => selection.wholeTeam || names.has(entry.teammate!)).map((entry) => ({ ...entry, team: selection.team.teamId }));
|
|
1459
|
+
});
|
|
1460
|
+
const filtered = filterTeamLog(entries, {
|
|
1381
1461
|
kind: params.kind,
|
|
1382
1462
|
search: params.search,
|
|
1383
1463
|
since: params.since,
|
|
1384
1464
|
});
|
|
1385
1465
|
const page = pageTeamLog(filtered, { limit: params.limit, cursor: params.cursor });
|
|
1386
|
-
const
|
|
1466
|
+
const selectedTeams = selections.map((selection) => ({
|
|
1467
|
+
teamName: selection.team.teamName,
|
|
1468
|
+
teamId: selection.team.teamId,
|
|
1469
|
+
roster: selection.team.teammates.map((teammate) => teammate.name),
|
|
1470
|
+
entries: page.entries.filter((entry) => entry.team === selection.team.teamId),
|
|
1471
|
+
totalMatched: filtered.filter((entry) => entry.team === selection.team.teamId).length,
|
|
1472
|
+
}));
|
|
1473
|
+
const tables = selectedTeams.map((team) => renderTeamLogPage({ team: `${team.teamName} (team ID: ${team.teamId})`, entries: team.entries, totalMatched: team.totalMatched, returned: team.entries.length, limit: page.limit }));
|
|
1474
|
+
const text = [...tables, `Total: ${page.returned} of ${page.totalMatched} matching events.${page.nextCursor ? ` nextCursor="${page.nextCursor}"` : ""}`].join("\n\n");
|
|
1387
1475
|
|
|
1388
1476
|
return {
|
|
1389
1477
|
content: [{ type: "text" as const, text }],
|
|
1390
1478
|
details: {
|
|
1391
|
-
|
|
1392
|
-
roster: [...team.members.keys()],
|
|
1479
|
+
teams: selectedTeams,
|
|
1393
1480
|
entries: page.entries,
|
|
1394
1481
|
totalMatched: page.totalMatched,
|
|
1395
1482
|
returned: page.returned,
|
|
1396
1483
|
nextCursor: page.nextCursor,
|
|
1397
1484
|
filters: {
|
|
1398
|
-
|
|
1485
|
+
targets: params.targets,
|
|
1399
1486
|
kind: params.kind,
|
|
1400
1487
|
search: params.search,
|
|
1401
1488
|
since: params.since,
|
|
@@ -1413,20 +1500,19 @@ export default function (pi: ExtensionAPI) {
|
|
|
1413
1500
|
name: "team_shutdown",
|
|
1414
1501
|
label: "Team Shutdown",
|
|
1415
1502
|
description: "Stop a team and kill its teammate processes.",
|
|
1416
|
-
promptSnippet: "Stop a team and kill its teammate processes",
|
|
1417
1503
|
renderShell: "self",
|
|
1418
1504
|
renderCall: (args, theme, context) => renderTeamToolCall("team_shutdown", args, theme, context, sessionTeammateRoster),
|
|
1419
1505
|
renderResult: (result, options, theme, context) => renderTeamToolResult("team_shutdown", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
1420
1506
|
parameters: Type.Object({
|
|
1421
|
-
team: Type.Optional(Type.String({ description: "Team name
|
|
1422
|
-
}),
|
|
1507
|
+
team: Type.Optional(Type.String({ description: "Team name or ID. Omit when exactly one owned active team exists." })),
|
|
1508
|
+
}, { additionalProperties: false }),
|
|
1423
1509
|
async execute(_toolCallId, params) {
|
|
1424
1510
|
const team = resolveTeam(owner, params.team);
|
|
1425
|
-
const teammates = [...team.members.
|
|
1511
|
+
const teammates = [...team.members.values()].map(teammateReference);
|
|
1426
1512
|
const errors = await shutdownTeam(team);
|
|
1427
1513
|
closeCallbackServerIfUnused();
|
|
1428
1514
|
if (errors.length > 0) throw new Error(`Failed to close Herdr teammate pane(s): ${errors.join("; ")}`);
|
|
1429
|
-
return toolResult({ stopped: true,
|
|
1515
|
+
return toolResult({ ...teamIdentity(team), stopped: true, teammates });
|
|
1430
1516
|
},
|
|
1431
1517
|
}),
|
|
1432
1518
|
);
|