pi-crew 0.1.30 → 0.1.32
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 +9 -0
- package/README.md +80 -27
- package/agents/analyst.md +11 -11
- package/agents/critic.md +11 -11
- package/agents/executor.md +11 -11
- package/agents/explorer.md +11 -11
- package/agents/planner.md +11 -11
- package/agents/reviewer.md +11 -11
- package/agents/security-reviewer.md +11 -11
- package/agents/test-engineer.md +11 -11
- package/agents/verifier.md +11 -11
- package/agents/writer.md +11 -11
- package/docs/architecture.md +173 -164
- package/docs/refactor-tasks-phase3.md +394 -394
- package/docs/refactor-tasks-phase4.md +564 -564
- package/docs/refactor-tasks-phase5.md +402 -402
- package/docs/refactor-tasks-phase6.md +662 -662
- package/docs/research-extension-examples.md +297 -0
- package/docs/research-extension-system.md +324 -0
- package/docs/research-optimization-plan.md +548 -0
- package/docs/research-pi-coding-agent.md +357 -0
- package/docs/resource-formats.md +4 -3
- package/docs/runtime-flow.md +148 -148
- package/docs/source-runtime-refactor-map.md +83 -83
- package/docs/usage.md +3 -3
- package/index.ts +6 -6
- package/package.json +1 -1
- package/schema.json +53 -1
- package/skills/git-master/SKILL.md +24 -19
- package/skills/read-only-explorer/SKILL.md +26 -21
- package/skills/safe-bash/SKILL.md +21 -16
- package/skills/task-packet/SKILL.md +28 -23
- package/skills/verify-evidence/SKILL.md +27 -22
- package/src/agents/agent-serializer.ts +34 -34
- package/src/agents/discover-agents.ts +102 -102
- package/src/config/config.ts +14 -1
- package/src/config/defaults.ts +3 -2
- package/src/extension/cross-extension-rpc.ts +82 -82
- package/src/extension/import-index.ts +4 -3
- package/src/extension/management.ts +2 -2
- package/src/extension/project-init.ts +9 -7
- package/src/extension/register.ts +63 -0
- package/src/extension/registration/artifact-cleanup.ts +15 -14
- package/src/extension/registration/commands.ts +208 -208
- package/src/extension/registration/compaction-guard.ts +125 -0
- package/src/extension/registration/subagent-tools.ts +27 -8
- package/src/extension/registration/team-tool.ts +61 -44
- package/src/extension/result-watcher.ts +98 -98
- package/src/extension/run-import.ts +4 -4
- package/src/extension/run-index.ts +14 -14
- package/src/extension/run-maintenance.ts +24 -24
- package/src/extension/team-tool/api.ts +3 -0
- package/src/extension/team-tool/cancel.ts +31 -31
- package/src/extension/team-tool/doctor.ts +179 -178
- package/src/extension/team-tool/inspect.ts +41 -41
- package/src/extension/team-tool/lifecycle-actions.ts +79 -79
- package/src/extension/team-tool/plan.ts +19 -19
- package/src/extension/team-tool/status.ts +73 -73
- package/src/prompt/prompt-runtime.ts +68 -68
- package/src/runtime/agent-control.ts +64 -64
- package/src/runtime/agent-memory.ts +72 -72
- package/src/runtime/agent-observability.ts +113 -113
- package/src/runtime/async-marker.ts +26 -26
- package/src/runtime/background-runner.ts +53 -53
- package/src/runtime/crew-agent-runtime.ts +58 -58
- package/src/runtime/direct-run.ts +35 -35
- package/src/runtime/foreground-control.ts +82 -82
- package/src/runtime/green-contract.ts +46 -46
- package/src/runtime/group-join.ts +88 -88
- package/src/runtime/live-agent-control.ts +78 -78
- package/src/runtime/live-agent-manager.ts +85 -85
- package/src/runtime/live-control-realtime.ts +36 -36
- package/src/runtime/live-session-runtime.ts +299 -299
- package/src/runtime/manifest-cache.ts +212 -214
- package/src/runtime/model-fallback.ts +261 -261
- package/src/runtime/parallel-research.ts +44 -44
- package/src/runtime/parallel-utils.ts +99 -99
- package/src/runtime/pi-json-output.ts +111 -111
- package/src/runtime/pi-spawn.ts +96 -96
- package/src/runtime/policy-engine.ts +78 -78
- package/src/runtime/post-exit-stdio-guard.ts +86 -86
- package/src/runtime/process-status.ts +56 -56
- package/src/runtime/progress-event-coalescer.ts +43 -43
- package/src/runtime/recovery-recipes.ts +74 -74
- package/src/runtime/role-permission.ts +39 -39
- package/src/runtime/session-usage.ts +79 -79
- package/src/runtime/sidechain-output.ts +28 -28
- package/src/runtime/subagent-manager.ts +29 -2
- package/src/runtime/task-display.ts +38 -38
- package/src/runtime/task-output-context.ts +106 -106
- package/src/runtime/task-packet.ts +84 -84
- package/src/runtime/task-runner/live-executor.ts +98 -98
- package/src/runtime/task-runner/progress.ts +111 -111
- package/src/runtime/task-runner/prompt-builder.ts +72 -72
- package/src/runtime/task-runner/result-utils.ts +14 -14
- package/src/runtime/task-runner/state-helpers.ts +22 -22
- package/src/runtime/worker-heartbeat.ts +21 -21
- package/src/runtime/worker-startup.ts +57 -57
- package/src/schema/config-schema.ts +12 -0
- package/src/schema/team-tool-schema.ts +100 -100
- package/src/state/artifact-store.ts +108 -108
- package/src/state/contracts.ts +105 -105
- package/src/state/jsonl-writer.ts +77 -77
- package/src/state/state-store.ts +8 -9
- package/src/state/task-claims.ts +42 -42
- package/src/state/types.ts +180 -180
- package/src/state/usage.ts +29 -29
- package/src/subagents/async-entry.ts +1 -1
- package/src/subagents/index.ts +3 -3
- package/src/subagents/live/control.ts +1 -1
- package/src/subagents/live/manager.ts +1 -1
- package/src/subagents/live/realtime.ts +1 -1
- package/src/subagents/live/session-runtime.ts +1 -1
- package/src/subagents/manager.ts +1 -1
- package/src/subagents/spawn.ts +1 -1
- package/src/teams/discover-teams.ts +2 -2
- package/src/teams/team-serializer.ts +36 -36
- package/src/types/diff.d.ts +18 -0
- package/src/ui/crew-footer.ts +101 -101
- package/src/ui/crew-select-list.ts +111 -111
- package/src/ui/crew-widget.ts +285 -285
- package/src/ui/dynamic-border.ts +25 -25
- package/src/ui/layout-primitives.ts +106 -106
- package/src/ui/loaders.ts +158 -158
- package/src/ui/mascot.ts +441 -441
- package/src/ui/powerbar-publisher.ts +94 -94
- package/src/ui/render-diff.ts +119 -119
- package/src/ui/run-dashboard.ts +372 -372
- package/src/ui/status-colors.ts +54 -54
- package/src/ui/syntax-highlight.ts +116 -116
- package/src/ui/transcript-viewer.ts +302 -302
- package/src/utils/completion-dedupe.ts +63 -63
- package/src/utils/file-coalescer.ts +84 -84
- package/src/utils/frontmatter.ts +36 -36
- package/src/utils/fs-watch.ts +31 -31
- package/src/utils/git.ts +262 -262
- package/src/utils/ids.ts +12 -12
- package/src/utils/names.ts +26 -26
- package/src/utils/paths.ts +34 -7
- package/src/utils/sleep.ts +32 -32
- package/src/utils/timings.ts +31 -31
- package/src/utils/visual.ts +159 -159
- package/src/workflows/discover-workflows.ts +2 -2
- package/src/workflows/validate-workflow.ts +40 -40
- package/src/worktree/branch-freshness.ts +45 -45
- package/src/worktree/cleanup.ts +71 -69
- package/src/worktree/worktree-manager.ts +3 -1
- package/teams/default.team.md +12 -12
- package/teams/fast-fix.team.md +11 -11
- package/teams/implementation.team.md +18 -18
- package/teams/parallel-research.team.md +14 -14
- package/teams/research.team.md +11 -11
- package/teams/review.team.md +12 -12
- package/workflows/default.workflow.md +29 -29
- package/workflows/fast-fix.workflow.md +22 -22
- package/workflows/implementation.workflow.md +38 -38
- package/workflows/parallel-research.workflow.md +46 -46
- package/workflows/research.workflow.md +22 -22
- package/workflows/review.workflow.md +30 -30
|
@@ -1,208 +1,208 @@
|
|
|
1
|
-
import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@mariozechner/pi-coding-agent";
|
|
2
|
-
import { loadConfig } from "../../config/config.ts";
|
|
3
|
-
import { handleTeamTool } from "../team-tool.ts";
|
|
4
|
-
import { piTeamsHelp } from "../help.ts";
|
|
5
|
-
import { handleTeamManagerCommand } from "../team-manager-command.ts";
|
|
6
|
-
import { loadRunManifestById } from "../../state/state-store.ts";
|
|
7
|
-
import type { TeamRunManifest } from "../../state/types.ts";
|
|
8
|
-
import { readCrewAgents } from "../../runtime/crew-agent-records.ts";
|
|
9
|
-
import { AnimatedMascot } from "../../ui/mascot.ts";
|
|
10
|
-
import { RunDashboard, type RunDashboardSelection } from "../../ui/run-dashboard.ts";
|
|
11
|
-
import { DurableTextViewer } from "../../ui/transcript-viewer.ts";
|
|
12
|
-
import { commandText, notifyCommandResult, parseRunArgs, parseScalar, pushUnset, setNestedConfig } from "./command-utils.ts";
|
|
13
|
-
import { openTranscriptViewer, selectAgentTask } from "./viewers.ts";
|
|
14
|
-
import { printTimings, time } from "../../utils/timings.ts";
|
|
15
|
-
|
|
16
|
-
export interface RegisterTeamCommandsDeps {
|
|
17
|
-
startForegroundRun: (ctx: ExtensionContext, runner: (signal?: AbortSignal) => Promise<void>, runId?: string) => void;
|
|
18
|
-
openLiveSidebar: (ctx: ExtensionContext, runId: string) => void;
|
|
19
|
-
getManifestCache: (cwd: string) => { list(max?: number): TeamRunManifest[] };
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function registerTeamCommands(pi: ExtensionAPI, deps: RegisterTeamCommandsDeps): void {
|
|
23
|
-
pi.registerCommand("teams", {
|
|
24
|
-
description: "List pi-crew teams, workflows, and agents",
|
|
25
|
-
handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
26
|
-
const result = await handleTeamTool({ action: "list" }, ctx);
|
|
27
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
28
|
-
},
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
pi.registerCommand("team-run", {
|
|
32
|
-
description: "Manually start a pi-crew run (agent may also use the team tool autonomously)",
|
|
33
|
-
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
34
|
-
const result = await handleTeamTool(parseRunArgs(args), { ...ctx, startForegroundRun: (runner, runId) => deps.startForegroundRun(ctx as ExtensionContext, runner, runId), onRunStarted: (runId) => deps.openLiveSidebar(ctx as ExtensionContext, runId) });
|
|
35
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
36
|
-
},
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
for (const [name, action, description] of [
|
|
40
|
-
["team-status", "status", "Show pi-crew run status"],
|
|
41
|
-
["team-resume", "resume", "Resume a pi-crew run by re-queueing failed/cancelled/skipped/running tasks"],
|
|
42
|
-
["team-summary", "summary", "Show pi-crew run summary"],
|
|
43
|
-
["team-events", "events", "Show full pi-crew event log for a run"],
|
|
44
|
-
["team-artifacts", "artifacts", "List pi-crew artifacts for a run"],
|
|
45
|
-
["team-worktrees", "worktrees", "List pi-crew worktrees for a run"],
|
|
46
|
-
["team-export", "export", "Export a pi-crew run bundle to artifacts/export"],
|
|
47
|
-
["team-cancel", "cancel", "Cancel a pi-crew run"],
|
|
48
|
-
] as const) {
|
|
49
|
-
pi.registerCommand(name, { description, handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
50
|
-
const runId = args.trim() || undefined;
|
|
51
|
-
const result = await handleTeamTool({ action, runId }, ctx);
|
|
52
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
53
|
-
} });
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
pi.registerCommand("team-api", {
|
|
57
|
-
description: "Run safe pi-crew API interop operations: <runId> <operation> [key=value]",
|
|
58
|
-
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
59
|
-
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
60
|
-
const runId = tokens.find((token) => !token.includes("=") && !token.startsWith("--"));
|
|
61
|
-
const operation = tokens.find((token) => token !== runId && !token.includes("=") && !token.startsWith("--")) ?? "read-manifest";
|
|
62
|
-
const config: Record<string, unknown> = { operation };
|
|
63
|
-
for (const token of tokens.filter((item) => item.includes("="))) {
|
|
64
|
-
const [key, ...rest] = token.split("=");
|
|
65
|
-
if (key) config[key] = parseScalar(rest.join("="));
|
|
66
|
-
}
|
|
67
|
-
const result = await handleTeamTool({ action: "api", runId, config }, ctx);
|
|
68
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
69
|
-
},
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
pi.registerCommand("team-imports", { description: "List imported pi-crew run bundles", handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
73
|
-
const result = await handleTeamTool({ action: "imports" }, ctx);
|
|
74
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
75
|
-
} });
|
|
76
|
-
|
|
77
|
-
pi.registerCommand("team-import", { description: "Import a pi-crew run-export.json bundle into local imports", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
78
|
-
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
79
|
-
const pathArg = tokens.find((token) => !token.startsWith("--"));
|
|
80
|
-
const scope = tokens.includes("--user") ? "user" : "project";
|
|
81
|
-
const result = await handleTeamTool({ action: "import", config: { path: pathArg, scope } }, ctx);
|
|
82
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
83
|
-
} });
|
|
84
|
-
|
|
85
|
-
pi.registerCommand("team-prune", { description: "Prune old finished pi-crew runs, keeping the newest N", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
86
|
-
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
87
|
-
const keepToken = tokens.find((token) => token.startsWith("--keep="));
|
|
88
|
-
const keep = keepToken ? Number.parseInt(keepToken.slice("--keep=".length), 10) : undefined;
|
|
89
|
-
const result = await handleTeamTool({ action: "prune", keep, confirm: tokens.includes("--confirm") }, ctx);
|
|
90
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
91
|
-
} });
|
|
92
|
-
|
|
93
|
-
pi.registerCommand("team-forget", { description: "Forget a pi-crew run by deleting its state and artifacts", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
94
|
-
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
95
|
-
const runId = tokens.find((token) => !token.startsWith("--"));
|
|
96
|
-
const result = await handleTeamTool({ action: "forget", runId, force: tokens.includes("--force"), confirm: tokens.includes("--confirm") }, ctx);
|
|
97
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
98
|
-
} });
|
|
99
|
-
|
|
100
|
-
pi.registerCommand("team-cleanup", { description: "Clean up pi-crew worktrees for a run", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
101
|
-
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
102
|
-
const runId = tokens.find((token) => !token.startsWith("--"));
|
|
103
|
-
const result = await handleTeamTool({ action: "cleanup", runId, force: tokens.includes("--force") }, ctx);
|
|
104
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
105
|
-
} });
|
|
106
|
-
|
|
107
|
-
pi.registerCommand("team-manager", { description: "Open a simple pi-crew interactive manager", handler: handleTeamManagerCommand });
|
|
108
|
-
|
|
109
|
-
pi.registerCommand("team-result", { description: "Open a pi-crew agent result viewer: <runId> [taskId]", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
110
|
-
const [runId, rawTaskId] = args.trim().split(/\s+/).filter(Boolean);
|
|
111
|
-
const selected = await selectAgentTask(ctx, runId, rawTaskId);
|
|
112
|
-
const loaded = selected ? loadRunManifestById(ctx.cwd, selected.runId) : undefined;
|
|
113
|
-
if (ctx.hasUI && loaded) {
|
|
114
|
-
const agent = readCrewAgents(loaded.manifest).find((item) => item.taskId === selected?.taskId || item.id === selected?.taskId) ?? readCrewAgents(loaded.manifest)[0];
|
|
115
|
-
const text = agent?.resultArtifactPath ? commandText(await handleTeamTool({ action: "api", runId: selected!.runId, config: { operation: "read-agent-output", agentId: agent.taskId, maxBytes: 64_000 } }, ctx)) : "(no result)";
|
|
116
|
-
await ctx.ui.custom<undefined>((_tui, theme, _keybindings, done) => new DurableTextViewer("pi-crew result", `${selected!.runId}:${agent?.taskId ?? "unknown"}`, text.split(/\r?\n/), theme, done), { overlay: true, overlayOptions: { width: "90%", maxHeight: "85%", anchor: "center" } });
|
|
117
|
-
return;
|
|
118
|
-
}
|
|
119
|
-
const result = await handleTeamTool({ action: "api", runId, config: { operation: "read-agent-output", agentId: rawTaskId, maxBytes: 64_000 } }, ctx);
|
|
120
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
121
|
-
} });
|
|
122
|
-
|
|
123
|
-
pi.registerCommand("team-transcript", { description: "Open a pi-crew transcript viewer: <runId> [taskId]", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
124
|
-
const [runId, taskId] = args.trim().split(/\s+/).filter(Boolean);
|
|
125
|
-
if (await openTranscriptViewer(ctx, runId, taskId)) return;
|
|
126
|
-
const result = await handleTeamTool({ action: "api", runId, config: { operation: "read-agent-transcript", agentId: taskId } }, ctx);
|
|
127
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
128
|
-
} });
|
|
129
|
-
|
|
130
|
-
pi.registerCommand("team-dashboard", { description: "Open a pi-crew run dashboard overlay", handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
131
|
-
for (;;) {
|
|
132
|
-
const runs = deps.getManifestCache(ctx.cwd).list(50);
|
|
133
|
-
const uiConfig = loadConfig(ctx.cwd).config.ui;
|
|
134
|
-
const rightPanel = uiConfig?.dashboardPlacement !== "center";
|
|
135
|
-
const width = rightPanel ? Math.min(90, Math.max(40, uiConfig?.dashboardWidth ?? 56)) : "90%";
|
|
136
|
-
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 }), { overlay: true, overlayOptions: rightPanel ? { width, minWidth: 40, maxHeight: "100%", anchor: "top-right", offsetX: 0, offsetY: 0, margin: { top: 0, right: 0, bottom: 0, left: 0 } } : { width, maxHeight: "90%", anchor: "center", margin: 2 } });
|
|
137
|
-
if (!selection) return;
|
|
138
|
-
if (selection.action === "reload") continue;
|
|
139
|
-
if (selection.action === "agent-transcript" && await openTranscriptViewer(ctx, selection.runId)) continue;
|
|
140
|
-
const result = selection.action === "api" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-manifest" } }, ctx) : selection.action === "agents" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "agent-dashboard" } }, ctx) : selection.action === "agent-events" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-events", limit: 50 } }, ctx) : selection.action === "agent-output" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-output", maxBytes: 32_000 } }, ctx) : selection.action === "agent-transcript" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-transcript" } }, ctx) : await handleTeamTool({ action: selection.action, runId: selection.runId }, ctx);
|
|
141
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
142
|
-
return;
|
|
143
|
-
}
|
|
144
|
-
} });
|
|
145
|
-
|
|
146
|
-
pi.registerCommand("team-mascot", { description: "Show an animated mascot splash", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
147
|
-
if (!ctx.hasUI) return;
|
|
148
|
-
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
149
|
-
const uiConfig = loadConfig(ctx.cwd).config.ui;
|
|
150
|
-
const styleArg = tokens.find((t) => t === "cat" || t === "armin");
|
|
151
|
-
const effectArg = tokens.find((t) => ["random", "none", "typewriter", "scanline", "rain", "fade", "crt", "glitch", "dissolve"].includes(t));
|
|
152
|
-
const style = (styleArg as "cat" | "armin" | undefined) ?? uiConfig?.mascotStyle ?? "cat";
|
|
153
|
-
const effect = (effectArg as "random" | "none" | "typewriter" | "scanline" | "rain" | "fade" | "crt" | "glitch" | "dissolve" | undefined) ?? uiConfig?.mascotEffect ?? "random";
|
|
154
|
-
await ctx.ui.custom<undefined>((tui, theme, _keybindings, done) => new AnimatedMascot(theme, () => done(undefined), { frameIntervalMs: style === "armin" ? 33 : 180, autoCloseMs: 7000, requestRender: () => (tui as { requestRender?: () => void }).requestRender?.(), style, effect }), { overlay: true, overlayOptions: { width: style === "armin" ? 48 : 62, maxHeight: "85%", anchor: "center" } });
|
|
155
|
-
} });
|
|
156
|
-
|
|
157
|
-
pi.registerCommand("team-init", { description: "Initialize project-local pi-crew directories and gitignore entries", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
158
|
-
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
159
|
-
const result = await handleTeamTool({ action: "init", config: { copyBuiltins: tokens.includes("--copy-builtins"), overwrite: tokens.includes("--overwrite") } }, ctx);
|
|
160
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
161
|
-
} });
|
|
162
|
-
|
|
163
|
-
pi.registerCommand("team-autonomy", { description: "Show or toggle pi-crew autonomous delegation policy: status|on|off", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
164
|
-
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
165
|
-
const mode = tokens[0]?.toLowerCase();
|
|
166
|
-
const config = mode === "on" ? { profile: "suggested", enabled: true, injectPolicy: true } : mode === "off" ? { profile: "manual", enabled: false } : mode === "manual" || mode === "suggested" || mode === "assisted" || mode === "aggressive" ? { profile: mode, enabled: mode !== "manual", injectPolicy: mode !== "manual" } : { preferAsyncForLongTasks: tokens.includes("--prefer-async") ? true : undefined, allowWorktreeSuggestion: tokens.includes("--no-worktree-suggest") ? false : undefined };
|
|
167
|
-
const result = await handleTeamTool({ action: "autonomy", config }, ctx);
|
|
168
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
169
|
-
} });
|
|
170
|
-
|
|
171
|
-
pi.registerCommand("team-config", { description: "Show or update pi-crew config. Use key=value [--project] to update.", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
172
|
-
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
173
|
-
if (tokens.length === 0) {
|
|
174
|
-
const result = await handleTeamTool({ action: "config" }, ctx);
|
|
175
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
const config: Record<string, unknown> = { scope: tokens.includes("--project") ? "project" : "user" };
|
|
179
|
-
for (const token of tokens) {
|
|
180
|
-
if (token.startsWith("--unset=")) {
|
|
181
|
-
pushUnset(config, token.slice("--unset=".length));
|
|
182
|
-
continue;
|
|
183
|
-
}
|
|
184
|
-
if (!token.includes("=")) continue;
|
|
185
|
-
const [key, ...rest] = token.split("=");
|
|
186
|
-
if (!key) continue;
|
|
187
|
-
const raw = rest.join("=");
|
|
188
|
-
if (raw === "unset" || raw === "null") pushUnset(config, key);
|
|
189
|
-
else setNestedConfig(config, key, parseScalar(raw));
|
|
190
|
-
}
|
|
191
|
-
const result = await handleTeamTool({ action: "config", config }, ctx);
|
|
192
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
193
|
-
} });
|
|
194
|
-
|
|
195
|
-
for (const [name, action, description] of [
|
|
196
|
-
["team-validate", "validate", "Validate pi-crew agents, teams, and workflows"],
|
|
197
|
-
["team-doctor", "doctor", "Check pi-crew installation and discovery readiness"],
|
|
198
|
-
] as const) pi.registerCommand(name, { description, handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
199
|
-
const result = await handleTeamTool({ action }, ctx);
|
|
200
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
201
|
-
} });
|
|
202
|
-
|
|
203
|
-
pi.registerCommand("team-help", { description: "Show pi-crew command help", handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
204
|
-
await notifyCommandResult(ctx, piTeamsHelp());
|
|
205
|
-
} });
|
|
206
|
-
time("register.commands");
|
|
207
|
-
printTimings();
|
|
208
|
-
}
|
|
1
|
+
import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@mariozechner/pi-coding-agent";
|
|
2
|
+
import { loadConfig } from "../../config/config.ts";
|
|
3
|
+
import { handleTeamTool } from "../team-tool.ts";
|
|
4
|
+
import { piTeamsHelp } from "../help.ts";
|
|
5
|
+
import { handleTeamManagerCommand } from "../team-manager-command.ts";
|
|
6
|
+
import { loadRunManifestById } from "../../state/state-store.ts";
|
|
7
|
+
import type { TeamRunManifest } from "../../state/types.ts";
|
|
8
|
+
import { readCrewAgents } from "../../runtime/crew-agent-records.ts";
|
|
9
|
+
import { AnimatedMascot } from "../../ui/mascot.ts";
|
|
10
|
+
import { RunDashboard, type RunDashboardSelection } from "../../ui/run-dashboard.ts";
|
|
11
|
+
import { DurableTextViewer } from "../../ui/transcript-viewer.ts";
|
|
12
|
+
import { commandText, notifyCommandResult, parseRunArgs, parseScalar, pushUnset, setNestedConfig } from "./command-utils.ts";
|
|
13
|
+
import { openTranscriptViewer, selectAgentTask } from "./viewers.ts";
|
|
14
|
+
import { printTimings, time } from "../../utils/timings.ts";
|
|
15
|
+
|
|
16
|
+
export interface RegisterTeamCommandsDeps {
|
|
17
|
+
startForegroundRun: (ctx: ExtensionContext, runner: (signal?: AbortSignal) => Promise<void>, runId?: string) => void;
|
|
18
|
+
openLiveSidebar: (ctx: ExtensionContext, runId: string) => void;
|
|
19
|
+
getManifestCache: (cwd: string) => { list(max?: number): TeamRunManifest[] };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function registerTeamCommands(pi: ExtensionAPI, deps: RegisterTeamCommandsDeps): void {
|
|
23
|
+
pi.registerCommand("teams", {
|
|
24
|
+
description: "List pi-crew teams, workflows, and agents",
|
|
25
|
+
handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
26
|
+
const result = await handleTeamTool({ action: "list" }, ctx);
|
|
27
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
pi.registerCommand("team-run", {
|
|
32
|
+
description: "Manually start a pi-crew run (agent may also use the team tool autonomously)",
|
|
33
|
+
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
34
|
+
const result = await handleTeamTool(parseRunArgs(args), { ...ctx, startForegroundRun: (runner, runId) => deps.startForegroundRun(ctx as ExtensionContext, runner, runId), onRunStarted: (runId) => deps.openLiveSidebar(ctx as ExtensionContext, runId) });
|
|
35
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
for (const [name, action, description] of [
|
|
40
|
+
["team-status", "status", "Show pi-crew run status"],
|
|
41
|
+
["team-resume", "resume", "Resume a pi-crew run by re-queueing failed/cancelled/skipped/running tasks"],
|
|
42
|
+
["team-summary", "summary", "Show pi-crew run summary"],
|
|
43
|
+
["team-events", "events", "Show full pi-crew event log for a run"],
|
|
44
|
+
["team-artifacts", "artifacts", "List pi-crew artifacts for a run"],
|
|
45
|
+
["team-worktrees", "worktrees", "List pi-crew worktrees for a run"],
|
|
46
|
+
["team-export", "export", "Export a pi-crew run bundle to artifacts/export"],
|
|
47
|
+
["team-cancel", "cancel", "Cancel a pi-crew run"],
|
|
48
|
+
] as const) {
|
|
49
|
+
pi.registerCommand(name, { description, handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
50
|
+
const runId = args.trim() || undefined;
|
|
51
|
+
const result = await handleTeamTool({ action, runId }, ctx);
|
|
52
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
53
|
+
} });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
pi.registerCommand("team-api", {
|
|
57
|
+
description: "Run safe pi-crew API interop operations: <runId> <operation> [key=value]",
|
|
58
|
+
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
59
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
60
|
+
const runId = tokens.find((token) => !token.includes("=") && !token.startsWith("--"));
|
|
61
|
+
const operation = tokens.find((token) => token !== runId && !token.includes("=") && !token.startsWith("--")) ?? "read-manifest";
|
|
62
|
+
const config: Record<string, unknown> = { operation };
|
|
63
|
+
for (const token of tokens.filter((item) => item.includes("="))) {
|
|
64
|
+
const [key, ...rest] = token.split("=");
|
|
65
|
+
if (key) config[key] = parseScalar(rest.join("="));
|
|
66
|
+
}
|
|
67
|
+
const result = await handleTeamTool({ action: "api", runId, config }, ctx);
|
|
68
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
pi.registerCommand("team-imports", { description: "List imported pi-crew run bundles", handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
73
|
+
const result = await handleTeamTool({ action: "imports" }, ctx);
|
|
74
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
75
|
+
} });
|
|
76
|
+
|
|
77
|
+
pi.registerCommand("team-import", { description: "Import a pi-crew run-export.json bundle into local imports", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
78
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
79
|
+
const pathArg = tokens.find((token) => !token.startsWith("--"));
|
|
80
|
+
const scope = tokens.includes("--user") ? "user" : "project";
|
|
81
|
+
const result = await handleTeamTool({ action: "import", config: { path: pathArg, scope } }, ctx);
|
|
82
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
83
|
+
} });
|
|
84
|
+
|
|
85
|
+
pi.registerCommand("team-prune", { description: "Prune old finished pi-crew runs, keeping the newest N", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
86
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
87
|
+
const keepToken = tokens.find((token) => token.startsWith("--keep="));
|
|
88
|
+
const keep = keepToken ? Number.parseInt(keepToken.slice("--keep=".length), 10) : undefined;
|
|
89
|
+
const result = await handleTeamTool({ action: "prune", keep, confirm: tokens.includes("--confirm") }, ctx);
|
|
90
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
91
|
+
} });
|
|
92
|
+
|
|
93
|
+
pi.registerCommand("team-forget", { description: "Forget a pi-crew run by deleting its state and artifacts", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
94
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
95
|
+
const runId = tokens.find((token) => !token.startsWith("--"));
|
|
96
|
+
const result = await handleTeamTool({ action: "forget", runId, force: tokens.includes("--force"), confirm: tokens.includes("--confirm") }, ctx);
|
|
97
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
98
|
+
} });
|
|
99
|
+
|
|
100
|
+
pi.registerCommand("team-cleanup", { description: "Clean up pi-crew worktrees for a run", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
101
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
102
|
+
const runId = tokens.find((token) => !token.startsWith("--"));
|
|
103
|
+
const result = await handleTeamTool({ action: "cleanup", runId, force: tokens.includes("--force") }, ctx);
|
|
104
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
105
|
+
} });
|
|
106
|
+
|
|
107
|
+
pi.registerCommand("team-manager", { description: "Open a simple pi-crew interactive manager", handler: handleTeamManagerCommand });
|
|
108
|
+
|
|
109
|
+
pi.registerCommand("team-result", { description: "Open a pi-crew agent result viewer: <runId> [taskId]", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
110
|
+
const [runId, rawTaskId] = args.trim().split(/\s+/).filter(Boolean);
|
|
111
|
+
const selected = await selectAgentTask(ctx, runId, rawTaskId);
|
|
112
|
+
const loaded = selected ? loadRunManifestById(ctx.cwd, selected.runId) : undefined;
|
|
113
|
+
if (ctx.hasUI && loaded) {
|
|
114
|
+
const agent = readCrewAgents(loaded.manifest).find((item) => item.taskId === selected?.taskId || item.id === selected?.taskId) ?? readCrewAgents(loaded.manifest)[0];
|
|
115
|
+
const text = agent?.resultArtifactPath ? commandText(await handleTeamTool({ action: "api", runId: selected!.runId, config: { operation: "read-agent-output", agentId: agent.taskId, maxBytes: 64_000 } }, ctx)) : "(no result)";
|
|
116
|
+
await ctx.ui.custom<undefined>((_tui, theme, _keybindings, done) => new DurableTextViewer("pi-crew result", `${selected!.runId}:${agent?.taskId ?? "unknown"}`, text.split(/\r?\n/), theme, done), { overlay: true, overlayOptions: { width: "90%", maxHeight: "85%", anchor: "center" } });
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const result = await handleTeamTool({ action: "api", runId, config: { operation: "read-agent-output", agentId: rawTaskId, maxBytes: 64_000 } }, ctx);
|
|
120
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
121
|
+
} });
|
|
122
|
+
|
|
123
|
+
pi.registerCommand("team-transcript", { description: "Open a pi-crew transcript viewer: <runId> [taskId]", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
124
|
+
const [runId, taskId] = args.trim().split(/\s+/).filter(Boolean);
|
|
125
|
+
if (await openTranscriptViewer(ctx, runId, taskId)) return;
|
|
126
|
+
const result = await handleTeamTool({ action: "api", runId, config: { operation: "read-agent-transcript", agentId: taskId } }, ctx);
|
|
127
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
128
|
+
} });
|
|
129
|
+
|
|
130
|
+
pi.registerCommand("team-dashboard", { description: "Open a pi-crew run dashboard overlay", handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
131
|
+
for (;;) {
|
|
132
|
+
const runs = deps.getManifestCache(ctx.cwd).list(50);
|
|
133
|
+
const uiConfig = loadConfig(ctx.cwd).config.ui;
|
|
134
|
+
const rightPanel = uiConfig?.dashboardPlacement !== "center";
|
|
135
|
+
const width = rightPanel ? Math.min(90, Math.max(40, uiConfig?.dashboardWidth ?? 56)) : "90%";
|
|
136
|
+
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 }), { overlay: true, overlayOptions: rightPanel ? { width, minWidth: 40, maxHeight: "100%", anchor: "top-right", offsetX: 0, offsetY: 0, margin: { top: 0, right: 0, bottom: 0, left: 0 } } : { width, maxHeight: "90%", anchor: "center", margin: 2 } });
|
|
137
|
+
if (!selection) return;
|
|
138
|
+
if (selection.action === "reload") continue;
|
|
139
|
+
if (selection.action === "agent-transcript" && await openTranscriptViewer(ctx, selection.runId)) continue;
|
|
140
|
+
const result = selection.action === "api" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-manifest" } }, ctx) : selection.action === "agents" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "agent-dashboard" } }, ctx) : selection.action === "agent-events" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-events", limit: 50 } }, ctx) : selection.action === "agent-output" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-output", maxBytes: 32_000 } }, ctx) : selection.action === "agent-transcript" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-transcript" } }, ctx) : await handleTeamTool({ action: selection.action, runId: selection.runId }, ctx);
|
|
141
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
} });
|
|
145
|
+
|
|
146
|
+
pi.registerCommand("team-mascot", { description: "Show an animated mascot splash", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
147
|
+
if (!ctx.hasUI) return;
|
|
148
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
149
|
+
const uiConfig = loadConfig(ctx.cwd).config.ui;
|
|
150
|
+
const styleArg = tokens.find((t) => t === "cat" || t === "armin");
|
|
151
|
+
const effectArg = tokens.find((t) => ["random", "none", "typewriter", "scanline", "rain", "fade", "crt", "glitch", "dissolve"].includes(t));
|
|
152
|
+
const style = (styleArg as "cat" | "armin" | undefined) ?? uiConfig?.mascotStyle ?? "cat";
|
|
153
|
+
const effect = (effectArg as "random" | "none" | "typewriter" | "scanline" | "rain" | "fade" | "crt" | "glitch" | "dissolve" | undefined) ?? uiConfig?.mascotEffect ?? "random";
|
|
154
|
+
await ctx.ui.custom<undefined>((tui, theme, _keybindings, done) => new AnimatedMascot(theme, () => done(undefined), { frameIntervalMs: style === "armin" ? 33 : 180, autoCloseMs: 7000, requestRender: () => (tui as { requestRender?: () => void }).requestRender?.(), style, effect }), { overlay: true, overlayOptions: { width: style === "armin" ? 48 : 62, maxHeight: "85%", anchor: "center" } });
|
|
155
|
+
} });
|
|
156
|
+
|
|
157
|
+
pi.registerCommand("team-init", { description: "Initialize project-local pi-crew directories and gitignore entries", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
158
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
159
|
+
const result = await handleTeamTool({ action: "init", config: { copyBuiltins: tokens.includes("--copy-builtins"), overwrite: tokens.includes("--overwrite") } }, ctx);
|
|
160
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
161
|
+
} });
|
|
162
|
+
|
|
163
|
+
pi.registerCommand("team-autonomy", { description: "Show or toggle pi-crew autonomous delegation policy: status|on|off", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
164
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
165
|
+
const mode = tokens[0]?.toLowerCase();
|
|
166
|
+
const config = mode === "on" ? { profile: "suggested", enabled: true, injectPolicy: true } : mode === "off" ? { profile: "manual", enabled: false } : mode === "manual" || mode === "suggested" || mode === "assisted" || mode === "aggressive" ? { profile: mode, enabled: mode !== "manual", injectPolicy: mode !== "manual" } : { preferAsyncForLongTasks: tokens.includes("--prefer-async") ? true : undefined, allowWorktreeSuggestion: tokens.includes("--no-worktree-suggest") ? false : undefined };
|
|
167
|
+
const result = await handleTeamTool({ action: "autonomy", config }, ctx);
|
|
168
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
169
|
+
} });
|
|
170
|
+
|
|
171
|
+
pi.registerCommand("team-config", { description: "Show or update pi-crew config. Use key=value [--project] to update.", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
172
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
173
|
+
if (tokens.length === 0) {
|
|
174
|
+
const result = await handleTeamTool({ action: "config" }, ctx);
|
|
175
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const config: Record<string, unknown> = { scope: tokens.includes("--project") ? "project" : "user" };
|
|
179
|
+
for (const token of tokens) {
|
|
180
|
+
if (token.startsWith("--unset=")) {
|
|
181
|
+
pushUnset(config, token.slice("--unset=".length));
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (!token.includes("=")) continue;
|
|
185
|
+
const [key, ...rest] = token.split("=");
|
|
186
|
+
if (!key) continue;
|
|
187
|
+
const raw = rest.join("=");
|
|
188
|
+
if (raw === "unset" || raw === "null") pushUnset(config, key);
|
|
189
|
+
else setNestedConfig(config, key, parseScalar(raw));
|
|
190
|
+
}
|
|
191
|
+
const result = await handleTeamTool({ action: "config", config }, ctx);
|
|
192
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
193
|
+
} });
|
|
194
|
+
|
|
195
|
+
for (const [name, action, description] of [
|
|
196
|
+
["team-validate", "validate", "Validate pi-crew agents, teams, and workflows"],
|
|
197
|
+
["team-doctor", "doctor", "Check pi-crew installation and discovery readiness"],
|
|
198
|
+
] as const) pi.registerCommand(name, { description, handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
199
|
+
const result = await handleTeamTool({ action }, ctx);
|
|
200
|
+
await notifyCommandResult(ctx, commandText(result));
|
|
201
|
+
} });
|
|
202
|
+
|
|
203
|
+
pi.registerCommand("team-help", { description: "Show pi-crew command help", handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
204
|
+
await notifyCommandResult(ctx, piTeamsHelp());
|
|
205
|
+
} });
|
|
206
|
+
time("register.commands");
|
|
207
|
+
printTimings();
|
|
208
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
|
|
2
|
+
import { listRecentRuns } from "../run-index.ts";
|
|
3
|
+
import type { ArtifactDescriptor, TeamRunManifest } from "../../state/types.ts";
|
|
4
|
+
|
|
5
|
+
export interface RegisterCompactionGuardOptions {
|
|
6
|
+
foregroundControllers: Set<AbortController>;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const TRIGGER_RATIO = 0.75;
|
|
10
|
+
const HARD_RATIO = 0.95;
|
|
11
|
+
const DEFAULT_CONTEXT_WINDOW = 200_000;
|
|
12
|
+
const MAX_ARTIFACT_INDEX_RUNS = 10;
|
|
13
|
+
const MAX_ARTIFACT_INDEX_ITEMS = 80;
|
|
14
|
+
|
|
15
|
+
function contextWindow(ctx: { model?: { contextWindow?: number } }): number {
|
|
16
|
+
const value = ctx.model?.contextWindow;
|
|
17
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : DEFAULT_CONTEXT_WINDOW;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function usageRatio(ctx: { getContextUsage(): { tokens: number | null } | undefined; model?: { contextWindow?: number } }): number | undefined {
|
|
21
|
+
const tokens = ctx.getContextUsage()?.tokens;
|
|
22
|
+
if (tokens === null || tokens === undefined || !Number.isFinite(tokens)) return undefined;
|
|
23
|
+
return tokens / contextWindow(ctx);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface CrewArtifactIndexEntry {
|
|
27
|
+
runId: string;
|
|
28
|
+
status: TeamRunManifest["status"];
|
|
29
|
+
team: string;
|
|
30
|
+
workflow?: string;
|
|
31
|
+
goal: string;
|
|
32
|
+
artifact: Pick<ArtifactDescriptor, "kind" | "path" | "producer" | "sizeBytes" | "createdAt">;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function collectCrewArtifactIndex(cwd: string): CrewArtifactIndexEntry[] {
|
|
36
|
+
const entries: CrewArtifactIndexEntry[] = [];
|
|
37
|
+
for (const run of listRecentRuns(cwd, MAX_ARTIFACT_INDEX_RUNS)) {
|
|
38
|
+
for (const artifact of run.artifacts) {
|
|
39
|
+
entries.push({
|
|
40
|
+
runId: run.runId,
|
|
41
|
+
status: run.status,
|
|
42
|
+
team: run.team,
|
|
43
|
+
workflow: run.workflow,
|
|
44
|
+
goal: run.goal,
|
|
45
|
+
artifact: {
|
|
46
|
+
kind: artifact.kind,
|
|
47
|
+
path: artifact.path,
|
|
48
|
+
producer: artifact.producer,
|
|
49
|
+
sizeBytes: artifact.sizeBytes,
|
|
50
|
+
createdAt: artifact.createdAt,
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
if (entries.length >= MAX_ARTIFACT_INDEX_ITEMS) return entries;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return entries;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function formatCrewArtifactIndex(entries: CrewArtifactIndexEntry[]): string {
|
|
60
|
+
if (!entries.length) return "";
|
|
61
|
+
const lines = ["", "# pi-crew artifact index", "Preserve these run artifact references in the compaction summary:"];
|
|
62
|
+
for (const entry of entries) {
|
|
63
|
+
lines.push(`- ${entry.artifact.kind}: ${entry.artifact.path} (run=${entry.runId}, status=${entry.status}, team=${entry.team}, workflow=${entry.workflow ?? "none"}, producer=${entry.artifact.producer})`);
|
|
64
|
+
}
|
|
65
|
+
return lines.join("\n");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function registerCompactionGuard(pi: ExtensionAPI, options: RegisterCompactionGuardOptions): void {
|
|
69
|
+
let pendingCompactReason: string | null = null;
|
|
70
|
+
let compactionInProgress = false;
|
|
71
|
+
|
|
72
|
+
const startCompact = (ctx: ExtensionContext, reason: string): void => {
|
|
73
|
+
if (compactionInProgress) return;
|
|
74
|
+
compactionInProgress = true;
|
|
75
|
+
const artifactIndex = collectCrewArtifactIndex(ctx.cwd);
|
|
76
|
+
if (artifactIndex.length > 0) {
|
|
77
|
+
pi.appendEntry("crew:artifact-index", {
|
|
78
|
+
reason,
|
|
79
|
+
createdAt: new Date().toISOString(),
|
|
80
|
+
artifacts: artifactIndex,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
ctx.compact({
|
|
84
|
+
customInstructions: `Prioritize keeping pi-crew run state, task results, artifact references, run IDs, and next actions. Keep completed-task detail concise.${formatCrewArtifactIndex(artifactIndex)}`,
|
|
85
|
+
onComplete: () => {
|
|
86
|
+
compactionInProgress = false;
|
|
87
|
+
ctx.ui.notify(reason === "deferred" ? "Deferred compaction completed" : "Auto-compacted context during team run", "info");
|
|
88
|
+
},
|
|
89
|
+
onError: (error) => {
|
|
90
|
+
compactionInProgress = false;
|
|
91
|
+
ctx.ui.notify(`${reason === "deferred" ? "Deferred" : "Auto"} compaction failed: ${error.message}`, "error");
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
// Phase 1.2: Defer compaction during foreground runs unless context is critically full.
|
|
97
|
+
pi.on("session_before_compact", async (_event, ctx) => {
|
|
98
|
+
if (options.foregroundControllers.size === 0) return;
|
|
99
|
+
const ratio = usageRatio(ctx);
|
|
100
|
+
if (ratio !== undefined && ratio >= HARD_RATIO) {
|
|
101
|
+
ctx.ui.notify("Compaction allowed despite foreground run: context is critically full", "warning");
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
pendingCompactReason = "deferred-during-foreground-run";
|
|
105
|
+
ctx.ui.notify("Compaction deferred: foreground team run in progress", "info");
|
|
106
|
+
return { cancel: true };
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// Phase 2.1: Proactive compaction with dynamic threshold based on model context window.
|
|
110
|
+
pi.on("turn_end", (_event, ctx) => {
|
|
111
|
+
if (compactionInProgress) return;
|
|
112
|
+
if (options.foregroundControllers.size === 0 && pendingCompactReason) {
|
|
113
|
+
pendingCompactReason = null;
|
|
114
|
+
startCompact(ctx, "deferred");
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const ratio = usageRatio(ctx);
|
|
118
|
+
if (ratio === undefined || ratio < TRIGGER_RATIO) return;
|
|
119
|
+
if (options.foregroundControllers.size > 0) {
|
|
120
|
+
pendingCompactReason = "threshold-during-foreground-run";
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
startCompact(ctx, "threshold");
|
|
124
|
+
});
|
|
125
|
+
}
|
|
@@ -4,6 +4,7 @@ import type { TeamToolParamsValue } from "../../schema/team-tool-schema.ts";
|
|
|
4
4
|
import { handleTeamTool } from "../team-tool.ts";
|
|
5
5
|
import { checkSubagentSpawnPermission, currentCrewRole } from "../../runtime/role-permission.ts";
|
|
6
6
|
import { readPersistedSubagentRecord, savePersistedSubagentRecord, type SubagentManager, type SubagentSpawnOptions } from "../../subagents/manager.ts";
|
|
7
|
+
import { loadConfig } from "../../config/config.ts";
|
|
7
8
|
import { logInternalError } from "../../utils/internal-error.ts";
|
|
8
9
|
import { __test__subagentSpawnParams, formatSubagentRecord, readSubagentRunResult, refreshPersistedSubagentRecord, subagentToolResult } from "./subagent-helpers.ts";
|
|
9
10
|
|
|
@@ -34,10 +35,22 @@ export function registerSubagentTools(pi: ExtensionAPI, subagentManager: Subagen
|
|
|
34
35
|
if (!options.prompt.trim()) return subagentToolResult("Agent requires prompt.", {}, true);
|
|
35
36
|
const runner = async (spawnOptions: SubagentSpawnOptions, childSignal?: AbortSignal) => handleTeamTool({ action: "run", agent: spawnOptions.type, goal: spawnOptions.prompt, model: spawnOptions.model, async: spawnOptions.background, config: spawnOptions.maxTurns ? { runtime: { maxTurns: spawnOptions.maxTurns } } : undefined } as TeamToolParamsValue, spawnOptions.background ? { ...ctx, signal: childSignal } : { ...ctx, signal: childSignal });
|
|
36
37
|
const record = subagentManager.spawn(options, runner, options.background ? undefined : signal);
|
|
37
|
-
if (options.background || record.status === "queued")
|
|
38
|
+
if (options.background || record.status === "queued") {
|
|
39
|
+
// Phase 1.1a: Terminate turn for background queued — no LLM follow-up needed.
|
|
40
|
+
// Phase 1.6: Record was terminated for telemetry.
|
|
41
|
+
record.terminated = true;
|
|
42
|
+
savePersistedSubagentRecord(ctx.cwd, record);
|
|
43
|
+
return { ...subagentToolResult([`Agent ${record.status === "queued" ? "queued" : "started"}.`, `Agent ID: ${record.id}`, `Type: ${record.type}`, `Description: ${record.description}`, "Use get_subagent_result to retrieve output. Do not duplicate this agent's work."].join("\n"), { agentId: record.id, status: record.status }), terminate: true };
|
|
44
|
+
}
|
|
38
45
|
await record.promise;
|
|
39
46
|
const output = readSubagentRunResult(ctx, record) ?? record.result ?? "No output.";
|
|
40
|
-
|
|
47
|
+
const foregroundResult = subagentToolResult([`Agent ${record.id} ${record.status}.`, "", output].join("\n"), { agentId: record.id, runId: record.runId, status: record.status }, record.status === "failed" || record.status === "error");
|
|
48
|
+
if (loadConfig(ctx.cwd).config.tools?.terminateOnForeground === true) {
|
|
49
|
+
record.terminated = true;
|
|
50
|
+
savePersistedSubagentRecord(ctx.cwd, record);
|
|
51
|
+
return { ...foregroundResult, terminate: true };
|
|
52
|
+
}
|
|
53
|
+
return foregroundResult;
|
|
41
54
|
},
|
|
42
55
|
};
|
|
43
56
|
|
|
@@ -99,12 +112,18 @@ export function registerSubagentTools(pi: ExtensionAPI, subagentManager: Subagen
|
|
|
99
112
|
const crewAgentTool: ToolDefinition = { ...agentTool, name: "crew_agent", label: "Crew Agent", description: "Launch a real pi-crew subagent using a conflict-safe pi-crew-specific tool name.", promptSnippet: "Use crew_agent when you need pi-crew subagents and another extension may own the generic Agent tool." };
|
|
100
113
|
const crewAgentResultTool: ToolDefinition = { ...getSubagentResultTool, name: "crew_agent_result", label: "Get Crew Agent Result", description: "Check status and retrieve results from a pi-crew subagent using the conflict-safe tool name." };
|
|
101
114
|
const crewAgentSteerTool: ToolDefinition = { ...steerSubagentTool, name: "crew_agent_steer", label: "Steer Crew Agent", description: "Send a steering note to a pi-crew subagent using the conflict-safe tool name." };
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
115
|
+
const toolConfig = loadConfig(process.cwd()).config.tools;
|
|
116
|
+
const enableSteer = toolConfig?.enableSteer !== false;
|
|
117
|
+
const enableClaudeStyleAliases = toolConfig?.enableClaudeStyleAliases !== false;
|
|
118
|
+
|
|
119
|
+
for (const extraTool of enableSteer ? [crewAgentTool, crewAgentResultTool, crewAgentSteerTool] : [crewAgentTool, crewAgentResultTool]) pi.registerTool(extraTool);
|
|
120
|
+
if (enableClaudeStyleAliases) {
|
|
121
|
+
for (const extraTool of enableSteer ? [agentTool, getSubagentResultTool, steerSubagentTool] : [agentTool, getSubagentResultTool]) {
|
|
122
|
+
try {
|
|
123
|
+
pi.registerTool(extraTool);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
logInternalError("register.duplicate-tool", error, `tool=${extraTool.name}`);
|
|
126
|
+
}
|
|
108
127
|
}
|
|
109
128
|
}
|
|
110
129
|
}
|