@giladbarnea/pi-simple-team 2.0.23 → 2.0.25
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/README.md +12 -2
- package/child-tools.ts +27 -0
- package/index.ts +312 -47
- package/package.json +1 -1
- package/render.ts +28 -11
- package/resume-message.ts +30 -0
- package/team-registry.ts +9 -1
- package/team-selection.ts +1 -1
- package/teammate-facts.ts +4 -4
package/README.md
CHANGED
|
@@ -128,7 +128,7 @@ Your main agent calls `team_status` and understands exactly what is going on. Ma
|
|
|
128
128
|
|
|
129
129
|
Teammates know how much free context they have left.
|
|
130
130
|
|
|
131
|
-
Main agent knows its own and everyone else's too.
|
|
131
|
+
Main agent knows its own and everyone else's too. You see it as well: team tool results show the last reported context use beside each teammate they involve, such as `Team Send → builder ▆72% context`.
|
|
132
132
|
|
|
133
133
|
They will hand off work autonomously when it's time to say goodbye.
|
|
134
134
|
|
|
@@ -171,6 +171,8 @@ Have a teammate do work, exit Pi entirely, come back tomorrow in a brand-new ses
|
|
|
171
171
|
|
|
172
172
|
You can even `/resume` a teammate session directly if you ever want a cozy one-on-one, or run `pi --session <teammate-session-id>`.
|
|
173
173
|
|
|
174
|
+
Every teammate session records which main session and team started it, in one `pi-simple-team-teammate` custom entry that the model and the TUI never see. Its `sessionId` is the session it was written in, so a later `pi --fork` of a teammate carries a copy you can tell is inherited.
|
|
175
|
+
|
|
174
176
|
## It’s teams all the way down (optionally)
|
|
175
177
|
|
|
176
178
|
Tell main you want to **have a teammate manage its own team(s).**
|
|
@@ -221,7 +223,7 @@ Kept minimal:
|
|
|
221
223
|
| | With team | `team_send_message` |
|
|
222
224
|
| | On team | `team_status`, `team_log` |
|
|
223
225
|
| | On everyone | `get_context_window_usage` |
|
|
224
|
-
| | On self | `schedule_reminder` |
|
|
226
|
+
| | On self | `schedule_reminder`, `list_reminders`, `cancel_reminders` |
|
|
225
227
|
| **Managing teammate** | On self and own teams | Same tools as the main agent |
|
|
226
228
|
| | With parent team | `team_send_message`, `team_status`, `send_main_message` |
|
|
227
229
|
| **Teammates** | With team | `team_send_message` |
|
|
@@ -233,12 +235,20 @@ Kept minimal:
|
|
|
233
235
|
|
|
234
236
|
Startup delivers `commonPrompt` inside `<team-system-message>` and each teammate's `systemPrompt` inside `<your-specific-system-message>`. These are labels in the custom team message, not system-role overrides. The briefing also contains the teammate's identity and coordination guidance.
|
|
235
237
|
|
|
238
|
+
When main quits, reloads or crashes, its teams stop. When that main session starts again, Simple Team reattaches the teammates that were running, idle and in their own conversations, without sending them anything or making a model request. Main gets one message listing them and which were working, so it can tell those to continue. Teams stopped with `team_shutdown`, or left by switching main to another session, stay stopped. After a crash, a Herdr pane teammate may still be running in its pane, so it is listed instead of reattached.
|
|
239
|
+
|
|
236
240
|
Resume appends a custom briefing with the team identity, current time, and last recorded model activity. Optional `resumptionPrompt` instructions follow that briefing without changing saved definitions. With `startIdle: true`, the briefing waits in context for the next turn.
|
|
237
241
|
|
|
238
242
|
Existing teammates can be selected by name or Pi session ID in the same input field. Messages, logs, and context usage share a `targets` list. Select a team for all its teammates, or select individual teammates across your teams. Ambiguous names return IDs you can use instead.
|
|
239
243
|
|
|
240
244
|
`team_update_teammates` changes a live teammate's model, thinking level or extensions in its own conversation. An idle teammate restarts at once, in its pane if it has one; a busy one keeps working and is updated when its run settles, or at once with `interrupt: true`. A managing teammate is never held: while it or any of its own teammates works, the call fails and tells main to ask it to soft-pause them, and the same call succeeds once they are idle. The restarted teammate gets a message with its new settings and the teams its restart stopped, so it can resume them. Main gets a message when a held update applies; `team_shutdown` lists any it drops. `team_resume` takes the same changes in `teammateUpdates` for the teammates it resumes. Instructions and `forkContext` stay as created.
|
|
241
245
|
|
|
246
|
+
`team_list` shows active teams as short rows, newest created first, 20 per page by default (`limit` up to 100, then `cursor`). Pass `includeDormantTeams: true` to include dormant teams, or `team` for one team's full records. Pages follow creation order, so a team that changes state or activity between pages is neither repeated nor skipped.
|
|
247
|
+
|
|
248
|
+
Reminders are recorded in the session, so they survive `/reload` and restarts of that session. One that fell due while Pi was not running fires on start and says how late it is.
|
|
249
|
+
|
|
250
|
+
`list_reminders` shows this session's pending reminders with their IDs, slugs and times. `cancel_reminders` cancels reminders by ID or slug, or every pending one with `all: true`; a call with neither cancels nothing.
|
|
251
|
+
|
|
242
252
|
Spawn, resume, and add return the complete roster. Results distinguish a live runtime from active work, including work that was already underway before the call.
|
|
243
253
|
|
|
244
254
|
Set `showOnHerdrPane: true` on individual teammates to open their panes. An explicit `showOnHerdrPanes` value on spawn overrides all individual settings.
|
package/child-tools.ts
CHANGED
|
@@ -37,6 +37,9 @@ export interface ChildRuntimeConfig {
|
|
|
37
37
|
processId?: string;
|
|
38
38
|
participants: string[];
|
|
39
39
|
canManageOwnTeams: boolean;
|
|
40
|
+
/** The main session that started this teammate. A simulated teammate without one records no breadcrumb. */
|
|
41
|
+
parentSessionId?: string;
|
|
42
|
+
parentSessionFile?: string;
|
|
40
43
|
interruptWaitTimeoutMilliseconds?: number;
|
|
41
44
|
}
|
|
42
45
|
|
|
@@ -66,9 +69,32 @@ function readRequiredChildRuntimeConfig(): ChildRuntimeConfig {
|
|
|
66
69
|
processId: process.env.PI_SIMPLE_TEAM_PROCESS,
|
|
67
70
|
participants: readParticipants(),
|
|
68
71
|
canManageOwnTeams: process.env.PI_SIMPLE_TEAM_CAN_MANAGE_OWN_TEAMS === "1",
|
|
72
|
+
parentSessionId: process.env.PI_SIMPLE_TEAM_PARENT_SESSION_ID,
|
|
73
|
+
parentSessionFile: process.env.PI_SIMPLE_TEAM_PARENT_SESSION_FILE,
|
|
69
74
|
};
|
|
70
75
|
}
|
|
71
76
|
|
|
77
|
+
const breadcrumbType = "pi-simple-team-teammate";
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Names, once in this teammate's own session, the main session and team that started it. It is a custom entry, so it never
|
|
81
|
+
* reaches the model or the TUI. Its sessionId tells the teammate's own breadcrumb from a copy inherited through a later fork.
|
|
82
|
+
*/
|
|
83
|
+
function recordBreadcrumb(pi: ExtensionAPI, config: ChildRuntimeConfig, context: ExtensionContext): void {
|
|
84
|
+
if (!config.parentSessionId) return;
|
|
85
|
+
const sessionId = context.sessionManager.getSessionId();
|
|
86
|
+
if (context.sessionManager.getEntries().some((entry) => entry.type === "custom" && entry.customType === breadcrumbType && (entry.data as { sessionId?: unknown } | undefined)?.sessionId === sessionId)) return;
|
|
87
|
+
pi.appendEntry(breadcrumbType, {
|
|
88
|
+
sessionId,
|
|
89
|
+
parentSessionId: config.parentSessionId,
|
|
90
|
+
parentSessionFile: config.parentSessionFile,
|
|
91
|
+
teamId: config.teamId,
|
|
92
|
+
teamName: config.teamName,
|
|
93
|
+
teammate: config.teammateName,
|
|
94
|
+
createdAt: new Date().toISOString(),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
72
98
|
/**
|
|
73
99
|
* A teammate process inherits discovered extensions, so it can also discover an installed copy of this package at another path.
|
|
74
100
|
* Only the copy main passed as PI_SIMPLE_TEAM_RUNTIME_PATH registers; another copy stays inert so their tools cannot conflict.
|
|
@@ -266,6 +292,7 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
|
266
292
|
});
|
|
267
293
|
pi.on("session_start", async (_event, context) => {
|
|
268
294
|
activateChildTools(pi);
|
|
295
|
+
recordBreadcrumb(pi, config, context);
|
|
269
296
|
server = http.createServer((request, response) => {
|
|
270
297
|
void (async () => {
|
|
271
298
|
try {
|
package/index.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { formatContextWindowReport, requireKnownContextUsage, type KnownContextU
|
|
|
11
11
|
import { useModelNames } from "./model-names.ts";
|
|
12
12
|
import { formatScopedModelGuidance, validateTeammateModels, type ModelReference } from "./model-preflight.ts";
|
|
13
13
|
import { composeTeamBriefing } from "./team-briefing.ts";
|
|
14
|
-
import { composeResumptionMessage, composeSettingsMessage } from "./resume-message.ts";
|
|
14
|
+
import { composeReattachmentMessage, composeResumptionMessage, composeSettingsMessage, type Reattachment } from "./resume-message.ts";
|
|
15
15
|
import { callParent, isInertTeamCopy, readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
|
|
16
16
|
import {
|
|
17
17
|
canonicalProjectDirectory,
|
|
@@ -105,6 +105,8 @@ interface TeamState {
|
|
|
105
105
|
showOnHerdrPanes: boolean;
|
|
106
106
|
teamPrompt: string;
|
|
107
107
|
mainSessionFile?: string;
|
|
108
|
+
/** The main session running this team. Every teammate it starts records it in its own session's breadcrumb. */
|
|
109
|
+
parentSession?: { id: string; file?: string };
|
|
108
110
|
members: Map<string, TeammateState>;
|
|
109
111
|
statuses: Map<string, TeamStatus>;
|
|
110
112
|
created: string;
|
|
@@ -123,6 +125,7 @@ const defaultRpcShutdownGraceMilliseconds = 1_000;
|
|
|
123
125
|
/** Time for main's own shutdown to mark its teams before an exit notice is sent, for signals that reach main and its teammates together. */
|
|
124
126
|
const exitNoticeGraceMilliseconds = 2_000;
|
|
125
127
|
const teamMessageType = "pi-simple-team";
|
|
128
|
+
const reattachedMessageType = "pi-simple-team-reattached";
|
|
126
129
|
const teams = new Map<string, TeamState>();
|
|
127
130
|
const callbackToken = crypto.randomBytes(24).toString("hex");
|
|
128
131
|
let callbackServer: http.Server | undefined;
|
|
@@ -149,6 +152,52 @@ function toolResult(payload: JsonRecord, viewDetails: JsonRecord = {}) {
|
|
|
149
152
|
};
|
|
150
153
|
}
|
|
151
154
|
|
|
155
|
+
const defaultTeamListLimit = 20;
|
|
156
|
+
|
|
157
|
+
/** A team_list position: a team's place in creation order, which no state change or activity moves, so paging neither skips nor repeats a team. */
|
|
158
|
+
interface TeamListCursor {
|
|
159
|
+
createdAt: string;
|
|
160
|
+
id: string;
|
|
161
|
+
includeDormantTeams: boolean;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** @example newestCreatedFirst({ createdAt: "2026-01-02", id: "b" }, { createdAt: "2026-01-01", id: "a" }) < 0 // true */
|
|
165
|
+
function newestCreatedFirst(first: { createdAt: string; id: string }, second: { createdAt: string; id: string }): number {
|
|
166
|
+
return second.createdAt.localeCompare(first.createdAt) || second.id.localeCompare(first.id);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** @example decodeTeamListCursor(encodeTeamListCursor({ createdAt: "t", id: "a", includeDormantTeams: false })).id // "a" */
|
|
170
|
+
function encodeTeamListCursor(cursor: TeamListCursor): string {
|
|
171
|
+
return Buffer.from(JSON.stringify(cursor)).toString("base64url");
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function decodeTeamListCursor(cursor: string): TeamListCursor {
|
|
175
|
+
let decoded: Partial<TeamListCursor>;
|
|
176
|
+
try {
|
|
177
|
+
decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")) as Partial<TeamListCursor>;
|
|
178
|
+
} catch {
|
|
179
|
+
decoded = {};
|
|
180
|
+
}
|
|
181
|
+
if (typeof decoded.createdAt !== "string" || typeof decoded.id !== "string" || typeof decoded.includeDormantTeams !== "boolean") throw new Error("Invalid team_list cursor. Pass nextCursor from the previous team_list result.");
|
|
182
|
+
return decoded as TeamListCursor;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
interface Reminder {
|
|
186
|
+
sessionId: string;
|
|
187
|
+
id: string;
|
|
188
|
+
slug: string;
|
|
189
|
+
message: string;
|
|
190
|
+
armedAt: Date;
|
|
191
|
+
wakeAt: Date;
|
|
192
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
193
|
+
state: "pending" | "delivered" | "cancelled";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** A reminder as its session records it. A reminder's latest record holds its current state. */
|
|
197
|
+
type ReminderRecord = Omit<Reminder, "armedAt" | "wakeAt" | "timer"> & { armedAt: string; wakeAt: string };
|
|
198
|
+
|
|
199
|
+
const reminderType = "pi-simple-team-reminder";
|
|
200
|
+
|
|
152
201
|
const reminderSlugWords = {
|
|
153
202
|
adjectives: ["amber", "brisk", "calm", "clever", "dusty", "eager", "fuzzy", "gentle", "golden", "hollow", "jolly", "lively", "mellow", "misty", "nimble", "plucky", "quiet", "rapid", "rusty", "silver", "steady", "sunny", "swift", "witty"],
|
|
154
203
|
nouns: ["badger", "beacon", "cedar", "comet", "falcon", "fern", "harbor", "heron", "lantern", "maple", "meadow", "otter", "pebble", "pine", "quail", "raven", "river", "robin", "sparrow", "spruce", "thistle", "tulip", "walrus", "willow"],
|
|
@@ -229,6 +278,33 @@ function lifecycleInstruction(startIdle: boolean): string {
|
|
|
229
278
|
return nextAction;
|
|
230
279
|
}
|
|
231
280
|
|
|
281
|
+
/** A listed team's full records: the saved definitions, with live runtime values for a team this process runs. */
|
|
282
|
+
function fullTeamListRow(manifest: TeamManifest): JsonRecord {
|
|
283
|
+
const liveTeam = teams.get(manifest.id);
|
|
284
|
+
return {
|
|
285
|
+
...teamIdentity(manifest),
|
|
286
|
+
state: manifest.state,
|
|
287
|
+
leaseState: readTeamLeaseState(manifest.id).state,
|
|
288
|
+
teammates: manifest.members.map(({ sessionMaterialized, ...member }) => {
|
|
289
|
+
const runtime = liveTeam?.members.get(member.name);
|
|
290
|
+
return runtime ? teammateRecord(runtime) : member;
|
|
291
|
+
}),
|
|
292
|
+
createdAt: manifest.createdAt,
|
|
293
|
+
updatedAt: manifest.updatedAt,
|
|
294
|
+
shutdownAt: manifest.shutdownAt,
|
|
295
|
+
expiresAt: manifest.expiresAt,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** The short row team_list shows the model by default: the team, its state, and each teammate's identity, model and liveness, without prompts or settings. */
|
|
300
|
+
function compactTeamListRow(manifest: TeamManifest): JsonRecord {
|
|
301
|
+
const full = fullTeamListRow(manifest);
|
|
302
|
+
return {
|
|
303
|
+
teamName: full.teamName, teamId: full.teamId, state: full.state,
|
|
304
|
+
teammates: (full.teammates as TeammateRecord[]).map(({ name, teammateId, model, live, active }) => ({ name, teammateId, model, live, active })),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
232
308
|
/** @example lifecycleResult(emptyTeam).started // false */
|
|
233
309
|
function lifecycleResult(team: TeamState): JsonRecord {
|
|
234
310
|
const teammates = [...team.members.values()].map(teammateRecord);
|
|
@@ -485,7 +561,7 @@ function resolveTeam(owner: symbol, teamIdentifier?: string): TeamState {
|
|
|
485
561
|
const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
|
|
486
562
|
if (teamIdentifier) {
|
|
487
563
|
const team = resolveTeamIdentifier(ownedTeams, teamIdentifier);
|
|
488
|
-
if (!team) throw new Error(`Unknown team: ${JSON.stringify(teamIdentifier)}. Available owned team IDs by name: ${JSON.stringify(teamChoices(ownedTeams))}. Use team_list to find dormant teams, or pass an owned active team name or ID in the team parameter.`);
|
|
564
|
+
if (!team) throw new Error(`Unknown team: ${JSON.stringify(teamIdentifier)}. Available owned team IDs by name: ${JSON.stringify(teamChoices(ownedTeams))}. Use team_list with includeDormantTeams: true to find dormant teams, or pass an owned active team name or ID in the team parameter.`);
|
|
489
565
|
return team;
|
|
490
566
|
}
|
|
491
567
|
|
|
@@ -526,6 +602,11 @@ function formatStatus(team: TeamState): Record<string, TeamStatus> {
|
|
|
526
602
|
return Object.fromEntries([...team.statuses.entries()].sort(([a], [b]) => a.localeCompare(b)));
|
|
527
603
|
}
|
|
528
604
|
|
|
605
|
+
/** A teammate a tool involves, with the context use it last reported, for that tool's renderer. */
|
|
606
|
+
function agentContext(teammate: TeammateState): { name: string; contextPercent?: number } {
|
|
607
|
+
return { name: teammate.name, contextPercent: teammate.contextPercent };
|
|
608
|
+
}
|
|
609
|
+
|
|
529
610
|
/** @example teammateViews(team).scout?.model // "openai-codex/gpt-6-luna" */
|
|
530
611
|
function teammateViews(team: TeamState): Record<string, TeammateView> {
|
|
531
612
|
return Object.fromEntries([...team.members.values()].map((teammate) => [teammate.name, {
|
|
@@ -623,9 +704,17 @@ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, par
|
|
|
623
704
|
PI_SIMPLE_TEAM_PROCESS: teammate.processRecord!.id,
|
|
624
705
|
PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
|
|
625
706
|
PI_SIMPLE_TEAM_CAN_MANAGE_OWN_TEAMS: teammate.canManageOwnTeams ? "1" : "0",
|
|
707
|
+
...(team.parentSession ? { PI_SIMPLE_TEAM_PARENT_SESSION_ID: team.parentSession.id } : {}),
|
|
708
|
+
...(team.parentSession?.file ? { PI_SIMPLE_TEAM_PARENT_SESSION_FILE: team.parentSession.file } : {}),
|
|
626
709
|
};
|
|
627
710
|
}
|
|
628
711
|
|
|
712
|
+
/** The main session a tool or event runs in, when it has one. */
|
|
713
|
+
function mainSession(context: ExtensionContext): TeamState["parentSession"] {
|
|
714
|
+
const id = context.sessionManager?.getSessionId?.();
|
|
715
|
+
return id ? { id, file: context.sessionManager?.getSessionFile?.() } : undefined;
|
|
716
|
+
}
|
|
717
|
+
|
|
629
718
|
function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
|
|
630
719
|
appendTeamLog(team, {
|
|
631
720
|
team: team.name,
|
|
@@ -754,13 +843,19 @@ function restartWithSettings(team: TeamState, teammate: TeammateState, update: T
|
|
|
754
843
|
});
|
|
755
844
|
}
|
|
756
845
|
|
|
846
|
+
/** Whether a living process of this session holds the team's lease. Another main that resumed the team holds it under its own session. */
|
|
847
|
+
function isLeaseHeldBy(teamId: string, sessionId: string | undefined): boolean {
|
|
848
|
+
const lease = readTeamLeaseState(teamId);
|
|
849
|
+
return lease.state === "claimed" && lease.mainSessionId === sessionId;
|
|
850
|
+
}
|
|
851
|
+
|
|
757
852
|
/**
|
|
758
853
|
* A managing teammate's running teams, which a restart would stop: its shutdown stops every team it owns.
|
|
759
|
-
* A running team's manifest is active and
|
|
854
|
+
* A running team's manifest is active and a living process of the manager's own session holds its lease. A manager that died abruptly leaves its manifests active behind a stale lease, and a team another main resumed is that main's, so neither counts.
|
|
760
855
|
*/
|
|
761
856
|
function activeManagedTeams(team: TeamState, teammate: TeammateState): TeamManifest[] {
|
|
762
857
|
if (!teammate.canManageOwnTeams || !team.projectDirectory) return [];
|
|
763
|
-
return listTeamManifests(team.projectDirectory).manifests.filter((manifest) => manifest.originMainSessionId === teammate.sessionId && manifest.state === "active" &&
|
|
858
|
+
return listTeamManifests(team.projectDirectory).manifests.filter((manifest) => manifest.originMainSessionId === teammate.sessionId && manifest.state === "active" && isLeaseHeldBy(manifest.id, teammate.sessionId));
|
|
764
859
|
}
|
|
765
860
|
|
|
766
861
|
/** The managing teammate's own teammates that are working, as their teams' manifests record them, named for main. */
|
|
@@ -907,6 +1002,7 @@ function persistActiveTeamManifest(team: TeamState): void {
|
|
|
907
1002
|
updatedAt,
|
|
908
1003
|
shutdownAt: undefined,
|
|
909
1004
|
expiresAt: undefined,
|
|
1005
|
+
interrupted: undefined,
|
|
910
1006
|
};
|
|
911
1007
|
writeTeamManifest(team.manifest);
|
|
912
1008
|
}
|
|
@@ -948,7 +1044,14 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
|
|
|
948
1044
|
teammate.process = undefined;
|
|
949
1045
|
}
|
|
950
1046
|
|
|
951
|
-
|
|
1047
|
+
/** The teammates main's own stop interrupts, read before it stops them; undefined when none is running or the team has no saved record to keep them in. */
|
|
1048
|
+
function interruptedTeammates(team: TeamState): TeamManifest["interrupted"] {
|
|
1049
|
+
const running = [...team.members.values()].filter((teammate) => teammate.alive && teammate.sessionId);
|
|
1050
|
+
if (running.length === 0 || !team.lease) return undefined;
|
|
1051
|
+
return { mainSessionId: team.lease.mainSessionId, teammates: running.map((teammate) => teammate.name), working: running.filter((teammate) => teammateSummary(teammate).active).map((teammate) => teammate.name) };
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
async function shutdownTeam(team: TeamState, interrupted?: TeamManifest["interrupted"]): Promise<string[]> {
|
|
952
1055
|
team.stopping = true;
|
|
953
1056
|
const errors: string[] = [];
|
|
954
1057
|
for (const teammate of team.members.values()) {
|
|
@@ -973,6 +1076,7 @@ async function shutdownTeam(team: TeamState): Promise<string[]> {
|
|
|
973
1076
|
updatedAt: shutdownAt,
|
|
974
1077
|
shutdownAt,
|
|
975
1078
|
expiresAt: new Date(Date.parse(shutdownAt) + dormantManifestRetentionMilliseconds).toISOString(),
|
|
1079
|
+
interrupted,
|
|
976
1080
|
};
|
|
977
1081
|
writeTeamManifest(team.manifest);
|
|
978
1082
|
} catch (error) {
|
|
@@ -1328,7 +1432,31 @@ export default function (pi: ExtensionAPI) {
|
|
|
1328
1432
|
|
|
1329
1433
|
const parentPiCommand = piCommand(process.argv[1], process.execPath, getPackageDir());
|
|
1330
1434
|
const owner = Symbol("pi-simple-team-owner");
|
|
1331
|
-
|
|
1435
|
+
/** This session's reminders by ID, restored from the session's records on every session start. */
|
|
1436
|
+
const reminders = new Map<string, Reminder>();
|
|
1437
|
+
let reminderCount = 0;
|
|
1438
|
+
|
|
1439
|
+
function recordReminder(reminder: Reminder): void {
|
|
1440
|
+
const { timer: _timer, ...fields } = reminder;
|
|
1441
|
+
pi.appendEntry<ReminderRecord>(reminderType, { ...fields, armedAt: reminder.armedAt.toISOString(), wakeAt: reminder.wakeAt.toISOString() });
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
/** Arms a pending reminder's timer. One that is already due fires at once and says how late it is. */
|
|
1445
|
+
function armReminder(reminder: Reminder): void {
|
|
1446
|
+
const delayMilliseconds = reminder.wakeAt.getTime() - Date.now();
|
|
1447
|
+
reminder.timer = setTimeout(() => {
|
|
1448
|
+
const now = new Date();
|
|
1449
|
+
const lateness = delayMilliseconds < 0 ? ` It is ${humanDuration(Math.round((now.getTime() - reminder.wakeAt.getTime()) / 1000))} late: it was due at ${humanTime(reminder.wakeAt)}.` : "";
|
|
1450
|
+
reminder.state = "delivered";
|
|
1451
|
+
recordReminder(reminder);
|
|
1452
|
+
pi.sendMessage(
|
|
1453
|
+
{ customType: reminderType, content: `Reminder ${reminder.slug} wake up: it's ${humanTime(now)} now.${lateness}\n\n${reminder.message}`, display: false },
|
|
1454
|
+
{ deliverAs: "followUp", triggerTurn: true },
|
|
1455
|
+
);
|
|
1456
|
+
}, Math.max(0, delayMilliseconds));
|
|
1457
|
+
reminder.timer.unref();
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1332
1460
|
const sessionTeammateRoster = childRuntimeConfig?.participants ?? [];
|
|
1333
1461
|
|
|
1334
1462
|
/** Current-project manifests that team_resume can select: all for main, only its own for a managing teammate. */
|
|
@@ -1361,15 +1489,88 @@ export default function (pi: ExtensionAPI) {
|
|
|
1361
1489
|
},
|
|
1362
1490
|
});
|
|
1363
1491
|
|
|
1364
|
-
pi.on("session_shutdown", async () => {
|
|
1365
|
-
for (const
|
|
1366
|
-
|
|
1492
|
+
pi.on("session_shutdown", async (event) => {
|
|
1493
|
+
for (const reminder of reminders.values()) clearTimeout(reminder.timer);
|
|
1494
|
+
reminders.clear();
|
|
1367
1495
|
const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
|
|
1368
1496
|
for (const team of ownedTeams) team.stopping = true;
|
|
1369
|
-
for
|
|
1497
|
+
// Main's quit or reload keeps its running teammates for its next start. Switching to another session releases them.
|
|
1498
|
+
const keepsTeams = !childRuntimeConfig && (event.reason === "quit" || event.reason === "reload");
|
|
1499
|
+
for (const team of ownedTeams) await shutdownTeam(team, keepsTeams ? interruptedTeammates(team) : undefined);
|
|
1370
1500
|
closeCallbackServerIfUnused();
|
|
1371
1501
|
});
|
|
1372
1502
|
|
|
1503
|
+
/** Restarts a team's interrupted teammates idle, in their own conversations, without delivering anything. */
|
|
1504
|
+
async function reattachTeam(manifest: TeamManifest, interrupted: NonNullable<TeamManifest["interrupted"]>, inPanes: string[], parentSession: NonNullable<TeamState["parentSession"]>): Promise<Reattachment> {
|
|
1505
|
+
const reattachment: Reattachment = { teamName: manifest.name, teamId: manifest.id, reattached: [], working: [], inPanes };
|
|
1506
|
+
let team: TeamState | undefined;
|
|
1507
|
+
try {
|
|
1508
|
+
await ensureCallbackServer();
|
|
1509
|
+
team = restoreTeamState(owner, pi, parentPiCommand, manifest, claimTeamLease(manifest.id, parentSession.id));
|
|
1510
|
+
team.parentSession = parentSession;
|
|
1511
|
+
teams.set(team.id!, team);
|
|
1512
|
+
const participantNames = [...team.members.keys()];
|
|
1513
|
+
sessionTeammateRoster.push(...participantNames.filter((name) => !sessionTeammateRoster.includes(name)));
|
|
1514
|
+
const emptyRestarts: TeammateState[] = [];
|
|
1515
|
+
for (const name of interrupted.teammates) {
|
|
1516
|
+
const teammate = team.members.get(name)!;
|
|
1517
|
+
const sessionFile = sessionFileForResume(teammate);
|
|
1518
|
+
prepareTeammateStart(teammate, "rpc");
|
|
1519
|
+
await startTeammate(team, teammate, participantNames, undefined, { sessionFile, restartEmpty: sessionFile === undefined });
|
|
1520
|
+
if (!sessionFile) emptyRestarts.push(teammate);
|
|
1521
|
+
team.statuses.set(name, status("idle", interrupted.working.includes(name) ? "Reattached; was working when main stopped" : "Reattached"));
|
|
1522
|
+
}
|
|
1523
|
+
persistActiveTeamManifest(team);
|
|
1524
|
+
// A teammate whose conversation was never saved restarts empty, so it gets its briefing back, staged without a turn.
|
|
1525
|
+
await kickoffTeammates(team, emptyRestarts, true, { emptyRestarts });
|
|
1526
|
+
return { ...reattachment, reattached: interrupted.teammates, working: interrupted.working };
|
|
1527
|
+
} catch (error) {
|
|
1528
|
+
if (team) await shutdownTeam(team);
|
|
1529
|
+
closeCallbackServerIfUnused();
|
|
1530
|
+
return { ...reattachment, error: error instanceof Error ? error.message : String(error) };
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
// A main session that starts again reattaches the teammates its quit, reload or crash cut off. A crash leaves the team active under a dead lease.
|
|
1535
|
+
pi.on("session_start", async (event, context) => {
|
|
1536
|
+
const mainSessionId = context.sessionManager?.getSessionId?.();
|
|
1537
|
+
const projectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
|
|
1538
|
+
if (childRuntimeConfig || (event.reason !== "startup" && event.reason !== "reload") || !mainSessionId || !projectDirectory) return;
|
|
1539
|
+
const reattachments: Reattachment[] = [];
|
|
1540
|
+
for (const manifest of listTeamManifests(projectDirectory).manifests) {
|
|
1541
|
+
const lease = manifest.state === "active" ? readTeamLeaseState(manifest.id) : undefined;
|
|
1542
|
+
const crashed = lease?.state === "stale" && lease.mainSessionId === mainSessionId;
|
|
1543
|
+
if (!crashed && manifest.interrupted?.mainSessionId !== mainSessionId) continue;
|
|
1544
|
+
const running = manifest.members.filter((member) => member.live);
|
|
1545
|
+
// A Herdr pane teammate is not main's child, so it can outlive main's crash; a second process on its session would corrupt it.
|
|
1546
|
+
const [inPanes, reattachable] = [running.filter((member) => member.showOnHerdrPane), running.filter((member) => !member.showOnHerdrPane)];
|
|
1547
|
+
const interrupted = crashed
|
|
1548
|
+
? { mainSessionId, teammates: reattachable.map((member) => member.name), working: reattachable.filter((member) => member.active).map((member) => member.name) }
|
|
1549
|
+
: manifest.interrupted;
|
|
1550
|
+
const inPaneNames = crashed ? inPanes.map((member) => member.name) : [];
|
|
1551
|
+
if (interrupted && interrupted.teammates.length > 0) reattachments.push(await reattachTeam(manifest, interrupted, inPaneNames, mainSession(context)!));
|
|
1552
|
+
else if (inPaneNames.length > 0) reattachments.push({ teamName: manifest.name, teamId: manifest.id, reattached: [], working: [], inPanes: inPaneNames });
|
|
1553
|
+
}
|
|
1554
|
+
if (reattachments.length > 0) pi.sendMessage({ customType: reattachedMessageType, content: composeReattachmentMessage(reattachments), display: true }, { deliverAs: "nextTurn" });
|
|
1555
|
+
});
|
|
1556
|
+
|
|
1557
|
+
pi.on("session_start", (_event, context) => {
|
|
1558
|
+
// Pi's RPC session switches emit session_start twice on one instance, so a restore replaces any earlier one.
|
|
1559
|
+
for (const reminder of reminders.values()) clearTimeout(reminder.timer);
|
|
1560
|
+
reminders.clear();
|
|
1561
|
+
const sessionId = context.sessionManager?.getSessionId?.();
|
|
1562
|
+
// A forked session copies its origin's records, which stay that session's reminders.
|
|
1563
|
+
const records = new Map((context.sessionManager?.getEntries?.() ?? [])
|
|
1564
|
+
.flatMap((entry) => entry.type === "custom" && entry.customType === reminderType && (entry.data as ReminderRecord).sessionId === sessionId ? [entry.data as ReminderRecord] : [])
|
|
1565
|
+
.map((record) => [record.id, record]));
|
|
1566
|
+
reminderCount = records.size;
|
|
1567
|
+
for (const record of records.values()) {
|
|
1568
|
+
const reminder: Reminder = { ...record, armedAt: new Date(record.armedAt), wakeAt: new Date(record.wakeAt) };
|
|
1569
|
+
reminders.set(reminder.id, reminder);
|
|
1570
|
+
if (reminder.state === "pending") armReminder(reminder);
|
|
1571
|
+
}
|
|
1572
|
+
});
|
|
1573
|
+
|
|
1373
1574
|
pi.on("session_start", (_event, context) => {
|
|
1374
1575
|
useModelNames(context.modelRegistry);
|
|
1375
1576
|
const scopedModels = (context as typeof context & { scopedModels?: ReadonlyArray<{ model: ModelReference }> }).scopedModels ?? [];
|
|
@@ -1438,6 +1639,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1438
1639
|
showOnHerdrPanes,
|
|
1439
1640
|
teamPrompt: params.commonPrompt,
|
|
1440
1641
|
mainSessionFile,
|
|
1642
|
+
parentSession: mainSession(context),
|
|
1441
1643
|
members: new Map(),
|
|
1442
1644
|
statuses: new Map([["main", status("available", "Main agent")]]),
|
|
1443
1645
|
created: new Date().toISOString(),
|
|
@@ -1498,21 +1700,18 @@ export default function (pi: ExtensionAPI) {
|
|
|
1498
1700
|
delayMinutes: Type.Number({ exclusiveMinimum: 0, maximum: 35_791, description: "Minutes until the reminder" }),
|
|
1499
1701
|
message: Type.String({ minLength: 1, description: "Custom message that wakes you" }),
|
|
1500
1702
|
}, { additionalProperties: false }),
|
|
1501
|
-
async execute(_toolCallId, params) {
|
|
1703
|
+
async execute(_toolCallId, params, _signal, _onUpdate, context) {
|
|
1502
1704
|
const delayMilliseconds = params.delayMinutes * 60_000;
|
|
1503
1705
|
const delaySeconds = Math.round(delayMilliseconds / 1000);
|
|
1504
1706
|
const armedAt = new Date();
|
|
1505
1707
|
const wakeAt = new Date(armedAt.getTime() + delayMilliseconds);
|
|
1506
|
-
const
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
}, delayMilliseconds);
|
|
1514
|
-
reminderTimers.add(timer);
|
|
1515
|
-
timer.unref();
|
|
1708
|
+
const pendingSlugs = new Set([...reminders.values()].filter((reminder) => reminder.state === "pending").map((reminder) => reminder.slug));
|
|
1709
|
+
let slug = reminderSlug();
|
|
1710
|
+
while (pendingSlugs.has(slug)) slug = reminderSlug();
|
|
1711
|
+
const reminder: Reminder = { sessionId: context.sessionManager.getSessionId(), id: `reminder-${++reminderCount}`, slug, message: params.message, armedAt, wakeAt, state: "pending" };
|
|
1712
|
+
reminders.set(reminder.id, reminder);
|
|
1713
|
+
recordReminder(reminder);
|
|
1714
|
+
armReminder(reminder);
|
|
1516
1715
|
return {
|
|
1517
1716
|
content: [{ type: "text" as const, text: `Armed reminder ${slug}: It's ${humanTime(armedAt)} now. Reminder set in ${delaySeconds} seconds (${humanDuration(delaySeconds)}) for ${humanTime(wakeAt)}.` }],
|
|
1518
1717
|
details: { scheduledAt: wakeAt.toISOString(), message: params.message, slug },
|
|
@@ -1521,19 +1720,76 @@ export default function (pi: ExtensionAPI) {
|
|
|
1521
1720
|
}),
|
|
1522
1721
|
);
|
|
1523
1722
|
|
|
1723
|
+
pi.registerTool(
|
|
1724
|
+
defineTool({
|
|
1725
|
+
name: "list_reminders",
|
|
1726
|
+
label: "List Reminders",
|
|
1727
|
+
description: "List your pending reminders in this session: ID, slug, and when each was armed and wakes, in absolute and relative time. Delivered and cancelled reminders are left out.",
|
|
1728
|
+
parameters: Type.Object({}, { additionalProperties: false }),
|
|
1729
|
+
async execute() {
|
|
1730
|
+
const now = Date.now();
|
|
1731
|
+
const pending = [...reminders.values()].filter((reminder) => reminder.state === "pending").sort((first, second) => first.wakeAt.getTime() - second.wakeAt.getTime());
|
|
1732
|
+
return toolResult({
|
|
1733
|
+
now: humanTime(new Date(now)),
|
|
1734
|
+
reminders: pending.map((reminder) => ({
|
|
1735
|
+
id: reminder.id, slug: reminder.slug,
|
|
1736
|
+
armedAt: `${humanTime(reminder.armedAt)} (${humanDuration(Math.round((now - reminder.armedAt.getTime()) / 1000))} ago)`,
|
|
1737
|
+
wakeAt: `${humanTime(reminder.wakeAt)} (in ${humanDuration(Math.max(0, Math.round((reminder.wakeAt.getTime() - now) / 1000)))})`,
|
|
1738
|
+
})),
|
|
1739
|
+
});
|
|
1740
|
+
},
|
|
1741
|
+
}),
|
|
1742
|
+
);
|
|
1743
|
+
|
|
1744
|
+
pi.registerTool(
|
|
1745
|
+
defineTool({
|
|
1746
|
+
name: "cancel_reminders",
|
|
1747
|
+
label: "Cancel Reminders",
|
|
1748
|
+
description: "Cancel your pending reminders in this session, by ID or slug, or all of them with all: true. Each result says cancelled, delivered or unknown; a cancelled one returns its message and wake time, so you can set it again with schedule_reminder.",
|
|
1749
|
+
parameters: Type.Object({
|
|
1750
|
+
reminders: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description: "Reminder IDs or slugs to cancel" })),
|
|
1751
|
+
all: Type.Optional(Type.Boolean({ description: "Cancel every pending reminder. Leaving out reminders without all: true cancels nothing." })),
|
|
1752
|
+
}, { additionalProperties: false }),
|
|
1753
|
+
async execute(_toolCallId, params) {
|
|
1754
|
+
if (params.reminders && params.all) throw new Error("Pass either reminders or all: true to cancel_reminders, not both. Nothing was cancelled.");
|
|
1755
|
+
if (!params.reminders && params.all !== true) throw new Error("Pass the reminder IDs or slugs to cancel, or all: true to cancel every pending reminder. Nothing was cancelled.");
|
|
1756
|
+
const cancel = (reminder: Reminder): JsonRecord => {
|
|
1757
|
+
if (reminder.state === "pending") {
|
|
1758
|
+
clearTimeout(reminder.timer);
|
|
1759
|
+
reminder.state = "cancelled";
|
|
1760
|
+
recordReminder(reminder);
|
|
1761
|
+
}
|
|
1762
|
+
return { id: reminder.id, slug: reminder.slug, result: reminder.state, ...(reminder.state === "cancelled" ? { message: reminder.message, wakeAt: humanTime(reminder.wakeAt) } : {}) };
|
|
1763
|
+
};
|
|
1764
|
+
const results = params.reminders
|
|
1765
|
+
? params.reminders.map((identifier) => {
|
|
1766
|
+
const matches = [...reminders.values()].filter((reminder) => reminder.id === identifier || reminder.slug === identifier);
|
|
1767
|
+
const reminder = matches.find((candidate) => candidate.state === "pending") ?? matches.at(-1);
|
|
1768
|
+
return reminder ? { reminder: identifier, ...cancel(reminder) } : { reminder: identifier, result: "unknown" };
|
|
1769
|
+
})
|
|
1770
|
+
: [...reminders.values()].filter((reminder) => reminder.state === "pending").map(cancel);
|
|
1771
|
+
return toolResult({ results });
|
|
1772
|
+
},
|
|
1773
|
+
}),
|
|
1774
|
+
);
|
|
1775
|
+
|
|
1524
1776
|
pi.registerTool(
|
|
1525
1777
|
defineTool({
|
|
1526
1778
|
name: "team_list",
|
|
1527
|
-
// TODO: Make listing dormant teams opt-in with includeDormantTeams: boolean.
|
|
1528
1779
|
label: "Team List",
|
|
1529
1780
|
description: childRuntimeConfig
|
|
1530
|
-
? "List active
|
|
1531
|
-
: "List active
|
|
1781
|
+
? "List the active teams in the current project that this managing teammate's Pi session created, newest first, as short rows. Pass includeDormantTeams to include dormant teams, or team for one team's full records."
|
|
1782
|
+
: "List the active teams in the current project, newest first, as short rows. Pass includeDormantTeams to include dormant teams, or team for one team's full records.",
|
|
1532
1783
|
renderShell: "self",
|
|
1533
1784
|
renderCall: (_args, theme, context) => renderTeamToolCall("team_list", {}, theme, context, sessionTeammateRoster),
|
|
1534
1785
|
renderResult: (result, options, theme, context) => renderTeamToolResult("team_list", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
1535
|
-
parameters: Type.Object({
|
|
1536
|
-
|
|
1786
|
+
parameters: Type.Object({
|
|
1787
|
+
team: Type.Optional(Type.String({ minLength: 1, description: "Team name or persistent ID. Returns that team's full records, active or dormant, without paging." })),
|
|
1788
|
+
includeDormantTeams: Type.Optional(Type.Boolean({ default: false, description: "Also list dormant teams. Defaults to false: active teams only." })),
|
|
1789
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, description: "Max teams to return, default 20, maximum 100" })),
|
|
1790
|
+
cursor: Type.Optional(Type.String({ description: "nextCursor from the previous team_list result. Keep the same includeDormantTeams when paging." })),
|
|
1791
|
+
}, { additionalProperties: false }),
|
|
1792
|
+
async execute(_toolCallId, params, _signal, _onUpdate, context) {
|
|
1537
1793
|
const projectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
|
|
1538
1794
|
if (!projectDirectory) throw new Error("team_list requires a project directory");
|
|
1539
1795
|
const managerSessionId = childRuntimeConfig ? context.sessionManager?.getSessionId?.() : undefined;
|
|
@@ -1542,25 +1798,29 @@ export default function (pi: ExtensionAPI) {
|
|
|
1542
1798
|
const manifests = listing.manifests.filter(
|
|
1543
1799
|
(manifest) => !managerSessionId || manifest.originMainSessionId === managerSessionId,
|
|
1544
1800
|
);
|
|
1801
|
+
const unreadable = listing.unreadable.length > 0 ? { unreadableManifests: listing.unreadable } : {};
|
|
1802
|
+
if (params.team) {
|
|
1803
|
+
if (params.cursor) throw new Error("Pass either team or cursor to team_list, not both.");
|
|
1804
|
+
const manifest = resolveTeamIdentifier(manifests, params.team);
|
|
1805
|
+
if (!manifest) throw new Error(`Unknown current-project team: ${JSON.stringify(params.team)}. Call team_list with includeDormantTeams: true to see every team.`);
|
|
1806
|
+
return toolResult({ ...unreadable, teams: [fullTeamListRow(manifest)] });
|
|
1807
|
+
}
|
|
1808
|
+
const includeDormantTeams = Boolean(params.includeDormantTeams);
|
|
1809
|
+
const after = params.cursor === undefined ? undefined : decodeTeamListCursor(params.cursor);
|
|
1810
|
+
if (after && after.includeDormantTeams !== includeDormantTeams) throw new Error("Keep the same includeDormantTeams when paging team_list with cursor.");
|
|
1811
|
+
const listed = manifests
|
|
1812
|
+
.filter((manifest) => includeDormantTeams || manifest.state === "active")
|
|
1813
|
+
.sort(newestCreatedFirst)
|
|
1814
|
+
.filter((manifest) => !after || newestCreatedFirst(manifest, after) > 0);
|
|
1815
|
+
const page = listed.slice(0, params.limit ?? defaultTeamListLimit);
|
|
1816
|
+
const last = page.at(-1);
|
|
1817
|
+
const hiddenDormantTeams = includeDormantTeams ? 0 : manifests.filter((manifest) => manifest.state === "dormant").length;
|
|
1545
1818
|
return toolResult({
|
|
1546
|
-
...
|
|
1547
|
-
teams:
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
state: manifest.state,
|
|
1552
|
-
leaseState: readTeamLeaseState(manifest.id).state,
|
|
1553
|
-
teammates: manifest.members.map(({ sessionMaterialized, ...member }) => {
|
|
1554
|
-
const runtime = liveTeam?.members.get(member.name);
|
|
1555
|
-
return runtime ? teammateRecord(runtime) : member;
|
|
1556
|
-
}),
|
|
1557
|
-
createdAt: manifest.createdAt,
|
|
1558
|
-
updatedAt: manifest.updatedAt,
|
|
1559
|
-
shutdownAt: manifest.shutdownAt,
|
|
1560
|
-
expiresAt: manifest.expiresAt,
|
|
1561
|
-
};
|
|
1562
|
-
}),
|
|
1563
|
-
});
|
|
1819
|
+
...unreadable,
|
|
1820
|
+
teams: page.map(compactTeamListRow),
|
|
1821
|
+
...(listed.length > page.length && last ? { nextCursor: encodeTeamListCursor({ createdAt: last.createdAt, id: last.id, includeDormantTeams }) } : {}),
|
|
1822
|
+
...(hiddenDormantTeams > 0 ? { dormantTeamsHidden: hiddenDormantTeams, instruction: "Pass includeDormantTeams: true to list dormant teams too." } : {}),
|
|
1823
|
+
}, { teams: page.map(fullTeamListRow) });
|
|
1564
1824
|
},
|
|
1565
1825
|
}),
|
|
1566
1826
|
);
|
|
@@ -1587,7 +1847,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1587
1847
|
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
1588
1848
|
signal?.throwIfAborted();
|
|
1589
1849
|
const manifest = resolveTeamIdentifier(resumableTeamManifests(context, "team_resume"), params.team);
|
|
1590
|
-
if (!manifest) throw new Error(`Unknown current-project team: ${JSON.stringify(params.team)}. Call team_list and pass a listed teamId or unique teamName in the team parameter.`);
|
|
1850
|
+
if (!manifest) throw new Error(`Unknown current-project team: ${JSON.stringify(params.team)}. Call team_list with includeDormantTeams: true and pass a listed teamId or unique teamName in the team parameter.`);
|
|
1591
1851
|
const members = manifest.members;
|
|
1592
1852
|
const requestedNames = resolveTeammates(members, params.teammates ?? members.map((member) => member.teammateId)).map((member) => member.name);
|
|
1593
1853
|
const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
|
|
@@ -1611,6 +1871,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1611
1871
|
try {
|
|
1612
1872
|
await ensureCallbackServer();
|
|
1613
1873
|
team = restoreTeamState(owner, pi, parentPiCommand, manifest, lease);
|
|
1874
|
+
team.parentSession = mainSession(context);
|
|
1614
1875
|
teams.set(team.id!, team);
|
|
1615
1876
|
} catch (error) {
|
|
1616
1877
|
releaseTeamLease(lease);
|
|
@@ -1829,6 +2090,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1829
2090
|
const selections = resolveTargets(candidates, params.targets);
|
|
1830
2091
|
const interrupted = interruptedTeammateIds(candidates, selections, params.interrupt);
|
|
1831
2092
|
const statuses: JsonRecord[] = [];
|
|
2093
|
+
const recipients: Array<{ name: string; contextPercent?: number }> = [];
|
|
1832
2094
|
for (const selection of selections) {
|
|
1833
2095
|
if (selection.team === parent) {
|
|
1834
2096
|
const result = await callParent(childRuntimeConfig!, "team_send_message", {
|
|
@@ -1836,13 +2098,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
1836
2098
|
interrupt: selection.teammates.filter((teammate) => interrupted.has(teammate.teammateId)).map((teammate) => teammate.teammateId),
|
|
1837
2099
|
}, signal);
|
|
1838
2100
|
statuses.push(...result.teams as JsonRecord[]);
|
|
2101
|
+
recipients.push(...selection.teammates.map((teammate) => ({ name: teammate.name })));
|
|
1839
2102
|
continue;
|
|
1840
2103
|
}
|
|
1841
2104
|
const team = teams.get(selection.team.teamId)!;
|
|
1842
2105
|
for (const recipient of selection.teammates) enqueueDelivery(team, "main", team.members.get(recipient.name)!, params.message, interrupted.has(recipient.teammateId));
|
|
1843
2106
|
statuses.push({ ...teamIdentity(team), status: formatStatus(team) });
|
|
2107
|
+
recipients.push(...selection.teammates.map((recipient) => agentContext(team.members.get(recipient.name)!)));
|
|
1844
2108
|
}
|
|
1845
|
-
return toolResult({ published: true, teams: statuses, instruction: "Do not wait for replies. Teammates will message you back." });
|
|
2109
|
+
return toolResult({ published: true, teams: statuses, instruction: "Do not wait for replies. Teammates will message you back." }, { agentContext: recipients });
|
|
1846
2110
|
},
|
|
1847
2111
|
}),
|
|
1848
2112
|
);
|
|
@@ -1987,6 +2251,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1987
2251
|
async execute(_toolCallId, params) {
|
|
1988
2252
|
const team = resolveTeam(owner, params.team);
|
|
1989
2253
|
const teammates = [...team.members.values()].map(teammateReference);
|
|
2254
|
+
const stoppedContext = [...team.members.values()].map(agentContext);
|
|
1990
2255
|
const droppedUpdates = [...team.members.values()].flatMap((teammate) => {
|
|
1991
2256
|
const heldUpdate = teammate.processRecord?.heldUpdate;
|
|
1992
2257
|
return heldUpdate ? [{ ...teammateReference(teammate), settings: describeSettings(heldUpdate) }] : [];
|
|
@@ -1997,7 +2262,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1997
2262
|
return toolResult({
|
|
1998
2263
|
...teamIdentity(team), stopped: true, teammates,
|
|
1999
2264
|
...(droppedUpdates.length > 0 ? { droppedUpdates, instruction: "These held settings updates were not applied. Pass them in teammateUpdates when you resume the team." } : {}),
|
|
2000
|
-
});
|
|
2265
|
+
}, { agentContext: stoppedContext });
|
|
2001
2266
|
},
|
|
2002
2267
|
}),
|
|
2003
2268
|
);
|
package/package.json
CHANGED
package/render.ts
CHANGED
|
@@ -33,6 +33,12 @@ export interface TeamStatusView {
|
|
|
33
33
|
updated: string;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
/** An agent a tool involves, with the context use it last reported when the result carries it. */
|
|
37
|
+
export interface AgentContextView {
|
|
38
|
+
name: string;
|
|
39
|
+
contextPercent?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
36
42
|
export interface TeamMessageDetails {
|
|
37
43
|
team: string;
|
|
38
44
|
from: string;
|
|
@@ -316,7 +322,7 @@ export interface TeamListTeamView {
|
|
|
316
322
|
function teamListMemberName(theme: ThemeLike, teamView: TeamListTeamView, member: TeamListMemberView, roster: string[]): string {
|
|
317
323
|
const hued = theme.fg(actorHueToken(member.name, roster), member.name);
|
|
318
324
|
const name = teamView.state === "active" && !member.live ? `${DIM_SGR_OPEN}${hued}${DIM_SGR_CLOSE}` : hued;
|
|
319
|
-
return [name, inlineFact(theme, "manager", member)].filter((part) => part.length > 0).join(" ");
|
|
325
|
+
return [name, inlineFact(theme, "context", member), inlineFact(theme, "manager", member)].filter((part) => part.length > 0).join(" ");
|
|
320
326
|
}
|
|
321
327
|
|
|
322
328
|
function teamListTimestamp(teamView: TeamListTeamView): string {
|
|
@@ -367,8 +373,18 @@ function actorList(theme: ThemeLike, names: string[], roster: string[], separato
|
|
|
367
373
|
return names.map((name) => theme.fg(actorHueToken(name, roster), name)).join(theme.fg("muted", separator));
|
|
368
374
|
}
|
|
369
375
|
|
|
370
|
-
|
|
371
|
-
|
|
376
|
+
/** An agent's name in its roster hue, followed by its context reading in the teammate rows' full form when known. */
|
|
377
|
+
function agentWithContext(theme: ThemeLike, agent: AgentContextView, roster: string[]): string {
|
|
378
|
+
return [theme.fg(actorHueToken(agent.name, roster), agent.name), inlineFact(theme, "context", agent, "full")].filter((part) => part.length > 0).join(" ");
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function agentsWithContext(theme: ThemeLike, agents: AgentContextView[], roster: string[], separator: string): string {
|
|
382
|
+
return agents.map((agent) => agentWithContext(theme, agent, roster)).join(theme.fg("muted", separator));
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** The pending call names the targets as given. A result names each recipient with its context use, which comes before the character count. */
|
|
386
|
+
function sendTarget(theme: ThemeLike, to: string[], roster: string[] = [], agentContext?: AgentContextView[]): string {
|
|
387
|
+
const recipients = agentContext ? agentsWithContext(theme, agentContext, roster, ", ") : actorList(theme, to, roster, ", ");
|
|
372
388
|
return `${theme.fg("muted", `${glyphs().arrow} `)}${recipients}`;
|
|
373
389
|
}
|
|
374
390
|
|
|
@@ -381,20 +397,20 @@ function hasInterruption(interrupt: unknown): boolean {
|
|
|
381
397
|
return interrupt === true || (Array.isArray(interrupt) && interrupt.length > 0);
|
|
382
398
|
}
|
|
383
399
|
|
|
384
|
-
function teamSendHeader(theme: ThemeLike, targets: string[], message: string, interrupt: boolean, roster: string[]): string {
|
|
385
|
-
return headerLine(theme, "Team Send", sendTarget(theme, targets, roster), sendStats(theme, message, interrupt));
|
|
400
|
+
function teamSendHeader(theme: ThemeLike, targets: string[], message: string, interrupt: boolean, roster: string[], agentContext?: AgentContextView[]): string {
|
|
401
|
+
return headerLine(theme, "Team Send", sendTarget(theme, targets, roster, agentContext), sendStats(theme, message, interrupt));
|
|
386
402
|
}
|
|
387
403
|
|
|
388
|
-
export function teamSendLines(theme: ThemeLike, options: { targets: string[]; message: string; interrupt: boolean; expanded: boolean }, roster: string[] = []): TeamLine[] {
|
|
389
|
-
const header = teamSendHeader(theme, options.targets, options.message, options.interrupt, roster);
|
|
404
|
+
export function teamSendLines(theme: ThemeLike, options: { targets: string[]; agentContext?: AgentContextView[]; message: string; interrupt: boolean; expanded: boolean }, roster: string[] = []): TeamLine[] {
|
|
405
|
+
const header = teamSendHeader(theme, options.targets, options.message, options.interrupt, roster, options.agentContext);
|
|
390
406
|
const lineLimit = options.expanded ? Number.POSITIVE_INFINITY : SEND_PREVIEW_LINES;
|
|
391
407
|
return [header, ...quotedBody(theme, options.message, { lineLimit, barToken: "muted" })];
|
|
392
408
|
}
|
|
393
409
|
|
|
394
|
-
export function teamShutdownLines(theme: ThemeLike, team: string, teammates:
|
|
410
|
+
export function teamShutdownLines(theme: ThemeLike, team: string, teammates: AgentContextView[], roster: string[] = []): string[] {
|
|
395
411
|
const header = headerLine(theme, "Team Shutdown", theme.fg("accent", team), [theme.fg("muted", `${plural(teammates.length, "teammate")} stopped`)]);
|
|
396
412
|
if (teammates.length === 0) return [header];
|
|
397
|
-
return [header, `${treeConnector(theme, "└")}${
|
|
413
|
+
return [header, `${treeConnector(theme, "└")}${agentsWithContext(theme, teammates, roster, glyphs().dot)}`];
|
|
398
414
|
}
|
|
399
415
|
|
|
400
416
|
function reminderCallBody(theme: ThemeLike, args: Record<string, unknown>): string {
|
|
@@ -829,6 +845,7 @@ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<strin
|
|
|
829
845
|
if (tool === "team_send_message") {
|
|
830
846
|
return teamSendLines(theme, {
|
|
831
847
|
targets: (args.targets ?? []) as string[],
|
|
848
|
+
agentContext: details.agentContext as AgentContextView[] | undefined,
|
|
832
849
|
message: String(args.message ?? ""),
|
|
833
850
|
interrupt: hasInterruption(args.interrupt),
|
|
834
851
|
expanded,
|
|
@@ -850,7 +867,7 @@ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<strin
|
|
|
850
867
|
if (details.nextCursor) lines.push(theme.fg("muted", ` Older events: cursor "${details.nextCursor}"`));
|
|
851
868
|
return lines;
|
|
852
869
|
}
|
|
853
|
-
return teamShutdownLines(theme, String(details.teamName), (details.
|
|
870
|
+
return teamShutdownLines(theme, String(details.teamName), (details.agentContext ?? details.teammates) as AgentContextView[], roster);
|
|
854
871
|
}
|
|
855
872
|
|
|
856
873
|
export function renderTeamToolCall(tool: TeamToolName, args: Record<string, unknown>, theme: ThemeLike, context: ToolRenderContextLike, roster: string[] = []) {
|
|
@@ -873,7 +890,7 @@ export function renderTeamToolResult(
|
|
|
873
890
|
const details = (result?.details ?? {}) as Record<string, unknown>;
|
|
874
891
|
if (markdownTheme && tool === "team_send_message") {
|
|
875
892
|
const message = String(args.message ?? "");
|
|
876
|
-
const header = teamSendHeader(theme, (args.targets ?? []) as string[], message, hasInterruption(args.interrupt), roster);
|
|
893
|
+
const header = teamSendHeader(theme, (args.targets ?? []) as string[], message, hasInterruption(args.interrupt), roster, details.agentContext as AgentContextView[] | undefined);
|
|
877
894
|
const bar = ` ${theme.fg("muted", glyphs().codeBar)} `;
|
|
878
895
|
return new QuotedMarkdownView(header, message, bar, markdownTheme, options.expanded, theme);
|
|
879
896
|
}
|
package/resume-message.ts
CHANGED
|
@@ -37,3 +37,33 @@ export function composeSettingsMessage(settings: string, stoppedTeams: ReadonlyA
|
|
|
37
37
|
stoppedTeams.length > 0 && `Your restart stopped the teams you manage: ${stopped}. Their teammates were idle, and their conversations are kept. Resume them with team_resume when you continue.`,
|
|
38
38
|
].filter(Boolean).join("\n\n");
|
|
39
39
|
}
|
|
40
|
+
|
|
41
|
+
/** What main's start did with one of its teams that its last stop interrupted. */
|
|
42
|
+
export interface Reattachment {
|
|
43
|
+
teamName: string;
|
|
44
|
+
teamId: string;
|
|
45
|
+
reattached: string[];
|
|
46
|
+
working: string[];
|
|
47
|
+
inPanes: string[];
|
|
48
|
+
error?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Tell main, in one message, which teammates its start reattached, which of them were working, and which it left alone.
|
|
53
|
+
* @example composeReattachmentMessage([{ teamName: "r", teamId: "m-r", reattached: ["a"], working: [], inPanes: [] }]).endsWith('Team "r" (team ID: m-r): a.') // true
|
|
54
|
+
*/
|
|
55
|
+
export function composeReattachmentMessage(reattachments: readonly Reattachment[]): string {
|
|
56
|
+
const listed = (pick: (reattachment: Reattachment) => string[]) => reattachments.flatMap((reattachment) => pick(reattachment).map((name) => `${name} (team "${reattachment.teamName}")`)).join(", ");
|
|
57
|
+
const reattached = reattachments.filter((reattachment) => reattachment.reattached.length > 0);
|
|
58
|
+
const working = listed((reattachment) => reattachment.working);
|
|
59
|
+
const inPanes = listed((reattachment) => reattachment.inPanes);
|
|
60
|
+
return [
|
|
61
|
+
reattached.length > 0 && [
|
|
62
|
+
"Simple Team reattached the teammates that were running when your session last stopped. They resumed idle, and nothing was sent to them.",
|
|
63
|
+
...reattached.map((reattachment) => `Team "${reattachment.teamName}" (team ID: ${reattachment.teamId}): ${reattachment.reattached.join(", ")}.`),
|
|
64
|
+
].join("\n"),
|
|
65
|
+
working && `These were working when your session stopped: ${working}. Message each one to continue.`,
|
|
66
|
+
inPanes && `Not reattached, because a Herdr pane teammate may still be running in its pane: ${inPanes}. Check its pane before you use team_resume.`,
|
|
67
|
+
...reattachments.filter((reattachment) => reattachment.error).map((reattachment) => `Could not reattach team "${reattachment.teamName}" (team ID: ${reattachment.teamId}): ${reattachment.error} Use team_resume to restart it.`),
|
|
68
|
+
].filter(Boolean).join("\n\n");
|
|
69
|
+
}
|
package/team-registry.ts
CHANGED
|
@@ -23,6 +23,8 @@ export interface TeamManifest {
|
|
|
23
23
|
updatedAt: string;
|
|
24
24
|
shutdownAt?: string;
|
|
25
25
|
expiresAt?: string;
|
|
26
|
+
/** The main session that was running this team when its quit or reload stopped it, and the teammates then running and working. That main's next start reattaches them. */
|
|
27
|
+
interrupted?: { mainSessionId: string; teammates: string[]; working: string[] };
|
|
26
28
|
}
|
|
27
29
|
|
|
28
30
|
export interface TeamLease {
|
|
@@ -82,6 +84,11 @@ function isManifestMember(value: unknown): value is TeamManifestMember {
|
|
|
82
84
|
);
|
|
83
85
|
}
|
|
84
86
|
|
|
87
|
+
function isInterruption(value: unknown): value is TeamManifest["interrupted"] {
|
|
88
|
+
const names = (list: unknown) => Array.isArray(list) && list.every((name) => typeof name === "string");
|
|
89
|
+
return typeof value === "object" && value !== null && typeof (value as Record<string, unknown>).mainSessionId === "string" && names((value as Record<string, unknown>).teammates) && names((value as Record<string, unknown>).working);
|
|
90
|
+
}
|
|
91
|
+
|
|
85
92
|
function parseManifest(filePath: string): TeamManifest {
|
|
86
93
|
const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
87
94
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
@@ -104,7 +111,8 @@ function parseManifest(filePath: string): TeamManifest {
|
|
|
104
111
|
typeof manifest.createdAt !== "string" ||
|
|
105
112
|
typeof manifest.updatedAt !== "string" ||
|
|
106
113
|
(manifest.shutdownAt !== undefined && typeof manifest.shutdownAt !== "string") ||
|
|
107
|
-
(manifest.expiresAt !== undefined && typeof manifest.expiresAt !== "string")
|
|
114
|
+
(manifest.expiresAt !== undefined && typeof manifest.expiresAt !== "string") ||
|
|
115
|
+
(manifest.interrupted !== undefined && !isInterruption(manifest.interrupted))
|
|
108
116
|
) {
|
|
109
117
|
throw new Error(`Invalid team manifest: ${filePath}`);
|
|
110
118
|
}
|
package/team-selection.ts
CHANGED
|
@@ -64,7 +64,7 @@ export function unknownTargetMessage(identifier: string, teams: readonly Selecta
|
|
|
64
64
|
"Resume the intended teammate with team_resume, then retry team_send_message.",
|
|
65
65
|
].join("\n");
|
|
66
66
|
const choices = targetCandidates(teams).map(({ name, id }) => ({ name, id }));
|
|
67
|
-
return `Unknown target ${name}. Available choices: ${JSON.stringify(choices)}. No active target matches. Use team_list to find active
|
|
67
|
+
return `Unknown target ${name}. Available choices: ${JSON.stringify(choices)}. No active target matches. Use team_list to find active teams, with includeDormantTeams: true for dormant teams; resume the intended teammate before retrying.`;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
/** @example resolveTargets([{ teamName: "review", teamId: "team-1", teammates: [{ name: "scout", teammateId: "session-1" }] }], ["review", "session-1"])[0].teammates.length // 1 */
|
package/teammate-facts.ts
CHANGED
|
@@ -27,7 +27,7 @@ export interface FactRow extends TeammateView {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
export type FactKey = "name" | "status" | "model" | "context" | "fork" | "manager" | "thinking" | "herdr";
|
|
30
|
-
type Form = "full" | "short" | "bare" | "icon";
|
|
30
|
+
export type Form = "full" | "short" | "bare" | "icon";
|
|
31
31
|
type FormOrHidden = Form | "hidden";
|
|
32
32
|
|
|
33
33
|
interface Paint {
|
|
@@ -151,9 +151,9 @@ function cell(key: FactKey, form: FormOrHidden, row: FactRow, paint: Paint): str
|
|
|
151
151
|
return ladder[shown]!(row, paint);
|
|
152
152
|
}
|
|
153
153
|
|
|
154
|
-
/** One fact in its icon form, for views that list teammates inline. Empty when the row lacks the fact. */
|
|
155
|
-
export function inlineFact(theme: FactTheme, key: FactKey, row: FactRow): string {
|
|
156
|
-
return cell(key,
|
|
154
|
+
/** One fact, in its icon form unless another is given, for views that list teammates inline. Empty when the row lacks the fact. */
|
|
155
|
+
export function inlineFact(theme: FactTheme, key: FactKey, row: FactRow, form: Form = "icon"): string {
|
|
156
|
+
return cell(key, form, row, { theme, roster: [], nameWidth: 0 });
|
|
157
157
|
}
|
|
158
158
|
|
|
159
159
|
/** The cells of every row at one state, padded into aligned columns. Empty columns drop out. */
|