@giladbarnea/pi-simple-team 2.0.21 → 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 +5 -2
- package/child-tools.ts +34 -2
- package/index.ts +294 -31
- 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
|
@@ -149,7 +149,8 @@ Your main uses `team_log` when it needs to understand the chain of events in hig
|
|
|
149
149
|
Provides main a timestamped, filterable, append-only record of the team’s messages, tool calls, and lifecycle events.
|
|
150
150
|
Attempts can end before retries finish. A separate run row reports final settlement as ended or cancelled. Ended does not imply success.
|
|
151
151
|
A run that ends on a provider error adds an error row with the provider's message and sets the teammate's status to `error` with that message, until a later run completes. Main also gets a message saying so.
|
|
152
|
-
A background teammate that exits without being stopped, after it registered, also sends main a message with its exit code. A teammate that quits itself (exit code 0) does not.
|
|
152
|
+
A background teammate that exits without being stopped, after it registered, also sends main a message with its exit code. A teammate that quits itself (exit code 0) does not.
|
|
153
|
+
A Herdr pane teammate gets the same messages. If its process dies, main is told that it exited. If it is idle when its pane is closed, or it receives SIGHUP or SIGTERM, main gets a neutral message that names the signal, because either can be on purpose. A pane closed while its teammate works usually ends Pi at once, so main is told that it exited. A restart closes the teammate's previous pane. A pane that main closes itself sends nothing.
|
|
153
154
|
|
|
154
155
|
### 🌅 Herdr Support
|
|
155
156
|
|
|
@@ -216,7 +217,7 @@ Kept minimal:
|
|
|
216
217
|
|
|
217
218
|
| Role | For | Tools |
|
|
218
219
|
| --- | --- | --- |
|
|
219
|
-
| **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` |
|
|
220
221
|
| | With team | `team_send_message` |
|
|
221
222
|
| | On team | `team_status`, `team_log` |
|
|
222
223
|
| | On everyone | `get_context_window_usage` |
|
|
@@ -236,6 +237,8 @@ Resume appends a custom briefing with the team identity, current time, and last
|
|
|
236
237
|
|
|
237
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.
|
|
238
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
|
+
|
|
239
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.
|
|
240
243
|
|
|
241
244
|
Set `showOnHerdrPane: true` on individual teammates to open their panes. An explicit `showOnHerdrPanes` value on spawn overrides all individual settings.
|
package/child-tools.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as http from "node:http";
|
|
2
|
+
import * as net from "node:net";
|
|
2
3
|
import { defineTool, getMarkdownTheme, type AgentActivityOutcome, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
4
|
import { Type } from "typebox";
|
|
4
5
|
import { formatContextWindowReport, requireKnownContextUsage } from "./context-window.ts";
|
|
@@ -111,6 +112,35 @@ export async function callParent(config: ChildRuntimeConfig, tool: string, args:
|
|
|
111
112
|
return (await response.json()) as JsonRecord;
|
|
112
113
|
}
|
|
113
114
|
|
|
115
|
+
type ShutdownSignal = "SIGHUP" | "SIGTERM";
|
|
116
|
+
|
|
117
|
+
/** Lives on globalThis, because it belongs to the process: Pi loads this module again on a reload or a session replacement. */
|
|
118
|
+
interface ProcessLifeline {
|
|
119
|
+
socket: net.Socket;
|
|
120
|
+
signal?: ShutdownSignal;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const lifelineKey: unique symbol = Symbol.for("pi-simple-team.lifeline");
|
|
124
|
+
const lifelineHolder = globalThis as { [lifelineKey]?: ProcessLifeline };
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Main has no process handle for a Herdr pane teammate. This connection stays open for the life of the process, so its close tells main that the process ended.
|
|
128
|
+
* The process also notes the signal that shuts it down in order, because a closed pane arrives as SIGHUP. Pi's interactive mode registers its own handlers for both signals before it loads extensions, so these listeners never replace the default termination.
|
|
129
|
+
*/
|
|
130
|
+
function holdLifeline(config: ChildRuntimeConfig, port: number): void {
|
|
131
|
+
if (lifelineHolder[lifelineKey]) return;
|
|
132
|
+
const socket = net.connect(port, "127.0.0.1", () => {
|
|
133
|
+
socket.write(`${JSON.stringify({ token: config.callbackToken, team: config.teamId ?? config.teamName, from: config.teammateName, process: config.processId })}\n`);
|
|
134
|
+
});
|
|
135
|
+
// Main closing first must not crash the teammate.
|
|
136
|
+
socket.on("error", () => undefined);
|
|
137
|
+
socket.unref();
|
|
138
|
+
const lifeline: ProcessLifeline = { socket };
|
|
139
|
+
// Prepended, because Pi 1.4 emits session_shutdown from inside its own signal handler.
|
|
140
|
+
for (const signal of ["SIGHUP", "SIGTERM"] as const) process.prependListener(signal, () => { lifeline.signal ??= signal; });
|
|
141
|
+
lifelineHolder[lifelineKey] = lifeline;
|
|
142
|
+
}
|
|
143
|
+
|
|
114
144
|
function toolResult(payload: JsonRecord): { content: [{ type: "text"; text: string }]; details: JsonRecord } {
|
|
115
145
|
return {
|
|
116
146
|
content: [{ type: "text" as const, text: JSON.stringify(payload, null, 2) }],
|
|
@@ -293,8 +323,9 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
|
293
323
|
const address = server.address();
|
|
294
324
|
if (!address || typeof address === "string") throw new Error("Child delivery server did not get a port");
|
|
295
325
|
|
|
326
|
+
let registration: JsonRecord;
|
|
296
327
|
try {
|
|
297
|
-
await callParent(config, "register", {
|
|
328
|
+
registration = await callParent(config, "register", {
|
|
298
329
|
url: `http://127.0.0.1:${address.port}/deliver`,
|
|
299
330
|
sessionId: context.sessionManager.getSessionId(),
|
|
300
331
|
sessionFile: context.sessionManager.getSessionFile(),
|
|
@@ -305,11 +336,12 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
|
305
336
|
context.shutdown();
|
|
306
337
|
throw error;
|
|
307
338
|
}
|
|
339
|
+
if (typeof registration.lifelinePort === "number") holdLifeline(config, registration.lifelinePort);
|
|
308
340
|
});
|
|
309
341
|
|
|
310
342
|
pi.on("session_shutdown", async (event) => {
|
|
311
343
|
markIdle();
|
|
312
|
-
await notifyParent({ type: "session_shutdown", reason: event.reason });
|
|
344
|
+
await notifyParent({ type: "session_shutdown", reason: event.reason, signal: lifelineHolder[lifelineKey]?.signal });
|
|
313
345
|
await new Promise<void>((resolve, reject) => {
|
|
314
346
|
if (!server) {
|
|
315
347
|
resolve();
|
package/index.ts
CHANGED
|
@@ -3,14 +3,15 @@ import type { ChildProcess } from "node:child_process";
|
|
|
3
3
|
import crypto from "node:crypto";
|
|
4
4
|
import * as fs from "node:fs";
|
|
5
5
|
import http from "node:http";
|
|
6
|
+
import * as net from "node:net";
|
|
6
7
|
import * as path from "node:path";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
8
|
-
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";
|
|
9
10
|
import { formatContextWindowReport, requireKnownContextUsage, type KnownContextUsage } from "./context-window.ts";
|
|
10
11
|
import { useModelNames } from "./model-names.ts";
|
|
11
12
|
import { formatScopedModelGuidance, validateTeammateModels, type ModelReference } from "./model-preflight.ts";
|
|
12
13
|
import { composeTeamBriefing } from "./team-briefing.ts";
|
|
13
|
-
import { composeResumptionMessage } from "./resume-message.ts";
|
|
14
|
+
import { composeResumptionMessage, composeSettingsMessage } from "./resume-message.ts";
|
|
14
15
|
import { callParent, isInertTeamCopy, readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
|
|
15
16
|
import {
|
|
16
17
|
canonicalProjectDirectory,
|
|
@@ -31,7 +32,7 @@ import { openTeamOverview, type TeamSnapshot } from "./team-ui.ts";
|
|
|
31
32
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
32
33
|
import { Type } from "typebox";
|
|
33
34
|
import { resolveTargets, resolveTeammates, interruptedTeammateIds, findUnknownTarget, unknownTargetMessage, targetDescription, interruptDescription, type DormantTeammateMatch, type SelectableTeam } from "./team-selection.ts";
|
|
34
|
-
import type { Teammate, TeammateRecord, ThinkingLevel } from "./teammate.ts";
|
|
35
|
+
import type { Teammate, TeammateRecord, TeammateUpdate, ThinkingLevel } from "./teammate.ts";
|
|
35
36
|
|
|
36
37
|
type JsonRecord = Record<string, unknown>;
|
|
37
38
|
|
|
@@ -51,13 +52,19 @@ interface RunFailure {
|
|
|
51
52
|
|
|
52
53
|
/**
|
|
53
54
|
* One start of a teammate's process. Main gives the process this record's id, and the process sends it with every callback,
|
|
54
|
-
* so main never mistakes a replaced process for the current one.
|
|
55
|
+
* so main never mistakes a replaced process for the current one. Its end is judged by its own record.
|
|
56
|
+
* Main has no process handle for a Herdr pane teammate, so that process also holds a lifeline connection, which closes when it ends.
|
|
55
57
|
*/
|
|
56
58
|
interface ProcessRecord {
|
|
57
59
|
id: string;
|
|
58
60
|
registered: boolean;
|
|
59
61
|
stopRequested: boolean;
|
|
60
62
|
quitReported: boolean;
|
|
63
|
+
/** Set once main has recorded this process's end, so a callback still in flight when it died changes nothing. */
|
|
64
|
+
ended?: boolean;
|
|
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;
|
|
61
68
|
}
|
|
62
69
|
|
|
63
70
|
interface TeammateState {
|
|
@@ -121,6 +128,8 @@ const callbackToken = crypto.randomBytes(24).toString("hex");
|
|
|
121
128
|
let callbackServer: http.Server | undefined;
|
|
122
129
|
let callbackReady: Promise<void> | undefined;
|
|
123
130
|
let callbackUrl = "";
|
|
131
|
+
let lifelineServer: net.Server | undefined;
|
|
132
|
+
let lifelinePort = 0;
|
|
124
133
|
|
|
125
134
|
function status(word: string, phrase: string): TeamStatus {
|
|
126
135
|
return { word, phrase, updated: new Date().toISOString() };
|
|
@@ -385,20 +394,60 @@ function isUnexpectedExit(record: ProcessRecord, code: number | null, signal: No
|
|
|
385
394
|
return record.registered && !record.stopRequested && !selfQuit;
|
|
386
395
|
}
|
|
387
396
|
|
|
388
|
-
/**
|
|
389
|
-
|
|
397
|
+
/**
|
|
398
|
+
* Tells the team owner that a teammate's process ended, in the same three lines for every transport: what happened, the cause, what to do.
|
|
399
|
+
* Waits for main's own shutdown to mark the team first, so a signal that reaches main and its teammates together sends nothing.
|
|
400
|
+
*/
|
|
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.` : "";
|
|
390
404
|
setTimeout(() => {
|
|
391
405
|
if (team.stopping || teams.get(team.id ?? team.name) !== team) return;
|
|
392
|
-
notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name})
|
|
406
|
+
notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) ${happened}.\nCause: ${cause}\n${advice}${droppedUpdate}`);
|
|
393
407
|
}, exitNoticeGraceMilliseconds).unref();
|
|
394
408
|
}
|
|
395
409
|
|
|
396
|
-
|
|
410
|
+
/** A Herdr pane teammate's process ended without a shutdown callback: a crash, a kill, or a terminal that vanished under a working Pi. */
|
|
411
|
+
function recordAbruptEnd(team: TeamState, teammate: TeammateState, record: ProcessRecord): void {
|
|
412
|
+
if (record.stopRequested || record.quitReported || record.ended) return;
|
|
413
|
+
record.ended = true;
|
|
414
|
+
teammate.alive = false;
|
|
415
|
+
teammate.active = false;
|
|
416
|
+
teammate.deliveryUrl = undefined;
|
|
417
|
+
team.statuses.set(teammate.name, status("stopped", "Ended without shutting down"));
|
|
418
|
+
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "ended without shutting down" });
|
|
419
|
+
persistActiveTeamManifest(team);
|
|
420
|
+
scheduleEndNotice(team, teammate, "exited", "its Pi process ended without shutting down (a crash, a kill, or its pane closed while it worked)", "Check its pane if it is still open. Use team_resume to restart it.");
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
type ShutdownSignal = "SIGHUP" | "SIGTERM";
|
|
424
|
+
|
|
425
|
+
/** What a signal shutdown most likely means. Nobody can tell who sent the signal or why, so neither reads as a failure. */
|
|
426
|
+
const signalReasons: Record<ShutdownSignal, string> = {
|
|
427
|
+
SIGHUP: "Its pane may have been closed on purpose.",
|
|
428
|
+
SIGTERM: "Something outside the team may have stopped it on purpose.",
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
/** A teammate's Pi shut down in order. Only a Herdr pane teammate reports a signal: nobody can tell who closed its pane or why, so the notice stays neutral. */
|
|
432
|
+
function recordQuit(team: TeamState, teammate: TeammateState, signal: unknown): void {
|
|
433
|
+
const record = teammate.processRecord!;
|
|
434
|
+
if (record.ended) return;
|
|
435
|
+
record.ended = true;
|
|
436
|
+
record.quitReported = true;
|
|
437
|
+
const afterSignal = typeof signal === "string" ? ` after ${signal}` : "";
|
|
438
|
+
team.statuses.set(teammate.name, status("stopped", afterSignal ? `Shut down${afterSignal}` : "Session shut down"));
|
|
439
|
+
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `session shut down${afterSignal}`, details: { reason: "quit", ...(afterSignal ? { signal } : {}) } });
|
|
440
|
+
if (!afterSignal || record.stopRequested) return;
|
|
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.");
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[]; settings?: ReadonlyMap<string, TeammateUpdate> }): Promise<void> {
|
|
397
445
|
const outcomes = await Promise.allSettled(teammates.map((teammate) => {
|
|
398
446
|
const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
|
|
399
447
|
const message = [
|
|
400
448
|
initialize && composeTeamBriefing(team.name, team.teamPrompt, teammate.name, teammate.prompt, [...team.members.keys()], teammate.canManageOwnTeams),
|
|
401
449
|
resumption && composeResumptionMessage(team.name, teammate.name, teammate.lastModelActivityAt, resumption.instructions),
|
|
450
|
+
resumption?.settings?.has(teammate.name) && composeSettingsMessage(describeSettings(resumption.settings.get(teammate.name)!), []),
|
|
402
451
|
].filter(Boolean).join("\n\n");
|
|
403
452
|
return queueDelivery(team, "main", teammate, message, false, !startIdle);
|
|
404
453
|
}));
|
|
@@ -524,13 +573,17 @@ function logStatusDeclaration(team: TeamState, participant: string, word?: strin
|
|
|
524
573
|
});
|
|
525
574
|
}
|
|
526
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
|
+
|
|
527
582
|
function createTeammateState(teammateSpec: Teammate): TeammateState {
|
|
528
583
|
const teammateName = compactName(teammateSpec.name);
|
|
529
584
|
const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
|
|
530
585
|
const extensionPaths = teammateSpec.extensionPaths ?? [];
|
|
531
|
-
|
|
532
|
-
if (!path.isAbsolute(extensionPath) || !fs.existsSync(extensionPath)) throw new Error(`Teammate extension must be an existing absolute path: ${extensionPath}`);
|
|
533
|
-
}
|
|
586
|
+
validateExtensionPaths(extensionPaths);
|
|
534
587
|
let resolveReady: (() => void) | undefined;
|
|
535
588
|
let rejectReady: ((error: Error) => void) | undefined;
|
|
536
589
|
const ready = new Promise<void>((resolve, reject) => {
|
|
@@ -588,6 +641,8 @@ interface ChildStartOptions {
|
|
|
588
641
|
sessionFile?: string;
|
|
589
642
|
restartEmpty?: boolean;
|
|
590
643
|
signal?: AbortSignal;
|
|
644
|
+
/** New settings, recorded once the previous process has ended and before the next one starts. */
|
|
645
|
+
settings?: TeammateUpdate;
|
|
591
646
|
}
|
|
592
647
|
|
|
593
648
|
/**
|
|
@@ -636,11 +691,111 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
636
691
|
rejectReady?.(new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
|
|
637
692
|
team.statuses.set(teammate.name, status("stopped", `Exited code=${code} signal=${signal}`));
|
|
638
693
|
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `exited (code=${code}, signal=${signal})`, details: { code, signal } });
|
|
639
|
-
if (isUnexpectedExit(record, code, signal))
|
|
694
|
+
if (isUnexpectedExit(record, code, signal)) scheduleEndNotice(team, teammate, "exited", `exited (code=${code}, signal=${signal})`, "Code 143 or 129 means its Pi shut down after SIGTERM or SIGHUP. Check team_log for its last stderr lines. Use team_resume to restart it.");
|
|
640
695
|
});
|
|
641
696
|
appendSpawnLog(team, teammate);
|
|
642
697
|
}
|
|
643
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
|
+
|
|
644
799
|
function parseHerdrPaneId(stdout: string, teammateName: string): string {
|
|
645
800
|
const response = JSON.parse(stdout) as { result?: { pane?: { pane_id?: string } } };
|
|
646
801
|
const paneId = response.result?.pane?.pane_id;
|
|
@@ -716,8 +871,10 @@ async function startTeammate(
|
|
|
716
871
|
startOptions: ChildStartOptions = {},
|
|
717
872
|
): Promise<void> {
|
|
718
873
|
startOptions.signal?.throwIfAborted();
|
|
719
|
-
// A Pi session has no lock against a second writer, so a restart ends the previous process before it starts the next.
|
|
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.
|
|
720
875
|
await stopRpcTeammate(teammate);
|
|
876
|
+
await closeHerdrPane(teammate);
|
|
877
|
+
if (startOptions.settings) applyTeammateSettings(teammate, startOptions.settings, startOptions.sessionFile);
|
|
721
878
|
teammate.processRecord = { id: crypto.randomUUID(), registered: false, stopRequested: false, quitReported: false };
|
|
722
879
|
if (teammate.transport === "herdr") await attachHerdrTeammate(team, teammate, participants, herdrParentPaneId!, startOptions);
|
|
723
880
|
else attachRpcTeammate(team, teammate, participants, startOptions);
|
|
@@ -760,6 +917,8 @@ function isHerdrPaneNotFound(error: unknown): boolean {
|
|
|
760
917
|
|
|
761
918
|
async function closeHerdrPane(teammate: TeammateState): Promise<void> {
|
|
762
919
|
if (!teammate.paneId) return;
|
|
920
|
+
teammate.processRecord!.stopRequested = true;
|
|
921
|
+
teammate.processRecord!.lifeline?.destroy();
|
|
763
922
|
try {
|
|
764
923
|
await runCommand("herdr", ["pane", "close", teammate.paneId], 10_000);
|
|
765
924
|
} catch (error) {
|
|
@@ -835,11 +994,49 @@ async function shutdownTeam(team: TeamState): Promise<string[]> {
|
|
|
835
994
|
function closeCallbackServerIfUnused(): void {
|
|
836
995
|
if (teams.size > 0 || !callbackServer) return;
|
|
837
996
|
callbackServer.close();
|
|
997
|
+
lifelineServer!.close();
|
|
838
998
|
callbackServer = undefined;
|
|
999
|
+
lifelineServer = undefined;
|
|
839
1000
|
callbackReady = undefined;
|
|
840
1001
|
callbackUrl = "";
|
|
841
1002
|
}
|
|
842
1003
|
|
|
1004
|
+
/**
|
|
1005
|
+
* Accepts one connection per Herdr pane teammate process. Its first line names the teammate and its process id, and its close is that process ending.
|
|
1006
|
+
* A raw socket, because a Bun HTTP server does not report a client that died while its request was open.
|
|
1007
|
+
*/
|
|
1008
|
+
function acceptLifeline(socket: net.Socket): void {
|
|
1009
|
+
socket.on("error", () => undefined);
|
|
1010
|
+
socket.once("data", (hello: Buffer) => {
|
|
1011
|
+
const { token, team: teamId, from, process: processId } = parseLifelineHello(hello);
|
|
1012
|
+
const team = token === callbackToken ? teams.get(String(teamId)) : undefined;
|
|
1013
|
+
const teammate = team?.members.get(String(from));
|
|
1014
|
+
const record = teammate?.processRecord;
|
|
1015
|
+
if (!team || !teammate || !record || record.id !== processId) {
|
|
1016
|
+
socket.destroy();
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
record.lifeline = socket;
|
|
1020
|
+
socket.on("close", () => recordAbruptEnd(team, teammate, record));
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
/** Any local process can connect, so a hello that is not JSON names nobody. */
|
|
1025
|
+
function parseLifelineHello(hello: Buffer): { token?: unknown; team?: unknown; from?: unknown; process?: unknown } {
|
|
1026
|
+
try {
|
|
1027
|
+
return JSON.parse(hello.toString("utf8")) as { token?: unknown; team?: unknown; from?: unknown; process?: unknown };
|
|
1028
|
+
} catch {
|
|
1029
|
+
return {};
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
function listenOnLoopback(server: http.Server | net.Server): Promise<number> {
|
|
1034
|
+
return new Promise<number>((resolve, reject) => {
|
|
1035
|
+
server.once("error", reject);
|
|
1036
|
+
server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port));
|
|
1037
|
+
});
|
|
1038
|
+
}
|
|
1039
|
+
|
|
843
1040
|
async function ensureCallbackServer(): Promise<void> {
|
|
844
1041
|
if (callbackReady) return callbackReady;
|
|
845
1042
|
|
|
@@ -847,15 +1044,11 @@ async function ensureCallbackServer(): Promise<void> {
|
|
|
847
1044
|
void handleCallbackRequest(request, response);
|
|
848
1045
|
});
|
|
849
1046
|
callbackServer = server;
|
|
1047
|
+
lifelineServer = net.createServer(acceptLifeline);
|
|
850
1048
|
|
|
851
|
-
callbackReady =
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
const address = server.address();
|
|
855
|
-
if (!address || typeof address === "string") throw new Error("Team callback server did not get a port");
|
|
856
|
-
callbackUrl = `http://127.0.0.1:${address.port}/callback`;
|
|
857
|
-
resolve();
|
|
858
|
-
});
|
|
1049
|
+
callbackReady = Promise.all([listenOnLoopback(server), listenOnLoopback(lifelineServer)]).then(([callbackPort, port]) => {
|
|
1050
|
+
callbackUrl = `http://127.0.0.1:${callbackPort}/callback`;
|
|
1051
|
+
lifelinePort = port;
|
|
859
1052
|
});
|
|
860
1053
|
return callbackReady;
|
|
861
1054
|
}
|
|
@@ -922,16 +1115,13 @@ function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonR
|
|
|
922
1115
|
if (event.type === "agent_start" || event.type === "work_queued") teammate.active = true;
|
|
923
1116
|
if (event.type === "agent_settled" || event.type === "session_shutdown") teammate.active = false;
|
|
924
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);
|
|
925
1119
|
if (event.type === "runtime_facts") applyRuntimeFacts(teammate, event);
|
|
926
1120
|
if (event.type === "session_shutdown") {
|
|
927
1121
|
teammate.alive = false;
|
|
928
1122
|
teammate.deliveryUrl = undefined;
|
|
929
|
-
if (event.reason === "quit") {
|
|
930
|
-
teammate.processRecord!.quitReported = true;
|
|
931
|
-
team.statuses.set(teammate.name, status("stopped", "Session shut down"));
|
|
932
|
-
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "session shut down", details: { reason: event.reason } });
|
|
933
|
-
}
|
|
934
1123
|
}
|
|
1124
|
+
if (event.type === "session_shutdown" && event.reason === "quit") recordQuit(team, teammate, event.signal);
|
|
935
1125
|
const logInput = normalizeChildEvent(team.name, teammate.name, event);
|
|
936
1126
|
if (logInput) appendTeamLog(team, logInput);
|
|
937
1127
|
if (["agent_start", "work_queued", "agent_settled", "session_shutdown"].includes(String(event.type))) persistActiveTeamManifest(team);
|
|
@@ -977,7 +1167,7 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
977
1167
|
team.statuses.set(teammate.name, status("idle", "Spawned"));
|
|
978
1168
|
teammate.processRecord!.registered = true;
|
|
979
1169
|
teammate.resolveReady?.();
|
|
980
|
-
writeJson(response, 200, { accepted: true, team: team.name, from });
|
|
1170
|
+
writeJson(response, 200, { accepted: true, team: team.name, from, ...(teammate.transport === "herdr" ? { lifelinePort } : {}) });
|
|
981
1171
|
return;
|
|
982
1172
|
}
|
|
983
1173
|
|
|
@@ -1058,6 +1248,15 @@ function teammateSchema(modelGuidance: string) {
|
|
|
1058
1248
|
}, { additionalProperties: false });
|
|
1059
1249
|
}
|
|
1060
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
|
+
|
|
1061
1260
|
function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiCommand: string[], manifest: TeamManifest, lease: TeamLease): TeamState {
|
|
1062
1261
|
const team: TeamState = {
|
|
1063
1262
|
owner,
|
|
@@ -1371,8 +1570,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1371
1570
|
name: "team_resume",
|
|
1372
1571
|
label: "Team Resume",
|
|
1373
1572
|
description: childRuntimeConfig
|
|
1374
|
-
? "Resume all or selected stopped teammates from a current-project team created by your Pi session. Already-running teammates remain as they are."
|
|
1375
|
-
: "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.",
|
|
1376
1575
|
renderShell: "self",
|
|
1377
1576
|
renderCall: (args, theme, context) => renderTeamToolCall("team_resume", args, theme, context, sessionTeammateRoster),
|
|
1378
1577
|
renderResult: (result, options, theme, context) => renderTeamToolResult("team_resume", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
@@ -1383,6 +1582,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1383
1582
|
showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false, description: "Open visible Herdr panes for selected teammates. Defaults to false." })),
|
|
1384
1583
|
startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start resumed teammates idle." })),
|
|
1385
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." })),
|
|
1386
1586
|
}, { additionalProperties: false }),
|
|
1387
1587
|
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
1388
1588
|
signal?.throwIfAborted();
|
|
@@ -1397,6 +1597,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
1397
1597
|
if (existingTeam && existingTeam.owner !== owner) {
|
|
1398
1598
|
throw new Error(`Team ${manifest.id} is already owned by another main session`);
|
|
1399
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
|
+
}
|
|
1400
1605
|
|
|
1401
1606
|
let team = existingTeam;
|
|
1402
1607
|
if (!team) {
|
|
@@ -1436,6 +1641,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1436
1641
|
sessionFile,
|
|
1437
1642
|
restartEmpty: sessionFile === undefined,
|
|
1438
1643
|
signal,
|
|
1644
|
+
settings: updates.get(teammate.name),
|
|
1439
1645
|
});
|
|
1440
1646
|
team.statuses.set(teammate.name, status("idle", "Resumed"));
|
|
1441
1647
|
}
|
|
@@ -1459,7 +1665,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1459
1665
|
throw error;
|
|
1460
1666
|
}
|
|
1461
1667
|
|
|
1462
|
-
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 });
|
|
1463
1669
|
return toolResult({
|
|
1464
1670
|
...lifecycleResult(team),
|
|
1465
1671
|
teammates: [...team.members.values()].map((teammate) => {
|
|
@@ -1549,6 +1755,56 @@ export default function (pi: ExtensionAPI) {
|
|
|
1549
1755
|
}),
|
|
1550
1756
|
);
|
|
1551
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
|
+
|
|
1552
1808
|
pi.registerTool(
|
|
1553
1809
|
defineTool({
|
|
1554
1810
|
name: "team_send_message",
|
|
@@ -1731,10 +1987,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
1731
1987
|
async execute(_toolCallId, params) {
|
|
1732
1988
|
const team = resolveTeam(owner, params.team);
|
|
1733
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
|
+
});
|
|
1734
1994
|
const errors = await shutdownTeam(team);
|
|
1735
1995
|
closeCallbackServerIfUnused();
|
|
1736
1996
|
if (errors.length > 0) throw new Error(`Failed to close Herdr teammate pane(s): ${errors.join("; ")}`);
|
|
1737
|
-
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
|
+
});
|
|
1738
2001
|
},
|
|
1739
2002
|
}),
|
|
1740
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;
|