@giladbarnea/pi-simple-team 1.0.21 → 1.0.22

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
@@ -155,13 +155,13 @@ Main agent knows its own and everyone else's too.
155
155
  - 17:32:01: Release teammate sets status: "Ran `git add .`, preparing commit and push."
156
156
  - 17:32:02: Scout immediately interrupts. Key never leaves the machine. Developer keeps their job.
157
157
 
158
- ### 📡 Complete observability by design.
158
+ ### 📡 Live observability without a second history.
159
159
 
160
- The main agent can access one exhaustive, **timestamped history** of tool calls, messages, and lifecycle events, **recorded by the harness itself.**
160
+ While a team runs, `teamlog` exposes a timestamped, filterable timeline of messages, tool calls, and lifecycle events.
161
161
 
162
- Main can filter and page that shared timeline on demand.
162
+ That live timeline stays in parent-process memory and starts fresh after a resume. Pi session JSONL files are the canonical conversation history.
163
163
 
164
- Useful for tracing a failure *across* teammates—without asking anyone to reconstruct it from memory.
164
+ `pi-simple-team` does not persist a separate parent-runtime log or duplicate `teamlog` data.
165
165
 
166
166
  <br>
167
167
 
@@ -175,6 +175,24 @@ Useful for tracing a failure *across* teammates—without asking anyone to recon
175
175
  - Live view of the room.
176
176
  - Talk directly with teammates.
177
177
 
178
+ ### 🧱 Teammates are durable Pi sessions.
179
+
180
+ A teammate is a normal Pi session with a team attachment and an optional live runtime. The attachment adds its team prompt, roster, and communication tools.
181
+
182
+ Each team ID is `{origin-main-session-id}-{team-name}`. `team_list` discovers active and dormant teams from the same canonical project directory.
183
+
184
+ `team_shutdown` stops every live runtime and leaves the team dormant. Its manifest expires after 30 days, but expiration never deletes Pi session files.
185
+
186
+ `team_resume` starts all stopped teammates by default, or only selected teammates. Resume uses RPC unless `showOnHerdrPanes` is explicitly set.
187
+
188
+ Pi creates a session path before it writes the session JSONL file. A teammate without a first assistant response therefore restarts empty.
189
+
190
+ A missing file that once held session history causes resume to fail. Persisted sessions restore their own model and thinking state from Pi.
191
+
192
+ `team_add` creates new RPC teammates only for a running team owned by the current main session.
193
+
194
+ **One Pi session can have only one live runtime.** Pi does not lock session files against concurrent writers.
195
+
178
196
 
179
197
  ## Install
180
198
 
@@ -190,16 +208,16 @@ pi install npm:@giladbarnea/pi-simple-team
190
208
  Kept minimal:
191
209
 
192
210
 
193
- | Role | For | Tools |
194
- | -------------- | -------------- | ----------------------------- |
195
- | **Main agent** | Team lifecycle | `team_spawn`, `team_shutdown` |
196
- | | With team | `teamsend` |
197
- | | On team | `teamstatus`, `teamlog` |
198
- | | On everyone | `report_context_window` |
199
- | **Teammates** | With team | `teamsend` |
200
- | | With main | `teammain` |
201
- | | On self | `report_context_window` |
202
- | **Everyone** | For everyone | `teamstatus` |
211
+ | Role | For | Tools |
212
+ | -------------- | -------------- | ---------------------------------------------------------------- |
213
+ | **Main agent** | Team lifecycle | `team_spawn`, `team_list`, `team_resume`, `team_add`, `team_shutdown` |
214
+ | | With team | `teamsend` |
215
+ | | On team | `teamstatus`, `teamlog` |
216
+ | | On everyone | `report_context_window` |
217
+ | **Teammates** | With team | `teamsend` |
218
+ | | With main | `teammain` |
219
+ | | On self | `report_context_window` |
220
+ | **Everyone** | For everyone | `teamstatus` |
203
221
 
204
222
 
205
223
  ---
@@ -220,5 +238,6 @@ Slash commands for:
220
238
 
221
239
  **Functional:**
222
240
 
223
- - [ ] Add new teammates after team has spawned.
241
+ - [x] Resume all or selected teammates from a dormant team.
242
+ - [x] Add new teammates after a team has spawned.
224
243
  - [ ] Main forces `/compact` on select teammate.
package/child-tools.ts CHANGED
@@ -13,6 +13,7 @@ const visibleLifecycleRetryAttempts = 3;
13
13
  export interface ChildRuntimeConfig {
14
14
  callbackUrl: string;
15
15
  callbackToken: string;
16
+ teamId?: string;
16
17
  teamName: string;
17
18
  teammateName: string;
18
19
  visible: boolean;
@@ -36,10 +37,12 @@ function readParticipants(): string[] {
36
37
  }
37
38
 
38
39
  function readRequiredChildRuntimeConfig(): ChildRuntimeConfig {
40
+ const teamId = requiredEnvironmentVariable("PI_SIMPLE_TEAM_TEAM");
39
41
  return {
40
42
  callbackUrl: requiredEnvironmentVariable("PI_SIMPLE_TEAM_CALLBACK_URL"),
41
43
  callbackToken: requiredEnvironmentVariable("PI_SIMPLE_TEAM_CALLBACK_TOKEN"),
42
- teamName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_TEAM"),
44
+ teamId,
45
+ teamName: process.env.PI_SIMPLE_TEAM_TEAM_NAME ?? teamId,
43
46
  teammateName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_MEMBER"),
44
47
  visible: process.env.PI_SIMPLE_TEAM_VISIBLE_CHILD === "1",
45
48
  participants: readParticipants(),
@@ -57,7 +60,7 @@ async function callParent(config: ChildRuntimeConfig, tool: string, args: JsonRe
57
60
  headers: { "content-type": "application/json" },
58
61
  body: JSON.stringify({
59
62
  token: config.callbackToken,
60
- team: config.teamName,
63
+ team: config.teamId ?? config.teamName,
61
64
  from: config.teammateName,
62
65
  tool,
63
66
  args,
@@ -226,7 +229,11 @@ function startVisibleChild(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
226
229
  if (!address || typeof address === "string") throw new Error("Visible teammate server did not get a port");
227
230
 
228
231
  try {
229
- await callParent(config, "visible_register", { url: `http://127.0.0.1:${address.port}/deliver` });
232
+ await callParent(config, "visible_register", {
233
+ url: `http://127.0.0.1:${address.port}/deliver`,
234
+ sessionId: context.sessionManager.getSessionId(),
235
+ sessionFile: context.sessionManager.getSessionFile(),
236
+ });
230
237
  } catch (error) {
231
238
  context.shutdown();
232
239
  throw error;
@@ -248,6 +255,25 @@ function startVisibleChild(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
248
255
 
249
256
  export function registerChildTools(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
250
257
  pi.registerMessageRenderer(teamMessageType, (message, _options, theme) => renderTeamMessage(message, theme, getMarkdownTheme(), config.participants));
258
+ const startupRosterInstruction = `Participants: main, ${config.participants.join(", ")}.`;
259
+ pi.on("before_agent_start", async (event, context) => {
260
+ const teamContext = await callParent(config, "team_context", {}, context.signal);
261
+ const rawParticipants: unknown = teamContext.participants;
262
+ if (!Array.isArray(rawParticipants) || rawParticipants.some((participant: unknown) => typeof participant !== "string")) {
263
+ throw new Error("team runtime returned an invalid participant list");
264
+ }
265
+ const participants = rawParticipants as string[];
266
+ if (!event.systemPrompt.includes(startupRosterInstruction)) {
267
+ throw new Error("team runtime could not find its startup roster instruction");
268
+ }
269
+ config.participants.splice(0, config.participants.length, ...participants);
270
+ return {
271
+ systemPrompt: event.systemPrompt.replace(
272
+ startupRosterInstruction,
273
+ `Participants: main, ${participants.join(", ")}.`,
274
+ ),
275
+ };
276
+ });
251
277
  if (config.visible) startVisibleChild(pi, config);
252
278
 
253
279
  pi.registerTool(
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,6 +12,18 @@ 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";
15
29
  import { StringEnum } from "@earendil-works/pi-ai";
@@ -57,6 +71,9 @@ interface TeammateState {
57
71
  thinking: ThinkingLevel;
58
72
  inheritContext: boolean;
59
73
  transport: TeammateTransport;
74
+ sessionId?: string;
75
+ sessionFile?: string;
76
+ sessionMaterialized: boolean;
60
77
  process?: ChildProcess;
61
78
  paneId?: string;
62
79
  visibleUrl?: string;
@@ -74,13 +91,17 @@ interface TeammateState {
74
91
  interface TeamState {
75
92
  owner: symbol;
76
93
  ownerPi: ExtensionAPI;
94
+ id?: string;
77
95
  name: string;
96
+ projectDirectory?: string;
78
97
  showOnHerdrPanes: boolean;
79
98
  teamPrompt: string;
80
99
  mainSessionFile?: string;
81
100
  members: Map<string, TeammateState>;
82
101
  statuses: Map<string, TeamStatus>;
83
102
  created: string;
103
+ manifest?: TeamManifest;
104
+ lease?: TeamLease;
84
105
  log: TeamLogEntry[];
85
106
  nextLogSequence: number;
86
107
  }
@@ -386,17 +407,18 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
386
407
  });
387
408
  }
388
409
 
389
- function resolveTeam(owner: symbol, teamName?: string): TeamState {
410
+ function resolveTeam(owner: symbol, teamIdentifier?: string): TeamState {
390
411
  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;
412
+ if (teamIdentifier) {
413
+ const matches = ownedTeams.filter((team) => team.id === teamIdentifier || team.name === teamIdentifier);
414
+ if (matches.length === 0) throw new Error(`Unknown team: ${teamIdentifier}`);
415
+ if (matches.length > 1) throw new Error(`Ambiguous team name: ${teamIdentifier}. Pass the persistent team ID.`);
416
+ return matches[0]!;
395
417
  }
396
418
 
397
419
  if (ownedTeams.length === 1) return ownedTeams[0];
398
420
  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.`);
421
+ throw new Error(`Multiple teams exist: ${ownedTeams.map((team) => team.id ?? team.name).join(", ")}. Pass team explicitly.`);
400
422
  }
401
423
 
402
424
  function resolveCallbackTeam(teamName: string): TeamState {
@@ -493,6 +515,7 @@ function createTeammateState(team: TeamState, teammateSpec: TeammateSpec): Teamm
493
515
  thinking,
494
516
  inheritContext: Boolean(teammateSpec.inheritContext),
495
517
  transport: team.showOnHerdrPanes ? "herdr" : "rpc",
518
+ sessionMaterialized: false,
496
519
  visibleReady,
497
520
  resolveVisibleReady,
498
521
  rejectVisibleReady,
@@ -511,7 +534,8 @@ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, par
511
534
  PI_SIMPLE_TEAM_VISIBLE_CHILD: visible ? "1" : "0",
512
535
  PI_SIMPLE_TEAM_CALLBACK_URL: callbackUrl,
513
536
  PI_SIMPLE_TEAM_CALLBACK_TOKEN: callbackToken,
514
- PI_SIMPLE_TEAM_TEAM: team.name,
537
+ PI_SIMPLE_TEAM_TEAM: team.id ?? team.name,
538
+ PI_SIMPLE_TEAM_TEAM_NAME: team.name,
515
539
  PI_SIMPLE_TEAM_MEMBER: teammate.name,
516
540
  PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
517
541
  };
@@ -528,29 +552,39 @@ function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
528
552
  });
529
553
  }
530
554
 
531
- function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[]): void {
532
- const sessionArgs = teammate.inheritContext ? ["--fork", team.mainSessionFile!] : [];
555
+ interface RpcStartOptions {
556
+ sessionFile?: string;
557
+ restartEmpty?: boolean;
558
+ }
559
+
560
+ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[], options: RpcStartOptions): void {
561
+ const sessionArgs = options.sessionFile
562
+ ? ["--session", options.sessionFile]
563
+ : teammate.inheritContext && !options.restartEmpty
564
+ ? ["--fork", team.mainSessionFile!]
565
+ : [];
566
+ const modelArgs = options.sessionFile ? [] : ["--model", teammate.model, "--thinking", teammate.thinking];
533
567
  const args = [
534
568
  "--mode",
535
569
  "rpc",
536
570
  ...sessionArgs,
571
+ "--no-extensions",
537
572
  "-e",
538
573
  teamLiteExtensionPath,
539
574
  "--no-prompt-templates",
540
575
  "--no-themes",
541
- "--model",
542
- teammate.model,
543
- "--thinking",
544
- teammate.thinking,
576
+ ...modelArgs,
545
577
  "--system-prompt",
546
578
  composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants),
547
579
  ];
548
580
  const proc = childProcess.spawn("pi", args, {
549
- cwd: process.cwd(),
581
+ cwd: team.projectDirectory ?? process.cwd(),
550
582
  stdio: ["pipe", "pipe", "pipe"],
551
583
  env: { ...process.env, ...childEnvironmentOverrides(team, teammate, participants, false) },
552
584
  });
553
585
  teammate.process = proc;
586
+ teammate.alive = true;
587
+ teammate.busy = false;
554
588
 
555
589
  attachJsonlReader(proc.stdout!, (line) => {
556
590
  if (!line.trim()) return;
@@ -575,6 +609,18 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
575
609
  appendSpawnLog(team, teammate);
576
610
  }
577
611
 
612
+ async function captureRpcSessionIdentity(teammate: TeammateState): Promise<void> {
613
+ const response = await sendRpc(teammate, { type: "get_state" }, 10_000);
614
+ await requireSuccessfulResponse(response, `read session identity from ${teammate.name}`);
615
+ const state = response.data as { sessionId?: unknown; sessionFile?: unknown } | undefined;
616
+ if (typeof state?.sessionId !== "string" || typeof state.sessionFile !== "string" || !path.isAbsolute(state.sessionFile)) {
617
+ throw new Error(`Teammate ${teammate.name} reported an invalid session identity`);
618
+ }
619
+ teammate.sessionId = state.sessionId;
620
+ teammate.sessionFile = state.sessionFile;
621
+ teammate.sessionMaterialized = fs.existsSync(state.sessionFile);
622
+ }
623
+
578
624
  function parseHerdrPaneId(stdout: string, teammateName: string): string {
579
625
  const response = JSON.parse(stdout) as { result?: { agent?: { pane_id?: string } } };
580
626
  const paneId = response.result?.agent?.pane_id;
@@ -582,23 +628,33 @@ function parseHerdrPaneId(stdout: string, teammateName: string): string {
582
628
  return paneId;
583
629
  }
584
630
 
585
- async function attachVisibleTeammate(team: TeamState, teammate: TeammateState, participants: string[], herdrTabId: string): Promise<void> {
631
+ async function attachVisibleTeammate(
632
+ team: TeamState,
633
+ teammate: TeammateState,
634
+ participants: string[],
635
+ herdrTabId: string,
636
+ options: RpcStartOptions,
637
+ ): Promise<void> {
586
638
  const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants);
587
639
  const environment = childEnvironmentOverrides(team, teammate, participants, true);
588
- const args = ["agent", "start", teammate.name, "--tab", herdrTabId, "--split", "right", "--no-focus", "--cwd", process.cwd()];
640
+ const sessionArgs = options.sessionFile
641
+ ? ["--session", options.sessionFile]
642
+ : teammate.inheritContext && !options.restartEmpty
643
+ ? ["--fork", team.mainSessionFile!]
644
+ : [];
645
+ const modelArgs = options.sessionFile ? [] : ["--model", teammate.model, "--thinking", teammate.thinking];
646
+ const args = ["agent", "start", teammate.name, "--tab", herdrTabId, "--split", "right", "--no-focus", "--cwd", team.projectDirectory ?? process.cwd()];
589
647
  for (const [name, value] of Object.entries(environment)) {
590
648
  if (value !== undefined) args.push("--env", `${name}=${value}`);
591
649
  }
592
650
  args.push(
593
651
  "--",
594
652
  "pi",
595
- ...(teammate.inheritContext ? ["--fork", team.mainSessionFile!] : []),
653
+ ...sessionArgs,
654
+ "--no-extensions",
596
655
  "-e",
597
656
  teamLiteExtensionPath,
598
- "--model",
599
- teammate.model,
600
- "--thinking",
601
- teammate.thinking,
657
+ ...modelArgs,
602
658
  "--system-prompt",
603
659
  systemPrompt,
604
660
  );
@@ -622,12 +678,52 @@ async function attachVisibleTeammate(team: TeamState, teammate: TeammateState, p
622
678
  }
623
679
  }
624
680
 
625
- async function startTeammate(team: TeamState, teammate: TeammateState, participants: string[], herdrTabId?: string): Promise<void> {
681
+ async function startTeammate(
682
+ team: TeamState,
683
+ teammate: TeammateState,
684
+ participants: string[],
685
+ herdrTabId?: string,
686
+ rpcOptions: RpcStartOptions = {},
687
+ ): Promise<void> {
626
688
  if (teammate.transport === "herdr") {
627
- await attachVisibleTeammate(team, teammate, participants, herdrTabId!);
689
+ await attachVisibleTeammate(team, teammate, participants, herdrTabId!, rpcOptions);
628
690
  return;
629
691
  }
630
- attachRpcTeammate(team, teammate, participants);
692
+ attachRpcTeammate(team, teammate, participants, rpcOptions);
693
+ if (team.id) await captureRpcSessionIdentity(teammate);
694
+ }
695
+
696
+ function manifestMemberFromTeammate(teammate: TeammateState): TeamManifestMember {
697
+ if (!teammate.sessionId || !teammate.sessionFile) {
698
+ throw new Error(`Teammate ${teammate.name} has no reported session identity`);
699
+ }
700
+ if (fs.existsSync(teammate.sessionFile)) teammate.sessionMaterialized = true;
701
+ return {
702
+ name: teammate.name,
703
+ prompt: teammate.prompt,
704
+ model: teammate.model,
705
+ thinking: teammate.thinking,
706
+ inheritContext: teammate.inheritContext,
707
+ transport: teammate.transport,
708
+ live: teammate.alive,
709
+ sessionId: teammate.sessionId,
710
+ sessionFile: teammate.sessionFile,
711
+ sessionMaterialized: teammate.sessionMaterialized,
712
+ };
713
+ }
714
+
715
+ function persistActiveTeamManifest(team: TeamState): void {
716
+ if (!team.manifest) return;
717
+ const updatedAt = new Date().toISOString();
718
+ team.manifest = {
719
+ ...team.manifest,
720
+ members: [...team.members.values()].map(manifestMemberFromTeammate),
721
+ state: "active",
722
+ updatedAt,
723
+ shutdownAt: undefined,
724
+ expiresAt: undefined,
725
+ };
726
+ writeTeamManifest(team.manifest);
631
727
  }
632
728
 
633
729
  function isHerdrPaneNotFound(error: unknown): boolean {
@@ -644,11 +740,29 @@ async function closeVisiblePane(teammate: TeammateState): Promise<void> {
644
740
  teammate.paneId = undefined;
645
741
  }
646
742
 
743
+ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
744
+ const processToStop = teammate.process;
745
+ if (!processToStop || !teammate.alive) return;
746
+
747
+ await new Promise<void>((resolve) => {
748
+ let forceKillTimeout: ReturnType<typeof setTimeout> | undefined;
749
+ const resolveExit = (): void => {
750
+ if (forceKillTimeout) clearTimeout(forceKillTimeout);
751
+ resolve();
752
+ };
753
+ processToStop.once("exit", resolveExit);
754
+ processToStop.kill("SIGTERM");
755
+ forceKillTimeout = setTimeout(() => processToStop.kill("SIGKILL"), 1_000);
756
+ forceKillTimeout.unref();
757
+ });
758
+ teammate.process = undefined;
759
+ }
760
+
647
761
  async function shutdownTeam(team: TeamState): Promise<string[]> {
648
762
  const errors: string[] = [];
649
763
  for (const teammate of team.members.values()) {
650
- teammate.alive = false;
651
764
  if (teammate.transport === "herdr") {
765
+ teammate.alive = false;
652
766
  try {
653
767
  await closeVisiblePane(teammate);
654
768
  } catch (error) {
@@ -656,13 +770,33 @@ async function shutdownTeam(team: TeamState): Promise<string[]> {
656
770
  }
657
771
  continue;
658
772
  }
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();
773
+ await stopRpcTeammate(teammate);
774
+ }
775
+ if (team.manifest) {
776
+ try {
777
+ const shutdownAt = new Date().toISOString();
778
+ team.manifest = {
779
+ ...team.manifest,
780
+ members: [...team.members.values()].map(manifestMemberFromTeammate),
781
+ state: "dormant",
782
+ updatedAt: shutdownAt,
783
+ shutdownAt,
784
+ expiresAt: new Date(Date.parse(shutdownAt) + dormantManifestRetentionMilliseconds).toISOString(),
785
+ };
786
+ writeTeamManifest(team.manifest);
787
+ } catch (error) {
788
+ errors.push(error instanceof Error ? error.message : String(error));
789
+ }
790
+ }
791
+ if (team.lease) {
792
+ try {
793
+ releaseTeamLease(team.lease);
794
+ } catch (error) {
795
+ errors.push(error instanceof Error ? error.message : String(error));
796
+ }
797
+ team.lease = undefined;
664
798
  }
665
- teams.delete(team.name);
799
+ teams.delete(team.id ?? team.name);
666
800
  return errors;
667
801
  }
668
802
 
@@ -758,6 +892,11 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
758
892
  if (tool === "visible_register") {
759
893
  if (!teammate || teammate.transport !== "herdr") throw new Error(`Unknown visible teammate: ${from}`);
760
894
  const url = String(args.url ?? "");
895
+ const sessionId = args.sessionId;
896
+ const sessionFile = args.sessionFile;
897
+ if (typeof sessionId !== "string" || typeof sessionFile !== "string" || !path.isAbsolute(sessionFile)) {
898
+ throw new Error(`Visible teammate ${from} reported an invalid session identity`);
899
+ }
761
900
  try {
762
901
  teammate.visibleUrl = validateVisibleChildUrl(url, from);
763
902
  } catch (error) {
@@ -765,6 +904,9 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
765
904
  teammate.rejectVisibleReady?.(failure);
766
905
  throw failure;
767
906
  }
907
+ teammate.sessionId = sessionId;
908
+ teammate.sessionFile = sessionFile;
909
+ teammate.sessionMaterialized = fs.existsSync(sessionFile);
768
910
  teammate.alive = true;
769
911
  teammate.busy = false;
770
912
  team.statuses.set(teammate.name, status("idle", "Spawned"));
@@ -780,6 +922,17 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
780
922
  return;
781
923
  }
782
924
 
925
+ if (tool === "team_context") {
926
+ if (!teammate) throw new Error(`Unknown teammate: ${from}`);
927
+ writeJson(response, 200, {
928
+ team: team.name,
929
+ from,
930
+ participants: [...team.members.keys()],
931
+ status: formatStatus(team),
932
+ });
933
+ return;
934
+ }
935
+
783
936
  if (tool === "teamsend") {
784
937
  const recipients = resolveRecipients(team, (args.to ?? []) as string[]);
785
938
  const message = String(args.message ?? "");
@@ -826,6 +979,60 @@ function teammateSchema(modelGuidance: string) {
826
979
  });
827
980
  }
828
981
 
982
+ function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, manifest: TeamManifest, lease: TeamLease): TeamState {
983
+ const team: TeamState = {
984
+ owner,
985
+ ownerPi,
986
+ id: manifest.id,
987
+ name: manifest.name,
988
+ projectDirectory: manifest.projectDirectory,
989
+ showOnHerdrPanes: false,
990
+ teamPrompt: manifest.teamPrompt,
991
+ members: new Map(),
992
+ statuses: new Map([["main", status("available", "Main agent")]]),
993
+ created: manifest.createdAt,
994
+ manifest,
995
+ lease,
996
+ log: [],
997
+ nextLogSequence: 1,
998
+ };
999
+ for (const member of manifest.members) {
1000
+ const teammate = createTeammateState(team, {
1001
+ name: member.name,
1002
+ prompt: member.prompt,
1003
+ model: member.model,
1004
+ thinking: member.thinking as ThinkingLevel,
1005
+ inheritContext: member.inheritContext,
1006
+ });
1007
+ teammate.transport = "rpc";
1008
+ teammate.sessionId = member.sessionId;
1009
+ teammate.sessionFile = member.sessionFile;
1010
+ teammate.sessionMaterialized = member.sessionMaterialized;
1011
+ teammate.alive = false;
1012
+ team.members.set(teammate.name, teammate);
1013
+ team.statuses.set(teammate.name, status("stopped", "Dormant"));
1014
+ }
1015
+ return team;
1016
+ }
1017
+
1018
+ function prepareVisibleTeammate(teammate: TeammateState): void {
1019
+ teammate.transport = "herdr";
1020
+ teammate.visibleReady = new Promise<void>((resolve, reject) => {
1021
+ teammate.resolveVisibleReady = resolve;
1022
+ teammate.rejectVisibleReady = reject;
1023
+ });
1024
+ }
1025
+
1026
+ function sessionFileForResume(teammate: TeammateState): string | undefined {
1027
+ if (!teammate.sessionFile) throw new Error(`Teammate ${teammate.name} has no reported session file`);
1028
+ if (fs.existsSync(teammate.sessionFile)) return teammate.sessionFile;
1029
+ if (teammate.sessionMaterialized) {
1030
+ throw new Error(`Materialized session file for ${teammate.name} is missing: ${teammate.sessionFile}`);
1031
+ }
1032
+ // This empty restart becomes redundant when team creation wakes every teammate and guarantees session persistence.
1033
+ return undefined;
1034
+ }
1035
+
829
1036
  export default function (pi: ExtensionAPI) {
830
1037
  const childRuntimeConfig = readChildRuntimeConfig();
831
1038
  if (childRuntimeConfig) {
@@ -864,7 +1071,6 @@ export default function (pi: ExtensionAPI) {
864
1071
  }),
865
1072
  async execute(_toolCallId, params, _signal, _onUpdate, context) {
866
1073
  const teamName = compactName(params.team);
867
- if (teams.has(teamName)) throw new Error(`Team already exists: ${teamName}`);
868
1074
  const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
869
1075
  const herdrTabId = showOnHerdrPanes ? await validateHerdrAvailability() : undefined;
870
1076
 
@@ -878,24 +1084,43 @@ export default function (pi: ExtensionAPI) {
878
1084
  const inheritsMainContext = teammateSpecs.some((teammate) => Boolean(teammate.inheritContext));
879
1085
  const mainSessionFile = inheritsMainContext ? context.sessionManager.getSessionFile() : undefined;
880
1086
  if (inheritsMainContext && !mainSessionFile) throw new Error("inheritContext requires a persistent main session");
1087
+ const originMainSessionId = context.sessionManager?.getSessionId?.();
1088
+ const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1089
+ const projectDirectory = rawProjectDirectory ? canonicalProjectDirectory(rawProjectDirectory) : undefined;
1090
+ const teamId = originMainSessionId && projectDirectory ? `${originMainSessionId}-${teamName}` : undefined;
1091
+ const runtimeTeamId = teamId ?? teamName;
1092
+ if (teams.has(runtimeTeamId)) throw new Error(`Team already exists: ${runtimeTeamId}`);
1093
+ const lease = teamId ? claimTeamLease(teamId, originMainSessionId) : undefined;
1094
+ if (teamId && projectDirectory && listTeamManifests(projectDirectory).some((manifest) => manifest.id === teamId)) {
1095
+ releaseTeamLease(lease!);
1096
+ throw new Error(`Team already exists: ${teamId}. Use team_resume.`);
1097
+ }
881
1098
  sessionTeammateRoster.push(...teammateNames.filter((teammateName) => !sessionTeammateRoster.includes(teammateName)));
882
- await ensureCallbackServer();
1099
+ try {
1100
+ await ensureCallbackServer();
1101
+ } catch (error) {
1102
+ if (lease) releaseTeamLease(lease);
1103
+ throw error;
1104
+ }
883
1105
 
884
1106
  const team: TeamState = {
885
1107
  owner,
886
1108
  ownerPi: pi,
1109
+ id: teamId,
887
1110
  name: teamName,
1111
+ projectDirectory,
888
1112
  showOnHerdrPanes,
889
1113
  teamPrompt: params.teamPrompt,
890
1114
  mainSessionFile,
891
1115
  members: new Map(),
892
1116
  statuses: new Map([["main", status("available", "Main agent")]]),
893
1117
  created: nowText(),
1118
+ lease,
894
1119
  log: [],
895
1120
  nextLogSequence: 1,
896
1121
  };
897
1122
 
898
- teams.set(teamName, team);
1123
+ teams.set(runtimeTeamId, team);
899
1124
  try {
900
1125
  for (const teammateSpec of teammateSpecs) {
901
1126
  const teammate = createTeammateState(team, teammateSpec);
@@ -903,6 +1128,25 @@ export default function (pi: ExtensionAPI) {
903
1128
  team.statuses.set(teammate.name, status("idle", "Spawned"));
904
1129
  await startTeammate(team, teammate, teammateNames, herdrTabId);
905
1130
  }
1131
+
1132
+ if (teamId && originMainSessionId && projectDirectory) {
1133
+ const timestamp = new Date().toISOString();
1134
+ const manifest: TeamManifest = {
1135
+ version: 1,
1136
+ id: teamId,
1137
+ name: team.name,
1138
+ originMainSessionId,
1139
+ projectDirectory,
1140
+ teamPrompt: team.teamPrompt,
1141
+ showOnHerdrPanes: team.showOnHerdrPanes,
1142
+ members: [...team.members.values()].map(manifestMemberFromTeammate),
1143
+ state: "active",
1144
+ createdAt: timestamp,
1145
+ updatedAt: timestamp,
1146
+ };
1147
+ writeTeamManifest(manifest);
1148
+ team.manifest = manifest;
1149
+ }
906
1150
  } catch (error) {
907
1151
  await shutdownTeam(team);
908
1152
  closeCallbackServerIfUnused();
@@ -910,8 +1154,14 @@ export default function (pi: ExtensionAPI) {
910
1154
  }
911
1155
  return toolResult({
912
1156
  accepted: true,
1157
+ id: team.id,
913
1158
  team: team.name,
914
1159
  teammates: [...team.members.keys()],
1160
+ sessions: Object.fromEntries(
1161
+ [...team.members.values()]
1162
+ .filter((teammate) => teammate.sessionId && teammate.sessionFile)
1163
+ .map((teammate) => [teammate.name, { sessionId: teammate.sessionId, sessionFile: teammate.sessionFile }]),
1164
+ ),
915
1165
  status: formatStatus(team),
916
1166
  instruction: bundledAiToAiSkillInstruction,
917
1167
  });
@@ -920,6 +1170,212 @@ export default function (pi: ExtensionAPI) {
920
1170
  );
921
1171
  });
922
1172
 
1173
+ pi.registerTool(
1174
+ defineTool({
1175
+ name: "team_list",
1176
+ label: "Team List",
1177
+ description: "List active and dormant teams for the current project.",
1178
+ promptSnippet: "List teams for the current project",
1179
+ parameters: Type.Object({}),
1180
+ async execute(_toolCallId, _params, _signal, _onUpdate, context) {
1181
+ const projectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1182
+ if (!projectDirectory) throw new Error("team_list requires a project directory");
1183
+ const manifests = listTeamManifests(projectDirectory);
1184
+ return toolResult({
1185
+ teams: manifests.map((manifest) => {
1186
+ const liveTeam = teams.get(manifest.id);
1187
+ return {
1188
+ id: manifest.id,
1189
+ name: manifest.name,
1190
+ state: manifest.state,
1191
+ leaseState: readTeamLeaseState(manifest.id).state,
1192
+ teammates: manifest.members.map((member) => member.name),
1193
+ members: manifest.members.map((member) => ({
1194
+ name: member.name,
1195
+ live: liveTeam?.members.get(member.name)?.alive ?? member.live,
1196
+ sessionId: member.sessionId,
1197
+ sessionFile: member.sessionFile,
1198
+ })),
1199
+ createdAt: manifest.createdAt,
1200
+ updatedAt: manifest.updatedAt,
1201
+ shutdownAt: manifest.shutdownAt,
1202
+ expiresAt: manifest.expiresAt,
1203
+ };
1204
+ }),
1205
+ });
1206
+ },
1207
+ }),
1208
+ );
1209
+
1210
+ pi.registerTool(
1211
+ defineTool({
1212
+ name: "team_resume",
1213
+ label: "Team Resume",
1214
+ description: "Resume all stopped teammates in a dormant current-project team, or only selected stopped teammates.",
1215
+ promptSnippet: "Resume all or selected stopped teammates",
1216
+ parameters: Type.Object({
1217
+ team: Type.String({ description: "Persistent team ID" }),
1218
+ teammates: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description: "Stopped teammate names. Omit to resume all stopped teammates." })),
1219
+ showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false, description: "Resume selected teammates in visible Herdr panes. Defaults to RPC." })),
1220
+ }),
1221
+ async execute(_toolCallId, params, _signal, _onUpdate, context) {
1222
+ const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1223
+ if (!rawProjectDirectory) throw new Error("team_resume requires a project directory");
1224
+ const manifest = listTeamManifests(rawProjectDirectory).find((candidate) => candidate.id === params.team);
1225
+ if (!manifest) throw new Error(`Unknown current-project team: ${params.team}`);
1226
+ const requestedNames = params.teammates?.map(compactName) ?? manifest.members.map((member) => member.name);
1227
+ const duplicateNames = requestedNames.filter((name, index) => requestedNames.indexOf(name) !== index);
1228
+ if (duplicateNames.length > 0) throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
1229
+ const manifestMemberNames = new Set(manifest.members.map((member) => member.name));
1230
+ const missingNames = requestedNames.filter((name) => !manifestMemberNames.has(name));
1231
+ if (missingNames.length > 0) throw new Error(`Unknown teammate(s) in ${manifest.name}: ${missingNames.join(", ")}`);
1232
+ const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
1233
+ const herdrTabId = showOnHerdrPanes ? await validateHerdrAvailability() : undefined;
1234
+
1235
+ const existingTeam = [...teams.values()].find((candidate) => candidate.id === manifest.id);
1236
+ if (existingTeam && existingTeam.owner !== owner) {
1237
+ throw new Error(`Team ${manifest.id} is already owned by another main session`);
1238
+ }
1239
+
1240
+ let team = existingTeam;
1241
+ if (!team) {
1242
+ const mainSessionId = context.sessionManager?.getSessionId?.();
1243
+ if (!mainSessionId) throw new Error("team_resume requires a persistent main session");
1244
+ const lease = claimTeamLease(manifest.id, mainSessionId);
1245
+ try {
1246
+ await ensureCallbackServer();
1247
+ team = restoreTeamState(owner, pi, manifest, lease);
1248
+ teams.set(team.id!, team);
1249
+ } catch (error) {
1250
+ releaseTeamLease(lease);
1251
+ closeCallbackServerIfUnused();
1252
+ throw error;
1253
+ }
1254
+ }
1255
+
1256
+ const teammates = requestedNames.map((name) => team.members.get(name)!).filter((teammate) => !teammate.alive);
1257
+ let starts: Array<{ teammate: TeammateState; sessionFile: string | undefined }>;
1258
+ try {
1259
+ starts = teammates.map((teammate) => ({ teammate, sessionFile: sessionFileForResume(teammate) }));
1260
+ } catch (error) {
1261
+ if (!existingTeam) {
1262
+ await shutdownTeam(team);
1263
+ closeCallbackServerIfUnused();
1264
+ }
1265
+ throw error;
1266
+ }
1267
+ const participantNames = [...team.members.keys()];
1268
+ sessionTeammateRoster.push(...participantNames.filter((name) => !sessionTeammateRoster.includes(name)));
1269
+
1270
+ try {
1271
+ for (const { teammate, sessionFile } of starts) {
1272
+ if (showOnHerdrPanes) prepareVisibleTeammate(teammate);
1273
+ else teammate.transport = "rpc";
1274
+ await startTeammate(team, teammate, participantNames, herdrTabId, {
1275
+ sessionFile,
1276
+ restartEmpty: sessionFile === undefined,
1277
+ });
1278
+ team.statuses.set(teammate.name, status("idle", "Resumed"));
1279
+ }
1280
+ persistActiveTeamManifest(team);
1281
+ } catch (error) {
1282
+ if (!existingTeam) {
1283
+ await shutdownTeam(team);
1284
+ closeCallbackServerIfUnused();
1285
+ throw error;
1286
+ }
1287
+ for (const { teammate } of starts) {
1288
+ if (teammate.transport === "herdr") {
1289
+ teammate.alive = false;
1290
+ await closeVisiblePane(teammate);
1291
+ } else {
1292
+ await stopRpcTeammate(teammate);
1293
+ }
1294
+ team.statuses.set(teammate.name, status("stopped", "Resume failed"));
1295
+ }
1296
+ throw error;
1297
+ }
1298
+
1299
+ return toolResult({
1300
+ accepted: true,
1301
+ id: team.id,
1302
+ team: team.name,
1303
+ resumed: starts.map(({ teammate }) => teammate.name),
1304
+ sessions: Object.fromEntries(
1305
+ starts.map(({ teammate }) => [teammate.name, { sessionId: teammate.sessionId, sessionFile: teammate.sessionFile }]),
1306
+ ),
1307
+ });
1308
+ },
1309
+ }),
1310
+ );
1311
+
1312
+ pi.registerTool(
1313
+ defineTool({
1314
+ name: "team_add",
1315
+ label: "Team Add",
1316
+ description: "Add one or more new RPC teammates to a running team owned by this main session.",
1317
+ promptSnippet: "Add new teammates to a running team",
1318
+ parameters: Type.Object({
1319
+ team: Type.String({ description: "Persistent team ID" }),
1320
+ teammates: Type.Array(teammateSchema(""), { minItems: 1, description: "New teammates to add" }),
1321
+ }),
1322
+ async execute(_toolCallId, params, _signal, _onUpdate, context) {
1323
+ const team = [...teams.values()].find((candidate) => candidate.id === params.team && candidate.owner === owner);
1324
+ if (!team || !team.manifest || !team.lease || team.manifest.state !== "active") {
1325
+ throw new Error(`team_add requires a running team owned by this main session: ${params.team}`);
1326
+ }
1327
+
1328
+ const teammateSpecs = params.teammates as TeammateSpec[];
1329
+ const teammateNames = teammateSpecs.map((teammate) => compactName(teammate.name));
1330
+ const duplicateNames = teammateNames.filter(
1331
+ (name, index) => teammateNames.indexOf(name) !== index || team.members.has(name),
1332
+ );
1333
+ if (duplicateNames.length > 0) {
1334
+ throw new Error(`Duplicate teammate name(s): ${[...new Set(duplicateNames)].join(", ")}`);
1335
+ }
1336
+ if (teammateNames.includes("main")) throw new Error('"main" is reserved');
1337
+ validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
1338
+
1339
+ const inheritsMainContext = teammateSpecs.some((teammate) => Boolean(teammate.inheritContext));
1340
+ const mainSessionFile = inheritsMainContext ? context.sessionManager.getSessionFile() : undefined;
1341
+ if (inheritsMainContext && !mainSessionFile) throw new Error("inheritContext requires a persistent main session");
1342
+ if (mainSessionFile) team.mainSessionFile = mainSessionFile;
1343
+
1344
+ const addedTeammates = teammateSpecs.map((teammateSpec) => createTeammateState(team, teammateSpec));
1345
+ for (const teammate of addedTeammates) {
1346
+ teammate.transport = "rpc";
1347
+ team.members.set(teammate.name, teammate);
1348
+ team.statuses.set(teammate.name, status("idle", "Spawned"));
1349
+ }
1350
+ const participantNames = [...team.members.keys()];
1351
+ sessionTeammateRoster.push(...teammateNames.filter((name) => !sessionTeammateRoster.includes(name)));
1352
+
1353
+ try {
1354
+ for (const teammate of addedTeammates) await startTeammate(team, teammate, participantNames);
1355
+ persistActiveTeamManifest(team);
1356
+ } catch (error) {
1357
+ for (const teammate of addedTeammates) await stopRpcTeammate(teammate);
1358
+ for (const teammate of addedTeammates) {
1359
+ team.members.delete(teammate.name);
1360
+ team.statuses.delete(teammate.name);
1361
+ }
1362
+ throw error;
1363
+ }
1364
+
1365
+ return toolResult({
1366
+ accepted: true,
1367
+ id: team.id,
1368
+ team: team.name,
1369
+ added: teammateNames,
1370
+ sessions: Object.fromEntries(
1371
+ addedTeammates.map((teammate) => [teammate.name, { sessionId: teammate.sessionId, sessionFile: teammate.sessionFile }]),
1372
+ ),
1373
+ status: formatStatus(team),
1374
+ });
1375
+ },
1376
+ }),
1377
+ );
1378
+
923
1379
  pi.registerTool(
924
1380
  defineTool({
925
1381
  name: "teamsend",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "1.0.21",
3
+ "version": "1.0.22",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",
package/system-prompt.ts CHANGED
@@ -9,7 +9,7 @@ export function composeSystemPrompt(teamName: string, teamPrompt: string, teamma
9
9
  `Participants: main, ${participants.join(", ")}.`,
10
10
  "Use teamsend to talk to teammates, teammain to talk to the main agent, and teamstatus to set/read public statuses.",
11
11
  "From the sender’s point of view, teamsend is fire-and-forget. From the recipient’s point of view, the message is pushed to context as soon as possible.",
12
- "Main agent sees the big picture and has been aware of the team’s actions and status updates since the team was created.",
12
+ "The main agent is the current coordinator. Use the team tools and available session history to share relevant context.",
13
13
  "As soon as you wake up, call teamstatus to acknowledge that you received your instructions before doing substantive work.",
14
14
  "Whenever you receive a message from main or a teammate, call teamstatus first to acknowledge that specific message, then proceed.",
15
15
  "Never set a waiting status until after you have sent the teammate you are waiting for a teamsend describing exactly what you need from them.",
@@ -0,0 +1,300 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+
5
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+
7
+ export interface TeamManifestMember {
8
+ name: string;
9
+ prompt: string;
10
+ model: string;
11
+ thinking: string;
12
+ inheritContext: boolean;
13
+ transport: "rpc" | "herdr";
14
+ live: boolean;
15
+ sessionId: string;
16
+ sessionFile: string;
17
+ sessionMaterialized: boolean;
18
+ }
19
+
20
+ export interface TeamManifest {
21
+ version: 1;
22
+ id: string;
23
+ name: string;
24
+ originMainSessionId: string;
25
+ projectDirectory: string;
26
+ teamPrompt: string;
27
+ showOnHerdrPanes: boolean;
28
+ members: TeamManifestMember[];
29
+ state: "active" | "dormant";
30
+ createdAt: string;
31
+ updatedAt: string;
32
+ shutdownAt?: string;
33
+ expiresAt?: string;
34
+ }
35
+
36
+ export interface TeamLease {
37
+ version: 1;
38
+ teamId: string;
39
+ mainSessionId: string;
40
+ processId: number;
41
+ token: string;
42
+ claimedAt: string;
43
+ }
44
+
45
+ export const dormantManifestRetentionMilliseconds = 30 * 24 * 60 * 60 * 1_000;
46
+
47
+ function manifestsDirectory(): string {
48
+ return path.join(getAgentDir(), "pi-simple-team", "teams");
49
+ }
50
+
51
+ /** @example canonicalProjectDirectory(".") // absolute real path */
52
+ export function canonicalProjectDirectory(projectDirectory: string): string {
53
+ return fs.realpathSync(path.resolve(projectDirectory));
54
+ }
55
+
56
+ function encodedTeamPath(teamId: string, suffix: string): string {
57
+ return path.join(manifestsDirectory(), `${encodeURIComponent(teamId)}${suffix}`);
58
+ }
59
+
60
+ function manifestPath(teamId: string): string {
61
+ return encodedTeamPath(teamId, ".json");
62
+ }
63
+
64
+ function leasePath(teamId: string): string {
65
+ return encodedTeamPath(teamId, ".lease");
66
+ }
67
+
68
+ function leaseClaimLockPath(teamId: string): string {
69
+ return encodedTeamPath(teamId, ".lease-claim-lock");
70
+ }
71
+
72
+ function isManifestMember(value: unknown): value is TeamManifestMember {
73
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
74
+ const member = value as Record<string, unknown>;
75
+ return (
76
+ typeof member.name === "string" &&
77
+ typeof member.prompt === "string" &&
78
+ typeof member.model === "string" &&
79
+ typeof member.thinking === "string" &&
80
+ typeof member.inheritContext === "boolean" &&
81
+ (member.transport === "rpc" || member.transport === "herdr") &&
82
+ typeof member.live === "boolean" &&
83
+ typeof member.sessionId === "string" &&
84
+ typeof member.sessionFile === "string" &&
85
+ typeof member.sessionMaterialized === "boolean"
86
+ );
87
+ }
88
+
89
+ function parseManifest(filePath: string): TeamManifest {
90
+ const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf8"));
91
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
92
+ throw new Error(`Invalid team manifest: ${filePath}`);
93
+ }
94
+
95
+ const manifest = parsed as Record<string, unknown>;
96
+ const validState = manifest.state === "active" || manifest.state === "dormant";
97
+ if (
98
+ manifest.version !== 1 ||
99
+ typeof manifest.id !== "string" ||
100
+ typeof manifest.name !== "string" ||
101
+ typeof manifest.originMainSessionId !== "string" ||
102
+ typeof manifest.projectDirectory !== "string" ||
103
+ typeof manifest.teamPrompt !== "string" ||
104
+ typeof manifest.showOnHerdrPanes !== "boolean" ||
105
+ !Array.isArray(manifest.members) ||
106
+ !manifest.members.every(isManifestMember) ||
107
+ !validState ||
108
+ typeof manifest.createdAt !== "string" ||
109
+ typeof manifest.updatedAt !== "string" ||
110
+ (manifest.shutdownAt !== undefined && typeof manifest.shutdownAt !== "string") ||
111
+ (manifest.expiresAt !== undefined && typeof manifest.expiresAt !== "string")
112
+ ) {
113
+ throw new Error(`Invalid team manifest: ${filePath}`);
114
+ }
115
+
116
+ return manifest as unknown as TeamManifest;
117
+ }
118
+
119
+ function parseLease(filePath: string): TeamLease {
120
+ const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf8"));
121
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
122
+ throw new Error(`Invalid team lease: ${filePath}`);
123
+ }
124
+ const lease = parsed as Record<string, unknown>;
125
+ if (
126
+ lease.version !== 1 ||
127
+ typeof lease.teamId !== "string" ||
128
+ typeof lease.mainSessionId !== "string" ||
129
+ typeof lease.processId !== "number" ||
130
+ typeof lease.token !== "string" ||
131
+ typeof lease.claimedAt !== "string"
132
+ ) {
133
+ throw new Error(`Invalid team lease: ${filePath}`);
134
+ }
135
+ return lease as unknown as TeamLease;
136
+ }
137
+
138
+ function processIsAlive(processId: number): boolean {
139
+ try {
140
+ process.kill(processId, 0);
141
+ return true;
142
+ } catch (error) {
143
+ return (error as NodeJS.ErrnoException).code !== "ESRCH";
144
+ }
145
+ }
146
+
147
+ export function writeTeamManifest(manifest: TeamManifest): void {
148
+ const directory = manifestsDirectory();
149
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
150
+ const filePath = manifestPath(manifest.id);
151
+ const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
152
+ fs.writeFileSync(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
153
+ fs.renameSync(temporaryPath, filePath);
154
+ }
155
+
156
+ export function listTeamManifests(projectDirectory: string): TeamManifest[] {
157
+ const directory = manifestsDirectory();
158
+ if (!fs.existsSync(directory)) return [];
159
+
160
+ const resolvedProjectDirectory = canonicalProjectDirectory(projectDirectory);
161
+ const now = Date.now();
162
+ return fs
163
+ .readdirSync(directory, { withFileTypes: true })
164
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
165
+ .map((entry) => ({ filePath: path.join(directory, entry.name), manifest: parseManifest(path.join(directory, entry.name)) }))
166
+ .filter(({ filePath, manifest }) => {
167
+ const expiresAt = Date.parse(manifest.expiresAt ?? "");
168
+ const shutdownAt = Date.parse(manifest.shutdownAt ?? "");
169
+ const expired = manifest.state === "dormant" && (
170
+ Number.isFinite(expiresAt)
171
+ ? now >= expiresAt
172
+ : now - shutdownAt >= dormantManifestRetentionMilliseconds
173
+ );
174
+ if (!expired) return true;
175
+ fs.rmSync(leasePath(manifest.id), { force: true });
176
+ fs.rmSync(filePath);
177
+ return false;
178
+ })
179
+ .map(({ manifest }) => manifest)
180
+ .filter((manifest) => manifest.projectDirectory === resolvedProjectDirectory)
181
+ .sort((left, right) => left.id.localeCompare(right.id));
182
+ }
183
+
184
+ export function readTeamLeaseState(teamId: string): { state: "unclaimed" | "claimed" | "stale"; mainSessionId?: string } {
185
+ let lease: TeamLease;
186
+ try {
187
+ lease = parseLease(leasePath(teamId));
188
+ } catch (error) {
189
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { state: "unclaimed" };
190
+ throw error;
191
+ }
192
+ return {
193
+ state: processIsAlive(lease.processId) ? "claimed" : "stale",
194
+ mainSessionId: lease.mainSessionId,
195
+ };
196
+ }
197
+
198
+ function markAbandonedTeamDormant(teamId: string): void {
199
+ let manifest: TeamManifest;
200
+ try {
201
+ manifest = parseManifest(manifestPath(teamId));
202
+ } catch (error) {
203
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
204
+ throw error;
205
+ }
206
+ if (manifest.state !== "active") return;
207
+
208
+ const shutdownAt = new Date().toISOString();
209
+ writeTeamManifest({
210
+ ...manifest,
211
+ members: manifest.members.map((member) => ({ ...member, live: false })),
212
+ state: "dormant",
213
+ updatedAt: shutdownAt,
214
+ shutdownAt,
215
+ expiresAt: new Date(Date.parse(shutdownAt) + dormantManifestRetentionMilliseconds).toISOString(),
216
+ });
217
+ }
218
+
219
+ function claimTeamLeaseUnderLock(teamId: string, mainSessionId: string): TeamLease {
220
+ const filePath = leasePath(teamId);
221
+ const lease: TeamLease = {
222
+ version: 1,
223
+ teamId,
224
+ mainSessionId,
225
+ processId: process.pid,
226
+ token: randomUUID(),
227
+ claimedAt: new Date().toISOString(),
228
+ };
229
+
230
+ let recoveredStaleLease = false;
231
+ while (true) {
232
+ try {
233
+ fs.writeFileSync(filePath, `${JSON.stringify(lease, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
234
+ if (recoveredStaleLease) {
235
+ try {
236
+ markAbandonedTeamDormant(teamId);
237
+ } catch (error) {
238
+ releaseTeamLease(lease);
239
+ throw error;
240
+ }
241
+ }
242
+ return lease;
243
+ } catch (error) {
244
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
245
+ }
246
+
247
+ let existingLease: TeamLease;
248
+ try {
249
+ existingLease = parseLease(filePath);
250
+ } catch (error) {
251
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
252
+ throw error;
253
+ }
254
+ if (processIsAlive(existingLease.processId)) {
255
+ throw new Error(`Team ${teamId} is already owned by main session ${existingLease.mainSessionId}`);
256
+ }
257
+
258
+ let currentLease: TeamLease;
259
+ try {
260
+ currentLease = parseLease(filePath);
261
+ } catch (error) {
262
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
263
+ throw error;
264
+ }
265
+ if (currentLease.token !== existingLease.token) continue;
266
+
267
+ recoveredStaleLease = true;
268
+ fs.unlinkSync(filePath);
269
+ }
270
+ }
271
+
272
+ export function claimTeamLease(teamId: string, mainSessionId: string): TeamLease {
273
+ fs.mkdirSync(manifestsDirectory(), { recursive: true, mode: 0o700 });
274
+ const lockPath = leaseClaimLockPath(teamId);
275
+ try {
276
+ fs.mkdirSync(lockPath, { mode: 0o700 });
277
+ } catch (error) {
278
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
279
+ throw new Error(`Team ${teamId} lease claim is already in progress`);
280
+ }
281
+
282
+ try {
283
+ return claimTeamLeaseUnderLock(teamId, mainSessionId);
284
+ } finally {
285
+ fs.rmdirSync(lockPath);
286
+ }
287
+ }
288
+
289
+ export function releaseTeamLease(lease: TeamLease): void {
290
+ const filePath = leasePath(lease.teamId);
291
+ let currentLease: TeamLease;
292
+ try {
293
+ currentLease = parseLease(filePath);
294
+ } catch (error) {
295
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
296
+ throw error;
297
+ }
298
+ if (currentLease.token !== lease.token) return;
299
+ fs.unlinkSync(filePath);
300
+ }