@oh-my-pi/pi-coding-agent 1.337.0
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 +1228 -0
- package/README.md +1041 -0
- package/docs/compaction.md +403 -0
- package/docs/custom-tools.md +541 -0
- package/docs/extension-loading.md +1004 -0
- package/docs/hooks.md +867 -0
- package/docs/rpc.md +1040 -0
- package/docs/sdk.md +994 -0
- package/docs/session-tree-plan.md +441 -0
- package/docs/session.md +240 -0
- package/docs/skills.md +290 -0
- package/docs/theme.md +637 -0
- package/docs/tree.md +197 -0
- package/docs/tui.md +341 -0
- package/examples/README.md +21 -0
- package/examples/custom-tools/README.md +124 -0
- package/examples/custom-tools/hello/index.ts +20 -0
- package/examples/custom-tools/question/index.ts +84 -0
- package/examples/custom-tools/subagent/README.md +172 -0
- package/examples/custom-tools/subagent/agents/planner.md +37 -0
- package/examples/custom-tools/subagent/agents/reviewer.md +35 -0
- package/examples/custom-tools/subagent/agents/scout.md +50 -0
- package/examples/custom-tools/subagent/agents/worker.md +24 -0
- package/examples/custom-tools/subagent/agents.ts +156 -0
- package/examples/custom-tools/subagent/commands/implement-and-review.md +10 -0
- package/examples/custom-tools/subagent/commands/implement.md +10 -0
- package/examples/custom-tools/subagent/commands/scout-and-plan.md +9 -0
- package/examples/custom-tools/subagent/index.ts +1002 -0
- package/examples/custom-tools/todo/index.ts +212 -0
- package/examples/hooks/README.md +56 -0
- package/examples/hooks/auto-commit-on-exit.ts +49 -0
- package/examples/hooks/confirm-destructive.ts +59 -0
- package/examples/hooks/custom-compaction.ts +116 -0
- package/examples/hooks/dirty-repo-guard.ts +52 -0
- package/examples/hooks/file-trigger.ts +41 -0
- package/examples/hooks/git-checkpoint.ts +53 -0
- package/examples/hooks/handoff.ts +150 -0
- package/examples/hooks/permission-gate.ts +34 -0
- package/examples/hooks/protected-paths.ts +30 -0
- package/examples/hooks/qna.ts +119 -0
- package/examples/hooks/snake.ts +343 -0
- package/examples/hooks/status-line.ts +40 -0
- package/examples/sdk/01-minimal.ts +22 -0
- package/examples/sdk/02-custom-model.ts +49 -0
- package/examples/sdk/03-custom-prompt.ts +44 -0
- package/examples/sdk/04-skills.ts +44 -0
- package/examples/sdk/05-tools.ts +90 -0
- package/examples/sdk/06-hooks.ts +61 -0
- package/examples/sdk/07-context-files.ts +36 -0
- package/examples/sdk/08-slash-commands.ts +42 -0
- package/examples/sdk/09-api-keys-and-oauth.ts +55 -0
- package/examples/sdk/10-settings.ts +38 -0
- package/examples/sdk/11-sessions.ts +48 -0
- package/examples/sdk/12-full-control.ts +95 -0
- package/examples/sdk/README.md +154 -0
- package/package.json +81 -0
- package/src/cli/args.ts +246 -0
- package/src/cli/file-processor.ts +72 -0
- package/src/cli/list-models.ts +104 -0
- package/src/cli/plugin-cli.ts +650 -0
- package/src/cli/session-picker.ts +41 -0
- package/src/cli.ts +10 -0
- package/src/commands/init.md +20 -0
- package/src/config.ts +159 -0
- package/src/core/agent-session.ts +1900 -0
- package/src/core/auth-storage.ts +236 -0
- package/src/core/bash-executor.ts +196 -0
- package/src/core/compaction/branch-summarization.ts +343 -0
- package/src/core/compaction/compaction.ts +742 -0
- package/src/core/compaction/index.ts +7 -0
- package/src/core/compaction/utils.ts +154 -0
- package/src/core/custom-tools/index.ts +21 -0
- package/src/core/custom-tools/loader.ts +248 -0
- package/src/core/custom-tools/types.ts +169 -0
- package/src/core/custom-tools/wrapper.ts +28 -0
- package/src/core/exec.ts +129 -0
- package/src/core/export-html/index.ts +211 -0
- package/src/core/export-html/template.css +781 -0
- package/src/core/export-html/template.html +54 -0
- package/src/core/export-html/template.js +1185 -0
- package/src/core/export-html/vendor/highlight.min.js +1213 -0
- package/src/core/export-html/vendor/marked.min.js +6 -0
- package/src/core/hooks/index.ts +16 -0
- package/src/core/hooks/loader.ts +312 -0
- package/src/core/hooks/runner.ts +434 -0
- package/src/core/hooks/tool-wrapper.ts +99 -0
- package/src/core/hooks/types.ts +773 -0
- package/src/core/index.ts +52 -0
- package/src/core/mcp/client.ts +158 -0
- package/src/core/mcp/config.ts +154 -0
- package/src/core/mcp/index.ts +45 -0
- package/src/core/mcp/loader.ts +68 -0
- package/src/core/mcp/manager.ts +181 -0
- package/src/core/mcp/tool-bridge.ts +148 -0
- package/src/core/mcp/transports/http.ts +316 -0
- package/src/core/mcp/transports/index.ts +6 -0
- package/src/core/mcp/transports/stdio.ts +252 -0
- package/src/core/mcp/types.ts +220 -0
- package/src/core/messages.ts +189 -0
- package/src/core/model-registry.ts +317 -0
- package/src/core/model-resolver.ts +393 -0
- package/src/core/plugins/doctor.ts +59 -0
- package/src/core/plugins/index.ts +38 -0
- package/src/core/plugins/installer.ts +189 -0
- package/src/core/plugins/loader.ts +338 -0
- package/src/core/plugins/manager.ts +672 -0
- package/src/core/plugins/parser.ts +105 -0
- package/src/core/plugins/paths.ts +32 -0
- package/src/core/plugins/types.ts +190 -0
- package/src/core/sdk.ts +760 -0
- package/src/core/session-manager.ts +1128 -0
- package/src/core/settings-manager.ts +443 -0
- package/src/core/skills.ts +437 -0
- package/src/core/slash-commands.ts +248 -0
- package/src/core/system-prompt.ts +439 -0
- package/src/core/timings.ts +25 -0
- package/src/core/tools/ask.ts +211 -0
- package/src/core/tools/bash-interceptor.ts +120 -0
- package/src/core/tools/bash.ts +250 -0
- package/src/core/tools/context.ts +32 -0
- package/src/core/tools/edit-diff.ts +475 -0
- package/src/core/tools/edit.ts +208 -0
- package/src/core/tools/exa/company.ts +59 -0
- package/src/core/tools/exa/index.ts +64 -0
- package/src/core/tools/exa/linkedin.ts +59 -0
- package/src/core/tools/exa/logger.ts +56 -0
- package/src/core/tools/exa/mcp-client.ts +368 -0
- package/src/core/tools/exa/render.ts +196 -0
- package/src/core/tools/exa/researcher.ts +90 -0
- package/src/core/tools/exa/search.ts +337 -0
- package/src/core/tools/exa/types.ts +168 -0
- package/src/core/tools/exa/websets.ts +248 -0
- package/src/core/tools/find.ts +261 -0
- package/src/core/tools/grep.ts +555 -0
- package/src/core/tools/index.ts +202 -0
- package/src/core/tools/ls.ts +140 -0
- package/src/core/tools/lsp/client.ts +605 -0
- package/src/core/tools/lsp/config.ts +147 -0
- package/src/core/tools/lsp/edits.ts +101 -0
- package/src/core/tools/lsp/index.ts +804 -0
- package/src/core/tools/lsp/render.ts +447 -0
- package/src/core/tools/lsp/rust-analyzer.ts +145 -0
- package/src/core/tools/lsp/types.ts +463 -0
- package/src/core/tools/lsp/utils.ts +486 -0
- package/src/core/tools/notebook.ts +229 -0
- package/src/core/tools/path-utils.ts +61 -0
- package/src/core/tools/read.ts +240 -0
- package/src/core/tools/renderers.ts +540 -0
- package/src/core/tools/task/agents.ts +153 -0
- package/src/core/tools/task/artifacts.ts +114 -0
- package/src/core/tools/task/bundled-agents/browser.md +71 -0
- package/src/core/tools/task/bundled-agents/explore.md +82 -0
- package/src/core/tools/task/bundled-agents/plan.md +54 -0
- package/src/core/tools/task/bundled-agents/reviewer.md +59 -0
- package/src/core/tools/task/bundled-agents/task.md +53 -0
- package/src/core/tools/task/bundled-commands/architect-plan.md +10 -0
- package/src/core/tools/task/bundled-commands/implement-with-critic.md +11 -0
- package/src/core/tools/task/bundled-commands/implement.md +11 -0
- package/src/core/tools/task/commands.ts +213 -0
- package/src/core/tools/task/discovery.ts +208 -0
- package/src/core/tools/task/executor.ts +367 -0
- package/src/core/tools/task/index.ts +388 -0
- package/src/core/tools/task/model-resolver.ts +115 -0
- package/src/core/tools/task/parallel.ts +38 -0
- package/src/core/tools/task/render.ts +232 -0
- package/src/core/tools/task/types.ts +99 -0
- package/src/core/tools/truncate.ts +265 -0
- package/src/core/tools/web-fetch.ts +2370 -0
- package/src/core/tools/web-search/auth.ts +193 -0
- package/src/core/tools/web-search/index.ts +537 -0
- package/src/core/tools/web-search/providers/anthropic.ts +198 -0
- package/src/core/tools/web-search/providers/exa.ts +302 -0
- package/src/core/tools/web-search/providers/perplexity.ts +195 -0
- package/src/core/tools/web-search/render.ts +182 -0
- package/src/core/tools/web-search/types.ts +180 -0
- package/src/core/tools/write.ts +99 -0
- package/src/index.ts +176 -0
- package/src/main.ts +464 -0
- package/src/migrations.ts +135 -0
- package/src/modes/index.ts +43 -0
- package/src/modes/interactive/components/armin.ts +382 -0
- package/src/modes/interactive/components/assistant-message.ts +86 -0
- package/src/modes/interactive/components/bash-execution.ts +196 -0
- package/src/modes/interactive/components/bordered-loader.ts +41 -0
- package/src/modes/interactive/components/branch-summary-message.ts +42 -0
- package/src/modes/interactive/components/compaction-summary-message.ts +45 -0
- package/src/modes/interactive/components/custom-editor.ts +122 -0
- package/src/modes/interactive/components/diff.ts +147 -0
- package/src/modes/interactive/components/dynamic-border.ts +25 -0
- package/src/modes/interactive/components/footer.ts +381 -0
- package/src/modes/interactive/components/hook-editor.ts +117 -0
- package/src/modes/interactive/components/hook-input.ts +64 -0
- package/src/modes/interactive/components/hook-message.ts +96 -0
- package/src/modes/interactive/components/hook-selector.ts +91 -0
- package/src/modes/interactive/components/model-selector.ts +247 -0
- package/src/modes/interactive/components/oauth-selector.ts +120 -0
- package/src/modes/interactive/components/plugin-settings.ts +479 -0
- package/src/modes/interactive/components/queue-mode-selector.ts +56 -0
- package/src/modes/interactive/components/session-selector.ts +204 -0
- package/src/modes/interactive/components/settings-selector.ts +453 -0
- package/src/modes/interactive/components/show-images-selector.ts +45 -0
- package/src/modes/interactive/components/theme-selector.ts +62 -0
- package/src/modes/interactive/components/thinking-selector.ts +64 -0
- package/src/modes/interactive/components/tool-execution.ts +675 -0
- package/src/modes/interactive/components/tree-selector.ts +866 -0
- package/src/modes/interactive/components/user-message-selector.ts +159 -0
- package/src/modes/interactive/components/user-message.ts +18 -0
- package/src/modes/interactive/components/visual-truncate.ts +50 -0
- package/src/modes/interactive/components/welcome.ts +183 -0
- package/src/modes/interactive/interactive-mode.ts +2516 -0
- package/src/modes/interactive/theme/dark.json +101 -0
- package/src/modes/interactive/theme/light.json +98 -0
- package/src/modes/interactive/theme/theme-schema.json +308 -0
- package/src/modes/interactive/theme/theme.ts +998 -0
- package/src/modes/print-mode.ts +128 -0
- package/src/modes/rpc/rpc-client.ts +527 -0
- package/src/modes/rpc/rpc-mode.ts +483 -0
- package/src/modes/rpc/rpc-types.ts +203 -0
- package/src/utils/changelog.ts +99 -0
- package/src/utils/clipboard.ts +265 -0
- package/src/utils/fuzzy.ts +108 -0
- package/src/utils/mime.ts +30 -0
- package/src/utils/shell.ts +276 -0
- package/src/utils/tools-manager.ts +274 -0
|
@@ -0,0 +1,1002 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent Tool - Delegate tasks to specialized agents
|
|
3
|
+
*
|
|
4
|
+
* Spawns a separate `pi` process for each subagent invocation,
|
|
5
|
+
* giving it an isolated context window.
|
|
6
|
+
*
|
|
7
|
+
* Supports three modes:
|
|
8
|
+
* - Single: { agent: "name", task: "..." }
|
|
9
|
+
* - Parallel: { tasks: [{ agent: "name", task: "..." }, ...] }
|
|
10
|
+
* - Chain: { chain: [{ agent: "name", task: "... {previous} ..." }, ...] }
|
|
11
|
+
*
|
|
12
|
+
* Uses JSON mode to capture structured output from subagents.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import * as fs from "node:fs";
|
|
16
|
+
import * as os from "node:os";
|
|
17
|
+
import * as path from "node:path";
|
|
18
|
+
import type { AgentToolResult } from "@oh-my-pi/pi-agent-core";
|
|
19
|
+
import type { Message } from "@oh-my-pi/pi-ai";
|
|
20
|
+
import type { CustomTool, CustomToolAPI, CustomToolFactory } from "@oh-my-pi/pi-coding-agent";
|
|
21
|
+
import { type AgentConfig, type AgentScope, discoverAgents, formatAgentList } from "./agents.js";
|
|
22
|
+
|
|
23
|
+
const MAX_PARALLEL_TASKS = 8;
|
|
24
|
+
const MAX_CONCURRENCY = 4;
|
|
25
|
+
const MAX_AGENTS_IN_DESCRIPTION = 10;
|
|
26
|
+
const COLLAPSED_ITEM_COUNT = 10;
|
|
27
|
+
|
|
28
|
+
function formatTokens(count: number): string {
|
|
29
|
+
if (count < 1000) return count.toString();
|
|
30
|
+
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
|
|
31
|
+
if (count < 1000000) return `${Math.round(count / 1000)}k`;
|
|
32
|
+
return `${(count / 1000000).toFixed(1)}M`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function formatUsageStats(
|
|
36
|
+
usage: {
|
|
37
|
+
input: number;
|
|
38
|
+
output: number;
|
|
39
|
+
cacheRead: number;
|
|
40
|
+
cacheWrite: number;
|
|
41
|
+
cost: number;
|
|
42
|
+
contextTokens?: number;
|
|
43
|
+
turns?: number;
|
|
44
|
+
},
|
|
45
|
+
model?: string,
|
|
46
|
+
): string {
|
|
47
|
+
const parts: string[] = [];
|
|
48
|
+
if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`);
|
|
49
|
+
if (usage.input) parts.push(`↑${formatTokens(usage.input)}`);
|
|
50
|
+
if (usage.output) parts.push(`↓${formatTokens(usage.output)}`);
|
|
51
|
+
if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`);
|
|
52
|
+
if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`);
|
|
53
|
+
if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
|
|
54
|
+
if (usage.contextTokens && usage.contextTokens > 0) {
|
|
55
|
+
parts.push(`ctx:${formatTokens(usage.contextTokens)}`);
|
|
56
|
+
}
|
|
57
|
+
if (model) parts.push(model);
|
|
58
|
+
return parts.join(" ");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function formatToolCall(
|
|
62
|
+
toolName: string,
|
|
63
|
+
args: Record<string, unknown>,
|
|
64
|
+
themeFg: (color: any, text: string) => string,
|
|
65
|
+
): string {
|
|
66
|
+
const shortenPath = (p: string) => {
|
|
67
|
+
const home = os.homedir();
|
|
68
|
+
return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
switch (toolName) {
|
|
72
|
+
case "bash": {
|
|
73
|
+
const command = (args.command as string) || "...";
|
|
74
|
+
const preview = command.length > 60 ? `${command.slice(0, 60)}...` : command;
|
|
75
|
+
return themeFg("muted", "$ ") + themeFg("toolOutput", preview);
|
|
76
|
+
}
|
|
77
|
+
case "read": {
|
|
78
|
+
const rawPath = (args.file_path || args.path || "...") as string;
|
|
79
|
+
const filePath = shortenPath(rawPath);
|
|
80
|
+
const offset = args.offset as number | undefined;
|
|
81
|
+
const limit = args.limit as number | undefined;
|
|
82
|
+
let text = themeFg("accent", filePath);
|
|
83
|
+
if (offset !== undefined || limit !== undefined) {
|
|
84
|
+
const startLine = offset ?? 1;
|
|
85
|
+
const endLine = limit !== undefined ? startLine + limit - 1 : "";
|
|
86
|
+
text += themeFg("warning", `:${startLine}${endLine ? `-${endLine}` : ""}`);
|
|
87
|
+
}
|
|
88
|
+
return themeFg("muted", "read ") + text;
|
|
89
|
+
}
|
|
90
|
+
case "write": {
|
|
91
|
+
const rawPath = (args.file_path || args.path || "...") as string;
|
|
92
|
+
const filePath = shortenPath(rawPath);
|
|
93
|
+
const content = (args.content || "") as string;
|
|
94
|
+
const lines = content.split("\n").length;
|
|
95
|
+
let text = themeFg("muted", "write ") + themeFg("accent", filePath);
|
|
96
|
+
if (lines > 1) text += themeFg("dim", ` (${lines} lines)`);
|
|
97
|
+
return text;
|
|
98
|
+
}
|
|
99
|
+
case "edit": {
|
|
100
|
+
const rawPath = (args.file_path || args.path || "...") as string;
|
|
101
|
+
return themeFg("muted", "edit ") + themeFg("accent", shortenPath(rawPath));
|
|
102
|
+
}
|
|
103
|
+
case "ls": {
|
|
104
|
+
const rawPath = (args.path || ".") as string;
|
|
105
|
+
return themeFg("muted", "ls ") + themeFg("accent", shortenPath(rawPath));
|
|
106
|
+
}
|
|
107
|
+
case "find": {
|
|
108
|
+
const pattern = (args.pattern || "*") as string;
|
|
109
|
+
const rawPath = (args.path || ".") as string;
|
|
110
|
+
return themeFg("muted", "find ") + themeFg("accent", pattern) + themeFg("dim", ` in ${shortenPath(rawPath)}`);
|
|
111
|
+
}
|
|
112
|
+
case "grep": {
|
|
113
|
+
const pattern = (args.pattern || "") as string;
|
|
114
|
+
const rawPath = (args.path || ".") as string;
|
|
115
|
+
return (
|
|
116
|
+
themeFg("muted", "grep ") +
|
|
117
|
+
themeFg("accent", `/${pattern}/`) +
|
|
118
|
+
themeFg("dim", ` in ${shortenPath(rawPath)}`)
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
default: {
|
|
122
|
+
const argsStr = JSON.stringify(args);
|
|
123
|
+
const preview = argsStr.length > 50 ? `${argsStr.slice(0, 50)}...` : argsStr;
|
|
124
|
+
return themeFg("accent", toolName) + themeFg("dim", ` ${preview}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
interface UsageStats {
|
|
130
|
+
input: number;
|
|
131
|
+
output: number;
|
|
132
|
+
cacheRead: number;
|
|
133
|
+
cacheWrite: number;
|
|
134
|
+
cost: number;
|
|
135
|
+
contextTokens: number;
|
|
136
|
+
turns: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
interface SingleResult {
|
|
140
|
+
agent: string;
|
|
141
|
+
agentSource: "user" | "project" | "unknown";
|
|
142
|
+
task: string;
|
|
143
|
+
exitCode: number;
|
|
144
|
+
messages: Message[];
|
|
145
|
+
stderr: string;
|
|
146
|
+
usage: UsageStats;
|
|
147
|
+
model?: string;
|
|
148
|
+
stopReason?: string;
|
|
149
|
+
errorMessage?: string;
|
|
150
|
+
step?: number;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
interface SubagentDetails {
|
|
154
|
+
mode: "single" | "parallel" | "chain";
|
|
155
|
+
agentScope: AgentScope;
|
|
156
|
+
projectAgentsDir: string | null;
|
|
157
|
+
results: SingleResult[];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function getFinalOutput(messages: Message[]): string {
|
|
161
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
162
|
+
const msg = messages[i];
|
|
163
|
+
if (msg.role === "assistant") {
|
|
164
|
+
for (const part of msg.content) {
|
|
165
|
+
if (part.type === "text") return part.text;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return "";
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record<string, any> };
|
|
173
|
+
|
|
174
|
+
function getDisplayItems(messages: Message[]): DisplayItem[] {
|
|
175
|
+
const items: DisplayItem[] = [];
|
|
176
|
+
for (const msg of messages) {
|
|
177
|
+
if (msg.role === "assistant") {
|
|
178
|
+
for (const part of msg.content) {
|
|
179
|
+
if (part.type === "text") items.push({ type: "text", text: part.text });
|
|
180
|
+
else if (part.type === "toolCall") items.push({ type: "toolCall", name: part.name, args: part.arguments });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return items;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function mapWithConcurrencyLimit<TIn, TOut>(
|
|
188
|
+
items: TIn[],
|
|
189
|
+
concurrency: number,
|
|
190
|
+
fn: (item: TIn, index: number) => Promise<TOut>,
|
|
191
|
+
): Promise<TOut[]> {
|
|
192
|
+
if (items.length === 0) return [];
|
|
193
|
+
const limit = Math.max(1, Math.min(concurrency, items.length));
|
|
194
|
+
const results: TOut[] = new Array(items.length);
|
|
195
|
+
let nextIndex = 0;
|
|
196
|
+
const workers = new Array(limit).fill(null).map(async () => {
|
|
197
|
+
while (true) {
|
|
198
|
+
const current = nextIndex++;
|
|
199
|
+
if (current >= items.length) return;
|
|
200
|
+
results[current] = await fn(items[current], current);
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
await Promise.all(workers);
|
|
204
|
+
return results;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function writePromptToTempFile(agentName: string, prompt: string): { dir: string; filePath: string } {
|
|
208
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
|
|
209
|
+
const safeName = agentName.replace(/[^\w.-]+/g, "_");
|
|
210
|
+
const filePath = path.join(tmpDir, `prompt-${safeName}.md`);
|
|
211
|
+
fs.writeFileSync(filePath, prompt, { encoding: "utf-8", mode: 0o600 });
|
|
212
|
+
return { dir: tmpDir, filePath };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
type OnUpdateCallback = (partial: AgentToolResult<SubagentDetails>) => void;
|
|
216
|
+
|
|
217
|
+
async function runSingleAgent(
|
|
218
|
+
pi: CustomToolAPI,
|
|
219
|
+
agents: AgentConfig[],
|
|
220
|
+
agentName: string,
|
|
221
|
+
task: string,
|
|
222
|
+
cwd: string | undefined,
|
|
223
|
+
step: number | undefined,
|
|
224
|
+
signal: AbortSignal | undefined,
|
|
225
|
+
onUpdate: OnUpdateCallback | undefined,
|
|
226
|
+
makeDetails: (results: SingleResult[]) => SubagentDetails,
|
|
227
|
+
): Promise<SingleResult> {
|
|
228
|
+
const agent = agents.find((a) => a.name === agentName);
|
|
229
|
+
|
|
230
|
+
if (!agent) {
|
|
231
|
+
return {
|
|
232
|
+
agent: agentName,
|
|
233
|
+
agentSource: "unknown",
|
|
234
|
+
task,
|
|
235
|
+
exitCode: 1,
|
|
236
|
+
messages: [],
|
|
237
|
+
stderr: `Unknown agent: ${agentName}`,
|
|
238
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
|
|
239
|
+
step,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const args: string[] = ["--mode", "json", "-p", "--no-session"];
|
|
244
|
+
if (agent.model) args.push("--model", agent.model);
|
|
245
|
+
if (agent.tools && agent.tools.length > 0) args.push("--tools", agent.tools.join(","));
|
|
246
|
+
|
|
247
|
+
let tmpPromptDir: string | null = null;
|
|
248
|
+
let tmpPromptPath: string | null = null;
|
|
249
|
+
|
|
250
|
+
const currentResult: SingleResult = {
|
|
251
|
+
agent: agentName,
|
|
252
|
+
agentSource: agent.source,
|
|
253
|
+
task,
|
|
254
|
+
exitCode: 0,
|
|
255
|
+
messages: [],
|
|
256
|
+
stderr: "",
|
|
257
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
|
|
258
|
+
model: agent.model,
|
|
259
|
+
step,
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
const emitUpdate = () => {
|
|
263
|
+
if (onUpdate) {
|
|
264
|
+
onUpdate({
|
|
265
|
+
content: [{ type: "text", text: getFinalOutput(currentResult.messages) || "(running...)" }],
|
|
266
|
+
details: makeDetails([currentResult]),
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
try {
|
|
272
|
+
if (agent.systemPrompt.trim()) {
|
|
273
|
+
const tmp = writePromptToTempFile(agent.name, agent.systemPrompt);
|
|
274
|
+
tmpPromptDir = tmp.dir;
|
|
275
|
+
tmpPromptPath = tmp.filePath;
|
|
276
|
+
args.push("--append-system-prompt", tmpPromptPath);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
args.push(`Task: ${task}`);
|
|
280
|
+
let wasAborted = false;
|
|
281
|
+
|
|
282
|
+
const exitCode = await new Promise<number>((resolve) => {
|
|
283
|
+
const proc = Bun.spawn(["pi", ...args], {
|
|
284
|
+
cwd: cwd ?? pi.cwd,
|
|
285
|
+
stdin: "ignore",
|
|
286
|
+
stdout: "pipe",
|
|
287
|
+
stderr: "pipe",
|
|
288
|
+
});
|
|
289
|
+
let buffer = "";
|
|
290
|
+
|
|
291
|
+
const processLine = (line: string) => {
|
|
292
|
+
if (!line.trim()) return;
|
|
293
|
+
let event: any;
|
|
294
|
+
try {
|
|
295
|
+
event = JSON.parse(line);
|
|
296
|
+
} catch {
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
if (event.type === "message_end" && event.message) {
|
|
301
|
+
const msg = event.message as Message;
|
|
302
|
+
currentResult.messages.push(msg);
|
|
303
|
+
|
|
304
|
+
if (msg.role === "assistant") {
|
|
305
|
+
currentResult.usage.turns++;
|
|
306
|
+
const usage = msg.usage;
|
|
307
|
+
if (usage) {
|
|
308
|
+
currentResult.usage.input += usage.input || 0;
|
|
309
|
+
currentResult.usage.output += usage.output || 0;
|
|
310
|
+
currentResult.usage.cacheRead += usage.cacheRead || 0;
|
|
311
|
+
currentResult.usage.cacheWrite += usage.cacheWrite || 0;
|
|
312
|
+
currentResult.usage.cost += usage.cost?.total || 0;
|
|
313
|
+
currentResult.usage.contextTokens = usage.totalTokens || 0;
|
|
314
|
+
}
|
|
315
|
+
if (!currentResult.model && msg.model) currentResult.model = msg.model;
|
|
316
|
+
if (msg.stopReason) currentResult.stopReason = msg.stopReason;
|
|
317
|
+
if (msg.errorMessage) currentResult.errorMessage = msg.errorMessage;
|
|
318
|
+
}
|
|
319
|
+
emitUpdate();
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (event.type === "tool_result_end" && event.message) {
|
|
323
|
+
currentResult.messages.push(event.message as Message);
|
|
324
|
+
emitUpdate();
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
(async () => {
|
|
329
|
+
const decoder = new TextDecoder();
|
|
330
|
+
const reader = proc.stdout.getReader();
|
|
331
|
+
try {
|
|
332
|
+
while (true) {
|
|
333
|
+
const { done, value } = await reader.read();
|
|
334
|
+
if (done) break;
|
|
335
|
+
buffer += decoder.decode(value, { stream: true });
|
|
336
|
+
const lines = buffer.split("\n");
|
|
337
|
+
buffer = lines.pop() || "";
|
|
338
|
+
for (const line of lines) processLine(line);
|
|
339
|
+
}
|
|
340
|
+
if (buffer.trim()) processLine(buffer);
|
|
341
|
+
} finally {
|
|
342
|
+
reader.releaseLock();
|
|
343
|
+
}
|
|
344
|
+
})();
|
|
345
|
+
|
|
346
|
+
(async () => {
|
|
347
|
+
const decoder = new TextDecoder();
|
|
348
|
+
const reader = proc.stderr.getReader();
|
|
349
|
+
try {
|
|
350
|
+
while (true) {
|
|
351
|
+
const { done, value } = await reader.read();
|
|
352
|
+
if (done) break;
|
|
353
|
+
currentResult.stderr += decoder.decode(value, { stream: true });
|
|
354
|
+
}
|
|
355
|
+
} finally {
|
|
356
|
+
reader.releaseLock();
|
|
357
|
+
}
|
|
358
|
+
})();
|
|
359
|
+
|
|
360
|
+
proc.exited.then((code) => {
|
|
361
|
+
resolve(code);
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
if (signal) {
|
|
365
|
+
const killProc = () => {
|
|
366
|
+
wasAborted = true;
|
|
367
|
+
proc.kill("SIGTERM");
|
|
368
|
+
setTimeout(() => {
|
|
369
|
+
if (!proc.killed) proc.kill("SIGKILL");
|
|
370
|
+
}, 5000);
|
|
371
|
+
};
|
|
372
|
+
if (signal.aborted) killProc();
|
|
373
|
+
else signal.addEventListener("abort", killProc, { once: true });
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
currentResult.exitCode = exitCode;
|
|
378
|
+
if (wasAborted) throw new Error("Subagent was aborted");
|
|
379
|
+
return currentResult;
|
|
380
|
+
} finally {
|
|
381
|
+
if (tmpPromptPath)
|
|
382
|
+
try {
|
|
383
|
+
fs.unlinkSync(tmpPromptPath);
|
|
384
|
+
} catch {
|
|
385
|
+
/* ignore */
|
|
386
|
+
}
|
|
387
|
+
if (tmpPromptDir)
|
|
388
|
+
try {
|
|
389
|
+
fs.rmdirSync(tmpPromptDir);
|
|
390
|
+
} catch {
|
|
391
|
+
/* ignore */
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const factory: CustomToolFactory = (pi) => {
|
|
397
|
+
const { Type } = pi.typebox;
|
|
398
|
+
const { StringEnum, Container, Markdown, Spacer, Text, getMarkdownTheme } = pi.pi;
|
|
399
|
+
|
|
400
|
+
const TaskItem = Type.Object({
|
|
401
|
+
agent: Type.String({ description: "Name of the agent to invoke" }),
|
|
402
|
+
task: Type.String({ description: "Task to delegate to the agent" }),
|
|
403
|
+
cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
const ChainItem = Type.Object({
|
|
407
|
+
agent: Type.String({ description: "Name of the agent to invoke" }),
|
|
408
|
+
task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
|
|
409
|
+
cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
const AgentScopeSchema = StringEnum(["user", "project", "both"] as const, {
|
|
413
|
+
description: 'Which agent directories to use. Default: "user". Use "both" to include project-local agents.',
|
|
414
|
+
default: "user",
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
const SubagentParams = Type.Object({
|
|
418
|
+
agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (for single mode)" })),
|
|
419
|
+
task: Type.Optional(Type.String({ description: "Task to delegate (for single mode)" })),
|
|
420
|
+
tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
|
|
421
|
+
chain: Type.Optional(Type.Array(ChainItem, { description: "Array of {agent, task} for sequential execution" })),
|
|
422
|
+
agentScope: Type.Optional(AgentScopeSchema),
|
|
423
|
+
confirmProjectAgents: Type.Optional(
|
|
424
|
+
Type.Boolean({ description: "Prompt before running project-local agents. Default: true.", default: true }),
|
|
425
|
+
),
|
|
426
|
+
cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
const tool: CustomTool<typeof SubagentParams, SubagentDetails> = {
|
|
430
|
+
name: "subagent",
|
|
431
|
+
label: "Subagent",
|
|
432
|
+
get description() {
|
|
433
|
+
const user = discoverAgents(pi.cwd, "user");
|
|
434
|
+
const project = discoverAgents(pi.cwd, "project");
|
|
435
|
+
const userList = formatAgentList(user.agents, MAX_AGENTS_IN_DESCRIPTION);
|
|
436
|
+
const projectList = formatAgentList(project.agents, MAX_AGENTS_IN_DESCRIPTION);
|
|
437
|
+
const userSuffix = userList.remaining > 0 ? `; ... and ${userList.remaining} more` : "";
|
|
438
|
+
const projectSuffix = projectList.remaining > 0 ? `; ... and ${projectList.remaining} more` : "";
|
|
439
|
+
const projectDirNote = project.projectAgentsDir ? ` (from ${project.projectAgentsDir})` : "";
|
|
440
|
+
return [
|
|
441
|
+
"Delegate tasks to specialized subagents with isolated context.",
|
|
442
|
+
"Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder).",
|
|
443
|
+
'Default agent scope is "user" (from ~/.pi/agent/agents).',
|
|
444
|
+
'To enable project-local agents in .pi/agents, set agentScope: "both" (or "project").',
|
|
445
|
+
`User agents: ${userList.text}${userSuffix}.`,
|
|
446
|
+
`Project agents${projectDirNote}: ${projectList.text}${projectSuffix}.`,
|
|
447
|
+
].join(" ");
|
|
448
|
+
},
|
|
449
|
+
parameters: SubagentParams,
|
|
450
|
+
|
|
451
|
+
async execute(_toolCallId, params, onUpdate, _ctx, signal) {
|
|
452
|
+
const agentScope = (params.agentScope ?? "user") as AgentScope;
|
|
453
|
+
const discovery = discoverAgents(pi.cwd, agentScope);
|
|
454
|
+
const agents = discovery.agents;
|
|
455
|
+
const confirmProjectAgents = params.confirmProjectAgents ?? true;
|
|
456
|
+
|
|
457
|
+
const hasChain = (params.chain?.length ?? 0) > 0;
|
|
458
|
+
const hasTasks = (params.tasks?.length ?? 0) > 0;
|
|
459
|
+
const hasSingle = Boolean(params.agent && params.task);
|
|
460
|
+
const modeCount = Number(hasChain) + Number(hasTasks) + Number(hasSingle);
|
|
461
|
+
|
|
462
|
+
const makeDetails =
|
|
463
|
+
(mode: "single" | "parallel" | "chain") =>
|
|
464
|
+
(results: SingleResult[]): SubagentDetails => ({
|
|
465
|
+
mode,
|
|
466
|
+
agentScope,
|
|
467
|
+
projectAgentsDir: discovery.projectAgentsDir,
|
|
468
|
+
results,
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
if (modeCount !== 1) {
|
|
472
|
+
const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
|
|
473
|
+
return {
|
|
474
|
+
content: [
|
|
475
|
+
{
|
|
476
|
+
type: "text",
|
|
477
|
+
text: `Invalid parameters. Provide exactly one mode.\nAvailable agents: ${available}`,
|
|
478
|
+
},
|
|
479
|
+
],
|
|
480
|
+
details: makeDetails("single")([]),
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
if ((agentScope === "project" || agentScope === "both") && confirmProjectAgents && pi.hasUI) {
|
|
485
|
+
const requestedAgentNames = new Set<string>();
|
|
486
|
+
if (params.chain) for (const step of params.chain) requestedAgentNames.add(step.agent);
|
|
487
|
+
if (params.tasks) for (const t of params.tasks) requestedAgentNames.add(t.agent);
|
|
488
|
+
if (params.agent) requestedAgentNames.add(params.agent);
|
|
489
|
+
|
|
490
|
+
const projectAgentsRequested = Array.from(requestedAgentNames)
|
|
491
|
+
.map((name) => agents.find((a) => a.name === name))
|
|
492
|
+
.filter((a): a is AgentConfig => a?.source === "project");
|
|
493
|
+
|
|
494
|
+
if (projectAgentsRequested.length > 0) {
|
|
495
|
+
const names = projectAgentsRequested.map((a) => a.name).join(", ");
|
|
496
|
+
const dir = discovery.projectAgentsDir ?? "(unknown)";
|
|
497
|
+
const ok = await pi.ui.confirm(
|
|
498
|
+
"Run project-local agents?",
|
|
499
|
+
`Agents: ${names}\nSource: ${dir}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`,
|
|
500
|
+
);
|
|
501
|
+
if (!ok)
|
|
502
|
+
return {
|
|
503
|
+
content: [{ type: "text", text: "Canceled: project-local agents not approved." }],
|
|
504
|
+
details: makeDetails(hasChain ? "chain" : hasTasks ? "parallel" : "single")([]),
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
if (params.chain && params.chain.length > 0) {
|
|
510
|
+
const results: SingleResult[] = [];
|
|
511
|
+
let previousOutput = "";
|
|
512
|
+
|
|
513
|
+
for (let i = 0; i < params.chain.length; i++) {
|
|
514
|
+
const step = params.chain[i];
|
|
515
|
+
const taskWithContext = step.task.replace(/\{previous\}/g, previousOutput);
|
|
516
|
+
|
|
517
|
+
// Create update callback that includes all previous results
|
|
518
|
+
const chainUpdate: OnUpdateCallback | undefined = onUpdate
|
|
519
|
+
? (partial) => {
|
|
520
|
+
// Combine completed results with current streaming result
|
|
521
|
+
const currentResult = partial.details?.results[0];
|
|
522
|
+
if (currentResult) {
|
|
523
|
+
const allResults = [...results, currentResult];
|
|
524
|
+
onUpdate({
|
|
525
|
+
content: partial.content,
|
|
526
|
+
details: makeDetails("chain")(allResults),
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
: undefined;
|
|
531
|
+
|
|
532
|
+
const result = await runSingleAgent(
|
|
533
|
+
pi,
|
|
534
|
+
agents,
|
|
535
|
+
step.agent,
|
|
536
|
+
taskWithContext,
|
|
537
|
+
step.cwd,
|
|
538
|
+
i + 1,
|
|
539
|
+
signal,
|
|
540
|
+
chainUpdate,
|
|
541
|
+
makeDetails("chain"),
|
|
542
|
+
);
|
|
543
|
+
results.push(result);
|
|
544
|
+
|
|
545
|
+
const isError =
|
|
546
|
+
result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
|
|
547
|
+
if (isError) {
|
|
548
|
+
const errorMsg =
|
|
549
|
+
result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
|
|
550
|
+
return {
|
|
551
|
+
content: [{ type: "text", text: `Chain stopped at step ${i + 1} (${step.agent}): ${errorMsg}` }],
|
|
552
|
+
details: makeDetails("chain")(results),
|
|
553
|
+
isError: true,
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
previousOutput = getFinalOutput(result.messages);
|
|
557
|
+
}
|
|
558
|
+
return {
|
|
559
|
+
content: [{ type: "text", text: getFinalOutput(results[results.length - 1].messages) || "(no output)" }],
|
|
560
|
+
details: makeDetails("chain")(results),
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
if (params.tasks && params.tasks.length > 0) {
|
|
565
|
+
if (params.tasks.length > MAX_PARALLEL_TASKS)
|
|
566
|
+
return {
|
|
567
|
+
content: [
|
|
568
|
+
{
|
|
569
|
+
type: "text",
|
|
570
|
+
text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_PARALLEL_TASKS}.`,
|
|
571
|
+
},
|
|
572
|
+
],
|
|
573
|
+
details: makeDetails("parallel")([]),
|
|
574
|
+
};
|
|
575
|
+
|
|
576
|
+
// Track all results for streaming updates
|
|
577
|
+
const allResults: SingleResult[] = new Array(params.tasks.length);
|
|
578
|
+
|
|
579
|
+
// Initialize placeholder results
|
|
580
|
+
for (let i = 0; i < params.tasks.length; i++) {
|
|
581
|
+
allResults[i] = {
|
|
582
|
+
agent: params.tasks[i].agent,
|
|
583
|
+
agentSource: "unknown",
|
|
584
|
+
task: params.tasks[i].task,
|
|
585
|
+
exitCode: -1, // -1 = still running
|
|
586
|
+
messages: [],
|
|
587
|
+
stderr: "",
|
|
588
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const emitParallelUpdate = () => {
|
|
593
|
+
if (onUpdate) {
|
|
594
|
+
const running = allResults.filter((r) => r.exitCode === -1).length;
|
|
595
|
+
const done = allResults.filter((r) => r.exitCode !== -1).length;
|
|
596
|
+
onUpdate({
|
|
597
|
+
content: [
|
|
598
|
+
{ type: "text", text: `Parallel: ${done}/${allResults.length} done, ${running} running...` },
|
|
599
|
+
],
|
|
600
|
+
details: makeDetails("parallel")([...allResults]),
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
};
|
|
604
|
+
|
|
605
|
+
const results = await mapWithConcurrencyLimit(params.tasks, MAX_CONCURRENCY, async (t, index) => {
|
|
606
|
+
const result = await runSingleAgent(
|
|
607
|
+
pi,
|
|
608
|
+
agents,
|
|
609
|
+
t.agent,
|
|
610
|
+
t.task,
|
|
611
|
+
t.cwd,
|
|
612
|
+
undefined,
|
|
613
|
+
signal,
|
|
614
|
+
// Per-task update callback
|
|
615
|
+
(partial) => {
|
|
616
|
+
if (partial.details?.results[0]) {
|
|
617
|
+
allResults[index] = partial.details.results[0];
|
|
618
|
+
emitParallelUpdate();
|
|
619
|
+
}
|
|
620
|
+
},
|
|
621
|
+
makeDetails("parallel"),
|
|
622
|
+
);
|
|
623
|
+
allResults[index] = result;
|
|
624
|
+
emitParallelUpdate();
|
|
625
|
+
return result;
|
|
626
|
+
});
|
|
627
|
+
|
|
628
|
+
const successCount = results.filter((r) => r.exitCode === 0).length;
|
|
629
|
+
const summaries = results.map((r) => {
|
|
630
|
+
const output = getFinalOutput(r.messages);
|
|
631
|
+
const preview = output.slice(0, 100) + (output.length > 100 ? "..." : "");
|
|
632
|
+
return `[${r.agent}] ${r.exitCode === 0 ? "completed" : "failed"}: ${preview || "(no output)"}`;
|
|
633
|
+
});
|
|
634
|
+
return {
|
|
635
|
+
content: [
|
|
636
|
+
{
|
|
637
|
+
type: "text",
|
|
638
|
+
text: `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n")}`,
|
|
639
|
+
},
|
|
640
|
+
],
|
|
641
|
+
details: makeDetails("parallel")(results),
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
if (params.agent && params.task) {
|
|
646
|
+
const result = await runSingleAgent(
|
|
647
|
+
pi,
|
|
648
|
+
agents,
|
|
649
|
+
params.agent,
|
|
650
|
+
params.task,
|
|
651
|
+
params.cwd,
|
|
652
|
+
undefined,
|
|
653
|
+
signal,
|
|
654
|
+
onUpdate,
|
|
655
|
+
makeDetails("single"),
|
|
656
|
+
);
|
|
657
|
+
const isError = result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
|
|
658
|
+
if (isError) {
|
|
659
|
+
const errorMsg =
|
|
660
|
+
result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
|
|
661
|
+
return {
|
|
662
|
+
content: [{ type: "text", text: `Agent ${result.stopReason || "failed"}: ${errorMsg}` }],
|
|
663
|
+
details: makeDetails("single")([result]),
|
|
664
|
+
isError: true,
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
return {
|
|
668
|
+
content: [{ type: "text", text: getFinalOutput(result.messages) || "(no output)" }],
|
|
669
|
+
details: makeDetails("single")([result]),
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
|
|
674
|
+
return {
|
|
675
|
+
content: [{ type: "text", text: `Invalid parameters. Available agents: ${available}` }],
|
|
676
|
+
details: makeDetails("single")([]),
|
|
677
|
+
};
|
|
678
|
+
},
|
|
679
|
+
|
|
680
|
+
renderCall(args, theme) {
|
|
681
|
+
const scope = (args.agentScope ?? "user") as AgentScope;
|
|
682
|
+
if (args.chain && args.chain.length > 0) {
|
|
683
|
+
let text =
|
|
684
|
+
theme.fg("toolTitle", theme.bold("subagent ")) +
|
|
685
|
+
theme.fg("accent", `chain (${args.chain.length} steps)`) +
|
|
686
|
+
theme.fg("muted", ` [${scope}]`);
|
|
687
|
+
for (let i = 0; i < Math.min(args.chain.length, 3); i++) {
|
|
688
|
+
const step = args.chain[i];
|
|
689
|
+
// Clean up {previous} placeholder for display
|
|
690
|
+
const cleanTask = step.task.replace(/\{previous\}/g, "").trim();
|
|
691
|
+
const preview = cleanTask.length > 40 ? `${cleanTask.slice(0, 40)}...` : cleanTask;
|
|
692
|
+
text +=
|
|
693
|
+
"\n " +
|
|
694
|
+
theme.fg("muted", `${i + 1}.`) +
|
|
695
|
+
" " +
|
|
696
|
+
theme.fg("accent", step.agent) +
|
|
697
|
+
theme.fg("dim", ` ${preview}`);
|
|
698
|
+
}
|
|
699
|
+
if (args.chain.length > 3) text += `\n ${theme.fg("muted", `... +${args.chain.length - 3} more`)}`;
|
|
700
|
+
return new Text(text, 0, 0);
|
|
701
|
+
}
|
|
702
|
+
if (args.tasks && args.tasks.length > 0) {
|
|
703
|
+
let text =
|
|
704
|
+
theme.fg("toolTitle", theme.bold("subagent ")) +
|
|
705
|
+
theme.fg("accent", `parallel (${args.tasks.length} tasks)`) +
|
|
706
|
+
theme.fg("muted", ` [${scope}]`);
|
|
707
|
+
for (const t of args.tasks.slice(0, 3)) {
|
|
708
|
+
const preview = t.task.length > 40 ? `${t.task.slice(0, 40)}...` : t.task;
|
|
709
|
+
text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", ` ${preview}`)}`;
|
|
710
|
+
}
|
|
711
|
+
if (args.tasks.length > 3) text += `\n ${theme.fg("muted", `... +${args.tasks.length - 3} more`)}`;
|
|
712
|
+
return new Text(text, 0, 0);
|
|
713
|
+
}
|
|
714
|
+
const agentName = args.agent || "...";
|
|
715
|
+
const preview = args.task ? (args.task.length > 60 ? `${args.task.slice(0, 60)}...` : args.task) : "...";
|
|
716
|
+
let text =
|
|
717
|
+
theme.fg("toolTitle", theme.bold("subagent ")) +
|
|
718
|
+
theme.fg("accent", agentName) +
|
|
719
|
+
theme.fg("muted", ` [${scope}]`);
|
|
720
|
+
text += `\n ${theme.fg("dim", preview)}`;
|
|
721
|
+
return new Text(text, 0, 0);
|
|
722
|
+
},
|
|
723
|
+
|
|
724
|
+
renderResult(result, { expanded }, theme) {
|
|
725
|
+
const { details } = result;
|
|
726
|
+
if (!details || details.results.length === 0) {
|
|
727
|
+
const text = result.content[0];
|
|
728
|
+
return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
const mdTheme = getMarkdownTheme();
|
|
732
|
+
|
|
733
|
+
const renderDisplayItems = (items: DisplayItem[], limit?: number) => {
|
|
734
|
+
const toShow = limit ? items.slice(-limit) : items;
|
|
735
|
+
const skipped = limit && items.length > limit ? items.length - limit : 0;
|
|
736
|
+
let text = "";
|
|
737
|
+
if (skipped > 0) text += theme.fg("muted", `... ${skipped} earlier items\n`);
|
|
738
|
+
for (const item of toShow) {
|
|
739
|
+
if (item.type === "text") {
|
|
740
|
+
const preview = expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n");
|
|
741
|
+
text += `${theme.fg("toolOutput", preview)}\n`;
|
|
742
|
+
} else {
|
|
743
|
+
text += `${theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme))}\n`;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
return text.trimEnd();
|
|
747
|
+
};
|
|
748
|
+
|
|
749
|
+
if (details.mode === "single" && details.results.length === 1) {
|
|
750
|
+
const r = details.results[0];
|
|
751
|
+
const isError = r.exitCode !== 0 || r.stopReason === "error" || r.stopReason === "aborted";
|
|
752
|
+
const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
|
|
753
|
+
const displayItems = getDisplayItems(r.messages);
|
|
754
|
+
const finalOutput = getFinalOutput(r.messages);
|
|
755
|
+
|
|
756
|
+
if (expanded) {
|
|
757
|
+
const container = new Container();
|
|
758
|
+
let header = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg(
|
|
759
|
+
"muted",
|
|
760
|
+
` (${r.agentSource})`,
|
|
761
|
+
)}`;
|
|
762
|
+
if (isError && r.stopReason) header += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
|
|
763
|
+
container.addChild(new Text(header, 0, 0));
|
|
764
|
+
if (isError && r.errorMessage)
|
|
765
|
+
container.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0));
|
|
766
|
+
container.addChild(new Spacer(1));
|
|
767
|
+
container.addChild(new Text(theme.fg("muted", "─── Task ───"), 0, 0));
|
|
768
|
+
container.addChild(new Text(theme.fg("dim", r.task), 0, 0));
|
|
769
|
+
container.addChild(new Spacer(1));
|
|
770
|
+
container.addChild(new Text(theme.fg("muted", "─── Output ───"), 0, 0));
|
|
771
|
+
if (displayItems.length === 0 && !finalOutput) {
|
|
772
|
+
container.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0));
|
|
773
|
+
} else {
|
|
774
|
+
for (const item of displayItems) {
|
|
775
|
+
if (item.type === "toolCall")
|
|
776
|
+
container.addChild(
|
|
777
|
+
new Text(
|
|
778
|
+
theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
|
|
779
|
+
0,
|
|
780
|
+
0,
|
|
781
|
+
),
|
|
782
|
+
);
|
|
783
|
+
}
|
|
784
|
+
if (finalOutput) {
|
|
785
|
+
container.addChild(new Spacer(1));
|
|
786
|
+
container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
const usageStr = formatUsageStats(r.usage, r.model);
|
|
790
|
+
if (usageStr) {
|
|
791
|
+
container.addChild(new Spacer(1));
|
|
792
|
+
container.addChild(new Text(theme.fg("dim", usageStr), 0, 0));
|
|
793
|
+
}
|
|
794
|
+
return container;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
let text = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
|
|
798
|
+
if (isError && r.stopReason) text += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
|
|
799
|
+
if (isError && r.errorMessage) text += `\n${theme.fg("error", `Error: ${r.errorMessage}`)}`;
|
|
800
|
+
else if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`;
|
|
801
|
+
else {
|
|
802
|
+
text += `\n${renderDisplayItems(displayItems, COLLAPSED_ITEM_COUNT)}`;
|
|
803
|
+
if (displayItems.length > COLLAPSED_ITEM_COUNT) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
|
|
804
|
+
}
|
|
805
|
+
const usageStr = formatUsageStats(r.usage, r.model);
|
|
806
|
+
if (usageStr) text += `\n${theme.fg("dim", usageStr)}`;
|
|
807
|
+
return new Text(text, 0, 0);
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
const aggregateUsage = (results: SingleResult[]) => {
|
|
811
|
+
const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
|
|
812
|
+
for (const r of results) {
|
|
813
|
+
total.input += r.usage.input;
|
|
814
|
+
total.output += r.usage.output;
|
|
815
|
+
total.cacheRead += r.usage.cacheRead;
|
|
816
|
+
total.cacheWrite += r.usage.cacheWrite;
|
|
817
|
+
total.cost += r.usage.cost;
|
|
818
|
+
total.turns += r.usage.turns;
|
|
819
|
+
}
|
|
820
|
+
return total;
|
|
821
|
+
};
|
|
822
|
+
|
|
823
|
+
if (details.mode === "chain") {
|
|
824
|
+
const successCount = details.results.filter((r) => r.exitCode === 0).length;
|
|
825
|
+
const icon = successCount === details.results.length ? theme.fg("success", "✓") : theme.fg("error", "✗");
|
|
826
|
+
|
|
827
|
+
if (expanded) {
|
|
828
|
+
const container = new Container();
|
|
829
|
+
container.addChild(
|
|
830
|
+
new Text(
|
|
831
|
+
icon +
|
|
832
|
+
" " +
|
|
833
|
+
theme.fg("toolTitle", theme.bold("chain ")) +
|
|
834
|
+
theme.fg("accent", `${successCount}/${details.results.length} steps`),
|
|
835
|
+
0,
|
|
836
|
+
0,
|
|
837
|
+
),
|
|
838
|
+
);
|
|
839
|
+
|
|
840
|
+
for (const r of details.results) {
|
|
841
|
+
const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
|
|
842
|
+
const displayItems = getDisplayItems(r.messages);
|
|
843
|
+
const finalOutput = getFinalOutput(r.messages);
|
|
844
|
+
|
|
845
|
+
container.addChild(new Spacer(1));
|
|
846
|
+
container.addChild(
|
|
847
|
+
new Text(
|
|
848
|
+
`${theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent)} ${rIcon}`,
|
|
849
|
+
0,
|
|
850
|
+
0,
|
|
851
|
+
),
|
|
852
|
+
);
|
|
853
|
+
container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
|
|
854
|
+
|
|
855
|
+
// Show tool calls
|
|
856
|
+
for (const item of displayItems) {
|
|
857
|
+
if (item.type === "toolCall") {
|
|
858
|
+
container.addChild(
|
|
859
|
+
new Text(
|
|
860
|
+
theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
|
|
861
|
+
0,
|
|
862
|
+
0,
|
|
863
|
+
),
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// Show final output as markdown
|
|
869
|
+
if (finalOutput) {
|
|
870
|
+
container.addChild(new Spacer(1));
|
|
871
|
+
container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
const stepUsage = formatUsageStats(r.usage, r.model);
|
|
875
|
+
if (stepUsage) container.addChild(new Text(theme.fg("dim", stepUsage), 0, 0));
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
const usageStr = formatUsageStats(aggregateUsage(details.results));
|
|
879
|
+
if (usageStr) {
|
|
880
|
+
container.addChild(new Spacer(1));
|
|
881
|
+
container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
|
|
882
|
+
}
|
|
883
|
+
return container;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
// Collapsed view
|
|
887
|
+
let text =
|
|
888
|
+
icon +
|
|
889
|
+
" " +
|
|
890
|
+
theme.fg("toolTitle", theme.bold("chain ")) +
|
|
891
|
+
theme.fg("accent", `${successCount}/${details.results.length} steps`);
|
|
892
|
+
for (const r of details.results) {
|
|
893
|
+
const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
|
|
894
|
+
const displayItems = getDisplayItems(r.messages);
|
|
895
|
+
text += `\n\n${theme.fg("muted", `─── Step ${r.step}: `)}${theme.fg("accent", r.agent)} ${rIcon}`;
|
|
896
|
+
if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`;
|
|
897
|
+
else text += `\n${renderDisplayItems(displayItems, 5)}`;
|
|
898
|
+
}
|
|
899
|
+
const usageStr = formatUsageStats(aggregateUsage(details.results));
|
|
900
|
+
if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
|
|
901
|
+
text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
|
|
902
|
+
return new Text(text, 0, 0);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
if (details.mode === "parallel") {
|
|
906
|
+
const running = details.results.filter((r) => r.exitCode === -1).length;
|
|
907
|
+
const successCount = details.results.filter((r) => r.exitCode === 0).length;
|
|
908
|
+
const failCount = details.results.filter((r) => r.exitCode > 0).length;
|
|
909
|
+
const isRunning = running > 0;
|
|
910
|
+
const icon = isRunning
|
|
911
|
+
? theme.fg("warning", "⏳")
|
|
912
|
+
: failCount > 0
|
|
913
|
+
? theme.fg("warning", "◐")
|
|
914
|
+
: theme.fg("success", "✓");
|
|
915
|
+
const status = isRunning
|
|
916
|
+
? `${successCount + failCount}/${details.results.length} done, ${running} running`
|
|
917
|
+
: `${successCount}/${details.results.length} tasks`;
|
|
918
|
+
|
|
919
|
+
if (expanded && !isRunning) {
|
|
920
|
+
const container = new Container();
|
|
921
|
+
container.addChild(
|
|
922
|
+
new Text(
|
|
923
|
+
`${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`,
|
|
924
|
+
0,
|
|
925
|
+
0,
|
|
926
|
+
),
|
|
927
|
+
);
|
|
928
|
+
|
|
929
|
+
for (const r of details.results) {
|
|
930
|
+
const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
|
|
931
|
+
const displayItems = getDisplayItems(r.messages);
|
|
932
|
+
const finalOutput = getFinalOutput(r.messages);
|
|
933
|
+
|
|
934
|
+
container.addChild(new Spacer(1));
|
|
935
|
+
container.addChild(
|
|
936
|
+
new Text(`${theme.fg("muted", "─── ") + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0),
|
|
937
|
+
);
|
|
938
|
+
container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
|
|
939
|
+
|
|
940
|
+
// Show tool calls
|
|
941
|
+
for (const item of displayItems) {
|
|
942
|
+
if (item.type === "toolCall") {
|
|
943
|
+
container.addChild(
|
|
944
|
+
new Text(
|
|
945
|
+
theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
|
|
946
|
+
0,
|
|
947
|
+
0,
|
|
948
|
+
),
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// Show final output as markdown
|
|
954
|
+
if (finalOutput) {
|
|
955
|
+
container.addChild(new Spacer(1));
|
|
956
|
+
container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
const taskUsage = formatUsageStats(r.usage, r.model);
|
|
960
|
+
if (taskUsage) container.addChild(new Text(theme.fg("dim", taskUsage), 0, 0));
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
const usageStr = formatUsageStats(aggregateUsage(details.results));
|
|
964
|
+
if (usageStr) {
|
|
965
|
+
container.addChild(new Spacer(1));
|
|
966
|
+
container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
|
|
967
|
+
}
|
|
968
|
+
return container;
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// Collapsed view (or still running)
|
|
972
|
+
let text = `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`;
|
|
973
|
+
for (const r of details.results) {
|
|
974
|
+
const rIcon =
|
|
975
|
+
r.exitCode === -1
|
|
976
|
+
? theme.fg("warning", "⏳")
|
|
977
|
+
: r.exitCode === 0
|
|
978
|
+
? theme.fg("success", "✓")
|
|
979
|
+
: theme.fg("error", "✗");
|
|
980
|
+
const displayItems = getDisplayItems(r.messages);
|
|
981
|
+
text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`;
|
|
982
|
+
if (displayItems.length === 0)
|
|
983
|
+
text += `\n${theme.fg("muted", r.exitCode === -1 ? "(running...)" : "(no output)")}`;
|
|
984
|
+
else text += `\n${renderDisplayItems(displayItems, 5)}`;
|
|
985
|
+
}
|
|
986
|
+
if (!isRunning) {
|
|
987
|
+
const usageStr = formatUsageStats(aggregateUsage(details.results));
|
|
988
|
+
if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
|
|
989
|
+
}
|
|
990
|
+
if (!expanded) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
|
|
991
|
+
return new Text(text, 0, 0);
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
const text = result.content[0];
|
|
995
|
+
return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
|
|
996
|
+
},
|
|
997
|
+
};
|
|
998
|
+
|
|
999
|
+
return tool;
|
|
1000
|
+
};
|
|
1001
|
+
|
|
1002
|
+
export default factory;
|