@giladbarnea/pi-simple-team 1.0.45 → 2.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.
@@ -28,5 +28,5 @@ export function validateTeammateModels(teammates: readonly TeammateModelSpec[],
28
28
  .map((teammate) => `Model ${JSON.stringify(teammate.model)} for teammate ${JSON.stringify(teammate.name)} is not available.`);
29
29
 
30
30
  if (errors.length === 0) return;
31
- throw new Error(`Model preflight failed:\n${errors.map((error) => `- ${error}`).join("\n")}`);
31
+ throw new Error(`Model preflight failed:\n${errors.map((error) => `- ${error}`).join("\n")}\nAvailable model IDs: ${JSON.stringify([...availableModelReferences])}. Choose an available ID for each teammate's model field and retry.`);
32
32
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "1.0.45",
3
+ "version": "2.0.0",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",
package/render.ts CHANGED
@@ -21,7 +21,7 @@ interface ToolRenderContextLike {
21
21
  toolCallId?: string;
22
22
  }
23
23
 
24
- export type TeamToolName = "team_spawn" | "team_list" | "team_resume" | "team_add" | "teamsend" | "teamstatus" | "teamlog" | "team_shutdown";
24
+ export type TeamToolName = "team_spawn" | "team_list" | "team_resume" | "team_add_teammates" | "team_send_message" | "team_status" | "team_log" | "team_shutdown";
25
25
 
26
26
  export interface TeamStatusView {
27
27
  word: string;
@@ -48,11 +48,9 @@ interface TeamLogRenderView {
48
48
  nowMilliseconds?: number;
49
49
  }
50
50
 
51
- /** Sessions persisted before the ISO switch carry pre-formatted timestamps; those pass through raw. */
51
+ /** @example relativeTimeText(new Date().toISOString()) // "just now" */
52
52
  export function relativeTimeText(timestamp: string): string {
53
- if (!timestamp.includes("T")) return timestamp;
54
- const parsed = Date.parse(timestamp);
55
- return Number.isFinite(parsed) ? relativeTime(parsed, Date.now()) : timestamp;
53
+ return relativeTime(Date.parse(timestamp), Date.now());
56
54
  }
57
55
 
58
56
  /** A rendered line with optional wrapping or right-aligned layout metadata. */
@@ -203,13 +201,12 @@ export function teamStatusLines(theme: ThemeLike, team: string, statuses: Record
203
201
  return [headerLine(theme, "Team Status", theme.fg("accent", team), stats), ...memberRows(theme, statuses, roster)];
204
202
  }
205
203
 
206
- export function allTeamsStatusLines(theme: ThemeLike, teams: Record<string, Record<string, TeamStatusView>>, roster: string[] = []): TeamLine[] {
207
- const teamNames = Object.keys(teams);
208
- const lines: TeamLine[] = [headerLine(theme, "Team Status", theme.fg("muted", plural(teamNames.length, "team")))];
209
- teamNames.forEach((teamName, index) => {
210
- const branch = index === teamNames.length - 1 ? "└" : "├";
211
- lines.push(`${treeConnector(theme, branch)}${theme.fg("accent", teamName)}`);
212
- lines.push(...memberRows(theme, teams[teamName]!, roster, treeStem(theme, branch)));
204
+ export function allTeamsStatusLines(theme: ThemeLike, teams: Array<{ teamName: string; status: Record<string, TeamStatusView> }>, roster: string[] = []): TeamLine[] {
205
+ const lines: TeamLine[] = [headerLine(theme, "Team Status", theme.fg("muted", plural(teams.length, "team")))];
206
+ teams.forEach((team, index) => {
207
+ const branch = index === teams.length - 1 ? "└" : "├";
208
+ lines.push(`${treeConnector(theme, branch)}${theme.fg("accent", team.teamName)}`);
209
+ lines.push(...memberRows(theme, team.status, roster, treeStem(theme, branch)));
213
210
  });
214
211
  return lines;
215
212
  }
@@ -244,19 +241,23 @@ export function teamAddLines(theme: ThemeLike, team: string, teammates: Teammate
244
241
 
245
242
  export interface ResumedMemberView {
246
243
  name: string;
247
- restored: boolean;
244
+ restored?: boolean;
245
+ live: boolean;
246
+ active: boolean;
248
247
  }
249
248
 
250
249
  export function teamResumeLines(theme: ThemeLike, team: string, resumed: ResumedMemberView[], teammateCount: number, roster: string[] = []): string[] {
251
- const countText = resumed.length === teammateCount ? `${resumed.length} resumed` : `${resumed.length} of ${teammateCount} resumed`;
250
+ const resumedCount = resumed.filter((member) => member.restored !== undefined).length;
251
+ const countText = resumedCount === teammateCount ? `${resumedCount} resumed` : `${resumedCount} of ${teammateCount} resumed`;
252
252
  const header = headerLine(theme, "Team Resume", theme.fg("accent", team), [theme.fg("muted", countText)]);
253
253
  if (resumed.length === 0) return [header, `${treeConnector(theme, "└")}${theme.fg("muted", "no stopped teammates")}`];
254
254
  const nameWidth = Math.max(...resumed.map((member) => member.name.length));
255
- const wordWidth = Math.max(...resumed.map((member) => (member.restored ? "resumed" : "restarted").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));
256
257
  const rows = resumed.map((member, index) => {
257
258
  const branch = index === resumed.length - 1 ? "└" : "├";
258
- const word = member.restored ? "resumed" : "restarted";
259
- const note = member.restored ? "history restored" : "empty session";
259
+ const word = words[index];
260
+ const note = member.restored === undefined ? "" : `${member.restored ? "history restored" : "empty session"}, ${member.active ? "working" : "idle"}`;
260
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)}`;
261
262
  });
262
263
  return [header, ...rows];
@@ -265,7 +266,7 @@ export function teamResumeLines(theme: ThemeLike, team: string, resumed: Resumed
265
266
  export interface TeamListMemberView {
266
267
  name: string;
267
268
  live: boolean;
268
- canOverseeOwnTeams: boolean;
269
+ canManageOwnTeams: boolean;
269
270
  }
270
271
 
271
272
  export interface TeamListTeamView {
@@ -280,7 +281,7 @@ export interface TeamListTeamView {
280
281
  function teamListMemberName(theme: ThemeLike, teamView: TeamListTeamView, member: TeamListMemberView, roster: string[]): string {
281
282
  let name = theme.fg(actorHueToken(member.name, roster), member.name);
282
283
  if (teamView.state === "active" && !member.live) name = `${DIM_SGR_OPEN}${name}${DIM_SGR_CLOSE}`;
283
- if (member.canOverseeOwnTeams) name += theme.fg("dim", glyphs().diamond);
284
+ if (member.canManageOwnTeams) name += theme.fg("dim", glyphs().diamond);
284
285
  return name;
285
286
  }
286
287
 
@@ -333,8 +334,13 @@ function sendStats(theme: ThemeLike, message: string, interrupt: boolean): strin
333
334
  return [interrupt ? theme.fg("warning", "interrupt") : "", theme.fg("muted", formatCharCount(message.length))];
334
335
  }
335
336
 
336
- export function teamSendLines(theme: ThemeLike, options: { to: string[]; message: string; interrupt: boolean; expanded: boolean }, roster: string[] = []): TeamLine[] {
337
- const header = headerLine(theme, "Team Send", sendTarget(theme, options.to, roster), sendStats(theme, options.message, options.interrupt));
337
+ /** @example hasInterruption([]) // false */
338
+ function hasInterruption(interrupt: unknown): boolean {
339
+ return interrupt === true || (Array.isArray(interrupt) && interrupt.length > 0);
340
+ }
341
+
342
+ 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));
338
344
  const lineLimit = options.expanded ? Number.POSITIVE_INFINITY : SEND_PREVIEW_LINES;
339
345
  return [header, ...quotedBody(theme, options.message, { lineLimit, barToken: "muted" })];
340
346
  }
@@ -756,7 +762,7 @@ function accentTeam(theme: ThemeLike, team: unknown): string {
756
762
  function callBodyFor(tool: TeamToolName, theme: ThemeLike, args: Record<string, unknown>, roster: string[]): string {
757
763
  if (tool === "team_spawn") {
758
764
  const teammates = (args.teammates ?? []) as unknown[];
759
- return callBody(theme, "Team Spawn", accentTeam(theme, args.team), [theme.fg("muted", plural(teammates.length, "teammate"))]);
765
+ return callBody(theme, "Team Spawn", accentTeam(theme, args.teamName), [theme.fg("muted", plural(teammates.length, "teammate"))]);
760
766
  }
761
767
  if (tool === "team_list") {
762
768
  return callBody(theme, "Team List", "");
@@ -766,81 +772,79 @@ function callBodyFor(tool: TeamToolName, theme: ThemeLike, args: Record<string,
766
772
  const scope = requested?.length ? plural(requested.length, "teammate") : "all stopped";
767
773
  return callBody(theme, "Team Resume", accentTeam(theme, args.team), [theme.fg("muted", scope)]);
768
774
  }
769
- if (tool === "team_add") {
775
+ if (tool === "team_add_teammates") {
770
776
  const teammates = (args.teammates ?? []) as unknown[];
771
777
  return callBody(theme, "Team Add", accentTeam(theme, args.team), [theme.fg("muted", plural(teammates.length, "teammate"))]);
772
778
  }
773
- if (tool === "teamsend") {
779
+ if (tool === "team_send_message") {
774
780
  const message = String(args.message ?? "");
775
- return callBody(theme, "Team Send", sendTarget(theme, (args.to ?? []) as string[], roster), sendStats(theme, message, Boolean(args.interrupt)));
781
+ return callBody(theme, "Team Send", sendTarget(theme, (args.targets ?? []) as string[], roster), sendStats(theme, message, hasInterruption(args.interrupt)));
776
782
  }
777
- if (tool === "teamstatus") {
783
+ if (tool === "team_status") {
778
784
  const target = accentTeam(theme, args.team) || theme.fg("muted", "all teams");
779
- const setting = inlineText(`${String(args.word ?? "")} ${String(args.phrase ?? "")}`);
785
+ const setting = inlineText(`${String(args.gerund ?? "")} ${String(args.phrase ?? "")}`);
780
786
  return callBody(theme, "Team Status", target, setting ? [theme.fg("dim", `set ${setting}`)] : []);
781
787
  }
782
- if (tool === "teamlog") {
783
- const filterStats = ["teammate", "kind", "search", "since", "cursor"]
788
+ if (tool === "team_log") {
789
+ const filterStats = ["kind", "search", "since", "cursor"]
784
790
  .filter((key) => (typeof args[key] === "string" && args[key]) || (Array.isArray(args[key]) && args[key].length > 0))
785
791
  .map((key) => {
786
792
  const value = String(args[key]);
787
- if (key === "teammate") return `${theme.fg("dim", "teammate=")}${theme.fg(actorHueToken(value, roster), value)}`;
788
793
  return theme.fg("dim", `${key}=${value}`);
789
794
  });
790
- return callBody(theme, "Team Log", accentTeam(theme, args.team), filterStats);
795
+ return callBody(theme, "Team Log", Array.isArray(args.targets) ? actorList(theme, args.targets as string[], roster, ", ") : theme.fg("muted", "all teams"), filterStats);
791
796
  }
792
797
  return callBody(theme, "Team Shutdown", accentTeam(theme, args.team));
793
798
  }
794
799
 
795
800
  function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<string, unknown>, details: Record<string, unknown>, expanded: boolean, roster: string[]): TeamLine[] {
796
801
  if (tool === "team_spawn") {
797
- return teamSpawnLines(theme, String(details.team), (args.teammates ?? []) as TeammateSpecView[], roster);
802
+ return teamSpawnLines(theme, String(details.teamName), details.teammates as TeammateSpecView[], roster);
798
803
  }
799
804
  if (tool === "team_list") {
800
805
  const teamViews = ((details.teams ?? []) as Array<Record<string, unknown>>).map((entry) => ({
801
- name: String(entry.name),
806
+ name: String(entry.teamName),
802
807
  state: String(entry.state),
803
808
  leaseState: String(entry.leaseState ?? ""),
804
- members: (entry.members ?? []) as TeamListMemberView[],
809
+ members: (entry.teammates ?? []) as TeamListMemberView[],
805
810
  updatedAt: String(entry.updatedAt),
806
811
  expiresAt: entry.expiresAt as string | undefined,
807
812
  }));
808
813
  return teamListLines(theme, teamViews, roster);
809
814
  }
810
815
  if (tool === "team_resume") {
811
- const restartedEmpty = new Set((details.restartedEmpty ?? []) as string[]);
812
- const resumed = ((details.resumed ?? []) as string[]).map((name) => ({ name, restored: !restartedEmpty.has(name) }));
813
- return teamResumeLines(theme, String(details.team), resumed, ((details.teammates ?? []) as string[]).length, roster);
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 }));
817
+ return teamResumeLines(theme, String(details.teamName), teammates, teammates.length, roster);
814
818
  }
815
- if (tool === "team_add") {
819
+ if (tool === "team_add_teammates") {
816
820
  const memberCount = Object.keys((details.status ?? {}) as Record<string, unknown>).length;
817
- return teamAddLines(theme, String(details.team), (args.teammates ?? []) as TeammateSpecView[], memberCount, roster);
821
+ return teamAddLines(theme, String(details.teamName), (args.teammates ?? []) as TeammateSpecView[], memberCount, roster);
818
822
  }
819
- if (tool === "teamsend") {
823
+ if (tool === "team_send_message") {
820
824
  return teamSendLines(theme, {
821
- to: (details.to ?? []) as string[],
825
+ targets: (args.targets ?? []) as string[],
822
826
  message: String(args.message ?? ""),
823
- interrupt: Boolean(details.interrupt),
827
+ interrupt: hasInterruption(args.interrupt),
824
828
  expanded,
825
829
  }, roster);
826
830
  }
827
- if (tool === "teamstatus") {
828
- if (details.teams) return allTeamsStatusLines(theme, details.teams as Record<string, Record<string, TeamStatusView>>, roster);
829
- return teamStatusLines(theme, String(details.team), details.status as Record<string, TeamStatusView>, roster);
831
+ 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);
830
834
  }
831
- if (tool === "teamlog") {
835
+ if (tool === "team_log") {
832
836
  const filters = (details.filters ?? {}) as Record<string, unknown>;
833
- return teamLogLines(theme, {
834
- team: String(details.team),
835
- roster: roster.length > 0 ? roster : (details.roster ?? []) as string[],
836
- entries: (details.entries ?? []) as TeamLogEntry[],
837
- totalMatched: Number(details.totalMatched ?? 0),
838
- returned: Number(details.returned ?? 0),
839
- nextCursor: details.nextCursor as string | undefined,
840
- filters: { teammate: filters.teammate, kind: filters.kind, search: filters.search, since: filters.since },
841
- });
837
+ const selectedTeams = details.teams as Array<{ teamName: string; teamId: string; roster: string[]; entries: TeamLogEntry[]; totalMatched: number }>;
838
+ const lines = selectedTeams.flatMap((team) => teamLogLines(theme, {
839
+ team: `${team.teamName} (${team.teamId})`, roster: roster.length > 0 ? roster : team.roster,
840
+ entries: team.entries, totalMatched: team.totalMatched, returned: team.entries.length,
841
+ filters: { targets: filters.targets, kind: filters.kind, search: filters.search, since: filters.since },
842
+ }));
843
+ if (selectedTeams.length === 0) lines.push(headerLine(theme, "Team Log", theme.fg("muted", "no teams")));
844
+ if (details.nextCursor) lines.push(theme.fg("muted", ` Older events: cursor "${details.nextCursor}"`));
845
+ return lines;
842
846
  }
843
- return teamShutdownLines(theme, String(details.team), (details.teammates ?? []) as string[], roster);
847
+ return teamShutdownLines(theme, String(details.teamName), (details.teammates as Array<{ name: string }>).map((teammate) => teammate.name), roster);
844
848
  }
845
849
 
846
850
  export function renderTeamToolCall(tool: TeamToolName, args: Record<string, unknown>, theme: ThemeLike, context: ToolRenderContextLike, roster: string[] = []) {
@@ -861,9 +865,9 @@ export function renderTeamToolResult(
861
865
  return new TeamLines(errorLines(theme, callBodyFor(tool, theme, args, roster), textContent(result)), options.expanded ? "wrap" : "clip");
862
866
  }
863
867
  const details = (result?.details ?? {}) as Record<string, unknown>;
864
- if (markdownTheme && tool === "teamsend") {
868
+ if (markdownTheme && tool === "team_send_message") {
865
869
  const message = String(args.message ?? "");
866
- const header = headerLine(theme, "Team Send", sendTarget(theme, (details.to ?? []) as string[], roster), sendStats(theme, message, Boolean(details.interrupt)));
870
+ const header = headerLine(theme, "Team Send", sendTarget(theme, (args.targets ?? []) as string[], roster), sendStats(theme, message, hasInterruption(args.interrupt)));
867
871
  const bar = ` ${theme.fg("muted", glyphs().codeBar)} `;
868
872
  return new TeamSendView(header, message, bar, markdownTheme, options.expanded, theme);
869
873
  }
package/system-prompt.ts CHANGED
@@ -6,7 +6,7 @@ export function composeSystemPrompt(
6
6
  teammateName: string,
7
7
  teammatePrompt: string,
8
8
  participants: string[],
9
- canOverseeOwnTeams = false,
9
+ canManageOwnTeams = false,
10
10
  ): string {
11
11
  return [
12
12
  bundledSkillsInstruction,
@@ -14,18 +14,17 @@ export function composeSystemPrompt(
14
14
  teammatePrompt.trim(),
15
15
  `You are ${teammateName}, a teammate on team ${teamName}.`,
16
16
  `Participants: main, ${participants.join(", ")}.`,
17
- "Use teamsend to talk to teammates, teammain to talk to the main agent, and teamstatus to set/read public statuses.",
18
- "From the sender’s point of view, teamsend is fire-and-forget. From the recipient’s point of view, the message is pushed to context as soon as possible.",
17
+ "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.",
19
18
  "The main agent is the current coordinator. Use the team tools and available session history to share relevant context.",
20
- canOverseeOwnTeams && "You can create and manage teams of your own with team_spawn, team_list, team_resume, team_add, teamsend, teamstatus, report_context_window, teamlog, and team_shutdown.",
21
- canOverseeOwnTeams && "Your manager tools are scoped to teams created by this Pi session. They cannot manage this parent team or teams owned by other sessions.",
22
- canOverseeOwnTeams && "For teamsend and teamstatus, omit `team` to operate on this parent team. Set `team` to operate on a team you own.",
23
- canOverseeOwnTeams && "For report_context_window, omit `targets` to report yourself. Set `targets` to inspect teammates in teams you own.",
24
- "As soon as you wake up, call teamstatus to acknowledge that you received your instructions before doing substantive work.",
25
- "Whenever you receive a message from main or a teammate, call teamstatus first to acknowledge that specific message, then proceed.",
26
- "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.",
27
- "If you are waiting, message the person you are waiting for. Ask them to wake you when the condition is met. Set your status to “waiting for X to wake me when Y is done”, then stay put.",
28
- "There is no inbox to poll and no done button. Coordinate naturally. If the team is done, one teammate should tell main via teammain.",
19
+ canManageOwnTeams && "You can create and manage teams of your own with team_spawn, team_list, team_resume, team_add_teammates, team_send_message, team_status, get_context_window_usage, team_log, and team_shutdown.",
20
+ canManageOwnTeams && "Your manager tools are scoped to teams created by this Pi session. They cannot manage this parent team or teams owned by other sessions.",
21
+ canManageOwnTeams && "For team_status, omit `team` to operate on this parent team. Set `team` to operate on a team you own.",
22
+ canManageOwnTeams && "For get_context_window_usage, omit `targets` to get your own usage. Set `targets` to inspect teammates in teams you own.",
23
+ "When your turn starts, call team_status to acknowledge that you received your instructions before doing substantive work.",
24
+ "Whenever you receive a message from main or a teammate, call team_status first to acknowledge that specific message, then proceed.",
25
+ "Never set a waiting status until after you have sent the teammate you are waiting for a team_send_message describing exactly what you need from them.",
26
+ "If you are waiting, message the person you are waiting for. Ask them to message you when the condition is met. Set your status to “waiting for X to message me when Y is done”, then stay put.",
27
+ "There is no inbox to poll and no done button. Coordinate naturally. If the team is done, one teammate should tell main via send_main_message.",
29
28
  ]
30
29
  .filter(Boolean)
31
30
  .join("\n\n");
package/team-registry.ts CHANGED
@@ -3,23 +3,14 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
 
5
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ import type { TeammateRecord } from "./teammate.ts";
6
7
 
7
- export interface TeamManifestMember {
8
- name: string;
9
- prompt: string;
10
- model: string;
11
- thinking: string;
12
- inheritContext: boolean;
13
- canOverseeOwnTeams?: boolean;
14
- transport: "rpc" | "herdr";
15
- live: boolean;
16
- sessionId: string;
17
- sessionFile: string;
8
+ export interface TeamManifestMember extends TeammateRecord {
18
9
  sessionMaterialized: boolean;
19
10
  }
20
11
 
21
12
  export interface TeamManifest {
22
- version: 1;
13
+ version: 2;
23
14
  id: string;
24
15
  name: string;
25
16
  originMainSessionId: string;
@@ -46,7 +37,7 @@ export interface TeamLease {
46
37
  export const dormantManifestRetentionMilliseconds = 30 * 24 * 60 * 60 * 1_000;
47
38
 
48
39
  function manifestsDirectory(): string {
49
- return path.join(getAgentDir(), "pi-simple-team", "teams");
40
+ return path.join(getAgentDir(), "pi-simple-team", "teams-v2");
50
41
  }
51
42
 
52
43
  /** @example canonicalProjectDirectory(".") // absolute real path */
@@ -75,14 +66,15 @@ function isManifestMember(value: unknown): value is TeamManifestMember {
75
66
  const member = value as Record<string, unknown>;
76
67
  return (
77
68
  typeof member.name === "string" &&
78
- typeof member.prompt === "string" &&
69
+ typeof member.systemPrompt === "string" &&
79
70
  typeof member.model === "string" &&
80
71
  typeof member.thinking === "string" &&
81
- typeof member.inheritContext === "boolean" &&
82
- (member.canOverseeOwnTeams === undefined || typeof member.canOverseeOwnTeams === "boolean") &&
83
- (member.transport === "rpc" || member.transport === "herdr") &&
72
+ typeof member.inheritMainContext === "boolean" &&
73
+ typeof member.canManageOwnTeams === "boolean" &&
74
+ typeof member.showOnHerdrPane === "boolean" &&
84
75
  typeof member.live === "boolean" &&
85
- typeof member.sessionId === "string" &&
76
+ typeof member.active === "boolean" &&
77
+ typeof member.teammateId === "string" &&
86
78
  typeof member.sessionFile === "string" &&
87
79
  typeof member.sessionMaterialized === "boolean"
88
80
  );
@@ -97,7 +89,7 @@ function parseManifest(filePath: string): TeamManifest {
97
89
  const manifest = parsed as Record<string, unknown>;
98
90
  const validState = manifest.state === "active" || manifest.state === "dormant";
99
91
  if (
100
- manifest.version !== 1 ||
92
+ manifest.version !== 2 ||
101
93
  typeof manifest.id !== "string" ||
102
94
  typeof manifest.name !== "string" ||
103
95
  typeof manifest.originMainSessionId !== "string" ||
@@ -167,12 +159,7 @@ export function listTeamManifests(projectDirectory: string): TeamManifest[] {
167
159
  .map((entry) => ({ filePath: path.join(directory, entry.name), manifest: parseManifest(path.join(directory, entry.name)) }))
168
160
  .filter(({ filePath, manifest }) => {
169
161
  const expiresAt = Date.parse(manifest.expiresAt ?? "");
170
- const shutdownAt = Date.parse(manifest.shutdownAt ?? "");
171
- const expired = manifest.state === "dormant" && (
172
- Number.isFinite(expiresAt)
173
- ? now >= expiresAt
174
- : now - shutdownAt >= dormantManifestRetentionMilliseconds
175
- );
162
+ const expired = manifest.state === "dormant" && now >= expiresAt;
176
163
  if (!expired) return true;
177
164
  fs.rmSync(leasePath(manifest.id), { force: true });
178
165
  fs.rmSync(filePath);
@@ -210,7 +197,7 @@ function markAbandonedTeamDormant(teamId: string): void {
210
197
  const shutdownAt = new Date().toISOString();
211
198
  writeTeamManifest({
212
199
  ...manifest,
213
- members: manifest.members.map((member) => ({ ...member, live: false })),
200
+ members: manifest.members.map((member) => ({ ...member, live: false, active: false })),
214
201
  state: "dormant",
215
202
  updatedAt: shutdownAt,
216
203
  shutdownAt,
@@ -0,0 +1,57 @@
1
+ export interface SelectableTeam {
2
+ teamName: string;
3
+ teamId: string;
4
+ teammates: Array<{ name: string; teammateId: string }>;
5
+ }
6
+
7
+ export interface TeamSelection {
8
+ team: SelectableTeam;
9
+ teammates: SelectableTeam["teammates"];
10
+ wholeTeam: boolean;
11
+ }
12
+
13
+ export const targetDescription = "Team or teammate names or IDs. A team selects all its teammates. Names must be unique in your available teams. Use IDs to resolve duplicate names. Overlapping selections count once.";
14
+ export const interruptDescription = "True interrupts all selected recipients. A list uses the same names or IDs as targets and must select only message recipients. False or omitted interrupts none.";
15
+
16
+ /** @example resolveNamedId([{ name: "scout", id: "session-1" }], "session-1", "teammates").name // "scout" */
17
+ function resolveNamedId<Reference extends { name: string; id: string }>(candidates: readonly Reference[], identifier: string, parameter: string): Reference {
18
+ const name = identifier.trim();
19
+ const matches = candidates.filter((candidate) => candidate.id === name || candidate.name === name);
20
+ const choices = (matches.length > 0 ? matches : candidates).map(({ name, id }) => ({ name, id }));
21
+ if (matches.length !== 1) throw new Error(`${matches.length === 0 ? "Unknown" : "Ambiguous"} target ${JSON.stringify(identifier)}. Available choices: ${JSON.stringify(choices)}. Pass the intended ID in ${parameter}.`);
22
+ return matches[0];
23
+ }
24
+
25
+ /** @example resolveTeammates([{ name: "scout", teammateId: "session-1" }], ["scout", "session-1"]).length // 1 */
26
+ export function resolveTeammates<Member extends { name: string; teammateId: string }>(teammates: readonly Member[], identifiers: readonly string[]): Member[] {
27
+ const candidates = teammates.map((teammate) => ({ name: teammate.name, id: teammate.teammateId, teammate }));
28
+ return [...new Set(identifiers.map((identifier) => resolveNamedId(candidates, identifier, "teammates").teammate))];
29
+ }
30
+
31
+ /** @example resolveTargets([{ teamName: "review", teamId: "team-1", teammates: [{ name: "scout", teammateId: "session-1" }] }], ["review", "session-1"])[0].teammates.length // 1 */
32
+ export function resolveTargets(teams: readonly SelectableTeam[], identifiers: readonly string[]): TeamSelection[] {
33
+ const candidates = teams.flatMap((team) => [
34
+ { name: team.teamName, id: team.teamId, team, teammate: undefined },
35
+ ...team.teammates.map((teammate) => ({ name: teammate.name, id: teammate.teammateId, team, teammate })),
36
+ ]);
37
+ const selected = new Map<string, TeamSelection>();
38
+ for (const identifier of identifiers) {
39
+ const match = resolveNamedId(candidates, identifier, "targets");
40
+ const selection = selected.get(match.team.teamId) ?? { team: match.team, teammates: [], wholeTeam: false };
41
+ const additions = match.teammate ? [match.teammate] : match.team.teammates;
42
+ selection.teammates.push(...additions.filter((teammate) => !selection.teammates.some((existing) => existing.teammateId === teammate.teammateId)));
43
+ selection.wholeTeam ||= match.teammate === undefined;
44
+ selected.set(match.team.teamId, selection);
45
+ }
46
+ return [...selected.values()];
47
+ }
48
+
49
+ /** @example interruptedTeammateIds([], [], false).size // 0 */
50
+ export function interruptedTeammateIds(teams: readonly SelectableTeam[], recipients: readonly TeamSelection[], interrupt?: boolean | string[]): Set<string> {
51
+ const recipientIds = new Set(recipients.flatMap((selection) => selection.teammates.map((teammate) => teammate.teammateId)));
52
+ if (interrupt === true) return recipientIds;
53
+ const interrupted = resolveTargets(teams, Array.isArray(interrupt) ? interrupt : []).flatMap((selection) => selection.teammates);
54
+ const invalid = interrupted.filter((teammate) => !recipientIds.has(teammate.teammateId));
55
+ if (invalid.length > 0) throw new Error(`interrupt must select only message recipients. Not selected by targets: ${JSON.stringify(invalid)}.`);
56
+ return new Set(interrupted.map((teammate) => teammate.teammateId));
57
+ }
package/team-ui.ts CHANGED
@@ -18,7 +18,7 @@ import type { TeamLogEntry, TeamLogKind } from "./teamlog.ts";
18
18
  export interface TeamSnapshot {
19
19
  name: string;
20
20
  created: string;
21
- showOnHerdrPanes: boolean;
21
+ transports: readonly ("rpc" | "herdr")[];
22
22
  roster: string[];
23
23
  statuses: Record<string, TeamStatusView>;
24
24
  log: TeamLogEntry[];
@@ -276,7 +276,7 @@ class TeamOverviewOverlay implements Component {
276
276
  }
277
277
 
278
278
  private headerRegion(team: TeamSnapshot, hint: string, contentWidth: number, headerHeight: number, breadcrumb?: string): string[] {
279
- const transport = team.showOnHerdrPanes ? "Herdr" : "RPC";
279
+ const transport = team.transports.map((transport) => transport === "herdr" ? "Herdr" : "RPC").join(" + ") || "RPC";
280
280
  const metadata = [
281
281
  `Created ${relativeTimeText(team.created)}`,
282
282
  `${team.roster.length} teammate${team.roster.length === 1 ? "" : "s"}`,
package/teamlog.ts CHANGED
@@ -169,19 +169,37 @@ function resolveLimit(limit: number | undefined): number {
169
169
  return Math.min(Math.floor(limit), MAX_LIMIT);
170
170
  }
171
171
 
172
- function parseCursor(cursor: string | undefined): number | undefined {
172
+ type LogPosition = [epochMilliseconds: number, team: string, sequence: number];
173
+
174
+ /** @example logPosition({ epochMilliseconds: 1000, team: "review", sequence: 2 }) // [1000, "review", 2] */
175
+ function logPosition(entry: Pick<TeamLogEntry, "epochMilliseconds" | "team" | "sequence">): LogPosition {
176
+ return [entry.epochMilliseconds, entry.team, entry.sequence];
177
+ }
178
+
179
+ /** @example compareLogPositions([1000, "a", 1], [1000, "b", 1]) < 0 // true */
180
+ function compareLogPositions(left: LogPosition, right: LogPosition): number {
181
+ return left[0] - right[0] || left[1].localeCompare(right[1]) || left[2] - right[2];
182
+ }
183
+
184
+ function parseCursor(cursor: string | undefined): LogPosition | undefined {
173
185
  if (cursor === undefined) return undefined;
174
- const match = /^before:(\d+)$/.exec(cursor);
175
- if (!match) throw new Error(`Invalid cursor: ${cursor}`);
176
- return Number(match[1]);
186
+ let position: unknown;
187
+ try {
188
+ position = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
189
+ } catch {
190
+ throw new Error(`Invalid cursor: ${cursor}`);
191
+ }
192
+ if (!Array.isArray(position) || position.length !== 3 || !Number.isFinite(position[0]) || typeof position[1] !== "string" || !Number.isSafeInteger(position[2])) throw new Error(`Invalid cursor: ${cursor}`);
193
+ return position as LogPosition;
177
194
  }
178
195
 
179
196
  export function pageTeamLog(filteredEntries: TeamLogEntry[], params: TeamLogPageParams): TeamLogPage {
180
197
  const limit = resolveLimit(params.limit);
181
- const beforeSequence = parseCursor(params.cursor);
198
+ const before = parseCursor(params.cursor);
182
199
  const totalMatched = filteredEntries.length;
183
200
 
184
- const eligible = beforeSequence === undefined ? filteredEntries : filteredEntries.filter((entry) => entry.sequence < beforeSequence);
201
+ const eligible = filteredEntries.filter((entry) => before === undefined || compareLogPositions(logPosition(entry), before) < 0)
202
+ .sort((left, right) => compareLogPositions(logPosition(left), logPosition(right)));
185
203
 
186
204
  const pageEntries = eligible.slice(Math.max(0, eligible.length - limit));
187
205
  const hasOlder = eligible.length > pageEntries.length;
@@ -191,7 +209,7 @@ export function pageTeamLog(filteredEntries: TeamLogEntry[], params: TeamLogPage
191
209
  entries: pageEntries,
192
210
  totalMatched,
193
211
  returned: pageEntries.length,
194
- nextCursor: hasOlder && oldestInPage ? `before:${oldestInPage.sequence}` : undefined,
212
+ nextCursor: hasOlder && oldestInPage ? Buffer.from(JSON.stringify(logPosition(oldestInPage))).toString("base64url") : undefined,
195
213
  limit,
196
214
  };
197
215
  }
@@ -230,7 +248,7 @@ export function renderTeamLogPage(view: TeamLogPageView): string {
230
248
  }
231
249
 
232
250
  /** Child team tools always emit a semantic entry (send/main_message/status), so their tool frames would be pure triplication. */
233
- const TEAM_CHILD_TOOLS = new Set(["teamsend", "teammain", "teamstatus"]);
251
+ const TEAM_CHILD_TOOLS = new Set(["team_send_message", "send_main_message", "team_status"]);
234
252
 
235
253
  export function normalizeChildEvent(team: string, teammate: string, event: Record<string, unknown>): TeamLogEntryInput | undefined {
236
254
  const type = event.type;
package/teammate.ts ADDED
@@ -0,0 +1,18 @@
1
+ export type ThinkingLevel = "low" | "medium" | "high" | "xhigh" | "max";
2
+
3
+ export interface Teammate {
4
+ name: string;
5
+ systemPrompt: string;
6
+ model: string;
7
+ thinking?: ThinkingLevel;
8
+ inheritMainContext?: boolean;
9
+ canManageOwnTeams?: boolean;
10
+ showOnHerdrPane?: boolean;
11
+ }
12
+
13
+ export type TeammateRecord = Required<Teammate> & {
14
+ teammateId: string;
15
+ sessionFile: string;
16
+ live: boolean;
17
+ active: boolean;
18
+ };