@giladbarnea/pi-simple-team 2.0.19 → 2.0.20

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.
Files changed (3) hide show
  1. package/README.md +2 -1
  2. package/index.ts +57 -7
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -148,7 +148,8 @@ Your main uses `team_log` when it needs to understand the chain of events in hig
148
148
 
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
- 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.
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
153
 
153
154
  ### 🌅 Herdr Support
154
155
 
package/index.ts CHANGED
@@ -49,6 +49,13 @@ interface RunFailure {
49
49
  replaced: TeamStatus;
50
50
  }
51
51
 
52
+ /** What one background child process has done. Its exit handler judges that process only, even after a resume starts another. */
53
+ interface RpcProcessRecord {
54
+ registered: boolean;
55
+ stopRequested: boolean;
56
+ quitReported: boolean;
57
+ }
58
+
52
59
  interface TeammateState {
53
60
  name: string;
54
61
  prompt: string;
@@ -63,6 +70,7 @@ interface TeammateState {
63
70
  sessionMaterialized: boolean;
64
71
  lastModelActivityAt?: string;
65
72
  process?: ChildProcess;
73
+ processRecord?: RpcProcessRecord;
66
74
  paneId?: string;
67
75
  deliveryUrl?: string;
68
76
  ready?: Promise<void>;
@@ -93,6 +101,7 @@ interface TeamState {
93
101
  lease?: TeamLease;
94
102
  log: TeamLogEntry[];
95
103
  nextLogSequence: number;
104
+ stopping?: boolean;
96
105
  }
97
106
 
98
107
  const teamLiteExtensionPath = fileURLToPath(import.meta.url);
@@ -100,6 +109,8 @@ const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
100
109
  const defaultThinkingLevel = "xhigh" satisfies ThinkingLevel;
101
110
  const deliveryTimeoutMilliseconds = 30_000;
102
111
  const defaultRpcShutdownGraceMilliseconds = 1_000;
112
+ /** Time for main's own shutdown to mark its teams before an exit notice is sent, for signals that reach main and its teammates together. */
113
+ const exitNoticeGraceMilliseconds = 2_000;
103
114
  const teamMessageType = "pi-simple-team";
104
115
  const teams = new Map<string, TeamState>();
105
116
  const callbackToken = crypto.randomBytes(24).toString("hex");
@@ -334,10 +345,7 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
334
345
  const notification = `Message delivery failed for teammate "${recipient.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}).\nOriginal message:\n${message}\nCause: ${errorMessage}\nCheck the teammate's status before retrying.`;
335
346
  try {
336
347
  if (from === "main") {
337
- team.ownerPi.sendMessage(
338
- { customType: teamMessageType, content: notification, display: true, details: { team: team.name, from: "runtime", sentAt: new Date().toISOString(), message: notification } },
339
- { deliverAs: "steer", triggerTurn: true },
340
- );
348
+ pushOwnerNotice(team, notification);
341
349
  return;
342
350
  }
343
351
  await deliverToTeammate(team, "runtime", team.members.get(from)!, notification, false);
@@ -347,6 +355,40 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
347
355
  });
348
356
  }
349
357
 
358
+ /** Wakes the team owner with a runtime notice. */
359
+ function pushOwnerNotice(team: TeamState, notification: string): void {
360
+ team.ownerPi.sendMessage(
361
+ { customType: teamMessageType, content: notification, display: true, details: { team: team.name, from: "runtime", sentAt: new Date().toISOString(), message: notification } },
362
+ { deliverAs: "steer", triggerTurn: true },
363
+ );
364
+ }
365
+
366
+ /** A failed run or an exit has no sender, so its notice goes to the team owner. A push that throws becomes an error row. */
367
+ function notifyOwner(team: TeamState, teammate: TeammateState, notification: string): void {
368
+ try {
369
+ pushOwnerNotice(team, notification);
370
+ } catch (error) {
371
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "error", summary: preview(`Could not notify main about ${teammate.name}: ${error instanceof Error ? error.message : String(error)}`) });
372
+ }
373
+ }
374
+
375
+ /**
376
+ * A notice for an exit nobody asked for. A self-quit (code 0 after a quit shutdown) and a stop by the parent are excluded.
377
+ * @example isUnexpectedExit({ registered: true, stopRequested: false, quitReported: true }, 143, null) // true
378
+ */
379
+ function isUnexpectedExit(record: RpcProcessRecord, code: number | null, signal: NodeJS.Signals | null): boolean {
380
+ const selfQuit = code === 0 && signal === null && record.quitReported;
381
+ return record.registered && !record.stopRequested && !selfQuit;
382
+ }
383
+
384
+ /** Waits for main's own shutdown to mark the team first, so a signal that reaches main and its teammates together sends nothing. */
385
+ function scheduleExitNotice(team: TeamState, teammate: TeammateState, code: number | null, signal: NodeJS.Signals | null): void {
386
+ setTimeout(() => {
387
+ if (team.stopping || teams.get(team.id ?? team.name) !== team) return;
388
+ 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.`);
389
+ }, exitNoticeGraceMilliseconds).unref();
390
+ }
391
+
350
392
  async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[] }): Promise<void> {
351
393
  const outcomes = await Promise.allSettled(teammates.map((teammate) => {
352
394
  const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
@@ -575,7 +617,9 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
575
617
  stdio: ["pipe", "ignore", "pipe"],
576
618
  env: { ...process.env, ...childEnvironmentOverrides(team, teammate, participants) },
577
619
  });
620
+ const record: RpcProcessRecord = { registered: false, stopRequested: false, quitReported: false };
578
621
  teammate.process = proc;
622
+ teammate.processRecord = record;
579
623
  teammate.alive = true;
580
624
 
581
625
  proc.stderr?.on("data", (chunk: Buffer | string) => {
@@ -587,6 +631,7 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
587
631
  teammate.rejectReady?.(new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
588
632
  team.statuses.set(teammate.name, status("stopped", `Exited code=${code} signal=${signal}`));
589
633
  appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `exited (code=${code}, signal=${signal})`, details: { code, signal } });
634
+ if (isUnexpectedExit(record, code, signal)) scheduleExitNotice(team, teammate, code, signal);
590
635
  });
591
636
  appendSpawnLog(team, teammate);
592
637
  }
@@ -726,6 +771,7 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
726
771
  resolve();
727
772
  };
728
773
  processToStop.once("exit", resolveExit);
774
+ teammate.processRecord!.stopRequested = true;
729
775
  processToStop.kill("SIGTERM");
730
776
  if (!teammate.canManageOwnTeams) {
731
777
  forceKillTimeout = setTimeout(() => processToStop.kill("SIGKILL"), defaultRpcShutdownGraceMilliseconds);
@@ -736,6 +782,7 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
736
782
  }
737
783
 
738
784
  async function shutdownTeam(team: TeamState): Promise<string[]> {
785
+ team.stopping = true;
739
786
  const errors: string[] = [];
740
787
  for (const teammate of team.members.values()) {
741
788
  if (teammate.transport === "herdr") {
@@ -855,6 +902,7 @@ function recordRunOutcome(team: TeamState, teammate: TeammateState, event: JsonR
855
902
  teammate.runFailure = { failure, replaced: current === teammate.runFailure?.failure ? teammate.runFailure.replaced : current };
856
903
  team.statuses.set(teammate.name, failure);
857
904
  appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "error", summary: preview(`${teammate.name} run failed: ${errorMessage}`), details: { error: errorMessage } });
905
+ notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) ended its latest run on an error.\nCause: ${errorMessage}\nEarlier steps of that run may have completed. Check the teammate's status and team_log before sending it more work.`);
858
906
  return;
859
907
  }
860
908
  if (event.outcome !== "completed" || !teammate.runFailure) return;
@@ -871,6 +919,7 @@ function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonR
871
919
  teammate.alive = false;
872
920
  teammate.deliveryUrl = undefined;
873
921
  if (event.reason === "quit") {
922
+ if (teammate.processRecord) teammate.processRecord.quitReported = true;
874
923
  team.statuses.set(teammate.name, status("stopped", "Session shut down"));
875
924
  appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "session shut down", details: { reason: event.reason } });
876
925
  }
@@ -917,6 +966,7 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
917
966
  teammate.alive = true;
918
967
  teammate.active = false;
919
968
  team.statuses.set(teammate.name, status("idle", "Spawned"));
969
+ if (teammate.processRecord) teammate.processRecord.registered = true;
920
970
  teammate.resolveReady?.();
921
971
  writeJson(response, 200, { accepted: true, team: team.name, from });
922
972
  return;
@@ -1106,9 +1156,9 @@ export default function (pi: ExtensionAPI) {
1106
1156
  pi.on("session_shutdown", async () => {
1107
1157
  for (const timer of reminderTimers) clearTimeout(timer);
1108
1158
  reminderTimers.clear();
1109
- for (const team of [...teams.values()]) {
1110
- if (team.owner === owner) await shutdownTeam(team);
1111
- }
1159
+ const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
1160
+ for (const team of ownedTeams) team.stopping = true;
1161
+ for (const team of ownedTeams) await shutdownTeam(team);
1112
1162
  closeCallbackServerIfUnused();
1113
1163
  });
1114
1164
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "2.0.19",
3
+ "version": "2.0.20",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",