@giladbarnea/pi-simple-team 2.0.1 → 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;
227
239
  }
228
240
 
229
- export function teamSpawnLines(theme: ThemeLike, team: string, teammates: TeammateSpecView[], roster: string[] = []): string[] {
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 };
244
+ }
245
+
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,32 +311,40 @@ 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
  }
310
334
 
311
- function quotedBody(theme: ThemeLike, message: string, options: { lineLimit: number; barToken: string }): TeamLine[] {
335
+ /** The dim "N more lines · ctrl+o to expand" footer under a collapsed body. */
336
+ function expandHint(theme: ThemeLike, hidden: number): string {
312
337
  const g = glyphs();
313
- const bar = ` ${theme.fg(options.barToken, g.codeBar)} `;
338
+ return theme.fg("dim", `${g.ellipsis} ${hidden} more line${hidden === 1 ? "" : "s"}${g.dot}ctrl+o to expand`);
339
+ }
340
+
341
+ function quotedBody(theme: ThemeLike, message: string, options: { lineLimit: number; barToken: string }): TeamLine[] {
342
+ const bar = ` ${theme.fg(options.barToken, glyphs().codeBar)} `;
314
343
  const lines = message.replace(/\r\n/g, "\n").split("\n");
315
344
  const shown = lines.slice(0, options.lineLimit);
316
345
  const body: TeamLine[] = shown.map((line) => ({ prefix: bar, text: line }));
317
346
  const hidden = lines.length - shown.length;
318
- if (hidden > 0) body.push({ prefix: bar, text: theme.fg("dim", `${g.ellipsis} ${hidden} more line${hidden === 1 ? "" : "s"}${g.dot}ctrl+o to expand`) });
347
+ if (hidden > 0) body.push({ prefix: bar, text: expandHint(theme, hidden) });
319
348
  return body;
320
349
  }
321
350
 
@@ -339,8 +368,12 @@ function hasInterruption(interrupt: unknown): boolean {
339
368
  return interrupt === true || (Array.isArray(interrupt) && interrupt.length > 0);
340
369
  }
341
370
 
371
+ function teamSendHeader(theme: ThemeLike, targets: string[], message: string, interrupt: boolean, roster: string[]): string {
372
+ return headerLine(theme, "Team Send", sendTarget(theme, targets, roster), sendStats(theme, message, interrupt));
373
+ }
374
+
342
375
  export function teamSendLines(theme: ThemeLike, options: { targets: string[]; message: string; interrupt: boolean; expanded: boolean }, roster: string[] = []): TeamLine[] {
343
- const header = headerLine(theme, "Team Send", sendTarget(theme, options.targets, roster), sendStats(theme, options.message, options.interrupt));
376
+ const header = teamSendHeader(theme, options.targets, options.message, options.interrupt, roster);
344
377
  const lineLimit = options.expanded ? Number.POSITIVE_INFINITY : SEND_PREVIEW_LINES;
345
378
  return [header, ...quotedBody(theme, options.message, { lineLimit, barToken: "muted" })];
346
379
  }
@@ -364,20 +397,6 @@ export function scheduleReminderLines(theme: ThemeLike, options: { delayMinutes:
364
397
  return [header, ...quotedBody(theme, options.message, { lineLimit, barToken: "muted" })];
365
398
  }
366
399
 
367
- const TEAMMATE_HUE_TOKENS = ["mdCode", "customMessageLabel", "mdHeading"] as const;
368
-
369
- /**
370
- * actorHueToken("main", ["scout"]) === "accent"; actorHueToken("scout", ["scout"]) === "mdCode"
371
- */
372
- export function actorHueToken(name: string, roster: string[]): string {
373
- if (name === "main") return "accent";
374
- const index = roster.indexOf(name);
375
- return index === -1 ? "text" : TEAMMATE_HUE_TOKENS[index % TEAMMATE_HUE_TOKENS.length]!;
376
- }
377
-
378
- const DIM_SGR_OPEN = "\x1b[2m";
379
- const DIM_SGR_CLOSE = "\x1b[22m";
380
-
381
400
  type LogIcon = "chevron" | "arrow" | "bullet" | "diamond" | "warn" | "fail";
382
401
 
383
402
  type LogDetail =
@@ -524,7 +543,7 @@ export function foldLogEntries(entries: TeamLogEntry[]): LogAction[] {
524
543
  continue;
525
544
  }
526
545
  if (entry.kind === "agent_start") {
527
- 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 };
528
547
  actions.push(action);
529
548
  openTurns.set(who, action);
530
549
  continue;
@@ -538,7 +557,11 @@ export function foldLogEntries(entries: TeamLogEntry[]): LogAction[] {
538
557
  open.details = [textDetail(durationText(open.startEpoch, entry.epochMilliseconds)), ...countDetails];
539
558
  continue;
540
559
  }
541
- 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")] });
542
565
  continue;
543
566
  }
544
567
  if (entry.kind === "spawn") {
@@ -662,8 +685,8 @@ export function teamLogLines(theme: ThemeLike, view: TeamLogRenderView): string[
662
685
  return [header, ...rows, ...(footer ? [footer] : [])];
663
686
  }
664
687
 
665
- export function teamMessageLines(theme: ThemeLike, details: TeamMessageDetails, roster: string[] = []): TeamLine[] {
666
- return [teamMessageHeader(theme, details, roster), ...quotedBody(theme, details.message, { lineLimit: Number.POSITIVE_INFINITY, barToken: "accent" })];
688
+ export function teamMessageLines(theme: ThemeLike, details: TeamMessageDetails, roster: string[] = [], lineLimit = Number.POSITIVE_INFINITY): TeamLine[] {
689
+ return [teamMessageHeader(theme, details, roster), ...quotedBody(theme, details.message, { lineLimit, barToken: "accent" })];
667
690
  }
668
691
 
669
692
  function teamMessageHeader(theme: ThemeLike, details: TeamMessageDetails, roster: string[]): string {
@@ -676,23 +699,23 @@ function teamMessageHeader(theme: ThemeLike, details: TeamMessageDetails, roster
676
699
  ].join("");
677
700
  }
678
701
 
679
- class TeamSendView {
702
+ /** A header over a quote-barred Markdown body, previewing SEND_PREVIEW_LINES body lines unless expanded. */
703
+ class QuotedMarkdownView {
680
704
  private md: Markdown;
681
- private headerStr: string;
682
- private barStr: string;
683
705
  private barWidth: number;
684
- private expanded: boolean;
685
- private theme: ThemeLike;
686
706
  private cachedWidth?: number;
687
707
  private cachedLines?: string[];
688
708
 
689
- constructor(headerStr: string, messageText: string, barStr: string, mdTheme: MarkdownTheme, expanded: boolean, theme: ThemeLike) {
690
- this.headerStr = headerStr;
691
- this.barStr = barStr;
709
+ constructor(
710
+ private readonly headerStr: string,
711
+ messageText: string,
712
+ private readonly barStr: string,
713
+ mdTheme: MarkdownTheme,
714
+ private readonly expanded: boolean,
715
+ private readonly theme: ThemeLike,
716
+ ) {
692
717
  this.barWidth = visibleLength(barStr);
693
718
  this.md = new Markdown(messageText, 0, 0, mdTheme);
694
- this.expanded = expanded;
695
- this.theme = theme;
696
719
  }
697
720
 
698
721
  invalidate(): void {
@@ -705,56 +728,16 @@ class TeamSendView {
705
728
  if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;
706
729
  const header = clipToWidth(this.headerStr, width);
707
730
  const bodyWidth = Math.max(1, width - this.barWidth);
708
- const bodyLines = this.md.render(bodyWidth);
709
- const barred = bodyLines.map((line) => clipToWidth(`${this.barStr}${line}`, width));
710
- if (this.expanded) {
711
- this.cachedLines = [header, ...barred];
712
- this.cachedWidth = width;
713
- return this.cachedLines;
714
- }
715
- const shown = barred.slice(0, SEND_PREVIEW_LINES);
716
- const hidden = barred.length - SEND_PREVIEW_LINES;
717
- if (hidden > 0) {
718
- const g = glyphs();
719
- shown.push(clipToWidth(`${this.barStr}${this.theme.fg("dim", `${g.ellipsis} ${hidden} more line${hidden === 1 ? "" : "s"}${g.dot}ctrl+o to expand`)}`, width));
720
- }
731
+ const barred = this.md.render(bodyWidth).map((line) => clipToWidth(`${this.barStr}${line}`, width));
732
+ const shown = this.expanded ? barred : barred.slice(0, SEND_PREVIEW_LINES);
733
+ const hidden = barred.length - shown.length;
734
+ if (hidden > 0) shown.push(clipToWidth(`${this.barStr}${expandHint(this.theme, hidden)}`, width));
721
735
  this.cachedLines = [header, ...shown];
722
736
  this.cachedWidth = width;
723
737
  return this.cachedLines;
724
738
  }
725
739
  }
726
740
 
727
- class TeamMessageView {
728
- private md: Markdown;
729
- private headerLine: string;
730
- private barStr: string;
731
- private barWidth: number;
732
- private cachedWidth?: number;
733
- private cachedLines?: string[];
734
-
735
- constructor(headerLine: string, messageText: string, barStr: string, mdTheme: MarkdownTheme) {
736
- this.headerLine = headerLine;
737
- this.barStr = barStr;
738
- this.barWidth = visibleLength(barStr);
739
- this.md = new Markdown(messageText, 0, 0, mdTheme);
740
- }
741
-
742
- invalidate(): void {
743
- this.md.invalidate();
744
- this.cachedWidth = undefined;
745
- this.cachedLines = undefined;
746
- }
747
-
748
- render(width: number): string[] {
749
- if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;
750
- const bodyWidth = Math.max(1, width - this.barWidth);
751
- const bodyLines = this.md.render(bodyWidth);
752
- this.cachedLines = [clipToWidth(this.headerLine, width), ...bodyLines.map((line) => clipToWidth(`${this.barStr}${line}`, width))];
753
- this.cachedWidth = width;
754
- return this.cachedLines;
755
- }
756
- }
757
-
758
741
  function accentTeam(theme: ThemeLike, team: unknown): string {
759
742
  return typeof team === "string" && team ? theme.fg("accent", team) : "";
760
743
  }
@@ -797,9 +780,10 @@ function callBodyFor(tool: TeamToolName, theme: ThemeLike, args: Record<string,
797
780
  return callBody(theme, "Team Shutdown", accentTeam(theme, args.team));
798
781
  }
799
782
 
800
- 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[] {
801
784
  if (tool === "team_spawn") {
802
- 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);
803
787
  }
804
788
  if (tool === "team_list") {
805
789
  const teamViews = ((details.teams ?? []) as Array<Record<string, unknown>>).map((entry) => ({
@@ -810,15 +794,15 @@ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<strin
810
794
  updatedAt: String(entry.updatedAt),
811
795
  expiresAt: entry.expiresAt as string | undefined,
812
796
  }));
813
- return teamListLines(theme, teamViews, roster);
797
+ return teamListLines(theme, teamViews, roster, expanded, ((details.unreadableManifests ?? []) as unknown[]).length);
814
798
  }
815
799
  if (tool === "team_resume") {
816
- 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 }));
817
801
  return teamResumeLines(theme, String(details.teamName), teammates, teammates.length, roster);
818
802
  }
819
803
  if (tool === "team_add_teammates") {
820
804
  const memberCount = Object.keys((details.status ?? {}) as Record<string, unknown>).length;
821
- 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);
822
806
  }
823
807
  if (tool === "team_send_message") {
824
808
  return teamSendLines(theme, {
@@ -829,8 +813,8 @@ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<strin
829
813
  }, roster);
830
814
  }
831
815
  if (tool === "team_status") {
832
- if (details.teams) return allTeamsStatusLines(theme, details.teams as Array<{ teamName: string; status: Record<string, TeamStatusView> }>, roster);
833
- 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);
834
818
  }
835
819
  if (tool === "team_log") {
836
820
  const filters = (details.filters ?? {}) as Record<string, unknown>;
@@ -859,7 +843,7 @@ export function renderTeamToolResult(
859
843
  context: ToolRenderContextLike,
860
844
  markdownTheme?: MarkdownTheme,
861
845
  roster: string[] = [],
862
- ): TeamSendView | TeamLines {
846
+ ): QuotedMarkdownView | TeamLines {
863
847
  const args = (context?.args ?? {}) as Record<string, unknown>;
864
848
  if (context?.isError || result?.isError) {
865
849
  return new TeamLines(errorLines(theme, callBodyFor(tool, theme, args, roster), textContent(result)), options.expanded ? "wrap" : "clip");
@@ -867,11 +851,11 @@ export function renderTeamToolResult(
867
851
  const details = (result?.details ?? {}) as Record<string, unknown>;
868
852
  if (markdownTheme && tool === "team_send_message") {
869
853
  const message = String(args.message ?? "");
870
- const header = headerLine(theme, "Team Send", sendTarget(theme, (args.targets ?? []) as string[], roster), sendStats(theme, message, hasInterruption(args.interrupt)));
854
+ const header = teamSendHeader(theme, (args.targets ?? []) as string[], message, hasInterruption(args.interrupt), roster);
871
855
  const bar = ` ${theme.fg("muted", glyphs().codeBar)} `;
872
- return new TeamSendView(header, message, bar, markdownTheme, options.expanded, theme);
856
+ return new QuotedMarkdownView(header, message, bar, markdownTheme, options.expanded, theme);
873
857
  }
874
- 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");
875
859
  }
876
860
 
877
861
  export function renderReminderToolCall(args: Record<string, unknown>, theme: ThemeLike, context: ToolRenderContextLike) {
@@ -898,13 +882,13 @@ export function renderReminderToolResult(
898
882
  );
899
883
  }
900
884
 
901
- export function renderTeamMessage(message: { details?: unknown }, theme: ThemeLike, markdownTheme?: MarkdownTheme, roster: string[] = []): TeamMessageView | TeamLines | undefined {
885
+ export function renderTeamMessage(message: { details?: unknown }, options: { expanded: boolean }, theme: ThemeLike, markdownTheme?: MarkdownTheme, roster: string[] = []): QuotedMarkdownView | TeamLines | undefined {
902
886
  const details = message.details as TeamMessageDetails | undefined;
903
887
  if (!details?.from || !details?.team || typeof details.message !== "string") return undefined;
904
888
  if (markdownTheme) {
905
- const g = glyphs();
906
- const bar = ` ${theme.fg("accent", g.codeBar)} `;
907
- return new TeamMessageView(teamMessageHeader(theme, details, roster), details.message, bar, markdownTheme);
889
+ const bar = ` ${theme.fg("accent", glyphs().codeBar)} `;
890
+ return new QuotedMarkdownView(teamMessageHeader(theme, details, roster), details.message, bar, markdownTheme, options.expanded, theme);
908
891
  }
909
- return new TeamLines(teamMessageLines(theme, details, roster), "wrap");
892
+ const lineLimit = options.expanded ? Number.POSITIVE_INFINITY : SEND_PREVIEW_LINES;
893
+ return new TeamLines(teamMessageLines(theme, details, roster, lineLimit), options.expanded ? "wrap" : "clip");
910
894
  }
@@ -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.",