@giladbarnea/pi-simple-team 1.0.21 → 1.0.23

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/index.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import * as childProcess from "node:child_process";
2
2
  import type { ChildProcess } from "node:child_process";
3
3
  import crypto from "node:crypto";
4
+ import * as fs from "node:fs";
4
5
  import http from "node:http";
6
+ import * as path from "node:path";
5
7
  import { StringDecoder } from "node:string_decoder";
6
8
  import { fileURLToPath } from "node:url";
7
9
  import { defineTool, type ContextUsage, type ExtensionAPI, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
@@ -10,8 +12,21 @@ import { formatContextWindowReport, requireKnownContextUsage, type KnownContextU
10
12
  import { formatScopedModelGuidance, validateTeammateModels, type ModelReference } from "./model-preflight.ts";
11
13
  import { composeSystemPrompt } from "./system-prompt.ts";
12
14
  import { readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
15
+ import {
16
+ canonicalProjectDirectory,
17
+ claimTeamLease,
18
+ dormantManifestRetentionMilliseconds,
19
+ listTeamManifests,
20
+ readTeamLeaseState,
21
+ releaseTeamLease,
22
+ writeTeamManifest,
23
+ type TeamLease,
24
+ type TeamManifest,
25
+ type TeamManifestMember,
26
+ } from "./team-registry.ts";
13
27
  import { appendTeamLog, filterTeamLog, normalizeChildEvent, nowText, pageTeamLog, preview, renderTeamLogPage, type TeamLogEntry } from "./teamlog.ts";
14
28
  import { renderTeamMessage, renderTeamToolCall, renderTeamToolResult, type TeamMessageDetails } from "./render.ts";
29
+ import { openTeamOverview, type TeamSnapshot } from "./team-ui.ts";
15
30
  import { StringEnum } from "@earendil-works/pi-ai";
16
31
  import { Type } from "typebox";
17
32
 
@@ -57,6 +72,9 @@ interface TeammateState {
57
72
  thinking: ThinkingLevel;
58
73
  inheritContext: boolean;
59
74
  transport: TeammateTransport;
75
+ sessionId?: string;
76
+ sessionFile?: string;
77
+ sessionMaterialized: boolean;
60
78
  process?: ChildProcess;
61
79
  paneId?: string;
62
80
  visibleUrl?: string;
@@ -74,13 +92,17 @@ interface TeammateState {
74
92
  interface TeamState {
75
93
  owner: symbol;
76
94
  ownerPi: ExtensionAPI;
95
+ id?: string;
77
96
  name: string;
97
+ projectDirectory?: string;
78
98
  showOnHerdrPanes: boolean;
79
99
  teamPrompt: string;
80
100
  mainSessionFile?: string;
81
101
  members: Map<string, TeammateState>;
82
102
  statuses: Map<string, TeamStatus>;
83
103
  created: string;
104
+ manifest?: TeamManifest;
105
+ lease?: TeamLease;
84
106
  log: TeamLogEntry[];
85
107
  nextLogSequence: number;
86
108
  }
@@ -366,7 +388,7 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
366
388
  direction: from === "main" ? "main->teammate" : "teammate->teammate",
367
389
  kind: "send",
368
390
  summary: preview(message),
369
- details: { from, to: recipient.name, interrupt },
391
+ details: { from, to: recipient.name, interrupt, message },
370
392
  });
371
393
 
372
394
  recipient.deliveryQueue = recipient.deliveryQueue
@@ -386,17 +408,18 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
386
408
  });
387
409
  }
388
410
 
389
- function resolveTeam(owner: symbol, teamName?: string): TeamState {
411
+ function resolveTeam(owner: symbol, teamIdentifier?: string): TeamState {
390
412
  const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
391
- if (teamName) {
392
- const team = teams.get(teamName);
393
- if (!team || team.owner !== owner) throw new Error(`Unknown team: ${teamName}`);
394
- return team;
413
+ if (teamIdentifier) {
414
+ const matches = ownedTeams.filter((team) => team.id === teamIdentifier || team.name === teamIdentifier);
415
+ if (matches.length === 0) throw new Error(`Unknown team: ${teamIdentifier}`);
416
+ if (matches.length > 1) throw new Error(`Ambiguous team name: ${teamIdentifier}. Pass the persistent team ID.`);
417
+ return matches[0]!;
395
418
  }
396
419
 
397
420
  if (ownedTeams.length === 1) return ownedTeams[0];
398
421
  if (ownedTeams.length === 0) throw new Error("No teams exist. Use team_spawn first.");
399
- throw new Error(`Multiple teams exist: ${ownedTeams.map((team) => team.name).join(", ")}. Pass team explicitly.`);
422
+ throw new Error(`Multiple teams exist: ${ownedTeams.map((team) => team.id ?? team.name).join(", ")}. Pass team explicitly.`);
400
423
  }
401
424
 
402
425
  function resolveCallbackTeam(teamName: string): TeamState {
@@ -455,6 +478,19 @@ function allStatuses(owner: symbol): Record<string, Record<string, TeamStatus>>
455
478
  return Object.fromEntries([...teams.values()].filter((team) => team.owner === owner).map((team) => [team.name, formatStatus(team)]));
456
479
  }
457
480
 
481
+ function ownedTeamSnapshots(owner: symbol): TeamSnapshot[] {
482
+ return [...teams.values()]
483
+ .filter((team) => team.owner === owner)
484
+ .map((team) => ({
485
+ name: team.name,
486
+ created: team.created,
487
+ showOnHerdrPanes: team.showOnHerdrPanes,
488
+ roster: [...team.members.keys()],
489
+ statuses: formatStatus(team),
490
+ log: [...team.log],
491
+ }));
492
+ }
493
+
458
494
  function updateStatus(team: TeamState, participant: string, word?: string, phrase?: string): void {
459
495
  if (word === undefined && phrase === undefined) return;
460
496
  const previous = team.statuses.get(participant) ?? status("active", "Working");
@@ -493,6 +529,7 @@ function createTeammateState(team: TeamState, teammateSpec: TeammateSpec): Teamm
493
529
  thinking,
494
530
  inheritContext: Boolean(teammateSpec.inheritContext),
495
531
  transport: team.showOnHerdrPanes ? "herdr" : "rpc",
532
+ sessionMaterialized: false,
496
533
  visibleReady,
497
534
  resolveVisibleReady,
498
535
  rejectVisibleReady,
@@ -511,7 +548,8 @@ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, par
511
548
  PI_SIMPLE_TEAM_VISIBLE_CHILD: visible ? "1" : "0",
512
549
  PI_SIMPLE_TEAM_CALLBACK_URL: callbackUrl,
513
550
  PI_SIMPLE_TEAM_CALLBACK_TOKEN: callbackToken,
514
- PI_SIMPLE_TEAM_TEAM: team.name,
551
+ PI_SIMPLE_TEAM_TEAM: team.id ?? team.name,
552
+ PI_SIMPLE_TEAM_TEAM_NAME: team.name,
515
553
  PI_SIMPLE_TEAM_MEMBER: teammate.name,
516
554
  PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
517
555
  };
@@ -528,29 +566,39 @@ function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
528
566
  });
529
567
  }
530
568
 
531
- function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[]): void {
532
- const sessionArgs = teammate.inheritContext ? ["--fork", team.mainSessionFile!] : [];
569
+ interface RpcStartOptions {
570
+ sessionFile?: string;
571
+ restartEmpty?: boolean;
572
+ }
573
+
574
+ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[], options: RpcStartOptions): void {
575
+ const sessionArgs = options.sessionFile
576
+ ? ["--session", options.sessionFile]
577
+ : teammate.inheritContext && !options.restartEmpty
578
+ ? ["--fork", team.mainSessionFile!]
579
+ : [];
580
+ const modelArgs = options.sessionFile ? [] : ["--model", teammate.model, "--thinking", teammate.thinking];
533
581
  const args = [
534
582
  "--mode",
535
583
  "rpc",
536
584
  ...sessionArgs,
585
+ "--no-extensions",
537
586
  "-e",
538
587
  teamLiteExtensionPath,
539
588
  "--no-prompt-templates",
540
589
  "--no-themes",
541
- "--model",
542
- teammate.model,
543
- "--thinking",
544
- teammate.thinking,
590
+ ...modelArgs,
545
591
  "--system-prompt",
546
592
  composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants),
547
593
  ];
548
594
  const proc = childProcess.spawn("pi", args, {
549
- cwd: process.cwd(),
595
+ cwd: team.projectDirectory ?? process.cwd(),
550
596
  stdio: ["pipe", "pipe", "pipe"],
551
597
  env: { ...process.env, ...childEnvironmentOverrides(team, teammate, participants, false) },
552
598
  });
553
599
  teammate.process = proc;
600
+ teammate.alive = true;
601
+ teammate.busy = false;
554
602
 
555
603
  attachJsonlReader(proc.stdout!, (line) => {
556
604
  if (!line.trim()) return;
@@ -575,6 +623,18 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
575
623
  appendSpawnLog(team, teammate);
576
624
  }
577
625
 
626
+ async function captureRpcSessionIdentity(teammate: TeammateState): Promise<void> {
627
+ const response = await sendRpc(teammate, { type: "get_state" }, 10_000);
628
+ await requireSuccessfulResponse(response, `read session identity from ${teammate.name}`);
629
+ const state = response.data as { sessionId?: unknown; sessionFile?: unknown } | undefined;
630
+ if (typeof state?.sessionId !== "string" || typeof state.sessionFile !== "string" || !path.isAbsolute(state.sessionFile)) {
631
+ throw new Error(`Teammate ${teammate.name} reported an invalid session identity`);
632
+ }
633
+ teammate.sessionId = state.sessionId;
634
+ teammate.sessionFile = state.sessionFile;
635
+ teammate.sessionMaterialized = fs.existsSync(state.sessionFile);
636
+ }
637
+
578
638
  function parseHerdrPaneId(stdout: string, teammateName: string): string {
579
639
  const response = JSON.parse(stdout) as { result?: { agent?: { pane_id?: string } } };
580
640
  const paneId = response.result?.agent?.pane_id;
@@ -582,23 +642,33 @@ function parseHerdrPaneId(stdout: string, teammateName: string): string {
582
642
  return paneId;
583
643
  }
584
644
 
585
- async function attachVisibleTeammate(team: TeamState, teammate: TeammateState, participants: string[], herdrTabId: string): Promise<void> {
645
+ async function attachVisibleTeammate(
646
+ team: TeamState,
647
+ teammate: TeammateState,
648
+ participants: string[],
649
+ herdrTabId: string,
650
+ options: RpcStartOptions,
651
+ ): Promise<void> {
586
652
  const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants);
587
653
  const environment = childEnvironmentOverrides(team, teammate, participants, true);
588
- const args = ["agent", "start", teammate.name, "--tab", herdrTabId, "--split", "right", "--no-focus", "--cwd", process.cwd()];
654
+ const sessionArgs = options.sessionFile
655
+ ? ["--session", options.sessionFile]
656
+ : teammate.inheritContext && !options.restartEmpty
657
+ ? ["--fork", team.mainSessionFile!]
658
+ : [];
659
+ const modelArgs = options.sessionFile ? [] : ["--model", teammate.model, "--thinking", teammate.thinking];
660
+ const args = ["agent", "start", teammate.name, "--tab", herdrTabId, "--split", "right", "--no-focus", "--cwd", team.projectDirectory ?? process.cwd()];
589
661
  for (const [name, value] of Object.entries(environment)) {
590
662
  if (value !== undefined) args.push("--env", `${name}=${value}`);
591
663
  }
592
664
  args.push(
593
665
  "--",
594
666
  "pi",
595
- ...(teammate.inheritContext ? ["--fork", team.mainSessionFile!] : []),
667
+ ...sessionArgs,
668
+ "--no-extensions",
596
669
  "-e",
597
670
  teamLiteExtensionPath,
598
- "--model",
599
- teammate.model,
600
- "--thinking",
601
- teammate.thinking,
671
+ ...modelArgs,
602
672
  "--system-prompt",
603
673
  systemPrompt,
604
674
  );
@@ -622,12 +692,52 @@ async function attachVisibleTeammate(team: TeamState, teammate: TeammateState, p
622
692
  }
623
693
  }
624
694
 
625
- async function startTeammate(team: TeamState, teammate: TeammateState, participants: string[], herdrTabId?: string): Promise<void> {
695
+ async function startTeammate(
696
+ team: TeamState,
697
+ teammate: TeammateState,
698
+ participants: string[],
699
+ herdrTabId?: string,
700
+ rpcOptions: RpcStartOptions = {},
701
+ ): Promise<void> {
626
702
  if (teammate.transport === "herdr") {
627
- await attachVisibleTeammate(team, teammate, participants, herdrTabId!);
703
+ await attachVisibleTeammate(team, teammate, participants, herdrTabId!, rpcOptions);
628
704
  return;
629
705
  }
630
- attachRpcTeammate(team, teammate, participants);
706
+ attachRpcTeammate(team, teammate, participants, rpcOptions);
707
+ if (team.id) await captureRpcSessionIdentity(teammate);
708
+ }
709
+
710
+ function manifestMemberFromTeammate(teammate: TeammateState): TeamManifestMember {
711
+ if (!teammate.sessionId || !teammate.sessionFile) {
712
+ throw new Error(`Teammate ${teammate.name} has no reported session identity`);
713
+ }
714
+ if (fs.existsSync(teammate.sessionFile)) teammate.sessionMaterialized = true;
715
+ return {
716
+ name: teammate.name,
717
+ prompt: teammate.prompt,
718
+ model: teammate.model,
719
+ thinking: teammate.thinking,
720
+ inheritContext: teammate.inheritContext,
721
+ transport: teammate.transport,
722
+ live: teammate.alive,
723
+ sessionId: teammate.sessionId,
724
+ sessionFile: teammate.sessionFile,
725
+ sessionMaterialized: teammate.sessionMaterialized,
726
+ };
727
+ }
728
+
729
+ function persistActiveTeamManifest(team: TeamState): void {
730
+ if (!team.manifest) return;
731
+ const updatedAt = new Date().toISOString();
732
+ team.manifest = {
733
+ ...team.manifest,
734
+ members: [...team.members.values()].map(manifestMemberFromTeammate),
735
+ state: "active",
736
+ updatedAt,
737
+ shutdownAt: undefined,
738
+ expiresAt: undefined,
739
+ };
740
+ writeTeamManifest(team.manifest);
631
741
  }
632
742
 
633
743
  function isHerdrPaneNotFound(error: unknown): boolean {
@@ -644,11 +754,29 @@ async function closeVisiblePane(teammate: TeammateState): Promise<void> {
644
754
  teammate.paneId = undefined;
645
755
  }
646
756
 
757
+ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
758
+ const processToStop = teammate.process;
759
+ if (!processToStop || !teammate.alive) return;
760
+
761
+ await new Promise<void>((resolve) => {
762
+ let forceKillTimeout: ReturnType<typeof setTimeout> | undefined;
763
+ const resolveExit = (): void => {
764
+ if (forceKillTimeout) clearTimeout(forceKillTimeout);
765
+ resolve();
766
+ };
767
+ processToStop.once("exit", resolveExit);
768
+ processToStop.kill("SIGTERM");
769
+ forceKillTimeout = setTimeout(() => processToStop.kill("SIGKILL"), 1_000);
770
+ forceKillTimeout.unref();
771
+ });
772
+ teammate.process = undefined;
773
+ }
774
+
647
775
  async function shutdownTeam(team: TeamState): Promise<string[]> {
648
776
  const errors: string[] = [];
649
777
  for (const teammate of team.members.values()) {
650
- teammate.alive = false;
651
778
  if (teammate.transport === "herdr") {
779
+ teammate.alive = false;
652
780
  try {
653
781
  await closeVisiblePane(teammate);
654
782
  } catch (error) {
@@ -656,13 +784,33 @@ async function shutdownTeam(team: TeamState): Promise<string[]> {
656
784
  }
657
785
  continue;
658
786
  }
659
- if (!teammate.process) continue;
660
- teammate.process.kill("SIGTERM");
661
- setTimeout(() => {
662
- if (teammate.process?.exitCode === null) teammate.process.kill("SIGKILL");
663
- }, 1_000).unref();
787
+ await stopRpcTeammate(teammate);
788
+ }
789
+ if (team.manifest) {
790
+ try {
791
+ const shutdownAt = new Date().toISOString();
792
+ team.manifest = {
793
+ ...team.manifest,
794
+ members: [...team.members.values()].map(manifestMemberFromTeammate),
795
+ state: "dormant",
796
+ updatedAt: shutdownAt,
797
+ shutdownAt,
798
+ expiresAt: new Date(Date.parse(shutdownAt) + dormantManifestRetentionMilliseconds).toISOString(),
799
+ };
800
+ writeTeamManifest(team.manifest);
801
+ } catch (error) {
802
+ errors.push(error instanceof Error ? error.message : String(error));
803
+ }
804
+ }
805
+ if (team.lease) {
806
+ try {
807
+ releaseTeamLease(team.lease);
808
+ } catch (error) {
809
+ errors.push(error instanceof Error ? error.message : String(error));
810
+ }
811
+ team.lease = undefined;
664
812
  }
665
- teams.delete(team.name);
813
+ teams.delete(team.id ?? team.name);
666
814
  return errors;
667
815
  }
668
816
 
@@ -758,6 +906,11 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
758
906
  if (tool === "visible_register") {
759
907
  if (!teammate || teammate.transport !== "herdr") throw new Error(`Unknown visible teammate: ${from}`);
760
908
  const url = String(args.url ?? "");
909
+ const sessionId = args.sessionId;
910
+ const sessionFile = args.sessionFile;
911
+ if (typeof sessionId !== "string" || typeof sessionFile !== "string" || !path.isAbsolute(sessionFile)) {
912
+ throw new Error(`Visible teammate ${from} reported an invalid session identity`);
913
+ }
761
914
  try {
762
915
  teammate.visibleUrl = validateVisibleChildUrl(url, from);
763
916
  } catch (error) {
@@ -765,6 +918,9 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
765
918
  teammate.rejectVisibleReady?.(failure);
766
919
  throw failure;
767
920
  }
921
+ teammate.sessionId = sessionId;
922
+ teammate.sessionFile = sessionFile;
923
+ teammate.sessionMaterialized = fs.existsSync(sessionFile);
768
924
  teammate.alive = true;
769
925
  teammate.busy = false;
770
926
  team.statuses.set(teammate.name, status("idle", "Spawned"));
@@ -780,6 +936,17 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
780
936
  return;
781
937
  }
782
938
 
939
+ if (tool === "team_context") {
940
+ if (!teammate) throw new Error(`Unknown teammate: ${from}`);
941
+ writeJson(response, 200, {
942
+ team: team.name,
943
+ from,
944
+ participants: [...team.members.keys()],
945
+ status: formatStatus(team),
946
+ });
947
+ return;
948
+ }
949
+
783
950
  if (tool === "teamsend") {
784
951
  const recipients = resolveRecipients(team, (args.to ?? []) as string[]);
785
952
  const message = String(args.message ?? "");
@@ -792,7 +959,14 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
792
959
  if (tool === "teammain") {
793
960
  const rawMessage = String(args.message ?? "");
794
961
  const details: TeamMessageDetails = { team: team.name, from, sentAt: nowText(), message: rawMessage };
795
- appendTeamLog(team, { team: team.name, teammate: from, direction: "teammate->main", kind: "main_message", summary: preview(rawMessage) });
962
+ appendTeamLog(team, {
963
+ team: team.name,
964
+ teammate: from,
965
+ direction: "teammate->main",
966
+ kind: "main_message",
967
+ summary: preview(rawMessage),
968
+ details: { from, to: "main", message: rawMessage },
969
+ });
796
970
  team.ownerPi.sendMessage(
797
971
  { customType: teamMessageType, content: `[${team.name}/${from}] ${rawMessage}`, display: true, details },
798
972
  { deliverAs: "steer", triggerTurn: true },
@@ -826,6 +1000,60 @@ function teammateSchema(modelGuidance: string) {
826
1000
  });
827
1001
  }
828
1002
 
1003
+ function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, manifest: TeamManifest, lease: TeamLease): TeamState {
1004
+ const team: TeamState = {
1005
+ owner,
1006
+ ownerPi,
1007
+ id: manifest.id,
1008
+ name: manifest.name,
1009
+ projectDirectory: manifest.projectDirectory,
1010
+ showOnHerdrPanes: false,
1011
+ teamPrompt: manifest.teamPrompt,
1012
+ members: new Map(),
1013
+ statuses: new Map([["main", status("available", "Main agent")]]),
1014
+ created: manifest.createdAt,
1015
+ manifest,
1016
+ lease,
1017
+ log: [],
1018
+ nextLogSequence: 1,
1019
+ };
1020
+ for (const member of manifest.members) {
1021
+ const teammate = createTeammateState(team, {
1022
+ name: member.name,
1023
+ prompt: member.prompt,
1024
+ model: member.model,
1025
+ thinking: member.thinking as ThinkingLevel,
1026
+ inheritContext: member.inheritContext,
1027
+ });
1028
+ teammate.transport = "rpc";
1029
+ teammate.sessionId = member.sessionId;
1030
+ teammate.sessionFile = member.sessionFile;
1031
+ teammate.sessionMaterialized = member.sessionMaterialized;
1032
+ teammate.alive = false;
1033
+ team.members.set(teammate.name, teammate);
1034
+ team.statuses.set(teammate.name, status("stopped", "Dormant"));
1035
+ }
1036
+ return team;
1037
+ }
1038
+
1039
+ function prepareVisibleTeammate(teammate: TeammateState): void {
1040
+ teammate.transport = "herdr";
1041
+ teammate.visibleReady = new Promise<void>((resolve, reject) => {
1042
+ teammate.resolveVisibleReady = resolve;
1043
+ teammate.rejectVisibleReady = reject;
1044
+ });
1045
+ }
1046
+
1047
+ function sessionFileForResume(teammate: TeammateState): string | undefined {
1048
+ if (!teammate.sessionFile) throw new Error(`Teammate ${teammate.name} has no reported session file`);
1049
+ if (fs.existsSync(teammate.sessionFile)) return teammate.sessionFile;
1050
+ if (teammate.sessionMaterialized) {
1051
+ throw new Error(`Materialized session file for ${teammate.name} is missing: ${teammate.sessionFile}`);
1052
+ }
1053
+ // This empty restart becomes redundant when team creation wakes every teammate and guarantees session persistence.
1054
+ return undefined;
1055
+ }
1056
+
829
1057
  export default function (pi: ExtensionAPI) {
830
1058
  const childRuntimeConfig = readChildRuntimeConfig();
831
1059
  if (childRuntimeConfig) {
@@ -837,6 +1065,13 @@ export default function (pi: ExtensionAPI) {
837
1065
  const sessionTeammateRoster: string[] = [];
838
1066
  pi.registerMessageRenderer(teamMessageType, (message, _options, theme) => renderTeamMessage(message, theme, getMarkdownTheme(), sessionTeammateRoster));
839
1067
 
1068
+ pi.registerCommand("team", {
1069
+ description: "Open a read-only team overview",
1070
+ handler: async (_args, context) => {
1071
+ await openTeamOverview(context, () => ownedTeamSnapshots(owner));
1072
+ },
1073
+ });
1074
+
840
1075
  pi.on("session_shutdown", async () => {
841
1076
  for (const team of [...teams.values()]) {
842
1077
  if (team.owner === owner) await shutdownTeam(team);
@@ -864,7 +1099,6 @@ export default function (pi: ExtensionAPI) {
864
1099
  }),
865
1100
  async execute(_toolCallId, params, _signal, _onUpdate, context) {
866
1101
  const teamName = compactName(params.team);
867
- if (teams.has(teamName)) throw new Error(`Team already exists: ${teamName}`);
868
1102
  const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
869
1103
  const herdrTabId = showOnHerdrPanes ? await validateHerdrAvailability() : undefined;
870
1104
 
@@ -878,24 +1112,43 @@ export default function (pi: ExtensionAPI) {
878
1112
  const inheritsMainContext = teammateSpecs.some((teammate) => Boolean(teammate.inheritContext));
879
1113
  const mainSessionFile = inheritsMainContext ? context.sessionManager.getSessionFile() : undefined;
880
1114
  if (inheritsMainContext && !mainSessionFile) throw new Error("inheritContext requires a persistent main session");
1115
+ const originMainSessionId = context.sessionManager?.getSessionId?.();
1116
+ const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1117
+ const projectDirectory = rawProjectDirectory ? canonicalProjectDirectory(rawProjectDirectory) : undefined;
1118
+ const teamId = originMainSessionId && projectDirectory ? `${originMainSessionId}-${teamName}` : undefined;
1119
+ const runtimeTeamId = teamId ?? teamName;
1120
+ if (teams.has(runtimeTeamId)) throw new Error(`Team already exists: ${runtimeTeamId}`);
1121
+ const lease = teamId ? claimTeamLease(teamId, originMainSessionId) : undefined;
1122
+ if (teamId && projectDirectory && listTeamManifests(projectDirectory).some((manifest) => manifest.id === teamId)) {
1123
+ releaseTeamLease(lease!);
1124
+ throw new Error(`Team already exists: ${teamId}. Use team_resume.`);
1125
+ }
881
1126
  sessionTeammateRoster.push(...teammateNames.filter((teammateName) => !sessionTeammateRoster.includes(teammateName)));
882
- await ensureCallbackServer();
1127
+ try {
1128
+ await ensureCallbackServer();
1129
+ } catch (error) {
1130
+ if (lease) releaseTeamLease(lease);
1131
+ throw error;
1132
+ }
883
1133
 
884
1134
  const team: TeamState = {
885
1135
  owner,
886
1136
  ownerPi: pi,
1137
+ id: teamId,
887
1138
  name: teamName,
1139
+ projectDirectory,
888
1140
  showOnHerdrPanes,
889
1141
  teamPrompt: params.teamPrompt,
890
1142
  mainSessionFile,
891
1143
  members: new Map(),
892
1144
  statuses: new Map([["main", status("available", "Main agent")]]),
893
1145
  created: nowText(),
1146
+ lease,
894
1147
  log: [],
895
1148
  nextLogSequence: 1,
896
1149
  };
897
1150
 
898
- teams.set(teamName, team);
1151
+ teams.set(runtimeTeamId, team);
899
1152
  try {
900
1153
  for (const teammateSpec of teammateSpecs) {
901
1154
  const teammate = createTeammateState(team, teammateSpec);
@@ -903,6 +1156,25 @@ export default function (pi: ExtensionAPI) {
903
1156
  team.statuses.set(teammate.name, status("idle", "Spawned"));
904
1157
  await startTeammate(team, teammate, teammateNames, herdrTabId);
905
1158
  }
1159
+
1160
+ if (teamId && originMainSessionId && projectDirectory) {
1161
+ const timestamp = new Date().toISOString();
1162
+ const manifest: TeamManifest = {
1163
+ version: 1,
1164
+ id: teamId,
1165
+ name: team.name,
1166
+ originMainSessionId,
1167
+ projectDirectory,
1168
+ teamPrompt: team.teamPrompt,
1169
+ showOnHerdrPanes: team.showOnHerdrPanes,
1170
+ members: [...team.members.values()].map(manifestMemberFromTeammate),
1171
+ state: "active",
1172
+ createdAt: timestamp,
1173
+ updatedAt: timestamp,
1174
+ };
1175
+ writeTeamManifest(manifest);
1176
+ team.manifest = manifest;
1177
+ }
906
1178
  } catch (error) {
907
1179
  await shutdownTeam(team);
908
1180
  closeCallbackServerIfUnused();
@@ -910,8 +1182,14 @@ export default function (pi: ExtensionAPI) {
910
1182
  }
911
1183
  return toolResult({
912
1184
  accepted: true,
1185
+ id: team.id,
913
1186
  team: team.name,
914
1187
  teammates: [...team.members.keys()],
1188
+ sessions: Object.fromEntries(
1189
+ [...team.members.values()]
1190
+ .filter((teammate) => teammate.sessionId && teammate.sessionFile)
1191
+ .map((teammate) => [teammate.name, { sessionId: teammate.sessionId, sessionFile: teammate.sessionFile }]),
1192
+ ),
915
1193
  status: formatStatus(team),
916
1194
  instruction: bundledAiToAiSkillInstruction,
917
1195
  });
@@ -920,6 +1198,212 @@ export default function (pi: ExtensionAPI) {
920
1198
  );
921
1199
  });
922
1200
 
1201
+ pi.registerTool(
1202
+ defineTool({
1203
+ name: "team_list",
1204
+ label: "Team List",
1205
+ description: "List active and dormant teams for the current project.",
1206
+ promptSnippet: "List teams for the current project",
1207
+ parameters: Type.Object({}),
1208
+ async execute(_toolCallId, _params, _signal, _onUpdate, context) {
1209
+ const projectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1210
+ if (!projectDirectory) throw new Error("team_list requires a project directory");
1211
+ const manifests = listTeamManifests(projectDirectory);
1212
+ return toolResult({
1213
+ teams: manifests.map((manifest) => {
1214
+ const liveTeam = teams.get(manifest.id);
1215
+ return {
1216
+ id: manifest.id,
1217
+ name: manifest.name,
1218
+ state: manifest.state,
1219
+ leaseState: readTeamLeaseState(manifest.id).state,
1220
+ teammates: manifest.members.map((member) => member.name),
1221
+ members: manifest.members.map((member) => ({
1222
+ name: member.name,
1223
+ live: liveTeam?.members.get(member.name)?.alive ?? member.live,
1224
+ sessionId: member.sessionId,
1225
+ sessionFile: member.sessionFile,
1226
+ })),
1227
+ createdAt: manifest.createdAt,
1228
+ updatedAt: manifest.updatedAt,
1229
+ shutdownAt: manifest.shutdownAt,
1230
+ expiresAt: manifest.expiresAt,
1231
+ };
1232
+ }),
1233
+ });
1234
+ },
1235
+ }),
1236
+ );
1237
+
1238
+ pi.registerTool(
1239
+ defineTool({
1240
+ name: "team_resume",
1241
+ label: "Team Resume",
1242
+ description: "Resume all stopped teammates in a dormant current-project team, or only selected stopped teammates.",
1243
+ promptSnippet: "Resume all or selected stopped teammates",
1244
+ parameters: Type.Object({
1245
+ team: Type.String({ description: "Persistent team ID" }),
1246
+ teammates: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description: "Stopped teammate names. Omit to resume all stopped teammates." })),
1247
+ showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false, description: "Resume selected teammates in visible Herdr panes. Defaults to RPC." })),
1248
+ }),
1249
+ async execute(_toolCallId, params, _signal, _onUpdate, context) {
1250
+ const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1251
+ if (!rawProjectDirectory) throw new Error("team_resume requires a project directory");
1252
+ const manifest = listTeamManifests(rawProjectDirectory).find((candidate) => candidate.id === params.team);
1253
+ if (!manifest) throw new Error(`Unknown current-project team: ${params.team}`);
1254
+ const requestedNames = params.teammates?.map(compactName) ?? manifest.members.map((member) => member.name);
1255
+ const duplicateNames = requestedNames.filter((name, index) => requestedNames.indexOf(name) !== index);
1256
+ if (duplicateNames.length > 0) throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
1257
+ const manifestMemberNames = new Set(manifest.members.map((member) => member.name));
1258
+ const missingNames = requestedNames.filter((name) => !manifestMemberNames.has(name));
1259
+ if (missingNames.length > 0) throw new Error(`Unknown teammate(s) in ${manifest.name}: ${missingNames.join(", ")}`);
1260
+ const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
1261
+ const herdrTabId = showOnHerdrPanes ? await validateHerdrAvailability() : undefined;
1262
+
1263
+ const existingTeam = [...teams.values()].find((candidate) => candidate.id === manifest.id);
1264
+ if (existingTeam && existingTeam.owner !== owner) {
1265
+ throw new Error(`Team ${manifest.id} is already owned by another main session`);
1266
+ }
1267
+
1268
+ let team = existingTeam;
1269
+ if (!team) {
1270
+ const mainSessionId = context.sessionManager?.getSessionId?.();
1271
+ if (!mainSessionId) throw new Error("team_resume requires a persistent main session");
1272
+ const lease = claimTeamLease(manifest.id, mainSessionId);
1273
+ try {
1274
+ await ensureCallbackServer();
1275
+ team = restoreTeamState(owner, pi, manifest, lease);
1276
+ teams.set(team.id!, team);
1277
+ } catch (error) {
1278
+ releaseTeamLease(lease);
1279
+ closeCallbackServerIfUnused();
1280
+ throw error;
1281
+ }
1282
+ }
1283
+
1284
+ const teammates = requestedNames.map((name) => team.members.get(name)!).filter((teammate) => !teammate.alive);
1285
+ let starts: Array<{ teammate: TeammateState; sessionFile: string | undefined }>;
1286
+ try {
1287
+ starts = teammates.map((teammate) => ({ teammate, sessionFile: sessionFileForResume(teammate) }));
1288
+ } catch (error) {
1289
+ if (!existingTeam) {
1290
+ await shutdownTeam(team);
1291
+ closeCallbackServerIfUnused();
1292
+ }
1293
+ throw error;
1294
+ }
1295
+ const participantNames = [...team.members.keys()];
1296
+ sessionTeammateRoster.push(...participantNames.filter((name) => !sessionTeammateRoster.includes(name)));
1297
+
1298
+ try {
1299
+ for (const { teammate, sessionFile } of starts) {
1300
+ if (showOnHerdrPanes) prepareVisibleTeammate(teammate);
1301
+ else teammate.transport = "rpc";
1302
+ await startTeammate(team, teammate, participantNames, herdrTabId, {
1303
+ sessionFile,
1304
+ restartEmpty: sessionFile === undefined,
1305
+ });
1306
+ team.statuses.set(teammate.name, status("idle", "Resumed"));
1307
+ }
1308
+ persistActiveTeamManifest(team);
1309
+ } catch (error) {
1310
+ if (!existingTeam) {
1311
+ await shutdownTeam(team);
1312
+ closeCallbackServerIfUnused();
1313
+ throw error;
1314
+ }
1315
+ for (const { teammate } of starts) {
1316
+ if (teammate.transport === "herdr") {
1317
+ teammate.alive = false;
1318
+ await closeVisiblePane(teammate);
1319
+ } else {
1320
+ await stopRpcTeammate(teammate);
1321
+ }
1322
+ team.statuses.set(teammate.name, status("stopped", "Resume failed"));
1323
+ }
1324
+ throw error;
1325
+ }
1326
+
1327
+ return toolResult({
1328
+ accepted: true,
1329
+ id: team.id,
1330
+ team: team.name,
1331
+ resumed: starts.map(({ teammate }) => teammate.name),
1332
+ sessions: Object.fromEntries(
1333
+ starts.map(({ teammate }) => [teammate.name, { sessionId: teammate.sessionId, sessionFile: teammate.sessionFile }]),
1334
+ ),
1335
+ });
1336
+ },
1337
+ }),
1338
+ );
1339
+
1340
+ pi.registerTool(
1341
+ defineTool({
1342
+ name: "team_add",
1343
+ label: "Team Add",
1344
+ description: "Add one or more new RPC teammates to a running team owned by this main session.",
1345
+ promptSnippet: "Add new teammates to a running team",
1346
+ parameters: Type.Object({
1347
+ team: Type.String({ description: "Persistent team ID" }),
1348
+ teammates: Type.Array(teammateSchema(""), { minItems: 1, description: "New teammates to add" }),
1349
+ }),
1350
+ async execute(_toolCallId, params, _signal, _onUpdate, context) {
1351
+ const team = [...teams.values()].find((candidate) => candidate.id === params.team && candidate.owner === owner);
1352
+ if (!team || !team.manifest || !team.lease || team.manifest.state !== "active") {
1353
+ throw new Error(`team_add requires a running team owned by this main session: ${params.team}`);
1354
+ }
1355
+
1356
+ const teammateSpecs = params.teammates as TeammateSpec[];
1357
+ const teammateNames = teammateSpecs.map((teammate) => compactName(teammate.name));
1358
+ const duplicateNames = teammateNames.filter(
1359
+ (name, index) => teammateNames.indexOf(name) !== index || team.members.has(name),
1360
+ );
1361
+ if (duplicateNames.length > 0) {
1362
+ throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
1363
+ }
1364
+ if (teammateNames.includes("main")) throw new Error('"main" is reserved');
1365
+ validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
1366
+
1367
+ const inheritsMainContext = teammateSpecs.some((teammate) => Boolean(teammate.inheritContext));
1368
+ const mainSessionFile = inheritsMainContext ? context.sessionManager.getSessionFile() : undefined;
1369
+ if (inheritsMainContext && !mainSessionFile) throw new Error("inheritContext requires a persistent main session");
1370
+ if (mainSessionFile) team.mainSessionFile = mainSessionFile;
1371
+
1372
+ const addedTeammates = teammateSpecs.map((teammateSpec) => createTeammateState(team, teammateSpec));
1373
+ for (const teammate of addedTeammates) {
1374
+ teammate.transport = "rpc";
1375
+ team.members.set(teammate.name, teammate);
1376
+ team.statuses.set(teammate.name, status("idle", "Spawned"));
1377
+ }
1378
+ const participantNames = [...team.members.keys()];
1379
+ sessionTeammateRoster.push(...teammateNames.filter((name) => !sessionTeammateRoster.includes(name)));
1380
+
1381
+ try {
1382
+ for (const teammate of addedTeammates) await startTeammate(team, teammate, participantNames);
1383
+ persistActiveTeamManifest(team);
1384
+ } catch (error) {
1385
+ for (const teammate of addedTeammates) await stopRpcTeammate(teammate);
1386
+ for (const teammate of addedTeammates) {
1387
+ team.members.delete(teammate.name);
1388
+ team.statuses.delete(teammate.name);
1389
+ }
1390
+ throw error;
1391
+ }
1392
+
1393
+ return toolResult({
1394
+ accepted: true,
1395
+ id: team.id,
1396
+ team: team.name,
1397
+ added: teammateNames,
1398
+ sessions: Object.fromEntries(
1399
+ addedTeammates.map((teammate) => [teammate.name, { sessionId: teammate.sessionId, sessionFile: teammate.sessionFile }]),
1400
+ ),
1401
+ status: formatStatus(team),
1402
+ });
1403
+ },
1404
+ }),
1405
+ );
1406
+
923
1407
  pi.registerTool(
924
1408
  defineTool({
925
1409
  name: "teamsend",