@giladbarnea/pi-simple-team 2.0.25 → 2.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -38,7 +38,7 @@ Not scheduling a meeting.
38
38
 
39
39
  ## Install
40
40
 
41
- Requires Pi 1.1.0 or newer.
41
+ Requires Pi 1.4.0 or newer.
42
42
 
43
43
  ```sh
44
44
  pi install npm:@giladbarnea/pi-simple-team
@@ -173,6 +173,10 @@ You can even `/resume` a teammate session directly if you ever want a cozy one-o
173
173
 
174
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
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
+
176
180
  ## 🪾 It’s teams all the way down (optionally)
177
181
 
178
182
  Tell main you want to **have a teammate manage its own team(s).**
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
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;
@@ -182,22 +190,12 @@ function decodeTeamListCursor(cursor: string): TeamListCursor {
182
190
  return decoded as TeamListCursor;
183
191
  }
184
192
 
185
- interface Reminder {
186
- sessionId: string;
187
- id: string;
188
- slug: string;
189
- message: string;
193
+ interface Reminder extends Omit<ReminderRecord, "armedAt" | "wakeAt"> {
190
194
  armedAt: Date;
191
195
  wakeAt: Date;
192
196
  timer?: ReturnType<typeof setTimeout>;
193
- state: "pending" | "delivered" | "cancelled";
194
197
  }
195
198
 
196
- /** A reminder as its session records it. A reminder's latest record holds its current state. */
197
- type ReminderRecord = Omit<Reminder, "armedAt" | "wakeAt" | "timer"> & { armedAt: string; wakeAt: string };
198
-
199
- const reminderType = "pi-simple-team-reminder";
200
-
201
199
  const reminderSlugWords = {
202
200
  adjectives: ["amber", "brisk", "calm", "clever", "dusty", "eager", "fuzzy", "gentle", "golden", "hollow", "jolly", "lively", "mellow", "misty", "nimble", "plucky", "quiet", "rapid", "rusty", "silver", "steady", "sunny", "swift", "witty"],
203
201
  nouns: ["badger", "beacon", "cedar", "comet", "falcon", "fern", "harbor", "heron", "lantern", "maple", "meadow", "otter", "pebble", "pine", "quail", "raven", "river", "robin", "sparrow", "spruce", "thistle", "tulip", "walrus", "willow"],
@@ -265,6 +263,7 @@ function teammateRecord(teammate: TeammateState): TeammateRecord {
265
263
  showOnHerdrPane: teammate.transport === "herdr",
266
264
  contextPercent: teammate.contextPercent,
267
265
  sessionFile: teammate.sessionFile!,
266
+ ...(teammate.session ? { session: teammate.session } : {}),
268
267
  ...(teammate.extensionPaths.length > 0 ? { extensionPaths: teammate.extensionPaths } : {}),
269
268
  };
270
269
  }
@@ -519,14 +518,18 @@ function recordQuit(team: TeamState, teammate: TeammateState, signal: unknown):
519
518
 
520
519
  async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[]; settings?: ReadonlyMap<string, TeammateUpdate> }): Promise<void> {
521
520
  const outcomes = await Promise.allSettled(teammates.map((teammate) => {
522
- const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
521
+ const initialize = !resumption || resumption.emptyRestarts.includes(teammate) || teammate.needsBriefing;
523
522
  const message = [
524
523
  initialize && composeTeamBriefing(team.name, team.teamPrompt, teammate.name, teammate.prompt, [...team.members.keys()], teammate.canManageOwnTeams),
525
524
  resumption && composeResumptionMessage(team.name, teammate.name, teammate.lastModelActivityAt, resumption.instructions),
526
525
  resumption?.settings?.has(teammate.name) && composeSettingsMessage(describeSettings(resumption.settings.get(teammate.name)!), []),
527
526
  ].filter(Boolean).join("\n\n");
528
- 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
+ });
529
531
  }));
532
+ persistActiveTeamManifest(team);
530
533
  const completed = teammates.filter((_teammate, index) => outcomes[index].status === "fulfilled").map((teammate) => teammate.name);
531
534
  const errors = outcomes.flatMap((outcome, index) => {
532
535
  if (outcome.status === "fulfilled") return [];
@@ -660,7 +663,7 @@ function validateExtensionPaths(extensionPaths: readonly string[]): void {
660
663
  }
661
664
  }
662
665
 
663
- function createTeammateState(teammateSpec: Teammate): TeammateState {
666
+ function createTeammateState(teammateSpec: Teammate, attachment?: ReturnType<typeof resolveSessionAttachment>, projectDirectory?: string): TeammateState {
664
667
  const teammateName = compactName(teammateSpec.name);
665
668
  const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
666
669
  const extensionPaths = teammateSpec.extensionPaths ?? [];
@@ -675,13 +678,19 @@ function createTeammateState(teammateSpec: Teammate): TeammateState {
675
678
  return {
676
679
  name: teammateName,
677
680
  prompt: teammateSpec.systemPrompt,
678
- model: teammateSpec.model,
681
+ model: teammateSpec.model ?? "",
679
682
  thinking,
680
683
  forkContext: Boolean(teammateSpec.forkContext),
681
684
  canManageOwnTeams: Boolean(teammateSpec.canManageOwnTeams),
682
685
  extensionPaths,
683
686
  transport: teammateSpec.showOnHerdrPane ? "herdr" : "rpc",
684
- 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
+ } : {}),
685
694
  ready,
686
695
  resolveReady,
687
696
  rejectReady,
@@ -728,6 +737,7 @@ function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
728
737
 
729
738
  interface ChildStartOptions {
730
739
  sessionFile?: string;
740
+ restoreSettings?: boolean;
731
741
  restartEmpty?: boolean;
732
742
  signal?: AbortSignal;
733
743
  /** New settings, recorded once the previous process has ended and before the next one starts. */
@@ -739,20 +749,27 @@ interface ChildStartOptions {
739
749
  * @example launchSettingArguments({ model: "openai-codex/gpt-6-luna", thinking: "xhigh" }, { sessionFile: "/sessions/a.jsonl" }) // ["--thinking", "xhigh"]
740
750
  */
741
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
+ ];
742
756
  const thinkingArguments = ["--thinking", teammate.thinking];
743
757
  return options.sessionFile ? thinkingArguments : ["--model", teammate.model, ...thinkingArguments];
744
758
  }
745
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
+
746
768
  function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[], options: ChildStartOptions): void {
747
- const sessionArgs = options.sessionFile
748
- ? ["--session", options.sessionFile]
749
- : teammate.forkContext && !options.restartEmpty
750
- ? ["--fork", team.mainSessionFile!]
751
- : [];
752
769
  const args = [
753
770
  "--mode",
754
771
  "rpc",
755
- ...sessionArgs,
772
+ ...launchSessionArguments(team, teammate, options),
756
773
  "-e",
757
774
  teamLiteExtensionPath,
758
775
  ...teammate.extensionPaths.flatMap(extensionPath => ["-e", extensionPath]),
@@ -838,7 +855,7 @@ function restartWithSettings(team: TeamState, teammate: TeammateState, update: T
838
855
  });
839
856
  teammate.deliveryQueue = restart.then(() => undefined, () => undefined);
840
857
  return restart.then(async ({ sessionFile, stoppedTeams }) => {
841
- if (sessionFile === undefined) await kickoffTeammates(team, [teammate], true);
858
+ if (sessionFile === undefined || teammate.needsBriefing) await kickoffTeammates(team, [teammate], true);
842
859
  await queueDelivery(team, "main", teammate, composeSettingsMessage(describeSettings(update), stoppedTeams), false, false);
843
860
  });
844
861
  }
@@ -911,11 +928,6 @@ async function attachHerdrTeammate(
911
928
  options: ChildStartOptions,
912
929
  ): Promise<void> {
913
930
  const environment = childEnvironmentOverrides(team, teammate, participants);
914
- const sessionArgs = options.sessionFile
915
- ? ["--session", options.sessionFile]
916
- : teammate.forkContext && !options.restartEmpty
917
- ? ["--fork", team.mainSessionFile!]
918
- : [];
919
931
  const args = ["pane", "split", "--pane", herdrParentPaneId, "--direction", "right", "--no-focus", "--cwd", team.projectDirectory ?? process.cwd()];
920
932
  for (const [name, value] of Object.entries(environment)) {
921
933
  if (value !== undefined) args.push("--env", `${name}=${value}`);
@@ -925,7 +937,7 @@ async function attachHerdrTeammate(
925
937
  await runCommand("herdr", ["pane", "rename", teammate.paneId, teammate.name]);
926
938
  const command = [
927
939
  ...team.parentPiCommand,
928
- ...sessionArgs,
940
+ ...launchSessionArguments(team, teammate, options),
929
941
  "-e",
930
942
  teamLiteExtensionPath,
931
943
  ...teammate.extensionPaths.flatMap(extensionPath => ["-e", extensionPath]),
@@ -984,14 +996,25 @@ function manifestMemberFromTeammate(teammate: TeammateState): TeamManifestMember
984
996
  return {
985
997
  ...teammateRecord(teammate),
986
998
  sessionMaterialized: teammate.sessionMaterialized,
999
+ ...(teammate.importPending ? { importPending: true } : {}),
1000
+ ...(teammate.needsBriefing ? { needsBriefing: true } : {}),
987
1001
  };
988
1002
  }
989
1003
 
990
- /** 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. */
991
1005
  function registeredManifestMembers(team: TeamState): TeamManifestMember[] {
992
1006
  return [...team.members.values()].filter((teammate) => teammate.sessionId).map(manifestMemberFromTeammate);
993
1007
  }
994
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
+
995
1018
  function persistActiveTeamManifest(team: TeamState): void {
996
1019
  if (!team.manifest || !teams.has(team.id ?? team.name)) return;
997
1020
  const updatedAt = new Date().toISOString();
@@ -1051,7 +1074,7 @@ function interruptedTeammates(team: TeamState): TeamManifest["interrupted"] {
1051
1074
  return { mainSessionId: team.lease.mainSessionId, teammates: running.map((teammate) => teammate.name), working: running.filter((teammate) => teammateSummary(teammate).active).map((teammate) => teammate.name) };
1052
1075
  }
1053
1076
 
1054
- async function shutdownTeam(team: TeamState, interrupted?: TeamManifest["interrupted"]): Promise<string[]> {
1077
+ async function shutdownTeam(team: TeamState, interrupted?: TeamManifest["interrupted"], discardNewAttachment = false): Promise<string[]> {
1055
1078
  team.stopping = true;
1056
1079
  const errors: string[] = [];
1057
1080
  for (const teammate of team.members.values()) {
@@ -1066,6 +1089,18 @@ async function shutdownTeam(team: TeamState, interrupted?: TeamManifest["interru
1066
1089
  }
1067
1090
  await stopRpcTeammate(teammate);
1068
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
+ }
1069
1104
  if (team.manifest) {
1070
1105
  try {
1071
1106
  const shutdownAt = new Date().toISOString();
@@ -1261,6 +1296,11 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
1261
1296
  teammate.rejectReady?.(failure);
1262
1297
  throw failure;
1263
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
+ }
1264
1304
  teammate.sessionId = sessionId;
1265
1305
  teammate.sessionFile = sessionFile;
1266
1306
  teammate.lastModelActivityAt = args.lastModelActivityAt as string | undefined;
@@ -1343,13 +1383,14 @@ function teammateSchema(modelGuidance: string) {
1343
1383
  return Type.Object({
1344
1384
  name: Type.String({ description: "Teammate name" }),
1345
1385
  systemPrompt: Type.String({ description: "Individual teammate instructions, delivered in the custom startup briefing" }),
1346
- model: Type.String({ description: `Canonical provider/model id for this teammate. ${modelGuidance}` }),
1347
- 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." })),
1348
1389
  forkContext: Type.Optional(Type.Boolean({ description: "Start as a fork of your context window rather than fresh. Defaults to false.", default: false })),
1349
1390
  canManageOwnTeams: Type.Optional(Type.Boolean({ description: "Allow this teammate to create and manage teams of its own. Defaults to false.", default: false })),
1350
1391
  showOnHerdrPane: Type.Optional(Type.Boolean({ description: "Open a visible Herdr pane for this teammate. Defaults to false.", default: false })),
1351
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." })),
1352
- }, { additionalProperties: false });
1393
+ }, { additionalProperties: false, anyOf: [{ required: ["model"] }, { required: ["session"] }] });
1353
1394
  }
1354
1395
 
1355
1396
  function teammateUpdateSchema() {
@@ -1361,6 +1402,13 @@ function teammateUpdateSchema() {
1361
1402
  }, { additionalProperties: false });
1362
1403
  }
1363
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
+
1364
1412
  function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiCommand: string[], manifest: TeamManifest, lease: TeamLease): TeamState {
1365
1413
  const team: TeamState = {
1366
1414
  owner,
@@ -1384,6 +1432,9 @@ function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiCommand:
1384
1432
  teammate.sessionId = member.teammateId;
1385
1433
  teammate.sessionFile = member.sessionFile;
1386
1434
  teammate.sessionMaterialized = member.sessionMaterialized;
1435
+ teammate.session = member.session;
1436
+ teammate.importPending = member.importPending;
1437
+ teammate.needsBriefing = member.needsBriefing;
1387
1438
  teammate.contextPercent = member.contextPercent;
1388
1439
  teammate.alive = false;
1389
1440
  team.members.set(teammate.name, teammate);
@@ -1470,6 +1521,17 @@ export default function (pi: ExtensionAPI) {
1470
1521
  );
1471
1522
  }
1472
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
+
1473
1535
  /** Stored dormant teammates of resumable current-project teams whose name or session ID is `identifier`. */
1474
1536
  function dormantTeammateMatches(context: ExtensionContext, identifier: string): DormantTeammateMatch[] {
1475
1537
  const name = identifier.trim();
@@ -1521,8 +1583,9 @@ export default function (pi: ExtensionAPI) {
1521
1583
  team.statuses.set(name, status("idle", interrupted.working.includes(name) ? "Reattached; was working when main stopped" : "Reattached"));
1522
1584
  }
1523
1585
  persistActiveTeamManifest(team);
1524
- // A teammate whose conversation was never saved restarts empty, so it gets its briefing back, staged without a turn.
1525
- await kickoffTeammates(team, emptyRestarts, true, { emptyRestarts });
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 });
1526
1589
  return { ...reattachment, reattached: interrupted.teammates, working: interrupted.working };
1527
1590
  } catch (error) {
1528
1591
  if (team) await shutdownTeam(team);
@@ -1541,6 +1604,11 @@ export default function (pi: ExtensionAPI) {
1541
1604
  const lease = manifest.state === "active" ? readTeamLeaseState(manifest.id) : undefined;
1542
1605
  const crashed = lease?.state === "stale" && lease.mainSessionId === mainSessionId;
1543
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
+ }
1544
1612
  const running = manifest.members.filter((member) => member.live);
1545
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.
1546
1614
  const [inPanes, reattachable] = [running.filter((member) => member.showOnHerdrPane), running.filter((member) => !member.showOnHerdrPane)];
@@ -1560,9 +1628,7 @@ export default function (pi: ExtensionAPI) {
1560
1628
  reminders.clear();
1561
1629
  const sessionId = context.sessionManager?.getSessionId?.();
1562
1630
  // A forked session copies its origin's records, which stay that session's reminders.
1563
- const records = new Map((context.sessionManager?.getEntries?.() ?? [])
1564
- .flatMap((entry) => entry.type === "custom" && entry.customType === reminderType && (entry.data as ReminderRecord).sessionId === sessionId ? [entry.data as ReminderRecord] : [])
1565
- .map((record) => [record.id, record]));
1631
+ const records = latestReminderRecords(context.sessionManager?.getEntries?.() ?? [], sessionId);
1566
1632
  reminderCount = records.size;
1567
1633
  for (const record of records.values()) {
1568
1634
  const reminder: Reminder = { ...record, armedAt: new Date(record.armedAt), wakeAt: new Date(record.wakeAt) };
@@ -1596,18 +1662,19 @@ export default function (pi: ExtensionAPI) {
1596
1662
  const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
1597
1663
  const teammateSpecs: Teammate[] = params.teammates.map((teammate) => ({ ...teammate, showOnHerdrPane: params.showOnHerdrPanes ?? teammate.showOnHerdrPane ?? false }));
1598
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!);
1599
1668
  const teammateNames = teammateSpecs.map((teammate) => compactName(teammate.name));
1600
1669
  const duplicateNames = teammateNames.filter((name, index) => teammateNames.indexOf(name) !== index);
1601
1670
  if (duplicateNames.length > 0) throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
1602
1671
  if (teammateNames.includes("main")) throw new Error('"main" is reserved');
1603
1672
 
1604
- validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
1673
+ validateTeammateModels(teammateSpecs.filter((spec) => spec.model !== undefined) as Array<Teammate & { model: string }>, context.modelRegistry.getAvailable());
1605
1674
  const forksContext = teammateSpecs.some((teammate) => Boolean(teammate.forkContext));
1606
1675
  const mainSessionFile = forksContext ? context.sessionManager.getSessionFile() : undefined;
1607
1676
  if (forksContext && !mainSessionFile) throw new Error("forkContext requires a saved main session. Use a saved main session or retry with forkContext: false.");
1608
1677
  const originMainSessionId = context.sessionManager?.getSessionId?.();
1609
- const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1610
- const projectDirectory = rawProjectDirectory ? canonicalProjectDirectory(rawProjectDirectory) : undefined;
1611
1678
  const teamId = originMainSessionId && projectDirectory ? `${originMainSessionId}-${teamName}` : undefined;
1612
1679
  const runtimeTeamId = teamId ?? teamName;
1613
1680
  if (teams.has(runtimeTeamId)) throw new Error(`Team already exists: ${runtimeTeamId}`);
@@ -1650,39 +1717,38 @@ export default function (pi: ExtensionAPI) {
1650
1717
 
1651
1718
  teams.set(runtimeTeamId, team);
1652
1719
  try {
1653
- for (const teammateSpec of teammateSpecs) {
1654
- const teammate = createTeammateState(teammateSpec);
1720
+ for (const [index, spec] of teammateSpecs.entries()) {
1721
+ const teammate = createTeammateState(spec, attachments[index], projectDirectory);
1655
1722
  team.members.set(teammate.name, teammate);
1656
1723
  team.statuses.set(teammate.name, status("idle", "Spawned"));
1657
- 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
+ });
1658
1737
  }
1659
1738
  signal?.throwIfAborted();
1660
1739
 
1661
1740
  if (teamId && originMainSessionId && projectDirectory) {
1662
- const timestamp = new Date().toISOString();
1663
- const manifest: TeamManifest = {
1664
- version: 2,
1665
- id: teamId,
1666
- name: team.name,
1667
- originMainSessionId,
1668
- projectDirectory,
1669
- teamPrompt: team.teamPrompt,
1670
- showOnHerdrPanes: team.showOnHerdrPanes,
1671
- members: [...team.members.values()].map(manifestMemberFromTeammate),
1672
- state: "active",
1673
- createdAt: timestamp,
1674
- updatedAt: timestamp,
1675
- };
1741
+ const manifest = createTeamManifest(team);
1676
1742
  writeTeamManifest(manifest);
1677
1743
  team.manifest = manifest;
1678
1744
  }
1679
1745
  } catch (error) {
1680
- await shutdownTeam(team);
1746
+ await shutdownTeam(team, undefined, true);
1681
1747
  closeCallbackServerIfUnused();
1682
1748
  throw error;
1683
1749
  }
1684
1750
  await kickoffTeammates(team, [...team.members.values()], Boolean(params.startIdle));
1685
- return toolResult(lifecycleResult(team));
1751
+ return toolResult({ ...lifecycleResult(team), teammates: [...team.members.values()].map((teammate) => ({ ...teammateRecord(teammate), ...(teammate.session ? { contextRestored: teammate.contextRestored } : {}) })) });
1686
1752
  },
1687
1753
  }),
1688
1754
  );
@@ -1837,7 +1903,6 @@ export default function (pi: ExtensionAPI) {
1837
1903
  renderResult: (result, options, theme, context) => renderTeamToolResult("team_resume", result, options, theme, context, undefined, sessionTeammateRoster),
1838
1904
  parameters: Type.Object({
1839
1905
  team: Type.String({ description: "Team name or persistent ID" }),
1840
- // 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.
1841
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." })),
1842
1907
  showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false, description: "Open visible Herdr panes for selected teammates. Defaults to false." })),
1843
1908
  startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start resumed teammates idle." })),
@@ -1848,6 +1913,8 @@ export default function (pi: ExtensionAPI) {
1848
1913
  signal?.throwIfAborted();
1849
1914
  const manifest = resolveTeamIdentifier(resumableTeamManifests(context, "team_resume"), params.team);
1850
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);
1851
1918
  const members = manifest.members;
1852
1919
  const requestedNames = resolveTeammates(members, params.teammates ?? members.map((member) => member.teammateId)).map((member) => member.name);
1853
1920
  const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
@@ -1950,8 +2017,7 @@ export default function (pi: ExtensionAPI) {
1950
2017
  renderResult: (result, options, theme, context) => renderTeamToolResult("team_add_teammates", result, options, theme, context, getMarkdownTheme(), sessionTeammateRoster),
1951
2018
  parameters: Type.Object({
1952
2019
  team: Type.Optional(Type.String({ description: "Team name or persistent ID. Omit when exactly one owned active team exists." })),
1953
- // TODO: Accept existing current-project Pi session IDs as well as new teammate definitions.
1954
- 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." }),
1955
2021
  startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start added teammates idle." })),
1956
2022
  }, { additionalProperties: false }),
1957
2023
  async execute(_toolCallId, params, signal, _onUpdate, context) {
@@ -1974,14 +2040,20 @@ export default function (pi: ExtensionAPI) {
1974
2040
  throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
1975
2041
  }
1976
2042
  if (teammateNames.includes("main")) throw new Error('"main" is reserved');
1977
- validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
2043
+ validateTeammateModels(teammateSpecs.filter((spec) => spec.model !== undefined) as Array<Teammate & { model: string }>, context.modelRegistry.getAvailable());
1978
2044
 
1979
2045
  const forksContext = teammateSpecs.some((teammate) => Boolean(teammate.forkContext));
1980
2046
  const mainSessionFile = forksContext ? context.sessionManager.getSessionFile() : undefined;
1981
2047
  if (forksContext && !mainSessionFile) throw new Error("forkContext requires a saved main session. Use a saved main session or retry with forkContext: false.");
1982
2048
  if (mainSessionFile) team.mainSessionFile = mainSessionFile;
1983
2049
 
1984
- 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
+ }
1985
2057
  for (const teammate of addedTeammates) {
1986
2058
  team.members.set(teammate.name, teammate);
1987
2059
  team.statuses.set(teammate.name, status("idle", "Spawned"));
@@ -1990,7 +2062,10 @@ export default function (pi: ExtensionAPI) {
1990
2062
  sessionTeammateRoster.push(...teammateNames.filter((name) => !sessionTeammateRoster.includes(name)));
1991
2063
 
1992
2064
  try {
1993
- 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
+ });
1994
2069
  signal?.throwIfAborted();
1995
2070
  persistActiveTeamManifest(team);
1996
2071
  } catch (error) {
@@ -1999,6 +2074,11 @@ export default function (pi: ExtensionAPI) {
1999
2074
  else await stopRpcTeammate(teammate);
2000
2075
  }
2001
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;
2002
2082
  team.members.delete(teammate.name);
2003
2083
  team.statuses.delete(teammate.name);
2004
2084
  }
@@ -2009,7 +2089,7 @@ export default function (pi: ExtensionAPI) {
2009
2089
  await kickoffTeammates(team, addedTeammates, Boolean(params.startIdle));
2010
2090
  return toolResult({
2011
2091
  ...lifecycleResult(team),
2012
- 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 } : {}) })),
2013
2093
  status: formatStatus(team),
2014
2094
  }, { addedTeammates: addedTeammates.map(teammateRecord) });
2015
2095
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "2.0.25",
3
+ "version": "2.0.27",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -46,7 +46,7 @@
46
46
  ],
47
47
  "peerDependencies": {
48
48
  "@earendil-works/pi-ai": "*",
49
- "@earendil-works/pi-coding-agent": ">=1.1.0",
49
+ "@earendil-works/pi-coding-agent": ">=1.4.0",
50
50
  "@earendil-works/pi-tui": "*",
51
51
  "typebox": "*"
52
52
  },
@@ -63,9 +63,9 @@
63
63
  "image": "https://raw.githubusercontent.com/giladbarnea/pi-simple-team/main/screenshots/abstract-tool-output-preview-640.png"
64
64
  },
65
65
  "devDependencies": {
66
- "@earendil-works/pi-ai": "1.1.0",
67
- "@earendil-works/pi-coding-agent": "1.1.0",
68
- "@earendil-works/pi-tui": "1.1.0",
66
+ "@earendil-works/pi-ai": "1.5.2",
67
+ "@earendil-works/pi-coding-agent": "1.5.2",
68
+ "@earendil-works/pi-tui": "1.5.2",
69
69
  "typebox": "1.3.27"
70
70
  }
71
71
  }
@@ -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/resume-message.ts CHANGED
@@ -64,6 +64,6 @@ export function composeReattachmentMessage(reattachments: readonly Reattachment[
64
64
  ].join("\n"),
65
65
  working && `These were working when your session stopped: ${working}. Message each one to continue.`,
66
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} Use team_resume to restart it.`),
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
68
  ].filter(Boolean).join("\n\n");
69
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 {
@@ -79,6 +82,9 @@ function isManifestMember(value: unknown): value is TeamManifestMember {
79
82
  typeof member.teammateId === "string" &&
80
83
  typeof member.sessionFile === "string" &&
81
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") &&
82
88
  (member.contextPercent === undefined || typeof member.contextPercent === "number") &&
83
89
  (member.extensionPaths === undefined || (Array.isArray(member.extensionPaths) && member.extensionPaths.every((value) => typeof value === "string" && path.isAbsolute(value))))
84
90
  );
@@ -157,6 +163,11 @@ export function writeTeamManifest(manifest: TeamManifest): void {
157
163
  fs.renameSync(temporaryPath, filePath);
158
164
  }
159
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
+
160
171
  /** Whether a saved attachment file holds this team ID, readable or not. */
161
172
  export function teamManifestExists(teamId: string): boolean {
162
173
  return fs.existsSync(manifestPath(teamId));
@@ -198,7 +209,7 @@ export function listTeamManifests(projectDirectory: string): { manifests: TeamMa
198
209
  if ((claimedProjectDirectory(filePath) ?? resolvedProjectDirectory) === resolvedProjectDirectory) unreadable.push({ filePath, error: error instanceof Error ? error.message : String(error) });
199
210
  continue;
200
211
  }
201
- 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 ?? "")) {
202
213
  fs.rmSync(leasePath(manifest.id), { force: true });
203
214
  fs.rmSync(filePath);
204
215
  continue;
@@ -208,6 +219,42 @@ export function listTeamManifests(projectDirectory: string): { manifests: TeamMa
208
219
  return { manifests: manifests.sort((left, right) => left.id.localeCompare(right.id)), unreadable };
209
220
  }
210
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
+
211
258
  export function readTeamLeaseState(teamId: string): { state: "unclaimed" | "claimed" | "stale"; mainSessionId?: string } {
212
259
  let lease: TeamLease;
213
260
  try {
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;