@giladbarnea/pi-simple-team 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts ADDED
@@ -0,0 +1,751 @@
1
+ import * as childProcess from "node:child_process";
2
+ import type { ChildProcess } from "node:child_process";
3
+ import crypto from "node:crypto";
4
+ import http from "node:http";
5
+ import { StringDecoder } from "node:string_decoder";
6
+ import { fileURLToPath } from "node:url";
7
+ import { defineTool, type ExtensionAPI, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
8
+ import { validateTeammateModels } from "./model-preflight.ts";
9
+ import { composeSystemPrompt } from "./system-prompt.ts";
10
+ import { readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
11
+ import { appendTeamLog, filterTeamLog, normalizeChildEvent, nowText, pageTeamLog, preview, renderTeamLogPage, type TeamLogEntry } from "./teamlog.ts";
12
+ import { renderTeamMessage, renderTeamToolCall, renderTeamToolResult, type TeamMessageDetails } from "./render.ts";
13
+ import { StringEnum } from "@earendil-works/pi-ai";
14
+ import { Type } from "typebox";
15
+
16
+ type ThinkingLevel = "low" | "medium" | "high" | "xhigh" | "max";
17
+
18
+ type JsonRecord = Record<string, unknown>;
19
+
20
+ interface TeamStatus {
21
+ word: string;
22
+ phrase: string;
23
+ updated: string;
24
+ }
25
+
26
+ interface RpcResponse extends JsonRecord {
27
+ type: "response";
28
+ id?: string;
29
+ command: string;
30
+ success: boolean;
31
+ error?: string;
32
+ data?: unknown;
33
+ }
34
+
35
+ interface PendingRequest {
36
+ resolve: (response: RpcResponse) => void;
37
+ reject: (error: Error) => void;
38
+ timeout: ReturnType<typeof setTimeout>;
39
+ }
40
+
41
+ interface TeammateSpec {
42
+ name: string;
43
+ prompt: string;
44
+ model: string;
45
+ thinking?: ThinkingLevel;
46
+ }
47
+
48
+ interface TeammateState {
49
+ name: string;
50
+ prompt: string;
51
+ model: string;
52
+ thinking: ThinkingLevel;
53
+ process: ChildProcess;
54
+ busy: boolean;
55
+ alive: boolean;
56
+ pendingRequests: Map<string, PendingRequest>;
57
+ deliveryQueue: Promise<void>;
58
+ recentEvents: JsonRecord[];
59
+ stderr: string;
60
+ }
61
+
62
+ interface TeamState {
63
+ owner: symbol;
64
+ ownerPi: ExtensionAPI;
65
+ name: string;
66
+ teamPrompt: string;
67
+ members: Map<string, TeammateState>;
68
+ statuses: Map<string, TeamStatus>;
69
+ created: string;
70
+ log: TeamLogEntry[];
71
+ nextLogSequence: number;
72
+ }
73
+
74
+ const teamLiteExtensionPath = fileURLToPath(import.meta.url);
75
+ const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
76
+ const defaultThinkingLevel: ThinkingLevel = "xhigh";
77
+ const teamMessageType = "pi-simple-team";
78
+ const teams = new Map<string, TeamState>();
79
+ const callbackToken = crypto.randomBytes(24).toString("hex");
80
+ let callbackServer: http.Server | undefined;
81
+ let callbackUrl = "";
82
+ let requestCounter = 0;
83
+
84
+ function status(word: string, phrase: string): TeamStatus {
85
+ return { word, phrase, updated: nowText() };
86
+ }
87
+
88
+ function compactName(name: string): string {
89
+ const trimmed = name.trim();
90
+ if (!trimmed) throw new Error("Name cannot be empty");
91
+ return trimmed;
92
+ }
93
+
94
+ function toolResult(payload: JsonRecord) {
95
+ return {
96
+ content: [{ type: "text" as const, text: JSON.stringify(payload, null, 2) }],
97
+ details: payload,
98
+ };
99
+ }
100
+
101
+ function sleep(milliseconds: number): Promise<void> {
102
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
103
+ }
104
+
105
+ function serializeJsonLine(value: unknown): string {
106
+ return `${JSON.stringify(value)}\n`;
107
+ }
108
+
109
+ function attachJsonlReader(stream: NodeJS.ReadableStream, onLine: (line: string) => void): void {
110
+ const decoder = new StringDecoder("utf8");
111
+ let buffer = "";
112
+
113
+ stream.on("data", (chunk: Buffer | string) => {
114
+ buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
115
+
116
+ while (true) {
117
+ const newlineIndex = buffer.indexOf("\n");
118
+ if (newlineIndex === -1) return;
119
+
120
+ let line = buffer.slice(0, newlineIndex);
121
+ buffer = buffer.slice(newlineIndex + 1);
122
+ if (line.endsWith("\r")) line = line.slice(0, -1);
123
+ onLine(line);
124
+ }
125
+ });
126
+
127
+ stream.on("end", () => {
128
+ buffer += decoder.end();
129
+ if (buffer.length > 0) onLine(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
130
+ });
131
+ }
132
+
133
+ function pushRecentEvent(teammate: TeammateState, event: JsonRecord): void {
134
+ teammate.recentEvents.push(event);
135
+ if (teammate.recentEvents.length > 200) teammate.recentEvents.shift();
136
+ }
137
+
138
+ function rejectPendingRequests(teammate: TeammateState, error: Error): void {
139
+ for (const pending of teammate.pendingRequests.values()) {
140
+ clearTimeout(pending.timeout);
141
+ pending.reject(error);
142
+ }
143
+ teammate.pendingRequests.clear();
144
+ }
145
+
146
+ function handleTeammateEvent(team: TeamState, teammate: TeammateState, event: JsonRecord): void {
147
+ pushRecentEvent(teammate, event);
148
+
149
+ if (event.type === "agent_start") teammate.busy = true;
150
+ if (event.type === "agent_end") teammate.busy = false;
151
+
152
+ const logInput = normalizeChildEvent(team.name, teammate.name, event);
153
+ if (logInput) appendTeamLog(team, logInput);
154
+
155
+ if (event.type !== "response") return;
156
+ const response = event as RpcResponse;
157
+ const requestId = response.id;
158
+ if (!requestId) return;
159
+
160
+ const pending = teammate.pendingRequests.get(requestId);
161
+ if (!pending) return;
162
+
163
+ teammate.pendingRequests.delete(requestId);
164
+ clearTimeout(pending.timeout);
165
+ pending.resolve(response);
166
+ }
167
+
168
+ function sendRpc(teammate: TeammateState, command: JsonRecord, timeoutMilliseconds = 30_000): Promise<RpcResponse> {
169
+ if (!teammate.alive || teammate.process.exitCode !== null) {
170
+ throw new Error(`Teammate ${teammate.name} is not alive`);
171
+ }
172
+
173
+ const id = `team-${++requestCounter}`;
174
+ const payload = { ...command, id };
175
+
176
+ return new Promise((resolve, reject) => {
177
+ const timeout = setTimeout(() => {
178
+ teammate.pendingRequests.delete(id);
179
+ reject(new Error(`Timed out waiting for ${String(command.type)} response from ${teammate.name}`));
180
+ }, timeoutMilliseconds);
181
+
182
+ teammate.pendingRequests.set(id, { resolve, reject, timeout });
183
+ teammate.process.stdin?.write(serializeJsonLine(payload));
184
+ });
185
+ }
186
+
187
+ async function requireSuccessfulResponse(response: RpcResponse, action: string): Promise<void> {
188
+ if (response.success) return;
189
+ throw new Error(`${action} failed: ${response.error ?? "unknown RPC error"}`);
190
+ }
191
+
192
+ async function getTeammateBusy(teammate: TeammateState): Promise<boolean> {
193
+ const response = await sendRpc(teammate, { type: "get_state" }, 10_000);
194
+ if (!response.success) return teammate.busy;
195
+ const data = response.data as { isStreaming?: boolean } | undefined;
196
+ teammate.busy = Boolean(data?.isStreaming);
197
+ return teammate.busy;
198
+ }
199
+
200
+ async function waitForIdle(teammate: TeammateState, timeoutMilliseconds = 30_000): Promise<void> {
201
+ const deadline = Date.now() + timeoutMilliseconds;
202
+
203
+ while (Date.now() < deadline) {
204
+ if (!(await getTeammateBusy(teammate))) return;
205
+ await sleep(100);
206
+ }
207
+
208
+ throw new Error(`Timed out waiting for ${teammate.name} to become idle`);
209
+ }
210
+
211
+ async function promptTeammate(team: TeamState, teammate: TeammateState, message: string): Promise<void> {
212
+ const response = await sendRpc(teammate, { type: "prompt", message });
213
+ if (response.success) {
214
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "ack", summary: "prompt accepted" });
215
+ return;
216
+ }
217
+
218
+ const fallback = await sendRpc(teammate, { type: "prompt", message, streamingBehavior: "steer" });
219
+ if (fallback.success) {
220
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "ack", summary: "steer fallback accepted" });
221
+ } else {
222
+ appendTeamLog(team, {
223
+ team: team.name,
224
+ teammate: teammate.name,
225
+ direction: "runtime",
226
+ kind: "error",
227
+ summary: preview(`steer fallback to ${teammate.name} failed: ${fallback.error ?? "unknown RPC error"}`),
228
+ });
229
+ }
230
+ await requireSuccessfulResponse(fallback, `steer fallback to ${teammate.name}`);
231
+ }
232
+
233
+ async function steerTeammate(team: TeamState, teammate: TeammateState, message: string): Promise<void> {
234
+ const response = await sendRpc(teammate, { type: "steer", message });
235
+ if (response.success) {
236
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "ack", summary: "steer accepted" });
237
+ return;
238
+ }
239
+ appendTeamLog(team, {
240
+ team: team.name,
241
+ teammate: teammate.name,
242
+ direction: "runtime",
243
+ kind: "error",
244
+ summary: preview(`steer to ${teammate.name} rejected: ${response.error ?? "unknown RPC error"}`),
245
+ });
246
+ await promptTeammate(team, teammate, message);
247
+ }
248
+
249
+ function formatTeammateMessage(team: TeamState, from: string, message: string): string {
250
+ return [`[from ${from} on team ${team.name}]`, message, "", "Current team status:", JSON.stringify(formatStatus(team), null, 2)].join("\n");
251
+ }
252
+
253
+ async function deliverToTeammate(team: TeamState, from: string, recipient: TeammateState, message: string, interrupt: boolean): Promise<void> {
254
+ const formattedMessage = formatTeammateMessage(team, from, message);
255
+ appendTeamLog(team, {
256
+ team: team.name,
257
+ teammate: recipient.name,
258
+ direction: from === "main" ? "main->teammate" : "teammate->teammate",
259
+ kind: "deliver",
260
+ summary: preview(message),
261
+ details: { from, to: recipient.name, interrupt },
262
+ });
263
+
264
+ if (interrupt && (recipient.busy || (await getTeammateBusy(recipient)))) {
265
+ await requireSuccessfulResponse(await sendRpc(recipient, { type: "abort" }, 60_000), `abort ${recipient.name}`);
266
+ await waitForIdle(recipient);
267
+ await promptTeammate(team, recipient, formattedMessage);
268
+ return;
269
+ }
270
+
271
+ if (recipient.busy || (await getTeammateBusy(recipient))) {
272
+ await steerTeammate(team, recipient, formattedMessage);
273
+ return;
274
+ }
275
+
276
+ await promptTeammate(team, recipient, formattedMessage);
277
+ }
278
+
279
+ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState, message: string, interrupt: boolean): void {
280
+ appendTeamLog(team, {
281
+ team: team.name,
282
+ teammate: recipient.name,
283
+ direction: from === "main" ? "main->teammate" : "teammate->teammate",
284
+ kind: "send",
285
+ summary: preview(message),
286
+ details: { from, to: recipient.name, interrupt },
287
+ });
288
+
289
+ recipient.deliveryQueue = recipient.deliveryQueue
290
+ .catch(() => undefined)
291
+ .then(() => deliverToTeammate(team, from, recipient, message, interrupt))
292
+ .catch((error) => {
293
+ const errorMessage = error instanceof Error ? error.message : String(error);
294
+ team.statuses.set(recipient.name, status("error", errorMessage));
295
+ appendTeamLog(team, {
296
+ team: team.name,
297
+ teammate: recipient.name,
298
+ direction: from === "main" ? "main->teammate" : "teammate->teammate",
299
+ kind: "error",
300
+ summary: preview(`delivery to ${recipient.name} failed: ${errorMessage}`),
301
+ details: { from, to: recipient.name, error: errorMessage },
302
+ });
303
+ });
304
+ }
305
+
306
+ function resolveTeam(owner: symbol, teamName?: string): TeamState {
307
+ const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
308
+ if (teamName) {
309
+ const team = teams.get(teamName);
310
+ if (!team || team.owner !== owner) throw new Error(`Unknown team: ${teamName}`);
311
+ return team;
312
+ }
313
+
314
+ if (ownedTeams.length === 1) return ownedTeams[0];
315
+ if (ownedTeams.length === 0) throw new Error("No teams exist. Use team_spawn first.");
316
+ throw new Error(`Multiple teams exist: ${ownedTeams.map((team) => team.name).join(", ")}. Pass team explicitly.`);
317
+ }
318
+
319
+ function resolveCallbackTeam(teamName: string): TeamState {
320
+ const team = teams.get(teamName);
321
+ if (!team) throw new Error(`Unknown team: ${teamName}`);
322
+ return team;
323
+ }
324
+
325
+ function resolveRecipients(team: TeamState, recipientNames: string[]): TeammateState[] {
326
+ const names = recipientNames.map(compactName);
327
+ const recipients = names.map((name) => team.members.get(name));
328
+ const missing = names.filter((name, index) => recipients[index] === undefined);
329
+ if (missing.length > 0) throw new Error(`Unknown teammate(s) in ${team.name}: ${missing.join(", ")}`);
330
+ return recipients as TeammateState[];
331
+ }
332
+
333
+ function formatStatus(team: TeamState): Record<string, TeamStatus> {
334
+ return Object.fromEntries([...team.statuses.entries()].sort(([a], [b]) => a.localeCompare(b)));
335
+ }
336
+
337
+ function allStatuses(owner: symbol): Record<string, Record<string, TeamStatus>> {
338
+ return Object.fromEntries([...teams.values()].filter((team) => team.owner === owner).map((team) => [team.name, formatStatus(team)]));
339
+ }
340
+
341
+ function updateStatus(team: TeamState, participant: string, word?: string, phrase?: string): void {
342
+ if (word === undefined && phrase === undefined) return;
343
+ const previous = team.statuses.get(participant) ?? status("active", "Working");
344
+ team.statuses.set(participant, status(word ?? previous.word, phrase ?? previous.phrase));
345
+ }
346
+
347
+ function startTeammate(team: TeamState, teammateSpec: TeammateSpec, participants: string[]): TeammateState {
348
+ const teammateName = compactName(teammateSpec.name);
349
+ const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
350
+ const args = [
351
+ "--mode",
352
+ "rpc",
353
+ "-e",
354
+ teamLiteExtensionPath,
355
+ "--no-prompt-templates",
356
+ "--no-themes",
357
+ "--model",
358
+ teammateSpec.model,
359
+ "--thinking",
360
+ thinking,
361
+ "--system-prompt",
362
+ composeSystemPrompt(team.name, team.teamPrompt, teammateName, teammateSpec.prompt, participants),
363
+ ];
364
+
365
+ const proc = childProcess.spawn("pi", args, {
366
+ cwd: process.cwd(),
367
+ stdio: ["pipe", "pipe", "pipe"],
368
+ env: {
369
+ ...process.env,
370
+ PI_SIMPLE_TEAM_CHILD: "1",
371
+ PI_SIMPLE_TEAM_CALLBACK_URL: callbackUrl,
372
+ PI_SIMPLE_TEAM_CALLBACK_TOKEN: callbackToken,
373
+ PI_SIMPLE_TEAM_TEAM: team.name,
374
+ PI_SIMPLE_TEAM_MEMBER: teammateName,
375
+ },
376
+ });
377
+
378
+ const teammate: TeammateState = {
379
+ name: teammateName,
380
+ prompt: teammateSpec.prompt,
381
+ model: teammateSpec.model,
382
+ thinking,
383
+ process: proc,
384
+ busy: false,
385
+ alive: true,
386
+ pendingRequests: new Map(),
387
+ deliveryQueue: Promise.resolve(),
388
+ recentEvents: [],
389
+ stderr: "",
390
+ };
391
+
392
+ attachJsonlReader(proc.stdout!, (line) => {
393
+ if (!line.trim()) return;
394
+ try {
395
+ handleTeammateEvent(team, teammate, JSON.parse(line) as JsonRecord);
396
+ } catch {
397
+ teammate.stderr += `\n[unparsed stdout] ${line}`;
398
+ }
399
+ });
400
+
401
+ proc.stderr?.on("data", (chunk: Buffer | string) => {
402
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
403
+ teammate.stderr += text;
404
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "stderr", summary: preview(text) });
405
+ });
406
+
407
+ proc.on("exit", (code, signal) => {
408
+ teammate.alive = false;
409
+ teammate.busy = false;
410
+ rejectPendingRequests(teammate, new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
411
+ team.statuses.set(teammate.name, status("stopped", `Exited code=${code} signal=${signal}`));
412
+ appendTeamLog(team, {
413
+ team: team.name,
414
+ teammate: teammate.name,
415
+ direction: "runtime",
416
+ kind: "exit",
417
+ summary: `exited (code=${code}, signal=${signal})`,
418
+ details: { code, signal },
419
+ });
420
+ });
421
+
422
+ appendTeamLog(team, {
423
+ team: team.name,
424
+ teammate: teammate.name,
425
+ direction: "runtime",
426
+ kind: "spawn",
427
+ summary: `spawned ${teammate.name} (model=${teammate.model}, thinking=${teammate.thinking})`,
428
+ });
429
+
430
+ return teammate;
431
+ }
432
+
433
+ function shutdownTeam(team: TeamState): void {
434
+ for (const teammate of team.members.values()) {
435
+ teammate.alive = false;
436
+ teammate.process.kill("SIGTERM");
437
+ setTimeout(() => {
438
+ if (teammate.process.exitCode === null) teammate.process.kill("SIGKILL");
439
+ }, 1_000).unref();
440
+ }
441
+ teams.delete(team.name);
442
+ }
443
+
444
+ function closeCallbackServerIfUnused(): void {
445
+ if (teams.size > 0 || !callbackServer) return;
446
+ callbackServer.close();
447
+ callbackServer = undefined;
448
+ callbackUrl = "";
449
+ }
450
+
451
+ async function ensureCallbackServer(): Promise<void> {
452
+ if (callbackServer) return;
453
+
454
+ callbackServer = http.createServer((request, response) => {
455
+ void handleCallbackRequest(request, response);
456
+ });
457
+
458
+ await new Promise<void>((resolve) => {
459
+ callbackServer!.listen(0, "127.0.0.1", () => {
460
+ const address = callbackServer!.address();
461
+ if (!address || typeof address === "string") throw new Error("Team callback server did not get a port");
462
+ callbackUrl = `http://127.0.0.1:${address.port}/callback`;
463
+ resolve();
464
+ });
465
+ });
466
+ }
467
+
468
+ async function readJsonBody(request: http.IncomingMessage): Promise<JsonRecord> {
469
+ const chunks: Buffer[] = [];
470
+ for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
471
+ return JSON.parse(Buffer.concat(chunks).toString("utf8")) as JsonRecord;
472
+ }
473
+
474
+ function writeJson(response: http.ServerResponse, statusCode: number, payload: JsonRecord): void {
475
+ const body = JSON.stringify(payload);
476
+ response.writeHead(statusCode, {
477
+ "content-type": "application/json",
478
+ "content-length": Buffer.byteLength(body),
479
+ });
480
+ response.end(body);
481
+ }
482
+
483
+ async function handleCallbackRequest(request: http.IncomingMessage, response: http.ServerResponse): Promise<void> {
484
+ try {
485
+ const body = await readJsonBody(request);
486
+ if (body.token !== callbackToken) {
487
+ writeJson(response, 403, { error: "invalid token" });
488
+ return;
489
+ }
490
+
491
+ const team = resolveCallbackTeam(String(body.team));
492
+ const from = compactName(String(body.from));
493
+ const tool = String(body.tool);
494
+ const args = (body.args ?? {}) as JsonRecord;
495
+
496
+ if (tool === "teamsend") {
497
+ const recipients = resolveRecipients(team, (args.to ?? []) as string[]);
498
+ const message = String(args.message ?? "");
499
+ const interrupt = Boolean(args.interrupt);
500
+ for (const recipient of recipients) enqueueDelivery(team, from, recipient, message, interrupt);
501
+ writeJson(response, 200, { accepted: true, team: team.name, from, to: recipients.map((recipient) => recipient.name), interrupt });
502
+ return;
503
+ }
504
+
505
+ if (tool === "teammain") {
506
+ const rawMessage = String(args.message ?? "");
507
+ const details: TeamMessageDetails = { team: team.name, from, sentAt: nowText(), message: rawMessage };
508
+ appendTeamLog(team, { team: team.name, teammate: from, direction: "teammate->main", kind: "main_message", summary: preview(rawMessage) });
509
+ team.ownerPi.sendMessage(
510
+ { customType: teamMessageType, content: `[${team.name}/${from}] ${rawMessage}`, display: true, details },
511
+ { deliverAs: "steer", triggerTurn: true },
512
+ );
513
+ writeJson(response, 200, { accepted: true, team: team.name, from, to: "main" });
514
+ return;
515
+ }
516
+
517
+ if (tool === "teamstatus") {
518
+ updateStatus(team, from, args.word as string | undefined, args.phrase as string | undefined);
519
+ appendTeamLog(team, {
520
+ team: team.name,
521
+ teammate: from,
522
+ direction: "runtime",
523
+ kind: "status",
524
+ summary: preview(`${String(args.word ?? "")} ${String(args.phrase ?? "")}`.trim()),
525
+ });
526
+ writeJson(response, 200, { team: team.name, status: formatStatus(team) });
527
+ return;
528
+ }
529
+
530
+ writeJson(response, 400, { error: `unknown tool: ${tool}` });
531
+ } catch (error) {
532
+ writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
533
+ }
534
+ }
535
+
536
+ const teammateSchema = Type.Object({
537
+ name: Type.String({ description: "Teammate name" }),
538
+ prompt: Type.String({ description: "Individual teammate system prompt" }),
539
+ model: Type.String({ description: "Model pattern or provider/model id for this teammate" }),
540
+ thinking: Type.Optional(StringEnum(thinkingLevels, { description: "Thinking level for this teammate. Defaults to xhigh.", default: defaultThinkingLevel })),
541
+ });
542
+
543
+ export default function (pi: ExtensionAPI) {
544
+ const childRuntimeConfig = readChildRuntimeConfig();
545
+ if (childRuntimeConfig) {
546
+ registerChildTools(pi, childRuntimeConfig);
547
+ return;
548
+ }
549
+
550
+ const owner = Symbol("pi-simple-team-owner");
551
+ pi.registerMessageRenderer(teamMessageType, (message, _options, theme) => renderTeamMessage(message, theme, getMarkdownTheme()));
552
+
553
+ pi.on("session_shutdown", async () => {
554
+ for (const team of [...teams.values()]) {
555
+ if (team.owner === owner) shutdownTeam(team);
556
+ }
557
+ closeCallbackServerIfUnused();
558
+ });
559
+
560
+ pi.registerTool(
561
+ defineTool({
562
+ name: "team_spawn",
563
+ label: "Team Spawn",
564
+ description: "Spawn a persistent team of RPC Pi teammates with fresh context windows. The main agent is included automatically; do not specify it as a teammate.",
565
+ promptSnippet: "Spawn persistent RPC Pi teammate processes",
566
+ renderShell: "self",
567
+ renderCall: (args, theme, context) => renderTeamToolCall("team_spawn", args, theme, context),
568
+ renderResult: (result, options, theme, context) => renderTeamToolResult("team_spawn", result, options, theme, context),
569
+ parameters: Type.Object({
570
+ team: Type.String({ description: "Team name" }),
571
+ teamPrompt: Type.String({ description: "Common team system prompt" }),
572
+ teammates: Type.Array(teammateSchema, { description: "Teammates to spawn" }),
573
+ }),
574
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
575
+ const teamName = compactName(params.team);
576
+ if (teams.has(teamName)) throw new Error(`Team already exists: ${teamName}`);
577
+
578
+ const teammateSpecs = params.teammates as TeammateSpec[];
579
+ const teammateNames = teammateSpecs.map((teammate) => compactName(teammate.name));
580
+ const duplicateNames = teammateNames.filter((name, index) => teammateNames.indexOf(name) !== index);
581
+ if (duplicateNames.length > 0) throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
582
+ if (teammateNames.includes("main")) throw new Error('"main" is reserved');
583
+
584
+ await validateTeammateModels(teammateSpecs);
585
+ await ensureCallbackServer();
586
+
587
+ const team: TeamState = {
588
+ owner,
589
+ ownerPi: pi,
590
+ name: teamName,
591
+ teamPrompt: params.teamPrompt,
592
+ members: new Map(),
593
+ statuses: new Map([["main", status("available", "Main agent")]]),
594
+ created: nowText(),
595
+ log: [],
596
+ nextLogSequence: 1,
597
+ };
598
+
599
+ teams.set(teamName, team);
600
+ try {
601
+ for (const teammateSpec of teammateSpecs) {
602
+ const teammate = startTeammate(team, teammateSpec, teammateNames);
603
+ team.members.set(teammate.name, teammate);
604
+ team.statuses.set(teammate.name, status("idle", "Spawned"));
605
+ }
606
+ } catch (error) {
607
+ shutdownTeam(team);
608
+ closeCallbackServerIfUnused();
609
+ throw error;
610
+ }
611
+
612
+ return toolResult({
613
+ accepted: true,
614
+ team: team.name,
615
+ teammates: [...team.members.keys()],
616
+ status: formatStatus(team),
617
+ });
618
+ },
619
+ }),
620
+ );
621
+
622
+ pi.registerTool(
623
+ defineTool({
624
+ name: "teamsend",
625
+ label: "Team Send",
626
+ description: "Send a message from main to teammate(s). Fire-and-forget; does not wait for replies.",
627
+ promptSnippet: "Send a message from main to teammate(s)",
628
+ renderShell: "self",
629
+ renderCall: (args, theme, context) => renderTeamToolCall("teamsend", args, theme, context),
630
+ renderResult: (result, options, theme, context) => renderTeamToolResult("teamsend", result, options, theme, context, getMarkdownTheme()),
631
+ parameters: Type.Object({
632
+ team: Type.Optional(Type.String({ description: "Team name; optional only when exactly one team exists" })),
633
+ to: Type.Array(Type.String(), { description: "Recipient teammate names" }),
634
+ message: Type.String({ description: "Message to send" }),
635
+ interrupt: Type.Optional(Type.Boolean({ description: "Abort busy recipients before delivery" })),
636
+ }),
637
+ async execute(_toolCallId, params) {
638
+ const team = resolveTeam(owner, params.team);
639
+ const recipients = resolveRecipients(team, params.to);
640
+ const interrupt = Boolean(params.interrupt);
641
+ for (const recipient of recipients) enqueueDelivery(team, "main", recipient, params.message, interrupt);
642
+ return toolResult({ accepted: true, team: team.name, from: "main", to: recipients.map((recipient) => recipient.name), interrupt });
643
+ },
644
+ }),
645
+ );
646
+
647
+ pi.registerTool(
648
+ defineTool({
649
+ name: "teamstatus",
650
+ label: "Team Status",
651
+ description: "Set main's status for a team and/or read team statuses.",
652
+ promptSnippet: "Set/read team status maps",
653
+ renderShell: "self",
654
+ renderCall: (args, theme, context) => renderTeamToolCall("teamstatus", args, theme, context),
655
+ renderResult: (result, options, theme, context) => renderTeamToolResult("teamstatus", result, options, theme, context),
656
+ parameters: Type.Object({
657
+ team: Type.Optional(Type.String({ description: "Team name; optional for listing all statuses or when exactly one team exists" })),
658
+ word: Type.Optional(Type.String({ description: "One-word main status" })),
659
+ phrase: Type.Optional(Type.String({ description: "Short main status phrase" })),
660
+ }),
661
+ async execute(_toolCallId, params) {
662
+ if (!params.team && params.word === undefined && params.phrase === undefined) {
663
+ return toolResult({ teams: allStatuses(owner) });
664
+ }
665
+ const team = resolveTeam(owner, params.team);
666
+ updateStatus(team, "main", params.word, params.phrase);
667
+ appendTeamLog(team, {
668
+ team: team.name,
669
+ teammate: "main",
670
+ direction: "runtime",
671
+ kind: "status",
672
+ summary: preview(`${params.word ?? ""} ${params.phrase ?? ""}`.trim()),
673
+ });
674
+ return toolResult({ team: team.name, status: formatStatus(team) });
675
+ },
676
+ }),
677
+ );
678
+
679
+ pi.registerTool(
680
+ defineTool({
681
+ name: "teamlog",
682
+ label: "Team Log",
683
+ description: "Inspect a compact, paged, filterable event log for a pi-simple-team team.",
684
+ promptSnippet: "Inspect team event log",
685
+ renderShell: "self",
686
+ renderCall: (args, theme, context) => renderTeamToolCall("teamlog", args, theme, context),
687
+ renderResult: (result, options, theme, context) => renderTeamToolResult("teamlog", result, options, theme, context),
688
+ parameters: Type.Object({
689
+ team: Type.Optional(Type.String({ description: "Team name; optional only when exactly one team exists" })),
690
+ teammate: Type.Optional(Type.String({ description: "Filter to one teammate name" })),
691
+ kind: Type.Optional(Type.String({ description: "Filter to one normalized event kind" })),
692
+ search: Type.Optional(Type.String({ description: "Case-insensitive substring search over summary, teammate, direction, kind, and details" })),
693
+ since: Type.Optional(Type.String({ description: "ISO timestamp filter; only entries at or after this time" })),
694
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, description: "Max rows to return, default 20, maximum 100" })),
695
+ cursor: Type.Optional(Type.String({ description: 'Opaque cursor from a previous response, e.g. "before:54"' })),
696
+ }),
697
+ async execute(_toolCallId, params) {
698
+ const team = resolveTeam(owner, params.team);
699
+ const filtered = filterTeamLog(team.log, {
700
+ teammate: params.teammate,
701
+ kind: params.kind,
702
+ search: params.search,
703
+ since: params.since,
704
+ });
705
+ const page = pageTeamLog(filtered, { limit: params.limit, cursor: params.cursor });
706
+ const text = renderTeamLogPage({ team: team.name, ...page });
707
+
708
+ return {
709
+ content: [{ type: "text" as const, text }],
710
+ details: {
711
+ team: team.name,
712
+ entries: page.entries,
713
+ totalMatched: page.totalMatched,
714
+ returned: page.returned,
715
+ nextCursor: page.nextCursor,
716
+ filters: {
717
+ teammate: params.teammate,
718
+ kind: params.kind,
719
+ search: params.search,
720
+ since: params.since,
721
+ limit: page.limit,
722
+ cursor: params.cursor,
723
+ },
724
+ },
725
+ };
726
+ },
727
+ }),
728
+ );
729
+
730
+ pi.registerTool(
731
+ defineTool({
732
+ name: "team_shutdown",
733
+ label: "Team Shutdown",
734
+ description: "Stop a team and kill its teammate processes.",
735
+ promptSnippet: "Stop a team and kill its teammate processes",
736
+ renderShell: "self",
737
+ renderCall: (args, theme, context) => renderTeamToolCall("team_shutdown", args, theme, context),
738
+ renderResult: (result, options, theme, context) => renderTeamToolResult("team_shutdown", result, options, theme, context),
739
+ parameters: Type.Object({
740
+ team: Type.Optional(Type.String({ description: "Team name; optional only when exactly one team exists" })),
741
+ }),
742
+ async execute(_toolCallId, params) {
743
+ const team = resolveTeam(owner, params.team);
744
+ const teammates = [...team.members.keys()];
745
+ shutdownTeam(team);
746
+ closeCallbackServerIfUnused();
747
+ return toolResult({ stopped: true, team: team.name, teammates });
748
+ },
749
+ }),
750
+ );
751
+ }