@giladbarnea/pi-simple-team 1.0.21 → 1.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -21
- package/child-tools.ts +29 -3
- package/index.ts +520 -36
- package/package.json +1 -1
- package/system-prompt.ts +1 -1
- package/team-registry.ts +300 -0
- package/team-ui.ts +342 -0
package/package.json
CHANGED
package/system-prompt.ts
CHANGED
|
@@ -9,7 +9,7 @@ export function composeSystemPrompt(teamName: string, teamPrompt: string, teamma
|
|
|
9
9
|
`Participants: main, ${participants.join(", ")}.`,
|
|
10
10
|
"Use teamsend to talk to teammates, teammain to talk to the main agent, and teamstatus to set/read public statuses.",
|
|
11
11
|
"From the sender’s point of view, teamsend is fire-and-forget. From the recipient’s point of view, the message is pushed to context as soon as possible.",
|
|
12
|
-
"
|
|
12
|
+
"The main agent is the current coordinator. Use the team tools and available session history to share relevant context.",
|
|
13
13
|
"As soon as you wake up, call teamstatus to acknowledge that you received your instructions before doing substantive work.",
|
|
14
14
|
"Whenever you receive a message from main or a teammate, call teamstatus first to acknowledge that specific message, then proceed.",
|
|
15
15
|
"Never set a waiting status until after you have sent the teammate you are waiting for a teamsend describing exactly what you need from them.",
|
package/team-registry.ts
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
|
|
5
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
|
|
7
|
+
export interface TeamManifestMember {
|
|
8
|
+
name: string;
|
|
9
|
+
prompt: string;
|
|
10
|
+
model: string;
|
|
11
|
+
thinking: string;
|
|
12
|
+
inheritContext: boolean;
|
|
13
|
+
transport: "rpc" | "herdr";
|
|
14
|
+
live: boolean;
|
|
15
|
+
sessionId: string;
|
|
16
|
+
sessionFile: string;
|
|
17
|
+
sessionMaterialized: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface TeamManifest {
|
|
21
|
+
version: 1;
|
|
22
|
+
id: string;
|
|
23
|
+
name: string;
|
|
24
|
+
originMainSessionId: string;
|
|
25
|
+
projectDirectory: string;
|
|
26
|
+
teamPrompt: string;
|
|
27
|
+
showOnHerdrPanes: boolean;
|
|
28
|
+
members: TeamManifestMember[];
|
|
29
|
+
state: "active" | "dormant";
|
|
30
|
+
createdAt: string;
|
|
31
|
+
updatedAt: string;
|
|
32
|
+
shutdownAt?: string;
|
|
33
|
+
expiresAt?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface TeamLease {
|
|
37
|
+
version: 1;
|
|
38
|
+
teamId: string;
|
|
39
|
+
mainSessionId: string;
|
|
40
|
+
processId: number;
|
|
41
|
+
token: string;
|
|
42
|
+
claimedAt: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const dormantManifestRetentionMilliseconds = 30 * 24 * 60 * 60 * 1_000;
|
|
46
|
+
|
|
47
|
+
function manifestsDirectory(): string {
|
|
48
|
+
return path.join(getAgentDir(), "pi-simple-team", "teams");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** @example canonicalProjectDirectory(".") // absolute real path */
|
|
52
|
+
export function canonicalProjectDirectory(projectDirectory: string): string {
|
|
53
|
+
return fs.realpathSync(path.resolve(projectDirectory));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function encodedTeamPath(teamId: string, suffix: string): string {
|
|
57
|
+
return path.join(manifestsDirectory(), `${encodeURIComponent(teamId)}${suffix}`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function manifestPath(teamId: string): string {
|
|
61
|
+
return encodedTeamPath(teamId, ".json");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function leasePath(teamId: string): string {
|
|
65
|
+
return encodedTeamPath(teamId, ".lease");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function leaseClaimLockPath(teamId: string): string {
|
|
69
|
+
return encodedTeamPath(teamId, ".lease-claim-lock");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isManifestMember(value: unknown): value is TeamManifestMember {
|
|
73
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
74
|
+
const member = value as Record<string, unknown>;
|
|
75
|
+
return (
|
|
76
|
+
typeof member.name === "string" &&
|
|
77
|
+
typeof member.prompt === "string" &&
|
|
78
|
+
typeof member.model === "string" &&
|
|
79
|
+
typeof member.thinking === "string" &&
|
|
80
|
+
typeof member.inheritContext === "boolean" &&
|
|
81
|
+
(member.transport === "rpc" || member.transport === "herdr") &&
|
|
82
|
+
typeof member.live === "boolean" &&
|
|
83
|
+
typeof member.sessionId === "string" &&
|
|
84
|
+
typeof member.sessionFile === "string" &&
|
|
85
|
+
typeof member.sessionMaterialized === "boolean"
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function parseManifest(filePath: string): TeamManifest {
|
|
90
|
+
const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
91
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
92
|
+
throw new Error(`Invalid team manifest: ${filePath}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const manifest = parsed as Record<string, unknown>;
|
|
96
|
+
const validState = manifest.state === "active" || manifest.state === "dormant";
|
|
97
|
+
if (
|
|
98
|
+
manifest.version !== 1 ||
|
|
99
|
+
typeof manifest.id !== "string" ||
|
|
100
|
+
typeof manifest.name !== "string" ||
|
|
101
|
+
typeof manifest.originMainSessionId !== "string" ||
|
|
102
|
+
typeof manifest.projectDirectory !== "string" ||
|
|
103
|
+
typeof manifest.teamPrompt !== "string" ||
|
|
104
|
+
typeof manifest.showOnHerdrPanes !== "boolean" ||
|
|
105
|
+
!Array.isArray(manifest.members) ||
|
|
106
|
+
!manifest.members.every(isManifestMember) ||
|
|
107
|
+
!validState ||
|
|
108
|
+
typeof manifest.createdAt !== "string" ||
|
|
109
|
+
typeof manifest.updatedAt !== "string" ||
|
|
110
|
+
(manifest.shutdownAt !== undefined && typeof manifest.shutdownAt !== "string") ||
|
|
111
|
+
(manifest.expiresAt !== undefined && typeof manifest.expiresAt !== "string")
|
|
112
|
+
) {
|
|
113
|
+
throw new Error(`Invalid team manifest: ${filePath}`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return manifest as unknown as TeamManifest;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function parseLease(filePath: string): TeamLease {
|
|
120
|
+
const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
121
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
122
|
+
throw new Error(`Invalid team lease: ${filePath}`);
|
|
123
|
+
}
|
|
124
|
+
const lease = parsed as Record<string, unknown>;
|
|
125
|
+
if (
|
|
126
|
+
lease.version !== 1 ||
|
|
127
|
+
typeof lease.teamId !== "string" ||
|
|
128
|
+
typeof lease.mainSessionId !== "string" ||
|
|
129
|
+
typeof lease.processId !== "number" ||
|
|
130
|
+
typeof lease.token !== "string" ||
|
|
131
|
+
typeof lease.claimedAt !== "string"
|
|
132
|
+
) {
|
|
133
|
+
throw new Error(`Invalid team lease: ${filePath}`);
|
|
134
|
+
}
|
|
135
|
+
return lease as unknown as TeamLease;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function processIsAlive(processId: number): boolean {
|
|
139
|
+
try {
|
|
140
|
+
process.kill(processId, 0);
|
|
141
|
+
return true;
|
|
142
|
+
} catch (error) {
|
|
143
|
+
return (error as NodeJS.ErrnoException).code !== "ESRCH";
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function writeTeamManifest(manifest: TeamManifest): void {
|
|
148
|
+
const directory = manifestsDirectory();
|
|
149
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
150
|
+
const filePath = manifestPath(manifest.id);
|
|
151
|
+
const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
152
|
+
fs.writeFileSync(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
153
|
+
fs.renameSync(temporaryPath, filePath);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function listTeamManifests(projectDirectory: string): TeamManifest[] {
|
|
157
|
+
const directory = manifestsDirectory();
|
|
158
|
+
if (!fs.existsSync(directory)) return [];
|
|
159
|
+
|
|
160
|
+
const resolvedProjectDirectory = canonicalProjectDirectory(projectDirectory);
|
|
161
|
+
const now = Date.now();
|
|
162
|
+
return fs
|
|
163
|
+
.readdirSync(directory, { withFileTypes: true })
|
|
164
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
|
|
165
|
+
.map((entry) => ({ filePath: path.join(directory, entry.name), manifest: parseManifest(path.join(directory, entry.name)) }))
|
|
166
|
+
.filter(({ filePath, manifest }) => {
|
|
167
|
+
const expiresAt = Date.parse(manifest.expiresAt ?? "");
|
|
168
|
+
const shutdownAt = Date.parse(manifest.shutdownAt ?? "");
|
|
169
|
+
const expired = manifest.state === "dormant" && (
|
|
170
|
+
Number.isFinite(expiresAt)
|
|
171
|
+
? now >= expiresAt
|
|
172
|
+
: now - shutdownAt >= dormantManifestRetentionMilliseconds
|
|
173
|
+
);
|
|
174
|
+
if (!expired) return true;
|
|
175
|
+
fs.rmSync(leasePath(manifest.id), { force: true });
|
|
176
|
+
fs.rmSync(filePath);
|
|
177
|
+
return false;
|
|
178
|
+
})
|
|
179
|
+
.map(({ manifest }) => manifest)
|
|
180
|
+
.filter((manifest) => manifest.projectDirectory === resolvedProjectDirectory)
|
|
181
|
+
.sort((left, right) => left.id.localeCompare(right.id));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function readTeamLeaseState(teamId: string): { state: "unclaimed" | "claimed" | "stale"; mainSessionId?: string } {
|
|
185
|
+
let lease: TeamLease;
|
|
186
|
+
try {
|
|
187
|
+
lease = parseLease(leasePath(teamId));
|
|
188
|
+
} catch (error) {
|
|
189
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return { state: "unclaimed" };
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
state: processIsAlive(lease.processId) ? "claimed" : "stale",
|
|
194
|
+
mainSessionId: lease.mainSessionId,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function markAbandonedTeamDormant(teamId: string): void {
|
|
199
|
+
let manifest: TeamManifest;
|
|
200
|
+
try {
|
|
201
|
+
manifest = parseManifest(manifestPath(teamId));
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
if (manifest.state !== "active") return;
|
|
207
|
+
|
|
208
|
+
const shutdownAt = new Date().toISOString();
|
|
209
|
+
writeTeamManifest({
|
|
210
|
+
...manifest,
|
|
211
|
+
members: manifest.members.map((member) => ({ ...member, live: false })),
|
|
212
|
+
state: "dormant",
|
|
213
|
+
updatedAt: shutdownAt,
|
|
214
|
+
shutdownAt,
|
|
215
|
+
expiresAt: new Date(Date.parse(shutdownAt) + dormantManifestRetentionMilliseconds).toISOString(),
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function claimTeamLeaseUnderLock(teamId: string, mainSessionId: string): TeamLease {
|
|
220
|
+
const filePath = leasePath(teamId);
|
|
221
|
+
const lease: TeamLease = {
|
|
222
|
+
version: 1,
|
|
223
|
+
teamId,
|
|
224
|
+
mainSessionId,
|
|
225
|
+
processId: process.pid,
|
|
226
|
+
token: randomUUID(),
|
|
227
|
+
claimedAt: new Date().toISOString(),
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
let recoveredStaleLease = false;
|
|
231
|
+
while (true) {
|
|
232
|
+
try {
|
|
233
|
+
fs.writeFileSync(filePath, `${JSON.stringify(lease, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
234
|
+
if (recoveredStaleLease) {
|
|
235
|
+
try {
|
|
236
|
+
markAbandonedTeamDormant(teamId);
|
|
237
|
+
} catch (error) {
|
|
238
|
+
releaseTeamLease(lease);
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return lease;
|
|
243
|
+
} catch (error) {
|
|
244
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
let existingLease: TeamLease;
|
|
248
|
+
try {
|
|
249
|
+
existingLease = parseLease(filePath);
|
|
250
|
+
} catch (error) {
|
|
251
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
if (processIsAlive(existingLease.processId)) {
|
|
255
|
+
throw new Error(`Team ${teamId} is already owned by main session ${existingLease.mainSessionId}`);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
let currentLease: TeamLease;
|
|
259
|
+
try {
|
|
260
|
+
currentLease = parseLease(filePath);
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
if (currentLease.token !== existingLease.token) continue;
|
|
266
|
+
|
|
267
|
+
recoveredStaleLease = true;
|
|
268
|
+
fs.unlinkSync(filePath);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function claimTeamLease(teamId: string, mainSessionId: string): TeamLease {
|
|
273
|
+
fs.mkdirSync(manifestsDirectory(), { recursive: true, mode: 0o700 });
|
|
274
|
+
const lockPath = leaseClaimLockPath(teamId);
|
|
275
|
+
try {
|
|
276
|
+
fs.mkdirSync(lockPath, { mode: 0o700 });
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
279
|
+
throw new Error(`Team ${teamId} lease claim is already in progress`);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
try {
|
|
283
|
+
return claimTeamLeaseUnderLock(teamId, mainSessionId);
|
|
284
|
+
} finally {
|
|
285
|
+
fs.rmdirSync(lockPath);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function releaseTeamLease(lease: TeamLease): void {
|
|
290
|
+
const filePath = leasePath(lease.teamId);
|
|
291
|
+
let currentLease: TeamLease;
|
|
292
|
+
try {
|
|
293
|
+
currentLease = parseLease(filePath);
|
|
294
|
+
} catch (error) {
|
|
295
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
296
|
+
throw error;
|
|
297
|
+
}
|
|
298
|
+
if (currentLease.token !== lease.token) return;
|
|
299
|
+
fs.unlinkSync(filePath);
|
|
300
|
+
}
|
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
|
+
}
|