@giladbarnea/pi-simple-team 2.0.21 → 2.0.22

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
@@ -149,7 +149,8 @@ Your main uses `team_log` when it needs to understand the chain of events in hig
149
149
  Provides main a timestamped, filterable, append-only record of the team’s messages, tool calls, and lifecycle events.
150
150
  Attempts can end before retries finish. A separate run row reports final settlement as ended or cancelled. Ended does not imply success.
151
151
  A run that ends on a provider error adds an error row with the provider's message and sets the teammate's status to `error` with that message, until a later run completes. Main also gets a message saying so.
152
- A background teammate that exits without being stopped, after it registered, also sends main a message with its exit code. A teammate that quits itself (exit code 0) does not. Herdr pane teammates have no exit message yet.
152
+ A background teammate that exits without being stopped, after it registered, also sends main a message with its exit code. A teammate that quits itself (exit code 0) does not.
153
+ A Herdr pane teammate gets the same messages. If its process dies, main is told that it exited. If it is idle when its pane is closed, or it receives SIGHUP or SIGTERM, main gets a neutral message that names the signal, because either can be on purpose. A pane closed while its teammate works usually ends Pi at once, so main is told that it exited. A restart closes the teammate's previous pane. A pane that main closes itself sends nothing.
153
154
 
154
155
  ### 🌅 Herdr Support
155
156
 
package/child-tools.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import * as http from "node:http";
2
+ import * as net from "node:net";
2
3
  import { defineTool, getMarkdownTheme, type AgentActivityOutcome, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
4
  import { Type } from "typebox";
4
5
  import { formatContextWindowReport, requireKnownContextUsage } from "./context-window.ts";
@@ -111,6 +112,35 @@ export async function callParent(config: ChildRuntimeConfig, tool: string, args:
111
112
  return (await response.json()) as JsonRecord;
112
113
  }
113
114
 
115
+ type ShutdownSignal = "SIGHUP" | "SIGTERM";
116
+
117
+ /** Lives on globalThis, because it belongs to the process: Pi loads this module again on a reload or a session replacement. */
118
+ interface ProcessLifeline {
119
+ socket: net.Socket;
120
+ signal?: ShutdownSignal;
121
+ }
122
+
123
+ const lifelineKey: unique symbol = Symbol.for("pi-simple-team.lifeline");
124
+ const lifelineHolder = globalThis as { [lifelineKey]?: ProcessLifeline };
125
+
126
+ /**
127
+ * Main has no process handle for a Herdr pane teammate. This connection stays open for the life of the process, so its close tells main that the process ended.
128
+ * The process also notes the signal that shuts it down in order, because a closed pane arrives as SIGHUP. Pi's interactive mode registers its own handlers for both signals before it loads extensions, so these listeners never replace the default termination.
129
+ */
130
+ function holdLifeline(config: ChildRuntimeConfig, port: number): void {
131
+ if (lifelineHolder[lifelineKey]) return;
132
+ const socket = net.connect(port, "127.0.0.1", () => {
133
+ socket.write(`${JSON.stringify({ token: config.callbackToken, team: config.teamId ?? config.teamName, from: config.teammateName, process: config.processId })}\n`);
134
+ });
135
+ // Main closing first must not crash the teammate.
136
+ socket.on("error", () => undefined);
137
+ socket.unref();
138
+ const lifeline: ProcessLifeline = { socket };
139
+ // Prepended, because Pi 1.4 emits session_shutdown from inside its own signal handler.
140
+ for (const signal of ["SIGHUP", "SIGTERM"] as const) process.prependListener(signal, () => { lifeline.signal ??= signal; });
141
+ lifelineHolder[lifelineKey] = lifeline;
142
+ }
143
+
114
144
  function toolResult(payload: JsonRecord): { content: [{ type: "text"; text: string }]; details: JsonRecord } {
115
145
  return {
116
146
  content: [{ type: "text" as const, text: JSON.stringify(payload, null, 2) }],
@@ -293,8 +323,9 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
293
323
  const address = server.address();
294
324
  if (!address || typeof address === "string") throw new Error("Child delivery server did not get a port");
295
325
 
326
+ let registration: JsonRecord;
296
327
  try {
297
- await callParent(config, "register", {
328
+ registration = await callParent(config, "register", {
298
329
  url: `http://127.0.0.1:${address.port}/deliver`,
299
330
  sessionId: context.sessionManager.getSessionId(),
300
331
  sessionFile: context.sessionManager.getSessionFile(),
@@ -305,11 +336,12 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
305
336
  context.shutdown();
306
337
  throw error;
307
338
  }
339
+ if (typeof registration.lifelinePort === "number") holdLifeline(config, registration.lifelinePort);
308
340
  });
309
341
 
310
342
  pi.on("session_shutdown", async (event) => {
311
343
  markIdle();
312
- await notifyParent({ type: "session_shutdown", reason: event.reason });
344
+ await notifyParent({ type: "session_shutdown", reason: event.reason, signal: lifelineHolder[lifelineKey]?.signal });
313
345
  await new Promise<void>((resolve, reject) => {
314
346
  if (!server) {
315
347
  resolve();
package/index.ts CHANGED
@@ -3,6 +3,7 @@ import type { ChildProcess } from "node:child_process";
3
3
  import crypto from "node:crypto";
4
4
  import * as fs from "node:fs";
5
5
  import http from "node:http";
6
+ import * as net from "node:net";
6
7
  import * as path from "node:path";
7
8
  import { fileURLToPath } from "node:url";
8
9
  import { defineTool, type ContextUsage, type ExtensionAPI, type ExtensionContext, getMarkdownTheme, getPackageDir } from "@earendil-works/pi-coding-agent";
@@ -51,13 +52,17 @@ interface RunFailure {
51
52
 
52
53
  /**
53
54
  * One start of a teammate's process. Main gives the process this record's id, and the process sends it with every callback,
54
- * so main never mistakes a replaced process for the current one. A background process's exit is judged by its own record.
55
+ * so main never mistakes a replaced process for the current one. Its end is judged by its own record.
56
+ * Main has no process handle for a Herdr pane teammate, so that process also holds a lifeline connection, which closes when it ends.
55
57
  */
56
58
  interface ProcessRecord {
57
59
  id: string;
58
60
  registered: boolean;
59
61
  stopRequested: boolean;
60
62
  quitReported: boolean;
63
+ /** Set once main has recorded this process's end, so a callback still in flight when it died changes nothing. */
64
+ ended?: boolean;
65
+ lifeline?: net.Socket;
61
66
  }
62
67
 
63
68
  interface TeammateState {
@@ -121,6 +126,8 @@ const callbackToken = crypto.randomBytes(24).toString("hex");
121
126
  let callbackServer: http.Server | undefined;
122
127
  let callbackReady: Promise<void> | undefined;
123
128
  let callbackUrl = "";
129
+ let lifelineServer: net.Server | undefined;
130
+ let lifelinePort = 0;
124
131
 
125
132
  function status(word: string, phrase: string): TeamStatus {
126
133
  return { word, phrase, updated: new Date().toISOString() };
@@ -385,14 +392,51 @@ function isUnexpectedExit(record: ProcessRecord, code: number | null, signal: No
385
392
  return record.registered && !record.stopRequested && !selfQuit;
386
393
  }
387
394
 
388
- /** Waits for main's own shutdown to mark the team first, so a signal that reaches main and its teammates together sends nothing. */
389
- function scheduleExitNotice(team: TeamState, teammate: TeammateState, code: number | null, signal: NodeJS.Signals | null): void {
395
+ /**
396
+ * Tells the team owner that a teammate's process ended, in the same three lines for every transport: what happened, the cause, what to do.
397
+ * Waits for main's own shutdown to mark the team first, so a signal that reaches main and its teammates together sends nothing.
398
+ */
399
+ function scheduleEndNotice(team: TeamState, teammate: TeammateState, happened: string, cause: string, advice: string): void {
390
400
  setTimeout(() => {
391
401
  if (team.stopping || teams.get(team.id ?? team.name) !== team) return;
392
- notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) exited.\nCause: exited (code=${code}, signal=${signal})\nCode 143 or 129 means its Pi shut down after SIGTERM or SIGHUP. Check team_log for its last stderr lines. Use team_resume to restart it.`);
402
+ notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) ${happened}.\nCause: ${cause}\n${advice}`);
393
403
  }, exitNoticeGraceMilliseconds).unref();
394
404
  }
395
405
 
406
+ /** A Herdr pane teammate's process ended without a shutdown callback: a crash, a kill, or a terminal that vanished under a working Pi. */
407
+ function recordAbruptEnd(team: TeamState, teammate: TeammateState, record: ProcessRecord): void {
408
+ if (record.stopRequested || record.quitReported || record.ended) return;
409
+ record.ended = true;
410
+ teammate.alive = false;
411
+ teammate.active = false;
412
+ teammate.deliveryUrl = undefined;
413
+ team.statuses.set(teammate.name, status("stopped", "Ended without shutting down"));
414
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "ended without shutting down" });
415
+ persistActiveTeamManifest(team);
416
+ scheduleEndNotice(team, teammate, "exited", "its Pi process ended without shutting down (a crash, a kill, or its pane closed while it worked)", "Check its pane if it is still open. Use team_resume to restart it.");
417
+ }
418
+
419
+ type ShutdownSignal = "SIGHUP" | "SIGTERM";
420
+
421
+ /** What a signal shutdown most likely means. Nobody can tell who sent the signal or why, so neither reads as a failure. */
422
+ const signalReasons: Record<ShutdownSignal, string> = {
423
+ SIGHUP: "Its pane may have been closed on purpose.",
424
+ SIGTERM: "Something outside the team may have stopped it on purpose.",
425
+ };
426
+
427
+ /** A teammate's Pi shut down in order. Only a Herdr pane teammate reports a signal: nobody can tell who closed its pane or why, so the notice stays neutral. */
428
+ function recordQuit(team: TeamState, teammate: TeammateState, signal: unknown): void {
429
+ const record = teammate.processRecord!;
430
+ if (record.ended) return;
431
+ record.ended = true;
432
+ record.quitReported = true;
433
+ const afterSignal = typeof signal === "string" ? ` after ${signal}` : "";
434
+ team.statuses.set(teammate.name, status("stopped", afterSignal ? `Shut down${afterSignal}` : "Session shut down"));
435
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `session shut down${afterSignal}`, details: { reason: "quit", ...(afterSignal ? { signal } : {}) } });
436
+ if (!afterSignal || record.stopRequested) return;
437
+ scheduleEndNotice(team, teammate, `shut down${afterSignal}`, `its Pi received ${signal} and shut down in order. ${signalReasons[signal as ShutdownSignal]}`, "Use team_resume to restart it if you still need it.");
438
+ }
439
+
396
440
  async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[] }): Promise<void> {
397
441
  const outcomes = await Promise.allSettled(teammates.map((teammate) => {
398
442
  const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
@@ -636,7 +680,7 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
636
680
  rejectReady?.(new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
637
681
  team.statuses.set(teammate.name, status("stopped", `Exited code=${code} signal=${signal}`));
638
682
  appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `exited (code=${code}, signal=${signal})`, details: { code, signal } });
639
- if (isUnexpectedExit(record, code, signal)) scheduleExitNotice(team, teammate, code, signal);
683
+ if (isUnexpectedExit(record, code, signal)) scheduleEndNotice(team, teammate, "exited", `exited (code=${code}, signal=${signal})`, "Code 143 or 129 means its Pi shut down after SIGTERM or SIGHUP. Check team_log for its last stderr lines. Use team_resume to restart it.");
640
684
  });
641
685
  appendSpawnLog(team, teammate);
642
686
  }
@@ -716,8 +760,9 @@ async function startTeammate(
716
760
  startOptions: ChildStartOptions = {},
717
761
  ): Promise<void> {
718
762
  startOptions.signal?.throwIfAborted();
719
- // A Pi session has no lock against a second writer, so a restart ends the previous process before it starts the next.
763
+ // A Pi session has no lock against a second writer, so a restart ends the previous process, or closes its pane, before it starts the next.
720
764
  await stopRpcTeammate(teammate);
765
+ await closeHerdrPane(teammate);
721
766
  teammate.processRecord = { id: crypto.randomUUID(), registered: false, stopRequested: false, quitReported: false };
722
767
  if (teammate.transport === "herdr") await attachHerdrTeammate(team, teammate, participants, herdrParentPaneId!, startOptions);
723
768
  else attachRpcTeammate(team, teammate, participants, startOptions);
@@ -760,6 +805,8 @@ function isHerdrPaneNotFound(error: unknown): boolean {
760
805
 
761
806
  async function closeHerdrPane(teammate: TeammateState): Promise<void> {
762
807
  if (!teammate.paneId) return;
808
+ teammate.processRecord!.stopRequested = true;
809
+ teammate.processRecord!.lifeline?.destroy();
763
810
  try {
764
811
  await runCommand("herdr", ["pane", "close", teammate.paneId], 10_000);
765
812
  } catch (error) {
@@ -835,11 +882,49 @@ async function shutdownTeam(team: TeamState): Promise<string[]> {
835
882
  function closeCallbackServerIfUnused(): void {
836
883
  if (teams.size > 0 || !callbackServer) return;
837
884
  callbackServer.close();
885
+ lifelineServer!.close();
838
886
  callbackServer = undefined;
887
+ lifelineServer = undefined;
839
888
  callbackReady = undefined;
840
889
  callbackUrl = "";
841
890
  }
842
891
 
892
+ /**
893
+ * Accepts one connection per Herdr pane teammate process. Its first line names the teammate and its process id, and its close is that process ending.
894
+ * A raw socket, because a Bun HTTP server does not report a client that died while its request was open.
895
+ */
896
+ function acceptLifeline(socket: net.Socket): void {
897
+ socket.on("error", () => undefined);
898
+ socket.once("data", (hello: Buffer) => {
899
+ const { token, team: teamId, from, process: processId } = parseLifelineHello(hello);
900
+ const team = token === callbackToken ? teams.get(String(teamId)) : undefined;
901
+ const teammate = team?.members.get(String(from));
902
+ const record = teammate?.processRecord;
903
+ if (!team || !teammate || !record || record.id !== processId) {
904
+ socket.destroy();
905
+ return;
906
+ }
907
+ record.lifeline = socket;
908
+ socket.on("close", () => recordAbruptEnd(team, teammate, record));
909
+ });
910
+ }
911
+
912
+ /** Any local process can connect, so a hello that is not JSON names nobody. */
913
+ function parseLifelineHello(hello: Buffer): { token?: unknown; team?: unknown; from?: unknown; process?: unknown } {
914
+ try {
915
+ return JSON.parse(hello.toString("utf8")) as { token?: unknown; team?: unknown; from?: unknown; process?: unknown };
916
+ } catch {
917
+ return {};
918
+ }
919
+ }
920
+
921
+ function listenOnLoopback(server: http.Server | net.Server): Promise<number> {
922
+ return new Promise<number>((resolve, reject) => {
923
+ server.once("error", reject);
924
+ server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port));
925
+ });
926
+ }
927
+
843
928
  async function ensureCallbackServer(): Promise<void> {
844
929
  if (callbackReady) return callbackReady;
845
930
 
@@ -847,15 +932,11 @@ async function ensureCallbackServer(): Promise<void> {
847
932
  void handleCallbackRequest(request, response);
848
933
  });
849
934
  callbackServer = server;
935
+ lifelineServer = net.createServer(acceptLifeline);
850
936
 
851
- callbackReady = new Promise<void>((resolve, reject) => {
852
- server.once("error", reject);
853
- server.listen(0, "127.0.0.1", () => {
854
- const address = server.address();
855
- if (!address || typeof address === "string") throw new Error("Team callback server did not get a port");
856
- callbackUrl = `http://127.0.0.1:${address.port}/callback`;
857
- resolve();
858
- });
937
+ callbackReady = Promise.all([listenOnLoopback(server), listenOnLoopback(lifelineServer)]).then(([callbackPort, port]) => {
938
+ callbackUrl = `http://127.0.0.1:${callbackPort}/callback`;
939
+ lifelinePort = port;
859
940
  });
860
941
  return callbackReady;
861
942
  }
@@ -926,12 +1007,8 @@ function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonR
926
1007
  if (event.type === "session_shutdown") {
927
1008
  teammate.alive = false;
928
1009
  teammate.deliveryUrl = undefined;
929
- if (event.reason === "quit") {
930
- teammate.processRecord!.quitReported = true;
931
- team.statuses.set(teammate.name, status("stopped", "Session shut down"));
932
- appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "session shut down", details: { reason: event.reason } });
933
- }
934
1010
  }
1011
+ if (event.type === "session_shutdown" && event.reason === "quit") recordQuit(team, teammate, event.signal);
935
1012
  const logInput = normalizeChildEvent(team.name, teammate.name, event);
936
1013
  if (logInput) appendTeamLog(team, logInput);
937
1014
  if (["agent_start", "work_queued", "agent_settled", "session_shutdown"].includes(String(event.type))) persistActiveTeamManifest(team);
@@ -977,7 +1054,7 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
977
1054
  team.statuses.set(teammate.name, status("idle", "Spawned"));
978
1055
  teammate.processRecord!.registered = true;
979
1056
  teammate.resolveReady?.();
980
- writeJson(response, 200, { accepted: true, team: team.name, from });
1057
+ writeJson(response, 200, { accepted: true, team: team.name, from, ...(teammate.transport === "herdr" ? { lifelinePort } : {}) });
981
1058
  return;
982
1059
  }
983
1060
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "2.0.21",
3
+ "version": "2.0.22",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",