@giladbarnea/pi-simple-team 2.0.18 β 2.0.20
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 +4 -3
- package/child-tools.ts +11 -0
- package/index.ts +78 -14
- package/model-names.ts +20 -0
- package/package.json +1 -1
- package/render.ts +2 -1
- package/team-briefing.ts +1 -0
- package/team-selection.ts +39 -3
- package/teammate-facts.ts +3 -2
package/README.md
CHANGED
|
@@ -148,7 +148,8 @@ Your main uses `team_log` when it needs to understand the chain of events in hig
|
|
|
148
148
|
|
|
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
|
-
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.
|
|
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. Herdr pane teammates have no exit message yet.
|
|
152
153
|
|
|
153
154
|
### π
Herdr Support
|
|
154
155
|
|
|
@@ -239,7 +240,7 @@ Spawn, resume, and add return the complete roster. Results distinguish a live ru
|
|
|
239
240
|
|
|
240
241
|
Set `showOnHerdrPane: true` on individual teammates to open their panes. An explicit `showOnHerdrPanes` value on spawn overrides all individual settings.
|
|
241
242
|
|
|
242
|
-
`extensionPaths` lists trusted, existing absolute extension paths for one teammate. RPC and Herdr launches load them alongside the team runtime, and resume keeps them.
|
|
243
|
+
`extensionPaths` lists trusted, existing absolute extension paths for one teammate. RPC and Herdr launches load them alongside the team runtime and the extensions a plain `pi` launch in the project discovers, and resume keeps them. The parent's own command-line `-e` extensions and `--no-extensions` are not inherited. An `extensionPaths` entry at a different path from a discovered copy of the same extension stops teammate startup when that extension registers tools or flags. The same path, or a symlink to it, loads once. These modules run with the same permissions as Pi.
|
|
243
244
|
|
|
244
245
|
Message tools return `published: true` when the extension accepts a message for delivery. If delivery later fails, the sender receives the error automatically.
|
|
245
246
|
|
|
@@ -263,7 +264,7 @@ Message tools return `published: true` when the extension accepts a message for
|
|
|
263
264
|
- [x] Resume all or selected teammates from a dormant team.
|
|
264
265
|
- [x] Add teammates after a team has spawned.
|
|
265
266
|
- [x] Let opted-in teammates create and manage teams of their own.
|
|
266
|
-
- [
|
|
267
|
+
- [ ] Remove teammates from a team.
|
|
267
268
|
- [ ] Main triggers `/compact` on select teammate.
|
|
268
269
|
- [ ] Teammates auto-reminded to hand off on low context.
|
|
269
270
|
|
package/child-tools.ts
CHANGED
|
@@ -65,6 +65,17 @@ function readRequiredChildRuntimeConfig(): ChildRuntimeConfig {
|
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
/**
|
|
69
|
+
* A teammate process inherits discovered extensions, so it can also discover an installed copy of this package at another path.
|
|
70
|
+
* Only the copy main passed as PI_SIMPLE_TEAM_RUNTIME_PATH registers; another copy stays inert so their tools cannot conflict.
|
|
71
|
+
* Simulated teammates without that variable load every copy.
|
|
72
|
+
*/
|
|
73
|
+
export function isInertTeamCopy(extensionPath: string): boolean {
|
|
74
|
+
const runtimePath = process.env.PI_SIMPLE_TEAM_RUNTIME_PATH;
|
|
75
|
+
const teammateProcess = process.env.PI_SIMPLE_TEAM_CHILD === "1" || process.env.PI_SIMPLE_TEAM_CHILD === String(process.pid);
|
|
76
|
+
return teammateProcess && runtimePath !== undefined && runtimePath !== extensionPath;
|
|
77
|
+
}
|
|
78
|
+
|
|
68
79
|
/**
|
|
69
80
|
* Main marks only the process it starts with PI_SIMPLE_TEAM_CHILD=1. That process claims the teammate identity for its PID, which
|
|
70
81
|
* survives Pi's in-process reloads and session replacements. Subprocesses inherit the environment, not the claim, so they run as main.
|
package/index.ts
CHANGED
|
@@ -7,10 +7,11 @@ import * as path from "node:path";
|
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import { defineTool, type ContextUsage, type ExtensionAPI, type ExtensionContext, getMarkdownTheme, getPackageDir } from "@earendil-works/pi-coding-agent";
|
|
9
9
|
import { formatContextWindowReport, requireKnownContextUsage, type KnownContextUsage } from "./context-window.ts";
|
|
10
|
+
import { useModelNames } from "./model-names.ts";
|
|
10
11
|
import { formatScopedModelGuidance, validateTeammateModels, type ModelReference } from "./model-preflight.ts";
|
|
11
12
|
import { composeTeamBriefing } from "./team-briefing.ts";
|
|
12
13
|
import { composeResumptionMessage } from "./resume-message.ts";
|
|
13
|
-
import { callParent, readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
|
|
14
|
+
import { callParent, isInertTeamCopy, readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
|
|
14
15
|
import {
|
|
15
16
|
canonicalProjectDirectory,
|
|
16
17
|
claimTeamLease,
|
|
@@ -29,7 +30,7 @@ import { renderReminderToolCall, renderReminderToolResult, renderTeamMessage, re
|
|
|
29
30
|
import { openTeamOverview, type TeamSnapshot } from "./team-ui.ts";
|
|
30
31
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
31
32
|
import { Type } from "typebox";
|
|
32
|
-
import { resolveTargets, resolveTeammates, interruptedTeammateIds, targetDescription, interruptDescription, type SelectableTeam } from "./team-selection.ts";
|
|
33
|
+
import { resolveTargets, resolveTeammates, interruptedTeammateIds, findUnknownTarget, unknownTargetMessage, targetDescription, interruptDescription, type DormantTeammateMatch, type SelectableTeam } from "./team-selection.ts";
|
|
33
34
|
import type { Teammate, TeammateRecord, ThinkingLevel } from "./teammate.ts";
|
|
34
35
|
|
|
35
36
|
type JsonRecord = Record<string, unknown>;
|
|
@@ -48,6 +49,13 @@ interface RunFailure {
|
|
|
48
49
|
replaced: TeamStatus;
|
|
49
50
|
}
|
|
50
51
|
|
|
52
|
+
/** What one background child process has done. Its exit handler judges that process only, even after a resume starts another. */
|
|
53
|
+
interface RpcProcessRecord {
|
|
54
|
+
registered: boolean;
|
|
55
|
+
stopRequested: boolean;
|
|
56
|
+
quitReported: boolean;
|
|
57
|
+
}
|
|
58
|
+
|
|
51
59
|
interface TeammateState {
|
|
52
60
|
name: string;
|
|
53
61
|
prompt: string;
|
|
@@ -62,6 +70,7 @@ interface TeammateState {
|
|
|
62
70
|
sessionMaterialized: boolean;
|
|
63
71
|
lastModelActivityAt?: string;
|
|
64
72
|
process?: ChildProcess;
|
|
73
|
+
processRecord?: RpcProcessRecord;
|
|
65
74
|
paneId?: string;
|
|
66
75
|
deliveryUrl?: string;
|
|
67
76
|
ready?: Promise<void>;
|
|
@@ -92,6 +101,7 @@ interface TeamState {
|
|
|
92
101
|
lease?: TeamLease;
|
|
93
102
|
log: TeamLogEntry[];
|
|
94
103
|
nextLogSequence: number;
|
|
104
|
+
stopping?: boolean;
|
|
95
105
|
}
|
|
96
106
|
|
|
97
107
|
const teamLiteExtensionPath = fileURLToPath(import.meta.url);
|
|
@@ -99,6 +109,8 @@ const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
|
99
109
|
const defaultThinkingLevel = "xhigh" satisfies ThinkingLevel;
|
|
100
110
|
const deliveryTimeoutMilliseconds = 30_000;
|
|
101
111
|
const defaultRpcShutdownGraceMilliseconds = 1_000;
|
|
112
|
+
/** Time for main's own shutdown to mark its teams before an exit notice is sent, for signals that reach main and its teammates together. */
|
|
113
|
+
const exitNoticeGraceMilliseconds = 2_000;
|
|
102
114
|
const teamMessageType = "pi-simple-team";
|
|
103
115
|
const teams = new Map<string, TeamState>();
|
|
104
116
|
const callbackToken = crypto.randomBytes(24).toString("hex");
|
|
@@ -333,10 +345,7 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
|
|
|
333
345
|
const notification = `Message delivery failed for teammate "${recipient.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}).\nOriginal message:\n${message}\nCause: ${errorMessage}\nCheck the teammate's status before retrying.`;
|
|
334
346
|
try {
|
|
335
347
|
if (from === "main") {
|
|
336
|
-
team
|
|
337
|
-
{ customType: teamMessageType, content: notification, display: true, details: { team: team.name, from: "runtime", sentAt: new Date().toISOString(), message: notification } },
|
|
338
|
-
{ deliverAs: "steer", triggerTurn: true },
|
|
339
|
-
);
|
|
348
|
+
pushOwnerNotice(team, notification);
|
|
340
349
|
return;
|
|
341
350
|
}
|
|
342
351
|
await deliverToTeammate(team, "runtime", team.members.get(from)!, notification, false);
|
|
@@ -346,6 +355,40 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
|
|
|
346
355
|
});
|
|
347
356
|
}
|
|
348
357
|
|
|
358
|
+
/** Wakes the team owner with a runtime notice. */
|
|
359
|
+
function pushOwnerNotice(team: TeamState, notification: string): void {
|
|
360
|
+
team.ownerPi.sendMessage(
|
|
361
|
+
{ customType: teamMessageType, content: notification, display: true, details: { team: team.name, from: "runtime", sentAt: new Date().toISOString(), message: notification } },
|
|
362
|
+
{ deliverAs: "steer", triggerTurn: true },
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** A failed run or an exit has no sender, so its notice goes to the team owner. A push that throws becomes an error row. */
|
|
367
|
+
function notifyOwner(team: TeamState, teammate: TeammateState, notification: string): void {
|
|
368
|
+
try {
|
|
369
|
+
pushOwnerNotice(team, notification);
|
|
370
|
+
} catch (error) {
|
|
371
|
+
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "error", summary: preview(`Could not notify main about ${teammate.name}: ${error instanceof Error ? error.message : String(error)}`) });
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* A notice for an exit nobody asked for. A self-quit (code 0 after a quit shutdown) and a stop by the parent are excluded.
|
|
377
|
+
* @example isUnexpectedExit({ registered: true, stopRequested: false, quitReported: true }, 143, null) // true
|
|
378
|
+
*/
|
|
379
|
+
function isUnexpectedExit(record: RpcProcessRecord, code: number | null, signal: NodeJS.Signals | null): boolean {
|
|
380
|
+
const selfQuit = code === 0 && signal === null && record.quitReported;
|
|
381
|
+
return record.registered && !record.stopRequested && !selfQuit;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Waits for main's own shutdown to mark the team first, so a signal that reaches main and its teammates together sends nothing. */
|
|
385
|
+
function scheduleExitNotice(team: TeamState, teammate: TeammateState, code: number | null, signal: NodeJS.Signals | null): void {
|
|
386
|
+
setTimeout(() => {
|
|
387
|
+
if (team.stopping || teams.get(team.id ?? team.name) !== team) return;
|
|
388
|
+
notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) exited.\nCause: exited (code=${code}, signal=${signal})\nCode 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.`);
|
|
389
|
+
}, exitNoticeGraceMilliseconds).unref();
|
|
390
|
+
}
|
|
391
|
+
|
|
349
392
|
async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[] }): Promise<void> {
|
|
350
393
|
const outcomes = await Promise.allSettled(teammates.map((teammate) => {
|
|
351
394
|
const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
|
|
@@ -514,6 +557,7 @@ function createTeammateState(teammateSpec: Teammate): TeammateState {
|
|
|
514
557
|
function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, participants: string[]): Record<string, string> {
|
|
515
558
|
return {
|
|
516
559
|
PI_SIMPLE_TEAM_CHILD: "1",
|
|
560
|
+
PI_SIMPLE_TEAM_RUNTIME_PATH: teamLiteExtensionPath,
|
|
517
561
|
PI_SIMPLE_TEAM_CALLBACK_URL: callbackUrl,
|
|
518
562
|
PI_SIMPLE_TEAM_CALLBACK_TOKEN: callbackToken,
|
|
519
563
|
PI_SIMPLE_TEAM_TEAM: team.id ?? team.name,
|
|
@@ -560,7 +604,6 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
560
604
|
"--mode",
|
|
561
605
|
"rpc",
|
|
562
606
|
...sessionArgs,
|
|
563
|
-
"--no-extensions",
|
|
564
607
|
"-e",
|
|
565
608
|
teamLiteExtensionPath,
|
|
566
609
|
...teammate.extensionPaths.flatMap(extensionPath => ["-e", extensionPath]),
|
|
@@ -574,7 +617,9 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
574
617
|
stdio: ["pipe", "ignore", "pipe"],
|
|
575
618
|
env: { ...process.env, ...childEnvironmentOverrides(team, teammate, participants) },
|
|
576
619
|
});
|
|
620
|
+
const record: RpcProcessRecord = { registered: false, stopRequested: false, quitReported: false };
|
|
577
621
|
teammate.process = proc;
|
|
622
|
+
teammate.processRecord = record;
|
|
578
623
|
teammate.alive = true;
|
|
579
624
|
|
|
580
625
|
proc.stderr?.on("data", (chunk: Buffer | string) => {
|
|
@@ -586,6 +631,7 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
586
631
|
teammate.rejectReady?.(new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
|
|
587
632
|
team.statuses.set(teammate.name, status("stopped", `Exited code=${code} signal=${signal}`));
|
|
588
633
|
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `exited (code=${code}, signal=${signal})`, details: { code, signal } });
|
|
634
|
+
if (isUnexpectedExit(record, code, signal)) scheduleExitNotice(team, teammate, code, signal);
|
|
589
635
|
});
|
|
590
636
|
appendSpawnLog(team, teammate);
|
|
591
637
|
}
|
|
@@ -625,7 +671,6 @@ async function attachHerdrTeammate(
|
|
|
625
671
|
const command = [
|
|
626
672
|
...team.parentPiCommand,
|
|
627
673
|
...sessionArgs,
|
|
628
|
-
"--no-extensions",
|
|
629
674
|
"-e",
|
|
630
675
|
teamLiteExtensionPath,
|
|
631
676
|
...teammate.extensionPaths.flatMap(extensionPath => ["-e", extensionPath]),
|
|
@@ -726,6 +771,7 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
|
|
|
726
771
|
resolve();
|
|
727
772
|
};
|
|
728
773
|
processToStop.once("exit", resolveExit);
|
|
774
|
+
teammate.processRecord!.stopRequested = true;
|
|
729
775
|
processToStop.kill("SIGTERM");
|
|
730
776
|
if (!teammate.canManageOwnTeams) {
|
|
731
777
|
forceKillTimeout = setTimeout(() => processToStop.kill("SIGKILL"), defaultRpcShutdownGraceMilliseconds);
|
|
@@ -736,6 +782,7 @@ async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
|
|
|
736
782
|
}
|
|
737
783
|
|
|
738
784
|
async function shutdownTeam(team: TeamState): Promise<string[]> {
|
|
785
|
+
team.stopping = true;
|
|
739
786
|
const errors: string[] = [];
|
|
740
787
|
for (const teammate of team.members.values()) {
|
|
741
788
|
if (teammate.transport === "herdr") {
|
|
@@ -855,6 +902,7 @@ function recordRunOutcome(team: TeamState, teammate: TeammateState, event: JsonR
|
|
|
855
902
|
teammate.runFailure = { failure, replaced: current === teammate.runFailure?.failure ? teammate.runFailure.replaced : current };
|
|
856
903
|
team.statuses.set(teammate.name, failure);
|
|
857
904
|
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "error", summary: preview(`${teammate.name} run failed: ${errorMessage}`), details: { error: errorMessage } });
|
|
905
|
+
notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) ended its latest run on an error.\nCause: ${errorMessage}\nEarlier steps of that run may have completed. Check the teammate's status and team_log before sending it more work.`);
|
|
858
906
|
return;
|
|
859
907
|
}
|
|
860
908
|
if (event.outcome !== "completed" || !teammate.runFailure) return;
|
|
@@ -871,6 +919,7 @@ function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonR
|
|
|
871
919
|
teammate.alive = false;
|
|
872
920
|
teammate.deliveryUrl = undefined;
|
|
873
921
|
if (event.reason === "quit") {
|
|
922
|
+
if (teammate.processRecord) teammate.processRecord.quitReported = true;
|
|
874
923
|
team.statuses.set(teammate.name, status("stopped", "Session shut down"));
|
|
875
924
|
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "session shut down", details: { reason: event.reason } });
|
|
876
925
|
}
|
|
@@ -917,6 +966,7 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
917
966
|
teammate.alive = true;
|
|
918
967
|
teammate.active = false;
|
|
919
968
|
team.statuses.set(teammate.name, status("idle", "Spawned"));
|
|
969
|
+
if (teammate.processRecord) teammate.processRecord.registered = true;
|
|
920
970
|
teammate.resolveReady?.();
|
|
921
971
|
writeJson(response, 200, { accepted: true, team: team.name, from });
|
|
922
972
|
return;
|
|
@@ -995,7 +1045,7 @@ function teammateSchema(modelGuidance: string) {
|
|
|
995
1045
|
forkContext: Type.Optional(Type.Boolean({ description: "Start as a fork of your context window rather than fresh. Defaults to false.", default: false })),
|
|
996
1046
|
canManageOwnTeams: Type.Optional(Type.Boolean({ description: "Allow this teammate to create and manage teams of its own. Defaults to false.", default: false })),
|
|
997
1047
|
showOnHerdrPane: Type.Optional(Type.Boolean({ description: "Open a visible Herdr pane for this teammate. Defaults to false.", default: false })),
|
|
998
|
-
extensionPaths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { uniqueItems: true, description: "Trusted extension files or directories to load alongside the team runtime. Use existing absolute paths. Saved for later resume; discovered extensions
|
|
1048
|
+
extensionPaths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { uniqueItems: true, description: "Trusted extension files or directories to load alongside the team runtime. Use existing absolute paths. Saved for later resume; discovered extensions also load." })),
|
|
999
1049
|
}, { additionalProperties: false });
|
|
1000
1050
|
}
|
|
1001
1051
|
|
|
@@ -1061,6 +1111,7 @@ function piCommand(entry: string, runtime: string, packageDirectory: string): st
|
|
|
1061
1111
|
}
|
|
1062
1112
|
|
|
1063
1113
|
export default function (pi: ExtensionAPI) {
|
|
1114
|
+
if (isInertTeamCopy(teamLiteExtensionPath)) return;
|
|
1064
1115
|
const childRuntimeConfig = readChildRuntimeConfig();
|
|
1065
1116
|
if (childRuntimeConfig) {
|
|
1066
1117
|
registerChildTools(pi, childRuntimeConfig);
|
|
@@ -1083,6 +1134,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
1083
1134
|
);
|
|
1084
1135
|
}
|
|
1085
1136
|
|
|
1137
|
+
/** Stored dormant teammates of resumable current-project teams whose name or session ID is `identifier`. */
|
|
1138
|
+
function dormantTeammateMatches(context: ExtensionContext, identifier: string): DormantTeammateMatch[] {
|
|
1139
|
+
const name = identifier.trim();
|
|
1140
|
+
return resumableTeamManifests(context, "team_send_message")
|
|
1141
|
+
.filter((manifest) => manifest.state === "dormant")
|
|
1142
|
+
.flatMap((manifest) => manifest.members
|
|
1143
|
+
.filter((member) => member.name === name || member.teammateId === name)
|
|
1144
|
+
.map((member) => ({ teamId: manifest.id, teammateId: member.teammateId })));
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1086
1147
|
pi.registerMessageRenderer(teamMessageType, (message, options, theme) => renderTeamMessage(message, options, theme, getMarkdownTheme(), sessionTeammateRoster));
|
|
1087
1148
|
|
|
1088
1149
|
pi.registerCommand("team", {
|
|
@@ -1095,20 +1156,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
1095
1156
|
pi.on("session_shutdown", async () => {
|
|
1096
1157
|
for (const timer of reminderTimers) clearTimeout(timer);
|
|
1097
1158
|
reminderTimers.clear();
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1159
|
+
const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
|
|
1160
|
+
for (const team of ownedTeams) team.stopping = true;
|
|
1161
|
+
for (const team of ownedTeams) await shutdownTeam(team);
|
|
1101
1162
|
closeCallbackServerIfUnused();
|
|
1102
1163
|
});
|
|
1103
1164
|
|
|
1104
1165
|
pi.on("session_start", (_event, context) => {
|
|
1166
|
+
useModelNames(context.modelRegistry);
|
|
1105
1167
|
const scopedModels = (context as typeof context & { scopedModels?: ReadonlyArray<{ model: ModelReference }> }).scopedModels ?? [];
|
|
1106
1168
|
const modelGuidance = formatScopedModelGuidance(scopedModels.map(({ model }) => model));
|
|
1107
1169
|
pi.registerTool(
|
|
1108
1170
|
defineTool({
|
|
1109
1171
|
name: "team_spawn",
|
|
1110
1172
|
label: "Team Spawn",
|
|
1111
|
-
description: "Spawn a versatile team of agents. You are automatically part of the team as main. Do not include yourself in teammates. Use `team_resume` to continue an existing team, or `team_add_teammates` to grow one.",
|
|
1173
|
+
description: "Spawn a versatile team of agents. It can also be used as a regular background agent spawn in a one-person team. You are automatically part of the team as main. Do not include yourself in teammates. Use `team_resume` to continue an existing team, or `team_add_teammates` to grow one.",
|
|
1112
1174
|
renderShell: "self",
|
|
1113
1175
|
renderCall: (args, theme, context) => renderTeamToolCall("team_spawn", args, theme, context, sessionTeammateRoster),
|
|
1114
1176
|
renderResult: (result, options, theme, context) => renderTeamToolResult("team_spawn", result, options, theme, context, getMarkdownTheme(), sessionTeammateRoster),
|
|
@@ -1494,9 +1556,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
1494
1556
|
message: Type.String({ description: "Message to send" }),
|
|
1495
1557
|
interrupt: Type.Optional(Type.Union([Type.Boolean(), Type.Array(Type.String({ minLength: 1 }))], { description: interruptDescription })),
|
|
1496
1558
|
}, { additionalProperties: false }),
|
|
1497
|
-
async execute(_toolCallId, params, signal) {
|
|
1559
|
+
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
1498
1560
|
const parent = childRuntimeConfig ? await callParent(childRuntimeConfig, "team_context", {}, signal) as unknown as SelectableTeam : undefined;
|
|
1499
1561
|
const candidates = [...ownedTargetTeams(owner), ...(parent ? [parent] : [])];
|
|
1562
|
+
const unknownTarget = findUnknownTarget(candidates, params.targets);
|
|
1563
|
+
if (unknownTarget !== undefined) throw new Error(unknownTargetMessage(unknownTarget, candidates, dormantTeammateMatches(context, unknownTarget)));
|
|
1500
1564
|
const selections = resolveTargets(candidates, params.targets);
|
|
1501
1565
|
const interrupted = interruptedTeammateIds(candidates, selections, params.interrupt);
|
|
1502
1566
|
const statuses: JsonRecord[] = [];
|
package/model-names.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
type ModelNameSource = Pick<ModelRegistry, "find">;
|
|
4
|
+
|
|
5
|
+
let modelNameSource: ModelNameSource | undefined;
|
|
6
|
+
|
|
7
|
+
/** Team screens read model names from the session's Pi model registry, which session_start provides. */
|
|
8
|
+
export function useModelNames(registry: ModelNameSource): void {
|
|
9
|
+
modelNameSource = registry;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Pi's name for a "provider/id" model, for human-facing team screens only: the user's models.json name, else the built-in name.
|
|
14
|
+
* Undefined when Pi does not know the model or no session has started.
|
|
15
|
+
* @example piModelName("anthropic/claude-opus-5-5") // "opus" under a models.json name override
|
|
16
|
+
*/
|
|
17
|
+
export function piModelName(model: string): string | undefined {
|
|
18
|
+
const slash = model.indexOf("/");
|
|
19
|
+
return modelNameSource?.find(model.slice(0, slash), model.slice(slash + 1))?.name;
|
|
20
|
+
}
|
package/package.json
CHANGED
package/render.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { padVisible, stableRenderWidth, visibleLength } from "./render-support/a
|
|
|
4
4
|
import { glyphs } from "./render-support/glyphs.ts";
|
|
5
5
|
import { stackPrefix, toolLabel, treeConnector, treeStem } from "./render-support/theme.ts";
|
|
6
6
|
import { commandExit, plural, renderPendingCall, textContent } from "./render-support/text.ts";
|
|
7
|
+
import { piModelName } from "./model-names.ts";
|
|
7
8
|
import { futureTime, logRowTime, monthDay, relativeTime, timeOfDay, type TeamLogEntry } from "./teamlog.ts";
|
|
8
9
|
import { actorHueToken, DIM_SGR_CLOSE, DIM_SGR_OPEN, FactTable, inlineFact, statusWordToken, type FactRow, type TeammateView } from "./teammate-facts.ts";
|
|
9
10
|
|
|
@@ -570,7 +571,7 @@ export function foldLogEntries(entries: TeamLogEntry[]): LogAction[] {
|
|
|
570
571
|
icon: "diamond",
|
|
571
572
|
iconToken: "borderMuted",
|
|
572
573
|
action: "spawn",
|
|
573
|
-
details: [textDetail(typeof details.model === "string" ? details.model : ""), textDetail(typeof details.thinking === "string" ? details.thinking : "")],
|
|
574
|
+
details: [textDetail(typeof details.model === "string" ? piModelName(details.model) ?? details.model : ""), textDetail(typeof details.thinking === "string" ? details.thinking : "")],
|
|
574
575
|
});
|
|
575
576
|
continue;
|
|
576
577
|
}
|
package/team-briefing.ts
CHANGED
|
@@ -12,6 +12,7 @@ export function composeTeamBriefing(
|
|
|
12
12
|
`<your-specific-system-message>\n${teammatePrompt.trim()}\n</your-specific-system-message>`,
|
|
13
13
|
`You are ${teammateName}, a teammate on team ${teamName}.`,
|
|
14
14
|
"Work on your current team assignment. Treat inherited conversation as background for this assignment.",
|
|
15
|
+
"Do not use tools meant for interaction with a human.",
|
|
15
16
|
`Participants: main, ${participants.join(", ")}.`,
|
|
16
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.",
|
|
17
18
|
"The main agent is the current coordinator. Use the team tools and available session history to share relevant context.",
|
package/team-selection.ts
CHANGED
|
@@ -10,6 +10,11 @@ export interface TeamSelection {
|
|
|
10
10
|
wholeTeam: boolean;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
export interface DormantTeammateMatch {
|
|
14
|
+
teamId: string;
|
|
15
|
+
teammateId: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
13
18
|
export const targetDescription = "Team or teammate names or IDs. A team selects all its teammates. Names must be unique in your available teams. Use IDs to resolve duplicate names. Overlapping selections count once.";
|
|
14
19
|
export const interruptDescription = "True interrupts all selected recipients. A list uses the same names or IDs as targets and must select only message recipients. False or omitted interrupts none.";
|
|
15
20
|
|
|
@@ -28,12 +33,43 @@ export function resolveTeammates<Member extends { name: string; teammateId: stri
|
|
|
28
33
|
return [...new Set(identifiers.map((identifier) => resolveNamedId(candidates, identifier, "teammates").teammate))];
|
|
29
34
|
}
|
|
30
35
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const candidates = teams.flatMap((team) => [
|
|
36
|
+
function targetCandidates(teams: readonly SelectableTeam[]) {
|
|
37
|
+
return teams.flatMap((team) => [
|
|
34
38
|
{ name: team.teamName, id: team.teamId, team, teammate: undefined },
|
|
35
39
|
...team.teammates.map((teammate) => ({ name: teammate.name, id: teammate.teammateId, team, teammate })),
|
|
36
40
|
]);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** @example findUnknownTarget([{ teamName: "review", teamId: "team-1", teammates: [] }], ["review", "scout"]) // "scout" */
|
|
44
|
+
export function findUnknownTarget(teams: readonly SelectableTeam[], identifiers: readonly string[]): string | undefined {
|
|
45
|
+
const candidates = targetCandidates(teams);
|
|
46
|
+
return identifiers.find((identifier) => !candidates.some((candidate) => candidate.id === identifier.trim() || candidate.name === identifier.trim()));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Recovery guidance for a target that matches no available team or teammate, given the stored dormant teammates it matches.
|
|
51
|
+
* @example unknownTargetMessage("scout", [], [{ teamId: "team-1", teammateId: "session-1" }]).split("\n")[1] // "Team: team-1"
|
|
52
|
+
*/
|
|
53
|
+
export function unknownTargetMessage(identifier: string, teams: readonly SelectableTeam[], dormantMatches: readonly DormantTeammateMatch[]): string {
|
|
54
|
+
const name = JSON.stringify(identifier);
|
|
55
|
+
if (dormantMatches.length === 1) return [
|
|
56
|
+
`Teammate ${name} belongs to a dormant team.`,
|
|
57
|
+
`Team: ${dormantMatches[0].teamId}`,
|
|
58
|
+
`Teammate: ${dormantMatches[0].teammateId}`,
|
|
59
|
+
"Resume this teammate with team_resume, then retry team_send_message.",
|
|
60
|
+
].join("\n");
|
|
61
|
+
if (dormantMatches.length > 1) return [
|
|
62
|
+
`Teammate ${name} matches more than one dormant teammate. Choose one:`,
|
|
63
|
+
...dormantMatches.map((match) => `Team: ${match.teamId}, Teammate: ${match.teammateId}`),
|
|
64
|
+
"Resume the intended teammate with team_resume, then retry team_send_message.",
|
|
65
|
+
].join("\n");
|
|
66
|
+
const choices = targetCandidates(teams).map(({ name, id }) => ({ name, id }));
|
|
67
|
+
return `Unknown target ${name}. Available choices: ${JSON.stringify(choices)}. No active target matches. Use team_list to find active or dormant teams; resume the intended teammate before retrying.`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** @example resolveTargets([{ teamName: "review", teamId: "team-1", teammates: [{ name: "scout", teammateId: "session-1" }] }], ["review", "session-1"])[0].teammates.length // 1 */
|
|
71
|
+
export function resolveTargets(teams: readonly SelectableTeam[], identifiers: readonly string[]): TeamSelection[] {
|
|
72
|
+
const candidates = targetCandidates(teams);
|
|
37
73
|
const selected = new Map<string, TeamSelection>();
|
|
38
74
|
for (const identifier of identifiers) {
|
|
39
75
|
const match = resolveNamedId(candidates, identifier, "targets");
|
package/teammate-facts.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
|
3
3
|
import { padVisible } from "./render-support/ansi.ts";
|
|
4
4
|
import { glyphs, glyphStyle } from "./render-support/glyphs.ts";
|
|
5
5
|
import { contextGauge, contextHeat, type HeatTheme } from "./render-support/heat.ts";
|
|
6
|
+
import { piModelName } from "./model-names.ts";
|
|
6
7
|
|
|
7
8
|
export interface FactTheme extends HeatTheme {
|
|
8
9
|
bold(text: string): string;
|
|
@@ -111,8 +112,8 @@ const LADDERS: Record<FactKey, Ladder> = {
|
|
|
111
112
|
},
|
|
112
113
|
status: { full: (row, paint) => (row.status ? paint.theme.fg(statusWordToken(row.status), row.status) : "") },
|
|
113
114
|
model: {
|
|
114
|
-
full: (row, paint) => (row.model ? paint.theme.fg("muted", row.model) : ""),
|
|
115
|
-
short: (row, paint) => (row.model ? paint.theme.fg("muted", modelTail(row.model)) : ""),
|
|
115
|
+
full: (row, paint) => (row.model ? paint.theme.fg("muted", piModelName(row.model) ?? row.model) : ""),
|
|
116
|
+
short: (row, paint) => (row.model ? paint.theme.fg("muted", piModelName(row.model) ?? modelTail(row.model)) : ""),
|
|
116
117
|
},
|
|
117
118
|
context: { full: context("context"), short: context("ctx"), bare: context("ctx", false), icon: context("") },
|
|
118
119
|
fork: flag("forkContext", { full: "β fork", short: "β fork", bare: "fork", icon: "β" }),
|