@giladbarnea/pi-simple-team 2.0.22 → 2.0.23
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 +3 -1
- package/index.ts +198 -12
- package/package.json +1 -1
- package/render.ts +20 -1
- package/resume-message.ts +12 -0
- package/team-briefing.ts +1 -1
- package/teammate.ts +3 -0
package/README.md
CHANGED
|
@@ -217,7 +217,7 @@ 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` |
|
|
@@ -237,6 +237,8 @@ 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
|
+
|
|
240
242
|
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
243
|
|
|
242
244
|
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 {
|
|
@@ -397,9 +399,11 @@ function isUnexpectedExit(record: ProcessRecord, code: number | null, signal: No
|
|
|
397
399
|
* Waits for main's own shutdown to mark the team first, so a signal that reaches main and its teammates together sends nothing.
|
|
398
400
|
*/
|
|
399
401
|
function scheduleEndNotice(team: TeamState, teammate: TeammateState, happened: string, cause: string, advice: string): void {
|
|
402
|
+
const heldUpdate = teammate.processRecord?.heldUpdate;
|
|
403
|
+
const droppedUpdate = heldUpdate ? `\nIts held settings update (${describeSettings(heldUpdate)}) was not applied. Pass it in teammateUpdates when you resume it.` : "";
|
|
400
404
|
setTimeout(() => {
|
|
401
405
|
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}`);
|
|
406
|
+
notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) ${happened}.\nCause: ${cause}\n${advice}${droppedUpdate}`);
|
|
403
407
|
}, exitNoticeGraceMilliseconds).unref();
|
|
404
408
|
}
|
|
405
409
|
|
|
@@ -437,12 +441,13 @@ function recordQuit(team: TeamState, teammate: TeammateState, signal: unknown):
|
|
|
437
441
|
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
442
|
}
|
|
439
443
|
|
|
440
|
-
async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[] }): Promise<void> {
|
|
444
|
+
async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[]; settings?: ReadonlyMap<string, TeammateUpdate> }): Promise<void> {
|
|
441
445
|
const outcomes = await Promise.allSettled(teammates.map((teammate) => {
|
|
442
446
|
const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
|
|
443
447
|
const message = [
|
|
444
448
|
initialize && composeTeamBriefing(team.name, team.teamPrompt, teammate.name, teammate.prompt, [...team.members.keys()], teammate.canManageOwnTeams),
|
|
445
449
|
resumption && composeResumptionMessage(team.name, teammate.name, teammate.lastModelActivityAt, resumption.instructions),
|
|
450
|
+
resumption?.settings?.has(teammate.name) && composeSettingsMessage(describeSettings(resumption.settings.get(teammate.name)!), []),
|
|
446
451
|
].filter(Boolean).join("\n\n");
|
|
447
452
|
return queueDelivery(team, "main", teammate, message, false, !startIdle);
|
|
448
453
|
}));
|
|
@@ -568,13 +573,17 @@ function logStatusDeclaration(team: TeamState, participant: string, word?: strin
|
|
|
568
573
|
});
|
|
569
574
|
}
|
|
570
575
|
|
|
576
|
+
function validateExtensionPaths(extensionPaths: readonly string[]): void {
|
|
577
|
+
for (const extensionPath of extensionPaths) {
|
|
578
|
+
if (!path.isAbsolute(extensionPath) || !fs.existsSync(extensionPath)) throw new Error(`Teammate extension must be an existing absolute path: ${extensionPath}`);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
571
582
|
function createTeammateState(teammateSpec: Teammate): TeammateState {
|
|
572
583
|
const teammateName = compactName(teammateSpec.name);
|
|
573
584
|
const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
|
|
574
585
|
const extensionPaths = teammateSpec.extensionPaths ?? [];
|
|
575
|
-
|
|
576
|
-
if (!path.isAbsolute(extensionPath) || !fs.existsSync(extensionPath)) throw new Error(`Teammate extension must be an existing absolute path: ${extensionPath}`);
|
|
577
|
-
}
|
|
586
|
+
validateExtensionPaths(extensionPaths);
|
|
578
587
|
let resolveReady: (() => void) | undefined;
|
|
579
588
|
let rejectReady: ((error: Error) => void) | undefined;
|
|
580
589
|
const ready = new Promise<void>((resolve, reject) => {
|
|
@@ -632,6 +641,8 @@ interface ChildStartOptions {
|
|
|
632
641
|
sessionFile?: string;
|
|
633
642
|
restartEmpty?: boolean;
|
|
634
643
|
signal?: AbortSignal;
|
|
644
|
+
/** New settings, recorded once the previous process has ended and before the next one starts. */
|
|
645
|
+
settings?: TeammateUpdate;
|
|
635
646
|
}
|
|
636
647
|
|
|
637
648
|
/**
|
|
@@ -685,6 +696,106 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
685
696
|
appendSpawnLog(team, teammate);
|
|
686
697
|
}
|
|
687
698
|
|
|
699
|
+
/**
|
|
700
|
+
* Resolves and validates main's settings changes, keyed by teammate name, before anything restarts.
|
|
701
|
+
* @example resolveTeammateUpdates([{ name: "x", teammateId: "s-1" }], [{ teammate: "s-1", thinking: "high" }], []).get("x")?.thinking // "high"
|
|
702
|
+
*/
|
|
703
|
+
function resolveTeammateUpdates(members: readonly { name: string; teammateId: string }[], updates: readonly TeammateUpdate[], availableModels: readonly ModelReference[]): Map<string, TeammateUpdate> {
|
|
704
|
+
const resolved = new Map<string, TeammateUpdate>();
|
|
705
|
+
for (const update of updates) {
|
|
706
|
+
const [member] = resolveTeammates(members, [update.teammate]);
|
|
707
|
+
if (resolved.has(member.name)) throw new Error(`Duplicate settings for teammate "${member.name}". Combine them into one item.`);
|
|
708
|
+
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.`);
|
|
709
|
+
validateExtensionPaths(update.extensionPaths ?? []);
|
|
710
|
+
resolved.set(member.name, update);
|
|
711
|
+
}
|
|
712
|
+
validateTeammateModels([...resolved].flatMap(([name, update]) => update.model === undefined ? [] : [{ name, model: update.model }]), availableModels);
|
|
713
|
+
return resolved;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* 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.
|
|
718
|
+
* Without a saved session there is nothing to record; the next start is a new session that receives the settings as launch arguments.
|
|
719
|
+
*/
|
|
720
|
+
function applyTeammateSettings(teammate: TeammateState, update: TeammateUpdate, sessionFile: string | undefined): void {
|
|
721
|
+
if (sessionFile) {
|
|
722
|
+
const session = SessionManager.open(sessionFile);
|
|
723
|
+
const current = session.buildSessionContext();
|
|
724
|
+
const slash = update.model?.indexOf("/") ?? -1;
|
|
725
|
+
if (update.model && update.model !== `${current.model?.provider}/${current.model?.modelId}`) session.appendModelChange(update.model.slice(0, slash), update.model.slice(slash + 1));
|
|
726
|
+
if (update.thinking && update.thinking !== current.thinkingLevel) session.appendThinkingLevelChange(update.thinking);
|
|
727
|
+
}
|
|
728
|
+
teammate.model = update.model ?? teammate.model;
|
|
729
|
+
teammate.thinking = update.thinking ?? teammate.thinking;
|
|
730
|
+
teammate.extensionPaths = update.extensionPaths ?? teammate.extensionPaths;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Restarts a live teammate on its own session with new settings, through the start path that ends its previous process or pane first.
|
|
735
|
+
* 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.
|
|
736
|
+
* A teammate without a saved session restarts empty and gets its briefing staged again, as team_resume does.
|
|
737
|
+
*/
|
|
738
|
+
function restartWithSettings(team: TeamState, teammate: TeammateState, update: TeammateUpdate): Promise<void> {
|
|
739
|
+
const restart = teammate.deliveryQueue.then(async () => {
|
|
740
|
+
const herdrParentPaneId = teammate.transport === "herdr" ? await validateHerdrAvailability() : undefined;
|
|
741
|
+
const sessionFile = sessionFileForResume(teammate);
|
|
742
|
+
const statusBefore = team.statuses.get(teammate.name)!;
|
|
743
|
+
const stoppedTeams = activeManagedTeams(team, teammate).map((manifest) => ({ name: manifest.name, id: manifest.id }));
|
|
744
|
+
prepareTeammateStart(teammate, teammate.transport);
|
|
745
|
+
await startTeammate(team, teammate, [...team.members.keys()], herdrParentPaneId, { sessionFile, restartEmpty: sessionFile === undefined, settings: update });
|
|
746
|
+
team.statuses.set(teammate.name, statusBefore);
|
|
747
|
+
persistActiveTeamManifest(team);
|
|
748
|
+
return { sessionFile, stoppedTeams };
|
|
749
|
+
});
|
|
750
|
+
teammate.deliveryQueue = restart.then(() => undefined, () => undefined);
|
|
751
|
+
return restart.then(async ({ sessionFile, stoppedTeams }) => {
|
|
752
|
+
if (sessionFile === undefined) await kickoffTeammates(team, [teammate], true);
|
|
753
|
+
await queueDelivery(team, "main", teammate, composeSettingsMessage(describeSettings(update), stoppedTeams), false, false);
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* 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 its lease is held by a living process. A manager that died abruptly leaves its manifests active behind a stale lease, and those teams run nothing.
|
|
760
|
+
*/
|
|
761
|
+
function activeManagedTeams(team: TeamState, teammate: TeammateState): TeamManifest[] {
|
|
762
|
+
if (!teammate.canManageOwnTeams || !team.projectDirectory) return [];
|
|
763
|
+
return listTeamManifests(team.projectDirectory).manifests.filter((manifest) => manifest.originMainSessionId === teammate.sessionId && manifest.state === "active" && readTeamLeaseState(manifest.id).state === "claimed");
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/** The managing teammate's own teammates that are working, as their teams' manifests record them, named for main. */
|
|
767
|
+
function activeManagedTeammates(team: TeamState, teammate: TeammateState): string[] {
|
|
768
|
+
return activeManagedTeams(team, teammate).flatMap((manifest) => manifest.members.filter((member) => member.active).map((member) => `"${member.name}" on team "${manifest.name}"`));
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** 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. */
|
|
772
|
+
function applyHeldUpdate(team: TeamState, teammate: TeammateState): void {
|
|
773
|
+
const update = teammate.processRecord!.heldUpdate!;
|
|
774
|
+
teammate.processRecord!.heldUpdate = undefined;
|
|
775
|
+
void restartWithSettings(team, teammate, update).then(() => {
|
|
776
|
+
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.`);
|
|
777
|
+
}, (error: unknown) => {
|
|
778
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
779
|
+
team.statuses.set(teammate.name, status("error", errorMessage));
|
|
780
|
+
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "error", summary: preview(`held update for ${teammate.name} failed: ${errorMessage}`) });
|
|
781
|
+
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.`);
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/** @example describeSettings({ teammate: "x", model: "local/b", thinking: "high" }) // "model: local/b, thinking: high" */
|
|
786
|
+
function describeSettings(update: TeammateUpdate): string {
|
|
787
|
+
return [
|
|
788
|
+
update.model !== undefined && `model: ${update.model}`,
|
|
789
|
+
update.thinking !== undefined && `thinking: ${update.thinking}`,
|
|
790
|
+
update.extensionPaths !== undefined && `extensions: ${JSON.stringify(update.extensionPaths)}`,
|
|
791
|
+
].filter(Boolean).join(", ");
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** @example interruptForUpdateNotice({ teammate: "x", thinking: "high" }) // "Main interrupted your run to update your configuration (thinking: high). Your conversation continues after a restart." */
|
|
795
|
+
function interruptForUpdateNotice(update: TeammateUpdate): string {
|
|
796
|
+
return `Main interrupted your run to update your configuration (${describeSettings(update)}). Your conversation continues after a restart.`;
|
|
797
|
+
}
|
|
798
|
+
|
|
688
799
|
function parseHerdrPaneId(stdout: string, teammateName: string): string {
|
|
689
800
|
const response = JSON.parse(stdout) as { result?: { pane?: { pane_id?: string } } };
|
|
690
801
|
const paneId = response.result?.pane?.pane_id;
|
|
@@ -763,6 +874,7 @@ async function startTeammate(
|
|
|
763
874
|
// 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
875
|
await stopRpcTeammate(teammate);
|
|
765
876
|
await closeHerdrPane(teammate);
|
|
877
|
+
if (startOptions.settings) applyTeammateSettings(teammate, startOptions.settings, startOptions.sessionFile);
|
|
766
878
|
teammate.processRecord = { id: crypto.randomUUID(), registered: false, stopRequested: false, quitReported: false };
|
|
767
879
|
if (teammate.transport === "herdr") await attachHerdrTeammate(team, teammate, participants, herdrParentPaneId!, startOptions);
|
|
768
880
|
else attachRpcTeammate(team, teammate, participants, startOptions);
|
|
@@ -1003,6 +1115,7 @@ function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonR
|
|
|
1003
1115
|
if (event.type === "agent_start" || event.type === "work_queued") teammate.active = true;
|
|
1004
1116
|
if (event.type === "agent_settled" || event.type === "session_shutdown") teammate.active = false;
|
|
1005
1117
|
if (event.type === "agent_settled") recordRunOutcome(team, teammate, event);
|
|
1118
|
+
if (event.type === "agent_settled" && teammate.processRecord?.heldUpdate && !teammate.processRecord.stopRequested && !team.stopping && !teammateSummary(teammate).active) applyHeldUpdate(team, teammate);
|
|
1006
1119
|
if (event.type === "runtime_facts") applyRuntimeFacts(teammate, event);
|
|
1007
1120
|
if (event.type === "session_shutdown") {
|
|
1008
1121
|
teammate.alive = false;
|
|
@@ -1135,6 +1248,15 @@ function teammateSchema(modelGuidance: string) {
|
|
|
1135
1248
|
}, { additionalProperties: false });
|
|
1136
1249
|
}
|
|
1137
1250
|
|
|
1251
|
+
function teammateUpdateSchema() {
|
|
1252
|
+
return Type.Object({
|
|
1253
|
+
teammate: Type.String({ minLength: 1, description: "Teammate name or Pi session ID" }),
|
|
1254
|
+
model: Type.Optional(Type.String({ description: "New canonical provider/model id." })),
|
|
1255
|
+
thinking: Type.Optional(StringEnum(thinkingLevels, { description: "New thinking level." })),
|
|
1256
|
+
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." })),
|
|
1257
|
+
}, { additionalProperties: false });
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1138
1260
|
function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiCommand: string[], manifest: TeamManifest, lease: TeamLease): TeamState {
|
|
1139
1261
|
const team: TeamState = {
|
|
1140
1262
|
owner,
|
|
@@ -1448,8 +1570,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1448
1570
|
name: "team_resume",
|
|
1449
1571
|
label: "Team Resume",
|
|
1450
1572
|
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.",
|
|
1573
|
+
? "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."
|
|
1574
|
+
: "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
1575
|
renderShell: "self",
|
|
1454
1576
|
renderCall: (args, theme, context) => renderTeamToolCall("team_resume", args, theme, context, sessionTeammateRoster),
|
|
1455
1577
|
renderResult: (result, options, theme, context) => renderTeamToolResult("team_resume", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
@@ -1460,6 +1582,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1460
1582
|
showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false, description: "Open visible Herdr panes for selected teammates. Defaults to false." })),
|
|
1461
1583
|
startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start resumed teammates idle." })),
|
|
1462
1584
|
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." })),
|
|
1585
|
+
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
1586
|
}, { additionalProperties: false }),
|
|
1464
1587
|
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
1465
1588
|
signal?.throwIfAborted();
|
|
@@ -1474,6 +1597,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
1474
1597
|
if (existingTeam && existingTeam.owner !== owner) {
|
|
1475
1598
|
throw new Error(`Team ${manifest.id} is already owned by another main session`);
|
|
1476
1599
|
}
|
|
1600
|
+
const updates = params.teammateUpdates ? resolveTeammateUpdates(members, params.teammateUpdates as TeammateUpdate[], context.modelRegistry.getAvailable()) : new Map<string, TeammateUpdate>();
|
|
1601
|
+
for (const name of updates.keys()) {
|
|
1602
|
+
if (existingTeam?.members.get(name)?.alive) throw new Error(`Teammate "${name}" is running. Use team_update_teammates to change a live teammate.`);
|
|
1603
|
+
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.`);
|
|
1604
|
+
}
|
|
1477
1605
|
|
|
1478
1606
|
let team = existingTeam;
|
|
1479
1607
|
if (!team) {
|
|
@@ -1513,6 +1641,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1513
1641
|
sessionFile,
|
|
1514
1642
|
restartEmpty: sessionFile === undefined,
|
|
1515
1643
|
signal,
|
|
1644
|
+
settings: updates.get(teammate.name),
|
|
1516
1645
|
});
|
|
1517
1646
|
team.statuses.set(teammate.name, status("idle", "Resumed"));
|
|
1518
1647
|
}
|
|
@@ -1536,7 +1665,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1536
1665
|
throw error;
|
|
1537
1666
|
}
|
|
1538
1667
|
|
|
1539
|
-
await kickoffTeammates(team, starts.map(({ teammate }) => teammate), Boolean(params.startIdle), { instructions: params.resumptionPrompt, emptyRestarts: starts.filter(({ sessionFile }) => sessionFile === undefined).map(({ teammate }) => teammate) });
|
|
1668
|
+
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
1669
|
return toolResult({
|
|
1541
1670
|
...lifecycleResult(team),
|
|
1542
1671
|
teammates: [...team.members.values()].map((teammate) => {
|
|
@@ -1626,6 +1755,56 @@ export default function (pi: ExtensionAPI) {
|
|
|
1626
1755
|
}),
|
|
1627
1756
|
);
|
|
1628
1757
|
|
|
1758
|
+
pi.registerTool(
|
|
1759
|
+
defineTool({
|
|
1760
|
+
name: "team_update_teammates",
|
|
1761
|
+
label: "Team Update",
|
|
1762
|
+
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.",
|
|
1763
|
+
renderShell: "self",
|
|
1764
|
+
renderCall: (args, theme, context) => renderTeamToolCall("team_update_teammates", args, theme, context, sessionTeammateRoster),
|
|
1765
|
+
renderResult: (result, options, theme, context) => renderTeamToolResult("team_update_teammates", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
1766
|
+
parameters: Type.Object({
|
|
1767
|
+
team: Type.Optional(Type.String({ description: "Team name or persistent ID. Omit when exactly one owned active team exists." })),
|
|
1768
|
+
teammates: Type.Array(teammateUpdateSchema(), { minItems: 1, description: "Settings to change, one item per teammate. Omitted settings keep their current values." }),
|
|
1769
|
+
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." })),
|
|
1770
|
+
}, { additionalProperties: false }),
|
|
1771
|
+
async execute(_toolCallId, params, _signal, _onUpdate, context) {
|
|
1772
|
+
const ownsSelectedTeam = !params.team || resolveTeamIdentifier([...teams.values()].filter((team) => team.owner === owner), params.team);
|
|
1773
|
+
const stoppedTeam = ownsSelectedTeam ? undefined : resolveTeamIdentifier(resumableTeamManifests(context, "team_update_teammates").filter((manifest) => manifest.state === "dormant"), params.team!);
|
|
1774
|
+
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.`);
|
|
1775
|
+
const team = resolveTeam(owner, params.team);
|
|
1776
|
+
const updates = resolveTeammateUpdates([...team.members.values()].filter((teammate) => teammate.sessionId).map(teammateReference), params.teammates as TeammateUpdate[], context.modelRegistry.getAvailable());
|
|
1777
|
+
const targets = [...updates.keys()].map((name) => team.members.get(name)!);
|
|
1778
|
+
for (const teammate of targets) {
|
|
1779
|
+
if (!teammate.alive) throw new Error(`Teammate "${teammate.name}" is stopped. Use team_resume with teammateUpdates to change its settings as it resumes.`);
|
|
1780
|
+
const workingTeammates = activeManagedTeammates(team, teammate);
|
|
1781
|
+
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.`);
|
|
1782
|
+
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.`);
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
const held = new Set<TeammateState>();
|
|
1786
|
+
for (const teammate of targets) {
|
|
1787
|
+
const record = teammate.processRecord!;
|
|
1788
|
+
const update = { ...record.heldUpdate, ...updates.get(teammate.name)! };
|
|
1789
|
+
if (teammateSummary(teammate).active && !params.interrupt) {
|
|
1790
|
+
record.heldUpdate = update;
|
|
1791
|
+
held.add(teammate);
|
|
1792
|
+
continue;
|
|
1793
|
+
}
|
|
1794
|
+
if (teammateSummary(teammate).active) await queueDelivery(team, "main", teammate, interruptForUpdateNotice(update), true, false);
|
|
1795
|
+
record.heldUpdate = undefined;
|
|
1796
|
+
await restartWithSettings(team, teammate, update);
|
|
1797
|
+
}
|
|
1798
|
+
return toolResult({
|
|
1799
|
+
...teamIdentity(team),
|
|
1800
|
+
teammates: targets.map((teammate) => ({ ...teammateRecord(teammate), held: held.has(teammate) })),
|
|
1801
|
+
status: formatStatus(team),
|
|
1802
|
+
...(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." } : {}),
|
|
1803
|
+
});
|
|
1804
|
+
},
|
|
1805
|
+
}),
|
|
1806
|
+
);
|
|
1807
|
+
|
|
1629
1808
|
pi.registerTool(
|
|
1630
1809
|
defineTool({
|
|
1631
1810
|
name: "team_send_message",
|
|
@@ -1808,10 +1987,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
1808
1987
|
async execute(_toolCallId, params) {
|
|
1809
1988
|
const team = resolveTeam(owner, params.team);
|
|
1810
1989
|
const teammates = [...team.members.values()].map(teammateReference);
|
|
1990
|
+
const droppedUpdates = [...team.members.values()].flatMap((teammate) => {
|
|
1991
|
+
const heldUpdate = teammate.processRecord?.heldUpdate;
|
|
1992
|
+
return heldUpdate ? [{ ...teammateReference(teammate), settings: describeSettings(heldUpdate) }] : [];
|
|
1993
|
+
});
|
|
1811
1994
|
const errors = await shutdownTeam(team);
|
|
1812
1995
|
closeCallbackServerIfUnused();
|
|
1813
1996
|
if (errors.length > 0) throw new Error(`Failed to close Herdr teammate pane(s): ${errors.join("; ")}`);
|
|
1814
|
-
return toolResult({
|
|
1997
|
+
return toolResult({
|
|
1998
|
+
...teamIdentity(team), stopped: true, teammates,
|
|
1999
|
+
...(droppedUpdates.length > 0 ? { droppedUpdates, instruction: "These held settings updates were not applied. Pass them in teammateUpdates when you resume the team." } : {}),
|
|
2000
|
+
});
|
|
1815
2001
|
},
|
|
1816
2002
|
}),
|
|
1817
2003
|
);
|
package/package.json
CHANGED
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/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;
|