@pi-archimedes/subagent 0.3.1
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/package.json +31 -0
- package/src/compact.ts +360 -0
- package/src/cost.ts +8 -0
- package/src/execute.ts +111 -0
- package/src/expanded.ts +221 -0
- package/src/format.ts +60 -0
- package/src/handlers.ts +158 -0
- package/src/index.ts +224 -0
- package/src/render.ts +123 -0
- package/src/spawn.ts +73 -0
- package/src/stream.ts +177 -0
- package/src/types.ts +76 -0
package/src/render.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
2
|
+
import type { SubagentDetails, SubagentProgress, SubagentToolResult } from "./types.js";
|
|
3
|
+
import {
|
|
4
|
+
renderCompactSingle,
|
|
5
|
+
renderCompactParallel,
|
|
6
|
+
renderCompactProgress,
|
|
7
|
+
renderCompactParallelProgress,
|
|
8
|
+
} from "./compact.js";
|
|
9
|
+
import {
|
|
10
|
+
renderExpanded,
|
|
11
|
+
renderProgressExpanded,
|
|
12
|
+
buildProgressExpandedText,
|
|
13
|
+
buildExpandedText,
|
|
14
|
+
} from "./expanded.js";
|
|
15
|
+
|
|
16
|
+
type Theme = { fg: (token: string, text: string) => string; bold: (text: string) => string };
|
|
17
|
+
type RenderContext = {
|
|
18
|
+
expanded: boolean;
|
|
19
|
+
isError: boolean;
|
|
20
|
+
lastComponent: Text | undefined;
|
|
21
|
+
state: Record<string, unknown>;
|
|
22
|
+
invalidate: () => void;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export function renderSubagentResult(
|
|
26
|
+
text: Text,
|
|
27
|
+
result: SubagentToolResult,
|
|
28
|
+
options: { expanded: boolean },
|
|
29
|
+
theme: Theme,
|
|
30
|
+
context: RenderContext,
|
|
31
|
+
): Text {
|
|
32
|
+
const details: SubagentDetails | undefined = result.details;
|
|
33
|
+
const expanded = context.expanded ?? options.expanded;
|
|
34
|
+
|
|
35
|
+
if (!details) {
|
|
36
|
+
text.setText(theme.fg("dim", " no results"));
|
|
37
|
+
return text;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ── Streaming progress (results empty but progress has data) ──────────
|
|
41
|
+
if (details.results.length === 0 && details.progress && details.progress.length > 0) {
|
|
42
|
+
if (details.progress.length === 1) {
|
|
43
|
+
return renderProgressUpdate(text, details.progress[0], expanded, theme, context);
|
|
44
|
+
}
|
|
45
|
+
return renderProgressUpdatesParallel(text, details, expanded, theme, context);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (details.results.length === 0) {
|
|
49
|
+
text.setText(theme.fg("dim", " no results"));
|
|
50
|
+
return text;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ── Single agent ────────────────────────────────────────────────────────
|
|
54
|
+
if (details.mode === "single" || details.results.length === 1) {
|
|
55
|
+
return renderSingleAgent(text, details.results[0], details.progress?.[0], expanded, theme, context);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ── Parallel agents ─────────────────────────────────────────────────────
|
|
59
|
+
return renderParallelAgents(text, details, expanded, theme, context);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function renderSingleAgent(
|
|
63
|
+
text: Text,
|
|
64
|
+
result: SubagentDetails["results"][number],
|
|
65
|
+
progress: SubagentDetails["progress"] extends (infer U)[] | undefined ? U | undefined : undefined,
|
|
66
|
+
expanded: boolean,
|
|
67
|
+
theme: Theme,
|
|
68
|
+
context: RenderContext,
|
|
69
|
+
): Text {
|
|
70
|
+
if (expanded) {
|
|
71
|
+
return renderExpanded(text, result, progress, theme);
|
|
72
|
+
}
|
|
73
|
+
return renderCompactSingle(text, result, progress, theme, context);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function renderParallelAgents(
|
|
77
|
+
text: Text,
|
|
78
|
+
details: SubagentDetails,
|
|
79
|
+
expanded: boolean,
|
|
80
|
+
theme: Theme,
|
|
81
|
+
context: RenderContext,
|
|
82
|
+
): Text {
|
|
83
|
+
if (expanded) {
|
|
84
|
+
const progressArr: SubagentProgress[] = details.progress ?? [];
|
|
85
|
+
const lines = details.results.map((result, i) => {
|
|
86
|
+
return buildExpandedText(result, progressArr[i], theme);
|
|
87
|
+
});
|
|
88
|
+
text.setText(lines.join("\n\n"));
|
|
89
|
+
return text;
|
|
90
|
+
}
|
|
91
|
+
return renderCompactParallel(text, details, theme, context);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function renderProgressUpdate(
|
|
95
|
+
text: Text,
|
|
96
|
+
progress: SubagentProgress,
|
|
97
|
+
expanded: boolean,
|
|
98
|
+
theme: Theme,
|
|
99
|
+
context: RenderContext,
|
|
100
|
+
): Text {
|
|
101
|
+
if (expanded) {
|
|
102
|
+
return renderProgressExpanded(text, progress, theme);
|
|
103
|
+
}
|
|
104
|
+
return renderCompactProgress(text, progress, theme, context);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function renderProgressUpdatesParallel(
|
|
108
|
+
text: Text,
|
|
109
|
+
details: SubagentDetails,
|
|
110
|
+
expanded: boolean,
|
|
111
|
+
theme: Theme,
|
|
112
|
+
context: RenderContext,
|
|
113
|
+
): Text {
|
|
114
|
+
if (expanded) {
|
|
115
|
+
const progressArr: SubagentProgress[] = details.progress ?? [];
|
|
116
|
+
const lines = progressArr.map((progress) => {
|
|
117
|
+
return buildProgressExpandedText(progress, theme);
|
|
118
|
+
});
|
|
119
|
+
text.setText(lines.join("\n\n"));
|
|
120
|
+
return text;
|
|
121
|
+
}
|
|
122
|
+
return renderCompactParallelProgress(text, details, theme, context);
|
|
123
|
+
}
|
package/src/spawn.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
2
|
+
import { execSync } from "node:child_process";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
|
|
5
|
+
export interface SpawnOptions {
|
|
6
|
+
task: string;
|
|
7
|
+
model?: string;
|
|
8
|
+
cwd?: string;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Resolve the `pi` command — finds it on PATH.
|
|
14
|
+
*/
|
|
15
|
+
export function resolvePiCommand(): { command: string; args: string[] } {
|
|
16
|
+
let piPath: string;
|
|
17
|
+
try {
|
|
18
|
+
piPath = execSync(process.platform === "win32" ? 'where pi' : 'which pi', {
|
|
19
|
+
encoding: "utf-8",
|
|
20
|
+
}).trim();
|
|
21
|
+
} catch {
|
|
22
|
+
throw new Error("pi command not found on PATH. Is pi installed?");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// On Windows, the CLI might be a .cmd script
|
|
26
|
+
if (process.platform === "win32" && !piPath.endsWith(".cmd") && !piPath.endsWith(".exe")) {
|
|
27
|
+
const cmdPath = piPath + ".cmd";
|
|
28
|
+
if (existsSync(cmdPath)) {
|
|
29
|
+
return { command: "cmd", args: ["/c", cmdPath] };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return { command: piPath, args: [] };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Spawn a child `pi` process in JSON mode.
|
|
37
|
+
*/
|
|
38
|
+
export function spawnSubagent(options: SpawnOptions): ChildProcess {
|
|
39
|
+
const { command, args: baseArgs } = resolvePiCommand();
|
|
40
|
+
const args: string[] = [
|
|
41
|
+
...baseArgs,
|
|
42
|
+
"--mode", "json",
|
|
43
|
+
"-p", options.task,
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
if (options.model) {
|
|
47
|
+
args.push("--model", options.model);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const child = spawn(command, args, {
|
|
51
|
+
cwd: options.cwd || process.cwd(),
|
|
52
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
53
|
+
env: process.env,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// Handle abort signal
|
|
57
|
+
if (options.signal) {
|
|
58
|
+
const cleanup = () => {
|
|
59
|
+
if (child.pid && !child.killed) {
|
|
60
|
+
child.kill("SIGTERM");
|
|
61
|
+
const forceKill = setTimeout(() => {
|
|
62
|
+
if (!child.killed) {
|
|
63
|
+
child.kill("SIGKILL");
|
|
64
|
+
}
|
|
65
|
+
}, 3000);
|
|
66
|
+
forceKill.unref();
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
options.signal.addEventListener("abort", cleanup, { once: true });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return child;
|
|
73
|
+
}
|
package/src/stream.ts
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { createInterface } from "node:readline";
|
|
2
|
+
import type { ChildProcess } from "node:child_process";
|
|
3
|
+
import type { StreamState, SubagentProgress, SubagentResult } from "./types.js";
|
|
4
|
+
import {
|
|
5
|
+
type JsonEvent,
|
|
6
|
+
handleToolStart,
|
|
7
|
+
handleToolEnd,
|
|
8
|
+
handleToolResult,
|
|
9
|
+
handleMessageEnd,
|
|
10
|
+
handleAgentEnd,
|
|
11
|
+
} from "./handlers.js";
|
|
12
|
+
|
|
13
|
+
export interface StreamCallbacks {
|
|
14
|
+
agent?: string;
|
|
15
|
+
task?: string;
|
|
16
|
+
onProgress?: (progress: SubagentProgress) => void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Stream JSON events from a child pi process and build progress/result.
|
|
21
|
+
*/
|
|
22
|
+
export function streamEvents(
|
|
23
|
+
child: ChildProcess,
|
|
24
|
+
callbacks: StreamCallbacks = {},
|
|
25
|
+
): Promise<SubagentResult> {
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
const startTime = Date.now();
|
|
28
|
+
const timeout = setTimeout(() => {
|
|
29
|
+
child.kill("SIGKILL");
|
|
30
|
+
reject(new Error("subagent timed out after 5 minutes"));
|
|
31
|
+
}, 5 * 60 * 1000);
|
|
32
|
+
|
|
33
|
+
const state: StreamState = {
|
|
34
|
+
toolCount: 0,
|
|
35
|
+
turnCount: 0,
|
|
36
|
+
totalInput: 0,
|
|
37
|
+
totalOutput: 0,
|
|
38
|
+
totalCacheRead: 0,
|
|
39
|
+
totalCacheWrite: 0,
|
|
40
|
+
totalCost: 0,
|
|
41
|
+
currentTool: undefined,
|
|
42
|
+
currentToolArgs: undefined,
|
|
43
|
+
currentToolStartedAt: undefined,
|
|
44
|
+
model: undefined,
|
|
45
|
+
accumulatedOutput: [],
|
|
46
|
+
recentOutput: [],
|
|
47
|
+
toolCalls: [],
|
|
48
|
+
finalOutput: undefined,
|
|
49
|
+
};
|
|
50
|
+
let error: string | undefined;
|
|
51
|
+
|
|
52
|
+
// Build progress from state
|
|
53
|
+
const buildProgress = (): SubagentProgress => ({
|
|
54
|
+
agent: callbacks.agent ?? "subagent",
|
|
55
|
+
status: "running",
|
|
56
|
+
task: callbacks.task ?? "",
|
|
57
|
+
currentTool: state.currentTool,
|
|
58
|
+
currentToolArgs: state.currentToolArgs,
|
|
59
|
+
currentToolStartedAt: state.currentToolStartedAt,
|
|
60
|
+
toolCount: state.toolCount,
|
|
61
|
+
inputTokens: state.totalInput,
|
|
62
|
+
outputTokens: state.totalOutput,
|
|
63
|
+
tokens: state.totalInput + state.totalOutput,
|
|
64
|
+
cost: state.totalCost,
|
|
65
|
+
durationMs: Date.now() - startTime,
|
|
66
|
+
error,
|
|
67
|
+
output: state.accumulatedOutput.length > 0 ? state.accumulatedOutput.join("\n\n") : undefined,
|
|
68
|
+
recentOutput: state.recentOutput.length > 0 ? state.recentOutput : undefined,
|
|
69
|
+
toolCalls: state.toolCalls.length > 0 ? state.toolCalls : undefined,
|
|
70
|
+
model: state.model,
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const emitProgress = () => {
|
|
74
|
+
callbacks.onProgress?.(buildProgress());
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// Collect stderr
|
|
78
|
+
const stderrParts: string[] = [];
|
|
79
|
+
child.stderr?.on("data", (data: Buffer) => {
|
|
80
|
+
stderrParts.push(data.toString());
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// Parse JSON lines from stdout
|
|
84
|
+
const rl = createInterface({
|
|
85
|
+
input: child.stdout!,
|
|
86
|
+
crlfDelay: Infinity,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
rl.on("line", (line: string) => {
|
|
90
|
+
let event: JsonEvent;
|
|
91
|
+
try {
|
|
92
|
+
event = JSON.parse(line);
|
|
93
|
+
} catch {
|
|
94
|
+
return; // Skip non-JSON lines
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
switch (event.type) {
|
|
98
|
+
case "tool_execution_start": {
|
|
99
|
+
handleToolStart(state, event);
|
|
100
|
+
emitProgress();
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
case "tool_execution_end": {
|
|
104
|
+
handleToolEnd(state);
|
|
105
|
+
emitProgress();
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
case "turn_start": {
|
|
109
|
+
state.turnCount++;
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
case "tool_result_end": {
|
|
113
|
+
handleToolResult(state, event);
|
|
114
|
+
emitProgress();
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
case "message_end": {
|
|
118
|
+
handleMessageEnd(state, event);
|
|
119
|
+
emitProgress();
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
case "agent_end": {
|
|
123
|
+
handleAgentEnd(state, event);
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// Handle process exit
|
|
130
|
+
child.on("close", (code) => {
|
|
131
|
+
clearTimeout(timeout);
|
|
132
|
+
const durationMs = Date.now() - startTime;
|
|
133
|
+
const exitCode = code ?? 1;
|
|
134
|
+
|
|
135
|
+
if (stderrParts.length > 0 && exitCode !== 0) {
|
|
136
|
+
error = stderrParts.join("").trim();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const result: SubagentResult = {
|
|
140
|
+
agent: callbacks.agent ?? "subagent",
|
|
141
|
+
task: callbacks.task ?? "",
|
|
142
|
+
exitCode,
|
|
143
|
+
model: state.model,
|
|
144
|
+
usage: {
|
|
145
|
+
input: state.totalInput,
|
|
146
|
+
output: state.totalOutput,
|
|
147
|
+
cacheRead: state.totalCacheRead,
|
|
148
|
+
cacheWrite: state.totalCacheWrite,
|
|
149
|
+
cost: state.totalCost,
|
|
150
|
+
turns: state.turnCount,
|
|
151
|
+
},
|
|
152
|
+
finalOutput: state.finalOutput,
|
|
153
|
+
error,
|
|
154
|
+
progress: {
|
|
155
|
+
...buildProgress(),
|
|
156
|
+
status: exitCode === 0 ? "completed" : "failed",
|
|
157
|
+
durationMs,
|
|
158
|
+
},
|
|
159
|
+
progressSummary: {
|
|
160
|
+
toolCount: state.toolCount,
|
|
161
|
+
tokens: state.totalInput + state.totalOutput,
|
|
162
|
+
durationMs,
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
// Final progress update
|
|
167
|
+
callbacks.onProgress?.(result.progress!);
|
|
168
|
+
|
|
169
|
+
resolve(result);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
child.on("error", (err) => {
|
|
173
|
+
clearTimeout(timeout);
|
|
174
|
+
reject(err);
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
export interface SubagentUsage {
|
|
2
|
+
input: number;
|
|
3
|
+
output: number;
|
|
4
|
+
cacheRead: number;
|
|
5
|
+
cacheWrite: number;
|
|
6
|
+
cost: number;
|
|
7
|
+
turns: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface SubagentProgress {
|
|
11
|
+
agent: string;
|
|
12
|
+
status: "running" | "completed" | "failed";
|
|
13
|
+
task: string;
|
|
14
|
+
currentTool?: string;
|
|
15
|
+
currentToolArgs?: string;
|
|
16
|
+
currentToolStartedAt?: number;
|
|
17
|
+
toolCount: number;
|
|
18
|
+
inputTokens: number;
|
|
19
|
+
outputTokens: number;
|
|
20
|
+
tokens: number;
|
|
21
|
+
cost: number;
|
|
22
|
+
durationMs: number;
|
|
23
|
+
error?: string;
|
|
24
|
+
/** Model used by the subagent */
|
|
25
|
+
model?: string;
|
|
26
|
+
/** Accumulated assistant text output during streaming */
|
|
27
|
+
output?: string;
|
|
28
|
+
/** Last N lines of assistant text for live display */
|
|
29
|
+
recentOutput?: string[];
|
|
30
|
+
/** History of tool calls: "toolName: args_preview" */
|
|
31
|
+
toolCalls?: string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SubagentResult {
|
|
35
|
+
agent: string;
|
|
36
|
+
task: string;
|
|
37
|
+
exitCode: number;
|
|
38
|
+
usage: SubagentUsage;
|
|
39
|
+
model?: string;
|
|
40
|
+
finalOutput?: string;
|
|
41
|
+
error?: string;
|
|
42
|
+
progress?: SubagentProgress;
|
|
43
|
+
progressSummary?: { toolCount: number; tokens: number; durationMs: number };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface SubagentToolResult {
|
|
47
|
+
content: Array<{ type: "text"; text: string }>;
|
|
48
|
+
details: SubagentDetails;
|
|
49
|
+
isError?: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface SubagentDetails {
|
|
53
|
+
mode: "single" | "parallel";
|
|
54
|
+
results: SubagentResult[];
|
|
55
|
+
progress?: SubagentProgress[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Mutable state during streaming — shared between stream.ts and handlers.ts */
|
|
59
|
+
export interface StreamState {
|
|
60
|
+
toolCount: number;
|
|
61
|
+
turnCount: number;
|
|
62
|
+
totalInput: number;
|
|
63
|
+
totalOutput: number;
|
|
64
|
+
totalCacheRead: number;
|
|
65
|
+
totalCacheWrite: number;
|
|
66
|
+
totalCost: number;
|
|
67
|
+
currentTool: string | undefined;
|
|
68
|
+
currentToolArgs: string | undefined;
|
|
69
|
+
currentToolStartedAt: number | undefined;
|
|
70
|
+
model: string | undefined;
|
|
71
|
+
accumulatedOutput: string[];
|
|
72
|
+
recentOutput: string[];
|
|
73
|
+
toolCalls: string[];
|
|
74
|
+
finalOutput: string | undefined;
|
|
75
|
+
}
|
|
76
|
+
|