@giladbarnea/pi-simple-team 1.0.22 → 1.0.24
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 +71 -22
- package/child-tools.ts +3 -1
- package/index.ts +97 -21
- package/package.json +1 -1
- package/system-prompt.ts +12 -1
- package/team-registry.ts +2 -0
- package/team-ui.ts +342 -0
package/README.md
CHANGED
|
@@ -15,7 +15,9 @@
|
|
|
15
15
|
|
|
16
16
|
**No roles. No org chart. No mailboxes. No routing rules.**
|
|
17
17
|
|
|
18
|
-
`pi-simple-team` spawns a
|
|
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
|
+
|
|
20
|
+
Each team stays flat. When the work needs another room, an opted-in teammate can now open and manage teams of its own.
|
|
19
21
|
|
|
20
22
|
</div>
|
|
21
23
|
|
|
@@ -41,6 +43,46 @@ Not scheduling a meeting.
|
|
|
41
43
|
Tell your main agent:
|
|
42
44
|
> Spawn a team.
|
|
43
45
|
|
|
46
|
+
### Give one teammate a room of its own.
|
|
47
|
+
|
|
48
|
+
Most work fits one flat team. Some work contains a second problem that needs its own people and its own coordination loop.
|
|
49
|
+
|
|
50
|
+
Set `canOverseeOwnTeams: true` when you create that teammate:
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"name": "research-lead",
|
|
55
|
+
"prompt": "Map the product domain. Create a team for the database investigation.",
|
|
56
|
+
"model": "provider/model-id",
|
|
57
|
+
"canOverseeOwnTeams": true
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
That teammate stays in the parent team and becomes main for every team it creates. It gets the same team lifecycle, messaging, status, log, and context-window tools as the original main agent.
|
|
62
|
+
|
|
63
|
+
The boundary is strict. It can manage only teams created by its own Pi session. It cannot inspect or stop its parent team, sibling teams, or their teammates. The option defaults to `false`.
|
|
64
|
+
|
|
65
|
+
```mermaid
|
|
66
|
+
flowchart LR
|
|
67
|
+
main["main"] --> A["Team A"]
|
|
68
|
+
main --> B["Team B"]
|
|
69
|
+
main --> C["Team C"]
|
|
70
|
+
A --> A1["A1 · canOverseeOwnTeams"]
|
|
71
|
+
A1 --> A1a["A1 team 1"]
|
|
72
|
+
A1 --> A1b["A1 team 2"]
|
|
73
|
+
A1 --> A1c["A1 team 3"]
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
A room can open another room. It does not get the keys to the whole building.
|
|
77
|
+
|
|
78
|
+
### Watch a live team with `/team`.
|
|
79
|
+
|
|
80
|
+
`/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.
|
|
81
|
+
|
|
82
|
+
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.
|
|
83
|
+
|
|
84
|
+
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.
|
|
85
|
+
|
|
44
86
|
### Throw a team at something hard.
|
|
45
87
|
|
|
46
88
|
The team takes the shape of the mission.
|
|
@@ -59,19 +101,19 @@ Main agent:
|
|
|
59
101
|
|
|
60
102
|
You:
|
|
61
103
|
> **Team goal:**
|
|
62
|
-
> 1.
|
|
104
|
+
> 1. Map all customer–product money streams in the database.
|
|
63
105
|
> 2. Feed this knowledge into the harness.
|
|
64
|
-
> 3.
|
|
106
|
+
> 3. Prove the data analysis agent passes the new evals.
|
|
65
107
|
>
|
|
66
108
|
> **Note:**
|
|
67
109
|
> - #1 and #3 are _loops._ Call them `1-map` and `3-eval`.
|
|
68
|
-
> - `1-map` and `3-eval` each gets a
|
|
110
|
+
> - `1-map` and `3-eval` each gets a teammate with `canOverseeOwnTeams: true`.
|
|
69
111
|
> - Each teammate spawns _its own team_ to loop on its task.
|
|
70
112
|
|
|
71
113
|
<br>
|
|
72
114
|
|
|
73
115
|
<center>
|
|
74
|
-
<b>Because</b> it does nothing
|
|
116
|
+
<b>Because</b> it does nothing special, <code>pi-simple-team</code> can construct any team graph you need.
|
|
75
117
|
</center>
|
|
76
118
|
<br>
|
|
77
119
|
That prompt gives you this graph:
|
|
@@ -116,7 +158,7 @@ when stuck. `"]
|
|
|
116
158
|
|
|
117
159
|
Tokens, intelligence and time are never wasted on busy-polling for messages.
|
|
118
160
|
|
|
119
|
-
Instead, `pi-simple-team` pushes messages to the
|
|
161
|
+
Instead, `pi-simple-team` pushes messages to the recipients.
|
|
120
162
|
|
|
121
163
|
This is both efficient and effective:
|
|
122
164
|
|
|
@@ -139,7 +181,7 @@ Teammates publish a one-liner:
|
|
|
139
181
|
|
|
140
182
|
> <span style="color:grey">reviewer </span> Reading implementation, will finalize review in a few minutes.
|
|
141
183
|
|
|
142
|
-
Your main agent calls `teamstatus` and understands exactly what
|
|
184
|
+
Your main agent calls `teamstatus` and understands exactly what is going on. Main does not ask teammates for updates or clutter their context.
|
|
143
185
|
|
|
144
186
|
### 🌡️ Context window self-awareness
|
|
145
187
|
|
|
@@ -191,6 +233,12 @@ A missing file that once held session history causes resume to fail. Persisted s
|
|
|
191
233
|
|
|
192
234
|
`team_add` creates new RPC teammates only for a running team owned by the current main session.
|
|
193
235
|
|
|
236
|
+
The `canOverseeOwnTeams` capability persists with the teammate attachment and returns after resume.
|
|
237
|
+
|
|
238
|
+
For an overseeing teammate, `teamsend` and `teamstatus` use the parent team when `team` is omitted. Set `team` to operate on one of its own teams. `report_context_window` reports itself when `targets` is omitted and inspects its own teammates when `targets` is set.
|
|
239
|
+
|
|
240
|
+
RPC shutdown waits while an overseeing teammate stops its own teams.
|
|
241
|
+
|
|
194
242
|
**One Pi session can have only one live runtime.** Pi does not lock session files against concurrent writers.
|
|
195
243
|
|
|
196
244
|
|
|
@@ -208,16 +256,18 @@ pi install npm:@giladbarnea/pi-simple-team
|
|
|
208
256
|
Kept minimal:
|
|
209
257
|
|
|
210
258
|
|
|
211
|
-
| Role
|
|
212
|
-
|
|
|
259
|
+
| Role | For | Tools |
|
|
260
|
+
| --- | --- | --- |
|
|
213
261
|
| **Main agent** | Team lifecycle | `team_spawn`, `team_list`, `team_resume`, `team_add`, `team_shutdown` |
|
|
214
|
-
|
|
|
215
|
-
|
|
|
216
|
-
|
|
|
217
|
-
| **
|
|
218
|
-
|
|
|
219
|
-
|
|
|
220
|
-
|
|
|
262
|
+
| | With team | `teamsend` |
|
|
263
|
+
| | On team | `teamstatus`, `teamlog` |
|
|
264
|
+
| | On everyone | `report_context_window` |
|
|
265
|
+
| **Overseeing teammate** | On own teams | Same tools as the main agent |
|
|
266
|
+
| | With parent team | `teamsend`, `teamstatus`, `teammain` |
|
|
267
|
+
| **Teammates** | With team | `teamsend` |
|
|
268
|
+
| | With main | `teammain` |
|
|
269
|
+
| | On self | `report_context_window` |
|
|
270
|
+
| **Everyone** | For everyone | `teamstatus` |
|
|
221
271
|
|
|
222
272
|
|
|
223
273
|
---
|
|
@@ -229,15 +279,14 @@ Kept minimal:
|
|
|
229
279
|
**User involvement track:**
|
|
230
280
|
|
|
231
281
|
- [x] Herdr panes for teammates.
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
- [ ]
|
|
236
|
-
- [ ] 👋 Joining and steering teams.
|
|
237
|
-
- [ ] 🪄 Spawning teams directly.
|
|
282
|
+
- [x] `/team`: live, read-only team dashboard.
|
|
283
|
+
- [ ] Teammate drill-down and transcripts.
|
|
284
|
+
- [ ] Joining and steering teams from slash commands.
|
|
285
|
+
- [ ] Spawning teams directly from slash commands.
|
|
238
286
|
|
|
239
287
|
**Functional:**
|
|
240
288
|
|
|
241
289
|
- [x] Resume all or selected teammates from a dormant team.
|
|
242
290
|
- [x] Add new teammates after a team has spawned.
|
|
291
|
+
- [x] Let opted-in teammates create and manage teams of their own.
|
|
243
292
|
- [ ] Main forces `/compact` on select teammate.
|
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,
|
|
@@ -26,6 +26,7 @@ import {
|
|
|
26
26
|
} from "./team-registry.ts";
|
|
27
27
|
import { appendTeamLog, filterTeamLog, normalizeChildEvent, nowText, pageTeamLog, preview, renderTeamLogPage, type TeamLogEntry } from "./teamlog.ts";
|
|
28
28
|
import { renderTeamMessage, renderTeamToolCall, renderTeamToolResult, type TeamMessageDetails } from "./render.ts";
|
|
29
|
+
import { openTeamOverview, type TeamSnapshot } from "./team-ui.ts";
|
|
29
30
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
30
31
|
import { Type } from "typebox";
|
|
31
32
|
|
|
@@ -60,6 +61,7 @@ interface TeammateSpec {
|
|
|
60
61
|
model: string;
|
|
61
62
|
thinking?: ThinkingLevel;
|
|
62
63
|
inheritContext?: boolean;
|
|
64
|
+
canOverseeOwnTeams?: boolean;
|
|
63
65
|
}
|
|
64
66
|
|
|
65
67
|
type TeammateTransport = "rpc" | "herdr";
|
|
@@ -70,6 +72,7 @@ interface TeammateState {
|
|
|
70
72
|
model: string;
|
|
71
73
|
thinking: ThinkingLevel;
|
|
72
74
|
inheritContext: boolean;
|
|
75
|
+
canOverseeOwnTeams: boolean;
|
|
73
76
|
transport: TeammateTransport;
|
|
74
77
|
sessionId?: string;
|
|
75
78
|
sessionFile?: string;
|
|
@@ -110,6 +113,7 @@ const teamLiteExtensionPath = fileURLToPath(import.meta.url);
|
|
|
110
113
|
const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
111
114
|
const defaultThinkingLevel: ThinkingLevel = "xhigh";
|
|
112
115
|
const visibleDeliveryTimeoutMilliseconds = 30_000;
|
|
116
|
+
const defaultRpcShutdownGraceMilliseconds = 1_000;
|
|
113
117
|
const teamMessageType = "pi-simple-team";
|
|
114
118
|
const teams = new Map<string, TeamState>();
|
|
115
119
|
const callbackToken = crypto.randomBytes(24).toString("hex");
|
|
@@ -387,7 +391,7 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
|
|
|
387
391
|
direction: from === "main" ? "main->teammate" : "teammate->teammate",
|
|
388
392
|
kind: "send",
|
|
389
393
|
summary: preview(message),
|
|
390
|
-
details: { from, to: recipient.name, interrupt },
|
|
394
|
+
details: { from, to: recipient.name, interrupt, message },
|
|
391
395
|
});
|
|
392
396
|
|
|
393
397
|
recipient.deliveryQueue = recipient.deliveryQueue
|
|
@@ -477,6 +481,19 @@ function allStatuses(owner: symbol): Record<string, Record<string, TeamStatus>>
|
|
|
477
481
|
return Object.fromEntries([...teams.values()].filter((team) => team.owner === owner).map((team) => [team.name, formatStatus(team)]));
|
|
478
482
|
}
|
|
479
483
|
|
|
484
|
+
function ownedTeamSnapshots(owner: symbol): TeamSnapshot[] {
|
|
485
|
+
return [...teams.values()]
|
|
486
|
+
.filter((team) => team.owner === owner)
|
|
487
|
+
.map((team) => ({
|
|
488
|
+
name: team.name,
|
|
489
|
+
created: team.created,
|
|
490
|
+
showOnHerdrPanes: team.showOnHerdrPanes,
|
|
491
|
+
roster: [...team.members.keys()],
|
|
492
|
+
statuses: formatStatus(team),
|
|
493
|
+
log: [...team.log],
|
|
494
|
+
}));
|
|
495
|
+
}
|
|
496
|
+
|
|
480
497
|
function updateStatus(team: TeamState, participant: string, word?: string, phrase?: string): void {
|
|
481
498
|
if (word === undefined && phrase === undefined) return;
|
|
482
499
|
const previous = team.statuses.get(participant) ?? status("active", "Working");
|
|
@@ -514,6 +531,7 @@ function createTeammateState(team: TeamState, teammateSpec: TeammateSpec): Teamm
|
|
|
514
531
|
model: teammateSpec.model,
|
|
515
532
|
thinking,
|
|
516
533
|
inheritContext: Boolean(teammateSpec.inheritContext),
|
|
534
|
+
canOverseeOwnTeams: Boolean(teammateSpec.canOverseeOwnTeams),
|
|
517
535
|
transport: team.showOnHerdrPanes ? "herdr" : "rpc",
|
|
518
536
|
sessionMaterialized: false,
|
|
519
537
|
visibleReady,
|
|
@@ -538,6 +556,7 @@ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, par
|
|
|
538
556
|
PI_SIMPLE_TEAM_TEAM_NAME: team.name,
|
|
539
557
|
PI_SIMPLE_TEAM_MEMBER: teammate.name,
|
|
540
558
|
PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
|
|
559
|
+
PI_SIMPLE_TEAM_CAN_OVERSEE_OWN_TEAMS: teammate.canOverseeOwnTeams ? "1" : "0",
|
|
541
560
|
};
|
|
542
561
|
}
|
|
543
562
|
|
|
@@ -575,7 +594,7 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
575
594
|
"--no-themes",
|
|
576
595
|
...modelArgs,
|
|
577
596
|
"--system-prompt",
|
|
578
|
-
composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants),
|
|
597
|
+
composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.canOverseeOwnTeams),
|
|
579
598
|
];
|
|
580
599
|
const proc = childProcess.spawn("pi", args, {
|
|
581
600
|
cwd: team.projectDirectory ?? process.cwd(),
|
|
@@ -635,7 +654,7 @@ async function attachVisibleTeammate(
|
|
|
635
654
|
herdrTabId: string,
|
|
636
655
|
options: RpcStartOptions,
|
|
637
656
|
): Promise<void> {
|
|
638
|
-
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);
|
|
639
658
|
const environment = childEnvironmentOverrides(team, teammate, participants, true);
|
|
640
659
|
const sessionArgs = options.sessionFile
|
|
641
660
|
? ["--session", options.sessionFile]
|
|
@@ -704,6 +723,7 @@ function manifestMemberFromTeammate(teammate: TeammateState): TeamManifestMember
|
|
|
704
723
|
model: teammate.model,
|
|
705
724
|
thinking: teammate.thinking,
|
|
706
725
|
inheritContext: teammate.inheritContext,
|
|
726
|
+
canOverseeOwnTeams: teammate.canOverseeOwnTeams,
|
|
707
727
|
transport: teammate.transport,
|
|
708
728
|
live: teammate.alive,
|
|
709
729
|
sessionId: teammate.sessionId,
|
|
@@ -752,8 +772,10 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
|
|
|
752
772
|
};
|
|
753
773
|
processToStop.once("exit", resolveExit);
|
|
754
774
|
processToStop.kill("SIGTERM");
|
|
755
|
-
|
|
756
|
-
|
|
775
|
+
if (!teammate.canOverseeOwnTeams) {
|
|
776
|
+
forceKillTimeout = setTimeout(() => processToStop.kill("SIGKILL"), defaultRpcShutdownGraceMilliseconds);
|
|
777
|
+
forceKillTimeout.unref();
|
|
778
|
+
}
|
|
757
779
|
});
|
|
758
780
|
teammate.process = undefined;
|
|
759
781
|
}
|
|
@@ -945,7 +967,14 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
945
967
|
if (tool === "teammain") {
|
|
946
968
|
const rawMessage = String(args.message ?? "");
|
|
947
969
|
const details: TeamMessageDetails = { team: team.name, from, sentAt: nowText(), message: rawMessage };
|
|
948
|
-
appendTeamLog(team, {
|
|
970
|
+
appendTeamLog(team, {
|
|
971
|
+
team: team.name,
|
|
972
|
+
teammate: from,
|
|
973
|
+
direction: "teammate->main",
|
|
974
|
+
kind: "main_message",
|
|
975
|
+
summary: preview(rawMessage),
|
|
976
|
+
details: { from, to: "main", message: rawMessage },
|
|
977
|
+
});
|
|
949
978
|
team.ownerPi.sendMessage(
|
|
950
979
|
{ customType: teamMessageType, content: `[${team.name}/${from}] ${rawMessage}`, display: true, details },
|
|
951
980
|
{ deliverAs: "steer", triggerTurn: true },
|
|
@@ -976,6 +1005,7 @@ function teammateSchema(modelGuidance: string) {
|
|
|
976
1005
|
model: Type.String({ description: `Canonical provider/model id for this teammate. ${modelGuidance}` }),
|
|
977
1006
|
thinking: Type.Optional(StringEnum(thinkingLevels, { description: "Thinking level for this teammate. Defaults to xhigh.", default: defaultThinkingLevel })),
|
|
978
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 })),
|
|
979
1009
|
});
|
|
980
1010
|
}
|
|
981
1011
|
|
|
@@ -1003,6 +1033,7 @@ function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, manifest: TeamMa
|
|
|
1003
1033
|
model: member.model,
|
|
1004
1034
|
thinking: member.thinking as ThinkingLevel,
|
|
1005
1035
|
inheritContext: member.inheritContext,
|
|
1036
|
+
canOverseeOwnTeams: Boolean(member.canOverseeOwnTeams),
|
|
1006
1037
|
});
|
|
1007
1038
|
teammate.transport = "rpc";
|
|
1008
1039
|
teammate.sessionId = member.sessionId;
|
|
@@ -1037,13 +1068,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
1037
1068
|
const childRuntimeConfig = readChildRuntimeConfig();
|
|
1038
1069
|
if (childRuntimeConfig) {
|
|
1039
1070
|
registerChildTools(pi, childRuntimeConfig);
|
|
1040
|
-
return;
|
|
1071
|
+
if (!childRuntimeConfig.canOverseeOwnTeams) return;
|
|
1041
1072
|
}
|
|
1042
1073
|
|
|
1043
1074
|
const owner = Symbol("pi-simple-team-owner");
|
|
1044
|
-
const sessionTeammateRoster
|
|
1075
|
+
const sessionTeammateRoster = childRuntimeConfig?.participants ?? [];
|
|
1045
1076
|
pi.registerMessageRenderer(teamMessageType, (message, _options, theme) => renderTeamMessage(message, theme, getMarkdownTheme(), sessionTeammateRoster));
|
|
1046
1077
|
|
|
1078
|
+
pi.registerCommand("team", {
|
|
1079
|
+
description: "Open a read-only team overview",
|
|
1080
|
+
handler: async (_args, context) => {
|
|
1081
|
+
await openTeamOverview(context, () => ownedTeamSnapshots(owner));
|
|
1082
|
+
},
|
|
1083
|
+
});
|
|
1084
|
+
|
|
1047
1085
|
pi.on("session_shutdown", async () => {
|
|
1048
1086
|
for (const team of [...teams.values()]) {
|
|
1049
1087
|
if (team.owner === owner) await shutdownTeam(team);
|
|
@@ -1174,13 +1212,19 @@ export default function (pi: ExtensionAPI) {
|
|
|
1174
1212
|
defineTool({
|
|
1175
1213
|
name: "team_list",
|
|
1176
1214
|
label: "Team List",
|
|
1177
|
-
description:
|
|
1215
|
+
description: childRuntimeConfig
|
|
1216
|
+
? "List active and dormant teams created by this overseeing teammate."
|
|
1217
|
+
: "List active and dormant teams for the current project.",
|
|
1178
1218
|
promptSnippet: "List teams for the current project",
|
|
1179
1219
|
parameters: Type.Object({}),
|
|
1180
1220
|
async execute(_toolCallId, _params, _signal, _onUpdate, context) {
|
|
1181
1221
|
const projectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
|
|
1182
1222
|
if (!projectDirectory) throw new Error("team_list requires a project directory");
|
|
1183
|
-
const
|
|
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
|
+
);
|
|
1184
1228
|
return toolResult({
|
|
1185
1229
|
teams: manifests.map((manifest) => {
|
|
1186
1230
|
const liveTeam = teams.get(manifest.id);
|
|
@@ -1193,6 +1237,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1193
1237
|
members: manifest.members.map((member) => ({
|
|
1194
1238
|
name: member.name,
|
|
1195
1239
|
live: liveTeam?.members.get(member.name)?.alive ?? member.live,
|
|
1240
|
+
canOverseeOwnTeams: Boolean(member.canOverseeOwnTeams),
|
|
1196
1241
|
sessionId: member.sessionId,
|
|
1197
1242
|
sessionFile: member.sessionFile,
|
|
1198
1243
|
})),
|
|
@@ -1211,7 +1256,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1211
1256
|
defineTool({
|
|
1212
1257
|
name: "team_resume",
|
|
1213
1258
|
label: "Team Resume",
|
|
1214
|
-
description:
|
|
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.",
|
|
1215
1262
|
promptSnippet: "Resume all or selected stopped teammates",
|
|
1216
1263
|
parameters: Type.Object({
|
|
1217
1264
|
team: Type.String({ description: "Persistent team ID" }),
|
|
@@ -1221,7 +1268,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
1221
1268
|
async execute(_toolCallId, params, _signal, _onUpdate, context) {
|
|
1222
1269
|
const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
|
|
1223
1270
|
if (!rawProjectDirectory) throw new Error("team_resume requires a project directory");
|
|
1224
|
-
const
|
|
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
|
+
);
|
|
1225
1276
|
if (!manifest) throw new Error(`Unknown current-project team: ${params.team}`);
|
|
1226
1277
|
const requestedNames = params.teammates?.map(compactName) ?? manifest.members.map((member) => member.name);
|
|
1227
1278
|
const duplicateNames = requestedNames.filter((name, index) => requestedNames.indexOf(name) !== index);
|
|
@@ -1380,18 +1431,27 @@ export default function (pi: ExtensionAPI) {
|
|
|
1380
1431
|
defineTool({
|
|
1381
1432
|
name: "teamsend",
|
|
1382
1433
|
label: "Team Send",
|
|
1383
|
-
description:
|
|
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.",
|
|
1384
1437
|
promptSnippet: "Send a message from main to teammate(s)",
|
|
1385
1438
|
renderShell: "self",
|
|
1386
1439
|
renderCall: (args, theme, context) => renderTeamToolCall("teamsend", args, theme, context, sessionTeammateRoster),
|
|
1387
1440
|
renderResult: (result, options, theme, context) => renderTeamToolResult("teamsend", result, options, theme, context, getMarkdownTheme(), sessionTeammateRoster),
|
|
1388
1441
|
parameters: Type.Object({
|
|
1389
|
-
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" })),
|
|
1390
1443
|
to: Type.Array(Type.String(), { description: "Recipient teammate names" }),
|
|
1391
1444
|
message: Type.String({ description: "Message to send" }),
|
|
1392
1445
|
interrupt: Type.Optional(Type.Boolean({ description: "Abort busy recipients before delivery" })),
|
|
1393
1446
|
}),
|
|
1394
|
-
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
|
+
}
|
|
1395
1455
|
const team = resolveTeam(owner, params.team);
|
|
1396
1456
|
const recipients = resolveRecipients(team, params.to);
|
|
1397
1457
|
const interrupt = Boolean(params.interrupt);
|
|
@@ -1405,18 +1465,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
1405
1465
|
defineTool({
|
|
1406
1466
|
name: "teamstatus",
|
|
1407
1467
|
label: "Team Status",
|
|
1408
|
-
description:
|
|
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.",
|
|
1409
1471
|
promptSnippet: "Set/read team status maps",
|
|
1410
1472
|
renderShell: "self",
|
|
1411
1473
|
renderCall: (args, theme, context) => renderTeamToolCall("teamstatus", args, theme, context, sessionTeammateRoster),
|
|
1412
1474
|
renderResult: (result, options, theme, context) => renderTeamToolResult("teamstatus", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
1413
1475
|
parameters: Type.Object({
|
|
1414
|
-
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" })),
|
|
1415
1477
|
// TODO: make gerund and phrase optionality a XOR.
|
|
1416
1478
|
gerund: Type.Optional(Type.String({ description: "Set one-word gerund main status" })),
|
|
1417
1479
|
phrase: Type.Optional(Type.String({ description: "Short main status verb-oriented phrase." })),
|
|
1418
1480
|
}),
|
|
1419
|
-
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
|
+
}
|
|
1420
1488
|
if (!params.team && params.gerund === undefined && params.phrase === undefined) {
|
|
1421
1489
|
return toolResult({ teams: allStatuses(owner) });
|
|
1422
1490
|
}
|
|
@@ -1432,12 +1500,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
1432
1500
|
defineTool({
|
|
1433
1501
|
name: "report_context_window",
|
|
1434
1502
|
label: "Report Context Window",
|
|
1435
|
-
description:
|
|
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.",
|
|
1436
1506
|
promptSnippet: "Report context-window use for selected teammates and main",
|
|
1437
1507
|
parameters: Type.Object({
|
|
1438
|
-
targets:
|
|
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." }),
|
|
1439
1511
|
}),
|
|
1440
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
|
+
}
|
|
1441
1517
|
const teammates = resolveContextTargets(owner, params.targets);
|
|
1442
1518
|
const reports = await Promise.all(
|
|
1443
1519
|
teammates.map(async (teammate) => formatContextWindowReport(`Teammate ${teammate.name} has`, await getTeammateContextUsage(teammate, signal))),
|
package/package.json
CHANGED
package/system-prompt.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { bundledAiToAiSkillInstruction } from "./bundled-skill.ts";
|
|
2
2
|
|
|
3
|
-
export function composeSystemPrompt(
|
|
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
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Key, matchesKey, SelectList, sliceByColumn, truncateToWidth, visibleWidth, type Component, type SelectItem, type TUI } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
actorHueToken,
|
|
6
|
+
statusWordToken,
|
|
7
|
+
teamLineText,
|
|
8
|
+
teamLogLines,
|
|
9
|
+
teamMessageLines,
|
|
10
|
+
type TeamMessageDetails,
|
|
11
|
+
type TeamStatusView,
|
|
12
|
+
type ThemeLike,
|
|
13
|
+
} from "./render.ts";
|
|
14
|
+
import type { TeamLogEntry, TeamLogKind } from "./teamlog.ts";
|
|
15
|
+
|
|
16
|
+
export interface TeamSnapshot {
|
|
17
|
+
name: string;
|
|
18
|
+
created: string;
|
|
19
|
+
showOnHerdrPanes: boolean;
|
|
20
|
+
roster: string[];
|
|
21
|
+
statuses: Record<string, TeamStatusView>;
|
|
22
|
+
log: TeamLogEntry[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type TeamSnapshotSource = () => readonly TeamSnapshot[];
|
|
26
|
+
|
|
27
|
+
const RECENT_STATUS_LIMIT = 5;
|
|
28
|
+
const RECENT_LOG_ENTRY_LIMIT = 20;
|
|
29
|
+
const LIVE_REFRESH_INTERVAL_MILLISECONDS = 500;
|
|
30
|
+
const MESSAGE_LOG_KINDS = new Set<TeamLogKind>(["send", "deliver", "ack", "main_message"]);
|
|
31
|
+
|
|
32
|
+
const overlayOptions = {
|
|
33
|
+
overlay: true,
|
|
34
|
+
overlayOptions: { anchor: "center", width: "90%", maxHeight: "90%" },
|
|
35
|
+
} as const;
|
|
36
|
+
|
|
37
|
+
function teamMessage(entry: TeamLogEntry): TeamMessageDetails | undefined {
|
|
38
|
+
if (entry.kind !== "send" && entry.kind !== "main_message") return undefined;
|
|
39
|
+
const details = entry.details as { from: string; to: string; message: string };
|
|
40
|
+
return {
|
|
41
|
+
team: entry.team,
|
|
42
|
+
from: entry.kind === "main_message" ? entry.teammate! : details.from,
|
|
43
|
+
to: entry.kind === "main_message" ? "main" : details.to,
|
|
44
|
+
sentAt: entry.timestamp,
|
|
45
|
+
message: details.message,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** middleTruncateToWidth("abcdefghij", 7) === "abc…hij" */
|
|
50
|
+
function middleTruncateToWidth(text: string, width: number, pad = false): string {
|
|
51
|
+
const targetWidth = Math.max(0, width);
|
|
52
|
+
const textWidth = visibleWidth(text);
|
|
53
|
+
if (textWidth <= targetWidth) return pad ? `${text}${" ".repeat(targetWidth - textWidth)}` : text;
|
|
54
|
+
if (targetWidth === 0) return "";
|
|
55
|
+
|
|
56
|
+
const ellipsis = "…";
|
|
57
|
+
const ellipsisWidth = visibleWidth(ellipsis);
|
|
58
|
+
if (ellipsisWidth >= targetWidth) return truncateToWidth(ellipsis, targetWidth, "", pad);
|
|
59
|
+
|
|
60
|
+
const retainedWidth = targetWidth - ellipsisWidth;
|
|
61
|
+
const leftWidth = Math.ceil(retainedWidth / 2);
|
|
62
|
+
const rightWidth = Math.floor(retainedWidth / 2);
|
|
63
|
+
const left = sliceByColumn(text, 0, leftWidth, true);
|
|
64
|
+
const right = sliceByColumn(text, textWidth - rightWidth, rightWidth, true);
|
|
65
|
+
const reset = text.includes("\x1b") ? "\x1b[0m" : "";
|
|
66
|
+
const result = `${left}${reset}${ellipsis}${reset}${right}`;
|
|
67
|
+
return pad ? `${result}${" ".repeat(Math.max(0, targetWidth - visibleWidth(result)))}` : result;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Keeps the most recently updated status first. */
|
|
71
|
+
function recentStatuses(statuses: Record<string, TeamStatusView>, limit: number): Array<[string, TeamStatusView]> {
|
|
72
|
+
return Object.entries(statuses)
|
|
73
|
+
.sort(([, left], [, right]) => Date.parse(right.updated) - Date.parse(left.updated))
|
|
74
|
+
.slice(0, limit);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function padVisible(text: string, width: number): string {
|
|
78
|
+
return `${text}${" ".repeat(Math.max(0, width - visibleWidth(text)))}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function statusRows(theme: ThemeLike, statuses: Array<[string, TeamStatusView]>, roster: string[], width: number): string[] {
|
|
82
|
+
const contentWidth = Math.max(0, width - 1);
|
|
83
|
+
const nameWidth = Math.max(0, ...statuses.map(([name]) => visibleWidth(name)));
|
|
84
|
+
const wordWidth = Math.max(0, ...statuses.map(([, status]) => visibleWidth(status.word)));
|
|
85
|
+
const timestampWidth = Math.max(0, ...statuses.map(([, status]) => visibleWidth(status.updated)));
|
|
86
|
+
const phraseWidth = Math.max(0, contentWidth - nameWidth - wordWidth - timestampWidth - 6);
|
|
87
|
+
|
|
88
|
+
return statuses.map(([name, status]) => {
|
|
89
|
+
const styledName = theme.fg(actorHueToken(name, roster), name);
|
|
90
|
+
const styledWord = theme.fg(statusWordToken(status.word), status.word);
|
|
91
|
+
const timestamp = theme.fg("dim", status.updated);
|
|
92
|
+
const phrase = middleTruncateToWidth(status.phrase, phraseWidth, true);
|
|
93
|
+
return `${padVisible(styledName, nameWidth)} ${padVisible(styledWord, wordWidth)} ${phrase} ${timestamp}`;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function limitMessageRows(lines: string[], height: number): string[] {
|
|
98
|
+
if (lines.length <= height) return lines;
|
|
99
|
+
if (height <= 0) return [];
|
|
100
|
+
if (height === 1) return [lines[0]!];
|
|
101
|
+
if (height === 2) return [lines[0]!, `… ${lines.length - 1} message lines omitted …`];
|
|
102
|
+
|
|
103
|
+
const body = lines.slice(1);
|
|
104
|
+
const retainedBodyRows = height - 2;
|
|
105
|
+
const leadingRows = Math.ceil(retainedBodyRows / 2);
|
|
106
|
+
const trailingRows = Math.floor(retainedBodyRows / 2);
|
|
107
|
+
return [
|
|
108
|
+
lines[0]!,
|
|
109
|
+
...body.slice(0, leadingRows),
|
|
110
|
+
`… ${body.length - retainedBodyRows} message lines omitted …`,
|
|
111
|
+
...(trailingRows > 0 ? body.slice(-trailingRows) : []),
|
|
112
|
+
];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
interface MessageLineSelection {
|
|
116
|
+
lines: string[];
|
|
117
|
+
messageCount: number;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** selectNewestMessageLines([["old"], ["new"]], 1).lines[0] === "new" */
|
|
121
|
+
function selectNewestMessageLines(groups: string[][], height: number): MessageLineSelection {
|
|
122
|
+
const selectedGroups: string[][] = [];
|
|
123
|
+
let remainingHeight = height;
|
|
124
|
+
|
|
125
|
+
for (let index = groups.length - 1; index >= 0; index--) {
|
|
126
|
+
const group = groups[index]!;
|
|
127
|
+
const separatorHeight = selectedGroups.length > 0 ? 1 : 0;
|
|
128
|
+
if (group.length + separatorHeight <= remainingHeight) {
|
|
129
|
+
selectedGroups.unshift(group);
|
|
130
|
+
remainingHeight -= group.length + separatorHeight;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (selectedGroups.length === 0) selectedGroups.push(limitMessageRows(group, height));
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
lines: selectedGroups.flatMap((group, index) => [...(index > 0 ? [""] : []), ...group]),
|
|
139
|
+
messageCount: selectedGroups.length,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
class TeamOverviewOverlay implements Component {
|
|
144
|
+
private readonly selector?: SelectList;
|
|
145
|
+
private selectedTeamName?: string;
|
|
146
|
+
private refreshTimer?: ReturnType<typeof setInterval>;
|
|
147
|
+
private closed = false;
|
|
148
|
+
|
|
149
|
+
constructor(
|
|
150
|
+
private readonly tui: TUI,
|
|
151
|
+
private readonly theme: ThemeLike,
|
|
152
|
+
private readonly teamSource: TeamSnapshotSource,
|
|
153
|
+
private readonly done: () => void,
|
|
154
|
+
) {
|
|
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
|
+
this.refreshTimer = setInterval(() => this.tui.requestRender(), LIVE_REFRESH_INTERVAL_MILLISECONDS);
|
|
178
|
+
this.refreshTimer.unref?.();
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
handleInput(data: string): void {
|
|
182
|
+
if (!this.selectedTeamName && this.selector) {
|
|
183
|
+
this.selector.handleInput(data);
|
|
184
|
+
this.tui.requestRender();
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) this.close();
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
render(width: number): string[] {
|
|
191
|
+
const height = Math.max(4, Math.floor(this.tui.terminal.rows * 0.9));
|
|
192
|
+
const teams = this.teamSource();
|
|
193
|
+
if (this.selectedTeamName) {
|
|
194
|
+
const team = teams.find((candidate) => candidate.name === this.selectedTeamName)!;
|
|
195
|
+
return this.dashboard(team, width, height);
|
|
196
|
+
}
|
|
197
|
+
const innerHeight = height - 2;
|
|
198
|
+
return this.frame(this.content(Math.max(1, width - 4), teams).slice(0, innerHeight), width, height);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
invalidate(): void {
|
|
202
|
+
this.selector?.invalidate();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
dispose(): void {
|
|
206
|
+
if (!this.refreshTimer) return;
|
|
207
|
+
clearInterval(this.refreshTimer);
|
|
208
|
+
this.refreshTimer = undefined;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private readonly close = (): void => {
|
|
212
|
+
if (this.closed) return;
|
|
213
|
+
this.closed = true;
|
|
214
|
+
this.dispose();
|
|
215
|
+
this.done();
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
private selectorHeight(teamCount: number): number {
|
|
219
|
+
return Math.max(1, Math.min(teamCount, Math.floor(this.tui.terminal.rows * 0.9) - 8));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private content(width: number, teams: readonly TeamSnapshot[]): string[] {
|
|
223
|
+
if (teams.length === 0) {
|
|
224
|
+
return [
|
|
225
|
+
this.theme.fg("accent", this.theme.bold("Teams")),
|
|
226
|
+
"",
|
|
227
|
+
"No teams exist.",
|
|
228
|
+
"",
|
|
229
|
+
this.theme.fg("dim", "Esc close"),
|
|
230
|
+
];
|
|
231
|
+
}
|
|
232
|
+
return [
|
|
233
|
+
this.theme.fg("accent", this.theme.bold("Select a team")),
|
|
234
|
+
"",
|
|
235
|
+
...this.selector!.render(width),
|
|
236
|
+
"",
|
|
237
|
+
this.theme.fg("dim", "↑↓ select · Enter open · Esc close"),
|
|
238
|
+
];
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private dashboard(team: TeamSnapshot, width: number, height: number): string[] {
|
|
242
|
+
const contentWidth = Math.max(1, width - 2);
|
|
243
|
+
const contentHeight = Math.max(1, height - 2);
|
|
244
|
+
const headerHeight = Math.min(3, Math.max(1, contentHeight - 3));
|
|
245
|
+
const desiredStatusHeight = Math.min(Object.keys(team.statuses).length, RECENT_STATUS_LIMIT) + 2;
|
|
246
|
+
const statusHeight = Math.max(1, Math.min(desiredStatusHeight, contentHeight - headerHeight - 2));
|
|
247
|
+
const feedHeight = contentHeight - headerHeight - statusHeight;
|
|
248
|
+
const messageHeight = Math.max(1, Math.min(feedHeight - 1, Math.round(feedHeight * 0.55)));
|
|
249
|
+
const logHeight = feedHeight - messageHeight;
|
|
250
|
+
|
|
251
|
+
const transport = team.showOnHerdrPanes ? "Herdr" : "RPC";
|
|
252
|
+
const metadata = [
|
|
253
|
+
`Created ${team.created}`,
|
|
254
|
+
`${team.roster.length} teammate${team.roster.length === 1 ? "" : "s"}`,
|
|
255
|
+
transport,
|
|
256
|
+
`${team.log.length} retained event${team.log.length === 1 ? "" : "s"}`,
|
|
257
|
+
"Esc close",
|
|
258
|
+
].join(" · ");
|
|
259
|
+
|
|
260
|
+
const statusContentHeight = Math.max(0, statusHeight - 2);
|
|
261
|
+
const statuses = recentStatuses(team.statuses, Math.min(RECENT_STATUS_LIMIT, statusContentHeight));
|
|
262
|
+
const statusLines = statusRows(this.theme, statuses, team.roster, Math.max(0, contentWidth - 2));
|
|
263
|
+
|
|
264
|
+
const allMessages = team.log.flatMap((entry) => {
|
|
265
|
+
const message = teamMessage(entry);
|
|
266
|
+
return message ? [message] : [];
|
|
267
|
+
});
|
|
268
|
+
const messageGroups = allMessages.map((message) => teamMessageLines(this.theme, message, team.roster).map(teamLineText));
|
|
269
|
+
const selectedMessages = selectNewestMessageLines(messageGroups, Math.max(0, messageHeight - 2));
|
|
270
|
+
const messageLines = selectedMessages.lines.length > 0 ? selectedMessages.lines : [this.theme.fg("muted", "No recent messages.")];
|
|
271
|
+
|
|
272
|
+
const allLogEntries = team.log.filter((entry) => !MESSAGE_LOG_KINDS.has(entry.kind));
|
|
273
|
+
const recentLogEntries = allLogEntries.slice(-RECENT_LOG_ENTRY_LIMIT);
|
|
274
|
+
const renderedLogLines = teamLogLines(this.theme, {
|
|
275
|
+
team: team.name,
|
|
276
|
+
roster: team.roster,
|
|
277
|
+
entries: recentLogEntries,
|
|
278
|
+
totalMatched: allLogEntries.length,
|
|
279
|
+
returned: recentLogEntries.length,
|
|
280
|
+
}).slice(1);
|
|
281
|
+
const logContentHeight = Math.max(0, logHeight - 2);
|
|
282
|
+
const logLines = renderedLogLines.slice(-logContentHeight);
|
|
283
|
+
|
|
284
|
+
const content = [
|
|
285
|
+
...this.region(this.theme.fg("accent", this.theme.bold(`Team: ${team.name}`)), [this.theme.fg("muted", metadata)], contentWidth, headerHeight),
|
|
286
|
+
...this.region(`Team Status ${team.name} · latest ${statuses.length} of ${Object.keys(team.statuses).length}`, statusLines, contentWidth, statusHeight),
|
|
287
|
+
...this.region(`Messages · latest ${selectedMessages.messageCount} of ${allMessages.length}`, messageLines, contentWidth, messageHeight),
|
|
288
|
+
...this.region(`Team Log ${team.name} · latest ${logLines.length} rows · ${allLogEntries.length} events`, logLines, contentWidth, logHeight),
|
|
289
|
+
];
|
|
290
|
+
return this.frame(content, width, height);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private region(title: string, content: string[], width: number, height: number): string[] {
|
|
294
|
+
const frameWidth = Math.max(1, width);
|
|
295
|
+
const border = (text: string): string => this.theme.fg("border", text);
|
|
296
|
+
if (frameWidth < 3) {
|
|
297
|
+
const top = border(frameWidth === 1 ? "╭" : "╭╮");
|
|
298
|
+
if (height === 1) return [top];
|
|
299
|
+
const row = border("│".repeat(frameWidth));
|
|
300
|
+
return [top, ...Array.from({ length: Math.max(0, height - 2) }, () => row), border(frameWidth === 1 ? "╰" : "╰╯")];
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const innerWidth = frameWidth - 2;
|
|
304
|
+
const labelWidth = Math.max(0, innerWidth - 3);
|
|
305
|
+
const label = middleTruncateToWidth(title, labelWidth);
|
|
306
|
+
const topFill = "─".repeat(Math.max(0, innerWidth - 3 - visibleWidth(label)));
|
|
307
|
+
const top = innerWidth < 3 ? border(`╭${"─".repeat(innerWidth)}╮`) : `${border("╭─ ")}${label}${border(` ${topFill}╮`)}`;
|
|
308
|
+
if (height === 1) return [top];
|
|
309
|
+
|
|
310
|
+
const visibleContent = content.slice(0, Math.max(0, height - 2));
|
|
311
|
+
while (visibleContent.length < height - 2) visibleContent.push("");
|
|
312
|
+
const row = (text: string): string => `${border("│")}${middleTruncateToWidth(` ${text}`, innerWidth, true)}${border("│")}`;
|
|
313
|
+
return [top, ...visibleContent.map(row), border(`╰${"─".repeat(innerWidth)}╯`)];
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
private frame(content: string[], width: number, height: number): string[] {
|
|
317
|
+
const frameWidth = Math.max(1, width);
|
|
318
|
+
const innerHeight = height - 2;
|
|
319
|
+
const border = (text: string): string => this.theme.fg("border", text);
|
|
320
|
+
if (frameWidth < 3) {
|
|
321
|
+
const row = border("│".repeat(frameWidth));
|
|
322
|
+
return [border(frameWidth === 1 ? "╭" : "╭╮"), ...Array.from({ length: innerHeight }, () => row), border(frameWidth === 1 ? "╰" : "╰╯")];
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const innerWidth = frameWidth - 2;
|
|
326
|
+
const visibleContent = content.slice(0, innerHeight);
|
|
327
|
+
while (visibleContent.length < innerHeight) visibleContent.push("");
|
|
328
|
+
const row = (text: string): string => `${border("│")}${middleTruncateToWidth(text, innerWidth, true)}${border("│")}`;
|
|
329
|
+
return [border(`╭${"─".repeat(innerWidth)}╮`), ...visibleContent.map(row), border(`╰${"─".repeat(innerWidth)}╯`)];
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export async function openTeamOverview(context: ExtensionCommandContext, teamSource: TeamSnapshotSource): Promise<void> {
|
|
334
|
+
if (context.mode !== "tui") {
|
|
335
|
+
context.ui.notify("/team is available only in interactive mode.", "warning");
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
await context.ui.custom<void>(
|
|
339
|
+
(tui, theme, _keybindings, done) => new TeamOverviewOverlay(tui, theme, teamSource, done),
|
|
340
|
+
overlayOptions,
|
|
341
|
+
);
|
|
342
|
+
}
|