@giladbarnea/pi-simple-team 2.0.24 → 2.0.26

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
@@ -128,7 +128,7 @@ Your main agent calls `team_status` and understands exactly what is going on. Ma
128
128
 
129
129
  Teammates know how much free context they have left.
130
130
 
131
- Main agent knows its own and everyone else's too.
131
+ Main agent knows its own and everyone else's too. You see it as well: team tool results show the last reported context use beside each teammate they involve, such as `Team Send → builder ▆72% context`.
132
132
 
133
133
  They will hand off work autonomously when it's time to say goodbye.
134
134
 
@@ -171,6 +171,12 @@ Have a teammate do work, exit Pi entirely, come back tomorrow in a brand-new ses
171
171
 
172
172
  You can even `/resume` a teammate session directly if you ever want a cozy one-on-one, or run `pi --session <teammate-session-id>`.
173
173
 
174
+ Every teammate session records which main session and team started it, in one `pi-simple-team-teammate` custom entry that the model and the TUI never see. Its `sessionId` is the session it was written in, so a later `pi --fork` of a teammate carries a copy you can tell is inherited.
175
+
176
+ `team_spawn` and `team_add_teammates` can also use a stopped, never-teamed conversation. Set `session` on its teammate definition to an exact current-project ID (resume or create), or an existing absolute JSONL path. Omit model/thinking to keep Pi’s saved settings or defaults. `startIdle` keeps it asleep until you message it.
177
+
178
+ This first version refuses known team-owned or previously teamed sessions, other projects, and pending reminders, naming the blocking state and where it belongs. Source processes must be stopped first: Pi has no session writer locks, and an ordinary process or surviving pane may be invisible to Simple Team. An unresolved import stays reserved and is not restarted automatically.
179
+
174
180
  ## 🪾 It’s teams all the way down (optionally)
175
181
 
176
182
  Tell main you want to **have a teammate manage its own team(s).**
@@ -233,6 +239,8 @@ Kept minimal:
233
239
 
234
240
  Startup delivers `commonPrompt` inside `<team-system-message>` and each teammate's `systemPrompt` inside `<your-specific-system-message>`. These are labels in the custom team message, not system-role overrides. The briefing also contains the teammate's identity and coordination guidance.
235
241
 
242
+ When main quits, reloads or crashes, its teams stop. When that main session starts again, Simple Team reattaches the teammates that were running, idle and in their own conversations, without sending them anything or making a model request. Main gets one message listing them and which were working, so it can tell those to continue. Teams stopped with `team_shutdown`, or left by switching main to another session, stay stopped. After a crash, a Herdr pane teammate may still be running in its pane, so it is listed instead of reattached.
243
+
236
244
  Resume appends a custom briefing with the team identity, current time, and last recorded model activity. Optional `resumptionPrompt` instructions follow that briefing without changing saved definitions. With `startIdle: true`, the briefing waits in context for the next turn.
237
245
 
238
246
  Existing teammates can be selected by name or Pi session ID in the same input field. Messages, logs, and context usage share a `targets` list. Select a team for all its teammates, or select individual teammates across your teams. Ambiguous names return IDs you can use instead.
@@ -241,6 +249,8 @@ Existing teammates can be selected by name or Pi session ID in the same input fi
241
249
 
242
250
  `team_list` shows active teams as short rows, newest created first, 20 per page by default (`limit` up to 100, then `cursor`). Pass `includeDormantTeams: true` to include dormant teams, or `team` for one team's full records. Pages follow creation order, so a team that changes state or activity between pages is neither repeated nor skipped.
243
251
 
252
+ Reminders are recorded in the session, so they survive `/reload` and restarts of that session. One that fell due while Pi was not running fires on start and says how late it is.
253
+
244
254
  `list_reminders` shows this session's pending reminders with their IDs, slugs and times. `cancel_reminders` cancels reminders by ID or slug, or every pending one with `all: true`; a call with neither cancels nothing.
245
255
 
246
256
  Spawn, resume, and add return the complete roster. Results distinguish a live runtime from active work, including work that was already underway before the call.
package/child-tools.ts CHANGED
@@ -37,6 +37,9 @@ export interface ChildRuntimeConfig {
37
37
  processId?: string;
38
38
  participants: string[];
39
39
  canManageOwnTeams: boolean;
40
+ /** The main session that started this teammate. A simulated teammate without one records no breadcrumb. */
41
+ parentSessionId?: string;
42
+ parentSessionFile?: string;
40
43
  interruptWaitTimeoutMilliseconds?: number;
41
44
  }
42
45
 
@@ -66,9 +69,32 @@ function readRequiredChildRuntimeConfig(): ChildRuntimeConfig {
66
69
  processId: process.env.PI_SIMPLE_TEAM_PROCESS,
67
70
  participants: readParticipants(),
68
71
  canManageOwnTeams: process.env.PI_SIMPLE_TEAM_CAN_MANAGE_OWN_TEAMS === "1",
72
+ parentSessionId: process.env.PI_SIMPLE_TEAM_PARENT_SESSION_ID,
73
+ parentSessionFile: process.env.PI_SIMPLE_TEAM_PARENT_SESSION_FILE,
69
74
  };
70
75
  }
71
76
 
77
+ const breadcrumbType = "pi-simple-team-teammate";
78
+
79
+ /**
80
+ * Names, once in this teammate's own session, the main session and team that started it. It is a custom entry, so it never
81
+ * reaches the model or the TUI. Its sessionId tells the teammate's own breadcrumb from a copy inherited through a later fork.
82
+ */
83
+ function recordBreadcrumb(pi: ExtensionAPI, config: ChildRuntimeConfig, context: ExtensionContext): void {
84
+ if (!config.parentSessionId) return;
85
+ const sessionId = context.sessionManager.getSessionId();
86
+ if (context.sessionManager.getEntries().some((entry) => entry.type === "custom" && entry.customType === breadcrumbType && (entry.data as { sessionId?: unknown } | undefined)?.sessionId === sessionId)) return;
87
+ pi.appendEntry(breadcrumbType, {
88
+ sessionId,
89
+ parentSessionId: config.parentSessionId,
90
+ parentSessionFile: config.parentSessionFile,
91
+ teamId: config.teamId,
92
+ teamName: config.teamName,
93
+ teammate: config.teammateName,
94
+ createdAt: new Date().toISOString(),
95
+ });
96
+ }
97
+
72
98
  /**
73
99
  * A teammate process inherits discovered extensions, so it can also discover an installed copy of this package at another path.
74
100
  * Only the copy main passed as PI_SIMPLE_TEAM_RUNTIME_PATH registers; another copy stays inert so their tools cannot conflict.
@@ -266,6 +292,7 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
266
292
  });
267
293
  pi.on("session_start", async (_event, context) => {
268
294
  activateChildTools(pi);
295
+ recordBreadcrumb(pi, config, context);
269
296
  server = http.createServer((request, response) => {
270
297
  void (async () => {
271
298
  try {
package/index.ts CHANGED
@@ -10,12 +10,16 @@ import { defineTool, type ContextUsage, type ExtensionAPI, type ExtensionContext
10
10
  import { formatContextWindowReport, requireKnownContextUsage, type KnownContextUsage } from "./context-window.ts";
11
11
  import { useModelNames } from "./model-names.ts";
12
12
  import { formatScopedModelGuidance, validateTeammateModels, type ModelReference } from "./model-preflight.ts";
13
+ import { latestReminderRecords, reminderType, type ReminderRecord } from "./reminder-records.ts";
14
+ import { resolveSessionAttachment } from "./session-attachment.ts";
13
15
  import { composeTeamBriefing } from "./team-briefing.ts";
14
- import { composeResumptionMessage, composeSettingsMessage } from "./resume-message.ts";
16
+ import { composeReattachmentMessage, composeResumptionMessage, composeSettingsMessage, type Reattachment } from "./resume-message.ts";
15
17
  import { callParent, isInertTeamCopy, readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
16
18
  import {
17
19
  canonicalProjectDirectory,
18
20
  claimTeamLease,
21
+ reserveSessionImports,
22
+ discardTeamImportReservation,
19
23
  dormantManifestRetentionMilliseconds,
20
24
  listTeamManifests,
21
25
  teamManifestExists,
@@ -79,6 +83,10 @@ interface TeammateState {
79
83
  sessionId?: string;
80
84
  sessionFile?: string;
81
85
  sessionMaterialized: boolean;
86
+ session?: string;
87
+ contextRestored?: boolean;
88
+ importPending?: boolean;
89
+ needsBriefing?: boolean;
82
90
  lastModelActivityAt?: string;
83
91
  process?: ChildProcess;
84
92
  processRecord?: ProcessRecord;
@@ -105,6 +113,8 @@ interface TeamState {
105
113
  showOnHerdrPanes: boolean;
106
114
  teamPrompt: string;
107
115
  mainSessionFile?: string;
116
+ /** The main session running this team. Every teammate it starts records it in its own session's breadcrumb. */
117
+ parentSession?: { id: string; file?: string };
108
118
  members: Map<string, TeammateState>;
109
119
  statuses: Map<string, TeamStatus>;
110
120
  created: string;
@@ -123,6 +133,7 @@ const defaultRpcShutdownGraceMilliseconds = 1_000;
123
133
  /** 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. */
124
134
  const exitNoticeGraceMilliseconds = 2_000;
125
135
  const teamMessageType = "pi-simple-team";
136
+ const reattachedMessageType = "pi-simple-team-reattached";
126
137
  const teams = new Map<string, TeamState>();
127
138
  const callbackToken = crypto.randomBytes(24).toString("hex");
128
139
  let callbackServer: http.Server | undefined;
@@ -179,14 +190,10 @@ function decodeTeamListCursor(cursor: string): TeamListCursor {
179
190
  return decoded as TeamListCursor;
180
191
  }
181
192
 
182
- interface Reminder {
183
- id: string;
184
- slug: string;
185
- message: string;
193
+ interface Reminder extends Omit<ReminderRecord, "armedAt" | "wakeAt"> {
186
194
  armedAt: Date;
187
195
  wakeAt: Date;
188
- timer: ReturnType<typeof setTimeout>;
189
- state: "pending" | "delivered" | "cancelled";
196
+ timer?: ReturnType<typeof setTimeout>;
190
197
  }
191
198
 
192
199
  const reminderSlugWords = {
@@ -256,6 +263,7 @@ function teammateRecord(teammate: TeammateState): TeammateRecord {
256
263
  showOnHerdrPane: teammate.transport === "herdr",
257
264
  contextPercent: teammate.contextPercent,
258
265
  sessionFile: teammate.sessionFile!,
266
+ ...(teammate.session ? { session: teammate.session } : {}),
259
267
  ...(teammate.extensionPaths.length > 0 ? { extensionPaths: teammate.extensionPaths } : {}),
260
268
  };
261
269
  }
@@ -510,14 +518,18 @@ function recordQuit(team: TeamState, teammate: TeammateState, signal: unknown):
510
518
 
511
519
  async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[]; settings?: ReadonlyMap<string, TeammateUpdate> }): Promise<void> {
512
520
  const outcomes = await Promise.allSettled(teammates.map((teammate) => {
513
- const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
521
+ const initialize = !resumption || resumption.emptyRestarts.includes(teammate) || teammate.needsBriefing;
514
522
  const message = [
515
523
  initialize && composeTeamBriefing(team.name, team.teamPrompt, teammate.name, teammate.prompt, [...team.members.keys()], teammate.canManageOwnTeams),
516
524
  resumption && composeResumptionMessage(team.name, teammate.name, teammate.lastModelActivityAt, resumption.instructions),
517
525
  resumption?.settings?.has(teammate.name) && composeSettingsMessage(describeSettings(resumption.settings.get(teammate.name)!), []),
518
526
  ].filter(Boolean).join("\n\n");
519
- return queueDelivery(team, "main", teammate, message, false, !startIdle);
527
+ return queueDelivery(team, "main", teammate, message, false, !startIdle).then(() => {
528
+ teammate.needsBriefing = undefined;
529
+ teammate.importPending = undefined;
530
+ });
520
531
  }));
532
+ persistActiveTeamManifest(team);
521
533
  const completed = teammates.filter((_teammate, index) => outcomes[index].status === "fulfilled").map((teammate) => teammate.name);
522
534
  const errors = outcomes.flatMap((outcome, index) => {
523
535
  if (outcome.status === "fulfilled") return [];
@@ -593,6 +605,11 @@ function formatStatus(team: TeamState): Record<string, TeamStatus> {
593
605
  return Object.fromEntries([...team.statuses.entries()].sort(([a], [b]) => a.localeCompare(b)));
594
606
  }
595
607
 
608
+ /** A teammate a tool involves, with the context use it last reported, for that tool's renderer. */
609
+ function agentContext(teammate: TeammateState): { name: string; contextPercent?: number } {
610
+ return { name: teammate.name, contextPercent: teammate.contextPercent };
611
+ }
612
+
596
613
  /** @example teammateViews(team).scout?.model // "openai-codex/gpt-6-luna" */
597
614
  function teammateViews(team: TeamState): Record<string, TeammateView> {
598
615
  return Object.fromEntries([...team.members.values()].map((teammate) => [teammate.name, {
@@ -646,7 +663,7 @@ function validateExtensionPaths(extensionPaths: readonly string[]): void {
646
663
  }
647
664
  }
648
665
 
649
- function createTeammateState(teammateSpec: Teammate): TeammateState {
666
+ function createTeammateState(teammateSpec: Teammate, attachment?: ReturnType<typeof resolveSessionAttachment>, projectDirectory?: string): TeammateState {
650
667
  const teammateName = compactName(teammateSpec.name);
651
668
  const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
652
669
  const extensionPaths = teammateSpec.extensionPaths ?? [];
@@ -661,13 +678,19 @@ function createTeammateState(teammateSpec: Teammate): TeammateState {
661
678
  return {
662
679
  name: teammateName,
663
680
  prompt: teammateSpec.systemPrompt,
664
- model: teammateSpec.model,
681
+ model: teammateSpec.model ?? "",
665
682
  thinking,
666
683
  forkContext: Boolean(teammateSpec.forkContext),
667
684
  canManageOwnTeams: Boolean(teammateSpec.canManageOwnTeams),
668
685
  extensionPaths,
669
686
  transport: teammateSpec.showOnHerdrPane ? "herdr" : "rpc",
670
- sessionMaterialized: false,
687
+ sessionMaterialized: Boolean(attachment?.file),
688
+ needsBriefing: true,
689
+ ...(attachment ? {
690
+ session: attachment.id, sessionId: attachment.id,
691
+ sessionFile: attachment.file ?? SessionManager.create(projectDirectory!, undefined, { id: attachment.id }).getSessionFile(),
692
+ contextRestored: Boolean(attachment.file), importPending: true,
693
+ } : {}),
671
694
  ready,
672
695
  resolveReady,
673
696
  rejectReady,
@@ -690,9 +713,17 @@ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, par
690
713
  PI_SIMPLE_TEAM_PROCESS: teammate.processRecord!.id,
691
714
  PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
692
715
  PI_SIMPLE_TEAM_CAN_MANAGE_OWN_TEAMS: teammate.canManageOwnTeams ? "1" : "0",
716
+ ...(team.parentSession ? { PI_SIMPLE_TEAM_PARENT_SESSION_ID: team.parentSession.id } : {}),
717
+ ...(team.parentSession?.file ? { PI_SIMPLE_TEAM_PARENT_SESSION_FILE: team.parentSession.file } : {}),
693
718
  };
694
719
  }
695
720
 
721
+ /** The main session a tool or event runs in, when it has one. */
722
+ function mainSession(context: ExtensionContext): TeamState["parentSession"] {
723
+ const id = context.sessionManager?.getSessionId?.();
724
+ return id ? { id, file: context.sessionManager?.getSessionFile?.() } : undefined;
725
+ }
726
+
696
727
  function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
697
728
  appendTeamLog(team, {
698
729
  team: team.name,
@@ -706,6 +737,7 @@ function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
706
737
 
707
738
  interface ChildStartOptions {
708
739
  sessionFile?: string;
740
+ restoreSettings?: boolean;
709
741
  restartEmpty?: boolean;
710
742
  signal?: AbortSignal;
711
743
  /** New settings, recorded once the previous process has ended and before the next one starts. */
@@ -717,20 +749,27 @@ interface ChildStartOptions {
717
749
  * @example launchSettingArguments({ model: "openai-codex/gpt-6-luna", thinking: "xhigh" }, { sessionFile: "/sessions/a.jsonl" }) // ["--thinking", "xhigh"]
718
750
  */
719
751
  function launchSettingArguments(teammate: Pick<TeammateState, "model" | "thinking">, options: ChildStartOptions): string[] {
752
+ if (options.restoreSettings) return [
753
+ ...(options.settings?.model ? ["--model", options.settings.model] : []),
754
+ ...(options.settings?.thinking ? ["--thinking", options.settings.thinking] : []),
755
+ ];
720
756
  const thinkingArguments = ["--thinking", teammate.thinking];
721
757
  return options.sessionFile ? thinkingArguments : ["--model", teammate.model, ...thinkingArguments];
722
758
  }
723
759
 
760
+ /** @example launchSessionArguments({}, { forkContext: false }, { sessionFile: "/sessions/a.jsonl" }) // ["--session", "/sessions/a.jsonl"] */
761
+ function launchSessionArguments(team: Pick<TeamState, "mainSessionFile">, teammate: Pick<TeammateState, "session" | "sessionId" | "forkContext">, options: ChildStartOptions): string[] {
762
+ if (options.sessionFile) return ["--session", options.sessionFile];
763
+ if (teammate.session) return ["--session-id", teammate.sessionId!];
764
+ if (teammate.forkContext && !options.restartEmpty) return ["--fork", team.mainSessionFile!];
765
+ return [];
766
+ }
767
+
724
768
  function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[], options: ChildStartOptions): void {
725
- const sessionArgs = options.sessionFile
726
- ? ["--session", options.sessionFile]
727
- : teammate.forkContext && !options.restartEmpty
728
- ? ["--fork", team.mainSessionFile!]
729
- : [];
730
769
  const args = [
731
770
  "--mode",
732
771
  "rpc",
733
- ...sessionArgs,
772
+ ...launchSessionArguments(team, teammate, options),
734
773
  "-e",
735
774
  teamLiteExtensionPath,
736
775
  ...teammate.extensionPaths.flatMap(extensionPath => ["-e", extensionPath]),
@@ -816,7 +855,7 @@ function restartWithSettings(team: TeamState, teammate: TeammateState, update: T
816
855
  });
817
856
  teammate.deliveryQueue = restart.then(() => undefined, () => undefined);
818
857
  return restart.then(async ({ sessionFile, stoppedTeams }) => {
819
- if (sessionFile === undefined) await kickoffTeammates(team, [teammate], true);
858
+ if (sessionFile === undefined || teammate.needsBriefing) await kickoffTeammates(team, [teammate], true);
820
859
  await queueDelivery(team, "main", teammate, composeSettingsMessage(describeSettings(update), stoppedTeams), false, false);
821
860
  });
822
861
  }
@@ -889,11 +928,6 @@ async function attachHerdrTeammate(
889
928
  options: ChildStartOptions,
890
929
  ): Promise<void> {
891
930
  const environment = childEnvironmentOverrides(team, teammate, participants);
892
- const sessionArgs = options.sessionFile
893
- ? ["--session", options.sessionFile]
894
- : teammate.forkContext && !options.restartEmpty
895
- ? ["--fork", team.mainSessionFile!]
896
- : [];
897
931
  const args = ["pane", "split", "--pane", herdrParentPaneId, "--direction", "right", "--no-focus", "--cwd", team.projectDirectory ?? process.cwd()];
898
932
  for (const [name, value] of Object.entries(environment)) {
899
933
  if (value !== undefined) args.push("--env", `${name}=${value}`);
@@ -903,7 +937,7 @@ async function attachHerdrTeammate(
903
937
  await runCommand("herdr", ["pane", "rename", teammate.paneId, teammate.name]);
904
938
  const command = [
905
939
  ...team.parentPiCommand,
906
- ...sessionArgs,
940
+ ...launchSessionArguments(team, teammate, options),
907
941
  "-e",
908
942
  teamLiteExtensionPath,
909
943
  ...teammate.extensionPaths.flatMap(extensionPath => ["-e", extensionPath]),
@@ -962,14 +996,25 @@ function manifestMemberFromTeammate(teammate: TeammateState): TeamManifestMember
962
996
  return {
963
997
  ...teammateRecord(teammate),
964
998
  sessionMaterialized: teammate.sessionMaterialized,
999
+ ...(teammate.importPending ? { importPending: true } : {}),
1000
+ ...(teammate.needsBriefing ? { needsBriefing: true } : {}),
965
1001
  };
966
1002
  }
967
1003
 
968
- /** A teammate that is still starting has no session identity yet. It joins the manifest after it registers, so it cannot fail bookkeeping for its siblings. */
1004
+ /** Fresh teammates join the manifest after registration; imports reserve their selected identity before startup. */
969
1005
  function registeredManifestMembers(team: TeamState): TeamManifestMember[] {
970
1006
  return [...team.members.values()].filter((teammate) => teammate.sessionId).map(manifestMemberFromTeammate);
971
1007
  }
972
1008
 
1009
+ function createTeamManifest(team: TeamState): TeamManifest {
1010
+ const timestamp = new Date().toISOString();
1011
+ return {
1012
+ version: 2, id: team.id!, name: team.name, originMainSessionId: team.parentSession!.id,
1013
+ projectDirectory: team.projectDirectory!, teamPrompt: team.teamPrompt, showOnHerdrPanes: team.showOnHerdrPanes,
1014
+ members: registeredManifestMembers(team), state: "active", createdAt: team.manifest?.createdAt ?? timestamp, updatedAt: timestamp,
1015
+ };
1016
+ }
1017
+
973
1018
  function persistActiveTeamManifest(team: TeamState): void {
974
1019
  if (!team.manifest || !teams.has(team.id ?? team.name)) return;
975
1020
  const updatedAt = new Date().toISOString();
@@ -980,6 +1025,7 @@ function persistActiveTeamManifest(team: TeamState): void {
980
1025
  updatedAt,
981
1026
  shutdownAt: undefined,
982
1027
  expiresAt: undefined,
1028
+ interrupted: undefined,
983
1029
  };
984
1030
  writeTeamManifest(team.manifest);
985
1031
  }
@@ -1021,7 +1067,14 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
1021
1067
  teammate.process = undefined;
1022
1068
  }
1023
1069
 
1024
- async function shutdownTeam(team: TeamState): Promise<string[]> {
1070
+ /** The teammates main's own stop interrupts, read before it stops them; undefined when none is running or the team has no saved record to keep them in. */
1071
+ function interruptedTeammates(team: TeamState): TeamManifest["interrupted"] {
1072
+ const running = [...team.members.values()].filter((teammate) => teammate.alive && teammate.sessionId);
1073
+ if (running.length === 0 || !team.lease) return undefined;
1074
+ return { mainSessionId: team.lease.mainSessionId, teammates: running.map((teammate) => teammate.name), working: running.filter((teammate) => teammateSummary(teammate).active).map((teammate) => teammate.name) };
1075
+ }
1076
+
1077
+ async function shutdownTeam(team: TeamState, interrupted?: TeamManifest["interrupted"], discardNewAttachment = false): Promise<string[]> {
1025
1078
  team.stopping = true;
1026
1079
  const errors: string[] = [];
1027
1080
  for (const teammate of team.members.values()) {
@@ -1036,6 +1089,18 @@ async function shutdownTeam(team: TeamState): Promise<string[]> {
1036
1089
  }
1037
1090
  await stopRpcTeammate(teammate);
1038
1091
  }
1092
+ for (const teammate of team.members.values()) {
1093
+ if (!teammate.importPending || teammate.transport !== "rpc") continue;
1094
+ if (teammate.processRecord?.registered) {
1095
+ teammate.importPending = undefined;
1096
+ continue;
1097
+ }
1098
+ team.members.delete(teammate.name);
1099
+ }
1100
+ if (team.manifest && discardNewAttachment && registeredManifestMembers(team).length === 0 && [...team.members.values()].every((teammate) => teammate.transport === "rpc" || !teammate.processRecord)) {
1101
+ discardTeamImportReservation(team.manifest.id);
1102
+ team.manifest = undefined;
1103
+ }
1039
1104
  if (team.manifest) {
1040
1105
  try {
1041
1106
  const shutdownAt = new Date().toISOString();
@@ -1046,6 +1111,7 @@ async function shutdownTeam(team: TeamState): Promise<string[]> {
1046
1111
  updatedAt: shutdownAt,
1047
1112
  shutdownAt,
1048
1113
  expiresAt: new Date(Date.parse(shutdownAt) + dormantManifestRetentionMilliseconds).toISOString(),
1114
+ interrupted,
1049
1115
  };
1050
1116
  writeTeamManifest(team.manifest);
1051
1117
  } catch (error) {
@@ -1230,6 +1296,11 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
1230
1296
  teammate.rejectReady?.(failure);
1231
1297
  throw failure;
1232
1298
  }
1299
+ if (teammate.session && sessionId !== teammate.sessionId) {
1300
+ const failure = new Error(`Session ${teammate.sessionId} registered as ${sessionId} at ${sessionFile}; refusing replacement identity.`);
1301
+ teammate.rejectReady?.(failure);
1302
+ throw failure;
1303
+ }
1233
1304
  teammate.sessionId = sessionId;
1234
1305
  teammate.sessionFile = sessionFile;
1235
1306
  teammate.lastModelActivityAt = args.lastModelActivityAt as string | undefined;
@@ -1312,13 +1383,14 @@ function teammateSchema(modelGuidance: string) {
1312
1383
  return Type.Object({
1313
1384
  name: Type.String({ description: "Teammate name" }),
1314
1385
  systemPrompt: Type.String({ description: "Individual teammate instructions, delivered in the custom startup briefing" }),
1315
- model: Type.String({ description: `Canonical provider/model id for this teammate. ${modelGuidance}` }),
1316
- thinking: Type.Optional(StringEnum(thinkingLevels, { description: "Thinking level for this teammate. Defaults to xhigh.", default: defaultThinkingLevel })),
1386
+ model: Type.Optional(Type.String({ description: `Canonical provider/model id. Required without session; otherwise omission restores Pi's settings. ${modelGuidance}` })),
1387
+ session: Type.Optional(Type.String({ minLength: 1, description: "Stopped, never-teamed Pi session: exact current-project ID (resume or create), or existing absolute JSONL path. Confirm its original process is stopped. Team-owned sessions and pending reminders are refused." })),
1388
+ thinking: Type.Optional(StringEnum(thinkingLevels, { description: "Thinking level. Defaults to xhigh without session; with session, omission restores Pi's settings." })),
1317
1389
  forkContext: Type.Optional(Type.Boolean({ description: "Start as a fork of your context window rather than fresh. Defaults to false.", default: false })),
1318
1390
  canManageOwnTeams: Type.Optional(Type.Boolean({ description: "Allow this teammate to create and manage teams of its own. Defaults to false.", default: false })),
1319
1391
  showOnHerdrPane: Type.Optional(Type.Boolean({ description: "Open a visible Herdr pane for this teammate. Defaults to false.", default: false })),
1320
1392
  extensionPaths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { uniqueItems: true, description: "Trusted extension files or directories to load alongside the team runtime. Use existing absolute paths. Saved for later resume; discovered extensions also load." })),
1321
- }, { additionalProperties: false });
1393
+ }, { additionalProperties: false, anyOf: [{ required: ["model"] }, { required: ["session"] }] });
1322
1394
  }
1323
1395
 
1324
1396
  function teammateUpdateSchema() {
@@ -1330,6 +1402,13 @@ function teammateUpdateSchema() {
1330
1402
  }, { additionalProperties: false });
1331
1403
  }
1332
1404
 
1405
+ /** Unknown startup remains reserved until child exit is known. @example pendingImportError({ members: [] } as TeamManifest) // undefined */
1406
+ function pendingImportError(manifest: TeamManifest): string | undefined {
1407
+ const pending = manifest.members.filter((member) => member.importPending);
1408
+ if (pending.length === 0) return undefined;
1409
+ return `Session(s) ${pending.map((member) => `${member.teammateId} at ${member.sessionFile}`).join(", ")}: import pending in team ${manifest.id}, main ${manifest.originMainSessionId}, project ${manifest.projectDirectory}. Previous child startup is unresolved; not resumed.`;
1410
+ }
1411
+
1333
1412
  function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiCommand: string[], manifest: TeamManifest, lease: TeamLease): TeamState {
1334
1413
  const team: TeamState = {
1335
1414
  owner,
@@ -1353,6 +1432,9 @@ function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiCommand:
1353
1432
  teammate.sessionId = member.teammateId;
1354
1433
  teammate.sessionFile = member.sessionFile;
1355
1434
  teammate.sessionMaterialized = member.sessionMaterialized;
1435
+ teammate.session = member.session;
1436
+ teammate.importPending = member.importPending;
1437
+ teammate.needsBriefing = member.needsBriefing;
1356
1438
  teammate.contextPercent = member.contextPercent;
1357
1439
  teammate.alive = false;
1358
1440
  team.members.set(teammate.name, teammate);
@@ -1401,9 +1483,31 @@ export default function (pi: ExtensionAPI) {
1401
1483
 
1402
1484
  const parentPiCommand = piCommand(process.argv[1], process.execPath, getPackageDir());
1403
1485
  const owner = Symbol("pi-simple-team-owner");
1404
- /** This session's reminders by ID. They live in memory, so after Pi restarts every earlier reminder is unknown. */
1486
+ /** This session's reminders by ID, restored from the session's records on every session start. */
1405
1487
  const reminders = new Map<string, Reminder>();
1406
1488
  let reminderCount = 0;
1489
+
1490
+ function recordReminder(reminder: Reminder): void {
1491
+ const { timer: _timer, ...fields } = reminder;
1492
+ pi.appendEntry<ReminderRecord>(reminderType, { ...fields, armedAt: reminder.armedAt.toISOString(), wakeAt: reminder.wakeAt.toISOString() });
1493
+ }
1494
+
1495
+ /** Arms a pending reminder's timer. One that is already due fires at once and says how late it is. */
1496
+ function armReminder(reminder: Reminder): void {
1497
+ const delayMilliseconds = reminder.wakeAt.getTime() - Date.now();
1498
+ reminder.timer = setTimeout(() => {
1499
+ const now = new Date();
1500
+ const lateness = delayMilliseconds < 0 ? ` It is ${humanDuration(Math.round((now.getTime() - reminder.wakeAt.getTime()) / 1000))} late: it was due at ${humanTime(reminder.wakeAt)}.` : "";
1501
+ reminder.state = "delivered";
1502
+ recordReminder(reminder);
1503
+ pi.sendMessage(
1504
+ { customType: reminderType, content: `Reminder ${reminder.slug} wake up: it's ${humanTime(now)} now.${lateness}\n\n${reminder.message}`, display: false },
1505
+ { deliverAs: "followUp", triggerTurn: true },
1506
+ );
1507
+ }, Math.max(0, delayMilliseconds));
1508
+ reminder.timer.unref();
1509
+ }
1510
+
1407
1511
  const sessionTeammateRoster = childRuntimeConfig?.participants ?? [];
1408
1512
 
1409
1513
  /** Current-project manifests that team_resume can select: all for main, only its own for a managing teammate. */
@@ -1417,6 +1521,17 @@ export default function (pi: ExtensionAPI) {
1417
1521
  );
1418
1522
  }
1419
1523
 
1524
+ function resolveAttachments(specs: readonly Teammate[], context: ExtensionContext, projectDirectory: string) {
1525
+ return specs.map((spec) => {
1526
+ if (spec.session === undefined) return undefined;
1527
+ if (spec.forkContext) throw new Error(`session ${spec.session} conflicts with forkContext: true; attach the conversation or fork main, not both.`);
1528
+ if (!context.sessionManager?.getSessionId?.() || !projectDirectory) throw new Error(`Attaching session ${spec.session} requires a persistent main and project directory.`);
1529
+ const attachment = resolveSessionAttachment(spec.session, projectDirectory);
1530
+ if ([context.sessionManager.getSessionId(), childRuntimeConfig?.parentSessionId].includes(attachment.id)) throw new Error(`Session ${attachment.id} at ${attachment.file ?? projectDirectory} is your current main or ancestor session; it cannot be its own teammate.`);
1531
+ return attachment;
1532
+ });
1533
+ }
1534
+
1420
1535
  /** Stored dormant teammates of resumable current-project teams whose name or session ID is `identifier`. */
1421
1536
  function dormantTeammateMatches(context: ExtensionContext, identifier: string): DormantTeammateMatch[] {
1422
1537
  const name = identifier.trim();
@@ -1436,15 +1551,92 @@ export default function (pi: ExtensionAPI) {
1436
1551
  },
1437
1552
  });
1438
1553
 
1439
- pi.on("session_shutdown", async () => {
1554
+ pi.on("session_shutdown", async (event) => {
1440
1555
  for (const reminder of reminders.values()) clearTimeout(reminder.timer);
1441
1556
  reminders.clear();
1442
1557
  const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
1443
1558
  for (const team of ownedTeams) team.stopping = true;
1444
- for (const team of ownedTeams) await shutdownTeam(team);
1559
+ // Main's quit or reload keeps its running teammates for its next start. Switching to another session releases them.
1560
+ const keepsTeams = !childRuntimeConfig && (event.reason === "quit" || event.reason === "reload");
1561
+ for (const team of ownedTeams) await shutdownTeam(team, keepsTeams ? interruptedTeammates(team) : undefined);
1445
1562
  closeCallbackServerIfUnused();
1446
1563
  });
1447
1564
 
1565
+ /** Restarts a team's interrupted teammates idle, in their own conversations, without delivering anything. */
1566
+ async function reattachTeam(manifest: TeamManifest, interrupted: NonNullable<TeamManifest["interrupted"]>, inPanes: string[], parentSession: NonNullable<TeamState["parentSession"]>): Promise<Reattachment> {
1567
+ const reattachment: Reattachment = { teamName: manifest.name, teamId: manifest.id, reattached: [], working: [], inPanes };
1568
+ let team: TeamState | undefined;
1569
+ try {
1570
+ await ensureCallbackServer();
1571
+ team = restoreTeamState(owner, pi, parentPiCommand, manifest, claimTeamLease(manifest.id, parentSession.id));
1572
+ team.parentSession = parentSession;
1573
+ teams.set(team.id!, team);
1574
+ const participantNames = [...team.members.keys()];
1575
+ sessionTeammateRoster.push(...participantNames.filter((name) => !sessionTeammateRoster.includes(name)));
1576
+ const emptyRestarts: TeammateState[] = [];
1577
+ for (const name of interrupted.teammates) {
1578
+ const teammate = team.members.get(name)!;
1579
+ const sessionFile = sessionFileForResume(teammate);
1580
+ prepareTeammateStart(teammate, "rpc");
1581
+ await startTeammate(team, teammate, participantNames, undefined, { sessionFile, restartEmpty: sessionFile === undefined });
1582
+ if (!sessionFile) emptyRestarts.push(teammate);
1583
+ team.statuses.set(name, status("idle", interrupted.working.includes(name) ? "Reattached; was working when main stopped" : "Reattached"));
1584
+ }
1585
+ persistActiveTeamManifest(team);
1586
+ // Uninitialized teammates get their first team briefing staged without a turn.
1587
+ const uninitialized = interrupted.teammates.map((name) => team!.members.get(name)!).filter((teammate) => teammate.needsBriefing || emptyRestarts.includes(teammate));
1588
+ await kickoffTeammates(team, uninitialized, true, { emptyRestarts });
1589
+ return { ...reattachment, reattached: interrupted.teammates, working: interrupted.working };
1590
+ } catch (error) {
1591
+ if (team) await shutdownTeam(team);
1592
+ closeCallbackServerIfUnused();
1593
+ return { ...reattachment, error: error instanceof Error ? error.message : String(error) };
1594
+ }
1595
+ }
1596
+
1597
+ // A main session that starts again reattaches the teammates its quit, reload or crash cut off. A crash leaves the team active under a dead lease.
1598
+ pi.on("session_start", async (event, context) => {
1599
+ const mainSessionId = context.sessionManager?.getSessionId?.();
1600
+ const projectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1601
+ if (childRuntimeConfig || (event.reason !== "startup" && event.reason !== "reload") || !mainSessionId || !projectDirectory) return;
1602
+ const reattachments: Reattachment[] = [];
1603
+ for (const manifest of listTeamManifests(projectDirectory).manifests) {
1604
+ const lease = manifest.state === "active" ? readTeamLeaseState(manifest.id) : undefined;
1605
+ const crashed = lease?.state === "stale" && lease.mainSessionId === mainSessionId;
1606
+ if (!crashed && manifest.interrupted?.mainSessionId !== mainSessionId) continue;
1607
+ const pending = pendingImportError(manifest);
1608
+ if (pending) {
1609
+ reattachments.push({ teamName: manifest.name, teamId: manifest.id, reattached: [], working: [], inPanes: [], error: pending });
1610
+ continue;
1611
+ }
1612
+ const running = manifest.members.filter((member) => member.live);
1613
+ // A Herdr pane teammate is not main's child, so it can outlive main's crash; a second process on its session would corrupt it.
1614
+ const [inPanes, reattachable] = [running.filter((member) => member.showOnHerdrPane), running.filter((member) => !member.showOnHerdrPane)];
1615
+ const interrupted = crashed
1616
+ ? { mainSessionId, teammates: reattachable.map((member) => member.name), working: reattachable.filter((member) => member.active).map((member) => member.name) }
1617
+ : manifest.interrupted;
1618
+ const inPaneNames = crashed ? inPanes.map((member) => member.name) : [];
1619
+ if (interrupted && interrupted.teammates.length > 0) reattachments.push(await reattachTeam(manifest, interrupted, inPaneNames, mainSession(context)!));
1620
+ else if (inPaneNames.length > 0) reattachments.push({ teamName: manifest.name, teamId: manifest.id, reattached: [], working: [], inPanes: inPaneNames });
1621
+ }
1622
+ if (reattachments.length > 0) pi.sendMessage({ customType: reattachedMessageType, content: composeReattachmentMessage(reattachments), display: true }, { deliverAs: "nextTurn" });
1623
+ });
1624
+
1625
+ pi.on("session_start", (_event, context) => {
1626
+ // Pi's RPC session switches emit session_start twice on one instance, so a restore replaces any earlier one.
1627
+ for (const reminder of reminders.values()) clearTimeout(reminder.timer);
1628
+ reminders.clear();
1629
+ const sessionId = context.sessionManager?.getSessionId?.();
1630
+ // A forked session copies its origin's records, which stay that session's reminders.
1631
+ const records = latestReminderRecords(context.sessionManager?.getEntries?.() ?? [], sessionId);
1632
+ reminderCount = records.size;
1633
+ for (const record of records.values()) {
1634
+ const reminder: Reminder = { ...record, armedAt: new Date(record.armedAt), wakeAt: new Date(record.wakeAt) };
1635
+ reminders.set(reminder.id, reminder);
1636
+ if (reminder.state === "pending") armReminder(reminder);
1637
+ }
1638
+ });
1639
+
1448
1640
  pi.on("session_start", (_event, context) => {
1449
1641
  useModelNames(context.modelRegistry);
1450
1642
  const scopedModels = (context as typeof context & { scopedModels?: ReadonlyArray<{ model: ModelReference }> }).scopedModels ?? [];
@@ -1470,18 +1662,19 @@ export default function (pi: ExtensionAPI) {
1470
1662
  const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
1471
1663
  const teammateSpecs: Teammate[] = params.teammates.map((teammate) => ({ ...teammate, showOnHerdrPane: params.showOnHerdrPanes ?? teammate.showOnHerdrPane ?? false }));
1472
1664
  const herdrParentPaneId = showOnHerdrPanes || teammateSpecs.some((teammate) => teammate.showOnHerdrPane) ? await validateHerdrAvailability() : undefined;
1665
+ const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1666
+ const projectDirectory = rawProjectDirectory ? canonicalProjectDirectory(rawProjectDirectory) : undefined;
1667
+ const attachments = resolveAttachments(teammateSpecs, context, projectDirectory!);
1473
1668
  const teammateNames = teammateSpecs.map((teammate) => compactName(teammate.name));
1474
1669
  const duplicateNames = teammateNames.filter((name, index) => teammateNames.indexOf(name) !== index);
1475
1670
  if (duplicateNames.length > 0) throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
1476
1671
  if (teammateNames.includes("main")) throw new Error('"main" is reserved');
1477
1672
 
1478
- validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
1673
+ validateTeammateModels(teammateSpecs.filter((spec) => spec.model !== undefined) as Array<Teammate & { model: string }>, context.modelRegistry.getAvailable());
1479
1674
  const forksContext = teammateSpecs.some((teammate) => Boolean(teammate.forkContext));
1480
1675
  const mainSessionFile = forksContext ? context.sessionManager.getSessionFile() : undefined;
1481
1676
  if (forksContext && !mainSessionFile) throw new Error("forkContext requires a saved main session. Use a saved main session or retry with forkContext: false.");
1482
1677
  const originMainSessionId = context.sessionManager?.getSessionId?.();
1483
- const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1484
- const projectDirectory = rawProjectDirectory ? canonicalProjectDirectory(rawProjectDirectory) : undefined;
1485
1678
  const teamId = originMainSessionId && projectDirectory ? `${originMainSessionId}-${teamName}` : undefined;
1486
1679
  const runtimeTeamId = teamId ?? teamName;
1487
1680
  if (teams.has(runtimeTeamId)) throw new Error(`Team already exists: ${runtimeTeamId}`);
@@ -1513,6 +1706,7 @@ export default function (pi: ExtensionAPI) {
1513
1706
  showOnHerdrPanes,
1514
1707
  teamPrompt: params.commonPrompt,
1515
1708
  mainSessionFile,
1709
+ parentSession: mainSession(context),
1516
1710
  members: new Map(),
1517
1711
  statuses: new Map([["main", status("available", "Main agent")]]),
1518
1712
  created: new Date().toISOString(),
@@ -1523,39 +1717,38 @@ export default function (pi: ExtensionAPI) {
1523
1717
 
1524
1718
  teams.set(runtimeTeamId, team);
1525
1719
  try {
1526
- for (const teammateSpec of teammateSpecs) {
1527
- const teammate = createTeammateState(teammateSpec);
1720
+ for (const [index, spec] of teammateSpecs.entries()) {
1721
+ const teammate = createTeammateState(spec, attachments[index], projectDirectory);
1528
1722
  team.members.set(teammate.name, teammate);
1529
1723
  team.statuses.set(teammate.name, status("idle", "Spawned"));
1530
- await startTeammate(team, teammate, teammateNames, herdrParentPaneId, { signal });
1724
+ }
1725
+ if (attachments.some(Boolean)) {
1726
+ const manifest = createTeamManifest(team);
1727
+ reserveSessionImports(manifest, attachments.filter((attachment) => attachment !== undefined), Boolean(childRuntimeConfig));
1728
+ team.manifest = manifest;
1729
+ }
1730
+ for (const [index, teammateSpec] of teammateSpecs.entries()) {
1731
+ const attachment = attachments[index];
1732
+ const teammate = team.members.get(compactName(teammateSpec.name))!;
1733
+ await startTeammate(team, teammate, teammateNames, herdrParentPaneId, {
1734
+ signal, sessionFile: attachment?.file, restoreSettings: Boolean(attachment),
1735
+ settings: attachment ? { teammate: teammate.name, model: teammateSpec.model, thinking: teammateSpec.thinking } : undefined,
1736
+ });
1531
1737
  }
1532
1738
  signal?.throwIfAborted();
1533
1739
 
1534
1740
  if (teamId && originMainSessionId && projectDirectory) {
1535
- const timestamp = new Date().toISOString();
1536
- const manifest: TeamManifest = {
1537
- version: 2,
1538
- id: teamId,
1539
- name: team.name,
1540
- originMainSessionId,
1541
- projectDirectory,
1542
- teamPrompt: team.teamPrompt,
1543
- showOnHerdrPanes: team.showOnHerdrPanes,
1544
- members: [...team.members.values()].map(manifestMemberFromTeammate),
1545
- state: "active",
1546
- createdAt: timestamp,
1547
- updatedAt: timestamp,
1548
- };
1741
+ const manifest = createTeamManifest(team);
1549
1742
  writeTeamManifest(manifest);
1550
1743
  team.manifest = manifest;
1551
1744
  }
1552
1745
  } catch (error) {
1553
- await shutdownTeam(team);
1746
+ await shutdownTeam(team, undefined, true);
1554
1747
  closeCallbackServerIfUnused();
1555
1748
  throw error;
1556
1749
  }
1557
1750
  await kickoffTeammates(team, [...team.members.values()], Boolean(params.startIdle));
1558
- return toolResult(lifecycleResult(team));
1751
+ return toolResult({ ...lifecycleResult(team), teammates: [...team.members.values()].map((teammate) => ({ ...teammateRecord(teammate), ...(teammate.session ? { contextRestored: teammate.contextRestored } : {}) })) });
1559
1752
  },
1560
1753
  }),
1561
1754
  );
@@ -1573,7 +1766,7 @@ export default function (pi: ExtensionAPI) {
1573
1766
  delayMinutes: Type.Number({ exclusiveMinimum: 0, maximum: 35_791, description: "Minutes until the reminder" }),
1574
1767
  message: Type.String({ minLength: 1, description: "Custom message that wakes you" }),
1575
1768
  }, { additionalProperties: false }),
1576
- async execute(_toolCallId, params) {
1769
+ async execute(_toolCallId, params, _signal, _onUpdate, context) {
1577
1770
  const delayMilliseconds = params.delayMinutes * 60_000;
1578
1771
  const delaySeconds = Math.round(delayMilliseconds / 1000);
1579
1772
  const armedAt = new Date();
@@ -1581,16 +1774,10 @@ export default function (pi: ExtensionAPI) {
1581
1774
  const pendingSlugs = new Set([...reminders.values()].filter((reminder) => reminder.state === "pending").map((reminder) => reminder.slug));
1582
1775
  let slug = reminderSlug();
1583
1776
  while (pendingSlugs.has(slug)) slug = reminderSlug();
1584
- const id = `reminder-${++reminderCount}`;
1585
- const timer = setTimeout(() => {
1586
- reminders.get(id)!.state = "delivered";
1587
- pi.sendMessage(
1588
- { customType: "pi-simple-team-reminder", content: `Reminder ${slug} wake up: it's ${humanTime(new Date())} now.\n\n${params.message}`, display: false },
1589
- { deliverAs: "followUp", triggerTurn: true },
1590
- );
1591
- }, delayMilliseconds);
1592
- reminders.set(id, { id, slug, message: params.message, armedAt, wakeAt, timer, state: "pending" });
1593
- timer.unref();
1777
+ const reminder: Reminder = { sessionId: context.sessionManager.getSessionId(), id: `reminder-${++reminderCount}`, slug, message: params.message, armedAt, wakeAt, state: "pending" };
1778
+ reminders.set(reminder.id, reminder);
1779
+ recordReminder(reminder);
1780
+ armReminder(reminder);
1594
1781
  return {
1595
1782
  content: [{ type: "text" as const, text: `Armed reminder ${slug}: It's ${humanTime(armedAt)} now. Reminder set in ${delaySeconds} seconds (${humanDuration(delaySeconds)}) for ${humanTime(wakeAt)}.` }],
1596
1783
  details: { scheduledAt: wakeAt.toISOString(), message: params.message, slug },
@@ -1636,6 +1823,7 @@ export default function (pi: ExtensionAPI) {
1636
1823
  if (reminder.state === "pending") {
1637
1824
  clearTimeout(reminder.timer);
1638
1825
  reminder.state = "cancelled";
1826
+ recordReminder(reminder);
1639
1827
  }
1640
1828
  return { id: reminder.id, slug: reminder.slug, result: reminder.state, ...(reminder.state === "cancelled" ? { message: reminder.message, wakeAt: humanTime(reminder.wakeAt) } : {}) };
1641
1829
  };
@@ -1715,7 +1903,6 @@ export default function (pi: ExtensionAPI) {
1715
1903
  renderResult: (result, options, theme, context) => renderTeamToolResult("team_resume", result, options, theme, context, undefined, sessionTeammateRoster),
1716
1904
  parameters: Type.Object({
1717
1905
  team: Type.String({ description: "Team name or persistent ID" }),
1718
- // TODO: Should allow defining new teammates or even existing teammates (any Pi session ID belonging to this project) from other teams and sessions for maximum flexibility.
1719
1906
  teammates: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description: "Teammate names or Pi session IDs within this team. Omit to resume all stopped teammates." })),
1720
1907
  showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false, description: "Open visible Herdr panes for selected teammates. Defaults to false." })),
1721
1908
  startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start resumed teammates idle." })),
@@ -1726,6 +1913,8 @@ export default function (pi: ExtensionAPI) {
1726
1913
  signal?.throwIfAborted();
1727
1914
  const manifest = resolveTeamIdentifier(resumableTeamManifests(context, "team_resume"), params.team);
1728
1915
  if (!manifest) throw new Error(`Unknown current-project team: ${JSON.stringify(params.team)}. Call team_list with includeDormantTeams: true and pass a listed teamId or unique teamName in the team parameter.`);
1916
+ const pending = pendingImportError(manifest);
1917
+ if (pending) throw new Error(pending);
1729
1918
  const members = manifest.members;
1730
1919
  const requestedNames = resolveTeammates(members, params.teammates ?? members.map((member) => member.teammateId)).map((member) => member.name);
1731
1920
  const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
@@ -1749,6 +1938,7 @@ export default function (pi: ExtensionAPI) {
1749
1938
  try {
1750
1939
  await ensureCallbackServer();
1751
1940
  team = restoreTeamState(owner, pi, parentPiCommand, manifest, lease);
1941
+ team.parentSession = mainSession(context);
1752
1942
  teams.set(team.id!, team);
1753
1943
  } catch (error) {
1754
1944
  releaseTeamLease(lease);
@@ -1827,8 +2017,7 @@ export default function (pi: ExtensionAPI) {
1827
2017
  renderResult: (result, options, theme, context) => renderTeamToolResult("team_add_teammates", result, options, theme, context, getMarkdownTheme(), sessionTeammateRoster),
1828
2018
  parameters: Type.Object({
1829
2019
  team: Type.Optional(Type.String({ description: "Team name or persistent ID. Omit when exactly one owned active team exists." })),
1830
- // TODO: Accept existing current-project Pi session IDs as well as new teammate definitions.
1831
- teammates: Type.Array(teammateSchema(""), { minItems: 1, description: "New teammate definitions to add. Existing Pi sessions cannot yet be attached." }),
2020
+ teammates: Type.Array(teammateSchema(""), { minItems: 1, description: "Teammate definitions to add, optionally using a stopped, never-teamed session." }),
1832
2021
  startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start added teammates idle." })),
1833
2022
  }, { additionalProperties: false }),
1834
2023
  async execute(_toolCallId, params, signal, _onUpdate, context) {
@@ -1851,14 +2040,20 @@ export default function (pi: ExtensionAPI) {
1851
2040
  throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
1852
2041
  }
1853
2042
  if (teammateNames.includes("main")) throw new Error('"main" is reserved');
1854
- validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
2043
+ validateTeammateModels(teammateSpecs.filter((spec) => spec.model !== undefined) as Array<Teammate & { model: string }>, context.modelRegistry.getAvailable());
1855
2044
 
1856
2045
  const forksContext = teammateSpecs.some((teammate) => Boolean(teammate.forkContext));
1857
2046
  const mainSessionFile = forksContext ? context.sessionManager.getSessionFile() : undefined;
1858
2047
  if (forksContext && !mainSessionFile) throw new Error("forkContext requires a saved main session. Use a saved main session or retry with forkContext: false.");
1859
2048
  if (mainSessionFile) team.mainSessionFile = mainSessionFile;
1860
2049
 
1861
- const addedTeammates = teammateSpecs.map(createTeammateState);
2050
+ const attachments = resolveAttachments(teammateSpecs, context, team.projectDirectory!);
2051
+ const addedTeammates = teammateSpecs.map((spec, index) => createTeammateState(spec, attachments[index], team.projectDirectory));
2052
+ if (attachments.some(Boolean)) {
2053
+ const manifest = { ...team.manifest, members: [...registeredManifestMembers(team), ...addedTeammates.filter((teammate) => teammate.session).map(manifestMemberFromTeammate)] };
2054
+ reserveSessionImports(manifest, attachments.filter((attachment) => attachment !== undefined), Boolean(childRuntimeConfig));
2055
+ team.manifest = manifest;
2056
+ }
1862
2057
  for (const teammate of addedTeammates) {
1863
2058
  team.members.set(teammate.name, teammate);
1864
2059
  team.statuses.set(teammate.name, status("idle", "Spawned"));
@@ -1867,7 +2062,10 @@ export default function (pi: ExtensionAPI) {
1867
2062
  sessionTeammateRoster.push(...teammateNames.filter((name) => !sessionTeammateRoster.includes(name)));
1868
2063
 
1869
2064
  try {
1870
- for (const teammate of addedTeammates) await startTeammate(team, teammate, participantNames, herdrParentPaneId, { signal });
2065
+ for (const [index, teammate] of addedTeammates.entries()) await startTeammate(team, teammate, participantNames, herdrParentPaneId, {
2066
+ signal, sessionFile: attachments[index]?.file, restoreSettings: Boolean(attachments[index]),
2067
+ settings: attachments[index] ? { teammate: teammate.name, model: teammateSpecs[index].model, thinking: teammateSpecs[index].thinking } : undefined,
2068
+ });
1871
2069
  signal?.throwIfAborted();
1872
2070
  persistActiveTeamManifest(team);
1873
2071
  } catch (error) {
@@ -1876,6 +2074,11 @@ export default function (pi: ExtensionAPI) {
1876
2074
  else await stopRpcTeammate(teammate);
1877
2075
  }
1878
2076
  for (const teammate of addedTeammates) {
2077
+ if (teammate.session && teammate.processRecord?.registered && teammate.transport === "rpc") {
2078
+ teammate.importPending = undefined;
2079
+ continue;
2080
+ }
2081
+ if (teammate.importPending && teammate.transport === "herdr" && teammate.processRecord) continue;
1879
2082
  team.members.delete(teammate.name);
1880
2083
  team.statuses.delete(teammate.name);
1881
2084
  }
@@ -1886,7 +2089,7 @@ export default function (pi: ExtensionAPI) {
1886
2089
  await kickoffTeammates(team, addedTeammates, Boolean(params.startIdle));
1887
2090
  return toolResult({
1888
2091
  ...lifecycleResult(team),
1889
- teammates: [...team.members.values()].map(teammateSummary),
2092
+ teammates: [...team.members.values()].map((teammate) => ({ ...teammateSummary(teammate), ...(addedTeammates.includes(teammate) && teammate.session ? { sessionFile: teammate.sessionFile, contextRestored: teammate.contextRestored } : {}) })),
1890
2093
  status: formatStatus(team),
1891
2094
  }, { addedTeammates: addedTeammates.map(teammateRecord) });
1892
2095
  },
@@ -1967,6 +2170,7 @@ export default function (pi: ExtensionAPI) {
1967
2170
  const selections = resolveTargets(candidates, params.targets);
1968
2171
  const interrupted = interruptedTeammateIds(candidates, selections, params.interrupt);
1969
2172
  const statuses: JsonRecord[] = [];
2173
+ const recipients: Array<{ name: string; contextPercent?: number }> = [];
1970
2174
  for (const selection of selections) {
1971
2175
  if (selection.team === parent) {
1972
2176
  const result = await callParent(childRuntimeConfig!, "team_send_message", {
@@ -1974,13 +2178,15 @@ export default function (pi: ExtensionAPI) {
1974
2178
  interrupt: selection.teammates.filter((teammate) => interrupted.has(teammate.teammateId)).map((teammate) => teammate.teammateId),
1975
2179
  }, signal);
1976
2180
  statuses.push(...result.teams as JsonRecord[]);
2181
+ recipients.push(...selection.teammates.map((teammate) => ({ name: teammate.name })));
1977
2182
  continue;
1978
2183
  }
1979
2184
  const team = teams.get(selection.team.teamId)!;
1980
2185
  for (const recipient of selection.teammates) enqueueDelivery(team, "main", team.members.get(recipient.name)!, params.message, interrupted.has(recipient.teammateId));
1981
2186
  statuses.push({ ...teamIdentity(team), status: formatStatus(team) });
2187
+ recipients.push(...selection.teammates.map((recipient) => agentContext(team.members.get(recipient.name)!)));
1982
2188
  }
1983
- return toolResult({ published: true, teams: statuses, instruction: "Do not wait for replies. Teammates will message you back." });
2189
+ return toolResult({ published: true, teams: statuses, instruction: "Do not wait for replies. Teammates will message you back." }, { agentContext: recipients });
1984
2190
  },
1985
2191
  }),
1986
2192
  );
@@ -2125,6 +2331,7 @@ export default function (pi: ExtensionAPI) {
2125
2331
  async execute(_toolCallId, params) {
2126
2332
  const team = resolveTeam(owner, params.team);
2127
2333
  const teammates = [...team.members.values()].map(teammateReference);
2334
+ const stoppedContext = [...team.members.values()].map(agentContext);
2128
2335
  const droppedUpdates = [...team.members.values()].flatMap((teammate) => {
2129
2336
  const heldUpdate = teammate.processRecord?.heldUpdate;
2130
2337
  return heldUpdate ? [{ ...teammateReference(teammate), settings: describeSettings(heldUpdate) }] : [];
@@ -2135,7 +2342,7 @@ export default function (pi: ExtensionAPI) {
2135
2342
  return toolResult({
2136
2343
  ...teamIdentity(team), stopped: true, teammates,
2137
2344
  ...(droppedUpdates.length > 0 ? { droppedUpdates, instruction: "These held settings updates were not applied. Pass them in teammateUpdates when you resume the team." } : {}),
2138
- });
2345
+ }, { agentContext: stoppedContext });
2139
2346
  },
2140
2347
  }),
2141
2348
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "2.0.24",
3
+ "version": "2.0.26",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -0,0 +1,20 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+
3
+ export interface ReminderRecord {
4
+ sessionId: string;
5
+ id: string;
6
+ slug: string;
7
+ message: string;
8
+ armedAt: string;
9
+ wakeAt: string;
10
+ state: "pending" | "delivered" | "cancelled";
11
+ }
12
+
13
+ export const reminderType = "pi-simple-team-reminder";
14
+
15
+ /** Select this session’s latest reminder records across all branches. @example latestReminderRecords([], "s").size // 0 */
16
+ export function latestReminderRecords(entries: readonly SessionEntry[], sessionId: string | undefined): Map<string, ReminderRecord> {
17
+ return new Map(entries
18
+ .flatMap((entry) => entry.type === "custom" && entry.customType === reminderType && (entry.data as ReminderRecord).sessionId === sessionId ? [entry.data as ReminderRecord] : [])
19
+ .map((record) => [record.id, record]));
20
+ }
package/render.ts CHANGED
@@ -33,6 +33,12 @@ export interface TeamStatusView {
33
33
  updated: string;
34
34
  }
35
35
 
36
+ /** An agent a tool involves, with the context use it last reported when the result carries it. */
37
+ export interface AgentContextView {
38
+ name: string;
39
+ contextPercent?: number;
40
+ }
41
+
36
42
  export interface TeamMessageDetails {
37
43
  team: string;
38
44
  from: string;
@@ -316,7 +322,7 @@ export interface TeamListTeamView {
316
322
  function teamListMemberName(theme: ThemeLike, teamView: TeamListTeamView, member: TeamListMemberView, roster: string[]): string {
317
323
  const hued = theme.fg(actorHueToken(member.name, roster), member.name);
318
324
  const name = teamView.state === "active" && !member.live ? `${DIM_SGR_OPEN}${hued}${DIM_SGR_CLOSE}` : hued;
319
- return [name, inlineFact(theme, "manager", member)].filter((part) => part.length > 0).join(" ");
325
+ return [name, inlineFact(theme, "context", member), inlineFact(theme, "manager", member)].filter((part) => part.length > 0).join(" ");
320
326
  }
321
327
 
322
328
  function teamListTimestamp(teamView: TeamListTeamView): string {
@@ -367,8 +373,18 @@ function actorList(theme: ThemeLike, names: string[], roster: string[], separato
367
373
  return names.map((name) => theme.fg(actorHueToken(name, roster), name)).join(theme.fg("muted", separator));
368
374
  }
369
375
 
370
- function sendTarget(theme: ThemeLike, to: string[], roster: string[] = []): string {
371
- const recipients = actorList(theme, to, roster, ", ");
376
+ /** An agent's name in its roster hue, followed by its context reading in the teammate rows' full form when known. */
377
+ function agentWithContext(theme: ThemeLike, agent: AgentContextView, roster: string[]): string {
378
+ return [theme.fg(actorHueToken(agent.name, roster), agent.name), inlineFact(theme, "context", agent, "full")].filter((part) => part.length > 0).join(" ");
379
+ }
380
+
381
+ function agentsWithContext(theme: ThemeLike, agents: AgentContextView[], roster: string[], separator: string): string {
382
+ return agents.map((agent) => agentWithContext(theme, agent, roster)).join(theme.fg("muted", separator));
383
+ }
384
+
385
+ /** The pending call names the targets as given. A result names each recipient with its context use, which comes before the character count. */
386
+ function sendTarget(theme: ThemeLike, to: string[], roster: string[] = [], agentContext?: AgentContextView[]): string {
387
+ const recipients = agentContext ? agentsWithContext(theme, agentContext, roster, ", ") : actorList(theme, to, roster, ", ");
372
388
  return `${theme.fg("muted", `${glyphs().arrow} `)}${recipients}`;
373
389
  }
374
390
 
@@ -381,20 +397,20 @@ function hasInterruption(interrupt: unknown): boolean {
381
397
  return interrupt === true || (Array.isArray(interrupt) && interrupt.length > 0);
382
398
  }
383
399
 
384
- function teamSendHeader(theme: ThemeLike, targets: string[], message: string, interrupt: boolean, roster: string[]): string {
385
- return headerLine(theme, "Team Send", sendTarget(theme, targets, roster), sendStats(theme, message, interrupt));
400
+ function teamSendHeader(theme: ThemeLike, targets: string[], message: string, interrupt: boolean, roster: string[], agentContext?: AgentContextView[]): string {
401
+ return headerLine(theme, "Team Send", sendTarget(theme, targets, roster, agentContext), sendStats(theme, message, interrupt));
386
402
  }
387
403
 
388
- export function teamSendLines(theme: ThemeLike, options: { targets: string[]; message: string; interrupt: boolean; expanded: boolean }, roster: string[] = []): TeamLine[] {
389
- const header = teamSendHeader(theme, options.targets, options.message, options.interrupt, roster);
404
+ export function teamSendLines(theme: ThemeLike, options: { targets: string[]; agentContext?: AgentContextView[]; message: string; interrupt: boolean; expanded: boolean }, roster: string[] = []): TeamLine[] {
405
+ const header = teamSendHeader(theme, options.targets, options.message, options.interrupt, roster, options.agentContext);
390
406
  const lineLimit = options.expanded ? Number.POSITIVE_INFINITY : SEND_PREVIEW_LINES;
391
407
  return [header, ...quotedBody(theme, options.message, { lineLimit, barToken: "muted" })];
392
408
  }
393
409
 
394
- export function teamShutdownLines(theme: ThemeLike, team: string, teammates: string[], roster: string[] = []): string[] {
410
+ export function teamShutdownLines(theme: ThemeLike, team: string, teammates: AgentContextView[], roster: string[] = []): string[] {
395
411
  const header = headerLine(theme, "Team Shutdown", theme.fg("accent", team), [theme.fg("muted", `${plural(teammates.length, "teammate")} stopped`)]);
396
412
  if (teammates.length === 0) return [header];
397
- return [header, `${treeConnector(theme, "└")}${actorList(theme, teammates, roster, glyphs().dot)}`];
413
+ return [header, `${treeConnector(theme, "└")}${agentsWithContext(theme, teammates, roster, glyphs().dot)}`];
398
414
  }
399
415
 
400
416
  function reminderCallBody(theme: ThemeLike, args: Record<string, unknown>): string {
@@ -829,6 +845,7 @@ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<strin
829
845
  if (tool === "team_send_message") {
830
846
  return teamSendLines(theme, {
831
847
  targets: (args.targets ?? []) as string[],
848
+ agentContext: details.agentContext as AgentContextView[] | undefined,
832
849
  message: String(args.message ?? ""),
833
850
  interrupt: hasInterruption(args.interrupt),
834
851
  expanded,
@@ -850,7 +867,7 @@ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<strin
850
867
  if (details.nextCursor) lines.push(theme.fg("muted", ` Older events: cursor "${details.nextCursor}"`));
851
868
  return lines;
852
869
  }
853
- return teamShutdownLines(theme, String(details.teamName), (details.teammates as Array<{ name: string }>).map((teammate) => teammate.name), roster);
870
+ return teamShutdownLines(theme, String(details.teamName), (details.agentContext ?? details.teammates) as AgentContextView[], roster);
854
871
  }
855
872
 
856
873
  export function renderTeamToolCall(tool: TeamToolName, args: Record<string, unknown>, theme: ThemeLike, context: ToolRenderContextLike, roster: string[] = []) {
@@ -873,7 +890,7 @@ export function renderTeamToolResult(
873
890
  const details = (result?.details ?? {}) as Record<string, unknown>;
874
891
  if (markdownTheme && tool === "team_send_message") {
875
892
  const message = String(args.message ?? "");
876
- const header = teamSendHeader(theme, (args.targets ?? []) as string[], message, hasInterruption(args.interrupt), roster);
893
+ const header = teamSendHeader(theme, (args.targets ?? []) as string[], message, hasInterruption(args.interrupt), roster, details.agentContext as AgentContextView[] | undefined);
877
894
  const bar = ` ${theme.fg("muted", glyphs().codeBar)} `;
878
895
  return new QuotedMarkdownView(header, message, bar, markdownTheme, options.expanded, theme);
879
896
  }
package/resume-message.ts CHANGED
@@ -37,3 +37,33 @@ export function composeSettingsMessage(settings: string, stoppedTeams: ReadonlyA
37
37
  stoppedTeams.length > 0 && `Your restart stopped the teams you manage: ${stopped}. Their teammates were idle, and their conversations are kept. Resume them with team_resume when you continue.`,
38
38
  ].filter(Boolean).join("\n\n");
39
39
  }
40
+
41
+ /** What main's start did with one of its teams that its last stop interrupted. */
42
+ export interface Reattachment {
43
+ teamName: string;
44
+ teamId: string;
45
+ reattached: string[];
46
+ working: string[];
47
+ inPanes: string[];
48
+ error?: string;
49
+ }
50
+
51
+ /**
52
+ * Tell main, in one message, which teammates its start reattached, which of them were working, and which it left alone.
53
+ * @example composeReattachmentMessage([{ teamName: "r", teamId: "m-r", reattached: ["a"], working: [], inPanes: [] }]).endsWith('Team "r" (team ID: m-r): a.') // true
54
+ */
55
+ export function composeReattachmentMessage(reattachments: readonly Reattachment[]): string {
56
+ const listed = (pick: (reattachment: Reattachment) => string[]) => reattachments.flatMap((reattachment) => pick(reattachment).map((name) => `${name} (team "${reattachment.teamName}")`)).join(", ");
57
+ const reattached = reattachments.filter((reattachment) => reattachment.reattached.length > 0);
58
+ const working = listed((reattachment) => reattachment.working);
59
+ const inPanes = listed((reattachment) => reattachment.inPanes);
60
+ return [
61
+ reattached.length > 0 && [
62
+ "Simple Team reattached the teammates that were running when your session last stopped. They resumed idle, and nothing was sent to them.",
63
+ ...reattached.map((reattachment) => `Team "${reattachment.teamName}" (team ID: ${reattachment.teamId}): ${reattachment.reattached.join(", ")}.`),
64
+ ].join("\n"),
65
+ working && `These were working when your session stopped: ${working}. Message each one to continue.`,
66
+ inPanes && `Not reattached, because a Herdr pane teammate may still be running in its pane: ${inPanes}. Check its pane before you use team_resume.`,
67
+ ...reattachments.filter((reattachment) => reattachment.error).map((reattachment) => `Could not reattach team "${reattachment.teamName}" (team ID: ${reattachment.teamId}): ${reattachment.error} Inspect the blocking state before resuming.`),
68
+ ].filter(Boolean).join("\n\n");
69
+ }
@@ -0,0 +1,34 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { SessionManager, type FileEntry } from "@earendil-works/pi-coding-agent";
4
+ import { latestReminderRecords } from "./reminder-records.ts";
5
+ import { canonicalProjectDirectory } from "./team-registry.ts";
6
+
7
+ export interface SessionAttachment {
8
+ id: string;
9
+ file?: string;
10
+ previousTeam?: string;
11
+ }
12
+
13
+ /** Resolves an exact project ID or existing absolute JSONL without opening a writable session. */
14
+ export function resolveSessionAttachment(selector: string, projectDirectory: string): SessionAttachment {
15
+ try {
16
+ const absolute = path.isAbsolute(selector);
17
+ if (!absolute) SessionManager.inMemory(projectDirectory, { id: selector });
18
+ const file = absolute ? selector : SessionManager.findById(projectDirectory, selector);
19
+ if (!file) return { id: selector };
20
+ const entries = fs.readFileSync(file, "utf8").split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line) as FileEntry);
21
+ const header = entries[0];
22
+ if (header?.type !== "session" || typeof header.id !== "string" || typeof header.cwd !== "string") throw new Error(`Session at ${file} has no valid Pi session header.`);
23
+ if (canonicalProjectDirectory(header.cwd) !== projectDirectory) throw new Error(`Session ${header.id} at ${file} belongs to project ${header.cwd}, not ${projectDirectory}. Cross-project attachment is not supported (#39).`);
24
+ const session = SessionManager.inMemory(projectDirectory, undefined, entries);
25
+ // #19: use the extracted reminder package's records/API when reminders move out.
26
+ const pending = [...latestReminderRecords(session.getEntries(), header.id).values()].filter((record) => record.state === "pending");
27
+ if (pending.length > 0) throw new Error(`Session ${header.id} at ${file} has ${pending.length} pending reminder(s): ${pending.map((record) => `${record.id} (${record.slug})`).join(", ")}. Resolve them in the original session before attaching.`);
28
+ const breadcrumb = session.getEntries().find((entry) => entry.type === "custom" && entry.customType === "pi-simple-team-teammate" && (entry.data as { sessionId?: string })?.sessionId === header.id);
29
+ const provenance = breadcrumb?.type === "custom" ? breadcrumb.data as { teamId: string; parentSessionId: string } : undefined;
30
+ return { id: header.id, file: fs.realpathSync(file), ...(provenance ? { previousTeam: `team ${provenance.teamId}, main ${provenance.parentSessionId}` } : {}) };
31
+ } catch (error) {
32
+ throw new Error(`Cannot attach session ${selector} in project ${projectDirectory}: ${error instanceof Error ? error.message : String(error)}`);
33
+ }
34
+ }
package/team-registry.ts CHANGED
@@ -3,10 +3,13 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
 
5
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ import type { SessionAttachment } from "./session-attachment.ts";
6
7
  import type { TeammateRecord } from "./teammate.ts";
7
8
 
8
9
  export interface TeamManifestMember extends TeammateRecord {
9
10
  sessionMaterialized: boolean;
11
+ importPending?: boolean;
12
+ needsBriefing?: boolean;
10
13
  }
11
14
 
12
15
  export interface TeamManifest {
@@ -23,6 +26,8 @@ export interface TeamManifest {
23
26
  updatedAt: string;
24
27
  shutdownAt?: string;
25
28
  expiresAt?: string;
29
+ /** The main session that was running this team when its quit or reload stopped it, and the teammates then running and working. That main's next start reattaches them. */
30
+ interrupted?: { mainSessionId: string; teammates: string[]; working: string[] };
26
31
  }
27
32
 
28
33
  export interface TeamLease {
@@ -77,11 +82,19 @@ function isManifestMember(value: unknown): value is TeamManifestMember {
77
82
  typeof member.teammateId === "string" &&
78
83
  typeof member.sessionFile === "string" &&
79
84
  typeof member.sessionMaterialized === "boolean" &&
85
+ (member.importPending === undefined || typeof member.importPending === "boolean") &&
86
+ (member.needsBriefing === undefined || typeof member.needsBriefing === "boolean") &&
87
+ (member.session === undefined || typeof member.session === "string") &&
80
88
  (member.contextPercent === undefined || typeof member.contextPercent === "number") &&
81
89
  (member.extensionPaths === undefined || (Array.isArray(member.extensionPaths) && member.extensionPaths.every((value) => typeof value === "string" && path.isAbsolute(value))))
82
90
  );
83
91
  }
84
92
 
93
+ function isInterruption(value: unknown): value is TeamManifest["interrupted"] {
94
+ const names = (list: unknown) => Array.isArray(list) && list.every((name) => typeof name === "string");
95
+ return typeof value === "object" && value !== null && typeof (value as Record<string, unknown>).mainSessionId === "string" && names((value as Record<string, unknown>).teammates) && names((value as Record<string, unknown>).working);
96
+ }
97
+
85
98
  function parseManifest(filePath: string): TeamManifest {
86
99
  const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf8"));
87
100
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
@@ -104,7 +117,8 @@ function parseManifest(filePath: string): TeamManifest {
104
117
  typeof manifest.createdAt !== "string" ||
105
118
  typeof manifest.updatedAt !== "string" ||
106
119
  (manifest.shutdownAt !== undefined && typeof manifest.shutdownAt !== "string") ||
107
- (manifest.expiresAt !== undefined && typeof manifest.expiresAt !== "string")
120
+ (manifest.expiresAt !== undefined && typeof manifest.expiresAt !== "string") ||
121
+ (manifest.interrupted !== undefined && !isInterruption(manifest.interrupted))
108
122
  ) {
109
123
  throw new Error(`Invalid team manifest: ${filePath}`);
110
124
  }
@@ -149,6 +163,11 @@ export function writeTeamManifest(manifest: TeamManifest): void {
149
163
  fs.renameSync(temporaryPath, filePath);
150
164
  }
151
165
 
166
+ /** Removes a new import reservation only after its creating runtime has stopped every child. */
167
+ export function discardTeamImportReservation(teamId: string): void {
168
+ fs.rmSync(manifestPath(teamId));
169
+ }
170
+
152
171
  /** Whether a saved attachment file holds this team ID, readable or not. */
153
172
  export function teamManifestExists(teamId: string): boolean {
154
173
  return fs.existsSync(manifestPath(teamId));
@@ -190,7 +209,7 @@ export function listTeamManifests(projectDirectory: string): { manifests: TeamMa
190
209
  if ((claimedProjectDirectory(filePath) ?? resolvedProjectDirectory) === resolvedProjectDirectory) unreadable.push({ filePath, error: error instanceof Error ? error.message : String(error) });
191
210
  continue;
192
211
  }
193
- if (manifest.state === "dormant" && now >= Date.parse(manifest.expiresAt ?? "")) {
212
+ if (manifest.state === "dormant" && !manifest.members.some((member) => member.importPending) && now >= Date.parse(manifest.expiresAt ?? "")) {
194
213
  fs.rmSync(leasePath(manifest.id), { force: true });
195
214
  fs.rmSync(filePath);
196
215
  continue;
@@ -200,6 +219,42 @@ export function listTeamManifests(projectDirectory: string): { manifests: TeamMa
200
219
  return { manifests: manifests.sort((left, right) => left.id.localeCompare(right.id)), unreadable };
201
220
  }
202
221
 
222
+ /** Checks retained ownership and reserves the import batch before any child can load its session. */
223
+ export function reserveSessionImports(destination: TeamManifest, attachments: readonly SessionAttachment[], managing = false): void {
224
+ const directory = manifestsDirectory();
225
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
226
+ const lock = path.join(directory, ".session-import-lock");
227
+ try {
228
+ fs.mkdirSync(lock, { mode: 0o700 });
229
+ } catch (error) {
230
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
231
+ throw new Error(`Session import reservation is already in progress at ${lock}; sessions ${attachments.map((attachment) => attachment.id).join(", ")} remain unclaimed by team ${destination.id}.`);
232
+ }
233
+ try {
234
+ const manifests = fs.readdirSync(directory).filter((file) => file.endsWith(".json")).map((file) => parseManifest(path.join(directory, file)));
235
+ const liveLeases = fs.readdirSync(directory).filter((file) => file.endsWith(".lease")).map((file) => parseLease(path.join(directory, file))).filter((lease) => processIsAlive(lease.processId));
236
+ const canonicalFile = (file: string): string => fs.existsSync(file) ? fs.realpathSync(file) : path.resolve(file);
237
+ const seen = new Set<string>();
238
+ for (const attachment of attachments) {
239
+ if (seen.has(attachment.id)) throw new Error(`Session ${attachment.id} at ${attachment.file ?? destination.projectDirectory} is selected twice for team ${destination.id}.`);
240
+ seen.add(attachment.id);
241
+ for (const manifest of manifests) {
242
+ const member = manifest.members.find((member) => (manifest.projectDirectory === destination.projectDirectory && member.teammateId === attachment.id) || (attachment.file && canonicalFile(member.sessionFile) === attachment.file));
243
+ const lease = readTeamLeaseState(manifest.id);
244
+ if (member && managing && manifest.originMainSessionId !== destination.originMainSessionId) throw new Error(`Session ${attachment.id} at ${attachment.file ?? member.sessionFile} is registered outside your management scope. Ask main to handle this session.`);
245
+ if (member) throw new Error(`Session ${attachment.id} at ${attachment.file ?? member.sessionFile} is ${member.importPending ? "reserved (import pending)" : "listed"} in team ${manifest.id}, main ${lease.mainSessionId ?? manifest.originMainSessionId}, project ${manifest.projectDirectory}${member.showOnHerdrPane && member.live ? "; may still be live in its Herdr pane" : ""}. Use team_resume for registered teammates; attachment does not transfer them.`);
246
+ }
247
+ const mainLease = liveLeases.find((lease) => lease.mainSessionId === attachment.id);
248
+ if (mainLease && managing) throw new Error(`Session ${attachment.id} at ${attachment.file ?? destination.projectDirectory} is live outside your management scope. Ask main to handle this session.`);
249
+ if (mainLease) throw new Error(`Session ${attachment.id} at ${attachment.file ?? destination.projectDirectory} is live as main of team ${mainLease.teamId} (lease in ${directory}).`);
250
+ if (attachment.previousTeam) throw new Error(`Session ${attachment.id} at ${attachment.file} was previously a teammate in ${attachment.previousTeam}. This first version only attaches never-teamed sessions.`);
251
+ }
252
+ writeTeamManifest(destination);
253
+ } finally {
254
+ fs.rmdirSync(lock);
255
+ }
256
+ }
257
+
203
258
  export function readTeamLeaseState(teamId: string): { state: "unclaimed" | "claimed" | "stale"; mainSessionId?: string } {
204
259
  let lease: TeamLease;
205
260
  try {
package/teammate-facts.ts CHANGED
@@ -27,7 +27,7 @@ export interface FactRow extends TeammateView {
27
27
  }
28
28
 
29
29
  export type FactKey = "name" | "status" | "model" | "context" | "fork" | "manager" | "thinking" | "herdr";
30
- type Form = "full" | "short" | "bare" | "icon";
30
+ export type Form = "full" | "short" | "bare" | "icon";
31
31
  type FormOrHidden = Form | "hidden";
32
32
 
33
33
  interface Paint {
@@ -151,9 +151,9 @@ function cell(key: FactKey, form: FormOrHidden, row: FactRow, paint: Paint): str
151
151
  return ladder[shown]!(row, paint);
152
152
  }
153
153
 
154
- /** One fact in its icon form, for views that list teammates inline. Empty when the row lacks the fact. */
155
- export function inlineFact(theme: FactTheme, key: FactKey, row: FactRow): string {
156
- return cell(key, "icon", row, { theme, roster: [], nameWidth: 0 });
154
+ /** One fact, in its icon form unless another is given, for views that list teammates inline. Empty when the row lacks the fact. */
155
+ export function inlineFact(theme: FactTheme, key: FactKey, row: FactRow, form: Form = "icon"): string {
156
+ return cell(key, form, row, { theme, roster: [], nameWidth: 0 });
157
157
  }
158
158
 
159
159
  /** The cells of every row at one state, padded into aligned columns. Empty columns drop out. */
package/teammate.ts CHANGED
@@ -4,7 +4,8 @@ export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhi
4
4
  export interface Teammate {
5
5
  name: string;
6
6
  systemPrompt: string;
7
- model: string;
7
+ model?: string;
8
+ session?: string;
8
9
  thinking?: ThinkingLevel;
9
10
  forkContext?: boolean;
10
11
  canManageOwnTeams?: boolean;
@@ -15,8 +16,9 @@ export interface Teammate {
15
16
  /** Settings main can change for an existing teammate. Its instructions and fork choice only matter at creation. */
16
17
  export type TeammateUpdate = { teammate: string } & Partial<Pick<Teammate, "model" | "thinking" | "extensionPaths">>;
17
18
 
18
- export type TeammateRecord = Required<Omit<Teammate, "extensionPaths">> & {
19
+ export type TeammateRecord = Required<Omit<Teammate, "extensionPaths" | "session">> & {
19
20
  extensionPaths?: string[];
21
+ session?: string;
20
22
  teammateId: string;
21
23
  sessionFile: string;
22
24
  live: boolean;