@giladbarnea/pi-simple-team 1.0.23 → 1.0.25

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
@@ -15,7 +15,7 @@
15
15
 
16
16
  **No roles. No org chart. No mailboxes. No routing rules.**
17
17
 
18
- `pi-simple-team` spawns a flat team of Pi agents that can all talk to each other, like the responsible adults they are, **and then stays out of the way.**
18
+ `pi-simple-team` spawns a small team of Pi agents that can all talk to each other, like the responsible adults they are, **and then stays out of the way.**
19
19
 
20
20
  </div>
21
21
 
@@ -24,7 +24,7 @@
24
24
 
25
25
  ## Why
26
26
 
27
- I've always done my best work in a small room with a few capable people, building something together.
27
+ I did my best work in a small room, together with a bunch of very capable people.
28
28
 
29
29
  > <span style="color:grey">_[shouts]_</span> Has anyone figured out how to set up auth yet?
30
30
 
@@ -36,24 +36,18 @@ Not scheduling a meeting.
36
36
 
37
37
  **That's the whole design. Not a swarm, not a company. *A room.***
38
38
 
39
+ ## Install
40
+
41
+ ```sh
42
+ pi install npm:@giladbarnea/pi-simple-team
43
+ ```
44
+
39
45
  ## Using `pi-simple-team`
40
46
 
41
47
  Tell your main agent:
42
48
  > Spawn a team.
43
49
 
44
- ### Watch a live team with `/team`.
45
-
46
- `/team` is for you, not another agent tool. It gives you a live view of the room without turning the main agent into a status relay.
47
-
48
- The command opens a read-only overlay with recent statuses, messages, and a separate event log. With no teams, it shows an empty state. With one team, it opens that team directly. With several teams, it starts with a selector.
49
-
50
- The fixed layout keeps the latest content in view as work arrives, without scrolling or jumping around. It is an overview of the room, not a teammate drill-down or transcript.
51
-
52
- ### Throw a team at something hard.
53
-
54
- The team takes the shape of the mission.
55
-
56
- **Basic example: adversarial pair**
50
+ That's it. The team takes the shape of the mission:
57
51
 
58
52
  You:
59
53
  > Create an implementer-reviewer team to complete `PLAN.md`.
@@ -63,60 +57,16 @@ Main agent:
63
57
 
64
58
  <br>
65
59
 
66
- **Better example: build an agentic graph**
67
-
68
- You:
69
- > **Team goal:**
70
- > 1. map out all customer–product money streams in the database.
71
- > 2. Feed this knowledge into the harness.
72
- > 3. Then prove the data analysis agent passes the new evals.
73
- >
74
- > **Note:**
75
- > - #1 and #3 are _loops._ Call them `1-map` and `3-eval`.
76
- > - `1-map` and `3-eval` each gets a teamate.
77
- > - Each teammate spawns _its own team_ to loop on its task.
78
-
79
- <br>
80
-
81
- <center>
82
- <b>Because</b> it does nothing specially, <code>pi-simple-team</code> can construct any topography you wish it to.
83
- </center>
84
- <br>
85
- That prompt gives you this graph:
86
-
87
- ```mermaid
88
- flowchart LR
89
- subgraph map["1-map: map the money streams"]
90
- scout["`**Scout**
91
- Runs repeatedly to clear
92
- out the fog of war.`"] <--> advocate["`**Devil’s advocate**
93
- Points out what we
94
- still don’t know.`"]
95
- end
96
-
97
- harness["`**2: subagent dispatch**
98
- Feeds new understanding
99
- into the harness.`"]
100
-
101
- subgraph eval["3-eval: hill-climb the evals"]
102
- engineer["`**Engineer**
103
- Improves the harness.`"] <--> watcher["`**Performance watcher**
104
- Suggests a fresh approach
105
- when stuck. `"]
106
- end
107
-
108
- map --> harness --> eval
109
- ```
60
+ ![Spawning a designer–adversary team, checking its status, and sending both teammates a shared instruction](screenshots/1.png)
110
61
 
111
- <br>
62
+ <div align="center"><em><code>pi-simple-team</code> in the TUI.</em></div>
112
63
 
113
- ---
64
+ ### Watch a live team with `/team`.
114
65
 
115
- <br>
66
+ `/team` is for you, not another agent tool. It gives you a live view of the room without turning the main agent into a status relay.
116
67
 
117
- ![Spawning a designer–adversary team, checking its status, and sending both teammates a shared instruction](screenshots/1.png)
68
+ The command opens an overlay rolling recent statuses, messages, and a separate event log.
118
69
 
119
- <div align="center"><em><code>pi-simple-team</code> in the TUI.</em></div>
120
70
 
121
71
  ## The mechanics
122
72
 
@@ -124,15 +74,15 @@ when stuck. `"]
124
74
 
125
75
  Tokens, intelligence and time are never wasted on busy-polling for messages.
126
76
 
127
- Instead, `pi-simple-team` pushes messages to the receipients.
77
+ Instead, `pi-simple-team` pushes messages to the recipients.
128
78
 
129
79
  This is both efficient and effective:
130
80
 
131
81
  - ✔ No inbox to forget.
132
82
  - ✔ Context window stays lean.
133
- - ✔ Unlocks teams doing arbitrary workflows.
83
+ - ✔ Unlocks arbitrary workflows.
134
84
 
135
- *{screenshot of Codex filling up the entire visible chat with countless* `Waiting agents to finish...`*}*
85
+ *{ironic screenshot of Codex filling up the entire visible chat with countless* `Waiting agents to finish...`*}*
136
86
 
137
87
  ### ⚡ Messages arrive _fast_.
138
88
 
@@ -143,11 +93,11 @@ This is both efficient and effective:
143
93
 
144
94
  Teammates publish a one-liner:
145
95
 
146
- > <span style="color:grey">implementer  </span> Done, 89 tests green, awaiting review.
96
+ > <span style="color:grey">implementer </span> Done, 89 tests green, awaiting review.
147
97
 
148
- > <span style="color:grey">reviewer      </span> Reading implementation, will finalize review in a few minutes.
98
+ > <span style="color:grey">reviewer </span> Reading implementation, will finalize review in a few minutes.
149
99
 
150
- Your main agent calls `teamstatus` and understands exactly what's going on. Main doesn't ask and clutter the teammates' context.
100
+ Your main agent calls `teamstatus` and understands exactly what is going on. Main does not ask teammates for updates or clutter their context.
151
101
 
152
102
  ### 🌡️ Context window self-awareness
153
103
 
@@ -155,21 +105,21 @@ Teammates know how much free context they have left.
155
105
 
156
106
  Main agent knows its own and everyone else's too.
157
107
 
108
+ They will hand off work on their own when it's time to say goodbye.
109
+
110
+ You can stop babysitting everyone's context window.
111
+
158
112
  ### 📣 Interrupts, when justified.
159
113
 
160
- > _Situation: Late afternoon. Team has finished a production hotfix and started to wrap up._
114
+ > _Situation: Late afternoon. Team finished production hotfix and started wrap up. There is one problem though._
161
115
 
162
116
  - 17:32:00: Security scout spots a private SSH key not covered by `.gitignore`.
163
- - 17:32:01: Release teammate sets status: "Ran `git add .`, preparing commit and push."
117
+ - 17:32:01: Release teammate sets status: _Ran `git add .`, preparing commit and push._
164
118
  - 17:32:02: Scout immediately interrupts. Key never leaves the machine. Developer keeps their job.
165
119
 
166
- ### 📡 Live observability without a second history.
167
-
168
- While a team runs, `teamlog` exposes a timestamped, filterable timeline of messages, tool calls, and lifecycle events.
120
+ ### 📡 Live, zero-cost observability
169
121
 
170
- That live timeline stays in parent-process memory and starts fresh after a resume. Pi session JSONL files are the canonical conversation history.
171
-
172
- `pi-simple-team` does not persist a separate parent-runtime log or duplicate `teamlog` data.
122
+ Your main uses `teamlog` when it needs to understand the chain of events in high granularity: a timestamped, filterable timeline of messages, tool calls, and lifecycle events.
173
123
 
174
124
  <br>
175
125
 
@@ -185,53 +135,68 @@ That live timeline stays in parent-process memory and starts fresh after a resum
185
135
 
186
136
  ### 🧱 Teammates are durable Pi sessions.
187
137
 
188
- 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.
138
+ A teammate is a normal Pi session with a team attachment.
189
139
 
190
- Each team ID is `{origin-main-session-id}-{team-name}`. `team_list` discovers active and dormant teams from the same canonical project directory.
140
+ This means every teammate can be resurrected, moved around teams and reused everywhere, anytime.
191
141
 
192
- `team_shutdown` stops every live runtime and leaves the team dormant. Its manifest expires after 30 days, but expiration never deletes Pi session files.
142
+ A teammate from one session can be added to a team in a later session.
193
143
 
194
- `team_resume` starts all stopped teammates by default, or only selected teammates. Resume uses RPC unless `showOnHerdrPanes` is explicitly set.
144
+ You can even `/resume` a teammate session directly if you ever want a cozy one-on-one.
195
145
 
196
- Pi creates a session path before it writes the session JSONL file. A teammate without a first assistant response therefore restarts empty.
146
+ The full lifecycle and persistence rules live in [ARCHITECTURE.md](ARCHITECTURE.md).
197
147
 
198
- A missing file that once held session history causes resume to fail. Persisted sessions restore their own model and thinking state from Pi.
148
+ ## When one room is not enough
199
149
 
200
- `team_add` creates new RPC teammates only for a running team owned by the current main session.
150
+ `pi-simple-team` supports teammates spawning and managing their own teams, one level down.
201
151
 
202
- **One Pi session can have only one live runtime.** Pi does not lock session files against concurrent writers.
152
+ This is opt-in: when spawning a team, ask main to turn this on for one (or more) teammates.
203
153
 
154
+ That teammate stays in your team and becomes main for the teams it creates, with the same tools your main agent has. The boundary is strict: it manages only teams its own session created — never its parent team, sibling teams, or their teammates.
204
155
 
205
- ## Install
156
+ A room can open another room. It does not get the keys to the whole building.
206
157
 
207
- ```sh
208
- pi install npm:@giladbarnea/pi-simple-team
209
- ```
158
+ ---
210
159
 
160
+ ## Graphs engineer themselves
211
161
 
162
+ **Because** it does nothing special, `pi-simple-team` can construct any team graph you need:
212
163
 
213
- ## Tools
164
+ You:
165
+ > **Team goal:**
166
+ > 1. Map all customer–product money streams in the database.
167
+ > 2. Feed this knowledge into the harness.
168
+ > 3. Prove the data analysis agent passes the new evals.
169
+ >
170
+ > **Note:**
171
+ > - #1 and #3 are _saturation loops._ Stop only when you can't find anything new.
172
+ > - Let teammates #1 and #3 create their own teams to loop until task is complete.
173
+
174
+ That prompt gives you this graph:
214
175
 
176
+ ![The team graph: 1-map (Scout and Devil’s advocate) feeding subagent dispatch, feeding 3-eval (Engineer and Performance watcher)](screenshots/team-graph.png)
177
+
178
+ ## Tools
215
179
 
216
180
  Kept minimal:
217
181
 
218
182
 
219
- | Role | For | Tools |
220
- | -------------- | -------------- | ---------------------------------------------------------------- |
183
+ | Role | For | Tools |
184
+ | --- | --- | --- |
221
185
  | **Main agent** | Team lifecycle | `team_spawn`, `team_list`, `team_resume`, `team_add`, `team_shutdown` |
222
- | | With team | `teamsend` |
223
- | | On team | `teamstatus`, `teamlog` |
224
- | | On everyone | `report_context_window` |
225
- | **Teammates** | With team | `teamsend` |
226
- | | With main | `teammain` |
227
- | | On self | `report_context_window` |
228
- | **Everyone** | For everyone | `teamstatus` |
186
+ | | With team | `teamsend` |
187
+ | | On team | `teamstatus`, `teamlog` |
188
+ | | On everyone | `report_context_window` |
189
+ | **Overseeing teammate** | On own teams | Same tools as the main agent |
190
+ | | With parent team | `teamsend`, `teamstatus`, `teammain` |
191
+ | **Teammates** | With team | `teamsend` |
192
+ | | With main | `teammain` |
193
+ | | On self | `report_context_window` |
194
+ | **Everyone** | For everyone | `teamstatus` |
229
195
 
230
196
 
231
197
  ---
232
198
 
233
199
 
234
-
235
200
  ## Roadmap
236
201
 
237
202
  **User involvement track:**
@@ -240,10 +205,13 @@ Kept minimal:
240
205
  - [x] `/team`: live, read-only team dashboard.
241
206
  - [ ] Teammate drill-down and transcripts.
242
207
  - [ ] Joining and steering teams from slash commands.
208
+ - [ ] Adding teammates to existing teams directly from slash commands.
243
209
  - [ ] Spawning teams directly from slash commands.
244
210
 
245
211
  **Functional:**
246
212
 
247
213
  - [x] Resume all or selected teammates from a dormant team.
248
214
  - [x] Add new teammates after a team has spawned.
215
+ - [x] Let opted-in teammates create and manage teams of their own.
249
216
  - [ ] Main forces `/compact` on select teammate.
217
+ - [ ] Teammates auto-reminded to hand off on low context.
package/child-tools.ts CHANGED
@@ -18,6 +18,7 @@ export interface ChildRuntimeConfig {
18
18
  teammateName: string;
19
19
  visible: boolean;
20
20
  participants: string[];
21
+ canOverseeOwnTeams: boolean;
21
22
  interruptWaitTimeoutMilliseconds?: number;
22
23
  }
23
24
 
@@ -46,6 +47,7 @@ function readRequiredChildRuntimeConfig(): ChildRuntimeConfig {
46
47
  teammateName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_MEMBER"),
47
48
  visible: process.env.PI_SIMPLE_TEAM_VISIBLE_CHILD === "1",
48
49
  participants: readParticipants(),
50
+ canOverseeOwnTeams: process.env.PI_SIMPLE_TEAM_CAN_OVERSEE_OWN_TEAMS === "1",
49
51
  };
50
52
  }
51
53
 
@@ -54,7 +56,7 @@ export function readChildRuntimeConfig(): ChildRuntimeConfig | undefined {
54
56
  return readRequiredChildRuntimeConfig();
55
57
  }
56
58
 
57
- async function callParent(config: ChildRuntimeConfig, tool: string, args: JsonRecord, signal?: AbortSignal): Promise<JsonRecord> {
59
+ export async function callParent(config: ChildRuntimeConfig, tool: string, args: JsonRecord, signal?: AbortSignal): Promise<JsonRecord> {
58
60
  const response = await fetch(config.callbackUrl, {
59
61
  method: "POST",
60
62
  headers: { "content-type": "application/json" },
package/index.ts CHANGED
@@ -11,7 +11,7 @@ import { bundledAiToAiSkillInstruction } from "./bundled-skill.ts";
11
11
  import { formatContextWindowReport, requireKnownContextUsage, type KnownContextUsage } from "./context-window.ts";
12
12
  import { formatScopedModelGuidance, validateTeammateModels, type ModelReference } from "./model-preflight.ts";
13
13
  import { composeSystemPrompt } from "./system-prompt.ts";
14
- import { readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
14
+ import { callParent, readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
15
15
  import {
16
16
  canonicalProjectDirectory,
17
17
  claimTeamLease,
@@ -61,6 +61,7 @@ interface TeammateSpec {
61
61
  model: string;
62
62
  thinking?: ThinkingLevel;
63
63
  inheritContext?: boolean;
64
+ canOverseeOwnTeams?: boolean;
64
65
  }
65
66
 
66
67
  type TeammateTransport = "rpc" | "herdr";
@@ -71,6 +72,7 @@ interface TeammateState {
71
72
  model: string;
72
73
  thinking: ThinkingLevel;
73
74
  inheritContext: boolean;
75
+ canOverseeOwnTeams: boolean;
74
76
  transport: TeammateTransport;
75
77
  sessionId?: string;
76
78
  sessionFile?: string;
@@ -111,6 +113,7 @@ const teamLiteExtensionPath = fileURLToPath(import.meta.url);
111
113
  const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
112
114
  const defaultThinkingLevel: ThinkingLevel = "xhigh";
113
115
  const visibleDeliveryTimeoutMilliseconds = 30_000;
116
+ const defaultRpcShutdownGraceMilliseconds = 1_000;
114
117
  const teamMessageType = "pi-simple-team";
115
118
  const teams = new Map<string, TeamState>();
116
119
  const callbackToken = crypto.randomBytes(24).toString("hex");
@@ -528,6 +531,7 @@ function createTeammateState(team: TeamState, teammateSpec: TeammateSpec): Teamm
528
531
  model: teammateSpec.model,
529
532
  thinking,
530
533
  inheritContext: Boolean(teammateSpec.inheritContext),
534
+ canOverseeOwnTeams: Boolean(teammateSpec.canOverseeOwnTeams),
531
535
  transport: team.showOnHerdrPanes ? "herdr" : "rpc",
532
536
  sessionMaterialized: false,
533
537
  visibleReady,
@@ -552,6 +556,7 @@ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, par
552
556
  PI_SIMPLE_TEAM_TEAM_NAME: team.name,
553
557
  PI_SIMPLE_TEAM_MEMBER: teammate.name,
554
558
  PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
559
+ PI_SIMPLE_TEAM_CAN_OVERSEE_OWN_TEAMS: teammate.canOverseeOwnTeams ? "1" : "0",
555
560
  };
556
561
  }
557
562
 
@@ -589,7 +594,7 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
589
594
  "--no-themes",
590
595
  ...modelArgs,
591
596
  "--system-prompt",
592
- composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants),
597
+ composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.canOverseeOwnTeams),
593
598
  ];
594
599
  const proc = childProcess.spawn("pi", args, {
595
600
  cwd: team.projectDirectory ?? process.cwd(),
@@ -649,7 +654,7 @@ async function attachVisibleTeammate(
649
654
  herdrTabId: string,
650
655
  options: RpcStartOptions,
651
656
  ): Promise<void> {
652
- const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants);
657
+ const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.canOverseeOwnTeams);
653
658
  const environment = childEnvironmentOverrides(team, teammate, participants, true);
654
659
  const sessionArgs = options.sessionFile
655
660
  ? ["--session", options.sessionFile]
@@ -718,6 +723,7 @@ function manifestMemberFromTeammate(teammate: TeammateState): TeamManifestMember
718
723
  model: teammate.model,
719
724
  thinking: teammate.thinking,
720
725
  inheritContext: teammate.inheritContext,
726
+ canOverseeOwnTeams: teammate.canOverseeOwnTeams,
721
727
  transport: teammate.transport,
722
728
  live: teammate.alive,
723
729
  sessionId: teammate.sessionId,
@@ -766,8 +772,10 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
766
772
  };
767
773
  processToStop.once("exit", resolveExit);
768
774
  processToStop.kill("SIGTERM");
769
- forceKillTimeout = setTimeout(() => processToStop.kill("SIGKILL"), 1_000);
770
- forceKillTimeout.unref();
775
+ if (!teammate.canOverseeOwnTeams) {
776
+ forceKillTimeout = setTimeout(() => processToStop.kill("SIGKILL"), defaultRpcShutdownGraceMilliseconds);
777
+ forceKillTimeout.unref();
778
+ }
771
779
  });
772
780
  teammate.process = undefined;
773
781
  }
@@ -997,6 +1005,7 @@ function teammateSchema(modelGuidance: string) {
997
1005
  model: Type.String({ description: `Canonical provider/model id for this teammate. ${modelGuidance}` }),
998
1006
  thinking: Type.Optional(StringEnum(thinkingLevels, { description: "Thinking level for this teammate. Defaults to xhigh.", default: defaultThinkingLevel })),
999
1007
  inheritContext: Type.Optional(Type.Boolean({ description: "Start from a fork of main's persisted session. The fork is taken during asynchronous child startup. Defaults to false.", default: false })),
1008
+ canOverseeOwnTeams: Type.Optional(Type.Boolean({ description: "Allow this teammate to create and manage teams of its own. Defaults to false.", default: false })),
1000
1009
  });
1001
1010
  }
1002
1011
 
@@ -1024,6 +1033,7 @@ function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, manifest: TeamMa
1024
1033
  model: member.model,
1025
1034
  thinking: member.thinking as ThinkingLevel,
1026
1035
  inheritContext: member.inheritContext,
1036
+ canOverseeOwnTeams: Boolean(member.canOverseeOwnTeams),
1027
1037
  });
1028
1038
  teammate.transport = "rpc";
1029
1039
  teammate.sessionId = member.sessionId;
@@ -1058,11 +1068,11 @@ export default function (pi: ExtensionAPI) {
1058
1068
  const childRuntimeConfig = readChildRuntimeConfig();
1059
1069
  if (childRuntimeConfig) {
1060
1070
  registerChildTools(pi, childRuntimeConfig);
1061
- return;
1071
+ if (!childRuntimeConfig.canOverseeOwnTeams) return;
1062
1072
  }
1063
1073
 
1064
1074
  const owner = Symbol("pi-simple-team-owner");
1065
- const sessionTeammateRoster: string[] = [];
1075
+ const sessionTeammateRoster = childRuntimeConfig?.participants ?? [];
1066
1076
  pi.registerMessageRenderer(teamMessageType, (message, _options, theme) => renderTeamMessage(message, theme, getMarkdownTheme(), sessionTeammateRoster));
1067
1077
 
1068
1078
  pi.registerCommand("team", {
@@ -1202,13 +1212,19 @@ export default function (pi: ExtensionAPI) {
1202
1212
  defineTool({
1203
1213
  name: "team_list",
1204
1214
  label: "Team List",
1205
- description: "List active and dormant teams for the current project.",
1215
+ description: childRuntimeConfig
1216
+ ? "List active and dormant teams created by this overseeing teammate."
1217
+ : "List active and dormant teams for the current project.",
1206
1218
  promptSnippet: "List teams for the current project",
1207
1219
  parameters: Type.Object({}),
1208
1220
  async execute(_toolCallId, _params, _signal, _onUpdate, context) {
1209
1221
  const projectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1210
1222
  if (!projectDirectory) throw new Error("team_list requires a project directory");
1211
- const manifests = listTeamManifests(projectDirectory);
1223
+ const managerSessionId = childRuntimeConfig ? context.sessionManager?.getSessionId?.() : undefined;
1224
+ if (childRuntimeConfig && !managerSessionId) throw new Error("team_list requires a persistent overseeing teammate session");
1225
+ const manifests = listTeamManifests(projectDirectory).filter(
1226
+ (manifest) => !managerSessionId || manifest.originMainSessionId === managerSessionId,
1227
+ );
1212
1228
  return toolResult({
1213
1229
  teams: manifests.map((manifest) => {
1214
1230
  const liveTeam = teams.get(manifest.id);
@@ -1221,6 +1237,7 @@ export default function (pi: ExtensionAPI) {
1221
1237
  members: manifest.members.map((member) => ({
1222
1238
  name: member.name,
1223
1239
  live: liveTeam?.members.get(member.name)?.alive ?? member.live,
1240
+ canOverseeOwnTeams: Boolean(member.canOverseeOwnTeams),
1224
1241
  sessionId: member.sessionId,
1225
1242
  sessionFile: member.sessionFile,
1226
1243
  })),
@@ -1239,7 +1256,9 @@ export default function (pi: ExtensionAPI) {
1239
1256
  defineTool({
1240
1257
  name: "team_resume",
1241
1258
  label: "Team Resume",
1242
- description: "Resume all stopped teammates in a dormant current-project team, or only selected stopped teammates.",
1259
+ description: childRuntimeConfig
1260
+ ? "Resume all or selected stopped members of a dormant team created by this overseeing teammate."
1261
+ : "Resume all stopped teammates in a dormant current-project team, or only selected stopped teammates.",
1243
1262
  promptSnippet: "Resume all or selected stopped teammates",
1244
1263
  parameters: Type.Object({
1245
1264
  team: Type.String({ description: "Persistent team ID" }),
@@ -1249,7 +1268,11 @@ export default function (pi: ExtensionAPI) {
1249
1268
  async execute(_toolCallId, params, _signal, _onUpdate, context) {
1250
1269
  const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1251
1270
  if (!rawProjectDirectory) throw new Error("team_resume requires a project directory");
1252
- const manifest = listTeamManifests(rawProjectDirectory).find((candidate) => candidate.id === params.team);
1271
+ const managerSessionId = childRuntimeConfig ? context.sessionManager?.getSessionId?.() : undefined;
1272
+ if (childRuntimeConfig && !managerSessionId) throw new Error("team_resume requires a persistent overseeing teammate session");
1273
+ const manifest = listTeamManifests(rawProjectDirectory).find(
1274
+ (candidate) => candidate.id === params.team && (!managerSessionId || candidate.originMainSessionId === managerSessionId),
1275
+ );
1253
1276
  if (!manifest) throw new Error(`Unknown current-project team: ${params.team}`);
1254
1277
  const requestedNames = params.teammates?.map(compactName) ?? manifest.members.map((member) => member.name);
1255
1278
  const duplicateNames = requestedNames.filter((name, index) => requestedNames.indexOf(name) !== index);
@@ -1408,18 +1431,27 @@ export default function (pi: ExtensionAPI) {
1408
1431
  defineTool({
1409
1432
  name: "teamsend",
1410
1433
  label: "Team Send",
1411
- description: "Send a message from main to teammate(s). Fire-and-forget; does not wait for replies. Teammates will send you messages as they deem appropriate by way of push.",
1434
+ description: childRuntimeConfig
1435
+ ? "Send to parent-team peers when team is omitted, or to teammates in an owned team when team is set. Fire-and-forget; does not wait for replies."
1436
+ : "Send a message from main to teammate(s). Fire-and-forget; does not wait for replies. Teammates will send you messages as they deem appropriate by way of push.",
1412
1437
  promptSnippet: "Send a message from main to teammate(s)",
1413
1438
  renderShell: "self",
1414
1439
  renderCall: (args, theme, context) => renderTeamToolCall("teamsend", args, theme, context, sessionTeammateRoster),
1415
1440
  renderResult: (result, options, theme, context) => renderTeamToolResult("teamsend", result, options, theme, context, getMarkdownTheme(), sessionTeammateRoster),
1416
1441
  parameters: Type.Object({
1417
- team: Type.Optional(Type.String({ description: "Team name; optional only when exactly one team exists" })),
1442
+ team: Type.Optional(Type.String({ description: childRuntimeConfig ? "Owned team name. Omit to use the parent team." : "Team name; optional only when exactly one team exists" })),
1418
1443
  to: Type.Array(Type.String(), { description: "Recipient teammate names" }),
1419
1444
  message: Type.String({ description: "Message to send" }),
1420
1445
  interrupt: Type.Optional(Type.Boolean({ description: "Abort busy recipients before delivery" })),
1421
1446
  }),
1422
- async execute(_toolCallId, params) {
1447
+ async execute(_toolCallId, params, signal) {
1448
+ if (childRuntimeConfig && !params.team) {
1449
+ return toolResult(await callParent(childRuntimeConfig, "teamsend", {
1450
+ to: params.to,
1451
+ message: params.message,
1452
+ ...(params.interrupt === undefined ? {} : { interrupt: params.interrupt }),
1453
+ }, signal));
1454
+ }
1423
1455
  const team = resolveTeam(owner, params.team);
1424
1456
  const recipients = resolveRecipients(team, params.to);
1425
1457
  const interrupt = Boolean(params.interrupt);
@@ -1433,18 +1465,26 @@ export default function (pi: ExtensionAPI) {
1433
1465
  defineTool({
1434
1466
  name: "teamstatus",
1435
1467
  label: "Team Status",
1436
- description: "Set main's status for a team and/or read team statuses.",
1468
+ description: childRuntimeConfig
1469
+ ? "Set or read parent-team status when team is omitted. Set or read an owned team's status when team is set."
1470
+ : "Set main's status for a team and/or read team statuses.",
1437
1471
  promptSnippet: "Set/read team status maps",
1438
1472
  renderShell: "self",
1439
1473
  renderCall: (args, theme, context) => renderTeamToolCall("teamstatus", args, theme, context, sessionTeammateRoster),
1440
1474
  renderResult: (result, options, theme, context) => renderTeamToolResult("teamstatus", result, options, theme, context, undefined, sessionTeammateRoster),
1441
1475
  parameters: Type.Object({
1442
- team: Type.Optional(Type.String({ description: "Team name; optional for listing all statuses or when exactly one team exists" })),
1476
+ team: Type.Optional(Type.String({ description: childRuntimeConfig ? "Owned team name. Omit to use the parent team." : "Team name; optional for listing all statuses or when exactly one team exists" })),
1443
1477
  // TODO: make gerund and phrase optionality a XOR.
1444
1478
  gerund: Type.Optional(Type.String({ description: "Set one-word gerund main status" })),
1445
1479
  phrase: Type.Optional(Type.String({ description: "Short main status verb-oriented phrase." })),
1446
1480
  }),
1447
- async execute(_toolCallId, params) {
1481
+ async execute(_toolCallId, params, signal) {
1482
+ if (childRuntimeConfig && !params.team) {
1483
+ return toolResult(await callParent(childRuntimeConfig, "teamstatus", {
1484
+ ...(params.gerund === undefined ? {} : { gerund: params.gerund }),
1485
+ ...(params.phrase === undefined ? {} : { phrase: params.phrase }),
1486
+ }, signal));
1487
+ }
1448
1488
  if (!params.team && params.gerund === undefined && params.phrase === undefined) {
1449
1489
  return toolResult({ teams: allStatuses(owner) });
1450
1490
  }
@@ -1460,12 +1500,20 @@ export default function (pi: ExtensionAPI) {
1460
1500
  defineTool({
1461
1501
  name: "report_context_window",
1462
1502
  label: "Report Context Window",
1463
- description: "Report context-window use for selected teammates and main. Main's report is always last.",
1503
+ description: childRuntimeConfig
1504
+ ? "Report your own context-window use when targets is omitted. When targets is present, report selected teammates in owned teams and yourself last."
1505
+ : "Report context-window use for selected teammates and main. Main's report is always last.",
1464
1506
  promptSnippet: "Report context-window use for selected teammates and main",
1465
1507
  parameters: Type.Object({
1466
- targets: Type.Array(Type.String({ minLength: 1 }), { description: "Teammate names. Use an empty list to report only main." }),
1508
+ targets: childRuntimeConfig
1509
+ ? Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Owned-team teammate names. Omit to report only yourself." }))
1510
+ : Type.Array(Type.String({ minLength: 1 }), { description: "Teammate names. Use an empty list to report only main." }),
1467
1511
  }),
1468
1512
  async execute(_toolCallId, params, signal, _onUpdate, context) {
1513
+ if (params.targets === undefined) {
1514
+ const text = formatContextWindowReport("You have", requireKnownContextUsage(context.getContextUsage()));
1515
+ return { content: [{ type: "text" as const, text }], details: {} };
1516
+ }
1469
1517
  const teammates = resolveContextTargets(owner, params.targets);
1470
1518
  const reports = await Promise.all(
1471
1519
  teammates.map(async (teammate) => formatContextWindowReport(`Teammate ${teammate.name} has`, await getTeammateContextUsage(teammate, signal))),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "1.0.23",
3
+ "version": "1.0.25",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -14,7 +14,7 @@ The flip side: if none of these payoffs apply, don't delegate. The anti-pattern
14
14
  - **Hivemind:** teams communicating internally in real time, as each teammate does work. Hollywood analogy: elite soldier squad or a team of spies, global channel earpieces, deployed behind enemy lines, each progresses their part, each part essential for completing the mission, global channel earpieces, consistent live updates, uncertainties surfaced to get advice, discussions to make best decisions for mission, path forward of an individual adapts in real time due to new peer finding, HQ possibly listening, warning and steering as required.
15
15
  - **De-bias:** It’s easier to spot blind spots or flaws when looking at someone else’s work (review; live or after the fact). Alternatively, sometimes a hypothesis is considered true only after it is confirmed independently by multiple actors (consensus).
16
16
 
17
- Read [`references/firstmate.md`](references/firstmate.md) when the user asks you to serve as their First Mate. See `./references/` for specific delegation shapes.
17
+ Read [`references/firstmate.md`](references/firstmate.md) when the user asks you to serve as their First Mate. Read [`references/captain.md`](references/captain.md) when the user asks you to serve as Captain of a fleet of teams. See `./references/` for specific delegation shapes.
18
18
 
19
19
  ---
20
20
 
@@ -0,0 +1,56 @@
1
+ ---
2
+ name: captain
3
+ description: Defines Gilad's admiral–captain relationship for fleet-scale delegated work. One level above firstmate.md.
4
+ last_updated: 2026-08-15
5
+ ---
6
+
7
+ # Captain
8
+
9
+ Gilad is the admiral. You are the captain.
10
+
11
+ This is the relationship defined in [`./firstmate.md`](./firstmate.md), lifted one level. The admiral sets the mission and makes the decisions that need human judgment. The captain turns the mission into a fleet and keeps the fleet coherent. A ship is one team with one first mate at its head. The fleet is your ships together.
12
+
13
+ ## Chain of command
14
+
15
+ Admiral → captain → first mates → their crews.
16
+
17
+ You speak only to first mates. Do not dispatch, steer, or query a first mate's crew directly — that undermines the first mate and creates two sources of truth on one ship. If a ship drifts, steer its first mate. Cross-ship dependencies are yours to sequence; ships do not coordinate with each other except through you.
18
+
19
+ You do not row, and you do not do a first mate's job either. The delegation parameters in firstmate.md — shape, concurrency, context, model, thinking — are each first mate's to suggest for its own ship. In a fleet, you occupy the captain seat of that document: their suggestions come to you for approval, their escalations come to you, and you answer without waking the admiral unless the answer needs human judgment.
20
+
21
+ What is yours to decide: how the mission decomposes into ships, what each ship's mission is, and what each first mate needs to know.
22
+
23
+ By default, each ship works on an independent git worktree. Confirm this with the admiral.
24
+
25
+ ## Fleet plan
26
+
27
+ You may suggest a fleet plan — how many ships, each ship's mission, what each brings back — but the admiral must approve it before you commission anyone.
28
+
29
+ The admiral sets fleet-wide policy in one line ("all first mates on model X at thinking Y, everything below them at thinking Z"). That policy, and every shape you approve for a first mate, is a contract. Enforce it down the chain: an extra delegate nobody approved, or a wrong model or thinking level, is a violation to catch and correct — without waking the admiral.
30
+
31
+ ## Commissioning a first mate
32
+
33
+ 1. Tell it to load `ai-to-ai`, the files it references, and `firstmate.md`; inform him about the chain-of-command, and that you are its captain: direction, approvals, and escalations flow between it and you.
34
+ 2. Give it the fleet's why, the slice that is its ship's mission, and the bottom-line added value the fleet needs back from it. Do not prescribe the how — the over-fitting warnings in `ai-to-ai` apply equally all the way down, including to first mates.
35
+
36
+ ## How a captain communicates with the admiral
37
+
38
+ **The admiral does not attend the session.** He is not reading your interim messages. Interim status updates go unread. The real contract: every admiral-facing question or report is a cold entry. It must re-ground from the last true common ground — the mission he gave you and the last decisions he has actually made last time you interacted — never from your previous message.
39
+
40
+ **A question must carry its own provenance.** A good admiral question states, in product terms: the progress made since last touch-point, what the fork is, the path that produced it, the options already rejected and why, and your recommendation. "May the first mate buy asset pack X?" out of the blue is a failure. "Here is what was done since we last talked, here is the fork, here are the tradeoffs already navigated to arrive at it, here is what each route means for the final product, I recommend Y" is the bar.
41
+
42
+ **If you cannot tell that story, the question goes back down, not up.** You are a translator between decks, not a relay. When a first mate's escalation is saturated with ship-internal jargon you cannot ground in product terms, ask the first mate for the missing context first. Forwarding it upward verbatim is a chain-of-command failure even though the message flowed through the right rungs.
43
+
44
+ **The escalation bar.** The chain processes at every rung: crews surface to their first mate, first mates surface to you, and you surface to the admiral only what needs human judgment. Reversible implementation tuning is yours to decide. What legitimately reaches the admiral: product-visible behavior, money, direction and scope changes, non-trivial cross-ship decisions, and blockers.
45
+
46
+ **Batch approvals.** When you expect several approvals to arrive close together — as when every first mate is drafting its shape proposal — hold them and bring one grouped request. One decision session beats three interruptions. A lone question does not wait for company.
47
+
48
+ ## Mid-flight steering
49
+
50
+ Terse steering is normal admiral behavior — "pass that down", a bare link, "yes good". Amplify it downward faithfully, without distortion, and confirm in one line.
51
+
52
+ ## Keep the fleet afloat
53
+
54
+ Your own context window should stay lean — but you are the fleet's memory, so watch it anyway. The "Keep the ship afloat" instruction in firstmate.md — including the handoff-skill instruction for delegates heading toward their cap — is each first mate's duty on its own ship. You hold the same duty one level up: the first mates are your delegates. Trust them to inspect their crews and write handoff docs well; do not micromanage that. Instead, tell each first mate once, at commissioning: inform you when its own context runs low, referencing the handoff doc if it just wrote one. Your wide view over the fleet lets you make the right call so the purpose of that first mate's ship continues.
55
+
56
+ Any memory you persist covers only your unique scope: the in-between of ships and the link to the admiral. Reference other docs; do not repeat their contents.
@@ -1,13 +1,15 @@
1
1
  ---
2
2
  name: firstmate
3
3
  description: Defines Gilad's captain–first mate relationship for delegated work.
4
- last_updated: 2026-08-05 09:47
4
+ last_updated: 2026-08-15
5
5
  ---
6
6
 
7
7
  # First Mate
8
8
 
9
9
  Gilad is the captain. You are the first mate.
10
10
 
11
+ In a fleet ([`captain.md`](captain.md)), a captain agent occupies the captain seat, and every "captain" below refers to it: your direction, approvals, and escalations flow between you and your captain, not Gilad.
12
+
11
13
  The captain sets direction and makes the decisions that need human judgment. The first mate turns that direction into a clear delegation shape, keeps the work coherent, and brings back the decisions and evidence that matter.
12
14
 
13
15
  Your fingers are delegation buttons. Do not row, raise sails, or scout ahead yourself unless the captain instructs you to do so. Delegate the operational work to subagents.
@@ -1,8 +1,6 @@
1
- <!-- name needs to change, not descriptive of actual purpose -->
1
+ # Colloquium Team
2
2
 
3
- # Thinktank Team
4
-
5
- Individually, each teammate is responsible for an orthogonal, parallel, read-only, think-heavy effort. The teammates would benefit from listening to the other teammates as they share their thoughts and findings in real time, exactly because each of them is doing its own thing. Sharing is fruitful for the same reason it’s fruitful for scientists to attend and listen to peers in scientific conferences: {some AI agent seeing this please insert the sentence i am looking for instead of this placeholder}.
3
+ Individually, each teammate is responsible for an orthogonal, parallel, read-only, think-heavy effort. The teammates would benefit from listening to the other teammates as they share their thoughts and findings in real time, exactly because each of them is doing its own thing. Sharing is fruitful for the same reason it’s fruitful for scientists to attend and listen to peers in scientific conferences: a peer’s finding from an adjacent problem updates your map of the shared terrain and reframes your own problem in ways you could not have generated from inside your own lane, at no cost to your own effort. Think of it as an open studio: everyone works on their own piece while absorbing the others’.
6
4
 
7
5
  ## Shape & Work flow
8
6
 
@@ -21,4 +19,3 @@ Examples (not an exhaustive list — infer the underlying principles and general
21
19
  ## When not to use
22
20
 
23
21
  When deliverable involves writing or editing.
24
-
package/system-prompt.ts CHANGED
@@ -1,6 +1,13 @@
1
1
  import { bundledAiToAiSkillInstruction } from "./bundled-skill.ts";
2
2
 
3
- export function composeSystemPrompt(teamName: string, teamPrompt: string, teammateName: string, teammatePrompt: string, participants: string[]): string {
3
+ export function composeSystemPrompt(
4
+ teamName: string,
5
+ teamPrompt: string,
6
+ teammateName: string,
7
+ teammatePrompt: string,
8
+ participants: string[],
9
+ canOverseeOwnTeams = false,
10
+ ): string {
4
11
  return [
5
12
  bundledAiToAiSkillInstruction,
6
13
  teamPrompt.trim(),
@@ -10,6 +17,10 @@ export function composeSystemPrompt(teamName: string, teamPrompt: string, teamma
10
17
  "Use teamsend to talk to teammates, teammain to talk to the main agent, and teamstatus to set/read public statuses.",
11
18
  "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
19
  "The main agent is the current coordinator. Use the team tools and available session history to share relevant context.",
20
+ canOverseeOwnTeams && "You can create and manage teams of your own with team_spawn, team_list, team_resume, team_add, teamsend, teamstatus, report_context_window, teamlog, and team_shutdown.",
21
+ canOverseeOwnTeams && "Your manager tools are scoped to teams created by this Pi session. They cannot manage this parent team or teams owned by other sessions.",
22
+ canOverseeOwnTeams && "For teamsend and teamstatus, omit `team` to operate on this parent team. Set `team` to operate on a team you own.",
23
+ canOverseeOwnTeams && "For report_context_window, omit `targets` to report yourself. Set `targets` to inspect teammates in teams you own.",
13
24
  "As soon as you wake up, call teamstatus to acknowledge that you received your instructions before doing substantive work.",
14
25
  "Whenever you receive a message from main or a teammate, call teamstatus first to acknowledge that specific message, then proceed.",
15
26
  "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.",
package/team-registry.ts CHANGED
@@ -10,6 +10,7 @@ export interface TeamManifestMember {
10
10
  model: string;
11
11
  thinking: string;
12
12
  inheritContext: boolean;
13
+ canOverseeOwnTeams?: boolean;
13
14
  transport: "rpc" | "herdr";
14
15
  live: boolean;
15
16
  sessionId: string;
@@ -78,6 +79,7 @@ function isManifestMember(value: unknown): value is TeamManifestMember {
78
79
  typeof member.model === "string" &&
79
80
  typeof member.thinking === "string" &&
80
81
  typeof member.inheritContext === "boolean" &&
82
+ (member.canOverseeOwnTeams === undefined || typeof member.canOverseeOwnTeams === "boolean") &&
81
83
  (member.transport === "rpc" || member.transport === "herdr") &&
82
84
  typeof member.live === "boolean" &&
83
85
  typeof member.sessionId === "string" &&
package/team-ui.ts CHANGED
@@ -141,7 +141,8 @@ function selectNewestMessageLines(groups: string[][], height: number): MessageLi
141
141
  }
142
142
 
143
143
  class TeamOverviewOverlay implements Component {
144
- private readonly selector?: SelectList;
144
+ private selector?: SelectList;
145
+ private selectorTeamNames?: string;
145
146
  private selectedTeamName?: string;
146
147
  private refreshTimer?: ReturnType<typeof setInterval>;
147
148
  private closed = false;
@@ -152,32 +153,34 @@ class TeamOverviewOverlay implements Component {
152
153
  private readonly teamSource: TeamSnapshotSource,
153
154
  private readonly done: () => void,
154
155
  ) {
155
- const teams = teamSource();
156
- this.selectedTeamName = teams.length === 1 ? teams[0]!.name : undefined;
157
- if (teams.length > 1) {
158
- const items: SelectItem[] = teams.map((team) => ({
159
- value: team.name,
160
- label: team.name,
161
- description: `${team.roster.length} teammate${team.roster.length === 1 ? "" : "s"}`,
162
- }));
163
- this.selector = new SelectList(items, this.selectorHeight(teams.length), {
164
- selectedPrefix: (text) => theme.fg("accent", text),
165
- selectedText: (text) => theme.fg("accent", text),
166
- description: (text) => theme.fg("muted", text),
167
- scrollInfo: (text) => theme.fg("dim", text),
168
- noMatch: (text) => theme.fg("warning", text),
169
- });
170
- this.selector.onSelect = (item) => {
171
- this.selectedTeamName = item.value;
172
- this.tui.requestRender();
173
- };
174
- this.selector.onCancel = this.close;
175
- }
176
-
177
156
  this.refreshTimer = setInterval(() => this.tui.requestRender(), LIVE_REFRESH_INTERVAL_MILLISECONDS);
178
157
  this.refreshTimer.unref?.();
179
158
  }
180
159
 
160
+ /** Teams can appear or vanish while the overlay is open, so the selector follows the current snapshot. */
161
+ private refreshSelector(teams: readonly TeamSnapshot[]): void {
162
+ const teamNames = teams.map((team) => team.name).join("\n");
163
+ if (this.selector && this.selectorTeamNames === teamNames) return;
164
+ this.selectorTeamNames = teamNames;
165
+ const items: SelectItem[] = teams.map((team) => ({
166
+ value: team.name,
167
+ label: team.name,
168
+ description: `${team.roster.length} teammate${team.roster.length === 1 ? "" : "s"}`,
169
+ }));
170
+ this.selector = new SelectList(items, this.selectorHeight(teams.length), {
171
+ selectedPrefix: (text) => this.theme.fg("accent", text),
172
+ selectedText: (text) => this.theme.fg("accent", text),
173
+ description: (text) => this.theme.fg("muted", text),
174
+ scrollInfo: (text) => this.theme.fg("dim", text),
175
+ noMatch: (text) => this.theme.fg("warning", text),
176
+ });
177
+ this.selector.onSelect = (item) => {
178
+ this.selectedTeamName = item.value;
179
+ this.tui.requestRender();
180
+ };
181
+ this.selector.onCancel = this.close;
182
+ }
183
+
181
184
  handleInput(data: string): void {
182
185
  if (!this.selectedTeamName && this.selector) {
183
186
  this.selector.handleInput(data);
@@ -190,10 +193,14 @@ class TeamOverviewOverlay implements Component {
190
193
  render(width: number): string[] {
191
194
  const height = Math.max(4, Math.floor(this.tui.terminal.rows * 0.9));
192
195
  const teams = this.teamSource();
196
+ if (this.selectedTeamName && !teams.some((candidate) => candidate.name === this.selectedTeamName)) this.selectedTeamName = undefined;
197
+ if (!this.selectedTeamName && teams.length === 1) this.selectedTeamName = teams[0]!.name;
193
198
  if (this.selectedTeamName) {
194
199
  const team = teams.find((candidate) => candidate.name === this.selectedTeamName)!;
195
200
  return this.dashboard(team, width, height);
196
201
  }
202
+ if (teams.length > 1) this.refreshSelector(teams);
203
+ else this.selector = undefined;
197
204
  const innerHeight = height - 2;
198
205
  return this.frame(this.content(Math.max(1, width - 4), teams).slice(0, innerHeight), width, height);
199
206
  }