@giladbarnea/pi-simple-team 1.0.12 → 1.0.14
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 -0
- package/child-tools.ts +206 -1
- package/context-window.ts +19 -0
- package/index.ts +339 -60
- package/package.json +1 -1
- package/render.ts +12 -10
- package/screenshots/1.png +0 -0
package/README.md
CHANGED
|
@@ -69,7 +69,11 @@ Ask your main agent for a team.
|
|
|
69
69
|
- ⚡ Sub-second, when the recipient is idle.
|
|
70
70
|
- 🏎️ The moment the current bout of work ends, when busy.
|
|
71
71
|
|
|
72
|
+
### Herdr, first-class.
|
|
72
73
|
|
|
74
|
+
`pi-simple-team` gives each teammate a Pi session in its own [Herdr](https://herdr.dev) pane. Just ask your agent to do that.
|
|
75
|
+
|
|
76
|
+
You get a live view of the room. Main and teammates keep using the same tools.
|
|
73
77
|
|
|
74
78
|
### Statuses everyone can see.
|
|
75
79
|
|
package/child-tools.ts
CHANGED
|
@@ -1,13 +1,23 @@
|
|
|
1
|
-
import
|
|
1
|
+
import * as http from "node:http";
|
|
2
|
+
import { defineTool, getMarkdownTheme, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
3
|
import { Type } from "typebox";
|
|
4
|
+
import { formatContextWindowReport, requireKnownContextUsage } from "./context-window.ts";
|
|
5
|
+
import { renderTeamMessage } from "./render.ts";
|
|
3
6
|
|
|
4
7
|
type JsonRecord = Record<string, unknown>;
|
|
5
8
|
|
|
9
|
+
const teamMessageType = "pi-simple-team";
|
|
10
|
+
const defaultVisibleInterruptWaitTimeoutMilliseconds = 25_000;
|
|
11
|
+
const visibleLifecycleRetryAttempts = 3;
|
|
12
|
+
|
|
6
13
|
export interface ChildRuntimeConfig {
|
|
7
14
|
callbackUrl: string;
|
|
8
15
|
callbackToken: string;
|
|
9
16
|
teamName: string;
|
|
10
17
|
teammateName: string;
|
|
18
|
+
visible: boolean;
|
|
19
|
+
participants: string[];
|
|
20
|
+
interruptWaitTimeoutMilliseconds?: number;
|
|
11
21
|
}
|
|
12
22
|
|
|
13
23
|
function requiredEnvironmentVariable(name: string): string {
|
|
@@ -16,12 +26,23 @@ function requiredEnvironmentVariable(name: string): string {
|
|
|
16
26
|
return value;
|
|
17
27
|
}
|
|
18
28
|
|
|
29
|
+
function readParticipants(): string[] {
|
|
30
|
+
const value = requiredEnvironmentVariable("PI_SIMPLE_TEAM_PARTICIPANTS");
|
|
31
|
+
const participants = JSON.parse(value) as unknown;
|
|
32
|
+
if (!Array.isArray(participants) || participants.some((participant) => typeof participant !== "string")) {
|
|
33
|
+
throw new Error("PI_SIMPLE_TEAM_PARTICIPANTS must be a JSON string array");
|
|
34
|
+
}
|
|
35
|
+
return participants;
|
|
36
|
+
}
|
|
37
|
+
|
|
19
38
|
function readRequiredChildRuntimeConfig(): ChildRuntimeConfig {
|
|
20
39
|
return {
|
|
21
40
|
callbackUrl: requiredEnvironmentVariable("PI_SIMPLE_TEAM_CALLBACK_URL"),
|
|
22
41
|
callbackToken: requiredEnvironmentVariable("PI_SIMPLE_TEAM_CALLBACK_TOKEN"),
|
|
23
42
|
teamName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_TEAM"),
|
|
24
43
|
teammateName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_MEMBER"),
|
|
44
|
+
visible: process.env.PI_SIMPLE_TEAM_VISIBLE_CHILD === "1",
|
|
45
|
+
participants: readParticipants(),
|
|
25
46
|
};
|
|
26
47
|
}
|
|
27
48
|
|
|
@@ -58,7 +79,191 @@ function toolResult(payload: JsonRecord): { content: [{ type: "text"; text: stri
|
|
|
58
79
|
};
|
|
59
80
|
}
|
|
60
81
|
|
|
82
|
+
function writeJson(response: http.ServerResponse, statusCode: number, payload: JsonRecord): void {
|
|
83
|
+
const body = JSON.stringify(payload);
|
|
84
|
+
response.writeHead(statusCode, {
|
|
85
|
+
"content-type": "application/json",
|
|
86
|
+
"content-length": Buffer.byteLength(body),
|
|
87
|
+
});
|
|
88
|
+
response.end(body);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function readJsonBody(request: http.IncomingMessage): Promise<JsonRecord> {
|
|
92
|
+
const chunks: Buffer[] = [];
|
|
93
|
+
for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
94
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8")) as JsonRecord;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
interface VisibleDelivery {
|
|
98
|
+
team: string;
|
|
99
|
+
from: string;
|
|
100
|
+
to: string;
|
|
101
|
+
sentAt: string;
|
|
102
|
+
message: string;
|
|
103
|
+
formattedMessage: string;
|
|
104
|
+
interrupt: boolean;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function startVisibleChild(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
108
|
+
let server: http.Server | undefined;
|
|
109
|
+
let activeContext: ExtensionContext | undefined;
|
|
110
|
+
let idle = true;
|
|
111
|
+
let idleWaiters: Array<() => void> = [];
|
|
112
|
+
let lifecycleQueue: Promise<void> = Promise.resolve();
|
|
113
|
+
let lifecycleError: Error | undefined;
|
|
114
|
+
|
|
115
|
+
const notifyParent = (event: JsonRecord): Promise<void> => {
|
|
116
|
+
lifecycleQueue = lifecycleQueue.then(async () => {
|
|
117
|
+
if (lifecycleError) return;
|
|
118
|
+
for (let attempt = 1; attempt <= visibleLifecycleRetryAttempts; attempt += 1) {
|
|
119
|
+
try {
|
|
120
|
+
await callParent(config, "visible_event", { event });
|
|
121
|
+
return;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (attempt === visibleLifecycleRetryAttempts) lifecycleError = error instanceof Error ? error : new Error(String(error));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
return lifecycleQueue;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const waitForIdle = async (): Promise<void> => {
|
|
131
|
+
if (idle) return;
|
|
132
|
+
await new Promise<void>((resolve, reject) => {
|
|
133
|
+
let resolveIdle: () => void;
|
|
134
|
+
const timeout = setTimeout(() => {
|
|
135
|
+
idleWaiters = idleWaiters.filter((waiter) => waiter !== resolveIdle);
|
|
136
|
+
reject(new Error("Timed out waiting for visible child to settle after interrupt"));
|
|
137
|
+
}, config.interruptWaitTimeoutMilliseconds ?? defaultVisibleInterruptWaitTimeoutMilliseconds);
|
|
138
|
+
resolveIdle = (): void => {
|
|
139
|
+
clearTimeout(timeout);
|
|
140
|
+
resolve();
|
|
141
|
+
};
|
|
142
|
+
idleWaiters.push(resolveIdle);
|
|
143
|
+
});
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const markIdle = (): void => {
|
|
147
|
+
idle = true;
|
|
148
|
+
activeContext = undefined;
|
|
149
|
+
const waiters = idleWaiters;
|
|
150
|
+
idleWaiters = [];
|
|
151
|
+
for (const resolve of waiters) resolve();
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
pi.on("agent_start", (event, context) => {
|
|
155
|
+
idle = false;
|
|
156
|
+
activeContext = context;
|
|
157
|
+
notifyParent({ type: "agent_start" });
|
|
158
|
+
});
|
|
159
|
+
pi.on("agent_end", (event) => {
|
|
160
|
+
notifyParent({ type: "agent_end", messages: event.messages });
|
|
161
|
+
});
|
|
162
|
+
pi.on("agent_settled", () => {
|
|
163
|
+
notifyParent({ type: "agent_settled" });
|
|
164
|
+
markIdle();
|
|
165
|
+
});
|
|
166
|
+
pi.on("tool_execution_start", (event) => {
|
|
167
|
+
notifyParent({ type: "tool_execution_start", toolCallId: event.toolCallId, toolName: event.toolName, args: event.args });
|
|
168
|
+
});
|
|
169
|
+
pi.on("tool_execution_end", (event) => {
|
|
170
|
+
notifyParent({ type: "tool_execution_end", toolCallId: event.toolCallId, toolName: event.toolName, isError: event.isError, result: event.result });
|
|
171
|
+
});
|
|
172
|
+
pi.on("session_start", async (_event, context) => {
|
|
173
|
+
server = http.createServer((request, response) => {
|
|
174
|
+
void (async () => {
|
|
175
|
+
try {
|
|
176
|
+
const body = await readJsonBody(request);
|
|
177
|
+
if (body.token !== config.callbackToken) {
|
|
178
|
+
writeJson(response, 403, { error: "invalid token" });
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (body.tool === "report_context_window") {
|
|
183
|
+
writeJson(response, 200, { contextUsage: requireKnownContextUsage(context.getContextUsage()) });
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (body.tool !== "deliver") {
|
|
188
|
+
writeJson(response, 400, { error: `unknown tool: ${String(body.tool)}` });
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const delivery = body.args as unknown as VisibleDelivery;
|
|
193
|
+
if (lifecycleError) throw new Error(`Visible lifecycle callback failed: ${lifecycleError.message}`);
|
|
194
|
+
if (delivery.interrupt && activeContext) {
|
|
195
|
+
activeContext.abort();
|
|
196
|
+
await waitForIdle();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
pi.sendMessage(
|
|
200
|
+
{
|
|
201
|
+
customType: teamMessageType,
|
|
202
|
+
content: delivery.formattedMessage,
|
|
203
|
+
display: true,
|
|
204
|
+
details: {
|
|
205
|
+
team: delivery.team,
|
|
206
|
+
from: delivery.from,
|
|
207
|
+
to: delivery.to,
|
|
208
|
+
sentAt: delivery.sentAt,
|
|
209
|
+
message: delivery.message,
|
|
210
|
+
},
|
|
211
|
+
},
|
|
212
|
+
{ deliverAs: "steer", triggerTurn: true },
|
|
213
|
+
);
|
|
214
|
+
writeJson(response, 200, { accepted: true, team: config.teamName, from: delivery.from, to: delivery.to, interrupt: delivery.interrupt });
|
|
215
|
+
} catch (error) {
|
|
216
|
+
writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
217
|
+
}
|
|
218
|
+
})();
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
await new Promise<void>((resolve, reject) => {
|
|
222
|
+
server!.once("error", reject);
|
|
223
|
+
server!.listen(0, "127.0.0.1", () => resolve());
|
|
224
|
+
});
|
|
225
|
+
const address = server.address();
|
|
226
|
+
if (!address || typeof address === "string") throw new Error("Visible teammate server did not get a port");
|
|
227
|
+
|
|
228
|
+
try {
|
|
229
|
+
await callParent(config, "visible_register", { url: `http://127.0.0.1:${address.port}/deliver` });
|
|
230
|
+
} catch (error) {
|
|
231
|
+
context.shutdown();
|
|
232
|
+
throw error;
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
pi.on("session_shutdown", async (event) => {
|
|
237
|
+
markIdle();
|
|
238
|
+
await notifyParent({ type: "session_shutdown", reason: event.reason });
|
|
239
|
+
await new Promise<void>((resolve, reject) => {
|
|
240
|
+
if (!server) {
|
|
241
|
+
resolve();
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
server.close((error) => (error ? reject(error) : resolve()));
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
61
249
|
export function registerChildTools(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
250
|
+
pi.registerMessageRenderer(teamMessageType, (message, _options, theme) => renderTeamMessage(message, theme, getMarkdownTheme(), config.participants));
|
|
251
|
+
if (config.visible) startVisibleChild(pi, config);
|
|
252
|
+
|
|
253
|
+
pi.registerTool(
|
|
254
|
+
defineTool({
|
|
255
|
+
name: "report_context_window",
|
|
256
|
+
label: "Report Context Window",
|
|
257
|
+
description: "Report your current context-window use.",
|
|
258
|
+
promptSnippet: "Report your current context-window use",
|
|
259
|
+
parameters: Type.Object({}),
|
|
260
|
+
async execute(_toolCallId, _params, _signal, _onUpdate, context) {
|
|
261
|
+
const text = formatContextWindowReport("You have", requireKnownContextUsage(context.getContextUsage()));
|
|
262
|
+
return { content: [{ type: "text" as const, text }], details: {} };
|
|
263
|
+
},
|
|
264
|
+
}),
|
|
265
|
+
);
|
|
266
|
+
|
|
62
267
|
pi.registerTool(
|
|
63
268
|
defineTool({
|
|
64
269
|
name: "teamsend",
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ContextUsage } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
export interface KnownContextUsage {
|
|
4
|
+
tokens: number;
|
|
5
|
+
contextWindow: number;
|
|
6
|
+
percent: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function requireKnownContextUsage(usage: ContextUsage | undefined): KnownContextUsage {
|
|
10
|
+
if (!usage || usage.tokens === null || usage.percent === null) throw new Error("Context usage is unavailable");
|
|
11
|
+
return { tokens: usage.tokens, contextWindow: usage.contextWindow, percent: usage.percent };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** @example formatContextWindowReport("You have", { tokens: 87_000, contextWindow: 272_000, percent: 32 }) */
|
|
15
|
+
export function formatContextWindowReport(subjectWithVerb: string, usage: KnownContextUsage): string {
|
|
16
|
+
const tokens = `${Math.round(usage.tokens / 1_000)}k`;
|
|
17
|
+
const contextWindow = `${Math.round(usage.contextWindow / 1_000)}k`;
|
|
18
|
+
return `${subjectWithVerb} used ${tokens} tokens out of ${contextWindow} available (${Math.round(usage.percent)}%).`;
|
|
19
|
+
}
|
package/index.ts
CHANGED
|
@@ -4,7 +4,8 @@ import crypto from "node:crypto";
|
|
|
4
4
|
import http from "node:http";
|
|
5
5
|
import { StringDecoder } from "node:string_decoder";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
|
-
import { defineTool, type ExtensionAPI, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { defineTool, type ContextUsage, type ExtensionAPI, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { formatContextWindowReport, requireKnownContextUsage, type KnownContextUsage } from "./context-window.ts";
|
|
8
9
|
import { validateTeammateModels } from "./model-preflight.ts";
|
|
9
10
|
import { composeSystemPrompt } from "./system-prompt.ts";
|
|
10
11
|
import { readChildRuntimeConfig, registerChildTools } from "./child-tools.ts";
|
|
@@ -45,12 +46,20 @@ interface TeammateSpec {
|
|
|
45
46
|
thinking?: ThinkingLevel;
|
|
46
47
|
}
|
|
47
48
|
|
|
49
|
+
type TeammateTransport = "rpc" | "herdr";
|
|
50
|
+
|
|
48
51
|
interface TeammateState {
|
|
49
52
|
name: string;
|
|
50
53
|
prompt: string;
|
|
51
54
|
model: string;
|
|
52
55
|
thinking: ThinkingLevel;
|
|
53
|
-
|
|
56
|
+
transport: TeammateTransport;
|
|
57
|
+
process?: ChildProcess;
|
|
58
|
+
paneId?: string;
|
|
59
|
+
visibleUrl?: string;
|
|
60
|
+
visibleReady?: Promise<void>;
|
|
61
|
+
resolveVisibleReady?: () => void;
|
|
62
|
+
rejectVisibleReady?: (error: Error) => void;
|
|
54
63
|
busy: boolean;
|
|
55
64
|
alive: boolean;
|
|
56
65
|
pendingRequests: Map<string, PendingRequest>;
|
|
@@ -63,6 +72,7 @@ interface TeamState {
|
|
|
63
72
|
owner: symbol;
|
|
64
73
|
ownerPi: ExtensionAPI;
|
|
65
74
|
name: string;
|
|
75
|
+
showOnHerdrPanes: boolean;
|
|
66
76
|
teamPrompt: string;
|
|
67
77
|
members: Map<string, TeammateState>;
|
|
68
78
|
statuses: Map<string, TeamStatus>;
|
|
@@ -74,6 +84,7 @@ interface TeamState {
|
|
|
74
84
|
const teamLiteExtensionPath = fileURLToPath(import.meta.url);
|
|
75
85
|
const thinkingLevels = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
76
86
|
const defaultThinkingLevel: ThinkingLevel = "xhigh";
|
|
87
|
+
const visibleDeliveryTimeoutMilliseconds = 30_000;
|
|
77
88
|
const teamMessageType = "pi-simple-team";
|
|
78
89
|
const teams = new Map<string, TeamState>();
|
|
79
90
|
const callbackToken = crypto.randomBytes(24).toString("hex");
|
|
@@ -102,6 +113,41 @@ function sleep(milliseconds: number): Promise<void> {
|
|
|
102
113
|
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
103
114
|
}
|
|
104
115
|
|
|
116
|
+
interface CommandResult {
|
|
117
|
+
stdout: string;
|
|
118
|
+
stderr: string;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function runCommand(command: string, args: string[], timeoutMilliseconds = 30_000): Promise<CommandResult> {
|
|
122
|
+
return new Promise((resolve, reject) => {
|
|
123
|
+
childProcess.execFile(command, args, { timeout: timeoutMilliseconds, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
|
|
124
|
+
if (error) {
|
|
125
|
+
reject(new Error(`${command} ${args.join(" ")} failed: ${error.message}${stderr.trim() ? `\n${stderr.trim()}` : ""}`));
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
resolve({ stdout, stderr });
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function validateHerdrAvailability(): Promise<string> {
|
|
134
|
+
const tabId = process.env.HERDR_TAB_ID?.trim();
|
|
135
|
+
if (!tabId) throw new Error("showOnHerdrPanes requires HERDR_TAB_ID in the main Pi process");
|
|
136
|
+
|
|
137
|
+
let result: CommandResult;
|
|
138
|
+
try {
|
|
139
|
+
result = await runCommand("herdr", ["status", "--json"], 10_000);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
throw new Error(`showOnHerdrPanes requires an available Herdr server: ${error instanceof Error ? error.message : String(error)}`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const status = JSON.parse(result.stdout) as { server?: { running?: boolean; compatible?: boolean } };
|
|
145
|
+
if (!status.server?.running || status.server.compatible === false) {
|
|
146
|
+
throw new Error("showOnHerdrPanes requires a running compatible Herdr server");
|
|
147
|
+
}
|
|
148
|
+
return tabId;
|
|
149
|
+
}
|
|
150
|
+
|
|
105
151
|
function serializeJsonLine(value: unknown): string {
|
|
106
152
|
return `${JSON.stringify(value)}\n`;
|
|
107
153
|
}
|
|
@@ -166,8 +212,8 @@ function handleTeammateEvent(team: TeamState, teammate: TeammateState, event: Js
|
|
|
166
212
|
}
|
|
167
213
|
|
|
168
214
|
function sendRpc(teammate: TeammateState, command: JsonRecord, timeoutMilliseconds = 30_000): Promise<RpcResponse> {
|
|
169
|
-
if (!teammate.alive || teammate.process.exitCode !== null) {
|
|
170
|
-
throw new Error(`Teammate ${teammate.name} is not alive`);
|
|
215
|
+
if (teammate.transport !== "rpc" || !teammate.process || !teammate.alive || teammate.process.exitCode !== null) {
|
|
216
|
+
throw new Error(`Teammate ${teammate.name} is not alive through RPC`);
|
|
171
217
|
}
|
|
172
218
|
|
|
173
219
|
const id = `team-${++requestCounter}`;
|
|
@@ -180,7 +226,7 @@ function sendRpc(teammate: TeammateState, command: JsonRecord, timeoutMillisecon
|
|
|
180
226
|
}, timeoutMilliseconds);
|
|
181
227
|
|
|
182
228
|
teammate.pendingRequests.set(id, { resolve, reject, timeout });
|
|
183
|
-
teammate.process
|
|
229
|
+
teammate.process!.stdin?.write(serializeJsonLine(payload));
|
|
184
230
|
});
|
|
185
231
|
}
|
|
186
232
|
|
|
@@ -190,6 +236,8 @@ async function requireSuccessfulResponse(response: RpcResponse, action: string):
|
|
|
190
236
|
}
|
|
191
237
|
|
|
192
238
|
async function getTeammateBusy(teammate: TeammateState): Promise<boolean> {
|
|
239
|
+
if (teammate.transport === "herdr") return teammate.busy;
|
|
240
|
+
|
|
193
241
|
const response = await sendRpc(teammate, { type: "get_state" }, 10_000);
|
|
194
242
|
if (!response.success) return teammate.busy;
|
|
195
243
|
const data = response.data as { isStreaming?: boolean } | undefined;
|
|
@@ -250,6 +298,33 @@ function formatTeammateMessage(team: TeamState, from: string, message: string):
|
|
|
250
298
|
return [`[from ${from} on team ${team.name}]`, message, "", "Current team status:", JSON.stringify(formatStatus(team), null, 2)].join("\n");
|
|
251
299
|
}
|
|
252
300
|
|
|
301
|
+
async function deliverVisibleMessage(team: TeamState, from: string, recipient: TeammateState, message: string, formattedMessage: string, interrupt: boolean): Promise<void> {
|
|
302
|
+
if (!recipient.alive || !recipient.visibleUrl) throw new Error(`Visible teammate ${recipient.name} is not ready`);
|
|
303
|
+
const controller = new AbortController();
|
|
304
|
+
const timeout = setTimeout(() => controller.abort(), visibleDeliveryTimeoutMilliseconds);
|
|
305
|
+
try {
|
|
306
|
+
const response = await fetch(recipient.visibleUrl, {
|
|
307
|
+
method: "POST",
|
|
308
|
+
headers: { "content-type": "application/json" },
|
|
309
|
+
body: JSON.stringify({
|
|
310
|
+
token: callbackToken,
|
|
311
|
+
tool: "deliver",
|
|
312
|
+
args: { team: team.name, from, to: recipient.name, sentAt: nowText(), message, formattedMessage, interrupt },
|
|
313
|
+
}),
|
|
314
|
+
signal: controller.signal,
|
|
315
|
+
});
|
|
316
|
+
if (!response.ok) throw new Error(`Visible teammate ${recipient.name} rejected delivery: ${response.status} ${await response.text()}`);
|
|
317
|
+
const result = (await response.json()) as { accepted?: boolean };
|
|
318
|
+
if (!result.accepted) throw new Error(`Visible teammate ${recipient.name} did not accept delivery`);
|
|
319
|
+
appendTeamLog(team, { team: team.name, teammate: recipient.name, direction: "runtime", kind: "ack", summary: "visible message accepted" });
|
|
320
|
+
} catch (error) {
|
|
321
|
+
if (controller.signal.aborted) throw new Error(`Timed out waiting for visible teammate ${recipient.name} delivery`);
|
|
322
|
+
throw error;
|
|
323
|
+
} finally {
|
|
324
|
+
clearTimeout(timeout);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
253
328
|
async function deliverToTeammate(team: TeamState, from: string, recipient: TeammateState, message: string, interrupt: boolean): Promise<void> {
|
|
254
329
|
const formattedMessage = formatTeammateMessage(team, from, message);
|
|
255
330
|
appendTeamLog(team, {
|
|
@@ -260,6 +335,10 @@ async function deliverToTeammate(team: TeamState, from: string, recipient: Teamm
|
|
|
260
335
|
summary: preview(message),
|
|
261
336
|
details: { from, to: recipient.name, interrupt },
|
|
262
337
|
});
|
|
338
|
+
if (recipient.transport === "herdr") {
|
|
339
|
+
await deliverVisibleMessage(team, from, recipient, message, formattedMessage, interrupt);
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
263
342
|
|
|
264
343
|
if (interrupt && (recipient.busy || (await getTeammateBusy(recipient)))) {
|
|
265
344
|
await requireSuccessfulResponse(await sendRpc(recipient, { type: "abort" }, 60_000), `abort ${recipient.name}`);
|
|
@@ -330,6 +409,40 @@ function resolveRecipients(team: TeamState, recipientNames: string[]): TeammateS
|
|
|
330
409
|
return recipients as TeammateState[];
|
|
331
410
|
}
|
|
332
411
|
|
|
412
|
+
function resolveContextTargets(owner: symbol, targetNames: string[]): TeammateState[] {
|
|
413
|
+
const ownedTeams = [...teams.values()].filter((team) => team.owner === owner);
|
|
414
|
+
const names = targetNames.map(compactName).filter((name) => name !== "main");
|
|
415
|
+
return names.map((name) => {
|
|
416
|
+
const matches = ownedTeams.flatMap((team) => {
|
|
417
|
+
const teammate = team.members.get(name);
|
|
418
|
+
return teammate ? [teammate] : [];
|
|
419
|
+
});
|
|
420
|
+
if (matches.length === 0) throw new Error(`Unknown teammate: ${name}`);
|
|
421
|
+
if (matches.length > 1) throw new Error(`Ambiguous teammate across teams: ${name}`);
|
|
422
|
+
return matches[0];
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async function getTeammateContextUsage(teammate: TeammateState, signal?: AbortSignal): Promise<KnownContextUsage> {
|
|
427
|
+
if (teammate.transport === "rpc") {
|
|
428
|
+
const response = await sendRpc(teammate, { type: "get_session_stats" });
|
|
429
|
+
await requireSuccessfulResponse(response, `read context usage from ${teammate.name}`);
|
|
430
|
+
const stats = response.data as { contextUsage?: ContextUsage };
|
|
431
|
+
return requireKnownContextUsage(stats.contextUsage);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
if (!teammate.alive || !teammate.visibleUrl) throw new Error(`Visible teammate ${teammate.name} is not ready`);
|
|
435
|
+
const response = await fetch(teammate.visibleUrl, {
|
|
436
|
+
method: "POST",
|
|
437
|
+
headers: { "content-type": "application/json" },
|
|
438
|
+
body: JSON.stringify({ token: callbackToken, tool: "report_context_window", args: {} }),
|
|
439
|
+
signal,
|
|
440
|
+
});
|
|
441
|
+
if (!response.ok) throw new Error(`Visible teammate ${teammate.name} rejected context-window query: ${response.status} ${await response.text()}`);
|
|
442
|
+
const payload = (await response.json()) as { contextUsage?: ContextUsage };
|
|
443
|
+
return requireKnownContextUsage(payload.contextUsage);
|
|
444
|
+
}
|
|
445
|
+
|
|
333
446
|
function formatStatus(team: TeamState): Record<string, TeamStatus> {
|
|
334
447
|
return Object.fromEntries([...team.statuses.entries()].sort(([a], [b]) => a.localeCompare(b)));
|
|
335
448
|
}
|
|
@@ -357,10 +470,60 @@ function logStatusDeclaration(team: TeamState, participant: string, word?: strin
|
|
|
357
470
|
});
|
|
358
471
|
}
|
|
359
472
|
|
|
360
|
-
|
|
361
|
-
function startTeammate(team: TeamState, teammateSpec: TeammateSpec, participants: string[]): TeammateState {
|
|
473
|
+
function createTeammateState(team: TeamState, teammateSpec: TeammateSpec): TeammateState {
|
|
362
474
|
const teammateName = compactName(teammateSpec.name);
|
|
363
475
|
const thinking = teammateSpec.thinking ?? defaultThinkingLevel;
|
|
476
|
+
let resolveVisibleReady: (() => void) | undefined;
|
|
477
|
+
let rejectVisibleReady: ((error: Error) => void) | undefined;
|
|
478
|
+
const visibleReady = team.showOnHerdrPanes
|
|
479
|
+
? new Promise<void>((resolve, reject) => {
|
|
480
|
+
resolveVisibleReady = resolve;
|
|
481
|
+
rejectVisibleReady = reject;
|
|
482
|
+
})
|
|
483
|
+
: undefined;
|
|
484
|
+
|
|
485
|
+
return {
|
|
486
|
+
name: teammateName,
|
|
487
|
+
prompt: teammateSpec.prompt,
|
|
488
|
+
model: teammateSpec.model,
|
|
489
|
+
thinking,
|
|
490
|
+
transport: team.showOnHerdrPanes ? "herdr" : "rpc",
|
|
491
|
+
visibleReady,
|
|
492
|
+
resolveVisibleReady,
|
|
493
|
+
rejectVisibleReady,
|
|
494
|
+
busy: false,
|
|
495
|
+
alive: true,
|
|
496
|
+
pendingRequests: new Map(),
|
|
497
|
+
deliveryQueue: Promise.resolve(),
|
|
498
|
+
recentEvents: [],
|
|
499
|
+
stderr: "",
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, participants: string[], visible: boolean): Record<string, string> {
|
|
504
|
+
return {
|
|
505
|
+
PI_SIMPLE_TEAM_CHILD: "1",
|
|
506
|
+
PI_SIMPLE_TEAM_VISIBLE_CHILD: visible ? "1" : "0",
|
|
507
|
+
PI_SIMPLE_TEAM_CALLBACK_URL: callbackUrl,
|
|
508
|
+
PI_SIMPLE_TEAM_CALLBACK_TOKEN: callbackToken,
|
|
509
|
+
PI_SIMPLE_TEAM_TEAM: team.name,
|
|
510
|
+
PI_SIMPLE_TEAM_MEMBER: teammate.name,
|
|
511
|
+
PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function appendSpawnLog(team: TeamState, teammate: TeammateState): void {
|
|
516
|
+
appendTeamLog(team, {
|
|
517
|
+
team: team.name,
|
|
518
|
+
teammate: teammate.name,
|
|
519
|
+
direction: "runtime",
|
|
520
|
+
kind: "spawn",
|
|
521
|
+
summary: `spawned ${teammate.name} (model=${teammate.model}, thinking=${teammate.thinking})`,
|
|
522
|
+
details: { model: teammate.model, thinking: teammate.thinking, transport: teammate.transport, paneId: teammate.paneId },
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function attachRpcTeammate(team: TeamState, teammate: TeammateState, participants: string[]): void {
|
|
364
527
|
const args = [
|
|
365
528
|
"--mode",
|
|
366
529
|
"rpc",
|
|
@@ -369,39 +532,18 @@ function startTeammate(team: TeamState, teammateSpec: TeammateSpec, participants
|
|
|
369
532
|
"--no-prompt-templates",
|
|
370
533
|
"--no-themes",
|
|
371
534
|
"--model",
|
|
372
|
-
|
|
535
|
+
teammate.model,
|
|
373
536
|
"--thinking",
|
|
374
|
-
thinking,
|
|
537
|
+
teammate.thinking,
|
|
375
538
|
"--system-prompt",
|
|
376
|
-
composeSystemPrompt(team.name, team.teamPrompt,
|
|
539
|
+
composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants),
|
|
377
540
|
];
|
|
378
|
-
|
|
379
541
|
const proc = childProcess.spawn("pi", args, {
|
|
380
542
|
cwd: process.cwd(),
|
|
381
543
|
stdio: ["pipe", "pipe", "pipe"],
|
|
382
|
-
env: {
|
|
383
|
-
...process.env,
|
|
384
|
-
PI_SIMPLE_TEAM_CHILD: "1",
|
|
385
|
-
PI_SIMPLE_TEAM_CALLBACK_URL: callbackUrl,
|
|
386
|
-
PI_SIMPLE_TEAM_CALLBACK_TOKEN: callbackToken,
|
|
387
|
-
PI_SIMPLE_TEAM_TEAM: team.name,
|
|
388
|
-
PI_SIMPLE_TEAM_MEMBER: teammateName,
|
|
389
|
-
},
|
|
544
|
+
env: { ...process.env, ...childEnvironmentOverrides(team, teammate, participants, false) },
|
|
390
545
|
});
|
|
391
|
-
|
|
392
|
-
const teammate: TeammateState = {
|
|
393
|
-
name: teammateName,
|
|
394
|
-
prompt: teammateSpec.prompt,
|
|
395
|
-
model: teammateSpec.model,
|
|
396
|
-
thinking,
|
|
397
|
-
process: proc,
|
|
398
|
-
busy: false,
|
|
399
|
-
alive: true,
|
|
400
|
-
pendingRequests: new Map(),
|
|
401
|
-
deliveryQueue: Promise.resolve(),
|
|
402
|
-
recentEvents: [],
|
|
403
|
-
stderr: "",
|
|
404
|
-
};
|
|
546
|
+
teammate.process = proc;
|
|
405
547
|
|
|
406
548
|
attachJsonlReader(proc.stdout!, (line) => {
|
|
407
549
|
if (!line.trim()) return;
|
|
@@ -411,49 +553,98 @@ function startTeammate(team: TeamState, teammateSpec: TeammateSpec, participants
|
|
|
411
553
|
teammate.stderr += `\n[unparsed stdout] ${line}`;
|
|
412
554
|
}
|
|
413
555
|
});
|
|
414
|
-
|
|
415
556
|
proc.stderr?.on("data", (chunk: Buffer | string) => {
|
|
416
557
|
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
417
558
|
teammate.stderr += text;
|
|
418
559
|
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "stderr", summary: preview(text) });
|
|
419
560
|
});
|
|
420
|
-
|
|
421
561
|
proc.on("exit", (code, signal) => {
|
|
422
562
|
teammate.alive = false;
|
|
423
563
|
teammate.busy = false;
|
|
424
564
|
rejectPendingRequests(teammate, new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
|
|
425
565
|
team.statuses.set(teammate.name, status("stopped", `Exited code=${code} signal=${signal}`));
|
|
426
|
-
appendTeamLog(team, {
|
|
427
|
-
team: team.name,
|
|
428
|
-
teammate: teammate.name,
|
|
429
|
-
direction: "runtime",
|
|
430
|
-
kind: "exit",
|
|
431
|
-
summary: `exited (code=${code}, signal=${signal})`,
|
|
432
|
-
details: { code, signal },
|
|
433
|
-
});
|
|
566
|
+
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `exited (code=${code}, signal=${signal})`, details: { code, signal } });
|
|
434
567
|
});
|
|
568
|
+
appendSpawnLog(team, teammate);
|
|
569
|
+
}
|
|
435
570
|
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
571
|
+
function parseHerdrPaneId(stdout: string, teammateName: string): string {
|
|
572
|
+
const response = JSON.parse(stdout) as { result?: { agent?: { pane_id?: string } } };
|
|
573
|
+
const paneId = response.result?.agent?.pane_id;
|
|
574
|
+
if (!paneId) throw new Error(`herdr agent start did not return a pane for ${teammateName}`);
|
|
575
|
+
return paneId;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
async function attachVisibleTeammate(team: TeamState, teammate: TeammateState, participants: string[], herdrTabId: string): Promise<void> {
|
|
579
|
+
const systemPrompt = composeSystemPrompt(team.name, team.teamPrompt, teammate.name, teammate.prompt, participants);
|
|
580
|
+
const environment = childEnvironmentOverrides(team, teammate, participants, true);
|
|
581
|
+
const args = ["agent", "start", teammate.name, "--tab", herdrTabId, "--split", "right", "--no-focus", "--cwd", process.cwd()];
|
|
582
|
+
for (const [name, value] of Object.entries(environment)) {
|
|
583
|
+
if (value !== undefined) args.push("--env", `${name}=${value}`);
|
|
584
|
+
}
|
|
585
|
+
args.push("--", "pi", "-e", teamLiteExtensionPath, "--model", teammate.model, "--thinking", teammate.thinking, "--system-prompt", systemPrompt);
|
|
586
|
+
const result = await runCommand("herdr", args);
|
|
587
|
+
teammate.paneId = parseHerdrPaneId(result.stdout, teammate.name);
|
|
588
|
+
appendSpawnLog(team, teammate);
|
|
589
|
+
|
|
590
|
+
let readinessTimeout: ReturnType<typeof setTimeout> | undefined;
|
|
591
|
+
try {
|
|
592
|
+
await Promise.race([
|
|
593
|
+
teammate.visibleReady!,
|
|
594
|
+
new Promise<never>((_, reject) => {
|
|
595
|
+
readinessTimeout = setTimeout(() => reject(new Error(`Timed out waiting for visible teammate ${teammate.name} readiness`)), 30_000);
|
|
596
|
+
}),
|
|
597
|
+
]);
|
|
598
|
+
} catch (error) {
|
|
599
|
+
teammate.rejectVisibleReady?.(error instanceof Error ? error : new Error(String(error)));
|
|
600
|
+
throw error;
|
|
601
|
+
} finally {
|
|
602
|
+
if (readinessTimeout) clearTimeout(readinessTimeout);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
444
605
|
|
|
445
|
-
|
|
606
|
+
async function startTeammate(team: TeamState, teammate: TeammateState, participants: string[], herdrTabId?: string): Promise<void> {
|
|
607
|
+
if (teammate.transport === "herdr") {
|
|
608
|
+
await attachVisibleTeammate(team, teammate, participants, herdrTabId!);
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
attachRpcTeammate(team, teammate, participants);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function isHerdrPaneNotFound(error: unknown): boolean {
|
|
615
|
+
return error instanceof Error && error.message.includes('"code":"pane_not_found"');
|
|
446
616
|
}
|
|
447
617
|
|
|
448
|
-
function
|
|
618
|
+
async function closeVisiblePane(teammate: TeammateState): Promise<void> {
|
|
619
|
+
if (!teammate.paneId) return;
|
|
620
|
+
try {
|
|
621
|
+
await runCommand("herdr", ["pane", "close", teammate.paneId], 10_000);
|
|
622
|
+
} catch (error) {
|
|
623
|
+
if (!isHerdrPaneNotFound(error)) throw error;
|
|
624
|
+
}
|
|
625
|
+
teammate.paneId = undefined;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
async function shutdownTeam(team: TeamState): Promise<string[]> {
|
|
629
|
+
const errors: string[] = [];
|
|
449
630
|
for (const teammate of team.members.values()) {
|
|
450
631
|
teammate.alive = false;
|
|
632
|
+
if (teammate.transport === "herdr") {
|
|
633
|
+
try {
|
|
634
|
+
await closeVisiblePane(teammate);
|
|
635
|
+
} catch (error) {
|
|
636
|
+
errors.push(error instanceof Error ? error.message : String(error));
|
|
637
|
+
}
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
if (!teammate.process) continue;
|
|
451
641
|
teammate.process.kill("SIGTERM");
|
|
452
642
|
setTimeout(() => {
|
|
453
|
-
if (teammate.process
|
|
643
|
+
if (teammate.process?.exitCode === null) teammate.process.kill("SIGKILL");
|
|
454
644
|
}, 1_000).unref();
|
|
455
645
|
}
|
|
456
646
|
teams.delete(team.name);
|
|
647
|
+
return errors;
|
|
457
648
|
}
|
|
458
649
|
|
|
459
650
|
function closeCallbackServerIfUnused(): void {
|
|
@@ -495,6 +686,42 @@ function writeJson(response: http.ServerResponse, statusCode: number, payload: J
|
|
|
495
686
|
response.end(body);
|
|
496
687
|
}
|
|
497
688
|
|
|
689
|
+
function validateVisibleChildUrl(rawUrl: string, teammateName: string): string {
|
|
690
|
+
let url: URL;
|
|
691
|
+
try {
|
|
692
|
+
url = new URL(rawUrl);
|
|
693
|
+
} catch {
|
|
694
|
+
throw new Error(`Invalid visible teammate URL for ${teammateName}`);
|
|
695
|
+
}
|
|
696
|
+
const port = Number(url.port);
|
|
697
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port || !Number.isInteger(port) || port < 1 || port > 65_535 || url.pathname !== "/deliver") {
|
|
698
|
+
throw new Error(`Invalid visible teammate URL for ${teammateName}`);
|
|
699
|
+
}
|
|
700
|
+
return url.toString();
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
function handleVisibleEvent(team: TeamState, teammate: TeammateState, event: JsonRecord): void {
|
|
704
|
+
if (event.type === "visible_startup_error") {
|
|
705
|
+
const error = new Error(String(event.error ?? "Visible teammate startup failed"));
|
|
706
|
+
teammate.rejectVisibleReady?.(error);
|
|
707
|
+
throw error;
|
|
708
|
+
}
|
|
709
|
+
if (event.type === "agent_start") teammate.busy = true;
|
|
710
|
+
if (event.type === "agent_end") teammate.busy = false;
|
|
711
|
+
if (event.type === "session_shutdown") {
|
|
712
|
+
teammate.alive = false;
|
|
713
|
+
teammate.busy = false;
|
|
714
|
+
teammate.visibleUrl = undefined;
|
|
715
|
+
if (event.reason === "quit") {
|
|
716
|
+
team.statuses.set(teammate.name, status("stopped", "Session shut down"));
|
|
717
|
+
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "visible session shut down", details: { reason: event.reason } });
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
pushRecentEvent(teammate, event);
|
|
721
|
+
const logInput = normalizeChildEvent(team.name, teammate.name, event);
|
|
722
|
+
if (logInput) appendTeamLog(team, logInput);
|
|
723
|
+
}
|
|
724
|
+
|
|
498
725
|
async function handleCallbackRequest(request: http.IncomingMessage, response: http.ServerResponse): Promise<void> {
|
|
499
726
|
try {
|
|
500
727
|
const body = await readJsonBody(request);
|
|
@@ -507,6 +734,32 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
507
734
|
const from = compactName(String(body.from));
|
|
508
735
|
const tool = String(body.tool);
|
|
509
736
|
const args = (body.args ?? {}) as JsonRecord;
|
|
737
|
+
const teammate = team.members.get(from);
|
|
738
|
+
|
|
739
|
+
if (tool === "visible_register") {
|
|
740
|
+
if (!teammate || teammate.transport !== "herdr") throw new Error(`Unknown visible teammate: ${from}`);
|
|
741
|
+
const url = String(args.url ?? "");
|
|
742
|
+
try {
|
|
743
|
+
teammate.visibleUrl = validateVisibleChildUrl(url, from);
|
|
744
|
+
} catch (error) {
|
|
745
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
746
|
+
teammate.rejectVisibleReady?.(failure);
|
|
747
|
+
throw failure;
|
|
748
|
+
}
|
|
749
|
+
teammate.alive = true;
|
|
750
|
+
teammate.busy = false;
|
|
751
|
+
team.statuses.set(teammate.name, status("idle", "Spawned"));
|
|
752
|
+
teammate.resolveVisibleReady?.();
|
|
753
|
+
writeJson(response, 200, { accepted: true, team: team.name, from });
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
if (tool === "visible_event") {
|
|
758
|
+
if (!teammate || teammate.transport !== "herdr") throw new Error(`Unknown visible teammate: ${from}`);
|
|
759
|
+
handleVisibleEvent(team, teammate, (args.event ?? {}) as JsonRecord);
|
|
760
|
+
writeJson(response, 200, { accepted: true, team: team.name, from });
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
510
763
|
|
|
511
764
|
if (tool === "teamsend") {
|
|
512
765
|
const recipients = resolveRecipients(team, (args.to ?? []) as string[]);
|
|
@@ -564,7 +817,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
564
817
|
|
|
565
818
|
pi.on("session_shutdown", async () => {
|
|
566
819
|
for (const team of [...teams.values()]) {
|
|
567
|
-
if (team.owner === owner) shutdownTeam(team);
|
|
820
|
+
if (team.owner === owner) await shutdownTeam(team);
|
|
568
821
|
}
|
|
569
822
|
closeCallbackServerIfUnused();
|
|
570
823
|
});
|
|
@@ -574,8 +827,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
574
827
|
defineTool({
|
|
575
828
|
name: "team_spawn",
|
|
576
829
|
label: "Team Spawn",
|
|
577
|
-
description: "Spawn a persistent team of
|
|
578
|
-
promptSnippet: "Spawn persistent
|
|
830
|
+
description: "Spawn a persistent team of Pi teammates with fresh context windows. Set showOnHerdrPanes to run each teammate in a visible Herdr pane. The main agent (you) is included automatically; do not specify it as a teammate.",
|
|
831
|
+
promptSnippet: "Spawn persistent Pi teammates. Set showOnHerdrPanes to true when user-visible teammate sessions add value. Currently, manually ‘starting’ the teammates is required after spawn. Unless required, don’t fill up your time by repeatedly busy-polling team information. Don’t bash sleep to wait for progress; instead, set your status to advertise that you are counting on teammates to send you important milestones or requests for help, and that otherwise you are staying idle. Send this actively to the team. Then end your turn by sending a simple message to the user, and finally stay put.",
|
|
579
832
|
renderShell: "self",
|
|
580
833
|
renderCall: (args, theme, context) => renderTeamToolCall("team_spawn", args, theme, context, sessionTeammateRoster),
|
|
581
834
|
renderResult: (result, options, theme, context) => renderTeamToolResult("team_spawn", result, options, theme, context, undefined, sessionTeammateRoster),
|
|
@@ -583,10 +836,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
583
836
|
team: Type.String({ description: "Team name" }),
|
|
584
837
|
teamPrompt: Type.String({ description: "Common team system prompt" }),
|
|
585
838
|
teammates: Type.Array(teammateSchema, { description: "Teammates to spawn" }),
|
|
839
|
+
showOnHerdrPanes: Type.Optional(Type.Boolean({ description: "Run each teammate in a visible Herdr pane instead of RPC mode", default: false })),
|
|
586
840
|
}),
|
|
587
841
|
async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
|
|
588
842
|
const teamName = compactName(params.team);
|
|
589
843
|
if (teams.has(teamName)) throw new Error(`Team already exists: ${teamName}`);
|
|
844
|
+
const showOnHerdrPanes = Boolean(params.showOnHerdrPanes);
|
|
845
|
+
const herdrTabId = showOnHerdrPanes ? await validateHerdrAvailability() : undefined;
|
|
590
846
|
|
|
591
847
|
const teammateSpecs = params.teammates as TeammateSpec[];
|
|
592
848
|
const teammateNames = teammateSpecs.map((teammate) => compactName(teammate.name));
|
|
@@ -602,6 +858,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
602
858
|
owner,
|
|
603
859
|
ownerPi: pi,
|
|
604
860
|
name: teamName,
|
|
861
|
+
showOnHerdrPanes,
|
|
605
862
|
teamPrompt: params.teamPrompt,
|
|
606
863
|
members: new Map(),
|
|
607
864
|
statuses: new Map([["main", status("available", "Main agent")]]),
|
|
@@ -613,12 +870,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
613
870
|
teams.set(teamName, team);
|
|
614
871
|
try {
|
|
615
872
|
for (const teammateSpec of teammateSpecs) {
|
|
616
|
-
const teammate =
|
|
873
|
+
const teammate = createTeammateState(team, teammateSpec);
|
|
617
874
|
team.members.set(teammate.name, teammate);
|
|
618
875
|
team.statuses.set(teammate.name, status("idle", "Spawned"));
|
|
876
|
+
await startTeammate(team, teammate, teammateNames, herdrTabId);
|
|
619
877
|
}
|
|
620
878
|
} catch (error) {
|
|
621
|
-
shutdownTeam(team);
|
|
879
|
+
await shutdownTeam(team);
|
|
622
880
|
closeCallbackServerIfUnused();
|
|
623
881
|
throw error;
|
|
624
882
|
}
|
|
@@ -684,6 +942,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
684
942
|
}),
|
|
685
943
|
);
|
|
686
944
|
|
|
945
|
+
pi.registerTool(
|
|
946
|
+
defineTool({
|
|
947
|
+
name: "report_context_window",
|
|
948
|
+
label: "Report Context Window",
|
|
949
|
+
description: "Report context-window use for selected teammates and main. Main's report is always last.",
|
|
950
|
+
promptSnippet: "Report context-window use for selected teammates and main",
|
|
951
|
+
parameters: Type.Object({
|
|
952
|
+
targets: Type.Array(Type.String({ minLength: 1 }), { description: "Teammate names. Use an empty list to report only main." }),
|
|
953
|
+
}),
|
|
954
|
+
async execute(_toolCallId, params, signal, _onUpdate, context) {
|
|
955
|
+
const teammates = resolveContextTargets(owner, params.targets);
|
|
956
|
+
const reports = await Promise.all(
|
|
957
|
+
teammates.map(async (teammate) => formatContextWindowReport(`Teammate ${teammate.name} has`, await getTeammateContextUsage(teammate, signal))),
|
|
958
|
+
);
|
|
959
|
+
reports.push(formatContextWindowReport("You have", requireKnownContextUsage(context.getContextUsage())));
|
|
960
|
+
return { content: [{ type: "text" as const, text: reports.join("\n") }], details: {} };
|
|
961
|
+
},
|
|
962
|
+
}),
|
|
963
|
+
);
|
|
964
|
+
|
|
687
965
|
// TODO: main could use more automatic meta/discoverability information in the return payload. To help orient around what has been read already, what hasn't been read, inside and outside the filtered space, how long is the log, etc.
|
|
688
966
|
pi.registerTool(
|
|
689
967
|
defineTool({
|
|
@@ -757,8 +1035,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
757
1035
|
async execute(_toolCallId, params) {
|
|
758
1036
|
const team = resolveTeam(owner, params.team);
|
|
759
1037
|
const teammates = [...team.members.keys()];
|
|
760
|
-
shutdownTeam(team);
|
|
1038
|
+
const errors = await shutdownTeam(team);
|
|
761
1039
|
closeCallbackServerIfUnused();
|
|
1040
|
+
if (errors.length > 0) throw new Error(`Failed to close Herdr teammate pane(s): ${errors.join("; ")}`);
|
|
762
1041
|
return toolResult({ stopped: true, team: team.name, teammates });
|
|
763
1042
|
},
|
|
764
1043
|
}),
|
package/package.json
CHANGED
package/render.ts
CHANGED
|
@@ -32,6 +32,7 @@ export interface TeamStatusView {
|
|
|
32
32
|
export interface TeamMessageDetails {
|
|
33
33
|
team: string;
|
|
34
34
|
from: string;
|
|
35
|
+
to?: string;
|
|
35
36
|
sentAt: string;
|
|
36
37
|
message: string;
|
|
37
38
|
}
|
|
@@ -72,10 +73,10 @@ function wrapTeamLine(line: TeamLine, width: number): string[] {
|
|
|
72
73
|
const wrapped = wrapTextWithAnsi(line, width);
|
|
73
74
|
return wrapped.length > 0 ? wrapped : [""];
|
|
74
75
|
}
|
|
75
|
-
const contentWidth = Math.max(
|
|
76
|
+
const contentWidth = Math.max(1, width - visibleLength(line.prefix));
|
|
76
77
|
const wrapped = wrapTextWithAnsi(line.text, contentWidth);
|
|
77
78
|
const parts = wrapped.length > 0 ? wrapped : [""];
|
|
78
|
-
return parts.map((part) => `${line.prefix}${part}`.trimEnd());
|
|
79
|
+
return parts.map((part) => clipToWidth(`${line.prefix}${part}`.trimEnd(), width));
|
|
79
80
|
}
|
|
80
81
|
|
|
81
82
|
function clipToWidth(line: string, width: number): string {
|
|
@@ -104,10 +105,11 @@ export class TeamLines {
|
|
|
104
105
|
render(width: number): string[] {
|
|
105
106
|
if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;
|
|
106
107
|
const targetWidth = Math.max(1, stableRenderWidth(width));
|
|
107
|
-
|
|
108
|
+
const renderedLines =
|
|
108
109
|
this.mode === "clip"
|
|
109
110
|
? this.lines.map((line) => clipTeamLine(line, targetWidth))
|
|
110
111
|
: this.lines.flatMap((line) => wrapTeamLine(line, targetWidth));
|
|
112
|
+
this.cachedLines = renderedLines.map((line) => clipToWidth(line, targetWidth));
|
|
111
113
|
this.cachedWidth = width;
|
|
112
114
|
return this.cachedLines;
|
|
113
115
|
}
|
|
@@ -540,7 +542,7 @@ export function teamMessageLines(theme: ThemeLike, details: TeamMessageDetails,
|
|
|
540
542
|
const header = [
|
|
541
543
|
theme.fg("accent", `${g.diamond} `),
|
|
542
544
|
theme.fg(actorHueToken(details.from, roster), theme.bold(details.from)),
|
|
543
|
-
theme.fg("muted", ` ${g.arrow} main`),
|
|
545
|
+
theme.fg("muted", ` ${g.arrow} ${details.to ?? "main"}`),
|
|
544
546
|
theme.fg("dim", `${g.dot}${details.team}${g.dot}${details.sentAt}`),
|
|
545
547
|
].join("");
|
|
546
548
|
return [header, ...quotedBody(theme, details.message, { lineLimit: Number.POSITIVE_INFINITY, barToken: "accent" })];
|
|
@@ -551,7 +553,7 @@ function teamMessageHeader(theme: ThemeLike, details: TeamMessageDetails, roster
|
|
|
551
553
|
return [
|
|
552
554
|
theme.fg("accent", `${g.diamond} `),
|
|
553
555
|
theme.fg(actorHueToken(details.from, roster), theme.bold(details.from)),
|
|
554
|
-
theme.fg("muted", ` ${g.arrow} main`),
|
|
556
|
+
theme.fg("muted", ` ${g.arrow} ${details.to ?? "main"}`),
|
|
555
557
|
theme.fg("dim", `${g.dot}${details.team}${g.dot}${details.sentAt}`),
|
|
556
558
|
].join("");
|
|
557
559
|
}
|
|
@@ -579,15 +581,15 @@ class TeamSendView {
|
|
|
579
581
|
|
|
580
582
|
render(width: number): string[] {
|
|
581
583
|
const header = clipToWidth(this.headerStr, width);
|
|
582
|
-
const bodyWidth = Math.max(
|
|
584
|
+
const bodyWidth = Math.max(1, width - this.barWidth);
|
|
583
585
|
const bodyLines = this.md.render(bodyWidth);
|
|
584
|
-
const barred = bodyLines.map((line) => `${this.barStr}${line}
|
|
586
|
+
const barred = bodyLines.map((line) => clipToWidth(`${this.barStr}${line}`, width));
|
|
585
587
|
if (this.expanded) return [header, ...barred];
|
|
586
588
|
const shown = barred.slice(0, SEND_PREVIEW_LINES);
|
|
587
589
|
const hidden = barred.length - SEND_PREVIEW_LINES;
|
|
588
590
|
if (hidden > 0) {
|
|
589
591
|
const g = glyphs();
|
|
590
|
-
shown.push(`${this.barStr}${this.theme.fg("dim", `${g.ellipsis} ${hidden} more line${hidden === 1 ? "" : "s"}${g.dot}ctrl+o to expand`)}
|
|
592
|
+
shown.push(clipToWidth(`${this.barStr}${this.theme.fg("dim", `${g.ellipsis} ${hidden} more line${hidden === 1 ? "" : "s"}${g.dot}ctrl+o to expand`)}`, width));
|
|
591
593
|
}
|
|
592
594
|
return [header, ...shown];
|
|
593
595
|
}
|
|
@@ -611,9 +613,9 @@ class TeamMessageView {
|
|
|
611
613
|
}
|
|
612
614
|
|
|
613
615
|
render(width: number): string[] {
|
|
614
|
-
const bodyWidth = Math.max(
|
|
616
|
+
const bodyWidth = Math.max(1, width - this.barWidth);
|
|
615
617
|
const bodyLines = this.md.render(bodyWidth);
|
|
616
|
-
return [clipToWidth(this.headerLine, width), ...bodyLines.map((line) => `${this.barStr}${line}
|
|
618
|
+
return [clipToWidth(this.headerLine, width), ...bodyLines.map((line) => clipToWidth(`${this.barStr}${line}`, width))];
|
|
617
619
|
}
|
|
618
620
|
}
|
|
619
621
|
|
package/screenshots/1.png
CHANGED
|
Binary file
|