@giladbarnea/pi-simple-team 2.0.19 → 2.0.21

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
@@ -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/child-tools.ts CHANGED
@@ -32,6 +32,8 @@ export interface ChildRuntimeConfig {
32
32
  teamId?: string;
33
33
  teamName: string;
34
34
  teammateName: string;
35
+ /** Names this start of the teammate's process to main. A main that predates process ids sets none and checks none. */
36
+ processId?: string;
35
37
  participants: string[];
36
38
  canManageOwnTeams: boolean;
37
39
  interruptWaitTimeoutMilliseconds?: number;
@@ -60,6 +62,7 @@ function readRequiredChildRuntimeConfig(): ChildRuntimeConfig {
60
62
  teamId,
61
63
  teamName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_TEAM_NAME"),
62
64
  teammateName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_MEMBER"),
65
+ processId: process.env.PI_SIMPLE_TEAM_PROCESS,
63
66
  participants: readParticipants(),
64
67
  canManageOwnTeams: process.env.PI_SIMPLE_TEAM_CAN_MANAGE_OWN_TEAMS === "1",
65
68
  };
@@ -94,6 +97,7 @@ export async function callParent(config: ChildRuntimeConfig, tool: string, args:
94
97
  token: config.callbackToken,
95
98
  team: config.teamId ?? config.teamName,
96
99
  from: config.teammateName,
100
+ process: config.processId,
97
101
  tool,
98
102
  args,
99
103
  }),
package/index.ts CHANGED
@@ -49,6 +49,17 @@ interface RunFailure {
49
49
  replaced: TeamStatus;
50
50
  }
51
51
 
52
+ /**
53
+ * 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
+ */
56
+ interface ProcessRecord {
57
+ id: string;
58
+ registered: boolean;
59
+ stopRequested: boolean;
60
+ quitReported: boolean;
61
+ }
62
+
52
63
  interface TeammateState {
53
64
  name: string;
54
65
  prompt: string;
@@ -63,6 +74,7 @@ interface TeammateState {
63
74
  sessionMaterialized: boolean;
64
75
  lastModelActivityAt?: string;
65
76
  process?: ChildProcess;
77
+ processRecord?: ProcessRecord;
66
78
  paneId?: string;
67
79
  deliveryUrl?: string;
68
80
  ready?: Promise<void>;
@@ -93,6 +105,7 @@ interface TeamState {
93
105
  lease?: TeamLease;
94
106
  log: TeamLogEntry[];
95
107
  nextLogSequence: number;
108
+ stopping?: boolean;
96
109
  }
97
110
 
98
111
  const teamLiteExtensionPath = fileURLToPath(import.meta.url);
@@ -100,6 +113,8 @@ const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
100
113
  const defaultThinkingLevel = "xhigh" satisfies ThinkingLevel;
101
114
  const deliveryTimeoutMilliseconds = 30_000;
102
115
  const defaultRpcShutdownGraceMilliseconds = 1_000;
116
+ /** 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. */
117
+ const exitNoticeGraceMilliseconds = 2_000;
103
118
  const teamMessageType = "pi-simple-team";
104
119
  const teams = new Map<string, TeamState>();
105
120
  const callbackToken = crypto.randomBytes(24).toString("hex");
@@ -334,10 +349,7 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
334
349
  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
350
  try {
336
351
  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
- );
352
+ pushOwnerNotice(team, notification);
341
353
  return;
342
354
  }
343
355
  await deliverToTeammate(team, "runtime", team.members.get(from)!, notification, false);
@@ -347,6 +359,40 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
347
359
  });
348
360
  }
349
361
 
362
+ /** Wakes the team owner with a runtime notice. */
363
+ function pushOwnerNotice(team: TeamState, notification: string): void {
364
+ team.ownerPi.sendMessage(
365
+ { customType: teamMessageType, content: notification, display: true, details: { team: team.name, from: "runtime", sentAt: new Date().toISOString(), message: notification } },
366
+ { deliverAs: "steer", triggerTurn: true },
367
+ );
368
+ }
369
+
370
+ /** 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. */
371
+ function notifyOwner(team: TeamState, teammate: TeammateState, notification: string): void {
372
+ try {
373
+ pushOwnerNotice(team, notification);
374
+ } catch (error) {
375
+ 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)}`) });
376
+ }
377
+ }
378
+
379
+ /**
380
+ * 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.
381
+ * @example isUnexpectedExit({ registered: true, stopRequested: false, quitReported: true }, 143, null) // true
382
+ */
383
+ function isUnexpectedExit(record: ProcessRecord, code: number | null, signal: NodeJS.Signals | null): boolean {
384
+ const selfQuit = code === 0 && signal === null && record.quitReported;
385
+ return record.registered && !record.stopRequested && !selfQuit;
386
+ }
387
+
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 {
390
+ setTimeout(() => {
391
+ 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.`);
393
+ }, exitNoticeGraceMilliseconds).unref();
394
+ }
395
+
350
396
  async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[] }): Promise<void> {
351
397
  const outcomes = await Promise.allSettled(teammates.map((teammate) => {
352
398
  const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
@@ -521,6 +567,7 @@ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, par
521
567
  PI_SIMPLE_TEAM_TEAM: team.id ?? team.name,
522
568
  PI_SIMPLE_TEAM_TEAM_NAME: team.name,
523
569
  PI_SIMPLE_TEAM_MEMBER: teammate.name,
570
+ PI_SIMPLE_TEAM_PROCESS: teammate.processRecord!.id,
524
571
  PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
525
572
  PI_SIMPLE_TEAM_CAN_MANAGE_OWN_TEAMS: teammate.canManageOwnTeams ? "1" : "0",
526
573
  };
@@ -575,6 +622,8 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
575
622
  stdio: ["pipe", "ignore", "pipe"],
576
623
  env: { ...process.env, ...childEnvironmentOverrides(team, teammate, participants) },
577
624
  });
625
+ const record = teammate.processRecord!;
626
+ const rejectReady = teammate.rejectReady;
578
627
  teammate.process = proc;
579
628
  teammate.alive = true;
580
629
 
@@ -584,9 +633,10 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
584
633
  });
585
634
  proc.on("exit", (code, signal) => {
586
635
  teammate.alive = false;
587
- teammate.rejectReady?.(new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
636
+ rejectReady?.(new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
588
637
  team.statuses.set(teammate.name, status("stopped", `Exited code=${code} signal=${signal}`));
589
638
  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);
590
640
  });
591
641
  appendSpawnLog(team, teammate);
592
642
  }
@@ -666,6 +716,9 @@ async function startTeammate(
666
716
  startOptions: ChildStartOptions = {},
667
717
  ): Promise<void> {
668
718
  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.
720
+ await stopRpcTeammate(teammate);
721
+ teammate.processRecord = { id: crypto.randomUUID(), registered: false, stopRequested: false, quitReported: false };
669
722
  if (teammate.transport === "herdr") await attachHerdrTeammate(team, teammate, participants, herdrParentPaneId!, startOptions);
670
723
  else attachRpcTeammate(team, teammate, participants, startOptions);
671
724
  await awaitChildRegistration(teammate, startOptions.signal);
@@ -717,7 +770,7 @@ async function closeHerdrPane(teammate: TeammateState): Promise<void> {
717
770
 
718
771
  async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
719
772
  const processToStop = teammate.process;
720
- if (!processToStop || !teammate.alive) return;
773
+ if (!processToStop || processToStop.exitCode !== null || processToStop.signalCode !== null) return;
721
774
 
722
775
  await new Promise<void>((resolve) => {
723
776
  let forceKillTimeout: ReturnType<typeof setTimeout> | undefined;
@@ -726,6 +779,7 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
726
779
  resolve();
727
780
  };
728
781
  processToStop.once("exit", resolveExit);
782
+ teammate.processRecord!.stopRequested = true;
729
783
  processToStop.kill("SIGTERM");
730
784
  if (!teammate.canManageOwnTeams) {
731
785
  forceKillTimeout = setTimeout(() => processToStop.kill("SIGKILL"), defaultRpcShutdownGraceMilliseconds);
@@ -736,6 +790,7 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
736
790
  }
737
791
 
738
792
  async function shutdownTeam(team: TeamState): Promise<string[]> {
793
+ team.stopping = true;
739
794
  const errors: string[] = [];
740
795
  for (const teammate of team.members.values()) {
741
796
  if (teammate.transport === "herdr") {
@@ -855,6 +910,7 @@ function recordRunOutcome(team: TeamState, teammate: TeammateState, event: JsonR
855
910
  teammate.runFailure = { failure, replaced: current === teammate.runFailure?.failure ? teammate.runFailure.replaced : current };
856
911
  team.statuses.set(teammate.name, failure);
857
912
  appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "error", summary: preview(`${teammate.name} run failed: ${errorMessage}`), details: { error: errorMessage } });
913
+ 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
914
  return;
859
915
  }
860
916
  if (event.outcome !== "completed" || !teammate.runFailure) return;
@@ -871,6 +927,7 @@ function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonR
871
927
  teammate.alive = false;
872
928
  teammate.deliveryUrl = undefined;
873
929
  if (event.reason === "quit") {
930
+ teammate.processRecord!.quitReported = true;
874
931
  team.statuses.set(teammate.name, status("stopped", "Session shut down"));
875
932
  appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "session shut down", details: { reason: event.reason } });
876
933
  }
@@ -893,6 +950,7 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
893
950
  const tool = String(body.tool);
894
951
  const args = (body.args ?? {}) as JsonRecord;
895
952
  const teammate = team.members.get(from);
953
+ if (teammate && body.process !== teammate.processRecord?.id) throw new Error(`Teammate ${from} on team ${team.name} was restarted. This process is no longer that teammate.`);
896
954
 
897
955
  if (tool === "register") {
898
956
  if (!teammate) throw new Error(`Unknown teammate: ${from}`);
@@ -917,6 +975,7 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
917
975
  teammate.alive = true;
918
976
  teammate.active = false;
919
977
  team.statuses.set(teammate.name, status("idle", "Spawned"));
978
+ teammate.processRecord!.registered = true;
920
979
  teammate.resolveReady?.();
921
980
  writeJson(response, 200, { accepted: true, team: team.name, from });
922
981
  return;
@@ -1106,9 +1165,9 @@ export default function (pi: ExtensionAPI) {
1106
1165
  pi.on("session_shutdown", async () => {
1107
1166
  for (const timer of reminderTimers) clearTimeout(timer);
1108
1167
  reminderTimers.clear();
1109
- for (const team of [...teams.values()]) {
1110
- if (team.owner === owner) await shutdownTeam(team);
1111
- }
1168
+ const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
1169
+ for (const team of ownedTeams) team.stopping = true;
1170
+ for (const team of ownedTeams) await shutdownTeam(team);
1112
1171
  closeCallbackServerIfUnused();
1113
1172
  });
1114
1173
 
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.21",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",