pi-crew 0.1.15 → 0.1.17
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/CHANGELOG.md +15 -0
- package/README.md +16 -1
- package/docs/usage.md +6 -1
- package/package.json +1 -1
- package/schema.json +6 -1
- package/src/config/config.ts +10 -0
- package/src/extension/register.ts +30 -6
- package/src/extension/run-index.ts +22 -6
- package/src/extension/team-tool.ts +23 -2
- package/src/runtime/child-pi.ts +94 -11
- package/src/runtime/crew-agent-records.ts +20 -1
- package/src/runtime/crew-agent-runtime.ts +3 -0
- package/src/runtime/pi-json-output.ts +3 -2
- package/src/runtime/policy-engine.ts +1 -1
- package/src/runtime/task-runner.ts +67 -6
- package/src/state/event-log.ts +10 -0
- package/src/ui/crew-widget.ts +7 -7
- package/src/ui/powerbar-publisher.ts +2 -2
- package/src/ui/run-dashboard.ts +70 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.17
|
|
4
|
+
|
|
5
|
+
- Fixed terminal/completed workers being incorrectly escalated as stale heartbeat blockers after all tasks completed.
|
|
6
|
+
- Cleaned child-process result extraction so result artifacts prefer final assistant output and no longer include worker prompt/context.
|
|
7
|
+
- Made `/team-dashboard` visibly render as a top-right sidebar by default with explicit right-sidebar title text.
|
|
8
|
+
- Added per-subagent model and usage fields to agent records, status output, and dashboard fallbacks so model/token totals stay visible while and after workers run.
|
|
9
|
+
|
|
10
|
+
## 0.1.16
|
|
11
|
+
|
|
12
|
+
- Added right-side `/team-dashboard` placement with model, token, and tool detail rows for subagents.
|
|
13
|
+
- Added UI config for dashboard placement/width and model/token/tool visibility.
|
|
14
|
+
- Foreground child-process runs now continue without blocking the interactive chat and remain tied to session shutdown.
|
|
15
|
+
- Child-process observability now drops noisy `message_update`/encrypted thinking deltas and stores compact events to prevent massive JSONL/output logs from freezing sessions.
|
|
16
|
+
- Cancel now syncs agent records and writes a foreground interrupt request so queued/running agents stop appearing stale.
|
|
17
|
+
|
|
3
18
|
## 0.1.15
|
|
4
19
|
|
|
5
20
|
- Child-process model selection now uses Pi-configured/available models and auto-discovers provider/model entries from Pi settings/models config.
|
package/README.md
CHANGED
|
@@ -169,11 +169,26 @@ Supported config:
|
|
|
169
169
|
"ui": {
|
|
170
170
|
"widgetPlacement": "aboveEditor",
|
|
171
171
|
"widgetMaxLines": 8,
|
|
172
|
-
"powerbar": true
|
|
172
|
+
"powerbar": true,
|
|
173
|
+
"dashboardPlacement": "right",
|
|
174
|
+
"dashboardWidth": 52,
|
|
175
|
+
"showModel": true,
|
|
176
|
+
"showTokens": true,
|
|
177
|
+
"showTools": true
|
|
173
178
|
}
|
|
174
179
|
}
|
|
175
180
|
```
|
|
176
181
|
|
|
182
|
+
Safety notes:
|
|
183
|
+
|
|
184
|
+
- Foreground child-process runs continue in the Pi extension process and return control to chat immediately, so large workflows do not block the interactive session. They are interrupted on session shutdown. Use `async: true` only for intentionally detached runs that may survive the current session.
|
|
185
|
+
|
|
186
|
+
UI notes:
|
|
187
|
+
|
|
188
|
+
- `widgetPlacement`/`widgetMaxLines` keep the persistent active-run widget compact.
|
|
189
|
+
- `dashboardPlacement: "right"` opens `/team-dashboard` as a right-side overlay panel instead of a centered modal.
|
|
190
|
+
- `showModel`, `showTokens`, and `showTools` show worker model attempts, token usage, and tool activity in dashboard agent rows.
|
|
191
|
+
|
|
177
192
|
Show config:
|
|
178
193
|
|
|
179
194
|
```text
|
package/docs/usage.md
CHANGED
|
@@ -32,7 +32,12 @@ Supported fields:
|
|
|
32
32
|
"ui": {
|
|
33
33
|
"widgetPlacement": "aboveEditor",
|
|
34
34
|
"widgetMaxLines": 8,
|
|
35
|
-
"powerbar": true
|
|
35
|
+
"powerbar": true,
|
|
36
|
+
"dashboardPlacement": "right",
|
|
37
|
+
"dashboardWidth": 52,
|
|
38
|
+
"showModel": true,
|
|
39
|
+
"showTokens": true,
|
|
40
|
+
"showTools": true
|
|
36
41
|
}
|
|
37
42
|
}
|
|
38
43
|
```
|
package/package.json
CHANGED
package/schema.json
CHANGED
|
@@ -86,7 +86,12 @@
|
|
|
86
86
|
"properties": {
|
|
87
87
|
"widgetPlacement": { "type": "string", "enum": ["aboveEditor", "belowEditor"] },
|
|
88
88
|
"widgetMaxLines": { "type": "integer", "minimum": 1, "maximum": 50 },
|
|
89
|
-
"powerbar": { "type": "boolean" }
|
|
89
|
+
"powerbar": { "type": "boolean" },
|
|
90
|
+
"dashboardPlacement": { "type": "string", "enum": ["center", "right"], "description": "Place /team-dashboard as a centered overlay or right-side panel." },
|
|
91
|
+
"dashboardWidth": { "type": "integer", "minimum": 32, "maximum": 120 },
|
|
92
|
+
"showModel": { "type": "boolean", "description": "Show worker model attempts in dashboard agent rows." },
|
|
93
|
+
"showTokens": { "type": "boolean", "description": "Show token usage in dashboard agent rows." },
|
|
94
|
+
"showTools": { "type": "boolean", "description": "Show tool activity in dashboard agent rows." }
|
|
90
95
|
}
|
|
91
96
|
}
|
|
92
97
|
}
|
package/src/config/config.ts
CHANGED
|
@@ -51,6 +51,11 @@ export interface CrewUiConfig {
|
|
|
51
51
|
widgetPlacement?: "aboveEditor" | "belowEditor";
|
|
52
52
|
widgetMaxLines?: number;
|
|
53
53
|
powerbar?: boolean;
|
|
54
|
+
dashboardPlacement?: "center" | "right";
|
|
55
|
+
dashboardWidth?: number;
|
|
56
|
+
showModel?: boolean;
|
|
57
|
+
showTokens?: boolean;
|
|
58
|
+
showTools?: boolean;
|
|
54
59
|
}
|
|
55
60
|
|
|
56
61
|
export interface AgentOverrideConfig {
|
|
@@ -309,6 +314,11 @@ function parseUiConfig(value: unknown): CrewUiConfig | undefined {
|
|
|
309
314
|
widgetPlacement: obj.widgetPlacement === "aboveEditor" || obj.widgetPlacement === "belowEditor" ? obj.widgetPlacement : undefined,
|
|
310
315
|
widgetMaxLines: parsePositiveInteger(obj.widgetMaxLines, 50),
|
|
311
316
|
powerbar: typeof obj.powerbar === "boolean" ? obj.powerbar : undefined,
|
|
317
|
+
dashboardPlacement: obj.dashboardPlacement === "center" || obj.dashboardPlacement === "right" ? obj.dashboardPlacement : undefined,
|
|
318
|
+
dashboardWidth: parsePositiveInteger(obj.dashboardWidth, 120),
|
|
319
|
+
showModel: typeof obj.showModel === "boolean" ? obj.showModel : undefined,
|
|
320
|
+
showTokens: typeof obj.showTokens === "boolean" ? obj.showTokens : undefined,
|
|
321
|
+
showTools: typeof obj.showTools === "boolean" ? obj.showTools : undefined,
|
|
312
322
|
};
|
|
313
323
|
return Object.values(ui).some((entry) => entry !== undefined) ? ui : undefined;
|
|
314
324
|
}
|
|
@@ -7,7 +7,7 @@ import { notifyActiveRuns } from "./session-summary.ts";
|
|
|
7
7
|
import { piTeamsHelp } from "./help.ts";
|
|
8
8
|
import { handleTeamManagerCommand } from "./team-manager-command.ts";
|
|
9
9
|
import { handleTeamTool, type TeamToolDetails } from "./team-tool.ts";
|
|
10
|
-
import {
|
|
10
|
+
import { listRecentRuns } from "./run-index.ts";
|
|
11
11
|
import { RunDashboard, type RunDashboardSelection } from "../ui/run-dashboard.ts";
|
|
12
12
|
import { registerPiCrewRpc, type PiCrewRpcHandle } from "./cross-extension-rpc.ts";
|
|
13
13
|
import { stopCrewWidget, updateCrewWidget, type CrewWidgetState } from "../ui/crew-widget.ts";
|
|
@@ -112,6 +112,25 @@ export function registerPiTeams(pi: ExtensionAPI): void {
|
|
|
112
112
|
let cleanedUp = false;
|
|
113
113
|
const widgetState: CrewWidgetState = { frame: 0 };
|
|
114
114
|
const foregroundControllers = new Set<AbortController>();
|
|
115
|
+
const startForegroundRun = (ctx: ExtensionContext, runner: (signal?: AbortSignal) => Promise<void>): void => {
|
|
116
|
+
const controller = new AbortController();
|
|
117
|
+
foregroundControllers.add(controller);
|
|
118
|
+
setImmediate(() => {
|
|
119
|
+
void runner(controller.signal)
|
|
120
|
+
.catch((error) => {
|
|
121
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
122
|
+
ctx.ui.notify(`pi-crew foreground run failed: ${message}`, "error");
|
|
123
|
+
})
|
|
124
|
+
.finally(() => {
|
|
125
|
+
foregroundControllers.delete(controller);
|
|
126
|
+
if (currentCtx) {
|
|
127
|
+
const config = loadConfig(currentCtx.cwd).config.ui;
|
|
128
|
+
updateCrewWidget(currentCtx, widgetState, config);
|
|
129
|
+
updatePiCrewPowerbar(pi.events, currentCtx.cwd, config);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
};
|
|
115
134
|
registerAutonomousPolicy(pi);
|
|
116
135
|
rpcHandle = registerPiCrewRpc((pi as unknown as { events?: Parameters<typeof registerPiCrewRpc>[0] }).events, () => currentCtx);
|
|
117
136
|
const cleanupRuntime = (): void => {
|
|
@@ -163,7 +182,7 @@ export function registerPiTeams(pi: ExtensionAPI): void {
|
|
|
163
182
|
const abort = (): void => controller.abort();
|
|
164
183
|
signal?.addEventListener("abort", abort, { once: true });
|
|
165
184
|
try {
|
|
166
|
-
const output = await handleTeamTool(params as TeamToolParamsValue, { ...ctx, signal: controller.signal });
|
|
185
|
+
const output = await handleTeamTool(params as TeamToolParamsValue, { ...ctx, signal: controller.signal, startForegroundRun: (runner) => startForegroundRun(ctx, runner) });
|
|
167
186
|
const config = loadConfig(ctx.cwd).config.ui;
|
|
168
187
|
updateCrewWidget(ctx, widgetState, config);
|
|
169
188
|
updatePiCrewPowerbar(pi.events, ctx.cwd, config);
|
|
@@ -188,7 +207,7 @@ export function registerPiTeams(pi: ExtensionAPI): void {
|
|
|
188
207
|
pi.registerCommand("team-run", {
|
|
189
208
|
description: "Manually start a pi-crew run (agent may also use the team tool autonomously)",
|
|
190
209
|
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
191
|
-
const result = await handleTeamTool(parseRunArgs(args), ctx);
|
|
210
|
+
const result = await handleTeamTool(parseRunArgs(args), { ...ctx, startForegroundRun: (runner) => startForegroundRun(ctx as ExtensionContext, runner) });
|
|
192
211
|
await notifyCommandResult(ctx, commandText(result));
|
|
193
212
|
},
|
|
194
213
|
});
|
|
@@ -362,10 +381,15 @@ export function registerPiTeams(pi: ExtensionAPI): void {
|
|
|
362
381
|
description: "Open a pi-crew run dashboard overlay",
|
|
363
382
|
handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
364
383
|
for (;;) {
|
|
365
|
-
const runs =
|
|
366
|
-
const
|
|
384
|
+
const runs = listRecentRuns(ctx.cwd, 50);
|
|
385
|
+
const uiConfig = loadConfig(ctx.cwd).config.ui;
|
|
386
|
+
const rightPanel = uiConfig?.dashboardPlacement !== "center";
|
|
387
|
+
const width = rightPanel ? Math.min(90, Math.max(40, uiConfig?.dashboardWidth ?? 56)) : "90%";
|
|
388
|
+
const selection = await ctx.ui.custom<RunDashboardSelection | undefined>((_tui, theme, _keybindings, done) => new RunDashboard(runs, done, theme, { placement: rightPanel ? "right" : "center", showModel: uiConfig?.showModel, showTokens: uiConfig?.showTokens, showTools: uiConfig?.showTools }), {
|
|
367
389
|
overlay: true,
|
|
368
|
-
overlayOptions:
|
|
390
|
+
overlayOptions: rightPanel
|
|
391
|
+
? { width, minWidth: 40, maxHeight: "100%", anchor: "top-right", offsetX: 0, offsetY: 0, margin: { top: 0, right: 0, bottom: 0, left: 0 } }
|
|
392
|
+
: { width, maxHeight: "90%", anchor: "center", margin: 2 },
|
|
369
393
|
});
|
|
370
394
|
if (!selection) return;
|
|
371
395
|
if (selection.action === "reload") continue;
|
|
@@ -11,18 +11,34 @@ function readManifest(filePath: string): TeamRunManifest | undefined {
|
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
function collectRuns(root: string): TeamRunManifest[] {
|
|
14
|
+
function collectRuns(root: string, maxEntries?: number): TeamRunManifest[] {
|
|
15
15
|
const runsRoot = path.join(root, "state", "runs");
|
|
16
16
|
if (!fs.existsSync(runsRoot)) return [];
|
|
17
|
-
|
|
17
|
+
const entries = fs.readdirSync(runsRoot).sort((a, b) => b.localeCompare(a));
|
|
18
|
+
const selected = maxEntries !== undefined ? entries.slice(0, Math.max(0, maxEntries)) : entries;
|
|
19
|
+
return selected
|
|
18
20
|
.map((entry) => readManifest(path.join(runsRoot, entry, "manifest.json")))
|
|
19
21
|
.filter((manifest): manifest is TeamRunManifest => manifest !== undefined);
|
|
20
22
|
}
|
|
21
23
|
|
|
22
|
-
|
|
23
|
-
const projectRuns = collectRuns(path.join(projectPiRoot(cwd), "teams"));
|
|
24
|
-
const userRuns = collectRuns(path.join(userPiRoot(), "extensions", "pi-crew", "runs"));
|
|
24
|
+
function mergeRuns(userRuns: TeamRunManifest[], projectRuns: TeamRunManifest[], max?: number): TeamRunManifest[] {
|
|
25
25
|
const byId = new Map<string, TeamRunManifest>();
|
|
26
26
|
for (const run of [...userRuns, ...projectRuns]) byId.set(run.runId, run);
|
|
27
|
-
|
|
27
|
+
const sorted = [...byId.values()].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
28
|
+
return max !== undefined ? sorted.slice(0, Math.max(0, max)) : sorted;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function listRuns(cwd: string): TeamRunManifest[] {
|
|
32
|
+
return mergeRuns(
|
|
33
|
+
collectRuns(path.join(userPiRoot(), "extensions", "pi-crew", "runs")),
|
|
34
|
+
collectRuns(path.join(projectPiRoot(cwd), "teams")),
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function listRecentRuns(cwd: string, max = 20): TeamRunManifest[] {
|
|
39
|
+
return mergeRuns(
|
|
40
|
+
collectRuns(path.join(userPiRoot(), "extensions", "pi-crew", "runs"), max),
|
|
41
|
+
collectRuns(path.join(projectPiRoot(cwd), "teams"), max),
|
|
42
|
+
max,
|
|
43
|
+
);
|
|
28
44
|
}
|
|
@@ -35,7 +35,7 @@ import { formatValidationReport, validateResources } from "./validate-resources.
|
|
|
35
35
|
import { formatRecommendation, recommendTeam } from "./team-recommendation.ts";
|
|
36
36
|
import { toolResult, type PiTeamsToolResult } from "./tool-result.ts";
|
|
37
37
|
import { touchWorkerHeartbeat } from "../runtime/worker-heartbeat.ts";
|
|
38
|
-
import { agentEventsPath, agentOutputPath, readCrewAgentEvents, readCrewAgentEventsCursor, readCrewAgentStatus, readCrewAgents } from "../runtime/crew-agent-records.ts";
|
|
38
|
+
import { agentEventsPath, agentOutputPath, readCrewAgentEvents, readCrewAgentEventsCursor, readCrewAgentStatus, readCrewAgents, recordFromTask, saveCrewAgents } from "../runtime/crew-agent-records.ts";
|
|
39
39
|
import { resolveCrewRuntime } from "../runtime/runtime-resolver.ts";
|
|
40
40
|
import { probeLiveSessionRuntime } from "../runtime/live-session-runtime.ts";
|
|
41
41
|
import { applyAttentionState, formatActivityAge, resolveCrewControlConfig } from "../runtime/agent-control.ts";
|
|
@@ -57,6 +57,7 @@ type TeamContext = Pick<ExtensionContext, "cwd"> & Partial<Pick<ExtensionContext
|
|
|
57
57
|
sessionManager?: { getBranch?: () => unknown[] };
|
|
58
58
|
events?: { emit?: (event: string, data: unknown) => void };
|
|
59
59
|
signal?: AbortSignal;
|
|
60
|
+
startForegroundRun?: (runner: (signal?: AbortSignal) => Promise<void>) => void;
|
|
60
61
|
};
|
|
61
62
|
|
|
62
63
|
function result(text: string, details: TeamToolDetails, isError = false): PiTeamsToolResult {
|
|
@@ -307,6 +308,24 @@ export async function handleRun(params: TeamToolParamsValue, ctx: TeamContext):
|
|
|
307
308
|
const runtime = await resolveCrewRuntime(effectiveRunConfig(loadedConfig.config, params.config));
|
|
308
309
|
const executeWorkers = runtime.kind === "child-process";
|
|
309
310
|
const executedConfig = effectiveRunConfig(loadedConfig.config, params.config);
|
|
311
|
+
if (executeWorkers && ctx.startForegroundRun) {
|
|
312
|
+
ctx.startForegroundRun(async (signal) => {
|
|
313
|
+
await executeTeamRun({ manifest: updatedManifest, tasks, team, workflow, agents, executeWorkers, limits: executedConfig.limits, runtime, runtimeConfig: executedConfig.runtime, parentContext: buildParentContext(ctx), parentModel: ctx.model, modelRegistry: ctx.modelRegistry, modelOverride: params.model, signal });
|
|
314
|
+
});
|
|
315
|
+
const text = [
|
|
316
|
+
`Started foreground pi-crew run ${updatedManifest.runId}.`,
|
|
317
|
+
`Team: ${team.name}`,
|
|
318
|
+
`Workflow: ${workflow.name}`,
|
|
319
|
+
"Status: running",
|
|
320
|
+
`Tasks: ${tasks.length}`,
|
|
321
|
+
`Runtime: ${runtime.kind}`,
|
|
322
|
+
`State: ${updatedManifest.stateRoot}`,
|
|
323
|
+
`Artifacts: ${updatedManifest.artifactsRoot}`,
|
|
324
|
+
"",
|
|
325
|
+
"The run continues in this Pi session without blocking the chat. It will be interrupted on session shutdown. Use /team-dashboard or /team-status to watch it.",
|
|
326
|
+
].join("\n");
|
|
327
|
+
return result(text, { action: "run", status: "ok", runId: updatedManifest.runId, artifactsRoot: updatedManifest.artifactsRoot });
|
|
328
|
+
}
|
|
310
329
|
const executed = await executeTeamRun({ manifest: updatedManifest, tasks, team, workflow, agents, executeWorkers, limits: executedConfig.limits, runtime, runtimeConfig: executedConfig.runtime, parentContext: buildParentContext(ctx), parentModel: ctx.model, modelRegistry: ctx.modelRegistry, modelOverride: params.model, signal: ctx.signal });
|
|
311
330
|
const text = [
|
|
312
331
|
`Created pi-crew run ${executed.manifest.runId}.`,
|
|
@@ -365,7 +384,7 @@ export function handleStatus(params: TeamToolParamsValue, ctx: TeamContext): PiT
|
|
|
365
384
|
...(tasks.length ? tasks.map((task) => `- ${task.id} [${task.status}] ${task.role} -> ${task.agent}${task.taskPacket ? ` scope=${task.taskPacket.scope}` : ""}${task.verification ? ` green=${task.verification.observedGreenLevel}/${task.verification.requiredGreenLevel}` : ""}${task.modelAttempts?.length ? ` attempts=${task.modelAttempts.length}` : ""}${task.jsonEvents !== undefined ? ` jsonEvents=${task.jsonEvents}` : ""}${task.usage ? ` usage=${JSON.stringify(task.usage)}` : ""}${task.worktree ? ` worktree=${task.worktree.path}` : ""}${task.error ? ` error=${task.error}` : ""}`) : ["- (none)"]),
|
|
366
385
|
`Task counts: ${[...counts.entries()].map(([status, count]) => `${status}=${count}`).join(", ") || "none"}`,
|
|
367
386
|
"Agents:",
|
|
368
|
-
...(crewAgents.length ? crewAgents.map((agent) => `- ${agent.id} [${agent.status}] ${agent.role} -> ${agent.agent} runtime=${agent.runtime}${agent.progress?.activityState === "needs_attention" ? " needs_attention" : ""}${formatActivityAge(agent) ? ` activity=${formatActivityAge(agent)}` : ""}${agent.progress?.currentTool ? ` tool=${agent.progress.currentTool}` : ""}${agent.toolUses ? ` tools=${agent.toolUses}` : ""}${agent.progress?.tokens ? ` tokens=${agent.progress.tokens}` : ""}${agent.progress?.turns ? ` turns=${agent.progress.turns}` : ""}${agent.jsonEvents !== undefined ? ` jsonEvents=${agent.jsonEvents}` : ""}${agent.statusPath ? ` status=${agent.statusPath}` : ""}${agent.error ? ` error=${agent.error}` : ""}`) : ["- (none)"]),
|
|
387
|
+
...(crewAgents.length ? crewAgents.map((agent) => `- ${agent.id} [${agent.status}] ${agent.role} -> ${agent.agent} runtime=${agent.runtime}${agent.model ? ` model=${agent.model}` : ""}${agent.usage ? ` usage=${formatUsage(agent.usage)}` : ""}${agent.progress?.activityState === "needs_attention" ? " needs_attention" : ""}${formatActivityAge(agent) ? ` activity=${formatActivityAge(agent)}` : ""}${agent.progress?.currentTool ? ` tool=${agent.progress.currentTool}` : ""}${agent.toolUses ? ` tools=${agent.toolUses}` : ""}${!agent.usage && agent.progress?.tokens ? ` tokens=${agent.progress.tokens}` : ""}${agent.progress?.turns ? ` turns=${agent.progress.turns}` : ""}${agent.jsonEvents !== undefined ? ` jsonEvents=${agent.jsonEvents}` : ""}${agent.statusPath ? ` status=${agent.statusPath}` : ""}${agent.error ? ` error=${agent.error}` : ""}`) : ["- (none)"]),
|
|
369
388
|
"Policy decisions:",
|
|
370
389
|
...(manifest.policyDecisions?.length ? manifest.policyDecisions.map((item) => `- ${item.action} (${item.reason})${item.taskId ? ` ${item.taskId}` : ""}: ${item.message}`) : ["- (none)"]),
|
|
371
390
|
`Total usage: ${formatUsage(totalUsage)}`,
|
|
@@ -409,6 +428,8 @@ export function handleCancel(params: TeamToolParamsValue, ctx: TeamContext): PiT
|
|
|
409
428
|
}
|
|
410
429
|
const tasks = loaded.tasks.map((task) => task.status === "queued" || task.status === "running" ? { ...task, status: "cancelled" as const, finishedAt: new Date().toISOString(), error: "Run cancelled by user request." } : task);
|
|
411
430
|
saveRunTasks(loaded.manifest, tasks);
|
|
431
|
+
try { saveCrewAgents(loaded.manifest, tasks.map((task) => recordFromTask(loaded.manifest, task, "child-process"))); } catch {}
|
|
432
|
+
try { writeForegroundInterruptRequest(loaded.manifest, "Run cancelled by user request."); } catch {}
|
|
412
433
|
const updated = updateRunStatus(loaded.manifest, "cancelled", "Run cancelled by user request. Already-finished worker processes are not retroactively changed.");
|
|
413
434
|
return result(`Cancelled run ${updated.runId}.`, { action: "cancel", status: "ok", runId: updated.runId, artifactsRoot: updated.artifactsRoot });
|
|
414
435
|
});
|
package/src/runtime/child-pi.ts
CHANGED
|
@@ -8,8 +8,18 @@ import { getPiSpawnCommand } from "./pi-spawn.ts";
|
|
|
8
8
|
const POST_EXIT_STDIO_GUARD_MS = 3000;
|
|
9
9
|
const FINAL_DRAIN_MS = 5000;
|
|
10
10
|
const HARD_KILL_MS = 3000;
|
|
11
|
+
const MAX_CAPTURE_BYTES = 256 * 1024;
|
|
12
|
+
const MAX_COMPACT_CONTENT_CHARS = 4096;
|
|
11
13
|
const activeChildProcesses = new Map<number, ChildProcess>();
|
|
12
14
|
|
|
15
|
+
function appendBoundedTail(current: string, chunk: string, maxBytes = MAX_CAPTURE_BYTES): string {
|
|
16
|
+
const combined = current + chunk;
|
|
17
|
+
if (Buffer.byteLength(combined, "utf-8") <= maxBytes) return combined;
|
|
18
|
+
let tail = combined.slice(Math.max(0, combined.length - maxBytes));
|
|
19
|
+
while (Buffer.byteLength(tail, "utf-8") > maxBytes) tail = tail.slice(1024);
|
|
20
|
+
return `[pi-crew captured output truncated to last ${Math.round(maxBytes / 1024)} KiB]\n${tail}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
13
23
|
function killProcessTree(pid: number | undefined): void {
|
|
14
24
|
if (!pid || !Number.isInteger(pid) || pid <= 0) return;
|
|
15
25
|
try {
|
|
@@ -59,6 +69,80 @@ function appendTranscript(input: ChildPiRunInput, line: string): void {
|
|
|
59
69
|
fs.appendFileSync(input.transcriptPath, `${line}\n`, "utf-8");
|
|
60
70
|
}
|
|
61
71
|
|
|
72
|
+
function compactString(value: string, maxChars = MAX_COMPACT_CONTENT_CHARS): string {
|
|
73
|
+
if (value.length <= maxChars) return value;
|
|
74
|
+
return `${value.slice(0, maxChars)}\n[pi-crew compacted ${value.length - maxChars} chars]`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function compactValue(value: unknown): unknown {
|
|
78
|
+
if (typeof value === "string") return compactString(value);
|
|
79
|
+
if (Array.isArray(value)) return value.slice(0, 20).map(compactValue);
|
|
80
|
+
const record = asRecord(value);
|
|
81
|
+
if (!record) return value;
|
|
82
|
+
const compacted: Record<string, unknown> = {};
|
|
83
|
+
for (const [key, entry] of Object.entries(record).slice(0, 20)) compacted[key] = compactValue(entry);
|
|
84
|
+
return compacted;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function compactContentPart(part: unknown): unknown | undefined {
|
|
88
|
+
const record = asRecord(part);
|
|
89
|
+
if (!record) return undefined;
|
|
90
|
+
if (record.type === "text") return { type: "text", text: typeof record.text === "string" ? compactString(record.text) : "" };
|
|
91
|
+
if (record.type === "toolCall") return { type: "toolCall", name: record.name, input: compactValue(record.input) };
|
|
92
|
+
if (record.type === "toolResult") return { type: "toolResult", name: record.name, content: compactValue(record.content) };
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function compactChildPiEvent(event: unknown): unknown | undefined {
|
|
97
|
+
const record = asRecord(event);
|
|
98
|
+
if (!record) return undefined;
|
|
99
|
+
if (record.type === "message_update") return undefined;
|
|
100
|
+
if (record.type === "tool_execution_start" || record.type === "tool_execution_end") {
|
|
101
|
+
return { type: record.type, toolName: record.toolName, args: record.args };
|
|
102
|
+
}
|
|
103
|
+
if (record.type === "tool_result_end" || record.type === "message_end" || record.type === "message") {
|
|
104
|
+
const message = asRecord(record.message);
|
|
105
|
+
const content = Array.isArray(message?.content) ? message.content.map(compactContentPart).filter((part) => part !== undefined) : undefined;
|
|
106
|
+
return {
|
|
107
|
+
type: record.type,
|
|
108
|
+
...(typeof record.text === "string" ? { text: record.text } : {}),
|
|
109
|
+
...(message ? { message: { role: message.role, ...(content ? { content } : {}), usage: message.usage, model: message.model, errorMessage: message.errorMessage, stopReason: message.stopReason } } : {}),
|
|
110
|
+
usage: record.usage,
|
|
111
|
+
model: record.model,
|
|
112
|
+
provider: record.provider,
|
|
113
|
+
stopReason: record.stopReason,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
return record.type ? { type: record.type } : undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function displayTextFromCompactEvent(event: unknown): string | undefined {
|
|
120
|
+
const record = asRecord(event);
|
|
121
|
+
if (!record) return undefined;
|
|
122
|
+
if (record.type === "tool_execution_start") {
|
|
123
|
+
return typeof record.toolName === "string" ? `tool: ${record.toolName}` : "tool started";
|
|
124
|
+
}
|
|
125
|
+
if (record.type !== "message" && record.type !== "message_end") return undefined;
|
|
126
|
+
const message = asRecord(record.message);
|
|
127
|
+
if (message?.role !== undefined && message.role !== "assistant") return undefined;
|
|
128
|
+
const content = Array.isArray(message?.content) ? message.content : [];
|
|
129
|
+
const text = content.flatMap((part) => {
|
|
130
|
+
const item = asRecord(part);
|
|
131
|
+
return item?.type === "text" && typeof item.text === "string" ? [item.text] : [];
|
|
132
|
+
}).join("\n").trim();
|
|
133
|
+
return text || (typeof record.text === "string" ? record.text : undefined);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function compactChildPiLine(line: string): { persistedLine: string; event?: unknown; displayLine?: string; json: boolean } {
|
|
137
|
+
try {
|
|
138
|
+
const parsed = JSON.parse(line);
|
|
139
|
+
const compact = compactChildPiEvent(parsed);
|
|
140
|
+
return { json: true, event: compact, persistedLine: compact ? JSON.stringify(compact) : "", displayLine: displayTextFromCompactEvent(compact) };
|
|
141
|
+
} catch {
|
|
142
|
+
return { json: false, persistedLine: line, displayLine: line };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
62
146
|
export class ChildPiLineObserver {
|
|
63
147
|
private buffer = "";
|
|
64
148
|
private readonly input: ChildPiRunInput;
|
|
@@ -83,13 +167,10 @@ export class ChildPiLineObserver {
|
|
|
83
167
|
|
|
84
168
|
private emitLine(line: string): void {
|
|
85
169
|
if (!line.trim()) return;
|
|
86
|
-
|
|
87
|
-
this.input.
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
} catch {
|
|
91
|
-
// Raw stdout is allowed.
|
|
92
|
-
}
|
|
170
|
+
const compact = compactChildPiLine(line);
|
|
171
|
+
if (compact.event !== undefined) this.input.onJsonEvent?.(compact.event);
|
|
172
|
+
if (compact.persistedLine) appendTranscript(this.input, compact.persistedLine);
|
|
173
|
+
if (compact.displayLine?.trim()) this.input.onStdoutLine?.(compact.displayLine);
|
|
93
174
|
}
|
|
94
175
|
}
|
|
95
176
|
|
|
@@ -156,6 +237,10 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
|
|
|
156
237
|
let forcedFinalDrain = false;
|
|
157
238
|
const lineObserver = new ChildPiLineObserver({
|
|
158
239
|
...input,
|
|
240
|
+
onStdoutLine: (line) => {
|
|
241
|
+
stdout = appendBoundedTail(stdout, `${line}\n`);
|
|
242
|
+
input.onStdoutLine?.(line);
|
|
243
|
+
},
|
|
159
244
|
onJsonEvent: (event) => {
|
|
160
245
|
input.onJsonEvent?.(event);
|
|
161
246
|
if (!isFinalAssistantEvent(event) || childExited || settled || finalDrainTimer) return;
|
|
@@ -202,12 +287,10 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
|
|
|
202
287
|
|
|
203
288
|
input.signal?.addEventListener("abort", abort, { once: true });
|
|
204
289
|
child.stdout?.on("data", (chunk: Buffer) => {
|
|
205
|
-
|
|
206
|
-
stdout += text;
|
|
207
|
-
lineObserver.observe(text);
|
|
290
|
+
lineObserver.observe(chunk.toString("utf-8"));
|
|
208
291
|
});
|
|
209
292
|
child.stderr?.on("data", (chunk: Buffer) => {
|
|
210
|
-
stderr
|
|
293
|
+
stderr = appendBoundedTail(stderr, chunk.toString("utf-8"));
|
|
211
294
|
});
|
|
212
295
|
child.on("error", (error) => {
|
|
213
296
|
settle({ exitCode: null, stdout, stderr, error: error.message });
|
|
@@ -52,8 +52,13 @@ export function readCrewAgentStatus(manifest: TeamRunManifest, taskOrAgentId: st
|
|
|
52
52
|
return readJsonFile<CrewAgentRecord>(agentStatusPath(manifest, taskId));
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
const agentEventSeqCache = new Map<string, { size: number; mtimeMs: number; seq: number }>();
|
|
56
|
+
|
|
55
57
|
function nextAgentEventSeq(filePath: string): number {
|
|
56
58
|
if (!fs.existsSync(filePath)) return 1;
|
|
59
|
+
const stat = fs.statSync(filePath);
|
|
60
|
+
const cached = agentEventSeqCache.get(filePath);
|
|
61
|
+
if (cached && cached.size === stat.size && cached.mtimeMs === stat.mtimeMs) return cached.seq + 1;
|
|
57
62
|
let max = 0;
|
|
58
63
|
for (const line of fs.readFileSync(filePath, "utf-8").split(/\r?\n/)) {
|
|
59
64
|
if (!line.trim()) continue;
|
|
@@ -65,13 +70,19 @@ function nextAgentEventSeq(filePath: string): number {
|
|
|
65
70
|
max += 1;
|
|
66
71
|
}
|
|
67
72
|
}
|
|
73
|
+
agentEventSeqCache.set(filePath, { size: stat.size, mtimeMs: stat.mtimeMs, seq: max });
|
|
68
74
|
return max + 1;
|
|
69
75
|
}
|
|
70
76
|
|
|
71
77
|
export function appendCrewAgentEvent(manifest: TeamRunManifest, taskId: string, event: unknown): void {
|
|
72
78
|
fs.mkdirSync(agentStateDir(manifest, taskId), { recursive: true });
|
|
73
79
|
const filePath = agentEventsPath(manifest, taskId);
|
|
74
|
-
|
|
80
|
+
const seq = nextAgentEventSeq(filePath);
|
|
81
|
+
fs.appendFileSync(filePath, `${JSON.stringify({ seq, time: new Date().toISOString(), event })}\n`, "utf-8");
|
|
82
|
+
try {
|
|
83
|
+
const stat = fs.statSync(filePath);
|
|
84
|
+
agentEventSeqCache.set(filePath, { size: stat.size, mtimeMs: stat.mtimeMs, seq });
|
|
85
|
+
} catch {}
|
|
75
86
|
}
|
|
76
87
|
|
|
77
88
|
export interface CrewAgentEventCursorOptions {
|
|
@@ -113,6 +124,12 @@ export function emptyCrewAgentProgress(): CrewAgentProgress {
|
|
|
113
124
|
return { recentTools: [], recentOutput: [], toolCount: 0 };
|
|
114
125
|
}
|
|
115
126
|
|
|
127
|
+
function modelFromTask(task: TeamTaskState): string | undefined {
|
|
128
|
+
const attempts = task.modelAttempts;
|
|
129
|
+
if (!attempts?.length) return undefined;
|
|
130
|
+
return attempts.find((attempt) => attempt.success)?.model ?? attempts.at(-1)?.model;
|
|
131
|
+
}
|
|
132
|
+
|
|
116
133
|
export function recordFromTask(manifest: TeamRunManifest, task: TeamTaskState, runtime: CrewRuntimeKind): CrewAgentRecord {
|
|
117
134
|
return {
|
|
118
135
|
id: `${manifest.runId}:${task.id}`,
|
|
@@ -131,6 +148,8 @@ export function recordFromTask(manifest: TeamRunManifest, task: TeamTaskState, r
|
|
|
131
148
|
outputPath: agentOutputPath(manifest, task.id),
|
|
132
149
|
toolUses: task.agentProgress?.toolCount,
|
|
133
150
|
jsonEvents: task.jsonEvents,
|
|
151
|
+
model: modelFromTask(task),
|
|
152
|
+
usage: task.usage,
|
|
134
153
|
progress: task.agentProgress,
|
|
135
154
|
error: task.error,
|
|
136
155
|
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { TeamTaskStatus } from "../state/contracts.ts";
|
|
2
|
+
import type { UsageState } from "../state/types.ts";
|
|
2
3
|
|
|
3
4
|
export type CrewRuntimeKind = "scaffold" | "child-process" | "live-session";
|
|
4
5
|
export type CrewAgentStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | "stopped";
|
|
@@ -41,6 +42,8 @@ export interface CrewAgentRecord {
|
|
|
41
42
|
outputPath?: string;
|
|
42
43
|
toolUses?: number;
|
|
43
44
|
jsonEvents?: number;
|
|
45
|
+
model?: string;
|
|
46
|
+
usage?: UsageState;
|
|
44
47
|
progress?: CrewAgentProgress;
|
|
45
48
|
error?: string;
|
|
46
49
|
}
|
|
@@ -72,13 +72,14 @@ function textFromContent(content: unknown): string[] {
|
|
|
72
72
|
function extractText(value: unknown): string[] {
|
|
73
73
|
const obj = asRecord(value);
|
|
74
74
|
if (!obj) return [];
|
|
75
|
+
const message = asRecord(obj.message);
|
|
76
|
+
if (message?.role !== undefined && message.role !== "assistant") return [];
|
|
75
77
|
const text: string[] = [];
|
|
76
78
|
if (typeof obj.text === "string") text.push(obj.text);
|
|
77
79
|
if (typeof obj.output === "string") text.push(obj.output);
|
|
78
80
|
if (typeof obj.finalOutput === "string") text.push(obj.finalOutput);
|
|
79
81
|
if (typeof obj.final_output === "string") text.push(obj.final_output);
|
|
80
|
-
text.push(...textFromContent(obj.content));
|
|
81
|
-
const message = asRecord(obj.message);
|
|
82
|
+
if (!message) text.push(...textFromContent(obj.content));
|
|
82
83
|
if (message) text.push(...textFromContent(message.content));
|
|
83
84
|
return text.filter((entry) => entry.trim().length > 0);
|
|
84
85
|
}
|
|
@@ -56,7 +56,7 @@ export function evaluateCrewPolicy(input: PolicyEngineInput): PolicyDecision[] {
|
|
|
56
56
|
const maxRetries = input.limits?.maxRetriesPerTask ?? 0;
|
|
57
57
|
decisions.push(decision(retryCount < maxRetries ? "retry" : "escalate", "task_failed", task.error ? `Task failed: ${task.error}` : "Task failed.", task.id));
|
|
58
58
|
}
|
|
59
|
-
if (task.heartbeat && isWorkerHeartbeatStale(task.heartbeat, input.limits?.heartbeatStaleMs ?? 60_000, input.now)) {
|
|
59
|
+
if ((task.status === "running" || task.status === "queued") && task.heartbeat && task.heartbeat.alive !== false && isWorkerHeartbeatStale(task.heartbeat, input.limits?.heartbeatStaleMs ?? 60_000, input.now)) {
|
|
60
60
|
decisions.push(decision("escalate", "worker_stale", "Worker heartbeat is stale.", task.id));
|
|
61
61
|
}
|
|
62
62
|
if (task.taskPacket?.verification) {
|
|
@@ -185,6 +185,35 @@ function applyUsageToProgress(progress: CrewAgentProgress | undefined, usage: Us
|
|
|
185
185
|
};
|
|
186
186
|
}
|
|
187
187
|
|
|
188
|
+
function shouldFlushProgressEvent(event: unknown): boolean {
|
|
189
|
+
const type = asRecord(event)?.type;
|
|
190
|
+
return type === "tool_execution_start" || type === "tool_execution_end" || type === "message_end" || type === "tool_result_end";
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function cleanResultText(text: string | undefined): string | undefined {
|
|
194
|
+
const trimmed = text?.trim();
|
|
195
|
+
if (!trimmed) return undefined;
|
|
196
|
+
const doneIndex = trimmed.lastIndexOf("\nDONE\n");
|
|
197
|
+
if (doneIndex >= 0) return trimmed.slice(doneIndex + 1).trim();
|
|
198
|
+
if (trimmed === "DONE" || trimmed.startsWith("DONE\n")) return trimmed;
|
|
199
|
+
const fencedPromptIndex = trimmed.lastIndexOf("</file>");
|
|
200
|
+
if (fencedPromptIndex >= 0 && fencedPromptIndex < trimmed.length - 7) return trimmed.slice(fencedPromptIndex + 7).trim() || trimmed;
|
|
201
|
+
return trimmed;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function progressEventSummary(task: TeamTaskState, event: unknown): Record<string, unknown> {
|
|
205
|
+
const type = asRecord(event)?.type;
|
|
206
|
+
return {
|
|
207
|
+
eventType: typeof type === "string" ? type : "event",
|
|
208
|
+
currentTool: task.agentProgress?.currentTool,
|
|
209
|
+
toolCount: task.agentProgress?.toolCount,
|
|
210
|
+
tokens: task.agentProgress?.tokens,
|
|
211
|
+
turns: task.agentProgress?.turns,
|
|
212
|
+
activityState: task.agentProgress?.activityState,
|
|
213
|
+
lastActivityAt: task.agentProgress?.lastActivityAt,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
188
217
|
function applyAgentProgressEvent(progress: CrewAgentProgress, event: unknown, startedAt: string | undefined): CrewAgentProgress {
|
|
189
218
|
const obj = asRecord(event);
|
|
190
219
|
const now = new Date().toISOString();
|
|
@@ -275,9 +304,26 @@ export async function runTeamTask(input: TaskRunnerInput): Promise<{ manifest: T
|
|
|
275
304
|
let finalStderr = "";
|
|
276
305
|
modelAttempts = [];
|
|
277
306
|
const transcriptPath = `${manifest.artifactsRoot}/transcripts/${task.id}.jsonl`;
|
|
307
|
+
let lastAgentRecordPersistedAt = 0;
|
|
308
|
+
let lastRunProgressPersistedAt = 0;
|
|
309
|
+
const persistChildProgress = (event: unknown, force = false): void => {
|
|
310
|
+
const now = Date.now();
|
|
311
|
+
if (force || shouldFlushProgressEvent(event) || now - lastAgentRecordPersistedAt >= 500) {
|
|
312
|
+
upsertCrewAgent(manifest, recordFromTask(manifest, task, "child-process"));
|
|
313
|
+
lastAgentRecordPersistedAt = now;
|
|
314
|
+
}
|
|
315
|
+
if (force || shouldFlushProgressEvent(event) || now - lastRunProgressPersistedAt >= 1000) {
|
|
316
|
+
appendEvent(manifest.eventsPath, { type: "task.progress", runId: manifest.runId, taskId: task.id, data: progressEventSummary(task, event) });
|
|
317
|
+
lastRunProgressPersistedAt = now;
|
|
318
|
+
}
|
|
319
|
+
};
|
|
278
320
|
for (let i = 0; i < attemptModels.length; i++) {
|
|
279
321
|
const model = attemptModels[i];
|
|
280
322
|
const attemptStartedAt = new Date();
|
|
323
|
+
const pendingAttempt: ModelAttemptSummary = { model: model ?? "default", success: false };
|
|
324
|
+
task = { ...task, modelAttempts: [...modelAttempts, pendingAttempt] };
|
|
325
|
+
tasks = updateTask(tasks, task);
|
|
326
|
+
upsertCrewAgent(manifest, recordFromTask(manifest, task, "child-process"));
|
|
281
327
|
const childResult = await runChildPi({
|
|
282
328
|
cwd: task.cwd,
|
|
283
329
|
task: prompt,
|
|
@@ -291,18 +337,20 @@ export async function runTeamTask(input: TaskRunnerInput): Promise<{ manifest: T
|
|
|
291
337
|
appendCrewAgentEvent(manifest, task.id, event);
|
|
292
338
|
task = { ...task, agentProgress: applyAgentProgressEvent(task.agentProgress ?? emptyCrewAgentProgress(), event, task.startedAt) };
|
|
293
339
|
tasks = updateTask(tasks, task);
|
|
294
|
-
|
|
295
|
-
appendEvent(manifest.eventsPath, { type: "task.progress", runId: manifest.runId, taskId: task.id, data: { event } });
|
|
340
|
+
persistChildProgress(event);
|
|
296
341
|
},
|
|
297
342
|
});
|
|
298
343
|
startupEvidence = createStartupEvidence({ command: "pi", startedAt: attemptStartedAt, finishedAt: new Date(), promptSentAt: attemptStartedAt, promptAccepted: childResult.exitCode === 0 && !childResult.error, stderr: childResult.stderr, error: childResult.error, exitCode: childResult.exitCode });
|
|
299
344
|
exitCode = childResult.exitCode;
|
|
300
345
|
finalStdout = childResult.stdout;
|
|
301
346
|
finalStderr = childResult.stderr;
|
|
302
|
-
parsedOutput = parsePiJsonOutput(childResult.stdout);
|
|
347
|
+
parsedOutput = parsePiJsonOutput(fs.existsSync(transcriptPath) ? fs.readFileSync(transcriptPath, "utf-8") : childResult.stdout);
|
|
303
348
|
error = childResult.error || (childResult.exitCode && childResult.exitCode !== 0 ? childResult.stderr || `Child Pi exited with ${childResult.exitCode}` : undefined);
|
|
349
|
+
persistChildProgress({ type: "attempt_finished" }, true);
|
|
304
350
|
const attempt: ModelAttemptSummary = { model: model ?? "default", success: !error, exitCode, error };
|
|
305
351
|
modelAttempts.push(attempt);
|
|
352
|
+
task = { ...task, modelAttempts: [...modelAttempts] };
|
|
353
|
+
tasks = updateTask(tasks, task);
|
|
306
354
|
logs.push(`MODEL ATTEMPT ${i + 1}: ${attempt.model}`, `success=${attempt.success}`, `exitCode=${attempt.exitCode ?? "null"}`, attempt.error ? `error=${attempt.error}` : "", "");
|
|
307
355
|
if (!error) break;
|
|
308
356
|
const nextModel = attemptModels[i + 1];
|
|
@@ -312,7 +360,7 @@ export async function runTeamTask(input: TaskRunnerInput): Promise<{ manifest: T
|
|
|
312
360
|
resultArtifact = writeArtifact(manifest.artifactsRoot, {
|
|
313
361
|
kind: "result",
|
|
314
362
|
relativePath: `results/${task.id}.txt`,
|
|
315
|
-
content: parsedOutput?.finalText
|
|
363
|
+
content: cleanResultText(parsedOutput?.finalText) ?? cleanResultText(finalStdout) ?? cleanResultText(finalStderr) ?? "(no output)",
|
|
316
364
|
producer: task.id,
|
|
317
365
|
});
|
|
318
366
|
logArtifact = writeArtifact(manifest.artifactsRoot, {
|
|
@@ -339,6 +387,19 @@ export async function runTeamTask(input: TaskRunnerInput): Promise<{ manifest: T
|
|
|
339
387
|
}
|
|
340
388
|
} else if (runtimeKind === "live-session") {
|
|
341
389
|
const transcriptPath = `${manifest.artifactsRoot}/transcripts/${task.id}.jsonl`;
|
|
390
|
+
let lastAgentRecordPersistedAt = 0;
|
|
391
|
+
let lastRunProgressPersistedAt = 0;
|
|
392
|
+
const persistLiveProgress = (event: unknown, force = false): void => {
|
|
393
|
+
const now = Date.now();
|
|
394
|
+
if (force || shouldFlushProgressEvent(event) || now - lastAgentRecordPersistedAt >= 500) {
|
|
395
|
+
upsertCrewAgent(manifest, recordFromTask(manifest, task, "live-session"));
|
|
396
|
+
lastAgentRecordPersistedAt = now;
|
|
397
|
+
}
|
|
398
|
+
if (force || shouldFlushProgressEvent(event) || now - lastRunProgressPersistedAt >= 1000) {
|
|
399
|
+
appendEvent(manifest.eventsPath, { type: "task.progress", runId: manifest.runId, taskId: task.id, data: progressEventSummary(task, event) });
|
|
400
|
+
lastRunProgressPersistedAt = now;
|
|
401
|
+
}
|
|
402
|
+
};
|
|
342
403
|
const attemptStartedAt = new Date();
|
|
343
404
|
const liveResult = await runLiveSessionTask({
|
|
344
405
|
manifest,
|
|
@@ -357,8 +418,7 @@ export async function runTeamTask(input: TaskRunnerInput): Promise<{ manifest: T
|
|
|
357
418
|
appendCrewAgentEvent(manifest, task.id, event);
|
|
358
419
|
task = { ...task, agentProgress: applyAgentProgressEvent(task.agentProgress ?? emptyCrewAgentProgress(), event, task.startedAt) };
|
|
359
420
|
tasks = updateTask(tasks, task);
|
|
360
|
-
|
|
361
|
-
appendEvent(manifest.eventsPath, { type: "task.progress", runId: manifest.runId, taskId: task.id, data: { event } });
|
|
421
|
+
persistLiveProgress(event);
|
|
362
422
|
},
|
|
363
423
|
});
|
|
364
424
|
startupEvidence = createStartupEvidence({ command: "live-session", startedAt: attemptStartedAt, finishedAt: new Date(), promptSentAt: attemptStartedAt, promptAccepted: liveResult.exitCode === 0 && !liveResult.error, stderr: liveResult.stderr, error: liveResult.error, exitCode: liveResult.exitCode });
|
|
@@ -366,6 +426,7 @@ export async function runTeamTask(input: TaskRunnerInput): Promise<{ manifest: T
|
|
|
366
426
|
error = liveResult.error || (liveResult.exitCode && liveResult.exitCode !== 0 ? liveResult.stderr || `Live session exited with ${liveResult.exitCode}` : undefined);
|
|
367
427
|
parsedOutput = { finalText: liveResult.stdout, textEvents: liveResult.stdout ? [liveResult.stdout] : [], jsonEvents: liveResult.jsonEvents, usage: liveResult.usage };
|
|
368
428
|
if (liveResult.usage) task = { ...task, usage: liveResult.usage, agentProgress: applyUsageToProgress(task.agentProgress, liveResult.usage) };
|
|
429
|
+
persistLiveProgress({ type: "attempt_finished" }, true);
|
|
369
430
|
resultArtifact = writeArtifact(manifest.artifactsRoot, {
|
|
370
431
|
kind: "result",
|
|
371
432
|
relativePath: `results/${task.id}.txt`,
|
package/src/state/event-log.ts
CHANGED
|
@@ -42,8 +42,13 @@ export type AppendTeamEvent = Omit<TeamEvent, "time" | "metadata"> & { metadata?
|
|
|
42
42
|
|
|
43
43
|
const TERMINAL_EVENT_TYPES = new Set(["run.blocked", "run.completed", "run.failed", "run.cancelled", "task.completed", "task.failed", "task.cancelled", "task.skipped"]);
|
|
44
44
|
|
|
45
|
+
const sequenceCache = new Map<string, { size: number; mtimeMs: number; seq: number }>();
|
|
46
|
+
|
|
45
47
|
function nextSequence(eventsPath: string): number {
|
|
46
48
|
if (!fs.existsSync(eventsPath)) return 1;
|
|
49
|
+
const stat = fs.statSync(eventsPath);
|
|
50
|
+
const cached = sequenceCache.get(eventsPath);
|
|
51
|
+
if (cached && cached.size === stat.size && cached.mtimeMs === stat.mtimeMs) return cached.seq + 1;
|
|
47
52
|
let max = 0;
|
|
48
53
|
for (const line of fs.readFileSync(eventsPath, "utf-8").split("\n")) {
|
|
49
54
|
if (!line.trim()) continue;
|
|
@@ -54,6 +59,7 @@ function nextSequence(eventsPath: string): number {
|
|
|
54
59
|
max += 1;
|
|
55
60
|
}
|
|
56
61
|
}
|
|
62
|
+
sequenceCache.set(eventsPath, { size: stat.size, mtimeMs: stat.mtimeMs, seq: max });
|
|
57
63
|
return max + 1;
|
|
58
64
|
}
|
|
59
65
|
|
|
@@ -82,6 +88,10 @@ export function appendEvent(eventsPath: string, event: AppendTeamEvent): TeamEve
|
|
|
82
88
|
fullEvent.metadata = metadata;
|
|
83
89
|
}
|
|
84
90
|
fs.appendFileSync(eventsPath, `${JSON.stringify(fullEvent)}\n`, "utf-8");
|
|
91
|
+
try {
|
|
92
|
+
const stat = fs.statSync(eventsPath);
|
|
93
|
+
sequenceCache.set(eventsPath, { size: stat.size, mtimeMs: stat.mtimeMs, seq: fullEvent.metadata?.seq ?? 0 });
|
|
94
|
+
} catch {}
|
|
85
95
|
return fullEvent;
|
|
86
96
|
}
|
|
87
97
|
|
package/src/ui/crew-widget.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ExtensionContext } from "@mariozechner/pi-coding-agent";
|
|
2
2
|
import type { CrewUiConfig } from "../config/config.ts";
|
|
3
|
-
import {
|
|
3
|
+
import { listRecentRuns } from "../extension/run-index.ts";
|
|
4
4
|
import { readCrewAgents } from "../runtime/crew-agent-records.ts";
|
|
5
5
|
import type { CrewAgentRecord } from "../runtime/crew-agent-runtime.ts";
|
|
6
6
|
import { isDisplayActiveRun } from "../runtime/process-status.ts";
|
|
@@ -106,8 +106,7 @@ function agentsFor(run: TeamRunManifest): CrewAgentRecord[] {
|
|
|
106
106
|
}
|
|
107
107
|
|
|
108
108
|
function activeWidgetRuns(cwd: string): WidgetRun[] {
|
|
109
|
-
|
|
110
|
-
return runs.map((run) => ({ run, agents: agentsFor(run) })).filter((item) => isDisplayActiveRun(item.run, item.agents));
|
|
109
|
+
return listRecentRuns(cwd, 20).map((run) => ({ run, agents: agentsFor(run) })).filter((item) => isDisplayActiveRun(item.run, item.agents));
|
|
111
110
|
}
|
|
112
111
|
|
|
113
112
|
function statusSummary(runs: WidgetRun[]): string {
|
|
@@ -136,8 +135,8 @@ function shortRunLabel(run: TeamRunManifest): string {
|
|
|
136
135
|
return `${run.team}/${run.workflow ?? "none"}`;
|
|
137
136
|
}
|
|
138
137
|
|
|
139
|
-
export function buildCrewWidgetLines(cwd: string, frame = 0, maxLines = 8): string[] {
|
|
140
|
-
const runs = activeWidgetRuns(cwd);
|
|
138
|
+
export function buildCrewWidgetLines(cwd: string, frame = 0, maxLines = 8, providedRuns?: WidgetRun[]): string[] {
|
|
139
|
+
const runs = providedRuns ?? activeWidgetRuns(cwd);
|
|
141
140
|
if (!runs.length) return [];
|
|
142
141
|
const runningGlyph = SPINNER[frame % SPINNER.length] ?? "⠋";
|
|
143
142
|
const lines: string[] = [widgetHeader(runs, runningGlyph)];
|
|
@@ -193,9 +192,10 @@ export function updateCrewWidget(ctx: Pick<ExtensionContext, "cwd" | "hasUI" | "
|
|
|
193
192
|
if (!ctx.hasUI) return;
|
|
194
193
|
state.frame += 1;
|
|
195
194
|
const maxLines = config?.widgetMaxLines ?? 10;
|
|
196
|
-
const
|
|
195
|
+
const runs = activeWidgetRuns(ctx.cwd);
|
|
196
|
+
const lines = buildCrewWidgetLines(ctx.cwd, state.frame, maxLines, runs);
|
|
197
197
|
const placement = config?.widgetPlacement ?? "aboveEditor";
|
|
198
|
-
ctx.ui.setStatus(STATUS_KEY, lines.length ? statusSummary(
|
|
198
|
+
ctx.ui.setStatus(STATUS_KEY, lines.length ? statusSummary(runs) : undefined);
|
|
199
199
|
ctx.ui.setWidget(LEGACY_WIDGET_KEY, undefined, { placement });
|
|
200
200
|
if (!lines.length) {
|
|
201
201
|
ctx.ui.setWidget(WIDGET_KEY, undefined, { placement });
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { CrewUiConfig } from "../config/config.ts";
|
|
2
|
-
import {
|
|
2
|
+
import { listRecentRuns } from "../extension/run-index.ts";
|
|
3
3
|
import { readCrewAgents } from "../runtime/crew-agent-records.ts";
|
|
4
4
|
import { isDisplayActiveRun } from "../runtime/process-status.ts";
|
|
5
5
|
|
|
@@ -17,7 +17,7 @@ export function registerPiCrewPowerbarSegments(events: EventBus, config?: CrewUi
|
|
|
17
17
|
|
|
18
18
|
export function updatePiCrewPowerbar(events: EventBus, cwd: string, config?: CrewUiConfig): void {
|
|
19
19
|
if (config?.powerbar === false) return;
|
|
20
|
-
const active =
|
|
20
|
+
const active = listRecentRuns(cwd, 20).map((run) => {
|
|
21
21
|
let agents = [] as ReturnType<typeof readCrewAgents>;
|
|
22
22
|
try { agents = readCrewAgents(run); } catch {}
|
|
23
23
|
return { run, agents };
|
package/src/ui/run-dashboard.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
|
-
import type { TeamRunManifest } from "../state/types.ts";
|
|
2
|
+
import type { TeamRunManifest, TeamTaskState, UsageState } from "../state/types.ts";
|
|
3
3
|
import { readCrewAgents } from "../runtime/crew-agent-records.ts";
|
|
4
4
|
import type { CrewAgentRecord } from "../runtime/crew-agent-runtime.ts";
|
|
5
5
|
import { isDisplayActiveRun, isLikelyOrphanedActiveRun } from "../runtime/process-status.ts";
|
|
@@ -12,6 +12,13 @@ interface DashboardComponent {
|
|
|
12
12
|
|
|
13
13
|
type DashboardTheme = { fg?: (color: string, text: string) => string; bold?: (text: string) => string };
|
|
14
14
|
|
|
15
|
+
export interface RunDashboardOptions {
|
|
16
|
+
placement?: "center" | "right";
|
|
17
|
+
showModel?: boolean;
|
|
18
|
+
showTokens?: boolean;
|
|
19
|
+
showTools?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
15
22
|
export type RunDashboardAction = "status" | "summary" | "artifacts" | "api" | "events" | "agents" | "agent-events" | "agent-output" | "agent-transcript" | "reload";
|
|
16
23
|
export interface RunDashboardSelection {
|
|
17
24
|
runId: string;
|
|
@@ -89,12 +96,52 @@ function formatAge(iso: string | undefined): string | undefined {
|
|
|
89
96
|
return `${Math.floor(ms / 3_600_000)}h`;
|
|
90
97
|
}
|
|
91
98
|
|
|
92
|
-
function
|
|
99
|
+
function readRunTasks(run: TeamRunManifest): TeamTaskState[] {
|
|
100
|
+
try {
|
|
101
|
+
if (!fs.existsSync(run.tasksPath)) return [];
|
|
102
|
+
const parsed = JSON.parse(fs.readFileSync(run.tasksPath, "utf-8"));
|
|
103
|
+
return Array.isArray(parsed) ? parsed as TeamTaskState[] : [];
|
|
104
|
+
} catch { return []; }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function formatTokens(usage: UsageState | undefined): string | undefined {
|
|
108
|
+
if (!usage) return undefined;
|
|
109
|
+
const total = (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
|
110
|
+
if (!total) return undefined;
|
|
111
|
+
const compact = total >= 1000 ? `${(total / 1000).toFixed(total >= 10_000 ? 0 : 1)}k` : `${total}`;
|
|
112
|
+
const parts = [`tok=${compact}`];
|
|
113
|
+
if (usage.input) parts.push(`in=${usage.input}`);
|
|
114
|
+
if (usage.output) parts.push(`out=${usage.output}`);
|
|
115
|
+
if (usage.cacheRead) parts.push(`cache=${usage.cacheRead}`);
|
|
116
|
+
if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
|
|
117
|
+
return parts.join("/");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function taskForAgent(tasks: TeamTaskState[], agent: CrewAgentRecord): TeamTaskState | undefined {
|
|
121
|
+
return tasks.find((task) => task.id === agent.taskId);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function modelForTask(task: TeamTaskState | undefined): string | undefined {
|
|
125
|
+
const attempts = task?.modelAttempts;
|
|
126
|
+
if (!attempts?.length) return undefined;
|
|
127
|
+
return attempts.find((attempt) => attempt.success)?.model ?? attempts.at(-1)?.model;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function modelForAgent(agent: CrewAgentRecord, task: TeamTaskState | undefined): string | undefined {
|
|
131
|
+
return modelForTask(task) ?? agent.model;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function usageForAgent(agent: CrewAgentRecord, task: TeamTaskState | undefined): UsageState | undefined {
|
|
135
|
+
return task?.usage ?? agent.usage;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function agentPreviewLine(agent: CrewAgentRecord, task: TeamTaskState | undefined, options: RunDashboardOptions): string {
|
|
93
139
|
const stats = [
|
|
94
140
|
agent.progress?.activityState,
|
|
95
|
-
|
|
96
|
-
agent.
|
|
97
|
-
agent.progress?.
|
|
141
|
+
options.showModel !== false && modelForAgent(agent, task) ? `model=${modelForAgent(agent, task)}` : undefined,
|
|
142
|
+
options.showTokens !== false ? formatTokens(usageForAgent(agent, task)) ?? (agent.progress?.tokens !== undefined ? `tok=${agent.progress.tokens}` : undefined) : undefined,
|
|
143
|
+
options.showTools !== false && agent.progress?.currentTool ? `tool=${agent.progress.currentTool}` : undefined,
|
|
144
|
+
options.showTools !== false && agent.toolUses !== undefined ? `${agent.toolUses} tools` : undefined,
|
|
98
145
|
agent.progress?.turns !== undefined ? `${agent.progress.turns} turns` : undefined,
|
|
99
146
|
agent.progress?.failedTool ? `failedTool=${agent.progress.failedTool}` : undefined,
|
|
100
147
|
agent.startedAt ? `age=${formatAge(agent.completedAt ?? agent.startedAt)}` : undefined,
|
|
@@ -103,11 +150,21 @@ function agentPreviewLine(agent: CrewAgentRecord): string {
|
|
|
103
150
|
return `Agent: ${statusIcon(agent.status)} ${agent.taskId} ${agent.role}->${agent.agent}${stats.length ? ` · ${stats.join(" · ")}` : ""}${recent ? ` ⎿ ${recent}` : ""}`;
|
|
104
151
|
}
|
|
105
152
|
|
|
106
|
-
function readAgentPreview(run: TeamRunManifest, maxLines = 5): string[] {
|
|
153
|
+
function readAgentPreview(run: TeamRunManifest, maxLines = 5, options: RunDashboardOptions = {}): string[] {
|
|
107
154
|
try {
|
|
108
155
|
const agents = readCrewAgents(run);
|
|
156
|
+
const tasks = readRunTasks(run);
|
|
109
157
|
if (!agents.length) return ["Agents: (none)"];
|
|
110
|
-
|
|
158
|
+
const totals = tasks.reduce((acc, task) => {
|
|
159
|
+
acc.input += task.usage?.input ?? 0;
|
|
160
|
+
acc.output += task.usage?.output ?? 0;
|
|
161
|
+
acc.cacheRead += task.usage?.cacheRead ?? 0;
|
|
162
|
+
acc.cacheWrite += task.usage?.cacheWrite ?? 0;
|
|
163
|
+
acc.cost += task.usage?.cost ?? 0;
|
|
164
|
+
return acc;
|
|
165
|
+
}, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
|
|
166
|
+
const header = formatTokens(totals) ? `Agents: ${formatTokens(totals)}` : "Agents:";
|
|
167
|
+
return [header, ...agents.slice(0, maxLines).map((agent) => agentPreviewLine(agent, taskForAgent(tasks, agent), options)), ...(agents.length > maxLines ? [`Agents: +${agents.length - maxLines} more`] : [])];
|
|
111
168
|
} catch (error) {
|
|
112
169
|
const message = error instanceof Error ? error.message : String(error);
|
|
113
170
|
return [`Agents: failed to read (${message})`];
|
|
@@ -154,11 +211,13 @@ export class RunDashboard implements DashboardComponent {
|
|
|
154
211
|
private readonly runs: TeamRunManifest[];
|
|
155
212
|
private readonly done: (selection: RunDashboardSelection | undefined) => void;
|
|
156
213
|
private readonly theme: DashboardTheme;
|
|
214
|
+
private readonly options: RunDashboardOptions;
|
|
157
215
|
|
|
158
|
-
constructor(runs: TeamRunManifest[], done: (selection: RunDashboardSelection | undefined) => void, theme: unknown = {}) {
|
|
216
|
+
constructor(runs: TeamRunManifest[], done: (selection: RunDashboardSelection | undefined) => void, theme: unknown = {}, options: RunDashboardOptions = {}) {
|
|
159
217
|
this.runs = runs;
|
|
160
218
|
this.done = done;
|
|
161
219
|
this.theme = theme as DashboardTheme;
|
|
220
|
+
this.options = options;
|
|
162
221
|
}
|
|
163
222
|
|
|
164
223
|
invalidate(): void {}
|
|
@@ -169,9 +228,10 @@ export class RunDashboard implements DashboardComponent {
|
|
|
169
228
|
const innerWidth = Math.max(20, width - 4);
|
|
170
229
|
const borderWidth = Math.min(innerWidth, Math.max(0, width - 2));
|
|
171
230
|
const border = (text: string) => fg("border", text);
|
|
231
|
+
const title = this.options.placement === "right" ? "pi-crew right sidebar" : "pi-crew dashboard";
|
|
172
232
|
const lines = [
|
|
173
233
|
border(`╭${"─".repeat(borderWidth)}╮`),
|
|
174
|
-
`│ ${padVisible(truncate(`${fg("accent", "
|
|
234
|
+
`│ ${padVisible(truncate(`${fg("accent", "▐")} ${bold(title)} ${this.options.placement === "right" ? fg("dim", "anchored top-right") : ""}`, innerWidth - 1), innerWidth - 1)}│`,
|
|
175
235
|
`│ ${padVisible(truncate(fg("dim", "↑/↓/j/k select • r reload • p progress • s/u/a/i actions • d agents • e/v/o viewers • q close"), innerWidth - 1), innerWidth - 1)}│`,
|
|
176
236
|
`│ ${padVisible(truncate(`Runs: ${this.runs.length} • ${countByStatus(this.runs)}`, innerWidth - 1), innerWidth - 1)}│`,
|
|
177
237
|
border(`├${"─".repeat(borderWidth)}┤`),
|
|
@@ -203,7 +263,7 @@ export class RunDashboard implements DashboardComponent {
|
|
|
203
263
|
selectedRun.async ? `Async: pid=${selectedRun.async.pid ?? "unknown"} log=${selectedRun.async.logPath}` : "Async: no",
|
|
204
264
|
`Goal: ${selectedRun.goal}`,
|
|
205
265
|
];
|
|
206
|
-
for (const detail of [...details, ...readAgentPreview(selectedRun), ...readProgressPreview(selectedRun, this.showFullProgress ? 20 : 5)]) {
|
|
266
|
+
for (const detail of [...details, ...readAgentPreview(selectedRun, this.showFullProgress ? 20 : 8, this.options), ...readProgressPreview(selectedRun, this.showFullProgress ? 20 : 5)]) {
|
|
207
267
|
lines.push(`│ ${padVisible(truncate(detail, innerWidth - 1), innerWidth - 1)}│`);
|
|
208
268
|
}
|
|
209
269
|
}
|