@giladbarnea/pi-simple-team 2.0.2 → 2.0.3
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 +7 -2
- package/child-tools.ts +22 -21
- package/index.ts +81 -47
- package/package.json +2 -2
- package/render-support/heat.ts +60 -0
- package/render.ts +127 -112
- package/resume-message.ts +27 -0
- package/screenshots/team-view.png +0 -0
- package/{system-prompt.ts → team-briefing.ts} +5 -3
- package/team-registry.ts +45 -16
- package/team-ui.ts +16 -30
- package/teamlog.ts +6 -1
- package/teammate-facts.ts +194 -0
- package/teammate.ts +4 -2
package/README.md
CHANGED
|
@@ -38,6 +38,8 @@ Not scheduling a meeting.
|
|
|
38
38
|
|
|
39
39
|
## Install
|
|
40
40
|
|
|
41
|
+
Requires Pi 1.1.0 or newer.
|
|
42
|
+
|
|
41
43
|
```sh
|
|
42
44
|
pi install npm:@giladbarnea/pi-simple-team
|
|
43
45
|
```
|
|
@@ -146,6 +148,7 @@ You can stop babysitting context windows.
|
|
|
146
148
|
Your main uses `team_log` when it needs to understand the chain of events in high granularity.
|
|
147
149
|
|
|
148
150
|
Provides main a timestamped, filterable, append-only record of the team’s messages, tool calls, and lifecycle events.
|
|
151
|
+
Attempts can end before retries finish. A separate run row reports final settlement as ended or cancelled. Ended does not imply success.
|
|
149
152
|
|
|
150
153
|
### 🌅 Herdr Support
|
|
151
154
|
|
|
@@ -220,9 +223,11 @@ Kept minimal:
|
|
|
220
223
|
| | On self | `get_context_window_usage` |
|
|
221
224
|
| **Everyone** | For everyone | `team_status` |
|
|
222
225
|
|
|
223
|
-
`team_spawn`, `team_resume`, and `team_add_teammates` start work automatically once every affected teammate is ready.
|
|
226
|
+
`team_spawn`, `team_resume`, and `team_add_teammates` start work automatically once every affected teammate is ready. With `startIdle: true`, their briefings wait in context without starting work.
|
|
227
|
+
|
|
228
|
+
Startup delivers `commonPrompt` inside `<team-system-message>` and each teammate's `systemPrompt` inside `<your-specific-system-message>`. These are labels in the custom team message, not system-role overrides. The briefing also contains the teammate's identity and coordination guidance.
|
|
224
229
|
|
|
225
|
-
|
|
230
|
+
Resume appends a custom briefing with the team identity, current time, and last recorded model activity. Optional `resumptionPrompt` instructions follow that briefing without changing saved definitions. With `startIdle: true`, the briefing waits in context for the next turn.
|
|
226
231
|
|
|
227
232
|
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.
|
|
228
233
|
|
package/child-tools.ts
CHANGED
|
@@ -2,6 +2,8 @@ import * as http from "node:http";
|
|
|
2
2
|
import { defineTool, getMarkdownTheme, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { Type } from "typebox";
|
|
4
4
|
import { formatContextWindowReport, requireKnownContextUsage } from "./context-window.ts";
|
|
5
|
+
import { formatModelReference } from "./model-preflight.ts";
|
|
6
|
+
import { lastRecordedModelActivity } from "./resume-message.ts";
|
|
5
7
|
import { renderTeamMessage } from "./render.ts";
|
|
6
8
|
import { targetDescription, interruptDescription } from "./team-selection.ts";
|
|
7
9
|
|
|
@@ -98,6 +100,15 @@ async function readJsonBody(request: http.IncomingMessage): Promise<JsonRecord>
|
|
|
98
100
|
return JSON.parse(Buffer.concat(chunks).toString("utf8")) as JsonRecord;
|
|
99
101
|
}
|
|
100
102
|
|
|
103
|
+
/** The model, thinking level, and context usage the child actually runs with. Pi may clamp the requested thinking level to the model. */
|
|
104
|
+
function runtimeFacts(context: ExtensionContext): JsonRecord {
|
|
105
|
+
return {
|
|
106
|
+
model: formatModelReference(context.model!),
|
|
107
|
+
thinking: context.thinkingLevel!,
|
|
108
|
+
contextPercent: context.getContextUsage()?.percent ?? null,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
101
112
|
interface ChildDelivery {
|
|
102
113
|
team: string;
|
|
103
114
|
from: string;
|
|
@@ -165,10 +176,16 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
|
165
176
|
pi.on("agent_end", (event) => {
|
|
166
177
|
notifyParent({ type: "agent_end", messages: event.messages });
|
|
167
178
|
});
|
|
168
|
-
pi.on("agent_settled", () => {
|
|
169
|
-
notifyParent({ type: "agent_settled" });
|
|
179
|
+
pi.on("agent_settled", (event) => {
|
|
180
|
+
notifyParent({ type: "agent_settled", aborted: event.aborted });
|
|
170
181
|
markIdle();
|
|
171
182
|
});
|
|
183
|
+
const reportRuntimeFacts = (context: ExtensionContext): Promise<void> => notifyParent({ type: "runtime_facts", ...runtimeFacts(context) });
|
|
184
|
+
pi.on("turn_end", (_event, context) => { void reportRuntimeFacts(context); });
|
|
185
|
+
pi.on("session_compact", (_event, context) => { void reportRuntimeFacts(context); });
|
|
186
|
+
pi.on("model_select", (_event, context) => { void reportRuntimeFacts(context); });
|
|
187
|
+
pi.on("thinking_level_select", (_event, context) => { void reportRuntimeFacts(context); });
|
|
188
|
+
pi.on("session_tree", (_event, context) => { void reportRuntimeFacts(context); });
|
|
172
189
|
pi.on("tool_execution_start", (event) => {
|
|
173
190
|
notifyParent({ type: "tool_execution_start", toolCallId: event.toolCallId, toolName: event.toolName, args: event.args });
|
|
174
191
|
});
|
|
@@ -218,6 +235,7 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
|
218
235
|
},
|
|
219
236
|
{ deliverAs: "steer", triggerTurn: delivery.triggerTurn !== false },
|
|
220
237
|
);
|
|
238
|
+
await reportRuntimeFacts(context);
|
|
221
239
|
writeJson(response, 200, { accepted: true, team: config.teamName, from: delivery.from, to: delivery.to, interrupt: delivery.interrupt });
|
|
222
240
|
} catch (error) {
|
|
223
241
|
writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
@@ -237,6 +255,8 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
|
237
255
|
url: `http://127.0.0.1:${address.port}/deliver`,
|
|
238
256
|
sessionId: context.sessionManager.getSessionId(),
|
|
239
257
|
sessionFile: context.sessionManager.getSessionFile(),
|
|
258
|
+
lastModelActivityAt: lastRecordedModelActivity(context.sessionManager.getBranch()),
|
|
259
|
+
...runtimeFacts(context),
|
|
240
260
|
});
|
|
241
261
|
} catch (error) {
|
|
242
262
|
context.shutdown();
|
|
@@ -259,25 +279,6 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
|
259
279
|
|
|
260
280
|
export function registerChildTools(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
261
281
|
pi.registerMessageRenderer(teamMessageType, (message, options, theme) => renderTeamMessage(message, options, theme, getMarkdownTheme(), config.participants));
|
|
262
|
-
const startupRosterInstruction = `Participants: main, ${config.participants.join(", ")}.`;
|
|
263
|
-
pi.on("before_agent_start", async (event, context) => {
|
|
264
|
-
const teamContext = await callParent(config, "team_context", {}, context.signal);
|
|
265
|
-
const rawParticipants: unknown = teamContext.participants;
|
|
266
|
-
if (!Array.isArray(rawParticipants) || rawParticipants.some((participant: unknown) => typeof participant !== "string")) {
|
|
267
|
-
throw new Error("team runtime returned an invalid participant list");
|
|
268
|
-
}
|
|
269
|
-
const participants = rawParticipants as string[];
|
|
270
|
-
if (!event.systemPrompt.includes(startupRosterInstruction)) {
|
|
271
|
-
throw new Error("team runtime could not find its startup roster instruction");
|
|
272
|
-
}
|
|
273
|
-
config.participants.splice(0, config.participants.length, ...participants);
|
|
274
|
-
return {
|
|
275
|
-
systemPrompt: event.systemPrompt.replace(
|
|
276
|
-
startupRosterInstruction,
|
|
277
|
-
`Participants: main, ${participants.join(", ")}.`,
|
|
278
|
-
),
|
|
279
|
-
};
|
|
280
|
-
});
|
|
281
282
|
startChildRuntime(pi, config);
|
|
282
283
|
|
|
283
284
|
pi.registerTool(
|
package/index.ts
CHANGED
|
@@ -9,13 +9,15 @@ import { defineTool, type ContextUsage, type ExtensionAPI, getMarkdownTheme } fr
|
|
|
9
9
|
import { bundledSkillsInstruction } from "./bundled-skill.ts";
|
|
10
10
|
import { formatContextWindowReport, requireKnownContextUsage, type KnownContextUsage } from "./context-window.ts";
|
|
11
11
|
import { formatScopedModelGuidance, validateTeammateModels, type ModelReference } from "./model-preflight.ts";
|
|
12
|
-
import {
|
|
12
|
+
import { composeTeamBriefing } from "./team-briefing.ts";
|
|
13
|
+
import { composeResumptionMessage } from "./resume-message.ts";
|
|
13
14
|
import { callParent, readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
|
|
14
15
|
import {
|
|
15
16
|
canonicalProjectDirectory,
|
|
16
17
|
claimTeamLease,
|
|
17
18
|
dormantManifestRetentionMilliseconds,
|
|
18
19
|
listTeamManifests,
|
|
20
|
+
teamManifestExists,
|
|
19
21
|
readTeamLeaseState,
|
|
20
22
|
releaseTeamLease,
|
|
21
23
|
writeTeamManifest,
|
|
@@ -24,7 +26,7 @@ import {
|
|
|
24
26
|
type TeamManifestMember,
|
|
25
27
|
} from "./team-registry.ts";
|
|
26
28
|
import { appendTeamLog, filterTeamLog, normalizeChildEvent, pageTeamLog, preview, renderTeamLogPage, type TeamLogEntry } from "./teamlog.ts";
|
|
27
|
-
import { renderReminderToolCall, renderReminderToolResult, renderTeamMessage, renderTeamToolCall, renderTeamToolResult, type TeamMessageDetails } from "./render.ts";
|
|
29
|
+
import { renderReminderToolCall, renderReminderToolResult, renderTeamMessage, renderTeamToolCall, renderTeamToolResult, type TeammateView, type TeamMessageDetails } from "./render.ts";
|
|
28
30
|
import { openTeamOverview, type TeamSnapshot } from "./team-ui.ts";
|
|
29
31
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
30
32
|
import { Type } from "typebox";
|
|
@@ -46,13 +48,14 @@ interface TeammateState {
|
|
|
46
48
|
prompt: string;
|
|
47
49
|
model: string;
|
|
48
50
|
thinking: ThinkingLevel;
|
|
49
|
-
|
|
51
|
+
forkContext: boolean;
|
|
50
52
|
canManageOwnTeams: boolean;
|
|
51
53
|
extensionPaths: string[];
|
|
52
54
|
transport: TeammateTransport;
|
|
53
55
|
sessionId?: string;
|
|
54
56
|
sessionFile?: string;
|
|
55
57
|
sessionMaterialized: boolean;
|
|
58
|
+
lastModelActivityAt?: string;
|
|
56
59
|
process?: ChildProcess;
|
|
57
60
|
paneId?: string;
|
|
58
61
|
deliveryUrl?: string;
|
|
@@ -61,6 +64,7 @@ interface TeammateState {
|
|
|
61
64
|
rejectReady?: (error: Error) => void;
|
|
62
65
|
alive: boolean;
|
|
63
66
|
active: boolean;
|
|
67
|
+
contextPercent?: number;
|
|
64
68
|
pendingTurnDeliveries: number;
|
|
65
69
|
deliveryQueue: Promise<void>;
|
|
66
70
|
}
|
|
@@ -86,7 +90,7 @@ interface TeamState {
|
|
|
86
90
|
|
|
87
91
|
const teamLiteExtensionPath = fileURLToPath(import.meta.url);
|
|
88
92
|
const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
89
|
-
const defaultThinkingLevel
|
|
93
|
+
const defaultThinkingLevel = "xhigh" satisfies ThinkingLevel;
|
|
90
94
|
const deliveryTimeoutMilliseconds = 30_000;
|
|
91
95
|
const defaultRpcShutdownGraceMilliseconds = 1_000;
|
|
92
96
|
const teamMessageType = "pi-simple-team";
|
|
@@ -106,10 +110,11 @@ function compactName(name: string): string {
|
|
|
106
110
|
return trimmed;
|
|
107
111
|
}
|
|
108
112
|
|
|
109
|
-
|
|
113
|
+
/** The model reads `payload`; the renderer reads `payload` plus `viewDetails`. */
|
|
114
|
+
function toolResult(payload: JsonRecord, viewDetails: JsonRecord = {}) {
|
|
110
115
|
return {
|
|
111
116
|
content: [{ type: "text" as const, text: JSON.stringify(payload, null, 2) }],
|
|
112
|
-
details: payload,
|
|
117
|
+
details: { ...payload, ...viewDetails },
|
|
113
118
|
};
|
|
114
119
|
}
|
|
115
120
|
|
|
@@ -135,9 +140,10 @@ function teammateRecord(teammate: TeammateState): TeammateRecord {
|
|
|
135
140
|
systemPrompt: teammate.prompt,
|
|
136
141
|
model: teammate.model,
|
|
137
142
|
thinking: teammate.thinking,
|
|
138
|
-
|
|
143
|
+
forkContext: teammate.forkContext,
|
|
139
144
|
canManageOwnTeams: teammate.canManageOwnTeams,
|
|
140
145
|
showOnHerdrPane: teammate.transport === "herdr",
|
|
146
|
+
contextPercent: teammate.contextPercent,
|
|
141
147
|
sessionFile: teammate.sessionFile!,
|
|
142
148
|
...(teammate.extensionPaths.length > 0 ? { extensionPaths: teammate.extensionPaths } : {}),
|
|
143
149
|
};
|
|
@@ -294,12 +300,14 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
|
|
|
294
300
|
});
|
|
295
301
|
}
|
|
296
302
|
|
|
297
|
-
async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean,
|
|
298
|
-
if (startIdle && resumptionPrompt === undefined) return;
|
|
303
|
+
async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[] }): Promise<void> {
|
|
299
304
|
const outcomes = await Promise.allSettled(teammates.map((teammate) => {
|
|
300
|
-
|
|
301
|
-
const
|
|
302
|
-
|
|
305
|
+
const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
|
|
306
|
+
const message = [
|
|
307
|
+
initialize && composeTeamBriefing(team.name, team.teamPrompt, teammate.name, teammate.prompt, [...team.members.keys()], teammate.canManageOwnTeams),
|
|
308
|
+
resumption && composeResumptionMessage(team.name, teammate.name, teammate.lastModelActivityAt, resumption.instructions),
|
|
309
|
+
].filter(Boolean).join("\n\n");
|
|
310
|
+
return queueDelivery(team, "main", teammate, message, false, !startIdle);
|
|
303
311
|
}));
|
|
304
312
|
const completed = teammates.filter((_teammate, index) => outcomes[index].status === "fulfilled").map((teammate) => teammate.name);
|
|
305
313
|
const errors = outcomes.flatMap((outcome, index) => {
|
|
@@ -376,8 +384,18 @@ function formatStatus(team: TeamState): Record<string, TeamStatus> {
|
|
|
376
384
|
return Object.fromEntries([...team.statuses.entries()].sort(([a], [b]) => a.localeCompare(b)));
|
|
377
385
|
}
|
|
378
386
|
|
|
379
|
-
|
|
380
|
-
|
|
387
|
+
/** @example teammateViews(team).scout?.model // "openai-codex/gpt-6-luna" */
|
|
388
|
+
function teammateViews(team: TeamState): Record<string, TeammateView> {
|
|
389
|
+
return Object.fromEntries([...team.members.values()].map((teammate) => [teammate.name, {
|
|
390
|
+
name: teammate.name,
|
|
391
|
+
live: teammate.alive,
|
|
392
|
+
model: teammate.model,
|
|
393
|
+
thinking: teammate.thinking,
|
|
394
|
+
forkContext: teammate.forkContext,
|
|
395
|
+
canManageOwnTeams: teammate.canManageOwnTeams,
|
|
396
|
+
showOnHerdrPane: teammate.transport === "herdr",
|
|
397
|
+
contextPercent: teammate.contextPercent,
|
|
398
|
+
}]));
|
|
381
399
|
}
|
|
382
400
|
|
|
383
401
|
function ownedTeamSnapshots(owner: symbol): TeamSnapshot[] {
|
|
@@ -389,6 +407,7 @@ function ownedTeamSnapshots(owner: symbol): TeamSnapshot[] {
|
|
|
389
407
|
transports: (["rpc", "herdr"] as const).filter((transport) => [...team.members.values()].some((teammate) => teammate.alive && teammate.transport === transport)),
|
|
390
408
|
roster: [...team.members.keys()],
|
|
391
409
|
statuses: formatStatus(team),
|
|
410
|
+
teammates: teammateViews(team),
|
|
392
411
|
log: [...team.log],
|
|
393
412
|
}));
|
|
394
413
|
}
|
|
@@ -431,7 +450,7 @@ function createTeammateState(teammateSpec: Teammate): TeammateState {
|
|
|
431
450
|
prompt: teammateSpec.systemPrompt,
|
|
432
451
|
model: teammateSpec.model,
|
|
433
452
|
thinking,
|
|
434
|
-
|
|
453
|
+
forkContext: Boolean(teammateSpec.forkContext),
|
|
435
454
|
canManageOwnTeams: Boolean(teammateSpec.canManageOwnTeams),
|
|
436
455
|
extensionPaths,
|
|
437
456
|
transport: teammateSpec.showOnHerdrPane ? "herdr" : "rpc",
|
|
@@ -465,8 +484,8 @@ function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
|
|
|
465
484
|
teammate: teammate.name,
|
|
466
485
|
direction: "runtime",
|
|
467
486
|
kind: "spawn",
|
|
468
|
-
summary: `spawned ${teammate.name} (model=${teammate.model}, thinking=${teammate.thinking}, context=${teammate.
|
|
469
|
-
details: { model: teammate.model, thinking: teammate.thinking,
|
|
487
|
+
summary: `spawned ${teammate.name} (model=${teammate.model}, thinking=${teammate.thinking}, context=${teammate.forkContext ? "forked" : "fresh"})`,
|
|
488
|
+
details: { model: teammate.model, thinking: teammate.thinking, forkContext: teammate.forkContext, transport: teammate.transport, paneId: teammate.paneId },
|
|
470
489
|
});
|
|
471
490
|
}
|
|
472
491
|
|
|
@@ -479,7 +498,7 @@ interface ChildStartOptions {
|
|
|
479
498
|
function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[], options: ChildStartOptions): void {
|
|
480
499
|
const sessionArgs = options.sessionFile
|
|
481
500
|
? ["--session", options.sessionFile]
|
|
482
|
-
: teammate.
|
|
501
|
+
: teammate.forkContext && !options.restartEmpty
|
|
483
502
|
? ["--fork", team.mainSessionFile!]
|
|
484
503
|
: [];
|
|
485
504
|
const modelArgs = options.sessionFile ? [] : ["--model", teammate.model, "--thinking", teammate.thinking];
|
|
@@ -494,8 +513,6 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
494
513
|
"--no-prompt-templates",
|
|
495
514
|
"--no-themes",
|
|
496
515
|
...modelArgs,
|
|
497
|
-
"--system-prompt",
|
|
498
|
-
composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.canManageOwnTeams),
|
|
499
516
|
];
|
|
500
517
|
const proc = childProcess.spawn(team.parentPiExecutable, args, {
|
|
501
518
|
cwd: team.projectDirectory ?? process.cwd(),
|
|
@@ -537,11 +554,10 @@ async function attachHerdrTeammate(
|
|
|
537
554
|
herdrParentPaneId: string,
|
|
538
555
|
options: ChildStartOptions,
|
|
539
556
|
): Promise<void> {
|
|
540
|
-
const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.canManageOwnTeams);
|
|
541
557
|
const environment = childEnvironmentOverrides(team, teammate, participants);
|
|
542
558
|
const sessionArgs = options.sessionFile
|
|
543
559
|
? ["--session", options.sessionFile]
|
|
544
|
-
: teammate.
|
|
560
|
+
: teammate.forkContext && !options.restartEmpty
|
|
545
561
|
? ["--fork", team.mainSessionFile!]
|
|
546
562
|
: [];
|
|
547
563
|
const modelArgs = options.sessionFile ? [] : ["--model", teammate.model, "--thinking", teammate.thinking];
|
|
@@ -560,8 +576,6 @@ async function attachHerdrTeammate(
|
|
|
560
576
|
teamLiteExtensionPath,
|
|
561
577
|
...teammate.extensionPaths.flatMap(extensionPath => ["-e", extensionPath]),
|
|
562
578
|
...modelArgs,
|
|
563
|
-
"--system-prompt",
|
|
564
|
-
systemPrompt,
|
|
565
579
|
].map(shellQuote).join(" ");
|
|
566
580
|
await runCommand("herdr", ["pane", "run", teammate.paneId, command]);
|
|
567
581
|
appendSpawnLog(team, teammate);
|
|
@@ -761,9 +775,18 @@ function validateChildDeliveryUrl(rawUrl: string, teammateName: string): string
|
|
|
761
775
|
return url.toString();
|
|
762
776
|
}
|
|
763
777
|
|
|
778
|
+
/** The child reports the model, thinking level, and context usage it runs with. They replace what main requested, because Pi may clamp the thinking level or restore other settings from the session. */
|
|
779
|
+
function applyRuntimeFacts(teammate: TeammateState, facts: JsonRecord): void {
|
|
780
|
+
if (typeof facts.model !== "string" || typeof facts.thinking !== "string") throw new Error(`Teammate ${teammate.name} reported invalid runtime facts`);
|
|
781
|
+
teammate.model = facts.model;
|
|
782
|
+
teammate.thinking = facts.thinking as ThinkingLevel;
|
|
783
|
+
teammate.contextPercent = (facts.contextPercent as number | null) ?? undefined;
|
|
784
|
+
}
|
|
785
|
+
|
|
764
786
|
function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonRecord): void {
|
|
765
787
|
if (event.type === "agent_start" || event.type === "work_queued") teammate.active = true;
|
|
766
788
|
if (event.type === "agent_settled" || event.type === "session_shutdown") teammate.active = false;
|
|
789
|
+
if (event.type === "runtime_facts") applyRuntimeFacts(teammate, event);
|
|
767
790
|
if (event.type === "session_shutdown") {
|
|
768
791
|
teammate.alive = false;
|
|
769
792
|
teammate.deliveryUrl = undefined;
|
|
@@ -808,7 +831,9 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
808
831
|
}
|
|
809
832
|
teammate.sessionId = sessionId;
|
|
810
833
|
teammate.sessionFile = sessionFile;
|
|
834
|
+
teammate.lastModelActivityAt = args.lastModelActivityAt as string | undefined;
|
|
811
835
|
teammate.sessionMaterialized = fs.existsSync(sessionFile);
|
|
836
|
+
applyRuntimeFacts(teammate, args);
|
|
812
837
|
teammate.alive = true;
|
|
813
838
|
teammate.active = false;
|
|
814
839
|
team.statuses.set(teammate.name, status("idle", "Spawned"));
|
|
@@ -884,10 +909,10 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
884
909
|
function teammateSchema(modelGuidance: string) {
|
|
885
910
|
return Type.Object({
|
|
886
911
|
name: Type.String({ description: "Teammate name" }),
|
|
887
|
-
systemPrompt: Type.String({ description: "Individual teammate
|
|
912
|
+
systemPrompt: Type.String({ description: "Individual teammate instructions, delivered in the custom startup briefing" }),
|
|
888
913
|
model: Type.String({ description: `Canonical provider/model id for this teammate. ${modelGuidance}` }),
|
|
889
914
|
thinking: Type.Optional(StringEnum(thinkingLevels, { description: "Thinking level for this teammate. Defaults to xhigh.", default: defaultThinkingLevel })),
|
|
890
|
-
|
|
915
|
+
forkContext: Type.Optional(Type.Boolean({ description: "Start as a fork of your context window rather than fresh. Defaults to false.", default: false })),
|
|
891
916
|
canManageOwnTeams: Type.Optional(Type.Boolean({ description: "Allow this teammate to create and manage teams of its own. Defaults to false.", default: false })),
|
|
892
917
|
showOnHerdrPane: Type.Optional(Type.Boolean({ description: "Open a visible Herdr pane for this teammate. Defaults to false.", default: false })),
|
|
893
918
|
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 stay disabled." })),
|
|
@@ -917,6 +942,7 @@ function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiExecutab
|
|
|
917
942
|
teammate.sessionId = member.teammateId;
|
|
918
943
|
teammate.sessionFile = member.sessionFile;
|
|
919
944
|
teammate.sessionMaterialized = member.sessionMaterialized;
|
|
945
|
+
teammate.contextPercent = member.contextPercent;
|
|
920
946
|
teammate.alive = false;
|
|
921
947
|
team.members.set(teammate.name, teammate);
|
|
922
948
|
team.statuses.set(teammate.name, status("stopped", "Dormant"));
|
|
@@ -982,13 +1008,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
982
1008
|
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.",
|
|
983
1009
|
renderShell: "self",
|
|
984
1010
|
renderCall: (args, theme, context) => renderTeamToolCall("team_spawn", args, theme, context, sessionTeammateRoster),
|
|
985
|
-
renderResult: (result, options, theme, context) => renderTeamToolResult("team_spawn", result, options, theme, context,
|
|
1011
|
+
renderResult: (result, options, theme, context) => renderTeamToolResult("team_spawn", result, options, theme, context, getMarkdownTheme(), sessionTeammateRoster),
|
|
986
1012
|
parameters: Type.Object({
|
|
987
1013
|
teamName: Type.String({ description: "Name for the new team" }),
|
|
988
|
-
commonPrompt: Type.String({ description: "
|
|
1014
|
+
commonPrompt: Type.String({ description: "Shared instructions for all teammates, delivered in the custom startup briefing" }),
|
|
989
1015
|
teammates: Type.Array(teammateSchema(modelGuidance), { description: "Teammates to spawn" }),
|
|
990
1016
|
showOnHerdrPanes: Type.Optional(Type.Boolean({ description: "Open visible Herdr panes for the team. Overrides individual teammate Herdr settings when explicitly supplied. Defaults to false.", default: false })),
|
|
991
|
-
startIdle: Type.Optional(Type.Boolean({ default: false, description: "
|
|
1017
|
+
startIdle: Type.Optional(Type.Boolean({ default: false, description: "Stage each teammate's briefing without starting work. Otherwise, start work once everyone is ready. Set true when only a few teammates should start first, then message those teammates." })),
|
|
992
1018
|
}, { additionalProperties: false }),
|
|
993
1019
|
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
994
1020
|
signal?.throwIfAborted();
|
|
@@ -1002,9 +1028,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1002
1028
|
if (teammateNames.includes("main")) throw new Error('"main" is reserved');
|
|
1003
1029
|
|
|
1004
1030
|
validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
|
|
1005
|
-
const
|
|
1006
|
-
const mainSessionFile =
|
|
1007
|
-
if (
|
|
1031
|
+
const forksContext = teammateSpecs.some((teammate) => Boolean(teammate.forkContext));
|
|
1032
|
+
const mainSessionFile = forksContext ? context.sessionManager.getSessionFile() : undefined;
|
|
1033
|
+
if (forksContext && !mainSessionFile) throw new Error("forkContext requires a saved main session. Use a saved main session or retry with forkContext: false.");
|
|
1008
1034
|
const originMainSessionId = context.sessionManager?.getSessionId?.();
|
|
1009
1035
|
const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
|
|
1010
1036
|
const projectDirectory = rawProjectDirectory ? canonicalProjectDirectory(rawProjectDirectory) : undefined;
|
|
@@ -1012,10 +1038,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
1012
1038
|
const runtimeTeamId = teamId ?? teamName;
|
|
1013
1039
|
if (teams.has(runtimeTeamId)) throw new Error(`Team already exists: ${runtimeTeamId}`);
|
|
1014
1040
|
const lease = teamId ? claimTeamLease(teamId, originMainSessionId) : undefined;
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1041
|
+
try {
|
|
1042
|
+
if (teamId && teamManifestExists(teamId)) {
|
|
1043
|
+
// TODO: Consider resuming here if all supplied spawn settings can be preserved.
|
|
1044
|
+
throw new Error(`Team already exists: ${teamId}. Use team_resume.`);
|
|
1045
|
+
}
|
|
1046
|
+
} catch (error) {
|
|
1047
|
+
if (lease) releaseTeamLease(lease);
|
|
1048
|
+
throw error;
|
|
1019
1049
|
}
|
|
1020
1050
|
sessionTeammateRoster.push(...teammateNames.filter((teammateName) => !sessionTeammateRoster.includes(teammateName)));
|
|
1021
1051
|
try {
|
|
@@ -1129,10 +1159,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
1129
1159
|
if (!projectDirectory) throw new Error("team_list requires a project directory");
|
|
1130
1160
|
const managerSessionId = childRuntimeConfig ? context.sessionManager?.getSessionId?.() : undefined;
|
|
1131
1161
|
if (childRuntimeConfig && !managerSessionId) throw new Error("team_list requires a persistent managing teammate Pi session");
|
|
1132
|
-
const
|
|
1162
|
+
const listing = listTeamManifests(projectDirectory);
|
|
1163
|
+
const manifests = listing.manifests.filter(
|
|
1133
1164
|
(manifest) => !managerSessionId || manifest.originMainSessionId === managerSessionId,
|
|
1134
1165
|
);
|
|
1135
1166
|
return toolResult({
|
|
1167
|
+
...(listing.unreadable.length > 0 ? { unreadableManifests: listing.unreadable } : {}),
|
|
1136
1168
|
teams: manifests.map((manifest) => {
|
|
1137
1169
|
const liveTeam = teams.get(manifest.id);
|
|
1138
1170
|
return {
|
|
@@ -1170,7 +1202,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1170
1202
|
teammates: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description: "Teammate names or Pi session IDs within this team. Omit to resume all stopped teammates." })),
|
|
1171
1203
|
showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false, description: "Open visible Herdr panes for selected teammates. Defaults to false." })),
|
|
1172
1204
|
startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start resumed teammates idle." })),
|
|
1173
|
-
resumptionPrompt: Type.Optional(Type.String({ description: "Instructions added once
|
|
1205
|
+
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." })),
|
|
1174
1206
|
}, { additionalProperties: false }),
|
|
1175
1207
|
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
1176
1208
|
signal?.throwIfAborted();
|
|
@@ -1178,7 +1210,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1178
1210
|
if (!rawProjectDirectory) throw new Error("team_resume requires a project directory");
|
|
1179
1211
|
const managerSessionId = childRuntimeConfig ? context.sessionManager?.getSessionId?.() : undefined;
|
|
1180
1212
|
if (childRuntimeConfig && !managerSessionId) throw new Error("team_resume requires a persistent managing teammate Pi session");
|
|
1181
|
-
const availableManifests = listTeamManifests(rawProjectDirectory).filter(
|
|
1213
|
+
const availableManifests = listTeamManifests(rawProjectDirectory).manifests.filter(
|
|
1182
1214
|
(candidate) => !managerSessionId || candidate.originMainSessionId === managerSessionId,
|
|
1183
1215
|
);
|
|
1184
1216
|
const manifest = resolveTeamIdentifier(availableManifests, params.team);
|
|
@@ -1254,7 +1286,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1254
1286
|
throw error;
|
|
1255
1287
|
}
|
|
1256
1288
|
|
|
1257
|
-
await kickoffTeammates(team, starts.map(({ teammate }) => teammate), Boolean(params.startIdle), params.resumptionPrompt);
|
|
1289
|
+
await kickoffTeammates(team, starts.map(({ teammate }) => teammate), Boolean(params.startIdle), { instructions: params.resumptionPrompt, emptyRestarts: starts.filter(({ sessionFile }) => sessionFile === undefined).map(({ teammate }) => teammate) });
|
|
1258
1290
|
return toolResult({
|
|
1259
1291
|
...lifecycleResult(team),
|
|
1260
1292
|
teammates: [...team.members.values()].map((teammate) => {
|
|
@@ -1275,7 +1307,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1275
1307
|
description: "Add teammates to an active team you own. Existing teammates continue their work.",
|
|
1276
1308
|
renderShell: "self",
|
|
1277
1309
|
renderCall: (args, theme, context) => renderTeamToolCall("team_add_teammates", args, theme, context, sessionTeammateRoster),
|
|
1278
|
-
renderResult: (result, options, theme, context) => renderTeamToolResult("team_add_teammates", result, options, theme, context,
|
|
1310
|
+
renderResult: (result, options, theme, context) => renderTeamToolResult("team_add_teammates", result, options, theme, context, getMarkdownTheme(), sessionTeammateRoster),
|
|
1279
1311
|
parameters: Type.Object({
|
|
1280
1312
|
team: Type.Optional(Type.String({ description: "Team name or persistent ID. Omit when exactly one owned active team exists." })),
|
|
1281
1313
|
// TODO: Accept existing current-project Pi session IDs as well as new teammate definitions.
|
|
@@ -1301,9 +1333,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1301
1333
|
if (teammateNames.includes("main")) throw new Error('"main" is reserved');
|
|
1302
1334
|
validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
|
|
1303
1335
|
|
|
1304
|
-
const
|
|
1305
|
-
const mainSessionFile =
|
|
1306
|
-
if (
|
|
1336
|
+
const forksContext = teammateSpecs.some((teammate) => Boolean(teammate.forkContext));
|
|
1337
|
+
const mainSessionFile = forksContext ? context.sessionManager.getSessionFile() : undefined;
|
|
1338
|
+
if (forksContext && !mainSessionFile) throw new Error("forkContext requires a saved main session. Use a saved main session or retry with forkContext: false.");
|
|
1307
1339
|
if (mainSessionFile) team.mainSessionFile = mainSessionFile;
|
|
1308
1340
|
|
|
1309
1341
|
const addedTeammates = teammateSpecs.map(createTeammateState);
|
|
@@ -1335,7 +1367,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1335
1367
|
...lifecycleResult(team),
|
|
1336
1368
|
teammates: [...team.members.values()].map(teammateSummary),
|
|
1337
1369
|
status: formatStatus(team),
|
|
1338
|
-
});
|
|
1370
|
+
}, { addedTeammates: addedTeammates.map(teammateRecord) });
|
|
1339
1371
|
},
|
|
1340
1372
|
}),
|
|
1341
1373
|
);
|
|
@@ -1404,12 +1436,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
1404
1436
|
}, signal));
|
|
1405
1437
|
}
|
|
1406
1438
|
if (!params.team && params.gerund === undefined && params.phrase === undefined) {
|
|
1407
|
-
|
|
1439
|
+
const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
|
|
1440
|
+
const statuses = ownedTeams.map((team) => ({ ...teamIdentity(team), status: formatStatus(team) }));
|
|
1441
|
+
return toolResult({ teams: statuses }, { teams: statuses.map((entry, index) => ({ ...entry, teammates: teammateViews(ownedTeams[index]!) })) });
|
|
1408
1442
|
}
|
|
1409
1443
|
const team = resolveTeam(owner, params.team);
|
|
1410
1444
|
updateStatus(team, "main", params.gerund, params.phrase);
|
|
1411
1445
|
logStatusDeclaration(team, "main", params.gerund, params.phrase);
|
|
1412
|
-
return toolResult({ ...teamIdentity(team), status: formatStatus(team) });
|
|
1446
|
+
return toolResult({ ...teamIdentity(team), status: formatStatus(team) }, { teammates: teammateViews(team) });
|
|
1413
1447
|
},
|
|
1414
1448
|
}),
|
|
1415
1449
|
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@giladbarnea/pi-simple-team",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.3",
|
|
4
4
|
"description": "A flat, live team of Pi agents.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
],
|
|
39
39
|
"peerDependencies": {
|
|
40
40
|
"@earendil-works/pi-ai": "*",
|
|
41
|
-
"@earendil-works/pi-coding-agent": "
|
|
41
|
+
"@earendil-works/pi-coding-agent": ">=1.1.0",
|
|
42
42
|
"@earendil-works/pi-tui": "*",
|
|
43
43
|
"typebox": "*"
|
|
44
44
|
},
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** A theme that can also report each token's live foreground escape, as Pi's `Theme` does. */
|
|
2
|
+
export interface HeatTheme {
|
|
3
|
+
fg(token: string, text: string): string;
|
|
4
|
+
getFgAnsi?(token: string): string;
|
|
5
|
+
getColorMode?(): string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
type Rgb = readonly [number, number, number];
|
|
9
|
+
type HeatStop = { at: number; token: string; quiet?: boolean };
|
|
10
|
+
|
|
11
|
+
/** Quiet at empty, loud at full. Mirrors the context ramp of the `custom-footer` extension. */
|
|
12
|
+
const CONTEXT_HEAT_STOPS: readonly HeatStop[] = [
|
|
13
|
+
{ at: 0, token: "success", quiet: true },
|
|
14
|
+
{ at: 40, token: "success" },
|
|
15
|
+
{ at: 70, token: "warning" },
|
|
16
|
+
{ at: 100, token: "error" },
|
|
17
|
+
];
|
|
18
|
+
const QUIET_BLEND = 0.38;
|
|
19
|
+
const GAUGE_GLYPHS = "▁▂▃▄▅▆▇█";
|
|
20
|
+
|
|
21
|
+
/** @example contextGauge(16) // "▂" */
|
|
22
|
+
export function contextGauge(percent: number): string {
|
|
23
|
+
return GAUGE_GLYPHS[Math.min(GAUGE_GLYPHS.length - 1, Math.floor(percent / (100 / GAUGE_GLYPHS.length)))]!;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function tokenRgb(theme: HeatTheme, token: string): Rgb | undefined {
|
|
27
|
+
const match = theme.getFgAnsi?.(token).match(/\x1b\[38;2;(\d+);(\d+);(\d+)m/);
|
|
28
|
+
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @example blendRgb([0, 0, 0], [100, 200, 50], 0.5) // [50, 100, 25] */
|
|
32
|
+
function blendRgb(start: Rgb, end: Rgb, ratio: number): Rgb {
|
|
33
|
+
return [0, 1, 2].map((channel) => Math.round(start[channel]! + (end[channel]! - start[channel]!) * ratio)) as unknown as Rgb;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function stopRgb(theme: HeatTheme, stop: HeatStop): Rgb | undefined {
|
|
37
|
+
const base = tokenRgb(theme, stop.token);
|
|
38
|
+
if (!stop.quiet) return base;
|
|
39
|
+
const dim = tokenRgb(theme, "dim");
|
|
40
|
+
return base && dim ? blendRgb(base, dim, QUIET_BLEND) : undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Colors `text` by where `percent` sits on the context ramp. Without truecolor theme values
|
|
45
|
+
* (a 256-color terminal or palette-index tokens), it uses the nearest stop's token instead of a blend.
|
|
46
|
+
*/
|
|
47
|
+
export function contextHeat(theme: HeatTheme, percent: number, text: string): string {
|
|
48
|
+
const value = Math.min(100, Math.max(0, percent));
|
|
49
|
+
const upper = Math.max(1, CONTEXT_HEAT_STOPS.findIndex((stop) => stop.at >= value));
|
|
50
|
+
const low = CONTEXT_HEAT_STOPS[upper - 1]!;
|
|
51
|
+
const high = CONTEXT_HEAT_STOPS[upper]!;
|
|
52
|
+
const lowRgb = stopRgb(theme, low);
|
|
53
|
+
const highRgb = stopRgb(theme, high);
|
|
54
|
+
if (theme.getColorMode?.() === "256color" || !lowRgb || !highRgb) {
|
|
55
|
+
const nearest = value - low.at <= high.at - value ? low : high;
|
|
56
|
+
return theme.fg(nearest.token, text);
|
|
57
|
+
}
|
|
58
|
+
const [red, green, blue] = blendRgb(lowRgb, highRgb, (value - low.at) / (high.at - low.at));
|
|
59
|
+
return `\x1b[38;2;${red};${green};${blue}m${text}\x1b[39m`;
|
|
60
|
+
}
|