@giladbarnea/pi-simple-team 2.0.2 → 2.0.3

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/render.ts CHANGED
@@ -5,6 +5,9 @@ import { glyphs } from "./render-support/glyphs.ts";
5
5
  import { stackPrefix, toolLabel, treeConnector, treeStem } from "./render-support/theme.ts";
6
6
  import { commandExit, plural, renderPendingCall, textContent } from "./render-support/text.ts";
7
7
  import { futureTime, monthDay, relativeTime, timeOfDay, type TeamLogEntry } from "./teamlog.ts";
8
+ import { actorHueToken, DIM_SGR_CLOSE, DIM_SGR_OPEN, FactTable, inlineFact, statusWordToken, type FactRow, type TeammateView } from "./teammate-facts.ts";
9
+
10
+ export { actorHueToken, statusWordToken, type TeammateView };
8
11
 
9
12
  export interface ThemeLike {
10
13
  bold(text: string): string;
@@ -54,15 +57,30 @@ export function relativeTimeText(timestamp: string): string {
54
57
  }
55
58
 
56
59
  /** A rendered line with optional wrapping or right-aligned layout metadata. */
57
- export type TeamLine = string | { prefix: string; text: string } | { left: string; right: string };
60
+ type MarkdownTeamLine = { prefix: string; markdown: string; markdownTheme: MarkdownTheme };
61
+
62
+ /** A teammate's fact row. Its table shrinks it to fit the width, in collapsed and expanded views alike. */
63
+ type FactTeamLine = { prefix: string; row: FactRow; table: FactTable };
64
+
65
+ export type TeamLine = string | { prefix: string; text: string } | { left: string; right: string } | MarkdownTeamLine | FactTeamLine;
58
66
 
59
67
  function isRightAlignedTeamLine(line: TeamLine): line is { left: string; right: string } {
60
68
  return typeof line !== "string" && "right" in line;
61
69
  }
62
70
 
71
+ function isMarkdownTeamLine(line: TeamLine): line is MarkdownTeamLine {
72
+ return typeof line !== "string" && "markdown" in line;
73
+ }
74
+
75
+ function isFactTeamLine(line: TeamLine): line is FactTeamLine {
76
+ return typeof line !== "string" && "table" in line;
77
+ }
78
+
63
79
  export function teamLineText(line: TeamLine): string {
64
80
  if (typeof line === "string") return line;
65
81
  if (isRightAlignedTeamLine(line)) return `${line.left}${line.right}`.trimEnd();
82
+ if (isMarkdownTeamLine(line)) return `${line.prefix}${line.markdown}`.trimEnd();
83
+ if (isFactTeamLine(line)) return `${line.prefix}${line.table.full(line.row)}`.trimEnd();
66
84
  return `${line.prefix}${line.text}`.trimEnd();
67
85
  }
68
86
 
@@ -74,13 +92,13 @@ function rightAlignedLine(left: string, right: string, width: number): string {
74
92
  }
75
93
 
76
94
  function wrapTeamLine(line: TeamLine, width: number): string[] {
77
- if (isRightAlignedTeamLine(line)) return [rightAlignedLine(line.left, line.right, width)];
95
+ if (isRightAlignedTeamLine(line) || isFactTeamLine(line)) return [clipTeamLine(line, width)];
78
96
  if (typeof line === "string") {
79
97
  const wrapped = wrapTextWithAnsi(line, width);
80
98
  return wrapped.length > 0 ? wrapped : [""];
81
99
  }
82
100
  const contentWidth = Math.max(1, width - visibleLength(line.prefix));
83
- const wrapped = wrapTextWithAnsi(line.text, contentWidth);
101
+ const wrapped = isMarkdownTeamLine(line) ? new Markdown(line.markdown, 0, 0, line.markdownTheme).render(contentWidth) : wrapTextWithAnsi(line.text, contentWidth);
84
102
  const parts = wrapped.length > 0 ? wrapped : [""];
85
103
  return parts.map((part) => clipToWidth(`${line.prefix}${part}`.trimEnd(), width));
86
104
  }
@@ -89,7 +107,13 @@ function clipToWidth(line: string, width: number): string {
89
107
  return truncateToWidth(line, Math.max(1, width), glyphs().ellipsis);
90
108
  }
91
109
 
110
+ /** Clips each logical line to exactly `width` columns, with no right-margin guard. */
111
+ export function clipTeamLines(lines: TeamLine[], width: number): string[] {
112
+ return lines.map((line) => clipToWidth(clipTeamLine(line, width), width));
113
+ }
114
+
92
115
  function clipTeamLine(line: TeamLine, width: number): string {
116
+ if (isFactTeamLine(line)) return `${line.prefix}${line.table.fit(line.row, width - visibleLength(line.prefix))}`;
93
117
  return isRightAlignedTeamLine(line) ? rightAlignedLine(line.left, line.right, width) : clipToWidth(teamLineText(line), width);
94
118
  }
95
119
 
@@ -111,11 +135,9 @@ export class TeamLines {
111
135
  render(width: number): string[] {
112
136
  if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;
113
137
  const targetWidth = Math.max(1, stableRenderWidth(width));
114
- const renderedLines =
115
- this.mode === "clip"
116
- ? this.lines.map((line) => clipTeamLine(line, targetWidth))
117
- : this.lines.flatMap((line) => wrapTeamLine(line, targetWidth));
118
- this.cachedLines = renderedLines.map((line) => clipToWidth(line, targetWidth));
138
+ this.cachedLines = this.mode === "clip"
139
+ ? clipTeamLines(this.lines, targetWidth)
140
+ : this.lines.flatMap((line) => wrapTeamLine(line, targetWidth)).map((line) => clipToWidth(line, targetWidth));
119
141
  this.cachedWidth = width;
120
142
  return this.cachedLines;
121
143
  }
@@ -153,120 +175,120 @@ export function formatCharCount(count: number): string {
153
175
  return `${count} chars`;
154
176
  }
155
177
 
156
- const STATUS_WORD_TOKENS: Record<string, string> = {
157
- active: "success",
158
- busy: "success",
159
- running: "success",
160
- working: "success",
161
- blocked: "warning",
162
- restarted: "warning",
163
- resumed: "success",
164
- waiting: "warning",
165
- available: "muted",
166
- dormant: "muted",
167
- idle: "muted",
168
- spawned: "muted",
169
- done: "dim",
170
- exited: "dim",
171
- stopped: "dim",
172
- error: "error",
173
- failed: "error",
174
- };
175
-
176
- /**
177
- * statusWordToken("working") === "success"; statusWordToken("reviewing") === "accent"
178
- */
179
- export function statusWordToken(word: string): string {
180
- return STATUS_WORD_TOKENS[word.trim().toLowerCase()] ?? "accent";
181
- }
182
-
183
- function memberRows(theme: ThemeLike, statuses: Record<string, TeamStatusView>, roster: string[], indent = ""): TeamLine[] {
184
- const names = Object.keys(statuses);
185
- const nameWidth = Math.max(...names.map((name) => name.length));
186
- const wordWidth = Math.max(...names.map((name) => statuses[name]!.word.length));
187
- return names.map((name, index) => {
188
- const entry = statuses[name]!;
189
- const branch = index === names.length - 1 ? "└" : "├";
190
- const left = `${indent}${treeConnector(theme, branch)}${theme.fg(actorHueToken(name, roster), padVisible(name, nameWidth))} ${theme.fg(statusWordToken(entry.word), padVisible(entry.word, wordWidth))} ${entry.phrase}`;
191
- const right = theme.fg("dim", relativeTimeText(entry.updated));
192
- return { left, right };
178
+ /** One tree entry per teammate: its fact row, then the rows `below` returns under the entry's stem. */
179
+ function teammateTree<Row extends FactRow>(
180
+ theme: ThemeLike,
181
+ rows: Row[],
182
+ roster: string[],
183
+ below: (row: Row, stem: string, isLast: boolean) => TeamLine[] = () => [],
184
+ indent = "",
185
+ ): TeamLine[] {
186
+ const table = new FactTable(theme, rows, roster);
187
+ return rows.flatMap((row, index) => {
188
+ const isLast = index === rows.length - 1;
189
+ const branch = isLast ? "└" : "├";
190
+ const stem = `${indent}${treeStem(theme, branch)}`;
191
+ return [{ prefix: `${indent}${treeConnector(theme, branch)}`, row, table }, ...below(row, stem, isLast)];
193
192
  });
194
193
  }
195
194
 
196
- export function teamStatusLines(theme: ThemeLike, team: string, statuses: Record<string, TeamStatusView>, roster: string[] = []): TeamLine[] {
195
+ /** A status row's phrase sits on its own line under the facts, with its time right-aligned. */
196
+ function statusPhraseLine(theme: ThemeLike, indent: string, status: TeamStatusView): TeamLine {
197
+ return { left: `${indent}${status.phrase}`, right: theme.fg("dim", ` ${relativeTimeText(status.updated)}`) };
198
+ }
199
+
200
+ type StatusRow = FactRow & { entry: TeamStatusView };
201
+
202
+ /** Status rows pair each participant's status with its teammate facts. Main has no teammate facts. */
203
+ function statusRows(statuses: Record<string, TeamStatusView>, teammates: Record<string, TeammateView> = {}): StatusRow[] {
204
+ return Object.entries(statuses).map(([name, entry]) => ({ ...teammates[name], name, status: entry.word, entry }));
205
+ }
206
+
207
+ /** Each participant's fact row with its status phrase under it, and an empty row before the next participant. Team Status and the /team overlay share it. */
208
+ export function memberRows(theme: ThemeLike, statuses: Record<string, TeamStatusView>, teammates: Record<string, TeammateView> | undefined, roster: string[], indent = ""): TeamLine[] {
209
+ const below = (row: StatusRow, stem: string, isLast: boolean): TeamLine[] => [statusPhraseLine(theme, stem, row.entry), ...(isLast ? [] : [{ prefix: stem, text: "" }])];
210
+ return teammateTree(theme, statusRows(statuses, teammates), roster, below, indent);
211
+ }
212
+
213
+ export function teamStatusLines(theme: ThemeLike, team: string, statuses: Record<string, TeamStatusView>, roster: string[] = [], teammates?: Record<string, TeammateView>): TeamLine[] {
197
214
  const members = Object.values(statuses);
198
215
  const workingCount = members.filter((member) => statusWordToken(member.word) === "success").length;
199
216
  const stats = [theme.fg("muted", plural(members.length, "member"))];
200
217
  if (workingCount > 0) stats.push(theme.fg("success", `${workingCount} working`));
201
- return [headerLine(theme, "Team Status", theme.fg("accent", team), stats), ...memberRows(theme, statuses, roster)];
218
+ return [headerLine(theme, "Team Status", theme.fg("accent", team), stats), ...memberRows(theme, statuses, teammates, roster)];
202
219
  }
203
220
 
204
- export function allTeamsStatusLines(theme: ThemeLike, teams: Array<{ teamName: string; status: Record<string, TeamStatusView> }>, roster: string[] = []): TeamLine[] {
221
+ export function allTeamsStatusLines(theme: ThemeLike, teams: Array<{ teamName: string; status: Record<string, TeamStatusView>; teammates?: Record<string, TeammateView> }>, roster: string[] = []): TeamLine[] {
205
222
  const lines: TeamLine[] = [headerLine(theme, "Team Status", theme.fg("muted", plural(teams.length, "team")))];
206
223
  teams.forEach((team, index) => {
207
224
  const branch = index === teams.length - 1 ? "└" : "├";
208
225
  lines.push(`${treeConnector(theme, branch)}${theme.fg("accent", team.teamName)}`);
209
- lines.push(...memberRows(theme, team.status, roster, treeStem(theme, branch)));
226
+ lines.push(...memberRows(theme, team.status, team.teammates, roster, treeStem(theme, branch)));
210
227
  });
211
228
  return lines;
212
229
  }
213
230
 
214
- interface TeammateSpecView {
215
- name: string;
216
- model: string;
217
- thinking?: string;
231
+ interface TeammateSpecView extends TeammateView {
232
+ systemPrompt: string;
218
233
  }
219
234
 
220
- function teammateSpecRows(theme: ThemeLike, teammates: TeammateSpecView[], roster: string[]): string[] {
221
- const nameWidth = Math.max(...teammates.map((teammate) => teammate.name.length));
222
- return teammates.map((teammate, index) => {
223
- const branch = index === teammates.length - 1 ? "└" : "├";
224
- const spec = statLine(theme, [theme.fg("muted", teammate.model), theme.fg("dim", teammate.thinking ?? "")]);
225
- return `${treeConnector(theme, branch)}${theme.fg(actorHueToken(teammate.name, roster), padVisible(teammate.name, nameWidth))} ${spec}`;
226
- });
235
+ /** @example specRow({ name: "a", model: "m", systemPrompt: "p", live: true }) // { name: "a", model: "m", ... } without `live` */
236
+ function specRow(spec: TeammateSpecView): FactRow & { systemPrompt: string } {
237
+ const { live: _live, ...row } = spec;
238
+ return row;
239
+ }
240
+
241
+ /** A full quote-barred Markdown text nested under a tree row. */
242
+ function treeQuote(prefix: string, theme: ThemeLike, markdown: string, markdownTheme: MarkdownTheme): MarkdownTeamLine {
243
+ return { prefix: `${prefix}${theme.fg("muted", glyphs().codeBar)} `, markdown, markdownTheme };
227
244
  }
228
245
 
229
- export function teamSpawnLines(theme: ThemeLike, team: string, teammates: TeammateSpecView[], roster: string[] = []): string[] {
246
+ /** One row per teammate. Expanded entries (given a Markdown theme) add the full system prompt and a spacer before the next entry. */
247
+ function teammateSpecRows(theme: ThemeLike, teammates: TeammateSpecView[], roster: string[], expandedMarkdownTheme?: MarkdownTheme): TeamLine[] {
248
+ const below = (row: FactRow & { systemPrompt: string }, stem: string, isLast: boolean): TeamLine[] => expandedMarkdownTheme
249
+ ? [treeQuote(stem, theme, row.systemPrompt, expandedMarkdownTheme), ...(isLast ? [] : [{ prefix: stem, text: "" }])]
250
+ : [];
251
+ return teammateTree(theme, teammates.map(specRow), roster, below);
252
+ }
253
+
254
+ export function teamSpawnLines(theme: ThemeLike, team: string, teammates: TeammateSpecView[], roster: string[] = [], expansion?: { commonPrompt: string; markdownTheme: MarkdownTheme }): TeamLine[] {
230
255
  const header = headerLine(theme, "Team Spawn", theme.fg("accent", team), [theme.fg("muted", plural(teammates.length, "teammate"))]);
231
- return [header, ...teammateSpecRows(theme, teammates, roster)];
256
+ const stem = treeStem(theme, "├");
257
+ const commonPromptRows: TeamLine[] = expansion
258
+ ? [`${treeConnector(theme, "├")}${theme.fg("accent", "common prompt")}`, treeQuote(stem, theme, expansion.commonPrompt, expansion.markdownTheme), { prefix: stem, text: "" }]
259
+ : [];
260
+ return [header, ...commonPromptRows, ...teammateSpecRows(theme, teammates, roster, expansion?.markdownTheme)];
232
261
  }
233
262
 
234
- export function teamAddLines(theme: ThemeLike, team: string, teammates: TeammateSpecView[], memberCount: number, roster: string[] = []): string[] {
263
+ export function teamAddLines(theme: ThemeLike, team: string, teammates: TeammateSpecView[], memberCount: number, roster: string[] = [], expandedMarkdownTheme?: MarkdownTheme): TeamLine[] {
235
264
  const header = headerLine(theme, "Team Add", theme.fg("accent", team), [
236
265
  theme.fg("muted", `${teammates.length} added`),
237
266
  theme.fg("muted", plural(memberCount, "member")),
238
267
  ]);
239
- return [header, ...teammateSpecRows(theme, teammates, roster)];
268
+ return [header, ...teammateSpecRows(theme, teammates, roster, expandedMarkdownTheme)];
240
269
  }
241
270
 
242
- export interface ResumedMemberView {
243
- name: string;
271
+ export interface ResumedMemberView extends TeammateView {
244
272
  restored?: boolean;
245
273
  live: boolean;
246
274
  active: boolean;
247
275
  }
248
276
 
249
- export function teamResumeLines(theme: ThemeLike, team: string, resumed: ResumedMemberView[], teammateCount: number, roster: string[] = []): string[] {
277
+ export function teamResumeLines(theme: ThemeLike, team: string, resumed: ResumedMemberView[], teammateCount: number, roster: string[] = []): TeamLine[] {
250
278
  const resumedCount = resumed.filter((member) => member.restored !== undefined).length;
251
279
  const countText = resumedCount === teammateCount ? `${resumedCount} resumed` : `${resumedCount} of ${teammateCount} resumed`;
252
280
  const header = headerLine(theme, "Team Resume", theme.fg("accent", team), [theme.fg("muted", countText)]);
253
281
  if (resumed.length === 0) return [header, `${treeConnector(theme, "└")}${theme.fg("muted", "no stopped teammates")}`];
254
- const nameWidth = Math.max(...resumed.map((member) => member.name.length));
255
- const words = resumed.map((member) => member.restored === undefined ? member.active ? "working" : member.live ? "idle" : "stopped" : member.restored ? "resumed" : "restarted");
256
- const wordWidth = Math.max(...words.map((word) => word.length));
257
- const rows = resumed.map((member, index) => {
258
- const branch = index === resumed.length - 1 ? "└" : "├";
259
- const word = words[index];
260
- const note = member.restored === undefined ? "" : `${member.restored ? "history restored" : "empty session"}, ${member.active ? "working" : "idle"}`;
261
- return `${treeConnector(theme, branch)}${theme.fg(actorHueToken(member.name, roster), padVisible(member.name, nameWidth))} ${theme.fg(statusWordToken(word), padVisible(word, wordWidth))} ${theme.fg("muted", note)}`;
262
- });
263
- return [header, ...rows];
282
+ const rows = resumed.map(({ restored, active, ...member }) => ({
283
+ ...member,
284
+ status: restored === undefined ? active ? "working" : member.live ? "idle" : "stopped" : restored ? "resumed" : "restarted",
285
+ note: restored === undefined ? "" : `${restored ? "history restored" : "empty session"}, ${active ? "working" : "idle"}`,
286
+ }));
287
+ return [header, ...teammateTree(theme, rows, roster, (row, stem) => (row.note ? [`${stem}${theme.fg("muted", row.note)}`] : []))];
264
288
  }
265
289
 
266
- export interface TeamListMemberView {
267
- name: string;
290
+ export interface TeamListMemberView extends TeammateView {
268
291
  live: boolean;
269
- canManageOwnTeams: boolean;
270
292
  }
271
293
 
272
294
  export interface TeamListTeamView {
@@ -279,10 +301,9 @@ export interface TeamListTeamView {
279
301
  }
280
302
 
281
303
  function teamListMemberName(theme: ThemeLike, teamView: TeamListTeamView, member: TeamListMemberView, roster: string[]): string {
282
- let name = theme.fg(actorHueToken(member.name, roster), member.name);
283
- if (teamView.state === "active" && !member.live) name = `${DIM_SGR_OPEN}${name}${DIM_SGR_CLOSE}`;
284
- if (member.canManageOwnTeams) name += theme.fg("dim", glyphs().diamond);
285
- return name;
304
+ const hued = theme.fg(actorHueToken(member.name, roster), member.name);
305
+ const name = teamView.state === "active" && !member.live ? `${DIM_SGR_OPEN}${hued}${DIM_SGR_CLOSE}` : hued;
306
+ return [name, inlineFact(theme, "manager", member)].filter((part) => part.length > 0).join(" ");
286
307
  }
287
308
 
288
309
  function teamListTimestamp(teamView: TeamListTeamView): string {
@@ -290,20 +311,23 @@ function teamListTimestamp(teamView: TeamListTeamView): string {
290
311
  return `updated ${relativeTime(Date.parse(teamView.updatedAt), Date.now())}`;
291
312
  }
292
313
 
293
- export function teamListLines(theme: ThemeLike, teamViews: TeamListTeamView[], roster: string[] = []): TeamLine[] {
314
+ /** Collapsed, each team lists its teammate names inline. Expanded, each teammate gets its own fact row. */
315
+ export function teamListLines(theme: ThemeLike, teamViews: TeamListTeamView[], roster: string[] = [], expanded = false, unreadableCount = 0): TeamLine[] {
294
316
  const activeCount = teamViews.filter((teamView) => teamView.state === "active").length;
295
317
  const stats = [theme.fg("muted", plural(teamViews.length, "team"))];
296
318
  if (activeCount > 0) stats.push(theme.fg("success", `${activeCount} active`));
319
+ if (unreadableCount > 0) stats.push(theme.fg("warning", `${unreadableCount} unreadable`));
297
320
  const header = headerLine(theme, "Team List", "", stats);
298
321
  if (teamViews.length === 0) return [header, `${treeConnector(theme, "└")}${theme.fg("muted", "no teams")}`];
299
322
  const nameWidth = Math.max(...teamViews.map((teamView) => teamView.name.length));
300
323
  const stateWidth = Math.max(...teamViews.map((teamView) => teamView.state.length));
301
- const rows: TeamLine[] = teamViews.map((teamView, index) => {
324
+ const rows: TeamLine[] = teamViews.flatMap((teamView, index) => {
302
325
  const branch = index === teamViews.length - 1 ? "└" : "├";
303
- const rosterText = teamView.members.map((member) => teamListMemberName(theme, teamView, member, roster)).join(theme.fg("muted", glyphs().dot));
326
+ const rosterText = expanded ? "" : teamView.members.map((member) => teamListMemberName(theme, teamView, member, roster)).join(theme.fg("muted", glyphs().dot));
304
327
  const staleLease = teamView.leaseState === "stale" ? `${dimDot(theme)}${theme.fg("error", "stale lease")}` : "";
305
328
  const left = `${treeConnector(theme, branch)}${theme.fg("accent", padVisible(teamView.name, nameWidth))} ${theme.fg(statusWordToken(teamView.state), padVisible(teamView.state, stateWidth))} ${rosterText}${staleLease}`;
306
- return { left, right: theme.fg("dim", teamListTimestamp(teamView)) };
329
+ const memberRows = expanded ? teammateTree(theme, teamView.members, roster, undefined, treeStem(theme, branch)) : [];
330
+ return [{ left, right: theme.fg("dim", teamListTimestamp(teamView)) }, ...memberRows];
307
331
  });
308
332
  return [header, ...rows];
309
333
  }
@@ -373,20 +397,6 @@ export function scheduleReminderLines(theme: ThemeLike, options: { delayMinutes:
373
397
  return [header, ...quotedBody(theme, options.message, { lineLimit, barToken: "muted" })];
374
398
  }
375
399
 
376
- const TEAMMATE_HUE_TOKENS = ["mdCode", "customMessageLabel", "mdHeading"] as const;
377
-
378
- /**
379
- * actorHueToken("main", ["scout"]) === "accent"; actorHueToken("scout", ["scout"]) === "mdCode"
380
- */
381
- export function actorHueToken(name: string, roster: string[]): string {
382
- if (name === "main") return "accent";
383
- const index = roster.indexOf(name);
384
- return index === -1 ? "text" : TEAMMATE_HUE_TOKENS[index % TEAMMATE_HUE_TOKENS.length]!;
385
- }
386
-
387
- const DIM_SGR_OPEN = "\x1b[2m";
388
- const DIM_SGR_CLOSE = "\x1b[22m";
389
-
390
400
  type LogIcon = "chevron" | "arrow" | "bullet" | "diamond" | "warn" | "fail";
391
401
 
392
402
  type LogDetail =
@@ -533,7 +543,7 @@ export function foldLogEntries(entries: TeamLogEntry[]): LogAction[] {
533
543
  continue;
534
544
  }
535
545
  if (entry.kind === "agent_start") {
536
- const action: LogAction = { ...base, icon: "diamond", iconToken: "borderMuted", action: "turn", details: [textDetail(ellipsis)], startEpoch: entry.epochMilliseconds };
546
+ const action: LogAction = { ...base, icon: "diamond", iconToken: "borderMuted", action: "attempt", details: [textDetail(ellipsis)], startEpoch: entry.epochMilliseconds };
537
547
  actions.push(action);
538
548
  openTurns.set(who, action);
539
549
  continue;
@@ -547,7 +557,11 @@ export function foldLogEntries(entries: TeamLogEntry[]): LogAction[] {
547
557
  open.details = [textDetail(durationText(open.startEpoch, entry.epochMilliseconds)), ...countDetails];
548
558
  continue;
549
559
  }
550
- actions.push({ ...base, icon: "diamond", iconToken: "borderMuted", action: "turn", details: countDetails });
560
+ actions.push({ ...base, icon: "diamond", iconToken: "borderMuted", action: "attempt", details: countDetails });
561
+ continue;
562
+ }
563
+ if (entry.kind === "agent_settled") {
564
+ actions.push({ ...base, icon: "diamond", iconToken: details.aborted ? "warning" : "borderMuted", action: "run", details: [textDetail(details.aborted ? "cancelled" : "ended")] });
551
565
  continue;
552
566
  }
553
567
  if (entry.kind === "spawn") {
@@ -766,9 +780,10 @@ function callBodyFor(tool: TeamToolName, theme: ThemeLike, args: Record<string,
766
780
  return callBody(theme, "Team Shutdown", accentTeam(theme, args.team));
767
781
  }
768
782
 
769
- function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<string, unknown>, details: Record<string, unknown>, expanded: boolean, roster: string[]): TeamLine[] {
783
+ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<string, unknown>, details: Record<string, unknown>, expanded: boolean, roster: string[], markdownTheme?: MarkdownTheme): TeamLine[] {
770
784
  if (tool === "team_spawn") {
771
- return teamSpawnLines(theme, String(details.teamName), details.teammates as TeammateSpecView[], roster);
785
+ const expansion = expanded ? { commonPrompt: args.commonPrompt as string, markdownTheme: markdownTheme! } : undefined;
786
+ return teamSpawnLines(theme, String(details.teamName), details.teammates as TeammateSpecView[], roster, expansion);
772
787
  }
773
788
  if (tool === "team_list") {
774
789
  const teamViews = ((details.teams ?? []) as Array<Record<string, unknown>>).map((entry) => ({
@@ -779,15 +794,15 @@ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<strin
779
794
  updatedAt: String(entry.updatedAt),
780
795
  expiresAt: entry.expiresAt as string | undefined,
781
796
  }));
782
- return teamListLines(theme, teamViews, roster);
797
+ return teamListLines(theme, teamViews, roster, expanded, ((details.unreadableManifests ?? []) as unknown[]).length);
783
798
  }
784
799
  if (tool === "team_resume") {
785
- const teammates = (details.teammates as Array<{ name: string; contextRestored?: boolean; live: boolean; active: boolean }>).map((member) => ({ name: member.name, restored: member.contextRestored, live: member.live, active: member.active }));
800
+ const teammates = (details.teammates as Array<ResumedMemberView & { contextRestored?: boolean }>).map(({ contextRestored, ...member }) => ({ ...member, restored: contextRestored }));
786
801
  return teamResumeLines(theme, String(details.teamName), teammates, teammates.length, roster);
787
802
  }
788
803
  if (tool === "team_add_teammates") {
789
804
  const memberCount = Object.keys((details.status ?? {}) as Record<string, unknown>).length;
790
- return teamAddLines(theme, String(details.teamName), (args.teammates ?? []) as TeammateSpecView[], memberCount, roster);
805
+ return teamAddLines(theme, String(details.teamName), details.addedTeammates as TeammateSpecView[], memberCount, roster, expanded ? markdownTheme! : undefined);
791
806
  }
792
807
  if (tool === "team_send_message") {
793
808
  return teamSendLines(theme, {
@@ -798,8 +813,8 @@ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<strin
798
813
  }, roster);
799
814
  }
800
815
  if (tool === "team_status") {
801
- if (details.teams) return allTeamsStatusLines(theme, details.teams as Array<{ teamName: string; status: Record<string, TeamStatusView> }>, roster);
802
- return teamStatusLines(theme, String(details.teamName), details.status as Record<string, TeamStatusView>, roster);
816
+ if (details.teams) return allTeamsStatusLines(theme, details.teams as Array<{ teamName: string; status: Record<string, TeamStatusView>; teammates?: Record<string, TeammateView> }>, roster);
817
+ return teamStatusLines(theme, String(details.teamName), details.status as Record<string, TeamStatusView>, roster, details.teammates as Record<string, TeammateView> | undefined);
803
818
  }
804
819
  if (tool === "team_log") {
805
820
  const filters = (details.filters ?? {}) as Record<string, unknown>;
@@ -840,7 +855,7 @@ export function renderTeamToolResult(
840
855
  const bar = ` ${theme.fg("muted", glyphs().codeBar)} `;
841
856
  return new QuotedMarkdownView(header, message, bar, markdownTheme, options.expanded, theme);
842
857
  }
843
- return new TeamLines(resultLinesFor(tool, theme, args, details, options.expanded, roster), options.expanded ? "wrap" : "clip");
858
+ return new TeamLines(resultLinesFor(tool, theme, args, details, options.expanded, roster, markdownTheme), options.expanded ? "wrap" : "clip");
844
859
  }
845
860
 
846
861
  export function renderReminderToolCall(args: Record<string, unknown>, theme: ThemeLike, context: ToolRenderContextLike) {
@@ -0,0 +1,27 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+
3
+ const dateTimeFormatter = new Intl.DateTimeFormat("en-GB", {
4
+ year: "numeric", month: "short", day: "2-digit",
5
+ hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", timeZoneName: "longOffset",
6
+ });
7
+
8
+ /** Select direct evidence of model activity, not trailing input, staging, or metadata. @example lastRecordedModelActivity([]) // undefined */
9
+ export function lastRecordedModelActivity(branch: readonly SessionEntry[]): string | undefined {
10
+ return branch.findLast((entry) =>
11
+ (entry.type === "message" && (entry.message.role === "assistant" || entry.message.role === "toolResult")) ||
12
+ ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage !== undefined),
13
+ )?.timestamp;
14
+ }
15
+
16
+ /** Ground a resumed teammate without repeating its saved assignment. @example composeResumptionMessage("review", "scout", undefined).includes('team "review"') // true */
17
+ export function composeResumptionMessage(teamName: string, teammateName: string, lastActivity: string | undefined, instructions?: string, now: Date = new Date()): string {
18
+ return [
19
+ `You are teammate "${teammateName}" on team "${teamName}". This session has resumed.`,
20
+ `Current time: ${dateTimeFormatter.format(now)}.`,
21
+ lastActivity === undefined
22
+ ? "No prior model activity is recorded in this conversation branch."
23
+ : `Your last recorded model activity was ${dateTimeFormatter.format(new Date(lastActivity))}.`,
24
+ "Continue from the saved progress. This resumption and any new instructions below take precedence over earlier team assignments. Treat earlier conversation as background.",
25
+ instructions,
26
+ ].filter((part) => part !== undefined).join("\n\n");
27
+ }
Binary file
@@ -1,6 +1,7 @@
1
1
  import { bundledSkillsInstruction } from "./bundled-skill.ts";
2
2
 
3
- export function composeSystemPrompt(
3
+ /** Compose the one-time custom team briefing. @example composeTeamBriefing("review", "Shared", "scout", "Inspect", []).includes("<team-system-message>") // true */
4
+ export function composeTeamBriefing(
4
5
  teamName: string,
5
6
  teamPrompt: string,
6
7
  teammateName: string,
@@ -10,9 +11,10 @@ export function composeSystemPrompt(
10
11
  ): string {
11
12
  return [
12
13
  bundledSkillsInstruction,
13
- teamPrompt.trim(),
14
- teammatePrompt.trim(),
14
+ `<team-system-message>\n${teamPrompt.trim()}\n</team-system-message>`,
15
+ `<your-specific-system-message>\n${teammatePrompt.trim()}\n</your-specific-system-message>`,
15
16
  `You are ${teammateName}, a teammate on team ${teamName}.`,
17
+ "Work on your current team assignment. Treat inherited conversation as background for this assignment.",
16
18
  `Participants: main, ${participants.join(", ")}.`,
17
19
  "Use team_send_message to talk to teammates, send_main_message to talk to the main agent, and team_status to set/read public statuses.",
18
20
  "The main agent is the current coordinator. Use the team tools and available session history to share relevant context.",
package/team-registry.ts CHANGED
@@ -69,7 +69,7 @@ function isManifestMember(value: unknown): value is TeamManifestMember {
69
69
  typeof member.systemPrompt === "string" &&
70
70
  typeof member.model === "string" &&
71
71
  typeof member.thinking === "string" &&
72
- typeof member.inheritMainContext === "boolean" &&
72
+ typeof member.forkContext === "boolean" &&
73
73
  typeof member.canManageOwnTeams === "boolean" &&
74
74
  typeof member.showOnHerdrPane === "boolean" &&
75
75
  typeof member.live === "boolean" &&
@@ -77,6 +77,7 @@ function isManifestMember(value: unknown): value is TeamManifestMember {
77
77
  typeof member.teammateId === "string" &&
78
78
  typeof member.sessionFile === "string" &&
79
79
  typeof member.sessionMaterialized === "boolean" &&
80
+ (member.contextPercent === undefined || typeof member.contextPercent === "number") &&
80
81
  (member.extensionPaths === undefined || (Array.isArray(member.extensionPaths) && member.extensionPaths.every((value) => typeof value === "string" && path.isAbsolute(value))))
81
82
  );
82
83
  }
@@ -148,27 +149,55 @@ export function writeTeamManifest(manifest: TeamManifest): void {
148
149
  fs.renameSync(temporaryPath, filePath);
149
150
  }
150
151
 
151
- export function listTeamManifests(projectDirectory: string): TeamManifest[] {
152
+ /** Whether a saved attachment file holds this team ID, readable or not. */
153
+ export function teamManifestExists(teamId: string): boolean {
154
+ return fs.existsSync(manifestPath(teamId));
155
+ }
156
+
157
+ export interface UnreadableManifest {
158
+ filePath: string;
159
+ error: string;
160
+ }
161
+
162
+ /** The project an unreadable manifest names, when its JSON still says. */
163
+ function claimedProjectDirectory(filePath: string): string | undefined {
164
+ try {
165
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf8")) as { projectDirectory?: unknown };
166
+ return typeof parsed.projectDirectory === "string" ? parsed.projectDirectory : undefined;
167
+ } catch {
168
+ return undefined;
169
+ }
170
+ }
171
+
172
+ /**
173
+ * The current project's readable manifests, plus the unreadable ones that may belong to it.
174
+ * A manifest from another Pi Simple Team version or another project never blocks this project.
175
+ */
176
+ export function listTeamManifests(projectDirectory: string): { manifests: TeamManifest[]; unreadable: UnreadableManifest[] } {
152
177
  const directory = manifestsDirectory();
153
- if (!fs.existsSync(directory)) return [];
178
+ if (!fs.existsSync(directory)) return { manifests: [], unreadable: [] };
154
179
 
155
180
  const resolvedProjectDirectory = canonicalProjectDirectory(projectDirectory);
156
181
  const now = Date.now();
157
- return fs
158
- .readdirSync(directory, { withFileTypes: true })
159
- .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
160
- .map((entry) => ({ filePath: path.join(directory, entry.name), manifest: parseManifest(path.join(directory, entry.name)) }))
161
- .filter(({ filePath, manifest }) => {
162
- const expiresAt = Date.parse(manifest.expiresAt ?? "");
163
- const expired = manifest.state === "dormant" && now >= expiresAt;
164
- if (!expired) return true;
182
+ const manifests: TeamManifest[] = [];
183
+ const unreadable: UnreadableManifest[] = [];
184
+ const filePaths = fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path.join(directory, entry.name));
185
+ for (const filePath of filePaths) {
186
+ let manifest: TeamManifest;
187
+ try {
188
+ manifest = parseManifest(filePath);
189
+ } catch (error) {
190
+ if ((claimedProjectDirectory(filePath) ?? resolvedProjectDirectory) === resolvedProjectDirectory) unreadable.push({ filePath, error: error instanceof Error ? error.message : String(error) });
191
+ continue;
192
+ }
193
+ if (manifest.state === "dormant" && now >= Date.parse(manifest.expiresAt ?? "")) {
165
194
  fs.rmSync(leasePath(manifest.id), { force: true });
166
195
  fs.rmSync(filePath);
167
- return false;
168
- })
169
- .map(({ manifest }) => manifest)
170
- .filter((manifest) => manifest.projectDirectory === resolvedProjectDirectory)
171
- .sort((left, right) => left.id.localeCompare(right.id));
196
+ continue;
197
+ }
198
+ if (manifest.projectDirectory === resolvedProjectDirectory) manifests.push(manifest);
199
+ }
200
+ return { manifests: manifests.sort((left, right) => left.id.localeCompare(right.id)), unreadable };
172
201
  }
173
202
 
174
203
  export function readTeamLeaseState(teamId: string): { state: "unclaimed" | "claimed" | "stale"; mainSessionId?: string } {