@giladbarnea/pi-simple-team 1.0.0

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 ADDED
@@ -0,0 +1,494 @@
1
+ import { Markdown, type MarkdownTheme, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
2
+
3
+ import { padVisible, stableRenderWidth, visibleLength } from "./render-support/ansi.ts";
4
+ import { glyphs } from "./render-support/glyphs.ts";
5
+ import { stackPrefix, toolLabel, treeConnector, treeStem } from "./render-support/theme.ts";
6
+ import { plural, renderPendingCall, textContent } from "./render-support/text.ts";
7
+ import { timeOfDay, type TeamLogEntry, type TeamLogKind } from "./teamlog.ts";
8
+
9
+ export interface ThemeLike {
10
+ bold(text: string): string;
11
+ fg(token: string, text: string): string;
12
+ }
13
+
14
+ interface ToolRenderContextLike {
15
+ args?: Record<string, unknown>;
16
+ cwd?: string;
17
+ executionStarted?: boolean;
18
+ invalidate?: () => void;
19
+ isError?: boolean;
20
+ isPartial?: boolean;
21
+ toolCallId?: string;
22
+ }
23
+
24
+ export type TeamToolName = "team_spawn" | "teamsend" | "teamstatus" | "teamlog" | "team_shutdown";
25
+
26
+ export interface TeamStatusView {
27
+ word: string;
28
+ phrase: string;
29
+ updated: string;
30
+ }
31
+
32
+ export interface TeamMessageDetails {
33
+ team: string;
34
+ from: string;
35
+ sentAt: string;
36
+ message: string;
37
+ }
38
+
39
+ interface TeamLogRenderView {
40
+ team: string;
41
+ entries: TeamLogEntry[];
42
+ totalMatched: number;
43
+ returned: number;
44
+ nextCursor?: string;
45
+ filters?: Record<string, unknown>;
46
+ }
47
+
48
+ /** A rendered line; the prefixed form re-applies its prefix (e.g. a quote bar) to wrapped continuations. */
49
+ export type TeamLine = string | { prefix: string; text: string };
50
+
51
+ export function teamLineText(line: TeamLine): string {
52
+ return typeof line === "string" ? line : `${line.prefix}${line.text}`.trimEnd();
53
+ }
54
+
55
+ function wrapTeamLine(line: TeamLine, width: number): string[] {
56
+ if (typeof line === "string") {
57
+ const wrapped = wrapTextWithAnsi(line, width);
58
+ return wrapped.length > 0 ? wrapped : [""];
59
+ }
60
+ const contentWidth = Math.max(10, width - visibleLength(line.prefix));
61
+ const wrapped = wrapTextWithAnsi(line.text, contentWidth);
62
+ const parts = wrapped.length > 0 ? wrapped : [""];
63
+ return parts.map((part) => `${line.prefix}${part}`.trimEnd());
64
+ }
65
+
66
+ /** Clips each logical line to the render width (collapsed) or wraps it (expanded). */
67
+ export class TeamLines {
68
+ private cachedWidth?: number;
69
+ private cachedLines?: string[];
70
+
71
+ constructor(
72
+ private readonly lines: TeamLine[],
73
+ private readonly mode: "clip" | "wrap",
74
+ ) {}
75
+
76
+ invalidate(): void {
77
+ this.cachedWidth = undefined;
78
+ this.cachedLines = undefined;
79
+ }
80
+
81
+ render(width: number): string[] {
82
+ if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;
83
+ const targetWidth = Math.max(1, stableRenderWidth(width));
84
+ this.cachedLines =
85
+ this.mode === "clip"
86
+ ? this.lines.map((line) => truncateToWidth(teamLineText(line), targetWidth, glyphs().ellipsis))
87
+ : this.lines.flatMap((line) => wrapTeamLine(line, targetWidth));
88
+ this.cachedWidth = width;
89
+ return this.cachedLines;
90
+ }
91
+ }
92
+
93
+ function dimDot(theme: ThemeLike): string {
94
+ return theme.fg("dim", glyphs().dot);
95
+ }
96
+
97
+ function statLine(theme: ThemeLike, parts: string[]): string {
98
+ return parts.filter((part) => part.length > 0).join(dimDot(theme));
99
+ }
100
+
101
+ function callBody(theme: ThemeLike, label: string, target: string, stats: string[] = []): string {
102
+ const head = target ? `${toolLabel(theme, `${label} `)}${target}` : toolLabel(theme, label);
103
+ const tail = statLine(theme, stats);
104
+ return tail ? `${head}${dimDot(theme)}${tail}` : head;
105
+ }
106
+
107
+ function headerLine(theme: ThemeLike, label: string, target: string, stats: string[] = []): string {
108
+ return `${stackPrefix(theme)}${callBody(theme, label, target, stats)}`;
109
+ }
110
+
111
+ function errorLines(theme: ThemeLike, body: string, errorText: string): string[] {
112
+ const firstLine = errorText.split(/\r?\n/)[0] || "failed";
113
+ return [`${stackPrefix(theme)}${body}${dimDot(theme)}${theme.fg("error", firstLine)}`];
114
+ }
115
+
116
+ /**
117
+ * formatCharCount(4) === "4 chars"; formatCharCount(4463) === "4.5k chars"; formatCharCount(45210) === "45k chars"
118
+ */
119
+ export function formatCharCount(count: number): string {
120
+ if (count >= 10_000) return `${Math.round(count / 1000)}k chars`;
121
+ if (count >= 1_000) return `${(count / 1000).toFixed(1)}k chars`;
122
+ return `${count} chars`;
123
+ }
124
+
125
+ const STATUS_WORD_TOKENS: Record<string, string> = {
126
+ active: "success",
127
+ busy: "success",
128
+ running: "success",
129
+ working: "success",
130
+ blocked: "warning",
131
+ waiting: "warning",
132
+ available: "muted",
133
+ idle: "muted",
134
+ spawned: "muted",
135
+ done: "dim",
136
+ exited: "dim",
137
+ stopped: "dim",
138
+ error: "error",
139
+ failed: "error",
140
+ };
141
+
142
+ /**
143
+ * statusWordToken("working") === "success"; statusWordToken("reviewing") === "accent"
144
+ */
145
+ export function statusWordToken(word: string): string {
146
+ return STATUS_WORD_TOKENS[word.trim().toLowerCase()] ?? "accent";
147
+ }
148
+
149
+ function memberRows(theme: ThemeLike, statuses: Record<string, TeamStatusView>, indent = ""): string[] {
150
+ const names = Object.keys(statuses);
151
+ const nameWidth = Math.max(...names.map((name) => name.length));
152
+ const wordWidth = Math.max(...names.map((name) => statuses[name]!.word.length));
153
+ return names.map((name, index) => {
154
+ const entry = statuses[name]!;
155
+ const branch = index === names.length - 1 ? "└" : "├";
156
+ const tail = statLine(theme, [entry.phrase, theme.fg("dim", entry.updated)]);
157
+ return `${indent}${treeConnector(theme, branch)}${theme.fg("accent", padVisible(name, nameWidth))} ${theme.fg(statusWordToken(entry.word), padVisible(entry.word, wordWidth))} ${tail}`;
158
+ });
159
+ }
160
+
161
+ export function teamStatusLines(theme: ThemeLike, team: string, statuses: Record<string, TeamStatusView>): string[] {
162
+ const members = Object.values(statuses);
163
+ const workingCount = members.filter((member) => statusWordToken(member.word) === "success").length;
164
+ const stats = [theme.fg("muted", plural(members.length, "member"))];
165
+ if (workingCount > 0) stats.push(theme.fg("success", `${workingCount} working`));
166
+ return [headerLine(theme, "Team Status", theme.fg("accent", team), stats), ...memberRows(theme, statuses)];
167
+ }
168
+
169
+ export function allTeamsStatusLines(theme: ThemeLike, teams: Record<string, Record<string, TeamStatusView>>): string[] {
170
+ const teamNames = Object.keys(teams);
171
+ const lines = [headerLine(theme, "Team Status", theme.fg("muted", plural(teamNames.length, "team")))];
172
+ teamNames.forEach((teamName, index) => {
173
+ const branch = index === teamNames.length - 1 ? "└" : "├";
174
+ lines.push(`${treeConnector(theme, branch)}${theme.fg("accent", teamName)}`);
175
+ lines.push(...memberRows(theme, teams[teamName]!, treeStem(theme, branch)));
176
+ });
177
+ return lines;
178
+ }
179
+
180
+ interface TeammateSpecView {
181
+ name: string;
182
+ model: string;
183
+ thinking?: string;
184
+ }
185
+
186
+ export function teamSpawnLines(theme: ThemeLike, team: string, teammates: TeammateSpecView[]): string[] {
187
+ const header = headerLine(theme, "Team Spawn", theme.fg("accent", team), [theme.fg("muted", plural(teammates.length, "teammate"))]);
188
+ const nameWidth = Math.max(...teammates.map((teammate) => teammate.name.length));
189
+ const rows = teammates.map((teammate, index) => {
190
+ const branch = index === teammates.length - 1 ? "└" : "├";
191
+ const spec = statLine(theme, [theme.fg("muted", teammate.model), theme.fg("dim", teammate.thinking ?? "")]);
192
+ return `${treeConnector(theme, branch)}${theme.fg("accent", padVisible(teammate.name, nameWidth))} ${spec}`;
193
+ });
194
+ return [header, ...rows];
195
+ }
196
+
197
+ function quotedBody(theme: ThemeLike, message: string, options: { lineLimit: number; barToken: string }): TeamLine[] {
198
+ const g = glyphs();
199
+ const bar = ` ${theme.fg(options.barToken, g.codeBar)} `;
200
+ const lines = message.replace(/\r\n/g, "\n").split("\n");
201
+ const shown = lines.slice(0, options.lineLimit);
202
+ const body: TeamLine[] = shown.map((line) => ({ prefix: bar, text: line }));
203
+ const hidden = lines.length - shown.length;
204
+ 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`) });
205
+ return body;
206
+ }
207
+
208
+ const SEND_PREVIEW_LINES = 3;
209
+
210
+ function sendTarget(theme: ThemeLike, to: string[]): string {
211
+ return `${theme.fg("muted", `${glyphs().arrow} `)}${theme.fg("accent", to.join(", "))}`;
212
+ }
213
+
214
+ function sendStats(theme: ThemeLike, message: string, interrupt: boolean): string[] {
215
+ return [interrupt ? theme.fg("warning", "interrupt") : "", theme.fg("muted", formatCharCount(message.length))];
216
+ }
217
+
218
+ export function teamSendLines(theme: ThemeLike, options: { to: string[]; message: string; interrupt: boolean; expanded: boolean }): TeamLine[] {
219
+ const header = headerLine(theme, "Team Send", sendTarget(theme, options.to), sendStats(theme, options.message, options.interrupt));
220
+ const lineLimit = options.expanded ? Number.POSITIVE_INFINITY : SEND_PREVIEW_LINES;
221
+ return [header, ...quotedBody(theme, options.message, { lineLimit, barToken: "muted" })];
222
+ }
223
+
224
+ export function teamShutdownLines(theme: ThemeLike, team: string, teammates: string[]): string[] {
225
+ const header = headerLine(theme, "Team Shutdown", theme.fg("accent", team), [theme.fg("muted", `${plural(teammates.length, "teammate")} stopped`)]);
226
+ if (teammates.length === 0) return [header];
227
+ return [header, `${treeConnector(theme, "└")}${theme.fg("muted", teammates.join(glyphs().dot))}`];
228
+ }
229
+
230
+ type KindMarkName = "arrow" | "bullet" | "diamond" | "emptyBullet" | "fail" | "ok" | "warn";
231
+
232
+ const KIND_MARK_SPECS: Record<TeamLogKind, { mark: KindMarkName; token: string }> = {
233
+ spawn: { mark: "diamond", token: "accent" },
234
+ send: { mark: "arrow", token: "accent" },
235
+ deliver: { mark: "arrow", token: "muted" },
236
+ ack: { mark: "ok", token: "dim" },
237
+ status: { mark: "emptyBullet", token: "muted" },
238
+ agent_start: { mark: "bullet", token: "success" },
239
+ agent_end: { mark: "emptyBullet", token: "muted" },
240
+ tool_start: { mark: "emptyBullet", token: "dim" },
241
+ tool_end: { mark: "ok", token: "muted" },
242
+ main_message: { mark: "arrow", token: "success" },
243
+ stderr: { mark: "warn", token: "warning" },
244
+ exit: { mark: "warn", token: "warning" },
245
+ error: { mark: "fail", token: "error" },
246
+ };
247
+
248
+ export function kindMark(entry: Pick<TeamLogEntry, "kind" | "details">): { glyph: string; token: string } {
249
+ const failedToolEnd = entry.kind === "tool_end" && Boolean(entry.details?.isError);
250
+ const spec = failedToolEnd ? { mark: "fail" as const, token: "error" } : KIND_MARK_SPECS[entry.kind];
251
+ const g = glyphs();
252
+ const marks: Record<KindMarkName, string> = {
253
+ arrow: g.arrow,
254
+ bullet: g.bullet.trim(),
255
+ diamond: g.diamond,
256
+ emptyBullet: g.emptyBullet.trim(),
257
+ fail: g.fail,
258
+ ok: g.ok,
259
+ warn: g.warn,
260
+ };
261
+ return { glyph: marks[spec.mark], token: spec.token };
262
+ }
263
+
264
+ function inlineText(value: unknown): string {
265
+ const text = typeof value === "string" ? value : (JSON.stringify(value) ?? String(value));
266
+ return text.replace(/\s+/g, " ").trim();
267
+ }
268
+
269
+ function toolResultText(result: unknown): string {
270
+ const content = (result as { content?: Array<{ type?: string; text?: string }> } | undefined)?.content;
271
+ const textPart = content?.find((part) => part?.type === "text" && typeof part.text === "string");
272
+ return inlineText(textPart?.text ?? result);
273
+ }
274
+
275
+ function entrySummary(theme: ThemeLike, entry: TeamLogEntry): string {
276
+ const details = entry.details ?? {};
277
+ if (entry.kind === "tool_start") return `${String(details.toolName ?? "tool")} ${theme.fg("dim", inlineText(details.args))}`;
278
+ if (entry.kind === "tool_end") {
279
+ const token = details.isError ? "error" : "dim";
280
+ return `${String(details.toolName ?? "tool")} ${theme.fg(token, toolResultText(details.result))}`;
281
+ }
282
+ if ((entry.kind === "send" || entry.kind === "deliver") && typeof details.from === "string") {
283
+ return `${theme.fg("dim", `${details.from} ${glyphs().arrow} `)}${entry.summary}`;
284
+ }
285
+ if (entry.kind === "error") return theme.fg("error", entry.summary);
286
+ if (entry.kind === "stderr") return theme.fg("warning", entry.summary);
287
+ return entry.summary;
288
+ }
289
+
290
+ export function teamLogLines(theme: ThemeLike, view: TeamLogRenderView): string[] {
291
+ const g = glyphs();
292
+ const stats = [theme.fg("muted", `${view.returned} of ${view.totalMatched} events`)];
293
+ for (const [key, value] of Object.entries(view.filters ?? {})) {
294
+ if (typeof value === "string" && value) stats.push(theme.fg("dim", `${key}=${value}`));
295
+ }
296
+ const header = headerLine(theme, "Team Log", theme.fg("accent", view.team), stats);
297
+ if (view.entries.length === 0) return [header, `${treeConnector(theme, "└")}${theme.fg("muted", "no matching events")}`];
298
+
299
+ const seqWidth = Math.max(...view.entries.map((entry) => String(entry.sequence).length)) + 1;
300
+ const nameWidth = Math.max(...view.entries.map((entry) => (entry.teammate ?? "main").length));
301
+ const kindWidth = Math.max(...view.entries.map((entry) => entry.kind.length));
302
+ const footer = view.nextCursor
303
+ ? `${treeConnector(theme, "└")}${theme.fg("muted", `${g.ellipsis} older events${g.dot}cursor "${view.nextCursor}"`)}`
304
+ : undefined;
305
+ const rows = view.entries.map((entry, index) => {
306
+ const branch = index === view.entries.length - 1 && !footer ? "└" : "├";
307
+ const mark = kindMark(entry);
308
+ return [
309
+ treeConnector(theme, branch),
310
+ theme.fg("dim", padVisible(`#${entry.sequence}`, seqWidth)),
311
+ ` ${theme.fg("dim", timeOfDay(entry.epochMilliseconds))}`,
312
+ ` ${theme.fg("accent", padVisible(entry.teammate ?? "main", nameWidth))}`,
313
+ ` ${theme.fg(mark.token, padVisible(mark.glyph, 2))}`,
314
+ theme.fg("muted", padVisible(entry.kind, kindWidth)),
315
+ ` ${entrySummary(theme, entry)}`,
316
+ ].join("");
317
+ });
318
+ return [header, ...rows, ...(footer ? [footer] : [])];
319
+ }
320
+
321
+ export function teamMessageLines(theme: ThemeLike, details: TeamMessageDetails): TeamLine[] {
322
+ const g = glyphs();
323
+ const header = [
324
+ theme.fg("accent", `${g.diamond} `),
325
+ theme.fg("accent", theme.bold(details.from)),
326
+ theme.fg("muted", ` ${g.arrow} main`),
327
+ theme.fg("dim", `${g.dot}${details.team}${g.dot}${details.sentAt}`),
328
+ ].join("");
329
+ return [header, ...quotedBody(theme, details.message, { lineLimit: Number.POSITIVE_INFINITY, barToken: "accent" })];
330
+ }
331
+
332
+ function teamMessageHeader(theme: ThemeLike, details: TeamMessageDetails): string {
333
+ const g = glyphs();
334
+ return [
335
+ theme.fg("accent", `${g.diamond} `),
336
+ theme.fg("accent", theme.bold(details.from)),
337
+ theme.fg("muted", ` ${g.arrow} main`),
338
+ theme.fg("dim", `${g.dot}${details.team}${g.dot}${details.sentAt}`),
339
+ ].join("");
340
+ }
341
+
342
+ class TeamSendView {
343
+ private md: Markdown;
344
+ private headerStr: string;
345
+ private barStr: string;
346
+ private barWidth: number;
347
+ private expanded: boolean;
348
+ private theme: ThemeLike;
349
+
350
+ constructor(headerStr: string, messageText: string, barStr: string, mdTheme: MarkdownTheme, expanded: boolean, theme: ThemeLike) {
351
+ this.headerStr = headerStr;
352
+ this.barStr = barStr;
353
+ this.barWidth = visibleLength(barStr);
354
+ this.md = new Markdown(messageText, 0, 0, mdTheme);
355
+ this.expanded = expanded;
356
+ this.theme = theme;
357
+ }
358
+
359
+ invalidate(): void {
360
+ this.md.invalidate();
361
+ }
362
+
363
+ render(width: number): string[] {
364
+ const bodyWidth = Math.max(10, width - this.barWidth);
365
+ const bodyLines = this.md.render(bodyWidth);
366
+ const barred = bodyLines.map((line) => `${this.barStr}${line}`);
367
+ if (this.expanded) return [this.headerStr, ...barred];
368
+ const shown = barred.slice(0, SEND_PREVIEW_LINES);
369
+ const hidden = barred.length - SEND_PREVIEW_LINES;
370
+ if (hidden > 0) {
371
+ const g = glyphs();
372
+ shown.push(`${this.barStr}${this.theme.fg("dim", `${g.ellipsis} ${hidden} more line${hidden === 1 ? "" : "s"}${g.dot}ctrl+o to expand`)}`);
373
+ }
374
+ return [this.headerStr, ...shown];
375
+ }
376
+ }
377
+
378
+ class TeamMessageView {
379
+ private md: Markdown;
380
+ private headerLine: string;
381
+ private barStr: string;
382
+ private barWidth: number;
383
+
384
+ constructor(headerLine: string, messageText: string, barStr: string, mdTheme: MarkdownTheme) {
385
+ this.headerLine = headerLine;
386
+ this.barStr = barStr;
387
+ this.barWidth = visibleLength(barStr);
388
+ this.md = new Markdown(messageText, 0, 0, mdTheme);
389
+ }
390
+
391
+ invalidate(): void {
392
+ this.md.invalidate();
393
+ }
394
+
395
+ render(width: number): string[] {
396
+ const bodyWidth = Math.max(10, width - this.barWidth);
397
+ const bodyLines = this.md.render(bodyWidth);
398
+ return [this.headerLine, ...bodyLines.map((line) => `${this.barStr}${line}`)];
399
+ }
400
+ }
401
+
402
+ function accentTeam(theme: ThemeLike, team: unknown): string {
403
+ return typeof team === "string" && team ? theme.fg("accent", team) : "";
404
+ }
405
+
406
+ function callBodyFor(tool: TeamToolName, theme: ThemeLike, args: Record<string, unknown>): string {
407
+ if (tool === "team_spawn") {
408
+ const teammates = (args.teammates ?? []) as unknown[];
409
+ return callBody(theme, "Team Spawn", accentTeam(theme, args.team), [theme.fg("muted", plural(teammates.length, "teammate"))]);
410
+ }
411
+ if (tool === "teamsend") {
412
+ const message = String(args.message ?? "");
413
+ return callBody(theme, "Team Send", sendTarget(theme, (args.to ?? []) as string[]), sendStats(theme, message, Boolean(args.interrupt)));
414
+ }
415
+ if (tool === "teamstatus") {
416
+ const target = accentTeam(theme, args.team) || theme.fg("muted", "all teams");
417
+ const setting = inlineText(`${String(args.word ?? "")} ${String(args.phrase ?? "")}`);
418
+ return callBody(theme, "Team Status", target, setting ? [theme.fg("dim", `set ${setting}`)] : []);
419
+ }
420
+ if (tool === "teamlog") {
421
+ const filterStats = ["teammate", "kind", "search", "since", "cursor"]
422
+ .filter((key) => typeof args[key] === "string" && args[key])
423
+ .map((key) => theme.fg("dim", `${key}=${String(args[key])}`));
424
+ return callBody(theme, "Team Log", accentTeam(theme, args.team), filterStats);
425
+ }
426
+ return callBody(theme, "Team Shutdown", accentTeam(theme, args.team));
427
+ }
428
+
429
+ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<string, unknown>, details: Record<string, unknown>, expanded: boolean): TeamLine[] {
430
+ if (tool === "team_spawn") {
431
+ return teamSpawnLines(theme, String(details.team), (args.teammates ?? []) as TeammateSpecView[]);
432
+ }
433
+ if (tool === "teamsend") {
434
+ return teamSendLines(theme, {
435
+ to: (details.to ?? []) as string[],
436
+ message: String(args.message ?? ""),
437
+ interrupt: Boolean(details.interrupt),
438
+ expanded,
439
+ });
440
+ }
441
+ if (tool === "teamstatus") {
442
+ if (details.teams) return allTeamsStatusLines(theme, details.teams as Record<string, Record<string, TeamStatusView>>);
443
+ return teamStatusLines(theme, String(details.team), details.status as Record<string, TeamStatusView>);
444
+ }
445
+ if (tool === "teamlog") {
446
+ const filters = (details.filters ?? {}) as Record<string, unknown>;
447
+ return teamLogLines(theme, {
448
+ team: String(details.team),
449
+ entries: (details.entries ?? []) as TeamLogEntry[],
450
+ totalMatched: Number(details.totalMatched ?? 0),
451
+ returned: Number(details.returned ?? 0),
452
+ nextCursor: details.nextCursor as string | undefined,
453
+ filters: { teammate: filters.teammate, kind: filters.kind, search: filters.search, since: filters.since },
454
+ });
455
+ }
456
+ return teamShutdownLines(theme, String(details.team), (details.teammates ?? []) as string[]);
457
+ }
458
+
459
+ export function renderTeamToolCall(tool: TeamToolName, args: Record<string, unknown>, theme: ThemeLike, context: ToolRenderContextLike) {
460
+ return renderPendingCall(callBodyFor(tool, theme, args ?? {}), theme, context, context?.cwd);
461
+ }
462
+
463
+ export function renderTeamToolResult(
464
+ tool: TeamToolName,
465
+ result: { isError?: boolean; details?: unknown },
466
+ options: { expanded: boolean },
467
+ theme: ThemeLike,
468
+ context: ToolRenderContextLike,
469
+ markdownTheme?: MarkdownTheme,
470
+ ): TeamSendView | TeamLines {
471
+ const args = context?.args ?? {};
472
+ if (context?.isError || result?.isError) {
473
+ return new TeamLines(errorLines(theme, callBodyFor(tool, theme, args), textContent(result)), options.expanded ? "wrap" : "clip");
474
+ }
475
+ const details = (result?.details ?? {}) as Record<string, unknown>;
476
+ if (markdownTheme && tool === "teamsend") {
477
+ const message = String(args.message ?? "");
478
+ const header = headerLine(theme, "Team Send", sendTarget(theme, (details.to ?? []) as string[]), sendStats(theme, message, Boolean(details.interrupt)));
479
+ const bar = ` ${theme.fg("muted", glyphs().codeBar)} `;
480
+ return new TeamSendView(header, message, bar, markdownTheme, options.expanded, theme);
481
+ }
482
+ return new TeamLines(resultLinesFor(tool, theme, args, details, options.expanded), options.expanded ? "wrap" : "clip");
483
+ }
484
+
485
+ export function renderTeamMessage(message: { details?: unknown }, theme: ThemeLike, markdownTheme?: MarkdownTheme): TeamMessageView | TeamLines | undefined {
486
+ const details = message.details as TeamMessageDetails | undefined;
487
+ if (!details?.from || !details?.team || typeof details.message !== "string") return undefined;
488
+ if (markdownTheme) {
489
+ const g = glyphs();
490
+ const bar = ` ${theme.fg("accent", g.codeBar)} `;
491
+ return new TeamMessageView(teamMessageHeader(theme, details), details.message, bar, markdownTheme);
492
+ }
493
+ return new TeamLines(teamMessageLines(theme, details), "wrap");
494
+ }
@@ -0,0 +1,15 @@
1
+ export function composeSystemPrompt(teamName: string, teamPrompt: string, teammateName: string, teammatePrompt: string, participants: string[]): string {
2
+ return [
3
+ teamPrompt.trim(),
4
+ teammatePrompt.trim(),
5
+ `You are ${teammateName}, a teammate on team ${teamName}.`,
6
+ `Participants: main, ${participants.join(", ")}.`,
7
+ "Use teamsend to talk to teammates, teammain to talk to the main agent, and teamstatus to set/read public statuses.",
8
+ "As soon as you wake up, call teamstatus to acknowledge that you received your instructions before doing substantive work.",
9
+ "Whenever you receive a message from main or a teammate, call teamstatus first to acknowledge that specific message, then proceed.",
10
+ "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.",
11
+ "There is no inbox to poll and no done button. Coordinate naturally. If the team is done, one teammate should tell main via teammain.",
12
+ ]
13
+ .filter(Boolean)
14
+ .join("\n\n");
15
+ }