@giladbarnea/pi-simple-team 2.0.1 → 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 +9 -2
- package/child-tools.ts +23 -22
- package/index.ts +96 -53
- package/package.json +2 -2
- package/render-support/heat.ts +60 -0
- package/render.ts +164 -180
- 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 +47 -17
- package/team-ui.ts +16 -30
- package/teamlog.ts +6 -1
- package/teammate-facts.ts +194 -0
- package/teammate.ts +7 -3
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
|
|
|
@@ -230,6 +235,8 @@ Spawn, resume, and add return the complete roster. Results distinguish a live ru
|
|
|
230
235
|
|
|
231
236
|
Set `showOnHerdrPane: true` on individual teammates to open their panes. An explicit `showOnHerdrPanes` value on spawn overrides all individual settings.
|
|
232
237
|
|
|
238
|
+
`extensionPaths` lists trusted, existing absolute extension paths for one teammate. RPC and Herdr launches load them alongside the team runtime, and resume keeps them. Discovered extensions remain disabled. These modules run with the same permissions as Pi.
|
|
239
|
+
|
|
233
240
|
Message tools return `published: true` when the extension accepts a message for delivery. If delivery later fails, the sender receives the error automatically.
|
|
234
241
|
|
|
235
242
|
|
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();
|
|
@@ -258,26 +278,7 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
|
258
278
|
}
|
|
259
279
|
|
|
260
280
|
export function registerChildTools(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
261
|
-
pi.registerMessageRenderer(teamMessageType, (message,
|
|
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
|
+
pi.registerMessageRenderer(teamMessageType, (message, options, theme) => renderTeamMessage(message, options, theme, getMarkdownTheme(), config.participants));
|
|
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,12 +48,14 @@ interface TeammateState {
|
|
|
46
48
|
prompt: string;
|
|
47
49
|
model: string;
|
|
48
50
|
thinking: ThinkingLevel;
|
|
49
|
-
|
|
51
|
+
forkContext: boolean;
|
|
50
52
|
canManageOwnTeams: boolean;
|
|
53
|
+
extensionPaths: string[];
|
|
51
54
|
transport: TeammateTransport;
|
|
52
55
|
sessionId?: string;
|
|
53
56
|
sessionFile?: string;
|
|
54
57
|
sessionMaterialized: boolean;
|
|
58
|
+
lastModelActivityAt?: string;
|
|
55
59
|
process?: ChildProcess;
|
|
56
60
|
paneId?: string;
|
|
57
61
|
deliveryUrl?: string;
|
|
@@ -60,6 +64,7 @@ interface TeammateState {
|
|
|
60
64
|
rejectReady?: (error: Error) => void;
|
|
61
65
|
alive: boolean;
|
|
62
66
|
active: boolean;
|
|
67
|
+
contextPercent?: number;
|
|
63
68
|
pendingTurnDeliveries: number;
|
|
64
69
|
deliveryQueue: Promise<void>;
|
|
65
70
|
}
|
|
@@ -85,7 +90,7 @@ interface TeamState {
|
|
|
85
90
|
|
|
86
91
|
const teamLiteExtensionPath = fileURLToPath(import.meta.url);
|
|
87
92
|
const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
88
|
-
const defaultThinkingLevel
|
|
93
|
+
const defaultThinkingLevel = "xhigh" satisfies ThinkingLevel;
|
|
89
94
|
const deliveryTimeoutMilliseconds = 30_000;
|
|
90
95
|
const defaultRpcShutdownGraceMilliseconds = 1_000;
|
|
91
96
|
const teamMessageType = "pi-simple-team";
|
|
@@ -105,10 +110,11 @@ function compactName(name: string): string {
|
|
|
105
110
|
return trimmed;
|
|
106
111
|
}
|
|
107
112
|
|
|
108
|
-
|
|
113
|
+
/** The model reads `payload`; the renderer reads `payload` plus `viewDetails`. */
|
|
114
|
+
function toolResult(payload: JsonRecord, viewDetails: JsonRecord = {}) {
|
|
109
115
|
return {
|
|
110
116
|
content: [{ type: "text" as const, text: JSON.stringify(payload, null, 2) }],
|
|
111
|
-
details: payload,
|
|
117
|
+
details: { ...payload, ...viewDetails },
|
|
112
118
|
};
|
|
113
119
|
}
|
|
114
120
|
|
|
@@ -134,18 +140,21 @@ function teammateRecord(teammate: TeammateState): TeammateRecord {
|
|
|
134
140
|
systemPrompt: teammate.prompt,
|
|
135
141
|
model: teammate.model,
|
|
136
142
|
thinking: teammate.thinking,
|
|
137
|
-
|
|
143
|
+
forkContext: teammate.forkContext,
|
|
138
144
|
canManageOwnTeams: teammate.canManageOwnTeams,
|
|
139
145
|
showOnHerdrPane: teammate.transport === "herdr",
|
|
146
|
+
contextPercent: teammate.contextPercent,
|
|
140
147
|
sessionFile: teammate.sessionFile!,
|
|
148
|
+
...(teammate.extensionPaths.length > 0 ? { extensionPaths: teammate.extensionPaths } : {}),
|
|
141
149
|
};
|
|
142
150
|
}
|
|
143
151
|
|
|
144
152
|
/** @example lifecycleInstruction(true).includes("idle") // true */
|
|
145
153
|
function lifecycleInstruction(startIdle: boolean): string {
|
|
154
|
+
const reminderOffer = "Ask the user whether to schedule recurring team progress checks, and at which interval. Suggest an interval proportional to the task: every 30-60 minutes for a multi-hour task, or every 15 minutes for a task of 1 hour or less. If they agree, use `schedule_reminder`. After each check, schedule the next while the team needs oversight.";
|
|
146
155
|
const nextAction = startIdle
|
|
147
|
-
?
|
|
148
|
-
:
|
|
156
|
+
? `All teammates are currently idle. Use \`team_send_message\` to start idle teammates, or \`team_resume\` for stopped teammates. After the team starts work: ${reminderOffer}`
|
|
157
|
+
: `Teammates will message you with milestones or requests for help. Avoid repeated status polling and shell sleeps. Set your status to explain what you expect from them. If you have no independent work, tell the user and end your turn. ${reminderOffer}`;
|
|
149
158
|
return `${bundledSkillsInstruction}\n\n${nextAction}`;
|
|
150
159
|
}
|
|
151
160
|
|
|
@@ -291,12 +300,14 @@ function enqueueDelivery(team: TeamState, from: string, recipient: TeammateState
|
|
|
291
300
|
});
|
|
292
301
|
}
|
|
293
302
|
|
|
294
|
-
async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean,
|
|
295
|
-
if (startIdle && resumptionPrompt === undefined) return;
|
|
303
|
+
async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[] }): Promise<void> {
|
|
296
304
|
const outcomes = await Promise.allSettled(teammates.map((teammate) => {
|
|
297
|
-
|
|
298
|
-
const
|
|
299
|
-
|
|
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);
|
|
300
311
|
}));
|
|
301
312
|
const completed = teammates.filter((_teammate, index) => outcomes[index].status === "fulfilled").map((teammate) => teammate.name);
|
|
302
313
|
const errors = outcomes.flatMap((outcome, index) => {
|
|
@@ -373,8 +384,18 @@ function formatStatus(team: TeamState): Record<string, TeamStatus> {
|
|
|
373
384
|
return Object.fromEntries([...team.statuses.entries()].sort(([a], [b]) => a.localeCompare(b)));
|
|
374
385
|
}
|
|
375
386
|
|
|
376
|
-
|
|
377
|
-
|
|
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
|
+
}]));
|
|
378
399
|
}
|
|
379
400
|
|
|
380
401
|
function ownedTeamSnapshots(owner: symbol): TeamSnapshot[] {
|
|
@@ -386,6 +407,7 @@ function ownedTeamSnapshots(owner: symbol): TeamSnapshot[] {
|
|
|
386
407
|
transports: (["rpc", "herdr"] as const).filter((transport) => [...team.members.values()].some((teammate) => teammate.alive && teammate.transport === transport)),
|
|
387
408
|
roster: [...team.members.keys()],
|
|
388
409
|
statuses: formatStatus(team),
|
|
410
|
+
teammates: teammateViews(team),
|
|
389
411
|
log: [...team.log],
|
|
390
412
|
}));
|
|
391
413
|
}
|
|
@@ -412,6 +434,10 @@ function logStatusDeclaration(team: TeamState, participant: string, word?: strin
|
|
|
412
434
|
function createTeammateState(teammateSpec: Teammate): TeammateState {
|
|
413
435
|
const teammateName = compactName(teammateSpec.name);
|
|
414
436
|
const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
|
|
437
|
+
const extensionPaths = teammateSpec.extensionPaths ?? [];
|
|
438
|
+
for (const extensionPath of extensionPaths) {
|
|
439
|
+
if (!path.isAbsolute(extensionPath) || !fs.existsSync(extensionPath)) throw new Error(`Teammate extension must be an existing absolute path: ${extensionPath}`);
|
|
440
|
+
}
|
|
415
441
|
let resolveReady: (() => void) | undefined;
|
|
416
442
|
let rejectReady: ((error: Error) => void) | undefined;
|
|
417
443
|
const ready = new Promise<void>((resolve, reject) => {
|
|
@@ -424,8 +450,9 @@ function createTeammateState(teammateSpec: Teammate): TeammateState {
|
|
|
424
450
|
prompt: teammateSpec.systemPrompt,
|
|
425
451
|
model: teammateSpec.model,
|
|
426
452
|
thinking,
|
|
427
|
-
|
|
453
|
+
forkContext: Boolean(teammateSpec.forkContext),
|
|
428
454
|
canManageOwnTeams: Boolean(teammateSpec.canManageOwnTeams),
|
|
455
|
+
extensionPaths,
|
|
429
456
|
transport: teammateSpec.showOnHerdrPane ? "herdr" : "rpc",
|
|
430
457
|
sessionMaterialized: false,
|
|
431
458
|
ready,
|
|
@@ -457,8 +484,8 @@ function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
|
|
|
457
484
|
teammate: teammate.name,
|
|
458
485
|
direction: "runtime",
|
|
459
486
|
kind: "spawn",
|
|
460
|
-
summary: `spawned ${teammate.name} (model=${teammate.model}, thinking=${teammate.thinking}, context=${teammate.
|
|
461
|
-
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 },
|
|
462
489
|
});
|
|
463
490
|
}
|
|
464
491
|
|
|
@@ -471,7 +498,7 @@ interface ChildStartOptions {
|
|
|
471
498
|
function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[], options: ChildStartOptions): void {
|
|
472
499
|
const sessionArgs = options.sessionFile
|
|
473
500
|
? ["--session", options.sessionFile]
|
|
474
|
-
: teammate.
|
|
501
|
+
: teammate.forkContext && !options.restartEmpty
|
|
475
502
|
? ["--fork", team.mainSessionFile!]
|
|
476
503
|
: [];
|
|
477
504
|
const modelArgs = options.sessionFile ? [] : ["--model", teammate.model, "--thinking", teammate.thinking];
|
|
@@ -482,11 +509,10 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
482
509
|
"--no-extensions",
|
|
483
510
|
"-e",
|
|
484
511
|
teamLiteExtensionPath,
|
|
512
|
+
...teammate.extensionPaths.flatMap(extensionPath => ["-e", extensionPath]),
|
|
485
513
|
"--no-prompt-templates",
|
|
486
514
|
"--no-themes",
|
|
487
515
|
...modelArgs,
|
|
488
|
-
"--system-prompt",
|
|
489
|
-
composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.canManageOwnTeams),
|
|
490
516
|
];
|
|
491
517
|
const proc = childProcess.spawn(team.parentPiExecutable, args, {
|
|
492
518
|
cwd: team.projectDirectory ?? process.cwd(),
|
|
@@ -528,11 +554,10 @@ async function attachHerdrTeammate(
|
|
|
528
554
|
herdrParentPaneId: string,
|
|
529
555
|
options: ChildStartOptions,
|
|
530
556
|
): Promise<void> {
|
|
531
|
-
const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants, teammate.canManageOwnTeams);
|
|
532
557
|
const environment = childEnvironmentOverrides(team, teammate, participants);
|
|
533
558
|
const sessionArgs = options.sessionFile
|
|
534
559
|
? ["--session", options.sessionFile]
|
|
535
|
-
: teammate.
|
|
560
|
+
: teammate.forkContext && !options.restartEmpty
|
|
536
561
|
? ["--fork", team.mainSessionFile!]
|
|
537
562
|
: [];
|
|
538
563
|
const modelArgs = options.sessionFile ? [] : ["--model", teammate.model, "--thinking", teammate.thinking];
|
|
@@ -549,9 +574,8 @@ async function attachHerdrTeammate(
|
|
|
549
574
|
"--no-extensions",
|
|
550
575
|
"-e",
|
|
551
576
|
teamLiteExtensionPath,
|
|
577
|
+
...teammate.extensionPaths.flatMap(extensionPath => ["-e", extensionPath]),
|
|
552
578
|
...modelArgs,
|
|
553
|
-
"--system-prompt",
|
|
554
|
-
systemPrompt,
|
|
555
579
|
].map(shellQuote).join(" ");
|
|
556
580
|
await runCommand("herdr", ["pane", "run", teammate.paneId, command]);
|
|
557
581
|
appendSpawnLog(team, teammate);
|
|
@@ -751,9 +775,18 @@ function validateChildDeliveryUrl(rawUrl: string, teammateName: string): string
|
|
|
751
775
|
return url.toString();
|
|
752
776
|
}
|
|
753
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
|
+
|
|
754
786
|
function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonRecord): void {
|
|
755
787
|
if (event.type === "agent_start" || event.type === "work_queued") teammate.active = true;
|
|
756
788
|
if (event.type === "agent_settled" || event.type === "session_shutdown") teammate.active = false;
|
|
789
|
+
if (event.type === "runtime_facts") applyRuntimeFacts(teammate, event);
|
|
757
790
|
if (event.type === "session_shutdown") {
|
|
758
791
|
teammate.alive = false;
|
|
759
792
|
teammate.deliveryUrl = undefined;
|
|
@@ -798,7 +831,9 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
798
831
|
}
|
|
799
832
|
teammate.sessionId = sessionId;
|
|
800
833
|
teammate.sessionFile = sessionFile;
|
|
834
|
+
teammate.lastModelActivityAt = args.lastModelActivityAt as string | undefined;
|
|
801
835
|
teammate.sessionMaterialized = fs.existsSync(sessionFile);
|
|
836
|
+
applyRuntimeFacts(teammate, args);
|
|
802
837
|
teammate.alive = true;
|
|
803
838
|
teammate.active = false;
|
|
804
839
|
team.statuses.set(teammate.name, status("idle", "Spawned"));
|
|
@@ -874,12 +909,13 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
874
909
|
function teammateSchema(modelGuidance: string) {
|
|
875
910
|
return Type.Object({
|
|
876
911
|
name: Type.String({ description: "Teammate name" }),
|
|
877
|
-
systemPrompt: Type.String({ description: "Individual teammate
|
|
912
|
+
systemPrompt: Type.String({ description: "Individual teammate instructions, delivered in the custom startup briefing" }),
|
|
878
913
|
model: Type.String({ description: `Canonical provider/model id for this teammate. ${modelGuidance}` }),
|
|
879
914
|
thinking: Type.Optional(StringEnum(thinkingLevels, { description: "Thinking level for this teammate. Defaults to xhigh.", default: defaultThinkingLevel })),
|
|
880
|
-
|
|
915
|
+
forkContext: Type.Optional(Type.Boolean({ description: "Start as a fork of your context window rather than fresh. Defaults to false.", default: false })),
|
|
881
916
|
canManageOwnTeams: Type.Optional(Type.Boolean({ description: "Allow this teammate to create and manage teams of its own. Defaults to false.", default: false })),
|
|
882
917
|
showOnHerdrPane: Type.Optional(Type.Boolean({ description: "Open a visible Herdr pane for this teammate. Defaults to false.", default: false })),
|
|
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." })),
|
|
883
919
|
}, { additionalProperties: false });
|
|
884
920
|
}
|
|
885
921
|
|
|
@@ -906,6 +942,7 @@ function restoreTeamState(owner: symbol, ownerPi: ExtensionAPI, parentPiExecutab
|
|
|
906
942
|
teammate.sessionId = member.teammateId;
|
|
907
943
|
teammate.sessionFile = member.sessionFile;
|
|
908
944
|
teammate.sessionMaterialized = member.sessionMaterialized;
|
|
945
|
+
teammate.contextPercent = member.contextPercent;
|
|
909
946
|
teammate.alive = false;
|
|
910
947
|
team.members.set(teammate.name, teammate);
|
|
911
948
|
team.statuses.set(teammate.name, status("stopped", "Dormant"));
|
|
@@ -943,7 +980,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
943
980
|
const owner = Symbol("pi-simple-team-owner");
|
|
944
981
|
const reminderTimers = new Set<ReturnType<typeof setTimeout>>();
|
|
945
982
|
const sessionTeammateRoster = childRuntimeConfig?.participants ?? [];
|
|
946
|
-
pi.registerMessageRenderer(teamMessageType, (message,
|
|
983
|
+
pi.registerMessageRenderer(teamMessageType, (message, options, theme) => renderTeamMessage(message, options, theme, getMarkdownTheme(), sessionTeammateRoster));
|
|
947
984
|
|
|
948
985
|
pi.registerCommand("team", {
|
|
949
986
|
description: "Open a read-only team overview",
|
|
@@ -968,17 +1005,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
968
1005
|
defineTool({
|
|
969
1006
|
name: "team_spawn",
|
|
970
1007
|
label: "Team Spawn",
|
|
971
|
-
description: "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.",
|
|
972
|
-
promptSnippet: "Spawn a versatile team of agents.",
|
|
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.",
|
|
973
1009
|
renderShell: "self",
|
|
974
1010
|
renderCall: (args, theme, context) => renderTeamToolCall("team_spawn", args, theme, context, sessionTeammateRoster),
|
|
975
|
-
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),
|
|
976
1012
|
parameters: Type.Object({
|
|
977
1013
|
teamName: Type.String({ description: "Name for the new team" }),
|
|
978
|
-
commonPrompt: Type.String({ description: "
|
|
1014
|
+
commonPrompt: Type.String({ description: "Shared instructions for all teammates, delivered in the custom startup briefing" }),
|
|
979
1015
|
teammates: Type.Array(teammateSchema(modelGuidance), { description: "Teammates to spawn" }),
|
|
980
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 })),
|
|
981
|
-
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." })),
|
|
982
1018
|
}, { additionalProperties: false }),
|
|
983
1019
|
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
984
1020
|
signal?.throwIfAborted();
|
|
@@ -992,9 +1028,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
992
1028
|
if (teammateNames.includes("main")) throw new Error('"main" is reserved');
|
|
993
1029
|
|
|
994
1030
|
validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
|
|
995
|
-
const
|
|
996
|
-
const mainSessionFile =
|
|
997
|
-
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.");
|
|
998
1034
|
const originMainSessionId = context.sessionManager?.getSessionId?.();
|
|
999
1035
|
const rawProjectDirectory = context.sessionManager?.getCwd?.() ?? context.cwd;
|
|
1000
1036
|
const projectDirectory = rawProjectDirectory ? canonicalProjectDirectory(rawProjectDirectory) : undefined;
|
|
@@ -1002,10 +1038,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
1002
1038
|
const runtimeTeamId = teamId ?? teamName;
|
|
1003
1039
|
if (teams.has(runtimeTeamId)) throw new Error(`Team already exists: ${runtimeTeamId}`);
|
|
1004
1040
|
const lease = teamId ? claimTeamLease(teamId, originMainSessionId) : undefined;
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
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;
|
|
1009
1049
|
}
|
|
1010
1050
|
sessionTeammateRoster.push(...teammateNames.filter((teammateName) => !sessionTeammateRoster.includes(teammateName)));
|
|
1011
1051
|
try {
|
|
@@ -1119,10 +1159,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
1119
1159
|
if (!projectDirectory) throw new Error("team_list requires a project directory");
|
|
1120
1160
|
const managerSessionId = childRuntimeConfig ? context.sessionManager?.getSessionId?.() : undefined;
|
|
1121
1161
|
if (childRuntimeConfig && !managerSessionId) throw new Error("team_list requires a persistent managing teammate Pi session");
|
|
1122
|
-
const
|
|
1162
|
+
const listing = listTeamManifests(projectDirectory);
|
|
1163
|
+
const manifests = listing.manifests.filter(
|
|
1123
1164
|
(manifest) => !managerSessionId || manifest.originMainSessionId === managerSessionId,
|
|
1124
1165
|
);
|
|
1125
1166
|
return toolResult({
|
|
1167
|
+
...(listing.unreadable.length > 0 ? { unreadableManifests: listing.unreadable } : {}),
|
|
1126
1168
|
teams: manifests.map((manifest) => {
|
|
1127
1169
|
const liveTeam = teams.get(manifest.id);
|
|
1128
1170
|
return {
|
|
@@ -1160,7 +1202,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1160
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." })),
|
|
1161
1203
|
showOnHerdrPanes: Type.Optional(Type.Boolean({ default: false, description: "Open visible Herdr panes for selected teammates. Defaults to false." })),
|
|
1162
1204
|
startIdle: Type.Optional(Type.Boolean({ default: false, description: "Start resumed teammates idle." })),
|
|
1163
|
-
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." })),
|
|
1164
1206
|
}, { additionalProperties: false }),
|
|
1165
1207
|
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
1166
1208
|
signal?.throwIfAborted();
|
|
@@ -1168,7 +1210,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1168
1210
|
if (!rawProjectDirectory) throw new Error("team_resume requires a project directory");
|
|
1169
1211
|
const managerSessionId = childRuntimeConfig ? context.sessionManager?.getSessionId?.() : undefined;
|
|
1170
1212
|
if (childRuntimeConfig && !managerSessionId) throw new Error("team_resume requires a persistent managing teammate Pi session");
|
|
1171
|
-
const availableManifests = listTeamManifests(rawProjectDirectory).filter(
|
|
1213
|
+
const availableManifests = listTeamManifests(rawProjectDirectory).manifests.filter(
|
|
1172
1214
|
(candidate) => !managerSessionId || candidate.originMainSessionId === managerSessionId,
|
|
1173
1215
|
);
|
|
1174
1216
|
const manifest = resolveTeamIdentifier(availableManifests, params.team);
|
|
@@ -1244,7 +1286,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1244
1286
|
throw error;
|
|
1245
1287
|
}
|
|
1246
1288
|
|
|
1247
|
-
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) });
|
|
1248
1290
|
return toolResult({
|
|
1249
1291
|
...lifecycleResult(team),
|
|
1250
1292
|
teammates: [...team.members.values()].map((teammate) => {
|
|
@@ -1263,10 +1305,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1263
1305
|
name: "team_add_teammates",
|
|
1264
1306
|
label: "Team Add",
|
|
1265
1307
|
description: "Add teammates to an active team you own. Existing teammates continue their work.",
|
|
1266
|
-
promptSnippet: "Add new teammates to a running team",
|
|
1267
1308
|
renderShell: "self",
|
|
1268
1309
|
renderCall: (args, theme, context) => renderTeamToolCall("team_add_teammates", args, theme, context, sessionTeammateRoster),
|
|
1269
|
-
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),
|
|
1270
1311
|
parameters: Type.Object({
|
|
1271
1312
|
team: Type.Optional(Type.String({ description: "Team name or persistent ID. Omit when exactly one owned active team exists." })),
|
|
1272
1313
|
// TODO: Accept existing current-project Pi session IDs as well as new teammate definitions.
|
|
@@ -1292,9 +1333,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1292
1333
|
if (teammateNames.includes("main")) throw new Error('"main" is reserved');
|
|
1293
1334
|
validateTeammateModels(teammateSpecs, context.modelRegistry.getAvailable());
|
|
1294
1335
|
|
|
1295
|
-
const
|
|
1296
|
-
const mainSessionFile =
|
|
1297
|
-
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.");
|
|
1298
1339
|
if (mainSessionFile) team.mainSessionFile = mainSessionFile;
|
|
1299
1340
|
|
|
1300
1341
|
const addedTeammates = teammateSpecs.map(createTeammateState);
|
|
@@ -1326,7 +1367,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1326
1367
|
...lifecycleResult(team),
|
|
1327
1368
|
teammates: [...team.members.values()].map(teammateSummary),
|
|
1328
1369
|
status: formatStatus(team),
|
|
1329
|
-
});
|
|
1370
|
+
}, { addedTeammates: addedTeammates.map(teammateRecord) });
|
|
1330
1371
|
},
|
|
1331
1372
|
}),
|
|
1332
1373
|
);
|
|
@@ -1395,12 +1436,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
1395
1436
|
}, signal));
|
|
1396
1437
|
}
|
|
1397
1438
|
if (!params.team && params.gerund === undefined && params.phrase === undefined) {
|
|
1398
|
-
|
|
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]!) })) });
|
|
1399
1442
|
}
|
|
1400
1443
|
const team = resolveTeam(owner, params.team);
|
|
1401
1444
|
updateStatus(team, "main", params.gerund, params.phrase);
|
|
1402
1445
|
logStatusDeclaration(team, "main", params.gerund, params.phrase);
|
|
1403
|
-
return toolResult({ ...teamIdentity(team), status: formatStatus(team) });
|
|
1446
|
+
return toolResult({ ...teamIdentity(team), status: formatStatus(team) }, { teammates: teammateViews(team) });
|
|
1404
1447
|
},
|
|
1405
1448
|
}),
|
|
1406
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
|
+
}
|