pi-crew 0.1.43 → 0.1.45
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 +27 -0
- 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/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 -297
- package/docs/research-extension-system.md +324 -324
- package/docs/research-optimization-plan.md +548 -548
- package/docs/research-phase10-distillation.md +199 -0
- package/docs/research-phase11-distillation.md +201 -0
- package/docs/research-pi-coding-agent.md +357 -357
- package/docs/research-source-pi-crew-reference.md +174 -174
- package/docs/runtime-flow.md +148 -148
- package/docs/source-runtime-refactor-map.md +83 -83
- package/index.ts +6 -6
- package/package.json +1 -1
- package/src/agents/agent-serializer.ts +34 -34
- package/src/agents/discover-agents.ts +1 -0
- package/src/config/config.ts +19 -0
- package/src/extension/cross-extension-rpc.ts +82 -82
- package/src/extension/register.ts +134 -8
- package/src/extension/registration/commands.ts +18 -2
- package/src/extension/registration/compaction-guard.ts +125 -125
- package/src/extension/registration/subagent-tools.ts +148 -148
- package/src/extension/registration/team-tool.ts +27 -8
- package/src/extension/run-bundle-schema.ts +89 -89
- package/src/extension/run-index.ts +19 -0
- package/src/extension/run-maintenance.ts +43 -43
- package/src/extension/team-tool/api.ts +1 -1
- package/src/extension/team-tool/cancel.ts +79 -4
- package/src/extension/team-tool/context.ts +2 -0
- package/src/extension/team-tool/handle-settings.ts +188 -188
- 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/respond.ts +84 -0
- package/src/extension/team-tool/run.ts +3 -2
- package/src/extension/team-tool/status.ts +7 -1
- package/src/extension/team-tool-types.ts +4 -0
- package/src/extension/team-tool.ts +2 -0
- package/src/i18n.ts +184 -184
- package/src/observability/event-to-metric.ts +6 -0
- package/src/observability/exporters/otlp-exporter.ts +77 -77
- package/src/prompt/prompt-runtime.ts +72 -72
- package/src/runtime/agent-control.ts +63 -63
- package/src/runtime/agent-memory.ts +72 -72
- package/src/runtime/agent-observability.ts +114 -114
- package/src/runtime/async-marker.ts +26 -26
- package/src/runtime/attention-events.ts +28 -28
- package/src/runtime/background-runner.ts +53 -53
- package/src/runtime/child-pi.ts +444 -444
- package/src/runtime/completion-guard.ts +87 -0
- package/src/runtime/crash-recovery.ts +30 -0
- package/src/runtime/crew-agent-records.ts +8 -0
- package/src/runtime/crew-agent-runtime.ts +2 -1
- package/src/runtime/delivery-coordinator.ts +154 -0
- 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 +106 -106
- package/src/runtime/heartbeat-gradient.ts +28 -28
- package/src/runtime/heartbeat-watcher.ts +124 -124
- package/src/runtime/live-agent-control.ts +87 -87
- 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 +305 -305
- package/src/runtime/model-fallback.ts +5 -2
- package/src/runtime/overflow-recovery.ts +176 -0
- package/src/runtime/parallel-research.ts +44 -44
- package/src/runtime/pi-json-output.ts +111 -111
- package/src/runtime/policy-engine.ts +79 -79
- package/src/runtime/process-status.ts +1 -1
- package/src/runtime/progress-event-coalescer.ts +43 -43
- package/src/runtime/recovery-recipes.ts +74 -74
- package/src/runtime/retry-executor.ts +64 -64
- package/src/runtime/role-permission.ts +39 -39
- package/src/runtime/session-resources.ts +25 -0
- package/src/runtime/session-snapshot.ts +59 -0
- package/src/runtime/session-usage.ts +79 -79
- package/src/runtime/sidechain-output.ts +29 -29
- package/src/runtime/stale-reconciler.ts +199 -0
- package/src/runtime/supervisor-contact.ts +59 -0
- package/src/runtime/task-display.ts +38 -38
- package/src/runtime/task-output-context.ts +127 -127
- package/src/runtime/task-runner/live-executor.ts +101 -101
- package/src/runtime/task-runner/progress.ts +119 -119
- package/src/runtime/task-runner/result-utils.ts +14 -14
- package/src/runtime/task-runner/state-helpers.ts +22 -22
- package/src/runtime/task-runner.ts +14 -0
- package/src/runtime/team-runner.ts +19 -8
- package/src/runtime/worker-heartbeat.ts +21 -21
- package/src/runtime/worker-startup.ts +57 -57
- package/src/schema/config-schema.ts +1 -0
- package/src/schema/team-tool-schema.ts +6 -1
- package/src/state/contracts.ts +6 -2
- package/src/state/state-store.ts +43 -0
- package/src/state/task-claims.ts +44 -44
- package/src/state/types.ts +2 -0
- 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/team-serializer.ts +38 -38
- package/src/types/diff.d.ts +18 -18
- package/src/ui/crew-footer.ts +101 -101
- package/src/ui/crew-select-list.ts +111 -111
- package/src/ui/crew-widget.ts +10 -5
- package/src/ui/dashboard-panes/mailbox-pane.ts +2 -1
- package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
- 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/powerbar-publisher.ts +4 -4
- package/src/ui/render-diff.ts +119 -119
- package/src/ui/render-scheduler.ts +143 -143
- package/src/ui/run-snapshot-cache.ts +310 -17
- package/src/ui/snapshot-types.ts +5 -0
- package/src/ui/spinner.ts +17 -17
- package/src/ui/status-colors.ts +58 -54
- package/src/ui/syntax-highlight.ts +116 -116
- package/src/utils/atomic-write.ts +33 -0
- package/src/utils/completion-dedupe.ts +63 -63
- package/src/utils/frontmatter.ts +68 -68
- package/src/utils/git.ts +262 -262
- package/src/utils/ids.ts +12 -12
- package/src/utils/names.ts +27 -27
- package/src/utils/redaction.ts +44 -44
- package/src/utils/safe-paths.ts +47 -47
- package/src/utils/sleep.ts +32 -32
- package/src/workflows/validate-workflow.ts +40 -40
- package/src/worktree/branch-freshness.ts +45 -45
- 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,125 +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
|
-
}
|
|
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
|
+
}
|
|
@@ -1,148 +1,148 @@
|
|
|
1
|
-
import type { ExtensionAPI, ToolDefinition } from "@mariozechner/pi-coding-agent";
|
|
2
|
-
import { Type } from "typebox";
|
|
3
|
-
import type { TeamToolParamsValue } from "../../schema/team-tool-schema.ts";
|
|
4
|
-
import { handleTeamTool } from "../team-tool.ts";
|
|
5
|
-
import { checkSubagentSpawnPermission, currentCrewRole } from "../../runtime/role-permission.ts";
|
|
6
|
-
import { readPersistedSubagentRecord, savePersistedSubagentRecord, type SubagentManager, type SubagentSpawnOptions } from "../../subagents/manager.ts";
|
|
7
|
-
import { loadConfig } from "../../config/config.ts";
|
|
8
|
-
import { logInternalError } from "../../utils/internal-error.ts";
|
|
9
|
-
import { __test__subagentSpawnParams, formatSubagentRecord, readSubagentRunResult, refreshPersistedSubagentRecord, subagentToolResult } from "./subagent-helpers.ts";
|
|
10
|
-
import { t } from "../../i18n.ts";
|
|
11
|
-
|
|
12
|
-
export interface SubagentToolRegistrationOptions {
|
|
13
|
-
ownerSessionGeneration?: () => number;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export function registerSubagentTools(pi: ExtensionAPI, subagentManager: SubagentManager, options: SubagentToolRegistrationOptions = {}): void {
|
|
17
|
-
const agentTool: ToolDefinition = {
|
|
18
|
-
name: "Agent",
|
|
19
|
-
label: "Agent",
|
|
20
|
-
description: "Launch a real pi-crew subagent. Uses pi-crew's durable child-process runtime by default; set run_in_background=true for parallel/background work, then use get_subagent_result.",
|
|
21
|
-
promptSnippet: "Use Agent to delegate focused work to a real pi-crew subagent. Use run_in_background=true for parallel work and get_subagent_result to join results.",
|
|
22
|
-
promptGuidelines: [
|
|
23
|
-
"Use Agent for independent exploration, review, verification, or implementation subtasks instead of doing all work in the parent turn.",
|
|
24
|
-
"For parallel work, launch multiple Agent calls with run_in_background=true, then call get_subagent_result for each result.",
|
|
25
|
-
"Available pi-crew subagent types include explorer, planner, analyst, executor, reviewer, verifier, writer, security-reviewer, and test-engineer.",
|
|
26
|
-
],
|
|
27
|
-
parameters: Type.Object({
|
|
28
|
-
prompt: Type.String({ description: "The task for the subagent to perform." }),
|
|
29
|
-
description: Type.String({ description: "Short 3-5 word task description." }),
|
|
30
|
-
subagent_type: Type.String({ description: "pi-crew agent name, e.g. explorer, planner, executor, reviewer, verifier, writer, security-reviewer, test-engineer." }),
|
|
31
|
-
model: Type.Optional(Type.String({ description: "Optional model override. If omitted, pi-crew uses Pi-configured model fallback." })),
|
|
32
|
-
max_turns: Type.Optional(Type.Number({ description: "Reserved for live-session subagents; child-process runtime may ignore this." })),
|
|
33
|
-
run_in_background: Type.Optional(Type.Boolean({ description: "Run in background and return an agent ID immediately." })),
|
|
34
|
-
}) as never,
|
|
35
|
-
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
36
|
-
const currentRole = currentCrewRole();
|
|
37
|
-
const permission = checkSubagentSpawnPermission(currentRole);
|
|
38
|
-
if (!permission.allowed) return subagentToolResult(permission.reason ?? "Current role cannot spawn subagents.", { role: currentRole, mode: permission.mode }, true);
|
|
39
|
-
const spawnOptions = __test__subagentSpawnParams(params as Record<string, unknown>, ctx);
|
|
40
|
-
spawnOptions.ownerSessionGeneration = options.ownerSessionGeneration?.();
|
|
41
|
-
if (!spawnOptions.prompt.trim()) return subagentToolResult(t("agent.requiresPrompt"), {}, true);
|
|
42
|
-
const runner = async (currentOptions: SubagentSpawnOptions, childSignal?: AbortSignal) => handleTeamTool({ action: "run", agent: currentOptions.type, goal: currentOptions.prompt, model: currentOptions.model, async: currentOptions.background, config: currentOptions.maxTurns ? { runtime: { maxTurns: currentOptions.maxTurns } } : undefined } as TeamToolParamsValue, currentOptions.background ? { ...ctx, signal: childSignal } : { ...ctx, signal: childSignal });
|
|
43
|
-
const record = subagentManager.spawn(spawnOptions, runner, spawnOptions.background ? undefined : signal);
|
|
44
|
-
if (spawnOptions.background || record.status === "queued") {
|
|
45
|
-
// Phase 1.1a: Terminate turn for background queued — no LLM follow-up needed.
|
|
46
|
-
// Phase 1.6: Record was terminated for telemetry.
|
|
47
|
-
record.terminated = true;
|
|
48
|
-
savePersistedSubagentRecord(ctx.cwd, record);
|
|
49
|
-
return { ...subagentToolResult([t("agent.started", { state: record.status === "queued" ? "queued" : "started" }), t("agent.id", { id: record.id }), t("agent.type", { type: record.type }), t("agent.description", { description: record.description }), t("agent.retrieveHint")].join("\n"), { agentId: record.id, status: record.status }), terminate: true };
|
|
50
|
-
}
|
|
51
|
-
await record.promise;
|
|
52
|
-
const output = readSubagentRunResult(ctx, record) ?? record.result ?? t("agent.noOutput");
|
|
53
|
-
const foregroundResult = subagentToolResult([t("agent.foregroundStatus", { id: record.id, status: record.status }), "", output].join("\n"), { agentId: record.id, runId: record.runId, status: record.status }, record.status === "failed" || record.status === "error");
|
|
54
|
-
if (loadConfig(ctx.cwd).config.tools?.terminateOnForeground === true) {
|
|
55
|
-
record.terminated = true;
|
|
56
|
-
savePersistedSubagentRecord(ctx.cwd, record);
|
|
57
|
-
return { ...foregroundResult, terminate: true };
|
|
58
|
-
}
|
|
59
|
-
return foregroundResult;
|
|
60
|
-
},
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
const getSubagentResultTool: ToolDefinition = {
|
|
64
|
-
name: "get_subagent_result",
|
|
65
|
-
label: "Get Agent Result",
|
|
66
|
-
description: "Check status and retrieve results from a pi-crew background subagent.",
|
|
67
|
-
parameters: Type.Object({ agent_id: Type.String({ description: "Agent ID returned by Agent." }), wait: Type.Optional(Type.Boolean({ description: "Wait for completion before returning." })), verbose: Type.Optional(Type.Boolean({ description: "Include status metadata before output." })) }) as never,
|
|
68
|
-
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
69
|
-
const p = params as { agent_id?: string; wait?: boolean; verbose?: boolean };
|
|
70
|
-
if (!p.agent_id) return subagentToolResult(t("result.requiresAgentId"), {}, true);
|
|
71
|
-
const inMemory = subagentManager.getRecord(p.agent_id);
|
|
72
|
-
const record = inMemory ?? readPersistedSubagentRecord(ctx.cwd, p.agent_id);
|
|
73
|
-
if (!record) return subagentToolResult(t("result.notFound", { id: p.agent_id }), {}, true);
|
|
74
|
-
let current = refreshPersistedSubagentRecord(ctx, record);
|
|
75
|
-
if (inMemory && current !== inMemory) Object.assign(inMemory, current);
|
|
76
|
-
if (!inMemory && !current.runId && (current.status === "running" || current.status === "queued")) {
|
|
77
|
-
current = { ...current, status: "error", error: t("result.unrecoverable"), completedAt: current.completedAt ?? Date.now() };
|
|
78
|
-
savePersistedSubagentRecord(ctx.cwd, current);
|
|
79
|
-
}
|
|
80
|
-
if (p.wait && (current.status === "running" || current.status === "queued")) {
|
|
81
|
-
const waited = await subagentManager.waitForRecord(current.id);
|
|
82
|
-
if (waited) current = waited;
|
|
83
|
-
if (current.status === "blocked") {
|
|
84
|
-
current.resultConsumed = false;
|
|
85
|
-
if (inMemory) inMemory.resultConsumed = false;
|
|
86
|
-
savePersistedSubagentRecord(ctx.cwd, current);
|
|
87
|
-
} else {
|
|
88
|
-
const waitStartMs = Date.now();
|
|
89
|
-
const maxWaitMs = 300_000; // 5 minutes
|
|
90
|
-
while (current.status === "running" || current.status === "queued") {
|
|
91
|
-
if (signal?.aborted) {
|
|
92
|
-
current = { ...current, status: "error", error: t("result.waitAborted"), completedAt: Date.now() };
|
|
93
|
-
savePersistedSubagentRecord(ctx.cwd, current);
|
|
94
|
-
break;
|
|
95
|
-
}
|
|
96
|
-
if (Date.now() - waitStartMs > maxWaitMs) {
|
|
97
|
-
current = { ...current, status: "error", error: t("result.waitTimeout"), completedAt: Date.now() };
|
|
98
|
-
savePersistedSubagentRecord(ctx.cwd, current);
|
|
99
|
-
break;
|
|
100
|
-
}
|
|
101
|
-
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
102
|
-
current = refreshPersistedSubagentRecord(ctx, current);
|
|
103
|
-
if (!current.runId) break;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
const output = readSubagentRunResult(ctx, current);
|
|
108
|
-
if (current.status !== "running" && current.status !== "queued" && current.status !== "blocked") {
|
|
109
|
-
current.resultConsumed = true;
|
|
110
|
-
if (inMemory) inMemory.resultConsumed = true;
|
|
111
|
-
savePersistedSubagentRecord(ctx.cwd, current);
|
|
112
|
-
}
|
|
113
|
-
const text = [p.verbose ? formatSubagentRecord(current) : undefined, output ? `${p.verbose ? "\n" : ""}${output}` : current.status === "running" || current.status === "queued" ? t("result.stillRunning") : current.error ?? t("agent.noOutput")].filter((line): line is string => Boolean(line)).join("\n");
|
|
114
|
-
return subagentToolResult(text, { agentId: current.id, runId: current.runId, status: current.status }, current.status === "failed" || current.status === "error");
|
|
115
|
-
},
|
|
116
|
-
};
|
|
117
|
-
|
|
118
|
-
const steerSubagentTool: ToolDefinition = {
|
|
119
|
-
name: "steer_subagent",
|
|
120
|
-
label: "Steer Agent",
|
|
121
|
-
description: "Send a steering note to a running pi-crew subagent. Live-session steering is planned; child-process runs expose durable status and can be cancelled if needed.",
|
|
122
|
-
parameters: Type.Object({ agent_id: Type.String(), message: Type.String() }) as never,
|
|
123
|
-
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
124
|
-
const p = params as { agent_id?: string; message?: string };
|
|
125
|
-
const record = p.agent_id ? subagentManager.getRecord(p.agent_id) ?? readPersistedSubagentRecord(ctx.cwd, p.agent_id) : undefined;
|
|
126
|
-
if (!record) return subagentToolResult(t("result.notFound", { id: p.agent_id ?? "" }), {}, true);
|
|
127
|
-
return subagentToolResult([t("steer.noted", { id: record.id }), t("steer.unavailable"), record.runId ? t("steer.cancelHint", { runId: record.runId }) : undefined].filter((line): line is string => Boolean(line)).join("\n"), { agentId: record.id, runId: record.runId, status: record.status });
|
|
128
|
-
},
|
|
129
|
-
};
|
|
130
|
-
|
|
131
|
-
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." };
|
|
132
|
-
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." };
|
|
133
|
-
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." };
|
|
134
|
-
const toolConfig = loadConfig(process.cwd()).config.tools;
|
|
135
|
-
const enableSteer = toolConfig?.enableSteer !== false;
|
|
136
|
-
const enableClaudeStyleAliases = toolConfig?.enableClaudeStyleAliases !== false;
|
|
137
|
-
|
|
138
|
-
for (const extraTool of enableSteer ? [crewAgentTool, crewAgentResultTool, crewAgentSteerTool] : [crewAgentTool, crewAgentResultTool]) pi.registerTool(extraTool);
|
|
139
|
-
if (enableClaudeStyleAliases) {
|
|
140
|
-
for (const extraTool of enableSteer ? [agentTool, getSubagentResultTool, steerSubagentTool] : [agentTool, getSubagentResultTool]) {
|
|
141
|
-
try {
|
|
142
|
-
pi.registerTool(extraTool);
|
|
143
|
-
} catch (error) {
|
|
144
|
-
logInternalError("register.duplicate-tool", error, `tool=${extraTool.name}`);
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
1
|
+
import type { ExtensionAPI, ToolDefinition } from "@mariozechner/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import type { TeamToolParamsValue } from "../../schema/team-tool-schema.ts";
|
|
4
|
+
import { handleTeamTool } from "../team-tool.ts";
|
|
5
|
+
import { checkSubagentSpawnPermission, currentCrewRole } from "../../runtime/role-permission.ts";
|
|
6
|
+
import { readPersistedSubagentRecord, savePersistedSubagentRecord, type SubagentManager, type SubagentSpawnOptions } from "../../subagents/manager.ts";
|
|
7
|
+
import { loadConfig } from "../../config/config.ts";
|
|
8
|
+
import { logInternalError } from "../../utils/internal-error.ts";
|
|
9
|
+
import { __test__subagentSpawnParams, formatSubagentRecord, readSubagentRunResult, refreshPersistedSubagentRecord, subagentToolResult } from "./subagent-helpers.ts";
|
|
10
|
+
import { t } from "../../i18n.ts";
|
|
11
|
+
|
|
12
|
+
export interface SubagentToolRegistrationOptions {
|
|
13
|
+
ownerSessionGeneration?: () => number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function registerSubagentTools(pi: ExtensionAPI, subagentManager: SubagentManager, options: SubagentToolRegistrationOptions = {}): void {
|
|
17
|
+
const agentTool: ToolDefinition = {
|
|
18
|
+
name: "Agent",
|
|
19
|
+
label: "Agent",
|
|
20
|
+
description: "Launch a real pi-crew subagent. Uses pi-crew's durable child-process runtime by default; set run_in_background=true for parallel/background work, then use get_subagent_result.",
|
|
21
|
+
promptSnippet: "Use Agent to delegate focused work to a real pi-crew subagent. Use run_in_background=true for parallel work and get_subagent_result to join results.",
|
|
22
|
+
promptGuidelines: [
|
|
23
|
+
"Use Agent for independent exploration, review, verification, or implementation subtasks instead of doing all work in the parent turn.",
|
|
24
|
+
"For parallel work, launch multiple Agent calls with run_in_background=true, then call get_subagent_result for each result.",
|
|
25
|
+
"Available pi-crew subagent types include explorer, planner, analyst, executor, reviewer, verifier, writer, security-reviewer, and test-engineer.",
|
|
26
|
+
],
|
|
27
|
+
parameters: Type.Object({
|
|
28
|
+
prompt: Type.String({ description: "The task for the subagent to perform." }),
|
|
29
|
+
description: Type.String({ description: "Short 3-5 word task description." }),
|
|
30
|
+
subagent_type: Type.String({ description: "pi-crew agent name, e.g. explorer, planner, executor, reviewer, verifier, writer, security-reviewer, test-engineer." }),
|
|
31
|
+
model: Type.Optional(Type.String({ description: "Optional model override. If omitted, pi-crew uses Pi-configured model fallback." })),
|
|
32
|
+
max_turns: Type.Optional(Type.Number({ description: "Reserved for live-session subagents; child-process runtime may ignore this." })),
|
|
33
|
+
run_in_background: Type.Optional(Type.Boolean({ description: "Run in background and return an agent ID immediately." })),
|
|
34
|
+
}) as never,
|
|
35
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
36
|
+
const currentRole = currentCrewRole();
|
|
37
|
+
const permission = checkSubagentSpawnPermission(currentRole);
|
|
38
|
+
if (!permission.allowed) return subagentToolResult(permission.reason ?? "Current role cannot spawn subagents.", { role: currentRole, mode: permission.mode }, true);
|
|
39
|
+
const spawnOptions = __test__subagentSpawnParams(params as Record<string, unknown>, ctx);
|
|
40
|
+
spawnOptions.ownerSessionGeneration = options.ownerSessionGeneration?.();
|
|
41
|
+
if (!spawnOptions.prompt.trim()) return subagentToolResult(t("agent.requiresPrompt"), {}, true);
|
|
42
|
+
const runner = async (currentOptions: SubagentSpawnOptions, childSignal?: AbortSignal) => handleTeamTool({ action: "run", agent: currentOptions.type, goal: currentOptions.prompt, model: currentOptions.model, async: currentOptions.background, config: currentOptions.maxTurns ? { runtime: { maxTurns: currentOptions.maxTurns } } : undefined } as TeamToolParamsValue, currentOptions.background ? { ...ctx, signal: childSignal } : { ...ctx, signal: childSignal });
|
|
43
|
+
const record = subagentManager.spawn(spawnOptions, runner, spawnOptions.background ? undefined : signal);
|
|
44
|
+
if (spawnOptions.background || record.status === "queued") {
|
|
45
|
+
// Phase 1.1a: Terminate turn for background queued — no LLM follow-up needed.
|
|
46
|
+
// Phase 1.6: Record was terminated for telemetry.
|
|
47
|
+
record.terminated = true;
|
|
48
|
+
savePersistedSubagentRecord(ctx.cwd, record);
|
|
49
|
+
return { ...subagentToolResult([t("agent.started", { state: record.status === "queued" ? "queued" : "started" }), t("agent.id", { id: record.id }), t("agent.type", { type: record.type }), t("agent.description", { description: record.description }), t("agent.retrieveHint")].join("\n"), { agentId: record.id, status: record.status }), terminate: true };
|
|
50
|
+
}
|
|
51
|
+
await record.promise;
|
|
52
|
+
const output = readSubagentRunResult(ctx, record) ?? record.result ?? t("agent.noOutput");
|
|
53
|
+
const foregroundResult = subagentToolResult([t("agent.foregroundStatus", { id: record.id, status: record.status }), "", output].join("\n"), { agentId: record.id, runId: record.runId, status: record.status }, record.status === "failed" || record.status === "error");
|
|
54
|
+
if (loadConfig(ctx.cwd).config.tools?.terminateOnForeground === true) {
|
|
55
|
+
record.terminated = true;
|
|
56
|
+
savePersistedSubagentRecord(ctx.cwd, record);
|
|
57
|
+
return { ...foregroundResult, terminate: true };
|
|
58
|
+
}
|
|
59
|
+
return foregroundResult;
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const getSubagentResultTool: ToolDefinition = {
|
|
64
|
+
name: "get_subagent_result",
|
|
65
|
+
label: "Get Agent Result",
|
|
66
|
+
description: "Check status and retrieve results from a pi-crew background subagent.",
|
|
67
|
+
parameters: Type.Object({ agent_id: Type.String({ description: "Agent ID returned by Agent." }), wait: Type.Optional(Type.Boolean({ description: "Wait for completion before returning." })), verbose: Type.Optional(Type.Boolean({ description: "Include status metadata before output." })) }) as never,
|
|
68
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
69
|
+
const p = params as { agent_id?: string; wait?: boolean; verbose?: boolean };
|
|
70
|
+
if (!p.agent_id) return subagentToolResult(t("result.requiresAgentId"), {}, true);
|
|
71
|
+
const inMemory = subagentManager.getRecord(p.agent_id);
|
|
72
|
+
const record = inMemory ?? readPersistedSubagentRecord(ctx.cwd, p.agent_id);
|
|
73
|
+
if (!record) return subagentToolResult(t("result.notFound", { id: p.agent_id }), {}, true);
|
|
74
|
+
let current = refreshPersistedSubagentRecord(ctx, record);
|
|
75
|
+
if (inMemory && current !== inMemory) Object.assign(inMemory, current);
|
|
76
|
+
if (!inMemory && !current.runId && (current.status === "running" || current.status === "queued")) {
|
|
77
|
+
current = { ...current, status: "error", error: t("result.unrecoverable"), completedAt: current.completedAt ?? Date.now() };
|
|
78
|
+
savePersistedSubagentRecord(ctx.cwd, current);
|
|
79
|
+
}
|
|
80
|
+
if (p.wait && (current.status === "running" || current.status === "queued")) {
|
|
81
|
+
const waited = await subagentManager.waitForRecord(current.id);
|
|
82
|
+
if (waited) current = waited;
|
|
83
|
+
if (current.status === "blocked") {
|
|
84
|
+
current.resultConsumed = false;
|
|
85
|
+
if (inMemory) inMemory.resultConsumed = false;
|
|
86
|
+
savePersistedSubagentRecord(ctx.cwd, current);
|
|
87
|
+
} else {
|
|
88
|
+
const waitStartMs = Date.now();
|
|
89
|
+
const maxWaitMs = 300_000; // 5 minutes
|
|
90
|
+
while (current.status === "running" || current.status === "queued") {
|
|
91
|
+
if (signal?.aborted) {
|
|
92
|
+
current = { ...current, status: "error", error: t("result.waitAborted"), completedAt: Date.now() };
|
|
93
|
+
savePersistedSubagentRecord(ctx.cwd, current);
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
if (Date.now() - waitStartMs > maxWaitMs) {
|
|
97
|
+
current = { ...current, status: "error", error: t("result.waitTimeout"), completedAt: Date.now() };
|
|
98
|
+
savePersistedSubagentRecord(ctx.cwd, current);
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
102
|
+
current = refreshPersistedSubagentRecord(ctx, current);
|
|
103
|
+
if (!current.runId) break;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const output = readSubagentRunResult(ctx, current);
|
|
108
|
+
if (current.status !== "running" && current.status !== "queued" && current.status !== "blocked") {
|
|
109
|
+
current.resultConsumed = true;
|
|
110
|
+
if (inMemory) inMemory.resultConsumed = true;
|
|
111
|
+
savePersistedSubagentRecord(ctx.cwd, current);
|
|
112
|
+
}
|
|
113
|
+
const text = [p.verbose ? formatSubagentRecord(current) : undefined, output ? `${p.verbose ? "\n" : ""}${output}` : current.status === "running" || current.status === "queued" ? t("result.stillRunning") : current.error ?? t("agent.noOutput")].filter((line): line is string => Boolean(line)).join("\n");
|
|
114
|
+
return subagentToolResult(text, { agentId: current.id, runId: current.runId, status: current.status }, current.status === "failed" || current.status === "error");
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const steerSubagentTool: ToolDefinition = {
|
|
119
|
+
name: "steer_subagent",
|
|
120
|
+
label: "Steer Agent",
|
|
121
|
+
description: "Send a steering note to a running pi-crew subagent. Live-session steering is planned; child-process runs expose durable status and can be cancelled if needed.",
|
|
122
|
+
parameters: Type.Object({ agent_id: Type.String(), message: Type.String() }) as never,
|
|
123
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
124
|
+
const p = params as { agent_id?: string; message?: string };
|
|
125
|
+
const record = p.agent_id ? subagentManager.getRecord(p.agent_id) ?? readPersistedSubagentRecord(ctx.cwd, p.agent_id) : undefined;
|
|
126
|
+
if (!record) return subagentToolResult(t("result.notFound", { id: p.agent_id ?? "" }), {}, true);
|
|
127
|
+
return subagentToolResult([t("steer.noted", { id: record.id }), t("steer.unavailable"), record.runId ? t("steer.cancelHint", { runId: record.runId }) : undefined].filter((line): line is string => Boolean(line)).join("\n"), { agentId: record.id, runId: record.runId, status: record.status });
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
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." };
|
|
132
|
+
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." };
|
|
133
|
+
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." };
|
|
134
|
+
const toolConfig = loadConfig(process.cwd()).config.tools;
|
|
135
|
+
const enableSteer = toolConfig?.enableSteer !== false;
|
|
136
|
+
const enableClaudeStyleAliases = toolConfig?.enableClaudeStyleAliases !== false;
|
|
137
|
+
|
|
138
|
+
for (const extraTool of enableSteer ? [crewAgentTool, crewAgentResultTool, crewAgentSteerTool] : [crewAgentTool, crewAgentResultTool]) pi.registerTool(extraTool);
|
|
139
|
+
if (enableClaudeStyleAliases) {
|
|
140
|
+
for (const extraTool of enableSteer ? [agentTool, getSubagentResultTool, steerSubagentTool] : [agentTool, getSubagentResultTool]) {
|
|
141
|
+
try {
|
|
142
|
+
pi.registerTool(extraTool);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
logInternalError("register.duplicate-tool", error, `tool=${extraTool.name}`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
1
3
|
import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@mariozechner/pi-coding-agent";
|
|
2
4
|
import { loadConfig } from "../../config/config.ts";
|
|
3
5
|
import { TeamToolParams, type TeamToolParamsValue } from "../../schema/team-tool-schema.ts";
|
|
@@ -8,6 +10,7 @@ import type { createManifestCache } from "../../runtime/manifest-cache.ts";
|
|
|
8
10
|
import type { createRunSnapshotCache } from "../../ui/run-snapshot-cache.ts";
|
|
9
11
|
import type { MetricRegistry } from "../../observability/metric-registry.ts";
|
|
10
12
|
import { handleTeamTool } from "../team-tool.ts";
|
|
13
|
+
import { toolResult } from "../tool-result.ts";
|
|
11
14
|
|
|
12
15
|
export interface RegisterTeamToolDeps {
|
|
13
16
|
foregroundControllers: Set<AbortController>;
|
|
@@ -17,6 +20,19 @@ export interface RegisterTeamToolDeps {
|
|
|
17
20
|
getRunSnapshotCache?: (cwd: string) => ReturnType<typeof createRunSnapshotCache>;
|
|
18
21
|
getMetricRegistry?: () => MetricRegistry | undefined;
|
|
19
22
|
widgetState: CrewWidgetState;
|
|
23
|
+
onJsonEvent?: (taskId: string, runId: string, event: unknown) => void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function resolveCwdOverride(baseCwd: string, override: string | undefined): { ok: true; cwd: string } | { ok: false; error: string } {
|
|
27
|
+
if (!override) return { ok: true, cwd: baseCwd };
|
|
28
|
+
const resolved = path.resolve(baseCwd, override);
|
|
29
|
+
try {
|
|
30
|
+
const stat = fs.statSync(resolved);
|
|
31
|
+
if (!stat.isDirectory()) return { ok: false, error: `cwd override is not a directory: ${resolved}` };
|
|
32
|
+
return { ok: true, cwd: resolved };
|
|
33
|
+
} catch {
|
|
34
|
+
return { ok: false, error: `cwd override does not exist: ${resolved}` };
|
|
35
|
+
}
|
|
20
36
|
}
|
|
21
37
|
|
|
22
38
|
export function registerTeamTool(pi: ExtensionAPI, deps: RegisterTeamToolDeps): void {
|
|
@@ -33,15 +49,18 @@ export function registerTeamTool(pi: ExtensionAPI, deps: RegisterTeamToolDeps):
|
|
|
33
49
|
signal?.addEventListener("abort", abort, { once: true });
|
|
34
50
|
try {
|
|
35
51
|
const resolved = params as TeamToolParamsValue;
|
|
52
|
+
const cwdOverride = resolveCwdOverride(ctx.cwd, resolved.cwd);
|
|
53
|
+
if (!cwdOverride.ok) return toolResult(cwdOverride.error, { action: resolved.action ?? "list", status: "error" }, true);
|
|
54
|
+
const toolCtx = { ...ctx, cwd: cwdOverride.cwd };
|
|
36
55
|
// Phase 1.5: Auto-set session name from team run context
|
|
37
56
|
if (resolved.action === "run" && resolved.goal && !pi.getSessionName()) {
|
|
38
57
|
const runLabel = resolved.team ?? resolved.agent ?? "direct";
|
|
39
58
|
pi.setSessionName(`pi-crew: ${runLabel}/${resolved.workflow ?? "default"} — ${resolved.goal.slice(0, 60)}`);
|
|
40
59
|
}
|
|
41
|
-
const output = await handleTeamTool(resolved, { ...
|
|
42
|
-
if (resolved.action === "run") {
|
|
60
|
+
const output = await handleTeamTool(resolved, { ...toolCtx, signal: controller.signal, metricRegistry: deps.getMetricRegistry?.(), startForegroundRun: (runner, runId) => deps.startForegroundRun(toolCtx, runner, runId), onRunStarted: (runId) => deps.openLiveSidebar(toolCtx, runId), onJsonEvent: deps.onJsonEvent });
|
|
61
|
+
if (resolved.action === "run" && !output.isError && typeof output.details?.runId === "string") {
|
|
43
62
|
pi.appendEntry("crew:run-started", {
|
|
44
|
-
runId: output.details
|
|
63
|
+
runId: output.details.runId,
|
|
45
64
|
team: resolved.team,
|
|
46
65
|
workflow: resolved.workflow,
|
|
47
66
|
agent: resolved.agent,
|
|
@@ -50,11 +69,11 @@ export function registerTeamTool(pi: ExtensionAPI, deps: RegisterTeamToolDeps):
|
|
|
50
69
|
timestamp: Date.now(),
|
|
51
70
|
});
|
|
52
71
|
}
|
|
53
|
-
const config = loadConfig(
|
|
54
|
-
const cache = deps.getManifestCache(
|
|
55
|
-
const snapshotCache = deps.getRunSnapshotCache?.(
|
|
56
|
-
updateCrewWidget(
|
|
57
|
-
updatePiCrewPowerbar(pi.events,
|
|
72
|
+
const config = loadConfig(toolCtx.cwd).config.ui;
|
|
73
|
+
const cache = deps.getManifestCache(toolCtx.cwd);
|
|
74
|
+
const snapshotCache = deps.getRunSnapshotCache?.(toolCtx.cwd);
|
|
75
|
+
updateCrewWidget(toolCtx, deps.widgetState, config, cache, snapshotCache);
|
|
76
|
+
updatePiCrewPowerbar(pi.events, toolCtx.cwd, config, cache, snapshotCache, toolCtx);
|
|
58
77
|
return output;
|
|
59
78
|
} finally {
|
|
60
79
|
signal?.removeEventListener("abort", abort);
|