@giladbarnea/pi-simple-team 2.0.22 → 2.0.24

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 CHANGED
@@ -217,11 +217,11 @@ Kept minimal:
217
217
 
218
218
  | Role | For | Tools |
219
219
  | --- | --- | --- |
220
- | **Main agent** | Team lifecycle | `team_spawn`, `team_list`, `team_resume`, `team_add_teammates`, `team_shutdown` |
220
+ | **Main agent** | Team lifecycle | `team_spawn`, `team_list`, `team_resume`, `team_add_teammates`, `team_update_teammates`, `team_shutdown` |
221
221
  | | With team | `team_send_message` |
222
222
  | | On team | `team_status`, `team_log` |
223
223
  | | On everyone | `get_context_window_usage` |
224
- | | On self | `schedule_reminder` |
224
+ | | On self | `schedule_reminder`, `list_reminders`, `cancel_reminders` |
225
225
  | **Managing teammate** | On self and own teams | Same tools as the main agent |
226
226
  | | With parent team | `team_send_message`, `team_status`, `send_main_message` |
227
227
  | **Teammates** | With team | `team_send_message` |
@@ -237,6 +237,12 @@ Resume appends a custom briefing with the team identity, current time, and last
237
237
 
238
238
  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
239
 
240
+ `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
+
242
+ `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.
243
+
244
+ `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.
245
+
240
246
  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.
241
247
 
242
248
  Set `showOnHerdrPane: true` on individual teammates to open their panes. An explicit `showOnHerdrPanes` value on spawn overrides all individual settings.
package/index.ts CHANGED
@@ -6,12 +6,12 @@ import http from "node:http";
6
6
  import * as net from "node:net";
7
7
  import * as path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
- import { defineTool, type ContextUsage, type ExtensionAPI, type ExtensionContext, getMarkdownTheme, getPackageDir } from "@earendil-works/pi-coding-agent";
9
+ import { defineTool, type ContextUsage, type ExtensionAPI, type ExtensionContext, getMarkdownTheme, getPackageDir, SessionManager } from "@earendil-works/pi-coding-agent";
10
10
  import { formatContextWindowReport, requireKnownContextUsage, type KnownContextUsage } from "./context-window.ts";
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 } from "./resume-message.ts";
14
+ import { composeResumptionMessage, composeSettingsMessage } from "./resume-message.ts";
15
15
  import { callParent, isInertTeamCopy, readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
16
16
  import {
17
17
  canonicalProjectDirectory,
@@ -32,7 +32,7 @@ import { openTeamOverview, type TeamSnapshot } from "./team-ui.ts";
32
32
  import { StringEnum } from "@earendil-works/pi-ai";
33
33
  import { Type } from "typebox";
34
34
  import { resolveTargets, resolveTeammates, interruptedTeammateIds, findUnknownTarget, unknownTargetMessage, targetDescription, interruptDescription, type DormantTeammateMatch, type SelectableTeam } from "./team-selection.ts";
35
- import type { Teammate, TeammateRecord, ThinkingLevel } from "./teammate.ts";
35
+ import type { Teammate, TeammateRecord, TeammateUpdate, ThinkingLevel } from "./teammate.ts";
36
36
 
37
37
  type JsonRecord = Record<string, unknown>;
38
38
 
@@ -63,6 +63,8 @@ interface ProcessRecord {
63
63
  /** Set once main has recorded this process's end, so a callback still in flight when it died changes nothing. */
64
64
  ended?: boolean;
65
65
  lifeline?: net.Socket;
66
+ /** Settings main changed while this process was busy. They apply when it settles, and end with it. */
67
+ heldUpdate?: TeammateUpdate;
66
68
  }
67
69
 
68
70
  interface TeammateState {
@@ -147,6 +149,46 @@ function toolResult(payload: JsonRecord, viewDetails: JsonRecord = {}) {
147
149
  };
148
150
  }
149
151
 
152
+ const defaultTeamListLimit = 20;
153
+
154
+ /** 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. */
155
+ interface TeamListCursor {
156
+ createdAt: string;
157
+ id: string;
158
+ includeDormantTeams: boolean;
159
+ }
160
+
161
+ /** @example newestCreatedFirst({ createdAt: "2026-01-02", id: "b" }, { createdAt: "2026-01-01", id: "a" }) < 0 // true */
162
+ function newestCreatedFirst(first: { createdAt: string; id: string }, second: { createdAt: string; id: string }): number {
163
+ return second.createdAt.localeCompare(first.createdAt) || second.id.localeCompare(first.id);
164
+ }
165
+
166
+ /** @example decodeTeamListCursor(encodeTeamListCursor({ createdAt: "t", id: "a", includeDormantTeams: false })).id // "a" */
167
+ function encodeTeamListCursor(cursor: TeamListCursor): string {
168
+ return Buffer.from(JSON.stringify(cursor)).toString("base64url");
169
+ }
170
+
171
+ function decodeTeamListCursor(cursor: string): TeamListCursor {
172
+ let decoded: Partial<TeamListCursor>;
173
+ try {
174
+ decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")) as Partial<TeamListCursor>;
175
+ } catch {
176
+ decoded = {};
177
+ }
178
+ 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.");
179
+ return decoded as TeamListCursor;
180
+ }
181
+
182
+ interface Reminder {
183
+ id: string;
184
+ slug: string;
185
+ message: string;
186
+ armedAt: Date;
187
+ wakeAt: Date;
188
+ timer: ReturnType<typeof setTimeout>;
189
+ state: "pending" | "delivered" | "cancelled";
190
+ }
191
+
150
192
  const reminderSlugWords = {
151
193
  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"],
152
194
  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"],
@@ -227,6 +269,33 @@ function lifecycleInstruction(startIdle: boolean): string {
227
269
  return nextAction;
228
270
  }
229
271
 
272
+ /** A listed team's full records: the saved definitions, with live runtime values for a team this process runs. */
273
+ function fullTeamListRow(manifest: TeamManifest): JsonRecord {
274
+ const liveTeam = teams.get(manifest.id);
275
+ return {
276
+ ...teamIdentity(manifest),
277
+ state: manifest.state,
278
+ leaseState: readTeamLeaseState(manifest.id).state,
279
+ teammates: manifest.members.map(({ sessionMaterialized, ...member }) => {
280
+ const runtime = liveTeam?.members.get(member.name);
281
+ return runtime ? teammateRecord(runtime) : member;
282
+ }),
283
+ createdAt: manifest.createdAt,
284
+ updatedAt: manifest.updatedAt,
285
+ shutdownAt: manifest.shutdownAt,
286
+ expiresAt: manifest.expiresAt,
287
+ };
288
+ }
289
+
290
+ /** 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. */
291
+ function compactTeamListRow(manifest: TeamManifest): JsonRecord {
292
+ const full = fullTeamListRow(manifest);
293
+ return {
294
+ teamName: full.teamName, teamId: full.teamId, state: full.state,
295
+ teammates: (full.teammates as TeammateRecord[]).map(({ name, teammateId, model, live, active }) => ({ name, teammateId, model, live, active })),
296
+ };
297
+ }
298
+
230
299
  /** @example lifecycleResult(emptyTeam).started // false */
231
300
  function lifecycleResult(team: TeamState): JsonRecord {
232
301
  const teammates = [...team.members.values()].map(teammateRecord);
@@ -397,9 +466,11 @@ function isUnexpectedExit(record: ProcessRecord, code: number | null, signal: No
397
466
  * Waits for main's own shutdown to mark the team first, so a signal that reaches main and its teammates together sends nothing.
398
467
  */
399
468
  function scheduleEndNotice(team: TeamState, teammate: TeammateState, happened: string, cause: string, advice: string): void {
469
+ const heldUpdate = teammate.processRecord?.heldUpdate;
470
+ const droppedUpdate = heldUpdate ? `\nIts held settings update (${describeSettings(heldUpdate)}) was not applied. Pass it in teammateUpdates when you resume it.` : "";
400
471
  setTimeout(() => {
401
472
  if (team.stopping || teams.get(team.id ?? team.name) !== team) return;
402
- notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) ${happened}.\nCause: ${cause}\n${advice}`);
473
+ notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) ${happened}.\nCause: ${cause}\n${advice}${droppedUpdate}`);
403
474
  }, exitNoticeGraceMilliseconds).unref();
404
475
  }
405
476
 
@@ -437,12 +508,13 @@ function recordQuit(team: TeamState, teammate: TeammateState, signal: unknown):
437
508
  scheduleEndNotice(team, teammate, `shut down${afterSignal}`, `its Pi received ${signal} and shut down in order. ${signalReasons[signal as ShutdownSignal]}`, "Use team_resume to restart it if you still need it.");
438
509
  }
439
510
 
440
- async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[] }): Promise<void> {
511
+ async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[]; settings?: ReadonlyMap<string, TeammateUpdate> }): Promise<void> {
441
512
  const outcomes = await Promise.allSettled(teammates.map((teammate) => {
442
513
  const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
443
514
  const message = [
444
515
  initialize && composeTeamBriefing(team.name, team.teamPrompt, teammate.name, teammate.prompt, [...team.members.keys()], teammate.canManageOwnTeams),
445
516
  resumption && composeResumptionMessage(team.name, teammate.name, teammate.lastModelActivityAt, resumption.instructions),
517
+ resumption?.settings?.has(teammate.name) && composeSettingsMessage(describeSettings(resumption.settings.get(teammate.name)!), []),
446
518
  ].filter(Boolean).join("\n\n");
447
519
  return queueDelivery(team, "main", teammate, message, false, !startIdle);
448
520
  }));
@@ -480,7 +552,7 @@ function resolveTeam(owner: symbol, teamIdentifier?: string): TeamState {
480
552
  const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
481
553
  if (teamIdentifier) {
482
554
  const team = resolveTeamIdentifier(ownedTeams, teamIdentifier);
483
- 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.`);
555
+ 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.`);
484
556
  return team;
485
557
  }
486
558
 
@@ -568,13 +640,17 @@ function logStatusDeclaration(team: TeamState, participant: string, word?: strin
568
640
  });
569
641
  }
570
642
 
643
+ function validateExtensionPaths(extensionPaths: readonly string[]): void {
644
+ for (const extensionPath of extensionPaths) {
645
+ if (!path.isAbsolute(extensionPath) || !fs.existsSync(extensionPath)) throw new Error(`Teammate extension must be an existing absolute path: ${extensionPath}`);
646
+ }
647
+ }
648
+
571
649
  function createTeammateState(teammateSpec: Teammate): TeammateState {
572
650
  const teammateName = compactName(teammateSpec.name);
573
651
  const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
574
652
  const extensionPaths = teammateSpec.extensionPaths ?? [];
575
- for (const extensionPath of extensionPaths) {
576
- if (!path.isAbsolute(extensionPath) || !fs.existsSync(extensionPath)) throw new Error(`Teammate extension must be an existing absolute path: ${extensionPath}`);
577
- }
653
+ validateExtensionPaths(extensionPaths);
578
654
  let resolveReady: (() => void) | undefined;
579
655
  let rejectReady: ((error: Error) => void) | undefined;
580
656
  const ready = new Promise<void>((resolve, reject) => {
@@ -632,6 +708,8 @@ interface ChildStartOptions {
632
708
  sessionFile?: string;
633
709
  restartEmpty?: boolean;
634
710
  signal?: AbortSignal;
711
+ /** New settings, recorded once the previous process has ended and before the next one starts. */
712
+ settings?: TeammateUpdate;
635
713
  }
636
714
 
637
715
  /**
@@ -685,6 +763,112 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
685
763
  appendSpawnLog(team, teammate);
686
764
  }
687
765
 
766
+ /**
767
+ * Resolves and validates main's settings changes, keyed by teammate name, before anything restarts.
768
+ * @example resolveTeammateUpdates([{ name: "x", teammateId: "s-1" }], [{ teammate: "s-1", thinking: "high" }], []).get("x")?.thinking // "high"
769
+ */
770
+ function resolveTeammateUpdates(members: readonly { name: string; teammateId: string }[], updates: readonly TeammateUpdate[], availableModels: readonly ModelReference[]): Map<string, TeammateUpdate> {
771
+ const resolved = new Map<string, TeammateUpdate>();
772
+ for (const update of updates) {
773
+ const [member] = resolveTeammates(members, [update.teammate]);
774
+ if (resolved.has(member.name)) throw new Error(`Duplicate settings for teammate "${member.name}". Combine them into one item.`);
775
+ if (update.model === undefined && update.thinking === undefined && update.extensionPaths === undefined) throw new Error(`Teammate "${member.name}" has no settings to change. Set model, thinking or extensionPaths.`);
776
+ validateExtensionPaths(update.extensionPaths ?? []);
777
+ resolved.set(member.name, update);
778
+ }
779
+ validateTeammateModels([...resolved].flatMap(([name, update]) => update.model === undefined ? [] : [{ name, model: update.model }]), availableModels);
780
+ return resolved;
781
+ }
782
+
783
+ /**
784
+ * Records new settings for a stopped teammate: in its session, as Pi records a model or thinking switch, so the next start restores them, and in its saved definition.
785
+ * Without a saved session there is nothing to record; the next start is a new session that receives the settings as launch arguments.
786
+ */
787
+ function applyTeammateSettings(teammate: TeammateState, update: TeammateUpdate, sessionFile: string | undefined): void {
788
+ if (sessionFile) {
789
+ const session = SessionManager.open(sessionFile);
790
+ const current = session.buildSessionContext();
791
+ const slash = update.model?.indexOf("/") ?? -1;
792
+ if (update.model && update.model !== `${current.model?.provider}/${current.model?.modelId}`) session.appendModelChange(update.model.slice(0, slash), update.model.slice(slash + 1));
793
+ if (update.thinking && update.thinking !== current.thinkingLevel) session.appendThinkingLevelChange(update.thinking);
794
+ }
795
+ teammate.model = update.model ?? teammate.model;
796
+ teammate.thinking = update.thinking ?? teammate.thinking;
797
+ teammate.extensionPaths = update.extensionPaths ?? teammate.extensionPaths;
798
+ }
799
+
800
+ /**
801
+ * Restarts a live teammate on its own session with new settings, through the start path that ends its previous process or pane first.
802
+ * It runs after the deliveries already queued for the teammate, and later deliveries reach the restarted runtime. The teammate keeps its status, including a failed run's error.
803
+ * A teammate without a saved session restarts empty and gets its briefing staged again, as team_resume does.
804
+ */
805
+ function restartWithSettings(team: TeamState, teammate: TeammateState, update: TeammateUpdate): Promise<void> {
806
+ const restart = teammate.deliveryQueue.then(async () => {
807
+ const herdrParentPaneId = teammate.transport === "herdr" ? await validateHerdrAvailability() : undefined;
808
+ const sessionFile = sessionFileForResume(teammate);
809
+ const statusBefore = team.statuses.get(teammate.name)!;
810
+ const stoppedTeams = activeManagedTeams(team, teammate).map((manifest) => ({ name: manifest.name, id: manifest.id }));
811
+ prepareTeammateStart(teammate, teammate.transport);
812
+ await startTeammate(team, teammate, [...team.members.keys()], herdrParentPaneId, { sessionFile, restartEmpty: sessionFile === undefined, settings: update });
813
+ team.statuses.set(teammate.name, statusBefore);
814
+ persistActiveTeamManifest(team);
815
+ return { sessionFile, stoppedTeams };
816
+ });
817
+ teammate.deliveryQueue = restart.then(() => undefined, () => undefined);
818
+ return restart.then(async ({ sessionFile, stoppedTeams }) => {
819
+ if (sessionFile === undefined) await kickoffTeammates(team, [teammate], true);
820
+ await queueDelivery(team, "main", teammate, composeSettingsMessage(describeSettings(update), stoppedTeams), false, false);
821
+ });
822
+ }
823
+
824
+ /** Whether a living process of this session holds the team's lease. Another main that resumed the team holds it under its own session. */
825
+ function isLeaseHeldBy(teamId: string, sessionId: string | undefined): boolean {
826
+ const lease = readTeamLeaseState(teamId);
827
+ return lease.state === "claimed" && lease.mainSessionId === sessionId;
828
+ }
829
+
830
+ /**
831
+ * A managing teammate's running teams, which a restart would stop: its shutdown stops every team it owns.
832
+ * 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.
833
+ */
834
+ function activeManagedTeams(team: TeamState, teammate: TeammateState): TeamManifest[] {
835
+ if (!teammate.canManageOwnTeams || !team.projectDirectory) return [];
836
+ return listTeamManifests(team.projectDirectory).manifests.filter((manifest) => manifest.originMainSessionId === teammate.sessionId && manifest.state === "active" && isLeaseHeldBy(manifest.id, teammate.sessionId));
837
+ }
838
+
839
+ /** The managing teammate's own teammates that are working, as their teams' manifests record them, named for main. */
840
+ function activeManagedTeammates(team: TeamState, teammate: TeammateState): string[] {
841
+ return activeManagedTeams(team, teammate).flatMap((manifest) => manifest.members.filter((member) => member.active).map((member) => `"${member.name}" on team "${manifest.name}"`));
842
+ }
843
+
844
+ /** Applies a busy teammate's held update once it has settled, with no message waiting and no active team of its own. Main hears about the outcome. */
845
+ function applyHeldUpdate(team: TeamState, teammate: TeammateState): void {
846
+ const update = teammate.processRecord!.heldUpdate!;
847
+ teammate.processRecord!.heldUpdate = undefined;
848
+ void restartWithSettings(team, teammate, update).then(() => {
849
+ notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) settled, and its held settings update is applied (${describeSettings(update)}). It continues in the same conversation.`);
850
+ }, (error: unknown) => {
851
+ const errorMessage = error instanceof Error ? error.message : String(error);
852
+ team.statuses.set(teammate.name, status("error", errorMessage));
853
+ appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "error", summary: preview(`held update for ${teammate.name} failed: ${errorMessage}`) });
854
+ notifyOwner(team, teammate, `The held settings update for teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) failed.\nCause: ${errorMessage}\nCheck the teammate's status. Use team_resume to restart it if it stopped.`);
855
+ });
856
+ }
857
+
858
+ /** @example describeSettings({ teammate: "x", model: "local/b", thinking: "high" }) // "model: local/b, thinking: high" */
859
+ function describeSettings(update: TeammateUpdate): string {
860
+ return [
861
+ update.model !== undefined && `model: ${update.model}`,
862
+ update.thinking !== undefined && `thinking: ${update.thinking}`,
863
+ update.extensionPaths !== undefined && `extensions: ${JSON.stringify(update.extensionPaths)}`,
864
+ ].filter(Boolean).join(", ");
865
+ }
866
+
867
+ /** @example interruptForUpdateNotice({ teammate: "x", thinking: "high" }) // "Main interrupted your run to update your configuration (thinking: high). Your conversation continues after a restart." */
868
+ function interruptForUpdateNotice(update: TeammateUpdate): string {
869
+ return `Main interrupted your run to update your configuration (${describeSettings(update)}). Your conversation continues after a restart.`;
870
+ }
871
+
688
872
  function parseHerdrPaneId(stdout: string, teammateName: string): string {
689
873
  const response = JSON.parse(stdout) as { result?: { pane?: { pane_id?: string } } };
690
874
  const paneId = response.result?.pane?.pane_id;
@@ -763,6 +947,7 @@ async function startTeammate(
763
947
  // A Pi session has no lock against a second writer, so a restart ends the previous process, or closes its pane, before it starts the next.
764
948
  await stopRpcTeammate(teammate);
765
949
  await closeHerdrPane(teammate);
950
+ if (startOptions.settings) applyTeammateSettings(teammate, startOptions.settings, startOptions.sessionFile);
766
951
  teammate.processRecord = { id: crypto.randomUUID(), registered: false, stopRequested: false, quitReported: false };
767
952
  if (teammate.transport === "herdr") await attachHerdrTeammate(team, teammate, participants, herdrParentPaneId!, startOptions);
768
953
  else attachRpcTeammate(team, teammate, participants, startOptions);
@@ -1003,6 +1188,7 @@ function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonR
1003
1188
  if (event.type === "agent_start" || event.type === "work_queued") teammate.active = true;
1004
1189
  if (event.type === "agent_settled" || event.type === "session_shutdown") teammate.active = false;
1005
1190
  if (event.type === "agent_settled") recordRunOutcome(team, teammate, event);
1191
+ if (event.type === "agent_settled" && teammate.processRecord?.heldUpdate && !teammate.processRecord.stopRequested && !team.stopping && !teammateSummary(teammate).active) applyHeldUpdate(team, teammate);
1006
1192
  if (event.type === "runtime_facts") applyRuntimeFacts(teammate, event);
1007
1193
  if (event.type === "session_shutdown") {
1008
1194
  teammate.alive = false;
@@ -1135,6 +1321,15 @@ function teammateSchema(modelGuidance: string) {
1135
1321
  }, { additionalProperties: false });
1136
1322
  }
1137
1323
 
1324
+ function teammateUpdateSchema() {
1325
+ return Type.Object({
1326
+ teammate: Type.String({ minLength: 1, description: "Teammate name or Pi session ID" }),
1327
+ model: Type.Optional(Type.String({ description: "New canonical provider/model id." })),
1328
+ thinking: Type.Optional(StringEnum(thinkingLevels, { description: "New thinking level." })),
1329
+ extensionPaths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { uniqueItems: true, description: "New list of trusted extension files or directories, replacing the saved list. Use existing absolute paths." })),
1330
+ }, { additionalProperties: false });
1331
+ }
1332
+
1138
1333
  function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiCommand: string[], manifest: TeamManifest, lease: TeamLease): TeamState {
1139
1334
  const team: TeamState = {
1140
1335
  owner,
@@ -1206,7 +1401,9 @@ export default function (pi: ExtensionAPI) {
1206
1401
 
1207
1402
  const parentPiCommand = piCommand(process.argv[1], process.execPath, getPackageDir());
1208
1403
  const owner = Symbol("pi-simple-team-owner");
1209
- const reminderTimers = new Set<ReturnType<typeof setTimeout>>();
1404
+ /** This session's reminders by ID. They live in memory, so after Pi restarts every earlier reminder is unknown. */
1405
+ const reminders = new Map<string, Reminder>();
1406
+ let reminderCount = 0;
1210
1407
  const sessionTeammateRoster = childRuntimeConfig?.participants ?? [];
1211
1408
 
1212
1409
  /** Current-project manifests that team_resume can select: all for main, only its own for a managing teammate. */
@@ -1240,8 +1437,8 @@ export default function (pi: ExtensionAPI) {
1240
1437
  });
1241
1438
 
1242
1439
  pi.on("session_shutdown", async () => {
1243
- for (const timer of reminderTimers) clearTimeout(timer);
1244
- reminderTimers.clear();
1440
+ for (const reminder of reminders.values()) clearTimeout(reminder.timer);
1441
+ reminders.clear();
1245
1442
  const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
1246
1443
  for (const team of ownedTeams) team.stopping = true;
1247
1444
  for (const team of ownedTeams) await shutdownTeam(team);
@@ -1381,15 +1578,18 @@ export default function (pi: ExtensionAPI) {
1381
1578
  const delaySeconds = Math.round(delayMilliseconds / 1000);
1382
1579
  const armedAt = new Date();
1383
1580
  const wakeAt = new Date(armedAt.getTime() + delayMilliseconds);
1384
- const slug = reminderSlug();
1581
+ const pendingSlugs = new Set([...reminders.values()].filter((reminder) => reminder.state === "pending").map((reminder) => reminder.slug));
1582
+ let slug = reminderSlug();
1583
+ while (pendingSlugs.has(slug)) slug = reminderSlug();
1584
+ const id = `reminder-${++reminderCount}`;
1385
1585
  const timer = setTimeout(() => {
1386
- reminderTimers.delete(timer);
1586
+ reminders.get(id)!.state = "delivered";
1387
1587
  pi.sendMessage(
1388
1588
  { customType: "pi-simple-team-reminder", content: `Reminder ${slug} wake up: it's ${humanTime(new Date())} now.\n\n${params.message}`, display: false },
1389
1589
  { deliverAs: "followUp", triggerTurn: true },
1390
1590
  );
1391
1591
  }, delayMilliseconds);
1392
- reminderTimers.add(timer);
1592
+ reminders.set(id, { id, slug, message: params.message, armedAt, wakeAt, timer, state: "pending" });
1393
1593
  timer.unref();
1394
1594
  return {
1395
1595
  content: [{ type: "text" as const, text: `Armed reminder ${slug}: It's ${humanTime(armedAt)} now. Reminder set in ${delaySeconds} seconds (${humanDuration(delaySeconds)}) for ${humanTime(wakeAt)}.` }],
@@ -1399,19 +1599,75 @@ export default function (pi: ExtensionAPI) {
1399
1599
  }),
1400
1600
  );
1401
1601
 
1602
+ pi.registerTool(
1603
+ defineTool({
1604
+ name: "list_reminders",
1605
+ label: "List Reminders",
1606
+ 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.",
1607
+ parameters: Type.Object({}, { additionalProperties: false }),
1608
+ async execute() {
1609
+ const now = Date.now();
1610
+ const pending = [...reminders.values()].filter((reminder) => reminder.state === "pending").sort((first, second) => first.wakeAt.getTime() - second.wakeAt.getTime());
1611
+ return toolResult({
1612
+ now: humanTime(new Date(now)),
1613
+ reminders: pending.map((reminder) => ({
1614
+ id: reminder.id, slug: reminder.slug,
1615
+ armedAt: `${humanTime(reminder.armedAt)} (${humanDuration(Math.round((now - reminder.armedAt.getTime()) / 1000))} ago)`,
1616
+ wakeAt: `${humanTime(reminder.wakeAt)} (in ${humanDuration(Math.max(0, Math.round((reminder.wakeAt.getTime() - now) / 1000)))})`,
1617
+ })),
1618
+ });
1619
+ },
1620
+ }),
1621
+ );
1622
+
1623
+ pi.registerTool(
1624
+ defineTool({
1625
+ name: "cancel_reminders",
1626
+ label: "Cancel Reminders",
1627
+ 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.",
1628
+ parameters: Type.Object({
1629
+ reminders: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description: "Reminder IDs or slugs to cancel" })),
1630
+ all: Type.Optional(Type.Boolean({ description: "Cancel every pending reminder. Leaving out reminders without all: true cancels nothing." })),
1631
+ }, { additionalProperties: false }),
1632
+ async execute(_toolCallId, params) {
1633
+ if (params.reminders && params.all) throw new Error("Pass either reminders or all: true to cancel_reminders, not both. Nothing was cancelled.");
1634
+ 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.");
1635
+ const cancel = (reminder: Reminder): JsonRecord => {
1636
+ if (reminder.state === "pending") {
1637
+ clearTimeout(reminder.timer);
1638
+ reminder.state = "cancelled";
1639
+ }
1640
+ return { id: reminder.id, slug: reminder.slug, result: reminder.state, ...(reminder.state === "cancelled" ? { message: reminder.message, wakeAt: humanTime(reminder.wakeAt) } : {}) };
1641
+ };
1642
+ const results = params.reminders
1643
+ ? params.reminders.map((identifier) => {
1644
+ const matches = [...reminders.values()].filter((reminder) => reminder.id === identifier || reminder.slug === identifier);
1645
+ const reminder = matches.find((candidate) => candidate.state === "pending") ?? matches.at(-1);
1646
+ return reminder ? { reminder: identifier, ...cancel(reminder) } : { reminder: identifier, result: "unknown" };
1647
+ })
1648
+ : [...reminders.values()].filter((reminder) => reminder.state === "pending").map(cancel);
1649
+ return toolResult({ results });
1650
+ },
1651
+ }),
1652
+ );
1653
+
1402
1654
  pi.registerTool(
1403
1655
  defineTool({
1404
1656
  name: "team_list",
1405
- // TODO: Make listing dormant teams opt-in with includeDormantTeams: boolean.
1406
1657
  label: "Team List",
1407
1658
  description: childRuntimeConfig
1408
- ? "List active and dormant teams in the current project that this managing teammate's Pi session created."
1409
- : "List active and dormant teams for the current project.",
1659
+ ? "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."
1660
+ : "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.",
1410
1661
  renderShell: "self",
1411
1662
  renderCall: (_args, theme, context) => renderTeamToolCall("team_list", {}, theme, context, sessionTeammateRoster),
1412
1663
  renderResult: (result, options, theme, context) => renderTeamToolResult("team_list", result, options, theme, context, undefined, sessionTeammateRoster),
1413
- parameters: Type.Object({}, { additionalProperties: false }),
1414
- async execute(_toolCallId, _params, _signal, _onUpdate, context) {
1664
+ parameters: Type.Object({
1665
+ team: Type.Optional(Type.String({ minLength: 1, description: "Team name or persistent ID. Returns that team's full records, active or dormant, without paging." })),
1666
+ includeDormantTeams: Type.Optional(Type.Boolean({ default: false, description: "Also list dormant teams. Defaults to false: active teams only." })),
1667
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, description: "Max teams to return, default 20, maximum 100" })),
1668
+ cursor: Type.Optional(Type.String({ description: "nextCursor from the previous team_list result. Keep the same includeDormantTeams when paging." })),
1669
+ }, { additionalProperties: false }),
1670
+ async execute(_toolCallId, params, _signal, _onUpdate, context) {
1415
1671
  const projectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
1416
1672
  if (!projectDirectory) throw new Error("team_list requires a project directory");
1417
1673
  const managerSessionId = childRuntimeConfig ? context.sessionManager?.getSessionId?.() : undefined;
@@ -1420,25 +1676,29 @@ export default function (pi: ExtensionAPI) {
1420
1676
  const manifests = listing.manifests.filter(
1421
1677
  (manifest) => !managerSessionId || manifest.originMainSessionId === managerSessionId,
1422
1678
  );
1679
+ const unreadable = listing.unreadable.length > 0 ? { unreadableManifests: listing.unreadable } : {};
1680
+ if (params.team) {
1681
+ if (params.cursor) throw new Error("Pass either team or cursor to team_list, not both.");
1682
+ const manifest = resolveTeamIdentifier(manifests, params.team);
1683
+ if (!manifest) throw new Error(`Unknown current-project team: ${JSON.stringify(params.team)}. Call team_list with includeDormantTeams: true to see every team.`);
1684
+ return toolResult({ ...unreadable, teams: [fullTeamListRow(manifest)] });
1685
+ }
1686
+ const includeDormantTeams = Boolean(params.includeDormantTeams);
1687
+ const after = params.cursor === undefined ? undefined : decodeTeamListCursor(params.cursor);
1688
+ if (after && after.includeDormantTeams !== includeDormantTeams) throw new Error("Keep the same includeDormantTeams when paging team_list with cursor.");
1689
+ const listed = manifests
1690
+ .filter((manifest) => includeDormantTeams || manifest.state === "active")
1691
+ .sort(newestCreatedFirst)
1692
+ .filter((manifest) => !after || newestCreatedFirst(manifest, after) > 0);
1693
+ const page = listed.slice(0, params.limit ?? defaultTeamListLimit);
1694
+ const last = page.at(-1);
1695
+ const hiddenDormantTeams = includeDormantTeams ? 0 : manifests.filter((manifest) => manifest.state === "dormant").length;
1423
1696
  return toolResult({
1424
- ...(listing.unreadable.length > 0 ? { unreadableManifests: listing.unreadable } : {}),
1425
- teams: manifests.map((manifest) => {
1426
- const liveTeam = teams.get(manifest.id);
1427
- return {
1428
- ...teamIdentity(manifest),
1429
- state: manifest.state,
1430
- leaseState: readTeamLeaseState(manifest.id).state,
1431
- teammates: manifest.members.map(({ sessionMaterialized, ...member }) => {
1432
- const runtime = liveTeam?.members.get(member.name);
1433
- return runtime ? teammateRecord(runtime) : member;
1434
- }),
1435
- createdAt: manifest.createdAt,
1436
- updatedAt: manifest.updatedAt,
1437
- shutdownAt: manifest.shutdownAt,
1438
- expiresAt: manifest.expiresAt,
1439
- };
1440
- }),
1441
- });
1697
+ ...unreadable,
1698
+ teams: page.map(compactTeamListRow),
1699
+ ...(listed.length > page.length && last ? { nextCursor: encodeTeamListCursor({ createdAt: last.createdAt, id: last.id, includeDormantTeams }) } : {}),
1700
+ ...(hiddenDormantTeams > 0 ? { dormantTeamsHidden: hiddenDormantTeams, instruction: "Pass includeDormantTeams: true to list dormant teams too." } : {}),
1701
+ }, { teams: page.map(fullTeamListRow) });
1442
1702
  },
1443
1703
  }),
1444
1704
  );
@@ -1448,8 +1708,8 @@ export default function (pi: ExtensionAPI) {
1448
1708
  name: "team_resume",
1449
1709
  label: "Team Resume",
1450
1710
  description: childRuntimeConfig
1451
- ? "Resume all or selected stopped teammates from a current-project team created by your Pi session. Already-running teammates remain as they are."
1452
- : "Resume all or selected stopped teammates from a team in the current project. Already-running teammates remain as they are.",
1711
+ ? "Resume all or selected stopped teammates from a current-project team created by your Pi session, optionally changing their model, thinking level or extensions. Already-running teammates remain as they are."
1712
+ : "Resume all or selected stopped teammates from a team in the current project, optionally changing their model, thinking level or extensions. Already-running teammates remain as they are.",
1453
1713
  renderShell: "self",
1454
1714
  renderCall: (args, theme, context) => renderTeamToolCall("team_resume", args, theme, context, sessionTeammateRoster),
1455
1715
  renderResult: (result, options, theme, context) => renderTeamToolResult("team_resume", result, options, theme, context, undefined, sessionTeammateRoster),
@@ -1460,11 +1720,12 @@ export default function (pi: ExtensionAPI) {
1460
1720
  showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false, description: "Open visible Herdr panes for selected teammates. Defaults to false." })),
1461
1721
  startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start resumed teammates idle." })),
1462
1722
  resumptionPrompt: Type.Optional(Type.String({ description: "Instructions added once after the resumed teammate's dated grounding. Does not change saved definitions or independently start work." })),
1723
+ teammateUpdates: Type.Optional(Type.Array(teammateUpdateSchema(), { minItems: 1, description: "Settings to change for resumed teammates before they restart, as in team_update_teammates. Omitted settings keep their saved values." })),
1463
1724
  }, { additionalProperties: false }),
1464
1725
  async execute(_toolCallId, params, signal, _onUpdate, context) {
1465
1726
  signal?.throwIfAborted();
1466
1727
  const manifest = resolveTeamIdentifier(resumableTeamManifests(context, "team_resume"), params.team);
1467
- 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.`);
1728
+ 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.`);
1468
1729
  const members = manifest.members;
1469
1730
  const requestedNames = resolveTeammates(members, params.teammates ?? members.map((member) => member.teammateId)).map((member) => member.name);
1470
1731
  const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
@@ -1474,6 +1735,11 @@ export default function (pi: ExtensionAPI) {
1474
1735
  if (existingTeam && existingTeam.owner !== owner) {
1475
1736
  throw new Error(`Team ${manifest.id} is already owned by another main session`);
1476
1737
  }
1738
+ const updates = params.teammateUpdates ? resolveTeammateUpdates(members, params.teammateUpdates as TeammateUpdate[], context.modelRegistry.getAvailable()) : new Map<string, TeammateUpdate>();
1739
+ for (const name of updates.keys()) {
1740
+ if (existingTeam?.members.get(name)?.alive) throw new Error(`Teammate "${name}" is running. Use team_update_teammates to change a live teammate.`);
1741
+ if (!requestedNames.includes(name)) throw new Error(`Teammate "${name}" is not selected for this resume. Add it to teammates, or omit teammates to resume every stopped teammate.`);
1742
+ }
1477
1743
 
1478
1744
  let team = existingTeam;
1479
1745
  if (!team) {
@@ -1513,6 +1779,7 @@ export default function (pi: ExtensionAPI) {
1513
1779
  sessionFile,
1514
1780
  restartEmpty: sessionFile === undefined,
1515
1781
  signal,
1782
+ settings: updates.get(teammate.name),
1516
1783
  });
1517
1784
  team.statuses.set(teammate.name, status("idle", "Resumed"));
1518
1785
  }
@@ -1536,7 +1803,7 @@ export default function (pi: ExtensionAPI) {
1536
1803
  throw error;
1537
1804
  }
1538
1805
 
1539
- await kickoffTeammates(team, starts.map(({ teammate }) => teammate), Boolean(params.startIdle), { instructions: params.resumptionPrompt, emptyRestarts: starts.filter(({ sessionFile }) => sessionFile === undefined).map(({ teammate }) => teammate) });
1806
+ await kickoffTeammates(team, starts.map(({ teammate }) => teammate), Boolean(params.startIdle), { instructions: params.resumptionPrompt, emptyRestarts: starts.filter(({ sessionFile }) => sessionFile === undefined).map(({ teammate }) => teammate), settings: updates });
1540
1807
  return toolResult({
1541
1808
  ...lifecycleResult(team),
1542
1809
  teammates: [...team.members.values()].map((teammate) => {
@@ -1626,6 +1893,56 @@ export default function (pi: ExtensionAPI) {
1626
1893
  }),
1627
1894
  );
1628
1895
 
1896
+ pi.registerTool(
1897
+ defineTool({
1898
+ name: "team_update_teammates",
1899
+ label: "Team Update",
1900
+ description: "Change the model, thinking level or extensions of live teammates in a team you own. Each keeps its conversation and identity. An idle teammate restarts on its own session at once; a busy one keeps working and is updated when its run settles. A managing teammate is never held: while it works or any of its own teammates work, the call fails and says what to ask it. Use team_resume to change stopped teammates.",
1901
+ renderShell: "self",
1902
+ renderCall: (args, theme, context) => renderTeamToolCall("team_update_teammates", args, theme, context, sessionTeammateRoster),
1903
+ renderResult: (result, options, theme, context) => renderTeamToolResult("team_update_teammates", result, options, theme, context, undefined, sessionTeammateRoster),
1904
+ parameters: Type.Object({
1905
+ team: Type.Optional(Type.String({ description: "Team name or persistent ID. Omit when exactly one owned active team exists." })),
1906
+ teammates: Type.Array(teammateUpdateSchema(), { minItems: 1, description: "Settings to change, one item per teammate. Omitted settings keep their current values." }),
1907
+ interrupt: Type.Optional(Type.Boolean({ default: false, description: "Interrupt busy teammates and update them at once. Otherwise a busy teammate is updated when its run settles." })),
1908
+ }, { additionalProperties: false }),
1909
+ async execute(_toolCallId, params, _signal, _onUpdate, context) {
1910
+ const ownsSelectedTeam = !params.team || resolveTeamIdentifier([...teams.values()].filter((team) => team.owner === owner), params.team);
1911
+ const stoppedTeam = ownsSelectedTeam ? undefined : resolveTeamIdentifier(resumableTeamManifests(context, "team_update_teammates").filter((manifest) => manifest.state === "dormant"), params.team!);
1912
+ if (stoppedTeam) throw new Error(`Team "${stoppedTeam.name}" (team ID: ${stoppedTeam.id}) is stopped. Use team_resume with teammateUpdates to change its teammates as they resume.`);
1913
+ const team = resolveTeam(owner, params.team);
1914
+ const updates = resolveTeammateUpdates([...team.members.values()].filter((teammate) => teammate.sessionId).map(teammateReference), params.teammates as TeammateUpdate[], context.modelRegistry.getAvailable());
1915
+ const targets = [...updates.keys()].map((name) => team.members.get(name)!);
1916
+ for (const teammate of targets) {
1917
+ if (!teammate.alive) throw new Error(`Teammate "${teammate.name}" is stopped. Use team_resume with teammateUpdates to change its settings as it resumes.`);
1918
+ const workingTeammates = activeManagedTeammates(team, teammate);
1919
+ if (workingTeammates.length > 0) throw new Error(`Teammate "${teammate.name}" has active teammates: ${workingTeammates.join(", ")}. Ask it to soft-pause them, because you want to reload its process without cutting them off. Once it reports them all idle, call team_update_teammates again.`);
1920
+ if (teammate.canManageOwnTeams && teammateSummary(teammate).active && !params.interrupt) throw new Error(`Teammate "${teammate.name}" manages teams and is working, so its update is not held. Ask it to pause, then call team_update_teammates again, or pass interrupt: true to stop its run.`);
1921
+ }
1922
+
1923
+ const held = new Set<TeammateState>();
1924
+ for (const teammate of targets) {
1925
+ const record = teammate.processRecord!;
1926
+ const update = { ...record.heldUpdate, ...updates.get(teammate.name)! };
1927
+ if (teammateSummary(teammate).active && !params.interrupt) {
1928
+ record.heldUpdate = update;
1929
+ held.add(teammate);
1930
+ continue;
1931
+ }
1932
+ if (teammateSummary(teammate).active) await queueDelivery(team, "main", teammate, interruptForUpdateNotice(update), true, false);
1933
+ record.heldUpdate = undefined;
1934
+ await restartWithSettings(team, teammate, update);
1935
+ }
1936
+ return toolResult({
1937
+ ...teamIdentity(team),
1938
+ teammates: targets.map((teammate) => ({ ...teammateRecord(teammate), held: held.has(teammate) })),
1939
+ status: formatStatus(team),
1940
+ ...(held.size > 0 ? { instruction: "Held teammates keep working. Each restarts with its new settings when its run settles, and you get a message then. Its saved settings change at that point. Shutting down the team first drops a held update." } : {}),
1941
+ });
1942
+ },
1943
+ }),
1944
+ );
1945
+
1629
1946
  pi.registerTool(
1630
1947
  defineTool({
1631
1948
  name: "team_send_message",
@@ -1808,10 +2125,17 @@ export default function (pi: ExtensionAPI) {
1808
2125
  async execute(_toolCallId, params) {
1809
2126
  const team = resolveTeam(owner, params.team);
1810
2127
  const teammates = [...team.members.values()].map(teammateReference);
2128
+ const droppedUpdates = [...team.members.values()].flatMap((teammate) => {
2129
+ const heldUpdate = teammate.processRecord?.heldUpdate;
2130
+ return heldUpdate ? [{ ...teammateReference(teammate), settings: describeSettings(heldUpdate) }] : [];
2131
+ });
1811
2132
  const errors = await shutdownTeam(team);
1812
2133
  closeCallbackServerIfUnused();
1813
2134
  if (errors.length > 0) throw new Error(`Failed to close Herdr teammate pane(s): ${errors.join("; ")}`);
1814
- return toolResult({ ...teamIdentity(team), stopped: true, teammates });
2135
+ return toolResult({
2136
+ ...teamIdentity(team), stopped: true, teammates,
2137
+ ...(droppedUpdates.length > 0 ? { droppedUpdates, instruction: "These held settings updates were not applied. Pass them in teammateUpdates when you resume the team." } : {}),
2138
+ });
1815
2139
  },
1816
2140
  }),
1817
2141
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "2.0.22",
3
+ "version": "2.0.24",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",
package/render.ts CHANGED
@@ -25,7 +25,7 @@ interface ToolRenderContextLike {
25
25
  toolCallId?: string;
26
26
  }
27
27
 
28
- export type TeamToolName = "team_spawn" | "team_list" | "team_resume" | "team_add_teammates" | "team_send_message" | "team_status" | "team_log" | "team_shutdown";
28
+ export type TeamToolName = "team_spawn" | "team_list" | "team_resume" | "team_add_teammates" | "team_update_teammates" | "team_send_message" | "team_status" | "team_log" | "team_shutdown";
29
29
 
30
30
  export interface TeamStatusView {
31
31
  word: string;
@@ -288,6 +288,18 @@ export function teamResumeLines(theme: ThemeLike, team: string, resumed: Resumed
288
288
  return [header, ...teammateTree(theme, rows, roster, (row, stem) => (row.note ? [`${stem}${theme.fg("muted", row.note)}`] : []))];
289
289
  }
290
290
 
291
+ export interface UpdatedMemberView extends TeammateView {
292
+ held: boolean;
293
+ }
294
+
295
+ export function teamUpdateLines(theme: ThemeLike, team: string, targets: UpdatedMemberView[], roster: string[] = []): TeamLine[] {
296
+ const heldCount = targets.filter((member) => member.held).length;
297
+ const counts = [`${targets.length - heldCount} updated`, heldCount > 0 && `${heldCount} held`].filter(Boolean).join(", ");
298
+ const header = headerLine(theme, "Team Update", theme.fg("accent", team), [theme.fg("muted", counts)]);
299
+ const rows = targets.map(({ held, ...member }) => ({ ...member, status: held ? "held" : "updated", note: held ? "updates when its run settles" : "restarted, history kept" }));
300
+ return [header, ...teammateTree(theme, rows, roster, (row, stem) => [`${stem}${theme.fg("muted", row.note)}`])];
301
+ }
302
+
291
303
  export interface TeamListMemberView extends TeammateView {
292
304
  live: boolean;
293
305
  }
@@ -762,6 +774,10 @@ function callBodyFor(tool: TeamToolName, theme: ThemeLike, args: Record<string,
762
774
  const teammates = (args.teammates ?? []) as unknown[];
763
775
  return callBody(theme, "Team Add", accentTeam(theme, args.team), [theme.fg("muted", plural(teammates.length, "teammate"))]);
764
776
  }
777
+ if (tool === "team_update_teammates") {
778
+ const teammates = (args.teammates ?? []) as unknown[];
779
+ return callBody(theme, "Team Update", accentTeam(theme, args.team), [theme.fg("muted", plural(teammates.length, "teammate"))]);
780
+ }
765
781
  if (tool === "team_send_message") {
766
782
  const message = String(args.message ?? "");
767
783
  return callBody(theme, "Team Send", sendTarget(theme, (args.targets ?? []) as string[], roster), sendStats(theme, message, hasInterruption(args.interrupt)));
@@ -803,6 +819,9 @@ function resultLinesFor(tool: TeamToolName, theme: ThemeLike, args: Record<strin
803
819
  const teammates = (details.teammates as Array<ResumedMemberView & { contextRestored?: boolean }>).map(({ contextRestored, ...member }) => ({ ...member, restored: contextRestored }));
804
820
  return teamResumeLines(theme, String(details.teamName), teammates, teammates.length, roster);
805
821
  }
822
+ if (tool === "team_update_teammates") {
823
+ return teamUpdateLines(theme, String(details.teamName), details.teammates as UpdatedMemberView[], roster);
824
+ }
806
825
  if (tool === "team_add_teammates") {
807
826
  const memberCount = Object.keys((details.status ?? {}) as Record<string, unknown>).length;
808
827
  return teamAddLines(theme, String(details.teamName), details.addedTeammates as TeammateSpecView[], memberCount, roster, expanded ? markdownTheme! : undefined);
package/resume-message.ts CHANGED
@@ -25,3 +25,15 @@ export function composeResumptionMessage(teamName: string, teammateName: string,
25
25
  instructions,
26
26
  ].filter((part) => part !== undefined).join("\n\n");
27
27
  }
28
+
29
+ /**
30
+ * Tell a teammate restarted with new settings what changed, and which teams it manages the restart stopped, so it resumes them.
31
+ * @example composeSettingsMessage("thinking: high", []) // "Main changed your configuration: thinking: high. You continue in this conversation with these settings."
32
+ */
33
+ export function composeSettingsMessage(settings: string, stoppedTeams: ReadonlyArray<{ name: string; id: string }>): string {
34
+ const stopped = stoppedTeams.map((team) => `"${team.name}" (team ID: ${team.id})`).join(", ");
35
+ return [
36
+ `Main changed your configuration: ${settings}. You continue in this conversation with these settings.`,
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
+ ].filter(Boolean).join("\n\n");
39
+ }
package/team-briefing.ts CHANGED
@@ -16,7 +16,7 @@ export function composeTeamBriefing(
16
16
  `Participants: main, ${participants.join(", ")}.`,
17
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.",
18
18
  "The main agent is the current coordinator. Use the team tools and available session history to share relevant context.",
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.",
19
+ canManageOwnTeams && "You can create and manage teams of your own with team_spawn, team_list, team_resume, team_add_teammates, team_update_teammates, team_send_message, team_status, get_context_window_usage, team_log, and team_shutdown.",
20
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
21
  canManageOwnTeams && "For team_status, omit `team` to operate on this parent team. Set `team` to operate on a team you own.",
22
22
  canManageOwnTeams && "For get_context_window_usage, omit `targets` to get your own usage. Set `targets` to inspect teammates in teams you own.",
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 or dormant teams; resume the intended teammate before retrying.`;
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.ts CHANGED
@@ -12,6 +12,9 @@ export interface Teammate {
12
12
  extensionPaths?: string[];
13
13
  }
14
14
 
15
+ /** Settings main can change for an existing teammate. Its instructions and fork choice only matter at creation. */
16
+ export type TeammateUpdate = { teammate: string } & Partial<Pick<Teammate, "model" | "thinking" | "extensionPaths">>;
17
+
15
18
  export type TeammateRecord = Required<Omit<Teammate, "extensionPaths">> & {
16
19
  extensionPaths?: string[];
17
20
  teammateId: string;