@giladbarnea/pi-simple-team 1.0.12 → 1.0.13

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 CHANGED
@@ -69,7 +69,11 @@ Ask your main agent for a team.
69
69
  - ⚡ Sub-second, when the recipient is idle.
70
70
  - 🏎️ The moment the current bout of work ends, when busy.
71
71
 
72
+ ### Herdr, first-class.
72
73
 
74
+ `pi-simple-team` gives each teammate a Pi session in its own [Herdr](https://herdr.dev) pane. Just ask your agent to do that.
75
+
76
+ You get a live view of the room. Main and teammates keep using the same tools.
73
77
 
74
78
  ### Statuses everyone can see.
75
79
 
package/child-tools.ts CHANGED
@@ -1,13 +1,22 @@
1
- import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import * as http from "node:http";
2
+ import { defineTool, getMarkdownTheme, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
3
  import { Type } from "typebox";
4
+ import { renderTeamMessage } from "./render.ts";
3
5
 
4
6
  type JsonRecord = Record<string, unknown>;
5
7
 
8
+ const teamMessageType = "pi-simple-team";
9
+ const defaultVisibleInterruptWaitTimeoutMilliseconds = 25_000;
10
+ const visibleLifecycleRetryAttempts = 3;
11
+
6
12
  export interface ChildRuntimeConfig {
7
13
  callbackUrl: string;
8
14
  callbackToken: string;
9
15
  teamName: string;
10
16
  teammateName: string;
17
+ visible: boolean;
18
+ participants: string[];
19
+ interruptWaitTimeoutMilliseconds?: number;
11
20
  }
12
21
 
13
22
  function requiredEnvironmentVariable(name: string): string {
@@ -16,12 +25,23 @@ function requiredEnvironmentVariable(name: string): string {
16
25
  return value;
17
26
  }
18
27
 
28
+ function readParticipants(): string[] {
29
+ const value = requiredEnvironmentVariable("PI_SIMPLE_TEAM_PARTICIPANTS");
30
+ const participants = JSON.parse(value) as unknown;
31
+ if (!Array.isArray(participants) || participants.some((participant) => typeof participant !== "string")) {
32
+ throw new Error("PI_SIMPLE_TEAM_PARTICIPANTS must be a JSON string array");
33
+ }
34
+ return participants;
35
+ }
36
+
19
37
  function readRequiredChildRuntimeConfig(): ChildRuntimeConfig {
20
38
  return {
21
39
  callbackUrl: requiredEnvironmentVariable("PI_SIMPLE_TEAM_CALLBACK_URL"),
22
40
  callbackToken: requiredEnvironmentVariable("PI_SIMPLE_TEAM_CALLBACK_TOKEN"),
23
41
  teamName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_TEAM"),
24
42
  teammateName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_MEMBER"),
43
+ visible: process.env.PI_SIMPLE_TEAM_VISIBLE_CHILD === "1",
44
+ participants: readParticipants(),
25
45
  };
26
46
  }
27
47
 
@@ -58,7 +78,172 @@ function toolResult(payload: JsonRecord): { content: [{ type: "text"; text: stri
58
78
  };
59
79
  }
60
80
 
81
+ function writeJson(response: http.ServerResponse, statusCode: number, payload: JsonRecord): void {
82
+ const body = JSON.stringify(payload);
83
+ response.writeHead(statusCode, {
84
+ "content-type": "application/json",
85
+ "content-length": Buffer.byteLength(body),
86
+ });
87
+ response.end(body);
88
+ }
89
+
90
+ async function readJsonBody(request: http.IncomingMessage): Promise<JsonRecord> {
91
+ const chunks: Buffer[] = [];
92
+ for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
93
+ return JSON.parse(Buffer.concat(chunks).toString("utf8")) as JsonRecord;
94
+ }
95
+
96
+ interface VisibleDelivery {
97
+ team: string;
98
+ from: string;
99
+ to: string;
100
+ sentAt: string;
101
+ message: string;
102
+ formattedMessage: string;
103
+ interrupt: boolean;
104
+ }
105
+
106
+ function startVisibleChild(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
107
+ let server: http.Server | undefined;
108
+ let activeContext: ExtensionContext | undefined;
109
+ let idle = true;
110
+ let idleWaiters: Array<() => void> = [];
111
+ let lifecycleQueue: Promise<void> = Promise.resolve();
112
+ let lifecycleError: Error | undefined;
113
+
114
+ const notifyParent = (event: JsonRecord): Promise<void> => {
115
+ lifecycleQueue = lifecycleQueue.then(async () => {
116
+ if (lifecycleError) return;
117
+ for (let attempt = 1; attempt <= visibleLifecycleRetryAttempts; attempt += 1) {
118
+ try {
119
+ await callParent(config, "visible_event", { event });
120
+ return;
121
+ } catch (error) {
122
+ if (attempt === visibleLifecycleRetryAttempts) lifecycleError = error instanceof Error ? error : new Error(String(error));
123
+ }
124
+ }
125
+ });
126
+ return lifecycleQueue;
127
+ };
128
+
129
+ const waitForIdle = async (): Promise<void> => {
130
+ if (idle) return;
131
+ await new Promise<void>((resolve, reject) => {
132
+ let resolveIdle: () => void;
133
+ const timeout = setTimeout(() => {
134
+ idleWaiters = idleWaiters.filter((waiter) => waiter !== resolveIdle);
135
+ reject(new Error("Timed out waiting for visible child to settle after interrupt"));
136
+ }, config.interruptWaitTimeoutMilliseconds ?? defaultVisibleInterruptWaitTimeoutMilliseconds);
137
+ resolveIdle = (): void => {
138
+ clearTimeout(timeout);
139
+ resolve();
140
+ };
141
+ idleWaiters.push(resolveIdle);
142
+ });
143
+ };
144
+
145
+ const markIdle = (): void => {
146
+ idle = true;
147
+ activeContext = undefined;
148
+ const waiters = idleWaiters;
149
+ idleWaiters = [];
150
+ for (const resolve of waiters) resolve();
151
+ };
152
+
153
+ pi.on("agent_start", (event, context) => {
154
+ idle = false;
155
+ activeContext = context;
156
+ notifyParent({ type: "agent_start" });
157
+ });
158
+ pi.on("agent_end", (event) => {
159
+ notifyParent({ type: "agent_end", messages: event.messages });
160
+ });
161
+ pi.on("agent_settled", () => {
162
+ notifyParent({ type: "agent_settled" });
163
+ markIdle();
164
+ });
165
+ pi.on("tool_execution_start", (event) => {
166
+ notifyParent({ type: "tool_execution_start", toolCallId: event.toolCallId, toolName: event.toolName, args: event.args });
167
+ });
168
+ pi.on("tool_execution_end", (event) => {
169
+ notifyParent({ type: "tool_execution_end", toolCallId: event.toolCallId, toolName: event.toolName, isError: event.isError, result: event.result });
170
+ });
171
+ pi.on("session_start", async (_event, context) => {
172
+ server = http.createServer((request, response) => {
173
+ void (async () => {
174
+ try {
175
+ const body = await readJsonBody(request);
176
+ if (body.token !== config.callbackToken) {
177
+ writeJson(response, 403, { error: "invalid token" });
178
+ return;
179
+ }
180
+
181
+ if (body.tool !== "deliver") {
182
+ writeJson(response, 400, { error: `unknown tool: ${String(body.tool)}` });
183
+ return;
184
+ }
185
+
186
+ const delivery = body.args as unknown as VisibleDelivery;
187
+ if (lifecycleError) throw new Error(`Visible lifecycle callback failed: ${lifecycleError.message}`);
188
+ if (delivery.interrupt && activeContext) {
189
+ activeContext.abort();
190
+ await waitForIdle();
191
+ }
192
+
193
+ pi.sendMessage(
194
+ {
195
+ customType: teamMessageType,
196
+ content: delivery.formattedMessage,
197
+ display: true,
198
+ details: {
199
+ team: delivery.team,
200
+ from: delivery.from,
201
+ to: delivery.to,
202
+ sentAt: delivery.sentAt,
203
+ message: delivery.message,
204
+ },
205
+ },
206
+ { deliverAs: "steer", triggerTurn: true },
207
+ );
208
+ writeJson(response, 200, { accepted: true, team: config.teamName, from: delivery.from, to: delivery.to, interrupt: delivery.interrupt });
209
+ } catch (error) {
210
+ writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
211
+ }
212
+ })();
213
+ });
214
+
215
+ await new Promise<void>((resolve, reject) => {
216
+ server!.once("error", reject);
217
+ server!.listen(0, "127.0.0.1", () => resolve());
218
+ });
219
+ const address = server.address();
220
+ if (!address || typeof address === "string") throw new Error("Visible teammate server did not get a port");
221
+
222
+ try {
223
+ await callParent(config, "visible_register", { url: `http://127.0.0.1:${address.port}/deliver` });
224
+ } catch (error) {
225
+ context.shutdown();
226
+ throw error;
227
+ }
228
+ });
229
+
230
+ pi.on("session_shutdown", async (event) => {
231
+ markIdle();
232
+ await notifyParent({ type: "session_shutdown", reason: event.reason });
233
+ await new Promise<void>((resolve, reject) => {
234
+ if (!server) {
235
+ resolve();
236
+ return;
237
+ }
238
+ server.close((error) => (error ? reject(error) : resolve()));
239
+ });
240
+ });
241
+ }
242
+
61
243
  export function registerChildTools(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
244
+ pi.registerMessageRenderer(teamMessageType, (message, _options, theme) => renderTeamMessage(message, theme, getMarkdownTheme(), config.participants));
245
+ if (config.visible) startVisibleChild(pi, config);
246
+
62
247
  pi.registerTool(
63
248
  defineTool({
64
249
  name: "teamsend",
package/index.ts CHANGED
@@ -45,12 +45,20 @@ interface TeammateSpec {
45
45
  thinking?: ThinkingLevel;
46
46
  }
47
47
 
48
+ type TeammateTransport = "rpc" | "herdr";
49
+
48
50
  interface TeammateState {
49
51
  name: string;
50
52
  prompt: string;
51
53
  model: string;
52
54
  thinking: ThinkingLevel;
53
- process: ChildProcess;
55
+ transport: TeammateTransport;
56
+ process?: ChildProcess;
57
+ paneId?: string;
58
+ visibleUrl?: string;
59
+ visibleReady?: Promise<void>;
60
+ resolveVisibleReady?: () => void;
61
+ rejectVisibleReady?: (error: Error) => void;
54
62
  busy: boolean;
55
63
  alive: boolean;
56
64
  pendingRequests: Map<string, PendingRequest>;
@@ -63,6 +71,7 @@ interface TeamState {
63
71
  owner: symbol;
64
72
  ownerPi: ExtensionAPI;
65
73
  name: string;
74
+ showOnHerdrPanes: boolean;
66
75
  teamPrompt: string;
67
76
  members: Map<string, TeammateState>;
68
77
  statuses: Map<string, TeamStatus>;
@@ -74,6 +83,7 @@ interface TeamState {
74
83
  const teamLiteExtensionPath = fileURLToPath(import.meta.url);
75
84
  const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
76
85
  const defaultThinkingLevel: ThinkingLevel = "xhigh";
86
+ const visibleDeliveryTimeoutMilliseconds = 30_000;
77
87
  const teamMessageType = "pi-simple-team";
78
88
  const teams = new Map<string, TeamState>();
79
89
  const callbackToken = crypto.randomBytes(24).toString("hex");
@@ -102,6 +112,41 @@ function sleep(milliseconds: number): Promise<void> {
102
112
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
103
113
  }
104
114
 
115
+ interface CommandResult {
116
+ stdout: string;
117
+ stderr: string;
118
+ }
119
+
120
+ function runCommand(command: string, args: string[], timeoutMilliseconds = 30_000): Promise<CommandResult> {
121
+ return new Promise((resolve, reject) => {
122
+ childProcess.execFile(command, args, { timeout: timeoutMilliseconds, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
123
+ if (error) {
124
+ reject(new Error(`${command} ${args.join(" ")} failed: ${error.message}${stderr.trim() ? `\n${stderr.trim()}` : ""}`));
125
+ return;
126
+ }
127
+ resolve({ stdout, stderr });
128
+ });
129
+ });
130
+ }
131
+
132
+ async function validateHerdrAvailability(): Promise<string> {
133
+ const tabId = process.env.HERDR_TAB_ID?.trim();
134
+ if (!tabId) throw new Error("showOnHerdrPanes requires HERDR_TAB_ID in the main Pi process");
135
+
136
+ let result: CommandResult;
137
+ try {
138
+ result = await runCommand("herdr", ["status", "--json"], 10_000);
139
+ } catch (error) {
140
+ throw new Error(`showOnHerdrPanes requires an available Herdr server: ${error instanceof Error ? error.message : String(error)}`);
141
+ }
142
+
143
+ const status = JSON.parse(result.stdout) as { server?: { running?: boolean; compatible?: boolean } };
144
+ if (!status.server?.running || status.server.compatible === false) {
145
+ throw new Error("showOnHerdrPanes requires a running compatible Herdr server");
146
+ }
147
+ return tabId;
148
+ }
149
+
105
150
  function serializeJsonLine(value: unknown): string {
106
151
  return `${JSON.stringify(value)}\n`;
107
152
  }
@@ -166,8 +211,8 @@ function handleTeammateEvent(team: TeamState, teammate: TeammateState, event: Js
166
211
  }
167
212
 
168
213
  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`);
214
+ if (teammate.transport !== "rpc" || !teammate.process || !teammate.alive || teammate.process.exitCode !== null) {
215
+ throw new Error(`Teammate ${teammate.name} is not alive through RPC`);
171
216
  }
172
217
 
173
218
  const id = `team-${++requestCounter}`;
@@ -180,7 +225,7 @@ function sendRpc(teammate: TeammateState, command: JsonRecord, timeoutMillisecon
180
225
  }, timeoutMilliseconds);
181
226
 
182
227
  teammate.pendingRequests.set(id, { resolve, reject, timeout });
183
- teammate.process.stdin?.write(serializeJsonLine(payload));
228
+ teammate.process!.stdin?.write(serializeJsonLine(payload));
184
229
  });
185
230
  }
186
231
 
@@ -190,6 +235,8 @@ async function requireSuccessfulResponse(response: RpcResponse, action: string):
190
235
  }
191
236
 
192
237
  async function getTeammateBusy(teammate: TeammateState): Promise<boolean> {
238
+ if (teammate.transport === "herdr") return teammate.busy;
239
+
193
240
  const response = await sendRpc(teammate, { type: "get_state" }, 10_000);
194
241
  if (!response.success) return teammate.busy;
195
242
  const data = response.data as { isStreaming?: boolean } | undefined;
@@ -250,6 +297,33 @@ function formatTeammateMessage(team: TeamState, from: string, message: string):
250
297
  return [`[from ${from} on team ${team.name}]`, message, "", "Current team status:", JSON.stringify(formatStatus(team), null, 2)].join("\n");
251
298
  }
252
299
 
300
+ async function deliverVisibleMessage(team: TeamState, from: string, recipient: TeammateState, message: string, formattedMessage: string, interrupt: boolean): Promise<void> {
301
+ if (!recipient.alive || !recipient.visibleUrl) throw new Error(`Visible teammate ${recipient.name} is not ready`);
302
+ const controller = new AbortController();
303
+ const timeout = setTimeout(() => controller.abort(), visibleDeliveryTimeoutMilliseconds);
304
+ try {
305
+ const response = await fetch(recipient.visibleUrl, {
306
+ method: "POST",
307
+ headers: { "content-type": "application/json" },
308
+ body: JSON.stringify({
309
+ token: callbackToken,
310
+ tool: "deliver",
311
+ args: { team: team.name, from, to: recipient.name, sentAt: nowText(), message, formattedMessage, interrupt },
312
+ }),
313
+ signal: controller.signal,
314
+ });
315
+ if (!response.ok) throw new Error(`Visible teammate ${recipient.name} rejected delivery: ${response.status} ${await response.text()}`);
316
+ const result = (await response.json()) as { accepted?: boolean };
317
+ if (!result.accepted) throw new Error(`Visible teammate ${recipient.name} did not accept delivery`);
318
+ appendTeamLog(team, { team: team.name, teammate: recipient.name, direction: "runtime", kind: "ack", summary: "visible message accepted" });
319
+ } catch (error) {
320
+ if (controller.signal.aborted) throw new Error(`Timed out waiting for visible teammate ${recipient.name} delivery`);
321
+ throw error;
322
+ } finally {
323
+ clearTimeout(timeout);
324
+ }
325
+ }
326
+
253
327
  async function deliverToTeammate(team: TeamState, from: string, recipient: TeammateState, message: string, interrupt: boolean): Promise<void> {
254
328
  const formattedMessage = formatTeammateMessage(team, from, message);
255
329
  appendTeamLog(team, {
@@ -260,6 +334,10 @@ async function deliverToTeammate(team: TeamState, from: string, recipient: Teamm
260
334
  summary: preview(message),
261
335
  details: { from, to: recipient.name, interrupt },
262
336
  });
337
+ if (recipient.transport === "herdr") {
338
+ await deliverVisibleMessage(team, from, recipient, message, formattedMessage, interrupt);
339
+ return;
340
+ }
263
341
 
264
342
  if (interrupt && (recipient.busy || (await getTeammateBusy(recipient)))) {
265
343
  await requireSuccessfulResponse(await sendRpc(recipient, { type: "abort" }, 60_000), `abort ${recipient.name}`);
@@ -357,10 +435,60 @@ function logStatusDeclaration(team: TeamState, participant: string, word?: strin
357
435
  });
358
436
  }
359
437
 
360
- // TODO: participants is unused. Smell.
361
- function startTeammate(team: TeamState, teammateSpec: TeammateSpec, participants: string[]): TeammateState {
438
+ function createTeammateState(team: TeamState, teammateSpec: TeammateSpec): TeammateState {
362
439
  const teammateName = compactName(teammateSpec.name);
363
440
  const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
441
+ let resolveVisibleReady: (() => void) | undefined;
442
+ let rejectVisibleReady: ((error: Error) => void) | undefined;
443
+ const visibleReady = team.showOnHerdrPanes
444
+ ? new Promise<void>((resolve, reject) => {
445
+ resolveVisibleReady = resolve;
446
+ rejectVisibleReady = reject;
447
+ })
448
+ : undefined;
449
+
450
+ return {
451
+ name: teammateName,
452
+ prompt: teammateSpec.prompt,
453
+ model: teammateSpec.model,
454
+ thinking,
455
+ transport: team.showOnHerdrPanes ? "herdr" : "rpc",
456
+ visibleReady,
457
+ resolveVisibleReady,
458
+ rejectVisibleReady,
459
+ busy: false,
460
+ alive: true,
461
+ pendingRequests: new Map(),
462
+ deliveryQueue: Promise.resolve(),
463
+ recentEvents: [],
464
+ stderr: "",
465
+ };
466
+ }
467
+
468
+ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, participants: string[], visible: boolean): Record<string, string> {
469
+ return {
470
+ PI_SIMPLE_TEAM_CHILD: "1",
471
+ PI_SIMPLE_TEAM_VISIBLE_CHILD: visible ? "1" : "0",
472
+ PI_SIMPLE_TEAM_CALLBACK_URL: callbackUrl,
473
+ PI_SIMPLE_TEAM_CALLBACK_TOKEN: callbackToken,
474
+ PI_SIMPLE_TEAM_TEAM: team.name,
475
+ PI_SIMPLE_TEAM_MEMBER: teammate.name,
476
+ PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
477
+ };
478
+ }
479
+
480
+ function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
481
+ appendTeamLog(team, {
482
+ team: team.name,
483
+ teammate: teammate.name,
484
+ direction: "runtime",
485
+ kind: "spawn",
486
+ summary: `spawned ${teammate.name} (model=${teammate.model}, thinking=${teammate.thinking})`,
487
+ details: { model: teammate.model, thinking: teammate.thinking, transport: teammate.transport, paneId: teammate.paneId },
488
+ });
489
+ }
490
+
491
+ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[]): void {
364
492
  const args = [
365
493
  "--mode",
366
494
  "rpc",
@@ -369,39 +497,18 @@ function startTeammate(team: TeamState, teammateSpec: TeammateSpec, participants
369
497
  "--no-prompt-templates",
370
498
  "--no-themes",
371
499
  "--model",
372
- teammateSpec.model,
500
+ teammate.model,
373
501
  "--thinking",
374
- thinking,
502
+ teammate.thinking,
375
503
  "--system-prompt",
376
- composeSystemPrompt(team.name, team.teamPrompt, teammateName, teammateSpec.prompt, participants),
504
+ composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants),
377
505
  ];
378
-
379
506
  const proc = childProcess.spawn("pi", args, {
380
507
  cwd: process.cwd(),
381
508
  stdio: ["pipe", "pipe", "pipe"],
382
- env: {
383
- ...process.env,
384
- PI_SIMPLE_TEAM_CHILD: "1",
385
- PI_SIMPLE_TEAM_CALLBACK_URL: callbackUrl,
386
- PI_SIMPLE_TEAM_CALLBACK_TOKEN: callbackToken,
387
- PI_SIMPLE_TEAM_TEAM: team.name,
388
- PI_SIMPLE_TEAM_MEMBER: teammateName,
389
- },
509
+ env: { ...process.env, ...childEnvironmentOverrides(team, teammate, participants, false) },
390
510
  });
391
-
392
- const teammate: TeammateState = {
393
- name: teammateName,
394
- prompt: teammateSpec.prompt,
395
- model: teammateSpec.model,
396
- thinking,
397
- process: proc,
398
- busy: false,
399
- alive: true,
400
- pendingRequests: new Map(),
401
- deliveryQueue: Promise.resolve(),
402
- recentEvents: [],
403
- stderr: "",
404
- };
511
+ teammate.process = proc;
405
512
 
406
513
  attachJsonlReader(proc.stdout!, (line) => {
407
514
  if (!line.trim()) return;
@@ -411,49 +518,98 @@ function startTeammate(team: TeamState, teammateSpec: TeammateSpec, participants
411
518
  teammate.stderr += `\n[unparsed stdout] ${line}`;
412
519
  }
413
520
  });
414
-
415
521
  proc.stderr?.on("data", (chunk: Buffer | string) => {
416
522
  const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
417
523
  teammate.stderr += text;
418
524
  appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "stderr", summary: preview(text) });
419
525
  });
420
-
421
526
  proc.on("exit", (code, signal) => {
422
527
  teammate.alive = false;
423
528
  teammate.busy = false;
424
529
  rejectPendingRequests(teammate, new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
425
530
  team.statuses.set(teammate.name, status("stopped", `Exited code=${code} signal=${signal}`));
426
- appendTeamLog(team, {
427
- team: team.name,
428
- teammate: teammate.name,
429
- direction: "runtime",
430
- kind: "exit",
431
- summary: `exited (code=${code}, signal=${signal})`,
432
- details: { code, signal },
433
- });
531
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `exited (code=${code}, signal=${signal})`, details: { code, signal } });
434
532
  });
533
+ appendSpawnLog(team, teammate);
534
+ }
435
535
 
436
- appendTeamLog(team, {
437
- team: team.name,
438
- teammate: teammate.name,
439
- direction: "runtime",
440
- kind: "spawn",
441
- summary: `spawned ${teammate.name} (model=${teammate.model}, thinking=${teammate.thinking})`,
442
- details: { model: teammate.model, thinking: teammate.thinking },
443
- });
536
+ function parseHerdrPaneId(stdout: string, teammateName: string): string {
537
+ const response = JSON.parse(stdout) as { result?: { agent?: { pane_id?: string } } };
538
+ const paneId = response.result?.agent?.pane_id;
539
+ if (!paneId) throw new Error(`herdr agent start did not return a pane for ${teammateName}`);
540
+ return paneId;
541
+ }
542
+
543
+ async function attachVisibleTeammate(team: TeamState, teammate: TeammateState, participants: string[], herdrTabId: string): Promise<void> {
544
+ const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants);
545
+ const environment = childEnvironmentOverrides(team, teammate, participants, true);
546
+ const args = ["agent", "start", teammate.name, "--tab", herdrTabId, "--split", "right", "--no-focus", "--cwd", process.cwd()];
547
+ for (const [name, value] of Object.entries(environment)) {
548
+ if (value !== undefined) args.push("--env", `${name}=${value}`);
549
+ }
550
+ args.push("--", "pi", "-e", teamLiteExtensionPath, "--model", teammate.model, "--thinking", teammate.thinking, "--system-prompt", systemPrompt);
551
+ const result = await runCommand("herdr", args);
552
+ teammate.paneId = parseHerdrPaneId(result.stdout, teammate.name);
553
+ appendSpawnLog(team, teammate);
554
+
555
+ let readinessTimeout: ReturnType<typeof setTimeout> | undefined;
556
+ try {
557
+ await Promise.race([
558
+ teammate.visibleReady!,
559
+ new Promise<never>((_, reject) => {
560
+ readinessTimeout = setTimeout(() => reject(new Error(`Timed out waiting for visible teammate ${teammate.name} readiness`)), 30_000);
561
+ }),
562
+ ]);
563
+ } catch (error) {
564
+ teammate.rejectVisibleReady?.(error instanceof Error ? error : new Error(String(error)));
565
+ throw error;
566
+ } finally {
567
+ if (readinessTimeout) clearTimeout(readinessTimeout);
568
+ }
569
+ }
570
+
571
+ async function startTeammate(team: TeamState, teammate: TeammateState, participants: string[], herdrTabId?: string): Promise<void> {
572
+ if (teammate.transport === "herdr") {
573
+ await attachVisibleTeammate(team, teammate, participants, herdrTabId!);
574
+ return;
575
+ }
576
+ attachRpcTeammate(team, teammate, participants);
577
+ }
578
+
579
+ function isHerdrPaneNotFound(error: unknown): boolean {
580
+ return error instanceof Error && error.message.includes('"code":"pane_not_found"');
581
+ }
444
582
 
445
- return teammate;
583
+ async function closeVisiblePane(teammate: TeammateState): Promise<void> {
584
+ if (!teammate.paneId) return;
585
+ try {
586
+ await runCommand("herdr", ["pane", "close", teammate.paneId], 10_000);
587
+ } catch (error) {
588
+ if (!isHerdrPaneNotFound(error)) throw error;
589
+ }
590
+ teammate.paneId = undefined;
446
591
  }
447
592
 
448
- function shutdownTeam(team: TeamState): void {
593
+ async function shutdownTeam(team: TeamState): Promise<string[]> {
594
+ const errors: string[] = [];
449
595
  for (const teammate of team.members.values()) {
450
596
  teammate.alive = false;
597
+ if (teammate.transport === "herdr") {
598
+ try {
599
+ await closeVisiblePane(teammate);
600
+ } catch (error) {
601
+ errors.push(error instanceof Error ? error.message : String(error));
602
+ }
603
+ continue;
604
+ }
605
+ if (!teammate.process) continue;
451
606
  teammate.process.kill("SIGTERM");
452
607
  setTimeout(() => {
453
- if (teammate.process.exitCode === null) teammate.process.kill("SIGKILL");
608
+ if (teammate.process?.exitCode === null) teammate.process.kill("SIGKILL");
454
609
  }, 1_000).unref();
455
610
  }
456
611
  teams.delete(team.name);
612
+ return errors;
457
613
  }
458
614
 
459
615
  function closeCallbackServerIfUnused(): void {
@@ -495,6 +651,42 @@ function writeJson(response: http.ServerResponse, statusCode: number, payload: J
495
651
  response.end(body);
496
652
  }
497
653
 
654
+ function validateVisibleChildUrl(rawUrl: string, teammateName: string): string {
655
+ let url: URL;
656
+ try {
657
+ url = new URL(rawUrl);
658
+ } catch {
659
+ throw new Error(`Invalid visible teammate URL for ${teammateName}`);
660
+ }
661
+ const port = Number(url.port);
662
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port || !Number.isInteger(port) || port < 1 || port > 65_535 || url.pathname !== "/deliver") {
663
+ throw new Error(`Invalid visible teammate URL for ${teammateName}`);
664
+ }
665
+ return url.toString();
666
+ }
667
+
668
+ function handleVisibleEvent(team: TeamState, teammate: TeammateState, event: JsonRecord): void {
669
+ if (event.type === "visible_startup_error") {
670
+ const error = new Error(String(event.error ?? "Visible teammate startup failed"));
671
+ teammate.rejectVisibleReady?.(error);
672
+ throw error;
673
+ }
674
+ if (event.type === "agent_start") teammate.busy = true;
675
+ if (event.type === "agent_end") teammate.busy = false;
676
+ if (event.type === "session_shutdown") {
677
+ teammate.alive = false;
678
+ teammate.busy = false;
679
+ teammate.visibleUrl = undefined;
680
+ if (event.reason === "quit") {
681
+ team.statuses.set(teammate.name, status("stopped", "Session shut down"));
682
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "visible session shut down", details: { reason: event.reason } });
683
+ }
684
+ }
685
+ pushRecentEvent(teammate, event);
686
+ const logInput = normalizeChildEvent(team.name, teammate.name, event);
687
+ if (logInput) appendTeamLog(team, logInput);
688
+ }
689
+
498
690
  async function handleCallbackRequest(request: http.IncomingMessage, response: http.ServerResponse): Promise<void> {
499
691
  try {
500
692
  const body = await readJsonBody(request);
@@ -507,6 +699,32 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
507
699
  const from = compactName(String(body.from));
508
700
  const tool = String(body.tool);
509
701
  const args = (body.args ?? {}) as JsonRecord;
702
+ const teammate = team.members.get(from);
703
+
704
+ if (tool === "visible_register") {
705
+ if (!teammate || teammate.transport !== "herdr") throw new Error(`Unknown visible teammate: ${from}`);
706
+ const url = String(args.url ?? "");
707
+ try {
708
+ teammate.visibleUrl = validateVisibleChildUrl(url, from);
709
+ } catch (error) {
710
+ const failure = error instanceof Error ? error : new Error(String(error));
711
+ teammate.rejectVisibleReady?.(failure);
712
+ throw failure;
713
+ }
714
+ teammate.alive = true;
715
+ teammate.busy = false;
716
+ team.statuses.set(teammate.name, status("idle", "Spawned"));
717
+ teammate.resolveVisibleReady?.();
718
+ writeJson(response, 200, { accepted: true, team: team.name, from });
719
+ return;
720
+ }
721
+
722
+ if (tool === "visible_event") {
723
+ if (!teammate || teammate.transport !== "herdr") throw new Error(`Unknown visible teammate: ${from}`);
724
+ handleVisibleEvent(team, teammate, (args.event ?? {}) as JsonRecord);
725
+ writeJson(response, 200, { accepted: true, team: team.name, from });
726
+ return;
727
+ }
510
728
 
511
729
  if (tool === "teamsend") {
512
730
  const recipients = resolveRecipients(team, (args.to ?? []) as string[]);
@@ -564,7 +782,7 @@ export default function (pi: ExtensionAPI) {
564
782
 
565
783
  pi.on("session_shutdown", async () => {
566
784
  for (const team of [...teams.values()]) {
567
- if (team.owner === owner) shutdownTeam(team);
785
+ if (team.owner === owner) await shutdownTeam(team);
568
786
  }
569
787
  closeCallbackServerIfUnused();
570
788
  });
@@ -574,8 +792,8 @@ export default function (pi: ExtensionAPI) {
574
792
  defineTool({
575
793
  name: "team_spawn",
576
794
  label: "Team Spawn",
577
- description: "Spawn a persistent team of RPC Pi teammates with fresh context windows. The main agent (you) is included automatically; do not specify it as a teammate.",
578
- promptSnippet: "Spawn persistent RPC Pi teammate processes. Currently, manually ‘starting’ the teammates is required after spawn. Unless required, don’t fill up your time by repeatedly busy-polling team information. Don’t bash sleep to wait for progress; instead, set your status to advertise that you are counting on teammates to send you a message updating important milestones or request for help, and that otherwise you are staying idle; Send this actively to the team; Then end your turn by sending a simple message to the user, and finally stay put.",
795
+ description: "Spawn a persistent team of Pi teammates with fresh context windows. Set showOnHerdrPanes to run each teammate in a visible Herdr pane. The main agent (you) is included automatically; do not specify it as a teammate.",
796
+ promptSnippet: "Spawn persistent Pi teammates. Set showOnHerdrPanes to true when user-visible teammate sessions add value. Currently, manually ‘starting’ the teammates is required after spawn. Unless required, don’t fill up your time by repeatedly busy-polling team information. Don’t bash sleep to wait for progress; instead, set your status to advertise that you are counting on teammates to send you important milestones or requests for help, and that otherwise you are staying idle. Send this actively to the team. Then end your turn by sending a simple message to the user, and finally stay put.",
579
797
  renderShell: "self",
580
798
  renderCall: (args, theme, context) => renderTeamToolCall("team_spawn", args, theme, context, sessionTeammateRoster),
581
799
  renderResult: (result, options, theme, context) => renderTeamToolResult("team_spawn", result, options, theme, context, undefined, sessionTeammateRoster),
@@ -583,10 +801,13 @@ export default function (pi: ExtensionAPI) {
583
801
  team: Type.String({ description: "Team name" }),
584
802
  teamPrompt: Type.String({ description: "Common team system prompt" }),
585
803
  teammates: Type.Array(teammateSchema, { description: "Teammates to spawn" }),
804
+ showOnHerdrPanes: Type.Optional(Type.Boolean({ description: "Run each teammate in a visible Herdr pane instead of RPC mode", default: false })),
586
805
  }),
587
806
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
588
807
  const teamName = compactName(params.team);
589
808
  if (teams.has(teamName)) throw new Error(`Team already exists: ${teamName}`);
809
+ const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
810
+ const herdrTabId = showOnHerdrPanes ? await validateHerdrAvailability() : undefined;
590
811
 
591
812
  const teammateSpecs = params.teammates as TeammateSpec[];
592
813
  const teammateNames = teammateSpecs.map((teammate) => compactName(teammate.name));
@@ -602,6 +823,7 @@ export default function (pi: ExtensionAPI) {
602
823
  owner,
603
824
  ownerPi: pi,
604
825
  name: teamName,
826
+ showOnHerdrPanes,
605
827
  teamPrompt: params.teamPrompt,
606
828
  members: new Map(),
607
829
  statuses: new Map([["main", status("available", "Main agent")]]),
@@ -613,12 +835,13 @@ export default function (pi: ExtensionAPI) {
613
835
  teams.set(teamName, team);
614
836
  try {
615
837
  for (const teammateSpec of teammateSpecs) {
616
- const teammate = startTeammate(team, teammateSpec, teammateNames);
838
+ const teammate = createTeammateState(team, teammateSpec);
617
839
  team.members.set(teammate.name, teammate);
618
840
  team.statuses.set(teammate.name, status("idle", "Spawned"));
841
+ await startTeammate(team, teammate, teammateNames, herdrTabId);
619
842
  }
620
843
  } catch (error) {
621
- shutdownTeam(team);
844
+ await shutdownTeam(team);
622
845
  closeCallbackServerIfUnused();
623
846
  throw error;
624
847
  }
@@ -757,8 +980,9 @@ export default function (pi: ExtensionAPI) {
757
980
  async execute(_toolCallId, params) {
758
981
  const team = resolveTeam(owner, params.team);
759
982
  const teammates = [...team.members.keys()];
760
- shutdownTeam(team);
983
+ const errors = await shutdownTeam(team);
761
984
  closeCallbackServerIfUnused();
985
+ if (errors.length > 0) throw new Error(`Failed to close Herdr teammate pane(s): ${errors.join("; ")}`);
762
986
  return toolResult({ stopped: true, team: team.name, teammates });
763
987
  },
764
988
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",
package/render.ts CHANGED
@@ -32,6 +32,7 @@ export interface TeamStatusView {
32
32
  export interface TeamMessageDetails {
33
33
  team: string;
34
34
  from: string;
35
+ to?: string;
35
36
  sentAt: string;
36
37
  message: string;
37
38
  }
@@ -72,10 +73,10 @@ function wrapTeamLine(line: TeamLine, width: number): string[] {
72
73
  const wrapped = wrapTextWithAnsi(line, width);
73
74
  return wrapped.length > 0 ? wrapped : [""];
74
75
  }
75
- const contentWidth = Math.max(10, width - visibleLength(line.prefix));
76
+ const contentWidth = Math.max(1, width - visibleLength(line.prefix));
76
77
  const wrapped = wrapTextWithAnsi(line.text, contentWidth);
77
78
  const parts = wrapped.length > 0 ? wrapped : [""];
78
- return parts.map((part) => `${line.prefix}${part}`.trimEnd());
79
+ return parts.map((part) => clipToWidth(`${line.prefix}${part}`.trimEnd(), width));
79
80
  }
80
81
 
81
82
  function clipToWidth(line: string, width: number): string {
@@ -104,10 +105,11 @@ export class TeamLines {
104
105
  render(width: number): string[] {
105
106
  if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;
106
107
  const targetWidth = Math.max(1, stableRenderWidth(width));
107
- this.cachedLines =
108
+ const renderedLines =
108
109
  this.mode === "clip"
109
110
  ? this.lines.map((line) => clipTeamLine(line, targetWidth))
110
111
  : this.lines.flatMap((line) => wrapTeamLine(line, targetWidth));
112
+ this.cachedLines = renderedLines.map((line) => clipToWidth(line, targetWidth));
111
113
  this.cachedWidth = width;
112
114
  return this.cachedLines;
113
115
  }
@@ -540,7 +542,7 @@ export function teamMessageLines(theme: ThemeLike, details: TeamMessageDetails,
540
542
  const header = [
541
543
  theme.fg("accent", `${g.diamond} `),
542
544
  theme.fg(actorHueToken(details.from, roster), theme.bold(details.from)),
543
- theme.fg("muted", ` ${g.arrow} main`),
545
+ theme.fg("muted", ` ${g.arrow} ${details.to ?? "main"}`),
544
546
  theme.fg("dim", `${g.dot}${details.team}${g.dot}${details.sentAt}`),
545
547
  ].join("");
546
548
  return [header, ...quotedBody(theme, details.message, { lineLimit: Number.POSITIVE_INFINITY, barToken: "accent" })];
@@ -551,7 +553,7 @@ function teamMessageHeader(theme: ThemeLike, details: TeamMessageDetails, roster
551
553
  return [
552
554
  theme.fg("accent", `${g.diamond} `),
553
555
  theme.fg(actorHueToken(details.from, roster), theme.bold(details.from)),
554
- theme.fg("muted", ` ${g.arrow} main`),
556
+ theme.fg("muted", ` ${g.arrow} ${details.to ?? "main"}`),
555
557
  theme.fg("dim", `${g.dot}${details.team}${g.dot}${details.sentAt}`),
556
558
  ].join("");
557
559
  }
@@ -579,15 +581,15 @@ class TeamSendView {
579
581
 
580
582
  render(width: number): string[] {
581
583
  const header = clipToWidth(this.headerStr, width);
582
- const bodyWidth = Math.max(10, width - this.barWidth);
584
+ const bodyWidth = Math.max(1, width - this.barWidth);
583
585
  const bodyLines = this.md.render(bodyWidth);
584
- const barred = bodyLines.map((line) => `${this.barStr}${line}`);
586
+ const barred = bodyLines.map((line) => clipToWidth(`${this.barStr}${line}`, width));
585
587
  if (this.expanded) return [header, ...barred];
586
588
  const shown = barred.slice(0, SEND_PREVIEW_LINES);
587
589
  const hidden = barred.length - SEND_PREVIEW_LINES;
588
590
  if (hidden > 0) {
589
591
  const g = glyphs();
590
- shown.push(`${this.barStr}${this.theme.fg("dim", `${g.ellipsis} ${hidden} more line${hidden === 1 ? "" : "s"}${g.dot}ctrl+o to expand`)}`);
592
+ shown.push(clipToWidth(`${this.barStr}${this.theme.fg("dim", `${g.ellipsis} ${hidden} more line${hidden === 1 ? "" : "s"}${g.dot}ctrl+o to expand`)}`, width));
591
593
  }
592
594
  return [header, ...shown];
593
595
  }
@@ -611,9 +613,9 @@ class TeamMessageView {
611
613
  }
612
614
 
613
615
  render(width: number): string[] {
614
- const bodyWidth = Math.max(10, width - this.barWidth);
616
+ const bodyWidth = Math.max(1, width - this.barWidth);
615
617
  const bodyLines = this.md.render(bodyWidth);
616
- return [clipToWidth(this.headerLine, width), ...bodyLines.map((line) => `${this.barStr}${line}`)];
618
+ return [clipToWidth(this.headerLine, width), ...bodyLines.map((line) => clipToWidth(`${this.barStr}${line}`, width))];
617
619
  }
618
620
  }
619
621
 
package/screenshots/1.png CHANGED
Binary file