@giladbarnea/pi-simple-team 1.0.25 → 1.0.27

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/child-tools.ts CHANGED
@@ -7,8 +7,8 @@ import { renderTeamMessage } from "./render.ts";
7
7
  type JsonRecord = Record<string, unknown>;
8
8
 
9
9
  const teamMessageType = "pi-simple-team";
10
- const defaultVisibleInterruptWaitTimeoutMilliseconds = 25_000;
11
- const visibleLifecycleRetryAttempts = 3;
10
+ const defaultInterruptWaitTimeoutMilliseconds = 25_000;
11
+ const lifecycleCallbackRetryAttempts = 3;
12
12
 
13
13
  export interface ChildRuntimeConfig {
14
14
  callbackUrl: string;
@@ -16,7 +16,6 @@ export interface ChildRuntimeConfig {
16
16
  teamId?: string;
17
17
  teamName: string;
18
18
  teammateName: string;
19
- visible: boolean;
20
19
  participants: string[];
21
20
  canOverseeOwnTeams: boolean;
22
21
  interruptWaitTimeoutMilliseconds?: number;
@@ -45,7 +44,6 @@ function readRequiredChildRuntimeConfig(): ChildRuntimeConfig {
45
44
  teamId,
46
45
  teamName: process.env.PI_SIMPLE_TEAM_TEAM_NAME ?? teamId,
47
46
  teammateName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_MEMBER"),
48
- visible: process.env.PI_SIMPLE_TEAM_VISIBLE_CHILD === "1",
49
47
  participants: readParticipants(),
50
48
  canOverseeOwnTeams: process.env.PI_SIMPLE_TEAM_CAN_OVERSEE_OWN_TEAMS === "1",
51
49
  };
@@ -99,7 +97,7 @@ async function readJsonBody(request: http.IncomingMessage): Promise<JsonRecord>
99
97
  return JSON.parse(Buffer.concat(chunks).toString("utf8")) as JsonRecord;
100
98
  }
101
99
 
102
- interface VisibleDelivery {
100
+ interface ChildDelivery {
103
101
  team: string;
104
102
  from: string;
105
103
  to: string;
@@ -109,7 +107,8 @@ interface VisibleDelivery {
109
107
  interrupt: boolean;
110
108
  }
111
109
 
112
- function startVisibleChild(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
110
+ /** The one live runtime every child gets: a delivery server, parent registration, and lifecycle callbacks. */
111
+ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
113
112
  let server: http.Server | undefined;
114
113
  let activeContext: ExtensionContext | undefined;
115
114
  let idle = true;
@@ -120,12 +119,12 @@ function startVisibleChild(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
120
119
  const notifyParent = (event: JsonRecord): Promise<void> => {
121
120
  lifecycleQueue = lifecycleQueue.then(async () => {
122
121
  if (lifecycleError) return;
123
- for (let attempt = 1; attempt <= visibleLifecycleRetryAttempts; attempt += 1) {
122
+ for (let attempt = 1; attempt <= lifecycleCallbackRetryAttempts; attempt += 1) {
124
123
  try {
125
- await callParent(config, "visible_event", { event });
124
+ await callParent(config, "event", { event });
126
125
  return;
127
126
  } catch (error) {
128
- if (attempt === visibleLifecycleRetryAttempts) lifecycleError = error instanceof Error ? error : new Error(String(error));
127
+ if (attempt === lifecycleCallbackRetryAttempts) lifecycleError = error instanceof Error ? error : new Error(String(error));
129
128
  }
130
129
  }
131
130
  });
@@ -138,8 +137,8 @@ function startVisibleChild(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
138
137
  let resolveIdle: () => void;
139
138
  const timeout = setTimeout(() => {
140
139
  idleWaiters = idleWaiters.filter((waiter) => waiter !== resolveIdle);
141
- reject(new Error("Timed out waiting for visible child to settle after interrupt"));
142
- }, config.interruptWaitTimeoutMilliseconds ?? defaultVisibleInterruptWaitTimeoutMilliseconds);
140
+ reject(new Error("Timed out waiting for the child to settle after interrupt"));
141
+ }, config.interruptWaitTimeoutMilliseconds ?? defaultInterruptWaitTimeoutMilliseconds);
143
142
  resolveIdle = (): void => {
144
143
  clearTimeout(timeout);
145
144
  resolve();
@@ -194,8 +193,8 @@ function startVisibleChild(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
194
193
  return;
195
194
  }
196
195
 
197
- const delivery = body.args as unknown as VisibleDelivery;
198
- if (lifecycleError) throw new Error(`Visible lifecycle callback failed: ${lifecycleError.message}`);
196
+ const delivery = body.args as unknown as ChildDelivery;
197
+ if (lifecycleError) throw new Error(`Lifecycle callback failed: ${lifecycleError.message}`);
199
198
  if (delivery.interrupt && activeContext) {
200
199
  activeContext.abort();
201
200
  await waitForIdle();
@@ -228,10 +227,10 @@ function startVisibleChild(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
228
227
  server!.listen(0, "127.0.0.1", () => resolve());
229
228
  });
230
229
  const address = server.address();
231
- if (!address || typeof address === "string") throw new Error("Visible teammate server did not get a port");
230
+ if (!address || typeof address === "string") throw new Error("Child delivery server did not get a port");
232
231
 
233
232
  try {
234
- await callParent(config, "visible_register", {
233
+ await callParent(config, "register", {
235
234
  url: `http://127.0.0.1:${address.port}/deliver`,
236
235
  sessionId: context.sessionManager.getSessionId(),
237
236
  sessionFile: context.sessionManager.getSessionFile(),
@@ -276,7 +275,7 @@ export function registerChildTools(pi: ExtensionAPI, config: ChildRuntimeConfig)
276
275
  ),
277
276
  };
278
277
  });
279
- if (config.visible) startVisibleChild(pi, config);
278
+ startChildRuntime(pi, config);
280
279
 
281
280
  pi.registerTool(
282
281
  defineTool({
package/index.ts CHANGED
@@ -4,7 +4,6 @@ import crypto from "node:crypto";
4
4
  import * as fs from "node:fs";
5
5
  import http from "node:http";
6
6
  import * as path from "node:path";
7
- import { StringDecoder } from "node:string_decoder";
8
7
  import { fileURLToPath } from "node:url";
9
8
  import { defineTool, type ContextUsage, type ExtensionAPI, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
10
9
  import { bundledAiToAiSkillInstruction } from "./bundled-skill.ts";
@@ -40,21 +39,6 @@ interface TeamStatus {
40
39
  updated: string;
41
40
  }
42
41
 
43
- interface RpcResponse extends JsonRecord {
44
- type: "response";
45
- id?: string;
46
- command: string;
47
- success: boolean;
48
- error?: string;
49
- data?: unknown;
50
- }
51
-
52
- interface PendingRequest {
53
- resolve: (response: RpcResponse) => void;
54
- reject: (error: Error) => void;
55
- timeout: ReturnType<typeof setTimeout>;
56
- }
57
-
58
42
  interface TeammateSpec {
59
43
  name: string;
60
44
  prompt: string;
@@ -79,15 +63,12 @@ interface TeammateState {
79
63
  sessionMaterialized: boolean;
80
64
  process?: ChildProcess;
81
65
  paneId?: string;
82
- visibleUrl?: string;
83
- visibleReady?: Promise<void>;
84
- resolveVisibleReady?: () => void;
85
- rejectVisibleReady?: (error: Error) => void;
86
- busy: boolean;
66
+ deliveryUrl?: string;
67
+ ready?: Promise<void>;
68
+ resolveReady?: () => void;
69
+ rejectReady?: (error: Error) => void;
87
70
  alive: boolean;
88
- pendingRequests: Map<string, PendingRequest>;
89
71
  deliveryQueue: Promise<void>;
90
- recentEvents: JsonRecord[];
91
72
  stderr: string;
92
73
  }
93
74
 
@@ -112,14 +93,13 @@ interface TeamState {
112
93
  const teamLiteExtensionPath = fileURLToPath(import.meta.url);
113
94
  const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
114
95
  const defaultThinkingLevel: ThinkingLevel = "xhigh";
115
- const visibleDeliveryTimeoutMilliseconds = 30_000;
96
+ const deliveryTimeoutMilliseconds = 30_000;
116
97
  const defaultRpcShutdownGraceMilliseconds = 1_000;
117
98
  const teamMessageType = "pi-simple-team";
118
99
  const teams = new Map<string, TeamState>();
119
100
  const callbackToken = crypto.randomBytes(24).toString("hex");
120
101
  let callbackServer: http.Server | undefined;
121
102
  let callbackUrl = "";
122
- let requestCounter = 0;
123
103
 
124
104
  function status(word: string, phrase: string): TeamStatus {
125
105
  return { word, phrase, updated: nowText() };
@@ -138,10 +118,6 @@ function toolResult(payload: JsonRecord) {
138
118
  };
139
119
  }
140
120
 
141
- function sleep(milliseconds: number): Promise<void> {
142
- return new Promise((resolve) => setTimeout(resolve, milliseconds));
143
- }
144
-
145
121
  interface CommandResult {
146
122
  stdout: string;
147
123
  stderr: string;
@@ -177,162 +153,16 @@ async function validateHerdrAvailability(): Promise<string> {
177
153
  return tabId;
178
154
  }
179
155
 
180
- function serializeJsonLine(value: unknown): string {
181
- return `${JSON.stringify(value)}\n`;
182
- }
183
-
184
- function attachJsonlReader(stream: NodeJS.ReadableStream, onLine: (line: string) => void): void {
185
- const decoder = new StringDecoder("utf8");
186
- let buffer = "";
187
-
188
- stream.on("data", (chunk: Buffer | string) => {
189
- buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
190
-
191
- while (true) {
192
- const newlineIndex = buffer.indexOf("\n");
193
- if (newlineIndex === -1) return;
194
-
195
- let line = buffer.slice(0, newlineIndex);
196
- buffer = buffer.slice(newlineIndex + 1);
197
- if (line.endsWith("\r")) line = line.slice(0, -1);
198
- onLine(line);
199
- }
200
- });
201
-
202
- stream.on("end", () => {
203
- buffer += decoder.end();
204
- if (buffer.length > 0) onLine(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
205
- });
206
- }
207
-
208
- function pushRecentEvent(teammate: TeammateState, event: JsonRecord): void {
209
- teammate.recentEvents.push(event);
210
- if (teammate.recentEvents.length > 200) teammate.recentEvents.shift();
211
- }
212
-
213
- function rejectPendingRequests(teammate: TeammateState, error: Error): void {
214
- for (const pending of teammate.pendingRequests.values()) {
215
- clearTimeout(pending.timeout);
216
- pending.reject(error);
217
- }
218
- teammate.pendingRequests.clear();
219
- }
220
-
221
- function handleTeammateEvent(team: TeamState, teammate: TeammateState, event: JsonRecord): void {
222
- pushRecentEvent(teammate, event);
223
-
224
- if (event.type === "agent_start") teammate.busy = true;
225
- if (event.type === "agent_end") teammate.busy = false;
226
-
227
- const logInput = normalizeChildEvent(team.name, teammate.name, event);
228
- if (logInput) appendTeamLog(team, logInput);
229
-
230
- if (event.type !== "response") return;
231
- const response = event as RpcResponse;
232
- const requestId = response.id;
233
- if (!requestId) return;
234
-
235
- const pending = teammate.pendingRequests.get(requestId);
236
- if (!pending) return;
237
-
238
- teammate.pendingRequests.delete(requestId);
239
- clearTimeout(pending.timeout);
240
- pending.resolve(response);
241
- }
242
-
243
- function sendRpc(teammate: TeammateState, command: JsonRecord, timeoutMilliseconds = 30_000): Promise<RpcResponse> {
244
- if (teammate.transport !== "rpc" || !teammate.process || !teammate.alive || teammate.process.exitCode !== null) {
245
- throw new Error(`Teammate ${teammate.name} is not alive through RPC`);
246
- }
247
-
248
- const id = `team-${++requestCounter}`;
249
- const payload = { ...command, id };
250
-
251
- return new Promise((resolve, reject) => {
252
- const timeout = setTimeout(() => {
253
- teammate.pendingRequests.delete(id);
254
- reject(new Error(`Timed out waiting for ${String(command.type)} response from ${teammate.name}`));
255
- }, timeoutMilliseconds);
256
-
257
- teammate.pendingRequests.set(id, { resolve, reject, timeout });
258
- teammate.process!.stdin?.write(serializeJsonLine(payload));
259
- });
260
- }
261
-
262
- async function requireSuccessfulResponse(response: RpcResponse, action: string): Promise<void> {
263
- if (response.success) return;
264
- throw new Error(`${action} failed: ${response.error ?? "unknown RPC error"}`);
265
- }
266
-
267
- async function getTeammateBusy(teammate: TeammateState): Promise<boolean> {
268
- if (teammate.transport === "herdr") return teammate.busy;
269
-
270
- const response = await sendRpc(teammate, { type: "get_state" }, 10_000);
271
- if (!response.success) return teammate.busy;
272
- const data = response.data as { isStreaming?: boolean } | undefined;
273
- teammate.busy = Boolean(data?.isStreaming);
274
- return teammate.busy;
275
- }
276
-
277
- async function waitForIdle(teammate: TeammateState, timeoutMilliseconds = 30_000): Promise<void> {
278
- const deadline = Date.now() + timeoutMilliseconds;
279
-
280
- while (Date.now() < deadline) {
281
- if (!(await getTeammateBusy(teammate))) return;
282
- await sleep(100);
283
- }
284
-
285
- throw new Error(`Timed out waiting for ${teammate.name} to become idle`);
286
- }
287
-
288
- async function promptTeammate(team: TeamState, teammate: TeammateState, message: string): Promise<void> {
289
- const response = await sendRpc(teammate, { type: "prompt", message });
290
- if (response.success) {
291
- appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "ack", summary: "prompt accepted" });
292
- return;
293
- }
294
-
295
- const fallback = await sendRpc(teammate, { type: "prompt", message, streamingBehavior: "steer" });
296
- if (fallback.success) {
297
- appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "ack", summary: "steer fallback accepted" });
298
- } else {
299
- appendTeamLog(team, {
300
- team: team.name,
301
- teammate: teammate.name,
302
- direction: "runtime",
303
- kind: "error",
304
- summary: preview(`steer fallback to ${teammate.name} failed: ${fallback.error ?? "unknown RPC error"}`),
305
- });
306
- }
307
- await requireSuccessfulResponse(fallback, `steer fallback to ${teammate.name}`);
308
- }
309
-
310
- async function steerTeammate(team: TeamState, teammate: TeammateState, message: string): Promise<void> {
311
- const response = await sendRpc(teammate, { type: "steer", message });
312
- if (response.success) {
313
- appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "ack", summary: "steer accepted" });
314
- return;
315
- }
316
- appendTeamLog(team, {
317
- team: team.name,
318
- teammate: teammate.name,
319
- direction: "runtime",
320
- kind: "error",
321
- summary: preview(`steer to ${teammate.name} rejected: ${response.error ?? "unknown RPC error"}`),
322
- });
323
- await promptTeammate(team, teammate, message);
324
- }
325
-
326
156
  function formatTeammateMessage(team: TeamState, from: string, message: string): string {
327
157
  return [`[from ${from} on team ${team.name}]`, message, "", "Current team status:", JSON.stringify(formatStatus(team), null, 2)].join("\n");
328
158
  }
329
159
 
330
- async function deliverVisibleMessage(team: TeamState, from: string, recipient: TeammateState, message: string, formattedMessage: string, interrupt: boolean): Promise<void> {
331
- if (!recipient.alive || !recipient.visibleUrl) throw new Error(`Visible teammate ${recipient.name} is not ready`);
160
+ async function deliverMessage(team: TeamState, from: string, recipient: TeammateState, message: string, formattedMessage: string, interrupt: boolean): Promise<void> {
161
+ if (!recipient.alive || !recipient.deliveryUrl) throw new Error(`Teammate ${recipient.name} is not ready`);
332
162
  const controller = new AbortController();
333
- const timeout = setTimeout(() => controller.abort(), visibleDeliveryTimeoutMilliseconds);
163
+ const timeout = setTimeout(() => controller.abort(), deliveryTimeoutMilliseconds);
334
164
  try {
335
- const response = await fetch(recipient.visibleUrl, {
165
+ const response = await fetch(recipient.deliveryUrl, {
336
166
  method: "POST",
337
167
  headers: { "content-type": "application/json" },
338
168
  body: JSON.stringify({
@@ -342,12 +172,12 @@ async function deliverVisibleMessage(team: TeamState, from: string, recipient: T
342
172
  }),
343
173
  signal: controller.signal,
344
174
  });
345
- if (!response.ok) throw new Error(`Visible teammate ${recipient.name} rejected delivery: ${response.status} ${await response.text()}`);
175
+ if (!response.ok) throw new Error(`Teammate ${recipient.name} rejected delivery: ${response.status} ${await response.text()}`);
346
176
  const result = (await response.json()) as { accepted?: boolean };
347
- if (!result.accepted) throw new Error(`Visible teammate ${recipient.name} did not accept delivery`);
348
- appendTeamLog(team, { team: team.name, teammate: recipient.name, direction: "runtime", kind: "ack", summary: "visible message accepted" });
177
+ if (!result.accepted) throw new Error(`Teammate ${recipient.name} did not accept delivery`);
178
+ appendTeamLog(team, { team: team.name, teammate: recipient.name, direction: "runtime", kind: "ack", summary: "message accepted" });
349
179
  } catch (error) {
350
- if (controller.signal.aborted) throw new Error(`Timed out waiting for visible teammate ${recipient.name} delivery`);
180
+ if (controller.signal.aborted) throw new Error(`Timed out waiting for teammate ${recipient.name} delivery`);
351
181
  throw error;
352
182
  } finally {
353
183
  clearTimeout(timeout);
@@ -364,24 +194,7 @@ async function deliverToTeammate(team: TeamState, from: string, recipient: Teamm
364
194
  summary: preview(message),
365
195
  details: { from, to: recipient.name, interrupt },
366
196
  });
367
- if (recipient.transport === "herdr") {
368
- await deliverVisibleMessage(team, from, recipient, message, formattedMessage, interrupt);
369
- return;
370
- }
371
-
372
- if (interrupt && (recipient.busy || (await getTeammateBusy(recipient)))) {
373
- await requireSuccessfulResponse(await sendRpc(recipient, { type: "abort" }, 60_000), `abort ${recipient.name}`);
374
- await waitForIdle(recipient);
375
- await promptTeammate(team, recipient, formattedMessage);
376
- return;
377
- }
378
-
379
- if (recipient.busy || (await getTeammateBusy(recipient))) {
380
- await steerTeammate(team, recipient, formattedMessage);
381
- return;
382
- }
383
-
384
- await promptTeammate(team, recipient, formattedMessage);
197
+ await deliverMessage(team, from, recipient, message, formattedMessage, interrupt);
385
198
  }
386
199
 
387
200
  function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState, message: string, interrupt: boolean): void {
@@ -454,21 +267,14 @@ function resolveContextTargets(owner: symbol, targetNames: string[]): TeammateSt
454
267
  }
455
268
 
456
269
  async function getTeammateContextUsage(teammate: TeammateState, signal?: AbortSignal): Promise<KnownContextUsage> {
457
- if (teammate.transport === "rpc") {
458
- const response = await sendRpc(teammate, { type: "get_session_stats" });
459
- await requireSuccessfulResponse(response, `read context usage from ${teammate.name}`);
460
- const stats = response.data as { contextUsage?: ContextUsage };
461
- return requireKnownContextUsage(stats.contextUsage);
462
- }
463
-
464
- if (!teammate.alive || !teammate.visibleUrl) throw new Error(`Visible teammate ${teammate.name} is not ready`);
465
- const response = await fetch(teammate.visibleUrl, {
270
+ if (!teammate.alive || !teammate.deliveryUrl) throw new Error(`Teammate ${teammate.name} is not ready`);
271
+ const response = await fetch(teammate.deliveryUrl, {
466
272
  method: "POST",
467
273
  headers: { "content-type": "application/json" },
468
274
  body: JSON.stringify({ token: callbackToken, tool: "report_context_window", args: {} }),
469
275
  signal,
470
276
  });
471
- if (!response.ok) throw new Error(`Visible teammate ${teammate.name} rejected context-window query: ${response.status} ${await response.text()}`);
277
+ if (!response.ok) throw new Error(`Teammate ${teammate.name} rejected context-window query: ${response.status} ${await response.text()}`);
472
278
  const payload = (await response.json()) as { contextUsage?: ContextUsage };
473
279
  return requireKnownContextUsage(payload.contextUsage);
474
280
  }
@@ -516,14 +322,12 @@ function logStatusDeclaration(team: TeamState, participant: string, word?: strin
516
322
  function createTeammateState(team: TeamState, teammateSpec: TeammateSpec): TeammateState {
517
323
  const teammateName = compactName(teammateSpec.name);
518
324
  const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
519
- let resolveVisibleReady: (() => void) | undefined;
520
- let rejectVisibleReady: ((error: Error) => void) | undefined;
521
- const visibleReady = team.showOnHerdrPanes
522
- ? new Promise<void>((resolve, reject) => {
523
- resolveVisibleReady = resolve;
524
- rejectVisibleReady = reject;
525
- })
526
- : undefined;
325
+ let resolveReady: (() => void) | undefined;
326
+ let rejectReady: ((error: Error) => void) | undefined;
327
+ const ready = new Promise<void>((resolve, reject) => {
328
+ resolveReady = resolve;
329
+ rejectReady = reject;
330
+ });
527
331
 
528
332
  return {
529
333
  name: teammateName,
@@ -534,22 +338,18 @@ function createTeammateState(team: TeamState, teammateSpec: TeammateSpec): Teamm
534
338
  canOverseeOwnTeams: Boolean(teammateSpec.canOverseeOwnTeams),
535
339
  transport: team.showOnHerdrPanes ? "herdr" : "rpc",
536
340
  sessionMaterialized: false,
537
- visibleReady,
538
- resolveVisibleReady,
539
- rejectVisibleReady,
540
- busy: false,
341
+ ready,
342
+ resolveReady,
343
+ rejectReady,
541
344
  alive: true,
542
- pendingRequests: new Map(),
543
345
  deliveryQueue: Promise.resolve(),
544
- recentEvents: [],
545
346
  stderr: "",
546
347
  };
547
348
  }
548
349
 
549
- function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, participants: string[], visible: boolean): Record<string, string> {
350
+ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, participants: string[]): Record<string, string> {
550
351
  return {
551
352
  PI_SIMPLE_TEAM_CHILD: "1",
552
- PI_SIMPLE_TEAM_VISIBLE_CHILD: visible ? "1" : "0",
553
353
  PI_SIMPLE_TEAM_CALLBACK_URL: callbackUrl,
554
354
  PI_SIMPLE_TEAM_CALLBACK_TOKEN: callbackToken,
555
355
  PI_SIMPLE_TEAM_TEAM: team.id ?? team.name,
@@ -571,12 +371,12 @@ function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
571
371
  });
572
372
  }
573
373
 
574
- interface RpcStartOptions {
374
+ interface ChildStartOptions {
575
375
  sessionFile?: string;
576
376
  restartEmpty?: boolean;
577
377
  }
578
378
 
579
- function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[], options: RpcStartOptions): void {
379
+ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[], options: ChildStartOptions): void {
580
380
  const sessionArgs = options.sessionFile
581
381
  ? ["--session", options.sessionFile]
582
382
  : teammate.inheritContext && !options.restartEmpty
@@ -598,21 +398,12 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
598
398
  ];
599
399
  const proc = childProcess.spawn("pi", args, {
600
400
  cwd: team.projectDirectory ?? process.cwd(),
601
- stdio: ["pipe", "pipe", "pipe"],
602
- env: { ...process.env, ...childEnvironmentOverrides(team, teammate, participants, false) },
401
+ stdio: ["pipe", "ignore", "pipe"],
402
+ env: { ...process.env, ...childEnvironmentOverrides(team, teammate, participants) },
603
403
  });
604
404
  teammate.process = proc;
605
405
  teammate.alive = true;
606
- teammate.busy = false;
607
406
 
608
- attachJsonlReader(proc.stdout!, (line) => {
609
- if (!line.trim()) return;
610
- try {
611
- handleTeammateEvent(team, teammate, JSON.parse(line) as JsonRecord);
612
- } catch {
613
- teammate.stderr += `\n[unparsed stdout] ${line}`;
614
- }
615
- });
616
407
  proc.stderr?.on("data", (chunk: Buffer | string) => {
617
408
  const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
618
409
  teammate.stderr += text;
@@ -620,26 +411,13 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
620
411
  });
621
412
  proc.on("exit", (code, signal) => {
622
413
  teammate.alive = false;
623
- teammate.busy = false;
624
- rejectPendingRequests(teammate, new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
414
+ teammate.rejectReady?.(new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
625
415
  team.statuses.set(teammate.name, status("stopped", `Exited code=${code} signal=${signal}`));
626
416
  appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `exited (code=${code}, signal=${signal})`, details: { code, signal } });
627
417
  });
628
418
  appendSpawnLog(team, teammate);
629
419
  }
630
420
 
631
- async function captureRpcSessionIdentity(teammate: TeammateState): Promise<void> {
632
- const response = await sendRpc(teammate, { type: "get_state" }, 10_000);
633
- await requireSuccessfulResponse(response, `read session identity from ${teammate.name}`);
634
- const state = response.data as { sessionId?: unknown; sessionFile?: unknown } | undefined;
635
- if (typeof state?.sessionId !== "string" || typeof state.sessionFile !== "string" || !path.isAbsolute(state.sessionFile)) {
636
- throw new Error(`Teammate ${teammate.name} reported an invalid session identity`);
637
- }
638
- teammate.sessionId = state.sessionId;
639
- teammate.sessionFile = state.sessionFile;
640
- teammate.sessionMaterialized = fs.existsSync(state.sessionFile);
641
- }
642
-
643
421
  function parseHerdrPaneId(stdout: string, teammateName: string): string {
644
422
  const response = JSON.parse(stdout) as { result?: { agent?: { pane_id?: string } } };
645
423
  const paneId = response.result?.agent?.pane_id;
@@ -647,15 +425,15 @@ function parseHerdrPaneId(stdout: string, teammateName: string): string {
647
425
  return paneId;
648
426
  }
649
427
 
650
- async function attachVisibleTeammate(
428
+ async function attachHerdrTeammate(
651
429
  team: TeamState,
652
430
  teammate: TeammateState,
653
431
  participants: string[],
654
432
  herdrTabId: string,
655
- options: RpcStartOptions,
433
+ options: ChildStartOptions,
656
434
  ): Promise<void> {
657
435
  const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.canOverseeOwnTeams);
658
- const environment = childEnvironmentOverrides(team, teammate, participants, true);
436
+ const environment = childEnvironmentOverrides(team, teammate, participants);
659
437
  const sessionArgs = options.sessionFile
660
438
  ? ["--session", options.sessionFile]
661
439
  : teammate.inheritContext && !options.restartEmpty
@@ -680,17 +458,20 @@ async function attachVisibleTeammate(
680
458
  const result = await runCommand("herdr", args);
681
459
  teammate.paneId = parseHerdrPaneId(result.stdout, teammate.name);
682
460
  appendSpawnLog(team, teammate);
461
+ }
683
462
 
463
+ /** Every child registers its delivery runtime through the parent callback; startup completes only after registration. */
464
+ async function awaitChildRegistration(teammate: TeammateState): Promise<void> {
684
465
  let readinessTimeout: ReturnType<typeof setTimeout> | undefined;
685
466
  try {
686
467
  await Promise.race([
687
- teammate.visibleReady!,
468
+ teammate.ready!,
688
469
  new Promise<never>((_, reject) => {
689
- readinessTimeout = setTimeout(() => reject(new Error(`Timed out waiting for visible teammate ${teammate.name} readiness`)), 30_000);
470
+ readinessTimeout = setTimeout(() => reject(new Error(`Timed out waiting for teammate ${teammate.name} to register`)), 30_000);
690
471
  }),
691
472
  ]);
692
473
  } catch (error) {
693
- teammate.rejectVisibleReady?.(error instanceof Error ? error : new Error(String(error)));
474
+ teammate.rejectReady?.(error instanceof Error ? error : new Error(String(error)));
694
475
  throw error;
695
476
  } finally {
696
477
  if (readinessTimeout) clearTimeout(readinessTimeout);
@@ -702,14 +483,11 @@ async function startTeammate(
702
483
  teammate: TeammateState,
703
484
  participants: string[],
704
485
  herdrTabId?: string,
705
- rpcOptions: RpcStartOptions = {},
486
+ startOptions: ChildStartOptions = {},
706
487
  ): Promise<void> {
707
- if (teammate.transport === "herdr") {
708
- await attachVisibleTeammate(team, teammate, participants, herdrTabId!, rpcOptions);
709
- return;
710
- }
711
- attachRpcTeammate(team, teammate, participants, rpcOptions);
712
- if (team.id) await captureRpcSessionIdentity(teammate);
488
+ if (teammate.transport === "herdr") await attachHerdrTeammate(team, teammate, participants, herdrTabId!, startOptions);
489
+ else attachRpcTeammate(team, teammate, participants, startOptions);
490
+ await awaitChildRegistration(teammate);
713
491
  }
714
492
 
715
493
  function manifestMemberFromTeammate(teammate: TeammateState): TeamManifestMember {
@@ -750,7 +528,7 @@ function isHerdrPaneNotFound(error: unknown): boolean {
750
528
  return error instanceof Error && error.message.includes('"code":"pane_not_found"');
751
529
  }
752
530
 
753
- async function closeVisiblePane(teammate: TeammateState): Promise<void> {
531
+ async function closeHerdrPane(teammate: TeammateState): Promise<void> {
754
532
  if (!teammate.paneId) return;
755
533
  try {
756
534
  await runCommand("herdr", ["pane", "close", teammate.paneId], 10_000);
@@ -786,7 +564,7 @@ async function shutdownTeam(team: TeamState): Promise<string[]> {
786
564
  if (teammate.transport === "herdr") {
787
565
  teammate.alive = false;
788
566
  try {
789
- await closeVisiblePane(teammate);
567
+ await closeHerdrPane(teammate);
790
568
  } catch (error) {
791
569
  errors.push(error instanceof Error ? error.message : String(error));
792
570
  }
@@ -861,38 +639,29 @@ function writeJson(response: http.ServerResponse, statusCode: number, payload: J
861
639
  response.end(body);
862
640
  }
863
641
 
864
- function validateVisibleChildUrl(rawUrl: string, teammateName: string): string {
642
+ function validateChildDeliveryUrl(rawUrl: string, teammateName: string): string {
865
643
  let url: URL;
866
644
  try {
867
645
  url = new URL(rawUrl);
868
646
  } catch {
869
- throw new Error(`Invalid visible teammate URL for ${teammateName}`);
647
+ throw new Error(`Invalid delivery URL for ${teammateName}`);
870
648
  }
871
649
  const port = Number(url.port);
872
650
  if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port || !Number.isInteger(port) || port < 1 || port > 65_535 || url.pathname !== "/deliver") {
873
- throw new Error(`Invalid visible teammate URL for ${teammateName}`);
651
+ throw new Error(`Invalid delivery URL for ${teammateName}`);
874
652
  }
875
653
  return url.toString();
876
654
  }
877
655
 
878
- function handleVisibleEvent(team: TeamState, teammate: TeammateState, event: JsonRecord): void {
879
- if (event.type === "visible_startup_error") {
880
- const error = new Error(String(event.error ?? "Visible teammate startup failed"));
881
- teammate.rejectVisibleReady?.(error);
882
- throw error;
883
- }
884
- if (event.type === "agent_start") teammate.busy = true;
885
- if (event.type === "agent_end") teammate.busy = false;
656
+ function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonRecord): void {
886
657
  if (event.type === "session_shutdown") {
887
658
  teammate.alive = false;
888
- teammate.busy = false;
889
- teammate.visibleUrl = undefined;
659
+ teammate.deliveryUrl = undefined;
890
660
  if (event.reason === "quit") {
891
661
  team.statuses.set(teammate.name, status("stopped", "Session shut down"));
892
- appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "visible session shut down", details: { reason: event.reason } });
662
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "session shut down", details: { reason: event.reason } });
893
663
  }
894
664
  }
895
- pushRecentEvent(teammate, event);
896
665
  const logInput = normalizeChildEvent(team.name, teammate.name, event);
897
666
  if (logInput) appendTeamLog(team, logInput);
898
667
  }
@@ -911,35 +680,34 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
911
680
  const args = (body.args ?? {}) as JsonRecord;
912
681
  const teammate = team.members.get(from);
913
682
 
914
- if (tool === "visible_register") {
915
- if (!teammate || teammate.transport !== "herdr") throw new Error(`Unknown visible teammate: ${from}`);
683
+ if (tool === "register") {
684
+ if (!teammate) throw new Error(`Unknown teammate: ${from}`);
916
685
  const url = String(args.url ?? "");
917
686
  const sessionId = args.sessionId;
918
687
  const sessionFile = args.sessionFile;
919
688
  if (typeof sessionId !== "string" || typeof sessionFile !== "string" || !path.isAbsolute(sessionFile)) {
920
- throw new Error(`Visible teammate ${from} reported an invalid session identity`);
689
+ throw new Error(`Teammate ${from} reported an invalid session identity`);
921
690
  }
922
691
  try {
923
- teammate.visibleUrl = validateVisibleChildUrl(url, from);
692
+ teammate.deliveryUrl = validateChildDeliveryUrl(url, from);
924
693
  } catch (error) {
925
694
  const failure = error instanceof Error ? error : new Error(String(error));
926
- teammate.rejectVisibleReady?.(failure);
695
+ teammate.rejectReady?.(failure);
927
696
  throw failure;
928
697
  }
929
698
  teammate.sessionId = sessionId;
930
699
  teammate.sessionFile = sessionFile;
931
700
  teammate.sessionMaterialized = fs.existsSync(sessionFile);
932
701
  teammate.alive = true;
933
- teammate.busy = false;
934
702
  team.statuses.set(teammate.name, status("idle", "Spawned"));
935
- teammate.resolveVisibleReady?.();
703
+ teammate.resolveReady?.();
936
704
  writeJson(response, 200, { accepted: true, team: team.name, from });
937
705
  return;
938
706
  }
939
707
 
940
- if (tool === "visible_event") {
941
- if (!teammate || teammate.transport !== "herdr") throw new Error(`Unknown visible teammate: ${from}`);
942
- handleVisibleEvent(team, teammate, (args.event ?? {}) as JsonRecord);
708
+ if (tool === "event") {
709
+ if (!teammate) throw new Error(`Unknown teammate: ${from}`);
710
+ handleChildEvent(team, teammate, (args.event ?? {}) as JsonRecord);
943
711
  writeJson(response, 200, { accepted: true, team: team.name, from });
944
712
  return;
945
713
  }
@@ -1046,11 +814,11 @@ function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, manifest: TeamMa
1046
814
  return team;
1047
815
  }
1048
816
 
1049
- function prepareVisibleTeammate(teammate: TeammateState): void {
1050
- teammate.transport = "herdr";
1051
- teammate.visibleReady = new Promise<void>((resolve, reject) => {
1052
- teammate.resolveVisibleReady = resolve;
1053
- teammate.rejectVisibleReady = reject;
817
+ function prepareTeammateStart(teammate: TeammateState, transport: TeammateTransport): void {
818
+ teammate.transport = transport;
819
+ teammate.ready = new Promise<void>((resolve, reject) => {
820
+ teammate.resolveReady = resolve;
821
+ teammate.rejectReady = reject;
1054
822
  });
1055
823
  }
1056
824
 
@@ -1320,8 +1088,7 @@ export default function (pi: ExtensionAPI) {
1320
1088
 
1321
1089
  try {
1322
1090
  for (const { teammate, sessionFile } of starts) {
1323
- if (showOnHerdrPanes) prepareVisibleTeammate(teammate);
1324
- else teammate.transport = "rpc";
1091
+ prepareTeammateStart(teammate, showOnHerdrPanes ? "herdr" : "rpc");
1325
1092
  await startTeammate(team, teammate, participantNames, herdrTabId, {
1326
1093
  sessionFile,
1327
1094
  restartEmpty: sessionFile === undefined,
@@ -1338,7 +1105,7 @@ export default function (pi: ExtensionAPI) {
1338
1105
  for (const { teammate } of starts) {
1339
1106
  if (teammate.transport === "herdr") {
1340
1107
  teammate.alive = false;
1341
- await closeVisiblePane(teammate);
1108
+ await closeHerdrPane(teammate);
1342
1109
  } else {
1343
1110
  await stopRpcTeammate(teammate);
1344
1111
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "1.0.25",
3
+ "version": "1.0.27",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -26,6 +26,7 @@
26
26
  "skills",
27
27
  "screenshots/1.png",
28
28
  "screenshots/2.png",
29
+ "screenshots/team-graph.png",
29
30
  "screenshots/pi-simple-team-banner.png",
30
31
  "README.md",
31
32
  "LICENSE"
Binary file