@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/teamlog.ts ADDED
@@ -0,0 +1,245 @@
1
+ export type TeamLogKind =
2
+ | "spawn"
3
+ | "send"
4
+ | "deliver"
5
+ | "ack"
6
+ | "status"
7
+ | "agent_start"
8
+ | "agent_end"
9
+ | "tool_start"
10
+ | "tool_end"
11
+ | "main_message"
12
+ | "stderr"
13
+ | "exit"
14
+ | "error";
15
+
16
+ export type TeamLogDirection = "main->teammate" | "teammate->main" | "teammate->teammate" | "runtime";
17
+
18
+ export interface TeamLogEntry {
19
+ sequence: number;
20
+ timestamp: string;
21
+ epochMilliseconds: number;
22
+ team: string;
23
+ teammate?: string;
24
+ direction?: TeamLogDirection;
25
+ kind: TeamLogKind;
26
+ summary: string;
27
+ details?: Record<string, unknown>;
28
+ }
29
+
30
+ export interface TeamLogState {
31
+ log: TeamLogEntry[];
32
+ nextLogSequence: number;
33
+ }
34
+
35
+ export type TeamLogEntryInput = Omit<TeamLogEntry, "sequence" | "timestamp" | "epochMilliseconds">;
36
+
37
+ export interface TeamLogFilterParams {
38
+ teammate?: string;
39
+ kind?: string;
40
+ search?: string;
41
+ since?: string;
42
+ }
43
+
44
+ export interface TeamLogPageParams {
45
+ limit?: number;
46
+ cursor?: string;
47
+ }
48
+
49
+ export interface TeamLogPage {
50
+ entries: TeamLogEntry[];
51
+ totalMatched: number;
52
+ returned: number;
53
+ nextCursor?: string;
54
+ limit: number;
55
+ }
56
+
57
+ export interface TeamLogPageView extends TeamLogPage {
58
+ team: string;
59
+ }
60
+
61
+ const MAX_LOG_ENTRIES = 1000;
62
+ const DEFAULT_PREVIEW_LENGTH = 160;
63
+ const DEFAULT_LIMIT = 20;
64
+ const MAX_LIMIT = 100;
65
+
66
+ const dateFormatter = new Intl.DateTimeFormat("en-US", { month: "long", day: "2-digit" });
67
+ const timeFormatter = new Intl.DateTimeFormat("en-GB", { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
68
+
69
+ export function nowText(date: Date = new Date()): string {
70
+ return `${dateFormatter.format(date)}, ${timeFormatter.format(date)}`;
71
+ }
72
+
73
+ export function timeOfDay(epochMilliseconds: number): string {
74
+ return timeFormatter.format(new Date(epochMilliseconds));
75
+ }
76
+
77
+ function safeStringify(value: unknown): string {
78
+ try {
79
+ return JSON.stringify(value) ?? String(value);
80
+ } catch {
81
+ return String(value);
82
+ }
83
+ }
84
+
85
+ export function preview(value: unknown, maxLength = DEFAULT_PREVIEW_LENGTH): string {
86
+ const text = typeof value === "string" ? value : safeStringify(value);
87
+ const normalized = text.replace(/\s+/g, " ").trim();
88
+ if (normalized.length <= maxLength) return normalized;
89
+ return `${normalized.slice(0, maxLength)} (truncated, ${normalized.length} chars)`;
90
+ }
91
+
92
+ export function appendTeamLog(state: TeamLogState, input: TeamLogEntryInput, now: Date = new Date()): TeamLogEntry {
93
+ const entry: TeamLogEntry = {
94
+ ...input,
95
+ sequence: state.nextLogSequence++,
96
+ timestamp: nowText(now),
97
+ epochMilliseconds: now.getTime(),
98
+ };
99
+ state.log.push(entry);
100
+ if (state.log.length > MAX_LOG_ENTRIES) state.log.shift();
101
+ return entry;
102
+ }
103
+
104
+ function parseSince(since: string | undefined): number | undefined {
105
+ if (since === undefined) return undefined;
106
+ const threshold = Date.parse(since);
107
+ if (Number.isNaN(threshold)) throw new Error(`Invalid since timestamp: ${since}`);
108
+ return threshold;
109
+ }
110
+
111
+ function matchesSearch(entry: TeamLogEntry, search: string): boolean {
112
+ const needle = search.toLowerCase();
113
+ const haystacks = [entry.summary, entry.teammate ?? "", entry.direction ?? "", entry.kind, entry.details ? safeStringify(entry.details) : ""];
114
+ return haystacks.some((haystack) => haystack.toLowerCase().includes(needle));
115
+ }
116
+
117
+ export function filterTeamLog(entries: TeamLogEntry[], params: TeamLogFilterParams): TeamLogEntry[] {
118
+ const sinceThreshold = parseSince(params.since);
119
+ return entries.filter((entry) => {
120
+ if (params.teammate !== undefined && entry.teammate !== params.teammate) return false;
121
+ if (params.kind !== undefined && entry.kind !== params.kind) return false;
122
+ if (sinceThreshold !== undefined && entry.epochMilliseconds < sinceThreshold) return false;
123
+ if (params.search !== undefined && !matchesSearch(entry, params.search)) return false;
124
+ return true;
125
+ });
126
+ }
127
+
128
+ function resolveLimit(limit: number | undefined): number {
129
+ if (limit === undefined) return DEFAULT_LIMIT;
130
+ if (!Number.isFinite(limit) || limit < 1) throw new Error(`Invalid limit: ${limit}. Must be at least 1.`);
131
+ return Math.min(Math.floor(limit), MAX_LIMIT);
132
+ }
133
+
134
+ function parseCursor(cursor: string | undefined): number | undefined {
135
+ if (cursor === undefined) return undefined;
136
+ const match = /^before:(\d+)$/.exec(cursor);
137
+ if (!match) throw new Error(`Invalid cursor: ${cursor}`);
138
+ return Number(match[1]);
139
+ }
140
+
141
+ export function pageTeamLog(filteredEntries: TeamLogEntry[], params: TeamLogPageParams): TeamLogPage {
142
+ const limit = resolveLimit(params.limit);
143
+ const beforeSequence = parseCursor(params.cursor);
144
+ const totalMatched = filteredEntries.length;
145
+
146
+ const eligible = beforeSequence === undefined ? filteredEntries : filteredEntries.filter((entry) => entry.sequence < beforeSequence);
147
+
148
+ const pageEntries = eligible.slice(Math.max(0, eligible.length - limit));
149
+ const hasOlder = eligible.length > pageEntries.length;
150
+ const oldestInPage = pageEntries[0];
151
+
152
+ return {
153
+ entries: pageEntries,
154
+ totalMatched,
155
+ returned: pageEntries.length,
156
+ nextCursor: hasOlder && oldestInPage ? `before:${oldestInPage.sequence}` : undefined,
157
+ limit,
158
+ };
159
+ }
160
+
161
+ const COLUMN_WIDTHS = { sequence: 3, time: 8, teammate: 10, kind: 12, direction: 19 } as const;
162
+
163
+ function column(text: string, width: number): string {
164
+ return text.padEnd(width);
165
+ }
166
+
167
+ function renderRow(entry: TeamLogEntry): string {
168
+ return [
169
+ column(String(entry.sequence).padStart(COLUMN_WIDTHS.sequence, "0"), COLUMN_WIDTHS.sequence),
170
+ column(timeOfDay(entry.epochMilliseconds), COLUMN_WIDTHS.time),
171
+ column(entry.teammate ?? "main", COLUMN_WIDTHS.teammate),
172
+ column(entry.kind, COLUMN_WIDTHS.kind),
173
+ column(entry.direction ?? "", COLUMN_WIDTHS.direction),
174
+ entry.summary,
175
+ ].join(" ");
176
+ }
177
+
178
+ export function renderTeamLogPage(view: TeamLogPageView): string {
179
+ const header = `Team ${view.team} — latest ${view.returned} of ${view.totalMatched} matching events`;
180
+ const columnHeader = [
181
+ column("seq", COLUMN_WIDTHS.sequence),
182
+ column("time", COLUMN_WIDTHS.time),
183
+ column("teammate", COLUMN_WIDTHS.teammate),
184
+ column("kind", COLUMN_WIDTHS.kind),
185
+ column("dir", COLUMN_WIDTHS.direction),
186
+ "summary",
187
+ ].join(" ");
188
+ const rows = view.entries.map(renderRow);
189
+ const cursorSuffix = view.nextCursor ? ` nextCursor="${view.nextCursor}"` : "";
190
+ const footer = `Showing ${view.returned} of ${view.totalMatched} matching events.${cursorSuffix}`;
191
+ return [header, columnHeader, ...rows, footer].join("\n");
192
+ }
193
+
194
+ export function normalizeChildEvent(team: string, teammate: string, event: Record<string, unknown>): TeamLogEntryInput | undefined {
195
+ const type = event.type;
196
+
197
+ if (type === "agent_start") {
198
+ return { team, teammate, direction: "runtime", kind: "agent_start", summary: `${teammate} started` };
199
+ }
200
+
201
+ if (type === "agent_end") {
202
+ const messages = event.messages;
203
+ const messageCount = Array.isArray(messages) ? messages.length : undefined;
204
+ const summary = messageCount === undefined ? `${teammate} finished` : `${teammate} finished (${messageCount} message${messageCount === 1 ? "" : "s"})`;
205
+ return { team, teammate, direction: "runtime", kind: "agent_end", summary };
206
+ }
207
+
208
+ if (type === "tool_execution_start") {
209
+ const toolName = String(event.toolName ?? "tool");
210
+ return {
211
+ team,
212
+ teammate,
213
+ direction: "runtime",
214
+ kind: "tool_start",
215
+ summary: `${teammate} started ${toolName}: ${preview(event.args)}`,
216
+ details: { toolCallId: event.toolCallId, toolName, args: event.args },
217
+ };
218
+ }
219
+
220
+ if (type === "tool_execution_end") {
221
+ const toolName = String(event.toolName ?? "tool");
222
+ const isError = Boolean(event.isError);
223
+ return {
224
+ team,
225
+ teammate,
226
+ direction: "runtime",
227
+ kind: "tool_end",
228
+ summary: `${teammate} ${isError ? "failed" : "finished"} ${toolName}: ${preview(event.result)}`,
229
+ details: { toolCallId: event.toolCallId, toolName, isError, result: event.result },
230
+ };
231
+ }
232
+
233
+ if (type === "extension_error") {
234
+ return {
235
+ team,
236
+ teammate,
237
+ direction: "runtime",
238
+ kind: "error",
239
+ summary: `${teammate} extension error: ${preview(event.error)}`,
240
+ details: { extensionPath: event.extensionPath, event: event.event, error: event.error },
241
+ };
242
+ }
243
+
244
+ return undefined;
245
+ }